Skip to content

Commit c9c880d

Browse files
refactor(web): drafts promote from the draft store, not from route effects
The thread route drove draft promotion through four effects: one marked a draft promoting once its reserved thread showed up, one navigated after the hero transition, one bounced an empty draft route home, and one finalized the draft once the server route showed a started thread. To find the reserved thread, the route subscribed to every thread ref in every environment, so it re-rendered whenever any thread anywhere was created or removed. It also latched the ChatView key with a setState during render so the draft's ChatView survived the route swap. subscribeDraftThreadPromotion, started once in appInit, now marks a draft promoting when its thread arrives and finalizes it once the server owns the send (after the hero transition). Finalizing records a redirect; the draft route renders the same keyed ChatView and a <Navigate> to the thread, and the thread route reuses that key while the redirect lasts. Redirects are dropped on route resolve once the route no longer shows the draft or its thread. resolveDraftPromotionNavigationTarget moves into the store with its tests. Effects: ThreadRouteView 5 -> 1. The kept effect clears pending sidebar file drops for a missing thread and leaves its route; it stays because the file-drop store change belongs to another slice. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 278588a commit c9c880d

6 files changed

Lines changed: 370 additions & 171 deletions

File tree

‎apps/web/src/appInit.tsx‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import { startGuideRunNotifications } from "./components/pullRequest/guide/PullR
2323
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
2424
import { resolveServerBackedAppDisplayName } from "./branding.logic";
2525
import { isElectron } from "./env";
26-
import { useComposerDraftStore } from "./composerDraftStore";
26+
import { subscribeDraftThreadPromotion, useComposerDraftStore } from "./composerDraftStore";
2727
import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
2828
import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
2929
import {
@@ -42,6 +42,7 @@ import { startProviderAuthDelivery } from "./providerAuthDelivery";
4242
import { getRouter, type AppRouter } from "./router";
4343
import { appAtomRegistry } from "./rpc/atomRegistry";
4444
import { primaryServerConfigAtom } from "./state/server";
45+
import { environmentThreadShells } from "./state/threads";
4546
import { resolveThreadRouteTarget } from "./threadRoutes";
4647

4748
/** Writes appearance settings onto the document, touching only the groups that changed. */
@@ -140,6 +141,22 @@ function startThreadOverlayRetention(router: AppRouter): void {
140141
});
141142
}
142143

