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