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

ChatHeader.tsx

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