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(license): token-authorized detail + release-others across the bridge
enes592093987e7f
diff --git a/src/core/license.test.ts b/src/core/license.test.tsindex 687fdce6a..74ed77896 100644--- a/src/core/license.test.ts+++ b/src/core/license.test.ts@@ -5,7 +5,7 @@ import { promises as fsp } from 'fs'import { tmpdir } from 'os'import path from 'path'import { IPC } from '../shared/ipc'-import type { LicenseStatus } from '../shared/types'+import type { LicenseDetail, LicenseStatus } from '../shared/types'// One temp userData dir per run; hoisted so the entitlement-key mock factory can see it.const h = vi.hoisted(() => ({@@ -375,3 +375,266 @@ describe('license seats entitlement', () => {}})})++describe('license detail + release', () => {+ let fake: import('./platform-fake').FakePlatform++ beforeEach(async () => {+ vi.useFakeTimers({ toFake: ['setInterval', 'Date'] })+ h.userData = mkdtempSync(path.join(tmpdir(), 'nt-license-detail-'))+ writeFileSync(path.join(h.userData, 'device-id'), 'test-device')+ delete process.env.DO_NOT_TRACK+ delete process.env.NODETERM_TELEMETRY_DISABLED+ process.env.NODETERM_API_BASE = 'http://127.0.0.1:1'+ // The launch refresh must not succeed here: rejecting it keeps the stored token intact+ // (offline grace) so every assertion below runs against the token the test wrote.+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')))+ vi.resetModules()+ const { initPlatform } = await import('./platform')+ const { fakePlatform } = await import('./platform-fake')+ fake = fakePlatform({ userDataDir: h.userData, isPackaged: false })+ initPlatform(fake)+ })++ afterEach(async () => {+ vi.unstubAllGlobals()+ vi.useRealTimers()+ const { resetPlatformForTests } = await import('./platform')+ resetPlatformForTests()+ delete process.env.DO_NOT_TRACK+ rmSync(h.userData, { recursive: true, force: true })+ })++ const TOKEN = mint(HOUR / 1000)++ function storeToken(token = TOKEN): void {+ writeFileSync(path.join(h.userData, 'license.json'), JSON.stringify({ token }))+ }++ /** Non-2xx reply shaped like our API's error bodies. */+ function errorResponse(status: number, body: unknown): {+ ok: boolean+ status: number+ json: () => Promise<unknown>+ } {+ return { ok: false, status, json: async () => body }+ }++ /**+ * Boot the service, let its launch refresh SETTLE, and only then install the fetch mock the+ * assertions are about. initLicense() fires an un-awaited refresh; installing the mock first+ * would make `mock.calls[0]` that refresh — so a handler that never called fetch at all could+ * still satisfy a "the request carried X" assertion.+ */+ async function boot(fetchMock: ReturnType<typeof vi.fn>): Promise<void> {+ const { initLicense } = await import('./license')+ initLicense()+ await refreshed()+ vi.stubGlobal('fetch', fetchMock)+ }++ const detail = (): Promise<LicenseDetail> =>+ fake.handlers[IPC.licenseDetail]() as Promise<LicenseDetail>+ const release = (): Promise<LicenseDetail> =>+ fake.handlers[IPC.licenseRelease]() as Promise<LicenseDetail>++ it('sends the stored entitlement token, never a deviceId', async () => {+ storeToken()+ const fetchMock = vi.fn(async (_url: string, _init: { method: string; body: string }) =>+ jsonResponse({ key: 'KEY-ABC', used: 2, seats: 3, source: 'keygen' })+ )+ await boot(fetchMock)++ expect(await detail()).toEqual({+ key: 'KEY-ABC',+ used: 2,+ seats: 3,+ source: 'keygen',+ error: null+ })++ expect(fetchMock).toHaveBeenCalledTimes(1)+ const [url, init] = fetchMock.mock.calls[0]+ expect(String(url)).toContain('/v1/license/detail')+ // A key works on ANY machine, so the request that reveals one is authorized by the signed+ // entitlement and by nothing else. deviceId rides query strings, telemetry and relay pairing.+ expect(String(url)).not.toContain(TOKEN)+ expect(init.method).toBe('POST')+ const body = JSON.parse(init.body) as Record<string, unknown>+ expect(body.entitlement).toBe(TOKEN) // the stored token itself, not merely "something truthy"+ expect(Object.keys(body)).toEqual(['entitlement']) // …and nothing else travels with it+ })++ it('release posts to its own route, not to detail', async () => {+ storeToken()+ const fetchMock = vi.fn(async (_url: string, _init: { body: string }) =>+ jsonResponse({ used: 1, seats: 3 })+ )+ await boot(fetchMock)++ const r = await release()+ expect(r.error).toBeNull()+ expect(r.used).toBe(1)+ const [url, init] = fetchMock.mock.calls[0]+ expect(String(url)).toContain('/v1/license/release')+ expect(String(url)).not.toContain('/v1/license/detail')+ expect((JSON.parse(init.body) as { entitlement: string }).entitlement).toBe(TOKEN)+ })++ it('carries the source, so a non-keygen entitlement is not read as a failed count', async () => {+ // An App Store purchase on a paired phone bridges Pro to the desktop as `apple:<txn>`. The+ // server makes zero keygen calls for it and answers 200 with no key and no machines — those+ // zeros mean "device counting does not apply here", NOT "the read failed". `source` is the+ // only thing that tells the two apart, and the UI hides the release action on it.+ storeToken()+ await boot(vi.fn(async () => jsonResponse({ key: null, used: 0, seats: 0, source: 'apple' })))++ expect(await detail()).toEqual({+ key: null,+ used: 0,+ seats: 0,+ source: 'apple',+ error: null+ })+ })++ it('a 200 with key null is a success, not the 402 inactive story', async () => {+ // A keygen policy may hide keys, and licenses predating the `key` column have none stored.+ // Reporting that as a failure would tell a paying subscriber their license is inactive.+ storeToken()+ await boot(vi.fn(async () => jsonResponse({ key: null, used: 2, seats: 3, source: 'keygen' })))++ expect(await detail()).toEqual({ key: null, used: 2, seats: 3, source: 'keygen', error: null })+ })++ it('402 inactive is an error with no source claimed', async () => {+ storeToken()+ await boot(vi.fn(async () => errorResponse(402, { error: 'inactive' })))++ expect(await detail()).toEqual({+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: 'inactive'+ })+ })++ it('401 unauthorized keeps the server-stated reason instead of a generic network error', async () => {+ storeToken()+ await boot(vi.fn(async () => errorResponse(401, { error: 'unauthorized' })))+ expect((await detail()).error).toBe('unauthorized')+ })++ it('reports an error instead of zero devices when the read fails', async () => {+ storeToken()+ await boot(+ vi.fn(async () => {+ throw new Error('down')+ })+ )++ expect(await detail()).toEqual({+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: 'offline'+ })+ })++ it('surfaces the 30-day throttle with its retry window', async () => {+ storeToken()+ await boot(vi.fn(async () => errorResponse(429, { error: 'too_soon', retryAfterDays: 12 })))++ // toEqual, not toMatchObject: the retry window is the whole point of this reply, and the+ // server side asserts only the error code — so if `retryAfterDays` is dropped anywhere+ // between the wire and the renderer, this is what fails.+ expect(await release()).toEqual({+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: 'too_soon',+ retryAfterDays: 12+ })+ })++ it('keeps not_applicable distinguishable from a plain bad request', async () => {+ // 'not_applicable' = this entitlement is not keygen-backed, so releasing means nothing. The+ // UI hides the action on `source`; this is the server-side floor under that, not a failure.+ storeToken()+ await boot(vi.fn(async () => errorResponse(400, { error: 'not_applicable' })))+ expect((await release()).error).toBe('not_applicable')++ vi.stubGlobal('fetch', vi.fn(async () => errorResponse(400, { error: 'bad_request' })))+ expect((await release()).error).toBe('bad_request')+ })++ it('an error body with no reason code falls back to network, and never to success', async () => {+ storeToken()+ await boot(vi.fn(async () => errorResponse(500, {})))+ expect((await detail()).error).toBe('network')+ })++ it('reports used above seats verbatim — a cap can be lowered after activation', async () => {+ storeToken()+ await boot(vi.fn(async () => jsonResponse({ key: 'K', used: 5, seats: 3, source: 'keygen' })))++ const d = await detail()+ expect(d.used).toBe(5) // never clamped to the cap: over-cap is a real, reportable state+ expect(d.seats).toBe(3)+ })++ it('accepts only real numbers as counts, so nothing renders as NaN or as a string', async () => {+ // The contract says numbers. A body that says otherwise is malformed, and `json.used ?? 0`+ // would forward whatever it holds — "3" into a meter, or NaN out of arithmetic on it.+ storeToken()+ await boot(vi.fn(async () => jsonResponse({ key: 'K', used: '3', seats: null, source: 'keygen' })))++ const d = await detail()+ expect(d.used).toBe(0)+ expect(d.seats).toBe(0)+ })++ it('refuses to call the server with no stored entitlement', async () => {+ // No license.json at all.+ const fetchMock = vi.fn()+ await boot(fetchMock)++ expect(await detail()).toEqual({+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: 'unauthorized'+ })+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('honors the telemetry kill switch without inventing a device count', async () => {+ storeToken()+ const fetchMock = vi.fn(async () => jsonResponse({ key: 'K', used: 2, seats: 3, source: 'keygen' }))+ await boot(fetchMock)+ process.env.DO_NOT_TRACK = '1'++ expect(await detail()).toEqual({+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: 'disabled'+ })+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('ignores a source it does not recognize rather than passing it through', async () => {+ // The value decides whether a destructive-ish action is offered, so an unknown word degrades+ // to "no source stated" (the action stays hidden) instead of reaching the UI as data.+ storeToken()+ await boot(+ vi.fn(async () => jsonResponse({ key: 'K', used: 1, seats: 3, source: 'paddle' }))+ )+ expect((await detail()).source).toBeNull()+ })+})diff --git a/src/core/license.ts b/src/core/license.tsindex e8a7a7b15..2dff0f53a 100644--- a/src/core/license.ts+++ b/src/core/license.ts@@ -8,7 +8,7 @@ import path from 'path'import crypto from 'node:crypto'import { platform } from './platform'import { IPC } from '../shared/ipc'-import type { LicenseStatus } from '../shared/types'+import type { LicenseDetail, LicenseSource, LicenseStatus } from '../shared/types'import { getDeviceId } from './device-id'import { ENTITLEMENT_PUBLIC_KEY } from './entitlement-key'@@ -106,6 +106,23 @@ function seatsFrom(p: Payload | null): number {return p ? Math.max(PRO_FREE_SEATS, p.seats ?? PRO_FREE_SEATS) : 0}+/** Every failure answers with this shape plus a reason code: zeros that are NEVER a device count.+ * The renderer must read `error` first — "we could not look" and "you have no devices" are+ * different facts, and rendering the first as the second is the bug this whole route exists for. */+const EMPTY_DETAIL: LicenseDetail = { key: null, used: 0, seats: 0, source: null, error: null }++const LICENSE_SOURCES: readonly string[] = ['keygen', 'apple', 'free']++/** The source decides whether the UI offers "release other devices" at all, so an unrecognized+ * word degrades to "none stated" (action hidden) rather than reaching the renderer as data. */+function licenseSourceOf(v: unknown): LicenseSource | null {+ return typeof v === 'string' && LICENSE_SOURCES.includes(v) ? (v as LicenseSource) : null+}++function countOf(v: unknown): number {+ return typeof v === 'number' && Number.isFinite(v) ? v : 0+}+function statusFrom(token: string | undefined, error: string | null = null): LicenseStatus {const p = verify(token)return p@@ -207,6 +224,60 @@ export function initLicense(onChange?: () => void): void {platform().handle(IPC.licenseStatus, () => statusFrom(load().token))+ // Both routes are authorized by the stored entitlement token. Sending a deviceId instead would+ // hand a key — which works on ANY machine — to whoever learned an id that rides query strings,+ // telemetry and relay pairing. The token is the only credential on the wire here, and it goes+ // in the BODY, never the URL.+ const licenseCall = async (route: string): Promise<LicenseDetail> => {+ const token = load().token+ if (!token) return { ...EMPTY_DETAIL, error: 'unauthorized' }+ if (!allowed()) return { ...EMPTY_DETAIL, error: 'disabled' }+ try {+ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), 8000)+ const res = await fetch(`${API_BASE}${route}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ entitlement: token }),+ signal: ctrl.signal+ }).finally(() => clearTimeout(t))+ const json = (await res.json().catch(() => ({}))) as {+ key?: unknown+ used?: unknown+ seats?: unknown+ source?: unknown+ error?: unknown+ retryAfterDays?: unknown+ }+ if (!res.ok) {+ // The server's own reason code (401 unauthorized / 402 inactive / 429 too_soon /+ // 400 not_applicable) is kept verbatim: the UI tells those four apart. `retryAfterDays`+ // rides only 429 and is the whole content of that answer.+ const days = countOf(json.retryAfterDays)+ return {+ ...EMPTY_DETAIL,+ error: typeof json.error === 'string' && json.error ? json.error : 'network',+ ...(days > 0 ? { retryAfterDays: days } : {})+ }+ }+ return {+ // `key: null` on a 200 is a real state (a keygen policy that hides keys, a license older+ // than the column, a non-keygen source) — a success, not a failed read.+ key: typeof json.key === 'string' ? json.key : null,+ // Never clamped against seats: a cap lowered after activation makes used > seats real.+ used: countOf(json.used),+ seats: countOf(json.seats),+ source: licenseSourceOf(json.source),+ error: null+ }+ } catch {+ return { ...EMPTY_DETAIL, error: 'offline' }+ }+ }++ platform().handle(IPC.licenseDetail, () => licenseCall('/v1/license/detail'))+ platform().handle(IPC.licenseRelease, () => licenseCall('/v1/license/release'))+// Device-bound upgrade: open Stripe checkout (carrying our deviceId), then poll the status// endpoint until the webhook has bound + minted the entitlement. Status arrives via broadcast.let polling = falsediff --git a/src/preload/index.ts b/src/preload/index.tsindex f4072ed00..86e2fa173 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -370,6 +370,8 @@ const api: NodeTerminalApi = {activate: (key: string) => ipcRenderer.invoke(IPC.licenseActivate, key),deactivate: () => ipcRenderer.invoke(IPC.licenseDeactivate),getStatus: () => ipcRenderer.invoke(IPC.licenseStatus),+ detail: () => ipcRenderer.invoke(IPC.licenseDetail),+ releaseOthers: () => ipcRenderer.invoke(IPC.licenseRelease),onChange: (listener) => {const handler = (_e: unknown, s: Parameters<typeof listener>[0]) => listener(s)ipcRenderer.on(IPC.licenseChanged, handler)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 9e8bee22e..4293bf60e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -220,6 +220,10 @@ export function buildStubApi(): Omit<deactivate: U('license.deactivate'),// Renderer has no catch here and silently degrades to the free tier on rejection.getStatus: U('license.getStatus'),+ // Server Edition has no license layer at all (initLicense runs only in src/main), so these+ // reject rather than answer a fabricated "0 devices" — the same degrade as getStatus above.+ detail: U('license.detail'),+ releaseOthers: U('license.releaseOthers'),onChange: noopUnsub},contextLink: {diff --git a/src/renderer/state/entitlement.ts b/src/renderer/state/entitlement.tsindex d107af416..051a301a5 100644--- a/src/renderer/state/entitlement.ts+++ b/src/renderer/state/entitlement.ts@@ -1,5 +1,5 @@import { create } from 'zustand'-import type { LicenseStatus } from '@shared/types'+import type { LicenseDetail, LicenseStatus } from '@shared/types'interface EntitlementState {status: LicenseStatus@@ -8,17 +8,33 @@ interface EntitlementState {/** Team seat cap (premium → max(3, N), premium-no-field → 3 = Pro's free seats, free/inactive* → 0). Mirrors `status.seats` so the Team seats section can select it directly. */seats: number+ /** The license key + device usage, or null before the first read. `detail.error` is the read's+ * verdict: non-null means we could not look, and its zeros are NOT a device count. */+ detail: LicenseDetail | nullhydrate(): Promise<void>/** Open Stripe checkout for this device; Pro arrives via onChange when the purchase lands.* `target: 'seats'` opens the add-seats (quantity) link instead of base Pro. */upgrade(target?: 'pro' | 'seats'): Promise<void>activate(key: string): Promise<void>deactivate(): Promise<void>+ /** Read the key + device usage (token-authorized). Replaces `detail` wholesale — it is the one+ * call that states every field. */+ loadDetail(): Promise<void>+ /** Deactivate every other device on this license, then fold the new counts into `detail`. */+ releaseOthers(): Promise<void>}const EMPTY: LicenseStatus = { tier: null, active: false, expiresAt: null, seats: 0, error: null }-export const useEntitlement = create<EntitlementState>((set) => {+const EMPTY_DETAIL: LicenseDetail = {+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: null+}++export const useEntitlement = create<EntitlementState>((set, get) => {const apply = (status: LicenseStatus) =>set({ status, isPremium: status.active, seats: status.seats })// Live updates from the main process (launch refresh, offline grace).@@ -27,6 +43,7 @@ export const useEntitlement = create<EntitlementState>((set) => {status: EMPTY,isPremium: false,seats: 0,+ detail: null,async hydrate() {apply(await window.nodeTerminal.license.getStatus())},@@ -38,6 +55,22 @@ export const useEntitlement = create<EntitlementState>((set) => {},async deactivate() {apply(await window.nodeTerminal.license.deactivate())+ },+ async loadDetail() {+ set({ detail: await window.nodeTerminal.license.detail() })+ },+ async releaseOthers() {+ const r = await window.nodeTerminal.license.releaseOthers()+ const prev = get().detail ?? EMPTY_DETAIL+ // The release route answers with COUNTS ONLY — no key, no source. Replacing `detail`+ // wholesale would blank the key the user came to this screen to copy, and drop the source+ // that decides whether this action is offered at all. And a FAILED release changed nothing+ // on the server, so its zeroed counts must not land either: only the reason code rides.+ set({+ detail: r.error+ ? { ...prev, error: r.error, retryAfterDays: r.retryAfterDays }+ : { ...prev, used: r.used, seats: r.seats, error: null, retryAfterDays: undefined }+ })}}})diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 656201acb..fea44ee81 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -158,6 +158,8 @@ export const IPC = {licenseStatus: 'license:status',licenseChanged: 'license:changed',licenseUpgrade: 'license:upgrade',+ licenseDetail: 'license:detail',+ licenseRelease: 'license:release',appRestartToUpdate: 'app:restart-to-update',announcementsFetch: 'announcements:fetch',usageFetch: 'usage:fetch',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 35a79298b..5015da94b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2122,6 +2122,35 @@ export interface LicenseStatus {error: string | null}+/**+ * Where the entitlement behind this install came from. A verified entitlement's licenseId is NOT+ * always a keygen license id: an App Store purchase on a paired phone bridges Pro to the desktop+ * and mints `apple:<txn>`, and `free:` exists too. For those the server makes zero keygen calls+ * and answers `key: null, used: 0, seats: 0` — genuinely "device counting does not apply here",+ * which is a different fact from a failed read and from a keygen license with no devices yet.+ */+export type LicenseSource = 'keygen' | 'apple' | 'free'++/** What Settings → License shows: the key to copy and how much of the device cap is in use.+ * A failed read is an ERROR, never "0 devices" — the two are different facts. */+export interface LicenseDetail {+ /** The license key to copy. `null` on a 200 is legitimate (a keygen policy that hides keys, a+ * license predating the column, a non-keygen source) — it is NOT an error. */+ key: string | null+ /** Devices currently activated. May EXCEED `seats` if a cap was lowered after activation. */+ used: number+ seats: number+ /** The source the server stated, or null when it stated none — every error reply, and the+ * release route's 200, which answers with counts only. Never inferred locally. */+ source: LicenseSource | null+ /** Null on success; a stable reason code otherwise ('unauthorized' | 'inactive' | 'offline' |+ * 'disabled' | 'too_soon' | 'not_applicable' | 'network'). A failed read is an error, never+ * "0 devices". */+ error: string | null+ /** Days until another release is allowed — only set with error === 'too_soon'. */+ retryAfterDays?: number+}+export interface LicenseApi {/** Open Stripe checkout bound to this device and poll for the entitlement (no key paste).* `target` picks the link: 'seats' = the add-seats (quantity) link, else base Pro (default).@@ -2135,6 +2164,13 @@ export interface LicenseApi {getStatus(): Promise<LicenseStatus>/** Fires when the license status changes. Returns unsubscribe. */onChange(listener: (s: LicenseStatus) => void): () => void+ /** The license key + device usage for this machine's license. Authorized by the stored+ * entitlement token — never by deviceId. */+ detail(): Promise<LicenseDetail>+ /** Deactivate every device on this license except this one. Throttled server-side to once+ * per 30 days (error 'too_soon' + retryAfterDays). Answers with COUNTS only: no key and no+ * source ride a successful release, so callers must merge rather than replace. */+ releaseOthers(): Promise<LicenseDetail>}export interface RemoteHostApi {