144+
/**
145+
* Drafts promote as their server threads arrive, wherever the user is. The redirect a finalized
146+
* draft leaves only serves the route that shows that draft or its thread.
147+
*/
148+
function startDraftThreadPromotion(router: AppRouter): void {
149+
subscribeDraftThreadPromotion({
150+
registry: appAtomRegistry,
151+
threadShellAtom: environmentThreadShells.quietThreadShellAtom,
152+
threadRefsAtom: environmentThreadShells.threadRefsAtom,
153+
});
154+
router.subscribe("onResolved", () => {
155+
const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
156+
useComposerDraftStore.getState().retainPromotedDraftRedirectsForRoute(target);
157+
});
158+
}
159+
143160
/**
144161
* Starts every app-lifetime service once, before the first render, and returns the router.
145162
* They run for the life of the page, so their disposers are dropped here.
@@ -169,6 +186,7 @@ export function startAppServices(): AppRouter {
169186
startPreviewTitleRecording();
170187
startBrowserProfileReporting();
171188
startThreadOverlayRetention(router);
189+
startDraftThreadPromotion(router);
172190
startMainAppLocationTracking(router);
173191
startBackgroundThreadAnnouncements(appAtomRegistry, router);
174192
startThreadVisitedMigration(appAtomRegistry);

‎apps/web/src/components/ChatView.logic.test.ts‎

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ import {
5252
deriveComposerSendState,
5353
deriveLockedProvider,
5454
hasServerAcknowledgedLocalDispatch,
55-
resolveDraftPromotionNavigationTarget,
5655
waitForRevertedMessage,
5756
} from "./ChatView.logic";
5857

@@ -105,51 +104,6 @@ const readySession = {
105104
updatedAt: "2026-03-29T00:00:10.000Z",
106105
};
107106

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-
153107
describe("deriveComposerSendState", () => {
154108
it("keeps text sendable while excluding expired terminal pills", () => {
155109
const state = deriveComposerSendState({

‎apps/web/src/components/ChatView.logic.ts‎

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -449,24 +449,6 @@ export function resolveThreadSwitchTimeline<T extends readonly unknown[]>(input:
449449
return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey };
450450
}
451451

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-
470452
export function startNewThreadForProject(
471453
projectRef: ScopedProjectRef | null,
472454
handleNewThread: (projectRef: ScopedProjectRef) => Promise<unknown>,
@@ -948,7 +930,7 @@ export function recallCheckoutIsRepo(
948930
: sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd));
949931
}
950932

951-
export function threadHasStarted(thread: Thread | null | undefined): boolean {
933+
function threadHasStarted(thread: Thread | null | undefined): boolean {
952934
return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime));
953935
}
954936

Lines changed: 37 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,12 @@
1-
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2-
import type { ScopedThreadRef } from "@t3tools/contracts";
3-
import { useNavigate } from "@tanstack/react-router";
4-
import { useEffect, useState } from "react";
1+
import { Navigate, useNavigate } from "@tanstack/react-router";
2+
import { useEffect } from "react";
53

64
import ChatView from "./ChatView";
75
import { BackgroundThreadContext } from "./chat/backgroundThread";
8-
import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
9-
import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";
106
import { SidebarInset } from "./ui/sidebar";
11-
import {
12-
finalizePromotedDraftThreadByRef,
13-
markPromotedDraftThreadByRef,
14-
useBackgroundDraftSubmissionPending,
15-
useComposerDraftStore,
16-
} from "../composerDraftStore";
7+
import { useComposerDraftStore } from "../composerDraftStore";
178
import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
18-
import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
9+
import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";
1910
import { useEnvironmentShellStatus } from "../state/shell";
2011
import { useEnvironmentThread } from "../state/threads";
2112
import {
@@ -26,7 +17,9 @@ import {
2617
} from "../threadRoutes";
2718

2819
/**
29-
* Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed.
20+
* Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`
21+
* layout, since an element only survives a route swap when the same parent renders it. Draft
22+
* promotion runs in the draft store; this only follows the redirect it leaves behind.
3023
* `background` keeps the thread mounted, inert and in place under Settings or Usage.
3124
*/
3225
export function ThreadRouteView({
@@ -41,54 +34,23 @@ export function ThreadRouteView({
4134
const draftSession = useComposerDraftStore((store) =>
4235
draftId === null ? null : store.getDraftSession(draftId),
4336
);
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,
37+
const draftRedirect = useComposerDraftStore((store) =>
38+
draftId === null ? null : store.getPromotedDraftRedirect(draftId),
5839
);
59-
const canonicalThreadRef =
60-
target.kind === "draft"
61-
? resolveDraftPromotionNavigationTarget({
62-
serverThreadRef,
63-
serverThread,
64-
backgroundSubmissionPending,
65-
})
66-
: null;
67-
40+
const serverThreadRef = target.kind === "server" ? target.threadRef : null;
41+
const serverThreadShell = useQuietThreadShell(serverThreadRef);
6842
const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
69-
const serverThreadShell = serverThread;
7043
const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
7144
const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
7245
const draftThread = useComposerDraftStore((store) =>
7346
serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
7447
);
48+
// The ChatView that carried a draft keeps its identity once the thread route takes over.
7549
const promotedDraftId = useComposerDraftStore((store) =>
76-
target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
50+
serverThreadRef
51+
? (store.getDraftIdByRef(serverThreadRef) ?? store.getPromotedDraftIdByRef(serverThreadRef))
52+
: null,
7753
);
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 }
88-
: null;
89-
if (nextChatViewKey !== chatViewKey) {
90-
setChatViewKey(nextChatViewKey);
91-
}
9254
const environmentHasDraftThreads = useComposerDraftStore((store) =>
9355
serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
9456
);
@@ -110,43 +72,8 @@ export function ThreadRouteView({
11072
unlistedThreadDetail,
11173
draftThreadExists: draftThread !== null,
11274
});
113-
const serverThreadStarted = threadHasStarted(serverThreadShell);
11475
const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
11576

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-
15077
useEffect(() => {
15178
if (target.kind !== "server" || !bootstrapComplete) {
15279
return;
@@ -160,14 +87,8 @@ export function ThreadRouteView({
16087
}
16188
}, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
16289

163-
useEffect(() => {
164-
if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
165-
return;
166-
}
167-
finalizePromotedDraftThreadByRef(target.threadRef);
168-
}, [draftThread, serverThreadStarted, target]);
169-
17090
let view: React.ReactNode = null;
91+
let redirect: React.ReactNode = null;
17192
if (target.kind === "draft") {
17293
if (draftSession) {
17394
view = (
@@ -180,11 +101,30 @@ export function ThreadRouteView({
180101
forceExpandedMobileComposer
181102
/>
182103
);
104+
} else if (draftRedirect) {
105+
// Same slot and key as the server route renders, so the swap keeps this instance.
106+
view = (
107+
<ChatView
108+
key={target.draftId}
109+
environmentId={draftRedirect.environmentId}
110+
threadId={draftRedirect.threadId}
111+
routeKind="server"
112+
/>
113+
);
114+
redirect = (
115+
<Navigate
116+
to="/$environmentId/$threadId"
117+
params={buildThreadRouteParams(draftRedirect)}
118+
replace
119+
/>
120+
);
121+
} else {
122+
redirect = <Navigate to="/" replace />;
183123
}
184124
} else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
185125
view = (
186126
<ChatView
187-
key={nextChatViewKey?.key}
127+
key={promotedDraftId ?? undefined}
188128
environmentId={target.threadRef.environmentId}
189129
threadId={target.threadRef.threadId}
190130
routeKind="server"
@@ -198,6 +138,7 @@ export function ThreadRouteView({
198138
inert={background}
199139
>
200140
<BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
141+
{background ? null : redirect}
201142
</SidebarInset>
202143
);
203144
}

0 commit comments

Comments
 (0)