Open History to see the last commit
1import { createFileRoute, useNavigate } from "@tanstack/react-router";
2import { useEffect } from "react";
3import ChatView from "../components/ChatView";
4import {
5 resolveDraftPromotionNavigationTarget,
6 threadHasStarted,
7} from "../components/ChatView.logic";
8import {
9 DraftId,
10 markPromotedDraftThreadByRef,
11 useBackgroundDraftSubmissionPending,
12 useComposerDraftStore,
13} from "../composerDraftStore";
14import { SidebarInset } from "../components/ui/sidebar";
15import { waitForDraftHeroTransition } from "../components/chat/draftHeroTransition";
16import { buildThreadRouteParams } from "../threadRoutes";
17import { useThread, useThreadRefs } from "../state/entities";
18
19function DraftChatThreadRouteView() {
20 const navigate = useNavigate();
21 const { draftId: rawDraftId } = Route.useParams();
22 const draftId = DraftId.make(rawDraftId);
23 const draftSession = useComposerDraftStore((store) => store.getDraftSession(draftId));
24 const threadRefs = useThreadRefs();
25 const inferredThreadRef = draftSession
26 ? (threadRefs.find(
27 (ref) =>
28 ref.environmentId === draftSession.environmentId &&
29 ref.threadId === draftSession.threadId,
30 ) ?? null)
31 : null;
32 const serverThreadRef = draftSession?.promotedTo ?? inferredThreadRef;
33 const serverThread = useThread(serverThreadRef);
34 const serverThreadStarted = threadHasStarted(serverThread);
35 const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(serverThreadRef);
36 const canonicalThreadRef = resolveDraftPromotionNavigationTarget({
37 serverThreadRef,
38 serverThreadStarted,
39 backgroundSubmissionPending,
40 });
41
42 useEffect(() => {
43 if (!inferredThreadRef || draftSession?.promotedTo) {
44 return;
45 }
46 markPromotedDraftThreadByRef(inferredThreadRef);
47 }, [draftSession?.promotedTo, inferredThreadRef]);
48
49 useEffect(() => {
50 if (!canonicalThreadRef) {
51 return;
52 }
53
54 let cancelled = false;
55 void waitForDraftHeroTransition().then(() => {
56 if (cancelled) {
57 return;
58 }
59 void navigate({
60 to: "/$environmentId/$threadId",
61 params: buildThreadRouteParams(canonicalThreadRef),
62 replace: true,
63 });
64 });
65
66 return () => {
67 cancelled = true;
68 };
69 }, [canonicalThreadRef, navigate]);
70
71 useEffect(() => {
72 if (draftSession || canonicalThreadRef) {
73 return;
74 }
75 void navigate({ to: "/", replace: true });
76 }, [canonicalThreadRef, draftSession, navigate]);
77
78 if (!draftSession) {
79 return null;
80 }
81
82 return (
83 <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">
84 <ChatView
85 draftId={draftId}
86 environmentId={draftSession.environmentId}
87 threadId={draftSession.threadId}
88 routeKind="draft"
89 forceExpandedMobileComposer
90 />
91 </SidebarInset>
92 );
93}
94
95export const Route = createFileRoute("/_chat/draft/$draftId")({
96 component: DraftChatThreadRouteView,
97});