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:
1 parent
43347d1d58
commit
a8e35ee83a
12 files changed
+517
-8
No files matched your search
@@ -33,7 +33,7 @@ Any mode:
|
|||||||
| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation |
|
| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation |
|
||||||
| `ctrl+c` | quit |
|
| `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:
|
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 |
|
| `m` | model, options (reasoning, fast mode…) and access mode |
|
||||||
| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval |
|
| `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) |
|
| `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 |
|
| `e` | expand all folded turns and work groups |
|
||||||
| `o` | load earlier turns |
|
| `o` | load earlier turns |
|
||||||
| `d` | show or hide thread details |
|
| `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.
|
- **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.
|
- **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).
|
- **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.
|
- **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.
|
- **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.
|
- 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
|
## How it connects
|
||||||
|
|
||||||
- It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`).
|
- 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`).
|
- 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.
|
Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots.
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@ import { dirname, join } from "node:path";
|
|||||||
* Scopes tui3 asks for: read and operate threads, read diffs, run git actions
|
* 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.
|
* (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 {
|
export interface ServerTarget {
|
||||||
/** e.g. http://127.0.0.1:3773 */
|
/** e.g. http://127.0.0.1:3773 */
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ import {
|
|||||||
type OrchestrationV2ThreadProjection,
|
type OrchestrationV2ThreadProjection,
|
||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type RuntimeRequestId,
|
type RuntimeRequestId,
|
||||||
|
type OrchestrationV2Subagent,
|
||||||
|
type RunId,
|
||||||
|
type SecretRequestAnswerInput,
|
||||||
type ThreadId,
|
type ThreadId,
|
||||||
type DiscoveredLocalServer,
|
type DiscoveredLocalServer,
|
||||||
type GitActionProgressEvent,
|
type GitActionProgressEvent,
|
||||||
@@ -36,9 +39,11 @@ import {
|
|||||||
import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";
|
import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";
|
||||||
import { mergeOlderHistoryIntoProjection } from "@t3tools/client-runtime/state/thread-history-merge";
|
import { mergeOlderHistoryIntoProjection } from "@t3tools/client-runtime/state/thread-history-merge";
|
||||||
import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
|
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 { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
|
||||||
import { appendFileSync } from "node:fs";
|
import { appendFileSync } from "node:fs";
|
||||||
|
|
||||||
|
import * as Cause from "effect/Cause";
|
||||||
import * as Effect from "effect/Effect";
|
import * as Effect from "effect/Effect";
|
||||||
import * as Exit from "effect/Exit";
|
import * as Exit from "effect/Exit";
|
||||||
import * as Fiber from "effect/Fiber";
|
import * as Fiber from "effect/Fiber";
|
||||||
@@ -417,6 +422,69 @@ export class T3Session {
|
|||||||
return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId });
|
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.
|
// The thread menu's actions, as the web's useThreadActions sends them.
|
||||||
settleThread(threadId: ThreadId): Promise<void> {
|
settleThread(threadId: ThreadId): Promise<void> {
|
||||||
return this.dispatch({ type: "thread.settle", commandId: newCommandId(), threadId });
|
return this.dispatch({ type: "thread.settle", commandId: newCommandId(), threadId });
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { OrchestrationV2TurnItem, RuntimeRequestId } from "@t3tools/contracts";
|
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. */
|
/** A turn item as one line or card: the fallback for timeline event rows the web app renders specially. */
|
||||||
export type Block =
|
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" };
|
return { kind: "notice", id, text: item.summary, tone: item.outcome === "failed" ? "bad" : item.outcome === "completed" ? "good" : "muted" };
|
||||||
case "compaction":
|
case "compaction":
|
||||||
return { kind: "notice", id, text: "context compacted", tone: "muted" };
|
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":
|
case "handoff":
|
||||||
return { kind: "notice", id, text: `handed off${item.toModel ? ` to ${item.toModel}` : ""}`, tone: "muted" };
|
return { kind: "notice", id, text: `handed off${item.toModel ? ` to ${item.toModel}` : ""}`, tone: "muted" };
|
||||||
case "checkpoint":
|
case "checkpoint":
|
||||||
|
|||||||
+47
-2
@@ -34,12 +34,17 @@ import { DraftView, type DraftLine } from "./DraftView.tsx";
|
|||||||
import { editInEditor } from "./editor.ts";
|
import { editInEditor } from "./editor.ts";
|
||||||
import { Palette } from "./Palette.tsx";
|
import { Palette } from "./Palette.tsx";
|
||||||
import { QuestionPanel } from "./QuestionPanel.tsx";
|
import { QuestionPanel } from "./QuestionPanel.tsx";
|
||||||
|
import { QueuePanel } from "./QueuePanel.tsx";
|
||||||
|
import { SecretPanel } from "./SecretPanel.tsx";
|
||||||
import { SettingsView } from "./SettingsView.tsx";
|
import { SettingsView } from "./SettingsView.tsx";
|
||||||
import { attachTerminal } from "./terminalAttach.ts";
|
import { attachTerminal } from "./terminalAttach.ts";
|
||||||
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
|
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
import { ThreadList } from "./ThreadList.tsx";
|
import { ThreadList } from "./ThreadList.tsx";
|
||||||
import { ThreadView } from "./ThreadView.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.
|
* "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),
|
(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) => {
|
onAlert.current = (alert) => {
|
||||||
const mode = config.notificationMode;
|
const mode = config.notificationMode;
|
||||||
if (mode === "sound" || mode === "notifications-and-sound") ring();
|
if (mode === "sound" || mode === "notifications-and-sound") ring();
|
||||||
@@ -887,6 +904,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
clearComposer();
|
clearComposer();
|
||||||
return advanceQuestion({ ...questionDraft, answers: { ...questionDraft.answers, ...(answer ? { [question.id]: answer } : {}) } });
|
return advanceQuestion({ ...questionDraft, answers: { ...questionDraft.answers, ...(answer ? { [question.id]: answer } : {}) } });
|
||||||
}
|
}
|
||||||
|
if (queue.submit(text)) return;
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
clearComposer();
|
clearComposer();
|
||||||
if (pendingApproval) {
|
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 && 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) 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 (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"] });
|
if (details?.changes && details.changes.files.length > 0) command("diff", "View uncommitted changes", () => openDiff(null), { keywords: ["diff", "changes"] });
|
||||||
for (const action of actions) {
|
for (const action of actions) {
|
||||||
@@ -1112,6 +1134,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
}
|
}
|
||||||
return;
|
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();
|
if (globalKey(key)) return key.preventDefault();
|
||||||
const digit = /^[1-9]$/.test(key.name) && !key.ctrl && !key.meta ? Number(key.name) - 1 : -1;
|
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))) {
|
if (digit >= 0 && pendingInput && (mode === "nav" || (mode === "input" && composerEmpty))) {
|
||||||
@@ -1265,6 +1289,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
: "Send a message to decline and redirect the agent"
|
: "Send a message to decline and redirect the agent"
|
||||||
: pendingInput
|
: pendingInput
|
||||||
? "Type your own answer, or leave this blank to use the selected option"
|
? "Type your own answer, or leave this blank to use the selected option"
|
||||||
|
: queue.placeholder
|
||||||
|
? queue.placeholder
|
||||||
: working
|
: working
|
||||||
? config.followUpBehavior === "queue"
|
? config.followUpBehavior === "queue"
|
||||||
? "Queue a message for after this run (alt+enter to steer instead)"
|
? "Queue a message for after this run (alt+enter to steer 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>
|
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
|
||||||
</box>
|
</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" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
|
||||||
{mode === "confirm" && confirmation ? (
|
{mode === "confirm" && confirmation ? (
|
||||||
<ConfirmBar
|
<ConfirmBar
|
||||||
@@ -1445,7 +1473,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
) : menuOpen ? (
|
) : menuOpen ? (
|
||||||
<text fg={colors.faint}>↑/↓ move · tab or enter choose · esc close</text>
|
<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>
|
</box>
|
||||||
{mode === "palette" ? (
|
{mode === "palette" ? (
|
||||||
@@ -1485,8 +1513,22 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
|
|
||||||
function hints(
|
function hints(
|
||||||
mode: Mode,
|
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 {
|
): 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 === "filter") return "enter done · esc close";
|
||||||
if (mode === "palette") return "↑/↓ move · enter run · esc close";
|
if (mode === "palette") return "↑/↓ move · enter run · esc close";
|
||||||
if (mode === "picker") return "↑/↓ move · enter choose · 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 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"];
|
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.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.approval) parts.unshift("approval waiting: esc, then y/n");
|
||||||
if (!state.attached) parts.push("ctrl+n/p thread");
|
if (!state.attached) parts.push("ctrl+n/p thread");
|
||||||
return parts.join(" · ");
|
return parts.join(" · ");
|
||||||
@@ -1509,7 +1552,9 @@ function hints(
|
|||||||
parts.push("i type", "c new", ". actions", "m model", "ctrl+j terminal", "l details");
|
parts.push("i type", "c new", ". actions", "m model", "ctrl+j terminal", "l details");
|
||||||
if (state.parent) parts.push("u parent");
|
if (state.parent) parts.push("u parent");
|
||||||
parts.push("ctrl+k commands", "q quit");
|
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.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");
|
if (state.approval) parts.unshift("y approve · Y always · n decline");
|
||||||
return parts.join(" · ");
|
return parts.join(" · ");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
+33
-1
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, test } from "bun:test";
|
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 Effect from "effect/Effect";
|
||||||
import * as Schema from "effect/Schema";
|
import * as Schema from "effect/Schema";
|
||||||
|
|
||||||
@@ -95,3 +95,35 @@ describe("commands tui3 dispatches", () => {
|
|||||||
expect(payload).toMatchObject({ initialMessage: { text: "Fix the flaky test", attachments: [] } });
|
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 });
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user