GeezerVison is showing github.com — fix(server): resend a Cursor request a restart cut off before its fir… · patroza/t3code@2313dfa
File treeExpand file treeCollapse file tree Open diff view settings apps/server/src/orchestration-v2 provider-cursor/src/server
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/ProviderTurnStartService.ts +115-6Lines changed: 115 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -151,6 +151,46 @@ export function abandonedProviderTurns( | 151 | 151 | }); | 152 | 152 | } | 153 | 153 |
| | 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 | + | 154 | 194 | export const isProviderTurnStartError = Schema.is(ProviderTurnStartError); | 155 | 195 | const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError); | 156 | 196 | const isProviderAdapterTurnStartError = Schema.is(ProviderAdapter.ProviderAdapterTurnStartError); | @@ -1063,6 +1103,70 @@ export const layer: Layer.Layer< | 1063 | 1103 | } | 1064 | 1104 | const session = sessionResult.success; | 1065 | 1105 | 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 | + } | 1066 | 1170 | const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* ( | 1067 | 1171 | load: Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapter.ProviderAdapterV2Error>, | 1068 | 1172 | ) { | @@ -2389,18 +2493,23 @@ export const layer: Layer.Layer< | 2389 | 2493 | (yield* projects | 2390 | 2494 | .getById(thread.projectId, { includeDeleted: true }) | 2391 | 2495 | .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 | + ); | 2392 | 2504 | const providerTurn = yield* cwd === undefined | 2393 | | - ? start(input, captureStartingRun) | | 2505 | + ? startSettled | 2394 | 2506 | : withTurnStartReservation( | 2395 | 2507 | fileSystem, | 2396 | 2508 | path, | 2397 | 2509 | path.resolve(cwd), | 2398 | 2510 | 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), | 2404 | 2513 | ); | 2405 | 2514 | if (providerTurn !== undefined && "worktreeSetup" in providerTurn) { | 2406 | 2515 | yield* providerTurn.worktreeSetup; | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -120,6 +120,7 @@ function makeTestAdapter(input: { | 120 | 120 | readonly rejectedNativeThreads?: Ref.Ref<ReadonlySet<string>>; | 121 | 121 | readonly failedRunOrdinals?: ReadonlySet<number>; | 122 | 122 | readonly promptDroppedRunOrdinals?: ReadonlySet<number>; | | 123 | + readonly nativeTurnKept?: (nativeTurnId: string) => boolean; | 123 | 124 | readonly brokenRunOrdinals?: ReadonlySet<number>; | 124 | 125 | readonly interruptedRunOrdinals?: ReadonlySet<number>; | 125 | 126 | readonly cancelledRunOrdinals?: ReadonlySet<number>; | @@ -201,6 +202,12 @@ function makeTestAdapter(input: { | 201 | 202 | ...(input.canReuseContextUsage === undefined | 202 | 203 | ? {} | 203 | 204 | : { canReuseContextUsage: input.canReuseContextUsage }), | | 205 | + ...(input.nativeTurnKept === undefined | | 206 | + ? {} | | 207 | + : { | | 208 | + nativeTurnKept: ({ nativeTurnId }) => | | 209 | + Effect.succeed(input.nativeTurnKept!(nativeTurnId)), | | 210 | + }), | 204 | 211 | ...(input.backgroundWork === undefined | 205 | 212 | ? {} | 206 | 213 | : { | @@ -6544,14 +6551,17 @@ describe("orchestration v2 provider switching", () => { | 6544 | 6551 | it.effect.each([ | 6545 | 6552 | "same-provider-retry", | 6546 | 6553 | "cancelled-dropped", | | 6554 | + "cancelled-by-restart", | 6547 | 6555 | "switch-away-and-return", | 6548 | 6556 | "persisted-failure", | 6549 | 6557 | ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => | 6550 | 6558 | Effect.gen(function* () { | 6551 | 6559 | const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); | 6552 | 6560 | 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; | 6555 | 6565 | const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ | 6556 | 6566 | makeTestAdapter({ | 6557 | 6567 | instanceId: CODEX_MODEL_SELECTION.instanceId, | @@ -6569,6 +6579,9 @@ describe("orchestration v2 provider switching", () => { | 6569 | 6579 | ? { cancelledRunOrdinals: new Set([3]) } | 6570 | 6580 | : { failedRunOrdinals: new Set([3]) }), | 6571 | 6581 | ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), | | 6582 | + ...(cutByRestart | | 6583 | + ? { nativeTurnKept: (nativeTurnId: string) => !nativeTurnId.endsWith(":3") } | | 6584 | + : {}), | 6572 | 6585 | }), | 6573 | 6586 | makeTestAdapter({ | 6574 | 6587 | instanceId: CLAUDE_MODEL_SELECTION.instanceId, | @@ -6650,7 +6663,7 @@ describe("orchestration v2 provider switching", () => { | 6650 | 6663 | assert.equal(run3Handoff?.delivery?.status, "inline"); | 6651 | 6664 | } | 6652 | 6665 |
| 6653 | | - if (variant === "same-provider-retry" || variant === "cancelled-dropped") { | | 6666 | + if (variant === "same-provider-retry" || variant === "cancelled-dropped" || cutByRestart) { | 6654 | 6667 | // Run 4: stay on Codex; must re-deliver run 2's handoff. | 6655 | 6668 | const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); | 6656 | 6669 | const turns = yield* Ref.get(capturedTurns); | @@ -6662,6 +6675,10 @@ describe("orchestration v2 provider switching", () => { | 6662 | 6675 | (handoff) => handoff.id === run3Handoff!.id, | 6663 | 6676 | ); | 6664 | 6677 | 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); | 6665 | 6682 | } else if (variant === "switch-away-and-return") { | 6666 | 6683 | // Run 4: bounce back to Claude, then Run 5: return to Codex. | 6667 | 6684 | yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); | @@ -6702,4 +6719,121 @@ describe("orchestration v2 provider switching", () => { | 6702 | 6719 | ); | 6703 | 6720 | }), | 6704 | 6721 | ); | | 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 | + ); | 6705 | 6839 | }); |
Collapse file Copy file name to clipboardExpand all lines: packages/provider-core/src/server/ProviderAdapter.ts +8Lines changed: 8 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -789,6 +789,14 @@ export interface ProviderAdapterV2SessionRuntime { | 789 | 789 | cwd?: string | null, | 790 | 790 | ) => number | undefined; | 791 | 791 | 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>; | 792 | 800 | /** Excludes turn-scoped options from native thread load matching. */ | 793 | 801 | readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection; | 794 | 802 | readonly ensureThread: ( | |
Collapse file Copy file name to clipboardExpand all lines: packages/provider-cursor/src/server/adapter.test.ts +6Lines changed: 6 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -939,6 +939,12 @@ describe("CursorAdapterV2", () => { | 939 | 939 | assert.equal(checkpointed.terminal?.status, "failed"); | 940 | 940 | assert.isUndefined(checkpointed.terminal?.promptDropped); | 941 | 941 | 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")); | 942 | 948 | }).pipe( | 943 | 949 | Effect.scoped, | 944 | 950 | Effect.provide( | |
|