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

assistantCitationNavigation.ts

174 lines6.0 KB

1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { pipe } from "effect/Function";
3import type {
4 AssistantCitation,
5 OrchestrationV2ThreadShell,
6 ScopedThreadRef,
7 ThreadId,
8} from "@t3tools/contracts";
9import { useRouter, type AnyRouter, type ParsedLocation } from "@tanstack/react-router";
10import {
11 formatAssistantCitationHref,
12 parseAssistantCitationHref,
13} from "@t3tools/shared/assistantCitations";
14import * as Base64Url from "effect/encoding/Base64Url";
15import * as Result from "effect/Result";
16import { useEffect } from "react";
17​
18import { useRightPanelStore } from "../rightPanelStore";
19import { useQuietThreadShell } from "~/state/entities";
20import { randomUUID } from "./utils";
21​
22declare module "@tanstack/react-router" {
23 interface HistoryState {
24 assistantCitationActivation?: string;
25 }
27​
28const CITATION_HASH_PREFIX = "assistant-citation=";
29​
30/** Base64url keeps router hash normalization from decoding quote whitespace or source IDs. */
31function assistantCitationHash(citation: AssistantCitation) {
32 return `${CITATION_HASH_PREFIX}${Base64Url.encode(formatAssistantCitationHref(citation))}`;
34​
35export function assistantCitationFromLocation(href: string) {
36 const hashIndex = href.indexOf("#");
37 if (hashIndex === -1) return null;
38 const hash = href.slice(hashIndex + 1);
39 if (!hash.startsWith(CITATION_HASH_PREFIX) || hash.length > 140_000) return null;
40 try {
41 return pipe(
42 hash.slice(CITATION_HASH_PREFIX.length),
43 Base64Url.decodeString,
44 Result.getOrThrow,
45 parseAssistantCitationHref,
46 );
47 } catch {
48 return null;
49 }
51​
52function hasAssistantCitationHash(href: string) {
53 const hashIndex = href.indexOf("#");
54 return hashIndex !== -1 && href.startsWith(CITATION_HASH_PREFIX, hashIndex + 1);
56​
57/**
58 * Router selectors for a quote link's href and activation key; null for any other location.
59 * Every navigation changes the href and the history key one commit before the route's
60 * params, so a component that selects either unconditionally renders the outgoing route
61 * once more on each navigation.
62 */
63export function selectAssistantCitationHref(location: ParsedLocation) {
64 return hasAssistantCitationHash(location.href) ? location.href : null;
66​
67export function selectAssistantCitationKey(location: ParsedLocation) {
68 if (!hasAssistantCitationHash(location.href)) return null;
69 return location.state.assistantCitationActivation ?? location.state.__TSR_key ?? null;
71​
72/** Return paths drop the quote hash so going back does not reveal its source again. */
73export function withoutAssistantCitationHash(href: string) {
74 return hasAssistantCitationHash(href) ? href.slice(0, href.indexOf("#")) : href;
76​
77type SourceThread = Pick<OrchestrationV2ThreadShell, "lineage"> | null;
78​
79function sideChatParentId(sourceThread: SourceThread) {
80 return sourceThread?.lineage.sideChat ? sourceThread.lineage.parentThreadId : null;
82​
83/** Side chat quotes open on their parent thread, where the side chat is a tab. */
84export function assistantCitationRoute(citation: AssistantCitation, sourceThread: SourceThread) {
85 return {
86 to: "/$environmentId/$threadId" as const,
87 params: {
88 environmentId: citation.environmentId,
89 threadId: sideChatParentId(sourceThread) ?? citation.threadId,
90 },
91 hash: assistantCitationHash(citation),
92 resetScroll: false,
93 };
95​
96/** A fresh activation lets the same link reveal its source again after dismissal. */
97export function assistantCitationNavigation(
98 citation: AssistantCitation,
99 sourceThread: SourceThread,
100) {
101 return {
102 ...assistantCitationRoute(citation, sourceThread),
103 state: { assistantCitationActivation: randomUUID() },
104 };
106​
107/**
108 * Reveals the location's side chat quote in its tab on `parentThreadId`, moving off the side
109 * chat's own route. Links, reloads and late-loading shells all land here, not only clicks.
110 */
111export function revealSideChatCitation(
112 router: Pick<AnyRouter, "navigate" | "state">,
113 routeThreadRef: ScopedThreadRef,
114 sideChatThreadId: ThreadId,
115 parentThreadId: ThreadId,
116 activation: string,
117) {
118 const { location } = router.state;
119 const citation = assistantCitationFromLocation(location.href);
120 if (
121 citation === null ||
122 citation.threadId !== sideChatThreadId ||
123 citation.environmentId !== routeThreadRef.environmentId ||
124 (routeThreadRef.threadId !== parentThreadId && routeThreadRef.threadId !== citation.threadId)
125 ) {
126 return;
127 }
128 useRightPanelStore
129 .getState()
130 .openThread(scopeThreadRef(citation.environmentId, parentThreadId), citation.threadId);
131 if (routeThreadRef.threadId === parentThreadId) return;
132 return router.navigate({
133 to: "/$environmentId/$threadId",
134 params: { environmentId: citation.environmentId, threadId: parentThreadId },
135 hash: true,
136 state: (state) => ({ ...state, assistantCitationActivation: activation }),
137 replace: true,
138 resetScroll: false,
139 });
141​
142export function useSideChatCitationReveal(
143 routeThreadRef: ScopedThreadRef | null,
144 citation: AssistantCitation | null,
145 activation: string,
146) {
147 const router = useRouter();
148 const sourceRef =
149 routeThreadRef && citation?.environmentId === routeThreadRef.environmentId
150 ? scopeThreadRef(citation.environmentId, citation.threadId)
151 : null;
152 const parentThreadId = sideChatParentId(useQuietThreadShell(sourceRef));
153 const environmentId = routeThreadRef?.environmentId;
154 const threadId = routeThreadRef?.threadId;
155 const sideChatThreadId = sourceRef?.threadId;
156 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves a side chat quote's router location and parent right panel once per activation, including after its shell loads
157 useEffect(() => {
158 if (
159 environmentId === undefined ||
160 threadId === undefined ||
161 sideChatThreadId === undefined ||
162 parentThreadId === null
163 ) {
164 return;
165 }
166 void revealSideChatCitation(
167 router,
168 scopeThreadRef(environmentId, threadId),
169 sideChatThreadId,
170 parentThreadId,
171 activation,
172 );
173 }, [router, environmentId, threadId, sideChatThreadId, parentThreadId, activation]);