Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(project-limit): core state, latch, deadline and lazy claim
review294c9b7f41d1
diff --git a/src/core/machine-id.test.ts b/src/core/machine-id.test.tsindex 6d25e34f0..254a2bb9e 100644--- a/src/core/machine-id.test.ts+++ b/src/core/machine-id.test.ts@@ -4,6 +4,7 @@ import {parseIoregUuid,parseRegMachineGuid,readMachineHash,+ readMachineHashResult,readMachineHashWith,setMachineIdDepsForTests,type MachineIdDeps@@ -228,3 +229,37 @@ describe('readMachineHash', () => {expect(calls).toEqual([IOREG_CALL, 'sleep 250', IOREG_CALL, IOREG_CALL])})})++// The project limit verifies a stored token's machine OFFLINE, and only against a hash it knows+// came from the OS: a fallback must never become the yardstick (see core/project-limit.ts).+describe('readMachineHashResult', () => {+ afterEach(() => setMachineIdDepsForTests(null))++ it('says the hash came from the OS when it did', async () => {+ const { deps } = fakeOs('darwin', { exec: { [IOREG]: IOREG_SAMPLE } })+ setMachineIdDepsForTests(deps)+ await expect(readMachineHashResult()).resolves.toEqual({ hash: OS_HASH, fromOs: true })+ })++ it('says the hostname fallback is not from the OS, and asks the OS again next time', async () => {+ const { deps, calls } = fakeOs('darwin', {+ exec: { [IOREG]: [null, null, IOREG_SAMPLE] },+ hostname: 'Mac-Studio.local'+ })+ setMachineIdDepsForTests(deps)+ await expect(readMachineHashResult()).resolves.toEqual({ hash: FALLBACK_HASH, fromOs: false })+ await expect(readMachineHashResult()).resolves.toEqual({ hash: OS_HASH, fromOs: true })+ expect(calls).toEqual([IOREG_CALL, 'sleep 250', IOREG_CALL, IOREG_CALL])+ })++ it('shares one read and one memo with readMachineHash', async () => {+ const { deps, calls } = fakeOs('darwin', { exec: { [IOREG]: IOREG_SAMPLE } })+ setMachineIdDepsForTests(deps)+ const result = readMachineHashResult()+ const hash = readMachineHash()+ await expect(result).resolves.toEqual({ hash: OS_HASH, fromOs: true })+ await expect(hash).resolves.toBe(OS_HASH)+ await expect(readMachineHashResult()).resolves.toEqual({ hash: OS_HASH, fromOs: true })+ expect(calls).toEqual([IOREG_CALL])+ })+})diff --git a/src/core/machine-id.ts b/src/core/machine-id.tsindex 194d032d1..672a1e62b 100644--- a/src/core/machine-id.ts+++ b/src/core/machine-id.ts@@ -126,31 +126,55 @@ export async function readMachineHashWith(deps: MachineIdDeps): Promise<string>return (await readOsMachineHash(deps)) ?? fallbackHash(deps)}+/** A machine hash and where it came from. `fromOs: false` = the `host:<hostname>` fallback. */+export interface MachineHashResult {+ hash: string+ fromOs: boolean+}+let deps: MachineIdDeps = realDeps/** Settled to a hash that came from the OS — kept for the life of the process. */-let memo: Promise<string> | null = null+let memo: Promise<MachineHashResult> | null = null/** The attempt in progress, shared by concurrent callers; cleared when it settles. */-let inFlight: Promise<string> | null = null+let inFlight: Promise<MachineHashResult> | null = null+/** `readMachineHash`'s view of each attempt, so one attempt always hands out one promise. */+const hashOf = new WeakMap<Promise<MachineHashResult>, Promise<string>>()-/** This machine's hash. An OS-read hash is memoized; the fallback is returned but not kept. */-export function readMachineHash(): Promise<string> {+/**+ * This machine's hash, saying whether it came from the OS. An OS-read hash is memoized; the+ * fallback is returned but not kept. The project limit verifies a stored token's machine only+ * against an OS-read hash: a fallback is a guess, and judging a token by a guess would drop a+ * legacy user to FREE on a transient read failure.+ */+export function readMachineHashResult(): Promise<MachineHashResult> {if (memo) return memoif (inFlight) return inFlightconst d = deps- const attempt: Promise<string> = readOsMachineHash(d)+ const attempt: Promise<MachineHashResult> = readOsMachineHash(d).catch(() => null).then((hash) => {// A test reset while this was in flight leaves it un-memoized.const current = inFlight === attemptif (current) inFlight = null- if (hash === null) return fallbackHash(d)+ if (hash === null) return { hash: fallbackHash(d), fromOs: false }if (current) memo = attempt- return hash+ return { hash, fromOs: true }})inFlight = attemptreturn attempt}+/** This machine's hash. An OS-read hash is memoized; the fallback is returned but not kept. */+export function readMachineHash(): Promise<string> {+ const attempt = readMachineHashResult()+ let hash = hashOf.get(attempt)+ if (!hash) {+ hash = attempt.then((r) => r.hash)+ hashOf.set(attempt, hash)+ }+ return hash+}+/** Test seam: swap the OS readers (null restores the real ones) and drop the memo. */export function setMachineIdDepsForTests(next: MachineIdDeps | null): void {deps = next ?? realDepsdiff --git a/src/core/project-allowance-token.test.ts b/src/core/project-allowance-token.test.tsindex 3b480a2fe..9e9145baa 100644--- a/src/core/project-allowance-token.test.ts+++ b/src/core/project-allowance-token.test.ts@@ -95,6 +95,29 @@ describe('verifyAllowanceToken', () => {expect(verifyAllowanceToken(mint(over), EXPECT, PUB)).toBeNull()})+ // `machine: null` = no OS-read hash known yet (core/project-limit.ts): the token is trusted+ // provisionally on everything but the machine. It must be an explicit null, never a missing key.+ it('skips only the machine match when machine is null', () => {+ const elsewhere = mint({ machine: machineHashOf('another-machine') })+ expect(verifyAllowanceToken(elsewhere, { deviceId: DEVICE, machine: null }, PUB)).toEqual({ allowance: 12, epoch: 2 })+ expect(verifyAllowanceToken(elsewhere, EXPECT, PUB)).toBeNull()+ })++ it.each([+ ['wrong typ', { typ: 'entitlement' }],+ ['wrong deviceId', { deviceId: 'device-2' }],+ ['allowance -1', { allowance: -1 }],+ ['no epoch', { epoch: undefined }]+ ])('with machine null, still refuses a signed token with %s', (_label, over) => {+ expect(verifyAllowanceToken(mint(over), { deviceId: DEVICE, machine: null }, PUB)).toBeNull()+ })++ it('with machine null, still checks the signature and the expected epoch', () => {+ const other = crypto.generateKeyPairSync('ed25519').privateKey+ expect(verifyAllowanceToken(mint({}, other), { deviceId: DEVICE, machine: null }, PUB)).toBeNull()+ expect(verifyAllowanceToken(mint(), { deviceId: DEVICE, machine: null, epoch: 3 }, PUB)).toBeNull()+ })+it('refuses an entitlement-shaped token signed with the same key', () => {// Everything an allowance needs, minus the kind gate: proves `typ` is checked, not inferred.const entitlement = signRaw({diff --git a/src/core/project-allowance-token.ts b/src/core/project-allowance-token.tsindex cc98fe01d..a9a6ba8ed 100644--- a/src/core/project-allowance-token.ts+++ b/src/core/project-allowance-token.ts@@ -28,10 +28,14 @@ const isCount = (v: unknown): v is number => Number.isSafeInteger(v) && (v as nu* The token's `{ allowance, epoch }` when it is signed by `publicKeyPem`, is a project-allowance* token (`typ`), was minted for this `deviceId` and `machine` (and `epoch`, when given), and carries* a non-negative integer allowance — else null. Never throws.+ *+ * `machine: null` skips the machine match and nothing else: the caller has no OS-read machine hash+ * yet (core/project-limit.ts trusts a stored token provisionally until it has one). It is an+ * explicit null rather than an optional key so that no caller can skip the check by omission.*/export function verifyAllowanceToken(token: string | undefined,- expect: { deviceId: string; machine: string; epoch?: number },+ expect: { deviceId: string; machine: string | null; epoch?: number },publicKeyPem: string = PROJECT_ALLOWANCE_PUBLIC_KEY): VerifiedAllowance | null {// A runtime guard, not a type one: the token comes off disk, where any JSON value can stand in.@@ -47,7 +51,8 @@ export function verifyAllowanceToken(if (typeof payload !== 'object' || payload === null) return nullconst { typ, deviceId, machine, allowance, epoch } = payload as Record<string, unknown>if (typ !== PROJECT_ALLOWANCE_KIND) return null- if (deviceId !== expect.deviceId || machine !== expect.machine) return null+ if (deviceId !== expect.deviceId) return null+ if (expect.machine !== null && machine !== expect.machine) return nullif (!isCount(allowance) || !isCount(epoch)) return nullif (expect.epoch !== undefined && epoch !== expect.epoch) return nullreturn { allowance, epoch }diff --git a/src/core/project-limit.test.ts b/src/core/project-limit.test.tsnew file mode 100644index 000000000..4b93731a1--- /dev/null+++ b/src/core/project-limit.test.ts@@ -0,0 +1,701 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import crypto from 'node:crypto'+import { existsSync, readFileSync, rmSync, writeFileSync } from 'fs'+import path from 'path'+import { IPC } from '../shared/ipc'+import { PROJECT_LIMIT_DEADLINE_MS, type ClaimResult, type ProjectLimitState } from '../shared/project-limit'+import { machineHashOf, type MachineHashResult } from './machine-id'+import { makeFakeUserDataDir, type FakePlatform } from './platform-fake'++// The Pro test needs a real entitlement token: license.ts verifies against this key.+const h = vi.hoisted(() => ({ entitlementPem: '' }))+vi.mock('./entitlement-key', () => ({+ get ENTITLEMENT_PUBLIC_KEY() {+ return h.entitlementPem+ }+}))+// Every write of project-limit.json must go through writeFileAtomic; the spy also counts them.+vi.mock('./fs-atomic', async (importOriginal) => {+ const actual = await importOriginal<typeof import('./fs-atomic')>()+ return { ...actual, writeFileAtomic: vi.fn(actual.writeFileAtomic) }+})++const entitlement = crypto.generateKeyPairSync('ed25519')+h.entitlementPem = entitlement.publicKey.export({ type: 'spki', format: 'pem' }).toString()+// The allowance key is passed to initProjectLimit (the shipped key is '' until owner step O1).+const allowanceKeys = crypto.generateKeyPairSync('ed25519')+const ALLOWANCE_PUB = allowanceKeys.publicKey.export({ type: 'spki', format: 'pem' }).toString()++const MINUTE = 60 * 1000+const HOUR = 60 * MINUTE+const DAY = 24 * HOUR+const DEADLINE = PROJECT_LIMIT_DEADLINE_MS+const BEFORE = DEADLINE - 30 * DAY+const AFTER = DEADLINE + 2 * DAY+const API = 'http://127.0.0.1:1'+const DEVICE = '3f0c6a52-9d7e-4b8a-a1c4-5e2f7d9b0c18'+const MACHINE = machineHashOf('0123456789abcdef0123456789abcdef')+const OTHER_MACHINE = machineHashOf('fedcba9876543210fedcba9876543210')+const FALLBACK = machineHashOf('host:test-host')++function signPayload(payload: object, key: crypto.KeyObject): string {+ const p = Buffer.from(JSON.stringify(payload)).toString('base64url')+ return `${p}.${crypto.sign(null, Buffer.from(p), key).toString('base64url')}`+}++/** An allowance token the way nodeterm-server's signer writes it. */+function allowanceToken(+ over: { allowance?: number; epoch?: number; machine?: string; deviceId?: string } = {},+ key: crypto.KeyObject = allowanceKeys.privateKey+): string {+ return signPayload(+ {+ typ: 'project-allowance',+ deviceId: over.deviceId ?? DEVICE,+ machine: over.machine ?? MACHINE,+ allowance: over.allowance ?? 9,+ epoch: over.epoch ?? 1,+ iat: Math.floor(Date.now() / 1000)+ },+ key+ )+}++function entitlementToken(ttlSeconds: number): string {+ const now = Math.floor(Date.now() / 1000)+ return signPayload(+ { deviceId: DEVICE, tier: 'pro', licenseId: 'lic_test', iat: now, exp: now + ttlSeconds },+ entitlement.privateKey+ )+}++interface FakeResponse {+ ok: boolean+ status: number+ json: () => Promise<unknown>+}+type Reply = (url: string, init?: RequestInit) => Promise<FakeResponse>++const reply = (status: number, body: unknown): Reply => () =>+ Promise.resolve({ ok: status >= 200 && status < 300, status, json: async () => body })+/** A body that is not JSON: a 500 page, a captive portal's HTML. */+const notJson = (status: number): Reply => () =>+ Promise.resolve({+ ok: status >= 200 && status < 300,+ status,+ json: async () => {+ throw new SyntaxError('Unexpected token < in JSON')+ }+ })+const offline: Reply = () => Promise.reject(new TypeError('fetch failed'))+const checkOn = (free: number, epoch: number): Reply =>+ reply(200, { messages: [], update: {}, limits: { projects: { free, epoch } } })+const checkOff: Reply = reply(200, { messages: [], update: {} })++let userData = ''+let fake: FakePlatform+let fetchMock: ReturnType<typeof vi.fn>+let notified: ProjectLimitState[] = []+const net: { check: Reply; claim: Reply } = { check: offline, claim: offline }+let machineSpy: ReturnType<typeof vi.fn<() => Promise<MachineHashResult>>>++const limitFile = (): string => path.join(userData, 'project-limit.json')+const readLimitFile = (): Record<string, unknown> => JSON.parse(readFileSync(limitFile(), 'utf-8'))+const writeLimitFile = (v: unknown): void =>+ writeFileSync(limitFile(), typeof v === 'string' ? v : JSON.stringify(v))+const writeLicense = (v: object): void => writeFileSync(path.join(userData, 'license.json'), JSON.stringify(v))+const urls = (): string[] => fetchMock.mock.calls.map((c) => String(c[0]))+const claimCalls = () => fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/v1/limits/claim'))+const checkCalls = (): number => urls().filter((u) => u.includes('/v1/check?')).length+const channelSends = () => fake.sent.filter((s) => s.channel === IPC.projectLimitChanged)++/** Let pending fs / promise work settle without touching the (partly faked) timers. */+const flush = async (): Promise<void> => {+ for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r))+}++interface Booted {+ handle: import('./project-limit').ProjectLimitHandle+ mod: typeof import('./project-limit')+ check: typeof import('./check')+ /** Calls of writeFileAtomic aimed at project-limit.json. */+ writes: () => number+ idle: () => Promise<void>+}+let booted: Booted++async function boot(+ opts: {+ packaged?: boolean+ file?: unknown+ openProjects?: () => number | undefined+ machineHash?: () => Promise<MachineHashResult>+ wait?: boolean+ } = {}+): Promise<Booted> {+ vi.resetModules()+ if (opts.file !== undefined) writeLimitFile(opts.file)+ const { initPlatform } = await import('./platform')+ const { fakePlatform } = await import('./platform-fake')+ fake = fakePlatform({ userDataDir: userData, isPackaged: opts.packaged ?? true })+ initPlatform(fake)+ const mod = await import('./project-limit')+ const check = await import('./check')+ const atomic = await import('./fs-atomic')+ const writeSpy = atomic.writeFileAtomic as unknown as ReturnType<typeof vi.fn>+ const handle = mod.initProjectLimit({+ openProjects: opts.openProjects ?? (() => 3),+ machineHash: opts.machineHash ?? machineSpy,+ publicKeyPem: ALLOWANCE_PUB,+ notify: (s) => notified.push(s)+ })+ booted = {+ handle,+ mod,+ check,+ writes: () => writeSpy.mock.calls.filter((c) => c[0] === limitFile()).length,+ idle: () => mod.__projectLimitIdleForTests()+ }+ if (opts.wait !== false) await booted.idle()+ return booted+}++/** Serve one /v1/check read (past check.ts's 5-minute cache) and let core digest the answer. */+async function answer(r: Reply): Promise<void> {+ net.check = r+ vi.setSystemTime(Date.now() + 6 * MINUTE)+ await booted.check.fetchCheck()+ await booted.idle()+}++beforeEach(() => {+ // Only the intervals and the clock are faked: fetch, fs and the claim's abort timer stay real.+ vi.useFakeTimers({ toFake: ['setInterval', 'Date'] })+ vi.setSystemTime(BEFORE)+ userData = makeFakeUserDataDir()+ writeFileSync(path.join(userData, 'device-id'), DEVICE)+ delete process.env.DO_NOT_TRACK+ delete process.env.NODETERM_TELEMETRY_DISABLED+ process.env.NODETERM_API_BASE = API+ net.check = offline+ net.claim = offline+ notified = []+ machineSpy = vi.fn(async () => ({ hash: MACHINE, fromOs: true }))+ fetchMock = vi.fn((url: string, init?: RequestInit) => {+ if (url.includes('/v1/check?')) return net.check(url, init)+ if (url.endsWith('/v1/limits/claim')) return net.claim(url, init)+ return Promise.reject(new Error(`unexpected fetch ${url}`))+ })+ vi.stubGlobal('fetch', fetchMock)+})++afterEach(async () => {+ await booted?.idle()+ vi.unstubAllGlobals()+ vi.useRealTimers()+ const { resetPlatformForTests } = await import('./platform')+ resetPlatformForTests()+ rmSync(userData, { recursive: true, force: true })+ delete process.env.NODETERM_API_BASE+ delete process.env.DO_NOT_TRACK+})++describe('project limit: on or off', () => {+ it('is inactive in an unpackaged build even when latched', async () => {+ vi.setSystemTime(AFTER)+ const { handle } = await boot({ packaged: false, file: { latched: true, free: 5, epoch: 1 } })+ expect(handle.state().active).toBe(false)+ await answer(checkOn(5, 1))+ expect(handle.state().active).toBe(false)+ })++ it('is inactive before the deadline with no server word', async () => {+ const { handle } = await boot()+ expect(handle.state()).toEqual({ active: false, pro: false, free: 5, allowance: null, dnt: false })+ vi.setSystemTime(DEADLINE - 1)+ expect(handle.state().active).toBe(false)+ // Review Focus 1: no claim and no machine read — the one request is the existing check.+ expect(urls()).toEqual([expect.stringContaining(`${API}/v1/check?`)])+ expect(machineSpy).not.toHaveBeenCalled()+ expect(notified.every((s) => !s.active)).toBe(true)++ // DO_NOT_TRACK users too, until the deadline — and they send nothing at all.+ process.env.DO_NOT_TRACK = '1'+ fetchMock.mockClear()+ const dnt = await boot()+ expect(dnt.handle.state()).toMatchObject({ active: false, allowance: null, dnt: true })+ expect(fetchMock).not.toHaveBeenCalled()+ expect(machineSpy).not.toHaveBeenCalled()+ })++ it('activates at the deadline using the clock anchor', async () => {+ // The wall clock is a month before the deadline, but this install has already observed an+ // instant past it (license.ts's `lastSeen`): a rolled-back clock does not move it back.+ writeLicense({ lastSeen: Math.floor((DEADLINE + DAY) / 1000) })+ const { handle } = await boot()+ expect(handle.state().active).toBe(true)++ // The reverse never activates early: a `lastSeen` before the deadline, wall clock before it.+ writeLicense({ lastSeen: Math.floor((DEADLINE - DAY) / 1000) })+ expect(handle.state().active).toBe(false)+ vi.setSystemTime(DEADLINE - 1)+ expect(handle.state().active).toBe(false)+ vi.setSystemTime(DEADLINE)+ expect(handle.state().active).toBe(true)+ })++ it('latches on a check answer with limits', async () => {+ const { handle } = await boot()+ expect(handle.state().active).toBe(false)+ await answer(checkOn(7, 3))+ expect(handle.state()).toMatchObject({ active: true, free: 7 })+ expect(readLimitFile()).toMatchObject({ latched: true, free: 7, epoch: 3 })+ expect(notified.at(-1)).toMatchObject({ active: true, free: 7 })+ })++ it('keeps the latch when later checks fail', async () => {+ const { handle } = await boot()+ await answer(checkOn(5, 1))+ // Review Focus 3: none of these is a successful check without `limits`.+ for (const failed of [+ reply(500, {}),+ reply(429, { error: 'rate_limited', scope: 'ip' }),+ notJson(502),+ offline,+ notJson(200), // a captive portal's HTML page+ reply(200, { status: 'ok' }), // JSON that is not a check reply+ reply(200, { messages: [], update: {}, limits: { projects: { free: 'x', epoch: 1 } } })+ ]) {+ await answer(failed)+ expect(handle.state().active).toBe(true)+ }+ expect(readLimitFile().latched).toBe(true)++ // A restart with the network down keeps it: the latch is on disk.+ const again = await boot()+ expect(again.handle.state().active).toBe(true)+ })++ it('clears the latch on a successful check without limits', async () => {+ const { handle } = await boot()+ await answer(checkOn(5, 1))+ expect(handle.state().active).toBe(true)+ await answer(checkOff)+ expect(handle.state().active).toBe(false)+ expect(readLimitFile().latched).toBe(false)+ expect(notified.at(-1)?.active).toBe(false)+ })++ it('a not_active claim clears and suppresses the deadline for 24 h', async () => {+ vi.setSystemTime(AFTER)+ const { handle, mod } = await boot({ file: { latched: true, epoch: 1, token: allowanceToken() } })+ expect(handle.state()).toMatchObject({ active: true, allowance: 9 })+ net.claim = reply(409, { error: 'not_active' })+ const r = await handle.claim()+ expect(r).toEqual({ ok: true, state: expect.objectContaining({ active: false, allowance: null }) })+ const file = readLimitFile()+ expect(file).toMatchObject({ latched: false, offAt: AFTER })+ expect(file.token).toBeUndefined()++ vi.setSystemTime(AFTER + mod.OFF_TRUST_MS - 1)+ expect(handle.state().active).toBe(false)+ // …across a restart too: the off answer is on disk.+ expect((await boot()).handle.state().active).toBe(false)+ // Then the deadline re-arms.+ vi.setSystemTime(AFTER + mod.OFF_TRUST_MS)+ expect(booted.handle.state().active).toBe(true)+ })++ it('records firstLaunchOpenCount once', async () => {+ let count: number | undefined+ const { handle, idle } = await boot({ openProjects: () => count })+ handle.state()+ await idle()+ // Unknown is never recorded — and never as 0.+ expect(existsSync(limitFile())).toBe(false)+ count = 4+ handle.state()+ await idle()+ expect(readLimitFile().firstLaunchOpenCount).toBe(4)+ count = 9+ handle.state()+ await idle()+ expect(readLimitFile().firstLaunchOpenCount).toBe(4)++ const again = await boot({ openProjects: () => 12 })+ again.handle.state()+ await again.idle()+ expect(readLimitFile().firstLaunchOpenCount).toBe(4)+ })++ it('drops a token whose epoch differs from the latest check', async () => {+ const token = allowanceToken({ allowance: 9, epoch: 1 })+ const { handle } = await boot({ file: { latched: true, free: 5, epoch: 1, token } })+ expect(handle.state().allowance).toBe(9)+ await answer(checkOn(5, 1))+ expect(handle.state().allowance).toBe(9)+ expect(readLimitFile().token).toBe(token)++ await answer(checkOn(5, 2))+ expect(handle.state().allowance).toBeNull()+ expect(readLimitFile()).toMatchObject({ latched: true, epoch: 2 })+ expect(readLimitFile().token).toBeUndefined()+ expect(notified.at(-1)?.allowance).toBeNull()+ })++ it('reports allowance from a stored token with the network down', async () => {+ vi.setSystemTime(AFTER)+ const { handle } = await boot({ file: { latched: true, free: 5, epoch: 1, token: allowanceToken({ allowance: 12 }) } })+ fetchMock.mockClear()+ // Review Focus 2: nothing on the way to the answer touches the network.+ expect(handle.state()).toEqual({ active: true, pro: false, free: 5, allowance: 12, dnt: false })+ expect(fake.handlers[IPC.projectLimitState]()).toEqual(handle.state())+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('free defaults to 5 and follows the server', async () => {+ const { handle } = await boot()+ expect(handle.state().free).toBe(5)+ await answer(checkOn(8, 1))+ expect(handle.state().free).toBe(8)+ net.claim = reply(200, { token: allowanceToken({ epoch: 1 }), free: 6, epoch: 1 })+ expect((await handle.claim()).state.free).toBe(6)+ net.check = offline // the restart hears nothing newer: the last server word is kept+ expect((await boot()).handle.state().free).toBe(6)+ })++ it('pro follows proForProjectLimit', async () => {+ const { handle } = await boot()+ expect(handle.state().pro).toBe(false)+ writeLicense({ token: entitlementToken(7 * 24 * 3600) })+ expect(handle.state().pro).toBe(true) // re-read on every state(): no restart, no event+ handle.refresh()+ expect(notified.at(-1)?.pro).toBe(true)+ // A token that lapsed 20 days ago still counts for the limit (license.ts's 30-day grace)…+ writeLicense({ token: entitlementToken(-20 * 24 * 3600) })+ expect(handle.state().pro).toBe(true)+ // …and no token is no Pro.+ writeLicense({})+ expect(handle.state().pro).toBe(false)+ })+})++describe('project limit: claim', () => {+ it('claim stores token, free and epoch and broadcasts', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 2 } })+ const token = allowanceToken({ allowance: 9, epoch: 2 })+ net.claim = reply(200, { token, free: 6, epoch: 2 })+ const r = await handle.claim()+ expect(r).toEqual({ ok: true, state: { active: true, pro: false, free: 6, allowance: 9, dnt: false } })+ expect(readLimitFile()).toMatchObject({ latched: true, free: 6, epoch: 2, token })+ expect(notified.at(-1)).toEqual(r.state)+ // This machine's windows only (the shell's `notify`), never platform().broadcast/sendTo.+ expect(channelSends()).toEqual([])+ })++ it('claim sends deviceId, machine and firstLaunchOpenCount', async () => {+ const { handle } = await boot({ file: { latched: true }, openProjects: () => 4 })+ net.claim = reply(409, { error: 'not_active' })+ await handle.claim()+ const [url, init] = claimCalls()[0]+ expect(url).toBe(`${API}/v1/limits/claim`)+ expect(init).toMatchObject({ method: 'POST', headers: { 'content-type': 'application/json' } })+ expect(JSON.parse(String(init.body))).toEqual({ deviceId: DEVICE, machine: MACHINE, firstLaunchOpenCount: 4 })++ // An unknown count is sent as null, never as 0.+ rmSync(limitFile())+ fetchMock.mockClear()+ const again = await boot({ file: { latched: true }, openProjects: () => undefined })+ await again.handle.claim()+ expect(JSON.parse(String(claimCalls()[0][1].body))).toEqual({+ deviceId: DEVICE,+ machine: MACHINE,+ firstLaunchOpenCount: null+ })+ })++ it('claim maps machine_mismatch with retryAfter', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 1 }, openProjects: () => undefined })+ const before = readFileSync(limitFile(), 'utf-8')+ net.claim = reply(409, { error: 'machine_mismatch', retryAfter: 1802174400 })+ expect(await handle.claim()).toEqual({+ ok: false,+ error: 'machine_mismatch',+ retryAfter: 1802174400,+ state: handle.state()+ })+ expect(readFileSync(limitFile(), 'utf-8')).toBe(before)+ // A retryAfter that is not a unix-seconds integer is left out rather than invented.+ net.claim = reply(409, { error: 'machine_mismatch', retryAfter: 'soon' })+ expect(await handle.claim()).toEqual({ ok: false, error: 'machine_mismatch', state: handle.state() })+ })++ it('claim maps 500/429 to server and a throw to offline', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 1 }, openProjects: () => undefined })+ const before = readFileSync(limitFile(), 'utf-8')+ for (const r of [+ notJson(500),+ reply(429, { error: 'rate_limited', scope: 'ip' }),+ reply(503, {}),+ reply(400, { error: 'bad_request' }),+ reply(404, {}),+ reply(409, { error: 'something_new' }),+ notJson(200),+ reply(200, {})+ ]) {+ net.claim = r+ expect(await handle.claim()).toEqual({ ok: false, error: 'server', state: handle.state() })+ }+ net.claim = offline+ expect(await handle.claim()).toEqual({ ok: false, error: 'offline', state: handle.state() })+ expect(readFileSync(limitFile(), 'utf-8')).toBe(before)+ })++ it('a 200 whose token does not verify is a server error', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 2 } })+ const other = crypto.generateKeyPairSync('ed25519').privateKey+ for (const body of [+ { token: allowanceToken({ epoch: 2 }, other), free: 5, epoch: 2 },+ { token: allowanceToken({ epoch: 2, machine: OTHER_MACHINE }), free: 5, epoch: 2 },+ { token: allowanceToken({ epoch: 2, deviceId: '00000000-0000-4000-8000-000000000000' }), free: 5, epoch: 2 },+ { token: allowanceToken({ epoch: 1 }), free: 5, epoch: 2 },+ { token: allowanceToken({ epoch: 2 }), free: 5 },+ { token: allowanceToken({ epoch: 2 }), free: 0, epoch: 2 },+ { token: 42, free: 5, epoch: 2 }+ ]) {+ net.claim = reply(200, body)+ expect(await handle.claim()).toEqual({ ok: false, error: 'server', state: handle.state() })+ }+ expect(handle.state().allowance).toBeNull()+ expect(readLimitFile().token).toBeUndefined()+ })++ it('claim under DNT without consent answers consent_required without a fetch', async () => {+ process.env.DO_NOT_TRACK = '1'+ const { handle } = await boot({ file: { latched: true } })+ fetchMock.mockClear()+ expect(await handle.claim()).toEqual({+ ok: false,+ error: 'consent_required',+ state: expect.objectContaining({ dnt: true })+ })+ expect(fetchMock).not.toHaveBeenCalled()+ expect(machineSpy).not.toHaveBeenCalled()+ })++ it('claim in an unpackaged build without an API override answers disabled, with no fetch or machine read', async () => {+ delete process.env.NODETERM_API_BASE+ const { handle } = await boot({ packaged: false })+ expect(await handle.claim()).toEqual({ ok: false, error: 'disabled', state: handle.state() })+ expect(fetchMock).not.toHaveBeenCalled()+ expect(machineSpy).not.toHaveBeenCalled()+ })++ it('concurrent claims share one request', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 1 } })+ let release: (() => void) | undefined+ net.claim = () =>+ new Promise<FakeResponse>((resolve) => {+ release = () => resolve({ ok: true, status: 200, json: async () => ({ token: allowanceToken(), free: 5, epoch: 1 }) })+ })+ const a = handle.claim()+ const b = handle.claim()+ expect(b).toBe(a)+ await flush()+ expect(claimCalls()).toHaveLength(1)+ release?.()+ expect((await a).ok).toBe(true)+ // Once it has settled, the next claim is a new request.+ net.claim = reply(409, { error: 'not_active' })+ await handle.claim()+ expect(claimCalls()).toHaveLength(2)+ })++ it('the claim timeout covers the response body', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 1 } })+ vi.useFakeTimers({ toFake: ['setInterval', 'Date', 'setTimeout', 'clearTimeout'] })+ // Headers arrive at once; the body never does (a proxy holding the connection open).+ net.claim = (_url, init) =>+ Promise.resolve({+ ok: true,+ status: 200,+ json: () =>+ new Promise((_resolve, reject) => {+ init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))+ })+ })+ let settled: ClaimResult | undefined+ void handle.claim().then((r) => (settled = r))+ await vi.advanceTimersByTimeAsync(7999)+ expect(settled).toBeUndefined()+ await vi.advanceTimersByTimeAsync(1)+ await flush()+ expect(settled).toEqual({ ok: false, error: 'offline', state: handle.state() })+ })++ it('never rejects, even when reading the machine fails', async () => {+ const { handle } = await boot({+ file: { latched: true },+ machineHash: () => Promise.reject(new Error('boom'))+ })+ await expect(handle.claim()).resolves.toEqual({ ok: false, error: 'server', state: handle.state() })+ expect(claimCalls()).toHaveLength(0)+ })++ it('is served over IPC', async () => {+ const { handle } = await boot({ file: { latched: true } })+ net.claim = reply(409, { error: 'not_active' })+ const r = (await fake.handlers[IPC.projectLimitClaim]()) as ClaimResult+ expect(r).toEqual({ ok: true, state: handle.state() })+ expect(r.state.active).toBe(false)+ })+})++describe('project limit: machine hash', () => {+ it('a dormant install never reads the machine id', async () => {+ const { handle } = await boot()+ handle.state()+ await answer(checkOn(5, 1))+ await answer(checkOff)+ handle.refresh()+ expect(machineSpy).not.toHaveBeenCalled()+ })++ it('trusts a stored token provisionally until an OS-read hash is known, then checks the machine', async () => {+ let resolve!: (r: MachineHashResult) => void+ const read = new Promise<MachineHashResult>((r) => (resolve = r))+ const { handle, idle } = await boot({+ file: { latched: true, epoch: 1, token: allowanceToken({ allowance: 12 }) },+ machineHash: () => read,+ wait: false+ })+ // Read pending: the allowance stands (a slow boot read must not push a legacy user to a claim).+ expect(handle.state().allowance).toBe(12)+ resolve({ hash: OTHER_MACHINE, fromOs: true })+ await idle()+ // The OS says this is another machine: the token was copied here.+ expect(handle.state().allowance).toBeNull()+ expect(notified.at(-1)?.allowance).toBeNull()+ })++ it('keeps trusting a stored token when the OS read falls back', async () => {+ const { handle } = await boot({+ file: { latched: true, epoch: 1, token: allowanceToken({ allowance: 12 }) },+ machineHash: async () => ({ hash: OTHER_MACHINE, fromOs: false })+ })+ expect(handle.state().allowance).toBe(12)+ })++ it('keeps a stored token whose machine the OS confirms', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 1, token: allowanceToken({ allowance: 12 }) } })+ expect(machineSpy).toHaveBeenCalledTimes(1)+ expect(handle.state().allowance).toBe(12)+ expect(notified.at(-1)?.allowance).toBe(12)+ })++ it('a successful claim caches the machine hash it sent only when it came from the OS', async () => {+ const { handle, mod } = await boot({+ file: { latched: true, epoch: 1 },+ machineHash: async () => ({ hash: FALLBACK, fromOs: false })+ })+ net.claim = reply(200, { token: allowanceToken({ machine: FALLBACK }), free: 5, epoch: 1 })+ expect((await handle.claim()).state.allowance).toBe(9)+ expect(mod.__projectLimitMachineForTests()).toBeNull()++ const again = await boot({ file: { latched: true, epoch: 1 } })+ net.claim = reply(200, { token: allowanceToken(), free: 5, epoch: 1 })+ expect((await again.handle.claim()).state.allowance).toBe(9)+ expect(again.mod.__projectLimitMachineForTests()).toBe(MACHINE)+ })+})++describe('project limit: persistence', () => {+ it.each([+ ['missing', undefined],+ ['unparsable', '{"latched": tr'],+ ['an array', '[true]'],+ ['null', 'null'],+ ['a string', '"latched"']+ ])('reads a %s file as no state, without throwing', async (_label, file) => {+ const { handle } = await boot({ file })+ expect(handle.state()).toEqual({ active: false, pro: false, free: 5, allowance: null, dnt: false })+ })++ it('drops wrong-typed fields one by one', async () => {+ const { handle } = await boot({+ file: { latched: true, offAt: 'yesterday', free: 2.5, epoch: 1, token: 42, firstLaunchOpenCount: '4' },+ openProjects: () => 7+ })+ expect(handle.state()).toMatchObject({ active: true, free: 5, allowance: null })+ await booted.idle()+ expect(readLimitFile()).toEqual({ latched: true, epoch: 1, firstLaunchOpenCount: 7 })++ const other = await boot({+ file: { latched: 'yes', free: 1001, epoch: 0, token: allowanceToken(), firstLaunchOpenCount: -1 },+ openProjects: () => undefined+ })+ expect(other.handle.state()).toMatchObject({ active: false, free: 5, allowance: 9 })+ })++ it('writes only when something changed', async () => {+ const { handle, writes, idle } = await boot({ openProjects: () => 3 })+ handle.state()+ await idle()+ expect(writes()).toBe(1) // the first-launch count+ handle.state()+ handle.state()+ await idle()+ expect(writes()).toBe(1)++ await answer(checkOn(5, 1))+ expect(writes()).toBe(2)+ const sent = notified.length+ // The same answer twice (two callers racing check.ts's cache miss) is one change.+ await answer(checkOn(5, 1))+ // An answer the client cannot read changes nothing.+ await answer(reply(200, { messages: [], update: {}, limits: { projects: {} } }))+ expect(writes()).toBe(2)+ expect(notified.length).toBe(sent)+ expect(readLimitFile()).toEqual({ firstLaunchOpenCount: 3, latched: true, free: 5, epoch: 1 })+ })++ it('an off answer writes nothing until it could matter at the deadline', async () => {+ const { writes } = await boot({ openProjects: () => undefined })+ await answer(checkOff)+ expect(writes()).toBe(0)+ // Within a day of the deadline the off answer is what keeps it from switching on: keep it.+ vi.setSystemTime(DEADLINE - 12 * HOUR)+ await answer(checkOff)+ expect(writes()).toBe(1)+ expect(readLimitFile()).toEqual({ latched: false, offAt: Date.now() })+ vi.setSystemTime(DEADLINE + HOUR)+ expect((await boot({ openProjects: () => undefined })).handle.state().active).toBe(false)+ })+})++describe('project limit: wiring', () => {+ it('sends projectLimit:changed through notify only, never platform().broadcast', async () => {+ const { handle } = await boot({ file: { latched: true, epoch: 1 } })+ await answer(checkOn(6, 1))+ net.claim = reply(200, { token: allowanceToken(), free: 6, epoch: 1 })+ await handle.claim()+ handle.refresh()+ expect(notified.length).toBeGreaterThanOrEqual(3)+ expect(channelSends()).toEqual([])+ })++ it('refresh() re-sends the current state', async () => {+ const { handle } = await boot()+ const n = notified.length+ handle.refresh()+ expect(notified.length).toBe(n + 1)+ expect(notified.at(-1)).toEqual(handle.state())+ })++ it('reads the check feed at init and every 6 hours', async () => {+ await boot()+ expect(checkCalls()).toBe(1)+ await vi.advanceTimersByTimeAsync(6 * HOUR)+ expect(checkCalls()).toBe(2)+ })+})diff --git a/src/core/project-limit.ts b/src/core/project-limit.tsnew file mode 100644index 000000000..eb08d6c04--- /dev/null+++ b/src/core/project-limit.ts@@ -0,0 +1,372 @@+/**+ * The free-tier open-project limit, desktop core (docs/superpowers/specs/2026-10-29-free-tier-project-limit-design.md+ * §5–§6). It decides whether the limit is on for this install and what its allowance is, and it+ * makes the claim. The renderer's gate asks for that state (`decideOpen` in shared/project-limit.ts)+ * and claims only when it has to. Desktop only: the Server Edition never calls `initProjectLimit`+ * (its bridge answers `INACTIVE_PROJECT_LIMIT`).+ *+ * ON OR OFF. `active` = a packaged build AND (the latch OR the embedded deadline has passed by the+ * clock anchor, with no server "off" in the last `OFF_TRUST_MS`). Dev builds are never active.+ * - The latch is the server's word. A check answer with `limits` sets it; a successful check+ * without them, or a claim answering `not_active`, clears it. Nothing else does: a failed check+ * gives no answer at all (check.ts `onCheckAnswer`), so being unreachable never turns it off.+ * - The deadline is compared against `clockAnchorMs()` (license.ts: the later of the wall clock and+ * the largest instant this install has observed), so rolling the clock back cannot move an install+ * from past the deadline to before it.+ * - An "off" (`offAt`) suppresses the deadline for 24 h. A check that keeps saying off refreshes it.+ *+ * THE ALLOWANCE comes from a server-signed token, verified offline on every `state()`: signature+ * (the separate allowance key), `typ`, deviceId, epoch, and the MACHINE hash. The machine is judged+ * only against a hash that came from a SUCCESSFUL OS read (machine-id.ts `fromOs`), which `state()`+ * cannot wait for. So when a token is stored (never on a dormant install) init starts that read in+ * the background; until it lands, or if the OS read fails and only the hostname fallback is known,+ * the token is trusted provisionally on everything but the machine. A slow or failed boot-time read+ * must never drop a legacy user to FREE and push them into a claim (which could rebind their+ * allowance to the wrong hash). Once an OS hash is known the machine check applies. A successful+ * claim also caches the hash it sent, if that one came from the OS.+ *+ * CLAIMS are lazy and never reject: one request shared by concurrent callers, an 8 s timeout over+ * the whole request including the body, and every failure folded into a `ClaimError`.+ *+ * `projectLimit:changed` goes to THIS machine's windows only, through the shell's `notify`. Never+ * `platform().broadcast`: on the desktop that fans out to every relay peer, and this state carries+ * the host's Pro and DO_NOT_TRACK facts (see HOST_ONLY_CHANNEL_PREFIXES for the inbound half).+ *+ * PERSISTENCE: `<userData>/project-limit.json`, written through `writeFileAtomic`, only when+ * something changed. A missing, unparsable or hand-edited file never throws: each wrong-typed+ * field is dropped on its own.+ */+import { readFileSync } from 'fs'+import path from 'path'+import { platform } from './platform'+import { IPC } from '../shared/ipc'+import {+ PROJECT_LIMIT_DEADLINE_MS,+ PROJECT_LIMIT_DEFAULT_FREE,+ type ClaimError,+ type ClaimResult,+ type ProjectLimitState+} from '../shared/project-limit'+import { clockAnchorMs, isDntEnv, licenseNetworkGate, proForProjectLimit } from './license'+import { getDeviceId } from './device-id'+import { fetchCheck, onCheckAnswer, type LimitsAnswer } from './check'+import { verifyAllowanceToken } from './project-allowance-token'+import { writeFileAtomic } from './fs-atomic'+import type { MachineHashResult } from './machine-id'++// The same base license.ts and check.ts use (a local server via NODETERM_API_BASE in development).+const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'++/** How long a server "off" keeps the embedded deadline from switching the limit on. */+export const OFF_TRUST_MS = 24 * 60 * 60 * 1000+/** The whole claim request, body included (see license.ts REQUEST_TIMEOUT_MS for why the body). */+const CLAIM_TIMEOUT_MS = 8000+/** The check feed is re-read on this cadence; it is cached, so it adds no traffic of its own. */+const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000+/** The server's own bounds: FREE in 1..1000 (check.ts), a first-launch count in 0..10000 (claim+ * route — anything larger is a 400, which would fail every claim). */+const FREE_MAX = 1000+const COUNT_MAX = 10_000++/** `<userData>/project-limit.json`. Every field is optional; see `load` for how each is read. */+interface Stored {+ latched?: boolean+ offAt?: number+ free?: number+ epoch?: number+ token?: string+ firstLaunchOpenCount?: number+}++export interface ProjectLimitDeps {+ /** `WorkspaceStore.openProjectCount` — undefined = unknown, never recorded or sent as 0. */+ openProjects: () => number | undefined+ /** `readMachineHashResult` (machine-id.ts). Read lazily: only by a claim, or at init when a+ * token is already stored. */+ machineHash: () => Promise<MachineHashResult>+ /** The allowance public key; defaults to the shipped one. Tests pass their own. */+ publicKeyPem?: string+ /** Deliver the new state to this machine's own windows — never to relay peers. */+ notify: (s: ProjectLimitState) => void+}++export interface ProjectLimitHandle {+ /** The current state. Synchronous and offline. */+ state(): ProjectLimitState+ /** Ask the server for this device's allowance. Never rejects. */+ claim(): Promise<ClaimResult>+ /** Re-send the state (a license or settings change can alter it with nothing here noticing). */+ refresh(): void+}++const isInt = (v: unknown): v is number => Number.isSafeInteger(v)+const isCount = (v: unknown): v is number => isInt(v) && v >= 0+const isFree = (v: unknown): v is number => isInt(v) && v >= 1 && v <= FREE_MAX+const isEpoch = (v: unknown): v is number => isInt(v) && v >= 1+const isRecord = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v)++let deps: ProjectLimitDeps+let stored: Stored = {}+/** The machine hash from a successful OS read; null = none yet (provisional trust, see header). */+let osMachine: string | null = null+let claimInFlight: Promise<ClaimResult> | null = null+let writes: Promise<void> = Promise.resolve()+/** Background reads and writes, so tests can wait for them (`__projectLimitIdleForTests`). */+const pending = new Set<Promise<unknown>>()++function track<T>(p: Promise<T>): Promise<T> {+ pending.add(p)+ const done = (): void => {+ pending.delete(p)+ }+ p.then(done, done)+ return p+}++function file(): string {+ return path.join(platform().userDataDir, 'project-limit.json')+}++function load(): Stored {+ let raw: unknown+ try {+ raw = JSON.parse(readFileSync(file(), 'utf-8'))+ } catch {+ return {}+ }+ if (!isRecord(raw)) return {}+ const s: Stored = {}+ if (typeof raw.latched === 'boolean') s.latched = raw.latched+ if (isCount(raw.offAt)) s.offAt = raw.offAt+ if (isFree(raw.free)) s.free = raw.free+ if (isEpoch(raw.epoch)) s.epoch = raw.epoch+ if (typeof raw.token === 'string' && raw.token) s.token = raw.token+ if (isCount(raw.firstLaunchOpenCount)) s.firstLaunchOpenCount = raw.firstLaunchOpenCount+ return s+}++/** Queue a write of the CURRENT record: the writes run in order and each serializes `stored` when+ * it runs, so the last one to land always carries the newest state. A failed write is logged and+ * the in-memory state stands. */+function persist(): Promise<void> {+ writes = writes+ .then(() => writeFileAtomic(file(), JSON.stringify(stored)))+ .catch((err) => console.warn('[project-limit] save failed', err instanceof Error ? err.message : String(err)))+ return track(writes)+}++function isActive(): boolean {+ if (!platform().isPackaged) return false+ if (stored.latched) return true+ const anchor = clockAnchorMs()+ return anchor >= PROJECT_LIMIT_DEADLINE_MS && !(stored.offAt !== undefined && anchor - stored.offAt < OFF_TRUST_MS)+}++function allowance(): number | null {+ if (!stored.token) return null+ const v = verifyAllowanceToken(+ stored.token,+ { deviceId: getDeviceId(), machine: osMachine, epoch: stored.epoch },+ deps.publicKeyPem+ )+ return v ? v.allowance : null+}++function compute(): ProjectLimitState {+ return {+ active: isActive(),+ pro: proForProjectLimit(),+ free: stored.free ?? PROJECT_LIMIT_DEFAULT_FREE,+ allowance: allowance(),+ dnt: isDntEnv()+ }+}++/** The count at the first launch of a limit-capable build (spec §4's late-updater basis): the first+ * number `openProjects()` gives, kept for good. */+function recordFirstLaunchOpenCount(): void {+ if (stored.firstLaunchOpenCount !== undefined) return+ let n: number | undefined+ try {+ n = deps.openProjects()+ } catch {+ return+ }+ if (!isCount(n)) return+ stored = { ...stored, firstLaunchOpenCount: n }+ void persist()+}++function state(): ProjectLimitState {+ recordFirstLaunchOpenCount()+ return compute()+}++function notify(): void {+ deps.notify(state())+}++/** Install `next`, save it when `save`, and tell this machine's windows if what they see changed. */+function commit(next: Stored, save: boolean): Promise<void> {+ const before = JSON.stringify(compute())+ stored = next+ const saved = save ? persist() : Promise.resolve()+ if (JSON.stringify(compute()) !== before) notify()+ return saved+}++/** The epoch a token says it was issued under, read WITHOUT verifying it. Used only to decide that+ * a newer epoch retires it — deleting is the safe direction: the next open past FREE re-claims. */+function tokenEpoch(token: string): number | null {+ const dot = token.indexOf('.')+ if (dot < 1) return null+ try {+ const payload: unknown = JSON.parse(Buffer.from(token.slice(0, dot), 'base64url').toString('utf-8'))+ return isRecord(payload) && isInt(payload.epoch) ? payload.epoch : null+ } catch {+ return null+ }+}++/** One check answer. Idempotent: the same answer twice changes nothing the second time. */+function onAnswer(a: LimitsAnswer): void {+ if (a.kind === 'on') {+ const next: Stored = { ...stored, latched: true, free: a.free, epoch: a.epoch }+ if (next.token !== undefined && tokenEpoch(next.token) !== a.epoch) delete next.token+ const changed =+ stored.latched !== true || stored.free !== a.free || stored.epoch !== a.epoch || stored.token !== next.token+ void commit(next, changed)+ } else if (a.kind === 'off') {+ const offAt = clockAnchorMs()+ // offAt only matters while `anchor - offAt < OFF_TRUST_MS` with `anchor >= deadline`, i.e. when+ // it is later than `deadline - OFF_TRUST_MS`. An earlier one can never change `active`, so it is+ // kept in memory but not written: a dormant install does not rewrite the file on every check.+ const save = stored.latched === true || offAt > PROJECT_LIMIT_DEADLINE_MS - OFF_TRUST_MS+ void commit({ ...stored, latched: false, offAt }, save)+ }+ // 'unknown' changes nothing: a reply that did not come from the route must not move the latch.+}++function fail(error: ClaimError, retryAfter?: number): ClaimResult {+ return retryAfter === undefined+ ? { ok: false, error, state: state() }+ : { ok: false, error, retryAfter, state: state() }+}++async function runClaim(): Promise<ClaimResult> {+ const gate = licenseNetworkGate()+ if (gate !== 'ok') return fail(gate)+ recordFirstLaunchOpenCount()+ const deviceId = getDeviceId()+ const machine = await deps.machineHash()+ const count = stored.firstLaunchOpenCount+ const ctrl = new AbortController()+ const timer = setTimeout(() => ctrl.abort(), CLAIM_TIMEOUT_MS)+ let status: number+ let body: unknown+ try {+ const res = await fetch(`${API_BASE}/v1/limits/claim`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ deviceId,+ machine: machine.hash,+ firstLaunchOpenCount: count === undefined ? null : Math.min(count, COUNT_MAX)+ }),+ signal: ctrl.signal+ })+ status = res.status+ try {+ body = await res.json()+ } catch {+ // A body cut off by the timeout is the network failing; one that is not JSON is the server's.+ if (ctrl.signal.aborted) return fail('offline')+ body = undefined+ }+ } catch {+ return fail('offline')+ } finally {+ // Cleared only once the body has been read: see CLAIM_TIMEOUT_MS.+ clearTimeout(timer)+ }+ const b = isRecord(body) ? body : {}+ if (status >= 200 && status < 300) {+ const { token, free, epoch } = b+ if (typeof token !== 'string' || !isFree(free) || !isEpoch(epoch)) return fail('server')+ // A 2xx is only an allowance if its token is one: signed, for this device, the machine we sent+ // and the epoch the reply states.+ if (!verifyAllowanceToken(token, { deviceId, machine: machine.hash, epoch }, deps.publicKeyPem)) {+ return fail('server')+ }+ if (machine.fromOs) osMachine = machine.hash+ await commit({ ...stored, latched: true, free, epoch, token }, true)+ return { ok: true, state: state() }+ }+ if (status === 409 && b.error === 'not_active') {+ const next: Stored = { ...stored, latched: false, offAt: clockAnchorMs() }+ delete next.token+ await commit(next, true)+ return { ok: true, state: state() }+ }+ if (status === 409 && b.error === 'machine_mismatch') {+ return fail('machine_mismatch', isCount(b.retryAfter) && b.retryAfter > 0 ? b.retryAfter : undefined)+ }+ // 429 (rate limited), 5xx, 400, 404 (claims disabled server-side), an unknown 409: never a final answer.+ return fail('server')+}++function claim(): Promise<ClaimResult> {+ if (!claimInFlight) {+ const run = runClaim().catch((err): ClaimResult => {+ console.warn('[project-limit] claim failed', err instanceof Error ? err.message : String(err))+ return fail('server')+ })+ claimInFlight = run.finally(() => {+ claimInFlight = null+ })+ }+ return claimInFlight+}++export function initProjectLimit(d: ProjectLimitDeps): ProjectLimitHandle {+ deps = d+ stored = load()+ osMachine = null+ claimInFlight = null+ const handle: ProjectLimitHandle = { state, claim, refresh: notify }+ platform().handle(IPC.projectLimitState, () => handle.state())+ platform().handle(IPC.projectLimitClaim, () => handle.claim())+ onCheckAnswer(onAnswer)++ // Only once a token is stored (post-flip): a dormant install never reads the machine id.+ if (stored.token) {+ track(+ deps+ .machineHash()+ .then((m) => {+ if (!m.fromOs) return+ osMachine = m.hash+ notify()+ })+ .catch(() => {})+ )+ }++ const readCheck = (): void => {+ track(fetchCheck().catch(() => {}))+ }+ readCheck()+ setInterval(readCheck, CHECK_INTERVAL_MS).unref()+ return handle+}++/** TEST ONLY: resolves once every background read and write started so far has settled. */+export async function __projectLimitIdleForTests(): Promise<void> {+ while (pending.size) await Promise.allSettled([...pending])+}++/** TEST ONLY: the machine hash stored tokens are judged against (null = provisional trust). */+export function __projectLimitMachineForTests(): string | null {+ return osMachine+}diff --git a/src/main/index.ts b/src/main/index.tsindex e68310ab8..a49975999 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -376,6 +376,8 @@ import {import { remoteCodexUsageTargets } from '../core/usage/remote-codex-usage'import { remoteUsageTargets } from '../core/usage/remote-claude-usage'import { initLicense, isPremium, getStoredEntitlement } from '../core/license'+import { initProjectLimit } from '../core/project-limit'+import { readMachineHashResult } from '../core/machine-id'import { WhisperModelStore } from '../core/speech/whisper-models'import { SpeechService } from '../core/speech/speech-service'import { registerSpeechIpc } from '../core/speech/register-ipc'@@ -4882,9 +4884,22 @@ app.whenReady().then(async () => {buildMirrorUsage(usageService.snapshot(), settingsStore.get().claudeAccounts ?? [], Date.now()))initTelemetry(() => settingsStore.get())+ // The free-tier open-project limit (core/project-limit.ts). Its state goes to THIS machine's+ // window only: sendToMain, never platform().broadcast, which also fans out to every relay peer+ // (the state carries this host's Pro and DO_NOT_TRACK facts). The Server Edition does not run it.+ const projectLimit = initProjectLimit({+ openProjects: () => workspaceStore.openProjectCount(),+ machineHash: readMachineHashResult,+ notify: (s) => sendToMain(IPC.projectLimitChanged, s)+ })+ settingsStore.onChange(() => projectLimit.refresh())// A license change (activate, refresh, a lapsed token replaced) re-arms every live link the API// refused: a link host whose 7-day entitlement expired under it stops minting until then (R41).- initLicense(() => watchLinks?.onEntitlementChanged())+ // It can also change Pro for the project limit, which nothing else would tell the renderer.+ initLicense(() => {+ watchLinks?.onEntitlementChanged()+ projectLimit.refresh()+ })// Lazy getter: sshProjectManager is created just below, so a remote account op (which only runs// after the user has connected an SSH project) always sees the live manager.initClaudeAccounts(() => sshProjectManager)diff --git a/src/main/project-limit-wiring.test.ts b/src/main/project-limit-wiring.test.tsnew file mode 100644index 000000000..073b40da2--- /dev/null+++ b/src/main/project-limit-wiring.test.ts@@ -0,0 +1,106 @@+// `projectLimit:changed` must reach this machine's window and NO relay peer: the state carries the+// host's Pro and DO_NOT_TRACK facts, and a peer's own tab keeps its local preload anyway. Nothing+// type-checks which sender main hands core, so the wiring is pinned at source level (the house+// remedy, see dev-ports-wiring.test.ts) and then driven for real: the actual Electron platform, the+// actual `sendToMain`, and a registered relay peer that must hear nothing.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { IPC } from '../shared/ipc'+import type { ProjectLimitState } from '../shared/project-limit'++const h = vi.hoisted(() => ({ userData: '' }))++vi.mock('electron', () => ({+ app: { getPath: () => h.userData, getVersion: () => '9.9.9', isPackaged: true },+ ipcMain: { handle: () => {}, on: () => {} },+ webContents: { fromId: () => undefined },+ shell: { openExternal: async () => {} },+ safeStorage: {}+}))++const read = (p: string): string => fs.readFileSync(path.join(__dirname, '..', p), 'utf8').replace(/\r\n/g, '\n')++describe('project-limit wiring (source)', () => {+ const main = read('main/index.ts')++ it("main sends the state to its own window, with the workspace count and the OS-aware machine read", () => {+ expect(main).toMatch(+ /initProjectLimit\(\{\s*openProjects: \(\) => workspaceStore\.openProjectCount\(\),\s*machineHash: readMachineHashResult,\s*notify: \(s\) => sendToMain\(IPC\.projectLimitChanged, s\)\s*\}\)/+ )+ })++ it('a license change and a settings change both re-send it', () => {+ expect(main).toMatch(/initLicense\(\(\) => \{\s*watchLinks\?\.onEntitlementChanged\(\)\s*projectLimit\.refresh\(\)\s*\}\)/)+ expect(main).toMatch(/settingsStore\.onChange\(\(\) => projectLimit\.refresh\(\)\)/)+ })++ it('nothing broadcasts the channel, and the Server Edition does not run the module', () => {+ for (const p of ['main/index.ts', 'core/project-limit.ts', 'server/index.ts']) {+ expect(read(p)).not.toMatch(/broadcast\(IPC\.projectLimitChanged/)+ }+ expect(read('server/index.ts')).not.toMatch(/initProjectLimit/)+ })+})++describe('project-limit wiring (relay peer)', () => {+ const PEER = 1_000_000 // allocateRelayClientId() mints peer ids from here++ beforeEach(() => {+ h.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-plwire-'))+ vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('fetch failed'))))+ })++ afterEach(async () => {+ const { peerRegistry, unregisterPeerSink } = await import('./peer-registry')+ for (const id of peerRegistry().ids()) unregisterPeerSink(id)+ const { resetPlatformForTests } = await import('../core/platform')+ resetPlatformForTests()+ const { __projectLimitIdleForTests } = await import('../core/project-limit')+ await __projectLimitIdleForTests()+ vi.unstubAllGlobals()+ fs.rmSync(h.userData, { recursive: true, force: true })+ })++ it('a registered relay peer receives no projectLimit:changed; the main window does', async () => {+ const { electronPlatform } = await import('./platform-electron')+ const { initPlatform, platform } = await import('../core/platform')+ const { setMainWindow, sendToMain } = await import('./main-window')+ const { registerPeerSink, wirePeerRegistry } = await import('./peer-registry')+ const { initProjectLimit } = await import('../core/project-limit')++ initPlatform(electronPlatform())+ const toWindow: Array<[string, unknown]> = []+ setMainWindow({+ isDestroyed: () => false,+ isFocused: () => true,+ isMinimized: () => false,+ restore: () => {},+ show: () => {},+ focus: () => {},+ on: () => {},+ webContents: { id: 1, send: (ch: string, arg: unknown) => toWindow.push([ch, arg]) }+ })+ wirePeerRegistry({ setFlow: () => {}, captureForResync: async () => '', onPeerGone: () => {} })+ const toPeer: string[] = []+ registerPeerSink(PEER, { sendText: (json) => toPeer.push(json), sendBinary: () => {}, bufferedAmount: () => 0 })++ // Exactly the lambda main/index.ts passes (pinned by the source test above).+ const projectLimit = initProjectLimit({+ openProjects: () => 2,+ machineHash: async () => ({ hash: 'x'.repeat(64), fromOs: true }),+ notify: (s) => sendToMain(IPC.projectLimitChanged, s)+ })+ projectLimit.refresh()++ const sent = toWindow.filter(([ch]) => ch === IPC.projectLimitChanged)+ expect(sent).toHaveLength(1)+ expect((sent[0][1] as ProjectLimitState).active).toBe(false)+ expect(toPeer.some((json) => json.includes(IPC.projectLimitChanged))).toBe(false)++ // The control: the same peer DOES hear a platform broadcast, so its silence above is the wiring.+ platform().broadcast('test:probe', 1)+ expect(toPeer.some((json) => json.includes('test:probe'))).toBe(true)+ })+})