fix(server): restarts keep queued steering and stop duplicate launches #17589
main fromt3/continue-threads-defaultopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:S
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:S
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/RestartContinuation.ts line 40OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -18,6 +20,21 @@20+ isWorktreeContinuationRun,1821 restartCancelledBackgroundWorkNote,1922 restartContinuationNote,23+ restartPromptSource,2024 } from "./RestartBackgroundNote.ts";21252226 const CONTINUE_PROMPT = "Continue where you left off.";232728+/** A recorded intent must not wake held threads, unanswered requests, or settled provider turns. */29+export function restartContinuationBlocked(30+ projection: Pick<31+ ProjectionRuntimeRecoveryState,32+ "thread" | "runtimeRequests" | "providerTurns" | "turnItems"33+ >,34+ source: OrchestrationV2Run,35+): boolean {36+ if (37+ projection.thread.archivedAt !== null ||38+ projection.thread.deletedAt !== null ||39+ projection.thread.settledOverride === "settled" ||40+ projection.thread.snoozedUntil != nullapps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 5986OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5942,3 +5972,15 @@59425972 }59435973 }594459745975+ // A rollback cursor applies once. Persist its consumption before5976+ // a restart can resume past it and discard this turn's progress.5977+ if (5978+ input.replayed !== true &&5979+ !context.nativeConversationHeadConsumed &&5980+ context.input.providerThread.nativeConversationHeadRef !== null &&5981+ ((message.type === "assistant" &&5982+ message.parent_tool_use_id === null &&5983+ message.error === undefined) ||5984+ (message.type === "system" && message.subtype === "compact_boundary"))5985+ ) {5986+ context.nativeConversationHeadConsumed = true;packages/provider-opencode/src/server/adapter.ts line 3276OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3233,0 +3256,21 @@3256+ "session.messages",3257+ yield* sdkCall("session.messages", { sessionID: sessionId }, () =>3258+ client.session.messages({ sessionID: sessionId }),3259+ ).pipe(3260+ Effect.tapError((cause) =>3261+ finalizeTurn(state, turn, "failed", {3262+ failure: makeProviderFailure({ cause, class: "provider_error" }),3263+ }),3264+ ),3265+ ),3266+ );3267+ const userIndex = history.findLastIndex((entry) => entry.info.role === "user");3268+ for (const entry of userIndex < 0 ? [] : history.slice(userIndex)) {3269+ if (turn.finalized) break;3270+ yield* handleMessageUpdated({3271+ id: entry.info.id,3272+ type: "message.updated",3273+ properties: { sessionID: sessionId, info: entry.info },3274+ });3275+ for (const part of entry.parts) {3276+ yield* handlePartUpdated({
- packages/provider-opencode/src/server/adapter.ts line 3247OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3231,3 +3231,17 @@32313231 lastRunOrdinal: turnInput.runOrdinal,32323232 });32333233 yield* updateProviderSession("running", null);3234+ if (turnInput.restartContinuationOfRunId !== undefined) {3235+ const statuses = unwrapData(3236+ "session.status",3237+ yield* sdkCall("session.status", { sessionID: sessionId }, () =>3238+ client.session.status(),3239+ ).pipe(3240+ Effect.tapError((cause) =>3241+ finalizeTurn(state, turn, "failed", {3242+ failure: makeProviderFailure({ cause, class: "provider_error" }),3243+ }),3244+ ),3245+ ),3246+ );3247+ if (statuses[sessionId] !== undefined && statuses[sessionId]?.type !== "idle") {packages/provider-opencode/src/server/adapter.ts line 3270OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3233,0 +3250,21 @@3250+ turn.admissionMessageId = null;3251+ advanceOpenCodePromptAdmission(turn, "busy");3252+ const admissionAction = advanceOpenCodePromptAdmission(turn, "accepted");3253+ yield* Deferred.succeed(admissionSettled, undefined);3254+ turn.admissionAbortController = null;3255+ const history = unwrapData(3256+ "session.messages",3257+ yield* sdkCall("session.messages", { sessionID: sessionId }, () =>3258+ client.session.messages({ sessionID: sessionId }),3259+ ).pipe(3260+ Effect.tapError((cause) =>3261+ finalizeTurn(state, turn, "failed", {3262+ failure: makeProviderFailure({ cause, class: "provider_error" }),3263+ }),3264+ ),3265+ ),3266+ );3267+ const userIndex = history.findLastIndex((entry) => entry.info.role === "user");3268+ for (const entry of userIndex < 0 ? [] : history.slice(userIndex)) {3269+ if (turn.finalized) break;3270+ yield* handleMessageUpdated({
- packages/provider-opencode/src/server/adapter.ts line 3254OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3231,3 +3237,18 @@32313237 lastRunOrdinal: turnInput.runOrdinal,32323238 });32333239 yield* updateProviderSession("running", null);3240+ if (turnInput.restartContinuationOfRunId !== undefined) {3241+ turn.usage.followingRestart = true;3242+ const statuses = unwrapData(3243+ "session.status",3244+ yield* sdkCall("session.status", { sessionID: sessionId }, () =>3245+ client.session.status(),3246+ ).pipe(3247+ Effect.tapError((cause) =>3248+ finalizeTurn(state, turn, "failed", {3249+ failure: makeProviderFailure({ cause, class: "provider_error" }),3250+ }),3251+ ),3252+ ),3253+ );3254+ const readHistory = sdkCall("session.messages", { sessionID: sessionId }, () =>
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/process/ownedProcesses.ts lines 304 to 308OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -260,0 +288,21 @@288+ processes:289+ launcher === undefined290+ ? []291+ : [{ pid: launcher.pid, startTime: launcher.startTime, pgid: launcher.pgid }],292+ });293+ const release = () => {294+ // The managed launcher stays alive between replacement children.295+ if (registration !== undefined && launcher === undefined)296+ NodeFS.rmSync(registration, { force: true });297+ };298+ const pruneServers = async () => {299+ if (servers === undefined) return;300+ const records = NodeFS.readdirSync(servers).flatMap((name) => {301+ if (!name.endsWith(".json")) return [];302+ const file = NodePath.join(servers, name);303+ try {304+ return [{ file, entry: decodeEntry(NodeFS.readFileSync(file, "utf8")) }];305+ } catch (cause) {306+ if ((cause as NodeJS.ErrnoException).code === "ENOENT") return [];307+ throw cause;308+ }packages/provider-opencode/src/server/v2/adapter.ts line 2855OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2789,0 +2835,21 @@2835+ if (restoringChild) {2836+ if (2837+ call.background &&2838+ activeSessions !== undefined &&2839+ !activeSessions.has(childId!)2840+ ) {2841+ yield* settleCall(call, "interrupted", LOST_BACKGROUND);2842+ continue;2843+ }2844+ const sessionID = Session.ID.make(childId!);2845+ if (activeSessions?.has(childId!) && call.child !== undefined) {2846+ const history = yield* OpenCode2Client.paginate(2847+ { sessionID, order: "desc" as const, limit: 50 },2848+ client.message.list,2849+ ).pipe(Stream.runCollect);2850+ const child = call.child;2851+ child.subagent!.turns = Math.max(2852+ child.subagent!.turns,2853+ history.filter((entry) => entry.type === "idle").length,2854+ );2855+ yield* startChildTurn(child);
- packages/provider-opencode/src/server/v2/adapter.ts line 4123OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3944,0 +4103,21 @@4103+ Stream.filter((message) => message.id === sourcePromptId),4104+ Stream.runHead,4105+ ),4106+ );4107+ if (!admitted) {4108+ turnInput = { ...turnInput, message: source.message };4109+ admissionId = sourcePromptId;4110+ }4111+ }4112+ return false;4113+ }4114+ const turn = yield* beginTurn(state, turnInput, false);4115+ yield* takeRunningWake(state);4116+ if (state.active !== turn) return true;4117+ if (prompt?.type === "user") {4118+ turn.providerTurn = {4119+ ...turn.providerTurn,4120+ nativeTurnRef: ref(prompt.id, "weak"),4121+ };4122+ yield* emitProviderTurn(state, turn, turn.providerTurn);4123+ yield* backfill(sessionId, state, new Set(Object.keys(active))).pipe(apps/server/src/process/ownedProcesses.ts lines 490 to 491OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -366,5 +487,5 @@366487 for (const p of stopped.values()) await signal(p, "SIGCONT").catch(() => undefined);367488 throw error;368489 }369- for (const p of survivors(next, await controller.snapshot()).toReversed())370- await signal(p, "SIGKILL");490+ table = await controller.snapshot();491+ next = protectedEntry(next, table);packages/provider-opencode/src/server/v2/adapter.ts line 2831OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2788,2 +2811,21 @@27882811 }27892812 if (part.type !== "tool") continue;2813+ if (part.name === "subagent") {2814+ if (!state.calls.has(part.id)) yield* startCall(state, turn, part.id);2815+ const call = state.calls.get(part.id)!;2816+ const input = typeof part.state.input === "object" ? part.state.input : undefined;2817+ const metadata = "metadata" in part.state ? part.state.metadata : undefined;2818+ call.prompt = stringField(input, "prompt") ?? call.prompt;2819+ call.title = stringField(input, "description") ?? call.title;2820+ call.agent = stringField(input, "agent") ?? call.agent;2821+ call.model = stringField(input, "model") ?? call.model;2822+ call.background =2823+ call.background ||2824+ stringField(metadata, "status") === "running" ||2825+ input?.["background"] === true;2826+ const childId = stringField(metadata, "sessionID");2827+ const restoringChild = childId !== undefined && call.child === undefined;2828+ if (childId !== undefined) yield* attachChild(call, childId);2829+ if (part.state.status === "error") {2830+ yield* settleCall(call, "failed", part.state.error.message);2831+ } else if (part.state.status === "completed" && !call.background) {
- apps/server/src/process/ownedProcesses.ts lines 512 to 512OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -401,0 +492,21 @@492+ if (server.hostname !== hostname || same(server.owner, entry.owner)) continue;493+ const live = table.find((p) => same(p, server.owner) && !p.zombie);494+ const managed = table.filter(495+ (p) => !p.zombie && server.processes.some((owned) => same(p, owned)),496+ );497+ if (live || managed.length > 0) {498+ if (live) owners.push(live);499+ owners.push(...managed);500+ } else if (501+ !table.some((p) => p.pid === server.owner.pid) &&502+ controller.exists(server.owner.pid)503+ )504+ throw new Error("Could not verify a live server during provider cleanup");505+ }506+ }507+ const protectedPids = new Set(owners.map((p) => p.pid));508+ let changed = true;509+ while (changed) {510+ changed = false;511+ for (const p of table) {512+ if (!protectedPids.has(p.pid) && protectedPids.has(p.ppid)) {
- @@ -401,0 +483,21 @@483+ for (const name of NodeFS.readdirSync(servers)) {484+ if (!name.endsWith(".json")) continue;485+ let server: Entry;486+ try {487+ server = decodeEntry(NodeFS.readFileSync(NodePath.join(servers, name), "utf8"));488+ } catch (cause) {489+ if ((cause as NodeJS.ErrnoException).code === "ENOENT") continue;490+ throw cause;491+ }492+ if (server.hostname !== hostname || same(server.owner, entry.owner)) continue;493+ const live = table.find((p) => same(p, server.owner) && !p.zombie);494+ const managed = table.filter(495+ (p) => !p.zombie && server.processes.some((owned) => same(p, owned)),496+ );497+ if (live || managed.length > 0) {498+ if (live) owners.push(live);499+ owners.push(...managed);500+ } else if (501+ !table.some((p) => p.pid === server.owner.pid) &&502+ controller.exists(server.owner.pid)503+ )
maria-rcks changed the title
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
maria-rcks changed the title
juliusmarminge assignedjuliusmarminge
juliusmarminge closed this
Sign in to join this conversation.


Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — This PR changes restart recovery, durable run state, prompt construction, Codex turn handling, and MCP launch idempotency across multiple production paths. Although the schema additions are backward-compatible and focused tests are included, the cross-component runtime impact warrants human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).