GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): resend a Cursor request a restart cut off before its fir… · patroza/t3code@2313dfa

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/orchestration-v2
    • ProviderTurnStartService.ts
    • testkit
      • ProviderSwitch.integration.test.ts
  • packages
    • provider-core/src/server
      • ProviderAdapter.ts
    • provider-cursor/src/server
      • adapter.test.ts
      • adapter.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+115-6Lines changed: 115 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,46 @@ export function abandonedProviderTurns(
151151
});
152152
}
153153

154+
const CUT_TURN_SETTLED = "cut-turn-settled";
155+
156+
/**
157+
* The previous run's cancelled turn when no adapter said whether it kept the request. A Stop
158+
* settles that as the turn ends; a restart cancels the turn with no adapter left to tell.
159+
*/
160+
function unsettledCancelledProviderTurn(
161+
projection: Pick<OrchestrationV2ThreadProjection, "runs" | "providerTurns">,
162+
run: Pick<OrchestrationV2Run, "ordinal">,
163+
providerThread: Pick<OrchestrationV2ProviderThread, "id" | "nativeThreadRef">,
164+
) {
165+
const previous = projection.runs.reduce<OrchestrationV2Run | undefined>(
166+
(latest, candidate) =>
167+
candidate.ordinal < run.ordinal &&
168+
candidate.providerThreadId === providerThread.id &&
169+
candidate.startedAt !== null &&
170+
(latest === undefined || candidate.ordinal > latest.ordinal)
171+
? candidate
172+
: latest,
173+
undefined,
174+
);
175+
if (previous?.status !== "cancelled" || previous.activeAttemptId === null) return undefined;
176+
const turn = projection.providerTurns.findLast(
177+
(candidate) =>
178+
candidate.runAttemptId === previous.activeAttemptId &&
179+
candidate.providerThreadId === providerThread.id,
180+
);
181+
const nativeTurnId = turn?.nativeTurnRef?.nativeId;
182+
if (
183+
turn === undefined ||
184+
nativeTurnId == null ||
185+
turn.status !== "cancelled" ||
186+
turn.promptDropped === true ||
187+
(turn.nativeThreadRef !== undefined &&
188+
turn.nativeThreadRef.nativeId !== providerThread.nativeThreadRef?.nativeId)
189+
)
190+
return undefined;
191+
return { run: previous, turn, nativeTurnId };
192+
}
193+
154194
export const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
155195
const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);
156196
const isProviderAdapterTurnStartError = Schema.is(ProviderAdapter.ProviderAdapterTurnStartError);
@@ -1063,6 +1103,70 @@ export const layer: Layer.Layer<
10631103
}
10641104
const session = sessionResult.success;
10651105
if (!(yield* isCurrentAttemptInStatus("starting"))) return;
1106+
const cutTurn = unsettledCancelledProviderTurn(projection, run, providerThread);
1107+
if (
1108+
cutTurn !== undefined &&
1109+
session.nativeTurnKept !== undefined &&
1110+
!(yield* (
1111+
session
1112+
.nativeTurnKept({ providerThread, nativeTurnId: cutTurn.nativeTurnId })
1113+
// As when the turn ends: an unknown answer resends the request rather than losing it.
1114+
.pipe(Effect.orElseSucceed(() => false))
1115+
))
1116+
) {
1117+
// Settle it as a Stop would: mark the request dropped and take back its inline context, so
1118+
// this turn resends both. Starting again reads the settled state.
1119+
const occurredAt = yield* DateTime.now;
1120+
const allocateEventId = () =>
1121+
idAllocator.allocate.event({ threadId: projection.thread.id });
1122+
// Its attempt starts before it delivers anything, so later inline deliveries are its own,
1123+
// including handoffs carried from an earlier run that they still target.
1124+
const cutStartedAt =
1125+
projection.attempts.find((candidate) => candidate.id === cutTurn.run.activeAttemptId)
1126+
?.startedAt ?? cutTurn.run.startedAt;
1127+
const settled = yield* eventSink.writeIfRunCurrent({
1128+
threadId: projection.thread.id,
1129+
runId: run.id,
1130+
activeAttemptId: attempt.id,
1131+
expectedStatus: "starting",
1132+
events: [
1133+
{
1134+
id: yield* allocateEventId(),
1135+
type: "provider-turn.updated" as const,
1136+
threadId: projection.thread.id,
1137+
runId: cutTurn.run.id,
1138+
nodeId: cutTurn.turn.nodeId,
1139+
providerInstanceId: cutTurn.run.providerInstanceId,
1140+
occurredAt,
1141+
payload: { ...cutTurn.turn, promptDropped: true as const },
1142+
},
1143+
...(yield* Effect.forEach(
1144+
projection.contextHandoffs.filter(
1145+
(handoff) =>
1146+
handoff.delivery?.status === "inline" &&
1147+
handoff.delivery.nativeThreadId === providerThread.nativeThreadRef?.nativeId &&
1148+
(handoff.targetRunId === cutTurn.run.id ||
1149+
(cutStartedAt !== null &&
1150+
DateTime.isGreaterThanOrEqualTo(handoff.updatedAt, cutStartedAt))),
1151+
),
1152+
({ delivery: _delivery, ...handoff }) =>
1153+
Effect.map(allocateEventId(), (id) => ({
1154+
id,
1155+
type: "context-handoff.updated" as const,
1156+
threadId: projection.thread.id,
1157+
runId: cutTurn.run.id,
1158+
providerInstanceId: cutTurn.run.providerInstanceId,
1159+
occurredAt,
1160+
payload: { ...handoff, updatedAt: occurredAt },
1161+
})),
1162+
)),
1163+
],
1164+
});
1165+
if (!settled.committed) return;
1166+
// The restarted start captures the same baseline; never let the two write at once.
1167+
yield* baseline;
1168+
return CUT_TURN_SETTLED;
1169+
}
10661170
const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* (
10671171
load: Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapter.ProviderAdapterV2Error>,
10681172
) {
@@ -2389,18 +2493,23 @@ export const layer: Layer.Layer<
23892493
(yield* projects
23902494
.getById(thread.projectId, { includeDeleted: true })
23912495
.pipe(Effect.map((project) => Option.getOrUndefined(project)?.workspaceRoot)));
2496+
// Settling a turn a restart cut off changes what a start reads, so it starts once more.
2497+
const startSettled = start(input, captureStartingRun).pipe(
2498+
Effect.filterOrElse(
2499+
(started) => started !== CUT_TURN_SETTLED,
2500+
() => start(input, captureStartingRun),
2501+
),
2502+
Effect.map((started) => (started === CUT_TURN_SETTLED ? undefined : started)),
2503+
);
23922504
const providerTurn = yield* cwd === undefined
2393-
? start(input, captureStartingRun)
2505+
? startSettled
23942506
: withTurnStartReservation(
23952507
fileSystem,
23962508
path,
23972509
path.resolve(cwd),
23982510
thread.worktreePath === null
2399-
? start(input, captureStartingRun)
2400-
: withWorkspaceLease(
2401-
path.resolve(thread.worktreePath),
2402-
start(input, captureStartingRun),
2403-
),
2511+
? startSettled
2512+
: withWorkspaceLease(path.resolve(thread.worktreePath), startSettled),
24042513
);
24052514
if (providerTurn !== undefined && "worktreeSetup" in providerTurn) {
24062515
yield* providerTurn.worktreeSetup;
Collapse file

‎apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+137-3Lines changed: 137 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ function makeTestAdapter(input: {
120120
readonly rejectedNativeThreads?: Ref.Ref<ReadonlySet<string>>;
121121
readonly failedRunOrdinals?: ReadonlySet<number>;
122122
readonly promptDroppedRunOrdinals?: ReadonlySet<number>;
123+
readonly nativeTurnKept?: (nativeTurnId: string) => boolean;
123124
readonly brokenRunOrdinals?: ReadonlySet<number>;
124125
readonly interruptedRunOrdinals?: ReadonlySet<number>;
125126
readonly cancelledRunOrdinals?: ReadonlySet<number>;
@@ -201,6 +202,12 @@ function makeTestAdapter(input: {
201202
...(input.canReuseContextUsage === undefined
202203
? {}
203204
: { canReuseContextUsage: input.canReuseContextUsage }),
205+
...(input.nativeTurnKept === undefined
206+
? {}
207+
: {
208+
nativeTurnKept: ({ nativeTurnId }) =>
209+
Effect.succeed(input.nativeTurnKept!(nativeTurnId)),
210+
}),
204211
...(input.backgroundWork === undefined
205212
? {}
206213
: {
@@ -6544,14 +6551,17 @@ describe("orchestration v2 provider switching", () => {
65446551
it.effect.each([
65456552
"same-provider-retry",
65466553
"cancelled-dropped",
6554+
"cancelled-by-restart",
65476555
"switch-away-and-return",
65486556
"persisted-failure",
65496557
] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) =>
65506558
Effect.gen(function* () {
65516559
const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`);
65526560
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
6553-
const dropped = variant !== "persisted-failure";
6554-
const cancelled = variant === "cancelled-dropped";
6561+
// A restart cancels the turn with no adapter left to report the drop.
6562+
const cutByRestart = variant === "cancelled-by-restart";
6563+
const dropped = variant !== "persisted-failure" && !cutByRestart;
6564+
const cancelled = variant === "cancelled-dropped" || cutByRestart;
65556565
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
65566566
makeTestAdapter({
65576567
instanceId: CODEX_MODEL_SELECTION.instanceId,
@@ -6569,6 +6579,9 @@ describe("orchestration v2 provider switching", () => {
65696579
? { cancelledRunOrdinals: new Set([3]) }
65706580
: { failedRunOrdinals: new Set([3]) }),
65716581
...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}),
6582+
...(cutByRestart
6583+
? { nativeTurnKept: (nativeTurnId: string) => !nativeTurnId.endsWith(":3") }
6584+
: {}),
65726585
}),
65736586
makeTestAdapter({
65746587
instanceId: CLAUDE_MODEL_SELECTION.instanceId,
@@ -6650,7 +6663,7 @@ describe("orchestration v2 provider switching", () => {
66506663
assert.equal(run3Handoff?.delivery?.status, "inline");
66516664
}
66526665

6653-
if (variant === "same-provider-retry" || variant === "cancelled-dropped") {
6666+
if (variant === "same-provider-retry" || variant === "cancelled-dropped" || cutByRestart) {
66546667
// Run 4: stay on Codex; must re-deliver run 2's handoff.
66556668
const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION);
66566669
const turns = yield* Ref.get(capturedTurns);
@@ -6662,6 +6675,10 @@ describe("orchestration v2 provider switching", () => {
66626675
(handoff) => handoff.id === run3Handoff!.id,
66636676
);
66646677
assert.equal(updatedHandoff?.delivery?.status, "inline");
6678+
const run3Turn = afterRun4.providerTurns.find(
6679+
(turn) => turn.runAttemptId === run3.activeAttemptId,
6680+
);
6681+
assert.equal(run3Turn?.promptDropped, true);
66656682
} else if (variant === "switch-away-and-return") {
66666683
// Run 4: bounce back to Claude, then Run 5: return to Codex.
66676684
yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION);
@@ -6702,4 +6719,121 @@ describe("orchestration v2 provider switching", () => {
67026719
);
67036720
}),
67046721
);
6722+
6723+
it.effect("restores a handoff that a turn cut by a restart carried from an earlier run", () =>
6724+
Effect.gen(function* () {
6725+
const cwd = yield* checkpointWorkspace("carried-handoff-cut-by-restart");
6726+
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
6727+
const refuseStarts = yield* Ref.make(0);
6728+
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
6729+
makeTestAdapter({
6730+
instanceId: CODEX_MODEL_SELECTION.instanceId,
6731+
driver: CODEX_DRIVER,
6732+
capabilities: CodexProviderCapabilitiesV2,
6733+
modelSelection: CODEX_MODEL_SELECTION,
6734+
responseByRunOrdinal: { 1: "Morning Codex summary.", 4: "", 5: "Recovered." },
6735+
capturedTurns,
6736+
refuseStarts,
6737+
// A restart cancels run 4 before the provider keeps its request.
6738+
cancelledRunOrdinals: new Set([4]),
6739+
nativeTurnKept: (nativeTurnId) => !nativeTurnId.endsWith(":4"),
6740+
}),
6741+
makeTestAdapter({
6742+
instanceId: CLAUDE_MODEL_SELECTION.instanceId,
6743+
driver: CLAUDE_DRIVER,
6744+
capabilities: ClaudeProviderCapabilitiesV2,
6745+
modelSelection: CLAUDE_MODEL_SELECTION,
6746+
responseByRunOrdinal: { 2: "Afternoon Claude shipped b63 live draft." },
6747+
capturedTurns,
6748+
}),
6749+
]);
6750+
6751+
yield* Effect.gen(function* () {
6752+
const orchestrator = yield* Orchestrator.OrchestratorV2;
6753+
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
6754+
const testThreadId = ThreadId.make("thread:carried-handoff-cut-by-restart");
6755+
yield* orchestrator.dispatch({
6756+
type: "thread.create",
6757+
createdBy: "user",
6758+
creationSource: "web",
6759+
commandId: CommandId.make("command:carried-handoff-cut:create"),
6760+
threadId: testThreadId,
6761+
projectId,
6762+
title: "Carried handoff cut by restart",
6763+
modelSelection: CODEX_MODEL_SELECTION,
6764+
runtimeMode: "full-access",
6765+
interactionMode: "default",
6766+
branch: null,
6767+
worktreePath: cwd,
6768+
});
6769+
let step = 0;
6770+
const send = (text: string, modelSelection: ModelSelection) =>
6771+
Effect.gen(function* () {
6772+
step += 1;
6773+
yield* orchestrator.dispatch({
6774+
type: "message.dispatch",
6775+
createdBy: "user",
6776+
creationSource: "web",
6777+
commandId: CommandId.make(`command:carried-handoff-cut:msg-${step}`),
6778+
threadId: testThreadId,
6779+
messageId: MessageId.make(`message:carried-handoff-cut:${step}`),
6780+
text,
6781+
attachments: [],
6782+
modelSelection,
6783+
dispatchMode: { type: "start_immediately" },
6784+
});
6785+
yield* worker.drain();
6786+
yield* waitForIdle(testThreadId);
6787+
yield* worker.drain();
6788+
return yield* orchestrator.getThreadProjection(testThreadId);
6789+
});
6790+
6791+
yield* send("Morning task", CODEX_MODEL_SELECTION);
6792+
yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION);
6793+
// Codex refuses run 3 before its prompt, so run 4 carries the handoff made for run 3.
6794+
yield* Ref.set(refuseStarts, 1);
6795+
const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION);
6796+
const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!;
6797+
assert.equal(run3.status, "failed");
6798+
const afterRun4 = yield* send("Carry the draft forward", CODEX_MODEL_SELECTION);
6799+
const run4 = afterRun4.runs.find((run) => run.ordinal === 4)!;
6800+
assert.equal(run4.status, "cancelled");
6801+
const carried = afterRun4.contextHandoffs.find(
6802+
(handoff) => handoff.targetRunId === run3.id,
6803+
);
6804+
assert.equal(carried?.delivery?.status, "inline");
6805+
assert.include(
6806+
(yield* Ref.get(capturedTurns)).at(-1)!.text,
6807+
"Afternoon Claude shipped b63 live draft.",
6808+
);
6809+
6810+
const afterRun5 = yield* send("Resume", CODEX_MODEL_SELECTION);
6811+
const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!;
6812+
assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft.");
6813+
assert.include(run5Turn.text, "Carry the draft forward");
6814+
const run4Turn = afterRun5.providerTurns.find(
6815+
(turn) => turn.runAttemptId === run4.activeAttemptId,
6816+
);
6817+
assert.equal(run4Turn?.promptDropped, true);
6818+
}).pipe(
6819+
Effect.provide(
6820+
ProviderReplayHarness.layerWithRegistry(
6821+
{
6822+
name: "carried-handoff-cut-by-restart",
6823+
runtimePolicyOverride: {
6824+
cwd,
6825+
approvalPolicy: "never",
6826+
sandboxPolicy: {
6827+
type: "readOnly",
6828+
access: { type: "fullAccess" },
6829+
networkAccess: false,
6830+
},
6831+
},
6832+
},
6833+
layerRegistry,
6834+
),
6835+
),
6836+
);
6837+
}),
6838+
);
67056839
});
Collapse file

‎packages/provider-core/src/server/ProviderAdapter.ts‎

Copy file name to clipboardExpand all lines: packages/provider-core/src/server/ProviderAdapter.ts
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,14 @@ export interface ProviderAdapterV2SessionRuntime {
789789
cwd?: string | null,
790790
) => number | undefined;
791791
readonly canReuseContextUsage?: (previous: ModelSelection, next: ModelSelection) => boolean;
792+
/**
793+
* False when the native session no longer holds a cancelled turn's request. Set only by
794+
* providers that can drop one, so a turn a restart cut off is settled like a Stop.
795+
*/
796+
readonly nativeTurnKept?: (input: {
797+
readonly providerThread: OrchestrationV2ProviderThread;
798+
readonly nativeTurnId: string;
799+
}) => Effect.Effect<boolean, ProviderAdapterV2Error>;
792800
/** Excludes turn-scoped options from native thread load matching. */
793801
readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection;
794802
readonly ensureThread: (
Collapse file

‎packages/provider-cursor/src/server/adapter.test.ts‎

Copy file name to clipboardExpand all lines: packages/provider-cursor/src/server/adapter.test.ts
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -939,6 +939,12 @@ describe("CursorAdapterV2", () => {
939939
assert.equal(checkpointed.terminal?.status, "failed");
940940
assert.isUndefined(checkpointed.terminal?.promptDropped);
941941
assert.isUndefined(checkpointed.turn?.promptDropped);
942+
943+
// After a restart no turn ends to report it, so the next turn start asks instead.
944+
const kept = (nativeTurnId: string) =>
945+
runtime.nativeTurnKept!({ providerThread, nativeTurnId });
946+
assert.isFalse(yield* kept("native-cursor-run-1"));
947+
assert.isTrue(yield* kept("native-cursor-run-2"));
942948
}).pipe(
943949
Effect.scoped,
944950
Effect.provide(

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.