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