From cea1409f4012811a5b3d459305d7f8f4dcc63224 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 17:06:06 +1100 Subject: [PATCH] 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 --- README.md | 30 ++-- src/client/session.ts | 60 ++++++-- src/model/threads.ts | 15 +- src/model/transcript.ts | 106 +++++++++++++-- src/ui/App.tsx | 295 +++++++++++++++++++++++----------------- src/ui/ThreadList.tsx | 8 +- src/ui/ThreadView.tsx | 148 ++++++++++++-------- src/ui/theme.ts | 1 + test/transcript.test.ts | 49 +++++++ 9 files changed, 500 insertions(+), 212 deletions(-) diff --git a/README.md b/README.md index 091be48..828b10c 100644 --- a/README.md +++ b/README.md @@ -21,19 +21,31 @@ tui3 list [--json] # print threads and exit 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 | | --- | --- | -| `j`/`k`, arrows | move in the list, or scroll the thread | -| `enter`/`tab`, `esc` | switch between list and thread | -| `/` | filter threads by title or project | -| `i` | message the thread (queued after the current run) | +| `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread | +| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation | +| `ctrl+c` | quit | + +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 | +| `e` | expand folded work and long messages | +| `/` | filter threads by title or project | | `S` | stop the thread | -| `r` | show full reasoning | -| `g` / `G` | top / bottom of the thread | -| `q`, `ctrl+c` | quit | +| `g` / `G` | top / bottom of the conversation | +| `q` | 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**. @@ -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`. - 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 The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag: diff --git a/src/client/session.ts b/src/client/session.ts index ae0efaa..9d51994 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -10,6 +10,8 @@ import { type ThreadId, } from "@t3tools/contracts"; import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; +import { appendFileSync } from "node:fs"; + import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -38,6 +40,25 @@ export interface ThreadState { type Listener = (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>; + fiber: Fiber.Fiber | null; + notifyTimer: ReturnType | null; + lingerTimer: ReturnType | null; +} + /** * One connection to T3 Code: a live shell (projects and threads) plus on-demand * thread subscriptions, exposed as plain listeners for the UI. @@ -47,7 +68,7 @@ export class T3Session { private connection: Connection | null = null; private shell: ShellState = { status: { type: "connecting" }, snapshot: null, serverUrl: null }; private readonly shellListeners = new Set>(); - private readonly threads = new Map>; fiber: Fiber.Fiber | null }>(); + private readonly threads = new Map(); async start(): Promise { const scope = Effect.runSync(Scope.make()); @@ -78,24 +99,33 @@ export class T3Session { 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): () => void { let entry = this.threads.get(threadId); 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); entry.fiber = this.runInScope(this.threadStream(threadId)); + debugLog(`subscribe ${threadId}`); } + if (entry.lingerTimer) clearTimeout(entry.lingerTimer); + entry.lingerTimer = null; entry.listeners.add(listener); listener(entry.state); + const watched = entry; return () => { - const current = this.threads.get(threadId); - if (!current) return; - current.listeners.delete(listener); - if (current.listeners.size === 0) { + watched.listeners.delete(listener); + if (watched.listeners.size > 0) return; + watched.lingerTimer = setTimeout(() => { + if (watched.listeners.size > 0 || this.threads.get(threadId) !== watched) return; 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" }); return; case "snapshot": + debugLog(`snapshot ${threadId} items=${item.projection.visibleTurnItems.length}`); this.setThread(threadId, { projection: item.projection }); return; case "event": @@ -202,11 +233,20 @@ export class T3Session { 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): void { const entry = this.threads.get(threadId); if (!entry) return; entry.state = { ...entry.state, ...patch }; - for (const listener of entry.listeners) listener(entry.state); + 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); + }; + if (immediate) notify(); + else entry.notifyTimer = setTimeout(notify, THREAD_NOTIFY_MS); } } diff --git a/src/model/threads.ts b/src/model/threads.ts index 0f68b5c..bc0e8a7 100644 --- a/src/model/threads.ts +++ b/src/model/threads.ts @@ -35,6 +35,19 @@ export function lastActivity(thread: OrchestrationV2ThreadShell): number { 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. */ export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, options: { readonly recentLimit?: number; readonly query?: string } = {}): ThreadRow[] { if (!snapshot) return []; @@ -44,7 +57,7 @@ export function threadRows(snapshot: OrchestrationV2ShellSnapshot | null, option const rows = snapshot.threads .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)) - .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; let recent = 0; return rows.filter((row) => row.group !== "recent" || recent++ < limit); diff --git a/src/model/transcript.ts b/src/model/transcript.ts index 8092595..e31f6b6 100644 --- a/src/model/transcript.ts +++ b/src/model/transcript.ts @@ -12,28 +12,110 @@ export type Block = 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; + +/** What the conversation view renders: messages stand alone, runs of work fold into one segment. */ +export type Segment = + | Extract + | { 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 { - readonly blocks: readonly Block[]; + readonly segments: readonly Segment[]; /** Turn items left out because only the tail is shown. */ readonly hiddenCount: number; - readonly pendingRequestIds: ReadonlySet; } const OUTPUT_TAIL_LINES = 3; -export function buildTranscript(projection: OrchestrationV2ThreadProjection, options: { readonly tail?: number } = {}): Transcript { - const pendingRequestIds = new Set(projection.runtimeRequests.filter((request) => request.status === "pending").map((request) => request.id as string)); - const items = projection.visibleTurnItems; - const tail = options.tail ?? 150; - const start = Math.max(0, items.length - tail); - const blocks: Block[] = []; - for (const row of items.slice(start)) { - const block = blockFor(row.item, pendingRequestIds); - if (block) blocks.push(block); +/** Blocks keyed by turn item object: the projection reducer keeps unchanged items identical. */ +const blockCache = new WeakMap(); + +function cachedBlock(item: OrchestrationV2TurnItem, pending: ReadonlySet): Block | null { + // Approval and question blocks depend on request state, not just the item. + if (item.type === "approval_request" || item.type === "user_input_request") return blockFor(item, pending); + let block = blockCache.get(item); + if (block === undefined) { + 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, b as unknown as Record); +} + +function shallowEqual(a: Record, b: Record): 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(); + 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 = { $: "command", "✎": "edit", "⌕": "search", "⚙": "tool call", "↳": "subagent", "☐": "plan update" }; + export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet): Block | null { const id = item.id; switch (item.type) { diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 509baae..4137ea8 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -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 type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts"; import { useEffect, useMemo, useRef, useState } from "react"; import type { ShellState, T3Session, ThreadState } from "../client/session.ts"; -import { buildTranscript } from "../model/transcript.ts"; -import { lastActivity, relativeTime, threadRows } from "../model/threads.ts"; +import { buildTranscript, type Transcript } from "../model/transcript.ts"; +import { isRunning, lastActivity, needsUser, relativeTime, threadRows } from "../model/threads.ts"; import { colors } from "./theme.ts"; import { ThreadList } from "./ThreadList.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 }) { const { session, attachThreadId } = props; const renderer = useRenderer(); const { width, height } = useTerminalDimensions(); const [shell, setShell] = useState(session.getShell()); - const [selected, setSelected] = useState(0); - const [focus, setFocus] = useState(attachThreadId ? "thread" : "list"); + const [selectedId, setSelectedId] = useState(attachThreadId); + const [mode, setMode] = useState(attachThreadId ? "input" : "nav"); 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 [draft, setDraft] = useState(""); + const [composerLines, setComposerLines] = useState(1); const scrollRef = useRef(null); - const composerRef = useRef(null); + const composerRef = useRef(null); + const drafts = useRef(new Map()); useEffect(() => session.onShell(setShell), [session]); const rows = useMemo(() => threadRows(shell.snapshot, { query: filter }), [shell.snapshot, filter]); - const selectedRow = rows[Math.min(selected, rows.length - 1)]; - const threadId = attachThreadId ?? selectedRow?.thread.id; + // 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); + // 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 selectedIdRef = useRef(undefined); + const [watchedId, setWatchedId] = useState(threadId); useEffect(() => { - const id = selectedIdRef.current; - if (!id) return; - const index = rows.findIndex((row) => row.thread.id === id); - if (index >= 0 && index !== selected) setSelected(index); - }, [rows]); - useEffect(() => { - selectedIdRef.current = rows[selected]?.thread.id; - }, [selected, rows]); + if (threadId === watchedId) return; + const timer = setTimeout(() => setWatchedId(threadId), SUBSCRIBE_DELAY_MS); + return () => clearTimeout(timer); + }, [threadId, watchedId]); const [thread, setThread] = useState(null); useEffect(() => { setThread(null); - if (!threadId || shell.status.type === "error" || !shell.serverUrl) return; - return session.watchThread(threadId, setThread); - }, [session, threadId, shell.serverUrl]); + if (!watchedId || !shell.serverUrl) return; + return session.watchThread(watchedId, setThread); + }, [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 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), ); }; - 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)); }; - const submitDraft = (value: string) => { - const text = value.trim(); - if (!text || !threadId) return; - setDraft(""); - if (composerRef.current) composerRef.current.value = ""; - setFocus("thread"); - run("Sent", () => session.sendMessage(threadId, text)); + const submit = () => { + const composer = composerRef.current; + const text = composer?.plainText.trim() ?? ""; + if (!composer || !text || !threadId) return; + composer.setText(""); + drafts.current.delete(threadId); + 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 = () => { void session.stop().finally(() => { 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(() => { let needs = 0; - let running = 0; + let active = 0; for (const row of threadRows(shell.snapshot, { recentLimit: 0 })) { 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]); - const status = - shell.status.type === "error" ? `error: ${shell.status.message}` : shell.status.type === "connecting" ? "connecting…" : shell.serverUrl ?? ""; - const listWidth = attachThreadId ? 0 : Math.min(48, Math.max(28, Math.floor(width * 0.32))); + const status = 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 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 ( @@ -165,58 +188,84 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI tui3 - {` ${status}`} + {` ${status}`} - {counts.needs > 0 ? {`● ${counts.needs} need you `} : null} - {`◐ ${counts.running} running`} + {counts.needs > 0 ? {`● ${counts.needs} need you `} : null} + {`◐ ${counts.active} running`} - {attachThreadId ? null : } + {attachThreadId ? null : } {threadId ? ( ) : ( - - {shell.snapshot ? "Select a thread." : "Waiting for threads…"} + + {shell.snapshot ? "No thread selected." : "Waiting for threads…"} )} - {focus === "composer" ? ( - - submitDraft(typeof value === "string" ? value : draft)} /> + {mode === "filter" ? ( + + setFilter(value)} onSubmit={() => setMode("nav")} /> - ) : null} - {focus === "filter" ? ( - - { setFilter(value); setSelected(0); }} onSubmit={() => setFocus("list")} /> + ) : threadId ? ( + +