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