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

ChatHeader.tsx

399 lines15.7 KB

1import {
2 AuthOrchestrationOperateScope,
3 type EnvironmentId,
4 type ScopedThreadRef,
5 type ThreadId,
6} from "@t3tools/contracts";
7import { scopeThreadRef } from "@t3tools/client-runtime/environment";
8import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import { ChevronDownIcon } from "lucide-react";
14import {
15 memo,
16 useEffect,
17 useRef,
18 useState,
19 type KeyboardEvent as ReactKeyboardEvent,
20 type MouseEvent as ReactMouseEvent,
21} from "react";
22import { isTrailingDoubleClick } from "../Sidebar.logic";
23import { Badge } from "../ui/badge";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import { toastManager } from "../ui/toast";
26import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
27import { readLocalApi } from "~/localApi";
28import { threadEnvironment } from "../../state/threads";
29import { canShareWithGuestAtom } from "./guestShareAvailability";
30import { useAtomValue } from "@effect/atom-react";
31import { useOrchestrationCommand } from "../../state/use-orchestration-command";
32import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
33import { ProjectFavicon } from "../ProjectFavicon";
34import {
35 WorkspaceBreadcrumb,
36 WorkspaceBreadcrumbItem,
37 WorkspaceBreadcrumbSeparator,
38 WorkspaceBreadcrumbText,
39} from "../WorkspaceBreadcrumb";
40import { observeResize } from "~/lib/observeResize";
41import { cn } from "~/lib/utils";
42import { textDirection } from "~/textDirection";
43import { useClientSettings } from "../../hooks/useSettings";
44import { GuestShareIndicator } from "./GuestShareControls";
45​
46interface ChatHeaderProps {
47 activeThreadEnvironmentId: EnvironmentId;
48 activeThreadId: ThreadId;
49 activeThreadTitle: string;
50 activeThreadLinkOrigin?: string | null | undefined;
51 isServerThread: boolean;
52 activeProject: EnvironmentProject | null;
53 parentThreadLink: { threadId: ThreadId; title: string } | null;
54 onOpenThread: (threadId: ThreadId) => void;
55 rightPanelOpen: boolean;
56 onNewThreadInProject: () => void;
57 onOpenProjectSettings?: (() => void) | undefined;
58 onFindInThread?: ((threadRef: ScopedThreadRef) => void) | undefined;
60​
61function resolveRenameCommit(input: {
62 readonly title: string;
63 readonly originalTitle: string;
64}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
65 const trimmed = input.title.trim();
66 if (trimmed.length === 0) return { action: "reject-empty" };
67 if (trimmed === input.originalTitle) return { action: "noop" };
68 return { action: "commit", title: trimmed };
70​
71export const ChatHeader = memo(function ChatHeader({
72 activeThreadEnvironmentId,
73 activeThreadId,
74 activeThreadTitle,
75 activeThreadLinkOrigin,
76 isServerThread,
77 activeProject,
78 parentThreadLink,
79 onOpenThread,
80 rightPanelOpen,
81 onNewThreadInProject,
82 onOpenProjectSettings,
83 onFindInThread,
84}: ChatHeaderProps) {
85 const activeProjectName = activeProject?.isScratch ? "No project" : activeProject?.title;
86 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
87 const interfaceFont = useClientSettings((settings) => settings.fontFamilySans);
88 const breadcrumbContainerRef = useRef<HTMLDivElement>(null);
89 const [collapseParentTitle, setCollapseParentTitle] = useState(false);
90 const activeThreadRef = scopeThreadRef(activeThreadEnvironmentId, activeThreadId);
91 const canOperateThread = useEnvironmentScope(
92 activeThreadEnvironmentId,
93 AuthOrchestrationOperateScope,
94 );
95 const canShareWithGuest = useAtomValue(canShareWithGuestAtom(activeThreadEnvironmentId));
96 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
97 reportFailure: false,
98 });
99 const [renaming, setRenaming] = useState<{
100 threadId: ThreadId;
101 environmentId: EnvironmentId;
102 title: string;
103 } | null>(null);
104 if (
105 renaming !== null &&
106 (renaming.threadId !== activeThreadId ||
107 renaming.environmentId !== activeThreadEnvironmentId ||
108 !canOperateThread)
109 ) {
110 setRenaming(null);
111 }
112 const renamingTitle =
113 canOperateThread &&
114 renaming?.threadId === activeThreadId &&
115 renaming.environmentId === activeThreadEnvironmentId
116 ? renaming.title
117 : null;
118 const isRenamingTitle = renamingTitle !== null;
119 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the breadcrumb list DOM via ResizeObserver, a frame and font loads to collapse the parent title
120 useEffect(() => {
121 const list = breadcrumbContainerRef.current?.querySelector("ol");
122 if (!list || !parentThreadLink) return;
123 const measure = () => {
124 const gap = Number.parseFloat(getComputedStyle(list).columnGap) || 0;
125 const width = Array.from(list.children).reduce(
126 (total, item) => {
127 const label = item.querySelector('[data-slot="workspace-breadcrumb-text"]');
128 const ellipsis = item.querySelector("[data-parent-breadcrumb-ellipsis]");
129 return (
130 total +
131 (item.firstElementChild?.getBoundingClientRect().width ?? 0) +
132 (label && getComputedStyle(label).maxWidth === "none"
133 ? label.scrollWidth - label.clientWidth
134 : 0) -
135 (ellipsis?.getBoundingClientRect().width ?? 0)
136 );
137 },
138 gap * (list.children.length - 1),
139 );
140 setCollapseParentTitle(width > list.clientWidth);
141 };
142 measure();
143 const frame = requestAnimationFrame(measure);
144 document.fonts.addEventListener("loadingdone", measure);
145 const stopObserving = observeResize(list, measure);
146 return () => {
147 cancelAnimationFrame(frame);
148 document.fonts.removeEventListener("loadingdone", measure);
149 stopObserving();
150 };
151 }, [
152 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Title, font and rename changes resize the breadcrumb text without resizing the list, so it re-measures.
153 activeProjectName,
154 activeThreadTitle,
155 parentThreadLink,
156 interfaceFont,
157 isRenamingTitle,
158 ]);
159 const renameCommittedRef = useRef(false);
160 const startRename = () => {
161 if (
162 !isServerThread ||
163 !readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)
164 )
165 return;
166 renameCommittedRef.current = false;
167 setRenaming({
168 environmentId: activeThreadEnvironmentId,
169 threadId: activeThreadId,
170 title: activeThreadTitle,
171 });
172 };
173 const commitRename = (title: string) => {
174 setRenaming(null);
175 if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return;
176 const resolution = resolveRenameCommit({
177 title,
178 originalTitle: renamingTitle ?? activeThreadTitle,
179 });
180 if (resolution.action === "reject-empty") {
181 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
182 return;
183 }
184 if (resolution.action === "noop") return;
185 void updateThreadMetadata({
186 environmentId: activeThreadEnvironmentId,
187 input: { threadId: activeThreadId, title: resolution.title },
188 }).then((result) => {
189 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
190 const error = squashAtomCommandFailure(result);
191 toastManager.add({
192 type: "error",
193 title: "Failed to rename thread",
194 description: error instanceof Error ? error.message : "An error occurred.",
195 });
196 }
197 });
198 };
199 const { openMenu, closeMenu } = useThreadActionMenu({
200 threadRef: isServerThread ? activeThreadRef : null,
201 projectCwd: activeProjectCwd,
202 onStartRename: startRename,
203 onFind: onFindInThread,
204 canShareWithGuest,
205 });
206 const openMenuFromTitle = (event: ReactMouseEvent<HTMLButtonElement>) => {
207 if (isTrailingDoubleClick(event.detail)) return;
208 const rect = event.currentTarget.getBoundingClientRect();
209 openMenu({ x: rect.left, y: rect.bottom + 4 });
210 };
211 // A native menu takes the second click, so only the in-page menu lets a double-click reach here.
212 const handleTitleDoubleClick = (event: ReactMouseEvent) => {
213 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
214 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
215 closeMenu();
216 startRename();
217 };
218 const handleHeaderContextMenu = (event: ReactMouseEvent) => {
219 if (renamingTitle !== null) return;
220 if (!isServerThread && onOpenProjectSettings === undefined) return;
221 event.preventDefault();
222 if (!isServerThread) {
223 const api = readLocalApi();
224 if (!api) return;
225 void api.contextMenu
226 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
227 x: event.clientX,
228 y: event.clientY,
229 })
230 .then((action) => {
231 if (action === "project-settings") onOpenProjectSettings?.();
232 });
233 return;
234 }
235 openMenu({ x: event.clientX, y: event.clientY });
236 };
237 const handleRenameKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
238 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
239 if (event.key === "Enter") {
240 renameCommittedRef.current = true;
241 commitRename(event.currentTarget.value);
242 } else if (event.key === "Escape") {
243 renameCommittedRef.current = true;
244 setRenaming(null);
245 }
246 };
247 return (
248 <div
249 ref={breadcrumbContainerRef}
250 className={cn(
251 "flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
252 rightPanelOpen ? "pr-10" : "pr-24",
253 )}
254 onContextMenu={handleHeaderContextMenu}
255 >
256 <WorkspaceBreadcrumb
257 ariaLabel="Thread breadcrumb"
258 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
259 >
260 {activeProject ? (
261 <>
262 <WorkspaceBreadcrumbItem className="shrink">
263 <Tooltip>
264 <TooltipTrigger
265 render={
266 <button
267 type="button"
268 aria-label={`New thread in ${activeProjectName}`}
269 onClick={onNewThreadInProject}
270 className="inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
271 />
272 }
273 >
274 <ProjectFavicon project={activeProject} className="size-3.5" />
275 <WorkspaceBreadcrumbText className="max-w-40">
276 {activeProjectName}
277 </WorkspaceBreadcrumbText>
278 </TooltipTrigger>
279 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
280 </Tooltip>
281 </WorkspaceBreadcrumbItem>
282 <WorkspaceBreadcrumbSeparator>
283 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
284 </WorkspaceBreadcrumbSeparator>
285 </>
286 ) : null}
287 {parentThreadLink ? (
288 <>
289 <WorkspaceBreadcrumbItem>
290 <Tooltip>
291 <TooltipTrigger
292 render={
293 <button
294 type="button"
295 aria-label={`Open parent thread: ${parentThreadLink.title}`}
296 onClick={() => onOpenThread(parentThreadLink.threadId)}
297 className="inline-flex min-w-0 max-w-full cursor-pointer items-center rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
298 />
299 }
300 >
301 <WorkspaceBreadcrumbText
302 aria-hidden
303 className={collapseParentTitle ? "w-0" : undefined}
304 >
305 {parentThreadLink.title}
306 </WorkspaceBreadcrumbText>
307 {collapseParentTitle ? (
308 <span aria-hidden data-parent-breadcrumb-ellipsis>
309 ...
310 </span>
311 ) : null}
312 </TooltipTrigger>
313 <TooltipPopup side="top">{parentThreadLink.title}</TooltipPopup>
314 </Tooltip>
315 </WorkspaceBreadcrumbItem>
316 <WorkspaceBreadcrumbSeparator>
317 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
318 </WorkspaceBreadcrumbSeparator>
319 </>
320 ) : null}
321 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
322 {renamingTitle !== null ? (
323 <input
324 autoFocus
325 dir="auto"
326 aria-label="Thread title"
327 className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-inset ring-ring/50 focus:ring-ring"
328 defaultValue={renamingTitle}
329 onBlur={(event) => {
330 if (renameCommittedRef.current) return;
331 if (
332 event.relatedTarget instanceof HTMLElement &&
333 event.relatedTarget.closest("button")
334 ) {
335 setRenaming(null);
336 return;
337 }
338 commitRename(event.currentTarget.value);
339 }}
340 onFocus={(event) => event.currentTarget.select()}
341 onKeyDown={handleRenameKeyDown}
342 />
343 ) : isServerThread ? (
344 <Tooltip>
345 <TooltipTrigger
346 render={
347 <button
348 type="button"
349 aria-label={`Thread actions for ${activeThreadTitle}`}
350 aria-haspopup="menu"
351 onClick={openMenuFromTitle}
352 onDoubleClick={canOperateThread ? handleTitleDoubleClick : undefined}
353 className="group/thread-title inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
354 />
355 }
356 >
357 <h2 className="min-w-0" dir={textDirection(activeThreadTitle)}>
358 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
359 </h2>
360 <ChevronDownIcon
361 aria-hidden
362 data-thread-title-chevron
363 className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
364 />
365 </TooltipTrigger>
366 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
367 </Tooltip>
368 ) : (
369 <Tooltip>
370 <TooltipTrigger
371 render={
372 <h2
373 aria-label={activeThreadTitle}
374 className="min-w-0 flex-1"
375 dir={textDirection(activeThreadTitle)}
376 />
377 }
378 >
379 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
380 </TooltipTrigger>
381 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
382 </Tooltip>
383 )}
384 {renamingTitle === null && activeThreadLinkOrigin ? (
385 <Tooltip>
386 <TooltipTrigger render={<Badge variant="info" size="sm" />}>
387 From {activeThreadLinkOrigin}
388 </TooltipTrigger>
389 <TooltipPopup side="top">
390 Started by an agent on {activeThreadLinkOrigin} through a linked environment.
391 </TooltipPopup>
392 </Tooltip>
393 ) : null}
394 </WorkspaceBreadcrumbItem>
395 </WorkspaceBreadcrumb>
396 {isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
397 </div>
398 );
399});