This commit is contained in:
Julius Marminge committed 2026-08-14 11:22:49 +02:00
1 parent 90d0f40790
commit 7c0d40fefe
14 files changed
+1297 -1059

No files matched your search

@@ -155,7 +155,7 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
timeoutMs = 30_000,
timeoutMs = 15_000,
) {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async (): Promise<{
@@ -180,7 +180,7 @@ async function waitForThread(
async function waitForEvent(
engine: OrchestrationEngineShape,
predicate: (event: { type: string }) => boolean,
timeoutMs = 30_000,
timeoutMs = 15_000,
) {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async () => {
@@ -231,7 +231,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 30_000) {
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
@@ -247,9 +247,6 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 30_000)
}
describe("CheckpointReactor", () => {
const LONG_TEST_TIMEOUT_MS = 30_000;
const test = (name: string, run: () => Promise<void>, timeout = LONG_TEST_TIMEOUT_MS) =>
it(name, run, timeout);
let runtime: ManagedRuntime.ManagedRuntime<
| OrchestrationEngineService
| CheckpointReactor
@@ -456,7 +453,7 @@ describe("CheckpointReactor", () => {
};
}
test("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -706,7 +703,7 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
test("captures pre-turn and completion checkpoints for claude runtime events", async () => {
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: ProviderDriverKind.make("claudeAgent"),
@@ -767,7 +764,7 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
test("appends capture failure activity when turn diff summary cannot be derived", async () => {
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -814,7 +811,7 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
test("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
it("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
const harness = await createHarness({
hasSession: false,
seedFilesystemCheckpoints: false,
@@ -851,7 +848,7 @@ describe("CheckpointReactor", () => {
).toBe("v1\n");
});
test("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
it("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
const harness = await createHarness({
hasSession: false,
seedFilesystemCheckpoints: false,
@@ -902,7 +899,7 @@ describe("CheckpointReactor", () => {
).toBe("v2\n");
});
test("ignores non-v2 checkpoint.captured runtime events", async () => {
it("ignores non-v2 checkpoint.captured runtime events", async () => {
const harness = await createHarness();
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -944,7 +941,7 @@ describe("CheckpointReactor", () => {
);
});
test("continues processing runtime events after a single checkpoint runtime failure", async () => {
it("continues processing runtime events after a single checkpoint runtime failure", async () => {
const nonRepositorySessionCwd = fs.mkdtempSync(
path.join(os.tmpdir(), "t3-checkpoint-runtime-non-repo-"),
);
@@ -1004,7 +1001,7 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
test("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
const harness = await createHarness();
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -1085,7 +1082,7 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
test("executes provider revert and emits thread.reverted for claude sessions", async () => {
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
@@ -1154,7 +1151,7 @@ describe("CheckpointReactor", () => {
});
});
test("processes consecutive revert requests with deterministic rollback sequencing", async () => {
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -1237,7 +1234,7 @@ describe("CheckpointReactor", () => {
});
});
test("appends an error activity when revert is requested without an active session", async () => {
it("appends an error activity when revert is requested without an active session", async () => {
const harness = await createHarness({ hasSession: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -21,7 +21,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Deferred, Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
@@ -544,59 +544,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("records session lastError and clears active turn when provider turn start fails", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.sendTurn.mockImplementation(
() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "cursor",
method: "session/set_config_option",
detail: 'Invalid value for session config option "model"',
}),
) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-session-error"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-session-error"),
role: "user",
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.session?.lastError ===
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"' &&
thread?.session?.status === "ready" &&
thread?.session?.activeTurnId === null
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).toMatchObject({
status: "ready",
activeTurnId: null,
lastError:
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"',
});
});
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2047,63 +1994,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("switches cursor model in-session without restarting", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "cursor", model: "composer-2" },
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-cursor-model-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-1"),
role: "user",
text: "first cursor turn",
attachments: [],
},
modelSelection: { provider: "cursor", model: "composer-2" },
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-cursor-model-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-2"),
role: "user",
text: "second cursor turn",
attachments: [],
},
modelSelection: {
provider: "cursor",
model: "composer-2",
options: { fastMode: true },
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2478,30 +2368,37 @@ describe("ProviderCommandReactor", () => {
});
});
it("preserves provider method context when turn start fails", async () => {
it("starts a fresh session when only projected session state exists", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.sendTurn.mockImplementation(
() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "cursor",
method: "session/set_config_option",
detail: "Invalid cursor/set_config_option payload: Expected string, got null",
}),
) as never,
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-stale"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-error"),
commandId: CommandId.make("cmd-turn-start-stale"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-provider-error"),
messageId: asMessageId("user-message-stale"),
role: "user",
text: "hello",
text: "resume codex",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -2510,73 +2407,19 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining(
"Provider adapter request failed (cursor) for session/set_config_option",
),
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
});
});
it("keeps the full rendered cause for non-adapter turn start failures", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.sendTurn.mockImplementation(
() =>
Effect.fail(
new Error("Invalid params", { cause: new Error("session/prompt failed") }),
) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-raw-error"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-raw-error"),
role: "user",
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("session/prompt failed"),
},
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
});
});
@@ -2692,60 +2535,6 @@ describe("ProviderCommandReactor", () => {
});
});
it("processes approval responses while a provider turn is still in flight", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const unblockSendTurn = Effect.runSync(Deferred.make<void>());
harness.sendTurn.mockImplementation(() =>
Deferred.await(unblockSendTurn).pipe(
Effect.as({
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-1"),
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-blocked-approval"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-blocked-approval"),
role: "user",
text: "need approval while turn is running",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-approval-respond-during-send-turn"),
threadId: ThreadId.make("thread-1"),
requestId: asApprovalRequestId("approval-request-while-send-turn-blocked"),
decision: "acceptForSession",
createdAt: now,
}),
);
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
requestId: "approval-request-while-send-turn-blocked",
decision: "acceptForSession",
});
await Effect.runPromise(Deferred.succeed(unblockSendTurn, undefined));
});
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -248,7 +248,7 @@ function findProviderAdapterRequestError(
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
if (error) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending approval request") ||
@@ -264,7 +264,7 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
if (error) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
const message = Cause.pretty(cause).toLowerCase();
@@ -379,7 +379,7 @@ const make = Effect.gen(function* () {
? failReason.error
: undefined;
if (providerError) {
return providerError.message;
return providerError.detail;
}
return Cause.pretty(cause);
};
@@ -659,9 +659,6 @@ const make = Effect.gen(function* () {
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
@@ -681,14 +678,15 @@ const make = Effect.gen(function* () {
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
return existingSessionThreadId;
}
const resumeCursor = providerChanged ? undefined : (activeSession?.resumeCursor ?? undefined);
const resumeCursor = shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
@@ -699,7 +697,6 @@ const make = Effect.gen(function* () {
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
providerChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
@@ -1120,6 +1117,9 @@ const make = Effect.gen(function* () {
}
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
@@ -1136,9 +1136,22 @@ const make = Effect.gen(function* () {
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(recoveryCause),
originalCause: Cause.pretty(cause),
}),
),
);
const sendTurnRequest = yield* buildSendTurnRequestForThread({
threadId: event.payload.threadId,
messageText: message.text,
@@ -1159,7 +1172,7 @@ const make = Effect.gen(function* () {
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(handleTurnStartFailure), Effect.forkScoped);
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (