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

Sidebar.tsx

1,350 lines50.7 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 const projectCreated = await api.orchestration
503 .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 .then(() => true)
513 .catch(() => false);
514 if (projectCreated) {
515 await handleNewThread(projectId).catch(() => undefined);
516 }
517 finishAddingProject();
518 },
519 [focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
520 );
521​
522 const handleAddProject = () => {
523 void addProjectFromPath(newCwd);
524 };
525​
526 const handlePickFolder = async () => {
527 const api = readNativeApi();
528 if (!api || isPickingFolder) return;
529 setIsPickingFolder(true);
530 let pickedPath: string | null = null;
531 try {
532 pickedPath = await api.dialogs.pickFolder();
533 } catch {
534 // Ignore picker failures and leave the current thread selection unchanged.
535 }
536 if (pickedPath) {
537 await addProjectFromPath(pickedPath);
538 }
539 setIsPickingFolder(false);
540 };
541​
542 const cancelRename = useCallback(() => {
543 setRenamingThreadId(null);
544 renamingInputRef.current = null;
545 }, []);
546​
547 const commitRename = useCallback(
548 async (threadId: ThreadId, newTitle: string, originalTitle: string) => {
549 const finishRename = () => {
550 setRenamingThreadId((current) => {
551 if (current !== threadId) return current;
552 renamingInputRef.current = null;
553 return null;
554 });
555 };
556​
557 const trimmed = newTitle.trim();
558 if (trimmed.length === 0) {
559 toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
560 finishRename();
561 return;
562 }
563 if (trimmed === originalTitle) {
564 finishRename();
565 return;
566 }
567 const api = readNativeApi();
568 if (!api) {
569 finishRename();
570 return;
571 }
572 try {
573 await api.orchestration.dispatchCommand({
574 type: "thread.meta.update",
575 commandId: newCommandId(),
576 threadId,
577 title: trimmed,
578 });
579 } catch (error) {
580 toastManager.add({
581 type: "error",
582 title: "Failed to rename thread",
583 description: error instanceof Error ? error.message : "An error occurred.",
584 });
585 }
586 finishRename();
587 },
588 [],
589 );
590​
591 const handleThreadContextMenu = useCallback(
592 async (threadId: ThreadId, position: { x: number; y: number }) => {
593 const api = readNativeApi();
594 if (!api) return;
595 const clicked = await api.contextMenu.show(
596 [
597 { id: "rename", label: "Rename thread" },
598 { id: "mark-unread", label: "Mark unread" },
599 { id: "copy-thread-id", label: "Copy Thread ID" },
600 { id: "delete", label: "Delete", destructive: true },
601 ],
602 position,
603 );
604 const thread = threads.find((t) => t.id === threadId);
605 if (!thread) return;
606​
607 if (clicked === "rename") {
608 setRenamingThreadId(threadId);
609 setRenamingTitle(thread.title);
610 renamingCommittedRef.current = false;
611 return;
612 }
613​
614 if (clicked === "mark-unread") {
615 markThreadUnread(threadId);
616 return;
617 }
618 if (clicked === "copy-thread-id") {
619 try {
620 await copyTextToClipboard(threadId);
621 toastManager.add({
622 type: "success",
623 title: "Thread ID copied",
624 description: threadId,
625 });
626 } catch (error) {
627 toastManager.add({
628 type: "error",
629 title: "Failed to copy thread ID",
630 description: error instanceof Error ? error.message : "An error occurred.",
631 });
632 }
633 return;
634 }
635 if (clicked !== "delete") return;
636 if (appSettings.confirmThreadDelete) {
637 const confirmed = await api.dialogs.confirm(
638 [
639 `Delete thread "${thread.title}"?`,
640 "This permanently clears conversation history for this thread.",
641 ].join("\n"),
642 );
643 if (!confirmed) {
644 return;
645 }
646 }
647 const threadProject = projects.find((project) => project.id === thread.projectId);
648 const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
649 const displayWorktreePath = orphanedWorktreePath
650 ? formatWorktreePathForDisplay(orphanedWorktreePath)
651 : null;
652 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
653 const shouldDeleteWorktree =
654 canDeleteWorktree &&
655 (await api.dialogs.confirm(
656 [
657 "This thread is the only one linked to this worktree:",
658 displayWorktreePath ?? orphanedWorktreePath,
659 "",
660 "Delete the worktree too?",
661 ].join("\n"),
662 ));
663​
664 if (thread.session && thread.session.status !== "closed") {
665 await api.orchestration
666 .dispatchCommand({
667 type: "thread.session.stop",
668 commandId: newCommandId(),
669 threadId,
670 createdAt: new Date().toISOString(),
671 })
672 .catch(() => undefined);
673 }
674​
675 try {
676 await api.terminal.close({
677 threadId,
678 deleteHistory: true,
679 });
680 } catch {
681 // Terminal may already be closed
682 }
683​
684 const shouldNavigateToFallback = routeThreadId === threadId;
685 const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
686 await api.orchestration.dispatchCommand({
687 type: "thread.delete",
688 commandId: newCommandId(),
689 threadId,
690 });
691 clearComposerDraftForThread(threadId);
692 clearProjectDraftThreadById(thread.projectId, thread.id);
693 clearTerminalState(threadId);
694 if (shouldNavigateToFallback) {
695 if (fallbackThreadId) {
696 void navigate({
697 to: "/$threadId",
698 params: { threadId: fallbackThreadId },
699 replace: true,
700 });
701 } else {
702 void navigate({ to: "/", replace: true });
703 }
704 }
705​
706 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
707 return;
708 }
709​
710 try {
711 await removeWorktreeMutation.mutateAsync({
712 cwd: threadProject.cwd,
713 path: orphanedWorktreePath,
714 force: true,
715 });
716 } catch (error) {
717 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
718 console.error("Failed to remove orphaned worktree after thread deletion", {
719 threadId,
720 projectCwd: threadProject.cwd,
721 worktreePath: orphanedWorktreePath,
722 error,
723 });
724 toastManager.add({
725 type: "error",
726 title: "Thread deleted, but worktree removal failed",
727 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
728 });
729 }
730 },
731 [
732 appSettings.confirmThreadDelete,
733 clearComposerDraftForThread,
734 clearProjectDraftThreadById,
735 clearTerminalState,
736 markThreadUnread,
737 navigate,
738 projects,
739 removeWorktreeMutation,
740 routeThreadId,
741 threads,
742 ],
743 );
744​
745 const handleProjectContextMenu = useCallback(
746 async (projectId: ProjectId, position: { x: number; y: number }) => {
747 const api = readNativeApi();
748 if (!api) return;
749 const clicked = await api.contextMenu.show(
750 [{ id: "delete", label: "Delete", destructive: true }],
751 position,
752 );
753 if (clicked !== "delete") return;
754​
755 const project = projects.find((entry) => entry.id === projectId);
756 if (!project) return;
757​
758 const projectThreads = threads.filter((thread) => thread.projectId === projectId);
759 if (projectThreads.length > 0) {
760 toastManager.add({
761 type: "warning",
762 title: "Project is not empty",
763 description: "Delete all threads in this project before deleting it.",
764 });
765 return;
766 }
767​
768 const confirmed = await api.dialogs.confirm(
769 [`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
770 );
771 if (!confirmed) return;
772​
773 try {
774 const projectDraftThread = getDraftThreadByProjectId(projectId);
775 if (projectDraftThread) {
776 clearComposerDraftForThread(projectDraftThread.threadId);
777 }
778 clearProjectDraftThreadId(projectId);
779 await api.orchestration.dispatchCommand({
780 type: "project.delete",
781 commandId: newCommandId(),
782 projectId,
783 });
784 } catch (error) {
785 const message = error instanceof Error ? error.message : "Unknown error deleting project.";
786 console.error("Failed to remove project", { projectId, error });
787 toastManager.add({
788 type: "error",
789 title: `Failed to delete "${project.name}"`,
790 description: message,
791 });
792 }
793 },
794 [
795 clearComposerDraftForThread,
796 clearProjectDraftThreadId,
797 getDraftThreadByProjectId,
798 projects,
799 threads,
800 ],
801 );
802​
803 useEffect(() => {
804 const onWindowKeyDown = (event: KeyboardEvent) => {
805 const activeThread = routeThreadId
806 ? threads.find((thread) => thread.id === routeThreadId)
807 : undefined;
808 const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
809 if (isChatNewLocalShortcut(event, keybindings)) {
810 const projectId =
811 activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
812 if (!projectId) return;
813 event.preventDefault();
814 void handleNewThread(projectId);
815 return;
816 }
817​
818 if (!isChatNewShortcut(event, keybindings)) return;
819 const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
820 if (!projectId) return;
821 event.preventDefault();
822 void handleNewThread(projectId, {
823 branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
824 worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
825 envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
826 });
827 };
828​
829 window.addEventListener("keydown", onWindowKeyDown);
830 return () => {
831 window.removeEventListener("keydown", onWindowKeyDown);
832 };
833 }, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
834​
835 useEffect(() => {
836 if (!isElectron) return;
837 const bridge = window.desktopBridge;
838 if (
839 !bridge ||
840 typeof bridge.getUpdateState !== "function" ||
841 typeof bridge.onUpdateState !== "function"
842 ) {
843 return;
844 }
845​
846 let disposed = false;
847 let receivedSubscriptionUpdate = false;
848 const unsubscribe = bridge.onUpdateState((nextState) => {
849 if (disposed) return;
850 receivedSubscriptionUpdate = true;
851 setDesktopUpdateState(nextState);
852 });
853​
854 void bridge
855 .getUpdateState()
856 .then((nextState) => {
857 if (disposed || receivedSubscriptionUpdate) return;
858 setDesktopUpdateState(nextState);
859 })
860 .catch(() => undefined);
861​
862 return () => {
863 disposed = true;
864 unsubscribe();
865 };
866 }, []);
867​
868 const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
869​
870 const desktopUpdateTooltip = desktopUpdateState
871 ? getDesktopUpdateButtonTooltip(desktopUpdateState)
872 : "Update available";
873​
874 const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
875 const desktopUpdateButtonAction = desktopUpdateState
876 ? resolveDesktopUpdateButtonAction(desktopUpdateState)
877 : "none";
878 const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
879 ? "cursor-not-allowed opacity-60"
880 : "hover:bg-accent hover:text-foreground";
881 const desktopUpdateButtonClasses =
882 desktopUpdateState?.status === "downloaded"
883 ? "text-emerald-500"
884 : desktopUpdateState?.status === "downloading"
885 ? "text-sky-400"
886 : shouldHighlightDesktopUpdateError(desktopUpdateState)
887 ? "text-rose-500 animate-pulse"
888 : "text-amber-500 animate-pulse";
889 const newThreadShortcutLabel = useMemo(
890 () =>
891 shortcutLabelForCommand(keybindings, "chat.newLocal") ??
892 shortcutLabelForCommand(keybindings, "chat.new"),
893 [keybindings],
894 );
895​
896 const handleDesktopUpdateButtonClick = useCallback(() => {
897 const bridge = window.desktopBridge;
898 if (!bridge || !desktopUpdateState) return;
899 if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;
900​
901 if (desktopUpdateButtonAction === "download") {
902 void bridge
903 .downloadUpdate()
904 .then((result) => {
905 if (result.completed) {
906 toastManager.add({
907 type: "success",
908 title: "Update downloaded",
909 description: "Restart the app from the update button to install it.",
910 });
911 }
912 if (!shouldToastDesktopUpdateActionResult(result)) return;
913 const actionError = getDesktopUpdateActionError(result);
914 if (!actionError) return;
915 toastManager.add({
916 type: "error",
917 title: "Could not download update",
918 description: actionError,
919 });
920 })
921 .catch((error) => {
922 toastManager.add({
923 type: "error",
924 title: "Could not start update download",
925 description: error instanceof Error ? error.message : "An unexpected error occurred.",
926 });
927 });
928 return;
929 }
930​
931 if (desktopUpdateButtonAction === "install") {
932 void bridge
933 .installUpdate()
934 .then((result) => {
935 if (!shouldToastDesktopUpdateActionResult(result)) return;
936 const actionError = getDesktopUpdateActionError(result);
937 if (!actionError) return;
938 toastManager.add({
939 type: "error",
940 title: "Could not install update",
941 description: actionError,
942 });
943 })
944 .catch((error) => {
945 toastManager.add({
946 type: "error",
947 title: "Could not install update",
948 description: error instanceof Error ? error.message : "An unexpected error occurred.",
949 });
950 });
951 }
952 }, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
953​
954 const expandThreadListForProject = useCallback((projectId: ProjectId) => {
955 setExpandedThreadListsByProject((current) => {
956 if (current.has(projectId)) return current;
957 const next = new Set(current);
958 next.add(projectId);
959 return next;
960 });
961 }, []);
962​
963 const collapseThreadListForProject = useCallback((projectId: ProjectId) => {
964 setExpandedThreadListsByProject((current) => {
965 if (!current.has(projectId)) return current;
966 const next = new Set(current);
967 next.delete(projectId);
968 return next;
969 });
970 }, []);
971​
972 const wordmark = (
973 <div className="flex items-center gap-2">
974 <SidebarTrigger className="shrink-0 md:hidden" />
975 <div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
976 <T3Wordmark />
977 <span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
978 Code
979 </span>
980 <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">
981 {APP_STAGE_LABEL}
982 </span>
983 </div>
984 </div>
985 );
986​
987 return (
988 <>
989 {isElectron ? (
990 <>
991 <SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
992 {wordmark}
993 {showDesktopUpdateButton && (
994 <Tooltip>
995 <TooltipTrigger
996 render={
997 <button
998 type="button"
999 aria-label={desktopUpdateTooltip}
1000 aria-disabled={desktopUpdateButtonDisabled || undefined}
1001 disabled={desktopUpdateButtonDisabled}
1002 className={`inline-flex size-7 ml-auto mt-2 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
1003 onClick={handleDesktopUpdateButtonClick}
1005 <RocketIcon className="size-3.5" />
1006 </button>
1008 />
1009 <TooltipPopup side="bottom">{desktopUpdateTooltip}</TooltipPopup>
1010 </Tooltip>
1011 )}
1012 </SidebarHeader>
1013 </>
1014 ) : (
1015 <SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
1016 {wordmark}
1017 </SidebarHeader>
1018 )}
1019​
1020 <SidebarContent className="gap-0">
1021 <SidebarGroup className="px-2 py-2">
1022 <SidebarMenu>
1023 {projects.map((project) => {
1024 const projectThreads = threads
1025 .filter((thread) => thread.projectId === project.id)
1026 .toSorted((a, b) => {
1027 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
1028 if (byDate !== 0) return byDate;
1029 return b.id.localeCompare(a.id);
1030 });
1031 const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
1032 const hasHiddenThreads = projectThreads.length > THREAD_PREVIEW_LIMIT;
1033 const visibleThreads =
1034 hasHiddenThreads && !isThreadListExpanded
1035 ? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
1036 : projectThreads;
1037​
1038 return (
1039 <Collapsible
1040 key={project.id}
1041 className="group/collapsible"
1042 open={project.expanded}
1043 onOpenChange={(open) => {
1044 if (open === project.expanded) return;
1045 toggleProject(project.id);
1046 }}
1048 <SidebarMenuItem>
1049 <div className="group/project-header relative">
1050 <CollapsibleTrigger
1051 render={
1052 <SidebarMenuButton
1053 size="sm"
1054 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"
1055 />
1057 onContextMenu={(event) => {
1058 event.preventDefault();
1059 void handleProjectContextMenu(project.id, {
1060 x: event.clientX,
1061 y: event.clientY,
1062 });
1063 }}
1065 <ChevronRightIcon
1066 className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${
1067 project.expanded ? "rotate-90" : ""
1068 }`}
1069 />
1070 <ProjectFavicon cwd={project.cwd} />
1071 <span className="flex-1 truncate text-xs font-medium text-foreground/90">
1072 {project.name}
1073 </span>
1074 </CollapsibleTrigger>
1075 <Tooltip>
1076 <TooltipTrigger
1077 render={
1078 <SidebarMenuAction
1079 render={
1080 <button
1081 type="button"
1082 aria-label={`Create new thread in ${project.name}`}
1083 />
1085 showOnHover
1086 className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
1087 onClick={(event) => {
1088 event.preventDefault();
1089 event.stopPropagation();
1090 void handleNewThread(project.id);
1091 }}
1093 <SquarePenIcon className="size-3.5" />
1094 </SidebarMenuAction>
1096 />
1097 <TooltipPopup side="top">
1098 {newThreadShortcutLabel
1099 ? `New thread (${newThreadShortcutLabel})`
1100 : "New thread"}
1101 </TooltipPopup>
1102 </Tooltip>
1103 </div>
1104​
1105 <CollapsibleContent>
1106 <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
1107 {visibleThreads.map((thread) => {
1108 const isActive = routeThreadId === thread.id;
1109 const threadStatus = threadStatusPill(
1110 thread,
1111 pendingApprovalByThreadId.get(thread.id) === true,
1112 );
1113 const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
1114 const terminalStatus = terminalStatusFromRunningIds(
1115 selectThreadTerminalState(terminalStateByThreadId, thread.id)
1116 .runningTerminalIds,
1117 );
1118​
1119 return (
1120 <SidebarMenuSubItem key={thread.id} className="w-full">
1121 <SidebarMenuSubButton
1122 render={<div role="button" tabIndex={0} />}
1123 size="sm"
1124 isActive={isActive}
1125 className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
1126 isActive
1127 ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
1128 : "text-muted-foreground"
1129 }`}
1130 onClick={() => {
1131 void navigate({
1132 to: "/$threadId",
1133 params: { threadId: thread.id },
1134 });
1135 }}
1136 onKeyDown={(event) => {
1137 if (event.key !== "Enter" && event.key !== " ") return;
1138 event.preventDefault();
1139 void navigate({
1140 to: "/$threadId",
1141 params: { threadId: thread.id },
1142 });
1143 }}
1144 onContextMenu={(event) => {
1145 event.preventDefault();
1146 void handleThreadContextMenu(thread.id, {
1147 x: event.clientX,
1148 y: event.clientY,
1149 });
1150 }}
1152 <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
1153 {prStatus && (
1154 <Tooltip>
1155 <TooltipTrigger
1156 render={
1157 <button
1158 type="button"
1159 aria-label={prStatus.tooltip}
1160 className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
1161 onClick={(event) => {
1162 openPrLink(event, prStatus.url);
1163 }}
1165 <GitPullRequestIcon className="size-3" />
1166 </button>
1168 />
1169 <TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
1170 </Tooltip>
1171 )}
1172 {threadStatus && (
1173 <span
1174 className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
1176 <span
1177 className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
1178 threadStatus.pulse ? "animate-pulse" : ""
1179 }`}
1180 />
1181 <span className="hidden md:inline">{threadStatus.label}</span>
1182 </span>
1183 )}
1184 {renamingThreadId === thread.id ? (
1185 <input
1186 ref={(el) => {
1187 if (el && renamingInputRef.current !== el) {
1188 renamingInputRef.current = el;
1189 el.focus();
1190 el.select();
1192 }}
1193 className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
1194 value={renamingTitle}
1195 onChange={(e) => setRenamingTitle(e.target.value)}
1196 onKeyDown={(e) => {
1197 e.stopPropagation();
1198 if (e.key === "Enter") {
1199 e.preventDefault();
1200 renamingCommittedRef.current = true;
1201 void commitRename(thread.id, renamingTitle, thread.title);
1202 } else if (e.key === "Escape") {
1203 e.preventDefault();
1204 renamingCommittedRef.current = true;
1205 cancelRename();
1207 }}
1208 onBlur={() => {
1209 if (!renamingCommittedRef.current) {
1210 void commitRename(thread.id, renamingTitle, thread.title);
1212 }}
1213 onClick={(e) => e.stopPropagation()}
1214 />
1215 ) : (
1216 <span className="min-w-0 flex-1 truncate text-xs">
1217 {thread.title}
1218 </span>
1219 )}
1220 </div>
1221 <div className="ml-auto flex shrink-0 items-center gap-1.5">
1222 {terminalStatus && (
1223 <span
1224 role="img"
1225 aria-label={terminalStatus.label}
1226 title={terminalStatus.label}
1227 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
1229 <TerminalIcon
1230 className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
1231 />
1232 </span>
1233 )}
1234 <span
1235 className={`text-[10px] ${
1236 isActive ? "text-foreground/65" : "text-muted-foreground/40"
1237 }`}
1239 {formatRelativeTime(thread.createdAt)}
1240 </span>
1241 </div>
1242 </SidebarMenuSubButton>
1243 </SidebarMenuSubItem>
1244 );
1245 })}
1246​
1247 {hasHiddenThreads && !isThreadListExpanded && (
1248 <SidebarMenuSubItem className="w-full">
1249 <SidebarMenuSubButton
1250 render={<button type="button" />}
1251 size="sm"
1252 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"
1253 onClick={() => {
1254 expandThreadListForProject(project.id);
1255 }}
1257 <span>Show more</span>
1258 </SidebarMenuSubButton>
1259 </SidebarMenuSubItem>
1260 )}
1261 {hasHiddenThreads && isThreadListExpanded && (
1262 <SidebarMenuSubItem className="w-full">
1263 <SidebarMenuSubButton
1264 render={<button type="button" />}
1265 size="sm"
1266 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"
1267 onClick={() => {
1268 collapseThreadListForProject(project.id);
1269 }}
1271 <span>Show less</span>
1272 </SidebarMenuSubButton>
1273 </SidebarMenuSubItem>
1274 )}
1275 </SidebarMenuSub>
1276 </CollapsibleContent>
1277 </SidebarMenuItem>
1278 </Collapsible>
1279 );
1280 })}
1281 </SidebarMenu>
1282​
1283 {projects.length === 0 && !addingProject && (
1284 <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
1285 No projects yet.
1286 <br />
1287 Add one to get started.
1288 </div>
1289 )}
1290 </SidebarGroup>
1291 </SidebarContent>
1292​
1293 <SidebarSeparator />
1294 <SidebarFooter className="gap-0 p-3">
1295 {addingProject ? (
1296 <>
1297 <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
1298 Add project
1299 </p>
1300 <input
1301 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"
1302 placeholder="/path/to/project"
1303 value={newCwd}
1304 onChange={(event) => setNewCwd(event.target.value)}
1305 onKeyDown={(event) => {
1306 if (event.key === "Enter") handleAddProject();
1307 if (event.key === "Escape") setAddingProject(false);
1308 }}
1309 />
1310 {isElectron && (
1311 <button
1312 type="button"
1313 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"
1314 onClick={() => void handlePickFolder()}
1315 disabled={isPickingFolder || isAddingProject}
1317 {isPickingFolder ? "Picking folder..." : "Browse for folder"}
1318 </button>
1319 )}
1320 <div className="flex gap-2">
1321 <button
1322 type="button"
1323 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"
1324 onClick={handleAddProject}
1325 disabled={isAddingProject}
1327 {isAddingProject ? "Adding..." : "Add"}
1328 </button>
1329 <button
1330 type="button"
1331 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"
1332 onClick={() => setAddingProject(false)}
1334 Cancel
1335 </button>
1336 </div>
1337 </>
1338 ) : (
1339 <button
1340 type="button"
1341 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"
1342 onClick={() => setAddingProject(true)}
1344 + Add project
1345 </button>
1346 )}
1347 </SidebarFooter>
1348 </>
1349 );