// An answer chosen on an alert, delivered to the session that asked, wherever // the reader is looking. The alert's buttons never move the view: the keys go // to the session's terminal over a link of its own, and the card says what // became of them. // // WHICH LINK. A pane that shows the session, in Chat or Term, in any split, // already holds a live connection and says so (registerSessionLink); the // answer goes through it. A session no pane shows gets a short connection of // its own, opened for this one answer and closed after it (alert-link.ts), so // the answer needs no Chat view mounted and no pane taken over. // // NOTHING IS SENT UNREAD. The screen is read first: a permission prompt must // show the row the button names (answer-intent.ts matchIntent, the same words // check the Decision card makes), a question must show its question and its // options. The steps carry what the screen has to show before each key // (use-terminal-session.ts sendAsk), so a prompt that moved is never answered. // // ONCE. A session's answer is single-flight: a second press while the first is // on its way, or after it was sent, does nothing (the card's status says so). import { askSteps, screenShows, type AskStep } from "./ask-keys"; import type { ChatQuestion } from "./components/chat/chat-model"; import type { AlertChoice, AlertModel } from "./alert-model"; import { matchIntent, type AnswerIntent } from "./answer-intent"; import { promptSteps, readScreenPrompt, rowRole } from "./screen-prompt"; import type { AskSendResult } from "./use-terminal-session"; /** Why an answer was not sent, or not known to be. */ export type AnswerMiss = /** The prompt is not the one the alert was raised for, or is gone. */ | "changed" /** The session has stopped waiting: answered elsewhere, or ended. */ | "gone" /** The session could not be reached, or is read only. Nothing went. */ | "unavailable" /** Some keys went before it stopped. Look at the session. */ | "partial" /** The row changes the session's rules: only in Term. */ | "locked" /** The alert cannot name this answer's keys. */ | "unsupported"; /** What an alert's card shows about its answer. */ export type AnswerStatus = | { kind: "pending" } | { kind: "sent" } | { kind: "failed"; reason: AnswerMiss }; /** The way to a session's terminal: its screen as it reads now, and the keys. */ export interface SessionLink { readScreen(): string | null; sendAsk(steps: readonly AskStep[]): Promise; } /** A link opened for one answer; `close` ends it. */ export interface OpenedLink { link: SessionLink; close(): void } // ── the links the panes hold ──────────────────────────────────────────────── const held = new Map(); /** A pane shows `sessionId` and can write to it. The returned function takes * the link back (the pane moved on, went read only, or closed). */ export function registerSessionLink(sessionId: string, link: SessionLink): () => void { held.set(sessionId, [...(held.get(sessionId) ?? []), link]); return () => { const rest = (held.get(sessionId) ?? []).filter(l => l !== link); if (rest.length) held.set(sessionId, rest); else held.delete(sessionId); }; } /** The newest pane's link for a session, or null when no pane holds one. */ export function sessionLinkFor(sessionId: string): SessionLink | null { return held.get(sessionId)?.at(-1) ?? null; } /** Tests: no pane holds anything. */ export function resetSessionLinks(): void { held.clear(); } // ── planning ──────────────────────────────────────────────────────────────── export type Plan = { ok: true; steps: AskStep[] } | { ok: false; reason: AnswerMiss }; const miss = (reason: AnswerMiss): Plan => ({ ok: false, reason }); /** The keys that answer `alert` with `choice` on the screen as it reads now. */ export function planAnswer(alert: AlertModel, choice: AlertChoice, screen: string | null): Plan { if (screen === null) return miss("unavailable"); if (choice.intent === "permission") return planPermission(alert, choice, screen); return planQuestion(alert, choice, screen); } function planPermission(alert: AlertModel, choice: AlertChoice, screen: string): Plan { const prompt = readScreenPrompt(screen); if (!prompt || prompt.kind !== "permission") return miss("changed"); const rows = prompt.options.map(label => ({ label, ...(rowRole("permission", label) === "answer" ? null : { locked: true }) })); const intent: AnswerIntent = { id: 0, sessionId: alert.sessionId, kind: "permission", choiceLabel: choice.label, choiceIndex: choice.index, ...(alert.detail ? { detail: alert.detail } : null), createdAt: 0, expiresAt: Number.POSITIVE_INFINITY, }; const m = matchIntent(intent, rows, 0, undefined, screen); if (!m.ok) return miss(m.reason === "locked" ? "locked" : "changed"); const steps = promptSteps(prompt, m.index); return steps ? { ok: true, steps } : miss("unsupported"); } function planQuestion(alert: AlertModel, choice: AlertChoice, screen: string): Plan { const ask = alert.ask; if (!ask || choice.index === null || ask.options[choice.index] !== choice.label) return miss("unsupported"); const question: ChatQuestion = { header: "", question: ask.question, multi: false, ...(ask.preview ? { preview: true } : null), options: ask.options.map(label => ({ label, description: "" })), }; const steps = askSteps([question], [{ options: [choice.index] }]); if (!steps) return miss("unsupported"); return screenShows(screen, steps[0].expect) ? { ok: true, steps } : miss("changed"); } // ── delivery ──────────────────────────────────────────────────────────────── /** How long the screen is given to show the prompt before the answer is given up. */ export const ANSWER_READ_MS = 5000; /** How often it is looked at in that time. */ export const ANSWER_POLL_MS = 100; export interface AnswerDeps { /** A pane's link for the session, when one holds it. */ link(sessionId: string): SessionLink | null; /** A link of its own, for a session no pane holds; null when none can be had. */ open?(sessionId: string): Promise; /** Whether the session still waits on the block the alert was raised for. */ waiting(alert: AlertModel): boolean; now?(): number; sleep?(ms: number): Promise; } const nap = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); const SENT: Record = { sent: { kind: "sent" }, changed: { kind: "failed", reason: "changed" }, partial: { kind: "failed", reason: "partial" }, unavailable: { kind: "failed", reason: "unavailable" }, }; /** Sends `choice` to the session `alert` was raised for, once the screen shows * its prompt, and says what became of it. Never throws. */ export async function deliverAnswer(alert: AlertModel, choice: AlertChoice, deps: AnswerDeps): Promise { const now = deps.now ?? Date.now; const sleep = deps.sleep ?? nap; const failed = (reason: AnswerMiss): AnswerStatus => ({ kind: "failed", reason }); if (!deps.waiting(alert)) return failed("gone"); let opened: OpenedLink | null = null; try { let link = deps.link(alert.sessionId); if (!link) { opened = deps.open ? await deps.open(alert.sessionId) : null; if (!opened) return failed("unavailable"); link = opened.link; } const until = now() + ANSWER_READ_MS; let plan: Plan = miss("unavailable"); for (;;) { if (!deps.waiting(alert)) return failed("gone"); plan = planAnswer(alert, choice, link.readScreen()); if (plan.ok || plan.reason === "locked" || plan.reason === "unsupported") break; if (now() >= until) break; await sleep(ANSWER_POLL_MS); } if (!plan.ok) return failed(plan.reason); if (!deps.waiting(alert)) return failed("gone"); return SENT[await link.sendAsk(plan.steps)]; } catch { return failed("unavailable"); } finally { opened?.close(); } }