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