feat(orchestrator): move a running thread between devices #5544
ClosedBil0000(GitHub profile, opens in a new tab)wants to merge 250+ commits into
t3code/codex-turn-mapping fromrefs/pull/5544/headopened View on GitHub- packages/contracts/src/orchestrationV2.ts lines 2452 to 2457OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2320,0 +2437,21 @@2437+ "thread_already_away",2438+ "repository_mismatch",2439+ "project_missing",2440+ "workspace_diverged",2441+ "payload_too_large",2442+ "part_missing",2443+ "part_digest_mismatch",2444+ "apply_failed",2445+ "store_failed",2446+]);2447+export type OrchestrationV2HandoffErrorReason = typeof OrchestrationV2HandoffErrorReason.Type;2448+2449+export class OrchestrationV2HandoffError extends Schema.TaggedErrorClass<OrchestrationV2HandoffError>()(2450+ "OrchestrationV2HandoffError",2451+ {2452+ reason: OrchestrationV2HandoffErrorReason,2453+ handoffId: Schema.optional(ThreadHandoffId),2454+ message: TrimmedNonEmptyString,2455+ cause: Schema.optional(Schema.Defect()),2456+ },2457+) {}
- apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 195OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +175,21 @@175+ }) => Effect.Effect<void, VcsError>;176+ readonly extractArchive: (input: {177+ readonly cwd: string;178+ readonly archivePath: string;179+ }) => Effect.Effect<void, VcsError>;180+ /** Restores a stash this hop created, used when an apply is rolled back. */181+ readonly popStash: (input: {182+ readonly cwd: string;183+ readonly stashRef: string;184+ }) => Effect.Effect<void, VcsError>;185+}186+187+export class ThreadHandoffGit extends Context.Service<ThreadHandoffGit, ThreadHandoffGitShape>()(188+ "t3/orchestration-v2/ThreadHandoffGit",189+) {}190+191+export const make = Effect.gen(function* () {192+ const process = yield* VcsProcess;193+ const git = (input: GitInput) => runGit(process, input);194+195+ const resolveTip: ThreadHandoffGitShape["resolveTip"] = (input) =>apps/server/src/orchestration-v2/ThreadHandoffService.ts lines 250 to 256OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +236,21 @@236+ const target = partPath({ handoffId: input.handoffId, kind: input.part.kind });237+ const exists = yield* fs238+ .exists(target)239+ .pipe(asHandoffError("store_failed", "Could not read a staged handoff part."));240+ if (!exists) {241+ return yield* handoffError({242+ reason: "part_missing",243+ message: `Handoff part ${input.part.kind} was never uploaded.`,244+ handoffId: input.handoffId,245+ });246+ }247+ const contents = yield* fs248+ .readFile(target)249+ .pipe(asHandoffError("store_failed", "Could not read a staged handoff part."));250+ if (sha256(contents) !== input.part.digest) {251+ return yield* handoffError({252+ reason: "part_digest_mismatch",253+ message: `Handoff part ${input.part.kind} does not match the digest in the manifest.`,254+ handoffId: input.handoffId,255+ });256+ }apps/server/src/orchestration-v2/ThreadHandoffService.ts line 693OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +673,21 @@673+674+ if (classification === "diverged" || classification === "unrelated") {675+ // Park the sender's commits and stop. Nothing on either machine has676+ // moved, and the user is left holding both histories.677+ const parkedRef = handoffRefName(bundle.origin.environmentId, branch ?? "HEAD");678+ yield* git679+ .writeRef({ cwd, ref: parkedRef, commit: incomingTip })680+ .pipe(asHandoffError("apply_failed", "Could not park the incoming commits."));681+ yield* markHop({682+ handoffId: bundle.handoffId,683+ state: "failed",684+ lastError: `branch ${classification}`,685+ });686+ return yield* handoffError({687+ reason: "workspace_diverged",688+ message: `The branch moved on both machines, so nothing here was changed. The incoming commits are at ${parkedRef}.`,689+ handoffId: bundle.handoffId,690+ });691+ }692+693+ yield* markHop({ handoffId: bundle.handoffId, state: "applying", lastError: null });apps/server/src/orchestration-v2/ThreadHandoffService.ts line 865OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +597,21 @@597+ threadId: thread.id,598+ providerInstanceId: thread.providerInstanceId,599+ occurredAt: now,600+ payload: thread,601+ },602+ ]),603+ ];604+ yield* eventStore.append({ events });605+ return thread;606+ }).pipe(607+ asHandoffError(608+ "store_failed",609+ "Could not write the arrival into this environment's history.",610+ ),611+ );612+613+ const receive: ThreadHandoffServiceShape["receive"] = (input) =>614+ serialize.withLock(615+ input.bundle.handoffId,616+ Effect.gen(function* () {617+ const { bundle } = input;apps/server/src/orchestration-v2/ThreadHandoffService.ts line 785OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +765,21 @@765+ peerEnvironmentId: bundle.origin.environmentId,766+ peerThreadId: bundle.origin.threadId,767+ previousHandoffId: bundle.lineage.previousHandoffId,768+ hopCount: bundle.lineage.hopCount,769+ state: "arrived",770+ bundle,771+ });772+ yield* markHop({773+ handoffId: bundle.handoffId,774+ state: "arrived",775+ lastError: null,776+ appliedHeadSha: incomingTip,777+ stashRef,778+ preTag,779+ });780+781+ return { threadId, classification, stashRef, preTag } satisfies ThreadHandoffApplication;782+ }),783+ );784+785+ const recoverInterrupted: ThreadHandoffServiceShape["recoverInterrupted"] = () =>apps/server/src/orchestration-v2/ThreadHandoffService.ts line 615OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +595,21 @@595+ id: EventId.make(`${HANDOFF_EVENT_PREFIX}:${bundle.handoffId}:arrived`),596+ type: "thread.handoff-arrived" as const,597+ threadId: thread.id,598+ providerInstanceId: thread.providerInstanceId,599+ occurredAt: now,600+ payload: thread,601+ },602+ ]),603+ ];604+ yield* eventStore.append({ events });605+ return thread;606+ }).pipe(607+ asHandoffError(608+ "store_failed",609+ "Could not write the arrival into this environment's history.",610+ ),611+ );612+613+ const receive: ThreadHandoffServiceShape["receive"] = (input) =>614+ serialize.withLock(615+ input.bundle.handoffId,apps/server/src/orchestration-v2/ThreadHandoffService.ts line 740OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +720,21 @@720+ .pipe(asHandoffError("store_failed", "Could not read the staged patch."));721+ // Dry run first: a patch that will not apply must leave the working722+ // tree exactly as it was, not half-written.723+ const applies = yield* git724+ .applyPatch({ cwd, patch, check: true })725+ .pipe(asHandoffError("apply_failed", "Could not test the incoming changes."));726+ if (!applies) {727+ yield* rollback({ cwd, preTag, stashRef });728+ yield* markHop({729+ handoffId: bundle.handoffId,730+ state: "failed",731+ lastError: "patch did not apply",732+ });733+ return yield* handoffError({734+ reason: "apply_failed",735+ message:736+ "The incoming changes could not be applied here, so this repository was put back exactly as it was.",737+ handoffId: bundle.handoffId,738+ });739+ }740+ yield* gitapps/server/src/orchestration-v2/ThreadHandoffService.ts line 622OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +602,21 @@602+ ]),603+ ];604+ yield* eventStore.append({ events });605+ return thread;606+ }).pipe(607+ asHandoffError(608+ "store_failed",609+ "Could not write the arrival into this environment's history.",610+ ),611+ );612+613+ const receive: ThreadHandoffServiceShape["receive"] = (input) =>614+ serialize.withLock(615+ input.bundle.handoffId,616+ Effect.gen(function* () {617+ const { bundle } = input;618+ yield* Effect.forEach(bundle.parts, (part) =>619+ verifyStagedPart({ handoffId: bundle.handoffId, part }),620+ );621+622+ const cwd = yield* workspaceRootFor(input.projectId);apps/server/src/orchestration-v2/ThreadHandoffService.ts line 604OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +584,21 @@584+ id: EventId.make(`${HANDOFF_EVENT_PREFIX}:${bundle.handoffId}:thread`),585+ type: returning ? "thread.handoff-returned" : "thread.created",586+ threadId: thread.id,587+ providerInstanceId: thread.providerInstanceId,588+ occurredAt: now,589+ payload: thread,590+ },591+ ...(returning592+ ? []593+ : [594+ {595+ id: EventId.make(`${HANDOFF_EVENT_PREFIX}:${bundle.handoffId}:arrived`),596+ type: "thread.handoff-arrived" as const,597+ threadId: thread.id,598+ providerInstanceId: thread.providerInstanceId,599+ occurredAt: now,600+ payload: thread,601+ },602+ ]),603+ ];604+ yield* eventStore.append({ events });
Bil0000(GitHub profile, opens in a new tab) changed the title
- packages/client-runtime/src/state/threadHandoffTransfer.ts line 230OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +181,21 @@181+ bundle,182+ projectId: input.targetProjectId,183+ returningThreadId: input.returningThreadId,184+ }),185+ );186+187+ report("settle", transferred, totalBytes);188+ yield* runInEnvironment(189+ input.originEnvironmentId,190+ completeThreadHandoff({191+ threadId: input.threadId,192+ handoffId: bundle.handoffId,193+ peerThreadId: application.threadId,194+ }),195+ );196+197+ return {198+ handoffId: bundle.handoffId,199+ targetThreadId: application.threadId,200+ } satisfies ThreadHandoffTransferResult;201+ }).pipe(apps/web/src/components/ThreadHandoffDialog.tsx line 311OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +174,21 @@174+ {progress.totalBytes > 0 ? ` / ${formatBytes(progress.totalBytes)}` : ""}175+ </span>176+ ) : null}177+ </div>178+ ))}179+ {canCancel ? null : (180+ <span className="text-muted-foreground text-xs">181+ The other machine is being written to; this can no longer be cancelled here.182+ </span>183+ )}184+ </div>185+ )}186+187+ {errorMessage === null ? null : (188+ <p className="text-destructive text-xs" role="alert">189+ {errorMessage}190+ </p>191+ )}192+ </DialogPanel>193+ <div className="flex justify-end gap-2 px-4 pb-4">194+ <Buttonapps/server/src/orchestration-v2/http.ts line 126OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -95 +106,21 @@95106 )107+ .handle(108+ "readHandoffPart",109+ Effect.fn("environment.orchestration.readHandoffPart")(function* (args) {110+ yield* annotateEnvironmentRequest(args.endpoint.name);111+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);112+ const target = threadHandoff.partPath({113+ handoffId: args.params.handoffId,114+ kind: args.params.kind,115+ });116+ const exists = yield* fs117+ .exists(target)118+ .pipe(119+ Effect.catch((cause) =>120+ failEnvironmentInternal("orchestration_handoff_part_failed", cause),121+ ),122+ );123+ if (!exists) {124+ return yield* failEnvironmentNotFound("handoff_part_not_found");125+ }126+ const contents = yield* fsapps/server/src/orchestration-v2/http.ts line 167OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -95,0 +147,21 @@147+ "writeHandoffPart",148+ Effect.fn("environment.orchestration.writeHandoffPart")(function* (args) {149+ yield* annotateEnvironmentRequest(args.endpoint.name);150+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);151+ const target = threadHandoff.partPath({152+ handoffId: args.params.handoffId,153+ kind: args.params.kind,154+ });155+ const staged = yield* fs.exists(target).pipe(156+ Effect.flatMap((exists) => (exists ? fs.readFile(target) : Effect.succeed(EMPTY_PART))),157+ Effect.catch((cause) =>158+ failEnvironmentInternal("orchestration_handoff_part_failed", cause),159+ ),160+ );161+ // A chunk that does not continue exactly where the staged bytes end162+ // would silently produce a part with a hole in it, which would only163+ // surface later as a digest mismatch or a corrupt bundle.164+ if (args.payload.offset !== staged.length) {165+ return yield* failEnvironmentInvalidRequest("handoff_part_offset_mismatch");166+ }167+ const next = new Uint8Array(staged.length + args.payload.data.length);packages/contracts/src/environmentHttp.ts line 494OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -460,3 +479,14 @@460479 threadId: ThreadId,461480 });462481482+/**483+ * Handoff part bytes move in chunks rather than as one body.484+ *485+ * A part can be up to the payload ceiling, so streaming it in bounded pieces486+ * keeps both servers from holding a whole payload in memory, and makes a487+ * transfer that dies partway resumable from the offset it reached instead of488+ * starting over.489+ */490+export const ENVIRONMENT_HANDOFF_PART_CHUNK_BYTES = 4 * 1024 * 1024;491+492+const EnvironmentHandoffPartParams = Schema.Struct({
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/http.ts lines 164 to 167OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -95,0 +147,21 @@147+ "writeHandoffPart",148+ Effect.fn("environment.orchestration.writeHandoffPart")(function* (args) {149+ yield* annotateEnvironmentRequest(args.endpoint.name);150+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);151+ const target = threadHandoff.partPath({152+ handoffId: args.params.handoffId,153+ kind: args.params.kind,154+ });155+ const staged = yield* fs.exists(target).pipe(156+ Effect.flatMap((exists) => (exists ? fs.readFile(target) : Effect.succeed(EMPTY_PART))),157+ Effect.catch((cause) =>158+ failEnvironmentInternal("orchestration_handoff_part_failed", cause),159+ ),160+ );161+ // A chunk that does not continue exactly where the staged bytes end162+ // would silently produce a part with a hole in it, which would only163+ // surface later as a digest mismatch or a corrupt bundle.164+ if (args.payload.offset !== staged.length) {165+ return yield* failEnvironmentInvalidRequest("handoff_part_offset_mismatch");166+ }167+ const next = new Uint8Array(staged.length + args.payload.data.length);apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 316OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +296,21 @@296+ });297+ const ref = stash.stdout.trim();298+ return ref.length > 0 ? ref : null;299+ });300+301+ const writeRef: ThreadHandoffGitShape["writeRef"] = (input) =>302+ git({303+ operation: "write-ref",304+ args: ["update-ref", input.ref, input.commit],305+ cwd: input.cwd,306+ }).pipe(Effect.asVoid);307+308+ const createBundle: ThreadHandoffGitShape["createBundle"] = (input) =>309+ git({310+ operation: "create-bundle",311+ args: [312+ "bundle",313+ "create",314+ input.outputPath,315+ ...input.refs,316+ ...(input.excludeTips.length === 0 ? [] : ["--not", ...input.excludeTips]),
- apps/server/src/orchestration-v2/ThreadHandoffGit.ts lines 424 to 430OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +410,21 @@410+ stdin: input.paths.length === 0 ? "" : `${input.paths.join("\0")}\0`,411+ })412+ .pipe(Effect.asVoid);413+414+ const extractArchive: ThreadHandoffGitShape["extractArchive"] = (input) =>415+ process416+ .run({417+ operation: "thread-handoff.extract-archive",418+ command: "tar",419+ args: ["-xzf", input.archivePath],420+ cwd: input.cwd,421+ })422+ .pipe(Effect.asVoid);423+424+ const popStash: ThreadHandoffGitShape["popStash"] = (input) =>425+ git({426+ operation: "pop-stash",427+ args: ["stash", "pop", input.stashRef],428+ cwd: input.cwd,429+ allowNonZeroExit: true,430+ }).pipe(Effect.asVoid);apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 414OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +394,21 @@394+ .split("\n")395+ .map((line) => line.trim())396+ .filter((line) => line.length > 0)397+ : [],398+ ),399+ );400+401+ const archivePaths: ThreadHandoffGitShape["archivePaths"] = (input) =>402+ // A null-delimited file list keeps paths containing spaces or newlines403+ // intact, which is the form `git ls-files -z` already produces.404+ process405+ .run({406+ operation: "thread-handoff.archive-paths",407+ command: "tar",408+ args: ["--null", "--files-from", "-", "-czf", input.outputPath],409+ cwd: input.cwd,410+ stdin: input.paths.length === 0 ? "" : `${input.paths.join("\0")}\0`,411+ })412+ .pipe(Effect.asVoid);413+414+ const extractArchive: ThreadHandoffGitShape["extractArchive"] = (input) =>
- packages/client-runtime/src/state/threadHandoffTransfer.ts line 167Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +114,21 @@114+export const runThreadHandoffTransfer = Effect.fn("clientRuntime.state.runThreadHandoffTransfer")(115+ function* (input: ThreadHandoffTransferInput) {116+ const report = (phase: ThreadHandoffPhase, transferredBytes: number, totalBytes: number) => {117+ input.onProgress?.({ phase, transferredBytes, totalBytes });118+ };119+120+ report("prepare", 0, 0);121+ const preparation = yield* runInEnvironment(122+ input.originEnvironmentId,123+ prepareThreadHandoff({124+ threadId: input.threadId,125+ peerEnvironmentId: input.targetEnvironmentId,126+ peerBranchTip: input.targetBranchTip,127+ previousHandoffId: input.previousHandoffId,128+ hopCount: input.hopCount,129+ }),130+ );131+ const bundle: OrchestrationV2HandoffBundleV1 = preparation.bundle;132+ const totalBytes = preparation.totalBytes;133+134+ report("depart", 0, totalBytes);apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 246OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +226,21 @@226+ args: ["merge-base", input.left, input.right],227+ cwd: input.cwd,228+ allowNonZeroExit: true,229+ }).pipe(Effect.map((output) => output.exitCode === 0 && output.stdout.trim().length > 0));230+231+ const hasCommit: ThreadHandoffGitShape["hasCommit"] = (input) =>232+ git({233+ operation: "has-commit",234+ args: ["cat-file", "-e", `${input.commit}^{commit}`],235+ cwd: input.cwd,236+ allowNonZeroExit: true,237+ }).pipe(Effect.map((output) => output.exitCode === 0));238+239+ const trackedPatch: ThreadHandoffGitShape["trackedPatch"] = (input) =>240+ git({241+ operation: "tracked-patch",242+ // --binary keeps images and other non-text changes intact; without it a243+ // dirty png silently arrives as "Binary files differ" and never applies.244+ args: ["diff", "--binary", "--no-color", "HEAD"],245+ cwd: input.cwd,246+ maxOutputBytes: Number.MAX_SAFE_INTEGER,
- apps/server/src/orchestration-v2/ThreadHandoffService.ts line 1246Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +732,21 @@732+ });733+ return yield* handoffError({734+ reason: "workspace_diverged",735+ message: `The branch moved on both machines, so nothing here was changed. The incoming commits are at ${parkedRef}.`,736+ handoffId: bundle.handoffId,737+ });738+ }739+740+ yield* markHop({ handoffId: bundle.handoffId, state: "applying", lastError: null });741+742+ if (localTip !== null) {743+ preTag = handoffPreTagName(bundle.handoffId);744+ yield* git745+ .tagCommit({ cwd, tag: preTag, commit: localTip })746+ .pipe(asHandoffError("apply_failed", "Could not tag the current tip."));747+ stashRef = yield* git748+ .stashWorktree({ cwd, label: handoffStashLabel(bundle.handoffId, localTip) })749+ .pipe(asHandoffError("apply_failed", "Could not set the local changes aside."));750+ }751+752+ if (classification === "advance" && branch !== null && !wantsWorktree) {apps/server/src/orchestration-v2/ThreadHandoffService.ts line 747OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +727,21 @@727+ .pipe(asHandoffError("apply_failed", "Could not park the incoming commits."));728+ yield* markHop({729+ handoffId: bundle.handoffId,730+ state: "failed",731+ lastError: `branch ${classification}`,732+ });733+ return yield* handoffError({734+ reason: "workspace_diverged",735+ message: `The branch moved on both machines, so nothing here was changed. The incoming commits are at ${parkedRef}.`,736+ handoffId: bundle.handoffId,737+ });738+ }739+740+ yield* markHop({ handoffId: bundle.handoffId, state: "applying", lastError: null });741+742+ if (localTip !== null) {743+ preTag = handoffPreTagName(bundle.handoffId);744+ yield* git745+ .tagCommit({ cwd, tag: preTag, commit: localTip })746+ .pipe(asHandoffError("apply_failed", "Could not tag the current tip."));747+ stashRef = yield* git
- packages/contracts/src/orchestrationV2.ts line 2612Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -2321,0 +2572,21 @@2572+export const OrchestrationV2PrepareHandoffInput = Schema.Struct({2573+ threadId: ThreadId,2574+ peerEnvironmentId: EnvironmentId,2575+ /** The destination's tip for this branch, so the bundle carries only what it lacks. */2576+ peerBranchTip: Schema.NullOr(TrimmedNonEmptyString),2577+ previousHandoffId: Schema.NullOr(ThreadHandoffId),2578+ hopCount: NonNegativeInt,2579+});2580+export type OrchestrationV2PrepareHandoffInput = typeof OrchestrationV2PrepareHandoffInput.Type;2581+2582+export const OrchestrationV2PrepareHandoffResult = Schema.Struct({2583+ bundle: OrchestrationV2HandoffBundleV1,2584+ totalBytes: NonNegativeInt,2585+ /** "warn" still transfers; the ceiling that refuses is enforced while preparing. */2586+ verdict: Schema.Literals(["ok", "warn"]),2587+ dirtyFileCount: NonNegativeInt,2588+ untrackedFileCount: NonNegativeInt,2589+});2590+export type OrchestrationV2PrepareHandoffResult = typeof OrchestrationV2PrepareHandoffResult.Type;2591+2592+export const OrchestrationV2ReceiveHandoffInput = Schema.Struct({apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 62Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +33,21 @@33+ if (input.localTip === null) return "advance";34+ if (input.localTip === input.incomingTip) return "absorb";35+ // Containment is checked before common ancestry: a commit that contains the36+ // other trivially shares history with it, and answering "unrelated" for a37+ // fast-forward would refuse a transfer that is safe by construction.38+ if (input.incomingContainsLocal) return "advance";39+ if (input.localContainsIncoming) return "absorb";40+ return input.hasCommonAncestor ? "diverged" : "unrelated";41+}42+43+/**44+ * Where the sender's commits are parked when a hop is refused. The receiving45+ * side writes them under its own namespace before deciding, so a refusal still46+ * leaves the user holding both histories and able to join them by hand.47+ */48+export function handoffRefName(environmentId: string, branch: string): string {49+ return `refs/handoff/${environmentId}/${branch}`;50+}51+52+/** Tag written over the old tip before any pointer moves. */53+export function handoffPreTagName(handoffId: string): string {apps/server/src/orchestration-v2/ThreadHandoffGit.ts lines 48 to 50OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +30,21 @@30+}31+32+export function classifyIncomingTip(input: ClassifyIncomingTipInput): HandoffTipClassification {33+ if (input.localTip === null) return "advance";34+ if (input.localTip === input.incomingTip) return "absorb";35+ // Containment is checked before common ancestry: a commit that contains the36+ // other trivially shares history with it, and answering "unrelated" for a37+ // fast-forward would refuse a transfer that is safe by construction.38+ if (input.incomingContainsLocal) return "advance";39+ if (input.localContainsIncoming) return "absorb";40+ return input.hasCommonAncestor ? "diverged" : "unrelated";41+}42+43+/**44+ * Where the sender's commits are parked when a hop is refused. The receiving45+ * side writes them under its own namespace before deciding, so a refusal still46+ * leaves the user holding both histories and able to join them by hand.47+ */48+export function handoffRefName(environmentId: string, branch: string): string {49+ return `refs/handoff/${environmentId}/${branch}`;50+}apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 611Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +422,21 @@422+ operation: "thread-handoff.archive-paths",423+ command: "tar",424+ args: ["--null", "--files-from", "-", "-czf", input.outputPath],425+ cwd: input.cwd,426+ stdin: input.paths.length === 0 ? "" : `${input.paths.join("\0")}\0`,427+ })428+ .pipe(Effect.asVoid);429+430+ const extractArchive: ThreadHandoffGitShape["extractArchive"] = (input) =>431+ process432+ .run({433+ operation: "thread-handoff.extract-archive",434+ command: "tar",435+ args: ["-xzf", input.archivePath],436+ cwd: input.cwd,437+ })438+ .pipe(Effect.asVoid);439+440+ const worktreeEntries = (input: { readonly cwd: string }) =>441+ git({442+ operation: "list-worktrees",apps/server/src/orchestration-v2/http.ts lines 164 to 166OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -95,0 +146,21 @@146+ .handle(147+ "writeHandoffPart",148+ Effect.fn("environment.orchestration.writeHandoffPart")(function* (args) {149+ yield* annotateEnvironmentRequest(args.endpoint.name);150+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);151+ const target = threadHandoff.partPath({152+ handoffId: args.params.handoffId,153+ kind: args.params.kind,154+ });155+ const staged = yield* fs.exists(target).pipe(156+ Effect.flatMap((exists) => (exists ? fs.readFile(target) : Effect.succeed(EMPTY_PART))),157+ Effect.catch((cause) =>158+ failEnvironmentInternal("orchestration_handoff_part_failed", cause),159+ ),160+ );161+ // A chunk that does not continue exactly where the staged bytes end162+ // would silently produce a part with a hole in it, which would only163+ // surface later as a digest mismatch or a corrupt bundle.164+ if (args.payload.offset !== staged.length) {165+ return yield* failEnvironmentInvalidRequest("handoff_part_offset_mismatch");166+ }packages/client-runtime/src/state/threadHandoffTransfer.ts line 150OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +130,21 @@130+ );131+ const bundle: OrchestrationV2HandoffBundleV1 = preparation.bundle;132+ const totalBytes = preparation.totalBytes;133+134+ report("depart", 0, totalBytes);135+ yield* runInEnvironment(136+ input.originEnvironmentId,137+ departThread({138+ threadId: input.threadId,139+ handoffId: bundle.handoffId,140+ peerEnvironmentId: input.targetEnvironmentId,141+ peerLabel: input.targetLabel,142+ previousHandoffId: input.previousHandoffId,143+ hopCount: input.hopCount,144+ }),145+ );146+147+ // From here on the thread is locked, so every failure has to release it148+ // before surfacing — otherwise a transient network error would leave a149+ // thread nobody can type in on either machine.150+ const release = (reason: string) =>
- apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 469Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +359,21 @@359+ // user can see changes.360+ args: ["fetch", "--no-tags", input.bundlePath, "+refs/*:refs/handoff-incoming/*"],361+ cwd: input.cwd,362+ }).pipe(Effect.asVoid);363+364+ const cloneFromBundle: ThreadHandoffGitShape["cloneFromBundle"] = (input) =>365+ git({366+ operation: "clone-from-bundle",367+ args: [368+ "clone",369+ ...(input.branch === null ? [] : ["--branch", input.branch]),370+ input.bundlePath,371+ input.targetPath,372+ ],373+ cwd: ".",374+ }).pipe(Effect.asVoid);375+376+ const applyPatch: ThreadHandoffGitShape["applyPatch"] = (input) =>377+ git({378+ operation: input.check ? "apply-patch-check" : "apply-patch",379+ args: ["apply", "--3way", "--binary", ...(input.check ? ["--check"] : []), "-"],
- apps/server/src/orchestration-v2/ThreadHandoffService.ts line 242OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +222,21 @@222+ // One hop at a time per thread: prepare reads a working tree a receive may be223+ // rewriting, and two concurrent hops would each believe they own the thread.224+ const serialize = yield* makeKeyedSerialExecutor<string>();225+226+ const handoffDir = (handoffId: ThreadHandoffId) => path.join(config.handoffsDir, handoffId);227+228+ const partPath: ThreadHandoffServiceShape["partPath"] = (input) =>229+ path.join(handoffDir(input.handoffId), partFileName(input.kind));230+231+ const stagePart = (input: {232+ readonly handoffId: ThreadHandoffId;233+ readonly kind: OrchestrationV2HandoffPartKind;234+ readonly write: (targetPath: string) => Effect.Effect<void, PlatformError | VcsError>;235+ }) =>236+ Effect.gen(function* () {237+ const target = partPath({ handoffId: input.handoffId, kind: input.kind });238+ yield* fs.makeDirectory(handoffDir(input.handoffId), { recursive: true });239+ yield* input.write(target);240+ const exists = yield* fs.exists(target);241+ if (!exists) return null;242+ const contents = yield* fs.readFile(target);
- packages/client-runtime/src/state/threadHandoffTransfer.ts lines 119 to 128Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +101,21 @@101+ input.onChunk(chunk.data.length);102+ }103+ offset = chunk.offset + chunk.data.length;104+ complete = chunk.complete;105+ }106+});107+108+/**109+ * Runs one hop end to end across two environments.110+ *111+ * The order is the safety model: stage, lock the giving side, move the bytes,112+ * apply, then record where the thread went. Locking before the bytes move is113+ * what guarantees the two sides can never both be live; anything that fails114+ * after the lock releases it, so a failed transfer leaves the thread usable115+ * where it started rather than stranded.116+ */117+export const runThreadHandoffTransfer = Effect.fn("clientRuntime.state.runThreadHandoffTransfer")(118+ function* (input: ThreadHandoffTransferInput) {119+ const report = (phase: ThreadHandoffPhase, transferredBytes: number, totalBytes: number) => {120+ input.onProgress?.({ phase, transferredBytes, totalBytes });121+ };apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 305OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +285,21 @@285+ Effect.map(286+ (output) => output.stdout.split("\0").filter((entry) => entry.trim().length > 0).length,287+ ),288+ );289+290+ const isPublished: ThreadHandoffGitShape["isPublished"] = (input) =>291+ git({292+ operation: "is-published",293+ args: ["branch", "--remotes", "--contains", input.commit],294+ cwd: input.cwd,295+ allowNonZeroExit: true,296+ }).pipe(Effect.map((output) => output.exitCode === 0 && output.stdout.trim().length > 0));297+298+ const tagCommit: ThreadHandoffGitShape["tagCommit"] = (input) =>299+ git({300+ operation: "tag-commit",301+ args: ["tag", "--force", input.tag, input.commit],302+ cwd: input.cwd,303+ }).pipe(Effect.asVoid);304+305+ const stashWorktree: ThreadHandoffGitShape["stashWorktree"] = (input) =>
- apps/mobile/src/features/threads/ThreadHandoffBanner.tsx line 36Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+ * this keeps a thread that was moved elsewhere legible rather than silently16+ * refusing every send.17+ */18+export function ThreadHandoffBanner(props: {19+ readonly environmentId: EnvironmentId;20+ readonly threadId: ThreadId;21+}) {22+ const shells = useThreadShells();23+ const shell =24+ shells.find(25+ (candidate) =>26+ candidate.environmentId === props.environmentId && candidate.id === props.threadId,27+ ) ?? null;28+ const handoff = shell?.handoff ?? null;29+ const releaseHandoff = useAtomCommand(threadEnvironment.releaseHandoff, {30+ reportFailure: false,31+ });32+ const [releasing, setReleasing] = useState(false);33+ const borderColor = useThemeColor("--color-border");34+35+ const handleRelease = useCallback(async () => {
- apps/server/src/orchestration-v2/ThreadHandoffService.ts line 1089OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +1069,21 @@1069+ yield* git1070+ .extractArchive({1071+ cwd: config.terminalLogsDir,1072+ archivePath: partPath({ handoffId: bundle.handoffId, kind: "terminals-tar" }),1073+ })1074+ .pipe(asHandoffError("apply_failed", "Could not restore the thread's terminals."));1075+ // History files are named by thread id, and the thread has a new id1076+ // here; rename the extracted files so the manager finds them.1077+ const originPrefix = terminalHistoryFilePrefix(bundle.origin.threadId);1078+ const localPrefix = terminalHistoryFilePrefix(threadId);1079+ if (originPrefix !== localPrefix) {1080+ const extracted = yield* fs.readDirectory(config.terminalLogsDir).pipe(1081+ Effect.map((entries) =>1082+ entries.filter(1083+ (entry) =>1084+ entry === `${originPrefix}.log` || entry.startsWith(`${originPrefix}_`),1085+ ),1086+ ),1087+ Effect.orElseSucceed(() => [] as ReadonlyArray<string>),1088+ );1089+ yield* Effect.forEach(
- apps/web/src/components/Sidebar.logic.ts line 130Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -105,5 +105,19 @@105105 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {106106 environmentId: string;107107 projectId: string;108+ id?: string | undefined;109+ handoff?:110+ | {111+ readonly presence: "away" | "here";112+ readonly peerEnvironmentId: string;113+ readonly peerThreadId: string | null;114+ }115+ | null116+ | undefined;108117 },109118 >(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {119+ // A handed-off thread exists on both environments, but the sidebar shows120+ // one row: the live copy. The away copy hides only while its live121+ // counterpart is actually in the list — if the owning device is offline,122+ // the away row stays visible so the thread never disappears entirely.123+ const present = new Set(
- apps/server/src/orchestration-v2/runtimeLayer.ts lines 46 to 49OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -43,3 +43,7 @@4343 import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";4444 import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.ts";4545 import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";46+import { layer as repositoryIdentityResolverLayer } from "../project/RepositoryIdentityResolver.ts";47+import { layer as vcsProcessLayer } from "../vcs/VcsProcess.ts";48+import { layer as threadHandoffGitLayer } from "./ThreadHandoffGit.ts";49+import { layer as threadHandoffServiceLayer } from "./ThreadHandoffService.ts";
- apps/server/src/orchestration-v2/ThreadHandoffService.ts line 979OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +959,21 @@959+960+ if (classification === "advance" && branch !== null && !wantsWorktree) {961+ yield* git962+ .checkoutBranchAt({ cwd, branch, commit: incomingTip })963+ .pipe(964+ asHandoffError("apply_failed", "Could not move the branch to the incoming commit."),965+ );966+ }967+ }968+969+ // A thread that lived in a worktree lands in one here too: reuse the970+ // worktree that already has the branch checked out, otherwise add a971+ // fresh one at the incoming commit. The branch attaches only when no972+ // other checkout holds it — git forbids two checkouts of one branch,973+ // and a detached worktree at the right commit still runs the thread.974+ let applyCwd = cwd;975+ if (wantsWorktree && branch !== null) {976+ const existingWorktree = yield* git977+ .findWorktreeForBranch({ cwd, branch })978+ .pipe(asHandoffError("apply_failed", "Could not inspect the repository's worktrees."));979+ if (existingWorktree !== null && existingWorktree !== cwd) {apps/server/src/orchestration-v2/Orchestrator.ts line 1455Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -1430,3 +1436,7 @@14301436 });14311437 }143214381439+ // A thread can only leave once, and only the hop that locked it may report1440+ // its landing or release it. Without these the client could lock a thread1441+ // twice and lose track of which peer owns it.1442+ if (command.type === "thread.handoff.depart" && thread.handoff?.presence === "away") {
- apps/server/src/orchestration-v2/ThreadHandoffGit.ts lines 6 to 6OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import type { VcsError } from "@t3tools/contracts";2+import * as Context from "effect/Context";3+import * as Effect from "effect/Effect";4+import * as Layer from "effect/Layer";5+6+import { VcsProcess } from "../vcs/VcsProcess.ts";apps/server/src/orchestration-v2/ThreadHandoffService.ts lines 35 to 37OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+ type OrchestrationV2TurnItem,18+ type VcsError,19+} from "@t3tools/contracts";20+import * as Context from "effect/Context";21+import type { PlatformError } from "effect/PlatformError";22+import * as DateTime from "effect/DateTime";23+import * as Effect from "effect/Effect";24+import * as FileSystem from "effect/FileSystem";25+import * as Layer from "effect/Layer";26+import * as Option from "effect/Option";27+import * as Path from "effect/Path";28+import * as Schema from "effect/Schema";29+import * as SqlClient from "effect/unstable/sql/SqlClient";30+import * as NodeCrypto from "node:crypto";31+32+import { toSafeThreadAttachmentSegment } from "../attachmentStore.ts";33+import { toSafeThreadId as terminalHistoryFilePrefix } from "../terminal/Manager.ts";34+import { ServerConfig } from "../config.ts";35+import { ServerEnvironment } from "../environment/ServerEnvironment.ts";36+import { ProjectService } from "../project/ProjectService.ts";37+import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";
- apps/web/src/components/ChatView.tsx lines 2119 to 2133OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -2067,0 +2113,21 @@2113+ >2114+ Pull back2115+ </Button>2116+ ) : null}2117+ {/* Escape hatch for a hop whose transfer never landed: releasing2118+ makes this side live again without waiting for the peer. */}2119+ <Button2120+ type="button"2121+ size="sm"2122+ variant="outline"2123+ onClick={() => {2124+ if (serverThread) {2125+ void releaseThreadHandoff({2126+ environmentId: serverThread.environmentId,2127+ input: { threadId: serverThread.id, handoffId: awayHandoff.handoffId },2128+ });2129+ }2130+ }}2131+ >2132+ Continue here2133+ </Button>
- apps/web/src/components/BranchToolbarEnvironmentSelector.tsx lines 91 to 104Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -46,5 +64,20 @@4664 label: env.label,4765 })),48- [availableEnvironments],66+ ...(onMoveThread === undefined67+ ? []68+ : moveTargets.map((env) => ({69+ value: `${MOVE_VALUE_PREFIX}${env.environmentId}`,70+ label: env.label,71+ }))),72+ ],73+ [availableEnvironments, moveTargets, onMoveThread],4974 );507576+ const handleValueChange = (value: EnvironmentId | null) => {77+ if (value === null) return;78+ if (value.startsWith(MOVE_VALUE_PREFIX)) {79+ onMoveThread?.(value.slice(MOVE_VALUE_PREFIX.length) as EnvironmentId);80+ return;81+ }82+ onEnvironmentChange?.(value);83+ };
- packages/client-runtime/src/state/threadHandoffTransfer.ts lines 209 to 209OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +189,21 @@189+ cloneWorkspaceRoot: input.cloneWorkspaceRoot,190+ returningThreadId: input.returningThreadId,191+ }),192+ );193+194+ report("settle", transferred, totalBytes);195+ yield* runInEnvironment(196+ input.originEnvironmentId,197+ completeThreadHandoff({198+ threadId: input.threadId,199+ handoffId: bundle.handoffId,200+ peerThreadId: application.threadId,201+ }),202+ );203+204+ return {205+ handoffId: bundle.handoffId,206+ targetThreadId: application.threadId,207+ } satisfies ThreadHandoffTransferResult;208+ }).pipe(209+ Effect.tapCause((cause) => release(String(cause))),
- apps/server/src/orchestration-v2/ThreadHandoffService.ts lines 700 to 707OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +687,21 @@687+ creationSource: "server",688+ createdAt: now,689+ updatedAt: now,690+ archivedAt: null,691+ settledOverride: null,692+ settledAt: null,693+ lastVisitedAt: null,694+ deletedAt: null,695+ };696+ const returning = input.existing !== null;697+ // Coming home (this thread had departed) ends the visible lineage; a698+ // revived copy that was pushed here again is simply "here" once more.699+ const cameHome = input.existing?.handoff?.presence === "away";700+ const thread: OrchestrationV2AppThread = {701+ ...base,702+ // Arrival revives: a copy the user archived (or one archived by an703+ // older build) returns to the sidebar the moment work lands in it.704+ archivedAt: returning ? null : base.archivedAt,705+ handoff: cameHome706+ ? null707+ : {
- apps/web/src/hooks/useThreadActions.ts line 308Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -265,8 +301,8 @@265301 }266302 return result;267303 },268- [unarchiveThreadMutation],304+ [mirrorToHandoffPeer, unarchiveThreadMutation],269305 );270306271307 const deleteThread = useCallback(272308 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
- apps/server/src/orchestration-v2/ThreadHandoffService.ts line 210OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +190,21 @@190+ /**191+ * Applies a staged bundle, creating the thread or — when the hop returns to192+ * a thread this environment already owns — continuing it.193+ */194+ readonly receive: (input: {195+ readonly bundle: OrchestrationV2HandoffBundleV1;196+ /** Null when the repository must first be cloned from the bundle. */197+ readonly projectId: ProjectId | null;198+ readonly cloneWorkspaceRoot: string | null;199+ readonly returningThreadId: ThreadId | null;200+ }) => Effect.Effect<ThreadHandoffApplication, OrchestrationV2HandoffError>;201+ /**202+ * Fails hops that were still applying when the server stopped. That is the203+ * only state in which a repository can have been written to, so it is the204+ * only state that needs recovering.205+ */206+ readonly recoverInterrupted: () => Effect.Effect<number>;207+ }208+>()("t3/orchestration-v2/ThreadHandoffService") {}209+210+export type ThreadHandoffServiceShape = ThreadHandoffService["Service"];apps/server/src/orchestration-v2/ThreadHandoffGit.ts line 110OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +90,21 @@90+ readonly args: ReadonlyArray<string>;91+ readonly cwd: string;92+ readonly stdin?: string;93+ readonly allowNonZeroExit?: boolean;94+ readonly maxOutputBytes?: number;95+ readonly timeoutMs?: number;96+}97+98+const runGit = (process: VcsProcess.VcsProcess["Service"], input: GitInput) =>99+ process.run({100+ operation: `thread-handoff.${input.operation}`,101+ command: "git",102+ args: input.args,103+ cwd: input.cwd,104+ ...(input.stdin === undefined ? {} : { stdin: input.stdin }),105+ ...(input.allowNonZeroExit === undefined ? {} : { allowNonZeroExit: input.allowNonZeroExit }),106+ ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),107+ ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),108+ });109+110+interface Shape {
- apps/server/src/orchestration-v2/ThreadHandoffService.ts line 1321OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +1301,21 @@1301+ });1302+ yield* recordHop({1303+ handoffId: bundle.handoffId,1304+ threadId,1305+ peerEnvironmentId: bundle.origin.environmentId,1306+ peerThreadId: bundle.origin.threadId,1307+ previousHandoffId: bundle.lineage.previousHandoffId,1308+ hopCount: bundle.lineage.hopCount,1309+ state: "arrived",1310+ bundle,1311+ });1312+ yield* markHop({1313+ handoffId: bundle.handoffId,1314+ state: "arrived",1315+ lastError: null,1316+ appliedHeadSha: incomingTip,1317+ stashRef: worktreeStashRef ?? rootStashRef,1318+ preTag,1319+ });1320+ });1321+ yield* applyRest.pipe(apps/server/src/orchestration-v2/ThreadHandoffService.ts line 1364OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +1344,21 @@1344+ );1345+1346+ const recoverInterrupted: ThreadHandoffServiceShape["recoverInterrupted"] = () =>1347+ Effect.gen(function* () {1348+ const rows = yield* sql<{1349+ readonly handoff_id: string;1350+ readonly thread_id: string;1351+ readonly stash_ref: string | null;1352+ readonly pre_tag: string | null;1353+ }>`1354+ SELECT handoff_id, thread_id, stash_ref, pre_tag1355+ FROM orchestration_v2_thread_handoffs WHERE state = 'applying'1356+ `;1357+ yield* Effect.forEach(1358+ rows,1359+ (row) =>1360+ Effect.gen(function* () {1361+ // A hop that died mid-apply left a written tree behind. Put it1362+ // back where the tag and stash say it was before marking the hop1363+ // failed — best effort, since the worktree may itself be gone.1364+ if (row.pre_tag !== null || row.stash_ref !== null) {apps/server/src/orchestration-v2/Orchestrator.ts lines 1503 to 1535Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -1432,0 +1490,21 @@1490+ thread.handoff.peerLabel ?? thread.handoff.peerEnvironmentId1491+ }.`,1492+ });1493+ }1494+ if (command.type === "thread.handoff.complete" || command.type === "thread.handoff.abort") {1495+ const link = thread.handoff ?? null;1496+ if (link === null || link.handoffId !== command.handoffId) {1497+ return yield* new OrchestratorDispatchError({1498+ commandId: command.commandId,1499+ commandType: command.type,1500+ cause: `Thread ${command.threadId} has no handoff ${command.handoffId} in flight.`,1501+ });1502+ }1503+ if (link.presence !== "away") {1504+ return yield* new OrchestratorDispatchError({1505+ commandId: command.commandId,1506+ commandType: command.type,1507+ cause: `Thread ${command.threadId} owns handoff ${command.handoffId} and cannot report on it.`,1508+ });1509+ }1510+ }apps/server/src/orchestration-v2/ThreadHandoffService.ts line 1321OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +1301,21 @@1301+ });1302+ yield* recordHop({1303+ handoffId: bundle.handoffId,1304+ threadId,1305+ peerEnvironmentId: bundle.origin.environmentId,1306+ peerThreadId: bundle.origin.threadId,1307+ previousHandoffId: bundle.lineage.previousHandoffId,1308+ hopCount: bundle.lineage.hopCount,1309+ state: "arrived",1310+ bundle,1311+ });1312+ yield* markHop({1313+ handoffId: bundle.handoffId,1314+ state: "arrived",1315+ lastError: null,1316+ appliedHeadSha: incomingTip,1317+ stashRef: worktreeStashRef ?? rootStashRef,1318+ preTag,1319+ });1320+ });1321+ yield* applyRest.pipe(apps/server/src/orchestration-v2/ThreadHandoffService.ts line 1636Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +1345,21 @@1345+1346+ const recoverInterrupted: ThreadHandoffServiceShape["recoverInterrupted"] = () =>1347+ Effect.gen(function* () {1348+ const rows = yield* sql<{1349+ readonly handoff_id: string;1350+ readonly thread_id: string;1351+ readonly stash_ref: string | null;1352+ readonly pre_tag: string | null;1353+ }>`1354+ SELECT handoff_id, thread_id, stash_ref, pre_tag1355+ FROM orchestration_v2_thread_handoffs WHERE state = 'applying'1356+ `;1357+ yield* Effect.forEach(1358+ rows,1359+ (row) =>1360+ Effect.gen(function* () {1361+ // A hop that died mid-apply left a written tree behind. Put it1362+ // back where the tag and stash say it was before marking the hop1363+ // failed — best effort, since the worktree may itself be gone.1364+ if (row.pre_tag !== null || row.stash_ref !== null) {1365+ yield* Effect.gen(function* () {
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
f38d45d4-abf4-498e-bf1f-f44233f84eebYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share