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