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