Add thread search, find navigation, archived and older shelves, and pin reordering

This commit is contained in:
Callum Alpass committed 2026-11-02 20:42:33 +11:00
1 parent 43347d1d58
commit 89625dddc5
17 files changed
+551 -24

No files matched your search

+9 -3
View File
@@ -58,11 +58,14 @@ Navigation:
| `x` | dismiss the agent's question | | `x` | dismiss the agent's question |
| `e` | expand all folded turns and work groups | | `e` | expand all folded turns and work groups |
| `o` | load earlier turns | | `o` | load earlier turns |
| `f` | find in the open thread; `enter` / `shift+enter` or `ctrl+n` / `ctrl+p` move between matches, `esc` closes |
| `A` | show archived threads / return to active threads |
| `J` / `K` | move the selected pinned thread down / up |
| `d` | show or hide thread details | | `d` | show or hide thread details |
| `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `t` turns an automation on or off, `esc` comes back | | `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `t` turns an automation on or off, `esc` comes back |
| `u` | go to the parent thread (from a fork or subagent) | | `u` | go to the parent thread (from a fork or subagent) |
| `:` | command palette | | `:` | command palette |
| `z` | show the Settled and Snoozed sections | | `z` | show the Settled and Snoozed sections; `Show more settled threads` in the palette loads older rows |
| `/` | filter threads by title or project (the box opens at the top of the thread list) | | `/` | filter threads by title or project (the box opens at the top of the thread list) |
| `S` | stop the thread | | `S` | stop the thread |
| `g` / `G` | top / bottom of the conversation | | `g` / `G` | top / bottom of the conversation |
@@ -77,7 +80,10 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
- **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line. - **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line.
- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). - **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off).
- **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). - **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them).
- **Command palette:** `ctrl+k`, as in the web app. It searches commands and threads with T3's own scoring; start with `>` for commands only. - **Command palette:** `ctrl+k`, as in the web app. It searches commands and threads with T3's own scoring, then lists full-text hits with snippets under `In messages`; start with `>` for commands only. Message search needs a word of at least three letters.
- **Find in thread:** `f` or `Find in thread` in the palette or thread menu searches the whole conversation, counts matches, highlights matching text and loads earlier history to reveal the selected match. Matching Markdown is shown as highlighted plain text while finding.
- **Archived threads:** `A` or `Show archived threads` in the palette opens the archive. Open a thread normally; `Unarchive thread` in the palette restores it. `Show active threads` returns to the live list.
- **Ordering:** `J` / `K` or `Move pinned thread down` / `Move pinned thread up` in the palette reorder pinned threads. Active threads stay ordered by return time, as in T3 Code's Working shelf.
- **Mouse:** click a thread to open it, a collapsed section to unfold it, a details row to run it, the message box to type, or a palette row. - **Mouse:** click a thread to open it, a collapsed section to unfold it, a details row to run it, the message box to type, or a palette row.
- Threads open scrolled to the bottom. - Threads open scrolled to the bottom.
- **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off. - **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off.
@@ -93,7 +99,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
- Copy the workspace path, branch, thread link or thread ID - Copy the workspace path, branch, thread link or thread ID
- Archive or delete - Archive or delete
Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first, as the app does by default; it doesn't offer to remove the thread's worktree, which the app does. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. The app's project settings, guest sharing and find-in-thread aren't here. Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first, as the app does by default; it doesn't offer to remove the thread's worktree, which the app does. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. The app's project settings and guest sharing aren't here.
## New threads ## New threads
+29
View File
@@ -6,6 +6,9 @@ import {
ORCHESTRATION_V2_WS_METHODS, ORCHESTRATION_V2_WS_METHODS,
OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadHistoryPage,
type OrchestrationV2Command, type OrchestrationV2Command,
type OrchestrationV2SearchThreadsInput,
type OrchestrationV2SearchThreadInput,
type OrchestrationV2GetOlderSettledThreadsInput,
type OrchestrationV2ShellSnapshot, type OrchestrationV2ShellSnapshot,
type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadProjection,
type ProviderApprovalDecision, type ProviderApprovalDecision,
@@ -516,6 +519,32 @@ export class T3Session {
return result.threadId; return result.threadId;
} }
/** Searches message bodies and older titles, as the web palette does. */
searchThreads(input: OrchestrationV2SearchThreadsInput) {
return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.searchThreads](input));
}
/** Finds one occurrence and its position in the whole thread, including unloaded history. */
searchThread(input: OrchestrationV2SearchThreadInput) {
return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.searchThread](input));
}
archivedThreads() {
return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]({}));
}
olderSettledThreads(input: OrchestrationV2GetOlderSettledThreadsInput) {
return Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads](input));
}
unarchiveThread(threadId: ThreadId): Promise<void> {
return this.dispatch({ type: "thread.unarchive", commandId: newCommandId(), threadId });
}
reorderThread(threadId: ThreadId, section: "pinned" | "active", orderKey: string): Promise<void> {
return this.dispatch({ type: section === "pinned" ? "thread.pin.reorder" : "thread.active.reorder", commandId: newCommandId(), threadId, orderKey });
}
/** Files and folders under `cwd` matching `query`, as the composer's @ menu searches them. */ /** Files and folders under `cwd` matching `query`, as the composer's @ menu searches them. */
async searchEntries(cwd: string, query: string, limit: number): Promise<readonly ProjectEntry[]> { async searchEntries(cwd: string, query: string, limit: number): Promise<readonly ProjectEntry[]> {
const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsSearchEntries]({ cwd, query, limit })); const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsSearchEntries]({ cwd, query, limit }));
+1 -1
View File
@@ -16,7 +16,7 @@ export interface PaletteCommand {
export type PaletteEntry = export type PaletteEntry =
| { readonly kind: "command"; readonly command: PaletteCommand } | { readonly kind: "command"; readonly command: PaletteCommand }
| { readonly kind: "thread"; readonly threadId: ThreadId; readonly title: string; readonly project: string; readonly subagent: boolean }; | { readonly kind: "thread"; readonly threadId: ThreadId; readonly title: string; readonly project: string; readonly subagent: boolean; readonly snippet?: string };
export interface PaletteGroup { export interface PaletteGroup {
readonly label: string; readonly label: string;
+79
View File
@@ -0,0 +1,79 @@
import type { OrchestrationV2SearchThreadsResult, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { THREAD_SEARCH_QUERY_MAX_LENGTH } from "@t3tools/contracts";
import { foldSearchQuery, messageSearchTokens, PALETTE_MESSAGE_LIMIT, rankMessageMatches } from "@t3tools/shared/paletteSearch";
import { presentThreadShell } from "@t3tools/client-runtime/state/models";
import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search";
import { EnvironmentId } from "@t3tools/contracts";
import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
import type { PaletteGroup } from "./palette.ts";
import { projectLabel, type ThreadRow } from "./threads.ts";
import { unified } from "unified";
import remarkParse from "remark-parse";
const markdown = unified().use(remarkParse);
interface TextNode { readonly type: string; readonly value?: string; readonly children?: readonly TextNode[] }
/** OpenTUI renders Markdown, not HTML; search highlights use its text leaves without markup. */
export function findTextSegments(text: string, userMessage = false): readonly string[] {
const tree = markdown.parse(text);
const segments: string[] = [];
const leaves = (node: TextNode): string => node.value ?? (node.children ?? []).map(leaves).join("");
const visit = (node: TextNode) => {
if (node.type === "code") segments.push(leaves(node));
else if (["paragraph", "heading", "tableCell"].includes(node.type)) {
const value = leaves(node);
segments.push(...(userMessage ? value.split(/\r?\n/) : [value.replace(/\r?\n/g, " ")]));
} else for (const child of node.children ?? []) visit(child);
};
visit(tree);
return segments;
}
/** The web searches messages only with a long token; omitted older titles need two characters. */
export function threadSearchQuery(query: string, olderSettled: boolean): string | null {
if (query.startsWith(">")) return null;
const normalized = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim();
return messageSearchTokens(normalized).long.length > 0 || (olderSettled && normalized.length >= 2) ? normalized : null;
}
/** Late message results stay last, without duplicating or moving title matches. */
export function messageMatchGroups(groups: readonly PaletteGroup[], result: OrchestrationV2SearchThreadsResult | null, snapshot: OrchestrationV2ShellSnapshot | null, query = "", now = Date.now()): PaletteGroup[] {
if (!result || !snapshot) return [...groups];
const listed = new Set(groups.flatMap((group) => group.entries.flatMap((entry) => entry.kind === "thread" ? [entry.threadId] : [])));
const threads = new Map([...snapshot.threads, ...(result.threads ?? [])].map((thread) => [thread.id, thread]));
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
const ranked = rankMessageMatches(result.matches, (match) => {
const thread = threads.get(match.threadId);
return thread ? threadSearchSubject(presentThreadShell(EnvironmentId.make("local"), thread), projectLabel(projects.get(thread.projectId))) : undefined;
}, foldSearchQuery(query), now);
const entries = ranked.flatMap((match) => {
const thread = threads.get(match.threadId);
if (listed.has(match.threadId) || thread?.archivedAt != null || thread?.deletedAt != null) return [];
listed.add(match.threadId);
return [{ kind: "thread" as const, threadId: match.threadId, title: thread?.title || "Thread", project: projectLabel(projects.get(match.projectId)), subagent: thread?.lineage.relationshipToParent === "subagent", snippet: match.snippet }];
});
return entries.length ? [...groups, { label: "In messages", entries: entries.slice(0, PALETTE_MESSAGE_LIMIT) }] : [...groups];
}
/** Live shell rows win over fetched pages, so returning activity cannot be overwritten by an old page. */
export function mergeThreadShells(snapshot: OrchestrationV2ShellSnapshot | null, extra: readonly OrchestrationV2ThreadShell[]): OrchestrationV2ShellSnapshot | null {
if (!snapshot) return null;
const threads = new Map(extra.map((thread) => [thread.id, thread]));
for (const thread of snapshot.archivedThreads ?? []) threads.set(thread.id, thread);
for (const thread of snapshot.threads) threads.set(thread.id, thread);
return { ...snapshot, threads: [...threads.values()] };
}
/** Keyboard moves use the web's midpoint planner, including its keyless-section rewrite. */
export function threadReorder(rows: readonly ThreadRow[], threadId: ThreadId, delta: 1 | -1, retainedRows = rows) {
const row = rows.find((candidate) => candidate.thread.id === threadId);
if (!row || (row.section !== "pinned" && row.section !== "active")) return null;
const section = row.section;
const members = rows.filter((candidate) => candidate.section === section);
const orderedIds = members.map((candidate) => candidate.thread.id);
const index = orderedIds.indexOf(threadId);
const target = index + delta;
if (target < 0 || target >= orderedIds.length) return null;
[orderedIds[index], orderedIds[target]] = [orderedIds[target]!, orderedIds[index]!];
return { section, assignments: planPinnedReorder({ orderedIds, movedId: threadId, keysById: new Map(retainedRows.filter((row) => row.section === section).map(({ thread }) => [thread.id, section === "pinned" ? thread.pinOrderKey : thread.activeOrderKey])) }) };
}
+3 -3
View File
@@ -10,8 +10,8 @@ export type { ThreadActionMenuId };
const LOCAL = EnvironmentId.make("local"); const LOCAL = EnvironmentId.make("local");
/** Web-only actions: finding in the thread, project settings, guest links, turning into a project. */ /** Web-only actions: project settings, guest links, turning into a project. */
const UNSUPPORTED: ReadonlySet<ThreadActionMenuId> = new Set(["find", "project-settings", "share-guest", "turn-into-project", "filter-by-project"]); const UNSUPPORTED: ReadonlySet<ThreadActionMenuId> = new Set(["project-settings", "share-guest", "turn-into-project", "filter-by-project"]);
export interface ThreadMenu { export interface ThreadMenu {
readonly items: readonly ContextMenuItem<ThreadActionMenuId>[]; readonly items: readonly ContextMenuItem<ThreadActionMenuId>[];
@@ -28,7 +28,7 @@ export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell;
const snoozePresets = snoozeMenu(config, input.timestampFormat, now); const snoozePresets = snoozeMenu(config, input.timestampFormat, now);
const items = buildThreadActionMenuItems({ const items = buildThreadActionMenuItems({
canOperate: true, canOperate: true,
canFind: false, canFind: true,
branch: thread.branch ?? null, branch: thread.branch ?? null,
projectFilter: null, projectFilter: null,
isPinned: thread.pinnedAt != null, isPinned: thread.pinnedAt != null,
+8 -6
View File
@@ -6,7 +6,7 @@ import { sortPinnedThreadsByOrderKey, sortSettledThreads } from "@t3tools/client
import * as DateTime from "effect/DateTime"; import * as DateTime from "effect/DateTime";
/** The web sidebar's sections, in its order. Active has no header unless others show. */ /** The web sidebar's sections, in its order. Active has no header unless others show. */
export type Section = "pinned" | "active" | "working" | "snoozed" | "settled"; export type Section = "pinned" | "active" | "working" | "snoozed" | "settled" | "archived";
/** The web sidebar's row status (resolveSidebarThreadStatus). */ /** The web sidebar's row status (resolveSidebarThreadStatus). */
export type ThreadStatus = "approval" | "input" | "request" | "waiting" | "working" | "limited" | "failed" | "ready"; export type ThreadStatus = "approval" | "input" | "request" | "waiting" | "working" | "limited" | "failed" | "ready";
@@ -27,9 +27,10 @@ export const SECTION_LABELS: Record<Section, string> = {
working: "Working", working: "Working",
snoozed: "Snoozed", snoozed: "Snoozed",
settled: "Settled", settled: "Settled",
archived: "Archived threads",
}; };
export const SECTION_ORDER: readonly Section[] = ["pinned", "active", "working", "snoozed", "settled"]; export const SECTION_ORDER: readonly Section[] = ["pinned", "active", "working", "snoozed", "settled", "archived"];
/** Only one server, so any constant id works for presentThreadShell. */ /** Only one server, so any constant id works for presentThreadShell. */
const LOCAL_ENVIRONMENT = "local" as EnvironmentId; const LOCAL_ENVIRONMENT = "local" as EnvironmentId;
@@ -88,19 +89,19 @@ export type StatusTone = "info" | "muted" | "warn" | "input" | "bad" | "good";
/** Threads in the web sidebar's sections and order. Subagent threads stay under their parent, so they're left out. */ /** Threads in the web sidebar's sections and order. Subagent threads stay under their parent, so they're left out. */
export function threadRows( export function threadRows(
snapshot: OrchestrationV2ShellSnapshot | null, snapshot: OrchestrationV2ShellSnapshot | null,
options: { readonly query?: string; readonly settledLimit?: number; readonly now?: string } = {}, options: { readonly query?: string; readonly settledLimit?: number; readonly archived?: boolean; readonly now?: string } = {},
): ThreadRow[] { ): ThreadRow[] {
if (!snapshot) return []; if (!snapshot) return [];
const projects = new Map<ProjectId, OrchestrationProjectShell>(snapshot.projects.map((project) => [project.id, project])); const projects = new Map<ProjectId, OrchestrationProjectShell>(snapshot.projects.map((project) => [project.id, project]));
const query = options.query?.trim().toLowerCase(); const query = options.query?.trim().toLowerCase();
const now = options.now ?? new Date().toISOString(); const now = options.now ?? new Date().toISOString();
const bySection: Record<Section, EnvironmentThreadShell[]> = { pinned: [], active: [], working: [], snoozed: [], settled: [] }; const bySection: Record<Section, EnvironmentThreadShell[]> = { pinned: [], active: [], working: [], snoozed: [], settled: [], archived: [] };
for (const thread of snapshot.threads) { for (const thread of snapshot.threads) {
if (thread.archivedAt !== null || thread.deletedAt !== null || thread.lineage.relationshipToParent === "subagent") continue; if ((thread.archivedAt !== null) !== (options.archived === true) || thread.deletedAt !== null || thread.lineage.relationshipToParent === "subagent") continue;
const projectName = projectLabel(projects.get(thread.projectId)); const projectName = projectLabel(projects.get(thread.projectId));
if (query && !thread.title.toLowerCase().includes(query) && !projectName.toLowerCase().includes(query)) continue; if (query && !thread.title.toLowerCase().includes(query) && !projectName.toLowerCase().includes(query)) continue;
const shell = presentThreadShell(LOCAL_ENVIRONMENT, thread); const shell = presentThreadShell(LOCAL_ENVIRONMENT, thread);
const section: Section = effectiveSnoozed(shell, { now }) const section: Section = options.archived ? "archived" : effectiveSnoozed(shell, { now })
? "snoozed" ? "snoozed"
: shell.settledOverride === "settled" : shell.settledOverride === "settled"
? "settled" ? "settled"
@@ -112,6 +113,7 @@ export function threadRows(
bySection[section].push(shell); bySection[section].push(shell);
} }
const sorted: Record<Section, EnvironmentThreadShell[]> = { const sorted: Record<Section, EnvironmentThreadShell[]> = {
archived: bySection.archived.toSorted((a, b) => Date.parse(b.archivedAt ?? "") - Date.parse(a.archivedAt ?? "")),
pinned: sortPinnedThreadsByOrderKey(bySection.pinned), pinned: sortPinnedThreadsByOrderKey(bySection.pinned),
active: sortInboxThreadsByReturn(bySection.active), active: sortInboxThreadsByReturn(bySection.active),
working: sortWorkingThreadsBySend(bySection.working), working: sortWorkingThreadsBySend(bySection.working),
+44 -9
View File
@@ -25,7 +25,7 @@ import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type De
import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type Picker, type PickerItem } from "../model/palette.ts"; import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type Picker, type PickerItem } from "../model/palette.ts";
import { serverSettingLines, settingRows } from "../model/settings.ts"; import { serverSettingLines, settingRows } from "../model/settings.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts"; import { buildTimeline, type Timeline } from "../model/timeline.ts";
import { threadRows, type Section } from "../model/threads.ts"; import type { Section } from "../model/threads.ts";
import { ComposerMenu } from "./ComposerMenu.tsx"; import { ComposerMenu } from "./ComposerMenu.tsx";
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx"; import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
import { DetailsPanel } from "./DetailsPanel.tsx"; import { DetailsPanel } from "./DetailsPanel.tsx";
@@ -40,13 +40,18 @@ import { copyText, desktopNotify, ring } from "./terminalOut.ts";
import { colors } from "./theme.ts"; import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx"; import { ThreadList } from "./ThreadList.tsx";
import { ThreadView } from "./ThreadView.tsx"; import { ThreadView } from "./ThreadView.tsx";
import { useThreadLibrary } from "./useThreadLibrary.ts";
import { usePaletteSearch } from "./usePaletteSearch.ts";
import { useThreadFind } from "./useThreadFind.ts";
import { ThreadFindBar } from "./ThreadFindBar.tsx";
import { mergeThreadShells, messageMatchGroups } from "../model/search.ts";
/** /**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve. * "input": typing goes to the composer. "nav": single keys move, scroll, approve.
* "details": j/k move through the details panel. "settings": j/k move through settings. * "details": j/k move through the details panel. "settings": j/k move through settings.
* The rest are overlays with their own input. * The rest are overlays with their own input.
*/ */
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings"; type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find";
/** Holding j/k skims past threads; only subscribe to one you stop on. */ /** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120; const SUBSCRIBE_DELAY_MS = 120;
@@ -158,8 +163,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return () => clearInterval(timer); return () => clearInterval(timer);
}, []); }, []);
const allRows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]); const library = useThreadLibrary(session, shell.snapshot, filter);
const unfold = showFolded || filter.trim() !== ""; const allRows = library.allRows;
useEffect(() => { if (!attached) setSelectedId(undefined); }, [library.archived]);
const unfold = library.archived || showFolded || filter.trim() !== "";
const rows = useMemo(() => (unfold ? allRows : allRows.filter((row) => !FOLDED_SECTIONS.includes(row.section))), [allRows, unfold]); const rows = useMemo(() => (unfold ? allRows : allRows.filter((row) => !FOLDED_SECTIONS.includes(row.section))), [allRows, unfold]);
const collapsed = useMemo( const collapsed = useMemo(
() => new Map(unfold ? [] : FOLDED_SECTIONS.map((section) => [section, allRows.filter((row) => row.section === section).length] as const)), () => new Map(unfold ? [] : FOLDED_SECTIONS.map((section) => [section, allRows.filter((row) => row.section === section).length] as const)),
@@ -169,7 +176,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const threadId = selectedId ?? rows[0]?.thread.id; const threadId = selectedId ?? rows[0]?.thread.id;
const selectedIndex = rows.findIndex((row) => row.thread.id === threadId); const selectedIndex = rows.findIndex((row) => row.thread.id === threadId);
const threadRow = allRows.find((row) => row.thread.id === threadId); const threadRow = allRows.find((row) => row.thread.id === threadId);
const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId) ?? (threadId ? familyShells.get(threadId) : undefined); const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId) ?? library.archive?.threads.find((thread) => thread.id === threadId) ?? library.merged?.threads.find((thread) => thread.id === threadId) ?? (threadId ? familyShells.get(threadId) : undefined);
const composerKey: string = draft ? DRAFT_KEY : (threadId ?? ""); const composerKey: string = draft ? DRAFT_KEY : (threadId ?? "");
// Pin the initial selection to a thread, or it would follow whatever sorts first. // Pin the initial selection to a thread, or it would follow whatever sorts first.
useEffect(() => { useEffect(() => {
@@ -213,11 +220,13 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const timeline = useMemo(() => { const timeline = useMemo(() => {
if (!thread?.projection || !watchedId) return null; if (!thread?.projection || !watchedId) return null;
const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : null; const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : null;
const next = buildTimeline(thread.projection, { expandAll }, previous); const next = buildTimeline(thread.projection, { expandAll: expandAll || mode === "find" }, previous);
previousTimeline.current = { id: watchedId, timeline: next }; previousTimeline.current = { id: watchedId, timeline: next };
return next; return next;
}, [thread?.projection, watchedId, expandAll]); }, [thread?.projection, watchedId, expandAll, mode === "find"]);
const current = watchedId === threadId ? timeline : null; const current = watchedId === threadId ? timeline : null;
const find = useThreadFind(session, watchedId, thread, current, mode === "find");
const openFind = () => { setDiff(null); setSettingsIndex(null); setMode("find"); };
const pendingApproval = current?.pending.approvals[0]; const pendingApproval = current?.pending.approvals[0];
const pendingInput = current?.pending.userInputs[0]; const pendingInput = current?.pending.userInputs[0];
const questionDraft = pendingInput ? (questionDrafts.get(pendingInput.requestId) ?? { index: 0, answers: {} }) : undefined; const questionDraft = pendingInput ? (questionDrafts.get(pendingInput.requestId) ?? { index: 0, answers: {} }) : undefined;
@@ -592,6 +601,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return run(`Snoozed until ${preset.whenLabel}`, () => session.snoozeThread(id, preset.snoozedUntil)); return run(`Snoozed until ${preset.whenLabel}`, () => session.snoozeThread(id, preset.snoozedUntil));
} }
switch (action) { switch (action) {
case "find":
openThread(id);
return openFind();
case "settle": case "settle":
return run("Settled", () => session.settleThread(id)); return run("Settled", () => session.settleThread(id));
case "unsettle": case "unsettle":
@@ -962,9 +974,13 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] }); command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] });
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] }); command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
commands.push(...library.commands(threadId));
if (threadId && !draft) command("find", "Find in thread", openFind, { shortcut: "f", keywords: ["search", "messages", "plans"] });
const paletteSearch = usePaletteSearch(session, library.merged, paletteQuery, mode === "palette");
const paletteSnapshot = useMemo(() => mergeThreadShells(library.merged, paletteSearch.result?.threads ?? []), [library.merged, paletteSearch.result]);
const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}`).join("|"); const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}`).join("|");
// eslint-disable-next-line react-hooks/exhaustive-deps -- commands are rebuilt each render; commandKey tracks what changed. // eslint-disable-next-line react-hooks/exhaustive-deps -- commands are rebuilt each render; commandKey tracks what changed.
const groups = useMemo(() => (mode === "palette" ? paletteGroups({ query: paletteQuery, commands, snapshot: shell.snapshot, now }) : []), [mode, paletteQuery, commandKey, shell.snapshot]); const groups = useMemo(() => (mode === "palette" ? messageMatchGroups(paletteGroups({ query: paletteQuery, commands, snapshot: paletteSnapshot, now }), paletteSearch.result, paletteSnapshot, paletteQuery, now) : []), [mode, paletteQuery, commandKey, paletteSnapshot, paletteSearch.result]);
const entries = paletteEntries(groups); const entries = paletteEntries(groups);
const openPalette = () => { const openPalette = () => {
if (mode !== "palette" && mode !== "confirm") returnMode.current = mode === "filter" ? "nav" : mode; if (mode !== "palette" && mode !== "confirm") returnMode.current = mode === "filter" ? "nav" : mode;
@@ -1078,6 +1094,15 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}; };
useKeyboard((key) => { useKeyboard((key) => {
if (mode === "find") {
if (key.ctrl && key.name === "c") return quit();
if (key.ctrl && key.name === "k") return openPalette(), key.preventDefault();
if (find.handleKey(key)) {
if (key.name === "escape") setMode("nav");
return key.preventDefault();
}
return;
}
if (mode === "input" && menuKey(key)) return key.preventDefault(); if (mode === "input" && menuKey(key)) return key.preventDefault();
if (mode === "picker") { if (mode === "picker") {
if (key.ctrl && key.name === "c") return quit(); if (key.ctrl && key.name === "c") return quit();
@@ -1176,6 +1201,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return setMode("nav"); return setMode("nav");
} }
} }
if (mode === "nav" && library.key(key, threadId)) return key.preventDefault();
if (mode === "nav" && key.name === "f" && threadId && !draft) return openFind(), key.preventDefault();
switch (key.name) { switch (key.name) {
case "q": case "q":
if (diff) return setDiff(null); if (diff) return setDiff(null);
@@ -1335,6 +1362,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
if (target) openThreadMenu(target); if (target) openThreadMenu(target);
}} }}
onUnfold={() => setShowFolded(true)} onUnfold={() => setShowFolded(true)}
showMore={unfold && library.hasOlder}
onShowMore={() => void library.loadOlder()}
shelfStatus={library.error ?? (library.loading ? "Loading…" : library.archived ? "Archived threads · A to go back" : null)}
/> />
)} )}
<box flexDirection="column" flexGrow={1} minHeight={0}> <box flexDirection="column" flexGrow={1} minHeight={0}>
@@ -1354,7 +1384,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<DiffView diff={diff} scrollRef={scrollRef} /> <DiffView diff={diff} scrollRef={scrollRef} />
) : draft ? ( ) : draft ? (
<DraftView lines={draftLines} /> <DraftView lines={draftLines} />
) : threadId && detailsInPlace ? ( ) : threadId && detailsInPlace && mode !== "find" ? (
<box flexGrow={1} minHeight={0} flexDirection="column"> <box flexGrow={1} minHeight={0} flexDirection="column">
{detailsPanel(true)} {detailsPanel(true)}
</box> </box>
@@ -1365,6 +1395,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
title={title} title={title}
detail={threadShell?.branch ?? ""} detail={threadShell?.branch ?? ""}
timeline={current} timeline={current}
findQuery={find.open ? find.query.trim() : ""}
findMatch={find.match}
history={watchedId === threadId ? (thread?.history ?? null) : null} history={watchedId === threadId ? (thread?.history ?? null) : null}
loading={watchedId !== threadId || thread?.status === "loading"} loading={watchedId !== threadId || thread?.status === "loading"}
error={thread?.error} error={thread?.error}
@@ -1379,6 +1411,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text> <text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
</box> </box>
)} )}
{find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null}
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null} {mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
{mode === "confirm" && confirmation ? ( {mode === "confirm" && confirmation ? (
<ConfirmBar <ConfirmBar
@@ -1451,6 +1484,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
{mode === "palette" ? ( {mode === "palette" ? (
<Palette <Palette
query={paletteQuery} query={paletteQuery}
status={paletteSearch.error ?? (paletteSearch.pending ? "Searching messages…" : null)}
groups={groups} groups={groups}
selected={Math.min(paletteIndex, Math.max(0, entries.length - 1))} selected={Math.min(paletteIndex, Math.max(0, entries.length - 1))}
width={width} width={width}
@@ -1487,6 +1521,7 @@ function hints(
mode: Mode, mode: Mode,
state: { readonly draft: boolean; readonly config: Tui3Config; readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean; readonly diff: boolean; readonly parent: boolean }, state: { readonly draft: boolean; readonly config: Tui3Config; readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean; readonly diff: boolean; readonly parent: boolean },
): string { ): string {
if (mode === "find") return "enter next match · shift+enter previous · ctrl+n/p match · esc close find";
if (mode === "filter") return "enter done · esc close"; if (mode === "filter") return "enter done · esc close";
if (mode === "palette") return "↑/↓ move · enter run · esc close"; if (mode === "palette") return "↑/↓ move · enter run · esc close";
if (mode === "picker") return "↑/↓ move · enter choose · esc close"; if (mode === "picker") return "↑/↓ move · enter choose · esc close";
+40
View File
@@ -0,0 +1,40 @@
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import type { ScrollBoxRenderable, TextRenderable } from "@opentui/core";
import { useEffect, useRef, type RefObject, type ReactNode } from "react";
import { colors } from "./theme.ts";
/** Searchable rendered text, with the web's literal case-insensitive occurrence matching. */
export function FindText(props: { readonly segments: readonly string[]; readonly query: string; readonly activeOccurrence: number | null; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
const activeText = useRef<{ node: TextRenderable; text: string; offset: number } | null>(null);
useEffect(() => {
if (props.activeOccurrence === null) return;
const timer = setTimeout(() => {
const active = activeText.current;
const scroll = props.scrollRef.current;
if (!active || !scroll) return;
const before = active.text.slice(0, active.offset).split("\n");
const source = before.length - 1;
const column = Bun.stringWidth(before.at(-1) ?? "");
const info = active.node.lineInfo;
let line = 0;
info.lineSources.forEach((value, index) => { if (value === source && info.lineStartCols[index]! <= column) line = index; });
scroll.scrollBy(active.node.y + line - scroll.viewport.y - Math.floor(scroll.viewport.height / 2));
}, 0);
return () => clearTimeout(timer);
}, [props.activeOccurrence, props.query, props.segments, props.scrollRef]);
let occurrence = 0;
return <box flexDirection="column" marginTop={1}>{props.segments.map((segment, index) => {
let cursor = 0;
const parts: ReactNode[] = [];
let activeOffset: number | null = null;
for (const offset of findThreadSearchOccurrences(segment, props.query)) {
const active = occurrence++ === props.activeOccurrence;
if (active) activeOffset = offset;
parts.push(segment.slice(cursor, offset));
parts.push(<span key={offset} bg={active ? colors.accent : colors.selectedBg} fg={active ? colors.bg : colors.text}>{segment.slice(offset, offset + props.query.length)}</span>);
cursor = offset + props.query.length;
}
parts.push(segment.slice(cursor));
return <text key={index} fg={colors.text} ref={(node) => { if (node && activeOffset !== null) activeText.current = { node, text: segment, offset: activeOffset }; }}>{parts}</text>;
})}</box>;
}
+3 -1
View File
@@ -7,6 +7,7 @@ import { colors } from "./theme.ts";
*/ */
export function Palette(props: { export function Palette(props: {
readonly query: string; readonly query: string;
readonly status?: string | null | undefined;
readonly placeholder?: string; readonly placeholder?: string;
readonly groups: readonly PaletteGroup[]; readonly groups: readonly PaletteGroup[];
readonly selected: number; readonly selected: number;
@@ -35,6 +36,7 @@ export function Palette(props: {
<text fg={colors.accent}>{"› "}</text> <text fg={colors.accent}>{"› "}</text>
<input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} /> <input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
</box> </box>
{props.status ? <text fg={colors.muted} paddingLeft={1}>{props.status}</text> : null}
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}> <box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}>
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null} {rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
{rows.slice(start, start + listHeight).map((row) => {rows.slice(start, start + listHeight).map((row) =>
@@ -54,7 +56,7 @@ export function Palette(props: {
function Row(props: { readonly entry: PaletteEntry; readonly selected: boolean; readonly inner: number; readonly onPick: () => void }) { function Row(props: { readonly entry: PaletteEntry; readonly selected: boolean; readonly inner: number; readonly onPick: () => void }) {
const { entry } = props; const { entry } = props;
const right = entry.kind === "command" ? (entry.command.shortcut ?? "") : entry.project; const right = entry.kind === "command" ? (entry.command.shortcut ?? "") : entry.project;
const title = entry.kind === "command" ? entry.command.title : `${entry.subagent ? "↳ " : ""}${entry.title}`; const title = entry.kind === "command" ? entry.command.title : `${entry.subagent ? "↳ " : ""}${entry.snippet ? truncate(entry.title, Math.max(12, Math.floor(props.inner / 3))) : entry.title}${entry.snippet ? ` — ${entry.snippet}` : ""}`;
return ( return (
<box flexDirection="row" paddingLeft={1} paddingRight={1} backgroundColor={props.selected ? colors.selectedBg : "transparent"} onMouseDown={props.onPick}> <box flexDirection="row" paddingLeft={1} paddingRight={1} backgroundColor={props.selected ? colors.selectedBg : "transparent"} onMouseDown={props.onPick}>
<text fg={props.selected ? colors.text : entry.kind === "command" ? colors.text : colors.muted}>{truncate(title, props.inner - right.length - 2)}</text> <text fg={props.selected ? colors.text : entry.kind === "command" ? colors.text : colors.muted}>{truncate(title, props.inner - right.length - 2)}</text>
+28
View File
@@ -0,0 +1,28 @@
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
import { colors } from "./theme.ts";
/** The web's find bar, with the same wraparound navigation and a focused one-line query. */
export function ThreadFindBar(props: {
readonly query: string;
readonly focused: boolean;
readonly data: OrchestrationV2SearchThreadResult | null;
readonly pending: boolean;
readonly error: string | null;
readonly onQuery: (query: string) => void;
readonly onStep: (delta: number) => void;
readonly onClose: () => void;
}) {
const count = props.data?.totalMatches ?? 0;
return (
<box flexDirection="column" flexShrink={0} border={["top"]} borderColor={colors.border} paddingLeft={1} paddingRight={1}>
<box flexDirection="row" height={1}>
<input focused={props.focused} flexGrow={1} placeholder="Find in thread" value={props.query} onInput={props.onQuery} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
<text fg={colors.muted}>{props.pending ? " Searching… " : ` ${count ? (props.data?.activeIndex ?? 0) + 1 : 0} of ${count} `}</text>
<text fg={colors.accent} onMouseDown={() => props.onStep(-1)}> ↑ </text>
<text fg={colors.accent} onMouseDown={() => props.onStep(1)}> ↓ </text>
<text fg={colors.muted} onMouseDown={props.onClose}> esc </text>
</box>
<text fg={props.error ? colors.bad : colors.faint}>{props.error ?? "enter / shift+enter or ctrl+n/p · esc close"}</text>
</box>
);
}
+5
View File
@@ -27,6 +27,9 @@ export function ThreadList(props: {
/** A right-click: the thread's menu. */ /** A right-click: the thread's menu. */
readonly onMenu: (threadId: ThreadId) => void; readonly onMenu: (threadId: ThreadId) => void;
readonly onUnfold: () => void; readonly onUnfold: () => void;
readonly shelfStatus?: string | null | undefined;
readonly showMore?: boolean;
readonly onShowMore?: () => void;
}) { }) {
const { rows, selected, focused, width, height, now } = props; const { rows, selected, focused, width, height, now } = props;
// Rows take two lines plus a header per section; keep the selection in view. // Rows take two lines plus a header per section; keep the selection in view.
@@ -82,6 +85,8 @@ export function ThreadList(props: {
) : null} ) : null}
{rows.length === 0 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines} {rows.length === 0 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines}
<box flexGrow={1} /> <box flexGrow={1} />
{props.shelfStatus ? <text fg={colors.muted} paddingLeft={1}>{props.shelfStatus}</text> : null}
{props.showMore ? <text fg={colors.accent} paddingLeft={1} onMouseDown={() => props.onShowMore?.()}>Show more settled threads (ctrl+k)</text> : null}
{collapsed.map(([section, count]) => ( {collapsed.map(([section, count]) => (
<text key={section} fg={colors.faint} onMouseDown={props.onUnfold}>{` › ${SECTION_LABELS[section]} ${count}`}</text> <text key={section} fg={colors.faint} onMouseDown={props.onUnfold}>{` › ${SECTION_LABELS[section]} ${count}`}</text>
))} ))}
+17
View File
@@ -3,6 +3,10 @@ import type { ThreadId } from "@t3tools/contracts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
import { memo, type RefObject } from "react"; import { memo, type RefObject } from "react";
import { findTextSegments } from "../model/search.ts";
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
import { FindText } from "./FindText.tsx";
import type { ThreadHistory } from "../client/session.ts"; import type { ThreadHistory } from "../client/session.ts";
import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts";
@@ -15,6 +19,8 @@ export function ThreadView(props: {
readonly title: string; readonly title: string;
readonly detail: string; readonly detail: string;
readonly timeline: Timeline | null; readonly timeline: Timeline | null;
readonly findQuery?: string | undefined;
readonly findMatch?: OrchestrationV2SearchThreadResult["match"] | undefined;
readonly history: ThreadHistory | null; readonly history: ThreadHistory | null;
readonly loading: boolean; readonly loading: boolean;
readonly error?: string | undefined; readonly error?: string | undefined;
@@ -51,6 +57,9 @@ export function ThreadView(props: {
<Row <Row
key={row.id} key={row.id}
row={row} row={row}
scrollRef={props.scrollRef}
findQuery={props.findQuery ?? ""}
activeOccurrence={props.findMatch?.entryId === row.id ? props.findMatch.occurrence : null}
pending={row.kind === "event" && pendingIds.has(eventRequestId(row) ?? "")} pending={row.kind === "event" && pendingIds.has(eventRequestId(row) ?? "")}
workspaceRoot={props.workspaceRoot} workspaceRoot={props.workspaceRoot}
now={row.kind === "working" ? props.now : 0} now={row.kind === "working" ? props.now : 0}
@@ -85,6 +94,9 @@ function Divider({ label, color }: { readonly label: string; readonly color: str
*/ */
const Row = memo(function Row(props: { const Row = memo(function Row(props: {
readonly row: MessagesTimelineRow; readonly row: MessagesTimelineRow;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
readonly findQuery: string;
readonly activeOccurrence: number | null;
readonly pending: boolean; readonly pending: boolean;
readonly workspaceRoot: string | undefined; readonly workspaceRoot: string | undefined;
readonly now: number; readonly now: number;
@@ -95,6 +107,10 @@ const Row = memo(function Row(props: {
switch (row.kind) { switch (row.kind) {
case "message": { case "message": {
const { message } = row; const { message } = row;
if (props.findQuery) {
const segments = findTextSegments(message.text, message.role === "user");
if (segments.some((segment) => findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return <FindText segments={segments} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
}
if (message.role === "user") return <UserMessage text={message.text} />; if (message.role === "user") return <UserMessage text={message.text} />;
if (message.role === "system") return <text marginTop={1} fg={colors.muted}>{message.text}</text>; if (message.role === "system") return <text marginTop={1} fg={colors.muted}>{message.text}</text>;
return ( return (
@@ -144,6 +160,7 @@ const Row = memo(function Row(props: {
case "context-compaction": case "context-compaction":
return <Divider label={row.failed ? `${row.title ?? "Compaction failed"}${row.failure ? `: ${row.failure}` : ""}` : (row.title ?? row.label)} color={row.failed ? colors.bad : colors.faint} />; return <Divider label={row.failed ? `${row.title ?? "Compaction failed"}${row.failure ? `: ${row.failure}` : ""}` : (row.title ?? row.label)} color={row.failed ? colors.bad : colors.faint} />;
case "proposed-plan": case "proposed-plan":
if (props.findQuery) return <FindText segments={findTextSegments(row.proposedPlan.planMarkdown)} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
return ( return (
<box marginTop={1} border borderStyle="rounded" borderColor={colors.plan} flexDirection="column" paddingLeft={1} paddingRight={1}> <box marginTop={1} border borderStyle="rounded" borderColor={colors.plan} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={colors.plan}> <text fg={colors.plan}>
+26
View File
@@ -0,0 +1,26 @@
import { useEffect, useState } from "react";
import type { OrchestrationV2SearchThreadsResult, OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
import type { T3Session } from "../client/session.ts";
import { threadSearchQuery } from "../model/search.ts";
import { messageSearchTokens } from "@t3tools/shared/paletteSearch";
/** The web palette waits 120ms, and ignores results from queries already replaced. */
export function usePaletteSearch(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string, open: boolean) {
const normalized = open ? threadSearchQuery(query, snapshot?.olderSettled != null) : null;
const before = snapshot?.olderSettled?.before;
const [result, setResult] = useState<{ query: string; value: OrchestrationV2SearchThreadsResult } | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setError(null);
if (!normalized) return;
let cancelled = false;
const timer = setTimeout(() => {
session.searchThreads({ query: normalized, ...(before ? { olderSettledBefore: before, ...(messageSearchTokens(normalized).long.length ? {} : { titlesOnly: true }) } : {}) }).then(
(value) => { if (!cancelled) setResult({ query: normalized, value }); },
(error) => { if (!cancelled) setError(`Could not search messages: ${String(error)}`); },
);
}, 120);
return () => { cancelled = true; clearTimeout(timer); };
}, [session, normalized, before]);
return { result: normalized && result?.query === normalized ? result.value : null, pending: normalized !== null && result?.query !== normalized && !error, error };
}
+55
View File
@@ -0,0 +1,55 @@
import type { KeyEvent } from "@opentui/core";
import type { OrchestrationV2SearchThreadResult, ThreadId } from "@t3tools/contracts";
import { useEffect, useRef, useState } from "react";
import type { T3Session, ThreadState } from "../client/session.ts";
import type { Timeline } from "../model/timeline.ts";
import { stepThreadFindIndex } from "../../vendor/t3code/apps/web/src/components/chat/threadFind.ts";
/** Find counts the entire thread on the server, paging history only until its selected entry appears. */
export function useThreadFind(session: T3Session, id: ThreadId | undefined, thread: ThreadState | null, timeline: Timeline | null, open: boolean) {
const [query, setQuery] = useState("");
const [index, setIndex] = useState(0);
const [result, setResult] = useState<{ key: string; value: OrchestrationV2SearchThreadResult } | null>(null);
const [error, setError] = useState<string | null>(null);
const normalized = query.trim().slice(0, 200).trim();
const key = open && id && normalized ? JSON.stringify([id, normalized, index]) : null;
const latestText = thread?.projection?.visibleTurnItems.at(-1);
useEffect(() => { setQuery(""); setIndex(0); }, [id]);
useEffect(() => {
setError(null);
if (!key || !id) return;
let cancelled = false;
const timer = setTimeout(() => {
session.searchThread({ threadId: id, query: normalized, index }).then(
(value) => { if (!cancelled) setResult({ key, value }); },
(error) => { if (!cancelled) setError(String(error)); },
);
}, 100);
return () => { cancelled = true; clearTimeout(timer); };
}, [session, id, key, latestText]);
const data = key && result?.key === key ? result.value : null;
const match = data?.match ?? null;
const requested = useRef<string | null>(null);
useEffect(() => {
if (!id || !match || !timeline || timeline.rows.some((row) => row.id === match.entryId)) return;
const history = thread?.history;
if (!history?.hasMore || history.loading || history.error) return;
const request = `${key}:${history.cursor}`;
if (requested.current === request) return;
requested.current = request;
session.loadEarlier(id).catch((error) => setError(String(error)));
}, [session, id, match, timeline, thread?.history, key]);
const step = (delta: number) => {
if (data) setIndex(stepThreadFindIndex(data.activeIndex, data.totalMatches, delta));
};
const handleKey = (key: KeyEvent): boolean => {
if (!open) return false;
if (key.name === "escape") return true;
else if (key.name === "return") step(key.shift ? -1 : 1);
else if (key.ctrl && key.name === "n") step(1);
else if (key.ctrl && key.name === "p") step(-1);
else return false;
return true;
};
return { open, query, onQuery: (value: string) => { setQuery(value); setIndex(0); }, data, match, error, pending: key !== null && data === null && !error, step, handleKey };
}
+95
View File
@@ -0,0 +1,95 @@
import type { KeyEvent } from "@opentui/core";
import type { OrchestrationV2ArchivedShellSnapshot, OrchestrationV2OlderSettledCursor, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { ThreadId as ThreadIdSchema } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { useEffect, useMemo, useState } from "react";
import type { T3Session } from "../client/session.ts";
import { mergeThreadShells, threadReorder } from "../model/search.ts";
import { threadRows } from "../model/threads.ts";
import type { PaletteCommand } from "../model/palette.ts";
type Command = PaletteCommand & { readonly run: () => void };
/** The sidebar's fetched shelves live separately from its live shell. */
export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string) {
const [archived, setArchived] = useState(false);
const [archive, setArchive] = useState<OrchestrationV2ArchivedShellSnapshot | null>(null);
const [older, setOlder] = useState<readonly OrchestrationV2ThreadShell[]>([]);
const [cursor, setCursor] = useState<OrchestrationV2OlderSettledCursor | null>(null);
const [end, setEnd] = useState(false);
const [limit, setLimit] = useState(30);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const cut = snapshot?.olderSettled?.before;
useEffect(() => {
setOlder([]);
setCursor(null);
setEnd(false);
setLimit(30);
}, [cut]);
const refreshArchive = () => session.archivedThreads().then(setArchive);
useEffect(() => {
if (!archived) { setLoading(false); return; }
let cancelled = false;
setLoading(true);
setError(null);
session.archivedThreads().then(
(value) => { if (!cancelled) { setArchive(value); setLoading(false); } },
(error) => { if (!cancelled) { setError(String(error)); setLoading(false); } },
);
return () => { cancelled = true; };
}, [session, archived]);
const merged = useMemo(() => mergeThreadShells(snapshot, older), [snapshot, older]);
const listSnapshot = archived && snapshot ? { ...snapshot, projects: archive?.projects ?? snapshot.projects, threads: archive?.threads ?? [] } : merged;
const allRows = useMemo(() => threadRows(listSnapshot, { query, archived, settledLimit: limit }), [listSnapshot, query, archived, limit]);
const totalSettled = useMemo(() => threadRows(merged, { query, settledLimit: Infinity }).filter((row) => row.section === "settled").length, [merged, query]);
const hasOlder = !archived && (totalSettled > limit || (!end && (snapshot?.olderSettled?.counts.some((count) => count.count > 0) ?? false)));
const loadOlder = async () => {
if (loading) return;
setLimit((value) => value + 30);
if (!cut || end || totalSettled > limit) return;
setLoading(true);
setError(null);
try {
const page = await session.olderSettledThreads({ before: cursor ?? { settledAt: cut }, limit: 30 });
setOlder((previous) => [...previous, ...page.threads]);
const last = page.threads.at(-1);
if (last?.settledAt) setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id });
setEnd(page.threads.length < 30);
} catch (error) {
setError(String(error));
} finally {
setLoading(false);
}
};
const toggle = () => { setError(null); setArchived((value) => !value); };
const unarchive = async (id: ThreadId) => {
await session.unarchiveThread(id);
await refreshArchive();
};
const reorder = async (id: ThreadId, delta: 1 | -1) => {
const row = allRows.find((row) => row.thread.id === id);
// The web's Working shelf makes Active chronological, not manually reorderable.
if (row?.section === "active") { setError("Active threads are ordered by return time, as in T3 Code's Working shelf."); return; }
const plan = threadReorder(allRows, id, delta, threadRows(listSnapshot, { archived, settledLimit: limit }));
if (!plan || archived) return;
try {
for (const assignment of plan.assignments) await session.reorderThread(ThreadIdSchema.make(assignment.id), plan.section, assignment.orderKey);
} catch (error) { setError(String(error)); }
};
const commands = (id: ThreadId | undefined): Command[] => [
{ id: "archived", title: archived ? "Show active threads" : "Show archived threads", shortcut: "A", keywords: ["archive", "history", "restore"], run: toggle },
...(hasOlder ? [{ id: "older-settled", title: "Show more settled threads", keywords: ["older", "history", "load"], run: () => void loadOlder() }] : []),
...(id && archive?.threads.some((thread) => thread.id === id) ? [{ id: "unarchive", title: "Unarchive thread", keywords: ["restore", "archived"], run: () => void unarchive(id).catch((error) => setError(String(error))) }] : []),
...(id && allRows.some((row) => row.thread.id === id && row.section === "pinned") ? [
{ id: "reorder-up", title: "Move pinned thread up", shortcut: "K", keywords: ["reorder", "sort"], run: () => void reorder(id, -1) },
{ id: "reorder-down", title: "Move pinned thread down", shortcut: "J", keywords: ["reorder", "sort"], run: () => void reorder(id, 1) },
] : []),
];
const key = (key: KeyEvent, id: ThreadId | undefined): boolean => {
if (key.name === "a" && key.shift) return toggle(), true;
if (id && key.shift && (key.name === "j" || key.name === "k")) return void reorder(id, key.name === "j" ? 1 : -1), true;
return false;
};
return { archived, allRows, merged, archive, commands, key, hasOlder, loadOlder, loading, error };
}
+102
View File
@@ -0,0 +1,102 @@
import { describe, expect, test } from "bun:test";
import { OrchestrationV2RpcSchemas, OrchestrationV2SearchThreadsInput, ThreadId, type OrchestrationV2SearchThreadsResult, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { T3Session } from "../src/client/session.ts";
import { findTextSegments, mergeThreadShells, messageMatchGroups, threadReorder, threadSearchQuery } from "../src/model/search.ts";
import { paletteGroups } from "../src/model/palette.ts";
import { threadRows } from "../src/model/threads.ts";
import { stepThreadFindIndex } from "../vendor/t3code/apps/web/src/components/chat/threadFind.ts";
const at = (ms: number) => DateTime.makeUnsafe(ms);
const thread = (id: string, extra: Record<string, unknown> = {}) => ({
id, title: id, projectId: "p1", status: "completed", activeRunId: null,
latestRunId: null, latestUserMessageAt: null, pendingRuntimeRequest: null,
lineage: { relationshipToParent: null, parentThreadId: null }, modelSelection: { instanceId: "codex", model: "gpt" },
archivedAt: null, deletedAt: null, settledOverride: null, settledAt: null, pinnedAt: null,
lastVisitedAt: at(100), hasActionableProposedPlan: false, interactionMode: "default", createdAt: at(0), updatedAt: at(100), ...extra,
}) as unknown as OrchestrationV2ThreadShell;
const snapshot = (threads: readonly OrchestrationV2ThreadShell[]) => ({ projects: [{ id: "p1", title: "Project", workspaceRoot: "/project" }], threads, archivedThreads: [] }) as unknown as OrchestrationV2ShellSnapshot;
describe("thread search", () => {
test("uses the web's minimum tokens, query cap, and commands-only prefix", () => {
expect(threadSearchQuery("ab", false)).toBeNull();
expect(threadSearchQuery("ab", true)).toBe("ab");
expect(threadSearchQuery(" hello world ", false)).toBe("hello world");
expect(threadSearchQuery("> search", true)).toBeNull();
expect(threadSearchQuery("x".repeat(300), false)?.length).toBe(200);
});
test("adds snippets in a final group, excluding threads already found by title", () => {
const shell = snapshot([thread("hello"), thread("other")]);
const groups = paletteGroups({ query: "hello", commands: [], snapshot: shell });
const result = { matches: [{ threadId: "hello", projectId: "p1", snippet: "hello", source: "user", messageCreatedAt: null }, { threadId: "other", projectId: "p1", snippet: "hello from a message", source: "assistant", messageCreatedAt: null }] } as unknown as OrchestrationV2SearchThreadsResult;
const combined = messageMatchGroups(groups, result, shell);
expect(combined.map((group) => group.label)).toEqual(["Threads", "In messages"]);
expect(combined.at(-1)?.entries[0]).toMatchObject({ threadId: "other", snippet: "hello from a message" });
expect(messageMatchGroups(groups, null, shell)).toEqual(groups);
});
test("live rows and archives replace stale fetched older rows", () => {
const old = thread("older", { settledOverride: "settled", settledAt: at(100) });
const active = thread("older");
expect(mergeThreadShells(snapshot([active]), [old])?.threads).toEqual([active]);
const archived = thread("older", { archivedAt: at(200) });
const merged = mergeThreadShells({ ...snapshot([]), archivedThreads: [archived] }, [old]);
expect(threadRows(merged)).toEqual([]);
});
test("archived rows stay separate and show newest archive first", () => {
const shell = snapshot([thread("active"), thread("older", { archivedAt: at(200) }), thread("newer", { archivedAt: at(300) })]);
expect(threadRows(shell).map((row) => row.thread.id as string)).toEqual(["active"]);
expect(threadRows(shell, { archived: true }).map((row) => [row.thread.id as string, row.section])).toEqual([["newer", "archived"], ["older", "archived"]]);
});
test("can reveal beyond the first thirty settled threads", () => {
const shell = snapshot(Array.from({ length: 45 }, (_, i) => thread(`settled-${i}`, { settledOverride: "settled", settledAt: at(i + 1) })));
expect(threadRows(shell)).toHaveLength(30);
expect(threadRows(shell, { settledLimit: 60 })).toHaveLength(45);
});
test("find strips markdown and wraps through server match counts", () => {
expect(findTextSegments("# Header\n\nFind **this** [label](https://example.com).\n\n```ts\nconst answer = 42;\n```\n")).toEqual(["Header", "Find this label.", "const answer = 42;"]);
expect(findTextSegments("Find a\nphrase")).toEqual(["Find a phrase"]);
expect(findTextSegments("Find a\nphrase", true)).toEqual(["Find a", "phrase"]);
expect(stepThreadFindIndex(2, 3, 1)).toBe(0);
expect(stepThreadFindIndex(0, 3, -1)).toBe(2);
expect(stepThreadFindIndex(0, 0, 1)).toBe(0);
});
test("reordering uses the web's planner and respects section boundaries", () => {
const rows = threadRows(snapshot([thread("one", { pinnedAt: at(1), pinOrderKey: "f" }), thread("two", { pinnedAt: at(1), pinOrderKey: "m" }), thread("three", { pinnedAt: at(1), pinOrderKey: "t" }), thread("active")]));
const move = threadReorder(rows, ThreadId.make("two"), 1);
expect(move?.section).toBe("pinned");
expect(move?.assignments).toHaveLength(1);
expect(move!.assignments[0]!.orderKey > "t").toBe(true);
expect(threadReorder(rows, ThreadId.make("one"), -1)).toBeNull();
expect(threadReorder(rows, ThreadId.make("three"), 1)).toBeNull();
const keyless = threadRows(snapshot([thread("one", { pinnedAt: at(1) }), thread("two", { pinnedAt: at(1) })]));
expect(threadReorder(keyless, ThreadId.make("one"), 1)?.assignments).toHaveLength(2);
const hidden = threadRows(snapshot([thread("hidden", { pinnedAt: at(1), pinOrderKey: "w" })]));
const filtered = threadReorder(rows.filter((row) => row.thread.id !== "three"), ThreadId.make("one"), 1, [...rows, ...hidden]);
expect(filtered?.assignments.every((assignment) => assignment.id !== "hidden" && assignment.orderKey !== "w")).toBe(true);
});
test("read RPC wrappers send payloads accepted by their contract schemas", async () => {
const session = new T3Session();
const schemas = { searchThreads: OrchestrationV2SearchThreadsInput, searchThread: OrchestrationV2RpcSchemas.searchThread.input, getArchivedShellSnapshot: OrchestrationV2RpcSchemas.getArchivedShellSnapshot.input, getOlderSettledThreads: OrchestrationV2RpcSchemas.getOlderSettledThreads.input };
const sent: { name: keyof typeof schemas; input: unknown }[] = [];
const rpc = Object.fromEntries(["searchThreads", "searchThread", "getArchivedShellSnapshot", "getOlderSettledThreads"].map((name) => [`orchestration.${name}`, (input: unknown) => {
sent.push({ name: name as keyof typeof schemas, input });
return Effect.succeed({});
}]));
(session as unknown as { connection: unknown }).connection = { rpc };
await session.searchThreads({ query: "hello", limit: 20, olderSettledBefore: "2026-10-01T00:00:00Z" });
await session.searchThread({ threadId: ThreadId.make("one"), query: "hello", index: 2 });
await session.archivedThreads();
await session.olderSettledThreads({ before: { settledAt: "2026-10-01T00:00:00Z", threadId: ThreadId.make("one") }, limit: 30 });
expect(sent).toHaveLength(4);
for (const call of sent) expect(Schema.is(schemas[call.name])(call.input)).toBe(true);
});
});
+7 -1
View File
@@ -54,7 +54,7 @@ describe("thread menu", () => {
expect(menu).toContain("copy-thread-id"); expect(menu).toContain("copy-thread-id");
expect(menu).toContain("delete"); expect(menu).toContain("delete");
expect(menu).not.toContain("project-settings"); expect(menu).not.toContain("project-settings");
expect(menu).not.toContain("find"); expect(menu).toContain("find");
}); });
test("a settled, pinned thread offers to undo both", () => { test("a settled, pinned thread offers to undo both", () => {
@@ -95,6 +95,9 @@ describe("thread menu", () => {
await session.renameThread(id, "New name"); await session.renameThread(id, "New name");
await session.regenerateTitle(id); await session.regenerateTitle(id);
await session.archiveThread(id); await session.archiveThread(id);
await session.unarchiveThread(id);
await session.reorderThread(id, "pinned", "m");
await session.reorderThread(id, "active", "t");
await session.deleteThread(id, false); await session.deleteThread(id, false);
expect(sent.filter((command) => !Schema.is(OrchestrationV2Command)(command))).toEqual([]); expect(sent.filter((command) => !Schema.is(OrchestrationV2Command)(command))).toEqual([]);
expect(sent.map((command) => (command as { type: string }).type)).toEqual([ expect(sent.map((command) => (command as { type: string }).type)).toEqual([
@@ -109,6 +112,9 @@ describe("thread menu", () => {
"thread.metadata.update", "thread.metadata.update",
"thread.metadata.update", "thread.metadata.update",
"thread.archive", "thread.archive",
"thread.unarchive",
"thread.pin.reorder",
"thread.active.reorder",
"thread.delete", "thread.delete",
]); ]);
}); });