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