Merge search: full-text palette search, find in thread, archive, older settled threads, pinned reorder

# Conflicts:
#	README.md
#	src/ui/App.tsx
This commit is contained in:
Callum Alpass committed 2026-11-02 20:43:43 +11:00
commit 5efadc0707
17 files changed
+551 -24

No files matched your search

+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 { 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";
@@ -45,13 +45,18 @@ import { ThreadView } from "./ThreadView.tsx";
import { useQueue } from "./useQueue.ts";
import { useSecretRequest } from "./useSecretRequest.ts";
import { canStopSubagent } from "../model/subagents.ts";
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;
@@ -162,8 +167,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)),
@@ -173,7 +180,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(() => {
@@ -217,11 +224,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;
@@ -607,6 +616,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":
@@ -949,9 +961,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;
@@ -1065,6 +1081,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();
@@ -1166,6 +1191,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}
}
if (workspace.key(key)) return;
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);
@@ -1327,6 +1354,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)}
/>
)}
<box flexDirection="column" flexGrow={1} minHeight={0}>
@@ -1346,7 +1376,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<DiffView diff={diff} scrollRef={scrollRef} />
) : draft ? (
<DraftView lines={draftLines} />
) : threadId && detailsInPlace ? (
) : threadId && detailsInPlace && mode !== "find" ? (
<box flexGrow={1} minHeight={0} flexDirection="column">
{detailsPanel(true)}
</box>
@@ -1357,6 +1387,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}
@@ -1372,6 +1404,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
</box>
)}
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
{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" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} /> : null}
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} /> : null}
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
@@ -1446,6 +1479,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
{mode === "palette" ? (
<Palette
query={paletteQuery}
status={paletteSearch.error ?? (paletteSearch.pending ? "Searching messages…" : null)}
groups={groups}
selected={Math.min(paletteIndex, Math.max(0, entries.length - 1))}
width={width}
@@ -1496,6 +1530,7 @@ function hints(
if (state.secret === "focused") return "type or paste the secret · enter save securely · esc cancel";
if (mode === "input" && state.queue === "editing") return "enter save the queued message · esc cancel the edit";
if (mode === "nav" && state.queue === "focused") return "j/k move · enter send now · e edit · x remove · esc back";
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 === "palette") return "↑/↓ move · enter run · 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: {
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: {
<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} />
</box>
{props.status ? <text fg={colors.muted} paddingLeft={1}>{props.status}</text> : null}
<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.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 (
<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>
+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. */
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 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines}
<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]) => (
<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 { 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: {
<Row
key={row.id}
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) ?? "")}
workspaceRoot={props.workspaceRoot}
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: {
readonly row: MessagesTimelineRow;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
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 <FindText segments={segments} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
}
if (message.role === "user") return <UserMessage text={message.text} />;
if (message.role === "system") return <text marginTop={1} fg={colors.muted}>{message.text}</text>;
return (
@@ -144,6 +160,7 @@ const Row = memo(function Row(props: {
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} />;
case "proposed-plan":
if (props.findQuery) return <FindText segments={findTextSegments(row.proposedPlan.planMarkdown)} query={props.findQuery} activeOccurrence={props.activeOccurrence} scrollRef={props.scrollRef} />;
return (
<box marginTop={1} border borderStyle="rounded" borderColor={colors.plan} flexDirection="column" paddingLeft={1} paddingRight={1}>
<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 };
}