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