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