Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import {
7 AuthOrchestrationOperateScope,
8 type ChatAttachment,
9 type GuestMessageId,
10 type ScopedThreadRef,
11 type ThreadGuestShare,
12} from "@t3tools/contracts";
13import { CheckIcon, CopyIcon, UserIcon } from "lucide-react";
14import { useState } from "react";
15
16import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
17import { useNowMinute } from "~/hooks/useNowMinute";
18import { appAtomRegistry } from "~/rpc/atomRegistry";
19import { useQuietThreadProjection } from "~/state/entities";
20import { serverEnvironment } from "~/state/server";
21import { useEnvironmentScope } from "~/state/session";
22import { threadEnvironment } from "~/state/threads";
23import { useAtomCommand } from "~/state/use-atom-command";
24import { cn } from "~/lib/utils";
25import { useOrchestrationCommand } from "~/state/use-orchestration-command";
26import { Button } from "../ui/button";
27import {
28 Dialog,
29 DialogDescription,
30 DialogFooter,
31 DialogHeader,
32 DialogPanel,
33 DialogPopup,
34 DialogTitle,
35} from "../ui/dialog";
36import { Input } from "../ui/input";
37import { useAssetUrls } from "~/assets/assetUrls";
38import { type ChatFileAttachment, isImageAttachment } from "../../types";
39import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
40import { GuestMessageAttachments } from "./GuestMessageAttachments";
41import { GuestMessageName, guestBubbleClassName } from "./guestMessageStyle";
42import { guestShareDialogThreadAtom } from "./guestShareDialogState";
43
44function useThreadGuestShare(threadRef: ScopedThreadRef | null): ThreadGuestShare | null {
45 return useQuietThreadProjection(threadRef)?.projection.thread.guestShare ?? null;
46}
47
48export function GuestShareDialogHost() {
49 const threadRef = useAtomValue(guestShareDialogThreadAtom);
50 if (threadRef === null) return null;
51 return (
52 <GuestShareDialog
53 key={`${threadRef.environmentId}:${threadRef.threadId}`}
54 threadRef={threadRef}
55 onClose={() => appAtomRegistry.set(guestShareDialogThreadAtom, null)}
56 />
57 );
58}
59
60type CreateState =
61 | { readonly status: "idle" }
62 | { readonly status: "creating" }
63 | { readonly status: "created"; readonly url: string }
64 | { readonly status: "failed"; readonly message: string };
65
66function GuestShareDialog({
67 threadRef,
68 onClose,
69}: {
70 readonly threadRef: ScopedThreadRef;
71 readonly onClose: () => void;
72}) {
73 const activeShare = useThreadGuestShare(threadRef);
74 const canCreate = useAtomValue(
75 serverEnvironment.createGuestShare.permissionAtom(threadRef.environmentId),
76 );
77 const createGuestShare = useAtomCommand(serverEnvironment.createGuestShare, {
78 reportFailure: false,
79 });
80 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "guest link" });
81 const [state, setState] = useState<CreateState>({ status: "idle" });
82
83 const create = async () => {
84 setState({ status: "creating" });
85 const result = await createGuestShare({
86 environmentId: threadRef.environmentId,
87 input: { threadId: threadRef.threadId },
88 });
89 if (result._tag === "Success") {
90 setState({ status: "created", url: result.value.url });
91 return;
92 }
93 if (isAtomCommandInterrupted(result)) {
94 setState({ status: "idle" });
95 return;
96 }
97 const error = squashAtomCommandFailure(result);
98 setState({
99 status: "failed",
100 message: error instanceof Error ? error.message : "Could not create a guest link.",
101 });
102 };
103
104 return (
105 <Dialog
106 open
107 onOpenChange={(open) => {
108 if (!open && state.status !== "creating") onClose();
109 }}
110 >
111 <DialogPopup className="max-w-lg">
112 <DialogHeader>
113 <DialogTitle>Share with guest</DialogTitle>
114 <DialogDescription>
115 The guest sees the thread as you do, including command output and the agent's
116 reasoning. Each message they send waits for you.
117 </DialogDescription>
118 </DialogHeader>
119 <DialogPanel>
120 {state.status === "created" ? (
121 <div className="flex items-center gap-2">
122 <Input
123 readOnly
124 aria-label="Guest link"
125 value={state.url}
126 onFocus={(event) => event.currentTarget.select()}
127 />
128 <Button size="sm" variant="outline" onClick={() => copyToClipboard(state.url)}>
129 {isCopied ? <CheckIcon /> : <CopyIcon />}
130 {isCopied ? "Copied" : "Copy"}
131 </Button>
132 </div>
133 ) : (
134 <p className="text-muted-foreground text-sm">
135 {activeShare !== null
136 ? "A new link ends the current one."
137 : "The link works once and expires in 24 hours."}
138 </p>
139 )}
140 {state.status === "failed" ? (
141 <p role="alert" className="text-destructive text-xs">
142 {state.message}
143 </p>
144 ) : null}
145 </DialogPanel>
146 <DialogFooter>
147 {state.status === "created" ? (
148 <Button size="sm" onClick={onClose}>
149 Done
150 </Button>
151 ) : (
152 <>
153 <Button
154 variant="outline"
155 size="sm"
156 onClick={onClose}
157 disabled={state.status === "creating"}
158 >
159 Cancel
160 </Button>
161 <Button
162 size="sm"
163 onClick={() => void create()}
164 disabled={!canCreate || state.status === "creating"}
165 >
166 {state.status === "creating" ? "Creating..." : "Create link"}
167 </Button>
168 </>
169 )}
170 </DialogFooter>
171 </DialogPopup>
172 </Dialog>
173 );
174}
175
176/** Header status for a shared thread, with the way to end the share. */
177export function GuestShareIndicator({ threadRef }: { readonly threadRef: ScopedThreadRef }) {
178 const share = useThreadGuestShare(threadRef);
179 const closeGuestShare = useOrchestrationCommand(threadEnvironment.closeGuestShare, {
180 label: "stop guest share",
181 });
182 const [closing, setClosing] = useState(false);
183 if (share === null) return null;
184 return (
185 <div className="flex shrink-0 items-center gap-1 text-muted-foreground text-xs">
186 <UserIcon aria-hidden className="size-3.5" />
187 <GuestShareStatus share={share} />
188 <Button
189 size="xs"
190 variant="ghost-muted"
191 disabled={closing}
192 onClick={async () => {
193 setClosing(true);
194 await closeGuestShare({
195 environmentId: threadRef.environmentId,
196 input: { threadId: threadRef.threadId },
197 });
198 setClosing(false);
199 }}
200 >
201 Stop sharing
202 </Button>
203 </div>
204 );
205}
206
207function GuestShareStatus({ share }: { readonly share: ThreadGuestShare }) {
208 const nowMinute = useNowMinute();
209 // The share stays on the thread after it expires, until the owner clears it.
210 if (share.expiresAt.slice(0, 16) <= nowMinute) return <span>Guest link expired</span>;
211 return (
212 <span>{share.guestName !== null ? `${share.guestName} is a guest` : "Guest link active"}</span>
213 );
214}
215
216/**
217 * A guest's messages wait at the end of the timeline until the owner sends or dismisses each one.
218 * Sent ones then show in the timeline as normal user messages with the guest's name.
219 */
220export function GuestPendingMessages({
221 threadRef,
222 onImageExpand,
223 onFileOpen,
224}: {
225 readonly threadRef: ScopedThreadRef;
226 readonly onImageExpand: (preview: ExpandedImagePreview) => void;
227 readonly onFileOpen: (attachment: ChatFileAttachment) => void;
228}) {
229 const share = useThreadGuestShare(threadRef);
230 const canOperate = useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope);
231 const resolveGuestMessage = useOrchestrationCommand(threadEnvironment.resolveGuestMessage, {
232 label: "resolve guest message",
233 });
234 const [busyIds, setBusyIds] = useState<ReadonlySet<GuestMessageId>>(new Set());
235 const pending = share?.messages.filter((message) => message.status === "pending") ?? [];
236 // The files are the thread's attachments, which the owner's environment serves like any other.
237 const images = pending.flatMap((message) => message.attachments ?? []).filter(isImageAttachment);
238 const imageUrls = useAssetUrls(
239 threadRef.environmentId,
240 images.map((image) => ({ _tag: "attachment" as const, attachmentId: image.id })),
241 );
242 const imageUrlById = new Map(
243 images.flatMap((image, index) => {
244 const url = imageUrls[index];
245 return url ? [[image.id, url] as const] : [];
246 }),
247 );
248 if (share === null || pending.length === 0) return null;
249 const guestName = share.guestName ?? "Guest";
250 const openImage = (attachment: ChatAttachment) => {
251 const preview = buildExpandedImagePreview(
252 images.map((image) => ({ ...image, previewUrl: imageUrlById.get(image.id) ?? "" })),
253 attachment.id,
254 );
255 if (preview) onImageExpand(preview);
256 };
257
258 const resolve = async (guestMessageId: GuestMessageId, decision: "send" | "dismiss") => {
259 setBusyIds((ids) => new Set(ids).add(guestMessageId));
260 await resolveGuestMessage({
261 environmentId: threadRef.environmentId,
262 input: { threadId: threadRef.threadId, guestMessageId, decision },
263 });
264 setBusyIds((ids) => {
265 const next = new Set(ids);
266 next.delete(guestMessageId);
267 return next;
268 });
269 };
270
271 return (
272 <ol
273 className="chat-content-lane flex flex-col gap-4 pb-4"
274 aria-label={`${pending.length} guest message${pending.length === 1 ? "" : "s"} waiting`}
275 aria-live="polite"
276 >
277 {pending.map((message) => {
278 const busy = busyIds.has(message.id);
279 return (
280 <li key={message.id} className="flex flex-col items-end gap-1">
281 <GuestMessageName name={guestName} />
282 <div
283 className={cn(
284 "flex min-w-0 max-w-[80%] flex-col gap-2 rounded-2xl p-3 text-foreground",
285 guestBubbleClassName(true),
286 )}
287 >
288 <GuestMessageAttachments
289 attachments={message.attachments ?? []}
290 imageUrl={(attachment) => imageUrlById.get(attachment.id)}
291 onOpenImage={openImage}
292 onOpenFile={onFileOpen}
293 />
294 {message.text ? (
295 <p className="text-sm leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]">
296 {message.text}
297 </p>
298 ) : null}
299 </div>
300 {canOperate ? (
301 <div className="flex items-center gap-1 pe-1">
302 <Button
303 size="xs"
304 variant="ghost-muted"
305 disabled={busy}
306 aria-label={`Dismiss message from ${guestName}`}
307 onClick={() => void resolve(message.id, "dismiss")}
308 >
309 Dismiss
310 </Button>
311 <Button
312 size="xs"
313 disabled={busy}
314 aria-label={`Send message from ${guestName}`}
315 onClick={() => void resolve(message.id, "send")}
316 >
317 Send
318 </Button>
319 </div>
320 ) : null}
321 </li>
322 );
323 })}
324 </ol>
325 );
326}