Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/agent/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,4 @@ export type {
*/
export { AGENT_PROMPT, parsePromptRecord } from "./src/journal.ts";
export type { PromptRecord } from "./src/journal.ts";
export { readPromptDiagnostic } from "./src/errors.ts";
13 changes: 11 additions & 2 deletions packages/cli/src/repl/sidekick/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -853,15 +853,24 @@ function established(
* is chat, and what belongs in chat is a sentence.
*/
function incompleteFailure(record: PromptRecord): string {
if (record.error?.message !== undefined) {
return record.error.message;
if (record.error !== undefined) {
return sidekickFailureText(record.error);
}
if (record.stopReason !== undefined) {
return `the agent stopped early (${record.stopReason}).`;
}
return `the agent's turn ${record.status}.`;
}

export function sidekickFailureText(failure: NonNullable<PromptRecord["error"]>): string {
const detail = failure.diagnostic?.acp?.details;
return failure.name === "SessionResumeRequiredError" &&
detail !== undefined &&
detail.trim() !== ""
? `${detail}\n${failure.message}`
: failure.message;
}

/**
* What a saved turn said, as the literal Output its source projects.
*
Expand Down
23 changes: 18 additions & 5 deletions packages/cli/src/repl/sidekick/owner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,15 @@ import {
AGENT_PROMPT,
AgentReplyWithheldError,
parsePromptRecord,
readPromptDiagnostic,
useAgentPromptPublisher,
} from "@executablemd/agent/host";
import type { ExecutionInstallation, GeneratedXmdRootResult } from "@executablemd/core/host";
import type { AgentPromptHandle, AgentPromptPublisher } from "@executablemd/agent/host";
import type {
AgentPromptHandle,
AgentPromptPublisher,
PromptRecord,
} from "@executablemd/agent/host";
import { serializeError } from "@executablemd/durable-streams";
import { useAgentConversation } from "@executablemd/agent/host";
import type { AgentConversation } from "@executablemd/agent/host";
Expand All @@ -136,6 +141,7 @@ import {
projectSidekick,
recoveryRequired,
requestsFromHistory,
sidekickFailureText,
} from "./model.ts";
import type { ProjectedHistory, SidekickReading } from "./model.ts";
import { controlJournal } from "./admission.ts";
Expand Down Expand Up @@ -2855,6 +2861,13 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation<SidekickO
});
}
const attempted = withheld ?? (yield* turnForRequest(paired, began, conversation));
const failure = sidekickFailureText(
attempted?.error ?? {
message: replied.error.message,
name: replied.error.name,
diagnostic: readPromptDiagnostic(replied.error),
},
);
// Kept as an attempt that did not finish, told which turn this
// request's own records say it became. With none, it claims no turn, no
// acceptance and no recorded failure; with one, the saved account of
Expand All @@ -2867,9 +2880,7 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation<SidekickO
!live.begun &&
(attempted === undefined || attempted.resumeRefused)
) {
return Err(
new SidekickContinuationUnavailable(replied.error.message, { cause: replied.error }),
);
return Err(new SidekickContinuationUnavailable(failure, { cause: replied.error }));
}
return Ok({
held: {
Expand All @@ -2880,7 +2891,7 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation<SidekickO
response,
output: attempted?.text ?? "",
hasOutput: false,
failure: replied.error.message,
failure,
},
answered: false,
next: undefined,
Expand Down Expand Up @@ -3246,6 +3257,7 @@ function* turnForRequest(
readonly text: string;
readonly withheld: boolean;
readonly resumeRefused: boolean;
readonly error: PromptRecord["error"];
}
| undefined
> {
Expand Down Expand Up @@ -3287,6 +3299,7 @@ function* turnForRequest(
text: saved.text,
withheld: saved.withheld === true,
resumeRefused: held.resumeRefused === true,
error: saved.error,
};
}
}
Expand Down
147 changes: 145 additions & 2 deletions packages/cli/tests/repl-sidekick-acp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,13 @@ import {
} from "./support/screen-journeys.ts";
import { useReplPage } from "./support/repl-page.ts";
import { settledReading } from "./support/mounted-history.ts";
import { awaitedFact } from "./support/mounted-repl.ts";
import { awaited, awaitedFact } from "./support/mounted-repl.ts";
import { runReplProgram } from "../src/repl/program.ts";
import { ReplHost } from "../src/repl/host.ts";
import { PAIRED_DIRECTORY, parseEntryRecords } from "../src/repl/sidekick/history.ts";
import { AGENT_PROMPT } from "@executablemd/agent/host";
import { AGENT_PROMPT, parsePromptRecord } from "@executablemd/agent/host";
import { encodeLocation } from "../src/repl/route.ts";
import { initialState } from "../src/repl/application.ts";
import {
Descriptor,
Request,
Expand Down Expand Up @@ -3650,6 +3652,147 @@ describe("ACP82: the file this publication keeps open", () => {
});
});

describe("resume presentation in mounted Sidekick chat", () => {
const actionable = "Release <writer> first.";
const credential = ["ghp", "_", "abcdefghijklmnopqrstuvwxyz0123456789"].join("");
const remedy = "could not be resumed";

for (const [mode, detail] of [
["actionable", actionable],
["absent", undefined],
["blank", " "],
["screened", credential],
] as const) {
it(`shows the same ${mode} refusal live and after passive reopen`, function* () {
yield* usePosixSidekickTransport(process.platform);
const home = yield* publishingHome("xmd-resume-presentation-");
const path = join(home, "attachment.json");
const host = yield* useMountedHost();
host.fake.script({ reply: "<Output>Established chat.</Output>" });
const original = yield* scoped(function* () {
const page = yield* useReplPage({ host, sidekickAcp: path });
const descriptor = Descriptor.parse(JSON.parse(yield* readTextFile(path)));
const baseline = yield* settledReading(page.repl);
page.repl.terminal.end();
yield* awaited("the first REPL joining", () => page.repl.outcome() !== undefined);
return { descriptor, baseline };
});
const opening = host.fake.turns[0]?.handle;
if (opening === undefined) {
throw new Error("The original provider session was not established");
}
const route = initialState(original.descriptor.execution).route;
const location = encodeLocation({ ...route, view: "sidekick", right: "sidekick" });
host.fake.refuseSessionResume(opening.sessionKey, detail);
const beforeEnsures = host.fake.ensured.length;
const after = yield* scoped(function* () {
const page = yield* useReplPage({ host, location, sidekickAcp: path });
yield* page.resize({ columns: 145, rows: 36 });
const descriptor = Descriptor.parse(JSON.parse(yield* readTextFile(path)));
expect(descriptor.conversation).toBe(original.descriptor.conversation);
expect(host.fake.ensured).toHaveLength(beforeEnsures);
expect((yield* settledReading(page.repl)).chat).toEqual(original.baseline.chat);
const attached = attachResult.parse(
yield* requestAttachment(path, { method: "attach", cwd: descriptor.cwd }),
);
const result = exchangeSchema.parse(
yield* requestAttachment(path, {
method: "prompt",
attachment: attached.attachment,
text: "Cold reconnect attempt.",
}),
);
const visible = yield* page.until(
"one failed chat attempt and its recovery message",
(one) =>
one.occurrences("(unfinished):") === 1 &&
one.shows(remedy) &&
(mode !== "actionable" || one.shows(`(unfinished): ${actionable}`)),
);
expect(visible.shows(actionable)).toBe(mode === "actionable");
expect(visible.shows(credential)).toBe(false);
expect(visible.shows("Internal error")).toBe(false);
expect(visible.shows("unrelated synthetic RPC payload")).toBe(false);
expect(host.fake.prompts).toHaveLength(1);
const retained = yield* settledReading(page.repl);
const delta = retained.chat.slice(original.baseline.chat.length);
expect(
delta.some(
(one) => one.kind === "response" || one.kind === "control" || one.kind === "feedback",
),
).toBe(false);
const attempts = delta.flatMap((one) =>
one.kind === "event"
? parseEntryRecords(one.event).flatMap((event) =>
event.type === "yield" &&
event.description.type === AGENT_PROMPT &&
event.result.status === "ok"
? [parsePromptRecord(event.result.value)]
: [],
)
: [],
);
expect(attempts).toHaveLength(1);
const saved = attempts[0]?.error;
if (saved === undefined) {
throw new Error("Expected a canonical resume failure");
}
expect(saved).toEqual({
name: "SessionResumeRequiredError",
message: expect.stringContaining(remedy),
diagnostic: {
provider: "acp",
operation: "session/prompt",
stage: "held-session-ensure",
code: "RUNTIME",
detailCode: "SESSION_RESUME_REQUIRED",
origin: "runtime",
acp: {
code: -32041,
message: "Internal error",
...(mode === "actionable" || mode === "blank" ? { details: detail } : {}),
},
},
});
expect(JSON.stringify(delta)).not.toContain(credential);
expect(JSON.stringify(delta)).not.toContain("unrelated synthetic RPC payload");
expect(result.ending).toMatchObject({
joined: true,
outcome: "failed",
error: mode === "actionable" ? actionable + "\n" + saved.message : saved.message,
});
expect(result.output).toBe("");
page.repl.terminal.end();
yield* awaited("the failed REPL joining", () => page.repl.outcome() !== undefined);
return retained;
});
const settledEnsures = host.fake.ensured.length;
const page = yield* useReplPage({ host, location });
yield* page.resize({ columns: 145, rows: 36 });
const reopened = yield* page.until(
"one reopened failure and its recovery message",
(one) =>
one.occurrences("(unfinished):") === 1 &&
one.shows(remedy) &&
(mode !== "actionable" || one.shows(`(unfinished): ${actionable}`)),
);
expect(reopened.shows(actionable)).toBe(mode === "actionable");
expect(reopened.shows(credential)).toBe(false);
expect(reopened.shows("unrelated synthetic RPC payload")).toBe(false);
expect(host.fake.ensured).toHaveLength(settledEnsures);
expect(host.fake.prompts).toHaveLength(1);
expect((yield* settledReading(page.repl)).chat).toEqual(after.chat);
host.fake.script({ reply: "<Output>Later explicit Send succeeded.</Output>" });
yield* sendMessage(page, "Fresh request after release.");
yield* page.until("the new reply", (one) => one.shows("Later explicit Send succeeded."));
expect(host.fake.prompts).toHaveLength(2);
expect(host.fake.prompts[1]).toContain("Fresh request after release.");
expect(host.fake.prompts[1]).not.toContain("Cold reconnect attempt.");
expect(host.fake.turns.at(-1)?.handle.sessionKey).toBe(opening.sessionKey);
});
}
});

describe("Follow: joined mixed-origin queue handoff", () => {
it("Follow: mounted UI and delivered ACP stay FIFO behind entry and generated-control cleanup", function* () {
yield* usePosixSidekickTransport(process.platform);
Expand Down
7 changes: 5 additions & 2 deletions packages/cli/tests/repl-sidekick-recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5098,7 +5098,7 @@ describe("resume retention and mounted retained recovery corrections", () => {
"the saved fallback and new chat action",
(one) => one.shows("could not be resumed") && one.shows("[Start new chat]"),
);
expect(page.screen().shows("Release the active writer.")).toBe(false);
expect(page.screen().shows("Release the active writer.")).toBe(true);
expect(page.screen().shows("[Retry]")).toBe(false);
page.repl.terminal.end();
yield* awaited("the REPL joining", () => page.repl.outcome() !== undefined);
Expand All @@ -5125,7 +5125,10 @@ describe("resume retention and mounted retained recovery corrections", () => {
host: { ...held.host, profile: held.profile },
location: held.location,
});
yield* reopened.until("the retained local failure", (one) => one.shows("could not be resumed"));
yield* reopened.until(
"the retained local failure",
(one) => one.shows("Release the active writer.") && one.shows("could not be resumed"),
);
expect(reopened.screen().shows("[Retry]")).toBe(false);
expect(yield* readSidekickRecords(held.chat.location.sidekick)).toEqual(after);
});
Expand Down
6 changes: 6 additions & 0 deletions specs/repl-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -1068,6 +1068,12 @@ no established request and appears beside the preceding attempt on its own.
It creates no feedback intent or acknowledgement. A second ordinary outcome
for the same request still refuses the history.

For a classified resume refusal, chat displays the screened ACP details as
literal text followed by the saved recovery message. A missing or blank detail
leaves the recovery message alone. The live exchange, including an original
continuation refusal, uses the same text as the saved attempt. The entry
Journal returns the canonical saved fields with their original values.

Activating a Sidekick turn opens the chat that contains it and brings that turn
into view. It sets `view=sidekick`, `right=sidekick` and that chat's own
identifier, and preserves the conversation filter, the saved surface, the
Expand Down
Loading