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

GuestShareService.ts

768 lines29.8 KB

1import {
2 type ChatAttachment,
3 ChatAttachmentId,
4 CommandId,
5 GUEST_SHARE_TTL_MS,
6 GuestMessageId,
7 GuestShareCreateError,
8 type GuestShareCreateInput,
9 type GuestShareCreateResult,
10 GuestShareId,
11 type GuestRedeemRequest,
12 type GuestStreamEvent,
13 type GuestSubmitRequest,
14 type OrchestrationV2AppThread,
15 type OrchestrationV2CommandOutputFrame,
16 type OrchestrationV2DomainEvent,
17 type OrchestrationV2GetTurnItemResult,
18 type OrchestrationV2ThreadHistoryPage,
19 type OrchestrationV2TurnItem,
20 ThreadId,
21 TurnItemId,
22} from "@t3tools/contracts";
23import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline";
24import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
25import * as Context from "effect/Context";
26import * as SecureRandom from "effect/crypto/SecureRandom";
27import * as DateTime from "effect/DateTime";
28import * as Duration from "effect/Duration";
29import * as Effect from "effect/Effect";
30import * as FileSystem from "effect/FileSystem";
31import * as Layer from "effect/Layer";
32import * as Option from "effect/Option";
33import * as Schedule from "effect/Schedule";
34import * as Schema from "effect/Schema";
35import * as Stream from "effect/Stream";
36​
37import {
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 }
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>;
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 random = yield* SecureRandom.SecureRandom;
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 random.uuidV4().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(base64UrlEncode(yield* random.randomBytes(SHARE_ID_BYTES)));
354 const now = yield* DateTime.now;
355 const expiresAt = DateTime.formatIso(DateTime.add(now, { milliseconds: GUEST_SHARE_TTL_MS }));
356 yield* orchestrator
357 .dispatch({
358 type: "thread.guest-share.open",
359 commandId: yield* commandId("open"),
360 threadId: input.threadId,
361 shareId,
362 host,
363 expiresAt,
364 })
365 .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "thread_unavailable" })));
366 const { thread } = yield* orchestrator
367 .getThreadRecords(input.threadId, [])
368 .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "read_failed" })));
369 if (!thread.guestShare || thread.guestShare.id !== shareId) {
370 return yield* new GuestShareCreateError({ reason: "changed" });
371 }
372 const credential = yield* signInvite(shareId);
373 return { url: `https://${host}/guest#${credential}`, share: thread.guestShare };
374 });
375​
376 const redeem = Effect.fn("GuestShareService.redeem")(function* (request: GuestRedeemRequest) {
377 const { thread, share } = yield* authorize(request.credential, "invite");
378 yield* dispatchGuestCommand({
379 type: "thread.guest-share.redeem",
380 commandId: yield* commandId("redeem"),
381 threadId: thread.id,
382 shareId: share.id,
383 guestName: request.name,
384 });
385 // Guests have no client connection, so their events carry no surface.
386 yield* analytics.record("feature.used", { feature: "guest_share.join" });
387 const token = yield* signSession({ kind: "session", threadId: thread.id, shareId: share.id });
388 return { token, shareId: share.id };
389 });
390​
391 const check = Effect.fn("GuestShareService.check")(function* (session: string) {
392 yield* authorize(session, "session");
393 });
394​
395 const uploadFailed = new GuestShareAccessError({ reason: "rejected" });
396 const removeStored = (attachments: ReadonlyArray<ChatAttachment>) =>
397 Effect.forEach(
398 attachments,
399 (attachment) => {
400 const path = resolveAttachmentPath({ attachmentsDir, attachment });
401 return path === null
402 ? Effect.void
403 : fileSystem.remove(path, { force: true }).pipe(Effect.ignore);
404 },
405 { discard: true },
406 );
407​
408 /**
409 * Checks the files and stores them as the thread's attachments, so a message can wait longer
410 * than the day the pending-upload sweep allows. Send uses them as they are; dismissing the
411 * message or ending the share deletes them.
412 */
413 const storeUploads = Effect.fn("GuestShareService.storeUploads")(function* (
414 threadId: ThreadId,
415 uploads: ReadonlyArray<GuestUpload>,
416 ) {
417 const inspected = yield* Effect.forEach(uploads, (upload) =>
418 Effect.gen(function* () {
419 const info = yield* fileSystem.stat(upload.path);
420 const file = yield* fileSystem.open(upload.path, { flag: "r" });
421 const header = Option.getOrElse(
422 yield* file.readAlloc(GUEST_UPLOAD_HEADER_BYTES),
423 () => new Uint8Array(),
424 );
425 return { ...upload, sizeBytes: Number(info.size), header };
426 }).pipe(
427 Effect.scoped,
428 Effect.mapError(() => uploadFailed),
429 ),
430 );
431 const classified = classifyGuestUploads(inspected);
432 if (!classified.ok) return yield* new GuestShareAccessError({ reason: classified.reason });
433 const stored: Array<ChatAttachment> = [];
434 yield* Effect.forEach(
435 classified.attachments,
436 (draft, index) =>
437 Effect.gen(function* () {
438 const id = createAttachmentId(
439 threadId,
440 draft.type === "file" ? attachmentFileExtension(draft.name) : undefined,
441 );
442 if (id === null) return yield* uploadFailed;
443 const attachment: ChatAttachment = { ...draft, id: ChatAttachmentId.make(id) };
444 const path = resolveAttachmentPath({ attachmentsDir, attachment });
445 if (path === null) return yield* uploadFailed;
446 yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
447 yield* fileSystem.copyFile(uploads[index]!.path, path);
448 stored.push(attachment);
449 }).pipe(Effect.mapError(() => uploadFailed)),
450 { discard: true },
451 ).pipe(Effect.onError(() => removeStored(stored)));
452 return stored;
453 });
454​
455 const submit = Effect.fn("GuestShareService.submit")(function* (
456 session: string,
457 request: GuestSubmitRequest,
458 uploads: ReadonlyArray<GuestUpload>,
459 ) {
460 const { thread, share } = yield* authorize(session, "session");
461 if (request.shareId !== share.id) {
462 return yield* new GuestShareAccessError({ reason: "stale_page" });
463 }
464 if (request.text === "" && uploads.length === 0) {
465 return yield* new GuestShareAccessError({ reason: "empty" });
466 }
467 const attachments = yield* storeUploads(thread.id, uploads);
468 yield* dispatchGuestCommand({
469 type: "thread.guest-message.submit",
470 commandId: yield* commandId("submit"),
471 threadId: thread.id,
472 shareId: share.id,
473 guestMessageId: GuestMessageId.make(yield* random.uuidV4()),
474 text: request.text,
475 ...(attachments.length === 0 ? {} : { attachments }),
476 }).pipe(Effect.onError(() => removeStored(attachments)));
477 yield* analytics.record("feature.used", {
478 feature: "guest_message.submit",
479 variant: attachments.length === 0 ? "text_only" : "with_files",
480 });
481 });
482​
483 /** Completes once the session no longer opens its share, so open reads end with it. */
484 const untilRevoked = (session: string) =>
485 authorize(session, "session").pipe(
486 Effect.repeat(Schedule.spaced(ACCESS_RECHECK_INTERVAL)),
487 Effect.ignore,
488 );
489​
490 // The image replies each share's guest stream has sent, in its opening snapshot or live, so an
491 // image loads while the guest's page can show its reply, inherited ones included. Keyed by
492 // share, so a new link on the thread starts empty. A share with an open stream keeps its
493 // record; past the limit, closed ones are dropped.
494 const sentImageReplies = new Map<
495 GuestShareId,
496 { openStreams: number; readonly replies: Map<string, SentReply> }
497 >();
498 const sentRecord = (shareId: GuestShareId) => {
499 let record = sentImageReplies.get(shareId);
500 if (record === undefined) {
501 record = { openStreams: 0, replies: new Map() };
502 sentImageReplies.set(shareId, record);
503 for (const [id, other] of sentImageReplies) {
504 if (sentImageReplies.size <= SHARED_THREAD_REPLIES_LIMIT) break;
505 if (other.openStreams === 0 && id !== shareId) sentImageReplies.delete(id);
506 }
507 }
508 return record;
509 };
510 const rememberSent = (shareId: GuestShareId, items: Iterable<OrchestrationV2TurnItem>) => {
511 for (const item of items) {
512 if (item.type !== "assistant_message") continue;
513 const key = `${item.threadId}\u0000${item.id}`;
514 // Only replies with image syntax can show an image. One edited to drop its images stops
515 // allowing them.
516 if (item.text.includes("![") || /<img/i.test(item.text)) {
517 sentRecord(shareId).replies.set(key, { text: item.text });
518 } else {
519 sentImageReplies.get(shareId)?.replies.delete(key);
520 }
521 }
522 };
523​
524 /**
525 * The thread as the owner's thread subscription sends it: a bounded snapshot, then the same
526 * wire events, batched the same way. Only the share's own state is added.
527 */
528 const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {
529 const { thread, share } = yield* authorize(session, "session");
530 const snapshot = yield* orchestrator
531 .getThreadSnapshotWindow(thread.id, {
532 rowLimit: SNAPSHOT_ROW_LIMIT,
533 userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,
534 })
535 .pipe(Effect.mapError(() => inactive));
536 // The share can end between authorize and this read; the live tail starts after it.
537 if (
538 snapshot.projection.thread.guestShare?.id !== share.id ||
539 snapshot.projection.thread.archivedAt !== null ||
540 snapshot.projection.thread.deletedAt !== null
541 ) {
542 return yield* inactive;
543 }
544 // Read once; a provider configured mid-share shows after the guest reconnects.
545 const providers = yield* providerRegistry.getProviders;
546 const viewOf = (current: OrchestrationV2AppThread) =>
547 guestShareView(current, guestThreadModel(current.modelSelection, providers));
548 const initialView = viewOf(snapshot.projection.thread);
549 if (initialView === null) return yield* inactive;
550​
551 const ended: GuestStreamEvent = { type: "ended" };
552 const endsShare = (event: OrchestrationV2DomainEvent) => {
553 if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
554 const updated = threadOf(event);
555 return updated !== null && updated.guestShare?.id !== share.id;
556 };
557 const live = orchestrator
558 .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })
559 .pipe(
560 Stream.map((stored) => ({
561 kind: "event" as const,
562 sequence: stored.sequence,
563 event: projectDomainEventForWire(stored.event),
564 })),
565 // Ending the source here flushes what the coalescer holds, so `ended` is not held back.
566 Stream.takeUntil((item) => endsShare(item.event)),
567 coalesceThreadLiveStream,
568 Stream.map((item): ReadonlyArray<GuestStreamEvent> => {
569 if (item.kind !== "event") return [];
570 if (endsShare(item.event)) return [ended];
571 if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]);
572 const updated = threadOf(item.event);
573 const view = updated === null ? null : viewOf(updated);
574 return view === null
575 ? [{ type: "thread", item }]
576 : [
577 { type: "thread", item },
578 { type: "view", view },
579 ];
580 }),
581 Stream.flattenIterable,
582 // A failed read closes the response without `ended`: the browser reconnects, and
583 // `authorize` decides whether the link still works.
584 Stream.catchCause(() => Stream.empty),
585 );
586 const untilExpiry = Effect.sleep(
587 Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
588 );
589 const openingSnapshot = buildBoundedThreadStreamSnapshot({
590 snapshotSequence: snapshot.snapshotSequence,
591 projection: snapshot.projection,
592 });
593 const opening: ReadonlyArray<GuestStreamEvent> = [
594 { type: "view", view: initialView },
595 { type: "thread", item: openingSnapshot },
596 ];
597 const events = Stream.fromIterable(opening).pipe(
598 Stream.concat(
599 Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {
600 haltStrategy: "either",
601 }),
602 ),
603 Stream.takeUntil((event) => event.type === "ended"),
604 // Unlinking T3 Connect closes it quietly, so a tunnel that comes back on the same host
605 // keeps the guest in. Turning the beta off closes it the same way. Closing and expiry end
606 // it above, with `ended`.
607 Stream.interruptWhen(
608 Effect.all([connectHostname, sharingEnabled]).pipe(
609 Effect.repeat({
610 schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),
611 until: ([host, enabled]) => host !== share.host || !enabled,
612 }),
613 ),
614 ),
615 );
616 // The record is opened and counted when the stream runs, paired with its release, so a
617 // response whose body never runs (HEAD) touches nothing.
618 return Stream.unwrap(
619 Effect.acquireRelease(
620 Effect.sync(() => {
621 const record = sentRecord(share.id);
622 record.openStreams += 1;
623 rememberSent(
624 share.id,
625 openingSnapshot.projection.visibleTurnItems.map((row) => row.item),
626 );
627 return record;
628 }),
629 (record) =>
630 Effect.sync(() => {
631 record.openStreams -= 1;
632 }),
633 ).pipe(Effect.as(events)),
634 );
635 });
636​
637 const unavailable = new GuestShareAccessError({ reason: "unavailable" });
638​
639 /** An item of the shared thread, read after the session check. */
640 const threadItem = Effect.fn("GuestShareService.threadItem")(function* (
641 session: string,
642 itemId: string,
643 ) {
644 const { thread } = yield* authorize(session, "session");
645 const item = yield* orchestrator
646 .getTurnItem({ threadId: thread.id, itemId: TurnItemId.make(itemId) })
647 .pipe(Effect.mapError(() => unavailable));
648 return item === null ? yield* unavailable : { thread, item };
649 });
650​
651 const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {
652 const { thread, item } = yield* threadItem(session, itemId);
653 if (item.type !== "dynamic_tool") return yield* unavailable;
654 const reference = htmlRenderFromToolItem(item);
655 const [attachmentId] = threadHtmlRenderAttachmentIds(thread.id, [item]);
656 const path =
657 attachmentId === undefined
658 ? null
659 : resolveAttachmentPathById({ attachmentsDir, attachmentId });
660 if (reference === undefined || path === null) return yield* unavailable;
661 return { path, title: reference.title };
662 });
663​
664 const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) {
665 const { item } = yield* threadItem(session, itemId);
666 return {
667 item:
668 item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item),
669 };
670 });
671​
672 const history = Effect.fn("GuestShareService.history")(function* (
673 session: string,
674 cursor: string,
675 ) {
676 const { thread, share } = yield* authorize(session, "session");
677 const page = yield* orchestrator
678 .getThreadHistoryPage(thread.id, cursor)
679 .pipe(Effect.mapError(() => unavailable));
680 rememberSent(
681 share.id,
682 page.items.map((row) => row.item),
683 );
684 return page;
685 });
686​
687 const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
688 session: string,
689 itemId: string,
690 ) {
691 const { thread, item } = yield* threadItem(session, itemId);
692 if (item.type !== "command_execution") return yield* unavailable;
693 return commandOutputs.subscribe({ threadId: thread.id, itemId: item.id }).pipe(
694 // A lost hub stream ends the output; the row reloads it when reopened.
695 Stream.catchCause(() => Stream.empty),
696 Stream.interruptWhen(untilRevoked(session)),
697 );
698 });
699​
700 const attachment = Effect.fn("GuestShareService.attachment")(function* (
701 session: string,
702 attachmentId: string,
703 ) {
704 const { thread, share } = yield* authorize(session, "session");
705 // A dismissed message's files are deleted with it.
706 const fromShare = share.messages
707 .flatMap((message) => (message.status === "dismissed" ? [] : (message.attachments ?? [])))
708 .find((candidate) => candidate.id === attachmentId);
709 const found =
710 fromShare ??
711 (yield* orchestrator.getThreadRecords(thread.id, ["messages"]).pipe(
712 Effect.map(({ messages }) =>
713 messages
714 .flatMap((message) => message.attachments ?? [])
715 .find((candidate) => candidate.id === attachmentId),
716 ),
717 Effect.mapError(() => unavailable),
718 ));
719 const path =
720 found === undefined ? null : resolveAttachmentPath({ attachmentsDir, attachment: found });
721 if (found === undefined || path === null) return yield* unavailable;
722 const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));
723 return exists ? { path, attachment: found } : yield* unavailable;
724 });
725​
726 const media = Effect.fn("GuestShareService.media")(function* (session: string, path: string) {
727 const { share } = yield* authorize(session, "session");
728 const mimeType = guestHostImageType(path);
729 if (mimeType === null) return yield* unavailable;
730 const sent = sentImageReplies.get(share.id)?.replies.values() ?? [];
731 // Each sent reply is parsed once, on the first request that needs it.
732 if (
733 !repliesShowImage(
734 path,
735 [...sent],
736 (reply) => (reply.sources ??= chatMarkdownImageSources(reply.text)),
737 )
738 ) {
739 return yield* unavailable;
740 }
741 // The bytes must be the image the name says, as for a guest's own upload.
742 const header = yield* fileSystem.open(path, { flag: "r" }).pipe(
743 Effect.flatMap((file) => file.readAlloc(GUEST_UPLOAD_HEADER_BYTES)),
744 Effect.scoped,
745 Effect.mapError(() => unavailable),
746 );
747 if (Option.isNone(header) || !matchesImageSignature(mimeType, header.value)) {
748 return yield* unavailable;
749 }
750 return { path, mimeType };
751 });
752​
753 return GuestShareService.of({
754 create,
755 redeem,
756 check,
757 submit,
758 stream,
759 render,
760 item,
761 history,
762 commandOutput,
763 attachment,
764 media,
765 });
766});
767​
768export const layer = Layer.effect(GuestShareService, make);