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): renderer store and open gate
review18c845c47d46
diff --git a/src/renderer/lib/projectLimitGate.test.ts b/src/renderer/lib/projectLimitGate.test.tsnew file mode 100644index 000000000..68a4ce5dd--- /dev/null+++ b/src/renderer/lib/projectLimitGate.test.ts@@ -0,0 +1,475 @@+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ClaimResult, ProjectLimitState } from '@shared/project-limit'++// The real bindings below import the project-limit store, which subscribes to+// `window.nodeTerminal.projectLimit.onChange` at import time — so the bridge must exist before any+// import runs. The settings and projects stores are replaced: the bound deps only need+// `useSettings.getState().{update,flush}` and `useProjects.getState().projects` from them.+const h = vi.hoisted(() => {+ const claim = vi.fn()+ const update = vi.fn()+ const flush = vi.fn()+ const box: { projects: { closed?: boolean; remote?: boolean }[] } = { projects: [] }+ vi.stubGlobal('window', {+ nodeTerminal: {+ projectLimit: {+ state: vi.fn(),+ claim,+ onChange: () => () => {}+ }+ }+ })+ return { claim, update, flush, box }+})+vi.mock('../state/settings', () => ({+ useSettings: { getState: () => ({ update: h.update, flush: h.flush }) }+}))+vi.mock('../state/projects', () => ({+ useProjects: { getState: () => ({ projects: h.box.projects }) }+}))++import {+ AGENT_DIALOG_QUIET_MS,+ CHECKING_DELAY_MS,+ createProjectOpenGate,+ liveProjectOpenGateDeps,+ type ProjectOpenGateDeps+} from './projectLimitGate'+import { useProjectLimit, type DialogOutcome, type LimitDialogRequest } from '../state/projectLimit'++afterAll(() => {+ vi.unstubAllGlobals()+})++const INACTIVE: ProjectLimitState = { active: false, pro: false, free: 5, allowance: null, dnt: false }+const AT_LIMIT: ProjectLimitState = { active: true, pro: false, free: 5, allowance: null, dnt: false }+const CLAIMED_5: ProjectLimitState = { ...AT_LIMIT, allowance: 5 }+const CLAIMED_7: ProjectLimitState = { ...AT_LIMIT, allowance: 7 }+const PRO: ProjectLimitState = { ...AT_LIMIT, pro: true }++/** A promise whose settlement the test controls. */+function deferred<T>(): { promise: Promise<T>; resolve(v: T): void; reject(e: unknown): void } {+ let resolve!: (v: T) => void+ let reject!: (e: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}++/** Let every queued microtask (and the gate's chained awaits) run. */+async function settle(): Promise<void> {+ for (let i = 0; i < 20; i++) await Promise.resolve()+}++interface Harness {+ deps: ProjectOpenGateDeps+ claim: ReturnType<typeof vi.fn<() => Promise<ClaimResult>>>+ setConsent: ReturnType<typeof vi.fn<() => Promise<void>>>+ setChecking: ReturnType<typeof vi.fn<(on: boolean) => void>>+ showDialog: ReturnType<typeof vi.fn<(r: LimitDialogRequest) => Promise<DialogOutcome>>>+ /** Resolve the dialog currently shown (the latest `showDialog` call). */+ answer(o: DialogOutcome): void+ set(s: ProjectLimitState): void+ setOpen(n: number): void+ setNow(ms: number): void+}++function harness(initial: ProjectLimitState, open: number): Harness {+ let state = initial+ let openCount = open+ let now = 1_000_000+ const pending: ((o: DialogOutcome) => void)[] = []+ const claim = vi.fn<() => Promise<ClaimResult>>()+ const setConsent = vi.fn<() => Promise<void>>(() => Promise.resolve())+ const setChecking = vi.fn<(on: boolean) => void>()+ const showDialog = vi.fn<(r: LimitDialogRequest) => Promise<DialogOutcome>>(+ () => new Promise<DialogOutcome>((resolve) => pending.push(resolve))+ )+ return {+ deps: {+ getState: () => state,+ openCount: () => openCount,+ claim,+ setConsent,+ showDialog,+ setChecking,+ now: () => now+ },+ claim,+ setConsent,+ setChecking,+ showDialog,+ answer(o) {+ const r = pending.pop()+ if (!r) throw new Error('no dialog is open')+ r(o)+ },+ set(s) {+ state = s+ },+ setOpen(n) {+ openCount = n+ },+ setNow(ms) {+ now = ms+ }+ }+}++afterEach(() => {+ vi.useRealTimers()+})++describe('gateProjectOpen — the human open path', () => {+ it('allows synchronously when inactive', () => {+ // Dormant day one (Review Focus 1): nine open, a tenth must open exactly as today — the literal+ // `true`, returned in the same tick, with no claim, no spinner and no modal.+ const t = harness(INACTIVE, 9)+ const gate = createProjectOpenGate(t.deps)+ expect(gate.gateProjectOpen()).toBe(true)+ // DNT changes nothing while the limit is off.+ t.set({ ...INACTIVE, dnt: true })+ expect(gate.gateProjectOpen()).toBe(true)+ expect(t.claim).not.toHaveBeenCalled()+ expect(t.showDialog).not.toHaveBeenCalled()+ expect(t.setChecking).not.toHaveBeenCalled()+ })++ it('allows synchronously for pro and under the limit', () => {+ const t = harness(PRO, 40)+ const gate = createProjectOpenGate(t.deps)+ expect(gate.gateProjectOpen()).toBe(true)+ t.set(AT_LIMIT)+ t.setOpen(4)+ expect(gate.gateProjectOpen()).toBe(true)+ t.set(CLAIMED_7)+ t.setOpen(6)+ expect(gate.gateProjectOpen()).toBe(true)+ expect(t.claim).not.toHaveBeenCalled()+ expect(t.showDialog).not.toHaveBeenCalled()+ })++ it('claims at the limit, then allows if the allowance permits', async () => {+ const t = harness(AT_LIMIT, 5)+ t.claim.mockResolvedValue({ ok: true, state: CLAIMED_7 })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ expect(g).toBeInstanceOf(Promise)+ await expect(g).resolves.toBe(true)+ expect(t.claim).toHaveBeenCalledTimes(1)+ expect(t.showDialog).not.toHaveBeenCalled()+ })++ it('shows checking only when the claim outlasts 300 ms', async () => {+ vi.useFakeTimers()+ const t = harness(AT_LIMIT, 5)+ const slow = deferred<ClaimResult>()+ t.claim.mockReturnValueOnce(slow.promise)+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await vi.advanceTimersByTimeAsync(CHECKING_DELAY_MS - 1)+ expect(t.setChecking).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(t.setChecking.mock.calls).toEqual([[true]])+ slow.resolve({ ok: true, state: CLAIMED_7 })+ await expect(g).resolves.toBe(true)+ expect(t.setChecking.mock.calls).toEqual([[true], [false]])++ // A fast claim never raises the spinner — not even for a frame.+ const u = harness(AT_LIMIT, 5)+ u.claim.mockResolvedValue({ ok: true, state: CLAIMED_7 })+ const fast = createProjectOpenGate(u.deps).gateProjectOpen()+ await vi.advanceTimersByTimeAsync(CHECKING_DELAY_MS * 3)+ await expect(fast).resolves.toBe(true)+ expect(u.setChecking).not.toHaveBeenCalledWith(true)+ })++ it('shows the limit dialog when still at the limit; cancel resolves false', async () => {+ const t = harness(AT_LIMIT, 5)+ t.claim.mockResolvedValue({ ok: true, state: CLAIMED_5 })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'limit' }]])+ t.answer('cancel')+ await expect(g).resolves.toBe(false)+ expect(t.claim).toHaveBeenCalledTimes(1)+ })++ it('proceed after a Close resolves true', async () => {+ // A known allowance at the limit blocks without asking the server again.+ const t = harness(CLAIMED_5, 5)+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ expect(t.claim).not.toHaveBeenCalled()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'limit' }]])+ t.setOpen(4) // the user pressed Close on one row+ t.answer('proceed')+ await expect(g).resolves.toBe(true)+ })++ it('proceed is re-decided, never trusted: still at the limit shows the dialog again', async () => {+ const t = harness(CLAIMED_5, 5)+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ // Something else filled the freed slot before the gate looked again.+ t.answer('proceed')+ await settle()+ expect(t.showDialog).toHaveBeenCalledTimes(2)+ t.answer('cancel')+ await expect(g).resolves.toBe(false)+ })++ it('a claim error shows the error dialog; retry claims again', async () => {+ const t = harness(AT_LIMIT, 5)+ t.claim+ .mockResolvedValueOnce({ ok: false, error: 'offline', state: AT_LIMIT })+ .mockResolvedValueOnce({ ok: true, state: CLAIMED_7 })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'error' }]])+ t.answer('retry')+ await expect(g).resolves.toBe(true)+ expect(t.claim).toHaveBeenCalledTimes(2)+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ })++ it('a rejected claim is an offline claim, not a thrown open', async () => {+ const t = harness(AT_LIMIT, 5)+ t.claim.mockRejectedValueOnce(new Error('No handler registered for projectLimit:claim'))+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'error' }]])+ t.answer('cancel')+ await expect(g).resolves.toBe(false)+ })++ it('machine_mismatch shows the mismatch dialog with retryAfter', async () => {+ const t = harness(AT_LIMIT, 5)+ t.claim.mockResolvedValue({ ok: false, error: 'machine_mismatch', retryAfter: 1_800_000_000, state: AT_LIMIT })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'mismatch', retryAfter: 1_800_000_000 }]])+ t.answer('cancel')+ await expect(g).resolves.toBe(false)+ })++ it('consent_required asks consent, stores it, then claims', async () => {+ const t = harness({ ...AT_LIMIT, dnt: true }, 5)+ const stored = deferred<void>()+ t.setConsent.mockReturnValueOnce(stored.promise)+ t.claim+ .mockResolvedValueOnce({ ok: false, error: 'consent_required', state: { ...AT_LIMIT, dnt: true } })+ .mockResolvedValueOnce({ ok: true, state: { ...CLAIMED_7, dnt: true } })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'consent' }]])+ t.answer('consent')+ await settle()+ expect(t.setConsent).toHaveBeenCalledTimes(1)+ // The second claim waits for the consent to be stored: core reads it, not the renderer.+ expect(t.claim).toHaveBeenCalledTimes(1)+ stored.resolve()+ await expect(g).resolves.toBe(true)+ expect(t.claim).toHaveBeenCalledTimes(2)+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ })++ it('a declined consent resolves false and stores nothing', async () => {+ const t = harness({ ...AT_LIMIT, dnt: true }, 5)+ t.claim.mockResolvedValue({ ok: false, error: 'consent_required', state: { ...AT_LIMIT, dnt: true } })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ t.answer('cancel')+ await expect(g).resolves.toBe(false)+ expect(t.setConsent).not.toHaveBeenCalled()+ expect(t.claim).toHaveBeenCalledTimes(1)+ })++ it('consent that core still does not see shows the error dialog, not the consent dialog again', async () => {+ const t = harness({ ...AT_LIMIT, dnt: true }, 5)+ t.claim.mockResolvedValue({ ok: false, error: 'consent_required', state: { ...AT_LIMIT, dnt: true } })+ const gate = createProjectOpenGate(t.deps)+ const g = gate.gateProjectOpen()+ await settle()+ t.answer('consent')+ await settle()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'consent' }], [{ mode: 'error' }]])+ t.answer('cancel')+ await expect(g).resolves.toBe(false)+ })++ it('refuses a second request while the dialog is open', async () => {+ // Review Focus 5: a second open at the edge is refused, never queued behind the first.+ const t = harness(CLAIMED_5, 5)+ const gate = createProjectOpenGate(t.deps)+ const first = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ const second = gate.gateProjectOpen()+ expect(second).toBeInstanceOf(Promise)+ await expect(second).resolves.toBe(false)+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ t.answer('cancel')+ await expect(first).resolves.toBe(false)+ // Not stuck: once the dialog is gone the next open is asked again.+ const third = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog).toHaveBeenCalledTimes(2)+ t.answer('cancel')+ await expect(third).resolves.toBe(false)+ })++ it('refuses a second request while the first one is still claiming', async () => {+ // Both would otherwise re-decide on the same count and both open: one past an allowance of 6.+ const t = harness(AT_LIMIT, 5)+ const slow = deferred<ClaimResult>()+ t.claim.mockReturnValueOnce(slow.promise)+ const gate = createProjectOpenGate(t.deps)+ const first = gate.gateProjectOpen()+ await settle()+ await expect(gate.gateProjectOpen()).resolves.toBe(false)+ expect(t.claim).toHaveBeenCalledTimes(1)+ slow.resolve({ ok: true, state: { ...AT_LIMIT, allowance: 6 } })+ await expect(first).resolves.toBe(true)+ })+})++describe('checkAgentProjectOpen — the agent open-project verb', () => {+ const MESSAGE = 'free plan: 5 of 5 projects are open; the user has been shown the options'++ it('allows when the open would be allowed for a person, without any dialog', async () => {+ const t = harness(INACTIVE, 9)+ const gate = createProjectOpenGate(t.deps)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: true })+ t.set(AT_LIMIT)+ t.claim.mockResolvedValue({ ok: true, state: CLAIMED_7 })+ t.setOpen(5)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: true })+ expect(t.showDialog).not.toHaveBeenCalled()+ })++ it('agent: refuses with the message and shows the dialog once per 60 s', async () => {+ const t = harness(CLAIMED_5, 5)+ const gate = createProjectOpenGate(t.deps)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: false, message: MESSAGE })+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'limit' }]])+ t.answer('cancel')+ await settle()+ // The agent retries inside the quiet window: refused, and the user is not shown it again.+ t.setNow(1_000_000 + AGENT_DIALOG_QUIET_MS - 1)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: false, message: MESSAGE })+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ // A minute after it was shown, the next refusal shows it once more.+ t.setNow(1_000_000 + AGENT_DIALOG_QUIET_MS)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: false, message: MESSAGE })+ expect(t.showDialog).toHaveBeenCalledTimes(2)+ expect(t.claim).not.toHaveBeenCalled()+ })++ it('agent: never stacks a dialog on one that is already open', async () => {+ const t = harness(CLAIMED_5, 5)+ const gate = createProjectOpenGate(t.deps)+ // A person's open is already showing the limit dialog.+ const human = gate.gateProjectOpen()+ await settle()+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: false, message: MESSAGE })+ expect(t.showDialog).toHaveBeenCalledTimes(1)+ t.answer('cancel')+ await expect(human).resolves.toBe(false)+ // An agent's own dialog blocks a person's open the same way (one dialog at a time).+ await gate.checkAgentProjectOpen()+ expect(t.showDialog).toHaveBeenCalledTimes(2)+ await expect(gate.gateProjectOpen()).resolves.toBe(false)+ expect(t.showDialog).toHaveBeenCalledTimes(2)+ })++ it('agent: never asks for consent', async () => {+ const t = harness({ ...AT_LIMIT, dnt: true }, 5)+ t.claim.mockResolvedValue({ ok: false, error: 'consent_required', state: { ...AT_LIMIT, dnt: true } })+ const gate = createProjectOpenGate(t.deps)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: false, message: MESSAGE })+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'limit' }]])+ expect(t.setConsent).not.toHaveBeenCalled()+ expect(t.setChecking).not.toHaveBeenCalled()+ })++ it('agent: the message carries the allowance, not FREE', async () => {+ const t = harness(AT_LIMIT, 7)+ t.claim.mockResolvedValue({ ok: true, state: CLAIMED_7 })+ const gate = createProjectOpenGate(t.deps)+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({+ ok: false,+ message: 'free plan: 7 of 7 projects are open; the user has been shown the options'+ })+ })+})++describe('the live bindings', () => {+ beforeEach(() => {+ h.claim.mockReset()+ h.update.mockReset()+ h.flush.mockReset()+ h.box.projects = []+ useProjectLimit.setState({ dialog: null, checking: false })+ })++ it('setConsent publishes the setting before it resolves', async () => {+ // `update` only schedules a coalesced save (300 ms): a claim fired right after it would reach a+ // core that has not seen the consent and answer consent_required again.+ const saved = deferred<void>()+ h.flush.mockReturnValue(saved.promise)+ let done = false+ const p = liveProjectOpenGateDeps.setConsent().then(() => {+ done = true+ })+ await settle()+ expect(h.update).toHaveBeenCalledWith({ licenseNetworkConsent: true })+ expect(h.flush).toHaveBeenCalledTimes(1)+ expect(h.update.mock.invocationCallOrder[0]).toBeLessThan(h.flush.mock.invocationCallOrder[0])+ expect(done).toBe(false)+ saved.resolve()+ await p+ expect(done).toBe(true)+ })++ it('openCount is the one definition: not closed, not a relay tab', () => {+ h.box.projects = [{}, { closed: true }, { remote: true }, { closed: false, remote: false }]+ expect(liveProjectOpenGateDeps.openCount()).toBe(2)+ })++ it('claim asks core over the bridge', async () => {+ h.claim.mockResolvedValue({ ok: true, state: CLAIMED_7 })+ await expect(liveProjectOpenGateDeps.claim()).resolves.toEqual({ ok: true, state: CLAIMED_7 })+ })++ it('showDialog is the store dialog, settled by resolveDialog', async () => {+ const p = liveProjectOpenGateDeps.showDialog({ mode: 'mismatch', retryAfter: 9 })+ expect(useProjectLimit.getState().dialog).toEqual({ mode: 'mismatch', retryAfter: 9 })+ useProjectLimit.getState().resolveDialog('retry')+ await expect(p).resolves.toBe('retry')+ expect(useProjectLimit.getState().dialog).toBeNull()+ })++ it('setChecking toggles the store spinner flag', () => {+ liveProjectOpenGateDeps.setChecking(true)+ expect(useProjectLimit.getState().checking).toBe(true)+ liveProjectOpenGateDeps.setChecking(false)+ expect(useProjectLimit.getState().checking).toBe(false)+ })++ it('getState reads the store', () => {+ useProjectLimit.setState({ state: CLAIMED_7 })+ expect(liveProjectOpenGateDeps.getState()).toEqual(CLAIMED_7)+ })+})diff --git a/src/renderer/lib/projectLimitGate.ts b/src/renderer/lib/projectLimitGate.tsnew file mode 100644index 000000000..d2edb6636--- /dev/null+++ b/src/renderer/lib/projectLimitGate.ts@@ -0,0 +1,208 @@+import {+ countOpenProjects,+ decideOpen,+ effectiveLimit,+ type ClaimResult,+ type ProjectLimitState+} from '@shared/project-limit'+import {+ setProjectLimitChecking,+ showProjectLimitDialog,+ useProjectLimit,+ type DialogOutcome,+ type LimitDialogRequest+} from '../state/projectLimit'+import { useProjects } from '../state/projects'+import { useSettings } from '../state/settings'++/**+ * The one renderer gate in front of every way a project becomes open (spec §7,+ * docs/superpowers/specs/2026-10-29-free-tier-project-limit-design.md). It ANSWERS whether one new+ * open may proceed; it never closes, deletes or detaches anything (§2).+ *+ * Two invariants the callers (Canvas's open paths, Task 18; the agent verb, Task 19) depend on:+ * - **Allowed is synchronous.** `gateProjectOpen()` returns the literal `true` in the same tick when+ * `decideOpen` allows — no promise, no microtask — so a caller that mutates the store right after+ * it keeps today's synchronous path, and two opens at the edge cannot both read the same count.+ * While the limit is off this is the ONLY branch reached: no claim, no spinner, no dialog.+ * - **One loop at a time.** A request that arrives while a person's open is being decided (claiming,+ * or a dialog up — a person's or an agent's) is refused, not queued: queued, it would re-decide on+ * a count the first open has not added to yet and both would open past the limit.+ */++/** §7's "brief spinner": raised only for a claim still in flight after this long. */+export const CHECKING_DELAY_MS = 300++/** An agent's refusal shows the user the limit dialog at most once in this window (§7.5: once per+ * refusal burst, not per retry). Measured from when the dialog was last shown for an agent. */+export const AGENT_DIALOG_QUIET_MS = 60_000++export interface ProjectOpenGateDeps {+ getState(): ProjectLimitState+ openCount(): number+ /** Core's claim. Never rejects by contract; a rejection is treated as `offline` anyway. */+ claim(): Promise<ClaimResult>+ /** Store the DO_NOT_TRACK consent where core reads it, resolving only once core can see it. */+ setConsent(): Promise<void>+ showDialog(r: LimitDialogRequest): Promise<DialogOutcome>+ setChecking(on: boolean): void+ now(): number+}++export type AgentOpenCheck = { ok: true } | { ok: false; message: string }++export interface ProjectOpenGate {+ gateProjectOpen(): true | Promise<boolean>+ checkAgentProjectOpen(): Promise<AgentOpenCheck>+}++/** The dialog that explains a failed claim. A repeated `consent_required` right after the user+ * consented means core still cannot see it: asking again would loop, so it reads as an error. */+function dialogFor(r: Extract<ClaimResult, { ok: false }>, consentGiven: boolean): LimitDialogRequest {+ if (r.error === 'consent_required' && !consentGiven) return { mode: 'consent' }+ if (r.error === 'machine_mismatch') {+ return r.retryAfter === undefined ? { mode: 'mismatch' } : { mode: 'mismatch', retryAfter: r.retryAfter }+ }+ return { mode: 'error' }+}++export function createProjectOpenGate(deps: ProjectOpenGateDeps): ProjectOpenGate {+ /** A person's open is being decided (claiming or showing a dialog). */+ let busy = false+ /** A dialog is up — a person's or one shown for an agent. */+ let dialogOpen = false+ let lastAgentDialogAt = Number.NEGATIVE_INFINITY++ async function claim(): Promise<ClaimResult> {+ try {+ return await deps.claim()+ } catch (err) {+ console.warn('[project-limit] claim rejected', err instanceof Error ? err.message : String(err))+ return { ok: false, error: 'offline', state: deps.getState() }+ }+ }++ /** A person's claim: the spinner goes up only if it is still in flight after CHECKING_DELAY_MS,+ * and comes down the moment it settles. */+ async function claimShowingCheck(): Promise<ClaimResult> {+ let raised = false+ const timer = setTimeout(() => {+ raised = true+ deps.setChecking(true)+ }, CHECKING_DELAY_MS)+ try {+ return await claim()+ } finally {+ clearTimeout(timer)+ if (raised) deps.setChecking(false)+ }+ }++ async function show(r: LimitDialogRequest): Promise<DialogOutcome> {+ dialogOpen = true+ try {+ return await deps.showDialog(r)+ } finally {+ dialogOpen = false+ }+ }++ async function decideForPerson(): Promise<boolean> {+ busy = true+ try {+ let claimNext = false+ let consentGiven = false+ for (;;) {+ const d = decideOpen(deps.getState(), deps.openCount())+ if (d === 'allow') return true+ let request: LimitDialogRequest = { mode: 'limit' }+ // At most one claim per pass: when there is no allowance yet, or after Retry / consent.+ if (d === 'claim' || claimNext) {+ claimNext = false+ const r = await claimShowingCheck()+ // Decided on the claim's own answer — core's state right after it — with the live count.+ if (decideOpen(r.state, deps.openCount()) === 'allow') return true+ if (!r.ok) request = dialogFor(r, consentGiven)+ }+ const outcome = await show(request)+ if (outcome === 'cancel') return false+ if (outcome === 'retry') claimNext = true+ if (outcome === 'consent') {+ try {+ await deps.setConsent()+ } catch (err) {+ console.warn('[project-limit] storing consent failed', err instanceof Error ? err.message : String(err))+ }+ consentGiven = true+ claimNext = true+ }+ // `proceed`: the dialog saw room; the next pass re-decides rather than trusting it.+ }+ } finally {+ busy = false+ }+ }++ function gateProjectOpen(): true | Promise<boolean> {+ if (decideOpen(deps.getState(), deps.openCount()) === 'allow') return true+ if (busy || dialogOpen) return Promise.resolve(false)+ return decideForPerson()+ }++ /** Show the user the limit dialog for an agent's refusal — not while one is up (or a person's open+ * is being decided), and not again within the quiet window. The agent does not wait for it. */+ function showForAgent(): void {+ if (busy || dialogOpen) return+ const t = deps.now()+ if (t - lastAgentDialogAt < AGENT_DIALOG_QUIET_MS) return+ lastAgentDialogAt = t+ void show({ mode: 'limit' }).catch(() => {})+ }++ async function checkAgentProjectOpen(): Promise<AgentOpenCheck> {+ let state = deps.getState()+ let d = decideOpen(state, deps.openCount())+ if (d === 'allow') return { ok: true }+ if (d === 'claim') {+ // Never the consent dialog and never the spinner: nobody pressed anything. A claim that needs+ // consent simply leaves the state blocking.+ const r = await claim()+ state = r.state+ d = decideOpen(state, deps.openCount())+ if (d === 'allow') return { ok: true }+ }+ showForAgent()+ return {+ ok: false,+ message: `free plan: ${deps.openCount()} of ${effectiveLimit(state)} projects are open; the user has been shown the options`+ }+ }++ return { gateProjectOpen, checkAgentProjectOpen }+}++/** The gate's deps bound to the live stores and bridge. Exported for its tests. */+export const liveProjectOpenGateDeps: ProjectOpenGateDeps = {+ getState: () => useProjectLimit.getState().state,+ openCount: () => countOpenProjects(useProjects.getState().projects),+ claim: () => window.nodeTerminal.projectLimit.claim(),+ async setConsent() {+ const settings = useSettings.getState()+ settings.update({ licenseNetworkConsent: true })+ // `update` only schedules a coalesced save; core reads the consent from ITS copy of the+ // settings, so the claim that follows must wait until that copy has it.+ await settings.flush()+ },+ showDialog: showProjectLimitDialog,+ setChecking: setProjectLimitChecking,+ now: () => Date.now()+}++const liveGate = createProjectOpenGate(liveProjectOpenGateDeps)++/** Whether a person's open may proceed: the literal `true` synchronously when allowed, else a+ * promise that the limit dialog (and a claim, if needed) settles. */+export const gateProjectOpen = liveGate.gateProjectOpen++/** Whether an agent's `open-project` may proceed; a refusal carries the message to send back. */+export const checkAgentProjectOpen = liveGate.checkAgentProjectOpendiff --git a/src/renderer/state/projectLimit.test.ts b/src/renderer/state/projectLimit.test.tsindex 02977354b..0d20d615f 100644--- a/src/renderer/state/projectLimit.test.ts+++ b/src/renderer/state/projectLimit.test.ts@@ -91,6 +91,59 @@ describe('project-limit store', () => {})})+describe('project-limit store — the limit dialog and the checking spinner', () => {+ it('starts with no dialog and no spinner', async () => {+ const useProjectLimit = await freshStore()+ expect(useProjectLimit.getState().dialog).toBeNull()+ expect(useProjectLimit.getState().checking).toBe(false)+ })++ it('a dialog request is held until resolveDialog settles it, and then it is gone', async () => {+ const useProjectLimit = await freshStore()+ const { showProjectLimitDialog } = await import('./projectLimit')+ const outcome = showProjectLimitDialog({ mode: 'limit' })+ expect(useProjectLimit.getState().dialog).toEqual({ mode: 'limit' })+ useProjectLimit.getState().resolveDialog('proceed')+ await expect(outcome).resolves.toBe('proceed')+ expect(useProjectLimit.getState().dialog).toBeNull()+ })++ it('resolveDialog with nothing shown changes nothing', async () => {+ const useProjectLimit = await freshStore()+ useProjectLimit.getState().resolveDialog('cancel')+ expect(useProjectLimit.getState().dialog).toBeNull()+ })++ it('a new request never strands the one it replaces: that one is cancelled', async () => {+ const useProjectLimit = await freshStore()+ const { showProjectLimitDialog } = await import('./projectLimit')+ const first = showProjectLimitDialog({ mode: 'error' })+ const second = showProjectLimitDialog({ mode: 'consent' })+ await expect(first).resolves.toBe('cancel')+ expect(useProjectLimit.getState().dialog).toEqual({ mode: 'consent' })+ useProjectLimit.getState().resolveDialog('consent')+ await expect(second).resolves.toBe('consent')+ })++ it('setProjectLimitChecking toggles the spinner flag', async () => {+ const useProjectLimit = await freshStore()+ const { setProjectLimitChecking } = await import('./projectLimit')+ setProjectLimitChecking(true)+ expect(useProjectLimit.getState().checking).toBe(true)+ setProjectLimitChecking(false)+ expect(useProjectLimit.getState().checking).toBe(false)+ })++ it('a push from core leaves an open dialog where it is', async () => {+ const useProjectLimit = await freshStore()+ const { showProjectLimitDialog } = await import('./projectLimit')+ void showProjectLimitDialog({ mode: 'limit' })+ pushed!(ACTIVE)+ expect(useProjectLimit.getState().dialog).toEqual({ mode: 'limit' })+ expect(useProjectLimit.getState().state).toEqual(ACTIVE)+ })+})+describe('project-limit store wiring (source)', () => {it('the boot effect reads the state AFTER the projects store is hydrated from the workspace', () => {// Core records the first-launch open count on the first `state()` it answers once the workspacediff --git a/src/renderer/state/projectLimit.ts b/src/renderer/state/projectLimit.tsindex 8618862a7..bb32760b7 100644--- a/src/renderer/state/projectLimit.ts+++ b/src/renderer/state/projectLimit.ts@@ -11,14 +11,41 @@ import { INACTIVE_PROJECT_LIMIT, type ProjectLimitState } from '@shared/project-* Desktop: the preload's `projectLimit`. Server Edition: the bridge stub answers inactive forever.* A relay tab keeps the LOCAL preload's api (the allowance is this machine's, never the host's).*/+/**+ * What the limit dialog (components/ProjectLimitDialog.tsx) is asked to show — spec §7:+ * - `limit`: still at the limit after any claim; Close / Cancel / Pro.+ * - `consent`: DO_NOT_TRACK without consent; a claim needs the user's yes first (§7.4).+ * - `error`: the claim could not get an answer (offline, server error); adds Retry.+ * - `mismatch`: the allowance is tied to another computer; `retryAfter` (unix seconds) says when+ * it may move to this one.+ */+export type LimitDialogRequest = { mode: 'limit' | 'consent' | 'error' | 'mismatch'; retryAfter?: number }++/**+ * How the dialog was left. `proceed` = the open may go ahead NOW (a Close made room, Pro arrived) —+ * the gate re-decides rather than trusting it; `retry` = claim again; `consent` = the user allowed+ * the license connection; `cancel` = the open does not happen.+ */+export type DialogOutcome = 'proceed' | 'cancel' | 'retry' | 'consent'+interface ProjectLimitStore {state: ProjectLimitState+ /** The dialog the open gate (lib/projectLimitGate.ts) is waiting on, or `null`. At most one. */+ dialog: LimitDialogRequest | null+ /** §7's "brief spinner": a person's claim is still in flight after `CHECKING_DELAY_MS`. */+ checking: boolean/** Read core's current state. Never rejects: a failed read keeps whatever is held (inactive until* core has said otherwise). Called from the boot effect AFTER the projects store is hydrated —* core records the first-launch open count on the first read it answers with the index loaded. */hydrate(): Promise<void>+ /** Settle the open dialog with `outcome` and take it down. Nothing shown → nothing happens. */+ resolveDialog(outcome: DialogOutcome): void}+/** The settle function of the dialog currently shown. Module state rather than store state: a+ * function is not something a component should render from. */+let settleDialog: ((outcome: DialogOutcome) => void) | null = null+export const useProjectLimit = create<ProjectLimitStore>((set) => {// Live updates from core: a server word, a license or settings change, time passing the deadline.// Subscribed at creation (the entitlement store's shape), so a push that lands before the first@@ -26,6 +53,15 @@ export const useProjectLimit = create<ProjectLimitStore>((set) => {window.nodeTerminal.projectLimit.onChange((state) => set({ state }))return {state: INACTIVE_PROJECT_LIMIT,+ dialog: null,+ checking: false,+ resolveDialog(outcome) {+ const settle = settleDialog+ if (!settle) return+ settleDialog = null+ set({ dialog: null })+ settle(outcome)+ },async hydrate() {try {set({ state: await window.nodeTerminal.projectLimit.state() })@@ -35,3 +71,21 @@ export const useProjectLimit = create<ProjectLimitStore>((set) => {}}})++/**+ * Show the limit dialog and wait for how it is left. The open gate's `showDialog`; only the gate+ * calls it, and it never has two up at once. Should a second request arrive anyway, the one it+ * replaces is settled `cancel` first, so no caller is ever left waiting on a dialog nobody can see.+ */+export function showProjectLimitDialog(request: LimitDialogRequest): Promise<DialogOutcome> {+ if (settleDialog) useProjectLimit.getState().resolveDialog('cancel')+ return new Promise<DialogOutcome>((resolve) => {+ settleDialog = resolve+ useProjectLimit.setState({ dialog: { ...request } })+ })+}++/** Raise or lower the "Checking your free allowance…" panel. The open gate's `setChecking`. */+export function setProjectLimitChecking(on: boolean): void {+ if (useProjectLimit.getState().checking !== on) useProjectLimit.setState({ checking: on })+}