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

ChatHeader.tsx

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