-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·1417 lines (1257 loc) · 51.3 KB
/
index.js
File metadata and controls
executable file
·1417 lines (1257 loc) · 51.3 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
#!/usr/bin/env node
/**
* OpenCode Starter (opencode-starter)
* ───────────────────────────────────
* A beautiful TUI for starting new and resuming past OpenCode sessions.
*
* Usage:
* opencode-starter # Launch interactive TUI
* opencode-starter --list # Print sessions as a table (no TUI)
* opencode-starter --list N # Print the latest N sessions
* opencode-starter --version # Show version
* opencode-starter --update # Update to the latest version
* opencode-starter --help # Show help
*
* Keyboard shortcuts (TUI mode):
* ↑/↓ or j/k Navigate sessions
* Enter Start new / resume selected session
* / Start search (live filter)
* Esc Clear search
* p Filter by project (popup)
* s Cycle sort: time → messages → project
* n Start new session
* r Rename a session (custom title)
* x / Delete Delete the selected session
* c Copy session ID to clipboard
* g / G Jump to top / bottom
* Ctrl-D / U Page down / up
* q / Ctrl-C Quit
*/
const blessed = require('blessed');
const fs = require('fs');
const path = require('path');
const { spawn, execSync } = require('child_process');
const os = require('os');
// ─── OpenCode CLI Detection ─────────────────────────────────────────────────
function detectCLI() {
// Just check if `opencode` is on PATH; we always invoke it as `opencode`.
try {
execSync('command -v opencode', { stdio: ['pipe', 'pipe', 'pipe'] });
return { name: 'opencode', cmd: 'opencode' };
} catch {
return { name: 'opencode', cmd: 'opencode' }; // fall through; spawn will error if missing
}
}
const CLI = detectCLI();
// ─── Color Palette (opencode-style) ─────────────────────────────────────────
// Mostly neutral, with restrained color accents — yellow for headings,
// green for user/success, blue for info, cyan for numbers, purple for keys,
// orange for warnings, red for danger. Inspired by the opencode CLI itself.
const C = {
fg: '#e5e7eb', // primary text
dim: '#9ca3af', // secondary text
faint: '#6b7280', // tertiary
rule: '#3a3a3a', // separators
white: '#ffffff', // strong emphasis
yellow: '#eab308', // section headings, highlights
green: '#22c55e', // success, user/human messages
blue: '#60a5fa', // info, paths, links
cyan: '#67e8f9', // numbers, counts
purple: '#c084fc', // hotkeys, accents
orange: '#fb923c', // warnings, allow-mode badge
red: '#ef4444', // danger, deletion
};
// Project name palette — tasteful colors so different projects are
// distinguishable at a glance, but not overwhelming.
const PROJECT_COLORS = [
'#60a5fa', '#22c55e', '#eab308', '#c084fc',
'#67e8f9', '#fb923c', '#f472b6', '#a3e635',
];
// ─── Paths ───────────────────────────────────────────────────────────────────
// OpenCode stores its data under XDG-style paths. On macOS / Linux the
// default lives under `~/.local/share/opencode/`. Allow overrides via env.
const OPENCODE_DATA_DIR =
process.env.OPENCODE_DATA_DIR ||
process.env.OPENCODE_HOME ||
path.join(os.homedir(), '.local', 'share', 'opencode');
const DB_PATH = path.join(OPENCODE_DATA_DIR, 'opencode.db');
const META_DIR = path.join(os.homedir(), '.opencode-starter');
const META_FILE = path.join(META_DIR, 'meta.json');
// OpenCode reads its global config from ~/.config/opencode/opencode.json.
// We modify just the `permission` block so users can switch between
// "ask every time" and "auto-approve everything" without leaving the TUI.
const OPENCODE_CONFIG_DIR = path.join(os.homedir(), '.config', 'opencode');
const OPENCODE_CONFIG_FILE = path.join(OPENCODE_CONFIG_DIR, 'opencode.json');
// ─── OpenCode Config (permission mode) ───────────────────────────────
// "ask" = original behaviour, every tool call prompts you
// "allow" = full bypass, never prompt
// "deny" = always refuse
// We treat "ask" as the unset/default state.
const PERMISSION_KEYS = ['edit', 'bash', 'webfetch'];
const PERMISSION_MODES = ['ask', 'allow', 'deny'];
function loadOpencodeConfig() {
try {
if (fs.existsSync(OPENCODE_CONFIG_FILE)) {
return JSON.parse(fs.readFileSync(OPENCODE_CONFIG_FILE, 'utf-8'));
}
} catch (e) { /* corrupt file → start fresh, never overwrite blindly though */ }
return null;
}
function saveOpencodeConfig(cfg) {
try {
if (!fs.existsSync(OPENCODE_CONFIG_DIR)) {
fs.mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });
}
fs.writeFileSync(OPENCODE_CONFIG_FILE, JSON.stringify(cfg, null, 2) + '\n', 'utf-8');
return true;
} catch (e) {
return false;
}
}
// Returns one of "ask" | "allow" | "deny" | "mixed".
// "mixed" means edit/bash/webfetch don't all agree (custom config), so we
// surface that instead of pretending one mode is active.
function getCurrentPermissionMode() {
const cfg = loadOpencodeConfig();
if (!cfg || !cfg.permission) return 'ask';
const vals = PERMISSION_KEYS.map(k => {
const v = cfg.permission[k];
if (typeof v === 'string') return v;
if (v == null) return 'ask';
return 'mixed'; // object form (per-command rules) — treat as advanced/mixed
});
const first = vals[0];
return vals.every(v => v === first) ? first : 'mixed';
}
// Set every key in PERMISSION_KEYS to the same string value, preserving any
// other top-level config the user may have. Returns true on success.
function setPermissionMode(mode) {
if (!PERMISSION_MODES.includes(mode)) {
throw new Error(`Invalid permission mode: ${mode}`);
}
const cfg = loadOpencodeConfig() || {
$schema: 'https://opencode.ai/config.json',
};
if (!cfg.permission || typeof cfg.permission !== 'object') cfg.permission = {};
for (const k of PERMISSION_KEYS) cfg.permission[k] = mode;
return saveOpencodeConfig(cfg);
}
// ─── Session Meta ────────────────────────────────────────────────────
// Stores user-defined customTitles for sessions in a simple JSON file.
// (OpenCode itself stores titles in SQLite; this is layered on top so a
// rename here is reversible and never corrupts the DB.)
function loadMeta() {
try {
if (fs.existsSync(META_FILE)) {
return JSON.parse(fs.readFileSync(META_FILE, 'utf-8'));
}
} catch (e) { /* corrupt file, start fresh */ }
return { sessions: {} };
}
function saveMeta(meta) {
try {
if (!fs.existsSync(META_DIR)) fs.mkdirSync(META_DIR, { recursive: true });
fs.writeFileSync(META_FILE, JSON.stringify(meta, null, 2), 'utf-8');
} catch (e) { /* silently fail */ }
}
function getSessionMeta(meta, sessionId) {
return meta.sessions[sessionId] || {};
}
function setSessionCustomTitle(meta, sessionId, title) {
if (!meta.sessions[sessionId]) meta.sessions[sessionId] = {};
if (title) {
meta.sessions[sessionId].customTitle = title;
} else {
delete meta.sessions[sessionId].customTitle;
}
saveMeta(meta);
}
// ─── Data Layer ──────────────────────────────────────────────────────────────
function getProjectDisplayName(worktree) {
// OpenCode's project.worktree is an absolute path (or "/" for the global
// project). Strip user-home prefix and grab the last meaningful segment.
if (!worktree || worktree === '/') return 'global';
let p = worktree;
// Remove home prefix
const home = os.homedir();
if (p.startsWith(home)) p = p.slice(home.length);
// Strip leading slashes/dashes
p = p.replace(/^[\/\\-]+/, '');
if (!p) return '~';
// Take the last path segment
const parts = p.split(/[\/\\]/).filter(Boolean);
if (parts.length === 0) return '~';
// Skip well-known parent dirs (Desktop, Projects, etc) so we surface the
// actual project folder name (mirrors claude-starter behaviour).
const skipPrefixes = /^(Desktop|Documents|Projects|Downloads|dev|src|code|repos|work|home)$/i;
while (parts.length > 1 && skipPrefixes.test(parts[0])) parts.shift();
return parts[parts.length - 1] || worktree;
}
// ─── SQLite access ──────────────────────────────────────────────────────────
// Resolved lazily so unit tests can run without the native module being
// importable (e.g. CI without a build toolchain).
let _Database = null;
function getDatabaseClass() {
if (_Database) return _Database;
try {
_Database = require('better-sqlite3');
} catch (e) {
throw new Error(
'better-sqlite3 is required to read OpenCode sessions.\n'
+ 'Install with: npm install -g opencode-starter\n'
+ 'Underlying error: ' + e.message,
);
}
return _Database;
}
function openDatabase(dbPath) {
if (!fs.existsSync(dbPath)) {
throw new Error(`OpenCode database not found at ${dbPath}\n`
+ `Set OPENCODE_DATA_DIR if it lives elsewhere.`);
}
const Database = getDatabaseClass();
// readonly to be safe; fileMustExist checked above
return new Database(dbPath, { readonly: true, fileMustExist: true });
}
// Extract a short text snippet from an opencode `part.data` JSON blob.
// Parts have type like "text", "step-start", "tool", "reasoning", etc.
function extractPartText(partRow) {
try {
const d = JSON.parse(partRow.data);
if (d.type === 'text' && typeof d.text === 'string') return d.text;
} catch { /* skip */ }
return '';
}
function summarizeProject(worktree) {
return {
name: getProjectDisplayName(worktree),
worktree,
};
}
// Build the per-session aggregate data we display.
function loadAllSessions(dbPath) {
const db = openDatabase(dbPath || DB_PATH);
try {
// Pull all sessions with project info joined in
const sessions = db.prepare(`
SELECT
s.id AS session_id,
s.project_id AS project_id,
s.title AS title,
s.directory AS directory,
s.version AS version,
s.time_created AS time_created,
s.time_updated AS time_updated,
s.time_archived AS time_archived,
s.parent_id AS parent_id,
p.worktree AS worktree
FROM session s
LEFT JOIN project p ON p.id = s.project_id
WHERE s.time_archived IS NULL
ORDER BY s.time_updated DESC
`).all();
// Per-session message counts
const msgCountStmt = db.prepare(
'SELECT COUNT(*) AS c FROM message WHERE session_id = ?',
);
// First text part (first user message) — a small heuristic for "topic".
// Order by message.time_created then part.time_created, find first
// text part where parent message is role=user.
const firstTextStmt = db.prepare(`
SELECT p.data AS data
FROM part p
INNER JOIN message m ON m.id = p.message_id
WHERE p.session_id = ?
AND json_extract(p.data, '$.type') = 'text'
AND json_extract(m.data, '$.role') = 'user'
ORDER BY m.time_created ASC, p.time_created ASC
LIMIT 1
`);
const result = [];
for (const r of sessions) {
const messages = msgCountStmt.get(r.session_id).c;
// Skip sessions with zero messages — these are aborted before any input.
if (!messages) continue;
let topic = '';
try {
const row = firstTextStmt.get(r.session_id);
if (row) topic = extractPartText({ data: row.data });
} catch { /* skip */ }
topic = (topic || '').replace(/\s+/g, ' ').trim();
if (topic.length > 200) topic = topic.substring(0, 200) + '…';
const projectName = getProjectDisplayName(r.worktree || r.directory);
result.push({
sessionId: r.session_id,
title: r.title || '',
topic: topic || r.title || '(no messages)',
project: projectName,
worktree: r.worktree || '',
directory: r.directory || '',
version: r.version || '',
firstTs: r.time_created,
lastTs: r.time_updated,
estimatedMessages: messages,
totalMessages: messages,
parentId: r.parent_id || null,
// filled by loadSessionDetail
userMessages: null,
assistantSnippets: null,
toolsUsed: null,
_detailLoaded: false,
});
}
return result;
} finally {
try { db.close(); } catch { /* ignore */ }
}
}
function loadSessionDetail(session, dbPath) {
if (session._detailLoaded) return session;
const db = openDatabase(dbPath || DB_PATH);
try {
const messages = db.prepare(`
SELECT id, data, time_created
FROM message
WHERE session_id = ?
ORDER BY time_created ASC, id ASC
`).all(session.sessionId);
const partsBySession = db.prepare(`
SELECT message_id, data, time_created
FROM part
WHERE session_id = ?
ORDER BY time_created ASC, id ASC
`).all(session.sessionId);
// group parts by message_id
const partsByMsg = new Map();
for (const p of partsBySession) {
if (!partsByMsg.has(p.message_id)) partsByMsg.set(p.message_id, []);
partsByMsg.get(p.message_id).push(p);
}
const userMessages = [];
const assistantSnippets = [];
const toolsUsed = new Set();
for (const m of messages) {
let role = '';
try { role = JSON.parse(m.data).role || ''; } catch { /* skip */ }
const parts = partsByMsg.get(m.id) || [];
let text = '';
for (const p of parts) {
try {
const d = JSON.parse(p.data);
if (d.type === 'text' && typeof d.text === 'string') {
text += (text ? ' ' : '') + d.text;
} else if (d.type === 'tool' && d.tool) {
toolsUsed.add(d.tool);
}
} catch { /* skip */ }
}
text = text.replace(/\s+/g, ' ').trim();
if (!text) continue;
if (role === 'user') {
userMessages.push(text.substring(0, 300));
} else if (role === 'assistant') {
assistantSnippets.push(text.substring(0, 400));
}
}
session.userMessages = userMessages;
session.assistantSnippets = assistantSnippets;
session.totalMessages = messages.length;
session.estimatedMessages = messages.length;
session.toolsUsed = Array.from(toolsUsed);
session._detailLoaded = true;
if (userMessages.length > 0 && (!session.topic || session.topic === '(no messages)')) {
let topic = userMessages[0].replace(/\n/g, ' ').trim();
if (topic.length > 120) topic = topic.substring(0, 120) + '…';
session.topic = topic;
}
} finally {
try { db.close(); } catch { /* ignore */ }
}
return session;
}
function deleteSessionFromDb(sessionId, dbPath) {
// Open writable for this operation only
const Database = getDatabaseClass();
const target = dbPath || DB_PATH;
if (!fs.existsSync(target)) return false;
const db = new Database(target);
try {
// FK cascades from session -> message -> part should clean dependent rows.
const info = db.prepare('DELETE FROM session WHERE id = ?').run(sessionId);
return info.changes > 0;
} finally {
try { db.close(); } catch { /* ignore */ }
}
}
// ─── Formatting Helpers ──────────────────────────────────────────────────────
function formatTimestamp(ts) {
if (!ts) return 'unknown';
const d = new Date(typeof ts === 'number' ? ts : ts);
if (isNaN(d.getTime())) return 'unknown';
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const targetStart = new Date(d.getFullYear(), d.getMonth(), d.getDate());
const diffDays = Math.round((todayStart.getTime() - targetStart.getTime()) / 86400000);
const time = d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });
if (diffDays === 0) return `Today ${time}`;
if (diffDays === 1) return `Yesterday ${time}`;
if (diffDays < 7 && diffDays > 0) return `${diffDays}d ago ${time}`;
if (diffDays < 365 && diffDays > 0) return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
return d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}
function formatCount(n) {
if (n < 1000) return String(n);
if (n < 1000000) return `${(n / 1000).toFixed(1)}k`;
return `${(n / 1000000).toFixed(1)}M`;
}
function getProjectColor(projectName, colorMap) {
if (!colorMap.has(projectName)) {
colorMap.set(projectName, PROJECT_COLORS[colorMap.size % PROJECT_COLORS.length]);
}
return colorMap.get(projectName);
}
function esc(text) {
return String(text).replace(/\{/g, '\\{');
}
// ─── CLI Mode (--list) ───────────────────────────────────────────────────────
function runListMode(limit) {
const sessions = loadAllSessions();
const display = sessions.slice(0, limit || 30);
const A = {
reset: '\x1b[0m',
dim: '\x1b[2m',
bold: '\x1b[1m',
white: '\x1b[97m',
gray: '\x1b[37m',
yellow: '\x1b[33m',
cyan: '\x1b[36m',
blue: '\x1b[94m',
purple: '\x1b[95m',
green: '\x1b[32m',
};
console.log(`\n${A.bold}${A.yellow}OpenCode Sessions${A.reset} ${A.dim}${sessions.length} total · showing ${display.length}${A.reset}\n`);
console.log(`${A.dim}${'─'.repeat(100)}${A.reset}`);
console.log(`${A.bold}${A.gray}${'#'.padStart(3)} ${'Time'.padEnd(18)} ${'Project'.padEnd(20)} ${'Msgs'.padStart(5)} Topic${A.reset}`);
console.log(`${A.dim}${'─'.repeat(100)}${A.reset}`);
display.forEach((s, i) => {
console.log(
`${A.dim}${`${i + 1}`.padStart(3)}${A.reset} `
+ `${A.gray}${formatTimestamp(s.lastTs).padEnd(18)}${A.reset} `
+ `${A.blue}${s.project.substring(0, 19).padEnd(20)}${A.reset} `
+ `${A.cyan}${formatCount(s.estimatedMessages).padStart(5)}${A.reset} `
+ `${A.white}${(s.title || s.topic).substring(0, 50)}${A.reset}`,
);
});
console.log(`${A.dim}${'─'.repeat(100)}${A.reset}`);
console.log(`\n${A.dim}Resume:${A.reset} ${A.purple}${CLI.name} -s <session-id> -c${A.reset}\n`);
}
// ─── TUI Application ────────────────────────────────────────────────────────
function createApp() {
const allSessions = loadAllSessions();
const meta = loadMeta();
// Apply meta customTitles — these override the DB title.
for (const session of allSessions) {
const sm = meta.sessions[session.sessionId];
if (sm && sm.customTitle) session.customTitle = sm.customTitle;
}
let filteredSessions = [...allSessions];
let selectedIndex = -1; // -1 = "New Session", 0+ = session index
let filterText = '';
let isSearchMode = false;
let sortMode = 'time';
const projectColorMap = new Map();
const uniqueProjects = [...new Set(allSessions.map(s => s.project))];
uniqueProjects.forEach(p => getProjectColor(p, projectColorMap));
const screen = blessed.screen({
smartCSR: false,
fastCSR: false,
title: 'OpenCode Starter',
fullUnicode: true,
autoPadding: true,
dockBorders: true,
});
// Don't force a bg — follow the terminal, like opencode itself does.
const header = blessed.box({
parent: screen, top: 0, left: 0, width: '100%', height: 3,
tags: true, style: { fg: 'white' },
});
function updateHeader() {
const title = '{bold}{#eab308-fg}OpenCode Starter{/}';
const count = `{#67e8f9-fg}${filteredSessions.length}{/}{#6b7280-fg}/${allSessions.length} sessions{/}`;
const proj = `{#60a5fa-fg}${uniqueProjects.length}{/}{#6b7280-fg} projects{/}`;
const sort = `{#c084fc-fg}[${sortMode}]{/}`;
// Live permission mode badge
const mode = getCurrentPermissionMode();
const modeColor = mode === 'allow' ? '#fb923c' // orange — heads-up, no prompts
: mode === 'deny' ? '#ef4444' // red — blocking
: mode === 'mixed' ? '#eab308' // yellow — partial
: '#22c55e'; // green — safe default (ask)
const modePrefix = mode === 'allow' ? '! ' : mode === 'deny' ? '✕ ' : '';
const modeBadge = `{${modeColor}-fg}${modePrefix}${mode}{/}`;
const search = isSearchMode
? `{#eab308-fg}/ ${filterText}▌{/}`
: (filterText ? `{#9ca3af-fg}/ ${filterText}{/}` : '');
let parts = [title, count, proj, sort, modeBadge];
if (search) parts.push(search);
header.setContent(`\n ${parts.join(' {#3a3a3a-fg}│{/} ')}`);
}
blessed.line({ parent: screen, top: 3, left: 0, width: '100%', orientation: 'horizontal', style: { fg: '#3a3a3a' } });
const listPanel = blessed.list({
parent: screen,
top: 4, left: 0, width: '50%', height: '100%-7',
tags: true,
scrollable: true,
alwaysScroll: true,
scrollbar: { ch: '▐', style: { fg: '#6b7280' } },
style: {
fg: '#e5e7eb',
selected: { bg: '#eab308', fg: 'black', bold: true },
},
keys: false,
vi: false,
mouse: true,
interactive: true,
});
blessed.line({ parent: screen, top: 4, left: '50%', height: '100%-7', orientation: 'vertical', style: { fg: '#3a3a3a' } });
const detailPanel = blessed.box({
parent: screen,
top: 4, left: '50%+1', width: '50%-1', height: '100%-7',
tags: true, scrollable: true, alwaysScroll: true,
scrollbar: { ch: '▐', style: { fg: '#6b7280' } },
style: { },
mouse: true,
});
blessed.line({ parent: screen, bottom: 2, left: 0, width: '100%', orientation: 'horizontal', style: { fg: '#3a3a3a' } });
const footer = blessed.box({
parent: screen, bottom: 0, left: 0, width: '100%', height: 2,
tags: true, style: { fg: '#e5e7eb' },
});
function updateFooter() {
if (isSearchMode) {
const keys = [
'{#c084fc-fg}{bold}↵{/} {#9ca3af-fg}Confirm{/}',
'{#c084fc-fg}{bold}↑↓{/} {#9ca3af-fg}Navigate{/}',
'{#c084fc-fg}{bold}⌫{/} {#9ca3af-fg}Delete char{/}',
'{#c084fc-fg}{bold}Esc{/} {#9ca3af-fg}Clear{/}',
];
footer.setContent(`\n ${keys.join(' {#3a3a3a-fg}│{/} ')}`);
return;
}
const keys = [
'{#c084fc-fg}{bold}n{/} {#9ca3af-fg}New{/}',
'{#c084fc-fg}{bold}↵{/} {#9ca3af-fg}Resume{/}',
'{#c084fc-fg}{bold}m{/} {#9ca3af-fg}Mode{/}',
'{#c084fc-fg}{bold}/{/} {#9ca3af-fg}Search{/}',
'{#c084fc-fg}{bold}p{/} {#9ca3af-fg}Project{/}',
'{#c084fc-fg}{bold}s{/} {#9ca3af-fg}Sort{/}',
'{#c084fc-fg}{bold}c{/} {#9ca3af-fg}Copy ID{/}',
'{#c084fc-fg}{bold}r{/} {#9ca3af-fg}Rename{/}',
'{#ef4444-fg}{bold}x{/} {#9ca3af-fg}Delete{/}',
'{#c084fc-fg}{bold}q{/} {#9ca3af-fg}Quit{/}',
];
footer.setContent(`\n ${keys.join(' {#3a3a3a-fg}│{/} ')}`);
}
const NEW_SESSION_LABEL = ' {#22c55e-fg}{bold}+ New Conversation{/}';
function refreshList() {
const listW = Math.floor((screen.width || 100) / 2) - 2;
const sessionItems = filteredSessions.map((session) => {
const color = getProjectColor(session.project, projectColorMap);
const proj = `{${color}-fg}${session.project.substring(0, 12).padEnd(12)}{/}`;
const time = `{#9ca3af-fg}${formatTimestamp(session.lastTs).padEnd(16)}{/}`;
const fixedLen = 1 + 12 + 1 + 16 + 1;
const topicMaxLen = Math.max(10, listW - fixedLen);
let topic = session.customTitle || session.title || session.topic || '';
if (topic.length > topicMaxLen) topic = topic.substring(0, topicMaxLen) + '…';
let label = ` ${proj} ${time} `;
if (session.customTitle) {
label += `{#d1d5db-fg}{bold}${esc(topic)}{/}`;
} else {
label += `{#e5e7eb-fg}${esc(topic)}{/}`;
}
return label;
});
const items = [NEW_SESSION_LABEL, ...sessionItems];
listPanel.setItems(items);
listPanel.select(selectedIndex + 1); // +1: index 0 is "New Session"
screen.render();
}
function renderDetail() {
if (selectedIndex === -1) {
let c = '';
c += `\n {#22c55e-fg}{bold}Start a New Conversation{/}\n`;
c += ` {#3a3a3a-fg}${'─'.repeat(44)}{/}\n\n`;
c += ` {#e5e7eb-fg}Open a fresh OpenCode session and start{/}\n`;
c += ` {#e5e7eb-fg}coding from scratch.{/}\n\n`;
c += ` {#6b7280-fg}Working Dir{/} {#60a5fa-fg}${process.cwd()}{/}\n`;
c += ` {#6b7280-fg}CLI{/} {#eab308-fg}${CLI.name}{/}\n`;
c += ` {#6b7280-fg}Command{/} {#9ca3af-fg}${CLI.name}{/}\n\n`;
c += ` {#3a3a3a-fg}${'─'.repeat(44)}{/}\n`;
c += ` {#c084fc-fg}{bold}↵ Enter{/}{#9ca3af-fg} or {/}{#c084fc-fg}{bold}n{/}{#9ca3af-fg} to launch{/}\n`;
detailPanel.setContent(c);
detailPanel.setScroll(0);
return;
}
if (filteredSessions.length === 0 || !filteredSessions[selectedIndex]) {
detailPanel.setContent('\n {#6b7280-fg}No session selected{/}');
return;
}
const session = filteredSessions[selectedIndex];
try { loadSessionDetail(session); } catch (e) { /* show what we have */ }
const sm = meta.sessions[session.sessionId];
if (sm && sm.customTitle) session.customTitle = sm.customTitle;
const color = getProjectColor(session.project, projectColorMap);
let c = '';
const sep = ` {#3a3a3a-fg}${'─'.repeat(44)}{/}`;
c += `\n {${color}-fg}{bold}█ ${session.project}{/}\n`;
if (session.customTitle) {
c += ` {#d1d5db-fg}{bold}${esc(session.customTitle)}{/}\n`;
} else if (session.title) {
c += ` {#e5e7eb-fg}${esc(session.title)}{/}\n`;
}
c += sep + '\n\n';
const fields = [
['Session', `{#60a5fa-fg}${session.sessionId}{/}`],
['Started', `{#9ca3af-fg}${session.firstTs ? new Date(session.firstTs).toLocaleString() : '?'}{/}`],
['Last active', `{#9ca3af-fg}${session.lastTs ? new Date(session.lastTs).toLocaleString() : '?'}{/}`],
['Messages', `{#67e8f9-fg}${session.totalMessages || session.estimatedMessages}{/}`],
];
if (session.version) fields.push(['Version', `{#eab308-fg}v${session.version}{/}`]);
if (session.worktree) fields.push(['Worktree', `{#60a5fa-fg}${session.worktree}{/}`]);
if (session.parentId) fields.push(['Parent', `{#6b7280-fg}${session.parentId}{/}`]);
for (const [label, value] of fields) {
c += ` {#6b7280-fg}${label.padEnd(12)}{/} ${value}\n`;
}
if (session.toolsUsed && session.toolsUsed.length > 0) {
c += `\n {#eab308-fg}{bold}Tools Used{/}\n`;
const chips = session.toolsUsed.slice(0, 10)
.map(t => `{#3a3a3a-fg}[{/}{#c084fc-fg}${t}{/}{#3a3a3a-fg}]{/}`)
.join(' ');
c += ` ${chips}\n`;
if (session.toolsUsed.length > 10) c += ` {#6b7280-fg}+${session.toolsUsed.length - 10} more{/}\n`;
}
c += `\n {#eab308-fg}{bold}Conversation{/}\n`;
c += sep + '\n';
const msgs = (session.userMessages || []).slice(0, 10);
const assists = (session.assistantSnippets || []);
if (msgs.length === 0) {
c += `\n {#6b7280-fg}(no readable messages){/}\n`;
} else {
msgs.forEach((msg, i) => {
const clean = esc(msg.replace(/\n/g, ' ').trim());
const trunc = clean.length > 80 ? clean.substring(0, 80) + '…' : clean;
c += `\n {#22c55e-fg}{bold}▎{/} {#e5e7eb-fg}{bold}${trunc}{/}\n`;
if (assists[i]) {
const aClean = esc(assists[i].replace(/\n/g, ' ').trim());
const aTrunc = aClean.length > 80 ? aClean.substring(0, 80) + '…' : aClean;
c += ` {#60a5fa-fg}▎{/} {#9ca3af-fg}${aTrunc}{/}\n`;
}
});
}
c += `\n${sep}`;
c += `\n {#c084fc-fg}{bold}↵ Enter{/}{#9ca3af-fg} to resume this conversation{/}`;
c += `\n {#60a5fa-fg}${CLI.name} -s ${session.sessionId} -c{/}\n`;
detailPanel.setContent(c);
detailPanel.setScroll(0);
}
function renderAll() {
updateHeader();
refreshList();
renderDetail();
updateFooter();
listPanel.focus();
screen.render();
}
function applyFilter() {
if (!filterText) {
filteredSessions = [...allSessions];
} else {
const terms = filterText.toLowerCase().split(/\s+/);
filteredSessions = allSessions.filter(s => {
const haystack = [
s.project, s.title || '', s.topic || '', s.customTitle || '',
s.sessionId, s.worktree || '',
...(s.userMessages || []),
].join(' ').toLowerCase();
return terms.every(t => haystack.includes(t));
});
}
selectedIndex = Math.min(selectedIndex, Math.max(-1, filteredSessions.length - 1));
if (filterText && filteredSessions.length > 0) selectedIndex = 0;
listPanel.childBase = 0;
renderAll();
}
function cycleSort() {
const modes = ['time', 'messages', 'project'];
sortMode = modes[(modes.indexOf(sortMode) + 1) % modes.length];
const sorters = {
time: (a, b) => (b.lastTs || 0) - (a.lastTs || 0),
messages: (a, b) => b.estimatedMessages - a.estimatedMessages,
project: (a, b) => a.project.localeCompare(b.project) || (b.lastTs || 0) - (a.lastTs || 0),
};
allSessions.sort(sorters[sortMode]);
selectedIndex = 0;
applyFilter();
}
// ─── Project Picker ────────────────────────────────────────────────────
let popupOpen = false;
function showProjectPicker() {
const projects = [' All Projects', ...uniqueProjects.map(p => ` ${p}`)];
const popup = blessed.list({
parent: screen, top: 'center', left: 'center',
width: Math.min(50, Math.max(...projects.map(p => p.length)) + 8),
height: Math.min(projects.length + 4, 20),
label: ' {bold}{#60a5fa-fg}Filter by Project{/} ',
tags: true, border: { type: 'line' },
style: {
border: { fg: '#60a5fa' }, bg: '#0a0a0a', fg: '#e5e7eb',
selected: { bg: '#60a5fa', fg: 'black', bold: true },
label: { fg: '#60a5fa' },
},
items: projects, keys: true, vi: true, mouse: true,
});
popupOpen = true;
popup.focus(); screen.render();
popup.on('select', (item, index) => {
filterText = index === 0 ? '' : uniqueProjects[index - 1];
popup.destroy(); popupOpen = false; selectedIndex = 0; applyFilter();
});
popup.key(['escape', 'q'], () => { popup.destroy(); popupOpen = false; screen.render(); });
}
// ─── Selection / Navigation ────────────────────────────────────────────
const _origSelect = listPanel.select.bind(listPanel);
listPanel.select = function (index) {
const sb = this.childBase;
_origSelect(index);
this.childBase = sb;
};
let suppressSelectEvent = false;
listPanel.on('select item', (item, index) => {
if (suppressSelectEvent) return;
selectedIndex = index - 1;
renderDetail(); updateHeader(); screen.render();
});
function moveSelection(delta) {
const newIdx = selectedIndex + delta;
if (newIdx >= -1 && newIdx < filteredSessions.length) {
selectedIndex = newIdx;
const listIdx = selectedIndex + 1;
suppressSelectEvent = true;
listPanel.select(listIdx);
suppressSelectEvent = false;
const base = listPanel.childBase;
const visible = listPanel.height;
if (listIdx < base) listPanel.childBase = listIdx;
else if (listIdx >= base + visible) listPanel.childBase = listIdx - visible + 1;
renderDetail(); updateHeader(); screen.render();
}
}
screen.key(['down'], () => {
if (renameMode || popupOpen) return;
if (isSearchMode) { isSearchMode = false; updateHeader(); updateFooter(); screen.render(); }
moveSelection(1);
});
screen.key(['up'], () => {
if (renameMode || popupOpen) return;
if (isSearchMode) { isSearchMode = false; updateHeader(); updateFooter(); screen.render(); }
moveSelection(-1);
});
screen.key(['home'], () => {
if (renameMode || popupOpen) return;
selectedIndex = -1;
suppressSelectEvent = true; listPanel.select(0); suppressSelectEvent = false;
listPanel.childBase = 0;
renderDetail(); updateHeader(); screen.render();
});
screen.key(['end'], () => {
if (renameMode || popupOpen) return;
selectedIndex = Math.max(0, filteredSessions.length - 1);
suppressSelectEvent = true; listPanel.select(selectedIndex + 1); suppressSelectEvent = false;
listPanel.childBase = Math.max(0, selectedIndex + 1 - listPanel.height + 1);
renderDetail(); updateHeader(); screen.render();
});
screen.key(['pagedown', 'C-d'], () => {
if (renameMode || popupOpen) return;
moveSelection(Math.floor((listPanel.height || 20) / 2));
});
screen.key(['pageup', 'C-u'], () => {
if (renameMode || popupOpen) return;
moveSelection(-Math.floor((listPanel.height || 20) / 2));
});
screen.key(['/'], () => {
if (renameMode || isSearchMode) return;
isSearchMode = true;
updateHeader(); updateFooter(); screen.render();
});
let searchJustConfirmed = false;
screen.on('keypress', (ch, key) => {
// Rename mode: capture all keys
if (renameMode) {
if (key.name === 'return' || key.name === 'enter') {
const session = renameSession;
const value = renameValue;
closeRename();
submitRename(session, value);
return;
}
if (key.name === 'escape') {
closeRename();
listPanel.focus();
screen.render();
return;
}
if (key.name === 'backspace') {
if (renameValue.length > 0) {
renameValue = [...renameValue].slice(0, -1).join('');
renderRenameInput();
}
return;
}
if (ch && ch.length >= 1 && ch.charCodeAt(0) >= 32 && !key.ctrl && !key.meta) {
renameValue += ch;
renderRenameInput();
}
return;
}
if (key.name === 'backspace') {
if (filterText) {
filterText = filterText.slice(0, -1);
selectedIndex = -1;
isSearchMode = !!filterText;
applyFilter();
} else if (isSearchMode) {
isSearchMode = false;
applyFilter();
}
return;
}
if (!isSearchMode && !popupOpen) {
if (ch === 'j') { moveSelection(1); return; }
if (ch === 'k') { moveSelection(-1); return; }
if (ch === 'G') {
selectedIndex = Math.max(0, filteredSessions.length - 1);
suppressSelectEvent = true; listPanel.select(selectedIndex + 1); suppressSelectEvent = false;
listPanel.childBase = Math.max(0, selectedIndex + 1 - listPanel.height + 1);
renderDetail(); updateHeader(); screen.render();
return;
}
if (ch === 'g') {
selectedIndex = -1;
suppressSelectEvent = true; listPanel.select(0); suppressSelectEvent = false;
listPanel.childBase = 0;
renderDetail(); updateHeader(); screen.render();
return;
}
}
if (!isSearchMode) return;
if (key.name === 'return' || key.name === 'enter') {
isSearchMode = false; searchJustConfirmed = true; renderAll(); return;
}
if (key.name === 'escape') { isSearchMode = false; filterText = ''; applyFilter(); return; }
if (ch && ch.length === 1 && ch.charCodeAt(0) >= 32 && !key.ctrl && !key.meta) {
filterText += ch; selectedIndex = -1; applyFilter();
}
});
function resumeSession(session) {
process.stdout.write('\x1b[0m');
screen.destroy();
console.log(`\n\x1b[1m⚡ Resuming OpenCode session\x1b[0m`);
console.log(`\x1b[90m Session: ${session.sessionId}\x1b[0m`);
console.log(`\x1b[90m Project: ${session.project} │ Messages: ${session.estimatedMessages}\x1b[0m\n`);
const cwd = (session.worktree && session.worktree !== '/' && fs.existsSync(session.worktree))
? session.worktree
: (session.directory && fs.existsSync(session.directory) ? session.directory : process.cwd());
const child = spawn(`${CLI.cmd} -s ${session.sessionId} -c`,
{ stdio: 'inherit', cwd, shell: true });
child.on('error', (err) => {
console.error(`\x1b[31mFailed to resume: ${err.message}\x1b[0m`);
console.log(`\x1b[2mManual: ${CLI.name} -s ${session.sessionId} -c\x1b[0m`);
process.exit(1);
});
child.on('exit', (code) => process.exit(code || 0));
}
function startNewSession() {
process.stdout.write('\x1b[0m');
screen.destroy();
console.log(`\n\x1b[1m✨ Starting new OpenCode session\x1b[0m\n`);
const child = spawn(CLI.cmd, { stdio: 'inherit', cwd: process.cwd(), shell: true });
child.on('error', (err) => {
console.error(`\x1b[31mFailed to start: ${err.message}\x1b[0m`);
process.exit(1);
});
child.on('exit', (code) => process.exit(code || 0));
}
screen.key(['enter'], () => {
if (renameMode) return;
if (renameJustFinished) return;