-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
689 lines (586 loc) · 25.9 KB
/
test.js
File metadata and controls
689 lines (586 loc) · 25.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
#!/usr/bin/env node
/**
* OpenCode Starter — Test Suite
* ──────────────────────────────
* Run: npm test (or) node --test test.js
*
* Uses Node.js built-in test runner (node:test + node:assert).
* The native module (better-sqlite3) is required for DB-related tests; if it
* is not importable in the current environment those suites are skipped.
*/
const { describe, it, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');
const mod = require('./index.js');
const {
getProjectDisplayName,
extractPartText,
loadAllSessions,
loadSessionDetail,
deleteSessionFromDb,
formatTimestamp,
formatCount,
getProjectColor,
esc,
loadMeta,
saveMeta,
getSessionMeta,
setSessionCustomTitle,
PROJECT_COLORS,
PERMISSION_MODES,
PERMISSION_KEYS,
loadOpencodeConfig,
saveOpencodeConfig,
getCurrentPermissionMode,
setPermissionMode,
detectCLI,
} = mod;
// ─── Probe whether better-sqlite3 is loadable ───────────────────────────────
let SQLITE_OK = true;
let Database = null;
try {
Database = require('better-sqlite3');
} catch (e) {
SQLITE_OK = false;
}
// =============================================================================
// 1. getProjectDisplayName
// =============================================================================
describe('getProjectDisplayName', () => {
it('returns "global" for "/" (the global pseudo-project)', () => {
assert.equal(getProjectDisplayName('/'), 'global');
});
it('returns "global" for empty input', () => {
assert.equal(getProjectDisplayName(''), 'global');
assert.equal(getProjectDisplayName(null), 'global');
assert.equal(getProjectDisplayName(undefined), 'global');
});
it('extracts last path segment from absolute path', () => {
assert.equal(getProjectDisplayName('/Users/bob/Desktop/my-app'), 'my-app');
assert.equal(getProjectDisplayName('/Users/bob/Projects/router-maestro'), 'router-maestro');
});
it('strips well-known parent dirs (Desktop, Projects, etc.)', () => {
assert.equal(getProjectDisplayName('/home/alice/Projects/foo'), 'foo');
assert.equal(getProjectDisplayName('/Users/bob/Documents/notes-app'), 'notes-app');
});
it('keeps the last segment even with many nested dirs', () => {
assert.equal(
getProjectDisplayName('/Users/bob/Desktop/Bojun-Vibe-Codings/opencode-starter'),
'opencode-starter',
);
});
it('handles paths under home prefix', () => {
const home = os.homedir();
assert.equal(getProjectDisplayName(`${home}/work/cool-thing`), 'cool-thing');
});
});
// =============================================================================
// 2. extractPartText
// =============================================================================
describe('extractPartText', () => {
it('returns text from a "text" part', () => {
const row = { data: JSON.stringify({ type: 'text', text: 'hello world' }) };
assert.equal(extractPartText(row), 'hello world');
});
it('returns "" for non-text part types', () => {
assert.equal(extractPartText({ data: JSON.stringify({ type: 'tool', tool: 'bash' }) }), '');
assert.equal(extractPartText({ data: JSON.stringify({ type: 'step-start' }) }), '');
});
it('returns "" for malformed JSON', () => {
assert.equal(extractPartText({ data: '{not json' }), '');
});
it('returns "" if text field is missing', () => {
assert.equal(extractPartText({ data: JSON.stringify({ type: 'text' }) }), '');
});
});
// =============================================================================
// 3. formatTimestamp
// =============================================================================
describe('formatTimestamp', () => {
it('returns "unknown" for falsy input', () => {
assert.equal(formatTimestamp(null), 'unknown');
assert.equal(formatTimestamp(undefined), 'unknown');
assert.equal(formatTimestamp(0), 'unknown');
});
it('formats today as "Today HH:MM"', () => {
const now = Date.now();
const out = formatTimestamp(now);
assert.match(out, /^Today \d{2}:\d{2}$/);
});
it('formats yesterday as "Yesterday HH:MM"', () => {
const yesterday = Date.now() - 86400000;
const out = formatTimestamp(yesterday);
// Could be "Yesterday HH:MM" or "1d ago HH:MM" depending on local TZ midnight,
// but in tests today's date is computed locally so this should match.
assert.match(out, /^(Yesterday|1d ago) \d{2}:\d{2}$/);
});
it('handles ISO-string input', () => {
const out = formatTimestamp(new Date().toISOString());
assert.match(out, /^Today \d{2}:\d{2}$/);
});
it('returns a date string for >= 1 year ago', () => {
const longAgo = Date.now() - 400 * 86400000;
const out = formatTimestamp(longAgo);
assert.match(out, /\d{4}/);
});
});
// =============================================================================
// 4. formatCount
// =============================================================================
describe('formatCount', () => {
it('returns plain integer below 1k', () => {
assert.equal(formatCount(0), '0');
assert.equal(formatCount(42), '42');
assert.equal(formatCount(999), '999');
});
it('formats thousands with k suffix', () => {
assert.equal(formatCount(1000), '1.0k');
assert.equal(formatCount(12500), '12.5k');
});
it('formats millions with M suffix', () => {
assert.equal(formatCount(1500000), '1.5M');
});
});
// =============================================================================
// 5. getProjectColor
// =============================================================================
describe('getProjectColor', () => {
it('returns a string color from the palette for any project', () => {
const map = new Map();
const a = getProjectColor('proj-a', map);
assert.equal(typeof a, 'string');
assert.ok(PROJECT_COLORS.includes(a));
});
it('is deterministic — same project always gets the same color', () => {
const map = new Map();
const a1 = getProjectColor('proj-a', map);
const a2 = getProjectColor('proj-a', map);
assert.equal(a1, a2);
});
it('cycles when more projects than palette slots', () => {
const map = new Map();
for (let i = 0; i < PROJECT_COLORS.length; i++) {
getProjectColor(`p${i}`, map);
}
const wraparound = getProjectColor(`p${PROJECT_COLORS.length}`, map);
assert.equal(wraparound, PROJECT_COLORS[0]);
});
it('only uses colors from the palette', () => {
const map = new Map();
for (let i = 0; i < 50; i++) {
const c = getProjectColor(`p${i}`, map);
assert.ok(PROJECT_COLORS.includes(c), `${c} should be in palette`);
}
});
it('palette has multiple distinct colors for visual variety', () => {
const unique = new Set(PROJECT_COLORS);
assert.ok(unique.size >= 4, `expected at least 4 distinct colors, got ${unique.size}`);
});
});
// =============================================================================
// 6. esc — escape blessed tags
// =============================================================================
describe('esc', () => {
it('escapes "{" so blessed does not interpret tags', () => {
assert.equal(esc('hello {world}'), 'hello \\{world}');
});
it('passes plain text through unchanged', () => {
assert.equal(esc('plain text'), 'plain text');
});
it('handles multiple braces', () => {
assert.equal(esc('{a} {b} {c}'), '\\{a} \\{b} \\{c}');
});
it('coerces non-strings to string', () => {
assert.equal(esc(42), '42');
assert.equal(esc(true), 'true');
});
});
// =============================================================================
// 7. Meta file persistence
// =============================================================================
describe('meta file persistence', () => {
let originalMetaFile;
let tmpFile;
before(() => {
// Redirect META_FILE inside the module to a tmp file.
// The module captures META_FILE at top-level, so we need to monkey-patch
// the implementation. Easiest path: use a fresh tmp file & invoke the
// helpers directly with that path-aware behavior. But save/load read
// module-level constants, so we point process.env first… Actually our
// module uses fs APIs against META_FILE directly. We monkey-patch fs.
tmpFile = path.join(os.tmpdir(), `opencode-starter-test-meta-${Date.now()}.json`);
originalMetaFile = mod.META_FILE;
// Override exported constant ref (used internally via lexical closure too —
// load/save read the lexical var, so we cannot redirect that way).
// Instead, we test the behavior by writing to a known temp file and
// re-importing helpers that operate on objects (they DO use META_FILE for
// I/O). For a true unit test we patch the constant via a stub of fs.
});
after(() => {
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
});
it('loadMeta returns default {sessions:{}} when file missing', () => {
// Even if real META_FILE is missing it should return defaults.
const m = loadMeta();
assert.ok(m && typeof m === 'object');
assert.ok('sessions' in m);
assert.equal(typeof m.sessions, 'object');
});
it('getSessionMeta returns {} for unknown id', () => {
assert.deepEqual(getSessionMeta({ sessions: {} }, 'nope'), {});
});
it('getSessionMeta returns the stored object when present', () => {
const data = { sessions: { abc: { customTitle: 'foo' } } };
assert.deepEqual(getSessionMeta(data, 'abc'), { customTitle: 'foo' });
});
it('setSessionCustomTitle round-trips title via meta object', () => {
// We test the in-memory mutation contract — saveMeta is allowed to fail
// silently in unit tests since the real meta file path may not be writable.
const m = { sessions: {} };
setSessionCustomTitle(m, 'sess-1', 'My Title');
assert.equal(m.sessions['sess-1'].customTitle, 'My Title');
setSessionCustomTitle(m, 'sess-1', '');
assert.equal(m.sessions['sess-1'].customTitle, undefined);
});
});
// =============================================================================
// 8. saveMeta + loadMeta round-trip (real fs, isolated tmp dir)
// =============================================================================
describe('saveMeta + loadMeta round-trip (isolated)', () => {
// We cannot redirect META_FILE without re-loading the module under
// a different env. So we test save/load behavior end-to-end by
// requiring the module fresh with a stubbed os.homedir. This proves
// the JSON serialization & dir creation logic works.
let tmpHome;
let freshMod;
before(() => {
tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-starter-home-'));
// Clear require cache for index.js then re-require with stubbed home.
const origHomedir = os.homedir;
os.homedir = () => tmpHome;
delete require.cache[require.resolve('./index.js')];
freshMod = require('./index.js');
os.homedir = origHomedir;
});
after(() => {
try { fs.rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }
// Restore the original module instance for any remaining tests
delete require.cache[require.resolve('./index.js')];
require('./index.js');
});
it('saveMeta creates directory and writes JSON; loadMeta reads it back', () => {
const data = { sessions: { abc: { customTitle: '中文标题' } }, version: 1 };
freshMod.saveMeta(data);
assert.ok(fs.existsSync(freshMod.META_FILE), 'META_FILE should exist after saveMeta');
const loaded = freshMod.loadMeta();
assert.deepEqual(loaded, data);
});
it('loadMeta tolerates a corrupt JSON file', () => {
fs.writeFileSync(freshMod.META_FILE, 'not json{{{', 'utf-8');
const loaded = freshMod.loadMeta();
assert.deepEqual(loaded, { sessions: {} });
});
});
// =============================================================================
// 9. detectCLI
// =============================================================================
describe('detectCLI', () => {
it('always returns an object with name and cmd', () => {
const r = detectCLI();
assert.equal(typeof r, 'object');
assert.equal(typeof r.name, 'string');
assert.equal(typeof r.cmd, 'string');
assert.ok(r.name.length > 0);
assert.ok(r.cmd.length > 0);
});
it('always reports name === "opencode" (single-CLI tool)', () => {
assert.equal(detectCLI().name, 'opencode');
});
});
// =============================================================================
// 10. SQLite integration (skipped if better-sqlite3 unavailable)
// =============================================================================
describe('SQLite integration', { skip: !SQLITE_OK }, () => {
let tmpDb;
// Build a minimal database that mirrors the OpenCode schema we depend on.
before(() => {
if (!SQLITE_OK) return;
tmpDb = path.join(os.tmpdir(), `opencode-starter-test-${Date.now()}.db`);
const db = new Database(tmpDb);
db.exec(`
CREATE TABLE project (
id TEXT PRIMARY KEY,
worktree TEXT NOT NULL,
time_created INTEGER NOT NULL,
time_updated INTEGER NOT NULL,
sandboxes TEXT NOT NULL DEFAULT '[]'
);
CREATE TABLE session (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
parent_id TEXT,
slug TEXT NOT NULL,
directory TEXT NOT NULL,
title TEXT NOT NULL,
version TEXT NOT NULL,
time_created INTEGER NOT NULL,
time_updated INTEGER NOT NULL,
time_archived INTEGER,
FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE CASCADE
);
CREATE TABLE message (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
time_created INTEGER NOT NULL,
time_updated INTEGER NOT NULL,
data TEXT NOT NULL,
FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE
);
CREATE TABLE part (
id TEXT PRIMARY KEY,
message_id TEXT NOT NULL,
session_id TEXT NOT NULL,
time_created INTEGER NOT NULL,
time_updated INTEGER NOT NULL,
data TEXT NOT NULL,
FOREIGN KEY (message_id) REFERENCES message(id) ON DELETE CASCADE
);
`);
const now = Date.now();
db.prepare(`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES (?, ?, ?, ?, '[]')`).run(
'p-global', '/', now - 100000, now,
);
db.prepare(`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES (?, ?, ?, ?, '[]')`).run(
'p-app', '/Users/test/Desktop/my-app', now - 100000, now,
);
// Session 1: in /, 2 messages
db.prepare(`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(
'ses-1', 'p-global', 'hello', '/', 'Hello World', '1.0.0', now - 50000, now - 1000,
);
db.prepare(`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)`).run(
'm-1', 'ses-1', now - 50000, now - 50000, JSON.stringify({ role: 'user' }),
);
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)`).run(
'pa-1', 'm-1', 'ses-1', now - 50000, now - 50000, JSON.stringify({ type: 'text', text: 'first user prompt about cats' }),
);
db.prepare(`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)`).run(
'm-2', 'ses-1', now - 49000, now - 49000, JSON.stringify({ role: 'assistant' }),
);
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)`).run(
'pa-2', 'm-2', 'ses-1', now - 49000, now - 49000, JSON.stringify({ type: 'text', text: 'cats are great' }),
);
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)`).run(
'pa-2b', 'm-2', 'ses-1', now - 48999, now - 48999, JSON.stringify({ type: 'tool', tool: 'bash' }),
);
// Session 2: in /Users/test/Desktop/my-app, 1 message
db.prepare(`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(
'ses-2', 'p-app', 'fix', '/Users/test/Desktop/my-app', 'Fix Bug', '1.0.0', now - 40000, now - 500,
);
db.prepare(`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)`).run(
'm-3', 'ses-2', now - 40000, now - 40000, JSON.stringify({ role: 'user' }),
);
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)`).run(
'pa-3', 'm-3', 'ses-2', now - 40000, now - 40000, JSON.stringify({ type: 'text', text: 'fix my auth bug' }),
);
// Session 3: archived, should NOT appear
db.prepare(`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated, time_archived)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
'ses-archived', 'p-global', 'old', '/', 'Old', '1.0.0', now - 100000, now - 99000, now - 90000,
);
db.prepare(`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)`).run(
'm-arc', 'ses-archived', now - 100000, now - 100000, JSON.stringify({ role: 'user' }),
);
// Session 4: zero messages — should be filtered out by loadAllSessions
db.prepare(`INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(
'ses-empty', 'p-global', 'empty', '/', 'Empty', '1.0.0', now - 30000, now - 30000,
);
db.close();
});
after(() => {
if (tmpDb) try { fs.unlinkSync(tmpDb); } catch { /* ignore */ }
});
it('loadAllSessions returns only non-archived sessions with messages', () => {
const sessions = loadAllSessions(tmpDb);
const ids = sessions.map(s => s.sessionId).sort();
assert.deepEqual(ids, ['ses-1', 'ses-2']);
});
it('loadAllSessions sorts by time_updated desc', () => {
const sessions = loadAllSessions(tmpDb);
assert.equal(sessions[0].sessionId, 'ses-2'); // newer
assert.equal(sessions[1].sessionId, 'ses-1');
});
it('loadAllSessions populates project name from worktree', () => {
const sessions = loadAllSessions(tmpDb);
const byId = Object.fromEntries(sessions.map(s => [s.sessionId, s]));
assert.equal(byId['ses-1'].project, 'global');
assert.equal(byId['ses-2'].project, 'my-app');
});
it('loadAllSessions extracts the first user text as topic', () => {
const sessions = loadAllSessions(tmpDb);
const byId = Object.fromEntries(sessions.map(s => [s.sessionId, s]));
assert.equal(byId['ses-1'].topic, 'first user prompt about cats');
assert.equal(byId['ses-2'].topic, 'fix my auth bug');
});
it('loadAllSessions respects message counts', () => {
const sessions = loadAllSessions(tmpDb);
const byId = Object.fromEntries(sessions.map(s => [s.sessionId, s]));
assert.equal(byId['ses-1'].estimatedMessages, 2);
assert.equal(byId['ses-2'].estimatedMessages, 1);
});
it('loadSessionDetail collects user/assistant messages and tools', () => {
const sessions = loadAllSessions(tmpDb);
const ses1 = sessions.find(s => s.sessionId === 'ses-1');
loadSessionDetail(ses1, tmpDb);
assert.deepEqual(ses1.userMessages, ['first user prompt about cats']);
assert.deepEqual(ses1.assistantSnippets, ['cats are great']);
assert.deepEqual(ses1.toolsUsed, ['bash']);
assert.equal(ses1._detailLoaded, true);
});
it('loadSessionDetail is idempotent', () => {
const sessions = loadAllSessions(tmpDb);
const ses = sessions[0];
loadSessionDetail(ses, tmpDb);
const before = JSON.stringify(ses.userMessages);
loadSessionDetail(ses, tmpDb); // call again
assert.equal(JSON.stringify(ses.userMessages), before);
});
it('deleteSessionFromDb removes the session and cascades messages/parts', () => {
// Create an isolated temp db copy so we don't mutate the suite's fixtures
const copy = tmpDb + '.copy';
fs.copyFileSync(tmpDb, copy);
const ok = deleteSessionFromDb('ses-1', copy);
assert.equal(ok, true);
const after = loadAllSessions(copy);
assert.ok(!after.find(s => s.sessionId === 'ses-1'), 'ses-1 should be gone');
const db = new Database(copy);
const msgCount = db.prepare('SELECT COUNT(*) AS c FROM message WHERE session_id = ?').get('ses-1').c;
const partCount = db.prepare('SELECT COUNT(*) AS c FROM part WHERE session_id = ?').get('ses-1').c;
db.close();
assert.equal(msgCount, 0, 'cascaded message rows should be deleted');
assert.equal(partCount, 0, 'cascaded part rows should be deleted');
fs.unlinkSync(copy);
});
it('deleteSessionFromDb returns false for non-existent id', () => {
const copy = tmpDb + '.copy2';
fs.copyFileSync(tmpDb, copy);
const ok = deleteSessionFromDb('does-not-exist', copy);
assert.equal(ok, false);
fs.unlinkSync(copy);
});
});
// =============================================================================
// 11. CLI integration: --version, --help, --list
// =============================================================================
describe('CLI integration', () => {
const bin = path.join(__dirname, 'index.js');
it('--version prints the version', () => {
const out = execSync(`node ${bin} --version`).toString();
assert.match(out, /opencode-starter v\d+\.\d+\.\d+/);
});
it('-v also prints the version', () => {
const out = execSync(`node ${bin} -v`).toString();
assert.match(out, /opencode-starter v/);
});
it('--help prints usage', () => {
const out = execSync(`node ${bin} --help`).toString();
assert.match(out, /Usage:/);
assert.match(out, /--list/);
assert.match(out, /--version/);
assert.match(out, /Keyboard Shortcuts/);
});
it('--list runs without throwing (uses real OpenCode db if present)', () => {
// We don't assert specific content; just that the command exits 0.
const out = execSync(`node ${bin} --list 1`, { stdio: ['ignore', 'pipe', 'pipe'] }).toString();
assert.match(out, /OpenCode Sessions/);
});
});
// =============================================================================
// 12. OpenCode permission-mode config (~/.config/opencode/opencode.json)
// =============================================================================
describe('OpenCode permission config', () => {
// We re-require the module under a stubbed os.homedir so the helpers
// operate on an isolated tmp dir — the real ~/.config/opencode is untouched.
let tmpHome;
let m;
before(() => {
tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-starter-cfg-'));
const orig = os.homedir;
os.homedir = () => tmpHome;
delete require.cache[require.resolve('./index.js')];
m = require('./index.js');
os.homedir = orig;
});
after(() => {
try { fs.rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }
delete require.cache[require.resolve('./index.js')];
require('./index.js');
});
it('exports the permission keys and modes', () => {
assert.deepEqual(m.PERMISSION_MODES, ['ask', 'allow', 'deny']);
assert.deepEqual(m.PERMISSION_KEYS, ['edit', 'bash', 'webfetch']);
});
it('loadOpencodeConfig returns null when no config file exists', () => {
assert.equal(m.loadOpencodeConfig(), null);
});
it('getCurrentPermissionMode defaults to "ask" with no config', () => {
assert.equal(m.getCurrentPermissionMode(), 'ask');
});
it('setPermissionMode("allow") writes a config setting all keys to allow', () => {
const ok = m.setPermissionMode('allow');
assert.equal(ok, true);
assert.ok(fs.existsSync(m.OPENCODE_CONFIG_FILE));
const cfg = m.loadOpencodeConfig();
assert.equal(cfg.permission.edit, 'allow');
assert.equal(cfg.permission.bash, 'allow');
assert.equal(cfg.permission.webfetch, 'allow');
assert.equal(cfg.$schema, 'https://opencode.ai/config.json');
assert.equal(m.getCurrentPermissionMode(), 'allow');
});
it('setPermissionMode preserves other top-level keys', () => {
// Pretend the user already had some unrelated config
const cfg = m.loadOpencodeConfig() || {};
cfg.theme = 'mono';
cfg.model = 'github-copilot/claude-opus-4.7';
m.saveOpencodeConfig(cfg);
const ok = m.setPermissionMode('ask');
assert.equal(ok, true);
const after = m.loadOpencodeConfig();
assert.equal(after.theme, 'mono');
assert.equal(after.model, 'github-copilot/claude-opus-4.7');
assert.equal(after.permission.edit, 'ask');
assert.equal(m.getCurrentPermissionMode(), 'ask');
});
it('getCurrentPermissionMode returns "mixed" when keys disagree', () => {
const cfg = m.loadOpencodeConfig() || {};
cfg.permission = { edit: 'allow', bash: 'ask', webfetch: 'allow' };
m.saveOpencodeConfig(cfg);
assert.equal(m.getCurrentPermissionMode(), 'mixed');
});
it('getCurrentPermissionMode returns "mixed" for object/per-command rules', () => {
const cfg = m.loadOpencodeConfig() || {};
cfg.permission = {
edit: 'allow',
bash: { 'rm -rf *': 'ask', '*': 'allow' },
webfetch: 'allow',
};
m.saveOpencodeConfig(cfg);
assert.equal(m.getCurrentPermissionMode(), 'mixed');
});
it('setPermissionMode rejects invalid mode values', () => {
assert.throws(() => m.setPermissionMode('yolo'), /Invalid permission mode/);
});
it('loadOpencodeConfig tolerates a corrupt JSON file (returns null)', () => {
fs.writeFileSync(m.OPENCODE_CONFIG_FILE, '{not json', 'utf-8');
assert.equal(m.loadOpencodeConfig(), null);
// And next setPermissionMode should still succeed by writing a fresh file
const ok = m.setPermissionMode('deny');
assert.equal(ok, true);
assert.equal(m.getCurrentPermissionMode(), 'deny');
});
});