feat(server): persist the worktree setup send and progress on the thread #11852
Mergedjuliusmarmingemerged 11 commits into
main fromrefs/pull/11852/headmerged by juliusmarminge 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
- apps/server/src/orchestration/decider.ts line 1506OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1474,0 +1486,21 @@1486+ return [1487+ ...lifecycleResetEvents,1488+ ...(userMessageEvent ? [userMessageEvent] : []),1489+ turnStartRequestedEvent,1490+ ];1491+ }1492+1493+ case "thread.message.user.append": {1494+ if (isImportedAgentSessionMessageId(command.message.messageId)) {1495+ return yield* new OrchestrationCommandInvariantError({1496+ commandType: command.type,1497+ detail: `Message id '${command.message.messageId}' uses the reserved imported-session namespace.`,1498+ });1499+ }1500+ const thread = yield* requireThread({1501+ readModel,1502+ command,1503+ threadId: command.threadId,1504+ });1505+ if (thread.messages.some((message) => message.id === command.message.messageId)) {1506+ return [];apps/server/src/orchestration/decider.ts line 1511Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1474,0 +1488,21 @@1488+ ...(userMessageEvent ? [userMessageEvent] : []),1489+ turnStartRequestedEvent,1490+ ];1491+ }1492+1493+ case "thread.message.user.append": {1494+ if (isImportedAgentSessionMessageId(command.message.messageId)) {1495+ return yield* new OrchestrationCommandInvariantError({1496+ commandType: command.type,1497+ detail: `Message id '${command.message.messageId}' uses the reserved imported-session namespace.`,1498+ });1499+ }1500+ const thread = yield* requireThread({1501+ readModel,1502+ command,1503+ threadId: command.threadId,1504+ });1505+ if (thread.messages.some((message) => message.id === command.message.messageId)) {1506+ return [];1507+ }1508+ return {@@ -1550,4 +1609,4 @@15501609 );15511610 }15521611 return track(1553- worktreeSetupTracker.finish(threadId, "failed", dispatchError.message),1612+ worktreeSetupTracker
- @@ -1401,13 +1393,8 @@1401- payload: {1402- threadId: command.threadId,1403- messageId: command.message.messageId,1404- role: "user",1405- text: command.message.text,1406- attachments: command.message.attachments,1407- ...(command.message.context !== undefined ? { context: command.message.context } : {}),1408- turnId: null,1409- streaming: false,1410- createdAt: command.createdAt,1411- updatedAt: command.createdAt,1412- },1413- };1393+ // A worktree bootstrap persists the message ahead of the turn with1394+ // `thread.message.user.append`; the turn then only references it.1395+ const persistedUserMessage = targetThread.messages.find(1396+ (message) =>1397+ message.id === command.message.messageId &&1398+ message.role === "user" &&1399+ message.turnId === null,1400+ );@@ -1535,4 +1592,6 @@15351592 Effect.uninterruptible,15361593 )15371594 : Effect.void;1538- return track(worktreeSetupTracker.finish(threadId, "cancelled")).pipe(1595+ return track(1596+ worktreeSetupTracker.finish(threadId, "cancelled").pipe(Effect.asVoid),1597+ ).pipe(@@ -1554,3 +1613,21 @@1613+ .finish(threadId, "failed", dispatchError.message)1614+ .pipe(Effect.asVoid),15541615 ).pipe(Effect.andThen(cleanupAndFail(cause, dispatchError)));15551616 }),15561617 );1618+1619+ // The bootstrap outlives the connection that asked for it: a reload1620+ // or a dropped socket must not abandon a half-made worktree, and1621+ // the thread it created is already visible to every client. The1622+ // RPC only waits on the detached fiber; a user cancel interrupts it1623+ // through the tracker.1624+ const runBootstrap = tracked1625+ ? Effect.gen(function* () {1626+ const fiber = yield* Effect.forkDetach(settledBootstrapProgram);1627+ yield* worktreeSetupTracker.begin({1628+ threadId,1629+ branch: bootstrap?.prepareWorktree?.branch ?? null,1630+ baseRef: bootstrap?.prepareWorktree?.baseBranch ?? null,1631+ stages: ["fetch", "checkout", "submodules", "setup-script", "agent"],1632+ fiber,1633+ });@@ -253,0 +274,21 @@274+ }275+ return null;276+}277+278+/**279+ * Which setup snapshot the timeline shows, if any. The live stream wins while280+ * it has a newer sequence; the recorded activity covers everything else. A281+ * running setup always shows. Once settled, the card stays only while it282+ * still says something the turn does not: the turn has not started yet, or a283+ * stage failed and the turn is still running so the exit code stays reachable.284+ */285+export function resolveVisibleWorktreeSetup(input: {286+ live: WorktreeSetupSnapshot | null;287+ recorded: WorktreeSetupSnapshot | null;288+ turnStarted: boolean;289+ isWorking: boolean;290+}): WorktreeSetupSnapshot | null {291+ const snapshot =292+ input.live && (!input.recorded || input.live.sequence >= input.recorded.sequence)293+ ? input.live294+ : input.recorded;@@ -8643,4 +8615,4 @@86438615 // setup (the bootstrap created it), so this keys off the route, not86448616 // `isLocalDraftThread`.86458617 const onWorktreeSetupWorkLocally = useCallback(() => {8646- if (!worktreeSetup || !worktreeSetupRef || worktreeSetup.phase !== "running" || !draftId) {8618+ if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) {
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
- apps/server/src/serverRuntimeStartup.ts line 763OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -742,3 +746,18 @@742746 ),743747 );744748749+const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);750+751+/**752+ * A worktree bootstrap records its setup snapshot on the thread while it runs753+ * and settles it when it finishes. The bootstrap itself lives only in memory,754+ * so a process exit mid-setup leaves a `running` record with nobody to finish755+ * it, and a persisted user message with no turn behind it. Mark those setups756+ * failed so every client shows the outcome instead of a spinner, and the user757+ * can send again.758+ */759+export const reconcileWorktreeSetups = Effect.gen(function* () {760+ const crypto = yield* Crypto.Crypto;761+ const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;762+ const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;763+ const { threads } = yield* query.getCommandReadModel();apps/server/src/ws.ts line 1636OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1552,5 +1617,20 @@15521617 return track(1553- worktreeSetupTracker.finish(threadId, "failed", dispatchError.message),1618+ worktreeSetupTracker1619+ .finish(threadId, "failed", dispatchError.message)1620+ .pipe(1621+ Effect.flatMap((snapshot) =>1622+ snapshot ? recordWorktreeSetup(snapshot) : Effect.void,1623+ ),1624+ ),15541625 ).pipe(Effect.andThen(cleanupAndFail(cause, dispatchError)));15551626 }),15561627 );1628+1629+ // The bootstrap outlives the connection that asked for it: a reload1630+ // or a dropped socket must not abandon a half-made worktree, and1631+ // the thread it created is already visible to every client. The1632+ // RPC only waits on the detached fiber; a user cancel interrupts it1633+ // through the tracker.1634+ const runBootstrap = tracked1635+ ? Effect.gen(function* () {1636+ const fiber = yield* Effect.forkDetach(settledBootstrapProgram);
- apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts line 3729Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3692,3 +3725,4 @@36923725 return {36933726 getCommandReadModel,36943727 getUserInputActivity,3728+ listActivitiesByKind,apps/server/src/serverRuntimeStartup.ts line 771Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -744,0 +750,21 @@750+751+/**752+ * A worktree bootstrap records its setup snapshot on the thread while it runs753+ * and settles it when it finishes. The bootstrap itself lives only in memory,754+ * so a process exit mid-setup leaves a `running` record with nobody to finish755+ * it, and a persisted user message with no turn behind it. Mark those setups756+ * failed so every client shows the outcome instead of a spinner, and the user757+ * can send again.758+ */759+export const reconcileWorktreeSetups = Effect.gen(function* () {760+ const crypto = yield* Crypto.Crypto;761+ const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;762+ const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;763+ // The command read model carries no activity bodies; read the setup764+ // records directly, live threads only.765+ const recordedSetups = yield* query.listActivitiesByKind(WORKTREE_SETUP_ACTIVITY_KIND);766+ const interruptedAt = DateTime.formatIso(yield* DateTime.now);767+768+ for (const recorded of recordedSetups) {769+ const snapshot = decodeWorktreeSetupSnapshot(recorded.payload);770+ if (Option.isNone(snapshot) || snapshot.value.phase !== "running") continue;
- apps/server/src/serverRuntimeStartup.ts lines 816 to 822Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -744,0 +790,21 @@790+ commandId: CommandId.make(yield* crypto.randomUUIDv4),791+ threadId: thread.id,792+ activity: {793+ id: EventId.make(worktreeSetupActivityId(thread.id)),794+ tone: "error",795+ kind: WORKTREE_SETUP_ACTIVITY_KIND,796+ summary: "Worktree setup interrupted by a server restart",797+ payload: interrupted,798+ turnId: null,799+ createdAt: snapshot.value.startedAt,800+ },801+ createdAt: interruptedAt,802+ })803+ .pipe(804+ Effect.catchCause((cause) =>805+ Cause.hasInterrupts(cause)806+ ? Effect.failCause(cause)807+ : Effect.logWarning("failed to settle interrupted worktree setup", {808+ threadId: thread.id,809+ cause,810+ }),
- apps/web/src/components/ChatView.logic.ts line 265Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -251,3 +254,12 @@251254 return false;252255 }253256257+const decodeWorktreeSetupSnapshot = Schema.decodeUnknownOption(WorktreeSetupSnapshot);258+259+/**260+ * The worktree setup the server recorded on the thread, if any: running once261+ * the bootstrap created the thread, then the settled outcome. It is what a262+ * reload or a second client renders, and what tells them to attach the live263+ * stream while it still says running.264+ */265+export function findRecordedWorktreeSetup(
- apps/web/src/components/ChatView.tsx line 3189Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3193,3 +3175,9 @@31933175 (isSendBusy || phase === "connecting" || phase === "running") &&31943176 compactRequestIsActive &&31953177 !compactionSettled;3178+ // A thread whose first user message is persisted but whose turn has not3179+ // started is mid-bootstrap on the server (the session is absent, or the3180+ // placeholder "starting" one the bootstrap projects). That is how a reload3181+ // or another client sees a worktree still being prepared, so it counts as3182+ // working just like the local dispatch that started it.3183+ const awaitingBootstrapTurn =
- apps/mobile/src/features/threads/ThreadRouteScreen.tsx line 791Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -782,3 +782,10 @@782782 }),783783 );784784 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);785+ // A worktree bootstrap projects a starting session and records a running786+ // setup on the thread before its turn, so a thread opened from another787+ // device (or after a restart) shows the same preparing state the sending788+ // client does. Both signals settle on every failure path.789+ const awaitingBootstrapTurn = useMemo(790+ () =>791+ selectedThreadDetail !== null &&apps/mobile/src/lib/threadActivity.ts lines 414 to 419OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -411,4 +411,9 @@411411 const ordered = Arr.sort(activities, activityOrder);412412 const entries: DerivedWorkLogEntry[] = [];413413 for (const activity of foldUserInputActivities(ordered)) {414- if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;414+ if (415+ isWorktreeSetupActivity(activity.kind) &&416+ (activity.tone !== "error" || activity.kind === "worktree-setup")417+ ) {418+ continue;419+ }
juliusmarminge merged this2c19283
juliusmarminge closed this
Sign in to join this conversation.



Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
26b8f98· PR result:f3096e6· 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.