The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): drafts promote from the draft store, not from route effects (#25615)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 17:11 UTC
5432d8e723c7ae28945ae5474435ac9f33de436a
6 files changed
+348
-168
apps/web/src/appInit.tsx
+8
-1
@@ -23,7 +23,7 @@ import { startGuideRunNotifications } from "./components/pullRequest/guide/PullR
23
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
24
import { resolveServerBackedAppDisplayName } from "./branding.logic";
25
import { isElectron } from "./env";
26
-import { useComposerDraftStore } from "./composerDraftStore";
26
+import { subscribeDraftThreadPromotion, useComposerDraftStore } from "./composerDraftStore";
27
import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
28
import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
29
import {
@@ -44,6 +44,7 @@ import { appAtomRegistry } from "./rpc/atomRegistry";
44
import { primaryServerConfigAtom } from "./state/server";
45
import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
46
import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
47
+import { environmentThreadShells } from "./state/threads";
48
import { resolveThreadRouteTarget } from "./threadRoutes";
49
50
/** Writes appearance settings onto the document, touching only the groups that changed. */
@@ -173,6 +174,12 @@ export function startAppServices(): AppRouter {
174
installChatRouteCommands(router);
175
registerOpenFavoriteEditorCommand();
176
startThreadOverlayRetention(router);
177
+ // Drafts promote as their server threads arrive, wherever the user is.
178
+ subscribeDraftThreadPromotion({
179
+ registry: appAtomRegistry,
180
+ threadShellAtom: environmentThreadShells.quietThreadShellAtom,
181
+ threadRefsAtom: environmentThreadShells.threadRefsAtom,
182
+ });
183
startMainAppLocationTracking(router);
184
startBackgroundThreadAnnouncements(appAtomRegistry, router);
185
startThreadVisitedMigration(appAtomRegistry);
apps/web/src/components/ChatView.logic.test.ts
-46
@@ -52,7 +52,6 @@ import {
52
deriveComposerSendState,
53
deriveLockedProvider,
54
hasServerAcknowledgedLocalDispatch,
55
- resolveDraftPromotionNavigationTarget,
55
waitForRevertedMessage,
56
} from "./ChatView.logic";
57
@@ -105,51 +104,6 @@ const readySession = {
104
updatedAt: "2026-03-29T00:00:10.000Z",
105
};
106
108
-describe("resolveDraftPromotionNavigationTarget", () => {
109
- const serverThreadRef = { environmentId, threadId };
110
- const preparingRun = {
111
- ...completedTurn,
112
- status: "preparing" as const,
113
- startedAt: null,
114
- completedAt: null,
115
- };
116
-
117
- it("stays on the draft until the server owns the send", () => {
118
- expect(
119
- resolveDraftPromotionNavigationTarget({
120
- serverThreadRef,
121
- serverThread: makeThread({ latestRun: preparingRun }),
122
- backgroundSubmissionPending: false,
123
- }),
124
- ).toBeNull();
125
- expect(
126
- resolveDraftPromotionNavigationTarget({
127
- serverThreadRef,
128
- serverThread: makeThread(),
129
- backgroundSubmissionPending: false,
130
- }),
131
- ).toBeNull();
132
- });
133
-
134
- it("promotes a persisted send while its worktree is still preparing", () => {
135
- const serverThread = makeThread({ latestRun: preparingRun, latestUserMessageAt: now });
136
- expect(
137
- resolveDraftPromotionNavigationTarget({
138
- serverThreadRef,
139
- serverThread,
140
- backgroundSubmissionPending: false,
141
- }),
142
- ).toBe(serverThreadRef);
143
- expect(
144
- resolveDraftPromotionNavigationTarget({
145
- serverThreadRef,
146
- serverThread,
147
- backgroundSubmissionPending: true,
148
- }),
149
- ).toBeNull();
150
- });
151
-});
152
-
107
describe("deriveComposerSendState", () => {
108
it("keeps text sendable while excluding expired terminal pills", () => {
109
const state = deriveComposerSendState({
apps/web/src/components/ChatView.logic.ts
+1
-19
@@ -449,24 +449,6 @@ export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input:
449
return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
450
}
451
452
-export function resolveDraftPromotionNavigationTarget(input: {
453
- serverThreadRef: ScopedThreadRef | null;
454
- serverThread: Pick<Thread, "latestRun" | "latestUserMessageAt"> | null | undefined;
455
- backgroundSubmissionPending: boolean;
456
-}): ScopedThreadRef | null {
457
- if (input.backgroundSubmissionPending) {
458
- return null;
459
- }
460
- const latestRun = input.serverThread?.latestRun ?? null;
461
- const runStarted = latestRun?.startedAt != null;
462
- const startupStopped =
463
- latestRun?.status === "failed" ||
464
- latestRun?.status === "interrupted" ||
465
- latestRun?.status === "cancelled";
466
- const messagePersisted = input.serverThread?.latestUserMessageAt != null;
467
- return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;
468
-}
469
-
452
export function startNewThreadForProject(
453
projectRef: ScopedProjectRef | null,
454
handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
@@ -948,7 +930,7 @@ export function recallCheckoutIsRepo(
930
: sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
931
}
932
951
-export function threadHasStarted(thread: Thread | null | undefined): boolean {
933
+function threadHasStarted(thread: Thread | null | undefined): boolean {
934
return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
935
}
936
apps/web/src/components/ThreadRouteView.tsx
+49
-93
@@ -1,21 +1,13 @@
1
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2
-import type { ScopedThreadRef } from "@t3tools/contracts";
3
-import { useNavigate } from "@tanstack/react-router";
2
+import { Navigate, useNavigate } from "@tanstack/react-router";
3
import { useEffect, useState } from "react";
4
5
import ChatView from "./ChatView";
6
import { BackgroundThreadContext } from "./chat/backgroundThread";
8
-import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
9
-import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";
7
import { SidebarInset } from "./ui/sidebar";
11
-import {
12
- finalizePromotedDraftThreadByRef,
13
- markPromotedDraftThreadByRef,
14
- useBackgroundDraftSubmissionPending,
15
- useComposerDraftStore,
16
-} from "../composerDraftStore";
8
+import { useComposerDraftStore } from "../composerDraftStore";
9
import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
18
-import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
10
+import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";
11
import { useEnvironmentShellStatus } from "../state/shell";
12
import { useEnvironmentThread } from "../state/threads";
13
import {
@@ -26,7 +18,9 @@ import {
18
} from "../threadRoutes";
19
20
/**
29
- * Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed.
21
+ * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`
22
+ * layout, since an element only survives a route swap when the same parent renders it. Draft
23
+ * promotion runs in the draft store; this only follows the redirect it leaves behind.
24
* `background` keeps the thread mounted, inert and in place under Settings or Usage.
25
*/
26
export function ThreadRouteView({
@@ -41,53 +35,36 @@ export function ThreadRouteView({
35
const draftSession = useComposerDraftStore((store) =>
36
draftId === null ? null : store.getDraftSession(draftId),
37
);
44
- const threadRefs = useThreadRefs();
45
- // Promotion can begin before the server creates the reserved thread.
46
- const inferredThreadRef = draftSession
47
- ? (threadRefs.find(
48
- (ref) =>
49
- ref.environmentId === draftSession.environmentId &&
50
- ref.threadId === draftSession.threadId,
51
- ) ?? null)
52
- : null;
53
- const serverThreadRef: ScopedThreadRef | null =
54
- target.kind === "server" ? target.threadRef : inferredThreadRef;
55
- const serverThread = useQuietThreadShell(serverThreadRef);
56
- const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
57
- target.kind === "draft" ? serverThreadRef : null,
38
+ const draftRedirect = useComposerDraftStore((store) =>
39
+ draftId === null ? null : store.getPromotedDraftRedirect(draftId),
40
);
59
- const canonicalThreadRef =
60
- target.kind === "draft"
61
- ? resolveDraftPromotionNavigationTarget({
62
- serverThreadRef,
63
- serverThread,
64
- backgroundSubmissionPending,
65
- })
66
- : null;
67
-
41
+ const serverThreadRef = target.kind === "server" ? target.threadRef : null;
42
+ const serverThreadShell = useQuietThreadShell(serverThreadRef);
43
const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
69
- const serverThreadShell = serverThread;
44
const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
45
const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
46
const draftThread = useComposerDraftStore((store) =>
47
serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
48
);
75
- const promotedDraftId = useComposerDraftStore((store) =>
76
- target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
49
+ // Reached from the sidebar before finalize, the thread still has its draft.
50
+ const serverThreadDraftId = useComposerDraftStore((store) =>
51
+ serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null,
52
);
78
- // Latch the key through promotion because the draft record disappears after the route swap.
79
- const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
80
- const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
81
- const nextChatViewKey =
82
- serverThreadKey === null
83
- ? null
84
- : chatViewKey?.threadKey === serverThreadKey
85
- ? chatViewKey
86
- : promotedDraftId
87
- ? { threadKey: serverThreadKey, key: promotedDraftId }
53
+ // The ChatView that carried a draft keeps its key through the redirect to its thread, and only
54
+ // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView.
55
+ const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null);
56
+ const nextHandoffKey =
57
+ draftId !== null && draftSession === null && draftRedirect
58
+ ? handoffKey?.key === draftId
59
+ ? handoffKey
60
+ : { threadKey: scopedThreadKey(draftRedirect), key: draftId }
61
+ : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef)
62
+ ? handoffKey
63
+ : serverThreadRef && serverThreadDraftId
64
+ ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId }
65
: null;
89
- if (nextChatViewKey !== chatViewKey) {
90
- setChatViewKey(nextChatViewKey);
66
+ if (nextHandoffKey !== handoffKey) {
67
+ setHandoffKey(nextHandoffKey);
68
}
69
const environmentHasDraftThreads = useComposerDraftStore((store) =>
70
serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
@@ -110,43 +87,8 @@ export function ThreadRouteView({
87
unlistedThreadDetail,
88
draftThreadExists: draftThread !== null,
89
});
113
- const serverThreadStarted = threadHasStarted(serverThreadShell);
90
const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
91
116
- useEffect(() => {
117
- if (!inferredThreadRef || draftSession?.promotedTo) {
118
- return;
119
- }
120
- markPromotedDraftThreadByRef(inferredThreadRef);
121
- }, [draftSession?.promotedTo, inferredThreadRef]);
122
-
123
- useEffect(() => {
124
- if (!canonicalThreadRef || background) {
125
- return;
126
- }
127
- let cancelled = false;
128
- void waitForDraftHeroTransition().then(() => {
129
- if (cancelled) {
130
- return;
131
- }
132
- void navigate({
133
- to: "/$environmentId/$threadId",
134
- params: buildThreadRouteParams(canonicalThreadRef),
135
- replace: true,
136
- });
137
- });
138
- return () => {
139
- cancelled = true;
140
- };
141
- }, [background, canonicalThreadRef, navigate]);
142
-
143
- useEffect(() => {
144
- if (background || target.kind !== "draft" || draftSession || canonicalThreadRef) {
145
- return;
146
- }
147
- void navigate({ to: "/", replace: true });
148
- }, [background, canonicalThreadRef, draftSession, navigate, target.kind]);
149
-
92
useEffect(() => {
93
if (target.kind !== "server" || !bootstrapComplete) {
94
return;
@@ -160,14 +102,8 @@ export function ThreadRouteView({
102
}
103
}, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
104
163
- useEffect(() => {
164
- if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
165
- return;
166
- }
167
- finalizePromotedDraftThreadByRef(target.threadRef);
168
- }, [draftThread, serverThreadStarted, target]);
169
-
105
let view: React.ReactNode = null;
106
+ let redirect: React.ReactNode = null;
107
if (target.kind === "draft") {
108
if (draftSession) {
109
view = (
@@ -180,11 +116,30 @@ export function ThreadRouteView({
116
forceExpandedMobileComposer
117
/>
118
);
119
+ } else if (draftRedirect) {
120
+ // Same slot and key as the server route renders, so the swap keeps this instance.
121
+ view = (
122
+ <ChatView
123
+ key={target.draftId}
124
+ environmentId={draftRedirect.environmentId}
125
+ threadId={draftRedirect.threadId}
126
+ routeKind="server"
127
+ />
128
+ );
129
+ redirect = (
130
+ <Navigate
131
+ to="/$environmentId/$threadId"
132
+ params={buildThreadRouteParams(draftRedirect)}
133
+ replace
134
+ />
135
+ );
136
+ } else {
137
+ redirect = <Navigate to="/" replace />;
138
}
139
} else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
140
view = (
141
<ChatView
187
- key={nextChatViewKey?.key}
142
+ key={nextHandoffKey?.key}
143
environmentId={target.threadRef.environmentId}
144
threadId={target.threadRef.threadId}
145
routeKind="server"
@@ -198,6 +153,7 @@ export function ThreadRouteView({
153
inert={background}
154
>
155
<BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
156
+ {background ? null : redirect}
157
</SidebarInset>
158
);
159
}
apps/web/src/composerDraftStore.test.ts
+163
@@ -26,12 +26,14 @@ import {
26
ProviderDriverKind,
27
ProviderInstanceId,
28
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
29
+ RunId,
30
ThreadId,
31
type OrchestrationV2ThreadShell,
32
type OrchestrationV2ShellSnapshot,
33
type ModelSelection,
34
type PreviewAnnotationPayload,
35
type ProviderOptionSelection,
36
+ type ScopedThreadRef,
37
} from "@t3tools/contracts";
38
import { createModelSelection } from "@t3tools/shared/model";
39
@@ -81,7 +83,9 @@ import {
83
clearBackgroundDraftSubmissionByRef,
84
finalizePromotedDraftThreadByRef,
85
markPromotedDraftThreadByRef,
86
+ resolveDraftPromotionNavigationTarget,
87
restoreFailedDraftThread,
88
+ subscribeDraftThreadPromotion,
89
type ComposerFileAttachment,
90
type ComposerImageAttachment,
91
composerFileNeedsReattach,
@@ -89,6 +93,7 @@ import {
93
useComposerDraftStore,
94
DraftId,
95
} from "./composerDraftStore";
96
+import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition";
97
import { insertInlineContextReference } from "./lib/composerContextReferences";
98
import { terminalContextReference, threadContextRecord } from "./lib/composerContextRecords";
99
import {
@@ -164,6 +169,8 @@ function resetComposerDraftStore() {
169
draftsByThreadKey: {},
170
draftThreadsByThreadKey: {},
171
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
172
+ backgroundSubmissionThreadKeys: {},
173
+ promotedDraftRedirects: {},
174
stickyModelSelectionByProvider: {},
175
stickyOptionsByModelByProvider: {},
176
stickyActiveProvider: null,
@@ -1306,6 +1313,162 @@ function modelReconciliationHarness(
1313
};
1314
}
1315
1316
+type PromotionShell = NonNullable<
1317
+ Parameters<typeof resolveDraftPromotionNavigationTarget>[0]["serverThread"]
1318
+>;
1319
+
1320
+function draftPromotionHarness() {
1321
+ const tasks: Array<() => void> = [];
1322
+ const registry = AtomRegistry.make({
1323
+ scheduleTask: (task) => {
1324
+ tasks.push(task);
1325
+ return () => {};
1326
+ },
1327
+ });
1328
+ onTestFinished(() => registry.dispose());
1329
+ const flush = () => {
1330
+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
1331
+ };
1332
+ const threadRefsAtom = Atom.make<ReadonlyArray<ScopedThreadRef>>([]);
1333
+ const shellAtoms = new Map<string, Atom.Writable<PromotionShell | null>>();
1334
+ const shellAtom = (ref: ScopedThreadRef) => {
1335
+ const key = scopedThreadKey(ref);
1336
+ let atom = shellAtoms.get(key);
1337
+ if (!atom) {
1338
+ atom = Atom.make<PromotionShell | null>(null);
1339
+ shellAtoms.set(key, atom);
1340
+ }
1341
+ return atom;
1342
+ };
1343
+ onTestFinished(
1344
+ subscribeDraftThreadPromotion({ registry, threadRefsAtom, threadShellAtom: shellAtom }),
1345
+ );
1346
+ flush();
1347
+ return {
1348
+ flush,
1349
+ arrive(ref: ScopedThreadRef, shell: PromotionShell | null = null) {
1350
+ registry.set(shellAtom(ref), shell);
1351
+ registry.set(threadRefsAtom, [...registry.get(threadRefsAtom), ref]);
1352
+ flush();
1353
+ },
1354
+ updateShell(ref: ScopedThreadRef, shell: PromotionShell) {
1355
+ registry.set(shellAtom(ref), shell);
1356
+ flush();
1357
+ },
1358
+ };
1359
+}
1360
+
1361
+describe("composerDraftStore draft promotion", () => {
1362
+ const projectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, ProjectId.make("project-promotion"));
1363
+ const draftId = DraftId.make("draft-promotion");
1364
+ const threadId = ThreadId.make("thread-promotion");
1365
+ const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
1366
+ const preparingRun = {
1367
+ runId: RunId.make("run-promotion"),
1368
+ status: "preparing" as const,
1369
+ requestedAt: "2026-03-29T00:00:00.000Z",
1370
+ startedAt: null,
1371
+ completedAt: null,
1372
+ assistantMessageId: null,
1373
+ };
1374
+
1375
+ beforeEach(resetComposerDraftStore);
1376
+
1377
+ it("stays on the draft until the server owns the send", () => {
1378
+ expect(
1379
+ resolveDraftPromotionNavigationTarget({
1380
+ serverThreadRef: threadRef,
1381
+ serverThread: { latestRun: preparingRun, latestUserMessageAt: null },
1382
+ backgroundSubmissionPending: false,
1383
+ }),
1384
+ ).toBeNull();
1385
+ expect(
1386
+ resolveDraftPromotionNavigationTarget({
1387
+ serverThreadRef: threadRef,
1388
+ serverThread: { latestRun: null, latestUserMessageAt: null },
1389
+ backgroundSubmissionPending: false,
1390
+ }),
1391
+ ).toBeNull();
1392
+ const persisted = { latestRun: preparingRun, latestUserMessageAt: "2026-03-29T00:00:00.000Z" };
1393
+ expect(
1394
+ resolveDraftPromotionNavigationTarget({
1395
+ serverThreadRef: threadRef,
1396
+ serverThread: persisted,
1397
+ backgroundSubmissionPending: false,
1398
+ }),
1399
+ ).toBe(threadRef);
1400
+ expect(
1401
+ resolveDraftPromotionNavigationTarget({
1402
+ serverThreadRef: threadRef,
1403
+ serverThread: persisted,
1404
+ backgroundSubmissionPending: true,
1405
+ }),
1406
+ ).toBeNull();
1407
+ });
1408
+
1409
+ it("marks a draft promoting when its reserved thread arrives, then finalizes into it", async () => {
1410
+ const h = draftPromotionHarness();
1411
+ const store = useComposerDraftStore.getState();
1412
+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });
1413
+ store.setPrompt(draftId, "typed during setup");
1414
+ h.flush();
1415
+ expect(store.getDraftSession(draftId)?.promotedTo).toBeNull();
1416
+
1417
+ h.arrive(threadRef, { latestRun: preparingRun, latestUserMessageAt: null });
1418
+ expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual(
1419
+ threadRef,
1420
+ );
1421
+
1422
+ h.updateShell(threadRef, {
1423
+ latestRun: preparingRun,
1424
+ latestUserMessageAt: "2026-03-29T00:00:00.000Z",
1425
+ });
1426
+ await waitForDraftHeroTransition();
1427
+
1428
+ const state = useComposerDraftStore.getState();
1429
+ expect(state.getDraftSession(draftId)).toBeNull();
1430
+ expect(state.getPromotedDraftRedirect(draftId)).toEqual(threadRef);
1431
+ expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("typed during setup");
1432
+ });
1433
+
1434
+ it("holds a background submission on its draft until the send settles", async () => {
1435
+ const h = draftPromotionHarness();
1436
+ const store = useComposerDraftStore.getState();
1437
+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });
1438
+ beginBackgroundDraftSubmissionByRef(threadRef);
1439
+ h.arrive(threadRef, {
1440
+ latestRun: preparingRun,
1441
+ latestUserMessageAt: "2026-03-29T00:00:00.000Z",
1442
+ });
1443
+ await waitForDraftHeroTransition();
1444
+ expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual(
1445
+ threadRef,
1446
+ );
1447
+
1448
+ clearBackgroundDraftSubmissionByRef(threadRef);
1449
+ h.flush();
1450
+ await waitForDraftHeroTransition();
1451
+ expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull();
1452
+ });
1453
+
1454
+ it("does not finalize a draft whose send failed and was restored", async () => {
1455
+ const h = draftPromotionHarness();
1456
+ const store = useComposerDraftStore.getState();
1457
+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });
1458
+ const sent = useComposerDraftStore.getState().getDraftSession(draftId)!;
1459
+ h.arrive(threadRef, {
1460
+ latestRun: { ...preparingRun, status: "failed" as const },
1461
+ latestUserMessageAt: null,
1462
+ });
1463
+ restoreFailedDraftThread(draftId, sent, ThreadId.make("retry-thread"));
1464
+ h.flush();
1465
+ await waitForDraftHeroTransition();
1466
+ expect(useComposerDraftStore.getState().getDraftSession(draftId)?.threadId).toBe(
1467
+ "retry-thread",
1468
+ );
1469
+ });
1470
+});
1471
+
1472
describe("composerDraftStore modelSelection", () => {
1473
const threadId = ThreadId.make("thread-model-options");
1474
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
apps/web/src/composerDraftStore.ts
+127
-9
@@ -49,6 +49,7 @@ import type {
49
EnvironmentShellState,
50
EnvironmentThreadShell,
51
} from "@t3tools/client-runtime/state/shell";
52
+import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition";
53
import { getLocalStorageItem } from "./hooks/useLocalStorage";
54
import { readThreadPreviewState } from "./previewStateStore";
55
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
@@ -416,6 +417,11 @@ interface ComposerDraftStoreState {
417
draftThreadsByThreadKey: Record<string, DraftThreadState>;
418
logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string>;
419
backgroundSubmissionThreadKeys: Record<string, true>;
420
+ /**
421
+ * Where each finalized draft went, so `/draft/<id>` keeps leading to its thread (Back, an
422
+ * "Open draft" toast) after the draft is gone. In memory only, one small entry per sent draft.
423
+ */
424
+ promotedDraftRedirects: Record<string, ScopedThreadRef>;
425
rewindingThreadKeys: ReadonlySet<string>;
426
stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
427
stickyOptionsByModelByProvider: Partial<
@@ -430,6 +436,7 @@ interface ComposerDraftStoreState {
436
getDraftSession: (draftId: DraftId) => DraftSessionState | null;
437
getDraftSessionByRef: (threadRef: ScopedThreadRef) => DraftSessionState | null;
438
getDraftIdByRef: (threadRef: ScopedThreadRef) => DraftId | null;
439
+ getPromotedDraftRedirect: (draftId: DraftId) => ScopedThreadRef | null;
440
getDraftThreadByRef: (threadRef: ScopedThreadRef) => DraftThreadState | null;
441
getDraftThread: (threadRef: ComposerThreadTarget) => DraftThreadState | null;
442
listDraftThreadKeys: () => string[];
@@ -2393,6 +2400,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
2400
draftThreadsByThreadKey: {},
2401
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
2402
backgroundSubmissionThreadKeys: {},
2403
+ promotedDraftRedirects: {},
2404
rewindingThreadKeys: new Set<string>(),
2405
stickyModelSelectionByProvider: {},
2406
stickyOptionsByModelByProvider: {},
@@ -2472,6 +2480,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
2480
}
2481
return null;
2482
},
2483
+ getPromotedDraftRedirect: (draftId) => get().promotedDraftRedirects[draftId] ?? null,
2484
getDraftThread: (threadRef) => {
2485
if (typeof threadRef === "string") {
2486
return get().getDraftSession(DraftId.make(threadRef));
@@ -2758,10 +2767,16 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
2767
}
2768
set((state) => {
2769
const existing = state.draftThreadsByThreadKey[threadKey];
2761
- if (!existing || !isDraftThreadPromoting(existing)) {
2770
+ if (!existing?.promotedTo) {
2771
return state;
2772
}
2764
- return removeDraftThreadReferences(state, threadKey, existing.promotedTo ?? undefined);
2773
+ return {
2774
+ ...removeDraftThreadReferences(state, threadKey, existing.promotedTo),
2775
+ promotedDraftRedirects: {
2776
+ ...state.promotedDraftRedirects,
2777
+ [threadKey]: existing.promotedTo,
2778
+ },
2779
+ };
2780
});
2781
},
2782
clearDraftThread: (threadRef) => {
@@ -4204,13 +4219,6 @@ export function clearBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef):
4219
});
4220
}
4221
4207
-export function useBackgroundDraftSubmissionPending(threadRef: ScopedThreadRef | null): boolean {
4208
- const threadKey = threadRef ? scopedThreadKey(threadRef) : null;
4209
- return useComposerDraftStore(
4210
- (state) => threadKey !== null && state.backgroundSubmissionThreadKeys[threadKey] === true,
4211
- );
4212
-}
4213
-
4222
export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): void {
4223
useComposerDraftStore.setState((state) => {
4224
const removedThreadKeys = new Set<string>();
@@ -4260,12 +4268,18 @@ export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): vo
4268
([threadKey]) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,
4269
),
4270
) as Record<string, true>;
4271
+ const nextPromotedDraftRedirects = Object.fromEntries(
4272
+ Object.entries(state.promotedDraftRedirects).filter(
4273
+ ([, promotedTo]) => promotedTo.environmentId !== environmentId,
4274
+ ),
4275
+ ) as Record<string, ScopedThreadRef>;
4276
4277
return {
4278
draftsByThreadKey: nextDrafts,
4279
draftThreadsByThreadKey: nextDraftThreads,
4280
logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings,
4281
backgroundSubmissionThreadKeys: nextBackgroundSubmissionThreadKeys,
4282
+ promotedDraftRedirects: nextPromotedDraftRedirects,
4283
rewindingThreadKeys: new Set(
4284
[...state.rewindingThreadKeys].filter(
4285
(threadKey) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,
@@ -4351,3 +4365,107 @@ export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): vo
4365
}
4366
clearBackgroundDraftSubmissionByRef(threadRef);
4367
}
4368
+
4369
+type DraftPromotionShell = Pick<EnvironmentThreadShell, "latestRun" | "latestUserMessageAt">;
4370
+
4371
+/** The server owns a draft's send once its message persisted or its run started or stopped. */
4372
+export function resolveDraftPromotionNavigationTarget(input: {
4373
+ serverThreadRef: ScopedThreadRef | null;
4374
+ serverThread: DraftPromotionShell | null | undefined;
4375
+ backgroundSubmissionPending: boolean;
4376
+}): ScopedThreadRef | null {
4377
+ if (input.backgroundSubmissionPending) {
4378
+ return null;
4379
+ }
4380
+ const latestRun = input.serverThread?.latestRun ?? null;
4381
+ const runStarted = latestRun?.startedAt != null;
4382
+ const startupStopped =
4383
+ latestRun?.status === "failed" ||
4384
+ latestRun?.status === "interrupted" ||
4385
+ latestRun?.status === "cancelled";
4386
+ const messagePersisted = input.serverThread?.latestUserMessageAt != null;
4387
+ return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null;
4388
+}
4389
+
4390
+/**
4391
+ * Drives every draft through promotion as server shells arrive: a draft whose reserved thread
4392
+ * appears on the server becomes promoting, and once the server owns its send (and any hero
4393
+ * transition has played) it finalizes into that thread. The draft route follows the redirect
4394
+ * that finalization records, so no route has to watch for these milestones.
4395
+ */
4396
+export function subscribeDraftThreadPromotion(input: {
4397
+ readonly registry: AtomRegistry.AtomRegistry;
4398
+ readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
4399
+ readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<DraftPromotionShell | null>;
4400
+}): () => void {
4401
+ // Only the promotion slices: prompt edits replace the store state on every keystroke.
4402
+ const promotionSlices = (state: ComposerDraftStoreState) => ({
4403
+ draftThreadsByThreadKey: state.draftThreadsByThreadKey,
4404
+ backgroundSubmissionThreadKeys: state.backgroundSubmissionThreadKeys,
4405
+ });
4406
+ const draftsAtom = Atom.make(promotionSlices(composerDraftStore.getState()));
4407
+ const unsubscribeDrafts = composerDraftStore.subscribe((state, previous) => {
4408
+ if (
4409
+ state.draftThreadsByThreadKey === previous.draftThreadsByThreadKey &&
4410
+ state.backgroundSubmissionThreadKeys === previous.backgroundSubmissionThreadKeys
4411
+ ) {
4412
+ return;
4413
+ }
4414
+ input.registry.set(draftsAtom, promotionSlices(state));
4415
+ });
4416
+ const threadKeysAtom = Atom.map(
4417
+ input.threadRefsAtom,
4418
+ (refs) => new Set(refs.map(scopedThreadKey)),
4419
+ );
4420
+ const milestonesAtom = Atom.make((get) => {
4421
+ const state = get(draftsAtom);
4422
+ const threadKeys = get(threadKeysAtom);
4423
+ const arrived: Array<readonly [DraftId, ScopedThreadRef]> = [];
4424
+ const owned: Array<readonly [DraftId, ScopedThreadRef]> = [];
4425
+ for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
4426
+ const ref =
4427
+ draftThread.promotedTo ?? scopeThreadRef(draftThread.environmentId, draftThread.threadId);
4428
+ const threadKey = scopedThreadKey(ref);
4429
+ if (!threadKeys.has(threadKey)) continue;
4430
+ if (!draftThread.promotedTo) {
4431
+ arrived.push([DraftId.make(draftId), ref]);
4432
+ continue;
4433
+ }
4434
+ const target = resolveDraftPromotionNavigationTarget({
4435
+ serverThreadRef: ref,
4436
+ serverThread: get(input.threadShellAtom(ref)),
4437
+ backgroundSubmissionPending: state.backgroundSubmissionThreadKeys[threadKey] === true,
4438
+ });
4439
+ if (target) owned.push([DraftId.make(draftId), target]);
4440
+ }
4441
+ return { arrived, owned };
4442
+ });
4443
+ let disposed = false;
4444
+ const finalizing = new Set<DraftId>();
4445
+ const unsubscribeMilestones = input.registry.subscribe(
4446
+ milestonesAtom,
4447
+ ({ arrived, owned }) => {
4448
+ const store = composerDraftStore.getState();
4449
+ for (const [draftId, ref] of arrived) {
4450
+ store.markDraftThreadPromoting(draftId, ref);
4451
+ }
4452
+ for (const [draftId, ref] of owned) {
4453
+ if (finalizing.has(draftId)) continue;
4454
+ finalizing.add(draftId);
4455
+ void waitForDraftHeroTransition().then(() => {
4456
+ finalizing.delete(draftId);
4457
+ if (disposed) return;
4458
+ const current = composerDraftStore.getState().draftThreadsByThreadKey[draftId];
4459
+ if (!current || !scopedThreadRefsEqual(current.promotedTo, ref)) return;
4460
+ finalizePromotedDraftThreadByRef(ref);
4461
+ });
4462
+ }
4463
+ },
4464
+ { immediate: true },
4465
+ );
4466
+ return () => {
4467
+ disposed = true;
4468
+ unsubscribeMilestones();
4469
+ unsubscribeDrafts();
4470
+ };
4471
+}