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