Open History to see the last commit
1import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
2import { useCallback, useEffect, useMemo, useState } from "react";
3import {
4 DEFAULT_MODEL,
5 ProjectId,
6 ThreadId,
7 type GitStatusResult,
8 type ResolvedKeybindingsConfig,
9} from "@t3tools/contracts";
10import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
11import { useNavigate, useParams } from "@tanstack/react-router";
12import { useAppSettings } from "../appSettings";
13import { isElectron } from "../env";
14import { APP_STAGE_LABEL } from "../branding";
15import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
16import { useStore } from "../store";
17import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
18import { type Thread } from "../types";
19import { derivePendingApprovals } from "../session-logic";
20import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
21import { serverConfigQueryOptions } from "../lib/serverReactQuery";
22import { readNativeApi } from "../nativeApi";
23import { toastManager } from "./ui/toast";
24import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
25import {
26 SidebarContent,
27 SidebarFooter,
28 SidebarGroup,
29 SidebarHeader,
30 SidebarMenu,
31 SidebarMenuButton,
32 SidebarMenuItem,
33 SidebarMenuSub,
34 SidebarMenuSubButton,
35 SidebarMenuSubItem,
36 SidebarSeparator,
37 SidebarTrigger,
38} from "./ui/sidebar";
39import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
40import { isNonEmpty as isNonEmptyString } from "effect/String";
41
42const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
43
44function formatRelativeTime(iso: string): string {
45 const diff = Date.now() - new Date(iso).getTime();
46 const minutes = Math.floor(diff / 60_000);
47 if (minutes < 1) return "just now";
48 if (minutes < 60) return `${minutes}m ago`;
49 const hours = Math.floor(minutes / 60);
50 if (hours < 24) return `${hours}h ago`;
51 return `${Math.floor(hours / 24)}d ago`;
52}
53
54interface ThreadStatusPill {
55 label: "Working" | "Connecting" | "Completed" | "Pending Approval";
56 colorClass: string;
57 dotClass: string;
58 pulse: boolean;
59}
60
61interface TerminalStatusIndicator {
62 label: "Terminal process running";
63 colorClass: string;
64 pulse: boolean;
65}
66
67interface PrStatusIndicator {
68 label: "PR open" | "PR closed" | "PR merged";
69 colorClass: string;
70}
71
72type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
73
74function hasUnseenCompletion(thread: Thread): boolean {
75 if (!thread.latestTurn?.completedAt) return false;
76 const completedAt = Date.parse(thread.latestTurn.completedAt);
77 if (Number.isNaN(completedAt)) return false;
78 if (!thread.lastVisitedAt) return true;
79
80 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
81 if (Number.isNaN(lastVisitedAt)) return true;
82 return completedAt > lastVisitedAt;
83}
84
85function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
86 if (hasPendingApprovals) {
87 return {
88 label: "Pending Approval",
89 colorClass: "text-amber-600 dark:text-amber-300/90",
90 dotClass: "bg-amber-500 dark:bg-amber-300/90",
91 pulse: false,
92 };
93 }
94
95 if (thread.session?.status === "running") {
96 return {
97 label: "Working",
98 colorClass: "text-sky-600 dark:text-sky-300/80",
99 dotClass: "bg-sky-500 dark:bg-sky-300/80",
100 pulse: true,
101 };
102 }
103
104 if (thread.session?.status === "connecting") {
105 return {
106 label: "Connecting",
107 colorClass: "text-sky-600 dark:text-sky-300/80",
108 dotClass: "bg-sky-500 dark:bg-sky-300/80",
109 pulse: true,
110 };
111 }
112
113 if (hasUnseenCompletion(thread)) {
114 return {
115 label: "Completed",
116 colorClass: "text-emerald-600 dark:text-emerald-300/90",
117 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
118 pulse: false,
119 };
120 }
121
122 return null;
123}
124
125function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
126 if (thread.runningTerminalIds.length === 0) {
127 return null;
128 }
129 return {
130 label: "Terminal process running",
131 colorClass: "text-teal-600 dark:text-teal-300/90",
132 pulse: true,
133 };
134}
135
136function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
137 if (prState === "open") {
138 return {
139 label: "PR open",
140 colorClass: "text-emerald-600 dark:text-emerald-300/90",
141 };
142 }
143 if (prState === "closed") {
144 return {
145 label: "PR closed",
146 colorClass: "text-zinc-500 dark:text-zinc-400/80",
147 };
148 }
149 if (prState === "merged") {
150 return {
151 label: "PR merged",
152 colorClass: "text-violet-600 dark:text-violet-300/90",
153 };
154 }
155 return null;
156}
157
158function T3Wordmark() {
159 return (
160 <svg
161 aria-label="T3"
162 className="h-3 w-auto shrink-0 text-foreground"
163 viewBox="15.5309 37 94.3941 56.96"
164 xmlns="http://www.w3.org/2000/svg"
165 >
166 <path
167 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"
168 fill="currentColor"
169 />
170 </svg>
171 );
172}
173
174/**
175 * Derives the server's HTTP origin (scheme + host + port) from the same
176 * sources WsTransport uses, converting ws(s) to http(s).
177 */
178function getServerHttpOrigin(): string {
179 const bridgeUrl = window.desktopBridge?.getWsUrl();
180 const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
181 const wsUrl =
182 bridgeUrl && bridgeUrl.length > 0
183 ? bridgeUrl
184 : envUrl && envUrl.length > 0
185 ? envUrl
186 : `ws://${window.location.hostname}:${window.location.port}`;
187 // Parse to extract just the origin, dropping path/query (e.g. ?token=…)
188 const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
189 try {
190 return new URL(httpUrl).origin;
191 } catch {
192 return httpUrl;
193 }
194}
195
196const serverHttpOrigin = getServerHttpOrigin();
197
198function ProjectFavicon({ cwd }: { cwd: string }) {
199 const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
200
201 const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
202
203 if (status === "error") {
204 return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
205 }
206
207 return (
208 <img
209 src={src}
210 alt=""
211 className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
212 onLoad={() => setStatus("loaded")}
213 onError={() => setStatus("error")}
214 />
215 );
216}
217
218export default function Sidebar() {
219 const { state, dispatch } = useStore();
220 const navigate = useNavigate();
221 const { settings: appSettings } = useAppSettings();
222 const routeThreadId = useParams({
223 strict: false,
224 select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
225 });
226 const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
227 ...serverConfigQueryOptions(),
228 select: (config) => config.keybindings,
229 });
230 const queryClient = useQueryClient();
231 const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
232 const [addingProject, setAddingProject] = useState(false);
233 const [newCwd, setNewCwd] = useState("");
234 const [isPickingFolder, setIsPickingFolder] = useState(false);
235 const [isAddingProject, setIsAddingProject] = useState(false);
236 const pendingApprovalByThreadId = useMemo(() => {
237 const map = new Map<ThreadId, boolean>();
238 for (const thread of state.threads) {
239 map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
240 }
241 return map;
242 }, [state.threads]);
243 const projectCwdById = useMemo(
244 () => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
245 [state.projects],
246 );
247 const threadGitTargets = useMemo(
248 () =>
249 state.threads.map((thread) => ({
250 threadId: thread.id,
251 branch: thread.branch,
252 cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
253 })),
254 [projectCwdById, state.threads],
255 );
256 const threadGitStatusCwds = useMemo(
257 () =>
258 [
259 ...new Set(
260 threadGitTargets
261 .filter((target) => target.branch !== null)
262 .map((target) => target.cwd)
263 .filter((cwd): cwd is string => cwd !== null),
264 ),
265 ],
266 [threadGitTargets],
267 );
268 const threadGitStatusQueries = useQueries({
269 queries: threadGitStatusCwds.map((cwd) => ({
270 ...gitStatusQueryOptions(cwd),
271 staleTime: 30_000,
272 refetchInterval: 60_000,
273 })),
274 });
275 const prStateByThreadId = useMemo(() => {
276 const statusByCwd = new Map<string, GitStatusResult>();
277 for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
278 const cwd = threadGitStatusCwds[index];
279 if (!cwd) continue;
280 const status = threadGitStatusQueries[index]?.data;
281 if (status) {
282 statusByCwd.set(cwd, status);
283 }
284 }
285
286 const map = new Map<ThreadId, ThreadPrState>();
287 for (const target of threadGitTargets) {
288 const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
289 const branchMatches =
290 target.branch !== null && status?.branch !== null && status?.branch === target.branch;
291 map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
292 }
293 return map;
294 }, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
295
296 const handleNewThread = useCallback(
297 (
298 projectId: ProjectId,
299 options?: {
300 branch?: string | null;
301 worktreePath?: string | null;
302 },
303 ): Promise<void> => {
304 const api = readNativeApi();
305 if (!api) return Promise.resolve();
306 const threadId = newThreadId();
307 const createdAt = new Date().toISOString();
308 const model =
309 state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
310 return (async () => {
311 await api.orchestration.dispatchCommand({
312 type: "thread.create",
313 commandId: newCommandId(),
314 threadId,
315 projectId,
316 title: "New thread",
317 model,
318 branch: options?.branch ?? null,
319 worktreePath: options?.worktreePath ?? null,
320 createdAt,
321 });
322
323 // Ensure route guards can see the new thread before navigating.
324 try {
325 const snapshot = await api.orchestration.getSnapshot();
326 dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
327 } catch {
328 // Event stream can still hydrate the thread shortly after dispatch.
329 }
330
331 await navigate({
332 to: "/$threadId",
333 params: { threadId },
334 });
335 })();
336 },
337 [dispatch, navigate, state.projects],
338 );
339
340 const focusMostRecentThreadForProject = useCallback(
341 (projectId: ProjectId) => {
342 const latestThread = state.threads
343 .filter((thread) => thread.projectId === projectId)
344 .toSorted((a, b) => {
345 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
346 if (byDate !== 0) return byDate;
347 return b.id.localeCompare(a.id);
348 })[0];
349 if (!latestThread) return;
350
351 void navigate({
352 to: "/$threadId",
353 params: { threadId: latestThread.id },
354 });
355 },
356 [navigate, state.threads],
357 );
358
359 const addProjectFromPath = useCallback(
360 async (rawCwd: string) => {
361 const cwd = rawCwd.trim();
362 if (!cwd || isAddingProject) return;
363 const api = readNativeApi();
364
365 setIsAddingProject(true);
366 try {
367 if (!api) return;
368 const existing = state.projects.find((project) => project.cwd === cwd);
369 if (existing) {
370 focusMostRecentThreadForProject(existing.id);
371 return;
372 }
373
374 const projectId = newProjectId();
375 const createdAt = new Date().toISOString();
376 const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
377 await api.orchestration.dispatchCommand({
378 type: "project.create",
379 commandId: newCommandId(),
380 projectId,
381 title,
382 workspaceRoot: cwd,
383 defaultModel: DEFAULT_MODEL,
384 createdAt,
385 });
386 await handleNewThread(projectId);
387 } finally {
388 setIsAddingProject(false);
389 setNewCwd("");
390 setAddingProject(false);
391 }
392 },
393 [focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
394 );
395
396 const handleAddProject = () => {
397 void addProjectFromPath(newCwd);
398 };
399
400 const handlePickFolder = async () => {
401 const api = readNativeApi();
402 if (!api || isPickingFolder) return;
403 setIsPickingFolder(true);
404 try {
405 const pickedPath = await api.dialogs.pickFolder();
406 if (!pickedPath) return;
407 await addProjectFromPath(pickedPath);
408 } finally {
409 setIsPickingFolder(false);
410 }
411 };
412
413 const handleThreadContextMenu = useCallback(
414 async (threadId: ThreadId, position: { x: number; y: number }) => {
415 const api = readNativeApi();
416 if (!api) return;
417 const clicked = await api.contextMenu.show(
418 [
419 { id: "mark-unread", label: "Mark unread" },
420 { id: "delete", label: "Delete" },
421 ],
422 position,
423 );
424 if (clicked === "mark-unread") {
425 dispatch({ type: "MARK_THREAD_UNREAD", threadId });
426 return;
427 }
428 if (clicked !== "delete") return;
429
430 const thread = state.threads.find((t) => t.id === threadId);
431 if (!thread) return;
432 if (appSettings.confirmThreadDelete) {
433 const confirmed = await api.dialogs.confirm(
434 [
435 `Delete thread "${thread.title}"?`,
436 "This permanently clears conversation history for this thread.",
437 ].join("\n"),
438 );
439 if (!confirmed) {
440 return;
441 }
442 }
443 const threadProject = state.projects.find((project) => project.id === thread.projectId);
444 const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
445 const displayWorktreePath = orphanedWorktreePath
446 ? formatWorktreePathForDisplay(orphanedWorktreePath)
447 : null;
448 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
449 const shouldDeleteWorktree =
450 canDeleteWorktree &&
451 (await api.dialogs.confirm(
452 [
453 "This thread is the only one linked to this worktree:",
454 displayWorktreePath ?? orphanedWorktreePath,
455 "",
456 "Delete the worktree too?",
457 ].join("\n"),
458 ));
459
460 if (thread.session && thread.session.status !== "closed") {
461 await api.orchestration
462 .dispatchCommand({
463 type: "thread.session.stop",
464 commandId: newCommandId(),
465 threadId,
466 createdAt: new Date().toISOString(),
467 })
468 .catch(() => undefined);
469 }
470
471 try {
472 await api.terminal.close({
473 threadId,
474 deleteHistory: true,
475 });
476 } catch {
477 // Terminal may already be closed
478 }
479
480 const shouldNavigateToFallback = routeThreadId === threadId;
481 const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
482 await api.orchestration.dispatchCommand({
483 type: "thread.delete",
484 commandId: newCommandId(),
485 threadId,
486 });
487 if (shouldNavigateToFallback) {
488 if (fallbackThreadId) {
489 void navigate({
490 to: "/$threadId",
491 params: { threadId: fallbackThreadId },
492 replace: true,
493 });
494 } else {
495 void navigate({ to: "/", replace: true });
496 }
497 }
498
499 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
500 return;
501 }
502
503 try {
504 await removeWorktreeMutation.mutateAsync({
505 cwd: threadProject.cwd,
506 path: orphanedWorktreePath,
507 force: true,
508 });
509 } catch (error) {
510 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
511 console.error("Failed to remove orphaned worktree after thread deletion", {
512 threadId,
513 projectCwd: threadProject.cwd,
514 worktreePath: orphanedWorktreePath,
515 error,
516 });
517 toastManager.add({
518 type: "error",
519 title: "Thread deleted, but worktree removal failed",
520 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
521 });
522 }
523 },
524 [
525 appSettings.confirmThreadDelete,
526 dispatch,
527 navigate,
528 removeWorktreeMutation,
529 routeThreadId,
530 state.projects,
531 state.threads,
532 ],
533 );
534
535 const handleProjectContextMenu = useCallback(
536 async (projectId: ProjectId, position: { x: number; y: number }) => {
537 const api = readNativeApi();
538 if (!api) return;
539 const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
540 if (clicked !== "delete") return;
541
542 const project = state.projects.find((entry) => entry.id === projectId);
543 if (!project) return;
544
545 const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
546 if (projectThreads.length > 0) {
547 toastManager.add({
548 type: "warning",
549 title: "Project is not empty",
550 description: "Delete all threads in this project before deleting it.",
551 });
552 return;
553 }
554
555 const confirmed = await api.dialogs.confirm(
556 [`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
557 );
558 if (!confirmed) return;
559
560 try {
561 await api.orchestration.dispatchCommand({
562 type: "project.delete",
563 commandId: newCommandId(),
564 projectId,
565 });
566 } catch (error) {
567 const message = error instanceof Error ? error.message : "Unknown error deleting project.";
568 console.error("Failed to remove project", { projectId, error });
569 toastManager.add({
570 type: "error",
571 title: `Failed to delete "${project.name}"`,
572 description: message,
573 });
574 }
575 },
576 [state.projects, state.threads],
577 );
578
579 useEffect(() => {
580 const onWindowKeyDown = (event: KeyboardEvent) => {
581 const activeThread = routeThreadId
582 ? state.threads.find((thread) => thread.id === routeThreadId)
583 : undefined;
584 if (isChatNewLocalShortcut(event, keybindings)) {
585 const projectId = activeThread?.projectId ?? state.projects[0]?.id;
586 if (!projectId) return;
587 event.preventDefault();
588 void handleNewThread(projectId);
589 return;
590 }
591
592 if (!isChatNewShortcut(event, keybindings)) return;
593 const projectId = activeThread?.projectId ?? state.projects[0]?.id;
594 if (!projectId) return;
595 event.preventDefault();
596 void handleNewThread(projectId, {
597 branch: activeThread?.branch ?? null,
598 worktreePath: activeThread?.worktreePath ?? null,
599 });
600 };
601
602 window.addEventListener("keydown", onWindowKeyDown);
603 return () => {
604 window.removeEventListener("keydown", onWindowKeyDown);
605 };
606 }, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
607
608 const onCreateThreadClick = () => {
609 if (state.projects.length === 0) {
610 setAddingProject(true);
611 return;
612 }
613 const firstProject = state.projects[0];
614 if (firstProject) void handleNewThread(firstProject.id);
615 };
616
617 const wordmark = (
618 <div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
619 <SidebarTrigger className="shrink-0 md:hidden" />
620 <div className="flex min-w-0 flex-1 items-center gap-1">
621 <T3Wordmark />
622 <span className="truncate text-base font-medium tracking-tight text-muted-foreground">
623 Code
624 </span>
625 <span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
626 {APP_STAGE_LABEL}
627 </span>
628 </div>
629 </div>
630 );
631
632 const newThreadButton = (
633 <button
634 type="button"
635 className="flex w-full items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent"
636 onClick={onCreateThreadClick}
637 >
638 <span className="text-foreground">+</span>
639 New thread
640 </button>
641 );
642
643 return (
644 <>
645 {isElectron ? (
646 <>
647 <SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
648 {wordmark}
649 </SidebarHeader>
650 <div className="px-4 pb-2">{newThreadButton}</div>
651 </>
652 ) : (
653 <SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
654 {wordmark}
655 {newThreadButton}
656 </SidebarHeader>
657 )}
658
659 <SidebarContent className="gap-0">
660 <SidebarGroup className="px-2 py-2">
661 <SidebarMenu>
662 {state.projects.map((project) => {
663 const threads = state.threads
664 .filter((thread) => thread.projectId === project.id)
665 .toSorted((a, b) => {
666 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
667 if (byDate !== 0) return byDate;
668 return b.id.localeCompare(a.id);
669 });
670
671 return (
672 <Collapsible
673 key={project.id}
674 className="group/collapsible"
675 open={project.expanded}
676 onOpenChange={(open) => {
677 if (open === project.expanded) return;
678 dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
679 }}
680 >
681 <SidebarMenuItem>
682 <CollapsibleTrigger
683 render={
684 <SidebarMenuButton
685 size="sm"
686 className="gap-2 px-2 py-1.5 text-left hover:bg-accent"
687 />
688 }
689 onContextMenu={(event) => {
690 event.preventDefault();
691 void handleProjectContextMenu(project.id, {
692 x: event.clientX,
693 y: event.clientY,
694 });
695 }}
696 >
697 <ChevronRightIcon
698 className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
699 project.expanded ? "rotate-90" : ""
700 }`}
701 />
702 <ProjectFavicon cwd={project.cwd} />
703 <span className="flex-1 truncate text-xs font-medium text-foreground/90">
704 {project.name}
705 </span>
706 <span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
707 </CollapsibleTrigger>
708
709 <CollapsibleContent>
710 <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
711 {threads.map((thread) => {
712 const isActive = routeThreadId === thread.id;
713 const threadStatus = threadStatusPill(
714 thread,
715 pendingApprovalByThreadId.get(thread.id) === true,
716 );
717 const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
718 const terminalStatus = terminalStatusIndicator(thread);
719
720 return (
721 <SidebarMenuSubItem key={thread.id} className="w-full">
722 <SidebarMenuSubButton
723 render={<button type="button" />}
724 size="sm"
725 isActive={isActive}
726 className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
727 isActive
728 ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
729 : "text-muted-foreground"
730 }`}
731 onClick={() => {
732 void navigate({
733 to: "/$threadId",
734 params: { threadId: thread.id },
735 });
736 }}
737 onContextMenu={(event) => {
738 event.preventDefault();
739 void handleThreadContextMenu(thread.id, {
740 x: event.clientX,
741 y: event.clientY,
742 });
743 }}
744 >
745 <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
746 {threadStatus && (
747 <span
748 className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
749 >
750 <span
751 className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
752 threadStatus.pulse ? "animate-pulse" : ""
753 }`}
754 />
755 <span className="hidden md:inline">{threadStatus.label}</span>
756 </span>
757 )}
758 <span className="min-w-0 flex-1 truncate text-xs">
759 {thread.title}
760 </span>
761 </div>
762 <div className="ml-auto flex shrink-0 items-center gap-1.5">
763 {prStatus && (
764 <span
765 role="img"
766 aria-label={prStatus.label}
767 title={prStatus.label}
768 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
769 >
770 <GitPullRequestIcon className="size-3" />
771 </span>
772 )}
773 {terminalStatus && (
774 <span
775 role="img"
776 aria-label={terminalStatus.label}
777 title={terminalStatus.label}
778 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
779 >
780 <TerminalIcon
781 className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
782 />
783 </span>
784 )}
785 <span
786 className={`text-[10px] ${
787 isActive ? "text-foreground/65" : "text-muted-foreground/40"
788 }`}
789 >
790 {formatRelativeTime(thread.createdAt)}
791 </span>
792 </div>
793 </SidebarMenuSubButton>
794 </SidebarMenuSubItem>
795 );
796 })}
797
798 <SidebarMenuSubItem className="w-full">
799 <SidebarMenuSubButton
800 render={<button type="button" />}
801 size="sm"
802 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"
803 onClick={() => {
804 void handleNewThread(project.id);
805 }}
806 >
807 <span>+</span>
808 <span>New thread</span>
809 </SidebarMenuSubButton>
810 </SidebarMenuSubItem>
811 </SidebarMenuSub>
812 </CollapsibleContent>
813 </SidebarMenuItem>
814 </Collapsible>
815 );
816 })}
817 </SidebarMenu>
818
819 {state.projects.length === 0 && !addingProject && (
820 <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
821 No projects yet.
822 <br />
823 Add one to get started.
824 </div>
825 )}
826 </SidebarGroup>
827 </SidebarContent>
828
829 <SidebarSeparator />
830 <SidebarFooter className="gap-0 p-3">
831 {addingProject ? (
832 <>
833 <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
834 Add project
835 </p>
836 <input
837 className="mb-2 w-full rounded-md border border-border bg-secondary px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:border-ring focus:outline-none"
838 placeholder="/path/to/project"
839 value={newCwd}
840 onChange={(event) => setNewCwd(event.target.value)}
841 onKeyDown={(event) => {
842 if (event.key === "Enter") handleAddProject();
843 if (event.key === "Escape") setAddingProject(false);
844 }}
845 />
846 {isElectron && (
847 <button
848 type="button"
849 className="mb-2 flex w-full items-center justify-center rounded-md border border-border px-2 py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60"
850 onClick={() => void handlePickFolder()}
851 disabled={isPickingFolder || isAddingProject}
852 >
853 {isPickingFolder ? "Picking folder..." : "Browse for folder"}
854 </button>
855 )}
856 <div className="flex gap-2">
857 <button
858 type="button"
859 className="flex-1 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90"
860 onClick={handleAddProject}
861 disabled={isAddingProject}
862 >
863 {isAddingProject ? "Adding..." : "Add"}
864 </button>
865 <button
866 type="button"
867 className="flex-1 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground/80 transition-colors duration-150 hover:bg-secondary"
868 onClick={() => setAddingProject(false)}
869 >
870 Cancel
871 </button>
872 </div>
873 </>
874 ) : (
875 <button
876 type="button"
877 className="flex w-full items-center justify-center gap-1 rounded-md border border-dashed border-border py-2 text-xs text-muted-foreground/70 transition-colors duration-150 hover:border-ring hover:text-muted-foreground"
878 onClick={() => setAddingProject(true)}
879 >
880 + Add project
881 </button>
882 )}
883 </SidebarFooter>
884 </>
885 );
886}