The best way to control Claude Code, Codex and more from any computer or phone

main
ts 235 lines 8.39 KB
Raw
1 import {
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 OrchestrationV2TurnItem,
14 type ThreadGuestMessage,
15 } from "@t3tools/contracts";
16 import { msg } from "gt-react";
17
18 import { m, type MessageResolver } from "~/i18n/messages";
19 import {
20 applyThreadHistoryPage,
21 applyThreadStreamItem,
22 initialThreadStreamState,
23 type ThreadStreamState,
24 } from "@t3tools/client-runtime/state/thread-stream";
25 import * as Option from "effect/Option";
26 import * as Schema from "effect/Schema";
27
28 export interface GuestStreamState extends ThreadStreamState {
29 readonly view: GuestShareView | null;
30 readonly ended: boolean;
31 /**
32 * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a
33 * message leaves once its row arrives, so a later bounded snapshot cannot bring it back.
34 */
35 readonly awaitingRowIds: ReadonlySet<GuestMessageId>;
36 }
37
38 export const initialGuestStreamState: GuestStreamState = {
39 ...initialThreadStreamState,
40 view: null,
41 ended: false,
42 awaitingRowIds: new Set(),
43 };
44
45 const guestMessageIdOf = (item: OrchestrationV2TurnItem) =>
46 item.type === "user_message" ? item.context?.guest?.guestMessageId : undefined;
47
48 function 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)]);
55 }
56
57 function 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;
69 }
70
71 const 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. */
76 export const parseGuestStreamEvent = (data: string): GuestStreamEvent | null =>
77 Option.getOrNull(decodeGuestStreamEvent(data));
78
79 /** A page of older turns, fetched from `cursor`. */
80 export type GuestHistoryPageLoaded = {
81 readonly type: "history-page";
82 readonly cursor: string;
83 readonly page: OrchestrationV2ThreadHistoryPage;
84 };
85
86 /**
87 * Applies the share's stream: its thread items go through the reducer every stream-only view of a
88 * thread shares, and the share's own state is tracked beside it.
89 */
90 export function applyGuestStreamEvent(
91 state: GuestStreamState,
92 event: GuestStreamEvent | GuestHistoryPageLoaded,
93 ): GuestStreamState {
94 switch (event.type) {
95 case "history-page": {
96 const next = applyThreadHistoryPage(state, event.cursor, event.page);
97 if (next === state) return state;
98 return {
99 ...state,
100 ...next,
101 awaitingRowIds: withoutPlaced(
102 state.awaitingRowIds,
103 event.page.items.map((row) => row.item),
104 ),
105 };
106 }
107 case "view":
108 // The page follows the share it names; a view of another one means the link changed.
109 if (state.view !== null && state.view.shareId !== event.view.shareId) {
110 return { ...state, ended: true };
111 }
112 return {
113 ...state,
114 view: event.view,
115 awaitingRowIds: withPendingFrom(state.awaitingRowIds, event.view),
116 };
117 case "thread": {
118 const next = applyThreadStreamItem(state, event.item);
119 if (next === state) return state;
120 const placed =
121 event.item.kind === "snapshot"
122 ? (next.projection?.visibleTurnItems.map((row) => row.item) ?? [])
123 : event.item.kind === "event" && event.item.event.type === "turn-item.updated"
124 ? [event.item.event.payload]
125 : [];
126 return {
127 ...state,
128 ...next,
129 awaitingRowIds: withoutPlaced(state.awaitingRowIds, placed),
130 };
131 }
132 case "ended":
133 return { ...state, ended: true };
134 }
135 }
136
137 /**
138 * The guest's messages to show after the transcript, oldest first. Pending ones always show. A
139 * sent or dismissed one shows only while it awaits a row (see `awaitingRowIds`): a queued send, or
140 * a dismissal to report. The transcript is a bounded window, so any other resolved message is old
141 * history, not something to place at the end.
142 */
143 export function unplacedGuestMessages(
144 messages: ReadonlyArray<ThreadGuestMessage>,
145 items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
146 awaitingRowIds: ReadonlySet<GuestMessageId>,
147 ): ReadonlyArray<ThreadGuestMessage> {
148 const placed = new Set(items.flatMap((row) => guestMessageIdOf(row.item) ?? []));
149 return messages
150 .filter(
151 (message) =>
152 !placed.has(message.id) && (message.status === "pending" || awaitingRowIds.has(message.id)),
153 )
154 .toSorted((a, b) => a.submittedAt.localeCompare(b.submittedAt));
155 }
156
157 /** "23h left" or "5m left", rounded down, for the guest page header. */
158 export function formatGuestExpiry(
159 expiresAt: string,
160 nowMs: number,
161 resolve: MessageResolver = m,
162 ): string {
163 const minutes = Math.floor((Date.parse(expiresAt) - nowMs) / 60_000);
164 if (minutes <= 0) return resolve(msg("Expired"));
165 return minutes >= 60
166 ? resolve(msg("{hours}h left", { hours: Math.floor(minutes / 60) }))
167 : resolve(msg("{minutes}m left", { minutes }));
168 }
169
170 /**
171 * The share an invite (`<shareId>.<signature>`) opens. Only used to name the share in the page
172 * URL and to find this browser's session for it; the server checks the signature.
173 */
174 export function inviteShareId(credential: string): string | null {
175 const [shareId, signature] = credential.split(".");
176 return shareId && signature ? shareId : null;
177 }
178
179 /** Where the guest page loads a file of the shared thread or of a waiting message. */
180 export const guestAttachmentUrl = (shareId: string, attachmentId: string) =>
181 `${GUEST_ATTACHMENT_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&id=${encodeURIComponent(attachmentId)}`;
182
183 /** Where the guest page loads an image file on the host that an agent message embeds. */
184 export const guestMediaUrl = (shareId: string, path: string) =>
185 `${GUEST_MEDIA_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&path=${encodeURIComponent(path)}`;
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 */
191 export function guestFilesProblem(
192 files: ReadonlyArray<Pick<File, "type" | "size">>,
193 resolve: MessageResolver = m,
194 ): string | null {
195 if (files.length > GUEST_MESSAGE_MAX_ATTACHMENTS) {
196 return resolve(
197 msg("Attach up to {count} files to a message.", { count: GUEST_MESSAGE_MAX_ATTACHMENTS }),
198 );
199 }
200 if (files.reduce((total, file) => total + file.size, 0) > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) {
201 return resolve(msg("Attached files can total up to 10 MB per message."));
202 }
203 const unsupported = files.some(
204 (file) =>
205 file.size === 0 ||
206 (file.type.toLowerCase().startsWith("image/") &&
207 !isProviderSendTurnSupportedImageMimeType(file.type)),
208 );
209 return unsupported
210 ? resolve(msg("This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP."))
211 : null;
212 }
213
214 /**
215 * Image URLs for the thread's messages, which the timeline shows as previews. The map keeps its
216 * identity while the rows do, because the timeline rebuilds its entries when it changes.
217 */
218 export function createGuestAttachmentUrls(shareId: string) {
219 let previousItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> | null = null;
220 let previous: ReadonlyMap<string, string> = new Map();
221 return (items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>): ReadonlyMap<string, string> => {
222 if (items === previousItems) return previous;
223 previousItems = items;
224 previous = new Map(
225 items.flatMap(({ item }) =>
226 item.type === "user_message"
227 ? item.attachments.map(
228 (attachment) => [attachment.id, guestAttachmentUrl(shareId, attachment.id)] as const,
229 )
230 : [],
231 ),
232 );
233 return previous;
234 };
235 }