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