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
feat: one desk per account — tabs are the same on every computer
0xdiego2567bdbe4e6a16
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 20d833d35..2356e6d5d 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -578,3 +578,22 @@ model HarnessShare {@@index([ownerId, machineId])@@map("harness_shares")}++/// The account's DESK: its tabs, in order, and the agents each holds — one document per user, the+/// same on every computer the person signs in on (owner, 2026-09-21: "tab là global"). Holds only+/// what the person would call "my tabs": ids, names, order, `(machineId, agentId)` pairs. Nothing+/// about a window — focus, zoom, pane sizes, which tab is on screen — those differ per computer and+/// stay in each app's own state file. Written through `POST /api/desk/ops` (routes/desk.ts): small+/// idempotent operations applied in order under `revision`, so two windows racing merge by rule+/// rather than by whoever saved last. Plaintext, like `Machine.name` and `MachineAgent.name`: the+/// doc adds no class of data the backend does not already hold.+model Desk {+ id String @id @default(auto()) @map("_id") @db.ObjectId+ userId String @unique+ revision Int @default(0)+ tabs Json @default("[]")+ updatedAt DateTime @updatedAt++ @@map("desks")+}+diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.tsindex 12b97c255..11fb73dce 100644--- a/backend/src/lib/adapterWs.ts+++ b/backend/src/lib/adapterWs.ts@@ -20,7 +20,7 @@ import { prisma } from './prisma.js'import {publishUp, claimMachineOwner, releaseMachineOwner, publishDeviceE2eePair,publishTerminalUp, subscribeTerminalDown,- setMachineAppState, clearMachineAppState,+ setMachineAppState, clearMachineAppState, subscribeDeskChanged,} from './bus.js'import { trackSocketLiveness } from './hub.js'import { guardedSend, guardedSendJson } from './wsSend.js'@@ -203,6 +203,12 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, cconst send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { machineId, kind: 'adapter' })logger.info('adapter connected', { machineId, computer: label })send({ t: 'connected', machineId })+ // The account's tabs changed on some worker: this computer's app re-fetches `/api/desk` through its+ // daemon (backendSocket.ts relays `desk_changed` to the window). One frame, no payload beyond the+ // revision — the doc itself is fetched, so a burst of edits collapses into one read.+ const deskUnsub = await subscribeDeskChanged(userId, (msg) => {+ send({ t: 'down', connId: '', frame: { type: 'desk_changed', payload: { revision: msg.revision } } })+ })// Last desktop-app state THIS socket asserted. Socket-scoped on purpose: a new adapter connection// starts with no claim and must re-assert, so a fresh value can never renew a stale one.@@ -474,6 +480,7 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, cconst cleanup = (): void => {releaseLiveness()terminalDownUnsub()+ void deskUnsub()// Only the CURRENT owner tears the role down — a superseded socket must not mark the fresh// connection offline. A superseded socket still releases its own liveness tracking above.if (owners.get(machineId) === ws) {diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.tsindex 7060777cf..c30b2ed02 100644--- a/backend/src/lib/bus.ts+++ b/backend/src/lib/bus.ts@@ -582,6 +582,20 @@ export function subscribeDeviceMachineListChanged(userId: string, cb: (msg: Devireturn addSub(deviceMachineListChannel(userId), cb as Cb)}+// Per-USER desk invalidation: the account's tabs changed (routes/desk.ts) on some REST worker; every+// adapter socket of that user — one per computer, possibly on other workers — is told to re-fetch.+export interface DeskChangedMsg { revision: number }++const deskChannel = (userId: string): string => `desk:${userId}`++export function publishDeskChanged(userId: string, msg: DeskChangedMsg): Promise<number> {+ return safePublish(deskChannel(userId), JSON.stringify(msg))+}++export function subscribeDeskChanged(userId: string, cb: (msg: DeskChangedMsg) => void): Promise<() => void> {+ return addSub(deskChannel(userId), cb as Cb)+}+export interface DeviceE2eePairMsg {kind: 'pending' | 'cleared'machineId: stringdiff --git a/backend/src/lib/desk.ts b/backend/src/lib/desk.tsnew file mode 100644index 000000000..aa10d09d4--- /dev/null+++ b/backend/src/lib/desk.ts@@ -0,0 +1,160 @@+/**+ * The desk document and the operations that change it — pure, so the merge rule can be tested+ * without a database.+ *+ * ONE RULE: every op is idempotent and an op on a tab that is gone is dropped, never an error. That+ * is the whole of how two windows racing merge — close a tab here while a pane is being added to it+ * there, and the add lands on nothing. A window that was offline for a day replays its queue against+ * a desk that moved, and every op still means what it meant.+ */+import { z } from 'zod'++export const DESK_MAX_TABS = 24 // the window's own ceiling (localWsServer.ts, appSwarmsFrom)+export const DESK_MAX_PANES = 9 // the window's grid (`maxPanes`)+export const DESK_NAME_MAX = 80++const id = z.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/)+const machineId = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/)+const agentId = z.string().min(1).max(160)+const name = z.string().trim().min(1).max(DESK_NAME_MAX)++export const deskPaneSchema = z.object({ machineId, agentId }).strict()+export const deskTabSchema = z.object({+ id,+ name,+ nameIsCustom: z.boolean().optional(),+ panes: z.array(deskPaneSchema).max(DESK_MAX_PANES),+}).strict()++export type DeskPane = z.infer<typeof deskPaneSchema>+export type DeskTab = z.infer<typeof deskTabSchema>+export interface DeskDoc { revision: number; tabs: DeskTab[] }++export const deskOpSchema = z.discriminatedUnion('op', [+ z.object({ op: z.literal('tab.create'), id, name, nameIsCustom: z.boolean().optional(), index: z.number().int().min(0).optional() }).strict(),+ z.object({ op: z.literal('tab.close'), id }).strict(),+ z.object({ op: z.literal('tab.rename'), id, name, nameIsCustom: z.boolean().optional() }).strict(),+ z.object({ op: z.literal('tab.move'), id, index: z.number().int().min(0) }).strict(),+ z.object({ op: z.literal('pane.add'), tabId: id, machineId, agentId, index: z.number().int().min(0).optional() }).strict(),+ z.object({ op: z.literal('pane.remove'), tabId: id, machineId, agentId }).strict(),+ z.object({ op: z.literal('pane.move'), tabId: id, machineId, agentId, index: z.number().int().min(0) }).strict(),+ // First sync from a computer that already had tabs of its own: every tab whose id the desk does+ // not know is appended, as it was. The person closes the extras; nothing of theirs is dropped.+ z.object({ op: z.literal('seed'), tabs: z.array(deskTabSchema).max(DESK_MAX_TABS) }).strict(),+])+export type DeskOp = z.infer<typeof deskOpSchema>++export const deskOpsBodySchema = z.object({+ ops: z.array(deskOpSchema).min(1).max(200),+}).strict()++/** `tabs` as stored (Json), validated shape by shape; anything malformed is dropped rather than served. */+export function parseTabs(raw: unknown): DeskTab[] {+ if (!Array.isArray(raw)) return []+ const out: DeskTab[] = []+ const seen = new Set<string>()+ for (const item of raw) {+ const parsed = deskTabSchema.safeParse(item)+ if (!parsed.success || seen.has(parsed.data.id)) continue+ seen.add(parsed.data.id)+ out.push(parsed.data)+ if (out.length >= DESK_MAX_TABS) break+ }+ return out+}++const clampIndex = (index: number | undefined, length: number): number =>+ index === undefined ? length : Math.max(0, Math.min(index, length))++const samePane = (a: DeskPane, b: { machineId: string; agentId: string }): boolean =>+ a.machineId === b.machineId && a.agentId === b.agentId++/**+ * Apply one op to a copy of `tabs`. Returns the new list and whether anything changed — an op that+ * finds its tab gone, or its pane already there, changes nothing and says so.+ */+export function applyDeskOp(tabs: DeskTab[], op: DeskOp): { tabs: DeskTab[]; changed: boolean } {+ const next = tabs.map((t) => ({ ...t, panes: [...t.panes] }))+ const at = (tabId: string) => next.findIndex((t) => t.id === tabId)+ switch (op.op) {+ case 'tab.create': {+ if (at(op.id) >= 0) return { tabs: next, changed: false } // already there: the same click twice+ if (next.length >= DESK_MAX_TABS) return { tabs: next, changed: false }+ const tab: DeskTab = { id: op.id, name: op.name, panes: [], ...(op.nameIsCustom ? { nameIsCustom: true } : {}) }+ next.splice(clampIndex(op.index, next.length), 0, tab)+ return { tabs: next, changed: true }+ }+ case 'tab.close': {+ const i = at(op.id)+ if (i < 0) return { tabs: next, changed: false }+ next.splice(i, 1)+ return { tabs: next, changed: true }+ }+ case 'tab.rename': {+ const i = at(op.id)+ if (i < 0) return { tabs: next, changed: false }+ const custom = op.nameIsCustom ?? next[i].nameIsCustom+ if (next[i].name === op.name && !!next[i].nameIsCustom === !!custom) return { tabs: next, changed: false }+ next[i] = { ...next[i], name: op.name, ...(custom ? { nameIsCustom: true } : {}) }+ if (!custom) delete next[i].nameIsCustom+ return { tabs: next, changed: true }+ }+ case 'tab.move': {+ const i = at(op.id)+ if (i < 0) return { tabs: next, changed: false }+ const [tab] = next.splice(i, 1)+ const dest = clampIndex(op.index, next.length)+ next.splice(dest, 0, tab)+ return { tabs: next, changed: dest !== i }+ }+ case 'pane.add': {+ const i = at(op.tabId)+ if (i < 0) return { tabs: next, changed: false }+ const panes = next[i].panes+ if (panes.some((p) => samePane(p, op))) return { tabs: next, changed: false }+ if (panes.length >= DESK_MAX_PANES) return { tabs: next, changed: false }+ panes.splice(clampIndex(op.index, panes.length), 0, { machineId: op.machineId, agentId: op.agentId })+ return { tabs: next, changed: true }+ }+ case 'pane.remove': {+ const i = at(op.tabId)+ if (i < 0) return { tabs: next, changed: false }+ const panes = next[i].panes+ const j = panes.findIndex((p) => samePane(p, op))+ if (j < 0) return { tabs: next, changed: false }+ panes.splice(j, 1)+ return { tabs: next, changed: true }+ }+ case 'pane.move': {+ const i = at(op.tabId)+ if (i < 0) return { tabs: next, changed: false }+ const panes = next[i].panes+ const j = panes.findIndex((p) => samePane(p, op))+ if (j < 0) return { tabs: next, changed: false }+ const [pane] = panes.splice(j, 1)+ const dest = clampIndex(op.index, panes.length)+ panes.splice(dest, 0, pane)+ return { tabs: next, changed: dest !== j }+ }+ case 'seed': {+ let changed = false+ for (const tab of op.tabs) {+ if (at(tab.id) >= 0 || next.length >= DESK_MAX_TABS) continue+ next.push({ ...tab, panes: [...tab.panes] })+ changed = true+ }+ return { tabs: next, changed }+ }+ }+}++export function applyDeskOps(tabs: DeskTab[], ops: DeskOp[]): { tabs: DeskTab[]; changed: boolean } {+ let current = tabs+ let changed = false+ for (const op of ops) {+ const result = applyDeskOp(current, op)+ current = result.tabs+ changed ||= result.changed+ }+ return { tabs: current, changed }+}diff --git a/backend/src/routes/desk.test.ts b/backend/src/routes/desk.test.tsnew file mode 100644index 000000000..402f18d8a--- /dev/null+++ b/backend/src/routes/desk.test.ts@@ -0,0 +1,149 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+const mocks = vi.hoisted(() => ({+ prisma: { desk: { findUnique: vi.fn(), updateMany: vi.fn(), create: vi.fn() } },+ changed: vi.fn(), auth: vi.fn(),+}))+vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma }))+vi.mock('../lib/bus.js', () => ({ publishDeskChanged: mocks.changed }))+vi.mock('../lib/ssoAuth.js', async original => ({ ...await original<typeof import('../lib/ssoAuth.js')>(), authenticateAccessToken: mocks.auth }))+import { deskRoutes } from './desk.js'+import { applyDeskOp, applyDeskOps, parseTabs, DESK_MAX_TABS, type DeskTab } from '../lib/desk.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'++const user = { sub: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' as const }+const tab = (id: string, panes: Array<[string, string]> = []): DeskTab =>+ ({ id, name: `Tab ${id}`, panes: panes.map(([machineId, agentId]) => ({ machineId, agentId })) })++describe('desk ops — the merge rule', () => {+ it('creates, renames, moves and closes tabs, and says when nothing moved', () => {+ let r = applyDeskOp([], { op: 'tab.create', id: 'a', name: 'Local' })+ expect(r.changed).toBe(true)+ r = applyDeskOp(r.tabs, { op: 'tab.create', id: 'a', name: 'Local' }) // the same click twice+ expect(r.changed).toBe(false)+ r = applyDeskOp(r.tabs, { op: 'tab.create', id: 'b', name: 'Blender', index: 0 })+ expect(r.tabs.map(t => t.id)).toEqual(['b', 'a'])+ r = applyDeskOp(r.tabs, { op: 'tab.rename', id: 'a', name: 'Home', nameIsCustom: true })+ expect(r.tabs[1]).toMatchObject({ name: 'Home', nameIsCustom: true })+ r = applyDeskOp(r.tabs, { op: 'tab.move', id: 'a', index: 0 })+ expect(r.tabs.map(t => t.id)).toEqual(['a', 'b'])+ r = applyDeskOp(r.tabs, { op: 'tab.close', id: 'b' })+ expect(r.tabs.map(t => t.id)).toEqual(['a'])+ r = applyDeskOp(r.tabs, { op: 'tab.close', id: 'b' }) // already gone+ expect(r.changed).toBe(false)+ })++ it('adds, moves and removes panes; a pane is one (machine, agent) once per tab', () => {+ let r = applyDeskOps([tab('a')], [+ { op: 'pane.add', tabId: 'a', machineId: 'm1', agentId: 'x' },+ { op: 'pane.add', tabId: 'a', machineId: 'm2', agentId: 'y' },+ { op: 'pane.add', tabId: 'a', machineId: 'm1', agentId: 'x' }, // twice = once+ ])+ expect(r.tabs[0].panes).toEqual([{ machineId: 'm1', agentId: 'x' }, { machineId: 'm2', agentId: 'y' }])+ r = applyDeskOp(r.tabs, { op: 'pane.move', tabId: 'a', machineId: 'm2', agentId: 'y', index: 0 })+ expect(r.tabs[0].panes[0]).toEqual({ machineId: 'm2', agentId: 'y' })+ r = applyDeskOp(r.tabs, { op: 'pane.remove', tabId: 'a', machineId: 'm1', agentId: 'x' })+ expect(r.tabs[0].panes).toHaveLength(1)+ expect(applyDeskOp(r.tabs, { op: 'pane.remove', tabId: 'a', machineId: 'm1', agentId: 'x' }).changed).toBe(false)+ })++ it('drops an op on a tab that is gone — close here, add there, and the add lands on nothing', () => {+ // Window A closed the tab; window B, offline, queued a pane for it. B's replay must not resurrect it.+ const afterClose = applyDeskOp([tab('a'), tab('b')], { op: 'tab.close', id: 'a' }).tabs+ const replayed = applyDeskOps(afterClose, [+ { op: 'pane.add', tabId: 'a', machineId: 'm1', agentId: 'x' },+ { op: 'tab.rename', id: 'a', name: 'Renamed' },+ { op: 'tab.move', id: 'a', index: 0 },+ ])+ expect(replayed.changed).toBe(false)+ expect(replayed.tabs.map(t => t.id)).toEqual(['b'])+ })++ it('seeds a computer\'s own tabs once, by id, and never past the cap', () => {+ const local = [tab('l1', [['m1', 'x']]), tab('l2')]+ let r = applyDeskOp([tab('a')], { op: 'seed', tabs: local })+ expect(r.tabs.map(t => t.id)).toEqual(['a', 'l1', 'l2'])+ expect(applyDeskOp(r.tabs, { op: 'seed', tabs: local }).changed).toBe(false) // second sign-in: nothing+ const many = Array.from({ length: DESK_MAX_TABS + 5 }, (_, i) => tab(`t${i}`))+ r = applyDeskOp([], { op: 'seed', tabs: many.slice(0, DESK_MAX_TABS) })+ expect(r.tabs).toHaveLength(DESK_MAX_TABS)+ expect(applyDeskOp(r.tabs, { op: 'tab.create', id: 'one-more', name: 'x' }).changed).toBe(false)+ })++ it('reads stored tabs shape by shape and drops what does not parse', () => {+ expect(parseTabs([tab('a'), { id: 'b' }, 'junk', tab('a')])).toEqual([tab('a')])+ expect(parseTabs(null)).toEqual([])+ })+})++describe('desk routes', () => {+ let app: FastifyInstance+ beforeEach(async () => {+ vi.resetAllMocks()+ mocks.auth.mockResolvedValue(user)+ mocks.changed.mockResolvedValue(1)+ app = Fastify(); app.setErrorHandler(errorHandler); registerAuthMiddleware(app, mocks.auth)+ await app.register(deskRoutes); await app.ready()+ })+ afterEach(async () => { await app.close() })+ const auth = { authorization: 'Bearer fixture' }+ const post = (ops: unknown) => app.inject({ method: 'POST', url: '/api/desk/ops', headers: auth, payload: { ops } as any })++ it('answers an empty desk for a user who has none', async () => {+ mocks.prisma.desk.findUnique.mockResolvedValue(null)+ const res = await app.inject({ method: 'GET', url: '/api/desk', headers: auth })+ expect(res.json()).toEqual({ success: true, data: { revision: 0, tabs: [] } })+ })++ it('creates the row on the first write and tells every adapter of the user', async () => {+ mocks.prisma.desk.findUnique.mockResolvedValue(null)+ mocks.prisma.desk.updateMany.mockResolvedValue({ count: 0 })+ mocks.prisma.desk.create.mockResolvedValue({})+ const res = await post([{ op: 'tab.create', id: 'a', name: 'Local' }])+ expect(res.json().data).toEqual({ revision: 1, tabs: [{ id: 'a', name: 'Local', panes: [] }] })+ expect(mocks.prisma.desk.create).toHaveBeenCalledWith({ data: { userId: 'u1', revision: 1, tabs: [{ id: 'a', name: 'Local', panes: [] }] } })+ expect(mocks.changed).toHaveBeenCalledWith('u1', { revision: 1 })+ })++ it('bumps the revision with a compare-and-set, and replays on a lost race', async () => {+ // First read sees revision 3; the update finds 4 (another window wrote); the re-read sees 4.+ mocks.prisma.desk.findUnique+ .mockResolvedValueOnce({ revision: 3, tabs: [tab('a')] })+ .mockResolvedValueOnce({ revision: 4, tabs: [tab('a'), tab('b')] })+ mocks.prisma.desk.updateMany+ .mockResolvedValueOnce({ count: 0 })+ .mockResolvedValueOnce({ count: 1 })+ const res = await post([{ op: 'pane.add', tabId: 'a', machineId: 'm1', agentId: 'x' }])+ expect(res.json().data).toEqual({ revision: 5, tabs: [tab('a', [['m1', 'x']]), tab('b')] })+ expect(mocks.prisma.desk.updateMany).toHaveBeenLastCalledWith({+ where: { userId: 'u1', revision: 4 },+ data: { revision: 5, tabs: [tab('a', [['m1', 'x']]), tab('b')] },+ })+ expect(mocks.prisma.desk.create).not.toHaveBeenCalled()+ })++ it('writes nothing, and says where the desk is, when the ops change nothing', async () => {+ mocks.prisma.desk.findUnique.mockResolvedValue({ revision: 7, tabs: [tab('a')] })+ const res = await post([{ op: 'tab.close', id: 'gone' }])+ expect(res.json().data).toEqual({ revision: 7, tabs: [tab('a')] })+ expect(mocks.prisma.desk.updateMany).not.toHaveBeenCalled()+ expect(mocks.changed).not.toHaveBeenCalled()+ })++ it('refuses a malformed op and a tab name longer than the strip can show', async () => {+ mocks.prisma.desk.findUnique.mockResolvedValue(null)+ expect((await post([{ op: 'tab.explode', id: 'a' }])).statusCode).toBe(400)+ expect((await post([{ op: 'tab.create', id: 'a', name: 'x'.repeat(81) }])).statusCode).toBe(400)+ expect((await post([])).statusCode).toBe(400)+ })++ it('gives up after five lost races rather than spinning', async () => {+ mocks.prisma.desk.findUnique.mockResolvedValue({ revision: 2, tabs: [] })+ mocks.prisma.desk.updateMany.mockResolvedValue({ count: 0 })+ const res = await post([{ op: 'tab.create', id: 'a', name: 'Local' }])+ expect(res.statusCode).toBe(409)+ expect(res.json().error.code).toBe('DESK_BUSY')+ expect(mocks.prisma.desk.updateMany).toHaveBeenCalledTimes(5)+ })+})diff --git a/backend/src/routes/desk.ts b/backend/src/routes/desk.tsnew file mode 100644index 000000000..39a38b044--- /dev/null+++ b/backend/src/routes/desk.ts@@ -0,0 +1,62 @@+/**+ * The account's desk — its tabs, the same on every computer (lib/desk.ts for the rules).+ *+ * GET /api/desk → { revision, tabs }+ * POST /api/desk/ops → { ops } applied in order under `revision`, answers the new { revision, tabs }+ *+ * A write that lost a race with another window (the revision moved under it) is retried from the+ * fresh document: the ops are idempotent and drop-on-missing, so replaying them is the merge. After+ * a change every adapter socket of the user hears `desk_changed` (lib/adapterWs.ts) and re-fetches.+ */+import type { FastifyInstance } from 'fastify'+import { Prisma } from '@prisma/client'+import type { z } from 'zod'+import { prisma } from '../lib/prisma.js'+import { publishDeskChanged } from '../lib/bus.js'+import { applyDeskOps, deskOpsBodySchema, parseTabs, type DeskDoc } from '../lib/desk.js'+import { validateBody } from '../middlewares/validation.js'+import { sendError, sendSuccess } from '../utils/response.js'++const WRITE_ATTEMPTS = 5++async function readDesk(userId: string): Promise<DeskDoc> {+ const row = await prisma.desk.findUnique({ where: { userId } })+ return row ? { revision: row.revision, tabs: parseTabs(row.tabs) } : { revision: 0, tabs: [] }+}++export async function deskRoutes(app: FastifyInstance): Promise<void> {+ app.get('/api/desk', async (req, reply) => {+ sendSuccess(reply, await readDesk(req.user!.sub))+ })++ app.post<{ Body: z.infer<typeof deskOpsBodySchema> }>(+ '/api/desk/ops', { preHandler: [validateBody(deskOpsBodySchema)] },+ async (req, reply) => {+ const userId = req.user!.sub+ for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt++) {+ const current = await readDesk(userId)+ const applied = applyDeskOps(current.tabs, req.body.ops)+ // Nothing moved — the same click twice, or ops on tabs already gone. Say where we are.+ if (!applied.changed) return sendSuccess(reply, current)+ const next = { revision: current.revision + 1, tabs: applied.tabs }+ const tabs = next.tabs as unknown as Prisma.InputJsonValue+ // Compare-and-set on the revision: whoever wrote first wins, the other re-reads and replays.+ const bumped = await prisma.desk.updateMany({ where: { userId, revision: current.revision }, data: { revision: next.revision, tabs } })+ if (bumped.count !== 1) {+ if (current.revision !== 0) continue+ // No row yet (the only way revision 0 and no update): make it. A second window making it at+ // the same moment trips the unique index and re-reads what the first one wrote.+ try {+ await prisma.desk.create({ data: { userId, revision: next.revision, tabs } })+ } catch (error) {+ if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') continue+ throw error+ }+ }+ void publishDeskChanged(userId, { revision: next.revision })+ return sendSuccess(reply, next)+ }+ return sendError(reply, 'The desk is changing too quickly; try again.', 'DESK_BUSY', 409)+ },+ )+}diff --git a/backend/src/server.ts b/backend/src/server.tsindex e1f21dbf2..aeb50755f 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -10,6 +10,7 @@ import { registerAuthMiddleware } from './middlewares/authMiddleware.js'import { cursorRoutes } from './routes/cursor.js'import { voiceRoutes } from './routes/voice.js'import { harnessShareRoutes } from './routes/harnessShares.js'+import { deskRoutes } from './routes/desk.js'import { handleObserverUpgrade } from './lib/observerWs.js'import { deviceAuthRoutes } from './routes/deviceAuth.js'import { healthRoutes, authRoutes, userRoutes, machineRoutes, planRoutes, gridRoutes, deviceRoutes, mobileRoutes, appRoutes, analyticsRoutes, agentRouteRoutes, storeRoutes } from './routes/index.js'@@ -158,6 +159,7 @@ async function start(): Promise<void> {await app.register(deviceAuthRoutes) // device-authorization grant: how the desktop app gets a machine keyawait app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registryawait app.register(harnessShareRoutes)+ await app.register(deskRoutes) // the account's tabs, the same on every computer (lib/desk.ts)// Dedicated public subdomain app-proxy on its own port (Host-header routed → tunnelled to the node app).const appProxyServer = startSubdomainProxy()diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex aa9cc59f6..5e6d23e78 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1247,6 +1247,30 @@ describe('BackendSocket outbound queue', () => {})})+describe('desk_changed relay', () => {+ afterEach(() => {+ wsMock.instances.length = 0+ vi.restoreAllMocks()+ })++ it('hands the backend\'s desk_changed to the window, and only the backend\'s', async () => {+ const socket = new BackendSocket('token')+ const frames: Array<Record<string, unknown>> = []+ socket.registerLocalClient('local:desk', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ ws.message({ t: 'down', connId: '', frame: { type: 'desk_changed', payload: { revision: 9 } } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'desk_changed', payload: { revision: 9 } }))+ // A local client saying it is not the backend: nothing is relayed.+ socket.handleLocalFrame('local:desk', { type: 'desk_changed', payload: { revision: 99 } })+ await new Promise((r) => setTimeout(r, 20))+ expect(frames.filter((f) => f.type === 'desk_changed')).toHaveLength(1)+ await socket.unregisterLocalClient('local:desk')+ await socket.stop()+ })+})+describe('agent_fork RPC', () => {afterEach(() => {wsMock.instances.length = 0diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex a994af5c8..b9b4ab615 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -181,7 +181,7 @@ export type DownTransport = 'relay' | 'local' | 'p2p'* backend blocks its OWN `__`-prefixed control frames from web clients for the same reason; these* two escaped that rule because they are not `__`-prefixed.*/-const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked'])+const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed'])interface QueueItem {id: number@@ -1429,6 +1429,15 @@ export class BackendSocket {// clear the saved token. `closed` blocks the reconnect that would otherwise fire on socket drop.if (type === 'machine_revoked') { this.closed = true; this.onRevoked?.(); return }+ // The account's tabs changed on another computer (or in another window of this one): hand the+ // window the revision and let it fetch `/api/desk` through this daemon. Backend-only, like+ // machine_meta — a local client cannot make the window re-read anything by sending this.+ if (type === 'desk_changed') {+ const revision = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { revision?: unknown }).revision : undefined)+ this.sendLocal({ type: 'desk_changed', payload: { revision: typeof revision === 'number' ? revision : 0 } })+ return+ }+// Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.if (type === 'machine_meta') {// ⚠️ The BACKEND's frame and nobody else's. It carries this machine's display name and, morediff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 975346af3..7981ff8ad 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -3471,6 +3471,10 @@ async function runForeground(session: AuthSession): Promise<void> {onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),onAuthMe: () => proxyBackend('GET', '/api/auth/me'),onSharedHarnesses: () => proxyBackend('GET', '/api/harness-shares'),+ // The account's desk — see backend routes/desk.ts. The window edits its tabs through the ops+ // 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),onStore: (method, path, body) => proxyBackend(method, path, body),})// Claim the pid file for OURSELVES, and only now that the control port is bound. It used to bediff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 3153a5758..fa0b9a2a0 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -186,6 +186,30 @@ describe('process-owned hook server', () => {})})+describe('the desk proxy', () => {+ it('reads the desk ungated and writes its ops only with the local header, body passed through', async () => {+ const ops = vi.fn(async (body: unknown) => ({ status: 200, body: { success: true, data: { revision: 2, tabs: [], echo: body } } }))+ const { base } = await start({+ onDeskRead: async () => ({ status: 200, body: { success: true, data: { revision: 1, tabs: [] } } }),+ onDeskOps: ops,+ })+ const read = await fetch(`${base}/api/desk`)+ expect(await read.json()).toEqual({ success: true, data: { revision: 1, tabs: [] } })++ const refused = await fetch(`${base}/api/desk/ops`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"ops":[]}' })+ expect(refused.status).toBe(403)+ expect(ops).not.toHaveBeenCalled()++ const body = { ops: [{ op: 'tab.create', id: 'a', name: 'Local' }] }+ const written = await fetch(`${base}/api/desk/ops`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: JSON.stringify(body) })+ expect(((await written.json()) as { data: unknown }).data).toMatchObject({ revision: 2, echo: body })+ expect(ops).toHaveBeenCalledWith(body)++ const bad = await fetch(`${base}/api/desk/ops`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{nope' })+ expect(bad.status).toBe(400)+ })+})+describe('the Harness Store proxy', () => {it('forwards a store read with its path and query, and a store write only with the local header', async () => {const calls: Array<[string, string, unknown]> = []diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 8ec6ce4d8..af0c2e5fb 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -125,6 +125,11 @@ export interface HookServerHandlers {/** GET /api/auth/me — proxy the signed-in user's profile from backend. */onAuthMe?: () => Promise<PairOutcome>onSharedHarnesses?: () => Promise<PairOutcome>+ /** GET /api/desk — the account's tabs, the same on every computer; proxied like the machine list. */+ onDeskRead?: () => Promise<PairOutcome>+ /** 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>/** /api/store/* — proxy the Harness Store's ratings and reviews to backend the same way: reads* ungated like the machine list, writes (PUT/DELETE) CSRF-guarded like a rename. See storeProxy.ts. */onStore?: StoreHandler@@ -618,6 +623,17 @@ export function startHookServer(if (!handlers.onSharedHarnesses) { json(503, { error: 'UNAVAILABLE' }); return }await proxied(handlers.onSharedHarnesses); return}+ if (req.method === 'GET' && url === '/api/desk') {+ if (!handlers.onDeskRead) { json(503, { error: 'UNAVAILABLE' }); return }+ await proxied(handlers.onDeskRead); return+ }+ if (req.method === 'POST' && url === '/api/desk/ops') {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onDeskOps) { 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.onDeskOps!(body)); return+ }if (req.method === 'GET' && url === '/api/auth/me') {const me = handlers.onAuthMeif (!me) { json(503, { error: 'UNAVAILABLE' }); return }diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex c7319cd80..b599ef00a 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -102,6 +102,28 @@ class ApiClient {return unwrapApiResponse(res) as Map<String, dynamic>?;}+ // -- the desk: the account's tabs, the same on every computer (proxied by the local CLI) --++ /// `{revision, tabs}` as the backend holds it; null when the daemon predates the desk (404) or is+ /// signed out (401) — the app then keeps its tabs to itself, as it did before the desk existed.+ Future<Map<String, dynamic>?> desk() async {+ final res = await _dio.get('/api/desk');+ if (res.statusCode == 404 || res.statusCode == 401) return null;+ return unwrapApiResponse(res) as Map<String, dynamic>?;+ }++ /// Apply [ops] to the desk (backend routes/desk.ts); answers the desk as it is afterwards. Null+ /// under the same two conditions as [desk].+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {+ final res = await _dio.post(+ '/api/desk/ops',+ data: {'ops': ops},+ options: Options(headers: {'x-adapter-local': '1'}),+ );+ if (res.statusCode == 404 || res.statusCode == 401) return null;+ return unwrapApiResponse(res) as Map<String, dynamic>?;+ }+// -- the Harness Store: ratings and reviews (control plane, proxied by the local CLI) --Future<Map<String, dynamic>?> storeRatings() async {final res = await _dio.get('/api/store/ratings');diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 7599dd39b..ff6e03aa9 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -48,6 +48,7 @@ import '../widgets/engine_identity.dart'import '../store/store_screen.dart' show openStoreAgent;import 'dial_status.dart';import 'harness_placement.dart';+import 'desk_sync.dart';import 'pane_layout_store.dart';import 'terminal_pane.dart';import 'swarm.dart';@@ -661,6 +662,27 @@ class AppNotifier extends ChangeNotifier {/// Swarms own arrangements; a shared pane owns one live terminal controller.final List<Swarm> swarms = [Swarm(id: 'swarm-1')];++ // ── the desk: the account's tabs, the same on every computer ─────────────+ //+ // `desk_sync.dart` has the shape and the rules; this is the window's half.+ // Every layout change funnels through [_persistLayout], which diffs the+ // desk-shaped projection of `swarms` against what the desk last agreed to+ // and sends the difference as ops. A `desk_changed` push (backend → daemon →+ // here) or the 15 s poll fetches the document, and [_deskApply] reconciles+ // `swarms` to it — creating, closing, renaming and reordering tabs and their+ // panes, and touching nothing a window keeps for itself.+ final DeskSyncState _desk = DeskSyncState();+ Timer? _deskRetry;+ Future<void>? _deskJoining;+ @visibleForTesting+ DeskSyncState get deskSyncForTest => _desk;+ @visibleForTesting+ Future<void> deskStartForTest() => _deskStart(_authRevision);+ @visibleForTesting+ Future<void> deskFetchForTest() => _deskFetch();+ @visibleForTesting+ Future<void> deskFlushForTest() => _deskFlush();String _activeSwarmId = 'swarm-1';int _nextSwarmId = 2;// No tab cap, as in Chrome: only the visible tab's panes are built, so a background tab costs its@@ -829,7 +851,12 @@ class AppNotifier extends ChangeNotifier {while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {_nextSwarmId++;}- final swarm = Swarm(id: 'swarm-${_nextSwarmId++}', name: name);+ // A desk id from the start when the desk is on: the tab will be everyone's+ // the moment it holds something.+ final swarm = Swarm(+ id: _desk.enabled ? newDeskId() : 'swarm-${_nextSwarmId++}',+ name: name,+ );if (draft) {_draftSwarmReturns[swarm.id] =_draftSwarmReturns[activeSwarmId] ?? activeSwarmId;@@ -2596,6 +2623,9 @@ class AppNotifier extends ChangeNotifier {// The CLI has confirmed sign-in and daemon readiness. Display-name/avatar// metadata is independent of machine discovery and must not delay work.unawaited(_loadProfile());+ // The desk too: tabs from the other computers appear as intent, like the+ // restored ones, and attach as their machines answer.+ _deskEnsure(revision);try {await refreshMachines();} catch (error) {@@ -2720,6 +2750,7 @@ class AppNotifier extends ChangeNotifier {if (online && wasOffline && status == AppStatus.authenticated) {if (refetch && !machinesRefreshing) unawaited(retryMachines());if (currentUser == null) unawaited(_loadProfile());+ _deskEnsure(_authRevision);}notifyListeners();}@@ -2825,6 +2856,11 @@ class AppNotifier extends ChangeNotifier {/// In particular, multiple emptied tabs must not prevent the next restore.void _clearAccountWorkspace() {++_layoutRevision;+ // Sign-out sends the desk nothing: the tabs closing here are this window+ // leaving the account, not the person closing them.+ _deskRetry?.cancel();+ _deskRetry = null;+ _desk.reset();_stopAllOfflineRetries();_stopAllLinkRetries();_stopAllAgentSyncTimers();@@ -3761,6 +3797,9 @@ class AppNotifier extends ChangeNotifier {}final discoveryRevision = _authRevision;_sharingDiscoveryBusy = true;+ // A push that was missed is caught here: the desk read is one small+ // GET, and an unchanged revision applies nothing.+ if (_desk.enabled && _desk.pending.isEmpty) unawaited(_deskFetch());try {await refreshMachines();} catch (error) {@@ -4350,6 +4389,9 @@ class AppNotifier extends ChangeNotifier {return;}if (currentUser == null) unawaited(_loadProfile());+ // A boot that found the daemon still connecting finishes THROUGH here (see+ // `_loadProfile`), so the desk is joined here as well — once.+ _deskEnsure(revision);try {if (!await refreshMachines() || !_authWorkCurrent(revision)) return;if (!automatic) _lastError = null;@@ -6078,47 +6120,50 @@ class AppNotifier extends ChangeNotifier {return null;}- String _creationFailureMessage(String code, String? detail, String machine) =>- switch (code) {- 'INVALID_PROJECT_SOURCE' ||- 'INVALID_REPOSITORY' ||- 'PROJECT_PREPARATION_FAILED' ||- 'PROJECT_EXISTS' ||- 'CLONE_FAILED' ||- 'CLONE_TIMEOUT' ||- 'GIT_UNAVAILABLE' =>- detail ?? 'Could not prepare the project folder on $machine.',- 'CWD_NOT_FOUND' || 'INVALID_CWD' =>- 'The project folder is unavailable on $machine. '- 'Choose another folder and try again.',- 'TMUX_UNAVAILABLE' =>- 'Harness needs tmux to start harnesses on $machine. '- 'Install tmux there, then try again.',- 'CODEX_CLI_TOO_OLD' =>- detail ??- 'The installed Codex CLI on $machine is too old for Auto approvals. '- 'Update Codex, or choose Ask permissions.',- 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>- 'Update the harness CLI on this machine to start a harness',- 'INVALID_DSH' =>- 'This harness is not installed on $machine. '- '${detail ?? 'Install it there, then try again.'}',- 'PROMPT_UNSUPPORTED' =>- 'This engine cannot be opened with a first message on $machine.',- 'PROMPT_TOO_LONG' =>- 'This first task is too long for $machine. Shorten it and try again.',- 'AGENT_UNSUPPORTED' =>- 'This engine cannot be opened as a named agent on $machine.',- 'INVALID_AGENT' =>- 'This engine cannot be opened as that named agent on $machine.',- 'INVALID_PERMISSION_MODE' =>- 'This engine has no such permission mode on $machine.',- // A daemon that predates the terminal engine refuses it by name; the- // fix is the same one the other UNSUPPORTED codes ask for.- 'INVALID_ENGINE' =>- 'Update the harness CLI on $machine to open this kind of pane.',- _ => 'Could not start harness: ${detail ?? code}',- };+ String _creationFailureMessage(+ String code,+ String? detail,+ String machine,+ ) => switch (code) {+ 'INVALID_PROJECT_SOURCE' ||+ 'INVALID_REPOSITORY' ||+ 'PROJECT_PREPARATION_FAILED' ||+ 'PROJECT_EXISTS' ||+ 'CLONE_FAILED' ||+ 'CLONE_TIMEOUT' ||+ 'GIT_UNAVAILABLE' =>+ detail ?? 'Could not prepare the project folder on $machine.',+ 'CWD_NOT_FOUND' || 'INVALID_CWD' =>+ 'The project folder is unavailable on $machine. '+ 'Choose another folder and try again.',+ 'TMUX_UNAVAILABLE' =>+ 'Harness needs tmux to start harnesses on $machine. '+ 'Install tmux there, then try again.',+ 'CODEX_CLI_TOO_OLD' =>+ detail ??+ 'The installed Codex CLI on $machine is too old for Auto approvals. '+ 'Update Codex, or choose Ask permissions.',+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>+ 'Update the harness CLI on this machine to start a harness',+ 'INVALID_DSH' =>+ 'This harness is not installed on $machine. '+ '${detail ?? 'Install it there, then try again.'}',+ 'PROMPT_UNSUPPORTED' =>+ 'This engine cannot be opened with a first message on $machine.',+ 'PROMPT_TOO_LONG' =>+ 'This first task is too long for $machine. Shorten it and try again.',+ 'AGENT_UNSUPPORTED' =>+ 'This engine cannot be opened as a named agent on $machine.',+ 'INVALID_AGENT' =>+ 'This engine cannot be opened as that named agent on $machine.',+ 'INVALID_PERMISSION_MODE' =>+ 'This engine has no such permission mode on $machine.',+ // A daemon that predates the terminal engine refuses it by name; the+ // fix is the same one the other UNSUPPORTED codes ask for.+ 'INVALID_ENGINE' =>+ 'Update the harness CLI on $machine to open this kind of pane.',+ _ => 'Could not start harness: ${detail ?? code}',+ };/// A confirmed name collision happens before any process starts. Only then/// may an automatic suggestion advance to another name with a fresh receipt.@@ -8362,6 +8407,352 @@ class AppNotifier extends ChangeNotifier {Future<void> flushPaneLayout() =>_paneLayout?.flushSwarms() ?? Future<void>.value();+ // ── desk sync ────────────────────────────────────────────────────────────++ /// Which tabs are the desk's business: harness tabs that are not drafts. The+ /// Store tab, orchestrator tabs and an untouched New Tab are this window's.+ bool _deskTracks(Swarm swarm) =>+ swarm.kind == 'harness' && !isDraftSwarm(swarm.id);++ /// `swarms` as the desk would hold them.+ List<DeskTab> _deskProjection() => [+ for (final swarm in swarms)+ if (_deskTracks(swarm))+ DeskTab(+ id: swarm.id,+ name: swarm.name,+ nameIsCustom: swarm.nameIsCustom,+ panes: [+ for (final pane in swarm.panes)+ if (pane.agentId != null)+ DeskPaneRef(machineId: pane.machineId, agentId: pane.agentId!),+ ],+ ),+ ];++ /// First contact with the desk after sign-in. A daemon that predates the+ /// desk, or a signed-out one, answers null and this window keeps its tabs to+ /// itself. Otherwise the desk is read, this computer's own tabs from before+ /// the desk are given desk ids and seeded (every machine's tabs land; the+ /// person closes the extras), and the merged desk is applied.+ Future<void> _deskStart(int authRevision) async {+ if (_deskJoining != null) return _deskJoining;+ final run = _deskJoin(authRevision);+ _deskJoining = run;+ try {+ await run;+ } finally {+ if (identical(_deskJoining, run)) _deskJoining = null;+ }+ }++ /// Join the desk unless this window already has (or is joining now). Every+ /// path that finishes a sign-in calls this — the boot, the retry the boot+ /// hands over to when the daemon is still connecting, and the daemon's+ /// backend link coming back — because a daemon whose backend was offline+ /// answered the first read with an error, not with a desk.+ void _deskEnsure(int authRevision) {+ if (_desk.enabled || _deskJoining != null) return;+ unawaited(_deskStart(authRevision));+ }++ Future<void> _deskJoin(int authRevision) async {+ Map<String, dynamic>? raw;+ try {+ raw = await api.desk();+ } catch (error) {+ appLog.warn('desk', 'first read failed: $error');+ return;+ }+ if (_disposed || !_authWorkCurrent(authRevision)) return;+ final doc = DeskDoc.fromJson(raw);+ if (doc == null) {+ appLog.info('desk', 'not available here — tabs stay local');+ return;+ }+ _desk.enabled = true;+ // Tabs from before the desk carry per-window ids (`swarm-N`) two computers+ // would both mint. Give them desk ids once; the layout store keys by the+ // same string, so it follows on the next save.+ for (final swarm in swarms) {+ if (_deskTracks(swarm) && !isDeskId(swarm.id)) {+ final was = swarm.id;+ swarm.id = newDeskId();+ if (_activeSwarmId == was) _activeSwarmId = swarm.id;+ for (final entry in _draftSwarmReturns.entries.toList()) {+ if (entry.value == was) _draftSwarmReturns[entry.key] = swarm.id;+ }+ }+ }+ final own = _deskProjection();+ final unknown = own+ .where((t) => !doc.tabs.any((d) => d.id == t.id))+ .toList();+ _desk.revision = doc.revision;+ _desk.synced = doc.tabs;+ if (unknown.isNotEmpty) {+ _desk.pending.add({+ 'op': 'seed',+ 'tabs': [for (final t in unknown) t.toJson()],+ });+ }+ appLog.info(+ 'desk',+ 'joined at rev ${doc.revision} · ${doc.tabs.length} on the desk · ${unknown.length} of ours to seed',+ );+ _deskApply(doc);+ await _deskFlush();+ }++ /// Called from [_persistLayout]: whatever just changed, said to the desk as ops.+ void _deskQueueDiff() {+ if (!_desk.enabled) return;+ final projection = _deskProjection();+ final ops = deskDiff(_desk.synced, projection);+ if (ops.isEmpty) return;+ // Optimistic: this window believes its own edit. The desk's answer (or a+ // document from elsewhere) is applied over it, with the pending ops laid+ // back on top until they are acknowledged.+ _desk.synced = projection;+ _desk.pending.addAll(ops);+ appLog.debug('desk', 'queued ${ops.map((o) => o['op']).join(' ')}');+ unawaited(_deskFlush());+ }++ Future<void> _deskFlush() async {+ if (!_desk.enabled ||+ _desk.inFlight ||+ _desk.pending.isEmpty ||+ _disposed) {+ return;+ }+ _desk.inFlight = true;+ final authRevision = _authRevision;+ final batch = List<Map<String, dynamic>>.from(_desk.pending);+ Map<String, dynamic>? raw;+ try {+ raw = await api.deskOps(batch);+ } catch (error) {+ _desk.inFlight = false;+ if (_disposed || !_authWorkCurrent(authRevision)) return;+ // Kept, not dropped: a tab closed while the backend was unreachable is+ // still closed everywhere once it is back. Backoff, capped at a minute.+ _desk.failures++;+ final wait = Duration(+ seconds: (5 * (1 << (_desk.failures - 1).clamp(0, 4))).clamp(5, 60),+ );+ appLog.warn(+ 'desk',+ 'write failed (${batch.length} ops, retry in ${wait.inSeconds}s): $error',+ );+ _deskRetry?.cancel();+ _deskRetry = Timer(wait, () => unawaited(_deskFlush()));+ return;+ }+ _desk.inFlight = false;+ if (_disposed || !_authWorkCurrent(authRevision)) return;+ _desk.failures = 0;+ _deskRetry?.cancel();+ _deskRetry = null;+ // Acknowledged (or, on null, refused for good — the daemon lost its+ // session): these ops are no longer pending either way.+ _desk.pending.removeRange(0, batch.length.clamp(0, _desk.pending.length));+ final doc = DeskDoc.fromJson(raw);+ if (doc == null) {+ appLog.info(+ 'desk',+ 'write not accepted — tabs stay local until the next sign-in',+ );+ _desk.enabled = false;+ _desk.pending.clear();+ return;+ }+ _deskApply(doc);+ if (_desk.pending.isNotEmpty) unawaited(_deskFlush());+ }++ Future<void> _deskFetch() async {+ if (!_desk.enabled || _disposed) return;+ final authRevision = _authRevision;+ Map<String, dynamic>? raw;+ try {+ raw = await api.desk();+ } catch (error) {+ appLog.warn('desk', 'read failed: $error');+ return;+ }+ if (_disposed || !_authWorkCurrent(authRevision)) return;+ final doc = DeskDoc.fromJson(raw);+ if (doc == null) return;+ _deskApply(doc);+ }++ /// Reconcile `swarms` to [doc], with this window's unacknowledged ops laid+ /// over it. Ignores a document older than one already applied.+ void _deskApply(DeskDoc doc) {+ if (doc.revision < _desk.revision) return;+ _desk.revision = doc.revision;+ final target = applyDeskOps(doc.tabs, _desk.pending);+ _desk.synced = target;+ _deskReconcile(target);+ }++ /// Make `swarms` say what [target] says, and no more: tabs the desk closed go+ /// (their streams released unless another tab still shows them), tabs it+ /// opened arrive as intent and attach as their machines answer, names the+ /// person chose follow, order follows. Focus, zoom, sizes, pins, viewers and+ /// this window's own local-only tabs are left exactly where they were.+ void _deskReconcile(List<DeskTab> target) {+ final targetById = {for (final t in target) t.id: t};+ final before = _deskProjection();+ final released = <TerminalPane>[];++ // Tabs the desk no longer has.+ final kept = <Swarm>[];+ for (final swarm in swarms) {+ if (_deskTracks(swarm) && !targetById.containsKey(swarm.id)) {+ released.addAll(swarm.panes);+ continue;+ }+ kept.add(swarm);+ }+ swarms+ ..clear()+ ..addAll(kept);++ // Tabs, names and panes.+ for (final tab in target) {+ var swarm = swarms.where((s) => s.id == tab.id).firstOrNull;+ if (swarm == null) {+ swarm = Swarm(+ id: tab.id,+ name: tab.name,+ nameIsCustom: tab.nameIsCustom,+ );+ swarms.add(swarm);+ } else if (tab.nameIsCustom &&+ (swarm.name != tab.name || !swarm.nameIsCustom)) {+ swarm.name = tab.name;+ swarm.nameIsCustom = true;+ }+ final wanted = {for (final p in tab.panes) p.key};+ for (final pane in swarm.panes.toList()) {+ if (pane.agentId == null) continue;+ if (wanted.contains('${pane.machineId}\u0000${pane.agentId}')) continue;+ swarm.remove(pane);+ released.add(pane);+ for (final viewer in swarm.panes.toList()) {+ if (viewer.isWeb &&+ viewer.machineId == pane.machineId &&+ viewer.ownerAgentId == pane.agentId) {+ swarm.remove(viewer);+ }+ }+ }+ for (var i = 0; i < tab.panes.length; i++) {+ final ref = tab.panes[i];+ final existing = swarm.panes+ .where(+ (p) => p.machineId == ref.machineId && p.agentId == ref.agentId,+ )+ .firstOrNull;+ if (existing != null) continue;+ // One TerminalPane per (machine, agent) across tabs — the same rule the+ // restore keeps — so a second tab showing an agent reuses its stream.+ final pane =+ allPanes+ .where(+ (p) =>+ p.machineId == ref.machineId && p.agentId == ref.agentId,+ )+ .firstOrNull ??+ TerminalPane(+ id: _nextPaneId++,+ machineId: ref.machineId,+ agentId: ref.agentId,+ );+ swarm.panes.insert(i.clamp(0, swarm.panes.length), pane);+ swarm.focusedPaneId ??= pane.id;+ }+ // Order among agent panes, viewers riding beside their owners.+ final agentOrder = {+ for (var i = 0; i < tab.panes.length; i++) tab.panes[i].key: i,+ };+ final ordered = swarm.panes.where((p) => p.agentId != null).toList()+ ..sort(+ (a, b) => (agentOrder['${a.machineId}\u0000${a.agentId}'] ?? 0)+ .compareTo(agentOrder['${b.machineId}\u0000${b.agentId}'] ?? 0),+ );+ final rebuilt = <TerminalPane>[];+ for (final pane in ordered) {+ rebuilt.add(pane);+ rebuilt.addAll(+ swarm.panes.where(+ (v) =>+ v.isWeb &&+ v.machineId == pane.machineId &&+ v.ownerAgentId == pane.agentId,+ ),+ );+ }+ for (final pane in swarm.panes) {+ if (!rebuilt.contains(pane)) {+ rebuilt.add(pane);+ }+ }+ swarm.panes+ ..clear()+ ..addAll(rebuilt);+ if (!swarm.nameIsCustom &&+ swarm.titleAgentId == null &&+ swarm.panes.isNotEmpty) {+ swarm.titleMachineId = swarm.panes.first.machineId;+ swarm.titleAgentId = swarm.panes.first.agentId;+ }+ }++ // Tab order: the desk's, with this window's local-only tabs where they were.+ final localOnly = <(int, Swarm)>[];+ for (var i = 0; i < kept.length; i++) {+ if (!_deskTracks(kept[i])) localOnly.add((i, kept[i]));+ }+ final ordered = <Swarm>[+ for (final tab in target) swarms.firstWhere((s) => s.id == tab.id),+ ];+ for (final (index, swarm) in localOnly) {+ ordered.insert(index.clamp(0, ordered.length), swarm);+ }+ swarms+ ..clear()+ ..addAll(ordered);+ if (swarms.isEmpty) swarms.add(Swarm(id: 'swarm-${_nextSwarmId++}'));+ if (!swarms.any((s) => s.id == _activeSwarmId)) {+ _activeSwarmId = swarms.first.id;+ selectedMachineId = focusedPane?.machineId;+ }++ // Streams nobody shows any more.+ for (final pane in released.toSet()) {+ if (!allPanes.contains(pane)) {+ unawaited(_detachSession(pane, sendClose: true));+ }+ }+ _settlePins();+ final after = _deskProjection();+ if (deskDiff(before, after).isNotEmpty) {+ appLog.debug(+ 'desk',+ 'applied rev ${_desk.revision} · ${swarms.length} tabs',+ );+ }+ _persistLayout();+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine, retryExisting: false);+ }+ _announceAppFocus();+ notifyListeners();+ }+void _persistLayout() {_draftSwarmReturns.removeWhere((id, _) {final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;@@ -8372,6 +8763,7 @@ class AppNotifier extends ChangeNotifier {});_layoutRevision++;_announceOpenPanesToDial();+ _deskQueueDiff();final saved = swarms.where((swarm) => !isDraftSwarm(swarm.id)).toList();if (saved.isEmpty) return;final savedActive = isDraftSwarm(activeSwarmId)@@ -8810,6 +9202,14 @@ class AppNotifier extends ChangeNotifier {}}break;+ case 'desk_changed':+ // Another window — on another computer, or this one — changed the+ // tabs. The payload is only the revision; the document is fetched.+ final deskRevision = payload['revision'];+ if (deskRevision is! int || deskRevision > _desk.revision) {+ unawaited(_deskFetch());+ }+ break;case 'dial_open':// A notification was tapped on the dial. Unlike `dial_focus` this asks for a tile of its own —// see openAgentFromDial for why a finished turn is not a replacement for what is on screen.diff --git a/desktop/lib/state/desk_sync.dart b/desktop/lib/state/desk_sync.dartnew file mode 100644index 000000000..2d2f58138--- /dev/null+++ b/desktop/lib/state/desk_sync.dart@@ -0,0 +1,326 @@+/// The desk: the account's tabs, the same on every computer.+///+/// The backend holds one document per user — `{ revision, tabs[] }`, each tab+/// `{ id, name, nameIsCustom?, panes: [{machineId, agentId}] }` — and changes it+/// through small idempotent ops (backend `lib/desk.ts` is the authority; the+/// copy of its rules here is for optimistic re-application only). This file is+/// the pure half: what a tab looks like on the wire, how two snapshots differ+/// as ops, and how ops apply to a snapshot. `AppNotifier` owns the other half —+/// turning `swarms` into a snapshot and a snapshot back into `swarms`.+///+/// What is NOT on the desk, by decision (owner, 2026-09-21): the active tab,+/// focus, zoom, pinned slots, presets, pane sizes, composer visibility, drafts,+/// Recently Closed, the Store tab and orchestrator tabs. Windows differ.+library;++import 'dart:math';++class DeskPaneRef {+ const DeskPaneRef({required this.machineId, required this.agentId});+ final String machineId;+ final String agentId;++ String get key => '$machineId\u0000$agentId';++ Map<String, dynamic> toJson() => {'machineId': machineId, 'agentId': agentId};++ static DeskPaneRef? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final machineId = raw['machineId'];+ final agentId = raw['agentId'];+ if (machineId is! String || machineId.isEmpty) return null;+ if (agentId is! String || agentId.isEmpty) return null;+ return DeskPaneRef(machineId: machineId, agentId: agentId);+ }++ @override+ bool operator ==(Object other) =>+ other is DeskPaneRef &&+ other.machineId == machineId &&+ other.agentId == agentId;++ @override+ int get hashCode => Object.hash(machineId, agentId);+}++class DeskTab {+ const DeskTab({+ required this.id,+ required this.name,+ this.nameIsCustom = false,+ this.panes = const [],+ });+ final String id;+ final String name;+ final bool nameIsCustom;+ final List<DeskPaneRef> panes;++ DeskTab copyWith({+ String? name,+ bool? nameIsCustom,+ List<DeskPaneRef>? panes,+ }) => DeskTab(+ id: id,+ name: name ?? this.name,+ nameIsCustom: nameIsCustom ?? this.nameIsCustom,+ panes: panes ?? this.panes,+ );++ Map<String, dynamic> toJson() => {+ 'id': id,+ 'name': name,+ if (nameIsCustom) 'nameIsCustom': true,+ 'panes': [for (final p in panes) p.toJson()],+ };++ static DeskTab? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final id = raw['id'];+ final name = raw['name'];+ if (id is! String || id.isEmpty || name is! String) return null;+ final panes = <DeskPaneRef>[];+ final seen = <String>{};+ if (raw['panes'] is List) {+ for (final item in raw['panes'] as List) {+ final pane = DeskPaneRef.fromJson(item);+ if (pane != null && seen.add(pane.key)) panes.add(pane);+ }+ }+ return DeskTab(+ id: id,+ name: name,+ nameIsCustom: raw['nameIsCustom'] == true,+ panes: panes,+ );+ }+}++class DeskDoc {+ const DeskDoc({required this.revision, required this.tabs});+ final int revision;+ final List<DeskTab> tabs;++ static DeskDoc? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final revision = raw['revision'];+ if (revision is! int) return null;+ final tabs = <DeskTab>[];+ final seen = <String>{};+ if (raw['tabs'] is List) {+ for (final item in raw['tabs'] as List) {+ final tab = DeskTab.fromJson(item);+ if (tab != null && seen.add(tab.id)) tabs.add(tab);+ }+ }+ return DeskDoc(revision: revision, tabs: tabs);+ }+}++/// A desk id: a tab that has been on the desk (or is bound for it) carries a+/// random 128-bit id, never the per-window `swarm-N` two computers would both+/// mint. `isDeskId` is how a restored layout from before the desk is told apart.+String newDeskId() {+ final random = Random.secure();+ final bytes = List<int>.generate(16, (_) => random.nextInt(256));+ return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();+}++final _deskIdShape = RegExp(r'^[0-9a-f]{32}$');+bool isDeskId(String id) => _deskIdShape.hasMatch(id);++/// The ops that turn [before] into [after], in an order the backend applies+/// left to right: closes first, then creates, then renames and pane changes,+/// then order. Names are compared only where the person named the tab —+/// a derived name is each window's own to derive.+List<Map<String, dynamic>> deskDiff(List<DeskTab> before, List<DeskTab> after) {+ final ops = <Map<String, dynamic>>[];+ final beforeById = {for (final t in before) t.id: t};+ final afterById = {for (final t in after) t.id: t};++ for (final old in before) {+ if (!afterById.containsKey(old.id)) {+ ops.add({'op': 'tab.close', 'id': old.id});+ }+ }+ for (var i = 0; i < after.length; i++) {+ final tab = after[i];+ if (beforeById.containsKey(tab.id)) continue;+ ops.add({+ 'op': 'tab.create',+ 'id': tab.id,+ 'name': tab.name,+ if (tab.nameIsCustom) 'nameIsCustom': true,+ 'index': i,+ });+ for (var j = 0; j < tab.panes.length; j++) {+ ops.add({+ 'op': 'pane.add',+ 'tabId': tab.id,+ ...tab.panes[j].toJson(),+ 'index': j,+ });+ }+ }+ for (final tab in after) {+ final old = beforeById[tab.id];+ if (old == null) continue;+ if (tab.nameIsCustom && (tab.name != old.name || !old.nameIsCustom)) {+ ops.add({+ 'op': 'tab.rename',+ 'id': tab.id,+ 'name': tab.name,+ 'nameIsCustom': true,+ });+ }+ final oldKeys = old.panes.map((p) => p.key).toSet();+ final newKeys = tab.panes.map((p) => p.key).toSet();+ for (final p in old.panes) {+ if (!newKeys.contains(p.key)) {+ ops.add({'op': 'pane.remove', 'tabId': tab.id, ...p.toJson()});+ }+ }+ for (var j = 0; j < tab.panes.length; j++) {+ final p = tab.panes[j];+ if (!oldKeys.contains(p.key)) {+ ops.add({'op': 'pane.add', 'tabId': tab.id, ...p.toJson(), 'index': j});+ }+ }+ // Order among the panes both sides have: move the ones out of place.+ final kept = old.panes+ .where((p) => newKeys.contains(p.key))+ .map((p) => p.key)+ .toList();+ final wanted = tab.panes+ .where((p) => oldKeys.contains(p.key))+ .map((p) => p.key)+ .toList();+ if (!_sameOrder(kept, wanted)) {+ for (var j = 0; j < tab.panes.length; j++) {+ if (oldKeys.contains(tab.panes[j].key)) {+ ops.add({+ 'op': 'pane.move',+ 'tabId': tab.id,+ ...tab.panes[j].toJson(),+ 'index': j,+ });+ }+ }+ }+ }+ // Tab order, over the tabs both sides have.+ final keptTabs = before+ .where((t) => afterById.containsKey(t.id))+ .map((t) => t.id)+ .toList();+ final wantedTabs = after+ .where((t) => beforeById.containsKey(t.id))+ .map((t) => t.id)+ .toList();+ if (!_sameOrder(keptTabs, wantedTabs)) {+ for (var i = 0; i < after.length; i++) {+ if (beforeById.containsKey(after[i].id)) {+ ops.add({'op': 'tab.move', 'id': after[i].id, 'index': i});+ }+ }+ }+ return ops;+}++bool _sameOrder(List<String> a, List<String> b) {+ if (a.length != b.length) return false;+ for (var i = 0; i < a.length; i++) {+ if (a[i] != b[i]) return false;+ }+ return true;+}++/// The backend's rules, replayed here so a window can lay its unacknowledged+/// ops over a document that arrived meanwhile. Idempotent; an op on a tab+/// that is gone changes nothing.+List<DeskTab> applyDeskOps(List<DeskTab> tabs, List<Map<String, dynamic>> ops) {+ var next = [+ for (final t in tabs) t.copyWith(panes: [...t.panes]),+ ];+ int at(String id) => next.indexWhere((t) => t.id == id);+ int clamp(Object? index, int length) =>+ index is int ? index.clamp(0, length) : length;+ for (final op in ops) {+ switch (op['op']) {+ case 'tab.create':+ final id = op['id'] as String;+ if (at(id) >= 0) break;+ next.insert(+ clamp(op['index'], next.length),+ DeskTab(+ id: id,+ name: op['name'] as String,+ nameIsCustom: op['nameIsCustom'] == true,+ panes: [],+ ),+ );+ case 'tab.close':+ final i = at(op['id'] as String);+ if (i >= 0) next.removeAt(i);+ case 'tab.rename':+ final i = at(op['id'] as String);+ if (i < 0) break;+ next[i] = next[i].copyWith(+ name: op['name'] as String,+ nameIsCustom: op['nameIsCustom'] == true || next[i].nameIsCustom,+ );+ case 'tab.move':+ final i = at(op['id'] as String);+ if (i < 0) break;+ final tab = next.removeAt(i);+ next.insert(clamp(op['index'], next.length), tab);+ case 'pane.add':+ final i = at(op['tabId'] as String);+ if (i < 0) break;+ final pane = DeskPaneRef.fromJson(op);+ if (pane == null || next[i].panes.contains(pane)) break;+ next[i].panes.insert(clamp(op['index'], next[i].panes.length), pane);+ case 'pane.remove':+ final i = at(op['tabId'] as String);+ if (i < 0) break;+ final pane = DeskPaneRef.fromJson(op);+ if (pane != null) next[i].panes.remove(pane);+ case 'pane.move':+ final i = at(op['tabId'] as String);+ if (i < 0) break;+ final pane = DeskPaneRef.fromJson(op);+ if (pane == null) break;+ final j = next[i].panes.indexOf(pane);+ if (j < 0) break;+ next[i].panes.removeAt(j);+ next[i].panes.insert(clamp(op['index'], next[i].panes.length), pane);+ case 'seed':+ for (final raw in (op['tabs'] as List? ?? const [])) {+ final tab = DeskTab.fromJson(raw);+ if (tab == null || at(tab.id) >= 0) continue;+ next.add(tab.copyWith(panes: [...tab.panes]));+ }+ }+ }+ return next;+}++/// What a window holds about its sync with the desk: the last snapshot it and+/// the desk agreed on, the ops it has sent that the desk has not yet answered,+/// and the desk's revision as last heard.+class DeskSyncState {+ int revision = 0;+ List<DeskTab> synced = const [];+ final List<Map<String, dynamic>> pending = [];+ bool enabled = false;+ bool inFlight = false;+ int failures = 0;++ void reset() {+ revision = 0;+ synced = const [];+ pending.clear();+ enabled = false;+ inFlight = false;+ failures = 0;+ }+}diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex 2fe6706e5..8ffb628b8 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -47,7 +47,10 @@ class Swarm {? defaultName: name;- final String id;+ /// Mutable for one reason: a tab from before the desk (`swarm-N`, this+ /// window's numbering) is given a desk id on the first sync+ /// (`AppNotifier._deskStart`). Nothing else ever writes it.+ String id;String name;bool nameIsCustom;String? titleMachineId, titleAgentId;diff --git a/desktop/test/desk_sync_test.dart b/desktop/test/desk_sync_test.dartnew file mode 100644index 000000000..dac278c93--- /dev/null+++ b/desktop/test/desk_sync_test.dart@@ -0,0 +1,372 @@+// The desk: the account's tabs, the same on every computer. The pure half+// (diff and replay) and the window's half (a document becomes `swarms`, an+// edit becomes ops, and what a window keeps for itself stays put).+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/state/desk_sync.dart';++import 'swarm_state_test.dart' show createApp;++DeskTab tab(+ String id, {+ String name = 'Tab',+ bool custom = false,+ List<String> agents = const [],+}) => DeskTab(+ id: id,+ name: name,+ nameIsCustom: custom,+ panes: [for (final a in agents) DeskPaneRef(machineId: 'm', agentId: a)],+);++/// The daemon's desk proxy, scripted: a document to hand out, the ops it was+/// asked to apply (applied with the same rules the backend uses), or a failure.+class _DeskApi extends ApiClient {+ _DeskApi() : super(config: AppConfig.dev, session: AuthSession());+ DeskDoc? doc = const DeskDoc(revision: 0, tabs: []);+ bool available = true;+ Object? failWith;+ final batches = <List<Map<String, dynamic>>>[];++ Map<String, dynamic>? _json(DeskDoc d) => {+ 'revision': d.revision,+ 'tabs': [for (final t in d.tabs) t.toJson()],+ };++ @override+ Future<Map<String, dynamic>?> desk() async {+ if (failWith != null) throw failWith!;+ if (!available || doc == null) return null;+ return _json(doc!);+ }++ @override+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {+ if (failWith != null) throw failWith!;+ if (!available || doc == null) return null;+ batches.add(ops);+ final next = applyDeskOps(doc!.tabs, ops);+ doc = DeskDoc(revision: doc!.revision + 1, tabs: next);+ return _json(doc!);+ }+}++void main() {+ group('deskDiff', () {+ test('creates a tab with its panes, closes, renames only what the person named, and reorders', () {+ final before = [+ tab('a', agents: ['x']),+ tab('b', name: 'derived'),+ ];+ final after = [+ tab('b', name: 'Home', custom: true),+ tab('c', name: 'New', agents: ['y', 'z']),+ ];+ final ops = deskDiff(before, after);+ expect(ops.map((o) => o['op']), [+ 'tab.close',+ 'tab.create',+ 'pane.add',+ 'pane.add',+ 'tab.rename',+ ]);+ expect(ops[1], {+ 'op': 'tab.create',+ 'id': 'c',+ 'name': 'New',+ 'index': 1,+ });+ expect(ops[2], {+ 'op': 'pane.add',+ 'tabId': 'c',+ 'machineId': 'm',+ 'agentId': 'y',+ 'index': 0,+ });+ expect(ops[4], {+ 'op': 'tab.rename',+ 'id': 'b',+ 'name': 'Home',+ 'nameIsCustom': true,+ });+ // A derived name that differs is each window's own to derive — no op.+ expect(+ deskDiff([tab('b', name: 'one')], [tab('b', name: 'two')]),+ isEmpty,+ );+ // Order of tabs both sides have.+ expect(+ deskDiff(+ [tab('a'), tab('b')],+ [tab('b'), tab('a')],+ ).map((o) => o['op']),+ ['tab.move', 'tab.move'],+ );+ });++ test('adds, removes and moves panes within a tab', () {+ final ops = deskDiff(+ [+ tab('a', agents: ['x', 'y']),+ ],+ [+ tab('a', agents: ['y', 'z']),+ ],+ );+ expect(ops, [+ {'op': 'pane.remove', 'tabId': 'a', 'machineId': 'm', 'agentId': 'x'},+ {+ 'op': 'pane.add',+ 'tabId': 'a',+ 'machineId': 'm',+ 'agentId': 'z',+ 'index': 1,+ },+ ]);+ final moved = deskDiff(+ [+ tab('a', agents: ['x', 'y']),+ ],+ [+ tab('a', agents: ['y', 'x']),+ ],+ );+ expect(moved.map((o) => o['op']), ['pane.move', 'pane.move']);+ expect(+ deskDiff(+ [+ tab('a', agents: ['x']),+ ],+ [+ tab('a', agents: ['x']),+ ],+ ),+ isEmpty,+ );+ });++ test(+ 'replays like the backend: idempotent, and nothing on a tab that is gone',+ () {+ final tabs = applyDeskOps(+ [tab('a')],+ [+ {'op': 'pane.add', 'tabId': 'a', 'machineId': 'm', 'agentId': 'x'},+ {'op': 'pane.add', 'tabId': 'a', 'machineId': 'm', 'agentId': 'x'},+ {'op': 'tab.close', 'id': 'a'},+ {'op': 'pane.add', 'tabId': 'a', 'machineId': 'm', 'agentId': 'y'},+ {'op': 'tab.create', 'id': 'b', 'name': 'B', 'index': 0},+ {'op': 'tab.create', 'id': 'b', 'name': 'B'},+ ],+ );+ expect(tabs.map((t) => t.id), ['b']);+ // A diff, replayed, is the "after" it was taken from.+ final before = [+ tab('a', agents: ['x', 'y']),+ tab('b'),+ ];+ final after = [+ tab('b', name: 'Home', custom: true),+ tab('a', agents: ['y']),+ tab('c', agents: ['z']),+ ];+ final replayed = applyDeskOps(before, deskDiff(before, after));+ expect(+ [for (final t in replayed) t.toJson()],+ [for (final t in after) t.toJson()],+ );+ },+ );++ test(+ 'desk ids are 32 hex characters; a window\'s own numbering is not one',+ () {+ expect(isDeskId(newDeskId()), isTrue);+ expect(newDeskId(), isNot(newDeskId()));+ expect(isDeskId('swarm-3'), isFalse);+ },+ );+ });++ group('the window and the desk', () {+ test('joins the desk: its own tabs get desk ids and are seeded, the desk\'s tabs appear as intent', () async {+ final api = _DeskApi()+ ..doc = DeskDoc(+ revision: 4,+ tabs: [+ tab(+ 'd1',+ name: 'From the other Mac',+ custom: true,+ agents: ['a5', 'a6'],+ ),+ ],+ );+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ await app.addAgentToSwarm(+ 'm',+ 'a0',+ ); // this window's own tab, numbered swarm-N+ final own = app.activeSwarm;+ expect(isDeskId(own.id), isFalse);++ await app.deskStartForTest();++ expect(+ isDeskId(own.id),+ isTrue,+ reason: 'the local tab was given a desk id',+ );+ expect(api.batches.single.single['op'], 'seed');+ // The desk's own tabs first, this computer's after them — that is where the seed puts them.+ expect(app.swarms.map((s) => s.id), ['d1', own.id]);+ final remote = app.swarms.first;+ expect(remote.name, 'From the other Mac');+ expect(remote.panes.map((p) => p.agentId), ['a5', 'a6']);+ expect(+ remote.panes.every((p) => p.session == null),+ isTrue,+ reason: 'intent only until the machine answers',+ );+ expect(+ app.activeSwarmId,+ own.id,+ reason: 'the active tab is this window\'s',+ );+ expect(app.deskSyncForTest.revision, 5);+ expect(app.deskSyncForTest.pending, isEmpty);+ });++ test(+ 'says every edit as ops: new tab, a pane, a rename, an order, a close',+ () async {+ final api = _DeskApi();+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ await app.deskStartForTest();+ api.batches.clear();++ app.newSwarm(name: 'Work');+ final work = app.activeSwarm;+ expect(isDeskId(work.id), isTrue);+ await app.addAgentToSwarm('m', 'a1');+ app.renameSwarm(work.id, 'Real work');+ app.newSwarm(name: 'Second');+ final second = app.activeSwarm;+ app.reorderSwarm(second.id, 0);+ await app.closeSwarm(work.id);+ await Future<void>.delayed(Duration.zero);++ final sent = api.batches.expand((b) => b).map((o) => o['op']).toList();+ expect(+ sent,+ containsAllInOrder([+ 'tab.create',+ 'pane.add',+ 'tab.rename',+ 'tab.create',+ 'tab.move',+ 'tab.close',+ ]),+ );+ // The starter tab this window opened with is on the desk too (empty, unnamed) — a tab is a tab.+ final ids = api.doc!.tabs.map((t) => t.id).toList();+ expect(ids, contains(second.id));+ expect(ids, isNot(contains(work.id)));+ expect(+ ids,+ app.swarms.map((s) => s.id).toList(),+ reason: 'the desk and the window agree on order',+ );+ expect(app.deskSyncForTest.pending, isEmpty);+ },+ );++ test('a desk_changed push closes a tab closed elsewhere and opens one opened elsewhere, keeping this window\'s focus', () async {+ final api = _DeskApi()+ ..doc = DeskDoc(+ revision: 1,+ tabs: [+ tab('d1', name: 'One', custom: true, agents: ['a1', 'a2']),+ tab('d2', name: 'Two', custom: true, agents: ['a3']),+ ],+ );+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ await app.deskStartForTest();+ api.batches.clear();+ app.selectSwarm('d1');+ final d1 = app.activeSwarm;+ final second = d1.panes[1];+ app.focusPane(second.id);+ expect(d1.focusedPaneId, second.id);++ // The other Mac: closed Two, renamed One, added a pane to One, opened Three.+ api.doc = DeskDoc(+ revision: 9,+ tabs: [+ tab('d3', name: 'Three', custom: true, agents: ['a9']),+ tab(+ 'd1',+ name: 'One, really',+ custom: true,+ agents: ['a1', 'a2', 'a4'],+ ),+ ],+ );+ await app.handleEventForTest('m', {+ 'type': 'desk_changed',+ 'payload': {'revision': 9},+ });+ await Future<void>.delayed(Duration.zero);++ // This window's starter tab went too: the other Mac's document did not have it.+ expect(app.swarms.map((s) => s.id), ['d3', 'd1']);+ expect(app.activeSwarmId, 'd1');+ expect(d1.name, 'One, really');+ expect(d1.panes.map((p) => p.agentId), ['a1', 'a2', 'a4']);+ expect(d1.focusedPaneId, second.id, reason: 'focus is this window\'s');+ expect(+ api.batches,+ isEmpty,+ reason: 'applying the desk sends nothing back',+ );+ });++ test('keeps its ops while the backend is unreachable and sends them once it is back', () async {+ final api = _DeskApi();+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ await app.deskStartForTest();+ api.failWith = StateError('offline');+ app.newSwarm(name: 'Offline work');+ final offline = app.activeSwarm;+ await Future<void>.delayed(Duration.zero);+ expect(app.deskSyncForTest.pending, isNotEmpty);+ expect(api.doc!.tabs.map((t) => t.id), isNot(contains(offline.id)));++ api.failWith = null;+ await app.deskFlushForTest();+ expect(api.doc!.tabs.map((t) => t.id), contains(offline.id));+ expect(app.deskSyncForTest.pending, isEmpty);+ });++ test(+ 'a daemon without a desk leaves the window as it was: local ids, no ops',+ () async {+ final api = _DeskApi()..available = false;+ final app = createApp()..api = api;+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ await app.deskStartForTest();+ expect(app.deskSyncForTest.enabled, isFalse);+ app.newSwarm(name: 'Local');+ expect(isDeskId(app.activeSwarm.id), isFalse);+ expect(api.batches, isEmpty);+ },+ );+ });+}