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): shared state, decision and IPC contract
reviewb6d325f2e050
diff --git a/src/preload/index.test.ts b/src/preload/index.test.tsindex 795da90ac..5cb24bfdd 100644--- a/src/preload/index.test.ts+++ b/src/preload/index.test.ts@@ -149,3 +149,28 @@ describe('preload canvasAuthority (the desktop governs nothing)', () => {expect(h.on).not.toHaveBeenCalled()})})++// The renderer's half of the project-limit contract. Main registers the handlers (core+// project-limit); the preload must invoke exactly these channels with no arguments — the claim's+// deviceId and machine hash are read by core itself, never supplied from the page.+describe('preload projectLimit wiring', () => {+ it('state and claim invoke their own channels with no arguments', async () => {+ h.invoke.mockClear()+ await api.projectLimit.state()+ await api.projectLimit.claim()+ expect(h.invoke.mock.calls).toEqual([[IPC.projectLimitState], [IPC.projectLimitClaim]])+ })++ it('onChange subscribes the change channel, forwards the state and unsubscribes', () => {+ const got: unknown[] = []+ const off = api.projectLimit.onChange((s) => got.push(s))+ const call = h.on.mock.calls.find((c) => c[0] === IPC.projectLimitChanged)+ expect(call).toBeTruthy()+ const handler = call![1] as (e: unknown, payload: unknown) => void+ const state = { active: true, pro: false, free: 5, allowance: 12, dnt: false }+ handler({}, state)+ expect(got).toEqual([state])+ off()+ expect(h.removeListener).toHaveBeenCalledWith(IPC.projectLimitChanged, handler)+ })+})diff --git a/src/preload/index.ts b/src/preload/index.tsindex 92e046f42..e033eea97 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -553,6 +553,17 @@ const api: NodeTerminalApi = {return () => ipcRenderer.removeListener(IPC.licenseChanged, handler)}},+ projectLimit: {+ // No arguments on purpose: core reads the deviceId and machine hash itself, so nothing the page+ // sends can name another device or machine.+ state: () => ipcRenderer.invoke(IPC.projectLimitState),+ claim: () => ipcRenderer.invoke(IPC.projectLimitClaim),+ onChange: (listener) => {+ const handler = (_e: unknown, s: Parameters<typeof listener>[0]) => listener(s)+ ipcRenderer.on(IPC.projectLimitChanged, handler)+ return () => ipcRenderer.removeListener(IPC.projectLimitChanged, handler)+ }+ },announcements: {fetch: () => ipcRenderer.invoke(IPC.announcementsFetch)},diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.tsindex 1cdea361d..3d0fb6f16 100644--- a/src/renderer/bridge/relay-api.test.ts+++ b/src/renderer/bridge/relay-api.test.ts@@ -51,6 +51,7 @@ function fakeLocalApi() {githubControl: { NAME: 'local-github-control' },dialog: { NAME: 'local-dialog' },license: { NAME: 'local-license' },+ projectLimit: { NAME: 'local-project-limit' },pty: { onData: ptyOnData },claude: { cliCaps: () => Promise.resolve({}), readTranscript: () => Promise.reject() },relayClient: { disconnect: vi.fn() }@@ -96,6 +97,8 @@ describe('buildRelayApi', () => {expect(api.clipboard).toBe(local.clipboard)expect(api.settings).toBe(local.settings)expect(api.license).toBe(local.license)+ // The free-project allowance is THIS machine's; the host refuses `projectLimit:*` from a peer.+ expect(api.projectLimit).toBe(local.projectLimit)expect(api.githubControl).toBe(local.githubControl)})diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex cc918f19c..9d6f855fa 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, afterEach } from 'vitest'import { buildStubApi, unsupported } from './stubs'import { E_UNSUPPORTED } from '../../shared/rpc'+import { INACTIVE_PROJECT_LIMIT } from '../../shared/project-limit'describe('bridge stubs', () => {it('unsupported rejects with a coded error', async () => {@@ -11,6 +12,7 @@ describe('bridge stubs', () => {const s = buildStubApi()for (const un of [s.license.onChange(() => {}),+ s.projectLimit.onChange(() => {}),s.onCloseNode(() => {}),s.onFocusNode(() => {}),s.browser.onBrowserNewWindow(() => {}),@@ -98,6 +100,16 @@ describe('bridge stubs', () => {await expect(s.license.releaseOthers()).rejects.toMatchObject({ code: E_UNSUPPORTED })})+ it('the project limit is inactive on the Server Edition: no gate, no claim', async () => {+ // Spec §10: the Server Edition has no gate. `state` answers the dormant default so every open+ // stays synchronous, and `claim` answers `disabled` instead of rejecting — a gate that somehow+ // reached it reads a typed refusal, never a thrown E_UNSUPPORTED it has no branch for.+ const s = buildStubApi()+ await expect(s.projectLimit.state()).resolves.toEqual(INACTIVE_PROJECT_LIMIT)+ await expect(s.projectLimit.claim()).resolves.toEqual({ ok: false, error: 'disabled', state: INACTIVE_PROJECT_LIMIT })+ expect((await s.projectLimit.state()).active).toBe(false)+ })+it('shell.openExternal opens a new browser tab; reveal/openPath are documented no-ops', () => {const s = buildStubApi()const open = vi.fn(() => null)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 27edcc4e4..928f306d9 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -27,6 +27,7 @@ import {type UpdatePolicy} from '../../shared/types'import { E_UNSUPPORTED } from '../../shared/rpc'+import { INACTIVE_PROJECT_LIMIT, type ClaimResult, type ProjectLimitState } from '../../shared/project-limit'import { isMacPlatform } from '../../shared/platform-utils'import { effectiveBindings, terminalShortcutPolicy } from '../lib/keybindingOverrides'import type { ContextElement } from '../lib/keyContext'@@ -283,6 +284,17 @@ export function buildStubApi(): Omit<releaseOthers: U('license.releaseOthers'),onChange: noopUnsub},+ projectLimit: {+ // Spec §10: the Server Edition has no open-project gate, so it answers the dormant state and+ // every open stays synchronous. Resolved, not rejected: unlike `license.getStatus`, this is+ // read on the open path, and "inactive" is the true answer here rather than "unknown".+ // `claim` answers `disabled` (this shell never talks to the license server) for the same+ // reason: a refusal `ClaimResult` names, where an E_UNSUPPORTED throw is outside the contract.+ state: (): Promise<ProjectLimitState> => Promise.resolve(INACTIVE_PROJECT_LIMIT),+ claim: (): Promise<ClaimResult> =>+ Promise.resolve({ ok: false, error: 'disabled', state: INACTIVE_PROJECT_LIMIT }),+ onChange: noopUnsub+ },contextLink: {setLinks: pnoop,info: U('contextLink.info')diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.tsindex f5553a5c8..242cf7025 100644--- a/src/shared/host-control.test.ts+++ b/src/shared/host-control.test.ts@@ -57,6 +57,17 @@ describe('isHostOnlyChannel', () => {expect(isHostOnlyChannel(IPC.stationNoticeList)).toBe(true)})+ it('covers the whole project-limit namespace — a relay peer must never read or claim the host’s allowance', () => {+ // A claim spends the HOST's per-device allowance on the host's machine hash, and the state names+ // the host's Pro and DNT facts. A relay tab keeps its own local preload for this namespace.+ expect(isHostOnlyChannel(IPC.projectLimitState)).toBe(true)+ expect(isHostOnlyChannel(IPC.projectLimitClaim)).toBe(true)+ expect(isHostOnlyChannel(IPC.projectLimitChanged)).toBe(true)+ expect(isHostOnlyChannel('projectLimit:claim')).toBe(true)+ // A namespace, not a list: a verb added later is refused the day it is added.+ expect(isHostOnlyChannel('projectLimit:something-new')).toBe(true)+ })+it('leaves the read-only/lifecycle channels alone — the gate is on ACTION, not on the namespace', () => {// Subscribing and receiving events costs a guest nothing the canvas does not already show;// running host code, and answering the host's own trust prompt, are the two acts being gated.diff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 12fbaba95..5b44229a8 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -51,6 +51,11 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = [// credentials into the account dir, removal deletes one), and account usage read with the// host's stored tokens.'license:',+ // The free-tier open-project allowance: a claim spends THIS device's allowance under this+ // machine's hash, and the state reports the host's Pro and DO_NOT_TRACK facts. A relay tab keeps+ // its own local preload for the namespace (relay-api.ts spreads `...local`), so only a peer+ // sending the raw request would ever reach these.+ 'projectLimit:','claude-accounts:','codex-accounts:','usage:',diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 136a643fd..088dffc61 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -371,6 +371,13 @@ export const IPC = {licenseUpgrade: 'license:upgrade',licenseDetail: 'license:detail',licenseRelease: 'license:release',+ // Free-tier open-project limit (src/shared/project-limit.ts). renderer → main (invoke): the+ // current `ProjectLimitState`, and a lazy allowance claim → `ClaimResult`. `projectLimitChanged`+ // is main → renderer with the new state. Host-only (`projectLimit:` in HOST_ONLY_CHANNEL_PREFIXES):+ // the allowance is this machine's, never a relay peer's to read or spend.+ projectLimitState: 'projectLimit:state',+ projectLimitClaim: 'projectLimit:claim',+ projectLimitChanged: 'projectLimit:changed',appRestartToUpdate: 'app:restart-to-update',announcementsFetch: 'announcements:fetch',usageFetch: 'usage:fetch',diff --git a/src/shared/project-limit.test.ts b/src/shared/project-limit.test.tsindex 26bbd13fa..1e4a2e253 100644--- a/src/shared/project-limit.test.ts+++ b/src/shared/project-limit.test.ts@@ -1,5 +1,13 @@import { describe, it, expect } from 'vitest'-import { countOpenProjects } from './project-limit'+import {+ INACTIVE_PROJECT_LIMIT,+ PROJECT_LIMIT_DEADLINE_MS,+ PROJECT_LIMIT_DEFAULT_FREE,+ countOpenProjects,+ decideOpen,+ effectiveLimit,+ type ProjectLimitState+} from './project-limit'describe('countOpenProjects — the one definition of an open project', () => {it('counts every project that is neither closed nor a relay tab', () => {@@ -10,3 +18,55 @@ describe('countOpenProjects — the one definition of an open project', () => {expect(countOpenProjects([])).toBe(0)})})++const on: ProjectLimitState = { active: true, pro: false, free: 5, allowance: null, dnt: false }++describe('decideOpen — allow, claim or block one new open', () => {+ it('allows anything while the limit is inactive, and for Pro', () => {+ expect(decideOpen({ ...on, active: false }, 99)).toBe('allow')+ expect(decideOpen({ ...on, pro: true }, 99)).toBe('allow')+ })++ it('allows under FREE and claims at it when no allowance is known', () => {+ expect(decideOpen(on, 4)).toBe('allow')+ expect(decideOpen(on, 5)).toBe('claim')+ })++ it('allows under a claimed allowance and blocks at it', () => {+ expect(decideOpen({ ...on, allowance: 30 }, 29)).toBe('allow')+ expect(decideOpen({ ...on, allowance: 30 }, 30)).toBe('block')+ })++ it('never lets an older allowance undercut a FREE the server raised after the token', () => {+ expect(decideOpen({ ...on, allowance: 5, free: 8 }, 6)).toBe('allow')+ expect(effectiveLimit({ ...on, allowance: 5, free: 8 })).toBe(8)+ })++ it('blocks a new open above the allowance (a Pro lapse) without asking again', () => {+ // Above the allowance is reachable (here: projects opened while Pro). The gate blocks the NEW+ // open and closes nothing; the allowance is known, so a claim would only hear the same number.+ expect(decideOpen({ ...on, allowance: 5 }, 7)).toBe('block')+ })++ it('reads the effective limit as FREE until an allowance is known', () => {+ expect(effectiveLimit(on)).toBe(5)+ expect(effectiveLimit({ ...on, allowance: 30 })).toBe(30)+ expect(effectiveLimit({ ...on, allowance: 0 })).toBe(5)+ })+})++describe('the dormant defaults', () => {+ it('INACTIVE_PROJECT_LIMIT allows every open and carries the compiled FREE', () => {+ expect(INACTIVE_PROJECT_LIMIT).toEqual({ active: false, pro: false, free: 5, allowance: null, dnt: false })+ expect(PROJECT_LIMIT_DEFAULT_FREE).toBe(5)+ expect(INACTIVE_PROJECT_LIMIT.free).toBe(PROJECT_LIMIT_DEFAULT_FREE)+ expect(decideOpen(INACTIVE_PROJECT_LIMIT, 1000)).toBe('allow')+ })++ it('the embedded deadline is a real instant', () => {+ // A typo in the literal makes Date.parse answer NaN, and `anchor >= NaN` is false forever: a+ // DNT client would then never ask the server at all, silently. The value itself is bumped every+ // release (docs/project-limit.md), so only its well-formedness is pinned here.+ expect(Number.isFinite(PROJECT_LIMIT_DEADLINE_MS)).toBe(true)+ })+})diff --git a/src/shared/project-limit.ts b/src/shared/project-limit.tsindex 13d71ccc0..9a008402c 100644--- a/src/shared/project-limit.ts+++ b/src/shared/project-limit.ts@@ -14,3 +14,97 @@ export function countOpenProjects(projects: readonly { closed?: boolean; remote?for (const p of projects) if (!p.closed && !p.remote) open++return open}++/**+ * The compiled FREE: how many open projects a non-Pro install may have before the server has said+ * otherwise. The server owns the real number (spec §4) and sends it on every check while the limit+ * is on, so changing FREE never needs a release; this is only the value used until it has spoken.+ */+export const PROJECT_LIMIT_DEFAULT_FREE = 5++/**+ * The embedded deadline (spec §5): past this instant a client that never heard from the server —+ * DO_NOT_TRACK, `NODETERM_TELEMETRY_DISABLED`, a blocked host — treats the limit as on. In practice+ * that only means "ask the server (claim) before opening beyond FREE"; a `not_active` answer turns+ * it off again. Compared against the clock anchor, never the bare wall clock.+ *+ * RELEASE CHECKLIST: this is BUMPED IN EVERY RELEASE BEFORE THE FLIP, to a date past the planned+ * flip — otherwise DNT users are gated before anyone else. At the flip it is set to the flip date+ * and `PROJECT_LIMIT_DEADLINE_FROZEN` becomes `true`. See docs/project-limit.md.+ *+ * Keep the literal form `Date.parse('<ISO instant>')` on one line: the release deadline guard+ * (docs/project-limit.md) reads it from this source text.+ */+export const PROJECT_LIMIT_DEADLINE_MS = Date.parse('2027-01-31T00:00:00Z')++/**+ * `true` once the flip has happened and the deadline above is the flip date for good: the release+ * guard then stops asking for it to be bumped. See docs/project-limit.md.+ */+export const PROJECT_LIMIT_DEADLINE_FROZEN = false++/** What the renderer's gate needs to decide one open. Core computes it (src/core/project-limit.ts). */+export interface ProjectLimitState {+ /** The limit is on for this install (server latch or embedded deadline; never in a dev build). */+ active: boolean+ /** Pro for the purposes of the limit: unlimited open projects, no claim. */+ pro: boolean+ /** FREE as the server last sent it, else `PROJECT_LIMIT_DEFAULT_FREE`. */+ free: number+ /** The allowance a verified, server-signed token grants this device; `null` = not claimed yet. */+ allowance: number | null+ /** DO_NOT_TRACK is set: a claim (and a purchase) needs the user's consent first (spec §7.4). */+ dnt: boolean+}++/**+ * The answer while the limit is off, and the Server Edition's permanent answer (spec §10): every+ * open is allowed synchronously, nothing is claimed, nothing is shown.+ */+export const INACTIVE_PROJECT_LIMIT: ProjectLimitState = {+ active: false,+ pro: false,+ free: PROJECT_LIMIT_DEFAULT_FREE,+ allowance: null,+ dnt: false+}++/**+ * Why a claim did not produce an allowance. `consent_required` = DO_NOT_TRACK without consent;+ * `disabled` = this build or shell never talks to the license server (an unpackaged desktop build+ * without `NODETERM_API_BASE`, the Server Edition).+ */+export type ClaimError = 'offline' | 'server' | 'machine_mismatch' | 'consent_required' | 'disabled'++/**+ * The outcome of one claim, always carrying the state after it. A server answering `not_active` is+ * `ok: true` with `state.active === false`: the limit is off, which is an answer, not a failure.+ * `retryAfter` (unix seconds) rides `machine_mismatch`: when this device may move machines again.+ */+export type ClaimResult =+ | { ok: true; state: ProjectLimitState }+ | { ok: false; error: ClaimError; retryAfter?: number; state: ProjectLimitState }++/** `claim` = ask the server for this device's allowance first, then decide again. */+export type OpenDecision = 'allow' | 'claim' | 'block'++/**+ * How many open projects this install may have. Never below FREE: an allowance issued before the+ * server raised FREE must not undercut the new FREE.+ */+export function effectiveLimit(s: ProjectLimitState): number {+ return Math.max(s.allowance ?? s.free, s.free)+}++/**+ * Whether ONE new open may proceed with `openCount` projects already open. Off or Pro → allow;+ * under the limit → allow; at it with no allowance yet → claim; at or above a known allowance →+ * block. Above it is reachable (a Pro lapse, for one): the gate blocks the new open and closes+ * nothing.+ */+export function decideOpen(s: ProjectLimitState, openCount: number): OpenDecision {+ if (!s.active || s.pro) return 'allow'+ if (openCount < effectiveLimit(s)) return 'allow'+ if (s.allowance === null) return 'claim'+ return 'block'+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex a90e9e402..23a1b5a85 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -30,6 +30,7 @@ import type { ProjectKanbanGitHub } from './github-issues'import type { KanbanPullAutoMove, KanbanPullLinks } from './kanban-pull-links'import type { BoardDispatch } from './board-dispatch'import type { CodexAccount } from './codex-account'+import type { ClaimResult, ProjectLimitState } from './project-limit'import type { NotchAlign } from './notch-hud'import type { ProjectIcon, ProjectIconPickResult } from './project-icon'import type { AlertSoundKind, AlertSoundSaveResult, CustomAlertSounds } from './alert-sound'@@ -4178,6 +4179,19 @@ export interface LicenseApi {releaseOthers(): Promise<LicenseDetail>}+/** The free-tier open-project limit (src/shared/project-limit.ts; core computes the state). Desktop+ * only: the Server Edition's stub answers `INACTIVE_PROJECT_LIMIT` and claims `disabled` (spec §10),+ * and a relay tab keeps the local preload — the allowance is this machine's, never the host's. */+export interface ProjectLimitApi {+ /** The current state. Cheap and offline: it never waits on the network. */+ state(): Promise<ProjectLimitState>+ /** Claim this device's allowance from the server (lazily, at the limit moment). Never rejects+ * for a network or server failure — that is `ok: false` with the state as it stands. */+ claim(): Promise<ClaimResult>+ /** Fires with the new state whenever it changes. Returns unsubscribe. */+ onChange(listener: (s: ProjectLimitState) => void): () => void+}+export type PhoneApprovalResult = {status: 'persisted' | 'approved' | 'saved-disconnected' | 'stale' | 'persistence-failed'}@@ -4587,6 +4601,7 @@ export interface NodeTerminalApi {updates: UpdateApiannouncements: AnnouncementsApilicense: LicenseApi+ projectLimit: ProjectLimitApicontextLink: ContextLinkApiboardLog: BoardLogApilogs: LogApi