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
+518
-9
No files matched your search
+48
-3
@@ -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(" · ");
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user