diff --git a/README.md b/README.md index dd48805..904b7c1 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/bin.ts b/src/bin.ts index 1582ceb..efa087a 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -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 } : {}) })); } diff --git a/src/client/auth.ts b/src/client/auth.ts index 3d8cef4..290a11b 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -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 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 { + 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 = (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>; +/** A subscription shared by every listener of the same key, restarted after reconnects. */ +interface FeedEntry { + state: unknown; + readonly listeners: Set>; + readonly stream: () => Effect.Effect; fiber: Fiber.Fiber | null; lingerTimer: ReturnType | null; } @@ -115,7 +141,7 @@ export class T3Session { private shell: ShellState = { status: { type: "connecting" }, snapshot: null, serverUrl: null }; private readonly shellListeners = new Set>(); private readonly threads = new Map(); - private readonly vcs = new Map(); + private readonly feeds = new Map(); async start(): Promise { 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 { @@ -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): () => 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(`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>): () => void { + return this.watchFeed>("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>): () => void { + return this.watchFeed>("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 { + 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): Promise { + 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 { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksSetEnabled]({ id, enabled })); + } + + runAutomationNow(id: ScheduledTaskId): Promise { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksRunNow]({ id })); + } + + stopServer(server: Pick): Promise { + 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): 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( + key: string, + initial: S, + listener: Listener, + stream: (update: (patch: Partial) => void) => Effect.Effect, + ): () => void { + let entry = this.feeds.get(key); + if (!entry) { + const update = (patch: Partial) => { + 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); + }), + ), + ); + 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; + 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)); } diff --git a/src/model/details.ts b/src/model/details.ts index c63d0bc..ec68fc2 100644 --- a/src/model/details.ts +++ b/src/model/details.ts @@ -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(); + 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 = new Set(["commit", "commit_push", "commit_push_pr"]); +const MENU_ACTIONS: Record = { 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 { + 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) { diff --git a/src/model/palette.ts b/src/model/palette.ts new file mode 100644 index 0000000..7b9fd37 --- /dev/null +++ b/src/model/palette.ts @@ -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(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); +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx index e2d144e..4f5f422 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -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; @@ -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(session.getShell()); + // Any thread, listed or not: subagents open here too. const [selectedId, setSelectedId] = useState(attachThreadId); - const [mode, setMode] = useState(attachThreadId ? "input" : "nav"); + const [mode, setMode] = useState(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(null); + const [detailsSelected, setDetailsSelected] = useState(null); + const [diff, setDiff] = useState(null); + const [confirmation, setConfirmation] = useState(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(null); const composerRef = useRef(null); const drafts = useRef(new Map()); + /** Where mode returns to when an overlay closes. */ + const returnMode = useRef("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 | null>(null); + const [automations, setAutomations] = useState | 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) => { 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 = {}) => 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) => ( + + ); return ( @@ -341,20 +642,42 @@ export function App(props: { readonly session: T3Session; readonly attachThreadI tui3 {` ${status}`} + + ctrl+k commands - {attachThreadId ? null : ( - + {attached ? null : ( + setMode("nav")} + onPick={(id) => { + openThread(id); + setMode("nav"); + }} + onUnfold={() => setShowFolded(true)} + /> )} - {threadId && detailsInPlace ? ( + {diff ? ( + + ) : threadId && detailsInPlace ? ( - + {detailsPanel(true)} ) : threadId ? ( ) : ( {shell.snapshot ? "No thread selected." : "Waiting for threads…"} )} - {mode !== "filter" && pendingInput && questionDraft ? : null} - {mode === "filter" ? ( - - setFilter(value)} onSubmit={() => setMode("nav")} /> - - ) : threadId ? ( + {mode !== "confirm" && pendingInput && questionDraft ? : null} + {mode === "confirm" && confirmation ? ( + { + closeOverlay(); + confirmation.run(confirmMessage); + }} + /> + ) : null} + {threadId ? ( setMode("input")} >