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

Sidebar.tsx

1,420 lines53.5 KB

1import {
2 ArrowLeftIcon,
3 ChevronRightIcon,
4 FolderIcon,
5 GitPullRequestIcon,
6 PlusIcon,
7 RocketIcon,
8 SettingsIcon,
9 SquarePenIcon,
10 TerminalIcon,
11} from "lucide-react";
12import { useCallback, useEffect, useMemo, useRef, useState } from "react";
13import {
14 DEFAULT_RUNTIME_MODE,
15 DEFAULT_MODEL_BY_PROVIDER,
16 type DesktopUpdateState,
17 ProjectId,
18 ThreadId,
19 type GitStatusResult,
20 type ResolvedKeybindingsConfig,
21} from "@t3tools/contracts";
22import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
23import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
24import { useAppSettings } from "../appSettings";
25import { isElectron } from "../env";
26import { APP_STAGE_LABEL } from "../branding";
27import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
28import { useStore } from "../store";
29import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
30import { type Thread } from "../types";
31import { derivePendingApprovals } from "../session-logic";
32import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
33import { serverConfigQueryOptions } from "../lib/serverReactQuery";
34import { readNativeApi } from "../nativeApi";
35import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
36import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
37import { toastManager } from "./ui/toast";
38import {
39 getDesktopUpdateActionError,
40 getDesktopUpdateButtonTooltip,
41 isDesktopUpdateButtonDisabled,
42 resolveDesktopUpdateButtonAction,
43 shouldHighlightDesktopUpdateError,
44 shouldShowDesktopUpdateButton,
45 shouldToastDesktopUpdateActionResult,
46} from "./desktopUpdate.logic";
47import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
48import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
49import {
50 SidebarContent,
51 SidebarFooter,
52 SidebarGroup,
53 SidebarHeader,
54 SidebarMenuAction,
55 SidebarMenu,
56 SidebarMenuButton,
57 SidebarMenuItem,
58 SidebarMenuSub,
59 SidebarMenuSubButton,
60 SidebarMenuSubItem,
61 SidebarSeparator,
62 SidebarTrigger,
63} from "./ui/sidebar";
64import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
65import { isNonEmpty as isNonEmptyString } from "effect/String";
66​
67const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
68const THREAD_PREVIEW_LIMIT = 6;
69​
70async function copyTextToClipboard(text: string): Promise<void> {
71 if (typeof navigator === "undefined" || navigator.clipboard?.writeText === undefined) {
72 throw new Error("Clipboard API unavailable.");
73 }
74 await navigator.clipboard.writeText(text);
76​
77function formatRelativeTime(iso: string): string {
78 const diff = Date.now() - new Date(iso).getTime();
79 const minutes = Math.floor(diff / 60_000);
80 if (minutes < 1) return "just now";
81 if (minutes < 60) return `${minutes}m ago`;
82 const hours = Math.floor(minutes / 60);
83 if (hours < 24) return `${hours}h ago`;
84 return `${Math.floor(hours / 24)}d ago`;
86​
87interface ThreadStatusPill {
88 label: "Working" | "Connecting" | "Completed" | "Pending Approval";
89 colorClass: string;
90 dotClass: string;
91 pulse: boolean;
93​
94interface TerminalStatusIndicator {
95 label: "Terminal process running";
96 colorClass: string;
97 pulse: boolean;
99​
100interface PrStatusIndicator {
101 label: "PR open" | "PR closed" | "PR merged";
102 colorClass: string;
103 tooltip: string;
104 url: string;
106​
107type ThreadPr = GitStatusResult["pr"];
108​
109function hasUnseenCompletion(thread: Thread): boolean {
110 if (!thread.latestTurn?.completedAt) return false;
111 const completedAt = Date.parse(thread.latestTurn.completedAt);
112 if (Number.isNaN(completedAt)) return false;
113 if (!thread.lastVisitedAt) return true;
114​
115 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
116 if (Number.isNaN(lastVisitedAt)) return true;
117 return completedAt > lastVisitedAt;
119​
120function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
121 if (hasPendingApprovals) {
122 return {
123 label: "Pending Approval",
124 colorClass: "text-amber-600 dark:text-amber-300/90",
125 dotClass: "bg-amber-500 dark:bg-amber-300/90",
126 pulse: false,
127 };
128 }
129​
130 if (thread.session?.status === "running") {
131 return {
132 label: "Working",
133 colorClass: "text-sky-600 dark:text-sky-300/80",
134 dotClass: "bg-sky-500 dark:bg-sky-300/80",
135 pulse: true,
136 };
137 }
138​
139 if (thread.session?.status === "connecting") {
140 return {
141 label: "Connecting",
142 colorClass: "text-sky-600 dark:text-sky-300/80",
143 dotClass: "bg-sky-500 dark:bg-sky-300/80",
144 pulse: true,
145 };
146 }
147​
148 if (hasUnseenCompletion(thread)) {
149 return {
150 label: "Completed",
151 colorClass: "text-emerald-600 dark:text-emerald-300/90",
152 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
153 pulse: false,
154 };
155 }
156​
157 return null;
159​
160function terminalStatusFromRunningIds(
161 runningTerminalIds: string[],
162): TerminalStatusIndicator | null {
163 if (runningTerminalIds.length === 0) {
164 return null;
165 }
166 return {
167 label: "Terminal process running",
168 colorClass: "text-teal-600 dark:text-teal-300/90",
169 pulse: true,
170 };
172​
173function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
174 if (!pr) return null;
175​
176 if (pr.state === "open") {
177 return {
178 label: "PR open",
179 colorClass: "text-emerald-600 dark:text-emerald-300/90",
180 tooltip: `#${pr.number} PR open: ${pr.title}`,
181 url: pr.url,
182 };
183 }
184 if (pr.state === "closed") {
185 return {
186 label: "PR closed",
187 colorClass: "text-zinc-500 dark:text-zinc-400/80",
188 tooltip: `#${pr.number} PR closed: ${pr.title}`,
189 url: pr.url,
190 };
191 }
192 if (pr.state === "merged") {
193 return {
194 label: "PR merged",
195 colorClass: "text-violet-600 dark:text-violet-300/90",
196 tooltip: `#${pr.number} PR merged: ${pr.title}`,
197 url: pr.url,
198 };
199 }
200 return null;
202​
203function T3Wordmark() {
204 return (
205 <svg
206 aria-label="T3"
207 className="h-2.5 w-auto shrink-0 text-foreground"
208 viewBox="15.5309 37 94.3941 56.96"
209 xmlns="http://www.w3.org/2000/svg"
210 >
211 <path
212 d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
213 fill="currentColor"
214 />
215 </svg>
216 );
218​
219/**
220 * Derives the server's HTTP origin (scheme + host + port) from the same
221 * sources WsTransport uses, converting ws(s) to http(s).
222 */
223function getServerHttpOrigin(): string {
224 const bridgeUrl = window.desktopBridge?.getWsUrl();
225 const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
226 const wsUrl =
227 bridgeUrl && bridgeUrl.length > 0
228 ? bridgeUrl
229 : envUrl && envUrl.length > 0
230 ? envUrl
231 : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
232 // Parse to extract just the origin, dropping path/query (e.g. ?token=…)
233 const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
234 try {
235 return new URL(httpUrl).origin;
236 } catch {
237 return httpUrl;
238 }
240​
241const serverHttpOrigin = getServerHttpOrigin();
242​
243function ProjectFavicon({ cwd }: { cwd: string }) {
244 const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
245​
246 const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
247​
248 if (status === "error") {
249 return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
250 }
251​
252 return (
253 <img
254 src={src}
255 alt=""
256 className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
257 onLoad={() => setStatus("loaded")}
258 onError={() => setStatus("error")}
259 />
260 );
262​
263export default function Sidebar() {
264 const projects = useStore((store) => store.projects);
265 const threads = useStore((store) => store.threads);
266 const markThreadUnread = useStore((store) => store.markThreadUnread);
267 const toggleProject = useStore((store) => store.toggleProject);
268 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
269 const getDraftThreadByProjectId = useComposerDraftStore(
270 (store) => store.getDraftThreadByProjectId,
271 );
272 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
273 const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
274 const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
275 const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
276 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
277 const clearProjectDraftThreadId = useComposerDraftStore(
278 (store) => store.clearProjectDraftThreadId,
279 );
280 const clearProjectDraftThreadById = useComposerDraftStore(
281 (store) => store.clearProjectDraftThreadById,
282 );
283 const navigate = useNavigate();
284 const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
285 const { settings: appSettings } = useAppSettings();
286 const routeThreadId = useParams({
287 strict: false,
288 select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
289 });
290 const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
291 ...serverConfigQueryOptions(),
292 select: (config) => config.keybindings,
293 });
294 const queryClient = useQueryClient();
295 const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
296 const [addingProject, setAddingProject] = useState(false);
297 const [newCwd, setNewCwd] = useState("");
298 const [isPickingFolder, setIsPickingFolder] = useState(false);
299 const [isAddingProject, setIsAddingProject] = useState(false);
300 const [addProjectError, setAddProjectError] = useState<string | null>(null);
301 const addProjectInputRef = useRef<HTMLInputElement | null>(null);
302 const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
303 const [renamingTitle, setRenamingTitle] = useState("");
304 const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
305 ReadonlySet<ProjectId>
306 >(() => new Set());
307 const renamingCommittedRef = useRef(false);
308 const renamingInputRef = useRef<HTMLInputElement | null>(null);
309 const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
310 const pendingApprovalByThreadId = useMemo(() => {
311 const map = new Map<ThreadId, boolean>();
312 for (const thread of threads) {
313 map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
314 }
315 return map;
316 }, [threads]);
317 const projectCwdById = useMemo(
318 () => new Map(projects.map((project) => [project.id, project.cwd] as const)),
319 [projects],
320 );
321 const threadGitTargets = useMemo(
322 () =>
323 threads.map((thread) => ({
324 threadId: thread.id,
325 branch: thread.branch,
326 cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
327 })),
328 [projectCwdById, threads],
329 );
330 const threadGitStatusCwds = useMemo(
331 () => [
332 ...new Set(
333 threadGitTargets
334 .filter((target) => target.branch !== null)
335 .map((target) => target.cwd)
336 .filter((cwd): cwd is string => cwd !== null),
337 ),
338 ],
339 [threadGitTargets],
340 );
341 const threadGitStatusQueries = useQueries({
342 queries: threadGitStatusCwds.map((cwd) => ({
343 ...gitStatusQueryOptions(cwd),
344 staleTime: 30_000,
345 refetchInterval: 60_000,
346 })),
347 });
348 const prByThreadId = useMemo(() => {
349 const statusByCwd = new Map<string, GitStatusResult>();
350 for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
351 const cwd = threadGitStatusCwds[index];
352 if (!cwd) continue;
353 const status = threadGitStatusQueries[index]?.data;
354 if (status) {
355 statusByCwd.set(cwd, status);
356 }
357 }
358​
359 const map = new Map<ThreadId, ThreadPr>();
360 for (const target of threadGitTargets) {
361 const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
362 const branchMatches =
363 target.branch !== null && status?.branch !== null && status?.branch === target.branch;
364 map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
365 }
366 return map;
367 }, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
368​
369 const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
370 event.preventDefault();
371 event.stopPropagation();
372​
373 const api = readNativeApi();
374 if (!api) {
375 toastManager.add({
376 type: "error",
377 title: "Link opening is unavailable.",
378 });
379 return;
380 }
381​
382 void api.shell.openExternal(prUrl).catch((error) => {
383 toastManager.add({
384 type: "error",
385 title: "Unable to open PR link",
386 description: error instanceof Error ? error.message : "An error occurred.",
387 });
388 });
389 }, []);
390​
391 const handleNewThread = useCallback(
392 (
393 projectId: ProjectId,
394 options?: {
395 branch?: string | null;
396 worktreePath?: string | null;
397 envMode?: DraftThreadEnvMode;
398 },
399 ): Promise<void> => {
400 const hasBranchOption = options?.branch !== undefined;
401 const hasWorktreePathOption = options?.worktreePath !== undefined;
402 const hasEnvModeOption = options?.envMode !== undefined;
403 const storedDraftThread = getDraftThreadByProjectId(projectId);
404 if (storedDraftThread) {
405 return (async () => {
406 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
407 setDraftThreadContext(storedDraftThread.threadId, {
408 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
409 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
410 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
411 });
412 }
413 setProjectDraftThreadId(projectId, storedDraftThread.threadId);
414 if (routeThreadId === storedDraftThread.threadId) {
415 return;
416 }
417 await navigate({
418 to: "/$threadId",
419 params: { threadId: storedDraftThread.threadId },
420 });
421 })();
422 }
423 clearProjectDraftThreadId(projectId);
424​
425 const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
426 if (activeDraftThread && routeThreadId && activeDraftThread.projectId === projectId) {
427 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
428 setDraftThreadContext(routeThreadId, {
429 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
430 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
431 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
432 });
433 }
434 setProjectDraftThreadId(projectId, routeThreadId);
435 return Promise.resolve();
436 }
437 const threadId = newThreadId();
438 const createdAt = new Date().toISOString();
439 return (async () => {
440 setProjectDraftThreadId(projectId, threadId, {
441 createdAt,
442 branch: options?.branch ?? null,
443 worktreePath: options?.worktreePath ?? null,
444 envMode: options?.envMode ?? "local",
445 runtimeMode: DEFAULT_RUNTIME_MODE,
446 });
447​
448 await navigate({
449 to: "/$threadId",
450 params: { threadId },
451 });
452 })();
453 },
454 [
455 clearProjectDraftThreadId,
456 getDraftThreadByProjectId,
457 navigate,
458 getDraftThread,
459 routeThreadId,
460 setDraftThreadContext,
461 setProjectDraftThreadId,
462 ],
463 );
464​
465 const focusMostRecentThreadForProject = useCallback(
466 (projectId: ProjectId) => {
467 const latestThread = threads
468 .filter((thread) => thread.projectId === projectId)
469 .toSorted((a, b) => {
470 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
471 if (byDate !== 0) return byDate;
472 return b.id.localeCompare(a.id);
473 })[0];
474 if (!latestThread) return;
475​
476 void navigate({
477 to: "/$threadId",
478 params: { threadId: latestThread.id },
479 });
480 },
481 [navigate, threads],
482 );
483​
484 const addProjectFromPath = useCallback(
485 async (rawCwd: string) => {
486 const cwd = rawCwd.trim();
487 if (!cwd || isAddingProject) return;
488 const api = readNativeApi();
489 if (!api) return;
490​
491 setIsAddingProject(true);
492 const finishAddingProject = () => {
493 setIsAddingProject(false);
494 setNewCwd("");
495 setAddProjectError(null);
496 setAddingProject(false);
497 };
498​
499 const existing = projects.find((project) => project.cwd === cwd);
500 if (existing) {
501 focusMostRecentThreadForProject(existing.id);
502 finishAddingProject();
503 return;
504 }
505​
506 const projectId = newProjectId();
507 const createdAt = new Date().toISOString();
508 const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
509 try {
510 await api.orchestration.dispatchCommand({
511 type: "project.create",
512 commandId: newCommandId(),
513 projectId,
514 title,
515 workspaceRoot: cwd,
516 defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
517 createdAt,
518 });
519 await handleNewThread(projectId).catch(() => undefined);
520 } catch (error) {
521 setIsAddingProject(false);
522 setAddProjectError(
523 error instanceof Error ? error.message : "An error occurred while adding the project.",
524 );
525 return;
526 }
527 finishAddingProject();
528 },
529 [focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
530 );
531​
532 const handleAddProject = () => {
533 void addProjectFromPath(newCwd);
534 };
535​
536 const handlePickFolder = async () => {
537 const api = readNativeApi();
538 if (!api || isPickingFolder) return;
539 setIsPickingFolder(true);
540 let pickedPath: string | null = null;
541 try {
542 pickedPath = await api.dialogs.pickFolder();
543 } catch {
544 // Ignore picker failures and leave the current thread selection unchanged.
545 }
546 if (pickedPath) {
547 await addProjectFromPath(pickedPath);
548 } else {
549 addProjectInputRef.current?.focus();
550 }
551 setIsPickingFolder(false);
552 };
553​
554 const cancelRename = useCallback(() => {
555 setRenamingThreadId(null);
556 renamingInputRef.current = null;
557 }, []);
558​
559 const commitRename = useCallback(
560 async (threadId: ThreadId, newTitle: string, originalTitle: string) => {
561 const finishRename = () => {
562 setRenamingThreadId((current) => {
563 if (current !== threadId) return current;
564 renamingInputRef.current = null;
565 return null;
566 });
567 };
568​
569 const trimmed = newTitle.trim();
570 if (trimmed.length === 0) {
571 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
572 finishRename();
573 return;
574 }
575 if (trimmed === originalTitle) {
576 finishRename();
577 return;
578 }
579 const api = readNativeApi();
580 if (!api) {
581 finishRename();
582 return;
583 }
584 try {
585 await api.orchestration.dispatchCommand({
586 type: "thread.meta.update",
587 commandId: newCommandId(),
588 threadId,
589 title: trimmed,
590 });
591 } catch (error) {
592 toastManager.add({
593 type: "error",
594 title: "Failed to rename thread",
595 description: error instanceof Error ? error.message : "An error occurred.",
596 });
597 }
598 finishRename();
599 },
600 [],
601 );
602​
603 const handleThreadContextMenu = useCallback(
604 async (threadId: ThreadId, position: { x: number; y: number }) => {
605 const api = readNativeApi();
606 if (!api) return;
607 const clicked = await api.contextMenu.show(
608 [
609 { id: "rename", label: "Rename thread" },
610 { id: "mark-unread", label: "Mark unread" },
611 { id: "copy-thread-id", label: "Copy Thread ID" },
612 { id: "delete", label: "Delete", destructive: true },
613 ],
614 position,
615 );
616 const thread = threads.find((t) => t.id === threadId);
617 if (!thread) return;
618​
619 if (clicked === "rename") {
620 setRenamingThreadId(threadId);
621 setRenamingTitle(thread.title);
622 renamingCommittedRef.current = false;
623 return;
624 }
625​
626 if (clicked === "mark-unread") {
627 markThreadUnread(threadId);
628 return;
629 }
630 if (clicked === "copy-thread-id") {
631 try {
632 await copyTextToClipboard(threadId);
633 toastManager.add({
634 type: "success",
635 title: "Thread ID copied",
636 description: threadId,
637 });
638 } catch (error) {
639 toastManager.add({
640 type: "error",
641 title: "Failed to copy thread ID",
642 description: error instanceof Error ? error.message : "An error occurred.",
643 });
644 }
645 return;
646 }
647 if (clicked !== "delete") return;
648 if (appSettings.confirmThreadDelete) {
649 const confirmed = await api.dialogs.confirm(
650 [
651 `Delete thread "${thread.title}"?`,
652 "This permanently clears conversation history for this thread.",
653 ].join("\n"),
654 );
655 if (!confirmed) {
656 return;
657 }
658 }
659 const threadProject = projects.find((project) => project.id === thread.projectId);
660 const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
661 const displayWorktreePath = orphanedWorktreePath
662 ? formatWorktreePathForDisplay(orphanedWorktreePath)
663 : null;
664 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
665 const shouldDeleteWorktree =
666 canDeleteWorktree &&
667 (await api.dialogs.confirm(
668 [
669 "This thread is the only one linked to this worktree:",
670 displayWorktreePath ?? orphanedWorktreePath,
671 "",
672 "Delete the worktree too?",
673 ].join("\n"),
674 ));
675​
676 if (thread.session && thread.session.status !== "closed") {
677 await api.orchestration
678 .dispatchCommand({
679 type: "thread.session.stop",
680 commandId: newCommandId(),
681 threadId,
682 createdAt: new Date().toISOString(),
683 })
684 .catch(() => undefined);
685 }
686​
687 try {
688 await api.terminal.close({
689 threadId,
690 deleteHistory: true,
691 });
692 } catch {
693 // Terminal may already be closed
694 }
695​
696 const shouldNavigateToFallback = routeThreadId === threadId;
697 const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
698 await api.orchestration.dispatchCommand({
699 type: "thread.delete",
700 commandId: newCommandId(),
701 threadId,
702 });
703 clearComposerDraftForThread(threadId);
704 clearProjectDraftThreadById(thread.projectId, thread.id);
705 clearTerminalState(threadId);
706 if (shouldNavigateToFallback) {
707 if (fallbackThreadId) {
708 void navigate({
709 to: "/$threadId",
710 params: { threadId: fallbackThreadId },
711 replace: true,
712 });
713 } else {
714 void navigate({ to: "/", replace: true });
715 }
716 }
717​
718 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
719 return;
720 }
721​
722 try {
723 await removeWorktreeMutation.mutateAsync({
724 cwd: threadProject.cwd,
725 path: orphanedWorktreePath,
726 force: true,
727 });
728 } catch (error) {
729 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
730 console.error("Failed to remove orphaned worktree after thread deletion", {
731 threadId,
732 projectCwd: threadProject.cwd,
733 worktreePath: orphanedWorktreePath,
734 error,
735 });
736 toastManager.add({
737 type: "error",
738 title: "Thread deleted, but worktree removal failed",
739 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
740 });
741 }
742 },
743 [
744 appSettings.confirmThreadDelete,
745 clearComposerDraftForThread,
746 clearProjectDraftThreadById,
747 clearTerminalState,
748 markThreadUnread,
749 navigate,
750 projects,
751 removeWorktreeMutation,
752 routeThreadId,
753 threads,
754 ],
755 );
756​
757 const handleProjectContextMenu = useCallback(
758 async (projectId: ProjectId, position: { x: number; y: number }) => {
759 const api = readNativeApi();
760 if (!api) return;
761 const clicked = await api.contextMenu.show(
762 [{ id: "delete", label: "Delete", destructive: true }],
763 position,
764 );
765 if (clicked !== "delete") return;
766​
767 const project = projects.find((entry) => entry.id === projectId);
768 if (!project) return;
769​
770 const projectThreads = threads.filter((thread) => thread.projectId === projectId);
771 if (projectThreads.length > 0) {
772 toastManager.add({
773 type: "warning",
774 title: "Project is not empty",
775 description: "Delete all threads in this project before deleting it.",
776 });
777 return;
778 }
779​
780 const confirmed = await api.dialogs.confirm(
781 [`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
782 );
783 if (!confirmed) return;
784​
785 try {
786 const projectDraftThread = getDraftThreadByProjectId(projectId);
787 if (projectDraftThread) {
788 clearComposerDraftForThread(projectDraftThread.threadId);
789 }
790 clearProjectDraftThreadId(projectId);
791 await api.orchestration.dispatchCommand({
792 type: "project.delete",
793 commandId: newCommandId(),
794 projectId,
795 });
796 } catch (error) {
797 const message = error instanceof Error ? error.message : "Unknown error deleting project.";
798 console.error("Failed to remove project", { projectId, error });
799 toastManager.add({
800 type: "error",
801 title: `Failed to delete "${project.name}"`,
802 description: message,
803 });
804 }
805 },
806 [
807 clearComposerDraftForThread,
808 clearProjectDraftThreadId,
809 getDraftThreadByProjectId,
810 projects,
811 threads,
812 ],
813 );
814​
815 useEffect(() => {
816 const onWindowKeyDown = (event: KeyboardEvent) => {
817 const activeThread = routeThreadId
818 ? threads.find((thread) => thread.id === routeThreadId)
819 : undefined;
820 const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
821 if (isChatNewLocalShortcut(event, keybindings)) {
822 const projectId =
823 activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
824 if (!projectId) return;
825 event.preventDefault();
826 void handleNewThread(projectId);
827 return;
828 }
829​
830 if (!isChatNewShortcut(event, keybindings)) return;
831 const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
832 if (!projectId) return;
833 event.preventDefault();
834 void handleNewThread(projectId, {
835 branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
836 worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
837 envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
838 });
839 };
840​
841 window.addEventListener("keydown", onWindowKeyDown);
842 return () => {
843 window.removeEventListener("keydown", onWindowKeyDown);
844 };
845 }, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
846​
847 useEffect(() => {
848 if (!isElectron) return;
849 const bridge = window.desktopBridge;
850 if (
851 !bridge ||
852 typeof bridge.getUpdateState !== "function" ||
853 typeof bridge.onUpdateState !== "function"
854 ) {
855 return;
856 }
857​
858 let disposed = false;
859 let receivedSubscriptionUpdate = false;
860 const unsubscribe = bridge.onUpdateState((nextState) => {
861 if (disposed) return;
862 receivedSubscriptionUpdate = true;
863 setDesktopUpdateState(nextState);
864 });
865​
866 void bridge
867 .getUpdateState()
868 .then((nextState) => {
869 if (disposed || receivedSubscriptionUpdate) return;
870 setDesktopUpdateState(nextState);
871 })
872 .catch(() => undefined);
873​
874 return () => {
875 disposed = true;
876 unsubscribe();
877 };
878 }, []);
879​
880 const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
881​
882 const desktopUpdateTooltip = desktopUpdateState
883 ? getDesktopUpdateButtonTooltip(desktopUpdateState)
884 : "Update available";
885​
886 const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
887 const desktopUpdateButtonAction = desktopUpdateState
888 ? resolveDesktopUpdateButtonAction(desktopUpdateState)
889 : "none";
890 const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
891 ? "cursor-not-allowed opacity-60"
892 : "hover:bg-accent hover:text-foreground";
893 const desktopUpdateButtonClasses =
894 desktopUpdateState?.status === "downloaded"
895 ? "text-emerald-500"
896 : desktopUpdateState?.status === "downloading"
897 ? "text-sky-400"
898 : shouldHighlightDesktopUpdateError(desktopUpdateState)
899 ? "text-rose-500 animate-pulse"
900 : "text-amber-500 animate-pulse";
901 const newThreadShortcutLabel = useMemo(
902 () =>
903 shortcutLabelForCommand(keybindings, "chat.newLocal") ??
904 shortcutLabelForCommand(keybindings, "chat.new"),
905 [keybindings],
906 );
907​
908 const handleDesktopUpdateButtonClick = useCallback(() => {
909 const bridge = window.desktopBridge;
910 if (!bridge || !desktopUpdateState) return;
911 if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;
912​
913 if (desktopUpdateButtonAction === "download") {
914 void bridge
915 .downloadUpdate()
916 .then((result) => {
917 if (result.completed) {
918 toastManager.add({
919 type: "success",
920 title: "Update downloaded",
921 description: "Restart the app from the update button to install it.",
922 });
923 }
924 if (!shouldToastDesktopUpdateActionResult(result)) return;
925 const actionError = getDesktopUpdateActionError(result);
926 if (!actionError) return;
927 toastManager.add({
928 type: "error",
929 title: "Could not download update",
930 description: actionError,
931 });
932 })
933 .catch((error) => {
934 toastManager.add({
935 type: "error",
936 title: "Could not start update download",
937 description: error instanceof Error ? error.message : "An unexpected error occurred.",
938 });
939 });
940 return;
941 }
942​
943 if (desktopUpdateButtonAction === "install") {
944 void bridge
945 .installUpdate()
946 .then((result) => {
947 if (!shouldToastDesktopUpdateActionResult(result)) return;
948 const actionError = getDesktopUpdateActionError(result);
949 if (!actionError) return;
950 toastManager.add({
951 type: "error",
952 title: "Could not install update",
953 description: actionError,
954 });
955 })
956 .catch((error) => {
957 toastManager.add({
958 type: "error",
959 title: "Could not install update",
960 description: error instanceof Error ? error.message : "An unexpected error occurred.",
961 });
962 });
963 }
964 }, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
965​
966 const expandThreadListForProject = useCallback((projectId: ProjectId) => {
967 setExpandedThreadListsByProject((current) => {
968 if (current.has(projectId)) return current;
969 const next = new Set(current);
970 next.add(projectId);
971 return next;
972 });
973 }, []);
974​
975 const collapseThreadListForProject = useCallback((projectId: ProjectId) => {
976 setExpandedThreadListsByProject((current) => {
977 if (!current.has(projectId)) return current;
978 const next = new Set(current);
979 next.delete(projectId);
980 return next;
981 });
982 }, []);
983​
984 const wordmark = (
985 <div className="flex items-center gap-2">
986 <SidebarTrigger className="shrink-0 md:hidden" />
987 <div className="flex min-w-0 flex-1 items-center gap-1 mt-1.5 ml-1">
988 <T3Wordmark />
989 <span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
990 Code
991 </span>
992 <span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
993 {APP_STAGE_LABEL}
994 </span>
995 </div>
996 </div>
997 );
998​
999 return (
1000 <>
1001 {isElectron ? (
1002 <>
1003 <SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px]">
1004 {wordmark}
1005 {showDesktopUpdateButton && (
1006 <Tooltip>
1007 <TooltipTrigger
1008 render={
1009 <button
1010 type="button"
1011 aria-label={desktopUpdateTooltip}
1012 aria-disabled={desktopUpdateButtonDisabled || undefined}
1013 disabled={desktopUpdateButtonDisabled}
1014 className={`inline-flex size-7 ml-auto mt-1.5 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
1015 onClick={handleDesktopUpdateButtonClick}
1017 <RocketIcon className="size-3.5" />
1018 </button>
1020 />
1021 <TooltipPopup side="bottom">{desktopUpdateTooltip}</TooltipPopup>
1022 </Tooltip>
1023 )}
1024 </SidebarHeader>
1025 </>
1026 ) : (
1027 <SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
1028 {wordmark}
1029 </SidebarHeader>
1030 )}
1031​
1032 <SidebarContent className="gap-0">
1033 <SidebarGroup className="px-2 py-2">
1034 <div className="mb-1 flex items-center justify-between px-2">
1035 <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
1036 Projects
1037 </span>
1038 <Tooltip>
1039 <TooltipTrigger
1040 render={
1041 <button
1042 type="button"
1043 aria-label="Add project"
1044 className="inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
1045 onClick={() => {
1046 setAddingProject((prev) => !prev);
1047 setAddProjectError(null);
1048 }}
1049 />
1052 <PlusIcon className="size-3.5" />
1053 </TooltipTrigger>
1054 <TooltipPopup side="right">Add project</TooltipPopup>
1055 </Tooltip>
1056 </div>
1057​
1058 {addingProject && (
1059 <div className="mb-2 px-1">
1060 {isElectron && (
1061 <button
1062 type="button"
1063 className="mb-1.5 flex w-full items-center justify-center gap-2 rounded-md border border-border bg-secondary py-1.5 text-xs text-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
1064 onClick={() => void handlePickFolder()}
1065 disabled={isPickingFolder || isAddingProject}
1067 <FolderIcon className="size-3.5" />
1068 {isPickingFolder ? "Picking folder..." : "Browse for folder"}
1069 </button>
1070 )}
1071 <div className="flex gap-1.5">
1072 <input
1073 ref={addProjectInputRef}
1074 className={`min-w-0 flex-1 rounded-md border bg-secondary px-2 py-1 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:outline-none ${
1075 addProjectError
1076 ? "border-red-500/70 focus:border-red-500"
1077 : "border-border focus:border-ring"
1078 }`}
1079 placeholder="/path/to/project"
1080 value={newCwd}
1081 onChange={(event) => {
1082 setNewCwd(event.target.value);
1083 setAddProjectError(null);
1084 }}
1085 onKeyDown={(event) => {
1086 if (event.key === "Enter") handleAddProject();
1087 if (event.key === "Escape") {
1088 setAddingProject(false);
1089 setAddProjectError(null);
1091 }}
1092 autoFocus
1093 />
1094 <button
1095 type="button"
1096 className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90 disabled:opacity-60"
1097 onClick={handleAddProject}
1098 disabled={isAddingProject}
1100 {isAddingProject ? "Adding..." : "Add"}
1101 </button>
1102 </div>
1103 {addProjectError && (
1104 <p className="mt-1 px-0.5 text-[11px] leading-tight text-red-400">
1105 {addProjectError}
1106 </p>
1107 )}
1108 <div className="mt-1.5 px-0.5">
1109 <button
1110 type="button"
1111 className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
1112 onClick={() => {
1113 setAddingProject(false);
1114 setAddProjectError(null);
1115 }}
1117 Cancel
1118 </button>
1119 </div>
1120 </div>
1121 )}
1122​
1123 <SidebarMenu>
1124 {projects.map((project) => {
1125 const projectThreads = threads
1126 .filter((thread) => thread.projectId === project.id)
1127 .toSorted((a, b) => {
1128 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
1129 if (byDate !== 0) return byDate;
1130 return b.id.localeCompare(a.id);
1131 });
1132 const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
1133 const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
1134 const visibleThreads =
1135 hasHiddenThreads && !isThreadListExpanded
1136 ? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
1137 : projectThreads;
1138​
1139 return (
1140 <Collapsible
1141 key={project.id}
1142 className="group/collapsible"
1143 open={project.expanded}
1144 onOpenChange={(open) => {
1145 if (open === project.expanded) return;
1146 toggleProject(project.id);
1147 }}
1149 <SidebarMenuItem>
1150 <div className="group/project-header relative">
1151 <CollapsibleTrigger
1152 render={
1153 <SidebarMenuButton
1154 size="sm"
1155 className="gap-2 px-2 py-1.5 text-left hover:bg-accent group-hover/project-header:bg-accent group-hover/project-header:text-sidebar-accent-foreground"
1156 />
1158 onContextMenu={(event) => {
1159 event.preventDefault();
1160 void handleProjectContextMenu(project.id, {
1161 x: event.clientX,
1162 y: event.clientY,
1163 });
1164 }}
1166 <ChevronRightIcon
1167 className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
1168 project.expanded ? "rotate-90" : ""
1169 }`}
1170 />
1171 <ProjectFavicon cwd={project.cwd} />
1172 <span className="flex-1 truncate text-xs font-medium text-foreground/90">
1173 {project.name}
1174 </span>
1175 </CollapsibleTrigger>
1176 <Tooltip>
1177 <TooltipTrigger
1178 render={
1179 <SidebarMenuAction
1180 render={
1181 <button
1182 type="button"
1183 aria-label={`Create new thread in ${project.name}`}
1184 />
1186 showOnHover
1187 className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
1188 onClick={(event) => {
1189 event.preventDefault();
1190 event.stopPropagation();
1191 void handleNewThread(project.id);
1192 }}
1194 <SquarePenIcon className="size-3.5" />
1195 </SidebarMenuAction>
1197 />
1198 <TooltipPopup side="top">
1199 {newThreadShortcutLabel
1200 ? `New thread (${newThreadShortcutLabel})`
1201 : "New thread"}
1202 </TooltipPopup>
1203 </Tooltip>
1204 </div>
1205​
1206 <CollapsibleContent>
1207 <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
1208 {visibleThreads.map((thread) => {
1209 const isActive = routeThreadId === thread.id;
1210 const threadStatus = threadStatusPill(
1211 thread,
1212 pendingApprovalByThreadId.get(thread.id) === true,
1213 );
1214 const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
1215 const terminalStatus = terminalStatusFromRunningIds(
1216 selectThreadTerminalState(terminalStateByThreadId, thread.id)
1217 .runningTerminalIds,
1218 );
1219​
1220 return (
1221 <SidebarMenuSubItem key={thread.id} className="w-full">
1222 <SidebarMenuSubButton
1223 render={<div role="button" tabIndex={0} />}
1224 size="sm"
1225 isActive={isActive}
1226 className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
1227 isActive
1228 ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
1229 : "text-muted-foreground"
1230 }`}
1231 onClick={() => {
1232 void navigate({
1233 to: "/$threadId",
1234 params: { threadId: thread.id },
1235 });
1236 }}
1237 onKeyDown={(event) => {
1238 if (event.key !== "Enter" && event.key !== " ") return;
1239 event.preventDefault();
1240 void navigate({
1241 to: "/$threadId",
1242 params: { threadId: thread.id },
1243 });
1244 }}
1245 onContextMenu={(event) => {
1246 event.preventDefault();
1247 void handleThreadContextMenu(thread.id, {
1248 x: event.clientX,
1249 y: event.clientY,
1250 });
1251 }}
1253 <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
1254 {prStatus && (
1255 <Tooltip>
1256 <TooltipTrigger
1257 render={
1258 <button
1259 type="button"
1260 aria-label={prStatus.tooltip}
1261 className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
1262 onClick={(event) => {
1263 openPrLink(event, prStatus.url);
1264 }}
1266 <GitPullRequestIcon className="size-3" />
1267 </button>
1269 />
1270 <TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
1271 </Tooltip>
1272 )}
1273 {threadStatus && (
1274 <span
1275 className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
1277 <span
1278 className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
1279 threadStatus.pulse ? "animate-pulse" : ""
1280 }`}
1281 />
1282 <span className="hidden md:inline">{threadStatus.label}</span>
1283 </span>
1284 )}
1285 {renamingThreadId === thread.id ? (
1286 <input
1287 ref={(el) => {
1288 if (el && renamingInputRef.current !== el) {
1289 renamingInputRef.current = el;
1290 el.focus();
1291 el.select();
1293 }}
1294 className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
1295 value={renamingTitle}
1296 onChange={(e) => setRenamingTitle(e.target.value)}
1297 onKeyDown={(e) => {
1298 e.stopPropagation();
1299 if (e.key === "Enter") {
1300 e.preventDefault();
1301 renamingCommittedRef.current = true;
1302 void commitRename(thread.id, renamingTitle, thread.title);
1303 } else if (e.key === "Escape") {
1304 e.preventDefault();
1305 renamingCommittedRef.current = true;
1306 cancelRename();
1308 }}
1309 onBlur={() => {
1310 if (!renamingCommittedRef.current) {
1311 void commitRename(thread.id, renamingTitle, thread.title);
1313 }}
1314 onClick={(e) => e.stopPropagation()}
1315 />
1316 ) : (
1317 <span className="min-w-0 flex-1 truncate text-xs">
1318 {thread.title}
1319 </span>
1320 )}
1321 </div>
1322 <div className="ml-auto flex shrink-0 items-center gap-1.5">
1323 {terminalStatus && (
1324 <span
1325 role="img"
1326 aria-label={terminalStatus.label}
1327 title={terminalStatus.label}
1328 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
1330 <TerminalIcon
1331 className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
1332 />
1333 </span>
1334 )}
1335 <span
1336 className={`text-[10px] ${
1337 isActive ? "text-foreground/65" : "text-muted-foreground/40"
1338 }`}
1340 {formatRelativeTime(thread.createdAt)}
1341 </span>
1342 </div>
1343 </SidebarMenuSubButton>
1344 </SidebarMenuSubItem>
1345 );
1346 })}
1347​
1348 {hasHiddenThreads && !isThreadListExpanded && (
1349 <SidebarMenuSubItem className="w-full">
1350 <SidebarMenuSubButton
1351 render={<button type="button" />}
1352 size="sm"
1353 className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
1354 onClick={() => {
1355 expandThreadListForProject(project.id);
1356 }}
1358 <span>Show more</span>
1359 </SidebarMenuSubButton>
1360 </SidebarMenuSubItem>
1361 )}
1362 {hasHiddenThreads && isThreadListExpanded && (
1363 <SidebarMenuSubItem className="w-full">
1364 <SidebarMenuSubButton
1365 render={<button type="button" />}
1366 size="sm"
1367 className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
1368 onClick={() => {
1369 collapseThreadListForProject(project.id);
1370 }}
1372 <span>Show less</span>
1373 </SidebarMenuSubButton>
1374 </SidebarMenuSubItem>
1375 )}
1376 </SidebarMenuSub>
1377 </CollapsibleContent>
1378 </SidebarMenuItem>
1379 </Collapsible>
1380 );
1381 })}
1382 </SidebarMenu>
1383​
1384 {projects.length === 0 && !addingProject && (
1385 <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
1386 No projects yet
1387 </div>
1388 )}
1389 </SidebarGroup>
1390 </SidebarContent>
1391​
1392 <SidebarSeparator />
1393 <SidebarFooter className="p-2">
1394 <SidebarMenu>
1395 <SidebarMenuItem>
1396 {isOnSettings ? (
1397 <SidebarMenuButton
1398 size="sm"
1399 className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
1400 onClick={() => window.history.back()}
1402 <ArrowLeftIcon className="size-3.5" />
1403 <span className="text-xs">Back</span>
1404 </SidebarMenuButton>
1405 ) : (
1406 <SidebarMenuButton
1407 size="sm"
1408 className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
1409 onClick={() => void navigate({ to: "/settings" })}
1411 <SettingsIcon className="size-3.5" />
1412 <span className="text-xs">Settings</span>
1413 </SidebarMenuButton>
1414 )}
1415 </SidebarMenuItem>
1416 </SidebarMenu>
1417 </SidebarFooter>
1418 </>
1419 );