Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatHeader.tsx

529 lines21.2 KB

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 type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import { ChevronDownIcon, EllipsisIcon } 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 { createPortal } from "react-dom";
26import GitActionsControl from "../GitActionsControl";
27import { isTrailingDoubleClick } from "../Sidebar.logic";
28import { type DraftId } from "~/composerDraftStore";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30import { toastManager } from "../ui/toast";
31import ProjectScriptsControl, {
32 type NewProjectScriptInput,
33 type ProjectScriptActionResult,
34} from "../ProjectScriptsControl";
35import { OpenInPicker } from "./OpenInPicker";
36import { useRemoteOpenState, type RemoteOpenMode } from "../../remoteOpen";
37import { usePrimaryEnvironmentId } from "../../state/environments";
38import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
39import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
40import { readLocalApi } from "~/localApi";
41import { threadEnvironment } from "../../state/threads";
42import { useAtomCommand } from "../../state/use-atom-command";
43import { observeResponsiveBreakpointFade, usePanelAnimationSettings } from "../../panelAnimations";
44import { ProjectFavicon } from "../ProjectFavicon";
45import {
46 WorkspaceBreadcrumb,
47 WorkspaceBreadcrumbItem,
48 WorkspaceBreadcrumbSeparator,
49 WorkspaceBreadcrumbText,
50} from "../WorkspaceBreadcrumb";
51import { cn } from "~/lib/utils";
52import { useIsMobile } from "~/hooks/useMediaQuery";
53import { Button } from "../ui/button";
54import { Menu, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu";
55​
56interface ChatHeaderProps {
57 activeThreadEnvironmentId: EnvironmentId;
58 activeThreadId: ThreadId;
59 draftId?: DraftId;
60 activeThreadTitle: string;
61 /** Drafts have no server thread yet, so the title carries no action menu. */
62 isServerThread: boolean;
63 activeProject: EnvironmentProject | null;
64 openInCwd: string | null;
65 activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
66 preferredScriptId: string | null;
67 keybindings: ResolvedKeybindingsConfig;
68 availableEditors: ReadonlyArray<EditorId>;
69 rightPanelOpen: boolean;
70 gitCwd: string | null;
71 readonly onOpenPullRequest?: ((number: number) => void) | undefined;
72 onNewThreadInProject: () => void;
73 onOpenProjectSettings?: (() => void) | undefined;
74 onRunProjectScript: (script: ProjectScript) => void;
75 onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
76 onUpdateProjectScript: (
77 scriptId: string,
78 input: NewProjectScriptInput,
79 ) => Promise<ProjectScriptActionResult>;
80 onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
82​
83/**
84 * Rename commit rule shared with the sidebar's inline rename: trim, reject
85 * empty (the caller toasts), and skip the mutation when nothing changed.
86 */
87export function resolveRenameCommit(input: {
88 readonly title: string;
89 readonly originalTitle: string;
90}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
91 const trimmed = input.title.trim();
92 if (trimmed.length === 0) return { action: "reject-empty" };
93 if (trimmed === input.originalTitle) return { action: "noop" };
94 return { action: "commit", title: trimmed };
96​
97// How long a click on the thread title waits before opening the action menu,
98// so a double-click-to-rename can cancel it first. Only the native desktop
99// menu needs this: it swallows input while open, so the wait must cover the
100// OS double-click interval. The browser fallback menu keeps seeing DOM
101// events (the second click dismisses it and dblclick still fires), so it
102// opens immediately.
103const TITLE_MENU_OPEN_DELAY_MS = 500;
104// Matches the @3xl/header-actions container breakpoint owned by this header.
105const HEADER_ACTIONS_EXPANDED_BREAKPOINT_REM = 48;
106​
107export function shouldShowOpenInPicker(input: {
108 readonly activeProjectName: string | undefined;
109 readonly activeThreadEnvironmentId: EnvironmentId;
110 readonly primaryEnvironmentId: EnvironmentId | null;
111 readonly remoteOpenMode: RemoteOpenMode;
112}): boolean {
113 if (!input.activeProjectName) return false;
114 if (
115 input.primaryEnvironmentId !== null &&
116 input.activeThreadEnvironmentId === input.primaryEnvironmentId
117 ) {
118 return true;
119 }
120 // Remote environments get the picker in deep-link mode (or its explicit
121 // "no SSH route" state). Non-primary local backends (e.g. WSL) keep it
122 // hidden, matching pre-remote behavior.
123 return input.remoteOpenMode !== "local-exec";
125​
126export const ChatHeader = memo(function ChatHeader({
127 activeThreadEnvironmentId,
128 activeThreadId,
129 draftId,
130 activeThreadTitle,
131 isServerThread,
132 activeProject,
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 isMobile = useIsMobile();
164 // Side panels can leave a desktop header narrower than a phone.
165 const [isNarrowHeader, setIsNarrowHeader] = useState(false);
166 useEffect(() => {
167 const container = headerActionsRef.current?.parentElement;
168 if (!container) return;
169 const update = () => setIsNarrowHeader(container.clientWidth < 512);
170 update();
171 const observer = new ResizeObserver(update);
172 observer.observe(container);
173 return () => observer.disconnect();
174 }, []);
175 const actionsCollapsed = isMobile || isNarrowHeader;
176 const [actionsOpen, setActionsOpen] = useState(false);
177 const [actionsContainer] = useState(() => {
178 const container = document.createElement("div");
179 container.className = "contents";
180 return container;
181 });
182 // Reparent the DOM host, not the React controls: rotating a phone or resizing
183 // a window must not discard an unsaved script or Git dialog.
184 const mountInlineActions = useCallback(
185 (node: HTMLDivElement | null) => {
186 if (node && !actionsCollapsed) node.appendChild(actionsContainer);
187 },
188 [actionsContainer, actionsCollapsed],
189 );
190 const mountMenuActions = useCallback(
191 (node: HTMLDivElement | null) => {
192 if (node && actionsCollapsed) node.appendChild(actionsContainer);
193 },
194 [actionsContainer, actionsCollapsed],
195 );
196 if (!actionsCollapsed && actionsOpen) setActionsOpen(false);
197 const primaryEnvironmentId = usePrimaryEnvironmentId();
198 const activeProjectName = activeProject?.title;
199 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
200 const fileScripts = useT3ProjectFileScripts(
201 activeThreadEnvironmentId,
202 activeProjectScripts ? activeProjectCwd : null,
203 );
204 const remoteOpenState = useRemoteOpenState(activeThreadEnvironmentId);
205 const showOpenInPicker = shouldShowOpenInPicker({
206 activeProjectName,
207 activeThreadEnvironmentId,
208 primaryEnvironmentId,
209 remoteOpenMode: remoteOpenState.mode,
210 });
211 const activeThreadRef = useMemo(
212 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
213 [activeThreadEnvironmentId, activeThreadId],
214 );
215 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
216 reportFailure: false,
217 });
218 // Inline rename, keyed by thread: navigating away drops an in-progress
219 // rename instead of committing stale text. Cleared on thread change (not
220 // just hidden) so returning to the thread doesn't revive the old draft.
221 const [renaming, setRenaming] = useState<{ threadId: ThreadId; title: string } | null>(null);
222 if (renaming !== null && renaming.threadId !== activeThreadId) {
223 setRenaming(null);
224 }
225 const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
226 const renameCommittedRef = useRef(false);
227 const startRename = useCallback(() => {
228 renameCommittedRef.current = false;
229 setRenaming({ threadId: activeThreadId, title: activeThreadTitle });
230 }, [activeThreadId, activeThreadTitle]);
231 const commitRename = useCallback(
232 (title: string) => {
233 setRenaming(null);
234 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
235 if (resolution.action === "reject-empty") {
236 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
237 return;
238 }
239 if (resolution.action === "noop") return;
240 void updateThreadMetadata({
241 environmentId: activeThreadEnvironmentId,
242 input: { threadId: activeThreadId, title: resolution.title },
243 }).then((result) => {
244 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
245 const error = squashAtomCommandFailure(result);
246 toastManager.add({
247 type: "error",
248 title: "Failed to rename thread",
249 description: error instanceof Error ? error.message : "An error occurred.",
250 });
251 }
252 });
253 },
254 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
255 );
256 const { openMenu, closeMenu } = useThreadActionMenu({
257 threadRef: isServerThread ? activeThreadRef : null,
258 projectCwd: activeProjectCwd,
259 onStartRename: startRename,
260 });
261 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
262 const titleMenuTimerRef = useRef<number | null>(null);
263 const cancelPendingTitleMenu = useCallback(() => {
264 if (titleMenuTimerRef.current === null) return;
265 clearTimeout(titleMenuTimerRef.current);
266 titleMenuTimerRef.current = null;
267 }, []);
268 // Drop a pending menu-open when the thread changes or the header unmounts,
269 // so it can never fire for a thread the user already left.
270 useEffect(
271 () => () => {
272 cancelPendingTitleMenu();
273 },
274 [activeThreadId, cancelPendingTitleMenu],
275 );
276 const openTitleMenuNow = useCallback(() => {
277 cancelPendingTitleMenu();
278 const rect = titleButtonRef.current?.getBoundingClientRect();
279 if (!rect) return;
280 openMenu({ x: rect.left, y: rect.bottom + 4 });
281 }, [cancelPendingTitleMenu, openMenu]);
282 const openMenuFromTitle = useCallback(
283 (event: ReactMouseEvent<HTMLButtonElement>) => {
284 // The trailing click of a double-click belongs to rename, not the menu.
285 if (isTrailingDoubleClick(event.detail)) return;
286 // Keyboard activation and the explicit chevron affordance can never be
287 // the first half of a double-click, so they open without waiting.
288 const clickedChevron =
289 (event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null;
290 if (event.detail === 0 || clickedChevron || window.desktopBridge === undefined) {
291 openTitleMenuNow();
292 return;
293 }
294 // Stay pending long enough for dblclick to cancel the open before the
295 // native menu appears and swallows the second click.
296 cancelPendingTitleMenu();
297 titleMenuTimerRef.current = window.setTimeout(() => {
298 titleMenuTimerRef.current = null;
299 openTitleMenuNow();
300 }, TITLE_MENU_OPEN_DELAY_MS);
301 },
302 [cancelPendingTitleMenu, openTitleMenuNow],
303 );
304 const handleTitleDoubleClick = useCallback(
305 (event: ReactMouseEvent) => {
306 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
307 // The chevron is the explicit menu affordance; only the title text renames.
308 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
309 cancelPendingTitleMenu();
310 closeMenu();
311 startRename();
312 },
313 [cancelPendingTitleMenu, closeMenu, startRename],
314 );
315 const handleHeaderContextMenu = useCallback(
316 (event: ReactMouseEvent) => {
317 if (renamingTitle !== null) return;
318 // The right-side controls (git, scripts, open-in) keep their own
319 // behavior; only the breadcrumb area opens the thread menu.
320 if ((event.target as HTMLElement).closest("[data-chat-header-actions]")) return;
321 if (!isServerThread && onOpenProjectSettings === undefined) return;
322 cancelPendingTitleMenu();
323 event.preventDefault();
324 if (!isServerThread) {
325 const api = readLocalApi();
326 if (!api) return;
327 void api.contextMenu
328 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
329 x: event.clientX,
330 y: event.clientY,
331 })
332 .then((action) => {
333 if (action === "project-settings") onOpenProjectSettings?.();
334 });
335 return;
336 }
337 openMenu({ x: event.clientX, y: event.clientY });
338 },
339 [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle],
340 );
341 const handleRenameKeyDown = useCallback(
342 (event: ReactKeyboardEvent<HTMLInputElement>) => {
343 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
344 if (event.key === "Enter") {
345 renameCommittedRef.current = true;
346 commitRename(event.currentTarget.value);
347 } else if (event.key === "Escape") {
348 renameCommittedRef.current = true;
349 setRenaming(null);
350 }
351 },
352 [commitRename],
353 );
354 const headerActions = (
355 <>
356 {activeProjectScripts && (
357 <>
358 <ProjectScriptsControl
359 onRequestMenuClose={() => setActionsOpen(false)}
360 presentation={actionsCollapsed ? "menu" : "toolbar"}
361 scripts={activeProjectScripts}
362 fileScripts={fileScripts}
363 keybindings={keybindings}
364 preferredScriptId={preferredScriptId}
365 onRunScript={onRunProjectScript}
366 onAddScript={onAddProjectScript}
367 onUpdateScript={onUpdateProjectScript}
368 onDeleteScript={onDeleteProjectScript}
369 />
370 </>
371 )}
372 {showOpenInPicker && (
373 <>
374 {actionsCollapsed && activeProjectScripts && <MenuSeparator />}
375 <OpenInPicker
376 presentation={actionsCollapsed ? "menu" : "toolbar"}
377 environmentId={activeThreadEnvironmentId}
378 keybindings={keybindings}
379 availableEditors={availableEditors}
380 openInCwd={openInCwd}
381 />
382 </>
383 )}
384 {activeProjectName && gitCwd && (
385 <>
386 {actionsCollapsed && (activeProjectScripts || showOpenInPicker) && <MenuSeparator />}
387 <GitActionsControl
388 presentation={actionsCollapsed ? "menu" : "toolbar"}
389 gitCwd={gitCwd}
390 activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
391 onOpenPullRequest={onOpenPullRequest}
392 {...(draftId ? { draftId } : {})}
393 />
394 </>
395 )}
396 </>
397 );
398 return (
399 <div
400 className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
401 onContextMenu={handleHeaderContextMenu}
402 >
403 <WorkspaceBreadcrumb
404 ariaLabel="Thread breadcrumb"
405 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
406 >
407 {/* The project always leads the header: knowing which project a
408 thread lives in is priority zero, and the thread title alone
409 doesn't answer it. */}
410 {activeProject ? (
411 <>
412 <WorkspaceBreadcrumbItem className="shrink">
413 <Tooltip>
414 <TooltipTrigger
415 render={
416 <button
417 type="button"
418 aria-label={`New thread in ${activeProjectName}`}
419 onClick={onNewThreadInProject}
420 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"
421 />
422 }
423 >
424 <ProjectFavicon project={activeProject} className="size-3.5" />
425 <WorkspaceBreadcrumbText className="max-w-40">
426 {activeProjectName}
427 </WorkspaceBreadcrumbText>
428 </TooltipTrigger>
429 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
430 </Tooltip>
431 </WorkspaceBreadcrumbItem>
432 <WorkspaceBreadcrumbSeparator>
433 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
434 </WorkspaceBreadcrumbSeparator>
435 </>
436 ) : null}
437 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
438 {renamingTitle !== null ? (
439 <input
440 autoFocus
441 aria-label="Thread title"
442 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"
443 defaultValue={renamingTitle}
444 onBlur={(event) => {
445 if (renameCommittedRef.current) return;
446 commitRename(event.currentTarget.value);
447 }}
448 onFocus={(event) => event.currentTarget.select()}
449 onKeyDown={handleRenameKeyDown}
450 />
451 ) : isServerThread ? (
452 <Tooltip>
453 <TooltipTrigger
454 render={
455 <button
456 ref={titleButtonRef}
457 type="button"
458 aria-label={`Thread actions for ${activeThreadTitle}`}
459 aria-haspopup="menu"
460 onClick={openMenuFromTitle}
461 onDoubleClick={handleTitleDoubleClick}
462 onBlur={cancelPendingTitleMenu}
463 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"
464 />
465 }
466 >
467 <h2 className="min-w-0">
468 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
469 </h2>
470 <ChevronDownIcon
471 aria-hidden
472 data-thread-title-chevron
473 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"
474 />
475 </TooltipTrigger>
476 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
477 </Tooltip>
478 ) : (
479 <Tooltip>
480 <TooltipTrigger
481 render={<h2 aria-label={activeThreadTitle} className="min-w-0 flex-1" />}
482 >
483 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
484 </TooltipTrigger>
485 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
486 </Tooltip>
487 )}
488 </WorkspaceBreadcrumbItem>
489 </WorkspaceBreadcrumb>
490 <div
491 ref={headerActionsRef}
492 data-chat-header-actions
493 className={cn(
494 "flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
495 // Reserve two panel toggles plus their 4px gaps and 1px edge inset.
496 // The page header adds 8px more right padding at sm.
497 rightPanelOpen ? "pr-0" : "pr-[calc(--spacing(18)+1px)] sm:pr-[calc(--spacing(14)+1px)]",
498 "[[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",
499 )}
500 >
501 <Menu open={actionsCollapsed && actionsOpen} onOpenChange={setActionsOpen}>
502 <MenuTrigger
503 className={
504 actionsCollapsed &&
505 (activeProjectScripts || showOpenInPicker || (activeProjectName && gitCwd))
506 ? undefined
507 : "hidden"
508 }
509 render={<Button size="icon-sm" variant="ghost" aria-label="More header actions" />}
510 >
511 <EllipsisIcon className="size-4" />
512 </MenuTrigger>
513 <div ref={mountInlineActions} className="contents" />
514 <MenuPopup
515 data-chat-header-actions
516 keepMounted
517 aria-label="Header actions"
518 align="end"
519 className="min-w-56 max-w-[calc(100vw-2rem)]"
520 finalFocus={actionsCollapsed ? undefined : false}
521 >
522 <div ref={mountMenuActions} className="contents" />
523 {createPortal(headerActions, actionsContainer)}
524 </MenuPopup>
525 </Menu>
526 </div>
527 </div>
528 );
529});