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(check): surface the server's project-limit answer

reviewd41ce66f4cab
diff --git a/src/core/check.test.ts b/src/core/check.test.ts
index 5f6837394..8fe50def9 100644
--- a/src/core/check.test.ts
+++ b/src/core/check.test.ts
@@ -1,7 +1,65 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { sanitizeCheckForTest as sanitize } from './check'
+import { sanitizeCheckForTest as sanitize, sanitizeLimitsForTest as sanitizeLimits } from './check'
import { fakePlatform } from './platform-fake'
+// The server states the open-project limit by the PRESENCE of `limits` in a successful reply. The
+// latch that consumes this reads `off` as "clear", so only a missing key is an off: anything present
+// that we cannot read is `unknown`, which changes nothing.
+describe('/v1/check sanitize — limits', () => {
+ it('reads a reply without limits as off', () => {
+ expect(sanitizeLimits({ messages: [], update: { minSupported: null, mandatory: false } })).toEqual({ kind: 'off' })
+ expect(sanitizeLimits({})).toEqual({ kind: 'off' })
+ })
+
+ it('reads a well-formed project limit as on, and nothing else from it', () => {
+ expect(sanitizeLimits({ limits: { projects: { free: 5, epoch: 1 } } })).toEqual({ kind: 'on', free: 5, epoch: 1 })
+ expect(sanitizeLimits({ limits: { projects: { free: 1, epoch: 7, extra: 'x' }, other: 1 } })).toEqual({
+ kind: 'on',
+ free: 1,
+ epoch: 7
+ })
+ expect(sanitizeLimits({ limits: { projects: { free: 1000, epoch: 2 } } })).toEqual({
+ kind: 'on',
+ free: 1000,
+ epoch: 2
+ })
+ })
+
+ it('reads a present but malformed limits value as unknown', () => {
+ const malformed: unknown[] = [
+ null,
+ true,
+ 'on',
+ 5,
+ [],
+ {},
+ { projects: null },
+ { projects: [] },
+ { projects: 'on' },
+ { projects: { epoch: 1 } },
+ { projects: { free: 5 } },
+ { projects: { free: 0, epoch: 1 } },
+ { projects: { free: 1001, epoch: 1 } },
+ { projects: { free: 2.5, epoch: 1 } },
+ { projects: { free: '5', epoch: 1 } },
+ { projects: { free: 5, epoch: 0 } },
+ { projects: { free: 5, epoch: -1 } },
+ { projects: { free: 5, epoch: 1.5 } },
+ { projects: { free: 5, epoch: '1' } },
+ { projects: { free: 5, epoch: 2 ** 53 } }
+ ]
+ for (const limits of malformed) {
+ expect(sanitizeLimits({ limits }), JSON.stringify(limits)).toEqual({ kind: 'unknown' })
+ }
+ })
+
+ it('reads a body that is not a JSON object as unknown, never off', () => {
+ for (const body of [null, undefined, 'ok', 3, true, [], [{ limits: null }]]) {
+ expect(sanitizeLimits(body), JSON.stringify(body)).toEqual({ kind: 'unknown' })
+ }
+ })
+})
+
describe('/v1/check sanitize — update notes', () => {
it('carries notes only together with the version they describe', () => {
expect(sanitize({ update: { mandatory: false, notes: '- a', latestVersion: '1.2.0' } }).update).toEqual({
@@ -168,4 +226,143 @@ describe('fetchCheck — reports the plan', () => {
])
})
})
+
+ // The project-limit latch (core/project-limit.ts) clears on `off`, so an answer may come only from
+ // a read the server actually made: a blocked network, a rate limit or a captive portal must never
+ // be able to say "off". The failure bodies below are JSON WITHOUT `limits` on purpose — read past
+ // their status, each would be exactly that misfired off.
+ describe('onCheckAnswer', () => {
+ const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
+ const limitsFeed = (free: number, epoch: number) =>
+ json({ messages: [], update: { minSupported: null, mandatory: false }, limits: { projects: { free, epoch } } })
+ const T0 = Date.UTC(2026, 9, 30, 12)
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(T0)
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('answers only on a 2xx JSON read', async () => {
+ const failures: Array<[string, () => Promise<Response>]> = [
+ ['500', async () => json({ error: 'internal' }, 500)],
+ ['429', async () => json({ error: 'rate_limited' }, 429)],
+ ['thrown fetch', async () => Promise.reject(new TypeError('fetch failed'))],
+ [
+ '200 text/html',
+ async () =>
+ new Response('<html><body>Sign in to the network</body></html>', {
+ status: 200,
+ headers: { 'content-type': 'text/html' }
+ })
+ ]
+ ]
+ for (const [label, respond] of failures) {
+ fetchMock.mockReset().mockImplementation(respond)
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ expect(await m.fetchCheck(), label).toEqual({ messages: [], update: { minSupported: null, mandatory: false } })
+ expect(fetchMock, label).toHaveBeenCalledTimes(1)
+ expect(listener, label).not.toHaveBeenCalled()
+ }
+ })
+
+ it('does not answer from the failure fallback of an earlier good read', async () => {
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ fetchMock.mockResolvedValueOnce(limitsFeed(5, 1)).mockResolvedValueOnce(json({ error: 'internal' }, 500))
+ await m.fetchCheck()
+ expect(listener).toHaveBeenCalledTimes(1)
+
+ vi.setSystemTime(T0 + 6 * 60 * 1000)
+ await m.fetchCheck()
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(listener).toHaveBeenCalledTimes(1)
+ })
+
+ it('a 2xx without limits answers off once', async () => {
+ fetchMock.mockResolvedValue(feed('x'))
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ await m.fetchCheck()
+ expect(listener.mock.calls).toEqual([[{ kind: 'off' }]])
+ })
+
+ it('a 2xx with limits answers on, and fetchCheck still returns only messages and update', async () => {
+ fetchMock.mockResolvedValue(limitsFeed(5, 3))
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ expect(await m.fetchCheck()).toEqual({ messages: [], update: { minSupported: null, mandatory: false } })
+ expect(listener.mock.calls).toEqual([[{ kind: 'on', free: 5, epoch: 3 }]])
+ })
+
+ it('a 2xx with a malformed limits value answers unknown', async () => {
+ fetchMock.mockResolvedValue(json({ messages: [], update: {}, limits: { projects: { free: 0, epoch: 1 } } }))
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ await m.fetchCheck()
+ expect(listener.mock.calls).toEqual([[{ kind: 'unknown' }]])
+ })
+
+ it('a cache hit within 5 min does not answer again; the next network read does', async () => {
+ fetchMock.mockImplementation(async () => limitsFeed(5, 1))
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ await m.fetchCheck()
+ vi.setSystemTime(T0 + 4 * 60 * 1000)
+ await m.fetchCheck()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(listener).toHaveBeenCalledTimes(1)
+
+ vi.setSystemTime(T0 + 6 * 60 * 1000)
+ await m.fetchCheck()
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(listener).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not answer when the feed is not allowed to run', async () => {
+ vi.stubEnv('DO_NOT_TRACK', '1')
+ const m = await loadCheck()
+ const listener = vi.fn()
+ m.onCheckAnswer(listener)
+ await m.fetchCheck()
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(listener).not.toHaveBeenCalled()
+ })
+
+ it('a listener that throws does not break fetchCheck or the other listeners', async () => {
+ fetchMock.mockResolvedValue(feed('x'))
+ const m = await loadCheck()
+ const after = vi.fn()
+ m.onCheckAnswer(() => {
+ throw new Error('listener bug')
+ })
+ m.onCheckAnswer(after)
+ expect((await m.fetchCheck()).messages.map((x) => x.title)).toEqual(['x'])
+ expect(after.mock.calls).toEqual([[{ kind: 'off' }]])
+ // The read was good: it is cached like any other, not retried as a failure.
+ await m.fetchCheck()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('stops answering a listener once unsubscribed', async () => {
+ fetchMock.mockImplementation(async () => feed('x'))
+ const m = await loadCheck()
+ const listener = vi.fn()
+ const off = m.onCheckAnswer(listener)
+ await m.fetchCheck()
+ off()
+ vi.setSystemTime(T0 + 6 * 60 * 1000)
+ await m.fetchCheck()
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(listener).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/src/core/check.ts b/src/core/check.ts
index 5e27a2123..b82b91b6c 100644
--- a/src/core/check.ts
+++ b/src/core/check.ts
@@ -8,6 +8,8 @@
// While the Settings → Privacy telemetry toggle is on it also carries the open-project count
// (`openProjects`, a bare number — never names, paths or hosts); the backend keeps the per-install
// maximum, the data the project-limit allowance is computed from. See `configureCheck`.
+// In the other direction, the reply says whether the open-project limit is on (`limits`, present
+// only while it is); that answer reaches core through `onCheckAnswer`, not through CheckResult.
// Nothing personal is sent and the client IP is never stored server-side; a hard opt-out is still
// DO_NOT_TRACK / NODETERM_TELEMETRY_DISABLED.
import { platform } from './platform'
@@ -69,6 +71,62 @@ const NOTES_MAX = 16 * 1024
/** Test seam: the sanitizer is the whole contract with the feed's shape. */
export const sanitizeCheckForTest = sanitize
+/** What one successful read of the feed said about the open-project limit. The server adds
+ * `limits: { projects: { free, epoch } }` exactly while the limit is on and leaves the key absent
+ * otherwise, so `off` is the ABSENCE of the key. `unknown` = something was there that we could not
+ * read; it must change nothing (a malformed answer is not an "off"). */
+export type LimitsAnswer = { kind: 'on'; free: number; epoch: number } | { kind: 'off' } | { kind: 'unknown' }
+
+const FREE_MIN = 1
+const FREE_MAX = 1000
+
+const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+
+// Kept apart from `sanitize`, whose CheckResult its existing callers (banner, update card) depend on
+// exactly. A body that is not a JSON object is not a check reply at all, so it is `unknown`, never
+// `off`. A fresh object every call, so no answer aliases a module constant a listener could mutate.
+function sanitizeLimits(data: unknown): LimitsAnswer {
+ if (!isRecord(data)) return { kind: 'unknown' }
+ if (!Object.hasOwn(data, 'limits')) return { kind: 'off' }
+ const projects = isRecord(data.limits) ? data.limits.projects : undefined
+ if (!isRecord(projects)) return { kind: 'unknown' }
+ const { free, epoch } = projects
+ if (typeof free !== 'number' || !Number.isInteger(free) || free < FREE_MIN || free > FREE_MAX) {
+ return { kind: 'unknown' }
+ }
+ // Safe integers only: the epoch is compared for equality against a stored token's.
+ if (typeof epoch !== 'number' || !Number.isSafeInteger(epoch) || epoch < 1) return { kind: 'unknown' }
+ return { kind: 'on', free, epoch }
+}
+
+/** Test seam: the limits half of the feed's shape. */
+export const sanitizeLimitsForTest = sanitizeLimits
+
+type AnswerListener = (a: LimitsAnswer) => void
+const answerListeners = new Set<AnswerListener>()
+
+/** Subscribe to the server's limit answer. Fired only after a 2xx response whose body parsed as
+ * JSON, once per network read — never for a cache hit, a failed read or its fallback, because the
+ * project-limit latch reads `off` as "clear" and a blocked network must not be able to say it.
+ * Returns the unsubscribe. */
+export function onCheckAnswer(listener: AnswerListener): () => void {
+ answerListeners.add(listener)
+ return () => {
+ answerListeners.delete(listener)
+ }
+}
+
+function emitAnswer(answer: LimitsAnswer): void {
+ // A copy, so a listener that unsubscribes (or subscribes) mid-emit does not skew this round.
+ for (const listener of [...answerListeners]) {
+ try {
+ listener(answer)
+ } catch {
+ // A listener's bug is its own: fetchCheck's callers still get the answer they asked for.
+ }
+ }
+}
+
export interface CheckDeps {
/** Open projects in the workspace index (`WorkspaceStore.openProjectCount`); undefined = unknown
* (index not loaded yet, or never saved in v3 form), and an unknown count is never sent. */
@@ -127,8 +185,13 @@ export async function fetchCheck(): Promise<CheckResult> {
cache: 'no-cache'
}).finally(() => clearTimeout(t))
if (!res.ok) return fallback()
- const data = sanitize(await res.json())
+ // 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 }
+ // 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))
return data
} catch {
return fallback()