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

GuestPage.tsx

833 lines30.9 KB

1import {
2 EnvironmentId,
3 GUEST_MESSAGE_MAX_LENGTH,
4 GUEST_HISTORY_ROUTE,
5 GUEST_NAME_MAX_LENGTH,
6 GUEST_ROUTE_PREFIX,
7 GUEST_SHARE_PARAM,
8 GuestMessageId,
9 type GuestRedeemRequest,
10 type GuestShareView,
11 type GuestThreadModel,
12 OrchestrationV2ThreadHistoryPage,
13 type OrchestrationV2ThreadProjection,
14 type ThreadGuestMessage,
15 type ThreadGuestMessageStatus,
16} from "@t3tools/contracts";
17import type { LegendListRef } from "@legendapp/list/react";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
21import {
22 deriveRunlessWorkStartedAt,
23 deriveThreadActivityRun,
24 deriveThreadStructureRuntime,
25} from "@t3tools/client-runtime/state/thread-execution";
26import { createQuestionHistoryProjector } from "@t3tools/client-runtime/state/thread-requests";
27import { ArrowUpIcon, PaperclipIcon, XIcon } from "lucide-react";
28import {
29 useEffect,
30 useReducer,
31 useRef,
32 useState,
33 type ClipboardEvent,
34 type FormEvent,
35 type KeyboardEvent,
36} from "react";
37import { msg, T, useGT, useMessages } from "gt-react";
38​
39import { m } from "~/i18n/messages";
40​
41import { useIncrementalTimelineEntries } from "~/hooks/useIncrementalTimelineEntries";
42import { useNowMinute } from "~/hooks/useNowMinute";
43import { useStableCallback } from "~/hooks/useStableCallback";
44import { useTheme } from "~/hooks/useTheme";
45import { cn } from "~/lib/utils";
46import { deriveActiveWorkStartedAt, derivePhase } from "~/session-logic";
47import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl";
48import type { ExpandedImagePreview } from "../chat/ExpandedImagePreview";
49import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";
50import { HostImageUrlContext } from "../chat/hostImageUrl";
51import { PierreEntryIcon } from "../chat/PierreEntryIcon";
52import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";
53import { MessagesTimeline, type MessagesTimelineHistoryControls } from "../chat/MessagesTimeline";
54import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
55import { getDisplayModelName, getTriggerDisplayModelName } from "../chat/providerIconUtils";
56import { ScrollToEndButton } from "../chat/TimelineOverlays";
57import type { TimelineRow } from "../chat/timelineRowContext";
58import { useTimelineFollow } from "../chat/useTimelineFollow";
59import { GuestHtmlRender } from "./GuestHtmlRender";
60import { Button } from "../ui/button";
61import { Input } from "../ui/input";
62import {
63 applyGuestStreamEvent,
64 formatGuestExpiry,
65 guestAttachmentUrl,
66 guestMediaUrl,
67 createGuestAttachmentUrls,
68 guestFilesProblem,
69 initialGuestStreamState,
70 inviteShareId,
71 type GuestStreamState,
72 parseGuestStreamEvent,
73 unplacedGuestMessages,
74} from "./guestStream.logic";
75import { guestTurnItemSource } from "./guestTurnItemSource";
76​
77interface GuestEntry {
78 /** Unspent invite from the URL hash, if this load came from a link. */
79 readonly credential: string | null;
80 readonly shareId: string | null;
82​
83let capturedEntry: GuestEntry | null = null;
84​
85// A reload keeps the tab's session, so it keeps which messages still wait for a row too.
86const AWAITING_ROWS_KEY = "t3:guest-awaiting-rows";
87const AWAITING_ROWS_LIMIT = 50;
88​
89function readAwaitingRowIds(): ReadonlySet<GuestMessageId> {
90 try {
91 const stored: unknown = JSON.parse(sessionStorage.getItem(AWAITING_ROWS_KEY) ?? "[]");
92 return new Set(
93 Array.isArray(stored)
94 ? stored.filter((id) => typeof id === "string").map((id) => GuestMessageId.make(id))
95 : [],
96 );
97 } catch {
98 return new Set();
99 }
101​
102function writeAwaitingRowIds(ids: ReadonlySet<GuestMessageId>) {
103 try {
104 sessionStorage.setItem(AWAITING_ROWS_KEY, JSON.stringify([...ids].slice(-AWAITING_ROWS_LIMIT)));
105 } catch {}
107​
108/**
109 * The invite credential travels in the URL hash so it never reaches a server log. It is read
110 * once and removed from history, so it lives only in memory. Opening the page never redeems it:
111 * only submitting a name does, so a reload before that leaves the link usable.
112 */
113function takeGuestEntry(): GuestEntry {
114 if (capturedEntry === null) {
115 // A malformed fragment is an invalid link, not a crash.
116 let credential = "";
117 try {
118 credential = decodeURIComponent(window.location.hash.slice(1)).trim();
119 } catch {}
120 const shareId =
121 credential !== ""
122 ? inviteShareId(credential)
123 : new URLSearchParams(window.location.search).get(GUEST_SHARE_PARAM);
124 // The share stays in the URL, so a reload or bookmark finds this browser's session for it.
125 window.history.replaceState(
126 window.history.state,
127 "",
128 shareId === null
129 ? window.location.pathname
130 : `${window.location.pathname}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
131 );
132 capturedEntry = { credential: credential === "" ? null : credential, shareId };
133 }
134 return capturedEntry;
136​
137const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({ message: Schema.String }));
138const decodeHistoryPage = Schema.decodeUnknownOption(
139 Schema.toCodecJson(OrchestrationV2ThreadHistoryPage),
140);
141​
142/** Resolves to the page, or to a message the guest can read. */
143async function fetchGuestHistoryPage(
144 shareId: string,
145 cursor: string,
146): Promise<OrchestrationV2ThreadHistoryPage | string> {
147 const failed = m(msg("Could not load earlier turns. Try again."));
148 try {
149 const response = await fetch(
150 `${GUEST_HISTORY_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&cursor=${encodeURIComponent(cursor)}`,
151 );
152 const json: unknown = await response.json().catch(() => null);
153 if (!response.ok) {
154 return Option.match(decodeErrorBody(json), {
155 onNone: () => failed,
156 onSome: ({ message }) => message,
157 });
158 }
159 return Option.getOrElse(decodeHistoryPage(json), () => failed);
160 } catch {
161 return m(msg("Could not reach the server."));
162 }
164​
165/** Resolves to null on success, or to a message the guest can read. */
166async function postGuest(
167 path: "redeem" | `messages?${string}`,
168 body: typeof GuestRedeemRequest.Encoded | FormData,
169): Promise<string | null> {
170 try {
171 const response = await fetch(
172 `${GUEST_ROUTE_PREFIX}/${path}`,
173 body instanceof FormData
174 ? { method: "POST", body }
175 : {
176 method: "POST",
177 headers: { "content-type": "application/json" },
178 body: JSON.stringify(body),
179 },
180 );
181 if (response.ok) return null;
182 const json: unknown = await response.json().catch(() => null);
183 return Option.match(decodeErrorBody(json), {
184 onNone: () => m(msg("Something went wrong. Try again.")),
185 onSome: ({ message }) => message,
186 });
187 } catch {
188 return m(msg("Could not reach the server."));
189 }
191​
192const STATUS_LABEL: Record<ThreadGuestMessageStatus, string> = {
193 pending: msg("Waiting for approval"),
194 sent: msg("Sent", { $context: "message status" }),
195 dismissed: msg("Not sent"),
196};
197​
198/** Same column as the owner's timeline, so both views wrap text at the same width. */
199const LANE = "chat-content-lane px-4";
200​
201type GuestAccess = "checking" | "session" | "name" | "none";
202​
203export function GuestPage() {
204 const gt = useGT();
205 const [{ credential, shareId }] = useState(takeGuestEntry);
206 // A browser that already joined this share goes straight back in, even from the spent link.
207 // Sessions are per share, so one for another link never stands in for this one.
208 const [access, setAccess] = useState<GuestAccess>(shareId === null ? "none" : "checking");
209 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches whether this browser already has a guest session and ignores the answer after cleanup
210 useEffect(() => {
211 if (shareId === null) return;
212 let live = true;
213 void fetch(`${GUEST_ROUTE_PREFIX}/session?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`)
214 .then(
215 (response): GuestAccess =>
216 response.ok ? "session" : credential !== null ? "name" : "none",
217 // Offline: an invite still needs the name form; without one, the stream reports what
218 // it finds once the network is back.
219 (): GuestAccess => (credential !== null ? "name" : "session"),
220 )
221 .then((next) => {
222 if (live) setAccess(next);
223 });
224 return () => {
225 live = false;
226 };
227 }, [credential, shareId]);
228 // Pasting another guest link into this tab changes only the hash, which does not reload the
229 // page; reload so the new invite is read instead of the one already captured.
230 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hashchange listener reloads the page when another guest link is pasted into this tab
231 useEffect(() => {
232 const onHashChange = () => {
233 if (window.location.hash !== "") window.location.reload();
234 };
235 window.addEventListener("hashchange", onHashChange);
236 return () => window.removeEventListener("hashchange", onHashChange);
237 }, []);
238​
239 return (
240 <div className="flex h-dvh flex-col bg-background text-foreground">
241 {access === "checking" ? (
242 <Notice title={gt("Connecting...")} />
243 ) : access === "name" && credential !== null ? (
244 <NameForm
245 credential={credential}
246 onJoined={() => {
247 // The invite is spent; a remount must open the session, not the name form again.
248 capturedEntry = { credential: null, shareId };
249 setAccess("session");
250 }}
251 />
252 ) : access === "session" && shareId !== null ? (
253 <GuestSession shareId={shareId} />
254 ) : (
255 <Notice
256 title={gt("This link has ended or is not valid")}
257 detail={gt("Ask the owner for a new link. Each link works in one browser.")}
258 />
259 )}
260 </div>
261 );
263​
264function GuestSession({ shareId }: { readonly shareId: string }) {
265 const gt = useGT();
266 const [stream, dispatch] = useReducer(applyGuestStreamEvent, null, () => ({
267 ...initialGuestStreamState,
268 awaitingRowIds: readAwaitingRowIds(),
269 }));
270 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persists the awaiting row ids to sessionStorage so a reload keeps them
271 useEffect(() => writeAwaitingRowIds(stream.awaitingRowIds), [stream.awaitingRowIds]);
272 // EventSource closes for good only on a non-200 response, which the guest routes send for a
273 // missing, invalid, or ended session. Network drops reconnect on their own.
274 const [rejected, setRejected] = useState(false);
275​
276 const [historyLoad, setHistoryLoad] = useState<{
277 readonly cursor: string;
278 readonly error: string | null;
279 } | null>(null);
280 const historyCursor = stream.historyCursor;
281 // A load for an older cursor is stale: a page or a reconnect snapshot moved the cursor on.
282 const currentLoad = historyLoad?.cursor === historyCursor ? historyLoad : null;
283 const loadingHistory = currentLoad !== null && currentLoad.error === null;
284 const historyError = currentLoad?.error ?? null;
285 const loadEarlier = async () => {
286 if (historyCursor === null || loadingHistory) return;
287 setHistoryLoad({ cursor: historyCursor, error: null });
288 const result = await fetchGuestHistoryPage(shareId, historyCursor);
289 if (typeof result === "string") setHistoryLoad({ cursor: historyCursor, error: result });
290 else dispatch({ type: "history-page", cursor: historyCursor, page: result });
291 };
292 const historyControls: MessagesTimelineHistoryControls | undefined =
293 historyCursor === null
294 ? undefined
295 : {
296 hasMoreHistory: true,
297 loading: loadingHistory,
298 error: historyError,
299 onLoadEarlier: () => void loadEarlier(),
300 };
301​
302 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets document.title to the shared thread's title
303 useEffect(() => {
304 if (stream.view) document.title = stream.view.title;
305 }, [stream.view]);
306​
307 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the guest EventSource stream and closes it on cleanup
308 useEffect(() => {
309 const source = new EventSource(
310 `${GUEST_ROUTE_PREFIX}/stream?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
311 );
312 source.addEventListener("message", (message) => {
313 const event = parseGuestStreamEvent(message.data);
314 if (event === null) return;
315 dispatch(event);
316 if (event.type === "ended") source.close();
317 });
318 source.addEventListener("error", () => {
319 if (source.readyState === EventSource.CLOSED) setRejected(true);
320 });
321 return () => source.close();
322 }, [shareId]);
323​
324 if (stream.ended || (rejected && stream.view !== null)) {
325 return (
326 <Notice
327 title={gt("This link has ended")}
328 detail={gt("The owner stopped sharing this thread.")}
329 />
330 );
331 }
332 if (stream.view !== null) {
333 if (stream.projection === null) return <Notice title={gt("Connecting...")} />;
334 return (
335 <GuestThread
336 view={stream.view}
337 projection={stream.projection}
338 awaitingRowIds={stream.awaitingRowIds}
339 historyControls={historyControls}
340 />
341 );
342 }
343 if (!rejected) return <Notice title={gt("Connecting...")} />;
344 return (
345 <Notice
346 title={gt("This link has ended or is not valid")}
347 detail={gt("Ask the owner for a new link. Each link works in one browser.")}
348 />
349 );
351​
352function Notice({ title, detail }: { readonly title: string; readonly detail?: string }) {
353 return (
354 <div className="m-auto flex max-w-sm flex-col gap-1 p-6 text-center">
355 <p className="text-sm font-medium">{title}</p>
356 {detail ? <p className="text-xs text-muted-foreground">{detail}</p> : null}
357 </div>
358 );
360​
361function NameForm({
362 credential,
363 onJoined,
364}: {
365 readonly credential: string;
366 readonly onJoined: () => void;
367}) {
368 const gt = useGT();
369 const [name, setName] = useState("");
370 const [submitting, setSubmitting] = useState(false);
371 const [error, setError] = useState<string | null>(null);
372 const submit = async (event: FormEvent) => {
373 event.preventDefault();
374 const trimmed = name.trim();
375 if (trimmed === "" || submitting) return;
376 setSubmitting(true);
377 const failure = await postGuest("redeem", { credential, name: trimmed });
378 setSubmitting(false);
379 if (failure === null) onJoined();
380 else setError(failure);
381 };
382 return (
383 <form className="m-auto flex w-full max-w-xs flex-col gap-3 p-6" onSubmit={submit}>
384 <h1 className="text-base font-medium">
385 <T>Join a shared thread</T>
386 </h1>
387 <label className="flex flex-col gap-1.5 text-sm" htmlFor="guest-name">
388 {gt("Your name")}
389 <Input
390 id="guest-name"
391 autoFocus
392 autoComplete="name"
393 maxLength={GUEST_NAME_MAX_LENGTH}
394 value={name}
395 onChange={(event) => setName(event.target.value)}
396 />
397 </label>
398 {error !== null ? (
399 <p role="alert" className="text-sm text-destructive">
400 {error}
401 </p>
402 ) : null}
403 <Button type="submit" disabled={submitting || name.trim() === ""}>
404 <T context="verb, join a shared thread">Join</T>
405 </Button>
406 <p className="text-xs text-muted-foreground">
407 <T>The owner sees your name and approves each message before the agent gets it.</T>
408 </p>
409 </form>
410 );
412​
413// The timeline needs an environment id to key its rows. Nothing behind it loads on this page;
414// see isGuestPage.
415const GUEST_ENVIRONMENT_ID = EnvironmentId.make("guest");
416const NO_TURN_DIFFS: ReadonlyArray<never> = [];
417const NO_OPTIMISTIC_MESSAGES: ReadonlyArray<never> = [];
418const ignore = () => {};
419​
420/**
421 * The owner's timeline, read-only: every action that would reach the owner's machine (fork,
422 * revert, diffs, files, other threads, shell) is left out, so its control does not render.
423 */
424function GuestThread({
425 view: { shareId, title, expiresAt, messages, model },
426 projection,
427 awaitingRowIds,
428 historyControls,
429}: {
430 readonly view: GuestShareView;
431 readonly projection: OrchestrationV2ThreadProjection;
432 readonly awaitingRowIds: GuestStreamState["awaitingRowIds"];
433 readonly historyControls: MessagesTimelineHistoryControls | undefined;
434}) {
435 // No ":" so the timeline finds no environment thread behind the key.
436 const threadKey = `guest-${shareId}`;
437 const listRef = useRef<LegendListRef | null>(null);
438 const { resolvedTheme } = useTheme();
439 // The rest is what ChatView derives from the same projection.
440 const [projectQuestionHistory] = useState(() => createQuestionHistoryProjector());
441 const items = projectQuestionHistory(projection);
442 // Files load through the guest route.
443 const [attachmentUrls] = useState(() => createGuestAttachmentUrls(shareId));
444 // Expanded rows read detail and command output through the guest routes.
445 const [turnItemSource] = useState(() => guestTurnItemSource(shareId));
446 const attachmentUrlById = attachmentUrls(items);
447 const entries = useIncrementalTimelineEntries(threadKey, {
448 visibleTurnItems: items,
449 optimisticMessages: NO_OPTIMISTIC_MESSAGES,
450 attachmentUrlById,
451 attempts: projection.attempts,
452 nodes: projection.nodes,
453 plans: projection.plans,
454 });
455 const openFile = useStableCallback((file: { readonly id: string }) =>
456 openInNewTab(guestAttachmentUrl(shareId, file.id)),
457 );
458 const hostImageUrl = useStableCallback((path: string) => guestMediaUrl(shareId, path));
459 const activityRun = deriveThreadActivityRun(projection);
460 const runtime = deriveThreadStructureRuntime(projection);
461 const runlessWorkStartedAt = deriveRunlessWorkStartedAt(projection);
462 const isWorking = derivePhase(runtime) === "running" || runlessWorkStartedAt !== null;
463 const workStartedAt =
464 deriveActiveWorkStartedAt(activityRun, runtime, null) ?? runlessWorkStartedAt;
465 const runningRunId = runtime?.activeRunId ?? null;
466 const follow = useTimelineFollow({
467 legendListRef: listRef,
468 composerTimelineInset: 0,
469 routeThreadKey: threadKey,
470 activeThreadKey: threadKey,
471 // Not a server thread: new turns follow the end instead of anchoring near the top.
472 isServerThread: false,
473 serverProjection: null,
474 threadStatus: "live",
475 activeActivityRun: activityRun,
476 activeRunningTurnId: runningRunId,
477 timelineEntries: entries,
478 timelineAnchorMessageId: null,
479 setTimelineAnchor: ignore,
480 });
481 const renderHtmlRender = useStableCallback(
482 (row: Extract<TimelineRow, { kind: "html-render" }>) => (
483 <GuestHtmlRender itemId={row.id} reference={row.htmlRender} shareId={shareId} />
484 ),
485 );
486 const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds);
487 return (
488 <>
489 <header className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5">
490 <h1 className="min-w-0 flex-1 truncate text-sm font-medium">{title}</h1>
491 <ExpiryLabel expiresAt={expiresAt} />
492 </header>
493 <div className="relative min-h-0 flex-1">
494 <HostImageUrlContext value={hostImageUrl}>
495 <MessagesTimeline
496 listRef={listRef}
497 timelineEntries={entries}
498 isWorking={isWorking}
499 activeTurnStartedAt={workStartedAt}
500 latestRun={activityRun}
501 runningRunId={runningRunId}
502 turnDiffSummaries={NO_TURN_DIFFS}
503 runs={projection.runs}
504 routeThreadKey={threadKey}
505 onOpenThread={ignore}
506 supportsConversationRollback={false}
507 onRevertToTurnCount={ignore}
508 isRevertingCheckpoint={false}
509 onImageExpand={openExpandedImage}
510 onFileOpen={openFile}
511 onFileDownload={openFile}
512 renderHtmlRender={renderHtmlRender}
513 turnItemSource={turnItemSource}
514 historyControls={historyControls}
515 activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}
516 markdownCwd={undefined}
517 resolvedTheme={resolvedTheme}
518 timestampFormat="locale"
519 workspaceRoot={undefined}
520 anchorMessageId={null}
521 onAnchorReady={ignore}
522 onAnchorSizeChanged={ignore}
523 contentInsetEndAdjustment={0}
524 emptyPlaceholderInset={0}
525 liveFollowEnabled={follow.timelineLiveFollowEnabled}
526 onIsAtEndChange={follow.onIsAtEndChangeStable}
527 onViewportAttach={follow.attachTimelineViewport}
528 onFooterGrow={follow.onTimelineFooterGrowStable}
529 footer={
530 unplaced.length === 0 ? null : (
531 <ol className="chat-content-lane flex flex-col gap-4 pb-4">
532 {unplaced.map((message) => (
533 <li key={message.id}>
534 <UnplacedGuestMessage shareId={shareId} message={message} />
535 </li>
536 ))}
537 </ol>
538 )
539 }
540 />
541 </HostImageUrlContext>
542 {follow.showScrollToBottom ? (
543 <ScrollToEndButton
544 summary={null}
545 bottom={4}
546 onScrollToEnd={() => follow.scrollToEnd(true)}
547 />
548 ) : null}
549 </div>
550 <div className={cn(LANE, "shrink-0 pb-4")}>
551 <GuestComposer shareId={shareId} model={model} onSent={() => follow.scrollToEnd(true)} />
552 </div>
553 </>
554 );
556​
557function ExpiryLabel({ expiresAt }: { readonly expiresAt: string }) {
558 const nowMinute = useNowMinute();
559 const m = useMessages();
560 return (
561 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
562 {formatGuestExpiry(expiresAt, Date.parse(`${nowMinute}Z`), m)}
563 </span>
564 );
566​
567const BUBBLE =
568 "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-sm whitespace-pre-wrap [overflow-wrap:anywhere]";
569​
570const openInNewTab = (url: string) => window.open(url, "_blank", "noopener,noreferrer");
571/** Guests have no image viewer; the browser shows the picture in its own tab. */
572const openExpandedImage = (preview: ExpandedImagePreview) => {
573 const src = preview.images[preview.index]?.src;
574 if (src) openInNewTab(src);
575};
576​
577/** A guest message the owner has not sent yet, or chose not to send. */
578function UnplacedGuestMessage({
579 shareId,
580 message,
581}: {
582 readonly shareId: GuestShareView["shareId"];
583 readonly message: ThreadGuestMessage;
584}) {
585 // A dismissed message's files are deleted, so only their names remain.
586 const served = message.status !== "dismissed";
587 const gt = useGT();
588 const m = useMessages();
589 const url = (attachment: { readonly id: string }) => guestAttachmentUrl(shareId, attachment.id);
590 return (
591 <div className="flex flex-col items-end gap-1">
592 <GuestMessageName name={gt("You", { $context: "the guest's own messages" })} />
593 <div
594 className={cn(
595 BUBBLE,
596 guestBubbleClassName(message.status !== "sent"),
597 message.status === "dismissed" ? "text-muted-foreground" : "text-message-foreground",
598 )}
599 >
600 <GuestMessageAttachments
601 attachments={message.attachments ?? []}
602 imageUrl={(attachment) => (served ? url(attachment) : undefined)}
603 onOpenImage={(attachment) => openInNewTab(url(attachment))}
604 {...(served ? { fileHref: url } : {})}
605 />
606 {message.text ? <span>{message.text}</span> : null}
607 </div>
608 <p className="me-1 text-2xs text-muted-foreground">{m(STATUS_LABEL[message.status])}</p>
609 </div>
610 );
612​
613/** The thread's model, labeled as the owner's composer labels it, with no way to change it. */
614function GuestModelLabel({ model }: { readonly model: GuestThreadModel }) {
615 const label = getTriggerDisplayModelName({ slug: model.name, ...model }, model.driver);
616 const fullLabel = getDisplayModelName({ slug: model.name, ...model });
617 const gt = useGT();
618 return (
619 <ComposerControl
620 render={<span />}
621 aria-label={gt("Model: {model}", { model: fullLabel })}
622 className="pointer-events-none min-w-0 shrink"
623 >
624 {model.driver === null ? null : (
625 <ProviderInstanceIcon
626 driverKind={model.driver}
627 displayName={label}
628 className="size-4"
629 iconClassName="size-4"
630 />
631 )}
632 <span className="min-w-0 truncate" data-chat-provider-model-picker-label="true">
633 {label}
634 </span>
635 </ComposerControl>
636 );
638​
639interface StagedFile {
640 readonly key: string;
641 readonly file: File;
643​
644/** A staged image's thumbnail; its object URL lives as long as the element. */
645function StagedImage({ file }: { readonly file: File }) {
646 return (
647 <img
648 alt={file.name}
649 className="size-full object-cover"
650 ref={(image) => {
651 if (!image) return;
652 const url = URL.createObjectURL(file);
653 image.src = url;
654 return () => URL.revokeObjectURL(url);
655 }}
656 />
657 );
659​
660function GuestComposer({
661 shareId,
662 model,
663 onSent,
664}: {
665 readonly shareId: GuestShareView["shareId"];
666 readonly model: GuestThreadModel;
667 /** The guest's own message comes into view even if they had scrolled up, as the owner's does. */
668 readonly onSent: () => void;
669}) {
670 const gt = useGT();
671 const m = useMessages();
672 const [text, setText] = useState("");
673 const [files, setFiles] = useState<ReadonlyArray<StagedFile>>([]);
674 const [sending, setSending] = useState(false);
675 const [error, setError] = useState<string | null>(null);
676 const fileInputRef = useRef<HTMLInputElement>(null);
677 const nextFileKey = useRef(0);
678 const { resolvedTheme } = useTheme();
679 const addFiles = (added: ReadonlyArray<File>) => {
680 if (added.length === 0) return;
681 const next = [
682 ...files,
683 ...added.map((file) => ({ key: `staged-${nextFileKey.current++}`, file })),
684 ];
685 const problem = guestFilesProblem(
686 next.map((staged) => staged.file),
687 m,
688 );
689 setError(problem);
690 if (problem === null) setFiles(next);
691 };
692 const send = async () => {
693 const trimmed = text.trim();
694 if ((trimmed === "" && files.length === 0) || sending) return;
695 setSending(true);
696 const sentFiles = files;
697 const form = new FormData();
698 form.append("shareId", shareId);
699 form.append("text", trimmed);
700 for (const staged of sentFiles) form.append("file", staged.file, staged.file.name);
701 const failure = await postGuest(
702 `messages?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}`,
703 form,
704 );
705 setSending(false);
706 setError(failure);
707 // Keep anything typed or attached while the request was in flight.
708 if (failure === null) {
709 onSent();
710 setText((current) => (current.trim() === trimmed ? "" : current));
711 setFiles((current) => current.filter((staged) => !sentFiles.includes(staged)));
712 }
713 };
714 const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
715 // Same as the app composer: Enter sends, Shift+Enter adds a line, IME composition is left alone.
716 if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
717 event.preventDefault();
718 void send();
719 }
720 };
721 // As in the app composer: pasted images attach, and other files attach when no text came along.
722 const onPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
723 const pasted = Array.from(event.clipboardData.files);
724 const hasImage = pasted.some((file) => file.type.startsWith("image/"));
725 if (pasted.length === 0 || (!hasImage && event.clipboardData.getData("text/plain") !== "")) {
726 return;
727 }
728 event.preventDefault();
729 addFiles(pasted);
730 };
731 return (
732 <form
733 className="flex flex-col gap-2 rounded-3xl border border-border bg-card px-4 pt-3 pb-2.5 shadow-composer dark:shadow-composer-dark"
734 onSubmit={(event) => {
735 event.preventDefault();
736 void send();
737 }}
738 onDragOver={(event) => {
739 if (event.dataTransfer.types.includes("Files")) event.preventDefault();
740 }}
741 onDrop={(event) => {
742 if (event.dataTransfer.files.length === 0) return;
743 event.preventDefault();
744 addFiles(Array.from(event.dataTransfer.files));
745 }}
746 >
747 {files.length > 0 ? (
748 <ul className="flex flex-wrap gap-2" aria-label={gt("Attached files")}>
749 {files.map((staged) => (
750 <li
751 key={staged.key}
752 className="flex h-14 min-w-0 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background/70 pe-1"
753 >
754 {staged.file.type.startsWith("image/") ? (
755 <span className="size-14 shrink-0">
756 <StagedImage file={staged.file} />
757 </span>
758 ) : (
759 <span className="flex min-w-0 items-center gap-2 ps-2 text-sm">
760 <PierreEntryIcon pathValue={staged.file.name} kind="file" theme={resolvedTheme} />
761 <span className="max-w-40 truncate">{staged.file.name}</span>
762 <span className="shrink-0 text-xs text-muted-foreground">
763 {formatAttachmentSize(staged.file.size, m)}
764 </span>
765 </span>
766 )}
767 <Button
768 size="icon-xs"
769 variant="ghost-muted"
770 aria-label={gt("Remove {name}", { name: staged.file.name })}
771 onClick={() => {
772 setError(null);
773 setFiles((current) => current.filter((candidate) => candidate !== staged));
774 }}
775 >
776 <XIcon />
777 </Button>
778 </li>
779 ))}
780 </ul>
781 ) : null}
782 <textarea
783 aria-label={gt("Message", { $context: "message input" })}
784 placeholder={gt("Message", { $context: "message input" })}
785 rows={2}
786 maxLength={GUEST_MESSAGE_MAX_LENGTH}
787 value={text}
788 onChange={(event) => setText(event.target.value)}
789 onKeyDown={onKeyDown}
790 onPaste={onPaste}
791 className="max-h-60 min-h-12 w-full resize-none bg-transparent text-sm outline-none field-sizing-content placeholder:text-placeholder"
792 />
793 <div className="flex items-center gap-3">
794 <input
795 ref={fileInputRef}
796 type="file"
797 multiple
798 hidden
799 aria-label={gt("Files to attach")}
800 onChange={(event) => {
801 addFiles(Array.from(event.target.files ?? []));
802 // The same file can be picked again after it is removed.
803 event.target.value = "";
804 }}
805 />
806 <ComposerControl
807 aria-label={gt("Attach files")}
808 onClick={() => fileInputRef.current?.click()}
809 >
810 <ComposerControlIcon icon={PaperclipIcon} />
811 </ComposerControl>
812 <GuestModelLabel model={model} />
813 {error !== null ? (
814 <p role="alert" className="min-w-0 flex-1 text-xs text-destructive">
815 {error}
816 </p>
817 ) : (
818 <p className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
819 <T>The owner approves each message</T>
820 </p>
821 )}
822 <button
823 type="submit"
824 aria-label={gt("Send", { $context: "verb, sends the message" })}
825 disabled={sending || (text.trim() === "" && files.length === 0)}
826 className="flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-message-action text-message-action-foreground shadow-xs hover:bg-message-action-hover focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-64"
827 >
828 <ArrowUpIcon aria-hidden className="size-4" />
829 </button>
830 </div>
831 </form>
832 );