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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 202 additions & 1 deletion apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,13 @@ it.each([
function makeLocalCommandHarness(input: {
readonly text: string;
readonly manualContinuation?: boolean;
readonly restartContinuation?: {
readonly canResumeAfterRestart: boolean;
/** The newest accepted turn on the native session was rolled back, and the agent cannot truncate. */
readonly lacksKeptTurns?: boolean;
/** The cut run only left a restart note to deliver (cancelled background work), no cut turn. */
readonly noteOnly?: boolean;
};
readonly nativeResumeUnsupported?: boolean;
readonly steeringRestart?: boolean;
readonly nativeGoals?: boolean;
Expand Down Expand Up @@ -558,6 +565,7 @@ function makeLocalCommandHarness(input: {
const messageId = MessageId.make("message-native-account-command");
const run: OrchestrationV2ThreadProjection["runs"][number] = {
...(input.manualContinuation ? { manualContinuationOfRunId: RunId.make("stopped-run") } : {}),
...(input.restartContinuation ? { restartContinuationOfRunId: RunId.make("cut-run") } : {}),
id: runId,
threadId,
ordinal: 2,
Expand Down Expand Up @@ -990,6 +998,77 @@ function makeLocalCommandHarness(input: {
),
};
}
if (input.restartContinuation?.lacksKeptTurns === true) {
const keptAttemptId = RunAttemptId.make("kept-attempt");
const rolledBackAttemptId = RunAttemptId.make("rolled-back-attempt");
const priorRun = (
id: string,
ordinal: number,
status: "completed" | "rolled_back",
attempt: RunAttemptId,
) => ({
...run,
id: RunId.make(id),
ordinal,
status,
activeAttemptId: attempt,
providerThreadId,
});
const priorAttempt = (id: RunAttemptId, runIdValue: string) => ({
...projection.attempts[0]!,
id,
runId: RunId.make(runIdValue),
providerThreadId,
status: "completed" as const,
});
const priorTurn = (id: string, attempt: RunAttemptId, ordinal: number) => ({
id: ProviderTurnId.make(id),
providerThreadId,
nodeId: rootNodeId,
runAttemptId: attempt,
ordinal,
nativeTurnRef: null,
status: "completed" as const,
startedAt: now,
completedAt: now,
});
projection = {
...projection,
runs: [
priorRun("kept-run", 0, "completed", keptAttemptId),
priorRun("rolled-back-run", 1, "rolled_back", rolledBackAttemptId),
...projection.runs,
],
attempts: [
priorAttempt(keptAttemptId, "kept-run"),
priorAttempt(rolledBackAttemptId, "rolled-back-run"),
...projection.attempts,
],
providerTurns: [
...projection.providerTurns,
priorTurn("kept-turn", keptAttemptId, 0),
priorTurn("rolled-back-turn", rolledBackAttemptId, 1),
],
};
}
if (input.restartContinuation?.noteOnly === true) {
projection = {
...projection,
runs: [
{
...run,
id: RunId.make("cut-run"),
ordinal: 1,
status: "completed" as const,
providerThreadId,
restartCancelledBackgroundWork: [
{ kind: "shell" as const, label: "sleep 25", awaited: true as const },
],
},
...projection.runs,
],
};
}
const earlierRunId = RunId.make("earlier-native-run");
const roleText =
"You are the inbox. Reply only 'Queued for Jarvis: <summary>' and never use tools.";
Expand Down Expand Up @@ -1218,6 +1297,7 @@ function makeLocalCommandHarness(input: {
const resumeFallbackSession = {
driver: providerThread.driver,
providerSession,
canResumeAfterRestart: input.restartContinuation?.canResumeAfterRestart,
resumeThread: () =>
Effect.fail(
input.resumeFailure ??
Expand Down Expand Up @@ -1265,7 +1345,22 @@ function makeLocalCommandHarness(input: {
: input.interruptOpen === true
? Effect.interrupt
: "historyReadFailureAfterFallback" in input || "resumeFailure" in input
? Effect.succeed({ ...resumeFallbackSession, providerSession } as never)
? Effect.succeed({
...resumeFallbackSession,
providerSession:
input.restartContinuation?.lacksKeptTurns === true
? {
...providerSession,
capabilities: {
...providerSession.capabilities,
checkpointing: {
...providerSession.capabilities.checkpointing,
providerCanRollbackConversation: false,
},
},
}
: providerSession,
} as never)
: "ensureThreadFailure" in input
? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)
: "openFailure" in input
Expand Down Expand Up @@ -3670,6 +3765,112 @@ effectIt.effect.each(["previous", "current", "previous-failover"] as const)(
}),
);

for (const canResumeAfterRestart of [true, false]) {
effectIt.effect(
`${canResumeAfterRestart ? "fails" : "falls back for"} a restart continuation whose agent ${canResumeAfterRestart ? "can" : "cannot"} reload sessions`,
() =>
Effect.gen(function* () {
const harness = makeLocalCommandHarness({
text: "Continue",
restartContinuation: { canResumeAfterRestart },
resumeFailure: new ProviderAdapter.ProviderAdapterResumeThreadError({
driver: ProviderDriverKind.make("acp"),
providerSessionId: ProviderSessionId.make("new-provider-session"),
providerThreadId: ProviderThreadId.make("new-provider-thread"),
cause: new Error("Internal error"),
}),
});

yield* Effect.exit(harness.start);

if (!canResumeAfterRestart) {
expect(harness.fallbackEnsureThread).toHaveBeenCalledOnce();
return;
}
expect(harness.fallbackEnsureThread).not.toHaveBeenCalled();
expect(harness.startRootRun).not.toHaveBeenCalled();
expect(harness.projection().runs.at(-1)).toMatchObject({ status: "failed" });
expect(harness.projection().turnItems).toMatchObject([
{
type: "error",
failure: {
message:
"The agent could not reopen this conversation after the restart, and its last turn may still be running there. Send a message to continue in a new session.",
},
},
]);
}),
);
}

effectIt.effect(
"falls back for a restart continuation whose native session lost the kept turns",
() =>
Effect.gen(function* () {
const harness = makeLocalCommandHarness({
text: "Continue",
restartContinuation: { canResumeAfterRestart: true, lacksKeptTurns: true },
resumeFailure: new ProviderAdapter.ProviderAdapterResumeThreadError({
driver: ProviderDriverKind.make("acp"),
providerSessionId: ProviderSessionId.make("new-provider-session"),
providerThreadId: ProviderThreadId.make("new-provider-thread"),
cause: new Error("Internal error"),
}),
});

yield* Effect.exit(harness.start);

expect(harness.fallbackEnsureThread).toHaveBeenCalledOnce();
}),
);

effectIt.effect("falls back for a restart continuation that only delivers a restart note", () =>
Effect.gen(function* () {
const harness = makeLocalCommandHarness({
text: "Continue",
restartContinuation: { canResumeAfterRestart: true, noteOnly: true },
resumeFailure: new ProviderAdapter.ProviderAdapterResumeThreadError({
driver: ProviderDriverKind.make("acp"),
providerSessionId: ProviderSessionId.make("new-provider-session"),
providerThreadId: ProviderThreadId.make("new-provider-thread"),
cause: new Error("Internal error"),
}),
});

yield* Effect.exit(harness.start);

expect(harness.fallbackEnsureThread).toHaveBeenCalledOnce();
}),
);

effectIt.effect("keeps an actionable resume refusal for a restart continuation", () =>
Effect.gen(function* () {
const refusal = Object.assign(
new Error(
'The agent did not accept the model "gone". Choose another model for this provider, then retry.',
),
{ _tag: "AcpModelSelectionError" },
);
const harness = makeLocalCommandHarness({
text: "Continue",
restartContinuation: { canResumeAfterRestart: true },
resumeFailure: new ProviderAdapter.ProviderAdapterResumeThreadError({
driver: ProviderDriverKind.make("acp"),
providerSessionId: ProviderSessionId.make("new-provider-session"),
providerThreadId: ProviderThreadId.make("new-provider-thread"),
cause: refusal,
}),
});

yield* Effect.exit(harness.start);

expect(harness.fallbackEnsureThread).not.toHaveBeenCalled();
expect(harness.projection().turnItems).toMatchObject([
{ type: "error", failure: { message: refusal.message } },
]);
}),
);

effectIt.effect("does not mistake a failed state read for a superseded run", () =>
Effect.gen(function* () {
const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true });
Expand Down
34 changes: 33 additions & 1 deletion apps/server/src/orchestration-v2/ProviderTurnStartService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ const RESUME_PROMPT = "Continue where you left off.";
const START_GAVE_UP_MESSAGE =
"T3 Code could not start this turn. Send the message again; if it keeps failing, check the server logs.";

const RESTART_RESUME_FAILED_MESSAGE =
"The agent could not reopen this conversation after the restart, and its last turn may still be running there. Send a message to continue in a new session.";

const startFailureMessage = (error: Error): string => {
const nestedCause = "cause" in error ? error.cause : undefined;
return (
Expand Down Expand Up @@ -1946,8 +1949,13 @@ export const layer: Layer.Layer<
handoff.toProviderThreadId === providerThread.id &&
handoff.strategy === "manual_context",
);
const resumeAttempted = !(
uncertainDelivery ||
nativeSessionLacksKeptTurns ||
rejectedHistory
);
const resumed = yield* Effect.result(
uncertainDelivery || nativeSessionLacksKeptTurns || rejectedHistory
!resumeAttempted
? Effect.fail(
new ProviderAdapter.ProviderAdapterTurnStartError({
driver: session.driver,
Expand Down Expand Up @@ -2017,6 +2025,30 @@ export const layer: Layer.Layer<
) {
return yield* loadFromProvider(Effect.fail(resumed.failure));
}
// ACP agents that restore sessions can outlive a backend restart, and their load errors
// cannot tell busy from gone. A fresh session could repeat the cut turn beside it.
if (
resumed._tag === "Failure" &&
resumeAttempted &&
run.restartContinuationOfRunId !== undefined &&
!noteContinuation &&
session.canResumeAfterRestart === true
Comment thread
chrisohearn marked this conversation as resolved.
Resolved
Comment thread
chrisohearn marked this conversation as resolved.
Resolved
) {
// An actionable refusal, such as a model the agent no longer accepts, keeps its own remedy.
if (knownProviderFailureMessage(resumed.failure) !== undefined) {
return yield* loadFromProvider(Effect.fail(resumed.failure));
}
return yield* loadFromProvider(
Effect.fail(
new ProviderAdapter.ProviderAdapterThreadInUseError({
driver: session.driver,
providerThreadId: providerThread.id,
detail: RESTART_RESUME_FAILED_MESSAGE,
Comment thread
chrisohearn marked this conversation as resolved.
Resolved
cause: resumed.failure,
}),
),
);
}

yield* Effect.logWarning("Recovering provider context in a fresh native session", {
driver: session.driver,
Expand Down
Loading