@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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