forked from OpenCoven/coven-cave
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomux-view.tsx
More file actions
2513 lines (2427 loc) · 117 KB
/
Copy pathcomux-view.tsx
File metadata and controls
2513 lines (2427 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
import { Fragment, useCallback, useEffect, useMemo, useReducer, useRef, useState, type CSSProperties, type DragEvent, type MouseEvent, type MutableRefObject, type ReactNode } from "react";
import { relativeTime } from "@/lib/relative-time";
import { useDateTimePrefs } from "@/lib/datetime-format";
import { Group, Panel, Separator } from "react-resizable-panels";
import { BottomTerminal } from "@/components/bottom-terminal";
import { killPtyBridge } from "@/lib/pty-ws-bridge";
import { Icon } from "@/lib/icon";
import { copyText } from "@/lib/clipboard";
import { ProjectTree, type ProjectTreeHandle } from "@/components/project-tree";
import { CodeQuickOpen } from "@/components/code-quick-open";
import { MarkdownBlock, SyntaxBlock } from "@/components/message-bubble";
import { SessionChangesInner } from "@/components/session-changes-panel";
import { useChangesSummary } from "@/lib/use-changes-summary";
import { CodeEditor } from "@/components/code-editor";
import { resolveLangLabel } from "@/lib/code-lang";
import {
CODE_PRESET_COLUMN_FLEX,
CODE_PRESET_EVENT,
CODE_PRESET_RIGHT_VIEW,
readProjectListCollapsed,
readCodePreset,
writeProjectListCollapsed,
type CodePreset,
} from "@/lib/code-layout-preset";
import type { SearchResult } from "@/lib/project-search";
import { SeparatorHandle } from "@/components/ui/separator-handle";
import { useAnnouncer } from "@/components/ui/live-region";
import { EmptyState } from "@/components/ui/empty-state";
import { ErrorState } from "@/components/ui/error-state";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import {
deriveComuxProjects,
projectName,
type ComuxProject,
} from "@/lib/comux-projects";
import { ProjectAvatar } from "@/components/project-avatar";
import { useRovingTabIndex } from "@/lib/use-roving-tabindex";
import { ContextMenu, openContextMenuAt, type ContextMenuState } from "@/components/ui/context-menu";
import { PopoverItem, PopoverSeparator } from "@/components/ui/popover";
import {
DndContext,
PointerSensor,
useSensor,
useSensors,
closestCenter,
type DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
useSortable,
arrayMove,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
readProjectOrder,
writeProjectOrder,
readPinnedProjects,
writePinnedProjects,
readSelectedProject,
writeSelectedProject,
toggleProjectPin,
isProjectPinned,
orderProjects,
} from "@/lib/comux-project-order";
import {
addTerminalSession,
closeTerminalSession,
createTerminalLayout,
focusTerminalSession,
moveTerminalPane,
normalizeTerminalLayout,
removeTerminalPaneView,
renameTerminalSession,
reorderTerminalSessions,
terminalLayoutVisibleSessionIds,
type TerminalLayoutNode,
type TerminalLayoutState,
type TerminalSession,
type TerminalSplitDirection,
type TerminalSplitSide,
} from "@/lib/terminal-layout";
import {
directionalNeighbor,
cycleVisibleSession,
paneNumberMap,
sessionAtPaneNumber,
type PaneDirection,
} from "@/lib/terminal-nav";
import { broadcastTargetIds } from "@/lib/terminal-broadcast";
import type { SessionRow } from "@/lib/types";
type ComuxViewMode = "terminal" | "projects";
type SessionPlacement = "replace" | "split";
type Props = {
view: ComuxViewMode;
sessions: SessionRow[];
onOpenSession: (sessionId: string, familiarId?: string | null) => void;
onNewChat: (projectRoot: string) => void;
active?: boolean;
/** Suffix that isolates this instance's persisted terminal layout/sessions
* from other ComuxView instances (e.g. the Code workspace keeps its own
* terminals separate from the standalone Terminal surface). */
storageNamespace?: string;
/** Controlled right-pane view. When provided (with onRightViewChange), the
* parent owns the Files↔Changes selection — the Code workspace drives it from
* its top-level tabs — and comux hides its own inline Files/Changes toggle and
* collapses the file-tree column while Changes is shown (so Changes is a
* full-width tab). Omit both for the standalone, self-toggling behaviour. */
rightView?: "files" | "changes";
onRightViewChange?: (view: "files" | "changes") => void;
/** Center column slot — the familiar conversation. When provided (the Code
* workspace), the projects view lays out three columns in the Codex position:
* the file-tree explorer (left), this chat (center), and the preview / Changes
* review (right). Omitted elsewhere, where
* comux stays two-column (tree | preview/changes). */
centerSlot?: ReactNode;
/** Code mode moves project/thread navigation into the primary shell sidebar.
* When this is true, keep this column focused on the selected project's
* details, search, files, terminals, preview, and diff state. */
hideProjectNavigator?: boolean;
/** Remove the left file-tree explorer column entirely (project header,
* Terminal/New chat, in-project search, sessions, and the FILES tree), so the
* surface is just the conversation + preview/Changes. The Code surface sets
* this; standalone project browsers keep their tree. */
hideFileTree?: boolean;
};
type ProjectFilePreview =
| { kind: "text"; content: string; size?: number }
| { kind: "image"; dataUrl: string; mimeType: string; size?: number }
| { kind: "error"; message: string };
const STORAGE_SESSIONS = "cave:comux:sessions";
const STORAGE_LAYOUT = "cave:comux:terminal-layout:v1";
const TERMINAL_SESSION_DRAG_TYPE = "application/x-cave-terminal-session";
function TerminalDropZone({
side,
onSplit,
}: {
side: TerminalSplitSide;
onSplit: (sessionId: string, side: TerminalSplitSide) => void;
}) {
const [over, setOver] = useState(false);
const acceptsTerminalSession = (event: DragEvent<HTMLDivElement>) =>
Array.from(event.dataTransfer.types).includes(TERMINAL_SESSION_DRAG_TYPE);
return (
<div
className={`comux-terminal-drop-zone comux-terminal-drop-zone--${side}${over ? " comux-terminal-drop-zone--over" : ""}`}
data-drop-side={side}
aria-hidden="true"
onDragEnter={(e) => {
if (!acceptsTerminalSession(e)) return;
e.preventDefault();
setOver(true);
}}
onDragOver={(e) => {
if (!acceptsTerminalSession(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setOver(true);
}}
onDragLeave={() => setOver(false)}
onDrop={(e) => {
if (!acceptsTerminalSession(e)) return;
e.preventDefault();
setOver(false);
const dragged = e.dataTransfer.getData(TERMINAL_SESSION_DRAG_TYPE);
if (!dragged) return;
onSplit(dragged, side);
}}
/>
);
}
function readLegacySessions(storageKey: string): TerminalSession[] {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(storageKey);
if (!raw) return [];
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) return [];
return parsed.filter(
(s): s is TerminalSession =>
typeof s === "object" &&
s !== null &&
typeof (s as Record<string, unknown>).id === "string" &&
typeof (s as Record<string, unknown>).label === "string",
).map((s) => ({
id: s.id,
label: s.label,
projectRoot:
typeof (s as Record<string, unknown>).projectRoot === "string"
? ((s as Record<string, unknown>).projectRoot as string)
: undefined,
}));
} catch {
return [];
}
}
function isLayoutNode(value: unknown): value is TerminalLayoutNode {
if (typeof value !== "object" || value === null) return false;
const node = value as Record<string, unknown>;
if (node.kind === "leaf") return typeof node.sessionId === "string";
if (node.kind !== "horizontal" && node.kind !== "vertical") return false;
return Array.isArray(node.children) && node.children.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const child = entry as Record<string, unknown>;
return typeof child.size === "number" && isLayoutNode(child.node);
});
}
function readTerminalLayout(layoutKey: string, sessionsKey: string): TerminalLayoutState {
if (typeof window === "undefined") return createTerminalLayout();
try {
const raw = window.localStorage.getItem(layoutKey);
if (raw) {
const parsed = JSON.parse(raw) as Partial<TerminalLayoutState>;
if (
parsed.version === 1 &&
Array.isArray(parsed.sessions) &&
(parsed.root === null || isLayoutNode(parsed.root))
) {
const layout: TerminalLayoutState = {
version: 1,
sessions: parsed.sessions.filter(
(session): session is TerminalSession =>
typeof session === "object" &&
session !== null &&
typeof (session as Record<string, unknown>).id === "string" &&
typeof (session as Record<string, unknown>).label === "string",
).map((session) => ({
id: session.id,
label: session.label,
projectRoot:
typeof session.projectRoot === "string"
? session.projectRoot
: undefined,
})),
activeSessionId:
typeof parsed.activeSessionId === "string"
? parsed.activeSessionId
: null,
root: parsed.root ?? null,
};
return normalizeTerminalLayout(layout);
}
}
} catch {
// Fall back to the legacy flat session list below.
}
const legacy = readLegacySessions(sessionsKey);
return createTerminalLayout(legacy, legacy[0]?.id ?? null);
}
type TerminalLayoutAction =
| {
type: "add";
session: TerminalSession;
placement?: SessionPlacement;
targetSessionId?: string | null;
side?: TerminalSplitSide;
}
| { type: "close"; sessionId: string }
| { type: "focus"; sessionId: string }
| { type: "move"; sourceSessionId: string; targetSessionId: string; side: TerminalSplitSide }
| { type: "remove-view"; sessionId: string }
| { type: "reorder"; sourceSessionId: string; targetSessionId: string }
| { type: "rename"; sessionId: string; label: string };
function terminalLayoutReducer(
state: TerminalLayoutState,
action: TerminalLayoutAction,
): TerminalLayoutState {
switch (action.type) {
case "add":
return addTerminalSession(state, action.session, {
placement: action.placement,
targetSessionId: action.targetSessionId ?? undefined,
side: action.side,
});
case "close":
return closeTerminalSession(state, action.sessionId);
case "focus":
return focusTerminalSession(state, action.sessionId);
case "move":
return moveTerminalPane(state, action);
case "remove-view":
return removeTerminalPaneView(state, action.sessionId);
case "reorder":
return reorderTerminalSessions(state, action.sourceSessionId, action.targetSessionId);
case "rename":
return renameTerminalSession(state, action.sessionId, action.label);
}
}
function uid(): string {
return crypto.randomUUID();
}
const MARKDOWN_EXTS = new Set(["md", "mdx", "markdown"]);
function isMarkdownPath(path: string | null): boolean {
if (!path) return false;
const ext = path.split(".").pop()?.toLowerCase();
return Boolean(ext && MARKDOWN_EXTS.has(ext));
}
function formatBytes(bytes: number | undefined): string | null {
if (typeof bytes !== "number" || bytes < 0) return null;
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function shortProjectTime(iso: string | null): string {
return iso ? relativeTime(iso) : "No sessions yet";
}
// One row in the Projects explorer. Sortable (drag to reorder, keyed by root)
// while `dragEnabled`; carries the per-project identity tile, monogram, a pin
// indicator, and the running dot. A pointer activation distance keeps a quick
// click an "open" — only a deliberate drag (≥5px) reorders.
function SortableProjectRow({
project,
isActive,
isPinned,
dragEnabled,
activeRowRef,
onSelect,
onRowContextMenu,
}: {
project: ComuxProject;
isActive: boolean;
isPinned: boolean;
dragEnabled: boolean;
activeRowRef: MutableRefObject<HTMLButtonElement | null>;
onSelect: (project: ComuxProject) => void;
onRowContextMenu: (project: ComuxProject, e: MouseEvent) => void;
}) {
const { setNodeRef, listeners, transform, transition, isDragging } = useSortable({
id: project.root,
disabled: !dragEnabled,
});
const meta: string[] = [];
if (project.sessionCount > 0) {
meta.push(`${project.sessionCount} ${project.sessionCount === 1 ? "chat" : "chats"}`);
}
if (project.updatedAt) meta.push(shortProjectTime(project.updatedAt));
const style: CSSProperties = {
transform: CSS.Translate.toString(transform),
transition,
};
return (
<button
// Merge the sortable node ref with the active-row ref (used to keep the
// selected project scrolled into view) without clobbering either.
ref={(el) => {
setNodeRef(el);
if (isActive) activeRowRef.current = el;
}}
type="button"
data-project-row
data-dragging={isDragging ? "true" : undefined}
onClick={() => onSelect(project)}
onContextMenu={(e) => onRowContextMenu(project, e)}
title={project.root}
aria-current={isActive ? "true" : undefined}
style={style}
{...listeners}
className={`comux-project-row group flex w-full items-center gap-2.5 rounded-lg px-2 py-[7px] text-left text-[12px] ${
dragEnabled ? "cursor-grab active:cursor-grabbing" : ""
} ${
isActive
? "comux-project-row--active text-[var(--text-primary)]"
: "text-[var(--text-primary)]"
}`}
>
<ProjectAvatar name={project.name} root={project.root} size="lg" className="shrink-0" />
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate font-medium leading-tight">{project.name}</span>
{meta.length > 0 && (
<span className="truncate text-[10px] leading-tight tabular-nums text-[var(--text-muted)]">
{meta.join(" · ")}
</span>
)}
</span>
{isPinned && (
<Icon
name="ph:push-pin-fill"
width={11}
className="shrink-0 text-[var(--accent-presence)]"
title="Pinned"
aria-hidden
/>
)}
{project.runningCount > 0 && (
<span
className="h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-[var(--color-success)] shadow-[0_0_8px_var(--color-success)]"
title={`${project.runningCount} running`}
/>
)}
</button>
);
}
export function ComuxView({ view, sessions: daemonSessions, onOpenSession, onNewChat, active = true, storageNamespace = "", rightView: rightViewProp, onRightViewChange, centerSlot, hideProjectNavigator = false, hideFileTree = false }: Props) {
useDateTimePrefs(); // subscribe: re-render when the date/time density pref changes
const layoutKey = STORAGE_LAYOUT + storageNamespace;
const sessionsKey = STORAGE_SESSIONS + storageNamespace;
const [terminalLayout, dispatchTerminalLayout] = useReducer(
terminalLayoutReducer,
undefined,
() => readTerminalLayout(layoutKey, sessionsKey),
);
const sessions = terminalLayout.sessions;
const activeSessionId = terminalLayout.activeSessionId;
const currentIdx = Math.max(
0,
sessions.findIndex((session) => session.id === activeSessionId),
);
// Project tab state
const [previewPath, setPreviewPath] = useState<string | null>(null);
const [preview, setPreview] = useState<ProjectFilePreview | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewError, setPreviewError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [copiedPath, setCopiedPath] = useState(false);
const [previewRaw, setPreviewRaw] = useState(false);
// 1-based line to scroll the preview to (set when opened from a search match,
// cleared when opened from the file tree).
const [previewLine, setPreviewLine] = useState<number | undefined>(undefined);
// Editable preview: edit mode swaps the read-only render for a textarea and
// POSTs back to /api/project-file on save.
const [editing, setEditing] = useState(false);
const [editValue, setEditValue] = useState("");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
// Brief "Saved" confirmation after a successful write (auto-clears).
const [justSaved, setJustSaved] = useState(false);
const { announce } = useAnnouncer();
const [tabDropTargetId, setTabDropTargetId] = useState<string | null>(null);
const [sessionsCollapsed, setSessionsCollapsed] = useState(false);
// Projects list (the 200px column) visibility, driven by the Code workspace
// toolbar's Projects toggle and its layout presets over window events. Lives
// here because comux owns the column; code-view only mirrors the boolean.
const [projectListCollapsed, setProjectListCollapsed] = useState(false);
const [projectDetailCollapsed, setProjectDetailCollapsed] = useState(false);
const [filePreviewCollapsed, setFilePreviewCollapsed] = useState(false);
const [codePreset, setCodePreset] = useState<CodePreset>(() => readCodePreset());
// Right pane view: the file preview, or the project's git changes/diff review.
// Controllable: when the parent passes onRightViewChange (the Code workspace's
// top-level Files/Changes tabs), the prop wins and every setRightView call is
// forwarded up; otherwise this is local, self-toggling state. The setter name
// stays `setRightView` so the diff-first/auto-switch logic below is unchanged.
const [rightViewState, setRightViewState] = useState<"files" | "changes">("files");
const isControlledRightView = onRightViewChange != null;
const rightView = isControlledRightView ? (rightViewProp ?? "files") : rightViewState;
const setRightView = useCallback(
(next: "files" | "changes") => {
if (onRightViewChange) onRightViewChange(next);
else setRightViewState(next);
},
[onRightViewChange],
);
// Diff-first review: auto-switch to Changes the first time an agent run
// produces edits — but never fight an explicit user choice. pinnedRightView
// flips once the user clicks a toggle or opens a file; prevChangeCount tracks
// the 0→>0 edit transition so we surface the diff exactly once per project.
const pinnedRightViewRef = useRef(false);
// Tracks the most-recent openFilePreview request so a slow response for an
// older file can't clobber a newer one (wrong file shown / edited).
const previewReqRef = useRef<string | null>(null);
// Jump-to-diff target from a transcript edit tool (cave:open-file-diff). The
// nonce re-triggers the focus even when the same path is clicked again.
const [focusDiff, setFocusDiff] = useState<{ path: string; nonce: number } | null>(null);
const prevChangeCountRef = useRef(0);
// Project-wide code search (CODE-SEARCH-01).
const [searchInput, setSearchInput] = useState("");
const [searchRegex, setSearchRegex] = useState(false);
const [searchCaseSensitive, setSearchCaseSensitive] = useState(false);
const [searchGlob, setSearchGlob] = useState("");
const [searchResult, setSearchResult] = useState<SearchResult | null>(null);
const [searchLoading, setSearchLoading] = useState(false);
const [searchError, setSearchError] = useState<string | null>(null);
const treeRef = useRef<ProjectTreeHandle | null>(null);
const wasActiveTerminalRef = useRef(false);
// Daemon project root — forwarded to BottomTerminal so terminals open in
// the right CWD instead of the app bundle dir.
const [daemonProjectRoot, setDaemonProjectRoot] = useState<string | undefined>(undefined);
const [selectedProjectRoot, setSelectedProjectRoot] = useState<string | undefined>(undefined);
// Projects-list ergonomics: type-to-filter (mirrors the Chat-tab projects
// list), arrow-key roving over the rows, and keeping the active row in view.
const [projectFilter, setProjectFilter] = useState("");
const projectFilterRef = useRef<HTMLInputElement>(null);
const projectListRef = useRef<HTMLDivElement>(null);
const activeProjectRowRef = useRef<HTMLButtonElement | null>(null);
const selectedRootRef = useRef<string | undefined>(undefined);
// Right-click context menu for a project row. `menuTarget` records which
// project was right-clicked (one menu serves the whole list).
const [projectMenu, setProjectMenu] = useState<ContextMenuState>(null);
const [projectMenuTarget, setProjectMenuTarget] = useState<ComuxProject | null>(null);
// Pinned roots float to the top; manual drag order persists below them. Both
// load from localStorage after mount so SSR markup and first render agree.
const [pinnedProjects, setPinnedProjects] = useState<string[]>([]);
const [projectOrder, setProjectOrder] = useState<string[]>([]);
useEffect(() => {
setPinnedProjects(readPinnedProjects());
setProjectOrder(readProjectOrder());
}, []);
// Pointer only (no KeyboardSensor) — arrow keys belong to the roving tab
// index, not to drag. Distance keeps a click an "open", not a drag.
const projectSensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
useEffect(() => {
void (async () => {
try {
const res = await fetch("/api/daemon/status", { cache: "no-store" });
const json = (await res.json()) as Record<string, unknown>;
const root =
(json.workspacePath as string | undefined) ??
(json.projectRoot as string | undefined);
if (root && typeof root === "string") {
setDaemonProjectRoot(root);
}
} catch {
// non-fatal — terminal will open in default shell dir
}
})();
}, []);
// Persist the full pane tree. Keep the legacy flat key in sync so older
// versions can still recover terminal tabs if a user rolls back.
useEffect(() => {
window.localStorage.setItem(layoutKey, JSON.stringify(terminalLayout));
window.localStorage.setItem(sessionsKey, JSON.stringify(sessions));
}, [terminalLayout, sessions, layoutKey, sessionsKey]);
const projects = useMemo(
() => deriveComuxProjects(daemonSessions, daemonProjectRoot),
[daemonSessions, daemonProjectRoot],
);
// Display order: pinned-first + manual drag order applied over the recency
// sort from deriveComuxProjects.
const orderedProjects = useMemo(
() => orderProjects(projects, projectOrder, pinnedProjects),
[projects, projectOrder, pinnedProjects],
);
// Filter the project list by name or path (case-insensitive). The code-search
// box below is a separate ripgrep search — this only narrows the switcher.
const visibleProjects = useMemo(() => {
const q = projectFilter.trim().toLowerCase();
if (!q) return orderedProjects;
return orderedProjects.filter(
(p) => p.name.toLowerCase().includes(q) || p.root.toLowerCase().includes(q),
);
}, [orderedProjects, projectFilter]);
// Drag reorders only the unfiltered full list (a filtered subset can't define
// a total order). Persist the new root sequence as the manual order.
const dragEnabled = !projectFilter.trim();
const handleProjectDragEnd = useCallback(
(event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const ids = orderedProjects.map((p) => p.root);
const from = ids.indexOf(String(active.id));
const to = ids.indexOf(String(over.id));
if (from < 0 || to < 0) return;
const next = arrayMove(ids, from, to);
setProjectOrder(next);
writeProjectOrder(next);
},
[orderedProjects],
);
const toggleProjectPinned = useCallback((root: string) => {
setPinnedProjects((prev) => {
const next = toggleProjectPin(prev, root);
writePinnedProjects(next);
return next;
});
}, []);
// Arrow-key roving over the project rows (WAI-ARIA): one tab stop, ↑/↓ move,
// Home/End jump. The hook ignores keystrokes while the filter input is focused.
useRovingTabIndex({
containerRef: projectListRef,
itemSelector: "[data-project-row]",
orientation: "vertical",
});
// GitHub-style "/" focuses the project filter while the Code surface is shown,
// unless the user is already typing or holding a modifier.
useEffect(() => {
if (hideProjectNavigator) return;
if (!active) return;
function onKey(e: KeyboardEvent) {
if (e.key !== "/" || e.metaKey || e.ctrlKey || e.altKey) return;
const t = e.target as HTMLElement | null;
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
const el = projectFilterRef.current;
if (!el) return;
e.preventDefault();
el.focus();
}
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [active, hideProjectNavigator]);
// Keep the selected project on screen — when the list is long, or after a
// filter changes which rows are rendered. block:"nearest" is a no-op if it's
// already visible, so clicking a visible row never jolts the scroll.
useEffect(() => {
activeProjectRowRef.current?.scrollIntoView({ block: "nearest" });
}, [selectedProjectRoot, visibleProjects]);
const selectedProject = useMemo(
() => projects.find((project) => project.root === selectedProjectRoot) ?? projects[0] ?? null,
[projects, selectedProjectRoot],
);
const selectedProjectSessions = useMemo(() => {
if (!selectedProject) return [];
return daemonSessions
.filter((session) => session.project_root === selectedProject.root)
.sort((a, b) =>
(b.updated_at || b.created_at).localeCompare(a.updated_at || a.created_at),
);
}, [daemonSessions, selectedProject]);
const recentProjectSessions = useMemo(
() => selectedProjectSessions.slice(0, 6),
[selectedProjectSessions],
);
const selectedProjectFamiliarId = useMemo(
() => selectedProjectSessions[0]?.familiarId ?? "",
[selectedProjectSessions],
);
useEffect(() => {
if (projects.length === 0) {
setSelectedProjectRoot(undefined);
return;
}
// Restore happens here rather than in a mount effect: projects arrive
// async, and the empty-list reset above would wipe a mount-time restore
// before the list ever populated.
setSelectedProjectRoot((current) => {
const stored = current ?? readSelectedProject() ?? undefined;
return stored && projects.some((project) => project.root === stored)
? stored
: projects[0].root;
});
}, [projects]);
useEffect(() => {
if (selectedProjectRoot) writeSelectedProject(selectedProjectRoot);
}, [selectedProjectRoot]);
const addSession = useCallback((rootOverride?: string, placement: SessionPlacement = "replace") => {
const id = uid();
const root = rootOverride ?? selectedProjectRoot ?? daemonProjectRoot;
const targetSessionId =
terminalLayout.activeSessionId ??
terminalLayoutVisibleSessionIds(terminalLayout)[0] ??
null;
dispatchTerminalLayout({
type: "add",
session: {
id,
label: root ? `${projectName(root)} ${sessions.length + 1}` : `Terminal ${sessions.length + 1}`,
projectRoot: root,
},
placement,
targetSessionId,
side: placement === "split" ? "right" : undefined,
});
return id;
}, [daemonProjectRoot, selectedProjectRoot, sessions.length, terminalLayout]);
useEffect(() => {
const activeTerminal = view === "terminal" && active;
if (!activeTerminal) {
wasActiveTerminalRef.current = false;
return;
}
if (wasActiveTerminalRef.current) return;
wasActiveTerminalRef.current = true;
if (sessions.length > 0) return;
addSession();
}, [active, addSession, sessions.length, view]);
const removeSession = useCallback(
(idx: number) => {
const removedId = sessions[idx]?.id;
if (!removedId) return;
dispatchTerminalLayout({ type: "close", sessionId: removedId });
// Closing a tab is the ONLY place a desktop PTY is killed. The
// terminal component deliberately does not stop the shell on
// unmount — tab switches remount terminals through the keepalive
// container, and killing there raced the next mount's liveness
// check, leaving a dead pane that ate keystrokes.
const internals = (window as unknown as Record<string, unknown>)
.__TAURI_INTERNALS__;
if (internals) {
void import("@tauri-apps/api/core")
.then(({ invoke }) =>
invoke("pty_stop", { threadId: `cave.comux.${removedId}` }),
)
.catch(() => {});
}
// WS transport (browser / iOS / Android): the desktop pty_stop above only
// reaps native-IPC shells. Without this, closing a tab merely drops the
// socket — which the server treats as a transient detach — so the shell
// (and its foreground job) leaks for the full detach grace (~5 min).
// killPtyBridge sends an explicit kill frame; it is a no-op when no WS
// bridge is registered for the threadId (i.e. the desktop transport), so
// running it unconditionally is safe.
killPtyBridge(`cave.comux.${removedId}`);
},
[sessions],
);
const renameSession = useCallback((idx: number, label: string) => {
const session = sessions[idx];
if (!session) return;
// Ignore blank/whitespace-only names so a cleared tab keeps its label
// instead of becoming an empty tab.
const trimmed = label.trim();
if (!trimmed) return;
dispatchTerminalLayout({ type: "rename", sessionId: session.id, label: trimmed });
}, [sessions]);
const visiblePaneSessionIds = useMemo(
() => terminalLayoutVisibleSessionIds(terminalLayout),
[terminalLayout],
);
// Zoom/maximize: when set, the surface renders only this pane full-size while
// its siblings stay alive (PTYs untouched) behind it. 1-based pane numbers
// back the badges + ⌘1…9 quick-jump.
const [zoomedSessionId, setZoomedSessionId] = useState<string | null>(null);
// Broadcast input ("sync panes"): a keystroke in any pane is mirrored to every
// other live pane. Each BottomTerminal registers its PTY writer; refs keep the
// input handler stable so toggling broadcast never re-mounts a pane.
const [broadcast, setBroadcast] = useState(false);
const broadcastRef = useRef(false);
broadcastRef.current = broadcast;
const paneWritersRef = useRef(new Map<string, (data: string) => void>());
const registerPaneWriter = useCallback(
(paneSessionId: string, write: ((data: string) => void) | null) => {
if (write) paneWritersRef.current.set(paneSessionId, write);
else paneWritersRef.current.delete(paneSessionId);
},
[],
);
const handlePaneInput = useCallback((originSessionId: string, data: string) => {
if (!broadcastRef.current) return;
for (const id of broadcastTargetIds([...paneWritersRef.current.keys()], originSessionId)) {
try {
paneWritersRef.current.get(id)?.(data);
} catch {
/* pane unmounted mid-broadcast — drop it */
}
}
}, []);
const paneNumbers = useMemo(() => paneNumberMap(terminalLayout), [terminalLayout]);
useEffect(() => {
if (zoomedSessionId && !visiblePaneSessionIds.includes(zoomedSessionId)) {
setZoomedSessionId(null);
}
}, [zoomedSessionId, visiblePaneSessionIds]);
const hiddenPaneSessions = useMemo(() => {
const visibleIds = new Set(visiblePaneSessionIds);
return sessions.filter((session) => !visibleIds.has(session.id));
}, [sessions, visiblePaneSessionIds]);
const focusSessionById = useCallback((sessionId: string) => {
dispatchTerminalLayout({ type: "focus", sessionId });
}, []);
const selectSession = useCallback((idx: number) => {
const session = sessions[idx];
if (!session) return;
dispatchTerminalLayout({ type: "focus", sessionId: session.id });
}, [sessions]);
const splitSessionIntoPane = useCallback(
(sessionId: string, targetSessionId: string, side: TerminalSplitSide) => {
if (!sessions.some((session) => session.id === sessionId)) return;
if (sessionId === targetSessionId) return;
dispatchTerminalLayout({
type: "move",
sourceSessionId: sessionId,
targetSessionId,
side,
});
},
[sessions],
);
const acceptsTerminalSessionDrag = useCallback((event: DragEvent<HTMLElement>) =>
Array.from(event.dataTransfer.types).some((type) =>
type === TERMINAL_SESSION_DRAG_TYPE || type === "text/plain",
),
[]);
const onSplitTerminal = useCallback(
(direction: TerminalSplitDirection) => {
const side: TerminalSplitSide = direction === "horizontal" ? "right" : "bottom";
const id = uid();
const root = selectedProjectRoot ?? daemonProjectRoot;
dispatchTerminalLayout({
type: "add",
session: {
id,
label: root ? `${projectName(root)} ${sessions.length + 1}` : `Terminal ${sessions.length + 1}`,
projectRoot: root,
},
placement: "split",
targetSessionId: terminalLayout.activeSessionId ?? visiblePaneSessionIds[0] ?? null,
side,
});
},
[daemonProjectRoot, selectedProjectRoot, sessions.length, terminalLayout.activeSessionId, visiblePaneSessionIds],
);
// Direct-manipulation split: spawn a new terminal adjacent to THIS pane
// (inherits its cwd), complementing the global toolbar split + drag-to-split.
const splitFromPane = useCallback(
(targetSessionId: string, side: TerminalSplitSide) => {
const id = uid();
const target = sessions.find((x) => x.id === targetSessionId);
const root = target?.projectRoot ?? selectedProjectRoot ?? daemonProjectRoot;
dispatchTerminalLayout({
type: "add",
session: {
id,
label: root ? `${projectName(root)} ${sessions.length + 1}` : `Terminal ${sessions.length + 1}`,
projectRoot: root,
},
placement: "split",
targetSessionId,
side,
});
},
[daemonProjectRoot, selectedProjectRoot, sessions],
);
useEffect(() => {
if (view !== "terminal" || !active) return;
const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey;
if (!mod) return;
const target = e.target as HTMLElement | null;
if (target?.isContentEditable) return;
// Ctrl-chords typed inside the terminal belong to the SHELL, not to
// tab management: Ctrl+W is readline delete-word and Ctrl+N is
// next-history. Hijacking them closed/spawned tabs mid-keystroke,
// which read as the terminal randomly "losing the ability to type".
// ⌘-chords still manage tabs (macOS terminals reserve ⌘, never Ctrl).
if (e.ctrlKey && !e.metaKey && target?.closest?.(".xterm")) return;
if (e.key === "n" || e.key === "N") {
e.preventDefault();
addSession();
} else if (e.key === "w" || e.key === "W") {
if (sessions.length === 0) return;
e.preventDefault();
removeSession(currentIdx);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [view, active, addSession, removeSession, currentIdx, sessions.length]);
// Multi-pane navigation (tmux-grade): directional focus (⌘⌥Arrow), cycle
// (⌘[ / ⌘]), quick-jump (⌘1…9), and zoom toggle (⌘Enter). All gated to ⌘/Ctrl
// chords the shell never sees; zoom follows focus so navigating while zoomed
// moves the maximized pane.
useEffect(() => {
if (view !== "terminal" || !active) return;
const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey;
if (!mod) return;
const target = e.target as HTMLElement | null;
if (target?.isContentEditable) return;
if (e.ctrlKey && !e.metaKey && target?.closest?.(".xterm")) return;
const activeId = terminalLayout.activeSessionId;
const focusPane = (id: string | null) => {
if (!id) return;
e.preventDefault();
dispatchTerminalLayout({ type: "focus", sessionId: id });
setZoomedSessionId((z) => (z ? id : z)); // zoom follows the focused pane
};
// Directional focus — ⌘⌥Arrow.
if (e.altKey && !e.shiftKey) {
const dir: PaneDirection | null =
e.key === "ArrowLeft" ? "left"
: e.key === "ArrowRight" ? "right"
: e.key === "ArrowUp" ? "up"
: e.key === "ArrowDown" ? "down"
: null;
if (dir && activeId) {
focusPane(directionalNeighbor(terminalLayout, activeId, dir));
}
return;
}
if (e.shiftKey && (e.key === "b" || e.key === "B")) {
e.preventDefault();
setBroadcast((v) => !v);
return;
}
if (e.shiftKey) return;
// Cycle visible panes — ⌘] (next) / ⌘[ (prev).
if (e.key === "]" || e.key === "[") {
focusPane(cycleVisibleSession(terminalLayout, activeId, e.key === "]" ? 1 : -1));
return;
}
// Quick-jump to pane N — ⌘1…9.
if (e.key >= "1" && e.key <= "9") {
const id = sessionAtPaneNumber(terminalLayout, Number(e.key));
if (id) focusPane(id);
return;
}
// Zoom / restore the active pane — ⌘Enter.
if (e.key === "Enter") {
if (!activeId) return;
if (visiblePaneSessionIds.length <= 1 && !zoomedSessionId) return;
e.preventDefault();
setZoomedSessionId((z) => (z ? null : activeId));
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [view, active, terminalLayout, zoomedSessionId, visiblePaneSessionIds]);
const openFilePreview = useCallback(async (path: string, line?: number) => {
previewReqRef.current = path;
setPreviewPath(path);
setPreviewLine(line);
setFilePreviewCollapsed(false);
setPreviewLoading(true);
setPreview(null);
setPreviewError(null);
setPreviewRaw(false);
// Leave any prior edit session — opening a new file discards unsaved edits.
setEditing(false);
setSaveError(null);
try {
const params = new URLSearchParams({
path,
familiarId: selectedProjectFamiliarId,
});
const res = await fetch(
`/api/project-file?${params.toString()}`,
{ cache: "no-store" },
);
const json = (await res.json()) as {
ok: boolean;
kind?: "text" | "image";
content?: string;
dataUrl?: string;
mimeType?: string;
size?: number;
error?: string;
};
// A newer file was opened while this fetch was in flight — drop the stale
// response so it can't paint over the current file.
if (previewReqRef.current !== path) return;
if (json.ok && json.kind === "image" && typeof json.dataUrl === "string" && typeof json.mimeType === "string") {
setPreview({ kind: "image", dataUrl: json.dataUrl, mimeType: json.mimeType, size: json.size });
} else if (json.ok && typeof json.content === "string") {
setPreview({ kind: "text", content: json.content, size: json.size });
} else {
setPreview({ kind: "error", message: json.error ?? "Could not load this file." });
}
} catch (err) {
if (previewReqRef.current !== path) return;
setPreview({ kind: "error", message: `Could not load this file. ${String(err)}` });
} finally {
if (previewReqRef.current === path) setPreviewLoading(false);
}
}, [selectedProjectFamiliarId]);