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.
This commit is contained in:
Callum Alpass committed 2026-11-02 20:36:39 +11:00
1 parent 43347d1d58
commit a8e35ee83a
12 files changed
+518 -9

No files matched your search

+1 -1
View File
@@ -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 */
+68
View File
@@ -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<void> {
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<void> {
return this.dispatch({ type: "queued-run.start", commandId: newCommandId(), threadId, runId });
}
promoteQueuedRun(threadId: ThreadId, queuedRunId: RunId, targetRunId: RunId): Promise<void> {
return this.dispatch({ type: "queued-message.promote-to-steer", commandId: newCommandId(), threadId, queuedRunId, targetRunId });
}
cancelQueuedRun(threadId: ThreadId, runId: RunId): Promise<void> {
return this.dispatch({ type: "queued-run.cancel", commandId: newCommandId(), threadId, runId });
}
editQueuedRun(threadId: ThreadId, runId: RunId, text: string): Promise<void> {
return this.dispatch({ type: "queued-run.edit", commandId: newCommandId(), threadId, runId, text });
}
/** Releases turns held after an interrupt. */
resumeQueue(threadId: ThreadId): Promise<void> {
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<void> {
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<void> {
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<void> {
return this.dispatch({ type: "thread.settle", commandId: newCommandId(), threadId });
+56
View File
@@ -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;
}
+14
View File
@@ -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);
}
+5
View File
@@ -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<str
return { kind: "notice", id, text: item.summary, tone: item.outcome === "failed" ? "bad" : item.outcome === "completed" ? "good" : "muted" };
case "compaction":
return { kind: "notice", id, text: "context compacted", tone: "muted" };
case "secret_request": {
const display = secretRequestDisplay(item, "local");
return { kind: "notice", id, text: `🔒 ${item.label} · ${display.kind === "answered" ? display.label : "waiting for your answer"}`, tone: display.kind === "answered" ? "muted" : "warn" };
}
case "handoff":
return { kind: "notice", id, text: `handed off${item.toModel ? ` to ${item.toModel}` : ""}`, tone: "muted" };
case "checkpoint":
+48 -3
View File
@@ -34,12 +34,17 @@ import { DraftView, type DraftLine } from "./DraftView.tsx";
import { editInEditor } from "./editor.ts";
import { Palette } from "./Palette.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx";
import { QueuePanel } from "./QueuePanel.tsx";
import { SecretPanel } from "./SecretPanel.tsx";
import { SettingsView } from "./SettingsView.tsx";
import { attachTerminal } from "./terminalAttach.ts";
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx";
import { ThreadView } from "./ThreadView.tsx";
import { useQueue } from "./useQueue.ts";
import { useSecretRequest } from "./useSecretRequest.ts";
import { canStopSubagent } from "../model/subagents.ts";
/**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve.
@@ -328,6 +333,18 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
(error) => 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
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
</box>
)}
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} /> : null}
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} /> : null}
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
{mode === "confirm" && confirmation ? (
<ConfirmBar
@@ -1445,7 +1473,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
) : menuOpen ? (
<text fg={colors.faint}>↑/↓ move · tab or enter choose · esc close</text>
) : (
<text fg={colors.faint}>{hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined })}</text>
<text fg={colors.faint}>{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 })}</text>
)}
</box>
{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(" · ");
}
+37
View File
@@ -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 (
<box border borderStyle="rounded" borderColor={focus === null ? colors.border : colors.borderFocused} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
<text fg={colors.muted}>{`${queued.length} queued${props.held ? " · held after the interrupt" : ""}`}</text>
{shown.map((message, offset) => {
const index = start + offset;
const editing = message.runId === props.editingRunId;
return (
<box key={message.runId} flexDirection="row" backgroundColor={index === focus ? colors.selectedBg : "transparent"}>
<text fg={editing ? colors.accent : colors.text}>{`${index + 1}. ${truncate(message.text, inner)}`}</text>
{editing ? <text fg={colors.accent}>{" editing in the composer"}</text> : null}
</box>
);
})}
{queued.length > shown.length ? <text fg={colors.faint}>{`${queued.length - shown.length} more · Q to go through them`}</text> : null}
</box>
);
}
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;
}
+23
View File
@@ -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 (
<box border borderStyle="rounded" borderColor={focused ? colors.borderFocused : colors.warn} flexDirection="column" flexShrink={0} marginLeft={1} marginRight={1} paddingLeft={1} paddingRight={1}>
<text fg={colors.warn}>
<strong>{`🔒 ${request.label}`}</strong>
</text>
{request.reason.trim() ? <text fg={colors.muted}>{request.reason}</text> : null}
<text fg={focused && value ? colors.text : colors.faint}>{focused ? (value ? "•".repeat(Math.min(value.length, 64)) : (request.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER)) : "enter to answer · x decline"}</text>
{props.error ? <text fg={colors.bad}>{props.error}</text> : null}
<text fg={colors.faint}>{props.busy ? "Saving…" : `${secretRequestPrivacyNote(request)}${focused ? " · enter save securely · esc cancel" : ""}`}</text>
</box>
);
}
+156
View File
@@ -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<unknown>) => 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<number | null>(null);
const focus = focusRaw === null || queued.length === 0 ? null : Math.min(focusRaw, queued.length - 1);
const [editing, setEditing] = useState<QueuedEdit | null>(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 };
}
+71
View File
@@ -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<string | null>(null);
const [error, setError] = useState<string | null>(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 };
}