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

GuestShareService.ts

818 lines32.5 KB

1import {
2 type ChatAttachment,
3 ChatAttachmentId,
4 CommandId,
5 GUEST_SHARE_TTL_MS,
6 GuestMessageId,
7 GuestShareCreateError,
8 type GuestShareCreateInput,
9 type GuestShareCreateResult,
10 GuestShareId,
11 type GuestRedeemRequest,
12 type GuestStreamEvent,
13 type GuestSubmitRequest,
14 type OrchestrationV2AppThread,
15 type OrchestrationV2CommandOutputFrame,
16 type OrchestrationV2DomainEvent,
17 type OrchestrationV2GetTurnItemResult,
18 type OrchestrationV2ThreadHistoryPage,
19 type OrchestrationV2TurnItem,
20 ThreadId,
21 TurnItemId,
22} from "@t3tools/contracts";
23import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline";
24import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
25import * as Context from "effect/Context";
26import * as SecureRandom from "effect/crypto/SecureRandom";
27import * as DateTime from "effect/DateTime";
28import * as Duration from "effect/Duration";
29import * as Effect from "effect/Effect";
30import * as FileSystem from "effect/FileSystem";
31import * as Layer from "effect/Layer";
32import * as Option from "effect/Option";
33import * as Schedule from "effect/Schedule";
34import * as Schema from "effect/Schema";
35import * as Stream from "effect/Stream";
36​
37import { base64UrlDecodeUtf8, base64UrlEncode, timingSafeEqualBase64Url } from "../auth/utils.ts";
38import * as PayloadSigner from "../auth/PayloadSigner.ts";
39import {
40 attachmentFileExtension,
41 createAttachmentId,
42 resolveAttachmentPath,
43 resolveAttachmentPathById,
44 threadHtmlRenderAttachmentIds,
45} from "../attachmentStore.ts";
46import * as ServerConfig from "../config.ts";
47import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";
48import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";
49import { GUEST_FAILURE } from "../orchestration-v2/GuestShareDecider.ts";
50import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
51import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoalescer.ts";
52import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts";
53import {
54 projectTurnItemForDetail,
55 threadStreamEventItem,
56} from "../orchestration-v2/WireProjection.ts";
57import * as DocumentText from "../provider/DocumentText.ts";
58import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
59import * as ServerSettings from "../serverSettings.ts";
60import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
61import { guestShareView, guestThreadModel } from "./guestView.ts";
62import {
63 classifyGuestUploads,
64 GUEST_UPLOAD_HEADER_BYTES,
65 guestHostImageType,
66 type GuestUpload,
67 matchesImageSignature,
68 repliesShowImage,
69} from "./guestAttachments.ts";
70​
71const SIGNING_SECRET_NAME = "guest-share-signing-key";
72const SHARE_ID_BYTES = 16;
73const INVITE_SIGNATURE_BYTES = 16;
74const SNAPSHOT_ROW_LIMIT = 600;
75const SNAPSHOT_USER_TURN_LIMIT = 20;
76// Shares with no open guest stream whose sent image replies are still kept.
77const SHARED_THREAD_REPLIES_LIMIT = 64;
78// How soon an open read notices that its link stopped working, such as Connect no longer serving
79// the host. Closing or replacing the link ends the main stream at once.
80const ACCESS_RECHECK_INTERVAL = Duration.seconds(30);
81​
82const GUEST_ACCESS_MESSAGES = {
83 ...GUEST_FAILURE,
84 invalid: "This guest link is not valid.",
85 stale_page: "This page is for an older guest link. Reload it to continue.",
86 unavailable: "This item is not available.",
87 rejected: "The owner's server rejected this request.",
88 empty: "Write a message or attach a file.",
89 too_many_files: "Attach up to 4 files to a message.",
90 too_large: "Attached files can total up to 10 MB per message.",
91 unsupported_file: "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP.",
92 files_busy: GUEST_FAILURE.filesBusy,
93} as const;
94​
95/** What a guest is told. The message comes from `reason`, never from a cause. */
96export class GuestShareAccessError extends Schema.TaggedError<GuestShareAccessError>()(
97 "GuestShareAccessError",
98 {
99 reason: Schema.Literals([
100 "invalid",
101 "inactive",
102 "used",
103 "busy",
104 "stale_page",
105 "unavailable",
106 "rejected",
107 "empty",
108 "too_many_files",
109 "too_large",
110 "unsupported_file",
111 "files_busy",
112 ]),
113 },
114) {
115 override get message(): string {
116 return GUEST_ACCESS_MESSAGES[this.reason];
117 }
119​
120const guestFailureReason = (cause: unknown): GuestShareAccessError["reason"] =>
121 cause === GUEST_FAILURE.inactive
122 ? "inactive"
123 : cause === GUEST_FAILURE.used
124 ? "used"
125 : cause === GUEST_FAILURE.busy
126 ? "busy"
127 : cause === GUEST_FAILURE.filesBusy
128 ? "files_busy"
129 : "rejected";
130​
131const SessionClaims = Schema.Struct({
132 kind: Schema.Literal("session"),
133 threadId: ThreadId,
134 shareId: GuestShareId,
135});
136type SessionClaims = typeof SessionClaims.Type;
137const decodeSessionClaims = Schema.decodeUnknownOption(Schema.fromJsonString(SessionClaims));
138​
139const inactive = new GuestShareAccessError({ reason: "inactive" });
140​
141export class GuestShareService extends Context.Service<
142 GuestShareService,
143 {
144 readonly create: (
145 input: GuestShareCreateInput,
146 ) => Effect.Effect<GuestShareCreateResult, GuestShareCreateError>;
147 /** Spends an invite and returns the session token for the guest's cookie. */
148 readonly redeem: (
149 request: GuestRedeemRequest,
150 ) => Effect.Effect<
151 { readonly token: string; readonly shareId: GuestShareId },
152 GuestShareAccessError
153 >;
154 /** Succeeds while the session can still open its share. */
155 readonly check: (session: string) => Effect.Effect<void, GuestShareAccessError>;
156 /** Stores the guest's files as the thread's attachments and records the message with them. */
157 readonly submit: (
158 session: string,
159 request: GuestSubmitRequest,
160 uploads: ReadonlyArray<GuestUpload>,
161 ) => Effect.Effect<void, GuestShareAccessError>;
162 readonly stream: (
163 session: string,
164 ) => Effect.Effect<Stream.Stream<GuestStreamEvent>, GuestShareAccessError>;
165 /** The file of an HTML render in the shared thread, and its title. */
166 readonly render: (
167 session: string,
168 itemId: string,
169 ) => Effect.Effect<{ readonly path: string; readonly title: string }, GuestShareAccessError>;
170 /** One item of the shared thread, as the owner's expanded row loads it, without file diffs. */
171 readonly item: (
172 session: string,
173 itemId: string,
174 ) => Effect.Effect<OrchestrationV2GetTurnItemResult, GuestShareAccessError>;
175 /** Older turns of the shared thread, as the owner's client pages them. */
176 readonly history: (
177 session: string,
178 cursor: string,
179 ) => Effect.Effect<OrchestrationV2ThreadHistoryPage, GuestShareAccessError>;
180 /** A command's output frames, as the owner's expanded row gets them, until the link ends. */
181 readonly commandOutput: (
182 session: string,
183 itemId: string,
184 ) => Effect.Effect<Stream.Stream<OrchestrationV2CommandOutputFrame>, GuestShareAccessError>;
185 /** A file in the shared thread or one of the share's messages, never a dismissed one's. */
186 readonly attachment: (
187 session: string,
188 attachmentId: string,
189 ) => Effect.Effect<
190 { readonly path: string; readonly attachment: ChatAttachment },
191 GuestShareAccessError
192 >;
193 /** An image on the host that an agent reply the guest sees shows, and its type. */
194 readonly media: (
195 session: string,
196 path: string,
197 ) => Effect.Effect<{ readonly path: string; readonly mimeType: string }, GuestShareAccessError>;
198 }
199>()("t3/guest/GuestShareService") {}
200​
201/** A reply a guest's stream sent, with its image sources once a media request parsed them. */
202interface SentReply {
203 readonly text: string;
204 sources?: ReadonlyArray<string>;
206​
207/** The thread record an event carries, for the share and the view. */
208const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => {
209 switch (event.type) {
210 case "thread.guest-share-updated":
211 case "thread.metadata-updated":
212 case "thread.model-selection-updated":
213 case "thread.provider-switched":
214 return event.payload;
215 default:
216 return null;
217 }
218};
219​
220/** A guest sees that a file changed, never the text of the change, whatever its status. */
221const withoutFileText = (item: OrchestrationV2TurnItem): OrchestrationV2TurnItem => {
222 if (item.type !== "file_change") return item;
223 const { diffStr: _diff, oldStr: _old, newStr: _new, ...shown } = item;
224 return shown;
225};
226const rowWithoutFileText = <Row extends { readonly item: OrchestrationV2TurnItem }>(
227 row: Row,
228): Row => ({ ...row, item: withoutFileText(row.item) });
229​
230const make = Effect.gen(function* () {
231 const orchestrator = yield* Orchestrator.OrchestratorV2;
232 const commandOutputs = yield* CommandOutputHub.CommandOutputHub;
233 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
234 const serverSettings = yield* ServerSettings.ServerSettingsService;
235 const managedEndpoint = yield* CloudManagedEndpointRuntime;
236 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
237 const fileSystem = yield* FileSystem.FileSystem;
238 const random = yield* SecureRandom.SecureRandom;
239 const analytics = yield* AnalyticsService.AnalyticsService;
240 const documents = yield* DocumentText.DocumentText;
241 const signer = yield* PayloadSigner.make(SIGNING_SECRET_NAME);
242 /** A truncated HMAC keeps invite links short. 128 bits is still far beyond guessing range. */
243 const inviteSignature = (shareId: string) =>
244 signer.sign(`guest-invite:${shareId}`).pipe(
245 Effect.orDie,
246 Effect.map((signature) =>
247 base64UrlEncode(Buffer.from(signature, "base64url").subarray(0, INVITE_SIGNATURE_BYTES)),
248 ),
249 );
250​
251 // Tokens are derived from the share id, so nothing secret is stored and replacing or closing
252 // the share in the thread projection revokes every token for it. An invite is
253 // `<shareId>.<signature>` and the thread is looked up by share id; a session token carries
254 // signed claims.
255 const signInvite = (shareId: GuestShareId) =>
256 inviteSignature(shareId).pipe(Effect.map((signature) => `${shareId}.${signature}`));
257 const signSession = (claims: SessionClaims) => {
258 const payload = base64UrlEncode(JSON.stringify(claims));
259 return signer.sign(payload).pipe(
260 Effect.orDie,
261 Effect.map((signature) => `${payload}.${signature}`),
262 );
263 };
264 const splitToken = (token: string) => {
265 const [payload, signature, extra] = token.split(".");
266 return payload && signature && extra === undefined ? { payload, signature } : null;
267 };
268 const verifyInvite = Effect.fn("GuestShareService.verifyInvite")(function* (token: string) {
269 const parts = splitToken(token);
270 if (parts === null) return Option.none<SessionClaims>();
271 const expected = yield* inviteSignature(parts.payload);
272 if (!timingSafeEqualBase64Url(parts.signature, expected)) {
273 return Option.none<SessionClaims>();
274 }
275 const shareId = GuestShareId.make(parts.payload);
276 const threadId = yield* orchestrator
277 .findGuestShareThreadId(shareId)
278 .pipe(Effect.mapError(() => inactive));
279 return threadId === null
280 ? Option.none<SessionClaims>()
281 : Option.some<SessionClaims>({ kind: "session", threadId, shareId });
282 });
283 // Untraced: runs on every guest request, like the Effect.map it replaced.
284 const verifySession = Effect.fnUntraced(function* (token: string) {
285 const parts = splitToken(token);
286 if (parts === null) return Option.none<SessionClaims>();
287 if (!(yield* signer.verify(parts.payload, parts.signature).pipe(Effect.orDie))) {
288 return Option.none<SessionClaims>();
289 }
290 return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));
291 });
292​
293 const connectHostname = managedEndpoint.inspectConnector.pipe(
294 Effect.map((facts) => facts?.hostname ?? null),
295 );
296 // A beta: while it is off, no link opens and every guest request is refused.
297 const sharingEnabled = serverSettings.getSettings.pipe(
298 Effect.map((settings) => settings.guestSharingEnabled),
299 Effect.orElseSucceed(() => false),
300 );
301​
302 const dispatchGuestCommand = (
303 command: Parameters<Orchestrator.OrchestratorV2["Service"]["dispatch"]>[0],
304 ) =>
305 orchestrator.dispatch(command).pipe(
306 Effect.mapError(
307 (error) =>
308 new GuestShareAccessError({
309 reason: guestFailureReason("cause" in error ? error.cause : undefined),
310 }),
311 ),
312 );
313​
314 const commandId = (label: string) =>
315 random.uuidV4().pipe(
316 Effect.map((uuid) => CommandId.make(`server:guest-share:${label}:${uuid}`)),
317 Effect.orDie,
318 );
319​
320 /** Checks a token against the live share: same id, not expired, and Connect still serving it. */
321 const authorize = Effect.fn("GuestShareService.authorize")(function* (
322 token: string,
323 kind: "invite" | "session",
324 ) {
325 const claims = yield* kind === "invite" ? verifyInvite(token) : verifySession(token);
326 if (Option.isNone(claims)) {
327 return yield* new GuestShareAccessError({ reason: "invalid" });
328 }
329 const { thread } = yield* orchestrator
330 .getThreadRecords(claims.value.threadId, [])
331 .pipe(Effect.mapError(() => inactive));
332 const share = thread.guestShare;
333 const now = yield* DateTime.now;
334 if (
335 !(yield* sharingEnabled) ||
336 !share ||
337 share.id !== claims.value.shareId ||
338 thread.archivedAt !== null ||
339 thread.deletedAt !== null ||
340 DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) ||
341 (kind === "session" && share.guestName === null) ||
342 (yield* connectHostname) !== share.host
343 ) {
344 return yield* inactive;
345 }
346 return { thread, share };
347 });
348​
349 const create = Effect.fn("GuestShareService.create")(function* (input: GuestShareCreateInput) {
350 if (!(yield* sharingEnabled)) {
351 return yield* new GuestShareCreateError({ reason: "disabled" });
352 }
353 const host = yield* connectHostname;
354 if (host === null) {
355 return yield* new GuestShareCreateError({ reason: "connect_unavailable" });
356 }
357 const shareId = GuestShareId.make(base64UrlEncode(yield* random.randomBytes(SHARE_ID_BYTES)));
358 const now = yield* DateTime.now;
359 const expiresAt = DateTime.formatIso(DateTime.add(now, { milliseconds: GUEST_SHARE_TTL_MS }));
360 yield* orchestrator
361 .dispatch({
362 type: "thread.guest-share.open",
363 commandId: yield* commandId("open"),
364 threadId: input.threadId,
365 shareId,
366 host,
367 expiresAt,
368 })
369 .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "thread_unavailable" })));
370 const { thread } = yield* orchestrator
371 .getThreadRecords(input.threadId, [])
372 .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "read_failed" })));
373 if (!thread.guestShare || thread.guestShare.id !== shareId) {
374 return yield* new GuestShareCreateError({ reason: "changed" });
375 }
376 const credential = yield* signInvite(shareId);
377 return { url: `https://${host}/guest#${credential}`, share: thread.guestShare };
378 });
379​
380 const redeem = Effect.fn("GuestShareService.redeem")(function* (request: GuestRedeemRequest) {
381 const { thread, share } = yield* authorize(request.credential, "invite");
382 yield* dispatchGuestCommand({
383 type: "thread.guest-share.redeem",
384 commandId: yield* commandId("redeem"),
385 threadId: thread.id,
386 shareId: share.id,
387 guestName: request.name,
388 });
389 // Guests have no client connection, so their events carry no surface.
390 yield* analytics.record("feature.used", { feature: "guest_share.join" });
391 const token = yield* signSession({ kind: "session", threadId: thread.id, shareId: share.id });
392 return { token, shareId: share.id };
393 });
394​
395 const check = Effect.fn("GuestShareService.check")(function* (session: string) {
396 yield* authorize(session, "session");
397 });
398​
399 const uploadFailed = new GuestShareAccessError({ reason: "rejected" });
400 const removeStored = (attachments: ReadonlyArray<ChatAttachment>) =>
401 Effect.forEach(
402 attachments,
403 (attachment) => {
404 const path = resolveAttachmentPath({ attachmentsDir, attachment });
405 return path === null
406 ? Effect.void
407 : fileSystem
408 .remove(path, { force: true })
409 .pipe(
410 Effect.andThen(fileSystem.remove(`${path}.txt`, { force: true })),
411 Effect.ignore,
412 );
413 },
414 { discard: true },
415 );
416​
417 /**
418 * Checks the files and stores them as the thread's attachments, so a message can wait longer
419 * than the day the pending-upload sweep allows. Send uses them as they are; dismissing the
420 * message or ending the share deletes them.
421 */
422 const storeUploads = Effect.fn("GuestShareService.storeUploads")(function* (
423 threadId: ThreadId,
424 uploads: ReadonlyArray<GuestUpload>,
425 ) {
426 const inspected = yield* Effect.forEach(uploads, (upload) =>
427 Effect.gen(function* () {
428 const info = yield* fileSystem.stat(upload.path);
429 const file = yield* fileSystem.open(upload.path, { flag: "r" });
430 const header = Option.getOrElse(
431 yield* file.readAlloc(GUEST_UPLOAD_HEADER_BYTES),
432 () => new Uint8Array(),
433 );
434 return { ...upload, sizeBytes: Number(info.size), header };
435 }).pipe(
436 Effect.scoped,
437 Effect.mapError(() => uploadFailed),
438 ),
439 );
440 const classified = classifyGuestUploads(inspected);
441 if (!classified.ok) return yield* new GuestShareAccessError({ reason: classified.reason });
442 const stored: Array<ChatAttachment> = [];
443 yield* Effect.forEach(
444 classified.attachments,
445 (draft, index) =>
446 Effect.gen(function* () {
447 const id = createAttachmentId(
448 threadId,
449 draft.type === "file" ? attachmentFileExtension(draft.name) : undefined,
450 );
451 if (id === null) return yield* uploadFailed;
452 const attachment: ChatAttachment = { ...draft, id: ChatAttachmentId.make(id) };
453 const path = resolveAttachmentPath({ attachmentsDir, attachment });
454 if (path === null) return yield* uploadFailed;
455 yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
456 yield* fileSystem.copyFile(uploads[index]!.path, path);
457 stored.push(attachment);
458 yield* documents.ensure(path);
459 }).pipe(Effect.mapError(() => uploadFailed)),
460 { discard: true },
461 ).pipe(Effect.onError(() => removeStored(stored)));
462 return stored;
463 });
464​
465 const submit = Effect.fn("GuestShareService.submit")(function* (
466 session: string,
467 request: GuestSubmitRequest,
468 uploads: ReadonlyArray<GuestUpload>,
469 ) {
470 const { thread, share } = yield* authorize(session, "session");
471 if (request.shareId !== share.id) {
472 return yield* new GuestShareAccessError({ reason: "stale_page" });
473 }
474 if (request.text === "" && uploads.length === 0) {
475 return yield* new GuestShareAccessError({ reason: "empty" });
476 }
477 const attachments = yield* storeUploads(thread.id, uploads);
478 yield* dispatchGuestCommand({
479 type: "thread.guest-message.submit",
480 commandId: yield* commandId("submit"),
481 threadId: thread.id,
482 shareId: share.id,
483 guestMessageId: GuestMessageId.make(yield* random.uuidV4()),
484 text: request.text,
485 ...(attachments.length === 0 ? {} : { attachments }),
486 }).pipe(Effect.onError(() => removeStored(attachments)));
487 yield* analytics.record("feature.used", {
488 feature: "guest_message.submit",
489 variant: attachments.length === 0 ? "text_only" : "with_files",
490 });
491 });
492​
493 const endsShareFor = (shareId: GuestShareId) => (event: OrchestrationV2DomainEvent) => {
494 if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
495 const updated = threadOf(event);
496 return updated !== null && updated.guestShare?.id !== shareId;
497 };
498​
499 /** Completes once the session no longer opens its share, so open reads end with it. */
500 const untilRevoked = (session: string) =>
501 authorize(session, "session").pipe(
502 Effect.repeat(Schedule.spaced(ACCESS_RECHECK_INTERVAL)),
503 Effect.ignore,
504 );
505​
506 // The image replies each share's guest stream has sent, in its opening snapshot or live, so an
507 // image loads while the guest's page can show its reply, inherited ones included. Keyed by
508 // share, so a new link on the thread starts empty. A share with an open stream keeps its
509 // record; past the limit, closed ones are dropped.
510 const sentImageReplies = new Map<
511 GuestShareId,
512 { openStreams: number; readonly replies: Map<string, SentReply> }
513 >();
514 const sentRecord = (shareId: GuestShareId) => {
515 let record = sentImageReplies.get(shareId);
516 if (record === undefined) {
517 record = { openStreams: 0, replies: new Map() };
518 sentImageReplies.set(shareId, record);
519 for (const [id, other] of sentImageReplies) {
520 if (sentImageReplies.size <= SHARED_THREAD_REPLIES_LIMIT) break;
521 if (other.openStreams === 0 && id !== shareId) sentImageReplies.delete(id);
522 }
523 }
524 return record;
525 };
526 const rememberSent = (shareId: GuestShareId, items: Iterable<OrchestrationV2TurnItem>) => {
527 for (const item of items) {
528 if (item.type !== "assistant_message") continue;
529 const key = `${item.threadId}\u0000${item.id}`;
530 // Only replies with image syntax can show an image. One edited to drop its images stops
531 // allowing them.
532 if (item.text.includes("![") || /<img/i.test(item.text)) {
533 sentRecord(shareId).replies.set(key, { text: item.text });
534 } else {
535 sentImageReplies.get(shareId)?.replies.delete(key);
536 }
537 }
538 };
539​
540 /**
541 * The thread as the owner's thread subscription sends it: a bounded snapshot, then the same
542 * wire events, batched the same way. Only the share's own state is added.
543 */
544 const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {
545 const { thread, share } = yield* authorize(session, "session");
546 const snapshot = yield* orchestrator
547 .getThreadSnapshotWindow(thread.id, {
548 rowLimit: SNAPSHOT_ROW_LIMIT,
549 userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,
550 })
551 .pipe(Effect.mapError(() => inactive));
552 // The share can end between authorize and this read; the live tail starts after it.
553 if (
554 snapshot.projection.thread.guestShare?.id !== share.id ||
555 snapshot.projection.thread.archivedAt !== null ||
556 snapshot.projection.thread.deletedAt !== null
557 ) {
558 return yield* inactive;
559 }
560 // Read once; a provider configured mid-share shows after the guest reconnects.
561 const providers = yield* providerRegistry.getProviders;
562 const viewOf = (current: OrchestrationV2AppThread) =>
563 guestShareView(current, guestThreadModel(current.modelSelection, providers));
564 const initialView = viewOf(snapshot.projection.thread);
565 if (initialView === null) return yield* inactive;
566​
567 const ended: GuestStreamEvent = { type: "ended" };
568 const endsShare = endsShareFor(share.id);
569 const live = orchestrator
570 .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })
571 .pipe(
572 Stream.map(threadStreamEventItem),
573 // Ending the source here flushes what the coalescer holds, so `ended` is not held back.
574 Stream.takeUntil((item) => endsShare(item.event)),
575 coalesceThreadLiveStream,
576 Stream.map((item): ReadonlyArray<GuestStreamEvent> => {
577 if (item.kind !== "event") return [];
578 if (endsShare(item.event)) return [ended];
579 if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]);
580 const shown =
581 item.event.type === "turn-item.updated"
582 ? { ...item, event: { ...item.event, payload: withoutFileText(item.event.payload) } }
583 : item;
584 const updated = threadOf(item.event);
585 const view = updated === null ? null : viewOf(updated);
586 return view === null
587 ? [{ type: "thread", item: shown }]
588 : [
589 { type: "thread", item: shown },
590 { type: "view", view },
591 ];
592 }),
593 Stream.flattenIterable,
594 // A failed read closes the response without `ended`: the browser reconnects, and
595 // `authorize` decides whether the link still works.
596 Stream.catchCause(() => Stream.empty),
597 );
598 const untilExpiry = Effect.sleep(
599 Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
600 );
601 const openingSnapshot = buildBoundedThreadStreamSnapshot({
602 snapshotSequence: snapshot.snapshotSequence,
603 projection: {
604 ...snapshot.projection,
605 turnItems: snapshot.projection.turnItems.map(withoutFileText),
606 visibleTurnItems: snapshot.projection.visibleTurnItems.map(rowWithoutFileText),
607 },
608 });
609 const opening: ReadonlyArray<GuestStreamEvent> = [
610 { type: "view", view: initialView },
611 { type: "thread", item: openingSnapshot },
612 ];
613 const events = Stream.fromIterable(opening).pipe(
614 Stream.concat(
615 Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {
616 haltStrategy: "either",
617 }),
618 ),
619 Stream.takeUntil((event) => event.type === "ended"),
620 // Unlinking T3 Connect closes it quietly, so a tunnel that comes back on the same host
621 // keeps the guest in. Turning the beta off closes it the same way. Closing and expiry end
622 // it above, with `ended`.
623 Stream.interruptWhen(
624 Effect.all([connectHostname, sharingEnabled]).pipe(
625 Effect.repeat({
626 schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),
627 until: ([host, enabled]) => host !== share.host || !enabled,
628 }),
629 ),
630 ),
631 );
632 // The record is opened and counted when the stream runs, paired with its release, so a
633 // response whose body never runs (HEAD) touches nothing.
634 return Stream.unwrap(
635 Effect.acquireRelease(
636 Effect.sync(() => {
637 const record = sentRecord(share.id);
638 record.openStreams += 1;
639 rememberSent(
640 share.id,
641 openingSnapshot.projection.visibleTurnItems.map((row) => row.item),
642 );
643 return record;
644 }),
645 (record) =>
646 Effect.sync(() => {
647 record.openStreams -= 1;
648 }),
649 ).pipe(Effect.as(events)),
650 );
651 });
652​
653 const unavailable = new GuestShareAccessError({ reason: "unavailable" });
654​
655 /** An item of the shared thread, read after the session check. */
656 const threadItem = Effect.fn("GuestShareService.threadItem")(function* (
657 session: string,
658 itemId: string,
659 ) {
660 const { thread, share } = yield* authorize(session, "session");
661 const id = TurnItemId.make(itemId);
662 const item =
663 (yield* orchestrator
664 .getTurnItem({ threadId: thread.id, itemId: id })
665 .pipe(Effect.mapError(() => unavailable))) ??
666 // A fork shows its source's earlier items, which stay in the source thread.
667 (thread.forkedFrom === null
668 ? null
669 : yield* orchestrator.getTimelinePage(thread.id, { itemId: id, limit: 1 }).pipe(
670 Effect.map((page) => page.items[0]?.item ?? null),
671 Effect.mapError(() => unavailable),
672 ));
673 return item === null ? yield* unavailable : { thread, share, item };
674 });
675​
676 const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {
677 const { item } = yield* threadItem(session, itemId);
678 if (item.type !== "dynamic_tool") return yield* unavailable;
679 const reference = htmlRenderFromToolItem(item);
680 const [attachmentId] = threadHtmlRenderAttachmentIds(item.threadId, [item]);
681 const path =
682 attachmentId === undefined
683 ? null
684 : resolveAttachmentPathById({ attachmentsDir, attachmentId });
685 if (reference === undefined || path === null) return yield* unavailable;
686 return { path, title: reference.title };
687 });
688​
689 const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) {
690 const { item } = yield* threadItem(session, itemId);
691 return { item: projectTurnItemForDetail(withoutFileText(item)) };
692 });
693​
694 const history = Effect.fn("GuestShareService.history")(function* (
695 session: string,
696 cursor: string,
697 ) {
698 const { thread, share } = yield* authorize(session, "session");
699 const page = yield* orchestrator
700 .getThreadHistoryPage(thread.id, cursor)
701 .pipe(Effect.mapError(() => unavailable));
702 rememberSent(
703 share.id,
704 page.items.map((row) => row.item),
705 );
706 return { ...page, items: page.items.map(rowWithoutFileText) };
707 });
708​
709 const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
710 session: string,
711 itemId: string,
712 ) {
713 const { thread, share, item } = yield* threadItem(session, itemId);
714 if (item.type !== "command_execution") return yield* unavailable;
715 const afterSequence = yield* orchestrator
716 .getThreadEventSequence(thread.id)
717 .pipe(Effect.mapError(() => unavailable));
718 // A share that ends before the cursor is read fails this check; one that ends after it ends
719 // `shareEnded`.
720 yield* authorize(session, "session");
721 const endsShare = endsShareFor(share.id);
722 const shareEnded = orchestrator
723 .streamStoredEventsFrom({ threadId: thread.id, afterSequence })
724 .pipe(
725 Stream.filter((stored) => endsShare(stored.event)),
726 Stream.runHead,
727 Effect.ignore,
728 );
729 const untilExpiry = Effect.sleep(
730 Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
731 );
732 return commandOutputs.subscribe({ threadId: item.threadId, itemId: item.id }).pipe(
733 // A lost hub stream ends the output; the row reloads it when reopened.
734 Stream.catchCause(() => Stream.empty),
735 Stream.interruptWhen(Effect.raceAll([shareEnded, untilExpiry, untilRevoked(session)])),
736 );
737 });
738​
739 const attachment = Effect.fn("GuestShareService.attachment")(function* (
740 session: string,
741 attachmentId: string,
742 ) {
743 const { thread, share } = yield* authorize(session, "session");
744 // A dismissed message's files are deleted with it.
745 const fromShare = share.messages
746 .flatMap((message) => (message.status === "dismissed" ? [] : (message.attachments ?? [])))
747 .find((candidate) => candidate.id === attachmentId);
748 const found =
749 fromShare ??
750 (yield* orchestrator.getThreadRecords(thread.id, ["messages"]).pipe(
751 Effect.map(({ messages }) =>
752 messages
753 .flatMap((message) => message.attachments ?? [])
754 .find((candidate) => candidate.id === attachmentId),
755 ),
756 Effect.mapError(() => unavailable),
757 )) ??
758 // A fork shows its source's earlier messages, which stay in the source thread.
759 (thread.forkedFrom === null
760 ? undefined
761 : yield* orchestrator.getTimelinePage(thread.id, { attachmentId, limit: 1 }).pipe(
762 Effect.map(({ items }) =>
763 items
764 .flatMap(({ item }) => (item.type === "user_message" ? item.attachments : []))
765 .find((candidate) => candidate.id === attachmentId),
766 ),
767 Effect.mapError(() => unavailable),
768 ));
769 const path =
770 found === undefined ? null : resolveAttachmentPath({ attachmentsDir, attachment: found });
771 if (found === undefined || path === null) return yield* unavailable;
772 const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));
773 return exists ? { path, attachment: found } : yield* unavailable;
774 });
775​
776 const media = Effect.fn("GuestShareService.media")(function* (session: string, path: string) {
777 const { share } = yield* authorize(session, "session");
778 const mimeType = guestHostImageType(path);
779 if (mimeType === null) return yield* unavailable;
780 const sent = sentImageReplies.get(share.id)?.replies.values() ?? [];
781 // Each sent reply is parsed once, on the first request that needs it.
782 if (
783 !repliesShowImage(
784 path,
785 [...sent],
786 (reply) => (reply.sources ??= chatMarkdownImageSources(reply.text)),
787 )
788 ) {
789 return yield* unavailable;
790 }
791 // The bytes must be the image the name says, as for a guest's own upload.
792 const header = yield* fileSystem.open(path, { flag: "r" }).pipe(
793 Effect.flatMap((file) => file.readAlloc(GUEST_UPLOAD_HEADER_BYTES)),
794 Effect.scoped,
795 Effect.mapError(() => unavailable),
796 );
797 if (Option.isNone(header) || !matchesImageSignature(mimeType, header.value)) {
798 return yield* unavailable;
799 }
800 return { path, mimeType };
801 });
802​
803 return GuestShareService.of({
804 create,
805 redeem,
806 check,
807 submit,
808 stream,
809 render,
810 item,
811 history,
812 commandOutput,
813 attachment,
814 media,
815 });
816});
817​
818export const layer = Layer.effect(GuestShareService, make);