Skip to content

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.

Batch K: #2015 #2055 #2064 #2029 #2044 (#2066)

0xken1559cfaaad7226
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index 03bfdc1c3..1e59b0e99 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -5,9 +5,10 @@ import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
-import { PrismaClient, type Prisma } from '@prisma/client'
+import { PrismaClient, type Prisma, type SuperTabDelivery } from '@prisma/client'
import type { AuthUser } from '../src/lib/ssoAuth.js'
-import { SuperTabStore, type SuperTabStoreHooks } from '../src/superTabs/store.js'
+import { SuperTabStore, type Polled, type SuperTabStoreHooks } from '../src/superTabs/store.js'
+import { SWEEP_EVERY_MS } from '../src/superTabs/liveness.js'
import { stableId } from '../src/superTabs/model.js'
import type { Command } from '../src/superTabs/commands.js'
import type { MachineObservation } from '../src/superTabs/machines.js'
@@ -697,7 +698,7 @@ describe('the delivery poll of an agent with nothing waiting', () => {
counted.ops.length = 0
f.clock.now += 29_999
expect(await f.timed.deliveries(host, f.tab, f.lead)).toEqual([])
- expect(counted.ops).toEqual(['SuperTabDelivery.findFirst'])
+ expect(counted.ops).toEqual(['SuperTabDelivery.findMany'])
counted.ops.length = 0
f.clock.now += 1
expect(await f.timed.deliveries(host, f.tab, f.lead)).toEqual([])
@@ -773,15 +774,15 @@ describe('the delivery poll of an agent with nothing waiting', () => {
// own full polls, so the one-row answer held only as often as a host met the same pod twice (stability roadmap 2.4).
it('answers from one indexed read on another server once any server ran the full poll, when they share the memory', async () => {
const counted = counting()
- const shared = new Map<string, number>()
- const polls = { get: async (key: string) => shared.get(key), set: async (key: string, at: number) => { shared.set(key, at) } }
+ const shared = new Map<string, Polled>()
+ const polls = { get: async (key: string) => shared.get(key), set: async (key: string, polled: Polled) => { shared.set(key, polled) } }
const f = await swarm({ client: counted.client, hooks: { polls } })
const other = new SuperTabStore(counted.client, () => f.clock.now, null, { polls })
expect(await f.timed.deliveries(host, f.tab, f.lead)).toEqual([])
counted.ops.length = 0
f.clock.now += 1_000
expect(await other.deliveries(host, f.tab, f.lead)).toEqual([])
- expect(counted.ops).toEqual(['SuperTabDelivery.findFirst'])
+ expect(counted.ops).toEqual(['SuperTabDelivery.findMany'])
})
it('runs the full checked poll each time while the shared memory cannot be read or written, and still answers', async () => {
@@ -808,6 +809,219 @@ describe('the delivery poll of an agent with nothing waiting', () => {
})
})
+// A delivery its host cannot type yet (a permission prompt, a draft, an idle wait) stays claimed and held, possibly for hours,
+// while the host polls each second (Diego, 10-28): the poll answers it from one indexed read while nothing it relied on moved.
+describe('the delivery poll of an agent with a held delivery', () => {
+ // The open deliveries, then the grant the host speaks for its agent under, read outside the Swarm (store.ts grantHolds):
+ // its contributor's Workspace membership, its machine and, lent by host to owner here, the contributor and the share.
+ const HELD_READS = ['SuperTabDelivery.findMany', 'SwarmWorkspaceMember.findUnique', 'Machine.findFirst', 'User.findUnique', 'MachineShare.findUnique']
+ /** A person's message to the Lead, read by a full poll, claimed and held by its host. */
+ const held = async (f: Awaited<ReturnType<typeof swarm>>) => {
+ const sent = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Status?', replyTo: null, recipientIds: [] })
+ const [row] = await f.timed.deliveries(host, f.tab, f.lead)
+ expect(row!.messageId).toBe(sent.result.messageId)
+ await f.timed.delivery(host, f.tab, f.lead, row!.id, { type: 'claim', claimId: 'claim-1' })
+ await f.timed.delivery(host, f.tab, f.lead, row!.id, { type: 'hold', claimId: 'claim-1', reason: 'team_waiting_user' })
+ return row!
+ }
+
+ it('answers the next poll without loading the Swarm: its open deliveries and its host\'s grant, each one indexed read', async () => {
+ const counted = counting()
+ const f = await swarm({ client: counted.client })
+ const row = await held(f)
+ f.clock.now += 1_000
+ await f.timed.deliveries(host, f.tab, f.lead)
+ counted.ops.length = 0
+ f.clock.now += 1_000
+ const rows = await f.timed.deliveries(host, f.tab, f.lead)
+ expect(counted.ops).toEqual(HELD_READS)
+ expect(rows.map(r => [r.id, r.status, r.holdReason])).toEqual([[row.id, 'claimed', 'team_waiting_user']])
+ })
+
+ it('answers a worker\'s held delivery from the same reads', async () => {
+ const counted = counting()
+ const f = await swarm({ client: counted.client })
+ const sent = await f.execute({ type: 'message.send', conversationId: f.group, text: 'Status?', replyTo: null, recipientIds: [f.worker] })
+ const full = await f.timed.deliveries(host, f.tab, f.worker)
+ const row = full.find(r => r.messageId === sent.result.messageId)!
+ await f.timed.delivery(host, f.tab, f.worker, row.id, { type: 'claim', claimId: 'claim-1' })
+ await f.timed.delivery(host, f.tab, f.worker, row.id, { type: 'hold', claimId: 'claim-1', reason: 'team_waiting_draft' })
+ counted.ops.length = 0
+ f.clock.now += 1_000
+ const rows = await f.timed.deliveries(host, f.tab, f.worker)
+ expect(counted.ops).toEqual(HELD_READS)
+ // Its assignment's delivery is open beside it, as the full poll found.
+ expect(rows.map(r => r.id)).toEqual(full.map(r => r.id))
+ expect(rows.find(r => r.id === row.id)!.holdReason).toBe('team_waiting_draft')
+ })
+
+ it('reads in full once another delivery arrives, and returns both', async () => {
+ const f = await swarm()
+ const row = await held(f)
+ f.clock.now += 1_000
+ const next = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'And now?', replyTo: null, recipientIds: [] })
+ f.clock.now += 1_000
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.messageId)).toEqual([row.messageId, next.result.messageId])
+ })
+
+ /** Another open delivery beside `row`, written alone, as a write that changes no Swarm part would: the stamp stays. */
+ const beside = (row: SuperTabDelivery, changes: Partial<SuperTabDelivery> = {}) => db.superTabDelivery.create({ data: {
+ ...row, id: randomUUID(), messageId: randomUUID(), status: 'queued', claimId: null, holdReason: null, holdSince: null,
+ createdAt: new Date(row.createdAt.getTime() + 1), updatedAt: undefined, ...changes } })
+
+ it('reads in full for a delivery the last full poll never saw, even with the stamp unchanged', async () => {
+ const f = await swarm()
+ const row = await held(f)
+ f.clock.now += 1_000
+ const added = await beside(row)
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.id)).toEqual([row.id, added.id])
+ })
+
+ it('never returns an open delivery the full poll did not let reach the agent', async () => {
+ const f = await swarm()
+ const row = await held(f)
+ const stale = await beside(row, { membershipGeneration: 'an-earlier-membership' })
+ f.clock.now += 1_000
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.id)).toEqual([row.id])
+ f.clock.now += 1_000
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.id)).not.toContain(stale.id)
+ })
+
+ // A Swarm write is what revokes a member, an agent or a conversation's audience: it moves the stamp the held answer was read at.
+ it('stops returning an agent\'s held delivery on the next poll once it leaves the conversation', async () => {
+ const f = await swarm()
+ const helper = await f.add(f.group, 'test-host', f.harness.other, 'Helper')
+ await f.execute({ type: 'message.send', conversationId: f.group, text: 'Status?', replyTo: null, recipientIds: [helper] })
+ const [row] = await f.timed.deliveries(host, f.tab, helper)
+ await f.timed.delivery(host, f.tab, helper, row!.id, { type: 'claim', claimId: 'claim-1' })
+ await f.timed.delivery(host, f.tab, helper, row!.id, { type: 'hold', claimId: 'claim-1', reason: 'team_waiting_draft' })
+ f.clock.now += 1_000
+ await f.execute({ type: 'conversation.agent', conversationId: f.group, agentId: helper, present: false, lead: false })
+ f.clock.now += 1_000
+ expect(await f.timed.deliveries(host, f.tab, helper)).toEqual([])
+ })
+
+ it('reads in full after any Swarm write, even one that sends the agent nothing', async () => {
+ const counted = counting()
+ const f = await swarm({ client: counted.client })
+ const row = await held(f)
+ f.clock.now += 1_000
+ const projectId = (await f.timed.read(owner, f.tab)).state.projects![0]!.id
+ await f.execute({ type: 'project.digest', projectId, time: '03:00', timeZone: 'UTC' })
+ counted.ops.length = 0
+ f.clock.now += 1_000
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.id)).toEqual([row.id])
+ expect(counted.ops).toContain('SwarmGroup.aggregateRaw')
+ })
+
+ // What no Swarm write records (a machine share revoked, a machine gone, a Workspace left) is read on every poll.
+ it('refuses on the next poll once its host\'s machine share is revoked', async () => {
+ const f = await swarm()
+ await held(f)
+ const share = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'lead-host' } })
+ await db.machineShare.update({ where: { machineId: 'lead-host' }, data: { emails: [] } })
+ try {
+ f.clock.now += 1_000
+ await expect(f.timed.deliveries(host, f.tab, f.lead)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ } finally {
+ await db.machineShare.update({ where: { machineId: 'lead-host' }, data: { emails: share.emails } })
+ }
+ })
+
+ // A turn typed into a terminal reaches the Lead only while its typist may still use that terminal's machine
+ // (native.ts allowsDelivery), which no Swarm write records either (review of #2055).
+ it('withholds a held terminal turn on the next poll once its typist\'s share of the machine is revoked', async () => {
+ const f = await swarm()
+ const { contextId } = await f.timed.native.open(owner, f.tab, { operationId: randomUUID(), conversationId: f.group, agentId: f.worker })
+ await f.timed.native.append(host, f.tab, contextId, { turnId: 'turn_1', kind: 'prompt', previousEventId: null, text: 'Typed by hand',
+ truncated: false, interrupted: false })
+ const turn = (await f.timed.deliveries(host, f.tab, f.lead)).find(r => r.nativeContextId === contextId)!
+ await f.timed.delivery(host, f.tab, f.lead, turn.id, { type: 'claim', claimId: 'claim-1' })
+ await f.timed.delivery(host, f.tab, f.lead, turn.id, { type: 'hold', claimId: 'claim-1', reason: 'team_waiting_user' })
+ f.clock.now += 1_000
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.id)).toContain(turn.id)
+ const share = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [] } })
+ try {
+ f.clock.now += 1_000
+ expect((await f.timed.deliveries(host, f.tab, f.lead)).map(r => r.id)).not.toContain(turn.id)
+ } finally {
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: share.emails } })
+ }
+ })
+
+ // #2022: one write's deliveries share a creation time; the held answer keeps each conversation's tied rows in its order too.
+ it('returns tied held deliveries in their conversation\'s order, without loading the Swarm', async () => {
+ const counted = counting()
+ const f = await swarm({ client: counted.client })
+ const assignments: string[] = []
+ for (const title of ['Parser', 'Renderer', 'Exporter']) {
+ const group = String((await f.execute({ type: 'conversation.create', title, brief: 'Build it',
+ checks: [{ description: 'Built', independent: false }] })).result.conversationId)
+ await f.execute({ type: 'conversation.agent', conversationId: group, agentId: f.lead, present: false, lead: false })
+ const worker = await f.add(group, 'test-host', randomUUID(), title)
+ assignments.push(String((await f.execute({ type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId))
+ }
+ f.clock.now += 6 * MINUTE
+ const expectedIds = assignments.map(assignment => stableId(stableId('work-lost', assignment, String(f.clock.now)), 'lead'))
+ const first = (await f.timed.deliveries(host, f.tab, f.lead)).filter(row => expectedIds.includes(row.messageId))
+ expect(first).toHaveLength(3)
+ await f.timed.delivery(host, f.tab, f.lead, first[0]!.id, { type: 'claim', claimId: 'claim-1' })
+ await f.timed.delivery(host, f.tab, f.lead, first[0]!.id, { type: 'hold', claimId: 'claim-1', reason: 'team_waiting_user' })
+ const page = (await f.timed.messages(owner, f.tab, 'lead', {})).messages.filter(row => expectedIds.includes(row.id))
+ f.clock.now += 1_000
+ await f.timed.deliveries(host, f.tab, f.lead)
+ // Stored later sequence first, so insertion order cannot stand in for the tie-break; no Swarm write, so the stamp stays.
+ const tiedAt = new Date('2026-10-28T00:00:00.000Z')
+ const stored = await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: { in: expectedIds } } })
+ await db.superTabDelivery.deleteMany({ where: { tabId: f.tab, messageId: { in: expectedIds } } })
+ for (const id of [...page.map(row => row.id)].reverse()) {
+ await db.superTabDelivery.create({ data: { ...stored.find(row => row.messageId === id)!, createdAt: tiedAt } })
+ }
+ counted.ops.length = 0
+ f.clock.now += 1_000
+ const held = (await f.timed.deliveries(host, f.tab, f.lead)).filter(row => expectedIds.includes(row.messageId))
+ expect(counted.ops).not.toContain('SwarmGroup.aggregateRaw')
+ expect(held.map(row => row.messageId)).toEqual(page.map(row => row.id))
+ })
+
+ // A Workspace removal is read outside the Swarm, as a machine share is (superTabs.test.ts): the next poll meets it.
+ it('refuses on the next poll once the agent\'s contributor is out of the Swarm\'s Workspace', async () => {
+ const f = await swarm()
+ await held(f)
+ const { workspaceId } = (await f.timed.read(owner, f.tab)).state
+ const id = `${workspaceId}:${owner.sub}`
+ await db.swarmWorkspaceMember.update({ where: { id }, data: { removedAt: new Date(), removedBy: owner.sub } })
+ try {
+ f.clock.now += 1_000
+ await expect(f.timed.deliveries(host, f.tab, f.lead)).rejects.toMatchObject({ code: 'WORKSPACE_ACCESS_REVOKED' })
+ } finally {
+ await db.swarmWorkspaceMember.update({ where: { id }, data: { removedAt: null, removedBy: null } })
+ }
+ })
+
+ it('never answers a team session from its person\'s held answer: the team session meets its own checks', async () => {
+ const f = await swarm()
+ await held(f)
+ f.clock.now += 1_000
+ const team: AuthUser = { ...host, harnessSessionId: 'team-elsewhere', harnessSessionKind: 'team', harnessComputerId: 'elsewhere' }
+ await expect(f.timed.deliveries(team, f.tab, f.lead)).rejects.toMatchObject({ code: 'TEAM_SESSION_LIMITED' })
+ })
+
+ it('still runs the Lead\'s time checks: the five-minute update request arrives beside the held delivery', async () => {
+ const f = await swarm()
+ const row = await held(f)
+ for (let second = 0; second < 5 * 60; second++) {
+ f.clock.now += 1_000
+ await f.timed.deliveries(host, f.tab, f.lead)
+ }
+ const rows = await f.timed.deliveries(host, f.tab, f.lead)
+ expect(rows[0]!.id).toBe(row.id)
+ const kinds = await db.superTabMessage.findMany({ where: { id: { in: rows.map(r => r.messageId) } } })
+ expect(kinds.map(m => (m.source as { kind?: string } | null)?.kind)).toContain('update-request')
+ })
+})
+
// Hosts read an idle agent's deliveries only every 30 s once the server pushes (stability roadmap 2.4): each new one is
// announced to the machine its agent runs on, once its write commits, so the host reads it at once.
describe('the push for a new delivery', () => {
@@ -899,6 +1113,44 @@ describe('the push for a new delivery', () => {
})
})
+// Diego's review of 10-28, item 1: every write of the full poll is the Lead's, so a worker's poll only reads. Through the
+// read cache, with no transaction: 20 workers were 40 whole-Swarm loads, clones and empty commits a minute. Each test holds
+// the Swarm in the cache first, as every reader of a busy Swarm finds it; a miss reads it once for all of them.
+describe('a worker\'s delivery poll', () => {
+ const counting = () => {
+ const opened = { count: 0 }
+ const client = new Proxy(db, { get(target, key, receiver) {
+ if (key !== '$transaction') return Reflect.get(target, key, receiver)
+ return (body: unknown, options: unknown) => {
+ opened.count++
+ return (target.$transaction as (b: unknown, o: unknown) => Promise<unknown>)(body, options)
+ }
+ } }) as PrismaClient
+ return { opened, client }
+ }
+
+ it('opens no transaction and returns the worker\'s open deliveries', async () => {
+ const { opened, client } = counting()
+ const f = await swarm({ client })
+ const sent = await f.execute({ type: 'message.send', conversationId: f.group, text: 'Status?', replyTo: null, recipientIds: [f.worker] })
+ await f.timed.readLoad(host, f.tab)
+ opened.count = 0
+ const rows = await f.timed.deliveries(host, f.tab, f.worker)
+ expect(opened.count).toBe(0)
+ expect(rows.map(r => r.messageId)).toContain(sent.result.messageId)
+ expect(rows.every(r => r.agentId === f.worker)).toBe(true)
+ })
+
+ it('still runs the Lead\'s poll in one transaction', async () => {
+ const { opened, client } = counting()
+ const f = await swarm({ client })
+ await f.timed.readLoad(host, f.tab)
+ opened.count = 0
+ await f.timed.deliveries(host, f.tab, f.lead)
+ expect(opened.count).toBe(1)
+ })
+})
+
describe('the morning digest', () => {
// #1772 review: every open decision counts, however many there are, and private ones never crowd out shared ones.
it('counts every decision waiting, past 200, and is not crowded out by newer private ones', async () => {
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index e9dfd3c80..85988f7d4 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -801,7 +801,8 @@ describe('private swarm projects on the real control API', () => {
await execute({ ...message('Tests passed'), conversationId: group } as Command)
now += 899_999
expect(await updates()).toEqual([])
- now++
+ // As above: the Lead's open deliveries are answered from its last full poll for 30 s, so the request lands within that.
+ now += 30_000
expect(await updates()).toHaveLength(1)
})
})
diff --git a/backend/src/lib/adapterShortTurns.test.ts b/backend/src/lib/adapterShortTurns.test.ts
index 10e3ea3c7..dcdb0a11e 100644
--- a/backend/src/lib/adapterShortTurns.test.ts
+++ b/backend/src/lib/adapterShortTurns.test.ts
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
// The machine socket's short-turn cap (lib/shortTurnGuard.ts) on the real handler. The socket harness is the one in
// teamSessionSockets.test.ts: authentication, the machine row, the bus and the hub are faked.
const m = vi.hoisted(() => ({
- auth: vi.fn(), upgrade: vi.fn(), resolve: vi.fn(), publishUp: vi.fn(), recordTurn: vi.fn(), nodeRole: vi.fn(), warn: vi.fn(),
+ auth: vi.fn(), upgrade: vi.fn(), resolve: vi.fn(), publishUp: vi.fn(), recordTurn: vi.fn(), nodeRole: vi.fn(), warn: vi.fn(), info: vi.fn(),
}))
vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))
vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))
@@ -29,7 +29,7 @@ vi.mock('./hub.js', () => ({
vi.mock('./dailyTracking.js', async original => ({ ...await original<typeof import('./dailyTracking.js')>(),
touchMachineOnlineDay: vi.fn(async () => {}), touchUserOnlineDay: vi.fn(async () => {}), touchClientOnlineDay: vi.fn(async () => {}),
recordTurnStarted: m.recordTurn }))
-vi.mock('../utils/logger.js', () => ({ logger: { warn: m.warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
+vi.mock('../utils/logger.js', () => ({ logger: { warn: m.warn, info: m.info, error: vi.fn(), debug: vi.fn() } }))
import { handleAdapterUpgrade } from './adapterWs.js'
@@ -38,15 +38,15 @@ const flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve(
class Socket extends EventEmitter {
readyState = 1; bufferedAmount = 0
send = vi.fn()
- close = vi.fn(() => { this.readyState = 3; this.emit('close') })
+ close = vi.fn((code?: number, reason?: string) => { this.readyState = 3; this.emit('close', code, Buffer.from(reason ?? '')) })
terminate = vi.fn(() => this.close())
frame(body: unknown) { this.emit('message', Buffer.from(JSON.stringify(body)), false) }
}
-async function machineSocket(): Promise<Socket> {
+async function machineSocket(query = ''): Promise<Socket> {
const ws = new Socket()
m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))
- handleAdapterUpgrade({ url: '/api/adapter-ws?computer=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&label=Mac&autonomousEnv=prod',
+ handleAdapterUpgrade({ url: `/api/adapter-ws?computer=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&label=Mac&autonomousEnv=prod${query}`,
headers: { 'sec-websocket-protocol': 'access-token' } } as never,
{ write: vi.fn(), destroy: vi.fn(), destroyed: false, on: vi.fn(), once: vi.fn() } as never, Buffer.alloc(0))
await flush()
@@ -90,3 +90,21 @@ describe('a machine starting turns in a loop', () => {
expect(types.at(-1)).toMatchObject({ type: 'turn_started', replay: true })
})
})
+
+// WebSocket roadmap Phase 0 (same harness): adapter reconnects could not be explained, the logs had no close codes.
+describe('a machine socket', () => {
+ it('logs its daemon version, and how and when it closed, a superseded one too (4000)', async () => {
+ const first = await machineSocket('&v=0.9.1')
+ // The second connect closes the first (4000 superseded), which still logs its own end.
+ const second = await machineSocket('&v=0.9.1')
+ expect(first.close).toHaveBeenCalledWith(4000, 'superseded')
+ second.emit('close', 1006, Buffer.alloc(0))
+ // The machine's socket left from the test before is superseded by the first connect here: only this test's two.
+ const lines = m.info.mock.calls.filter(c => c[0] === 'adapter disconnected').map(c => c[1]).slice(-2)
+ expect(lines).toEqual([
+ expect.objectContaining({ endpoint: 'adapter', client: 'daemon', version: '0.9.1', machineId: 'looping-mac', code: 4000,
+ reason: 'superseded', aliveMs: expect.any(Number) }),
+ expect.objectContaining({ endpoint: 'adapter', client: 'daemon', machineId: 'looping-mac', code: 1006 }),
+ ])
+ })
+})
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 851259178..6aec392ac 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -29,6 +29,7 @@ import {
} from './bus.js'
import { trackSocketLiveness } from './hub.js'
import { guardedSend, guardedSendJson } from './wsSend.js'
+import { trackSocket } from './wsAttribution.js'
import { attachNodeRole, PRESENCE_TTL_SEC } from './nodeRole.js'
import { presenceTracker, presenceWriteDue, recordTurnStarted, touchClientOnlineDay, touchMachineOnlineDay, touchUserOnlineDay, TUI_SURFACES, type ClientSurface, type PresenceWriteState } from './dailyTracking.js'
import { countryCodeFromHeaders } from './clientGeo.js'
@@ -230,7 +231,10 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
owners.get(machineId)?.close(4000, 'superseded')
owners.set(machineId, ws)
const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { machineId, kind: 'adapter' })
- logger.info('adapter connected', { machineId, computer: label })
+ // Its connect and disconnect lines (lib/wsAttribution.ts): 227 adapter reconnects in 45 minutes in prod (2026-10-28)
+ // could not be explained without the close codes.
+ const track = trackSocket('adapter', 'adapter', ws, { client: 'daemon', version: clientVersion ?? null, machineId, computer: label })
+ ws.once('close', (code: number, reason?: Buffer) => track.closed(code, reason?.toString()))
send({ t: 'connected', machineId })
// What changed for the ACCOUNT on some worker (its tabs, its machine list): this computer's app
// re-reads through its daemon rather than polling for it. See adapterAccountPushes.ts.
@@ -583,7 +587,6 @@ async function attachAdapter(ws: WebSocket, machineId: string, userId: string, c
// this delete is what stops a reconnect from briefly re-reading the dead value.
void clearMachineAppState(machineId)
touchMachinePresence('close') // exact lastSeenAt at disconnect; a superseded socket must not stamp it
- logger.info('adapter disconnected', { machineId })
}
}
ws.on('close', cleanup)
diff --git a/backend/src/lib/agentMessagesWs.test.ts b/backend/src/lib/agentMessagesWs.test.ts
index 73a284e3f..86096cd8d 100644
--- a/backend/src/lib/agentMessagesWs.test.ts
+++ b/backend/src/lib/agentMessagesWs.test.ts
@@ -1,10 +1,11 @@
import { EventEmitter } from 'node:events'
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
const m = vi.hoisted(() => ({
- auth: vi.fn(), admits: vi.fn(), relay: vi.fn(), publish: vi.fn(), changed: vi.fn(), live: vi.fn(), upgrade: vi.fn(),
+ auth: vi.fn(), admits: vi.fn(), relay: vi.fn(), publish: vi.fn(), changed: vi.fn(), live: vi.fn(), upgrade: vi.fn(), info: vi.fn(),
SsoAuthError: class SsoAuthError extends Error { constructor(message: string, readonly code: string) { super(message) } },
}))
vi.mock('./ssoAuth.js', () => ({ authenticateAccessToken: m.auth, SsoAuthError: m.SsoAuthError }))
+vi.mock('../utils/logger.js', () => ({ logger: { info: m.info, warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
vi.mock('./agentMessageShares.js', () => ({ admits: m.admits }))
vi.mock('./bus.js', () => ({ subscribeTabRelay: m.relay, publishTabRelay: m.publish, subscribeAgentMessageShareChanged: m.changed }))
vi.mock('./hub.js', () => ({ trackSocketLiveness: m.live }))
@@ -52,6 +53,25 @@ describe('blind shared-tab relay WebSocket', () => {
expect(m.auth).not.toHaveBeenCalled(); expect(m.upgrade).not.toHaveBeenCalled()
})
+ // WebSocket roadmap Phase 0: which daemon, how its socket ended and after how long.
+ it('logs the daemon it declared, and how and when its socket closed', async () => {
+ await connect(req(`share=${SHARE}&machine=ken-mac&client=relay&v=0.9.1`))
+ vi.advanceTimersByTime(1_500)
+ ws.emit('close', 4409, Buffer.from('Replaced by a newer connection'))
+ const lines = m.info.mock.calls.filter(c => c[0] === 'agent-messages disconnected').map(c => c[1])
+ expect(lines).toEqual([expect.objectContaining({ endpoint: 'agentMessages', client: 'relay', version: '0.9.1', userId: 'ken',
+ machineId: 'ken-mac', code: 4409, reason: 'Replaced by a newer connection', aliveMs: 1_500 })])
+ })
+
+ // Review of #2029: as the observer's, the shared tab's lines never carry its id.
+ it('keeps the shared tab id out of its connect and disconnect lines', async () => {
+ await connect(req(`share=${SHARE}&machine=ken-mac&client=relay`))
+ ws.emit('close', 1000, Buffer.alloc(0))
+ const lines = m.info.mock.calls.filter(c => String(c[0]).startsWith('agent-messages'))
+ expect(lines.map(c => c[0])).toEqual(['agent-messages connected', 'agent-messages disconnected'])
+ expect(JSON.stringify(lines)).not.toContain(SHARE)
+ })
+
it('upgrades a refused connection and closes it 4403, authenticating as a daemon', async () => {
m.admits.mockResolvedValue(false)
await connect(req(`share=${SHARE}&machine=ken-mac&autonomousEnv=stag`))
diff --git a/backend/src/lib/agentMessagesWs.ts b/backend/src/lib/agentMessagesWs.ts
index 0e1b70395..7348eae93 100644
--- a/backend/src/lib/agentMessagesWs.ts
+++ b/backend/src/lib/agentMessagesWs.ts
@@ -17,6 +17,7 @@ import { publishTabRelay, subscribeTabRelay, subscribeAgentMessageShareChanged }
import { guardedSendJson } from './wsSend.js'
import { trackSocketLiveness } from './hub.js'
import { createOrderedInbox } from './orderedInbox.js'
+import { declaredKind, trackSocket } from './wsAttribution.js'
const wss = createWss(WS_LIMITS.agentMessages, { echoFirstProtocol: true })
/** The daemons' one ceiling for a shared tab's frame (cli lib/e2ee/tabSession.ts `SHARED_TAB_FRAME_MAX`). */
@@ -47,10 +48,11 @@ export function handleAgentMessagesUpgrade(req: IncomingMessage, socket: Duplex,
}
const allowed = await admits(user.sub, machine, share, env)
if (socket.destroyed) return
+ const declared = declaredKind(url.searchParams)
wss.handleUpgrade(req, socket, head, ws => {
// 4403 is admission's answer alone: the account is not the tab's owner or an accepted member.
if (!allowed) { ws.close(4403, 'Not in this shared tab'); return }
- void attach(ws, user.sub, share, machine, env).catch(() => ws.close(1013, 'Shared tab temporarily unavailable'))
+ void attach(ws, user.sub, share, machine, env, declared).catch(() => ws.close(1013, 'Shared tab temporarily unavailable'))
})
})().catch(() => { if (!socket.destroyed) socket.destroy() })
}
@@ -61,7 +63,11 @@ function refuse(socket: Duplex, status: string): void {
socket.destroy()
}
-async function attach(ws: WebSocket, userId: string, share: string, machine: string, env: ReturnType<typeof parseAutonomousEnvironment>) {
+async function attach(ws: WebSocket, userId: string, share: string, machine: string, env: ReturnType<typeof parseAutonomousEnvironment>,
+ declared: ReturnType<typeof declaredKind>) {
+ // Its connect and disconnect lines (lib/wsAttribution.ts). The shared tab's id is not logged.
+ const track = trackSocket('agentMessages', 'agent-messages', ws, { ...declared, userId, machineId: machine })
+ ws.once('close', (code: number, reason?: Buffer) => track.closed(code, reason?.toString()))
const key = `${share}:${machine}`
live.get(key)?.close(4409, 'Replaced by a newer connection')
live.set(key, ws)
diff --git a/backend/src/lib/observerWs.test.ts b/backend/src/lib/observerWs.test.ts
index f52898b28..51b091d35 100644
--- a/backend/src/lib/observerWs.test.ts
+++ b/backend/src/lib/observerWs.test.ts
@@ -2,8 +2,9 @@ import { EventEmitter } from 'node:events'
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
const m = vi.hoisted(() => ({
auth: vi.fn(), grant: vi.fn(), up: vi.fn(), changed: vi.fn(), swarm: vi.fn(), down: vi.fn(), live: vi.fn(),
- upgrade: vi.fn(), link: vi.fn(), profile: vi.fn(),
+ upgrade: vi.fn(), link: vi.fn(), profile: vi.fn(), info: vi.fn(),
}))
+vi.mock('../utils/logger.js', () => ({ logger: { info: m.info, warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
vi.mock('./ssoAuth.js', () => ({ authenticateAccessToken: m.auth }))
vi.mock('./prisma.js', () => ({ prisma: { user: { findUnique: m.profile } } }))
vi.mock('../routes/harnessLinks.js', () => ({ recipientLink: m.link }))
@@ -38,6 +39,21 @@ describe('isolated observer WebSocket boundary', () => {
afterEach(() => { ws.close(); vi.useRealTimers() })
const attach = () => attachObserver(ws as never, user, share as never)
const hello = () => ws.message('observer_hello', { ephemeral: Buffer.alloc(32, 1).toString('base64') })
+ // WebSocket roadmap Phase 0: which client watched, how its socket ended and after how long. Never the share or link
+ // id, which for a link is the address that opens it.
+ it('logs the client it declared, and how and when its socket closed, without the share id', async () => {
+ const socket = { destroyed: false, destroy: vi.fn() }
+ handleObserverUpgrade({ url: `/api/observer-ws?share=${share.id}&client=relay&v=0.9.1`, headers: { 'sec-websocket-protocol': 'tok' } } as never,
+ socket as never, Buffer.alloc(0))
+ await flush()
+ vi.advanceTimersByTime(700)
+ ws.emit('close', 1012, Buffer.from('Owner is offline'))
+ const lines = m.info.mock.calls.filter(c => c[0] === 'observer disconnected').map(c => c[1])
+ expect(lines).toEqual([expect.objectContaining({ endpoint: 'observer', client: 'relay', version: '0.9.1', userId: 'ken', machineId: 'm',
+ code: 1012, reason: 'Owner is offline', aliveMs: 700 })])
+ expect(JSON.stringify(m.info.mock.calls)).not.toContain(share.id)
+ })
+
it('admits anonymous public links, passes only authenticated comment identity and rechecks link access', async () => {
const socket = { destroyed: false, destroy: vi.fn() }
const req = (token?: string) => ({ url: `/api/observer-ws?link=${share.id}`, headers: token ? { 'sec-websocket-protocol': token } : {} })
diff --git a/backend/src/lib/observerWs.ts b/backend/src/lib/observerWs.ts
index be7807b7c..a21d9aafc 100644
--- a/backend/src/lib/observerWs.ts
+++ b/backend/src/lib/observerWs.ts
@@ -14,6 +14,7 @@ import { publishDown, subscribeUp, subscribeShareChanged, subscribeSwarmAccessCh
import { guardedSendJson } from './wsSend.js'
import { trackSocketLiveness } from './hub.js'
import { createOrderedInbox } from './orderedInbox.js'
+import { declaredKind, trackSocket } from './wsAttribution.js'
const wss = createWss(WS_LIMITS.web, { echoFirstProtocol: true })
const RECHECK_MS = 60_000
@@ -29,16 +30,22 @@ export function handleObserverUpgrade(req: IncomingMessage, socket: Duplex, head
const user = token ? await authenticateAccessToken(token, autonomousEnv) : null
const share = linkMode ? await recipientLink(id, user, autonomousEnv) : await recipientShare(id, user!)
if (socket.destroyed) return
+ const declared = declaredKind(url.searchParams)
wss.handleUpgrade(req, socket, head, ws => {
if (!share) { ws.close(4403, 'Sharing ended or invitation expired'); return }
- void attachObserver(ws, user, share, linkMode ? autonomousEnv : undefined).catch(() => ws.close(1013, 'Sharing temporarily unavailable'))
+ void attachObserver(ws, user, share, linkMode ? autonomousEnv : undefined, declared)
+ .catch(() => ws.close(1013, 'Sharing temporarily unavailable'))
})
})().catch(() => { if (!socket.destroyed) socket.destroy() })
}
/** Separate from the machine hub: no group key, machine inventory, P2P, or generic RPC route. */
export async function attachObserver(ws: WebSocket, user: AuthUser | null,
- share: { id: string; machineId: string; ownerId: string; superTabId?: string | null }, linkEnv?: AutonomousEnvironment): Promise<void> {
+ share: { id: string; machineId: string; ownerId: string; superTabId?: string | null }, linkEnv?: AutonomousEnvironment,
+ declared: ReturnType<typeof declaredKind> = { client: 'unknown', version: null }): Promise<void> {
+ // Its connect and disconnect lines (lib/wsAttribution.ts). Never the share or link id: a link's is its address.
+ const track = trackSocket('observer', 'observer', ws, { ...declared, userId: user?.sub, machineId: share.machineId })
+ ws.once('close', (code: number, reason?: Buffer) => track.closed(code, reason?.toString()))
const connId = `observer:${randomUUID()}`
const send = (frame: unknown) => guardedSendJson(ws, frame, 'must')
const disposers: Array<() => void> = [trackSocketLiveness(ws, 'observer')]
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index 10d2f2ecc..7dd531cc1 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -59,6 +59,7 @@ import {
terminalP2pPolicy,
} from './p2pSignaling.js'
import { presenceTracker, recordRemoteUsage, touchClientOnlineDay, type ClientBuild } from './dailyTracking.js'
+import { declaredKind, trackSocket } from './wsAttribution.js'
import { isBackendOnlyDownType } from './backendOnlyFrames.js'
// How often an open mobile/web socket refreshes its person's `user_daily_client_presence` row.
@@ -113,7 +114,7 @@ export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buf
void (async () => {
const binding = await prisma.machine.findUnique({ where: { machineId: machineId } })
if (!binding || binding.deletedAt || !machineBillingAllowsDataPlane(binding)) { socket.destroy(); return }
- wss.handleUpgrade(req, socket, head, (ws) => attachWebClient(ws, machineId))
+ wss.handleUpgrade(req, socket, head, (ws) => attachWebClient(ws, machineId, declaredKind(new URL(req.url ?? '/', 'http://x').searchParams)))
})().catch((err) => { logger.warn('web-ws legacy upgrade failed', { error: String(err) }); socket.destroy() })
return
}
@@ -126,9 +127,10 @@ export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buf
// Who is on the other end, as the client declares it: the mobile app and the web viewer say so;
// the daemon's relay (and any older client) says nothing and is never counted as a person.
const { surface, build } = declaredClient(query)
+ const declared = declaredKind(query)
const user = await authenticateAccessToken(cred, requestedEnvironment)
if (socket.destroyed) return
- wss.handleUpgrade(req, socket, head, (ws) => attachUserClient(ws, user, surface, build))
+ wss.handleUpgrade(req, socket, head, (ws) => attachUserClient(ws, user, surface, build, declared))
} catch (err) {
if (socket.destroyed) return
const invalid = err instanceof SsoAuthError && err.code === 'INVALID_TOKEN'
@@ -149,7 +151,8 @@ export function handleWebUpgrade(req: IncomingMessage, socket: Duplex, head: Buf
}
/** PER-USER socket: starts unattached; `machine_select` scopes it to one owned machine at a time. */
-function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'web' | null, build: ClientBuild): void {
+function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'web' | null, build: ClientBuild,
+ declared: ReturnType<typeof declaredKind> = { client: 'unknown', version: null }): void {
let client: HubClient | null = null
let currentAgentId: string | null = null
let currentBinding: Machine | null = null
@@ -162,7 +165,13 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
const p2pSignalRate = new P2pSignalRateGuard()
const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { userId: user.sub })
- logger.info('web user connected', { userId: user.sub })
+ // Its connect and disconnect lines (lib/wsAttribution.ts): prod, 2026-10-28, 2,304 of 2,308 opens in 15 minutes
+ // declared no client and lived a median 0.4 s, and these lines named only the user.
+ const track = trackSocket('web', 'web user', ws, { ...declared, userId: user.sub })
+ const refuse = (payload: { machineId: string; error: string; retryAfterMs?: number }): void => {
+ track.selected(payload.error)
+ send({ type: 'machine_select_error', payload })
+ }
send({ type: 'connected', payload: { userId: user.sub } })
// The desktop app never dials this socket — the local daemon does, one per FOREIGN machine it relays —
@@ -332,6 +341,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
// ── Agent selection ──────────────────────────────────────────────────────────────────────────
const ack = (machineId: string): void => {
+ track.selected('accepted')
send({
type: 'connected',
payload: { machineId: machineId, p2p: terminalP2pPolicy(user.sub, machineId) },
@@ -363,20 +373,20 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
// client's stale list; a failed share check is ours.
const reason = !binding ? 'unknown' : binding.deletedAt ? 'deleted' : shareCheckFailed ? 'share_check_failed' : 'not_shared'
logger.warn('machine_select rejected', { userId: user.sub, machineId, reason })
- send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'NOT_YOUR_MACHINE' } })
+ refuse({ machineId: machineId, error: 'NOT_YOUR_MACHINE' })
return
}
if (storedAutonomousEnvironment(binding.autonomousEnv) !== user.autonomousEnv) {
logger.warn('machine_select environment rejected', { userId: user.sub, machineId, autonomousEnv: user.autonomousEnv })
- send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_ENV_MISMATCH' } })
+ refuse({ machineId: machineId, error: 'MACHINE_ENV_MISMATCH' })
return
}
if (binding.billingStatus === 'pending') {
- send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_PAYMENT_PENDING' } })
+ refuse({ machineId: machineId, error: 'MACHINE_PAYMENT_PENDING' })
return
}
if (binding.billingStatus === 'suspended') {
- send({ type: 'machine_select_error', payload: { machineId: machineId, error: 'MACHINE_SUBSCRIPTION_REQUIRED' } })
+ refuse({ machineId: machineId, error: 'MACHINE_SUBSCRIPTION_REQUIRED' })
return
}
try {
@@ -384,7 +394,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
} catch (err) {
if (!closed && gen === selectGen) {
const code = err instanceof Error && 'code' in err ? String((err as { code?: unknown }).code) : 'MACHINE_START_FAILED'
- send({ type: 'machine_select_error', payload: { machineId: machineId, error: code } })
+ refuse({ machineId: machineId, error: code })
}
return
}
@@ -398,7 +408,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
// the web viewer waits attached for the machine to come back, as before.
if ((refuseOffline || !surface) && !await machineOnline(machineId, !!await getAgentPresence(machineId))) {
if (!closed && gen === selectGen) {
- send({ type: 'machine_select_error', payload: { machineId, error: 'MACHINE_OFFLINE', retryAfterMs: OFFLINE_RETRY_AFTER_MS } })
+ refuse({ machineId, error: 'MACHINE_OFFLINE', retryAfterMs: OFFLINE_RETRY_AFTER_MS })
}
return
}
@@ -433,7 +443,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
client = null
currentAgentId = null
currentBinding = null
- send({ type: 'machine_select_error', payload: { machineId, error: 'NOT_YOUR_MACHINE' } })
+ refuse({ machineId, error: 'NOT_YOUR_MACHINE' })
ws.close(4403, 'Sharing ended')
}
void subscribeMachineShareChanged(machineId, () => { void recheck().catch(() => { /* the next change asks again */ }) })
@@ -625,18 +635,20 @@ function attachUserClient(ws: WebSocket, user: AuthUser, surface: 'mobile' | 'we
if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }
if (deviceE2eePairUnsub) { deviceE2eePairUnsub(); deviceE2eePairUnsub = null }
if (documentsUnsub) { documentsUnsub(); documentsUnsub = null }
- logger.info('web user disconnected', { userId: user.sub, machineId: currentAgentId ?? undefined })
}
- ws.on('close', cleanup)
- ws.on('error', cleanup)
+ // The line takes its code from the close: `ws` emits an error first on a broken socket, which has none (review of #2029).
+ ws.on('close', (code: number, reason: Buffer) => { cleanup(); track.closed(code, reason?.toString(), { machineId: currentAgentId ?? undefined }) })
+ ws.on('error', () => cleanup())
}
/** LEGACY per-agent socket (old bundle during rolling deploys): bound to one agent for life. */
-function attachWebClient(ws: WebSocket, machineId: string): void {
+function attachWebClient(ws: WebSocket, machineId: string, declared: ReturnType<typeof declaredKind>): void {
const client = attachHubClient(ws, machineId, 'web')
const terminalRate = new TerminalRateGuard()
const send = (obj: unknown): boolean => guardedSendJson(ws, obj, 'must', { machineId, connId: client.connId })
- logger.info('web client connected (legacy)', { machineId, connId: client.connId })
+ // Tracked like the per-user socket (lib/wsAttribution.ts); untracked, each one counted as refused (review of #2029).
+ const track = trackSocket('web', 'web client (legacy)', ws, { ...declared, machineId, hubConnId: client.connId })
+ ws.once('close', (code: number, reason?: Buffer) => track.closed(code, reason?.toString()))
send({ type: 'connected', payload: { machineId: machineId } })
@@ -680,7 +692,6 @@ function attachWebClient(ws: WebSocket, machineId: string): void {
if (closed) return // 'error' is followed by 'close': detach (and its __client_disconnected) only once
closed = true
client.detach()
- logger.info('web client disconnected (legacy)', { machineId, connId: client.connId })
}
ws.on('close', cleanup)
ws.on('error', cleanup)
diff --git a/backend/src/lib/webWsOffline.test.ts b/backend/src/lib/webWsOffline.test.ts
index c4c18e69a..1f2660e50 100644
--- a/backend/src/lib/webWsOffline.test.ts
+++ b/backend/src/lib/webWsOffline.test.ts
@@ -7,9 +7,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
// already out there) is refused at once, with how long to wait; a phone or the web viewer still waits attached.
const m = vi.hoisted(() => ({
auth: vi.fn(), upgrade: vi.fn(), presence: vi.fn(), online: vi.fn(), attach: vi.fn(),
- machineFindUnique: vi.fn(), shared: vi.fn(), warn: vi.fn(),
+ machineFindUnique: vi.fn(), shared: vi.fn(), warn: vi.fn(), info: vi.fn(),
}))
-vi.mock('../utils/logger.js', () => ({ logger: { warn: m.warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
+vi.mock('../utils/logger.js', () => ({ logger: { warn: m.warn, info: m.info, error: vi.fn(), debug: vi.fn() } }))
vi.mock('./machineAccess.js', async original => ({ ...await original<typeof import('./machineAccess.js')>(), sharedMachineAccess: m.shared }))
vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))
vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))
@@ -104,3 +104,53 @@ describe('a refused machine select', () => {
expect(m.warn).toHaveBeenCalledWith('machine_select rejected', { userId: 'owner', machineId: 'owner-mac', reason })
})
})
+
+// Prod, 2026-10-28: 2,304 of 2,308 opens in 15 minutes declared no client and lived a median 0.4 s, and the disconnect
+// line said only who. It now says which client and version, how the socket closed, after how long, and what its selects
+// were answered (lib/wsAttribution.ts), so a relay's churn can be told apart from a person's reconnects.
+describe('a closed socket', () => {
+ const lines = (message: string) => m.info.mock.calls.filter(c => c[0] === message).map(c => c[1])
+
+ it('logs a relay refused as offline with its client, close, lifetime and select', async () => {
+ const ws = await selects({}, '&client=relay&v=0.9.1')
+ ws.emit('close', 1000, Buffer.from('handshake failed'))
+ const [connected] = lines('web user connected')
+ expect(connected).toMatchObject({ endpoint: 'web', client: 'relay', version: '0.9.1', userId: 'owner' })
+ expect(lines('web user disconnected')).toEqual([{ ...connected, code: 1000, reason: 'handshake failed',
+ aliveMs: expect.any(Number), selects: 1, select: 'MACHINE_OFFLINE' }])
+ })
+
+ it('logs a phone with its release, the machine it had selected, and the select accepted', async () => {
+ m.online.mockResolvedValue(true)
+ const ws = await selects({}, '&client=mobile&release=1.4.2')
+ ws.emit('close', 1006, Buffer.alloc(0))
+ expect(lines('web user disconnected')).toEqual([expect.objectContaining({ client: 'mobile', version: '1.4.2', machineId: 'owner-mac',
+ code: 1006, selects: 1, select: 'accepted' })])
+ })
+
+ // Review of #2029: `ws` emits an error before the close; the line must carry the close's code, not none.
+ it('takes the close code from the close, not an error before it', async () => {
+ const ws = await selects({}, '&client=relay')
+ ws.emit('error', new Error('read ECONNRESET'))
+ ws.emit('close', 1006, Buffer.alloc(0))
+ expect(lines('web user disconnected')).toEqual([expect.objectContaining({ code: 1006 })])
+ })
+
+ // Review of #2029: the old per-agent key path was upgraded and never tracked, so each of its sockets counted as refused.
+ it('tracks a legacy per-agent socket like any other', async () => {
+ const ws = new Socket()
+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(ws))
+ m.attach.mockReturnValue({ connId: 'legacy-conn', detach: vi.fn(), sendDown: vi.fn() })
+ handleWebUpgrade({ url: '/api/web-ws', headers: { 'sec-websocket-protocol': 'a'.repeat(64) } } as never, raw() as never, Buffer.alloc(0))
+ await flush()
+ ws.emit('close', 1001, Buffer.from('going away'))
+ expect(lines('web client (legacy) disconnected')).toEqual([expect.objectContaining({ endpoint: 'web', client: 'unknown',
+ machineId: expect.any(String), code: 1001, reason: 'going away', aliveMs: expect.any(Number) })])
+ })
+
+ it('logs a client that declared nothing as unknown', async () => {
+ const ws = await selects({})
+ ws.emit('close', 1000, Buffer.alloc(0))
+ expect(lines('web user disconnected')[0]).toMatchObject({ client: 'unknown', version: null })
+ })
+})
diff --git a/backend/src/lib/wsAttribution.test.ts b/backend/src/lib/wsAttribution.test.ts
new file mode 100644
index 000000000..107df5709
--- /dev/null
+++ b/backend/src/lib/wsAttribution.test.ts
@@ -0,0 +1,145 @@
+import { EventEmitter } from 'node:events'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// Roadmap Phase 0 (2026-10-28): the logs could not say which client opened a socket, how it closed or how long it
+// lived, so 8,760 web-ws connects in 45 minutes could not be told apart. Every socket now says so, and each pod logs
+// its counts once a minute, refusals apart from real connects.
+const m = vi.hoisted(() => ({ info: vi.fn() }))
+vi.mock('../utils/logger.js', () => ({ logger: { info: m.info, warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
+vi.mock('./instance.js', () => ({ INSTANCE_ID: 'pod-a-0' }))
+
+import { declaredKind, refusedUpgrade, resetWsCountersForTest, trackSocket, watchUpgrade, wsCounterLine } from './wsAttribution.js'
+
+/** A raw upgrade socket, and the `ws` socket over it once upgraded. */
+const raw = () => new EventEmitter()
+const upgraded = (socket: EventEmitter) => ({ _socket: socket }) as never
+const lines = (message: string) => m.info.mock.calls.filter(c => c[0] === message).map(c => c[1])
+
+beforeEach(() => { vi.clearAllMocks(); resetWsCountersForTest() })
+
+describe('the client a socket declares', () => {
+ it.each([
+ ['client=relay&v=0.9.1', { client: 'relay', version: '0.9.1' }],
+ ['client=group-sync&v=1.4.2', { client: 'group-sync', version: '1.4.2' }],
+ ['client=link', { client: 'link', version: null }],
+ ['client=desktop&v=1.3.0', { client: 'desktop', version: '1.3.0' }],
+ ['client=web', { client: 'web', version: null }],
+ // The phone has sent its release since before `v`.
+ ['client=mobile&release=2.1.0', { client: 'mobile', version: '2.1.0' }],
+ // Nothing declared: an older daemon or app. Anything else is not a kind this backend knows.
+ ['', { client: 'unknown', version: null }],
+ ['client=toaster&v=1', { client: 'unknown', version: '1' }],
+ // A version is a short plain token or nothing: never free text into the logs.
+ ['client=relay&v=1.0%20%3Cscript%3E', { client: 'relay', version: null }],
+ [`client=relay&v=${'9'.repeat(41)}`, { client: 'relay', version: null }],
+ ])('%s', (query, expected) => {
+ expect(declaredKind(new URLSearchParams(query))).toEqual(expected)
+ })
+})
+
+describe('a tracked socket', () => {
+ it('logs its connect and its disconnect: code, reason, lifetime and what its selects were answered', () => {
+ let now = 1_000
+ const socket = trackSocket('web', 'web user', upgraded(raw()), { client: 'relay', version: '0.9.1', userId: 'u1' }, () => now)
+ expect(lines('web user connected')).toEqual([{ endpoint: 'web', client: 'relay', version: '0.9.1', pod: 'pod-a-0', connId: socket.connId, userId: 'u1' }])
+ socket.selected('MACHINE_OFFLINE')
+ now += 400
+ socket.closed(1000, 'handshake failed', { machineId: undefined })
+ // A second close (an error, then the close) is the same socket's end: one line.
+ socket.closed(1006, '')
+ expect(lines('web user disconnected')).toEqual([{ endpoint: 'web', client: 'relay', version: '0.9.1', pod: 'pod-a-0', connId: socket.connId,
+ userId: 'u1', code: 1000, reason: 'handshake failed', aliveMs: 400, selects: 1, select: 'MACHINE_OFFLINE' }])
+ })
+
+ // Review of #2029: a close reason is the peer's own text. Kept short and plain, like the version, so no line carries
+ // control characters, markup or a pasted token-length string.
+ it('keeps a close reason short and plain', () => {
+ const socket = trackSocket('web', 'web user', upgraded(raw()), { client: 'relay', version: null })
+ socket.closed(4000, ` peer\nsaid <b>bye</b>\u0000 ${'x'.repeat(200)}`)
+ const { reason } = lines('web user disconnected')[0] as { reason: string }
+ expect(reason).toBe(`peer said bbye/b ${'x'.repeat(63)}`)
+ expect(reason.length).toBe(80)
+ })
+
+ it('says a socket that never selected so', () => {
+ const socket = trackSocket('web', 'web user', upgraded(raw()), { client: 'web', version: null })
+ socket.closed(1001, '')
+ expect(lines('web user disconnected')[0]).toMatchObject({ selects: 0, select: 'none', code: 1001 })
+ expect(lines('web user disconnected')[0]).not.toHaveProperty('reason')
+ })
+
+ it('gives every socket its own id', () => {
+ const a = trackSocket('observer', 'observer', upgraded(raw()), { client: 'relay', version: null })
+ const b = trackSocket('observer', 'observer', upgraded(raw()), { client: 'relay', version: null })
+ expect(a.connId).not.toBe(b.connId)
+ })
+})
+
+describe('the counters each pod logs', () => {
+ it('count open sockets, connects by client, sockets that lived under 2 s, and refusals apart', () => {
+ let now = 0
+ const clock = () => now
+ const refusedRaw = raw(); watchUpgrade('web', refusedRaw)
+ const shortRaw = raw(); watchUpgrade('web', shortRaw)
+ const longRaw = raw(); watchUpgrade('web', longRaw)
+ const adapterRaw = raw(); watchUpgrade('adapter', adapterRaw)
+ const short = trackSocket('web', 'web user', upgraded(shortRaw), { client: 'relay', version: null }, clock)
+ trackSocket('web', 'web user', upgraded(longRaw), { client: 'mobile', version: '2.1.0' }, clock)
+ trackSocket('adapter', 'adapter', upgraded(adapterRaw), { client: 'daemon', version: '0.9.1' }, clock)
+ // Signed in badly: upgraded, then closed before anything tracked it. Not a connect.
+ refusedRaw.emit('close')
+ // Refused before any upgrade, by the server's handshake limit.
+ refusedUpgrade('observer')
+ now = 1_999
+ short.closed(1000, '')
+ shortRaw.emit('close')
+
+ expect(wsCounterLine()).toEqual({
+ pod: 'pod-a-0',
+ web: { open: 1, connects: 2, clients: { relay: 1, mobile: 1 }, short: 1, refused: 1 },
+ adapter: { open: 1, connects: 1, clients: { daemon: 1 }, short: 0, refused: 0 },
+ observer: { open: 0, connects: 0, clients: {}, short: 0, refused: 1 },
+ agentMessages: { open: 0, connects: 0, clients: {}, short: 0, refused: 0 },
+ })
+ // Each line counts since the one before; open sockets carry over.
+ expect(wsCounterLine().web).toEqual({ open: 1, connects: 0, clients: {}, short: 0, refused: 0 })
+ })
+})
+
+// The server's upgrade hook (server.ts) on a real HTTP server and real `ws` sockets: what the counters lean on is that
+// an upgraded socket's raw socket is the one watched, so a tracked socket is never also counted refused.
+describe('real upgrades', () => {
+ it('count a socket destroyed before its upgrade and one closed right after it as refused, a tracked one as a connect', async () => {
+ const { createServer } = await import('node:http')
+ const { WebSocketServer, WebSocket } = await import('ws')
+ const wss = new WebSocketServer({ noServer: true })
+ const server = createServer()
+ server.on('upgrade', (req, socket, head) => {
+ watchUpgrade('web', socket)
+ const how = new URL(req.url ?? '/', 'http://x').searchParams.get('how')
+ if (how === 'destroy') { socket.destroy(); return }
+ wss.handleUpgrade(req, socket, head, ws => {
+ if (how === 'refuse') { ws.close(4401, 'auth expired'); return }
+ const tracked = trackSocket('web', 'web user', ws, { client: 'relay', version: null })
+ ws.once('close', (code, reason) => tracked.closed(code, reason.toString()))
+ })
+ })
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const port = (server.address() as { port: number }).port
+ const dial = (how: string) => new Promise<void>(resolve => {
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/?how=${how}`)
+ ws.on('open', () => { if (how === 'track') ws.close(1000) })
+ ws.on('error', () => resolve())
+ ws.on('close', () => resolve())
+ })
+ for (const how of ['destroy', 'refuse', 'track']) await dial(how)
+ // The server side's close events land a moment after the client's. Each line counts since the last, so add them up.
+ const seen = { connects: 0, refused: 0, open: -1 }
+ await vi.waitFor(() => {
+ const web = wsCounterLine().web as { open: number; connects: number; refused: number }
+ seen.connects += web.connects; seen.refused += web.refused; seen.open = web.open
+ expect(seen).toEqual({ connects: 1, refused: 2, open: 0 })
+ }, { timeout: 2_000 })
+ server.close()
+ })
+})
diff --git a/backend/src/lib/wsAttribution.ts b/backend/src/lib/wsAttribution.ts
new file mode 100644
index 000000000..f4cf0b2c3
--- /dev/null
+++ b/backend/src/lib/wsAttribution.ts
@@ -0,0 +1,153 @@
+/**
+ * Who each backend socket belongs to, how it ended and how long it lived, for the four sockets the apps and
+ * daemons dial: web-ws, adapter-ws, observer-ws and agent-messages-ws (WebSocket roadmap, Phase 0).
+ *
+ * Prod, 2026-10-28: 8,760 web-ws connects in 45 minutes, 81% never selecting a machine, and the logs said only
+ * who: not which client, how the socket closed, or how long it lived. Every tracked socket now logs a connect line
+ * and a disconnect line with the same connId, and each pod logs its counts once a minute, with refusals (a socket
+ * turned away before or right at its upgrade) apart from real connects.
+ *
+ * `pod` is the process, not the Kubernetes pod: the host name plus the cluster worker's index (`INSTANCE_ID`,
+ * lib/instance.ts). Every worker logs its own counter line, so a pod's totals are the sum of its workers' lines,
+ * and no line is counted twice.
+ */
+import { randomUUID } from 'node:crypto'
+import type { WebSocket } from 'ws'
+import { INSTANCE_ID } from './instance.js'
+import { logger } from '../utils/logger.js'
+
+export type WsEndpoint = 'web' | 'adapter' | 'observer' | 'agentMessages'
+const ENDPOINTS: readonly WsEndpoint[] = ['web', 'adapter', 'observer', 'agentMessages']
+
+/** What a client says it is (`?client=`): the browser, the phone, the desktop app dialling itself, a daemon's relay,
+ * the apps' one-shot trust-group and link sockets; `daemon` is the adapter's own socket. */
+export const WS_CLIENT_KINDS = ['web', 'mobile', 'desktop', 'relay', 'group-sync', 'link', 'daemon'] as const
+export type WsClientKind = typeof WS_CLIENT_KINDS[number] | 'unknown'
+
+/** A socket that lived less than this counts as short: a refusal, a crash loop, or a dial nobody needed. */
+const SHORT_MS = 2_000
+const VERSION = /^[0-9A-Za-z.+-]{1,40}$/
+const REASON_MAX = 80
+
+/** A close reason is the peer's own text (up to 123 bytes): plain characters only, one line, at most REASON_MAX. */
+function plainReason(reason: string | undefined): string | undefined {
+ const plain = reason
+ ?.replace(/[\u0000-\u001f\u007f]/g, ' ')
+ .replace(/[^0-9A-Za-z .,:;_()'/+-]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, REASON_MAX)
+ return plain || undefined
+}
+
+/** The client a socket's query declares, and its version (`?v=`; the phone's `?release=`, which it sent first). */
+export function declaredKind(query: URLSearchParams): { client: WsClientKind; version: string | null } {
+ const declared = query.get('client')
+ const client = (WS_CLIENT_KINDS as readonly string[]).includes(declared ?? '') ? declared as WsClientKind : 'unknown'
+ const version = query.get('v') ?? query.get('release')
+ return { client, version: version && VERSION.test(version) ? version : null }
+}
+
+interface Counts { connects: Partial<Record<WsClientKind, number>>; short: number; refused: number }
+const fresh = (): Counts => ({ connects: {}, short: 0, refused: 0 })
+let open = Object.fromEntries(ENDPOINTS.map(e => [e, 0])) as Record<WsEndpoint, number>
+let counts = Object.fromEntries(ENDPOINTS.map(e => [e, fresh()])) as Record<WsEndpoint, Counts>
+
+/** Set on the raw socket once its `ws` socket is tracked: one that closes without it was refused. */
+const TRACKED = Symbol('wsTracked')
+type RawSocket = { [TRACKED]?: true; once(event: 'close', listener: () => void): unknown }
+const rawOf = (ws: WebSocket): RawSocket | undefined => (ws as unknown as { _socket?: RawSocket })._socket
+
+export interface TrackedSocket {
+ readonly connId: string
+ /** What a select was answered: `accepted`, or the refusal's code. The disconnect line reports the last. */
+ selected(outcome: string): void
+ /** The socket ended. Logs its disconnect line once, with what the endpoint adds. */
+ closed(code: number | undefined, reason: string | undefined, extra?: Record<string, unknown>): void
+}
+
+/**
+ * Starts tracking an accepted socket: logs `<label> connected` and counts it. `fields` are the client and version it
+ * declared plus what the endpoint names it by (user, machine); they are repeated on the disconnect line.
+ */
+export function trackSocket(
+ endpoint: WsEndpoint, label: string, ws: WebSocket,
+ fields: { client: WsClientKind; version: string | null } & Record<string, unknown>,
+ now: () => number = Date.now,
+): TrackedSocket {
+ const raw = rawOf(ws)
+ if (raw) raw[TRACKED] = true
+ const connId = randomUUID()
+ const openedAt = now()
+ const common = { endpoint, client: fields.client, version: fields.version, pod: INSTANCE_ID, connId }
+ const { client: _client, version: _version, ...ids } = fields
+ logger.info(`${label} connected`, { ...common, ...ids })
+ open[endpoint]++
+ const byClient = counts[endpoint].connects
+ byClient[fields.client] = (byClient[fields.client] ?? 0) + 1
+ let selects = 0
+ let outcome = 'none'
+ let ended = false
+ return {
+ connId,
+ selected(result) { selects++; outcome = result },
+ closed(code, reason, extra = {}) {
+ if (ended) return
+ ended = true
+ const aliveMs = now() - openedAt
+ open[endpoint]--
+ if (aliveMs < SHORT_MS) counts[endpoint].short++
+ const defined = Object.fromEntries(Object.entries(extra).filter(([, v]) => v !== undefined))
+ reason = plainReason(reason)
+ logger.info(`${label} disconnected`, {
+ ...common, ...ids, ...defined, ...(code !== undefined ? { code } : {}), ...(reason ? { reason } : {}),
+ aliveMs, selects, select: outcome,
+ })
+ },
+ }
+}
+
+/** Watches a raw upgrade socket for `endpoint`: if it closes before its `ws` socket was tracked, it was refused. */
+export function watchUpgrade(endpoint: WsEndpoint, socket: RawSocket): void {
+ socket.once('close', () => { if (!socket[TRACKED]) counts[endpoint].refused++ })
+}
+
+/** A socket refused before anything could watch it (the server's handshake limit). */
+export function refusedUpgrade(endpoint: WsEndpoint): void {
+ counts[endpoint].refused++
+}
+
+/** The endpoint an upgrade's path names, or null for a socket these counters do not cover. */
+export function endpointOf(path: string): WsEndpoint | null {
+ switch (path) {
+ case '/api/web-ws': return 'web'
+ case '/api/adapter-ws': return 'adapter'
+ case '/api/observer-ws': return 'observer'
+ case '/api/agent-messages-ws': return 'agentMessages'
+ default: return null
+ }
+}
+
+/** This pod's counts since the last line, and its open sockets now. */
+export function wsCounterLine(): Record<string, unknown> {
+ const line: Record<string, unknown> = { pod: INSTANCE_ID }
+ for (const endpoint of ENDPOINTS) {
+ const c = counts[endpoint]
+ const connects = Object.values(c.connects).reduce((sum, n) => sum + (n ?? 0), 0)
+ line[endpoint] = { open: open[endpoint], connects, clients: c.connects, short: c.short, refused: c.refused }
+ counts[endpoint] = fresh()
+ }
+ return line
+}
+
+/** Logs `ws counters` every `intervalMs`; returns its stop. */
+export function startWsCounterLog(intervalMs = 60_000): () => void {
+ const timer = setInterval(() => logger.info('ws counters', wsCounterLine()), intervalMs)
+ timer.unref()
+ return () => clearInterval(timer)
+}
+
+export function resetWsCountersForTest(): void {
+ open = Object.fromEntries(ENDPOINTS.map(e => [e, 0])) as Record<WsEndpoint, number>
+ counts = Object.fromEntries(ENDPOINTS.map(e => [e, fresh()])) as Record<WsEndpoint, Counts>
+}
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 41e78fc7f..df2b66419 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -30,6 +30,7 @@ import { createRouteRateLimit } from './middlewares/routeRateLimit.js'
import { redisWindowCounter } from './lib/redisRateCounter.js'
import { selfProfileFromEnv } from './lib/selfProfile.js'
import { drainAllSockets, openSocketCount, RELEASE_UPGRADE_SLOT, type SlotSocket } from './lib/wsServer.js'
+import { endpointOf, refusedUpgrade, startWsCounterLog, watchUpgrade } from './lib/wsAttribution.js'
// Node ≥ 15 turns an unhandled rejection into a process exit. On a cluster worker that holds thousands of
// sockets, one DB/Redis hiccup inside a fire-and-forget promise would then drop every one of them and
@@ -65,7 +66,11 @@ const app = Fastify({
// data. Nothing in this codebase called setNoDelay() before, so every socket here defaulted to
// Nagle-enabled.
if (socket instanceof net.Socket) socket.setNoDelay(true)
+ const path = (req.url ?? '').split('?')[0]
+ // Counted apart from real connects (lib/wsAttribution.ts): a socket that closes before it is tracked was refused.
+ const endpoint = endpointOf(path)
if (pendingUpgrades >= MAX_PENDING_UPGRADES) {
+ if (endpoint) refusedUpgrade(endpoint)
try { socket.write('HTTP/1.1 503 Service Unavailable\r\nRetry-After: 2\r\nConnection: close\r\nContent-Length: 0\r\n\r\n') } catch { /* ignore */ }
socket.destroy()
return
@@ -85,7 +90,7 @@ const app = Fastify({
// A handshake that never completes (auth call hung, peer went silent) must not hold the socket.
// `ws` resets the timeout to 0 once it completes the upgrade, so this only ever fires pre-upgrade.
if (socket instanceof net.Socket) socket.setTimeout(UPGRADE_HANDSHAKE_TIMEOUT_MS, () => socket.destroy())
- const path = (req.url ?? '').split('?')[0]
+ if (endpoint) watchUpgrade(endpoint, socket)
if (path === '/api/observer-ws') {
handleObserverUpgrade(req, socket, head)
return
@@ -150,6 +155,8 @@ async function start(): Promise<void> {
useSharedSsoProfileStore(redisSsoProfileStore)
// Rate limits count across every process and pod (lib/rateLimit.ts), not once per process.
useSharedRateCounter(redisWindowCounter(pub))
+ // Each pod's socket counts once a minute: open, connects by client, short-lived, refused (WebSocket roadmap Phase 0).
+ startWsCounterLog()
configureSwarmStamps(redisSwarmStamps(), { reads: env.SWARM_READ_CACHE === 'on', maxBytes: env.SWARM_CACHE_MB * 2 ** 20 })
// Hot Swarm reads name their indexes once the database is seen to have them (superTabs/parts/indexed.ts).
watchGroupIndexes(prisma)
diff --git a/backend/src/superTabs/cache.ts b/backend/src/superTabs/cache.ts
index 1553676a9..77ef82be1 100644
--- a/backend/src/superTabs/cache.ts
+++ b/backend/src/superTabs/cache.ts
@@ -156,6 +156,11 @@ export class CacheView {
get available(): boolean { return this.stamps !== null }
+ /** This Swarm's main stamp as the view read it, or none without stamps or a cache. */
+ mainStamp(tabId: string): number | undefined {
+ return this.cache ? this.stamps?.get(tabId)?.main : undefined
+ }
+
/** The value `load` gives for this Swarm at the view's stamp: held, or loaded and held. `scope` says which stamps it
* depends on: 'main' for what a machine's reading never changes, 'all' for anything holding machine parts. */
async get<T>(tabId: string, name: string, scope: StampScope | 'all', load: () => Promise<T>): Promise<T> {
diff --git a/backend/src/superTabs/pollMemory.test.ts b/backend/src/superTabs/pollMemory.test.ts
index ae481cc24..43b7e56e3 100644
--- a/backend/src/superTabs/pollMemory.test.ts
+++ b/backend/src/superTabs/pollMemory.test.ts
@@ -23,27 +23,49 @@ function fakeRedis() {
describe('the delivery poll memory every server shares', () => {
it('answers with the time any server last remembered for a caller', async () => {
const redis = fakeRedis()
- await redisPollMemory(redis).set('tab:agent:user', 1_234)
- expect(await redisPollMemory(redis).get('tab:agent:user')).toBe(1_234)
+ await redisPollMemory(redis).set('tab:agent:user', { at: 1_234 })
+ expect(await redisPollMemory(redis).get('tab:agent:user')).toEqual({ at: 1_234 })
expect(await redisPollMemory(redis).get('tab:agent:other')).toBeUndefined()
})
// A key per tab, agent and caller that never expired would grow Redis by one for every agent that ever polled.
it('forgets each caller 30 seconds after it was remembered', async () => {
const redis = fakeRedis()
- await redisPollMemory(redis).set('tab:agent:user', 1_234)
+ await redisPollMemory(redis).set('tab:agent:user', { at: 1_234 })
redis.tick(29_999)
- expect(await redisPollMemory(redis).get('tab:agent:user')).toBe(1_234)
+ expect(await redisPollMemory(redis).get('tab:agent:user')).toEqual({ at: 1_234 })
redis.tick(1)
expect(await redisPollMemory(redis).get('tab:agent:user')).toBeUndefined()
})
it('keeps its keys apart from the rest of Redis', async () => {
const redis = fakeRedis()
- await redisPollMemory(redis).set('tab:agent:user', 1)
+ await redisPollMemory(redis).set('tab:agent:user', { at: 1 })
expect([...redis.keys.keys()]).toEqual(['swarm:polled:tab:agent:user'])
})
+ // A held delivery is answered from what the last full poll found open (store.ts deliveries), on whichever server polls next.
+ it('gives back the open deliveries a full poll found, the stamp it found them at and the grants it checked', async () => {
+ const redis = fakeRedis()
+ const found = { at: 1_234, open: { stamp: 7, seen: ['d1', 'd2'], allowed: ['d2'], swarm: { workspaceId: 'w1', environment: 'prod' },
+ grants: { a1: { contributorId: 'u1', machineId: 'm1', machineOwnerId: 'u2', hostGrant: 'g1' }, a2: { contributorId: 'u2', machineId: 'm2', machineOwnerId: 'u2', hostGrant: null } } } }
+ await redisPollMemory(redis).set('tab:agent:user', found)
+ expect(await redisPollMemory(redis).get('tab:agent:user')).toEqual(found)
+ })
+
+ // During a deploy an older server still writes the bare time: its full poll counts, with nothing open remembered.
+ it('reads the bare time an older server wrote', async () => {
+ const redis = fakeRedis()
+ await redis.set('swarm:polled:tab:agent:user', '1234', 'PX', 30_000)
+ expect(await redisPollMemory(redis).get('tab:agent:user')).toEqual({ at: 1_234 })
+ })
+
+ it('reads a remembered poll whose open deliveries are malformed as never remembered', async () => {
+ const redis = fakeRedis()
+ await redis.set('swarm:polled:tab:agent:user', JSON.stringify({ at: 1, open: { stamp: 7, seen: [], allowed: [], swarm: { environment: 'prod' }, grants: { a1: { machineId: 'm1' } } } }), 'PX', 30_000)
+ expect(await redisPollMemory(redis).get('tab:agent:user')).toBeUndefined()
+ })
+
it('reads a value it cannot use as never remembered', async () => {
const redis = fakeRedis()
await redis.set('swarm:polled:tab:agent:user', 'not a time', 'PX', 30_000)
diff --git a/backend/src/superTabs/pollMemory.ts b/backend/src/superTabs/pollMemory.ts
index 28262e30d..1802d4c00 100644
--- a/backend/src/superTabs/pollMemory.ts
+++ b/backend/src/superTabs/pollMemory.ts
@@ -1,5 +1,6 @@
+import { z } from 'zod'
import { SWEEP_EVERY_MS } from './liveness.js'
-import type { PollMemory } from './store.js'
+import type { PollMemory, Polled } from './store.js'
/** The Redis commands the memory needs: the bus' fail-fast connection (lib/bus.ts `pub`) in production. */
export interface PollRedis {
@@ -7,6 +8,25 @@ export interface PollRedis {
set(key: string, value: string, mode: 'PX', ms: number): Promise<unknown>
}
+const grant = z.object({ contributorId: z.string(), machineId: z.string(), machineOwnerId: z.string(), hostGrant: z.string().nullable() })
+const polled = z.object({
+ at: z.number().finite(),
+ open: z.object({ stamp: z.number().finite(), seen: z.array(z.string()), allowed: z.array(z.string()),
+ swarm: z.object({ workspaceId: z.string().optional(), environment: z.string() }), grants: z.record(z.string(), grant) }).optional(),
+})
+
+/** A remembered poll as stored: JSON, or the bare time an older server wrote. Anything else was never remembered. */
+function parse(value: string | null): Polled | undefined {
+ if (value === null) return undefined
+ if (/^\d+$/.test(value)) return { at: Number(value) }
+ try {
+ const read = polled.safeParse(JSON.parse(value))
+ return read.success ? read.data : undefined
+ } catch {
+ return undefined
+ }
+}
+
/**
* Each caller's last full delivery poll, in Redis so every server answers the quiet poll from any server's full one (stability
* roadmap 2.4). One key per tab, agent and caller, gone after SWEEP_EVERY_MS: an older one is never read anyway.
@@ -14,10 +34,7 @@ export interface PollRedis {
export function redisPollMemory(redis: PollRedis): PollMemory {
const key = (k: string) => `swarm:polled:${k}`
return {
- async get(k) {
- const value = Number(await redis.get(key(k)) ?? NaN)
- return Number.isFinite(value) ? value : undefined
- },
- async set(k, at) { await redis.set(key(k), String(at), 'PX', SWEEP_EVERY_MS) },
+ get: async k => parse(await redis.get(key(k))),
+ async set(k, value) { await redis.set(key(k), JSON.stringify(value), 'PX', SWEEP_EVERY_MS) },
}
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 01d87f3bd..f156fc249 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -181,6 +181,28 @@ export function afterCommit(tx: Transaction, callback: () => void): void {
if (!pending) throw new Error('afterCommit needs a client from a Swarm transaction (store.ts transaction).')
pending.push(callback)
}
+/** An agent's open deliveries, oldest first and each conversation's tied rows in its order (pageReads.ts): one indexed
+ * read, and the tied messages' sequences only when there are ties. */
+const openDeliveries = async (tx: Transaction, tabId: string, agentId: string) => inConversationOrder(tx, tabId,
+ await tx.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } }, orderBy: { createdAt: 'asc' }, take: 100 }))
+
+/** The grants a held answer checks again: the agent's own and those of the agents that sent what it allowed. */
+function grantsOf(state: SuperTabState, agentId: string, allowed: SuperTabDelivery[]) {
+ const grants: Record<string, AgentGrant> = {}
+ for (const id of [agentId, ...allowed.filter(d => d.authorKind === 'agent').map(d => d.authorId)]) {
+ const found = state.agents.find(a => a.id === id)
+ if (found) grants[id] = { contributorId: found.contributorId, machineId: found.machineId, machineOwnerId: found.machineOwnerId, hostGrant: found.hostGrant ?? null }
+ }
+ return { swarm: { workspaceId: state.workspaceId, environment: state.environment }, grants }
+}
+
+const sameIds = (rows: SuperTabDelivery[], ids: string[]) => rows.length === ids.length && rows.every(r => ids.includes(r.id))
+
+/** Whose full poll `deliveries` remembers: the caller, and a team session apart, as it may act only for its own machine's
+ * agents (teamHost) while its person may act for any of theirs. */
+const pollKey = (user: AuthUser, tabId: string, agentId: string) =>
+ `${tabId}:${agentId}:${user.sub}${user.harnessSessionKind === 'team' ? `:team:${user.harnessComputerId ?? ''}` : ''}`
+
/** Logged, never thrown: without the memory the delivery poll just runs in full. */
const pollMemoryFailed = (error: unknown): void => {
logger.warn('[super-tab] delivery poll memory unavailable', { error: error instanceof Error ? error.message : String(error) })
@@ -240,21 +262,36 @@ export interface SuperTabStoreHooks {
/** Which agent, of which Swarm, on which machine, has a delivery to read. */
export interface DeliveriesWaiting { machineId: string; tabId: string; agentId: string }
+/** What of a Swarm an agent's grant is checked against (SuperTabStore.grantHolds). */
+export type SwarmGrant = Pick<SuperTabState, 'workspaceId' | 'environment'>
+/** What of an agent its grant is checked against: who lent which machine to whom, under which share grant. */
+export type AgentGrant = Pick<Agent, 'contributorId' | 'machineId' | 'machineOwnerId' | 'hostGrant'>
+
+/** A caller's last full delivery poll: when it succeeded and, when it found deliveries open, what it found. */
+export interface Polled {
+ at: number
+ /** The open deliveries it read, those of them it let reach the agent, and the Swarm's main stamp (cache.ts) read before
+ * it loaded: while all three are unchanged, a held delivery is answered without loading the Swarm (deliveries). The
+ * grants of the agent and of the agents that sent what it allowed, by agent id, are checked again on every such answer:
+ * they rest on Workspaces, machines and shares, which no Swarm write records. */
+ open?: { stamp: number; seen: string[]; allowed: string[]; swarm: SwarmGrant; grants: Record<string, AgentGrant> }
+}
+
/** Where `deliveries` remembers each caller's last full poll. Either call may throw: the poll then runs in full. */
export interface PollMemory {
- get(key: string): Promise<number | undefined>
+ get(key: string): Promise<Polled | undefined>
/** Remembered for SWEEP_EVERY_MS at least; an older entry is never read. */
- set(key: string, at: number): Promise<void>
+ set(key: string, polled: Polled): Promise<void>
}
/** One server's own memory: with several servers behind a load balancer, each runs its own full polls. */
export function localPollMemory(now: () => number): PollMemory {
- const polled = new Map<string, number>()
+ const polled = new Map<string, Polled>()
return {
get: async key => polled.get(key),
- set: async (key, at) => {
- polled.set(key, at)
- if (polled.size > POLLED_CAP) for (const [k, last] of polled) if (now() - last >= SWEEP_EVERY_MS) polled.delete(k)
+ set: async (key, value) => {
+ polled.set(key, value)
+ if (polled.size > POLLED_CAP) for (const [k, last] of polled) if (now() - last.at >= SWEEP_EVERY_MS) polled.delete(k)
},
}
}
@@ -560,13 +597,19 @@ export class SuperTabStore {
* contributor, who must still be in the Swarm's Workspace. Its host need not be, as it need not be in the Swarm. */
/** `reads`: one request's reads, shared by every agent it checks (GrantReads). */
async agentGrant(tx: Transaction, state: SuperTabState, target: Agent, reads?: GrantReads): Promise<void> {
+ await this.grantHolds(tx, state, target, () => person(state, target.contributorId), reads)
+ }
+
+ /** What an agent's grant rests on outside the Swarm: its contributor's Workspace membership, its machine and, lent, the
+ * machine's share. `inSwarm` checks the contributor is still in it, at the point the full check always did. */
+ private async grantHolds(tx: Transaction, state: SwarmGrant, target: AgentGrant, inSwarm: () => void, reads?: GrantReads): Promise<void> {
const once = <T>(key: string, read: () => Promise<T>) => reads ? reads.once(key, read) : read()
await once(`workspace:${state.workspaceId}:${target.contributorId}`, () => requireWorkspaceAccess(tx, state, target.contributorId))
const machine = await once(machineKey(state.environment, target.machineId, target.machineOwnerId), () => tx.machine.findFirst({
where: { machineId: target.machineId, userId: target.machineOwnerId, autonomousEnv: state.environment, ...machineAlive } }))
if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
if (target.contributorId !== machine.userId) {
- person(state, target.contributorId)
+ inSwarm()
const contributor = await once(`user:${target.contributorId}`, () => tx.user.findUnique({ where: { id: target.contributorId }, select: { email: true, autonomousEnv: true } }))
const share = await once(`share:${machine.machineId}`, () => tx.machineShare.findUnique({ where: { machineId: machine.machineId } }))
if (!contributor || contributor.autonomousEnv !== state.environment || !share || share.ownerId !== machine.userId ||
@@ -2063,16 +2106,56 @@ export class SuperTabStore {
* succeeded is ever answered this way, so a stranger or a revoked host meets the authority checks every time.
*/
async deliveries(user: AuthUser, tabId: string, agentId: string) {
- const key = `${tabId}:${agentId}:${user.sub}`
+ const key = pollKey(user, tabId, agentId)
const last = await this.polls.get(key).catch(error => { pollMemoryFailed(error); return undefined })
- if (last !== undefined && this.now() - last < SWEEP_EVERY_MS
- && !await this.db.superTabDelivery.findFirst({ where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } }, select: { id: true } })) return []
- const rows = await this.fullDeliveries(user, tabId, agentId)
- await this.polls.set(key, this.now()).catch(pollMemoryFailed)
- return rows
+ if (last !== undefined && this.now() - last.at < SWEEP_EVERY_MS) {
+ const open = await openDeliveries(this.db, tabId, agentId)
+ if (!open.length) return []
+ // A held delivery stays open for as long as its host cannot type it, possibly hours, polled each second (Diego, 10-28):
+ // the same open deliveries at the same main stamp are allowed as the full poll found them. Anything a Swarm write
+ // revokes moves the stamp; what no Swarm write records (a Workspace, a machine, a share) is checked again each time.
+ // A turn typed into a terminal rests on its typist's access too (native.ts allowsDelivery): it takes the full poll.
+ const seen = last.open, stamp = seen && (await this.view([tabId])).mainStamp(tabId)
+ if (seen?.grants[agentId] && stamp === seen.stamp && sameIds(open, seen.seen) && !open.some(d => d.nativeContextId)) {
+ return this.heldDeliveries(user, agentId, open, seen)
+ }
+ }
+ const view = await this.view([tabId]), stamp = view.mainStamp(tabId)
+ const { open, allowed, state } = await this.fullDeliveries(user, tabId, agentId, view)
+ await this.polls.set(key, { at: this.now(), ...open.length && stamp !== undefined
+ ? { open: { stamp, seen: open.map(d => d.id), allowed: allowed.map(d => d.id), ...grantsOf(state, agentId, allowed) } } : {} })
+ .catch(pollMemoryFailed)
+ return allowed
}
- private async fullDeliveries(user: AuthUser, tabId: string, agentId: string) {
+ /** The open deliveries the last full poll allowed, while the Swarm is as it read it: the grants it checked are checked
+ * again, as the full poll does: the agent's refuses the poll, a sender's withholds what it sent (senderAllowed). */
+ private async heldDeliveries(user: AuthUser, agentId: string, open: SuperTabDelivery[], seen: NonNullable<Polled['open']>) {
+ // One request's reads, shared by the agent's check and its senders' (GrantReads), never kept past it.
+ const target = seen.grants[agentId]!, inSwarm = () => {}, reads = new GrantReads()
+ const team = await this.teamHost(this.db, user)
+ if (team !== null && target.machineId !== team) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
+ await this.grantHolds(this.db, seen.swarm, target, inSwarm, reads)
+ const senders = new Map<string, Promise<boolean>>()
+ const sent = (id: string) => senders.get(id) ?? senders.set(id, this.grantHolds(this.db, seen.swarm, seen.grants[id]!, inSwarm, reads)
+ .then(() => true, error => { if (error instanceof SuperTabError) return false; throw error })).get(id)!
+ const allowed: SuperTabDelivery[] = []
+ for (const delivery of open) {
+ if (!seen.allowed.includes(delivery.id)) continue
+ if (delivery.authorKind !== 'agent' || seen.grants[delivery.authorId] && await sent(delivery.authorId)) allowed.push(delivery)
+ }
+ return allowed
+ }
+
+ private async fullDeliveries(user: AuthUser, tabId: string, agentId: string, view: CacheView) {
+ // Every write below is the Lead's: its time checks, idle stops, update request, digest and stale runs. Any other agent's
+ // poll only reads, through the read cache with no transaction (Diego's review of 10-28, item 1: 20 workers were 40
+ // whole-Swarm loads, clones and empty commits a minute). The authority checks are the same; a claim checks them again.
+ const read = await this.readLoad(user, tabId, {}, view)
+ if (!ledProject(read.state, agentId)) {
+ author(read.state, await this.actor(this.db, user, read.state, agentId), true)
+ return this.allowedDeliveries(this.db, read.state, tabId, agentId)
+ }
return transaction(this.db, async tx => {
let loaded = await this.load(tx, user, tabId)
// Work finished since the last digest and archived or asleep since still shipped, but ordinary loads leave it out
@@ -2144,16 +2227,20 @@ export class SuperTabStore {
await this.save(tx, loaded, state, clock.next(), [...judgedMachines(loaded.state, state, written), ...stoppedMachines(state, idle),
...woken ? [{ kind: 'agent' as const, key: agentId }] : []])
await this.writeMessages(tx, tabId, state, written, sequences, true)
- const rows = await inConversationOrder(tx, tabId, await tx.superTabDelivery.findMany({
- where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } }, orderBy: { createdAt: 'asc' }, take: 100 }))
- const allowed: SuperTabDelivery[] = []
- for (const delivery of rows) {
- if (this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery)) allowed.push(delivery)
- }
- return allowed
+ return this.allowedDeliveries(tx, state, tabId, agentId)
})
}
+ /** The agent's open deliveries, and those of them its Swarm still lets reach it. */
+ private async allowedDeliveries(tx: Transaction, state: SuperTabState, tabId: string, agentId: string) {
+ const open = await openDeliveries(tx, tabId, agentId)
+ const allowed: SuperTabDelivery[] = []
+ for (const delivery of open) {
+ if (this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery)) allowed.push(delivery)
+ }
+ return { open, allowed, state }
+ }
+
/** A withdrawn host can retire its own journal without regaining shared
* conversation access. Machine ownership is captured when input is created. */
async deliveryReceipt(user: AuthUser, tabId: string, agentId: string, deliveryId: string) {
diff --git a/cli/src/gateway/tabRelay.spec.ts b/cli/src/gateway/tabRelay.spec.ts
index 7e9037a15..c7b37f049 100644
--- a/cli/src/gateway/tabRelay.spec.ts
+++ b/cli/src/gateway/tabRelay.spec.ts
@@ -12,6 +12,7 @@ vi.mock('../lib/wsLiveness.js', () => ({
}))
import { SHARED_TAB_FRAME_MAX } from '../lib/e2ee/tabSession.js'
import { TAB_RELAY_MAX_FRAME, TAB_RELAY_QUEUE, TAB_RELAY_READY_WAIT_MS, TAB_RELAY_SEND_DEADLINE_MS, TabRelaySockets } from './tabRelay.js'
+import { VERSION } from '../version.js'
const TAB = 'a1b2c3d4e5f6a1b2c3d4e5f6'
const TAB2 = 'b1b2c3d4e5f6a1b2c3d4e5f6'
@@ -92,7 +93,9 @@ describe('the gateway\'s sockets to the shared tabs\' relay', () => {
await relay.open(TAB)
await relay.open(TAB)
await until(() => server.conns.length === 1)
- expect(server.conns[0].url).toBe(`/api/agent-messages-ws?share=${TAB}&machine=bob-mini&autonomousEnv=staging`)
+ // It says it is a daemon's relay, and which CLI (WebSocket roadmap Phase 0).
+ expect(server.conns[0].url).toBe(`/api/agent-messages-ws?share=${TAB}&machine=bob-mini&autonomousEnv=staging`
+ + `&client=relay&v=${encodeURIComponent(VERSION)}`)
expect(server.conns[0].protocol).toBe('tok-1')
await relay.open(TAB)
await sleep(30)
diff --git a/cli/src/gateway/tabRelay.ts b/cli/src/gateway/tabRelay.ts
index 2c7f01592..1fb8d3471 100644
--- a/cli/src/gateway/tabRelay.ts
+++ b/cli/src/gateway/tabRelay.ts
@@ -18,6 +18,7 @@ import { WebSocket } from 'ws'
import type { GatewayEvents, TabRelay } from '../core/api.js'
import { SHARED_TAB_FRAME_MAX } from '../lib/e2ee/tabSession.js'
import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from '../lib/wsLiveness.js'
+import { declaredClientQuery } from '../lib/declaredClient.js'
/** The relay closes a socket that sends a frame bigger than this (agentMessagesWs.ts `MAX_FRAME`): refused here first. */
export const TAB_RELAY_MAX_FRAME = SHARED_TAB_FRAME_MAX
@@ -141,7 +142,7 @@ export class TabRelaySockets implements TabRelay {
if (entry.closed) return
const { base, environment } = this.deps
const url = `${base.replace(/\/$/, '')}/api/agent-messages-ws?share=${encodeURIComponent(sharedTabId)}`
- + `&machine=${encodeURIComponent(this.deps.machineId())}&autonomousEnv=${encodeURIComponent(environment)}`
+ + `&machine=${encodeURIComponent(this.deps.machineId())}&autonomousEnv=${encodeURIComponent(environment)}&${declaredClientQuery('relay')}`
let ws: WebSocket
try {
ws = new WebSocket(url, [token], { handshakeTimeout: HANDSHAKE_TIMEOUT_MS, maxPayload: MAX_PAYLOAD })
diff --git a/cli/src/lib/declaredClient.ts b/cli/src/lib/declaredClient.ts
new file mode 100644
index 000000000..2913f485f
--- /dev/null
+++ b/cli/src/lib/declaredClient.ts
@@ -0,0 +1,11 @@
+/**
+ * What a daemon's backend socket says it is (`?client=`, `?v=`), read by the backend's lib/wsAttribution.ts.
+ * Prod, 2026-10-28: 2,304 of 2,308 web-ws opens in 15 minutes declared nothing, so nobody could say which client
+ * churned (WebSocket roadmap Phase 0). `relay`: the daemon's relays (web-ws, observer-ws, agent-messages-ws);
+ * `link`: `harness link connect`'s one-shot socket.
+ */
+import { VERSION } from '../version.js'
+
+export function declaredClientQuery(client: 'relay' | 'link'): string {
+ return `client=${client}&v=${encodeURIComponent(VERSION)}`
+}
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index ed82eaca2..8596ed605 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -16,6 +16,7 @@ import type { TerminalBinaryClear } from '../terminalBinary.js'
import { deriveTerminalBinaryKey, openTerminalBinary, sealTerminalBinary } from './terminalSeal.js'
import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
import { ReplayWindow } from './replayWindow.js'
+import { declaredClientQuery } from '../declaredClient.js'
type Frame = Record<string, unknown>
@@ -209,7 +210,7 @@ export async function connectWithPassword(opts: {
* machineId gets pinned back by a target that understands it, so the link works both ways. */
self?: { machineId?: string; kind: 'machine' | 'viewer'; label?: string }
}): Promise<PwConnectResult> {
- const url = `${opts.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(opts.autonomousEnv)}`
+ const url = `${opts.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(opts.autonomousEnv)}&${declaredClientQuery('link')}`
const ws = new WebSocket(url, [opts.accessToken])
const sid = C.newPairId()
const sidB64 = C.b64e(sid)
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index b03751a8e..3488db87d 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -39,6 +39,7 @@ import { RemoteViewerProxy } from './remoteViewerProxy.js'
import { VIEWER_UP_TYPES } from './viewerWire.js'
import { isWrapped } from './e2ee/core.js'
import { admitRelayedPairFrame, isPairFrameType } from './e2ee/applicationFrames.js'
+import { declaredClientQuery } from './declaredClient.js'
const CONNECT_TIMEOUT_MS = 15_000
const LINGER_MS = 30_000
@@ -501,7 +502,7 @@ export class RemoteRelayPool {
const peer = this.peers.get(machineId)
if (!peer) throw new RelayConnectError('NO_PEER_LINK')
const token = await this.auth.accessToken({ force: forceRefresh })
- const url = `${this.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(autonomousEnv)}`
+ const url = `${this.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(autonomousEnv)}&${declaredClientQuery('relay')}`
const ws = new WebSocket(url, [token])
// An 'error' with no listener throws out of the emitter and takes the daemon down. The handshake's
// once('error') below is consumed by its first emit, and nothing listens after the handshake at all;
diff --git a/cli/src/lib/remoteRelayRestart.spec.ts b/cli/src/lib/remoteRelayRestart.spec.ts
index 7c068ce95..da47ec451 100644
--- a/cli/src/lib/remoteRelayRestart.spec.ts
+++ b/cli/src/lib/remoteRelayRestart.spec.ts
@@ -7,6 +7,7 @@ import { MachinePeerStore } from './e2ee/machinePeers.js'
import { b64e, newIdentity } from './e2ee/core.js'
import { E2eeStore } from './e2ee/store.js'
import type { LocalClientSink } from '../backendSocket.js'
+import { VERSION } from '../version.js'
const machineId = 'abcdabcdabcdabcdabcdabcdabcdabcd'
type Frame = { type: string; payload?: Record<string, unknown> }
@@ -15,6 +16,7 @@ afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(
async function fixture(opts: { offline?: boolean; lingerMs?: number } = {}) {
const sockets = new Map<string, WebSocket>()
+ const urls: string[] = []
let next = 0
let hellos = 0
const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' })
@@ -34,7 +36,8 @@ async function fixture(opts: { offline?: boolean; lingerMs?: number } = {}) {
`ws://127.0.0.1:${(wss.address() as AddressInfo).port}`,
self, peers, { p2p: false, lingerMs: opts.lingerMs },
)
- wss.on('connection', ws => {
+ wss.on('connection', (ws, req) => {
+ urls.push(req.url ?? '')
const id = `remote-${++next}`
sockets.set(id, ws)
ws.on('close', () => { sockets.delete(id); manager.dropSession(id) })
@@ -58,7 +61,7 @@ async function fixture(opts: { offline?: boolean; lingerMs?: number } = {}) {
await new Promise<void>(resolve => wss.close(() => resolve()))
})
return {
- pool, peers, peerPub, hellos: () => hellos,
+ pool, peers, peerPub, hellos: () => hellos, urls,
select: { type: 'machine_select', payload: { machineId } },
restart() { manager = new E2eeManager(managerDeps) },
status(online: boolean) { for (const ws of sockets.values()) ws.send(JSON.stringify({ type: 'node_status', payload: { online } })) },
@@ -66,6 +69,13 @@ async function fixture(opts: { offline?: boolean; lingerMs?: number } = {}) {
}
describe('remote daemon restart recovery', () => {
+ // WebSocket roadmap Phase 0: 2,304 of 2,308 web-ws opens in 15 minutes declared nothing (prod, 2026-10-28).
+ it('dials as a daemon relay, saying which CLI', async () => {
+ const f = await fixture({ offline: true })
+ await f.pool.acquire(machineId, 'prod', f.select, { sendFrame: () => true, sendBinary: () => true }, () => {}).catch(() => {})
+ expect(f.urls).toEqual([`/api/web-ws?autonomousEnv=prod&client=relay&v=${encodeURIComponent(VERSION)}`])
+ })
+
it('reports an offline peer immediately during the handshake and keeps its trust', async () => {
const f = await fixture({ offline: true })
await expect(f.pool.acquire(machineId, 'prod', f.select, { sendFrame: () => true, sendBinary: () => true }, () => {}))
diff --git a/cli/src/sharing/relay.spec.ts b/cli/src/sharing/relay.spec.ts
index 551fc8ecd..ec8f176e3 100644
--- a/cli/src/sharing/relay.spec.ts
+++ b/cli/src/sharing/relay.spec.ts
@@ -16,6 +16,7 @@ vi.mock('ws', async () => {
})
vi.mock('../lib/wsLiveness.js', () => ({ BACKEND_IDLE_DEADLINE_MS: 75_000, watchSocketLiveness: (_ws: unknown, opts: unknown) => { state.liveness = opts; return { stop: state.stop } } }))
import { HarnessShareRelay, SharingEndedError } from './relay.js'
+import { VERSION } from '../version.js'
import { SHARE_REQUEST_TYPES, SHARE_RESULT_TYPES } from './protocol.js'
describe('recipient relay', () => {
const identity = newIdentity()
@@ -50,7 +51,9 @@ describe('recipient relay', () => {
}
it('uses the account token and exact grant, authenticates the owner, and decrypts terminal/viewer output', async () => {
const { session, ws, owner } = await ready()
- expect(ws.args).toEqual(['ws://localhost:1234/api/observer-ws?share=share&autonomousEnv=prod', ['signed-in-token'], expect.any(Object)])
+ // It says it is a daemon's relay, and which CLI (WebSocket roadmap Phase 0).
+ expect(ws.args).toEqual([`ws://localhost:1234/api/observer-ws?share=share&autonomousEnv=prod&client=relay&v=${encodeURIComponent(VERSION)}`,
+ ['signed-in-token'], expect.any(Object)])
expect(sink.sendFrame).toHaveBeenCalledWith({ type: 'connected', payload: { machineId: 'machine', e2ee: false, readOnly: true } })
await session.send({ type: 'terminal_open', payload: { agentId: 'agent' } })
const packet = JSON.parse(ws.send.mock.calls.at(-1)[0])
diff --git a/cli/src/sharing/relay.ts b/cli/src/sharing/relay.ts
index fe50f22e7..fadb2c54f 100644
--- a/cli/src/sharing/relay.ts
+++ b/cli/src/sharing/relay.ts
@@ -6,6 +6,7 @@ import type { RelaySession } from '../lib/remoteRelay.js'
import { DAEMON_LOCAL_ONLY_TYPES } from '../lib/relayFrames.js'
import { recipientHandshake, type ObserverCipher } from './crypto.js'
import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness } from '../lib/wsLiveness.js'
+import { declaredClientQuery } from '../lib/declaredClient.js'
export interface SharedHarnessReference {
id: string; agentId: string; name: string; engine: string | null; ownerPublicKey: string; expiresAt: string
@@ -29,6 +30,7 @@ export class HarnessShareRelay {
if (!share) throw new SharingEndedError('Sharing ended or invitation expired')
const token = await this.auth.accessToken()
const url = `${this.backendWsBase.replace(/\/$/, '')}/api/observer-ws?share=${encodeURIComponent(shareId)}&autonomousEnv=${encodeURIComponent(this.environment)}`
+ + `&${declaredClientQuery('relay')}`
const ws = new WebSocket(url, [token], { handshakeTimeout: 10_000, maxPayload: 3 * 1024 * 1024 })
const ephemeral = newEphemeral()
let cipher: ObserverCipher | null = null, detached = false, settled = false
diff --git a/desktop/lib/main.dart b/desktop/lib/main.dart
index 3e92e6db6..56fe3fcf5 100644
--- a/desktop/lib/main.dart
+++ b/desktop/lib/main.dart
@@ -4,6 +4,7 @@ import 'package:flutter/widgets.dart';
import 'app_shell.dart';
import 'core/connected_semantics.dart';
+import 'ws/ws_conn.dart' show rememberAppVersionForSockets;
import 'update/started_marker.dart';
import 'desktop_workspace.dart'
if (dart.library.js_interop) 'web/web_entry.dart';
@@ -18,6 +19,7 @@ import 'desktop_workspace.dart'
Future<void> main() async {
HarnessWidgetsBinding();
prepareConsole();
+ unawaited(rememberAppVersionForSockets());
await startHarness(
authenticatedScreen: authenticatedWorkspace,
frame: appFrame,
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 8677383f9..c1a43bf7e 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -126,11 +126,13 @@ class _SuperTabViewState extends State<SuperTabView>
// Each list's dividing row: see [_splitAt].
final _split = <String, SuperTabMessage>{};
final _newerRows = UniqueKey();
- int _mentionIndex = 0;
+ // The composer's completions are drawn by builders of their own, so typing
+ // and choosing among them never rebuild the transcript.
+ final _mentionIndex = ValueNotifier(0);
late final _tagBackspace = _TagBackspace(
() => c.mentions(c.selectedId).values,
);
- String? _dismissedMention;
+ final _dismissedMention = ValueNotifier<String?>(null);
String? _completionPrefix;
/// The folders whose paths were dropped into each chat's message: what
@@ -404,6 +406,8 @@ class _SuperTabViewState extends State<SuperTabView>
_dial.cancel();
_litTimer?.cancel();
_composer.dispose();
+ _mentionIndex.dispose();
+ _dismissedMention.dispose();
_focus.dispose();
_pullRequestsFocus.dispose();
for (final scroll in _scroll.values) {
@@ -417,7 +421,7 @@ class _SuperTabViewState extends State<SuperTabView>
Future<void> _send() async {
final choices = _completionChoices;
if (choices.isNotEmpty) {
- choices[_mentionIndex.clamp(0, choices.length - 1)].choose();
+ choices[_mentionIndex.value.clamp(0, choices.length - 1)].choose();
return;
}
if (!c.canWrite ||
@@ -572,10 +576,8 @@ class _SuperTabViewState extends State<SuperTabView>
final prefix = value.selection.isValid
? value.text.substring(0, value.selection.baseOffset)
: null;
- setState(() {
- if (_completionPrefix != prefix) _mentionIndex = 0;
- _completionPrefix = prefix;
- });
+ if (_completionPrefix != prefix) _mentionIndex.value = 0;
+ _completionPrefix = prefix;
}
({int start, int end, String query})? get _workgroupAtCursor {
@@ -587,7 +589,7 @@ class _SuperTabViewState extends State<SuperTabView>
}
final end = value.selection.baseOffset;
final prefix = value.text.substring(0, end);
- if (prefix == _dismissedMention) return null;
+ if (prefix == _dismissedMention.value) return null;
final match = RegExp(r'(?:^|[\s(])#([^\s#`()]*)$').firstMatch(prefix);
if (match == null) return null;
// A reference picker must not interrupt Markdown code or URL fragments.
@@ -680,7 +682,7 @@ class _SuperTabViewState extends State<SuperTabView>
final text = _composer.text.replaceRange(at.start, at.end, token);
final caret = at.start + token.length;
c.setDraft(c.selectedId, text);
- setState(() => _dismissedMention = text.substring(0, caret));
+ _dismissedMention.value = text.substring(0, caret);
_composer.value = TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: caret),
@@ -689,7 +691,7 @@ class _SuperTabViewState extends State<SuperTabView>
}
void _moveCompletion(int index) {
- setState(() => _mentionIndex = index);
+ _mentionIndex.value = index;
WidgetsBinding.instance.addPostFrameCallback((_) {
final context = _completionKeys[index].currentContext;
if (mounted && context != null) {
@@ -726,7 +728,7 @@ class _SuperTabViewState extends State<SuperTabView>
final end = value.selection.baseOffset;
final prefix = value.text.substring(0, end);
final match = RegExp(r'(?:^|\s)@([^@\n]*)$').firstMatch(prefix);
- if (match == null || prefix == _dismissedMention) return null;
+ if (match == null || prefix == _dismissedMention.value) return null;
final start = prefix.lastIndexOf('@');
final query = match.group(1)!;
if (c.mentions(c.selectedId).values.contains('@${query.trimRight()}')) {
@@ -762,7 +764,7 @@ class _SuperTabViewState extends State<SuperTabView>
text: text,
selection: TextSelection.collapsed(offset: at.start + token.length + 1),
);
- setState(() => _mentionIndex = 0);
+ _mentionIndex.value = 0;
_focus.requestFocus();
}
@@ -1874,12 +1876,32 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
+ // What every row reads from the Swarm, built once per snapshot read rather
+ // than over every group and person for each row.
+ SuperTabSnapshot? _indexed;
+ Map<int, String> _references = const {};
+ Map<String, SuperTabPerson> _people = const {};
+ void _index() {
+ final snapshot = c.snapshot;
+ if (identical(snapshot, _indexed)) return;
+ _indexed = snapshot;
+ _references = {
+ for (final g in snapshot?.conversations ?? <SuperTabConversation>[])
+ if (g.number != null) g.number!: g.id,
+ };
+ _people = {};
+ for (final person in snapshot?.people ?? <SuperTabPerson>[]) {
+ _people.putIfAbsent(person.id, () => person);
+ }
+ }
+
Widget _message(
SuperTabMessage message,
bool grouped,
Map<String, SuperTabMessage> byId, {
bool showReceipt = false,
}) {
+ _index();
if (message.terminalEvent || message.source['kind'] == 'overlap') {
return SuperTabTerminalRow(
key: ValueKey('super-message-${message.id}'),
@@ -1921,25 +1943,16 @@ class _SuperTabViewState extends State<SuperTabView>
// A person is named by their address's first part, as people say it.
mentions: [
for (final id in message.mentions)
- if (c.snapshot?.people.where((p) => p.id == id).firstOrNull
- case final person?)
- person.email.split('@').first,
+ if (_people[id] case final person?) person.email.split('@').first,
],
- references: {
- for (final g in c.snapshot?.conversations ?? <SuperTabConversation>[])
- if (g.number != null) g.number!: g.id,
- },
+ references: _references,
onOpenGroup: (id) {
setState(() => _showPullRequests = false);
c.select(id);
c.selectTerminal(id, null);
},
agent: agent,
- person: message.fromAgent
- ? null
- : c.snapshot?.people
- .where((p) => p.id == message.authorId)
- .firstOrNull,
+ person: message.fromAgent ? null : _people[message.authorId],
onOpenAgent: agent == null ? null : () => _openAgent(agent),
machineName: agent == null ? null : widget.machineName(agent.machineId),
grouped: grouped,
@@ -1957,11 +1970,10 @@ class _SuperTabViewState extends State<SuperTabView>
readerId: c.accountId,
reactorName: (kind, id) => kind == 'agent'
? c.snapshot?.agentName(id) ?? 'Agent'
- : c.snapshot?.people
- .where((p) => p.id == id)
- .map((p) => superTabPersonName(p.email))
- .firstOrNull ??
- 'Someone',
+ : switch (_people[id]) {
+ final person? => superTabPersonName(person.email),
+ null => 'Someone',
+ },
onReact: c.canWrite && c.selected?.archived == false
? (emoji) => unawaited(_react(message, emoji))
: null,
@@ -2250,11 +2262,16 @@ class _SuperTabViewState extends State<SuperTabView>
);
final finding = _finding?.conversationId == c.selectedId ? _finding : null;
final back = finding == null && _back?.conversationId == c.selectedId;
- final choices = _completionChoices;
final chatId = c.selectedId;
- final pastedFolders = group != null && _agentsElsewhere(group)
+ // Read as the message changes, by the composer's own builders.
+ List<String> pastedFolders() => group != null && _agentsElsewhere(group)
? _foldersInMessage(chatId)
: const <String>[];
+ final completing = Listenable.merge([
+ _composer,
+ _mentionIndex,
+ _dismissedMention,
+ ]);
// No conversation read yet: its error is the page itself, not a line over "Loading".
final unread = _readsFirst && c.snapshot == null;
return Column(
@@ -2577,59 +2594,66 @@ class _SuperTabViewState extends State<SuperTabView>
onTap: () => _openAgent(agent),
),
),
- if (choices.isNotEmpty)
- Padding(
- padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
- child: Material(
- color: DesktopChrome.surface,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(
- DesktopChrome.controlRadius,
- ),
- side: BorderSide(color: DesktopChrome.rim),
- ),
- clipBehavior: Clip.antiAlias,
- child: ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: MediaQuery.sizeOf(context).height * .3,
+ ListenableBuilder(
+ listenable: completing,
+ builder: (context, _) {
+ final choices = _completionChoices;
+ if (choices.isEmpty) return const SizedBox.shrink();
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
+ child: Material(
+ color: DesktopChrome.surface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ side: BorderSide(color: DesktopChrome.rim),
),
- child: ListView(
- key: const ValueKey('super-composer-completions'),
- shrinkWrap: true,
- padding: const EdgeInsets.symmetric(vertical: 4),
- children: [
- for (var i = 0; i < choices.length; i++)
- ListTile(
- key: _completionKeys[i],
- dense: true,
- selected:
- i == _mentionIndex.clamp(0, choices.length - 1),
- selectedTileColor: grid.AppSurface.selectedFill,
- selectedColor: DesktopChrome.foreground,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- title: Text(
- choices[i].label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(),
+ clipBehavior: Clip.antiAlias,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * .3,
+ ),
+ child: ListView(
+ key: const ValueKey('super-composer-completions'),
+ shrinkWrap: true,
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ children: [
+ for (var i = 0; i < choices.length; i++)
+ ListTile(
+ key: _completionKeys[i],
+ dense: true,
+ selected:
+ i ==
+ _mentionIndex.value.clamp(0, choices.length - 1),
+ selectedTileColor: grid.AppSurface.selectedFill,
+ selectedColor: DesktopChrome.foreground,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ ),
+ title: Text(
+ choices[i].label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ subtitle: choices[i].detail == null
+ ? null
+ : Text(
+ choices[i].detail!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ onTap: choices[i].choose,
),
- subtitle: choices[i].detail == null
- ? null
- : Text(
- choices[i].detail!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.metadata(),
- ),
- onTap: choices[i].choose,
- ),
- ],
+ ],
+ ),
),
),
- ),
- ),
+ );
+ },
+ ),
if (group != null && group.archived)
Padding(
padding: const EdgeInsets.fromLTRB(24, 12, 24, 16),
@@ -2653,36 +2677,43 @@ class _SuperTabViewState extends State<SuperTabView>
),
)
else
- Padding(
+ ListenableBuilder(
// Keyed: the lines that come and go above it (a reply, mention
- // choices, an error) are Paddings too, and would otherwise take
- // over this element and remount the field. A remounted field
- // keeps focus but loses its text input connection, so typing,
- // Backspace included, would go nowhere.
+ // choices, an error) would otherwise take over this element and
+ // remount the field. A remounted field keeps focus but loses its
+ // text input connection, so typing, Backspace included, would go
+ // nowhere.
key: const ValueKey('super-message-composer-row'),
- padding: EdgeInsets.fromLTRB(
- 24,
- 12,
- 24,
- pastedFolders.isEmpty ? 16 : 6,
+ listenable: _composer,
+ builder: (context, field) => Padding(
+ padding: EdgeInsets.fromLTRB(
+ 24,
+ 12,
+ 24,
+ pastedFolders().isEmpty ? 16 : 6,
+ ),
+ child: field,
),
child: Focus(
onKeyEvent: (node, event) {
final keys = HardwareKeyboard.instance;
final composing = _composer.value.composing;
- if (_focus.hasFocus &&
- event is KeyDownEvent &&
- choices.isNotEmpty &&
- !keys.isControlPressed &&
- !keys.isMetaPressed &&
- !keys.isAltPressed &&
- !keys.isShiftPressed &&
- !(composing.isValid && !composing.isCollapsed)) {
+ final choices =
+ _focus.hasFocus &&
+ event is KeyDownEvent &&
+ !keys.isControlPressed &&
+ !keys.isMetaPressed &&
+ !keys.isAltPressed &&
+ !keys.isShiftPressed &&
+ !(composing.isValid && !composing.isCollapsed)
+ ? _completionChoices
+ : const <_ComposerChoice>[];
+ if (choices.isNotEmpty) {
final key = event.logicalKey;
if (key == LogicalKeyboardKey.arrowDown ||
key == LogicalKeyboardKey.arrowUp) {
_moveCompletion(
- (_mentionIndex +
+ (_mentionIndex.value +
(key == LogicalKeyboardKey.arrowDown ? 1 : -1)) %
choices.length,
);
@@ -2690,16 +2721,14 @@ class _SuperTabViewState extends State<SuperTabView>
}
if (key == LogicalKeyboardKey.tab ||
key == LogicalKeyboardKey.enter) {
- choices[_mentionIndex.clamp(0, choices.length - 1)]
+ choices[_mentionIndex.value.clamp(0, choices.length - 1)]
.choose();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.escape) {
- setState(
- () => _dismissedMention = _composer.text.substring(
- 0,
- _composer.selection.baseOffset,
- ),
+ _dismissedMention.value = _composer.text.substring(
+ 0,
+ _composer.selection.baseOffset,
);
return KeyEventResult.handled;
}
@@ -2819,10 +2848,8 @@ class _SuperTabViewState extends State<SuperTabView>
),
onChanged: (text) {
c.setDraft(c.selectedId, text);
- setState(() {
- _mentionIndex = 0;
- _dismissedMention = null;
- });
+ _mentionIndex.value = 0;
+ _dismissedMention.value = null;
},
),
),
@@ -2869,34 +2896,42 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
),
- if (pastedFolders.isNotEmpty && !(group?.archived ?? true))
- Padding(
- key: const ValueKey('super-folder-path-hint'),
- padding: const EdgeInsets.fromLTRB(28, 0, 24, 10),
- child: Row(
- children: [
- Expanded(
- child: Text(
- pastedFolders.length == 1
- ? "This path is on this computer. Agents on other "
- "computers can't open it."
- : "These paths are on this computer. Agents on "
- "other computers can't open them.",
- style: DesktopChrome.metadata(),
- ),
- ),
- TextButton(
- onPressed: _zipping.contains(chatId) || !writable || busy
- ? null
- : () => unawaited(
- _attachFoldersAsZip(chatId, pastedFolders),
- ),
- child: Text(
- _zipping.contains(chatId) ? 'Zipping…' : 'Attach as zip',
- ),
+ if (!(group?.archived ?? true))
+ ListenableBuilder(
+ listenable: _composer,
+ builder: (context, _) {
+ final pasted = pastedFolders();
+ if (pasted.isEmpty) return const SizedBox.shrink();
+ return Padding(
+ key: const ValueKey('super-folder-path-hint'),
+ padding: const EdgeInsets.fromLTRB(28, 0, 24, 10),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ pasted.length == 1
+ ? "This path is on this computer. Agents on other "
+ "computers can't open it."
+ : "These paths are on this computer. Agents on "
+ "other computers can't open them.",
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ TextButton(
+ onPressed: _zipping.contains(chatId) || !writable || busy
+ ? null
+ : () =>
+ unawaited(_attachFoldersAsZip(chatId, pasted)),
+ child: Text(
+ _zipping.contains(chatId)
+ ? 'Zipping…'
+ : 'Attach as zip',
+ ),
+ ),
+ ],
),
- ],
- ),
+ );
+ },
),
],
);
diff --git a/desktop/lib/viewer/group_sync.dart b/desktop/lib/viewer/group_sync.dart
index fb33b4127..dbb98cd35 100644
--- a/desktop/lib/viewer/group_sync.dart
+++ b/desktop/lib/viewer/group_sync.dart
@@ -240,8 +240,10 @@ Future<GroupSyncOutcome> syncTrustGroup({
identity: identity,
peerPub: pin.pub,
);
- final uri = Uri.parse('$wsBaseUrl/api/web-ws')
- .replace(queryParameters: {'autonomousEnv': autonomousEnv});
+ // It says what it is (`?client=`; backend lib/wsAttribution.ts, WebSocket roadmap Phase 0).
+ final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(
+ queryParameters: {'autonomousEnv': autonomousEnv, 'client': 'group-sync'},
+ );
final ch = channel = socket(uri, [accessToken]);
final reply = await () async {
await ch.ready;
diff --git a/desktop/lib/viewer/password_link.dart b/desktop/lib/viewer/password_link.dart
index df5edc77a..58fda61a0 100644
--- a/desktop/lib/viewer/password_link.dart
+++ b/desktop/lib/viewer/password_link.dart
@@ -70,8 +70,9 @@ Future<PasswordLinkResult> linkWithPassword({
Duration timeout = const Duration(seconds: 30),
}) async {
onProgress?.call(PasswordLinkStage.connecting);
+ // It says what it is (`?client=`; backend lib/wsAttribution.ts, WebSocket roadmap Phase 0).
final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(
- queryParameters: {'autonomousEnv': autonomousEnv},
+ queryParameters: {'autonomousEnv': autonomousEnv, 'client': 'link'},
);
final channel = socket(uri, [accessToken]);
final run = _PasswordLinkRun(machineId, password, identity, channel, onProgress);
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index 134a2e467..855646157 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -7,6 +7,7 @@ import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
+import '../core/app_version.dart';
import '../core/sleep_aware.dart';
import '../core/test_run.dart';
import '../logging/app_log.dart';
@@ -48,6 +49,30 @@ Duration reconnectDelay(int attempt, Random random) {
/// every second, for good: about 54 dials a minute from one browser tab (prod, 2026-10-28).
const connectionStableAfter = Duration(minutes: 1);
+/// This build's version, which every backend socket it dials says (`?v=`), read once at start-up
+/// ([rememberAppVersionForSockets]). Null until then, and a socket dialled before says no version.
+String? declaredAppVersion;
+
+/// The read behind [declaredAppVersion] while it is out; null natively before start-up and in tests.
+Future<void>? appVersionRead;
+
+/// Reads this build's version for [declaredAppVersion]; a build that cannot say leaves it null.
+Future<void> rememberAppVersionForSockets() {
+ final read = () async {
+ try {
+ declaredAppVersion = await runningAppVersion();
+ } catch (_) {
+ // Sockets go on saying what they are, without a version.
+ }
+ }();
+ appVersionRead = read;
+ return read;
+}
+
+/// How long a backend dial waits for [appVersionRead]: the browser reads its version from the
+/// host's release file, and a socket dialled before that read lands would carry none.
+const _appVersionWait = Duration(seconds: 1);
+
/// The backend's refusals of a `machine_select` that no redial can change: the machine left the
/// account or was never shared with it, it belongs to another environment, or its subscription stops
/// it (`backend/src/lib/webWs.ts`). Through this computer's daemon they arrive as the relay's close,
@@ -453,6 +478,17 @@ class WsConn {
}
uri = local;
} else {
+ final versionRead = appVersionRead;
+ if (versionRead != null && declaredAppVersion == null) {
+ await versionRead.timeout(
+ _appVersionWait,
+ // Waited out once: a read that never ends must not hold every later dial too.
+ onTimeout: () {
+ if (identical(appVersionRead, versionRead)) appVersionRead = null;
+ },
+ );
+ if (_closing) return;
+ }
final base = Uri.parse(
'$wsBaseUrl/api/${_directObserver ? 'observer-ws' : 'web-ws'}',
);
@@ -463,8 +499,10 @@ class WsConn {
if (_directObserver)
(observerLink ? 'link' : 'share'): observerShareId!,
// The browser counts its person as on the web today (backend
- // user_daily_client_presence). Not other viewer builds: they are not the web.
- if (!_directObserver && kIsWeb) 'client': 'web',
+ // user_daily_client_presence). Other viewer builds say they are the desktop app,
+ // which counts no presence. Both say which build (WebSocket roadmap Phase 0).
+ 'client': kIsWeb ? 'web' : 'desktop',
+ 'v': ?declaredAppVersion,
},
);
}
diff --git a/desktop/test/super_tab_composer_rebuild_test.dart b/desktop/test/super_tab_composer_rebuild_test.dart
new file mode 100644
index 000000000..eb9296082
--- /dev/null
+++ b/desktop/test/super_tab_composer_rebuild_test.dart
@@ -0,0 +1,103 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/message_row.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Typing in a long chat must not rebuild its transcript: on a chat holding
+/// hundreds of messages each keystroke redid the work of every held message.
+void main() {
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ final transcript = find.byType(CustomScrollView);
+
+ ConversationServer longChat() {
+ final server = ConversationServer()..messagePage = 300;
+ for (var i = 0; i < 300; i++) {
+ server.append('Update $i');
+ }
+ return server;
+ }
+
+ testWidgets('typing in a 300-message chat leaves the transcript as built', (
+ tester,
+ ) async {
+ final c = await show(tester, longChat());
+ expect(c.messages(c.selectedId), hasLength(300));
+ await tester.showKeyboard(composer);
+ await tester.pump();
+ final before = tester.widget(transcript);
+ var text = '';
+ for (final char in 'abcdefghij'.split('')) {
+ text += char;
+ tester.testTextInput.updateEditingValue(
+ TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: text.length),
+ ),
+ );
+ await tester.pump();
+ // A rebuilt transcript is a new widget: the same one was not built again.
+ expect(identical(tester.widget(transcript), before), isTrue);
+ }
+ expect(c.draft(c.selectedId), 'abcdefghij');
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ testWidgets('rows share one map of group references, read again on change', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ (server.state['conversations'] as List)[1]['number'] = 12;
+ server.append('See #12');
+ server.append('And #12 again');
+ final c = await show(tester, server);
+ List<Map<int, String>> references() => [
+ for (final row in tester.widgetList<SuperTabMessageRow>(
+ find.byType(SuperTabMessageRow),
+ ))
+ row.references,
+ ];
+ final first = references();
+ expect(first, hasLength(2));
+ expect(first.first, {12: 'offline'});
+ // Built once for the Swarm as read, not once per row.
+ expect(identical(first.first, first.last), isTrue);
+
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('sync', 'Sync reliability'),
+ 'number': 13,
+ });
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(c.snapshot!.conversation('sync'), isNotNull);
+ expect(references().first, {12: 'offline', 13: 'sync'});
+ });
+}
diff --git a/desktop/test/viewer/group_sync_test.dart b/desktop/test/viewer/group_sync_test.dart
index 30d1394ea..a25bf87e0 100644
--- a/desktop/test/viewer/group_sync_test.dart
+++ b/desktop/test/viewer/group_sync_test.dart
@@ -42,7 +42,12 @@ class _Socket implements WebSocketChannel {
@override
WebSocketSink get sink => _sink;
void emit(Map<String, dynamic> frame) => _down.add(jsonEncode(frame));
- WebSocketChannel factory(Uri _, Iterable<String> _) => this;
+ /// The address the swap dialled.
+ Uri? dialled;
+ WebSocketChannel factory(Uri uri, Iterable<String> _) {
+ dialled = uri;
+ return this;
+ }
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
@@ -170,6 +175,11 @@ void main() {
);
expect(seen!['self'], containsPair('kind', 'viewer'));
expect(outcome.pinned, [_c]);
+ // It says what it is (WebSocket roadmap Phase 0).
+ expect(
+ socket.dialled.toString(),
+ 'wss://relay.test/api/web-ws?autonomousEnv=prod&client=group-sync',
+ );
expect(b64e((await keys.peer(_c))!.pub), cPub);
},
);
diff --git a/desktop/test/ws_conn_test.dart b/desktop/test/ws_conn_test.dart
index cb06e421d..86efc7a22 100644
--- a/desktop/test/ws_conn_test.dart
+++ b/desktop/test/ws_conn_test.dart
@@ -27,6 +27,7 @@ class FakeHub {
final List<String> protocols = [];
final List<String?> environments = [];
final List<String?> declaredClients = [];
+ final List<String?> declaredVersions = [];
final Map<String, int> machineSelected = {};
final List<WebSocket> clients = [];
Map<String, dynamic> closeResponse = {'activity': 'idle'};
@@ -50,6 +51,7 @@ class FakeHub {
hub.protocols.add(protocol);
hub.environments.add(request.uri.queryParameters['autonomousEnv']);
hub.declaredClients.add(request.uri.queryParameters['client']);
+ hub.declaredVersions.add(request.uri.queryParameters['v']);
final ws = await WebSocketTransformer.upgrade(
request,
protocolSelector: (protocols) =>
@@ -294,12 +296,16 @@ void main() {
onEvent: (_) {},
onStatus: (_) {},
);
+ declaredAppVersion = '1.3.0';
+ addTearDown(() => declaredAppVersion = null);
await conn!.connect();
final result = await conn!.request('agents_list');
expect(hub.protocols, ['access-token']);
expect(hub.environments, ['prod']);
- // A native build is not the web: no presence surface declared.
- expect(hub.declaredClients, [null]);
+ // A native build is not the web (no presence surface), but says what it is and which build (WebSocket
+ // roadmap Phase 0).
+ expect(hub.declaredClients, ['desktop']);
+ expect(hub.declaredVersions, ['1.3.0']);
expect(hub.machineSelected['m1'], 1);
expect((result['agents'] as List).first['id'], 'a1');
},
@@ -527,6 +533,77 @@ void main() {
expect(conn!.isClosed, isTrue);
});
+ // The browser reads its version from the host's release file at start-up; a socket dialled while that read is out
+ // waits for it a moment, so the web build's first sockets carry it too (the e2e harness counts them per kind).
+ test('a socket waits up to a second for the version read, then dials with it', () async {
+ hub = await FakeHub.start();
+ final read = Completer<void>();
+ appVersionRead = read.future;
+ addTearDown(() {
+ appVersionRead = null;
+ declaredAppVersion = null;
+ });
+ conn = WsConn(
+ wsBaseUrl: 'ws://127.0.0.1:${hub.port}',
+ autonomousEnv: 'prod',
+ machineId: 'm1',
+ accessTokenProvider: (_, _) async => 'access-token',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ unawaited(conn!.connect());
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ declaredAppVersion = '1.3.58';
+ read.complete();
+ await conn!.request('agents_list');
+ expect(hub.declaredVersions, ['1.3.58']);
+ });
+
+ test('a version read that never ends holds a dial for a second at most', () async {
+ hub = await FakeHub.start();
+ appVersionRead = Completer<void>().future;
+ addTearDown(() => appVersionRead = null);
+ conn = WsConn(
+ wsBaseUrl: 'ws://127.0.0.1:${hub.port}',
+ autonomousEnv: 'prod',
+ machineId: 'm1',
+ accessTokenProvider: (_, _) async => 'access-token',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final started = DateTime.now();
+ await conn!.connect();
+ await conn!.request('agents_list');
+ expect(DateTime.now().difference(started), lessThan(const Duration(seconds: 2)));
+ expect(hub.declaredVersions, [null]);
+ });
+
+ // Review of #2044: a read that never ends costs the first dial its second, not every dial after it.
+ test('after a version read times out once, later dials do not wait', () async {
+ hub = await FakeHub.start();
+ appVersionRead = Completer<void>().future;
+ addTearDown(() => appVersionRead = null);
+ WsConn dialer() => WsConn(
+ wsBaseUrl: 'ws://127.0.0.1:${hub.port}',
+ autonomousEnv: 'prod',
+ machineId: 'm1',
+ accessTokenProvider: (_, _) async => 'access-token',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final first = dialer();
+ addTearDown(first.close);
+ await first.connect();
+ conn = dialer();
+ final started = DateTime.now();
+ await conn!.connect();
+ await conn!.request('agents_list');
+ expect(DateTime.now().difference(started), lessThan(const Duration(milliseconds: 500)));
+ });
+
// Prod, 2026-10-28: a laptop removed from the account in September was still selected every few
// seconds. Through this computer's daemon the refusal arrives as the relay's close, with the
// backend's code for its reason; straight from the backend (the web viewer), as the frame.
diff --git a/mobile/lib/viewer/code_link.dart b/mobile/lib/viewer/code_link.dart
index 1042b9a12..141ebf29c 100644
--- a/mobile/lib/viewer/code_link.dart
+++ b/mobile/lib/viewer/code_link.dart
@@ -37,8 +37,10 @@ Future<PasswordLinkResult> linkWithCode({
RelaySocketFactory socket = defaultRelaySocket,
Duration timeout = const Duration(seconds: 50),
}) async {
- final uri = Uri.parse('$wsBaseUrl/api/web-ws')
- .replace(queryParameters: {'autonomousEnv': autonomousEnv});
+ // It says what it is (`?client=`; backend lib/wsAttribution.ts, WebSocket roadmap Phase 0).
+ final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(
+ queryParameters: {'autonomousEnv': autonomousEnv, 'client': 'link'},
+ );
final channel = socket(uri, [accessToken]);
final run = CodeLinkRun(
machineId: machineId,
diff --git a/mobile/lib/viewer/group_sync.dart b/mobile/lib/viewer/group_sync.dart
index fb33b4127..dbb98cd35 100644
--- a/mobile/lib/viewer/group_sync.dart
+++ b/mobile/lib/viewer/group_sync.dart
@@ -240,8 +240,10 @@ Future<GroupSyncOutcome> syncTrustGroup({
identity: identity,
peerPub: pin.pub,
);
- final uri = Uri.parse('$wsBaseUrl/api/web-ws')
- .replace(queryParameters: {'autonomousEnv': autonomousEnv});
+ // It says what it is (`?client=`; backend lib/wsAttribution.ts, WebSocket roadmap Phase 0).
+ final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(
+ queryParameters: {'autonomousEnv': autonomousEnv, 'client': 'group-sync'},
+ );
final ch = channel = socket(uri, [accessToken]);
final reply = await () async {
await ch.ready;
diff --git a/mobile/lib/viewer/password_link.dart b/mobile/lib/viewer/password_link.dart
index 7e0730356..47132a16f 100644
--- a/mobile/lib/viewer/password_link.dart
+++ b/mobile/lib/viewer/password_link.dart
@@ -73,8 +73,10 @@ Future<PasswordLinkResult> linkWithPassword({
Duration timeout = const Duration(seconds: 30),
}) async {
onProgress?.call(PasswordLinkStage.connecting);
- final uri = Uri.parse('$wsBaseUrl/api/web-ws')
- .replace(queryParameters: {'autonomousEnv': autonomousEnv});
+ // It says what it is (`?client=`; backend lib/wsAttribution.ts, WebSocket roadmap Phase 0).
+ final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(
+ queryParameters: {'autonomousEnv': autonomousEnv, 'client': 'link'},
+ );
final channel = socket(uri, [accessToken]);
final run = _PasswordLinkRun(
machineId,
diff --git a/mobile/test/code_link_test.dart b/mobile/test/code_link_test.dart
index 9c94d57b0..f72e20ac5 100644
--- a/mobile/test/code_link_test.dart
+++ b/mobile/test/code_link_test.dart
@@ -244,7 +244,8 @@ void main() {
expect(machine.pinned, phone.pub);
expect(
socket.dialled.toString(),
- 'wss://relay.invalid/api/web-ws?autonomousEnv=prod',
+ // It says what it is (WebSocket roadmap Phase 0).
+ 'wss://relay.invalid/api/web-ws?autonomousEnv=prod&client=link',
);
expect(socket.protocols, ['tok']);
expect(socket.closedByPhone, isTrue);
diff --git a/mobile/test/viewer/password_link_test.dart b/mobile/test/viewer/password_link_test.dart
index 94a15cb80..dd970b7d1 100644
--- a/mobile/test/viewer/password_link_test.dart
+++ b/mobile/test/viewer/password_link_test.dart
@@ -83,7 +83,8 @@ void main() {
]);
expect(
socket.dialled.toString(),
- 'wss://relay.invalid/api/web-ws?autonomousEnv=stag',
+ // It says what it is (WebSocket roadmap Phase 0).
+ 'wss://relay.invalid/api/web-ws?autonomousEnv=stag&client=link',
);
expect(socket.protocols, ['tok']);
expect(socket.closedByPhone, isTrue);