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 { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
18import { useEnvironmentShellStatus } from "../state/shell";
19import { useEnvironmentThread } from "../state/threads";
20import {
21 buildThreadRouteParams,
22 isThreadRouteSnapshotAuthoritative,
23 resolveThreadRouteRenderState,
24 type ThreadRouteTarget,
25} from "../threadRoutes";
26
27/** Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed. */
28export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
29 const navigate = useNavigate();
30 const draftId = target.kind === "draft" ? target.draftId : null;
31 const draftSession = useComposerDraftStore((store) =>
32 draftId === null ? null : store.getDraftSession(draftId),
33 );
34 const threadRefs = useThreadRefs();
35 // Promotion can begin before the server creates the reserved thread.
36 const inferredThreadRef = draftSession
37 ? (threadRefs.find(
38 (ref) =>
39 ref.environmentId === draftSession.environmentId &&
40 ref.threadId === draftSession.threadId,
41 ) ?? null)
42 : null;
43 const serverThreadRef: ScopedThreadRef | null =
44 target.kind === "server" ? target.threadRef : inferredThreadRef;
45 const serverThread = useQuietThreadShell(serverThreadRef);
46 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(
47 target.kind === "draft" ? serverThreadRef : null,
48 );
49 const canonicalThreadRef =
50 target.kind === "draft"
51 ? resolveDraftPromotionNavigationTarget({
52 serverThreadRef,
53 serverThread,
54 backgroundSubmissionPending,
55 })
56 : null;
57
58 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
59 const serverThreadShell = serverThread;
60 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
61 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
62 const draftThread = useComposerDraftStore((store) =>
63 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
64 );
65 const promotedDraftId = useComposerDraftStore((store) =>
66 target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
67 );
68 // Latch the key through promotion because the draft record disappears after the route swap.
69 const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
70 const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
71 const nextChatViewKey =
72 serverThreadKey === null
73 ? null
74 : chatViewKey?.threadKey === serverThreadKey
75 ? chatViewKey
76 : promotedDraftId
77 ? { threadKey: serverThreadKey, key: promotedDraftId }
78 : null;
79 if (nextChatViewKey !== chatViewKey) {
80 setChatViewKey(nextChatViewKey);
81 }
82 const environmentHasDraftThreads = useComposerDraftStore((store) =>
83 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
84 );
85 // Until the shell lists the thread, its own load (HTTP, then the socket)
86 // decides whether it exists. Read only then: once listed, ChatView keeps
87 // this stream open and its updates need not re-render the route.
88 const unlistedThreadRef =
89 target.kind === "server" && serverThreadShell === null && draftThread === null
90 ? target.threadRef
91 : null;
92 const unlistedThreadDetail = useEnvironmentThread(
93 unlistedThreadRef?.environmentId ?? null,
94 unlistedThreadRef?.threadId ?? null,
95 );
96 const renderState = resolveThreadRouteRenderState({
97 bootstrapComplete,
98 serverThreadExists: serverThreadShell !== null,
99 serverThreadDeleted: serverThreadShell?.deletedAt != null,
100 unlistedThreadDetail,
101 draftThreadExists: draftThread !== null,
102 });
103 const serverThreadStarted = threadHasStarted(serverThreadShell);
104 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
105
106 useEffect(() => {
107 if (!inferredThreadRef || draftSession?.promotedTo) {
108 return;
109 }
110 markPromotedDraftThreadByRef(inferredThreadRef);
111 }, [draftSession?.promotedTo, inferredThreadRef]);
112
113 useEffect(() => {
114 if (!canonicalThreadRef) {
115 return;
116 }
117 let cancelled = false;
118 void waitForDraftHeroTransition().then(() => {
119 if (cancelled) {
120 return;
121 }
122 void navigate({
123 to: "/$environmentId/$threadId",
124 params: buildThreadRouteParams(canonicalThreadRef),
125 replace: true,
126 });
127 });
128 return () => {
129 cancelled = true;
130 };
131 }, [canonicalThreadRef, navigate]);
132
133 useEffect(() => {
134 if (target.kind !== "draft" || draftSession || canonicalThreadRef) {
135 return;
136 }
137 void navigate({ to: "/", replace: true });
138 }, [canonicalThreadRef, draftSession, navigate, target.kind]);
139
140 useEffect(() => {
141 if (target.kind !== "server" || !bootstrapComplete) {
142 return;
143 }
144 if (renderState === "missing") {
145 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
146 clearPendingFileDropsForThread(target.threadRef);
147 if (environmentHasAnyThreads) {
148 void navigate({ to: "/", replace: true });
149 }
150 }
151 }, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
152
153 useEffect(() => {
154 if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
155 return;
156 }
157 finalizePromotedDraftThreadByRef(target.threadRef);
158 }, [draftThread, serverThreadStarted, target]);
159
160 let view: React.ReactNode = null;
161 if (target.kind === "draft") {
162 if (draftSession) {
163 view = (
164 <ChatView
165 key={target.draftId}
166 draftId={target.draftId}
167 environmentId={draftSession.environmentId}
168 threadId={draftSession.threadId}
169 routeKind="draft"
170 forceExpandedMobileComposer
171 />
172 );
173 }
174 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
175 view = (
176 <ChatView
177 key={nextChatViewKey?.key}
178 environmentId={target.threadRef.environmentId}
179 threadId={target.threadRef.threadId}
180 routeKind="server"
181 />
182 );
183 }
184
185 return (
186 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh">
187 {view}
188 </SidebarInset>
189 );
190}