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

GuestShareService.ts

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