Open History to see the last commit
1import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
2import { useCallback, useEffect, useMemo, useRef, 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 { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
24import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
25import { toastManager } from "./ui/toast";
26import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
28import {
29 SidebarContent,
30 SidebarFooter,
31 SidebarGroup,
32 SidebarHeader,
33 SidebarMenu,
34 SidebarMenuButton,
35 SidebarMenuItem,
36 SidebarMenuSub,
37 SidebarMenuSubButton,
38 SidebarMenuSubItem,
39 SidebarSeparator,
40 SidebarTrigger,
41} from "./ui/sidebar";
42import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
43import { isNonEmpty as isNonEmptyString } from "effect/String";
44
45const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
46
47function formatRelativeTime(iso: string): string {
48 const diff = Date.now() - new Date(iso).getTime();
49 const minutes = Math.floor(diff / 60_000);
50 if (minutes < 1) return "just now";
51 if (minutes < 60) return `${minutes}m ago`;
52 const hours = Math.floor(minutes / 60);
53 if (hours < 24) return `${hours}h ago`;
54 return `${Math.floor(hours / 24)}d ago`;
55}
56
57interface ThreadStatusPill {
58 label: "Working" | "Connecting" | "Completed" | "Pending Approval";
59 colorClass: string;
60 dotClass: string;
61 pulse: boolean;
62}
63
64interface TerminalStatusIndicator {
65 label: "Terminal process running";
66 colorClass: string;
67 pulse: boolean;
68}
69
70interface PrStatusIndicator {
71 label: "PR open" | "PR closed" | "PR merged";
72 colorClass: string;
73 tooltip: string;
74 url: string;
75}
76
77type ThreadPr = GitStatusResult["pr"];
78
79function hasUnseenCompletion(thread: Thread): boolean {
80 if (!thread.latestTurn?.completedAt) return false;
81 const completedAt = Date.parse(thread.latestTurn.completedAt);
82 if (Number.isNaN(completedAt)) return false;
83 if (!thread.lastVisitedAt) return true;
84
85 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
86 if (Number.isNaN(lastVisitedAt)) return true;
87 return completedAt > lastVisitedAt;
88}
89
90function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
91 if (hasPendingApprovals) {
92 return {
93 label: "Pending Approval",
94 colorClass: "text-amber-600 dark:text-amber-300/90",
95 dotClass: "bg-amber-500 dark:bg-amber-300/90",
96 pulse: false,
97 };
98 }
99
100 if (thread.session?.status === "running") {
101 return {
102 label: "Working",
103 colorClass: "text-sky-600 dark:text-sky-300/80",
104 dotClass: "bg-sky-500 dark:bg-sky-300/80",
105 pulse: true,
106 };
107 }
108
109 if (thread.session?.status === "connecting") {
110 return {
111 label: "Connecting",
112 colorClass: "text-sky-600 dark:text-sky-300/80",
113 dotClass: "bg-sky-500 dark:bg-sky-300/80",
114 pulse: true,
115 };
116 }
117
118 if (hasUnseenCompletion(thread)) {
119 return {
120 label: "Completed",
121 colorClass: "text-emerald-600 dark:text-emerald-300/90",
122 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
123 pulse: false,
124 };
125 }
126
127 return null;
128}
129
130function terminalStatusFromRunningIds(
131 runningTerminalIds: string[],
132): TerminalStatusIndicator | null {
133 if (runningTerminalIds.length === 0) {
134 return null;
135 }
136 return {
137 label: "Terminal process running",
138 colorClass: "text-teal-600 dark:text-teal-300/90",
139 pulse: true,
140 };
141}
142
143function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
144 if (!pr) return null;
145
146 if (pr.state === "open") {
147 return {
148 label: "PR open",
149 colorClass: "text-emerald-600 dark:text-emerald-300/90",
150 tooltip: `#${pr.number} PR open: ${pr.title}`,
151 url: pr.url,
152 };
153 }
154 if (pr.state === "closed") {
155 return {
156 label: "PR closed",
157 colorClass: "text-zinc-500 dark:text-zinc-400/80",
158 tooltip: `#${pr.number} PR closed: ${pr.title}`,
159 url: pr.url,
160 };
161 }
162 if (pr.state === "merged") {
163 return {
164 label: "PR merged",
165 colorClass: "text-violet-600 dark:text-violet-300/90",
166 tooltip: `#${pr.number} PR merged: ${pr.title}`,
167 url: pr.url,
168 };
169 }
170 return null;
171}
172
173function T3Wordmark() {
174 return (
175 <svg
176 aria-label="T3"
177 className="h-2.5 w-auto shrink-0 text-foreground"
178 viewBox="15.5309 37 94.3941 56.96"
179 xmlns="http://www.w3.org/2000/svg"
180 >
181 <path
182 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"
183 fill="currentColor"
184 />
185 </svg>
186 );
187}
188
189/**
190 * Derives the server's HTTP origin (scheme + host + port) from the same
191 * sources WsTransport uses, converting ws(s) to http(s).
192 */
193function getServerHttpOrigin(): string {
194 const bridgeUrl = window.desktopBridge?.getWsUrl();
195 const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
196 const wsUrl =
197 bridgeUrl && bridgeUrl.length > 0
198 ? bridgeUrl
199 : envUrl && envUrl.length > 0
200 ? envUrl
201 : `ws://${window.location.hostname}:${window.location.port}`;
202 // Parse to extract just the origin, dropping path/query (e.g. ?token=…)
203 const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
204 try {
205 return new URL(httpUrl).origin;
206 } catch {
207 return httpUrl;
208 }
209}
210
211const serverHttpOrigin = getServerHttpOrigin();
212
213function ProjectFavicon({ cwd }: { cwd: string }) {
214 const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
215
216 const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
217
218 if (status === "error") {
219 return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
220 }
221
222 return (
223 <img
224 src={src}
225 alt=""
226 className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
227 onLoad={() => setStatus("loaded")}
228 onError={() => setStatus("error")}
229 />
230 );
231}
232
233export default function Sidebar() {
234 const projects = useStore((store) => store.projects);
235 const threads = useStore((store) => store.threads);
236 const markThreadUnread = useStore((store) => store.markThreadUnread);
237 const toggleProject = useStore((store) => store.toggleProject);
238 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
239 const getDraftThreadByProjectId = useComposerDraftStore(
240 (store) => store.getDraftThreadByProjectId,
241 );
242 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
243 const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
244 const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
245 const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
246 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
247 const clearProjectDraftThreadId = useComposerDraftStore(
248 (store) => store.clearProjectDraftThreadId,
249 );
250 const clearProjectDraftThreadById = useComposerDraftStore(
251 (store) => store.clearProjectDraftThreadById,
252 );
253 const navigate = useNavigate();
254 const { settings: appSettings } = useAppSettings();
255 const routeThreadId = useParams({
256 strict: false,
257 select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
258 });
259 const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
260 ...serverConfigQueryOptions(),
261 select: (config) => config.keybindings,
262 });
263 const queryClient = useQueryClient();
264 const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
265 const [addingProject, setAddingProject] = useState(false);
266 const [newCwd, setNewCwd] = useState("");
267 const [isPickingFolder, setIsPickingFolder] = useState(false);
268 const [isAddingProject, setIsAddingProject] = useState(false);
269 const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
270 const [renamingTitle, setRenamingTitle] = useState("");
271 const renamingCommittedRef = useRef(false);
272 const renamingInputRef = useRef<HTMLInputElement | null>(null);
273 const pendingApprovalByThreadId = useMemo(() => {
274 const map = new Map<ThreadId, boolean>();
275 for (const thread of threads) {
276 map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
277 }
278 return map;
279 }, [threads]);
280 const projectCwdById = useMemo(
281 () => new Map(projects.map((project) => [project.id, project.cwd] as const)),
282 [projects],
283 );
284 const threadGitTargets = useMemo(
285 () =>
286 threads.map((thread) => ({
287 threadId: thread.id,
288 branch: thread.branch,
289 cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
290 })),
291 [projectCwdById, threads],
292 );
293 const threadGitStatusCwds = useMemo(
294 () => [
295 ...new Set(
296 threadGitTargets
297 .filter((target) => target.branch !== null)
298 .map((target) => target.cwd)
299 .filter((cwd): cwd is string => cwd !== null),
300 ),
301 ],
302 [threadGitTargets],
303 );
304 const threadGitStatusQueries = useQueries({
305 queries: threadGitStatusCwds.map((cwd) => ({
306 ...gitStatusQueryOptions(cwd),
307 staleTime: 30_000,
308 refetchInterval: 60_000,
309 })),
310 });
311 const prByThreadId = useMemo(() => {
312 const statusByCwd = new Map<string, GitStatusResult>();
313 for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
314 const cwd = threadGitStatusCwds[index];
315 if (!cwd) continue;
316 const status = threadGitStatusQueries[index]?.data;
317 if (status) {
318 statusByCwd.set(cwd, status);
319 }
320 }
321
322 const map = new Map<ThreadId, ThreadPr>();
323 for (const target of threadGitTargets) {
324 const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
325 const branchMatches =
326 target.branch !== null && status?.branch !== null && status?.branch === target.branch;
327 map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
328 }
329 return map;
330 }, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
331
332 const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
333 event.preventDefault();
334 event.stopPropagation();
335
336 const api = readNativeApi();
337 if (!api) {
338 toastManager.add({
339 type: "error",
340 title: "Link opening is unavailable.",
341 });
342 return;
343 }
344
345 void api.shell.openExternal(prUrl).catch((error) => {
346 toastManager.add({
347 type: "error",
348 title: "Unable to open PR link",
349 description: error instanceof Error ? error.message : "An error occurred.",
350 });
351 });
352 }, []);
353
354 const handleNewThread = useCallback(
355 (
356 projectId: ProjectId,
357 options?: {
358 branch?: string | null;
359 worktreePath?: string | null;
360 envMode?: DraftThreadEnvMode;
361 },
362 ): Promise<void> => {
363 const hasBranchOption = options?.branch !== undefined;
364 const hasWorktreePathOption = options?.worktreePath !== undefined;
365 const hasEnvModeOption = options?.envMode !== undefined;
366 const storedDraftThread = getDraftThreadByProjectId(projectId);
367 if (storedDraftThread) {
368 return (async () => {
369 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
370 setDraftThreadContext(storedDraftThread.threadId, {
371 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
372 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
373 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
374 });
375 }
376 setProjectDraftThreadId(projectId, storedDraftThread.threadId);
377 if (routeThreadId === storedDraftThread.threadId) {
378 return;
379 }
380 await navigate({
381 to: "/$threadId",
382 params: { threadId: storedDraftThread.threadId },
383 });
384 })();
385 }
386 clearProjectDraftThreadId(projectId);
387
388 const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
389 if (activeDraftThread && routeThreadId && activeDraftThread.projectId === projectId) {
390 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
391 setDraftThreadContext(routeThreadId, {
392 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
393 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
394 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
395 });
396 }
397 setProjectDraftThreadId(projectId, routeThreadId);
398 return Promise.resolve();
399 }
400 const threadId = newThreadId();
401 const createdAt = new Date().toISOString();
402 return (async () => {
403 setProjectDraftThreadId(projectId, threadId, {
404 createdAt,
405 branch: options?.branch ?? null,
406 worktreePath: options?.worktreePath ?? null,
407 envMode: options?.envMode ?? "local",
408 });
409
410 await navigate({
411 to: "/$threadId",
412 params: { threadId },
413 });
414 })();
415 },
416 [
417 clearProjectDraftThreadId,
418 getDraftThreadByProjectId,
419 navigate,
420 getDraftThread,
421 routeThreadId,
422 setDraftThreadContext,
423 setProjectDraftThreadId,
424 ],
425 );
426
427 const focusMostRecentThreadForProject = useCallback(
428 (projectId: ProjectId) => {
429 const latestThread = threads
430 .filter((thread) => thread.projectId === projectId)
431 .toSorted((a, b) => {
432 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
433 if (byDate !== 0) return byDate;
434 return b.id.localeCompare(a.id);
435 })[0];
436 if (!latestThread) return;
437
438 void navigate({
439 to: "/$threadId",
440 params: { threadId: latestThread.id },
441 });
442 },
443 [navigate, threads],
444 );
445
446 const addProjectFromPath = useCallback(
447 async (rawCwd: string) => {
448 const cwd = rawCwd.trim();
449 if (!cwd || isAddingProject) return;
450 const api = readNativeApi();
451 if (!api) return;
452
453 setIsAddingProject(true);
454 const finishAddingProject = () => {
455 setIsAddingProject(false);
456 setNewCwd("");
457 setAddingProject(false);
458 };
459
460 const existing = projects.find((project) => project.cwd === cwd);
461 if (existing) {
462 focusMostRecentThreadForProject(existing.id);
463 finishAddingProject();
464 return;
465 }
466
467 const projectId = newProjectId();
468 const createdAt = new Date().toISOString();
469 const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
470 const projectCreated = await api.orchestration
471 .dispatchCommand({
472 type: "project.create",
473 commandId: newCommandId(),
474 projectId,
475 title,
476 workspaceRoot: cwd,
477 defaultModel: DEFAULT_MODEL,
478 createdAt,
479 })
480 .then(() => true)
481 .catch(() => false);
482 if (projectCreated) {
483 await handleNewThread(projectId).catch(() => undefined);
484 }
485 finishAddingProject();
486 },
487 [focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
488 );
489
490 const handleAddProject = () => {
491 void addProjectFromPath(newCwd);
492 };
493
494 const handlePickFolder = async () => {
495 const api = readNativeApi();
496 if (!api || isPickingFolder) return;
497 setIsPickingFolder(true);
498 let pickedPath: string | null = null;
499 try {
500 pickedPath = await api.dialogs.pickFolder();
501 } catch {
502 // Ignore picker failures and leave the current thread selection unchanged.
503 }
504 if (pickedPath) {
505 await addProjectFromPath(pickedPath);
506 }
507 setIsPickingFolder(false);
508 };
509
510 const cancelRename = useCallback(() => {
511 setRenamingThreadId(null);
512 renamingInputRef.current = null;
513 }, []);
514
515 const commitRename = useCallback(
516 async (threadId: ThreadId, newTitle: string, originalTitle: string) => {
517 const finishRename = () => {
518 setRenamingThreadId((current) => {
519 if (current !== threadId) return current;
520 renamingInputRef.current = null;
521 return null;
522 });
523 };
524
525 const trimmed = newTitle.trim();
526 if (trimmed.length === 0) {
527 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
528 finishRename();
529 return;
530 }
531 if (trimmed === originalTitle) {
532 finishRename();
533 return;
534 }
535 const api = readNativeApi();
536 if (!api) {
537 finishRename();
538 return;
539 }
540 try {
541 await api.orchestration.dispatchCommand({
542 type: "thread.meta.update",
543 commandId: newCommandId(),
544 threadId,
545 title: trimmed,
546 });
547 } catch (error) {
548 toastManager.add({
549 type: "error",
550 title: "Failed to rename thread",
551 description: error instanceof Error ? error.message : "An error occurred.",
552 });
553 }
554 finishRename();
555 },
556 [],
557 );
558
559 const handleThreadContextMenu = useCallback(
560 async (threadId: ThreadId, position: { x: number; y: number }) => {
561 const api = readNativeApi();
562 if (!api) return;
563 const clicked = await api.contextMenu.show(
564 [
565 { id: "rename", label: "Rename thread" },
566 { id: "mark-unread", label: "Mark unread" },
567 { id: "delete", label: "Delete", destructive: true },
568 ],
569 position,
570 );
571 const thread = threads.find((t) => t.id === threadId);
572 if (!thread) return;
573
574 if (clicked === "rename") {
575 setRenamingThreadId(threadId);
576 setRenamingTitle(thread.title);
577 renamingCommittedRef.current = false;
578 return;
579 }
580
581 if (clicked === "mark-unread") {
582 markThreadUnread(threadId);
583 return;
584 }
585 if (clicked !== "delete") return;
586 if (appSettings.confirmThreadDelete) {
587 const confirmed = await api.dialogs.confirm(
588 [
589 `Delete thread "${thread.title}"?`,
590 "This permanently clears conversation history for this thread.",
591 ].join("\n"),
592 );
593 if (!confirmed) {
594 return;
595 }
596 }
597 const threadProject = projects.find((project) => project.id === thread.projectId);
598 const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
599 const displayWorktreePath = orphanedWorktreePath
600 ? formatWorktreePathForDisplay(orphanedWorktreePath)
601 : null;
602 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
603 const shouldDeleteWorktree =
604 canDeleteWorktree &&
605 (await api.dialogs.confirm(
606 [
607 "This thread is the only one linked to this worktree:",
608 displayWorktreePath ?? orphanedWorktreePath,
609 "",
610 "Delete the worktree too?",
611 ].join("\n"),
612 ));
613
614 if (thread.session && thread.session.status !== "closed") {
615 await api.orchestration
616 .dispatchCommand({
617 type: "thread.session.stop",
618 commandId: newCommandId(),
619 threadId,
620 createdAt: new Date().toISOString(),
621 })
622 .catch(() => undefined);
623 }
624
625 try {
626 await api.terminal.close({
627 threadId,
628 deleteHistory: true,
629 });
630 } catch {
631 // Terminal may already be closed
632 }
633
634 const shouldNavigateToFallback = routeThreadId === threadId;
635 const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
636 await api.orchestration.dispatchCommand({
637 type: "thread.delete",
638 commandId: newCommandId(),
639 threadId,
640 });
641 clearComposerDraftForThread(threadId);
642 clearProjectDraftThreadById(thread.projectId, thread.id);
643 clearTerminalState(threadId);
644 if (shouldNavigateToFallback) {
645 if (fallbackThreadId) {
646 void navigate({
647 to: "/$threadId",
648 params: { threadId: fallbackThreadId },
649 replace: true,
650 });
651 } else {
652 void navigate({ to: "/", replace: true });
653 }
654 }
655
656 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
657 return;
658 }
659
660 try {
661 await removeWorktreeMutation.mutateAsync({
662 cwd: threadProject.cwd,
663 path: orphanedWorktreePath,
664 force: true,
665 });
666 } catch (error) {
667 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
668 console.error("Failed to remove orphaned worktree after thread deletion", {
669 threadId,
670 projectCwd: threadProject.cwd,
671 worktreePath: orphanedWorktreePath,
672 error,
673 });
674 toastManager.add({
675 type: "error",
676 title: "Thread deleted, but worktree removal failed",
677 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
678 });
679 }
680 },
681 [
682 appSettings.confirmThreadDelete,
683 clearComposerDraftForThread,
684 clearProjectDraftThreadById,
685 clearTerminalState,
686 markThreadUnread,
687 navigate,
688 projects,
689 removeWorktreeMutation,
690 routeThreadId,
691 threads,
692 ],
693 );
694
695 const handleProjectContextMenu = useCallback(
696 async (projectId: ProjectId, position: { x: number; y: number }) => {
697 const api = readNativeApi();
698 if (!api) return;
699 const clicked = await api.contextMenu.show(
700 [{ id: "delete", label: "Delete", destructive: true }],
701 position,
702 );
703 if (clicked !== "delete") return;
704
705 const project = projects.find((entry) => entry.id === projectId);
706 if (!project) return;
707
708 const projectThreads = threads.filter((thread) => thread.projectId === projectId);
709 if (projectThreads.length > 0) {
710 toastManager.add({
711 type: "warning",
712 title: "Project is not empty",
713 description: "Delete all threads in this project before deleting it.",
714 });
715 return;
716 }
717
718 const confirmed = await api.dialogs.confirm(
719 [`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
720 );
721 if (!confirmed) return;
722
723 try {
724 const projectDraftThread = getDraftThreadByProjectId(projectId);
725 if (projectDraftThread) {
726 clearComposerDraftForThread(projectDraftThread.threadId);
727 }
728 clearProjectDraftThreadId(projectId);
729 await api.orchestration.dispatchCommand({
730 type: "project.delete",
731 commandId: newCommandId(),
732 projectId,
733 });
734 } catch (error) {
735 const message = error instanceof Error ? error.message : "Unknown error deleting project.";
736 console.error("Failed to remove project", { projectId, error });
737 toastManager.add({
738 type: "error",
739 title: `Failed to delete "${project.name}"`,
740 description: message,
741 });
742 }
743 },
744 [
745 clearComposerDraftForThread,
746 clearProjectDraftThreadId,
747 getDraftThreadByProjectId,
748 projects,
749 threads,
750 ],
751 );
752
753 useEffect(() => {
754 const onWindowKeyDown = (event: KeyboardEvent) => {
755 const activeThread = routeThreadId
756 ? threads.find((thread) => thread.id === routeThreadId)
757 : undefined;
758 const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
759 if (isChatNewLocalShortcut(event, keybindings)) {
760 const projectId =
761 activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
762 if (!projectId) return;
763 event.preventDefault();
764 void handleNewThread(projectId);
765 return;
766 }
767
768 if (!isChatNewShortcut(event, keybindings)) return;
769 const projectId =
770 activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
771 if (!projectId) return;
772 event.preventDefault();
773 void handleNewThread(projectId, {
774 branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
775 worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
776 envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
777 });
778 };
779
780 window.addEventListener("keydown", onWindowKeyDown);
781 return () => {
782 window.removeEventListener("keydown", onWindowKeyDown);
783 };
784 }, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
785
786 const onCreateThreadClick = () => {
787 if (projects.length === 0) {
788 setAddingProject(true);
789 return;
790 }
791 const firstProject = projects[0];
792 if (firstProject) void handleNewThread(firstProject.id);
793 };
794
795 const wordmark = (
796 <div className="flex items-center gap-2">
797 <SidebarTrigger className="shrink-0 md:hidden" />
798 <div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
799 <T3Wordmark />
800 <span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
801 Code
802 </span>
803 <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">
804 {APP_STAGE_LABEL}
805 </span>
806 </div>
807 </div>
808 );
809
810 const newThreadButton = (
811 <button
812 type="button"
813 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"
814 onClick={onCreateThreadClick}
815 >
816 <span className="text-foreground">+</span>
817 New thread
818 </button>
819 );
820
821 return (
822 <>
823 {isElectron ? (
824 <>
825 <SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
826 {wordmark}
827 </SidebarHeader>
828 <div className="px-4 py-2">{newThreadButton}</div>
829 </>
830 ) : (
831 <SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
832 {wordmark}
833 {newThreadButton}
834 </SidebarHeader>
835 )}
836
837 <SidebarContent className="gap-0">
838 <SidebarGroup className="px-2 py-2">
839 <SidebarMenu>
840 {projects.map((project) => {
841 const visibleThreads = threads
842 .filter((thread) => thread.projectId === project.id)
843 .toSorted((a, b) => {
844 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
845 if (byDate !== 0) return byDate;
846 return b.id.localeCompare(a.id);
847 });
848
849 return (
850 <Collapsible
851 key={project.id}
852 className="group/collapsible"
853 open={project.expanded}
854 onOpenChange={(open) => {
855 if (open === project.expanded) return;
856 toggleProject(project.id);
857 }}
858 >
859 <SidebarMenuItem>
860 <CollapsibleTrigger
861 render={
862 <SidebarMenuButton
863 size="sm"
864 className="gap-2 px-2 py-1.5 text-left hover:bg-accent"
865 />
866 }
867 onContextMenu={(event) => {
868 event.preventDefault();
869 void handleProjectContextMenu(project.id, {
870 x: event.clientX,
871 y: event.clientY,
872 });
873 }}
874 >
875 <ChevronRightIcon
876 className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
877 project.expanded ? "rotate-90" : ""
878 }`}
879 />
880 <ProjectFavicon cwd={project.cwd} />
881 <span className="flex-1 truncate text-xs font-medium text-foreground/90">
882 {project.name}
883 </span>
884 <span className="text-[10px] text-muted-foreground/60">
885 {visibleThreads.length}
886 </span>
887 </CollapsibleTrigger>
888
889 <CollapsibleContent>
890 <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
891 {visibleThreads.map((thread) => {
892 const isActive = routeThreadId === thread.id;
893 const threadStatus = threadStatusPill(
894 thread,
895 pendingApprovalByThreadId.get(thread.id) === true,
896 );
897 const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
898 const terminalStatus = terminalStatusFromRunningIds(
899 selectThreadTerminalState(terminalStateByThreadId, thread.id)
900 .runningTerminalIds,
901 );
902
903 return (
904 <SidebarMenuSubItem key={thread.id} className="w-full">
905 <SidebarMenuSubButton
906 render={<div role="button" tabIndex={0} />}
907 size="sm"
908 isActive={isActive}
909 className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
910 isActive
911 ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
912 : "text-muted-foreground"
913 }`}
914 onClick={() => {
915 void navigate({
916 to: "/$threadId",
917 params: { threadId: thread.id },
918 });
919 }}
920 onKeyDown={(event) => {
921 if (event.key !== "Enter" && event.key !== " ") return;
922 event.preventDefault();
923 void navigate({
924 to: "/$threadId",
925 params: { threadId: thread.id },
926 });
927 }}
928 onContextMenu={(event) => {
929 event.preventDefault();
930 void handleThreadContextMenu(thread.id, {
931 x: event.clientX,
932 y: event.clientY,
933 });
934 }}
935 >
936 <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
937 {prStatus && (
938 <Tooltip>
939 <TooltipTrigger
940 render={
941 <button
942 type="button"
943 aria-label={prStatus.tooltip}
944 className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
945 onClick={(event) => {
946 openPrLink(event, prStatus.url);
947 }}
948 >
949 <GitPullRequestIcon className="size-3" />
950 </button>
951 }
952 />
953 <TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
954 </Tooltip>
955 )}
956 {threadStatus && (
957 <span
958 className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
959 >
960 <span
961 className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
962 threadStatus.pulse ? "animate-pulse" : ""
963 }`}
964 />
965 <span className="hidden md:inline">{threadStatus.label}</span>
966 </span>
967 )}
968 {renamingThreadId === thread.id ? (
969 <input
970 ref={(el) => {
971 if (el && renamingInputRef.current !== el) {
972 renamingInputRef.current = el;
973 el.focus();
974 el.select();
975 }
976 }}
977 className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
978 value={renamingTitle}
979 onChange={(e) => setRenamingTitle(e.target.value)}
980 onKeyDown={(e) => {
981 e.stopPropagation();
982 if (e.key === "Enter") {
983 e.preventDefault();
984 renamingCommittedRef.current = true;
985 void commitRename(thread.id, renamingTitle, thread.title);
986 } else if (e.key === "Escape") {
987 e.preventDefault();
988 renamingCommittedRef.current = true;
989 cancelRename();
990 }
991 }}
992 onBlur={() => {
993 if (!renamingCommittedRef.current) {
994 void commitRename(thread.id, renamingTitle, thread.title);
995 }
996 }}
997 onClick={(e) => e.stopPropagation()}
998 />
999 ) : (
1000 <span className="min-w-0 flex-1 truncate text-xs">
1001 {thread.title}
1002 </span>
1003 )}
1004 </div>
1005 <div className="ml-auto flex shrink-0 items-center gap-1.5">
1006 {terminalStatus && (
1007 <span
1008 role="img"
1009 aria-label={terminalStatus.label}
1010 title={terminalStatus.label}
1011 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
1012 >
1013 <TerminalIcon
1014 className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
1015 />
1016 </span>
1017 )}
1018 <span
1019 className={`text-[10px] ${
1020 isActive ? "text-foreground/65" : "text-muted-foreground/40"
1021 }`}
1022 >
1023 {formatRelativeTime(thread.createdAt)}
1024 </span>
1025 </div>
1026 </SidebarMenuSubButton>
1027 </SidebarMenuSubItem>
1028 );
1029 })}
1030
1031 <SidebarMenuSubItem className="w-full">
1032 <SidebarMenuSubButton
1033 render={<button type="button" />}
1034 size="sm"
1035 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"
1036 onClick={() => {
1037 void handleNewThread(project.id);
1038 }}
1039 >
1040 <span>+</span>
1041 <span>New thread</span>
1042 </SidebarMenuSubButton>
1043 </SidebarMenuSubItem>
1044 </SidebarMenuSub>
1045 </CollapsibleContent>
1046 </SidebarMenuItem>
1047 </Collapsible>
1048 );
1049 })}
1050 </SidebarMenu>
1051
1052 {projects.length === 0 && !addingProject && (
1053 <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
1054 No projects yet.
1055 <br />
1056 Add one to get started.
1057 </div>
1058 )}
1059 </SidebarGroup>
1060 </SidebarContent>
1061
1062 <SidebarSeparator />
1063 <SidebarFooter className="gap-0 p-3">
1064 {addingProject ? (
1065 <>
1066 <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
1067 Add project
1068 </p>
1069 <input
1070 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"
1071 placeholder="/path/to/project"
1072 value={newCwd}
1073 onChange={(event) => setNewCwd(event.target.value)}
1074 onKeyDown={(event) => {
1075 if (event.key === "Enter") handleAddProject();
1076 if (event.key === "Escape") setAddingProject(false);
1077 }}
1078 />
1079 {isElectron && (
1080 <button
1081 type="button"
1082 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"
1083 onClick={() => void handlePickFolder()}
1084 disabled={isPickingFolder || isAddingProject}
1085 >
1086 {isPickingFolder ? "Picking folder..." : "Browse for folder"}
1087 </button>
1088 )}
1089 <div className="flex gap-2">
1090 <button
1091 type="button"
1092 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"
1093 onClick={handleAddProject}
1094 disabled={isAddingProject}
1095 >
1096 {isAddingProject ? "Adding..." : "Add"}
1097 </button>
1098 <button
1099 type="button"
1100 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"
1101 onClick={() => setAddingProject(false)}
1102 >
1103 Cancel
1104 </button>
1105 </div>
1106 </>
1107 ) : (
1108 <button
1109 type="button"
1110 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"
1111 onClick={() => setAddingProject(true)}
1112 >
1113 + Add project
1114 </button>
1115 )}
1116 </SidebarFooter>
1117 </>
1118 );
1119}