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

GuestShareService.test.ts

1,115 lines43.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 ChatAttachmentId,
5 CommandId,
6 EventId,
7 GuestShareId,
8 type GuestStreamEvent,
9 MessageId,
10 type OrchestrationV2TurnItem,
11 ProjectId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 RunId,
15 ThreadId,
16 TurnItemId,
17} from "@t3tools/contracts";
18import * as Context from "effect/Context";
19import * as DateTime from "effect/DateTime";
20import * as Deferred from "effect/Deferred";
21import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
22import * as Effect from "effect/Effect";
23import * as Exit from "effect/Exit";
24import * as FileSystem from "effect/FileSystem";
25import * as Fiber from "effect/Fiber";
26import * as Layer from "effect/Layer";
27import * as Queue from "effect/Queue";
28import * as Ref from "effect/Ref";
29import * as Stream from "effect/Stream";
30import * as TestClock from "effect/testing/TestClock";
31​
32import {
33 createAttachmentId,
34 resolveAttachmentPath,
35 resolveAttachmentPathById,
36 sweepStalePendingAttachments,
37} from "../attachmentStore.ts";
38import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
39import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";
40import * as ServerConfig from "../config.ts";
41import * as SqlitePersistence from "../persistence/Sqlite.ts";
42import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
43import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";
44import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts";
45import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
46import * as EventSink from "../orchestration-v2/EventSink.ts";
47import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
48import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
49import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
50import * as ResourceCleanupService from "../orchestration-v2/ResourceCleanupService.ts";
51import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
52import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
53import * as ServerSettings from "../serverSettings.ts";
54import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
55import * as GuestShareService from "./GuestShareService.ts";
56​
57const instanceId = ProviderInstanceId.make("codex");
58const adapter = {
59 instanceId,
60 driver: ProviderDriverKind.make("codex"),
61 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
62 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
63 openSession: () => Effect.die("No provider process needed for guest shares"),
64} as ProviderAdapter.ProviderAdapterV2["Service"];
65const layerDatabase = SqlitePersistence.layerMemory;
66const layerOrchestration = Layer.mergeAll(
67 layerDatabase,
68 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
69 EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
70 ProviderReplayHarness.layerWithRegistry(
71 { name: "guest-share-service" },
72 ProviderAdapterRegistry.layerFromAdapters([adapter]),
73 { databaseLayer: layerDatabase, runEffectWorker: false },
74 ),
75);
76​
77// The Connect hostname the fake tunnel reports. Tests set it to null to simulate an unlink.
78const hostname = Ref.makeUnsafe<string | null>("env.t3.test");
79const layerConnect = Layer.mock(CloudManagedEndpointRuntime)({
80 inspectConnector: Effect.map(Ref.get(hostname), (value) => ({
81 readyConnections: 1,
82 hostname: value,
83 protocol: "http2",
84 })),
85});
86const layerProviders = Layer.mock(ProviderRegistry.ProviderRegistry)({
87 getProviders: Effect.succeed([]),
88});
89const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-guest-share-" });
90// The real cleanup also closes terminals and previews; these tests only need the files gone.
91const layerCleanup = Layer.effect(
92 ResourceCleanupService.ResourceCleanupService,
93 Effect.gen(function* () {
94 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
95 const fileSystem = yield* FileSystem.FileSystem;
96 return {
97 cleanupScheduledTasks: () => Effect.void,
98 cleanupTerminals: () => Effect.void,
99 cleanupPreviews: () => Effect.void,
100 cleanupAttachments: (attachmentIds) =>
101 Effect.forEach(
102 attachmentIds,
103 (attachmentId) => {
104 const path = resolveAttachmentPathById({ attachmentsDir, attachmentId });
105 return path === null ? Effect.void : fileSystem.remove(path).pipe(Effect.orDie);
106 },
107 { discard: true },
108 ),
109 };
110 }),
111).pipe(Layer.provide(layerConfig), Layer.provide(NodeServices.layer));
112class RecordedAnalytics extends Context.Service<
113 RecordedAnalytics,
114 Ref.Ref<ReadonlyArray<Readonly<Record<string, unknown>>>>
115>()("t3/guest/GuestShareService.test/RecordedAnalytics") {}
116const layerAnalytics = Layer.effectContext(
117 Effect.gen(function* () {
118 const recorded = yield* Ref.make<ReadonlyArray<Readonly<Record<string, unknown>>>>([]);
119 return Context.make(RecordedAnalytics, recorded).pipe(
120 Context.add(
121 AnalyticsService.AnalyticsService,
122 AnalyticsService.AnalyticsService.of({
123 record: (event, properties) =>
124 Ref.update(recorded, (events) => [...events, { event, ...properties }]),
125 flush: Effect.void,
126 recordOwners: () => Effect.void,
127 }),
128 ),
129 );
130 }),
131);
132const layerTest = GuestShareService.layer.pipe(
133 Layer.provideMerge(
134 CommandOutputHub.layer.pipe(
135 Layer.provideMerge(layerOrchestration.pipe(Layer.provide(layerCleanup))),
136 ),
137 ),
138 Layer.provide(layerProviders),
139 Layer.provideMerge(ServerSettings.layerTest({ guestSharingEnabled: true })),
140 Layer.provide(layerConnect),
141 Layer.provideMerge(layerAnalytics),
142 Layer.provide(ServerSecretStore.layer),
143 Layer.provideMerge(layerConfig),
144 Layer.provideMerge(NodeServices.layer),
145);
146​
147const threadId = ThreadId.make("thread:guest-share-service");
148​
149const shareThreadFor = Effect.fn(function* (threadId: ThreadId) {
150 yield* Ref.set(hostname, "env.t3.test");
151 const orchestrator = yield* Orchestrator.OrchestratorV2;
152 yield* orchestrator.dispatch({
153 type: "thread.create",
154 commandId: CommandId.make(`create:${threadId}`),
155 threadId,
156 projectId: ProjectId.make("project:guest-share-service"),
157 title: "Review me",
158 modelSelection: { instanceId, model: "gpt-5.1-codex" },
159 runtimeMode: "full-access",
160 interactionMode: "default",
161 branch: null,
162 worktreePath: null,
163 createdBy: "user",
164 creationSource: "web",
165 });
166 const guestShares = yield* GuestShareService.GuestShareService;
167 const { url } = yield* guestShares.create({ threadId });
168 assert.isTrue(url.startsWith("https://env.t3.test/guest#"));
169 const credential = url.slice(url.indexOf("#") + 1);
170 return { orchestrator, guestShares, credential };
171});
172const shareThread = shareThreadFor(threadId);
173​
174it.effect("spends an invite once and ends the guest stream when the owner stops sharing", () =>
175 Effect.gen(function* () {
176 const { orchestrator, guestShares, credential } = yield* shareThread;
177 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
178 const again = yield* Effect.exit(guestShares.redeem({ credential, name: "Eve" }));
179 assert.isTrue(Exit.isFailure(again));
180 // The browser that joined can come back without the spent invite.
181 assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.check(session))));
182 // An invite token is not a session token.
183 assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(credential))));
184​
185 const events = yield* guestShares.stream(session);
186 yield* orchestrator.dispatch({
187 type: "thread.guest-share.close",
188 commandId: CommandId.make("close-guest-share"),
189 threadId,
190 });
191 const received = Array.from(yield* Stream.runCollect(events));
192 assert.deepEqual(
193 received.map((event) => (event.type === "thread" ? event.item.kind : event.type)),
194 ["view", "snapshot", "ended"],
195 );
196 assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(session))));
197 assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.check(session))));
198 }).pipe(Effect.provide(layerTest)),
199);
200​
201it.effect("counts a guest joining and sending, without their name or text", () =>
202 Effect.gen(function* () {
203 const { guestShares, credential } = yield* shareThread;
204 const { token: session, shareId } = yield* guestShares.redeem({ credential, name: "Sam" });
205 yield* guestShares.submit(session, { shareId, text: "Hello" }, []);
206 assert.deepEqual(yield* Ref.get(yield* RecordedAnalytics), [
207 { event: "feature.used", feature: "guest_share.join" },
208 { event: "feature.used", feature: "guest_message.submit", variant: "text_only" },
209 ]);
210 }).pipe(Effect.provide(layerTest)),
211);
212​
213it.effect("streams the owner's thread events after the share and a snapshot", () =>
214 Effect.gen(function* () {
215 const { orchestrator, guestShares, credential } = yield* shareThread;
216 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
217 const events = yield* guestShares.stream(session);
218 yield* orchestrator.dispatch({
219 type: "message.dispatch",
220 commandId: CommandId.make("owner-message"),
221 threadId,
222 messageId: MessageId.make("message:owner"),
223 text: "Fix the login bug",
224 attachments: [],
225 dispatchMode: { type: "defer_start" },
226 createdBy: "user",
227 creationSource: "web",
228 });
229 yield* orchestrator.dispatch({
230 type: "thread.guest-share.close",
231 commandId: CommandId.make("close-after-message"),
232 threadId,
233 });
234 const received = Array.from(yield* Stream.runCollect(events));
235 assert.equal(received.at(-1)?.type, "ended");
236 const turnItems = received.flatMap((event) =>
237 event.type === "thread" &&
238 event.item.kind === "event" &&
239 event.item.event.type === "turn-item.updated"
240 ? [event.item.event.payload]
241 : [],
242 );
243 assert.deepEqual(
244 turnItems.flatMap((item) => (item.type === "user_message" ? [item.text] : [])),
245 ["Fix the login bug"],
246 );
247 }).pipe(Effect.provide(layerTest)),
248);
249​
250it.effect("starts a stream with the runs and items already in the thread", () =>
251 Effect.gen(function* () {
252 const { orchestrator, guestShares, credential } = yield* shareThread;
253 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
254 yield* orchestrator.dispatch({
255 type: "message.dispatch",
256 commandId: CommandId.make("owner-message-before"),
257 threadId,
258 messageId: MessageId.make("message:before"),
259 text: "Fix the login bug",
260 attachments: [],
261 dispatchMode: { type: "defer_start" },
262 createdBy: "user",
263 creationSource: "web",
264 });
265 const [view, snapshot] = Array.from(
266 yield* Stream.runCollect(Stream.take(yield* guestShares.stream(session), 2)),
267 );
268 assert.equal(view?.type, "view");
269 if (snapshot?.type !== "thread" || snapshot.item.kind !== "snapshot") {
270 return assert.fail("Expected the thread snapshot second.");
271 }
272 assert.equal(snapshot.item.projection.runs.length, 1);
273 assert.include(
274 snapshot.item.projection.visibleTurnItems.map((row) => row.item.type),
275 "user_message",
276 );
277 }).pipe(Effect.provide(layerTest)),
278);
279​
280it.effect("redeems only a short invite whose signature and share id are both current", () =>
281 Effect.gen(function* () {
282 const { guestShares, credential: replaced } = yield* shareThread;
283 const { url } = yield* guestShares.create({ threadId });
284 const credential = url.slice(url.indexOf("#") + 1);
285 assert.match(credential, /^[\w-]{22}\.[\w-]{22}$/);
286​
287 const [shareId, signature] = credential.split(".");
288 const tampered = `${shareId}.${signature!.startsWith("A") ? "B" : "A"}${signature!.slice(1)}`;
289 for (const rejected of [tampered, replaced]) {
290 const error = yield* Effect.flip(guestShares.redeem({ credential: rejected, name: "Eve" }));
291 assert.equal(error.reason, "invalid");
292 }
293 assert.isTrue(
294 Exit.isSuccess(yield* Effect.exit(guestShares.redeem({ credential, name: "Sam" }))),
295 );
296 }).pipe(Effect.provide(layerTest)),
297);
298​
299it.effect("refuses guest requests once T3 Connect no longer serves the link's host", () =>
300 Effect.gen(function* () {
301 const { guestShares, credential } = yield* shareThread;
302 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
303 const { id: shareId } = (yield* Orchestrator.OrchestratorV2.use((orchestrator) =>
304 orchestrator.getThreadRecords(threadId, []),
305 )).thread.guestShare!;
306 yield* Ref.set(hostname, null);
307 const submitted = yield* Effect.exit(
308 guestShares.submit(session, { shareId, text: "Hello" }, []),
309 );
310 assert.isTrue(Exit.isFailure(submitted));
311 }).pipe(Effect.provide(layerTest)),
312);
313​
314it.effect("closes an open guest stream when T3 Connect stops serving the link's host", () =>
315 Effect.gen(function* () {
316 const { guestShares, credential } = yield* shareThread;
317 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
318 const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(
319 Effect.forkChild,
320 );
321 yield* Ref.set(hostname, null);
322 yield* TestClock.adjust("30 seconds");
323 // No `ended`: the browser reconnects, and the host check refuses it while Connect is gone.
324 const received = Array.from(yield* Fiber.join(collecting));
325 assert.deepEqual(
326 received.map((event) => (event.type === "thread" ? event.item.kind : event.type)),
327 ["view", "snapshot"],
328 );
329 assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.stream(session))));
330 yield* Ref.set(hostname, "env.t3.test");
331 assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.stream(session))));
332 }).pipe(Effect.provide(layerTest)),
333);
334​
335it.effect("refuses new links and every guest request while the beta is off", () =>
336 Effect.gen(function* () {
337 const { guestShares, credential } = yield* shareThread;
338 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
339 const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(
340 Effect.forkChild,
341 );
342 const settings = yield* ServerSettings.ServerSettingsService;
343 yield* settings.updateSettings({ guestSharingEnabled: false });
344 // An open stream closes at the next access check.
345 yield* TestClock.adjust("30 seconds");
346 yield* Fiber.join(collecting);
347 assert.equal((yield* Effect.flip(guestShares.create({ threadId }))).reason, "disabled");
348 assert.equal((yield* Effect.flip(guestShares.check(session))).reason, "inactive");
349 // Turning it back on lets the same guest back in.
350 yield* settings.updateSettings({ guestSharingEnabled: true });
351 assert.isTrue(Exit.isSuccess(yield* Effect.exit(guestShares.check(session))));
352 }).pipe(Effect.provide(layerTest)),
353);
354​
355it.effect("ends an open guest stream when the link expires", () =>
356 Effect.gen(function* () {
357 const { guestShares, credential } = yield* shareThread;
358 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
359 const collecting = yield* Stream.runCollect(yield* guestShares.stream(session)).pipe(
360 Effect.forkChild,
361 );
362 yield* TestClock.adjust("25 hours");
363 const received = Array.from(yield* Fiber.join(collecting));
364 assert.equal(received.at(-1)?.type, "ended");
365 }).pipe(Effect.provide(layerTest)),
366);
367​
368it.effect("shows the guest the thread's new model", () =>
369 Effect.gen(function* () {
370 const { orchestrator, guestShares, credential } = yield* shareThread;
371 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
372 const events = yield* guestShares.stream(session);
373 yield* orchestrator.dispatch({
374 type: "thread.model-selection.set",
375 commandId: CommandId.make("switch-model"),
376 threadId,
377 modelSelection: { instanceId, model: "gpt-5.2-codex" },
378 });
379 yield* orchestrator.dispatch({
380 type: "thread.guest-share.close",
381 commandId: CommandId.make("close-after-switch"),
382 threadId,
383 });
384 const views = Array.from(yield* Stream.runCollect(events)).flatMap((event) =>
385 event.type === "view" ? [event.view.model.name] : [],
386 );
387 assert.include(views, "gpt-5.2-codex");
388 }).pipe(Effect.provide(layerTest)),
389);
390​
391it.effect("refuses a message a page sends for a share the cookie no longer opens", () =>
392 Effect.gen(function* () {
393 const { guestShares, credential } = yield* shareThread;
394 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
395 const submitted = yield* Effect.exit(
396 guestShares.submit(session, { shareId: GuestShareId.make("share:older"), text: "Hello" }, []),
397 );
398 assert.isTrue(Exit.isFailure(submitted));
399 }).pipe(Effect.provide(layerTest)),
400);
401​
402it.effect("serves no render for an item outside the shared thread", () =>
403 Effect.gen(function* () {
404 const { guestShares, credential } = yield* shareThread;
405 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
406 assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.render(session, "item:missing"))));
407 // The invite itself is not a session.
408 assert.isTrue(
409 Exit.isFailure(yield* Effect.exit(guestShares.render(credential, "item:missing"))),
410 );
411 }).pipe(Effect.provide(layerTest)),
412);
413​
414/** A message from the owner, which opens a run for the command below. */
415const ownerRun = Effect.gen(function* () {
416 const orchestrator = yield* Orchestrator.OrchestratorV2;
417 yield* orchestrator.dispatch({
418 type: "message.dispatch",
419 commandId: CommandId.make("owner-message-for-command"),
420 threadId,
421 messageId: MessageId.make("message:command"),
422 text: "Build it",
423 attachments: [],
424 dispatchMode: { type: "defer_start" },
425 createdBy: "user",
426 creationSource: "web",
427 });
428 const { runs } = (yield* orchestrator.getThreadSnapshotWindow(threadId, { rowLimit: 10 }))
429 .projection;
430 return runs[0]!.id;
431});
432​
433const writeCommand = (
434 id: string,
435 fields: Pick<
436 Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
437 "status" | "output"
438 >,
439) =>
440 Effect.gen(function* () {
441 const runId = yield* ownerRun;
442 const eventSink = yield* EventSink.EventSinkV2;
443 const now = yield* DateTime.now;
444 yield* eventSink.write({
445 events: [
446 {
447 id: EventId.make(`event:${id}`),
448 type: "turn-item.updated",
449 threadId,
450 driver: ProviderDriverKind.make("codex"),
451 providerInstanceId: instanceId,
452 occurredAt: now,
453 payload: {
454 id: TurnItemId.make(id),
455 threadId,
456 runId,
457 nodeId: null,
458 providerThreadId: null,
459 providerTurnId: null,
460 nativeItemRef: null,
461 parentItemId: null,
462 ordinal: 1,
463 title: null,
464 startedAt: now,
465 completedAt: fields.status === "running" ? null : now,
466 updatedAt: now,
467 type: "command_execution",
468 input: "ls /work/src",
469 ...fields,
470 },
471 },
472 ],
473 });
474 return TurnItemId.make(id);
475 });
476​
477it.effect("gives the guest a command's detail and output, as the owner's row loads them", () =>
478 Effect.gen(function* () {
479 const { guestShares, credential } = yield* shareThread;
480 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
481 const command = yield* writeCommand("item:command", {
482 status: "completed",
483 output: "/work/src/auth.ts\n",
484 });
485​
486 const detail = (yield* guestShares.item(session, command)).item;
487 assert.deepInclude(detail, { input: "ls /work/src", output: "/work/src/auth.ts\n" });
488 const frames = Array.from(
489 yield* Stream.runCollect(yield* guestShares.commandOutput(session, command)),
490 );
491 assert.deepEqual(frames, [
492 { kind: "replace", text: "/work/src/auth.ts\n", truncated: false, running: false },
493 ]);
494 // Only with a session, and only for an item of this thread.
495 const refused: ReadonlyArray<Effect.Effect<unknown, GuestShareService.GuestShareAccessError>> =
496 [
497 guestShares.item(credential, command),
498 guestShares.commandOutput(credential, command),
499 guestShares.item(session, "item:elsewhere"),
500 ];
501 for (const request of refused) {
502 assert.isTrue(Exit.isFailure(yield* Effect.exit(request)));
503 }
504 }).pipe(Effect.provide(layerTest)),
505);
506​
507it.effect("ends a running command's output once the owner stops sharing", () =>
508 Effect.gen(function* () {
509 const { orchestrator, guestShares, credential } = yield* shareThread;
510 const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
511 const command = yield* writeCommand("item:running", { status: "running" });
512 const collecting = yield* Stream.runCollect(
513 yield* guestShares.commandOutput(session, command),
514 ).pipe(Effect.forkChild);
515 yield* orchestrator.dispatch({
516 type: "thread.guest-share.close",
517 commandId: CommandId.make("close-during-command"),
518 threadId,
519 });
520 yield* TestClock.adjust("30 seconds");
521 const frames = Array.from(yield* Fiber.join(collecting));
522 assert.isTrue(frames.every((frame) => frame.running));
523 assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command))));
524 }).pipe(Effect.provide(layerTest)),
525);
526​
527const PNG = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13);
528const MIB = 1024 * 1024;
529​
530/** Files as the multipart parser leaves them: on disk, with the browser's name and type. */
531const uploadsOf = Effect.fn(function* (
532 files: ReadonlyArray<{
533 readonly name: string;
534 readonly contentType: string;
535 readonly bytes: Uint8Array;
536 }>,
537) {
538 const fileSystem = yield* FileSystem.FileSystem;
539 const directory = yield* fileSystem.makeTempDirectoryScoped();
540 return yield* Effect.forEach(files, (file, index) => {
541 const path = `${directory}/${index}`;
542 return fileSystem
543 .writeFile(path, file.bytes)
544 .pipe(Effect.as({ name: file.name, contentType: file.contentType, path }));
545 });
546});
547const png = (name: string, sizeBytes = PNG.length) => {
548 const bytes = new Uint8Array(sizeBytes);
549 bytes.set(PNG);
550 return { name, contentType: "image/png", bytes };
551};
552​
553/** Every stored attachment file. */
554const storedFiles = Effect.gen(function* () {
555 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
556 const fileSystem = yield* FileSystem.FileSystem;
557 return yield* fileSystem.readDirectory(attachmentsDir).pipe(Effect.orElseSucceed(() => []));
558});
559​
560const joinedGuest = Effect.gen(function* () {
561 const shared = yield* shareThread;
562 const { token: session, shareId } = yield* shared.guestShares.redeem({
563 credential: shared.credential,
564 name: "Sam",
565 });
566 return { ...shared, session, shareId };
567});
568​
569const waitingMessages = Effect.gen(function* () {
570 const orchestrator = yield* Orchestrator.OrchestratorV2;
571 const { thread } = yield* orchestrator.getThreadRecords(threadId, []);
572 return thread.guestShare?.messages ?? [];
573});
574​
575it.effect("refuses too many files, too many bytes, and images that are not what they say", () =>
576 Effect.gen(function* () {
577 const { guestShares, session, shareId } = yield* joinedGuest;
578 const before = yield* storedFiles;
579 const refused = [
580 ["too_many_files", [1, 2, 3, 4, 5].map((index) => png(`${index}.png`))],
581 ["too_large", [png("big.png", 10 * MIB + 1)]],
582 ["unsupported_file", [{ name: "logo.svg", contentType: "image/svg+xml", bytes: PNG }]],
583 [
584 "unsupported_file",
585 [{ name: "page.png", contentType: "image/png", bytes: new TextEncoder().encode("<html>") }],
586 ],
587 [
588 "unsupported_file",
589 [{ name: "empty.txt", contentType: "text/plain", bytes: new Uint8Array() }],
590 ],
591 ] as const;
592 for (const [reason, files] of refused) {
593 const error = yield* Effect.flip(
594 guestShares.submit(session, { shareId, text: "Look" }, yield* uploadsOf(files)),
595 );
596 assert.equal(error.reason, reason);
597 }
598 // Nothing is kept from a refused message, and no message waits.
599 assert.deepEqual(yield* storedFiles, before);
600 assert.deepEqual(yield* waitingMessages, []);
601​
602 yield* guestShares.submit(
603 session,
604 { shareId, text: "" },
605 yield* uploadsOf([
606 png("screen.png"),
607 // A direction override would make this name read as a PDF.
608 {
609 name: "notes\u202Efdp.html",
610 contentType: "text/html",
611 bytes: new TextEncoder().encode("<b>"),
612 },
613 ]),
614 );
615 const [message] = yield* waitingMessages;
616 assert.deepEqual(
617 message?.attachments?.map(({ type, name, mimeType, sizeBytes }) => ({
618 type,
619 name,
620 mimeType,
621 sizeBytes,
622 })),
623 [
624 { type: "image", name: "screen.png", mimeType: "image/png", sizeBytes: PNG.length },
625 { type: "file", name: "notes_fdp.html", mimeType: "text/html", sizeBytes: 3 },
626 ],
627 );
628 }).pipe(Effect.scoped, Effect.provide(layerTest)),
629);
630​
631it.effect("caps the bytes of files waiting in one share", () =>
632 Effect.gen(function* () {
633 const { guestShares, session, shareId } = yield* joinedGuest;
634 const submit = (sizeBytes: number) =>
635 Effect.gen(function* () {
636 return guestShares.submit(
637 session,
638 { shareId, text: "Look" },
639 yield* uploadsOf([png("big.png", sizeBytes)]),
640 );
641 }).pipe(Effect.flatten);
642 yield* submit(9 * MIB);
643 yield* submit(9 * MIB);
644 const error = yield* Effect.flip(submit(9 * MIB));
645 assert.equal(error.reason, "files_busy");
646 // Text alone still goes through.
647 yield* guestShares.submit(session, { shareId, text: "One more thing" }, []);
648 assert.equal((yield* waitingMessages).length, 3);
649 }).pipe(Effect.scoped, Effect.provide(layerTest)),
650);
651​
652it.effect("deletes a waiting message's files when the owner dismisses it or stops sharing", () =>
653 Effect.gen(function* () {
654 const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
655 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
656 yield* guestShares.submit(
657 session,
658 { shareId, text: "First" },
659 yield* uploadsOf([png("a.png")]),
660 );
661 yield* guestShares.submit(
662 session,
663 { shareId, text: "Second" },
664 yield* uploadsOf([png("b.png")]),
665 );
666 const [first, second] = yield* waitingMessages;
667 const fileOf = (message: typeof first) => message!.attachments![0]!.id;
668 const stored = yield* storedFiles;
669 assert.isTrue(stored.some((entry) => entry.startsWith(fileOf(first))));
670​
671 yield* orchestrator.dispatch({
672 type: "thread.guest-message.dismiss",
673 commandId: CommandId.make("dismiss-first"),
674 threadId,
675 guestMessageId: first!.id,
676 });
677 yield* worker.drain();
678 const afterDismiss = yield* storedFiles;
679 assert.isFalse(afterDismiss.some((entry) => entry.startsWith(fileOf(first))));
680 assert.isTrue(afterDismiss.some((entry) => entry.startsWith(fileOf(second))));
681 // A dismissed message's file is no longer the guest's to load.
682 assert.isTrue(
683 Exit.isFailure(yield* Effect.exit(guestShares.attachment(session, fileOf(first)))),
684 );
685​
686 yield* orchestrator.dispatch({
687 type: "thread.guest-share.close",
688 commandId: CommandId.make("close-with-files"),
689 threadId,
690 });
691 yield* worker.drain();
692 assert.isFalse((yield* storedFiles).some((entry) => entry.startsWith(fileOf(second))));
693 }).pipe(Effect.scoped, Effect.provide(layerTest)),
694);
695​
696it.effect.each(["thread.archive", "thread.delete"] as const)(
697 "deletes a waiting message's files on %s",
698 (type) =>
699 Effect.gen(function* () {
700 const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
701 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
702 const before = yield* storedFiles;
703 yield* guestShares.submit(
704 session,
705 { shareId, text: "Look" },
706 yield* uploadsOf([png("a.png")]),
707 );
708 assert.equal((yield* storedFiles).length, before.length + 1);
709 yield* orchestrator.dispatch({
710 type,
711 commandId: CommandId.make(`${type}-with-files`),
712 threadId,
713 });
714 yield* worker.drain();
715 assert.deepEqual(yield* storedFiles, before);
716 }).pipe(Effect.scoped, Effect.provide(layerTest)),
717);
718​
719it.effect("sends a guest's files as the guest's message and keeps them the guest's to load", () =>
720 Effect.gen(function* () {
721 const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
722 yield* guestShares.submit(
723 session,
724 { shareId, text: "See this" },
725 yield* uploadsOf([png("a.png")]),
726 );
727 const [message] = yield* waitingMessages;
728 const pending = message!.attachments!;
729 // Served while it waits.
730 const served = yield* guestShares.attachment(session, pending[0]!.id);
731 assert.equal(served.attachment.mimeType, "image/png");
732​
733 // The day-old pending-upload sweep leaves a waiting guest's files alone.
734 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
735 // Any pending upload counts as stale at the end of time.
736 sweepStalePendingAttachments({ attachmentsDir, nowMs: Number.MAX_SAFE_INTEGER });
737 const copied = pending[0]!;
738 yield* orchestrator.dispatch({
739 type: "message.dispatch",
740 commandId: CommandId.make("send-guest-files"),
741 threadId,
742 messageId: MessageId.make("message:guest-files"),
743 guestMessageId: message!.id,
744 text: "",
745 attachments: [copied],
746 dispatchMode: { type: "defer_start" },
747 createdBy: "user",
748 creationSource: "web",
749 });
750 const items = (yield* orchestrator.getThreadSnapshotWindow(threadId, {
751 rowLimit: 20,
752 })).projection.visibleTurnItems.map((entry) => entry.item);
753 const sent = items.find(
754 (item) => item.type === "user_message" && item.context?.guest?.guestMessageId === message!.id,
755 );
756 assert.deepInclude(sent, { attachments: [copied] });
757 if (sent?.type !== "user_message") return;
758 assert.deepEqual(sent.context?.guest, {
759 guestMessageId: message!.id,
760 name: "Sam",
761 text: "See this",
762 shareId,
763 });
764 // The guest loads the thread's copy from their own row.
765 const fromRow = yield* guestShares.attachment(session, copied.id);
766 assert.equal(fromRow.attachment.id, copied.id);
767​
768 // Still theirs after their share's message list has trimmed it away.
769 for (let index = 0; index < 21; index += 1) {
770 yield* guestShares.submit(session, { shareId, text: `note ${index}` }, []);
771 const [waiting] = (yield* waitingMessages).filter((next) => next.status === "pending");
772 yield* orchestrator.dispatch({
773 type: "thread.guest-message.dismiss",
774 commandId: CommandId.make(`dismiss-note-${index}`),
775 threadId,
776 guestMessageId: waiting!.id,
777 });
778 }
779 assert.isFalse((yield* waitingMessages).some((next) => next.id === message!.id));
780 assert.equal((yield* guestShares.attachment(session, copied.id)).attachment.id, copied.id);
781 }).pipe(Effect.scoped, Effect.provide(layerTest)),
782);
783​
784it.effect("serves the shared thread's files to its guest, never another thread's", () =>
785 Effect.gen(function* () {
786 const { orchestrator, guestShares, session, shareId } = yield* joinedGuest;
787 // Another thread's guest attaches a file.
788 const other = yield* shareThreadFor(ThreadId.make("thread:other-share"));
789 const otherGuest = yield* guestShares.redeem({ credential: other.credential, name: "Eve" });
790 yield* guestShares.submit(
791 otherGuest.token,
792 { shareId: otherGuest.shareId, text: "Mine" },
793 yield* uploadsOf([png("eve.png")]),
794 );
795 const { thread: otherThread } = yield* orchestrator.getThreadRecords(
796 ThreadId.make("thread:other-share"),
797 [],
798 );
799 const othersFile = otherThread.guestShare!.messages[0]!.attachments![0]!.id;
800 assert.isTrue(
801 Exit.isSuccess(yield* Effect.exit(guestShares.attachment(otherGuest.token, othersFile))),
802 );
803​
804 // The owner sends a message with an image of their own.
805 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
806 const fileSystem = yield* FileSystem.FileSystem;
807 const ownerImage = {
808 type: "image" as const,
809 id: ChatAttachmentId.make(createAttachmentId(threadId)!),
810 name: "secret.png",
811 mimeType: "image/png",
812 sizeBytes: PNG.length,
813 };
814 yield* fileSystem.writeFile(
815 resolveAttachmentPath({ attachmentsDir, attachment: ownerImage })!,
816 PNG,
817 );
818 yield* orchestrator.dispatch({
819 type: "message.dispatch",
820 commandId: CommandId.make("owner-image"),
821 threadId,
822 messageId: MessageId.make("message:owner-image"),
823 text: "My screen",
824 attachments: [ownerImage],
825 dispatchMode: { type: "defer_start" },
826 createdBy: "user",
827 creationSource: "web",
828 });
829​
830 // The guest sees the thread as the owner does, files included.
831 assert.equal(
832 (yield* guestShares.attachment(session, ownerImage.id)).attachment.id,
833 ownerImage.id,
834 );
835 for (const id of [othersFile, "pending-missing"]) {
836 const error = yield* Effect.flip(guestShares.attachment(session, id));
837 assert.equal(error.reason, "unavailable");
838 }
839 // Nor with the other share's id on this page.
840 assert.equal(
841 (yield* Effect.flip(
842 guestShares.submit(session, { shareId: otherGuest.shareId, text: "x" }, []),
843 )).reason,
844 "stale_page",
845 );
846 assert.isDefined(shareId);
847 }).pipe(Effect.scoped, Effect.provide(layerTest)),
848);
849​
850it.effect("serves an image on the host only when an agent reply the guest sees shows it", () =>
851 Effect.gen(function* () {
852 const { orchestrator, guestShares } = yield* shareThread;
853 const runId = yield* ownerRun;
854 const fileSystem = yield* FileSystem.FileSystem;
855 const directory = yield* fileSystem.makeTempDirectoryScoped();
856 const shot = `${directory}/my shot.png`;
857 const fileUrl = `${directory}/file-url.png`;
858 const page = `${directory}/page.png`;
859 const fromUser = `${directory}/from-user.png`;
860 const unnamed = `${directory}/unnamed.png`;
861 const later = `${directory}/later.png`;
862 for (const path of [shot, fileUrl, fromUser, unnamed, later]) {
863 yield* fileSystem.writeFile(path, PNG);
864 }
865 yield* fileSystem.writeFileString(page, "<script>alert(1)</script>");
866 const eventSink = yield* EventSink.EventSinkV2;
867 const now = yield* DateTime.now;
868 const run = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs[0];
869 const item = (
870 id: string,
871 ordinal: number,
872 fields:
873 | { readonly type: "assistant_message"; readonly text: string }
874 | { readonly type: "user_message"; readonly text: string },
875 target: { readonly threadId: ThreadId; readonly runId: RunId } = { threadId, runId },
876 ) => ({
877 id: EventId.make(`event:${id}`),
878 type: "turn-item.updated" as const,
879 threadId: target.threadId,
880 driver: ProviderDriverKind.make("codex"),
881 providerInstanceId: instanceId,
882 occurredAt: now,
883 payload: {
884 id: TurnItemId.make(id),
885 threadId: target.threadId,
886 runId: target.runId,
887 nodeId: null,
888 providerThreadId: null,
889 providerTurnId: null,
890 nativeItemRef: null,
891 parentItemId: null,
892 ordinal,
893 title: null,
894 status: "completed" as const,
895 startedAt: now,
896 completedAt: now,
897 updatedAt: now,
898 messageId: MessageId.make(id),
899 ...(fields.type === "assistant_message"
900 ? { ...fields, streaming: false }
901 : {
902 ...fields,
903 createdBy: "user" as const,
904 creationSource: "web" as const,
905 inputIntent: "turn_start" as const,
906 attachments: [],
907 }),
908 },
909 });
910 yield* eventSink.write({
911 events: [
912 item("item:agent-images", 1, {
913 type: "assistant_message",
914 text: `Done: ![Shot](<${shot}>) ![Other](file://${encodeURI(fileUrl)}) ![Page](${page})`,
915 }),
916 // A guest's sent message is a user message; it must not open files on the host.
917 item("item:guest-image", 2, { type: "user_message", text: `![Mine](${fromUser})` }),
918 {
919 id: EventId.make("event:run-done"),
920 type: "run.updated" as const,
921 threadId,
922 runId,
923 providerInstanceId: instanceId,
924 occurredAt: now,
925 payload: { ...run!, status: "completed" as const, completedAt: now },
926 },
927 ],
928 });
929 // The guest watches a fork, which shows these replies as inherited history.
930 const forkId = ThreadId.make("thread:guest-share-fork");
931 yield* orchestrator.dispatch({
932 type: "thread.fork",
933 commandId: CommandId.make("fork"),
934 sourceThreadId: threadId,
935 targetThreadId: forkId,
936 sourcePoint: { type: "run", runId },
937 createdBy: "user",
938 creationSource: "web",
939 });
940 const { url } = yield* guestShares.create({ threadId: forkId });
941 const { token: session } = yield* guestShares.redeem({
942 credential: url.slice(url.indexOf("#") + 1),
943 name: "Sam",
944 });
945​
946 // The guest's page opens, and its stream sends the replies the fork inherits.
947 const sent = yield* Queue.unbounded<GuestStreamEvent>();
948 yield* Stream.runForEach(yield* guestShares.stream(session), (event) =>
949 Queue.offer(sent, event),
950 ).pipe(Effect.forkScoped);
951 const sentItem = Effect.fn(function* (id: string) {
952 for (;;) {
953 const event = yield* Queue.take(sent);
954 if (
955 event.type === "thread" &&
956 event.item.kind === "event" &&
957 event.item.event.type === "turn-item.updated" &&
958 event.item.event.payload.id === id
959 ) {
960 return;
961 }
962 }
963 });
964​
965 // The agent shows another screenshot live, then enough rows to push the first reply out of
966 // the window, before the page asks for any image.
967 yield* orchestrator.dispatch({
968 type: "message.dispatch",
969 commandId: CommandId.make("fork-message"),
970 threadId: forkId,
971 messageId: MessageId.make("message:fork"),
972 text: "One more",
973 attachments: [],
974 dispatchMode: { type: "defer_start" },
975 createdBy: "user",
976 creationSource: "web",
977 });
978 const forkRun = (yield* orchestrator.getThreadRecords(forkId, ["runs"])).runs.at(-1)!;
979 const inFork = { threadId: forkId, runId: forkRun.id };
980 yield* eventSink.write({
981 events: [
982 item(
983 "item:later-image",
984 1,
985 { type: "assistant_message", text: `![Later](${later})` },
986 inFork,
987 ),
988 ...Array.from({ length: 600 }, (_, index) =>
989 item(
990 `item:filler-${index}`,
991 index + 2,
992 { type: "assistant_message", text: "Working." },
993 inFork,
994 ),
995 ),
996 ],
997 });
998 yield* sentItem("item:later-image");
999​
1000 // The page still shows every reply it was sent, so each image loads.
1001 for (const path of [shot, fileUrl, later]) {
1002 assert.deepStrictEqual(yield* guestShares.media(session, path), {
1003 path,
1004 mimeType: "image/png",
1005 });
1007 for (const path of [page, fromUser, unnamed, `${directory}/missing.png`]) {
1008 assert.equal((yield* Effect.flip(guestShares.media(session, path))).reason, "unavailable");
1010​
1011 // A reply edited to drop its image stops allowing it.
1012 yield* eventSink.write({
1013 events: [
1015 ...item("item:later-image", 1, { type: "assistant_message", text: "Gone." }, inFork),
1016 id: EventId.make("event:later-image-edited"),
1017 },
1018 ],
1019 });
1020 yield* sentItem("item:later-image");
1021 assert.equal((yield* Effect.flip(guestShares.media(session, later))).reason, "unavailable");
1022 }).pipe(Effect.scoped, Effect.provide(layerTest)),
1024​
1025it.effect("keeps a connected guest's images while other shares come and go", () =>
1026 Effect.gen(function* () {
1027 const fileSystem = yield* FileSystem.FileSystem;
1028 const directory = yield* fileSystem.makeTempDirectoryScoped();
1029 const shot = `${directory}/shot.png`;
1030 yield* fileSystem.writeFile(shot, PNG);
1031 const eventSink = yield* EventSink.EventSinkV2;
1032 const now = yield* DateTime.now;
1033 /** A shared thread whose agent reply shows the screenshot, and its guest's session. */
1034 const sharedWithImage = Effect.fn(function* (id: ThreadId) {
1035 const { orchestrator, guestShares, credential } = yield* shareThreadFor(id);
1036 yield* orchestrator.dispatch({
1037 type: "message.dispatch",
1038 commandId: CommandId.make(`message:${id}`),
1039 threadId: id,
1040 messageId: MessageId.make(`message:${id}`),
1041 text: "Show me",
1042 attachments: [],
1043 dispatchMode: { type: "defer_start" },
1044 createdBy: "user",
1045 creationSource: "web",
1046 });
1047 const runId = (yield* orchestrator.getThreadRecords(id, ["runs"])).runs[0]!.id;
1048 yield* eventSink.write({
1049 events: [
1051 id: EventId.make(`event:reply:${id}`),
1052 type: "turn-item.updated",
1053 threadId: id,
1054 driver: ProviderDriverKind.make("codex"),
1055 providerInstanceId: instanceId,
1056 occurredAt: now,
1057 payload: {
1058 id: TurnItemId.make(`item:reply:${id}`),
1059 threadId: id,
1060 runId,
1061 nodeId: null,
1062 providerThreadId: null,
1063 providerTurnId: null,
1064 nativeItemRef: null,
1065 parentItemId: null,
1066 ordinal: 1,
1067 title: null,
1068 status: "completed",
1069 startedAt: now,
1070 completedAt: now,
1071 updatedAt: now,
1072 type: "assistant_message",
1073 messageId: MessageId.make(`item:reply:${id}`),
1074 text: `![Shot](${shot})`,
1075 streaming: false,
1076 },
1077 },
1078 ],
1079 });
1080 const { token } = yield* guestShares.redeem({ credential, name: "Sam" });
1081 return { guestShares, token };
1082 });
1083​
1084 // This guest's page stays open while more guests than the record keeps open and close theirs.
1085 const { guestShares, token } = yield* sharedWithImage(threadId);
1086 const opened = yield* Deferred.make<void>();
1087 yield* Stream.runForEach(yield* guestShares.stream(token), () =>
1088 Deferred.succeed(opened, undefined),
1089 ).pipe(Effect.forkScoped);
1090 yield* Deferred.await(opened);
1091 const closedTokens: Array<string> = [];
1092 for (let index = 0; index < 65; index++) {
1093 const other = yield* sharedWithImage(ThreadId.make(`thread:other-${index}`));
1094 const events = yield* guestShares.stream(other.token);
1095 // The first is built but never read, as for a HEAD request; the rest open and close.
1096 if (index > 0) yield* Stream.runDrain(Stream.take(events, 2));
1097 closedTokens.push(other.token);
1099 assert.equal((yield* guestShares.media(token, shot)).mimeType, "image/png");
1100 // Records of guests with no open page were dropped to make room.
1101 for (const closed of closedTokens.slice(0, 2)) {
1102 assert.equal((yield* Effect.flip(guestShares.media(closed, shot))).reason, "unavailable");
1104​
1105 // A new link on the thread starts empty: its guest gets nothing the last guest was sent.
1106 const { url } = yield* guestShares.create({ threadId });
1107 const next = yield* guestShares.redeem({
1108 credential: url.slice(url.indexOf("#") + 1),
1109 name: "Kim",
1110 });
1111 assert.equal((yield* Effect.flip(guestShares.media(next.token, shot))).reason, "unavailable");
1112 yield* Stream.runDrain(Stream.take(yield* guestShares.stream(next.token), 2));
1113 assert.equal((yield* guestShares.media(next.token, shot)).mimeType, "image/png");
1114 }).pipe(Effect.scoped, Effect.provide(layerTest)),