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

guestStream.logic.ts

237 lines9.1 KB

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