feat(server): fork threads and side chats #9436
Closedamanthanvi(GitHub profile, opens in a new tab)wants to merge 27 commits into
main fromrefs/pull/9436/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1101Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -782,0 +830,21 @@830+ method: "thread.turn.start",831+ detail: `Source thread '${latestTurnFork?.sourceThreadId}' advanced after fork '${threadId}' was created. Latest-turn providers can only fork from the source's current completed head.`,832+ });833+834+ if (!(yield* sourceStillAtRecordedForkBoundary())) {835+ return yield* latestTurnForkBoundaryError();836+ }837+838+ const startedSession = yield* startProviderSession(839+ thread.fork == null840+ ? undefined841+ : {842+ forkFrom: {843+ threadId: thread.fork.sourceThreadId,844+ ...(thread.fork.sourceTurnId !== null ? { turnId: thread.fork.sourceTurnId } : {}),845+ },846+ },847+ );848+ if (!(yield* sourceStillAtRecordedForkBoundary())) {849+ const boundaryError = latestTurnForkBoundaryError();850+ yield* providerService.stopSession({ threadId: startedSession.threadId }).pipe(packages/contracts/src/orchestration.ts line 1070Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -802,3 +814,10 @@802814 createdAt: IsoDateTime,803815 });804816817+export const ThreadForkCommand = Schema.Struct({818+ type: Schema.Literal("thread.fork"),819+ commandId: CommandId,820+ threadId: ThreadId,821+ sourceThreadId: ThreadId,822+ sourceTurnId: Schema.optional(TurnId),823+ sourceMessageId: Schema.optional(MessageId),docs/internals/glossary.md lines 44 to 44OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -35,3 +35,10 @@35353636 The main durable unit of conversation and workspace history. In [the orchestration contracts][1], a thread holds messages, activities, checkpoints, and session-related state. See [projector.ts][4].373738+#### Fork39+40+A durable thread whose provider context branches from another thread at a completed turn boundary. The fork stores immutable source thread, turn, and message IDs, but starts with an empty T3 transcript; the provider session carrying inherited context is created lazily on the fork's first turn. Native fork startup never resumes the parent session. Codex fork failures fail startup rather than silently creating an empty conversation. Latest-turn providers fork only at the source head, and clients use `sessionFork` to disable older-message fork actions for them.41+42+#### Side chat43+44+A presentation of a normal durable fork with `sideChat: true`. Side chats are omitted from navigation lists and grouped beside their parent thread. Promoting one clears the flag through `thread.meta.update`; closing is client-local, while deletion uses the normal `thread.delete` command.packages/contracts/src/orchestration.ts line 1069Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -802,3 +814,9 @@802814 createdAt: IsoDateTime,803815 });804816817+export const ThreadForkCommand = Schema.Struct({818+ type: Schema.Literal("thread.fork"),819+ commandId: CommandId,820+ threadId: ThreadId,821+ sourceThreadId: ThreadId,822+ sourceTurnId: Schema.optional(TurnId),
- apps/server/src/orchestration/decider.ts lines 376 to 381OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -359,3 +361,21 @@359361 };360362 }361363364+ case "thread.fork": {365+ const source = yield* requireThread({366+ readModel,367+ command,368+ threadId: command.sourceThreadId,369+ });370+ if (source.deletedAt !== null) {371+ return yield* new OrchestrationCommandInvariantError({372+ commandType: command.type,373+ detail: `Source thread '${command.sourceThreadId}' is deleted and cannot be forked.`,374+ });375+ }376+ if (findThreadById(readModel, command.threadId) !== undefined) {377+ return yield* new OrchestrationCommandInvariantError({378+ commandType: command.type,379+ detail: `Thread '${command.threadId}' already exists and cannot be created twice.`,380+ });381+ }apps/server/src/orchestration/threadTitles.ts line 25OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -11,3 +11,15 @@1111 ? trimmedCurrentTitle === trimmedTitleSeed1212 : false;1313 }14+15+/**16+ * Title for a thread forked from `sourceTitle`, following the Codex app's17+ * convention: the first fork reuses the source title with " (1)", the next18+ * gets " (2)", and so on. The counter is derived from the titles already in19+ * the project so it survives renames and deletions of earlier forks.20+ */21+export function forkThreadTitle(22+ sourceTitle: string,23+ existingTitles: ReadonlyArray<string>,24+): string {25+ const base = stripForkSuffix(sourceTitle.trim()) || DEFAULT_THREAD_TITLE;
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 987Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -711,3 +740,11 @@711740 });712741 });713742743+ let providerCapabilities: ProviderAdapterCapabilities | undefined;744+ let latestTurnFork: typeof thread.fork = null;745+ if (thread.fork != null && !forkHasOwnResumeCursor) {746+ providerCapabilities = yield* providerService.getCapabilities(desiredInstanceId);747+ if (providerCapabilities.sessionFork === "latest-turn") {748+ latestTurnFork = thread.fork;749+ }750+ }apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1098Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -779,4 +837,17 @@779837 return restartedSession.threadId;780838 }781839782- const startedSession = yield* startProviderSession(undefined);840+ if (!(yield* sourceStillAtRecordedForkBoundary())) {841+ return yield* latestTurnForkBoundaryError();842+ }843+844+ const startedSession = yield* startProviderSession(845+ thread.fork == null846+ ? undefined847+ : {848+ forkFrom: {849+ threadId: thread.fork.sourceThreadId,850+ ...(thread.fork.sourceTurnId !== null ? { turnId: thread.fork.sourceTurnId } : {}),851+ },852+ },853+ );apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1002Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -711,3 +740,20 @@711740 });712741 });713742743+ let providerCapabilities: ProviderAdapterCapabilities | undefined;744+ let latestTurnFork: typeof thread.fork = null;745+ if (thread.fork != null && !forkHasOwnResumeCursor) {746+ providerCapabilities = yield* providerService.getCapabilities(desiredInstanceId);747+ if (providerCapabilities.sessionFork === "latest-turn") {748+ latestTurnFork = thread.fork;749+ }750+ }751+752+ const sourceStillAtRecordedForkBoundary = Effect.fnUntraced(function* () {753+ if (latestTurnFork === null) return true;754+ const source = yield* resolveThread(latestTurnFork.sourceThreadId);755+ const sourceLatestTurn = source?.latestTurn ?? null;756+ return latestTurnFork.sourceTurnId === null757+ ? sourceLatestTurn === null758+ : sourceLatestTurn?.turnId === latestTurnFork.sourceTurnId &&759+ sourceLatestTurn.state === "completed";
- apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts line 907OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -879,3 +896,12 @@879896 ON projects.project_id = threads.project_id880897 WHERE threads.deleted_at IS NULL881898 AND threads.archived_at IS NULL899+ AND (900+ threads.side_chat = 0901+ OR NOT EXISTS (902+ SELECT 1903+ FROM projection_threads AS parents904+ WHERE parents.thread_id = json_extract(threads.fork_json, '$.sourceThreadId')905+ AND parents.deleted_at IS NULL906+ )907+ )apps/server/src/orchestration/Normalizer.ts line 181OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -131,0 +161,21 @@161+ });162+ }163+164+ const activeSourceThread = yield* projectionSnapshotQuery.getThreadShellById(165+ canonicalCommand.sourceThreadId,166+ );167+ const sourceThread = Option.isSome(activeSourceThread)168+ ? activeSourceThread169+ : Option.fromNullishOr(170+ (yield* projectionSnapshotQuery.getArchivedShellSnapshot()).threads.find(171+ (thread) => thread.id === canonicalCommand.sourceThreadId,172+ ),173+ );174+ if (Option.isSome(sourceThread)) {175+ const providerService = yield* ProviderService;176+ // The live session's instance wins over the stored selection, matching177+ // the reactor and the clients after a provider switch.178+ const sourceInstanceId =179+ sourceThread.value.session?.providerInstanceId ??180+ sourceThread.value.modelSelection.instanceId;181+ const capabilities = yield* providerService.getCapabilities(sourceInstanceId);
- apps/server/src/orchestration/Normalizer.ts line 178OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -131,0 +158,21 @@158+ return yield* new OrchestrationCommandInvariantError({159+ commandType: canonicalCommand.type,160+ detail: `Message '${canonicalCommand.sourceMessageId}' is not the assistant message for turn '${canonicalCommand.sourceTurnId}' on source thread '${canonicalCommand.sourceThreadId}'.`,161+ });162+ }163+164+ const activeSourceThread = yield* projectionSnapshotQuery.getThreadShellById(165+ canonicalCommand.sourceThreadId,166+ );167+ const sourceThread = Option.isSome(activeSourceThread)168+ ? activeSourceThread169+ : Option.fromNullishOr(170+ (yield* projectionSnapshotQuery.getArchivedShellSnapshot()).threads.find(171+ (thread) => thread.id === canonicalCommand.sourceThreadId,172+ ),173+ );174+ if (Option.isSome(sourceThread)) {175+ const providerService = yield* ProviderService;176+ // The live session's instance wins over the stored selection, matching177+ // the reactor and the clients after a provider switch.178+ const sourceInstanceId =
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/orchestration/Layers/ProviderCommandReactor.ts line 611OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -567,0 +591,21 @@591+ baseDesiredModelSelection.instanceId !== forkSourceInstanceId592+ ? yield* Effect.gen(function* () {593+ const sourceProvider = (yield* providerRegistry.getProviders).find(594+ (provider) => provider.instanceId === forkSourceInstanceId,595+ );596+ const resolvedModel = sourceProvider597+ ? resolveSelectableModel(598+ sourceProvider.driver,599+ baseDesiredModelSelection.model,600+ sourceProvider.models,601+ )602+ : null;603+ return resolvedModel === null604+ ? { ...forkSource.modelSelection, instanceId: forkSourceInstanceId }605+ : {606+ ...baseDesiredModelSelection,607+ instanceId: forkSourceInstanceId,608+ model: resolvedModel,609+ };610+ })611+ : baseDesiredModelSelection;apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 558OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -536,3 +538,21 @@536538537539 const desiredRuntimeMode = thread.runtimeMode;538540 const requestedModelSelection = options?.modelSelection;541+ const forkBinding =542+ thread.fork == null ? null : yield* providerService.getSessionBinding(threadId);543+ const forkResumeCursor = forkBinding?.resumeCursor ?? undefined;544+ const forkHasOwnResumeCursor = forkResumeCursor !== undefined;545+ const forkSource =546+ thread.fork != null && !forkHasOwnResumeCursor547+ ? yield* resolveThread(thread.fork.sourceThreadId)548+ : undefined;549+ // Only a live source session says where the source runs now; a stopped550+ // or errored session is history, so the stored selection wins.551+ const forkSourceSession =552+ forkSource?.session != null &&553+ forkSource.session.status !== "stopped" &&554+ forkSource.session.status !== "error"555+ ? forkSource.session556+ : null;557+ const forkSourceInstanceId =558+ forkSourceSession?.providerInstanceId ?? forkSource?.modelSelection.instanceId;
- packages/contracts/src/orchestration.ts lines 558 to 558Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -407,3 +407,20 @@407407 });408408 export type OrchestrationSession = typeof OrchestrationSession.Type;409409410+/**411+ * Provider instance that currently holds a thread's conversation. A live412+ * session says where the thread runs now; a stopped or errored session is413+ * history, so the stored selection wins. Server and clients share this rule414+ * when they decide which instance's fork capability applies to a thread.415+ */416+export function threadProviderInstanceId(thread: {417+ readonly modelSelection: { readonly instanceId: ProviderInstanceId };418+ readonly session: {419+ readonly status: OrchestrationSessionStatus;420+ readonly providerInstanceId?: ProviderInstanceId | undefined;421+ } | null;422+}): ProviderInstanceId {423+ const session = thread.session;424+ return session !== null &&425+ session.status !== "stopped" &&426+ session.status !== "error" &&
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 801Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -563,5 +594,15 @@563594 activeSession !== undefined &&564595 activeSession.providerInstanceId !== undefined565596 ? activeSession.providerInstanceId566- : thread.modelSelection.instanceId;567- const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;597+ : (forkBinding?.providerInstanceId ?? thread.modelSelection.instanceId);598+ const baseDesiredModelSelection = requestedModelSelection ?? thread.modelSelection;599+ // When the source moved, the fork follows it onto the source's current600+ // instance and model: the inherited selection described the old home.601+ const forkSourceMoved =602+ forkSource !== undefined &&603+ forkSourceInstanceId !== undefined &&604+ forkSourceInstanceId !== thread.modelSelection.instanceId;605+ const movedForkSourceSelection: ModelSelection | undefined = forkSourceMoved606+ ? { ...forkSource.modelSelection, instanceId: forkSourceInstanceId }607+ : undefined;608+ const desiredModelSelection = movedForkSourceSelection ?? baseDesiredModelSelection;
- packages/client-runtime/src/state/threadShell.ts line 102OutdatedResolvedby amanthanvi(GitHub profile, opens in a new tab)@@ -73,3 +95,8 @@7395 );74967597 const environmentThreadRefsAtom = Atom.family((environmentId: EnvironmentId) => {98+ let previous: ReadonlyArray<ScopedThreadRef> = [];99+ return Atom.make((get) => {100+ const threadIds = get(environmentThreadIndexAtom(environmentId));101+ const next = get(environmentThreadsAtom(environmentId))102+ .filter((thread) => !isHiddenSideChat(thread, threadIds))apps/server/src/provider/Layers/CodexSessionRuntime.ts line 749Resolvedby amanthanvi(GitHub profile, opens in a new tab)@@ -706,3 +717,8 @@706717 serviceTier: input.serviceTier,707718 });708719720+ if (input.forkFrom !== undefined) {721+ const { ephemeral: _ephemeral, ...forkStartParams } = startParams;722+ return input.client.request("thread/fork", {723+ threadId: input.forkFrom.threadId,724+ ...(input.forkFrom.turnId !== undefined ? { lastTurnId: input.forkFrom.turnId } : {}),
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts lines 775 to 778Resolvedby amanthanvi(GitHub profile, opens in a new tab)@@ -616,5 +675,13 @@616675 activeSession !== undefined &&617676 activeSession.providerInstanceId !== undefined618677 ? activeSession.providerInstanceId619- : thread.modelSelection.instanceId;620- const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;678+ : (forkBinding?.providerInstanceId ?? thread.modelSelection.instanceId);679+ const baseDesiredModelSelection = requestedModelSelection ?? thread.modelSelection;680+ // When the source moved, the fork follows it onto the source's current681+ // instance and model: the inherited selection described the old home.682+ let movedForkSourceSelection: ModelSelection | undefined;683+ if (684+ forkSource !== undefined &&685+ forkSourceInstanceId !== undefined &&686+ forkSourceInstanceId !== thread.modelSelection.instanceId687+ ) {
- apps/server/src/orchestration/decider.ts lines 420 to 422Resolvedby amanthanvi(GitHub profile, opens in a new tab)@@ -386 +387,21 @@386387388+ case "thread.fork": {389+ const source = yield* requireThread({390+ readModel,391+ command,392+ threadId: command.sourceThreadId,393+ });394+ if (source.deletedAt !== null) {395+ return yield* new OrchestrationCommandInvariantError({396+ commandType: command.type,397+ detail: `Source thread '${command.sourceThreadId}' is deleted and cannot be forked.`,398+ });399+ }400+ yield* requireThreadAbsent({ readModel, command, threadId: command.threadId });401+402+ const latestTurn = source.latestTurn;403+ const sourceTurnIsLatest =404+ command.sourceTurnId !== undefined && latestTurn?.turnId === command.sourceTurnId;405+ const sourceMessageTargetsLatest =406+ command.sourceMessageId !== undefined &&407+ (command.sourceTurnId === undefined || sourceTurnIsLatest);apps/server/src/orchestration/decider.ts line 447OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -386,0 +427,21 @@427+ return yield* new OrchestrationCommandInvariantError({428+ commandType: command.type,429+ detail: `Turn '${command.sourceTurnId}' is not a completed turn of source thread '${command.sourceThreadId}'.`,430+ });431+ }432+ }433+ if (434+ sourceMessageTargetsLatest &&435+ latestTurn?.assistantMessageId !== command.sourceMessageId436+ ) {437+ return yield* new OrchestrationCommandInvariantError({438+ commandType: command.type,439+ detail: `Message '${command.sourceMessageId}' is not the assistant message for turn '${latestTurn?.turnId ?? "none"}' on source thread '${command.sourceThreadId}'.`,440+ });441+ }442+443+ const title =444+ command.title ??445+ forkThreadTitle(446+ source.title,447+ listThreadsByProjectId(readModel, source.projectId).map((thread) => thread.title),apps/server/src/orchestration/Layers/ProviderCommandReactor.ts lines 1014 to 1015Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -767,3 +904,21 @@904+ latestTurnFork.sourceThreadId,905+ );906+ if (Option.isNone(source)) return true;907+ const sourceLatestTurn = source.value.latestTurn;908+ return latestTurnFork.sourceTurnId === null909+ ? sourceLatestTurn === null910+ : sourceLatestTurn?.turnId === latestTurnFork.sourceTurnId &&911+ sourceLatestTurn.state === "completed";912+ });913+ const latestTurnForkBoundaryError = () =>914+ new ProviderAdapterRequestError({915+ provider: preferredProvider,916+ method: "thread.turn.start",917+ detail: `Source thread '${latestTurnFork?.sourceThreadId}' advanced after fork '${threadId}' was created. Latest-turn providers can only fork from the source's current completed head.`,918+ });919+767920 const existingSessionThreadId =768921 thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;769922 if (existingSessionThreadId) {923+ if (!(yield* sourceStillAtRecordedForkBoundary())) {924+ return yield* latestTurnForkBoundaryError();
- @@ -2863,3 +2893,21 @@28632893 // a confirmed not-found (start fresh); transport/auth/server28642894 // errors propagate instead of masking as a new empty session.28652895 const resolved = yield* Effect.gen(function* () {2896+ if (forkSessionId) {2897+ const forkedSession = yield* runOpenCodeSdk("session.fork", () =>2898+ client.session.fork({ sessionID: forkSessionId, directory }),2899+ );2900+ const forked = forkedSession.data;2901+ if (!forked) {2902+ return yield* new OpenCodeRuntimeError({2903+ operation: "session.fork",2904+ detail: "OpenCode session.fork returned no session payload.",2905+ });2906+ }2907+ yield* applyForkedOpenCodeSessionPermissions(2908+ client,2909+ forked.id,2910+ input.runtimeMode,2911+ );2912+ return { openCodeSession: forked, created: true };2913+ }
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed