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

GuestShareService.test.ts

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