diff --git a/README.md b/README.md index 901d0d3..f5bd0f4 100644 --- a/README.md +++ b/README.md @@ -58,11 +58,14 @@ Navigation: | `x` | dismiss the agent's question | | `e` | expand all folded turns and work groups | | `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 | | `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) | | `:` | 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) | | `S` | stop the thread | | `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. - **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). -- **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. - 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. @@ -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 - 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 diff --git a/src/client/session.ts b/src/client/session.ts index e5d8848..9ca4427 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -6,6 +6,9 @@ import { ORCHESTRATION_V2_WS_METHODS, OrchestrationV2ThreadHistoryPage, type OrchestrationV2Command, + type OrchestrationV2SearchThreadsInput, + type OrchestrationV2SearchThreadInput, + type OrchestrationV2GetOlderSettledThreadsInput, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadProjection, type ProviderApprovalDecision, @@ -516,6 +519,32 @@ export class T3Session { 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 { + return this.dispatch({ type: "thread.unarchive", commandId: newCommandId(), threadId }); + } + + reorderThread(threadId: ThreadId, section: "pinned" | "active", orderKey: string): Promise { + 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. */ async searchEntries(cwd: string, query: string, limit: number): Promise { const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsSearchEntries]({ cwd, query, limit })); diff --git a/src/model/palette.ts b/src/model/palette.ts index 2e7fd53..d965025 100644 --- a/src/model/palette.ts +++ b/src/model/palette.ts @@ -16,7 +16,7 @@ export interface PaletteCommand { export type PaletteEntry = | { 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 { readonly label: string; diff --git a/src/model/search.ts b/src/model/search.ts new file mode 100644 index 0000000..65afc28 --- /dev/null +++ b/src/model/search.ts @@ -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])) }) }; +} diff --git a/src/model/threadMenu.ts b/src/model/threadMenu.ts index a42dda4..0583b47 100644 --- a/src/model/threadMenu.ts +++ b/src/model/threadMenu.ts @@ -10,8 +10,8 @@ export type { ThreadActionMenuId }; const LOCAL = EnvironmentId.make("local"); -/** Web-only actions: finding in the thread, project settings, guest links, turning into a project. */ -const UNSUPPORTED: ReadonlySet = new Set(["find", "project-settings", "share-guest", "turn-into-project", "filter-by-project"]); +/** Web-only actions: project settings, guest links, turning into a project. */ +const UNSUPPORTED: ReadonlySet = new Set(["project-settings", "share-guest", "turn-into-project", "filter-by-project"]); export interface ThreadMenu { readonly items: readonly ContextMenuItem[]; @@ -28,7 +28,7 @@ export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; const snoozePresets = snoozeMenu(config, input.timestampFormat, now); const items = buildThreadActionMenuItems({ canOperate: true, - canFind: false, + canFind: true, branch: thread.branch ?? null, projectFilter: null, isPinned: thread.pinnedAt != null, diff --git a/src/model/threads.ts b/src/model/threads.ts index 55cb6d9..6a63db8 100644 --- a/src/model/threads.ts +++ b/src/model/threads.ts @@ -6,7 +6,7 @@ import { sortPinnedThreadsByOrderKey, sortSettledThreads } from "@t3tools/client import * as DateTime from "effect/DateTime"; /** 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). */ export type ThreadStatus = "approval" | "input" | "request" | "waiting" | "working" | "limited" | "failed" | "ready"; @@ -27,9 +27,10 @@ export const SECTION_LABELS: Record = { working: "Working", snoozed: "Snoozed", 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. */ 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. */ export function threadRows( 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[] { if (!snapshot) return []; const projects = new Map(snapshot.projects.map((project) => [project.id, project])); const query = options.query?.trim().toLowerCase(); const now = options.now ?? new Date().toISOString(); - const bySection: Record = { pinned: [], active: [], working: [], snoozed: [], settled: [] }; + const bySection: Record = { pinned: [], active: [], working: [], snoozed: [], settled: [], archived: [] }; 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)); if (query && !thread.title.toLowerCase().includes(query) && !projectName.toLowerCase().includes(query)) continue; const shell = presentThreadShell(LOCAL_ENVIRONMENT, thread); - const section: Section = effectiveSnoozed(shell, { now }) + const section: Section = options.archived ? "archived" : effectiveSnoozed(shell, { now }) ? "snoozed" : shell.settledOverride === "settled" ? "settled" @@ -112,6 +113,7 @@ export function threadRows( bySection[section].push(shell); } const sorted: Record = { + archived: bySection.archived.toSorted((a, b) => Date.parse(b.archivedAt ?? "") - Date.parse(a.archivedAt ?? "")), pinned: sortPinnedThreadsByOrderKey(bySection.pinned), active: sortInboxThreadsByReturn(bySection.active), working: sortWorkingThreadsBySend(bySection.working), diff --git a/src/ui/App.tsx b/src/ui/App.tsx index da7fabd..9da5310 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -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 { serverSettingLines, settingRows } from "../model/settings.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 { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx"; import { DetailsPanel } from "./DetailsPanel.tsx"; @@ -40,13 +40,18 @@ import { copyText, desktopNotify, ring } from "./terminalOut.ts"; import { colors } from "./theme.ts"; import { ThreadList } from "./ThreadList.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. * "details": j/k move through the details panel. "settings": j/k move through settings. * 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. */ const SUBSCRIBE_DELAY_MS = 120; @@ -158,8 +163,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return () => clearInterval(timer); }, []); - const allRows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]); - const unfold = showFolded || filter.trim() !== ""; + const library = useThreadLibrary(session, shell.snapshot, filter); + 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 collapsed = useMemo( () => 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 selectedIndex = rows.findIndex((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 ?? ""); // Pin the initial selection to a thread, or it would follow whatever sorts first. useEffect(() => { @@ -213,11 +220,13 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const timeline = useMemo(() => { if (!thread?.projection || !watchedId) return 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 }; return next; - }, [thread?.projection, watchedId, expandAll]); + }, [thread?.projection, watchedId, expandAll, mode === "find"]); 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 pendingInput = current?.pending.userInputs[0]; 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)); } switch (action) { + case "find": + openThread(id); + return openFind(); case "settle": return run("Settled", () => session.settleThread(id)); 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("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("|"); // 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 openPalette = () => { 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) => { + 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 === "picker") { 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"); } } + 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) { case "q": if (diff) return setDiff(null); @@ -1335,6 +1362,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C if (target) openThreadMenu(target); }} 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)} /> )} @@ -1354,7 +1384,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C ) : draft ? ( - ) : threadId && detailsInPlace ? ( + ) : threadId && detailsInPlace && mode !== "find" ? ( {detailsPanel(true)} @@ -1365,6 +1395,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C title={title} detail={threadShell?.branch ?? ""} timeline={current} + findQuery={find.open ? find.query.trim() : ""} + findMatch={find.match} history={watchedId === threadId ? (thread?.history ?? null) : null} loading={watchedId !== threadId || thread?.status === "loading"} error={thread?.error} @@ -1379,6 +1411,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C {shell.snapshot ? "No thread selected." : "Waiting for threads…"} )} + {find.open ? setMode("nav")} /> : null} {mode !== "confirm" && pendingInput && questionDraft ? : null} {mode === "confirm" && confirmation ? ( }) { + 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 {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({segment.slice(offset, offset + props.query.length)}); + cursor = offset + props.query.length; + } + parts.push(segment.slice(cursor)); + return { if (node && activeOffset !== null) activeText.current = { node, text: segment, offset: activeOffset }; }}>{parts}; + })}; +} diff --git a/src/ui/Palette.tsx b/src/ui/Palette.tsx index f458b9d..2df3075 100644 --- a/src/ui/Palette.tsx +++ b/src/ui/Palette.tsx @@ -7,6 +7,7 @@ import { colors } from "./theme.ts"; */ export function Palette(props: { readonly query: string; + readonly status?: string | null | undefined; readonly placeholder?: string; readonly groups: readonly PaletteGroup[]; readonly selected: number; @@ -35,6 +36,7 @@ export function Palette(props: { {"› "} for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} /> + {props.status ? {props.status} : null} {rows.length === 0 ? No matches : null} {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 }) { const { entry } = props; 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 ( {truncate(title, props.inner - right.length - 2)} diff --git a/src/ui/ThreadFindBar.tsx b/src/ui/ThreadFindBar.tsx new file mode 100644 index 0000000..5fbeee1 --- /dev/null +++ b/src/ui/ThreadFindBar.tsx @@ -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 ( + + + + {props.pending ? " Searching… " : ` ${count ? (props.data?.activeIndex ?? 0) + 1 : 0} of ${count} `} + props.onStep(-1)}> ↑ + props.onStep(1)}> ↓ + esc + + {props.error ?? "enter / shift+enter or ctrl+n/p · esc close"} + + ); +} diff --git a/src/ui/ThreadList.tsx b/src/ui/ThreadList.tsx index 0af2d27..32f0227 100644 --- a/src/ui/ThreadList.tsx +++ b/src/ui/ThreadList.tsx @@ -27,6 +27,9 @@ export function ThreadList(props: { /** A right-click: the thread's menu. */ readonly onMenu: (threadId: ThreadId) => void; readonly onUnfold: () => void; + readonly shelfStatus?: string | null | undefined; + readonly showMore?: boolean; + readonly onShowMore?: () => void; }) { const { rows, selected, focused, width, height, now } = props; // Rows take two lines plus a header per section; keep the selection in view. @@ -82,6 +85,8 @@ export function ThreadList(props: { ) : null} {rows.length === 0 ? {props.filter ? " no matches" : " no threads"} : lines} + {props.shelfStatus ? {props.shelfStatus} : null} + {props.showMore ? props.onShowMore?.()}>Show more settled threads (ctrl+k) : null} {collapsed.map(([section, count]) => ( {` › ${SECTION_LABELS[section]} ${count}`} ))} diff --git a/src/ui/ThreadView.tsx b/src/ui/ThreadView.tsx index 584844c..7a3a1da 100644 --- a/src/ui/ThreadView.tsx +++ b/src/ui/ThreadView.tsx @@ -3,6 +3,10 @@ import type { ThreadId } from "@t3tools/contracts"; import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; 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 { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; @@ -15,6 +19,8 @@ export function ThreadView(props: { readonly title: string; readonly detail: string; readonly timeline: Timeline | null; + readonly findQuery?: string | undefined; + readonly findMatch?: OrchestrationV2SearchThreadResult["match"] | undefined; readonly history: ThreadHistory | null; readonly loading: boolean; readonly error?: string | undefined; @@ -51,6 +57,9 @@ export function ThreadView(props: { ; + readonly findQuery: string; + readonly activeOccurrence: number | null; readonly pending: boolean; readonly workspaceRoot: string | undefined; readonly now: number; @@ -95,6 +107,10 @@ const Row = memo(function Row(props: { switch (row.kind) { case "message": { 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 ; + } if (message.role === "user") return ; if (message.role === "system") return {message.text}; return ( @@ -144,6 +160,7 @@ const Row = memo(function Row(props: { case "context-compaction": return ; case "proposed-plan": + if (props.findQuery) return ; return ( diff --git a/src/ui/usePaletteSearch.ts b/src/ui/usePaletteSearch.ts new file mode 100644 index 0000000..1559d6b --- /dev/null +++ b/src/ui/usePaletteSearch.ts @@ -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(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 }; +} diff --git a/src/ui/useThreadFind.ts b/src/ui/useThreadFind.ts new file mode 100644 index 0000000..0fca212 --- /dev/null +++ b/src/ui/useThreadFind.ts @@ -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(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(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 }; +} diff --git a/src/ui/useThreadLibrary.ts b/src/ui/useThreadLibrary.ts new file mode 100644 index 0000000..2e97813 --- /dev/null +++ b/src/ui/useThreadLibrary.ts @@ -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(null); + const [older, setOlder] = useState([]); + const [cursor, setCursor] = useState(null); + const [end, setEnd] = useState(false); + const [limit, setLimit] = useState(30); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(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 }; +} diff --git a/test/search.test.ts b/test/search.test.ts new file mode 100644 index 0000000..4681aa2 --- /dev/null +++ b/test/search.test.ts @@ -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 = {}) => ({ + 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); + }); +}); diff --git a/test/threadMenu.test.ts b/test/threadMenu.test.ts index fcc8594..e2de4c5 100644 --- a/test/threadMenu.test.ts +++ b/test/threadMenu.test.ts @@ -54,7 +54,7 @@ describe("thread menu", () => { expect(menu).toContain("copy-thread-id"); expect(menu).toContain("delete"); expect(menu).not.toContain("project-settings"); - expect(menu).not.toContain("find"); + expect(menu).toContain("find"); }); test("a settled, pinned thread offers to undo both", () => { @@ -95,6 +95,9 @@ describe("thread menu", () => { await session.renameThread(id, "New name"); await session.regenerateTitle(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); expect(sent.filter((command) => !Schema.is(OrchestrationV2Command)(command))).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.archive", + "thread.unarchive", + "thread.pin.reorder", + "thread.active.reorder", "thread.delete", ]); });