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