Open History to see the last commit
1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3import { useNavigate } from "@tanstack/react-router";
4import { useEffect, useState } from "react";
5
6import ChatView from "./ChatView";
7import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
8import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";
9import { SidebarInset } from "./ui/sidebar";
10import {
11 finalizePromotedDraftThreadByRef,
12 markPromotedDraftThreadByRef,
13 useBackgroundDraftSubmissionPending,
14 useComposerDraftStore,
15} from "../composerDraftStore";
16import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
17import {
18 useEnvironmentThreadRefs,
19 useThread,
20 useThreadDetail,
21 useThreadRefs,
22 useThreadShell,
23 useThreadStatus,
24} from "../state/entities";
25import { useEnvironmentQuery } from "../state/query";
26import { environmentShell } from "../state/shell";
27import {
28 buildThreadRouteParams,
29 resolveThreadRouteRenderState,
30 type ThreadRouteTarget,
31} from "../threadRoutes";
32import { resolveThreadSyncPhase } from "../threadSync";
33
34/**
35 * The single chat surface behind both `/draft/$draftId` and
36 * `/$environmentId/$threadId`. Each draft gets its own ChatView instance (so
37 * a background send's state stays with the draft it came from), and that
38 * instance carries the draft through its promotion to a server thread: the
39 * thread route keeps keying by the draft id while the draft record exists,
40 * so the route swap only changes props and the timeline never paints an
41 * empty frame. Plain server threads are unkeyed, so navigating between them
42 * reuses one instance as ChatView expects.
43 *
44 * Rendered by the `_chat` layout rather than by the two leaf routes, since
45 * an element only survives a route swap when the same parent renders it.
46 */
47export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
48 const navigate = useNavigate();
49 const draftId = target.kind === "draft" ? target.draftId : null;
50 const draftSession = useComposerDraftStore((store) =>
51 draftId === null ? null : store.getDraftSession(draftId),
52 );
53 const threadRefs = useThreadRefs();
54 // The server thread this view is about: the route's own ref, or the draft's
55 // reserved ref once the server knows it.
56 const inferredThreadRef = draftSession
57 ? (threadRefs.find(
58 (ref) =>
59 ref.environmentId === draftSession.environmentId &&
60 ref.threadId === draftSession.threadId,
61 ) ?? null)
62 : null;
63 const serverThreadRef: ScopedThreadRef | null =
64 target.kind === "server" ? target.threadRef : (draftSession?.promotedTo ?? inferredThreadRef);
65 const serverThread = useThread(serverThreadRef);
66 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
67 target.kind === "draft" ? serverThreadRef : null,
68 );
69 const canonicalThreadRef =
70 target.kind === "draft"
71 ? resolveDraftPromotionNavigationTarget({
72 serverThreadRef,
73 serverThread,
74 backgroundSubmissionPending,
75 })
76 : null;
77
78 const shell = useEnvironmentQuery(
79 serverThreadRef === null ? null : environmentShell.stateAtom(serverThreadRef.environmentId),
80 );
81 const serverThreadShell = useThreadShell(serverThreadRef);
82 const serverThreadDetail = useThreadDetail(serverThreadRef);
83 const serverThreadStatus = useThreadStatus(serverThreadRef);
84 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
85 const bootstrapComplete = shell.data?.snapshot._tag === "Some";
86 const draftThread = useComposerDraftStore((store) =>
87 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
88 );
89 const promotedDraftId = useComposerDraftStore((store) =>
90 target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
91 );
92 // The draft record is removed once the promoted thread has started, which
93 // is after the route swap. Latch the key so the element that carried the
94 // draft keeps its identity for as long as this thread stays on screen.
95 const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
96 const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
97 const nextChatViewKey =
98 serverThreadKey === null
99 ? null
100 : chatViewKey?.threadKey === serverThreadKey
101 ? chatViewKey
102 : promotedDraftId
103 ? { threadKey: serverThreadKey, key: promotedDraftId }
104 : null;
105 if (nextChatViewKey !== chatViewKey) {
106 setChatViewKey(nextChatViewKey);
107 }
108 const environmentHasDraftThreads = useComposerDraftStore((store) =>
109 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
110 );
111 const renderState = resolveThreadRouteRenderState({
112 bootstrapComplete,
113 serverThreadShellExists: serverThreadShell !== null,
114 serverThreadDetailExists: serverThreadDetail !== null,
115 serverThreadDetailDeleted: serverThreadStatus === "deleted",
116 draftThreadExists: draftThread !== null,
117 });
118 const threadSyncPhase = resolveThreadSyncPhase({
119 detailExists: serverThreadDetail !== null,
120 shellExists: serverThreadShell !== null,
121 status: serverThreadStatus,
122 });
123 const serverThreadStarted = threadHasStarted(serverThreadDetail);
124 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
125
126 useEffect(() => {
127 if (!inferredThreadRef || draftSession?.promotedTo) {
128 return;
129 }
130 markPromotedDraftThreadByRef(inferredThreadRef);
131 }, [draftSession?.promotedTo, inferredThreadRef]);
132
133 useEffect(() => {
134 if (!canonicalThreadRef) {
135 return;
136 }
137 let cancelled = false;
138 void waitForDraftHeroTransition().then(() => {
139 if (cancelled) {
140 return;
141 }
142 void navigate({
143 to: "/$environmentId/$threadId",
144 params: buildThreadRouteParams(canonicalThreadRef),
145 replace: true,
146 });
147 });
148 return () => {
149 cancelled = true;
150 };
151 }, [canonicalThreadRef, navigate]);
152
153 useEffect(() => {
154 if (target.kind !== "draft" || draftSession || canonicalThreadRef) {
155 return;
156 }
157 void navigate({ to: "/", replace: true });
158 }, [canonicalThreadRef, draftSession, navigate, target.kind]);
159
160 useEffect(() => {
161 if (target.kind !== "server" || !bootstrapComplete) {
162 return;
163 }
164 // Navigation already resolved onto this path, so a drop aimed here
165 // passed its landing check; once the thread reads as missing it can
166 // never be attached, release it even when there is nowhere to redirect.
167 if (renderState === "missing") {
168 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
169 clearPendingFileDropsForThread(target.threadRef);
170 if (environmentHasAnyThreads) {
171 void navigate({ to: "/", replace: true });
172 }
173 }
174 }, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
175
176 useEffect(() => {
177 if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
178 return;
179 }
180 finalizePromotedDraftThreadByRef(target.threadRef);
181 }, [draftThread, serverThreadStarted, target]);
182
183 let view: React.ReactNode = null;
184 if (target.kind === "draft") {
185 if (draftSession) {
186 view = (
187 <ChatView
188 key={target.draftId}
189 draftId={target.draftId}
190 environmentId={draftSession.environmentId}
191 threadId={draftSession.threadId}
192 routeKind="draft"
193 forceExpandedMobileComposer
194 />
195 );
196 }
197 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
198 view = (
199 <ChatView
200 {...(nextChatViewKey ? { key: nextChatViewKey.key } : {})}
201 environmentId={target.threadRef.environmentId}
202 threadId={target.threadRef.threadId}
203 routeKind="server"
204 threadSyncPhase={threadSyncPhase}
205 />
206 );
207 }
208
209 return (
210 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh">
211 {view}
212 </SidebarInset>
213 );
214}