Open History to see the last commit
1import {
2 type EnvironmentId,
3 type EditorId,
4 type ProjectScript,
5 type ResolvedKeybindingsConfig,
6 type ThreadId,
7} from "@t3tools/contracts";
8import { scopeThreadRef } from "@t3tools/client-runtime/environment";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import { ChevronDownIcon } from "lucide-react";
14import {
15 memo,
16 useCallback,
17 useEffect,
18 useMemo,
19 useRef,
20 useState,
21 type KeyboardEvent as ReactKeyboardEvent,
22 type MouseEvent as ReactMouseEvent,
23} from "react";
24import GitActionsControl from "../GitActionsControl";
25import { isTrailingDoubleClick } from "../Sidebar.logic";
26import { type DraftId } from "~/composerDraftStore";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
28import { toastManager } from "../ui/toast";
29import ProjectScriptsControl, {
30 type NewProjectScriptInput,
31 type ProjectScriptActionResult,
32} from "../ProjectScriptsControl";
33import { OpenInPicker } from "./OpenInPicker";
34import { useRemoteOpenState, type RemoteOpenMode } from "../../remoteOpen";
35import { usePrimaryEnvironmentId } from "../../state/environments";
36import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
37import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
38import { readLocalApi } from "~/localApi";
39import { threadEnvironment } from "../../state/threads";
40import { useAtomCommand } from "../../state/use-atom-command";
41import { observeResponsiveBreakpointFade, usePanelAnimationSettings } from "../../panelAnimations";
42import { ProjectFavicon } from "../ProjectFavicon";
43import {
44 WorkspaceBreadcrumb,
45 WorkspaceBreadcrumbItem,
46 WorkspaceBreadcrumbSeparator,
47} from "../WorkspaceBreadcrumb";
48import { cn } from "~/lib/utils";
49
50interface ChatHeaderProps {
51 activeThreadEnvironmentId: EnvironmentId;
52 activeThreadId: ThreadId;
53 draftId?: DraftId;
54 activeThreadTitle: string;
55 /** Drafts have no server thread yet, so the title carries no action menu. */
56 isServerThread: boolean;
57 activeProjectName: string | undefined;
58 activeProjectCwd: string | null;
59 activeProjectFaviconPath: string | null;
60 activeProjectIcon: import("@t3tools/contracts").ProjectIconOverride | null;
61 openInCwd: string | null;
62 activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
63 preferredScriptId: string | null;
64 keybindings: ResolvedKeybindingsConfig;
65 availableEditors: ReadonlyArray<EditorId>;
66 rightPanelOpen: boolean;
67 gitCwd: string | null;
68 readonly onOpenPullRequest?: ((number: number) => void) | undefined;
69 onNewThreadInProject: () => void;
70 onOpenProjectSettings?: (() => void) | undefined;
71 onRunProjectScript: (script: ProjectScript) => void;
72 onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
73 onUpdateProjectScript: (
74 scriptId: string,
75 input: NewProjectScriptInput,
76 ) => Promise<ProjectScriptActionResult>;
77 onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
78}
79
80/**
81 * Rename commit rule shared with the sidebar's inline rename: trim, reject
82 * empty (the caller toasts), and skip the mutation when nothing changed.
83 */
84export function resolveRenameCommit(input: {
85 readonly title: string;
86 readonly originalTitle: string;
87}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
88 const trimmed = input.title.trim();
89 if (trimmed.length === 0) return { action: "reject-empty" };
90 if (trimmed === input.originalTitle) return { action: "noop" };
91 return { action: "commit", title: trimmed };
92}
93
94// How long a click on the thread title waits before opening the action menu,
95// so a double-click-to-rename can cancel it first. Only the native desktop
96// menu needs this: it swallows input while open, so the wait must cover the
97// OS double-click interval. The browser fallback menu keeps seeing DOM
98// events (the second click dismisses it and dblclick still fires), so it
99// opens immediately.
100const TITLE_MENU_OPEN_DELAY_MS = 500;
101// Matches the @3xl/header-actions container breakpoint owned by this header.
102const HEADER_ACTIONS_EXPANDED_BREAKPOINT_REM = 48;
103
104export function shouldShowOpenInPicker(input: {
105 readonly activeProjectName: string | undefined;
106 readonly activeThreadEnvironmentId: EnvironmentId;
107 readonly primaryEnvironmentId: EnvironmentId | null;
108 readonly remoteOpenMode: RemoteOpenMode;
109}): boolean {
110 if (!input.activeProjectName) return false;
111 if (
112 input.primaryEnvironmentId !== null &&
113 input.activeThreadEnvironmentId === input.primaryEnvironmentId
114 ) {
115 return true;
116 }
117 // Remote environments get the picker in deep-link mode (or its explicit
118 // "no SSH route" state). Non-primary local backends (e.g. WSL) keep it
119 // hidden, matching pre-remote behavior.
120 return input.remoteOpenMode !== "local-exec";
121}
122
123export const ChatHeader = memo(function ChatHeader({
124 activeThreadEnvironmentId,
125 activeThreadId,
126 draftId,
127 activeThreadTitle,
128 isServerThread,
129 activeProjectName,
130 activeProjectCwd,
131 activeProjectFaviconPath,
132 activeProjectIcon,
133 openInCwd,
134 activeProjectScripts,
135 preferredScriptId,
136 keybindings,
137 availableEditors,
138 rightPanelOpen,
139 gitCwd,
140 onOpenPullRequest,
141 onNewThreadInProject,
142 onOpenProjectSettings,
143 onRunProjectScript,
144 onAddProjectScript,
145 onUpdateProjectScript,
146 onDeleteProjectScript,
147}: ChatHeaderProps) {
148 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
149 usePanelAnimationSettings();
150 const headerActionsRef = useRef<HTMLDivElement | null>(null);
151 useEffect(() => {
152 const actions = headerActionsRef.current;
153 const container = actions?.parentElement;
154 if (!actions || !container) return;
155 return observeResponsiveBreakpointFade({
156 target: actions,
157 container,
158 active: panelAnimationsActive,
159 durationMs: panelAnimationDurationMs,
160 breakpoint: { value: HEADER_ACTIONS_EXPANDED_BREAKPOINT_REM, unit: "rem" },
161 });
162 }, [panelAnimationDurationMs, panelAnimationsActive]);
163 const primaryEnvironmentId = usePrimaryEnvironmentId();
164 const fileScripts = useT3ProjectFileScripts(
165 activeThreadEnvironmentId,
166 activeProjectScripts ? activeProjectCwd : null,
167 );
168 const remoteOpenState = useRemoteOpenState(activeThreadEnvironmentId);
169 const showOpenInPicker = shouldShowOpenInPicker({
170 activeProjectName,
171 activeThreadEnvironmentId,
172 primaryEnvironmentId,
173 remoteOpenMode: remoteOpenState.mode,
174 });
175 const activeThreadRef = useMemo(
176 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
177 [activeThreadEnvironmentId, activeThreadId],
178 );
179 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
180 reportFailure: false,
181 });
182 // Inline rename, keyed by thread: navigating away drops an in-progress
183 // rename instead of committing stale text. Cleared on thread change (not
184 // just hidden) so returning to the thread doesn't revive the old draft.
185 const [renaming, setRenaming] = useState<{ threadId: ThreadId; title: string } | null>(null);
186 if (renaming !== null && renaming.threadId !== activeThreadId) {
187 setRenaming(null);
188 }
189 const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
190 const renameCommittedRef = useRef(false);
191 const startRename = useCallback(() => {
192 renameCommittedRef.current = false;
193 setRenaming({ threadId: activeThreadId, title: activeThreadTitle });
194 }, [activeThreadId, activeThreadTitle]);
195 const commitRename = useCallback(
196 (title: string) => {
197 setRenaming(null);
198 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
199 if (resolution.action === "reject-empty") {
200 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
201 return;
202 }
203 if (resolution.action === "noop") return;
204 void updateThreadMetadata({
205 environmentId: activeThreadEnvironmentId,
206 input: { threadId: activeThreadId, title: resolution.title },
207 }).then((result) => {
208 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
209 const error = squashAtomCommandFailure(result);
210 toastManager.add({
211 type: "error",
212 title: "Failed to rename thread",
213 description: error instanceof Error ? error.message : "An error occurred.",
214 });
215 }
216 });
217 },
218 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
219 );
220 const { openMenu, closeMenu } = useThreadActionMenu({
221 threadRef: isServerThread ? activeThreadRef : null,
222 projectCwd: activeProjectCwd,
223 onStartRename: startRename,
224 });
225 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
226 const titleMenuTimerRef = useRef<number | null>(null);
227 const cancelPendingTitleMenu = useCallback(() => {
228 if (titleMenuTimerRef.current === null) return;
229 clearTimeout(titleMenuTimerRef.current);
230 titleMenuTimerRef.current = null;
231 }, []);
232 // Drop a pending menu-open when the thread changes or the header unmounts,
233 // so it can never fire for a thread the user already left.
234 useEffect(
235 () => () => {
236 cancelPendingTitleMenu();
237 },
238 [activeThreadId, cancelPendingTitleMenu],
239 );
240 const openTitleMenuNow = useCallback(() => {
241 cancelPendingTitleMenu();
242 const rect = titleButtonRef.current?.getBoundingClientRect();
243 if (!rect) return;
244 openMenu({ x: rect.left, y: rect.bottom + 4 });
245 }, [cancelPendingTitleMenu, openMenu]);
246 const openMenuFromTitle = useCallback(
247 (event: ReactMouseEvent<HTMLButtonElement>) => {
248 // The trailing click of a double-click belongs to rename, not the menu.
249 if (isTrailingDoubleClick(event.detail)) return;
250 // Keyboard activation and the explicit chevron affordance can never be
251 // the first half of a double-click, so they open without waiting.
252 const clickedChevron =
253 (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null;
254 if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) {
255 openTitleMenuNow();
256 return;
257 }
258 // Stay pending long enough for dblclick to cancel the open before the
259 // native menu appears and swallows the second click.
260 cancelPendingTitleMenu();
261 titleMenuTimerRef.current = window.setTimeout(() => {
262 titleMenuTimerRef.current = null;
263 openTitleMenuNow();
264 }, TITLE_MENU_OPEN_DELAY_MS);
265 },
266 [cancelPendingTitleMenu, openTitleMenuNow],
267 );
268 const handleTitleDoubleClick = useCallback(
269 (event: ReactMouseEvent) => {
270 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
271 // The chevron is the explicit menu affordance; only the title text renames.
272 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
273 cancelPendingTitleMenu();
274 closeMenu();
275 startRename();
276 },
277 [cancelPendingTitleMenu, closeMenu, startRename],
278 );
279 const handleHeaderContextMenu = useCallback(
280 (event: ReactMouseEvent) => {
281 if (renamingTitle !== null) return;
282 // The right-side controls (git, scripts, open-in) keep their own
283 // behavior; only the breadcrumb area opens the thread menu.
284 if ((event.target as HTMLElement).closest("[data-chat-header-actions]")) return;
285 if (!isServerThread && onOpenProjectSettings === undefined) return;
286 cancelPendingTitleMenu();
287 event.preventDefault();
288 if (!isServerThread) {
289 const api = readLocalApi();
290 if (!api) return;
291 void api.contextMenu
292 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
293 x: event.clientX,
294 y: event.clientY,
295 })
296 .then((action) => {
297 if (action === "project-settings") onOpenProjectSettings?.();
298 });
299 return;
300 }
301 openMenu({ x: event.clientX, y: event.clientY });
302 },
303 [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle],
304 );
305 const handleRenameKeyDown = useCallback(
306 (event: ReactKeyboardEvent<HTMLInputElement>) => {
307 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
308 if (event.key === "Enter") {
309 renameCommittedRef.current = true;
310 commitRename(event.currentTarget.value);
311 } else if (event.key === "Escape") {
312 renameCommittedRef.current = true;
313 setRenaming(null);
314 }
315 },
316 [commitRename],
317 );
318 return (
319 <div
320 className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
321 onContextMenu={handleHeaderContextMenu}
322 >
323 <WorkspaceBreadcrumb
324 ariaLabel="Thread breadcrumb"
325 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
326 >
327 {/* The project always leads the header: knowing which project a
328 thread lives in is priority zero, and the thread title alone
329 doesn't answer it. */}
330 {activeProjectName ? (
331 <>
332 <WorkspaceBreadcrumbItem className="shrink">
333 <Tooltip>
334 <TooltipTrigger
335 render={
336 <button
337 type="button"
338 aria-label={`New thread in ${activeProjectName}`}
339 onClick={onNewThreadInProject}
340 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"
341 />
342 }
343 >
344 <ProjectFavicon
345 environmentId={activeThreadEnvironmentId}
346 cwd={activeProjectCwd ?? ""}
347 projectName={activeProjectName}
348 faviconPath={activeProjectFaviconPath}
349 projectIcon={activeProjectIcon}
350 className="size-3.5"
351 />
352 <span className="max-w-40 truncate">{activeProjectName}</span>
353 </TooltipTrigger>
354 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
355 </Tooltip>
356 </WorkspaceBreadcrumbItem>
357 <WorkspaceBreadcrumbSeparator />
358 </>
359 ) : null}
360 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
361 {renamingTitle !== null ? (
362 <input
363 autoFocus
364 aria-label="Thread title"
365 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"
366 defaultValue={renamingTitle}
367 onBlur={(event) => {
368 if (renameCommittedRef.current) return;
369 commitRename(event.currentTarget.value);
370 }}
371 onFocus={(event) => event.currentTarget.select()}
372 onKeyDown={handleRenameKeyDown}
373 />
374 ) : isServerThread ? (
375 <Tooltip>
376 <TooltipTrigger
377 render={
378 <button
379 ref={titleButtonRef}
380 type="button"
381 aria-label={`Thread actions for ${activeThreadTitle}`}
382 aria-haspopup="menu"
383 onClick={openMenuFromTitle}
384 onDoubleClick={handleTitleDoubleClick}
385 onBlur={cancelPendingTitleMenu}
386 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"
387 />
388 }
389 >
390 <h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
391 <ChevronDownIcon
392 aria-hidden
393 data-thread-title-chevron
394 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"
395 />
396 </TooltipTrigger>
397 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
398 </Tooltip>
399 ) : (
400 <Tooltip>
401 <TooltipTrigger
402 render={
403 <h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
404 {activeThreadTitle}
405 </h2>
406 }
407 />
408 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
409 </Tooltip>
410 )}
411 </WorkspaceBreadcrumbItem>
412 </WorkspaceBreadcrumb>
413 <div
414 ref={headerActionsRef}
415 data-chat-header-actions
416 className={cn(
417 "flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
418 rightPanelOpen ? "pr-0" : "pr-16",
419 "[[data-panel-animations=true]_&]:motion-safe:transition-[padding-right] [[data-panel-animations=true]_&]:motion-safe:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:motion-safe:ease-out",
420 )}
421 >
422 {activeProjectScripts && (
423 <ProjectScriptsControl
424 scripts={activeProjectScripts}
425 fileScripts={fileScripts}
426 keybindings={keybindings}
427 preferredScriptId={preferredScriptId}
428 onRunScript={onRunProjectScript}
429 onAddScript={onAddProjectScript}
430 onUpdateScript={onUpdateProjectScript}
431 onDeleteScript={onDeleteProjectScript}
432 />
433 )}
434 {showOpenInPicker && (
435 <OpenInPicker
436 environmentId={activeThreadEnvironmentId}
437 keybindings={keybindings}
438 availableEditors={availableEditors}
439 openInCwd={openInCwd}
440 />
441 )}
442 {activeProjectName && (
443 <GitActionsControl
444 gitCwd={gitCwd}
445 activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
446 onOpenPullRequest={onOpenPullRequest}
447 {...(draftId ? { draftId } : {})}
448 />
449 )}
450 </div>
451 </div>
452 );
453});