The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix: stop hammering the storefront profile API — cache token validation, push the machine list, prove tokens at /me/identity (#178)
Dev at Autonomous6821e595522b
diff --git a/backend/.env.example b/backend/.env.exampleindex e91002ab0..c6007d861 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -53,12 +53,18 @@ APP_PROXY_IDLE_TIMEOUT_MS=300000# admins opt individual new users into staging via User.autonomousEnv.SSO_ISSUER=https://auth.autonomous.aiSSO_PROFILE_URL=https://apiv2.autonomous.ai/api/v1/me/profile+# Asked before SSO_PROFILE_URL (which stays the fallback on a 404). '' turns it off. Move this whenever you move SSO_PROFILE_URL.+SSO_IDENTITY_URL=https://apiv2.autonomous.ai/api/v1/me/identitySTAGING_SSO_ISSUER=https://auth.staging.autonomousdev.xyzSTAGING_SSO_PROFILE_URL=https://apiv2.staging.autonomousdev.xyz/api/v1/me/profile+STAGING_SSO_IDENTITY_URL=https://apiv2.staging.autonomousdev.xyz/api/v1/me/identity# Optional when staging uses a different OAuth client; otherwise SSO_CLIENT_* is reused.# STAGING_SSO_CLIENT_ID=# STAGING_SSO_CLIENT_SECRET=SSO_PROFILE_TIMEOUT_MS=5000+# How long a token the profile API accepted is trusted before asking again (0 = ask every request).+# Also the longest a token revoked at the SSO keeps working here.+SSO_PROFILE_CACHE_TTL_MS=60000# New managed harness checkout (enabled by default). Before production boot, both backend + manager# must share the same random 32-byte base64 encryption key (`openssl rand -base64 32`). Set falsediff --git a/backend/README.md b/backend/README.mdindex d65cc648b..8c0aa8b98 100644--- a/backend/README.md+++ b/backend/README.md@@ -46,7 +46,8 @@ npm run dev # tsx watch, :8085 by defaultCopy `.env.example` → `.env` and set at least `MANAGER_API_KEY` (to match the manager) and a`DATABASE_URL` pointing at the **same** MongoDB the manager uses. Production SSO/profile URLs are-the defaults; override `SSO_ISSUER` and `SSO_PROFILE_URL` with the staging hosts for local testing.+the defaults; override `SSO_ISSUER`, `SSO_PROFILE_URL` and `SSO_IDENTITY_URL` with the staging hosts for local testing+(the identity URL is asked first — leave it on production and staging tokens are refused there).| dev | build | other ||-----|-------|-------|diff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex c330bcdc4..750b0aecb 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -93,13 +93,22 @@ const envSchema = z.object({SSO_CLIENT_SECRET: z.string().optional(), // public client (PKCE, auth method 'none') → leave unsetSSO_SCOPE: z.string().default('openid profile email roles'),SSO_PROFILE_URL: z.string().default('https://apiv2.autonomous.ai/api/v1/me/profile'),+ // The cheap way to prove a token: the same answer shape as SSO_PROFILE_URL with no customer or cart+ // read behind it. Asked first; SSO_PROFILE_URL is the fallback on a 404 (a BFF that predates the+ // route). '' turns it off — set that, or your own URL, WHENEVER you move SSO_PROFILE_URL, or tokens+ // for your host get proved against this one.+ SSO_IDENTITY_URL: z.string().default('https://apiv2.autonomous.ai/api/v1/me/identity'),// Per-user staging override. Production remains the default; these are consulted only after the// login transaction/user record explicitly selects `stag`.STAGING_SSO_ISSUER: z.string().default('https://auth.staging.autonomousdev.xyz'),STAGING_SSO_CLIENT_ID: z.string().optional(),STAGING_SSO_CLIENT_SECRET: z.string().optional(),STAGING_SSO_PROFILE_URL: z.string().default('https://apiv2.staging.autonomousdev.xyz/api/v1/me/profile'),+ STAGING_SSO_IDENTITY_URL: z.string().default('https://apiv2.staging.autonomousdev.xyz/api/v1/me/identity'),SSO_PROFILE_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),+ // How long a token the profile API just accepted is trusted without asking again (0 = ask every+ // time). This is also the longest a token revoked at the SSO keeps working here.+ SSO_PROFILE_CACHE_TTL_MS: z.coerce.number().int().min(0).default(60_000),// Forces the SSO account picker so users can switch accounts (not silently auto-login the last one).// Set to '' to disable, or 'login' to force re-entering credentials.SSO_PROMPT: z.string().default('select_account'),diff --git a/backend/src/lib/adapterAccountPushes.test.ts b/backend/src/lib/adapterAccountPushes.test.tsnew file mode 100644index 000000000..52e861ddd--- /dev/null+++ b/backend/src/lib/adapterAccountPushes.test.ts@@ -0,0 +1,50 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const m = vi.hoisted(() => ({+ desk: vi.fn(), machines: vi.fn(),+ deskUnsub: vi.fn(), machinesUnsub: vi.fn(),+}))+vi.mock('./bus.js', () => ({ subscribeDeskChanged: m.desk, subscribeDeviceMachineListChanged: m.machines }))++import { relayAccountPushes } from './adapterAccountPushes.js'++describe('account pushes on a daemon socket', () => {+ beforeEach(() => {+ vi.resetAllMocks()+ m.desk.mockResolvedValue(m.deskUnsub)+ m.machines.mockResolvedValue(m.machinesUnsub)+ })++ it('listens on the channels of the account that owns the socket', async () => {+ await relayAccountPushes('user-1', vi.fn())+ expect(m.desk).toHaveBeenCalledWith('user-1', expect.any(Function))+ expect(m.machines).toHaveBeenCalledWith('user-1', expect.any(Function))+ })++ it('hands the daemon a desk change as a connection-less down frame carrying the revision', async () => {+ const send = vi.fn()+ await relayAccountPushes('user-1', send)+ m.desk.mock.calls[0][1]({ revision: 7 })+ expect(send).toHaveBeenCalledWith({ t: 'down', connId: '', frame: { type: 'desk_changed', payload: { revision: 7 } } })+ })++ it('hands the daemon a machine-list change, so the app re-reads instead of polling', async () => {+ const send = vi.fn()+ await relayAccountPushes('user-1', send)+ m.machines.mock.calls[0][1]({ reason: 'renamed' })+ expect(send).toHaveBeenCalledWith({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: 'renamed' } } })+ })++ it('stops listening on both channels when the socket goes away', async () => {+ const stop = await relayAccountPushes('user-1', vi.fn())+ stop()+ expect(m.deskUnsub).toHaveBeenCalledOnce()+ expect(m.machinesUnsub).toHaveBeenCalledOnce()+ })++ it('does not leave the desk subscription behind when the second subscribe fails', async () => {+ m.machines.mockRejectedValue(new Error('redis unreachable'))+ await expect(relayAccountPushes('user-1', vi.fn())).rejects.toThrow('redis unreachable')+ expect(m.deskUnsub).toHaveBeenCalledOnce()+ })+})diff --git a/backend/src/lib/adapterAccountPushes.ts b/backend/src/lib/adapterAccountPushes.tsnew file mode 100644index 000000000..69e45d957--- /dev/null+++ b/backend/src/lib/adapterAccountPushes.ts@@ -0,0 +1,32 @@+import { subscribeDeskChanged, subscribeDeviceMachineListChanged } from './bus.js'++/**+ * The pushes a daemon socket carries for its ACCOUNT rather than for its machine: something the+ * signed-in user can see changed on some worker, so this computer's app should re-read it.+ *+ * Each is a connection-less down frame with only enough payload to decide whether to fetch — the+ * daemon (backendSocket.ts) relays it to the window, which re-reads through the daemon's proxy. A burst+ * of changes therefore collapses into reads, and a missed push costs a stale view until the next one.+ *+ * - `desk_changed` — the account's tabs.+ * - `machines_changed` — the account's machine list: a machine created / renamed / deleted, or a+ * shared harness invited / taken back (routes/harnessShares.ts pokes the recipient). This is what+ * lets the app discover invitations without polling `/api/machines` + `/api/harness-shares`.+ *+ * Resolves to the unsubscribe for both.+ */+export async function relayAccountPushes(userId: string, send: (frame: unknown) => unknown): Promise<() => void> {+ const deskUnsub = await subscribeDeskChanged(userId, (msg) => {+ send({ t: 'down', connId: '', frame: { type: 'desk_changed', payload: { revision: msg.revision } } })+ })+ let machinesUnsub: () => void+ try {+ machinesUnsub = await subscribeDeviceMachineListChanged(userId, (msg) => {+ send({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: msg.reason } } })+ })+ } catch (err) {+ deskUnsub()+ throw err+ }+ return () => { deskUnsub(); machinesUnsub() }+}diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex b6822423c..68d1017ee 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -20,7 +20,7 @@ import { prisma } from './prisma.js'import {publishUp, claimMachineOwner, releaseMachineOwner, publishDeviceE2eePair,publishTerminalUp, subscribeTerminalDown,- setMachineAppState, clearMachineAppState, subscribeDeskChanged,+ setMachineAppState, clearMachineAppState,} from './bus.js'import { trackSocketLiveness } from './hub.js'import { guardedSend, guardedSendJson } from './wsSend.js'@@ -34,6 +34,7 @@ import { utcDayKey } from '../types/analytics.js'import { machineBillingAllowsDataPlane } from './billingState.js'import { normalizeComputerId } from './deviceAuth.js'import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'+import { relayAccountPushes } from './adapterAccountPushes.js'import { parseAutonomousEnvironment } from './autonomousEnvironment.js'import { machineService } from '../services/MachineService.js'import { AppError } from '../errors/index.js'@@ -207,12 +208,9 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, cconst send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { machineId, kind: 'adapter' })logger.info('adapter connected', { machineId, computer: label })send({ t: 'connected', machineId })- // The account's tabs changed on some worker: this computer's app re-fetches `/api/desk` through its- // daemon (backendSocket.ts relays `desk_changed` to the window). One frame, no payload beyond the- // revision — the doc itself is fetched, so a burst of edits collapses into one read.- const deskUnsub = await subscribeDeskChanged(userId, (msg) => {- send({ t: 'down', connId: '', frame: { type: 'desk_changed', payload: { revision: msg.revision } } })- })+ // What changed for the ACCOUNT on some worker (its tabs, its machine list): this computer's app+ // re-reads through its daemon rather than polling for it. See adapterAccountPushes.ts.+ const accountPushesUnsub = await relayAccountPushes(userId, send)// Last desktop-app state THIS socket asserted. Socket-scoped on purpose: a new adapter connection// starts with no claim and must re-assert, so a fresh value can never renew a stale one.@@ -487,7 +485,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, cconst cleanup = (): void => {releaseLiveness()terminalDownUnsub()- void deskUnsub()+ accountPushesUnsub()// Only the CURRENT owner tears the role down — a superseded socket must not mark the fresh// connection offline. A superseded socket still releases its own liveness tracking above.if (owners.get(machineId) === ws) {diff --git a/backend/src/lib/autonomousEnvironment.ts b/backend/src/lib/autonomousEnvironment.tsindex ba26dc078..f14a18b8d 100644--- a/backend/src/lib/autonomousEnvironment.ts+++ b/backend/src/lib/autonomousEnvironment.ts@@ -28,6 +28,8 @@ export interface AutonomousEnvironmentConfig {ssoClientId: stringssoClientSecret?: stringssoProfileUrl: string+ /** Asked before `ssoProfileUrl`, which stays the fallback on a 404. Absent = turned off (''). */+ ssoIdentityUrl?: stringbffUrl: stringcheckoutOrigin: stringcampaignApiUrl: string@@ -43,6 +45,7 @@ export function autonomousEnvironmentConfig(name: AutonomousEnvironment): AutonossoClientId: env.STAGING_SSO_CLIENT_ID || env.SSO_CLIENT_ID,ssoClientSecret: env.STAGING_SSO_CLIENT_SECRET || env.SSO_CLIENT_SECRET,ssoProfileUrl: env.STAGING_SSO_PROFILE_URL,+ ssoIdentityUrl: env.STAGING_SSO_IDENTITY_URL || undefined,bffUrl: env.STAGING_AUTONOMOUS_BFF_URL,checkoutOrigin: env.STAGING_AUTONOMOUS_CHECKOUT_ORIGIN,campaignApiUrl: env.STAGING_AUTONOMOUS_CAMPAIGN_API_URL,@@ -55,6 +58,7 @@ export function autonomousEnvironmentConfig(name: AutonomousEnvironment): AutonossoClientId: env.SSO_CLIENT_ID,ssoClientSecret: env.SSO_CLIENT_SECRET,ssoProfileUrl: env.SSO_PROFILE_URL,+ ssoIdentityUrl: env.SSO_IDENTITY_URL || undefined,bffUrl: env.AUTONOMOUS_BFF_URL,checkoutOrigin: env.AUTONOMOUS_CHECKOUT_ORIGIN,campaignApiUrl: env.AUTONOMOUS_CAMPAIGN_API_URL,diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.tsindex c30b2ed02..137921dc3 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -794,3 +794,17 @@ export async function getCommanderJoinGeneration(machineId: string): Promise<numreturn undefined}}++// ── validated SSO tokens (so N processes ask the profile API once, not N times) ────────────────────+//+// Not try/caught like the presence keys above: the cache treats a throw as a miss, and swallowing it+// here would also swallow the difference between "absent" and "Redis is down" for anyone reading logs.+// The key is a digest of the token — see `ssoProfileCache.ts` — and the value holds no credential.++export const redisSsoProfileStore = {+ get: (key: string): Promise<string | null> => pub.get(key),+ async set(key: string, value: string, ttlMs: number): Promise<void> {+ const px = Math.floor(ttlMs)+ if (px > 0) await pub.set(key, value, 'PX', px)+ },+}diff --git a/backend/src/lib/ssoAuth.identityOff.test.ts b/backend/src/lib/ssoAuth.identityOff.test.tsnew file mode 100644index 000000000..2fdc14134--- /dev/null+++ b/backend/src/lib/ssoAuth.identityOff.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest'++// A deployment (or a test rig) that points the profile URL somewhere of its own turns the identity+// endpoint off with SSO_IDENTITY_URL='' — otherwise its tokens would be proved against the default host.+vi.mock('../config/env.js', () => ({+ env: {+ SSO_PROFILE_URL: 'http://127.0.0.1:4010/profile',+ SSO_IDENTITY_URL: '',+ SSO_PROFILE_TIMEOUT_MS: 1000,+ SSO_PROFILE_CACHE_TTL_MS: 0,+ },+}))+vi.mock('../services/UserService.js', () => ({+ userService: {},+ normalizeUserEmail: (email: string) => email,+ isProvisionalUserEmail: () => false,+}))++import { fetchSsoProfile } from './ssoAuth.js'++describe('identity endpoint turned off', () => {+ it('asks only the profile URL', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => new Response(+ JSON.stringify({ status: 1, data: { id: 'external-1', email: '[email protected]' } }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ))++ await expect(fetchSsoProfile('token', fetchMock)).resolves.toEqual({ id: 'external-1', email: '[email protected]' })++ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual(['http://127.0.0.1:4010/profile'])+ })+})diff --git a/backend/src/lib/ssoAuth.test.ts b/backend/src/lib/ssoAuth.test.tsindex 8117c3390..43e4076a2 100644--- a/backend/src/lib/ssoAuth.test.ts+++ b/backend/src/lib/ssoAuth.test.ts@@ -10,7 +10,7 @@ vi.mock('../services/UserService.js', () => ({isProvisionalUserEmail: (email: string) => email.endsWith('@pending.harness.invalid'),}))-import { authenticateAccessToken, fetchSsoProfile, SsoAuthError } from './ssoAuth.js'+import { authenticateAccessToken, clearSsoProfileCache, fetchSsoProfile, SsoAuthError } from './ssoAuth.js'function response(status: number, body: unknown): Response {return new Response(JSON.stringify(body), {@@ -54,10 +54,102 @@ describe('SSO profile authentication', () => {})})+describe('which endpoint proves a token', () => {+ afterEach(() => clearSsoProfileCache())+ const ok = () => response(200, { status: 1, data: { id: 'external-1', email: '[email protected]' } })+ const calledUrls = (mock: ReturnType<typeof vi.fn<typeof fetch>>) => mock.mock.calls.map(([url]) => String(url))++ it('asks the identity endpoint, which costs the storefront no customer or cart read', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => ok())++ await expect(fetchSsoProfile('token', fetchMock)).resolves.toEqual({ id: 'external-1', email: '[email protected]' })++ expect(calledUrls(fetchMock)).toEqual(['https://apiv2.autonomous.ai/api/v1/me/identity'])+ })++ it('falls back to the profile endpoint while the identity endpoint is not deployed', async () => {+ const fetchMock = vi.fn<typeof fetch>()+ .mockResolvedValueOnce(response(404, { message: 'page not found' }))+ .mockResolvedValueOnce(ok())++ await expect(fetchSsoProfile('token', fetchMock)).resolves.toEqual({ id: 'external-1', email: '[email protected]' })++ expect(calledUrls(fetchMock)).toEqual([+ 'https://apiv2.autonomous.ai/api/v1/me/identity',+ 'https://apiv2.autonomous.ai/api/v1/me/profile',+ ])+ })++ it('falls back when the identity endpoint is failing, so the new route is not a new way to be down', async () => {+ const fetchMock = vi.fn<typeof fetch>()+ .mockResolvedValueOnce(response(502, { message: 'bad gateway' }))+ .mockResolvedValueOnce(ok())++ await expect(fetchSsoProfile('token', fetchMock)).resolves.toEqual({ id: 'external-1', email: '[email protected]' })++ expect(calledUrls(fetchMock)).toEqual([+ 'https://apiv2.autonomous.ai/api/v1/me/identity',+ 'https://apiv2.autonomous.ai/api/v1/me/profile',+ ])+ })++ it('falls back when the identity endpoint cannot be reached', async () => {+ const fetchMock = vi.fn<typeof fetch>()+ .mockRejectedValueOnce(new Error('timeout'))+ .mockResolvedValueOnce(ok())++ await expect(fetchSsoProfile('token', fetchMock)).resolves.toEqual({ id: 'external-1', email: '[email protected]' })++ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('remembers that the identity endpoint is not deployed instead of asking it before every validation', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (url) =>+ String(url).endsWith('/me/identity') ? response(404, { message: 'page not found' }) : ok())++ await fetchSsoProfile('token-1', fetchMock)+ await fetchSsoProfile('token-2', fetchMock)++ expect(calledUrls(fetchMock)).toEqual([+ 'https://apiv2.autonomous.ai/api/v1/me/identity',+ 'https://apiv2.autonomous.ai/api/v1/me/profile',+ 'https://apiv2.autonomous.ai/api/v1/me/profile',+ ])+ })++ it('does not let one failing answer stop it asking the identity endpoint next time', async () => {+ const fetchMock = vi.fn<typeof fetch>()+ .mockResolvedValueOnce(response(502, { message: 'bad gateway' }))+ .mockImplementation(async () => ok())++ await fetchSsoProfile('token-1', fetchMock)+ await fetchSsoProfile('token-2', fetchMock)++ expect(calledUrls(fetchMock)[2]).toBe('https://apiv2.autonomous.ai/api/v1/me/identity')+ })++ it('takes the identity endpoint at its word when it rejects the token', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => response(401, { message: 'Invalid or expired JWT' }))++ await expect(fetchSsoProfile('expired', fetchMock)).rejects.toMatchObject({ code: 'INVALID_TOKEN' })++ expect(fetchMock).toHaveBeenCalledOnce()+ })++ it('asks the staging identity endpoint for a staging sign-in', async () => {+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => ok())++ await fetchSsoProfile('token', 'stag', fetchMock)++ expect(calledUrls(fetchMock)).toEqual(['https://apiv2.staging.autonomousdev.xyz/api/v1/me/identity'])+ })+})+describe('authenticated user resolution', () => {afterEach(() => {vi.clearAllMocks()vi.unstubAllGlobals()+ clearSsoProfileCache()})function profileFetch(id: string, email: string): void {@@ -141,4 +233,25 @@ describe('authenticated user resolution', () => {})expect(upsertFromSso).not.toHaveBeenCalled()})++ it('asks the profile service once for a token used on back-to-back requests', async () => {+ profileFetch('prod-sub-1', '[email protected]')+ const existing = { id: 'u1', email: '[email protected]', externalId: 'prod-sub-1', role: 'user', autonomousEnv: 'prod' }+ findByEmail.mockResolvedValue(existing)+ upsertFromSso.mockResolvedValue(existing)++ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.toMatchObject({ sub: 'u1' })+ await expect(authenticateAccessToken('a.e30.c', 'prod')).resolves.toMatchObject({ sub: 'u1' })++ expect(fetch).toHaveBeenCalledOnce()+ })++ it('asks the profile service again for a token it rejected', async () => {+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => response(401, { message: 'Invalid or expired JWT' })))++ await expect(authenticateAccessToken('a.e30.c', 'prod')).rejects.toMatchObject({ code: 'INVALID_TOKEN' })+ await expect(authenticateAccessToken('a.e30.c', 'prod')).rejects.toMatchObject({ code: 'INVALID_TOKEN' })++ expect(fetch).toHaveBeenCalledTimes(2)+ })})diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.tsindex ab80a81fd..830afe267 100644--- a/backend/src/lib/ssoAuth.ts+++ b/backend/src/lib/ssoAuth.ts@@ -9,6 +9,7 @@ import {storedAutonomousEnvironment,type AutonomousEnvironment,} from './autonomousEnvironment.js'+import { createSsoProfileCache, type SharedProfileStore } from './ssoProfileCache.js'/** Internal identity attached to authenticated backend requests and user WebSockets. */export interface AuthUser {@@ -42,6 +43,28 @@ export function bearerToken(header: string | undefined): string | undefined {type FetchLike = typeof fetch+// The cross-process store is attached by the server at startup rather than imported here: the Redis+// module connects on import, and this file is imported by everything that authenticates.+let sharedProfileStore: SharedProfileStore | null = null+const profileCache = createSsoProfileCache({+ ttlMs: env.SSO_PROFILE_CACHE_TTL_MS,+ shared: () => sharedProfileStore,+})++export function useSharedSsoProfileStore(store: SharedProfileStore | null): void {+ sharedProfileStore = store+}++// A BFF that predates the identity route answers it 404 every time. Remember that per account plane+// for a few minutes rather than asking twice before every validation.+const IDENTITY_MISSING_TTL_MS = 5 * 60_000+const identityMissingUntil = new Map<AutonomousEnvironment, number>()++export function clearSsoProfileCache(): void {+ profileCache.clear()+ identityMissingUntil.clear()+}+/** Validate the SSO access token against the Autonomous profile service. */export async function fetchSsoProfile(token: string,@@ -52,21 +75,38 @@ export async function fetchSsoProfile(// always supplies the environment explicitly.const autonomousEnv = typeof autonomousEnvOrFetch === 'function' ? 'prod' : autonomousEnvOrFetchconst fetchImpl = typeof autonomousEnvOrFetch === 'function' ? autonomousEnvOrFetch : (fetchOverride ?? fetch)- let res: Response- try {- res = await fetchImpl(autonomousEnvironmentConfig(autonomousEnv).ssoProfileUrl, {- method: 'GET',- headers: {- Accept: 'application/json',- 'Content-Type': 'application/json',- Location: 'en-US',- Authorization: `Bearer ${token}`,- },- signal: AbortSignal.timeout(env.SSO_PROFILE_TIMEOUT_MS),- })- } catch {- throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')+ const { ssoProfileUrl, ssoIdentityUrl } = autonomousEnvironmentConfig(autonomousEnv)+ const ask = async (url: string): Promise<Response> => {+ try {+ return await fetchImpl(url, {+ method: 'GET',+ headers: {+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ Location: 'en-US',+ Authorization: `Bearer ${token}`,+ },+ signal: AbortSignal.timeout(env.SSO_PROFILE_TIMEOUT_MS),+ })+ } catch {+ throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')+ }+ }++ // The identity endpoint answers from the token alone; the profile endpoint costs the storefront a+ // customer read and a cart read per call. Same envelope, same two fields.+ //+ // Identity is an optimisation, never a dependency: whenever it cannot give an ANSWER — not deployed+ // (404), failing (5xx), unreachable — the profile URL is asked instead, exactly as before it existed.+ // A 401/403 is an answer, and is final.+ const useIdentity = !!ssoIdentityUrl && (identityMissingUntil.get(autonomousEnv) ?? 0) <= Date.now()+ let res: Response | undefined+ if (useIdentity) {+ res = await ask(ssoIdentityUrl!).catch(() => undefined)+ if (res?.status === 404) identityMissingUntil.set(autonomousEnv, Date.now() + IDENTITY_MISSING_TTL_MS)+ if (res && (res.status === 404 || res.status >= 500)) res = undefined}+ res ??= await ask(ssoProfileUrl)if (res.status === 401 || res.status === 403) {throw new SsoAuthError('Invalid or expired SSO access token', 'INVALID_TOKEN')@@ -141,7 +181,7 @@ export async function authenticateAccessToken(autonomousEnv: AutonomousEnvironment = 'prod',{ enforceEnv = true }: { enforceEnv?: boolean } = {},): Promise<AuthUser> {- const profile = await fetchSsoProfile(token, autonomousEnv)+ const profile = await profileCache.resolve(token, autonomousEnv, () => fetchSsoProfile(token, autonomousEnv))const metadata = accessTokenMetadata(token)const email = normalizeUserEmail(profile.email)if (!email) throw new SsoAuthError('SSO profile service returned an invalid profile', 'AUTH_SERVICE_UNAVAILABLE')diff --git a/backend/src/lib/ssoProfileCache.test.ts b/backend/src/lib/ssoProfileCache.test.tsnew file mode 100644index 000000000..47239a930--- /dev/null+++ b/backend/src/lib/ssoProfileCache.test.ts@@ -0,0 +1,232 @@+import { describe, expect, it } from 'vitest'+import { createSsoProfileCache, type SharedProfileStore } from './ssoProfileCache.js'++const profile = { id: 'external-1', email: '[email protected]' }++/** An access token shaped like the real one: only the payload's `exp` (seconds) is ever read. */+function tokenExpiringAt(expMs: number, salt = 'a'): string {+ const payload = Buffer.from(JSON.stringify({ exp: Math.floor(expMs / 1000), salt })).toString('base64url')+ return `header.${payload}.signature`+}++/** A counting loader, so a test can say how many times the profile service was really asked. */+function loader(result: typeof profile | Error = profile) {+ const state = { calls: 0 }+ const load = async () => {+ state.calls+++ if (result instanceof Error) throw result+ return result+ }+ return { state, load }+}++/** What Redis is to the cache: a string store with a TTL, shared by every backend process. */+function memoryStore(now: () => number): SharedProfileStore & { keys: () => string[]; values: () => string[] } {+ const rows = new Map<string, { value: string; expiresAt: number }>()+ return {+ async get(key) {+ const row = rows.get(key)+ return row && row.expiresAt > now() ? row.value : null+ },+ async set(key, value, ttlMs) { rows.set(key, { value, expiresAt: now() + ttlMs }) },+ keys: () => [...rows.keys()],+ values: () => [...rows.values()].map((row) => row.value),+ }+}++describe('SSO profile cache', () => {+ it('asks the profile service once for a token it has just validated', async () => {+ const cache = createSsoProfileCache({ ttlMs: 60_000 })+ const { state, load } = loader()++ await expect(cache.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)+ await expect(cache.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)++ expect(state.calls).toBe(1)+ })++ it('asks again once the entry is older than the TTL', async () => {+ let now = 1_000_000+ const cache = createSsoProfileCache({ ttlMs: 60_000, now: () => now })+ const { state, load } = loader()++ await cache.resolve('opaque-token', 'prod', load)+ now += 60_001+ await cache.resolve('opaque-token', 'prod', load)++ expect(state.calls).toBe(2)+ })++ it('never keeps a token past its own expiry', async () => {+ let now = 1_000_000+ const cache = createSsoProfileCache({ ttlMs: 60_000, now: () => now })+ const token = tokenExpiringAt(now + 10_000)+ const { state, load } = loader()++ await cache.resolve(token, 'prod', load)+ now += 9_000+ await cache.resolve(token, 'prod', load)+ expect(state.calls).toBe(1)++ now += 2_000+ await cache.resolve(token, 'prod', load)+ expect(state.calls).toBe(2)+ })++ it('does not remember a token the profile service rejected', async () => {+ const cache = createSsoProfileCache({ ttlMs: 60_000 })+ const rejected = loader(new Error('Invalid or expired SSO access token'))+ const accepted = loader()++ await expect(cache.resolve('opaque-token', 'prod', rejected.load)).rejects.toThrow('Invalid or expired')+ await expect(cache.resolve('opaque-token', 'prod', accepted.load)).resolves.toEqual(profile)++ expect(accepted.state.calls).toBe(1)+ })++ it('shares one in-flight validation between requests that arrive together', async () => {+ const cache = createSsoProfileCache({ ttlMs: 60_000 })+ let calls = 0+ let release!: () => void+ const gate = new Promise<void>((resolve) => { release = resolve })+ const load = async () => { calls++; await gate; return profile }++ const both = Promise.all([+ cache.resolve('opaque-token', 'prod', load),+ cache.resolve('opaque-token', 'prod', load),+ ])+ release()++ await expect(both).resolves.toEqual([profile, profile])+ expect(calls).toBe(1)+ })++ it('keeps the two account planes apart for the same token', async () => {+ const cache = createSsoProfileCache({ ttlMs: 60_000 })+ const prod = loader()+ const stag = loader({ id: 'stag-1', email: '[email protected]' })++ await cache.resolve('opaque-token', 'prod', prod.load)+ await expect(cache.resolve('opaque-token', 'stag', stag.load)).resolves.toEqual({ id: 'stag-1', email: '[email protected]' })++ expect(stag.state.calls).toBe(1)+ })++ it('reuses a validation another backend process already made', async () => {+ const now = () => 1_000_000+ const shared = memoryStore(now)+ const first = createSsoProfileCache({ ttlMs: 60_000, now, shared: () => shared })+ const second = createSsoProfileCache({ ttlMs: 60_000, now, shared: () => shared })+ const { state, load } = loader()++ await first.resolve('opaque-token', 'prod', load)+ await expect(second.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)++ expect(state.calls).toBe(1)+ })++ it('trusts a borrowed validation no longer than the process that made it', async () => {+ let now = 1_000_000+ const shared = memoryStore(() => now)+ const first = createSsoProfileCache({ ttlMs: 60_000, now: () => now, shared: () => shared })+ const second = createSsoProfileCache({ ttlMs: 60_000, now: () => now, shared: () => shared })+ const { state, load } = loader()++ await first.resolve('opaque-token', 'prod', load)+ now += 59_000+ await second.resolve('opaque-token', 'prod', load)+ expect(state.calls).toBe(1)++ now += 2_000+ await second.resolve('opaque-token', 'prod', load)+ expect(state.calls).toBe(2)+ })++ it('never hands the shared store the token itself', async () => {+ const now = () => 1_000_000+ const shared = memoryStore(now)+ const cache = createSsoProfileCache({ ttlMs: 60_000, now, shared: () => shared })++ await cache.resolve('very-secret-access-token', 'prod', loader().load)++ expect(shared.keys()).toHaveLength(1)+ expect([...shared.keys(), ...shared.values()].join(' ')).not.toContain('very-secret-access-token')+ })++ it('still authenticates when the shared store is down', async () => {+ const broken: SharedProfileStore = {+ get: async () => { throw new Error('redis unreachable') },+ set: async () => { throw new Error('redis unreachable') },+ }+ const cache = createSsoProfileCache({ ttlMs: 60_000, shared: () => broken })+ const { state, load } = loader()++ await expect(cache.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)+ await expect(cache.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)++ expect(state.calls).toBe(1)+ })++ it('does not wait for the shared store to save what it just validated', async () => {+ const stalled: SharedProfileStore = { get: async () => null, set: () => new Promise<void>(() => {}) }+ const cache = createSsoProfileCache({ ttlMs: 60_000, shared: () => stalled })++ await expect(cache.resolve('opaque-token', 'prod', loader().load)).resolves.toEqual(profile)+ })++ it('treats a shared store that does not answer promptly as a miss', async () => {+ const hung: SharedProfileStore = { get: () => new Promise<string | null>(() => {}), set: async () => {} }+ const cache = createSsoProfileCache({ ttlMs: 60_000, shared: () => hung, sharedReadTimeoutMs: 10 })+ const { state, load } = loader()++ await expect(cache.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)+ expect(state.calls).toBe(1)+ })++ it('ignores a shared entry that is not a profile', async () => {+ const now = () => 1_000_000+ const shared = memoryStore(now)+ const writer = createSsoProfileCache({ ttlMs: 60_000, now, shared: () => shared })+ await writer.resolve('opaque-token', 'prod', loader().load)+ await shared.set(shared.keys()[0], '{"id":42}', 60_000)++ const reader = createSsoProfileCache({ ttlMs: 60_000, now, shared: () => shared })+ const { state, load } = loader()+ await expect(reader.resolve('opaque-token', 'prod', load)).resolves.toEqual(profile)++ expect(state.calls).toBe(1)+ })++ it('validates every time when the TTL is zero', async () => {+ const cache = createSsoProfileCache({ ttlMs: 0 })+ const { state, load } = loader()++ await cache.resolve('opaque-token', 'prod', load)+ await cache.resolve('opaque-token', 'prod', load)++ expect(state.calls).toBe(2)+ })++ it('forgets the oldest token when it is full', async () => {+ const cache = createSsoProfileCache({ ttlMs: 60_000, maxEntries: 2 })+ const first = loader()++ await cache.resolve('token-1', 'prod', first.load)+ await cache.resolve('token-2', 'prod', loader().load)+ await cache.resolve('token-3', 'prod', loader().load)+ await cache.resolve('token-1', 'prod', first.load)++ expect(first.state.calls).toBe(2)+ })++ it('forgets everything on clear', async () => {+ const cache = createSsoProfileCache({ ttlMs: 60_000 })+ const { state, load } = loader()++ await cache.resolve('opaque-token', 'prod', load)+ cache.clear()+ await cache.resolve('opaque-token', 'prod', load)++ expect(state.calls).toBe(2)+ })+})diff --git a/backend/src/lib/ssoProfileCache.ts b/backend/src/lib/ssoProfileCache.tsnew file mode 100644index 000000000..7ba3b1683--- /dev/null+++ b/backend/src/lib/ssoProfileCache.ts@@ -0,0 +1,144 @@+import { createHash } from 'node:crypto'++/**+ * A short memory of "the profile service just said this access token is valid, and whose it is".+ *+ * The backend mints no session of its own: every REST request and every socket upgrade proves its+ * token by asking the Autonomous profile API. That API is a storefront endpoint — one call is a+ * customer read plus a cart read — and a single open desktop app asks several times a minute, so an+ * uncached validation turned a few hundred users into the profile API's largest caller by two orders+ * of magnitude.+ *+ * Two levels, because the backend is many processes (a pm2 cluster, or N pods). A per-process map+ * alone would still let one client's requests, spread across workers, each validate for themselves;+ * the shared store is what makes it "once per token per TTL" for the whole deployment. The+ * per-process map in front of it keeps the hot path off the network entirely.+ *+ * What the TTL costs: a token revoked at the SSO keeps working HERE for at most that long. Only a+ * positive answer is remembered — a rejected token is asked about again every time — and an entry+ * never outlives the token's own `exp`.+ */++export interface CachedSsoProfile {+ id: string+ email: string+}++/** The cross-process half: a string store with a per-key TTL. In production, Redis. */+export interface SharedProfileStore {+ get(key: string): Promise<string | null>+ set(key: string, value: string, ttlMs: number): Promise<void>+}++export interface SsoProfileCache {+ /** The profile for this token on this account plane: remembered if it can be, else `load()`. */+ resolve(token: string, autonomousEnv: string, load: () => Promise<CachedSsoProfile>): Promise<CachedSsoProfile>+ /** Forget this process' entries. The shared store expires on its own. */+ clear(): void+}++interface Options {+ /** How long a validation is trusted. 0 turns the cache off. */+ ttlMs: number+ now?: () => number+ /** Read on every miss rather than captured once, so the store can be attached after startup. */+ shared?: () => SharedProfileStore | null+ /** How long a shared read may take before it counts as a miss. The store's own command timeout is+ * seconds; nobody signing in should wait that long for a cache. */+ sharedReadTimeoutMs?: number+ maxEntries?: number+}++interface Entry {+ profile: CachedSsoProfile+ expiresAt: number+}++/** The token's own expiry in ms, if it is a JWT that states one. Unverified: it can only SHORTEN the TTL. */+function tokenExpiresAt(token: string): number | undefined {+ try {+ const part = token.split('.')[1]+ if (!part) return undefined+ const exp = (JSON.parse(Buffer.from(part, 'base64url').toString('utf8')) as { exp?: unknown }).exp+ return typeof exp === 'number' && Number.isFinite(exp) ? exp * 1000 : undefined+ } catch {+ return undefined+ }+}++/** A shared row carries the expiry its writer chose, so a process that borrows it late cannot extend it. */+function parseEntry(raw: string | null): Entry | undefined {+ if (!raw) return undefined+ try {+ const value = JSON.parse(raw) as { id?: unknown; email?: unknown; expiresAt?: unknown }+ if (typeof value.id !== 'string' || !value.id || typeof value.email !== 'string' || !value.email) return undefined+ if (typeof value.expiresAt !== 'number' || !Number.isFinite(value.expiresAt)) return undefined+ return { profile: { id: value.id, email: value.email }, expiresAt: value.expiresAt }+ } catch {+ return undefined+ }+}++/** `work`'s value if it settles within `ms`, else null. A rejection is null too. */+function promptly<T>(work: Promise<T>, ms: number): Promise<T | null> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve(null), ms)+ timer.unref?.()+ work.then((value) => { clearTimeout(timer); resolve(value) }, () => { clearTimeout(timer); resolve(null) })+ })+}++export function createSsoProfileCache({ ttlMs, now = Date.now, shared = () => null, sharedReadTimeoutMs = 250, maxEntries = 50_000 }: Options): SsoProfileCache {+ const entries = new Map<string, Entry>()+ const inFlight = new Map<string, Promise<CachedSsoProfile>>()++ // The key is a digest, never the token: it is written to a store other services can read.+ const keyOf = (token: string, autonomousEnv: string): string =>+ `sso:profile:${createHash('sha256').update(`${autonomousEnv}:${token}`).digest('hex')}`++ const remember = (key: string, profile: CachedSsoProfile, expiresAt: number): void => {+ if (entries.size >= maxEntries && !entries.has(key)) {+ const oldest = entries.keys().next().value+ if (oldest !== undefined) entries.delete(oldest)+ }+ entries.set(key, { profile, expiresAt })+ }++ const fill = async (key: string, expiresAt: number, load: () => Promise<CachedSsoProfile>): Promise<CachedSsoProfile> => {+ const store = shared()+ if (store) {+ // A store that is down — or merely slow — is a cache miss, not an authentication failure.+ const hit = parseEntry(await promptly(store.get(key), sharedReadTimeoutMs))+ if (hit && hit.expiresAt > now()) {+ remember(key, hit.profile, Math.min(hit.expiresAt, expiresAt))+ return hit.profile+ }+ }+ const profile = await load()+ remember(key, profile, expiresAt)+ // Not awaited: the token is already proved, and a hung store must not hold the answer hostage.+ if (store) void Promise.resolve().then(() => store.set(key, JSON.stringify({ ...profile, expiresAt }), expiresAt - now())).catch(() => { /* best effort */ })+ return profile+ }++ return {+ resolve(token, autonomousEnv, load) {+ const expiresAt = Math.min(now() + ttlMs, tokenExpiresAt(token) ?? Infinity)+ if (expiresAt <= now()) return load()++ const key = keyOf(token, autonomousEnv)+ const entry = entries.get(key)+ if (entry && entry.expiresAt > now()) return Promise.resolve(entry.profile)+ if (entry) entries.delete(key)++ const pending = inFlight.get(key)+ if (pending) return pending+ const filling = fill(key, expiresAt, load).finally(() => { inFlight.delete(key) })+ inFlight.set(key, filling)+ return filling+ },+ clear() {+ entries.clear()+ },+ }+}diff --git a/backend/src/lib/webWs.test.ts b/backend/src/lib/webWs.test.tsindex 63c35ea4d..d7125c278 100644--- a/backend/src/lib/webWs.test.ts+++ b/backend/src/lib/webWs.test.ts@@ -9,10 +9,12 @@ import { BACKEND_ONLY_DOWN_TYPES } from './webWs.js'* dropped during a tidy-up, which reopens the hole silently.*/describe('frames a web client may never forge', () => {- it('refuses the two backend-authoritative frames that are not `__`-prefixed', () => {+ it('refuses the backend-authoritative frames that are not `__`-prefixed', () => {// machine_meta names the account's private grid — the inference endpoint every agent on that// computer is then pointed at. machine_revoked makes the adapter clear its session and exit.- expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['machine_meta', 'machine_revoked'])+ // desk_changed / machines_changed make every window on that computer re-read from the backend:+ // forged in a loop, that is request amplification against our own API.+ expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['desk_changed', 'machine_meta', 'machine_revoked', 'machines_changed'])})it('covers only frames that are NOT already caught by the `__` rule', () => {diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.tsindex 2c61f62f1..72ad3c6d8 100644--- a/backend/src/lib/webWs.ts+++ b/backend/src/lib/webWs.ts@@ -62,10 +62,11 @@ import { recordRemoteUsage } from './dailyTracking.js'* prefixed, so they fell through this handler's namespace checks into the verbatim forward at the* bottom. See the block in `handleFrame` for what each one does when forged.*- * Senders, all backend-side: `lib/adapterWs.ts` (on connect) and `services/MachineService.ts`- * (rename, revoke).+ * Senders, all backend-side: `lib/adapterWs.ts` (on connect), `services/MachineService.ts`+ * (rename, revoke) and `lib/adapterAccountPushes.ts` (desk_changed, machines_changed — forged, each+ * one makes every window on that computer re-read from this backend).*/-export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked'])+export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'machines_changed'])const wss = createWss(WS_LIMITS.web, { echoFirstProtocol: true })diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.tsindex 4239d18f8..35a2f7a17 100644--- a/backend/src/routes/harnessShares.test.ts+++ b/backend/src/routes/harnessShares.test.ts@@ -3,11 +3,12 @@ import Fastify, { type FastifyInstance } from 'fastify'import { randomUUID } from 'node:crypto'const mocks = vi.hoisted(() => ({prisma: { harnessShare: { findFirst: vi.fn(), findMany: vi.fn(), findUnique: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },- machine: { findFirst: vi.fn(), findMany: vi.fn() }, user: { findMany: vi.fn() } },- presence: vi.fn(), changed: vi.fn(), auth: vi.fn(),+ machine: { findFirst: vi.fn(), findMany: vi.fn() }, user: { findMany: vi.fn(), findUnique: vi.fn() } },+ presence: vi.fn(), changed: vi.fn(), listChanged: vi.fn(), auth: vi.fn(),}))vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))-vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: mocks.presence, publishShareChanged: mocks.changed }))+vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: mocks.presence, publishShareChanged: mocks.changed,+ publishDeviceMachineListChanged: mocks.listChanged }))vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))import { harnessShareRoutes, recipientShare } from './harnessShares.js'import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'@@ -118,6 +119,33 @@ describe('account-bound harness invitations', () => {expect((await remove()).statusCode).toBe(404)expect(mocks.changed).toHaveBeenCalledTimes(1)})+ it('tells the invited account that its list changed, so its apps need not poll for invitations', async () => {+ const id = randomUUID()+ // First read is the "may this grant be changed" check (no row yet); the second is the saved invitation.+ mocks.prisma.harnessShare.findUnique.mockResolvedValueOnce(null).mockResolvedValue({ id, recipientEmail: '[email protected]' })+ mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })+ expect((await put(input(), id)).statusCode).toBe(200)+ expect(mocks.prisma.user.findUnique).toHaveBeenCalledWith({ where: { email: '[email protected]' }, select: { id: true } })+ expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'updated' })+ })+ it('tells the invited account when the owner takes the invitation back', async () => {+ const id = randomUUID()+ mocks.prisma.harnessShare.findUnique.mockResolvedValue({ id, recipientEmail: '[email protected]' })+ mocks.prisma.user.findUnique.mockResolvedValue({ id: 'ken' })+ expect((await app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })).statusCode).toBe(200)+ expect(mocks.listChanged).toHaveBeenCalledWith('ken', { reason: 'updated' })+ })+ it('invites an address with no account yet, and survives the lookup failing, without telling anyone', async () => {+ const id = randomUUID(), remove = () => app.inject({ method: 'DELETE', url: `/api/harness-shares/${id}`, headers: auth })+ mocks.prisma.harnessShare.findUnique.mockResolvedValue({ id, recipientEmail: '[email protected]' })+ mocks.prisma.user.findUnique.mockResolvedValue(null)+ expect((await remove()).statusCode).toBe(200)+ mocks.prisma.user.findUnique.mockRejectedValue(new Error('db unavailable'))+ expect((await remove()).statusCode).toBe(200)+ mocks.prisma.harnessShare.findUnique.mockResolvedValue(null)+ expect((await remove()).statusCode).toBe(200)+ expect(mocks.listChanged).not.toHaveBeenCalled()+ })it('rechecks exact recipient, expiry, current machine ownership and billing on socket admission', async () => {const grant = { ...input(), id: 'share', ownerId: 'owner' }mocks.prisma.harnessShare.findFirst.mockResolvedValue(null)diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.tsindex 8fdb547a0..1bcc23771 100644--- a/backend/src/routes/harnessShares.ts+++ b/backend/src/routes/harnessShares.ts@@ -1,7 +1,7 @@import type { FastifyInstance } from 'fastify'import { z } from 'zod'import { prisma, machineAlive } from '../lib/prisma.js'-import { getAgentPresenceMany, publishShareChanged } from '../lib/bus.js'+import { getAgentPresenceMany, publishDeviceMachineListChanged, publishShareChanged } from '../lib/bus.js'import { machineBillingAllowsDataPlane } from '../lib/billingState.js'import { validateBody, validateParams } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'@@ -22,6 +22,21 @@ const body = z.object({}).strict()/** Used again at socket admission and throughout a live connection. Never disclose another grant. */+/**+ * Shared harnesses arrive in the invited account's machine list, so an invitation given or taken back+ * is a list change for THAT account: poke its open apps (web tabs, and each computer's daemon → app)+ * to re-read. This is what lets the app stop polling `/api/harness-shares` to discover invitations.+ * Best effort — the invitation is already persisted, and an address with no account has nobody to tell.+ */+async function tellRecipient(shareId: string): Promise<void> {+ try {+ const share = await prisma.harnessShare.findUnique({ where: { id: shareId } })+ if (!share) return+ const recipient = await prisma.user.findUnique({ where: { email: share.recipientEmail }, select: { id: true } })+ if (recipient) await publishDeviceMachineListChanged(recipient.id, { reason: 'updated' })+ } catch { /* best effort */ }+}+export async function recipientShare(id: string, user: AuthUser) {const share = await prisma.harnessShare.findFirst({ where: {id, recipientEmail: user.email.trim().toLowerCase(), autonomousEnv: user.autonomousEnv,@@ -83,6 +98,7 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {await prisma.harnessShare.upsert({ where: { id: req.params.id },create: { id: req.params.id, ...data }, update: data })await publishShareChanged(req.params.id)+ await tellRecipient(req.params.id)sendSuccess(reply, { id: req.params.id })},)@@ -94,6 +110,7 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {}, data: { revokedAt: new Date() } })if (!changed.count) return sendError(reply, 'Invitation not found.', 'NOT_FOUND', 404)await publishShareChanged(req.params.id)+ await tellRecipient(req.params.id)sendSuccess(reply, { removed: true })})}diff --git a/backend/src/server.ts b/backend/src/server.tsindex aeb50755f..f136e117d 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -21,7 +21,8 @@ import { handleManagerUpgrade } from './lib/managerWs.js'import { handleAdapterUpgrade } from './lib/adapterWs.js'import { logger } from './utils/logger.js'import { startTurnCredentialRefresh } from './lib/turnCredentials.js'-import { closeBus } from './lib/bus.js'+import { closeBus, redisSsoProfileStore } from './lib/bus.js'+import { useSharedSsoProfileStore } from './lib/ssoAuth.js'import { drainAllSockets, openSocketCount, RELEASE_UPGRADE_SLOT, type SlotSocket } from './lib/wsServer.js'// Node ≥ 15 turns an unhandled rejection into a process exit. On a cluster worker that holds thousands of@@ -138,6 +139,10 @@ async function start(): Promise<void> {methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],})+ // Every process shares one memory of validated tokens; without it each worker asks the profile API+ // for itself. Attached before anything can authenticate — the REST gate below and the socket upgrades.+ useSharedSsoProfileStore(redisSsoProfileStore)+// SSO access-token gate for the control API (data-plane auth happens before Fastify).registerAuthMiddleware(app)diff --git a/cli/scripts/local-stack-peer.ts b/cli/scripts/local-stack-peer.tsindex 92487aad7..29cf62a41 100644--- a/cli/scripts/local-stack-peer.ts+++ b/cli/scripts/local-stack-peer.ts@@ -114,7 +114,7 @@ try {const backendEnv = { ...process.env, NODE_ENV: 'test', PORT: String(backendPort), PORT_APP_PROXY: String(proxyPort),DATABASE_URL: `mongodb://127.0.0.1:${mongoPort}/harness?replicaSet=rs0&directConnection=true`,REDIS_URL: `redis://127.0.0.1:${redisPort}`, HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false',- SSO_PROFILE_URL: `http://127.0.0.1:${ssoPort}/profile`, TERMINAL_P2P_ROLLOUT_PERCENT: '0',+ SSO_PROFILE_URL: `http://127.0.0.1:${ssoPort}/profile`, SSO_IDENTITY_URL: '', TERMINAL_P2P_ROLLOUT_PERCENT: '0',HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'],{ cwd: join(repo, 'backend'), env: backendEnv, timeout: 60_000 })diff --git a/cli/scripts/remote-viewers-stack.ts b/cli/scripts/remote-viewers-stack.tsindex d38b16a5c..bbccbff8a 100644--- a/cli/scripts/remote-viewers-stack.ts+++ b/cli/scripts/remote-viewers-stack.ts@@ -125,6 +125,7 @@ try {const backendEnv = { ...process.env, NODE_ENV: 'test', DATABASE_URL: mongo.getUri('viewer'),REDIS_URL: `redis://127.0.0.1:${redisPort}`, HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false',SSO_PROFILE_URL: `http://127.0.0.1:${(sso.address() as { port: number }).port}/profile`,+ SSO_IDENTITY_URL: '', // the stand-in SSO has only /profile; never prove rig tokens against the real BFFTERMINAL_P2P_ROLLOUT_PERCENT: '0', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {cwd: join(repo, 'backend'), env: backendEnv, timeout: 60_000,diff --git a/cli/scripts/share-harness-e2e.ts b/cli/scripts/share-harness-e2e.tsindex 2a60436d6..f935693ae 100644--- a/cli/scripts/share-harness-e2e.ts+++ b/cli/scripts/share-harness-e2e.ts@@ -121,6 +121,7 @@ try {const backendEnv = { ...process.env, NODE_ENV: 'test', PORT: String(backendPort), PORT_APP_PROXY: String(proxyPort),DATABASE_URL: mongo.href, REDIS_URL: redis.href, HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false',SSO_PROFILE_URL: `http://127.0.0.1:${(sso.address() as { port: number }).port}/profile`,+ SSO_IDENTITY_URL: '', // the stand-in SSO has only /profile; never prove rig tokens against the real BFFTERMINAL_P2P_ROLLOUT_PERCENT: '0', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], { cwd: join(repo, 'backend'), env: backendEnv, timeout: 60_000 })run('backend', join(repo, 'backend'), ['--import', 'tsx', 'src/server.ts'], backendEnv)diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex ef0ac8aa3..19c821de0 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { readFileSync } from 'fs'import { homedir } from 'os'import { fileURLToPath } from 'url'@@ -2155,3 +2155,42 @@ describe('agent_recent replies', () => {expect(reply.events[0]).not.toHaveProperty('fullText')})})++describe('machines_changed relay', () => {+ // Earlier suites in this file leave their sockets in the mock's list; index 0 must be ours.+ beforeEach(() => { wsMock.instances.length = 0 })+ afterEach(() => {+ wsMock.instances.length = 0+ vi.restoreAllMocks()+ })++ it('hands the backend\'s machines_changed to the window, and only the backend\'s', async () => {+ const socket = new BackendSocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:machines', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ ws.message({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: 'updated' } } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'machines_changed', payload: { reason: 'updated' } }))+ // A local client cannot make every window of this computer re-read the list by saying so.+ socket.handleLocalFrame('local:machines', { type: 'machines_changed', payload: { reason: 'forged' } })+ await new Promise((r) => setTimeout(r, 20))+ expect(frames.filter((f) => f.type === 'machines_changed')).toHaveLength(1)+ await socket.unregisterLocalClient('local:machines')+ await socket.stop()+ })++ it('relays a reason it can show and nothing else from the payload', async () => {+ const socket = new BackendSocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:machines', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ ws.message({ t: 'down', connId: '', frame: { type: 'machines_changed', payload: { reason: 42, extra: 'x' } } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'machines_changed', payload: { reason: 'updated' } }))+ await socket.unregisterLocalClient('local:machines')+ await socket.stop()+ })+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 29811fec3..cf3ea0a67 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -182,7 +182,7 @@ export type DownTransport = 'relay' | 'local' | 'p2p'* backend blocks its OWN `__`-prefixed control frames from web clients for the same reason; these* two escaped that rule because they are not `__`-prefixed.*/-const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed'])+const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'machines_changed'])interface QueueItem {id: number@@ -1450,6 +1450,15 @@ export class BackendSocket {return}+ // The account's machine list changed on some worker — a machine created / renamed / deleted, or a+ // shared harness invited / taken back. The window re-reads `/api/machines` through this daemon; this+ // push is why it does not have to poll for that. Backend-only for the same reason as desk_changed.+ if (type === 'machines_changed') {+ const reason = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { reason?: unknown }).reason : undefined)+ this.sendLocal({ type: 'machines_changed', payload: { reason: typeof reason === 'string' ? reason : 'updated' } })+ return+ }+// Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.if (type === 'machine_meta') {// ⚠️ The BACKEND's frame and nobody else's. It carries this machine's display name and, morediff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b24e387a9..8c7789954 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -550,6 +550,7 @@ class AppNotifier extends ChangeNotifier {Timer? _machineRecoveryTimer;Timer? _sharingDiscoveryTimer;bool _sharingDiscoveryBusy = false;+ bool _sharingDiscoveryAgain = false;int _machineRecoveryAttempts = 0;String? _machineLoadError;@@ -1536,6 +1537,14 @@ class AppNotifier extends ChangeNotifier {static const localDaemonReconnectDelay = Duration(seconds: 1);static const agentSyncInterval = Duration(seconds: 60);+ /// How often the machine list is re-read with nothing having asked for it.+ /// The list is PUSHED (`machines_changed`, backend → daemon → this window);+ /// this only catches a push that was missed. Minutes, never seconds: a re-read+ /// is two authenticated backend requests (`/api/machines` ++ /// `/api/harness-shares`) from every open app, and at 15s that — not people —+ /// was most of the backend's traffic.+ static const machineListSafetyNetInterval = Duration(minutes: 5);+MachineState? stateOf(String machineId) => machineStates[machineId];// ── the grid ────────────────────────────────────────────────────────────────────────────────────@@ -2880,6 +2889,7 @@ class AppNotifier extends ChangeNotifier {_sharingDiscoveryTimer?.cancel();_sharingDiscoveryTimer = null;_sharingDiscoveryBusy = false;+ _sharingDiscoveryAgain = false;_daemonGateFailed = false;_bootStatusMessage = null;_clearAllTurnActivity();@@ -3797,34 +3807,78 @@ class AppNotifier extends ChangeNotifier {}if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);_autoConnectAndLoadMachines();- _sharingDiscoveryTimer ??= Timer.periodic(const Duration(seconds: 15), (+ // The list is pushed (`machines_changed`); this only catches a missed push.+ _sharingDiscoveryTimer ??= Timer.periodic(machineListSafetyNetInterval, (_,- ) async {- if (_disposed ||- status != AppStatus.authenticated ||- _sharingDiscoveryBusy ||- machinesRefreshing) {- return;- }- final discoveryRevision = _authRevision;- _sharingDiscoveryBusy = true;- // A push that was missed is caught here: the desk read is one small- // GET, and an unchanged revision applies nothing.- if (_desk.enabled && _desk.pending.isEmpty) unawaited(_deskFetch());- try {- await refreshMachines();- } catch (error) {- if (_authWorkCurrent(discoveryRevision)) {- _reportMachineLoadError(error, automatic: true);- notifyListeners();- }- } finally {- if (_authWorkCurrent(discoveryRevision)) _sharingDiscoveryBusy = false;- }+ ) {+ // The desk is pushed too, and a missed desk push is caught here as well:+ // one small GET, and an unchanged revision applies nothing.+ if (!_disposed &&+ status == AppStatus.authenticated &&+ _desk.enabled &&+ _desk.pending.isEmpty) {+ unawaited(_deskFetch());+ }+ unawaited(_rereadMachinesInBackground(pushed: false));});notifyListeners();}+ /// Re-read the machine list because something other than the person asked:+ /// a `machines_changed` push, or the safety-net timer.+ ///+ /// One at a time. A push that arrives while a read is open marks it dirty+ /// instead of starting another — the open read may predate that change, so+ /// exactly one more follows it. A bulk rename pushes once per machine;+ /// without this each push would be its own pair of requests. A timer tick+ /// that finds a read open has nothing to add and is dropped.+ Future<void> _rereadMachinesInBackground({required bool pushed}) async {+ if (_disposed || status != AppStatus.authenticated) return;+ if (_sharingDiscoveryBusy) {+ if (pushed) _sharingDiscoveryAgain = true;+ return;+ }+ if (machinesRefreshing && !pushed) return;+ final discoveryRevision = _authRevision;+ _sharingDiscoveryBusy = true;+ try {+ // This call owes one read; every push that lands while we are busy owes+ // one more (collapsed into a single follow-up by the flag).+ var owed = true;+ while (owed || _sharingDiscoveryAgain) {+ // Still ours? Checked BEFORE the flag is cleared: a run left over from+ // a session that has since signed out must not eat the dirty flag that+ // belongs to the new session's run.+ if (_disposed ||+ status != AppStatus.authenticated ||+ !_authWorkCurrent(discoveryRevision)) {+ return;+ }+ // A reload (the person's, or recovery's) that is open right now: let it+ // finish first, on EVERY pass. Its read may predate this push, and+ // starting ours beside it would supersede its request — it would then+ // give up before clearing its error and reloading the open machines.+ final reload = _retryInFlight;+ if (reload != null) {+ try {+ await reload;+ } catch (_) {}+ continue;+ }+ owed = false;+ _sharingDiscoveryAgain = false;+ await refreshMachines();+ }+ } catch (error) {+ if (_authWorkCurrent(discoveryRevision)) {+ _reportMachineLoadError(error, automatic: true);+ notifyListeners();+ }+ } finally {+ if (_authWorkCurrent(discoveryRevision)) _sharingDiscoveryBusy = false;+ }+ }+// The daemon reports `connected` only once its own backend socket is open, but// `/api/machines` is a separate REST leg (fresh token refresh + fetch) that can still stall// briefly right after that — a bounded retry absorbs that transient window without falling@@ -9388,6 +9442,12 @@ class AppNotifier extends ChangeNotifier {}}break;+ case 'machines_changed':+ // The account's machine list changed somewhere: a machine created,+ // renamed or deleted, or a shared harness invited or taken back. The+ // payload is only a reason; the list itself is re-read.+ unawaited(_rereadMachinesInBackground(pushed: true));+ break;case 'desk_changed':// Another window — on another computer, or this one — changed the// tabs. The payload is only the revision; the document is fetched.diff --git a/desktop/test/machine_list_push_test.dart b/desktop/test/machine_list_push_test.dartnew file mode 100644index 000000000..10055092d--- /dev/null+++ b/desktop/test/machine_list_push_test.dart@@ -0,0 +1,272 @@+// The machine list is pushed, not polled. The backend tells every daemon socket+// of the account when the list changed (a machine created / renamed / deleted,+// a shared harness invited or taken back); the daemon relays `machines_changed`+// to the window, which re-reads. What is left on a timer is a safety net for a+// push that was missed — minutes apart, because every re-read is two+// authenticated backend requests from every open app.+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/auth/cli_login.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:harness/ws/ws_conn.dart';++const _computerId = 'aabbccddeeff0011';++/// Counts every read of the list, and lets a test hold one open.+class _Api extends ApiClient {+ _Api() : super(config: AppConfig.dev, session: AuthSession());+ int reads = 0;+ Completer<void>? hold;++ /// When set, every read waits on a gate of its own, so a test can finish+ /// them in the order it chooses.+ List<Completer<void>>? gates;++ @override+ Future<Map<String, dynamic>?> me() async => null;++ // A daemon without the desk: a manual reload asks, and must not reach the network.+ @override+ Future<Map<String, dynamic>?> desk() async => null;++ @override+ Future<List<Machine>> machines() async {+ reads++;+ final gate = gates == null ? null : Completer<void>();+ if (gate != null) gates!.add(gate);+ await hold?.future;+ await gate?.future;+ return const [_localMachine];+ }+}++class _Cli extends CliLogin {+ @override+ Future<CliAuthStatus> checkStatus() async =>+ const CliAuthStatus(loggedIn: true);+ @override+ Future<void> login({void Function(String url)? onAuthorizeUrl}) async {}+ @override+ Future<void> logout() async {}+}++class _Discovery extends LocalCliDiscovery {+ _Discovery() : super(config: AppConfig.dev);+ @override+ Future<String?> computerId() async => _computerId;+ @override+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>+ LocalCliEndpoint(+ computerId: _computerId,+ wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),+ protocolVersion: localWsProtocolVersion,+ terminalProtocolVersion: 1,+ machineId: 'local-machine',+ backendOnline: true,+ );+}++class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'local-machine',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async => const {'agents': []};+}++class _App extends AppNotifier {+ _App(_Api api)+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ cliLogin: _Cli(),+ localCliDiscovery: _Discovery(),+ connectionForTest: (_) => _Connection(),+ ) {+ this.api = api;+ }+ @override+ Future<void> ensureCliDaemonReady() async {}+}++const _localMachine = Machine(+ machineId: 'local-machine',+ name: 'This computer',+ computerId: _computerId,+ authMode: MachineAuthMode.remote,+ status: 'online',+);++const _push = {+ 'type': 'machines_changed',+ 'payload': {'reason': 'updated'},+};++/// A successful read arms the safety-net timer, and `testWidgets` checks for+/// pending timers before tear-downs run — so every test disposes its own app.+_App _signedIn(_Api api) {+ final app = _App(api);+ app.status = AppStatus.authenticated;+ app.machines = [_localMachine];+ app.machineStates['local-machine'] = MachineState(_localMachine)+ ..localOnly = true;+ return app;+}++void main() {+ testWidgets('a machines_changed push re-reads the machine list', (+ tester,+ ) async {+ final api = _Api();+ final app = _signedIn(api);++ await app.handleEventForTest('local-machine', _push);+ await tester.pump();++ expect(api.reads, 1);+ app.dispose();+ });++ testWidgets('a push is ignored once the person has signed out', (+ tester,+ ) async {+ final api = _Api();+ final app = _signedIn(api)..status = AppStatus.unauthenticated;++ await app.handleEventForTest('local-machine', _push);+ await tester.pump();++ expect(api.reads, 0);+ app.dispose();+ });++ testWidgets(+ 'a burst of pushes during a re-read costs one more read, not one each',+ (tester) async {+ final api = _Api()..hold = Completer<void>();+ final app = _signedIn(api);++ // A bulk rename: the first push starts a read, the rest land while it is open.+ for (var i = 0; i < 5; i++) {+ await app.handleEventForTest('local-machine', _push);+ }+ await tester.pump();+ expect(api.reads, 1);++ // The open read may predate the later changes, so exactly one more follows it.+ api.hold!.complete();+ api.hold = null;+ await tester.pump();+ await tester.pump();+ expect(api.reads, 2);+ app.dispose();+ },+ );++ testWidgets(+ 'a push that lands during a read the person started is not lost',+ (tester) async {+ final api = _Api()..hold = Completer<void>();+ final app = _signedIn(api);++ // Reload pressed; the read is open when the list changes underneath it.+ final manual = app.retryMachines();+ await tester.pump();+ expect(api.reads, 1);+ await app.handleEventForTest('local-machine', _push);+ await tester.pump();++ api.hold!.complete();+ api.hold = null;+ await tester.pump();+ await manual;+ await tester.pump();++ // The open read may predate the change, so the push still gets its own.+ expect(api.reads, 2);+ app.dispose();+ },+ );++ testWidgets(+ 'a follow-up read waits for a reload that started meanwhile, instead of superseding it',+ (tester) async {+ final api = _Api()..gates = [];+ final app = _signedIn(api);++ // Read #1 is ours; a second push asks for a follow-up once it is done.+ await app.handleEventForTest('local-machine', _push);+ await tester.pump();+ await app.handleEventForTest('local-machine', _push);+ // The person presses Reload while #1 is still open: read #2 is theirs.+ final manual = app.retryMachines();+ await tester.pump();+ expect(api.reads, 2);++ // #1 finishes. Starting the follow-up NOW would supersede the reload's+ // request, and the reload would give up before finishing its own work.+ api.gates![0].complete();+ await tester.pump();+ await tester.pump();+ expect(api.reads, 2, reason: 'the follow-up waits for the reload');++ api.gates![1].complete();+ await tester.pump();+ await manual;+ await tester.pump();+ expect(api.reads, 3, reason: 'then the follow-up read happens');+ api.gates![2].complete();+ await tester.pump();+ await tester.pump();+ app.dispose();+ },+ );++ testWidgets(+ 'what is left on a timer is a safety net, minutes apart — not a poll',+ (tester) async {+ final api = _Api();+ final app = _signedIn(api);++ // A successful read arms the background timer.+ await app.refreshMachines();+ await tester.pump();+ final afterLoad = api.reads;++ // The old 15s discovery poll would have read four more times by now.+ await tester.pump(const Duration(seconds: 60));+ expect(api.reads, afterLoad);++ await tester.pump(AppNotifier.machineListSafetyNetInterval);+ await tester.pump();+ expect(api.reads, afterLoad + 1);+ app.dispose();+ },+ );++ test('the safety net is minutes, never seconds', () {+ expect(+ AppNotifier.machineListSafetyNetInterval,+ greaterThanOrEqualTo(const Duration(minutes: 5)),+ );+ });+}diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dartindex 14723dc86..25e152c4f 100644--- a/desktop/test/profile_startup_test.dart+++ b/desktop/test/profile_startup_test.dart@@ -262,9 +262,12 @@ void main() {expect(app.lastError, isNull);expect(app.machineStates['fixture']!.agents, hasLength(1));expect(app.daemonChecks, 2);- await tester.pump(const Duration(seconds: 35));- // Invitation discovery continues after recovery without probing the daemon again.- // Its pending poll is coalesced across subsequent ticks.+ await tester.pump(+ AppNotifier.machineListSafetyNetInterval * 2 ++ const Duration(seconds: 5),+ );+ // The safety-net re-read continues after recovery without probing the daemon again.+ // Its pending read is coalesced across subsequent ticks.expect(api.lists, hasLength(3));api.lists.last.complete([_machine]);await tester.pump();@@ -283,7 +286,7 @@ void main() {await tester.pump();await start;- await tester.pump(const Duration(seconds: 15));+ await tester.pump(AppNotifier.machineListSafetyNetInterval);expect(api.lists, hasLength(2));api.lists.last.completeError(ApiException('Backend unreachable', status: 502),@@ -295,16 +298,19 @@ void main() {await tester.pump(const Duration(seconds: 2));expect(api.lists, hasLength(3));- // Discovery must not duplicate a recovery request that is still pending.- await tester.pump(const Duration(seconds: 30));+ // The safety net must not duplicate a recovery request that is still pending.+ await tester.pump(AppNotifier.machineListSafetyNetInterval);expect(api.lists, hasLength(3));api.lists.last.complete([_machine]);await tester.pump();expect(app.machinesRefreshing, isFalse);- await tester.pump(const Duration(seconds: 15));+ await tester.pump(AppNotifier.machineListSafetyNetInterval);expect(api.lists, hasLength(4));api.lists.last.complete([_machine]);await tester.pump();+ // …nor remember the tick it skipped: one read per tick, not a second one owed from before.+ await tester.pump();+ expect(api.lists, hasLength(4));disposeApp();},);