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

linkedThreadView.ts

286 lines10.8 KB

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