From b95b62d8fa8ce5c19322a2df7364d479d5284006 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 10 Jul 2026 16:20:41 -0700 Subject: [PATCH] fix(cli): surface mDNS scan errors, robust spend-flow rollup + date label, harden tests Addresses T1 review: discovery.ts logs mDNS bind errors to stderr and returns already-found devices instead of masking failures as empty; spend-flow uses a collision-proof "other" sentinel and a local-date period label; the spend/date flags get friendly error handling; devices-json tests are deterministic (mocked discovery) and assert the read-only mutation guards. 13 tests green, tsc clean. Implemented by Codex gpt-5.5 (high); committed by Fable (git blocked in Codex sandbox). --- src/main.ts | 13 ++- src/sharing/discovery.ts | 10 +- src/spend-flow.ts | 9 +- tests/devices-json.test.ts | 129 ++++++++++++++++++--- tests/fixtures/mock-discovery-register.mjs | 38 ++++++ tests/spend-flow.test.ts | 65 ++++++++++- 6 files changed, 235 insertions(+), 29 deletions(-) create mode 100644 tests/fixtures/mock-discovery-register.mjs diff --git a/src/main.ts b/src/main.ts index 5c94f330..e26d2228 100644 --- a/src/main.ts +++ b/src/main.ts @@ -537,7 +537,7 @@ program program .command('share [action]') - .description("Securely share this device's usage with your other devices on the same network") + .description("Securely share this device's usage with your other devices. Actions: status. Supports --format json for status.") .option('--port ', 'Port to listen on', parseInteger, 7777) .option('--pair', 'Open a pairing window and print a PIN to add a new device') .option('--always', 'Keep sharing until stopped (default stops after 10 min idle)') @@ -567,7 +567,7 @@ program program .command('devices [action] [target]') - .description('Combined usage across your devices. Actions: add (find nearby & pair) | add --pin (manual) | rm ') + .description('Combined usage across your devices. Actions: scan | add (find nearby & pair) | add --pin (manual) | rm . Supports --format json for read-only output and scan.') .option('--pin ', 'Pairing PIN shown on the device you are adding') .option('-p, --period ', 'Period: today, week, 30days, month, all', 'month') .option('--port ', 'Default port when adding a device', parseInteger, 7777) @@ -1637,12 +1637,13 @@ program let range: DateRange if (opts.from || opts.to) { - const customRange = parseDateRangeFlags(opts.from, opts.to) - if (!customRange) { - process.stderr.write('codeburn: --from and --to must be valid YYYY-MM-DD dates\n') + try { + range = parseDateRangeFlags(opts.from, opts.to)! + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + console.error(`\n Error: ${message}\n`) process.exit(1) } - range = customRange } else { range = getDateRange(opts.period).range } diff --git a/src/sharing/discovery.ts b/src/sharing/discovery.ts index 13759b7f..e019a8c4 100644 --- a/src/sharing/discovery.ts +++ b/src/sharing/discovery.ts @@ -57,9 +57,15 @@ export function browse(timeoutMs = 2500): Promise { } } - bonjour = new Bonjour({}, () => finish([])) + const finishWithError = (err?: unknown) => { + if (err) console.error(`codeburn devices scan: mDNS discovery failed: ${err instanceof Error ? err.message : String(err)}`) + else console.error('codeburn devices scan: mDNS discovery failed') + finish([...found.values()]) + } + + bonjour = new Bonjour({}, finishWithError) const mdns = (bonjour as unknown as { server?: { mdns?: { on: (event: string, cb: () => void) => void } } }).server?.mdns - mdns?.on('error', () => finish([])) + mdns?.on('error', finishWithError) browser = bonjour.find({ type: SERVICE_TYPE }, (service) => { const txt = (service.txt ?? {}) as Record const fingerprint = txt['fp'] diff --git a/src/spend-flow.ts b/src/spend-flow.ts index 006602a3..3693dc4b 100644 --- a/src/spend-flow.ts +++ b/src/spend-flow.ts @@ -1,4 +1,5 @@ import { parseAllSessions } from './parser.js' +import { toDateString } from './daily-cache.js' import type { DateRange } from './types.js' export type SpendFlowNode = { id: string; label: string; cost: number } @@ -11,14 +12,10 @@ export type SpendFlow = { } const TOP_NODE_LIMIT = 8 -const OTHER_ID = 'other' - -function datePart(date: Date): string { - return date.toISOString().slice(0, 10) -} +const OTHER_ID = '__other__' function periodLabel(range: DateRange): string { - return `${datePart(range.start)} to ${datePart(range.end)}` + return `${toDateString(range.start)} to ${toDateString(range.end)}` } function addToMap(map: Map, key: K, cost: number): void { diff --git a/tests/devices-json.test.ts b/tests/devices-json.test.ts index 9bd08478..eb3b5d0c 100644 --- a/tests/devices-json.test.ts +++ b/tests/devices-json.test.ts @@ -3,10 +3,49 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { spawnSync } from 'node:child_process' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' -function runCli(args: string[], home: string) { - return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { +const DISCOVERY_MOCK_REGISTER = join(process.cwd(), 'tests', 'fixtures', 'mock-discovery-register.mjs') + +const bonjourMock = vi.hoisted(() => ({ + destroy: vi.fn((cb: () => void) => cb()), + find: vi.fn(), + mdnsOn: vi.fn(), + stop: vi.fn(), + serviceCallback: undefined as ((service: { + txt?: Record + addresses?: string[] + host?: string + name?: string + port: number + }) => void) | undefined, + errorCallback: undefined as ((err?: unknown) => void) | undefined, +})) + +vi.mock('bonjour-service', () => ({ + Bonjour: class { + server = { + mdns: { + on: bonjourMock.mdnsOn.mockImplementation((_event: string, cb: (err?: unknown) => void) => { + bonjourMock.errorCallback = cb + }), + }, + } + + destroy = bonjourMock.destroy + + find(_opts: unknown, cb: NonNullable) { + bonjourMock.serviceCallback = cb + bonjourMock.find(_opts, cb) + return { stop: bonjourMock.stop } + } + }, +})) + +function runCli(args: string[], home: string, opts: { mockDiscovery?: boolean } = {}) { + const nodeArgs = ['--import', 'tsx'] + if (opts.mockDiscovery) nodeArgs.push('--import', DISCOVERY_MOCK_REGISTER) + return spawnSync(process.execPath, [...nodeArgs, 'src/cli.ts', ...args], { cwd: process.cwd(), env: { ...process.env, @@ -45,6 +84,42 @@ function assistantLine(sessionId: string, timestamp: string, messageId: string): }) } +describe('sharing discovery', () => { + it('logs mDNS errors and returns devices found before the error', async () => { + vi.resetModules() + bonjourMock.destroy.mockClear() + bonjourMock.find.mockClear() + bonjourMock.mdnsOn.mockClear() + bonjourMock.stop.mockClear() + bonjourMock.serviceCallback = undefined + bonjourMock.errorCallback = undefined + const stderr = vi.spyOn(console, 'error').mockImplementation(() => {}) + + try { + const { browse } = await import('../src/sharing/discovery.js') + const pending = browse(10_000) + bonjourMock.serviceCallback?.({ + txt: { fp: 'fixture-fingerprint', dn: 'Fixture Mac' }, + addresses: ['192.168.1.25'], + port: 7777, + }) + bonjourMock.errorCallback?.(new Error('bind EPERM')) + + await expect(pending).resolves.toEqual([ + { + name: 'Fixture Mac', + host: '192.168.1.25', + port: 7777, + fingerprint: 'fixture-fingerprint', + }, + ]) + expect(stderr).toHaveBeenCalledWith('codeburn devices scan: mDNS discovery failed: bind EPERM') + } finally { + stderr.mockRestore() + } + }) +}) + describe('devices/share/identity JSON CLI output', () => { it('devices --format json returns CombinedUsage with the local device', async () => { const home = await mkdtemp(join(tmpdir(), 'codeburn-devices-json-')) @@ -109,21 +184,49 @@ describe('devices/share/identity JSON CLI output', () => { const home = await mkdtemp(join(tmpdir(), 'codeburn-devices-scan-json-')) try { - const result = runCli(['devices', 'scan', '--format', 'json'], home) + const result = runCli(['devices', 'scan', '--format', 'json'], home, { mockDiscovery: true }) expect(result.status, `stderr: ${result.stderr}`).toBe(0) const payload = JSON.parse(result.stdout) as { found: Array<{ name: string; host: string; port: number; fingerprint: string; code: string; paired: boolean }> } - expect(Array.isArray(payload.found)).toBe(true) - for (const device of payload.found) { - expect(typeof device.name).toBe('string') - expect(typeof device.host).toBe('string') - expect(typeof device.port).toBe('number') - expect(typeof device.fingerprint).toBe('string') - expect(typeof device.code).toBe('string') - expect(typeof device.paired).toBe('boolean') - } + expect(payload.found).toHaveLength(1) + expect(payload.found[0]).toMatchObject({ + name: 'Fixture Mac', + host: 'fixture.local', + port: 7777, + fingerprint: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', + paired: false, + }) + expect(payload.found[0]?.code).toMatch(/^\d{3}$/) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('devices add --format json is rejected as a mutation', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-devices-add-json-')) + + try { + const result = runCli(['devices', 'add', '--format', 'json'], home) + + expect(result.status).not.toBe(0) + expect(result.stdout).toBe('') + expect(result.stderr).toContain('--format json is only supported for read-only devices output and scan') + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('share --format json is rejected without the status action', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-share-json-guard-')) + + try { + const result = runCli(['share', '--format', 'json'], home) + + expect(result.status).not.toBe(0) + expect(result.stdout).toBe('') + expect(result.stderr).toContain('--format json is only supported for `share status`') } finally { await rm(home, { recursive: true, force: true }) } diff --git a/tests/fixtures/mock-discovery-register.mjs b/tests/fixtures/mock-discovery-register.mjs new file mode 100644 index 00000000..25c46686 --- /dev/null +++ b/tests/fixtures/mock-discovery-register.mjs @@ -0,0 +1,38 @@ +import * as Module from 'node:module' + +const discoveryFixtureUrl = `data:text/javascript,${encodeURIComponent(` +export async function browse() { + return [{ + name: 'Fixture Mac', + host: 'fixture.local', + port: 7777, + fingerprint: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', + }] +} + +export function advertise() { + return { stop: async () => {} } +} +`)}` + +function resolve(specifier, context, nextResolve) { + if (specifier === './sharing/discovery.js' || specifier.endsWith('/sharing/discovery.js')) { + return { url: discoveryFixtureUrl, shortCircuit: true } + } + return nextResolve(specifier, context) +} + +if (typeof Module.registerHooks === 'function') { + Module.registerHooks({ resolve }) +} else { + Module.register(`data:text/javascript,${encodeURIComponent(` +const discoveryFixtureUrl = ${JSON.stringify(discoveryFixtureUrl)} + +export async function resolve(specifier, context, nextResolve) { + if (specifier === './sharing/discovery.js' || specifier.endsWith('/sharing/discovery.js')) { + return { url: discoveryFixtureUrl, shortCircuit: true } + } + return nextResolve(specifier, context) +} +`)}`) +} diff --git a/tests/spend-flow.test.ts b/tests/spend-flow.test.ts index 1e85d9b2..5f031e20 100644 --- a/tests/spend-flow.test.ts +++ b/tests/spend-flow.test.ts @@ -180,12 +180,58 @@ describe('computeSpendFlow', () => { expect(flow.models).toHaveLength(9) expect(flow.projects).toHaveLength(9) - expect(flow.models.at(-1)).toMatchObject({ id: 'other', label: 'Other' }) - expect(flow.projects.at(-1)).toMatchObject({ id: 'other', label: 'Other' }) + expect(flow.models.at(-1)).toMatchObject({ id: '__other__', label: 'Other' }) + expect(flow.projects.at(-1)).toMatchObject({ id: '__other__', label: 'Other' }) expectTotalsReconcile(flow.models, sumLinksBy(flow.links, 'model')) expectTotalsReconcile(flow.projects, sumLinksBy(flow.links, 'project')) expect(flow.links.reduce((sum, link) => sum + link.cost, 0)).toBeCloseTo(expectedTotal, 10) }) + + it('keeps real other nodes separate from the rollup bucket', async () => { + const { computeSpendFlow } = await import('../src/spend-flow.js') + const range: DateRange = { + start: new Date('2026-06-01T00:00:00.000Z'), + end: new Date('2026-06-30T23:59:59.999Z'), + } + parserMock.parseAllSessions.mockResolvedValueOnce([ + project('other', [session('s-other', 'other', { other: 1000 })]), + ...Array.from({ length: 9 }, (_, index) => { + const n = index + 1 + return project(`project-${n}`, [session(`s-${n}`, `project-${n}`, { [`model-${n}`]: 100 - n * 10 })]) + }), + ]) + + const flow = await computeSpendFlow(range, 'all') + + expect(flow.models).toContainEqual({ id: 'other', label: 'other', cost: 1000 }) + expect(flow.models).toContainEqual({ id: '__other__', label: 'Other', cost: 30 }) + expect(flow.projects).toContainEqual({ id: 'other', label: 'other', cost: 1000 }) + expect(flow.projects).toContainEqual({ id: '__other__', label: 'Other', cost: 30 }) + expect(flow.links).toContainEqual({ model: 'other', project: 'other', cost: 1000 }) + expect(flow.links).toContainEqual({ model: '__other__', project: '__other__', cost: 30 }) + expectTotalsReconcile(flow.models, sumLinksBy(flow.links, 'model')) + expectTotalsReconcile(flow.projects, sumLinksBy(flow.links, 'project')) + }) + + it('labels the period with local calendar dates', async () => { + const previousTz = process.env['TZ'] + process.env['TZ'] = 'America/Los_Angeles' + try { + const { computeSpendFlow } = await import('../src/spend-flow.js') + const range: DateRange = { + start: new Date(2026, 6, 10, 0, 0, 0, 0), + end: new Date(2026, 6, 10, 23, 59, 59, 999), + } + parserMock.parseAllSessions.mockResolvedValueOnce([]) + + const flow = await computeSpendFlow(range, 'all') + + expect(flow.period.label).toBe('2026-07-10 to 2026-07-10') + } finally { + if (previousTz === undefined) delete process.env['TZ'] + else process.env['TZ'] = previousTz + } + }) }) describe('codeburn spend --format flow-json', () => { @@ -222,4 +268,19 @@ describe('codeburn spend --format flow-json', () => { await rm(home, { recursive: true, force: true }) } }) + + it('prints a friendly error for invalid custom date flags', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-spend-flow-date-error-')) + + try { + const result = runCli(['spend', '--format', 'flow-json', '--from', 'April 7'], home) + + expect(result.status).not.toBe(0) + expect(result.stdout).toBe('') + expect(result.stderr).toContain('Error: Invalid date format "April 7": expected YYYY-MM-DD') + expect(result.stderr).not.toContain('UsageQueryError') + } finally { + await rm(home, { recursive: true, force: true }) + } + }) })