Open History to see the last commit
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;
59}
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 };
69}
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({ title, originalTitle: activeThreadTitle });
179 if (resolution.action === "reject-empty") {
180 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
181 return;
182 }
183 if (resolution.action === "noop") return;
184 void updateThreadMetadata({
185 environmentId: activeThreadEnvironmentId,
186 input: { threadId: activeThreadId, title: resolution.title },
187 }).then((result) => {
188 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
189 const error = squashAtomCommandFailure(result);
190 toastManager.add({
191 type: "error",
192 title: "Failed to rename thread",
193 description: error instanceof Error ? error.message : "An error occurred.",
194 });
195 }
196 });
197 };
198 const { openMenu, closeMenu } = useThreadActionMenu({
199 threadRef: isServerThread ? activeThreadRef : null,
200 projectCwd: activeProjectCwd,
201 onStartRename: startRename,
202 onFind: onFindInThread,
203 canShareWithGuest,
204 });
205 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
206 const titleMenuTimerRef = useRef<number | null>(null);
207 const cancelPendingTitleMenu = () => {
208 if (titleMenuTimerRef.current === null) return;
209 clearTimeout(titleMenuTimerRef.current);
210 titleMenuTimerRef.current = null;
211 };
212 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the pending title-menu timer when the thread switches or the header unmounts
213 useEffect(
214 () => () => {
215 if (titleMenuTimerRef.current === null) return;
216 clearTimeout(titleMenuTimerRef.current);
217 titleMenuTimerRef.current = null;
218 },
219 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A pending title menu belongs to the thread that was clicked, so switching threads drops it.
220 [activeThreadEnvironmentId, activeThreadId],
221 );
222 const openTitleMenuNow = () => {
223 cancelPendingTitleMenu();
224 const rect = titleButtonRef.current?.getBoundingClientRect();
225 if (!rect) return;
226 openMenu({ x: rect.left, y: rect.bottom + 4 });
227 };
228 const openMenuFromTitle = (event: ReactMouseEvent<HTMLButtonElement>) => {
229 if (isTrailingDoubleClick(event.detail)) return;
230 const clickedChevron =
231 (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null;
232 if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) {
233 openTitleMenuNow();
234 return;
235 }
236 cancelPendingTitleMenu();
237 titleMenuTimerRef.current = window.setTimeout(() => {
238 titleMenuTimerRef.current = null;
239 openTitleMenuNow();
240 }, TITLE_MENU_OPEN_DELAY_MS);
241 };
242 const handleTitleDoubleClick = (event: ReactMouseEvent) => {
243 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
244 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
245 cancelPendingTitleMenu();
246 closeMenu();
247 startRename();
248 };
249 const handleHeaderContextMenu = (event: ReactMouseEvent) => {
250 if (renamingTitle !== null) return;
251 if (!isServerThread && onOpenProjectSettings === undefined) return;
252 cancelPendingTitleMenu();
253 event.preventDefault();
254 if (!isServerThread) {
255 const api = readLocalApi();
256 if (!api) return;
257 void api.contextMenu
258 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
259 x: event.clientX,
260 y: event.clientY,
261 })
262 .then((action) => {
263 if (action === "project-settings") onOpenProjectSettings?.();
264 });
265 return;
266 }
267 openMenu({ x: event.clientX, y: event.clientY });
268 };
269 const handleRenameKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
270 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
271 if (event.key === "Enter") {
272 renameCommittedRef.current = true;
273 commitRename(event.currentTarget.value);
274 } else if (event.key === "Escape") {
275 renameCommittedRef.current = true;
276 setRenaming(null);
277 }
278 };
279 return (
280 <div
281 ref={breadcrumbContainerRef}
282 className={cn(
283 "flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
284 rightPanelOpen ? "pr-10" : "pr-24",
285 )}
286 onContextMenu={handleHeaderContextMenu}
287 >
288 <WorkspaceBreadcrumb
289 ariaLabel="Thread breadcrumb"
290 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
291 >
292 {activeProject ? (
293 <>
294 <WorkspaceBreadcrumbItem className="shrink">
295 <Tooltip>
296 <TooltipTrigger
297 render={
298 <button
299 type="button"
300 aria-label={`New thread in ${activeProjectName}`}
301 onClick={onNewThreadInProject}
302 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"
303 />
304 }
305 >
306 <ProjectFavicon project={activeProject} className="size-3.5" />
307 <WorkspaceBreadcrumbText className="max-w-40">
308 {activeProjectName}
309 </WorkspaceBreadcrumbText>
310 </TooltipTrigger>
311 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
312 </Tooltip>
313 </WorkspaceBreadcrumbItem>
314 <WorkspaceBreadcrumbSeparator>
315 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
316 </WorkspaceBreadcrumbSeparator>
317 </>
318 ) : null}
319 {parentThreadLink ? (
320 <>
321 <WorkspaceBreadcrumbItem>
322 <Tooltip>
323 <TooltipTrigger
324 render={
325 <button
326 type="button"
327 aria-label={`Open parent thread: ${parentThreadLink.title}`}
328 onClick={() => onOpenThread(parentThreadLink.threadId)}
329 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"
330 />
331 }
332 >
333 <WorkspaceBreadcrumbText
334 aria-hidden
335 className={collapseParentTitle ? "w-0" : undefined}
336 >
337 {parentThreadLink.title}
338 </WorkspaceBreadcrumbText>
339 {collapseParentTitle ? (
340 <span aria-hidden data-parent-breadcrumb-ellipsis>
341 ...
342 </span>
343 ) : null}
344 </TooltipTrigger>
345 <TooltipPopup side="top">{parentThreadLink.title}</TooltipPopup>
346 </Tooltip>
347 </WorkspaceBreadcrumbItem>
348 <WorkspaceBreadcrumbSeparator>
349 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
350 </WorkspaceBreadcrumbSeparator>
351 </>
352 ) : null}
353 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
354 {renamingTitle !== null ? (
355 <input
356 autoFocus
357 dir="auto"
358 aria-label="Thread title"
359 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"
360 defaultValue={renamingTitle}
361 onBlur={(event) => {
362 if (renameCommittedRef.current) return;
363 if (
364 event.relatedTarget instanceof HTMLElement &&
365 event.relatedTarget.closest("button")
366 ) {
367 setRenaming(null);
368 return;
369 }
370 commitRename(event.currentTarget.value);
371 }}
372 onFocus={(event) => event.currentTarget.select()}
373 onKeyDown={handleRenameKeyDown}
374 />
375 ) : isServerThread ? (
376 <Tooltip>
377 <TooltipTrigger
378 render={
379 <button
380 ref={titleButtonRef}
381 type="button"
382 aria-label={`Thread actions for ${activeThreadTitle}`}
383 aria-haspopup="menu"
384 onClick={openMenuFromTitle}
385 onDoubleClick={canOperateThread ? handleTitleDoubleClick : undefined}
386 onBlur={cancelPendingTitleMenu}
387 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"
388 />
389 }
390 >
391 <h2 className="min-w-0" dir={textDirection(activeThreadTitle)}>
392 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
393 </h2>
394 <ChevronDownIcon
395 aria-hidden
396 data-thread-title-chevron
397 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"
398 />
399 </TooltipTrigger>
400 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
401 </Tooltip>
402 ) : (
403 <Tooltip>
404 <TooltipTrigger
405 render={
406 <h2
407 aria-label={activeThreadTitle}
408 className="min-w-0 flex-1"
409 dir={textDirection(activeThreadTitle)}
410 />
411 }
412 >
413 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
414 </TooltipTrigger>
415 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
416 </Tooltip>
417 )}
418 {renamingTitle === null && activeThreadLinkOrigin ? (
419 <Tooltip>
420 <TooltipTrigger render={<Badge variant="info" size="sm" />}>
421 From {activeThreadLinkOrigin}
422 </TooltipTrigger>
423 <TooltipPopup side="top">
424 Started by an agent on {activeThreadLinkOrigin} through a linked environment.
425 </TooltipPopup>
426 </Tooltip>
427 ) : null}
428 </WorkspaceBreadcrumbItem>
429 </WorkspaceBreadcrumb>
430 {isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
431 </div>
432 );
433});