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

GuestPage.tsx

771 lines29.1 KB

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