mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 03:29:51 +00:00
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).
This commit is contained in:
parent
055e0d07e4
commit
b95b62d8fa
6 changed files with 235 additions and 29 deletions
13
src/main.ts
13
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 <number>', '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 <host> --pin <pin> (manual) | rm <name>')
|
||||
.description('Combined usage across your devices. Actions: scan | add (find nearby & pair) | add <host> --pin <pin> (manual) | rm <name>. Supports --format json for read-only output and scan.')
|
||||
.option('--pin <pin>', 'Pairing PIN shown on the device you are adding')
|
||||
.option('-p, --period <period>', 'Period: today, week, 30days, month, all', 'month')
|
||||
.option('--port <number>', '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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,9 +57,15 @@ export function browse(timeoutMs = 2500): Promise<DiscoveredDevice[]> {
|
|||
}
|
||||
}
|
||||
|
||||
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<string, string>
|
||||
const fingerprint = txt['fp']
|
||||
|
|
|
|||
|
|
@ -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<K>(map: Map<K, number>, key: K, cost: number): void {
|
||||
|
|
|
|||
|
|
@ -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<string, string>
|
||||
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<typeof bonjourMock.serviceCallback>) {
|
||||
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 })
|
||||
}
|
||||
|
|
|
|||
38
tests/fixtures/mock-discovery-register.mjs
vendored
Normal file
38
tests/fixtures/mock-discovery-register.mjs
vendored
Normal file
|
|
@ -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)
|
||||
}
|
||||
`)}`)
|
||||
}
|
||||
|
|
@ -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 })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue