From 3b7ed56e16e40068fa7385ee38817274349dce03 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 16:51:37 +1100 Subject: [PATCH] Add dashboard, attach view, list and tmux commands --- README.md | 59 +++++++++++ bunfig.toml | 2 + scripts/spike-shell.ts | 25 ----- scripts/spike-thread.ts | 25 ----- src/bin.ts | 142 +++++++++++++++++++++++++ src/model/threads.ts | 82 +++++++++++++++ src/model/transcript.ts | 137 +++++++++++++++++++++++++ src/mux/tmux.ts | 67 ++++++++++++ src/ui/App.tsx | 222 ++++++++++++++++++++++++++++++++++++++++ src/ui/ThreadList.tsx | 70 +++++++++++++ src/ui/ThreadView.tsx | 105 +++++++++++++++++++ src/ui/theme.ts | 47 +++++++++ test/commands.test.ts | 43 ++++++++ test/threads.test.ts | 51 +++++++++ test/transcript.test.ts | 29 ++++++ 15 files changed, 1056 insertions(+), 50 deletions(-) create mode 100644 README.md create mode 100644 bunfig.toml delete mode 100644 scripts/spike-shell.ts delete mode 100644 scripts/spike-thread.ts create mode 100755 src/bin.ts create mode 100644 src/model/threads.ts create mode 100644 src/model/transcript.ts create mode 100644 src/mux/tmux.ts create mode 100644 src/ui/App.tsx create mode 100644 src/ui/ThreadList.tsx create mode 100644 src/ui/ThreadView.tsx create mode 100644 src/ui/theme.ts create mode 100644 test/commands.test.ts create mode 100644 test/threads.test.ts create mode 100644 test/transcript.test.ts diff --git a/README.md b/README.md new file mode 100644 index 0000000..091be48 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# tui3 + +A terminal client for [T3 Code](https://github.com/pingdotgg/t3code). It connects to the T3 Code server you already run, shows every thread live, and lets you read, message, approve and stop them without the GUI. + +Built with Bun and [OpenTUI](https://github.com/anomalyco/opentui) (React). + +## Install + +```sh +git clone --recurse-submodules && cd tui3 +bun install # also links the pinned T3 Code packages into node_modules +bun link # optional: puts `tui3` on your PATH +``` + +## Use + +```sh +tui3 # dashboard: threads on the left, the selected thread on the right +tui3 attach # one thread, full screen (id, short id from `tui3 list`, or title text) +tui3 list [--json] # print threads and exit +tui3 tmux [--watch] # mirror active threads into a tmux session, one window each +``` + +Dashboard keys: + +| 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) | +| `y` / `Y` / `n` | accept / accept for session / decline the pending approval | +| `S` | stop the thread | +| `r` | show full reasoning | +| `g` / `G` | top / bottom of the thread | +| `q`, `ctrl+c` | quit | + +Threads are grouped into **Needs you** (waiting on an approval), **Running**, and **Recent**. + +## How it connects + +- It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`). +- 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`). + +## Updating for a newer T3 Code + +The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag: + +```sh +cd vendor/t3code && git fetch --depth 1 origin tag && git checkout && cd - +bun install && bun run typecheck && bun test +``` + +Type errors after a bump point at the protocol changes to adapt to. + +## Not yet supported + +Answering agent questions (`user_input` requests), starting new threads, attachments, diffs, and the integrated terminal. Use the T3 Code app for those. diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..49211bd --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,2 @@ +[test] +root = "./test" diff --git a/scripts/spike-shell.ts b/scripts/spike-shell.ts deleted file mode 100644 index be76645..0000000 --- a/scripts/spike-shell.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Stream from "effect/Stream"; -import { connect } from "../src/client/rpc.ts"; - -const program = Effect.gen(function* () { - const { rpc, target } = yield* connect; - console.log("connected to", target.httpBaseUrl); - yield* rpc[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({ omitIdleSubagents: true, omitOlderSettled: true }).pipe( - Stream.take(3), - Stream.runForEach((item) => - Effect.sync(() => { - if (item.kind === "snapshot") { - const s = item.snapshot as any; - console.log("snapshot keys:", Object.keys(s)); - console.log("projects:", s.projects?.length, "threads:", s.threads?.length); - for (const t of (s.threads ?? []).slice(0, 8)) console.log(" -", t.status, t.activityRunStatus, t.pendingRuntimeRequest ? "[NEEDS YOU]" : "", t.title); - } else console.log("item:", item.kind); - }), - ), - Effect.timeout("10 seconds"), - ); -}); -await Effect.runPromise(Effect.scoped(program)).catch((e) => { console.error("FAILED:", e); process.exit(1); }); -process.exit(0); diff --git a/scripts/spike-thread.ts b/scripts/spike-thread.ts deleted file mode 100644 index cf96299..0000000 --- a/scripts/spike-thread.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { T3Session } from "../src/client/session.ts"; -const s = new T3Session(); -await s.start(); -await new Promise((r) => { const off = s.onShell((st) => { if (st.status.type !== "connecting" && st.snapshot) { off(); r(); } }); }); -const shell = s.getShell(); -console.log("status", shell.status, "threads", shell.snapshot?.threads.length); -const counts: Record = {}; -for (const t of shell.snapshot!.threads) counts[t.status] = (counts[t.status] ?? 0) + 1; -console.log(counts); -const t = shell.snapshot!.threads.find((t) => t.status === "running") ?? shell.snapshot!.threads[0]!; -console.log("watching", t.title, t.status); -let events = 0; -const off = s.watchThread(t.id, (st) => { - events++; - if (st.projection && events < 4) { - const items = st.projection.visibleTurnItems; - console.log(st.status, "items", items.length, "types", [...new Set(items.map((i) => i.item.type))].join(",")); - const last = items.at(-1)?.item as any; - console.log("last:", last?.type, String(last?.text ?? last?.input ?? "").slice(0, 120)); - } - if (st.error) console.log("ERR", st.error); -}); -await Bun.sleep(5000); -console.log("updates received", events); -off(); await s.stop(); process.exit(0); diff --git a/src/bin.ts b/src/bin.ts new file mode 100755 index 0000000..133bd3c --- /dev/null +++ b/src/bin.ts @@ -0,0 +1,142 @@ +#!/usr/bin/env bun +import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; + +import { T3Session } from "./client/session.ts"; +import { findThread, lastActivity, relativeTime, shortId, threadRows } from "./model/threads.ts"; + +const USAGE = `tui3: a terminal client for T3 Code + +usage: + tui3 dashboard: every thread, live + tui3 attach one thread, full screen (id, short id from \`list\`, or title text) + tui3 list [--json] print threads and exit + tui3 tmux [--watch] [--session ] + mirror active threads into tmux windows (default session: tui3) + tui3 help + +env: + TUI3_SERVER server origin (default: the local server from ~/.t3) + TUI3_TOKEN bearer token for a remote server (local servers mint one via \`t3\`)`; + +async function main(argv: string[]) { + const [command, ...rest] = argv; + switch (command) { + case undefined: + return runUi(); + case "attach": { + const needle = rest.join(" ").trim(); + if (!needle) return fail("usage: tui3 attach "); + return runUi(needle); + } + case "list": + case "ls": + return list(rest.includes("--json")); + case "tmux": + return tmuxCommand(rest); + case "help": + case "--help": + case "-h": + console.log(USAGE); + return; + default: + return fail(`unknown command: ${command}\n\n${USAGE}`); + } +} + +async function connectedSession(): Promise<{ session: T3Session; snapshot: OrchestrationV2ShellSnapshot }> { + const session = new T3Session(); + await session.start(); + const snapshot = await new Promise((resolve, reject) => { + const off = session.onShell((shell) => { + if (shell.status.type === "error") { + queueMicrotask(() => off()); + reject(new Error(shell.status.message)); + } else if (shell.status.type === "live" && shell.snapshot) { + queueMicrotask(() => off()); + resolve(shell.snapshot); + } + }); + }); + return { session, snapshot }; +} + +async function list(json: boolean) { + const { session, snapshot } = await connectedSession(); + const rows = threadRows(snapshot, { recentLimit: 40 }); + if (json) { + console.log(JSON.stringify(rows.map((row) => ({ id: row.thread.id, title: row.thread.title, project: row.projectName, group: row.group, status: row.thread.status, updatedAt: new Date(lastActivity(row.thread)).toISOString() })), null, 2)); + } else { + for (const row of rows) { + const mark = row.group === "needs-you" ? "!" : row.group === "running" ? "~" : " "; + console.log(`${mark} ${shortId(row.thread.id)} ${relativeTime(lastActivity(row.thread)).padStart(4)} ${row.projectName.padEnd(20).slice(0, 20)} ${row.thread.title}`); + } + } + await session.stop(); +} + +async function tmuxCommand(args: string[]) { + const { syncTmux } = await import("./mux/tmux.ts"); + const sessionFlag = args.indexOf("--session"); + const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "tui3"; + if (!name) return fail("usage: tui3 tmux [--watch] [--session ]"); + const options = { session: name, tui3: [process.execPath, import.meta.path] }; + const { session, snapshot } = await connectedSession(); + const { opened } = await syncTmux(snapshot, options); + console.log(`tmux session "${name}" is in sync (${opened} new window${opened === 1 ? "" : "s"}). Attach with: tmux attach -t ${name}`); + if (!args.includes("--watch")) return session.stop(); + // Coalesce bursts of shell updates into one sync at a time. + let pending = false; + let syncing = false; + const sync = async () => { + if (syncing) return void (pending = true); + syncing = true; + try { + const latest = session.getShell().snapshot; + if (latest) { + const result = await syncTmux(latest, options); + if (result.opened > 0) console.log(`opened ${result.opened} window${result.opened === 1 ? "" : "s"}`); + } + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + } finally { + syncing = false; + if (pending) { + pending = false; + void sync(); + } + } + }; + session.onShell((shell) => { + if (shell.status.type === "error") fail(shell.status.message); + void sync(); + }); + await new Promise(() => {}); +} + +async function runUi(attachNeedle?: string) { + const { session, snapshot } = await connectedSession(); + let attachThreadId; + if (attachNeedle) { + const thread = findThread(snapshot, attachNeedle); + if (!thread) { + await session.stop(); + return fail(`No thread matches "${attachNeedle}".`); + } + attachThreadId = thread.id; + } + // Load the renderer only for the UI so `list` stays fast and works without a TTY. + // Sequential on purpose: importing core and react concurrently trips a module init cycle. + const { createCliRenderer } = await import("@opentui/core"); + const { createRoot } = await import("@opentui/react"); + const { createElement } = await import("react"); + const { App } = await import("./ui/App.tsx"); + const renderer = await createCliRenderer({ exitOnCtrlC: false }); + createRoot(renderer).render(createElement(App, { session, ...(attachThreadId ? { attachThreadId } : {}) })); +} + +function fail(message: string): never { + console.error(message); + process.exit(1); +} + +main(process.argv.slice(2)).catch((error) => fail(error instanceof Error ? error.message : String(error))); diff --git a/src/model/threads.ts b/src/model/threads.ts new file mode 100644 index 0000000..0f68b5c --- /dev/null +++ b/src/model/threads.ts @@ -0,0 +1,82 @@ +import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ProjectId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +export type ThreadGroup = "needs-you" | "running" | "recent"; + +export interface ThreadRow { + readonly thread: OrchestrationV2ThreadShell; + readonly group: ThreadGroup; + readonly projectName: string; +} + +export const GROUP_LABELS: Record = { + "needs-you": "Needs you", + running: "Running", + recent: "Recent", +}; + +const ACTIVE_STATUSES = new Set(["preparing", "starting", "running", "waiting"]); + +export function needsUser(thread: OrchestrationV2ThreadShell): boolean { + return thread.pendingRuntimeRequest !== null && thread.pendingRuntimeRequest.blocking !== false; +} + +export function isRunning(thread: OrchestrationV2ThreadShell): boolean { + return thread.activeRunId !== null || ACTIVE_STATUSES.has(thread.status); +} + +export function groupOf(thread: OrchestrationV2ThreadShell): ThreadGroup { + if (needsUser(thread)) return "needs-you"; + if (isRunning(thread)) return "running"; + return "recent"; +} + +export function lastActivity(thread: OrchestrationV2ThreadShell): number { + return DateTime.toEpochMillis(thread.updatedAt); +} + +/** 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 []; + const projects = new Map(snapshot.projects.map((project) => [project.id, project])); + const query = options.query?.trim().toLowerCase(); + const order: ThreadGroup[] = ["needs-you", "running", "recent"]; + 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)); + const limit = options.recentLimit ?? 60; + let recent = 0; + return rows.filter((row) => row.group !== "recent" || recent++ < limit); +} + +export function projectLabel(project: OrchestrationProjectShell | undefined): string { + if (!project) return ""; + return project.title || project.workspaceRoot.split("/").filter(Boolean).pop() || project.workspaceRoot; +} + +/** Matches a thread by id, id prefix, or a case-insensitive title substring. */ +export function findThread(snapshot: OrchestrationV2ShellSnapshot, needle: string): OrchestrationV2ThreadShell | undefined { + const lower = needle.toLowerCase(); + return ( + snapshot.threads.find((thread) => thread.id === needle) ?? + snapshot.threads.find((thread) => thread.id.startsWith(needle)) ?? + snapshot.threads.find((thread) => thread.id.endsWith(needle)) ?? + snapshot.threads.filter((thread) => thread.title.toLowerCase().includes(lower)).sort((a, b) => lastActivity(b) - lastActivity(a))[0] + ); +} + +/** A short handle `findThread` accepts: MCP-launched ids share a prefix, so use the tail. */ +export function shortId(id: string): string { + return id.slice(-8); +} + +export function relativeTime(ms: number, now = Date.now()): string { + const seconds = Math.max(0, Math.round((now - ms) / 1000)); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.round(seconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `${hours}h`; + return `${Math.round(hours / 24)}d`; +} diff --git a/src/model/transcript.ts b/src/model/transcript.ts new file mode 100644 index 0000000..8092595 --- /dev/null +++ b/src/model/transcript.ts @@ -0,0 +1,137 @@ +import type { OrchestrationV2ThreadProjection, OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts"; + +/** One rendered row of the transcript. Markdown blocks get the markdown renderer; the rest are plain lines. */ +export type Block = + | { readonly kind: "user"; readonly id: string; readonly text: string } + | { readonly kind: "assistant"; readonly id: string; readonly markdown: string; readonly streaming: boolean } + | { readonly kind: "reasoning"; readonly id: string; readonly text: string; readonly streaming: boolean } + | { readonly kind: "tool"; readonly id: string; readonly icon: string; readonly label: string; readonly detail?: string; readonly tone: Tone } + | { readonly kind: "approval"; readonly id: string; readonly requestId: RuntimeRequestId; readonly title: string; readonly detail?: string; readonly pending: boolean } + | { readonly kind: "question"; readonly id: string; readonly requestId: RuntimeRequestId; readonly questions: readonly string[]; readonly pending: boolean } + | { readonly kind: "notice"; readonly id: string; readonly text: string; readonly tone: Tone }; + +export type Tone = "normal" | "muted" | "good" | "bad" | "warn"; + +export interface Transcript { + readonly blocks: readonly Block[]; + /** 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); + } + return { blocks, hiddenCount: start, pendingRequestIds }; +} + +export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet): Block | null { + const id = item.id; + switch (item.type) { + case "user_message": + return item.text.trim() ? { kind: "user", id, text: item.text } : null; + case "assistant_message": + return item.text.trim() || item.streaming ? { kind: "assistant", id, markdown: item.text, streaming: item.streaming } : null; + case "reasoning": + return item.text.trim() ? { kind: "reasoning", id, text: item.text, streaming: item.streaming } : null; + case "command_execution": { + const failed = item.outputIndicatesFailure === true || (item.exitCode !== undefined && item.exitCode !== 0); + const exit = item.exitCode === undefined ? "" : failed ? ` (exit ${item.exitCode})` : ""; + const output = item.output ? tailLines(item.output, OUTPUT_TAIL_LINES) : undefined; + return { kind: "tool", id, icon: "$", label: firstLine(item.input) + exit, ...(output ? { detail: output } : {}), tone: failed ? "bad" : "normal" }; + } + case "file_change": { + const stats = item.additions !== undefined || item.deletions !== undefined ? ` +${item.additions ?? 0} −${item.deletions ?? 0}` : ""; + return { kind: "tool", id, icon: "✎", label: `${item.fileName}${stats}`, tone: "normal" }; + } + case "file_search": + return { kind: "tool", id, icon: "⌕", label: `search ${item.pattern ?? ""}`.trim() + countSuffix(item.results?.length), tone: "muted" }; + case "web_search": + return { kind: "tool", id, icon: "⌕", label: `web ${(item.patterns ?? []).join(", ")}`.trim() + countSuffix(item.results?.length), tone: "muted" }; + case "dynamic_tool": + return { kind: "tool", id, icon: "⚙", label: `${item.toolName ?? "tool"} ${summarizeInput(item.input)}`.trim(), tone: "muted" }; + case "subagent": { + const state = item.result !== null ? "done" : item.progress ? item.progress : "running"; + return { kind: "tool", id, icon: "↳", label: `subagent: ${firstLine(item.prompt)}`, detail: firstLine(state), tone: "muted" }; + } + case "todo_list": + return { + kind: "tool", + id, + icon: "☐", + label: "plan", + detail: item.steps.map((step) => `${step.status === "completed" ? "✓" : step.status === "running" ? "▸" : "·"} ${step.text}`).join("\n"), + tone: "normal", + }; + case "proposed_plan": + return { kind: "assistant", id, markdown: item.markdown, streaming: item.streaming }; + case "approval_request": + return { + kind: "approval", + id, + requestId: item.requestId, + title: `${item.appName ? `${item.appName}: ` : ""}${item.prompt ?? item.requestKind}`, + ...(item.reason ? { detail: item.reason } : {}), + pending: pending.has(item.requestId), + }; + case "user_input_request": + return { kind: "question", id, requestId: item.requestId, questions: item.questions.map((q) => q.question), pending: pending.has(item.requestId) }; + case "error": + return { kind: "notice", id, text: `error: ${item.failure.message}`, tone: "bad" }; + case "system_notice": + return { kind: "notice", id, text: item.message, tone: "muted" }; + case "run_interrupt_request": + case "run_interrupt_result": + return { kind: "notice", id, text: item.message, tone: "warn" }; + case "notification": + return { kind: "notice", id, text: item.summary, tone: item.outcome === "failed" ? "bad" : item.outcome === "completed" ? "good" : "muted" }; + case "compaction": + return { kind: "notice", id, text: "context compacted", tone: "muted" }; + case "handoff": + return { kind: "notice", id, text: `handed off${item.toModel ? ` to ${item.toModel}` : ""}`, tone: "muted" }; + case "checkpoint": + case "fork": + case "thread_created": + return null; + default: + return null; + } +} + +function firstLine(text: string): string { + const line = text.trim().split("\n")[0] ?? ""; + return line.length > 160 ? `${line.slice(0, 157)}…` : line; +} + +function tailLines(text: string, count: number): string { + const lines = text.replace(/\s+$/, "").split("\n"); + const kept = lines.slice(-count).map((line) => (line.length > 200 ? `${line.slice(0, 197)}…` : line)); + return (lines.length > count ? ["…", ...kept] : kept).join("\n"); +} + +function countSuffix(count: number | undefined): string { + return count === undefined ? "" : ` (${count})`; +} + +function summarizeInput(input: unknown): string { + if (input === null || input === undefined) return ""; + if (typeof input === "string") return firstLine(input); + if (typeof input === "object") { + const record = input as Record; + for (const key of ["command", "file_path", "path", "pattern", "query", "url", "description", "prompt"]) { + const value = record[key]; + if (typeof value === "string" && value.trim()) return firstLine(value); + } + return firstLine(JSON.stringify(input)); + } + return String(input); +} diff --git a/src/mux/tmux.ts b/src/mux/tmux.ts new file mode 100644 index 0000000..b95e732 --- /dev/null +++ b/src/mux/tmux.ts @@ -0,0 +1,67 @@ +import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; + +import { threadRows, type ThreadRow } from "../model/threads.ts"; + +/** Window option that ties a tmux window to the thread it attaches to. */ +const THREAD_OPTION = "@tui3_thread"; +const TITLE_WIDTH = 24; + +export interface TmuxSyncOptions { + readonly session: string; + /** Command that starts tui3, e.g. [bun, /path/to/bin.ts]. */ + readonly tui3: readonly string[]; +} + +async function tmux(args: readonly string[], allowFailure = false): Promise { + const proc = Bun.spawn(["tmux", ...args], { stdout: "pipe", stderr: "pipe" }); + const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + if (code !== 0 && !allowFailure) throw new Error(`tmux ${args[0]} failed: ${stderr.trim()}`); + return code === 0 ? stdout : ""; +} + +const shellJoin = (parts: readonly string[]) => parts.map((part) => `'${part.replaceAll("'", `'\\''`)}'`).join(" "); + +export function windowName(row: ThreadRow): string { + const mark = row.group === "needs-you" ? "● " : row.group === "running" ? "" : "✓ "; + const title = (row.thread.title || "thread").replace(/\s+/g, " "); + return mark + (title.length > TITLE_WIDTH ? `${title.slice(0, TITLE_WIDTH - 1)}…` : title); +} + +/** + * Makes the tmux session mirror T3 Code: a dashboard window, plus a window per + * thread that is running or waiting on you. Windows for threads that finish + * are kept (marked ✓) so nothing you're reading disappears. + */ +export async function syncTmux(snapshot: OrchestrationV2ShellSnapshot, options: TmuxSyncOptions): Promise<{ readonly opened: number }> { + const { session } = options; + if (!(await sessionExists(session))) { + await tmux(["new-session", "-d", "-s", session, "-n", "dashboard", shellJoin(options.tui3)]); + } + const windows = new Map(); + for (const line of (await tmux(["list-windows", "-t", `=${session}`, "-F", `#{window_id}\t#{${THREAD_OPTION}}`])).split("\n")) { + const [windowId, threadId] = line.split("\t"); + if (windowId && threadId) windows.set(threadId, windowId); + } + const rows = threadRows(snapshot, { recentLimit: 0 }); + const byId = new Map(threadRows(snapshot, { recentLimit: Number.MAX_SAFE_INTEGER }).map((row) => [row.thread.id as string, row])); + let opened = 0; + for (const row of rows) { + if (windows.has(row.thread.id)) continue; + const windowId = ( + await tmux(["new-window", "-d", "-P", "-F", "#{window_id}", "-t", `=${session}:`, "-n", windowName(row), shellJoin([...options.tui3, "attach", row.thread.id])]) + ).trim(); + await tmux(["set-option", "-w", "-t", windowId, THREAD_OPTION, row.thread.id]); + windows.set(row.thread.id, windowId); + opened++; + } + for (const [threadId, windowId] of windows) { + const row = byId.get(threadId); + if (row) await tmux(["rename-window", "-t", windowId, windowName(row)], true); + } + return { opened }; +} + +async function sessionExists(session: string): Promise { + const proc = Bun.spawn(["tmux", "has-session", "-t", `=${session}`], { stdout: "ignore", stderr: "ignore" }); + return (await proc.exited) === 0; +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx new file mode 100644 index 0000000..509baae --- /dev/null +++ b/src/ui/App.tsx @@ -0,0 +1,222 @@ +import type { InputRenderable, ScrollBoxRenderable } 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 { colors } from "./theme.ts"; +import { ThreadList } from "./ThreadList.tsx"; +import { ThreadView } from "./ThreadView.tsx"; + +type Focus = "list" | "thread" | "composer" | "filter"; + +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 [filter, setFilter] = useState(""); + const [showReasoning, setShowReasoning] = useState(false); + const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null); + const [draft, setDraft] = useState(""); + const scrollRef = useRef(null); + const composerRef = useRef(null); + + 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; + const threadShell = shell.snapshot?.threads.find((thread) => thread.id === threadId); + + // Keep the selection on the same thread when the list reorders under it. + const selectedIdRef = useRef(undefined); + 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]); + + 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]); + + const transcript = useMemo(() => (thread?.projection ? buildTranscript(thread.projection) : null), [thread?.projection]); + const pendingRequest = thread?.projection?.runtimeRequests.findLast((request) => request.status === "pending" && request.kind !== "user_input"); + + const say = (text: string, bad = false) => { + setFlash({ text, bad }); + setTimeout(() => setFlash((current) => (current?.text === text ? null : current)), 4000); + }; + const run = (label: string, action: () => Promise) => { + 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)); + }; + + 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)); + }; + + 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(); + process.exit(0); + }); + }; + + const counts = useMemo(() => { + let needs = 0; + let running = 0; + for (const row of threadRows(shell.snapshot, { recentLimit: 0 })) { + if (row.group === "needs-you") needs++; + else if (row.group === "running") running++; + } + return { needs, running }; + }, [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 subtitle = threadShell + ? [threadShell.status, threadShell.modelSelection.model, threadShell.branch, relativeTime(lastActivity(threadShell))].filter(Boolean).join(" · ") + : ""; + + return ( + + + + tui3 + + {` ${status}`} + + {counts.needs > 0 ? {`● ${counts.needs} need you `} : null} + {`◐ ${counts.running} running`} + + + {attachThreadId ? null : } + + {threadId ? ( + + ) : ( + + {shell.snapshot ? "Select a thread." : "Waiting for threads…"} + + )} + {focus === "composer" ? ( + + submitDraft(typeof value === "string" ? value : draft)} /> + + ) : null} + {focus === "filter" ? ( + + { setFilter(value); setSelected(0); }} onSubmit={() => setFocus("list")} /> + + ) : null} + + + + {flash ? ( + {flash.text} + ) : ( + {hints(focus, Boolean(pendingRequest), Boolean(attachThreadId))} + )} + + + ); +} + +function hints(focus: Focus, pending: boolean, attached: boolean): string { + if (focus === "composer" || focus === "filter") return "enter submit · esc cancel"; + 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"]; + parts.push("i message", "r reasoning", "S stop"); + if (pending) parts.unshift("y accept · Y session · n decline"); + parts.push("q quit"); + return parts.join(" · "); +} diff --git a/src/ui/ThreadList.tsx b/src/ui/ThreadList.tsx new file mode 100644 index 0000000..66bca49 --- /dev/null +++ b/src/ui/ThreadList.tsx @@ -0,0 +1,70 @@ +import { GROUP_LABELS, lastActivity, relativeTime, type ThreadRow } from "../model/threads.ts"; +import { colors } from "./theme.ts"; + +const STATUS_GLYPH: Record = { + "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 - 2 - 3) / 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 lines: React.ReactNode[] = []; + let previousGroup = start > 0 ? rows[start - 1]?.group : undefined; + windowRows.forEach((row, offset) => { + const index = start + offset; + if (row.group !== previousGroup) { + lines.push( + + {GROUP_LABELS[row.group]} + , + ); + previousGroup = row.group; + } + const { glyph, color } = glyphFor(row); + const isSelected = index === selected; + const title = truncate(row.thread.title || "(untitled)", titleWidth); + lines.push( + + {` ${glyph} `} + + {title} + {truncate(`${row.projectName} · ${relativeTime(lastActivity(row.thread), now)}`, titleWidth)} + + , + ); + }); + return ( + + {rows.length === 0 ? no threads : lines} + + ); +} + +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; +} diff --git a/src/ui/ThreadView.tsx b/src/ui/ThreadView.tsx new file mode 100644 index 0000000..803e961 --- /dev/null +++ b/src/ui/ThreadView.tsx @@ -0,0 +1,105 @@ +import type { ScrollBoxRenderable } from "@opentui/core"; +import { useMemo, type RefObject } from "react"; + +import type { Block, Transcript } from "../model/transcript.ts"; +import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; + +export function ThreadView(props: { + readonly title: string; + readonly subtitle: string; + readonly transcript: Transcript | null; + readonly loading: boolean; + readonly error?: string | undefined; + readonly focused: boolean; + readonly showReasoning: boolean; + readonly scrollRef: RefObject; +}) { + const { transcript } = props; + const body = useMemo(() => { + if (!transcript) return null; + return transcript.blocks.map((block) => ); + }, [transcript, props.showReasoning]); + + return ( + + {props.subtitle} + {props.error ? {props.error} : null} + {props.loading && !transcript ? loading… : null} + + {transcript && transcript.hiddenCount > 0 ? {`… ${transcript.hiddenCount} earlier items not shown`} : null} + {body} + + + ); +} + +function BlockView({ block, showReasoning }: { readonly block: Block; readonly showReasoning: boolean }) { + switch (block.kind) { + case "user": + return ( + + › + + {block.text.trim()} + + + ); + case "assistant": + return ( + + + + ); + case "reasoning": + if (!showReasoning) return {` ∴ ${firstLine(block.text)}`}; + return ( + + {block.text.trim()} + + ); + case "tool": + return ( + + {` ${block.icon} ${block.label}`} + {block.detail ? {indent(block.detail, " ")} : null} + + ); + case "approval": + return ( + + + {block.pending ? "Approval needed: " : "Approval: "} + {block.title} + + {block.detail ? {block.detail} : null} + {block.pending ? [y] accept [Y] accept for session [n] decline : null} + + ); + case "question": + return ( + + + {block.pending ? "Question for you" : "Question"} + + {block.questions.map((question, index) => ( + {`• ${question}`} + ))} + {block.pending ? Answer in the T3 Code app for now. : null} + + ); + case "notice": + return {` ${block.text}`}; + } +} + +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"); +} diff --git a/src/ui/theme.ts b/src/ui/theme.ts new file mode 100644 index 0000000..830dd63 --- /dev/null +++ b/src/ui/theme.ts @@ -0,0 +1,47 @@ +import { SyntaxStyle } from "@opentui/core"; + +import type { Tone } from "../model/transcript.ts"; + +export const colors = { + bg: "#16161e", + panel: "#1a1b26", + border: "#2f334d", + borderFocused: "#7aa2f7", + text: "#c0caf5", + muted: "#737aa2", + faint: "#545c7e", + accent: "#7aa2f7", + user: "#7dcfff", + good: "#9ece6a", + bad: "#f7768e", + warn: "#e0af68", + selectedBg: "#283457", +} as const; + +export const toneColor: Record = { + normal: colors.text, + muted: colors.muted, + good: colors.good, + bad: colors.bad, + warn: colors.warn, +}; + +let markdownStyle: SyntaxStyle | undefined; + +/** Created lazily: SyntaxStyle needs the native renderer library loaded. */ +export function getMarkdownStyle(): SyntaxStyle { + markdownStyle ??= SyntaxStyle.fromStyles({ + default: { fg: colors.text }, + "markup.heading": { fg: colors.accent, bold: true }, + "markup.strong": { bold: true }, + "markup.italic": { italic: true }, + "markup.strikethrough": { dim: true }, + "markup.link": { fg: colors.user, underline: true }, + "markup.link.label": { fg: colors.user }, + "markup.link.url": { fg: colors.faint, underline: true }, + "markup.quote": { fg: colors.muted, italic: true }, + "markup.raw": { fg: colors.warn }, + "markup.raw.block": { fg: colors.text }, + }); + return markdownStyle; +} diff --git a/test/commands.test.ts b/test/commands.test.ts new file mode 100644 index 0000000..41fd931 --- /dev/null +++ b/test/commands.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from "bun:test"; +import { OrchestrationV2Command, ThreadId, RuntimeRequestId } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import { T3Session } from "../src/client/session.ts"; + +// Captures what the session would dispatch, without a server, and checks it +// against the server's own command schema. +function capturingSession() { + const session = new T3Session(); + const sent: unknown[] = []; + (session as unknown as { dispatch: (command: unknown) => Promise }).dispatch = async (command) => { + sent.push(command); + }; + return { session, sent }; +} + +const isCommand = Schema.is(OrchestrationV2Command); +const threadId = ThreadId.make("thread-1"); + +describe("commands tui3 dispatches", () => { + test("a queued message is a valid message.dispatch", async () => { + const { session, sent } = capturingSession(); + await session.sendMessage(threadId, "hello"); + expect(sent).toHaveLength(1); + expect(isCommand(sent[0])).toBe(true); + expect(sent[0]).toMatchObject({ type: "message.dispatch", threadId, text: "hello", dispatchMode: { type: "queue_after_active" } }); + }); + + test("an approval is a valid runtime-request.respond", async () => { + const { session, sent } = capturingSession(); + await session.respond(threadId, RuntimeRequestId.make("req-1"), "acceptForSession"); + expect(isCommand(sent[0])).toBe(true); + expect(sent[0]).toMatchObject({ type: "runtime-request.respond", decision: "acceptForSession" }); + }); + + test("stop is a valid thread.stop", async () => { + const { session, sent } = capturingSession(); + await session.stopThread(threadId); + expect(isCommand(sent[0])).toBe(true); + expect(sent[0]).toMatchObject({ type: "thread.stop", threadId }); + }); +}); diff --git a/test/threads.test.ts b/test/threads.test.ts new file mode 100644 index 0000000..6819c6c --- /dev/null +++ b/test/threads.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "bun:test"; +import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import { findThread, relativeTime, threadRows } from "../src/model/threads.ts"; + +const at = (ms: number) => DateTime.makeUnsafe(ms); +const thread = (id: string, title: string, updated: number, extra: Record = {}) => ({ + id, + title, + projectId: "p1", + status: "completed", + activeRunId: null, + pendingRuntimeRequest: null, + updatedAt: at(updated), + ...extra, +}); +const snapshot = { + projects: [{ id: "p1", title: "tasknotes", workspaceRoot: "/home/me/tasknotes" }], + threads: [ + thread("mcp:launch:aaaa1111", "old finished", 1_000), + thread("t-running", "busy one", 2_000, { status: "running", activeRunId: "r1" }), + thread("t-waiting", "wants approval", 500, { status: "running", activeRunId: "r2", pendingRuntimeRequest: { id: "q", kind: "command", createdAt: at(0) } }), + thread("t-new", "newest finished", 3_000), + ], +} as unknown as OrchestrationV2ShellSnapshot; + +describe("threadRows", () => { + test("orders needs-you, then running, then recent by activity", () => { + expect(threadRows(snapshot).map((row) => row.thread.id as string)).toEqual(["t-waiting", "t-running", "t-new", "mcp:launch:aaaa1111"]); + }); + + test("filters by title or project and caps recent rows", () => { + expect(threadRows(snapshot, { query: "BUSY" }).map((row) => row.thread.id as string)).toEqual(["t-running"]); + expect(threadRows(snapshot, { query: "tasknotes" })).toHaveLength(4); + expect(threadRows(snapshot, { recentLimit: 1 }).map((row) => row.group)).toEqual(["needs-you", "running", "recent"]); + }); +}); + +describe("findThread", () => { + test("matches ids, id tails and title text", () => { + expect(findThread(snapshot, "t-new")?.title).toBe("newest finished"); + expect(findThread(snapshot, "aaaa1111")?.title).toBe("old finished"); + expect(findThread(snapshot, "Approval")?.id as string | undefined).toBe("t-waiting"); + }); +}); + +test("relativeTime", () => { + expect(relativeTime(0, 45_000)).toBe("45s"); + expect(relativeTime(0, 3 * 3600_000)).toBe("3h"); +}); diff --git a/test/transcript.test.ts b/test/transcript.test.ts new file mode 100644 index 0000000..ab33c87 --- /dev/null +++ b/test/transcript.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import type { OrchestrationV2TurnItem } from "@t3tools/contracts"; + +import { blockFor } from "../src/model/transcript.ts"; + +const base = { id: "item-1", threadId: "thread-1", runId: null } as const; +const item = (fields: Record) => ({ ...base, ...fields }) as unknown as OrchestrationV2TurnItem; + +describe("blockFor", () => { + test("failed commands show the exit code and a short output tail", () => { + const block = blockFor(item({ type: "command_execution", input: "make test\n--verbose", output: "a\nb\nc\nd\ne", exitCode: 2 }), new Set()); + expect(block).toEqual({ kind: "tool", id: "item-1", icon: "$", label: "make test (exit 2)", detail: "…\nc\nd\ne", tone: "bad" }); + }); + + test("approvals know whether they are still pending", () => { + const fields = { type: "approval_request", requestId: "req-1", requestKind: "command", prompt: "Run rm -rf build?" }; + expect(blockFor(item(fields), new Set(["req-1"]))).toMatchObject({ kind: "approval", pending: true, title: "Run rm -rf build?" }); + expect(blockFor(item(fields), new Set())).toMatchObject({ pending: false }); + }); + + test("dynamic tools summarize their input", () => { + expect(blockFor(item({ type: "dynamic_tool", toolName: "read", input: { file_path: "/tmp/x.ts" } }), new Set())).toMatchObject({ label: "read /tmp/x.ts" }); + }); + + test("empty messages and bookkeeping items render nothing", () => { + expect(blockFor(item({ type: "user_message", text: " " }), new Set())).toBeNull(); + expect(blockFor(item({ type: "checkpoint" }), new Set())).toBeNull(); + }); +});