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