Stable thread updates, folded work view, always-on composer

- Track selection by thread id and sort active threads by run start, so
  reordering no longer resubscribes and reloads the open thread
- Cache blocks per turn item, reuse unchanged segments, memoize views,
  and batch streamed updates to one redraw per frame
- Keep left threads subscribed for a minute so switching back is instant
- Fold runs of tool calls and reasoning into one summary line; clip long
  user messages; e expands both
- Always-visible multi-line composer with per-thread drafts and
  typing/navigation modes
This commit is contained in:
Callum Alpass committed 2026-11-02 17:06:06 +11:00
1 parent 3b7ed56e16
commit cea1409f40
9 files changed
+497 -209

No files matched your search

+22 -8
View File
@@ -21,19 +21,31 @@ tui3 list [--json] # print threads and exit
tui3 tmux [--watch] # mirror active threads into a tmux session, one window each tui3 tmux [--watch] # mirror active threads into a tmux session, one window each
``` ```
Dashboard keys: The message box is always at the bottom. tui3 has two modes: **typing**, where keys go to the message box, and **navigation**, where single keys act. `esc` switches to navigation; `i`, `enter` or `tab` switch back. Drafts are kept per thread.
Any mode:
| Key | Action | | Key | Action |
| --- | --- | | --- | --- |
| `j`/`k`, arrows | move in the list, or scroll the thread | | `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread |
| `enter`/`tab`, `esc` | switch between list and thread | | `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation |
| `/` | filter threads by title or project | | `ctrl+c` | quit |
| `i` | message the thread (queued after the current run) |
Typing: `enter` sends (queued after the current run if the thread is busy), `shift+enter` or `ctrl+j` adds a newline.
Navigation:
| Key | Action |
| --- | --- |
| `j`/`k`, arrows | next / previous thread (scroll, in `attach`) |
| `y` / `Y` / `n` | accept / accept for session / decline the pending approval | | `y` / `Y` / `n` | accept / accept for session / decline the pending approval |
| `e` | expand folded work and long messages |
| `/` | filter threads by title or project |
| `S` | stop the thread | | `S` | stop the thread |
| `r` | show full reasoning | | `g` / `G` | top / bottom of the conversation |
| `g` / `G` | top / bottom of the thread | | `q` | quit |
| `q`, `ctrl+c` | quit |
The conversation shows your messages and the agent's replies; each run of tool calls and reasoning between them folds into one summary line (`▸ 5 commands · 3 edits`), with the latest step shown while it's running.
Threads are grouped into **Needs you** (waiting on an approval), **Running**, and **Recent**. Threads are grouped into **Needs you** (waiting on an approval), **Running**, and **Recent**.
@@ -43,6 +55,8 @@ Threads are grouped into **Needs you** (waiting on an approval), **Running**, an
- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read` and `orchestration:operate`, and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `TUI3_TOKEN`. - On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read` and `orchestration:operate`, and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `TUI3_TOKEN`.
- It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`). - It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`).
Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots.
## Updating for a newer T3 Code ## Updating for a newer T3 Code
The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag: The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag:
+49 -9
View File
@@ -10,6 +10,8 @@ import {
type ThreadId, type ThreadId,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";
import { appendFileSync } from "node:fs";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit"; import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber"; import * as Fiber from "effect/Fiber";
@@ -38,6 +40,25 @@ export interface ThreadState {
type Listener<T> = (value: T) => void; type Listener<T> = (value: T) => void;
/** Streaming deltas arrive far faster than a terminal can usefully redraw. */
const THREAD_NOTIFY_MS = 33;
/** Threads you leave stay subscribed this long, so switching back is instant. */
const THREAD_LINGER_MS = 60_000;
const debugPath = process.env.TUI3_DEBUG;
/** Appends to the file named by TUI3_DEBUG; the TUI owns stdout and stderr. */
export function debugLog(message: string): void {
if (debugPath) appendFileSync(debugPath, `${new Date().toISOString()} ${message}\n`);
}
interface ThreadEntry {
state: ThreadState;
readonly listeners: Set<Listener<ThreadState>>;
fiber: Fiber.Fiber<unknown, unknown> | null;
notifyTimer: ReturnType<typeof setTimeout> | null;
lingerTimer: ReturnType<typeof setTimeout> | null;
}
/** /**
* One connection to T3 Code: a live shell (projects and threads) plus on-demand * One connection to T3 Code: a live shell (projects and threads) plus on-demand
* thread subscriptions, exposed as plain listeners for the UI. * thread subscriptions, exposed as plain listeners for the UI.
@@ -47,7 +68,7 @@ export class T3Session {
private connection: Connection | null = null; private connection: Connection | null = null;
private shell: ShellState = { status: { type: "connecting" }, snapshot: null, serverUrl: null }; private shell: ShellState = { status: { type: "connecting" }, snapshot: null, serverUrl: null };
private readonly shellListeners = new Set<Listener<ShellState>>(); private readonly shellListeners = new Set<Listener<ShellState>>();
private readonly threads = new Map<ThreadId, { state: ThreadState; listeners: Set<Listener<ThreadState>>; fiber: Fiber.Fiber<unknown, unknown> | null }>(); private readonly threads = new Map<ThreadId, ThreadEntry>();
async start(): Promise<void> { async start(): Promise<void> {
const scope = Effect.runSync(Scope.make()); const scope = Effect.runSync(Scope.make());
@@ -78,24 +99,33 @@ export class T3Session {
return () => this.shellListeners.delete(listener); return () => this.shellListeners.delete(listener);
} }
/** Subscribes to one thread's live projection; the stream stops when the last listener leaves. */ /**
* Subscribes to one thread's live projection. The stream outlives its last
* listener by THREAD_LINGER_MS, so flipping between threads doesn't reload them.
*/
watchThread(threadId: ThreadId, listener: Listener<ThreadState>): () => void { watchThread(threadId: ThreadId, listener: Listener<ThreadState>): () => void {
let entry = this.threads.get(threadId); let entry = this.threads.get(threadId);
if (!entry) { if (!entry) {
entry = { state: { status: "loading", projection: null }, listeners: new Set(), fiber: null }; entry = { state: { status: "loading", projection: null }, listeners: new Set(), fiber: null, notifyTimer: null, lingerTimer: null };
this.threads.set(threadId, entry); this.threads.set(threadId, entry);
entry.fiber = this.runInScope(this.threadStream(threadId)); entry.fiber = this.runInScope(this.threadStream(threadId));
debugLog(`subscribe ${threadId}`);
} }
if (entry.lingerTimer) clearTimeout(entry.lingerTimer);
entry.lingerTimer = null;
entry.listeners.add(listener); entry.listeners.add(listener);
listener(entry.state); listener(entry.state);
const watched = entry;
return () => { return () => {
const current = this.threads.get(threadId); watched.listeners.delete(listener);
if (!current) return; if (watched.listeners.size > 0) return;
current.listeners.delete(listener); watched.lingerTimer = setTimeout(() => {
if (current.listeners.size === 0) { if (watched.listeners.size > 0 || this.threads.get(threadId) !== watched) return;
this.threads.delete(threadId); this.threads.delete(threadId);
if (current.fiber) Effect.runFork(Fiber.interrupt(current.fiber)); debugLog(`unsubscribe ${threadId}`);
} if (watched.notifyTimer) clearTimeout(watched.notifyTimer);
if (watched.fiber) Effect.runFork(Fiber.interrupt(watched.fiber));
}, THREAD_LINGER_MS);
}; };
} }
@@ -172,6 +202,7 @@ export class T3Session {
this.setThread(threadId, { status: "live" }); this.setThread(threadId, { status: "live" });
return; return;
case "snapshot": case "snapshot":
debugLog(`snapshot ${threadId} items=${item.projection.visibleTurnItems.length}`);
this.setThread(threadId, { projection: item.projection }); this.setThread(threadId, { projection: item.projection });
return; return;
case "event": case "event":
@@ -202,11 +233,20 @@ export class T3Session {
for (const listener of this.shellListeners) listener(this.shell); for (const listener of this.shellListeners) listener(this.shell);
} }
/** Applies the patch now but tells listeners at most once per THREAD_NOTIFY_MS. */
private setThread(threadId: ThreadId, patch: Partial<ThreadState>): void { private setThread(threadId: ThreadId, patch: Partial<ThreadState>): void {
const entry = this.threads.get(threadId); const entry = this.threads.get(threadId);
if (!entry) return; if (!entry) return;
entry.state = { ...entry.state, ...patch }; entry.state = { ...entry.state, ...patch };
if (entry.notifyTimer) return;
// The first snapshot and status changes show at once; streamed events batch.
const immediate = patch.status !== undefined || entry.state.status === "loading";
const notify = () => {
entry.notifyTimer = null;
for (const listener of entry.listeners) listener(entry.state); for (const listener of entry.listeners) listener(entry.state);
};
if (immediate) notify();
else entry.notifyTimer = setTimeout(notify, THREAD_NOTIFY_MS);
} }
} }
+14 -1
View File
@@ -35,6 +35,19 @@ export function lastActivity(thread: OrchestrationV2ThreadShell): number {
return DateTime.toEpochMillis(thread.updatedAt); return DateTime.toEpochMillis(thread.updatedAt);
} }
const millis = (value: DateTime.Utc | null | undefined) => (value ? DateTime.toEpochMillis(value) : 0);
/**
* Sort key within a group. Active threads update every second while they
* stream, so they sort by something that holds still: when they started
* waiting on you, or when their run began.
*/
export function sortKey(thread: OrchestrationV2ThreadShell, group: ThreadGroup): number {
if (group === "needs-you") return millis(thread.pendingRuntimeRequest?.createdAt) || millis(thread.createdAt);
if (group === "running") return millis(thread.latestRunStartedAt) || millis(thread.latestRunRequestedAt) || millis(thread.createdAt);
return lastActivity(thread);
}
/** Threads in display order: the ones waiting on you, then running, then the most recent. */ /** Threads in display order: the ones waiting on you, then running, then the most recent. */
export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, options: { readonly recentLimit?: number; readonly query?: string } = {}): ThreadRow[] { export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, options: { readonly recentLimit?: number; readonly query?: string } = {}): ThreadRow[] {
if (!snapshot) return []; if (!snapshot) return [];
@@ -44,7 +57,7 @@ export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, option
const rows = snapshot.threads const rows = snapshot.threads
.map((thread) => ({ thread, group: groupOf(thread), projectName: projectLabel(projects.get(thread.projectId)) })) .map((thread) => ({ thread, group: groupOf(thread), projectName: projectLabel(projects.get(thread.projectId)) }))
.filter((row) => !query || row.thread.title.toLowerCase().includes(query) || row.projectName.toLowerCase().includes(query)) .filter((row) => !query || row.thread.title.toLowerCase().includes(query) || row.projectName.toLowerCase().includes(query))
.sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group) || lastActivity(b.thread) - lastActivity(a.thread)); .sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group) || sortKey(b.thread, b.group) - sortKey(a.thread, a.group) || a.thread.id.localeCompare(b.thread.id));
const limit = options.recentLimit ?? 60; const limit = options.recentLimit ?? 60;
let recent = 0; let recent = 0;
return rows.filter((row) => row.group !== "recent" || recent++ < limit); return rows.filter((row) => row.group !== "recent" || recent++ < limit);
+94 -12
View File
@@ -12,28 +12,110 @@ export type Block =
export type Tone = "normal" | "muted" | "good" | "bad" | "warn"; export type Tone = "normal" | "muted" | "good" | "bad" | "warn";
/** Tool calls, reasoning and minor notices: the agent's working, as opposed to what it says. */
export type Step = Extract<Block, { kind: "tool" | "reasoning" | "notice" }>;
/** What the conversation view renders: messages stand alone, runs of work fold into one segment. */
export type Segment =
| Extract<Block, { kind: "user" | "assistant" | "approval" | "question" }>
| { readonly kind: "work"; readonly id: string; readonly steps: readonly Step[]; readonly active: boolean }
| { readonly kind: "alert"; readonly id: string; readonly text: string; readonly tone: Tone };
export interface Transcript { export interface Transcript {
readonly blocks: readonly Block[]; readonly segments: readonly Segment[];
/** Turn items left out because only the tail is shown. */ /** Turn items left out because only the tail is shown. */
readonly hiddenCount: number; readonly hiddenCount: number;
readonly pendingRequestIds: ReadonlySet<string>;
} }
const OUTPUT_TAIL_LINES = 3; const OUTPUT_TAIL_LINES = 3;
export function buildTranscript(projection: OrchestrationV2ThreadProjection, options: { readonly tail?: number } = {}): Transcript { /** Blocks keyed by turn item object: the projection reducer keeps unchanged items identical. */
const pendingRequestIds = new Set(projection.runtimeRequests.filter((request) => request.status === "pending").map((request) => request.id as string)); const blockCache = new WeakMap<object, Block | null>();
const items = projection.visibleTurnItems;
const tail = options.tail ?? 150; function cachedBlock(item: OrchestrationV2TurnItem, pending: ReadonlySet<string>): Block | null {
const start = Math.max(0, items.length - tail); // Approval and question blocks depend on request state, not just the item.
const blocks: Block[] = []; if (item.type === "approval_request" || item.type === "user_input_request") return blockFor(item, pending);
for (const row of items.slice(start)) { let block = blockCache.get(item);
const block = blockFor(row.item, pendingRequestIds); if (block === undefined) {
if (block) blocks.push(block); block = blockFor(item, pending);
blockCache.set(item, block);
} }
return { blocks, hiddenCount: start, pendingRequestIds }; return block;
} }
export function buildTranscript(
projection: OrchestrationV2ThreadProjection,
options: { readonly tail?: number; readonly running?: boolean; readonly previous?: Transcript | null } = {},
): Transcript {
const pending = new Set(projection.runtimeRequests.filter((request) => request.status === "pending").map((request) => request.id as string));
const items = projection.visibleTurnItems;
const tail = options.tail ?? 200;
const start = Math.max(0, items.length - tail);
const segments: Segment[] = [];
let work: Step[] | null = null;
const flushWork = () => {
if (work && work.length > 0) segments.push({ kind: "work", id: `work-${work[0]!.id}`, steps: work, active: false });
work = null;
};
for (let index = start; index < items.length; index++) {
const block = cachedBlock(items[index]!.item, pending);
if (!block) continue;
if (block.kind === "tool" || block.kind === "reasoning" || (block.kind === "notice" && block.tone !== "bad" && block.tone !== "warn")) {
(work ??= []).push(block);
continue;
}
flushWork();
segments.push(block.kind === "notice" ? { kind: "alert", id: block.id, text: block.text, tone: block.tone } : block);
}
flushWork();
const last = segments.at(-1);
if (options.running && last?.kind === "work") segments[segments.length - 1] = { ...last, active: true };
return { segments: reuseUnchanged(segments, options.previous ?? null), hiddenCount: start };
}
/** Keeps the previous segment object when nothing in it changed, so memoized views skip it. */
function reuseUnchanged(segments: Segment[], previous: Transcript | null): Segment[] {
if (!previous) return segments;
const byId = new Map(previous.segments.map((segment) => [segment.id, segment]));
return segments.map((segment) => {
const old = byId.get(segment.id);
return old && sameSegment(old, segment) ? old : segment;
});
}
function sameSegment(a: Segment, b: Segment): boolean {
if (a === b) return true;
if (a.kind !== b.kind) return false;
if (a.kind === "work" && b.kind === "work") {
return a.active === b.active && a.steps.length === b.steps.length && a.steps.every((step, index) => step === b.steps[index]);
}
return shallowEqual(a as unknown as Record<string, unknown>, b as unknown as Record<string, unknown>);
}
function shallowEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
const keys = Object.keys(a);
return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]) || (Array.isArray(a[key]) && Array.isArray(b[key]) && shallowEqualArray(a[key] as unknown[], b[key] as unknown[])));
}
function shallowEqualArray(a: unknown[], b: unknown[]): boolean {
return a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
}
/** One line describing a folded run of work, e.g. "5 commands · 3 edits · 2 searches". */
export function summarizeWork(steps: readonly Step[]): string {
const counts = new Map<string, number>();
const bump = (label: string) => counts.set(label, (counts.get(label) ?? 0) + 1);
for (const step of steps) {
if (step.kind === "reasoning") continue;
if (step.kind === "notice") bump("update");
else bump(STEP_LABELS[step.icon] ?? "tool call");
}
const parts = [...counts].sort((a, b) => b[1] - a[1]).map(([label, count]) => `${count} ${count === 1 ? label : `${label}s`}`);
return parts.length > 0 ? parts.join(" · ") : "thinking";
}
const STEP_LABELS: Record<string, string> = { $: "command", "✎": "edit", "⌕": "search", "⚙": "tool call", "↳": "subagent", "☐": "plan update" };
export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet<string>): Block | null { export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet<string>): Block | null {
const id = item.id; const id = item.id;
switch (item.type) { switch (item.type) {
+171 -122
View File
@@ -1,58 +1,83 @@
import type { InputRenderable, ScrollBoxRenderable } from "@opentui/core"; import type { KeyEvent, ScrollBoxRenderable, TextareaRenderable } from "@opentui/core";
import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"; import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react";
import type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts"; import type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import type { ShellState, T3Session, ThreadState } from "../client/session.ts"; import type { ShellState, T3Session, ThreadState } from "../client/session.ts";
import { buildTranscript } from "../model/transcript.ts"; import { buildTranscript, type Transcript } from "../model/transcript.ts";
import { lastActivity, relativeTime, threadRows } from "../model/threads.ts"; import { isRunning, lastActivity, needsUser, relativeTime, threadRows } from "../model/threads.ts";
import { colors } from "./theme.ts"; import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx"; import { ThreadList } from "./ThreadList.tsx";
import { ThreadView } from "./ThreadView.tsx"; import { ThreadView } from "./ThreadView.tsx";
type Focus = "list" | "thread" | "composer" | "filter"; /** "input": typing goes to the composer. "nav": single keys move, scroll, approve. */
type Mode = "input" | "nav" | "filter";
/** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120;
const MAX_COMPOSER_LINES = 6;
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;
export function App(props: { readonly session: T3Session; readonly attachThreadId?: ThreadId }) { export function App(props: { readonly session: T3Session; readonly attachThreadId?: ThreadId }) {
const { session, attachThreadId } = props; const { session, attachThreadId } = props;
const renderer = useRenderer(); const renderer = useRenderer();
const { width, height } = useTerminalDimensions(); const { width, height } = useTerminalDimensions();
const [shell, setShell] = useState<ShellState>(session.getShell()); const [shell, setShell] = useState<ShellState>(session.getShell());
const [selected, setSelected] = useState(0); const [selectedId, setSelectedId] = useState<ThreadId | undefined>(attachThreadId);
const [focus, setFocus] = useState<Focus>(attachThreadId ? "thread" : "list"); const [mode, setMode] = useState<Mode>(attachThreadId ? "input" : "nav");
const [filter, setFilter] = useState(""); const [filter, setFilter] = useState("");
const [showReasoning, setShowReasoning] = useState(false); const [expandWork, setExpandWork] = useState(false);
const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null); const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null);
const [draft, setDraft] = useState(""); const [composerLines, setComposerLines] = useState(1);
const scrollRef = useRef<ScrollBoxRenderable | null>(null); const scrollRef = useRef<ScrollBoxRenderable | null>(null);
const composerRef = useRef<InputRenderable | null>(null); const composerRef = useRef<TextareaRenderable | null>(null);
const drafts = useRef(new Map<string, string>());
useEffect(() => session.onShell(setShell), [session]); useEffect(() => session.onShell(setShell), [session]);
const rows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]); const rows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]);
const selectedRow = rows[Math.min(selected, rows.length - 1)]; // Selection is a thread id, not an index, so the list can reorder underneath it.
const threadId = attachThreadId ?? selectedRow?.thread.id; 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 threadShell = 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);
}, [selectedId, rows]);
const move = (delta: number) => {
const next = rows[Math.min(rows.length - 1, Math.max(0, selectedIndex + delta))];
if (next) setSelectedId(next.thread.id);
};
// Keep the selection on the same thread when the list reorders under it. const [watchedId, setWatchedId] = useState(threadId);
const selectedIdRef = useRef<string | undefined>(undefined);
useEffect(() => { useEffect(() => {
const id = selectedIdRef.current; if (threadId === watchedId) return;
if (!id) return; const timer = setTimeout(() => setWatchedId(threadId), SUBSCRIBE_DELAY_MS);
const index = rows.findIndex((row) => row.thread.id === id); return () => clearTimeout(timer);
if (index >= 0 && index !== selected) setSelected(index); }, [threadId, watchedId]);
}, [rows]);
useEffect(() => {
selectedIdRef.current = rows[selected]?.thread.id;
}, [selected, rows]);
const [thread, setThread] = useState<ThreadState | null>(null); const [thread, setThread] = useState<ThreadState | null>(null);
useEffect(() => { useEffect(() => {
setThread(null); setThread(null);
if (!threadId || shell.status.type === "error" || !shell.serverUrl) return; if (!watchedId || !shell.serverUrl) return;
return session.watchThread(threadId, setThread); return session.watchThread(watchedId, setThread);
}, [session, threadId, shell.serverUrl]); }, [session, watchedId, shell.serverUrl]);
const transcript = useMemo(() => (thread?.projection ? buildTranscript(thread.projection) : null), [thread?.projection]); const running = threadShell ? isRunning(threadShell) && !needsUser(threadShell) : false;
const previousTranscript = useRef<{ id: string; transcript: Transcript } | null>(null);
const transcript = 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 };
return next;
}, [thread?.projection, watchedId, running]);
const pendingRequest = thread?.projection?.runtimeRequests.findLast((request) => request.status === "pending" && request.kind !== "user_input"); const pendingRequest = thread?.projection?.runtimeRequests.findLast((request) => request.status === "pending" && request.kind !== "user_input");
const say = (text: string, bad = false) => { const say = (text: string, bad = false) => {
@@ -65,76 +90,21 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
(error) => say(`${label} failed: ${error instanceof Error ? error.message : String(error)}`, true), (error) => say(`${label} failed: ${error instanceof Error ? error.message : String(error)}`, true),
); );
}; };
const respond = (decision: ProviderApprovalDecision) => { const respond = (decision: ProviderApprovalDecision) => {
if (!threadId || !pendingRequest) return say("Nothing is waiting for approval.", true); if (!threadId || !pendingRequest) return say("Nothing is waiting for approval.", true);
run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingRequest.id, decision)); run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingRequest.id, decision));
}; };
const submitDraft = (value: string) => { const submit = () => {
const text = value.trim(); const composer = composerRef.current;
if (!text || !threadId) return; const text = composer?.plainText.trim() ?? "";
setDraft(""); if (!composer || !text || !threadId) return;
if (composerRef.current) composerRef.current.value = ""; composer.setText("");
setFocus("thread"); drafts.current.delete(threadId);
run("Sent", () => session.sendMessage(threadId, text)); setComposerLines(1);
run(running ? "Queued for after the current run" : "Sent", () => session.sendMessage(threadId, text));
}; };
useKeyboard((key) => {
if (key.ctrl && key.name === "c") return quit();
if (focus === "composer" || focus === "filter") {
if (key.name === "escape") setFocus(attachThreadId ? "thread" : focus === "filter" ? "list" : "thread");
return;
}
const scroll = scrollRef.current;
switch (key.name) {
case "q":
return quit();
case "j":
case "down":
if (focus === "list") return setSelected((index) => Math.min(index + 1, rows.length - 1));
return scroll?.scrollBy(1);
case "k":
case "up":
if (focus === "list") return setSelected((index) => Math.max(index - 1, 0));
return scroll?.scrollBy(-1);
case "pagedown":
return scroll?.scrollBy(Math.max(1, height - 8));
case "pageup":
return scroll?.scrollBy(-Math.max(1, height - 8));
case "g":
if (key.shift) return scroll?.scrollTo(scroll.scrollHeight);
return scroll?.scrollTo(0);
case "return":
case "tab":
case "l":
case "right":
if (!attachThreadId) setFocus(focus === "list" ? "thread" : "list");
return;
case "h":
case "left":
case "escape":
if (!attachThreadId) setFocus("list");
return;
case "i":
case "m":
if (threadId) setFocus("composer");
return;
case "/":
if (!attachThreadId) setFocus("filter");
return;
case "r":
return setShowReasoning((value) => !value);
case "y":
return respond(key.shift ? "acceptForSession" : "accept");
case "n":
return respond("decline");
case "s":
if (threadId && key.shift) run("Stop requested", () => session.stopThread(threadId));
return;
}
});
const quit = () => { const quit = () => {
void session.stop().finally(() => { void session.stop().finally(() => {
renderer.destroy(); renderer.destroy();
@@ -142,22 +112,75 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
}); });
}; };
const scrollPage = (direction: 1 | -1) => scrollRef.current?.scrollBy(direction * Math.max(1, height - 10));
/** Keys that work in every mode. Returns true when handled. */
const globalKey = (key: KeyEvent): boolean => {
if (key.ctrl && key.name === "c") return quit(), true;
if (key.name === "pagedown" || (key.ctrl && key.name === "d")) return scrollPage(1), true;
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;
return false;
};
useKeyboard((key) => {
if (globalKey(key)) return key.preventDefault();
if (mode === "input" || mode === "filter") {
if (key.name === "escape") {
setMode("nav");
key.preventDefault();
}
return;
}
const scroll = scrollRef.current;
switch (key.name) {
case "q":
return quit();
case "j":
case "down":
return attachThreadId ? scroll?.scrollBy(1) : move(1);
case "k":
case "up":
return attachThreadId ? scroll?.scrollBy(-1) : move(-1);
case "g":
return key.shift ? scroll?.scrollTo(scroll.scrollHeight) : scroll?.scrollTo(0);
case "e":
return setExpandWork((value) => !value);
case "y":
return respond(key.shift ? "acceptForSession" : "accept");
case "n":
return respond("decline");
case "s":
if (threadId && key.shift) run("Stop requested", () => session.stopThread(threadId));
return;
case "/":
if (!attachThreadId) setMode("filter");
return key.preventDefault();
case "i":
case "return":
case "tab":
if (threadId) setMode("input");
return key.preventDefault();
}
});
const counts = useMemo(() => { const counts = useMemo(() => {
let needs = 0; let needs = 0;
let running = 0; let active = 0;
for (const row of threadRows(shell.snapshot, { recentLimit: 0 })) { for (const row of threadRows(shell.snapshot, { recentLimit: 0 })) {
if (row.group === "needs-you") needs++; if (row.group === "needs-you") needs++;
else if (row.group === "running") running++; else if (row.group === "running") active++;
} }
return { needs, running }; return { needs, active };
}, [shell.snapshot]); }, [shell.snapshot]);
const status = const status = shell.status.type === "error" ? `error: ${shell.status.message}` : shell.status.type === "connecting" ? "connecting…" : (shell.serverUrl ?? "");
shell.status.type === "error" ? `error: ${shell.status.message}` : shell.status.type === "connecting" ? "connecting…" : shell.serverUrl ?? ""; const listWidth = attachThreadId ? 0 : Math.min(46, Math.max(28, Math.floor(width * 0.3)));
const listWidth = attachThreadId ? 0 : Math.min(48, Math.max(28, Math.floor(width * 0.32)));
const subtitle = threadShell const subtitle = threadShell
? [threadShell.status, threadShell.modelSelection.model, threadShell.branch, relativeTime(lastActivity(threadShell))].filter(Boolean).join(" · ") ? [threadShell.modelSelection.model === "default" ? "" : threadShell.modelSelection.model, threadShell.branch, relativeTime(lastActivity(threadShell))].filter(Boolean).join(" · ")
: ""; : "";
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2;
return ( return (
<box flexDirection="column" width={width} height={height} backgroundColor={colors.bg}> <box flexDirection="column" width={width} height={height} backgroundColor={colors.bg}>
@@ -165,58 +188,84 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
<text fg={colors.accent}> <text fg={colors.accent}>
<strong>tui3</strong> <strong>tui3</strong>
</text> </text>
<text fg={colors.muted}>{` ${status}`}</text> <text fg={colors.faint}>{` ${status}`}</text>
<box flexGrow={1} /> <box flexGrow={1} />
{counts.needs > 0 ? <text fg={colors.warn}>{`● ${counts.needs} need you `}</text> : null} {counts.needs > 0 ? <text fg={colors.warn}>{`● ${counts.needs} need you `}</text> : null}
<text fg={colors.accent}>{`◐ ${counts.running} running`}</text> <text fg={colors.muted}>{`◐ ${counts.active} running`}</text>
</box> </box>
<box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden"> <box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden">
{attachThreadId ? null : <ThreadList rows={rows} selected={selected} focused={focus === "list"} width={listWidth} height={height - 4} filter={filter} />} {attachThreadId ? null : <ThreadList rows={rows} selected={selectedIndex} focused={mode === "nav"} width={listWidth} height={height - 2} filter={filter} />}
<box flexDirection="column" flexGrow={1} minHeight={0}> <box flexDirection="column" flexGrow={1} minHeight={0}>
{threadId ? ( {threadId ? (
<ThreadView <ThreadView
title={threadShell?.title ?? "thread"} title={threadShell?.title ?? "thread"}
subtitle={subtitle} subtitle={subtitle}
transcript={transcript} transcript={watchedId === threadId ? transcript : null}
loading={thread?.status === "loading"} loading={watchedId !== threadId || thread?.status === "loading"}
error={thread?.error} error={thread?.error}
focused={focus === "thread"} working={running}
showReasoning={showReasoning} expandWork={expandWork}
scrollRef={scrollRef} scrollRef={scrollRef}
/> />
) : ( ) : (
<box border borderColor={colors.border} flexGrow={1}> <box flexGrow={1} paddingLeft={2} paddingTop={1}>
<text fg={colors.muted}>{shell.snapshot ? "Select a thread." : "Waiting for threads…"}</text> <text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
</box> </box>
)} )}
{focus === "composer" ? ( {mode === "filter" ? (
<box title=" message (enter to send, esc to cancel) " border borderColor={colors.borderFocused} height={3} flexShrink={0}> <box title=" filter " border borderStyle="rounded" borderColor={colors.borderFocused} height={3} flexShrink={0} marginLeft={1} marginRight={1}>
<input ref={composerRef} focused placeholder="Queue a message for this thread…" value={draft} onInput={setDraft} onSubmit={(value: unknown) => submitDraft(typeof value === "string" ? value : draft)} /> <input focused placeholder="title or project…" value={filter} onInput={(value: string) => setFilter(value)} onSubmit={() => setMode("nav")} />
</box> </box>
) : null} ) : threadId ? (
{focus === "filter" ? ( <box
<box title=" filter threads (esc to close) " border borderColor={colors.borderFocused} height={3} flexShrink={0}> border
<input focused placeholder="title or project…" value={filter} onInput={(value: string) => { setFilter(value); setSelected(0); }} onSubmit={() => setFocus("list")} /> borderStyle="rounded"
borderColor={mode === "input" ? colors.borderFocused : colors.border}
height={composerHeight}
flexShrink={0}
marginLeft={1}
marginRight={1}
paddingLeft={1}
paddingRight={1}
>
<textarea
key={threadId}
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"}
placeholderColor={colors.faint}
textColor={colors.text}
keyBindings={[...COMPOSER_KEYS]}
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));
}}
/>
</box> </box>
) : null} ) : null}
</box> </box>
</box> </box>
<box flexDirection="row" paddingLeft={1} height={1} flexShrink={0}> <box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
{flash ? ( {flash ? <text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text> : <text fg={colors.faint}>{hints(mode, Boolean(pendingRequest), Boolean(attachThreadId))}</text>}
<text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text>
) : (
<text fg={colors.faint}>{hints(focus, Boolean(pendingRequest), Boolean(attachThreadId))}</text>
)}
</box> </box>
</box> </box>
); );
} }
function hints(focus: Focus, pending: boolean, attached: boolean): string { function hints(mode: Mode, pending: boolean, attached: boolean): string {
if (focus === "composer" || focus === "filter") return "enter submit · esc cancel"; if (mode === "filter") return "enter done · esc close";
const parts = attached ? ["j/k scroll", "g/G top/bottom"] : focus === "list" ? ["j/k move", "enter open", "/ filter"] : ["j/k scroll", "esc list", "g/G top/bottom"]; if (mode === "input") {
parts.push("i message", "r reasoning", "S stop"); 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");
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"); if (pending) parts.unshift("y accept · Y session · n decline");
parts.push("q quit");
return parts.join(" · "); return parts.join(" · ");
} }
+4 -4
View File
@@ -18,7 +18,7 @@ function glyphFor(row: ThreadRow) {
export function ThreadList(props: { readonly rows: readonly ThreadRow[]; readonly selected: number; readonly focused: boolean; readonly width: number; readonly height: number; readonly filter: string }) { 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; 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. // 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 - 2 - 3) / 2)); const visibleCount = Math.max(1, Math.floor((height - 3) / 2));
const start = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), rows.length - visibleCount)); const start = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), rows.length - visibleCount));
const windowRows = rows.slice(start, start + visibleCount); const windowRows = rows.slice(start, start + visibleCount);
const titleWidth = Math.max(8, width - 12); const titleWidth = Math.max(8, width - 12);
@@ -50,15 +50,15 @@ export function ThreadList(props: { readonly rows: readonly ThreadRow[]; readonl
}); });
return ( return (
<box <box
title={props.filter ? ` threads /${props.filter} ` : " threads "} border={["right"]}
border borderColor={colors.border}
borderColor={focused ? colors.borderFocused : colors.border}
width={width} width={width}
flexShrink={0} flexShrink={0}
overflow="hidden" overflow="hidden"
flexDirection="column" flexDirection="column"
paddingLeft={0} paddingLeft={0}
> >
{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}> no threads</text> : lines}
</box> </box>
); );
+93 -53
View File
@@ -1,7 +1,7 @@
import type { ScrollBoxRenderable } from "@opentui/core"; import type { ScrollBoxRenderable } from "@opentui/core";
import { useMemo, type RefObject } from "react"; import { memo, type RefObject } from "react";
import type { Block, Transcript } from "../model/transcript.ts"; import { summarizeWork, type Segment, type Step, type Transcript } from "../model/transcript.ts";
import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts";
export function ThreadView(props: { export function ThreadView(props: {
@@ -10,86 +10,126 @@ export function ThreadView(props: {
readonly transcript: Transcript | null; readonly transcript: Transcript | null;
readonly loading: boolean; readonly loading: boolean;
readonly error?: string | undefined; readonly error?: string | undefined;
readonly focused: boolean; readonly working: boolean;
readonly showReasoning: boolean; readonly expandWork: boolean;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
}) { }) {
const { transcript } = props; const { transcript } = props;
const body = useMemo(() => { const last = transcript?.segments.at(-1);
if (!transcript) return null; // The folded work line already says it's working; otherwise show it at the bottom.
return transcript.blocks.map((block) => <BlockView key={block.id} block={block} showReasoning={props.showReasoning} />); const showWorking = props.working && !(last?.kind === "work" && last.active) && !(last?.kind === "assistant" && last.streaming);
}, [transcript, props.showReasoning]);
return ( return (
<box title={` ${props.title} `} border borderColor={props.focused ? colors.borderFocused : colors.border} flexGrow={1} minHeight={0} flexDirection="column"> <box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={colors.faint} flexShrink={0} height={1}>{props.subtitle}</text> <box flexDirection="row" flexShrink={0} height={1}>
{props.error ? <text fg={colors.bad}>{props.error}</text> : null} <text fg={colors.text}>
<strong>{props.title}</strong>
</text>
<text fg={colors.faint}>{props.subtitle ? ` ${props.subtitle}` : ""}</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} {props.loading && !transcript ? <text fg={colors.muted}>loading…</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom" focused={props.focused}> {transcript && transcript.hiddenCount > 0 ? <text fg={colors.faint}>{`… ${transcript.hiddenCount} earlier items`}</text> : null}
{transcript && transcript.hiddenCount > 0 ? <text fg={colors.faint}>{`… ${transcript.hiddenCount} earlier items not shown`}</text> : null} {transcript?.segments.map((segment) => <SegmentView key={segment.id} segment={segment} expandWork={props.expandWork} />)}
{body} {showWorking ? <text fg={colors.accent} marginTop={1}>◐ working…</text> : null}
</scrollbox> </scrollbox>
</box> </box>
); );
} }
function BlockView({ block, showReasoning }: { readonly block: Block; readonly showReasoning: boolean }) { /** Memoized: unchanged segments keep their object identity across updates, so only what changed re-renders. */
switch (block.kind) { const SegmentView = memo(function SegmentView({ segment, expandWork }: { readonly segment: Segment; readonly expandWork: boolean }) {
case "user": switch (segment.kind) {
case "user": {
const { text, hidden } = expandWork ? { text: segment.text.trim(), hidden: 0 } : clip(segment.text.trim());
return ( return (
<box marginTop={1} flexDirection="row"> <box marginTop={1} border={["left"]} borderColor={colors.user} backgroundColor={colors.userBg} paddingLeft={1} paddingRight={1} flexDirection="column">
<text fg={colors.user}>› </text> <text fg={colors.text}>{text}</text>
<text fg={colors.user}> {hidden > 0 ? <text fg={colors.faint}>{`… ${hidden} more lines (e to expand)`}</text> : null}
<strong>{block.text.trim()}</strong>
</text>
</box> </box>
); );
}
case "assistant": case "assistant":
return ( return (
<box marginTop={1}> <box marginTop={1} paddingLeft={1}>
<markdown content={block.markdown || "…"} syntaxStyle={getMarkdownStyle()} streaming={block.streaming} conceal /> <markdown content={segment.markdown || "…"} syntaxStyle={getMarkdownStyle()} streaming={segment.streaming} conceal />
</box>
);
case "reasoning":
if (!showReasoning) return <text fg={colors.faint}>{` ∴ ${firstLine(block.text)}`}</text>;
return (
<text fg={colors.faint}>
<i>{block.text.trim()}</i>
</text>
);
case "tool":
return (
<box flexDirection="column">
<text fg={toneColor[block.tone]}>{` ${block.icon} ${block.label}`}</text>
{block.detail ? <text fg={colors.faint}>{indent(block.detail, " ")}</text> : null}
</box> </box>
); );
case "work":
return expandWork ? <ExpandedWork steps={segment.steps} /> : <FoldedWork steps={segment.steps} active={segment.active} />;
case "approval": case "approval":
return ( return (
<box marginTop={1} border borderColor={block.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1}> <box marginTop={1} border borderStyle="rounded" borderColor={segment.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={block.pending ? colors.warn : colors.muted}> <text fg={segment.pending ? colors.warn : colors.muted}>
<strong>{block.pending ? "Approval needed: " : "Approval: "}</strong> <strong>{segment.pending ? "Needs approval" : "Approval"}</strong>
{block.title}
</text> </text>
{block.detail ? <text fg={colors.muted}>{block.detail}</text> : null} <text fg={colors.text}>{segment.title}</text>
{block.pending ? <text fg={colors.text}>[y] accept [Y] accept for session [n] decline</text> : null} {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> </box>
); );
case "question": case "question":
return ( return (
<box marginTop={1} border borderColor={block.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1}> <box marginTop={1} border borderStyle="rounded" borderColor={segment.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1} paddingRight={1}>
<text fg={block.pending ? colors.warn : colors.muted}> <text fg={segment.pending ? colors.warn : colors.muted}>
<strong>{block.pending ? "Question for you" : "Question"}</strong> <strong>{segment.pending ? "Question for you" : "Question"}</strong>
</text> </text>
{block.questions.map((question, index) => ( {segment.questions.map((question, index) => (
<text key={index} fg={colors.text}>{`• ${question}`}</text> <text key={index} fg={colors.text}>{question}</text>
))} ))}
{block.pending ? <text fg={colors.muted}>Answer in the T3 Code app for now.</text> : null} {segment.pending ? <text fg={colors.faint}>Answer this in the T3 Code app for now.</text> : null}
</box> </box>
); );
case "notice": case "alert":
return <text fg={toneColor[block.tone]}>{` ${block.text}`}</text>; return <text marginTop={1} paddingLeft={1} fg={toneColor[segment.tone]}>{segment.text}</text>;
} }
});
function FoldedWork({ steps, active }: { readonly steps: readonly Step[]; readonly active: boolean }) {
const latest = active ? steps.at(-1) : undefined;
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>
);
}
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 stepLine(step: Step): string {
switch (step.kind) {
case "tool":
return `${step.icon} ${step.label}`;
case "reasoning":
return `∴ ${firstLine(step.text)}`;
case "notice":
return `· ${step.text}`;
}
}
const CLIP_LINES = 6;
const CLIP_CHARS = 480;
/** 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 firstLine(text: string): string { function firstLine(text: string): string {
+1
View File
@@ -12,6 +12,7 @@ export const colors = {
faint: "#545c7e", faint: "#545c7e",
accent: "#7aa2f7", accent: "#7aa2f7",
user: "#7dcfff", user: "#7dcfff",
userBg: "#1f2335",
good: "#9ece6a", good: "#9ece6a",
bad: "#f7768e", bad: "#f7768e",
warn: "#e0af68", warn: "#e0af68",
+49
View File
@@ -27,3 +27,52 @@ describe("blockFor", () => {
expect(blockFor(item({ type: "checkpoint" }), new Set())).toBeNull(); expect(blockFor(item({ type: "checkpoint" }), new Set())).toBeNull();
}); });
}); });
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import { buildTranscript, summarizeWork } from "../src/model/transcript.ts";
const projectionOf = (items: OrchestrationV2TurnItem[], pendingIds: string[] = []) =>
({
runtimeRequests: pendingIds.map((id) => ({ id, status: "pending" })),
visibleTurnItems: items.map((entry, position) => ({ position, item: entry })),
}) as unknown as OrchestrationV2ThreadProjection;
let counter = 0;
const turn = (fields: Record<string, unknown>) => item({ id: `i${counter++}`, ...fields });
describe("buildTranscript", () => {
test("folds runs of work between messages into one segment", () => {
const transcript = buildTranscript(
projectionOf([
turn({ type: "user_message", text: "fix it" }),
turn({ type: "command_execution", input: "ls" }),
turn({ type: "reasoning", text: "thinking", streaming: false }),
turn({ type: "file_change", fileName: "a.ts" }),
turn({ type: "assistant_message", text: "done", streaming: false }),
]),
);
expect(transcript.segments.map((segment) => segment.kind)).toEqual(["user", "work", "assistant"]);
const work = transcript.segments[1];
expect(work?.kind === "work" && summarizeWork(work.steps)).toBe("1 command · 1 edit");
});
test("marks trailing work active while the thread runs", () => {
const transcript = buildTranscript(projectionOf([turn({ type: "command_execution", input: "make" })]), { running: true });
expect(transcript.segments[0]).toMatchObject({ kind: "work", active: true });
});
test("errors break out of folded work", () => {
const transcript = buildTranscript(projectionOf([turn({ type: "command_execution", input: "a" }), turn({ type: "error", failure: { message: "boom" } }), turn({ type: "command_execution", input: "b" })]));
expect(transcript.segments.map((segment) => segment.kind)).toEqual(["work", "alert", "work"]);
});
test("reuses unchanged segments so the view can skip them", () => {
const user = turn({ type: "user_message", text: "hi" });
const command = turn({ type: "command_execution", input: "ls" });
const first = buildTranscript(projectionOf([user, command, turn({ type: "assistant_message", text: "He", streaming: true })]));
const second = buildTranscript(projectionOf([user, command, turn({ type: "assistant_message", text: "Hello", streaming: true })]), { previous: first });
expect(second.segments[0]).toBe(first.segments[0]!);
expect(second.segments[1]).toBe(first.segments[1]!);
expect(second.segments[2]).not.toBe(first.segments[2]!);
});
});