Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadRouteView.tsx

203 lines7.3 KB

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 { BackgroundThreadContext } from "./chat/backgroundThread";
8import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
9import { waitForDraftHeroTransition } from "./chat/draftHeroTransition";
10import { SidebarInset } from "./ui/sidebar";
11import {
12 finalizePromotedDraftThreadByRef,
13 markPromotedDraftThreadByRef,
14 useBackgroundDraftSubmissionPending,
15 useComposerDraftStore,
16} from "../composerDraftStore";
17import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
18import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities";
19import { useEnvironmentShellStatus } from "../state/shell";
20import { useEnvironmentThread } from "../state/threads";
21import {
22 buildThreadRouteParams,
23 isThreadRouteSnapshotAuthoritative,
24 resolveThreadRouteRenderState,
25 type ThreadRouteTarget,
26} from "../threadRoutes";
27​
28/**
29 * Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed.
30 * `background` keeps the thread mounted, inert and in place under Settings or Usage.
31 */
32export function ThreadRouteView({
33 target,
34 background = false,
35}: {
36 target: ThreadRouteTarget;
37 background?: boolean;
38}) {
39 const navigate = useNavigate();
40 const draftId = target.kind === "draft" ? target.draftId : null;
41 const draftSession = useComposerDraftStore((store) =>
42 draftId === null ? null : store.getDraftSession(draftId),
43 );
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,
58 );
59 const canonicalThreadRef =
60 target.kind === "draft"
61 ? resolveDraftPromotionNavigationTarget({
62 serverThreadRef,
63 serverThread,
64 backgroundSubmissionPending,
65 })
66 : null;
67​
68 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
69 const serverThreadShell = serverThread;
70 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
71 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
72 const draftThread = useComposerDraftStore((store) =>
73 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
74 );
75 const promotedDraftId = useComposerDraftStore((store) =>
76 target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
77 );
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 }
92 const environmentHasDraftThreads = useComposerDraftStore((store) =>
93 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
94 );
95 // Until the shell lists the thread, its own load (HTTP, then the socket)
96 // decides whether it exists. Read only then: once listed, ChatView keeps
97 // this stream open and its updates need not re-render the route.
98 const unlistedThreadRef =
99 target.kind === "server" && serverThreadShell === null && draftThread === null
100 ? target.threadRef
101 : null;
102 const unlistedThreadDetail = useEnvironmentThread(
103 unlistedThreadRef?.environmentId ?? null,
104 unlistedThreadRef?.threadId ?? null,
105 );
106 const renderState = resolveThreadRouteRenderState({
107 bootstrapComplete,
108 serverThreadExists: serverThreadShell !== null,
109 serverThreadDeleted: serverThreadShell?.deletedAt != null,
110 unlistedThreadDetail,
111 draftThreadExists: draftThread !== null,
112 });
113 const serverThreadStarted = threadHasStarted(serverThreadShell);
114 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
115​
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​
150 useEffect(() => {
151 if (target.kind !== "server" || !bootstrapComplete) {
152 return;
153 }
154 if (renderState === "missing") {
155 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
156 clearPendingFileDropsForThread(target.threadRef);
157 if (environmentHasAnyThreads && !background) {
158 void navigate({ to: "/", replace: true });
159 }
160 }
161 }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
162​
163 useEffect(() => {
164 if (target.kind !== "server" || !serverThreadStarted || !draftThread) {
165 return;
166 }
167 finalizePromotedDraftThreadByRef(target.threadRef);
168 }, [draftThread, serverThreadStarted, target]);
169​
170 let view: React.ReactNode = null;
171 if (target.kind === "draft") {
172 if (draftSession) {
173 view = (
174 <ChatView
175 key={target.draftId}
176 draftId={target.draftId}
177 environmentId={draftSession.environmentId}
178 threadId={draftSession.threadId}
179 routeKind="draft"
180 forceExpandedMobileComposer
181 />
182 );
183 }
184 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
185 view = (
186 <ChatView
187 key={nextChatViewKey?.key}
188 environmentId={target.threadRef.environmentId}
189 threadId={target.threadRef.threadId}
190 routeKind="server"
191 />
192 );
193 }
194​
195 return (
196 <SidebarInset
197 className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh"
198 inert={background}
199 >
200 <BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
201 </SidebarInset>
202 );