Open History to see the last commit
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 }
118}
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>;
205}
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 /** Completes once the session no longer opens its share, so open reads end with it. */
494 const untilRevoked = (session: string) =>
495 authorize(session, "session").pipe(
496 Effect.repeat(Schedule.spaced(ACCESS_RECHECK_INTERVAL)),
497 Effect.ignore,
498 );
499
500 // The image replies each share's guest stream has sent, in its opening snapshot or live, so an
501 // image loads while the guest's page can show its reply, inherited ones included. Keyed by
502 // share, so a new link on the thread starts empty. A share with an open stream keeps its
503 // record; past the limit, closed ones are dropped.
504 const sentImageReplies = new Map<
505 GuestShareId,
506 { openStreams: number; readonly replies: Map<string, SentReply> }
507 >();
508 const sentRecord = (shareId: GuestShareId) => {
509 let record = sentImageReplies.get(shareId);
510 if (record === undefined) {
511 record = { openStreams: 0, replies: new Map() };
512 sentImageReplies.set(shareId, record);
513 for (const [id, other] of sentImageReplies) {
514 if (sentImageReplies.size <= SHARED_THREAD_REPLIES_LIMIT) break;
515 if (other.openStreams === 0 && id !== shareId) sentImageReplies.delete(id);
516 }
517 }
518 return record;
519 };
520 const rememberSent = (shareId: GuestShareId, items: Iterable<OrchestrationV2TurnItem>) => {
521 for (const item of items) {
522 if (item.type !== "assistant_message") continue;
523 const key = `${item.threadId}\u0000${item.id}`;
524 // Only replies with image syntax can show an image. One edited to drop its images stops
525 // allowing them.
526 if (item.text.includes("![") || /<img/i.test(item.text)) {
527 sentRecord(shareId).replies.set(key, { text: item.text });
528 } else {
529 sentImageReplies.get(shareId)?.replies.delete(key);
530 }
531 }
532 };
533
534 /**
535 * The thread as the owner's thread subscription sends it: a bounded snapshot, then the same
536 * wire events, batched the same way. Only the share's own state is added.
537 */
538 const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {
539 const { thread, share } = yield* authorize(session, "session");
540 const snapshot = yield* orchestrator
541 .getThreadSnapshotWindow(thread.id, {
542 rowLimit: SNAPSHOT_ROW_LIMIT,
543 userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,
544 })
545 .pipe(Effect.mapError(() => inactive));
546 // The share can end between authorize and this read; the live tail starts after it.
547 if (
548 snapshot.projection.thread.guestShare?.id !== share.id ||
549 snapshot.projection.thread.archivedAt !== null ||
550 snapshot.projection.thread.deletedAt !== null
551 ) {
552 return yield* inactive;
553 }
554 // Read once; a provider configured mid-share shows after the guest reconnects.
555 const providers = yield* providerRegistry.getProviders;
556 const viewOf = (current: OrchestrationV2AppThread) =>
557 guestShareView(current, guestThreadModel(current.modelSelection, providers));
558 const initialView = viewOf(snapshot.projection.thread);
559 if (initialView === null) return yield* inactive;
560
561 const ended: GuestStreamEvent = { type: "ended" };
562 const endsShare = (event: OrchestrationV2DomainEvent) => {
563 if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
564 const updated = threadOf(event);
565 return updated !== null && updated.guestShare?.id !== share.id;
566 };
567 const live = orchestrator
568 .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })
569 .pipe(
570 Stream.map(threadStreamEventItem),
571 // Ending the source here flushes what the coalescer holds, so `ended` is not held back.
572 Stream.takeUntil((item) => endsShare(item.event)),
573 coalesceThreadLiveStream,
574 Stream.map((item): ReadonlyArray<GuestStreamEvent> => {
575 if (item.kind !== "event") return [];
576 if (endsShare(item.event)) return [ended];
577 if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]);
578 const shown =
579 item.event.type === "turn-item.updated"
580 ? { ...item, event: { ...item.event, payload: withoutFileText(item.event.payload) } }
581 : item;
582 const updated = threadOf(item.event);
583 const view = updated === null ? null : viewOf(updated);
584 return view === null
585 ? [{ type: "thread", item: shown }]
586 : [
587 { type: "thread", item: shown },
588 { type: "view", view },
589 ];
590 }),
591 Stream.flattenIterable,
592 // A failed read closes the response without `ended`: the browser reconnects, and
593 // `authorize` decides whether the link still works.
594 Stream.catchCause(() => Stream.empty),
595 );
596 const untilExpiry = Effect.sleep(
597 Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
598 );
599 const openingSnapshot = buildBoundedThreadStreamSnapshot({
600 snapshotSequence: snapshot.snapshotSequence,
601 projection: {
602 ...snapshot.projection,
603 turnItems: snapshot.projection.turnItems.map(withoutFileText),
604 visibleTurnItems: snapshot.projection.visibleTurnItems.map(rowWithoutFileText),
605 },
606 });
607 const opening: ReadonlyArray<GuestStreamEvent> = [
608 { type: "view", view: initialView },
609 { type: "thread", item: openingSnapshot },
610 ];
611 const events = Stream.fromIterable(opening).pipe(
612 Stream.concat(
613 Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {
614 haltStrategy: "either",
615 }),
616 ),
617 Stream.takeUntil((event) => event.type === "ended"),
618 // Unlinking T3 Connect closes it quietly, so a tunnel that comes back on the same host
619 // keeps the guest in. Turning the beta off closes it the same way. Closing and expiry end
620 // it above, with `ended`.
621 Stream.interruptWhen(
622 Effect.all([connectHostname, sharingEnabled]).pipe(
623 Effect.repeat({
624 schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),
625 until: ([host, enabled]) => host !== share.host || !enabled,
626 }),
627 ),
628 ),
629 );
630 // The record is opened and counted when the stream runs, paired with its release, so a
631 // response whose body never runs (HEAD) touches nothing.
632 return Stream.unwrap(
633 Effect.acquireRelease(
634 Effect.sync(() => {
635 const record = sentRecord(share.id);
636 record.openStreams += 1;
637 rememberSent(
638 share.id,
639 openingSnapshot.projection.visibleTurnItems.map((row) => row.item),
640 );
641 return record;
642 }),
643 (record) =>
644 Effect.sync(() => {
645 record.openStreams -= 1;
646 }),
647 ).pipe(Effect.as(events)),
648 );
649 });
650
651 const unavailable = new GuestShareAccessError({ reason: "unavailable" });
652
653 /** An item of the shared thread, read after the session check. */
654 const threadItem = Effect.fn("GuestShareService.threadItem")(function* (
655 session: string,
656 itemId: string,
657 ) {
658 const { thread } = yield* authorize(session, "session");
659 const id = TurnItemId.make(itemId);
660 const item =
661 (yield* orchestrator
662 .getTurnItem({ threadId: thread.id, itemId: id })
663 .pipe(Effect.mapError(() => unavailable))) ??
664 // A fork shows its source's earlier items, which stay in the source thread.
665 (thread.forkedFrom === null
666 ? null
667 : yield* orchestrator.getTimelinePage(thread.id, { itemId: id, limit: 1 }).pipe(
668 Effect.map((page) => page.items[0]?.item ?? null),
669 Effect.mapError(() => unavailable),
670 ));
671 return item === null ? yield* unavailable : { thread, item };
672 });
673
674 const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {
675 const { item } = yield* threadItem(session, itemId);
676 if (item.type !== "dynamic_tool") return yield* unavailable;
677 const reference = htmlRenderFromToolItem(item);
678 const [attachmentId] = threadHtmlRenderAttachmentIds(item.threadId, [item]);
679 const path =
680 attachmentId === undefined
681 ? null
682 : resolveAttachmentPathById({ attachmentsDir, attachmentId });
683 if (reference === undefined || path === null) return yield* unavailable;
684 return { path, title: reference.title };
685 });
686
687 const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) {
688 const { item } = yield* threadItem(session, itemId);
689 return { item: projectTurnItemForDetail(withoutFileText(item)) };
690 });
691
692 const history = Effect.fn("GuestShareService.history")(function* (
693 session: string,
694 cursor: string,
695 ) {
696 const { thread, share } = yield* authorize(session, "session");
697 const page = yield* orchestrator
698 .getThreadHistoryPage(thread.id, cursor)
699 .pipe(Effect.mapError(() => unavailable));
700 rememberSent(
701 share.id,
702 page.items.map((row) => row.item),
703 );
704 return { ...page, items: page.items.map(rowWithoutFileText) };
705 });
706
707 const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
708 session: string,
709 itemId: string,
710 ) {
711 const { item } = yield* threadItem(session, itemId);
712 if (item.type !== "command_execution") return yield* unavailable;
713 return commandOutputs.subscribe({ threadId: item.threadId, itemId: item.id }).pipe(
714 // A lost hub stream ends the output; the row reloads it when reopened.
715 Stream.catchCause(() => Stream.empty),
716 Stream.interruptWhen(untilRevoked(session)),
717 );
718 });
719
720 const attachment = Effect.fn("GuestShareService.attachment")(function* (
721 session: string,
722 attachmentId: string,
723 ) {
724 const { thread, share } = yield* authorize(session, "session");
725 // A dismissed message's files are deleted with it.
726 const fromShare = share.messages
727 .flatMap((message) => (message.status === "dismissed" ? [] : (message.attachments ?? [])))
728 .find((candidate) => candidate.id === attachmentId);
729 const found =
730 fromShare ??
731 (yield* orchestrator.getThreadRecords(thread.id, ["messages"]).pipe(
732 Effect.map(({ messages }) =>
733 messages
734 .flatMap((message) => message.attachments ?? [])
735 .find((candidate) => candidate.id === attachmentId),
736 ),
737 Effect.mapError(() => unavailable),
738 )) ??
739 // A fork shows its source's earlier messages, which stay in the source thread.
740 (thread.forkedFrom === null
741 ? undefined
742 : yield* orchestrator.getTimelinePage(thread.id, { attachmentId, limit: 1 }).pipe(
743 Effect.map(({ items }) =>
744 items
745 .flatMap(({ item }) => (item.type === "user_message" ? item.attachments : []))
746 .find((candidate) => candidate.id === attachmentId),
747 ),
748 Effect.mapError(() => unavailable),
749 ));
750 const path =
751 found === undefined ? null : resolveAttachmentPath({ attachmentsDir, attachment: found });
752 if (found === undefined || path === null) return yield* unavailable;
753 const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));
754 return exists ? { path, attachment: found } : yield* unavailable;
755 });
756
757 const media = Effect.fn("GuestShareService.media")(function* (session: string, path: string) {
758 const { share } = yield* authorize(session, "session");
759 const mimeType = guestHostImageType(path);
760 if (mimeType === null) return yield* unavailable;
761 const sent = sentImageReplies.get(share.id)?.replies.values() ?? [];
762 // Each sent reply is parsed once, on the first request that needs it.
763 if (
764 !repliesShowImage(
765 path,
766 [...sent],
767 (reply) => (reply.sources ??= chatMarkdownImageSources(reply.text)),
768 )
769 ) {
770 return yield* unavailable;
771 }
772 // The bytes must be the image the name says, as for a guest's own upload.
773 const header = yield* fileSystem.open(path, { flag: "r" }).pipe(
774 Effect.flatMap((file) => file.readAlloc(GUEST_UPLOAD_HEADER_BYTES)),
775 Effect.scoped,
776 Effect.mapError(() => unavailable),
777 );
778 if (Option.isNone(header) || !matchesImageSignature(mimeType, header.value)) {
779 return yield* unavailable;
780 }
781 return { path, mimeType };
782 });
783
784 return GuestShareService.of({
785 create,
786 redeem,
787 check,
788 submit,
789 stream,
790 render,
791 item,
792 history,
793 commandOutput,
794 attachment,
795 media,
796 });
797});
798
799export const layer = Layer.effect(GuestShareService, make);