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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 27 additions & 20 deletions apps/server/src/provider/AcpRegistrySessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
) {
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);

Expand Down
112 changes: 83 additions & 29 deletions apps/server/src/ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -2436,38 +2460,15 @@ 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;
});

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 });
Expand All @@ -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<ThreadId> = [];
const deleted: Array<string> = [];
const session = (sessionId: string) => ({
Expand Down Expand Up @@ -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)({}),
Expand Down Expand Up @@ -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),
);
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
AcpRegistryOperationError,
EnvironmentId,
ProjectId,
ProviderDriverKind,
Expand All @@ -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";

Expand Down Expand Up @@ -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({
Expand Down
Loading
Loading