The best way to control Claude Code, Codex and more from any computer or phone

main
ts 270 lines 10.2 KB
Raw
1 import { useAtom, useAtomSet, useAtomValue } from "@effect/atom-react";
2 import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3 import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread";
4 import {
5 connectLinkedEnvironment,
6 type LinkedThreadOpen,
7 resolveLinkedThreadOpen,
8 } from "@t3tools/client-runtime/linked-thread";
9 import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
10 import { useNavigate, useRouter } from "@tanstack/react-router";
11 import { AsyncResult, Atom } from "effect/reactivity";
12
13 import type { TurnItemSource } from "../components/chat/timelineRowContext";
14 import { useRightPanelStore } from "../rightPanelStore";
15 import { connectPairing, reachesEnvironment } from "../connection/onboarding";
16 import { openLinkedThreadRead } from "../lib/sideChatPane";
17 import type { LinkedThreadSurface } from "../linkedThreadSurface";
18 import { buildThreadRouteParams } from "../threadRoutes";
19 import { useEnvironment } from "./environments";
20 import { peerLinkEnvironment, useLinkedEnvironments } from "./peerLinks";
21 import { useEnvironmentQuery } from "./query";
22 import { 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 */
29 export 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
82 type 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
92 const 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. */
100 const 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.make((get) => {
111 const live = get(view);
112 const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title;
113 if (title && panelRef !== null) {
114 useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title);
115 }
116 return live;
117 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`));
118 });
119
120 /**
121 * The thread of `surface`, streamed through the environment that links to it, for the tab in
122 * `panelRef`'s panel or, with null, the main screen. The stream runs only while `visible`; what
123 * it last showed stays.
124 */
125 export function useLinkedThreadView(
126 panelRef: ScopedThreadRef | null,
127 surface: Pick<LinkedThreadSurface, "id" | "viaEnvironmentId" | "environmentId" | "threadId">,
128 visible: boolean,
129 ) {
130 const key: TabKey = [
131 panelRef?.environmentId ?? null,
132 panelRef?.threadId ?? null,
133 surface.id,
134 surface.viaEnvironmentId,
135 surface.environmentId,
136 surface.threadId,
137 ];
138 const live = useEnvironmentQuery(visible ? tabViewAtom(JSON.stringify(key)) : null);
139 const view = useAtomValue(peerLinkEnvironment.lastThreadView(targetOf(surface)));
140 return {
141 view,
142 /** Why the stream is not running: it ended, or it waits to ask again. */
143 error: live.failure ?? view?.error ?? null,
144 /** Asks again now. */
145 retry: live.refresh,
146 };
147 }
148
149 /** A linked environment the add-environment dialog opens for, with what is known about it filled in. */
150 export interface AddEnvironmentPrefill {
151 readonly environmentId: EnvironmentId;
152 readonly label: string;
153 readonly host: string | null;
154 }
155
156 export const addEnvironmentPrefillAtom = Atom.make<AddEnvironmentPrefill | null>(null).pipe(
157 Atom.withLabel("add-environment-prefill"),
158 );
159
160 export type LinkedEnvironmentConnectState =
161 | { readonly phase: "idle" | "connecting" }
162 | { readonly phase: "unreachable"; readonly label: string }
163 /** The user pairs with a code of their own; `prefill` reopens the dialog for it. */
164 | { readonly phase: "manual"; readonly prefill: AddEnvironmentPrefill };
165
166 // Kept like the tab's reads, so the tab still says what happened after a visit to Settings.
167 const linkedEnvironmentConnectAtom = Atom.family((key: string) =>
168 Atom.make<LinkedEnvironmentConnectState>({ phase: "idle" }).pipe(
169 Atom.setIdleTTL(5 * 60_000),
170 Atom.withLabel(`linked-environment-connect:${key}`),
171 ),
172 );
173
174 /**
175 * Connects this client to the environment `surface`'s thread lives in. One step when the linking
176 * environment can get a pairing for this client: the thread then opens there, in place of the
177 * read-only view. Otherwise the add-environment dialog opens for that machine. `panelRef` is the
178 * thread whose panel shows the read, or null on the main screen.
179 */
180 export function useConnectLinkedEnvironment(
181 panelRef: ScopedThreadRef | null,
182 surface: LinkedThreadSurface,
183 ) {
184 const navigate = useNavigate();
185 const router = useRouter();
186 const setPrefill = useAtomSet(addEnvironmentPrefillAtom);
187 const mayPair = useAtomValue(
188 peerLinkEnvironment.pairClient.permissionAtom(surface.viaEnvironmentId),
189 );
190 const quiet = { reportFailure: false, reportDefect: false } as const;
191 const requestPairing = useAtomCommand(peerLinkEnvironment.pairClient, quiet);
192 const reaches = useAtomCommand(reachesEnvironment, quiet);
193 const pair = useAtomCommand(connectPairing, quiet);
194 const [state, setState] = useAtom(
195 linkedEnvironmentConnectAtom(
196 `${panelRef === null ? "main" : scopedThreadKey(panelRef)}:${surface.id}`,
197 ),
198 );
199 const addWithCode = (prefill: AddEnvironmentPrefill) => {
200 setPrefill(prefill);
201 void navigate({ to: "/settings/connections" });
202 };
203 const connect = async () => {
204 setState({ phase: "connecting" });
205 const startedOn = router.state.location.href;
206 // Pairing takes a moment; a user who has gone elsewhere since is not moved again.
207 const stayed = () => router.state.location.href === startedOn;
208 const outcome = await connectLinkedEnvironment({
209 label: surface.label,
210 requestPairing: async () => {
211 // Without it the linking environment refuses; the user can still pair by hand.
212 if (!mayPair) return null;
213 const result = await requestPairing({
214 environmentId: surface.viaEnvironmentId,
215 input: { environmentId: surface.environmentId },
216 });
217 return result._tag === "Success" ? result.value : null;
218 },
219 reaches: async (host) => {
220 const result = await reaches({ host, environmentId: surface.environmentId });
221 return result._tag === "Success" && result.value;
222 },
223 pair: async ({ host, pairingCode }) => {
224 const result = await pair({
225 host,
226 pairingCode,
227 expectedEnvironmentId: surface.environmentId,
228 });
229 return result._tag === "Success";
230 },
231 });
232 if (outcome.type === "unreachable") {
233 setState({ phase: "unreachable", label: outcome.label });
234 return outcome;
235 }
236 if (outcome.type === "connected") {
237 setState({ phase: "idle" });
238 // The thread opens where every thread on a connected environment does, so its tab is done.
239 if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id);
240 if (!stayed()) return outcome;
241 void navigate({
242 to: "/$environmentId/$threadId",
243 params: buildThreadRouteParams(scopeThreadRef(surface.environmentId, surface.threadId)),
244 // The read-only page has nothing left to go back to.
245 replace: panelRef === null,
246 });
247 return outcome;
248 }
249 const prefill = {
250 environmentId: surface.environmentId,
251 label: outcome.label,
252 host: outcome.host,
253 };
254 setState({ phase: "manual", prefill });
255 if (stayed()) addWithCode(prefill);
256 return outcome;
257 };
258 return { state, connect, addWithCode };
259 }
260
261 /** Where a linked thread's expanded rows read an item in full: through the linking environment. */
262 export const linkedThreadItemSource = (
263 target: Pick<LinkedThreadSurface, "viaEnvironmentId" | "environmentId">,
264 ): TurnItemSource => ({
265 detail: (input) =>
266 peerLinkEnvironment.threadItem({
267 environmentId: target.viaEnvironmentId,
268 input: { environmentId: target.environmentId, ...input },
269 }),
270 });