fix(cursor): background commands survive the turn and wake the agent when they exit #38348
MergedYash-Singh1(GitHub profile, opens in a new tab)merged 17 commits into
main fromrefs/pull/38348/headmerged by Yash-Singh1(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -1078,0 +1118,21 @@1118+ providerThread: OrchestrationV2ProviderThread,1119+ ): OrchestrationV2ProviderThread => ({1120+ ...providerThread,1121+ pendingBackgroundTasks: [...backgroundShells].flatMap(([taskId, shell]) =>1122+ shell.providerThreadId === providerThread.id1123+ ? [1124+ {1125+ taskId,1126+ kind: "command" as const,1127+ command: shell.command,1128+ ...(shell.command.trim().length === 01129+ ? {}1130+ : { description: shell.command.trim() }),1131+ ...(shell.awaited ? { awaited: true as const } : {}),1132+ },1133+ ]1134+ : [],1135+ ),1136+ });1137+1138+ const emitProviderThread = Effect.fnUntraced(function* (
- @@ -442,0 +494,21 @@494+ const notify =495+ typeof conversationId === "string" ? backgroundShellListeners.get(conversationId) : undefined;496+ if (notify === undefined) return false;497+ const ref = {498+ id: String(shell.id),499+ pid: typeof shell.pid === "number" ? shell.pid : undefined,500+ command: typeof command === "string" ? command : "",501+ };502+ notify({ ...ref, type: "started", stop: () => shell.abort() });503+ shell.onComplete((completion) =>504+ notify({505+ ...ref,506+ type: "ended",507+ stopped: completion.aborted === true,508+ exitCode: typeof completion.code === "number" ? completion.code : undefined,509+ outputPath: typeof completion.outputPath === "string" ? completion.outputPath : undefined,510+ }),511+ );512+ return true;513+ };514+ backgroundShellListeners.set(agentId, listener);@@ -1071,3 +1096,4 @@10711096 const resumedAgent = yield* Ref.make<string | null>(null);10721097 const warnedUnsupportedSandbox = yield* Ref.make(false);10731098 const activeTurn = yield* Ref.make<ActiveCursorTurn | null>(null);1099+ // Background shells the agent left running, by the shell id Cursor gave it.
- @@ -165,4 +165,4 @@165165 // Only marks which tasks keep the thread Working; Claude Plan mode blocks tools without this.166166 .annotate(Tool.Readonly, true)167167 .annotate(Tool.Destructive, false)168- .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);168+ .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutBackgroundWait);@@ -570,3 +570,7 @@570570 >(["orchestration", "worktree", "pull-requests", "issues"]);571571 if (browserToolsAvailable) capabilities.add("preview");572572 if (deviceToolsAvailable) capabilities.add("device");573+ const backgroundWait = yield* registry.get(providerInstanceId).pipe(574+ Effect.flatMap((adapter) => adapter.getCapabilities()),575+ Effect.map((adapter) => adapter.tools.supportsBackgroundWait === true),576+ Effect.orElseSucceed(() => false),@@ -1071,3 +1096,5 @@10711096 const resumedAgent = yield* Ref.make<string | null>(null);10721097 const warnedUnsupportedSandbox = yield* Ref.make(false);10731098 const activeTurn = yield* Ref.make<ActiveCursorTurn | null>(null);1099+ // Background shells the agent left running, by the shell id Cursor gave it.1100+ const backgroundShells = new Map<@@ -1078,0 +1118,21 @@1118+ providerThread: OrchestrationV2ProviderThread,1119+ ): OrchestrationV2ProviderThread => ({1120+ ...providerThread,1121+ pendingBackgroundTasks: [...backgroundShells].flatMap(([taskId, shell]) =>1122+ shell.providerThreadId === providerThread.id1123+ ? [1124+ {1125+ taskId,1126+ kind: "command" as const,1127+ command: shell.command,1128+ ...(shell.command.trim().length === 01129+ ? {}1130+ : { description: shell.command.trim() }),1131+ ...(shell.awaited ? { awaited: true as const } : {}),1132+ },1133+ ]1134+ : [],1135+ ),1136+ });1137+1138+ const emitProviderThread = Effect.fnUntraced(function* (@@ -1078,0 +1151,21 @@1151+1152+ const publishBackgroundShells = Effect.fnUntraced(function* (1153+ providerThreadId: OrchestrationV2ProviderThread["id"],1154+ ) {1155+ const published = yield* Ref.get(publishedProviderThread);1156+ if (published?.id !== providerThreadId) return;1157+ const turn = yield* Ref.get(activeTurn);1158+ // No run reads this stream between turns, so the session stores the snapshot itself.1159+ yield* emitProviderThread(1160+ { ...published, updatedAt: yield* DateTime.now },1161+ turn === null || turn.finalized,1162+ );1163+ });1164+1165+ const onBackgroundShell = Effect.fnUntraced(function* (1166+ turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,1167+ shell: CursorAgentSdk.CursorBackgroundShellEvent,1168+ ) {1169+ const providerThreadId = turnInput.providerThread.id;1170+ if (shell.type === "started") {1171+ backgroundShells.set(shell.id, {@@ -2968,3 +3115,4 @@29683115 );2969311629703117 const closeSession = Effect.fnUntraced(function* () {3118+ yield* stopBackgroundShells();@@ -3130,3 +3278,13 @@31303278 ),31313279 ),31323280 ),3281+ awaitBackgroundTasks: Effect.fn("CursorAdapterV2.awaitBackgroundTasks")(function* ({3282+ providerThread,3283+ taskIds,3284+ awaited,3285+ }) {3286+ // Cursor shows the agent a shell's id and its pid; either names it.3287+ const matched = [...new Set(taskIds)].filter((taskId) => {3288+ const shell =3289+ backgroundShells.get(taskId) ??3290+ [...backgroundShells.values()].find((shell) => String(shell.pid) === taskId);@@ -3262,4 +3436,9 @@32623436 // The kept turns may predate a compaction, so the instructions are sent again.32633437 const forgetConversation = (agent: string) =>32643438 Effect.all([3265- Ref.set(told, { agent, orchestration: false, device: false }),3439+ Ref.set(told, {3440+ agent,3441+ orchestration: false,3442+ device: false,3443+ backgroundWait: false,3444+ }),@@ -442,0 +494,21 @@494+ const notify =495+ typeof conversationId === "string" ? backgroundShellListeners.get(conversationId) : undefined;496+ if (notify === undefined) return false;497+ const ref = {498+ id: String(shell.id),499+ pid: typeof shell.pid === "number" ? shell.pid : undefined,500+ command: typeof command === "string" ? command : "",501+ };502+ notify({ ...ref, type: "started", stop: () => shell.abort() });503+ shell.onComplete((completion) =>504+ notify({505+ ...ref,506+ type: "ended",507+ stopped: completion.aborted === true,508+ exitCode: typeof completion.code === "number" ? completion.code : undefined,509+ outputPath: typeof completion.outputPath === "string" ? completion.outputPath : undefined,510+ }),511+ );512+ return true;513+ };514+ backgroundShellListeners.set(agentId, listener);@@ -570,3 +644,5 @@570644 payload: { type: "run.start", message: sendInput.message, options },571645 });572646647+ const onBackgroundShell = sendInput.onBackgroundShell;648+ if (onBackgroundShell !== undefined) {
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge added labelstakeover:in-progress
- @@ -1078,0 +1173,21 @@1173+ if (shell.type === "started") {1174+ if (stoppedRuns.has(turnInput.runId)) return shell.stop();1175+ backgroundShells.set(shell.id, {1176+ providerThreadId,1177+ runId: turnInput.runId,1178+ pid: shell.pid,1179+ command: shell.command,1180+ stop: shell.stop,1181+ awaited: false,1182+ });1183+ return yield* publishBackgroundShells(providerThreadId);1184+ }1185+ const started = backgroundShells.get(shell.id);1186+ if (started === undefined) return;1187+ backgroundShells.delete(shell.id);1188+ yield* publishBackgroundShells(providerThreadId);1189+ // Nobody waits to hear about a shell the agent or a Stop killed.1190+ if (shell.stopped) return;1191+ // The run that started it is still going, so the agent can read the result itself.1192+ const turn = yield* Ref.get(activeTurn);1193+ if (turn !== null && !turn.finalized && turn.input.runId === started.runId) return;
- @@ -1078,0 +1181,21 @@1181+ awaited: false,1182+ });1183+ return yield* publishBackgroundShells(providerThreadId);1184+ }1185+ const started = backgroundShells.get(shell.id);1186+ if (started === undefined) return;1187+ backgroundShells.delete(shell.id);1188+ yield* publishBackgroundShells(providerThreadId);1189+ // Nobody waits to hear about a shell the agent or a Stop killed.1190+ if (shell.stopped) return;1191+ // The run that started it is still working, so the agent can read the result itself.1192+ const turn = yield* Ref.get(activeTurn);1193+ if (1194+ turn !== null &&1195+ !turn.finalized &&1196+ !turn.turnEnded &&1197+ turn.input.runId === started.runId1198+ ) {1199+ return;1200+ }1201+ yield* continuationRequests.offer({
juliusmarminge added labelstakeover:blocked
juliusmarminge removed labelstakeover:in-progress
Pushed6dc806e
Pushedb684524
Pushed015484f
Pushed4c2dac8
Yash-Singh1(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Other scenarios#
All 64 scenario measurements match
main.All 64 scenario measurements
short turn resumeWebSocket decodedshort turn resumeWebSocket messageslong turn running, cold openHTTP decodedlong turn running, cold openrowslong turn running, history pageHTTP decodedlong turn running, history pagerowslong turn finished, cold openHTTP decodedlong turn finished, cold openrowslong turn finished, socket cold openWebSocket decodedlong turn finished, socket cold openWebSocket messageslong turn finished, socket cold openrowslong turn finished, work pageHTTP decodedlong turn finished, work pagerowsidle thread resumeWebSocket decodedidle thread resumeWebSocket messagesfleet shell snapshotHTTP decodedfleet shell snapshotrowsfleet shell subscribeWebSocket decodedfleet shell subscribeWebSocket messagesfleet shell resume checkHTTP decodedfleet shell resume checkrowsstale shell reloadHTTP decodedstale shell reloadrowsstale shell resumeWebSocket decodedstale shell resumeWebSocket messagesstale todo list cold openHTTP decodedstale todo list cold openrowsstale todo list cold opennodesstale todo list cold opensubagentsstale todo list cold openplansstale todo list cold openproviderTurnsstale todo list cold opencheckpointsshort turn resumeWebSocket decodedshort turn resumeWebSocket messageslong turn running, cold openHTTP decodedlong turn running, cold openrowslong turn running, history pageHTTP decodedlong turn running, history pagerowslong turn finished, cold openHTTP decodedlong turn finished, cold openrowslong turn finished, socket cold openWebSocket decodedlong turn finished, socket cold openWebSocket messageslong turn finished, socket cold openrowslong turn finished, work pageHTTP decodedlong turn finished, work pagerowsidle thread resumeWebSocket decodedidle thread resumeWebSocket messagesfleet shell snapshotHTTP decodedfleet shell snapshotrowsfleet shell subscribeWebSocket decodedfleet shell subscribeWebSocket messagesfleet shell resume checkHTTP decodedfleet shell resume checkrowsstale shell reloadHTTP decodedstale shell reloadrowsstale shell resumeWebSocket decodedstale shell resumeWebSocket messagesstale todo list cold openHTTP decodedstale todo list cold openrowsstale todo list cold opennodesstale todo list cold opensubagentsstale todo list cold openplansstale todo list cold openproviderTurnsstale todo list cold opencheckpointsBaseline:
ed203c4· PR result:4c2dac8· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.