diff --git a/apps/server/src/provider/AcpRegistrySessions.ts b/apps/server/src/provider/AcpRegistrySessions.ts index e0b46e08ea993..6375b4cabba5d 100644 --- a/apps/server/src/provider/AcpRegistrySessions.ts +++ b/apps/server/src/provider/AcpRegistrySessions.ts @@ -144,6 +144,31 @@ 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.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.", + ...(pending ? { pendingHistoryThreadId: threadId } : {}), + cause, + }); + }), + ), + ), + ); + const importSession = Effect.fn("AcpRegistrySessions.importSession")(function* ( input: AcpRegistryImportSessionInput, ) { @@ -185,16 +210,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 +268,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); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c96497c76a2c3..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; }); @@ -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,8 @@ 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"); + let runDuringHistoryRead = false; const repaired: Array = []; const deleted: Array = []; const session = (sessionId: string) => ({ @@ -2511,7 +2514,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 +2551,34 @@ 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(fresh); + return { threadId: fresh, projection, resumed: false }; + }).pipe(Effect.provideService(EventSink.EventSinkV2, sink), Effect.orDie), + }), Layer.mock(AgentSessionImporter.AgentSessionImporter)({ importNativeHistory: ({ threadId }) => - Effect.sync(() => repaired.push(threadId)).pipe(Effect.as(1)), + threadId === fresh + ? 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), ); @@ -2598,6 +2624,34 @@ 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, + }, + ); + + 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, 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..32f000062536a 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, @@ -18,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"; @@ -37,6 +39,10 @@ interface AcpSessionProject { readonly workspaceRoot: string; } +type SessionImportState = Pick; + +const isAcpRegistryOperationError = Schema.is(AcpRegistryOperationError); + function needsImport(session: AcpRegistrySession) { return session.importedThreadId === null || session.nativeHistoryPending === true; } @@ -120,12 +126,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 +199,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 +211,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 +249,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 +267,24 @@ function InstanceSessionManagement( }); return; } + const error = squashAtomCommandFailure(result); + if (isAcpRegistryOperationError(error) && 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 +306,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 +544,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 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: {}, delete: {} } }, + 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 }); + 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", + 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); + 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(); + }, +);