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