claude-instance-manager 0.0.0-stage → 1.0.1

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,336 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const vm = require('vm');
6
+
7
+ class Element {
8
+ constructor() {
9
+ this.children = [];
10
+ this.attributes = {};
11
+ this.className = '';
12
+ this.text = '';
13
+ this.listeners = {};
14
+ this.dataset = {};
15
+ }
16
+
17
+ set textContent(value) {
18
+ this.text = String(value);
19
+ this.children = [];
20
+ }
21
+
22
+ get textContent() {
23
+ return this.text + this.children.map(child => child.textContent).join('');
24
+ }
25
+
26
+ append(...children) {
27
+ this.children.push(...children);
28
+ }
29
+
30
+ replaceChildren(...children) {
31
+ this.text = '';
32
+ this.children = children;
33
+ }
34
+
35
+ setAttribute(name, value) {
36
+ this.attributes[name] = value;
37
+ }
38
+
39
+ addEventListener(type, callback) {
40
+ this.listeners[type] = callback;
41
+ }
42
+
43
+ click() {
44
+ if (!this.disabled && this.listeners.click) this.listeners.click();
45
+ }
46
+
47
+ showModal() {
48
+ this.open = true;
49
+ }
50
+
51
+ close() {
52
+ this.open = false;
53
+ if (this.listeners.close) this.listeners.close();
54
+ }
55
+
56
+ focus() {
57
+ this.focused = true;
58
+ }
59
+
60
+ querySelectorAll(selector) {
61
+ const matches = [];
62
+ for (const child of this.children) {
63
+ if (child.className.split(' ').includes(selector.slice(1))) matches.push(child);
64
+ matches.push(...child.querySelectorAll(selector));
65
+ }
66
+ return matches;
67
+ }
68
+ }
69
+
70
+ function createRenderer() {
71
+ const ids = ['list', 'instanceDetail', 'accInput', 'newInstanceDialog', 'newInstanceButton', 'cancelInstanceButton', 'formMessage', 'stateMessage', 'instanceCount', 'runningCount', 'installState', 'installDot', 'refreshNote', 'addForm'];
72
+ const elements = Object.fromEntries(ids.map(id => [id, new Element()]));
73
+ const pending = [];
74
+ const deletions = [];
75
+ const launches = [];
76
+ const storage = {};
77
+ const documentListeners = {};
78
+ let interval;
79
+ const document = {
80
+ getElementById: id => elements[id],
81
+ addEventListener: (type, callback) => { documentListeners[type] = callback; },
82
+ createElement: () => new Element(),
83
+ createTextNode: text => {
84
+ const element = new Element();
85
+ element.textContent = text;
86
+ return element;
87
+ }
88
+ };
89
+ const sandbox = {
90
+ document,
91
+ localStorage: { getItem: key => storage[key] || null, setItem: (key, value) => { storage[key] = value; } },
92
+ window: { claudeManager: {
93
+ getInstanceState: () => new Promise((resolve, reject) => pending.push({ resolve, reject })),
94
+ deleteInstance: id => new Promise((resolve, reject) => deletions.push({ id, resolve, reject })),
95
+ launch: id => launches.push(id)
96
+ } },
97
+ console: { error: () => {} },
98
+ setInterval: callback => { interval = callback; },
99
+ setTimeout: () => {}
100
+ };
101
+ const html = fs.readFileSync(path.join(__dirname, '..', 'index.html'), 'utf8');
102
+ vm.runInNewContext(html.match(/<script>([\s\S]*?)<\/script>/)[1], sandbox);
103
+ return { elements, pending, deletions, launches, storage, interval, documentListeners };
104
+ }
105
+
106
+ test('shows only the selected instance local usage and explains missing data and errors', async () => {
107
+ const { elements, pending, interval } = createRenderer();
108
+ const state = {
109
+ installed: true,
110
+ instances: [{ id: 'Work', name: 'Work' }],
111
+ running: { defaultRunning: false, instances: [] },
112
+ usage: {
113
+ default: { history: { recordedAt: 1000, metrics: { 'Five-hour': 35, 'Weekly all models': 120 },
114
+ resets: { 'Five-hour': { resetAt: '2026-12-05T20:00:00Z', cachedAt: 2000 } } }, error: false },
115
+ managed: [{ id: 'work', history: null, error: false }]
116
+ }
117
+ };
118
+ pending[0].resolve(state);
119
+ await new Promise(setImmediate);
120
+ assert.match(elements.instanceDetail.textContent, /Five-hour35%/);
121
+ assert.match(elements.instanceDetail.textContent, /Weekly all models120%/);
122
+ assert.match(elements.instanceDetail.textContent, /previously signed-in account/);
123
+ assert.match(elements.instanceDetail.textContent, /Cached reset times may be stale/);
124
+ const resetNotes = elements.instanceDetail.querySelectorAll('.usage-reset');
125
+ assert.match(resetNotes[0].textContent, /Cached reset:.*cached/);
126
+ assert.ok(resetNotes[0].textContent.includes(new Date('2026-12-05T20:00:00Z').toLocaleString()));
127
+ assert.equal(resetNotes[1].textContent, 'Reset time unavailable in local cache.');
128
+ const bars = elements.instanceDetail.querySelectorAll('.usage-bar');
129
+ assert.equal(bars.length, 2);
130
+ assert.equal(bars[0].value, 35);
131
+ assert.equal(bars[0].max, 100);
132
+ assert.equal(bars[0].attributes['aria-label'], 'Five-hour usage');
133
+ assert.equal(bars[1].value, 100);
134
+ assert.equal(bars[1].attributes['aria-valuetext'], '120% used');
135
+ elements.list.querySelectorAll('.instance-row').find(row => row.dataset.instanceKey === 'work').click();
136
+ assert.match(elements.instanceDetail.textContent, /No local usage history/);
137
+ assert.doesNotMatch(elements.instanceDetail.textContent, /35%/);
138
+ interval();
139
+ pending[1].resolve({ ...state, usage: { ...state.usage, managed: [{ id: 'work', history: null, error: true }] } });
140
+ await new Promise(setImmediate);
141
+ assert.match(elements.instanceDetail.textContent, /Could not read local usage history/);
142
+ });
143
+
144
+ test('Ctrl+N opens the instance dialog without resetting it or intercepting other shortcuts', () => {
145
+ const { elements, documentListeners } = createRenderer();
146
+ const press = overrides => {
147
+ let prevented = false;
148
+ documentListeners.keydown({
149
+ key: 'n', ctrlKey: true, altKey: false, metaKey: false, shiftKey: false,
150
+ isComposing: false, repeat: false,
151
+ ...overrides,
152
+ preventDefault: () => { prevented = true; }
153
+ });
154
+ return prevented;
155
+ };
156
+
157
+ assert.equal(press(), true);
158
+ assert.equal(elements.newInstanceDialog.open, true);
159
+ elements.accInput.value = 'Draft';
160
+ assert.equal(press({ key: 'N' }), true);
161
+ assert.equal(elements.accInput.value, 'Draft');
162
+ elements.newInstanceDialog.close();
163
+ assert.equal(press({ shiftKey: true }), false);
164
+ assert.equal(press({ altKey: true }), false);
165
+ assert.equal(press({ isComposing: true }), false);
166
+ assert.equal(press({ key: 'm' }), false);
167
+ assert.equal(press({ repeat: true }), true);
168
+ assert.equal(elements.newInstanceDialog.open, false);
169
+ });
170
+
171
+ test('creates an instance only after confirming a valid name in the dialog', async () => {
172
+ const { elements, pending, storage } = createRenderer();
173
+ pending[0].resolve({ installed: true, instances: [], running: { defaultRunning: false, instances: [] } });
174
+ await new Promise(setImmediate);
175
+ assert.match(elements.instanceDetail.textContent, /Existing Claude Desktop instance/);
176
+
177
+ const submit = () => elements.addForm.listeners.submit({ preventDefault() {} });
178
+ elements.newInstanceButton.click();
179
+ assert.equal(elements.newInstanceDialog.open, true);
180
+ elements.accInput.value = 'invalid/name';
181
+ submit();
182
+ assert.equal(elements.newInstanceDialog.open, true);
183
+ assert.match(elements.formMessage.textContent, /instance name.*invalid characters/);
184
+ elements.accInput.value = 'Work';
185
+ submit();
186
+ assert.match(elements.formMessage.textContent, /instance.*already exists/);
187
+
188
+ elements.accInput.value = ' Creative ';
189
+ submit();
190
+ assert.equal(elements.newInstanceDialog.open, false);
191
+ assert.deepEqual(JSON.parse(storage.claude_profiles), ['Personal', 'Work', 'Creative']);
192
+ assert.match(elements.instanceDetail.textContent, /Creative/);
193
+ assert.equal(elements.accInput.value, '');
194
+
195
+ elements.newInstanceButton.click();
196
+ elements.accInput.value = 'Unconfirmed';
197
+ elements.cancelInstanceButton.click();
198
+ assert.equal(elements.newInstanceDialog.open, false);
199
+ assert.equal(elements.accInput.value, '');
200
+ assert.equal(elements.newInstanceButton.focused, true);
201
+ assert.deepEqual(JSON.parse(storage.claude_profiles), ['Personal', 'Work', 'Creative']);
202
+ });
203
+
204
+ test('shows initial loading but refreshes existing statuses quietly', async () => {
205
+ const { elements, pending, interval } = createRenderer();
206
+
207
+ let statuses = elements.list.querySelectorAll('.status');
208
+ assert.equal(statuses[0].textContent, 'Checking status…');
209
+ assert.equal(statuses[0].children[0].className, 'dot loading');
210
+ assert.equal(elements.list.attributes['aria-busy'], 'true');
211
+ assert.equal(elements.instanceDetail.querySelectorAll('.status')[0].textContent, 'Checking status…');
212
+ assert.equal(elements.runningCount.textContent, '—');
213
+
214
+ const runningState = { installed: true, instances: [], running: { defaultRunning: true, instances: [] } };
215
+ pending[0].resolve(runningState);
216
+ await new Promise(setImmediate);
217
+ statuses = elements.list.querySelectorAll('.status');
218
+ assert.equal(statuses[0].textContent, 'Running');
219
+ assert.equal(elements.instanceDetail.querySelectorAll('.status')[0].textContent, 'Running');
220
+ assert.equal(elements.runningCount.textContent, '1');
221
+ assert.equal(elements.list.attributes['aria-busy'], 'false');
222
+
223
+ const previousStatus = statuses[0];
224
+ const previousDetail = elements.instanceDetail.querySelectorAll('.status')[0];
225
+ interval();
226
+ statuses = elements.list.querySelectorAll('.status');
227
+ assert.equal(statuses[0], previousStatus);
228
+ assert.equal(statuses[0].textContent, 'Running');
229
+ assert.equal(elements.instanceDetail.querySelectorAll('.status')[0].textContent, 'Running');
230
+ assert.equal(elements.runningCount.textContent, '1');
231
+ assert.equal(elements.list.attributes['aria-busy'], 'false');
232
+
233
+ pending[1].resolve({ ...runningState });
234
+ await new Promise(setImmediate);
235
+ assert.equal(elements.list.querySelectorAll('.status')[0], previousStatus);
236
+ assert.equal(elements.instanceDetail.querySelectorAll('.status')[0], previousDetail);
237
+
238
+ interval();
239
+ assert.equal(elements.list.querySelectorAll('.status')[0].textContent, 'Running');
240
+ pending[2].resolve({ ...runningState, running: { defaultRunning: false, instances: [] } });
241
+ await new Promise(setImmediate);
242
+ assert.equal(elements.list.querySelectorAll('.status')[0].textContent, 'Not running');
243
+ assert.equal(elements.runningCount.textContent, '0');
244
+
245
+ interval();
246
+ pending[3].reject(new Error('status check failed'));
247
+ await new Promise(setImmediate);
248
+ statuses = elements.list.querySelectorAll('.status');
249
+ assert.equal(statuses[0].textContent, 'Status unavailable');
250
+ assert.equal(elements.installState.textContent, 'Claude installed');
251
+ assert.equal(elements.list.attributes['aria-busy'], 'false');
252
+ assert.match(elements.stateMessage.textContent, /Could not load local instances/);
253
+ });
254
+
255
+ test('retries quietly after an initial status error', async () => {
256
+ const { elements, pending, interval } = createRenderer();
257
+ pending[0].reject(new Error('status check failed'));
258
+ await new Promise(setImmediate);
259
+ assert.equal(elements.list.querySelectorAll('.status')[0].textContent, 'Status unavailable');
260
+ interval();
261
+ assert.equal(elements.list.querySelectorAll('.status')[0].textContent, 'Status unavailable');
262
+ assert.equal(elements.list.attributes['aria-busy'], 'false');
263
+ pending[1].resolve({ installed: true, instances: [], running: { defaultRunning: true, instances: [] } });
264
+ await new Promise(setImmediate);
265
+ assert.equal(elements.list.querySelectorAll('.status')[0].textContent, 'Running');
266
+ });
267
+
268
+ test('sidebar selects the instance for opening and hiding without deleting its data', async () => {
269
+ const { elements, pending, deletions, launches, storage, interval } = createRenderer();
270
+ pending[0].resolve({ installed: true, instances: [{ id: 'Work', name: 'Work' }], running: { defaultRunning: false, instances: ['work'] } });
271
+ await new Promise(setImmediate);
272
+ const selectWork = () => elements.list.querySelectorAll('.instance-row').find(row => row.dataset.instanceKey === 'work').click();
273
+ selectWork();
274
+ assert.match(elements.instanceDetail.textContent, /Work/);
275
+ assert.equal(elements.instanceDetail.querySelectorAll('.status')[0].textContent, 'Running');
276
+ elements.instanceDetail.querySelectorAll('.open')[0].click();
277
+ assert.deepEqual(launches, ['Work']);
278
+
279
+ interval();
280
+ pending[1].reject(new Error('status check failed'));
281
+ await new Promise(setImmediate);
282
+ assert.match(elements.instanceDetail.textContent, /Work/);
283
+ assert.equal(elements.instanceDetail.querySelectorAll('.status')[0].textContent, 'Status unavailable');
284
+
285
+ elements.instanceDetail.querySelectorAll('.hide')[0].click();
286
+ assert.equal(deletions.length, 0);
287
+ assert.deepEqual(JSON.parse(storage.claude_hidden_profiles), ['work']);
288
+ assert.match(elements.instanceDetail.textContent, /Default/);
289
+
290
+ elements.newInstanceButton.click();
291
+ elements.accInput.value = 'Work';
292
+ elements.addForm.listeners.submit({ preventDefault() {} });
293
+ assert.match(elements.instanceDetail.textContent, /Work/);
294
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete').length, 1);
295
+ });
296
+
297
+ test('deletes only confirmed instances and ignores stale instance refreshes', async () => {
298
+ const { elements, pending, deletions, storage, interval } = createRenderer();
299
+ const existing = { installed: true, instances: [{ id: 'Work', name: 'Work' }], running: { defaultRunning: false, instances: [] } };
300
+ pending[0].resolve(existing);
301
+ await new Promise(setImmediate);
302
+
303
+ const rows = elements.list.querySelectorAll('.instance-row');
304
+ assert.equal(rows[0].attributes['aria-pressed'], 'true');
305
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete').length, 0);
306
+ rows.find(row => row.dataset.instanceKey === 'work').click();
307
+ assert.match(elements.instanceDetail.textContent, /Work/);
308
+ assert.equal(elements.list.querySelectorAll('.instance-row').find(row => row.dataset.instanceKey === 'work').attributes['aria-pressed'], 'true');
309
+ let buttons = elements.instanceDetail.querySelectorAll('.delete');
310
+ assert.equal(buttons.length, 1);
311
+ assert.equal(buttons[0].attributes['aria-label'], 'Delete Work');
312
+ buttons[0].click();
313
+ assert.equal(deletions[0].id, 'Work');
314
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete')[0].disabled, true);
315
+ deletions[0].resolve('cancelled');
316
+ await new Promise(setImmediate);
317
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete').length, 1);
318
+ assert.equal(pending.length, 1);
319
+
320
+ elements.instanceDetail.querySelectorAll('.delete')[0].click();
321
+ interval();
322
+ assert.equal(pending.length, 2);
323
+ deletions[1].resolve('deleted');
324
+ await new Promise(setImmediate);
325
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete').length, 0);
326
+ assert.match(elements.instanceDetail.textContent, /Default/);
327
+ assert.deepEqual(JSON.parse(storage.claude_profiles), ['Personal']);
328
+
329
+ pending[1].resolve({ ...existing, instances: [{ id: 'Work', name: 'Work' }] });
330
+ await new Promise(setImmediate);
331
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete').length, 0);
332
+ assert.equal(pending.length, 3);
333
+ pending[2].resolve({ ...existing, instances: [] });
334
+ await new Promise(setImmediate);
335
+ assert.equal(elements.instanceDetail.querySelectorAll('.delete').length, 0);
336
+ });
@@ -0,0 +1,127 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const vm = require('vm');
7
+ const { execFileSync } = require('child_process');
8
+
9
+ function runShortcut({ platform = 'win32', electronExists = true, failure, action = 'create-shortcut', execute, electron = 'C:\\Program Files\\Manager\\electron.exe' } = {}) {
10
+ const calls = [];
11
+ const logs = [];
12
+ const errors = [];
13
+ const process = { platform, env: { ...globalThis.process.env, APPDATA: 'C:\\Instances' }, argv: ['node', 'cli.js', action], exitCode: 0 };
14
+ const childProcess = {
15
+ execFileSync: (...args) => {
16
+ calls.push(args);
17
+ if (failure) throw failure;
18
+ if (execute) return execute(...args);
19
+ return 'Created shortcut: Desktop\\Claude Instance Manager.lnk\n';
20
+ }
21
+ };
22
+ const sandbox = {
23
+ require: id => id === 'electron' ? electron : id === 'fs' ? { existsSync: () => electronExists } :
24
+ id === 'child_process' ? childProcess : id === './instances' || id === './wipe' ? {} : require(id),
25
+ process,
26
+ console: { log: message => logs.push(message), error: message => errors.push(message) },
27
+ __dirname: path.resolve(__dirname, '..')
28
+ };
29
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, '..', 'cli.js'), 'utf8'), sandbox);
30
+ return { calls, logs, errors, process, electron, directory: sandbox.__dirname };
31
+ }
32
+
33
+ test('creates a shortcut pointing to Electron and the launcher', () => {
34
+ const result = runShortcut();
35
+ assert.equal(result.calls.length, 1);
36
+ const [command, args, options] = result.calls[0];
37
+ assert.equal(command, 'powershell.exe');
38
+ assert.deepEqual(Array.from(args.slice(0, 3)), ['-NoProfile', '-NonInteractive', '-Command']);
39
+ assert.equal(options.env.CLAUDE_INSTANCE_MANAGER_ELECTRON, result.electron);
40
+ assert.equal(options.env.CLAUDE_INSTANCE_MANAGER_MAIN, path.join(result.directory, 'main.js'));
41
+ assert.equal(options.env.CLAUDE_INSTANCE_MANAGER_DIRECTORY, result.directory);
42
+ assert.match(result.logs[0], /Created shortcut/);
43
+ });
44
+
45
+ test('reports unsupported platforms and missing Electron', () => {
46
+ for (const options of [{ platform: 'linux' }, { electronExists: false }]) {
47
+ const result = runShortcut(options);
48
+ assert.equal(result.calls.length, 0);
49
+ assert.equal(result.process.exitCode, 1);
50
+ assert.ok(result.errors.length);
51
+ }
52
+ });
53
+
54
+ test('reports shortcut creation failures', () => {
55
+ const result = runShortcut({ failure: Object.assign(new Error('failed'), { stderr: 'Access denied' }) });
56
+ assert.equal(result.process.exitCode, 1);
57
+ assert.match(result.errors[0], /Access denied/);
58
+ });
59
+
60
+ test('removal does not require the Electron executable to exist', () => {
61
+ const result = runShortcut({ action: 'remove-shortcut', electronExists: false });
62
+ assert.equal(result.process.exitCode, 0);
63
+ assert.equal(result.calls[0][2].env.CLAUDE_INSTANCE_MANAGER_SHORTCUT_ACTION, 'remove');
64
+ });
65
+
66
+ test('creates and removes only its own shortcut', { skip: process.platform !== 'win32' }, () => {
67
+ const desktop = fs.mkdtempSync(path.join(os.tmpdir(), 'claude shortcut test-'));
68
+ const shortcut = path.join(desktop, 'Claude Instance Manager.lnk');
69
+ const legacy = path.join(desktop, 'Claude Desktop Manager.lnk');
70
+ const execute = (command, args, options) => {
71
+ const script = args[3].replace("[Environment]::GetFolderPath('Desktop')", '$env:TEST_DESKTOP');
72
+ assert.notEqual(script, args[3]);
73
+ return execFileSync(command, [...args.slice(0, 3), script], {
74
+ ...options,
75
+ env: { ...options.env, TEST_DESKTOP: desktop },
76
+ stdio: ['ignore', 'pipe', 'pipe']
77
+ });
78
+ };
79
+
80
+ try {
81
+ let result = runShortcut({ execute });
82
+ assert.equal(result.process.exitCode, 0);
83
+ assert.ok(fs.existsSync(shortcut));
84
+ result = runShortcut({ execute });
85
+ assert.match(result.logs[0], /already exists/);
86
+
87
+ fs.renameSync(shortcut, legacy);
88
+ result = runShortcut({ execute });
89
+ assert.match(result.logs[0], /Updated shortcut/);
90
+ assert.ok(fs.existsSync(shortcut));
91
+ assert.equal(fs.existsSync(legacy), false);
92
+
93
+ result = runShortcut({ execute, action: 'remove-shortcut' });
94
+ assert.equal(result.process.exitCode, 0);
95
+ assert.match(result.logs[0], /Removed shortcut/);
96
+ assert.equal(fs.existsSync(shortcut), false);
97
+ result = runShortcut({ execute, action: 'remove-shortcut' });
98
+ assert.match(result.logs[0], /not found/);
99
+
100
+ result = runShortcut({ execute });
101
+ assert.equal(result.process.exitCode, 0);
102
+ fs.renameSync(shortcut, legacy);
103
+ result = runShortcut({ execute, action: 'remove-shortcut' });
104
+ assert.equal(result.process.exitCode, 0);
105
+ assert.equal(fs.existsSync(legacy), false);
106
+
107
+ result = runShortcut({ execute, electron: 'C:\\Other\\electron.exe' });
108
+ assert.equal(result.process.exitCode, 0);
109
+ const original = fs.readFileSync(shortcut);
110
+ result = runShortcut({ execute, action: 'remove-shortcut' });
111
+ assert.equal(result.process.exitCode, 1);
112
+ assert.match(result.errors[0], /different shortcut/);
113
+ assert.deepEqual(fs.readFileSync(shortcut), original);
114
+
115
+ fs.renameSync(shortcut, legacy);
116
+ result = runShortcut({ execute });
117
+ assert.equal(result.process.exitCode, 0);
118
+ assert.ok(fs.existsSync(shortcut));
119
+ assert.deepEqual(fs.readFileSync(legacy), original);
120
+ result = runShortcut({ execute, action: 'remove-shortcut' });
121
+ assert.equal(result.process.exitCode, 0);
122
+ assert.equal(fs.existsSync(shortcut), false);
123
+ assert.deepEqual(fs.readFileSync(legacy), original);
124
+ } finally {
125
+ fs.rmSync(desktop, { recursive: true, force: true });
126
+ }
127
+ });
@@ -0,0 +1,106 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const zlib = require('zlib');
7
+ const { readUsageHistory } = require('../usage');
8
+
9
+ test('reads the newest supported local sample without exposing account identifiers', async () => {
10
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-usage-test-'));
11
+ const file = path.join(dir, 'plan-usage-history.json');
12
+ try {
13
+ assert.equal(await readUsageHistory(dir), null);
14
+ fs.writeFileSync(file, JSON.stringify({
15
+ version: 2,
16
+ samples: [
17
+ { t: 2000, org: 'private-id', u: { fh: 35.5, sd: 62, sn: 5, unknown: 9 } },
18
+ { t: 1000, org: 'other-id', u: { fh: 1 } },
19
+ { t: 3000, org: 'private-id', u: { fh: 'invalid' } }
20
+ ]
21
+ }));
22
+ assert.deepEqual(await readUsageHistory(dir), {
23
+ recordedAt: 2000,
24
+ metrics: { 'Five-hour': 35.5, 'Weekly all models': 62, 'Weekly Sonnet': 5 }
25
+ });
26
+
27
+ fs.writeFileSync(file, JSON.stringify({ version: 1, samples: [{ t: 4000, fh: 7, sd: null }] }));
28
+ assert.deepEqual(await readUsageHistory(dir), { recordedAt: 4000, metrics: { 'Five-hour': 7 } });
29
+
30
+ fs.writeFileSync(file, JSON.stringify({ version: 3, samples: [] }));
31
+ await assert.rejects(readUsageHistory(dir), /Unsupported local usage history/);
32
+ fs.writeFileSync(file, '{');
33
+ await assert.rejects(readUsageHistory(dir), SyntaxError);
34
+ } finally {
35
+ fs.rmSync(dir, { recursive: true, force: true });
36
+ }
37
+ });
38
+
39
+ test('reads reset times only from matching recent cached usage responses', {
40
+ skip: typeof zlib.zstdCompressSync !== 'function' || typeof zlib.zstdDecompressSync !== 'function'
41
+ }, async () => {
42
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-usage-cache-test-'));
43
+ const cache = path.join(dir, 'Cache', 'Cache_Data');
44
+ const sampleTime = Date.now();
45
+ const reset = '2026-12-10T12:00:00Z';
46
+ fs.mkdirSync(cache, { recursive: true });
47
+
48
+ function writeEntry(name, organization, values, time) {
49
+ const key = Buffer.from(`1/0/https://claude.ai/api/organizations/${organization}/usage`);
50
+ const header = Buffer.alloc(24);
51
+ Buffer.from('305c72a71b6dfbfc', 'hex').copy(header);
52
+ header.writeUInt32LE(5, 8);
53
+ header.writeUInt32LE(key.length, 12);
54
+ const file = path.join(cache, name);
55
+ fs.writeFileSync(file, Buffer.concat([header, key, zlib.zstdCompressSync(Buffer.from(JSON.stringify(values)))]));
56
+ fs.utimesSync(file, new Date(time), new Date(time));
57
+ }
58
+
59
+ try {
60
+ fs.writeFileSync(path.join(dir, 'plan-usage-history.json'), JSON.stringify({
61
+ version: 2, samples: [{ t: sampleTime, org: 'account-a', u: { fh: 35, sd: 70 } }]
62
+ }));
63
+ writeEntry('aaaaaaaaaaaaaaaa_0', 'account-a', {
64
+ five_hour: { utilization: 35, resets_at: reset },
65
+ seven_day: { utilization: 99, resets_at: reset }
66
+ }, sampleTime);
67
+ writeEntry('bbbbbbbbbbbbbbbb_0', 'account-b', {
68
+ seven_day: { utilization: 70, resets_at: reset }
69
+ }, sampleTime + 1000);
70
+ writeEntry('cccccccccccccccc_0', 'account-a', {
71
+ seven_day: { utilization: 70, resets_at: reset }
72
+ }, sampleTime - 11 * 60 * 1000);
73
+ const history = await readUsageHistory(dir);
74
+ assert.equal(history.resets['Five-hour'].resetAt, reset);
75
+ assert.ok(Math.abs(history.resets['Five-hour'].cachedAt - sampleTime) < 1000);
76
+ assert.equal(history.resets['Weekly all models'], undefined);
77
+ assert.equal(history.org, undefined);
78
+
79
+ const badFile = path.join(cache, 'dddddddddddddddd_0');
80
+ writeEntry('dddddddddddddddd_0', 'account-a', {}, sampleTime);
81
+ const data = fs.readFileSync(badFile);
82
+ const frame = data.indexOf(Buffer.from('28b52ffd', 'hex'));
83
+ fs.writeFileSync(badFile, Buffer.concat([
84
+ data.subarray(0, frame),
85
+ zlib.zstdCompressSync(Buffer.from('sensitive-cache-marker'))
86
+ ]));
87
+ fs.utimesSync(badFile, new Date(sampleTime), new Date(sampleTime));
88
+ fs.writeFileSync(path.join(dir, 'plan-usage-history.json'), JSON.stringify({
89
+ version: 2, samples: [{ t: sampleTime + 1, org: 'account-a', u: { fh: 35, sd: 70 } }]
90
+ }));
91
+ const errors = [];
92
+ const originalError = console.error;
93
+ try {
94
+ console.error = (...args) => errors.push(args.join(' '));
95
+ const failed = await readUsageHistory(dir);
96
+ assert.equal(failed.resetError, true);
97
+ assert.equal(failed.metrics['Five-hour'], 35);
98
+ assert.equal(errors.length, 1);
99
+ assert.doesNotMatch(errors[0], /sensitive-cache-marker/);
100
+ } finally {
101
+ console.error = originalError;
102
+ }
103
+ } finally {
104
+ fs.rmSync(dir, { recursive: true, force: true });
105
+ }
106
+ });