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