-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathindex.ts
More file actions
2019 lines (1807 loc) · 73.9 KB
/
Copy pathindex.ts
File metadata and controls
2019 lines (1807 loc) · 73.9 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
import { existsSync, readFileSync, unlinkSync, writeFileSync, appendFileSync, watch, type FSWatcher } from "fs";
import { join } from "path";
import { homedir } from "os";
import type { MuxProvider } from "../contracts/mux";
import { isFullSidebarCapable, isBatchCapable } from "../contracts/mux";
import type { AgentEvent } from "../contracts/agent";
import type { AgentWatcher, AgentWatcherContext } from "../contracts/agent-watcher";
import { AgentTracker } from "../agents/tracker";
import { SessionOrder } from "./session-order";
import { SessionMetadataStore } from "./metadata-store";
import { buildLocalLinks, loadPortlessState } from "./portless";
import {
areWidthReportsSuppressed,
canStartTransientResize,
createSidebarCoordinator,
readSidebarCoordinatorState,
} from "./sidebar-coordinator";
import { loadConfig, saveConfig } from "../config";
import type { SessionFilterMode } from "../config";
import {
clampSidebarWidth,
} from "./sidebar-width-sync";
import {
type ServerState,
type SessionData,
type ClientCommand,
type FocusUpdate,
SERVER_PORT,
SERVER_HOST,
PID_FILE,
SERVER_IDLE_TIMEOUT_MS,
STUCK_RUNNING_TIMEOUT_MS,
} from "../shared";
// --- Debug logger ---
const DEBUG_LOG = "/tmp/opensessions-debug.log";
function log(category: string, msg: string, data?: Record<string, unknown>) {
const ts = new Date().toISOString().slice(11, 23);
const extra = data ? " " + JSON.stringify(data) : "";
const line = `[${ts}] [${category}] ${msg}${extra}\n`;
try { appendFileSync(DEBUG_LOG, line); } catch {}
}
// --- Shell helper (for git commands only) ---
function shell(cmd: string[]): string {
try {
const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" });
return result.stdout.toString().trim();
} catch {
return "";
}
}
// --- Git helpers ---
interface GitInfo {
branch: string;
dirty: boolean;
isWorktree: boolean;
}
const gitInfoCache = new Map<string, { info: GitInfo; ts: number }>();
const GIT_CACHE_TTL_MS = 5000;
const SPAWN_STAGGER_MS = 500;
function getGitInfo(dir: string): GitInfo {
if (!dir) return { branch: "", dirty: false, isWorktree: false };
const cached = gitInfoCache.get(dir);
if (cached && Date.now() - cached.ts < GIT_CACHE_TTL_MS) return cached.info;
const out = shell([
"sh", "-c",
`cd "${dir}" 2>/dev/null && git rev-parse --abbrev-ref HEAD --git-dir 2>/dev/null && echo "---" && git status --porcelain 2>/dev/null`,
]);
if (!out) return { branch: "", dirty: false, isWorktree: false };
const sepIdx = out.indexOf("---");
const headerPart = sepIdx >= 0 ? out.slice(0, sepIdx).trim() : out.trim();
const statusPart = sepIdx >= 0 ? out.slice(sepIdx + 3).trim() : "";
const lines = headerPart.split("\n");
const branch = lines[0] ?? "";
const gitDir = lines[1] ?? "";
const info: GitInfo = {
branch,
dirty: statusPart.length > 0,
isWorktree: gitDir.includes("/worktrees/"),
};
gitInfoCache.set(dir, { info, ts: Date.now() });
return info;
}
function invalidateGitCache(dir?: string) {
if (dir) gitInfoCache.delete(dir);
else gitInfoCache.clear();
}
// --- Port detection ---
// Global port snapshot — refreshed by the port poll timer, read by computeState.
// Runs lsof + ps once for ALL sessions instead of per-session.
let portSnapshot = new Map<string, number[]>();
function refreshPortSnapshot(sessionNames: string[]): boolean {
try {
// 1. Gather pane PIDs for all sessions in one tmux call per session
// (tmux doesn't support multi-session list-panes, so we batch via a single format string)
const panePidsBySession = new Map<string, number[]>();
for (const name of sessionNames) {
const r = Bun.spawnSync(
["tmux", "list-panes", "-s", "-t", name, "-F", "#{pane_pid}"],
{ stdout: "pipe", stderr: "pipe" },
);
const pids = r.stdout.toString().trim().split("\n").filter(Boolean).map(Number).filter((n) => !isNaN(n));
if (pids.length > 0) panePidsBySession.set(name, pids);
}
if (panePidsBySession.size === 0) {
portSnapshot = new Map();
return false;
}
// 2. Build parent→children map from a single ps call
const childrenOf = new Map<number, number[]>();
const psResult = Bun.spawnSync(["ps", "-eo", "pid=,ppid="], { stdout: "pipe", stderr: "pipe" });
for (const line of psResult.stdout.toString().trim().split("\n")) {
const parts = line.trim().split(/\s+/);
if (parts.length < 2) continue;
const pid = parseInt(parts[0], 10);
const ppid = parseInt(parts[1], 10);
if (isNaN(pid) || isNaN(ppid)) continue;
let arr = childrenOf.get(ppid);
if (!arr) { arr = []; childrenOf.set(ppid, arr); }
arr.push(pid);
}
// 3. BFS from pane PIDs to get full descendant tree per session
// Also build a reverse map: pid → session name(s)
const pidToSessions = new Map<number, string[]>();
for (const [name, panePids] of panePidsBySession) {
const allPids = new Set<number>(panePids);
const queue = [...panePids];
while (queue.length > 0) {
const pid = queue.pop()!;
const kids = childrenOf.get(pid);
if (!kids) continue;
for (const kid of kids) {
if (!allPids.has(kid)) {
allPids.add(kid);
queue.push(kid);
}
}
}
for (const pid of allPids) {
let arr = pidToSessions.get(pid);
if (!arr) { arr = []; pidToSessions.set(pid, arr); }
arr.push(name);
}
}
// 4. Single lsof call for all listening TCP ports
const lsofResult = Bun.spawnSync(
["/usr/sbin/lsof", "-iTCP", "-sTCP:LISTEN", "-nP", "-F", "pn"],
{ stdout: "pipe", stderr: "pipe" },
);
if (lsofResult.exitCode !== 0) {
log("ports", "lsof failed", { exitCode: lsofResult.exitCode, stderr: lsofResult.stderr.toString().slice(0, 200) });
return false;
}
// 5. Parse and attribute ports to sessions
const sessionPorts = new Map<string, Set<number>>();
let currentPid = 0;
for (const line of lsofResult.stdout.toString().split("\n")) {
if (line.startsWith("p")) {
currentPid = parseInt(line.slice(1), 10);
} else if (line.startsWith("n")) {
const sessions = pidToSessions.get(currentPid);
if (!sessions) continue;
const match = line.match(/:(\d+)$/);
if (!match) continue;
const port = parseInt(match[1], 10);
if (isNaN(port)) continue;
for (const name of sessions) {
let set = sessionPorts.get(name);
if (!set) { set = new Set(); sessionPorts.set(name, set); }
set.add(port);
}
}
}
// 6. Build the new snapshot
const next = new Map<string, number[]>();
for (const name of sessionNames) {
const set = sessionPorts.get(name);
next.set(name, set ? [...set].sort((a, b) => a - b) : []);
}
const changed = !mapsEqual(portSnapshot, next);
portSnapshot = next;
return changed;
} catch (err) {
log("ports", "refreshPortSnapshot failed", { error: String(err) });
return false;
}
}
function mapsEqual(a: Map<string, number[]>, b: Map<string, number[]>): boolean {
if (a.size !== b.size) return false;
for (const [k, v] of a) {
const bv = b.get(k);
if (!bv || bv.length !== v.length || v.some((n, i) => n !== bv[i])) return false;
}
return true;
}
function getSessionPorts(sessionName: string): number[] {
return portSnapshot.get(sessionName) ?? [];
}
// --- Git HEAD file watchers ---
const gitHeadWatchers = new Map<string, FSWatcher>();
function resolveGitHeadPath(dir: string): string | null {
if (!dir) return null;
const gitDir = shell(["git", "-C", dir, "rev-parse", "--git-dir"]);
if (!gitDir) return null;
const absGitDir = gitDir.startsWith("/") ? gitDir : join(dir, gitDir);
const headPath = join(absGitDir, "HEAD");
return existsSync(headPath) ? headPath : null;
}
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
function onGitHeadChange(broadcastFn: () => void) {
if (debounceTimer) return;
debounceTimer = setTimeout(() => {
debounceTimer = null;
invalidateGitCache();
broadcastFn();
}, 200);
}
function syncGitWatchers(sessions: SessionData[], broadcastFn: () => void) {
const currentDirs = new Set<string>();
for (const s of sessions) {
if (s.dir) currentDirs.add(s.dir);
}
for (const [dir, watcher] of gitHeadWatchers) {
if (!currentDirs.has(dir)) {
watcher.close();
gitHeadWatchers.delete(dir);
}
}
for (const dir of currentDirs) {
if (gitHeadWatchers.has(dir)) continue;
const headPath = resolveGitHeadPath(dir);
if (!headPath) continue;
try {
const watcher = watch(headPath, () => onGitHeadChange(broadcastFn));
gitHeadWatchers.set(dir, watcher);
} catch { /* ignore */ }
}
}
// --- Server startup ---
export function startServer(mux: MuxProvider, extraProviders?: MuxProvider[], watchers?: AgentWatcher[]): void {
const allProviders = [mux, ...(extraProviders ?? [])];
const allWatchers = watchers ?? [];
const tracker = new AgentTracker();
const metadataStore = new SessionMetadataStore();
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
const sessionOrderPath = join(home, ".config", "opensessions", "session-order.json");
const sessionOrder = new SessionOrder(sessionOrderPath);
// Clear previous log on server start
try { writeFileSync(DEBUG_LOG, ""); } catch {}
log("server", "starting", { providers: allProviders.map((p) => p.name) });
// Load initial theme from config
const config = loadConfig();
let currentTheme: string | undefined = typeof config.theme === "string" ? config.theme : undefined;
let currentFilter: SessionFilterMode | undefined = config.sessionFilter;
let sidebarWidth = clampSidebarWidth(config.sidebarWidth ?? 26);
let sidebarPosition: "left" | "right" = config.sidebarPosition ?? "left";
const sidebarCoordinator = createSidebarCoordinator();
// The sidebar launcher lives with the TUI app, not the tmux integration layer.
const scriptsDir = (() => {
const envDir = process.env.OPENSESSIONS_DIR;
if (envDir) return join(envDir, "apps", "tui", "scripts");
// Fallback: relative to this file
return join(import.meta.dir, "..", "..", "..", "..", "apps", "tui", "scripts");
})();
log("server", "config loaded", {
sidebarWidth, sidebarPosition, scriptsDir,
theme: currentTheme, configKeys: Object.keys(config),
});
// Bootstrap active sessions
const currentSession = mux.getCurrentSession();
if (currentSession) {
tracker.setActiveSessions([currentSession]);
}
// --- Agent watcher context ---
let watcherBroadcastTimer: ReturnType<typeof setTimeout> | null = null;
function debouncedBroadcast() {
if (watcherBroadcastTimer) return;
watcherBroadcastTimer = setTimeout(() => {
watcherBroadcastTimer = null;
broadcastState();
}, 200);
}
// Cache for dir→session resolution (rebuilt per scan cycle)
let dirSessionCache: Map<string, string> | null = null;
let dirSessionCacheTs = 0;
const DIR_CACHE_TTL = 5000;
function getDirSessionMap(): Map<string, string> {
const now = Date.now();
if (dirSessionCache && now - dirSessionCacheTs < DIR_CACHE_TTL) return dirSessionCache;
const map = new Map<string, string>();
for (const p of allProviders) {
for (const s of p.listSessions()) {
if (s.dir) map.set(s.dir, s.name);
}
}
dirSessionCache = map;
dirSessionCacheTs = now;
return map;
}
const watcherCtx: AgentWatcherContext = {
resolveSession(projectDir: string): string | null {
const map = getDirSessionMap();
// Direct path match
const direct = map.get(projectDir);
if (direct) return direct;
// Substring match (parent/child directories)
for (const [dir, name] of map) {
if (projectDir.startsWith(dir + "/") || dir.startsWith(projectDir + "/")) return name;
}
// Encoded match: the watcher couldn't decode the path unambiguously,
// so try encoding each session dir and comparing against the encoded form.
// Claude Code encodes /, ., and _ as - in project directory names.
if (projectDir.startsWith("__encoded__:")) {
const encoded = projectDir.slice("__encoded__:".length);
for (const [dir, name] of map) {
if (dir.replace(/[/._]/g, "-") === encoded) return name;
}
}
return null;
},
emit(event: AgentEvent) {
log("agent-emit", event.agent, { session: event.session, status: event.status, threadId: event.threadId?.slice(0, 8) });
tracker.applyEvent(event, { seed: !watchersSeeded });
debouncedBroadcast();
},
};
// Flag to track when initial watcher seeding is complete
let watchersSeeded = false;
setTimeout(() => {
watchersSeeded = true;
// Re-apply focus for the current session to clear seed-unseen flags
// (handleFocus already ran before seed events arrived)
const current = getCurrentSession();
if (current && tracker.handleFocus(current)) {
broadcastState();
}
}, 3000);
let focusedSession: string | null = null;
let lastState: ServerState | null = null;
let clientCount = 0;
let initializingTimer: ReturnType<typeof setTimeout> | null = null;
let transientResizeTimer: ReturnType<typeof setTimeout> | null = null;
let resizeStaggerTimers: ReturnType<typeof setTimeout>[] = [];
let idleTimer: ReturnType<typeof setTimeout> | null = null;
const clientTtys = new WeakMap<object, string>();
const clientSessionNames = new WeakMap<object, string>();
const clientWindowIds = new WeakMap<object, string>();
const connectedClients = new Set<any>();
const sessionProviders = new Map<string, MuxProvider>();
// Map session name → client TTY (from hook context, for multi-client setups)
const clientTtyBySession = new Map<string, string>();
function getSidebarState() {
return readSidebarCoordinatorState(sidebarCoordinator.getSnapshot());
}
function isSidebarVisible(): boolean {
return getSidebarState().visible;
}
function suppressWidthReports(ms = 500): void {
sidebarCoordinator.send({ type: "SUPPRESS_WIDTH_REPORTS", until: Date.now() + ms });
}
function beginSidebarWarmup(): void {
sidebarCoordinator.send({ type: "BEGIN_WARMUP" });
}
function finishSidebarWarmup(): void {
sidebarCoordinator.send({ type: "WARMUP_DONE" });
}
function beginSidebarResize(): void {
sidebarCoordinator.send({ type: "BEGIN_RESIZE" });
}
function finishSidebarResize(): void {
sidebarCoordinator.send({ type: "RESIZE_DONE" });
}
function markSidebarReady(): void {
sidebarCoordinator.send({ type: "MARK_READY" });
}
function hideSidebarLifecycle(): void {
sidebarCoordinator.send({ type: "HIDE" });
}
function clearTransientResizeTimer(): void {
if (!transientResizeTimer) return;
clearTimeout(transientResizeTimer);
transientResizeTimer = null;
}
function startTransientSidebarResize(ms = 180): boolean {
const sidebarState = getSidebarState();
const extendingTransientResize = sidebarState.mode === "resizing" && transientResizeTimer !== null;
if (!canStartTransientResize(sidebarState, transientResizeTimer !== null)) return false;
clearTransientResizeTimer();
if (!extendingTransientResize) {
beginSidebarResize();
broadcastState();
}
transientResizeTimer = setTimeout(() => {
transientResizeTimer = null;
if (!isSidebarVisible() || resizeStaggerTimers.length > 0) return;
finishSidebarResize();
broadcastState();
}, ms);
return true;
}
function sendYourSession(ws: any, sessionName: string, clientTty?: string | null): void {
clientSessionNames.set(ws, sessionName);
ws.send(JSON.stringify({
type: "your-session",
name: sessionName,
clientTty: clientTty ?? clientTtyBySession.get(sessionName) ?? null,
}));
}
function syncClientSessionsForTty(clientTty: string | undefined, sessionName: string, windowId?: string): void {
if (!clientTty) return;
clientTtyBySession.set(sessionName, clientTty);
for (const ws of connectedClients) {
if (clientTtys.get(ws) !== clientTty) continue;
if (windowId && clientWindowIds.get(ws) !== windowId) continue;
sendYourSession(ws, sessionName, clientTty);
}
}
function getCurrentSession(): string | null {
// Try all providers until one returns a session
for (const p of allProviders) {
const result = p.getCurrentSession();
if (result) {
log("getCurrentSession", "result", { result, provider: p.name });
return result;
}
}
log("getCurrentSession", "no provider returned a session");
return null;
}
function computeState(): ServerState {
// Merge sessions from all providers
const allMuxSessions: (import("../contracts/mux").MuxSessionInfo & { provider: MuxProvider })[] = [];
for (const p of allProviders) {
for (const s of p.listSessions()) {
allMuxSessions.push({ ...s, provider: p });
}
}
allMuxSessions.sort((a, b) => {
if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
return a.name.localeCompare(b.name);
});
const currentSession = getCurrentSession();
// Sync custom ordering with current session list
sessionOrder.sync(allMuxSessions.map((s) => s.name));
if (currentSession) {
sessionOrder.show(currentSession);
}
// Apply custom ordering
const orderedNames = sessionOrder.apply(allMuxSessions.map((s) => s.name));
const sessionByName = new Map(allMuxSessions.map((s) => [s.name, s]));
const orderedMuxSessions = orderedNames.map((n) => sessionByName.get(n)!);
const portlessState = loadPortlessState();
// Batch pane counts per provider (uses BatchCapable type guard)
const paneCountMaps = new Map<MuxProvider, Map<string, number>>();
for (const p of allProviders) {
if (isBatchCapable(p)) {
paneCountMaps.set(p, p.getAllPaneCounts());
}
}
// Build paneId -> windowId map for agent-to-window association
const paneToWindow = new Map<string, string>();
try {
const raw = shell(["tmux", "list-panes", "-a", "-F", "#{pane_id}|#{window_id}"]);
for (const line of raw.split("\n")) {
if (!line) continue;
const sep = line.indexOf("|");
if (sep > 0) paneToWindow.set(line.slice(0, sep), line.slice(sep + 1));
}
} catch {}
const sessions: SessionData[] = orderedMuxSessions.map(({ name, createdAt, windows, windowList, dir, provider }) => {
sessionProviders.set(name, provider);
const git = getGitInfo(dir);
const providerPaneCounts = paneCountMaps.get(provider);
const panes = providerPaneCounts?.get(name) ?? provider.getPaneCount(name);
let uptime = "";
const diff = Math.floor(Date.now() / 1000) - createdAt;
if (!isNaN(diff) && diff >= 0) {
const days = Math.floor(diff / 86400);
const hours = Math.floor((diff % 86400) / 3600);
const mins = Math.floor((diff % 3600) / 60);
if (days > 0) uptime = `${days}d${hours}h`;
else if (hours > 0) uptime = `${hours}h${mins}m`;
else uptime = `${mins}m`;
}
return {
name,
createdAt,
dir,
branch: git.branch,
dirty: git.dirty,
isWorktree: git.isWorktree,
unseen: tracker.isUnseen(name),
panes,
ports: getSessionPorts(name),
localLinks: buildLocalLinks(getSessionPorts(name), portlessState),
windows,
windowList: (windowList ?? []).map((w) => {
const agents = tracker.getAgents(name);
const windowAgent = agents.find((a) => a.paneId && paneToWindow.get(a.paneId) === w.id);
return {
...w,
agentStatus: windowAgent?.status,
agentName: windowAgent?.agent,
};
}),
uptime,
agentState: tracker.getState(name),
agents: tracker.getAgents(name),
eventTimestamps: tracker.getEventTimestamps(name),
metadata: metadataStore.get(name),
};
});
metadataStore.pruneSessions(new Set(sessions.map((s) => s.name)));
if (sessions.length === 0) {
focusedSession = null;
} else if (!focusedSession || !sessions.some((s) => s.name === focusedSession)) {
focusedSession = sessions.find((s) => s.name === currentSession)?.name ?? sessions[0]!.name;
}
const sidebarState = getSidebarState();
return {
type: "state",
sessions,
focusedSession,
currentSession,
theme: currentTheme,
sessionFilter: currentFilter,
sidebarWidth,
initializing: sidebarState.initializing,
initLabel: sidebarState.initLabel,
ts: Date.now(),
};
}
let broadcastPending = false;
function broadcastState() {
if (broadcastPending) return;
broadcastPending = true;
queueMicrotask(() => {
broadcastPending = false;
broadcastStateImmediate();
});
}
function broadcastStateImmediate() {
invalidateCurrentSessionCache();
tracker.pruneStuck(STUCK_RUNNING_TIMEOUT_MS);
tracker.pruneTerminal();
lastState = computeState();
syncGitWatchers(lastState.sessions, broadcastState);
const msg = JSON.stringify(lastState);
server.publish("sidebar", msg);
}
// Lightweight current-session cache — avoids a tmux subprocess per focus update
let cachedCurrentSession: string | null = null;
let cachedCurrentSessionTs = 0;
const CURRENT_SESSION_CACHE_TTL = 500; // ms — short TTL, just enough to coalesce rapid switches
function getCachedCurrentSession(): string | null {
const now = Date.now();
if (now - cachedCurrentSessionTs < CURRENT_SESSION_CACHE_TTL) return cachedCurrentSession;
cachedCurrentSession = getCurrentSession();
cachedCurrentSessionTs = now;
return cachedCurrentSession;
}
function invalidateCurrentSessionCache(): void {
cachedCurrentSessionTs = 0;
}
function broadcastFocusOnly(sender?: any) {
if (!lastState) return;
const currentSession = getCachedCurrentSession();
lastState = { ...lastState, focusedSession, currentSession };
const msg: FocusUpdate = { type: "focus", focusedSession, currentSession };
const payload = JSON.stringify(msg);
if (sender) {
sender.publish("sidebar", payload);
} else {
server.publish("sidebar", payload);
}
}
function moveFocus(delta: -1 | 1, sender?: any) {
if (!lastState || lastState.sessions.length === 0) return;
const sessions = lastState.sessions;
const currentIdx = sessions.findIndex((s) => s.name === focusedSession);
const newIdx = Math.max(0, Math.min(sessions.length - 1, (currentIdx === -1 ? 0 : currentIdx) + delta));
focusedSession = sessions[newIdx]!.name;
broadcastFocusOnly(sender);
}
function setFocus(name: string, sender?: any) {
if (lastState && lastState.sessions.some((s) => s.name === name)) {
focusedSession = name;
broadcastFocusOnly(sender);
}
}
function handleFocus(name: string): void {
focusedSession = name;
invalidateCurrentSessionCache();
// Rescan pane agents when session focus changes
refreshPaneAgents();
const hadUnseen = tracker.handleFocus(name);
if (hadUnseen && lastState) {
// Patch unseen flags in-place — avoids a full computeState with many subprocesses
const currentSession = getCachedCurrentSession();
const updatedSessions = lastState.sessions.map((s) => {
if (s.name !== name) return s;
return {
...s,
unseen: false,
agents: s.agents.map((a) => ({ ...a, unseen: false })),
};
});
lastState = { ...lastState, sessions: updatedSessions, focusedSession, currentSession };
server.publish("sidebar", JSON.stringify(lastState));
} else if (hadUnseen) {
broadcastState();
} else {
broadcastFocusOnly();
}
}
function switchToVisibleIndex(index: number, clientTty?: string): void {
if (!lastState) {
broadcastState();
}
if (!lastState) return;
const idx = index - 1;
if (idx < 0 || idx >= lastState.sessions.length) return;
const name = lastState.sessions[idx]!.name;
const p = sessionProviders.get(name) ?? mux;
p.switchSession(name, clientTty);
if (isSidebarVisible() && isFullSidebarCapable(p) && p.name === "zellij") {
const activeWindows = p.listActiveWindows();
const targetWindow = activeWindows.find((w) => w.sessionName === name);
if (targetWindow) {
setTimeout(() => {
ensureSidebarInWindow(p, { session: name, windowId: targetWindow.id });
}, 500);
}
}
}
// --- Sidebar management ---
function getProvidersWithSidebar() {
return allProviders.filter(isFullSidebarCapable);
}
/** Parse "clientTty|session|windowId" or legacy "session:windowId" context from POST body */
function parseContext(body: string): { clientTty?: string; session: string; windowId: string } | null {
const trimmed = body.trim().replace(/^"+|"+$/g, "").replace(/^'+|'+$/g, "");
// New format: pipe-separated "clientTty|session|windowId"
const pipeParts = trimmed.split("|");
if (pipeParts.length === 3 && pipeParts[1] && pipeParts[2]) {
const ctx = { clientTty: pipeParts[0] || undefined, session: pipeParts[1], windowId: pipeParts[2] };
if (ctx.clientTty && ctx.session) {
clientTtyBySession.set(ctx.session, ctx.clientTty);
}
return ctx;
}
// Legacy format: "session:windowId"
const colonIdx = trimmed.indexOf(":");
if (colonIdx < 1) return null;
const session = trimmed.slice(0, colonIdx);
const windowId = trimmed.slice(colonIdx + 1);
if (!session || !windowId) return null;
return { session, windowId };
}
// Short-lived cache for sidebar pane listings — avoid repeated tmux list-panes -a
let sidebarPaneCache: ReturnType<typeof listSidebarPanesByProviderUncached> | null = null;
let sidebarPaneCacheTs = 0;
const SIDEBAR_PANE_CACHE_TTL = 300; // ms
function listSidebarPanesByProviderUncached() {
return getProvidersWithSidebar().map((provider) => ({
provider,
panes: provider.listSidebarPanes(),
}));
}
function listSidebarPanesByProvider() {
const now = Date.now();
if (sidebarPaneCache && now - sidebarPaneCacheTs < SIDEBAR_PANE_CACHE_TTL) return sidebarPaneCache;
sidebarPaneCache = listSidebarPanesByProviderUncached();
sidebarPaneCacheTs = now;
return sidebarPaneCache;
}
function invalidateSidebarPaneCache(): void {
sidebarPaneCache = null;
sidebarPaneCacheTs = 0;
}
function reconcileSidebarPresence() {
invalidateSidebarPaneCache();
const panesByProvider = listSidebarPanesByProvider();
return {
panesByProvider,
visible: panesByProvider.some(({ panes }) => panes.length > 0),
};
}
const pendingSidebarSpawns = new Set<string>();
function toggleSidebar(ctx?: { session: string; windowId: string }): void {
const providers = getProvidersWithSidebar();
if (providers.length === 0) {
log("toggle", "SKIP — no providers with sidebar methods");
return;
}
const { panesByProvider, visible: sidebarPresent } = reconcileSidebarPresence();
const hasPaneInContextWindow = ctx
? panesByProvider.some(({ panes }) => panes.some((pane) => pane.windowId === ctx.windowId))
: false;
// If the server rebooted into a degraded state where only some sidebar
// panes survived, treat toggle from a pane-less window as a recovery
// request and restore missing panes instead of hiding the lone survivor.
const recoverVisibleState = sidebarPresent && ctx && !hasPaneInContextWindow;
if (sidebarPresent && !recoverVisibleState) {
for (const p of providers) {
const panes = p.listSidebarPanes();
log("toggle", "OFF — hiding panes", { provider: p.name, count: panes.length });
for (const pane of panes) {
p.hideSidebar(pane.paneId);
}
}
clearTransientResizeTimer();
hideSidebarLifecycle();
if (initializingTimer) { clearTimeout(initializingTimer); initializingTimer = null; }
for (const t of resizeStaggerTimers) clearTimeout(t);
resizeStaggerTimers = [];
} else {
if (initializingTimer) clearTimeout(initializingTimer);
suppressWidthReports();
markSidebarReady();
invalidateSidebarPaneCache();
// Prioritized spawn order:
// 1. Current active window (instant)
// 2. Other windows in the current session
// 3. Windows in other sessions (staggered)
const curSession = ctx?.session ?? getCurrentSession();
// Track max delay to know when all spawns are done
let maxDelay = 0;
for (const p of providers) {
const allWindows = p.listActiveWindows();
log("toggle", recoverVisibleState ? "RECOVER — ensuring all windows" : "ON — spawning in all windows", {
provider: p.name,
total: allWindows.length,
currentSession: curSession,
});
// Tier 1: current active window (instant)
const curWindowId = ctx?.windowId ?? p.getCurrentWindowId();
if (curSession && curWindowId) {
const activeWindow = allWindows.find((w) => w.sessionName === curSession && w.id === curWindowId);
if (activeWindow) {
log("toggle", "tier1: active window", { session: curSession, windowId: curWindowId });
ensureSidebarInWindow(p, { session: activeWindow.sessionName, windowId: activeWindow.id });
}
}
// Tier 2: other windows in current session (slight delay)
const tier2 = allWindows.filter((w) => w.sessionName === curSession && w.id !== curWindowId);
// Tier 3: windows in other sessions
const tier3 = allWindows.filter((w) => w.sessionName !== curSession);
log("toggle", "spawn plan", { tier2: tier2.length, tier3: tier3.length });
// Stagger background spawns — each ensureSidebarInWindow blocks ~100ms
// with sync tmux calls, so space them out to keep the event loop responsive.
let delay = SPAWN_STAGGER_MS;
for (const w of tier2) {
const win = w;
const prov = p;
setTimeout(() => {
if (isSidebarVisible()) ensureSidebarInWindow(prov, { session: win.sessionName, windowId: win.id });
}, delay);
delay += SPAWN_STAGGER_MS;
}
for (const w of tier3) {
const win = w;
const prov = p;
setTimeout(() => {
if (isSidebarVisible()) ensureSidebarInWindow(prov, { session: win.sessionName, windowId: win.id });
}, delay);
delay += SPAWN_STAGGER_MS;
}
if (delay > maxDelay) maxDelay = delay;
}
// Set initializing state during stagger
if (maxDelay > 0) {
beginSidebarWarmup();
initializingTimer = setTimeout(() => {
initializingTimer = null;
finishSidebarWarmup();
log("toggle", "initializing complete");
broadcastState();
}, maxDelay + 500); // extra 500ms buffer for last spawn to finish
} else {
markSidebarReady();
}
scheduleSidebarWidthEnforcement();
server.publish("sidebar", JSON.stringify({ type: "re-identify" }));
}
log("toggle", "done", { sidebarVisible: isSidebarVisible() });
}
function ensureSidebarInWindow(provider?: ReturnType<typeof getProvidersWithSidebar>[number], ctx?: { session: string; windowId: string }): void {
// If no specific provider, try to find one for the session
const p = provider ?? (() => {
const providers = getProvidersWithSidebar();
if (ctx?.session) {
const sessionProvider = sessionProviders.get(ctx.session);
return providers.find((pp) => pp === sessionProvider) ?? providers[0];
}
return providers[0];
})();
if (!p || !isSidebarVisible()) {
log("ensure", "SKIP", { hasProvider: !!p, sidebarVisible: isSidebarVisible() });
return;
}
const curSession = ctx?.session ?? getCurrentSession();
if (!curSession) {
log("ensure", "SKIP — no current session");
return;
}
const windowId = ctx?.windowId ?? p.getCurrentWindowId();
if (!windowId) {
log("ensure", "SKIP — could not get window_id");
return;
}
const spawnKey = `${p.name}:${windowId}`;
if (pendingSidebarSpawns.has(spawnKey)) {
log("ensure", "SKIP — spawn already in progress", { curSession, windowId, provider: p.name });
return;
}
// Use cached pane listing to avoid redundant tmux list-panes -a calls
// Invalidate before check — staggered spawns change pane state between calls
invalidateSidebarPaneCache();
const allPanesByProvider = listSidebarPanesByProvider();
const providerEntry = allPanesByProvider.find((e) => e.provider === p);
const existingPanes = providerEntry?.panes ?? [];
const hasInWindow = existingPanes.some((ep) => ep.windowId === windowId);
log("ensure", "checking window", {
curSession, windowId, existingPanes: existingPanes.length,
hasInWindow, paneIds: existingPanes.map((x) => `${x.paneId}@${x.windowId}`),
});
if (!hasInWindow) {
invalidateSidebarPaneCache();
pendingSidebarSpawns.add(spawnKey);
log("ensure", "SPAWNING sidebar", { curSession, windowId, sidebarWidth, sidebarPosition, scriptsDir });
try {
const newPaneId = p.spawnSidebar(curSession, windowId, sidebarWidth, sidebarPosition, scriptsDir);
log("ensure", "spawn result", { newPaneId });
// Do NOT refocus the main pane here — the TUI handles it.
// For fresh spawns, the TUI refocuses after capability detection.
// For stash restores, the TUI refocuses after restoreTerminalModes
// responses settle. Refocusing immediately from the server causes
// capability query responses to leak as garbage escape sequences.
} finally {
pendingSidebarSpawns.delete(spawnKey);
}
}
// Always enforce width — session switches can change window width,
// causing tmux to proportionally redistribute pane sizes.
// Call directly (not scheduled) since we're already behind debouncedEnsureSidebar.
suppressWidthReports();
enforceSidebarWidth();
}
// Debounced ensure-sidebar — collapses rapid hook-fired calls during fast
// session switching into a single check after switching settles.
let ensureSidebarTimer: ReturnType<typeof setTimeout> | null = null;
let ensureSidebarPendingCtx: { session: string; windowId: string } | undefined;
function debouncedEnsureSidebar(ctx?: { session: string; windowId: string }): void {
if (ctx) ensureSidebarPendingCtx = ctx;
if (ensureSidebarTimer) clearTimeout(ensureSidebarTimer);
ensureSidebarTimer = setTimeout(() => {
ensureSidebarTimer = null;
const nextCtx = ensureSidebarPendingCtx;
ensureSidebarPendingCtx = undefined;
ensureSidebarInWindow(undefined, nextCtx);
}, 150);
}
// Debounced width enforcement — collapses resize storms (monitor switch,
// terminal resize) into a single tmux resize pass.
let sidebarEnforceTimer: ReturnType<typeof setTimeout> | null = null;
function scheduleSidebarWidthEnforcement(): void {
if (!isSidebarVisible()) return;
log("scheduleEnforce", "scheduling debounced enforcement", { sidebarWidth });
suppressWidthReports();
if (sidebarEnforceTimer) clearTimeout(sidebarEnforceTimer);
sidebarEnforceTimer = setTimeout(() => {
sidebarEnforceTimer = null;
log("scheduleEnforce", "FIRING debounced enforcement", { sidebarVisible: isSidebarVisible(), sidebarWidth });
if (isSidebarVisible()) {
enforceSidebarWidth();