Fix Claude Process leak[MEMORY INTENSIVE], archiving, and stale claude session monitoring. (#2042)
Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: codex <[email protected]>
This commit is contained in:
19 files changed
+1686
-49
No files matched your search
@@ -20,7 +20,8 @@
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
|
||||
@@ -470,6 +470,154 @@ describe("startSession", () => {
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("disposes an existing session before starting a replacement for the same thread", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const existingContext = {
|
||||
session: {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.set(asThreadId("thread-1"), existingContext);
|
||||
|
||||
const disposeSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
disposeSession: (
|
||||
context: typeof existingContext,
|
||||
options?: { readonly emitLifecycleEvent?: boolean },
|
||||
) => void;
|
||||
},
|
||||
"disposeSession",
|
||||
)
|
||||
.mockImplementation(() => {});
|
||||
const assertSupportedCodexCliVersion = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {});
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
|
||||
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
|
||||
emitLifecycleEvent: false,
|
||||
});
|
||||
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
disposeSession.mockRestore();
|
||||
assertSupportedCodexCliVersion.mockRestore();
|
||||
processCwd.mockRestore();
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.clear();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("continues replacement start when existing session disposal fails", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const existingContext = {
|
||||
session: {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.set(asThreadId("thread-1"), existingContext);
|
||||
|
||||
const disposeSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
disposeSession: (
|
||||
context: typeof existingContext,
|
||||
options?: { readonly emitLifecycleEvent?: boolean },
|
||||
) => void;
|
||||
},
|
||||
"disposeSession",
|
||||
)
|
||||
.mockImplementation(() => {
|
||||
throw new Error("dispose failed");
|
||||
});
|
||||
const assertSupportedCodexCliVersion = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {});
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
|
||||
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
|
||||
emitLifecycleEvent: false,
|
||||
});
|
||||
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
disposeSession.mockRestore();
|
||||
assertSupportedCodexCliVersion.mockRestore();
|
||||
processCwd.mockRestore();
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.clear();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
|
||||
@@ -450,6 +450,25 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
let context: CodexSessionContext | undefined;
|
||||
|
||||
try {
|
||||
const existingContext = this.sessions.get(threadId);
|
||||
if (existingContext) {
|
||||
await Effect.logWarning("codex app-server replacing existing session", {
|
||||
threadId,
|
||||
existingStatus: existingContext.session.status,
|
||||
}).pipe(this.runPromise);
|
||||
try {
|
||||
this.disposeSession(existingContext, {
|
||||
emitLifecycleEvent: false,
|
||||
});
|
||||
} catch (error) {
|
||||
await Effect.logWarning("codex app-server failed to dispose existing session", {
|
||||
threadId,
|
||||
existingStatus: existingContext.session.status,
|
||||
cause: error instanceof Error ? error.message : String(error),
|
||||
}).pipe(this.runPromise);
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedCwd = input.cwd ?? process.cwd();
|
||||
|
||||
const session: ProviderSession = {
|
||||
@@ -901,6 +920,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposeSession(context, {
|
||||
emitLifecycleEvent: true,
|
||||
});
|
||||
}
|
||||
|
||||
private disposeSession(
|
||||
context: CodexSessionContext,
|
||||
options?: { readonly emitLifecycleEvent?: boolean },
|
||||
): void {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.stopping = true;
|
||||
|
||||
for (const pending of context.pending.values()) {
|
||||
@@ -921,8 +953,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
this.sessions.delete(threadId);
|
||||
if (options?.emitLifecycleEvent !== false) {
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
}
|
||||
this.sessions.delete(context.session.threadId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
|
||||
@@ -1307,6 +1307,71 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("closes the previous session before replacing an existing thread session", () => {
|
||||
const queries: FakeClaudeQuery[] = [];
|
||||
const layer = makeClaudeAdapterLive({
|
||||
createQuery: () => {
|
||||
const query = new FakeClaudeQuery();
|
||||
queries.push(query);
|
||||
return query;
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const firstSession = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const secondSession = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: firstSession.resumeCursor,
|
||||
});
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const activeSessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(queries.length, 2);
|
||||
assert.equal(queries[0]?.closeCalls, 1);
|
||||
assert.equal(queries[1]?.closeCalls, 0);
|
||||
assert.equal(yield* adapter.hasSession(THREAD_ID), true);
|
||||
assert.equal(activeSessions.length, 1);
|
||||
assert.deepEqual(activeSessions[0]?.resumeCursor, secondSession.resumeCursor);
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
runtimeEvents.some((event) => event.type === "session.exited"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
|
||||
// The SDK consumes user messages via `for await (... of prompt)`.
|
||||
// Stopping a session must end that loop cleanly — not throw an error.
|
||||
|
||||
@@ -470,7 +470,10 @@ function isTodoTool(toolName: string): boolean {
|
||||
return toolName.toLowerCase().includes("todowrite");
|
||||
}
|
||||
|
||||
type PlanStep = { step: string; status: "pending" | "inProgress" | "completed" };
|
||||
type PlanStep = {
|
||||
step: string;
|
||||
status: "pending" | "inProgress" | "completed";
|
||||
};
|
||||
|
||||
function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep[] | null {
|
||||
// TodoWrite format: { todos: [{ content, status, activeForm? }] }
|
||||
@@ -973,7 +976,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
((input: {
|
||||
readonly prompt: AsyncIterable<SDKUserMessage>;
|
||||
readonly options: ClaudeQueryOptions;
|
||||
}) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
|
||||
}) =>
|
||||
query({
|
||||
prompt: input.prompt,
|
||||
options: input.options,
|
||||
}) as ClaudeQueryRuntime);
|
||||
|
||||
const sessions = new Map<ThreadId, ClaudeSessionContext>();
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
@@ -1012,7 +1019,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(typeof message.session_id === "string"
|
||||
? { providerThreadId: message.session_id }
|
||||
: {}),
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
...(context.turnState
|
||||
? {
|
||||
turnId: asCanonicalTurnId(context.turnState.turnId),
|
||||
}
|
||||
: {}),
|
||||
...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),
|
||||
payload: message,
|
||||
},
|
||||
@@ -1401,7 +1412,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? { totalProcessedTokens: accumulatedTotalProcessedTokens }
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
@@ -1465,7 +1478,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
input: tool.input,
|
||||
},
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: tool.itemId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/result",
|
||||
@@ -1587,7 +1602,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
threadId: context.session.threadId,
|
||||
turnId: context.turnState.turnId,
|
||||
...(assistantBlockEntry?.block
|
||||
? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) }
|
||||
? {
|
||||
itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),
|
||||
}
|
||||
: {}),
|
||||
payload: {
|
||||
streamKind,
|
||||
@@ -1646,7 +1663,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
...(context.turnState
|
||||
? {
|
||||
turnId: asCanonicalTurnId(context.turnState.turnId),
|
||||
}
|
||||
: {}),
|
||||
itemId: asRuntimeItemId(nextTool.itemId),
|
||||
payload: {
|
||||
itemType: nextTool.itemType,
|
||||
@@ -1658,7 +1679,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
input: nextTool.input,
|
||||
},
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }),
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: nextTool.itemId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/stream_event/content_block_delta/input_json_delta",
|
||||
@@ -1677,7 +1700,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
provider: PROVIDER,
|
||||
createdAt: planStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
...(context.turnState
|
||||
? {
|
||||
turnId: asCanonicalTurnId(context.turnState.turnId),
|
||||
}
|
||||
: {}),
|
||||
payload: {
|
||||
plan: planSteps,
|
||||
},
|
||||
@@ -1747,7 +1774,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
input: toolInput,
|
||||
},
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: tool.itemId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/stream_event/content_block_start",
|
||||
@@ -1819,7 +1848,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
data: toolData,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: tool.itemId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/user",
|
||||
@@ -1842,7 +1873,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
streamKind,
|
||||
delta: toolResult.text,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: tool.itemId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/user",
|
||||
@@ -1867,7 +1900,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
data: toolData,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: tool.itemId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/user",
|
||||
@@ -2223,7 +2258,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
payload: {
|
||||
summary: message.summary,
|
||||
...(message.preceding_tool_use_ids.length > 0
|
||||
? { precedingToolUseIds: message.preceding_tool_use_ids }
|
||||
? {
|
||||
precedingToolUseIds: message.preceding_tool_use_ids,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
@@ -2440,6 +2477,27 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const existingContext = sessions.get(input.threadId);
|
||||
if (existingContext) {
|
||||
yield* Effect.logWarning("claude.session.replacing", {
|
||||
threadId: input.threadId,
|
||||
existingSessionStatus: existingContext.session.status,
|
||||
reason: "startSession called with existing active session",
|
||||
});
|
||||
yield* stopSessionInternal(existingContext, {
|
||||
emitExitEvent: false,
|
||||
}).pipe(
|
||||
// Replacement cleanup is best-effort: never block the new session on
|
||||
// either typed failures or unexpected defects from tearing down the old one.
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("claude.session.replace.stop-failed", {
|
||||
threadId: input.threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const startedAt = yield* nowIso;
|
||||
const resumeState = readClaudeResumeState(input.resumeCursor);
|
||||
const threadId = input.threadId;
|
||||
@@ -2475,7 +2533,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
toolInput: Record<string, unknown>,
|
||||
callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
|
||||
callbackOptions: {
|
||||
readonly signal: AbortSignal;
|
||||
readonly toolUseID?: string;
|
||||
},
|
||||
) {
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
|
||||
@@ -2511,7 +2572,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
provider: PROVIDER,
|
||||
createdAt: requestedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
...(context.turnState
|
||||
? {
|
||||
turnId: asCanonicalTurnId(context.turnState.turnId),
|
||||
}
|
||||
: {}),
|
||||
requestId: asRuntimeRequestId(requestId),
|
||||
payload: { questions },
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
@@ -2520,7 +2585,10 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
raw: {
|
||||
source: "claude.sdk.permission",
|
||||
method: "canUseTool/AskUserQuestion",
|
||||
payload: { toolName: "AskUserQuestion", input: toolInput },
|
||||
payload: {
|
||||
toolName: "AskUserQuestion",
|
||||
input: toolInput,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2535,7 +2603,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
pendingUserInputs.delete(requestId);
|
||||
runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
|
||||
};
|
||||
callbackOptions.signal.addEventListener("abort", onAbort, { once: true });
|
||||
callbackOptions.signal.addEventListener("abort", onAbort, {
|
||||
once: true,
|
||||
});
|
||||
|
||||
// Block until the user provides answers.
|
||||
const answers = yield* Deferred.await(answersDeferred);
|
||||
@@ -2549,7 +2619,11 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
provider: PROVIDER,
|
||||
createdAt: resolvedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
...(context.turnState
|
||||
? {
|
||||
turnId: asCanonicalTurnId(context.turnState.turnId),
|
||||
}
|
||||
: {}),
|
||||
requestId: asRuntimeRequestId(requestId),
|
||||
payload: { answers },
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
@@ -2719,7 +2793,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
behavior: "allow",
|
||||
updatedInput: toolInput,
|
||||
...(decision === "acceptForSession" && pendingApproval.suggestions
|
||||
? { updatedPermissions: [...pendingApproval.suggestions] }
|
||||
? {
|
||||
updatedPermissions: [...pendingApproval.suggestions],
|
||||
}
|
||||
: {}),
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationManager = new FakeCodexManager();
|
||||
|
||||
@@ -654,6 +654,43 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops stale sessions in other providers after a successful replacement start", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const threadId = asThreadId("thread-provider-replacement");
|
||||
|
||||
const codexSession = yield* provider.startSession(threadId, {
|
||||
provider: "codex",
|
||||
threadId,
|
||||
cwd: "/tmp/project-provider-replacement",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
routing.codex.stopSession.mockClear();
|
||||
routing.claude.stopSession.mockClear();
|
||||
|
||||
const claudeSession = yield* provider.startSession(threadId, {
|
||||
provider: "claudeAgent",
|
||||
threadId,
|
||||
cwd: "/tmp/project-provider-replacement",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(codexSession.provider, "codex");
|
||||
assert.equal(claudeSession.provider, "claudeAgent");
|
||||
assert.deepEqual(routing.codex.stopSession.mock.calls, [[threadId]]);
|
||||
assert.equal(routing.claude.stopSession.mock.calls.length, 0);
|
||||
|
||||
const sessions = yield* provider.listSessions();
|
||||
assert.deepEqual(
|
||||
sessions
|
||||
.filter((session) => session.threadId === threadId)
|
||||
.map((session) => session.provider),
|
||||
["claudeAgent"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
@@ -297,6 +297,40 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
|
||||
});
|
||||
|
||||
const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly currentProvider: ProviderSession["provider"];
|
||||
}) {
|
||||
yield* Effect.forEach(
|
||||
adapters,
|
||||
(adapter) =>
|
||||
adapter.provider === input.currentProvider
|
||||
? Effect.void
|
||||
: Effect.gen(function* () {
|
||||
const hasSession = yield* adapter.hasSession(input.threadId);
|
||||
if (!hasSession) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* adapter.stopSession(input.threadId).pipe(
|
||||
Effect.tap(() =>
|
||||
analytics.record("provider.session.stopped", {
|
||||
provider: adapter.provider,
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider.session.stop-stale-failed", {
|
||||
threadId: input.threadId,
|
||||
provider: adapter.provider,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
|
||||
function* (threadId, rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
@@ -351,6 +385,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
}
|
||||
|
||||
yield* stopStaleSessionsForThread({
|
||||
threadId,
|
||||
currentProvider: adapter.provider,
|
||||
});
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
@@ -133,6 +133,78 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}
|
||||
}));
|
||||
|
||||
it("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
const olderThreadId = ThreadId.make("thread-runtime-older");
|
||||
const newerThreadId = ThreadId.make("thread-runtime-newer");
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId: newerThreadId,
|
||||
providerName: "codex",
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T12:05:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-newer",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/newer",
|
||||
},
|
||||
});
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId: olderThreadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
status: "starting",
|
||||
lastSeenAt: "2026-04-14T12:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-older",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/older",
|
||||
},
|
||||
});
|
||||
|
||||
const bindings = yield* directory.listBindings();
|
||||
|
||||
assert.deepEqual(bindings, [
|
||||
{
|
||||
threadId: olderThreadId,
|
||||
provider: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
status: "starting",
|
||||
lastSeenAt: "2026-04-14T12:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-older",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/older",
|
||||
},
|
||||
},
|
||||
{
|
||||
threadId: newerThreadId,
|
||||
provider: "codex",
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T12:05:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-newer",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/newer",
|
||||
},
|
||||
},
|
||||
]);
|
||||
}));
|
||||
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderRuntimeBinding,
|
||||
type ProviderRuntimeBindingWithMetadata,
|
||||
type ProviderSessionDirectoryShape,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
|
||||
@@ -50,6 +52,27 @@ function mergeRuntimePayload(
|
||||
return next;
|
||||
}
|
||||
|
||||
function toRuntimeBinding(
|
||||
runtime: ProviderSessionRuntime,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderKind(runtime.providerName, operation).pipe(
|
||||
Effect.map(
|
||||
(provider) =>
|
||||
({
|
||||
threadId: runtime.threadId,
|
||||
provider,
|
||||
adapterKey: runtime.adapterKey,
|
||||
runtimeMode: runtime.runtimeMode,
|
||||
status: runtime.status,
|
||||
resumeCursor: runtime.resumeCursor,
|
||||
runtimePayload: runtime.runtimePayload,
|
||||
lastSeenAt: runtime.lastSeenAt,
|
||||
}) satisfies ProviderRuntimeBindingWithMetadata,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
@@ -60,18 +83,8 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onSome: (value) =>
|
||||
decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map((provider) =>
|
||||
Option.some({
|
||||
threadId: value.threadId,
|
||||
provider,
|
||||
adapterKey: value.adapterKey,
|
||||
runtimeMode: value.runtimeMode,
|
||||
status: value.status,
|
||||
resumeCursor: value.resumeCursor,
|
||||
runtimePayload: value.runtimePayload,
|
||||
}),
|
||||
),
|
||||
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map((binding) => Option.some(binding)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
@@ -145,12 +158,25 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
Effect.map((rows) => rows.map((row) => row.threadId)),
|
||||
);
|
||||
|
||||
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
remove,
|
||||
listThreadIds,
|
||||
listBindings,
|
||||
} satisfies ProviderSessionDirectoryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
|
||||
|
||||
const defaultModelSelection = {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
} as const;
|
||||
|
||||
async function waitFor(
|
||||
predicate: () => boolean | Promise<boolean>,
|
||||
timeoutMs = 2_000,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (await predicate()) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for expectation.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return poll();
|
||||
};
|
||||
|
||||
return poll();
|
||||
}
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
|
||||
function makeReadModel(
|
||||
threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
readonly session: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
|
||||
readonly providerName: "codex" | "claudeAgent";
|
||||
readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
|
||||
readonly activeTurnId: TurnId | null;
|
||||
readonly lastError: string | null;
|
||||
readonly updatedAt: string;
|
||||
} | null;
|
||||
}>,
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
const projectId = ProjectId.make("project-provider-session-reaper");
|
||||
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
{
|
||||
id: projectId,
|
||||
title: "Provider Reaper Project",
|
||||
workspaceRoot: "/tmp/provider-reaper-project",
|
||||
defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId,
|
||||
title: `Thread ${thread.id}`,
|
||||
modelSelection: defaultModelSelection,
|
||||
interactionMode: "default" as const,
|
||||
runtimeMode: "full-access" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: thread.session,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderSessionReaper", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
ProviderSessionReaper | ProviderSessionRuntimeRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
scope = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
async function createHarness(input: {
|
||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||
readonly stopSessionImplementation?: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||
}) {
|
||||
const stoppedThreadIds = new Set<ThreadId>();
|
||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||
(request) =>
|
||||
(input.stopSessionImplementation
|
||||
? input.stopSessionImplementation(request)
|
||||
: Effect.sync(() => {
|
||||
stoppedThreadIds.add(request.threadId);
|
||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||
);
|
||||
|
||||
const providerService: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession,
|
||||
listSessions: () => Effect.succeed([]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const orchestrationEngine: OrchestrationEngineShape = {
|
||||
getReadModel: () => Effect.succeed(input.readModel),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => unsupported(),
|
||||
streamDomainEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const layer = makeProviderSessionReaperLive({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}).pipe(
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
return { stopSession, stoppedThreadIds };
|
||||
}
|
||||
|
||||
it("reaps stale persisted sessions without active turns", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-stale");
|
||||
const now = new Date().toISOString();
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-stale",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
|
||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
|
||||
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips stale sessions when the thread still has an active turn", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-active-turn");
|
||||
const turnId = TurnId.make("turn-reaper-active");
|
||||
const now = new Date().toISOString();
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-active-turn",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not reap sessions that are still within the inactivity threshold", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-fresh");
|
||||
const now = new Date().toISOString();
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor: {
|
||||
opaque: "resume-fresh",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips persisted sessions that are already marked stopped", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-stopped");
|
||||
const now = new Date().toISOString();
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "stopped",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-stopped",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it("continues reaping other sessions when one stop attempt fails", async () => {
|
||||
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
|
||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
|
||||
const now = new Date().toISOString();
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: failedThreadId,
|
||||
session: {
|
||||
threadId: failedThreadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: reapedThreadId,
|
||||
session: {
|
||||
threadId: reapedThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
stopSessionImplementation: (request) =>
|
||||
request.threadId === failedThreadId
|
||||
? Effect.fail(
|
||||
new ProviderValidationError({
|
||||
operation: "ProviderSessionReaper.test",
|
||||
issue: "simulated stop failure",
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: failedThreadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-failure",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-success",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
||||
failedThreadId,
|
||||
reapedThreadId,
|
||||
]);
|
||||
});
|
||||
|
||||
it("continues reaping other sessions when one stop attempt defects", async () => {
|
||||
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
|
||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
|
||||
const now = new Date().toISOString();
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: defectThreadId,
|
||||
session: {
|
||||
threadId: defectThreadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: reapedThreadId,
|
||||
session: {
|
||||
threadId: reapedThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
stopSessionImplementation: (request) =>
|
||||
request.threadId === defectThreadId
|
||||
? Effect.die(new Error("simulated stop defect"))
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository));
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: defectThreadId,
|
||||
providerName: "claudeAgent",
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-defect",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-after-defect",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
||||
defectThreadId,
|
||||
reapedThreadId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { Duration, Effect, Layer, Schedule } from "effect";
|
||||
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
type ProviderSessionReaperShape,
|
||||
} from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService } from "../Services/ProviderService.ts";
|
||||
|
||||
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
|
||||
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface ProviderSessionReaperLiveOptions {
|
||||
readonly inactivityThresholdMs?: number;
|
||||
readonly sweepIntervalMs?: number;
|
||||
}
|
||||
|
||||
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
|
||||
);
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
|
||||
const sweep = Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
|
||||
const bindings = yield* directory.listBindings();
|
||||
const now = Date.now();
|
||||
let reapedCount = 0;
|
||||
|
||||
for (const binding of bindings) {
|
||||
if (binding.status === "stopped") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const lastSeenMs = Date.parse(binding.lastSeenAt);
|
||||
if (Number.isNaN(lastSeenMs)) {
|
||||
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
lastSeenAt: binding.lastSeenAt,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const idleDurationMs = now - lastSeenMs;
|
||||
if (idleDurationMs < inactivityThresholdMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const thread = threadsById.get(binding.threadId);
|
||||
if (thread?.session?.activeTurnId != null) {
|
||||
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
|
||||
threadId: binding.threadId,
|
||||
activeTurnId: thread.session.activeTurnId,
|
||||
idleDurationMs,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.logInfo("provider.session.reaped", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
idleDurationMs,
|
||||
reason: "inactivity_threshold",
|
||||
}),
|
||||
),
|
||||
Effect.as(true),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider.session.reaper.stop-failed", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
idleDurationMs,
|
||||
cause,
|
||||
}).pipe(Effect.as(false)),
|
||||
),
|
||||
);
|
||||
|
||||
if (reaped) {
|
||||
reapedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (reapedCount > 0) {
|
||||
yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
|
||||
reapedCount,
|
||||
totalBindings: bindings.length,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const start: ProviderSessionReaperShape["start"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
sweep.pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-failed", {
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.catchDefect((defect: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-defect", {
|
||||
defect,
|
||||
}),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.logInfo("provider.session.reaper.started", {
|
||||
inactivityThresholdMs,
|
||||
sweepIntervalMs,
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies ProviderSessionReaperShape;
|
||||
});
|
||||
|
||||
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
|
||||
|
||||
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
|
||||
@@ -22,6 +22,10 @@ export interface ProviderRuntimeBinding {
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
|
||||
readonly lastSeenAt: string;
|
||||
}
|
||||
|
||||
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
@@ -49,6 +53,11 @@ export interface ProviderSessionDirectoryShape {
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
|
||||
readonly listBindings: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
|
||||
export class ProviderSessionDirectory extends Context.Service<
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
export interface ProviderSessionReaperShape {
|
||||
/**
|
||||
* Start the background provider session reaper within the provided scope.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ProviderSessionReaper extends Context.Service<
|
||||
ProviderSessionReaper,
|
||||
ProviderSessionReaperShape
|
||||
>()("t3/provider/Services/ProviderSessionReaper") {}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
KeybindingRule,
|
||||
MessageId,
|
||||
OpenError,
|
||||
type OrchestrationThreadShell,
|
||||
TerminalNotRunningError,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
@@ -166,6 +167,32 @@ const makeDefaultOrchestrationReadModel = () => {
|
||||
};
|
||||
};
|
||||
|
||||
const makeDefaultOrchestrationThreadShell = (
|
||||
overrides: Partial<OrchestrationThreadShell> = {},
|
||||
): OrchestrationThreadShell => {
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
id: defaultThreadId,
|
||||
projectId: defaultProjectId,
|
||||
title: "Default Thread",
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
};
|
||||
|
||||
const workspaceAndProjectServicesLayer = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
|
||||
@@ -2945,21 +2972,48 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("closes thread terminals after a successful archive command", () =>
|
||||
it.effect("stops the provider session and closes thread terminals after archive", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive");
|
||||
const closeInputs: Array<Parameters<TerminalManagerShape["close"]>[0]> = [];
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
closeInputs.push(input);
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: () => Effect.succeed({ sequence: 8 }),
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2975,8 +3029,363 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 8);
|
||||
assert.deepEqual(closeInputs, [{ threadId }]);
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
const sessionStopCommand = dispatchedCommands[1];
|
||||
assert.equal(sessionStopCommand?.type, "thread.session.stop");
|
||||
if (sessionStopCommand?.type === "thread.session.stop") {
|
||||
assert.equal(sessionStopCommand.threadId, threadId);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("checks session status before archiving removes the thread from active lookups", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-precheck");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
let archived = false;
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
if (command.type === "thread.archive") {
|
||||
archived = true;
|
||||
}
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`query:thread-shell:${archived ? "archived" : "active"}`);
|
||||
return archived
|
||||
? Option.none()
|
||||
: Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-precheck"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"query:thread-shell:active",
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive", "thread.session.stop"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("archives without dispatching session stop when the thread has no session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-no-session");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-no-session"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"archives without dispatching session stop when the thread session is already stopped",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-stopped-session");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) =>
|
||||
Effect.sync(() => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
return { sequence: dispatchedCommands.length };
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-stopped-session"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("archives and still closes terminals when session stop fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-stop-failure");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
if (command.type === "thread.session.stop") {
|
||||
return Effect.fail(
|
||||
new OrchestrationListenerCallbackError({
|
||||
listener: "domain-event",
|
||||
detail: "simulated archive stop failure",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed({ sequence: dispatchedCommands.length });
|
||||
},
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-stop-failure"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive", "thread.session.stop"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("archives and still closes terminals when session stop defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-archive-stop-defect");
|
||||
const effects: string[] = [];
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
terminalManager: {
|
||||
close: (input) =>
|
||||
Effect.sync(() => {
|
||||
effects.push(`terminal.close:${input.threadId}`);
|
||||
}),
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: (command) => {
|
||||
dispatchedCommands.push(command);
|
||||
effects.push(`dispatch:${command.type}`);
|
||||
if (command.type === "thread.session.stop") {
|
||||
return Effect.die(new Error("simulated archive stop defect"));
|
||||
}
|
||||
return Effect.succeed({ sequence: dispatchedCommands.length });
|
||||
},
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadShellById: () =>
|
||||
Effect.succeed(
|
||||
Option.some(
|
||||
makeDefaultOrchestrationThreadShell({
|
||||
id: threadId,
|
||||
updatedAt: now,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const dispatchResult = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-stop-defect"),
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(dispatchResult.sequence, 1);
|
||||
assert.deepEqual(effects, [
|
||||
"dispatch:thread.archive",
|
||||
"dispatch:thread.session.stop",
|
||||
`terminal.close:${threadId}`,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
dispatchedCommands.map((command) => command.type),
|
||||
["thread.archive", "thread.session.stop"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
@@ -134,6 +135,10 @@ const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
|
||||
const ProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
@@ -143,9 +148,6 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
@@ -155,11 +157,14 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||
).pipe(
|
||||
Layer.provide(adapterRegistryLayer),
|
||||
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -194,12 +199,16 @@ const AuthLayerLive = ServerAuthLive.pipe(
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
);
|
||||
|
||||
const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
);
|
||||
|
||||
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(ProviderRuntimeLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(KeybindingsLive),
|
||||
|
||||
@@ -32,6 +32,7 @@ import { ServerSettingsService } from "./serverSettings";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth";
|
||||
import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper";
|
||||
import {
|
||||
formatHeadlessServeOutput,
|
||||
formatHostForUrl,
|
||||
@@ -281,6 +282,7 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const keybindings = yield* Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor;
|
||||
const providerSessionReaper = yield* ProviderSessionReaper;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverEnvironment = yield* ServerEnvironment;
|
||||
@@ -325,7 +327,10 @@ export const makeServerRuntimeStartup = Effect.gen(function* () {
|
||||
yield* Effect.logDebug("startup phase: starting orchestration reactors");
|
||||
yield* runStartupPhase(
|
||||
"reactors.start",
|
||||
orchestrationReactor.start().pipe(Scope.provide(reactorScope)),
|
||||
Effect.gen(function* () {
|
||||
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
|
||||
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
|
||||
}),
|
||||
);
|
||||
|
||||
const welcomeBase = yield* resolveWelcomeBase;
|
||||
|
||||
@@ -550,8 +550,45 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
Effect.gen(function* () {
|
||||
const normalizedCommand = yield* normalizeDispatchCommand(command);
|
||||
const shouldStopSessionAfterArchive =
|
||||
normalizedCommand.type === "thread.archive"
|
||||
? yield* projectionSnapshotQuery
|
||||
.getThreadShellById(normalizedCommand.threadId)
|
||||
.pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => false,
|
||||
onSome: (thread) =>
|
||||
thread.session !== null && thread.session.status !== "stopped",
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
)
|
||||
: false;
|
||||
const result = yield* dispatchNormalizedCommand(normalizedCommand);
|
||||
if (normalizedCommand.type === "thread.archive") {
|
||||
if (shouldStopSessionAfterArchive) {
|
||||
yield* Effect.gen(function* () {
|
||||
const stopCommand = yield* normalizeDispatchCommand({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.make(
|
||||
`session-stop-for-archive:${normalizedCommand.commandId}`,
|
||||
),
|
||||
threadId: normalizedCommand.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
yield* dispatchNormalizedCommand(stopCommand);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to stop provider session during archive", {
|
||||
threadId: normalizedCommand.threadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to close thread terminals after archive", {
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"typecheck": "turbo run typecheck",
|
||||
"lint": "oxlint --report-unused-disable-directives",
|
||||
"test": "turbo run test",
|
||||
"test:process-reaper": "bun run --cwd apps/server test:process-reaper",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"fmt:check": "oxfmt --check",
|
||||
|
||||
Reference in new issue
Block a user