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

ChatHeader.tsx

427 lines16.8 KB

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