@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 316 lines 12.5 KB
Raw
1 import type {
2 EnvironmentId,
3 OrchestrationV2ThreadHistoryPage,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2ThreadStreamItem,
6 PeerLinkClientPairingResult,
7 ThreadId,
8 } from "@t3tools/contracts";
9 import * as Effect from "effect/Effect";
10 import * as Queue from "effect/Queue";
11 import * as Stream from "effect/Stream";
12 import { mFallback, msg } from "gt-i18n";
13 import type { MFunctionType } from "gt-i18n/types";
14
15 import {
16 deriveRunlessWorkStartedAt,
17 deriveThreadStructureRuntime,
18 } from "./state/threadExecution.ts";
19 import {
20 applyThreadHistoryPage,
21 applyThreadStreamItem,
22 initialThreadStreamState,
23 type ThreadStreamState,
24 } from "./state/threadStream.ts";
25
26 /** A thread on a linked environment, read through the environment that holds the link. */
27 export interface LinkedThreadTarget {
28 /** The environment this client is connected to, which reads the thread over its link. */
29 readonly viaEnvironmentId: EnvironmentId;
30 /** The linked environment the thread lives in. */
31 readonly environmentId: EnvironmentId;
32 readonly threadId: ThreadId;
33 /** What to call the linked environment and the thread until the first page names them. */
34 readonly label: string;
35 readonly title: string | null;
36 }
37
38 export type LinkedThreadOpen = "direct" | "linked" | "unavailable";
39
40 /**
41 * How a client opens a thread on `environmentId` that a thread or link in `viaEnvironmentId`
42 * points at. A connection of the client's own always wins, since it can do more than read. Without
43 * one, the environment holding the link reads it. A saved environment that neither answers nor is
44 * linked still opens directly, where the client says it is offline.
45 */
46 export function resolveLinkedThreadOpen(input: {
47 readonly environmentId: EnvironmentId;
48 readonly viaEnvironmentId: EnvironmentId;
49 /** The client's own saved connection to `environmentId`, when it has one. */
50 readonly own: { readonly connected: boolean } | undefined;
51 /** Whether `viaEnvironmentId` holds a link to `environmentId`. */
52 readonly linked: boolean;
53 }): LinkedThreadOpen {
54 if (input.environmentId === input.viaEnvironmentId) return "direct";
55 if (input.own?.connected === true) return "direct";
56 if (input.linked) return "linked";
57 return input.own === undefined ? "unavailable" : "direct";
58 }
59
60 export type LinkedEnvironmentConnection =
61 /** This client paired with the linked environment and saved it. */
62 | { readonly type: "connected" }
63 /** No address the linking environment knows answers from this device. */
64 | { readonly type: "unreachable"; readonly label: string }
65 /** The user pairs with a code of their own, in the add-environment flow, with this filled in. */
66 | { readonly type: "manual"; readonly label: string; readonly host: string | null };
67
68 /**
69 * Connects this client to a linked environment. The linking environment asks it for a one-time
70 * pairing over a full-access link, and the client redeems that at an address it can reach itself.
71 * Anything short of that leaves the user to pair by hand.
72 */
73 export async function connectLinkedEnvironment(options: {
74 readonly label: string;
75 /** Asks the linking environment for a pairing; null when it could not answer. */
76 readonly requestPairing: () => Promise<PeerLinkClientPairingResult | null>;
77 /** Whether an address answers this device as the linked environment. */
78 readonly reaches: (host: string) => Promise<boolean>;
79 /** Pairs at `host` with the one-time credential and saves the environment. */
80 readonly pair: (input: {
81 readonly host: string;
82 readonly pairingCode: string;
83 }) => Promise<boolean>;
84 }): Promise<LinkedEnvironmentConnection> {
85 const pairing = await options.requestPairing();
86 if (pairing === null) return { type: "manual", label: options.label, host: null };
87 const { label, urls } = pairing;
88 // Asked together, taken in the linking environment's order of preference.
89 const answers = await Promise.all(urls.map((url) => options.reaches(url)));
90 const host = urls.find((_, index) => answers[index]) ?? null;
91 if (pairing.type === "unsupported") {
92 return { type: "manual", label, host: host ?? urls[0] ?? null };
93 }
94 if (host === null) return { type: "unreachable", label };
95 return (await options.pair({ host, pairingCode: pairing.credential }))
96 ? { type: "connected" }
97 : { type: "manual", label, host };
98 }
99
100 const hasStringField = <K extends string>(value: unknown, key: K): value is Record<K, string> =>
101 typeof value === "object" &&
102 value !== null &&
103 typeof (value as Record<string, unknown>)[key] === "string";
104
105 /** Whether a failed read can succeed later with nothing changed: the linked environment was only out of reach. */
106 const isLinkedThreadUnreachable = (error: unknown): boolean =>
107 hasStringField(error, "_tag") &&
108 error._tag === "PeerLinkThreadReadError" &&
109 hasStringField(error, "reason") &&
110 error.reason === "unreachable";
111
112 export interface LinkedThreadFailure {
113 readonly title: string;
114 readonly detail: string;
115 /** Whether reading again can succeed without the user changing something first. */
116 readonly retryable: boolean;
117 }
118
119 /**
120 * A failed read in the user's words. `via` and `label` name the two environments as the client
121 * knows them; the server's own label wins once it has answered with one.
122 */
123 export function linkedThreadFailure(
124 error: unknown,
125 names: { readonly via: string; readonly label: string },
126 resolve: MFunctionType = mFallback,
127 ): LinkedThreadFailure {
128 const via = names.via;
129 const serverMessage = hasStringField(error, "message") ? error.message : "";
130 if (!hasStringField(error, "_tag") || error._tag !== "PeerLinkThreadReadError") {
131 // An environment from before this read answers with an unknown method.
132 return {
133 title: resolve(msg("Could not read this thread through {via}", { via })),
134 detail:
135 serverMessage ||
136 resolve(msg("{via} may need an update before it can read linked threads.", { via })),
137 retryable: true,
138 };
139 }
140 const retryable = isLinkedThreadUnreachable(error);
141 const label = hasStringField(error, "label") ? error.label : names.label;
142 const reason = hasStringField(error, "reason") ? error.reason : "";
143 switch (reason) {
144 case "disabled":
145 return {
146 title: resolve(msg("Linked environments is off on {via}", { via })),
147 detail: resolve(
148 msg(
149 "Turn it on in {via}'s Settings → Labs to read threads on the machines it links to.",
150 {
151 via,
152 },
153 ),
154 ),
155 retryable,
156 };
157 case "unknown_link":
158 return {
159 title: resolve(msg("{via} is no longer linked to {label}", { via, label })),
160 detail: resolve(
161 msg("Link it again in {via}'s Settings → Connections to read its threads from here.", {
162 via,
163 }),
164 ),
165 retryable,
166 };
167 case "expired":
168 return {
169 title: resolve(msg("The link from {via} to {label} expired", { via, label })),
170 detail: resolve(
171 msg("Link it again in {via}'s Settings → Connections with a new pairing code.", { via }),
172 ),
173 retryable,
174 };
175 case "rejected":
176 return {
177 title: resolve(msg("{label} refused the read", { label })),
178 detail: serverMessage,
179 retryable,
180 };
181 case "thread_not_found":
182 return {
183 title: resolve(msg("This thread is no longer on {label}", { label })),
184 detail: resolve(msg("It may have been deleted there.")),
185 retryable,
186 };
187 case "incompatible":
188 return {
189 title: resolve(msg("{label} needs an update", { label })),
190 detail: serverMessage,
191 retryable,
192 };
193 default:
194 return {
195 title: resolve(msg("{label} is not answering {via}", { label, via })),
196 detail: serverMessage,
197 retryable,
198 };
199 }
200 }
201
202 const WORKING_STATUSES = new Set(["preparing", "queued", "starting", "running", "waiting"]);
203
204 /** Whether the thread has work under way, for the note that stands where its composer would. */
205 export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjection): boolean {
206 return (
207 WORKING_STATUSES.has(deriveThreadStructureRuntime(projection)?.status ?? "") ||
208 deriveRunlessWorkStartedAt(projection) !== null
209 );
210 }
211
212 /** How long a view waits before asking again for a thread whose environment did not answer. */
213 export const LINKED_THREAD_RETRY_MS = 15_000;
214
215 /** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */
216 export interface LinkedThreadView {
217 readonly thread: ThreadStreamState;
218 /** Why the stream stopped, while the view waits to ask again; the next item clears it. */
219 readonly error: unknown;
220 readonly history: { readonly loading: boolean; readonly failed: boolean };
221 /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */
222 readonly loadEarlier: () => void;
223 }
224
225 /**
226 * What a view keeps once its stream shows `next`. A stream that was opened again has read nothing
227 * until its snapshot arrives, so the thread read before stays, with the new stream's state beside
228 * it. Its earlier turns load again only once that stream has a thread of its own to add them to.
229 */
230 export const keepLinkedThreadView = (
231 kept: LinkedThreadView | null,
232 next: LinkedThreadView,
233 ): LinkedThreadView =>
234 next.thread.projection !== null || kept === null || kept.thread.projection === null
235 ? next
236 : { ...next, thread: { ...kept.thread, historyCursor: null } };
237
238 /**
239 * Follows a linked environment's thread for as long as something consumes the result. The thread
240 * is built from the same stream items and with the same reducer as a guest page's, and older
241 * turns load through the same cursor. A linked environment that stops answering is asked again
242 * after a wait, with what was read kept; any other failure ends the stream.
243 */
244 export const followLinkedThread = <E, R, E2, R2>(source: {
245 readonly items: Stream.Stream<OrchestrationV2ThreadStreamItem, E, R>;
246 readonly historyPage: (cursor: string) => Effect.Effect<OrchestrationV2ThreadHistoryPage, E2, R2>;
247 }): Stream.Stream<LinkedThreadView, E, R | R2> =>
248 Stream.unwrap(
249 Effect.gen(function* () {
250 const requests = yield* Queue.unbounded<void>();
251 let requested = false;
252 // Both halves below run one step at a time, so each reads the view the other left.
253 let view: LinkedThreadView = {
254 thread: initialThreadStreamState,
255 error: null,
256 history: { loading: false, failed: false },
257 loadEarlier: () => {
258 if (requested || view.thread.historyCursor === null) return;
259 requested = true;
260 Queue.offerUnsafe(requests, undefined);
261 },
262 };
263 const show = (patch: Partial<LinkedThreadView>) => {
264 view = { ...view, ...patch };
265 return view;
266 };
267 const attempt = (): Stream.Stream<LinkedThreadView, E, R> =>
268 source.items.pipe(
269 Stream.map((item) =>
270 show({ thread: applyThreadStreamItem(view.thread, item), error: null }),
271 ),
272 Stream.catch((error) =>
273 isLinkedThreadUnreachable(error)
274 ? Stream.make(show({ error })).pipe(
275 Stream.concat(
276 Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))),
277 ),
278 )
279 : Stream.fail(error),
280 ),
281 );
282 const earlier = Stream.fromQueue(requests).pipe(
283 Stream.flatMap(() =>
284 Stream.suspend(() => {
285 const cursor = view.thread.historyCursor;
286 if (cursor === null) {
287 requested = false;
288 return Stream.empty;
289 }
290 return Stream.make(show({ history: { loading: true, failed: false } })).pipe(
291 Stream.concat(
292 Stream.fromEffect(
293 source.historyPage(cursor).pipe(
294 Effect.match({
295 onSuccess: (page) =>
296 show({
297 thread: applyThreadHistoryPage(view.thread, cursor, page),
298 history: { loading: false, failed: false },
299 }),
300 onFailure: () => show({ history: { loading: false, failed: true } }),
301 }),
302 Effect.ensuring(
303 Effect.sync(() => {
304 requested = false;
305 }),
306 ),
307 ),
308 ),
309 ),
310 );
311 }),
312 ),
313 );
314 return Stream.merge(attempt(), earlier, { haltStrategy: "left" });
315 }),
316 );