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): gate every way a person opens a project
reviewaff6003b62ea
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 41479ccc0..7f867350b 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -288,6 +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 { opensProject, type OpenAction } from '../lib/projectOpens'import { LiveLinkDialog } from '../components/LiveLinkDialog'import { requireProOr } from '../state/upgradeGate'import { startWatchLinkSync, useWatchLinks } from '../state/watchLinks'@@ -6382,6 +6384,11 @@ export function Canvas() {// tab at all (plus an unhandled rejection) where the old code always created one. A failed// probe simply means "we learned nothing about this folder" → the virgin-folder path.const probed = await api.workspace.probeFolder(clonedPath).catch(() => null)+ // The project limit (lib/projectLimitGate.ts) is the LAST await before the store write, so two+ // opens at the edge cannot both pass on one count. Declined, the clone stays on disk with no+ // tab: the user chose Cancel.+ const g = opensProject(useProjects.getState().projects, { kind: 'new' }) ? gateProjectOpen() : true+ if (g !== true && !(await g)) returnconst project = probed? useProjects.getState().adoptProject({ ...probed, closed: false }): useProjects.getState().addProject(name, clonedPath)@@ -10209,14 +10216,16 @@ export function Canvas() {)/** Ask before opening a project this desktop handed to a hosted team: the server's core writes- * that canvas now, and opening it here too makes a second writer that overwrites it. True = go- * ahead, and going ahead takes the project back — the mark is cleared, so this desktop saves and- * mirrors it again (the caller saves), and its agent nodes skip their next automatic resume. A- * project that was never handed off answers true. */+ * that canvas now, and opening it here too makes a second writer that overwrites it. Null = do+ * not open. Otherwise go ahead, calling the returned take-back immediately before the open:+ * going ahead takes the project back — the mark is cleared, so this desktop saves and mirrors it+ * again (the caller saves), and its agent nodes skip their next automatic resume. It is handed+ * back rather than run here so a project-limit gate that declines after this question leaves+ * the mark in place. A project that was never handed off answers a take-back that does nothing. */const confirmHandedOffReopen = useCallback(- async (id: string): Promise<boolean> => {+ async (id: string): Promise<(() => void) | null> => {const marked = useProjects.getState().getProject(id)?.handedOffTo- if (!marked) return true+ if (!marked) return () => {}const hostId = marked.hostId// The team's name from this device's bookmark of it. Only a label, so every failure (no// relay on this surface, an IPC error, no bookmark for that team) falls back to null.@@ -10231,14 +10240,14 @@ export function Canvas() {}// Read again after the lookup: the project may have been deleted or taken back meanwhile.const project = useProjects.getState().getProject(id)- if (!project) return false+ if (!project) return nullconst message = handedOffWarning(project, label)- if (!message) return true+ if (!message) return () => {}// One actionable dialog at a time (`confirmFlags`): replacing an open one would drop its// answer. Say why nothing opened rather than doing nothing.if (confirmBusy()) {setNotice({ kind: 'error', text: `Answer the open dialog first, then open ${project.name} again.` })- return false+ return null}const ok = await new Promise<boolean>((resolve) =>setConfirm({@@ -10254,27 +10263,41 @@ export function Canvas() {}))if (ok) {- useProjects.getState().setHandedOffTo(id, undefined)- // Its agents would resume the conversations the team's server is running: each one skips- // its automatic cold-resume once, and says why (terminal/handed-off-resume.ts).- skipNextColdResumeFor(useProjects.getState().getProject(id)?.nodes ?? [])+ return () => {+ useProjects.getState().setHandedOffTo(id, undefined)+ // Its agents would resume the conversations the team's server is running: each one skips+ // its automatic cold-resume once, and says why (terminal/handed-off-resume.ts).+ skipNextColdResumeFor(useProjects.getState().getProject(id)?.nodes ?? [])+ }}- return ok+ return null},[confirmBusy, setConfirm])/** The reopen every human path uses (Welcome's and the sidebar's "Recently closed", ⇧⌘T, ⌘K,* travel, "Open recent", Set folder…). A handed-off project asks first; any other reopens at- * once, synchronously, exactly as before the question existed. Resolves false when the user- * declined or the reopen was refused (a team tab), so a caller that staged follow-up work (a- * focus, a resume) can drop it. */+ * once, synchronously, exactly as before the question existed — unless the project limit has to+ * decide (lib/projectLimitGate.ts: synchronous whenever it allows). Resolves false when the+ * user declined (either question) or the reopen was refused (a team tab), so a caller that+ * staged follow-up work (a focus, a resume) can drop it. The gate is the last await before+ * `reopenProjectUnchecked`, so two reopens at the edge cannot both pass on one count. */const reopenProject = useCallback((id: string): Promise<boolean> => {if (!useProjects.getState().getProject(id)?.handedOffTo) {- return Promise.resolve(reopenProjectUnchecked(id))- }- return confirmHandedOffReopen(id).then((ok) => ok && reopenProjectUnchecked(id))+ const g = opensProject(useProjects.getState().projects, { kind: 'reopen', id }) ? gateProjectOpen() : true+ if (g === true) return Promise.resolve(reopenProjectUnchecked(id))+ return g.then((ok) => ok && reopenProjectUnchecked(id))+ }+ return confirmHandedOffReopen(id).then((takeBack) => {+ if (!takeBack) return false+ const g = opensProject(useProjects.getState().projects, { kind: 'reopen', id }) ? gateProjectOpen() : true+ const open = (): boolean => {+ takeBack()+ return reopenProjectUnchecked(id)+ }+ return g === true ? open() : g.then((ok) => ok && open())+ })},[confirmHandedOffReopen, reopenProjectUnchecked])@@ -17780,7 +17803,12 @@ export function Canvas() {const existing = useProjects.getState().projects.find((p) => !!p.ssh && sameSshEndpoint(p.ssh, ssh))- if (existing?.handedOffTo && !(await confirmHandedOffReopen(existing.id))) return+ const takeBack = existing?.handedOffTo ? await confirmHandedOffReopen(existing.id) : undefined+ if (takeBack === null) return+ // The project limit is the LAST await before the store write (lib/projectLimitGate.ts).+ const g = opensProject(useProjects.getState().projects, { kind: 'ssh', ssh }) ? gateProjectOpen() : true+ if (g !== true && !(await g)) return+ takeBack?.()commitActiveToStore()useProjects.getState().openSshProject(input.label, ssh)// Same contract as onRepoCloned: the welcome screen waits behind the SSH dialog and@@ -17792,7 +17820,11 @@ export function Canvas() {[commitActiveToStore, writeDisk, confirmHandedOffReopen])- const addProject = useCallback(() => {+ // Synchronous end to end while the project limit allows (its gate answers `true` in the same+ // tick); otherwise it waits for the limit dialog and opens only if that makes room.+ const addProject = useCallback(async (): Promise<void> => {+ const g = opensProject(useProjects.getState().projects, { kind: 'new' }) ? gateProjectOpen() : true+ if (g !== true && !(await g)) returncommitActiveToStore()const project = useProjects.getState().addProject()useProjects.getState().setActive(project.id)@@ -17803,9 +17835,10 @@ export function Canvas() {* dialog and the drag-and-drop entry point: a folder maps to one project, and this is the* ONE place that decides whether to reuse/reopen an already-registered project, adopt an* existing `.nodeterm/project.json` (git clone, synced copy, another machine's project), or- * create a brand-new one. */+ * create a brand-new one. Resolves false only when the project limit declined the open (the+ * user cancelled its dialog): nothing was opened, and the caller should say nothing either. */const openOrAdoptFolder = useCallback(- async (folder: string): Promise<void> => {+ async (folder: string): Promise<boolean> => {commitActiveToStore()// A folder maps to one project: reuse the already-registered one first…// A relay tab carries the HOST's cwd: the same path on two machines must not route a local@@ -17814,7 +17847,12 @@ export function Canvas() {if (existing) {// That reuse reopens the project, so one handed to a hosted team (an SSH project can carry// a local folder too, via "Set folder…") asks first, like every other reopen.- if (existing.handedOffTo && !(await confirmHandedOffReopen(existing.id))) return+ const takeBack = existing.handedOffTo ? await confirmHandedOffReopen(existing.id) : undefined+ if (takeBack === null) return true+ // The project limit is the LAST await before the store write (lib/projectLimitGate.ts).+ const g = opensProject(useProjects.getState().projects, { kind: 'folder', folder }) ? gateProjectOpen() : true+ if (g !== true && !(await g)) return false+ takeBack?.()useProjects.getState().openFolderProject(folder)// An `unavailable` placeholder never recovers on its own: a save emits a header-only ref// for it (never a file), so a deleted project.json stays deleted and every later load@@ -17834,21 +17872,26 @@ export function Canvas() {// …else adopt the folder's own .nodeterm/project.json (git clone, synced copy,// another machine's project) — only a virgin folder gets a brand-new project.const probed = await api.workspace.probeFolder(folder)+ // Adopting always appends a project; openFolderProject may still find one opened meanwhile.+ const action: OpenAction = probed ? { kind: 'new' } : { kind: 'folder', folder }+ const g = opensProject(useProjects.getState().projects, action) ? gateProjectOpen() : true+ if (g !== true && !(await g)) return falseif (probed) useProjects.getState().adoptProject({ ...probed, closed: false })else useProjects.getState().openFolderProject(folder)}void writeDisk()+ return true},[commitActiveToStore, writeDisk, confirmHandedOffReopen])- /** Returns true when a folder was picked (false on cancel), so callers like the welcome- * screen can keep their overlay up until the picker actually resolves. */+ /** Returns true when a folder was picked (false on cancel, of the picker or of the project+ * limit's dialog), so callers like the welcome screen can keep their overlay up until the+ * picker actually resolves. */const addProjectFromFolder = useCallback(async (): Promise<boolean> => {const folder = await window.nodeTerminal.dialog.selectFolder()if (!folder) return false- await openOrAdoptFolder(folder)- return true+ return await openOrAdoptFolder(folder)}, [openOrAdoptFolder])// Drop a folder anywhere in the app (canvas background, Welcome screen, general chrome) → open@@ -17874,9 +17917,10 @@ export function Canvas() {.filter((p): p is string => !!p)// Sequential, not Promise.all: each folder's commitActiveToStore/writeDisk must not race// the next folder's. The last resolved folder ends up active (openFolderProject's existing- // single-folder activation semantics).+ // single-folder activation semantics). A declined open (the project limit's dialog+ // cancelled) ends the batch: the rest would only raise that dialog again, once per folder.void (async () => {- for (const folder of paths) await openOrAdoptFolder(folder)+ for (const folder of paths) if (!(await openOrAdoptFolder(folder))) break})()}window.addEventListener('dragover', onDragOver)@@ -18484,7 +18528,8 @@ export function Canvas() {returncase 'open-folder':void openOrAdoptFolder(plan.folder)- .then(() => {+ .then((opened) => {+ if (!opened) return // the project limit's dialog was cancelled: nothing to resumesetWelcomeOpen(false)const landed = useProjects.getState()@@ -18553,7 +18598,8 @@ export function Canvas() {let projectId = accepted.projectIdif (accepted.newProjectCwd) {const folder = comparablePath(accepted.newProjectCwd)- await openOrAdoptFolder(accepted.newProjectCwd)+ // Declined at the project limit (its dialog cancelled): the user already chose; say nothing.+ if (!(await openOrAdoptFolder(accepted.newProjectCwd))) returnprojectId = useProjects.getState().projects.find((p) => !p.ssh && !p.remote && p.cwd && comparablePath(p.cwd) === folder)?.id@@ -19203,7 +19249,7 @@ export function Canvas() {icon: <IconGroup />,run: () => setSpawnTeamDialog({})},- { id: 'new-project', label: 'New project', icon: <IconProject />, run: () => addProject() },+ { id: 'new-project', label: 'New project', icon: <IconProject />, run: () => void addProject() },{ id: 'clone-repo', label: 'Clone repository…', icon: <IconProject />, run: () => setCloneDialogOpen(true) },{id: 'new-remote',@@ -20161,7 +20207,7 @@ export function Canvas() {<WelcomeScreenonNewProject={() => {setWelcomeOpen(false)- addProject()+ void addProject()}}onOpenFolder={() => {// Keep the welcome screen up behind the native picker; dismiss it only once adiff --git a/src/renderer/canvas/handed-off-reopen.source.test.ts b/src/renderer/canvas/handed-off-reopen.source.test.tsindex 9d7baafee..a053697d0 100644--- a/src/renderer/canvas/handed-off-reopen.source.test.ts+++ b/src/renderer/canvas/handed-off-reopen.source.test.ts@@ -25,10 +25,28 @@ describe('handed-off reopen guard in Canvas', () => {expect(ask).toContain('handedOffWarning(project, label)')expect(ask).toContain("confirmLabel: 'Open here anyway'")expect(ask).toContain('danger: true')- expect(ask).toMatch(/if \(ok\) \{\s+useProjects\.getState\(\)\.setHandedOffTo\(id, undefined\)/)+ // The take-back is HANDED BACK, not run: a project-limit gate after the question may still+ // decline the open, and a declined open must leave the mark in place.+ expect(ask).toMatch(/if \(ok\) \{\s+return \(\) => \{\s+useProjects\.getState\(\)\.setHandedOffTo\(id, undefined\)/)// …and its agent nodes skip their next automatic resume (the team's server runs those// conversations): the decision is proven in terminal/handed-off-resume.test.ts.expect(ask).toMatch(/if \(ok\) \{[\s\S]*?skipNextColdResumeFor\(useProjects\.getState\(\)\.getProject\(id\)\?\.nodes \?\? \[\]\)/)+ expect(ask.match(/setHandedOffTo\(/g)).toHaveLength(1)+ // Every caller runs the take-back only once the project-limit gate has let the open through.+ for (const [decl, gate] of [+ ['const reopenProject = useCallback(', "{ kind: 'reopen', id }"],+ ['const createSshProject = useCallback(', "{ kind: 'ssh', ssh }"],+ ['const openOrAdoptFolder = useCallback(', "{ kind: 'folder', folder }"]+ ]) {+ const body = between(decl, CALLBACK_END)+ const asked = body.indexOf('confirmHandedOffReopen(')+ const gated = body.indexOf(`opensProject(useProjects.getState().projects, ${gate}) ? gateProjectOpen() : true`, asked)+ expect(asked, decl).toBeGreaterThan(-1)+ expect(gated, decl).toBeGreaterThan(asked)+ const takeBackCall = /takeBack(\?\.)?\(\)/+ expect(body.slice(0, gated).search(takeBackCall), decl).toBe(-1)+ expect(body.slice(gated).search(takeBackCall), decl).toBeGreaterThan(-1)+ }// The team label is display only: its lookup fails open to null.expect(ask).toMatch(/try \{\n\s+const list = await window\.nodeTerminal\.relayHosted\?\.bookmarks\(\)/)})diff --git a/src/renderer/canvas/project-limit-opens.source.test.ts b/src/renderer/canvas/project-limit-opens.source.test.tsnew file mode 100644index 000000000..3f68c7646--- /dev/null+++ b/src/renderer/canvas/project-limit-opens.source.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for the project-limit placement rule (free-tier project limit plan, Task 18 /+ * Review Focus 5). What the gate decides is proven in lib/projectLimitGate.test.ts and which+ * actions open a project in lib/projectOpens.test.ts; what only a source read can pin is WHERE each+ * human open path asks: the gate is the last await before the store mutation, so two opens at the+ * edge cannot both pass on one count, and it is skipped (no gate call at all) when the action+ * opens nothing new.+ */+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++function between(start: string, end: string): string {+ const a = src.indexOf(start)+ expect(a, start).toBeGreaterThan(-1)+ const b = src.indexOf(end, a + start.length)+ expect(b, end).toBeGreaterThan(a)+ return src.slice(a, b)+}++const CALLBACK_END = '\n )\n'+const gateFor = (action: string): string =>+ `const g = opensProject(useProjects.getState().projects, ${action}) ? gateProjectOpen() : true`+const AWAIT_GATE = 'if (g !== true && !(await g)) return'++/** In `body`, the gate for `action` is followed by its await and then `mutation`, with no other+ * await in between. Returns the gate's offset so callers can check what precedes it. */+function expectGateRightBefore(body: string, action: string, mutation: string, from = 0): number {+ const gate = body.indexOf(gateFor(action), from)+ expect(gate, action).toBeGreaterThan(-1)+ const awaited = body.indexOf(AWAIT_GATE, gate)+ expect(awaited, action).toBeGreaterThan(gate)+ const mutated = body.indexOf(mutation, awaited)+ expect(mutated, mutation).toBeGreaterThan(awaited)+ const window = body.slice(awaited + AWAIT_GATE.length, mutated)+ expect(window, `${action} → ${mutation}`).not.toMatch(/\bawait\b|\.then\(/)+ return gate+}++describe('project-limit gate placement in Canvas', () => {+ it('New project: the gate comes first, then the synchronous add', () => {+ const body = between('const addProject = useCallback(', '}, [commitActiveToStore, writeDisk])')+ const gate = expectGateRightBefore(body, "{ kind: 'new' }", 'useProjects.getState().addProject()')+ expect(body.indexOf('commitActiveToStore()')).toBeGreaterThan(gate)+ })++ it('Clone: the gate comes after the probe, immediately before the adopt/add', () => {+ const body = between('const onRepoCloned = useCallback(', CALLBACK_END)+ const gate = expectGateRightBefore(body, "{ kind: 'new' }", 'useProjects.getState().adoptProject(')+ expect(body.indexOf('await api.workspace.probeFolder(clonedPath)')).toBeLessThan(gate)+ })++ it('SSH open: the gate comes after the handed-off question, immediately before openSshProject', () => {+ const body = between('const createSshProject = useCallback(', CALLBACK_END)+ const gate = expectGateRightBefore(body, "{ kind: 'ssh', ssh }", '.openSshProject(input.label, ssh)')+ expect(body.indexOf('await confirmHandedOffReopen(existing.id)')).toBeLessThan(gate)+ })++ it('Open folder: both branches ask after their own awaits, immediately before the store write', () => {+ const body = between('const openOrAdoptFolder = useCallback(', CALLBACK_END)+ const reuse = expectGateRightBefore(body, "{ kind: 'folder', folder }", '.openFolderProject(folder)')+ expect(body.indexOf('await confirmHandedOffReopen(existing.id)')).toBeLessThan(reuse)+ const fresh = expectGateRightBefore(body, 'action', '.adoptProject({ ...probed, closed: false })', reuse + 1)+ expect(body.indexOf('await api.workspace.probeFolder(folder)')).toBeLessThan(fresh)+ // A declined open says so to its caller (no toast here, and none there either).+ expect(body.match(/if \(g !== true && !\(await g\)\) return false/g)).toHaveLength(2)+ })++ it('Reopen keeps its synchronous path when the gate allows at once', () => {+ const body = between('const reopenProject = useCallback(', CALLBACK_END)+ const gate = body.indexOf(gateFor("{ kind: 'reopen', id }"))+ expect(gate).toBeGreaterThan(-1)+ expect(body.indexOf('if (g === true) return Promise.resolve(reopenProjectUnchecked(id))')).toBeGreaterThan(gate)+ expect(body).toContain('return g.then((ok) => ok && reopenProjectUnchecked(id))')+ // The handed-off branch: the question, then the gate, then the open in the same continuation.+ const asked = body.indexOf('confirmHandedOffReopen(id)')+ expect(body.indexOf(gateFor("{ kind: 'reopen', id }"), asked)).toBeGreaterThan(asked)+ expect(body).toContain('return g === true ? open() : g.then((ok) => ok && open())')+ })++ it('every gate call is guarded by opensProject, and only the human open paths call it', () => {+ const calls = src.match(/gateProjectOpen\(\)/g) ?? []+ const guarded = src.match(/\? gateProjectOpen\(\) : true/g) ?? []+ expect(guarded.length).toBe(calls.length)+ const inPaths = [+ between('const addProject = useCallback(', '}, [commitActiveToStore, writeDisk])'),+ between('const onRepoCloned = useCallback(', CALLBACK_END),+ between('const createSshProject = useCallback(', CALLBACK_END),+ between('const openOrAdoptFolder = useCallback(', CALLBACK_END),+ between('const reopenProject = useCallback(', CALLBACK_END)+ ].reduce((n, body) => n + (body.match(/gateProjectOpen\(\)/g) ?? []).length, 0)+ expect(inPaths).toBe(calls.length)+ // The share-to-team undo and relay/team tabs never meet the gate.+ expect(between('const reopenProjectUnchecked = useCallback(', CALLBACK_END)).not.toContain('gateProjectOpen')+ })+})diff --git a/src/renderer/lib/projectOpens.test.ts b/src/renderer/lib/projectOpens.test.tsnew file mode 100644index 000000000..0e2405238--- /dev/null+++ b/src/renderer/lib/projectOpens.test.ts@@ -0,0 +1,195 @@+import { describe, expect, it } from 'vitest'+import type { Project } from '@shared/types'+import type { SshServer } from '@shared/ssh'+import { countOpenProjects } from '@shared/project-limit'+import { opensProject } from './projectOpens'+import { useProjects } from '../state/projects'++/**+ * `opensProject` decides whether the project-limit gate is asked at all (spec §3: "Activating a+ * project that is already open is not an open"). Each case is checked against the store action the+ * call site runs right after it, so the prediction cannot drift from what the store does.+ */++const server = (over: Partial<SshServer> = {}): SshServer => ({+ id: 'srv-1',+ label: 'box',+ host: 'box.example',+ user: 'me',+ ...over+})++function project(id: string, over: Partial<Project> = {}): Project {+ return { id, name: id, color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [], ...over }+}++describe('opensProject — new', () => {+ it('always opens a project', () => {+ expect(opensProject([], { kind: 'new' })).toBe(true)+ expect(opensProject([project('a', { cwd: '/a' })], { kind: 'new' })).toBe(true)+ })+})++describe('opensProject — folder (openFolderProject / adopt)', () => {+ it('opens when no project has that cwd', () => {+ expect(opensProject([project('a', { cwd: '/x' })], { kind: 'folder', folder: '/a/b' })).toBe(true)+ })++ it('does not open when an OPEN project already has that cwd (it is only activated)', () => {+ expect(opensProject([project('a', { cwd: '/a/b' })], { kind: 'folder', folder: '/a/b' })).toBe(false)+ })++ it('opens when the project with that cwd is closed (it is reopened)', () => {+ expect(opensProject([project('a', { cwd: '/a/b', closed: true })], { kind: 'folder', folder: '/a/b' })).toBe(true)+ })++ it('opens when only a relay tab carries that cwd (the store never routes a local folder to it)', () => {+ expect(opensProject([project('r', { cwd: '/a/b', remote: true })], { kind: 'folder', folder: '/a/b' })).toBe(true)+ })++ it('matches the cwd exactly, like openFolderProject', () => {+ expect(opensProject([project('a', { cwd: '/a/b' })], { kind: 'folder', folder: '/a/b/' })).toBe(true)+ })+})++describe('opensProject — ssh (openSshProject)', () => {+ const ssh = { server: server(), remoteCwd: '/srv/app' }++ it('opens when no project has that endpoint and remote folder', () => {+ expect(opensProject([project('a', { cwd: '/srv/app' })], { kind: 'ssh', ssh })).toBe(true)+ expect(+ opensProject([project('a', { ssh: { server: server(), remoteCwd: '/srv/other' } })], { kind: 'ssh', ssh })+ ).toBe(true)+ })++ it('does not open when an open project already serves that folder — even under another server entry', () => {+ const reAdded = { server: server({ id: 'srv-2', label: 'renamed' }), remoteCwd: '/srv/app' }+ expect(opensProject([project('a', { ssh: reAdded })], { kind: 'ssh', ssh })).toBe(false)+ })++ it('treats a missing port as 22, like sameSshEndpoint', () => {+ const explicit = { server: server({ port: 22 }), remoteCwd: '/srv/app' }+ expect(opensProject([project('a', { ssh: explicit })], { kind: 'ssh', ssh })).toBe(false)+ const other = { server: server({ port: 2222 }), remoteCwd: '/srv/app' }+ expect(opensProject([project('a', { ssh: other })], { kind: 'ssh', ssh })).toBe(true)+ })++ it('opens when that SSH project is closed (it is reopened)', () => {+ expect(opensProject([project('a', { ssh, closed: true })], { kind: 'ssh', ssh })).toBe(true)+ })+})++describe('opensProject — reopen', () => {+ it('opens a closed project', () => {+ expect(opensProject([project('a', { closed: true })], { kind: 'reopen', id: 'a' })).toBe(true)+ })++ it('does not open an already-open project (activation only)', () => {+ expect(opensProject([project('a')], { kind: 'reopen', id: 'a' })).toBe(false)+ })++ it('does not open a relay tab (reopenProjectUnchecked refuses it, and relay tabs never count)', () => {+ expect(opensProject([project('r', { closed: true, remote: true })], { kind: 'reopen', id: 'r' })).toBe(false)+ })++ it('does not open a project that does not exist', () => {+ expect(opensProject([project('a', { closed: true })], { kind: 'reopen', id: 'gone' })).toBe(false)+ })+})++describe('opensProject — register (the agent verb’s registerProject)', () => {+ it('opens when no project has that cwd', () => {+ expect(opensProject([], { kind: 'register', cwd: '/a/b' })).toBe(true)+ })++ it('normalizes the trailing slash exactly as registerProject does', () => {+ expect(opensProject([project('a', { cwd: '/a/b' })], { kind: 'register', cwd: '/a/b/' })).toBe(false)+ expect(opensProject([project('a', { cwd: '/a/b' })], { kind: 'register', cwd: '/a/b//' })).toBe(false)+ })++ it('keeps root as "/" — it does not match a cwd-less project', () => {+ expect(opensProject([project('a')], { kind: 'register', cwd: '/' })).toBe(true)+ expect(opensProject([project('a', { cwd: '/' })], { kind: 'register', cwd: '/' })).toBe(false)+ })++ it('opens when the project with that cwd is closed (registerProject un-closes it)', () => {+ expect(opensProject([project('a', { cwd: '/a/b', closed: true })], { kind: 'register', cwd: '/a/b/' })).toBe(true)+ })+})++describe('opensProject agrees with what the store action then does to the open count', () => {+ type Case = { name: string; projects: Project[]; act: () => void; predict: Parameters<typeof opensProject>[1] }+ const ssh = { server: server(), remoteCwd: '/srv/app' }+ const cases: Case[] = [+ {+ name: 'openFolderProject on an open folder',+ projects: [project('a', { cwd: '/a/b' })],+ act: () => useProjects.getState().openFolderProject('/a/b'),+ predict: { kind: 'folder', folder: '/a/b' }+ },+ {+ name: 'openFolderProject on a closed folder',+ projects: [project('a', { cwd: '/a/b', closed: true }), project('o')],+ act: () => useProjects.getState().openFolderProject('/a/b'),+ predict: { kind: 'folder', folder: '/a/b' }+ },+ {+ name: 'openFolderProject beside a relay tab with the same cwd',+ projects: [project('r', { cwd: '/a/b', remote: true })],+ act: () => useProjects.getState().openFolderProject('/a/b'),+ predict: { kind: 'folder', folder: '/a/b' }+ },+ {+ name: 'openSshProject on an open endpoint',+ projects: [project('a', { ssh })],+ act: () => useProjects.getState().openSshProject('box', ssh),+ predict: { kind: 'ssh', ssh }+ },+ {+ name: 'openSshProject on a closed endpoint',+ projects: [project('a', { ssh, closed: true })],+ act: () => useProjects.getState().openSshProject('box', ssh),+ predict: { kind: 'ssh', ssh }+ },+ {+ name: 'openSshProject on a new endpoint',+ projects: [],+ act: () => useProjects.getState().openSshProject('box', ssh),+ predict: { kind: 'ssh', ssh }+ },+ {+ name: 'reopenProject on a closed project',+ projects: [project('a', { closed: true })],+ act: () => useProjects.getState().reopenProject('a'),+ predict: { kind: 'reopen', id: 'a' }+ },+ {+ name: 'registerProject with a trailing slash on an open folder',+ projects: [project('a', { cwd: '/a/b' })],+ act: () => useProjects.getState().registerProject({ resolvedCwd: '/a/b/' }),+ predict: { kind: 'register', cwd: '/a/b/' }+ },+ {+ name: 'registerProject on a closed folder',+ projects: [project('a', { cwd: '/a/b', closed: true })],+ act: () => useProjects.getState().registerProject({ resolvedCwd: '/a/b' }),+ predict: { kind: 'register', cwd: '/a/b' }+ },+ {+ name: 'registerProject on a new folder',+ projects: [project('a', { cwd: '/x' })],+ act: () => useProjects.getState().registerProject({ resolvedCwd: '/a/b/' }),+ predict: { kind: 'register', cwd: '/a/b/' }+ }+ ]+ for (const c of cases) {+ it(c.name, () => {+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: c.projects })+ const before = countOpenProjects(useProjects.getState().projects)+ const predicted = opensProject(useProjects.getState().projects, c.predict)+ c.act()+ const after = countOpenProjects(useProjects.getState().projects)+ expect(predicted).toBe(after > before)+ })+ }+})diff --git a/src/renderer/lib/projectOpens.ts b/src/renderer/lib/projectOpens.tsnew file mode 100644index 000000000..4d6bd7427--- /dev/null+++ b/src/renderer/lib/projectOpens.ts@@ -0,0 +1,56 @@+import type { Project } from '@shared/types'+import { registeredCwd, sameSshEndpoint } from '../state/projects'++/**+ * One way a project can be asked to become open, named by the store action that will carry it out:+ * - `new` — `addProject`, or `adoptProject` of a probed folder (both always append an open project);+ * - `folder` — `openFolderProject(folder)`;+ * - `ssh` — `openSshProject(label, ssh)`;+ * - `reopen` — `reopenProject(id)` (through Canvas's `reopenProjectUnchecked`);+ * - `register` — `registerProject({ resolvedCwd: cwd })`, the agent `open-project` verb.+ */+export type OpenAction =+ | { kind: 'new' }+ | { kind: 'folder'; folder: string }+ | { kind: 'ssh'; ssh: NonNullable<Project['ssh']> }+ | { kind: 'reopen'; id: string }+ | { kind: 'register'; cwd: string }++/** Un-closing `p` makes it open: it is closed, and not a relay tab (those never count, spec §3). */+const reopens = (p: Project): boolean => !!p.closed && !p.remote++/**+ * Whether `a` makes a project OPEN that was not (spec §3,+ * docs/superpowers/specs/2026-10-29-free-tier-project-limit-design.md) — that is, whether the+ * project-limit gate must be asked before it. Activating a project that is already open is not an+ * open, so it never meets the gate.+ *+ * Each branch finds the project exactly as its store action will (the same matcher, in the same+ * order), so the answer is a prediction of what that action does to the open count, not a second+ * opinion about which project a folder belongs to. Callers read `projects` at the moment they ask,+ * immediately before the gate and the mutation (see the placement rule in Canvas's open paths).+ */+export function opensProject(projects: readonly Project[], a: OpenAction): boolean {+ switch (a.kind) {+ case 'new':+ return true+ case 'folder': {+ // openFolderProject's match: never a relay tab, which carries the HOST's cwd.+ const existing = projects.find((p) => p.cwd === a.folder && !p.remote)+ return !existing || reopens(existing)+ }+ case 'ssh': {+ const existing = projects.find((p) => !!p.ssh && sameSshEndpoint(p.ssh, a.ssh))+ return !existing || reopens(existing)+ }+ case 'reopen': {+ const existing = projects.find((p) => p.id === a.id)+ return !!existing && reopens(existing)+ }+ case 'register': {+ const cwd = registeredCwd(a.cwd)+ const existing = projects.find((p) => p.cwd === cwd)+ return !existing || reopens(existing)+ }+ }+}diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 9b499ed3d..eac3e0869 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -492,6 +492,13 @@ export function sameSshEndpoint(a: NonNullable<Project['ssh']>, b: NonNullable<P)}+/** The cwd `registerProject` dedupes by: trailing slashes stripped, so `/a/b/` and `/a/b` cannot+ * mint two tabs for one directory. Root stays '/': stripping it to '' would match every cwd-less+ * project. Exported so anything predicting registerProject's match uses this rule, not a copy. */+export function registeredCwd(resolvedCwd: string): string {+ return resolvedCwd.length > 1 ? resolvedCwd.replace(/\/+$/, '') : resolvedCwd+}+export const useProjects = create<ProjectsState>((set, get) => ({projects: [],activeProjectId: '',@@ -1107,9 +1114,8 @@ export const useProjects = create<ProjectsState>((set, get) => ({registerProject({ resolvedCwd, name, color, probed }) {// The same exact-match rule as `openFolderProject` (a folder maps to one project), with the- // trailing slash stripped so `/a/b/` and `/a/b` cannot mint two tabs for one directory.- // Root stays '/': stripping it to '' would match every cwd-less project.- const cwd = resolvedCwd.length > 1 ? resolvedCwd.replace(/\/+$/, '') : resolvedCwd+ // trailing slash stripped (`registeredCwd`).+ const cwd = registeredCwd(resolvedCwd)const existing = get().projects.find((p) => p.cwd === cwd)if (existing) {if (existing.closed) {