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