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.

fix(project-limit): the boot-time check carries the open-project count

review025111d53b1a
diff --git a/docs/project-limit.md b/docs/project-limit.md
index e6b0acf9a..d230350df 100644
--- a/docs/project-limit.md
+++ b/docs/project-limit.md
@@ -63,10 +63,16 @@ gate. How that is held, layer by layer:
An install the limit was never switched on for has no token, so it never reads it; one that was
switched off by an undo through the check feed keeps its token and still reads it at boot.
- The only request a dormant install makes is `/v1/check`, the call it already made. Core also
- reads it at boot and every 6 h, through the same 5-minute cache and the same build /
- DO_NOT_TRACK guards. Core records the first-launch count once (the late-updater basis above, by
- design); `project-limit.json` is otherwise written only when a server word changes the stored
- state, not on every check.
+ reads it once the boot workspace load has settled (`initProjectLimit`'s `ready`) and every 6 h,
+ through the same 5-minute cache and the same build / DO_NOT_TRACK guards. That boot read is not
+ free: a reply fetched while the open-project count was wanted (telemetry on) but still unknown —
+ the index loading, which is when the banner's and the update card's first reads can run — does not
+ stand in for a later read that can carry the count; that read refetches and replaces the cache.
+ So a boot can cost one extra request, and the count reaches the server as soon as the index is
+ loaded instead of only on the 6 h tick (a session shorter than that would otherwise never report
+ it). Core records the first-launch count once (the late-updater basis above, by design);
+ `project-limit.json` is otherwise written only when a server word changes the stored state, not
+ on every check.
- The agent `open-project` verb asks synchronously too while the limit is off; the headless start
of a node in a closed project unhides exactly as before.
diff --git a/src/core/check.test.ts b/src/core/check.test.ts
index 68369e8e5..3d53c3200 100644
--- a/src/core/check.test.ts
+++ b/src/core/check.test.ts
@@ -256,6 +256,88 @@ describe('fetchCheck — reports the plan', () => {
'version'
])
})
+
+ // At boot the first reads can run before the workspace index has loaded, so they go out with
+ // no count. Served from the cache, that reply would keep the count off the wire for 5 minutes
+ // and — the next read being the 6 h tick — for the whole of a short session.
+ describe('a reply fetched while the count was still unknown', () => {
+ const titles = async (m: Awaited<ReturnType<typeof loadCheck>>) =>
+ (await m.fetchCheck()).messages.map((x) => x.title)
+
+ beforeEach(() => {
+ let n = 0
+ fetchMock.mockImplementation(async () => feed(`read ${++n}`))
+ })
+
+ it('does not stand in for a read that can carry it: that read refetches and replaces the cache', async () => {
+ const m = await loadCheck()
+ let count: number | undefined
+ m.configureCheck({ openProjects: () => count, telemetryEnabled: () => true })
+ expect(await titles(m)).toEqual(['read 1'])
+ expect(param(0, 'openProjects')).toBeNull()
+
+ count = 4
+ expect(await titles(m)).toEqual(['read 2'])
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(param(1, 'openProjects')).toBe('4')
+
+ // The reply that carried the count is an ordinary cache entry again.
+ count = 5
+ expect(await titles(m)).toEqual(['read 2'])
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('is reused while the count is still unknown, or no longer wanted', async () => {
+ const m = await loadCheck()
+ let count: number | undefined
+ let telemetry = true
+ m.configureCheck({ openProjects: () => count, telemetryEnabled: () => telemetry })
+ await m.fetchCheck()
+ expect(await titles(m)).toEqual(['read 1'])
+ telemetry = false
+ count = 4
+ expect(await titles(m)).toEqual(['read 1'])
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('a failed refetch falls back to it and the next read tries again', async () => {
+ const m = await loadCheck()
+ let count: number | undefined
+ m.configureCheck({ openProjects: () => count, telemetryEnabled: () => true })
+ await m.fetchCheck()
+ count = 4
+ fetchMock.mockRejectedValueOnce(new Error('offline'))
+ expect(await titles(m)).toEqual(['read 1'])
+ expect(await titles(m)).toEqual(['read 2'])
+ expect(param(2, 'openProjects')).toBe('4')
+ })
+ })
+
+ it('a reply fetched with the count is reused within 5 minutes, whatever the count becomes', async () => {
+ let n = 0
+ fetchMock.mockImplementation(async () => feed(`read ${++n}`))
+ const m = await loadCheck()
+ let count = 4
+ m.configureCheck({ openProjects: () => count, telemetryEnabled: () => true })
+ await m.fetchCheck()
+ count = 9
+ expect((await m.fetchCheck()).messages.map((x) => x.title)).toEqual(['read 1'])
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('a reply fetched with telemetry off is reused within 5 minutes, even once the count is wanted and known', async () => {
+ let n = 0
+ fetchMock.mockImplementation(async () => feed(`read ${++n}`))
+ const m = await loadCheck()
+ let count: number | undefined
+ let telemetry = false
+ m.configureCheck({ openProjects: () => count, telemetryEnabled: () => telemetry })
+ await m.fetchCheck()
+ telemetry = true
+ count = 4
+ expect((await m.fetchCheck()).messages.map((x) => x.title)).toEqual(['read 1'])
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
})
// The project-limit latch (core/project-limit.ts) clears on `off`, so an answer may come only from
diff --git a/src/core/check.ts b/src/core/check.ts
index 4228f64a8..85d26985b 100644
--- a/src/core/check.ts
+++ b/src/core/check.ts
@@ -31,7 +31,7 @@ const EMPTY: CheckResult = { messages: [], update: { minSupported: null, mandato
// server is targeted explicitly. Deliberately NOT gated on the in-app telemetry toggle: this
// call always runs (content delivery + the anonymous install count), so an install still counts
// even if the user never opts into the detailed telemetry ping. The env kill-switches above are
-// the hard off. The one field that IS gated on the toggle is `openProjects` (`openProjectsParam`).
+// the hard off. The one field that IS gated on the toggle is `openProjects` (`openProjectsQuery`).
function allowed(): boolean {
if (process.env.DO_NOT_TRACK || process.env.NODETERM_TELEMETRY_DISABLED) return false
if (!platform().isPackaged && !process.env.NODETERM_API_BASE) return false
@@ -148,12 +148,27 @@ export function configureCheck(next: CheckDeps): void {
deps = next
}
-// `openProjects=<n>` only when configured, the telemetry toggle is on and `n` is a non-negative
-// integer. Nothing else is added.
-function openProjectsParam(): Record<string, string> {
- if (!deps || deps.telemetryEnabled() !== true) return {}
- const n = deps.openProjects()
- return typeof n === 'number' && Number.isInteger(n) && n >= 0 ? { openProjects: String(n) } : {}
+/** The open-project count for one read: `param` is `openProjects=<n>` only when configured, the
+ * telemetry toggle is on and `n` is a non-negative integer (nothing else is added); `owed` = the
+ * count was wanted (toggle on) but is not known yet — the index still loading at boot. Never
+ * throws: a toggle that cannot be read is off, a count that cannot be read is unknown. */
+function openProjectsQuery(): { param: Record<string, string>; owed: boolean } {
+ let wanted = false
+ try {
+ wanted = !!deps && deps.telemetryEnabled() === true
+ } catch {
+ wanted = false
+ }
+ if (!deps || !wanted) return { param: {}, owed: false }
+ let n: number | undefined
+ try {
+ n = deps.openProjects()
+ } catch {
+ n = undefined
+ }
+ return typeof n === 'number' && Number.isInteger(n) && n >= 0
+ ? { param: { openProjects: String(n) }, owed: false }
+ : { param: {}, owed: true }
}
type Plan = 'pro' | 'free'
@@ -161,14 +176,23 @@ type Plan = 'pro' | 'free'
// The plan the response was fetched for. The backend aims messages at paid or free users by the
// plan WE state (the feed is anonymous — it cannot look a device up), so an answer belongs to the
// plan it was asked with: a purchase or a lapse must not be served the other plan's messages.
-let cache: { at: number; plan: Plan; data: CheckResult } | null = null
+// `countOwed`: the read went out while the count was wanted but unknown (see openProjectsQuery).
+let cache: { at: number; plan: Plan; data: CheckResult; countOwed: boolean } | null = null
export async function fetchCheck(): Promise<CheckResult> {
if (!allowed()) return EMPTY
const now = Date.now()
// Offline token verify, so it is cheap to read per call and already right at boot.
const plan: Plan = isPremium() ? 'pro' : 'free'
- if (cache && cache.plan === plan && now - cache.at < CACHE_MS) return cache.data
+ const count = openProjectsQuery()
+ // A reply fetched while the count was owed does not stand in for a read that can carry it: at boot
+ // the first reads (this module's own, the banner's, the update card's) can all run before the
+ // workspace index is loaded, and served from the cache that count-less reply would keep the count
+ // off the wire until the 6 h tick — for a session shorter than that, for good. So once the count
+ // is known this read refetches, and its reply replaces the cache. A reply that carried the count,
+ // or was fetched with the toggle off, is reused exactly as before.
+ const countNowKnown = cache?.countOwed === true && Object.hasOwn(count.param, 'openProjects')
+ if (cache && cache.plan === plan && now - cache.at < CACHE_MS && !countNowKnown) return cache.data
// A failed read keeps the last good answer, except the messages it fetched for another plan.
// The update policy does not depend on the plan, so it survives.
const fallback = (): CheckResult =>
@@ -181,7 +205,7 @@ export async function fetchCheck(): Promise<CheckResult> {
arch: process.arch,
channel: 'stable',
plan,
- ...openProjectsParam()
+ ...count.param
})
const ctrl = new AbortController()
const t = setTimeout(() => ctrl.abort(), 8000)
@@ -193,7 +217,7 @@ export async function fetchCheck(): Promise<CheckResult> {
// A body that does not parse (a captive portal's HTML page) throws into the fallback below.
const body: unknown = await res.json()
const data = sanitize(body)
- cache = { at: now, plan, data }
+ cache = { at: now, plan, data, countOwed: count.owed }
// The one place an answer is given: a 2xx whose body parsed as JSON. Cached first, so a
// listener that reads the feed again is served from the cache rather than re-fetching.
emitAnswer(sanitizeLimits(body))
diff --git a/src/core/project-limit.test.ts b/src/core/project-limit.test.ts
index 8d7d421b5..5b027c92a 100644
--- a/src/core/project-limit.test.ts
+++ b/src/core/project-limit.test.ts
@@ -133,6 +133,8 @@ async function boot(
machineHash?: () => Promise<MachineHashResult>
/** The allowance key passed to core: the test key unless given; `undefined` = the shipped key. */
publicKeyPem?: string
+ /** Passed through as the `ready` dep (main: the boot workspace load). */
+ ready?: Promise<unknown>
wait?: boolean
} = {}
): Promise<Booted> {
@@ -154,6 +156,7 @@ async function boot(
? {}
: { publicKeyPem: opts.publicKeyPem }
: { publicKeyPem: ALLOWANCE_PUB }),
+ ...(opts.ready ? { ready: opts.ready } : {}),
notify: (s) => notified.push(s)
})
booted = {
@@ -797,4 +800,29 @@ describe('project limit: wiring', () => {
await vi.advanceTimersByTimeAsync(6 * HOUR)
expect(checkCalls()).toBe(2)
})
+
+ // Main hands in the boot workspace load: read any earlier and the open-project count is still
+ // unknown, so that first read (and every cache hit on it) would go out without it.
+ it('the init read waits for `ready`, so it carries the count the workspace load made known', async () => {
+ let release: () => void = () => {}
+ const ready = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ let count: number | undefined
+ const { check } = await boot({ ready, wait: false })
+ check.configureCheck({ openProjects: () => count, telemetryEnabled: () => true })
+ await flush()
+ expect(checkCalls()).toBe(0)
+
+ count = 4
+ release()
+ await booted.idle()
+ expect(checkCalls()).toBe(1)
+ expect(new URL(urls()[0]).searchParams.get('openProjects')).toBe('4')
+ })
+
+ it('a `ready` that rejects still lets the init read run', async () => {
+ await boot({ ready: Promise.reject(new Error('workspace load failed')) })
+ expect(checkCalls()).toBe(1)
+ })
})
diff --git a/src/core/project-limit.ts b/src/core/project-limit.ts
index 35f31cbc9..50562f7d6 100644
--- a/src/core/project-limit.ts
+++ b/src/core/project-limit.ts
@@ -71,7 +71,7 @@ const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'
export const OFF_TRUST_MS = 24 * 60 * 60 * 1000
/** The whole claim request, body included (see license.ts REQUEST_TIMEOUT_MS for why the body). */
const CLAIM_TIMEOUT_MS = 8000
-/** The check feed is re-read on this cadence; it is cached, so it adds no traffic of its own. */
+/** The check feed is re-read on this cadence, through check.ts's 5-minute cache. */
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000
/** The server's own bounds: FREE in 1..1000 (check.ts), a first-launch count in 0..10000 (claim
* route — anything larger is a 400, which would fail every claim). */
@@ -98,6 +98,10 @@ export interface ProjectLimitDeps {
publicKeyPem?: string
/** Deliver the new state to this machine's own windows — never to relay peers. */
notify: (s: ProjectLimitState) => void
+ /** Settles once `openProjects` can answer (main: the boot workspace load). The init check read
+ * waits for it, settled either way: read before it, the count is still unknown and that read
+ * goes out without it. Absent = read at once. */
+ ready?: Promise<unknown>
}
export interface ProjectLimitHandle {
@@ -390,7 +394,10 @@ export function initProjectLimit(d: ProjectLimitDeps): ProjectLimitHandle {
const readCheck = (): void => {
track(fetchCheck().catch(() => {}))
}
- readCheck()
+ // After the workspace load, whichever way it settles: the open-project count rides this read only
+ // once the index is known (check.ts), and the next read of our own is the 6 h tick.
+ if (deps.ready) track(deps.ready.finally(readCheck).catch(() => {}))
+ else readCheck()
setInterval(() => {
// Time alone can change the state (see pushIfChanged); the check below covers the server's word.
pushIfChanged()
diff --git a/src/main/index.ts b/src/main/index.ts
index 08f54de26..0f8618ad8 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -4887,10 +4887,13 @@ app.whenReady().then(async () => {
// The free-tier open-project limit (core/project-limit.ts). Its state goes to THIS machine's
// window only: sendToMain, never platform().broadcast, which also fans out to every relay peer
// (the state carries this host's Pro and DO_NOT_TRACK facts). The Server Edition does not run it.
+ // Its first check read waits for the boot workspace load, the one the delivery queue waits on: read
+ // before the index is loaded, the open-project count is unknown and would not ride that read.
const projectLimit = initProjectLimit({
openProjects: () => workspaceStore.openProjectCount(),
machineHash: readMachineHashResult,
- notify: (s) => sendToMain(IPC.projectLimitChanged, s)
+ notify: (s) => sendToMain(IPC.projectLimitChanged, s),
+ ready: bootWorkspaceLoad
})
settingsStore.onChange(() => projectLimit.refresh())
// DO_NOT_TRACK consent for license and allowance calls (spec §7.4): Settings → Privacy, read on
diff --git a/src/main/project-limit-wiring.test.ts b/src/main/project-limit-wiring.test.ts
index e945a0ee5..e3013da82 100644
--- a/src/main/project-limit-wiring.test.ts
+++ b/src/main/project-limit-wiring.test.ts
@@ -27,10 +27,20 @@ describe('project-limit wiring (source)', () => {
it("main sends the state to its own window, with the workspace count and the OS-aware machine read", () => {
expect(main).toMatch(
- /initProjectLimit\(\{\s*openProjects: \(\) => workspaceStore\.openProjectCount\(\),\s*machineHash: readMachineHashResult,\s*notify: \(s\) => sendToMain\(IPC\.projectLimitChanged, s\)\s*\}\)/
+ /initProjectLimit\(\{\s*openProjects: \(\) => workspaceStore\.openProjectCount\(\),\s*machineHash: readMachineHashResult,\s*notify: \(s\) => sendToMain\(IPC\.projectLimitChanged, s\),\s*ready: bootWorkspaceLoad\s*\}\)/
)
})
+ it('the first check read waits for the boot workspace load, which main starts once and earlier', () => {
+ // Read before the index is loaded, the open-project count is unknown and that read (and every
+ // cache hit on it) goes out without it. `ready` is the SAME promise the delivery queue waits on:
+ // a second load of its own would change when the index is read, not just who waits for it.
+ const load = main.indexOf('const bootWorkspaceLoad = workspaceStore.load({ sideline: false })')
+ expect(load).toBeGreaterThan(-1)
+ expect(main.indexOf('initProjectLimit({')).toBeGreaterThan(load)
+ expect(main.match(/const bootWorkspaceLoad = /g)).toHaveLength(1)
+ })
+
it('a license change and a settings change both re-send it', () => {
expect(main).toMatch(/initLicense\(\(\) => \{\s*watchLinks\?\.onEntitlementChanged\(\)\s*projectLimit\.refresh\(\)\s*\}\)/)
expect(main).toMatch(/settingsStore\.onChange\(\(\) => projectLimit\.refresh\(\)\)/)