Open History to see the last commit
1import { type EnvironmentId, type ThreadId } from "@t3tools/contracts";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { ChevronDownIcon } from "lucide-react";
9import {
10 memo,
11 useCallback,
12 useEffect,
13 useMemo,
14 useRef,
15 useState,
16 type KeyboardEvent as ReactKeyboardEvent,
17 type MouseEvent as ReactMouseEvent,
18} from "react";
19import { isTrailingDoubleClick } from "../Sidebar.logic";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21import { toastManager } from "../ui/toast";
22import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
23import { readLocalApi } from "~/localApi";
24import { threadEnvironment } from "../../state/threads";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { ProjectFavicon } from "../ProjectFavicon";
27import {
28 WorkspaceBreadcrumb,
29 WorkspaceBreadcrumbItem,
30 WorkspaceBreadcrumbSeparator,
31 WorkspaceBreadcrumbText,
32} from "../WorkspaceBreadcrumb";
33import { cn } from "~/lib/utils";
34
35interface ChatHeaderProps {
36 activeThreadEnvironmentId: EnvironmentId;
37 activeThreadId: ThreadId;
38 activeThreadTitle: string;
39 /** Drafts have no server thread yet, so the title carries no action menu. */
40 isServerThread: boolean;
41 activeProject: EnvironmentProject | null;
42 rightPanelOpen: boolean;
43 onNewThreadInProject: () => void;
44 onOpenProjectSettings?: (() => void) | undefined;
45}
46
47/**
48 * Rename commit rule shared with the sidebar's inline rename: trim, reject
49 * empty (the caller toasts), and skip the mutation when nothing changed.
50 */
51export function resolveRenameCommit(input: {
52 readonly title: string;
53 readonly originalTitle: string;
54}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
55 const trimmed = input.title.trim();
56 if (trimmed.length === 0) return { action: "reject-empty" };
57 if (trimmed === input.originalTitle) return { action: "noop" };
58 return { action: "commit", title: trimmed };
59}
60
61// How long a click on the thread title waits before opening the action menu,
62// so a double-click-to-rename can cancel it first. Only the native desktop
63// menu needs this: it swallows input while open, so the wait must cover the
64// OS double-click interval. The browser fallback menu keeps seeing DOM
65// events (the second click dismisses it and dblclick still fires), so it
66// opens immediately.
67const TITLE_MENU_OPEN_DELAY_MS = 500;
68export const ChatHeader = memo(function ChatHeader({
69 activeThreadEnvironmentId,
70 activeThreadId,
71 activeThreadTitle,
72 isServerThread,
73 activeProject,
74 rightPanelOpen,
75 onNewThreadInProject,
76 onOpenProjectSettings,
77}: ChatHeaderProps) {
78 const activeProjectName = activeProject?.title;
79 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
80 const activeThreadRef = useMemo(
81 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
82 [activeThreadEnvironmentId, activeThreadId],
83 );
84 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
85 reportFailure: false,
86 });
87 // Inline rename, keyed by thread: navigating away drops an in-progress
88 // rename instead of committing stale text. Cleared on thread change (not
89 // just hidden) so returning to the thread doesn't revive the old draft.
90 const [renaming, setRenaming] = useState<{
91 threadId: ThreadId;
92 environmentId: EnvironmentId;
93 title: string;
94 } | null>(null);
95 if (
96 renaming !== null &&
97 (renaming.threadId !== activeThreadId || renaming.environmentId !== activeThreadEnvironmentId)
98 ) {
99 setRenaming(null);
100 }
101 const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
102 const renameCommittedRef = useRef(false);
103 const startRename = useCallback(() => {
104 renameCommittedRef.current = false;
105 setRenaming({
106 threadId: activeThreadId,
107 environmentId: activeThreadEnvironmentId,
108 title: activeThreadTitle,
109 });
110 }, [activeThreadEnvironmentId, activeThreadId, activeThreadTitle]);
111 const commitRename = useCallback(
112 (title: string) => {
113 setRenaming(null);
114 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
115 if (resolution.action === "reject-empty") {
116 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
117 return;
118 }
119 if (resolution.action === "noop") return;
120 void updateThreadMetadata({
121 environmentId: activeThreadEnvironmentId,
122 input: { threadId: activeThreadId, title: resolution.title },
123 }).then((result) => {
124 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
125 const error = squashAtomCommandFailure(result);
126 toastManager.add({
127 type: "error",
128 title: "Failed to rename thread",
129 description: error instanceof Error ? error.message : "An error occurred.",
130 });
131 }
132 });
133 },
134 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
135 );
136 const { openMenu, closeMenu } = useThreadActionMenu({
137 threadRef: isServerThread ? activeThreadRef : null,
138 projectCwd: activeProjectCwd,
139 onStartRename: startRename,
140 });
141 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
142 const titleMenuTimerRef = useRef<number | null>(null);
143 const cancelPendingTitleMenu = useCallback(() => {
144 if (titleMenuTimerRef.current === null) return;
145 clearTimeout(titleMenuTimerRef.current);
146 titleMenuTimerRef.current = null;
147 }, []);
148 // Drop a pending menu-open when the thread changes or the header unmounts,
149 // so it can never fire for a thread the user already left.
150 useEffect(
151 () => () => {
152 cancelPendingTitleMenu();
153 },
154 [activeThreadEnvironmentId, activeThreadId, cancelPendingTitleMenu],
155 );
156 const openTitleMenuNow = useCallback(() => {
157 cancelPendingTitleMenu();
158 const rect = titleButtonRef.current?.getBoundingClientRect();
159 if (!rect) return;
160 openMenu({ x: rect.left, y: rect.bottom + 4 });
161 }, [cancelPendingTitleMenu, openMenu]);
162 const openMenuFromTitle = useCallback(
163 (event: ReactMouseEvent<HTMLButtonElement>) => {
164 // The trailing click of a double-click belongs to rename, not the menu.
165 if (isTrailingDoubleClick(event.detail)) return;
166 // Keyboard activation and the explicit chevron affordance can never be
167 // the first half of a double-click, so they open without waiting.
168 const clickedChevron =
169 (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null;
170 if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) {
171 openTitleMenuNow();
172 return;
173 }
174 // Stay pending long enough for dblclick to cancel the open before the
175 // native menu appears and swallows the second click.
176 cancelPendingTitleMenu();
177 titleMenuTimerRef.current = window.setTimeout(() => {
178 titleMenuTimerRef.current = null;
179 openTitleMenuNow();
180 }, TITLE_MENU_OPEN_DELAY_MS);
181 },
182 [cancelPendingTitleMenu, openTitleMenuNow],
183 );
184 const handleTitleDoubleClick = useCallback(
185 (event: ReactMouseEvent) => {
186 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
187 // The chevron is the explicit menu affordance; only the title text renames.
188 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
189 cancelPendingTitleMenu();
190 closeMenu();
191 startRename();
192 },
193 [cancelPendingTitleMenu, closeMenu, startRename],
194 );
195 const handleHeaderContextMenu = useCallback(
196 (event: ReactMouseEvent) => {
197 if (renamingTitle !== null) return;
198 if (!isServerThread && onOpenProjectSettings === undefined) return;
199 cancelPendingTitleMenu();
200 event.preventDefault();
201 if (!isServerThread) {
202 const api = readLocalApi();
203 if (!api) return;
204 void api.contextMenu
205 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
206 x: event.clientX,
207 y: event.clientY,
208 })
209 .then((action) => {
210 if (action === "project-settings") onOpenProjectSettings?.();
211 });
212 return;
213 }
214 openMenu({ x: event.clientX, y: event.clientY });
215 },
216 [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle],
217 );
218 const handleRenameKeyDown = useCallback(
219 (event: ReactKeyboardEvent<HTMLInputElement>) => {
220 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
221 if (event.key === "Enter") {
222 renameCommittedRef.current = true;
223 commitRename(event.currentTarget.value);
224 } else if (event.key === "Escape") {
225 renameCommittedRef.current = true;
226 setRenaming(null);
227 }
228 },
229 [commitRename],
230 );
231 return (
232 <div
233 className={cn(
234 "flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
235 rightPanelOpen ? "pr-10" : "pr-24",
236 )}
237 onContextMenu={handleHeaderContextMenu}
238 >
239 <WorkspaceBreadcrumb
240 ariaLabel="Thread breadcrumb"
241 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
242 >
243 {/* The project always leads the header: knowing which project a
244 thread lives in is priority zero, and the thread title alone
245 doesn't answer it. */}
246 {activeProject ? (
247 <>
248 <WorkspaceBreadcrumbItem className="shrink">
249 <Tooltip>
250 <TooltipTrigger
251 render={
252 <button
253 type="button"
254 aria-label={`New thread in ${activeProjectName}`}
255 onClick={onNewThreadInProject}
256 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-ring"
257 />
258 }
259 >
260 <ProjectFavicon project={activeProject} className="size-3.5" />
261 <WorkspaceBreadcrumbText className="max-w-40">
262 {activeProjectName}
263 </WorkspaceBreadcrumbText>
264 </TooltipTrigger>
265 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
266 </Tooltip>
267 </WorkspaceBreadcrumbItem>
268 <WorkspaceBreadcrumbSeparator>
269 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
270 </WorkspaceBreadcrumbSeparator>
271 </>
272 ) : null}
273 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
274 {renamingTitle !== null ? (
275 <input
276 autoFocus
277 aria-label="Thread title"
278 className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-ring/50 focus:ring-ring"
279 defaultValue={renamingTitle}
280 onBlur={(event) => {
281 if (renameCommittedRef.current) return;
282 // Focus landing on a navigation button means the rename was
283 // abandoned — discard it rather than persisting a half-draft.
284 if (
285 event.relatedTarget instanceof HTMLElement &&
286 event.relatedTarget.closest("button")
287 ) {
288 setRenaming(null);
289 return;
290 }
291 commitRename(event.currentTarget.value);
292 }}
293 onFocus={(event) => event.currentTarget.select()}
294 onKeyDown={handleRenameKeyDown}
295 />
296 ) : isServerThread ? (
297 <Tooltip>
298 <TooltipTrigger
299 render={
300 <button
301 ref={titleButtonRef}
302 type="button"
303 aria-label={`Thread actions for ${activeThreadTitle}`}
304 aria-haspopup="menu"
305 onClick={openMenuFromTitle}
306 onDoubleClick={handleTitleDoubleClick}
307 onBlur={cancelPendingTitleMenu}
308 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-ring"
309 />
310 }
311 >
312 <h2 className="min-w-0">
313 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
314 </h2>
315 <ChevronDownIcon
316 aria-hidden
317 data-thread-title-chevron
318 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"
319 />
320 </TooltipTrigger>
321 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
322 </Tooltip>
323 ) : (
324 <Tooltip>
325 <TooltipTrigger
326 render={<h2 aria-label={activeThreadTitle} className="min-w-0 flex-1" />}
327 >
328 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
329 </TooltipTrigger>
330 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
331 </Tooltip>
332 )}
333 </WorkspaceBreadcrumbItem>
334 </WorkspaceBreadcrumb>
335 </div>
336 );
337});