diff --git a/pi-ask/CHANGELOG.md b/pi-ask/CHANGELOG.md index 168e44c..4317425 100644 --- a/pi-ask/CHANGELOG.md +++ b/pi-ask/CHANGELOG.md @@ -13,6 +13,7 @@ - **Cancel with a comment and skip.** `c` on the review tab attaches a short reason to a cancellation. `s` declines one question without cancelling the form; skipped is neither an answer nor approval. - **Configuration and keys.** New keys `behaviour.background`, `expiry.enabled` and `expiry.minSeconds`, plus keymaps `global.later`, `global.panelFocus`, `main.skip` and `main.cancelComment`. `/ask-settings` exposes the expiry toggles; schema changes apply on `/reload`. `/ask-panel` shows waiting and expired forms. - **Hosts without the custom TUI** keep the blocking card flow: `background` blocks there and there is no countdown. +- **Fixed.** A failed journal read on attach or a failed countdown-stop write no longer breaks panel refresh or swallows the first keystroke, and a blocking reply that could not be saved now returns the form to the panel with an error notice and tells the agent not to re-ask. - The default `ask_user` context footprint is 1,598 chars (≈ 400 tokens), or 1,534 (≈ 384) with expiry off, within the existing 450/420 token ceilings. ## 0.1.5 diff --git a/pi-ask/README.md b/pi-ask/README.md index e3d388b..4bef33e 100644 --- a/pi-ask/README.md +++ b/pi-ask/README.md @@ -117,7 +117,7 @@ The later answer is a `pi-ask:answer` message that names the request and each qu Every form, draft and outcome is journalled in the session. A form left open when Pi quit comes back in the panel on startup, resume or fork with its draft, and its answer reaches the agent once: delivery is decided from what the active branch already holds. The journal follows the active branch. -A receipt or completed tool result requires a successful journal write. Storage failures are reported rather than acknowledged; a panel form whose answer could not be saved stays editable for retry. Hiding the panel or temporarily covering it with a blocking form preserves its live editor, including typing not yet flushed to the journal. +A receipt or completed tool result requires a successful journal write. Storage failures are reported rather than acknowledged; a panel form whose answer could not be saved stays editable for retry. Only panel forms are retried in place: if a blocking form's answer (or cancel, defer or expiry) cannot be saved, the form returns to the panel at once with its draft and you get an error notice, and the tool returns an error telling the agent the reply was not saved, the form will reappear in your panel and it should not re-ask. The non-TUI (RPC and print) path also requires the journal write before it returns. Hiding the panel or temporarily covering it with a blocking form preserves its live editor, including typing not yet flushed to the journal. Optional config: `~/.pi/agent/extensions/pi-ask.json`. `/answer` uses the current chat model unless `answer.extractionModels` is set. `PI_ASK_LOCALE=zh` localizes the dialog cards and result summaries (Simplified Chinese). diff --git a/pi-ask/src/ask-tool.ts b/pi-ask/src/ask-tool.ts index 90e250c..b2d6d65 100644 --- a/pi-ask/src/ask-tool.ts +++ b/pi-ask/src/ask-tool.ts @@ -15,7 +15,7 @@ import { import { getAskConfigStore } from "./config/store.ts"; import { type AskFeatures, NO_ASK_FEATURES } from "./features.ts"; import { buildAskParamsSchema, stripSchemaDescriptions } from "./schema.ts"; -import { toFormSnapshot } from "./journal/journal.ts"; +import { AskJournalWriteError, describeExpiryStopFailure, toFormSnapshot } from "./journal/journal.ts"; import { type AskRuntime, createAskRuntime } from "./runtime.ts"; import { createExpiryTimer, @@ -62,7 +62,7 @@ export function registerAskTool(pi: ExtensionAPI, options: AskToolOptions = {}) } async function executeAskTool( - { background, clock, flushers, journal, live }: AskRuntime, + { background, clock, flushers, journal, live, returning, unsaved }: AskRuntime, features: AskFeatures, toolCallId: string, params: AskParams, @@ -125,6 +125,13 @@ async function executeAskTool( // A stopped countdown is journalled, so no rebuild can bring it back. timer?.subscribe({ stop: (reason) => journal.recordExpiryStop(requestId, reason), + failed: (error) => { + if (error instanceof AskJournalWriteError) { + ctx.ui.notify(describeExpiryStopFailure(error), "error"); + return true; + } + return false; + }, }); const openForm = () => runAskFlow(ctx, params, { @@ -152,11 +159,18 @@ async function executeAskTool( if (background && result.status === "deferred") { // "Answer later": the form keeps its request-order place in the queue // and its draft; the answer follows as a message. - journal.recordDefer(requestId); + saved(ctx, background, unsaved, requestId, "deferred", () => + journal.recordDefer(requestId) + ); background.enqueue(ctx, requestId, "deferred"); return successfulResponse(receipt(validation.state, "deferred", requestId)); } - const outcome = journal.recordOutcome(requestId, result, "tool"); + const outcome = saved(ctx, background, unsaved, requestId, result.status, () => + journal.recordOutcome(requestId, result, "tool") + ); + // The tool result follows this return; until it lands on the branch the + // answer must not also be adopted as an orphan. + returning.add(requestId); if (result.status === "expired") { // It can now be reopened for a late correction. background?.formEnded(ctx); @@ -164,6 +178,43 @@ async function executeAskTool( return successfulResponse(outcome.result); } +const UNSAVED: Record = { + cancelled: "cancellation", + deferred: "deferral", + expired: "expiry", +}; + +/** + * The user's reply is gone from the screen but not in the journal. Put the + * form back in the panel at once, tell the user, and tell the agent not to + * ask again. + */ +function saved( + ctx: ExtensionContext, + background: AskRuntime["background"], + unsaved: Set, + requestId: string, + status: string, + write: () => T +): T { + try { + return write(); + } catch (error) { + if (error instanceof AskJournalWriteError) { + const what = UNSAVED[status] ?? "answer"; + unsaved.add(requestId); + try { + background?.formEnded(ctx); + ctx.ui.notify(`${error.message} The form is back in your panel.`, "error"); + } catch { + // The screen is gone; the journal still holds the form. + } + error.message += ` The user's ${what} was not saved; the form will reappear in their panel. Do not re-ask.`; + } + throw error; + } +} + /** A receipt names the form and carries no answers, not even drafted ones. */ function receipt( state: AskState, diff --git a/pi-ask/src/background.ts b/pi-ask/src/background.ts index 20c0e91..7afe95c 100644 --- a/pi-ask/src/background.ts +++ b/pi-ask/src/background.ts @@ -26,7 +26,7 @@ import { } from "./delivery.ts"; import { askStrings } from "./i18n.ts"; import { ASK_ANSWER_MESSAGE_TYPE } from "./journal/entries.ts"; -import { AskJournalWriteError, readAskJournal } from "./journal/journal.ts"; +import { AskJournalWriteError, describeExpiryStopFailure, readAskJournal } from "./journal/journal.ts"; import { type AskJournalRecord, getRecord, @@ -121,9 +121,12 @@ export function registerAskBackground( "agent_before_settle", (event, ctx) => background.boundary(ctx, event) ); - pi.on("agent_settled", (event, ctx) => - background.settled(ctx, event.aborted) - ); + pi.on("agent_settled", (event, ctx) => { + // Every result of the run has landed, or never will. Landed results + // are excluded by the branch itself; this only ends the hold. + runtime.returning.clear(); + background.settled(ctx, event.aborted); + }); // A manual compaction keeps Pi busy without a run; pick up afterwards. pi.on("session_compact", (_event, ctx) => background.poke(ctx)); pi.registerMessageRenderer?.( @@ -139,12 +142,22 @@ export function registerAskBackground( return background; } +/** Pi's own error for an extension context used after reload or replacement. */ +function isRecoverableReadError(error: unknown): boolean { + return ( + error instanceof Error && + error.message.startsWith("This extension ctx is stale after") + ); +} + export function createAskBackground( pi: Pick, - { clock, flushers, journal, live }: AskRuntime + { clock, flushers, journal, live, returning, unsaved }: AskRuntime ): AskBackground { const now = clock?.now ?? Date.now; - const delivery = createAskDelivery(pi); + const delivery = createAskDelivery(pi, { + isLive: (requestId) => live.has(requestId) || returning.has(requestId), + }); const recorders = new Map void>(); // Content key of the draft each loaded form last started from or wrote, // to tell whether a re-read branch still agrees with what is on screen. @@ -218,9 +231,39 @@ export function createAskBackground( return recorder; } + /** + * Forms whose save failed are held in memory. Once the journal accepts a + * `defer` for one, it is an ordinary queued form and survives a reload. + */ + function persistUnsaved(current: ExtensionContext) { + if (unsaved.size === 0) { + return; + } + const journalState = readAskJournal(current); + for (const requestId of [...unsaved]) { + const record = getRecord(journalState, requestId); + if (!record) { + continue; + } + if (!isOpen(record) || record.deferred) { + unsaved.delete(requestId); + } else if (!live.has(requestId)) { + try { + journal.recordDefer(requestId); + unsaved.delete(requestId); + } catch (error) { + if (!(error instanceof AskJournalWriteError)) { + throw error; + } + } + } + } + } + function readQueue(current: ExtensionContext) { + persistUnsaved(current); const journalState = readAskJournal(current); - const pending = pendingForms(journalState, live, reopened); + const pending = pendingForms(journalState, live, reopened, unsaved); records = new Map(pending.map((record) => [record.requestId, record])); for (const requestId of recorders.keys()) { if (!records.has(requestId)) { @@ -567,8 +610,18 @@ export function createAskBackground( } reconcileBranch(next); refresh((queue, hidden) => ({ type: "sync", queue, hidden })); - delivery.attach(next); - poke(next); + try { + delivery.attach(next); + } catch (error) { + // A stale context or an unreadable branch is retried by the next + // pump or lifecycle event; nothing stale is kept. Anything else + // is a bug: surface it once the panel has refreshed. + if (!isRecoverableReadError(error)) { + throw error; + } + } finally { + poke(next); + } }, poke, formEnded(next) { @@ -584,6 +637,13 @@ export function createAskBackground( const timer = createExpiryTimer(options.timeoutSeconds, clock); timer.subscribe({ stop: (reason) => journal.recordExpiryStop(requestId, reason), + failed: (error) => { + if (error instanceof AskJournalWriteError) { + ctx?.ui.notify(describeExpiryStopFailure(error), "error"); + return true; + } + return false; + }, expire: () => expire(requestId), }); timers.set(requestId, timer); diff --git a/pi-ask/src/delivery.ts b/pi-ask/src/delivery.ts index 6d76faa..1ac9496 100644 --- a/pi-ask/src/delivery.ts +++ b/pi-ask/src/delivery.ts @@ -164,7 +164,8 @@ function answerMessage(outcome: AskOutcomeEntry) { } export function createAskDelivery( - pi: Pick + pi: Pick, + { isLive = () => false }: { isLive?: (requestId: string) => boolean } = {} ): AskDelivery { // Sent in this process, potentially still being written by a run. Cleared // only when idle or a new run starts; the branch then proves delivery. @@ -175,8 +176,30 @@ export function createAskDelivery( // Only tool outcomes already orphaned at attach can become messages. // Eligibility lasts until branch evidence proves delivery, not one plan. let adopted = new Set(); + // An attach whose journal read failed: adoption is retried before the + // next plan, and nothing from the previous branch stays eligible. + let adoptionPending = false; + + function adopt(ctx: DeliveryContext) { + adopted = new Set(); + adoptionPending = true; + adopted = new Set( + undeliveredOutcomes(readAskJournal(ctx), { unrecordedTool: true }) + // A call still returning its result is not an orphan. + .filter( + ({ outcome }) => + outcome.channel === "tool" && !isLive(outcome.requestId) + ) + .map(({ outcome }) => outcome.outcomeId) + ); + adoptionPending = false; + watching = true; + } function plan(ctx: DeliveryContext, situation: AskDeliverySituation) { + if (adoptionPending) { + adopt(ctx); + } if (!watching) { return; } @@ -219,14 +242,7 @@ export function createAskDelivery( post() { watching = true; }, - attach(ctx) { - adopted = new Set( - undeliveredOutcomes(readAskJournal(ctx), { unrecordedTool: true }) - .filter(({ outcome }) => outcome.channel === "tool") - .map(({ outcome }) => outcome.outcomeId) - ); - watching = true; - }, + attach: adopt, started() { // No prior run can still be writing a send. Do not send here: this // run's starting message is recorded before its first boundary. diff --git a/pi-ask/src/journal/journal.ts b/pi-ask/src/journal/journal.ts index cf4bd37..7031684 100644 --- a/pi-ask/src/journal/journal.ts +++ b/pi-ask/src/journal/journal.ts @@ -142,6 +142,12 @@ export class AskJournalWriteError extends Error { } } +/** User-facing text for a countdown stop that could not be journalled. */ +export function describeExpiryStopFailure(error: AskJournalWriteError): string { + const cause = error.cause instanceof Error ? error.cause.message : String(error.cause); + return `Could not save the ask_user countdown stop (${cause}). The countdown is stopped for now, but a reload may restore it; fix session storage.`; +} + /** Journal backed by the session file; successful writes are required. */ export function createSessionAskJournal( pi: Pick, diff --git a/pi-ask/src/journal/replay.ts b/pi-ask/src/journal/replay.ts index faf902b..cd7626f 100644 --- a/pi-ask/src/journal/replay.ts +++ b/pi-ask/src/journal/replay.ts @@ -202,13 +202,21 @@ export function queuedForms(state: AskJournalState): AskJournalRecord[] { export function pendingForms( state: AskJournalState, live: ReadonlySet = new Set(), - reopened: ReadonlySet = new Set() + reopened: ReadonlySet = new Set(), + unsaved: ReadonlySet = new Set() ): AskJournalRecord[] { const waiting = new Set( [...queuedForms(state), ...interruptedForms(state)] .filter((record) => record.deferred || !live.has(record.requestId)) .map((record) => record.requestId) ); + // A form whose save failed was promised back; later messages do not + // supersede it, but one still on screen is not waiting yet. + for (const record of state.records) { + if (isOpen(record) && unsaved.has(record.requestId) && !live.has(record.requestId)) { + waiting.add(record.requestId); + } + } // An expired form joins the queue only once the user asked for it. for (const record of reopenableForms(state)) { if (reopened.has(record.requestId)) { diff --git a/pi-ask/src/runtime.ts b/pi-ask/src/runtime.ts index 879bb8b..e83bcd6 100644 --- a/pi-ask/src/runtime.ts +++ b/pi-ask/src/runtime.ts @@ -24,6 +24,18 @@ export interface AskRuntime { * skips them: an open form is not an interrupted one. */ live: Set; + /** + * Blocking calls whose outcome is journalled but whose tool result may + * not be on the branch yet, identified by request id. The result is + * about to arrive, so the answer must not also be sent as a message. + */ + returning: Set; + /** + * Blocking forms whose outcome or deferral could not be journalled. The + * agent was told they will reappear, so the panel keeps them even after + * the conversation moves on, until a `defer` entry makes that durable. + */ + unsaved: Set; } export function createAskRuntime( @@ -35,5 +47,7 @@ export function createAskRuntime( flushers: new Set(), journal: createSessionAskJournal(pi, clock && { now: clock.now }), live: new Set(), + returning: new Set(), + unsaved: new Set(), }; } diff --git a/pi-ask/src/state/expiry.ts b/pi-ask/src/state/expiry.ts index f3243cc..4b7f4d3 100644 --- a/pi-ask/src/state/expiry.ts +++ b/pi-ask/src/state/expiry.ts @@ -53,6 +53,12 @@ export interface ExpiryListener { change?(view: ExpiryView): void; /** The limit lapsed. */ expire?(): void; + /** + * Another listener threw; return true when the error was reported. An + * unreported error is rethrown once every listener has run. The timer's + * own state is unaffected either way. + */ + failed?(error: unknown): boolean | undefined; /** The countdown was stopped before it lapsed. */ stop?(reason: ExpiryStopReason): void; } @@ -105,9 +111,34 @@ export function createExpiryTimer( remainingSeconds: remaining(), ...(stopReason ? { stopReason } : {}), }); - const emit = (call: (listener: ExpiryListener) => void) => { + /** Runs every listener; returns the first error nobody reported. */ + const emit = (call: (listener: ExpiryListener) => void): unknown[] => { + // One listener's failure never skips the others or undoes a state change. + const failures: unknown[] = []; for (const listener of [...listeners]) { - call(listener); + try { + call(listener); + } catch (error) { + failures.push(error); + } + } + return failures.filter((error) => { + let reported = false; + for (const listener of [...listeners]) { + try { + reported = listener.failed?.(error) === true || reported; + } catch { + // Reporting is best-effort. + } + } + return !reported; + }); + }; + /** Surfaces the first unreported listener error after all work is done. */ + const settle = (...unreported: unknown[][]) => { + const [first] = unreported.flat(); + if (first !== undefined) { + throw first; } }; const cancelTick = () => { @@ -129,12 +160,15 @@ export function createExpiryTimer( } if (clock.now() >= deadline) { phase = "expired"; - emit((listener) => listener.change?.(view())); - emit((listener) => listener.expire?.()); + settle( + emit((listener) => listener.change?.(view())), + emit((listener) => listener.expire?.()) + ); return; } - emit((listener) => listener.change?.(view())); + const unreported = emit((listener) => listener.change?.(view())); schedule(); + settle(unreported); } function maybeStart() { if (disposed || phase !== "pending" || !(armed && visible)) { @@ -143,7 +177,7 @@ export function createExpiryTimer( phase = "running"; deadline = clock.now() + seconds * 1000; schedule(); - emit((listener) => listener.change?.(view())); + settle(emit((listener) => listener.change?.(view()))); } function stop(reason: ExpiryStopReason) { if (phase !== "pending" && phase !== "running") { @@ -152,8 +186,10 @@ export function createExpiryTimer( cancelTick(); phase = "stopped"; stopReason = reason; - emit((listener) => listener.stop?.(reason)); - emit((listener) => listener.change?.(view())); + settle( + emit((listener) => listener.stop?.(reason)), + emit((listener) => listener.change?.(view())) + ); } return { diff --git a/pi-ask/src/ui/controller.ts b/pi-ask/src/ui/controller.ts index 83cbb16..637c6a1 100644 --- a/pi-ask/src/ui/controller.ts +++ b/pi-ask/src/ui/controller.ts @@ -275,13 +275,22 @@ export function createAskFlowController( controller.editor.invalidate(); }, handleInput(data: string) { + let unexpected: unknown; try { // One key means the user is here: the countdown ends for good. controller.expiry?.interact(); + } catch (error) { + // The stop holds in memory; the key must still be handled. + unexpected = error; + } + try { handleControllerInput(controller, data); } catch (error) { reportJournalError(controller, error); } + if (unexpected !== undefined) { + reportJournalError(controller, unexpected); + } }, detach() { cancelDraftTimer(controller); diff --git a/pi-ask/tests/attach-resilience.test.ts b/pi-ask/tests/attach-resilience.test.ts new file mode 100644 index 0000000..570551d --- /dev/null +++ b/pi-ask/tests/attach-resilience.test.ts @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { boot, ONE, SUBMIT_ONE, SUBMIT_TWO, start, unrecordedToolSession, withBackgroundForm } from "./support/background.ts"; +import { KEY, quietConfig, tick } from "./support/fake-pi.ts"; + +beforeEach(quietConfig); + +test("a journal read that throws on attach neither throws nor stops later delivery", async (t) => { + const { host } = await withBackgroundForm(); + const failing = t.mock.method(host.session, "getBranch", () => { + throw new Error("This extension ctx is stale after session replacement or reload."); + }); + assert.doesNotThrow(() => host.emit("session_tree")); + await tick(); + failing.mock.restore(); + + host.emit("session_tree"); + await tick(); + assert.match(host.panelText(), /Which database/); + if (!host.focusIs("panel")) { + host.type(KEY.focus); + } + host.type(...SUBMIT_TWO); + await tick(); + assert.equal(host.sent.length, 1); + host.emit("session_shutdown"); +}); + +test("an orphaned tool answer is adopted by a later pump after a failed attach, once", async (t) => { + const session = await unrecordedToolSession(); + const host = boot(session); + const failing = t.mock.method(host.session, "getBranch", () => { + throw new Error("This extension ctx is stale after session replacement or reload."); + }); + assert.doesNotThrow(() => host.emit("session_start", { reason: "resume" })); + await tick(); + failing.mock.restore(); + assert.equal(host.sent.length, 0, "nothing is delivered while the branch is unreadable"); + + host.emit("agent_settled", { aborted: false }); + await tick(); + assert.equal(host.sent.length, 1); + host.recordWake(); + host.emit("agent_settled", { aborted: false }); + await start(host, "reload"); + assert.equal(host.sent.length, 1, "delivered exactly once"); + host.emit("session_shutdown"); +}); + +test("an unrelated error that mentions staleness is surfaced, not swallowed", async (t) => { + const { host } = await withBackgroundForm(); + t.mock.method(host.session, "getBranch", () => { + throw new Error("stale cache entry"); + }); + assert.throws(() => host.emit("session_tree"), /stale cache entry/); + host.emit("session_shutdown"); +}); + +test("an unrecognised attach failure is surfaced, after the attach finished its other work", async (t) => { + const { host } = await withBackgroundForm(); + const failing = t.mock.method(host.session, "getBranch", () => { + throw new Error("boom"); + }); + assert.throws(() => host.emit("session_tree"), /boom/); + failing.mock.restore(); + host.emit("session_tree"); + await tick(); + assert.match(host.panelText(), /Which database/); + host.emit("session_shutdown"); +}); + +test("a blocking answer whose tool result has not landed is never adopted and sent as well", async (t) => { + const host = boot(undefined, { holdToolResults: true }); + const pending = host.ask(ONE("choice")); + await tick(); + host.forms[0]?.press(...SUBMIT_ONE); + const response = await pending; + assert.equal(response.details.status, "submitted"); + assert.equal(host.answers().length, 0, "the result is still on its way"); + assert.equal(host.session.getBranch().some((entry) => entry.type === "message" && entry.message.role === "toolResult"), false); + + // A failing read, then a recovering one, then a pump from another event. + const failing = t.mock.method(host.session, "getBranch", () => { + throw new Error("This extension ctx is stale after session replacement or reload."); + }); + assert.doesNotThrow(() => host.emit("session_tree")); + failing.mock.restore(); + host.emit("session_tree"); + host.emit("session_compact"); + await tick(); + assert.deepEqual(host.sent, [], "the live answer is not sent as a message"); + + // Pi awaits message_end handlers before it persists the result: a pump or + // attach in that gap must still not send the answer. + host.endHeldToolResults(); + host.emit("session_tree"); + host.emit("session_compact"); + await tick(); + assert.deepEqual(host.sent, [], "nothing is sent between message_end and the append"); + + host.landToolResults(); + host.emit("session_tree"); + host.emit("session_compact"); + host.settle(); + await tick(); + assert.deepEqual(host.sent, [], "nothing extra once the result landed"); + host.emit("session_shutdown"); +}); diff --git a/pi-ask/tests/background-hidden-panel.test.ts b/pi-ask/tests/background-hidden-panel.test.ts new file mode 100644 index 0000000..a08666c --- /dev/null +++ b/pi-ask/tests/background-hidden-panel.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { type ExtensionAPI, SessionManager } from "@earendil-works/pi-coding-agent"; +import type { AskJournalEntry } from "../src/journal/entries.ts"; +import { KEY, quietConfig, type SentMessage, tick } from "./support/fake-pi.ts"; +import { boot, kinds, ONE, start, SUBMIT_ONE, withBackgroundForm } from "./support/background.ts"; + +beforeEach(quietConfig); + +const NOTES = { title: "Notes", questions: [{ id: "dir", label: "DIR", prompt: "Which directory?", type: "text" }] }; + +test("a turn boundary with a cancellation and an answer continues the turn", async () => { + const { host } = await withBackgroundForm(ONE("a")); + await host.askInBackground(ONE("b")); + host.setIdle(false); + host.type(KEY.ctrlC); + host.type(...SUBMIT_ONE); + await tick(); + + const boundary = host.turnEnd(); + assert.equal(boundary.entries.length, 2); + assert.equal(boundary.continue, true, "the answer must be seen by the agent"); + host.emit("session_shutdown"); +}); + +test("a tree move while the panel is hidden shows the branch's draft and answers once", async () => { + const session = SessionManager.inMemory(); + session.appendMessage({ role: "user", content: "start", timestamp: Date.now() }); + const host = boot(session); + await start(host, "startup"); + await host.askInBackground(); + const formEntry = session.getBranch().at(-1)?.id; + assert.ok(formEntry); + + // Branch A: the database is answered. + host.type(KEY.enter, KEY.escape); + const branchA = session.getBranch().at(-1)?.id; + assert.ok(branchA); + // Branch B: the same form, a different draft, panel hidden. + session.branch(formEntry); + host.emit("session_tree"); + await tick(); + host.type(KEY.focus, KEY.down, KEY.enter, KEY.escape); + assert.equal(host.panelText(), ""); + + const drafts = () => kinds(host).filter((kind) => kind === "draft").length; + session.branch(branchA); + host.emit("session_tree"); + await tick(); + const before = drafts(); + assert.equal(host.panelText(), "", "the panel stays hidden"); + + await host.command("ask-panel"); + assert.match(host.panelText(), /Which cache\?/, "branch A's draft is shown"); + assert.equal(drafts(), before, "no stale draft was written"); + + host.type(KEY.enter, KEY.enter); + await tick(); + assert.equal(host.sent.length, 1); + assert.deepEqual(host.sent[0].message.details.result.answers.db.values, ["postgres"]); + assert.equal(kinds(host).filter((kind) => kind === "outcome").length, 1); + host.emit("session_shutdown"); +}); + +test("a hidden panel whose draft cannot be saved keeps the form and reports it", async (t) => { + const { host } = await withBackgroundForm(NOTES); + const pi: ExtensionAPI = host.pi; + const append = pi.appendEntry; + const failure = t.mock.method(pi, "appendEntry", (type: string, data: unknown) => { + if ((data as AskJournalEntry).kind === "draft") { + throw new Error("disk full"); + } + append(type, data); + }); + host.type(..."keep this"); + host.type(KEY.escape, KEY.escape); + await tick(); + assert.match(host.notices.join("\n"), /Could not save ask_user draft/); + assert.deepEqual(host.sent, []); + assert.equal(kinds(host).includes("outcome"), false); + + failure.mock.restore(); + await host.command("ask-panel"); + assert.match(host.panelText(), /keep this/, "the typed answer was kept"); + host.type(KEY.enter, KEY.enter, KEY.enter); + await tick(); + const sent = host.sent as SentMessage[]; + assert.equal(sent.length, 1); + assert.equal(sent[0]?.message.details.result.answers.dir.customText, "keep this"); + host.emit("session_shutdown"); +}); diff --git a/pi-ask/tests/expiry-flow.test.ts b/pi-ask/tests/expiry-flow.test.ts index 30a0899..09c24a5 100644 --- a/pi-ask/tests/expiry-flow.test.ts +++ b/pi-ask/tests/expiry-flow.test.ts @@ -525,3 +525,26 @@ test("a blocking form that expired can be corrected late too", async () => { assert.match(host.sent[0]?.message.content ?? "", /^CORRECTION: /); assert.equal(outcomes(host).at(-1)?.supersedes, outcomes(host)[0].outcomeId); }); + +test("a countdown stop that cannot be journalled still stops, still handles the key and reports", async (t) => { + const { host } = await withTimedPanel(); + assert.match(host.panelText(), /No reply in 1:00/); + const pi: ExtensionAPI = host.pi; + const append = pi.appendEntry; + t.mock.method(pi, "appendEntry", (type: string, data: any) => { + if (data.kind === "expiry") { + throw new Error("disk full"); + } + append(type, data); + }); + + host.type(KEY.enter); + assert.match(host.notices.at(-1) ?? "", /Could not save the ask_user countdown stop.*disk full.*stopped for now/); + assert.match(host.panelText(), /Which cache/, "the first key was handled"); + assert.doesNotMatch(host.panelText(), /No reply in/, "the countdown stopped"); + + host.time.advance(120 * SECOND); + assert.equal(outcomes(host).length, 0, "a stopped clock does not restart"); + assert.equal(host.sent.length, 0); + host.emit("session_shutdown"); +}); diff --git a/pi-ask/tests/expiry.test.ts b/pi-ask/tests/expiry.test.ts index 203d38d..ce11f93 100644 --- a/pi-ask/tests/expiry.test.ts +++ b/pi-ask/tests/expiry.test.ts @@ -225,3 +225,40 @@ test("an expiry with no declared fallback is still expired, with nothing applied assert.deepEqual(result.expired, []); assert.deepEqual(result.answers, {}); }); + +test("a throwing listener cannot skip the others, and an unreported error is rethrown last", () => { + const time = fakeClock(); + const timer = createExpiryTimer(30, time.clock); + timer.subscribe({ + stop: () => { + throw new Error("listener bug"); + }, + }); + const events = record(timer); + timer.arm(); + timer.show(); + assert.throws(() => timer.interact(), /listener bug/); + assert.deepEqual(events.slice(-2), ["stop:interaction", "change:stopped:0"]); + assert.equal(timer.view().phase, "stopped"); + time.advance(60_000); + assert.equal(timer.view().phase, "stopped", "the stop holds"); +}); + +test("an error a listener reports is not rethrown", () => { + const time = fakeClock(); + const timer = createExpiryTimer(30, time.clock); + const reported: unknown[] = []; + timer.subscribe({ + stop: () => { + throw new Error("handled"); + }, + failed: (error) => { + reported.push(error); + return true; + }, + }); + timer.arm(); + timer.show(); + assert.doesNotThrow(() => timer.interact()); + assert.equal(reported.length, 1); +}); diff --git a/pi-ask/tests/journal-failure.test.ts b/pi-ask/tests/journal-failure.test.ts index 00c8d80..abd52b0 100644 --- a/pi-ask/tests/journal-failure.test.ts +++ b/pi-ask/tests/journal-failure.test.ts @@ -4,7 +4,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import type { AskJournalEntry } from "../src/journal/entries.ts"; import { AskJournalWriteError, createAskJournal } from "../src/journal/journal.ts"; import { createInitialState } from "../src/state/create.ts"; -import { boot, kinds, ONE, SUBMIT_ONE, SUBMIT_TWO, withBackgroundForm } from "./support/background.ts"; +import { boot, kinds, ONE, start, SUBMIT_ONE, SUBMIT_TWO, withBackgroundForm } from "./support/background.ts"; import { KEY, quietConfig, tick } from "./support/fake-pi.ts"; beforeEach(quietConfig); @@ -110,3 +110,109 @@ test("draft deduplication advances only after a successful write", () => { record(state); assert.equal(writes, 2, "the failed write is retried, then deduplicated"); }); + +for (const [name, kind, keys, wording] of [ + ["submit", "outcome", SUBMIT_ONE, /answer was not saved/], + ["defer", "defer", [KEY.later], /deferral was not saved/], + ["cancel", "outcome", [KEY.ctrlC], /cancellation was not saved/], +] as const) { + test(`a failed blocking ${name} save puts the form back in the panel, tells the user and the agent`, async (t) => { + const host = boot(); + const pi: ExtensionAPI = host.pi; + const append = pi.appendEntry; + t.mock.method(pi, "appendEntry", (type: string, data: unknown) => { + if ((data as AskJournalEntry).kind === kind) { + throw new Error("disk full"); + } + append(type, data); + }); + const rejected = assert.rejects( + host.ask(ONE("choice")), + new RegExp(`${wording.source}.*reappear in their panel.*Do not re-ask`) + ); + await tick(); + host.forms[0]?.press(...keys); + await rejected; + assert.match(host.panelText(), /CHOICE/, "the form is back at once"); + assert.match(host.notices.at(-1) ?? "", /Could not save ask_user.*disk full.*back in your panel/); + host.emit("session_shutdown"); + }); +} + +for (const [name, keys] of [ + ["submit", SUBMIT_ONE], + ["defer", [KEY.later]], +] as const) { + test(`a form whose blocking ${name} save failed stays in the panel after the chat moves on, then survives a reload`, async (t) => { + const host = boot(); + await start(host, "startup"); + const pi: ExtensionAPI = host.pi; + const append = pi.appendEntry; + let broken = false; + t.mock.method(pi, "appendEntry", (type: string, data: unknown) => { + if (broken) { + throw new Error("disk full"); + } + append(type, data); + }); + const rejected = assert.rejects(host.ask(ONE("choice")), AskJournalWriteError); + await tick(); + broken = true; + host.forms[0]?.press(...keys); + await rejected; + assert.match(host.panelText(), /CHOICE/); + + // The agent carries on, as promised, and a message lands on the branch. + host.session.appendMessage({ + role: "assistant", + content: [{ type: "text", text: "Continuing." }], + timestamp: Date.now(), + } as never); + await host.command("ask-panel"); + host.emit("session_tree"); + await tick(); + assert.match(host.panelText(), /CHOICE/, "still pending while storage is down"); + + // Storage works again: the next refresh makes it durable. + broken = false; + await host.command("ask-panel"); + assert.equal(kinds(host).filter((kind) => kind === "defer").length, 1); + host.emit("session_shutdown"); + + const later = boot(host.session); + await start(later); + assert.match(later.panelText(), /CHOICE/, "back after a reload"); + later.type(KEY.focus, KEY.enter, KEY.enter); + await tick(); + assert.equal(later.sent.length, 1); + assert.equal(kinds(later).filter((kind) => kind === "outcome").length, 1); + later.emit("session_shutdown"); + }); +} + +test("a failed-save form answered from the panel while storage is still down is delivered once after recovery", async (t) => { + const host = boot(); + await start(host, "startup"); + const pi: ExtensionAPI = host.pi; + const append = pi.appendEntry; + let broken = false; + t.mock.method(pi, "appendEntry", (type: string, data: unknown) => { + if (broken) { + throw new Error("disk full"); + } + append(type, data); + }); + const rejected = assert.rejects(host.ask(ONE("choice")), AskJournalWriteError); + await tick(); + broken = true; + host.forms[0]?.press(...SUBMIT_ONE); + await rejected; + host.session.appendMessage({ role: "user", content: "next", timestamp: Date.now() }); + broken = false; + await host.command("ask-panel"); + host.type(KEY.enter, KEY.enter); + await tick(); + assert.equal(host.sent.length, 1); + assert.equal(kinds(host).filter((kind) => kind === "outcome").length, 1); + host.emit("session_shutdown"); +}); diff --git a/pi-ask/tests/support/background.ts b/pi-ask/tests/support/background.ts index d61eb88..30ee987 100644 --- a/pi-ask/tests/support/background.ts +++ b/pi-ask/tests/support/background.ts @@ -35,6 +35,7 @@ export function boot( session?: SessionManager, options: { background?: boolean; + holdToolResults?: boolean; mode?: string; persistToolResults?: boolean; } = {} diff --git a/pi-ask/tests/support/fake-pi.ts b/pi-ask/tests/support/fake-pi.ts index 9cb848c..75ad1ab 100644 --- a/pi-ask/tests/support/fake-pi.ts +++ b/pi-ask/tests/support/fake-pi.ts @@ -74,6 +74,8 @@ export function fakePi( mode?: string; /** Model a process that dies before Pi records a tool result. */ persistToolResults?: boolean; + /** The tool result lands only when the test calls `landToolResults`. */ + holdToolResults?: boolean; persistSentMessages?: boolean; } = {} ) { @@ -94,6 +96,7 @@ export function fakePi( const heldCustom: SentMessage["message"][] = []; const persistToolResults = options.persistToolResults ?? true; let idle = true; + const heldResults: Array<{ ended: boolean; end: () => void; append: () => void }> = []; // The next triggered send is accepted but its run fails to start before // recording the message, as a failed pre-run compaction would. let failWake = false; @@ -151,8 +154,8 @@ export function fakePi( async execute(...args: any[]) { const result = await run(...args); if (persistToolResults) { - session.appendMessage({ - role: "toolResult", + const message = { + role: "toolResult" as const, toolCallId: String(args[0]), toolName: tool.name, content: result.content ?? [], @@ -161,7 +164,26 @@ export function fakePi( : { details: result.details }), isError: false, timestamp: Date.now(), - }); + }; + // As Pi does: handlers are awaited before the result is persisted. + const held = { + ended: false, + end() { + if (!held.ended) { + held.ended = true; + emit("message_end", { message }); + } + }, + append() { + held.end(); + session.appendMessage(message); + }, + }; + if (options.holdToolResults) { + heldResults.push(held); + } else { + held.append(); + } } return result; }, @@ -309,6 +331,18 @@ export function fakePi( failWake = true; }, isIdle: () => idle, + /** Pi appends the tool results it was holding back. */ + landToolResults() { + for (const held of heldResults.splice(0)) { + held.append(); + } + }, + /** Pi announces the end of each held result before persisting it. */ + endHeldToolResults() { + for (const held of heldResults) { + held.end(); + } + }, /** Dispatch a lifecycle event; returns what the handlers returned. */ emit, /** The run started by an idle wake writes its starting message. */