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