TypeScript
refactor(web): drafts promote from the draft store, not from route effects (#25615)
Julius Marminge5432d8e723c7
diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsxindex fe0cc4ceda4..0be6d822c86 100644--- a/apps/web/src/appInit.tsx+++ b/apps/web/src/appInit.tsx@@ -23,7 +23,7 @@ import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRimport { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";import { resolveServerBackedAppDisplayName } from "./branding.logic";import { isElectron } from "./env";-import { useComposerDraftStore } from "./composerDraftStore";+import { subscribeDraftThreadPromotion, useComposerDraftStore } from "./composerDraftStore";import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";import {@@ -44,6 +44,7 @@ import { appAtomRegistry } from "./rpc/atomRegistry";import { primaryServerConfigAtom } from "./state/server";import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";+import { environmentThreadShells } from "./state/threads";import { resolveThreadRouteTarget } from "./threadRoutes";/** Writes appearance settings onto the document, touching only the groups that changed. */@@ -173,6 +174,12 @@ export function startAppServices(): AppRouter {installChatRouteCommands(router);registerOpenFavoriteEditorCommand();startThreadOverlayRetention(router);+ // Drafts promote as their server threads arrive, wherever the user is.+ subscribeDraftThreadPromotion({+ registry: appAtomRegistry,+ threadShellAtom: environmentThreadShells.quietThreadShellAtom,+ threadRefsAtom: environmentThreadShells.threadRefsAtom,+ });startMainAppLocationTracking(router);startBackgroundThreadAnnouncements(appAtomRegistry, router);startThreadVisitedMigration(appAtomRegistry);diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 426818dba7a..969a5d2e24c 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -52,7 +52,6 @@ import {deriveComposerSendState,deriveLockedProvider,hasServerAcknowledgedLocalDispatch,- resolveDraftPromotionNavigationTarget,waitForRevertedMessage,} from "./ChatView.logic";@@ -105,51 +104,6 @@ const readySession = {updatedAt: "2026-03-29T00:00:10.000Z",};-describe("resolveDraftPromotionNavigationTarget", () => {- const serverThreadRef = { environmentId, threadId };- const preparingRun = {- ...completedTurn,- status: "preparing" as const,- startedAt: null,- completedAt: null,- };-- it("stays on the draft until the server owns the send", () => {- expect(- resolveDraftPromotionNavigationTarget({- serverThreadRef,- serverThread: makeThread({ latestRun: preparingRun }),- backgroundSubmissionPending: false,- }),- ).toBeNull();- expect(- resolveDraftPromotionNavigationTarget({- serverThreadRef,- serverThread: makeThread(),- backgroundSubmissionPending: false,- }),- ).toBeNull();- });-- it("promotes a persisted send while its worktree is still preparing", () => {- const serverThread = makeThread({ latestRun: preparingRun, latestUserMessageAt: now });- expect(- resolveDraftPromotionNavigationTarget({- serverThreadRef,- serverThread,- backgroundSubmissionPending: false,- }),- ).toBe(serverThreadRef);- expect(- resolveDraftPromotionNavigationTarget({- serverThreadRef,- serverThread,- backgroundSubmissionPending: true,- }),- ).toBeNull();- });-});-describe("deriveComposerSendState", () => {it("keeps text sendable while excluding expired terminal pills", () => {const state = deriveComposerSendState({diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex e14d296cdd0..b3594ed28ef 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -449,24 +449,6 @@ export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input:return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };}-export function resolveDraftPromotionNavigationTarget(input: {- serverThreadRef: ScopedThreadRef | null;- serverThread: Pick<Thread, "latestRun" | "latestUserMessageAt"> | null | undefined;- backgroundSubmissionPending: boolean;-}): ScopedThreadRef | null {- if (input.backgroundSubmissionPending) {- return null;- }- const latestRun = input.serverThread?.latestRun ?? null;- const runStarted = latestRun?.startedAt != null;- const startupStopped =- latestRun?.status === "failed" ||- latestRun?.status === "interrupted" ||- latestRun?.status === "cancelled";- const messagePersisted = input.serverThread?.latestUserMessageAt != null;- return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;-}-export function startNewThreadForProject(projectRef: ScopedProjectRef | null,handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,@@ -948,7 +930,7 @@ export function recallCheckoutIsRepo(: sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));}-export function threadHasStarted(thread: Thread | null | undefined): boolean {+function threadHasStarted(thread: Thread | null | undefined): boolean {return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));}diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsxindex d798eb88431..30ee70d0dd6 100644--- a/apps/web/src/components/ThreadRouteView.tsx+++ b/apps/web/src/components/ThreadRouteView.tsx@@ -1,21 +1,13 @@import { scopedThreadKey } from "@t3tools/client-runtime/environment";-import type { ScopedThreadRef } from "@t3tools/contracts";-import { useNavigate } from "@tanstack/react-router";+import { Navigate, useNavigate } from "@tanstack/react-router";import { useEffect, useState } from "react";import ChatView from "./ChatView";import { BackgroundThreadContext } from "./chat/backgroundThread";-import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";-import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";import { SidebarInset } from "./ui/sidebar";-import {- finalizePromotedDraftThreadByRef,- markPromotedDraftThreadByRef,- useBackgroundDraftSubmissionPending,- useComposerDraftStore,-} from "../composerDraftStore";+import { useComposerDraftStore } from "../composerDraftStore";import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";-import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";+import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";import { useEnvironmentShellStatus } from "../state/shell";import { useEnvironmentThread } from "../state/threads";import {@@ -26,7 +18,9 @@ import {} from "../threadRoutes";/**- * Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed.+ * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`+ * layout, since an element only survives a route swap when the same parent renders it. Draft+ * promotion runs in the draft store; this only follows the redirect it leaves behind.* `background` keeps the thread mounted, inert and in place under Settings or Usage.*/export function ThreadRouteView({@@ -41,53 +35,36 @@ export function ThreadRouteView({const draftSession = useComposerDraftStore((store) =>draftId === null ? null : store.getDraftSession(draftId),);- const threadRefs = useThreadRefs();- // Promotion can begin before the server creates the reserved thread.- const inferredThreadRef = draftSession- ? (threadRefs.find(- (ref) =>- ref.environmentId === draftSession.environmentId &&- ref.threadId === draftSession.threadId,- ) ?? null)- : null;- const serverThreadRef: ScopedThreadRef | null =- target.kind === "server" ? target.threadRef : inferredThreadRef;- const serverThread = useQuietThreadShell(serverThreadRef);- const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(- target.kind === "draft" ? serverThreadRef : null,+ const draftRedirect = useComposerDraftStore((store) =>+ draftId === null ? null : store.getPromotedDraftRedirect(draftId),);- const canonicalThreadRef =- target.kind === "draft"- ? resolveDraftPromotionNavigationTarget({- serverThreadRef,- serverThread,- backgroundSubmissionPending,- })- : null;-+ const serverThreadRef = target.kind === "server" ? target.threadRef : null;+ const serverThreadShell = useQuietThreadShell(serverThreadRef);const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);- const serverThreadShell = serverThread;const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);const draftThread = useComposerDraftStore((store) =>serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,);- const promotedDraftId = useComposerDraftStore((store) =>- target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,+ // Reached from the sidebar before finalize, the thread still has its draft.+ const serverThreadDraftId = useComposerDraftStore((store) =>+ serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null,);- // Latch the key through promotion because the draft record disappears after the route swap.- const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);- const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;- const nextChatViewKey =- serverThreadKey === null- ? null- : chatViewKey?.threadKey === serverThreadKey- ? chatViewKey- : promotedDraftId- ? { threadKey: serverThreadKey, key: promotedDraftId }+ // The ChatView that carried a draft keeps its key through the redirect to its thread, and only+ // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView.+ const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null);+ const nextHandoffKey =+ draftId !== null && draftSession === null && draftRedirect+ ? handoffKey?.key === draftId+ ? handoffKey+ : { threadKey: scopedThreadKey(draftRedirect), key: draftId }+ : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef)+ ? handoffKey+ : serverThreadRef && serverThreadDraftId+ ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId }: null;- if (nextChatViewKey !== chatViewKey) {- setChatViewKey(nextChatViewKey);+ if (nextHandoffKey !== handoffKey) {+ setHandoffKey(nextHandoffKey);}const environmentHasDraftThreads = useComposerDraftStore((store) =>serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,@@ -110,43 +87,8 @@ export function ThreadRouteView({unlistedThreadDetail,draftThreadExists: draftThread !== null,});- const serverThreadStarted = threadHasStarted(serverThreadShell);const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;- useEffect(() => {- if (!inferredThreadRef || draftSession?.promotedTo) {- return;- }- markPromotedDraftThreadByRef(inferredThreadRef);- }, [draftSession?.promotedTo, inferredThreadRef]);-- useEffect(() => {- if (!canonicalThreadRef || background) {- return;- }- let cancelled = false;- void waitForDraftHeroTransition().then(() => {- if (cancelled) {- return;- }- void navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(canonicalThreadRef),- replace: true,- });- });- return () => {- cancelled = true;- };- }, [background, canonicalThreadRef, navigate]);-- useEffect(() => {- if (background || target.kind !== "draft" || draftSession || canonicalThreadRef) {- return;- }- void navigate({ to: "/", replace: true });- }, [background, canonicalThreadRef, draftSession, navigate, target.kind]);-useEffect(() => {if (target.kind !== "server" || !bootstrapComplete) {return;@@ -160,14 +102,8 @@ export function ThreadRouteView({}}, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);- useEffect(() => {- if (target.kind !== "server" || !serverThreadStarted || !draftThread) {- return;- }- finalizePromotedDraftThreadByRef(target.threadRef);- }, [draftThread, serverThreadStarted, target]);-let view: React.ReactNode = null;+ let redirect: React.ReactNode = null;if (target.kind === "draft") {if (draftSession) {view = (@@ -180,11 +116,30 @@ export function ThreadRouteView({forceExpandedMobileComposer/>);+ } else if (draftRedirect) {+ // Same slot and key as the server route renders, so the swap keeps this instance.+ view = (+ <ChatView+ key={target.draftId}+ environmentId={draftRedirect.environmentId}+ threadId={draftRedirect.threadId}+ routeKind="server"+ />+ );+ redirect = (+ <Navigate+ to="/$environmentId/$threadId"+ params={buildThreadRouteParams(draftRedirect)}+ replace+ />+ );+ } else {+ redirect = <Navigate to="/" replace />;}} else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {view = (<ChatView- key={nextChatViewKey?.key}+ key={nextHandoffKey?.key}environmentId={target.threadRef.environmentId}threadId={target.threadRef.threadId}routeKind="server"@@ -198,6 +153,7 @@ export function ThreadRouteView({inert={background}><BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>+ {background ? null : redirect}</SidebarInset>);}diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.tsindex 238cd866351..250c7790e07 100644--- a/apps/web/src/composerDraftStore.test.ts+++ b/apps/web/src/composerDraftStore.test.ts@@ -26,12 +26,14 @@ import {ProviderDriverKind,ProviderInstanceId,PROVIDER_SEND_TURN_MAX_ATTACHMENTS,+ RunId,ThreadId,type OrchestrationV2ThreadShell,type OrchestrationV2ShellSnapshot,type ModelSelection,type PreviewAnnotationPayload,type ProviderOptionSelection,+ type ScopedThreadRef,} from "@t3tools/contracts";import { createModelSelection } from "@t3tools/shared/model";@@ -81,7 +83,9 @@ import {clearBackgroundDraftSubmissionByRef,finalizePromotedDraftThreadByRef,markPromotedDraftThreadByRef,+ resolveDraftPromotionNavigationTarget,restoreFailedDraftThread,+ subscribeDraftThreadPromotion,type ComposerFileAttachment,type ComposerImageAttachment,composerFileNeedsReattach,@@ -89,6 +93,7 @@ import {useComposerDraftStore,DraftId,} from "./composerDraftStore";+import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition";import { insertInlineContextReference } from "./lib/composerContextReferences";import { terminalContextReference, threadContextRecord } from "./lib/composerContextRecords";import {@@ -164,6 +169,8 @@ function resetComposerDraftStore() {draftsByThreadKey: {},draftThreadsByThreadKey: {},logicalProjectDraftThreadKeyByLogicalProjectKey: {},+ backgroundSubmissionThreadKeys: {},+ promotedDraftRedirects: {},stickyModelSelectionByProvider: {},stickyOptionsByModelByProvider: {},stickyActiveProvider: null,@@ -1306,6 +1313,162 @@ function modelReconciliationHarness(};}+type PromotionShell = NonNullable<+ Parameters<typeof resolveDraftPromotionNavigationTarget>[0]["serverThread"]+>;++function draftPromotionHarness() {+ const tasks: Array<() => void> = [];+ const registry = AtomRegistry.make({+ scheduleTask: (task) => {+ tasks.push(task);+ return () => {};+ },+ });+ onTestFinished(() => registry.dispose());+ const flush = () => {+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();+ };+ const threadRefsAtom = Atom.make<ReadonlyArray<ScopedThreadRef>>([]);+ const shellAtoms = new Map<string, Atom.Writable<PromotionShell | null>>();+ const shellAtom = (ref: ScopedThreadRef) => {+ const key = scopedThreadKey(ref);+ let atom = shellAtoms.get(key);+ if (!atom) {+ atom = Atom.make<PromotionShell | null>(null);+ shellAtoms.set(key, atom);+ }+ return atom;+ };+ onTestFinished(+ subscribeDraftThreadPromotion({ registry, threadRefsAtom, threadShellAtom: shellAtom }),+ );+ flush();+ return {+ flush,+ arrive(ref: ScopedThreadRef, shell: PromotionShell | null = null) {+ registry.set(shellAtom(ref), shell);+ registry.set(threadRefsAtom, [...registry.get(threadRefsAtom), ref]);+ flush();+ },+ updateShell(ref: ScopedThreadRef, shell: PromotionShell) {+ registry.set(shellAtom(ref), shell);+ flush();+ },+ };+}++describe("composerDraftStore draft promotion", () => {+ const projectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, ProjectId.make("project-promotion"));+ const draftId = DraftId.make("draft-promotion");+ const threadId = ThreadId.make("thread-promotion");+ const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);+ const preparingRun = {+ runId: RunId.make("run-promotion"),+ status: "preparing" as const,+ requestedAt: "2026-03-29T00:00:00.000Z",+ startedAt: null,+ completedAt: null,+ assistantMessageId: null,+ };++ beforeEach(resetComposerDraftStore);++ it("stays on the draft until the server owns the send", () => {+ expect(+ resolveDraftPromotionNavigationTarget({+ serverThreadRef: threadRef,+ serverThread: { latestRun: preparingRun, latestUserMessageAt: null },+ backgroundSubmissionPending: false,+ }),+ ).toBeNull();+ expect(+ resolveDraftPromotionNavigationTarget({+ serverThreadRef: threadRef,+ serverThread: { latestRun: null, latestUserMessageAt: null },+ backgroundSubmissionPending: false,+ }),+ ).toBeNull();+ const persisted = { latestRun: preparingRun, latestUserMessageAt: "2026-03-29T00:00:00.000Z" };+ expect(+ resolveDraftPromotionNavigationTarget({+ serverThreadRef: threadRef,+ serverThread: persisted,+ backgroundSubmissionPending: false,+ }),+ ).toBe(threadRef);+ expect(+ resolveDraftPromotionNavigationTarget({+ serverThreadRef: threadRef,+ serverThread: persisted,+ backgroundSubmissionPending: true,+ }),+ ).toBeNull();+ });++ it("marks a draft promoting when its reserved thread arrives, then finalizes into it", async () => {+ const h = draftPromotionHarness();+ const store = useComposerDraftStore.getState();+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });+ store.setPrompt(draftId, "typed during setup");+ h.flush();+ expect(store.getDraftSession(draftId)?.promotedTo).toBeNull();++ h.arrive(threadRef, { latestRun: preparingRun, latestUserMessageAt: null });+ expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual(+ threadRef,+ );++ h.updateShell(threadRef, {+ latestRun: preparingRun,+ latestUserMessageAt: "2026-03-29T00:00:00.000Z",+ });+ await waitForDraftHeroTransition();++ const state = useComposerDraftStore.getState();+ expect(state.getDraftSession(draftId)).toBeNull();+ expect(state.getPromotedDraftRedirect(draftId)).toEqual(threadRef);+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("typed during setup");+ });++ it("holds a background submission on its draft until the send settles", async () => {+ const h = draftPromotionHarness();+ const store = useComposerDraftStore.getState();+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });+ beginBackgroundDraftSubmissionByRef(threadRef);+ h.arrive(threadRef, {+ latestRun: preparingRun,+ latestUserMessageAt: "2026-03-29T00:00:00.000Z",+ });+ await waitForDraftHeroTransition();+ expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual(+ threadRef,+ );++ clearBackgroundDraftSubmissionByRef(threadRef);+ h.flush();+ await waitForDraftHeroTransition();+ expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull();+ });++ it("does not finalize a draft whose send failed and was restored", async () => {+ const h = draftPromotionHarness();+ const store = useComposerDraftStore.getState();+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });+ const sent = useComposerDraftStore.getState().getDraftSession(draftId)!;+ h.arrive(threadRef, {+ latestRun: { ...preparingRun, status: "failed" as const },+ latestUserMessageAt: null,+ });+ restoreFailedDraftThread(draftId, sent, ThreadId.make("retry-thread"));+ h.flush();+ await waitForDraftHeroTransition();+ expect(useComposerDraftStore.getState().getDraftSession(draftId)?.threadId).toBe(+ "retry-thread",+ );+ });+});+describe("composerDraftStore modelSelection", () => {const threadId = ThreadId.make("thread-model-options");const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.tsindex 59188ac8d79..6ce4d4fd4cc 100644--- a/apps/web/src/composerDraftStore.ts+++ b/apps/web/src/composerDraftStore.ts@@ -49,6 +49,7 @@ import type {EnvironmentShellState,EnvironmentThreadShell,} from "@t3tools/client-runtime/state/shell";+import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition";import { getLocalStorageItem } from "./hooks/useLocalStorage";import { readThreadPreviewState } from "./previewStateStore";import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";@@ -416,6 +417,11 @@ interface ComposerDraftStoreState {draftThreadsByThreadKey: Record<string, DraftThreadState>;logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string>;backgroundSubmissionThreadKeys: Record<string, true>;+ /**+ * Where each finalized draft went, so `/draft/<id>` keeps leading to its thread (Back, an+ * "Open draft" toast) after the draft is gone. In memory only, one small entry per sent draft.+ */+ promotedDraftRedirects: Record<string, ScopedThreadRef>;rewindingThreadKeys: ReadonlySet<string>;stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;stickyOptionsByModelByProvider: Partial<@@ -430,6 +436,7 @@ interface ComposerDraftStoreState {getDraftSession: (draftId: DraftId) => DraftSessionState | null;getDraftSessionByRef: (threadRef: ScopedThreadRef) => DraftSessionState | null;getDraftIdByRef: (threadRef: ScopedThreadRef) => DraftId | null;+ getPromotedDraftRedirect: (draftId: DraftId) => ScopedThreadRef | null;getDraftThreadByRef: (threadRef: ScopedThreadRef) => DraftThreadState | null;getDraftThread: (threadRef: ComposerThreadTarget) => DraftThreadState | null;listDraftThreadKeys: () => string[];@@ -2393,6 +2400,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(draftThreadsByThreadKey: {},logicalProjectDraftThreadKeyByLogicalProjectKey: {},backgroundSubmissionThreadKeys: {},+ promotedDraftRedirects: {},rewindingThreadKeys: new Set<string>(),stickyModelSelectionByProvider: {},stickyOptionsByModelByProvider: {},@@ -2472,6 +2480,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(}return null;},+ getPromotedDraftRedirect: (draftId) => get().promotedDraftRedirects[draftId] ?? null,getDraftThread: (threadRef) => {if (typeof threadRef === "string") {return get().getDraftSession(DraftId.make(threadRef));@@ -2758,10 +2767,16 @@ const composerDraftStore = create<ComposerDraftStoreState>()(}set((state) => {const existing = state.draftThreadsByThreadKey[threadKey];- if (!existing || !isDraftThreadPromoting(existing)) {+ if (!existing?.promotedTo) {return state;}- return removeDraftThreadReferences(state, threadKey, existing.promotedTo ?? undefined);+ return {+ ...removeDraftThreadReferences(state, threadKey, existing.promotedTo),+ promotedDraftRedirects: {+ ...state.promotedDraftRedirects,+ [threadKey]: existing.promotedTo,+ },+ };});},clearDraftThread: (threadRef) => {@@ -4204,13 +4219,6 @@ export function clearBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef):});}-export function useBackgroundDraftSubmissionPending(threadRef: ScopedThreadRef | null): boolean {- const threadKey = threadRef ? scopedThreadKey(threadRef) : null;- return useComposerDraftStore(- (state) => threadKey !== null && state.backgroundSubmissionThreadKeys[threadKey] === true,- );-}-export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): void {useComposerDraftStore.setState((state) => {const removedThreadKeys = new Set<string>();@@ -4260,12 +4268,18 @@ export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): vo([threadKey]) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,),) as Record<string, true>;+ const nextPromotedDraftRedirects = Object.fromEntries(+ Object.entries(state.promotedDraftRedirects).filter(+ ([, promotedTo]) => promotedTo.environmentId !== environmentId,+ ),+ ) as Record<string, ScopedThreadRef>;return {draftsByThreadKey: nextDrafts,draftThreadsByThreadKey: nextDraftThreads,logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings,backgroundSubmissionThreadKeys: nextBackgroundSubmissionThreadKeys,+ promotedDraftRedirects: nextPromotedDraftRedirects,rewindingThreadKeys: new Set([...state.rewindingThreadKeys].filter((threadKey) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,@@ -4351,3 +4365,107 @@ export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): vo}clearBackgroundDraftSubmissionByRef(threadRef);}++type DraftPromotionShell = Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt">;++/** The server owns a draft's send once its message persisted or its run started or stopped. */+export function resolveDraftPromotionNavigationTarget(input: {+ serverThreadRef: ScopedThreadRef | null;+ serverThread: DraftPromotionShell | null | undefined;+ backgroundSubmissionPending: boolean;+}): ScopedThreadRef | null {+ if (input.backgroundSubmissionPending) {+ return null;+ }+ const latestRun = input.serverThread?.latestRun ?? null;+ const runStarted = latestRun?.startedAt != null;+ const startupStopped =+ latestRun?.status === "failed" ||+ latestRun?.status === "interrupted" ||+ latestRun?.status === "cancelled";+ const messagePersisted = input.serverThread?.latestUserMessageAt != null;+ return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;+}++/**+ * Drives every draft through promotion as server shells arrive: a draft whose reserved thread+ * appears on the server becomes promoting, and once the server owns its send (and any hero+ * transition has played) it finalizes into that thread. The draft route follows the redirect+ * that finalization records, so no route has to watch for these milestones.+ */+export function subscribeDraftThreadPromotion(input: {+ readonly registry: AtomRegistry.AtomRegistry;+ readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<DraftPromotionShell | null>;+}): () => void {+ // Only the promotion slices: prompt edits replace the store state on every keystroke.+ const promotionSlices = (state: ComposerDraftStoreState) => ({+ draftThreadsByThreadKey: state.draftThreadsByThreadKey,+ backgroundSubmissionThreadKeys: state.backgroundSubmissionThreadKeys,+ });+ const draftsAtom = Atom.make(promotionSlices(composerDraftStore.getState()));+ const unsubscribeDrafts = composerDraftStore.subscribe((state, previous) => {+ if (+ state.draftThreadsByThreadKey === previous.draftThreadsByThreadKey &&+ state.backgroundSubmissionThreadKeys === previous.backgroundSubmissionThreadKeys+ ) {+ return;+ }+ input.registry.set(draftsAtom, promotionSlices(state));+ });+ const threadKeysAtom = Atom.map(+ input.threadRefsAtom,+ (refs) => new Set(refs.map(scopedThreadKey)),+ );+ const milestonesAtom = Atom.make((get) => {+ const state = get(draftsAtom);+ const threadKeys = get(threadKeysAtom);+ const arrived: Array<readonly [DraftId, ScopedThreadRef]> = [];+ const owned: Array<readonly [DraftId, ScopedThreadRef]> = [];+ for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {+ const ref =+ draftThread.promotedTo ?? scopeThreadRef(draftThread.environmentId, draftThread.threadId);+ const threadKey = scopedThreadKey(ref);+ if (!threadKeys.has(threadKey)) continue;+ if (!draftThread.promotedTo) {+ arrived.push([DraftId.make(draftId), ref]);+ continue;+ }+ const target = resolveDraftPromotionNavigationTarget({+ serverThreadRef: ref,+ serverThread: get(input.threadShellAtom(ref)),+ backgroundSubmissionPending: state.backgroundSubmissionThreadKeys[threadKey] === true,+ });+ if (target) owned.push([DraftId.make(draftId), target]);+ }+ return { arrived, owned };+ });+ let disposed = false;+ const finalizing = new Set<DraftId>();+ const unsubscribeMilestones = input.registry.subscribe(+ milestonesAtom,+ ({ arrived, owned }) => {+ const store = composerDraftStore.getState();+ for (const [draftId, ref] of arrived) {+ store.markDraftThreadPromoting(draftId, ref);+ }+ for (const [draftId, ref] of owned) {+ if (finalizing.has(draftId)) continue;+ finalizing.add(draftId);+ void waitForDraftHeroTransition().then(() => {+ finalizing.delete(draftId);+ if (disposed) return;+ const current = composerDraftStore.getState().draftThreadsByThreadKey[draftId];+ if (!current || !scopedThreadRefsEqual(current.promotedTo, ref)) return;+ finalizePromotedDraftThreadByRef(ref);+ });+ }+ },+ { immediate: true },+ );+ return () => {+ disposed = true;+ unsubscribeMilestones();+ unsubscribeDrafts();+ };+}