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

Sidebar.tsx

1,356 lines50.9 KB

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