Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 type EnvironmentId,
4 type ScopedThreadRef,
5 type ThreadId,
6} from "@t3tools/contracts";
7import { contextMenuSourceOf } from "~/contextMenuSource";
8import { scopeThreadRef } from "@t3tools/client-runtime/environment";
9import {
10 resolveProjectDisplayTitle,
11 selectProjectGroupingSettings,
12} from "@t3tools/client-runtime/state/project-grouping";
13import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
14import {
15 isAtomCommandInterrupted,
16 squashAtomCommandFailure,
17} from "@t3tools/client-runtime/state/runtime";
18import { T, useGT, Var } from "gt-react";
19import { ChevronDownIcon } from "lucide-react";
20import {
21 memo,
22 useEffect,
23 useRef,
24 useState,
25 type KeyboardEvent as ReactKeyboardEvent,
26 type MouseEvent as ReactMouseEvent,
27} from "react";
28import { flushSync } from "react-dom";
29import { isTrailingDoubleClick } from "../Sidebar.logic";
30import { Badge } from "../ui/badge";
31import { MiddleTruncate } from "../ui/middle-truncate";
32import { toastManager } from "../ui/toast";
33import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
34import { readLocalApi } from "~/localApi";
35import { useProjects } from "../../state/entities";
36import { threadEnvironment } from "../../state/threads";
37import { canShareWithGuestAtom } from "./guestShareAvailability";
38import { useAtomValue } from "@effect/atom-react";
39import { useOrchestrationCommand } from "../../state/use-orchestration-command";
40import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
41import { ProjectFavicon } from "../ProjectFavicon";
42import {
43 WorkspaceBreadcrumb,
44 WorkspaceBreadcrumbItem,
45 WorkspaceBreadcrumbSeparator,
46 WorkspaceBreadcrumbText,
47} from "../WorkspaceBreadcrumb";
48import { observeResize } from "~/lib/observeResize";
49import { cn } from "~/lib/utils";
50import { textDirection } from "~/textDirection";
51import { useClientSettings } from "../../hooks/useSettings";
52import { GuestShareIndicator } from "./GuestShareControls";
53import { SharedTooltipTrigger } from "../ui/shared-tooltip";
54
55interface ChatHeaderProps {
56 activeThreadEnvironmentId: EnvironmentId;
57 activeThreadId: ThreadId;
58 activeThreadTitle: string;
59 activeThreadLinkOrigin?: string | null | undefined;
60 isServerThread: boolean;
61 activeProject: EnvironmentProject | null;
62 parentThreadLink: { threadId: ThreadId; title: string } | null;
63 onOpenThread: (threadId: ThreadId) => void;
64 rightPanelOpen: boolean;
65 onNewThreadInProject: () => void;
66 onOpenProjectSettings?: (() => void) | undefined;
67 onFindInThread?: ((threadRef: ScopedThreadRef) => void) | undefined;
68}
69
70function resolveRenameCommit(input: {
71 readonly title: string;
72 readonly originalTitle: string;
73}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
74 const trimmed = input.title.trim();
75 if (trimmed.length === 0) return { action: "reject-empty" };
76 if (trimmed === input.originalTitle) return { action: "noop" };
77 return { action: "commit", title: trimmed };
78}
79
80export const ChatHeader = memo(function ChatHeader({
81 activeThreadEnvironmentId,
82 activeThreadId,
83 activeThreadTitle,
84 activeThreadLinkOrigin,
85 isServerThread,
86 activeProject,
87 parentThreadLink,
88 onOpenThread,
89 rightPanelOpen,
90 onNewThreadInProject,
91 onOpenProjectSettings,
92 onFindInThread,
93}: ChatHeaderProps) {
94 const gt = useGT();
95 const projects = useProjects();
96 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
97 const activeProjectName = activeProject
98 ? activeProject.isScratch
99 ? gt`No project`
100 : resolveProjectDisplayTitle(activeProject, projects, projectGroupingSettings)
101 : undefined;
102 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
103 const interfaceFont = useClientSettings((settings) => settings.fontFamilySans);
104 const breadcrumbContainerRef = useRef<HTMLDivElement>(null);
105 const [collapseParentTitle, setCollapseParentTitle] = useState(false);
106 const activeThreadRef = scopeThreadRef(activeThreadEnvironmentId, activeThreadId);
107 const canOperateThread = useEnvironmentScope(
108 activeThreadEnvironmentId,
109 AuthOrchestrationOperateScope,
110 );
111 const canShareWithGuest = useAtomValue(canShareWithGuestAtom(activeThreadEnvironmentId));
112 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
113 reportFailure: false,
114 });
115 const [renaming, setRenaming] = useState<{
116 threadId: ThreadId;
117 environmentId: EnvironmentId;
118 title: string;
119 } | null>(null);
120 if (
121 renaming !== null &&
122 (renaming.threadId !== activeThreadId ||
123 renaming.environmentId !== activeThreadEnvironmentId ||
124 !canOperateThread)
125 ) {
126 setRenaming(null);
127 }
128 const renamingTitle =
129 canOperateThread &&
130 renaming?.threadId === activeThreadId &&
131 renaming.environmentId === activeThreadEnvironmentId
132 ? renaming.title
133 : null;
134 const isRenamingTitle = renamingTitle !== null;
135 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the breadcrumb list DOM via ResizeObserver, a frame and font loads to collapse the parent title
136 useEffect(() => {
137 const list = breadcrumbContainerRef.current?.querySelector("ol");
138 if (!list || !parentThreadLink) return;
139 const measure = () => {
140 const gap = Number.parseFloat(getComputedStyle(list).columnGap) || 0;
141 const width = Array.from(list.children).reduce(
142 (total, item) => {
143 const label = item.querySelector('[data-slot="workspace-breadcrumb-text"]');
144 const ellipsis = item.querySelector("[data-parent-breadcrumb-ellipsis]");
145 return (
146 total +
147 (item.firstElementChild?.getBoundingClientRect().width ?? 0) +
148 (label && getComputedStyle(label).maxWidth === "none"
149 ? label.scrollWidth - label.clientWidth
150 : 0) -
151 (ellipsis?.getBoundingClientRect().width ?? 0)
152 );
153 },
154 gap * (list.children.length - 1),
155 );
156 setCollapseParentTitle(width > list.clientWidth);
157 };
158 measure();
159 const frame = requestAnimationFrame(measure);
160 document.fonts.addEventListener("loadingdone", measure);
161 const stopObserving = observeResize(list, measure);
162 return () => {
163 cancelAnimationFrame(frame);
164 document.fonts.removeEventListener("loadingdone", measure);
165 stopObserving();
166 };
167 }, [
168 // Title, font and rename changes resize the breadcrumb text without resizing the list, so it re-measures.
169 activeProjectName,
170 activeThreadTitle,
171 parentThreadLink,
172 interfaceFont,
173 isRenamingTitle,
174 ]);
175 const renameCommittedRef = useRef(false);
176 const titleButtonRef = useRef<HTMLButtonElement>(null);
177 const startRename = () => {
178 if (
179 !isServerThread ||
180 !readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)
181 )
182 return;
183 renameCommittedRef.current = false;
184 setRenaming({
185 environmentId: activeThreadEnvironmentId,
186 threadId: activeThreadId,
187 title: activeThreadTitle,
188 });
189 };
190 const commitRename = (title: string) => {
191 setRenaming(null);
192 if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return;
193 const resolution = resolveRenameCommit({
194 title,
195 originalTitle: renamingTitle ?? activeThreadTitle,
196 });
197 if (resolution.action === "reject-empty") {
198 toastManager.add({ type: "warning", title: gt`Thread title cannot be empty` });
199 return;
200 }
201 if (resolution.action === "noop") return;
202 void updateThreadMetadata({
203 environmentId: activeThreadEnvironmentId,
204 input: { threadId: activeThreadId, title: resolution.title },
205 }).then((result) => {
206 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
207 const error = squashAtomCommandFailure(result);
208 toastManager.add({
209 type: "error",
210 title: gt`Failed to rename thread`,
211 description: error instanceof Error ? error.message : gt`An error occurred.`,
212 });
213 }
214 });
215 };
216 const { openMenu, closeMenu } = useThreadActionMenu({
217 threadRef: isServerThread ? activeThreadRef : null,
218 projectCwd: activeProjectCwd,
219 onStartRename: startRename,
220 onFind: onFindInThread,
221 canShareWithGuest,
222 });
223 const openMenuFromTitle = (event: ReactMouseEvent<HTMLButtonElement>) => {
224 if (isTrailingDoubleClick(event.detail)) return;
225 const rect = event.currentTarget.getBoundingClientRect();
226 openMenu({ x: rect.left, y: rect.bottom + 4 }, contextMenuSourceOf(event));
227 };
228 // A native menu takes the second click, so only the in-page menu lets a double-click reach here.
229 const handleTitleDoubleClick = (event: ReactMouseEvent) => {
230 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
231 if ((event.target as HTMLElement).closest("[data-thread-title-chevron]") !== null) return;
232 closeMenu();
233 startRename();
234 };
235 const handleHeaderContextMenu = (event: ReactMouseEvent) => {
236 if (renamingTitle !== null) return;
237 if (!isServerThread && onOpenProjectSettings === undefined) return;
238 event.preventDefault();
239 if (!isServerThread) {
240 const api = readLocalApi();
241 if (!api) return;
242 void api.contextMenu
243 .show(
244 [{ id: "project-settings", label: gt`Project settings`, icon: "settings" }],
245 { x: event.clientX, y: event.clientY },
246 contextMenuSourceOf(event),
247 )
248 .then((action) => {
249 if (action === "project-settings") onOpenProjectSettings?.();
250 });
251 return;
252 }
253 openMenu({ x: event.clientX, y: event.clientY }, contextMenuSourceOf(event));
254 };
255 const handleRenameKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
256 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
257 if (event.key === "Enter") {
258 renameCommittedRef.current = true;
259 commitRename(event.currentTarget.value);
260 } else if (event.key === "Escape") {
261 event.preventDefault();
262 renameCommittedRef.current = true;
263 flushSync(() => setRenaming(null));
264 titleButtonRef.current?.focus({ preventScroll: true });
265 }
266 };
267 return (
268 <div
269 ref={breadcrumbContainerRef}
270 className={cn(
271 "flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
272 rightPanelOpen ? "pr-10" : "pr-24",
273 )}
274 onContextMenu={handleHeaderContextMenu}
275 >
276 <WorkspaceBreadcrumb
277 ariaLabel={gt`Thread breadcrumb`}
278 className="flex-1 overflow-clip [overflow-clip-margin:2px]"
279 >
280 {activeProject ? (
281 <>
282 <WorkspaceBreadcrumbItem className="shrink">
283 <SharedTooltipTrigger
284 render={
285 <button
286 type="button"
287 aria-label={gt`New thread in ${{ project: activeProjectName }}`}
288 onClick={onNewThreadInProject}
289 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-inset focus-visible:ring-ring"
290 />
291 }
292 label={
293 <>
294 <T>
295 New thread in <Var>{activeProjectName}</Var>
296 </T>
297 </>
298 }
299 >
300 <ProjectFavicon project={activeProject} className="size-3.5" />
301 <MiddleTruncate
302 data-slot="workspace-breadcrumb-text"
303 value={activeProjectName ?? ""}
304 showTitle={false}
305 variant="cap-aligned"
306 />
307 </SharedTooltipTrigger>
308 </WorkspaceBreadcrumbItem>
309 <WorkspaceBreadcrumbSeparator>
310 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
311 </WorkspaceBreadcrumbSeparator>
312 </>
313 ) : null}
314 {parentThreadLink ? (
315 <>
316 <WorkspaceBreadcrumbItem>
317 <SharedTooltipTrigger
318 render={
319 <button
320 type="button"
321 aria-label={gt`Open parent thread: ${{ title: parentThreadLink.title }}`}
322 onClick={() => onOpenThread(parentThreadLink.threadId)}
323 className="inline-flex min-w-0 max-w-full cursor-pointer items-center rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
324 />
325 }
326 label={parentThreadLink.title}
327 >
328 <WorkspaceBreadcrumbText
329 aria-hidden
330 className={collapseParentTitle ? "w-0" : undefined}
331 >
332 {parentThreadLink.title}
333 </WorkspaceBreadcrumbText>
334 {collapseParentTitle ? (
335 <span aria-hidden data-parent-breadcrumb-ellipsis>
336 ...
337 </span>
338 ) : null}
339 </SharedTooltipTrigger>
340 </WorkspaceBreadcrumbItem>
341 <WorkspaceBreadcrumbSeparator>
342 <WorkspaceBreadcrumbText>/</WorkspaceBreadcrumbText>
343 </WorkspaceBreadcrumbSeparator>
344 </>
345 ) : null}
346 <WorkspaceBreadcrumbItem current className="min-w-10 flex-1">
347 {renamingTitle !== null ? (
348 <input
349 autoFocus
350 dir="auto"
351 aria-label={gt`Thread title`}
352 className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-inset ring-ring/50 focus:ring-ring"
353 defaultValue={renamingTitle}
354 onBlur={(event) => {
355 if (renameCommittedRef.current) return;
356 if (
357 event.relatedTarget instanceof HTMLElement &&
358 event.relatedTarget.closest("button")
359 ) {
360 setRenaming(null);
361 return;
362 }
363 commitRename(event.currentTarget.value);
364 }}
365 onFocus={(event) => event.currentTarget.select()}
366 onKeyDown={handleRenameKeyDown}
367 />
368 ) : isServerThread ? (
369 <SharedTooltipTrigger
370 render={
371 <button
372 ref={titleButtonRef}
373 type="button"
374 aria-label={gt`Thread actions for ${{ title: activeThreadTitle }}`}
375 aria-haspopup="menu"
376 onClick={openMenuFromTitle}
377 onDoubleClick={canOperateThread ? handleTitleDoubleClick : undefined}
378 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-inset focus-visible:ring-ring"
379 />
380 }
381 label={activeThreadTitle}
382 >
383 <h2 className="min-w-0" dir={textDirection(activeThreadTitle)}>
384 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
385 </h2>
386 <ChevronDownIcon
387 aria-hidden
388 data-thread-title-chevron
389 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"
390 />
391 </SharedTooltipTrigger>
392 ) : (
393 <SharedTooltipTrigger
394 render={
395 <h2
396 aria-label={activeThreadTitle}
397 className="min-w-0 flex-1"
398 dir={textDirection(activeThreadTitle)}
399 />
400 }
401 label={activeThreadTitle}
402 >
403 <WorkspaceBreadcrumbText>{activeThreadTitle}</WorkspaceBreadcrumbText>
404 </SharedTooltipTrigger>
405 )}
406 {renamingTitle === null && activeThreadLinkOrigin ? (
407 <SharedTooltipTrigger
408 render={<Badge variant="info" size="sm" />}
409 label={
410 <>
411 <T>
412 Started by an agent on <Var>{activeThreadLinkOrigin}</Var> through a linked
413 environment.
414 </T>
415 </>
416 }
417 >
418 <T>
419 From <Var>{activeThreadLinkOrigin}</Var>
420 </T>
421 </SharedTooltipTrigger>
422 ) : null}
423 </WorkspaceBreadcrumbItem>
424 </WorkspaceBreadcrumb>
425 {isServerThread ? <GuestShareIndicator threadRef={activeThreadRef} /> : null}
426 </div>
427 );
428});