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

ThreadRouteView.tsx

160 lines6.4 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import { Navigate, useNavigate } from "@tanstack/react-router";
3import { useEffect, useState } from "react";
4​
5import ChatView from "./ChatView";
6import { BackgroundThreadContext } from "./chat/backgroundThread";
7import { SidebarInset } from "./ui/sidebar";
8import { useComposerDraftStore } from "../composerDraftStore";
9import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
10import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities";
11import { useEnvironmentShellStatus } from "../state/shell";
12import { useEnvironmentThread } from "../state/threads";
13import {
14 buildThreadRouteParams,
15 isThreadRouteSnapshotAuthoritative,
16 resolveThreadRouteRenderState,
17 type ThreadRouteTarget,
18} from "../threadRoutes";
19​
20/**
21 * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`
22 * layout, since an element only survives a route swap when the same parent renders it. Draft
23 * promotion runs in the draft store; this only follows the redirect it leaves behind.
24 * `background` keeps the thread mounted, inert and in place under Settings or Usage.
25 */
26export function ThreadRouteView({
27 target,
28 background = false,
29}: {
30 target: ThreadRouteTarget;
31 background?: boolean;
32}) {
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 draftRedirect = useComposerDraftStore((store) =>
39 draftId === null ? null : store.getPromotedDraftRedirect(draftId),
40 );
41 const serverThreadRef = target.kind === "server" ? target.threadRef : null;
42 const serverThreadShell = useQuietThreadShell(serverThreadRef);
43 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
44 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
45 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
46 const draftThread = useComposerDraftStore((store) =>
47 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
48 );
49 // Reached from the sidebar before finalize, the thread still has its draft.
50 const serverThreadDraftId = useComposerDraftStore((store) =>
51 serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null,
52 );
53 // The ChatView that carried a draft keeps its key through the redirect to its thread, and only
54 // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView.
55 const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null);
56 const nextHandoffKey =
57 draftId !== null && draftSession === null && draftRedirect
58 ? handoffKey?.key === draftId
59 ? handoffKey
60 : { threadKey: scopedThreadKey(draftRedirect), key: draftId }
61 : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef)
62 ? handoffKey
63 : serverThreadRef && serverThreadDraftId
64 ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId }
65 : null;
66 if (nextHandoffKey !== handoffKey) {
67 setHandoffKey(nextHandoffKey);
68 }
69 const environmentHasDraftThreads = useComposerDraftStore((store) =>
70 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
71 );
72 // Until the shell lists the thread, its own load (HTTP, then the socket)
73 // decides whether it exists. Read only then: once listed, ChatView keeps
74 // this stream open and its updates need not re-render the route.
75 const unlistedThreadRef =
76 target.kind === "server" && serverThreadShell === null && draftThread === null
77 ? target.threadRef
78 : null;
79 const unlistedThreadDetail = useEnvironmentThread(
80 unlistedThreadRef?.environmentId ?? null,
81 unlistedThreadRef?.threadId ?? null,
82 );
83 const renderState = resolveThreadRouteRenderState({
84 bootstrapComplete,
85 serverThreadExists: serverThreadShell !== null,
86 serverThreadDeleted: serverThreadShell?.deletedAt != null,
87 unlistedThreadDetail,
88 draftThreadExists: draftThread !== null,
89 });
90 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
91​
92 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears pending file drops and navigates the router home once a server thread is confirmed missing
93 useEffect(() => {
94 if (target.kind !== "server" || !bootstrapComplete) {
95 return;
96 }
97 if (renderState === "missing") {
98 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
99 clearPendingFileDropsForThread(target.threadRef);
100 if (environmentHasAnyThreads && !background) {
101 void navigate({ to: "/", replace: true });
102 }
103 }
104 }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
105​
106 let view: React.ReactNode = null;
107 let redirect: React.ReactNode = null;
108 if (target.kind === "draft") {
109 if (draftSession) {
110 view = (
111 <ChatView
112 key={target.draftId}
113 draftId={target.draftId}
114 environmentId={draftSession.environmentId}
115 threadId={draftSession.threadId}
116 routeKind="draft"
117 forceExpandedMobileComposer
118 />
119 );
120 } else if (draftRedirect) {
121 // Same slot and key as the server route renders, so the swap keeps this instance.
122 view = (
123 <ChatView
124 key={target.draftId}
125 environmentId={draftRedirect.environmentId}
126 threadId={draftRedirect.threadId}
127 routeKind="server"
128 />
129 );
130 redirect = (
131 <Navigate
132 to="/$environmentId/$threadId"
133 params={buildThreadRouteParams(draftRedirect)}
134 replace
135 />
136 );
137 } else {
138 redirect = <Navigate to="/" replace />;
139 }
140 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
141 view = (
142 <ChatView
143 key={nextHandoffKey?.key}
144 environmentId={target.threadRef.environmentId}
145 threadId={target.threadRef.threadId}
146 routeKind="server"
147 />
148 );
149 }
150​
151 return (
152 <SidebarInset
153 className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh"
154 inert={background}
155 >
156 <BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
157 {background ? null : redirect}
158 </SidebarInset>
159 );