pi-odd-worktree 3.14.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.
@@ -0,0 +1,196 @@
1
+ 'use strict';
2
+ // S5/S7/S8 (opencode-usage-alert): the `Alert` page of `/gentle:customize`. It carries one
3
+ // Off/On pair PER provider the peak registry declares, in the registry's declaration order,
4
+ // under each provider's own setting label (`Deepseek peak`, then `Claude peak`). Each line
5
+ // reads and writes the boolean `lib/alert-mode.js` owns for that provider id, and a
6
+ // successful change applies to the RUNNING session at once — no `/reload`, so nothing says
7
+ // "restart". Pure over the injected bridge and callbacks; nothing here loads the extension.
8
+ const { test, describe } = require('node:test');
9
+ const assert = require('node:assert/strict');
10
+
11
+ const alertMode = require('../lib/alert-mode.js');
12
+ const alertRows = require('../lib/alert-rows.js');
13
+ const { PROVIDERS } = require('../lib/peak-providers.js');
14
+
15
+ // A bridge whose `createStore` keeps one in-memory file per plugin id, like the real one.
16
+ function fakeBridge(initial = {}) {
17
+ const files = new Map(Object.entries(initial));
18
+ const writes = [];
19
+ const createStore = (id) => ({
20
+ get: (key, fallback) => (files.get(id)?.[key] !== undefined ? files.get(id)[key] : fallback),
21
+ set: (key, value) => {
22
+ files.set(id, { ...(files.get(id) ?? {}), [key]: value });
23
+ writes.push([id, key, value]);
24
+ },
25
+ });
26
+ return { api: { createStore }, files, writes };
27
+ }
28
+
29
+ // The rows of one provider's pair: Off first, then On, both under the provider's setting.
30
+ function pairOf(rows, setting) {
31
+ return rows.filter((row) => row.choice.setting === setting);
32
+ }
33
+
34
+ function stored(value = {}) {
35
+ return fakeBridge({ 'odd-worktree': { alerts: { peaks: value } } });
36
+ }
37
+
38
+ function provider(api, hooks = {}) {
39
+ const calls = { notify: [], onChange: [] };
40
+ const rows = alertRows.alertRowsProvider({
41
+ api,
42
+ notify: (text) => {
43
+ calls.notify.push(text);
44
+ if (hooks.notify) hooks.notify(text);
45
+ },
46
+ onChange: () => {
47
+ calls.onChange.push(true);
48
+ if (hooks.onChange) hooks.onChange();
49
+ },
50
+ });
51
+ return { provider: rows, calls, rows: (ctx = {}) => rows.rows(ctx) };
52
+ }
53
+
54
+ describe('the Alert page', () => {
55
+ test('is one provider, named, on a page of its own, placed right after Notifications', () => {
56
+ const { provider: page } = provider(fakeBridge().api);
57
+ assert.deepEqual(Object.keys(page).sort(), ['category', 'categoryPlacement', 'id', 'rows']);
58
+ assert.equal(page.id, 'odd-worktree.alert.peak');
59
+ assert.equal(page.category, 'Alert');
60
+ assert.deepEqual(page.categoryPlacement, { after: 'Notifications' });
61
+ });
62
+
63
+ test('carries exactly one Off/On pair per registry entry, in declaration order, with its own label', () => {
64
+ const { rows } = provider(fakeBridge().api);
65
+ const built = rows();
66
+ assert.equal(PROVIDERS.length > 0, true, 'the registry declares at least one provider');
67
+ assert.deepEqual(
68
+ built.map((row) => [row.choice.setting, row.choice.value]),
69
+ PROVIDERS.flatMap((entry) => [[entry.setting, 'Off'], [entry.setting, 'On']]),
70
+ );
71
+ // The registry's documented shape: DeepSeek first, Claude second, each under its setting.
72
+ assert.deepEqual(PROVIDERS.map((entry) => entry.id), ['deepseek', 'claude']);
73
+ assert.deepEqual(PROVIDERS.map((entry) => entry.setting), ['Deepseek peak', 'Claude peak']);
74
+ for (const row of built) {
75
+ assert.equal(row.category, 'Alert');
76
+ assert.equal(typeof row.label, 'function');
77
+ assert.equal(typeof row.action, 'function');
78
+ }
79
+ });
80
+
81
+ test('labels each pair with its provider\'s setting, not with a fixed name', () => {
82
+ const built = provider(fakeBridge().api).rows();
83
+ for (const entry of PROVIDERS) {
84
+ const pair = pairOf(built, entry.setting);
85
+ assert.equal(pair.length, 2, entry.setting);
86
+ assert.deepEqual(pair.map((row) => row.choice.value), ['Off', 'On'], entry.setting);
87
+ for (const row of pair) assert.equal(row.label(), entry.setting);
88
+ }
89
+ });
90
+ });
91
+
92
+ describe('the current value', () => {
93
+ test('is Off for every provider on a first run, and follows each provider\'s own switch', () => {
94
+ const fresh = provider(fakeBridge().api).rows();
95
+ for (const entry of PROVIDERS) {
96
+ assert.deepEqual(pairOf(fresh, entry.setting).map((row) => row.choice.current()), [true, false], entry.setting);
97
+ }
98
+ for (const entry of PROVIDERS) {
99
+ const built = provider(stored({ [entry.id]: true }).api).rows();
100
+ const pair = pairOf(built, entry.setting);
101
+ assert.deepEqual(pair.map((row) => row.choice.current()), [false, true], entry.setting);
102
+ // Every other provider is untouched by that one provider's value.
103
+ for (const sibling of PROVIDERS.filter((other) => other.id !== entry.id)) {
104
+ assert.deepEqual(
105
+ pairOf(built, sibling.setting).map((row) => row.choice.current()),
106
+ [true, false],
107
+ `${entry.id} vs ${sibling.id}`,
108
+ );
109
+ }
110
+ }
111
+ });
112
+
113
+ test('is read live: a value changed between two builds is reflected', () => {
114
+ const bridge = fakeBridge();
115
+ const { rows } = provider(bridge.api);
116
+ const target = PROVIDERS[0];
117
+ const sibling = PROVIDERS[1];
118
+ assert.deepEqual(pairOf(rows(), target.setting).map((row) => row.choice.current()), [true, false]);
119
+ alertMode.writePeakAlert(bridge.api, target.id, true);
120
+ assert.deepEqual(pairOf(rows(), target.setting).map((row) => row.choice.current()), [false, true]);
121
+ assert.deepEqual(pairOf(rows(), sibling.setting).map((row) => row.choice.current()), [true, false]);
122
+ alertMode.writePeakAlert(bridge.api, target.id, false);
123
+ assert.deepEqual(pairOf(rows(), target.setting).map((row) => row.choice.current()), [true, false]);
124
+ });
125
+ });
126
+
127
+ describe('choosing a value', () => {
128
+ test('persists that provider\'s id, then applies it to the running session once', async () => {
129
+ const bridge = fakeBridge();
130
+ const { rows, calls } = provider(bridge.api);
131
+ const target = PROVIDERS[0];
132
+ await pairOf(rows(), target.setting)[1].action();
133
+ assert.deepEqual(bridge.files.get('odd-worktree'), { alerts: { peaks: { [target.id]: true } } });
134
+ assert.equal(calls.onChange.length, 1);
135
+ assert.equal(alertMode.readPeakAlert(bridge.api, target.id), true);
136
+ await pairOf(rows(), target.setting)[0].action();
137
+ assert.deepEqual(bridge.files.get('odd-worktree'), { alerts: { peaks: { [target.id]: false } } });
138
+ assert.equal(calls.onChange.length, 2);
139
+ assert.equal(alertMode.readPeakAlert(bridge.api, target.id), false);
140
+ });
141
+
142
+ test('a second provider\'s line writes only its own id and leaves its siblings alone', async () => {
143
+ const bridge = stored({});
144
+ const { rows, calls } = provider(bridge.api);
145
+ await pairOf(rows(), PROVIDERS[0].setting)[1].action();
146
+ await pairOf(rows(), PROVIDERS[1].setting)[1].action();
147
+ assert.deepEqual(bridge.files.get('odd-worktree'), {
148
+ alerts: { peaks: { [PROVIDERS[0].id]: true, [PROVIDERS[1].id]: true } },
149
+ });
150
+ assert.equal(calls.onChange.length, 2);
151
+ await pairOf(rows(), PROVIDERS[0].setting)[0].action();
152
+ assert.equal(alertMode.readPeakAlert(bridge.api, PROVIDERS[0].id), false);
153
+ assert.equal(alertMode.readPeakAlert(bridge.api, PROVIDERS[1].id), true);
154
+ });
155
+
156
+ test('keeps the other keys of the store', async () => {
157
+ const bridge = fakeBridge({ 'odd-worktree': { modules: { codegraph: false } } });
158
+ await provider(bridge.api).rows()[0].action();
159
+ assert.deepEqual(bridge.files.get('odd-worktree'), {
160
+ modules: { codegraph: false },
161
+ alerts: { peaks: { [PROVIDERS[0].id]: false } },
162
+ });
163
+ });
164
+
165
+ test('says nothing: these switches need no reload, so no restart notice is printed', async () => {
166
+ const bridge = fakeBridge();
167
+ const { rows, calls } = provider(bridge.api);
168
+ for (const row of rows()) await row.action();
169
+ assert.deepEqual(calls.notify, []);
170
+ });
171
+ });
172
+
173
+ describe('a write the store refuses', () => {
174
+ test('is thrown per provider so the menu reports it, and nothing is told it changed', async () => {
175
+ const api = { createStore: () => ({ get: (_key, fallback) => fallback, set: () => { throw new Error('read-only'); } }) };
176
+ const { rows, calls } = provider(api);
177
+ for (const entry of PROVIDERS) {
178
+ const pair = pairOf(rows(), entry.setting);
179
+ await assert.rejects(async () => pair[0].action(), new RegExp(`^Error: ${entry.setting} could not be saved$`), entry.setting);
180
+ await assert.rejects(async () => pair[1].action(), new RegExp(`^Error: ${entry.setting} could not be saved$`), entry.setting);
181
+ }
182
+ assert.deepEqual(calls.onChange, []);
183
+ });
184
+
185
+ test('is thrown for a host with no store at all, and still calls nothing', async () => {
186
+ const { rows, calls } = provider(undefined);
187
+ await assert.rejects(async () => rows()[0].action(), /could not be saved$/);
188
+ assert.deepEqual(calls.onChange, []);
189
+ });
190
+
191
+ test('leaves the stored value reading Off, the way it read before the press', async () => {
192
+ const api = { createStore: () => ({ get: (_key, fallback) => fallback, set: () => { throw new Error('read-only'); } }) };
193
+ await assert.rejects(async () => provider(api).rows()[1].action(), /could not be saved$/);
194
+ assert.equal(alertMode.readPeakAlert(api, PROVIDERS[0].id), false);
195
+ });
196
+ });
@@ -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
+ }