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

ThreadRouteView.tsx

215 lines9.0 KB

1import { useAtomValue } from "@effect/atom-react";
2import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
4import { visibilityParentKey } from "@t3tools/client-runtime/state/threads";
5import * as Option from "effect/Option";
6import { Navigate, useNavigate } from "@tanstack/react-router";
7import { useEffect, useState } from "react";
8​
9import ChatView from "./ChatView";
10import { BackgroundThreadContext } from "./chat/backgroundThread";
11import { SidebarInset } from "./ui/sidebar";
12import { useComposerDraftStore } from "../composerDraftStore";
13import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
14import {
15 useEnvironmentThreadRefs,
16 useAnyEnvironmentHiding,
17 useQuietThreadShell,
18} from "../state/entities";
19import { useEnvironmentShellStatus } from "../state/shell";
20import { environmentThreadShells, useEnvironmentThread } from "../state/threads";
21import {
22 buildThreadRouteParams,
23 isThreadRouteSnapshotAuthoritative,
24 resolveThreadRouteRenderState,
25 type ThreadRouteTarget,
26} from "../threadRoutes";
27​
28/**
29 * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat`
30 * layout, since an element only survives a route swap when the same parent renders it. Draft
31 * promotion runs in the draft store; this only follows the redirect it leaves behind.
32 * `background` keeps the thread mounted, inert and in place under Settings or Usage.
33 */
34export function ThreadRouteView({
35 target,
36 background = false,
37}: {
38 target: ThreadRouteTarget;
39 background?: boolean;
40}) {
41 const navigate = useNavigate();
42 const draftId = target.kind === "draft" ? target.draftId : null;
43 const draftSession = useComposerDraftStore((store) =>
44 draftId === null ? null : store.getDraftSession(draftId),
45 );
46 const draftRedirect = useComposerDraftStore((store) =>
47 draftId === null ? null : store.getPromotedDraftRedirect(draftId),
48 );
49 const serverThreadRef = target.kind === "server" ? target.threadRef : null;
50 const serverThreadShell = useQuietThreadShell(serverThreadRef);
51 const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null);
52 const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null);
53 const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus);
54 const draftThread = useComposerDraftStore((store) =>
55 serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
56 );
57 // Reached from the sidebar before finalize, the thread still has its draft.
58 const serverThreadDraftId = useComposerDraftStore((store) =>
59 serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null,
60 );
61 // The ChatView that carried a draft keeps its key through the redirect to its thread, and only
62 // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView.
63 const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null);
64 const nextHandoffKey =
65 draftId !== null && draftSession === null && draftRedirect
66 ? handoffKey?.key === draftId
67 ? handoffKey
68 : { threadKey: scopedThreadKey(draftRedirect), key: draftId }
69 : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef)
70 ? handoffKey
71 : serverThreadRef && serverThreadDraftId
72 ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId }
73 : null;
74 if (nextHandoffKey !== handoffKey) {
75 setHandoffKey(nextHandoffKey);
76 }
77 const environmentHasDraftThreads = useComposerDraftStore((store) =>
78 serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
79 );
80 // Until the shell lists the thread, its own load (HTTP, then the socket)
81 // decides whether it exists. Read only then: once listed, ChatView keeps
82 // this stream open and its updates need not re-render the route.
83 const unlistedThreadRef =
84 target.kind === "server" && serverThreadShell === null && draftThread === null
85 ? target.threadRef
86 : null;
87 const unlistedThreadDetail = useEnvironmentThread(
88 unlistedThreadRef?.environmentId ?? null,
89 unlistedThreadRef?.threadId ?? null,
90 );
91 const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
92 const unlistedThread = Option.getOrNull(Option.map(unlistedThreadDetail.data, (p) => p.thread));
93 const unlistedParentKey =
94 unlistedThreadRef === null || unlistedThread === null
95 ? null
96 : visibilityParentKey(unlistedThreadRef.environmentId, unlistedThread);
97 const unlistedParentShell = useQuietThreadShell(
98 unlistedParentKey === null ? null : parseThreadKey(unlistedParentKey),
99 );
100 const hidingAnywhere = useAnyEnvironmentHiding();
101 const draftRedirectShell = useQuietThreadShell(draftRedirect ?? null);
102 const hiddenByTagFilter = serverThreadRef !== null && hiddenKeys.has(threadKey(serverThreadRef));
103 // Cached detail can predate a tag or an archive, so while hiding an off-shell thread opens only
104 // as the child of a loaded, visible parent (lineage never changes); anything else stays closed.
105 const offShellBlocked =
106 hidingAnywhere &&
107 unlistedThreadRef !== null &&
108 !(
109 unlistedParentKey !== null &&
110 unlistedParentShell !== null &&
111 !hiddenKeys.has(unlistedParentKey)
112 );
113 const renderState = resolveThreadRouteRenderState({
114 bootstrapComplete,
115 serverThreadExists: serverThreadShell !== null,
116 serverThreadDeleted: serverThreadShell?.deletedAt != null,
117 unlistedThreadDetail,
118 draftThreadExists: draftThread !== null,
119 });
120 const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads;
121​
122 // 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
123 useEffect(() => {
124 if (target.kind !== "server" || !bootstrapComplete) {
125 return;
126 }
127 if (renderState === "missing") {
128 const { clearPendingFileDropsForThread } = useSidebarPendingFileDropStore.getState();
129 clearPendingFileDropsForThread(target.threadRef);
130 if (environmentHasAnyThreads && !background) {
131 void navigate({ to: "/", replace: true });
132 }
133 }
134 }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]);
135​
136 let view: React.ReactNode = null;
137 let redirect: React.ReactNode = null;
138 if (target.kind === "draft") {
139 if (
140 draftSession &&
141 hiddenKeys.has(
142 threadKey({ environmentId: draftSession.environmentId, threadId: draftSession.threadId }),
143 )
144 ) {
145 // A draft whose thread is already live and hidden (mid-promotion): never mount it.
146 redirect = <Navigate to="/" replace />;
147 } else if (draftSession) {
148 view = (
149 <ChatView
150 key={target.draftId}
151 draftId={target.draftId}
152 environmentId={draftSession.environmentId}
153 threadId={draftSession.threadId}
154 routeKind="draft"
155 forceExpandedMobileComposer
156 />
157 );
158 } else if (draftRedirect && hiddenKeys.has(threadKey(draftRedirect))) {
159 // Back to a promoted draft whose thread is now hidden: never mount it.
160 redirect = <Navigate to="/" replace />;
161 } else if (draftRedirect && hidingAnywhere && draftRedirectShell === null) {
162 // While hiding, a thread outside the live list is judged by the server route, unmounted here.
163 redirect = (
164 <Navigate
165 to="/$environmentId/$threadId"
166 params={buildThreadRouteParams(draftRedirect)}
167 replace
168 />
169 );
170 } else if (draftRedirect) {
171 // Same slot and key as the server route renders, so the swap keeps this instance.
172 view = (
173 <ChatView
174 key={target.draftId}
175 environmentId={draftRedirect.environmentId}
176 threadId={draftRedirect.threadId}
177 routeKind="server"
178 />
179 );
180 redirect = (
181 <Navigate
182 to="/$environmentId/$threadId"
183 params={buildThreadRouteParams(draftRedirect)}
184 replace
185 />
186 );
187 } else {
188 redirect = <Navigate to="/" replace />;
189 }
190 } else if (hiddenByTagFilter) {
191 redirect = <Navigate to="/" replace />;
192 } else if (offShellBlocked) {
193 // Before the shell bootstraps, a listed visible thread can still look off-shell.
194 if (bootstrapComplete && unlistedThread !== null) redirect = <Navigate to="/" replace />;
195 } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
196 view = (
197 <ChatView
198 key={nextHandoffKey?.key}
199 environmentId={target.threadRef.environmentId}
200 threadId={target.threadRef.threadId}
201 routeKind="server"
202 />
203 );
204 }
205​
206 return (
207 <SidebarInset
208 className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh"
209 inert={background}
210 >
211 <BackgroundThreadContext value={background}>{view}</BackgroundThreadContext>
212 {background ? null : redirect}
213 </SidebarInset>
214 );