From a8e35ee83ae54cf0b5dee1b99d1c256161c2a00f Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 20:36:39 +1100 Subject: [PATCH] Queue controls, resume, secret requests and subagent stop, as in T3 Code Queued messages show above the composer (Q to go through them: send now, edit in the composer, remove; alt+up edits the last). An empty enter after an interrupt continues where the run left off and releases held messages. Secret requests get a masked field that never touches the message box. Running subagents the web can stop get a palette command. Adds the diagnostics:read and providers:manage scopes for usage limits. --- README.md | 10 ++- src/client/auth.ts | 2 +- src/client/session.ts | 68 ++++++++++++++++ src/model/queue.ts | 56 +++++++++++++ src/model/subagents.ts | 14 ++++ src/model/transcript.ts | 5 ++ src/ui/App.tsx | 51 +++++++++++- src/ui/QueuePanel.tsx | 37 +++++++++ src/ui/SecretPanel.tsx | 23 ++++++ src/ui/useQueue.ts | 156 +++++++++++++++++++++++++++++++++++++ src/ui/useSecretRequest.ts | 71 +++++++++++++++++ test/commands.test.ts | 34 +++++++- 12 files changed, 518 insertions(+), 9 deletions(-) create mode 100644 src/model/queue.ts create mode 100644 src/model/subagents.ts create mode 100644 src/ui/QueuePanel.tsx create mode 100644 src/ui/SecretPanel.tsx create mode 100644 src/ui/useQueue.ts create mode 100644 src/ui/useSecretRequest.ts diff --git a/README.md b/README.md index 901d0d3..ff90280 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Any mode: | `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` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back. +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` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. With the box empty after an interrupted run (or one a usage limit stopped), `enter` continues where it left off, as T3's resume button does, and releases messages held in the queue. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back. As in T3 Code's message box, typing a trigger opens a list of suggestions above the box: @@ -55,7 +55,9 @@ Navigation: | `m` | model, options (reasoning, fast mode…) and access mode | | `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | | `1`–`9` | pick an option when the agent asks a question (also in an empty message box) | -| `x` | dismiss the agent's question | +| `x` | dismiss the agent's question, or decline its secret request | +| `enter` | with a secret request pending: type or paste the secret into a masked field (it never goes through the message box); `enter` saves it, `esc` cancels | +| `Q` | go through queued messages: `j`/`k` move, `enter` sends one now (starts a turn, or steers it into the running one), `e` edits it in the message box (`enter` saves, `esc` cancels), `x` removes it. `alt+↑` in the message box edits the last one | | `e` | expand all folded turns and work groups | | `o` | load earlier turns | | `d` | show or hide thread details | @@ -76,7 +78,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code - **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, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). +- **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, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). A running subagent the web could stop gets a "Stop subagent" command in the palette. - **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. @@ -140,7 +142,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`, `orchestration:operate`, `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, 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`. +- 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), `terminal:read` and `terminal:operate` (terminals, stopping servers), `diagnostics:read` (usage limits) and `providers:manage` (spending a usage reset credit), 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. diff --git a/src/client/auth.ts b/src/client/auth.ts index e717c66..d1c2172 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -6,7 +6,7 @@ import { dirname, join } from "node:path"; * Scopes tui3 asks for: read and operate threads, read diffs, run git actions * (commit, push, open a PR), stop a thread's local servers, and use its terminals. */ -export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:read", "terminal:operate"] as const; +export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:read", "terminal:operate", "diagnostics:read", "providers:manage"] as const; export interface ServerTarget { /** e.g. http://127.0.0.1:3773 */ diff --git a/src/client/session.ts b/src/client/session.ts index e5d8848..0382092 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -10,6 +10,9 @@ import { type OrchestrationV2ThreadProjection, type ProviderApprovalDecision, type RuntimeRequestId, + type OrchestrationV2Subagent, + type RunId, + type SecretRequestAnswerInput, type ThreadId, type DiscoveredLocalServer, type GitActionProgressEvent, @@ -36,9 +39,11 @@ import { import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; import { mergeOlderHistoryIntoProjection } from "@t3tools/client-runtime/state/thread-history-merge"; import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; +import { secretRequestFailureMessage } from "@t3tools/client-runtime/secret-request"; import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { appendFileSync } from "node:fs"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -417,6 +422,69 @@ export class T3Session { return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId }); } + /** + * Ends one subagent's task, as the web's interruptThreadTurn does: an app-owned one is ended by + * its parent and its own thread stopped, even when the parent lost track of it. + */ + async stopSubagent(agent: OrchestrationV2Subagent): Promise { + const stop = (runId: RunId) => this.dispatch({ type: "subagent.stop", commandId: newCommandId(), threadId: agent.threadId, runId, subagentId: agent.id }); + if (agent.origin === "app_owned" && agent.childThreadId !== null) { + if (agent.runId !== null) await stop(agent.runId).catch(() => {}); + return this.stopThread(agent.childThreadId); + } + if (agent.runId != null) await stop(agent.runId); + } + + // The queue's controls, as the web's QueuedRunsControl sends them. + startQueuedRun(threadId: ThreadId, runId: RunId): Promise { + return this.dispatch({ type: "queued-run.start", commandId: newCommandId(), threadId, runId }); + } + + promoteQueuedRun(threadId: ThreadId, queuedRunId: RunId, targetRunId: RunId): Promise { + return this.dispatch({ type: "queued-message.promote-to-steer", commandId: newCommandId(), threadId, queuedRunId, targetRunId }); + } + + cancelQueuedRun(threadId: ThreadId, runId: RunId): Promise { + return this.dispatch({ type: "queued-run.cancel", commandId: newCommandId(), threadId, runId }); + } + + editQueuedRun(threadId: ThreadId, runId: RunId, text: string): Promise { + return this.dispatch({ type: "queued-run.edit", commandId: newCommandId(), threadId, runId, text }); + } + + /** Releases turns held after an interrupt. */ + resumeQueue(threadId: ThreadId): Promise { + return this.dispatch({ type: "queue.resume", commandId: newCommandId(), threadId }); + } + + /** The web's resume: "Continue where you left off." after an interrupted run, then the held queue. */ + async continueRun(threadId: ThreadId, runId: RunId | null, releaseQueue: boolean, modelSelection?: ModelSelection): Promise { + if (runId !== null) { + const commandId = newCommandId(); + await this.dispatch({ + type: "message.dispatch", + commandId, + threadId, + messageId: MessageId.make(commandId), + text: "Continue where you left off.", + attachments: [], + manualContinuationOfRunId: runId, + ...(modelSelection ? { modelSelection } : {}), + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + } + if (releaseQueue) await this.resumeQueue(threadId); + } + + /** Answers an agent's secret request; the server keeps the value, the thread only learns the outcome. */ + async answerSecret(input: SecretRequestAnswerInput): Promise { + const exit = await Effect.runPromiseExit(this.requireConnection().rpc[WS_METHODS.secretsAnswerRequest](input)); + // Only the server's own messages pass through, so the typed value never shows in an error. + if (Exit.isFailure(exit)) throw new Error(secretRequestFailureMessage(Cause.squash(exit.cause))); + } + // The thread menu's actions, as the web's useThreadActions sends them. settleThread(threadId: ThreadId): Promise { return this.dispatch({ type: "thread.settle", commandId: newCommandId(), threadId }); diff --git a/src/model/queue.ts b/src/model/queue.ts new file mode 100644 index 0000000..e17ef0d --- /dev/null +++ b/src/model/queue.ts @@ -0,0 +1,56 @@ +import type { OrchestrationV2ThreadProjection, RunId } from "@t3tools/contracts"; +import { secretRequestDisplay, type SecretRequestItem } from "@t3tools/client-runtime/secret-request"; +import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; +import { deriveThreadStructureRuntime } from "@t3tools/client-runtime/state/thread-execution"; +import { latestExecutedRun, latestRootProviderFailure } from "@t3tools/shared/orchestrationV2ThreadError"; + +export interface QueuedMessage { + readonly runId: RunId; + readonly text: string; + /** A guest's message keeps the guest's words: it can be removed, not rewritten. */ + readonly editable: boolean; +} + +/** What the composer's queue controls need, derived as the web's chat view derives it. */ +export interface QueueState { + readonly queued: readonly QueuedMessage[]; + readonly activeRunId: RunId | null; + /** "Send now" starts a turn with the message when idle, or steers it into the running one. */ + readonly canSendNow: boolean; + readonly canPromoteToSteer: boolean; + /** An interrupted run (or one stopped by a usage limit) the web offers to continue. */ + readonly resumableRunId: RunId | null; + /** Queued turns held back by an interrupt, released by resuming. */ + readonly held: boolean; +} + +export function queueState(projection: OrchestrationV2ThreadProjection): QueueState { + const workflow = deriveThreadQueueWorkflowState(projection); + return { + queued: workflow.queuedRuns.map(({ run, text, context }) => ({ runId: run.id, text, editable: context?.guest === undefined })), + activeRunId: workflow.activeRun?.id ?? null, + canSendNow: workflow.canSendNow, + canPromoteToSteer: workflow.canPromoteToSteer, + resumableRunId: resumableRunId(projection), + held: workflow.isHeld, + }; +} + +function resumableRunId(projection: OrchestrationV2ThreadProjection): RunId | null { + const run = latestExecutedRun(projection.runs); + if (run?.status === "interrupted") return run.id; + return run?.status === "failed" && + deriveThreadStructureRuntime(projection)?.lastErrorClass === "usage_limit" && + latestRootProviderFailure(run, projection.turnItems)?.class === "usage_limit" + ? run.id + : null; +} + +/** The oldest secret request this thread can answer: one asked here, not inherited from a fork. */ +export function pendingSecretRequest(projection: OrchestrationV2ThreadProjection): SecretRequestItem | null { + for (const projected of projection.visibleTurnItems) { + const item = projected.item; + if (item.type === "secret_request" && secretRequestDisplay(item, projected.visibility).kind === "pending") return item; + } + return null; +} diff --git a/src/model/subagents.ts b/src/model/subagents.ts new file mode 100644 index 0000000..a9018bf --- /dev/null +++ b/src/model/subagents.ts @@ -0,0 +1,14 @@ +import type { OrchestrationV2Subagent } from "@t3tools/contracts"; + +const LIVE = ["pending", "running", "waiting"]; + +/** + * Whether a subagent can be stopped from its parent, as the web's lineage panel decides: app-owned + * tasks always, Claude's native ones only with a strong task reference to aim the stop at. + */ +export function canStopSubagent(agent: OrchestrationV2Subagent): boolean { + const reachable = + agent.origin === "app_owned" || + (agent.origin === "provider_native" && agent.driver === "claudeAgent" && agent.runId != null && agent.nativeTaskRef?.strength === "strong" && agent.nativeTaskRef.nativeId !== null); + return reachable && agent.startedAt != null && LIVE.includes(agent.status); +} diff --git a/src/model/transcript.ts b/src/model/transcript.ts index 2ae5976..00f8ff3 100644 --- a/src/model/transcript.ts +++ b/src/model/transcript.ts @@ -1,4 +1,5 @@ import type { OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts"; +import { secretRequestDisplay } from "@t3tools/client-runtime/secret-request"; /** A turn item as one line or card: the fallback for timeline event rows the web app renders specially. */ export type Block = @@ -76,6 +77,10 @@ export function blockFor(item: OrchestrationV2TurnItem, pending: ReadonlySet say(`${label} failed: ${messageOf(error)}`, true), ); }; + const queue = useQueue({ + session, + threadId: draft ? undefined : threadId, + projection, + composer: () => composerRef.current, + openQuestionCount: current?.pending.userInputs.length ?? 0, + modelSelection: threadId ? pendingModels.get(threadId) : undefined, + run, + say, + toInput: () => setMode("input"), + }); + const secret = useSecretRequest({ session, projection: draft ? null : projection }); onAlert.current = (alert) => { const mode = config.notificationMode; if (mode === "sound" || mode === "notifications-and-sound") ring(); @@ -887,6 +904,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C clearComposer(); return advanceQuestion({ ...questionDraft, answers: { ...questionDraft.answers, ...(answer ? { [question.id]: answer } : {}) } }); } + if (queue.submit(text)) return; if (!text) return; clearComposer(); if (pendingApproval) { @@ -930,6 +948,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C } 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"] }); + commands.push(...secret.commands, ...queue.commands); + for (const agent of projection?.subagents ?? []) { + if (threadId && canStopSubagent(agent)) command(`stop-subagent:${agent.id}`, `Stop subagent: ${agent.title ?? "subagent"}`, () => run("Stop requested", () => session.stopSubagent(agent)), { keywords: ["interrupt", "cancel", "kill"] }); + } 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) { @@ -1112,6 +1134,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C } return; } + if (secret.key(key, mode === "nav", Boolean(pendingInput))) return key.preventDefault(); + if (queue.key(key, mode === "nav" ? "nav" : mode === "input" ? "input" : "other")) return key.preventDefault(); 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))) { @@ -1265,7 +1289,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C : "Send a message to decline and redirect the agent" : pendingInput ? "Type your own answer, or leave this blank to use the selected option" - : working + : queue.placeholder + ? queue.placeholder + : working ? config.followUpBehavior === "queue" ? "Queue a message for after this run (alt+enter to steer instead)" : "Steer the agent (alt+enter to queue instead)" @@ -1379,6 +1405,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C {shell.snapshot ? "No thread selected." : "Waiting for threads…"} )} + {mode !== "confirm" && secret.request ? : null} + {queue.queued.length > 0 ? : null} {mode !== "confirm" && pendingInput && questionDraft ? : null} {mode === "confirm" && confirmation ? ( ↑/↓ move · tab or enter choose · esc close ) : ( - {hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined })} + {hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined, secret: secret.focused ? "focused" : secret.request ? "pending" : null, queue: queue.focused ? "focused" : queue.editing ? "editing" : queue.queued.length > 0 ? "queued" : null })} )} {mode === "palette" ? ( @@ -1485,8 +1513,22 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C function hints( mode: Mode, - state: { readonly draft: boolean; readonly config: Tui3Config; readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean; readonly diff: boolean; readonly parent: boolean }, + state: { + readonly draft: boolean; + readonly config: Tui3Config; + readonly approval: boolean; + readonly question: boolean; + readonly working: boolean; + readonly attached: boolean; + readonly diff: boolean; + readonly parent: boolean; + readonly secret: "pending" | "focused" | null; + readonly queue: "queued" | "focused" | "editing" | null; + }, ): string { + if (state.secret === "focused") return "type or paste the secret · enter save securely · esc cancel"; + if (mode === "input" && state.queue === "editing") return "enter save the queued message · esc cancel the edit"; + if (mode === "nav" && state.queue === "focused") return "j/k move · enter send now · e edit · x remove · esc back"; if (mode === "filter") return "enter done · esc close"; if (mode === "palette") return "↑/↓ move · enter run · esc close"; if (mode === "picker") return "↑/↓ move · enter choose · esc close"; @@ -1499,6 +1541,7 @@ function hints( const newline = state.config.sendShortcut === "enter" ? "shift+enter or \\ newline" : "enter newline"; const parts = [state.working ? `${send} ${state.config.followUpBehavior} · alt+enter ${other}` : `${send} send`, newline, "ctrl+g editor", "esc navigate"]; if (state.question) parts.unshift("1-9 pick"); + if (state.queue === "queued") parts.splice(1, 0, "alt+↑ edit queued"); if (state.approval) parts.unshift("approval waiting: esc, then y/n"); if (!state.attached) parts.push("ctrl+n/p thread"); return parts.join(" · "); @@ -1509,7 +1552,9 @@ function hints( parts.push("i type", "c new", ". actions", "m model", "ctrl+j terminal", "l details"); if (state.parent) parts.push("u parent"); parts.push("ctrl+k commands", "q quit"); + if (state.queue === "queued") parts.unshift("Q queue"); if (state.question) parts.unshift("1-9 pick · x dismiss"); + if (state.secret === "pending") parts.unshift("enter answer the secret request · x decline"); if (state.approval) parts.unshift("y approve · Y always · n decline"); return parts.join(" · "); } diff --git a/src/ui/QueuePanel.tsx b/src/ui/QueuePanel.tsx new file mode 100644 index 0000000..c4d11ee --- /dev/null +++ b/src/ui/QueuePanel.tsx @@ -0,0 +1,37 @@ +import type { QueuedMessage } from "../model/queue.ts"; +import { colors } from "./theme.ts"; + +/** As the web: three rows, then the rest behind "show all". */ +const VISIBLE_ROWS = 3; + +/** + * The web's queued messages, just above the composer: each waits for the run to finish. Focused + * (Q), j/k move, enter sends now, e edits in the composer, x removes. + */ +export function QueuePanel(props: { readonly queued: readonly QueuedMessage[]; readonly focus: number | null; readonly editingRunId: string | null; readonly held: boolean; readonly width: number }) { + const { queued, focus } = props; + const start = focus === null ? 0 : Math.max(0, Math.min(focus - 1, queued.length - VISIBLE_ROWS)); + const shown = queued.slice(start, start + VISIBLE_ROWS); + const inner = Math.max(10, props.width - 8); + return ( + + {`${queued.length} queued${props.held ? " · held after the interrupt" : ""}`} + {shown.map((message, offset) => { + const index = start + offset; + const editing = message.runId === props.editingRunId; + return ( + + {`${index + 1}. ${truncate(message.text, inner)}`} + {editing ? {" editing in the composer"} : null} + + ); + })} + {queued.length > shown.length ? {`${queued.length - shown.length} more · Q to go through them`} : null} + + ); +} + +function truncate(text: string, width: number): string { + const single = text.replace(/\s+/g, " ").trim(); + return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; +} diff --git a/src/ui/SecretPanel.tsx b/src/ui/SecretPanel.tsx new file mode 100644 index 0000000..a767765 --- /dev/null +++ b/src/ui/SecretPanel.tsx @@ -0,0 +1,23 @@ +import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, secretRequestPrivacyNote, type SecretRequestItem } from "@t3tools/client-runtime/secret-request"; + +import { colors } from "./theme.ts"; + +/** + * The web's secret request card: the agent asks for a value it never sees. Typing is masked; + * `value` is null until the field is focused (enter). + */ +export function SecretPanel(props: { readonly request: SecretRequestItem; readonly value: string | null; readonly error: string | null; readonly busy: boolean }) { + const { request, value } = props; + const focused = value !== null; + return ( + + + {`🔒 ${request.label}`} + + {request.reason.trim() ? {request.reason} : null} + {focused ? (value ? "•".repeat(Math.min(value.length, 64)) : (request.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER)) : "enter to answer · x decline"} + {props.error ? {props.error} : null} + {props.busy ? "Saving…" : `${secretRequestPrivacyNote(request)}${focused ? " · enter save securely · esc cancel" : ""}`} + + ); +} diff --git a/src/ui/useQueue.ts b/src/ui/useQueue.ts new file mode 100644 index 0000000..9de4344 --- /dev/null +++ b/src/ui/useQueue.ts @@ -0,0 +1,156 @@ +import type { ModelSelection, OrchestrationV2ThreadProjection, RunId, ThreadId } from "@t3tools/contracts"; +import { queuedRunEditBlockedReason, resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; +import type { KeyEvent, TextareaRenderable } from "@opentui/core"; +import { useEffect, useState } from "react"; + +import type { T3Session } from "../client/session.ts"; +import { queueState, type QueuedMessage } from "../model/queue.ts"; + +interface QueuedEdit { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly original: string; + /** The composer's own draft, put back when the edit ends. */ + readonly stash: string; +} + +/** + * The web's queue controls for the open thread: send a queued message now, edit it in the + * composer, remove it, and resume after an interrupt. + */ +export function useQueue(input: { + readonly session: T3Session; + readonly threadId: ThreadId | undefined; + readonly projection: OrchestrationV2ThreadProjection | null | undefined; + readonly composer: () => TextareaRenderable | null; + readonly openQuestionCount: number; + readonly modelSelection: ModelSelection | undefined; + readonly run: (label: string, action: () => Promise) => void; + readonly say: (text: string, bad?: boolean) => void; + readonly toInput: () => void; +}) { + const { session, threadId, run, say } = input; + const queue = input.projection ? queueState(input.projection) : null; + const queued = queue?.queued ?? []; + const [focusRaw, setFocus] = useState(null); + const focus = focusRaw === null || queued.length === 0 ? null : Math.min(focusRaw, queued.length - 1); + const [editing, setEditing] = useState(null); + + const setComposer = (text: string) => { + const composer = input.composer(); + composer?.setText(text); + composer?.gotoBufferEnd(); + }; + + // An edit ends when the thread changes, or when its message leaves the queue (sent or removed). + const editLeftQueue = editing !== null && queue !== null && !queued.some((message) => message.runId === editing.runId); + useEffect(() => { + if (editing && editing.threadId !== threadId) setEditing(null); + }, [threadId]); + useEffect(() => { + if (!editLeftQueue || !editing) return; + const exit = resolveQueuedEditExit({ editChanged: (input.composer()?.plainText ?? "") !== editing.original, threadDraftEmpty: editing.stash.trim() === "" }); + if (exit !== "kept") setComposer(editing.stash); + say(exit === "kept" ? "That message left the queue; your edit stays in the composer" : "That message left the queue"); + setEditing(null); + }, [editLeftQueue]); + + const beginEdit = (message: QueuedMessage) => { + if (!threadId) return; + if (!message.editable) return say("A guest's message can be removed, not edited", true); + const blocked = queuedRunEditBlockedReason({ openQuestionCount: input.openQuestionCount }); + if (blocked) return say(blocked, true); + const stash = editing ? editing.stash : (input.composer()?.plainText ?? ""); + setEditing({ threadId, runId: message.runId, original: message.text, stash }); + setComposer(message.text); + setFocus(null); + input.toInput(); + }; + + const cancelEdit = () => { + if (!editing) return; + setComposer(editing.stash); + setEditing(null); + }; + + const sendNow = (message: QueuedMessage) => { + if (!threadId || !queue) return; + if (queue.canSendNow) return run("Sent", () => session.startQueuedRun(threadId, message.runId)); + if (queue.canPromoteToSteer && queue.activeRunId) return run("Steered", () => session.promoteQueuedRun(threadId, message.runId, queue.activeRunId!)); + say("This message waits for the current run to finish", true); + }; + + const remove = (message: QueuedMessage) => threadId && run("Removed from queue", () => session.cancelQueuedRun(threadId, message.runId)); + + const canResume = queue !== null && (queue.resumableRunId !== null || queue.held); + const resume = () => { + if (!threadId || !queue || !canResume) return; + run(queue.resumableRunId ? "Continuing" : "Sending held messages", () => session.continueRun(threadId, queue.resumableRunId, queue.held, input.modelSelection)); + }; + + /** Enter in the composer: saves an edit, or resumes when the box is empty. True when handled. */ + const submit = (text: string): boolean => { + if (editing && threadId) { + if (!text) { + say("A queued message can't be empty; Q then x removes it", true); + return true; + } + const { runId, stash } = editing; + setEditing(null); + setComposer(stash); + run("Queued message updated", () => session.editQueuedRun(threadId, runId, text)); + return true; + } + if (!text && canResume) { + resume(); + return true; + } + return false; + }; + + const key = (event: KeyEvent, mode: "nav" | "input" | "other"): boolean => { + if (mode === "nav" && focus !== null) { + const message = queued[focus]!; + switch (event.name) { + case "j": + case "down": + return setFocus(Math.min(queued.length - 1, focus + 1)), true; + case "k": + case "up": + return setFocus(Math.max(0, focus - 1)), true; + case "return": + case "s": + return sendNow(message), true; + case "e": + return beginEdit(message), true; + case "x": + case "d": + case "backspace": + return remove(message), true; + case "escape": + case "q": + return setFocus(null), true; + } + return false; + } + if (mode === "nav" && event.name === "q" && event.shift && queued.length > 0) return setFocus(0), true; + // The web's alt+↑: edit the last queued message. + if (mode === "input" && event.meta && event.name === "up" && !editing && queued.length > 0) return beginEdit(queued[queued.length - 1]!), true; + if (mode === "input" && event.name === "escape" && editing) return cancelEdit(), true; + return false; + }; + + const first = queued[0]; + const last = queued[queued.length - 1]; + const commands = [ + ...(first && queue && (queue.canSendNow || queue.canPromoteToSteer) ? [{ id: "queue-send", title: "Queue: send first queued message", run: () => sendNow(first), keywords: ["steer", "now"] }] : []), + ...(last ? [{ id: "queue-edit", title: "Queue: edit last queued message", run: () => beginEdit(last), shortcut: "alt+↑", keywords: ["change"] }] : []), + ...(queued.length > 0 ? [{ id: "queue-focus", title: "Queue: go through queued messages", run: () => setFocus(0), shortcut: "Q", keywords: ["remove", "cancel", "delete"] }] : []), + ...queued.map((message, index) => ({ id: `queue-remove:${message.runId}`, title: `Queue: remove ${index + 1}. ${message.text.replace(/\s+/g, " ").slice(0, 60)}`, run: () => remove(message), keywords: ["cancel", "delete"] })), + ...(canResume ? [{ id: "queue-resume", title: queue?.resumableRunId ? "Continue where it left off" : "Send held queued messages", run: resume, keywords: ["resume", "interrupted"] }] : []), + ]; + + const placeholder = editing ? "Edit the queued message (enter saves, esc cancels)" : canResume ? (queue?.resumableRunId ? "Ask anything, or press enter to continue where it left off" : "Ask anything, or press enter to send the held messages") : null; + + return { queue, queued, focus, focused: focus !== null, editingRunId: editing?.runId ?? null, editing: editing !== null, key, submit, commands, placeholder }; +} diff --git a/src/ui/useSecretRequest.ts b/src/ui/useSecretRequest.ts new file mode 100644 index 0000000..0a209ac --- /dev/null +++ b/src/ui/useSecretRequest.ts @@ -0,0 +1,71 @@ +import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { secretRequestAnswerInput } from "@t3tools/client-runtime/secret-request"; +import type { KeyEvent } from "@opentui/core"; +import { usePaste } from "@opentui/react"; +import { useEffect, useState } from "react"; + +import type { T3Session } from "../client/session.ts"; +import { pendingSecretRequest } from "../model/queue.ts"; + +const decoder = new TextDecoder(); + +/** + * The open thread's pending secret request and its masked field. The field takes keys itself + * (the composer never sees the value, so it can't be sent as a message by mistake). + */ +export function useSecretRequest(input: { readonly session: T3Session; readonly projection: OrchestrationV2ThreadProjection | null | undefined }) { + const request = input.projection ? pendingSecretRequest(input.projection) : null; + const [value, setValue] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + setValue(null); + setError(null); + }, [request?.id]); + + usePaste((event) => { + if (value === null) return; + event.preventDefault(); + setValue(value + decoder.decode(event.bytes).replace(/[\r\n]+/g, "")); + }); + + const answer = (reply: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" }) => { + const answerInput = request ? secretRequestAnswerInput(request, reply) : null; + if (!answerInput || busy) return; + setBusy(true); + setError(null); + input.session + .answerSecret(answerInput) + .then(() => setValue(null)) + .catch((failure: unknown) => setError(failure instanceof Error ? failure.message : String(failure))) + .finally(() => setBusy(false)); + }; + + /** Keys for the field while it's focused, and enter / x on the card in navigation. */ + const key = (event: KeyEvent, nav: boolean, questionPending: boolean): boolean => { + if (!request) return false; + if (value === null) { + if (!nav) return false; + if (event.name === "return") return setValue(""), true; + if (event.name === "x" && !questionPending) return answer({ type: "decline" }), true; + return false; + } + if (event.ctrl && event.name === "c") return false; + if (event.name === "escape") setValue(null); + else if (event.name === "return") answer({ type: "save", secret: value }); + else if (event.name === "backspace") setValue(value.slice(0, -1)); + else if (event.ctrl && event.name === "u") setValue(""); + else if (!event.ctrl && !event.meta && event.sequence.length === 1 && event.sequence >= " ") setValue(value + event.sequence); + return true; + }; + + const commands = request + ? [ + { id: "secret-answer", title: `Answer secret request: ${request.label}`, run: () => setValue(""), shortcut: "enter", keywords: ["password", "token", "key", "credential"] }, + { id: "secret-decline", title: `Decline secret request: ${request.label}`, run: () => answer({ type: "decline" }), keywords: ["password", "token", "key", "credential"] }, + ] + : []; + + return { request, value, error, busy, focused: value !== null, key, commands }; +} diff --git a/test/commands.test.ts b/test/commands.test.ts index 70b9ffd..7faa7db 100644 --- a/test/commands.test.ts +++ b/test/commands.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { OrchestrationV2Command, OrchestrationV2ThreadLaunchInput, ProjectId, ProviderInstanceId, ThreadId, RuntimeRequestId } from "@t3tools/contracts"; +import { NodeId, OrchestrationV2Command, OrchestrationV2ThreadLaunchInput, ProjectId, ProviderInstanceId, RunId, ThreadId, RuntimeRequestId, type OrchestrationV2Subagent } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -95,3 +95,35 @@ describe("commands tui3 dispatches", () => { expect(payload).toMatchObject({ initialMessage: { text: "Fix the flaky test", attachments: [] } }); }); }); + +describe("queue, resume and subagent commands", () => { + const runId = RunId.make("run-2"); + + test("queue controls dispatch as the web's QueuedRunsControl", async () => { + const { session, sent } = capturingSession(); + await session.startQueuedRun(threadId, runId); + await session.promoteQueuedRun(threadId, runId, RunId.make("run-1")); + await session.cancelQueuedRun(threadId, runId); + await session.editQueuedRun(threadId, runId, "reworded"); + await session.resumeQueue(threadId); + expect(sent.every(isCommand)).toBe(true); + expect(sent.map((command) => (command as { type: string }).type)).toEqual(["queued-run.start", "queued-message.promote-to-steer", "queued-run.cancel", "queued-run.edit", "queue.resume"]); + }); + + test("resuming continues the interrupted run, then releases the held queue", async () => { + const { session, sent } = capturingSession(); + await session.continueRun(threadId, RunId.make("run-1"), true); + expect(sent.every(isCommand)).toBe(true); + expect(sent[0]).toMatchObject({ type: "message.dispatch", text: "Continue where you left off.", manualContinuationOfRunId: "run-1", dispatchMode: { type: "start_immediately" } }); + expect(sent[1]).toMatchObject({ type: "queue.resume" }); + }); + + test("an app-owned subagent is stopped from its parent and in its own thread", async () => { + const { session, sent } = capturingSession(); + const child = ThreadId.make("child-1"); + await session.stopSubagent({ id: NodeId.make("node-1"), threadId, runId: RunId.make("run-1"), origin: "app_owned", childThreadId: child } as OrchestrationV2Subagent); + expect(sent.every(isCommand)).toBe(true); + expect(sent[0]).toMatchObject({ type: "subagent.stop", threadId, subagentId: "node-1" }); + expect(sent[1]).toMatchObject({ type: "thread.stop", threadId: child }); + }); +});