Open History to see the last commit
1import { useAtom, useAtomSet, useAtomValue } from "@effect/atom-react";
2import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread";
4import {
5 connectLinkedEnvironment,
6 type LinkedThreadOpen,
7 resolveLinkedThreadOpen,
8} from "@t3tools/client-runtime/linked-thread";
9import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
10import { useNavigate, useRouter } from "@tanstack/react-router";
11import { AsyncResult, Atom } from "effect/reactivity";
12
13import type { TurnItemSource } from "../components/chat/timelineRowContext";
14import {
15 selectActiveRightPanelSurface,
16 selectThreadRightPanelState,
17 useRightPanelStore,
18} from "../rightPanelStore";
19import { connectPairing, reachesEnvironment } from "../connection/onboarding";
20import { openLinkedThreadRead } from "../lib/sideChatPane";
21import type { LinkedThreadSurface } from "../linkedThreadSurface";
22import { buildThreadRouteParams } from "../threadRoutes";
23import { useEnvironment } from "./environments";
24import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
25import { useEnvironmentQuery } from "./query";
26import { useAtomCommand } from "./use-atom-command";
27
28/**
29 * How a click opens a thread `panelRef` says is on a linked environment: in place when this client
30 * is connected there, else read-only through `panelRef`'s environment, in its right panel or on
31 * the main screen as the click asks. A saved environment whose link is gone opens in place.
32 */
33export function useLinkedThreadOpener(
34 panelRef: ScopedThreadRef,
35 thread:
36 | {
37 readonly environmentId: EnvironmentId;
38 readonly threadId: ThreadId;
39 readonly label: string;
40 }
41 | undefined,
42 title: string | null,
43): {
44 readonly mode: Exclude<LinkedThreadOpen, "unavailable">;
45 readonly open: (intent: SideThreadOpenIntent) => void;
46} | null {
47 const navigate = useNavigate();
48 const viaEnvironmentId = panelRef.environmentId;
49 const own = useEnvironment(thread?.environmentId ?? null);
50 const connected = own?.connection.phase === "connected";
51 const links = useLinkedEnvironments(
52 thread === undefined || connected ? null : viaEnvironmentId,
53 thread?.environmentId,
54 );
55 if (thread === undefined) return null;
56 const resolved = resolveLinkedThreadOpen({
57 environmentId: thread.environmentId,
58 viaEnvironmentId,
59 own: own === null ? undefined : { connected },
60 linked: links.has(thread.environmentId),
61 });
62 const mode = resolved === "direct" ? "direct" : "linked";
63 return {
64 mode,
65 open: (intent) => {
66 if (mode === "linked") {
67 openLinkedThreadRead({
68 panelRef,
69 target: {
70 viaEnvironmentId,
71 environmentId: thread.environmentId,
72 threadId: thread.threadId,
73 label: own?.label ?? thread.label,
74 title,
75 },
76 intent,
77 navigate,
78 });
79 return;
80 }
81 void navigate({
82 to: "/$environmentId/$threadId",
83 params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.threadId)),
84 });
85 },
86 };
87}
88
89type TabKey = readonly [
90 /** Null on the main screen, where no tab shows the title. */
91 panelEnvironmentId: EnvironmentId | null,
92 panelThreadId: ThreadId | null,
93 surfaceId: string,
94 viaEnvironmentId: EnvironmentId,
95 environmentId: EnvironmentId,
96 threadId: ThreadId,
97];
98
99const targetOf = (
100 surface: Pick<LinkedThreadSurface, "viaEnvironmentId" | "environmentId" | "threadId">,
101) => ({
102 environmentId: surface.viaEnvironmentId,
103 input: { environmentId: surface.environmentId, threadId: surface.threadId },
104});
105
106/** One tab's subscription, which also keeps the tab's title to the thread's own. */
107const tabViewAtom = Atom.family((key: string) => {
108 const [panelEnvironmentId, panelThreadId, surfaceId, viaEnvironmentId, environmentId, threadId] =
109 JSON.parse(key) as TabKey;
110 const panelRef =
111 panelEnvironmentId === null || panelThreadId === null
112 ? null
113 : scopeThreadRef(panelEnvironmentId, panelThreadId);
114 const view = peerLinkEnvironment.threadView(
115 targetOf({ viaEnvironmentId, environmentId, threadId }),
116 );
117 return Atom.readable(
118 (get) => {
119 const live = get(view);
120 const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title;
121 if (title && panelRef !== null) {
122 useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title);
123 }
124 return live;
125 },
126 (refresh) => refresh(view),
127 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`));
128});
129
130/**
131 * The thread of `surface`, streamed through the environment that links to it, for the tab in
132 * `panelRef`'s panel or, with null, the main screen. The stream runs only while `visible`; what
133 * it last showed stays.
134 */
135export function useLinkedThreadView(
136 panelRef: ScopedThreadRef | null,
137 surface: Pick<LinkedThreadSurface, "id" | "viaEnvironmentId" | "environmentId" | "threadId">,
138 visible: boolean,
139) {
140 const key: TabKey = [
141 panelRef?.environmentId ?? null,
142 panelRef?.threadId ?? null,
143 surface.id,
144 surface.viaEnvironmentId,
145 surface.environmentId,
146 surface.threadId,
147 ];
148 const live = useEnvironmentQuery(visible ? tabViewAtom(JSON.stringify(key)) : null);
149 const view = useAtomValue(peerLinkEnvironment.lastThreadView(targetOf(surface)));
150 return {
151 view,
152 /** Why the stream is not running: it ended, or it waits to ask again. */
153 error: live.failure ?? view?.error ?? null,
154 /** Asks again now. */
155 retry: live.refresh,
156 };
157}
158
159/** A linked environment the add-environment dialog opens for, with what is known about it filled in. */
160export interface AddEnvironmentPrefill {
161 readonly environmentId: EnvironmentId;
162 readonly label: string;
163 readonly host: string | null;
164}
165
166export const addEnvironmentPrefillAtom = Atom.make<AddEnvironmentPrefill | null>(null).pipe(
167 Atom.withLabel("add-environment-prefill"),
168);
169
170export type LinkedEnvironmentConnectState =
171 | { readonly phase: "idle" | "connecting" }
172 | { readonly phase: "unreachable"; readonly label: string }
173 /** The user pairs with a code of their own; `prefill` reopens the dialog for it. */
174 | { readonly phase: "manual"; readonly prefill: AddEnvironmentPrefill };
175
176// Kept like the tab's reads, so the tab still says what happened after a visit to Settings.
177const linkedEnvironmentConnectAtom = Atom.family((key: string) =>
178 Atom.make<LinkedEnvironmentConnectState>({ phase: "idle" }).pipe(
179 Atom.setIdleTTL(5 * 60_000),
180 Atom.withLabel(`linked-environment-connect:${key}`),
181 ),
182);
183
184/**
185 * Connects this client to the environment `surface`'s thread lives in. One step when the linking
186 * environment can get a pairing for this client: the thread then opens there, in place of the
187 * read-only view. Otherwise the add-environment dialog opens for that machine. `panelRef` is the
188 * thread whose panel shows the read, or null on the main screen.
189 */
190export function useConnectLinkedEnvironment(
191 panelRef: ScopedThreadRef | null,
192 surface: LinkedThreadSurface,
193) {
194 const navigate = useNavigate();
195 const router = useRouter();
196 const setPrefill = useAtomSet(addEnvironmentPrefillAtom);
197 const mayPair = useAtomValue(
198 peerLinkEnvironment.pairClient.permissionAtom(surface.viaEnvironmentId),
199 );
200 const quiet = { reportFailure: false, reportDefect: false } as const;
201 const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
202 const reaches = useAtomCommand(reachesEnvironment, quiet);
203 const pair = useAtomCommand(connectPairing, quiet);
204 const [state, setState] = useAtom(
205 linkedEnvironmentConnectAtom(
206 `${panelRef === null ? "main" : scopedThreadKey(panelRef)}:${surface.id}`,
207 ),
208 );
209 const addWithCode = (prefill: AddEnvironmentPrefill) => {
210 setPrefill(prefill);
211 void navigate({ to: "/settings/connections" });
212 };
213 /** `unasked` leaves a pairing code to the notice's button instead of opening Settings. */
214 const connect = async (options?: { readonly unasked?: boolean }) => {
215 setState({ phase: "connecting" });
216 const startedOn = router.state.location.href;
217 let tabClosed = false;
218 // A tab can close and reopen with the same ID while pairing is in flight.
219 const stopWatchingTab =
220 panelRef === null
221 ? undefined
222 : useRightPanelStore.subscribe((state) => {
223 const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef);
224 if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true;
225 });
226 // Pairing takes a moment; a user who has gone elsewhere since is not moved again.
227 const stayed = () =>
228 !tabClosed &&
229 router.state.location.href === startedOn &&
230 (panelRef === null ||
231 selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, panelRef)?.id ===
232 surface.id);
233 const outcome = await connectLinkedEnvironment({
234 label: surface.label,
235 requestPairing: async () => {
236 // Without it the linking environment refuses; the user can still pair by hand.
237 if (!mayPair) return null;
238 const result = await requestPairing({
239 environmentId: surface.viaEnvironmentId,
240 input: { environmentId: surface.environmentId },
241 });
242 return result._tag === "Success" ? result.value : null;
243 },
244 reaches: async (host) => {
245 const result = await reaches({ host, environmentId: surface.environmentId });
246 return result._tag === "Success" && result.value;
247 },
248 pair: async ({ host, pairingCode }) => {
249 const result = await pair({
250 host,
251 pairingCode,
252 expectedEnvironmentId: surface.environmentId,
253 });
254 return result._tag === "Success";
255 },
256 }).finally(stopWatchingTab);
257 if (outcome.type === "unreachable") {
258 setState({ phase: "unreachable", label: outcome.label });
259 return outcome;
260 }
261 if (outcome.type === "connected") {
262 setState({ phase: "idle" });
263 if (tabClosed) return outcome;
264 const shouldNavigate = stayed();
265 // The thread opens where every thread on a connected environment does, so its tab is done.
266 if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id);
267 if (!shouldNavigate) return outcome;
268 void navigate({
269 to: "/$environmentId/$threadId",
270 params: buildThreadRouteParams(scopeThreadRef(surface.environmentId, surface.threadId)),
271 // The read-only page has nothing left to go back to.
272 replace: panelRef === null,
273 });
274 return outcome;
275 }
276 const prefill = {
277 environmentId: surface.environmentId,
278 label: outcome.label,
279 host: outcome.host,
280 };
281 setState({ phase: "manual", prefill });
282 if (stayed() && options?.unasked !== true) addWithCode(prefill);
283 return outcome;
284 };
285 return { state, connect, addWithCode };
286}
287
288/** Where a linked thread's expanded rows read an item in full: through the linking environment. */
289export const linkedThreadItemSource = (
290 target: Pick<LinkedThreadSurface, "viaEnvironmentId" | "environmentId">,
291): TurnItemSource => ({
292 detail: (input) =>
293 peerLinkEnvironment.threadItem({
294 environmentId: target.viaEnvironmentId,
295 input: { environmentId: target.environmentId, ...input },
296 }),
297});