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
Persist experiments and creature collections per account (#437)
Dee621a2b8f6df1
diff --git a/.github/assets/swarm-collaboration/README.md b/.github/assets/swarm-collaboration/README.mdindex 244f3036a..0fe6279ca 100644--- a/.github/assets/swarm-collaboration/README.md+++ b/.github/assets/swarm-collaboration/README.md@@ -2,7 +2,7 @@Flutter widget renders with synthetic account and conversation data, September 28, 2026.-- `settings.png`: Settings → Experimental, with Swarm collaboration off by default beside the existing experiments.+- `settings.png`: Settings → Experimental, with all switches off by default and saved to the account. The creature card explains that its collection and progress are saved too.- `conversation.png`: the current tab's peers, correlated question and answer, and return delivery state.Regenerate using `CHANNEL_RENDER_DIR=/tmp/harness-channel-review` with the desktopdiff --git a/.github/assets/swarm-collaboration/settings.png b/.github/assets/swarm-collaboration/settings.pngindex 6e01aaeb3..9a874301f 100644Binary files a/.github/assets/swarm-collaboration/settings.png and b/.github/assets/swarm-collaboration/settings.png differdiff --git a/backend/.env.example b/backend/.env.exampleindex 2e0b170e5..9201fc2a2 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -92,8 +92,8 @@ HARNESS_CREDENTIAL_ENCRYPTION_KEY=# Comma-separated emails that get role=admin when first created (login auto-creates users).ADMIN_EMAILS=-# Daemons (daemons/README.md, "Off switches"). Off unless true: the zoo routes are not registered, so-# /api/zoo answers 404 and every client hides daemons. With it on, HARNESS_DAEMONS_USERS (comma-separated-# user ids or emails) limits them to those accounts; empty is everyone.-HARNESS_DAEMONS=false+# Creature availability (daemons/README.md, "Off switches"). Every account must still opt in through+# Experimental settings; missing choices are off. Explicit false disables the module and its routes.+# HARNESS_DAEMONS_USERS optionally limits availability to comma-separated user ids or emails.+HARNESS_DAEMONS=trueHARNESS_DAEMONS_USERS=diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex f684e4232..e266f53b1 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -653,6 +653,18 @@ model TabChannelSettings {@@map("tab_channel_settings")}+/// Explicit account opt-ins; missing choices stay off. Each write changes one feature.+model ExperimentalSettings {+ id String @id @map("_id") @db.ObjectId+ userId String+ focusBarCreature Boolean @default(false)+ shareButton Boolean @default(false)+ revision Int @default(0)++ @@index([userId])+ @@map("experimental_settings")+}+/// The account's ZOO: the daemons it hatched, the eggs waiting, which one is paired, and the/// first-egg habits done so far — one document per user, the same on every client, like the desk/// but separate from it (daemons/README.md, "The zoo"). Written through `POST /api/zoo/ops`diff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex f94e92e6a..77bbf726d 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -179,11 +179,9 @@ const envSchema = z.object({// Comma-separated emails granted role=admin on first creation.ADMIN_EMAILS: z.string().default(''),- // The daemons (daemons/README.md, "Off switches"): OFF unless 'true'. Off, the zoo routes are not- // registered at all (/api/zoo answers the ordinary 404) and nothing publishes or hears `zoo_changed`,- // which every client reads as "daemons are off". HARNESS_DAEMONS_USERS, with it on: comma-separated user- // ids or emails who alone see the zoo (the rest get the same 404); empty is everyone. lib/daemonsSwitch.ts.- HARNESS_DAEMONS: z.string().default('false'),+ // Server availability, not user opt-in. Accounts must enable the creature in Experimental settings.+ // Explicit false keeps the module dark; the optional allowlist further limits availability.+ HARNESS_DAEMONS: z.string().default('true'),HARNESS_DAEMONS_USERS: z.string().default(''),// Device voice STT (PCM arrives on /api/device-ws → batch STT). VOICE_PROVIDER selects the backend:@@ -266,5 +264,5 @@ export const ADMIN_EMAILS = new Set(env.ADMIN_EMAILS.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean),)-/** Whether this server has daemons, and for whom (lib/daemonsSwitch.ts). Off by default. */+/** Server availability (lib/daemonsSwitch.ts). The account's Experimental opt-in defaults off. */export const DAEMONS = parseDaemonsSwitch(env.HARNESS_DAEMONS, env.HARNESS_DAEMONS_USERS)diff --git a/backend/src/lib/daemonsSwitch.test.ts b/backend/src/lib/daemonsSwitch.test.tsindex 8a1bfab2f..102f2639e 100644--- a/backend/src/lib/daemonsSwitch.test.ts+++ b/backend/src/lib/daemonsSwitch.test.ts@@ -28,7 +28,7 @@ describe('the daemons switch', () => {it('says what it does in the boot log without naming anyone', () => {expect(describeDaemonsSwitch(DAEMONS_DARK)).toBe('daemons: off (HARNESS_DAEMONS)')- expect(describeDaemonsSwitch(parseDaemonsSwitch('true'))).toBe('daemons: on for everyone')- expect(describeDaemonsSwitch(parseDaemonsSwitch('true', '[email protected]'))).toBe('daemons: on for 1 allowlisted account')+ expect(describeDaemonsSwitch(parseDaemonsSwitch('true'))).toBe('daemons: available (account opt-in required)')+ expect(describeDaemonsSwitch(parseDaemonsSwitch('true', '[email protected]'))).toBe('daemons: available to 1 allowlisted account (account opt-in required)')})})diff --git a/backend/src/lib/daemonsSwitch.ts b/backend/src/lib/daemonsSwitch.tsindex 98e1cf42b..7c9a841b2 100644--- a/backend/src/lib/daemonsSwitch.ts+++ b/backend/src/lib/daemonsSwitch.ts@@ -1,12 +1,13 @@/**- * The daemons' server switch (daemons/README.md, "Off switches"). Every deploy ships them dark:+ * Server availability (daemons/README.md, "Off switches"), separate from account opt-in:*- * HARNESS_DAEMONS off unless `true`, `1`, `on` or `yes`. Off, the zoo routes are never registered+ * HARNESS_DAEMONS env.ts defaults to `true`; explicit false disables it. Off, zoo routes are never registered* (`/api/zoo` and `/api/zoo/ops` answer the server's ordinary 404), nothing- * publishes `zoo_changed`, and no socket subscribes to it.+ * writes the zoo, and no socket subscribes to `zoo_changed`.* HARNESS_DAEMONS_USERS optional, with the switch on: comma-separated user ids or emails (emails in* any case). Only those accounts see the zoo; everyone else gets the same 404 as- * if the switch were off. Empty: every account.+ * if the switch were off. Empty: every account may opt in.+ * Experimental settings focus_bar_creature must also be true. Missing choices are off.** A client (harnessd, the desktop, the phone, hn) treats a 404 from `GET /api/zoo` as "daemons are off":* it hides everything daemon-related and behaves exactly as it did before daemons existed.@@ -29,7 +30,7 @@ export function parseDaemonsSwitch(flag: string | undefined, users?: string): Dareturn { on, users: list.length ? new Set(list) : null }}-/** Whether this account sees the zoo. */+/** Whether this account may opt in to the zoo. */export function daemonsFor(sw: DaemonsSwitch, user: { sub: string; email?: string | null } | null | undefined): boolean {if (!sw.on || !user) return falseif (!sw.users) return true@@ -39,5 +40,5 @@ export function daemonsFor(sw: DaemonsSwitch, user: { sub: string; email?: strin/** One line for the boot log: what this server does with daemons. Never lists who. */export function describeDaemonsSwitch(sw: DaemonsSwitch): string {if (!sw.on) return 'daemons: off (HARNESS_DAEMONS)'- return sw.users ? `daemons: on for ${sw.users.size} allowlisted account${sw.users.size === 1 ? '' : 's'}` : 'daemons: on for everyone'+ return sw.users ? `daemons: available to ${sw.users.size} allowlisted account${sw.users.size === 1 ? '' : 's'} (account opt-in required)` : 'daemons: available (account opt-in required)'}diff --git a/backend/src/lib/experimentalSettings.ts b/backend/src/lib/experimentalSettings.tsnew file mode 100644index 000000000..01b3ee899--- /dev/null+++ b/backend/src/lib/experimentalSettings.ts@@ -0,0 +1,37 @@+import { createHash } from 'node:crypto'+import { Prisma } from '@prisma/client'+import { prisma } from './prisma.js'++export const experimentalFeatures = ['focus_bar_creature', 'share_button'] as const+export type ExperimentalFeature = typeof experimentalFeatures[number]+export const experimentalSettingsId = (userId: string): string =>+ createHash('sha256').update(JSON.stringify(['experimental-settings', userId])).digest('hex').slice(0, 24)++const snapshot = (row: { focusBarCreature: boolean; shareButton: boolean; revision: number } | null) => ({+ revision: row?.revision ?? 0,+ features: { focus_bar_creature: row?.focusBarCreature === true, share_button: row?.shareButton === true },+})++/** Reading never opts an account in or imports an installation's unscoped preferences. */+export async function readExperimentalSettings(userId: string) {+ const row = await prisma.experimentalSettings.findUnique({ where: { id: experimentalSettingsId(userId) } })+ if (row && row.userId !== userId) throw new Error('Experimental settings identity mismatch')+ return snapshot(row)+}++/** Change one field atomically so two machines editing different switches keep both choices. */+export async function setExperimentalSetting(userId: string, feature: ExperimentalFeature, enabled: boolean) {+ const id = experimentalSettingsId(userId)+ const field = feature === 'focus_bar_creature' ? 'focusBarCreature' : 'shareButton'+ const data = { [field]: enabled, revision: { increment: 1 } }+ let row+ try {+ row = await prisma.experimentalSettings.upsert({ where: { id },+ create: { id, userId, focusBarCreature: false, shareButton: false, [field]: enabled, revision: 1 },+ update: data })+ } catch (error) {+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== 'P2002') throw error+ row = await prisma.experimentalSettings.update({ where: { id }, data })+ }+ return snapshot(row)+}diff --git a/backend/src/routes/experimentalSettings.test.ts b/backend/src/routes/experimentalSettings.test.tsnew file mode 100644index 000000000..98e457ae8--- /dev/null+++ b/backend/src/routes/experimentalSettings.test.ts@@ -0,0 +1,105 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import { Prisma } from '@prisma/client'+const mocks = vi.hoisted(() => ({+ prisma: { experimentalSettings: { findUnique: vi.fn(), upsert: vi.fn(), update: vi.fn() }, zoo: { findUnique: vi.fn() } },+ auth: vi.fn(), deskChanged: vi.fn(), zooChanged: vi.fn(),+}))+vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma }))+vi.mock('../lib/bus.js', () => ({ publishDeskChanged: mocks.deskChanged, publishZooChanged: mocks.zooChanged }))+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))+import { experimentalSettingsRoutes } from './experimentalSettings.js'+import { experimentalSettingsId } from '../lib/experimentalSettings.js'+import { zooRoutes } from './zoo.js'+import { emptyZoo } from '../lib/zoo.js'+import { DAEMONS_DARK, DAEMONS_EVERYONE, type DaemonsSwitch } from '../lib/daemonsSwitch.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'++type Row = { id: string; userId: string; focusBarCreature: boolean; shareButton: boolean; revision: number }+describe('account experiments and retained collections', () => {+ let app: FastifyInstance+ let rows: Map<string, Row>+ const auth = { authorization: 'Bearer fixture' }+ async function makeApp(daemons: DaemonsSwitch = DAEMONS_EVERYONE) {+ const server = Fastify(); server.setErrorHandler(errorHandler); registerAuthMiddleware(server, mocks.auth)+ await server.register(experimentalSettingsRoutes, { daemons })+ await server.register(zooRoutes, { daemons, requireAccountOptIn: true }); await server.ready()+ return server+ }+ beforeEach(async () => {+ vi.resetAllMocks(); rows = new Map()+ mocks.auth.mockResolvedValue({ sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' })+ mocks.deskChanged.mockResolvedValue(0); mocks.zooChanged.mockResolvedValue(0)+ mocks.prisma.experimentalSettings.findUnique.mockImplementation(async ({ where }) => rows.get(where.id) ?? null)+ mocks.prisma.experimentalSettings.update.mockImplementation(async ({ where, data }) => {+ const row = { ...rows.get(where.id)! }+ for (const key of ['focusBarCreature', 'shareButton'] as const) if (key in data) row[key] = data[key]+ row.revision++; rows.set(row.id, row); return row+ })+ mocks.prisma.experimentalSettings.upsert.mockImplementation(async ({ where, create, update }) => {+ if (rows.has(where.id)) return mocks.prisma.experimentalSettings.update({ where, data: update })+ rows.set(where.id, create); return create+ })+ mocks.prisma.zoo.findUnique.mockResolvedValue(null)+ app = await makeApp()+ })+ afterEach(async () => app.close())+ const read = () => app.inject({ method: 'GET', url: '/api/experimental-settings', headers: auth })+ const write = (feature: string, enabled: boolean, accountId = 'owner') => app.inject({+ method: 'PATCH', url: '/api/experimental-settings', headers: auth, payload: { accountId, feature, enabled },+ })+ const zoo = () => app.inject({ method: 'GET', url: '/api/zoo', headers: auth })++ it('requires authentication and defaults off without writing or reading the collection', async () => {+ expect((await app.inject({ method: 'GET', url: '/api/experimental-settings' })).statusCode).toBe(401)+ expect(mocks.prisma.experimentalSettings.findUnique).not.toHaveBeenCalled()+ expect((await read()).json().data).toEqual({ accountId: 'owner', revision: 0,+ features: { focus_bar_creature: false, share_button: false }, available: { focus_bar_creature: true, share_button: true } })+ expect(rows.size).toBe(0)+ expect((await zoo()).statusCode).toBe(404)+ expect(mocks.prisma.zoo.findUnique).not.toHaveBeenCalled()+ })+ it('shares choices between clients without losing concurrent changes to different switches', async () => {+ expect((await Promise.all([write('focus_bar_creature', true), write('share_button', true)])).map(r => r.statusCode)).toEqual([200, 200])+ expect((await read()).json().data).toMatchObject({ revision: 2, features: { focus_bar_creature: true, share_button: true } })+ expect((await write('share_button', false)).json().data.features).toEqual({ focus_bar_creature: true, share_button: false })+ expect(mocks.deskChanged).toHaveBeenCalledWith('owner', { revision: 0 })+ expect(mocks.zooChanged).toHaveBeenCalledExactlyOnceWith('owner', { revision: 0 })+ })+ it('rejects malformed writes and requests created before an account switch', async () => {+ expect((await write('focus_bar_creature', true, 'another-account')).statusCode).toBe(409)+ expect((await write('unknown', true)).statusCode).toBe(400)+ expect((await app.inject({ method: 'PATCH', url: '/api/experimental-settings', headers: auth,+ payload: { accountId: 'owner', feature: 'share_button', enabled: 'true' } })).statusCode).toBe(400)+ expect(rows.size).toBe(0); expect(mocks.deskChanged).not.toHaveBeenCalled()+ })+ it('isolates accounts and resumes the same collection after off/on', async () => {+ const collection = { ...emptyZoo(), habits: ['turn', 'split'], eggs: [{ id: 'saved-egg', kind: 'first', grantedAt: '2026-09-28T00:00:00.000Z' }] }+ mocks.prisma.zoo.findUnique.mockImplementation(async ({ where }) => where.userId === 'owner' ? { revision: 7, state: collection } : null)+ await write('focus_bar_creature', true)+ expect((await zoo()).json().data).toEqual({ revision: 7, zoo: collection })+ await write('focus_bar_creature', false); expect((await zoo()).statusCode).toBe(404)+ await write('focus_bar_creature', true)+ expect((await zoo()).json().data).toEqual({ revision: 7, zoo: collection })+ mocks.auth.mockResolvedValue({ sub: 'second', email: '[email protected]', role: 'user', autonomousEnv: 'prod' })+ expect((await read()).json().data.features.focus_bar_creature).toBe(false)+ expect((await zoo()).statusCode).toBe(404)+ await write('focus_bar_creature', true, 'second')+ expect((await zoo()).json().data.zoo).toEqual(emptyZoo())+ })+ it('retries a concurrent first write without replacing the other switch', async () => {+ const id = experimentalSettingsId('owner')+ rows.set(id, { id, userId: 'owner', focusBarCreature: true, shareButton: false, revision: 1 })+ mocks.prisma.experimentalSettings.upsert.mockRejectedValueOnce(new Prisma.PrismaClientKnownRequestError('duplicate', { code: 'P2002', clientVersion: 'fixture' }))+ expect((await write('share_button', true)).json().data).toMatchObject({ revision: 2, features: { focus_bar_creature: true, share_button: true } })+ })+ it('respects the operator off switch without changing account choices', async () => {+ await app.close(); app = await makeApp(DAEMONS_DARK)+ expect((await read()).json().data.available.focus_bar_creature).toBe(false)+ expect((await write('focus_bar_creature', true)).statusCode).toBe(503)+ expect(rows.size).toBe(0)+ expect((await write('share_button', true)).statusCode).toBe(200)+ expect((await zoo()).statusCode).toBe(404)+ })+})diff --git a/backend/src/routes/experimentalSettings.ts b/backend/src/routes/experimentalSettings.tsnew file mode 100644index 000000000..e69590a50--- /dev/null+++ b/backend/src/routes/experimentalSettings.ts@@ -0,0 +1,32 @@+import type { FastifyInstance } from 'fastify'+import { z } from 'zod'+import { experimentalFeatures, readExperimentalSettings, setExperimentalSetting } from '../lib/experimentalSettings.js'+import { daemonsFor, DAEMONS_DARK, type DaemonsSwitch } from '../lib/daemonsSwitch.js'+import { publishDeskChanged, publishZooChanged } from '../lib/bus.js'+import { validateBody } from '../middlewares/validation.js'+import { sendError, sendSuccess } from '../utils/response.js'++const settingBody = z.object({ accountId: z.string().min(1).max(200), feature: z.enum(experimentalFeatures), enabled: z.boolean() }).strict()++export async function experimentalSettingsRoutes(app: FastifyInstance, opts: { daemons?: DaemonsSwitch } = {}) {+ const available = (user: { sub: string; email?: string | null } | undefined) => ({+ focus_bar_creature: daemonsFor(opts.daemons ?? DAEMONS_DARK, user), share_button: true,+ })+ app.get('/api/experimental-settings', async (req, reply) => {+ sendSuccess(reply, { accountId: req.user!.sub, ...await readExperimentalSettings(req.user!.sub), available: available(req.user) })+ })+ app.patch<{ Body: z.infer<typeof settingBody> }>('/api/experimental-settings', {+ preHandler: validateBody(settingBody),+ }, async (req, reply) => {+ const { feature, enabled } = req.body+ if (req.body.accountId !== req.user!.sub) return sendError(reply, 'Your account changed. Reopen Settings and try again.', 'ACCOUNT_CHANGED', 409)+ const availability = available(req.user)+ if (enabled && !availability[feature]) return sendError(reply, 'This experiment is unavailable on this server.', 'EXPERIMENT_UNAVAILABLE', 503)+ const userId = req.user!.sub+ const settings = await setExperimentalSetting(userId, feature, enabled)+ // Existing account invalidations reach old and new daemons without changing the desk document.+ void publishDeskChanged(userId, { revision: 0 })+ if (feature === 'focus_bar_creature') void publishZooChanged(userId, { revision: 0 })+ sendSuccess(reply, { accountId: userId, ...settings, available: availability })+ })+}diff --git a/backend/src/routes/zoo.ts b/backend/src/routes/zoo.tsindex 1d3b6bb2e..55457c197 100644--- a/backend/src/routes/zoo.ts+++ b/backend/src/routes/zoo.ts@@ -26,7 +26,8 @@* Dark unless the server's daemons switch is on (lib/daemonsSwitch.ts, `HARNESS_DAEMONS`): off, none of* this is registered and both paths answer the server's ordinary 404; on with an allowlist* (`HARNESS_DAEMONS_USERS`), an account outside it gets that same 404 before anything is read or written.- * A client reads the 404 as "daemons are off" and shows nothing of them.+ * Production also requires the account's focus_bar_creature opt-in; absent or false returns 404+ * without reading or changing its collection. A client reads 404 as "daemons are off" and hides it.*/import type { FastifyInstance } from 'fastify'import { Prisma } from '@prisma/client'@@ -37,6 +38,7 @@ import { daemonsFor, DAEMONS_DARK, type DaemonsSwitch } from '../lib/daemonsSwitimport { applyZooOps, emptyZoo, parseZoo, zooOpsBodySchema, zooShownChanged, type Hatched, type Zoo, type ZooContext, type ZooDoc, type ZooOp } from '../lib/zoo.js'import { validateBody } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'+import { readExperimentalSettings } from '../lib/experimentalSettings.js'const WRITE_ATTEMPTS = 5/** Two first-ever hatches of one daemon at once both try to create its counter; the loser increments. */@@ -103,6 +105,8 @@ function keepSerials(pool: SerialPool, used: Array<[string, number]>): void {export interface ZooRouteOptions {/** Whether this server has daemons, and for whom. Absent: dark, nothing registered. */daemons?: DaemonsSwitch+ /** Production requires the account's explicit Experimental choice as well as server availability. */+ requireAccountOptIn?: boolean}export async function zooRoutes(app: FastifyInstance, opts: ZooRouteOptions = {}): Promise<void> {@@ -113,6 +117,9 @@ export async function zooRoutes(app: FastifyInstance, opts: ZooRouteOptions = {}// this plugin, so it guards these routes only.app.addHook('preHandler', async (req, reply) => {if (!daemonsFor(daemons, req.user)) return reply.callNotFound()+ if (opts.requireAccountOptIn && !(await readExperimentalSettings(req.user!.sub)).features.focus_bar_creature) {+ return reply.callNotFound()+ }})app.get('/api/zoo', async (req, reply) => {diff --git a/backend/src/server.ts b/backend/src/server.tsindex a7d9e7005..e399542f0 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -14,6 +14,7 @@ import { harnessLinkRoutes } from './routes/harnessLinks.js'import { deskRoutes } from './routes/desk.js'import { tabChannelRoutes } from './routes/tabChannels.js'import { zooRoutes } from './routes/zoo.js'+import { experimentalSettingsRoutes } from './routes/experimentalSettings.js'import { describeDaemonsSwitch } from './lib/daemonsSwitch.js'import { handleObserverUpgrade } from './lib/observerWs.js'import { deviceAuthRoutes } from './routes/deviceAuth.js'@@ -171,9 +172,9 @@ async function start(): Promise<void> {await app.register(harnessLinkRoutes)await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)if (env.HARNESS_CHANNELS) await app.register(tabChannelRoutes)- // The account's daemons and eggs, the same on every client (lib/zoo.ts). Dark unless HARNESS_DAEMONS is- // on (lib/daemonsSwitch.ts): off, nothing is registered and /api/zoo answers the ordinary 404.- await app.register(zooRoutes, { daemons: DAEMONS })+ await app.register(experimentalSettingsRoutes, { daemons: DAEMONS })+ // Availability is separate from opt-in: every account starts off, and its collection is retained.+ await app.register(zooRoutes, { daemons: DAEMONS, requireAccountOptIn: true })logger.info(describeDaemonsSwitch(DAEMONS))// Dedicated public subdomain app-proxy on its own port (Host-header routed → tunnelled to the node app).diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ff2992038..465da48b6 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -4266,9 +4266,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// route and hears about everyone else's edits as `desk_changed` (backendSocket.ts).onDeskRead: () => proxyBackend('GET', '/api/desk'),onDeskOps: (body) => proxyBackend('POST', '/api/desk/ops', body),+ onExperimentalRead: () => proxyBackend('GET', '/api/experimental-settings'),+ onExperimentalWrite: (body) => proxyBackend('PATCH', '/api/experimental-settings', body),// The account's zoo — see backend routes/zoo.ts. Same shape as the desk: read and ops proxied,- // everyone else's changes heard as `zoo_changed`. Signed out, proxyBackend answers 401 NOT_SIGNED_IN- // and a guest keeps its zoo locally until it seeds this one.+ // everyone else's changes heard as `zoo_changed`. The backend requires the account's creature+ // opt-in. Signed out, proxyBackend answers 401 NOT_SIGNED_IN.// Killed on this computer (lib/daemonsSwitch.ts): a 404 DAEMONS_OFF without asking, which a window reads// exactly as the server's own 404 — daemons hidden. Otherwise verbatim, and the switch learns from it.onZooRead: () => zooProxy.read(),diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex de8ecc5e2..dd312ab16 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -254,6 +254,22 @@ describe('the desk proxy', () => {})})+describe('account Experimental settings proxy', () => {+ it('reads through the account proxy and guards writes with the local header', async () => {+ const snapshot = { accountId: 'owner', revision: 0, features: { focus_bar_creature: false, share_button: false } }+ const write = vi.fn(async (body: unknown) => ({ status: 200, body: { success: true, data: { ...snapshot, echo: body } } }))+ const { base } = await start({ onExperimentalRead: async () => ({ status: 200, body: { success: true, data: snapshot } }), onExperimentalWrite: write })+ expect((await (await fetch(`${base}/api/experimental-settings`)).json())).toEqual({ success: true, data: snapshot })+ const body = { accountId: 'owner', feature: 'share_button', enabled: true }+ expect((await fetch(`${base}/api/experimental-settings`, { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })).status).toBe(403)+ expect(write).not.toHaveBeenCalled()+ const saved = await fetch(`${base}/api/experimental-settings`, { method: 'PATCH', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: JSON.stringify(body) })+ expect(saved.status).toBe(200)+ expect(write).toHaveBeenCalledExactlyOnceWith(body)+ expect((await fetch(`${base}/api/experimental-settings`, { method: 'PATCH', headers: { 'x-adapter-local': '1' }, body: '{bad' })).status).toBe(400)+ })+})+describe('the zoo proxy', () => {it('reads the zoo ungated and writes its ops only with the local header, body passed through', async () => {const zoo = { daemons: [], eggs: [], pair: null, habits: [], firstEgg: false, pity: 0, easter: [] }diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 55519f762..eb0c61447 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -140,6 +140,9 @@ export interface HookServerHandlers {/** POST /api/desk/ops — the window's tab edits, applied on the backend (its routes/desk.ts); a* local write, so CSRF-guarded like a rename. */onDeskOps?: (body: unknown) => Promise<PairOutcome>+ /** The account's Experimental switches, proxied with the daemon's own identity. */+ onExperimentalRead?: () => Promise<PairOutcome>+ onExperimentalWrite?: (body: unknown) => Promise<PairOutcome>/** GET /api/zoo — the account's daemons and eggs (daemons/README.md); proxied like the desk. */onZooRead?: () => Promise<PairOutcome>/** POST /api/zoo/ops — habits, hatches, pair and nickname, applied on the backend (its routes/zoo.ts),@@ -722,6 +725,17 @@ export function startHookServer(try { body = JSON.parse(await readBody(req)) } catch { json(400, { error: { code: 'BAD_REQUEST', message: 'Invalid JSON body' } }); return }await proxied(() => handlers.onDeskOps!(body)); return}+ if (req.method === 'GET' && url === '/api/experimental-settings') {+ if (!handlers.onExperimentalRead) { json(503, { error: 'UNAVAILABLE' }); return }+ await proxied(handlers.onExperimentalRead); return+ }+ if (req.method === 'PATCH' && url === '/api/experimental-settings') {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onExperimentalWrite) { json(503, { error: 'UNAVAILABLE' }); return }+ let body: unknown+ try { body = JSON.parse(await readBody(req)) } catch { json(400, { error: { code: 'BAD_REQUEST', message: 'Invalid JSON body' } }); return }+ await proxied(() => handlers.onExperimentalWrite!(body)); return+ }if (req.method === 'GET' && url === '/api/zoo') {if (!handlers.onZooRead) { json(503, { error: 'UNAVAILABLE' }); return }await proxied(handlers.onZooRead); returndiff --git a/daemons/README.md b/daemons/README.mdindex 1efc4f4a4..fbe6f8330 100644--- a/daemons/README.md+++ b/daemons/README.md@@ -182,13 +182,25 @@ Silent by default.## Off switches-Every daemon deploy ships dark: until daemons are turned on, nothing here changes anything for anyone.--- **Server** (`backend/src/lib/daemonsSwitch.ts`). `HARNESS_DAEMONS` is off unless `true`. Off, the zoo+Every account starts with the creature off. **Settings → Experimental → Focus-bar creature** enables+it for that account on every supported desktop. Its eggs, creatures, names and progress live in the+account's zoo; closing a window or turning the switch off does not erase them. Signed-out windows+cannot enable it. The former window-only preview collection is not imported into an account.+Old installation-wide switch values are not imported either; opt in once for the signed-in account.+Deploy the backend settings routes and CLI proxy before the desktop update that reads them.++- **Account** (`backend/src/routes/experimentalSettings.ts`). `focus_bar_creature` defaults false.+ Without an explicit opt-in, both zoo routes return 404 before reading or writing the collection.+ `GET /api/experimental-settings` only reads; `PATCH` changes one switch and requires the authenticated+ account's id so a delayed save cannot change another account. Different switches can be changed by+ two clients without overwriting each other. Switch changes invalidate connected clients through+ `desk_changed`; a creature change also sends `zoo_changed` to wake or stop harnessd.+- **Server** (`backend/src/lib/daemonsSwitch.ts`). `HARNESS_DAEMONS` defaults `true`, making account+ opt-in available. Explicit false disables the module. Off, the zooroutes are not registered — `/api/zoo` and `/api/zoo/ops` answer the server's ordinary 404 — nothing- publishes `zoo_changed` and no socket subscribes to it. On, `HARNESS_DAEMONS_USERS` (comma-separated user- ids or emails; empty is everyone) limits the zoo to those accounts; any other gets the same 404 before- anything is read or written.+ writes the zoo and no socket subscribes to `zoo_changed`. On, `HARNESS_DAEMONS_USERS` (comma-separated+ user ids or emails; empty is everyone) limits which accounts may opt in; any other gets the same 404+ before its collection is read or written.- **harnessd** (`cli/src/lib/daemonsSwitch.ts`). Idle until `GET /api/zoo` answers 200: no `zoo.turn`reporter, no `zoo.lesson` credit, no PairSensor or journal, no brain, no learning (signals, distilling,usage, lessons in launches), no pair harness, no pair.jsonc tick — no timers, no files, no model warm-up,diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex fab5a0880..af3fa6c35 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -218,6 +218,14 @@ injection point (`main_local_manual.dart` overrides it). `bootstrap()` → `_pre`cliLogin.checkStatus()` → `_finishBootstrapSignedIn()` (restore pane layout, create `WsPool`, ensurethe daemon, `api.me()`, `refreshMachines()`).+Experimental switches are account state. `AppNotifier.experimentalFeatures` binds after `api.me()`+identifies the account, clears on sign-out/account change, and rejects stale responses. It uses+`/api/experimental-settings`, refreshes on account invalidations and a 30-second fallback poll, and+shows changes only after server acknowledgement. Do not restore the old unscoped local keys at startup.+Swarm collaboration keeps its existing account settings RPC. The creature switch opens the account's+`ZooController` collection; disabling it hides the creature without deleting eggs, individuals or progress.+Window-only preview collections are test/render fixtures, not a user setting.+Per-machine runtime state is `MachineState` (connection status, transport mode, agents, `nodeOnline`from `node_status` pushes — distinct from our own socket status, pending offline agent, turn activity).diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex f61ac5b5a..6b06e36da 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -141,11 +141,26 @@ class ApiClient {return unwrapApiResponse(res) as Map<String, dynamic>?;}- // -- the zoo: the account's daemons and eggs (daemons/README.md), proxied like the desk --+ // -- account-wide Experimental preferences --+ Future<Map<String, dynamic>> experimentalSettings() async {+ final res = await _dio.get('/api/experimental-settings');+ return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);+ }++ Future<Map<String, dynamic>> setExperimentalSetting(+ String accountId,+ String feature,+ bool enabled,+ ) async {+ final res = await _dio.patch(+ '/api/experimental-settings',+ data: {'accountId': accountId, 'feature': feature, 'enabled': enabled},+ options: Options(headers: {'x-adapter-local': '1'}),+ );+ return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);+ }- /// `{revision, zoo}`; null when daemons are off: a 404 (the server's switch, harnessd's- /// `DAEMONS_OFF`, or a harnessd that predates the zoo) or signed out (401). A 5xx throws: it- /// is not an answer (daemons/README.md, "Off switches").+ /// The account's collection; null when disabled or signed out. A failed read throws.Future<Map<String, dynamic>?> zoo() async {final res = await _dio.get('/api/zoo');if (res.statusCode == 404 || res.statusCode == 401) return null;diff --git a/desktop/lib/core/startup.dart b/desktop/lib/core/startup.dartindex bc29c287e..352cf9fdd 100644--- a/desktop/lib/core/startup.dart+++ b/desktop/lib/core/startup.dart@@ -4,7 +4,6 @@ import '../terminal/terminal_font_store.dart';import '../terminal/terminal_theme_store.dart';import '../notify/alert_sounds.dart';import '../notify/system_notifications.dart';-import '../settings/experimental_features.dart';/// Every preference that has to be in place BEFORE the first frame.///@@ -26,7 +25,6 @@ Future<void> loadPersistedSettings({AlertSoundStore? alertSounds,ScreenAlertStore? screenAlerts,DesktopNotificationStore? desktopNotifications,- ExperimentalFeaturesStore? experimentalFeatures,}) async {// Independent stores may load together, but all must finish before runApp.// Font and appearance share a serialized file store; each reads its related@@ -48,6 +46,5 @@ Future<void> loadPersistedSettings({(alertSounds ?? alertSoundStore).load(),(screenAlerts ?? screenAlertStore).load(),(desktopNotifications ?? desktopNotificationStore).load(),- (experimentalFeatures ?? experimentalFeaturesStore).load(),]);}diff --git a/desktop/lib/daemons/zoo_controller.dart b/desktop/lib/daemons/zoo_controller.dartindex 6831c7a12..0e62ce242 100644--- a/desktop/lib/daemons/zoo_controller.dart+++ b/desktop/lib/daemons/zoo_controller.dart@@ -13,8 +13,8 @@/// to ask) is [DaemonsSwitch.off]: nothing is shown, read, kept or sent, and/// the window behaves exactly as it did before daemons existed. A failed read/// is not an answer: whatever was known stands, and it is asked again. A-/// guest's durable local zoo stays off. Settings → Experimental opens a-/// separate, window-only preview with no account or persistence.+/// guest's durable local zoo stays off. Settings → Experimental opens the+/// account collection. The window-only preview is reserved for render fixtures.library;import 'dart:async';@@ -80,11 +80,11 @@ enum DaemonsSwitch {unknown,/// The server has no zoo for this account (404), harnessd is switched off- /// (`DAEMONS_OFF`), or a guest has not enabled the experimental preview. Everything- /// daemon-related stays hidden and silent.+ /// (`DAEMONS_OFF`), or the account has not opted in. Everything daemon-related+ /// stays hidden and silent.off,- /// `GET /api/zoo` answered 200, or the experimental local preview is on.+ /// `GET /api/zoo` answered 200, or a test fixture enabled a local collection.on,}@@ -280,7 +280,7 @@ class ZooController extends ChangeNotifier {if (scope != null && !_off) unawaited(_load(generation));}- /// The hidden focus-bar preview works even with the server feature off.+ /// A render fixture can preview a creature with the server feature off./// Keep its collection in this controller only, across hide/show, and never/// use the guest's persisted zoo (which can later be seeded to an account).void showPreview() => bind(_previewScope);@@ -394,7 +394,7 @@ class ZooController extends ChangeNotifier {Future<void> _fetch(int generation) async {final remote = _remote;- if (remote == null) return;+ if (remote == null || !_enabled || !_current(generation)) return;Map<String, dynamic>? raw;_fetching = true;try {diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 0e084d6f9..876c1353c 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -13,6 +13,7 @@ import 'package:xterm/xterm.dart' show TerminalTheme;import '../core/runtime_platform.dart';import '../analytics/analytics.dart';+import '../api/api_client.dart';import '../core/desktop_window.dart';import '../core/harness_file_store.dart';import '../core/project_folder.dart';@@ -229,11 +230,21 @@ class _SwarmScreenState extends State<SwarmScreen> {storage: kUnderTest ? null : HarnessFileStore.shared,now: widget.daemonClock,);- late final ZooTransport? _zooTransport =- widget.zooTransport ?? (kUnderTest ? null : ApiZooTransport(app.api));+ ApiClient? _zooApi;+ ZooTransport? _apiZooTransport;+ ZooTransport? get _zooTransport {+ if (widget.zooTransport != null) return widget.zooTransport;+ if (kUnderTest) return null;+ if (!identical(_zooApi, app.api)) {+ _zooApi = app.api;+ _apiZooTransport = ApiZooTransport(app.api);+ }+ return _apiZooTransport;+ }+late final _daemonSettings = DaemonSettings(storage: kUnderTest ? null : HarnessFileStore.shared,- canPersist: () => _daemonPreviewOverride == null,+ canPersist: () => !_zoo.isPreview,);late final _face = DaemonFace(_zoo,@@ -243,18 +254,16 @@ class _SwarmScreenState extends State<SwarmScreen> {late final ValueListenable<bool>? _daemonsPreview = widget.daemonsPreview;late final _experimentalFeatures =- widget.experimentalFeatures ?? experimentalFeaturesStore;+ widget.experimentalFeatures ?? app.experimentalFeatures;bool get _showShareButton =>_experimentalFeatures.enabled(ExperimentalFeature.shareButton);- /// An explicit local choice overrides the separate account rollout. This- /// stays null for installations that have never tried the test collection.- late bool? _daemonPreviewOverride = _creaturePreviewChoice;- bool? get _creaturePreviewChoice =>- ExperimentalFeature.focusBarCreature.available && app.viewer == null- ? _experimentalFeatures.choice(ExperimentalFeature.focusBarCreature)- : null;+ late bool _creatureEnabled = _creatureChoice;+ bool get _creatureChoice =>+ ExperimentalFeature.focusBarCreature.available &&+ app.viewer == null &&+ _experimentalFeatures.enabled(ExperimentalFeature.focusBarCreature);late final _brain = DaemonBrain(send: _sendDaemonFrame,storage: kUnderTest ? null : HarnessFileStore.shared,@@ -478,7 +487,6 @@ class _SwarmScreenState extends State<SwarmScreen> {_face.voiceLine.addListener(_voiceChanged);_daemonsPreview?.addListener(_syncDaemon);_experimentalFeatures.addListener(_experimentalFeaturesChanged);- if (_daemonPreviewOverride == true) _baselinePreviewTurns();app.agentPulse.addListener(_face.pulse);_face.dialogOpen = () =>_dialogOpen ||@@ -494,7 +502,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_face.plates = _plates;_brainSubscriptions.addAll([app.daemonFrames.listen((f) {- if (_daemonPreviewOverride != null) return;+ if (_zoo.isPreview || !_zoo.loaded) return;if (f.type == 'daemon_plate') {_plates.receive(f.type, f.payload);return;@@ -1087,19 +1095,11 @@ class _SwarmScreenState extends State<SwarmScreen> {}void _syncDaemon() {- if (_daemonPreviewOverride == true) {- _zoo.showPreview();- } else {- _zoo.bind(- _daemonPreviewOverride == false ? null : _accountScope,- remote: app.isGuest || _daemonPreviewOverride == false- ? null- : _zooTransport,- enabled:- _daemonPreviewOverride != false &&- (!app.isGuest || _daemonsPreview?.value == true),- );- }+ _zoo.bind(+ _accountScope,+ remote: app.isGuest ? null : _zooTransport,+ enabled: app.isGuest ? _daemonsPreview?.value == true : _creatureEnabled,+ );_zoo.recheckIfDue();final backendOnline = app.backendOnline;// A reconnect asks again, on or off.@@ -3225,18 +3225,15 @@ class _SwarmScreenState extends State<SwarmScreen> {/// A `daemon_*` or `pair` frame to this computer's harnessd, only while/// daemons are on here: off (or not decided yet), nothing is sent.bool _sendDaemonFrame(String type, Map<String, dynamic> payload) =>- _daemonPreviewOverride == null &&- _zoo.loaded &&- app.sendDaemonFrame(type, payload);+ !_zoo.isPreview && _zoo.loaded && app.sendDaemonFrame(type, payload);void _experimentalFeaturesChanged() {setState(() {});if (_native) _syncNative();- final choice = _creaturePreviewChoice;- if (_daemonPreviewOverride == choice) return;+ final choice = _creatureChoice;+ if (_creatureEnabled == choice) return;final hadOverlay = _daemonOverlay != null || _hatchOverlay != null;- _daemonPreviewOverride = choice;- _baselinePreviewTurns();+ _creatureEnabled = choice;_closeDaemonHint();_closeDaemon(restoreFocus: false);_closeHatch(restoreFocus: false);@@ -3248,18 +3245,6 @@ class _SwarmScreenState extends State<SwarmScreen> {if (hadOverlay && _routeIsCurrent && !_dialogOpen) _returnFocusToPane();}- void _baselinePreviewTurns() {- // Existing work is a baseline; only turns finishing during the preview- // should earn its eggs. No terminal focus or input changes on reveal.- _zooTurnsSeen- ..clear()- ..addEntries(- app.machineStates.values.map(- (machine) => MapEntry(machine.machine.machineId, machine.zooTurns),- ),- );- }-Map<String, Object?> get _daemonPayload {final theme = terminalThemeFor(grid.AppTheme.palette.value,diff --git a/desktop/lib/settings/experimental_features.dart b/desktop/lib/settings/experimental_features.dartindex d8c139646..e07863312 100644--- a/desktop/lib/settings/experimental_features.dart+++ b/desktop/lib/settings/experimental_features.dart@@ -1,17 +1,15 @@+import 'dart:async';+import 'package:flutter/foundation.dart';-import '../core/harness_file_store.dart';-import '../core/local_key_value_store.dart';+import '../api/api_client.dart';import '../core/viewer_mode.dart';-/// The catalog behind Settings → Experimental. Add new opt-in features here-/// so their labels, storage keys and switches stay together.enum ExperimentalFeature {focusBarCreature('focus_bar_creature','Focus-bar creature',- 'Start with an egg in the focus bar. Work toward hatching your companion. '- 'Its test collection resets when you close the window.',+ 'Start with an egg in the focus bar. Your collection and progress are saved to your account.',),shareButton('share_button',@@ -21,82 +19,173 @@ enum ExperimentalFeature {const ExperimentalFeature(this.id, this.label, this.description);final String id, label, description;-- String get storageKey => 'experimental.$id';-bool get available => switch (this) {- // The creature preview belongs to the native desktop workspace.focusBarCreature => !kIsWeb && !kViewerMode,shareButton => true,};}-/// Per-installation preferences, loaded before the first frame. Experiments are-/// off until chosen; neither an account nor a server can opt a user into one.-class ExperimentalFeaturesStore extends ChangeNotifier {- ExperimentalFeaturesStore({LocalKeyValueStore? storage})- : _storage = storage ?? HarnessFileStore.shared;+abstract interface class ExperimentalSettingsTransport {+ Future<Map<String, dynamic>> read();+ Future<Map<String, dynamic>> write(+ String accountId,+ ExperimentalFeature feature,+ bool enabled,+ );+}++class ApiExperimentalSettingsTransport+ implements ExperimentalSettingsTransport {+ ApiExperimentalSettingsTransport(this.api);+ final ApiClient api;+ @override+ Future<Map<String, dynamic>> read() => api.experimentalSettings();+ @override+ Future<Map<String, dynamic>> write(+ String accountId,+ ExperimentalFeature feature,+ bool enabled,+ ) => api.setExperimentalSetting(accountId, feature.id, enabled);+}- final LocalKeyValueStore _storage;+/// Account opt-ins. No installation-wide cache can enable another account's experiments.+/// Changes are displayed only after acknowledgement; reads never write or migrate local choices.+class ExperimentalFeaturesStore extends ChangeNotifier {+ ExperimentalFeaturesStore({this.pollInterval = const Duration(seconds: 30)});+ final Duration pollInterval;final _choices = <ExperimentalFeature, bool>{};- final _edits = <ExperimentalFeature, int>{};- Future<void>? _saving;- bool _disposed = false;+ final _available = <ExperimentalFeature, bool>{};+ ExperimentalSettingsTransport? _transport;+ String? accountId;+ int _generation = 0, _epoch = 0, _revision = -1;+ bool loaded = false, saving = false, _disposed = false;+ String? error;+ ExperimentalFeature? savingFeature, errorFeature;+ Future<void>? _reading;+ Timer? _poll;bool enabled(ExperimentalFeature feature) => choice(feature) == true;+ bool? choice(ExperimentalFeature feature) =>+ loaded ? _choices[feature] : null;+ bool isAvailable(ExperimentalFeature feature) => _available[feature] != false;+ bool get signedIn => accountId != null;++ void bind(String? account, {ExperimentalSettingsTransport? transport}) {+ if (_disposed || (accountId == account && _transport == transport)) return;+ ++_generation;+ ++_epoch;+ accountId = account;+ _transport = transport;+ loaded = saving = false;+ savingFeature = errorFeature = null;+ error = null;+ _revision = -1;+ _choices.clear();+ _available.clear();+ _reading = null;+ _poll?.cancel();+ _poll = null;+ _notify();+ if (account != null && transport != null) {+ unawaited(refresh());+ if (pollInterval > Duration.zero) {+ _poll = Timer.periodic(pollInterval, (_) => unawaited(refresh()));+ }+ }+ }- /// Null means no local choice. This lets the creature preserve the separate- /// account rollout until a person explicitly overrides it with this preview.- bool? choice(ExperimentalFeature feature) => _choices[feature];+ void _notify() {+ if (!_disposed) notifyListeners();+ }- Future<void> load() async {- final edits = Map.of(_edits);+ bool _current(int generation) => !_disposed && generation == _generation;++ Future<void> refresh() {+ if (_disposed || accountId == null || _transport == null || saving) {+ return Future.value();+ }+ final pending = _reading;+ if (pending != null) return pending;+ late final Future<void> reading;+ reading = _read(_generation, _epoch).whenComplete(() {+ if (identical(_reading, reading)) _reading = null;+ });+ return _reading = reading;+ }++ Future<void> _read(int generation, int epoch) async {try {- final values = await _storage.readMany(- ExperimentalFeature.values.map((feature) => feature.storageKey),- );- if (_disposed) return;- var changed = false;- for (final feature in ExperimentalFeature.values) {- if (_edits[feature] != edits[feature]) continue;- final value = switch (values[feature.storageKey]) {- 'on' => true,- 'off' => false,- _ => null,- };- if (choice(feature) == value) continue;- changed = true;- if (value == null) {- _choices.remove(feature);- } else {- _choices[feature] = value;- }- }- if (changed) notifyListeners();+ final result = await _transport!.read();+ if (!_current(generation) || epoch != _epoch) return;+ _apply(result);+ error = null;+ errorFeature = null;} catch (_) {- // Missing or unreadable preferences never opt someone into an experiment.+ if (!_current(generation) || epoch != _epoch) return;+ error = 'Couldn’t read your account settings. Refresh to try again.';}+ _notify();}- /// Apply immediately and serialize writes so the last flip wins. A failed- /// save is reported to the caller and does not poison later writes or retries.- Future<void> set(ExperimentalFeature feature, bool on) {- _edits[feature] = (_edits[feature] ?? 0) + 1;- final changed = choice(feature) != on;- _choices[feature] = on;- if (changed && !_disposed) notifyListeners();- final pending = (_saving ?? Future<void>.value()).then(- (_) => _storage.write(feature.storageKey, on ? 'on' : 'off'),- );- _saving = pending.then<void>((_) {}, onError: (Object _, StackTrace _) {});- return pending;+ void _apply(Map<String, dynamic> result) {+ final revision = result['revision'];+ final features = result['features'];+ final available = result['available'];+ if (result['accountId'] != accountId ||+ revision is! int ||+ revision < 0 ||+ features is! Map ||+ ExperimentalFeature.values.any(+ (feature) => features[feature.id] is! bool,+ )) {+ throw const FormatException('Invalid account settings');+ }+ if (revision < _revision) return;+ _revision = revision;+ for (final feature in ExperimentalFeature.values) {+ _choices[feature] = features[feature.id] as bool;+ _available[feature] = available is! Map || available[feature.id] != false;+ }+ loaded = true;+ }++ Future<void> set(ExperimentalFeature feature, bool on) async {+ if (_disposed ||+ !loaded ||+ saving ||+ accountId == null ||+ _transport == null) {+ return;+ }+ final generation = _generation;+ ++_epoch;+ saving = true;+ savingFeature = feature;+ error = null;+ errorFeature = null;+ _notify();+ try {+ final result = await _transport!.write(accountId!, feature, on);+ if (!_current(generation)) return;+ _apply(result);+ } catch (_) {+ if (!_current(generation)) return;+ error =+ 'Couldn’t confirm the change. Refresh to check your saved setting.';+ errorFeature = feature;+ } finally {+ if (_current(generation)) {+ saving = false;+ savingFeature = null;+ _notify();+ }+ }}@overridevoid dispose() {_disposed = true;+ _poll?.cancel();super.dispose();}}--final experimentalFeaturesStore = ExperimentalFeaturesStore();diff --git a/desktop/lib/settings/sections/experimental_section.dart b/desktop/lib/settings/sections/experimental_section.dartindex 78e349d67..c03bc7ec3 100644--- a/desktop/lib/settings/sections/experimental_section.dart+++ b/desktop/lib/settings/sections/experimental_section.dart@@ -21,44 +21,26 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {@overridevoid initState() {super.initState();+ unawaited((widget.store ?? _fallbackStore).refresh());final controller = widget.controller;if (controller != null) unawaited(controller.refresh());}- Future<void> _set(- BuildContext context,- ExperimentalFeaturesStore preferences,- ExperimentalFeature feature,- bool on,- ) async {- try {- await preferences.set(feature, on);- } catch (_) {- if (!context.mounted || preferences.enabled(feature) != on) return;- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(- content: const Text(- 'This change couldn’t be saved. It will last for this window.',- ),- action: SnackBarAction(- label: 'Retry',- onPressed: () => unawaited(- _set(context, preferences, feature, preferences.enabled(feature)),- ),- ),- ),- );- }+ final _fallbackStore = ExperimentalFeaturesStore();++ @override+ void dispose() {+ _fallbackStore.dispose();+ super.dispose();}@overrideWidget build(BuildContext context) {- final preferences = widget.store ?? experimentalFeaturesStore;+ final preferences = widget.store ?? _fallbackStore;final features = ExperimentalFeature.values.where((f) => f.available);return SectionScaffold(title: 'Experimental',- subtitle:- 'Try features that are still taking shape. Turn them off any time.',+ subtitle: 'Try features that are still taking shape. These settings sync across your account.',child: SingleChildScrollView(child: ListenableBuilder(listenable: Listenable.merge([preferences, widget.controller]),@@ -66,21 +48,67 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {crossAxisAlignment: CrossAxisAlignment.stretch,spacing: 10,children: [+ if (!preferences.loaded ||+ (preferences.error != null &&+ preferences.errorFeature == null))+ Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ preferences.error ??+ (preferences.signedIn+ ? 'Loading your account settings…'+ : 'Sign in to choose experiments for your account.'),+ ),+ if (preferences.error != null)+ TextButton(+ onPressed: () => unawaited(preferences.refresh()),+ child: const Text('Refresh settings'),+ ),+ ],+ ),for (final feature in features)- MergeSemantics(- child: SettingRow(- title: feature.label,- detail: feature.description,- control: Align(+ SettingRow(+ title: feature.label,+ detail: feature.description,+ control: Semantics(+ label: feature.label,+ child: Align(alignment: Alignment.centerLeft,child: Switch(key: ValueKey('experimental-${feature.id}'),value: preferences.enabled(feature),- onChanged: (on) =>- unawaited(_set(context, preferences, feature, on)),+ onChanged:+ preferences.loaded &&+ !preferences.saving &&+ (preferences.isAvailable(feature) ||+ preferences.enabled(feature))+ ? (on) => unawaited(preferences.set(feature, on))+ : null,),),),+ footer: preferences.savingFeature == feature+ ? Semantics(liveRegion: true, child: Text('Saving…'))+ : preferences.errorFeature == feature+ ? Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Semantics(+ liveRegion: true,+ child: Text(preferences.error!),+ ),+ TextButton(+ onPressed: () => unawaited(preferences.refresh()),+ child: const Text('Refresh setting'),+ ),+ ],+ )+ : preferences.loaded && !preferences.isAvailable(feature)+ ? const Text(+ 'This experiment is unavailable on this server.',+ )+ : null,),if (widget.controller case final controller?)_SwarmCollaborationSetting(controller: controller),@@ -108,7 +136,7 @@ class _SwarmCollaborationSetting extends StatelessWidget {title: 'Swarm collaboration',detail:'Let agents automatically consult only peers in the same tab. '- 'Off by default. This setting applies to your account.',+ 'Off by default.',control: Semantics(label: 'Swarm collaboration',child: Align(diff --git a/desktop/lib/settings/settings_screen.dart b/desktop/lib/settings/settings_screen.dartindex 67e7ab8de..390a2af15 100644--- a/desktop/lib/settings/settings_screen.dart+++ b/desktop/lib/settings/settings_screen.dart@@ -203,7 +203,7 @@ class _SettingsBody extends StatelessWidget {),SettingsSection.notifications => const NotificationsSection(),SettingsSection.experimental => ExperimentalSection(- store: experimentalFeatures,+ store: experimentalFeatures ?? notifier.experimentalFeatures,controller: notifier.swarmSettings,),SettingsSection.devices => const DevicesSection(),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 159b644d8..abc177948 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -47,6 +47,7 @@ import '../core/project_preview.dart';import '../core/repository_clone.dart';import '../core/retry.dart';import '../settings/config_store.dart';+import '../settings/experimental_features.dart';import '../stats/harness_stats.dart';import '../terminal/terminal_session.dart';import '../terminal/terminal_theme.dart';@@ -864,7 +865,35 @@ class AppNotifier extends ChangeNotifier {);AppStatus status = AppStatus.bootstrapping;- CurrentUserProfile? currentUser;+ CurrentUserProfile? _currentUser;+ CurrentUserProfile? get currentUser => _currentUser;+ set currentUser(CurrentUserProfile? profile) {+ _currentUser = profile;+ final id = profile?.id;+ experimentalFeatures.bind(+ id,+ transport: id == null ? null : _experimentTransport,+ );+ }++ final experimentalFeatures = ExperimentalFeaturesStore(+ pollInterval: kUnderTest ? Duration.zero : const Duration(seconds: 30),+ );+ final ExperimentalSettingsTransport? experimentalSettingsTransport;+ ApiClient? _experimentApi;+ ExperimentalSettingsTransport? _apiExperimentTransport;+ ExperimentalSettingsTransport? get _experimentTransport {+ if (experimentalSettingsTransport != null) {+ return experimentalSettingsTransport;+ }+ if (kUnderTest) return null;+ if (!identical(_experimentApi, api)) {+ _experimentApi = api;+ _apiExperimentTransport = ApiExperimentalSettingsTransport(api);+ }+ return _apiExperimentTransport;+ }+List<Machine> machines = [];final Map<String, MachineState> machineStates = {};final Set<String> expandedMachines = {};@@ -1913,6 +1942,7 @@ class AppNotifier extends ChangeNotifier {AgentAlerts? agentAlerts,AgentUnread? agentUnread,SystemNotifications? systemNotifications,+ this.experimentalSettingsTransport,}) : alerts = alerts ?? AlertSounds(store: alertSoundStore),agentAlerts = agentAlerts ?? AgentAlerts(),systemNotifications =@@ -3892,6 +3922,7 @@ class AppNotifier extends ChangeNotifier {/// Remove the old account's live objects without overwriting its saved desk./// In particular, multiple emptied tabs must not prevent the next restore.void _clearAccountWorkspace() {+ experimentalFeatures.bind(null);++_layoutRevision;// Sign-out sends the desk nothing: the tabs closing here are this window// leaving the account, not the person closing them.@@ -12558,6 +12589,8 @@ class AppNotifier extends ChangeNotifier {unawaited(_rereadMachinesInBackground(pushed: true));break;case 'desk_changed':+ unawaited(experimentalFeatures.refresh());+ if (_swarmSettings case final settings?) unawaited(settings.refresh());// Another window — on another computer, or this one — changed the// tabs. The payload is only the revision; the document is fetched.final deskRevision = payload['revision'];@@ -12980,6 +13013,7 @@ class AppNotifier extends ChangeNotifier {@overridevoid dispose() {+ experimentalFeatures.dispose();viewer?.auth.dispose();_deviceVisit?.dispose();_modelManager?.dispose();diff --git a/desktop/test/api_client_test.dart b/desktop/test/api_client_test.dartindex 77ee61ec7..7e5721f11 100644--- a/desktop/test/api_client_test.dart+++ b/desktop/test/api_client_test.dart@@ -8,6 +8,61 @@ import 'package:harness/core/config.dart';import 'package:flutter_test/flutter_test.dart';void main() {+ test(+ 'account experiment writes include identity and the local proxy header',+ () async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final seen = <(String, String, String?, String)>[];+ final snapshot = {+ 'accountId': 'account-a',+ 'revision': 1,+ 'features': {'focus_bar_creature': false, 'share_button': true},+ };+ final subscription = server.listen((request) async {+ seen.add((+ request.method,+ request.uri.path,+ request.headers.value('x-adapter-local'),+ await utf8.decoder.bind(request).join(),+ ));+ request.response+ ..headers.contentType = ContentType.json+ ..write(jsonEncode({'success': true, 'data': snapshot}));+ await request.response.close();+ });+ try {+ final api = ApiClient(+ config: AppConfig(+ apiBaseUrl: 'http://unused.invalid',+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',+ ),+ session: AuthSession(),+ );+ expect(await api.experimentalSettings(), snapshot);+ expect(+ await api.setExperimentalSetting('account-a', 'share_button', true),+ snapshot,+ );+ expect(seen, [+ ('GET', '/api/experimental-settings', null, ''),+ (+ 'PATCH',+ '/api/experimental-settings',+ '1',+ jsonEncode({+ 'accountId': 'account-a',+ 'feature': 'share_button',+ 'enabled': true,+ }),+ ),+ ]);+ } finally {+ await subscription.cancel();+ await server.close(force: true);+ }+ },+ );+test('machine request hits the local CLI proxy, not the backend, with no credential', () async {final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);final paths = <String>[];diff --git a/desktop/test/benchmarks/startup_benchmark.dart b/desktop/test/benchmarks/startup_benchmark.dartindex 9262c896e..29c7472af 100644--- a/desktop/test/benchmarks/startup_benchmark.dart+++ b/desktop/test/benchmarks/startup_benchmark.dart@@ -9,7 +9,6 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/harness_file_store.dart';import 'package:harness/core/snapshot_store.dart';import 'package:harness/core/startup.dart';-import 'package:harness/settings/experimental_features.dart';import 'package:harness/notify/alert_sounds.dart';import 'package:harness/notify/system_notifications.dart';import 'package:harness/shared/theme/appearance_prefs_store.dart';@@ -67,7 +66,6 @@ void main() {final scheme = TerminalThemeStore(storage: storage);final appearance = AppearancePrefsStore(storage: storage);final stats = HarnessStats(store: statsStore);- final experiments = ExperimentalFeaturesStore(storage: storage);final keymapStore = KeymapStore(file: keymapFile,defaults: harnessDefaultBindings,@@ -87,7 +85,6 @@ void main() {alertSounds: AlertSoundStore(storage: storage),screenAlerts: ScreenAlertStore(storage: storage),desktopNotifications: DesktopNotificationStore(storage: storage),- experimentalFeatures: experiments,),if (withKeymap) keymap.start(),]);@@ -107,7 +104,6 @@ void main() {keymap.dispose();keymapStore.dispose();stats.dispose();- experiments.dispose();font.dispose();scheme.dispose();appearance.dispose();diff --git a/desktop/test/daemon_off_test.dart b/desktop/test/daemon_off_test.dartindex a39ff06e8..10bc979f7 100644--- a/desktop/test/daemon_off_test.dart+++ b/desktop/test/daemon_off_test.dart@@ -29,6 +29,8 @@ import 'package:harness/state/swarm_catalog.dart' show SwarmProjectStore;import 'package:harness/state/workspace_onboarding.dart';import 'package:harness/ws/local_cli_discovery.dart';+import 'support/experimental_settings.dart';+import 'daemons/zoo_test.dart' show FakeZooTransport;import 'keymap_host_test.dart' show key;import 'support/status_bar_layout.dart';@@ -72,7 +74,7 @@ void main() {};preview = ValueNotifier(false);preferences = MemoryStore();- experiments = ExperimentalFeaturesStore(storage: preferences);+ experiments = MemoryExperimentalFeaturesStore(storage: preferences);});tearDown(() {app.dispose();@@ -84,15 +86,22 @@ void main() {Future<void> mount(WidgetTester tester, {bool on = false,+ bool? enabled = true,+ FakeZooTransport? server,Zoo? seed,bool native = false,Completer<void>? gate,WorkspaceOnboarding? onboarding,}) async {- remote = FakeZooTransport(available: on)- ..zoo = seed ?? _tim- ..revision = 1- ..gate = gate;+ if (enabled != null) {+ await experiments.set(ExperimentalFeature.focusBarCreature, enabled);+ }+ remote =+ server ??+ (FakeZooTransport(available: on)+ ..zoo = seed ?? _tim+ ..revision = 1+ ..gate = gate);zoo = ZooController(random: Random(1));addTearDown(zoo.dispose);tester.view.devicePixelRatio = 1;@@ -142,7 +151,7 @@ void main() {const ValueKey('experimental-focus_bar_creature'),);- Future<void> setPreview(WidgetTester tester, bool on) async {+ Future<void> setCreature(WidgetTester tester, bool on) async {await experiments.set(feature, on);await tester.pump(const Duration(seconds: 1));}@@ -162,31 +171,33 @@ void main() {testWidgets('Settings switches the creature on and off without leaving Settings',(tester) async {- await mount(tester);+ await mount(tester, on: true, enabled: false, seed: Zoo.empty);expect(slot, findsNothing);+ expect(remote.fetches, 0);final tab = app.activeSwarmId;await openExperimental(tester);expect(tester.widget<Switch>(experimentSwitch).value, isFalse);await tester.tap(experimentSwitch);await tester.pump(const Duration(seconds: 1));expect(tester.widget<Switch>(experimentSwitch).value, isTrue);- expect(zoo.isPreview, isTrue);+ expect(zoo.isAccount, isTrue);expect(zoo.paired, isNull);expect(zoo.zoo.daemons, isEmpty);expect(zoo.readyEgg, isNull);expect(find.byType(SettingsScreen), findsOneWidget);expect(app.activeSwarmId, tab);- expect(frames, isEmpty);- expect(remote.batches, isEmpty);+ expect(+ remote.batches+ .expand((batch) => batch)+ .where((op) => op['op'] == 'zoo.turn'),+ isEmpty,+ );await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump(const Duration(seconds: 1));expect(slot, findsOneWidget);await tester.tap(slot);await tester.pump();- expect(- find.byKey(const ValueKey('daemon-preview-label')),- findsOneWidget,- );+ expect(find.byKey(const ValueKey('daemon-preview-label')), findsNothing);await openExperimental(tester);await tester.tap(experimentSwitch);await tester.pump();@@ -197,16 +208,16 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();expect(slot, findsNothing);- expect(preferences.values[feature.storageKey], 'off');+ expect(preferences.values[experimentFixtureKey(feature)], 'off');await unmount(tester);},);testWidgets(- 'the experimental egg earns its first hatch from workspace activity',+ 'the account egg earns and saves its first hatch from workspace activity',(tester) async {- await mount(tester);- await setPreview(tester, true);+ await mount(tester, on: true, enabled: false, seed: Zoo.empty);+ await setCreature(tester, true);String glyph() => tester.widget<Text>(find.byKey(const ValueKey('daemon-slot-glyph'))).data!@@ -253,63 +264,67 @@ void main() {await tester.tap(saveName);await tester.pump();expect(zoo.paired!.name, 'Pip');- expect(find.byKey(const ValueKey('daemon-hatch-next')), findsNothing);- expect(frames, isEmpty);- expect(remote.batches, isEmpty);+ expect(zoo.isAccount, isTrue);+ expect(+ remote.batches+ .expand((batch) => batch)+ .where((op) => op['op'] == 'zoo.turn'),+ isEmpty,+ );expect(tester.takeException(), isNull);await unmount(tester);},);testWidgets(- 'the saved switch survives a new window but the test collection does not',+ 'the account collection and its name survive a new window and off/on',(tester) async {- await mount(tester);- await setPreview(tester, true);+ await mount(tester, on: true, seed: Zoo.empty);for (final habit in ['turn', 'split', 'find']) {zoo.habit(habit);}+ await zoo.flush();final hatch = (await zoo.hatch(zoo.readyEgg!.id))!;expect(zoo.nickname(hatch.uid!, 'Window one'), isTrue);- await tester.pump();- expect(zoo.paired!.name, 'Window one');+ await zoo.flush();+ final saved = remote;await unmount(tester);experiments.dispose();- experiments = ExperimentalFeaturesStore(storage: preferences);- await experiments.load();- await mount(tester);+ experiments = MemoryExperimentalFeaturesStore(storage: preferences);+ await experiments.refresh();+ await mount(tester, server: saved, enabled: null);await tester.pump(const Duration(seconds: 1));expect(slot, findsOneWidget);- expect(zoo.isPreview, isTrue);- expect(zoo.paired, isNull);- expect(zoo.zoo.daemons, isEmpty);- expect(zoo.readyEgg, isNull);- await setPreview(tester, false);+ expect(zoo.isAccount, isTrue);+ expect(zoo.paired!.name, 'Window one');+ expect(zoo.paired!.uid, hatch.uid);+ await setCreature(tester, false);+ expect(slot, findsNothing);+ await setCreature(tester, true);+ expect(zoo.paired!.name, 'Window one');+ await setCreature(tester, false);await unmount(tester);experiments.dispose();- experiments = ExperimentalFeaturesStore(storage: preferences);- await experiments.load();- await mount(tester, on: true);- await tester.pump(const Duration(seconds: 1));- expect(- slot,- findsNothing,- reason: 'saved off also overrides the account rollout',- );- expect(remote.fetches, 0);+ experiments = MemoryExperimentalFeaturesStore(storage: preferences);+ await experiments.refresh();+ final fetches = saved.fetches;+ await mount(tester, server: saved, enabled: null);+ expect(slot, findsNothing);+ expect(saved.fetches, fetches);+ expect(saved.zoo.paired!.name, 'Window one');await unmount(tester);},);- testWidgets('preview stays hidden after account pushes and reconnects', (+ testWidgets('account opt-out stays hidden after pushes and reconnects', (tester,) async {await mount(tester, on: true);await tester.pump();expect(slot, findsOneWidget);- await setPreview(tester, true);- expect(zoo.isPreview, isTrue);- await setPreview(tester, false);+ await setCreature(tester, true);+ expect(zoo.isAccount, isTrue);+ await setCreature(tester, false);final fetches = remote.fetches;zoo.pushed(999);zoo.refresh();@@ -324,16 +339,17 @@ void main() {testWidgets('disabling the experiment also closes an egg reveal', (tester,) async {- await mount(tester);- await setPreview(tester, true);+ await mount(tester, on: true, enabled: false, seed: Zoo.empty);+ await setCreature(tester, true);for (final habit in ['turn', 'split', 'find']) {zoo.habit(habit);}+ await zoo.flush();await tester.pump();await tester.tap(slot);await tester.pump();expect(find.byKey(const ValueKey('daemon-hatch')), findsOneWidget);- await setPreview(tester, false);+ await setCreature(tester, false);expect(slot, findsNothing);expect(find.byKey(const ValueKey('daemon-panel')), findsNothing);await tester.pump(const Duration(seconds: 15));@@ -343,48 +359,58 @@ void main() {reason: 'a late animation cannot reveal it again',);expect(tester.takeException(), isNull);- expect(frames, isEmpty);- expect(remote.batches, isEmpty);- await unmount(tester);- });-- testWidgets('guest preview needs no sign-in and has no activation shortcut', (- tester,- ) async {- app.signedIn = false;- await mount(tester);- expect(slot, findsNothing);- await key(- tester,- LogicalKeyboardKey.keyD,- cmd: true,- alt: true,- shift: true,- );- expect(slot, findsNothing, reason: 'the removed shortcut does nothing');- await setPreview(tester, true);- expect(slot, findsOneWidget);- expect(remote.fetches, 0);- final context = tester.element(find.byType(SwarmScreen));expect(- effectiveShortcutRows(- context,- KeymapContext.workspace,- ).map((r) => r.label),- isNot(contains('Toggle creature preview')),+ remote.batches+ .expand((batch) => batch)+ .where((op) => op['op'] == 'zoo.turn'),+ isEmpty,);- await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);- await tester.enterText(- find.byKey(const ValueKey('swarm-search-input')),- '>creature preview',- );- await tester.pump(const Duration(milliseconds: 100));- expect(find.text('Toggle creature preview'), findsNothing);- expect(remote.batches, isEmpty);- expect(frames, isEmpty);await unmount(tester);});+ testWidgets(+ 'guests cannot enable account experiments or use an activation shortcut',+ (tester) async {+ app.signedIn = false;+ experiments.bind(null);+ await mount(tester, enabled: null);+ expect(slot, findsNothing);+ await key(+ tester,+ LogicalKeyboardKey.keyD,+ cmd: true,+ alt: true,+ shift: true,+ );+ expect(slot, findsNothing, reason: 'the removed shortcut does nothing');+ await setCreature(tester, true);+ expect(slot, findsNothing);+ expect(remote.fetches, 0);+ final context = tester.element(find.byType(SwarmScreen));+ expect(+ effectiveShortcutRows(+ context,+ KeymapContext.workspace,+ ).map((r) => r.label),+ isNot(contains('Toggle creature preview')),+ );+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);+ await tester.enterText(+ find.byKey(const ValueKey('swarm-search-input')),+ '>creature preview',+ );+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.text('Toggle creature preview'), findsNothing);+ expect(+ remote.batches+ .expand((batch) => batch)+ .where((op) => op['op'] == 'zoo.turn'),+ isEmpty,+ );+ await unmount(tester);+ },+ );+testWidgets('the experiment updates the native focus bar without a shortcut',(tester) async {@@ -402,27 +428,37 @@ void main() {null,),);- await mount(tester, native: true);+ await mount(+ tester,+ on: true,+ enabled: false,+ seed: Zoo.empty,+ native: true,+ );final keymap = calls.lastWhere((c) => c.method == 'keymapState');expect(jsonEncode(keymap.arguments),isNot(contains('app.daemon_preview')),);- await setPreview(tester, true);+ await setCreature(tester, true);expect(zoo.paired, isNull);final updates = calls.where((c) => c.method == 'update');final daemon = (updates.last.arguments as Map)['daemon'] as Map;expect(daemon['visible'], isTrue);expect(daemon['glyph'], r'\_( )_/');expect(daemon['label'], 'Egg');- expect(daemon['tooltip'], contains('Settings → Experimental'));- await setPreview(tester, false);+ expect(daemon['tooltip'], isNot(contains('Local preview')));+ await setCreature(tester, false);expect(zoo.loaded, isFalse);expect(calls.lastWhere((c) => c.method == 'daemonState').arguments, {'visible': false,});- expect(frames, isEmpty);- expect(remote.batches, isEmpty);+ expect(+ remote.batches+ .expand((batch) => batch)+ .where((op) => op['op'] == 'zoo.turn'),+ isEmpty,+ );await unmount(tester);},);diff --git a/desktop/test/daemon_review_render_test.dart b/desktop/test/daemon_review_render_test.dartindex 6bf2e4333..ea84bb9bc 100644--- a/desktop/test/daemon_review_render_test.dart+++ b/desktop/test/daemon_review_render_test.dart@@ -23,12 +23,14 @@ import 'package:harness/daemons/render.dart';import 'package:harness/daemons/roster.dart';import 'package:harness/daemons/zoo.dart';import 'package:harness/daemons/zoo_controller.dart';-import 'package:harness/core/models.dart' show CurrentUserProfile, ConnectionStatus;+import 'package:harness/core/models.dart'+ show CurrentUserProfile, ConnectionStatus;import 'package:harness/core/agent_git_context.dart';import 'package:harness/shared/theme/appearance_prefs_store.dart';import 'package:harness/shared/theme/prompt_style.dart';import 'package:harness/shared/theme/status_line_style.dart';import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/settings/experimental_features.dart';import 'package:harness/state/swarm_catalog.dart' show SwarmProjectStore;import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/shared/theme/workspace_bar_style.dart';@@ -41,7 +43,7 @@ import 'package:harness/widgets/daemon_slot.dart';import 'package:xterm/xterm.dart' show TerminalStyle, TerminalTheme;import 'daemons/zoo_test.dart' show FakeZooTransport;-import 'package:harness/settings/experimental_features.dart';+import 'support/experimental_settings.dart';import 'support/real_fonts.dart';import 'support/status_bar_layout.dart' show seedStatusBarWorkspace;import 'swarm_state_test.dart' show MemoryStore, createApp;@@ -990,8 +992,11 @@ void main() {);expect(find.text('api@office Bash: npm test'), findsOneWidget);expect(find.byKey(const ValueKey('daemon-answer-y')), findsWidgets);- expect(find.text('3 done'), findsNothing,- reason: 'finished turns affect the face without adding a bar count');+ expect(+ find.text('3 done'),+ findsNothing,+ reason: 'finished turns affect the face without adding a bar count',+ );await tester.pumpWidget(const SizedBox());for (final (_, face) in rows) {face.sync(const DaemonWatch());@@ -1945,19 +1950,26 @@ void main() {}for (final width in [640.0, 1280.0]) {- testWidgets('experimental creature preview panel at ${width.toInt()}', (tester) async {+ testWidgets('experimental account creature panel at ${width.toInt()}', (+ tester,+ ) async {final app = createApp();addTearDown(app.dispose);seedStatusBarWorkspace(app);- app.currentUser = const CurrentUserProfile(id: 'preview', email: '[email protected]');+ app.currentUser = const CurrentUserProfile(+ id: 'preview',+ email: '[email protected]',+ );final zoo = ZooController();addTearDown(zoo.dispose);- final remote = FakeZooTransport(available: false);- final experiments = ExperimentalFeaturesStore(storage: MemoryStore());+ final remote = FakeZooTransport();+ final experiments = MemoryExperimentalFeaturesStore(+ storage: MemoryStore(),+ );addTearDown(experiments.dispose);await _capture(tester,- 'experimental-preview-panel-${width.toInt()}',+ 'experimental-account-panel-${width.toInt()}',Size(width, 620),(context) => SwarmScreen(notifier: app,@@ -1976,23 +1988,36 @@ void main() {await tester.pump();},);- expect(find.byKey(const ValueKey('daemon-preview-label')), findsOneWidget);- expect(remote.batches, isEmpty);+ expect(find.byKey(const ValueKey('daemon-preview-label')), findsNothing);+ expect(zoo.isAccount, isTrue);await tester.pumpWidget(const SizedBox());await tester.pump(const Duration(seconds: 11));});}- for (final (native, width) in [(false, 640.0), (false, 1280.0), (true, 1280.0)]) {- testWidgets('creature alone beside Git at $width native=$native', (tester) async {+ for (final (native, width) in [+ (false, 640.0),+ (false, 1280.0),+ (true, 1280.0),+ ]) {+ testWidgets('creature alone beside Git at $width native=$native', (+ tester,+ ) async {final appearance = appearancePrefsStore.value;appearancePrefsStore.value = appearance.copyWith(- prompt: const PromptPrefs(statusStyle: StatusLineStyle.powerlevel10kRainbow),+ prompt: const PromptPrefs(+ statusStyle: StatusLineStyle.powerlevel10kRainbow,+ ),);addTearDown(() => appearancePrefsStore.value = appearance);final app = createApp();addTearDown(app.dispose);seedStatusBarWorkspace(app);+ final experiments = MemoryExperimentalFeaturesStore(+ storage: MemoryStore(),+ );+ addTearDown(experiments.dispose);+ await experiments.set(ExperimentalFeature.focusBarCreature, true);final git = gitFixture(branch: 'continue-daemons');final project = git['current'] as Map<String, dynamic>;git['state'] = 'multiple';@@ -2000,7 +2025,12 @@ void main() {git['checkouts'] = [project,for (var i = 0; i < 3; i++)- {...project, 'cwd': '/fixture-$i', 'root': '/fixture-$i', 'branch': 'work-$i'},+ {+ ...project,+ 'cwd': '/fixture-$i',+ 'root': '/fixture-$i',+ 'branch': 'work-$i',+ },];git['recentWork'] = {'project': project, 'at': '2026-09-27T13:00:00Z'};final machine = app.stateOf('m')!;@@ -2013,21 +2043,32 @@ void main() {final zoo = ZooController(storage: _Memory());addTearDown(zoo.dispose);final remote = FakeZooTransport()- ..zoo = _paired('gnu', version: '0.1', eggs: const [- ZooEgg(id: 'one', kind: 'turn', grantedAt: ''),- ZooEgg(id: 'two', kind: 'week', grantedAt: ''),- ]);+ ..zoo = _paired(+ 'gnu',+ version: '0.1',+ eggs: const [+ ZooEgg(id: 'one', kind: 'turn', grantedAt: ''),+ ZooEgg(id: 'two', kind: 'week', grantedAt: ''),+ ],+ );const channel = MethodChannel('harness/swarm_tabs');Map<String, dynamic>? state;- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async {- if (call.method == 'update') state = Map<String, dynamic>.from(call.arguments as Map);+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (+ call,+ ) async {+ if (call.method == 'update') {+ state = Map<String, dynamic>.from(call.arguments as Map);+ }if (call.method == 'daemonState') state?['daemon'] = call.arguments;return null;});addTearDown(() async {await tester.pumpWidget(const SizedBox());await tester.pump();- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ );});await _capture(tester,@@ -2039,12 +2080,16 @@ void main() {projectStore: SwarmProjectStore(),zoo: zoo,zooTransport: remote,+ experimentalFeatures: experiments,daemonClock: () => tester.binding.clock.now(),),act: () async {app.notifyListeners();await tester.pump();- await app.handleMachineEventForTest('m', {'type': 'turn_ended', 'agentId': 'a0'});+ await app.handleMachineEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ });await tester.pump(const Duration(milliseconds: 3100));},);@@ -2055,16 +2100,25 @@ void main() {expect(daemon.containsKey('tallyCells'), isFalse);if (_output case final output?) {await tester.runAsync(() async {- await File('$output/creature-only-native.json').writeAsString(jsonEncode(state));- await File('$output/catalog.json').writeAsString(jsonEncode([- {'id': 'creature-only-native', 'label': 'Git branches | creature'},- ]));+ await File('$output/creature-only-native.json')+ .writeAsString(jsonEncode(state));+ await File('$output/catalog.json').writeAsString(+ jsonEncode([+ {+ 'id': 'creature-only-native',+ 'label': 'Git branches | creature',+ },+ ]),+ );});}} else {final slot = find.byKey(const ValueKey('daemon-slot'));final cell = workspaceBarCellSizeOf(tester.element(slot));- expect(find.descendant(of: slot, matching: find.byType(Text)), findsOneWidget);+ expect(+ find.descendant(of: slot, matching: find.byType(Text)),+ findsOneWidget,+ );expect(tester.getRect(slot).width, cell.width * 10);expect(tester.getRect(slot).right, lessThanOrEqualTo(width));}@@ -2101,6 +2155,13 @@ void main() {..revision = 1;final switchOn = ValueNotifier(preview);addTearDown(switchOn.dispose);+ final experiments = MemoryExperimentalFeaturesStore(+ storage: MemoryStore(),+ );+ addTearDown(experiments.dispose);+ if (!guest) {+ await experiments.set(ExperimentalFeature.focusBarCreature, true);+ }await _capture(tester,'workspace-bar-$name-${width.toInt()}',@@ -2112,6 +2173,7 @@ void main() {zoo: zoo,zooTransport: remote,daemonsPreview: switchOn,+ experimentalFeatures: experiments,),settle: const Duration(milliseconds: 200),);diff --git a/desktop/test/daemon_workspace_test.dart b/desktop/test/daemon_workspace_test.dartindex 3bd720334..cc0ca6104 100644--- a/desktop/test/daemon_workspace_test.dart+++ b/desktop/test/daemon_workspace_test.dart@@ -13,15 +13,17 @@ import 'package:harness/daemons/roster.dart';import 'package:harness/daemons/zoo.dart';import 'package:harness/daemons/zoo_controller.dart';import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/settings/experimental_features.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';import 'package:harness/ws/local_cli_discovery.dart';import 'package:harness/state/swarm_catalog.dart' show SwarmProjectStore;+import 'support/experimental_settings.dart';import 'daemons/zoo_test.dart' show FakeZooTransport;import 'keymap_host_test.dart' show key;import 'swarm_screen_test.dart' show terminal;-import 'swarm_state_test.dart' show createApp;+import 'swarm_state_test.dart' show createApp, MemoryStore;const _habits5 = ['turn', 'split', 'find', 'machine', 'store'];@@ -58,6 +60,9 @@ void main() {// Daemons (preview). The off cases are in daemon_off_test.dart.bool guestPreview = true,}) async {+ final experiments = MemoryExperimentalFeaturesStore(storage: MemoryStore());+ addTearDown(experiments.dispose);+ await experiments.set(ExperimentalFeature.focusBarCreature, true);remote = FakeZooTransport()..zoo = seed..revision = 1@@ -80,6 +85,7 @@ void main() {notifier: app,nativeTabs: native,projectStore: SwarmProjectStore(),+ experimentalFeatures: experiments,zoo: zoo,zooTransport: remote,daemonClock: () => tester.binding.clock.now(),@@ -792,10 +798,16 @@ void main() {await tester.pump();final focused = app.focusedPane!.agentId;expect(focused, isNotNull);- expect(tester.getRect(slot), beforeTurns,- reason: 'finished turns do not take more focus-bar space');- expect(find.descendant(of: slot, matching: find.byType(Text)), findsOneWidget,- reason: 'only the creature is drawn, without labels or counts');+ expect(+ tester.getRect(slot),+ beforeTurns,+ reason: 'finished turns do not take more focus-bar space',+ );+ expect(+ find.descendant(of: slot, matching: find.byType(Text)),+ findsOneWidget,+ reason: 'only the creature is drawn, without labels or counts',+ );expect(find.byKey(const ValueKey('daemon-voice')), findsNothing);final glyphTarget = find.byKey(const ValueKey('daemon-slot-glyph'));final beforeHover = tester.getRect(glyphTarget);@@ -805,14 +817,20 @@ void main() {await mouse.moveTo(beforeHover.center);await tester.pump();expect(find.byKey(const ValueKey('daemon-slot-tally')), findsNothing);- expect(tester.getRect(glyphTarget), beforeHover,- reason: 'hover must not move the creature away from the click');+ expect(+ tester.getRect(glyphTarget),+ beforeHover,+ reason: 'hover must not move the creature away from the click',+ );await tester.tapAt(beforeHover.center);await tester.pump();await mouse.moveTo(Offset.zero);await tester.pump();- expect(tester.getRect(glyphTarget), beforeHover,- reason: 'leaving the creature keeps the same fixed slot');+ expect(+ tester.getRect(glyphTarget),+ beforeHover,+ reason: 'leaving the creature keeps the same fixed slot',+ );expect(find.byKey(const ValueKey('daemon-slot-tally')), findsNothing);// The switches are on the settings tab: 4.await key(tester, LogicalKeyboardKey.digit4);@@ -896,8 +914,11 @@ void main() {),);await tester.pump();- expect(find.descendant(of: slot, matching: find.byType(Text)), findsOneWidget,- reason: 'additional eggs wait in the panel, without a bar count');+ expect(+ find.descendant(of: slot, matching: find.byType(Text)),+ findsOneWidget,+ reason: 'additional eggs wait in the panel, without a bar count',+ );await tester.tap(slot);await tester.pump();await tester.tap(find.byKey(const ValueKey('daemon-egg:turn')));@@ -915,7 +936,9 @@ void main() {await unmount(tester);});- testWidgets('native hears only the ten cells, without count labels', (tester) async {+ testWidgets('native hears only the ten cells, without count labels', (+ tester,+ ) async {final states = <Map>[];const channel = MethodChannel('harness/swarm_tabs');tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (@@ -1245,8 +1268,11 @@ void main() {],),);- expect(find.descendant(of: slot, matching: find.byType(Text)), findsOneWidget,- reason: 'remote completions do not add a focus-bar count');+ expect(+ find.descendant(of: slot, matching: find.byType(Text)),+ findsOneWidget,+ reason: 'remote completions do not add a focus-bar count',+ );expect(glyph(tester), '(o o)', reason: 'asleep is never a failure');// It acted within rules: drawn like done.await frame(tester, 'daemon_say', {diff --git a/desktop/test/experimental_features_test.dart b/desktop/test/experimental_features_test.dartindex 1014d25a2..1d633667d 100644--- a/desktop/test/experimental_features_test.dart+++ b/desktop/test/experimental_features_test.dart@@ -1,107 +1,244 @@import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';import 'package:harness/settings/experimental_features.dart';+import 'package:harness/settings/sections/experimental_section.dart';+import 'package:harness/state/app_state.dart';-import 'swarm_state_test.dart' show MemoryStore;--class _DelayedRead extends MemoryStore implements BatchLocalKeyValueStore {- final ready = Completer<Map<String, String?>>();-+class AccountSettings implements ExperimentalSettingsTransport {+ AccountSettings(this.accountId);+ String accountId;+ int revision = 0, reads = 0;+ final writes = <(String, ExperimentalFeature, bool)>[];+ final features = {for (final f in ExperimentalFeature.values) f.id: false};+ Future<Map<String, dynamic>> Function()? readOverride;+ Future<Map<String, dynamic>> Function()? writeOverride;+ Map<String, dynamic> get snapshot => {+ 'accountId': accountId,+ 'revision': revision,+ 'features': Map<String, bool>.of(features),+ };@override- Future<Map<String, String?>> readMany(Iterable<String> keys) => ready.future;-}--class _DelayedWrite extends MemoryStore {- final ready = Completer<void>();- int writes = 0;- bool fail = false;+ Future<Map<String, dynamic>> read() async {+ reads++;+ return readOverride == null ? snapshot : await readOverride!();+ }@override- Future<void> write(String key, String value) async {- if (++writes == 1) await ready.future;- if (fail) throw StateError('synthetic write failure');- await super.write(key, value);+ Future<Map<String, dynamic>> write(+ String account,+ ExperimentalFeature feature,+ bool enabled,+ ) async {+ writes.add((account, feature, enabled));+ if (account != accountId) throw StateError('Account changed');+ if (writeOverride != null) return writeOverride!();+ features[feature.id] = enabled;+ revision++;+ return snapshot;}}void main() {const creature = ExperimentalFeature.focusBarCreature;+ const share = ExperimentalFeature.shareButton;+ Future<ExperimentalFeaturesStore> open(AccountSettings server) async {+ final store = ExperimentalFeaturesStore(pollInterval: Duration.zero);+ addTearDown(store.dispose);+ store.bind(server.accountId, transport: server);+ await store.refresh();+ return store;+ }for (final feature in ExperimentalFeature.values) {test(- '${feature.label} defaults off and restores both saved choices',+ '${feature.label} follows the account across clients and reopening',() async {- final storage = MemoryStore();- Future<ExperimentalFeaturesStore> reopen() async {- final store = ExperimentalFeaturesStore(storage: storage);- addTearDown(store.dispose);- await store.load();- return store;- }-- final first = await reopen();+ final server = AccountSettings('a');+ final first = await open(server);+ final second = await open(server);expect(first.enabled(feature), isFalse);- expect(first.choice(feature), isNull);- expect(storage.values, isEmpty);+ expect(server.writes, isEmpty, reason: 'opening settings only reads');await first.set(feature, true);- final second = await reopen();+ await second.refresh();expect(second.enabled(feature), isTrue);+ expect((await open(server)).enabled(feature), isTrue);await second.set(feature, false);- final third = await reopen();- expect(third.choice(feature), isFalse);- storage.values[feature.storageKey] = 'true';- expect((await reopen()).enabled(feature), isFalse);+ await first.refresh();+ expect(first.enabled(feature), isFalse);+ expect((await open(AccountSettings('b'))).enabled(feature), isFalse);},);}- test(- 'a late preference read cannot undo a choice made in Settings',- () async {- final storage = _DelayedRead();- final store = ExperimentalFeaturesStore(storage: storage);- addTearDown(store.dispose);- final loading = store.load();- await store.set(creature, true);- storage.ready.complete({creature.storageKey: 'off'});- await loading;- expect(store.enabled(creature), isTrue);- expect(storage.values[creature.storageKey], 'on');- },- );+ test('a pending save is not presented as saved, and a failed save can be retried', () async {+ final server = AccountSettings('a');+ final store = await open(server);+ final save = Completer<Map<String, dynamic>>();+ server.writeOverride = () => save.future;+ final writing = store.set(creature, true);+ expect(store.saving, isTrue);+ expect(store.enabled(creature), isFalse);+ save.completeError(StateError('offline'));+ await writing;+ expect(store.enabled(creature), isFalse);+ expect(store.error, contains('Refresh'));+ server.writeOverride = null;+ await store.set(creature, true);+ expect(store.enabled(creature), isTrue);+ expect(store.error, isNull);+ });++ test('a late read cannot reverse an acknowledged choice', () async {+ final server = AccountSettings('a');+ final store = await open(server);+ final old = server.snapshot;+ final read = Completer<Map<String, dynamic>>();+ server.readOverride = () => read.future;+ final reading = store.refresh();+ await store.set(share, true);+ read.complete(old);+ await reading;+ expect(store.enabled(share), isTrue);+ });++ test('switching accounts clears choices immediately and ignores old reads and writes', () async {+ final a = AccountSettings('a');+ final b = AccountSettings('b');+ final store = await open(a);+ await store.set(creature, true);+ final read = Completer<Map<String, dynamic>>();+ final write = Completer<Map<String, dynamic>>();+ a.readOverride = () => read.future;+ a.writeOverride = () => write.future;+ final reading = store.refresh();+ final writing = store.set(share, true);+ store.bind('b', transport: b);+ expect(store.enabled(creature), isFalse);+ expect(store.loaded, isFalse);+ await store.refresh();+ read.complete(a.snapshot);+ write.complete({+ ...a.snapshot,+ 'revision': 20,+ 'features': {creature.id: true, share.id: true},+ });+ await Future.wait([reading, writing]);+ expect(store.accountId, 'b');+ expect(store.enabled(creature), isFalse);+ expect(store.enabled(share), isFalse);+ expect(store.saving, isFalse);+ expect(b.writes, isEmpty);+ store.bind(null);+ await store.set(creature, true);+ expect(store.loaded, isFalse);+ expect(b.writes, isEmpty);+ });test(- 'rapid flips apply immediately and save the final choice last',+ 'unreadable or wrong-account settings never enable experiments',() async {- final storage = _DelayedWrite();- final store = ExperimentalFeaturesStore(storage: storage);- addTearDown(store.dispose);- final on = store.set(creature, true);- final off = store.set(creature, false);+ final server = AccountSettings('a')+ ..readOverride = () async => {+ 'accountId': 'b',+ 'revision': 1,+ 'features': {creature.id: true, share.id: true},+ };+ final store = await open(server);+ expect(store.loaded, isFalse);expect(store.enabled(creature), isFalse);- await Future<void>.delayed(Duration.zero);- expect(storage.writes, 1);- expect(storage.values, isEmpty);- storage.ready.complete();- await Future.wait([on, off]);- expect(storage.values[creature.storageKey], 'off');+ await store.set(creature, true);+ expect(server.writes, isEmpty);+ server.readOverride = () => Future.error(StateError('offline'));+ await store.refresh();+ expect(store.loaded, isFalse);+ expect(store.error, isNotNull);},);- test(- 'a failed save can be retried without flipping the switch again',- () async {- final storage = _DelayedWrite()..fail = true;- storage.ready.complete();- final store = ExperimentalFeaturesStore(storage: storage);- addTearDown(store.dispose);- await expectLater(store.set(creature, true), throwsStateError);- expect(store.enabled(creature), isTrue);- storage.fail = false;- await store.set(creature, true);- expect(storage.values[creature.storageKey], 'on');+ test('AppNotifier binds preferences only after the account profile arrives and clears on sign-out', () async {+ final server = AccountSettings('a')..features[creature.id] = true;+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ experimentalSettingsTransport: server,+ );+ addTearDown(app.dispose);+ expect(server.reads, 0);+ expect(app.experimentalFeatures.loaded, isFalse);+ app.currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ );+ await app.experimentalFeatures.refresh();+ expect(app.experimentalFeatures.enabled(creature), isTrue);+ app.currentUser = null;+ expect(app.experimentalFeatures.enabled(creature), isFalse);+ expect(app.experimentalFeatures.accountId, isNull);+ expect(server.writes, isEmpty);+ });++ testWidgets('missed push notifications reconcile through the account poll', (+ tester,+ ) async {+ final server = AccountSettings('a');+ final store = ExperimentalFeaturesStore();+ store.bind('a', transport: server);+ await tester.pump();+ server.features[share.id] = true;+ server.revision++;+ await tester.pump(const Duration(seconds: 30));+ expect(store.enabled(share), isTrue);+ store.dispose();+ final reads = server.reads;+ await tester.pump(const Duration(seconds: 30));+ expect(server.reads, reads);+ });++ testWidgets(+ 'settings show pending saves, uncertain writes and read failures with recovery',+ (tester) async {+ final server = AccountSettings('a');+ final store = await open(server);+ final reply = Completer<Map<String, dynamic>>();+ server.writeOverride = () => reply.future;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(body: ExperimentalSection(store: store)),+ ),+ );+ await tester.pumpAndSettle();+ final toggle = find.byKey(const ValueKey('experimental-share_button'));+ await tester.tap(toggle);+ await tester.pump();+ expect(tester.widget<Switch>(toggle).value, isFalse);+ expect(tester.widget<Switch>(toggle).onChanged, isNull);+ expect(find.text('Saving…'), findsOneWidget);+ // The server saved it, but the acknowledgement did not reach this window.+ server.features[share.id] = true;+ server.revision++;+ reply.completeError(StateError('Connection lost'));+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(toggle).value, isFalse);+ expect(find.textContaining('Couldn’t confirm'), findsOneWidget);+ await tester.tap(find.text('Refresh setting'));+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(toggle).value, isTrue);+ expect(find.textContaining('Couldn’t confirm'), findsNothing);+ server.readOverride = () => Future.error(StateError('offline'));+ await store.refresh();+ await tester.pumpAndSettle();+ expect(tester.widget<Switch>(toggle).value, isTrue);+ expect(find.textContaining('Couldn’t read'), findsOneWidget);+ server.readOverride = null;+ await tester.tap(find.text('Refresh settings'));+ await tester.pumpAndSettle();+ expect(find.textContaining('Couldn’t read'), findsNothing);+ await tester.pumpWidget(const SizedBox());},);}diff --git a/desktop/test/settings_review_render_test.dart b/desktop/test/settings_review_render_test.dartindex 55a4d25f0..50e2aeaca 100644--- a/desktop/test/settings_review_render_test.dart+++ b/desktop/test/settings_review_render_test.dart@@ -16,7 +16,6 @@ import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/settings/settings_nav.dart';import 'package:harness/settings/experimental_features.dart';-import 'swarm_state_test.dart' show MemoryStore;import 'package:harness/settings/settings_screen.dart';import 'package:harness/settings/settings_section.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;@@ -27,7 +26,9 @@ import 'package:harness/update/manual_update_check.dart';import 'package:harness/widgets/shortcuts_sheet.dart';import 'package:harness/widgets/update_notice.dart';+import 'support/experimental_settings.dart';import 'support/real_fonts.dart';+import 'swarm_state_test.dart' show MemoryStore;void main() {setUpAll(() async {@@ -98,9 +99,12 @@ void main() {name: 'Morgan Rivera',email: '[email protected]',);- final experiments = ExperimentalFeaturesStore(storage: MemoryStore());+ final experiments = MemoryExperimentalFeaturesStore(+ storage: MemoryStore(),+ );addTearDown(experiments.dispose);- if (section == SettingsSection.experimental && brightness == Brightness.dark) {+ if (section == SettingsSection.experimental &&+ brightness == Brightness.dark) {await experiments.set(ExperimentalFeature.focusBarCreature, true);}final boundary = GlobalKey();@@ -138,7 +142,10 @@ void main() {.copyWith(textScaler: TextScaler.linear(scale)),child: grid.BrightnessScope(child: child!),),- home: SettingsScreen(notifier: app, experimentalFeatures: experiments),+ home: SettingsScreen(+ notifier: app,+ experimentalFeatures: experiments,+ ),),),);diff --git a/desktop/test/settings_screen_test.dart b/desktop/test/settings_screen_test.dartindex 853150b16..07e916280 100644--- a/desktop/test/settings_screen_test.dart+++ b/desktop/test/settings_screen_test.dart@@ -25,6 +25,8 @@ import 'package:harness/shortcuts/keyboard_practice.dart';import 'package:harness/state/app_state.dart';import 'package:harness/widgets/harness_customize_pane.dart';+import 'support/experimental_settings.dart';+import 'swarm_state_test.dart' show MemoryStore;void main() {@@ -144,7 +146,7 @@ void main() {'Experimental is searchable and its labelled switch works by keyboard',(tester) async {final storage = MemoryStore();- final experiments = ExperimentalFeaturesStore(storage: storage);+ final experiments = MemoryExperimentalFeaturesStore(storage: storage);addTearDown(experiments.dispose);await openSettings(tester, experiments: experiments);await tester.enterText(@@ -159,8 +161,16 @@ void main() {expect(tester.widget<Switch>(toggle).value, isFalse);final semantics = tester.ensureSemantics();expect(- find.bySemanticsLabel(RegExp('Focus-bar creature')),- findsOneWidget,+ tester.getSemantics(toggle),+ matchesSemantics(+ label: 'Focus-bar creature',+ hasToggledState: true,+ hasEnabledState: true,+ isEnabled: true,+ isFocusable: true,+ hasTapAction: true,+ hasFocusAction: true,+ ),);semantics.dispose();// Search → matching nav row → switch.@@ -171,14 +181,18 @@ void main() {await tester.pumpAndSettle();expect(tester.widget<Switch>(toggle).value, isTrue);expect(- storage.values[ExperimentalFeature.focusBarCreature.storageKey],+ storage.values[experimentFixtureKey(+ ExperimentalFeature.focusBarCreature,+ )],'on',);await tester.sendKeyEvent(LogicalKeyboardKey.space);await tester.pumpAndSettle();expect(tester.widget<Switch>(toggle).value, isFalse);expect(- storage.values[ExperimentalFeature.focusBarCreature.storageKey],+ storage.values[experimentFixtureKey(+ ExperimentalFeature.focusBarCreature,+ )],'off',);await tester.sendKeyEvent(LogicalKeyboardKey.escape);diff --git a/desktop/test/share_toolbar_test.dart b/desktop/test/share_toolbar_test.dartindex 2c423beaf..ece2a94ab 100644--- a/desktop/test/share_toolbar_test.dart+++ b/desktop/test/share_toolbar_test.dart@@ -22,6 +22,8 @@ import 'package:harness/terminal/terminal_binary.dart';import 'package:harness/widgets/workspace_share_button.dart';import 'package:harness/ws/ws_conn.dart';+import 'support/experimental_settings.dart';+import 'keymap_host_test.dart' show MemoryKeymap, key;import 'swarm_screen_test.dart' show terminal;import 'swarm_state_test.dart' show createApp, MemoryStore;@@ -68,7 +70,7 @@ void main() {app.stateOf('m')!.nodeOnline = true;keymap = MemoryKeymap();preferences = MemoryStore();- experiments = ExperimentalFeaturesStore(storage: preferences);+ experiments = MemoryExperimentalFeaturesStore(storage: preferences);input.clear();});tearDown(() {@@ -129,7 +131,7 @@ void main() {final session = terminal('a0', input);final pane = app.adoptSessionForTest(session);await mount(tester, native: native, enableShareButton: false);- expect(experiments.choice(feature), isNull);+ expect(experiments.choice(feature), isFalse);expect(button, findsNothing);if (native) expect(updates.last['shareAction'], isNull);@@ -151,7 +153,7 @@ void main() {await tester.tap(toggle);await tester.pumpAndSettle();expect(tester.widget<Switch>(toggle).value, isTrue);- expect(preferences.values[feature.storageKey], 'on');+ expect(preferences.values[experimentFixtureKey(feature)], 'on');await tester.tap(find.byKey(const Key('settings-back-button')));await tester.pumpAndSettle();expect(find.byType(SettingsScreen), findsNothing);@@ -166,7 +168,7 @@ void main() {expect(tester.widget<Switch>(toggle).value, isTrue);await tester.tap(toggle);await tester.pumpAndSettle();- expect(preferences.values[feature.storageKey], 'off');+ expect(preferences.values[experimentFixtureKey(feature)], 'off');await tester.tap(find.byKey(const Key('settings-back-button')));await tester.pumpAndSettle();expect(button, findsNothing);diff --git a/desktop/test/startup_test.dart b/desktop/test/startup_test.dartindex 871651d56..cde3d248b 100644--- a/desktop/test/startup_test.dart+++ b/desktop/test/startup_test.dart@@ -7,7 +7,6 @@ import 'package:harness/core/harness_file_store.dart';import 'package:harness/core/local_key_value_store.dart';import 'package:harness/core/snapshot_store.dart';import 'package:harness/core/startup.dart';-import 'package:harness/settings/experimental_features.dart';import 'package:harness/notify/alert_sounds.dart';import 'package:harness/notify/system_notifications.dart';import 'package:harness/shared/theme/appearance_prefs_store.dart';@@ -47,7 +46,6 @@ void main() {late TerminalThemeStore scheme;late AppearancePrefsStore appearance;late HarnessStats stats;- late ExperimentalFeaturesStore experiments;setUp(() async {dir = await Directory.systemTemp.createTemp('harness-startup-');@@ -57,7 +55,6 @@ void main() {scheme = TerminalThemeStore(storage: storage);appearance = AppearancePrefsStore(storage: storage);stats = HarnessStats(store: statsStorage);- experiments = ExperimentalFeaturesStore(storage: storage);});tearDown(() async {@@ -65,14 +62,12 @@ void main() {scheme.dispose();appearance.dispose();stats.dispose();- experiments.dispose();await dir.delete(recursive: true);});test('a relaunch restores appearance and counters before returning', () async {// Every store, including stats, uses only this test's temporary directory.// Write through the real setters so the persisted formats are exercised.- await experiments.set(ExperimentalFeature.focusBarCreature, true);await font.setFamily(TerminalFontChoice.menlo);await font.setSize(17);await scheme.set(TerminalThemeChoice.tango);@@ -89,8 +84,6 @@ void main() {await stats.flush();final reopened = HarnessFileStore(directory: storage.directory);- final nextExperiments = ExperimentalFeaturesStore(storage: reopened);- addTearDown(nextExperiments.dispose);final nextFont = TerminalFontStore(storage: reopened);final nextScheme = TerminalThemeStore(storage: reopened);final nextAppearance = AppearancePrefsStore(storage: reopened);@@ -109,13 +102,8 @@ void main() {alertSounds: AlertSoundStore(storage: storage),screenAlerts: ScreenAlertStore(storage: storage),desktopNotifications: DesktopNotificationStore(storage: storage),- experimentalFeatures: nextExperiments,);- expect(- nextExperiments.enabled(ExperimentalFeature.focusBarCreature),- isTrue,- );expect(nextFont.family, TerminalFontChoice.menlo);expect(nextFont.size, 17);expect(nextScheme.value, TerminalThemeChoice.tango);@@ -142,9 +130,7 @@ void main() {alertSounds: AlertSoundStore(storage: storage),screenAlerts: ScreenAlertStore(storage: storage),desktopNotifications: DesktopNotificationStore(storage: storage),- experimentalFeatures: experiments,);- expect(experiments.enabled(ExperimentalFeature.focusBarCreature), isFalse);expect(font.family, TerminalFontChoice.defaultForPlatform);expect(font.size, terminalFontSize);expect(scheme.value, TerminalThemeChoice.fallback);@@ -178,7 +164,6 @@ void main() {alertSounds: AlertSoundStore(storage: storage),screenAlerts: ScreenAlertStore(storage: storage),desktopNotifications: DesktopNotificationStore(storage: storage),- experimentalFeatures: experiments,).then((_) => finished = true);expect(fontStorage.requests, [@@ -254,7 +239,6 @@ void main() {alertSounds: AlertSoundStore(storage: storage),screenAlerts: ScreenAlertStore(storage: storage),desktopNotifications: DesktopNotificationStore(storage: storage),- experimentalFeatures: experiments,).then((_) => finished = true);broken.ready.completeError(const FileSystemException('unreadable'));await Future<void>.delayed(Duration.zero);diff --git a/desktop/test/support/experimental_settings.dart b/desktop/test/support/experimental_settings.dartnew file mode 100644index 000000000..98a316460--- /dev/null+++ b/desktop/test/support/experimental_settings.dart@@ -0,0 +1,48 @@+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/settings/experimental_features.dart';++String experimentFixtureKey(ExperimentalFeature feature) =>+ 'experimental.${feature.id}';++/// An injected server fixture. The production store never reads these local keys.+class MemoryExperimentalTransport implements ExperimentalSettingsTransport {+ MemoryExperimentalTransport(this.storage, {this.accountId = 'u1'});+ final LocalKeyValueStore storage;+ final String accountId;+ int revision = 0;++ @override+ Future<Map<String, dynamic>> read() async => {+ 'accountId': accountId,+ 'revision': revision,+ 'features': {+ for (final feature in ExperimentalFeature.values)+ feature.id: await storage.read(experimentFixtureKey(feature)) == 'on',+ },+ };++ @override+ Future<Map<String, dynamic>> write(+ String account,+ ExperimentalFeature feature,+ bool enabled,+ ) async {+ if (account != accountId) throw StateError('Account changed');+ await storage.write(experimentFixtureKey(feature), enabled ? 'on' : 'off');+ revision++;+ return read();+ }+}++class MemoryExperimentalFeaturesStore extends ExperimentalFeaturesStore {+ MemoryExperimentalFeaturesStore({required LocalKeyValueStore storage})+ : super(pollInterval: Duration.zero) {+ bind('u1', transport: MemoryExperimentalTransport(storage));+ }++ @override+ Future<void> set(ExperimentalFeature feature, bool on) async {+ if (!loaded) await refresh();+ await super.set(feature, on);+ }+}diff --git a/desktop/test/swarm_settings_test.dart b/desktop/test/swarm_settings_test.dartindex a06d9b8c6..dfd79c5c0 100644--- a/desktop/test/swarm_settings_test.dart+++ b/desktop/test/swarm_settings_test.dart@@ -10,6 +10,8 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/teams/swarm_settings_controller.dart';import 'support/real_fonts.dart';+import 'support/experimental_settings.dart';+import 'swarm_state_test.dart' show MemoryStore;void main() {setUpAll(loadRealFonts);@@ -116,6 +118,11 @@ void main() {},);final capture = GlobalKey();+ final preferences = MemoryExperimentalFeaturesStore(+ storage: MemoryStore(),+ );+ addTearDown(preferences.dispose);+ await preferences.refresh();await tester.pumpWidget(MaterialApp(debugShowCheckedModeBanner: false,@@ -123,7 +130,10 @@ void main() {home: Scaffold(body: RepaintBoundary(key: capture,- child: ExperimentalSection(controller: controller),+ child: ExperimentalSection(+ store: preferences,+ controller: controller,+ ),),),),