pi-odd-worktree 3.13.0 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2472,10 +2472,19 @@ describe('createOddView grouped listing (T9: S10,S11,S13)', () => {
2472
2472
  const rowsOf = (lines) => listCells(lines)
2473
2473
  .map((cell) => cell.trim().replace(/^▸\s*/, ''))
2474
2474
  .filter((cell) => cell !== '');
2475
+ // The focused row's label. The CURSOR is the first cell after the frame's
2476
+ // `│ `, so it sits at index 1 of the pane cell, while a folded group's own
2477
+ // marker is indented past it: a folded header is not mistaken for the cursor
2478
+ // (odd-panel-groups S1 makes every group folded by default).
2475
2479
  const focusedRow = (lines) => {
2476
- const cell = listCells(lines).map((value) => value.trim()).find((value) => value.startsWith('▸'));
2477
- return cell === undefined ? null : cell.replace(/^▸\s*/, '');
2480
+ const cell = listCells(lines).find((value) => value[1] === '▸');
2481
+ return cell === undefined ? null : cell.trim().replace(/^▸\s*/, '');
2478
2482
  };
2483
+ // The list rows as LABELS, with the cursor and the fold marker removed, so a row
2484
+ // reads the same however it is drawn.
2485
+ const labelsOf = (lines) => listCells(lines)
2486
+ .map((cell) => cell.replace(/[▸▾]/g, '').trim().replace(/\s+/g, ' '))
2487
+ .filter((cell) => cell !== '');
2479
2488
  const bodyOf = (lines) => strip(lines.join('\n'));
2480
2489
  const footerOf = (lines) => strip(lines[lines.length - 2]);
2481
2490
 
@@ -2538,54 +2547,52 @@ describe('createOddView grouped listing (T9: S10,S11,S13)', () => {
2538
2547
  assert.ok(!bodyOf(groupedFrame).includes('▾'), 'and no header is painted');
2539
2548
  });
2540
2549
 
2541
- test('S10: a header row per checkout, in order, each followed by its own documents', async () => {
2542
- const view = build({ groups: [MAIN, RAIL] });
2550
+ test('S1: a header row per checkout, in order, and Enter opens each one', async () => {
2551
+ const view = build({ groups: [MAIN, RAIL], initialDoc: '/wt/main/odd/tasks/alpha.md' });
2543
2552
  await tick();
2544
- const lines = view.render(100);
2545
- assert.deepEqual(rowsOf(lines), ['▾ main', 'alpha', 'bravo', '▾ odd-rail', 'delta'],
2546
- 'the main group, its documents, then the worktree group and its documents');
2547
- assert.equal(focusedRow(lines), 'alpha', 'the first DOCUMENT is focused, not the header');
2548
- assert.match(bodyOf(lines), /body of alpha/, 'and its document is the one painted');
2549
- assert.match(bodyOf(lines), /✎ Odd · 3 documents/, 'the title counts the listed documents');
2553
+ assert.deepEqual(labelsOf(view.render(100)), ['main (2 odd)', 'alpha', 'bravo', 'odd-rail (1 odd)'],
2554
+ 'main first with its documents, then the worktree group, still folded');
2555
+ // From alpha, two steps reach the odd-rail header; Enter opens it.
2556
+ view.handleInput('down');
2557
+ view.handleInput('down');
2558
+ view.handleInput('enter');
2559
+ assert.deepEqual(labelsOf(view.render(100)), ['main (2 odd)', 'alpha', 'bravo', 'odd-rail (1 odd)', 'delta'],
2560
+ 'the opened worktree group follows main with its own document');
2550
2561
  });
2551
2562
 
2552
2563
  test('S13: a worktree group with no documents of its own is dropped', async () => {
2553
2564
  const view = build({ groups: [MAIN, RAIL, checkout('odd-fix', '/wt/odd-fix', false, [])] });
2554
2565
  await tick();
2555
2566
  const lines = view.render(100);
2556
- assert.deepEqual(rowsOf(lines), ['▾ main', 'alpha', 'bravo', '▾ odd-rail', 'delta'],
2567
+ assert.deepEqual(labelsOf(lines), ['main (2 odd)', 'odd-rail (1 odd)'],
2557
2568
  'the empty worktree contributes neither header nor rows');
2558
2569
  assert.ok(!bodyOf(lines).includes('odd-fix'), 'and it is never named');
2559
2570
  });
2560
2571
 
2561
- test('S10: Enter on a header collapses the group, hides its documents and keeps the focus on it', async () => {
2572
+ test('S10: Enter on a header opens it, Enter again closes it, and the focus stays on it', async () => {
2562
2573
  const view = build({ groups: [MAIN, RAIL] });
2563
2574
  await tick();
2564
- // Rows: [header main, alpha, bravo, header odd-rail, delta]; the mount
2565
- // focuses alpha (index 1), so two steps reach the worktree header.
2566
- for (let step = 0; step < 2; step += 1) view.handleInput('down');
2567
- assert.equal(focusedRow(view.render(100)), '▾ odd-rail', 'the premise: the header is focused');
2575
+ // The folded default paints two headers; one step reaches the worktree header.
2576
+ view.handleInput('down');
2577
+ assert.equal(focusedRow(view.render(100)), '▸ odd-rail (1 odd)', 'the premise: the folded header is focused');
2568
2578
  view.handleInput('enter');
2569
- const collapsed = view.render(100);
2570
- assert.deepEqual(rowsOf(collapsed), ['▾ main', 'alpha', 'bravo', '▸ odd-rail'],
2571
- 'the header stays and its documents are gone');
2572
- assert.equal(focusedRow(collapsed), '▸ odd-rail', 'the focus stays on the header');
2573
- assert.equal(view.state.index, 3, 'and so does its row');
2574
- assert.ok(!bodyOf(collapsed).includes('delta'), 'the collapsed documents are hidden');
2579
+ const opened = view.render(100);
2580
+ assert.deepEqual(labelsOf(opened), ['main (2 odd)', 'odd-rail (1 odd)', 'delta'], 'its document appears');
2581
+ assert.equal(focusedRow(opened), '▾ odd-rail (1 odd)', 'and the focus stays on the header');
2582
+ assert.equal(view.state.index, 1, 'which is still its row');
2575
2583
  view.handleInput('enter');
2576
- assert.deepEqual(rowsOf(view.render(100)), ['▾ main', 'alpha', 'bravo', '▾ odd-rail', 'delta'],
2577
- 'Enter again reopens it');
2584
+ assert.deepEqual(labelsOf(view.render(100)), ['main (2 odd)', 'odd-rail (1 odd)'], 'Enter again closes it');
2578
2585
  });
2579
2586
 
2580
2587
  test('Enter on a document keeps today\'s no-op: nothing folds and nothing moves', async () => {
2581
- const view = build({ groups: [MAIN, RAIL] });
2588
+ const view = build({ groups: [MAIN, RAIL], initialDoc: '/wt/main/odd/tasks/alpha.md' });
2582
2589
  await tick();
2583
2590
  view.handleInput('down');
2584
2591
  const before = view.render(100);
2585
2592
  assert.equal(focusedRow(before), 'bravo', 'the premise: a document is focused');
2586
2593
  view.handleInput('enter');
2587
2594
  const after = view.render(100);
2588
- assert.deepEqual(rowsOf(after), rowsOf(before), 'no group folded around the focused document');
2595
+ assert.deepEqual(labelsOf(after), labelsOf(before), 'no group folded around the focused document');
2589
2596
  assert.equal(view.state.index, 2, 'and the selection did not move');
2590
2597
  });
2591
2598
 
@@ -2663,12 +2670,15 @@ describe('createOddView grouped listing (T9: S10,S11,S13)', () => {
2663
2670
  });
2664
2671
 
2665
2672
  test('S11: the reloaded grouping re-applies the selection when the document is still there', async () => {
2666
- const view = build({ groups: [MAIN, RAIL], onToggleAll: () => {} });
2673
+ const view = build({
2674
+ groups: [MAIN, RAIL],
2675
+ initialDoc: '/wt/odd-rail/odd/tasks/delta.md',
2676
+ onToggleAll: () => {},
2677
+ });
2667
2678
  await tick();
2668
- for (let step = 0; step < 3; step += 1) view.handleInput('down');
2669
2679
  assert.equal(focusedRow(view.render(100)), 'delta', 'the premise: delta is the document being read');
2670
2680
  // The caller answered the `a` toggle with every worktree: delta is still
2671
- // there, in a different place of a longer listing.
2681
+ // there, in a longer listing, and its group is still the one open.
2672
2682
  view.applyGroups([
2673
2683
  MAIN,
2674
2684
  checkout('odd-rail', '/wt/odd-rail', false, [
@@ -2678,7 +2688,7 @@ describe('createOddView grouped listing (T9: S10,S11,S13)', () => {
2678
2688
  ]);
2679
2689
  await tick();
2680
2690
  const lines = view.render(100);
2681
- assert.deepEqual(rowsOf(lines), ['▾ main', 'alpha', 'bravo', '▾ odd-rail', 'zulu', 'delta']);
2691
+ assert.deepEqual(labelsOf(lines), ['main (2 odd)', 'odd-rail (2 odd)', 'zulu', 'delta']);
2682
2692
  assert.equal(focusedRow(lines), 'delta', 'the reader keeps the SAME document');
2683
2693
  assert.match(bodyOf(lines), /body of delta/, 'and its pane is still the one being read');
2684
2694
  });
@@ -2705,10 +2715,88 @@ describe('createOddView grouped listing (T9: S10,S11,S13)', () => {
2705
2715
  await tick();
2706
2716
  const lines = view.render(100);
2707
2717
  assert.equal(focusedRow(lines), 'delta', 'the highlight is on the requested document row');
2708
- assert.equal(view.state.index, 3, 'across the group it lives in');
2718
+ assert.equal(view.state.index, 2, 'across the group it lives in, which is the only one open');
2709
2719
  assert.match(bodyOf(lines), /body of delta/, 'the right pane starts on the requested document');
2710
2720
  assert.equal(view.state.scroll, 0, 'and at the top of it');
2711
2721
  });
2722
+
2723
+ // -------------------------------------------------------------------------
2724
+ // odd-panel-groups (S1-S5): the panel OPENS folded, expands the ONE group the
2725
+ // requested ODD lives in, aligns a document's text with its group's text and
2726
+ // counts every group and the whole listing.
2727
+ // -------------------------------------------------------------------------
2728
+ test('S1: every group opens folded, with no document row painted', async () => {
2729
+ const view = build({ groups: [MAIN, RAIL] });
2730
+ await tick();
2731
+ const lines = view.render(100);
2732
+ assert.deepEqual(labelsOf(lines), ['main (2 odd)', 'odd-rail (1 odd)'],
2733
+ 'the two headers and nothing under them');
2734
+ assert.equal(view.state.index, 0, 'the cursor opens on the first header');
2735
+ assert.equal(listCells(lines)[0][1], '▸', 'drawn as the focused row');
2736
+ assert.match(bodyOf(lines), /enter opens this group/, 'and the pane says how to open one');
2737
+ });
2738
+
2739
+ test('S2: the requested document expands its OWN group only, and is selected', async () => {
2740
+ const view = build({ groups: [MAIN, RAIL], initialDoc: '/wt/odd-rail/odd/tasks/delta.md' });
2741
+ await tick();
2742
+ const lines = view.render(100);
2743
+ assert.deepEqual(labelsOf(lines), ['main (2 odd)', 'odd-rail (1 odd)', 'delta'],
2744
+ 'main stays folded; the group of the requested ODD is the only one open');
2745
+ assert.equal(focusedRow(lines), 'delta', 'and its document is the selection');
2746
+ assert.match(bodyOf(lines), /body of delta/, 'the pane is on it');
2747
+ });
2748
+
2749
+ test('S2: a request for a document of main expands main and leaves the worktree folded', async () => {
2750
+ const view = build({ groups: [MAIN, RAIL], initialDoc: '/wt/main/odd/tasks/bravo.md' });
2751
+ await tick();
2752
+ const lines = view.render(100);
2753
+ assert.deepEqual(labelsOf(lines), ['main (2 odd)', 'alpha', 'bravo', 'odd-rail (1 odd)'],
2754
+ 'main is open, the worktree group stays closed');
2755
+ assert.equal(focusedRow(lines), 'bravo');
2756
+ });
2757
+
2758
+ test('S1: Enter opens the focused group and closes it again', async () => {
2759
+ const view = build({ groups: [MAIN, RAIL] });
2760
+ await tick();
2761
+ view.handleInput('enter');
2762
+ assert.deepEqual(labelsOf(view.render(100)), ['main (2 odd)', 'alpha', 'bravo', 'odd-rail (1 odd)'],
2763
+ 'Enter on the folded header opens that group only');
2764
+ view.handleInput('enter');
2765
+ assert.deepEqual(labelsOf(view.render(100)), ['main (2 odd)', 'odd-rail (1 odd)'],
2766
+ 'Enter again closes it');
2767
+ });
2768
+
2769
+ test('S3: a document reads at the column its group name starts at', async () => {
2770
+ const view = build({ groups: [MAIN, RAIL], initialDoc: '/wt/main/odd/tasks/alpha.md' });
2771
+ await tick();
2772
+ const cells = listCells(view.render(100));
2773
+ const header = cells.find((cell) => cell.includes('main (2 odd)'));
2774
+ const child = cells.find((cell) => cell.includes('alpha'));
2775
+ assert.ok(header !== undefined && child !== undefined, 'both rows are painted');
2776
+ assert.equal(child.indexOf('alpha'), header.indexOf('main'),
2777
+ 'the document starts at the column the group name starts at');
2778
+ assert.ok(header.indexOf('main') > 2, 'and the disclosure marker keeps a column of its own');
2779
+ });
2780
+
2781
+ test('S4/S5: each header carries its count and the title sums every group', async () => {
2782
+ const view = build({ groups: [MAIN, RAIL], initialDoc: '/wt/main/odd/tasks/alpha.md' });
2783
+ await tick();
2784
+ const text = bodyOf(view.render(100));
2785
+ assert.match(text, /▾ main \(2 odd\)/, 'the main group names how many it lists');
2786
+ assert.match(text, /▸ odd-rail \(1 odd\)/, 'and so does the folded worktree group');
2787
+ assert.match(text, /✎ Odd · 3 documents/, '2 of main + 1 of the worktree = 3, never 2');
2788
+ });
2789
+
2790
+ test('S4: a group with one document says `1 odd`, never `1 odds`', async () => {
2791
+ const view = build({
2792
+ groups: [checkout('main', '/wt/main', true, [groupDoc('alpha')]), RAIL],
2793
+ initialDoc: '/wt/main/odd/tasks/alpha.md',
2794
+ });
2795
+ await tick();
2796
+ const text = bodyOf(view.render(100));
2797
+ assert.match(text, /▾ main \(1 odd\)/);
2798
+ assert.ok(!text.includes('odds'), 'the count is `odd` at every size');
2799
+ });
2712
2800
  });
2713
2801
 
2714
2802
  // ---------------------------------------------------------------------------
@@ -0,0 +1,252 @@
1
+ 'use strict';
2
+ // S1/S5/S7/S8 (opencode-usage-alert): what the extension registers and draws for the halves
3
+ // absorbed from `pi-opencode-gs`. The engine and the rows are unit-tested on their own; this
4
+ // suite is the WIRING — the exact event payload, and the fact that the peak rows above the
5
+ // editor are one row per provider, gated by that provider's own switch and by its window, never
6
+ // by the model this session uses and never by a usage key.
7
+ //
8
+ // The instants are pinned by replacing `Date.now` alone: the sync reads the clock through it,
9
+ // and every schedule function takes the instant it reasons about as an argument.
10
+ const { test, describe, afterEach } = require('node:test');
11
+ const assert = require('node:assert/strict');
12
+ const os = require('node:os');
13
+
14
+ const { BRIDGE_SLOT, defaultBridge, loadExtension } = require('./fixtures/load-extension.js');
15
+
16
+ // Tuesday, inside DeepSeek's first UTC window (01:00–04:00) and outside Claude's.
17
+ const DEEPSEEK_PEAK = Date.UTC(2026, 10, 24, 2, 0, 0);
18
+ // The same Tuesday afternoon: Claude's window in Pacific STANDARD time (13:00–19:00 UTC here),
19
+ // which is where DeepSeek is off-peak. The two windows never overlap today, which is why each
20
+ // case pins only the provider it names.
21
+ const CLAUDE_PEAK = Date.UTC(2026, 10, 24, 15, 0, 0);
22
+
23
+ const WIDGET_KEY = 'opencode-go-peak-widget';
24
+
25
+ function usagePayload() {
26
+ const reset = '2026-11-24T09:00:00Z';
27
+ return {
28
+ usage: {
29
+ rolling: { status: 'ok', percent: 12, resetsAt: reset },
30
+ weekly: { status: 'ok', percent: 30, resetsAt: reset },
31
+ monthly: { status: 'ok', percent: 48, resetsAt: reset },
32
+ },
33
+ };
34
+ }
35
+
36
+ const OK_FETCH = async () => ({ ok: true, redirected: false, url: 'https://opencode.ai/zen/go/v1/usage', json: async () => usagePayload() });
37
+
38
+ /** A host whose widget map is captured, so a paint is observed where the human sees it. */
39
+ function capturingUi() {
40
+ const calls = [];
41
+ const ui = {
42
+ setWidget(key, content, options) {
43
+ calls.push({ key, content, options });
44
+ },
45
+ notify() {},
46
+ };
47
+ const lastFor = (key) => {
48
+ const matching = calls.filter((call) => call.key === key);
49
+ return matching.length === 0 ? undefined : matching[matching.length - 1];
50
+ };
51
+ return { ui, calls, lastFor };
52
+ }
53
+
54
+ /** A bridge whose own-store `alerts` document is the one handed in. */
55
+ async function load(alertsDocument) {
56
+ const bridge = defaultBridge();
57
+ let document = alertsDocument;
58
+ bridge.api.createStore = () => ({
59
+ get: (key, fallback) => (key === 'alerts' && document !== undefined ? document : fallback),
60
+ set: (key, value) => {
61
+ if (key === 'alerts') document = value;
62
+ },
63
+ delete: () => {},
64
+ });
65
+ const emitted = [];
66
+ // The slot is installed BEFORE the load: the extension reads the published object once, at
67
+ // registration, and the fixture's own default bridge only fills an empty slot.
68
+ globalThis[BRIDGE_SLOT] = bridge.api;
69
+ const loaded = await loadExtension({
70
+ events: { emit: (name, payload) => emitted.push({ name, payload }) },
71
+ });
72
+ return { ...loaded, bridge, emitted, storeDocument: () => document };
73
+ }
74
+
75
+ const saved = globalThis[BRIDGE_SLOT];
76
+ afterEach(() => {
77
+ if (saved === undefined) delete globalThis[BRIDGE_SLOT];
78
+ else globalThis[BRIDGE_SLOT] = saved;
79
+ });
80
+
81
+ /** Run `run` with the process clock answering exactly `instant`. */
82
+ function atFixedInstant(instant, run) {
83
+ const realNow = Date.now;
84
+ Date.now = () => instant;
85
+ try {
86
+ return run();
87
+ } finally {
88
+ Date.now = realNow;
89
+ }
90
+ }
91
+
92
+ /** The session boundary, at one instant, exactly as the host calls it. */
93
+ function startSessionAt(loaded, ui, instant) {
94
+ const ctx = { ui, cwd: os.tmpdir() };
95
+ atFixedInstant(instant, () => {
96
+ for (const [name, hook] of loaded.hooks) if (name === 'session_start') hook({}, ctx);
97
+ });
98
+ return ctx;
99
+ }
100
+
101
+ const alertRowsOf = (bridge) => bridge.rows.find((provider) => provider.category === 'Alert');
102
+
103
+ describe('the OpenCode Go usage source', () => {
104
+ test('registers one payload with the four contract keys', async () => {
105
+ const { emitted } = await load(undefined);
106
+ const registrations = emitted.filter((entry) => entry.name === 'gentle-pi:usage-source/v1');
107
+ assert.equal(registrations.length, 1, 'one source per load');
108
+ const payload = registrations[0].payload;
109
+ assert.deepEqual(Object.keys(payload).sort(), ['fetch', 'pendingNote', 'provider', 'schema']);
110
+ assert.equal(payload.schema, 'gentle-pi.usage-source/v1');
111
+ assert.equal(payload.provider, 'opencode-go');
112
+ assert.equal(payload.pendingNote, 'opencode-go · press r to fetch');
113
+ assert.equal(typeof payload.fetch, 'function');
114
+ });
115
+
116
+ test('the fetch carries the peak schedule in its plan field, off-peak included', async () => {
117
+ const { emitted } = await load(undefined);
118
+ const source = emitted.find((entry) => entry.name === 'gentle-pi:usage-source/v1').payload;
119
+ const peak = await source.fetch('key', OK_FETCH, DEEPSEEK_PEAK);
120
+ const off = await source.fetch('key', OK_FETCH, CLAUDE_PEAK);
121
+ assert.match(peak.plan, /^peak /);
122
+ assert.match(off.plan, /^off-peak /);
123
+ assert.deepEqual(
124
+ peak.limits[0].windows.map((window) => window.label),
125
+ ['5h', 'week', 'month'],
126
+ 'the panel rows keep their plain window names',
127
+ );
128
+ });
129
+
130
+ test('a missing key never stops the source from existing', async () => {
131
+ const { emitted } = await load(undefined);
132
+ const source = emitted.find((entry) => entry.name === 'gentle-pi:usage-source/v1').payload;
133
+ assert.equal(await source.fetch(undefined, OK_FETCH, DEEPSEEK_PEAK), undefined, 'no key, no snapshot');
134
+ assert.equal(typeof source.pendingNote, 'string', 'and the panel still has its pending line');
135
+ });
136
+ });
137
+
138
+ describe('the Alert page', () => {
139
+ test('is one provider, one Off/On pair, in the registry order, both Off by default', async () => {
140
+ const { bridge } = await load(undefined);
141
+ const alerts = alertRowsOf(bridge);
142
+ assert.ok(alerts, 'the page is registered');
143
+ assert.deepEqual(alerts.categoryPlacement, { after: 'Notifications' });
144
+ const rows = alerts.rows({});
145
+ assert.deepEqual(
146
+ rows.map((row) => `${row.choice.setting} ${row.choice.value}`),
147
+ ['Deepseek peak Off', 'Deepseek peak On', 'Claude peak Off', 'Claude peak On'],
148
+ 'a first run reads Off for every provider',
149
+ );
150
+ assert.deepEqual(
151
+ rows.filter((row) => row.choice.current()).map((row) => row.choice.value),
152
+ ['Off', 'Off'],
153
+ 'no provider is On until the human says so',
154
+ );
155
+ });
156
+
157
+ test('each provider reads and writes its own value, leaving the other alone', async () => {
158
+ const { bridge, storeDocument } = await load(undefined);
159
+ const alerts = alertRowsOf(bridge);
160
+ const claudeOn = alerts.rows({}).find((row) => row.choice.setting === 'Claude peak' && row.choice.value === 'On');
161
+ claudeOn.action({});
162
+ assert.deepEqual(storeDocument(), { peaks: { claude: true } });
163
+ const current = alerts.rows({}).filter((row) => row.choice.current());
164
+ assert.deepEqual(
165
+ current.map((row) => `${row.choice.setting} ${row.choice.value}`),
166
+ ['Deepseek peak Off', 'Claude peak On'],
167
+ 'DeepSeek stays Off',
168
+ );
169
+ });
170
+ });
171
+
172
+ describe('the peak rows above the editor', () => {
173
+ test('draw nothing while every switch is Off, whatever the clock says', async () => {
174
+ const loaded = await load(undefined);
175
+ const { ui, lastFor } = capturingUi();
176
+ startSessionAt(loaded, ui, DEEPSEEK_PEAK);
177
+ assert.equal(lastFor(WIDGET_KEY).content, undefined, 'Off owns no row');
178
+ });
179
+
180
+ test('one provider in peak draws exactly its own row, with no fetch and no key', async () => {
181
+ const loaded = await load({ peaks: { claude: true } });
182
+ const { ui, lastFor } = capturingUi();
183
+ startSessionAt(loaded, ui, CLAUDE_PEAK);
184
+ const paint = lastFor(WIDGET_KEY);
185
+ assert.equal(paint.options.placement, 'aboveEditor');
186
+ assert.equal(paint.content.length, 1, 'one row for one provider');
187
+ assert.match(paint.content[0], /claude/);
188
+ assert.match(paint.content[0], /until /);
189
+ });
190
+
191
+ test('DeepSeek and Claude are independent: each switch draws only its own row', async () => {
192
+ const deepseek = await load({ peaks: { deepseek: true } });
193
+ const first = capturingUi();
194
+ startSessionAt(deepseek, first.ui, DEEPSEEK_PEAK);
195
+ assert.equal(first.lastFor(WIDGET_KEY).content.length, 1);
196
+ assert.match(first.lastFor(WIDGET_KEY).content[0], /2× deepseek/);
197
+ // The same switch at Claude's instant draws nothing: a window is a window.
198
+ atFixedInstant(CLAUDE_PEAK, () => {
199
+ for (const [name, hook] of deepseek.hooks) {
200
+ if (name === 'turn_end') hook({}, { ui: first.ui, cwd: os.tmpdir() });
201
+ }
202
+ });
203
+ assert.equal(first.lastFor(WIDGET_KEY).content, undefined, 'DeepSeek off-peak, no row');
204
+
205
+ const claude = await load({ peaks: { claude: true } });
206
+ const second = capturingUi();
207
+ startSessionAt(claude, second.ui, DEEPSEEK_PEAK);
208
+ assert.equal(second.lastFor(WIDGET_KEY).content, undefined, 'Claude off-peak at 02:00 UTC');
209
+ atFixedInstant(CLAUDE_PEAK, () => {
210
+ for (const [name, hook] of claude.hooks) {
211
+ if (name === 'turn_end') hook({}, { ui: second.ui, cwd: os.tmpdir() });
212
+ }
213
+ });
214
+ assert.equal(second.lastFor(WIDGET_KEY).content.length, 1);
215
+ assert.match(second.lastFor(WIDGET_KEY).content[0], /claude/);
216
+ });
217
+
218
+ test('Off withholds one row in the running session and On brings it back', async () => {
219
+ const loaded = await load({ peaks: { deepseek: true } });
220
+ const { bridge, storeDocument } = loaded;
221
+ const alerts = alertRowsOf(bridge);
222
+ const { ui, lastFor } = capturingUi();
223
+ startSessionAt(loaded, ui, DEEPSEEK_PEAK);
224
+ assert.ok(Array.isArray(lastFor(WIDGET_KEY).content));
225
+
226
+ const off = alerts.rows({}).find((row) => row.choice.setting === 'Deepseek peak' && row.choice.value === 'Off');
227
+ atFixedInstant(DEEPSEEK_PEAK, () => off.action({}));
228
+ assert.equal(storeDocument().peaks.deepseek, false, 'the choice is persisted');
229
+ assert.equal(lastFor(WIDGET_KEY).content, undefined, 'Off withholds the row at once');
230
+
231
+ const on = alerts.rows({}).find((row) => row.choice.setting === 'Deepseek peak' && row.choice.value === 'On');
232
+ atFixedInstant(DEEPSEEK_PEAK, () => on.action({}));
233
+ assert.equal(storeDocument().peaks.deepseek, true);
234
+ assert.ok(Array.isArray(lastFor(WIDGET_KEY).content), 'On restores it with no /reload');
235
+ });
236
+
237
+ // The two real windows never overlap today (DeepSeek 01:00–04:00 and 06:00–10:00 UTC, Claude
238
+ // 12:00–18:00 UTC under PDT and 13:00–19:00 UTC under PST), so "two rows at once" is proved where
239
+ // it can be: on the engine, with two providers told apart (tools/peak-schedule.test.js). What the
240
+ // wiring owes that engine is the loop, and the case below is its shape — every provider whose own
241
+ // switch is On contributes its own line, in the registry's order, and nothing merges them.
242
+ test('the rows are built per provider, never merged into one line', async () => {
243
+ const loaded = await load({ peaks: { deepseek: true, claude: true } });
244
+ const { ui, lastFor } = capturingUi();
245
+ startSessionAt(loaded, ui, CLAUDE_PEAK);
246
+ const content = lastFor(WIDGET_KEY).content;
247
+ assert.equal(content.length, 1, 'only Claude is inside its window at 15:00 UTC');
248
+ assert.match(content[0], /^.*claude/);
249
+ assert.doesNotMatch(content[0], /deepseek/, 'the off-peak provider is not mentioned');
250
+ assert.equal(new Set(content).size, content.length, 'one entry per line, no duplicates');
251
+ });
252
+ });
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+ // S2 (opencode-usage-alert): the LIFECYCLE of the peak row's one timer, written against the
3
+ // independent verification of `c41914c` — the timer reaches the window boundary and stops there
4
+ // (a fired timer at the exact off-peak instant must already show no row), the re-arm skips the
5
+ // weekend because the schedule does, and a fetch that settles after its session ended can neither
6
+ // arm a timer nor speak for the session that replaced it.
7
+ //
8
+ // The clock and the timer table are both injected, so the cases are deterministic: `advance` fires
9
+ // every armed timer in order and moves the clock exactly to its instant, which is what a real
10
+ // boundary would do.
11
+ const assert = require('node:assert/strict');
12
+ const { test } = require('node:test');
13
+ const os = require('node:os');
14
+ const { loadExtension, BRIDGE_SLOT, defaultBridge } = require('./fixtures/load-extension.js');
15
+
16
+ const FRIDAY_END = Date.parse('2026-11-27T10:00:00Z');
17
+ const MONDAY_START = Date.parse('2026-11-30T01:00:00Z');
18
+ const PEAK = FRIDAY_END - 5000;
19
+ const WIDGET = 'opencode-go-peak-widget';
20
+ const reply = () => ({ ok: true, json: async () => ({ usage: Object.fromEntries(
21
+ ['rolling', 'weekly', 'monthly'].map((name) => [name, {
22
+ status: 'ok', percent: 25, resetsAt: '2026-11-30T11:25:00Z',
23
+ }]),
24
+ ) }) });
25
+
26
+ async function fixture(t) {
27
+ const previous = [globalThis[BRIDGE_SLOT], Date.now, setTimeout, clearTimeout];
28
+ t.after(() => { [globalThis[BRIDGE_SLOT], Date.now, global.setTimeout, global.clearTimeout] = previous; });
29
+ // The rows are Off until the human says On, so this suite turns DeepSeek's switch on: what it
30
+ // tests is the timer, not the default.
31
+ const bridge = defaultBridge();
32
+ bridge.api.createStore = () => ({
33
+ get: (key, fallback) => (key === 'alerts' ? { peaks: { deepseek: true } } : fallback),
34
+ set: () => {},
35
+ delete: () => {},
36
+ });
37
+ globalThis[BRIDGE_SLOT] = bridge.api;
38
+ const sources = [];
39
+ const { hooks } = await loadExtension({ events: { emit(name, payload) {
40
+ if (name === 'gentle-pi:usage-source/v1') sources.push(payload);
41
+ } } }, { gh: false });
42
+ let now = PEAK;
43
+ const timers = new Set();
44
+ Date.now = () => now;
45
+ global.setTimeout = (fire, delay) => {
46
+ const timer = { fire, at: now + delay, detached: false, unref() { this.detached = true; return this; } };
47
+ timers.add(timer);
48
+ return timer;
49
+ };
50
+ global.clearTimeout = (timer) => timers.delete(timer);
51
+ const alerts = () => [...timers].filter((timer) => timer.detached);
52
+ const rows = new Map();
53
+ const ctx = { cwd: os.tmpdir(), hasUI: true, ui: {
54
+ notify() {},
55
+ setWidget(key, content) { if (content === undefined) rows.delete(key); else rows.set(key, content); },
56
+ } };
57
+ const event = async (name) => { for (const [type, handler] of hooks) if (type === name) await handler({}, ctx); };
58
+ const advance = (until) => {
59
+ for (;;) {
60
+ const timer = alerts().sort((a, b) => a.at - b.at)[0];
61
+ if (timer === undefined || timer.at > until) break;
62
+ timers.delete(timer);
63
+ now = timer.at;
64
+ timer.fire();
65
+ }
66
+ now = until;
67
+ };
68
+ await event('session_start');
69
+ return { alerts, rows, advance, event, source: () => sources.at(-1) };
70
+ }
71
+
72
+ test('S2: the only unref timer fires at the boundary and skips the weekend', async (t) => {
73
+ const f = await fixture(t);
74
+ assert.ok(await f.source().fetch('probe', reply, PEAK));
75
+ assert.equal(f.rows.has(WIDGET), true);
76
+ assert.deepEqual(f.alerts().map(({ at }) => at), [FRIDAY_END]);
77
+ f.advance(FRIDAY_END);
78
+ assert.equal(f.rows.has(WIDGET), false);
79
+ assert.deepEqual(f.alerts().map(({ at }) => at), [MONDAY_START]);
80
+ f.advance(MONDAY_START);
81
+ assert.equal(f.rows.has(WIDGET), true);
82
+ await f.event('session_shutdown');
83
+ assert.deepEqual(f.alerts(), []);
84
+ assert.equal(f.rows.has(WIDGET), false);
85
+ });
86
+
87
+ for (const replacement of [false, true]) {
88
+ test(`S2: a late reply cannot revive a stopped session (replacement: ${replacement})`, async (t) => {
89
+ const f = await fixture(t);
90
+ let deliver;
91
+ const stale = f.source().fetch('previous-key', () => new Promise((resolve) => { deliver = resolve; }), PEAK);
92
+ await f.event('session_shutdown');
93
+ if (replacement) {
94
+ await f.event('session_start');
95
+ assert.equal(await f.source().fetch('', () => assert.fail('missing key must not fetch'), PEAK), undefined);
96
+ }
97
+ deliver(reply());
98
+ assert.ok(await stale, 'the old caller still gets its snapshot');
99
+ if (!replacement) {
100
+ assert.equal(f.rows.has(WIDGET), false);
101
+ assert.deepEqual(f.alerts(), []);
102
+ return;
103
+ }
104
+ // The replacement session owns its own row and its own timer — the switch and the window are
105
+ // its gates, not the key of the session that ended. What the late answer must NOT do is add a
106
+ // second timer or change what that row says.
107
+ assert.equal(f.alerts().length, 1, 'one timer, the running session\'s own');
108
+ assert.equal(f.rows.get(WIDGET).length, 1, 'one row, unchanged by the late answer');
109
+ });
110
+ }