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
fix(project-limit): claim at the agent's write when the early check could not
reviewab651e0436a1
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex c0c8264b5..922780d35 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -288,7 +288,12 @@ import { SAS_COMPARE_HINT } from '@shared/remote/sas'import { promptDialog } from '../components/promptDialog'import { UpgradeDialog } from '../components/UpgradeDialog'import { ProjectLimitDialog } from '../components/ProjectLimitDialog'-import { checkAgentProjectOpen, gateProjectOpen, recheckAgentProjectOpen } from '../lib/projectLimitGate'+import {+ checkAgentProjectOpen,+ finishAgentProjectOpen,+ gateProjectOpen,+ type AgentOpenFinish+} from '../lib/projectLimitGate'import { countOpenProjects, decideOpen } from '@shared/project-limit'import { opensProject, type OpenAction } from '../lib/projectOpens'import { LiveLinkDialog } from '../components/LiveLinkDialog'@@ -13606,10 +13611,11 @@ export function Canvas() {// 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.+ // one; and again in opFinish, whose final decision shares one tick with 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 or there, so a path that+ // was synchronous stays so.const opOpens = (): boolean =>opensProject(useProjects.getState().projects, { kind: 'register', cwd: resolvedCwd })if (@@ -13628,23 +13634,29 @@ export function Canvas() {// 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 — 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 })+ // Exactly one reply either way. The registration runs inside finishAgentProjectOpen, right+ // after its final decision and in the same tick; the result is synchronous unless the limit+ // has to claim first (an open landed during the confirm dialog), the one promise branch.+ const opFinish = (adoptProbed?: Project): string | null | Promise<string | null> => {+ const settle = (f: AgentOpenFinish<string>): string | null => {+ if (f.ok) return f.value+ reply({ ok: false, error: f.message })return null}- const r = useProjects.getState().registerProject({- resolvedCwd,- name: args.name,- color: opColor,- ...(adoptProbed ? { probed: adoptProbed } : {})+ const finished = finishAgentProjectOpen(opOpens, () => {+ const r = useProjects.getState().registerProject({+ resolvedCwd,+ name: args.name,+ color: opColor,+ ...(adoptProbed ? { probed: adoptProbed } : {})+ })+ recordAttachConsent(sourceNodeId, r.project.id)+ void writeDisk()+ const done = openProjectReply(r.project, r.created, r.adopted)+ reply({ ok: true, ...done })+ return done.message})- recordAttachConsent(sourceNodeId, r.project.id)- void writeDisk()- const done = openProjectReply(r.project, r.created, r.adopted)- reply({ ok: true, ...done })- return done.message+ return finished instanceof Promise ? finished.then(settle) : settle(finished)}// The probe only matters when no project owns this cwd yet (adopt-vs-create copy) — an// idempotent hit must not pay a folder read.@@ -13663,7 +13675,7 @@ export function Canvas() {})if (opPlan.kind === 'silent') {// This caller already passed a human decision for this project (Q1): idempotent, quiet.- opFinish()+ await opFinish()return}// What an answer adopts, decided once so the waived path and the confirmed path register@@ -13677,7 +13689,7 @@ export function Canvas() {const opWaiver = controlConfirmDecision(verb, ctlProject?.id)if (opWaiver.via) {// A waived registration still announces itself, naming the waiver that let it through.- const opDone = opFinish(opAdopt)+ const opDone = await opFinish(opAdopt)if (opDone === null) returnsetNotice({kind: 'info',@@ -13704,7 +13716,7 @@ export function Canvas() {onExpire: () => reply({ ok: false, error: 'expired before the user answered' }),onConfirm: () => {setConfirm(null)- opFinish(opAdopt)+ void opFinish(opAdopt)},onCancel: () => reply({ ok: false, error: 'denied by user' })})diff --git a/src/renderer/canvas/project-limit-opens.source.test.ts b/src/renderer/canvas/project-limit-opens.source.test.tsindex 5714532fc..04a1f31c2 100644--- a/src/renderer/canvas/project-limit-opens.source.test.ts+++ b/src/renderer/canvas/project-limit-opens.source.test.ts@@ -122,19 +122,29 @@ describe('project-limit gate in the agent open-project verb (Task 19)', () => {}})- it('opFinish re-checks synchronously, ahead of registerProject, and refuses instead of registering', () => {+ it('opFinish registers inside finishAgentProjectOpen: nothing between the final decision and registerProject', () => {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 gate takes its final decision and calls this callback in the same tick+ // (lib/projectLimitGate.test.ts proves that half). What only the source can show is that the+ // callback is synchronous and its first statement is the store write — no await, no async+ // callback, nothing in front of registerProject.+ expect(finish).toMatch(+ /finishAgentProjectOpen\(opOpens, \(\) => \{\s+const r = useProjects\.getState\(\)\.registerProject\(\{/)- // 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\(/)+ expect(finish.match(/registerProject\(/g)).toHaveLength(1)+ const callback = finish.slice(finish.indexOf('finishAgentProjectOpen(opOpens'), finish.indexOf('return done.message'))+ expect(callback).not.toMatch(/\bawait\b|\.then\(|\basync\b/)+ // A refusal replies once, from the gate's message, and returns null; the claim branch is the+ // only promise, settled the same way.+ expect(finish).toMatch(/if \(f\.ok\) return f\.value\s+reply\(\{ ok: false, error: f\.message \}\)\s+return null/)+ expect(finish).toContain('return finished instanceof Promise ? finished.then(settle) : settle(finished)')+ // Every caller copes with the claim branch: the two in the handler await it, the dialog's+ // confirm fires it. A refused waived registration announces nothing: it was not registered.+ expect(body).toContain('await opFinish()\n return')+ expect(body).toMatch(/const opDone = await opFinish\(opAdopt\)\s+if \(opDone === null\) return\s+setNotice\(/)+ expect(body).toMatch(/onConfirm: \(\) => \{\s+setConfirm\(null\)\s+void opFinish\(opAdopt\)\s+\}/)+ expect(body.match(/opFinish\(/g)).toHaveLength(3)})it('a headless start into a closed project restores its tab only when the limit allows', () => {diff --git a/src/renderer/lib/projectLimitGate.test.ts b/src/renderer/lib/projectLimitGate.test.tsindex 522c41e24..0428ad4f6 100644--- a/src/renderer/lib/projectLimitGate.test.ts+++ b/src/renderer/lib/projectLimitGate.test.ts@@ -415,74 +415,173 @@ describe('checkAgentProjectOpen — the agent open-project verb', () => {})})-describe('recheckAgentProjectOpen — the synchronous re-check right before an agent registers', () => {+describe('finishAgentProjectOpen — the final decision and the agent registration, in one tick', () => {const MESSAGE = 'free plan: 5 of 5 projects are open; the user has been shown the options'+ const CLAIMED_12: ProjectLimitState = { ...AT_LIMIT, allowance: 12 }++ /** A register callback that counts its calls and, like registerProject, adds an open project. */+ function registrar(t: Harness, open: { n: number }) {+ return vi.fn(() => {+ open.n += 1+ t.setOpen(open.n)+ return `registered #${open.n}`+ })+ }- it('allows in the same tick, with no claim and no dialog, whenever a person would be allowed', () => {- for (const [state, open] of [+ it('allows and registers in the same tick, with no claim and no dialog, whenever a person would be allowed', () => {+ for (const [state, n] 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 })+ const t = harness(state, n)+ const register = registrar(t, { n })+ // A plain object, not a promise: the write has already happened when the call returns.+ expect(createProjectOpenGate(t.deps).finishAgentProjectOpen(() => true, register)).toEqual({+ ok: true,+ value: `registered #${n + 1}`+ })+ expect(register).toHaveBeenCalledTimes(1)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 () => {+ it('a registration that opens nothing new is never refused, even past the limit', () => {+ const t = harness(CLAIMED_5, 7)+ const register = vi.fn(() => 'hit')+ expect(createProjectOpenGate(t.deps).finishAgentProjectOpen(() => false, register)).toEqual({+ ok: true,+ value: 'hit'+ })+ expect(t.showDialog).not.toHaveBeenCalled()+ })++ it('refuses at a known allowance synchronously, with the async check’s message, and writes nothing', async () => {const t = harness(CLAIMED_5, 5)const gate = createProjectOpenGate(t.deps)- expect(gate.recheckAgentProjectOpen()).toEqual({ ok: false, message: MESSAGE })+ const register = vi.fn(() => 'never')+ expect(gate.finishAgentProjectOpen(() => true, register)).toEqual({ ok: false, message: MESSAGE })+ expect(register).not.toHaveBeenCalled()+ expect(t.claim).not.toHaveBeenCalled()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 open = { n: 4 }+ const register = registrar(t, open)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 })+ expect(gate.finishAgentProjectOpen(() => true, register)).toEqual({ ok: true, value: 'registered #5' })+ // The second is refused at the store write instead of making a sixth.+ expect(gate.finishAgentProjectOpen(() => true, register)).toEqual({ ok: false, message: MESSAGE })+ expect(register).toHaveBeenCalledTimes(1)+ })++ it('a claim the early check never made: due at the write, claimed there, registered on a high allowance', async () => {+ const t = harness(AT_LIMIT, 4)+ const gate = createProjectOpenGate(t.deps)+ // At 4 of 5 with no allowance yet the early check allows without claiming.+ await expect(gate.checkAgentProjectOpen()).resolves.toEqual({ ok: true })+ expect(t.claim).not.toHaveBeenCalled()+ // A fifth project opens while the user answers the confirm dialog.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 })+ const open = { n: 5 }+ const register = registrar(t, open)+ // The claim's answer is decided on directly: the store has not heard it (`getState` still+ // answers AT_LIMIT), exactly as for the other two paths.+ t.claim.mockResolvedValue({ ok: true, state: CLAIMED_12 })+ const finished = gate.finishAgentProjectOpen(() => true, register)+ expect(finished).toBeInstanceOf(Promise)+ expect(register).not.toHaveBeenCalled()+ await expect(finished).resolves.toEqual({ ok: true, value: 'registered #6' })+ expect(t.claim).toHaveBeenCalledTimes(1)+ expect(t.showDialog).not.toHaveBeenCalled()+ expect(t.setChecking).not.toHaveBeenCalled()+ })++ it('a claim the early check never made: refused with the message when the claim leaves it at 5', async () => {+ const t = harness(AT_LIMIT, 5)+ const gate = createProjectOpenGate(t.deps)+ const register = vi.fn(() => 'never')+ t.claim.mockResolvedValue({ ok: true, state: CLAIMED_5 })+ await expect(gate.finishAgentProjectOpen(() => true, register)).resolves.toEqual({ ok: false, message: MESSAGE })+ expect(register).not.toHaveBeenCalled()+ expect(t.showDialog.mock.calls).toEqual([[{ mode: 'limit' }]])+ // A failed claim (or one that needs consent) is a refusal too — never the consent dialog.+ const u = harness({ ...AT_LIMIT, dnt: true }, 5)+ u.claim.mockResolvedValue({ ok: false, error: 'consent_required', state: { ...AT_LIMIT, dnt: true } })+ await expect(createProjectOpenGate(u.deps).finishAgentProjectOpen(() => true, register)).resolves.toEqual({+ ok: false,+ message: MESSAGE+ })+ expect(u.setConsent).not.toHaveBeenCalled()+ expect(register).not.toHaveBeenCalled()+ })++ it('two claims at the edge: the decision and the write share one tick, so only one registers', async () => {+ // 5 open, no allowance; both claims answer 6. Were there a yield between deciding and+ // registering, both would decide on 5 < 6 and the canvas would end at 7.+ const t = harness(AT_LIMIT, 5)+ const open = { n: 5 }+ const register = registrar(t, open)+ const gate = createProjectOpenGate(t.deps)+ const answer = deferred<ClaimResult>()+ t.claim.mockReturnValue(answer.promise)+ const a = gate.finishAgentProjectOpen(() => true, register)+ const b = gate.finishAgentProjectOpen(() => true, register)+ answer.resolve({ ok: true, state: { ...AT_LIMIT, allowance: 6 } })+ await expect(a).resolves.toEqual({ ok: true, value: 'registered #6' })+ await expect(b).resolves.toEqual({+ ok: false,+ message: 'free plan: 6 of 6 projects are open; the user has been shown the options'+ })+ expect(register).toHaveBeenCalledTimes(1)+ })++ it('opens is asked at the final decision: a project opened meanwhile is a hit, not a refusal', async () => {+ const t = harness(AT_LIMIT, 5)+ let opens = true+ const answer = deferred<ClaimResult>()+ t.claim.mockReturnValue(answer.promise)+ const register = vi.fn(() => 'hit')+ const finished = createProjectOpenGate(t.deps).finishAgentProjectOpen(() => opens, register)+ // The user reopens that very project by hand while the claim is in flight.+ opens = false+ answer.resolve({ ok: true, state: CLAIMED_5 })+ await expect(finished).resolves.toEqual({ ok: true, value: 'hit' })})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()+ const register = vi.fn(() => 'never')+ gate.finishAgentProjectOpen(() => true, register)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()+ gate.finishAgentProjectOpen(() => true, register)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()+ gate.finishAgentProjectOpen(() => true, register)expect(t.showDialog).toHaveBeenCalledTimes(2)t.answer('cancel')await expect(human).resolves.toBe(false)+ expect(register).not.toHaveBeenCalled()})})diff --git a/src/renderer/lib/projectLimitGate.ts b/src/renderer/lib/projectLimitGate.tsindex 5f326ac6a..3f1a9674e 100644--- a/src/renderer/lib/projectLimitGate.ts+++ b/src/renderer/lib/projectLimitGate.ts@@ -51,10 +51,13 @@ export interface ProjectOpenGateDeps {export type AgentOpenCheck = { ok: true } | { ok: false; message: string }+/** An agent registration run under the limit: what `register` returned, or the refusal. */+export type AgentOpenFinish<T> = { ok: true; value: T } | { ok: false; message: string }+export interface ProjectOpenGate {gateProjectOpen(): true | Promise<boolean>checkAgentProjectOpen(): Promise<AgentOpenCheck>- recheckAgentProjectOpen(): AgentOpenCheck+ finishAgentProjectOpen<T>(opens: () => boolean, register: () => T): AgentOpenFinish<T> | Promise<AgentOpenFinish<T>>}/** The dialog that explains a failed claim. A repeated `consent_required` right after the user@@ -162,7 +165,7 @@ export function createProjectOpenGate(deps: ProjectOpenGateDeps): ProjectOpenGat/** 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 {+ function refuseAgent(state: ProjectLimitState): Extract<AgentOpenCheck, { ok: false }> {showForAgent()return {ok: false,@@ -185,16 +188,37 @@ export function createProjectOpenGate(deps: ProjectOpenGateDeps): ProjectOpenGatreturn refuseAgent(state)}- /** 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 {+ /**+ * The agent verb's last word, and its store write: the user's confirm dialog sits between+ * `checkAgentProjectOpen` and the registration, and another open may have landed meanwhile. The+ * FINAL decision and `register()` run in one tick — nothing can run between the count read here+ * and the write — so two agents at the edge cannot both pass on one count (plan Review Focus 5).+ *+ * Synchronous whenever the limit decides at once (allow — every call while it is off — or block).+ * Only a claim still due returns a promise, and it is due exactly when the early check did NOT+ * claim: it saw room (4 of 5, no allowance yet) and an open landed before this point. That claim+ * is made here (never the consent dialog, never the spinner), and the decision is taken on its+ * own answer — the store may not have heard it yet, the rule both other paths follow — with the+ * live count, `register()` following in the same continuation. A legacy install whose allowance+ * is well above FREE is therefore registered, not refused at "5 of 5".+ *+ * `opens` is asked at the decision itself: a registration that no longer opens a project (it was+ * opened meanwhile) is never refused.+ */+ function finishAgentProjectOpen<T>(+ opens: () => boolean,+ register: () => T+ ): AgentOpenFinish<T> | Promise<AgentOpenFinish<T>> {+ const decideAndRegister = (state: ProjectLimitState): AgentOpenFinish<T> => {+ if (opens() && decideOpen(state, deps.openCount()) !== 'allow') return refuseAgent(state)+ return { ok: true, value: register() }+ }const state = deps.getState()- return decideOpen(state, deps.openCount()) === 'allow' ? { ok: true } : refuseAgent(state)+ if (!opens() || decideOpen(state, deps.openCount()) !== 'claim') return decideAndRegister(state)+ return claim().then((r) => decideAndRegister(r.state))}- return { gateProjectOpen, checkAgentProjectOpen, recheckAgentProjectOpen }+ return { gateProjectOpen, checkAgentProjectOpen, finishAgentProjectOpen }}/** The gate's deps bound to the live stores and bridge. Exported for its tests. */@@ -223,5 +247,5 @@ 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+/** Run an agent's `open-project` registration under the limit, deciding and writing in one tick. */+export const finishAgentProjectOpen = liveGate.finishAgentProjectOpen