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

main
ts 330 lines 13 KB
Raw
1 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
2 import {
3 EnvironmentId,
4 EventId,
5 type OrchestrationV2StoredEvent,
6 OrchestrationV2ThreadStreamItem,
7 type PeerLinkThreadReadError,
8 PEER_LINK_THREAD_HISTORY_ROUTE,
9 PEER_LINK_THREAD_ITEM_ROUTE,
10 PEER_LINK_THREAD_STREAM_ROUTE,
11 ThreadId,
12 TurnItemId,
13 } from "@t3tools/contracts";
14 import { expect, it } from "@effect/vitest";
15 import type * as Cause from "effect/Cause";
16 import * as Context from "effect/Context";
17 import * as DateTime from "effect/DateTime";
18 import * as Deferred from "effect/Deferred";
19 import * as Duration from "effect/Duration";
20 import * as Effect from "effect/Effect";
21 import * as Fiber from "effect/Fiber";
22 import * as Layer from "effect/Layer";
23 import * as Queue from "effect/Queue";
24 import * as Ref from "effect/Ref";
25 import * as Schema from "effect/Schema";
26 import * as Stream from "effect/Stream";
27 import { HttpRouter, HttpServerResponse } from "effect/http";
28 import * as FetchHttpClient from "effect/http/FetchHttpClient";
29 import * as HttpClient from "effect/http/HttpClient";
30 import * as HttpClientRequest from "effect/http/HttpClientRequest";
31 import { TestClock } from "effect/testing";
32
33 import { idleThreadProjection, liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
34 import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
35 import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
36 import * as ServerSettings from "../serverSettings.ts";
37 import * as LinkThreadHttp from "./linkThreadHttp.ts";
38 import * as PeerLinks from "./PeerLinks.ts";
39 import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
40 import * as PeerThreadRelay from "./PeerThreadRelay.ts";
41
42 const laptop = descriptorOf("environment-laptop", "Laptop");
43 const box = descriptorOf("environment-box", "Box", { linkThreadStream: true });
44 const boxThread = ThreadId.make("thread:box");
45 const boxItem = TurnItemId.make("item:box");
46 const input = { environmentId: box.environmentId, threadId: boxThread };
47
48 const boxShell = { ...liveThreadShell(boxThread, { activeRunId: null }), title: "On the box" };
49 const boxProjection = idleThreadProjection(boxShell);
50
51 const archived = (sequence: number): OrchestrationV2StoredEvent => ({
52 sequence,
53 commandId: null,
54 event: {
55 id: EventId.make(`event:${sequence}`),
56 type: "thread.archived",
57 threadId: boxThread,
58 occurredAt: DateTime.makeUnsafe(0),
59 payload: boxProjection.thread,
60 },
61 });
62
63 /**
64 * B, serving one thread to its links: `live` feeds the thread's live events, and `closed`
65 * completes when B's stream of them is torn down.
66 */
67 const serveBox = Effect.gen(function* () {
68 const live = yield* Queue.unbounded<OrchestrationV2StoredEvent, Cause.Done>();
69 const closed = yield* Deferred.make<void>();
70 const threads = Layer.mock(ThreadManagement.ThreadManagementService)({
71 getThreadShell: (threadId) => Effect.succeed(threadId === boxThread ? boxShell : null),
72 ensureLegacyTranscript: () => Effect.void,
73 getThreadSnapshotWindow: () =>
74 Effect.succeed({ snapshotSequence: 7, projection: boxProjection } as never),
75 streamStoredEventsFrom: () =>
76 Stream.fromQueue(live).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
77 getThreadHistoryPage: (_threadId, cursor) =>
78 Effect.succeed({ snapshotSequence: 7, items: [], hasMoreHistory: false, nextCursor: cursor }),
79 getTurnItem: () => Effect.succeed({ item: null }),
80 });
81 const peer = yield* servePeer(box, Layer.empty, LinkThreadHttp.layer).pipe(
82 Effect.provide(
83 Layer.merge(threads, Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({})),
84 ),
85 );
86 return { ...peer, live, closed };
87 });
88
89 /** A, holding the link and relaying B's threads to its own clients. */
90 const makeLaptop = Effect.gen(function* () {
91 const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
92 const answered = yield* Queue.unbounded<number>();
93 const relay = yield* PeerThreadRelay.layer.pipe(
94 Layer.provide(Layer.succeedContext(linking)),
95 Layer.provide(
96 Layer.effect(
97 HttpClient.HttpClient,
98 Effect.map(
99 HttpClient.HttpClient,
100 HttpClient.tap((response) => Queue.offer(answered, response.status)),
101 ),
102 ).pipe(Layer.provide(FetchHttpClient.layer)),
103 ),
104 Layer.build,
105 );
106 return {
107 links: Context.get(linking, PeerLinks.PeerLinks),
108 settings: Context.get(linking, ServerSettings.ServerSettingsService),
109 relay: Context.get(relay, PeerThreadRelay.PeerThreadRelay),
110 /** The status of each answer the relay got, once its headers arrived. */
111 answered,
112 };
113 });
114
115 const encodeStreamItem = Schema.encodeSync(
116 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadStreamItem)),
117 );
118
119 it.effect("relays a linked thread's snapshot and live items, and stops when the client does", () =>
120 Effect.scoped(
121 Effect.gen(function* () {
122 const b = yield* serveBox;
123 const a = yield* makeLaptop;
124 yield* linkTo(a.links, b, "read-only");
125
126 const received = yield* Queue.unbounded<unknown>();
127 const subscription = yield* a.relay.subscribe(input).pipe(
128 Stream.runForEach((item) => Queue.offer(received, item)),
129 Effect.forkScoped,
130 );
131 expect(yield* Queue.take(received)).toMatchObject({
132 kind: "snapshot",
133 snapshotSequence: 7,
134 projection: { thread: { id: boxThread, title: "On the box" } },
135 });
136 yield* Queue.offer(b.live, archived(8));
137 expect(yield* Queue.take(received)).toMatchObject({
138 kind: "event",
139 sequence: 8,
140 event: { type: "thread.archived", threadId: boxThread },
141 });
142
143 // The client unsubscribing ends B's stream, not only A's relay of it.
144 yield* Fiber.interrupt(subscription);
145 yield* Deferred.await(b.closed);
146
147 expect(yield* a.relay.historyPage({ ...input, cursor: "cursor-1" })).toMatchObject({
148 hasMoreHistory: false,
149 nextCursor: "cursor-1",
150 });
151 expect(yield* a.relay.item({ ...input, itemId: boxItem })).toEqual({ item: null });
152 }),
153 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
154 );
155
156 it.effect("tells the client when the linked environment closes the stream", () =>
157 Effect.scoped(
158 Effect.gen(function* () {
159 const b = yield* serveBox;
160 const a = yield* makeLaptop;
161 yield* linkTo(a.links, b);
162 const ended = yield* a.relay
163 .subscribe(input)
164 .pipe(Stream.runDrain, Effect.flip, Effect.forkScoped);
165 yield* Queue.end(b.live);
166 expect(yield* Fiber.join(ended)).toMatchObject({ reason: "unreachable", label: "Box" });
167 }),
168 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
169 );
170
171 it.effect("serves a thread only to a link's own session", () =>
172 Effect.scoped(
173 Effect.gen(function* () {
174 const b = yield* serveBox;
175 const a = yield* makeLaptop;
176 yield* linkTo(a.links, b);
177 const linkBearer = `Bearer ${(yield* a.links.resolve(box.environmentId)).token}`;
178 const agent = yield* b.auth.issueMcpClientSession({
179 label: "ChatGPT",
180 access: "full-access",
181 peerLink: false,
182 client: { deviceType: "bot" },
183 });
184 const http = yield* HttpClient.HttpClient;
185 const statusOf = (headers: Record<string, string>) =>
186 http
187 .execute(
188 HttpClientRequest.get(
189 `${b.url}${PEER_LINK_THREAD_STREAM_ROUTE}?thread=${encodeURIComponent(boxThread)}`,
190 ).pipe(HttpClientRequest.setHeaders(headers)),
191 )
192 .pipe(Effect.map((response) => response.status));
193
194 expect(yield* statusOf({})).toBe(401);
195 // An outside agent's session reads through `/mcp`, never here.
196 expect(yield* statusOf({ authorization: `Bearer ${agent.token}` })).toBe(403);
197 // A browser page never holds a link's token, so no page's request is served.
198 expect(yield* statusOf({ authorization: linkBearer, origin: "https://app.t3.codes" })).toBe(
199 403,
200 );
201 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
202 expect(yield* statusOf({ authorization: linkBearer })).toBe(403);
203 }),
204 ).pipe(Effect.provide(Layer.merge(NodeHttpServer.layerTest, FetchHttpClient.layer))),
205 );
206
207 it.effect("tells a client why a linked environment's thread cannot be read", () =>
208 Effect.scoped(
209 Effect.gen(function* () {
210 const b = yield* serveBox;
211 const a = yield* makeLaptop;
212 yield* linkTo(a.links, b);
213 const session = (yield* b.linkedSessions)[0]!.sessionId;
214 const reasonOf = (target: Partial<typeof input> = {}) =>
215 a.relay.subscribe({ ...input, ...target }).pipe(
216 Stream.runHead,
217 Effect.flip,
218 Effect.map(({ reason, label }: PeerLinkThreadReadError) => ({ reason, label })),
219 );
220
221 expect(yield* reasonOf({ threadId: ThreadId.make("thread:box-gone") })).toEqual({
222 reason: "thread_not_found",
223 label: "Box",
224 });
225
226 yield* Ref.set(b.bearers, []);
227 expect(
228 yield* reasonOf({ environmentId: EnvironmentId.make("environment-elsewhere") }),
229 ).toEqual({ reason: "unknown_link", label: null });
230 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
231 expect(yield* reasonOf()).toEqual({ reason: "disabled", label: null });
232 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: true });
233 // A box from before it served threads to links is never asked for one.
234 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box"));
235 expect(yield* reasonOf()).toEqual({ reason: "incompatible", label: "Box" });
236 expect(yield* Ref.get(b.bearers)).toEqual([]);
237 yield* Ref.set(b.descriptor, box);
238
239 yield* b.auth.revokeSession(session);
240 expect(yield* reasonOf()).toEqual({ reason: "rejected", label: "Box" });
241
242 yield* Ref.set(b.bearers, []);
243 yield* TestClock.adjust(Duration.days(31));
244 expect(yield* reasonOf()).toEqual({ reason: "expired", label: "Box" });
245 expect(yield* Ref.get(b.bearers)).toEqual([]);
246 }),
247 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
248 );
249
250 it.effect("leaves out what a newer linked environment sends that this one cannot pass on", () =>
251 Effect.scoped(
252 Effect.gen(function* () {
253 const frames = [
254 encodeStreamItem({ kind: "snapshot", snapshotSequence: 7, projection: boxProjection }),
255 // An event type added after this version, which its schema reads but never writes.
256 JSON.stringify({ kind: "event", sequence: 8, event: { type: "thread.teleported" } }),
257 encodeStreamItem({ kind: "event", ...archived(9) }),
258 ];
259 const b = yield* servePeer(
260 box,
261 Layer.empty,
262 HttpRouter.add(
263 "GET",
264 PEER_LINK_THREAD_STREAM_ROUTE,
265 Effect.succeed(
266 HttpServerResponse.stream(
267 Stream.fromIterable(frames).pipe(
268 Stream.map((frame) => `data: ${frame}\n\n`),
269 Stream.concat(Stream.never),
270 Stream.encodeText,
271 ),
272 { contentType: "text/event-stream" },
273 ),
274 ),
275 ),
276 );
277 const a = yield* makeLaptop;
278 yield* linkTo(a.links, b);
279
280 const relayed = yield* a.relay.subscribe(input).pipe(Stream.take(2), Stream.runCollect);
281 expect(relayed.map((item) => [item.kind, "sequence" in item ? item.sequence : null])).toEqual(
282 [
283 ["snapshot", null],
284 ["event", 9],
285 ],
286 );
287 // Each one goes on to this environment's client in the same encoding.
288 expect(relayed.map((item) => encodeStreamItem(item))).toHaveLength(2);
289 }),
290 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
291 );
292
293 it.effect("gives up on an answer whose body never arrives", () =>
294 Effect.scoped(
295 Effect.gen(function* () {
296 const stalled = (status: number) =>
297 Effect.succeed(
298 HttpServerResponse.stream(
299 Stream.make("{").pipe(Stream.concat(Stream.never), Stream.encodeText),
300 { status, contentType: "application/json" },
301 ),
302 );
303 const b = yield* servePeer(
304 box,
305 Layer.empty,
306 Layer.mergeAll(
307 HttpRouter.add("GET", PEER_LINK_THREAD_ITEM_ROUTE, stalled(200)),
308 HttpRouter.add("GET", PEER_LINK_THREAD_HISTORY_ROUTE, stalled(403)),
309 ),
310 );
311 const a = yield* makeLaptop;
312 yield* linkTo(a.links, b);
313
314 const item = yield* a.relay
315 .item({ ...input, itemId: boxItem })
316 .pipe(Effect.flip, Effect.forkScoped);
317 expect(yield* Queue.take(a.answered)).toBe(200);
318 yield* TestClock.adjust(Duration.seconds(10));
319 expect(yield* Fiber.join(item)).toMatchObject({ reason: "unreachable", label: "Box" });
320
321 // A refusal is known by its status, so its body is not waited for either.
322 const page = yield* a.relay
323 .historyPage({ ...input, cursor: "cursor-1" })
324 .pipe(Effect.flip, Effect.forkScoped);
325 expect(yield* Queue.take(a.answered)).toBe(403);
326 yield* TestClock.adjust(Duration.seconds(10));
327 expect(yield* Fiber.join(page)).toMatchObject({ reason: "rejected", label: "Box" });
328 }),
329 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
330 );