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

guestStream.logic.ts

232 lines8.8 KB

1import {
2 GUEST_ATTACHMENT_ROUTE,
3 GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
4 GUEST_MESSAGE_MAX_ATTACHMENTS,
5 GUEST_SHARE_PARAM,
6 GuestStreamEvent,
7 isProviderSendTurnSupportedImageMimeType,
8 type GuestMessageId,
9 type GuestShareView,
10 type OrchestrationV2ProjectedTurnItem,
11 type OrchestrationV2ThreadProjection,
12 type OrchestrationV2TurnItem,
13 type ThreadGuestMessage,
14} from "@t3tools/contracts";
15import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";
16import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19​
20export interface GuestStreamState {
21 readonly view: GuestShareView | null;
22 /** The thread as the owner's client holds it, built with the same reducer. */
23 readonly projection: OrchestrationV2ThreadProjection | null;
24 readonly sequence: number;
25 /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */
26 readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null;
27 readonly ended: boolean;
28 /**
29 * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a
30 * message leaves once its row arrives, so a later bounded snapshot cannot bring it back.
31 */
32 readonly awaitingRowIds: ReadonlySet<GuestMessageId>;
34​
35export const initialGuestStreamState: GuestStreamState = {
36 view: null,
37 projection: null,
38 sequence: 0,
39 partial: null,
40 ended: false,
41 awaitingRowIds: new Set(),
42};
43​
44const guestMessageIdOf = (item: OrchestrationV2TurnItem) =>
45 item.type === "user_message" ? item.context?.guest?.guestMessageId : undefined;
46​
47function withPendingFrom(
48 awaiting: ReadonlySet<GuestMessageId>,
49 view: GuestShareView,
50): ReadonlySet<GuestMessageId> {
51 const pending = view.messages.filter((message) => message.status === "pending");
52 if (pending.every((message) => awaiting.has(message.id))) return awaiting;
53 return new Set([...awaiting, ...pending.map((message) => message.id)]);
55​
56function withoutPlaced(
57 awaiting: ReadonlySet<GuestMessageId>,
58 items: ReadonlyArray<OrchestrationV2TurnItem>,
59): ReadonlySet<GuestMessageId> {
60 const placed = items.flatMap((item) => {
61 const id = guestMessageIdOf(item);
62 return id !== undefined && awaiting.has(id) ? [id] : [];
63 });
64 if (placed.length === 0) return awaiting;
65 const next = new Set(awaiting);
66 for (const id of placed) next.delete(id);
67 return next;
69​
70const decodeGuestStreamEvent = Schema.decodeUnknownOption(
71 Schema.fromJsonString(Schema.toCodecJson(GuestStreamEvent)),
72);
73​
74/** Returns null for anything the server would never send, so a bad frame is skipped, not fatal. */
75export const parseGuestStreamEvent = (data: string): GuestStreamEvent | null =>
76 Option.getOrNull(decodeGuestStreamEvent(data));
77​
78/**
79 * Applies the owner's thread stream the way the owner's client does (see
80 * EnvironmentThreadState in client-runtime): a snapshot replaces the thread, and later events
81 * pass through the same projection reducer, once each.
82 */
83export function applyGuestStreamEvent(
84 state: GuestStreamState,
85 event: GuestStreamEvent,
86): GuestStreamState {
87 switch (event.type) {
88 case "view":
89 // The page follows the share it names; a view of another one means the link changed.
90 if (state.view !== null && state.view.shareId !== event.view.shareId) {
91 return { ...state, ended: true };
92 }
93 return {
94 ...state,
95 view: event.view,
96 awaitingRowIds: withPendingFrom(state.awaitingRowIds, event.view),
97 };
98 case "thread": {
99 const item = event.item;
100 if (item.kind === "snapshot") {
101 const projection = boundedSnapshotProjection(item);
102 return {
103 ...state,
104 projection,
105 sequence: item.snapshotSequence,
106 partial:
107 item.hasMoreHistory === true || (item.historyCursor ?? null) !== null
108 ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null }
109 : null,
110 awaitingRowIds: withoutPlaced(
111 state.awaitingRowIds,
112 projection.visibleTurnItems.map((row) => row.item),
113 ),
114 };
115 }
116 if (item.kind === "synchronized" || item.sequence <= state.sequence) return state;
117 if (item.kind === "unknown-event") return { ...state, sequence: item.sequence };
118 const projection =
119 applyOrchestrationV2ProjectionEvent(
120 state.projection,
121 item.event,
122 state.partial === null ? undefined : { partialTimeline: true, ...state.partial },
123 ) ?? state.projection;
124 const turnItem = item.event.type === "turn-item.updated" ? item.event.payload : null;
125 const watermark = state.partial?.latestLocalTurnOrdinal ?? null;
126 return {
127 ...state,
128 projection,
129 sequence: item.sequence,
130 partial:
131 state.partial !== null &&
132 turnItem !== null &&
133 (watermark === null || turnItem.ordinal > watermark)
134 ? { latestLocalTurnOrdinal: turnItem.ordinal }
135 : state.partial,
136 awaitingRowIds:
137 turnItem === null
138 ? state.awaitingRowIds
139 : withoutPlaced(state.awaitingRowIds, [turnItem]),
140 };
141 }
142 case "ended":
143 return { ...state, ended: true };
144 }
146​
147/**
148 * The guest's messages to show after the transcript, oldest first. Pending ones always show. A
149 * sent or dismissed one shows only while it awaits a row (see `awaitingRowIds`): a queued send, or
150 * a dismissal to report. The transcript is a bounded window, so any other resolved message is old
151 * history, not something to place at the end.
152 */
153export function unplacedGuestMessages(
154 messages: ReadonlyArray<ThreadGuestMessage>,
155 items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
156 awaitingRowIds: ReadonlySet<GuestMessageId>,
157): ReadonlyArray<ThreadGuestMessage> {
158 const placed = new Set(items.flatMap((row) => guestMessageIdOf(row.item) ?? []));
159 return messages
160 .filter(
161 (message) =>
162 !placed.has(message.id) && (message.status === "pending" || awaitingRowIds.has(message.id)),
163 )
164 .toSorted((a, b) => a.submittedAt.localeCompare(b.submittedAt));
166​
167/** "23h left" or "5m left", rounded down, for the guest page header. */
168export function formatGuestExpiry(expiresAt: string, nowMs: number): string {
169 const minutes = Math.floor((Date.parse(expiresAt) - nowMs) / 60_000);
170 if (minutes <= 0) return "Expired";
171 return minutes >= 60 ? `${Math.floor(minutes / 60)}h left` : `${minutes}m left`;
173​
174/**
175 * The share an invite (`<shareId>.<signature>`) opens. Only used to name the share in the page
176 * URL and to find this browser's session for it; the server checks the signature.
177 */
178export function inviteShareId(credential: string): string | null {
179 const [shareId, signature] = credential.split(".");
180 return shareId && signature ? shareId : null;
182​
183/** Where the guest page loads a file of the shared thread or of a waiting message. */
184export const guestAttachmentUrl = (shareId: string, attachmentId: string) =>
185 `${GUEST_ATTACHMENT_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&id=${encodeURIComponent(attachmentId)}`;
186​
187/**
188 * Why these files cannot go with one message, or null. The server checks the same limits; this
189 * only says so before the upload.
190 */
191export function guestFilesProblem(
192 files: ReadonlyArray<Pick<File, "type" | "size">>,
193): string | null {
194 if (files.length > GUEST_MESSAGE_MAX_ATTACHMENTS) {
195 return `Attach up to ${GUEST_MESSAGE_MAX_ATTACHMENTS} files to a message.`;
196 }
197 if (files.reduce((total, file) => total + file.size, 0) > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) {
198 return "Attached files can total up to 10 MB per message.";
199 }
200 const unsupported = files.some(
201 (file) =>
202 file.size === 0 ||
203 (file.type.toLowerCase().startsWith("image/") &&
204 !isProviderSendTurnSupportedImageMimeType(file.type)),
205 );
206 return unsupported
207 ? "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP."
208 : null;
210​
211/**
212 * Image URLs for the thread's messages, which the timeline shows as previews. The map keeps its
213 * identity while the rows do, because the timeline rebuilds its entries when it changes.
214 */
215export function createGuestAttachmentUrls(shareId: string) {
216 let previousItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> | null = null;
217 let previous: ReadonlyMap<string, string> = new Map();
218 return (items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>): ReadonlyMap<string, string> => {
219 if (items === previousItems) return previous;
220 previousItems = items;
221 previous = new Map(
222 items.flatMap(({ item }) =>
223 item.type === "user_message"
224 ? item.attachments.map(
225 (attachment) => [attachment.id, guestAttachmentUrl(shareId, attachment.id)] as const,
226 )
227 : [],
228 ),
229 );
230 return previous;
231 };