Add dashboard, attach view, list and tmux commands

This commit is contained in:
Callum Alpass committed 2026-11-02 16:51:37 +11:00
1 parent c93244e7f4
commit 3b7ed56e16
15 files changed
+1056 -50

No files matched your search

Executable
+142
View File
@@ -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 <thread> one thread, full screen (id, short id from \`list\`, or title text)
tui3 list [--json] print threads and exit
tui3 tmux [--watch] [--session <name>]
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 <thread>");
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<OrchestrationV2ShellSnapshot>((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 <name>]");
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)));
+82
View File
@@ -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<ThreadGroup, string> = {
"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<ProjectId, OrchestrationProjectShell>(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`;
}
+137
View File
@@ -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<string>;
}
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<string>): 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<string, unknown>;
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);
}
+67
View File
@@ -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<string> {
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<string, string>();
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<boolean> {
const proc = Bun.spawn(["tmux", "has-session", "-t", `=${session}`], { stdout: "ignore", stderr: "ignore" });
return (await proc.exited) === 0;
}
+222
View File
@@ -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<ShellState>(session.getShell());
const [selected, setSelected] = useState(0);
const [focus, setFocus] = useState<Focus>(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<ScrollBoxRenderable | null>(null);
const composerRef = useRef<InputRenderable | null>(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<string | undefined>(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<ThreadState | null>(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<void>) => {
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 (
<box flexDirection="column" width={width} height={height} backgroundColor={colors.bg}>
<box flexDirection="row" paddingLeft={1} paddingRight={1} height={1} flexShrink={0}>
<text fg={colors.accent}>
<strong>tui3</strong>
</text>
<text fg={colors.muted}>{` ${status}`}</text>
<box flexGrow={1} />
{counts.needs > 0 ? <text fg={colors.warn}>{`● ${counts.needs} need you `}</text> : null}
<text fg={colors.accent}>{`◐ ${counts.running} running`}</text>
</box>
<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} />}
<box flexDirection="column" flexGrow={1} minHeight={0}>
{threadId ? (
<ThreadView
title={threadShell?.title ?? "thread"}
subtitle={subtitle}
transcript={transcript}
loading={thread?.status === "loading"}
error={thread?.error}
focused={focus === "thread"}
showReasoning={showReasoning}
scrollRef={scrollRef}
/>
) : (
<box border borderColor={colors.border} flexGrow={1}>
<text fg={colors.muted}>{shell.snapshot ? "Select a thread." : "Waiting for threads…"}</text>
</box>
)}
{focus === "composer" ? (
<box title=" message (enter to send, esc to cancel) " border borderColor={colors.borderFocused} height={3} flexShrink={0}>
<input ref={composerRef} focused placeholder="Queue a message for this thread…" value={draft} onInput={setDraft} onSubmit={(value: unknown) => submitDraft(typeof value === "string" ? value : draft)} />
</box>
) : null}
{focus === "filter" ? (
<box title=" filter threads (esc to close) " border borderColor={colors.borderFocused} height={3} flexShrink={0}>
<input focused placeholder="title or project…" value={filter} onInput={(value: string) => { setFilter(value); setSelected(0); }} onSubmit={() => setFocus("list")} />
</box>
) : null}
</box>
</box>
<box flexDirection="row" paddingLeft={1} height={1} flexShrink={0}>
{flash ? (
<text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text>
) : (
<text fg={colors.faint}>{hints(focus, Boolean(pendingRequest), Boolean(attachThreadId))}</text>
)}
</box>
</box>
);
}
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(" · ");
}
+70
View File
@@ -0,0 +1,70 @@
import { GROUP_LABELS, lastActivity, relativeTime, type ThreadRow } from "../model/threads.ts";
import { colors } from "./theme.ts";
const STATUS_GLYPH: Record<string, { glyph: string; color: string }> = {
"needs-you": { glyph: "●", color: colors.warn },
running: { glyph: "◐", color: colors.accent },
failed: { glyph: "✕", color: colors.bad },
interrupted: { glyph: "◌", color: colors.muted },
completed: { glyph: "✓", color: colors.faint },
idle: { glyph: "·", color: colors.faint },
};
function glyphFor(row: ThreadRow) {
if (row.group !== "recent") return STATUS_GLYPH[row.group]!;
return STATUS_GLYPH[row.thread.status] ?? STATUS_GLYPH.idle!;
}
export function ThreadList(props: { readonly rows: readonly ThreadRow[]; readonly selected: number; readonly focused: boolean; readonly width: number; readonly height: number; readonly filter: string }) {
const { rows, selected, focused, width, height } = props;
// Rows take two lines and up to three group headers take one each; keep the selection in view.
const visibleCount = Math.max(1, Math.floor((height - 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(
<text key={`h-${row.group}`} fg={row.group === "needs-you" ? colors.warn : colors.muted}>
<strong>{GROUP_LABELS[row.group]}</strong>
</text>,
);
previousGroup = row.group;
}
const { glyph, color } = glyphFor(row);
const isSelected = index === selected;
const title = truncate(row.thread.title || "(untitled)", titleWidth);
lines.push(
<box key={row.thread.id} flexDirection="row" backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.border) : "transparent"}>
<text fg={color}>{` ${glyph} `}</text>
<box flexGrow={1} flexDirection="column">
<text fg={isSelected ? colors.text : colors.text}>{title}</text>
<text fg={colors.faint}>{truncate(`${row.projectName} · ${relativeTime(lastActivity(row.thread), now)}`, titleWidth)}</text>
</box>
</box>,
);
});
return (
<box
title={props.filter ? ` threads /${props.filter} ` : " threads "}
border
borderColor={focused ? colors.borderFocused : colors.border}
width={width}
flexShrink={0}
overflow="hidden"
flexDirection="column"
paddingLeft={0}
>
{rows.length === 0 ? <text fg={colors.muted}> no threads</text> : lines}
</box>
);
}
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;
}
+105
View File
@@ -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<ScrollBoxRenderable | null>;
}) {
const { transcript } = props;
const body = useMemo(() => {
if (!transcript) return null;
return transcript.blocks.map((block) => <BlockView key={block.id} block={block} showReasoning={props.showReasoning} />);
}, [transcript, props.showReasoning]);
return (
<box title={` ${props.title} `} border borderColor={props.focused ? colors.borderFocused : colors.border} flexGrow={1} minHeight={0} flexDirection="column">
<text fg={colors.faint} flexShrink={0} height={1}>{props.subtitle}</text>
{props.error ? <text fg={colors.bad}>{props.error}</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 not shown`}</text> : null}
{body}
</scrollbox>
</box>
);
}
function BlockView({ block, showReasoning }: { readonly block: Block; readonly showReasoning: boolean }) {
switch (block.kind) {
case "user":
return (
<box marginTop={1} flexDirection="row">
<text fg={colors.user}>› </text>
<text fg={colors.user}>
<strong>{block.text.trim()}</strong>
</text>
</box>
);
case "assistant":
return (
<box marginTop={1}>
<markdown content={block.markdown || "…"} syntaxStyle={getMarkdownStyle()} streaming={block.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>
);
case "approval":
return (
<box marginTop={1} border borderColor={block.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1}>
<text fg={block.pending ? colors.warn : colors.muted}>
<strong>{block.pending ? "Approval needed: " : "Approval: "}</strong>
{block.title}
</text>
{block.detail ? <text fg={colors.muted}>{block.detail}</text> : null}
{block.pending ? <text fg={colors.text}>[y] accept [Y] accept for session [n] decline</text> : null}
</box>
);
case "question":
return (
<box marginTop={1} border borderColor={block.pending ? colors.warn : colors.border} flexDirection="column" paddingLeft={1}>
<text fg={block.pending ? colors.warn : colors.muted}>
<strong>{block.pending ? "Question for you" : "Question"}</strong>
</text>
{block.questions.map((question, index) => (
<text key={index} fg={colors.text}>{`• ${question}`}</text>
))}
{block.pending ? <text fg={colors.muted}>Answer in the T3 Code app for now.</text> : null}
</box>
);
case "notice":
return <text fg={toneColor[block.tone]}>{` ${block.text}`}</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");
}
+47
View File
@@ -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<Tone, string> = {
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;
}