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

Sidebar.tsx

645 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 scripts: result.project.scripts,
218 };
219 const existingById = state.projects.find((p) => p.id === project.id);
220 const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
221 if (!existingById && !existingByCwd) {
222 dispatch({ type: "ADD_PROJECT", project });
223 }
224 const resolvedProjectId = existingByCwd?.id ?? project.id;
225​
226 if (result.created) {
227 handleNewThread(resolvedProjectId);
228 } else {
229 focusMostRecentThreadForProject(resolvedProjectId);
230 }
231 } else {
232 const existing = state.projects.find((project) => project.cwd === cwd);
233 if (existing) {
234 focusMostRecentThreadForProject(existing.id);
235 return;
236 }
237​
238 const name = inferProjectName(cwd);
239 const project: Project = {
240 id: crypto.randomUUID(),
241 name,
242 cwd,
243 model: DEFAULT_MODEL,
244 expanded: true,
245 scripts: [],
246 };
247 dispatch({ type: "ADD_PROJECT", project });
248 handleNewThread(project.id);
249 }
250 } finally {
251 setIsAddingProject(false);
252 setNewCwd("");
253 setAddingProject(false);
254 }
255 },
256 [
257 api,
258 dispatch,
259 focusMostRecentThreadForProject,
260 handleNewThread,
261 isAddingProject,
262 state.projects,
263 ],
264 );
265​
266 const handleAddProject = () => {
267 void addProjectFromPath(newCwd);
268 };
269​
270 const handlePickFolder = async () => {
271 if (!api || isPickingFolder) return;
272 setIsPickingFolder(true);
273 try {
274 const pickedPath = await api.dialogs.pickFolder();
275 if (!pickedPath) return;
276 await addProjectFromPath(pickedPath);
277 } finally {
278 setIsPickingFolder(false);
279 }
280 };
281​
282 const handleThreadContextMenu = useCallback(
283 async (threadId: string, position: { x: number; y: number }) => {
284 if (!api) return;
285 const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
286 if (clicked !== "delete") return;
287​
288 const thread = state.threads.find((t) => t.id === threadId);
289 if (!thread) return;
290 const threadProject = state.projects.find((project) => project.id === thread.projectId);
291 const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
292 const displayWorktreePath = orphanedWorktreePath
293 ? formatWorktreePathForDisplay(orphanedWorktreePath)
294 : null;
295 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
296 const shouldDeleteWorktree =
297 canDeleteWorktree &&
298 (await api.dialogs.confirm(
299 [
300 "This thread is the only one linked to this worktree:",
301 displayWorktreePath ?? orphanedWorktreePath,
302 "",
303 "Delete the worktree too?",
304 ].join("\n"),
305 ));
306​
307 // Stop active session if running
308 if (thread.session?.sessionId) {
309 try {
310 await api.providers.stopSession({
311 sessionId: thread.session.sessionId,
312 });
313 } catch {
314 // Session may already be stopped
315 }
316 }
317​
318 try {
319 await api.terminal.close({
320 threadId,
321 deleteHistory: true,
322 });
323 } catch {
324 // Terminal may already be closed
325 }
326​
327 dispatch({ type: "DELETE_THREAD", threadId });
328​
329 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
330 return;
331 }
332​
333 try {
334 await removeWorktreeMutation.mutateAsync({
335 cwd: threadProject.cwd,
336 path: orphanedWorktreePath,
337 });
338 } catch {
339 // Worktree deletion is best-effort and should not block thread deletion.
340 }
341 },
342 [api, dispatch, removeWorktreeMutation, state.projects, state.threads],
343 );
344​
345 const handleProjectContextMenu = useCallback(
346 async (projectId: string, position: { x: number; y: number }) => {
347 if (!api) return;
348 const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
349 if (clicked !== "delete") return;
350​
351 const project = state.projects.find((entry) => entry.id === projectId);
352 if (!project) return;
353​
354 const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
355 if (projectThreads.length > 0) {
356 toastManager.add({
357 type: "warning",
358 title: "Project is not empty",
359 description: "Delete all threads in this project before deleting it.",
360 });
361 return;
362 }
363​
364 const confirmed = await api.dialogs.confirm(
365 [`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
366 );
367 if (!confirmed) return;
368​
369 if (isElectron) {
370 try {
371 await api.projects.remove({ id: projectId });
372 } catch (error) {
373 const message =
374 error instanceof Error ? error.message : "Unknown error deleting project.";
375 console.error("Failed to remove project", { projectId, error });
376 toastManager.add({
377 type: "error",
378 title: `Failed to delete "${project.name}"`,
379 description: message,
380 });
381 return;
382 }
383 }
384​
385 dispatch({ type: "DELETE_PROJECT", projectId });
386 },
387 [api, dispatch, state.projects, state.threads],
388 );
389​
390 useEffect(() => {
391 const onWindowKeyDown = (event: KeyboardEvent) => {
392 const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
393 if (isChatNewLocalShortcut(event, keybindings)) {
394 const projectId = activeThread?.projectId ?? state.projects[0]?.id;
395 if (!projectId) return;
396 event.preventDefault();
397 handleNewThread(projectId);
398 return;
399 }
400​
401 if (!isChatNewShortcut(event, keybindings)) return;
402 const projectId = activeThread?.projectId ?? state.projects[0]?.id;
403 if (!projectId) return;
404 event.preventDefault();
405 handleNewThread(projectId, {
406 branch: activeThread?.branch ?? null,
407 worktreePath: activeThread?.worktreePath ?? null,
408 });
409 };
410​
411 window.addEventListener("keydown", onWindowKeyDown);
412 return () => {
413 window.removeEventListener("keydown", onWindowKeyDown);
414 };
415 }, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
416​
417 return (
418 <aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
419 {/* Branding */}
420 <div
421 className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
422 >
423 <span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
424 T3 <span className="font-normal text-muted-foreground">Code</span>
425 </span>
426 <button
427 type="button"
428 className="rounded-md p-1.5 text-muted-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-muted-foreground"
429 onClick={() => setTheme(THEME_CYCLE[theme])}
430 aria-label={`Theme: ${theme}`}
431 title={`Theme: ${theme}`}
432 >
433 {theme === "system" ? (
434 <MonitorIcon className="size-3.5" />
435 ) : theme === "light" ? (
436 <SunIcon className="size-3.5" />
437 ) : (
438 <MoonIcon className="size-3.5" />
439 )}
440 </button>
441 </div>
442​
443 {/* New thread (global) */}
444 <div className="px-3 pb-3">
445 <button
446 type="button"
447 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"
448 onClick={() => {
449 if (state.projects.length === 0) {
450 setAddingProject(true);
451 return;
452 }
453 const firstProject = state.projects[0];
454 if (firstProject) handleNewThread(firstProject.id);
455 }}
456 >
457 <span className="text-foreground">+</span>
458 New thread
459 </button>
460 </div>
461​
462 {/* Project list */}
463 <nav className="flex-1 overflow-y-auto px-2">
464 {state.projects.map((project) => {
465 const threads = state.threads
466 .filter((t) => t.projectId === project.id)
467 .toSorted((a, b) => {
468 const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
469 if (byDate !== 0) return byDate;
470 return b.id.localeCompare(a.id);
471 });
472 return (
473 <div key={project.id} className="mb-1">
474 {/* Project header */}
475 <button
476 type="button"
477 className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
478 onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
479 onContextMenu={(e) => {
480 e.preventDefault();
481 void handleProjectContextMenu(project.id, {
482 x: e.clientX,
483 y: e.clientY,
484 });
485 }}
486 >
487 <span className="text-[10px] text-muted-foreground/70">
488 {project.expanded ? "▼" : "▶"}
489 </span>
490 <span className="flex-1 truncate text-xs font-medium text-foreground/90">
491 {project.name}
492 </span>
493 <span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
494 </button>
495​
496 {/* Threads */}
497 {project.expanded && (
498 <div className="ml-2 border-l border-border/80 pl-2">
499 {threads.map((thread) => {
500 const isActive = state.activeThreadId === thread.id;
501 const threadStatus = threadStatusPill(
502 thread,
503 pendingApprovalByThreadId.get(thread.id) === true,
504 );
505 const terminalStatus = terminalStatusIndicator(thread);
506 return (
507 <button
508 key={thread.id}
509 type="button"
510 className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 ${
511 isActive
512 ? "bg-accent text-foreground"
513 : "text-muted-foreground hover:bg-secondary"
514 }`}
515 onClick={() =>
516 dispatch({
517 type: "SET_ACTIVE_THREAD",
518 threadId: thread.id,
519 })
520 }
521 onContextMenu={(e) => {
522 e.preventDefault();
523 void handleThreadContextMenu(thread.id, {
524 x: e.clientX,
525 y: e.clientY,
526 });
527 }}
528 >
529 <div className="flex min-w-0 flex-1 items-center gap-1.5">
530 {threadStatus && (
531 <span
532 className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
533 >
534 <span
535 className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
536 threadStatus.pulse ? "animate-pulse" : ""
537 }`}
538 />
539 <span className="hidden md:inline">{threadStatus.label}</span>
540 </span>
541 )}
542 <span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
543 </div>
544 <div className="ml-2 flex shrink-0 items-center gap-1.5">
545 {terminalStatus && (
546 <span
547 role="img"
548 aria-label={terminalStatus.label}
549 title={terminalStatus.label}
550 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
551 >
552 <TerminalIcon
553 className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
554 />
555 </span>
556 )}
557 <span className="text-[10px] text-muted-foreground/40">
558 {formatRelativeTime(thread.createdAt)}
559 </span>
560 </div>
561 </button>
562 );
563 })}
564​
565 {/* New thread within project */}
566 <button
567 type="button"
568 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"
569 onClick={() => handleNewThread(project.id)}
570 >
571 <span>+</span> New thread
572 </button>
573 </div>
574 )}
575 </div>
576 );
577 })}
578​
579 {state.projects.length === 0 && !addingProject && (
580 <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
581 No projects yet.
582 <br />
583 Add one to get started.
584 </div>
585 )}
586 </nav>
587​
588 {/* Add project form */}
589 {addingProject ? (
590 <div className="border-t border-border p-3">
591 <p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70">
592 Add project
593 </p>
594 <input
595 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"
596 placeholder="/path/to/project"
597 value={newCwd}
598 onChange={(e) => setNewCwd(e.target.value)}
599 onKeyDown={(e) => {
600 if (e.key === "Enter") handleAddProject();
601 if (e.key === "Escape") setAddingProject(false);
602 }}
603 />
604 {isElectron && api && (
605 <button
606 type="button"
607 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"
608 onClick={() => void handlePickFolder()}
609 disabled={isPickingFolder || isAddingProject}
610 >
611 {isPickingFolder ? "Picking folder..." : "Browse for folder"}
612 </button>
613 )}
614 <div className="flex gap-2">
615 <button
616 type="button"
617 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"
618 onClick={handleAddProject}
619 disabled={isAddingProject}
620 >
621 {isAddingProject ? "Adding..." : "Add"}
622 </button>
623 <button
624 type="button"
625 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"
626 onClick={() => setAddingProject(false)}
627 >
628 Cancel
629 </button>
630 </div>
631 </div>
632 ) : (
633 <div className="border-t border-border p-3">
634 <button
635 type="button"
636 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"
637 onClick={() => setAddingProject(true)}
638 >
639 + Add project
640 </button>
641 </div>
642 )}
643 </aside>
644 );