Add diffs, git actions, servers, automations and a command palette

- Details rows are actionable: view the working-tree diff (whole or per
  file), run the web app's git quick action or menu after a confirmation,
  stop a local server, run or toggle an automation, open lineage threads.
- Command palette (ctrl+k or :) searching commands and threads with T3's
  own scoring.
- Subagent work entries link to their child threads; u goes to the parent.
- Threads open scrolled to the bottom.
- Mouse: thread rows, collapsed sections, details rows, palette, composer.
- The / filter opens in the thread list.
- Multi-line composer: shift+enter, ctrl+j, or a trailing backslash; it
  grows to 8 lines.
- The credential asks for filesystem:read, source-control:write and
  terminal:operate, and is reissued when a stored one lacks them.
This commit is contained in:
Callum Alpass committed 2026-11-02 18:11:48 +11:00
1 parent 248603d9ae
commit ed36949fa7
15 files changed
+1235 -192

No files matched your search

+16 -5
View File
@@ -27,11 +27,12 @@ Any mode:
| Key | Action |
| --- | --- |
| `ctrl+k` | command palette: every action below, plus thread search |
| `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. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` or `ctrl+j` adds a newline.
Typing: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` or `ctrl+j` adds a newline (`shift+enter` needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines.
Navigation:
@@ -44,17 +45,27 @@ Navigation:
| `e` | expand all folded turns and work groups |
| `o` | load earlier turns |
| `d` | show or hide thread details |
| `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `t` turns an automation on or off, `esc` comes back |
| `u` | go to the parent thread (from a fork or subagent) |
| `:` | command palette |
| `z` | show the Settled and Snoozed sections |
| `/` | filter threads by title or project |
| `/` | filter threads by title or project (the box opens at the top of the thread list) |
| `S` | stop the thread |
| `g` / `G` | top / bottom of the conversation |
| `q` | quit |
| `esc` / `q` | close the diff; otherwise `q` quits |
The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream):
- **Sidebar:** the same sections (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold.
- **Conversation:** built by the web app's timeline logic. Each finished turn's work folds into one line (`Worked for 3m 12s`), your messages are right-aligned, and a running turn shows its live step and `Working for 12s`.
- **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation.
- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `j`/`k` scroll, `esc` closes.
- **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line.
- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off).
- **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents have no details, because the thread list leaves them out.
- **Command palette:** `ctrl+k`, as in the web app. It searches commands and threads with T3's own scoring; start with `>` for commands only.
- **Mouse:** click a thread to open it, a collapsed section to unfold it, a details row to run it, the message box to type, or a palette row.
- Threads open scrolled to the bottom.
- **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off.
Long threads load as a bounded window of recent turns; press `o` for older ones. If the connection drops, tui3 reconnects with backoff and resubscribes.
@@ -62,7 +73,7 @@ Long threads load as a bounded window of recent turns; press `o` for older ones.
## 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`.
- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read`, `orchestration:operate`, `filesystem:read` (diffs), `source-control:write` (git actions) and `terminal:operate` (stopping servers), and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. A stored credential missing any of these scopes is replaced with a new one. 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.
@@ -80,4 +91,4 @@ Type errors after a bump point at the protocol changes to adapt to.
## Not yet supported
Starting new threads, editing queued messages, plan follow-ups, attachments, diffs, and the integrated terminal. Use the T3 Code app for those.
Starting new threads, editing queued messages, plan follow-ups, attachments, reviewing or commenting on diffs, and the integrated terminal. Use the T3 Code app for those.
+2 -1
View File
@@ -130,7 +130,8 @@ async function runUi(attachNeedle?: string) {
const { createRoot } = await import("@opentui/react");
const { createElement } = await import("react");
const { App } = await import("./ui/App.tsx");
const renderer = await createCliRenderer({ exitOnCtrlC: false });
// The kitty keyboard protocol lets terminals that support it send shift+enter, for newlines.
const renderer = await createCliRenderer({ exitOnCtrlC: false, useMouse: true, useKittyKeyboard: {} });
createRoot(renderer).render(createElement(App, { session, ...(attachThreadId ? { attachThreadId } : {}) }));
}
+11 -4
View File
@@ -2,8 +2,11 @@ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
/** Scopes tui3 asks for: read threads, and send/approve/interrupt them. */
export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate"] as const;
/**
* Scopes tui3 asks for: read and operate threads, read diffs, run git actions
* (commit, push, open a PR), and stop a thread's local servers.
*/
export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:operate"] as const;
export interface ServerTarget {
/** e.g. http://127.0.0.1:3773 */
@@ -15,6 +18,8 @@ export interface StoredCredential {
readonly httpBaseUrl: string;
readonly bearerToken: string;
readonly issuedAt: string;
/** Absent on credentials from before scopes were recorded. */
readonly scopes?: readonly string[];
}
const t3Home = () => process.env.T3CODE_HOME ?? join(homedir(), ".t3");
@@ -50,7 +55,9 @@ export async function readCredential(target: ServerTarget): Promise<StoredCreden
}
try {
const all: StoredCredential[] = JSON.parse(await readFile(credentialPath(), "utf8"));
return all.find((c) => c.httpBaseUrl === target.httpBaseUrl);
const stored = all.find((c) => c.httpBaseUrl === target.httpBaseUrl);
// A credential from an older tui3 lacks newer scopes; issue a fresh one.
return stored && TUI3_SCOPES.every((scope) => stored.scopes?.includes(scope)) ? stored : undefined;
} catch {
return undefined;
}
@@ -86,7 +93,7 @@ export async function issueLocalCredential(target: ServerTarget): Promise<Stored
if (code !== 0 || !token) {
throw new Error(`\`t3 auth session issue\` failed (exit ${code}): ${stderr.trim() || stdout.trim()}`);
}
const credential = { httpBaseUrl: target.httpBaseUrl, bearerToken: token, issuedAt: new Date().toISOString() };
const credential = { httpBaseUrl: target.httpBaseUrl, bearerToken: token, issuedAt: new Date().toISOString(), scopes: [...TUI3_SCOPES] };
await writeCredential(credential);
return credential;
}
+157 -55
View File
@@ -11,6 +11,14 @@ import {
type ProviderApprovalDecision,
type RuntimeRequestId,
type ThreadId,
type DiscoveredLocalServer,
type GitActionProgressEvent,
type GitRunStackedActionResult,
type GitStackedAction,
type ProjectId,
type ReviewDiffPreviewSource,
type ScheduledTask,
type ScheduledTaskId,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
WS_METHODS,
@@ -66,6 +74,22 @@ export interface VcsState {
readonly error?: string;
}
/** A server-wide list that streams whole: local servers or scheduled tasks. */
export interface FeedState<T> {
readonly status: "loading" | "live" | "error";
readonly items: readonly T[];
readonly error?: string;
}
export interface GitActionRequest {
readonly cwd: string;
readonly action: GitStackedAction;
/** Left out, the server writes one with a model. */
readonly commitMessage?: string;
readonly threadId?: ThreadId;
readonly projectId?: ProjectId;
}
type Listener<T> = (value: T) => void;
/** Streaming deltas arrive far faster than a terminal can usefully redraw. */
@@ -85,9 +109,11 @@ export function debugLog(message: string): void {
const decodeHistoryPage = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage));
interface VcsEntry {
state: VcsState;
readonly listeners: Set<Listener<VcsState>>;
/** A subscription shared by every listener of the same key, restarted after reconnects. */
interface FeedEntry {
state: unknown;
readonly listeners: Set<Listener<unknown>>;
readonly stream: () => Effect.Effect<unknown, unknown>;
fiber: Fiber.Fiber<unknown, unknown> | null;
lingerTimer: ReturnType<typeof setTimeout> | null;
}
@@ -115,7 +141,7 @@ export class T3Session {
private shell: ShellState = { status: { type: "connecting" }, snapshot: null, serverUrl: null };
private readonly shellListeners = new Set<Listener<ShellState>>();
private readonly threads = new Map<ThreadId, ThreadEntry>();
private readonly vcs = new Map<string, VcsEntry>();
private readonly feeds = new Map<string, FeedEntry>();
async start(): Promise<void> {
const scope = Effect.runSync(Scope.make());
@@ -133,7 +159,7 @@ export class T3Session {
this.setShell({ serverUrl: this.connection.target.httpBaseUrl });
this.runInScope(this.shellStream());
for (const [threadId, entry] of this.threads) entry.fiber = this.runInScope(this.threadStream(threadId));
for (const [cwd, entry] of this.vcs) entry.fiber = this.runInScope(this.vcsStream(cwd));
for (const entry of this.feeds.values()) entry.fiber = this.runInScope(entry.stream());
}
async stop(): Promise<void> {
@@ -184,26 +210,85 @@ export class T3Session {
/** Subscribes to a working directory's git status: branch, changes, and the remote's ahead/behind and PR. */
watchVcs(cwd: string, listener: Listener<VcsState>): () => void {
let entry = this.vcs.get(cwd);
if (!entry) {
entry = { state: { status: "loading", local: null, remote: null }, listeners: new Set(), fiber: null, lingerTimer: null };
this.vcs.set(cwd, entry);
if (this.connection) entry.fiber = this.runInScope(this.vcsStream(cwd));
}
if (entry.lingerTimer) clearTimeout(entry.lingerTimer);
entry.lingerTimer = null;
entry.listeners.add(listener);
listener(entry.state);
const watched = entry;
return () => {
watched.listeners.delete(listener);
if (watched.listeners.size > 0) return;
watched.lingerTimer = setTimeout(() => {
if (watched.listeners.size > 0 || this.vcs.get(cwd) !== watched) return;
this.vcs.delete(cwd);
if (watched.fiber) Effect.runFork(Fiber.interrupt(watched.fiber));
}, THREAD_LINGER_MS);
};
return this.watchFeed<VcsState>(`vcs:${cwd}`, { status: "loading", local: null, remote: null }, listener, (update) =>
this.requireConnection()
.rpc[WS_METHODS.subscribeVcsStatus]({ cwd, includeRemote: true })
.pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
switch (event._tag) {
case "snapshot":
return update({ status: "live", local: event.local, remote: event.remote });
case "localUpdated":
return update({ status: "live", local: event.local });
case "remoteUpdated":
return update({ remote: event.remote });
}
}),
),
),
);
}
/** Local servers the server has discovered, across all threads; each says which thread started it. */
watchServers(listener: Listener<FeedState<DiscoveredLocalServer>>): () => void {
return this.watchFeed<FeedState<DiscoveredLocalServer>>("servers", { status: "loading", items: [] }, listener, (update) =>
this.requireConnection()
.rpc[WS_METHODS.subscribeDiscoveredLocalServers]({})
.pipe(Stream.runForEach((list) => Effect.sync(() => update({ status: "live", items: list.servers })))),
);
}
/** Every scheduled task (automation); each names its thread, if any. */
watchAutomations(listener: Listener<FeedState<ScheduledTask>>): () => void {
return this.watchFeed<FeedState<ScheduledTask>>("automations", { status: "loading", items: [] }, listener, (update) =>
this.requireConnection()
.rpc[WS_METHODS.scheduledTasksSubscribe]({})
.pipe(Stream.runForEach((list) => Effect.sync(() => update({ status: "live", items: list.tasks })))),
);
}
/** The uncommitted diff (git diff HEAD, untracked files included), for one file or the whole tree. */
async workingTreeDiff(cwd: string, path?: string): Promise<ReviewDiffPreviewSource | null> {
const rpc = this.requireConnection().rpc;
const result = await Effect.runPromise(
rpc[WS_METHODS.reviewGetDiffPreview]({ cwd, ...(path ? { file: { path, previousPath: null, sourceKind: "working-tree" as const } } : {}) }),
);
return result.sources.find((source) => source.kind === "working-tree") ?? null;
}
/** Runs a commit / push / PR action, reporting progress as it goes. Rejects with the server's message on failure. */
async runGitAction(request: GitActionRequest, onProgress: Listener<GitActionProgressEvent>): Promise<GitRunStackedActionResult> {
const rpc = this.requireConnection().rpc;
let result: GitRunStackedActionResult | null = null;
let failure: string | null = null;
await Effect.runPromise(
rpc[WS_METHODS.gitRunStackedAction]({ actionId: crypto.randomUUID(), ...request }).pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
onProgress(event);
if (event.kind === "action_finished") result = event.result;
if (event.kind === "action_failed") failure = event.message;
}),
),
),
);
if (failure) throw new Error(failure);
if (!result) throw new Error("The git action ended without a result.");
return result;
}
setAutomationEnabled(id: ScheduledTaskId, enabled: boolean): Promise<unknown> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksSetEnabled]({ id, enabled }));
}
runAutomationNow(id: ScheduledTaskId): Promise<unknown> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksRunNow]({ id }));
}
stopServer(server: Pick<DiscoveredLocalServer, "pid" | "port">): Promise<unknown> {
if (server.pid === null) return Promise.reject(new Error("The server's process is unknown."));
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.previewStopLocalServer]({ pid: server.pid, port: server.port }));
}
/** Fetches the next page of older turns and prepends it. Resolves false when there was nothing to load. */
@@ -353,35 +438,52 @@ export class T3Session {
);
}
private vcsStream(cwd: string) {
const rpc = this.requireConnection().rpc;
return rpc[WS_METHODS.subscribeVcsStatus]({ cwd, includeRemote: true }).pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
switch (event._tag) {
case "snapshot":
return this.setVcs(cwd, { status: "live", local: event.local, remote: event.remote });
case "localUpdated":
return this.setVcs(cwd, { status: "live", local: event.local });
case "remoteUpdated":
return this.setVcs(cwd, { remote: event.remote });
}
}),
),
Effect.catchCause((cause) =>
Effect.sync(() => {
const message = prettyCause(cause);
if (!isSocketFailure(message)) this.setVcs(cwd, { status: "error", error: message });
}),
),
);
}
private setVcs(cwd: string, patch: Partial<VcsState>): void {
const entry = this.vcs.get(cwd);
if (!entry) return;
entry.state = { ...entry.state, ...patch };
for (const listener of entry.listeners) listener(entry.state);
/**
* Shares one stream per key among listeners and keeps it THREAD_LINGER_MS after the last
* leaves. `stream` applies updates through the callback it's given.
*/
private watchFeed<S extends { readonly status: string; readonly error?: string }>(
key: string,
initial: S,
listener: Listener<S>,
stream: (update: (patch: Partial<S>) => void) => Effect.Effect<unknown, unknown>,
): () => void {
let entry = this.feeds.get(key);
if (!entry) {
const update = (patch: Partial<S>) => {
const current = this.feeds.get(key);
if (!current) return;
current.state = { ...(current.state as S), ...patch };
for (const notify of current.listeners) notify(current.state);
};
const run = () =>
stream(update).pipe(
Effect.catchCause((cause) =>
Effect.sync(() => {
const message = prettyCause(cause);
if (!isSocketFailure(message)) update({ status: "error", error: message } as Partial<S>);
}),
),
);
entry = { state: initial, listeners: new Set(), stream: run, fiber: null, lingerTimer: null };
this.feeds.set(key, entry);
if (this.connection) entry.fiber = this.runInScope(run());
}
if (entry.lingerTimer) clearTimeout(entry.lingerTimer);
entry.lingerTimer = null;
const untyped = listener as Listener<unknown>;
entry.listeners.add(untyped);
listener(entry.state as S);
const watched = entry;
return () => {
watched.listeners.delete(untyped);
if (watched.listeners.size > 0) return;
watched.lingerTimer = setTimeout(() => {
if (watched.listeners.size > 0 || this.feeds.get(key) !== watched) return;
this.feeds.delete(key);
if (watched.fiber) Effect.runFork(Fiber.interrupt(watched.fiber));
}, THREAD_LINGER_MS);
};
}
private connectionLost(message: string): void {
@@ -407,7 +509,7 @@ export class T3Session {
this.scope = null;
this.connection = null;
for (const entry of this.threads.values()) entry.fiber = null;
for (const entry of this.vcs.values()) entry.fiber = null;
for (const entry of this.feeds.values()) entry.fiber = null;
if (scope) await Effect.runPromise(Scope.close(scope, Exit.void));
}
+137 -18
View File
@@ -1,8 +1,19 @@
import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell } from "@t3tools/contracts";
import type {
DiscoveredLocalServer,
GitStackedAction,
OrchestrationProjectShell,
OrchestrationV2ShellSnapshot,
OrchestrationV2Subagent,
OrchestrationV2ThreadShell,
ScheduledTask,
ThreadId,
VcsStatusResult,
} from "@t3tools/contracts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
import { homedir } from "node:os";
import type { VcsState } from "../client/session.ts";
import { buildMenuItems, resolveQuickAction } from "../../vendor/t3code/apps/web/src/components/GitActionsControl.logic.ts";
import type { StatusTone } from "./threads.ts";
/** The web's thread details card, reduced to what a terminal column can show. Sections with nothing to say are left out. */
@@ -25,13 +36,63 @@ export interface ThreadDetails {
/** The branch's total against its base, when it differs from the working tree's. */
readonly branchTotal: { readonly baseRef: string | null; readonly insertions: number; readonly deletions: number } | null;
} | null;
readonly lineage: readonly { readonly glyph: string; readonly text: string }[];
/** The web's git quick action and menu: commit, push, create PR. */
readonly git: {
readonly quick: GitAction | null;
/** Why there's no quick action ("Up to date", "Sync ref"), as the web's disabled button says. */
readonly hint: string | null;
readonly menu: readonly GitAction[];
} | null;
readonly lineage: readonly LineageLine[];
readonly servers: readonly { readonly server: DiscoveredLocalServer; readonly label: string }[];
readonly automations: readonly AutomationLine[];
readonly background: readonly { readonly glyph: string; readonly text: string }[];
readonly goal: { readonly objective: string; readonly status: string; readonly tone: StatusTone } | null;
/** Git status failed, or the folder isn't a repository. */
readonly vcsNote: string | null;
}
export interface GitAction {
readonly action: GitStackedAction;
readonly label: string;
/** Commit actions take a message; the others don't. */
readonly commits: boolean;
}
export interface LineageLine {
readonly glyph: string;
readonly text: string;
/** The thread it links to, when there's one to open. */
readonly threadId?: ThreadId;
}
export interface AutomationLine {
readonly task: ScheduledTask;
readonly schedule: string;
readonly status: string;
readonly tone: StatusTone;
}
/** Something in the panel you can select and activate, in display order. */
export type DetailsAction =
| { readonly kind: "diff"; readonly id: string; readonly path: string | null }
| { readonly kind: "git"; readonly id: string; readonly git: GitAction }
| { readonly kind: "thread"; readonly id: string; readonly threadId: ThreadId }
| { readonly kind: "server"; readonly id: string; readonly server: DiscoveredLocalServer }
| { readonly kind: "automation"; readonly id: string; readonly task: ScheduledTask };
export interface DetailsInput {
readonly thread: OrchestrationV2ThreadShell;
readonly project: OrchestrationProjectShell | undefined;
readonly vcs: VcsState | null;
readonly snapshot: OrchestrationV2ShellSnapshot | null;
/** From the thread's projection, when it's loaded: names idle subagents the shell leaves out. */
readonly subagents?: readonly OrchestrationV2Subagent[];
readonly servers?: readonly DiscoveredLocalServer[];
readonly automations?: readonly ScheduledTask[];
readonly now?: number;
}
export interface PullRequestLine {
readonly number: number;
readonly title: string | null;
@@ -52,12 +113,9 @@ export function detailsCwd(thread: OrchestrationV2ThreadShell, project: Orchestr
return thread.worktreePath ?? project?.workspaceRoot ?? null;
}
export function threadDetails(
thread: OrchestrationV2ThreadShell,
project: OrchestrationProjectShell | undefined,
vcs: VcsState | null,
snapshot: OrchestrationV2ShellSnapshot | null,
): ThreadDetails {
export function threadDetails(input: DetailsInput): ThreadDetails {
const { thread, project, vcs, snapshot } = input;
const now = input.now ?? Date.now();
const local = vcs?.local?.isRepo ? vcs.local : null;
const remote = local ? (vcs?.remote ?? null) : null;
const path = detailsCwd(thread, project) ?? "";
@@ -90,16 +148,30 @@ export function threadDetails(
const threads = snapshot?.threads ?? [];
const titleOf = (id: string) => threads.find((other) => other.id === id)?.title ?? "another thread";
const lineage: { glyph: string; text: string }[] = [];
const lineage: LineageLine[] = [];
const parentId = thread.lineage.parentThreadId ?? (thread.forkedFrom?.type === "run" ? thread.forkedFrom.threadId : null);
if (parentId) lineage.push({ glyph: "↰", text: `${thread.lineage.relationshipToParent === "subagent" ? "subagent of" : "forked from"} ${quote(titleOf(parentId))}` });
const forks = threads.filter((other) => other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "fork" && other.deletedAt === null);
if (forks.length > 0) lineage.push({ glyph: "↳", text: forks.length === 1 ? `forked into ${quote(forks[0]!.title)}` : `${forks.length} forks` });
const subagents = threads.filter((other) => other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "subagent");
const runningSubagents = (thread.pendingBackgroundTasks ?? []).filter((task) => task.kind === "subagent").length;
// Idle subagents are left out of the shell, so the running count can exceed what's listed.
const subagentCount = Math.max(subagents.length, runningSubagents);
if (subagentCount > 0) lineage.push({ glyph: "↳", text: `${plural(subagentCount, "subagent")}${runningSubagents > 0 ? ` (${runningSubagents} running)` : ""}` });
if (parentId) lineage.push({ glyph: "↰", text: `${thread.lineage.relationshipToParent === "subagent" ? "subagent of" : "forked from"} ${quote(titleOf(parentId))}`, threadId: parentId });
for (const fork of threads.filter((other) => other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "fork" && other.deletedAt === null)) {
lineage.push({ glyph: "↳", text: `fork ${quote(fork.title)}`, threadId: fork.id });
}
// The projection names every subagent; the shell only the busy ones.
const subagents = new Map<ThreadId, string>();
for (const subagent of input.subagents ?? []) if (subagent.childThreadId) subagents.set(subagent.childThreadId, subagent.title ?? titleOf(subagent.childThreadId));
for (const other of threads) if (other.lineage.parentThreadId === thread.id && other.lineage.relationshipToParent === "subagent") subagents.set(other.id, other.title);
const running = new Set(threads.filter((other) => other.activeRunId !== null).map((other) => other.id as string));
for (const [threadId, title] of subagents) lineage.push({ glyph: running.has(threadId) ? "◐" : "↳", text: `subagent ${quote(title)}`, threadId });
const unnamed = (thread.pendingBackgroundTasks ?? []).filter((task) => task.kind === "subagent" && !(task.childThreadId && subagents.has(task.childThreadId))).length;
if (unnamed > 0) lineage.push({ glyph: "◐", text: `${plural(unnamed, "subagent")} running` });
const git = local ? gitActions({ ...local, ...(remote ?? { hasUpstream: false, aheadCount: 0, behindCount: 0, pr: null }) }) : null;
const servers = (input.servers ?? [])
.filter((server) => server.terminal?.threadId === thread.id || server.agent?.threadId === thread.id)
.map((server) => ({ server, label: `${server.url.replace(/^https?:\/\//, "")}${server.processName ? ` ${server.processName}` : ""}` }));
const automations = (input.automations ?? [])
.filter((task) => task.threadId === thread.id)
.map((task) => automationLine(task, now));
const background = (thread.pendingBackgroundTasks ?? [])
.filter((task) => task.kind !== "subagent")
@@ -114,9 +186,56 @@ export function threadDetails(
: null;
const vcsNote = vcs?.status === "error" ? "Git status unavailable" : vcs?.local && !vcs.local.isRepo ? "Not a git repository" : null;
return { workspace: { path: tildify(path), worktree: thread.worktreePath !== null && project !== undefined && thread.worktreePath !== project.workspaceRoot, model, mode }, branch, changes, lineage, background, goal, vcsNote };
return { git, servers, automations, workspace: { path: tildify(path), worktree: thread.worktreePath !== null && project !== undefined && thread.worktreePath !== project.workspaceRoot, model, mode }, branch, changes, lineage, background, goal, vcsNote };
}
/** Every selectable line, top to bottom, as the panel shows them. */
export function detailsActions(details: ThreadDetails): DetailsAction[] {
const actions: DetailsAction[] = [];
if (details.git?.quick) actions.push({ kind: "git", id: `git:quick:${details.git.quick.action}`, git: details.git.quick });
for (const git of details.git?.menu ?? []) actions.push({ kind: "git", id: `git:${git.action}`, git });
if (details.changes && details.changes.files.length > 0) {
actions.push({ kind: "diff", id: "diff:*", path: null });
for (const file of details.changes.files.slice(0, MAX_DETAIL_FILES)) actions.push({ kind: "diff", id: `diff:${file.path}`, path: file.path });
}
for (const line of details.lineage) if (line.threadId) actions.push({ kind: "thread", id: `thread:${line.threadId}`, threadId: line.threadId });
for (const { server } of details.servers) actions.push({ kind: "server", id: `server:${server.port}`, server });
for (const { task } of details.automations) actions.push({ kind: "automation", id: `automation:${task.id}`, task });
return actions;
}
/** Files listed under Changes before the rest fold into a count. */
export const MAX_DETAIL_FILES = 8;
const COMMIT_ACTIONS: ReadonlySet<GitStackedAction> = new Set(["commit", "commit_push", "commit_push_pr"]);
const MENU_ACTIONS: Record<string, GitStackedAction> = { commit: "commit", push: "push", pr: "create_pr" };
/** The web's GitActionsControl logic: one quick action, plus the enabled menu items it doesn't already cover. */
function gitActions(status: VcsStatusResult): NonNullable<ThreadDetails["git"]> {
const quickAction = resolveQuickAction(status, false, status.isDefaultRef, status.hasPrimaryRemote);
const quick = quickAction.kind === "run_action" && quickAction.action && !quickAction.disabled ? { action: quickAction.action, label: quickAction.label, commits: COMMIT_ACTIONS.has(quickAction.action) } : null;
const menu = buildMenuItems(status, false, status.hasPrimaryRemote)
.filter((item) => !item.disabled && MENU_ACTIONS[item.id] && MENU_ACTIONS[item.id] !== quick?.action)
.map((item) => ({ action: MENU_ACTIONS[item.id]!, label: item.label, commits: item.id === "commit" }));
return { quick, hint: quick ? null : quickAction.hint ?? quickAction.label, menu };
}
function automationLine(task: ScheduledTask, now: number): AutomationLine {
const schedule =
task.schedule.type === "interval"
? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}`
: task.schedule.type === "fixed_time"
? `${task.schedule.weekdays && task.schedule.weekdays.length < 7 ? task.schedule.weekdays.map((day) => WEEKDAYS[day]).join(",") + " " : "daily "}${task.schedule.timeOfDay}`
: "on webhook";
if (!task.enabled) return { task, schedule, status: "off", tone: "muted" };
if (task.lastRunStatus === "running") return { task, schedule, status: "running", tone: "info" };
if (task.lastRunStatus === "failed") return { task, schedule, status: "failed", tone: "bad" };
const next = task.nextRunAt ? Date.parse(String(task.nextRunAt)) : NaN;
return { task, schedule, status: Number.isFinite(next) && next > now ? `in ${formatWorkingDurationLabel(next - now)}` : "on", tone: "good" };
}
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
/** The remote's PR for the branch, else the newest PR the thread linked. */
function pullRequestLine(thread: OrchestrationV2ThreadShell, remote: VcsState["remote"]): PullRequestLine | null {
if (remote?.pr) {
+90
View File
@@ -0,0 +1,90 @@
import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts";
import { foldSearchQuery, scoreSearchTerms, scoreThreadSearch, type ThreadSearchSubject } from "@t3tools/shared/paletteSearch";
import * as DateTime from "effect/DateTime";
import { projectLabel } from "./threads.ts";
/** A command the palette can run; `when` false hides it. */
export interface PaletteCommand {
readonly id: string;
readonly title: string;
/** The key that does the same, shown on the right. */
readonly shortcut?: string;
/** Extra words it answers to. */
readonly keywords?: readonly string[];
}
export type PaletteEntry =
| { readonly kind: "command"; readonly command: PaletteCommand }
| { readonly kind: "thread"; readonly threadId: ThreadId; readonly title: string; readonly project: string; readonly subagent: boolean };
export interface PaletteGroup {
readonly label: string;
readonly entries: readonly PaletteEntry[];
}
/** Threads shown before you type, as the web palette's recent threads. */
const RECENT_THREADS = 8;
/** As the web palette's PALETTE_THREAD_LIMIT. */
const THREAD_LIMIT = 20;
/**
* The web palette's search: commands by name and keywords, threads by T3's own thread
* scoring (title, branch, project, PRs, recent use). `>` searches commands only.
*/
export function paletteGroups(input: {
readonly query: string;
readonly commands: readonly PaletteCommand[];
readonly snapshot: OrchestrationV2ShellSnapshot | null;
readonly now?: number;
}): PaletteGroup[] {
const now = input.now ?? Date.now();
const commandsOnly = input.query.startsWith(">");
const query = foldSearchQuery(commandsOnly ? input.query.slice(1) : input.query);
const commands = query
? input.commands
.map((command) => ({ command, match: scoreSearchTerms(query, [command.title, ...(command.keywords ?? [])], { typos: true }) }))
.filter((candidate) => candidate.match !== null)
.sort((a, b) => b.match!.score - a.match!.score)
.map(({ command }) => command)
: input.commands;
const groups: PaletteGroup[] = [];
if (commands.length > 0) groups.push({ label: "Commands", entries: commands.map((command) => ({ kind: "command", command })) });
if (commandsOnly || !input.snapshot) return groups;
const projects = new Map<string, OrchestrationProjectShell>(input.snapshot.projects.map((project) => [project.id, project]));
const candidates = input.snapshot.threads
.filter((thread) => thread.archivedAt === null && thread.deletedAt === null)
.map((thread) => {
const project = projectLabel(projects.get(thread.projectId));
const subject: ThreadSearchSubject = {
id: thread.id,
title: thread.title,
branch: thread.branch,
projectTitle: project,
pullRequests: (thread.pullRequests ?? []).map((pr) => ({ number: pr.number, title: pr.snapshot?.title ?? null, references: [pr.url] })),
activityAt: DateTime.toEpochMillis(thread.latestUserMessageAt ?? thread.updatedAt),
opens: thread.opens ?? null,
};
return { thread, project, subject };
});
const ranked = query
? candidates
.map((candidate) => ({ candidate, match: scoreThreadSearch(query, candidate.subject, now) }))
.filter((scored) => scored.match !== null)
.sort((a, b) => b.match!.score - a.match!.score)
.slice(0, THREAD_LIMIT)
.map(({ candidate }) => candidate)
: candidates.sort((a, b) => (b.subject.activityAt ?? 0) - (a.subject.activityAt ?? 0)).slice(0, RECENT_THREADS);
if (ranked.length > 0) {
groups.push({
label: query ? "Threads" : "Recent threads",
entries: ranked.map(({ thread, project }) => ({ kind: "thread", threadId: thread.id, title: thread.title || "New thread", project, subagent: thread.lineage.relationshipToParent === "subagent" })),
});
}
return groups;
}
export function paletteEntries(groups: readonly PaletteGroup[]): PaletteEntry[] {
return groups.flatMap((group) => group.entries);
}
+434 -66
View File
@@ -8,29 +8,41 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "@t3tools/client-runtime/state/pending-user-input";
import type { ProviderApprovalDecision, ThreadId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef, useState } from "react";
import type { DiscoveredLocalServer, ProviderApprovalDecision, ScheduledTask, ThreadId } from "@t3tools/contracts";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts";
import { detailsCwd, RUNTIME_MODE_LABELS, threadDetails } from "../model/details.ts";
import type { FeedState, ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts";
import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts";
import { paletteEntries, paletteGroups, type PaletteCommand } from "../model/palette.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts";
import { threadRows, type Section } from "../model/threads.ts";
import { QuestionPanel } from "./QuestionPanel.tsx";
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
import { DetailsPanel } from "./DetailsPanel.tsx";
import { DiffView, type DiffState } from "./DiffView.tsx";
import { Palette } from "./Palette.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx";
import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx";
import { ThreadView } from "./ThreadView.tsx";
/** "input": typing goes to the composer. "nav": single keys move, scroll, approve. */
type Mode = "input" | "nav" | "filter";
/**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve.
* "details": j/k move through the details panel. The rest are overlays with their own input.
*/
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "confirm";
/** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120;
/** Opening a thread marks it read once you've stayed this long, as in the web app. */
const VISIT_DELAY_MS = 1_500;
const MAX_COMPOSER_LINES = 6;
const MAX_COMPOSER_LINES = 8;
/** Sections folded to a count unless you filter or press z, like the web sidebar's. */
const FOLDED_SECTIONS: readonly Section[] = ["snoozed", "settled"];
/** The details column opens by itself on terminals at least this wide. */
const DETAILS_AUTO_WIDTH = 160;
const DETAILS_WIDTH = 38;
/** Below this, the details panel takes the conversation's place instead of a column beside it. */
const MIN_CONVERSATION_WIDTH = 70;
const COMPOSER_KEYS = [
{ name: "return", action: "submit" },
@@ -38,12 +50,6 @@ const COMPOSER_KEYS = [
{ name: "j", ctrl: true, action: "newline" },
] as const;
/** The details column opens by itself on terminals at least this wide. */
const DETAILS_AUTO_WIDTH = 160;
const DETAILS_WIDTH = 36;
/** Below this, the details panel takes the conversation's place instead of a column beside it. */
const MIN_CONVERSATION_WIDTH = 70;
interface QuestionDraft {
readonly index: number;
readonly answers: Record<string, PendingUserInputDraftAnswer>;
@@ -51,16 +57,24 @@ interface QuestionDraft {
export function App(props: { readonly session: T3Session; readonly attachThreadId?: ThreadId }) {
const { session, attachThreadId } = props;
const attached = attachThreadId !== undefined;
const renderer = useRenderer();
const { width, height } = useTerminalDimensions();
const [shell, setShell] = useState<ShellState>(session.getShell());
// Any thread, listed or not: subagents open here too.
const [selectedId, setSelectedId] = useState<ThreadId | undefined>(attachThreadId);
const [mode, setMode] = useState<Mode>(attachThreadId ? "input" : "nav");
const [mode, setMode] = useState<Mode>(attached ? "input" : "nav");
const [filter, setFilter] = useState("");
const [showFolded, setShowFolded] = useState(false);
const [expandAll, setExpandAll] = useState(false);
/** null follows the terminal width; d sets it for the rest of the session. */
const [detailsPref, setDetailsPref] = useState<boolean | null>(null);
const [detailsSelected, setDetailsSelected] = useState<string | null>(null);
const [diff, setDiff] = useState<DiffState | null>(null);
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
const [confirmMessage, setConfirmMessage] = useState("");
const [paletteQuery, setPaletteQuery] = useState("");
const [paletteIndex, setPaletteIndex] = useState(0);
const [flash, setFlash] = useState<{ text: string; bad?: boolean } | null>(null);
const [composerLines, setComposerLines] = useState(1);
const [composerEmpty, setComposerEmpty] = useState(true);
@@ -69,6 +83,8 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const scrollRef = useRef<ScrollBoxRenderable | null>(null);
const composerRef = useRef<TextareaRenderable | null>(null);
const drafts = useRef(new Map<string, string>());
/** Where mode returns to when an overlay closes. */
const returnMode = useRef<Mode>("nav");
useEffect(() => session.onShell(setShell), [session]);
// Drives "Working for 12s" and the sidebar's durations.
@@ -85,18 +101,21 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
[allRows, unfold],
);
// Selection is a thread id, not an index, so the list can reorder underneath it.
const selectedIndex = Math.max(0, rows.findIndex((row) => row.thread.id === selectedId));
const threadId = attachThreadId ?? rows[selectedIndex]?.thread.id;
const threadId = selectedId ?? rows[0]?.thread.id;
const selectedIndex = rows.findIndex((row) => row.thread.id === threadId);
const threadRow = allRows.find((row) => row.thread.id === threadId);
const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId);
// Pin the initial selection to a thread, or it would follow whatever sorts first.
useEffect(() => {
if (selectedId === undefined && rows[0]) setSelectedId(rows[0].thread.id);
}, [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);
};
const openThread = useCallback((id: ThreadId) => {
setSelectedId(id);
setDiff(null);
setDetailsSelected(null);
setMode((current) => (current === "details" ? "nav" : current));
}, []);
const [watchedId, setWatchedId] = useState(threadId);
useEffect(() => {
@@ -119,20 +138,6 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
return () => clearTimeout(timer);
}, [session, watchedId, unread]);
const showDetails = detailsPref ?? width >= DETAILS_AUTO_WIDTH;
const project = threadShell ? shell.snapshot?.projects.find((candidate) => candidate.id === threadShell.projectId) : undefined;
const vcsCwd = threadShell ? detailsCwd(threadShell, project) : null;
const [vcs, setVcs] = useState<{ cwd: string; state: VcsState } | null>(null);
useEffect(() => {
if (!showDetails || !vcsCwd || shell.status.type !== "live") return;
return session.watchVcs(vcsCwd, (state) => setVcs({ cwd: vcsCwd, state }));
}, [session, showDetails, vcsCwd, shell.status.type]);
const vcsState = vcs?.cwd === vcsCwd ? vcs.state : null;
const details = useMemo(
() => (showDetails && threadShell ? threadDetails(threadShell, project, vcsState, shell.snapshot) : null),
[showDetails, threadShell, project, vcsState, shell.snapshot],
);
const previousTimeline = useRef<{ id: string; timeline: Timeline } | null>(null);
const timeline = useMemo(() => {
if (!thread?.projection || !watchedId) return null;
@@ -147,6 +152,70 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const questionDraft = pendingInput ? (questionDrafts.get(pendingInput.requestId) ?? { index: 0, answers: {} }) : undefined;
const working = current?.isWorking ?? false;
// A thread opens at its latest message: once its first snapshot renders, jump to the bottom.
const loaded = current !== null;
useEffect(() => {
if (!loaded) return;
const timer = setTimeout(() => scrollRef.current?.scrollTo(scrollRef.current.scrollHeight), 0);
return () => clearTimeout(timer);
}, [loaded, watchedId]);
const projection = watchedId === threadId ? thread?.projection : null;
const appThread = projection?.thread;
const title = threadShell?.title ?? appThread?.title ?? "Thread";
const parentId = (threadShell?.lineage ?? appThread?.lineage)?.parentThreadId ?? null;
const parent = parentId
? { threadId: parentId, title: shell.snapshot?.threads.find((other) => other.id === parentId)?.title ?? "Parent thread" }
: undefined;
const move = (delta: number) => {
// From a subagent, which isn't listed, j/k carry on from its parent's row.
const parentIndex = rows.findIndex((row) => row.thread.id === parentId);
const from = selectedIndex >= 0 ? selectedIndex : parentIndex >= 0 ? parentIndex : delta > 0 ? -1 : rows.length;
const next = rows[Math.min(rows.length - 1, Math.max(0, from + delta))];
if (next) openThread(next.thread.id);
};
// Details: git status for the thread's folder, plus the server-wide servers and automations lists.
const showDetails = detailsPref ?? width >= DETAILS_AUTO_WIDTH;
const project = threadShell ? shell.snapshot?.projects.find((candidate) => candidate.id === threadShell.projectId) : undefined;
const vcsCwd = threadShell ? detailsCwd(threadShell, project) : null;
const live = shell.status.type === "live";
const [vcs, setVcs] = useState<{ cwd: string; state: VcsState } | null>(null);
useEffect(() => {
if (!showDetails || !vcsCwd || !live) return;
return session.watchVcs(vcsCwd, (state) => setVcs({ cwd: vcsCwd, state }));
}, [session, showDetails, vcsCwd, live]);
const [servers, setServers] = useState<FeedState<DiscoveredLocalServer> | null>(null);
const [automations, setAutomations] = useState<FeedState<ScheduledTask> | null>(null);
useEffect(() => {
if (!live) return;
const stopServers = session.watchServers(setServers);
const stopAutomations = session.watchAutomations(setAutomations);
return () => {
stopServers();
stopAutomations();
};
}, [session, live]);
const vcsState = vcs?.cwd === vcsCwd ? vcs.state : null;
const details = useMemo(
() =>
threadShell
? threadDetails({
thread: threadShell,
project,
vcs: vcsState,
snapshot: shell.snapshot,
subagents: projection?.subagents ?? [],
servers: servers?.items ?? [],
automations: automations?.items ?? [],
now,
})
: null,
[threadShell, project, vcsState, shell.snapshot, projection?.subagents, servers, automations, now],
);
const actions = useMemo(() => (details ? detailsActions(details) : []), [details]);
const say = (text: string, bad = false) => {
setFlash({ text, bad });
setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), 4000);
@@ -154,7 +223,7 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const run = (label: string, action: () => Promise<unknown>) => {
action().then(
() => say(label),
(error) => say(`${label} failed: ${error instanceof Error ? error.message : String(error)}`, true),
(error) => say(`${label} failed: ${messageOf(error)}`, true),
);
};
const respond = (decision: ProviderApprovalDecision) => {
@@ -162,6 +231,100 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingApproval.requestId, decision));
};
const confirm = (next: Confirmation) => {
if (mode !== "confirm" && mode !== "palette") returnMode.current = mode;
setConfirmMessage("");
setConfirmation(next);
setMode("confirm");
};
const closeOverlay = () => {
setConfirmation(null);
setMode(returnMode.current);
};
const openDiff = (path: string | null) => {
if (!vcsCwd) return;
const cwd = vcsCwd;
setDiff({ cwd, path, status: "loading" });
session.workingTreeDiff(cwd, path ?? undefined).then(
(source) => setDiff((value) => (value?.cwd === cwd && value.path === path ? { cwd, path, status: "ready", patch: source?.diff ?? "", truncated: source?.truncated ?? false } : value)),
(error) => setDiff((value) => (value?.cwd === cwd && value.path === path ? { cwd, path, status: "error", error: messageOf(error) } : value)),
);
};
const runGit = (git: GitAction) => {
if (!vcsCwd || !threadShell) return;
const cwd = vcsCwd;
const branch = details?.branch?.name;
const onDefault = vcsState?.local?.isDefaultRef === true;
confirm({
title: `${git.label}?`,
detail: `${branch ? `On ${branch}` : "In"} · ${details?.workspace.path ?? cwd}${onDefault && git.action !== "create_pr" ? " · this is the default branch" : ""}`,
...(git.commits ? { message: { placeholder: "Leave blank to have one written for you" } } : {}),
confirmLabel: git.label.toLowerCase(),
run: (message) => {
say(`${git.label}…`);
session
.runGitAction(
{ cwd, action: git.action, threadId: threadShell.id, projectId: threadShell.projectId, ...(git.commits && message.trim() ? { commitMessage: message.trim() } : {}) },
(event) => {
if (event.kind === "phase_started") setFlash({ text: `${event.label}…` });
if (event.kind === "hook_started") setFlash({ text: `Running ${event.hookName} hook…` });
},
)
.then(
(result) => say(result.toast.description ? `${result.toast.title}: ${result.toast.description}` : result.toast.title),
(error) => say(`${git.label} failed: ${messageOf(error)}`, true),
);
},
});
};
const stopServer = (server: DiscoveredLocalServer) =>
confirm({
title: `Stop ${server.url}?`,
...(server.processName ? { detail: `${server.processName}${server.pid ? ` (pid ${server.pid})` : ""}` } : {}),
confirmLabel: "stop",
run: () => run("Server stopped", () => session.stopServer(server)),
});
const runAutomation = (task: ScheduledTask) =>
confirm({ title: `Run "${task.title}" now?`, detail: firstLine(task.prompt), confirmLabel: "run", run: () => run("Automation started", () => session.runAutomationNow(task.id)) });
const toggleAutomation = (task: ScheduledTask) => run(task.enabled ? "Automation turned off" : "Automation turned on", () => session.setAutomationEnabled(task.id, !task.enabled));
const activate = (action: DetailsAction) => {
setDetailsSelected(action.id);
switch (action.kind) {
case "diff":
return openDiff(action.path);
case "git":
return runGit(action.git);
case "thread":
return openThread(action.threadId);
case "server":
return stopServer(action.server);
case "automation":
return runAutomation(action.task);
}
};
const activateById = (id: string) => {
const action = actions.find((candidate) => candidate.id === id);
if (!action) return;
if (action.kind !== "thread") setMode("details");
activate(action);
};
const moveDetails = (delta: number) => {
if (actions.length === 0) return;
const index = actions.findIndex((action) => action.id === detailsSelected);
const next = actions[index < 0 ? (delta > 0 ? 0 : actions.length - 1) : Math.min(actions.length - 1, Math.max(0, index + delta))];
if (next) setDetailsSelected(next.id);
};
const focusDetails = () => {
if (!threadShell) return;
if (!showDetails) setDetailsPref(true);
if (!actions.some((action) => action.id === detailsSelected)) setDetailsSelected(actions[0]?.id ?? null);
setMode("details");
};
const clearComposer = () => {
composerRef.current?.setText("");
if (threadId) drafts.current.delete(threadId);
@@ -200,7 +363,16 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
/** Enter in the composer; `alternate` is alt+enter, which flips steer and queue. */
const submit = (alternate = false) => {
const text = composerRef.current?.plainText.trim() ?? "";
const composer = composerRef.current;
const raw = composer?.plainText ?? "";
// A trailing backslash continues onto a new line, for terminals that can't send shift+enter.
if (!alternate && composer && raw.endsWith("\\")) {
composer.setText(raw.slice(0, -1));
composer.gotoBufferEnd();
composer.newLine();
return;
}
const text = raw.trim();
if (!threadId) return;
if (pendingInput && questionDraft) {
const question = pendingInput.questions[questionDraft.index];
@@ -222,7 +394,7 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const loadEarlier = () => {
if (!watchedId) return;
session.loadEarlier(watchedId).catch((error) => say(`Could not load earlier turns: ${error instanceof Error ? error.message : String(error)}`, true));
session.loadEarlier(watchedId).catch((error) => say(`Could not load earlier turns: ${messageOf(error)}`, true));
};
const quit = () => {
@@ -234,18 +406,93 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
const scrollPage = (direction: 1 | -1) => scrollRef.current?.scrollBy(direction * Math.max(1, height - 10));
// The command palette: everything the keys do, plus what the details panel offers.
const commands: (PaletteCommand & { readonly run: () => void })[] = [];
const command = (id: string, label: string, action: () => void, extra: Omit<PaletteCommand, "id" | "title"> = {}) => commands.push({ id, title: label, run: action, ...extra });
if (pendingApproval) {
command("approve", "Approve request", () => respond("accept"), { shortcut: "y" });
command("approve-session", "Always allow this session", () => respond("acceptForSession"), { shortcut: "Y" });
command("decline", "Decline request", () => respond("decline"), { shortcut: "n" });
}
if (threadId && pendingInput?.dismissible) command("dismiss", "Dismiss question", () => run("Dismissed", () => session.dismissQuestion(threadId, pendingInput.requestId)), { shortcut: "x" });
if (threadId) command("type", "Write a message", () => setMode("input"), { shortcut: "i", keywords: ["compose", "send", "steer"] });
if (threadId && working) command("stop", "Stop thread", () => run("Stop requested", () => session.stopThread(threadId)), { shortcut: "S", keywords: ["interrupt", "cancel"] });
if (details?.changes && details.changes.files.length > 0) command("diff", "View uncommitted changes", () => openDiff(null), { keywords: ["diff", "changes"] });
for (const action of actions) {
if (action.kind === "git") command(action.id, `Git: ${action.git.label}`, () => runGit(action.git), { keywords: ["commit", "push", "pull request", "pr"] });
if (action.kind === "server") command(action.id, `Stop server ${action.server.url}`, () => stopServer(action.server), { keywords: ["port", "kill"] });
if (action.kind === "automation") {
command(action.id, `Run automation: ${action.task.title}`, () => runAutomation(action.task), { keywords: ["scheduled", "task"] });
command(`${action.id}:toggle`, `${action.task.enabled ? "Turn off" : "Turn on"} automation: ${action.task.title}`, () => toggleAutomation(action.task), { keywords: ["scheduled", "task", "enable", "disable"] });
}
}
if (parent) command("parent", `Go to parent: ${parent.title}`, () => openThread(parent.threadId), { shortcut: "u" });
command("details", showDetails ? "Hide thread details" : "Show thread details", () => setDetailsPref(!showDetails), { shortcut: "d", keywords: ["panel", "info"] });
if (threadShell) command("focus-details", "Focus thread details", focusDetails, { shortcut: "l" });
command("expand", expandAll ? "Collapse work" : "Expand all work", () => setExpandAll(!expandAll), { shortcut: "e", keywords: ["fold", "tool calls"] });
if (thread?.history.hasMore) command("earlier", "Load earlier turns", loadEarlier, { shortcut: "o", keywords: ["history", "older"] });
if (!attached) {
command("filter", "Filter threads", () => setMode("filter"), { shortcut: "/", keywords: ["search"] });
command("settled", showFolded ? "Hide settled threads" : "Show settled threads", () => setShowFolded(!showFolded), { shortcut: "z", keywords: ["snoozed", "archive"] });
}
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}`).join("|");
// eslint-disable-next-line react-hooks/exhaustive-deps -- commands are rebuilt each render; commandKey tracks what changed.
const groups = useMemo(() => (mode === "palette" ? paletteGroups({ query: paletteQuery, commands, snapshot: shell.snapshot, now }) : []), [mode, paletteQuery, commandKey, shell.snapshot]);
const entries = paletteEntries(groups);
const openPalette = () => {
if (mode !== "palette" && mode !== "confirm") returnMode.current = mode === "filter" ? "nav" : mode;
setPaletteQuery("");
setPaletteIndex(0);
setMode("palette");
};
const pick = (index: number) => {
const entry = entries[index];
if (!entry) return;
setMode(returnMode.current === "details" ? "nav" : returnMode.current);
if (entry.kind === "thread") return openThread(entry.threadId);
commands.find((candidate) => candidate.id === entry.command.id)?.run();
};
/** 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;
if (key.ctrl && key.name === "k") return openPalette(), true;
// One-line inputs keep ctrl+u and ctrl+d for editing.
const lineInput = mode === "filter" || mode === "palette" || mode === "confirm";
if (key.name === "pagedown" || (!lineInput && key.ctrl && key.name === "d")) return scrollPage(1), true;
if (key.name === "pageup" || (!lineInput && key.ctrl && key.name === "u")) return scrollPage(-1), true;
if (!attached && ((key.ctrl && key.name === "n") || (key.meta && key.name === "down"))) return move(1), true;
if (!attached && ((key.ctrl && key.name === "p") || (key.meta && key.name === "up"))) return move(-1), true;
if (mode === "input" && key.meta && key.name === "return") return submit(true), true;
return false;
};
useKeyboard((key) => {
if (mode === "palette") {
if (key.ctrl && key.name === "c") return quit();
if (key.name === "escape" || (key.ctrl && key.name === "k")) setMode(returnMode.current);
else if (key.name === "down" || (key.ctrl && key.name === "n")) setPaletteIndex((index) => Math.min(entries.length - 1, index + 1));
else if (key.name === "up" || (key.ctrl && key.name === "p")) setPaletteIndex((index) => Math.max(0, index - 1));
else return;
return key.preventDefault();
}
if (mode === "confirm") {
if (key.ctrl && key.name === "c") return quit();
if (key.name === "escape") {
closeOverlay();
return key.preventDefault();
}
// Without a message box, enter confirms here; with one, the box's submit does.
if (key.name === "return" && !confirmation?.message) {
const pending = confirmation;
closeOverlay();
pending?.run("");
return key.preventDefault();
}
return;
}
if (globalKey(key)) return key.preventDefault();
const digit = /^[1-9]$/.test(key.name) && !key.ctrl && !key.meta ? Number(key.name) - 1 : -1;
if (digit >= 0 && pendingInput && (mode === "nav" || (mode === "input" && composerEmpty))) {
@@ -260,19 +507,58 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
return;
}
const scroll = scrollRef.current;
if (mode === "details") {
switch (key.name) {
case "j":
case "down":
return moveDetails(1);
case "k":
case "up":
return moveDetails(-1);
case "return":
case "space": {
const action = actions.find((candidate) => candidate.id === detailsSelected);
if (action) activate(action);
return key.preventDefault();
}
case "t": {
const action = actions.find((candidate) => candidate.id === detailsSelected);
if (action?.kind === "automation") toggleAutomation(action.task);
return;
}
case "escape":
if (diff) return setDiff(null);
setDetailsSelected(null);
return setMode("nav");
case "h":
case "left":
setDetailsSelected(null);
return setMode("nav");
}
}
switch (key.name) {
case "q":
if (diff) return setDiff(null);
return quit();
case "escape":
if (diff) setDiff(null);
return;
case "j":
case "down":
return attachThreadId ? scroll?.scrollBy(1) : move(1);
return attached || diff ? scroll?.scrollBy(1) : move(1);
case "k":
case "up":
return attachThreadId ? scroll?.scrollBy(-1) : move(-1);
return attached || diff ? scroll?.scrollBy(-1) : move(-1);
case "g":
return key.shift ? scroll?.scrollTo(scroll.scrollHeight) : scroll?.scrollTo(0);
case "d":
return setDetailsPref(!showDetails);
case "l":
case "right":
return focusDetails();
case "u":
if (parent) openThread(parent.threadId);
return;
case "e":
return setExpandAll((value) => !value);
case "o":
@@ -289,8 +575,11 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
case "s":
if (threadId && key.shift) run("Stop requested", () => session.stopThread(threadId));
return;
case ":":
openPalette();
return key.preventDefault();
case "/":
if (!attachThreadId) setMode("filter");
if (!attached) setMode("filter");
return key.preventDefault();
case "i":
case "return":
@@ -308,7 +597,7 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
: shell.status.type === "reconnecting"
? "reconnecting…"
: (shell.serverUrl ?? "");
const listWidth = attachThreadId ? 0 : Math.min(46, Math.max(28, Math.floor(width * 0.3)));
const listWidth = attached ? 0 : Math.min(46, Math.max(28, Math.floor(width * 0.3)));
const detailsColumn = showDetails && width - listWidth - DETAILS_WIDTH >= MIN_CONVERSATION_WIDTH;
const detailsInPlace = showDetails && !detailsColumn;
const composerHeight = Math.min(MAX_COMPOSER_LINES, composerLines) + 2;
@@ -333,6 +622,18 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
.filter(Boolean)
.join(" · ")
: "";
const detailsPanel = (inPlace: boolean) => (
<DetailsPanel
details={details}
// Idle subagents are left out of the shell, which is where details come from.
{...(threadId && !threadShell ? { empty: "No details for idle subagent threads. u goes to the parent." } : {})}
width={inPlace ? width - listWidth : DETAILS_WIDTH}
loading={vcsState?.status !== "live"}
inPlace={inPlace}
selected={mode === "details" || (mode === "confirm" && returnMode.current === "details") ? detailsSelected : null}
onActivate={activateById}
/>
);
return (
<box flexDirection="column" width={width} height={height} backgroundColor={colors.bg}>
@@ -341,20 +642,42 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
<strong>tui3</strong>
</text>
<text fg={shell.status.type === "live" ? colors.faint : colors.warn}>{` ${status}`}</text>
<box flexGrow={1} />
<text fg={colors.faint}>ctrl+k commands</text>
</box>
<box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden">
{attachThreadId ? null : (
<ThreadList rows={rows} collapsed={collapsed} selected={selectedIndex} focused={mode === "nav"} width={listWidth} height={height - 2} filter={filter} now={now} />
{attached ? null : (
<ThreadList
rows={rows}
collapsed={collapsed}
selected={selectedIndex}
focused={mode === "nav" || mode === "filter"}
width={listWidth}
height={height - 2}
filter={filter}
filtering={mode === "filter"}
now={now}
onFilter={setFilter}
onFilterDone={() => setMode("nav")}
onPick={(id) => {
openThread(id);
setMode("nav");
}}
onUnfold={() => setShowFolded(true)}
/>
)}
<box flexDirection="column" flexGrow={1} minHeight={0}>
{threadId && detailsInPlace ? (
{diff ? (
<DiffView diff={diff} scrollRef={scrollRef} />
) : threadId && detailsInPlace ? (
<box flexGrow={1} minHeight={0} flexDirection="column">
<DetailsPanel details={details} width={width - listWidth} loading={vcsState?.status !== "live"} inPlace />
{detailsPanel(true)}
</box>
) : threadId ? (
<ThreadView
key={watchedId}
project={threadRow?.projectName ?? ""}
title={threadShell?.title ?? "Thread"}
title={title}
detail={threadShell?.branch ?? ""}
timeline={current}
history={watchedId === threadId ? (thread?.history ?? null) : null}
@@ -363,18 +686,27 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
workspaceRoot={threadShell?.worktreePath ?? undefined}
now={now}
scrollRef={scrollRef}
parent={parent}
onOpenThread={openThread}
/>
) : (
<box flexGrow={1} paddingLeft={2} paddingTop={1}>
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
</box>
)}
{mode !== "filter" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
{mode === "filter" ? (
<box title=" filter " border borderStyle="rounded" borderColor={colors.borderFocused} height={3} flexShrink={0} marginLeft={1} marginRight={1}>
<input focused placeholder="title or project…" value={filter} onInput={(value: string) => setFilter(value)} onSubmit={() => setMode("nav")} />
</box>
) : threadId ? (
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
{mode === "confirm" && confirmation ? (
<ConfirmBar
confirmation={confirmation}
message={confirmMessage}
onMessage={setConfirmMessage}
onSubmit={() => {
closeOverlay();
confirmation.run(confirmMessage);
}}
/>
) : null}
{threadId ? (
<box
border
borderStyle="rounded"
@@ -385,6 +717,7 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
marginRight={1}
paddingLeft={1}
paddingRight={1}
onMouseDown={() => setMode("input")}
>
<textarea
key={threadId}
@@ -394,49 +727,84 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI
placeholder={placeholder}
placeholderColor={colors.faint}
textColor={colors.text}
wrapMode="word"
keyBindings={[...COMPOSER_KEYS]}
onSubmit={() => submit()}
onContentChange={() => {
const text = composerRef.current?.plainText ?? "";
const composer = composerRef.current;
const text = composer?.plainText ?? "";
if (text) drafts.current.set(threadId, text);
else drafts.current.delete(threadId);
setComposerLines(Math.max(1, text.split("\n").length));
// Wrapped lines count too, so a long paragraph grows the box.
// The wrapped count can lag a programmatic newline, so hard lines are a floor.
setComposerLines(Math.max(text.split("\n").length, composer?.virtualLineCount ?? 1));
setComposerEmpty(text.trim() === "");
}}
/>
</box>
) : null}
{mode !== "filter" && threadId ? (
{threadId ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
<text fg={colors.faint}>{footer}</text>
</box>
) : null}
</box>
{detailsColumn ? <DetailsPanel details={details} width={DETAILS_WIDTH} loading={vcsState?.status !== "live"} /> : null}
{detailsColumn ? detailsPanel(false) : null}
</box>
<box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
{flash ? (
<text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text>
) : (
<text fg={colors.faint}>{hints(mode, { approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached: Boolean(attachThreadId) })}</text>
<text fg={colors.faint}>{hints(mode, { approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined })}</text>
)}
</box>
{mode === "palette" ? (
<Palette
query={paletteQuery}
groups={groups}
selected={Math.min(paletteIndex, Math.max(0, entries.length - 1))}
width={width}
height={height}
onQuery={(value) => {
setPaletteQuery(value);
setPaletteIndex(0);
}}
onSubmit={() => pick(Math.min(paletteIndex, entries.length - 1))}
onPick={pick}
/>
) : null}
</box>
);
}
function hints(mode: Mode, state: { readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean }): string {
function hints(
mode: Mode,
state: { readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean; readonly diff: boolean; readonly parent: boolean },
): string {
if (mode === "filter") return "enter done · esc close";
if (mode === "palette") return "↑/↓ move · enter run · esc close";
if (mode === "confirm") return "enter confirm · esc cancel";
if (mode === "details") return "j/k move · enter open · t toggle automation · esc back";
if (mode === "input") {
const parts = [state.working ? "enter steer · alt+enter queue" : "enter send", "shift+enter newline", "esc navigate"];
const parts = [state.working ? "enter steer · alt+enter queue" : "enter send", "shift+enter or \\ newline", "esc navigate"];
if (state.question) parts.unshift("1-9 pick");
if (state.approval) parts.unshift("approval waiting: esc, then y/n");
if (!state.attached) parts.push("ctrl+n/p thread");
return parts.join(" · ");
}
const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter", "z settled"];
parts.push("i type", "e expand", "o earlier", "d details", "S stop", "q quit");
if (state.diff) return "j/k scroll · esc close diff · l details";
const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter"];
parts.push("i type", "l details", "e expand", "o earlier");
if (state.parent) parts.push("u parent");
parts.push("ctrl+k commands", "q quit");
if (state.question) parts.unshift("1-9 pick · x dismiss");
if (state.approval) parts.unshift("y approve · Y always · n decline");
return parts.join(" · ");
}
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
function firstLine(text: string): string {
const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ");
return line.length > 100 ? `${line.slice(0, 99)}…` : line;
}
+31
View File
@@ -0,0 +1,31 @@
import { colors } from "./theme.ts";
/** An action that waits for you to say yes: git actions, stopping a server, running an automation. */
export interface Confirmation {
readonly title: string;
readonly detail?: string;
/** Commit actions take an optional message, typed here; blank lets the server write one. */
readonly message?: { readonly placeholder: string };
readonly confirmLabel: string;
readonly run: (message: string) => void;
}
/** Shown above the composer while a confirmation is open. */
export function ConfirmBar(props: { readonly confirmation: Confirmation; readonly message: string; readonly onMessage: (value: string) => void; readonly onSubmit: () => void }) {
const { confirmation } = props;
return (
<box border borderStyle="rounded" borderColor={colors.warn} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
<text fg={colors.warn}>
<strong>{confirmation.title}</strong>
</text>
{confirmation.detail ? <text fg={colors.muted}>{confirmation.detail}</text> : null}
{confirmation.message ? (
<box flexDirection="row" height={1}>
<text fg={colors.faint}>{"Message: "}</text>
<input focused flexGrow={1} placeholder={confirmation.message.placeholder} value={props.message} onInput={props.onMessage} onSubmit={props.onSubmit} />
</box>
) : null}
<text fg={colors.faint}>{`enter ${confirmation.confirmLabel} · esc cancel`}</text>
</box>
);
}
+90 -25
View File
@@ -1,29 +1,55 @@
import type { ReactNode } from "react";
import type { ThreadDetails } from "../model/details.ts";
import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts";
import { colors, statusColor } from "./theme.ts";
/** Files listed under Changes before the rest fold into a count. */
const MAX_FILES = 8;
/** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */
const IN_PLACE_MAX_WIDTH = 64;
/** The web's thread details card as a right-hand column: workspace, branch and PR, changes, lineage, background work, goal. */
export function DetailsPanel(props: { readonly details: ThreadDetails | null; readonly width: number; readonly loading: boolean; readonly inPlace?: boolean }) {
/**
* The web's thread details card as a right-hand column: workspace, branch and PR, git actions,
* changes, lineage, servers, automations, background work, goal. Lines that do something are
* selectable with the keyboard and clickable.
*/
export function DetailsPanel(props: {
readonly details: ThreadDetails | null;
readonly width: number;
readonly loading: boolean;
readonly inPlace?: boolean;
/** The selected line's action id, while the panel has focus. */
readonly selected: string | null;
readonly onActivate: (id: string) => void;
/** Shown when there are no details, which defaults to no thread being selected. */
readonly empty?: string;
}) {
const { details } = props;
// In place of the conversation it sits beside the thread list's border and needs none of its own.
const width = props.inPlace ? Math.min(props.width, IN_PLACE_MAX_WIDTH) : props.width;
const inner = Math.max(10, width - (props.inPlace ? 3 : 4));
return (
<box {...(props.inPlace ? {} : { border: ["left"] as const, borderColor: colors.border })} width={width} flexShrink={0} flexDirection="column" paddingLeft={1} paddingRight={1} overflow="hidden">
{!details ? <text fg={colors.faint}>No thread selected.</text> : <Sections details={details} inner={inner} loading={props.loading} />}
<box
{...(props.inPlace ? {} : { border: ["left"] as const, borderColor: props.selected ? colors.borderFocused : colors.border })}
width={width}
flexShrink={0}
flexDirection="column"
overflow="hidden"
>
<scrollbox flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1}>
{!details ? <text fg={colors.faint}>{props.empty ?? "No thread selected."}</text> : <Sections details={details} inner={inner} loading={props.loading} selected={props.selected} onActivate={props.onActivate} />}
</scrollbox>
</box>
);
}
function Sections({ details, inner, loading }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean }) {
const { workspace, branch, changes } = details;
interface LineProps {
readonly selected: string | null;
readonly onActivate: (id: string) => void;
}
function Sections({ details, inner, loading, selected, onActivate }: { readonly details: ThreadDetails; readonly inner: number; readonly loading: boolean } & LineProps) {
const { workspace, branch, changes, git } = details;
const files = changes?.files ?? [];
const line = { selected, onActivate };
return (
<>
<Section title="Workspace" first>
@@ -35,7 +61,11 @@ function Sections({ details, inner, loading }: { readonly details: ThreadDetails
{branch ? (
<Section title="Branch">
<Line left={truncate(branch.name, inner - (branch.upstream?.length ?? 0) - 1)} right={branch.upstream ?? ""} />
<box flexDirection="row">
<text fg={colors.text}>{truncate(branch.name, inner - (branch.upstream?.length ?? 0) - 1)}</text>
<box flexGrow={1} />
<text fg={colors.faint}>{branch.upstream ?? ""}</text>
</box>
{branch.pullRequest ? (
<>
<box flexDirection="row">
@@ -47,15 +77,21 @@ function Sections({ details, inner, loading }: { readonly details: ThreadDetails
{branch.pullRequest.title ? <text fg={colors.muted}>{truncate(branch.pullRequest.title, inner)}</text> : null}
</>
) : null}
{git?.quick ? <Selectable id={`git:quick:${git.quick.action}`} {...line} color={colors.accent} text={`▸ ${git.quick.label}`} inner={inner} /> : null}
{git?.menu.map((item) => <Selectable key={item.action} id={`git:${item.action}`} {...line} color={colors.muted} text={` ${item.label}`} inner={inner} />)}
{git && !git.quick && git.hint ? <text fg={colors.faint}>{truncate(git.hint, inner)}</text> : null}
</Section>
) : null}
{changes ? (
<Section title="Changes" right={<Counts insertions={changes.insertions} deletions={changes.deletions} />}>
{files.slice(0, MAX_FILES).map((file) => (
<FileLine key={file.path} path={file.path} insertions={file.insertions} deletions={file.deletions} inner={inner} />
{files.length > 0 ? <Selectable id="diff:*" {...line} color={colors.accent} text="▸ View diff" inner={inner} /> : null}
{files.slice(0, MAX_DETAIL_FILES).map((file) => (
<Selectable key={file.path} id={`diff:${file.path}`} {...line} inner={inner}>
<FileLine path={file.path} insertions={file.insertions} deletions={file.deletions} inner={inner} />
</Selectable>
))}
{files.length > MAX_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_FILES} more files`}</text> : null}
{files.length > MAX_DETAIL_FILES ? <text fg={colors.faint}>{`… ${files.length - MAX_DETAIL_FILES} more files (in the full diff)`}</text> : null}
{files.length === 0 ? <text fg={colors.faint}>Working tree clean</text> : null}
{changes.branchTotal ? (
<box flexDirection="row">
@@ -74,8 +110,37 @@ function Sections({ details, inner, loading }: { readonly details: ThreadDetails
{details.lineage.length > 0 ? (
<Section title="Lineage">
{details.lineage.map((entry) => (
<text key={entry.text} fg={colors.muted}>{truncate(`${entry.glyph} ${entry.text}`, inner)}</text>
{details.lineage.map((entry) =>
entry.threadId ? (
<Selectable key={entry.threadId} id={`thread:${entry.threadId}`} {...line} color={colors.muted} text={`${entry.glyph} ${entry.text}`} inner={inner} />
) : (
<text key={entry.text} fg={colors.muted}>{truncate(`${entry.glyph} ${entry.text}`, inner)}</text>
),
)}
</Section>
) : null}
{details.servers.length > 0 ? (
<Section title="Servers">
{details.servers.map(({ server, label }) => (
<Selectable key={server.port} id={`server:${server.port}`} {...line} color={colors.info} text={`● ${label}`} inner={inner} />
))}
</Section>
) : null}
{details.automations.length > 0 ? (
<Section title="Automations">
{details.automations.map((automation) => (
<Selectable key={automation.task.id} id={`automation:${automation.task.id}`} {...line} inner={inner}>
<box flexDirection="column">
<text fg={colors.text}>{truncate(automation.task.title, inner)}</text>
<box flexDirection="row">
<text fg={colors.faint}>{truncate(automation.schedule, inner - automation.status.length - 1)}</text>
<box flexGrow={1} />
<text fg={statusColor[automation.tone]}>{automation.status}</text>
</box>
</box>
</Selectable>
))}
</Section>
) : null}
@@ -98,6 +163,16 @@ function Sections({ details, inner, loading }: { readonly details: ThreadDetails
);
}
/** A line that does something: highlighted when selected, activated by a click. */
function Selectable(props: LineProps & { readonly id: DetailsAction["id"]; readonly inner: number; readonly text?: string; readonly color?: string; readonly children?: ReactNode }) {
const active = props.selected === props.id;
return (
<box backgroundColor={active ? colors.selectedBg : "transparent"} onMouseDown={() => props.onActivate(props.id)}>
{props.children ?? <text fg={active ? colors.text : (props.color ?? colors.muted)}>{truncate(props.text ?? "", props.inner)}</text>}
</box>
);
}
function Section(props: { readonly title: string; readonly right?: ReactNode; readonly first?: boolean; readonly children: ReactNode }) {
return (
<box flexDirection="column" marginTop={props.first ? 0 : 1} flexShrink={0}>
@@ -113,16 +188,6 @@ function Section(props: { readonly title: string; readonly right?: ReactNode; re
);
}
function Line({ left, right }: { readonly left: string; readonly right: string }) {
return (
<box flexDirection="row">
<text fg={colors.text}>{left}</text>
<box flexGrow={1} />
<text fg={colors.faint}>{right}</text>
</box>
);
}
function FileLine(props: { readonly path: string; readonly insertions: number; readonly deletions: number; readonly inner: number }) {
const counts = countsText(props.insertions, props.deletions);
return (
+73
View File
@@ -0,0 +1,73 @@
import type { ScrollBoxRenderable } from "@opentui/core";
import type { RefObject } from "react";
import { colors, getMarkdownStyle } from "./theme.ts";
export interface DiffState {
readonly cwd: string;
/** null for the whole working tree. */
readonly path: string | null;
readonly status: "loading" | "ready" | "error";
readonly patch?: string;
readonly truncated?: boolean;
readonly error?: string;
}
/** Uncommitted changes as unified diffs, one block per file, in place of the conversation. */
export function DiffView(props: { readonly diff: DiffState; readonly scrollRef: RefObject<ScrollBoxRenderable | null> }) {
const { diff } = props;
const files = diff.patch ? splitPatch(diff.patch) : [];
return (
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={1} paddingRight={1}>
<box flexDirection="row" flexShrink={0} height={1}>
<text fg={colors.muted}>Uncommitted / </text>
<text fg={colors.text}>
<strong>{diff.path ?? `${files.length} ${files.length === 1 ? "file" : "files"}`}</strong>
</text>
<box flexGrow={1} />
<text fg={colors.faint}>esc close</text>
</box>
{diff.status === "loading" ? <text fg={colors.muted}>Loading diff…</text> : null}
{diff.status === "error" ? <text fg={colors.bad}>{`Could not load the diff: ${diff.error ?? "unknown error"}`}</text> : null}
{diff.status === "ready" && files.length === 0 ? <text fg={colors.muted}>No changes.</text> : null}
{diff.truncated ? <text fg={colors.warn}>The diff was too large and is cut short.</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} minHeight={0}>
{files.map((file) => (
<box key={file.path} flexDirection="column" marginTop={1}>
{diff.path ? null : <text fg={colors.accent}>{file.path}</text>}
<diff
diff={file.patch}
view="unified"
{...(filetypeOf(file.path) ? { filetype: filetypeOf(file.path)! } : {})}
syntaxStyle={getMarkdownStyle()}
showLineNumbers
wrapMode="none"
fg={colors.text}
addedBg="#1e2a1e"
removedBg="#2d1f24"
addedContentBg="#1e2a1e"
removedContentBg="#2d1f24"
addedSignColor={colors.good}
removedSignColor={colors.bad}
lineNumberFg={colors.faint}
/>
</box>
))}
</scrollbox>
</box>
);
}
/** Splits a multi-file patch at each `diff --git` header. */
export function splitPatch(patch: string): { path: string; patch: string }[] {
return patch
.split(/^(?=diff --git )/m)
.filter((chunk) => chunk.startsWith("diff --git "))
.map((chunk) => ({ path: /^diff --git a\/(.+?) b\//.exec(chunk)?.[1] ?? "file", patch: chunk }));
}
const FILETYPES: Record<string, string> = { ts: "typescript", tsx: "tsx", js: "javascript", jsx: "javascript", json: "json", md: "markdown", rs: "rust", py: "python", go: "go", css: "css", html: "html", sh: "bash", yml: "yaml", yaml: "yaml", zig: "zig" };
function filetypeOf(path: string): string | undefined {
return FILETYPES[path.split(".").pop() ?? ""];
}
+72
View File
@@ -0,0 +1,72 @@
import type { PaletteEntry, PaletteGroup } from "../model/palette.ts";
import { colors } from "./theme.ts";
/**
* The web's command palette (mod+K) as an overlay: a search box over grouped commands and
* threads. Arrows or ctrl+n/p move, enter runs, a click runs, esc closes.
*/
export function Palette(props: {
readonly query: string;
readonly groups: readonly PaletteGroup[];
readonly selected: number;
readonly width: number;
readonly height: number;
readonly onQuery: (query: string) => void;
readonly onSubmit: () => void;
readonly onPick: (index: number) => void;
}) {
const width = Math.min(80, props.width - 4);
const listHeight = Math.max(4, Math.min(props.height - 8, 22));
// Rows are entries plus a header per group; keep the selection in view.
const rows: ({ kind: "header"; label: string } | { kind: "entry"; entry: PaletteEntry; index: number })[] = [];
let index = 0;
for (const group of props.groups) {
rows.push({ kind: "header", label: group.label });
for (const entry of group.entries) rows.push({ kind: "entry", entry, index: index++ });
}
const selectedRow = rows.findIndex((row) => row.kind === "entry" && row.index === props.selected);
const start = Math.max(0, Math.min(selectedRow - Math.floor(listHeight / 2), rows.length - listHeight));
const inner = width - 4;
return (
<box position="absolute" top={2} left={Math.floor((props.width - width) / 2)} width={width} zIndex={10} flexDirection="column" border borderStyle="rounded" borderColor={colors.borderFocused} backgroundColor={colors.panel}>
<box paddingLeft={1} paddingRight={1} height={1} flexDirection="row">
<text fg={colors.accent}>{"› "}</text>
<input focused flexGrow={1} placeholder="Search commands and threads (> for commands only)" value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
</box>
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}>
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
{rows.slice(start, start + listHeight).map((row) =>
row.kind === "header" ? (
<text key={`h-${row.label}`} fg={colors.faint} paddingLeft={1}>
{row.label}
</text>
) : (
<Row key={entryKey(row.entry)} entry={row.entry} selected={row.index === props.selected} inner={inner} onPick={() => props.onPick(row.index)} />
),
)}
</box>
</box>
);
}
function Row(props: { readonly entry: PaletteEntry; readonly selected: boolean; readonly inner: number; readonly onPick: () => void }) {
const { entry } = props;
const right = entry.kind === "command" ? (entry.command.shortcut ?? "") : entry.project;
const title = entry.kind === "command" ? entry.command.title : `${entry.subagent ? "↳ " : ""}${entry.title}`;
return (
<box flexDirection="row" paddingLeft={1} paddingRight={1} backgroundColor={props.selected ? colors.selectedBg : "transparent"} onMouseDown={props.onPick}>
<text fg={props.selected ? colors.text : entry.kind === "command" ? colors.text : colors.muted}>{truncate(title, props.inner - right.length - 2)}</text>
<box flexGrow={1} />
<text fg={colors.faint}>{right}</text>
</box>
);
}
export function entryKey(entry: PaletteEntry): string {
return entry.kind === "command" ? `c:${entry.command.id}` : `t:${entry.threadId}`;
}
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;
}
+25 -4
View File
@@ -1,4 +1,6 @@
import { needsAttention, relativeTime, rowTime, SECTION_LABELS, statusLabel, type Section, type ThreadRow } from "../model/threads.ts";
import type { ThreadId } from "@t3tools/contracts";
import { colors, statusColor } from "./theme.ts";
/**
@@ -15,11 +17,17 @@ export function ThreadList(props: {
readonly width: number;
readonly height: number;
readonly filter: string;
/** The filter box is open and has the keyboard. */
readonly filtering: boolean;
readonly now: number;
readonly onFilter: (value: string) => void;
readonly onFilterDone: () => void;
readonly onPick: (threadId: ThreadId) => void;
readonly onUnfold: () => void;
}) {
const { rows, selected, focused, width, height, now } = props;
// Rows take two lines plus a header per section; keep the selection in view.
const visibleCount = Math.max(1, Math.floor((height - 6) / 2));
const visibleCount = Math.max(1, Math.floor((height - (props.filtering ? 9 : 6)) / 2));
const start = Math.max(0, Math.min(selected - Math.floor(visibleCount / 2), rows.length - visibleCount));
const windowRows = rows.slice(start, start + visibleCount);
const inner = Math.max(8, width - 3);
@@ -42,7 +50,14 @@ export function ThreadList(props: {
const recede = !isSelected && (row.status === "working" || row.status === "waiting" || (row.status === "ready" && !row.unread));
const title = truncate(row.thread.title || "New thread", inner);
lines.push(
<box key={row.thread.id} flexDirection="column" paddingLeft={1} paddingRight={1} backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.panel) : "transparent"}>
<box
key={row.thread.id}
flexDirection="column"
paddingLeft={1}
paddingRight={1}
backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.panel) : "transparent"}
onMouseDown={() => props.onPick(row.thread.id)}
>
<box flexDirection="row">
<text fg={colors.faint}>{left}</text>
<box flexGrow={1} />
@@ -55,11 +70,17 @@ export function ThreadList(props: {
const collapsed = [...props.collapsed].filter(([, count]) => count > 0);
return (
<box border={["right"]} borderColor={colors.border} width={width} flexShrink={0} overflow="hidden" flexDirection="column">
{props.filter ? <text fg={colors.accent}>{` /${props.filter}`}</text> : null}
{props.filtering ? (
<box border borderStyle="rounded" borderColor={colors.borderFocused} height={3} flexShrink={0}>
<input focused placeholder="Filter threads…" value={props.filter} onInput={props.onFilter} onSubmit={props.onFilterDone} />
</box>
) : props.filter ? (
<text fg={colors.accent}>{` /${props.filter}`}</text>
) : null}
{rows.length === 0 ? <text fg={colors.muted}>{props.filter ? " no matches" : " no threads"}</text> : lines}
<box flexGrow={1} />
{collapsed.map(([section, count]) => (
<text key={section} fg={colors.faint}>{` › ${SECTION_LABELS[section]} ${count}`}</text>
<text key={section} fg={colors.faint} onMouseDown={props.onUnfold}>{` › ${SECTION_LABELS[section]} ${count}`}</text>
))}
</box>
);
+32 -5
View File
@@ -1,4 +1,5 @@
import type { ScrollBoxRenderable } from "@opentui/core";
import type { ThreadId } from "@t3tools/contracts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
import { memo, type RefObject } from "react";
@@ -20,6 +21,10 @@ export function ThreadView(props: {
readonly workspaceRoot: string | undefined;
readonly now: number;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
/** For a subagent or fork: the thread it came from, shown as a link in the header. */
readonly parent?: { readonly title: string; readonly threadId: ThreadId } | undefined;
/** Opens another thread: a subagent from its work row, or the parent from the header. Keep it stable; rows are memoized on it. */
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
const { timeline, history } = props;
const pendingIds = new Set<string>(timeline?.pending.approvals.map((approval) => approval.requestId) ?? []);
@@ -33,6 +38,11 @@ export function ThreadView(props: {
<box flexGrow={1} />
<text fg={colors.faint}>{props.detail}</text>
</box>
{props.parent ? (
<box flexShrink={0} height={1} onMouseDown={() => props.onOpenThread(props.parent!.threadId)}>
<text fg={colors.accent}>{`↰ ${props.parent.title} (u)`}</text>
</box>
) : null}
{props.error ? <text fg={colors.bad} flexShrink={0}>{props.error}</text> : null}
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom">
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
@@ -45,6 +55,7 @@ export function ThreadView(props: {
workspaceRoot={props.workspaceRoot}
now={row.kind === "working" ? props.now : 0}
workStartedAt={timeline.workStartedAt}
onOpenThread={props.onOpenThread}
/>
))}
</scrollbox>
@@ -78,6 +89,7 @@ const Row = memo(function Row(props: {
readonly workspaceRoot: string | undefined;
readonly now: number;
readonly workStartedAt: string | null;
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
const { row, workspaceRoot } = props;
switch (row.kind) {
@@ -109,7 +121,7 @@ const Row = memo(function Row(props: {
return (
<box marginTop={row.continuesWorkLog ? 0 : 1} flexDirection="column">
{row.groupedEntries.map((entry) => (
<WorkEntry key={entry.id} entry={entry} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} />
<WorkEntry key={entry.id} entry={entry} label={row.displayLabel && row.groupedEntries.length === 1 ? row.displayLabel : workEntryDisplayLabel(entry, workspaceRoot)} onOpenThread={props.onOpenThread} />
))}
</box>
);
@@ -117,7 +129,9 @@ const Row = memo(function Row(props: {
return (
<box marginTop={1} flexDirection="column">
{row.thought?.detail ? <text fg={colors.faint}>{`∴ ${liveThoughtLine(row.thought.detail)}`}</text> : null}
<text fg={row.active ? colors.info : colors.muted}>{`${row.active ? "◐" : glyphFor(row.entry)} ${liveWorkEntryLabel(row.entry, workspaceRoot, row.active)}`}</text>
<box onMouseDown={() => openChild(row.entry, props.onOpenThread)}>
<text fg={row.active ? colors.info : colors.muted}>{`${row.active ? "◐" : glyphFor(row.entry)} ${liveWorkEntryLabel(row.entry, workspaceRoot, row.active)}${childThreadOf(row.entry) ? " ↗" : ""}`}</text>
</box>
</box>
);
case "working": {
@@ -166,10 +180,23 @@ function UserMessage({ text }: { readonly text: string }) {
);
}
function WorkEntry({ entry, label }: { readonly entry: WorkLogEntry; readonly label: string }) {
function WorkEntry({ entry, label, onOpenThread }: { readonly entry: WorkLogEntry; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void }) {
const failed = workEntryDisplayIndicatesToolFailure(entry);
const tone = failed || entry.tone === "error" ? colors.bad : entry.tone === "thinking" ? colors.faint : colors.muted;
return <text fg={tone}>{`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}`}</text>;
const child = childThreadOf(entry);
const tone = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : entry.tone === "thinking" ? colors.faint : colors.muted;
const text = <text fg={tone}>{`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}${child ? " ↗" : ""}`}</text>;
return child ? <box onMouseDown={() => onOpenThread(child)}>{text}</box> : text;
}
/** The thread a subagent work row ran in, when it has its own. */
export function childThreadOf(entry: WorkLogEntry): ThreadId | null {
const item = entry.structuredPayload;
return item?.type === "subagent" ? (item.childThreadId ?? null) : null;
}
function openChild(entry: WorkLogEntry, onOpenThread: (threadId: ThreadId) => void): void {
const child = childThreadOf(entry);
if (child) onOpenThread(child);
}
function EventRow({ item, pending }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) {
+28 -9
View File
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
import type { OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell } from "@t3tools/contracts";
import type { VcsState } from "../src/client/session.ts";
import { detailsCwd, threadDetails } from "../src/model/details.ts";
import { detailsActions, detailsCwd, threadDetails } from "../src/model/details.ts";
const project = { id: "p1", title: "tasknotes", workspaceRoot: "/repo/tasknotes" } as unknown as OrchestrationProjectShell;
const thread = (extra: Record<string, unknown> = {}) =>
@@ -38,9 +38,12 @@ const vcs = (local: Record<string, unknown>, remote: Record<string, unknown> | n
remote,
}) as unknown as VcsState;
const detailsOf = (t: OrchestrationV2ThreadShell, v: VcsState | null, snapshot: OrchestrationV2ShellSnapshot | null, extra: Partial<Parameters<typeof threadDetails>[0]> = {}) =>
threadDetails({ thread: t, project, vcs: v, snapshot, ...extra });
describe("threadDetails", () => {
test("runs git in the worktree and labels the workspace", () => {
const details = threadDetails(thread(), project, null, null);
const details = detailsOf(thread(), null, null);
expect(detailsCwd(thread(), project)).toBe("/repo/tasknotes-wt/sync");
expect(detailsCwd(thread({ worktreePath: null }), project)).toBe("/repo/tasknotes");
expect(details.workspace).toEqual({ path: "/repo/tasknotes-wt/sync", worktree: true, model: "gpt-5", mode: "Build · Supervised" });
@@ -50,9 +53,8 @@ describe("threadDetails", () => {
});
test("shows changes, ahead/behind and the remote's PR", () => {
const details = threadDetails(
const details = detailsOf(
thread(),
project,
vcs(
{
workingTree: { files: [{ path: "src/a.ts", insertions: 3, deletions: 1 }], insertions: 3, deletions: 1 },
@@ -71,7 +73,7 @@ describe("threadDetails", () => {
const pullRequests = [
{ host: "github.com", repository: "o/r", number: 7, url: "u", source: "created", linkedAt: "2026-01-01T00:00:00Z", stack: null, snapshot: { state: "open", title: "Seven", headBranch: "x", baseBranch: "main", isDraft: true, updatedAt: null, syncedAt: "2026-01-01T00:00:00Z", checksState: "failing" } },
];
const details = threadDetails(thread({ pullRequests }), project, vcs({}, { hasUpstream: false, aheadCount: 0, behindCount: 0, pr: null }), null);
const details = detailsOf(thread({ pullRequests }), vcs({}, { hasUpstream: false, aheadCount: 0, behindCount: 0, pr: null }), null);
expect(details.branch?.upstream).toBe("not pushed");
expect(details.branch?.pullRequest).toEqual({ number: 7, title: "Seven", state: "draft", tone: "muted", checks: { text: "✕ checks", tone: "bad" } });
});
@@ -83,7 +85,7 @@ describe("threadDetails", () => {
{ id: "fork", title: "Try another way", lineage: { parentThreadId: "t1", relationshipToParent: "fork" }, deletedAt: null },
],
} as unknown as OrchestrationV2ShellSnapshot;
const details = threadDetails(
const details = detailsOf(
thread({
lineage: { parentThreadId: "parent", relationshipToParent: "fork", rootThreadId: "parent" },
pendingBackgroundTasks: [
@@ -92,16 +94,33 @@ describe("threadDetails", () => {
],
goal: { objective: "Ship sync", status: "active", timeUsedSeconds: 90 },
}),
project,
vcs({}),
snapshot,
);
expect(details.lineage.map((entry) => entry.text)).toEqual(['forked from "Plan sync"', 'forked into "Try another way"', "1 subagent (1 running)"]);
expect(details.lineage.map((entry) => [entry.text, entry.threadId])).toEqual([
['forked from "Plan sync"', "parent"],
['fork "Try another way"', "fork"],
["1 subagent running", undefined],
]);
expect(details.background).toEqual([{ glyph: "◐", text: "dev server :5173" }]);
expect(details.goal).toEqual({ objective: "Ship sync", status: "active · 1m", tone: "info" });
});
test("notes folders that aren't repositories", () => {
expect(threadDetails(thread(), project, vcs({ isRepo: false }), null).vcsNote).toBe("Not a git repository");
expect(detailsOf(thread(), vcs({ isRepo: false }), null).vcsNote).toBe("Not a git repository");
});
test("offers the web's git actions and lists selectable lines in order", () => {
const servers = [{ host: "127.0.0.1", port: 5173, url: "http://127.0.0.1:5173", processName: "vite", pid: 42, terminal: null, agent: { threadId: "t1" } }];
const automations = [{ id: "a1", title: "Nightly check", prompt: "check", enabled: true, schedule: { type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2] }, threadId: "t1", nextRunAt: null, lastRunAt: null, lastRunStatus: "never", lastRunError: null, runCount: 0 }];
const details = detailsOf(
thread(),
vcs({ workingTree: { files: [{ path: "src/a.ts", insertions: 3, deletions: 1 }], insertions: 3, deletions: 1 } }, { hasUpstream: true, aheadCount: 0, behindCount: 0, aheadOfDefaultCount: 0, pr: null }),
null,
{ servers, automations } as never,
);
expect(details.git?.quick).toEqual({ action: "commit_push_pr", label: "Commit, push & PR", commits: true });
expect(details.automations[0]).toMatchObject({ schedule: "Mon,Tue 09:00", status: "on" });
expect(detailsActions(details).map((action) => action.id)).toEqual(["git:quick:commit_push_pr", "git:commit", "diff:*", "diff:src/a.ts", "server:5173", "automation:a1"]);
});
});
+37
View File
@@ -0,0 +1,37 @@
import { expect, test } from "bun:test";
import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { paletteEntries, paletteGroups } from "../src/model/palette.ts";
const at = (ms: number) => DateTime.makeUnsafe(ms);
const thread = (id: string, title: string, updated: number, extra: Record<string, unknown> = {}) => ({
id, title, projectId: "p1", branch: null, archivedAt: null, deletedAt: null, latestUserMessageAt: null, updatedAt: at(updated),
lineage: { parentThreadId: null, relationshipToParent: null }, ...extra,
});
const snapshot = {
projects: [{ id: "p1", title: "tasknotes", workspaceRoot: "/r" }],
threads: [
thread("t1", "Fix calendar sync", 1_000),
thread("t2", "Release notes", 3_000),
thread("t3", "Sync worker", 2_000, { lineage: { parentThreadId: "t1", relationshipToParent: "subagent" } }),
thread("t4", "Old", 500, { archivedAt: at(600) }),
],
} as unknown as OrchestrationV2ShellSnapshot;
const commands = [
{ id: "details", title: "Show thread details", shortcut: "d" },
{ id: "diff", title: "View uncommitted changes", keywords: ["diff"] },
];
test("lists commands, then recent threads, before you type", () => {
const groups = paletteGroups({ query: "", commands, snapshot });
expect(groups.map((group) => group.label)).toEqual(["Commands", "Recent threads"]);
expect(groups[1]!.entries.map((entry) => (entry.kind === "thread" ? (entry.threadId as string) : ""))).toEqual(["t2", "t3", "t1"]);
});
test("searches threads, subagents included, and commands by keyword", () => {
const entries = paletteEntries(paletteGroups({ query: "sync", commands, snapshot }));
expect(entries.map((entry) => (entry.kind === "thread" ? `${entry.threadId}${entry.subagent ? "*" : ""}` : entry.command.id)).sort()).toEqual(["t1", "t3*"]);
expect(paletteEntries(paletteGroups({ query: "diff", commands, snapshot }))[0]).toMatchObject({ kind: "command", command: { id: "diff" } });
expect(paletteGroups({ query: ">", commands, snapshot }).map((group) => group.label)).toEqual(["Commands"]);
});