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 { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
14import { ChevronDownIcon } from "lucide-react";
15import {
16 memo,
17 useCallback,
18 useMemo,
19 useRef,
20 useState,
21 type KeyboardEvent as ReactKeyboardEvent,
22 type MouseEvent as ReactMouseEvent,
23} from "react";
24import GitActionsControl from "../GitActionsControl";
25import { type DraftId } from "~/composerDraftStore";
26import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27import { toastManager } from "../ui/toast";
28import ProjectScriptsControl, {
29 type NewProjectScriptInput,
30 type ProjectScriptActionResult,
31} from "../ProjectScriptsControl";
32import { OpenInPicker } from "./OpenInPicker";
33import { usePrimaryEnvironmentId } from "../../state/environments";
34import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
35import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
36import { threadEnvironment } from "../../state/threads";
37import { useAtomCommand } from "../../state/use-atom-command";
38import { ProjectFavicon } from "../ProjectFavicon";
39import {
40 WorkspaceBreadcrumb,
41 WorkspaceBreadcrumbItem,
42 WorkspaceBreadcrumbSeparator,
43} from "../WorkspaceBreadcrumb";
44import { cn } from "~/lib/utils";
45
46interface ChatHeaderProps {
47 activeThreadEnvironmentId: EnvironmentId;
48 activeThreadId: ThreadId;
49 draftId?: DraftId;
50 activeThreadTitle: string;
51 /** Drafts have no server thread yet, so the title carries no action menu. */
52 isServerThread: boolean;
53 /** PR state feeding the settled classification, resolved by ChatView. */
54 changeRequestState: ChangeRequestStateLike | null;
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
90export function shouldShowOpenInPicker(input: {
91 readonly activeProjectName: string | undefined;
92 readonly activeThreadEnvironmentId: EnvironmentId;
93 readonly primaryEnvironmentId: EnvironmentId | null;
94}): boolean {
95 return (
96 Boolean(input.activeProjectName) &&
97 input.primaryEnvironmentId !== null &&
98 input.activeThreadEnvironmentId === input.primaryEnvironmentId
99 );
100}
101
102export const ChatHeader = memo(function ChatHeader({
103 activeThreadEnvironmentId,
104 activeThreadId,
105 draftId,
106 activeThreadTitle,
107 isServerThread,
108 changeRequestState,
109 activeProjectName,
110 activeProjectCwd,
111 activeProjectFaviconPath,
112 openInCwd,
113 activeProjectScripts,
114 preferredScriptId,
115 keybindings,
116 availableEditors,
117 rightPanelOpen,
118 gitCwd,
119 onOpenPullRequest,
120 onNewThreadInProject,
121 onRunProjectScript,
122 onAddProjectScript,
123 onUpdateProjectScript,
124 onDeleteProjectScript,
125}: ChatHeaderProps) {
126 const primaryEnvironmentId = usePrimaryEnvironmentId();
127 const fileScripts = useT3ProjectFileScripts(
128 activeThreadEnvironmentId,
129 activeProjectScripts ? activeProjectCwd : null,
130 );
131 const showOpenInPicker = shouldShowOpenInPicker({
132 activeProjectName,
133 activeThreadEnvironmentId,
134 primaryEnvironmentId,
135 });
136 const activeThreadRef = useMemo(
137 () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
138 [activeThreadEnvironmentId, activeThreadId],
139 );
140 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
141 reportFailure: false,
142 });
143 // Inline rename, keyed by thread: navigating away drops an in-progress
144 // rename instead of committing stale text. Cleared on thread change (not
145 // just hidden) so returning to the thread doesn't revive the old draft.
146 const [renaming, setRenaming] = useState<{ threadId: ThreadId; title: string } | null>(null);
147 if (renaming !== null && renaming.threadId !== activeThreadId) {
148 setRenaming(null);
149 }
150 const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
151 const renameCommittedRef = useRef(false);
152 const startRename = useCallback(() => {
153 renameCommittedRef.current = false;
154 setRenaming({ threadId: activeThreadId, title: activeThreadTitle });
155 }, [activeThreadId, activeThreadTitle]);
156 const commitRename = useCallback(
157 (title: string) => {
158 setRenaming(null);
159 const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
160 if (resolution.action === "reject-empty") {
161 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
162 return;
163 }
164 if (resolution.action === "noop") return;
165 void updateThreadMetadata({
166 environmentId: activeThreadEnvironmentId,
167 input: { threadId: activeThreadId, title: resolution.title },
168 }).then((result) => {
169 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
170 const error = squashAtomCommandFailure(result);
171 toastManager.add({
172 type: "error",
173 title: "Failed to rename thread",
174 description: error instanceof Error ? error.message : "An error occurred.",
175 });
176 }
177 });
178 },
179 [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
180 );
181 const { openMenu } = useThreadActionMenu({
182 threadRef: isServerThread ? activeThreadRef : null,
183 projectCwd: activeProjectCwd,
184 changeRequestState,
185 onStartRename: startRename,
186 });
187 const titleButtonRef = useRef<HTMLButtonElement | null>(null);
188 const openMenuFromTitle = useCallback(() => {
189 const rect = titleButtonRef.current?.getBoundingClientRect();
190 if (!rect) return;
191 openMenu({ x: rect.left, y: rect.bottom + 4 });
192 }, [openMenu]);
193 const handleHeaderContextMenu = useCallback(
194 (event: ReactMouseEvent) => {
195 if (!isServerThread || renamingTitle !== null) return;
196 // The right-side controls (git, scripts, open-in) keep their own
197 // behavior; only the breadcrumb area opens the thread menu.
198 if ((event.target as HTMLElement).closest("[data-chat-header-actions]")) return;
199 event.preventDefault();
200 openMenu({ x: event.clientX, y: event.clientY });
201 },
202 [isServerThread, openMenu, renamingTitle],
203 );
204 const handleRenameKeyDown = useCallback(
205 (event: ReactKeyboardEvent<HTMLInputElement>) => {
206 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
207 if (event.key === "Enter") {
208 renameCommittedRef.current = true;
209 commitRename(event.currentTarget.value);
210 } else if (event.key === "Escape") {
211 renameCommittedRef.current = true;
212 setRenaming(null);
213 }
214 },
215 [commitRename],
216 );
217 return (
218 <div
219 className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
220 onContextMenu={handleHeaderContextMenu}
221 >
222 <WorkspaceBreadcrumb ariaLabel="Thread breadcrumb" className="flex-1">
223 {/* The project always leads the header: knowing which project a
224 thread lives in is priority zero, and the thread title alone
225 doesn't answer it. */}
226 {activeProjectName ? (
227 <>
228 <WorkspaceBreadcrumbItem>
229 <Tooltip>
230 <TooltipTrigger
231 render={
232 <button
233 type="button"
234 aria-label={`New thread in ${activeProjectName}`}
235 onClick={onNewThreadInProject}
236 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"
237 />
238 }
239 >
240 <ProjectFavicon
241 environmentId={activeThreadEnvironmentId}
242 cwd={activeProjectCwd ?? ""}
243 faviconPath={activeProjectFaviconPath}
244 className="size-3.5"
245 />
246 <span className="max-w-40 truncate">{activeProjectName}</span>
247 </TooltipTrigger>
248 <TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
249 </Tooltip>
250 </WorkspaceBreadcrumbItem>
251 <WorkspaceBreadcrumbSeparator />
252 </>
253 ) : null}
254 <WorkspaceBreadcrumbItem current className="flex-1">
255 {renamingTitle !== null ? (
256 <input
257 autoFocus
258 aria-label="Thread title"
259 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"
260 defaultValue={renamingTitle}
261 onBlur={(event) => {
262 if (renameCommittedRef.current) return;
263 commitRename(event.currentTarget.value);
264 }}
265 onFocus={(event) => event.currentTarget.select()}
266 onKeyDown={handleRenameKeyDown}
267 />
268 ) : isServerThread ? (
269 <Tooltip>
270 <TooltipTrigger
271 render={
272 <button
273 ref={titleButtonRef}
274 type="button"
275 aria-label={`Thread actions for ${activeThreadTitle}`}
276 aria-haspopup="menu"
277 onClick={openMenuFromTitle}
278 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"
279 />
280 }
281 >
282 <h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
283 <ChevronDownIcon
284 aria-hidden
285 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"
286 />
287 </TooltipTrigger>
288 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
289 </Tooltip>
290 ) : (
291 <Tooltip>
292 <TooltipTrigger
293 render={
294 <h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
295 {activeThreadTitle}
296 </h2>
297 }
298 />
299 <TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
300 </Tooltip>
301 )}
302 </WorkspaceBreadcrumbItem>
303 </WorkspaceBreadcrumb>
304 <div
305 data-chat-header-actions
306 className={cn(
307 "flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
308 rightPanelOpen ? "pr-0" : "pr-16",
309 )}
310 >
311 {activeProjectScripts && (
312 <ProjectScriptsControl
313 scripts={activeProjectScripts}
314 fileScripts={fileScripts}
315 keybindings={keybindings}
316 preferredScriptId={preferredScriptId}
317 onRunScript={onRunProjectScript}
318 onAddScript={onAddProjectScript}
319 onUpdateScript={onUpdateProjectScript}
320 onDeleteScript={onDeleteProjectScript}
321 />
322 )}
323 {showOpenInPicker && (
324 <OpenInPicker
325 environmentId={activeThreadEnvironmentId}
326 keybindings={keybindings}
327 availableEditors={availableEditors}
328 openInCwd={openInCwd}
329 />
330 )}
331 {activeProjectName && (
332 <GitActionsControl
333 gitCwd={gitCwd}
334 activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
335 onOpenPullRequest={onOpenPullRequest}
336 {...(draftId ? { draftId } : {})}
337 />
338 )}
339 </div>
340 </div>
341 );
342});