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

ChatHeader.tsx

443 lines17.6 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 } 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 { readLocalApi } from "~/localApi";
40import { threadEnvironment } from "../../state/threads";
41import { useAtomCommand } from "../../state/use-atom-command";
42import { observeResponsiveBreakpointFade, usePanelAnimationSettings } from "../../panelAnimations";
43import { ProjectFavicon } from "../ProjectFavicon";
44import {
45 WorkspaceBreadcrumb,
46 WorkspaceBreadcrumbItem,
47 WorkspaceBreadcrumbSeparator,
48} from "../WorkspaceBreadcrumb";
49import { cn } from "~/lib/utils";
50​
51interface ChatHeaderProps {
52 activeThreadEnvironmentId: EnvironmentId;
53 activeThreadId: ThreadId;
54 draftId?: DraftId;
55 activeThreadTitle: string;
56 /** Drafts have no server thread yet, so the title carries no action menu. */
57 isServerThread: boolean;
58 activeProject: EnvironmentProject | 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 onOpenProjectSettings?: (() => void) | undefined;
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>;
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 };
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";
120​
121export const ChatHeader = memo(function ChatHeader({
122 activeThreadEnvironmentId,
123 activeThreadId,
124 draftId,
125 activeThreadTitle,
126 isServerThread,
127 activeProject,
128 openInCwd,
129 activeProjectScripts,
130 preferredScriptId,
131 keybindings,
132 availableEditors,
133 rightPanelOpen,
134 gitCwd,
135 onOpenPullRequest,
136 onNewThreadInProject,
137 onOpenProjectSettings,
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 activeProjectName = activeProject?.title;
160 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
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 (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 if (!isServerThread && onOpenProjectSettings === undefined) return;
283 cancelPendingTitleMenu();
284 event.preventDefault();
285 if (!isServerThread) {
286 const api = readLocalApi();
287 if (!api) return;
288 void api.contextMenu
289 .show([{ id: "project-settings", label: "Project settings", icon: "settings" }], {
290 x: event.clientX,
291 y: event.clientY,
292 })
293 .then((action) => {
294 if (action === "project-settings") onOpenProjectSettings?.();
295 });
296 return;
297 }
298 openMenu({ x: event.clientX, y: event.clientY });
299 },
300 [cancelPendingTitleMenu, isServerThread, onOpenProjectSettings, openMenu, renamingTitle],
301 );
302 const handleRenameKeyDown = useCallback(
303 (event: ReactKeyboardEvent<HTMLInputElement>) => {
304 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
305 if (event.key === "Enter") {
306 renameCommittedRef.current = true;
307 commitRename(event.currentTarget.value);
308 } else if (event.key === "Escape") {
309 renameCommittedRef.current = true;
310 setRenaming(null);
311 }
312 },
313 [commitRename],
314 );
315 return (
316 <div
317 className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
318 onContextMenu={handleHeaderContextMenu}
319 >
320 <WorkspaceBreadcrumb
321 ariaLabel="Thread breadcrumb"
322 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
323 >
324 {/* The project always leads the header: knowing which project a
325 thread lives in is priority zero, and the thread title alone
326 doesn't answer it. */}
327 {activeProject ? (
328 <>
329 <WorkspaceBreadcrumbItem className="shrink">
330 <Tooltip>
331 <TooltipTrigger
332 render={
333 <button
334 type="button"
335 aria-label={`New thread in ${activeProjectName}`}
336 onClick={onNewThreadInProject}
337 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"
338 />
339 }
340 >
341 <ProjectFavicon project={activeProject} className="size-3.5" />
342 <span className="max-w-40 truncate">{activeProjectName}</span>
343 </TooltipTrigger>
344 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
345 </Tooltip>
346 </WorkspaceBreadcrumbItem>
347 <WorkspaceBreadcrumbSeparator />
348 </>
349 ) : null}
350 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
351 {renamingTitle !== null ? (
352 <input
353 autoFocus
354 aria-label="Thread title"
355 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"
356 defaultValue={renamingTitle}
357 onBlur={(event) => {
358 if (renameCommittedRef.current) return;
359 commitRename(event.currentTarget.value);
360 }}
361 onFocus={(event) => event.currentTarget.select()}
362 onKeyDown={handleRenameKeyDown}
363 />
364 ) : isServerThread ? (
365 <Tooltip>
366 <TooltipTrigger
367 render={
368 <button
369 ref={titleButtonRef}
370 type="button"
371 aria-label={`Thread actions for ${activeThreadTitle}`}
372 aria-haspopup="menu"
373 onClick={openMenuFromTitle}
374 onDoubleClick={handleTitleDoubleClick}
375 onBlur={cancelPendingTitleMenu}
376 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"
377 />
378 }
379 >
380 <h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
381 <ChevronDownIcon
382 aria-hidden
383 data-thread-title-chevron
384 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"
385 />
386 </TooltipTrigger>
387 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
388 </Tooltip>
389 ) : (
390 <Tooltip>
391 <TooltipTrigger
392 render={
393 <h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
394 {activeThreadTitle}
395 </h2>
396 }
397 />
398 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
399 </Tooltip>
400 )}
401 </WorkspaceBreadcrumbItem>
402 </WorkspaceBreadcrumb>
403 <div
404 ref={headerActionsRef}
405 data-chat-header-actions
406 className={cn(
407 "flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
408 rightPanelOpen ? "pr-0" : "pr-16",
409 "[[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",
410 )}
411 >
412 {activeProjectScripts && (
413 <ProjectScriptsControl
414 scripts={activeProjectScripts}
415 fileScripts={fileScripts}
416 keybindings={keybindings}
417 preferredScriptId={preferredScriptId}
418 onRunScript={onRunProjectScript}
419 onAddScript={onAddProjectScript}
420 onUpdateScript={onUpdateProjectScript}
421 onDeleteScript={onDeleteProjectScript}
422 />
423 )}
424 {showOpenInPicker && (
425 <OpenInPicker
426 environmentId={activeThreadEnvironmentId}
427 keybindings={keybindings}
428 availableEditors={availableEditors}
429 openInCwd={openInCwd}
430 />
431 )}
432 {activeProjectName && (
433 <GitActionsControl
434 gitCwd={gitCwd}
435 activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
436 onOpenPullRequest={onOpenPullRequest}
437 {...(draftId ? { draftId } : {})}
438 />
439 )}
440 </div>
441 </div>
442 );
443});