Skip to content

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.

feat(project-limit): agents get a plain refusal at the limit

reviewf59f375138b5
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 61e1c5a46..cb948ffc4 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -559,10 +559,9 @@ const VERBS: ControlVerb[] = [
'notify',
'sticky',
'browser',
- // Issue #338 PR 1: registered in the model (parse + gates + the grant ledger run in main), but
- // INERT until PR 2 adds the renderer dispatch case — today the renderer's `default:` answers
- // `unknown verb: open-project`. Deliberately undocumented in the skill/instructions bodies until
- // PR 2 makes it do something (spec §8: docs land in the same PR that makes the verb reachable).
+ // Issue #338: parse + gates + the grant ledger run in main; the renderer answers it from the
+ // projects store (Canvas's early `open-project` block) — create/adopt/find a project for a local
+ // cwd, confirmed by the user, never focused. Both agent-facing bodies document it.
'open-project',
// Read and ask to change the few settings on the allowlist (@shared/settings-verb). Every change
// is confirmed by the user on the desktop; the Server Edition refuses `--set` by name.
@@ -990,6 +989,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' a denial is final, do not retry it. The user may have turned that dialog off for agents in',
' your project, in which case it simply applies. Local only (refused from an SSH project), and it never',
' focuses the new project\'s tab. The returned id is what `--project` accepts.',
+ ' On the free plan this can be refused when the open-project limit is reached. Do not retry: the user has already been shown the options.',
' Server Edition is narrower: it can only re-open an exact local project already saved in its',
' workspace (pass `--cwd` only); it never creates, adds, renames, recolors, or focuses one.',
'- `show-image <path>` / `show-video <path>` — open a media file as a node.',
@@ -1583,6 +1583,7 @@ ${reportOutcomeDocLines().join('\n')}
it. The user may have turned that dialog off for agents in your project, in which case it simply
applies. Local only (refused from an SSH project), and it never focuses the new project's tab: use
the returned id with \`--project\` to open sessions there.
+ On the free plan this can be refused when the open-project limit is reached. Do not retry: the user has already been shown the options.
On Server Edition this is a restart-recovery operation only: pass \`--cwd\` for an exact local
project already saved in that Server workspace. It never creates, adds, renames, recolors, or
focuses a project; register a missing project in the UI first.
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 5748b60dc..7168edee7 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1706,6 +1706,33 @@ describe('open-project --name limit in the agent-facing text (issue #940)', () =
})
})
+describe('open-project at the free-tier project limit (project-limit plan, Task 19)', () => {
+ // Verbatim from the plan. The renderer refuses the verb at the limit with `free plan: N of N
+ // projects are open; the user has been shown the options` and has already shown the user the
+ // limit dialog, so an agent that retries only re-reads the same refusal.
+ const SENTENCE =
+ ' On the free plan this can be refused when the open-project limit is reached. Do not retry: the user has already been shown the options.'
+
+ it.each([
+ ['skill', buildCanvasSkillBody('/x/shim.sh')],
+ ['instructions', buildCanvasControlInstructions('/x/shim.sh')]
+ ])('%s body: the open-project entry says a limit refusal is final', (name, body) => {
+ expect(body, name).toContain('open-project limit')
+ expect(body, name).toContain('Do not retry')
+ const lines = body.split('\n')
+ const entry = lines.findIndex((l) => l.startsWith('- `open-project --cwd'))
+ expect(entry, `${name}: the open-project entry`).toBeGreaterThan(-1)
+ const nextEntry = lines.findIndex((l, i) => i > entry && l.startsWith('- '))
+ // The Server Edition never limits (its state is permanently inactive, spec §10), so the
+ // sentence sits in the desktop half of the entry, ahead of the Server Edition paragraph.
+ const serverEdition = lines.findIndex((l, i) => i > entry && l.includes('Server Edition'))
+ const at = lines.indexOf(SENTENCE)
+ expect(at, `${name}: the sentence, verbatim, on a line of its own`).toBeGreaterThan(entry)
+ expect(at, `${name}: inside the open-project entry`).toBeLessThan(nextEntry)
+ expect(at, `${name}: before the Server Edition paragraph`).toBeLessThan(serverEdition)
+ })
+})
+
describe('one-way context links (issue #852) — agent-facing docs', () => {
it('both canvas-control surfaces document link --one-way', () => {
expect(buildCanvasControlInstructions('/x/nodeterm.sh')).toContain('--one-way')
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7f867350b..c0c8264b5 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -288,7 +288,8 @@ import { SAS_COMPARE_HINT } from '@shared/remote/sas'
import { promptDialog } from '../components/promptDialog'
import { UpgradeDialog } from '../components/UpgradeDialog'
import { ProjectLimitDialog } from '../components/ProjectLimitDialog'
-import { gateProjectOpen } from '../lib/projectLimitGate'
+import { checkAgentProjectOpen, gateProjectOpen, recheckAgentProjectOpen } from '../lib/projectLimitGate'
+import { countOpenProjects, decideOpen } from '@shared/project-limit'
import { opensProject, type OpenAction } from '../lib/projectOpens'
import { LiveLinkDialog } from '../components/LiveLinkDialog'
import { requireProOr } from '../state/upgradeGate'
@@ -878,8 +879,8 @@ import {
mergeRunNow,
planRunVerb,
savePendingAnywhere,
+ shouldUnhideForHeadlessStart,
startHeadless,
- unhidesForHeadlessStart,
type HeadlessStartBatch
} from '../lib/headlessRun'
import {
@@ -13602,11 +13603,37 @@ export function Canvas() {
return
}
}
+ // The free-tier project limit (lib/projectLimitGate.ts), asked only when this registration
+ // makes a project open that was not (lib/projectOpens.ts), and asked twice: here, ahead of
+ // the probe and the consent planning, where a limit with no allowance yet may still claim
+ // one; and again in opFinish, in the same tick as registerProject, because the user's
+ // confirm dialog sits between the two — two agents at the edge both pass here, and only the
+ // first to register passes there (plan Review Focus 5). An open the limit allows at once —
+ // every one, while it is off — awaits nothing here, so a path that was synchronous stays so.
+ const opOpens = (): boolean =>
+ opensProject(useProjects.getState().projects, { kind: 'register', cwd: resolvedCwd })
+ if (
+ opOpens() &&
+ decideOpen(useProjectLimit.getState().state, countOpenProjects(useProjects.getState().projects)) !==
+ 'allow'
+ ) {
+ const opLimit = await checkAgentProjectOpen()
+ if (!opLimit.ok) {
+ reply({ ok: false, error: opLimit.message })
+ return
+ }
+ }
// Apply one consent decision: register (create/adopt/idempotent hit) without activating,
// persist, remember the (caller, project) pair for dialog dedupe — authorization stays
// main-side — and reply with the id the caller can feed `--project`. Returns the reply's
- // sentence, so a WAIVED registration can announce exactly what it did.
- const opFinish = (adoptProbed?: Project): string => {
+ // sentence, so a WAIVED registration can announce exactly what it did — or null when the
+ // project limit refused it at the last moment (already replied; nothing was registered).
+ const opFinish = (adoptProbed?: Project): string | null => {
+ const opLimit = opOpens() ? recheckAgentProjectOpen() : null
+ if (opLimit && !opLimit.ok) {
+ reply({ ok: false, error: opLimit.message })
+ return null
+ }
const r = useProjects.getState().registerProject({
resolvedCwd,
name: args.name,
@@ -13651,6 +13678,7 @@ export function Canvas() {
if (opWaiver.via) {
// A waived registration still announces itself, naming the waiver that let it through.
const opDone = opFinish(opAdopt)
+ if (opDone === null) return
setNotice({
kind: 'info',
text: waivedNotice(`Agent "${opTitle}" ${opDone}`, opWaiver.via, ctlProject?.name)
@@ -18803,12 +18831,19 @@ export function Canvas() {
}
// A closed project gets its tab back, never the focus (#925 spec §2.5): unhide BEFORE the
// claim's disk write, so the same write persists it. When it does NOT (the welcome screen,
- // an SSH project) is `unhidesForHeadlessStart`'s to say; the answer rides back in the batch,
- // because the reply's "reopen it from the welcome screen" hint stays true unless it acted.
+ // an SSH project, the free-tier project limit) is `shouldUnhideForHeadlessStart`'s to say;
+ // the answer rides back in the batch, because the reply's "reopen it from the welcome
+ // screen" hint stays true unless it acted. At the limit the session still starts.
const projectsNow = useProjects.getState()
const storedProject = projectsNow.getProject(project.id)
const unhidden =
- !!storedProject && unhidesForHeadlessStart(storedProject, projectsNow.activeProjectId)
+ !!storedProject &&
+ shouldUnhideForHeadlessStart(
+ storedProject,
+ projectsNow.activeProjectId,
+ useProjectLimit.getState().state,
+ projectsNow.projects
+ )
if (unhidden) projectsNow.unhideProject(project.id)
const outcomes = await Promise.all(nodes.map((node) => startHeadless(deps, { project, node })))
const started = outcomes.filter((o) => o.started).map((o) => o.id)
diff --git a/src/renderer/canvas/project-limit-opens.source.test.ts b/src/renderer/canvas/project-limit-opens.source.test.ts
index 3f68c7646..5714532fc 100644
--- a/src/renderer/canvas/project-limit-opens.source.test.ts
+++ b/src/renderer/canvas/project-limit-opens.source.test.ts
@@ -95,3 +95,55 @@ describe('project-limit gate placement in Canvas', () => {
expect(between('const reopenProjectUnchecked = useCallback(', CALLBACK_END)).not.toContain('gateProjectOpen')
})
})
+
+/** The early-handled `open-project` block: from its guard to the next section rule. */
+function openProjectBlock(): string {
+ return between(`if (verb === 'open-project')`, '// ──')
+}
+
+describe('project-limit gate in the agent open-project verb (Task 19)', () => {
+ const OPENS = "opensProject(useProjects.getState().projects, { kind: 'register', cwd: resolvedCwd })"
+ const REFUSE = /if \(!opLimit\.ok\) \{\s+reply\(\{ ok: false, error: opLimit\.message \}\)\s+return/
+
+ it('asks before the probe and the consent planning, only for a registration that opens a project', () => {
+ const body = openProjectBlock()
+ expect(body).toContain(`const opOpens = (): boolean =>\n ${OPENS}`)
+ const early = body.indexOf('await checkAgentProjectOpen()')
+ expect(early).toBeGreaterThan(-1)
+ expect(body.match(/\bcheckAgentProjectOpen\(\)/g)).toHaveLength(1)
+ // Guarded: no await at all when the registration opens nothing new, or when the limit allows
+ // at once (always while it is off) — so a path that was synchronous stays synchronous.
+ expect(body).toMatch(
+ /if \(\s*opOpens\(\) &&\s*decideOpen\(useProjectLimit\.getState\(\)\.state, countOpenProjects\(useProjects\.getState\(\)\.projects\)\) !==\s*'allow'\s*\) \{\s*const opLimit = await checkAgentProjectOpen\(\)/
+ )
+ expect(body.slice(early)).toMatch(REFUSE)
+ for (const later of ['api.workspace.probeFolder(resolvedCwd)', 'planOpenProject(', 'setConfirm({']) {
+ expect(body.indexOf(later), later).toBeGreaterThan(early)
+ }
+ })
+
+ it('opFinish re-checks synchronously, ahead of registerProject, and refuses instead of registering', () => {
+ const body = openProjectBlock()
+ const finish = body.slice(body.indexOf('const opFinish'), body.indexOf('// The probe only matters'))
+ const recheck = finish.indexOf('const opLimit = opOpens() ? recheckAgentProjectOpen() : null')
+ expect(recheck).toBeGreaterThan(-1)
+ expect(finish.indexOf('registerProject(')).toBeGreaterThan(recheck)
+ expect(finish.slice(recheck)).toMatch(
+ /if \(opLimit && !opLimit\.ok\) \{\s+reply\(\{ ok: false, error: opLimit\.message \}\)\s+return null/
+ )
+ // The confirm dialog sits before this point; nothing may sit between the re-check and the write.
+ expect(finish).not.toMatch(/\bawait\b|\.then\(/)
+ // A refused waived registration announces nothing: it was not registered.
+ expect(body).toMatch(/const opDone = opFinish\(opAdopt\)\s+if \(opDone === null\) return\s+setNotice\(/)
+ })
+
+ it('a headless start into a closed project restores its tab only when the limit allows', () => {
+ const body = between('startNodesHeadlessRef.current = async (project, nodes) => {', 'runQueuedNodeRef.current = ')
+ expect(body).toMatch(
+ /shouldUnhideForHeadlessStart\(\s*storedProject,\s*projectsNow\.activeProjectId,\s*useProjectLimit\.getState\(\)\.state,\s*projectsNow\.projects\s*\)/
+ )
+ expect(body).toContain('if (unhidden) projectsNow.unhideProject(project.id)')
+ // The limit-blind predicate is never consulted on its own by the canvas.
+ expect(src).not.toMatch(/\bunhidesForHeadlessStart\(/)
+ })
+})
diff --git a/src/renderer/lib/headlessRun.test.ts b/src/renderer/lib/headlessRun.test.ts
index adef34fa0..9677d9967 100644
--- a/src/renderer/lib/headlessRun.test.ts
+++ b/src/renderer/lib/headlessRun.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import type { CanvasNodeState, PendingLaunch, Project } from '@shared/types'
import type { HeadlessLaunchResult } from '@shared/headless-launch'
+import type { ProjectLimitState } from '@shared/project-limit'
import { coldOpenMessage } from './coldOpen'
import {
claimForHeadless,
@@ -9,6 +10,7 @@ import {
mergeRunNow,
planRunVerb,
savePendingAnywhere,
+ shouldUnhideForHeadlessStart,
startHeadless,
unhidesForHeadlessStart,
type HeadlessStartDeps,
@@ -281,6 +283,47 @@ describe('unhidesForHeadlessStart', () => {
})
})
+describe('shouldUnhideForHeadlessStart — the free-tier project limit', () => {
+ const INACTIVE: ProjectLimitState = { active: false, pro: false, free: 5, allowance: null, dnt: false }
+ const CLAIMED_5: ProjectLimitState = { active: true, pro: false, free: 5, allowance: 5, dnt: false }
+ const NO_ALLOWANCE: ProjectLimitState = { ...CLAIMED_5, allowance: null }
+ const open = (n: number) => Array.from({ length: n }, () => ({}))
+ const closed = { closed: true }
+
+ it('while the limit is off it answers exactly what unhidesForHeadlessStart answers', () => {
+ for (const [p, active] of [
+ [closed, 'p1'],
+ [{ closed: false }, 'p1'],
+ [{ closed: true, ssh: sshProject.ssh }, 'p1'],
+ [closed, '']
+ ] as const) {
+ expect(shouldUnhideForHeadlessStart(p, active, INACTIVE, open(9))).toBe(unhidesForHeadlessStart(p, active))
+ }
+ })
+
+ it('at the limit the tab stays closed — the session still starts, nothing is refused', () => {
+ expect(shouldUnhideForHeadlessStart(closed, 'p1', CLAIMED_5, open(5))).toBe(false)
+ // No allowance yet: a claim would be due, and a headless start never claims or asks.
+ expect(shouldUnhideForHeadlessStart(closed, 'p1', NO_ALLOWANCE, open(5))).toBe(false)
+ // Closed projects are not open ones: they do not count towards the limit.
+ expect(shouldUnhideForHeadlessStart(closed, 'p1', CLAIMED_5, [...open(4), { closed: true }])).toBe(true)
+ })
+
+ it('under the limit, or Pro, it restores the tab', () => {
+ expect(shouldUnhideForHeadlessStart(closed, 'p1', CLAIMED_5, open(4))).toBe(true)
+ expect(shouldUnhideForHeadlessStart(closed, 'p1', { ...CLAIMED_5, pro: true }, open(9))).toBe(true)
+ })
+
+ it('a relay tab never counts, so un-closing one is not an open the limit refuses', () => {
+ expect(shouldUnhideForHeadlessStart({ closed: true, remote: true }, 'p1', CLAIMED_5, open(5))).toBe(true)
+ })
+
+ it('never restores what unhidesForHeadlessStart would not, whatever the limit says', () => {
+ expect(shouldUnhideForHeadlessStart({ closed: true, ssh: sshProject.ssh }, 'p1', CLAIMED_5, open(1))).toBe(false)
+ expect(shouldUnhideForHeadlessStart(closed, '', CLAIMED_5, open(1))).toBe(false)
+ })
+})
+
describe('mergeRunNow + notice', () => {
const closedBase = (ids: string[]) => ({
ok: true as const,
diff --git a/src/renderer/lib/headlessRun.ts b/src/renderer/lib/headlessRun.ts
index 3c9e50be6..4b499c4a6 100644
--- a/src/renderer/lib/headlessRun.ts
+++ b/src/renderer/lib/headlessRun.ts
@@ -7,6 +7,7 @@
import type { CanvasNodeState, PendingLaunch, Project, PtyCreateOptions } from '@shared/types'
import type { HeadlessLaunchFailure, HeadlessLaunchResult } from '@shared/headless-launch'
import { HEADLESS_COLS, HEADLESS_ROWS, localNodePtyOptions } from '@shared/node-pty-options'
+import { countOpenProjects, decideOpen, type ProjectLimitState } from '@shared/project-limit'
import { COLD_OPEN_RUN_HINT } from './coldOpen'
export type RunVerbPlan =
@@ -109,6 +110,26 @@ export function unhidesForHeadlessStart(
return !!project.closed && !project.ssh && activeProjectId !== ''
}
+/**
+ * `unhidesForHeadlessStart`, under the free-tier project limit
+ * (docs/superpowers/specs/2026-10-29-free-tier-project-limit-design.md). Restoring a closed tab
+ * makes a project open, so at the limit the tab simply stays in Recently closed: the session still
+ * starts, nothing is refused and no dialog is shown (nobody pressed anything), and the reply keeps
+ * its "reopen it from the welcome screen" hint — exactly the branch where the predicate says no.
+ * A claim still due is a no as well: a headless start never claims. While the limit is off,
+ * `decideOpen` always allows, so this answers what the predicate answers. A relay tab never counts
+ * as open (spec §3), so un-closing one is not an open the limit has a say in.
+ */
+export function shouldUnhideForHeadlessStart(
+ project: { closed?: boolean; ssh?: Project['ssh']; remote?: Project['remote'] },
+ activeProjectId: string,
+ limit: ProjectLimitState,
+ projects: readonly { closed?: boolean; remote?: boolean }[]
+): boolean {
+ if (!unhidesForHeadlessStart(project, activeProjectId)) return false
+ return !!project.remote || decideOpen(limit, countOpenProjects(projects)) === 'allow'
+}
+
export interface HeadlessStartDeps {
launch(req: { ptyOptions: PtyCreateOptions; command: string }): Promise<HeadlessLaunchResult>
/** Persist `pending` (undefined = cleared) on the node wherever it lives NOW; true = on disk. */
diff --git a/src/renderer/lib/projectLimitGate.test.ts b/src/renderer/lib/projectLimitGate.test.ts
index 68a4ce5dd..522c41e24 100644
--- a/src/renderer/lib/projectLimitGate.test.ts
+++ b/src/renderer/lib/projectLimitGate.test.ts
@@ -415,6 +415,77 @@ describe('checkAgentProjectOpen — the agent open-project verb', () => {
})
})
+describe('recheckAgentProjectOpen — the synchronous re-check right before an agent registers', () => {
+ const MESSAGE = 'free plan: 5 of 5 projects are open; the user has been shown the options'
+
+ it('allows in the same tick, with no claim and no dialog, whenever a person would be allowed', () => {
+ for (const [state, open] of [
+ [INACTIVE, 9],
+ [PRO, 9],
+ [CLAIMED_5, 4],
+ [AT_LIMIT, 4]
+ ] as const) {
+ const t = harness(state, open)
+ const gate = createProjectOpenGate(t.deps)
+ // A plain object, not a promise: the caller registers in this very tick.
+ expect(gate.recheckAgentProjectOpen()).toEqual({ ok: true })
+ expect(t.claim).not.toHaveBeenCalled()
+ expect(t.showDialog).not.toHaveBeenCalled()
+ }
+ })
+
+ it('refuses at the limit with the same message as the async check, and never claims', async () => {
+ const t = harness(CLAIMED_5, 5)
+ const gate = createProjectOpenGate(t.deps)
+ expect(gate.recheckAgentProjectOpen()).toEqual({ ok: false, message: MESSAGE })
+ t.answer('cancel')
+ await settle()
+ t.setNow(1_000_000 + AGENT_DIALOG_QUIET_MS)
+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: false, message: MESSAGE })
+ // No allowance yet (a claim would be due): still refused synchronously, still no claim.
+ const u = harness(AT_LIMIT, 5)
+ expect(createProjectOpenGate(u.deps).recheckAgentProjectOpen()).toEqual({ ok: false, message: MESSAGE })
+ expect(u.claim).not.toHaveBeenCalled()
+ expect(t.claim).not.toHaveBeenCalled()
+ })
+
+ it('two agents at the edge end at the limit, not past it (Review Focus 5)', async () => {
+ const t = harness(CLAIMED_5, 4)
+ const gate = createProjectOpenGate(t.deps)
+ // Both pass the early check while the user is still answering their confirm dialogs.
+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: true })
+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: true })
+ // The first confirm lands: re-checked, registered, the count moves.
+ expect(gate.recheckAgentProjectOpen()).toEqual({ ok: true })
+ t.setOpen(5)
+ // The second one is refused at the store write instead of making a sixth.
+ expect(gate.recheckAgentProjectOpen()).toEqual({ ok: false, message: MESSAGE })
+ })
+
+ it('shows the user the dialog under the same rules as the async check: once per quiet window', async () => {
+ const t = harness(CLAIMED_5, 5)
+ const gate = createProjectOpenGate(t.deps)
+ gate.recheckAgentProjectOpen()
+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'limit' }]])
+ t.answer('cancel')
+ await settle()
+ // Inside the window — whichever check refuses next — the user is not shown it again.
+ t.setNow(1_000_000 + AGENT_DIALOG_QUIET_MS - 1)
+ await gate.checkAgentProjectOpen()
+ gate.recheckAgentProjectOpen()
+ expect(t.showDialog).toHaveBeenCalledTimes(1)
+ // And never stacked on a dialog that is already up.
+ t.setNow(1_000_000 + AGENT_DIALOG_QUIET_MS)
+ const human = gate.gateProjectOpen()
+ await settle()
+ expect(t.showDialog).toHaveBeenCalledTimes(2)
+ gate.recheckAgentProjectOpen()
+ expect(t.showDialog).toHaveBeenCalledTimes(2)
+ t.answer('cancel')
+ await expect(human).resolves.toBe(false)
+ })
+})
+
describe('the live bindings', () => {
beforeEach(() => {
h.claim.mockReset()
diff --git a/src/renderer/lib/projectLimitGate.ts b/src/renderer/lib/projectLimitGate.ts
index d2edb6636..5f326ac6a 100644
--- a/src/renderer/lib/projectLimitGate.ts
+++ b/src/renderer/lib/projectLimitGate.ts
@@ -54,6 +54,7 @@ export type AgentOpenCheck = { ok: true } | { ok: false; message: string }
export interface ProjectOpenGate {
gateProjectOpen(): true | Promise<boolean>
checkAgentProjectOpen(): Promise<AgentOpenCheck>
+ recheckAgentProjectOpen(): AgentOpenCheck
}
/** The dialog that explains a failed claim. A repeated `consent_required` right after the user
@@ -159,6 +160,16 @@ export function createProjectOpenGate(deps: ProjectOpenGateDeps): ProjectOpenGat
void show({ mode: 'limit' }).catch(() => {})
}
+ /** Every agent refusal, from either check: the user is shown the dialog (under showForAgent's
+ * rules) and the agent gets the one sentence (spec §7.5), so the two checks cannot word it twice. */
+ function refuseAgent(state: ProjectLimitState): AgentOpenCheck {
+ showForAgent()
+ return {
+ ok: false,
+ message: `free plan: ${deps.openCount()} of ${effectiveLimit(state)} projects are open; the user has been shown the options`
+ }
+ }
+
async function checkAgentProjectOpen(): Promise<AgentOpenCheck> {
let state = deps.getState()
let d = decideOpen(state, deps.openCount())
@@ -171,14 +182,19 @@ export function createProjectOpenGate(deps: ProjectOpenGateDeps): ProjectOpenGat
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 refuseAgent(state)
}
- return { gateProjectOpen, checkAgentProjectOpen }
+ /** The agent verb's last word, asked in the same tick as its store write: the user's confirm
+ * dialog sits between `checkAgentProjectOpen` and the registration, and another open may have
+ * landed meanwhile. Synchronous by construction — it never claims; a claim still due is a
+ * refusal (the early check had its chance to claim). */
+ function recheckAgentProjectOpen(): AgentOpenCheck {
+ const state = deps.getState()
+ return decideOpen(state, deps.openCount()) === 'allow' ? { ok: true } : refuseAgent(state)
+ }
+
+ return { gateProjectOpen, checkAgentProjectOpen, recheckAgentProjectOpen }
}
/** The gate's deps bound to the live stores and bridge. Exported for its tests. */
@@ -206,3 +222,6 @@ 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.checkAgentProjectOpen
+
+/** The synchronous re-check immediately before an agent's registration; same refusal message. */
+export const recheckAgentProjectOpen = liveGate.recheckAgentProjectOpen