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

Sidebar.tsx

643 lines23.0 KB

1import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
2import { useCallback, useEffect, useMemo, useState } from "react";
3import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
4import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
5import { isElectron } from "../env";
6import { useTheme } from "../hooks/useTheme";
7import { DEFAULT_MODEL } from "../model-logic";
8import { derivePendingApprovals } from "../session-logic";
9import { useStore } from "../store";
10import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
11import {
12 DEFAULT_THREAD_TERMINAL_HEIGHT,
13 DEFAULT_THREAD_TERMINAL_ID,
14 type Project,
15 type Thread,
16} from "../types";
17import { useNativeApi } from "../hooks/useNativeApi";
18import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
19import { serverConfigQueryOptions } from "../lib/serverReactQuery";
20import { toastManager } from "./ui/toast";
21import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
22​
23const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
24const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
25​
26function formatRelativeTime(iso: string): string {
27 const diff = Date.now() - new Date(iso).getTime();
28 const minutes = Math.floor(diff / 60_000);
29 if (minutes < 1) return "just now";
30 if (minutes < 60) return `${minutes}m ago`;
31 const hours = Math.floor(minutes / 60);
32 if (hours < 24) return `${hours}h ago`;
33 return `${Math.floor(hours / 24)}d ago`;
35​
36function inferProjectName(cwd: string): string {
37 const normalized = cwd.replace(/\\/g, "/").replace(/\/+$/, "");
38 const parts = normalized.split("/");
39 const last = parts[parts.length - 1];
40 return last && last.length > 0 ? last : "project";
42​
43interface ThreadStatusPill {
44 label: "Working" | "Connecting" | "Completed" | "Awaiting response";
45 colorClass: string;
46 dotClass: string;
47 pulse: boolean;
49​
50interface TerminalStatusIndicator {
51 label: "Terminal process running";
52 colorClass: string;
53 pulse: boolean;
55​
56function hasUnseenCompletion(thread: Thread): boolean {
57 if (!thread.latestTurnCompletedAt) return false;
58 const completedAt = Date.parse(thread.latestTurnCompletedAt);
59 if (Number.isNaN(completedAt)) return false;
60 if (!thread.lastVisitedAt) return true;
61​
62 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
63 if (Number.isNaN(lastVisitedAt)) return true;
64 return completedAt > lastVisitedAt;
66​
67function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
68 if (hasPendingApprovals) {
69 return {
70 label: "Awaiting response",
71 colorClass: "text-amber-600 dark:text-amber-300/90",
72 dotClass: "bg-amber-500 dark:bg-amber-300/90",
73 pulse: false,
74 };
75 }
76​
77 if (thread.session?.status === "running") {
78 return {
79 label: "Working",
80 colorClass: "text-sky-600 dark:text-sky-300/80",
81 dotClass: "bg-sky-500 dark:bg-sky-300/80",
82 pulse: true,
83 };
84 }
85​
86 if (thread.session?.status === "connecting") {
87 return {
88 label: "Connecting",
89 colorClass: "text-sky-600 dark:text-sky-300/80",
90 dotClass: "bg-sky-500 dark:bg-sky-300/80",
91 pulse: true,
92 };
93 }
94​
95 if (hasUnseenCompletion(thread)) {
96 return {
97 label: "Completed",
98 colorClass: "text-emerald-600 dark:text-emerald-300/90",
99 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
100 pulse: false,
101 };
102 }
103​
104 return null;
106​
107function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
108 if (thread.runningTerminalIds.length === 0) {
109 return null;
110 }
111 return {
112 label: "Terminal process running",
113 colorClass: "text-teal-600 dark:text-teal-300/90",
114 pulse: true,
115 };
117​
118export default function Sidebar() {
119 const { state, dispatch } = useStore();
120 const api = useNativeApi();
121 const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
122 ...serverConfigQueryOptions(api),
123 select: (config) => config.keybindings,
124 });
125 const queryClient = useQueryClient();
126 const removeWorktreeMutation = useMutation(
127 gitRemoveWorktreeMutationOptions({ api, queryClient }),
128 );
129 const { theme, setTheme } = useTheme();
130 const [addingProject, setAddingProject] = useState(false);
131 const [newCwd, setNewCwd] = useState("");
132 const [isPickingFolder, setIsPickingFolder] = useState(false);
133 const [isAddingProject, setIsAddingProject] = useState(false);
134 const pendingApprovalByThreadId = useMemo(() => {
135 const map = new Map<string, boolean>();
136 for (const thread of state.threads) {
137 map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
138 }
139 return map;
140 }, [state.threads]);
141​
142 const handleNewThread = useCallback(
143 (
144 projectId: string,
145 options?: {
146 branch?: string | null;
147 worktreePath?: string | null;
148 },
149 ) => {
150 dispatch({
151 type: "ADD_THREAD",
152 thread: {
153 id: crypto.randomUUID(),
154 codexThreadId: null,
155 projectId,
156 title: "New thread",
157 model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
158 terminalOpen: false,
159 terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
160 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
161 runningTerminalIds: [],
162 activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
163 terminalGroups: [
164 {
165 id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
166 terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
167 },
168 ],
169 activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
170 session: null,
171 messages: [],
172 events: [],
173 error: null,
174 createdAt: new Date().toISOString(),
175 branch: options?.branch ?? null,
176 worktreePath: options?.worktreePath ?? null,
177 },
178 });
179 },
180 [dispatch, state.projects],
181 );
182​
183 const focusMostRecentThreadForProject = useCallback(
184 (projectId: string) => {
185 const latestThread = state.threads
186 .filter((thread) => thread.projectId === projectId)
187 .toSorted((a, b) => {
188 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
189 if (byDate !== 0) return byDate;
190 return b.id.localeCompare(a.id);
191 })[0];
192 if (!latestThread) return;
193​
194 dispatch({
195 type: "SET_ACTIVE_THREAD",
196 threadId: latestThread.id,
197 });
198 },
199 [dispatch, state.threads],
200 );
201​
202 const addProjectFromPath = useCallback(
203 async (rawCwd: string) => {
204 const cwd = rawCwd.trim();
205 if (!cwd || isAddingProject) return;
206​
207 setIsAddingProject(true);
208 try {
209 if (isElectron && api) {
210 const result = await api.projects.add({ cwd });
211 const project: Project = {
212 id: result.project.id,
213 name: result.project.name,
214 cwd: result.project.cwd,
215 model: DEFAULT_MODEL,
216 expanded: true,
217 };
218 const existingById = state.projects.find((p) => p.id === project.id);
219 const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
220 if (!existingById && !existingByCwd) {
221 dispatch({ type: "ADD_PROJECT", project });
222 }
223 const resolvedProjectId = existingByCwd?.id ?? project.id;
224​
225 if (result.created) {
226 handleNewThread(resolvedProjectId);
227 } else {
228 focusMostRecentThreadForProject(resolvedProjectId);
229 }
230 } else {
231 const existing = state.projects.find((project) => project.cwd === cwd);
232 if (existing) {
233 focusMostRecentThreadForProject(existing.id);
234 return;
235 }
236​
237 const name = inferProjectName(cwd);
238 const project: Project = {
239 id: crypto.randomUUID(),
240 name,
241 cwd,
242 model: DEFAULT_MODEL,
243 expanded: true,
244 };
245 dispatch({ type: "ADD_PROJECT", project });
246 handleNewThread(project.id);
247 }
248 } finally {
249 setIsAddingProject(false);
250 setNewCwd("");
251 setAddingProject(false);
252 }
253 },
254 [
255 api,
256 dispatch,
257 focusMostRecentThreadForProject,
258 handleNewThread,
259 isAddingProject,
260 state.projects,
261 ],
262 );
263​
264 const handleAddProject = () => {
265 void addProjectFromPath(newCwd);
266 };
267​
268 const handlePickFolder = async () => {
269 if (!api || isPickingFolder) return;
270 setIsPickingFolder(true);
271 try {
272 const pickedPath = await api.dialogs.pickFolder();
273 if (!pickedPath) return;
274 await addProjectFromPath(pickedPath);
275 } finally {
276 setIsPickingFolder(false);
277 }
278 };
279​
280 const handleThreadContextMenu = useCallback(
281 async (threadId: string, position: { x: number; y: number }) => {
282 if (!api) return;
283 const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
284 if (clicked !== "delete") return;
285​
286 const thread = state.threads.find((t) => t.id === threadId);
287 if (!thread) return;
288 const threadProject = state.projects.find((project) => project.id === thread.projectId);
289 const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
290 const displayWorktreePath = orphanedWorktreePath
291 ? formatWorktreePathForDisplay(orphanedWorktreePath)
292 : null;
293 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
294 const shouldDeleteWorktree =
295 canDeleteWorktree &&
296 (await api.dialogs.confirm(
297 [
298 "This thread is the only one linked to this worktree:",
299 displayWorktreePath ?? orphanedWorktreePath,
300 "",
301 "Delete the worktree too?",
302 ].join("\n"),
303 ));
304​
305 // Stop active session if running
306 if (thread.session?.sessionId) {
307 try {
308 await api.providers.stopSession({
309 sessionId: thread.session.sessionId,
310 });
311 } catch {
312 // Session may already be stopped
313 }
314 }
315​
316 try {
317 await api.terminal.close({
318 threadId,
319 deleteHistory: true,
320 });
321 } catch {
322 // Terminal may already be closed
323 }
324​
325 dispatch({ type: "DELETE_THREAD", threadId });
326​
327 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
328 return;
329 }
330​
331 try {
332 await removeWorktreeMutation.mutateAsync({
333 cwd: threadProject.cwd,
334 path: orphanedWorktreePath,
335 });
336 } catch {
337 // Worktree deletion is best-effort and should not block thread deletion.
338 }
339 },
340 [api, dispatch, removeWorktreeMutation, state.projects, state.threads],
341 );
342​
343 const handleProjectContextMenu = useCallback(
344 async (projectId: string, position: { x: number; y: number }) => {
345 if (!api) return;
346 const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
347 if (clicked !== "delete") return;
348​
349 const project = state.projects.find((entry) => entry.id === projectId);
350 if (!project) return;
351​
352 const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
353 if (projectThreads.length > 0) {
354 toastManager.add({
355 type: "warning",
356 title: "Project is not empty",
357 description: "Delete all threads in this project before deleting it.",
358 });
359 return;
360 }
361​
362 const confirmed = await api.dialogs.confirm(
363 [`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
364 );
365 if (!confirmed) return;
366​
367 if (isElectron) {
368 try {
369 await api.projects.remove({ id: projectId });
370 } catch (error) {
371 const message =
372 error instanceof Error ? error.message : "Unknown error deleting project.";
373 console.error("Failed to remove project", { projectId, error });
374 toastManager.add({
375 type: "error",
376 title: `Failed to delete "${project.name}"`,
377 description: message,
378 });
379 return;
380 }
381 }
382​
383 dispatch({ type: "DELETE_PROJECT", projectId });
384 },
385 [api, dispatch, state.projects, state.threads],
386 );
387​
388 useEffect(() => {
389 const onWindowKeyDown = (event: KeyboardEvent) => {
390 const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
391 if (isChatNewLocalShortcut(event, keybindings)) {
392 const projectId = activeThread?.projectId ?? state.projects[0]?.id;
393 if (!projectId) return;
394 event.preventDefault();
395 handleNewThread(projectId);
396 return;
397 }
398​
399 if (!isChatNewShortcut(event, keybindings)) return;
400 const projectId = activeThread?.projectId ?? state.projects[0]?.id;
401 if (!projectId) return;
402 event.preventDefault();
403 handleNewThread(projectId, {
404 branch: activeThread?.branch ?? null,
405 worktreePath: activeThread?.worktreePath ?? null,
406 });
407 };
408​
409 window.addEventListener("keydown", onWindowKeyDown);
410 return () => {
411 window.removeEventListener("keydown", onWindowKeyDown);
412 };
413 }, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
414​
415 return (
416 <aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
417 {/* Branding */}
418 <div
419 className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
420 >
421 <span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
422 T3 <span className="font-normal text-muted-foreground">Code</span>
423 </span>
424 <button
425 type="button"
426 className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
427 onClick={() => setTheme(THEME_CYCLE[theme])}
428 aria-label={`Theme: ${theme}`}
429 title={`Theme: ${theme}`}
430 >
431 {theme === "system" ? (
432 <MonitorIcon className="size-3.5" />
433 ) : theme === "light" ? (
434 <SunIcon className="size-3.5" />
435 ) : (
436 <MoonIcon className="size-3.5" />
437 )}
438 </button>
439 </div>
440​
441 {/* New thread (global) */}
442 <div className="px-3 pb-3">
443 <button
444 type="button"
445 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"
446 onClick={() => {
447 if (state.projects.length === 0) {
448 setAddingProject(true);
449 return;
450 }
451 const firstProject = state.projects[0];
452 if (firstProject) handleNewThread(firstProject.id);
453 }}
454 >
455 <span className="text-foreground">+</span>
456 New thread
457 </button>
458 </div>
459​
460 {/* Project list */}
461 <nav className="flex-1 overflow-y-auto px-2">
462 {state.projects.map((project) => {
463 const threads = state.threads
464 .filter((t) => t.projectId === project.id)
465 .toSorted((a, b) => {
466 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
467 if (byDate !== 0) return byDate;
468 return b.id.localeCompare(a.id);
469 });
470 return (
471 <div key={project.id} className="mb-1">
472 {/* Project header */}
473 <button
474 type="button"
475 className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
476 onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
477 onContextMenu={(e) => {
478 e.preventDefault();
479 void handleProjectContextMenu(project.id, {
480 x: e.clientX,
481 y: e.clientY,
482 });
483 }}
484 >
485 <span className="text-[10px] text-muted-foreground/70">
486 {project.expanded ? "▼" : "▶"}
487 </span>
488 <span className="flex-1 truncate text-xs font-medium text-foreground/90">
489 {project.name}
490 </span>
491 <span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
492 </button>
493​
494 {/* Threads */}
495 {project.expanded && (
496 <div className="ml-2 border-l border-border/80 pl-2">
497 {threads.map((thread) => {
498 const isActive = state.activeThreadId === thread.id;
499 const threadStatus = threadStatusPill(
500 thread,
501 pendingApprovalByThreadId.get(thread.id) === true,
502 );
503 const terminalStatus = terminalStatusIndicator(thread);
504 return (
505 <button
506 key={thread.id}
507 type="button"
508 className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
509 isActive
510 ? "bg-accent text-foreground"
511 : "text-muted-foreground hover:bg-secondary"
512 }`}
513 onClick={() =>
514 dispatch({
515 type: "SET_ACTIVE_THREAD",
516 threadId: thread.id,
517 })
518 }
519 onContextMenu={(e) => {
520 e.preventDefault();
521 void handleThreadContextMenu(thread.id, {
522 x: e.clientX,
523 y: e.clientY,
524 });
525 }}
526 >
527 <div className="flex min-w-0 flex-1 items-center gap-1.5">
528 {threadStatus && (
529 <span
530 className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
531 >
532 <span
533 className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
534 threadStatus.pulse ? "animate-pulse" : ""
535 }`}
536 />
537 <span className="hidden md:inline">{threadStatus.label}</span>
538 </span>
539 )}
540 <span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
541 </div>
542 <div className="ml-2 flex shrink-0 items-center gap-1.5">
543 {terminalStatus && (
544 <span
545 role="img"
546 aria-label={terminalStatus.label}
547 title={terminalStatus.label}
548 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
549 >
550 <TerminalIcon
551 className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
552 />
553 </span>
554 )}
555 <span className="text-[10px] text-muted-foreground/40">
556 {formatRelativeTime(thread.createdAt)}
557 </span>
558 </div>
559 </button>
560 );
561 })}
562​
563 {/* New thread within project */}
564 <button
565 type="button"
566 className="flex w-full items-center gap-1 px-2 py-1 text-[10px] text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground/80"
567 onClick={() => handleNewThread(project.id)}
568 >
569 <span>+</span> New thread
570 </button>
571 </div>
572 )}
573 </div>
574 );
575 })}
576​
577 {state.projects.length === 0 && !addingProject && (
578 <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
579 No projects yet.
580 <br />
581 Add one to get started.
582 </div>
583 )}
584 </nav>
585​
586 {/* Add project form */}
587 {addingProject ? (
588 <div className="border-t border-border p-3">
589 <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
590 Add project
591 </p>
592 <input
593 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"
594 placeholder="/path/to/project"
595 value={newCwd}
596 onChange={(e) => setNewCwd(e.target.value)}
597 onKeyDown={(e) => {
598 if (e.key === "Enter") handleAddProject();
599 if (e.key === "Escape") setAddingProject(false);
600 }}
601 />
602 {isElectron && api && (
603 <button
604 type="button"
605 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"
606 onClick={() => void handlePickFolder()}
607 disabled={isPickingFolder || isAddingProject}
608 >
609 {isPickingFolder ? "Picking folder..." : "Browse for folder"}
610 </button>
611 )}
612 <div className="flex gap-2">
613 <button
614 type="button"
615 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"
616 onClick={handleAddProject}
617 disabled={isAddingProject}
618 >
619 {isAddingProject ? "Adding..." : "Add"}
620 </button>
621 <button
622 type="button"
623 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"
624 onClick={() => setAddingProject(false)}
625 >
626 Cancel
627 </button>
628 </div>
629 </div>
630 ) : (
631 <div className="border-t border-border p-3">
632 <button
633 type="button"
634 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"
635 onClick={() => setAddingProject(true)}
636 >
637 + Add project
638 </button>
639 </div>
640 )}
641 </aside>
642 );