Match T3 Code's sidebar, timeline and composer

Reuse the web app's timeline derivation (turn folds, work groups, live
work), its sidebar sections and status words, steer-by-default sending,
the question panel, decline-with-feedback, and visit/read marking.
This commit is contained in:
Callum Alpass committed 2026-11-02 17:35:56 +11:00
1 parent 4f42407099
commit 2dac4763d2
17 files changed
+988 -430

No files matched your search

+199 -61
View File
@@ -1,11 +1,20 @@
import type { KeyEvent, ScrollBoxRenderable, TextareaRenderable } from "@opentui/core";
import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react";
import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
import {
buildPendingUserInputAnswers,
resolvePendingUserInputAnswer,
setPendingUserInputCustomAnswer,
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "@t3tools/client-runtime/state/pending-user-input";
import type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef, useState } from "react";
import type { ShellState, T3Session, ThreadState } from "../client/session.ts";
import { buildTranscript, type Transcript } from "../model/transcript.ts";
import { isRunning, lastActivity, needsUser, relativeTime, threadRows } from "../model/threads.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts";
import { threadRows, type Section } from "../model/threads.ts";
import { QuestionPanel } from "./QuestionPanel.tsx";
import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx";
import { ThreadView } from "./ThreadView.tsx";
@@ -15,15 +24,30 @@ type Mode = "input" | "nav" | "filter";
/** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120;
/** Opening a thread marks it read once you've stayed this long, as in the web app. */
const VISIT_DELAY_MS = 1_500;
const MAX_COMPOSER_LINES = 6;
/** Sections folded to a count unless you filter or press z, like the web sidebar's. */
const FOLDED_SECTIONS: readonly Section[] = ["snoozed", "settled"];
const COMPOSER_KEYS = [
{ name: "return", action: "submit" },
{ name: "return", shift: true, action: "newline" },
{ name: "return", meta: true, action: "newline" },
{ name: "j", ctrl: true, action: "newline" },
] as const;
const RUNTIME_MODE_LABELS: Record<string, string> = {
"approval-required": "Supervised",
"auto-accept-edits": "Auto-accept edits",
auto: "Auto",
"full-access": "Full access",
};
interface QuestionDraft {
readonly index: number;
readonly answers: Record<string, PendingUserInputDraftAnswer>;
}
export function App(props: { readonly session: T3Session; readonly attachThreadId?: ThreadId }) {
const { session, attachThreadId } = props;
const renderer = useRenderer();
@@ -32,20 +56,36 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const [selectedId, setSelectedId] = useState<ThreadId | undefined>(attachThreadId);
const [mode, setMode] = useState<Mode>(attachThreadId ? "input" : "nav");
const [filter, setFilter] = useState("");
const [expandWork, setExpandWork] = useState(false);
const [showFolded, setShowFolded] = useState(false);
const [expandAll, setExpandAll] = useState(false);
const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null);
const [composerLines, setComposerLines] = useState(1);
const [composerEmpty, setComposerEmpty] = useState(true);
const [questionDrafts, setQuestionDrafts] = useState<ReadonlyMap<string, QuestionDraft>>(new Map());
const [now, setNow] = useState(Date.now());
const scrollRef = useRef<ScrollBoxRenderable | null>(null);
const composerRef = useRef<TextareaRenderable | null>(null);
const drafts = useRef(new Map<string, string>());
useEffect(() => session.onShell(setShell), [session]);
// Drives "Working for 12s" and the sidebar's durations.
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1_000);
return () => clearInterval(timer);
}, []);
const rows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]);
const allRows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]);
const unfold = 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)),
[allRows, unfold],
);
// Selection is a thread id, not an index, so the list can reorder underneath it.
const selectedIndex = Math.max(0, rows.findIndex((row) => row.thread.id === selectedId));
const threadId = attachThreadId ?? rows[selectedIndex]?.thread.id;
const threadShell = shell.snapshot?.threads.find((thread) => thread.id === threadId);
const threadRow = allRows.find((row) => row.thread.id === threadId);
const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId);
// Pin the initial selection to a thread, or it would follow whatever sorts first.
useEffect(() => {
if (selectedId === undefined && rows[0]) setSelectedId(rows[0].thread.id);
@@ -65,44 +105,107 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const [thread, setThread] = useState<ThreadState | null>(null);
useEffect(() => {
setThread(null);
if (!watchedId || !shell.serverUrl) return;
if (!watchedId || shell.status.type !== "live") return;
return session.watchThread(watchedId, setThread);
}, [session, watchedId, shell.serverUrl]);
}, [session, watchedId, shell.status.type]);
const running = threadShell ? isRunning(threadShell) && !needsUser(threadShell) : false;
const previousTranscript = useRef<{ id: string; transcript: Transcript } | null>(null);
const transcript = useMemo(() => {
const unread = threadRow?.unread === true;
useEffect(() => {
if (!watchedId || !unread) return;
const timer = setTimeout(() => void session.visit(watchedId).catch(() => {}), VISIT_DELAY_MS);
return () => clearTimeout(timer);
}, [session, watchedId, unread]);
const previousTimeline = useRef<{ id: string; timeline: Timeline } | null>(null);
const timeline = useMemo(() => {
if (!thread?.projection || !watchedId) return null;
const previous = previousTranscript.current?.id === watchedId ? previousTranscript.current.transcript : null;
const next = buildTranscript(thread.projection, { running, previous });
previousTranscript.current = { id: watchedId, transcript: next };
const previous = previousTimeline.current?.id === watchedId ? previousTimeline.current.timeline : null;
const next = buildTimeline(thread.projection, { expandAll }, previous);
previousTimeline.current = { id: watchedId, timeline: next };
return next;
}, [thread?.projection, watchedId, running]);
const pendingRequest = thread?.projection?.runtimeRequests.findLast((request) => request.status === "pending" && request.kind !== "user_input");
}, [thread?.projection, watchedId, expandAll]);
const current = watchedId === threadId ? timeline : null;
const pendingApproval = current?.pending.approvals[0];
const pendingInput = current?.pending.userInputs[0];
const questionDraft = pendingInput ? (questionDrafts.get(pendingInput.requestId) ?? { index: 0, answers: {} }) : undefined;
const working = current?.isWorking ?? false;
const say = (text: string, bad = false) => {
setFlash({ text, bad });
setTimeout(() => setFlash((current) => (current?.text === text ? null : current)), 4000);
setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), 4000);
};
const run = (label: string, action: () => Promise<void>) => {
const run = (label: string, action: () => Promise<unknown>) => {
action().then(
() => say(label),
(error) => say(`${label} failed: ${error instanceof Error ? error.message : String(error)}`, true),
);
};
const respond = (decision: ProviderApprovalDecision) => {
if (!threadId || !pendingRequest) return say("Nothing is waiting for approval.", true);
run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingRequest.id, decision));
if (!threadId || !pendingApproval) return say("Nothing is waiting for approval.", true);
run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingApproval.requestId, decision));
};
const submit = () => {
const composer = composerRef.current;
const text = composer?.plainText.trim() ?? "";
if (!composer || !text || !threadId) return;
composer.setText("");
drafts.current.delete(threadId);
const clearComposer = () => {
composerRef.current?.setText("");
if (threadId) drafts.current.delete(threadId);
setComposerLines(1);
run(running ? "Queued for after the current run" : "Sent", () => session.sendMessage(threadId, text));
setComposerEmpty(true);
};
/** Moves the question flow on: the next question, or the answers once all are in. */
const advanceQuestion = (draft: QuestionDraft) => {
if (!threadId || !pendingInput) return;
const question = pendingInput.questions[draft.index];
if (!question || resolvePendingUserInputAnswer(question, draft.answers[question.id]) === null) {
setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, draft));
return say("Pick an option or type an answer.", true);
}
if (draft.index + 1 < pendingInput.questions.length) {
setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, { ...draft, index: draft.index + 1 }));
return;
}
const answers = buildPendingUserInputAnswers(pendingInput.questions, draft.answers);
if (!answers) return say("Some questions are unanswered.", true);
setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, draft));
run("Answered", () => session.answer(threadId, pendingInput.requestId, answers));
};
const pickOption = (optionIndex: number) => {
if (!pendingInput || !questionDraft) return;
const question = pendingInput.questions[questionDraft.index];
const option = question?.options[optionIndex];
if (!question || !option) return;
const draft = { ...questionDraft, answers: { ...questionDraft.answers, [question.id]: togglePendingUserInputOptionSelection(question, questionDraft.answers[question.id], option.value ?? option.label) } };
setQuestionDrafts((map) => new Map(map).set(pendingInput.requestId, draft));
// Single choice moves on by itself, after a beat to show the pick.
if (!question.multiSelect) setTimeout(() => advanceQuestion(draft), 200);
};
/** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */
const submit = (alternate = false) => {
const text = composerRef.current?.plainText.trim() ?? "";
if (!threadId) return;
if (pendingInput && questionDraft) {
const question = pendingInput.questions[questionDraft.index];
if (!question) return;
const answer = text ? setPendingUserInputCustomAnswer(question, questionDraft.answers[question.id], text) : questionDraft.answers[question.id];
clearComposer();
return advanceQuestion({ ...questionDraft, answers: { ...questionDraft.answers, ...(answer ? { [question.id]: answer } : {}) } });
}
if (!text) return;
clearComposer();
if (pendingApproval) {
// As in the web composer: the message declines the request and redirects the agent.
if (pendingApproval.supportsFeedback) return run("Declined with feedback", () => session.respond(threadId, pendingApproval.requestId, "decline", text));
return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer"));
}
const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate });
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode));
};
const loadEarlier = () => {
if (!watchedId) return;
session.loadEarlier(watchedId).catch((error) => say(`Could not load earlier turns: ${error instanceof Error ? error.message : String(error)}`, true));
};
const quit = () => {
@@ -121,11 +224,17 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
if (key.name === "pageup" || (key.ctrl && key.name === "u")) return scrollPage(-1), true;
if (!attachThreadId && ((key.ctrl && key.name === "n") || (key.meta && key.name === "down"))) return move(1), true;
if (!attachThreadId && ((key.ctrl && key.name === "p") || (key.meta && key.name === "up"))) return move(-1), true;
if (mode === "input" && key.meta && key.name === "return") return submit(true), true;
return false;
};
useKeyboard((key) => {
if (globalKey(key)) return key.preventDefault();
const digit = /^[1-9]$/.test(key.name) && !key.ctrl && !key.meta ? Number(key.name) - 1 : -1;
if (digit >= 0 && pendingInput && (mode === "nav" || (mode === "input" && composerEmpty))) {
pickOption(digit);
return key.preventDefault();
}
if (mode === "input" || mode === "filter") {
if (key.name === "escape") {
setMode("nav");
@@ -146,11 +255,18 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
case "g":
return key.shift ? scroll?.scrollTo(scroll.scrollHeight) : scroll?.scrollTo(0);
case "e":
return setExpandWork((value) => !value);
return setExpandAll((value) => !value);
case "o":
return loadEarlier();
case "z":
return setShowFolded((value) => !value);
case "y":
return respond(key.shift ? "acceptForSession" : "accept");
case "n":
return respond("decline");
case "x":
if (threadId && pendingInput?.dismissible) run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId));
return;
case "s":
if (threadId && key.shift) run("Stop requested", () => session.stopThread(threadId));
return;
@@ -165,16 +281,6 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
}
});
const counts = useMemo(() => {
let needs = 0;
let active = 0;
for (const row of threadRows(shell.snapshot, { recentLimit: 0 })) {
if (row.group === "needs-you") needs++;
else if (row.group === "running") active++;
}
return { needs, active };
}, [shell.snapshot]);
const status =
shell.status.type === "error"
? `error: ${shell.status.message}`
@@ -184,10 +290,28 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
? "reconnecting…"
: (shell.serverUrl ?? "");
const listWidth = attachThreadId ? 0 : Math.min(46, Math.max(28, Math.floor(width * 0.3)));
const subtitle = threadShell
? [threadShell.modelSelection.model === "default" ? "" : threadShell.modelSelection.model, threadShell.branch, relativeTime(lastActivity(threadShell))].filter(Boolean).join(" · ")
: "";
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2;
const placeholder =
mode !== "input"
? "Press i to type"
: pendingApproval
? pendingApproval.supportsFeedback
? "Send feedback to decline this request"
: "Send a message to decline and redirect the agent"
: pendingInput
? "Type your own answer, or leave this blank to use the selected option"
: working
? "Steer the agent (alt+enter to queue instead)"
: "Ask anything";
const footer = threadShell
? [
threadShell.modelSelection.model === "default" ? "" : threadShell.modelSelection.model,
threadShell.interactionMode === "plan" ? "Plan" : "Build",
threadShell.runtimeMode === "full-access" ? "" : (RUNTIME_MODE_LABELS[threadShell.runtimeMode] ?? threadShell.runtimeMode),
]
.filter(Boolean)
.join(" · ")
: "";
return (
<box flexDirection="column" width={width} height={height} backgroundColor={colors.bg}>
@@ -195,23 +319,24 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
<text fg={colors.accent}>
<strong>tui3</strong>
</text>
<text fg={colors.faint}>{` ${status}`}</text>
<box flexGrow={1} />
{counts.needs > 0 ? <text fg={colors.warn}>{`● ${counts.needs} need you `}</text> : null}
<text fg={colors.muted}>{`◐ ${counts.active} running`}</text>
<text fg={shell.status.type === "live" ? colors.faint : colors.warn}>{` ${status}`}</text>
</box>
<box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden">
{attachThreadId ? null : <ThreadList rows={rows} selected={selectedIndex} focused={mode === "nav"} width={listWidth} height={height - 2} filter={filter} />}
{attachThreadId ? null : (
<ThreadList rows={rows} collapsed={collapsed} selected={selectedIndex} focused={mode === "nav"} width={listWidth} height={height - 2} filter={filter} now={now} />
)}
<box flexDirection="column" flexGrow={1} minHeight={0}>
{threadId ? (
<ThreadView
title={threadShell?.title ?? "thread"}
subtitle={subtitle}
transcript={watchedId === threadId ? transcript : null}
project={threadRow?.projectName ?? ""}
title={threadShell?.title ?? "Thread"}
detail={threadShell?.branch ?? ""}
timeline={current}
history={watchedId === threadId ? (thread?.history ?? null) : null}
loading={watchedId !== threadId || thread?.status === "loading"}
error={thread?.error}
working={running}
expandWork={expandWork}
workspaceRoot={threadShell?.worktreePath ?? undefined}
now={now}
scrollRef={scrollRef}
/>
) : (
@@ -219,6 +344,7 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
</box>
)}
{mode !== "filter" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
{mode === "filter" ? (
<box title=" filter " border borderStyle="rounded" borderColor={colors.borderFocused} height={3} flexShrink={0} marginLeft={1} marginRight={1}>
<input focused placeholder="title or project…" value={filter} onInput={(value: string) => setFilter(value)} onSubmit={() => setMode("nav")} />
@@ -240,39 +366,51 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
ref={composerRef}
focused={mode === "input"}
initialValue={drafts.current.get(threadId) ?? ""}
placeholder={mode === "input" ? (running ? "Message (queued until the current run finishes)" : "Message") : "Press i to type"}
placeholder={placeholder}
placeholderColor={colors.faint}
textColor={colors.text}
keyBindings={[...COMPOSER_KEYS]}
onSubmit={submit}
onSubmit={() => submit()}
onContentChange={() => {
const text = composerRef.current?.plainText ?? "";
if (text) drafts.current.set(threadId, text);
else drafts.current.delete(threadId);
setComposerLines(Math.max(1, text.split("\n").length));
setComposerEmpty(text.trim() === "");
}}
/>
</box>
) : null}
{mode !== "filter" && threadId ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
<text fg={colors.faint}>{footer}</text>
</box>
) : null}
</box>
</box>
<box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
{flash ? <text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text> : <text fg={colors.faint}>{hints(mode, Boolean(pendingRequest), Boolean(attachThreadId))}</text>}
{flash ? (
<text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text>
) : (
<text fg={colors.faint}>{hints(mode, { approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached: Boolean(attachThreadId) })}</text>
)}
</box>
</box>
);
}
function hints(mode: Mode, pending: boolean, attached: boolean): string {
function hints(mode: Mode, state: { readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean }): string {
if (mode === "filter") return "enter done · esc close";
if (mode === "input") {
const parts = ["enter send", "shift+enter newline", "esc navigate"];
if (!attached) parts.push("ctrl+n/p switch thread");
if (pending) parts.unshift("approval waiting: esc, then y/n");
const parts = [state.working ? "enter steer · alt+enter queue" : "enter send", "shift+enter newline", "esc navigate"];
if (state.question) parts.unshift("1-9 pick");
if (state.approval) parts.unshift("approval waiting: esc, then y/n");
if (!state.attached) parts.push("ctrl+n/p thread");
return parts.join(" · ");
}
const parts = attached ? ["j/k scroll"] : ["j/k threads", "/ filter"];
parts.push("i type", "e expand work", "pgup/pgdn scroll", "S stop", "q quit");
if (pending) parts.unshift("y accept · Y session · n decline");
const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter", "z settled"];
parts.push("i type", "e expand", "o earlier", "S stop", "q quit");
if (state.question) parts.unshift("1-9 pick · x dismiss");
if (state.approval) parts.unshift("y approve · Y always · n decline");
return parts.join(" · ");
}
+42
View File
@@ -0,0 +1,42 @@
import type { ThreadPendingUserInput } from "@t3tools/client-runtime/state/thread-requests";
import { isPendingUserInputOptionSelected, type PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
import { colors } from "./theme.ts";
/**
* The web composer's pending-input panel: header with progress, the question,
* and its options with digit shortcuts. The composer below takes a typed answer.
*/
export function QuestionPanel(props: {
readonly request: ThreadPendingUserInput;
readonly index: number;
readonly draft: PendingUserInputDraftAnswer | undefined;
}) {
const { request, index, draft } = props;
const question = request.questions[index];
if (!question) return null;
const total = request.questions.length;
return (
<box border borderStyle="rounded" borderColor={colors.input} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
<box flexDirection="row">
<text fg={colors.input}>
<strong>{question.header}</strong>
</text>
<box flexGrow={1} />
<text fg={colors.faint}>{total > 1 ? `${index + 1}/${total}` : ""}</text>
</box>
<text fg={colors.text}>{question.question}</text>
{question.options.slice(0, 9).map((option, optionIndex) => {
const selected = isPendingUserInputOptionSelected(question, draft, option.value ?? option.label);
const mark = question.multiSelect ? (selected ? "☑" : "☐") : selected ? "●" : "○";
return (
<box key={option.label} flexDirection="row">
<text fg={selected ? colors.input : colors.faint}>{`${optionIndex + 1} ${mark} `}</text>
<text fg={selected ? colors.text : colors.muted}>{option.label}</text>
<text fg={colors.faint}>{option.description ? ` ${option.description}` : ""}</text>
</box>
);
})}
</box>
);
}
+56 -47
View File
@@ -1,69 +1,78 @@
import { GROUP_LABELS, lastActivity, relativeTime, type ThreadRow } from "../model/threads.ts";
import { colors } from "./theme.ts";
import { needsAttention, relativeTime, rowTime, SECTION_LABELS, statusLabel, type Section, type ThreadRow } from "../model/threads.ts";
import { colors, statusColor } from "./theme.ts";
const STATUS_GLYPH: Record<string, { glyph: string; color: string }> = {
"needs-you": { glyph: "●", color: colors.warn },
running: { glyph: "◐", color: colors.accent },
failed: { glyph: "✕", color: colors.bad },
interrupted: { glyph: "◌", color: colors.muted },
completed: { glyph: "✓", color: colors.faint },
idle: { glyph: "·", color: colors.faint },
};
function glyphFor(row: ThreadRow) {
if (row.group !== "recent") return STATUS_GLYPH[row.group]!;
return STATUS_GLYPH[row.thread.status] ?? STATUS_GLYPH.idle!;
}
export function ThreadList(props: { readonly rows: readonly ThreadRow[]; readonly selected: number; readonly focused: boolean; readonly width: number; readonly height: number; readonly filter: string }) {
const { rows, selected, focused, width, height } = props;
// Rows take two lines and up to three group headers take one each; keep the selection in view.
const visibleCount = Math.max(1, Math.floor((height - 3) / 2));
/**
* The web sidebar as a list: section headers, then two-line rows of
* project + status (or time), and the title, bold when it needs you and
* dimmed while it works or once read.
*/
export function ThreadList(props: {
readonly rows: readonly ThreadRow[];
/** Sections folded to a header with a count, like the web's Snoozed and Settled. */
readonly collapsed: ReadonlyMap<Section, number>;
readonly selected: number;
readonly focused: boolean;
readonly width: number;
readonly height: number;
readonly filter: string;
readonly now: number;
}) {
const { rows, selected, focused, width, height, now } = props;
// Rows take two lines plus a header per section; keep the selection in view.
const visibleCount = Math.max(1, Math.floor((height - 6) / 2));
const start = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), rows.length - visibleCount));
const windowRows = rows.slice(start, start + visibleCount);
const titleWidth = Math.max(8, width - 12);
const now = Date.now();
const inner = Math.max(8, width - 3);
// Active goes unlabelled when it leads the list, as in the web sidebar.
const labelActive = rows.some((row) => row.section === "pinned");
const lines: React.ReactNode[] = [];
let previousGroup = start > 0 ? rows[start - 1]?.group : undefined;
let previousSection = start > 0 ? rows[start - 1]?.section : undefined;
windowRows.forEach((row, offset) => {
const index = start + offset;
if (row.group !== previousGroup) {
lines.push(
<text key={`h-${row.group}`} fg={row.group === "needs-you" ? colors.warn : colors.muted}>
<strong>{GROUP_LABELS[row.group]}</strong>
</text>,
);
previousGroup = row.group;
if (row.section !== previousSection) {
if (row.section !== "active" || labelActive) lines.push(<SectionHeader key={`h-${row.section}`} label={SECTION_LABELS[row.section]} />);
else if (previousSection !== undefined) lines.push(<text key="h-gap"> </text>);
previousSection = row.section;
}
const { glyph, color } = glyphFor(row);
const isSelected = index === selected;
const title = truncate(row.thread.title || "(untitled)", titleWidth);
const status = statusLabel(row, now);
const right = status?.text ?? relativeTime(rowTime(row.thread), now);
const left = truncate(row.projectName || "No project", Math.max(4, inner - right.length - 1));
const attention = needsAttention(row);
const recede = !isSelected && (row.status === "working" || row.status === "waiting" || (row.status === "ready" && !row.unread));
const title = truncate(row.thread.title || "New thread", inner);
lines.push(
<box key={row.thread.id} flexDirection="row" backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.border) : "transparent"}>
<text fg={color}>{` ${glyph} `}</text>
<box flexGrow={1} flexDirection="column">
<text fg={isSelected ? colors.text : colors.text}>{title}</text>
<text fg={colors.faint}>{truncate(`${row.projectName} · ${relativeTime(lastActivity(row.thread), now)}`, titleWidth)}</text>
<box key={row.thread.id} flexDirection="column" paddingLeft={1} paddingRight={1} backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.panel) : "transparent"}>
<box flexDirection="row">
<text fg={colors.faint}>{left}</text>
<box flexGrow={1} />
<text fg={status ? statusColor[status.tone] : colors.faint}>{right}</text>
</box>
<text fg={recede ? colors.muted : colors.text}>{attention ? <strong>{title}</strong> : title}</text>
</box>,
);
});
const collapsed = [...props.collapsed].filter(([, count]) => count > 0);
return (
<box
border={["right"]}
borderColor={colors.border}
width={width}
flexShrink={0}
overflow="hidden"
flexDirection="column"
paddingLeft={0}
>
<box border={["right"]} borderColor={colors.border} width={width} flexShrink={0} overflow="hidden" flexDirection="column">
{props.filter ? <text fg={colors.accent}>{` /${props.filter}`}</text> : null}
{rows.length === 0 ? <text fg={colors.muted}> no threads</text> : lines}
{rows.length === 0 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines}
<box flexGrow={1} />
{collapsed.map(([section, count]) => (
<text key={section} fg={colors.faint}>{` › ${SECTION_LABELS[section]} ${count}`}</text>
))}
</box>
);
}
function SectionHeader({ label }: { readonly label: string }) {
return (
<text fg={colors.muted} paddingLeft={1}>
<strong>{label}</strong>
</text>
);
}
function truncate(text: string, width: number): string {
const single = text.replace(/\s+/g, " ");
return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single;
+192 -89
View File
@@ -1,145 +1,248 @@
import type { ScrollBoxRenderable } from "@opentui/core";
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 { summarizeWork, type Segment, type Step, type Transcript } from "../model/transcript.ts";
import type { ThreadHistory } from "../client/session.ts";
import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts";
import { blockFor } from "../model/transcript.ts";
import { colors, getMarkdownStyle, toneColor } from "./theme.ts";
/** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */
export function ThreadView(props: {
readonly project: string;
readonly title: string;
readonly subtitle: string;
readonly transcript: Transcript | null;
readonly detail: string;
readonly timeline: Timeline | null;
readonly history: ThreadHistory | null;
readonly loading: boolean;
readonly error?: string | undefined;
readonly working: boolean;
readonly expandWork: boolean;
readonly workspaceRoot: string | undefined;
readonly now: number;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
}) {
const { transcript } = props;
const last = transcript?.segments.at(-1);
// The folded work line already says it's working; otherwise show it at the bottom.
const showWorking = props.working && !(last?.kind === "work" && last.active) && !(last?.kind === "assistant" && last.streaming);
const { timeline, history } = props;
const pendingIds = new Set<string>(timeline?.pending.approvals.map((approval) => approval.requestId) ?? []);
return (
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
<box flexDirection="row" flexShrink={0} height={1}>
<text fg={colors.muted}>{props.project ? `${props.project} / ` : ""}</text>
<text fg={colors.text}>
<strong>{props.title}</strong>
</text>
<text fg={colors.faint}>{props.subtitle ? ` ${props.subtitle}` : ""}</text>
<box flexGrow={1} />
<text fg={colors.faint}>{props.detail}</text>
</box>
{props.error ? <text fg={colors.bad} flexShrink={0}>{props.error}</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom">
{props.loading && !transcript ? <text fg={colors.muted}>loading…</text> : null}
{transcript && transcript.hiddenCount > 0 ? <text fg={colors.faint}>{`… ${transcript.hiddenCount} earlier items`}</text> : null}
{transcript?.segments.map((segment) => <SegmentView key={segment.id} segment={segment} expandWork={props.expandWork} />)}
{showWorking ? <text fg={colors.accent} marginTop={1}>◐ working…</text> : null}
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
{history?.hasMore || history?.error ? <LoadEarlier history={history} /> : null}
{timeline?.rows.map((row) => (
<Row
key={row.id}
row={row}
pending={row.kind === "event" && pendingIds.has(eventRequestId(row) ?? "")}
workspaceRoot={props.workspaceRoot}
now={row.kind === "working" ? props.now : 0}
workStartedAt={timeline.workStartedAt}
/>
))}
</scrollbox>
</box>
);
}
/** Memoized: unchanged segments keep their object identity across updates, so only what changed re-renders. */
const SegmentView = memo(function SegmentView({ segment, expandWork }: { readonly segment: Segment; readonly expandWork: boolean }) {
switch (segment.kind) {
case "user": {
const { text, hidden } = expandWork ? { text: segment.text.trim(), hidden: 0 } : clip(segment.text.trim());
function LoadEarlier({ history }: { readonly history: ThreadHistory }) {
const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)";
return <Divider label={label} color={history.error ? colors.bad : colors.faint} />;
}
function Divider({ label, color }: { readonly label: string; readonly color: string }) {
return (
<box flexDirection="row" marginTop={1}>
<box flexGrow={1} border={["bottom"]} borderColor={colors.border} height={1} />
<text fg={color}>{` ${label} `}</text>
<box flexGrow={1} border={["bottom"]} borderColor={colors.border} height={1} />
</box>
);
}
/**
* Memoized: computeStableMessagesTimelineRows keeps unchanged rows identical,
* so a streamed update re-renders only its own rows. `now` is nonzero only for
* the working row, which ticks.
*/
const Row = memo(function Row(props: {
readonly row: MessagesTimelineRow;
readonly pending: boolean;
readonly workspaceRoot: string | undefined;
readonly now: number;
readonly workStartedAt: string | null;
}) {
const { row, workspaceRoot } = props;
switch (row.kind) {
case "message": {
const { message } = row;
if (message.role === "user") return <UserMessage text={message.text} />;
if (message.role === "system") return <text marginTop={1} fg={colors.muted}>{message.text}</text>;
return (
<box marginTop={1} border={["left"]} borderColor={colors.user} backgroundColor={colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column">
<text fg={colors.text}>{text}</text>
{hidden > 0 ? <text fg={colors.faint}>{`… ${hidden} more lines (e to expand)`}</text> : null}
<box marginTop={1}>
<markdown content={message.text || "…"} syntaxStyle={getMarkdownStyle()} streaming={message.streaming} conceal />
</box>
);
}
case "assistant":
case "turn-fold":
case "attempt-fold":
// The finished turn's work, folded: the web's turn separator.
return (
<box marginTop={1} paddingLeft={1}>
<markdown content={segment.markdown || "…"} syntaxStyle={getMarkdownStyle()} streaming={segment.streaming} conceal />
<box marginTop={1} border={["bottom"]} borderColor={colors.border} flexDirection="row">
<text fg={colors.muted}>{`${row.label} ${row.expanded ? "⌄" : "›"}`}</text>
</box>
);
case "work-toggle":
return (
<box marginTop={1} flexDirection="row">
<text fg={row.hasFailure ? colors.bad : colors.muted}>{`${SUMMARY_GLYPH[row.summaryKind] ?? "•"} ${row.summary} ${row.expanded ? "⌄" : "›"}`}</text>
</box>
);
case "work":
return expandWork ? <ExpandedWork steps={segment.steps} /> : <FoldedWork steps={segment.steps} active={segment.active} />;
case "approval":
return (
<box marginTop={1} border borderStyle="rounded" borderColor={segment.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={segment.pending ? colors.warn : colors.muted}>
<strong>{segment.pending ? "Needs approval" : "Approval"}</strong>
</text>
<text fg={colors.text}>{segment.title}</text>
{segment.detail ? <text fg={colors.muted}>{segment.detail}</text> : null}
{segment.pending ? <text fg={colors.faint}>esc, then y accept · Y accept for session · n decline</text> : null}
</box>
);
case "question":
return (
<box marginTop={1} border borderStyle="rounded" borderColor={segment.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={segment.pending ? colors.warn : colors.muted}>
<strong>{segment.pending ? "Question for you" : "Question"}</strong>
</text>
{segment.questions.map((question, index) => (
<text key={index} fg={colors.text}>{question}</text>
<box marginTop={row.continuesWorkLog ? 0 : 1} flexDirection="column">
{row.groupedEntries.map((entry) => (
<WorkEntry key={entry.id} entry={entry} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} />
))}
{segment.pending ? <text fg={colors.faint}>Answer this in the T3 Code app for now.</text> : null}
</box>
);
case "alert":
return <text marginTop={1} paddingLeft={1} fg={toneColor[segment.tone]}>{segment.text}</text>;
case "work-live":
return (
<box marginTop={1} flexDirection="column">
{row.thought?.detail ? <text fg={colors.faint}>{`∴ ${liveThoughtLine(row.thought.detail)}`}</text> : null}
<text fg={row.active ? colors.info : colors.muted}>{`${row.active ? "◐" : glyphFor(row.entry)} ${liveWorkEntryLabel(row.entry, workspaceRoot, row.active)}`}</text>
</box>
);
case "working": {
const since = props.workStartedAt ? Date.parse(props.workStartedAt) : NaN;
const verb = row.compacting ? "Compacting" : "Working";
return <text marginTop={1} fg={colors.info}>{Number.isFinite(since) ? `◐ ${verb} for ${formatWorkingDurationLabel(props.now - since)}` : `◐ ${verb}…`}</text>;
}
case "thinking":
return <text marginTop={1} fg={colors.faint}>∴ Thinking…</text>;
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":
return (
<box marginTop={1} border borderStyle="rounded" borderColor={colors.plan} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={colors.plan}>
<strong>Plan</strong>
</text>
<markdown content={row.proposedPlan.planMarkdown} syntaxStyle={getMarkdownStyle()} conceal />
</box>
);
case "event":
return <EventRow item={row.projectedItem.item} pending={props.pending} />;
case "worktree-setup":
return <text marginTop={1} fg={colors.info}>◐ Setting up worktree…</text>;
default:
// assistant-meta, html-render, mcp-app: nothing a terminal can show.
return null;
}
});
function FoldedWork({ steps, active }: { readonly steps: readonly Step[]; readonly active: boolean }) {
const latest = active ? steps.at(-1) : undefined;
const USER_FOLD_LINES = 8;
const USER_FOLD_CHARS = 600;
/** The web's user bubble: right-aligned, at most 80% wide, folded past 8 lines or 600 characters. */
function UserMessage({ text }: { readonly text: string }) {
const trimmed = text.trim();
const lines = trimmed.split("\n");
let shown = lines.slice(0, USER_FOLD_LINES).join("\n");
if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`;
const folded = shown.length < trimmed.length;
return (
<box marginTop={1} paddingLeft={1} flexDirection="column">
<text fg={active ? colors.accent : colors.faint}>{`${active ? "◐" : "▸"} ${summarizeWork(steps)}`}</text>
{latest ? <text fg={colors.muted}>{` ${stepLine(latest)}`}</text> : null}
<box marginTop={1} alignSelf="flex-end" maxWidth="80%" backgroundColor={colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column">
<text fg={colors.text}>{shown}</text>
{folded ? <text fg={colors.faint}>{`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`}</text> : null}
</box>
);
}
function ExpandedWork({ steps }: { readonly steps: readonly Step[] }) {
return (
<box marginTop={1} paddingLeft={1} flexDirection="column">
{steps.map((step) => (
<box key={step.id} flexDirection="column">
<text fg={step.kind === "reasoning" ? colors.faint : toneColor[step.tone]}>{stepLine(step)}</text>
{step.kind === "tool" && step.detail ? <text fg={colors.faint}>{indent(step.detail, " ")}</text> : null}
</box>
))}
</box>
);
function WorkEntry({ entry, label }: { readonly entry: WorkLogEntry; readonly label: string }) {
const failed = workEntryDisplayIndicatesToolFailure(entry);
const tone = failed || entry.tone === "error" ? colors.bad : entry.tone === "thinking" ? colors.faint : colors.muted;
return <text fg={tone}>{`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}`}</text>;
}
function stepLine(step: Step): string {
switch (step.kind) {
case "tool":
return `${step.icon} ${step.label}`;
case "reasoning":
return `∴ ${firstLine(step.text)}`;
function EventRow({ item, pending }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) {
if (item.type === "approval_request" && pending) {
return (
<box marginTop={1} border borderStyle="rounded" borderColor={colors.warn} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={colors.warn}>
<strong>{approvalTitle(item.requestKind)}</strong>
</text>
{item.prompt ? <text fg={colors.text}>{item.prompt}</text> : null}
{item.reason ? <text fg={colors.muted}>{item.reason}</text> : null}
<text fg={colors.faint}>Waiting for approval · y Approve · Y Always allow this session · n Decline</text>
</box>
);
}
const block = blockFor(item, new Set());
if (!block) return null;
switch (block.kind) {
case "notice":
return `· ${step.text}`;
return <text marginTop={1} fg={toneColor[block.tone]}>{block.text}</text>;
case "tool":
return <text marginTop={1} fg={toneColor[block.tone]}>{`${block.icon} ${block.label}`}</text>;
case "approval":
return <text marginTop={1} fg={colors.muted}>{`Approval requested: ${block.title}`}</text>;
case "question":
return <text marginTop={1} fg={colors.muted}>{block.pending ? "Input requested" : "Answered questions"}</text>;
default:
return null;
}
}
const CLIP_LINES = 6;
const CLIP_CHARS = 480;
function approvalTitle(kind: string): string {
if (kind.includes("command")) return "Command approval";
if (kind.includes("read")) return "File read approval";
if (kind.includes("file")) return "File change approval";
if (kind.includes("access")) return "App access approval";
if (kind.includes("permission")) return "App permission approval";
return "Approval";
}
/** Long prompts (delegation briefs, pasted logs) shrink to their opening lines. */
function clip(text: string): { readonly text: string; readonly hidden: number } {
const lines = text.split("\n");
let kept = lines.slice(0, CLIP_LINES).join("\n");
if (kept.length > CLIP_CHARS) kept = `${kept.slice(0, CLIP_CHARS).trimEnd()}…`;
const keptLines = kept.split("\n").length;
const hidden = lines.length - keptLines;
return kept.length < text.length ? { text: kept, hidden: Math.max(hidden, 1) } : { text, hidden: 0 };
function eventRequestId(row: Extract<MessagesTimelineRow, { kind: "event" }>): string | undefined {
const item = row.projectedItem.item;
return item.type === "approval_request" ? item.requestId : undefined;
}
/** Terminal stand-ins for the web's lucide icons. */
const SUMMARY_GLYPH: Partial<Record<ToolGroupSummaryKind, string>> = {
read: "◉",
edit: "✎",
command: "$",
"code-search": "⌕",
search: "⌕",
browser: "◍",
reasoning: "∴",
"thread-create": "↳",
"agent-tool": "↳",
"pull-request": "⇅",
"dynamic-tool": "⚙",
other: "⚙",
mixed: "•",
};
function glyphFor(entry: WorkLogEntry): string {
if (entry.tone === "thinking" || entry.itemType === "reasoning") return "∴";
if (entry.command) return "$";
if (entry.changedFiles?.length) return "✎";
if (entry.itemType === "subagent") return "↳";
if (entry.itemType === "file_search" || entry.itemType === "web_search") return "⌕";
if (entry.itemType === "todo_list") return "☐";
return "·";
}
function firstLine(text: string): string {
const line = (text.trim().split("\n")[0] ?? "").replace(/\*\*(.+?)\*\*/g, "$1");
return line.length > 120 ? `${line.slice(0, 117)}…` : line;
}
function indent(text: string, prefix: string): string {
return text
.split("\n")
.map((line) => prefix + line)
.join("\n");
const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ");
return line.length > 200 ? `${line.slice(0, 197)}…` : line;
}
+14
View File
@@ -1,5 +1,6 @@
import { SyntaxStyle } from "@opentui/core";
import type { StatusTone } from "../model/threads.ts";
import type { Tone } from "../model/transcript.ts";
export const colors = {
@@ -17,8 +18,21 @@ export const colors = {
bad: "#f7768e",
warn: "#e0af68",
selectedBg: "#283457",
/** The web app's sky / indigo / violet status hues. */
info: "#7dcfff",
input: "#bb9af7",
plan: "#c099ff",
} as const;
export const statusColor: Record<StatusTone, string> = {
info: colors.info,
muted: colors.muted,
warn: colors.warn,
input: colors.input,
bad: colors.bad,
good: colors.good,
};
export const toneColor: Record<Tone, string> = {
normal: colors.text,
muted: colors.muted,