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