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