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

GuestShareService.ts

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