From 913e7112fe1e7cdb55a19e519924a6f51d7f5b35 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:01:18 +0100 Subject: [PATCH 01/10] test(acp): cover retry after a failed native history import Co-authored-by: GPT 6.2 Sol --- ...iled-history-keeps-import-available.e2e.ts | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts diff --git a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts new file mode 100644 index 0000000000000..bbc63cdb278e1 --- /dev/null +++ b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts @@ -0,0 +1,102 @@ +// @effect-diagnostics nodeBuiltinImport:off -- The scenario supplies a local ACP agent. +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const SESSION_TITLE = "Conversation with temporarily unavailable history"; +const ACP = ` +import { existsSync } from "node:fs"; +import { createInterface } from "node:readline"; + +const [recovered] = process.argv.slice(2); +for await (const line of createInterface({ input: process.stdin })) { + const { id, method, params } = JSON.parse(line); + if (id === undefined) continue; + const reply = (body) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...body }) + "\\n"); + if (method === "initialize") { + reply({ id, result: { + protocolVersion: 1, + agentInfo: { name: "history-scenario", version: "1.0.0" }, + agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } }, + authMethods: [], + } }); + } else if (method === "session/new") { + reply({ id, result: { sessionId: "health-probe" } }); + } else if (method === "session/list") { + reply({ id, result: { sessions: [{ + sessionId: "native-history", + cwd: params.cwd, + title: ${JSON.stringify(SESSION_TITLE)}, + }] } }); + } else if (method === "session/load") { + if (!existsSync(recovered)) { + reply({ id, error: { code: -32000, message: "History temporarily unavailable" } }); + continue; + } + reply({ method: "session/update", params: { + sessionId: params.sessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "An earlier answer from the native session" }, + }, + } }); + reply({ id, result: {} }); + } else { + reply({ id, error: { code: -32601, message: "Method not found" } }); + } +} +`; + +test( + "A failed native ACP history read leaves Import available without refreshing Settings", + WEB, + async ({ t3, app, screen }) => { + const instanceId = ProviderInstanceId.make("scenario-history-agent"); + const workspaceRoot = await t3.project("demo", { "history-agent.mjs": ACP }); + const recovered = NodePath.join(workspaceRoot, "history-recovered"); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, app.baseUrl ?? ""); + yield* client["server.updateSettings"]({ + patch: {}, + providerInstanceMutation: { + operation: "upsert", + instanceId, + instance: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "History scenario agent", + enabled: true, + config: { + source: "local", + commandPath: process.execPath, + commandArgs: [NodePath.join(workspaceRoot, "history-agent.mjs"), recovered], + }, + }, + }, + }); + }).pipe(Effect.scoped), + ); + + await t3.open(`/settings/providers?instanceId=${instanceId}`); + await screen.getByRole("button", "List sessions", { exact: true }).tap({ timeout: 60_000 }); + await screen.getByText(SESSION_TITLE, { exact: true }).waitFor(); + const importButton = screen.getByRole("button", "Import", { exact: true }); + await importButton.tap(); + await screen.getByRole("button", "Importing", { exact: true }).waitFor({ + state: "hidden", + timeout: 60_000, + }); + await NodeFSP.writeFile(recovered, ""); + await app.screenshot("native-session-after-history-failure"); + expect( + (await importButton.isVisible()) && (await importButton.isEnabled()), + "Import can be retried after the history read failed", + ).toBe(true); + }, +); From 04424733ea26527fb8577f42143c82e8a2223848 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:02:04 +0100 Subject: [PATCH 02/10] fix(acp): report failed native history imports Co-authored-by: GPT 6.2 Sol --- .../src/provider/AcpRegistrySessions.ts | 36 +++++++++---------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/apps/server/src/provider/AcpRegistrySessions.ts b/apps/server/src/provider/AcpRegistrySessions.ts index e0b46e08ea993..56838969b4e42 100644 --- a/apps/server/src/provider/AcpRegistrySessions.ts +++ b/apps/server/src/provider/AcpRegistrySessions.ts @@ -144,6 +144,20 @@ const make = Effect.gen(function* () { return { instance, manager: instance.acpSessionManagement }; }); + const importHistory = Effect.fn("AcpRegistrySessions.importHistory")( + (threadId: ThreadId, workspaceRoot: string) => + agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( + Effect.mapError( + (cause) => + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not import the ACP session history.", + cause, + }), + ), + ), + ); + const importSession = Effect.fn("AcpRegistrySessions.importSession")(function* ( input: AcpRegistryImportSessionInput, ) { @@ -185,16 +199,7 @@ const make = Effect.gen(function* () { historyOrigin: existing.historyOrigin, hasRun: existing.latestRunId !== null, }); - yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ - reason: "session_import_failed", - message: "Could not import the ACP session history.", - cause, - }), - ), - ); + yield* importHistory(threadId, workspaceRoot); return { threadId, imported: repairing } as const; } @@ -252,16 +257,7 @@ const make = Effect.gen(function* () { cause: launched.failure, }); } - // The thread is usable without its history, so a failed read only logs. - yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( - Effect.catch((cause) => - Effect.logWarning("Could not import ACP session history", { - instanceId: input.instanceId, - sessionId: input.sessionId, - cause, - }), - ), - ); + yield* importHistory(threadId, workspaceRoot); return { threadId, imported: true } as const; }, coordinator.withSessionMutation); From 04c907fcf524b3c93b501020b6022c909d45688d Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:15:50 +0100 Subject: [PATCH 03/10] fix(acp): keep pending history imports bound in Settings Co-authored-by: GPT 6.2 Sol --- .../src/provider/AcpRegistrySessions.ts | 7 +-- apps/server/src/ws.test.ts | 47 ++++++++++++++++-- ...pSessionManagementSection.browser.test.tsx | 37 ++++++++++++++ .../settings/AcpSessionManagementSection.tsx | 49 +++++++++++++------ packages/contracts/src/acpRegistry.ts | 1 + 5 files changed, 119 insertions(+), 22 deletions(-) diff --git a/apps/server/src/provider/AcpRegistrySessions.ts b/apps/server/src/provider/AcpRegistrySessions.ts index 56838969b4e42..250ad9d752e56 100644 --- a/apps/server/src/provider/AcpRegistrySessions.ts +++ b/apps/server/src/provider/AcpRegistrySessions.ts @@ -145,13 +145,14 @@ const make = Effect.gen(function* () { }); const importHistory = Effect.fn("AcpRegistrySessions.importHistory")( - (threadId: ThreadId, workspaceRoot: string) => + (threadId: ThreadId, workspaceRoot: string, nativeHistoryPending: boolean) => agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( Effect.mapError( (cause) => new AcpRegistryOperationError({ reason: "session_import_failed", message: "Could not import the ACP session history.", + ...(nativeHistoryPending ? { pendingHistoryThreadId: threadId } : {}), cause, }), ), @@ -199,7 +200,7 @@ const make = Effect.gen(function* () { historyOrigin: existing.historyOrigin, hasRun: existing.latestRunId !== null, }); - yield* importHistory(threadId, workspaceRoot); + yield* importHistory(threadId, workspaceRoot, repairing); return { threadId, imported: repairing } as const; } @@ -257,7 +258,7 @@ const make = Effect.gen(function* () { cause: launched.failure, }); } - yield* importHistory(threadId, workspaceRoot); + yield* importHistory(threadId, workspaceRoot, true); return { threadId, imported: true } as const; }, coordinator.withSessionMutation); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c96497c76a2c3..e370f360d6ec1 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2468,6 +2468,7 @@ const seedAcpThread = Effect.fn(function* ( it.effect("ACP session RPCs list a thread missing its history and repair it on import", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; + const sink = yield* EventSink.EventSinkV2; const sql = yield* SqlClient.SqlClient; const pending = yield* seedAcpThread("pending", { imported: false, ran: false }); const complete = yield* seedAcpThread("complete", { imported: true, ran: false }); @@ -2477,6 +2478,7 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i ran: true, nativeId: "owned-session", }); + const fresh = acpThreadId("new"); const repaired: Array = []; const deleted: Array = []; const session = (sessionId: string) => ({ @@ -2511,7 +2513,7 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i layerUnusedConfigRpcServices, Layer.fresh(layerConfigSources), Layer.mock(ExternalLauncher.ExternalLauncher)({}), - Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), Layer.mock(UsageLimitSources.UsageLimitSources)({}), Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), Layer.mock(DirectEndpoints.DirectEndpoints)({}), @@ -2548,11 +2550,29 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i ), ), }), - // Repairing an existing thread must not launch another one. - Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({ + enqueueCommand: (effect) => effect, + }), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: ({ threadId, importedNativeThread }) => + Effect.gen(function* () { + assert.equal(threadId, fresh); + assert.equal(importedNativeThread?.ref.nativeId, "new"); + yield* seedAcpThread("new", { imported: false, ran: false, nativeId: "new" }); + const projection = yield* projections.getThreadProjection(threadId).pipe(Effect.orDie); + return { threadId, projection, resumed: false }; + }).pipe(Effect.provideService(EventSink.EventSinkV2, sink)), + }), Layer.mock(AgentSessionImporter.AgentSessionImporter)({ importNativeHistory: ({ threadId }) => - Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)), + threadId === fresh + ? Effect.fail( + new Orchestrator.OrchestratorProjectionError({ + threadId, + cause: new Error("Native history unavailable"), + }), + ) + : Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)), }), Layer.succeed(SqlClient.SqlClient, sql), ); @@ -2598,6 +2618,25 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i ], ); + const failed = yield* client[WS_METHODS.serverImportAcpRegistrySession]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + sessionId: "new", + }).pipe(Effect.flip); + assert.propertyVal(failed, "reason", "session_import_failed"); + assert.propertyVal(failed, "pendingHistoryThreadId", fresh); + const afterFailure = yield* client[WS_METHODS.serverListAcpRegistrySessions]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + }); + assert.include( + afterFailure.sessions.find(({ sessionId }) => sessionId === "new"), + { + importedThreadId: fresh, + nativeHistoryPending: true, + }, + ); + const imported = yield* client[WS_METHODS.serverImportAcpRegistrySession]({ instanceId: acpInstanceId, projectId: acpProjectId, diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx index d0b1292cca7cc..30ecdb873b8cb 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx @@ -1,4 +1,5 @@ import { + AcpRegistryOperationError, EnvironmentId, ProjectId, ProviderDriverKind, @@ -8,6 +9,7 @@ import { type AcpRegistryConfigurableProvider, } from "@t3tools/contracts"; import type { ComponentProps } from "react"; +import * as Cause from "effect/Cause"; import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; @@ -186,6 +188,41 @@ it("rechecks task access after confirming deletion", async () => { expect(commands.delete).not.toHaveBeenCalled(); }); +it("keeps Import available and disables Delete after a bound session fails to import history", async () => { + setup(); + commands.import.mockResolvedValueOnce({ + _tag: "Failure", + cause: Cause.fail( + new AcpRegistryOperationError({ + reason: "session_import_failed", + message: "Could not import the ACP session history.", + pendingHistoryThreadId: ThreadId.make("thread-imported"), + }), + ), + }); + await using screen = await renderSection(); + await screen.click("List sessions"); + expect(screen.button("Delete").disabled).toBe(false); + + let finishRefresh!: (value: unknown) => void; + commands.list.mockReturnValueOnce( + new Promise((resolve) => { + finishRefresh = resolve; + }), + ); + await screen.click("Refresh"); + await screen.click("Import"); + expect(screen.button("Delete").disabled).toBe(true); + await act(async () => + finishRefresh({ _tag: "Success", value: { sessions: [session], nextCursor: null } }), + ); + expect(screen.button("Import").disabled).toBe(false); + expect(screen.button("Delete").disabled).toBe(true); + + await screen.click("Import"); + expect(screen.button("Imported").disabled).toBe(true); +}); + it("keeps a deleted ACP session out of a pending page only", async () => { setup(); commands.list.mockResolvedValueOnce({ diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsx index 063c57d1681f8..2cd3aa4cbf767 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx @@ -1,5 +1,6 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { + AcpRegistryOperationError, AuthOrchestrationOperateScope, AuthProvidersManageScope, AuthOrchestrationReadScope, @@ -37,6 +38,8 @@ interface AcpSessionProject { readonly workspaceRoot: string; } +type SessionImportState = Pick; + function needsImport(session: AcpRegistrySession) { return session.importedThreadId === null || session.nativeHistoryPending === true; } @@ -120,12 +123,12 @@ function InstanceSessionManagement( const canRead = useEnvironmentScope(props.environmentId, AuthOrchestrationReadScope); const { projectId } = props; const projectGeneration = useRef(0); - const deletionsDuringList = useRef | null>(null); + const mutationsDuringList = useRef | null>(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Late continuations must not act on a replaced project scope. useLayoutEffect(() => { return () => { projectGeneration.current += 1; - deletionsDuringList.current = null; + mutationsDuringList.current = null; }; // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retiring a project invalidates its pending operations even when the instance stays mounted. }, [projectId]); @@ -193,8 +196,8 @@ function InstanceSessionManagement( const loadSessions = async (cursor?: string) => { const generation = projectGeneration.current; if (projectId === null || loading) return; - const deletedSessionIds = new Set(); - deletionsDuringList.current = deletedSessionIds; + const mutations = new Map(); + mutationsDuringList.current = mutations; setLoading(true); const result = await listSessions({ environmentId: props.environmentId, @@ -205,13 +208,14 @@ function InstanceSessionManagement( }, }); if (generation !== projectGeneration.current) return; - deletionsDuringList.current = null; + mutationsDuringList.current = null; setLoading(false); if (result._tag === "Success") { - // A pending list can return a snapshot taken before a deletion completed. - const listedSessions = result.value.sessions.filter( - (session) => !deletedSessionIds.has(session.sessionId), - ); + // A pending list can return a snapshot taken before a mutation completed. + const listedSessions = result.value.sessions.flatMap((session) => { + const mutation = mutations.get(session.sessionId); + return mutation === null ? [] : [{ ...session, ...mutation }]; + }); setSessions((current) => cursor === undefined ? listedSessions : [...current, ...listedSessions], ); @@ -242,14 +246,16 @@ function InstanceSessionManagement( }); if (generation !== projectGeneration.current) return; setImportingSessionId(null); - if (result._tag === "Success") { + const updateImportState = (state: SessionImportState) => { + mutationsDuringList.current?.set(session.sessionId, state); setSessions((current) => current.map((candidate) => - candidate.sessionId === session.sessionId - ? { ...candidate, importedThreadId: result.value.threadId, nativeHistoryPending: false } - : candidate, + candidate.sessionId === session.sessionId ? { ...candidate, ...state } : candidate, ), ); + }; + if (result._tag === "Success") { + updateImportState({ importedThreadId: result.value.threadId, nativeHistoryPending: false }); toastManager.add({ type: "success", title: result.value.imported @@ -258,12 +264,24 @@ function InstanceSessionManagement( }); return; } + const error = squashAtomCommandFailure(result); + if (error instanceof AcpRegistryOperationError && error.pendingHistoryThreadId !== undefined) { + updateImportState({ + importedThreadId: error.pendingHistoryThreadId, + nativeHistoryPending: true, + }); + } reportFailure(gt("Could not import ACP session"), result); }; const deleteNativeSession = async (session: AcpRegistrySession) => { const generation = projectGeneration.current; - if (projectId === null || deletingSessionId !== null || session.importedThreadId !== null) + if ( + projectId === null || + deletingSessionId !== null || + importingSessionId === session.sessionId || + session.importedThreadId !== null + ) return; const confirmed = await ensureLocalApi().dialogs.confirm( gt('Permanently delete native ACP session "{session}"?', { @@ -285,7 +303,7 @@ function InstanceSessionManagement( if (generation !== projectGeneration.current) return; setDeletingSessionId(null); if (result._tag === "Success") { - deletionsDuringList.current?.add(session.sessionId); + mutationsDuringList.current?.set(session.sessionId, null); setSessions((current) => current.filter((candidate) => candidate.sessionId !== session.sessionId), ); @@ -523,6 +541,7 @@ function InstanceSessionManagement( disabled={ !canOperate || session.importedThreadId !== null || + importingSessionId === session.sessionId || deletingSessionId !== null } onClick={() => void deleteNativeSession(session)} diff --git a/packages/contracts/src/acpRegistry.ts b/packages/contracts/src/acpRegistry.ts index fffbe8dd44934..119471b993453 100644 --- a/packages/contracts/src/acpRegistry.ts +++ b/packages/contracts/src/acpRegistry.ts @@ -346,6 +346,7 @@ export class AcpRegistryOperationError extends Schema.TaggedError Date: Fri, 20 Nov 2026 08:17:16 +0100 Subject: [PATCH 04/10] fix(acp): validate the history error with its schema Co-authored-by: GPT 6.2 Sol --- apps/server/src/ws.test.ts | 8 +++++--- .../components/settings/AcpSessionManagementSection.tsx | 5 ++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e370f360d6ec1..78fb426649c26 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2558,9 +2558,11 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i Effect.gen(function* () { assert.equal(threadId, fresh); assert.equal(importedNativeThread?.ref.nativeId, "new"); - yield* seedAcpThread("new", { imported: false, ran: false, nativeId: "new" }); - const projection = yield* projections.getThreadProjection(threadId).pipe(Effect.orDie); - return { threadId, projection, resumed: false }; + yield* seedAcpThread("new", { imported: false, ran: false, nativeId: "new" }).pipe( + Effect.orDie, + ); + const projection = yield* projections.getThreadProjection(fresh).pipe(Effect.orDie); + return { threadId: fresh, projection, resumed: false }; }).pipe(Effect.provideService(EventSink.EventSinkV2, sink)), }), Layer.mock(AgentSessionImporter.AgentSessionImporter)({ diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsx index 2cd3aa4cbf767..32f000062536a 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx @@ -19,6 +19,7 @@ import { squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; +import * as Schema from "effect/Schema"; import { useLayoutEffect, useRef, useState } from "react"; import { msg, T, useGT } from "gt-react"; import { m } from "../../i18n/messages"; @@ -40,6 +41,8 @@ interface AcpSessionProject { type SessionImportState = Pick; +const isAcpRegistryOperationError = Schema.is(AcpRegistryOperationError); + function needsImport(session: AcpRegistrySession) { return session.importedThreadId === null || session.nativeHistoryPending === true; } @@ -265,7 +268,7 @@ function InstanceSessionManagement( return; } const error = squashAtomCommandFailure(result); - if (error instanceof AcpRegistryOperationError && error.pendingHistoryThreadId !== undefined) { + if (isAcpRegistryOperationError(error) && error.pendingHistoryThreadId !== undefined) { updateImportState({ importedThreadId: error.pendingHistoryThreadId, nativeHistoryPending: true, From 9711457ca20f82ec0b1a6d6216a09328151748fe Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:19:52 +0100 Subject: [PATCH 05/10] test(acp): handle launch fixture errors once Co-authored-by: GPT 6.2 Sol --- apps/server/src/ws.test.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 78fb426649c26..e322f3ec9eb9d 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2558,12 +2558,10 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i Effect.gen(function* () { assert.equal(threadId, fresh); assert.equal(importedNativeThread?.ref.nativeId, "new"); - yield* seedAcpThread("new", { imported: false, ran: false, nativeId: "new" }).pipe( - Effect.orDie, - ); - const projection = yield* projections.getThreadProjection(fresh).pipe(Effect.orDie); + yield* seedAcpThread("new", { imported: false, ran: false, nativeId: "new" }); + const projection = yield* projections.getThreadProjection(fresh); return { threadId: fresh, projection, resumed: false }; - }).pipe(Effect.provideService(EventSink.EventSinkV2, sink)), + }).pipe(Effect.provideService(EventSink.EventSinkV2, sink), Effect.orDie), }), Layer.mock(AgentSessionImporter.AgentSessionImporter)({ importNativeHistory: ({ threadId }) => From ca2b31328fb20204fd1a0916ed54f5c36389c146 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:27:59 +0100 Subject: [PATCH 06/10] fix(acp): recheck history retry eligibility after a failed read Co-authored-by: GPT 6.2 Sol --- .../src/provider/AcpRegistrySessions.ts | 26 +++++-- apps/server/src/ws.test.ts | 73 +++++++++++-------- 2 files changed, 62 insertions(+), 37 deletions(-) diff --git a/apps/server/src/provider/AcpRegistrySessions.ts b/apps/server/src/provider/AcpRegistrySessions.ts index 250ad9d752e56..6375b4cabba5d 100644 --- a/apps/server/src/provider/AcpRegistrySessions.ts +++ b/apps/server/src/provider/AcpRegistrySessions.ts @@ -145,16 +145,26 @@ const make = Effect.gen(function* () { }); const importHistory = Effect.fn("AcpRegistrySessions.importHistory")( - (threadId: ThreadId, workspaceRoot: string, nativeHistoryPending: boolean) => + (threadId: ThreadId, workspaceRoot: string) => agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( - Effect.mapError( - (cause) => - new AcpRegistryOperationError({ + Effect.catch((cause) => + Effect.gen(function* () { + const thread = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.orElseSucceed(() => null)); + const pending = + thread !== null && + AgentSessionImporter.isNativeHistoryPending({ + historyOrigin: thread.historyOrigin, + hasRun: thread.latestRunId !== null, + }); + return yield* new AcpRegistryOperationError({ reason: "session_import_failed", message: "Could not import the ACP session history.", - ...(nativeHistoryPending ? { pendingHistoryThreadId: threadId } : {}), + ...(pending ? { pendingHistoryThreadId: threadId } : {}), cause, - }), + }); + }), ), ), ); @@ -200,7 +210,7 @@ const make = Effect.gen(function* () { historyOrigin: existing.historyOrigin, hasRun: existing.latestRunId !== null, }); - yield* importHistory(threadId, workspaceRoot, repairing); + yield* importHistory(threadId, workspaceRoot); return { threadId, imported: repairing } as const; } @@ -258,7 +268,7 @@ const make = Effect.gen(function* () { cause: launched.failure, }); } - yield* importHistory(threadId, workspaceRoot, true); + yield* importHistory(threadId, workspaceRoot); return { threadId, imported: true } as const; }, coordinator.withSessionMutation); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e322f3ec9eb9d..3c5e3927228b4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2370,6 +2370,30 @@ const acpStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( Layer.provideMerge(SqlitePersistence.layerMemory), ); +const acpRunUpdated = (threadId: ThreadId, now: DateTime.Utc): OrchestrationV2DomainEvent => ({ + id: EventId.make(`${threadId}:run`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + id: RunId.make(`${threadId}:run`), + threadId, + ordinal: 1, + providerInstanceId: acpInstanceId, + modelSelection: { instanceId: acpInstanceId, model: "default" }, + providerThreadId: null, + userMessageId: MessageId.make(`${threadId}:prompt`), + rootNodeId: null, + activeAttemptId: null, + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }, +}); + const seedAcpThread = Effect.fn(function* ( sessionId: string, state: { readonly imported: boolean; readonly ran: boolean; readonly nativeId?: string }, @@ -2436,31 +2460,7 @@ const seedAcpThread = Effect.fn(function* ( }, }); } - if (state.ran) { - events.push({ - id: EventId.make(`${threadId}:run`), - type: "run.updated", - threadId, - occurredAt: now, - payload: { - id: RunId.make(`${threadId}:run`), - threadId, - ordinal: 1, - providerInstanceId: acpInstanceId, - modelSelection: thread.modelSelection, - providerThreadId: null, - userMessageId: MessageId.make(`${threadId}:prompt`), - rootNodeId: null, - activeAttemptId: null, - status: "completed", - requestedAt: now, - startedAt: now, - completedAt: now, - checkpointId: null, - contextHandoffId: null, - }, - }); - } + if (state.ran) events.push(acpRunUpdated(threadId, now)); yield* sink.write({ events }); return threadId; }); @@ -2479,6 +2479,7 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i nativeId: "owned-session", }); const fresh = acpThreadId("new"); + let runDuringHistoryRead = false; const repaired: Array = []; const deleted: Array = []; const session = (sessionId: string) => ({ @@ -2566,12 +2567,17 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i Layer.mock(AgentSessionImporter.AgentSessionImporter)({ importNativeHistory: ({ threadId }) => threadId === fresh - ? Effect.fail( - new Orchestrator.OrchestratorProjectionError({ + ? Effect.gen(function* () { + if (runDuringHistoryRead) { + yield* sink + .write({ events: [acpRunUpdated(threadId, yield* DateTime.now)] }) + .pipe(Effect.orDie); + } + return yield* new Orchestrator.OrchestratorProjectionError({ threadId, cause: new Error("Native history unavailable"), - }), - ) + }); + }) : Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)), }), Layer.succeed(SqlClient.SqlClient, sql), @@ -2637,6 +2643,15 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i }, ); + runDuringHistoryRead = true; + const failedAfterRun = yield* client[WS_METHODS.serverImportAcpRegistrySession]({ + instanceId: acpInstanceId, + projectId: acpProjectId, + sessionId: "new", + }).pipe(Effect.flip); + assert.propertyVal(failedAfterRun, "reason", "session_import_failed"); + assert.notProperty(failedAfterRun, "pendingHistoryThreadId"); + const imported = yield* client[WS_METHODS.serverImportAcpRegistrySession]({ instanceId: acpInstanceId, projectId: acpProjectId, From eae66b9c1c369a475f1155270ad91e48cd874a05 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:28:18 +0100 Subject: [PATCH 07/10] test(acp): verify ownership and recovery after a history read fails Co-authored-by: GPT 6.2 Sol --- .../acp-failed-history-keeps-import-available.e2e.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts index bbc63cdb278e1..75d38ba065548 100644 --- a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts +++ b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts @@ -23,7 +23,7 @@ for await (const line of createInterface({ input: process.stdin })) { reply({ id, result: { protocolVersion: 1, agentInfo: { name: "history-scenario", version: "1.0.0" }, - agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } }, + agentCapabilities: { loadSession: true, sessionCapabilities: { list: {}, delete: {} } }, authMethods: [], } }); } else if (method === "session/new") { @@ -87,6 +87,8 @@ test( await screen.getByRole("button", "List sessions", { exact: true }).tap({ timeout: 60_000 }); await screen.getByText(SESSION_TITLE, { exact: true }).waitFor(); const importButton = screen.getByRole("button", "Import", { exact: true }); + const deleteButton = screen.getByRole("button", "Delete", { exact: true }); + await expect(deleteButton).toBeEnabled(); await importButton.tap(); await screen.getByRole("button", "Importing", { exact: true }).waitFor({ state: "hidden", @@ -98,5 +100,12 @@ test( (await importButton.isVisible()) && (await importButton.isEnabled()), "Import can be retried after the history read failed", ).toBe(true); + await expect(deleteButton).toBeDisabled(); + + await importButton.tap(); + const importedButton = screen.getByRole("button", "Imported", { exact: true }); + await importedButton.waitFor({ timeout: 60_000 }); + await expect(importedButton).toBeDisabled(); + await expect(screen.getByText("ACP session imported", { exact: true })).toBeVisible(); }, ); From 4448e99136e1c14c55425016440ae769539520c6 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:31:21 +0100 Subject: [PATCH 08/10] test(acp): extend the original fixture with deletion capability Co-authored-by: GPT 6.2 Sol --- .../acp-failed-history-keeps-import-available.e2e.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts index 75d38ba065548..249abed416613 100644 --- a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts +++ b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts @@ -15,6 +15,10 @@ import { existsSync } from "node:fs"; import { createInterface } from "node:readline"; const [recovered] = process.argv.slice(2); +const withSessionDelete = (result) => { + result.agentCapabilities.sessionCapabilities.delete = {}; + return result; +}; for await (const line of createInterface({ input: process.stdin })) { const { id, method, params } = JSON.parse(line); if (id === undefined) continue; @@ -23,7 +27,9 @@ for await (const line of createInterface({ input: process.stdin })) { reply({ id, result: { protocolVersion: 1, agentInfo: { name: "history-scenario", version: "1.0.0" }, - agentCapabilities: { loadSession: true, sessionCapabilities: { list: {}, delete: {} } }, + ...withSessionDelete({ + agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } }, + }), authMethods: [], } }); } else if (method === "session/new") { From 4f596b081453cc002216748c3bcb97dc83c9fffc Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:34:27 +0100 Subject: [PATCH 09/10] chore: credit the models that worked on this change Co-authored-by: Claude Opus 5.5 From fae68bf4d2543023761a52771930a29ac199cadd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 07:51:43 +0000 Subject: [PATCH 10/10] test(acp): declare session delete in the scenario agent's capabilities Co-Authored-By: Claude Opus 5.5 --- .../acp-failed-history-keeps-import-available.e2e.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts index 249abed416613..75d38ba065548 100644 --- a/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts +++ b/scripts/scenarios/acp-failed-history-keeps-import-available.e2e.ts @@ -15,10 +15,6 @@ import { existsSync } from "node:fs"; import { createInterface } from "node:readline"; const [recovered] = process.argv.slice(2); -const withSessionDelete = (result) => { - result.agentCapabilities.sessionCapabilities.delete = {}; - return result; -}; for await (const line of createInterface({ input: process.stdin })) { const { id, method, params } = JSON.parse(line); if (id === undefined) continue; @@ -27,9 +23,7 @@ for await (const line of createInterface({ input: process.stdin })) { reply({ id, result: { protocolVersion: 1, agentInfo: { name: "history-scenario", version: "1.0.0" }, - ...withSessionDelete({ - agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } }, - }), + agentCapabilities: { loadSession: true, sessionCapabilities: { list: {}, delete: {} } }, authMethods: [], } }); } else if (method === "session/new") {