Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
test(agent-runtime): cover the resumable-delegation registry and rebuild paths
Tioit-Wang5527460f48ee
diff --git a/apps/desktop/test/assistant-turns.test.mjs b/apps/desktop/test/assistant-turns.test.mjsindex de4013e5a..7d35b30e8 100644--- a/apps/desktop/test/assistant-turns.test.mjs+++ b/apps/desktop/test/assistant-turns.test.mjs@@ -259,7 +259,7 @@ test("a delegate turn with both reasoning and text keeps both rows", () => {);});-test("a resumed delegation continues in the latest Task card (ADR 0276)", () => {+test("a resumed delegation continues in the latest Task card (ADR 0278)", () => {const { entries, visible } = buildTranscriptEntries([message("user", "user", "Audit the store"),message("task-1", "tool", "report", {diff --git a/packages/agent-runtime/src/delegation-chain.test.ts b/packages/agent-runtime/src/delegation-chain.test.tsnew file mode 100644index 000000000..fcbf2041c--- /dev/null+++ b/packages/agent-runtime/src/delegation-chain.test.ts@@ -0,0 +1,450 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { MAX_RESUMABLE_CHAINS_PER_AGENT } from "@pi-desktop/shared";+import { DelegationChainRegistry } from "./delegation-chain.js";+import type { DelegationChain } from "./delegation-history.js";++const NONE = new Set<string>();++type StartOptions = {+ delegateSessionId: string;+ delegationId: string;+ agentName?: string;+ toolCallId?: string;+ originalTask?: string;+ objective?: string;+ modelId?: string;+ modelKey?: string;+};++function start(+ registry: DelegationChainRegistry,+ options: StartOptions,+): DelegationChain {+ return registry.start({+ delegateSessionId: options.delegateSessionId,+ delegationId: options.delegationId,+ toolCallId: options.toolCallId ?? `call-${options.delegationId}`,+ agentName: options.agentName ?? "explorer",+ originalTask: options.originalTask ?? "explore the parser",+ objective: options.objective ?? "explore the parser",+ ...(options.modelId ? { latestModelId: options.modelId } : {}),+ ...(options.modelKey ? { latestModelKey: options.modelKey } : {}),+ });+}++function chain(+ overrides: Partial<DelegationChain> = {},+): DelegationChain {+ return {+ delegateSessionId: "res-1",+ toolCallIds: ["call-1", "call-2", "call-3"],+ delegationIds: ["del-1", "del-2", "del-3"],+ agentName: "explorer",+ readFiles: [],+ readLineCount: 0,+ latestDelegationId: "del-3",+ latestObjective: "third run",+ lastActivityAt: 1,+ ...overrides,+ };+}++afterEach(() => {+ vi.useRealTimers();+});++describe("hydrate / lookup", () => {+ it("resolves a chain from any delegationId on it, middle ids included", () => {+ const registry = new DelegationChainRegistry();+ registry.hydrate([chain()]);++ for (const delegationId of ["del-1", "del-2", "del-3"]) {+ expect(registry.lookup(delegationId)).toMatchObject({+ delegateSessionId: "res-1",+ agentName: "explorer",+ });+ }+ expect(registry.lookup("del-unknown")).toBeUndefined();+ });+});++describe("resolveResume", () => {+ it("reports an unknown id", () => {+ const registry = new DelegationChainRegistry();+ const result = registry.resolveResume({+ resume: "missing",+ agentName: "explorer",+ runningDelegationIds: NONE,+ });+ expect(result).toEqual({ ok: false, error: { kind: "unknown" } });+ });++ it("reports a chain whose latest run is still running", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ const result = registry.resolveResume({+ resume: "del-1",+ agentName: "explorer",+ runningDelegationIds: new Set(["del-1"]),+ });+ expect(result).toEqual({+ ok: false,+ error: { kind: "running", delegationId: "del-1" },+ });+ });++ it("reports a settled chain whose status is not resumable", () => {+ for (const status of ["stopped", "aborted", "interrupted"]) {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.settle("res-1", status);+ expect(+ registry.resolveResume({+ resume: "del-1",+ agentName: "explorer",+ runningDelegationIds: NONE,+ }),+ ).toEqual({ ok: false, error: { kind: "not-resumable", status } });+ }+ });++ it("accepts every settled status a delegate can end on", () => {+ for (const status of ["completed", "failed", "timed_out"]) {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.settle("res-1", status);+ const result = registry.resolveResume({+ resume: "del-1",+ agentName: "explorer",+ runningDelegationIds: NONE,+ });+ expect(result.ok).toBe(true);+ }+ });++ it("reports an agent mismatch before any other gate", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.settle("res-1", "completed");+ const result = registry.resolveResume({+ resume: "del-1",+ agentName: "reviewer",+ runningDelegationIds: new Set(["del-1"]),+ });+ expect(result).toEqual({+ ok: false,+ error: { kind: "agent-mismatch", expected: "explorer", actual: "reviewer" },+ });+ });++ it("reports a chain that read past the resume budget", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.noteReads("res-1", ["huge.ts"], 50_001);+ registry.settle("res-1", "completed");+ expect(+ registry.resolveResume({+ resume: "del-1",+ agentName: "explorer",+ runningDelegationIds: NONE,+ }),+ ).toEqual({ ok: false, error: { kind: "over-budget" } });+ });++ it("accepts a chain exactly at the budget", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.noteReads("res-1", ["big.ts"], 50_000);+ registry.settle("res-1", "completed");+ expect(+ registry.resolveResume({+ resume: "del-1",+ agentName: "explorer",+ runningDelegationIds: NONE,+ }).ok,+ ).toBe(true);+ });+});++describe("resumableList / promptBlock", () => {+ it("excludes running, non-resumable and over-budget chains, newest first", () => {+ vi.useFakeTimers({ now: 1_700_000_000_000 });+ const registry = new DelegationChainRegistry();+ // One agent per excluded case: eviction is per agent, so a third settled+ // chain for `explorer` would drop the two the ordering check needs.+ start(registry, { delegateSessionId: "res-a", delegationId: "del-a" });+ registry.settle("res-a", "completed");+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId: "res-b", delegationId: "del-b" });+ registry.settle("res-b", "completed");+ // Rebuilt from the transcript at launch: no settled status recorded yet.+ registry.hydrate([+ ...registry.resumableList({ runningDelegationIds: NONE }),+ chain({+ delegateSessionId: "res-c",+ toolCallIds: ["task-c"],+ delegationIds: ["del-c"],+ agentName: "fixer",+ latestDelegationId: "del-c",+ latestObjective: "still working",+ lastActivityAt: 1_700_000_009_000,+ }),+ ]);+ start(registry, {+ delegateSessionId: "res-d",+ delegationId: "del-d",+ agentName: "reviewer",+ });+ registry.settle("res-d", "stopped");+ start(registry, {+ delegateSessionId: "res-e",+ delegationId: "del-e",+ agentName: "test-runner",+ });+ registry.noteReads("res-e", ["huge.ts"], 50_001);+ registry.settle("res-e", "completed");++ expect(+ registry+ .resumableList({ runningDelegationIds: new Set(["del-c"]) })+ .map((entry) => entry.latestDelegationId),+ ).toEqual(["del-b", "del-a"]);+ // A chain whose status is unknown is only held back while it is running.+ expect(+ registry+ .resumableList({ runningDelegationIds: NONE })+ .map((entry) => entry.latestDelegationId),+ ).toEqual(["del-c", "del-b", "del-a"]);+ });++ it("prompts with the agent, the id, the objective and the files it read", () => {+ const registry = new DelegationChainRegistry();+ start(registry, {+ delegateSessionId: "res-1",+ delegationId: "del-1",+ objective: "explore the parser",+ });+ registry.noteReads(+ "res-1",+ ["a1.ts", "a2.ts", "a3.ts", "a4.ts", "a5.ts", "a6.ts", "a7.ts", "a8.ts", "a9.ts"],+ 9,+ );+ registry.settle("res-1", "completed");+ start(registry, {+ delegateSessionId: "res-2",+ delegationId: "del-2",+ agentName: "reviewer",+ objective: "",+ });+ registry.settle("res-2", "failed");++ const block = registry.promptBlock({ runningDelegationIds: NONE });+ expect(block).toContain("explorer / del-1: explore the parser");+ expect(block).toContain("Files read: a1.ts, a2.ts");+ expect(block).toContain("(+1 more)");+ expect(block).toContain("reviewer / del-2: (no label)");+ expect(block).toContain("reviewer / del-2");+ });++ it("says so when a chain read nothing", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.settle("res-1", "completed");+ expect(registry.promptBlock({ runningDelegationIds: NONE })).toContain(+ "Files read: none recorded",+ );+ });+});++describe("LRU eviction", () => {+ it("never evicts a running chain and drops the oldest settled one", () => {+ vi.useFakeTimers({ now: 1_700_000_000_000 });+ const registry = new DelegationChainRegistry();+ // The running chain is the *oldest* activity of the group: a naive LRU+ // would drop it first, stranding the delegate still writing into it.+ start(registry, { delegateSessionId: "res-run", delegationId: "del-run" });+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId: "res-a", delegationId: "del-a" });+ registry.settle("res-a", "completed");+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId: "res-b", delegationId: "del-b" });+ registry.settle("res-b", "completed");+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId: "res-c", delegationId: "del-c" });+ registry.settle("res-c", "completed");++ expect(registry.lookup("del-run")).toMatchObject({+ latestStatus: "running",+ });+ expect(registry.lookup("del-a")).toBeUndefined();+ expect(registry.lookup("del-b")).toBeDefined();+ expect(registry.lookup("del-c")).toBeDefined();++ const listed = registry.resumableList({+ runningDelegationIds: new Set(["del-run"]),+ });+ expect(listed.map((entry) => entry.latestDelegationId)).toEqual([+ "del-c",+ "del-b",+ ]);+ expect(listed).toHaveLength(MAX_RESUMABLE_CHAINS_PER_AGENT);+ });++ it("keeps every chain when only two per agent are settled", () => {+ vi.useFakeTimers({ now: 1_700_000_000_000 });+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-a", delegationId: "del-a" });+ registry.settle("res-a", "completed");+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId: "res-b", delegationId: "del-b" });+ registry.settle("res-b", "completed");+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId: "res-run", delegationId: "del-run" });+ // Re-settling an already settled chain is what triggers the sweep here.+ registry.settle("res-b", "completed");++ for (const delegationId of ["del-a", "del-b", "del-run"]) {+ expect(registry.lookup(delegationId)).toBeDefined();+ }+ expect(registry.lookup("del-run")).toMatchObject({+ latestStatus: "running",+ });+ });++ it("evicts per agent, not across agents", () => {+ vi.useFakeTimers({ now: 1_700_000_000_000 });+ const registry = new DelegationChainRegistry();+ const settled: Array<[string, string]> = [+ ["res-e1", "del-e1"],+ ["res-e2", "del-e2"],+ ["res-e3", "del-e3"],+ ];+ for (const [delegateSessionId, delegationId] of settled) {+ vi.advanceTimersByTime(1_000);+ start(registry, { delegateSessionId, delegationId });+ registry.settle(delegateSessionId, "completed");+ }+ vi.advanceTimersByTime(1_000);+ start(registry, {+ delegateSessionId: "res-r1",+ delegationId: "del-r1",+ agentName: "reviewer",+ });+ registry.settle("res-r1", "completed");++ expect(registry.lookup("del-e1")).toBeUndefined();+ expect(registry.lookup("del-r1")).toBeDefined();+ });+});++describe("noteReads", () => {+ it("merges files, adds new lines and keeps the chain identity", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ registry.noteReads("res-1", ["a.ts", "b.ts"], 3);+ registry.noteReads("res-1", ["b.ts", "c.ts"], 2);++ expect(registry.lookup("del-1")).toMatchObject({+ readFiles: ["a.ts", "b.ts", "c.ts"],+ readLineCount: 5,+ });+ });++ it("returns silently for a chain it does not hold", () => {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });+ expect(() => registry.noteReads("res-missing", ["x.ts"], 10)).not.toThrow();+ expect(registry.lookup("del-1")).toMatchObject({+ readFiles: [],+ readLineCount: 0,+ });+ expect(+ registry.resumableList({ runningDelegationIds: NONE }),+ ).toHaveLength(0);+ });+});++describe("retarget", () => {+ it("updates the model and keeps the last known key when none is given", () => {+ const registry = new DelegationChainRegistry();+ start(registry, {+ delegateSessionId: "res-1",+ delegationId: "del-1",+ modelId: "m1",+ modelKey: "local/m1",+ });+ registry.retarget("res-1", { modelKey: "remote/m2", modelId: "m2" });+ expect(registry.lookup("del-1")).toMatchObject({+ latestModelId: "m2",+ latestModelKey: "remote/m2",+ });++ registry.retarget("res-1", { modelId: "m3" });+ expect(registry.lookup("del-1")).toMatchObject({+ latestModelId: "m3",+ latestModelKey: "remote/m2",+ });+ });++ it("returns silently for a chain it does not hold", () => {+ const registry = new DelegationChainRegistry();+ expect(() =>+ registry.retarget("res-missing", { modelId: "m1" }),+ ).not.toThrow();+ });+});++describe("drop", () => {+ it("removes every delegationId on the chain", () => {+ const registry = new DelegationChainRegistry();+ registry.hydrate([chain()]);+ registry.drop("res-1");+ for (const delegationId of ["del-1", "del-2", "del-3"]) {+ expect(registry.lookup(delegationId)).toBeUndefined();+ }+ expect(registry.resumableList({ runningDelegationIds: NONE })).toEqual([]);+ });+});++describe("resume error messages", () => {+ function registryWithChain(): DelegationChainRegistry {+ const registry = new DelegationChainRegistry();+ start(registry, { delegateSessionId: "res-a", delegationId: "del-a" });+ registry.settle("res-a", "completed");+ return registry;+ }++ it("says there is nothing to reuse when the list is empty", () => {+ const registry = new DelegationChainRegistry();+ const unknown = registry.unknownResumeError("missing", []);+ expect(unknown).toContain('Unknown delegation "missing".');+ expect(unknown).toContain("No reusable subagent sessions in this conversation.");+ expect(unknown).not.toContain("Reusable:");++ const noHistory = registry.noHistoryResumeError("del-a", []);+ expect(noHistory).toContain('Delegation "del-a" has no recorded history');+ expect(noHistory).toContain("Start a new delegation.");+ expect(noHistory).not.toContain("Reusable:");+ });++ it("hints at the reusable chains it was given", () => {+ const registry = registryWithChain();+ const list = registry.resumableList({ runningDelegationIds: NONE });+ expect(list).toHaveLength(1);+ expect(registry.unknownResumeError("missing", list)).toContain(+ "Reusable: explorer / del-a.",+ );+ });++ it("never advertises the dropped id as reusable", () => {+ const registry = registryWithChain();+ // The caller drops the chain before composing the message (ADR 0278 §4),+ // so the id it names must not come back as its own suggestion.+ registry.drop("res-b");+ const list = registry.resumableList({ runningDelegationIds: NONE });+ const message = registry.noHistoryResumeError("del-b", list);+ expect(message).toContain('Delegation "del-b" has no recorded history');+ expect(message).toContain("Reusable: explorer / del-a.");+ expect(message).not.toContain("Reusable: explorer / del-b");+ });+});diff --git a/packages/agent-runtime/src/delegation-history.test.ts b/packages/agent-runtime/src/delegation-history.test.tsindex 49ce9431f..a216b7949 100644--- a/packages/agent-runtime/src/delegation-history.test.ts+++ b/packages/agent-runtime/src/delegation-history.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import { MAX_RESUMABLE_READ_LINES, type UiMessage } from "@pi-desktop/shared";import {+ chainRowsToMessages,extractReadFiles,formatResumableList,isChainWithinReadBudget,@@ -13,6 +14,7 @@ import {type DelegationChain,type ResumableChain,} from "./delegation-history.js";+import { DelegationChainRegistry } from "./delegation-chain.js";import type { RuntimeProviderConfig } from "./provider-binding.js";import { buildProviderModel } from "./provider-binding.js";@@ -430,3 +432,262 @@ describe("chain shape", () => {expect(chain.latestStatus).toBeUndefined();});});++/** A persisted `Task` row, as the settlement projection rewrites it. */+function restartedTaskRow(+ toolCallId: string,+ details: Record<string, unknown>,+ options: {+ toolStatus?: UiMessage["toolStatus"];+ args?: Record<string, unknown>;+ } = {},+): UiMessage {+ return {+ id: `row-${toolCallId}`,+ role: "tool",+ content: "",+ toolCallId,+ toolName: "Task",+ toolArgs: { agent: "explorer", task: "explore the parser", ...options.args },+ toolResult: { details },+ toolStatus: options.toolStatus ?? "success",+ createdAt: new Date(1_700_000_000_000).toISOString(),+ };+}++/** The same gate the live runtime uses, over chains rebuilt from the transcript. */+function resolveRebuilt(+ chains: DelegationChain[],+ resume: string,+ agentName = "explorer",+) {+ const registry = new DelegationChainRegistry();+ registry.hydrate(chains);+ return registry.resolveResume({+ resume,+ agentName,+ runningDelegationIds: new Set(),+ });+}++describe("rebuildChainsFromTranscript restart status (ADR 0278)", () => {+ it("keeps a completed or failed status a settled Task row recorded", () => {+ for (const status of ["completed", "failed"]) {+ const chains = rebuildChainsFromTranscript([+ restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status,+ }),+ ]);+ expect(chains).toHaveLength(1);+ expect(chains[0].latestStatus).toBe(status);+ expect(resolveRebuilt(chains, "d1").ok).toBe(true);+ }+ });++ it("keeps a stopped or aborted chain out of the resumable set", () => {+ for (const status of ["stopped", "aborted"]) {+ const chains = rebuildChainsFromTranscript([+ restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status,+ }),+ ]);+ expect(chains[0].latestStatus).toBe(status);+ expect(resolveRebuilt(chains, "d1")).toEqual({+ ok: false,+ error: { kind: "not-resumable", status },+ });+ }+ });++ it("normalizes a Task row the app closed mid-run to interrupted", () => {+ const chains = rebuildChainsFromTranscript([+ restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status: "running",+ }),+ ]);+ expect(chains[0].latestStatus).toBe("interrupted");+ expect(resolveRebuilt(chains, "d1")).toEqual({+ ok: false,+ error: { kind: "not-resumable", status: "interrupted" },+ });+ });++ it("normalizes an errored Task row without a status to failed", () => {+ const chains = rebuildChainsFromTranscript([+ restartedTaskRow(+ "call-1",+ { delegationId: "d1", agent: "explorer" },+ { toolStatus: "error" },+ ),+ ]);+ expect(chains[0].latestStatus).toBe("failed");+ expect(resolveRebuilt(chains, "d1").ok).toBe(true);+ });++ it("ignores a Task row that never produced a delegationId", () => {+ const rejected = restartedTaskRow(+ "call-1",+ { error: 'Unknown subagent "Researcher".' },+ { toolStatus: "error", args: { agent: "Researcher", task: "Find it." } },+ );+ expect(rebuildChainsFromTranscript([rejected])).toEqual([]);+ expect(+ rebuildChainsFromTranscript([+ rejected,+ delegateAssistant("a1", "found a", "call-1"),+ ]),+ ).toEqual([]);+ });+});++describe("rebuildChainsFromTranscript agent normalization (ADR 0278)", () => {+ it("normalizes the recorded agent so a restarted session still selects its rows", () => {+ for (const recorded of ["Explorer", "explorer.md", "EXPLORER "]) {+ const task = restartedTaskRow(+ "call-1",+ { delegationId: "d1", agent: "explorer", status: "completed" },+ { args: { agent: recorded } },+ );+ const read = delegateTool(+ "t1",+ "Read",+ { path: "src/app.ts" },+ { content: [{ type: "text", text: "body" }] },+ "call-1",+ );+ const transcript = [task, read];+ const chains = rebuildChainsFromTranscript(transcript);++ expect(chains).toHaveLength(1);+ expect(chains[0].agentName).toBe("explorer");+ // The delegate's own rows only match under the normalized name.+ expect(chains[0].readFiles).toEqual(["src/app.ts"]);+ expect(+ selectChainRows(transcript, {+ toolCallIds: ["call-1"],+ agentName: "explorer",+ }),+ ).toHaveLength(1);+ expect(resolveRebuilt(chains, "d1").ok).toBe(true);+ }+ });+});++describe("rebuildChainsFromTranscript settled copies and replay (ADR 0278)", () => {+ it("rebuilds a Task call once and lets the settled copy win", () => {+ const immediate = restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status: "running",+ });+ const settled = restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status: "completed",+ });+ const chains = rebuildChainsFromTranscript([+ immediate,+ delegateAssistant("a1", "found a", "call-1"),+ settled,+ ]);++ expect(chains).toHaveLength(1);+ expect(chains[0].toolCallIds).toEqual(["call-1"]);+ expect(chains[0].delegationIds).toEqual(["d1"]);+ expect(chains[0].latestStatus).toBe("completed");+ expect(resolveRebuilt(chains, "d1").ok).toBe(true);+ });++ it("resolves every delegationId on a rebuilt chain, resume links included", () => {+ const transcript: UiMessage[] = [+ restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status: "completed",+ }),+ delegateAssistant("a1", "found a", "call-1"),+ restartedTaskRow(+ "call-2",+ { delegationId: "d2", agent: "explorer", status: "completed" },+ { args: { resume: "d1" } },+ ),+ delegateAssistant("a2", "covered b", "call-2"),+ ];+ const chains = rebuildChainsFromTranscript(transcript);++ expect(chains).toHaveLength(1);+ expect(chains[0].delegationIds).toEqual(["d1", "d2"]);+ const registry = new DelegationChainRegistry();+ registry.hydrate(chains);+ for (const delegationId of ["d1", "d2"]) {+ expect(registry.lookup(delegationId)?.delegateSessionId).toBe("d1");+ }+ expect(+ registry+ .resumableList({ runningDelegationIds: new Set() })+ .map((entry) => entry.latestDelegationId),+ ).toEqual(["d2"]);+ });++ it("gates a rebuilt chain on the lines its own rows read", () => {+ const text = Array.from({ length: MAX_RESUMABLE_READ_LINES + 1 }, () => "x").join(+ "\n",+ );+ const transcript: UiMessage[] = [+ restartedTaskRow("call-1", {+ delegationId: "d1",+ agent: "explorer",+ status: "completed",+ }),+ delegateTool(+ "t1",+ "Read",+ { path: "huge.ts" },+ { content: [{ type: "text", text }] },+ "call-1",+ ),+ ];+ const [chain] = rebuildChainsFromTranscript(transcript);++ expect(chain.readLineCount).toBe(MAX_RESUMABLE_READ_LINES + 1);+ expect(isChainWithinReadBudget(chain)).toBe(false);+ expect(resolveRebuilt([chain], "d1")).toEqual({+ ok: false,+ error: { kind: "over-budget" },+ });+ });++ it("replays a delegate tool row with the arguments its call recorded", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", "reading src/app.ts", "call-1"),+ delegateTool(+ "t1",+ "Read",+ { path: "src/app.ts", offset: 3 },+ { content: [{ type: "text", text: "body" }] },+ "call-1",+ ),+ ];+ const messages = chainRowsToMessages(rows, provider(), buildProviderModel(provider()));+ const assistant = messages.find((message) => message.role === "assistant");++ expect(+ assistant?.role === "assistant" ? assistant.content : [],+ ).toContainEqual({+ type: "toolCall",+ id: "t1",+ name: "Read",+ arguments: { path: "src/app.ts", offset: 3 },+ });+ expect(messages.map((message) => message.role)).toEqual([+ "assistant",+ "toolResult",+ ]);+ });+});diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex d870d2e1f..11ad25b87 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -89,9 +89,11 @@ vi.mock("./subagent.js", async (importOriginal) => {});import {DEFAULT_SUBAGENT_IDLE_TIMEOUT_SECONDS,+ MAX_RESUMABLE_CHAINS_PER_AGENT,MAX_SUBAGENT_CONCURRENCY,} from "@pi-desktop/shared";import type {+ AgentEventEnvelope,ContextCompactionRecord,ContextCompactionSettings,CommandShellOption,@@ -6804,7 +6806,7 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});- describe("resume (ADR 0276)", () => {+ describe("resume (ADR 0278)", () => {/** Rows a delegate left in the transcript, tagged with its `Task` call. */function delegateRow(id: string,@@ -6896,12 +6898,16 @@ describe("DesktopAgentRuntime subagents", () => {),),).toBe(true);- const record = (runtime as any).delegations.get(- (started.details as any).delegationId,- );+ const internals = runtime as any;+ const delegationId = (started.details as any).delegationId as string;+ const record = internals.delegations.get(delegationId);expect(record.resumedFrom).toBe("del-1");expect(record.delegateSessionId).toBe("del-1");- expect(record.toolCallIdChain).toEqual(["task-1", "task-2"]);+ // The chain owns its calls now (ADR 0278); the id resolves to both.+ expect(internals.delegationChains.lookup(delegationId).toolCallIds).toEqual([+ "task-1",+ "task-2",+ ]);await runtime.dispose();});@@ -7032,6 +7038,402 @@ describe("DesktopAgentRuntime subagents", () => {subagentRuns.deferred = false;await runtime.dispose();});++ /** A `Task` row a restart rebuilds its chains from. */+ function restartedTaskRow(+ taskCallId: string,+ delegationId: string,+ details: Record<string, unknown> = {},+ ): UiMessage {+ return {+ id: `row-${taskCallId}`,+ role: "tool",+ content: "",+ createdAt: "2026-08-06T00:00:00.000Z",+ toolCallId: taskCallId,+ toolName: "Task",+ toolArgs: { agent: "explorer", task: "Explore the parser." },+ toolResult: {+ details: { delegationId, agent: "explorer", ...details },+ },+ toolStatus: "success",+ };+ }++ /** The envelope shape a delegate's own `SubagentRun` sends. */+ function delegateEnvelope(+ parentToolCallId: string,+ event: Record<string, unknown>,+ ): AgentEventEnvelope {+ return {+ sessionId: "session-1",+ turnId: "turn-1",+ ts: Date.now(),+ event: event as unknown as AgentEventEnvelope["event"],+ parentToolCallId,+ agentName: "explorer",+ };+ }++ it("records a delegate's reads in-session so the same session can resume them", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ const internals = runtime as any;+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.result = undefined;+ subagentRuns.deferred = true;++ const started = await startTask(runtime, "task-1", {+ agent: "explorer",+ task: "Find it.",+ description: "find the bug",+ });+ const delegationId = (started.details as any).delegationId as string;+ // A live delegate's tool events reach the runtime through the Task wiring.+ const onEvent = subagentRuns.calls[0].onEvent as (+ envelope: AgentEventEnvelope,+ ) => void;+ onEvent(+ delegateEnvelope("task-1", {+ type: "tool_start",+ toolCallId: "read-1",+ toolName: "Read",+ args: { path: "src/deep.ts" },+ }),+ );+ onEvent(+ delegateEnvelope("task-1", {+ type: "tool_end",+ toolCallId: "read-1",+ result: { content: [{ type: "text", text: "line one\nline two" }] },+ isError: false,+ }),+ );++ // The row a later resume replays keeps the call's arguments.+ const row = (internals.transcriptHistory as UiMessage[]).find(+ (entry) => entry.toolCallId === "read-1",+ );+ expect(row).toMatchObject({+ role: "tool",+ toolName: "Read",+ toolArgs: { path: "src/deep.ts" },+ parentToolCallId: "task-1",+ agentName: "explorer",+ });+ expect(internals.delegationChains.lookup(delegationId)).toMatchObject({+ readFiles: ["src/deep.ts"],+ readLineCount: 2,+ });++ subagentRuns.resolveRun?.({+ agentName: "explorer",+ status: "completed",+ report: "done",+ turns: 1,+ toolCalls: 1,+ });+ await vi.waitFor(() => {+ expect(internals.agent.state.systemPrompt).toContain(+ "Files read: src/deep.ts",+ );+ });+ expect(internals.agent.state.systemPrompt).not.toContain(+ "Files read: none recorded",+ );+ expect(+ internals.delegationChains+ .resumableList({ runningDelegationIds: new Set() })+ .find(+ (chain: { latestDelegationId: string }) =>+ chain.latestDelegationId === delegationId,+ )?.readFiles,+ ).toEqual(["src/deep.ts"]);++ // No restart in between: the same runtime resumes and replays that read.+ subagentRuns.calls.length = 0;+ const resumed = await startTask(runtime, "task-2", {+ agent: "explorer",+ task: "Now the rest.",+ resume: delegationId,+ });+ expect((resumed.details as any).resumedFrom).toBe(delegationId);+ expect(subagentRuns.calls).toHaveLength(1);+ const initial = subagentRuns.calls[0].initialMessages as Array<any>;+ expect(+ initial.some(+ (message: any) =>+ message.role === "assistant" &&+ message.content.some(+ (block: any) =>+ block.type === "toolCall" && block.arguments?.path === "src/deep.ts",+ ),+ ),+ ).toBe(true);++ subagentRuns.deferred = false;+ await runtime.dispose();+ });++ it("refuses to resume a chain a restart rebuilt from a stopped Task row", async () => {+ const history: UiMessage[] = [+ restartedTaskRow("task-1", "del-1", { status: "stopped" }),+ delegateRow("child-1", "task-1"),+ ];+ const runtime = createRuntime({ subagents: [explorer], history });+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;++ const result = await startTask(runtime, "task-2", {+ agent: "explorer",+ task: "Continue.",+ resume: "del-1",+ });++ expect(String((result.details as any).error)).toContain(+ 'ended as "stopped"',+ );+ expect(String((result.details as any).error)).toContain("cannot be resumed");+ expect(subagentRuns.calls).toHaveLength(0);+ await runtime.dispose();+ });++ it("resumes a chain a restart rebuilt from a completed Task row", async () => {+ const history: UiMessage[] = [+ restartedTaskRow("task-1", "del-1", { status: "completed" }),+ delegateRow("child-1", "task-1"),+ ];+ const runtime = createRuntime({ subagents: [explorer], history });+ subagentRuns.calls.length = 0;+ subagentRuns.result = undefined;+ subagentRuns.deferred = false;++ const result = await startTask(runtime, "task-2", {+ agent: "explorer",+ task: "Continue.",+ resume: "del-1",+ });++ expect((result.details as any).error).toBeUndefined();+ expect((result.details as any).resumedFrom).toBe("del-1");+ expect(subagentRuns.calls).toHaveLength(1);+ expect(subagentRuns.calls[0].initialMessages).toBeDefined();+ await runtime.dispose();+ });++ it("keeps a resumed chain on its recorded model after the session model moved", async () => {+ const remote = {+ ...provider,+ id: "remote",+ name: "Remote",+ modelId: "remote-model",+ modelConfig: undefined,+ };+ const moved = { ...provider, modelId: "next-model", modelConfig: undefined };+ const history: UiMessage[] = [+ restartedTaskRow("task-1", "del-1", {+ status: "completed",+ modelId: "remote-model",+ }),+ delegateRow("child-1", "task-1"),+ ];+ const runtime = createRuntime({+ provider: moved,+ subagents: [explorer],+ history,+ subagentProviders: { "remote/remote-model": remote },+ subagentModelKeys: ["remote/remote-model"],+ });+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = true;++ const result = await startTask(runtime, "task-2", {+ agent: "explorer",+ task: "Continue.",+ resume: "del-1",+ });++ // The session model is no reason to refuse: the chain keeps its own.+ expect((result.details as any).error).toBeUndefined();+ expect((result.details as any).resumedFrom).toBe("del-1");+ expect(subagentRuns.calls[0].provider).toBe(remote);++ subagentRuns.deferred = false;+ await runtime.dispose();+ });++ it("continues a chain whose recorded binding is gone and reports the change", async () => {+ const onEvent = vi.fn();+ const history: UiMessage[] = [+ restartedTaskRow("task-1", "del-1", {+ status: "completed",+ modelId: "gone-model",+ }),+ delegateRow("child-1", "task-1"),+ ];+ const runtime = createRuntime({ subagents: [explorer], history, onEvent });+ const internals = runtime as any;+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.deferred = true;++ const args = { agent: "explorer", task: "Continue.", resume: "del-1" };+ const result = await startTask(runtime, "task-2", args);+ const delegationId = (result.details as any).delegationId as string;++ // Refusing would strand the chain forever, so it continues on the+ // definition's current binding and records what it left behind.+ expect((result.details as any).error).toBeUndefined();+ expect((result.details as any).resumedFrom).toBe("del-1");+ expect(subagentRuns.calls[0].provider).toBe(provider);+ expect(internals.delegations.get(delegationId).modelChangedFrom).toBe(+ "gone-model",+ );++ // …and the parent sees it on the settled Task row.+ const handle = internals.handleAgentEvent.bind(runtime);+ await handle({+ type: "tool_execution_start",+ toolName: "Task",+ toolCallId: "task-2",+ args,+ });+ await handle({+ type: "tool_execution_end",+ toolName: "Task",+ toolCallId: "task-2",+ result,+ isError: false,+ });+ subagentRuns.resolveRun?.({+ agentName: "explorer",+ status: "completed",+ report: "done",+ turns: 1,+ toolCalls: 0,+ });+ await vi.waitFor(() => {+ const snapshots = onEvent.mock.calls+ .map(([envelope]) => envelope as any)+ .filter(+ (envelope) =>+ envelope.event.type === "message_end" &&+ envelope.event.message.role === "tool",+ );+ expect(snapshots).toHaveLength(1);+ });+ const snapshot = onEvent.mock.calls+ .map(([envelope]) => envelope as any)+ .find(+ (envelope) =>+ envelope.event.type === "message_end" &&+ envelope.event.message.role === "tool",+ );+ expect(snapshot.event.message.toolResult.details).toMatchObject({+ delegationId,+ status: "completed",+ modelChangedFrom: "gone-model",+ });++ subagentRuns.deferred = false;+ await runtime.dispose();+ });++ it("drops a chain whose rows are gone and keeps its id out of the reusable list", async () => {+ const history: UiMessage[] = [+ restartedTaskRow("task-1", "del-1", { status: "completed" }),+ restartedTaskRow("task-9", "del-2", { status: "completed" }),+ delegateRow("child-2", "task-9"),+ ];+ const runtime = createRuntime({ subagents: [explorer], history });+ const internals = runtime as any;+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ expect(internals.delegationChains.lookup("del-2")).toBeDefined();++ const result = await startTask(runtime, "task-2", {+ agent: "explorer",+ task: "Continue.",+ resume: "del-1",+ });+ const message = String((result.details as any).error);++ expect(message).toContain('Delegation "del-1" has no recorded history');+ // The chain is dropped before the message is composed, so the id it+ // names can never come back as its own suggestion (ADR 0278 §4).+ expect(message).not.toContain("Reusable: explorer / del-1");+ expect(message.split("Reusable: ")[1]).toBe("explorer / del-2.");+ expect(internals.delegationChains.lookup("del-1")).toBeUndefined();+ expect(+ internals.delegationChains+ .resumableList({ runningDelegationIds: new Set() })+ .map((chain: { latestDelegationId: string }) => chain.latestDelegationId),+ ).toEqual(["del-2"]);+ expect(subagentRuns.calls).toHaveLength(0);+ await runtime.dispose();+ });++ it("keeps a running chain in the registry when a sibling settles", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ const internals = runtime as any;+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.result = undefined;+ subagentRuns.deferred = true;++ const startedIds: string[] = [];+ const startOne = async (toolCallId: string) => {+ const result = await startTask(runtime, toolCallId, {+ agent: "explorer",+ task: "Find it.",+ });+ startedIds.push((result.details as any).delegationId as string);+ };+ const settleNewest = async () => {+ subagentRuns.instances[subagentRuns.instances.length - 1].resolve({+ agentName: "explorer",+ status: "completed",+ report: "done",+ turns: 1,+ toolCalls: 0,+ });+ await vi.waitFor(() => {+ expect(+ internals.delegations.get(startedIds[startedIds.length - 1]).status,+ ).toBe("completed");+ });+ };++ // The chain that stays running is the oldest of the four, so a plain LRU+ // would evict it and strand the delegate still writing into it.+ await startOne("task-run");+ for (const toolCallId of ["task-a", "task-b", "task-c"]) {+ await new Promise((resolve) => setTimeout(resolve, 5));+ await startOne(toolCallId);+ await settleNewest();+ }++ const runningId = startedIds[0];+ expect(internals.delegationChains.lookup(runningId)).toMatchObject({+ latestStatus: "running",+ });+ expect(internals.delegationChains.lookup(startedIds[1])).toBeUndefined();+ expect(internals.delegationChains.lookup(startedIds[2])).toBeDefined();+ expect(internals.delegationChains.lookup(startedIds[3])).toBeDefined();+ expect(+ internals.delegationChains+ .resumableList({ runningDelegationIds: new Set([runningId]) })+ .map((chain: { latestDelegationId: string }) => chain.latestDelegationId),+ ).toEqual([startedIds[3], startedIds[2]]);+ expect(+ [startedIds[1], startedIds[2], startedIds[3]].filter((id) =>+ internals.delegationChains.lookup(id),+ ),+ ).toHaveLength(MAX_RESUMABLE_CHAINS_PER_AGENT);++ subagentRuns.deferred = false;+ await runtime.dispose();+ });});});