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