The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-03 ce: #2740 #2299 #2300 #2602 #2757 #2268 #2758 #2770 #2753 #2767 #2622 (#2785)
0xken1564c71a056f39
diff --git a/backend/integration/harnessSharesIndexPlan.test.ts b/backend/integration/harnessSharesIndexPlan.test.tsnew file mode 100644index 000000000..54ce425a7--- /dev/null+++ b/backend/integration/harnessSharesIndexPlan.test.ts@@ -0,0 +1,60 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { planDatabase, plan, profiled, reads } from './plans.test-support.js'++// Prod 2026-11-02 (Atlas Performance Advisor): the share list filters one recipient's shares in one environment and sorts them by+// createdAt, which the (recipientEmail, autonomousEnv, expiresAt) index cannot give, so Mongo sorted every unexpired share in memory.+// A fresh loopback replica set; the route's own Prisma client is pointed at it. Never DATABASE_URL.+const shared = vi.hoisted(() => ({ db: null as unknown as PrismaClient }))+vi.mock('../src/lib/prisma.js', async original => ({ ...await original<typeof import('../src/lib/prisma.js')>(), get prisma() { return shared.db } }))+vi.mock('../src/lib/bus.js', async original => ({ ...await original<typeof import('../src/lib/bus.js')>(),+ getAgentPresenceMany: async (ids: string[]) => new Map(ids.map(id => [id, 'running'])) }))+const { harnessShareRoutes } = await import('../src/routes/harnessShares.js')++const DAY = 86_400_000+let replica: MongoMemoryReplSet+let db: PrismaClient+let app: FastifyInstance+const recipient = { sub: 'a'.repeat(24), email: '[email protected]', autonomousEnv: 'prod' } as unknown as AuthUser++beforeAll(async () => {+ ({ replica, db } = await planDatabase('share_index_plan'))+ shared.db = db+ const share = (recipientEmail: string, i: number, extra: Record<string, unknown> = {}) => ({ id: randomUUID(), ownerId: 'b'.repeat(24), machineId: `m-${i}`,+ agentId: `agent-${i}`, recipientEmail, autonomousEnv: 'prod', name: `agent ${i}`, ownerPublicKey: 'fixture-key', revokedAt: null, expiresAt: new Date(Date.now() + DAY),+ createdAt: new Date(Date.now() - (100 - i) * 1000), ...extra })+ await db.harnessShare.createMany({ data: [+ // Many other recipients' shares, which a read not bounded by recipient examines too.+ ...Array.from({ length: 60 }, (_, i) => share(`other-${i}@example.com`, i)),+ ...Array.from({ length: 5 }, (_, i) => share('[email protected]', 100 + i)),+ share('[email protected]', 110, { autonomousEnv: 'dev' }),+ // Revoked but not yet expired, as production holds them by the thousand: each sits inside the expiresAt range.+ ...Array.from({ length: 30 }, (_, i) => share('[email protected]', 200 + i, { revokedAt: new Date() })),+ share('[email protected]', 112, { expiresAt: new Date(Date.now() - 1000) }),+ ] })+ app = Fastify()+ app.decorateRequest('user', null)+ app.addHook('onRequest', async req => { req.user = recipient })+ await app.register(harnessShareRoutes)+ await app.ready()+}, 300_000)+afterAll(async () => {+ await app?.close()+ await db?.$disconnect()+ await replica?.stop()+})++describe('the harness shares list', () => {+ it('reads one recipient\'s shares in creation order from the index that holds that order', async () => {+ const entries = await profiled(db, async () => { expect((await app.inject({ method: 'GET', url: '/api/harness-shares' })).statusCode).toBe(200) })+ const rows = reads(entries, 'harness_shares', ['recipientEmail', 'autonomousEnv', 'revokedAt', 'expiresAt'])+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ recipientEmail: 1, autonomousEnv: 1, revokedAt: 1, createdAt: 1, expiresAt: 1 \}/)+ // Only the recipient's shares in this environment (just the 5 listed): not the 30 revoked, the expired one or the 60 others.+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(5)+ })+})diff --git a/backend/integration/harnessSharesList.test.ts b/backend/integration/harnessSharesList.test.tsindex dbf7422b6..8119c3be3 100644--- a/backend/integration/harnessSharesList.test.ts+++ b/backend/integration/harnessSharesList.test.ts@@ -172,7 +172,11 @@ describe('the harness shares list on a Swarm-sized database', () => {for (const read of reads) {expect(read.plans.filter(p => p.startsWith('COLLSCAN')), read.collection).toEqual([])// Prisma's `in` is planned as one index scan per value (an OR of N branches), each read planned anew: one $in scan instead.- expect(read.plans.filter(p => p.includes('}, IXSCAN')), read.collection).toEqual([])+ // The share list's `revokedAt: null` is an `$expr` equality that Mongo plans as the same index twice (the null bounds): the one+ // exception, at most two scans of one index. Anywhere else a repeated scan is a branch per value, as Prisma's `in` makes.+ const branches = (p: string) => p.split(/(?<=\}), (?=IXSCAN)/)+ const nullBounds = (p: string) => read.collection === 'harness_shares' && branches(p).length === 2 && new Set(branches(p)).size === 1+ expect(read.plans.filter(p => p.includes('}, IXSCAN') && !nullBounds(p)), read.collection).toEqual([])expect(read.docsExamined, read.collection).toBeLessThanOrEqual(read.returned + 2)// Keys too: an agent read by key that walks the (tabId, key) index costs every other Swarm in production.expect(read.keysExamined, read.collection).toBeLessThanOrEqual(read.returned + 10)diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex bc4931f21..65969ca54 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -5,13 +5,14 @@ import { join } from 'node:path'import { tmpdir } from 'node:os'import { Readable } from 'node:stream'import { crc32, deflateSync, inflateSync } from 'node:zlib'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import { storeOldLeads } from './oldLeads.test-support.js'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'+import { sweepUnsentAttachments } from '../src/lib/attachmentSweep.js'import type { Command } from '../src/superTabs/commands.js'import { poolRows, rosterRows } from './hostRows.test-support.js'import { SwarmReads } from '../src/superTabs/read/service.js'@@ -448,6 +449,29 @@ describe('a Buddy through the store', () => {await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: '', replyTo: null, recipientIds: [], attachmentIds: [loose] }, peer, agentId)).rejects.toThrow('Attach this file again')})+ it('never carries a file the expiry sweep took, its owner\'s or its own (Diego, 10-30)', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ const bucket = { store: f.files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' }+ const upload = async (name: string, asBuddy: boolean) =>+ (await f.store.upload(peer, f.tab, chat, { name, mime: 'text/plain', body: Readable.from([Buffer.from(name)]) }, asBuddy ? agentId : undefined)).attachment.id+ // One its owner uploaded in their chat and never sent, one of its own; the sweep took both a day later, and their files+ // are not gone yet (the bucket failed), so the rows are still there.+ const [owners, own] = [await upload('draft.txt', false), await upload('notes.txt', true)]+ await db.superTabAttachment.updateMany({ where: { id: { in: [owners, own] } }, data: { createdAt: new Date(Date.now() - 25 * 3_600_000) } })+ const remove = vi.spyOn(f.files, 'delete').mockRejectedValue(new Error('bucket unavailable'))+ try {+ await sweepUnsentAttachments(db, bucket, new Date(), { chunk: 10, chunks: 1, pauseMs: 0 })+ } finally {+ remove.mockRestore()+ }+ const ask = String((await f.execute({ type: 'message.send', conversationId: chat, text: 'Send it to the PM', replyTo: null, recipientIds: [] }, peer)).result.messageId)+ const propose = (attachmentIds: string[]) => f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, goal: 'Offline sync',+ scope: 'Desktop only', priority: 'normal', attachmentIds }, peer, agentId)+ await expect(propose([owners])).rejects.toThrow('Upload this file again')+ await expect(propose([own])).rejects.toThrow('Upload this file again')+ expect((await db.superTabAttachment.findMany({ where: { id: { in: [owners, own] } } })).map(r => r.proposedBy ?? null)).toEqual([null, null])+ })it('never hears of a machine removed from the Swarm in its change feed, though the PM does (security review 2 of #2115)', async () => {const f = await swarm()const { agentId } = await buddy(f)diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.tsindex 767b9429e..270f7158b 100644--- a/backend/integration/superTabSwarmBuddy.test.ts+++ b/backend/integration/superTabSwarmBuddy.test.ts@@ -602,6 +602,34 @@ describe('security reviews of #2435', () => {expect((await f.store.read(owner, f.tab)).state.agents.map(a => a.id)).not.toContain(narrow)})+ // Task #2356 (Diego): a New session there started wide, so it read its person's whole home, other projects' clones included.+ it('starts a New session in an older project chat narrow, as that chat\'s own Buddy is', async () => {+ const f = await swarm()+ await buddy(f)+ const old = String((await f.execute({ type: 'buddy.chat', projectId: f.web.projectId }, peer)).result.conversationId)+ await f.launch(String((await send(f, old, 'From the phone')).result.startId))+ const startId = String((await send(f, old, 'Work on this', { newSession: true })).result.startId)+ const state = (await f.store.read(peer, f.tab)).state+ expect(state.starts!.find(s => s.id === startId)!.request).toMatchObject({ worktree: true, buddyNarrow: true })+ const session = await f.launch(startId)+ expect((await f.store.read(peer, f.tab)).state.agents.find(a => a.id === session)).toMatchObject({ buddyNarrow: true, projectId: f.web.projectId })+ })++ it('ends a New session in an older project chat when its person loses the project', async () => {+ const f = await swarm()+ await buddy(f)+ const old = String((await f.execute({ type: 'buddy.chat', projectId: f.secret.projectId }, peer)).result.conversationId)+ await f.launch(String((await send(f, old, 'From the phone')).result.startId))+ const session = await f.launch(String((await send(f, old, 'Work on this', { newSession: true })).result.startId))+ const pending = String((await send(f, old, 'And this', { newSession: true })).result.startId)+ expect((await f.store.read(owner, f.tab)).state.agents.map(a => a.id)).toContain(session)+ await f.execute({ type: 'project.sharing', projectId: f.secret.projectId, visibility: 'private', memberIds: [owner.sub] })+ const state = (await f.store.read(owner, f.tab)).state+ expect(state.agents.map(a => a.id)).not.toContain(session)+ // Its host never launches the start still pending.+ await expect(f.launch(pending)).rejects.toBeDefined()+ })+it('shows a project session none of its chat\'s sessions: other threads, other projects\' and starts still pending', async () => {const f = await swarm()const { chat } = await buddy(f)diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 6d24399fe..ca3ee3904 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -1214,3 +1214,20 @@ describe('a message from an agent of another account (audit M3)', () => {expect(await store.delivery(owner, f.tab, f.lead, delivery.id, { type: 'claim', claimId: randomUUID() })).toMatchObject({ otherAccount: true })})})++// Task #2390 (Tony, 11-03): a machine's owner keeps it for some projects; every other project's work is refused there.+describe('a machine its owner keeps for some projects', () => {+ it('is kept for them across reads, set by its owner alone, and takes no start for another project', async () => {+ const f = await fixture()+ const limit = (projectIds: string[] | null, user: AuthUser) => run(f.tab, { type: 'machine.projects', machineId: 'team-mac', projectIds } as Command, user)+ await expect(limit([f.own], owner)).rejects.toMatchObject({ code: 'OWNER_REQUIRED' })+ // Its Harness Team account session cannot change what its owner chose.+ await expect(limit(['lead'], team)).rejects.toMatchObject({ code: 'TEAM_SESSION_LIMITED' })+ await limit([f.own], person)+ expect((await store.read(owner, f.tab)).state.machines!.find(m => m.machineId === 'team-mac')!.projects).toEqual([f.own])+ await expect(run(f.tab, { type: 'agent.start', request: { conversationId: f.teamGroup, machineId: 'team-mac', engine: 'codex',+ name: 'Second', cwd: '/team', worktree: false, requirements } })).rejects.toMatchObject({ code: 'MACHINE_PROJECTS', message: 'MacBook Pro · Team runs only Own.' })+ await limit(null, person)+ expect((await store.read(owner, f.tab)).state.machines!.find(m => m.machineId === 'team-mac')!.projects).toBeUndefined()+ })+})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 2e279ab79..7f1459857 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -12,7 +12,8 @@ import Fastify, { type FastifyInstance } from 'fastify'import type { AuthUser } from '../src/lib/ssoAuth.js'import { ABANDONED_START_MS, GrantReads, SuperTabStore } from '../src/superTabs/store.js'import { HostReads } from '../src/superTabs/read/host.js'-import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'+import { attachmentsFromEnv, MemoryAttachmentStore, MemoryAvatarStore, REMOVING_UPLOAD_PURPOSE } from '../src/superTabs/attachments.js'+import { startAttachmentSweepFrom, sweepUnsentAttachments } from '../src/lib/attachmentSweep.js'import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'import { logger } from '../src/utils/logger.js'@@ -2572,6 +2573,8 @@ describe('Super Tab chat attachments', () => {const signed = (path: string) => new RegExp(`^https://storage\\.memory\\.test/${path}\\?expires=\\d+&signature=[0-9a-f]{64}$`)/** A file as two reads hand it: the same object, each with a link of its own read. */const sameFile = (file: Uploaded) => ({ ...file, link: expect.stringMatching(signed(objectKey(file.url).replaceAll('.', '\\.'))), expiresAt: expect.any(Number) })+ /** A file as a message keeps it: a read signs a fresh link for it (fileLinks.ts), so the upload answer's link is not part of it. */+ const keptFile = ({ link: _link, expiresAt: _expiresAt, ...file }: Uploaded) => fileit('keeps a credential out of a file\'s name, which the chat shows like the message', async () => {const { tab } = await fixture()@@ -2995,6 +2998,210 @@ describe('Super Tab chat attachments', () => {expect(await file(tab, 'a.png', new Uint8Array(1), 'image/png', 'lead', peer)).toMatchObject({ status: 403, code: 'READ_ONLY' })expect(files.objects.size).toBe(before)})++ // Diego, 10-30: uploads nobody sends within a day are removed, row and stored file, so the bucket stops growing.+ describe('unsent files expire after a day', () => {+ const HOUR = 3_600_000+ const pictures = new MemoryAvatarStore('https://avatars.example.test')+ const bucket = { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test', avatars: pictures, avatarPrefix: 'super-tabs' }+ // Two a chunk, so a run takes several chunks.+ const sweep = (database: PrismaClient = db) => sweepUnsentAttachments(database, bucket, new Date(), { chunk: 2, chunks: 5, pauseMs: 0 })+ const aged = (id: string, hours: number) => db.superTabAttachment.update({ where: { id }, data: { createdAt: new Date(Date.now() - hours * HOUR) } })+ const row = (id: string) => db.superTabAttachment.findUnique({ where: { id } })+ const stored = (url: string) => files.objects.has(objectKey(url))+ const picture = async (tab: string) => {+ const bytes = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(24)])+ const { avatar } = await new SuperTabStore(db, Date.now, bucket).uploadAvatar(owner, tab, { body: Readable.from([bytes]) })+ return { id: avatar.id, key: (await row(avatar.id))!.objectKey }+ }+ const useAvatar = (tab: string, id: string) => new SuperTabStore(db, Date.now, bucket).execute(owner, tab,+ { operationId: randomUUID(), command: { type: 'member.avatar', avatar: { kind: 'upload', id } } })++ it('removes a file nobody sent within a day, row and object, and keeps a sent one and a young one', async () => {+ const { tab } = await fixture()+ const [old, older, sent, young] = [(await file(tab, 'old.txt')).attachment, (await file(tab, 'older.txt')).attachment,+ (await file(tab, 'sent.txt')).attachment, (await file(tab, 'young.txt')).attachment]+ const messageId = String((await send(tab, [sent.id])).result.messageId)+ const [unusedPicture, usedPicture] = [await picture(tab), await picture(tab)]+ await useAvatar(tab, usedPicture.id)+ for (const [id, hours] of [[old.id, 25], [older.id, 48], [sent.id, 25], [young.id, 1], [unusedPicture.id, 25], [usedPicture.id, 25]] as const) await aged(id, hours)++ await sweep()+ expect([await row(old.id), await row(older.id), stored(old.url), stored(older.url)]).toEqual([null, null, false, false])+ expect(await row(sent.id)).toMatchObject({ usedBy: messageId })+ expect(await row(young.id)).toMatchObject({ usedBy: null })+ expect([stored(sent.url), stored(young.url)]).toEqual([true, true])+ // The sent message still links its file.+ expect((await store.messages(owner, tab, 'lead', {})).messages.find(m => m.id === messageId)?.attachments).toEqual([keptFile(sent)])+ // Pictures alike: one never used is removed from the avatar store, the one in use stays.+ expect([await row(unusedPicture.id), pictures.objects.has(unusedPicture.key)]).toEqual([null, false])+ expect([(await row(usedPicture.id))?.id, pictures.objects.has(usedPicture.key)]).toEqual([usedPicture.id, true])+ // A young file is still sent as usual.+ expect((await send(tab, [young.id])).result.messageId).toBeTruthy()+ })++ it('leaves an upload still on its link, or being removed by its own sweep, to the pending-upload sweep, however old', async () => {+ const { tab } = await fixture()+ const [pending, removing] = [(await linkFor(tab, { size: 5 })).upload, (await linkFor(tab, { size: 5 })).upload]+ for (const link of [pending, removing]) expect(await files.receive(link.url, link.headers, Buffer.alloc(5))).toBe(200)+ await db.superTabAttachment.update({ where: { id: removing.id }, data: { purpose: REMOVING_UPLOAD_PURPOSE } })+ for (const id of [pending.id, removing.id]) await aged(id, 25)+ const keys = [(await row(pending.id))!.objectKey, (await row(removing.id))!.objectKey]++ expect(await sweep()).toEqual({ removed: 0, failed: 0 })+ expect([(await row(pending.id))?.usedBy, (await row(removing.id))?.usedBy]).toEqual([null, null])+ expect(keys.map(key => files.objects.has(key))).toEqual([true, true])+ // Its own sweep takes them, file and row (lib/pendingUploadSweep.ts).+ expect(await sweepPendingUploads(db, files, Date.now())).toEqual({ removed: 2, failed: 0 })+ expect(keys.map(key => files.objects.has(key))).toEqual([false, false])+ })++ it('keeps a file whose object could not be deleted for the next run, and nothing can use it meanwhile', async () => {+ const { tab } = await fixture()+ const [stuck, other] = [(await file(tab, 'stuck.txt')).attachment, (await file(tab, 'other.txt')).attachment]+ const stuckPicture = await picture(tab)+ for (const id of [stuck.id, other.id, stuckPicture.id]) await aged(id, 25)+ const failing = new Set([objectKey(stuck.url), stuckPicture.key])+ const unavailable = async function (this: MemoryAttachmentStore, key: string) {+ if (failing.has(key)) throw new Error('bucket unavailable')+ this.objects.delete(key)+ }+ const chat = vi.spyOn(files, 'delete').mockImplementation(unavailable)+ const avatars = vi.spyOn(pictures, 'delete').mockImplementation(unavailable)+ try {+ await sweep()+ } finally {+ chat.mockRestore()+ avatars.mockRestore()+ }+ expect([await row(other.id), stored(other.url)]).toEqual([null, false])+ expect([(await row(stuck.id))?.id, stored(stuck.url), (await row(stuckPicture.id))?.id, pictures.objects.has(stuckPicture.key)])+ .toEqual([stuck.id, true, stuckPicture.id, true])+ await expect(send(tab, [stuck.id])).rejects.toMatchObject({ code: 'ATTACHMENT_EXPIRED', status: 410 })+ // Nobody else learns it existed: another member, or its owner from another Swarm, is refused as for an id that never was.+ await invite(tab)+ const never = await send(tab, ['0'.repeat(24)], peer).catch((error: unknown) => error as { code: string; message: string; status: number })+ expect(never.code).toBe('ATTACHMENT_UNAVAILABLE')+ const unknown = { code: never.code, message: never.message, status: never.status }+ await expect(send(tab, [stuck.id], peer)).rejects.toMatchObject(unknown)+ await expect(send((await fixture()).tab, [stuck.id])).rejects.toMatchObject(unknown)+ await expect(useAvatar(tab, stuckPicture.id)).rejects.toMatchObject({ code: 'AVATAR_UNAVAILABLE' })++ await sweep()+ expect([await row(stuck.id), stored(stuck.url), await row(stuckPicture.id), pictures.objects.has(stuckPicture.key)]).toEqual([null, false, null, false])+ })++ it('logs a failed delete by its code alone, never the stored file\'s address, name or link key', async () => {+ const { tab } = await fixture()+ const [offline, refused, odd] = [(await file(tab, 'offline-secret-plan.txt')).attachment, (await file(tab, 'refused-secret-plan.txt')).attachment,+ (await file(tab, 'odd-secret-plan.txt')).attachment]+ for (const id of [offline.id, refused.id, odd.id]) await aged(id, 25)+ const keys = [offline, refused, odd].map(upload => objectKey(upload.url))+ // As @google-cloud/storage fails: a network error's text is "request to <the object's address> failed" with a+ // system code, a refused call's text names the object with an HTTP status code; some errors carry neither.+ const address = (key: string) => `https://storage.googleapis.com/storage/v1/b/attachments/o/${encodeURIComponent(key)}`+ const errors = new Map<string, Error>([+ [keys[0], Object.assign(new Error(`request to ${address(keys[0])} failed, reason: socket hang up`), { code: 'ECONNRESET' })],+ [keys[1], Object.assign(new Error(`Permission denied on attachments/${keys[1]}`), { code: 403 })],+ [keys[2], new Error(`Could not reach ${address(keys[2])}`)],+ ])+ const chat = vi.spyOn(files, 'delete').mockImplementation(async (key: string) => { throw errors.get(key) ?? new Error('unexpected key') })+ const said: unknown[][] = []+ const log = { info: (...line: unknown[]) => said.push(line), warn: (...line: unknown[]) => said.push(line) }+ try {+ expect(await sweepUnsentAttachments(db, bucket, new Date(), { chunk: 10, chunks: 1, pauseMs: 0, log })).toEqual({ removed: 0, failed: 3 })+ } finally {+ chat.mockRestore()+ }+ const text = JSON.stringify(said)+ // Each key is <prefix>/<Swarm>/<link key>/<file name>; the link key alone opens the file on the CDN.+ const linkKeys = keys.map(key => key.split('/').at(-2)!)+ expect(linkKeys.every(linkKey => /^[0-9a-f]{32}$/.test(linkKey))).toBe(true)+ for (const secret of [...keys, ...linkKeys, 'secret-plan', 'storage.googleapis.com', 'socket hang up', 'Permission denied']) expect(text).not.toContain(secret)+ const line = '[attachment-sweep] could not remove a stored file; its row stays for the next run'+ expect(said).toEqual(expect.arrayContaining([[line, { attachmentId: offline.id, code: 'ECONNRESET' }], [line, { attachmentId: refused.id, code: '403' }],+ [line, { attachmentId: odd.id, code: 'unknown' }]]))+ await sweep()+ expect([await row(offline.id), await row(refused.id), await row(odd.id)]).toEqual([null, null, null])+ })++ it('runs a pass as the worker starts it, then hourly, and says once that it is on and what it removed', async () => {+ const { tab } = await fixture()+ const stale = (await file(tab, 'stale.txt')).attachment+ await aged(stale.id, 25)+ const said: unknown[] = []+ const stop = startAttachmentSweepFrom(db, () => bucket, { pauseMs: 0, log: { info: (...line: unknown[]) => said.push(line), warn: (...line: unknown[]) => said.push(line) } })+ try {+ await vi.waitFor(async () => expect(await row(stale.id)).toBeNull())+ expect(stored(stale.url)).toBe(false)+ await vi.waitFor(() => expect(said).toContainEqual(['[attachment-sweep] pass', { removed: 1, failed: 0 }]))+ expect(said.filter(line => (line as unknown[])[0] === '[attachment-sweep] on')).toEqual([['[attachment-sweep] on', { everyMinutes: 60 }]])+ } finally {+ stop()+ }+ })++ it('says once when the worker has no bucket, and a settings error turns off only the sweep', async () => {+ const said: unknown[][] = []+ const log = { info: (...line: unknown[]) => said.push(['info', ...line]), warn: (...line: unknown[]) => said.push(['warn', ...line]) }+ const settings = { NODE_ENV: 'production', SUPER_TAB_ATTACHMENTS_BUCKET: '', SUPER_TAB_ATTACHMENTS_CREDENTIALS: '', SUPER_TAB_ATTACHMENTS_PREFIX: 'super-tabs',+ SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: 'https://cdn.example.test', SUPER_TAB_AVATARS_BUCKET: '' }+ startAttachmentSweepFrom(db, () => attachmentsFromEnv(settings), { log })()+ expect(said).toEqual([['info', '[attachment-sweep] off: no attachments bucket is set (SUPER_TAB_ATTACHMENTS_BUCKET)']])+ said.length = 0+ // Settings the API would refuse too: the worker's other jobs still start, and the log says why the sweep did not.+ const broken = { ...settings, SUPER_TAB_ATTACHMENTS_BUCKET: 'attachments', SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: 'http://cdn.example.test' }+ expect(() => attachmentsFromEnv(broken)).toThrow()+ let stop: (() => void) | undefined+ expect(() => { stop = startAttachmentSweepFrom(db, () => attachmentsFromEnv(broken), { log }) }).not.toThrow()+ stop!()+ expect(said).toEqual([['warn', '[attachment-sweep] off: the attachment settings are invalid',+ { error: 'SUPER_TAB_ATTACHMENTS_PUBLIC_BASE must be an https:// address in production.' }]])+ })++ it('lets a send racing the sweep either take the file or be refused, never post a message linking a removed file', async () => {+ const { tab } = await fixture()+ // The sweep runs inside the send's transaction, after it read the file and just before it takes it. The send's+ // write then conflicts, and its retry finds the file gone.+ const late = (await file(tab, 'late.txt')).attachment+ await aged(late.id, 25)+ let attempts = 0+ const racing = new SuperTabStore(new Proxy(db, { get(target, key, receiver) {+ if (key !== '$transaction') return Reflect.get(target, key, receiver)+ return (body: (tx: PrismaClient) => Promise<unknown>, options: unknown) => target.$transaction(tx => body(new Proxy(tx, { get(client, name, clientReceiver) {+ const model = Reflect.get(client, name, clientReceiver)+ if (name !== 'superTabAttachment') return model+ return new Proxy(model, { get(delegate, method, delegateReceiver) {+ const original = Reflect.get(delegate, method, delegateReceiver)+ if (method !== 'updateMany') return original+ return async (...args: unknown[]) => { if (!attempts++) await sweep(); return original.apply(delegate, args) }+ } })+ } }) as PrismaClient), options as never)+ } }), Date.now, bucket)+ await expect(racing.execute(owner, tab, { operationId: randomUUID(), command: { type: 'message.send', conversationId: 'lead', text: 'late',+ replyTo: null, recipientIds: [], attachmentIds: [late.id] } })).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })+ expect(attempts).toBe(1)+ expect([await row(late.id), stored(late.url)]).toEqual([null, false])+ expect((await store.messages(owner, tab, 'lead', {})).messages.filter(m => m.attachments?.some(a => a.id === late.id))).toEqual([])++ // The send commits after the sweep picked the file, before the sweep's claim: the claim checks again and leaves it.+ const onTime = (await file(tab, 'on-time.txt')).attachment+ await aged(onTime.id, 25)+ let messageId = ''+ const sentBeforeClaim = new Proxy(db, { get(target, key, receiver) {+ const original = Reflect.get(target, key, receiver)+ if (key !== '$runCommandRaw') return original+ return async (command: Record<string, unknown>) => {+ if ('update' in command && !messageId) messageId = String((await send(tab, [onTime.id])).result.messageId)+ return original.call(target, command)+ }+ } })+ await sweep(sentBeforeClaim)+ expect(messageId).not.toBe('')+ expect([(await row(onTime.id))?.usedBy, stored(onTime.url)]).toEqual([messageId, true])+ expect((await store.messages(owner, tab, 'lead', {})).messages.find(m => m.id === messageId)?.attachments).toEqual([keptFile(onTime)])+ })+ })})it('releases a finished worker through its execution host, cancels deliveries and returns the machine slot', async () => {diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex b05d8bf04..2a8a097ea 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -879,6 +879,9 @@ model HarnessShare {@@unique([machineId, agentId, recipientEmail])@@index([recipientEmail, autonomousEnv, expiresAt])+ /// The share list (routes/harnessShares.ts): one recipient's unrevoked shares by createdAt, read without a sort in memory and+ /// without fetching the revoked ones. expiresAt last, so an expired share is dropped from its key before it is fetched.+ @@index([recipientEmail, autonomousEnv, revokedAt, createdAt, expiresAt])@@index([ownerId, machineId])@@map("harness_shares")}diff --git a/backend/src/lib/attachmentSweep.ts b/backend/src/lib/attachmentSweep.tsnew file mode 100644index 000000000..1d8ef02fc--- /dev/null+++ b/backend/src/lib/attachmentSweep.ts@@ -0,0 +1,149 @@+import { setTimeout as delay } from 'node:timers/promises'+import type { PrismaClient } from '@prisma/client'+import { AVATAR_PURPOSE, EXPIRED_UPLOAD, PENDING_UPLOAD_PURPOSE, REMOVING_UPLOAD_PURPOSE, UNSENT_LIFE_MS, type AttachmentStore, type Attachments } from '../superTabs/attachments.js'+import { logger } from '../utils/logger.js'++/**+ * Removes Swarm uploads nobody used within a day (Diego, 10-30): chat files never sent and pictures never set, row and stored+ * file, so the bucket stops growing. A file a message, a proposal or an avatar uses is never touched.+ *+ * An upload is first taken with one conditional write: still unused, never proposed and still a day old, its `usedBy` becomes+ * [EXPIRED_UPLOAD]. Every use takes an upload only while `usedBy` is empty (superTabs/store.ts), so a send racing the sweep+ * either took it first, and the claim leaves it, or finds it taken and is refused. Servers from before this sweep refuse a+ * taken upload too: to them it is a file already sent. Only what the claim marked is then removed: its stored file first,+ * then its row. When the file cannot be removed, the row stays marked and a later run tries again.+ *+ * Nothing indexes this scan (the only index starts with the Swarm), and it runs once an hour in the singleton worker over+ * about 2,000 rows (10-30).+ */+type Log = Pick<typeof logger, 'info' | 'warn'>+export interface AttachmentSweepOptions { chunk: number; chunks: number; pauseMs: number; log?: Log }+/** At most 500 uploads an hour, in chunks of 100 with a pause between them. */+export const ATTACHMENT_SWEEP = { chunk: 100, chunks: 5, pauseMs: 250, everyMs: 3_600_000 } as const++export interface AttachmentSweepPass {+ /** Uploads removed, stored file and row. */+ removed: number+ /** Taken uploads whose stored file could not be removed this run: their rows stay for the next one. */+ failed: number+}++// Raw commands, as the receipt sweep sends them: Prisma would send `in` and the unset-field checks as $expr (superTabs/hotFilters.test.ts).+const COLLECTION = 'SuperTabAttachment'+const date = (at: Date) => ({ $date: at.toISOString() })+type Found<T> = { cursor: { firstBatch: T[] } }+type Written = { n?: number; writeErrors?: unknown[] }+const written = (answer: Written, what: string) => {+ if (answer.writeErrors?.length) throw new Error(`The database refused some upload ${what}`)+ return answer.n ?? 0+}++/** Takes up to [chunk] uploads that are a day old and unused; answers how many it took. `null` also matches a missing field.+ * An upload still on its link, or being removed after it, is the pending-upload sweep's (lib/pendingUploadSweep.ts). */+async function claim(db: PrismaClient, cutoff: Date, chunk: number): Promise<number> {+ const due = { createdAt: { $lt: date(cutoff) }, usedBy: null, proposedBy: null, purpose: { $nin: [PENDING_UPLOAD_PURPOSE, REMOVING_UPLOAD_PURPOSE] } }+ const found = await db.$runCommandRaw({ find: COLLECTION, filter: due, projection: { _id: 1 }, limit: chunk, singleBatch: true } as never) as Found<{ _id: string }>+ const ids = found.cursor.firstBatch.map(row => row._id)+ if (!ids.length) return 0+ // The same conditions again: one used since it was found stays.+ return written(await db.$runCommandRaw({ update: COLLECTION, updates: [{ q: { _id: { $in: ids }, ...due }, u: { $set: { usedBy: EXPIRED_UPLOAD } },+ multi: true }] } as never) as Written, 'claims')+}++/**+ * What a failed store call is, without its text: a network error's text holds the request's address, and that holds the+ * stored file's name and its link key, which opens the file. A system code (ECONNRESET) or an HTTP status (403) says enough.+ */+export function failureCode(error: unknown): string {+ const { code, status } = (error && typeof error === 'object' ? error : {}) as { code?: unknown; status?: unknown }+ for (const value of [code, status]) {+ if (typeof value === 'number' && Number.isInteger(value)) return String(value)+ if (typeof value === 'string' && /^[A-Z][A-Z0-9_]{0,39}$/.test(value)) return value+ }+ return 'unknown'+}++/** Removes up to [chunk] taken uploads, skipping those whose file failed earlier in this run. */+async function remove(db: PrismaClient, attachments: Attachments, chunk: number, failedIds: Set<string>, log: Log): Promise<AttachmentSweepPass & { found: number }> {+ const found = await db.$runCommandRaw({ find: COLLECTION, filter: { usedBy: EXPIRED_UPLOAD, _id: { $nin: [...failedIds] } },+ projection: { _id: 1, objectKey: 1, purpose: 1 }, limit: chunk, singleBatch: true } as never) as Found<{ _id: string; objectKey: string; purpose?: string | null }>+ const rows = found.cursor.firstBatch+ const gone: string[] = []+ for (const row of rows) {+ const store: AttachmentStore | null = row.purpose === AVATAR_PURPOSE ? attachments.avatars ?? null : attachments.store+ try {+ if (!store) throw new Error('No avatar store is configured')+ await store.delete(row.objectKey)+ gone.push(row._id)+ } catch (error) {+ // The key and the error's text hold the file's name and link key: only the row id and the error's code are logged.+ failedIds.add(row._id)+ log.warn('[attachment-sweep] could not remove a stored file; its row stays for the next run', { attachmentId: row._id, code: failureCode(error) })+ }+ }+ const removed = gone.length ? written(await db.$runCommandRaw({ delete: COLLECTION, deletes: [{ q: { _id: { $in: gone }, usedBy: EXPIRED_UPLOAD }, limit: 0 }] } as never) as Written, 'removals') : 0+ return { removed, failed: rows.length - gone.length, found: rows.length }+}++/** One pass: at most [chunks] × [chunk] uploads taken and removed. Safe to repeat, and from two processes at once. */+export async function sweepUnsentAttachments(db: PrismaClient, attachments: Attachments, now = new Date(),+ options: AttachmentSweepOptions = ATTACHMENT_SWEEP): Promise<AttachmentSweepPass> {+ const cutoff = new Date(now.getTime() - UNSENT_LIFE_MS)+ const failedIds = new Set<string>()+ let removed = 0+ for (let i = 0; i < options.chunks; i++) {+ if (i) await delay(options.pauseMs)+ const taken = await claim(db, cutoff, options.chunk)+ const pass = await remove(db, attachments, options.chunk, failedIds, options.log ?? logger)+ removed += pass.removed+ if (taken < options.chunk && pass.found < options.chunk) break+ }+ return { removed, failed: failedIds.size }+}++/** Runs a pass at start and then every hour in the singleton worker. A failed pass is logged and the next one tries again. */+export function startAttachmentSweep(db: PrismaClient, attachments: Attachments, settings: Partial<AttachmentSweepOptions & { everyMs: number;+ now: () => Date; log: Log }> = {}): () => void {+ const { everyMs, now, ...options } = { ...ATTACHMENT_SWEEP, now: () => new Date(), log: logger as Log, ...settings }+ const { log } = options+ let running = false+ const run = async () => {+ if (running) return+ running = true+ try {+ const pass = await sweepUnsentAttachments(db, attachments, now(), options)+ if (pass.removed || pass.failed) log.info('[attachment-sweep] pass', { ...pass })+ } catch (error) {+ log.warn('[attachment-sweep] pass failed; retrying next hour', { error: error instanceof Error ? error.message : String(error) })+ } finally {+ running = false+ }+ }+ const timer = setInterval(() => void run(), everyMs)+ timer.unref()+ void run()+ return () => clearInterval(timer)+}++/**+ * The worker's start: reads the attachment settings, says once whether the sweep is on, and starts it. The worker runs+ * in its own deployment, so its settings can differ from the API's: without a bucket the sweep says it is off, and settings+ * that cannot be read turn off only the sweep, never the worker's other jobs. Setting errors name a setting, never its value.+ */+export function startAttachmentSweepFrom(db: PrismaClient, settings: () => Attachments | null,+ options: Parameters<typeof startAttachmentSweep>[2] = {}): () => void {+ const log = options.log ?? logger+ let attachments: Attachments | null+ try {+ attachments = settings()+ } catch (error) {+ log.warn('[attachment-sweep] off: the attachment settings are invalid', { error: error instanceof Error ? error.message : String(error) })+ return () => {}+ }+ if (!attachments) {+ log.info('[attachment-sweep] off: no attachments bucket is set (SUPER_TAB_ATTACHMENTS_BUCKET)')+ return () => {}+ }+ log.info('[attachment-sweep] on', { everyMinutes: (options.everyMs ?? ATTACHMENT_SWEEP.everyMs) / 60_000 })+ return startAttachmentSweep(db, attachments, options)+}diff --git a/backend/src/lib/voiceQuota.ts b/backend/src/lib/voiceQuota.tsindex 78d1786c9..df1275034 100644--- a/backend/src/lib/voiceQuota.ts+++ b/backend/src/lib/voiceQuota.ts@@ -1,5 +1,6 @@import type { Prisma } from '@prisma/client'-import { prisma } from './prisma.js'+import { machineAlive, prisma } from './prisma.js'+import { machineBillingAllowsDataPlane } from './billingState.js'import { logger } from '../utils/logger.js'const PENDING_RESERVATION_MS = 20 * 60_000@@ -72,6 +73,47 @@ async function limitForMachine(machineId: string, db: DbClient = prisma): Promisreturn Math.max(0, plan?.dailyVoiceLimitSeconds ?? 0)}+/**+ * An account's bucket in the same usage and reservation tables a device's machineId keys. A machineId is+ * 32 hex characters (sha256 of its key), so the `user:` prefix can never name a real machine, and no+ * schema change or second cleanup is needed.+ */+export const userVoiceBucket = (userId: string): string => `user:${userId}`++/** The Free tier's allowance (lib/db/seed.ts), for an account whose plans cannot be read at all. */+const FALLBACK_USER_LIMIT_SECONDS = 10 * 60++/**+ * An account's daily voice seconds: the most generous plan among its live machines (0, unlimited, beats+ * any number), else its environment's default plan. Only a machine whose billing lets it run grants its+ * plan (the rule every data-plane path applies): a checkout that never completed would buy Pro voice by+ * opening it, and a lapsed Max subscription would keep unlimited voice. Unlike a device, an account with no plan to+ * read is never unlimited: it is any signed-in account, so it falls back to the Free allowance.+ */+async function limitForUser(userId: string, autonomousEnv: string, db: DbClient = prisma): Promise<number> {+ const machines = await db.machine.findMany({+ where: { userId, ...machineAlive },+ select: { planId: true, billingStatus: true, authMode: true },+ })+ const planIds = [...new Set(machines+ .filter((m) => m.planId && machineBillingAllowsDataPlane(m))+ .map((m) => m.planId as string))]+ // By id, one read each: an account has a machine or a few, and an `in` filter is sent as $expr.+ const plans = await Promise.all(planIds.map((id) =>+ db.subscriptionPlan.findUnique({ where: { id }, select: { dailyVoiceLimitSeconds: true } })))+ const limits = plans+ .map((p) => p?.dailyVoiceLimitSeconds)+ .filter((s): s is number => typeof s === 'number')+ .map((s) => Math.max(0, s))+ if (limits.length) return limits.includes(0) ? 0 : Math.max(...limits)+ const fallback = await db.subscriptionPlan.findFirst({+ where: { autonomousEnv, isDefault: true },+ select: { dailyVoiceLimitSeconds: true },+ })+ const seconds = fallback?.dailyVoiceLimitSeconds+ return typeof seconds === 'number' && seconds > 0 ? seconds : FALLBACK_USER_LIMIT_SECONDS+}+function transientTransactionError(err: unknown): boolean {const code = typeof err === 'object' && err ? (err as { code?: unknown }).code : undefinedconst message = err instanceof Error ? err.message : String(err)@@ -96,6 +138,92 @@ async function withTransactionRetry<T>(throw lastError}+/**+ * Charge [durationMs] to one bucket's UTC day: a device's machineId, or an account's {@link userVoiceBucket}.+ * [limitOf] resolves the bucket's plan inside the same transaction as the usage increment so a concurrent+ * plan change cannot validate against one tier and charge against another snapshot.+ */+async function reserveInBucket(+ machineId: string,+ limitOf: (tx: Prisma.TransactionClient) => Promise<number>,+ uploadId: string,+ durationMs: number,+ now: Date,+): Promise<VoiceQuotaReservationResult> {+ if (!uploadId) throw new Error('voice uploadId is required')+ const roundedDurationMs = Math.max(1, Math.ceil(durationMs))+ const { dayKey, resetAt, expiresAt } = utcWindow(now)++ return withTransactionRetry(async (tx) => {+ const limitSeconds = await limitOf(tx)+ const limitMs = limitSeconds * 1000+ const existing = await tx.machineVoiceReservation.findUnique({ where: { uploadId } })+ if (existing && (existing.machineId !== machineId || existing.dayKey !== dayKey)) {+ throw new Error('voice uploadId belongs to another machine or UTC day')+ }+ const usage = await tx.machineVoiceDailyUsage.upsert({+ where: { machineId_dayKey: { machineId, dayKey } },+ update: { expiresAt },+ create: { machineId, dayKey, usedMs: 0, expiresAt },+ })+ if (existing?.status === 'committed' || existing?.status === 'pending') {+ return {+ snapshot: snapshot(machineId, dayKey, resetAt, usage.usedMs, limitSeconds),+ state: existing.status,+ }+ }+ if (limitSeconds > 0 && usage.usedMs + roundedDurationMs > limitMs) {+ throw new VoiceQuotaExceededError(snapshot(machineId, dayKey, resetAt, usage.usedMs, limitSeconds))+ }++ const updated = await tx.machineVoiceDailyUsage.updateMany({+ where: {+ machineId,+ dayKey,+ ...(limitSeconds > 0 ? { usedMs: { lte: limitMs - roundedDurationMs } } : {}),+ },+ data: { usedMs: { increment: roundedDurationMs }, expiresAt },+ })+ if (updated.count !== 1) {+ const current = await tx.machineVoiceDailyUsage.findUnique({+ where: { machineId_dayKey: { machineId, dayKey } },+ })+ throw new VoiceQuotaExceededError(snapshot(machineId, dayKey, resetAt, current?.usedMs ?? 0, limitSeconds))+ }++ const releaseAt = new Date(now.getTime() + PENDING_RESERVATION_MS)+ if (existing?.status === 'released') {+ await tx.machineVoiceReservation.update({+ where: { uploadId },+ data: {+ durationMs: roundedDurationMs,+ status: 'pending',+ releaseAt,+ expiresAt,+ committedAt: null,+ releasedAt: null,+ },+ })+ } else {+ await tx.machineVoiceReservation.create({+ data: {+ uploadId,+ machineId,+ dayKey,+ durationMs: roundedDurationMs,+ status: 'pending',+ releaseAt,+ expiresAt,+ },+ })+ }+ return {+ snapshot: snapshot(machineId, dayKey, resetAt, usage.usedMs + roundedDurationMs, limitSeconds),+ state: 'reserved',+ }+ })+}+export const voiceQuotaService = {async snapshotForMachine(machineId: string, now = new Date()): Promise<VoiceQuotaSnapshot> {const [{ dayKey, resetAt }, limitSeconds] = await Promise.all([@@ -115,82 +243,25 @@ export const voiceQuotaService = {durationMs: number,now = new Date(),): Promise<VoiceQuotaReservationResult> {- if (!uploadId) throw new Error('voice uploadId is required')- const roundedDurationMs = Math.max(1, Math.ceil(durationMs))- const { dayKey, resetAt, expiresAt } = utcWindow(now)-- return withTransactionRetry(async (tx) => {- // Resolve the plan inside the same transaction as the usage increment so a concurrent plan- // change cannot validate against one tier and charge against another snapshot.- const limitSeconds = await limitForMachine(machineId, tx)- const limitMs = limitSeconds * 1000- const existing = await tx.machineVoiceReservation.findUnique({ where: { uploadId } })- if (existing && (existing.machineId !== machineId || existing.dayKey !== dayKey)) {- throw new Error('voice uploadId belongs to another machine or UTC day')- }- const usage = await tx.machineVoiceDailyUsage.upsert({- where: { machineId_dayKey: { machineId, dayKey } },- update: { expiresAt },- create: { machineId, dayKey, usedMs: 0, expiresAt },- })- if (existing?.status === 'committed' || existing?.status === 'pending') {- return {- snapshot: snapshot(machineId, dayKey, resetAt, usage.usedMs, limitSeconds),- state: existing.status,- }- }- if (limitSeconds > 0 && usage.usedMs + roundedDurationMs > limitMs) {- throw new VoiceQuotaExceededError(snapshot(machineId, dayKey, resetAt, usage.usedMs, limitSeconds))- }-- const updated = await tx.machineVoiceDailyUsage.updateMany({- where: {- machineId,- dayKey,- ...(limitSeconds > 0 ? { usedMs: { lte: limitMs - roundedDurationMs } } : {}),- },- data: { usedMs: { increment: roundedDurationMs }, expiresAt },- })- if (updated.count !== 1) {- const current = await tx.machineVoiceDailyUsage.findUnique({- where: { machineId_dayKey: { machineId, dayKey } },- })- throw new VoiceQuotaExceededError(snapshot(machineId, dayKey, resetAt, current?.usedMs ?? 0, limitSeconds))- }-- const releaseAt = new Date(now.getTime() + PENDING_RESERVATION_MS)- if (existing?.status === 'released') {- await tx.machineVoiceReservation.update({- where: { uploadId },- data: {- durationMs: roundedDurationMs,- status: 'pending',- releaseAt,- expiresAt,- committedAt: null,- releasedAt: null,- },- })- } else {- await tx.machineVoiceReservation.create({- data: {- uploadId,- machineId,- dayKey,- durationMs: roundedDurationMs,- status: 'pending',- releaseAt,- expiresAt,- },- })- }- return {- snapshot: snapshot(machineId, dayKey, resetAt, usage.usedMs + roundedDurationMs, limitSeconds),- state: 'reserved',- }- })+ return reserveInBucket(machineId, (tx) => limitForMachine(machineId, tx), uploadId, durationMs, now)},+ /**+ * The same daily ceiling for a signed-in account rather than a device: /api/voice/stt, which the phone's+ * voice input and the cabled dial (through the CLI) both reach with the person's own sign-in. Its bucket+ * is the account's ({@link userVoiceBucket}), so it is commit()ed and release()d by uploadId like any+ * other reservation, and the cleanup worker releases a stale one the same way.+ */+ async reserveForUser(+ userId: string,+ autonomousEnv: string,+ uploadId: string,+ durationMs: number,+ now = new Date(),+ ): Promise<VoiceQuotaReservationResult> {+ if (!userId) throw new Error('voice userId is required')+ return reserveInBucket(userVoiceBucket(userId), (tx) => limitForUser(userId, autonomousEnv, tx), uploadId, durationMs, now)+ },async commit(uploadId: string, now = new Date()): Promise<void> {await prisma.machineVoiceReservation.updateMany({where: { uploadId, status: 'pending' },diff --git a/backend/src/routes/voice.test.ts b/backend/src/routes/voice.test.tsnew file mode 100644index 000000000..b881d76f4--- /dev/null+++ b/backend/src/routes/voice.test.ts@@ -0,0 +1,323 @@+// POST /api/voice/stt — the phone's voice input and the cabled dial, transcribed on Harness's Deepgram key.+//+// Pinned here: that one account cannot spend that key without bound. A burst is cut at a per-minute cap,+// the account's plan bounds its seconds a day, and an upload the process-wide voice memory budget cannot+// hold is refused before it is buffered. Deepgram is never called for a refused clip, and every answered+// clip gives its memory back.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'++const authenticateAccessToken = vi.hoisted(() => vi.fn())+vi.mock('../lib/ssoAuth.js', async (importActual) => ({+ ...(await importActual<typeof import('../lib/ssoAuth.js')>()),+ authenticateAccessToken,+}))++const transcribeWavWithDeepgram = vi.hoisted(() => vi.fn())+vi.mock('../lib/deepgramWav.js', async (importActual) => ({+ ...(await importActual<typeof import('../lib/deepgramWav.js')>()),+ transcribeWavWithDeepgram,+}))++// The voice usage tables and the plan rows, in memory: enough of Prisma for lib/voiceQuota.ts.+interface MachineRow { userId: string; planId: string | null; deletedAt?: Date | null; billingStatus?: string | null; billingActivatedAt?: Date | null; autonomousEnv?: string }+interface PlanRow { id: string; autonomousEnv: string; isDefault: boolean; dailyVoiceLimitSeconds: number | null }+interface UsageRow { machineId: string; dayKey: string; usedMs: number; expiresAt: Date }+const store = vi.hoisted(() => ({+ machines: [] as MachineRow[],+ plans: [] as PlanRow[],+ usage: new Map<string, UsageRow>(),+ reservations: new Map<string, Record<string, unknown>>(),+}))++vi.mock('../lib/prisma.js', () => {+ const usageKey = (where: { machineId_dayKey?: { machineId: string; dayKey: string }; machineId?: string; dayKey?: string }) => {+ const k = where.machineId_dayKey ?? where+ return `${k.machineId}|${k.dayKey}`+ }+ const alive = (m: MachineRow) => m.deletedAt == null+ const db = {+ machine: {+ findUnique: async () => null,+ findMany: async ({ where }: { where: { userId: string } }) =>+ store.machines.filter((m) => m.userId === where.userId && alive(m)).map((m) => ({ ...m })),+ },+ subscriptionPlan: {+ findUnique: async ({ where }: { where: { id: string } }) => store.plans.find((p) => p.id === where.id) ?? null,+ findFirst: async ({ where }: { where: { autonomousEnv: string; isDefault: boolean } }) =>+ store.plans.find((p) => p.autonomousEnv === where.autonomousEnv && p.isDefault === where.isDefault) ?? null,+ },+ machineVoiceDailyUsage: {+ findUnique: async ({ where }: { where: { machineId_dayKey: { machineId: string; dayKey: string } } }) => {+ const row = store.usage.get(usageKey(where))+ return row ? { ...row } : null+ },+ upsert: async ({ where, create, update }: { where: { machineId_dayKey: { machineId: string; dayKey: string } }; create: UsageRow; update: { expiresAt: Date } }) => {+ const key = usageKey(where)+ const row = store.usage.get(key)+ if (row) row.expiresAt = update.expiresAt+ else store.usage.set(key, { ...create })+ return { ...store.usage.get(key)! }+ },+ updateMany: async ({ where, data }: { where: { machineId: string; dayKey: string; usedMs?: { lte?: number } }; data: { usedMs: { increment?: number; decrement?: number } } }) => {+ const row = store.usage.get(usageKey(where))+ if (!row) return { count: 0 }+ if (where.usedMs?.lte != null && row.usedMs > where.usedMs.lte) return { count: 0 }+ row.usedMs += data.usedMs.increment ?? -(data.usedMs.decrement ?? 0)+ return { count: 1 }+ },+ },+ machineVoiceReservation: {+ findUnique: async ({ where }: { where: { uploadId: string } }) => store.reservations.get(where.uploadId) ?? null,+ create: async ({ data }: { data: Record<string, unknown> }) => {+ store.reservations.set(String(data.uploadId), { ...data })+ return data+ },+ update: async ({ where, data }: { where: { uploadId: string }; data: Record<string, unknown> }) => {+ const next = { ...store.reservations.get(where.uploadId), ...data }+ store.reservations.set(where.uploadId, next)+ return next+ },+ updateMany: async ({ where, data }: { where: { uploadId: string; status?: string }; data: Record<string, unknown> }) => {+ const row = store.reservations.get(where.uploadId)+ if (!row || (where.status && row.status !== where.status)) return { count: 0 }+ store.reservations.set(where.uploadId, { ...row, ...data })+ return { count: 1 }+ },+ },+ $transaction: async (action: (tx: unknown) => Promise<unknown>) => action(db),+ }+ return { prisma: db, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }+})++import { voiceRoutes, VOICE_STT_PATH } from './voice.js'+import { errorHandler } from '../middlewares/errorHandler.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { env } from '../config/env.js'+import { voiceInflightBytes } from '../lib/voiceBudget.js'++const FREE: PlanRow = { id: 'plan-free', autonomousEnv: 'prod', isDefault: true, dailyVoiceLimitSeconds: 10 * 60 }+const PRO: PlanRow = { id: 'plan-pro', autonomousEnv: 'prod', isDefault: false, dailyVoiceLimitSeconds: 30 * 60 }+const MAX: PlanRow = { id: 'plan-max', autonomousEnv: 'prod', isDefault: false, dailyVoiceLimitSeconds: 0 }++const BYTES_PER_SECOND = 16_000 * 2 // 16 kHz, mono, 16-bit: what the phone and the dial record++/** A WAV of [seconds] of silence, its header stating [sampleRate] and [format] (16 kHz PCM unless forged). */+function wav(seconds: number, sampleRate = 16_000, format = 1): Buffer {+ const data = Math.round(seconds * BYTES_PER_SECOND)+ const out = Buffer.alloc(44 + data)+ out.write('RIFF', 0, 'ascii')+ out.writeUInt32LE(36 + data, 4)+ out.write('WAVE', 8, 'ascii')+ out.write('fmt ', 12, 'ascii')+ out.writeUInt32LE(16, 16)+ out.writeUInt16LE(format, 20) // 1 = PCM+ out.writeUInt16LE(1, 22) // mono+ out.writeUInt32LE(sampleRate, 24)+ out.writeUInt32LE((sampleRate * 2) >>> 0, 28)+ out.writeUInt16LE(2, 32)+ out.writeUInt16LE(16, 34)+ out.write('data', 36, 'ascii')+ out.writeUInt32LE(data, 40)+ return out+}++function multipart(file: Buffer, contentType = 'audio/wav'): { payload: Buffer; headers: Record<string, string> } {+ const boundary = 'harness-test-boundary'+ const payload = Buffer.concat([+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="voice.wav"\r\nContent-Type: ${contentType}\r\n\r\n`),+ file,+ Buffer.from(`\r\n--${boundary}--\r\n`),+ ])+ return { payload, headers: { 'content-type': `multipart/form-data; boundary=${boundary}` } }+}++async function build(): Promise<FastifyInstance> {+ const app = Fastify()+ app.setErrorHandler(errorHandler)+ registerAuthMiddleware(app, authenticateAccessToken)+ await app.register(voiceRoutes)+ await app.ready()+ return app+}++const send = (app: FastifyInstance, file: Buffer, user = 'user-1', contentType = 'audio/wav') => {+ const { payload, headers } = multipart(file, contentType)+ return app.inject({+ method: 'POST',+ url: `${VOICE_STT_PATH}?lang=en`,+ payload,+ headers: { ...headers, authorization: `Bearer token-of-${user}` },+ })+}++const usedSeconds = (user: string) => {+ const row = [...store.usage.values()].find((r) => r.machineId === `user:${user}`)+ return row ? row.usedMs / 1000 : 0+}++let app: FastifyInstance+const budget = env.VOICE_INFLIGHT_MAX_BYTES++beforeEach(async () => {+ vi.clearAllMocks()+ store.machines = []+ store.plans = [FREE, PRO, MAX]+ store.usage.clear()+ store.reservations.clear()+ env.VOICE_INFLIGHT_MAX_BYTES = budget+ authenticateAccessToken.mockImplementation(async (token: string) => ({+ sub: token.replace('token-of-', ''), email: '[email protected]', role: 'user', autonomousEnv: 'prod',+ }))+ transcribeWavWithDeepgram.mockResolvedValue('hello there')+ app = await build()+})++afterEach(async () => {+ await app.close()+ env.VOICE_INFLIGHT_MAX_BYTES = budget+})++describe('POST /api/voice/stt', () => {+ it('transcribes a clip and charges its seconds to the account', async () => {+ const res = await send(app, wav(3))+ expect(res.statusCode).toBe(200)+ expect(res.json()).toEqual({ success: true, data: { transcript: 'hello there', lang: 'en' } })+ expect(transcribeWavWithDeepgram).toHaveBeenCalledTimes(1)+ expect(usedSeconds('user-1')).toBe(3)+ })++ describe('per-minute cap', () => {+ it('refuses a burst past the cap with 429 and never calls Deepgram for the refused clips', async () => {+ store.machines = [{ userId: 'user-1', planId: MAX.id }]+ const codes: number[] = []+ for (let i = 0; i < 14; i++) codes.push((await send(app, wav(1))).statusCode)+ expect(codes.slice(0, 10)).toEqual(Array(10).fill(200))+ expect(codes.slice(10)).toEqual(Array(4).fill(429))+ expect(transcribeWavWithDeepgram).toHaveBeenCalledTimes(10)+ const refused = await send(app, wav(1))+ expect(refused.json().error.code).toBe('RATE_LIMITED')+ })++ it('counts each account on its own', async () => {+ for (let i = 0; i < 10; i++) await send(app, wav(1), 'user-1')+ expect((await send(app, wav(1), 'user-1')).statusCode).toBe(429)+ expect((await send(app, wav(1), 'user-2')).statusCode).toBe(200)+ })+ })++ describe('daily seconds by plan', () => {+ it('refuses a Free account past 10 minutes a day, in plain words, without calling Deepgram', async () => {+ for (let i = 0; i < 4; i++) expect((await send(app, wav(140))).statusCode).toBe(200)+ expect(usedSeconds('user-1')).toBe(560)+ transcribeWavWithDeepgram.mockClear()+ const res = await send(app, wav(60))+ expect(res.statusCode).toBe(429)+ expect(res.json().error.code).toBe('DAILY_VOICE_LIMIT_REACHED')+ expect(res.json().error.message).toMatch(/today's voice limit/i)+ expect(res.json().error.message).toMatch(/10 minutes/)+ expect(transcribeWavWithDeepgram).not.toHaveBeenCalled()+ expect(usedSeconds('user-1')).toBe(560)+ // What is left still passes.+ expect((await send(app, wav(40))).statusCode).toBe(200)+ })++ it('gives a Pro account 30 minutes a day', async () => {+ store.machines = [{ userId: 'user-1', planId: FREE.id }, { userId: 'user-1', planId: PRO.id }]+ for (let i = 0; i < 6; i++) expect((await send(app, wav(290))).statusCode).toBe(200)+ expect((await send(app, wav(61))).statusCode).toBe(429)+ })++ it('lifts the cap for an account on an unlimited plan', async () => {+ store.machines = [{ userId: 'user-1', planId: MAX.id }]+ for (let i = 0; i < 3; i++) expect((await send(app, wav(400))).statusCode).toBe(200)+ })++ it('does not grant a plan through a deleted machine or an unpaid checkout', async () => {+ store.machines = [+ { userId: 'user-1', planId: MAX.id, deletedAt: new Date() },+ { userId: 'user-1', planId: PRO.id, billingStatus: 'pending', billingActivatedAt: null },+ ]+ expect((await send(app, wav(590))).statusCode).toBe(200)+ expect((await send(app, wav(20))).statusCode).toBe(429)+ })++ it('does not grant a plan through a machine whose subscription lapsed', async () => {+ store.machines = [{ userId: 'user-1', planId: MAX.id, billingStatus: 'suspended', billingActivatedAt: new Date('2026-10-01') }]+ expect((await send(app, wav(590))).statusCode).toBe(200)+ expect((await send(app, wav(20))).statusCode).toBe(429)+ })++ it('holds even with no plan rows: a forgotten default never means unlimited', async () => {+ store.plans = []+ expect((await send(app, wav(590))).statusCode).toBe(200)+ expect((await send(app, wav(20))).statusCode).toBe(429)+ })++ it('refuses a header that claims an absurd sample rate, which would read a long clip as no time', async () => {+ const res = await send(app, wav(590, 0xffff_fff0))+ expect(res.statusCode).toBe(415)+ expect(transcribeWavWithDeepgram).not.toHaveBeenCalled()+ expect(usedSeconds('user-1')).toBe(0)+ })++ it('refuses compressed audio, whose bytes say nothing of its length, before Deepgram', async () => {+ // An MP3 or Opus file is many times longer than its bytes at 16 kHz PCM: charging it as PCM lets a+ // Free account transcribe hours a day. The phone and the dial send 16 kHz PCM WAV only.+ const mp3 = Buffer.concat([Buffer.from('ID3\x04\x00\x00\x00\x00\x00\x00', 'binary'), Buffer.alloc(64_000, 0xff)])+ const notWav = await send(app, mp3, 'user-1', 'audio/mpeg')+ expect(notWav.statusCode).toBe(415)+ expect(notWav.json().error.code).toBe('UNSUPPORTED_AUDIO')+ const mp3InWav = await send(app, wav(5, 16_000, 0x55))+ expect(mp3InWav.statusCode).toBe(415)+ expect(transcribeWavWithDeepgram).not.toHaveBeenCalled()+ expect(usedSeconds('user-1')).toBe(0)+ expect(voiceInflightBytes()).toBe(0)+ })++ it('sends Deepgram the audio as WAV, whatever type the caller named', async () => {+ expect((await send(app, wav(2), 'user-1', 'audio/ogg')).statusCode).toBe(200)+ expect(transcribeWavWithDeepgram).toHaveBeenCalledWith(expect.any(Buffer), 'audio/wav', 'en')+ })++ it('gives the seconds back when Deepgram fails', async () => {+ transcribeWavWithDeepgram.mockRejectedValueOnce(new Error('Deepgram HTTP 500'))+ const res = await send(app, wav(30))+ expect(res.statusCode).toBe(502)+ expect(usedSeconds('user-1')).toBe(0)+ })+ })++ describe('voice memory budget', () => {+ it('refuses an upload the budget cannot hold, before Deepgram', async () => {+ env.VOICE_INFLIGHT_MAX_BYTES = 64 * 1024+ const res = await send(app, wav(5)) // ~160 KB+ expect(res.statusCode).toBe(503)+ expect(res.json().error.code).toBe('VOICE_BUSY')+ expect(transcribeWavWithDeepgram).not.toHaveBeenCalled()+ expect(voiceInflightBytes()).toBe(0)+ expect(usedSeconds('user-1')).toBe(0)+ })++ it('holds the upload in the budget while it is transcribed and releases it after each answered clip', async () => {+ let heldDuring = 0+ transcribeWavWithDeepgram.mockImplementation(async () => {+ heldDuring = voiceInflightBytes()+ return 'ok'+ })+ expect((await send(app, wav(2))).statusCode).toBe(200)+ expect(heldDuring).toBeGreaterThanOrEqual(2 * BYTES_PER_SECOND)+ expect(voiceInflightBytes()).toBe(0)++ transcribeWavWithDeepgram.mockRejectedValueOnce(new Error('Deepgram HTTP 500'))+ expect((await send(app, wav(2))).statusCode).toBe(502)+ expect(voiceInflightBytes()).toBe(0)++ store.usage.set(`user:user-1|${new Date().toISOString().slice(0, 10)}`, {+ machineId: 'user:user-1', dayKey: new Date().toISOString().slice(0, 10), usedMs: 600_000, expiresAt: new Date(Date.now() + 86_400_000),+ })+ expect((await send(app, wav(2))).statusCode).toBe(429)+ expect(voiceInflightBytes()).toBe(0)+ })+ })+})diff --git a/backend/src/routes/voice.ts b/backend/src/routes/voice.tsindex b61f3bc59..037b92c23 100644--- a/backend/src/routes/voice.ts+++ b/backend/src/routes/voice.ts@@ -14,11 +14,24 @@** NOT in the auth middleware's skip-list, deliberately: being absent from that list is what applies the* SSO gate, so `req.user` is populated here and an unauthenticated request never reaches this handler.+ *+ * WHAT BOUNDS IT. Every clip is paid on Harness's Deepgram key, so a signed-in account is held to what its+ * device would be held to (lib/deviceWs.ts), in this order, each before anything is spent on the next:+ * 1. a per-minute cap per account, counted in Redis across every pod (lib/rateLimit.ts);+ * 2. the process-wide voice memory budget (lib/voiceBudget.ts), taken for the whole request before the+ * upload is buffered and given back once it is answered;+ * 3. the account's plan's daily voice seconds (lib/voiceQuota.ts), charged by the clip's length before+ * Deepgram is called and given back when Deepgram fails. Only PCM WAV is taken, so that length is+ * known from the bytes (wavDurationMs).*/-import type { FastifyInstance } from 'fastify'+import { randomUUID } from 'node:crypto'+import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'import multipart from '@fastify/multipart'import { VOICE_WAV_LANGS, transcribeWavWithDeepgram } from '../lib/deepgramWav.js'+import { createRateLimiter } from '../lib/rateLimit.js'+import { releaseVoice, reserveVoice } from '../lib/voiceBudget.js'+import { VoiceQuotaExceededError, voiceQuotaService } from '../lib/voiceQuota.js'import { sendError, sendSuccess } from '../utils/response.js'import { logger } from '../utils/logger.js'@@ -27,6 +40,40 @@ export const VOICE_STT_PATH = '/api/voice/stt'/** ~25 MB — far above any dictation clip this serves, while still bounding one request's buffer. */const MAX_AUDIO_BYTES = 25 * 1024 * 1024+/** Per account. Dictation is a clip every few seconds at most; a client in a loop does not get far. */+const PER_MINUTE = 10+const MINUTE_MS = 60_000++const WAV_HEADER_BYTES = 44+const WAVE_FORMAT_PCM = 1++/**+ * The clip's length in milliseconds, as Deepgram will hear it, or null when it cannot be told from the bytes.+ *+ * Only uncompressed PCM WAV is accepted, which is all the phone (mobile/lib/phone/voice_wav.dart) and the dial+ * (cli/src/cable/cableHost.ts wav()) ever send: its length is the bytes after the header at the rate the header+ * states. Compressed audio (MP3, Opus, or a compressed codec inside a WAV) is many times longer than its bytes+ * suggest, so charging it by size would let one account transcribe hours a day on a 10-minute plan. The header+ * is the caller's to write, so a rate, channel count or sample size outside what a microphone records (which+ * would make a long clip read as no time at all) is refused too.+ */+export function wavDurationMs(audio: Buffer): number | null {+ if (audio.length < WAV_HEADER_BYTES) return null+ if (audio.toString('ascii', 0, 4) !== 'RIFF' || audio.toString('ascii', 8, 12) !== 'WAVE' || audio.toString('ascii', 12, 16) !== 'fmt ') return null+ if (audio.readUInt16LE(20) !== WAVE_FORMAT_PCM) return null+ const channels = audio.readUInt16LE(22)+ const sampleRate = audio.readUInt32LE(24)+ const bits = audio.readUInt16LE(34)+ if (channels < 1 || channels > 2 || sampleRate < 8_000 || sampleRate > 48_000 || ![8, 16, 24, 32].includes(bits)) return null+ const bytesPerSecond = sampleRate * channels * (bits / 8)+ return Math.ceil(((audio.length - WAV_HEADER_BYTES) / bytesPerSecond) * 1000)+}++function dailyLimitMessage(err: VoiceQuotaExceededError): string {+ const minutes = Math.round(err.snapshot.limitSeconds / 60)+ return `You've used today's voice limit (${minutes} minutes a day). It resets at midnight UTC.`+}+/** The language the dial stated. Unknown values fall back rather than failing: a transcript in the wrong* language is recoverable by the person; a 400 in the middle of a spoken turn is not. */function pickLang(value: unknown): string {@@ -39,7 +86,33 @@ export async function voiceRoutes(app: FastifyInstance): Promise<void> {// nothing else, so no other endpoint's body handling changes by adding it.await app.register(multipart, { limits: { fileSize: MAX_AUDIO_BYTES, files: 1 } })+ // Per plugin instance, so each app (and each test) counts from zero in this process when Redis is absent.+ const perMinute = createRateLimiter('voice-stt', MINUTE_MS, PER_MINUTE)+app.post(VOICE_STT_PATH, async (req, reply) => {+ const userId = req.user?.sub ?? ''+ if (!(await perMinute.allows(userId))) {+ sendError(reply, 'Too many voice clips in a minute. Wait a moment and try again.', 'RATE_LIMITED', 429)+ return+ }++ // The whole request is an upper bound on the clip it carries: Node reads no more than Content-Length,+ // and a request without one (chunked) is held to the most this route accepts.+ const declared = Number(req.headers['content-length'])+ const held = Number.isFinite(declared) && declared > 0 ? Math.min(declared, MAX_AUDIO_BYTES + 64 * 1024) : MAX_AUDIO_BYTES+ if (!reserveVoice(held)) {+ logger.warn('voice-stt: voice memory budget full', { user: userId, bytes: held })+ sendError(reply, 'Voice is busy right now. Try again in a moment.', 'VOICE_BUSY', 503)+ return+ }+ try {+ await transcribe(req, reply, userId)+ } finally {+ releaseVoice(held)+ }+ })++ async function transcribe(req: FastifyRequest, reply: FastifyReply, userId: string): Promise<void> {let filetry {file = await req.file()@@ -52,31 +125,65 @@ export async function voiceRoutes(app: FastifyInstance): Promise<void> {return}- const audio = await file.toBuffer()+ let audio: Buffer+ try {+ audio = await file.toBuffer()+ } catch {+ sendError(reply, 'That recording is too long to transcribe', 'PAYLOAD_TOO_LARGE', 413)+ return+ }if (audio.length === 0) {sendError(reply, 'Empty audio file', 'BAD_REQUEST', 400)return}+ const durationMs = wavDurationMs(audio)+ if (durationMs === null) {+ sendError(reply, 'Voice recordings must be uncompressed WAV audio', 'UNSUPPORTED_AUDIO', 415)+ return+ }++ const uploadId = `stt-${randomUUID()}`+ try {+ await voiceQuotaService.reserveForUser(userId, req.user?.autonomousEnv ?? 'prod', uploadId, durationMs)+ } catch (err) {+ if (err instanceof VoiceQuotaExceededError) {+ sendError(reply, dailyLimitMessage(err), err.code, 429, {+ limitSeconds: err.snapshot.limitSeconds,+ resetAt: err.snapshot.resetAt,+ })+ return+ }+ logger.error('voice-stt: daily voice quota unavailable', { user: userId, error: err instanceof Error ? err.message : String(err) })+ sendError(reply, 'Voice is unavailable right now. Try again in a moment.', 'VOICE_QUOTA_UNAVAILABLE', 503)+ return+ }+const lang = pickLang((req.query as { lang?: unknown } | undefined)?.lang)try {- const transcript = await transcribeWavWithDeepgram(audio, file.mimetype || 'audio/wav', lang)+ // Always WAV: the bytes were checked as PCM WAV above, so the caller's own type never chooses a decoder.+ const transcript = await transcribeWavWithDeepgram(audio, 'audio/wav', lang)+ await voiceQuotaService.commit(uploadId).catch((err) => {+ // Left pending, the cleanup worker would hand these seconds back: logged, never silent.+ logger.error('voice-stt: quota commit failed', { user: userId, error: err instanceof Error ? err.message : String(err) })+ })// The user is logged, the words are not. A transcript is the most private thing this service sees,// and the useful diagnostics — did it arrive, how big, what language, did it come back empty — do// not require keeping it.logger.info('voice-stt', {- user: req.user?.sub,+ user: userId,bytes: audio.length,lang,chars: transcript.length,})sendSuccess(reply, { transcript, lang })} catch (err) {+ await voiceQuotaService.release(uploadId).catch(() => { /* the cleanup worker releases a stale pending one */ })logger.error('voice-stt failed', {- user: req.user?.sub,+ user: userId,error: err instanceof Error ? err.message : String(err),})sendError(reply, 'Transcription failed', 'STT_FAILED', 502)}- })+ }}diff --git a/backend/src/superTabs/attachments.test.ts b/backend/src/superTabs/attachments.test.tsindex a04f97820..685209234 100644--- a/backend/src/superTabs/attachments.test.ts+++ b/backend/src/superTabs/attachments.test.ts@@ -1,7 +1,8 @@import { generateKeyPairSync } from 'node:crypto'import { describe, expect, it } from 'vitest'import { Readable } from 'node:stream'-import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, directUploads, imageTypeOf, GcsAttachmentStore, GcsAvatarStore, MAX_ATTACHMENT_BYTES, MAX_FORM_ATTACHMENT_BYTES, MemoryAttachmentStore, objectKeyFor, served, serviceAccountFrom, typeFromHead, UPLOAD_LINK_MS } from './attachments.js'+import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, directUploads, imageTypeOf, GcsAttachmentStore, GcsAvatarStore, MAX_ATTACHMENT_BYTES, MAX_FORM_ATTACHMENT_BYTES, MemoryAttachmentStore,+ MemoryAvatarStore, objectKeyFor, served, serviceAccountFrom, SharedAvatarStore, typeFromHead, UPLOAD_LINK_MS, type AttachmentStore } from './attachments.js'const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })const key = { type: 'service_account', project_id: 'harness-test', client_email: '[email protected]',@@ -184,6 +185,18 @@ describe('attachment files', () => {await expect(store.put('k2', { name: 'b.bin', mime: 'application/octet-stream' }, Readable.from([Buffer.alloc(6)]), 5)).rejects.toBeInstanceOf(AttachmentTooLarge)expect(store.objects.has('k2')).toBe(false)})+ it('deletes an object, and counts one already gone as deleted, in each store', async () => {+ const shared = new MemoryAttachmentStore(), pictures = new MemoryAvatarStore('https://avatars.example.test')+ const stores: Array<[AttachmentStore, MemoryAttachmentStore]> = [[shared, shared], [pictures, pictures],+ [new SharedAvatarStore(shared), shared]]+ for (const [store, bucket] of stores) {+ await store.put('avatars/k', { name: 'a.txt', mime: 'text/plain' }, Readable.from([Buffer.from('a')]), 5)+ await store.put('avatars/other', { name: 'b.txt', mime: 'text/plain' }, Readable.from([Buffer.from('b')]), 5)+ await store.delete('avatars/k')+ expect([bucket.objects.has('avatars/k'), bucket.objects.has('avatars/other')]).toEqual([false, true])+ await expect(store.delete('avatars/k')).resolves.toBeUndefined()+ }+ })})describe('upload links on the memory bucket, with storage\'s rules', () => {diff --git a/backend/src/superTabs/attachments.ts b/backend/src/superTabs/attachments.tsindex 23a13cc82..a41ecf0e7 100644--- a/backend/src/superTabs/attachments.ts+++ b/backend/src/superTabs/attachments.ts@@ -38,6 +38,11 @@ export const MAX_AVATAR_BYTES = 1024 * 1024export const AVATAR_TYPES: ReadonlySet<string> = new Set(['image/png', 'image/jpeg', 'image/webp'])/** The `purpose` of an avatar upload (schema.prisma SuperTabAttachment): never sendable as a chat file. */export const AVATAR_PURPOSE = 'avatar'+/** How long an upload may wait to be sent. */+export const UNSENT_LIFE_MS = 24 * 3_600_000+/** `usedBy` of an upload the expiry sweep took (lib/attachmentSweep.ts): its file is being removed and nothing may use it.+ * Message and receipt ids are 24 hex characters (model.ts stableId), so the colon keeps it from ever matching one. */+export const EXPIRED_UPLOAD = 'expired:unsent'// Control, format (bidi overrides, zero-width) and line/paragraph separators: a name that hides its real shape.export const attachmentName = z.string().trim().min(1).max(255).refine(value => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value), 'Use a printable file name.')@@ -87,6 +92,8 @@ export interface AttachmentStore {/** A link that opens [objectKey] until [expiresAt] (epoch ms) and never after, whether or not the bucket is public. Storage* checks it when a request starts, so a long download that started in time finishes. */signedUrl(objectKey: string, expiresAt: number): Promise<string>+ /** Removes the object. One that is already gone counts as removed. */+ delete(objectKey: string): Promise<void>}/** Where avatars are kept, and the link a member read carries for one (avatarLinks.ts). */export interface AvatarStore extends AttachmentStore {}@@ -246,6 +253,7 @@ export class SharedAvatarStore implements AvatarStore {constructor(readonly store: AttachmentStore) {}put(objectKey: string, file: { name: string; mime: string }, body: Readable, cap: number) { return this.store.put(objectKey, file, body, cap) }signedUrl(objectKey: string, expiresAt: number) { return this.store.signedUrl(objectKey, expiresAt) }+ delete(objectKey: string) { return this.store.delete(objectKey) }}export class MemoryAttachmentStore implements AttachmentStore, DirectUploads {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 92a38239c..df0624c41 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -146,6 +146,8 @@ export const commandSchema = z.discriminatedUnion('type', [unlessRemoved: z.literal(true).optional() }).strict(),z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),z.object({ type: z.literal('machine.engineResume'), machineId: id, engine: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), askedIn: askedInSchema.optional() }).strict(),+ // The projects that may use a machine; null: every project (Tony, 11-03).+ z.object({ type: z.literal('machine.projects'), machineId: id, projectIds: z.array(id).min(1).max(64).nullable(), askedIn: askedInSchema.optional() }).strict(),z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),z.object({ type: z.literal('machine.cleaned'), machineId: id, removalId: id }).strict(),z.object({ type: z.literal('localModels.set'), enabled: z.boolean() }).strict(),@@ -622,7 +624,7 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, commaif ('agentId' in command) readAgent(state, actor, command.agentId)if (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'- || command.type === 'machine.engineResume') && command.askedIn) {+ || command.type === 'machine.engineResume' || command.type === 'machine.projects') && command.askedIn) {readConversation(state, actor, command.askedIn.conversationId)}if ('startId' in command && command.type !== 'route.modelResult') {@@ -832,6 +834,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userIdconst sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username')authorizeCommandAccess(state, actor, command, context)+ /** A machine's owner said so: they sent the command, or the Lead of the chat [askedIn] names passes on a message they wrote+ * there in the last day, as routing rules are (machine.engineResume, machine.projects). */+ const machineOwnerWord = (pool: ContributedMachine, askedIn: { conversationId: string } | undefined) => {+ if (actor.kind === 'person') return actor.userId === pool.contributorId+ const asked = askedIn && context.askedIn+ return !!asked && asked.author.kind === 'person' && asked.author.id === pool.contributorId && !asked.source+ && context.now - asked.createdAt <= RULE_MESSAGE_MS && state.conversations.find(c => c.id === askedIn.conversationId)?.leadId === actor.agentId+ }const rememberAttempt = (group: ReturnType<typeof conversation>) => {if (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,brief: group.brief, checks: group.checks, assignment: group.assignment }))@@ -1117,7 +1127,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const projectId = command.sessionProjectId ?? context.reply?.sessionProjectconst project = swarm ? projectId ? readProject(state, actor, projectId) : undefined : groupProject(state, chat)const me = person(state, owner.id)- const folder = project ? { cwd: projectFolder(pool, project), worktree: true, ...(swarm ? { buddyNarrow: true as const } : {}) }+ // A session of one project never reads beyond its folder, in either chat (task #2356: one in an older project chat ran+ // wide, so it read its person's whole home, other projects' clones included, while that chat's own Buddy was narrow).+ const folder = project ? { cwd: projectFolder(pool, project), worktree: true, buddyNarrow: true as const }: { cwd: buddyHomeFolder(pool, me), worktree: false, buddyScope: 'swarm' as const, buddyProjects: buddyProjectsOn(state, pool, me) }const request: AgentStartRequest = { conversationId: chat.id, machineId: main.machineId, engine: main.configuration.engine,...(main.configuration.model ? { model: main.configuration.model } : {}), ...(main.configuration.effort ? { effort: main.configuration.effort } : {}),@@ -1547,6 +1559,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (start.request.buddySession?.projectId === project.id && !start.harnessId && !start.error) start.error = 'Its project was deleted.'}deleteProject(state, actor, command.projectId)+ // No machine keeps it any more; one kept only for it now serves none (machines.ts machineProjectRefusal).+ for (const pool of state.machines ?? []) if (pool.projects) pool.projects = pool.projects.filter(id => id !== project.id)break}case 'project.sharing': {@@ -1711,6 +1725,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// Added as its person joined (Desktop's join): teammates' work only through its Harness Team account, for as long as// it stays contributed. Saving its settings sends the contribution without the field, and must not drop the rule.const teamAccountOnly = command.teamAccountOnly || state.machines.find(m => m.machineId === command.machineId)?.teamAccountOnly+ // Its owner's choice of projects is its own command's (machine.projects): saving the settings keeps it.+ const projects = state.machines.find(m => m.machineId === command.machineId && !m.buddyOnly)?.projectsstate.machines = state.machines.filter(m => m.machineId !== command.machineId)state.machineCleanups = state.machineCleanups?.filter(c => c.machineId !== command.machineId)if (!state.machineCleanups?.length) delete state.machineCleanups@@ -1718,7 +1734,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,state.machines.push({ machineId: command.machineId, name: mac?.name ?? context.contribution?.machineName ?? command.name, cwd: command.cwd, engines: [...new Set(command.engines)],maxAgents: mac?.maxAgents ?? command.maxAgents, ...(command.scope ? { scope: command.scope } : {}),contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused,- ...(host ? { hostMachineId: host } : {}), ...(teamAccountOnly ? { teamAccountOnly: true as const } : {}) })+ ...(host ? { hostMachineId: host } : {}), ...(teamAccountOnly ? { teamAccountOnly: true as const } : {}), ...(projects && !host ? { projects } : {}) })// A Mac given other slots or a new name gives its team account the same, and its pause; its own folder, engines and grant stay.const added = state.machines.at(-1)!for (const team of teamPoolsOf(state, added)) if (!team.removal) Object.assign(team, { name: added.name, maxAgents: added.maxAgents, paused: added.paused })@@ -1737,16 +1753,27 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// A suspended engine (engineHealth.ts) is offered again at its owner's word: theirs, or a Lead's passing on a chat// message they wrote in the last day, as routing rules are. No new button: the only visible change is the struck name.const pool = machineContribution(state, command.machineId) ?? fail('NOT_FOUND', 'This machine has not been contributed.', 404)- const asked = actor.kind === 'agent' && command.askedIn && context.askedIn- const ownerAsked = !!asked && asked.author.kind === 'person' && asked.author.id === pool.contributorId && !asked.source- && context.now - asked.createdAt <= RULE_MESSAGE_MS && !!state.conversations.find(c => c.id === command.askedIn!.conversationId)?.leadId- && state.conversations.find(c => c.id === command.askedIn!.conversationId)!.leadId === actor.agentId- if (!(actor.kind === 'person' && actor.userId === pool.contributorId) && !ownerAsked) {+ if (!machineOwnerWord(pool, command.askedIn)) {fail('OWNER_REQUIRED', "Only the machine's owner, or the Lead passing on a chat message the owner wrote in the last day, resumes an engine there.", 403)}resumeEngine(pool, command.engine)break}+ case 'machine.projects': {+ // Which projects may run agents here (Tony, 11-03): its owner's choice, or a Lead's passing on their chat message. A Mac's+ // Harness Team account follows its Mac (machines.ts machineProjectRefusal), so it is set on the Mac.+ const pool = machineContribution(state, command.machineId) ?? fail('NOT_FOUND', 'This machine has not been contributed.', 404)+ if (pool.hostMachineId || pool.buddyOnly) fail('NOT_FOUND', 'This machine has not been contributed.', 404)+ if (!machineOwnerWord(pool, command.askedIn)) {+ fail('OWNER_REQUIRED', "Only the machine's owner, or the Lead passing on a chat message the owner wrote in the last day, chooses its projects.", 403)+ }+ if (command.projectIds === null) { delete pool.projects; break }+ // Only projects its owner may read: they cannot keep a machine for a project they do not see.+ const keeper = person(state, pool.contributorId)+ const asOwner: Actor = { kind: 'person', userId: keeper.id, email: keeper.email }+ pool.projects = [...new Set(command.projectIds)].map(projectId => readProject(state, asOwner, projectId).id)+ break+ }case 'machine.remove': {// Its owner takes the machine out with every Swarm agent on it, each removed like one agent (its host closes the// session; a Product Manager refuses it, protectLead). A contributed machine then stays listed, paused, while itsdiff --git a/backend/src/superTabs/machineProjects.test.ts b/backend/src/superTabs/machineProjects.test.tsnew file mode 100644index 000000000..61fb76dfa--- /dev/null+++ b/backend/src/superTabs/machineProjects.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'+import { admitMachineStart, type ContributedMachine } from './machines.js'+import { createSuperTab, SuperTabError, visibleState, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'++// Task #2390 (Tony, 11-03): a machine's owner chooses which of the Swarm's projects may run agents on it. Default all, as+// before; only its owner sets it, or the Lead passing on the owner's own chat message (as machine.engineResume).+const NOW = 50_000_000+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const tony: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'tony', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,+ deviceType: null, chip: null, os: null, gpuPercent: null }+const reading = (): NonNullable<ContributedMachine['observation']> => ({ generation: 'g1', receivedAt: NOW, sessionKind: 'computer', resources, tools: {},+ quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] })+const refusal = (body: () => unknown): SuperTabError | null => {+ try { body(); return null } catch (error) { if (error instanceof SuperTabError) return error; throw error }+}++/** The owner's Swarm ('lead' is its first project, "Pilot"), with Tony's MacBook and the owner's Mac contributed for every+ * project, and the owner's other projects: lampos (public) and secret (private, Tony not a member). */+function swarm() {+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')+ let sequence = 0+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, teamMachines: [], ...context })+ state = effects.state+ return effects+ }+ const invited = run({ type: 'invite.create', email: tony.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, tony)+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation+ const pool = (machineId: string, contributorId: string, name: string, extra: Partial<ContributedMachine> = {}): ContributedMachine => ({ machineId, name,+ contributorId, membershipGeneration: generation(contributorId), generation: 'g1', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4,+ paused: false, observation: reading(), ...extra })+ state.machines = [pool('tony-mac', 'tony', 'MacBook Pro'), pool('owner-mac', 'owner', 'Owner Mac')]+ const lampos = String(run({ type: 'project.create', name: 'lampos', visibility: 'public', brief: '' }).result.projectId)+ const secret = String(run({ type: 'project.create', name: 'secret', visibility: 'private', brief: '' }).result.projectId)+ const lead = String(run({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: 'lead', name: 'Lead', configuration: config, lead: true },+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId)+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'owner' }+ const machine = (machineId: string) => state.machines!.find(m => m.machineId === machineId)!+ const limit = (projectIds: string[] | null, machineId = 'tony-mac', actor: Actor = tony, context: Partial<CommandContext> = {}, extra: Record<string, unknown> = {}) =>+ run({ type: 'machine.projects', machineId, projectIds, ...extra } as Command, actor, context)+ const group = (projectId: string) => String(run({ type: 'conversation.create', projectId, title: 'Work', brief: 'Build it.', checks: [] }).result.conversationId)+ const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }+ const request = (conversationId: string, machineId: string, projectId: string) =>+ ({ conversationId, machineId, engine: 'codex', name: 'Builder', cwd: `/swarm/${projectId}`, worktree: true, requirements })+ const start = (conversationId: string, machineId: string, projectId: string) => run({ type: 'agent.start', request: request(conversationId, machineId, projectId) },+ owner, { contribution: { machineOwnerId: machine(machineId).contributorId, contributorId: machine(machineId).contributorId, hostGrant: null } })+ /** An agent already in the Swarm on [machineId], of [projectId]. */+ const member = (id: string, machineId: string, projectId: string) => {+ const contributorId = machine(machineId).contributorId+ state.agents.push({ id, machineId, harnessId: `harness-${id}`, projectId, machineOwnerId: contributorId, contributorId,+ membershipGeneration: generation(contributorId), hostGrant: null, name: id, configuration: config })+ return id+ }+ return { run, machine, limit, lampos, secret, leadActor, pool, group, request, start, member, get state() { return state } }+}++describe('a machine\'s projects', () => {+ it('serves every project until its owner limits it, and every project again when they choose All', () => {+ const f = swarm()+ expect(f.machine('tony-mac').projects).toBeUndefined()+ f.limit(['lead'])+ expect(f.machine('tony-mac').projects).toEqual(['lead'])+ f.limit(['lead', f.lampos, 'lead'])+ expect(f.machine('tony-mac').projects).toEqual(['lead', f.lampos])+ f.limit(null)+ expect(f.machine('tony-mac').projects).toBeUndefined()+ })++ it('is changed by nobody but the machine\'s owner: not the Swarm owner, nor a Lead on its own word', () => {+ const f = swarm()+ expect(refusal(() => f.limit(['lead'], 'tony-mac', owner))?.code).toBe('OWNER_REQUIRED')+ expect(refusal(() => f.limit(['lead'], 'tony-mac', f.leadActor))?.code).toBe('OWNER_REQUIRED')+ expect(f.machine('tony-mac').projects).toBeUndefined()+ })++ it('is set by the Lead passing on the owner\'s own chat message from the last day, and not on anyone else\'s', () => {+ const f = swarm()+ const askedIn = { conversationId: 'lead', messageId: 'm-tony' }+ const said = (id: string, createdAt = NOW - 1000) => ({ askedIn: { author: { kind: 'person', id } as never, source: false, createdAt } })+ expect(refusal(() => f.limit(['lead'], 'tony-mac', f.leadActor, said('owner'), { askedIn }))?.code).toBe('OWNER_REQUIRED')+ expect(refusal(() => f.limit(['lead'], 'tony-mac', f.leadActor, said('tony', NOW - 2 * 24 * 60 * 60_000), { askedIn }))?.code).toBe('OWNER_REQUIRED')+ f.limit(['lead'], 'tony-mac', f.leadActor, said('tony'), { askedIn })+ expect(f.machine('tony-mac').projects).toEqual(['lead'])+ })++ it('names only projects of this Swarm its owner may read, at least one', () => {+ const f = swarm()+ expect(refusal(() => f.limit(['no-such-project']))?.code).toBe('NOT_FOUND')+ // Tony is no member of the private project: he cannot keep his machine for it.+ expect(refusal(() => f.limit([f.secret]))?.code).toBe('NOT_FOUND')+ expect(commandSchema.safeParse({ type: 'machine.projects', machineId: 'tony-mac', projectIds: [] }).success).toBe(false)+ f.limit([f.secret], 'owner-mac', owner)+ expect(f.machine('owner-mac').projects).toEqual([f.secret])+ })++ it('stays when the machine\'s settings are saved again', () => {+ const f = swarm()+ f.limit(['lead'])+ f.run({ type: 'machine.contribute', machineId: 'tony-mac', name: 'MacBook Pro', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 6 }, tony,+ { contribution: { machineOwnerId: 'tony', contributorId: 'tony', hostGrant: null } })+ expect(f.machine('tony-mac')).toMatchObject({ maxAgents: 6, projects: ['lead'] })+ })++ it('loses a project that is deleted', () => {+ const f = swarm()+ f.limit(['lead', f.lampos])+ f.run({ type: 'project.delete', projectId: f.lampos })+ expect(f.machine('tony-mac').projects).toEqual(['lead'])+ })++ it('shows each reader only the projects they may read', () => {+ const f = swarm()+ f.limit(['lead', f.secret], 'owner-mac', owner)+ const seen = (actor: Actor) => visibleState(f.state, actor, NOW).machines!.find(m => m.machineId === 'owner-mac')!.projects+ expect(seen(owner)).toEqual(['lead', f.secret])+ expect(seen(tony)).toEqual(['lead'])+ })+})++describe('a machine kept for some projects', () => {+ const candidate = (id: string, machineId: string, patch: Record<string, unknown> = {}) => ({ id, kind: 'new', machineId, engine: 'codex',+ model: 'default', effort: 'default', quality: 3, cost: 2, title: `${id} on ${machineId}`, label: `Label ${id}`, ...patch })+ const record = (candidates: unknown[], pick = 'c0') => ({ assessment: { difficulty: 'medium', risk: 'low', why: 'A small change.' },+ candidates, excluded: [], floor: 2, notes: false, pick, via: 'order', p: null, belowFloor: false, why: 'Policy order.' })++ it('refuses a start for another project, and takes one for its own', () => {+ const f = swarm()+ f.limit(['lead'])+ expect(refusal(() => f.start(f.group(f.lampos), 'tony-mac', f.lampos))).toMatchObject({ code: 'MACHINE_PROJECTS', message: 'MacBook Pro runs only Pilot.' })+ expect(f.start(f.group('lead'), 'tony-mac', 'lead').result.startId).toBeTruthy()+ })++ it('refuses another project\'s Product Manager there', () => {+ const f = swarm()+ f.limit(['lead'])+ const chat = f.state.projects!.find(p => p.id === f.lampos)!.leadConversationId+ expect(refusal(() => admitMachineStart(f.state, { ...f.request(chat, 'tony-mac', f.lampos), leadFor: { projectId: f.lampos, personId: 'owner', generation: 'g' } }, NOW))+ ?.code).toBe('MACHINE_PROJECTS')+ })++ it('gives an agent there no task of another project, and lets none join one, while it keeps its own', () => {+ const f = swarm()+ const there = f.member('there', 'tony-mac', f.lampos)+ f.limit(['lead'])+ const work = f.group(f.lampos)+ expect(refusal(() => f.run({ type: 'work.assign', conversationId: work, agentId: there }))?.code).toBe('MACHINE_PROJECTS')+ expect(refusal(() => f.run({ type: 'conversation.agent', conversationId: work, agentId: there, present: true, lead: false }))?.code).toBe('MACHINE_PROJECTS')+ // Not removed: it stays listed, as an agent whose machine stopped taking teammates' work does.+ expect(f.state.agents.some(a => a.id === there)).toBe(true)+ const ours = f.member('ours', 'tony-mac', 'lead'), own = f.group('lead')+ f.run({ type: 'work.assign', conversationId: own, agentId: ours })+ expect(f.state.conversations.find(c => c.id === own)!.assignment).toMatchObject({ agentId: ours })+ })++ it('is left out of another project\'s route, saying why, and refused as its pick', () => {+ const f = swarm()+ f.limit(['lead'])+ const work = f.group(f.lampos)+ const effects = f.run({ type: 'route.record', conversationId: work, decision: record([candidate('c0', 'owner-mac'), candidate('c1', 'tony-mac')]) } as Command)+ expect(effects.routeDecisions[0]).toMatchObject({ op: 'create', record: { candidates: [{ id: 'c0' }],+ excluded: [{ title: 'c1 on tony-mac', reason: 'MacBook Pro runs only Pilot.' }] } })+ expect(refusal(() => f.run({ type: 'route.record', conversationId: f.group(f.lampos), decision: record([candidate('c0', 'tony-mac')]) } as Command))).toMatchObject({ code: 'MACHINE_PROJECTS', message: 'MacBook Pro runs only Pilot. Route again.' })+ })++ it('holds for its Mac\'s Harness Team account too', () => {+ const f = swarm()+ f.state.machines!.push(f.pool('tony-team', 'tony', 'MacBook Pro · Team', { hostMachineId: 'tony-mac',+ observation: { ...f.machine('tony-mac').observation!, sessionKind: 'team', privacy: { mode: 'dedicated', seenAt: NOW } } }))+ f.limit(['lead'])+ const theirs = f.group(f.lampos), ours = f.group('lead')+ expect(refusal(() => admitMachineStart(f.state, f.request(theirs, 'tony-team', f.lampos), NOW, undefined, ['tony-team']))?.code).toBe('MACHINE_PROJECTS')+ expect(admitMachineStart(f.state, f.request(ours, 'tony-team', 'lead'), NOW, undefined, ['tony-team'])?.machineId).toBe('tony-team')+ // It is set on the Mac, never on its account.+ expect(refusal(() => f.limit(['lead'], 'tony-team'))?.code).toBe('NOT_FOUND')+ })++ it('counts a private project it is kept for, never naming it', () => {+ const f = swarm()+ f.limit(['lead', f.secret], 'owner-mac', owner)+ expect(refusal(() => f.start(f.group(f.lampos), 'owner-mac', f.lampos))?.message).toBe('Owner Mac runs only Pilot and 1 other project.')+ f.limit([f.secret], 'owner-mac', owner)+ expect(refusal(() => f.start(f.group(f.lampos), 'owner-mac', f.lampos))?.message).toBe('Owner Mac runs only 1 other project.')+ })++ it('kept only for a deleted project, takes no project\'s work, and says so', () => {+ const f = swarm()+ f.limit([f.lampos])+ f.run({ type: 'project.delete', projectId: f.lampos })+ expect(refusal(() => f.start(f.group('lead'), 'tony-mac', 'lead'))?.message).toBe('MacBook Pro runs no project now: its owner can choose its projects again.')+ })++ it('with no list, takes every project\'s work as before', () => {+ const f = swarm()+ expect(f.start(f.group(f.lampos), 'tony-mac', f.lampos).result.startId).toBeTruthy()+ expect(f.start(f.group('lead'), 'tony-mac', 'lead').result.startId).toBeTruthy()+ })+})diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 3bbc5bd87..590aa5305 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -48,6 +48,9 @@ export interface ContributedMachine {lent?: import('./leaderboard/lent.js').LentWeek[]/** The same by day, for the board's rolling periods. Only the leaderboard read gets it (model.ts visibleState). */lentDays?: import('./leaderboard/lent.js').LentDay[]+ /** The projects whose agents may run here, set by its owner (commands.ts machine.projects, Tony 11-03); absent: every+ * project, as before. A Mac's Harness Team account keeps none of its own: it follows its Mac's (machineProjectRefusal). */+ projects?: string[]/** Per engine, its failed starts here in a row, until one runs or they suspend it (engineHealth.ts). */engineFailures?: Record<string, number>/** Per engine, a suspension after failed starts: when, and whether its reading already said signed in with quota then. */@@ -261,7 +264,7 @@ export function observedPrivacy(previous: StoredPrivacy | undefined, reported: M}export type TeamWorkCode = 'TEAM_WRITTEN_WORK' | 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'- | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE'+ | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS'export interface TeamWorkRefusal { code: TeamWorkCode; reason: string }/** Refusals that hold until a person acts on the machine; a stale check or an offline machine may pass again by itself. */export const LASTING_TEAM_REFUSALS: readonly string[] = ['TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED', 'MACHINE_IN_OTHER_WORKSPACE']@@ -333,6 +336,9 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =*/export function teamWorkCheck(state: SuperTabState, machineId: string, contributorId: string, project: SwarmProject, now: number,teamMachines: readonly string[] = [], otherWorkspaceMachines: readonly string[] = []): TeamWorkRefusal | null {+ // Its owner kept it for other projects (machine.projects): whoever's project and grant it is.+ const kept = machineProjectRefusal(state, machineId, project)+ if (kept) return keptconst pool = state.machines?.find(m => m.machineId === machineId)// A Buddy-only machine is its person's alone: an agent they added there takes their own projects' work and no other's,// whatever the Team account switches say (security re-check 1 of #2234). New starts there are refused in admitMachineStart.@@ -346,6 +352,24 @@ export function teamWorkCheck(state: SuperTabState, machineId: string, contributreturn teamWorkRefusal(pool, now, teamMachines.includes(machineId), teamAccountRequired(), otherWorkspaceMachines.includes(machineId))}+/**+ * Why [machineId] takes no work of [project]: its owner kept it for other projects (commands.ts machine.projects, Tony+ * 11-03), or null. A Mac's Harness Team account follows its Mac's list. The sentence names only projects every member may+ * read and counts the rest, since it reaches the readers of [project] (a route's exclusions, a refused start).+ */+export function machineProjectRefusal(state: SuperTabState, machineId: string, project: SwarmProject): TeamWorkRefusal | null {+ const pool = state.machines?.find(m => m.machineId === machineId)+ const mac = pool?.hostMachineId ? state.machines?.find(m => m.machineId === pool.hostMachineId && m.contributorId === pool.contributorId) ?? pool : pool+ const listed = mac?.projects+ if (!mac || !listed || listed.includes(project.id)) return null+ const kept = projectsOf(state).filter(p => listed.includes(p.id))+ if (!kept.length) return { code: 'MACHINE_PROJECTS', reason: `${mac.name} runs no project now: its owner can choose its projects again.` }+ const named = kept.filter(p => p.visibility === 'public').map(p => p.name), others = kept.length - named.length+ const parts = [...named, ...(others ? [`${others} other project${others > 1 ? 's' : ''}`] : [])]+ const list = parts.length > 1 ? `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}` : parts[0]+ return { code: 'MACHINE_PROJECTS', reason: `${mac.name} runs only ${list}.` }+}+// ── One machine: a Mac and its Harness Team account ─────────────────────────────────────────────────────────────────// The team account is how a Mac runs teammates' work without its owner's files, not a machine of its own to anyone: a// Lead names the Mac, and the work for another person's project lands in the Mac's team account.@@ -726,6 +750,9 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartRequeconst project = forProject ?? (!isSwarmBuddyChat(group!) ? groupProject(state, group!): request.buddySession?.projectId ? projectOf(state, request.buddySession.projectId) : undefined)if (project && !pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')+ // Kept by its owner for other projects: a Product Manager too. A Buddy is its owner's own (commands.ts buddy.create).+ const kept = project && !request.buddyOf ? machineProjectRefusal(state, pool.machineId, project) : null+ if (kept) failTeamWork(kept)const held = teamAccountPool(pool) ? productManagerOn(state, pool.machineId) : nullif (held && held !== project?.id) {fail('TEAM_ACCOUNT_HELD', `The Harness Team account on ${pool.name} runs another project's Product Manager, so it takes only that project's work for now.`, 403)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex be2e025eb..9eee71c46 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -835,6 +835,11 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(else delete visible.removedMachines// Rows by day and project that only the leaderboard read uses, and it takes them from the Swarm itself.for (const pool of visible.machines ?? []) delete pool.lentDays+ // A machine kept for some projects names to each reader only those they may read (machines.ts projects): a private+ // project's id is not another member's to see.+ for (const pool of visible.machines ?? []) {+ if (pool.projects) pool.projects = pool.projects.filter(id => projectsOf(state).some(p => p.id === id && canReadProject(state, actor, p)))+ }// Nor its id, which a Buddy's row carries (machineHiddenFrom).visible.agents = visible.agents.map(a => machineHiddenFrom(state, actor, a) ? agentWithoutMachine(a) : a)// The removed Leads conversation reaches nobody (leadsRemoved), its id included.diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex c1e02625b..2e42f88c7 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -21,7 +21,7 @@ import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCEimport { deliveriesByMessage } from './read/pageDeliveries.js'import { restoreDelivery } from './deliveryCompaction.js'import { threadSummaries } from './threads.js'-import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,+import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, EXPIRED_UPLOAD, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'import { FileLinks } from './fileLinks.js'import { randomBytes } from 'node:crypto'@@ -649,7 +649,7 @@ export class SuperTabStore {if (target && target.machineId !== team && !onTeamAccount(state, target)) refuse(target)}switch (command.type) {- case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.engineResume': return refuse()+ case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.engineResume': case 'machine.projects': return refuse()case 'machine.cleaned': case 'tab.project': case 'agent.add':if (command.machineId !== team) refuse()return@@ -1543,7 +1543,7 @@ export class SuperTabStore {}if (command.type === 'note.add' || command.type === 'note.remove') context.notes = await readNotes(tx, tabId, command.projectId)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'- || command.type === 'machine.engineResume') && command.askedIn) {+ || command.type === 'machine.engineResume' || command.type === 'machine.projects') && command.askedIn) {const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }}@@ -2165,6 +2165,7 @@ export class SuperTabStore {if (!row || row.actorKey !== actorKey(actor) || row.conversationId !== command.conversationId || row.purpose) {fail('ATTACHMENT_UNAVAILABLE', 'Attach this file again before sending it.', 400)}+ if (row.usedBy === EXPIRED_UPLOAD) fail('ATTACHMENT_EXPIRED', 'This file was not sent within a day and was removed. Attach it again.', 410)if (row.usedBy) fail('ATTACHMENT_USED', 'This file was already sent. Attach it again to send it in another message.')return { id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, row.objectKey) }})@@ -2185,7 +2186,8 @@ export class SuperTabStore {const ids = [...new Set(command.attachmentIds)]const rows = await tx.superTabAttachment.findMany({ where: { tabId: state.id, id: { in: ids }, conversationId: command.conversationId } })const own = rows.filter(r => !r.purpose && r.actorKey === actorKey(actor) && !r.usedBy)- let handed = rows.filter(r => !r.purpose && r.actorKey === `person:${ownerId}` && !!r.usedBy)+ // A file the expiry sweep took (lib/attachmentSweep.ts) is being removed: it was never sent, so it was never handed.+ let handed = rows.filter(r => !r.purpose && r.actorKey === `person:${ownerId}` && !!r.usedBy && r.usedBy !== EXPIRED_UPLOAD)// A thread session reads its own thread alone, so it proposes only files its person sent there (spec: Guard): a file from// the main chat or another thread could be another project's.const thread = self.buddySession?.threaddiff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 74ac8cd8f..a0b51e3c6 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -34,6 +34,8 @@ import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRoimport { startReceiptSweep } from './lib/productUsageReceiptSweep.js'import { startPendingUploadSweep } from './lib/pendingUploadSweep.js'import { startSwarmPurge } from './superTabs/purge.js'+import { startAttachmentSweepFrom } from './lib/attachmentSweep.js'+import { attachmentsFromEnv } from './superTabs/attachments.js'import { startRoutingReflection } from './lib/routingReflection.js'import { logger } from './utils/logger.js'@@ -75,6 +77,7 @@ async function start(): Promise<void> {let stopReceiptSweep = (): void => {}let stopPendingUploads = (): void => {}let stopSwarmPurge = (): void => {}+ let stopAttachmentSweep = (): void => {}let stopReflection = (): void => {}const shutdown = (signal: string): void => {logger.info(`Received ${signal}, stopping backend worker...`)@@ -90,6 +93,7 @@ async function start(): Promise<void> {stopReceiptSweep()stopPendingUploads()stopSwarmPurge()+ stopAttachmentSweep()stopReflection()stopThreadBackfill()// The last partial minute, before the database closes.@@ -108,6 +112,9 @@ async function start(): Promise<void> {stopPendingUploads = startPendingUploadSweep(prisma, env)// Deleted Swarms past their 7 days go with their records and stored files (superTabs/purge.ts).stopSwarmPurge = startSwarmPurge(prisma, env)+ // Swarm uploads nobody sent within a day, row and stored file, once an hour (lib/attachmentSweep.ts). It logs whether it+ // is on; settings it cannot read turn off only the sweep.+ stopAttachmentSweep = startAttachmentSweepFrom(prisma, () => attachmentsFromEnv(env))// The worker's sweeps and archive write Swarms: they bump the stamps the API processes read by. It reads too little to keep a cache.configureSwarmStamps(redisSwarmStamps(), { reads: false })// Archive notes and Workspace removals write messages too: their recipients' hosts hear of them at once, and of thediff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 30d797693..6bd0340d2 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -5,7 +5,7 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts','integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',- 'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',+ 'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts','integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex e76c8815b..a551848d4 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -5322,6 +5322,68 @@ describe('swarm cards', () => {expect(await spoken(ROUND, [withBuddy({ local: 'h1' })], offline)).toEqual({ errors: ['Could not reach the Swarm. Try again.'], turns: [] })})+ // Swarm parity part 3 on top of part 1's review fix: a Pro's words follow its face chat only when its voice.begin says they+ // were spoken on the Lead view (`face`), which shows that chat. Its plain agent room names the same harness and shows none.+ describe('a Pro speaks to its face chat from the Lead view only', () => {+ const PRO_BUDDY = { ...BUDDY, board: 'pro' }+ const proSpoken = async (leads: SwarmLead[], agentId: string, face: boolean, swarmSay: CableHost['swarmSay']) => {+ const host = cardHost({ cards: [card('st1', leads)] }, { transcribe: vi.fn(async () => 'ship it'), route: vi.fn(), swarmSay })+ const { session, port } = await connect(host)+ try {+ port.say(PRO_BUDDY); await settle()+ port.say({ t: 'voice.begin', uploadId: `u-${agentId}`, agentId, ...(face ? { face: true } : {}) })+ port.pcm(Buffer.alloc(3200)); port.say({ t: 'voice.end' })+ await vi.waitFor(() => expect(port.sent.some((m) => m.t === 'voice.error' || m.t === 'voice.transcript') || vi.mocked(host.sendTurn).mock.calls.length > 0).toBe(true))+ await settle()+ return { errors: ofType(port, 'voice.error').map((m) => m.message), turns: vi.mocked(host.sendTurn).mock.calls }+ } finally { await session.stop() }+ }++ it('on the Buddy side, the words go to the Buddy chat, never the Lead conversation', async () => {+ const swarmSay = vi.fn(async (): Promise<SaidOnCard> => ({ said: true }))+ expect(await proSpoken([withBuddy({ local: 'h1' })], 'h1', true, swarmSay)).toEqual({ errors: [], turns: [] })+ expect(swarmSay.mock.calls).toEqual([['h1', 'ship it', 'buddy', 'pm1']])+ })++ it('on the PM side, the words go to the face chat it shows', async () => {+ const swarmSay = vi.fn(async (): Promise<SaidOnCard> => ({ said: true }))+ const leadFace = { kind: 'lead' as const, id: 'lead-c1', name: 'Lead', working: false }+ await proSpoken([withBuddy({ local: 'h1', sideChat: leadFace })], 'h1', true, swarmSay)+ expect(swarmSay.mock.calls).toEqual([['h1', 'ship it', 'buddy', 'lead-c1']])+ })++ it('to a remote Lead named by its Swarm id, the words go to its face chat', async () => {+ const remote = 'b'.repeat(24)+ const swarmSay = vi.fn(async (): Promise<SaidOnCard> => ({ said: true }))+ await proSpoken([withBuddy({ id: remote })], remote, true, swarmSay)+ expect(swarmSay.mock.calls).toEqual([[remote, 'ship it', 'buddy', 'pm1']])+ })++ it('a Buddy post that fails is a voice error, never the Lead\'s terminal', async () => {+ const offline = vi.fn(async (): Promise<SaidOnCard> => { throw new Error('offline') })+ expect(await proSpoken([withBuddy({ local: 'h1' })], 'h1', true, offline)).toEqual({ errors: ['Could not reach your Buddy. Try again.'], turns: [] })+ })++ it('without face (the plain agent room), the words stay in the Lead conversation as part 1 ruled', async () => {+ const swarmSay = vi.fn(async (): Promise<SaidOnCard> => ({ said: true }))+ await proSpoken([withBuddy({ local: 'h1' })], 'h1', false, swarmSay)+ expect(swarmSay.mock.calls).toEqual([['h1', 'ship it']])+ })++ it('a round dial ignores face and keeps its own rule', async () => {+ const swarmSay = vi.fn(async (): Promise<SaidOnCard> => ({ said: true }))+ const host = cardHost({ cards: [card('st1', [withBuddy({ local: 'h1' })])] }, { transcribe: vi.fn(async () => 'ship it'), route: vi.fn(), swarmSay })+ const { session, port } = await connect(host)+ try {+ port.say(BUDDY); await settle()+ port.say({ t: 'voice.begin', uploadId: 'u-h1', agentId: 'h1', face: true })+ port.pcm(Buffer.alloc(3200)); port.say({ t: 'voice.end' })+ await vi.waitFor(() => expect(swarmSay).toHaveBeenCalled())+ expect(swarmSay.mock.calls).toEqual([['h1', 'ship it', 'buddy', 'pm1']])+ } finally { await session.stop() }+ })+ })+it('a Buddy utterance never falls back after desktop focus changes during its post', async () => {const state = { cards: [card('st1', [withBuddy({ local: 'h1' })])] }let rejectPost!: (error: Error) => voiddiff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex b9775d0fe..595624520 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -1758,13 +1758,15 @@ export class CableSession {// start. Quoted text, carried text, questions and edits already have their own pinned targets.// Except words for a Swarm face's chat: the dial shows that chat, so a pane focused in the window never takes them.const plain = str('agentId') && !formVoice && !searchVoice && !draftVoice && !questionVoice && !carryVoice && !('selectionId' in msg)- const dialFace = plain ? this.voiceFaceOf(str('agentId')!) : undefined+ // A Pro says `face` when the words were spoken on its Lead view, which shows that chat (Swarm parity, part 3).+ const proFace = msg.face === true+ const dialFace = plain ? this.voiceFaceOf(str('agentId')!, proFace) : undefined// A Swarm Lead's id (the backend's 24 hex; a harness's is a UUID) with no card here yet (the devices process just// restarted) or any more: words for a Lead on another machine, which the focused pane must not take (review of #2232).const swarmId = plain && !dialFace && SWARM_AGENT_ID.test(str('agentId')!)const focused = plain && !dialFace && !swarmId ? this.host.appFocus?.() : undefinedconst agentId = focused?.agentId ?? str('agentId')- const swarmFace = dialFace ?? (agentId ? this.voiceFaceOf(agentId) : undefined)+ const swarmFace = dialFace ?? (agentId ? this.voiceFaceOf(agentId, proFace) : undefined)this.voice = {agentId,...(swarmFace ? { swarmFace } : {}),@@ -2799,10 +2801,12 @@ export class CableSession {* The chat words spoken to this Lead are posted in: its face chat, for a dial that names where words go. Never for a Pro:* it shows the face chat but no "Sending to", and its plain agent room shows no chat at all, so following the desktop's* open chat would post the person's words in a group or PM chat they cannot see they are talking to (review of #2298). Its- * words go to the Lead conversation, as before it said swarmChat, until voice comes to the Pro (Swarm parity, part 3).+ * words go to the Lead conversation, as before it said swarmChat, unless its voice.begin says `face`: spoken on its Lead+ * view, which shows the face chat and the PM | Buddy side (Swarm parity, part 3). Without it, a Buddy-side word would be+ * posted in the shared Lead chat.*/- private voiceFaceOf(harnessId: string): SwarmFace | undefined {- return this.seqOn ? undefined : this.swarmFaceOf(harnessId)+ private voiceFaceOf(harnessId: string, proFace: boolean): SwarmFace | undefined {+ return this.seqOn && !proFace ? undefined : this.swarmFaceOf(harnessId)}/** Whether `harnessId` is a Swarm Lead's harness on this machine. */@@ -2812,8 +2816,9 @@ export class CableSession {/** The extra arguments of words spoken to a Swarm Lead: the dial's chat flag, and the chat they were spoken to. */private sayArgs(face: SwarmFace | undefined): [chat?: CardChat, chatId?: string] {- // A chat flag with no id means "the chat open on the desktop" to the Swarm service: a Pro sends neither (voiceFaceOf).- if (this.seqOn) return []+ // A chat flag with no id means "the chat open on the desktop" to the Swarm service: a Pro sends neither unless its words+ // were for the face chat it showed (voiceFaceOf), and then names that chat.+ if (this.seqOn && !face) return []const [chat] = this.chatFlag()if (chat === undefined) return []return face ? [chat, face.id] : [chat]diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.tsindex dd8eada7b..9d9d97349 100644--- a/cli/src/lib/gitProject.spec.ts+++ b/cli/src/lib/gitProject.spec.ts@@ -7,8 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'import { placeholderBranch, sessionBranchNames, worktreeFolderName } from './agentNames.js'import { nameBranchAfterSession } from './branchNaming.js'-import { fetchDefaultBranch, harnessMadeWorktree, prepareGitProject, readGitProject, validGitPath } from './gitProject.js'-import { parseProjectFolder, prepareProjectFolder } from './projectFolder.js'+import { fetchStartBase, harnessMadeWorktree, prepareGitProject, readGitProject, validGitPath } from './gitProject.js'+import { cloneRepository, parseProjectFolder, prepareProjectFolder } from './projectFolder.js'import { engineSessionTitle, namingTitle } from './sessionTitle.js'const exec = promisify(execFile)@@ -445,22 +445,22 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {expect(parseProjectFolder({ projectSource: 'worktree', gitSource: managed, branchBase: 'default', offline: true })).not.toHaveProperty('offline')// The host's fetch, with the environment it is given in place of the daemon's.const env = { ...process.env, GIT_CONFIG_PARAMETERS: `'harness.fixture'='yes'` }- expect(await fetchDefaultBranch(managed, env)).toBe(true)+ expect(await fetchStartBase(managed, env)).toBe(true)expect(await inClone('rev-parse', 'refs/remotes/origin/main')).not.toBe(before)const folder = await prepareProjectFolder({ source: 'worktree', gitSource: managed, branchName: 'super-tab/start-2', fromDefaultBranch: true, offline: true }, options())expect(await readFile(join(folder, 'src', 'value'), 'utf8')).toBe('pushed')})it('a host\'s fetch does nothing outside a checkout or without a default branch, and says when it could not fetch', async () => {- expect(await fetchDefaultBranch('relative/path', process.env)).toBe(false)- expect(await fetchDefaultBranch(join(root, 'nowhere'), process.env)).toBe(false)+ expect(await fetchStartBase('relative/path', process.env)).toBe(false)+ expect(await fetchStartBase(join(root, 'nowhere'), process.env)).toBe(false)const local = join(root, 'no-remote')await mkdir(local)await exec('git', ['-C', local, 'init', '-q', '-b', 'trunk'])await exec('git', ['-C', local, ...identity, 'commit', '-q', '--allow-empty', '-m', 'initial'])- expect(await fetchDefaultBranch(local, process.env)).toBe(false)+ expect(await fetchStartBase(local, process.env)).toBe(false)await inClone('remote', 'set-url', 'origin', join(root, 'gone.git'))- expect(await fetchDefaultBranch(managed, process.env)).toBe(false)+ expect(await fetchStartBase(managed, process.env)).toBe(false)})it('starts from the branch it is given, not the default one', async () => {@@ -496,6 +496,87 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {})})+ describe('a Swarm start for another person\'s work in a blob-less, single-branch clone', () => {+ // The project clone fetches only the default branch, and file contents as they are needed (projectFolder.ts). A start+ // for another person's work is offline: its host fetches with the app's token first, and the owner's login is never+ // used, so nothing may be fetched lazily while its worktree is made.+ let origin: string, managed: string, contacts: string+ const identity = ['-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null']+ const inClone = (...args: string[]) => exec('git', ['-C', managed, ...args]).then(out => out.stdout.trim())+ const offlineStart = (name: string, extra: Partial<{ branchRef: string }> = {}) => prepareProjectFolder({ source: 'worktree', gitSource: managed,+ branchName: name, offline: true, ...(extra.branchRef ? { branchRef: extra.branchRef } : { fromDefaultBranch: true }) }, options())+ /** Someone pushes [value] to [branch] after the managed clone was made. */+ const pushToOrigin = async (branch: string, value: string) => {+ const pusher = join(root, `pusher-${branch}`)+ await exec('git', ['clone', '--quiet', '--branch', branch, origin, pusher])+ await writeFile(join(pusher, 'src', 'value'), value)+ await exec('git', ['-C', pusher, ...identity, 'commit', '-qam', value])+ await exec('git', ['-C', pusher, 'push', '--quiet', 'origin', branch])+ }+ beforeEach(async () => {+ origin = join(root, 'origin.git'); managed = join(root, 'managed'); contacts = join(root, 'contacts.log')+ await exec('git', ['clone', '--quiet', '--bare', repo, origin])+ for (const key of ['uploadpack.allowFilter', 'uploadpack.allowAnySHA1InWant']) await exec('git', ['-C', origin, 'config', key, 'true'])+ await cloneRepository(`file://${origin}`, managed)+ // Every time this clone asks the origin for anything, it says so.+ const uploadPack = join(root, 'upload-pack')+ await writeFile(uploadPack, `#!/bin/sh\necho contact >> '${contacts}'\nexec git-upload-pack "$@"\n`, { mode: 0o755 })+ await inClone('config', 'remote.origin.uploadpack', uploadPack)+ })++ it('fetches the start\'s own base branch and its files with the token, so its offline worktree needs nothing else', async () => {+ await pushToOrigin('feature', 'feature, later')+ expect(await fetchStartBase(managed, process.env, 'refs/remotes/origin/feature')).toBe(true)+ await rm(origin, { recursive: true })+ const folder = await offlineStart('super-tab/start-1', { branchRef: 'refs/remotes/origin/feature' })+ expect(await readFile(join(folder, 'src', 'value'), 'utf8')).toBe('feature, later')+ })++ it('fetches the default branch and its files when the start names no branch', async () => {+ await pushToOrigin('main', 'main, later')+ expect(await fetchStartBase(managed, process.env)).toBe(true)+ await rm(origin, { recursive: true })+ expect(await readFile(join(await offlineStart('super-tab/start-1'), 'src', 'value'), 'utf8')).toBe('main, later')+ })++ it('never fetches missing files while making an offline worktree', async () => {+ await pushToOrigin('main', 'main, later')+ // The branch, without its files: what a fetch with no file contents leaves.+ await inClone('fetch', '--quiet', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main')+ await rm(contacts, { force: true })+ // The start says what is wrong: the branch's files are not here, not Git or folder permissions.+ await expect(offlineStart('super-tab/start-1')).rejects.toThrow("This branch's files could not be fetched for the start. Check the connection, then retry.")+ expect(await readFile(contacts, 'utf8').catch(() => '')).toBe('')+ })++ it('says so when the files of a start\'s branch could not be fetched', async () => {+ await pushToOrigin('main', 'main, later')+ // The branch comes; the request for its files fails.+ const flaky = join(root, 'flaky-upload-pack'), served = join(root, 'served')+ await writeFile(flaky, `#!/bin/sh\n[ -e '${served}' ] && exit 1\ntouch '${served}'\nexec git-upload-pack "$@"\n`, { mode: 0o755 })+ await inClone('config', 'remote.origin.uploadpack', flaky)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ expect(await fetchStartBase(managed, process.env)).toBe(true)+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not fetch the files of refs/remotes/origin/main'))+ } finally { warn.mockRestore() }+ })++ // GIT_NO_LAZY_FETCH is read only by git 2.44 and later (Ubuntu 22.04 ships 2.34, Debian 12 2.39): review 1 of #2770.+ it('never fetches missing files offline even with a git that ignores GIT_NO_LAZY_FETCH', async () => {+ await pushToOrigin('main', 'main, later')+ await inClone('fetch', '--quiet', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main')+ await rm(contacts, { force: true })+ const realGit = (await exec('sh', ['-c', 'command -v git'])).stdout.trim()+ const olderGit = join(root, 'older-git')+ await mkdir(olderGit)+ await writeFile(join(olderGit, 'git'), `#!/bin/sh\nunset GIT_NO_LAZY_FETCH\nexec '${realGit}' "$@"\n`, { mode: 0o755 })+ vi.stubEnv('PATH', `${olderGit}:${process.env.PATH}`)+ await expect(offlineStart('super-tab/start-1')).rejects.toThrow()+ expect(await readFile(contacts, 'utf8').catch(() => '')).toBe('')+ })+ })+describe('a worktree whose git is slow or fails', () => {const harnesses = () => join(root, 'harnesses')const listed = () => git('worktree', 'list', '--porcelain')diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.tsindex 549010a20..2c527a386 100644--- a/cli/src/lib/gitProject.ts+++ b/cli/src/lib/gitProject.ts@@ -220,16 +220,42 @@ export async function originDefaultRef(path: string): Promise<string | null> {}/**- * Brings the remote's default branch up to date in [source], with [env]'s git setup instead of the daemon's: a Swarm- * host's fetch with the Harness GitHub App's token (lib/swarmGitHub.ts `swarmGitPrepareEnv`), before the worktree starts- * from it. True when it fetched. Offline, slow or refused, the worktree starts from what is here, as `prepareGitProject`'s- * own fetch does; a repository with no `origin` default branch has nothing to fetch.+ * Brings the branch a start names ([branchRef], `refs/remotes/origin/X`), or the remote's default branch when it names none+ * or a local one, up to date in [source], with [env]'s git setup instead of the daemon's: a Swarm host's fetch with the+ * Harness GitHub App's token (lib/swarmGitHub.ts `swarmGitPrepareEnv`), before the worktree starts from it. Offline, slow or+ * refused, the worktree starts from what is here; a repository with no `origin` default branch has nothing to fetch. A+ * project clone is single-branch (projectFolder.ts), so X is fetched here or not at all: the start that follows is offline. In a blob-less clone the files of that branch's tip come too, with the same [env], so the+ * offline worktree needs nothing fetched lazily (it may not: `prepareGitProject` `offline`). False when nothing was fetched;+ * files that could not come leave the branch fetched and the start to fail offline, never to use another login.*/-export async function fetchDefaultBranch(source: string, env: NodeJS.ProcessEnv): Promise<boolean> {+export async function fetchStartBase(source: string, env: NodeJS.ProcessEnv, branchRef?: string): Promise<boolean> {if (!validGitPath(source) || !(await insideGitCheckout(source))) return false- const remote = remoteBranch(await originDefaultRef(source) ?? undefined)+ const remote = remoteBranch(branchRef) ?? remoteBranch(await originDefaultRef(source) ?? undefined)if (!remote) return false- return git(source, ['fetch', '--quiet', '--no-tags', remote.remote, remote.refspec], 60_000, env).then(() => true, () => false)+ const fetched = await git(source, ['fetch', '--quiet', '--no-tags', remote.remote, remote.refspec], 60_000, env).then(() => true, () => false)+ if (fetched) await fetchMissingFiles(source, remote.remote, `refs/remotes/${remote.remote}/${remote.branch}`, env)+ return fetched+}++/** In a partial clone, fetches what [ref]'s tree lacks from [remote] in one request, as git's own lazy fetch would ask for it+ * (promisor-remote.c), but with [env]. Listing what is missing fetches nothing. A clone that is not partial lacks nothing.+ * A failure is logged: the offline worktree that follows then fails on the files it lacks. */+async function fetchMissingFiles(source: string, remote: string, ref: string, env: NodeJS.ProcessEnv): Promise<void> {+ if (await git(source, ['config', '--get', `remote.${remote}.promisor`]).catch(() => '') !== 'true') return+ const failed = (stderr: string) => console.warn(`[worktree] could not fetch the files of ${ref} for an offline start: ${gitReason(stderr)}`)+ const listing = await exec('git', gitArgs(source, ['rev-list', '--objects', '--missing=print', '--no-object-names', '--end-of-options', `${ref}^{tree}`]), {+ timeout: 120_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024, env: { ...gitEnv(env), GIT_NO_LAZY_FETCH: '1' },+ }).then(out => out.stdout, (error: { stderr?: string; message?: string }) => { failed(error.stderr || error.message || ''); return '' })+ const missing = listing.split('\n').filter(line => /^\?[0-9a-f]{40,64}$/.test(line)).map(line => line.slice(1))+ if (missing.length === 0) return+ await new Promise<void>(resolve => {+ const child = execFile('git', gitArgs(source, ['-c', 'fetch.negotiationAlgorithm=noop', 'fetch', '--quiet', '--no-tags', '--no-write-fetch-head',+ '--recurse-submodules=no', '--filter=blob:none', '--stdin', remote]), { timeout: 600_000, killSignal: 'SIGKILL', env: gitEnv(env) },+ (error, _stdout, stderr) => { if (error) failed(stderr || error.message); resolve() })+ // A git that exits before reading the whole list closes its input; that is its failure above, not another.+ child.stdin?.on('error', () => {})+ child.stdin?.end(missing.join('\n') + '\n')+ })}export type GitProjectOptions = {@@ -242,7 +268,7 @@ export type GitProjectOptions = {* behind. Only a Swarm start asks for it; a repository with no `origin` default branch starts from `HEAD`. */fromDefaultBranch?: boolean/** Fetch nothing: start from what the checkout already has. A Swarm start doing another person's work: its host- * fetched with the Harness GitHub App's token just before (`fetchDefaultBranch`), and this machine's own git+ * fetched with the Harness GitHub App's token just before (`fetchStartBase`), and this machine's own git* login must not be used for it. */offline?: boolean/** The worktree's branch: created from `ref`, or with `existingBranch` checked out as it is. */@@ -408,7 +434,10 @@ export async function prepareGitProject(source: string, options: GitProjectOptioconst registered = new Set(await readdir(admin).catch(() => [] as string[]))const upstream = tracks ? await git(source, ['branch', `--set-upstream-to=${options.ref}`, branch]).then(() => true, () => false) : trueconst added: WorktreeAdd = upstream- ? await worktreeAdd(source, ['worktree', 'add', '--', destination, branch], options.worktreeTimeout ?? WORKTREE_ADD_TIMEOUT)+ // Offline means nothing fetched, a partial clone's missing files included: they would come with this machine's login.+ // GIT_NO_LAZY_FETCH is read from git 2.44 on; a protocol list naming no transport stops every git (review 1 of #2770).+ ? await worktreeAdd(source, ['worktree', 'add', '--', destination, branch], options.worktreeTimeout ?? WORKTREE_ADD_TIMEOUT,+ options.offline ? { GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: 'none' } : {}): { ok: false, reason: 'could not track its remote branch', stderr: '', timedOut: false, diskFull: false, running: false }if (!added.ok && added.running) {// Deleting the folder under a process still writing it would only race it; the next start takes another folder.@@ -420,6 +449,10 @@ export async function prepareGitProject(source: string, options: GitProjectOptio// A retry starts clean. The folder is this start's own (reserved above), and so is the branch it made.await removePartialWorktree(source, destination, made, admin, registered)if (added.diskFull) throw new GitProjectError('WORKTREE_FAILED', worktreeDiskFull)+ // Offline in a blob-less clone: files `fetchStartBase` could not bring, which this start may not fetch itself.+ if (options.offline && /promisor remote|lazy fetching disabled/i.test(added.stderr)) {+ throw new GitProjectError('WORKTREE_FAILED', "This branch's files could not be fetched for the start. Check the connection, then retry.")+ }throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)}// Harness made this branch: its cleanup may remove it, and a made-up name gives way to the session's.@@ -444,14 +477,14 @@ type WorktreeAdd = { ok: true } | WorktreeAddFailure* the timeout the whole group is killed (on Windows, git's process tree), and the result waits until no process* holds git's stderr any more: until then something git started may still be writing the folder. If that takes* as long again as the timeout (at most a minute), the result says it is `running`. */-function worktreeAdd(source: string, args: string[], timeout: number): Promise<WorktreeAdd> {+function worktreeAdd(source: string, args: string[], timeout: number, extraEnv: NodeJS.ProcessEnv = {}): Promise<WorktreeAdd> {return new Promise(resolve => {let stderr = '', timedOut = false, settled = false, waited: NodeJS.Timeout | undefinedconst done = (result: WorktreeAdd) => { if (!settled) { settled = true; clearTimeout(timer); clearTimeout(waited); resolve(result) } }const failed = (reason: string, running = false): WorktreeAddFailure => ({ ok: false, reason, stderr, timedOut, diskFull: diskFull({ stderr }), running })const late = () => `timed out after ${Math.round(timeout / 1000)} s`const child = spawn('git', gitArgs(source, args), {- env: gitEnv(process.env), stdio: ['ignore', 'ignore', 'pipe'], detached: process.platform !== 'win32', windowsHide: true,+ env: { ...gitEnv(process.env), ...extraEnv }, stdio: ['ignore', 'ignore', 'pipe'], detached: process.platform !== 'win32', windowsHide: true,})child.stderr.on('data', (chunk: Buffer) => { if (stderr.length < 64 * 1024) stderr += chunk.toString() })const timer = setTimeout(() => {@@ -468,7 +501,7 @@ function worktreeAdd(source: string, args: string[], timeout: number): Promise<W/** Kills [pid] and everything it started: its process group, or on Windows its tree. Null when that was done, else why* not. On Windows `taskkill /T` finds only what still descends from a live git, so a failure here is reported and* `worktreeAdd` still waits for git's stderr to close before anything is read or removed. */-function stopTree(pid: number | undefined): Promise<string | null> {+export function stopTree(pid: number | undefined): Promise<string | null> {if (pid === undefined) return Promise.resolve(null)if (process.platform !== 'win32') {try { process.kill(-pid, 'SIGKILL'); return Promise.resolve(null) } catch (error) {diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.tsindex 2ef0dec07..d1ea9ea44 100644--- a/cli/src/lib/projectFolder.spec.ts+++ b/cli/src/lib/projectFolder.spec.ts@@ -4,7 +4,7 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promisimport { tmpdir } from 'node:os'import { join } from 'node:path'import {- cloneFailure, otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, projectsRoot, repositoryIdentity, RepositoryAccessError, RepositoryHostKeyError,+ cloneFailure, cloneRepository, otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, projectsRoot, repositoryIdentity, RepositoryAccessError, RepositoryHostKeyError,} from './projectFolder.js'/** A checkout at [folder] whose origin is [origin] (none when null), made by the real git, with no network. */@@ -367,6 +367,77 @@ describe('a clone GitHub refuses', () => {})})+/** Real git with nothing of this machine's own config: no owner credential helper or url rewrite reaches these clones. */+const isolatedGit: NodeJS.ProcessEnv = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' }+const gitIn = (cwd: string, ...args: string[]) => execFileSync('git', ['-c', 'user.name=t', '-c', '[email protected]', ...args],+ { cwd, env: isolatedGit, encoding: 'utf8' }).trim()++/** An origin that serves partial clones, with `main` and a `feature` branch, each holding a file of its own. */+async function originWithBranches(root: string): Promise<string> {+ const origin = join(root, 'origin')+ execFileSync('git', ['init', '-q', '-b', 'main', origin], { env: isolatedGit })+ for (const [key, value] of [['uploadpack.allowFilter', 'true'], ['uploadpack.allowAnySHA1InWant', 'true']]) gitIn(origin, 'config', key!, value!)+ await writeFile(join(origin, 'main.txt'), 'first\n')+ gitIn(origin, 'add', '.'); gitIn(origin, 'commit', '-q', '-m', 'first')+ await writeFile(join(origin, 'main.txt'), 'first\nsecond\n')+ gitIn(origin, 'commit', '-q', '-am', 'second')+ gitIn(origin, 'checkout', '-q', '-b', 'feature')+ await writeFile(join(origin, 'feature.txt'), 'feature work\n')+ gitIn(origin, 'add', '.'); gitIn(origin, 'commit', '-q', '-m', 'feature')+ gitIn(origin, 'checkout', '-q', 'main')+ return origin+}++describe('the project clone of a large repository', () => {+ let root: string+ beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'harness-clone-test-')) })+ afterEach(async () => { await rm(root, { recursive: true, force: true }) })++ it('clones only the default branch without file contents, and fetches another branch on demand', async () => {+ const origin = await originWithBranches(root)+ const dest = join(root, 'checkout')+ await cloneRepository(`file://${origin}`, dest, isolatedGit)+ expect(gitIn(dest, 'config', 'remote.origin.promisor')).toBe('true')+ expect(gitIn(dest, 'config', 'remote.origin.partialclonefilter')).toBe('blob:none')+ // Only the default branch came: lampOS has about 4,400.+ expect(gitIn(dest, 'for-each-ref', '--format=%(refname)', 'refs/remotes/origin/')).not.toContain('feature')+ // A later fetch still sees every branch, as a full clone's would.+ expect(gitIn(dest, 'config', '--get-all', 'remote.origin.fetch')).toBe('+refs/heads/*:refs/remotes/origin/*')+ expect(gitIn(dest, 'log', '--format=%s')).toBe('second\nfirst')+ expect(gitIn(dest, 'blame', '--porcelain', 'main.txt')).toContain('summary first')+ gitIn(dest, 'fetch', '-q', 'origin', 'feature')+ gitIn(dest, 'checkout', '-q', 'feature')+ expect(await readFile(join(dest, 'feature.txt'), 'utf8')).toBe('feature work\n')+ })++ /** A stand-in for git at [root]/fake-git: [body] runs for `clone`; `config` succeeds. Its pid is written to [root]/pid. */+ async function fakeGit(body: string): Promise<string> {+ const path = join(root, 'fake-git')+ await writeFile(path, `#!/bin/sh\necho $$ > '${join(root, 'pid')}'\n[ "$1" = clone ] || exit 0\n${body}\n`, { mode: 0o755 })+ return path+ }+ const running = (pid: number) => { try { process.kill(pid, 0); return true } catch { return false } }++ it('gives up on a clone that stops making progress, and stops its git', async () => {+ const git = await fakeGit("echo 'Receiving objects: 1%' >&2\nexec sleep 30")+ const started = Date.now()+ const failure = await cloneRepository('https://github.com/owner/repo', join(root, 'checkout'), process.env, { git, stallMs: 1500 })+ .then(() => null, (error: unknown) => error)+ expect(failure).toBeInstanceOf(ProjectFolderError)+ expect(failure).toMatchObject({ code: 'CLONE_TIMEOUT', message: 'Cloning stopped making progress. Check the connection and retry.' })+ expect(Date.now() - started).toBeLessThan(10_000)+ expect(running(Number(await readFile(join(root, 'pid'), 'utf8')))).toBe(false)+ }, 20_000)++ it('never cuts off a slow clone that keeps making progress', async () => {+ // Over three times the window, a line every 200 ms: the receiving part of a big clone on a slow connection.+ const git = await fakeGit("i=0\nwhile [ $i -lt 25 ]; do echo \"Receiving objects: $i%\" >&2; sleep 0.2; i=$((i+1)); done\nexit 0")+ const started = Date.now()+ await expect(cloneRepository('https://github.com/owner/repo', join(root, 'checkout'), process.env, { git, stallMs: 1500 })).resolves.toBeUndefined()+ expect(Date.now() - started).toBeGreaterThan(4500)+ }, 20_000)+})+// The OS chooses a familiar project root without changing other hn installations.it('uses lowercase projects only in the explicit Harness OS environment', () => {try {diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.tsindex f6de4f6ce..a6469fdfa 100644--- a/cli/src/lib/projectFolder.ts+++ b/cli/src/lib/projectFolder.ts@@ -4,7 +4,7 @@ import { access, lstat, mkdir, mkdtemp, rename, rm, stat } from 'node:fs/promiseimport { homedir } from 'node:os'import { dirname, join } from 'node:path'import { plausibleBranchName, projectFolderName, projectFolderSlug } from './agentNames.js'-import { GitProjectError, prepareGitProject, validGitPath } from './gitProject.js'+import { GitProjectError, prepareGitProject, stopTree, validGitPath } from './gitProject.js'import { cloneAttempts, isGitHubHost, parseGitHubRepository, resolvedRepositoryIdentity } from './githubRepository.js'import { githubAliases, resolveHost } from './sshHosts.js'import { scmByKind } from '../scm/scmProjects.js'@@ -282,36 +282,55 @@ function logAttempt(owner: string, name: string, url: string, outcome: string):console.info(`[project] clone ${owner}/${name} over ${via}: ${outcome}`)}+/** Every branch a fetch sees, as a full clone's `origin` has: a single-branch clone writes only its own. */+const ALL_BRANCHES = '+refs/heads/*:refs/remotes/origin/*'++/** How long a clone may go without git reporting any progress before it is given up. Git reports at least once a second+ * while objects arrive (`--progress`); the longest silence measured cloning lampOS was 4.4 s. A clone that keeps+ * progressing is never cut off, however long it takes on a slow connection. */+export const CLONE_STALL_MS = 120_000+/** No shell interpolation or interactive password prompt. Diagnostics stay- * bounded and private; only actionable, credential-free messages reach the UI. */-function cloneRepository(url: string, destination: string, gitEnv?: NodeJS.ProcessEnv): Promise<void> {+ * bounded and private; only actionable, credential-free messages reach the UI.+ *+ * Blob-less and single-branch: the default branch with its whole history, file contents fetched as they are needed (the+ * checkout's own, then whatever `blame` or another branch's checkout reads). lampOS (576 MB pack, about 4,400 branches)+ * took 48 s in full on MACs-Mac-Studio and longer than the 5 minutes once allowed on a slower Mac; blob-less, 6 s. The+ * fetch rule is then widened to every branch, so `git fetch origin X && git checkout X` works as in a full clone.+ * [options] are for tests: `git` the command, `stallMs` the no-progress window. */+export function cloneRepository(url: string, destination: string, gitEnv?: NodeJS.ProcessEnv,+ options: { git?: string; stallMs?: number } = {}): Promise<void> {return new Promise((resolve, reject) => {const base = gitEnv ?? process.env- const child = spawn('git', ['clone', '--', url, destination], {- stdio: ['ignore', 'ignore', 'pipe'],- env: { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',- GIT_SSH_COMMAND: base.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=20' },+ const git = options.git ?? 'git'+ const env = { ...base, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',+ GIT_SSH_COMMAND: base.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=20' }+ // Its own process group, so a stalled clone's remote helper and index-pack stop with it.+ const child = spawn(git, ['clone', '--progress', '--filter=blob:none', '--single-branch', '--', url, destination], {+ stdio: ['ignore', 'ignore', 'pipe'], env, detached: process.platform !== 'win32', windowsHide: true,+ })+ let diagnostic = '', stalled = false+ const stall = setTimeout(() => {+ stalled = true+ void stopTree(child.pid).then(problem => { if (problem) console.error(`[project] could not stop a stalled clone: ${problem}`) })+ }, options.stallMs ?? CLONE_STALL_MS)+ stall.unref()+ child.stderr?.on('data', (chunk: Buffer) => {+ if (!stalled) stall.refresh()+ diagnostic = (diagnostic + chunk.toString()).slice(-8192)})- let diagnostic = '', timedOut = false- let forceKill: ReturnType<typeof setTimeout> | undefined- const deadline = setTimeout(() => {- timedOut = true- child.kill()- forceKill = setTimeout(() => child.kill('SIGKILL'), 2000)- forceKill.unref()- }, 300_000)- deadline.unref()- child.stderr?.on('data', (chunk: Buffer) => { diagnostic = (diagnostic + chunk.toString()).slice(0, 8192) })child.on('error', () => {- clearTimeout(deadline)+ clearTimeout(stall)reject(new ProjectFolderError('GIT_UNAVAILABLE', 'Git could not start. Install Git on the selected machine, then retry.'))})child.on('close', (code) => {- clearTimeout(deadline)- clearTimeout(forceKill)- if (timedOut) reject(new ProjectFolderError('CLONE_TIMEOUT', 'Cloning took too long. Check the connection and retry.'))- else if (code === 0) resolve()- else reject(cloneFailure(diagnostic))+ clearTimeout(stall)+ if (stalled) reject(new ProjectFolderError('CLONE_TIMEOUT', 'Cloning stopped making progress. Check the connection and retry.'))+ else if (code !== 0) reject(cloneFailure(diagnostic))+ else {+ execFile(git, ['-C', destination, 'config', 'remote.origin.fetch', ALL_BRANCHES], { env, timeout: 10_000, killSignal: 'SIGKILL' },+ error => error ? reject(new ProjectFolderError('CLONE_FAILED', 'Could not clone the repository. Check the URL and connection, then retry.')) : resolve())+ }})})}diff --git a/cli/src/lib/swarmGitHub.spec.ts b/cli/src/lib/swarmGitHub.spec.tsindex cbdcedaa2..39ff5383c 100644--- a/cli/src/lib/swarmGitHub.spec.ts+++ b/cli/src/lib/swarmGitHub.spec.ts@@ -79,6 +79,23 @@ describe('the shared helper and hooks', () => {expect(() => swarmGitPrepareEnv('not a token; rm -rf /')).toThrow('not in the form GitHub gives')})+ // MACs-Mac-Studio, 2026-11-03: lampOS keeps CAD files in Git LFS, git-lfs was not installed, and the filter set here anyway+ // made Apple's git fail the checkout ("git-lfs: command not found", "the remote end hung up unexpectedly", exit 128), which+ // the start reported as "Could not clone the repository". Without git-lfs those files stay pointer files, as in any clone.+ it('sets the Git LFS filter only when git-lfs is on the clone\'s PATH', () => {+ const token = `ghs_${'t'.repeat(36)}`+ const without = swarmGitPrepareEnv(token, { PATH: fresh('no-lfs'), HOME: home })+ expect(without.GIT_CONFIG_PARAMETERS).not.toContain('filter.lfs')+ const tools = fresh('lfs-tools')+ script(join(tools, 'git-lfs'), 'exit 0')+ const withLfs = swarmGitPrepareEnv(token, { PATH: `${fresh('empty')}:${tools}`, HOME: home })+ for (const key of ['filter.lfs.process', 'filter.lfs.clean', 'filter.lfs.smudge']) expect(withLfs.GIT_CONFIG_PARAMETERS).toContain(`'${key}'=`)+ // A file named git-lfs that cannot run is no git-lfs.+ const broken = fresh('lfs-broken')+ writeFileSync(join(broken, 'git-lfs'), 'not a program')+ expect(swarmGitPrepareEnv(token, { PATH: broken, HOME: home }).GIT_CONFIG_PARAMETERS).not.toContain('filter.lfs')+ })+it('writes the helper for this daemon\'s CLI and one hook for every hook git runs, private to its user, once', () => {const dataDir = fresh('data')const { helper, hooks } = writeSwarmGitHubTools({ dataDir, command: "'/opt/node' '/opt/harness/cli.js'", port: 18500, machineId: 'machine-1' })diff --git a/cli/src/lib/swarmGitHub.ts b/cli/src/lib/swarmGitHub.tsindex 94c1ab5e2..f01b5920e 100644--- a/cli/src/lib/swarmGitHub.ts+++ b/cli/src/lib/swarmGitHub.ts@@ -16,8 +16,8 @@** The variable `GIT_CONFIG_KEY_n` is not used: Codex leaves out of its commands every variable whose name contains KEY.*/-import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs'-import { join } from 'node:path'+import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'+import { delimiter, join } from 'node:path'import { env } from '../config/env.js'import { daemonCommand } from './daemonCommand.js'import { readAuthSession } from './authSession.js'@@ -59,6 +59,15 @@ export function gitConfigParameters(helper: string, hooks: string, identity?: streturn entries.map(([key, value]) => `${shellWord(key)}=${shellWord(value)}`).join(' ')}+/** Whether a program git-lfs that git can run is on [path] (a PATH value). */+export function hasGitLfs(path: string | undefined): boolean {+ const name = process.platform === 'win32' ? 'git-lfs.exe' : 'git-lfs'+ return (path ?? '').split(delimiter).some(dir => {+ if (!dir) return false+ try { const file = join(dir, name); accessSync(file, constants.X_OK); return statSync(file).isFile() } catch { return false }+ })+}+/*** The environment for the git a machine runs itself to prepare a Swarm agent's folder before the agent exists: the clone* and the fetch of the default branch (superTabs/projectFolder.ts), with [token], a read-only Harness GitHub App token for@@ -81,10 +90,13 @@ export function swarmGitPrepareEnv(token: string, base: NodeJS.ProcessEnv = proc['credential.https://github.com.helper', helper],['url.https://github.com/.insteadof', '[email protected]:'],['url.https://github.com/.insteadof', 'ssh://[email protected]/'],- // Large files still arrive as git-lfs would bring them, when it is installed: its filter is in the global config skipped above.- ['filter.lfs.process', 'git-lfs filter-process'],- ['filter.lfs.clean', 'git-lfs clean -- %f'],- ['filter.lfs.smudge', 'git-lfs smudge -- %f'],+ // Large files still arrive as git-lfs would bring them, when it is installed: its filter is in the global config skipped+ // above. Only then: a filter naming a missing git-lfs failed Apple git's checkout of lampOS (MACs-Mac-Studio, 2026-11-03).+ ...(hasGitLfs(env.PATH ?? env.Path) ? [+ ['filter.lfs.process', 'git-lfs filter-process'],+ ['filter.lfs.clean', 'git-lfs clean -- %f'],+ ['filter.lfs.smudge', 'git-lfs smudge -- %f'],+ ] as Array<[string, string]> : []),]return {...env,diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.tsindex 58f35fb08..dcbf4c944 100644--- a/cli/src/superTabs/projectFolder.spec.ts+++ b/cli/src/superTabs/projectFolder.spec.ts@@ -146,6 +146,13 @@ describe('preparing another person\'s start with the Harness GitHub App', () =>expect(f.fetch).toHaveBeenCalledWith(f.start.request.cwd, options.gitEnv)})+ it('fetches the branch a start names, not only the default branch: a single-branch clone has no other', async () => {+ const f = hosted()+ ;(f.start.request as Record<string, unknown>).branchRef = 'refs/remotes/origin/feature'+ await f.ready()+ expect(f.fetch).toHaveBeenCalledWith(f.start.request.cwd, expect.objectContaining({ HARNESS_SWARM_GIT_TOKEN: TOKEN }), 'refs/remotes/origin/feature')+ })+it('leaves the machine owner\'s own project, and a server without the app, to the owner\'s login as before', async () => {const own = hosted({ github: false })expect(await own.ready()).toBeNull()diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.tsindex a61eb5670..0fbfc71ca 100644--- a/cli/src/superTabs/projectFolder.ts+++ b/cli/src/superTabs/projectFolder.ts@@ -1,6 +1,6 @@import { isAbsolute, join, resolve } from 'node:path'import type { CoreApi } from '../core/api.js'-import { fetchDefaultBranch } from '../lib/gitProject.js'+import { fetchStartBase } from '../lib/gitProject.js'import { otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'import { revokeGitHubToken, swarmGitPrepareEnv } from '../lib/swarmGitHub.js'import { identifier, object, SuperTabHostError } from './wire.js'@@ -65,12 +65,12 @@ async function revokeQuietly(token: string, revoke = revokeGitHubToken): Promise/*** Everything a queued start on this machine needs before its agent is created: the Harness GitHub App's token when the work- * is another person's (`startGitHub`), the Swarm folder's checkout (`prepareSwarmProject`) and, for a worktree, its default- * branch brought up to date with that token, so the agent's worktree starts from it (the core then fetches nothing itself:+ * is another person's (`startGitHub`), the Swarm folder's checkout (`prepareSwarmProject`) and, for a worktree, the branch it+ * starts from (the default one unless it names another) brought up to date with that token, its files included, so the agent's worktree starts from it (the core then fetches nothing itself:* core/agents/launches.ts). Returns whom the work is for, for the start; null when this machine's own login is right for it.*/export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,- deps: { backend: Backend; team: boolean; prepare?: typeof prepareProjectFolder; fetch?: typeof fetchDefaultBranch; revoke?: (token: string) => Promise<void> }):+ deps: { backend: Backend; team: boolean; prepare?: typeof prepareProjectFolder; fetch?: typeof fetchStartBase; revoke?: (token: string) => Promise<void> }):Promise<{ requester: string } | null> {const request = object(start.request)// A person's one Buddy has no project: its launch makes its folder from the checkouts already here and fetches nothing@@ -81,7 +81,8 @@ export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,try {if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, gitEnv)if (gitEnv && request.worktree === true && typeof request.cwd === 'string' && isAbsolute(request.cwd)) {- await (deps.fetch ?? fetchDefaultBranch)(resolve(request.cwd), gitEnv)+ // The branch the start names, when it names one: a project clone has only the default branch (lib/projectFolder.ts).+ await (deps.fetch ?? fetchStartBase)(resolve(request.cwd), gitEnv, ...(typeof request.branchRef === 'string' ? [request.branchRef] : []))}} finally {// The read-only token is done with: the agent gets a token of its own for its task (superTabs/github.ts).diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex b42c9702c..e8aef9d59 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -1511,6 +1511,26 @@ describe('routing contributed capacity', () => {const silent = await runPool(offline, false, {}, owners)expect(silent.answer.excluded).not.toEqual(expect.arrayContaining([expect.objectContaining({ reason: expect.stringContaining('Contributed laptop is offline.') })]))})+ // Task #2390 (Tony, 11-03): a machine its owner keeps for some projects (backend machines.ts machine.projects) is left out of+ // every other project's route, new agents and members alike, with why. The backend refuses it too.+ it('leaves out a machine its owner keeps for other projects, new agents and members alike, and offers it to those projects', async () => {+ const projects = [{ id: 'lead', ownerId: 'owner', name: 'Pilot', visibility: 'public' }, { id: 'oh', ownerId: 'owner', name: 'openharness', visibility: 'public' },+ { id: 'hidden', ownerId: 'owner', name: 'secret', visibility: 'private' }]+ const kept = (ids: string[]) => ({ ...healthy(), projects: ids })+ const other = await runPool(kept(['oh']), true, {}, undefined, { state: { projects } })+ expect(other.answer).toMatchObject({ error: 'NO_CANDIDATE' })+ expect(other.answer.excluded).toEqual(expect.arrayContaining([+ expect.objectContaining({ title: expect.stringContaining('Multiply'), reason: 'Contributed laptop runs only openharness.' }),+ expect.objectContaining({ title: expect.not.stringContaining('Multiply'), reason: 'Contributed laptop runs only openharness.' })]))+ // A private project's name is never written into another project's route.+ const secret = await runPool(kept(['hidden']), false, {}, undefined, { state: { projects } })+ expect(secret.answer.excluded).toEqual(expect.arrayContaining([+ expect.objectContaining({ reason: 'Contributed laptop is kept by its owner for other projects.' })]))+ expect(JSON.stringify(secret.answer)).not.toContain('secret')+ // Kept for this project, or for none in particular: offered as before.+ expect((await runPool(kept(['oh', 'lead']), true, {}, undefined, { state: { projects } })).answer.ok).toBe(true)+ expect((await runPool(healthy(), true, {}, undefined, { state: { projects } })).answer.ok).toBe(true)+ })// One machine (docs/plans/2026-10-24-swarm-team-account.md): a Mac's Harness Team account is that Mac. The Lead is offered// the Mac once: a teammate's project starts in the team account, the Mac's owner's own projects stay with the owner.describe('a Mac and its Harness Team account', () => {diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 0c4d21014..d55ba2a98 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -271,6 +271,17 @@ export async function routeTask(input: { tabId: string; conversationId: string;// A teammate's project runs only on Team machines: the backend says per machine whether it takes one now, and why not// (backend superTabs/machines.ts teamWorkRefusal). Its project owner's own machines take its work as before.const projectOwner = project?.ownerId ?? state.ownerId+ // A machine its owner keeps for some projects (backend machines.ts machine.projects, Tony 11-03): a Mac's Harness Team+ // account follows its Mac. Only public projects are named, as the backend's own sentence does: the route's exclusions reach+ // this project's readers.+ const keptFor = (m: Json) => {+ const mac = typeof m.hostMachineId === 'string' ? list(state.machines).find(x => x.machineId === m.hostMachineId && x.contributorId === m.contributorId) ?? m : m+ const ids: unknown[] | null = Array.isArray(mac.projects) ? mac.projects : null+ if (!ids || ids.includes(projectId)) return null+ const named = list(state.projects).filter(p => ids.includes(p.id) && p.visibility === 'public').map(p => String(p.name))+ return named.length ? `${String(mac.name)} runs only ${named.length > 1 ? `${named.slice(0, -1).join(', ')} and ${named.at(-1)}` : named[0]}.`+ : `${String(mac.name)} is kept by its owner for other projects.`+ }for (const original of list(state.machines)) {const repository = object(project?.repository)const teamWork = object(original.teamWork)@@ -281,6 +292,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;...(original.scope === 'swarm' ? { cwd: repository.machineId === original.machineId? repository.cwd : `${String(original.cwd).replace(/\/+$/, '')}/${projectId}` } : {}),...(original.scope !== 'swarm' && projectId !== 'lead' ? { projectUnavailable: true } : {}),+ ...(keptFor(original) ? { keptForOthers: keptFor(original) } : {}),...(original.scope === 'swarm' && repository.machineId !== original.machineId && typeof repository.repositoryUrl !== 'string'? { repositoryUnavailable: true } : {}),...relayedReadings(original, list(state.machines)),@@ -599,7 +611,8 @@ async function probeMachine(machineId: string, { name: machineName, status, accoconst tools = object(observed.tools)/** Work for a project its owner does not run here: a new agent runs under the contribution, a member under its own grant. */const teammates = (contributorId: unknown) => typeof pool.teammatesRefused === 'string' && contributorId !== pool.projectOwnerId ? [pool.teammatesRefused] : []- const newReasons = [...blocked, ...teammates(pool.contributorId),+ const kept = typeof pool.keptForOthers === 'string' ? [pool.keptForOthers] : []+ const newReasons = [...blocked, ...kept, ...teammates(pool.contributorId),...(pool.projectUnavailable === true ? ['Its owner must add this machine to the swarm again to support other projects.'] : []),...(pool.repositoryUnavailable === true ? ['Share a repository for this project before starting agents on this machine.'] : []),...(pool.availableSlots === 0 ? ['This machine has no available agent slots.'] : []),@@ -620,7 +633,7 @@ async function probeMachine(machineId: string, { name: machineName, status, accoconst engine = String(object(m.configuration).engine), allowance = quota(engine)const running = Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.includes(m.harnessId) : nullreturn { ...memberProbe(m, fresh ? [...memberRefusals(running, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),- ...teammates(m.contributorId)] : [OFFLINE],+ ...kept, ...teammates(m.contributorId)] : [OFFLINE],allowance, null, fresh && running === null, [...pushNote, ...usedUp(allowance)]), ...(fresh ? { load } : {}) }}),...models.map(m => ({ ...newProbe(m, [...newReasons, ...(unready.engines[m.engine] ? [unready.engines[m.engine]!] : [])], quota(m.engine), fresh && quota(m.engine).known,diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 607e60f3f..8ade6c2d3 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -50,7 +50,7 @@ const MENTION_HELP = ' --mention tags a person, by the id or email shown in stat/** What the command entry says after how its JSON is passed, the same for everyone. A task's review plan (#2382) is said in* its brief (backend superTabs/model.ts renderWorkTask), for whoever opens its review (project instructions, phase 4). */const COMMAND_ABOUT = 'send one of the commands below.'-const COMMAND_RULES = 'Reuse exactly the same ID and JSON after an interrupted request. A task is taken as written: conversation.create and work.define send the parts you give (goal, changes, constraints, owns), and checks may be empty. A task\'s optional review ({"focus": what every review of it checks first, such as the most-likely-wrong list; "reviews": 2 for two independent reviews}) is written into its brief, where whoever opens its review reads it; the Swarm opens no review by itself. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. To change how the project works or routes, change its instructions (instructions.save; read them with instructions). tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: the machine\'s owner does, or the PM passing on the owner\'s chat message, with askedIn naming it.'+const COMMAND_RULES = 'Reuse exactly the same ID and JSON after an interrupted request. A task is taken as written: conversation.create and work.define send the parts you give (goal, changes, constraints, owns), and checks may be empty. A task\'s optional review ({"focus": what every review of it checks first, such as the most-likely-wrong list; "reviews": 2 for two independent reviews}) is written into its brief, where whoever opens its review reads it; the Swarm opens no review by itself. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. To change how the project works or routes, change its instructions (instructions.save; read them with instructions). tab.tidy turns off, or back on, the Swarm\'s tidying: finished groups archive once their pull requests are merged or closed. The Swarm owner does, or the PM passing on the owner\'s own chat message, with askedIn naming it. Two failed starts in a row suspend an engine on a machine for up to 6 hours (the route says so); machine.engineResume offers it there again: the machine\'s owner does, or the PM passing on the owner\'s chat message, with askedIn naming it. machine.projects keeps a machine for some projects (projectIds null: every project); the route leaves it out for the others: the machine\'s owner sets it, or the PM passing on the owner\'s chat message, with askedIn naming it.'/** A Buddy's guard refuses `command` itself and every JSON read from stdin, so its help never offers - and stdin there either* (a Buddy that follows a stdin form is refused and tries again, #2360); it quotes the JSON, as its usage hints do. */const BUDDY_COMMAND_HELP = `command OPERATION_ID JSON: ${COMMAND_ABOUT} The JSON is one argument, in single quotes: command OPERATION_ID '{...}' (an apostrophe inside it as \\u0027). ${COMMAND_RULES}`@@ -113,6 +113,7 @@ const HELP = {{ type: 'agent.release', agentId: 'AGENT', decision: 'keep|stop' },{ type: 'instructions.save', projectId: 'PROJECT', baseRevision: 3, text: 'The whole new document', summary: 'One line, up to 200 characters', askedBy: 'PERSON' },{ type: 'machine.engineResume', machineId: 'MACHINE', engine: 'codex', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },+ { type: 'machine.projects', machineId: 'MACHINE', projectIds: ['PROJECT'], askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },{ type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT', routeDecisionId: 'DECISION' },{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'current', status: 'working', result: null },// Both reach the PM and alert the Harness Pro on the machine running the agent until the status moves on.diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex 1929a7ee7..f7f174c9d 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -7,6 +7,9 @@ import { buildEngineCommandArgv } from '../lib/engineLaunch.js'import { readCapacityDisk } from './disk.js'import { SuperTabHostError } from './wire.js'import { PM_HOMES } from './teamDaemon.js'+import { buddyNarrowFile } from '../lib/buddyGuard.js'+import { worktreeFolderName } from '../lib/agentNames.js'+import { env } from '../config/env.js'const teamDaemon = vi.hoisted(() => ({ value: false, relayed: true, offered: null as null | { slugs: string[]; listed: string[] } }))vi.mock('./teamDaemon.js', async (original) => ({ ...await original<object>(), isTeamDaemon: () => teamDaemon.value }))vi.mock('../team/relay.js', async (original) => ({ ...await original<object>(), teamRelayed: () => teamDaemon.relayed, offeredCodexModels: async () => teamDaemon.offered }))@@ -452,6 +455,22 @@ it.each(['claude'])('starts a %s thread session as a Buddy in every way, told itexpect(prompt).not.toContain('assign')})+// Task #2356 (Diego): a thread session of one project, in an older project's Buddy chat or a project session, launches with no+// wide guard, as its chat's own Buddy does (lib/buddyGuard.ts buddyLaunchWide): its folder is marked before it launches.+it('marks a narrow thread session\'s folder before it launches, and a wide one\'s not', async () => {+ const mark = buddyNarrowFile(env.ADAPTER_DATA_DIR, worktreeFolderName('super-tab/start'))+ const wide = fixture()+ wide.start.request = { ...wide.start.request, buddyOf: { personId: 'peer', generation: 'g' }, buddySession: { thread: 'root-1', from: 1 } } as typeof wide.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-session-wide', request: wide.start.request }, wide.scoped, where, wide.open)+ expect(wide.request.mock.calls.some(call => call[0] === 'agent_create')).toBe(true)+ expect(existsSync(mark)).toBe(false)+ const f = fixture()+ f.start.request = { ...f.start.request, buddyOf: { personId: 'peer', generation: 'g' }, buddySession: { thread: 'root-1', from: 1 }, buddyNarrow: true } as typeof f.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-session-narrow', request: f.start.request }, f.scoped, where, f.open)+ expect(f.request.mock.calls.some(call => call[0] === 'agent_create')).toBe(true)+ expect(existsSync(mark)).toBe(true)+})+it('refuses a Codex thread session before anything launches: Codex runs without the Buddy guard hook (security review 1 of #2345)', async () => {const f = fixture()f.start.request = { ...f.start.request, engine: 'codex', buddyOf: { personId: 'peer', generation: 'g' }, buddySession: { thread: 'root-1', from: 1 } } as typeof f.start.requestdiff --git a/desktop/lib/core/web_build_version.dart b/desktop/lib/core/web_build_version.dartnew file mode 100644index 000000000..7f3989bc7--- /dev/null+++ b/desktop/lib/core/web_build_version.dart@@ -0,0 +1,23 @@+/// The release a web build was built as, compiled in by+/// `scripts/build-web-release.sh` (`--dart-define=HARNESS_BUILD_VERSION`).+/// Empty for a build that was not: `flutter run`, and Desktop.+const kBuiltWebVersion = String.fromEnvironment('HARNESS_BUILD_VERSION');++/// [built] as a version, or null when none was compiled in.+String? builtWebVersion([String built = kBuiltWebVersion]) =>+ built.trim().isEmpty ? null : built.trim();++/// The release this page is, for the account menu: the one compiled into it,+/// else what it read from its host at start-up ([declared]). Never the host's+/// answer alone where a build can say its own: a page an old cache keeps+/// starts later and would read the host's newer release as its own, and so+/// never say it is out of date (review of #2622).+String? webPageVersion({String built = kBuiltWebVersion, String? declared}) =>+ builtWebVersion(built) ?? declared;++/// The same, for the watch for a newer release: a build with none compiled in+/// takes what [readHost] says, since there is no better answer.+Future<String?> webRunningVersion({+ String built = kBuiltWebVersion,+ required Future<String?> Function() readHost,+}) async => builtWebVersion(built) ?? await readHost();diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 7c1ab121a..472688708 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -13,6 +13,8 @@ import 'package:flutter/services.dart';import 'package:url_launcher/url_launcher.dart';import 'package:xterm/xterm.dart' show TerminalTheme;+import '../core/web_build_version.dart' show webPageVersion;+import '../ws/ws_conn.dart' show declaredAppVersion;import '../agent_messages/agent_messages_view.dart';import '../agent_messages/shared_tab_dialogs.dart';import '../agent_messages/shared_tab_placement.dart' show plainSharedText;@@ -3463,6 +3465,9 @@ class _SwarmScreenState extends State<SwarmScreen> {topInset: _native ? 0 : _tabBarHeight,// Pairing a phone is for a computer; a phone is already here.forPhone: _compact(context),+ // The browser says which release this page runs; Desktop's menu+ // stays as it was.+ version: kIsWeb ? webPageVersion(declared: declaredAppVersion) : null,devices: app.devicesEnabled,onOpen: onOpen,ownsPointer: (position) => _owns(_accountButtonKey, position),diff --git a/desktop/lib/super_tabs/machine_projects.dart b/desktop/lib/super_tabs/machine_projects.dartnew file mode 100644index 000000000..b0942f6e2--- /dev/null+++ b/desktop/lib/super_tabs/machine_projects.dart@@ -0,0 +1,142 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';++/// Which of the Swarm's projects may run agents on a machine (Tony, 2026-11-03; backend machines.ts `machine.projects`),+/// in the machine's details. Its owner chooses All projects or Only some; anyone else reads the choice. [kept] null is+/// every project, as a machine nobody limited serves. [onChanged] gets the projects kept, in [projects]' order, or null+/// for All. Choosing Only starts with every project ticked, so nothing changes until the owner unticks one, and the last+/// ticked project cannot be unticked: a machine kept for none is no choice to offer here.+class SuperTabMachineProjects extends StatelessWidget {+ const SuperTabMachineProjects({+ super.key,+ required this.projects,+ required this.kept,+ required this.editable,+ required this.onChanged,+ this.busy = false,+ });++ final List<({String id, String name})> projects;+ final List<String>? kept;+ final bool editable;+ final bool busy;+ final ValueChanged<List<String>?> onChanged;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final kept = this.kept;+ final heading = Text(+ 'Projects that may use it',+ style: DesktopChrome.text(),+ );+ if (!editable) {+ final names = kept == null+ ? 'All projects'+ : projects+ .where((p) => kept.contains(p.id))+ .map((p) => p.name)+ .join(', ');+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ heading,+ const SizedBox(height: grid.AppDesktop.controlGap / 2),+ Text(+ names.isEmpty ? 'No project now' : names,+ style: DesktopChrome.control(color: DesktopChrome.muted),+ ),+ ],+ );+ }+ final ids = projects.map((p) => p.id).toList();+ void toggle(String id, bool on) {+ final next = {...?kept};+ on ? next.add(id) : next.remove(id);+ onChanged(ids.where(next.contains).toList());+ }++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ heading,+ RadioGroup<bool>(+ groupValue: kept != null,+ onChanged: (only) {+ if (busy || only == null || only == (kept != null)) return;+ onChanged(only ? ids : null);+ },+ // Side by side, as the mockup Tony was shown (11-03); each choice clickable by its words too.+ child: Wrap(+ spacing: grid.AppDesktop.groupGap,+ children: [+ _choice(+ false,+ 'All projects',+ const ValueKey('machine-projects-all'),+ kept != null,+ ids,+ ),+ _choice(+ true,+ 'Only:',+ const ValueKey('machine-projects-only'),+ kept == null,+ ids,+ ),+ ],+ ),+ ),+ if (kept != null)+ Wrap(+ spacing: grid.AppDesktop.groupGap,+ children: [+ for (final project in projects)+ Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Checkbox(+ key: ValueKey('machine-project-${project.id}'),+ value: kept.contains(project.id),+ semanticLabel: project.name,+ onChanged:+ busy ||+ (kept.length == 1 && kept.contains(project.id))+ ? null+ : (on) => toggle(project.id, on ?? false),+ ),+ Text(project.name, style: DesktopChrome.control()),+ ],+ ),+ ],+ ),+ ],+ );+ }++ /// One of the two choices: the radio, and its words, which choose it too when it is not chosen yet.+ Widget _choice(+ bool only,+ String label,+ Key key,+ bool changes,+ List<String> ids,+ ) => InkWell(+ borderRadius: BorderRadius.circular(grid.AppControl.radius),+ onTap: busy || !changes ? null : () => onChanged(only ? ids : null),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Radio<bool>(key: key, value: only, enabled: !busy),+ Padding(+ padding: const EdgeInsets.only(right: grid.AppDesktop.controlGap),+ child: Text(label, style: DesktopChrome.control()),+ ),+ ],+ ),+ );+}diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 264d83180..5096a506a 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -33,6 +33,7 @@ import 'detail_dialog.dart';import 'dialog_scope.dart';import 'identity.dart';import 'local_models.dart';+import 'machine_projects.dart';import 'machine_allowance.dart';import '../models/swarm_models_target.dart' show swarmSharedWithYouShown;import 'machine_details.dart';@@ -1874,10 +1875,17 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {resources: dim ? null : value,engines: allowed,accounts: dim ? const [] : accounts,- footer: SuperTabMachineLocalModels(- controller: c,- machineId: id,- now: widget.now,+ footer: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ _MachineProjectsSetting(controller: c, machineId: id),+ SuperTabMachineLocalModels(+ controller: c,+ machineId: id,+ now: widget.now,+ ),+ ],),),// One clear action at the right; the rarer ones quiet at the left (Ken, 2026-10-28).@@ -2737,6 +2745,70 @@ class _Allowance {const _noQuotaLeft = 'No quota left until it resets.';/// The same leading icon/name and trailing status column as projects.+/// The machine's projects setting (machine_projects.dart) on this Swarm's state: its owner changes it with+/// `machine.projects` at once, as Pause does. A Mac's Harness Team account follows its Mac, so it has none of its own,+/// and a Swarm with one project and no choice made has nothing to choose.+class _MachineProjectsSetting extends StatefulWidget {+ const _MachineProjectsSetting({+ required this.controller,+ required this.machineId,+ });++ final SuperTabController controller;+ final String machineId;++ @override+ State<_MachineProjectsSetting> createState() =>+ _MachineProjectsSettingState();+}++class _MachineProjectsSettingState extends State<_MachineProjectsSetting> {+ bool _busy = false;++ Future<void> _send(List<String>? projectIds) async {+ setState(() => _busy = true);+ try {+ await widget.controller.command({+ 'type': 'machine.projects',+ 'machineId': widget.machineId,+ 'projectIds': projectIds,+ });+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final c = widget.controller, snapshot = c.snapshot;+ final pool = snapshot?.machines+ .where((m) => m['machineId'] == widget.machineId)+ .firstOrNull;+ if (snapshot == null || pool == null || pool['hostMachineId'] is String)+ return const SizedBox.shrink();+ final kept = pool['projects'] is List+ ? [+ for (final id in pool['projects'] as List)+ if (id is String) id,+ ]+ : null;+ final projects = [+ for (final p in snapshot.projects) (id: p.id, name: p.name),+ ];+ if (kept == null && projects.length < 2) return const SizedBox.shrink();+ return Padding(+ padding: const EdgeInsets.only(top: grid.AppDesktop.groupGap),+ child: SuperTabMachineProjects(+ projects: projects,+ kept: kept,+ editable: pool['contributorId'] == c.accountId && c.canWrite,+ busy: _busy,+ onChanged: (ids) => unawaited(_send(ids)),+ ),+ );+ }+}+class _MachineLine extends StatelessWidget {const _MachineLine({required this.view,diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 40fc03877..0ee736fe7 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -843,42 +843,44 @@ class SuperTabThreadLine extends StatelessWidget {final lastReply = last == null? null: 'Last reply ${superTabAgo(DateTime.now().difference(last))}';- final when = DesktopChrome.metadata();- // Wide enough for either words, so hover moves nothing.- final slot = _widest(context, [?lastReply, 'View thread'], when);final link = _SuperTabThreadBar(key: ValueKey('super-thread-bar-${thread.id}'),label: unread ? '$count, unread' : count,onTap: onOpen,builder: (active) => Row(- mainAxisSize: MainAxisSize.min,children: [for (final author in thread.authors.take(_faces)) ...[_face(author),const SizedBox(width: grid.AppDesktop.menuInset),],- Flexible(- child: Text(- count,- key: ValueKey('super-thread-count-${thread.id}'),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(color: DesktopChrome.accent)- .copyWith(- fontWeight: unread ? FontWeight.w700 : FontWeight.w500,+ // Its words share what the faces leave; the arrow ends the bar.+ Expanded(+ child: Row(+ children: [+ Flexible(+ child: Text(+ count,+ key: ValueKey('super-thread-count-${thread.id}'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(color: DesktopChrome.accent)+ .copyWith(+ fontWeight: unread+ ? FontWeight.w700+ : FontWeight.w500,+ ),),- ),- ),- const SizedBox(width: grid.AppDesktop.controlGap),- Flexible(- child: SizedBox(- width: slot,- child: Text(- active ? 'View thread' : lastReply ?? '',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: when,- ),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Flexible(+ child: Text(+ active ? 'View thread' : lastReply ?? '',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ ],),),const SizedBox(width: grid.AppDesktop.controlGap),@@ -912,32 +914,14 @@ class SuperTabThreadLine extends StatelessWidget {/// On one line while it fits, and on two in a narrow chat.Widget _wrapped(List<Widget> children) =>Wrap(crossAxisAlignment: WrapCrossAlignment.center, children: children);-- /// The width of the widest of [texts] in [style], as this context lays out.- static double _widest(- BuildContext context,- List<String> texts,- TextStyle style,- ) {- var widest = 0.0;- for (final text in texts) {- final painter = TextPainter(- text: TextSpan(text: text, style: style),- textDirection: Directionality.of(context),- textScaler: MediaQuery.textScalerOf(context),- maxLines: 1,- )..layout();- if (painter.width > widest) widest = painter.width;- painter.dispose();- }- return widest.ceilToDouble();- }}/// The reply bar: one target, a hand cursor anywhere on it, reached by Tab and/// pressed with Enter or Space. Hover fills it and draws the rim; focus fills/// it and draws the blue boundary. Both rims are reserved at rest, so neither-/// moves the words. [builder] is told whether it is hovered or focused.+/// moves the words. [builder] is told whether it is hovered or focused, and+/// fills the bar's width: Slack's, or the column's when the chat is narrower+/// (Huy, 2026-11-03, #2373).class _SuperTabThreadBar extends StatefulWidget {const _SuperTabThreadBar({super.key,@@ -950,8 +934,8 @@ class _SuperTabThreadBar extends StatefulWidget {final VoidCallback onTap;final Widget Function(bool active) builder;- /// No wider than this, however wide the chat.- static const maxWidth = 480.0;+ /// Its width, however wide the chat.+ static const width = 600.0;@overrideState<_SuperTabThreadBar> createState() => _SuperTabThreadBarState();@@ -969,39 +953,42 @@ class _SuperTabThreadBarState extends State<_SuperTabThreadBar> {return Semantics(button: true,label: widget.label,- child: ConstrainedBox(- constraints: const BoxConstraints(- maxWidth: _SuperTabThreadBar.maxWidth,- minHeight: 32,- ),- child: InkWell(- onTap: widget.onTap,- onHover: (hovered) => setState(() => _hovered = hovered),- onFocusChange: (focused) => setState(() => _focused = focused),- mouseCursor: SystemMouseCursors.click,- borderRadius: radius,- hoverColor: Colors.transparent,- focusColor: Colors.transparent,- highlightColor: grid.AppSurface.hoverFill,- splashFactory: NoSplash.splashFactory,- child: DecoratedBox(- decoration: BoxDecoration(- color: active ? grid.AppSurface.hoverFill : Colors.transparent,- borderRadius: radius,- border: Border.all(- color: _focused- ? DesktopChrome.focusRing- : _hovered- ? DesktopChrome.rim- : Colors.transparent,- width: grid.AppDesktop.focusWidth,+ child: LayoutBuilder(+ builder: (context, constraints) => ConstrainedBox(+ constraints: BoxConstraints.tightFor(+ width: constraints.maxWidth < _SuperTabThreadBar.width+ ? constraints.maxWidth+ : _SuperTabThreadBar.width,+ ).copyWith(minHeight: 32),+ child: InkWell(+ onTap: widget.onTap,+ onHover: (hovered) => setState(() => _hovered = hovered),+ onFocusChange: (focused) => setState(() => _focused = focused),+ mouseCursor: SystemMouseCursors.click,+ borderRadius: radius,+ hoverColor: Colors.transparent,+ focusColor: Colors.transparent,+ highlightColor: grid.AppSurface.hoverFill,+ splashFactory: NoSplash.splashFactory,+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: active ? grid.AppSurface.hoverFill : Colors.transparent,+ borderRadius: radius,+ border: Border.all(+ color: _focused+ ? DesktopChrome.focusRing+ : _hovered+ ? DesktopChrome.rim+ : Colors.transparent,+ width: grid.AppDesktop.focusWidth,+ ),),- ),- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.menuInset,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.menuInset,+ ),+ child: ExcludeSemantics(child: widget.builder(active)),),- child: ExcludeSemantics(child: widget.builder(active)),),),),diff --git a/desktop/lib/super_tabs/personal_projects.dart b/desktop/lib/super_tabs/personal_projects.dartindex bcb1da4fe..48904190f 100644--- a/desktop/lib/super_tabs/personal_projects.dart+++ b/desktop/lib/super_tabs/personal_projects.dart@@ -5,6 +5,7 @@ import 'package:clock/clock.dart';import 'package:cryptography/dart.dart' show DartSha256;import 'package:flutter/foundation.dart';+import '../logging/app_log.dart';import '../state/app_state.dart';import '../state/swarm.dart';import '../state/terminal_pane.dart';@@ -15,8 +16,9 @@ import 'swarm_switcher.dart' show PersonalSwarm;/// A person's panes as projects of their Personal Swarm (Dee, 10-30 design;/// "build the rest, but leave the tabs", 10-31): every pane of theirs joins/// the project of its repo, whatever tab it is in, the same repo on each of-/// their computers being one project, and a pane with no repo joins-/// # scratch. A project's [term] shows those very panes: the tab keeps them,+/// their computers being one project, and a pane with no repo joins its tab's+/// project, named after the tab (Huy, 11-03: his tabs' panes all landed in one+/// # scratch). A project's [term] shows those very panes: the tab keeps them,/// and nothing about a tab changes.////// Which pane belongs where is worked out here, on the person's own Desktop,@@ -27,10 +29,6 @@ import 'swarm_switcher.dart' show PersonalSwarm;/// Not yet: a repo that already has a team project joining that one. It/// crosses Swarms and needs its own security review.-/// The key of the project for panes with no repo.-const kScratchRepo = 'scratch';-const kScratchProjectName = 'scratch';-/// The form an agent reports its project's remote in: `host[:port]/owner/repo`/// with no scheme, user or `.git` (the CLI's `canonicalRepository`, and/// `canonicalGitRemote` for this computer's own reading). Every real remote@@ -81,6 +79,24 @@ String? normalizedRemote(String? remote) {return [host, ...parts].join('/').toLowerCase();}+/// The project key of a tab's panes with no repo: the desk's tab id, the same+/// on each of the person's computers and through a rename (task #2376).+String personalTabKey(String tabId) => 'tab:$tabId';++/// The name a tab's project is made with on every computer, so that request is+/// one request wherever it is sent (the server refuses a request id reused for+/// another name: review of #2753). It is then renamed to its tab's name, and a+/// tab with no usable name keeps it.+const kTabProjectName = 'Tab';++/// [name] as a project name the server takes: trimmed, at most 160+/// characters (backend `project.create`), [kTabProjectName] for none.+String tabProjectName(String name) {+ final trimmed = name.trim();+ if (trimmed.isEmpty) return kTabProjectName;+ return trimmed.length > 160 ? trimmed.substring(0, 160).trimRight() : trimmed;+}+/// The repo's own name: `github.com/owner/api` is `api`.String repoName(String repo) => repo.split('/').last;@@ -98,14 +114,18 @@ String _hash(String text) => const DartSha256().join().substring(0, 24);-/// The request id a repo's project is created with: the same on every-/// computer of the person's, so the server answers each with the one project-/// (backend commands.ts `project.create`: the project's id comes from it).-String personalProjectOperation(String repo) =>- repo == kScratchRepo ? 'personal-scratch' : 'personal-repo-${_hash(repo)}';+/// The request id a repo's or a tab's project is created with: the same on+/// every computer of the person's, so the server answers each with the one+/// project (backend commands.ts `project.create`: the project's id comes from+/// it). Neither the URL nor the tab's id is in it.+String personalProjectOperation(String key) => _isTab(key)+ ? 'personal-tab-${_hash(key.substring(4))}'+ : 'personal-repo-${_hash(key)}';-/// One of the person's panes, the tab it is first in, and its repo-/// ([kScratchRepo] for none).+bool _isTab(String key) => key.startsWith('tab:');++/// One of the person's panes, the tab it is first in, and its project's key:+/// its repo, or [personalTabKey] of its tab for none.typedef PersonalPane = ({Swarm tab, TerminalPane pane, String repo});/// The person's own panes in their tabs, in tab order then each tab's reading@@ -130,7 +150,8 @@ List<PersonalPane> personalPanes(AppNotifier app) {out.add((tab: tab,pane: pane,- repo: normalizedRemote(agent?.project?.remote) ?? kScratchRepo,+ repo:+ normalizedRemote(agent?.project?.remote) ?? personalTabKey(tab.id),));}}@@ -306,13 +327,25 @@ class PersonalProjects extends ChangeNotifier {_again.remove(scope);if (!eligible(c)) return;final projects = _projects(account, swarm);- final wanted = {for (final p in personalPanes(app)) p.repo};+ // Each project's name: the repo's own, or its tab's name, given once its+ // project is made (a later rename of the tab keeps the project, and its+ // name).+ final wanted = <String, String>{+ for (final p in personalPanes(app))+ p.repo: _isTab(p.repo)+ ? tabProjectName(p.tab.name)+ : repoName(p.repo),+ };var made = false;- for (final repo in wanted) {+ for (final MapEntry(key: repo, value: name) in wanted.entries) {if (projects.containsKey(repo)) continue;final retryAt = _retryAt['$scope/$repo'];if (retryAt != null && clock.now().isBefore(retryAt)) continue;- final answer = await _create(c, repo);+ final answer = await _create(+ c,+ repo,+ _isTab(repo) ? kTabProjectName : name,+ );if (!eligible(c)) return;if (answer case (:final id)) {projects[repo] = id;@@ -324,6 +357,8 @@ class PersonalProjects extends ChangeNotifier {// The new projects read before two of one name are told apart.if (made && !await _reread(c)) return;if (!eligible(c)) return;+ if (await _nameTabs(c, wanted) && eligible(c)) await _reread(c);+ if (!eligible(c)) return;if (await _tellApart(c) && eligible(c)) await _reread(c);} while (_again.contains(scope));} finally {@@ -344,7 +379,11 @@ class PersonalProjects extends ChangeNotifier {/// Creates (or finds again) [repo]'s project: its id, null once the person/// deleted it, or nothing on a failure, asked again after a wait that/// doubles up to [maxRetryWait] when the Swarm next changes.- Future<({String? id})?> _create(SuperTabController c, String repo) async {+ Future<({String? id})?> _create(+ SuperTabController c,+ String repo,+ String name,+ ) async {final key = '${c.accountId}/${c.tabId}/$repo';try {final answer = await c.request(@@ -355,8 +394,9 @@ class PersonalProjects extends ChangeNotifier {'command': {'type': 'project.create',// Every computer sends the same request, so the name is the repo's- // own; two of one name are told apart after ([_tellApart]).- 'name': repo == kScratchRepo ? kScratchProjectName : repoName(repo),+ // own, or the tab's (the desk names a tab alike on each); two repos+ // of one name are told apart after ([_tellApart]).+ 'name': name,'visibility': 'private','brief': '',},@@ -375,17 +415,70 @@ class PersonalProjects extends ChangeNotifier {eligible(c)) {return (id: null);}- _failed(key);- } catch (_) {- _failed(key);+ _failed(key, 'create', failure);+ } catch (error) {+ _failed(key, 'create', error);}return null;}- void _failed(String key) {+ /// What a failure is called in the log: its code, or its kind.+ static String _codeOf(Object error) =>+ error is SuperTabFailure ? error.code : '${error.runtimeType}';++ /// Waits before [key] is asked again, and says why in the log: the+ /// failure's code, never the repo's or the tab's name (ENGINEERING.md 6, 7).+ void _failed(String key, String what, Object error) {final count = _failures[key] = (_failures[key] ?? 0) + 1;final wait = Duration(seconds: 5 << count.clamp(1, 6));- _retryAt[key] = clock.now().add(wait < maxRetryWait ? wait : maxRetryWait);+ final next = wait < maxRetryWait ? wait : maxRetryWait;+ _retryAt[key] = clock.now().add(next);+ appLog.warn(+ 'super-tabs',+ 'Personal project $what refused (${_codeOf(error)}); asked again in ${next.inSeconds} s',+ );+ }++ /// A tab's project still under the name every computer makes it with takes+ /// its tab's name. Asked again on the next sync when it fails. A name the+ /// person chose stays.+ Future<bool> _nameTabs(+ SuperTabController c,+ Map<String, String> wanted,+ ) async {+ final projects = _projects(c.accountId, c.tabId);+ var changed = false;+ for (final MapEntry(key: repo, value: name) in wanted.entries) {+ final id = projects[repo];+ if (!_isTab(repo) || id == null || name == kTabProjectName) continue;+ if (c.snapshot?.projectById(id)?.name != kTabProjectName) continue;+ // A refused rename waits as a refused create does ([_failed]).+ final key = '${c.accountId}/${c.tabId}/$repo/name';+ final retryAt = _retryAt[key];+ if (retryAt != null && clock.now().isBefore(retryAt)) continue;+ try {+ await c.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(c.tabId)}/commands',+ body: {+ 'operationId': 'personal-tab-name-${_hash('$repo\n$name')}',+ 'command': {+ 'type': 'project.rename',+ 'projectId': id,+ 'name': name,+ },+ },+ );+ } catch (error) {+ _failed(key, 'rename', error);+ continue;+ }+ _failures.remove(key);+ _retryAt.remove(key);+ if (!eligible(c)) return changed;+ changed = true;+ }+ return changed;}/// Two repos of one name, both still under it: each is renamed to its long@@ -396,7 +489,7 @@ class PersonalProjects extends ChangeNotifier {final renamed = (_renamed[account] ??= {})[swarm] ??= {};final byName = <String, List<String>>{};for (final MapEntry(key: repo, value: id) in projects.entries) {- if (id == null || repo == kScratchRepo) continue;+ if (id == null || _isTab(repo)) continue;(byName[repoName(repo)] ??= []).add(repo);}var changed = false;@@ -419,7 +512,12 @@ class PersonalProjects extends ChangeNotifier {},},);- } catch (_) {+ } catch (error) {+ // Asked again on the next sync; said in the log by its code alone.+ appLog.warn(+ 'super-tabs',+ 'Personal project rename refused (${_codeOf(error)})',+ );continue;}if (!eligible(c)) return changed;diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 5def2c203..4e51c1748 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -11,6 +11,7 @@ import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_dialog.dart';import '../shared/widgets/app_icon_button.dart';+import '../shared/widgets/empty_state.dart';import '../widgets/desktop_chrome.dart';import '../widgets/finger_target.dart';import '../widgets/new_harness_attachments.dart';@@ -2376,6 +2377,36 @@ class _SuperTabViewState extends State<SuperTabView>null => 0,};+ /// How many of the person's own panes a project of their Personal Swarm+ /// holds (personal_projects.dart); none elsewhere.+ int _personalPaneCount(SuperTabConversation group) =>+ c.snapshot?.isProjectLead(group.id) == true+ ? switch (widget.app) {+ final app? => PersonalProjects.of(app).panesFor(c, group.id).length,+ null => 0,+ }+ : 0;++ /// A Personal project's empty chat when it holds panes: the panes are behind+ /// the header's terminals button, so the empty view says so and opens them+ /// (Huy, 11-03: # scratch looked empty with four panes in it).+ Widget _panesWaiting(SuperTabConversation group) {+ final count = _personalPaneCount(group);+ return EmptyState(+ icon: AppIcons.terminal,+ title: count == 1+ ? '1 pane in this project'+ : '$count panes in this project',+ message:+ 'Discuss the plan with ${c.snapshot!.coordinatorNameOf(group.projectId)}.',+ action: OutlinedButton(+ key: const ValueKey('super-project-show-panes'),+ onPressed: _openTerminals(group),+ child: const Text('Show panes'),+ ),+ );+ }+/// Opens the group's terminals beside the chat; null when it has none this/// reader may open (a read-only viewer's terminal reads are refused).VoidCallback? _openTerminals(SuperTabConversation group) =>@@ -3657,6 +3688,12 @@ class _SuperTabViewState extends State<SuperTabView>? const Center(child: CircularProgressIndicator()): unread && c.error != null? _firstReadFailed(c.error!)+ : messages.isEmpty &&+ outgoing.isEmpty &&+ !c.accessRevoked &&+ group != null &&+ _personalPaneCount(group) > 0+ ? _panesWaiting(group): messages.isEmpty && outgoing.isEmpty? Padding(// The pane's side padding, as the composer has: a long linediff --git a/desktop/lib/web/parts/page_reload.dart b/desktop/lib/web/parts/page_reload.dartindex a5366d3e4..2c89bdb20 100644--- a/desktop/lib/web/parts/page_reload.dart+++ b/desktop/lib/web/parts/page_reload.dart@@ -1,3 +1,6 @@/// Reloads the page; a native build has none (`page_reload_web.dart` is the/// browser's, picked by the import in `deferred_part.dart`).void reloadPage() {}++/// Reloads the page into the newest release; a native build has no page.+Future<void> reloadForNewVersion() async {}diff --git a/desktop/lib/web/parts/page_reload_web.dart b/desktop/lib/web/parts/page_reload_web.dartindex dcd7ed083..f28d24f7e 100644--- a/desktop/lib/web/parts/page_reload_web.dart+++ b/desktop/lib/web/parts/page_reload_web.dart@@ -1,4 +1,36 @@+import 'dart:js_interop';+import 'package:web/web.dart' as web;/// Reloads the page, for a part an older page can no longer download.void reloadPage() => web.window.location.reload();++/// Reloads the page into the release the host serves now. A service worker or+/// cache an older release left in this browser would answer the reload with+/// the old build, so they go first; each step is allowed to fail, and the page+/// reloads whatever came of it. [reload] and [window] are for tests.+Future<void> reloadForNewVersion({+ void Function()? reload,+ web.Window? window,+}) async {+ final win = window ?? web.window;+ try {+ final registrations = await win.navigator.serviceWorker+ .getRegistrations()+ .toDart;+ for (final registration in registrations.toDart) {+ await registration.unregister().toDart;+ }+ } catch (_) {+ // No service workers here, or the browser refuses them.+ }+ try {+ final names = await win.caches.keys().toDart;+ for (final name in names.toDart) {+ await win.caches.delete(name.toDart).toDart;+ }+ } catch (_) {+ // No cache storage here (an insecure page), or the browser refuses it.+ }+ (reload ?? () => win.location.reload())();+}diff --git a/desktop/lib/web/update/page_visible.dart b/desktop/lib/web/update/page_visible.dartnew file mode 100644index 000000000..fbce97af2--- /dev/null+++ b/desktop/lib/web/update/page_visible.dart@@ -0,0 +1,4 @@+/// Tells each time the page comes back to the front; a native build has no+/// page to come back (`page_visible_web.dart` is the browser's, picked by the+/// import in `web_update_host.dart`).+Stream<void> pageShown() => const Stream.empty();diff --git a/desktop/lib/web/update/page_visible_web.dart b/desktop/lib/web/update/page_visible_web.dartnew file mode 100644index 000000000..aafbbe08c--- /dev/null+++ b/desktop/lib/web/update/page_visible_web.dart@@ -0,0 +1,21 @@+import 'dart:async';+import 'dart:js_interop';++import 'package:web/web.dart' as web;++/// Tells each time the page comes back to the front: a tab left in the+/// background is where a release is missed longest, since a browser slows its+/// timers there.+Stream<void> pageShown() {+ late final StreamController<void> controller;+ late final JSFunction listener = ((web.Event _) {+ if (web.document.visibilityState == 'visible') controller.add(null);+ }).toJS;++ controller = StreamController<void>.broadcast(+ onListen: () => web.document.addEventListener('visibilitychange', listener),+ onCancel: () =>+ web.document.removeEventListener('visibilitychange', listener),+ );+ return controller.stream;+}diff --git a/desktop/lib/web/update/web_update_bar.dart b/desktop/lib/web/update/web_update_bar.dartnew file mode 100644index 000000000..a674757b5--- /dev/null+++ b/desktop/lib/web/update/web_update_bar.dart@@ -0,0 +1,102 @@+import 'package:flutter/material.dart';++import '../../shared/theme/app_theme.dart' as grid;+import '../../shared/theme/app_type.dart';+import '../shell/web_hidden_under_keyboard.dart';+import 'web_update_watcher.dart';++/// Everything below a quiet bar that says a newer release is out (task #2185,+/// Huy's mockup): "A new version of Harness is ready." and Reload. The bar+/// comes with [WebUpdateWatcher.updateReady] and stays until the page is+/// reloaded; nothing else asks for a decision.+///+/// One shape whether or not the bar shows: the app below must never be+/// remounted by a bar coming. The bar takes the top inset when it is the top+/// of the page (a phone's browser, no store bar over it), and the app below+/// starts under it.+class WebUpdateFrame extends StatelessWidget {+ const WebUpdateFrame({+ super.key,+ required this.watcher,+ required this.reload,+ required this.child,+ });++ final WebUpdateWatcher watcher;++ /// Loads the new build; tests pass a recorder.+ final VoidCallback reload;+ final Widget child;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: watcher,+ builder: (context, _) {+ final shown = watcher.updateReady;+ final media = MediaQuery.of(context);+ return Column(+ children: [+ if (shown)+ WebHiddenUnderKeyboard(child: _WebUpdateBar(onReload: reload)),+ Expanded(+ key: const ValueKey('web-update-frame-app'),+ child: MediaQuery(+ data: shown ? media.removePadding(removeTop: true) : media,+ child: child,+ ),+ ),+ ],+ );+ },+ );+}++class _WebUpdateBar extends StatelessWidget {+ const _WebUpdateBar({required this.onReload});++ final VoidCallback onReload;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Material(+ key: const ValueKey('web-update-bar'),+ color: grid.AppPalette.swarmTabBar,+ child: SafeArea(+ bottom: false,+ child: DecoratedBox(+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: grid.AppPalette.divider)),+ ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 4),+ child: Row(+ children: [+ Expanded(+ // Wraps on a narrow phone rather than losing its end.+ child: Text(+ 'A new version of Harness is ready.',+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(color: grid.AppPalette.textPrimary),+ ),+ ),+ const SizedBox(width: 8),+ TextButton(+ key: const ValueKey('web-update-reload'),+ onPressed: onReload,+ style: TextButton.styleFrom(+ minimumSize: const Size(64, 44),+ padding: const EdgeInsets.symmetric(horizontal: 12),+ tapTargetSize: MaterialTapTargetSize.padded,+ ),+ child: const Text('Reload'),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/desktop/lib/web/update/web_update_host.dart b/desktop/lib/web/update/web_update_host.dartnew file mode 100644index 000000000..b49900daa--- /dev/null+++ b/desktop/lib/web/update/web_update_host.dart@@ -0,0 +1,120 @@+import 'dart:async';++import 'package:flutter/widgets.dart';++import '../../core/web_build_version.dart';+import '../../core/web_release.dart';+import '../../ws/ws_conn.dart' show appVersionRead, declaredAppVersion;+import '../parts/page_reload.dart'+ if (dart.library.js_interop) '../parts/page_reload_web.dart';+import 'page_visible.dart'+ if (dart.library.js_interop) 'page_visible_web.dart'+ as visible;+import 'web_update_bar.dart';+import 'web_update_watcher.dart';++/// The browser build's watch for a newer release (task #2185): it learns which+/// release this page runs once the start-up read of it lands, then asks the+/// host which one it serves now every few minutes and whenever the page comes+/// back to the front, and draws [WebUpdateFrame]'s bar when they differ. Until+/// then, and for a page that cannot tell its own release, [child] is drawn+/// alone: the app is never held for this.+class WebUpdateHost extends StatefulWidget {+ WebUpdateHost({+ super.key,+ required this.child,+ Future<String?> Function()? readRunning,+ Future<String?> Function()? readLatest,+ VoidCallback? reload,+ this.every = const Duration(minutes: 5),+ Stream<void>? pageShown,+ }) : readRunning = readRunning ?? _runningVersion,+ readLatest = readLatest ?? webReleaseVersion,+ reload = reload ?? (() => unawaited(reloadForNewVersion())),+ pageShown = pageShown ?? _pageShown();++ final Widget child;++ /// The release this page started on, as the start-up read says it.+ final Future<String?> Function() readRunning;++ /// The release the host serves now.+ final Future<String?> Function() readLatest;++ /// Loads the new build.+ final VoidCallback reload;+ final Duration every;++ /// Each time the page comes back to the front.+ final Stream<void> pageShown;++ /// The release this build was built as; for a build that cannot say, what+ /// the start-up read of the host's manifest said.+ static Future<String?> _runningVersion() => webRunningVersion(+ readHost: () async {+ await appVersionRead;+ return declaredAppVersion;+ },+ );++ static Stream<void> _pageShown() => visible.pageShown();++ @override+ State<WebUpdateHost> createState() => _WebUpdateHostState();+}++class _WebUpdateHostState extends State<WebUpdateHost> {+ WebUpdateWatcher? _watcher;+ StreamSubscription<void>? _shown;+ bool _disposed = false;++ @override+ void initState() {+ super.initState();+ unawaited(_begin());+ }++ Future<void> _begin() async {+ String? running;+ try {+ running = await widget.readRunning();+ } catch (_) {+ // A page that cannot say its release never says another is ready.+ }+ if (_disposed || running == null) return;+ final watcher = WebUpdateWatcher(+ running: running,+ readLatest: widget.readLatest,+ every: widget.every,+ )..start();+ // A page an old cache kept may be out of date already: ask once now.+ unawaited(watcher.check());+ _shown = widget.pageShown.listen((_) => unawaited(watcher.check()));+ setState(() => _watcher = watcher);+ }++ @override+ void dispose() {+ _disposed = true;+ unawaited(_shown?.cancel());+ _watcher?.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final watcher = _watcher;+ // One shape from the first frame: the app is not remounted when the+ // watch starts.+ return WebUpdateFrame(+ watcher: watcher ?? _never,+ reload: widget.reload,+ child: widget.child,+ );+ }++ static final _never = WebUpdateWatcher(+ running: null,+ readLatest: () async => null,+ );+}diff --git a/desktop/lib/web/update/web_update_watcher.dart b/desktop/lib/web/update/web_update_watcher.dartnew file mode 100644index 000000000..6dcb775c9--- /dev/null+++ b/desktop/lib/web/update/web_update_watcher.dart@@ -0,0 +1,62 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++/// Tells an open page that the host now serves another release than the one+/// the page started on (task #2185). The page re-reads the host's release+/// manifest (`webReleaseVersion`, served `no-store`) every [every], and+/// [updateReady] latches once it names a version other than [running].+///+/// A manifest that cannot be read — offline, a failed deploy, an odd body —+/// is no answer: it neither raises nor clears the notice. A page that does+/// not know its own version ([running] null: `flutter run`, a failed read at+/// start-up) never says ready, since every release would differ from it.+class WebUpdateWatcher extends ChangeNotifier {+ WebUpdateWatcher({+ required this.running,+ required this.readLatest,+ this.every = const Duration(minutes: 5),+ });++ /// The version this page started on.+ final String? running;++ /// The version the host serves now; null when it cannot say.+ final Future<String?> Function() readLatest;++ /// How often the host is asked.+ final Duration every;++ bool _ready = false, _disposed = false;+ Timer? _timer;++ /// A release other than [running] is out.+ bool get updateReady => _ready;++ /// Asks the host once.+ Future<void> check() async {+ final known = running;+ if (_ready || _disposed || known == null) return;+ String? latest;+ try {+ latest = await readLatest();+ } catch (_) {+ return;+ }+ if (_disposed || latest == null || latest == known) return;+ _ready = true;+ notifyListeners();+ }++ /// Asks the host every [every] from now on, until disposed.+ void start() {+ _timer ??= Timer.periodic(every, (_) => unawaited(check()));+ }++ @override+ void dispose() {+ _disposed = true;+ _timer?.cancel();+ super.dispose();+ }+}diff --git a/desktop/lib/web/web_entry.dart b/desktop/lib/web/web_entry.dartindex bee3ffd03..72e609bf1 100644--- a/desktop/lib/web/web_entry.dart+++ b/desktop/lib/web/web_entry.dart@@ -10,6 +10,7 @@ import 'p2p/web_terminal_p2p.dart';import 'parts/workspace_part.dart';import 'shell/web_focus_ring.dart';import 'shell/web_store_banner.dart';+import 'update/web_update_host.dart';import 'web_console.dart';/// The signed-in screen of a browser build, chosen over@@ -25,14 +26,18 @@ Widget authenticatedWorkspace(AppNotifier app) => P2pResumeRetry(void prepareConsole() => prepareWebConsole();/// What a browser build draws around every screen: on a phone, the bar that-/// sends it to the Harness app in its store. Above the Navigator, so every+/// sends it to the Harness app in its store, and the bar that says a newer+/// release is out. Above the Navigator, so every/// screen and route under it shows no key hints: the web is mouse-first./// Its first frame starts the workspace's download, and from the start it/// keeps (and forgets) the account's computers.Widget appFrame(Widget app) => WorkspacePrefetch(child: KeptComputers(child: WebFocusRing(- child: WebAppStoreFrame(child: KeyHints(visible: false, child: app)),+ // The update bar sits under the store bar, above the app.+ child: WebAppStoreFrame(+ child: WebUpdateHost(child: KeyHints(visible: false, child: app)),+ ),),),);diff --git a/desktop/lib/widgets/account_menu.dart b/desktop/lib/widgets/account_menu.dartindex 6ce7cd5f8..5ff9b37c9 100644--- a/desktop/lib/widgets/account_menu.dart+++ b/desktop/lib/widgets/account_menu.dart@@ -41,6 +41,7 @@ Future<AccountMenuChoice?> showAccountMenu(double topInset = 0,bool focusFirst = false,bool forPhone = false,+ String? version,bool devices = true,void Function(void Function() close)? onOpen,bool Function(Offset position)? ownsPointer,@@ -56,6 +57,7 @@ Future<AccountMenuChoice?> showAccountMenu(name: name,email: email,forPhone: forPhone,+ version: version,devices: devices,onChoose: close,),@@ -68,6 +70,7 @@ class AccountMenu extends StatelessWidget {required this.email,required this.onChoose,this.forPhone = false,+ this.version,this.devices = true,});@@ -80,6 +83,11 @@ class AccountMenu extends StatelessWidget {/// already here). Its compact bar keeps Devices and the Store itself.final bool forPhone;+ /// The version this build runs, when it says one: the web build's, so a page+ /// held open since a release can be told from the new one (task #2185).+ /// Desktop gives none, and its menu is as it was.+ final String? version;+/// Whether this build has Devices (`AppNotifier.devicesEnabled`).final bool devices;@@ -178,6 +186,19 @@ class AccountMenu extends StatelessWidget {),),],+ if (version case final version?) ...[+ const AppMenuDivider(),+ Padding(+ padding: const EdgeInsets.fromLTRB(15, 6, 15, 4),+ child: Text(+ 'Harness $version',+ key: const ValueKey('account-menu-version'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ ],],),),diff --git a/desktop/scripts/build-web-release.sh b/desktop/scripts/build-web-release.shindex 7329bd414..f38caaab5 100644--- a/desktop/scripts/build-web-release.sh+++ b/desktop/scripts/build-web-release.sh@@ -18,7 +18,8 @@ source_commit="$(git rev-parse HEAD)"api_url='https://harness-api.autonomous.ai'"${FLUTTER_BIN:-flutter}" build web --release --no-wasm-dry-run \--no-web-resources-cdn --base-href=/harness-web/ \- --output=build/web-release --build-name="$version"+ --output=build/web-release --build-name="$version" \+ --dart-define=HARNESS_BUILD_VERSION="$version"# lucide_icons_flutter lists seven fonts and the browser fetches every one on first load, but# the app draws only weight 400 (lib/shared/theme/app_icons.dart): the other six are 1.5 MBdiff --git a/desktop/test/account_menu_version_test.dart b/desktop/test/account_menu_version_test.dartnew file mode 100644index 000000000..c3070909b--- /dev/null+++ b/desktop/test/account_menu_version_test.dart@@ -0,0 +1,54 @@+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/widgets/account_menu.dart';++/// The running version, one quiet line under the account menu's last row+/// (task #2185, Huy's mockup). Only the web build says one: Desktop's menu is+/// as it was.+void main() {+ Future<void> open(WidgetTester tester, {String? version}) =>+ tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: AccountMenu(+ name: 'Huy',+ email: '[email protected]',+ onChoose: (_) {},+ version: version,+ ),+ ),+ ),+ );++ testWidgets('the web build says which version is running', (tester) async {+ await open(tester, version: '1.3.51');+ expect(+ tester+ .widget<Text>(find.byKey(const ValueKey('account-menu-version')))+ .data,+ 'Harness 1.3.51',+ );+ // Under Sign out, the menu's last row.+ expect(+ tester.getTopLeft(find.byKey(const ValueKey('account-menu-version'))).dy,+ greaterThan(+ tester+ .getBottomLeft(+ find.byKey(const ValueKey('account-menu-signOut')),+ )+ .dy -+ 1,+ ),+ );+ });++ testWidgets('a build that says none shows no such line (Desktop)', (+ tester,+ ) async {+ await open(tester);+ expect(find.byKey(const ValueKey('account-menu-version')), findsNothing);+ expect(find.byKey(const ValueKey('account-menu-signOut')), findsOneWidget);+ });+}diff --git a/desktop/test/super_tab_machine_projects_test.dart b/desktop/test/super_tab_machine_projects_test.dartnew file mode 100644index 000000000..77df4db35--- /dev/null+++ b/desktop/test/super_tab_machine_projects_test.dart@@ -0,0 +1,157 @@+// Task #2390 (Tony, 11-03): a machine's owner chooses which of the Swarm's projects may run agents on it, in its details in+// Manage > Machines (backend machines.ts machine.projects). Default all; a teammate sees the choice and cannot change it.+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/machine_projects.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['MACHINE_PROJECT_SHOTS'];++const projects = [+ (id: 'oh', name: 'openharness'),+ (id: 'lampos', name: 'lampos'),+ (id: 'spaceship', name: 'spaceship'),+ (id: 'computer', name: 'computer'),+ (id: 'router', name: 'physical-router'),+];++Future<List<List<String>?>> _show(+ WidgetTester tester, {+ List<String>? kept,+ bool editable = true,+ Brightness brightness = Brightness.dark,+ GlobalKey? picture,+}) async {+ final sent = <List<String>?>[];+ // As the app's own scope sets the design tokens from the theme (main.dart _GridTokenScope).+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Center(+ child: RepaintBoundary(+ key: picture,+ child: Container(+ // The details dialog's card, which the setting sits on.+ color: grid.AppCard.base,+ width: 520,+ child: Padding(+ padding: const EdgeInsets.all(16),+ child: SuperTabMachineProjects(+ projects: projects,+ kept: kept,+ editable: editable,+ onChanged: sent.add,+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return sent;+}++Checkbox _box(WidgetTester tester, String name) =>+ tester.widget<Checkbox>(find.byKey(ValueKey('machine-project-$name')));++void main() {+ testWidgets(+ 'a machine nobody limited serves every project, and Only starts with every project ticked',+ (tester) async {+ final sent = await _show(tester);+ expect(find.text('Projects that may use it'), findsOneWidget);+ expect(find.text('All projects'), findsOneWidget);+ // No project boxes until the owner chooses Only.+ expect(find.byType(Checkbox), findsNothing);+ await tester.tap(find.byKey(const ValueKey('machine-projects-only')));+ await tester.pump();+ expect(sent, [+ ['oh', 'lampos', 'spaceship', 'computer', 'router'],+ ]);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets(+ 'the owner ticks and unticks projects, never the last one, and All sends every project again',+ (tester) async {+ final sent = await _show(tester, kept: ['oh', 'lampos']);+ expect(_box(tester, 'oh').value, isTrue);+ expect(_box(tester, 'spaceship').value, isFalse);+ await tester.tap(find.byKey(const ValueKey('machine-project-lampos')));+ await tester.tap(find.byKey(const ValueKey('machine-project-computer')));+ await tester.tap(find.byKey(const ValueKey('machine-projects-all')));+ await tester.pump();+ expect(sent, [+ ['oh'],+ ['oh', 'lampos', 'computer'],+ null,+ ]);+ // The one project left ticked cannot be unticked: a machine kept for no project is no choice to offer.+ await _show(tester, kept: ['oh']);+ expect(_box(tester, 'oh').onChanged, isNull);+ expect(_box(tester, 'lampos').onChanged, isNotNull);+ },+ );++ testWidgets('a teammate sees which projects may use it, without controls', (+ tester,+ ) async {+ await _show(tester, kept: ['oh'], editable: false);+ expect(find.text('Projects that may use it'), findsOneWidget);+ expect(find.text('openharness'), findsOneWidget);+ expect(find.text('lampos'), findsNothing);+ expect(find.byType(Checkbox), findsNothing);+ expect(find.byType(Radio<bool>), findsNothing);+ await _show(tester, editable: false);+ expect(find.text('All projects'), findsOneWidget);+ expect(find.byType(Radio<bool>), findsNothing);+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ await loadPreviewFonts();+ final picture = GlobalKey();+ Future<void> shot(String name) => tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 2);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/machine-projects-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ await _show(+ tester,+ kept: ['oh'],+ brightness: brightness,+ picture: picture,+ );+ await shot('owner-only');+ await _show(tester, brightness: brightness, picture: picture);+ await shot('owner-all');+ await _show(+ tester,+ kept: ['oh'],+ editable: false,+ brightness: brightness,+ picture: picture,+ );+ await shot('teammate');+ }, skip: shots == null);+ }+}diff --git a/desktop/test/super_tab_personal_projects_test.dart b/desktop/test/super_tab_personal_projects_test.dartindex b7f6303d2..7114fd21d 100644--- a/desktop/test/super_tab_personal_projects_test.dart+++ b/desktop/test/super_tab_personal_projects_test.dart@@ -5,6 +5,7 @@ import 'package:clock/clock.dart';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';+import 'package:harness/logging/app_log.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';import 'package:harness/state/swarm.dart';@@ -60,8 +61,13 @@ TerminalPane _pane(String machineId, String agentId) =>TerminalPane(id: _paneIds++, machineId: machineId, agentId: agentId);/// A desk tab of the person's, holding [panes] in this order.-Swarm _tab(AppNotifier app, String id, List<TerminalPane> panes) {- final tab = Swarm(id: id, name: id)..panes.addAll(panes);+Swarm _tab(+ AppNotifier app,+ String id,+ List<TerminalPane> panes, {+ String? name,+}) {+ final tab = Swarm(id: id, name: name ?? id)..panes.addAll(panes);app.swarms.add(tab);return tab;}@@ -132,6 +138,33 @@ _desk(SuperTabLaunchFixture f) {return panes;}+/// Huy's desk (task #2376): tabs Harness Monitor (its web view, then its+/// assistant) and code (two agents), every agent in a folder with no remote.+({TerminalPane a1, TerminalPane a2, TerminalPane mon}) _huyDesk(+ SuperTabLaunchFixture f,+) {+ f.app.machineStates['m']!.agents = [+ _agent('a1', cwd: '/Users/huy/code'),+ _agent('a2', cwd: '/Users/huy/code'),+ _agent('mon', cwd: '/Users/huy'),+ ];+ final panes = (+ a1: _pane('m', 'a1'),+ a2: _pane('m', 'a2'),+ mon: _pane('m', 'mon'),+ );+ final view = TerminalPane(+ id: _paneIds++,+ machineId: 'm',+ ownerAgentId: 'mon',+ kind: PaneKind.web,+ url: 'http://127.0.0.1:1/',+ );+ _tab(f.app, 'desk-monitor', [view, panes.mon], name: 'Harness Monitor');+ _tab(f.app, 'desk-code', [panes.a1, panes.a2], name: 'code');+ return panes;+}+void main() {setUpAll(() => loadCaptureFonts(_shots));@@ -240,7 +273,10 @@ void main() {expect(id, isNot(contains('acme')));expect(id, personalProjectOperation('github.com/acme/api'));expect(id, isNot(personalProjectOperation('github.com/other/api')));- expect(personalProjectOperation(kScratchRepo), 'personal-scratch');+ expect(+ personalProjectOperation(personalTabKey('desk-code')),+ allOf(startsWith('personal-tab-'), isNot(contains('desk-code'))),+ );});test('two repos of one name have long names that tell them apart', () {@@ -260,7 +296,7 @@ void main() {[for (final e in panes) e.repo],['github.com/acme/api',- kScratchRepo,+ personalTabKey('one'),'github.com/acme/web','github.com/acme/api',],@@ -311,53 +347,51 @@ void main() {});group('Personal\'s projects', () {- test(- 'each repo, and # scratch, is made once as a private project',- () async {- final f = SuperTabLaunchFixture();- _desk(f);- final c = await _personal(f);- await PersonalProjects.of(f.app).sync(c);- final creates = _commands(f);- expect(- [for (final p in creates) p['operationId']],- [- personalProjectOperation('github.com/acme/api'),- 'personal-scratch',- personalProjectOperation('github.com/acme/web'),- ],- );- expect(- [for (final p in creates) p['command']['name']],- ['api', 'scratch', 'web'],- );- expect(- creates.every((p) => p['command']['visibility'] == 'private'),- isTrue,- );- final names = [for (final p in c.snapshot!.projects) p.name];- expect(names, containsAll(['api', 'scratch', 'web']));+ test('each repo, and each tab\'s panes with no repo, is made once as a private project', () async {+ final f = SuperTabLaunchFixture();+ _desk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final creates = _commands(f);+ expect(+ [for (final p in creates) p['operationId']],+ [+ personalProjectOperation('github.com/acme/api'),+ personalProjectOperation(personalTabKey('one')),+ personalProjectOperation('github.com/acme/web'),+ ],+ );+ expect(+ [for (final p in creates) p['command']['name']],+ ['api', kTabProjectName, 'web'],+ );+ expect(+ creates.every((p) => p['command']['visibility'] == 'private'),+ isTrue,+ );+ final names = [for (final p in c.snapshot!.projects) p.name];+ expect(names, containsAll(['api', 'one', 'web']));+ expect(names, isNot(contains('scratch')));- // Again: nothing.- await PersonalProjects.of(f.app).sync(c);- expect(_commands(f), hasLength(3));+ // Again: nothing.+ await PersonalProjects.of(f.app).sync(c);+ expect(_commands(f), hasLength(3));- // The app restarted on the same computer: what it kept, no request.- final restarted = SuperTabLaunchFixture();- restarted.store.values.addAll(f.store.values);- restarted.connection.server.state- ..clear()- ..addAll(f.connection.server.state);- _desk(restarted);- final rc = await _personal(restarted);- await PersonalProjects.of(restarted.app).sync(rc);- expect(_commands(restarted), isEmpty);- expect(- PersonalProjects.of(restarted.app).knownForTest('owner', tabId),- PersonalProjects.of(f.app).knownForTest('owner', tabId),- );- },- );+ // The app restarted on the same computer: what it kept, no request.+ final restarted = SuperTabLaunchFixture();+ restarted.store.values.addAll(f.store.values);+ restarted.connection.server.state+ ..clear()+ ..addAll(f.connection.server.state);+ _desk(restarted);+ final rc = await _personal(restarted);+ await PersonalProjects.of(restarted.app).sync(rc);+ expect(_commands(restarted), isEmpty);+ expect(+ PersonalProjects.of(restarted.app).knownForTest('owner', tabId),+ PersonalProjects.of(f.app).knownForTest('owner', tabId),+ );+ });test('panes whose agents report the daemon\'s own remote form get repo projects', () async {final f = SuperTabLaunchFixture();@@ -572,6 +606,28 @@ void main() {expect(PersonalProjects.of(f.app).knownForTest('owner', tabId), isEmpty);});+ test('a refused rename of two repos of one name is logged by its code, not the repo', () async {+ final lines = <String>[];+ final previous = appLog;+ appLog = _Recorder(lines);+ addTearDown(() => appLog = previous);+ final f = SuperTabLaunchFixture();+ f.app.machineStates['m']!.agents = [+ _agent('n1', remote: '[email protected]:acme/api.git'),+ _agent('n2', remote: '[email protected]:kim/api.git'),+ ];+ _tab(f.app, 'one', [_pane('m', 'n1'), _pane('m', 'n2')]);+ final c = await _personal(f);+ f.connection.server.unknownCommand = (command) =>+ command['type'] == 'project.rename';+ await PersonalProjects.of(f.app).sync(c);+ expect(lines.where((l) => l.contains('VALIDATION_ERROR')), isNotEmpty);+ for (final line in lines) {+ expect(line, isNot(contains('acme')), reason: line);+ expect(line, isNot(contains('kim')), reason: line);+ }+ });+test('two repos of one name become two projects told apart', () async {final f = SuperTabLaunchFixture();f.app.machineStates['m']!.agents = [@@ -635,7 +691,7 @@ void main() {.firstWhere((p) => p.name == name).leadConversationId;final projects = PersonalProjects.of(f.app);- expect(projects.panesFor(c, lead('scratch')), [p.folder]);+ expect(projects.panesFor(c, lead('one')), [p.folder]);// The folder becomes a checkout of the web app.f.app.machineStates['m']!.agents = [@@ -644,7 +700,7 @@ void main() {? _agent('n2', remote: '[email protected]:acme/web.git'): a,];- expect(projects.panesFor(c, lead('scratch')), isEmpty);+ expect(projects.panesFor(c, lead('one')), isEmpty);expect(projects.panesFor(c, lead('web')), [p.folder, p.web]);});@@ -667,6 +723,327 @@ void main() {});});+ group('panes with no repo, per tab (task #2376)', () {+ test('Huy\'s two tabs are two projects named after them, each with its own panes', () async {+ final f = SuperTabLaunchFixture();+ final p = _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ expect(+ [for (final post in _commands(f)) post['command']['name']],+ [kTabProjectName, kTabProjectName],+ );+ // Made under one name on every computer, then named after its tab.+ expect(+ [+ for (final post in _commands(f, 'project.rename'))+ post['command']['name'],+ ],+ ['Harness Monitor', 'code'],+ );+ String lead(String name) => c.snapshot!.projects+ .firstWhere((p) => p.name == name)+ .leadConversationId;+ final projects = PersonalProjects.of(f.app);+ expect(projects.panesFor(c, lead('Harness Monitor')), [p.mon]);+ expect(projects.panesFor(c, lead('code')), [p.a1, p.a2]);+ expect([+ for (final p in c.snapshot!.projects) p.name,+ ], isNot(contains('scratch')));+ });++ test('panes with a repo still join the repo\'s project, whatever tab', () {+ final f = SuperTabLaunchFixture();+ final p = _desk(f);+ final keys = {for (final e in personalPanes(f.app)) e.pane: e.repo};+ expect(keys[p.api], 'github.com/acme/api');+ expect(keys[p.api2], 'github.com/acme/api');+ expect(keys[p.web], 'github.com/acme/web');+ expect(keys[p.folder], personalTabKey('one'));+ });++ test('a renamed tab keeps its project and its name', () async {+ final f = SuperTabLaunchFixture();+ final p = _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final code = c.snapshot!.projects.firstWhere((p) => p.name == 'code');+ f.app.swarms.firstWhere((s) => s.id == 'desk-code')+ ..name = 'backend'+ ..nameIsCustom = true;+ await PersonalProjects.of(f.app).sync(c);+ expect(_commands(f), hasLength(2));+ expect(PersonalProjects.of(f.app).panesFor(c, code.leadConversationId), [+ p.a1,+ p.a2,+ ]);+ expect(c.snapshot!.projectById(code.id)?.name, 'code');+ });++ test(+ 'another computer of the person\'s finds the same tab projects',+ () async {+ final f = SuperTabLaunchFixture();+ _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final laptop = SuperTabLaunchFixture();+ laptop.connection.server.state+ ..clear()+ ..addAll(f.connection.server.state);+ _huyDesk(laptop);+ final lc = await _personal(laptop);+ await PersonalProjects.of(laptop.app).sync(lc);+ expect(+ [for (final post in _commands(laptop)) post['operationId']],+ [for (final post in _commands(f)) post['operationId']],+ );+ expect(+ PersonalProjects.of(laptop.app).knownForTest('owner', tabId),+ PersonalProjects.of(f.app).knownForTest('owner', tabId),+ );+ },+ );++ // Security review 1 of #2753 (Linnet): every computer sends one request for a+ // tab's project, so a tab renamed before another computer asks must not+ // change that request, which the server refuses for another name.+ test('a tab renamed before another computer asks still finds its project there', () async {+ final f = SuperTabLaunchFixture();+ f.connection.server.refuseReusedOperations = true;+ final p = _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final code = c.snapshot!.projects.firstWhere((p) => p.name == 'code');++ // The laptop, with nothing kept, after the tab was renamed.+ final laptop = SuperTabLaunchFixture();+ laptop.connection.server+ ..refuseReusedOperations = true+ ..receipts.addAll(f.connection.server.receipts)+ ..receiptCommands.addAll(f.connection.server.receiptCommands);+ laptop.connection.server.state+ ..clear()+ ..addAll(f.connection.server.state);+ final lp = _huyDesk(laptop);+ laptop.app.swarms.firstWhere((s) => s.id == 'desk-code')+ ..name = 'backend'+ ..nameIsCustom = true;+ final lc = await _personal(laptop);+ await PersonalProjects.of(laptop.app).sync(lc);+ expect(+ PersonalProjects.of(laptop.app).panesFor(lc, code.leadConversationId),+ [lp.a1, lp.a2],+ );+ expect(p.a1.agentId, lp.a1.agentId);+ // The project keeps the name it was made with.+ expect(lc.snapshot!.projectById(code.id)?.name, 'code');+ });++ // ENGINEERING.md 6 (Linnet, review round 3): a refused create or rename+ // says so in the log, with its code and nothing of the tab.+ test(+ 'a refused create or rename is logged by its code, without the tab',+ () async {+ final lines = <String>[];+ final previous = appLog;+ appLog = _Recorder(lines);+ addTearDown(() => appLog = previous);+ final f = SuperTabLaunchFixture();+ _huyDesk(f);+ for (final tab in f.app.swarms.where((s) => s.id.startsWith('desk-'))) {+ tab.name = 'SECRET_${tab.id}';+ }+ final c = await _personal(f);+ var now = DateTime(2026, 11, 3, 9);+ Future<void> sync() => withClock(+ Clock(() => now),+ () => PersonalProjects.of(f.app).sync(c),+ );+ f.connection.server+ ..refuse = {'code': 'SERVICE_UNAVAILABLE', 'message': 'Busy.'}+ ..refuseStatus = 503;+ await sync();+ expect(+ lines.where((l) => l.contains('SERVICE_UNAVAILABLE')),+ isNotEmpty,+ );+ f.connection.server.refuse = null;+ f.connection.server.unknownCommand = (command) =>+ command['type'] == 'project.rename';+ now = now.add(const Duration(seconds: 11));+ await sync();+ expect(lines.where((l) => l.contains('VALIDATION_ERROR')), isNotEmpty);+ for (final line in lines) {+ expect(line, isNot(contains('SECRET_')), reason: line);+ expect(line, isNot(contains('desk-')), reason: line);+ }+ },+ );++ // ENGINEERING.md §6 (River, 11-03): a failed rename waits, as a failed+ // create does, instead of being asked again on every sync.+ test(+ 'a refused rename of a tab\'s project waits before it is asked again',+ () async {+ final f = SuperTabLaunchFixture();+ _huyDesk(f);+ final c = await _personal(f);+ var now = DateTime(2026, 11, 3, 9);+ Future<void> sync() => withClock(+ Clock(() => now),+ () => PersonalProjects.of(f.app).sync(c),+ );+ f.connection.server.unknownCommand = (command) =>+ command['type'] == 'project.rename';+ await sync();+ expect(_commands(f, 'project.rename'), hasLength(2));+ await sync();+ expect(+ _commands(f, 'project.rename'),+ hasLength(2),+ reason: 'waits before asking again',+ );+ f.connection.server.unknownCommand = null;+ now = now.add(const Duration(seconds: 11));+ await sync();+ expect(_commands(f, 'project.rename'), hasLength(4));+ final names = [for (final p in c.snapshot!.projects) p.name];+ expect(names, containsAll(['code', 'Harness Monitor']));+ },+ );++ test('a tab with no usable name still gets a project, under a name the server takes', () async {+ final f = SuperTabLaunchFixture();+ final p = _huyDesk(f);+ f.app.swarms.firstWhere((s) => s.id == 'desk-code').name = ' ';+ f.app.swarms.firstWhere((s) => s.id == 'desk-monitor').name = 'M' * 300;+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final names = [for (final p in c.snapshot!.projects) p.name];+ expect(names, contains('Tab'));+ expect(names, contains('M' * 160));+ final tab = c.snapshot!.projects.firstWhere((p) => p.name == 'Tab');+ expect(+ PersonalProjects.of(f.app)+ .panesFor(f.app.superTabs.peek(tabId)!, tab.leadConversationId),+ [p.a1, p.a2],+ );+ });++ test('nothing is sent of a tab but its project\'s name', () async {+ final f = SuperTabLaunchFixture();+ _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final sent = f.connection.server.posts.toString();+ for (final leak in ['desk-code', 'desk-monitor', '/Users/huy', 'a1']) {+ expect(sent, isNot(contains(leak)), reason: leak);+ }+ });+ });++ group('the empty chat of a project with panes (task #2376)', () {+ Future<void> show(WidgetTester tester, SuperTabLaunchFixture f) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: const Text('Native terminals'),+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 20));+ }+ }++ Future<void> close(+ WidgetTester tester,+ SuperTabLaunchFixture f,+ SuperTabController c,+ ) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ }++ testWidgets('says how many panes the project has, and opens them', (+ tester,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final f = SuperTabLaunchFixture();+ final p = _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ final code = c.snapshot!.projects.firstWhere((p) => p.name == 'code');+ c.select(code.leadConversationId);+ await show(tester, f);+ expect(find.text('2 panes in this project'), findsOneWidget);+ expect(+ find.text('Discuss the plan with Product Manager.'),+ findsOneWidget,+ );+ await tester.tap(find.text('Show panes'));+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 20));+ }+ expect(c.groupTerminalsOpen(code.leadConversationId), isTrue);+ final swarm = f.app.swarms.firstWhere((s) => s.superTabId == tabId);+ expect(swarm.panes, [p.a1, p.a2]);+ await close(tester, f, c);+ });++ testWidgets('one pane is one pane', (tester) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final f = SuperTabLaunchFixture();+ _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ c.select(+ c.snapshot!.projects+ .firstWhere((p) => p.name == 'Harness Monitor')+ .leadConversationId,+ );+ await show(tester, f);+ expect(find.text('1 pane in this project'), findsOneWidget);+ await close(tester, f, c);+ });++ testWidgets('a project with no panes keeps today\'s empty chat', (+ tester,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final f = SuperTabLaunchFixture();+ _huyDesk(f);+ final c = await _personal(f);+ await PersonalProjects.of(f.app).sync(c);+ // The Personal Swarm's first project holds none of the person's panes.+ final first = c.snapshot!.projects.firstWhere(+ (p) => p.name == 'Pilot' || p.name == 'Personal',+ );+ c.select(first.leadConversationId);+ await show(tester, f);+ expect(find.textContaining('panes in this project'), findsNothing);+ expect(find.text('Show panes'), findsNothing);+ expect(+ find.text('Discuss the plan with Product Manager.'),+ findsOneWidget,+ );+ await close(tester, f, c);+ });+ });+group('[term]', () {testWidgets('shows the very panes the tabs hold, and the tabs stay as they are',@@ -854,3 +1231,17 @@ void main() {int _projectCount(SuperTabLaunchFixture f) =>(f.connection.server.state['projects'] as List? ?? const []).length;++class _Recorder implements AppLog {+ _Recorder(this.lines);+ final List<String> lines;++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) => lines.add('$level $category $message ${error ?? ''}');+}diff --git a/desktop/test/super_tab_threads_test.dart b/desktop/test/super_tab_threads_test.dartindex e5054f643..a238d47b2 100644--- a/desktop/test/super_tab_threads_test.dart+++ b/desktop/test/super_tab_threads_test.dart@@ -1046,17 +1046,31 @@ void main() {expect(opened, ['m1']);});- testWidgets('it is as wide as its content, within its maximum', (- tester,- ) async {- await pump(tester);- expect(tester.getSize(bar).width, lessThan(600));-- // Many repliers in a narrow chat: a few faces, and nothing overflows.- await pump(tester, width: 300, authors: 12);- expect(tester.takeException(), isNull);- expect(tester.getSize(bar).width, lessThanOrEqualTo(300));- expect(find.byType(SuperTabAvatar), findsNWidgets(5));- });+ // Huy, 2026-11-03 (#2373): as wide as Slack's, about 600 points, or the+ // message column when the chat is narrower; its arrow at the right end.+ testWidgets(+ 'it is 600 wide, or the column\'s width, its arrow at the end',+ (tester) async {+ final opened = await pump(tester);+ final wide = tester.getRect(bar);+ expect(wide.width, 600);+ expect(wide.right - tester.getRect(chevron).right, lessThan(12));+ // Its right end, far past the words, is still the bar.+ await tester.tapAt(wide.centerRight - const Offset(3, 0));+ await tester.pump();+ expect(opened, ['m1']);++ // Many repliers in a narrow chat: the column's width, a few faces, and+ // nothing overflows.+ await pump(tester, width: 300, authors: 12);+ expect(tester.takeException(), isNull);+ expect(tester.getSize(bar).width, 300);+ expect(+ tester.getRect(bar).right - tester.getRect(chevron).right,+ lessThan(12),+ );+ expect(find.byType(SuperTabAvatar), findsNWidgets(5));+ },+ );});}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex b8bab7a3c..3cad28d74 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -503,6 +503,12 @@ class ConversationServer {/// refuses a machine that cannot take the Product Manager (leadStart.ts).Map<String, String>? leadRefusal;final receipts = <String, Map<String, dynamic>>{};++ /// As the backend (store.ts): a request id used again for another command is+ /// refused with OPERATION_REUSED instead of answered from its receipt. Off by+ /// default, as most tests resend one request id freely.+ bool refuseReusedOperations = false;+ final receiptCommands = <String, String>{};final messages = <Map<String, dynamic>>[];// Route decisions by id, answered by GET .../route-decisions/:id.final routeDecisions = <String, Map<String, dynamic>>{};@@ -1029,6 +1035,16 @@ class ConversationServer {);}final operationId = body['operationId'] as String;+ final earlier = refuseReusedOperations+ ? receiptCommands[operationId]+ : null;+ if (earlier != null && earlier != jsonEncode(body['command'])) {+ throw const SuperTabFailure(+ 'OPERATION_REUSED',+ 'Use a new operation ID for a different request.',+ statusCode: 400,+ );+ }if (receipts[operationId] case final receipt?) {if (loseResentReplies > 0) {loseResentReplies--;@@ -1461,6 +1477,7 @@ class ConversationServer {'lastChangedAt': parts.clock,};receipts[operationId] = result;+ receiptCommands[operationId] = jsonEncode(body['command']);if (loseReply) {loseReply = false;throw StateError('Connection lost after commit');diff --git a/desktop/test/web/web_frame_key_hints_test.dart b/desktop/test/web/web_frame_key_hints_test.dartindex 336979f7f..5cd7aa03f 100644--- a/desktop/test/web/web_frame_key_hints_test.dart+++ b/desktop/test/web/web_frame_key_hints_test.dart@@ -11,6 +11,7 @@ import 'package:harness/core/config.dart';import 'package:harness/state/app_state.dart';import 'package:harness/shortcuts/shortcuts_browser.dart';import 'package:harness/web/parts/terminal_fonts.dart';+import 'package:harness/web/update/web_update_host.dart';import 'package:harness/web/web_entry.dart';import 'package:harness/widgets/key_hints.dart';@@ -62,4 +63,25 @@ void main() {// font a test browser never sends: let its grace run out.await tester.pump(terminalFontsGrace);});++ // A page held open across a release says so (task #2185).+ testWidgets('the web frame watches for a newer release', (tester) async {+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ addTearDown(app.dispose);+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: MaterialApp(+ builder: (context, child) => appFrame(child!),+ home: const SizedBox.shrink(),+ ),+ ),+ );+ expect(find.byType(WebUpdateHost), findsOneWidget);+ await tester.pump(terminalFontsGrace);+ });}diff --git a/desktop/test/web/web_reload_test.dart b/desktop/test/web/web_reload_test.dartnew file mode 100644index 000000000..466005490--- /dev/null+++ b/desktop/test/web/web_reload_test.dart@@ -0,0 +1,33 @@+@TestOn('browser')+library;++import 'dart:js_interop';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/web/parts/page_reload_web.dart';+import 'package:web/web.dart' as web;++/// Reload into a new release (task #2185): what an older release left in the+/// browser must not answer the reload with the old build.+void main() {+ test('Reload clears the page\'s caches, then reloads once', () async {+ await web.window.caches.open('old-release').toDart;+ final before = (await web.window.caches.keys().toDart).toDart;+ expect(before.map((name) => name.toDart), contains('old-release'));+ var reloads = 0;+ await reloadForNewVersion(reload: () => reloads++);+ expect(reloads, 1);+ // Gone by the time the call that reloads has returned.+ expect((await web.window.caches.keys().toDart).toDart, isEmpty);+ });++ test('a browser that refuses service workers and caches still reloads', () async {+ var reloads = 0;+ // A window with nothing the cleanup can use: every step fails, the reload+ // still happens.+ await reloadForNewVersion(window: _refusing(), reload: () => reloads++);+ expect(reloads, 1);+ });+}++web.Window _refusing() => ({}.jsify() as web.Window);diff --git a/desktop/test/web_build_version_test.dart b/desktop/test/web_build_version_test.dartnew file mode 100644index 000000000..324bcf57a--- /dev/null+++ b/desktop/test/web_build_version_test.dart@@ -0,0 +1,37 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/web_build_version.dart';++/// The release a page was built as, told apart from the one its host serves+/// now (task #2185, review of #2622): a page an old cache keeps must not take+/// the host's newer version for its own.+void main() {+ test('a build says the version compiled into it, or none', () {+ expect(builtWebVersion(''), isNull);+ expect(builtWebVersion(' '), isNull);+ expect(builtWebVersion(' 1.3.50 \n'), '1.3.50');+ });++ test('the page\'s own version is the built one, not what the host says', () {+ expect(webPageVersion(built: '1.3.50', declared: '1.3.51'), '1.3.50');+ });++ test('a build with none compiled in (flutter run) falls back to what it '+ 'read at start-up', () {+ expect(webPageVersion(built: '', declared: '1.3.51'), '1.3.51');+ expect(webPageVersion(built: '', declared: null), isNull);+ });++ test('a page started from an old cache learns the host runs another one, '+ 'before the first interval', () async {+ final running = await webRunningVersion(+ built: '1.3.50',+ readHost: () async => '1.3.51',+ );+ expect(running, '1.3.50');+ // Without a compiled-in version the host's answer stands in.+ expect(+ await webRunningVersion(built: '', readHost: () async => '1.3.51'),+ '1.3.51',+ );+ });+}diff --git a/desktop/test/web_release_script_test.dart b/desktop/test/web_release_script_test.dartindex ab2cc134c..b43987648 100644--- a/desktop/test/web_release_script_test.dart+++ b/desktop/test/web_release_script_test.dart@@ -49,6 +49,7 @@ for arg in "\$@"; docase "\$arg" in --output=*) out="\${arg#--output=}" ;; esacdonemkdir -p "\$out/assets"+printf '%s\\n' "\$@" > "\$out/build-args.txt"printf '%s' '$manifest' > "\$out/assets/FontManifest.json"printf '%s' '$_index' > "\$out/index.html"for asset in $assets; do@@ -116,6 +117,17 @@ void main() {final skip = Platform.isWindows ? 'needs bash and python3' : null;+ test('the build compiles its own version in, for a page an old cache keeps '+ 'to tell it is out of date', () async {+ await _release(repo, [..._others, _mono, _icons, ..._unusedLucide, _used]);++ final args = File(+ p.join(repo.path, 'build/web-release/build-args.txt'),+ ).readAsLinesSync();+ expect(args, contains('--dart-define=HARNESS_BUILD_VERSION=1.2.3'));+ expect(args, contains('--build-name=1.2.3'));+ }, skip: skip);+test('the web release drops the Lucide weights the app never uses', () async {final result = await _release(repo, [..._others,diff --git a/desktop/test/web_update_bar_test.dart b/desktop/test/web_update_bar_test.dartnew file mode 100644index 000000000..03de4018f--- /dev/null+++ b/desktop/test/web_update_bar_test.dart@@ -0,0 +1,129 @@+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/web/update/web_update_bar.dart';+import 'package:harness/web/update/web_update_watcher.dart';++/// The quiet bar a page shows once the host serves a newer release (task+/// #2185, Huy's mockup): "A new version of Harness is ready." and Reload.+void main() {+ late String? latest;+ late WebUpdateWatcher watcher;+ var reloads = 0;++ Future<void> mount(WidgetTester tester, {Widget? child}) async {+ reloads = 0;+ latest = '1.3.51';+ watcher = WebUpdateWatcher(+ running: '1.3.51',+ readLatest: () async => latest,+ );+ addTearDown(watcher.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: WebUpdateFrame(+ watcher: watcher,+ reload: () => reloads++,+ child: child ?? const Text('the app'),+ ),+ ),+ ),+ );+ }++ Finder bar() => find.byKey(const ValueKey('web-update-bar'));++ testWidgets('the same build shows nothing', (tester) async {+ await mount(tester);+ await watcher.check();+ await tester.pump();+ expect(bar(), findsNothing);+ expect(find.text('the app'), findsOneWidget);+ });++ testWidgets('a newer build shows the bar, and Reload reloads once', (+ tester,+ ) async {+ await mount(tester);+ latest = '1.3.52';+ await watcher.check();+ await tester.pump();+ expect(bar(), findsOneWidget);+ expect(find.text('A new version of Harness is ready.'), findsOneWidget);+ expect(reloads, 0);+ await tester.tap(find.byKey(const ValueKey('web-update-reload')));+ await tester.pump();+ expect(reloads, 1);+ });++ testWidgets('the bar coming does not remount the app below it', (+ tester,+ ) async {+ await mount(tester, child: const _Counter());+ await tester.tap(find.byKey(const ValueKey('counter')));+ await tester.pump();+ expect(find.text('taps 1'), findsOneWidget);+ latest = '1.3.52';+ await watcher.check();+ await tester.pump();+ expect(bar(), findsOneWidget);+ expect(find.text('taps 1'), findsOneWidget);+ });++ testWidgets('the bar sits above the app, reads in the page\'s own '+ 'surface and offers Reload to a thumb', (tester) async {+ final handle = tester.ensureSemantics();+ await mount(tester);+ latest = '1.3.52';+ await watcher.check();+ await tester.pump();+ expect(+ tester.getTopLeft(bar()).dy,+ lessThan(tester.getTopLeft(find.text('the app')).dy),+ );+ final reload = tester.getSize(+ find.byKey(const ValueKey('web-update-reload')),+ );+ expect(reload.height, greaterThanOrEqualTo(40));+ final semantics = tester.getSemantics(+ find.byKey(const ValueKey('web-update-reload')),+ );+ expect(semantics.label, 'Reload');+ handle.dispose();+ });++ testWidgets('Reload sits as far from the right edge as the text does from '+ 'the left', (tester) async {+ await mount(tester);+ latest = '1.3.52';+ await watcher.check();+ await tester.pump();+ final left =+ tester+ .getTopLeft(find.text('A new version of Harness is ready.'))+ .dx -+ tester.getTopLeft(bar()).dx;+ final right =+ tester.getTopRight(bar()).dx -+ tester.getTopRight(find.byKey(const ValueKey('web-update-reload'))).dx;+ expect(right, left);+ });+}++class _Counter extends StatefulWidget {+ const _Counter();+ @override+ State<_Counter> createState() => _CounterState();+}++class _CounterState extends State<_Counter> {+ var taps = 0;+ @override+ Widget build(BuildContext context) => TextButton(+ key: const ValueKey('counter'),+ onPressed: () => setState(() => taps++),+ child: Text('taps $taps'),+ );+}diff --git a/desktop/test/web_update_host_test.dart b/desktop/test/web_update_host_test.dartnew file mode 100644index 000000000..7721d6f37--- /dev/null+++ b/desktop/test/web_update_host_test.dart@@ -0,0 +1,127 @@+import 'dart:async';++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/web/update/web_update_host.dart';++/// The page's own watch for a newer release (task #2185): it learns which+/// release it runs, asks the host for the one it serves now, and shows the bar+/// when they differ. Native builds never mount it.+void main() {+ late String? latest;+ var reloads = 0;+ late StreamController<void> shown;++ Future<void> mount(+ WidgetTester tester, {+ String? running = '1.3.51',+ Future<String?> Function()? readRunning,+ }) async {+ reloads = 0;+ latest = '1.3.51';+ shown = StreamController<void>.broadcast();+ addTearDown(shown.close);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: WebUpdateHost(+ readRunning: readRunning ?? () async => running,+ readLatest: () async => latest,+ reload: () => reloads++,+ every: const Duration(minutes: 5),+ pageShown: shown.stream,+ child: const Text('the app'),+ ),+ ),+ ),+ );+ await tester.pump();+ }++ final bar = find.byKey(const ValueKey('web-update-bar'));++ testWidgets('a release out while the page is open shows the bar after the '+ 'next check, and Reload reloads', (tester) async {+ await mount(tester);+ expect(bar, findsNothing);+ latest = '1.3.52';+ await tester.pump(const Duration(minutes: 5));+ expect(bar, findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('web-update-reload')));+ expect(reloads, 1);+ });++ testWidgets('a page an old cache kept shows the bar at once: it need not '+ 'wait for an interval', (tester) async {+ reloads = 0;+ shown = StreamController<void>.broadcast();+ addTearDown(shown.close);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: WebUpdateHost(+ // Its own build, older than what the host now serves.+ readRunning: () async => '1.3.50',+ readLatest: () async => '1.3.51',+ reload: () => reloads++,+ pageShown: shown.stream,+ child: const Text('the app'),+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ expect(bar, findsOneWidget);+ });++ testWidgets('the page coming back to the front checks at once', (+ tester,+ ) async {+ await mount(tester);+ latest = '1.3.52';+ shown.add(null);+ // The page's event, the read, then the frame that draws it.+ await tester.pump();+ await tester.pump();+ expect(bar, findsOneWidget);+ });++ testWidgets('the same release shows nothing, however long it is open', (+ tester,+ ) async {+ await mount(tester);+ await tester.pump(const Duration(hours: 2));+ expect(bar, findsNothing);+ });++ testWidgets('a page that cannot tell its own release never shows the bar', (+ tester,+ ) async {+ await mount(tester, running: null);+ latest = '1.3.52';+ await tester.pump(const Duration(minutes: 30));+ expect(bar, findsNothing);+ expect(find.text('the app'), findsOneWidget);+ });++ testWidgets('a start-up read that fails is the same as none', (tester) async {+ await mount(tester, readRunning: () async => throw StateError('offline'));+ latest = '1.3.52';+ await tester.pump(const Duration(minutes: 30));+ expect(bar, findsNothing);+ });++ testWidgets('the app is there from the first frame, before the version is '+ 'known', (tester) async {+ final slow = Completer<String?>();+ await mount(tester, readRunning: () => slow.future);+ expect(find.text('the app'), findsOneWidget);+ slow.complete('1.3.51');+ await tester.pump();+ expect(find.text('the app'), findsOneWidget);+ });+}diff --git a/desktop/test/web_update_watcher_test.dart b/desktop/test/web_update_watcher_test.dartnew file mode 100644index 000000000..92d67d6e1--- /dev/null+++ b/desktop/test/web_update_watcher_test.dart@@ -0,0 +1,92 @@+import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/web/update/web_update_watcher.dart';++/// A page that opened on one release finds out a newer one is out: it+/// re-reads the host's release manifest, and says so once it names another+/// version (task #2185).+void main() {+ WebUpdateWatcher watcher(+ String? running,+ List<String?> reads, {+ Duration every = const Duration(minutes: 5),+ }) {+ var i = 0;+ return WebUpdateWatcher(+ running: running,+ every: every,+ readLatest: () async => reads[i < reads.length ? i++ : reads.length - 1],+ );+ }++ test('a different version is ready, the same one is not', () async {+ final same = watcher('1.3.51', ['1.3.51']);+ await same.check();+ expect(same.updateReady, isFalse);+ final newer = watcher('1.3.51', ['1.3.52']);+ await newer.check();+ expect(newer.updateReady, isTrue);+ // A rollback is also another build: Reload brings the page to it.+ final rolledBack = watcher('1.3.51', ['1.3.50']);+ await rolledBack.check();+ expect(rolledBack.updateReady, isTrue);+ });++ test('an unreadable manifest changes nothing, before or after the bar '+ 'shows', () async {+ final w = watcher('1.3.51', [null, '1.3.52', null]);+ await w.check();+ expect(w.updateReady, isFalse);+ await w.check();+ expect(w.updateReady, isTrue);+ await w.check();+ expect(w.updateReady, isTrue);+ });++ test('a read that throws is no answer either', () async {+ final w = WebUpdateWatcher(+ running: '1.3.51',+ readLatest: () async => throw StateError('offline'),+ );+ await w.check();+ expect(w.updateReady, isFalse);+ });++ test('a page that does not know its own version never says ready', () async {+ final w = watcher(null, ['1.3.52']);+ await w.check();+ expect(w.updateReady, isFalse);+ });++ test('listeners hear it once, however many checks follow', () async {+ final w = watcher('1.3.51', ['1.3.52']);+ var told = 0;+ w.addListener(() => told++);+ await w.check();+ await w.check();+ await w.check();+ expect(told, 1);+ });++ test('it checks again every interval until disposed', () {+ fakeAsync((async) {+ var reads = 0;+ final w = WebUpdateWatcher(+ running: '1.3.51',+ every: const Duration(minutes: 5),+ readLatest: () async {+ reads++;+ return '1.3.51';+ },+ )..start();+ expect(reads, 0);+ async.elapse(const Duration(minutes: 5));+ expect(reads, 1);+ async.elapse(const Duration(minutes: 10));+ expect(reads, 3);+ w.dispose();+ async.elapse(const Duration(minutes: 30));+ expect(reads, 3);+ });+ });+}diff --git a/devices/harness-pro/docs/cable.md b/devices/harness-pro/docs/cable.mdindex 00d4102cf..c9bec182f 100644--- a/devices/harness-pro/docs/cable.md+++ b/devices/harness-pro/docs/cable.md@@ -31,6 +31,7 @@ Full key list, in the order the Pro sends it:| `superTab` | `"wait-v1"` | capability: Super Tab waits on `question` (below) || `swarmCard` | `"v1"` | capability: the Swarm cards and the Lead view (frames below) || `swarmChat` | `"v1"` | capability: the chat the desktop has open on each Lead's face, and its notices (the round dial's, spec 2026-10-30-harness-pro-swarm-parity) |+| `swarmBuddy` | `"v1"` | capability: the PM and the Buddy in each Swarm project (the round dial's, same spec) || `ota` | `"v1"` | capability: the Pro takes firmware offers || `mac` | `aa:bb:...` | existing || `settings` | object | existing: brightness, character, face, voiceLang, muted, quiet, straightTitle, focusFace, scrollReversed, round |@@ -253,5 +254,22 @@ With `swarmChat`, the daemon sends the round dial's frames (`docs/device-voice-sA Swarm that leaves `supertabs`, or a Lead that leaves its Swarm's `supertab` frame, takes its rows and their toast with it: access lost sends no read.- `state` is `work` only for a working group and otherwise `done`; `ask` and `stuck` are not sent to a `swarmChat` device.- `supertab.focus` with an empty `lead` (the desktop opened the Swarm with no project, e.g. its Chat with PM) opens the Lead last shown in that Swarm, else its first.-- Voice does not follow the face. The daemon treats a `board:"pro"` hello's `voice.begin` as it did before `swarmChat`: spoken words post in the Lead conversation, never in the- group, PM or Buddy chat the desktop has open, because the Pro's rooms do not show where words go. Voice comes to the face chat in Phase 3 of the parity spec.+- Voice follows the face only from the Lead view. A `voice.begin` the Pro sends from a Lead view carries `"face":true`: the daemon posts the words in that Lead's face+ chat, the side it holds (the Buddy chat on the Buddy side), and a failed Buddy post is a `voice.error`, never a terminal turn. Without `face` (the plain agent room,+ which shows no chat) the daemon treats a `board:"pro"` hello's `voice.begin` as it did before `swarmChat`: the words post in the Lead conversation, never in the+ group, PM or Buddy chat the desktop has open. An older daemon ignores `face`.++### PM | Buddy (`swarmBuddy: "v1"`)++```+{"t":"supertab", ..., "side":"pm|buddy", "leads":[{..., "chat":"buddy", "buddies":true,+ "buddy":{"chatId":"<conversationId>","name":"diego's Buddy","engine":"claude","cells":25513,"color":"#d6a79a","live":true}}]}+{"t":"supertab.side","tab":"<superTabId>","side":"pm|buddy"} Pro to daemon: a tap on the pill+```++- With `buddies`, the Lead view has a PM | Buddy pill at the top. A tap sends `supertab.side` and shows the segment pressed until the next `supertab` for that+ Swarm, which carries the side the daemon keeps (the newest of the Pro and the desktop wins).+- The face chat `buddy` draws the Buddy's avatar (`cells`, `color`: the desktop pattern), its name in lilac and "offline" while `live` is false. With the Buddy+ side and no `buddy`: "No Buddy here yet".+- A `supertab.notice` with `chat:"buddy"` is quiet: no toast, no Notices row, no beep; a lilac dot on the pill's Buddy segment until the Buddy side opens.+- A link drop clears the dot.diff --git a/devices/harness-pro/firmware/main/CMakeLists.txt b/devices/harness-pro/firmware/main/CMakeLists.txtindex 9c315ce14..6ce369637 100644--- a/devices/harness-pro/firmware/main/CMakeLists.txt+++ b/devices/harness-pro/firmware/main/CMakeLists.txt@@ -33,6 +33,7 @@ idf_component_register("display/terminal.c""display/scroll.c""pod/home/ph_agent.c"+ "pod/home/ph_avatar.c""pod/home/ph_bubble.c""pod/home/ph_chrome.c""pod/home/ph_inbox.c"diff --git a/devices/harness-pro/firmware/main/app/pod_glue.c b/devices/harness-pro/firmware/main/app/pod_glue.cindex 0a1ea3a04..59c03dee5 100644--- a/devices/harness-pro/firmware/main/app/pod_glue.c+++ b/devices/harness-pro/firmware/main/app/pod_glue.c@@ -31,6 +31,12 @@ void pod_ui_render(pod_ui_t *u, ht_scene_t *scene, uint32_t now_ms)u->dirty = false;return;}+ { // drawing means the glass is lit: the Buddy chat on the face of a Lead has been seen, its dot goes+ const pod_frame_t *t = top(u);+ const pod_swarm_t *sw = NULL;+ const pod_lead_t *l = t && t->view == POD_V_LEAD ? pod_nav_lead(&u->nav, &u->model, &sw) : NULL;+ if (l && l->chat == POD_CHAT_BUDDY && pod_model_buddy_mark(&u->model, sw->id, l->id, false)) u->dirty = true;+ }pod_nav_flip_recaps(&u->nav, &u->model); // the clock alone can end a stale Working: show the recap it opens on// The banner shows while its entry is still unread, the time has not run out, the cable is up and nobody is recording.const pod_unread_t *ban = NULL;@@ -70,8 +76,11 @@ static pod_out_t synced(pod_ui_t *u)return o;}+void pod_ui_set_swarm_remote(pod_ui_t *u, bool on) { u->swarm_remote = on; }+pod_out_t pod_ui_link(pod_ui_t *u, bool up){+ if (!up) u->swarm_remote = false; // the next welcome says againif (up && !u->model.linked) u->sweep.restart = true;if (!up) pod_ui_sweep_abort(u);if (!up || !u->model.linked) { // the daemon forgets the open recap and any focus with its link: nothing queued or open carries over@@ -281,14 +290,30 @@ static bool asks_here(const pod_model_t *m, const pod_agent_t *a)return pod_model_eff(m, a) == POD_ASKING && pod_model_attention(m, a) == POD_ATTN_NONE;}+// The id a tap on this frame talks to: a Lead view's `local` harness whenever set (on the roster or not: the daemon pins the face by it, as on the round),+// else its own Swarm id when the daemon routes it (swarm.remote); an agent's screen its harness (f->agent). Else NULL.+static const char *talk_id(const pod_ui_t *u, const pod_frame_t *f)+{+ if (f->view != POD_V_LEAD) return f->agent[0] ? f->agent : NULL;+ const pod_lead_t *l = pod_nav_lead(&u->nav, &u->model, NULL);+ if (!l) return NULL;+ return l->local[0] ? l->local : u->swarm_remote && f->lead_id[0] ? f->lead_id : NULL;+}+static const char *talk_target(const pod_ui_t *u){const pod_frame_t *f = top(u);if (!f || u->ban_touch) return NULL;if (u->start_y < POD_BAR_H) return NULL; // nothing in the top band talks- if (u->hit_valid && (u->hit.action == POD_A_BACK || u->hit.action == POD_A_INBOX)) return NULL;- const char *id = f->view == POD_V_AGENT || f->view == POD_V_RECAP || f->view == POD_V_LEAD ? f->agent : NULL; // a Lead view's agent is its local harness (empty for a remote Lead: no talk)- const pod_agent_t *a = id ? pod_model_find(&u->model, id) : NULL;+ if (u->hit_valid && (u->hit.action == POD_A_BACK || u->hit.action == POD_A_INBOX || u->hit.action == POD_A_SIDE)) return NULL;+ const char *id = f->view == POD_V_AGENT || f->view == POD_V_RECAP || f->view == POD_V_LEAD ? talk_id(u, f) : NULL;+ if (!id) return NULL;+ if (f->view == POD_V_LEAD) { // words for a Swarm face go to its chat, not the terminal: a question there blocks nothing. The Buddy side of a Lead that has none says "No Buddy here yet": nothing there talks (the words would reach the Lead's shared chat)+ const pod_swarm_t *sw = NULL;+ const pod_lead_t *l = pod_nav_lead(&u->nav, &u->model, &sw);+ return l && sw && pod_model_no_buddy(&u->model, sw, l) ? NULL : id;+ }+ const pod_agent_t *a = pod_model_find(&u->model, id);return a && !asks_here(&u->model, a) ? id : NULL;}static bool wide(int dx, int dy) { return iabs(dx) * 2 > iabs(dy) * 3; }@@ -343,17 +368,20 @@ static pod_out_t talk_fire(pod_ui_t *u, uint32_t now_ms)pod_out_t none;memset(&none, 0, sizeof none);const pod_frame_t *t = top(u);- if (!t || u->nav.depth != u->talk_depth || t->view != u->talk_view || strcmp(t->agent, u->talk_agent))+ const char *now_id = t ? talk_id(u, t) : NULL;+ if (!t || u->nav.depth != u->talk_depth || t->view != u->talk_view || !now_id || strcmp(now_id, u->talk_agent))return none; // the screen or the agent changed under the finger since the DOWN: not this tap's any morechar id[ID_MAX];pod_copy_str(id, sizeof id, u->talk_agent);- const pod_agent_t *ag = pod_model_find(&u->model, id);- if (!ag || asks_here(&u->model, ag)) return none;- if (ag->state == POD_OFFLINE) {+ const bool lead = t->view == POD_V_LEAD; // a Swarm face: its words go to its chat, so no machine's question or state gates them+ const pod_agent_t *ag = lead ? NULL : pod_model_find(&u->model, id);+ if (!lead && !ag) return none;+ if (ag && asks_here(&u->model, ag)) return none;+ if (ag && ag->state == POD_OFFLINE) {pod_ui_notice(u, "That machine is offline", now_ms);return none;}- pod_out_t o = pod_nav_act(&u->nav, &u->model, POD_A_TALK, 0, now_ms);+ pod_out_t o = pod_nav_act(&u->nav, &u->model, POD_A_TALK, lead, now_ms);if (o.fx != POD_FX_VOICE_BEGIN) {u->dirty = true;return none;@@ -364,15 +392,17 @@ static pod_out_t talk_fire(pod_ui_t *u, uint32_t now_ms)}// ---- the Lead view's frames for the daemon -----static bool sup_push(pod_ui_t *u, const char *t, const char *tab, const char *lead)+static bool sup_push_side(pod_ui_t *u, const char *t, const char *tab, const char *lead, const char *side){if (u->sup_qn >= POD_SUPERTAB_OUT_MAX) return false; // a burst past the queue is lost, like any frame on a busy link: the caller counts it as not sentpod_supertab_out_t *o = &u->sup_q[u->sup_qn++];o->t = t;pod_copy_str(o->tab, sizeof o->tab, tab);pod_copy_str(o->lead, sizeof o->lead, lead);+ pod_copy_str(o->side, sizeof o->side, side);return true;}+static bool sup_push(pod_ui_t *u, const char *t, const char *tab, const char *lead) { return sup_push_side(u, t, tab, lead, ""); }// A tap on a Swarm chat's notice (its toast or its Notices row): read the entry and open that Lead's view, the desktop told to select it. Not Notices.static void swarm_entry_open(pod_ui_t *u, const pod_unread_t *e)@@ -626,6 +656,19 @@ pod_out_t pod_ui_touch(pod_ui_t *u, bool down, int x, int y, uint32_t now_ms, boreturn none;}}+ // The Lead view's pill (POD_A_SIDE: arg = the side, id = the Swarm's id): the side is asked of the daemon, the tapped segment shows at once (until the Swarm's+ // next frame) and the Buddy's dot goes with the tap. The Swarm must still be held; nothing else happens.+ if (u->hit.id[0] && u->hit.action == POD_A_SIDE) {+ const pod_swarm_t *sw = pod_model_swarm(&u->model, u->hit.id);+ if (sw) {+ const pod_side_t side = arg == POD_SIDE_BUDDY ? POD_SIDE_BUDDY : POD_SIDE_PM;+ if (pod_ui_supertab_side(u, sw->id, side)) pod_model_side_press(&u->model, sw->id, side, now_ms);+ const int j = top(u) ? pod_model_lead_index(sw, top(u)->lead_id) : -1; // the Lead on screen+ if (side == POD_SIDE_BUDDY && j >= 0) pod_model_buddy_mark(&u->model, sw->id, sw->leads[j].id, false);+ }+ *changed = true;+ return none;+ }if (arg == -1 && u->hit.id[0]) { *changed = true; return none; } // what it named is gone: redraw, open nothingif (u->hit.action == POD_A_OPEN_NOTIF && arg >= 0 && arg < u->model.unread_count && u->model.unread[arg].tab[0]) { swarm_entry_open(u, &u->model.unread[arg]); *changed = true; return none; }if (u->hit.action == POD_A_OPEN_NOTIF && arg >= 0 && arg < u->model.unread_count && notice_lead(u, u->model.unread[arg].agent)) { *changed = true; return none; }@@ -674,6 +717,12 @@ bool pod_ui_talking(const pod_ui_t *u)return f && f->view == POD_V_TALK;}+bool pod_ui_talking_to_swarm(const pod_ui_t *u)+{+ const pod_frame_t *f = top(u);+ return f && f->view == POD_V_TALK && f->swarm[0];+}+void pod_ui_talk_over(pod_ui_t *u){pod_nav_talk_over(&u->nav); // back on the screen TALK came from, same stack; no ABORT: nothing records@@ -951,12 +1000,18 @@ bool pod_ui_notify_text(pod_ui_t *u, const char *agent_id, pod_tier_t tier, consreturn tier == POD_TIER_ALERT;}-bool pod_ui_swarm_notice(pod_ui_t *u, const char *tab, const char *lead, const char *chat_id, const char *text, bool awake, uint32_t now_ms)+bool pod_ui_swarm_notice(pod_ui_t *u, const char *tab, const char *lead, const char *chat, const char *chat_id, const char *text, bool awake, uint32_t now_ms){pod_model_clock(&u->model, now_ms);const pod_swarm_t *sw = pod_model_swarm(&u->model, tab);if (!sw || pod_model_lead_index(sw, lead) < 0) return false;const pod_frame_t *t = top(u);+ if (chat && !strcmp(chat, "buddy")) { // the Buddy's quiet notice: a dot on its segment, no row, no toast, no beep+ pod_lead_t *bl = &((pod_swarm_t *)sw)->leads[pod_model_lead_index(sw, lead)];+ const bool seen = awake && t && t->view == POD_V_LEAD && !strcmp(t->swarm, sw->id) && !strcmp(t->lead_id, lead) && bl->chat == POD_CHAT_BUDDY; // its chat is the one on screen+ if (!seen && pod_model_buddy_mark(&u->model, sw->id, lead, true)) u->dirty = true;+ return false;+ }pod_model_swarm_notice(&u->model, sw->id, lead, chat_id, text, now_ms); // filed first, so a seen one also replaces this Lead's older rowconst pod_lead_t *face = awake && t && t->view == POD_V_LEAD && !strcmp(t->swarm, sw->id) && !strcmp(t->lead_id, lead) ? &sw->leads[pod_model_lead_index(sw, lead)] : NULL;if (face && !strcmp(face->chat_id, chat_id ? chat_id : "")) { // the face shows that very chat: seen at once@@ -976,6 +1031,9 @@ bool pod_ui_swarm_notice(pod_ui_t *u, const char *tab, const char *lead, const cvoid pod_ui_swarm_notice_read(pod_ui_t *u, const char *tab, const char *lead, const char *chat_id){+ const pod_swarm_t *bs = pod_model_swarm(&u->model, tab); // the Buddy chat became the open one: its dot goes+ const int bj = pod_model_lead_index(bs, lead);+ if (bj >= 0 && chat_id && !strcmp(chat_id, bs->leads[bj].buddy.chat_id) && pod_model_buddy_mark(&u->model, tab, lead, false)) u->dirty = true;if (!pod_model_swarm_notice_read(&u->model, tab, lead, chat_id)) return;if (u->ban_on && !strcmp(u->ban_tab, tab) && !strcmp(u->ban_agent, lead)) u->ban_on = false;u->dirty = true;@@ -1129,6 +1187,20 @@ int pod_ui_take_supertab(pod_ui_t *u, pod_supertab_out_t out[], int max)return n;}+// The side frame could not be sent: the tapped segment would never be answered, so it is not kept.+void pod_ui_side_unsent(pod_ui_t *u, const char *tab)+{+ if (u->model.side_press == POD_SIDE_NONE || strcmp(u->model.side_press_swarm, tab)) return;+ pod_model_side_press(&u->model, tab, POD_SIDE_NONE, u->model.clock_ms);+ u->dirty = true;+}++bool pod_ui_supertab_side(pod_ui_t *u, const char *tab, pod_side_t side)+{+ if (!tab || !tab[0] || (side != POD_SIDE_PM && side != POD_SIDE_BUDDY)) return false;+ return sup_push_side(u, "supertab.side", tab, "", side == POD_SIDE_BUDDY ? "buddy" : "pm");+}+void pod_ui_supertab_unsent(pod_ui_t *u, const pod_supertab_out_t *frame){if (!frame || !frame->t) return;diff --git a/devices/harness-pro/firmware/main/app/pod_glue.h b/devices/harness-pro/firmware/main/app/pod_glue.hindex 845b0396c..df2963202 100644--- a/devices/harness-pro/firmware/main/app/pod_glue.h+++ b/devices/harness-pro/firmware/main/app/pod_glue.h@@ -21,7 +21,7 @@ enum { POD_BAR_H = 72, POD_BAR_SWIPE = 80, POD_EDGE_SWIPE = 80, POD_BOTTOM_Y = 6typedef struct { const char *id, *name, *engine, *machine; } pod_roster_row_t;// One frame for the daemon about the Swarm cards: `t` is "supertab.select", "supertab.open" or "supertab.recap.get" (a literal), lead "" closes the open recap.-typedef struct { const char *t; char tab[ID_MAX], lead[ID_MAX]; } pod_supertab_out_t;+typedef struct { const char *t; char tab[ID_MAX], lead[ID_MAX], side[8]; } pod_supertab_out_t; // side: only "supertab.side" ("pm" / "buddy")enum { POD_SUPERTAB_OUT_MAX = 8, POD_SUPERTAB_RETRIES = 5, POD_SUPERTAB_RETRY_MS = 3000 };typedef struct {@@ -85,6 +85,7 @@ typedef struct {uint32_t down_ms;// Tap to talk: armed at a DOWN that may talk, fired by its lift if the finger stayed within POD_TAP_SLOP (pod_ui_touch, on the touch task).bool talk_armed, bar, edge; // bar: the contact began in the top edge (y < POD_BAR_H) of a non-Talk screen: a swipe down opens the Inbox; edge: the contact began in the bottom zone (y >= POD_BOTTOM_Y) of a room or a recap: a swipe up goes Home, and it scrolls nothing+ bool swarm_remote; // the daemon routes a voice turn named with a Lead's Swarm id (welcome `swarm.remote`): a remote Lead talks. Cleared with the linkbool hands_free; // a tap started a recording; the next new tap sends it (cleared by END, ABORT, talk_over)uint8_t talk_depth;pod_view_t talk_view; // the screen (nav depth and view) and agent the tap was armed on: it fires only there@@ -160,6 +161,10 @@ pod_out_t pod_ui_focus(pod_ui_t *, const char *agent_id, uint32_t now_ms);int pod_ui_take_supertab(pod_ui_t *, pod_supertab_out_t out[], int max);// A frame taken by pod_ui_take_supertab that could not be sent (the link was busy): open / recap.get count as not sent, so the retry comes again (a failed retry is not counted);// the closing open (no lead) is owed until it is sent, unless a Lead opened since.+// The person picked a side of that Swarm: queue `supertab.side`. False when the queue is full or `side` is NONE. A frame that could not be sent is dropped, not+// retried (pod_ui_supertab_unsent ignores it): the next supertab frame shows the side the desktop really holds.+bool pod_ui_supertab_side(pod_ui_t *, const char *tab, pod_side_t side);+void pod_ui_side_unsent(pod_ui_t *, const char *tab);void pod_ui_supertab_unsent(pod_ui_t *, const pod_supertab_out_t *frame);// The start, armed by a real link down -> up (pod_ui_link): once swarms of this link have arrived, if the stack is at the@@ -218,7 +223,7 @@ bool pod_ui_notify(pod_ui_t *, const char *agent_id, pod_tier_t tier, bool awake// or on its Notices row opens that Lead (and selects it on the desktop) instead of Notices. Returns true when the caller must wake the glass and beep. Nothing// is filed for a Swarm or Lead the model does not hold. If that Lead's own view is on screen and the glass is lit, it is read at once: no entry, no toast, false.// The read (supertab.notice.read) drops the entry of that chat only, and ends its toast if that is the one showing.-bool pod_ui_swarm_notice(pod_ui_t *, const char *tab, const char *lead, const char *chat_id, const char *text, bool awake, uint32_t now_ms);+bool pod_ui_swarm_notice(pod_ui_t *, const char *tab, const char *lead, const char *chat, const char *chat_id, const char *text, bool awake, uint32_t now_ms);void pod_ui_swarm_notice_read(pod_ui_t *, const char *tab, const char *lead, const char *chat_id);// notif.replace: begin (clears the list), one row per item, end. The toast is not shown for these.void pod_ui_notif_begin(pod_ui_t *);@@ -240,9 +245,13 @@ pod_out_t pod_ui_touch_cancel(pod_ui_t *); // the contact is dropped; an open// ---- voice and clock ---------------------------------------------------------------------------------------bool pod_ui_talking(const pod_ui_t *);+// The welcome's `swarm.remote` (pro_app_features): a Lead with no harness here, or its Buddy, is talked to by the Lead's Swarm id. pod_ui_link(false) clears it.+void pod_ui_set_swarm_remote(pod_ui_t *, bool on);// Leave a TALK frame whose recording is already over (refused start, link loss, the 600 s cap): back to the Agent// or Recap screen it came from, same stack, no effect to perform.void pod_ui_talk_over(pod_ui_t *);+// TALK opened from a Lead view: the words go to that Swarm chat (the daemon's swarmSay), so no terminal turn follows to end "sending".+bool pod_ui_talking_to_swarm(const pod_ui_t *);// SEND was tapped but the recorder had not started, so nothing is sent: forget the send (no send scene), say// "Not sent" for a moment. The frame is already back on the Agent screen.void pod_ui_unsend(pod_ui_t *, uint32_t now_ms);diff --git a/devices/harness-pro/firmware/main/app/pro_app.c b/devices/harness-pro/firmware/main/app/pro_app.cindex b78d84c6e..92f9f3c0b 100644--- a/devices/harness-pro/firmware/main/app/pro_app.c+++ b/devices/harness-pro/firmware/main/app/pro_app.c@@ -17,6 +17,7 @@#include "app/pro_voice.h"#include "audio/audio_capture.h"#include "audio/pro_recorder.h"+#include "cable/cable_features.h"#include "cable/cable_link.h"#include "cable/pro_cable.h"#include "pro_app_api.h"@@ -164,12 +165,21 @@ static __attribute__((noinline)) void send_supertabs(void)const int n = pod_ui_take_supertab(&s_pod, q, POD_SUPERTAB_OUT_MAX);if (s_pod.model.revision != rev) change(); // asking for a recap puts it LOADING: a change no feed announced (the flag is the model's revision: not consumed here)pro_app_unlock();- bool lost[POD_SUPERTAB_OUT_MAX] = {0};+ bool lost[POD_SUPERTAB_OUT_MAX] = {0}, side_lost[POD_SUPERTAB_OUT_MAX] = {0};bool any = false;- for (int i = 0; i < n; i++) any |= lost[i] = !pro_cable_supertab_send(q[i].t, q[i].tab, q[i].lead);+ for (int i = 0; i < n; i++) {+ if (!strcmp(q[i].t, "supertab.side")) { // not owed again: the next supertab frame shows the true side+ if (!pro_cable_supertab_side(q[i].tab, q[i].side)) { lost[i] = false; side_lost[i] = true; any = true; }+ continue;+ }+ any |= lost[i] = !pro_cable_supertab_send(q[i].t, q[i].tab, q[i].lead);+ }if (!any) return;pro_app_lock(); // a frame the link dropped is owed again (open / recap.get are retried)- for (int i = 0; i < n; i++) if (lost[i]) pod_ui_supertab_unsent(&s_pod, &q[i]);+ for (int i = 0; i < n; i++) {+ if (lost[i]) pod_ui_supertab_unsent(&s_pod, &q[i]);+ if (side_lost[i]) { pod_ui_side_unsent(&s_pod, q[i].tab); change(); } // the tapped segment would never be answered+ }pro_app_unlock();}@@ -307,6 +317,13 @@ static void show_updated(void);// ---- the link -------------------------------------------------------------------------------------------+void pro_app_features(uint32_t features)+{+ pro_app_lock();+ pod_ui_set_swarm_remote(&s_pod, (features & CABLE_FEATURE_SWARM_REMOTE) != 0);+ pro_app_unlock();+}+void pro_app_link(bool up, const char *machine){(void)machine;@@ -404,9 +421,8 @@ void pro_app_supertab_focus(const char *tab, const char *lead)void pro_app_supertab_notice(const char *tab, const char *lead, const char *chat, const char *chat_id, const char *text){- if (chat && !strcmp(chat, "buddy")) return; // the Buddy's quiet notice is a dot on its button, not a row or a toastpro_app_lock();- if (pod_ui_swarm_notice(&s_pod, tab, lead, chat_id, text, !pro_app_asleep(), ms())) alert_locked();+ if (pod_ui_swarm_notice(&s_pod, tab, lead, chat, chat_id, text, !pro_app_asleep(), ms())) alert_locked();settle((pod_out_t){0});leave();}@@ -674,7 +690,8 @@ const char *pro_app_voice_block_reason(const char *agent_id){const char *why = NULL;pro_app_lock();- const pod_agent_t *pa = id_ok(agent_id) ? pod_model_find(&s_pod.model, agent_id) : NULL;+ // Words for a Swarm face go to its chat (the round's rule): the terminal's pane type, machine and question gate nothing there.+ const pod_agent_t *pa = id_ok(agent_id) && !pod_ui_talking_to_swarm(&s_pod) ? pod_model_find(&s_pod.model, agent_id) : NULL;if (pod_ui_updating(&s_pod) || atomic_load(&s_updating)) { // the flag alone: an offer's gate holds voice off before its screenwhy = "Updating"; // a recording over a firmware write would starve it (owner, 2026-10-11)} else if (!s_linked) {@@ -703,8 +720,10 @@ void pro_app_voice_result(int kind, const char *text)if (!pro_voice_open()) return; // a reply nobody waits forpro_voice_close(); // MUST end the state, or the next start is refused (P22)pro_app_lock();- if (kind != PRO_VOICE_OK) pod_ui_talk_over(&s_pod); // an error leaves the voice screen; a sent clip stays on it, sending- if (kind == PRO_VOICE_OK && text && text[0] && held(text)) settle(pod_ui_sent(&s_pod, text, ms())); // Working until its turn speaks+ // An error leaves the voice screen; a sent clip stays on it, sending, until its turn speaks. Words for a Swarm face were posted in+ // its chat (the round's rule): no turn of that harness follows, so the transcript is the end.+ if (kind != PRO_VOICE_OK || pod_ui_talking_to_swarm(&s_pod)) pod_ui_talk_over(&s_pod);+ else if (text && text[0] && held(text)) settle(pod_ui_sent(&s_pod, text, ms())); // Working until its turn speaksif (kind == PRO_VOICE_ERROR) // owner decision 2: the daemon's message, as Pod's noticepod_ui_notice(&s_pod, text && text[0] ? text : "Voice failed", ms());change();@@ -716,8 +735,11 @@ static void voice_begin_effect(const char *agent){const char *why = pro_app_voice_block_reason(agent);const bool was_open = pro_voice_open();+ pro_app_lock();+ const bool face = pod_ui_talking_to_swarm(&s_pod); // a Lead view's talk: its words are for the face chat it shows+ pro_app_unlock();if (!why) {- pro_voice_begin(agent);+ pro_voice_begin(agent, face);// The offer's gate raises s_updating BEFORE it reads whether voice is open, and a start opens voice BEFORE this reads// s_updating: one of the two always sees the other, so a recording never starts over an accepted update.if (atomic_load(&s_updating)) { pro_voice_end(false); why = "Updating"; }diff --git a/devices/harness-pro/firmware/main/app/pro_voice.h b/devices/harness-pro/firmware/main/app/pro_voice.hindex 72f628c71..d19d69f28 100644--- a/devices/harness-pro/firmware/main/app/pro_voice.h+++ b/devices/harness-pro/firmware/main/app/pro_voice.h@@ -12,7 +12,7 @@ bool pro_voice_init(void);// Start a recording for `agent_id` (a gate-checked agent). After it returns pro_voice_start_pending() is true until// the recorder is running; false at once if the start was refused.-void pro_voice_begin(const char *agent_id);+void pro_voice_begin(const char *agent_id, bool face); // face: spoken on a Lead view (pro_cable_voice_begin)// send=true: stop and send what was recorded (the reply arrives as pro_app_voice_result). send=false: discard it.void pro_voice_end(bool send);diff --git a/devices/harness-pro/firmware/main/audio/pro_recorder.c b/devices/harness-pro/firmware/main/audio/pro_recorder.cindex c02d697a7..69ed07c09 100644--- a/devices/harness-pro/firmware/main/audio/pro_recorder.c+++ b/devices/harness-pro/firmware/main/audio/pro_recorder.c@@ -32,6 +32,7 @@ static atomic_bool s_active, s_recording, s_stop, s_abort, s_quiet, s_capture_dostatic atomic_uint s_level;static portMUX_TYPE s_mux = portMUX_INITIALIZER_UNLOCKED;static char s_agent[ID_MAX], s_upload[24], s_lang[CFG_VLANG_MAX];+static bool s_face; // spoken on a Lead view (pro_cable_voice_begin)static uint32_t s_produced, s_high_water, s_read_max_us;static void capture(void *unused)@@ -95,13 +96,14 @@ static void sender(void *unused)if (!atomic_load(&s_active)) continue;char agent[ID_MAX], upload[24], lang[CFG_VLANG_MAX];portENTER_CRITICAL(&s_mux);+ const bool face = s_face;snprintf(agent, sizeof agent, "%s", s_agent);snprintf(upload, sizeof upload, "%s", s_upload);snprintf(lang, sizeof lang, "%s", s_lang);portEXIT_CRITICAL(&s_mux);const int64_t began = esp_timer_get_time();xTaskNotifyGive(s_capture_task);- if (!pro_cable_voice_begin(agent, lang, AUDIO_SAMPLE_RATE, upload)) atomic_store(&s_abort, true);+ if (!pro_cable_voice_begin(agent, face, lang, AUDIO_SAMPLE_RATE, upload)) atomic_store(&s_abort, true);uint32_t delivered = 0, send_max_us = 0;for (;;) {if (atomic_load(&s_abort)) break;@@ -169,7 +171,7 @@ bool pro_rec_init(void)return true;}-bool pro_rec_start(const char *agent_id, const char *lang, const char *upload_id)+bool pro_rec_start(const char *agent_id, bool face, const char *lang, const char *upload_id){if (!s_capture_task || !s_sender_task) {ESP_LOGE(TAG, "audio unavailable");@@ -181,6 +183,7 @@ bool pro_rec_start(const char *agent_id, const char *lang, const char *upload_idreturn false;}snprintf(s_agent, sizeof s_agent, "%s", agent_id ? agent_id : "");+ s_face = face;snprintf(s_upload, sizeof s_upload, "%s", upload_id ? upload_id : "");snprintf(s_lang, sizeof s_lang, "%s", lang ? lang : "");s_produced = s_high_water = s_read_max_us = 0;diff --git a/devices/harness-pro/firmware/main/audio/pro_recorder.h b/devices/harness-pro/firmware/main/audio/pro_recorder.hindex 6437215c3..4ff048afc 100644--- a/devices/harness-pro/firmware/main/audio/pro_recorder.h+++ b/devices/harness-pro/firmware/main/audio/pro_recorder.h@@ -14,7 +14,7 @@ bool pro_rec_init(void);// Begin one utterance: the capture task opens the mic, the sender sends voice.begin and then the PCM. False when// the recorder is unavailable or a previous utterance is still being finalised.-bool pro_rec_start(const char *agent_id, const char *lang, const char *upload_id);+bool pro_rec_start(const char *agent_id, bool face, const char *lang, const char *upload_id);// Finish normally: stop capturing, drain the ring, send voice.end.void pro_rec_stop(void);// Discard it. quiet=true: the cable is dead, send nothing (otherwise voice.abort goes out).diff --git a/devices/harness-pro/firmware/main/audio/pro_voice.c b/devices/harness-pro/firmware/main/audio/pro_voice.cindex a355b325d..2f2765fc8 100644--- a/devices/harness-pro/firmware/main/audio/pro_voice.c+++ b/devices/harness-pro/firmware/main/audio/pro_voice.c@@ -63,7 +63,7 @@ extern void pro_voice_test_step(int step);#define TEST_STEP(n) ((void)0)#endif-void pro_voice_begin(const char *agent_id)+void pro_voice_begin(const char *agent_id, bool face){bool expected = false;if (!atomic_compare_exchange_strong(&s_starting, &expected, true)) return; // another begin is mid-flight@@ -87,7 +87,7 @@ void pro_voice_begin(const char *agent_id)portEXIT_CRITICAL(&s_mux);atomic_store(&s_waiting, false);TEST_STEP(4);- const bool started = pro_rec_start(agent_id, lang, upload); // unavailable, or the last clip is still finishing+ const bool started = pro_rec_start(agent_id, face, lang, upload); // unavailable, or the last clip is still finishingTEST_STEP(5);if (!started) atomic_store(&s_open, false);atomic_store(&s_starting, false);diff --git a/devices/harness-pro/firmware/main/cable/cable_features.c b/devices/harness-pro/firmware/main/cable/cable_features.cindex cf66638a6..9d44b1352 100644--- a/devices/harness-pro/firmware/main/cable/cable_features.c+++ b/devices/harness-pro/firmware/main/cable/cable_features.c@@ -13,6 +13,7 @@ uint32_t cable_features_parse(const cJSON *welcome)if (++count > 16 || !cJSON_IsString(item)) return 0;if (!strcmp(item->valuestring, "player.library")) result |= CABLE_FEATURE_PLAYER_LIBRARY;if (!strcmp(item->valuestring, "resync")) result |= CABLE_FEATURE_RESYNC;+ if (!strcmp(item->valuestring, "swarm.remote")) result |= CABLE_FEATURE_SWARM_REMOTE;}return result;}diff --git a/devices/harness-pro/firmware/main/cable/cable_features.h b/devices/harness-pro/firmware/main/cable/cable_features.hindex 56d2a4723..7af229e37 100644--- a/devices/harness-pro/firmware/main/cable/cable_features.h+++ b/devices/harness-pro/firmware/main/cable/cable_features.h@@ -2,10 +2,11 @@#include <stdint.h>typedef struct cJSON cJSON;-// The Pro reads two welcome features: the player library (the daemon answers `player.library.get`) and `resync`.+// The Pro reads three welcome features: the player library (the daemon answers `player.library.get`), `resync` and `swarm.remote`.enum {CABLE_FEATURE_PLAYER_LIBRARY = 1u << 0,CABLE_FEATURE_RESYNC = 1u << 1, // the daemon answers `resync` with a full snapshot (older ones do not know it)+ CABLE_FEATURE_SWARM_REMOTE = 1u << 2, // the daemon routes a voice turn named with a Lead's Swarm id (a Lead on another machine, or its Buddy)};// Optional welcome field. Older daemons omit it; unknown names are ignored. More than 16 entries, or andiff --git a/devices/harness-pro/firmware/main/cable/cable_types.h b/devices/harness-pro/firmware/main/cable/cable_types.hindex c8836de57..b93766d82 100644--- a/devices/harness-pro/firmware/main/cable/cable_types.h+++ b/devices/harness-pro/firmware/main/cable/cable_types.h@@ -77,6 +77,14 @@ enum { SWARMS_CARD_MAX = 16, SWARM_LEADS_MAX = 12, SWARM_TEXT_MAX = 1501 }; //typedef enum { POD_LEAD_ASK, POD_LEAD_STUCK, POD_LEAD_WORK, POD_LEAD_DONE } pod_lead_state_t; // needs you, stuck, working, donetypedef enum { POD_CHAT_NONE, POD_CHAT_LEAD, POD_CHAT_PM, POD_CHAT_GROUP, POD_CHAT_BUDDY } pod_chat_t; // the chat the Lead's face showstypedef enum { POD_RECAP_NONE, POD_RECAP_LOADING, POD_RECAP_LOADED, POD_RECAP_EMPTY } pod_recap_state_t;+typedef enum { POD_SIDE_NONE, POD_SIDE_PM, POD_SIDE_BUDDY } pod_side_t; // the side of a Swarm the person looks at (NONE: the frame named none)+typedef struct {+ char chat_id[ID_MAX], name[49], engine[16]; // the reader's Buddy chat; name as project: 48 bytes + NUL, cut on a codepoint+ uint16_t cells; // the avatar's pattern, 15 bits (0..32767)+ uint32_t color; // 0xRRGGBB+ bool live; // the Buddy is answering now+} pod_buddy_t;+enum { POD_BUDDY_INK = 0xC49BFF }; // the lilac of a Buddy: its default colour, the pill's segment, the dot, its nametypedef struct {char id[ID_MAX], projectId[ID_MAX], project[49], engine[16], owner[49], local[ID_MAX]; // owner: another person's machine; local: the harness to talk topod_lead_state_t state;@@ -86,10 +94,15 @@ typedef struct {pod_recap_state_t recap;char *text; // the Lead's last message, PSRAM, owned by the model (NULL unless LOADED); the cable side leaves it NULLuint32_t text_at; // when it was written (epoch seconds)+ bool buddies; // the Lead has a Buddy side (JSON true only)+ bool has_buddy; // `buddy` is a usable block+ bool buddy_unread; // the Buddy spoke while the person was elsewhere; device-local, a frame never sets it+ pod_buddy_t buddy;} pod_lead_t;typedef struct {char id[ID_MAX], tab[ID_MAX], name[49];uint16_t count; // workspaces (projects that have a Lead)uint8_t lead_n;+ pod_side_t side; // the side the desktop shows for this Swarmpod_lead_t leads[SWARM_LEADS_MAX]; // in card order} pod_swarm_t;diff --git a/devices/harness-pro/firmware/main/cable/pro_cable.c b/devices/harness-pro/firmware/main/cable/pro_cable.cindex 795aec53c..d95ae2d98 100644--- a/devices/harness-pro/firmware/main/cable/pro_cable.c+++ b/devices/harness-pro/firmware/main/cable/pro_cable.c@@ -4,6 +4,7 @@#include <stdatomic.h>#include <stdio.h>#include <stdlib.h>+#include <ctype.h>#include <string.h>#include "board/board.h"@@ -146,6 +147,10 @@ static bool msg_number(cJSON **root, const char *key, double value){return *root && msg_check(root, cJSON_AddNumberToObject(*root, key, value) != NULL);}+static bool msg_bool(cJSON **root, const char *key, bool value)+{+ return *root && msg_check(root, cJSON_AddBoolToObject(*root, key, value) != NULL);+}const char *pro_cable_fw_version(void){@@ -229,7 +234,8 @@ static void send_hello(void)msg_string(&root, "player", "library-v1");msg_string(&root, "superTab", "wait-v1"); // a question with superTab + attention is shown as a wait (handle_question)msg_string(&root, "swarmCard", "v1"); // supertabs / supertab.recap / supertab.focus: the Swarm cards (handle_supertab)- msg_string(&root, "swarmChat", "v1"); // each Lead's face chat (chat, chatId, chatName), recaps by chatId, supertab.notice / .read; voice stays in the Lead conversation (cable.md)+ msg_string(&root, "swarmChat", "v1"); // each Lead's face chat (chat, chatId, chatName), recaps by chatId, supertab.notice / .read; voice follows the face only with voice.begin face (cable.md)+ msg_string(&root, "swarmBuddy", "v1"); // PM | Buddy: buddies, buddy {..}, the Swarm's side; supertab.side from the pillmsg_string(&root, "ota", "v1");char mac[24] = "";device_mac_str(mac, sizeof(mac));@@ -283,6 +289,15 @@ bool pro_cable_supertab_send(const char *t, const char *tab, const char *lead)return send_json_with(root, false); // false: dropped on a busy link (the caller retries)}+bool pro_cable_supertab_side(const char *tab, const char *side)+{+ if (!tab || !tab[0] || !side || (strcmp(side, "pm") && strcmp(side, "buddy"))) return false;+ cJSON *root = msg("supertab.side");+ msg_string(&root, "tab", tab);+ msg_string(&root, "side", side);+ return send_json_with(root, false); // false: dropped on a busy link; the next supertab frame shows the true side+}+bool pro_cable_send_scroll(pro_scroll_phase_t phase, int dy, int velocity){_Static_assert(PRO_SCROLL_DOWN == 0 && PRO_SCROLL_MOVE == 1 && PRO_SCROLL_UP == 2, "scroll phase wire order");@@ -322,13 +337,14 @@ static bool upload_matches(const char *upload_id)return same;}-bool pro_cable_voice_begin(const char *agent_id, const char *lang, int sample_rate, const char *upload_id)+bool pro_cable_voice_begin(const char *agent_id, bool face, const char *lang, int sample_rate, const char *upload_id){if (!upload_id || !upload_id[0]) return false;remember_upload(upload_id);cJSON *root = msg("voice.begin");// OMITTED, not empty, without an agent: absence tells the daemon to route the transcript itself.if (agent_id && agent_id[0]) msg_string(&root, "agentId", agent_id);+ if (face) msg_bool(&root, "face", true); // OMITTED otherwise: an older daemon ignores it, a newer one routes as before swarmChatmsg_string(&root, "lang", lang && lang[0] ? lang : "en");msg_number(&root, "sr", sample_rate);msg_string(&root, "uploadId", upload_id);@@ -562,6 +578,32 @@ static pod_lead_state_t lead_state(const char *s)}// The Leads in the Swarm's order (each Lead's `order`, the project's index in the app), whatever their urgency; a Lead without one keeps its place as it came.+// The Lead's Buddy: `buddies` is true only for JSON true; the block counts only with a `cells` integer in 0..32767. Bad fields keep the Lead.+static void read_buddy(const cJSON *l, pod_lead_t *ld)+{+ ld->buddies = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(l, "buddies"));+ const cJSON *b = cJSON_GetObjectItemCaseSensitive(l, "buddy");+ const cJSON *cells = cJSON_IsObject(b) ? cJSON_GetObjectItemCaseSensitive(b, "cells") : NULL;+ if (!cJSON_IsNumber(cells) || cells->valuedouble < 0 || cells->valuedouble > 32767 || cells->valuedouble != (double)(int)cells->valuedouble) return;+ pod_buddy_t *bd = &ld->buddy;+ ld->has_buddy = true;+ bd->cells = (uint16_t)cells->valuedouble;+ const char *cid = str_of(b, "chatId");+ if (cid && strlen(cid) < sizeof bd->chat_id) snprintf(bd->chat_id, sizeof bd->chat_id, "%s", cid); // whole or none+ cut_of(b, "name", bd->name, sizeof bd->name);+ cut_of(b, "engine", bd->engine, sizeof bd->engine);+ const char *col = str_of(b, "color");+ bd->color = POD_BUDDY_INK;+ if (col && strlen(col) == 7 && col[0] == '#') {+ char *end = NULL;+ bool hex = true;+ for (int i = 1; i < 7; i++) hex = hex && isxdigit((unsigned char)col[i]);+ const unsigned long v = hex ? strtoul(col + 1, &end, 16) : 0;+ if (hex) bd->color = (uint32_t)v;+ }+ bd->live = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(b, "live"));+}+static void read_leads(const cJSON *it, pod_swarm_t *sw){double order[SWARM_LEADS_MAX];@@ -601,6 +643,7 @@ static void read_leads(const cJSON *it, pod_swarm_t *sw)if (cid && strlen(cid) < sizeof ld->chat_id) snprintf(ld->chat_id, sizeof ld->chat_id, "%s", cid); // whole or nonecut_of(l, "chatName", ld->chat_name, sizeof ld->chat_name);ld->recap = POD_RECAP_NONE;+ read_buddy(l, ld);}}@@ -632,6 +675,8 @@ static void handle_supertab(const cJSON *p)const char *tab = str_of(p, "tab");if (tab && strlen(tab) < sizeof sw->tab) snprintf(sw->tab, sizeof sw->tab, "%s", tab);cut_of(p, "name", sw->name, sizeof sw->name);+ const char *side = str_of(p, "side");+ sw->side = !side ? POD_SIDE_NONE : !strcmp(side, "buddy") ? POD_SIDE_BUDDY : !strcmp(side, "pm") ? POD_SIDE_PM : POD_SIDE_NONE;read_leads(p, sw);const cJSON *count = cJSON_GetObjectItemCaseSensitive(p, "count"); // absent: the Leads listedsw->count = cJSON_IsNumber(count) ? (count->valuedouble > 0 ? (count->valuedouble > 65535 ? 65535 : (uint16_t)count->valuedouble) : 0)@@ -971,7 +1016,9 @@ static void handle_voice_error(const cJSON *p)static void session_up(const cJSON *p){- atomic_store(&s_features, cable_features_parse(p));+ const uint32_t features = cable_features_parse(p);+ atomic_store(&s_features, features);+ pro_app_features(features); // pro_app keeps the ones the screens act on (swarm.remote: talk to a remote Lead)const cJSON *machine = p ? cJSON_GetObjectItemCaseSensitive(p, "machine") : NULL;const char *name = str_of(machine, "name");copy_cut(s_machine_name, sizeof s_machine_name, name ? name : "Machine");diff --git a/devices/harness-pro/firmware/main/cable/pro_cable.h b/devices/harness-pro/firmware/main/cable/pro_cable.hindex ef9322e68..aabc98a67 100644--- a/devices/harness-pro/firmware/main/cable/pro_cable.h+++ b/devices/harness-pro/firmware/main/cable/pro_cable.h@@ -28,10 +28,14 @@ bool pro_cable_request_library(int offset, uint32_t request);// recap on screen; `lead` NULL or "" when it closes) and "supertab.select" (pick the Lead on the desktop). Anything else, or// no `tab`, sends nothing. Never waits (the render and touch tasks send it); a busy link loses it, so the caller asks again.bool pro_cable_supertab_send(const char *t, const char *tab, const char *lead);+// `supertab.side` {tab, side}: the side the person picked for that Swarm, "pm" or "buddy" (anything else: false). Dropped on a busy link, not retried.+bool pro_cable_supertab_side(const char *tab, const char *side);// Voice: begin sends voice.begin and remembers `upload_id` (<= 23 chars) to match the reply; pcm is a CABLE_TYPE_PCM// frame (16-bit mono); end finishes the recording (the reply arrives as pro_app_voice_result); abort/cancel discard it.-bool pro_cable_voice_begin(const char *agent_id, const char *lang, int sample_rate, const char *upload_id);+// face: spoken on a Lead view, which shows the face chat: the daemon posts the words there (Swarm parity, part 3). Else they go to the+// Lead conversation or the harness, as before swarmChat (review of #2298).+bool pro_cable_voice_begin(const char *agent_id, bool face, const char *lang, int sample_rate, const char *upload_id);bool pro_cable_voice_pcm(const uint8_t *pcm, size_t len);bool pro_cable_voice_end(const char *upload_id);bool pro_cable_voice_abort(const char *upload_id, const char *why); // why may be NULLdiff --git a/devices/harness-pro/firmware/main/pod/home/ph.h b/devices/harness-pro/firmware/main/pod/home/ph.hindex 3775c2560..766776113 100644--- a/devices/harness-pro/firmware/main/pod/home/ph.h+++ b/devices/harness-pro/firmware/main/pod/home/ph.h@@ -28,6 +28,7 @@ enum { PH_HOME_BG = 0x151413,void ph_working_mark_big(ht_scene_t *, int x, int y, uint32_t now_ms);// A title centred on x 360 at y 46 (ph_sb_26, PH_ROOM_INK), control characters as spaces, cut with an ellipsis at 640 px: the room's name, "Notices".void ph_title(ht_scene_t *, const char *);+void ph_title_ink(ht_scene_t *, const char *, unsigned rgb); // the same in another ink (the Buddy talk's lilac name)// Whether the agent has recap text (a non-empty line).bool ph_has_recap(const pod_agent_t *);// Text on one line, vertically centred on cy (the lowercase band), cut with an ellipsis at w px.@@ -36,6 +37,9 @@ void ph_text(ht_scene_t *, int x, int cy, int w, const ht_pro_font_t *, unsignedint ph_runs(const pod_out_frame_t *);// pct % of colour a over colour b, per channel (0xRRGGBB).unsigned ph_mix(unsigned a, unsigned b, unsigned pct);+// A Buddy's avatar (ph_avatar.c): a disc of diameter d at (x, y), `color` 22 % over bg, with a 3 px ring at 33 %, and the desktop's 5 x 5 agent pattern+// (the 15-bit half `cells`, mirrored) over it in `color`. At most 27 runs.+void ph_buddy_avatar(ht_scene_t *, int x, int y, int d, uint16_t cells, uint32_t color, unsigned bg);// ---- Home (ph_overview.c) ------------------------------------------------------------------------------------------// Cover cards (the owner's mockup): the TABS frame's scroll is the tab (clamped; Recent is not a page). The tab is a 540 x 560 card at (90, 56)diff --git a/devices/harness-pro/firmware/main/pod/home/ph_avatar.c b/devices/harness-pro/firmware/main/pod/home/ph_avatar.cnew file mode 100644index 000000000..4a533f360--- /dev/null+++ b/devices/harness-pro/firmware/main/pod/home/ph_avatar.c@@ -0,0 +1,20 @@+// A Buddy's avatar (the desktop's superTabAgentPattern, avatar_art.dart): a disc of diameter d with a 3 px ring, and a 5 x 5 pattern of rounded cells+// spanning d * 56 / 100, centred. The 15 bits are the left half: cell (row, col) is lit when bit row * 3 + [0, 1, 2, 1, 0][col] is set, so the right two+// columns mirror the left. Fill is the colour 22 % over the background, the ring 33 %. At most 27 runs: the ring, the fill and up to 25 cells.+#include "pod/home/ph.h"+#include "pro_canvas.h"++#define C(rgb) ht_rgb(rgb)+enum { RING = 3, FILL_PCT = 22, RING_PCT = 33, PATTERN_PCT = 56, GRID = 5 };++void ph_buddy_avatar(ht_scene_t *s, int x, int y, int d, uint16_t cells, uint32_t color, unsigned bg)+{+ static const uint8_t mirror[GRID] = { 0, 1, 2, 1, 0 };+ ht_pro_rect_aa(s, x, y, d, d, d / 2, C(ph_mix(color, bg, RING_PCT)));+ ht_pro_rect_aa(s, x + RING, y + RING, d - 2 * RING, d - 2 * RING, d / 2 - RING, C(ph_mix(color, bg, FILL_PCT)));+ int cell = d * PATTERN_PCT / 100 / GRID;+ int ox = x + (d - GRID * cell) / 2, oy = y + (d - GRID * cell) / 2;+ for (int r = 0; r < GRID; r++)+ for (int c = 0; c < GRID; c++)+ if (cells >> (r * 3 + mirror[c]) & 1) ht_pro_rect_aa(s, ox + c * cell, oy + r * cell, cell, cell, cell / 5, C(color));+}diff --git a/devices/harness-pro/firmware/main/pod/home/ph_chrome.c b/devices/harness-pro/firmware/main/pod/home/ph_chrome.cindex e2bae1b45..6dffc8873 100644--- a/devices/harness-pro/firmware/main/pod/home/ph_chrome.c+++ b/devices/harness-pro/firmware/main/pod/home/ph_chrome.c@@ -70,7 +70,8 @@ void ph_room_floor(ht_scene_t *s, int cx, int foot, int w)enum { NAME_CY = 46, NAME_MAX_W = 640 };// A title centred on x = 360 (the room's name, Notices), cut with an ellipsis at NAME_MAX_W.-void ph_title(ht_scene_t *s, const char *t)+void ph_title(ht_scene_t *s, const char *t) { ph_title_ink(s, t, PH_ROOM_INK); }+void ph_title_ink(ht_scene_t *s, const char *t, unsigned rgb){char buf[sizeof((pod_agent_t *)0)->name + 4];snprintf(buf, sizeof buf, "%s", t);@@ -84,7 +85,7 @@ void ph_title(ht_scene_t *s, const char *t)} while (len > 0 && ht_pro_width(f, buf) > NAME_MAX_W);}int w = ht_pro_width(f, buf);- ph_text(s, (POD_W - w) / 2, NAME_CY, w + 2, f, PH_ROOM_INK, buf);+ ph_text(s, (POD_W - w) / 2, NAME_CY, w + 2, f, rgb, buf);}void ph_room_chrome(pod_out_frame_t *f, const pod_nav_t *nav, const pod_model_t *m, const pod_agent_t *a)diff --git a/devices/harness-pro/firmware/main/pod/home/ph_lead.c b/devices/harness-pro/firmware/main/pod/home/ph_lead.cindex a0a83565b..4b9134237 100644--- a/devices/harness-pro/firmware/main/pod/home/ph_lead.c+++ b/devices/harness-pro/firmware/main/pod/home/ph_lead.c@@ -7,6 +7,11 @@// bubble, "No message yet" muted in the middle and the pet resting; LOADED the text. A long message shows 7 rows at a time and scrolls by rows (the frame's// scroll; a vertical drag, pod_scroll_pitch / pod_scroll_max; the same drag scrolls the desktop's Swarm chat), the last visible row lighter while more follows. No hit: a tap anywhere talks to a local Lead's// harness (the glue), a horizontal swipe steps to the previous / next Lead (pod_nav_act PREV / NEXT). No page dots.+// A Lead with a Buddy side (`buddies`) adds the PM | Buddy pill (mockup pro-swarm-parity 2A: 300 x 44 at (210, 16), radius 22, the selected segment filled: PM ink, Buddy lilac) and+// the header becomes one line at cy 94 (the Swarm's name small purple, " . " muted, the project; the Swarm's name gives way first), a PM or group name moving to cy 130 under the pill; the+// bubble stays at 150. Two POD_A_SIDE hits (one per segment; the glue sends supertab.side and shows the tapped segment until the Swarm's next frame). A Lead whose chat is the Buddy's+// signs with the Buddy: its avatar (120 px in the pet's box), its name in lilac and "offline" under it while it is not live. On the Buddy side with no Buddy yet there is no bubble and+// no who row: a dashed circle with "+" and two muted lines. The Buddy's quiet notice is a 12 px lilac dot at the Buddy segment's top right while the PM side shows.#include <stdio.h>#include <string.h>@@ -22,8 +27,12 @@enum { BG = PH_ROOM_BG, BX = 60, BW = 600, BY = 150, RAD = 34, PAD_X = 34, PAD_Y = 28, TEXT_W = BW - 2 * PAD_X, PITCH = 46, ROWS_VIS = 7, ROWS_MAX = 64,EDGE = 8, EDGE_W = 120, // the inner edge: a rounded block of this width in the edge colour, the bubble drawn 8 px in over itTAIL_CX = BX + 48 + 18, TAIL_HALF = 24, TAIL_DROP = 23,- ROW_GAP = 18, PET_X = 16, PET_SIDE = 150, PET_UP = 10, NAME_X = 160, NAME_MAX_X = 660, HEAD_W = 640,+ ROW_GAP = 18, AVATAR_D = 120, PET_X = 16, PET_SIDE = 150, PET_UP = 10, NAME_X = 160, NAME_MAX_X = 660, HEAD_W = 640,SW_CY = 42, PROJ_CY = 84, CHAT_CY = 120, NOMSG_CY = 330,+ PILL_X = 210, PILL_Y = 16, PILL_W = 300, PILL_H = 44, SEG_W = 150, PILL_CY = 38, HEAD_A_CY = 94, CHAT_PILL_CY = 130, // the pill, header A, the chat name under the pill+ DOT = 12, DOT_X = 480, DOT_Y = 18, DOT_RING = 3, // right of "Buddy", clear of its ink+ NB_CX = 360, NB_CY = 250, NB_D = 120, NB_DASHES = 12, NB_TITLE_CY = 364, NB_SUB_CY = 412, // no Buddy yet: the dashed circle, the two lines+ TRACK = 0x34302C, BUDDY_INK = POD_BUDDY_INK,EDGE_ASK = 0xFF9A52, EDGE_STUCK = 0xE5484D, SWARM_INK = 0xB79CFF }; // the mockup's #ff9a52 and a red; the Swarm name's purplestatic const ht_pro_font_t *const FONT = &ph_rg_36;@@ -92,10 +101,12 @@ static int rows_of(const char *text)}int ph_lead_pitch(void) { return PITCH; }+int ph_lead_max_row(const pod_nav_t *nav, const pod_model_t *m){- const pod_lead_t *l = pod_nav_lead(nav, m, NULL);- if (!l || l->recap != POD_RECAP_LOADED) return 0;+ const pod_swarm_t *sw = NULL;+ const pod_lead_t *l = pod_nav_lead(nav, m, &sw);+ if (!l || l->recap != POD_RECAP_LOADED || (sw && pod_model_no_buddy(m, sw, l))) return 0;const int rows = rows_of(l->text);return rows > ROWS_VIS ? rows - ROWS_VIS : 0;}@@ -129,6 +140,67 @@ static void centred(ht_scene_t *s, int cy, const ht_pro_font_t *f, unsigned rgb,ph_text(s, (POD_W - w) / 2, cy, w + 2, f, rgb, t);}+// The pill: the track, the selected segment filled, "PM" and "Buddy", the two hits and, while the Buddy spoke and the PM side shows, the lilac dot with its track-coloured ring.+static void draw_pill(pod_out_frame_t *f, const pod_swarm_t *sw, pod_side_t side, bool dot)+{+ ht_scene_t *s = f->scene;+ const bool pm = side == POD_SIDE_PM;+ ht_pro_rect_aa(s, PILL_X, PILL_Y, PILL_W, PILL_H, PILL_H / 2, C(TRACK));+ ht_pro_rect_aa(s, PILL_X + (pm ? 0 : SEG_W), PILL_Y, SEG_W, PILL_H, PILL_H / 2, C(pm ? PH_ROOM_INK : BUDDY_INK));+ const char *label[2] = { "PM", "Buddy" };+ for (int i = 0; i < 2; i++) {+ const bool on = (i == 0) == pm;+ const int w = ht_pro_width(&ph_sb_22, label[i]);+ ph_text(s, PILL_X + i * SEG_W + (SEG_W - w) / 2, PILL_CY, w + 2, &ph_sb_22, on ? PH_ROOM_BG : PH_ROOM_MUTED, label[i]);+ pod_hit_add_id(f, PILL_X + i * SEG_W, PILL_Y - 8, SEG_W, PILL_H + 16, POD_A_SIDE, i ? POD_SIDE_BUDDY : POD_SIDE_PM, sw->id); // a taller target than the pill, inside the status band+ }+ if (dot) {+ ht_pro_rect_aa(s, DOT_X - DOT_RING, DOT_Y - DOT_RING, DOT + 2 * DOT_RING, DOT + 2 * DOT_RING, (DOT + 2 * DOT_RING) / 2, C(TRACK));+ ht_pro_rect_aa(s, DOT_X, DOT_Y, DOT, DOT, DOT / 2, C(BUDDY_INK));+ }+}++// Header A: the Swarm's name (ph_sb_26, purple), " . " (muted) and the project (ph_sb_34) on one line centred at cy 94, the whole line within HEAD_W: the Swarm's name is+// shortened first, the project's end last.+static void head_a(ht_scene_t *s, const char *swarm, const char *project)+{+ char name[HT_TEXT_BYTES], proj[HT_TEXT_BYTES];+ fit_line(proj, sizeof proj, project, &ph_sb_34, HEAD_W);+ const char *sep = " \xc2\xb7 ";+ const int sepw = ht_pro_width(&ph_sb_34, sep), ellw = ht_pro_width(&ph_sb_26, ELL);+ int room = HEAD_W - sepw - ht_pro_width(&ph_sb_34, proj); // what the name may have+ if (room < ellw) { // the project alone is too long beside even a bare ellipsis: it gives up its end+ room = ellw;+ fit_line(proj, sizeof proj, project, &ph_sb_34, HEAD_W - sepw - ellw);+ }+ fit_line(name, sizeof name, swarm, &ph_sb_26, room);+ const int nw = ht_pro_width(&ph_sb_26, name), pw = ht_pro_width(&ph_sb_34, proj);+ int x = (POD_W - (nw + sepw + pw)) / 2;+ ph_text(s, x, HEAD_A_CY, nw + 2, &ph_sb_26, SWARM_INK, name);+ ph_text(s, x + nw, HEAD_A_CY, sepw + 2, &ph_sb_34, PH_ROOM_MUTED, sep);+ ph_text(s, x + nw + sepw, HEAD_A_CY, pw + 2, &ph_sb_34, PH_ROOM_INK, proj);+}++// The Buddy's who row: its avatar (d 120, centred in the pet's 150 px box) with its name in lilac, and "offline" under it while it is not live.+static void who_buddy(ht_scene_t *s, const pod_lead_t *l, int cy)+{+ char line[HT_TEXT_BYTES];+ ph_buddy_avatar(s, PET_X + (PET_SIDE - AVATAR_D) / 2, cy - AVATAR_D / 2, AVATAR_D, l->buddy.cells, l->buddy.color, BG);+ fit_line(line, sizeof line, l->buddy.name, &ph_sb_34, NAME_MAX_X - NAME_X);+ ph_text(s, NAME_X, cy - 17, NAME_MAX_X - NAME_X, &ph_sb_34, BUDDY_INK, line);+ if (!l->buddy.live) ph_text(s, NAME_X, cy + 22, NAME_MAX_X - NAME_X, &ph_sb_22, PH_ROOM_MUTED, "offline");+}++// No Buddy yet: a dashed circle (twelve short arcs) with a "+", then two muted lines.+static void draw_pod_model_no_buddy(ht_scene_t *s)+{+ for (int k = 0; k < NB_DASHES; k++)+ pod_arc(s, NB_CX * 16, NB_CY * 16, (NB_D / 2 - 2) * 16, 4 * 16, k * 360 / NB_DASHES, 360 / NB_DASHES / 4, C(PH_ROOM_MUTED));+ centred(s, NB_CY, &ph_sb_48, PH_ROOM_MUTED, "+");+ centred(s, NB_TITLE_CY, &ph_sb_34, PH_ROOM_MUTED, "No Buddy here yet");+ centred(s, NB_SUB_CY, &ph_rg_28, PH_ROOM_MUTED, "Add one in the Harness app.");+}+void ph_view_lead(pod_out_frame_t *f, const pod_nav_t *nav, pod_model_t *m, uint32_t now_ms){ht_scene_t *s = f->scene;@@ -137,14 +209,21 @@ void ph_view_lead(pod_out_frame_t *f, const pod_nav_t *nav, pod_model_t *m, uintconst pod_lead_t *l = pod_nav_lead(nav, m, &sw);if (!l) return; // the link dropped or the list has not come back: nothing to say yet (the view stays; pod_nav_sync decides when it goes)char line[HT_TEXT_BYTES];- fit_line(line, sizeof line, sw->name, &ph_sb_22, HEAD_W);- centred(s, SW_CY, &ph_sb_22, SWARM_INK, line);- fit_line(line, sizeof line, l->project, &ph_sb_34, HEAD_W);- centred(s, PROJ_CY, &ph_sb_34, PH_ROOM_INK, line);+ const pod_side_t side = pod_model_side_shown(m, sw);+ if (l->buddies) { // the pill, and the header on one line under it+ draw_pill(f, sw, side, l->buddy_unread && side == POD_SIDE_PM);+ head_a(s, sw->name, l->project);+ } else {+ fit_line(line, sizeof line, sw->name, &ph_sb_22, HEAD_W);+ centred(s, SW_CY, &ph_sb_22, SWARM_INK, line);+ fit_line(line, sizeof line, l->project, &ph_sb_34, HEAD_W);+ centred(s, PROJ_CY, &ph_sb_34, PH_ROOM_INK, line);+ }if ((l->chat == POD_CHAT_PM || l->chat == POD_CHAT_GROUP) && l->chat_name[0]) { // the chat the desktop has open (a PM or a group; the Lead's own chat adds nothing)fit_line(line, sizeof line, l->chat_name, &ph_sb_22, HEAD_W);- centred(s, CHAT_CY, &ph_sb_22, PH_ROOM_MUTED, line);+ centred(s, l->buddies ? CHAT_PILL_CY : CHAT_CY, &ph_sb_22, PH_ROOM_MUTED, line);}+ if (pod_model_no_buddy(m, sw, l)) { draw_pod_model_no_buddy(s); return; }// The bubble: the text (loaded), "..." (loading) or nothing (no message yet, or not asked yet: the same "..." as loading)const bool empty = l->recap == POD_RECAP_EMPTY, loaded = l->recap == POD_RECAP_LOADED;@@ -176,6 +255,7 @@ void ph_view_lead(pod_out_frame_t *f, const pod_nav_t *nav, pod_model_t *m, uint// The who row: the pet in its state's scene (resting when there is nothing to say), "Lead" and the status line beside itconst pod_scene_t scene = empty ? POD_SCENE_REST : ph_lead_scene(l->state);const int pet_y = bb + ROW_GAP - PET_UP, cy = pet_y + PET_SIDE / 2;+ if (l->chat == POD_CHAT_BUDDY && l->has_buddy) { who_buddy(s, l, cy); return; } // the Buddy signs its own chatif (pod_pet_for(l->engine)) pod_pet_draw_flat(s, PET_X, pet_y, PET_SIDE, l->engine, scene, now_ms, 0, BG, 8);else ph_engine_logo(s, PET_X + PET_SIDE / 2 - 36, cy - 36, 72, l->engine, BG);const int max_w = NAME_MAX_X - NAME_X;@@ -192,7 +272,8 @@ void ph_view_lead(pod_out_frame_t *f, const pod_nav_t *nav, pod_model_t *m, uintuint32_t ph_lead_next_ms(const pod_nav_t *nav, const pod_model_t *m, uint32_t now_ms){- const pod_lead_t *l = pod_nav_lead(nav, m, NULL);+ const pod_swarm_t *sw = NULL;+ const pod_lead_t *l = pod_nav_lead(nav, m, &sw);if (!l) return POD_PET_STEP_MS;uint32_t ms = pod_pet_next_beat_ms(l->engine, l->recap == POD_RECAP_EMPTY ? POD_SCENE_REST : ph_lead_scene(l->state), now_ms, 0);if (ms < POD_PH_ANIM_MS) ms = POD_PH_ANIM_MS - now_ms % POD_PH_ANIM_MS; // a pet redraws a lot: no faster than the Pets beat@@ -200,5 +281,7 @@ uint32_t ph_lead_next_ms(const pod_nav_t *nav, const pod_model_t *m, uint32_t noconst uint32_t into = (int32_t)(now_ms - l->since_at_ms) > 0 ? now_ms - l->since_at_ms : 0, t = 1000 - into % 1000;if (ms > t) ms = t;}+ const uint32_t left = sw ? pod_model_side_press_left_ms(m, sw) : 0; // a tapped segment the daemon never answered lapses: draw the Swarm's own side then+ if (left && ms > left) ms = left;return ms;}diff --git a/devices/harness-pro/firmware/main/pod/home/ph_talk.c b/devices/harness-pro/firmware/main/pod/home/ph_talk.cindex 1230ce8b7..9c31e0c87 100644--- a/devices/harness-pro/firmware/main/pod/home/ph_talk.c+++ b/devices/harness-pro/firmware/main/pod/home/ph_talk.c@@ -1,5 +1,6 @@// Pets voice (pro-edge2 "Listening" and "It answers"): the pet alone, as in its room. Listening: the room chrome (the agent's name on top) and the-// LISTEN scene at 2x. Sending: the name and the SEND scene at 2x. No bubbles, no wave, no dots: the pet's own animation is all that moves+// LISTEN scene at 2x. Opened from a Lead view with no harness here (a remote Lead, talked to by its Swarm id) the roster has no agent: the name is "Lead" and the+// pet the Lead's engine, as its who row shows them. On the Buddy screen (the Lead's chat is the Buddy's) it is the Buddy: its engine's pet and its name in lilac. Sending: the name and the SEND scene at 2x. No bubbles, no wave, no dots: the pet's own animation is all that moves// (pod_view_next_ms follows it). One full-screen POD_A_TALK hit, added last, ends the recording (or the glue's timing decides).#include <stdio.h>#include <string.h>@@ -56,20 +57,38 @@ static void fx_send(ht_scene_t *s, uint32_t now_ms)ht_pro_image(s, 360 + (i - 1) * SPARK_PITCH - PH_SPARK_W / 2, FX_Y - PH_SPARK_H / 2, spark(i == lit));}+enum { BUDDY_INK = 0xC49BFF }; // the Buddy's lilac, as the Lead view's pill and name++// Who the voice screen shows: the roster agent of the frame, else the Lead of a Lead frame ("Lead" and its engine), or its Buddy on the Buddy screen. NULL: nobody.+typedef struct { const pod_agent_t *agent; const char *engine, *name; unsigned ink; } talk_who_t;+static talk_who_t talk_who(const pod_nav_t *nav, const pod_model_t *m)+{+ talk_who_t w = { pod_view_agent_of(nav, m), NULL, NULL, PH_ROOM_INK };+ const pod_lead_t *l = pod_nav_lead(nav, m, NULL);+ if (nav->talk_buddy) return (talk_who_t){ NULL, nav->talk_engine, nav->talk_name, BUDDY_INK }; // the face pinned at begin: a side flip mid-recording renames nothing+ if (w.agent) { w.engine = w.agent->engine; w.name = w.agent->name; }+ else if (l) { w.engine = l->engine; w.name = "Lead"; }+ return w;+}+void ph_view_talk(pod_out_frame_t *f, const pod_nav_t *nav, pod_model_t *m, uint32_t now_ms){ht_scene_t *s = f->scene;- const pod_agent_t *a = pod_view_agent_of(nav, m);- if (!a) { s->background = C(PH_ROOM_BG); return; }- ph_room_chrome(f, nav, m, a);- if (!pod_pet_for(a->engine)) { // no pet: the effect alone+ const talk_who_t who = talk_who(nav, m);+ if (!who.name) { s->background = C(PH_ROOM_BG); return; }+ s->background = C(PH_ROOM_BG);+ ph_title_ink(s, who.name, who.ink);+ if (!pod_pet_for(who.engine)) { // no pet: the effect aloneif (nav->sending) fx_send(s, now_ms); else fx_listen(s, now_ms);if (!nav->sending) pod_hit_add(f, 0, 0, POD_W, POD_W, POD_A_TALK, 0);return;}const int cx = 360, foot = PET_FOOT;ph_room_floor(s, cx, foot, 420);- ph_room_pet(s, m, a, nav->sending ? POD_SCENE_SEND : POD_SCENE_LISTEN, cx, foot, now_ms, nav->sending ? nav->send_started_ms : nav->talk_started_ms);+ const pod_scene_t scene = nav->sending ? POD_SCENE_SEND : POD_SCENE_LISTEN;+ const uint32_t started = nav->sending ? nav->send_started_ms : nav->talk_started_ms;+ const int side = 260, h = pod_pet_ink_h(who.engine, scene, side, 16); // ph_room_pet's own pet, at 2x+ if (h) pod_pet_draw(s, cx - side / 2, foot - h / 2 - side / 2, side, who.engine, scene, now_ms, started, 16);if (!nav->sending) pod_hit_add(f, 0, 0, POD_W, POD_W, POD_A_TALK, 0); // LAST: hits are scanned last to first, so nothing steals the send}@@ -77,11 +96,11 @@ void ph_view_talk(pod_out_frame_t *f, const pod_nav_t *nav, pod_model_t *m, uint// pet with its waves costs most of a frame, so no faster cadence is ever asked for. SEND plays once and holds its last step, then nothing moves.uint32_t ph_talk_next_ms(const pod_nav_t *nav, const pod_model_t *m, uint32_t now_ms){- const pod_agent_t *a = pod_view_agent_of(nav, m);+ const talk_who_t who = talk_who(nav, m);uint32_t ms = 1000;- if (a && !pod_pet_for(a->engine)) return nav->sending ? SEND_MS - now_ms % SEND_MS : WAVE_MS - now_ms % WAVE_MS; // the effect's own steps: 80 ms wave frames, 200 ms sparkles- if (a && pod_pet_for(a->engine))- ms = pod_pet_next_beat_ms(a->engine, nav->sending ? POD_SCENE_SEND : POD_SCENE_LISTEN, now_ms, nav->sending ? nav->send_started_ms : nav->talk_started_ms);+ if (who.name && !pod_pet_for(who.engine)) return nav->sending ? SEND_MS - now_ms % SEND_MS : WAVE_MS - now_ms % WAVE_MS; // the effect's own steps: 80 ms wave frames, 200 ms sparkles+ if (who.name && pod_pet_for(who.engine))+ ms = pod_pet_next_beat_ms(who.engine, nav->sending ? POD_SCENE_SEND : POD_SCENE_LISTEN, now_ms, nav->sending ? nav->send_started_ms : nav->talk_started_ms);if (ms < POD_PH_ANIM_MS) ms = POD_PH_ANIM_MS - now_ms % POD_PH_ANIM_MS; // never faster than the beat, and on itreturn ms;}diff --git a/devices/harness-pro/firmware/main/pod/pod_model.c b/devices/harness-pro/firmware/main/pod/pod_model.cindex c0cfd36dc..8f1d9aa4f 100644--- a/devices/harness-pro/firmware/main/pod/pod_model.c+++ b/devices/harness-pro/firmware/main/pod/pod_model.c@@ -715,6 +715,10 @@ void pod_model_link(pod_model_t *m, bool up) {m->want_n = 0;m->swarm_ids = false;m->focus_pending = false;+ m->side_press = POD_SIDE_NONE;+ m->side_press_swarm[0] = 0;+ for (int i = 0; i < SWARMS_CARD_MAX; i++) // the Buddy's dot is the device's own: a new link starts without one+ for (int j = 0; j < SWARM_LEADS_MAX; j++) m->swarms[i].leads[j].buddy_unread = false;}m->revision++;}@@ -810,7 +814,7 @@ void pod_model_supertab(pod_model_t *m, const pod_swarm_t *s, uint32_t now_ms) {m->swarm_n++;}pod_swarm_t *d = &m->swarms[at];- struct { pod_recap_state_t recap; char *text; uint32_t text_at; } carry[SWARM_LEADS_MAX];+ struct { pod_recap_state_t recap; char *text; uint32_t text_at; bool buddy_unread; } carry[SWARM_LEADS_MAX];memset(carry, 0, sizeof carry);const int ln = s->lead_n > SWARM_LEADS_MAX ? SWARM_LEADS_MAX : s->lead_n;for (int j = 0; j < ln; j++) {@@ -818,6 +822,7 @@ void pod_model_supertab(pod_model_t *m, const pod_swarm_t *s, uint32_t now_ms) {if (k < 0) continue;pod_lead_t *ol = &d->leads[k]; // taken over: the old copy no longer owns the textcarry[j].recap = ol->recap; carry[j].text = ol->text; carry[j].text_at = ol->text_at;+ carry[j].buddy_unread = ol->buddy_unread; // the device's own mark: no frame sets or clears itol->text = NULL;if (strcmp(ol->chat_id, s->leads[j].chat_id)) { // another chat: the old message is not its messagefree(carry[j].text);@@ -834,11 +839,13 @@ void pod_model_supertab(pod_model_t *m, const pod_swarm_t *s, uint32_t now_ms) {l->text = carry[j].text;l->recap = carry[j].recap;l->text_at = carry[j].text_at;+ l->buddy_unread = carry[j].buddy_unread;l->since_at_ms = now_ms;}// The same for a Lead that left this Swarm. The same id in another Swarm is another row's business.for (int i = m->unread_count - 1; i >= 0; i--)if (!strcmp(m->unread[i].tab, d->id) && pod_model_lead_index(d, m->unread[i].agent) < 0) unread_drop(m, i);+ if (m->side_press != POD_SIDE_NONE && !strcmp(m->side_press_swarm, s->id)) { m->side_press = POD_SIDE_NONE; m->side_press_swarm[0] = 0; } // the daemon has answeredm->revision++;}@@ -880,6 +887,35 @@ void pod_model_supertab_close(pod_model_t *m, const char *tab, const char *lead)m->revision++;}+void pod_model_side_press(pod_model_t *m, const char *swarm_id, pod_side_t side, uint32_t now_ms) {+ pod_model_clock(m, now_ms);+ m->side_press = side;+ m->side_press_ms = m->clock_ms;+ pod_copy_str(m->side_press_swarm, sizeof m->side_press_swarm, side == POD_SIDE_NONE || !swarm_id ? "" : swarm_id);+ m->revision++;+}++pod_side_t pod_model_side_shown(const pod_model_t *m, const pod_swarm_t *sw) {+ pod_side_t side = sw->side;+ if (m->side_press != POD_SIDE_NONE && !strcmp(m->side_press_swarm, sw->id) && (uint32_t)(m->clock_ms - m->side_press_ms) < POD_SIDE_PRESS_MS) side = m->side_press;+ return side == POD_SIDE_BUDDY ? POD_SIDE_BUDDY : POD_SIDE_PM;+}+bool pod_model_no_buddy(const pod_model_t *m, const pod_swarm_t *sw, const pod_lead_t *l) {+ return l->buddies && !l->has_buddy && pod_model_side_shown(m, sw) == POD_SIDE_BUDDY;+}+uint32_t pod_model_side_press_left_ms(const pod_model_t *m, const pod_swarm_t *sw) {+ if (m->side_press == POD_SIDE_NONE || strcmp(m->side_press_swarm, sw->id)) return 0;+ const uint32_t gone = m->clock_ms - m->side_press_ms;+ return gone < POD_SIDE_PRESS_MS ? POD_SIDE_PRESS_MS - gone : 0;+}+bool pod_model_buddy_mark(pod_model_t *m, const char *tab, const char *lead, bool unread) {+ pod_swarm_t *sw = (pod_swarm_t *)pod_model_swarm(m, tab);+ const int j = sw ? pod_model_lead_index(sw, lead) : -1;+ if (j < 0 || sw->leads[j].buddy_unread == unread) return false;+ sw->leads[j].buddy_unread = unread;+ return true;+}+void pod_model_supertab_focus(pod_model_t *m, const char *tab, const char *lead) {if (!tab || !*tab || !lead) return; // an empty lead is kept: the Swarm opens on the Lead last shown therepod_copy_str(m->focus_tab, sizeof m->focus_tab, tab);diff --git a/devices/harness-pro/firmware/main/pod/pod_model.h b/devices/harness-pro/firmware/main/pod/pod_model.hindex b806c7ed0..8f55d2952 100644--- a/devices/harness-pro/firmware/main/pod/pod_model.h+++ b/devices/harness-pro/firmware/main/pod/pod_model.h@@ -131,6 +131,10 @@ typedef struct {// Swarm the list does not hold yet waits for it).bool focus_pending;char focus_tab[ID_MAX], focus_lead[ID_MAX];+ // The PM | Buddy segment the person just tapped on this Swarm (the pill draws it selected at once); the Swarm's next supertab frame ends it.+ pod_side_t side_press;+ char side_press_swarm[ID_MAX];+ uint32_t side_press_ms; // the device clock when it was tapped} pod_model_t;// Copy src into dst[cap], cut on a UTF-8 codepoint boundary (always valid, always NUL-terminated); src may be dst.@@ -197,6 +201,18 @@ void pod_model_supertab_recap(pod_model_t *, const char *tab, const char *lead,// close sends a LOADING, LOADED or EMPTY one back to NONE and frees its text (only the open Lead gets pushes, so a closed one would go stale).void pod_model_supertab_loading(pod_model_t *, const char *tab, const char *lead);void pod_model_supertab_close(pod_model_t *, const char *tab, const char *lead);+// A tap on the pill: the segment shows selected on this Swarm until its next supertab frame (NONE clears it). `buddy_unread` of the Lead is the glue's to clear.+void pod_model_side_press(pod_model_t *, const char *swarm_id, pod_side_t side, uint32_t now_ms);+enum { POD_SIDE_PRESS_MS = 3000 }; // as POD_SUPERTAB_RETRY_MS: how long a tap waits for the daemon's frame+// The side the pill and the body show for this Swarm (PM or BUDDY): the tapped segment while the daemon has not answered, else the Swarm's own (NONE counts+// as PM). A press older than POD_SIDE_PRESS_MS is dropped: the frame it asked for may never come. The view and the glue both read it, so they cannot disagree.+pod_side_t pod_model_side_shown(const pod_model_t *, const pod_swarm_t *);+// The Buddy side of a Lead that has none is showing: "No Buddy here yet", no bubble, nothing to talk to.+bool pod_model_no_buddy(const pod_model_t *, const pod_swarm_t *, const pod_lead_t *);+// The milliseconds left before the press on this Swarm lapses; 0 when there is none.+uint32_t pod_model_side_press_left_ms(const pod_model_t *, const pod_swarm_t *);+// Mark (unread) or clear the lilac dot of a Buddy chat; the Lead must be held. True when the mark changed.+bool pod_model_buddy_mark(pod_model_t *, const char *tab, const char *lead, bool unread);// supertab.focus: record it as pending (focus_pending, focus_tab, focus_lead); the latest one wins.void pod_model_supertab_focus(pod_model_t *, const char *tab, const char *lead);const pod_swarm_t *pod_model_swarm_for_tab(const pod_model_t *, const char *tab_id); // the desk tab's Swarm (its `tab` link); NULL for "" or nonediff --git a/devices/harness-pro/firmware/main/pod/pod_nav.c b/devices/harness-pro/firmware/main/pod/pod_nav.cindex 21626d535..d103c3863 100644--- a/devices/harness-pro/firmware/main/pod/pod_nav.c+++ b/devices/harness-pro/firmware/main/pod/pod_nav.c@@ -290,18 +290,26 @@ static pod_out_t nav_act(pod_nav_t *n, pod_model_t *m, pod_action_t a, int arg,}break;case POD_A_TALK:- if (f->view == POD_V_LEAD) { // a local Lead: talk to its harness (a remote one has none: f->agent is empty)- const pod_agent_t *talk_to = pod_model_find(m, f->agent);- if (!talk_to || talk_to->state == POD_OFFLINE) break;+ if (f->view == POD_V_LEAD) { // the round's rule: the Lead's `local` whenever set (roster or not: the daemon pins the face by it), else its own Swarm id when arg says the daemon routes it+ const pod_swarm_t *sw = NULL;+ const pod_lead_t *l = pod_nav_lead(n, m, &sw);+ const char *id = !l ? NULL : l->local[0] ? l->local : arg && f->lead_id[0] ? f->lead_id : NULL;+ if (!id) break;n->talk_prev = POD_V_LEAD;+ n->talk_buddy = l->chat == POD_CHAT_BUDDY && l->has_buddy; // the voice view signs the face pinned now, whatever the desktop flips mid-recording+ if (n->talk_buddy) {+ pod_copy_str(n->talk_name, sizeof n->talk_name, l->buddy.name);+ pod_copy_str(n->talk_engine, sizeof n->talk_engine, l->buddy.engine);+ }f->view = POD_V_TALK;n->talk_started_ms = now_ms;- return out_fx(POD_FX_VOICE_BEGIN, f->agent);+ return out_fx(POD_FX_VOICE_BEGIN, id);}if (f->view == POD_V_AGENT || f->view == POD_V_RECAP) {const pod_agent_t *talk_to = pod_model_find(m, f->agent);if (!talk_to || talk_to->state == POD_OFFLINE) break; // an offline machine has nobody to hear itn->talk_prev = f->view;+ n->talk_buddy = false;f->view = POD_V_TALK;n->talk_started_ms = now_ms;return out_fx(POD_FX_VOICE_BEGIN, f->agent);@@ -311,7 +319,7 @@ static pod_out_t nav_act(pod_nav_t *n, pod_model_t *m, pod_action_t a, int arg,n->sending = true; // stay on the voice screen; pod_nav_flip_recaps releases itn->sent_seen = false;n->send_started_ms = now_ms;- set_id(n->sent_agent, f->agent);+ set_id(n->sent_agent, f->agent); // empty for a remote Lead: release_send waits it outreturn out_fx(POD_FX_VOICE_END, f->agent);}break;@@ -353,6 +361,7 @@ static pod_out_t nav_act(pod_nav_t *n, pod_model_t *m, pod_action_t a, int arg,case POD_A_NONE:case POD_A_BANNER:case POD_A_LEAD:+ case POD_A_SIDE:break;}return out_none();@@ -385,7 +394,8 @@ static void release_send(pod_nav_t *n, const pod_model_t *m, pod_frame_t *f) {const pod_agent_t *a = pod_model_find(m, n->sent_agent);if (a && a->sent) n->sent_seen = true;bool turn = a && a->state == POD_WORKING && !a->sent && (n->sent_seen || (int32_t)(a->since_ms - n->send_started_ms) >= 0);- if (turn || !a || (int32_t)(m->clock_ms - n->send_started_ms) >= (int32_t)POD_SENT_WAIT_MS) {+ const bool remote = f->swarm[0] && !f->agent[0]; // a remote Lead has no turn to see here: the screen holds its time+ if (turn || (!a && !remote) || (int32_t)(m->clock_ms - n->send_started_ms) >= (int32_t)POD_SENT_WAIT_MS) {n->sending = false;f->view = f->swarm[0] ? POD_V_LEAD : turn ? POD_V_AGENT : n->talk_prev == POD_V_RECAP ? POD_V_RECAP : POD_V_AGENT;}diff --git a/devices/harness-pro/firmware/main/pod/pod_nav.h b/devices/harness-pro/firmware/main/pod/pod_nav.hindex 00a03dc30..2fc9c3166 100644--- a/devices/harness-pro/firmware/main/pod/pod_nav.h+++ b/devices/harness-pro/firmware/main/pod/pod_nav.h@@ -30,6 +30,8 @@ typedef struct {uint8_t work_page; // Home's Working card: the page of three pets shown (0-based; reset when the card is not shown)uint8_t swarm_page; // Home's Swarm card: the page of three Lead pets shown (0-based; reset when the card is not shown or the person pages cards)pod_view_t talk_prev; // AGENT or RECAP: the screen TALK was opened from (talk_over goes back to it)+ bool talk_buddy; // the voice view shows the Buddy (pinned at TALK's begin, like the daemon's face): its name and engine below+ char talk_name[49], talk_engine[16];bool sending; // TALK after the stop tap: the voice screen shows SEND until the agent's real turn begins (or POD_SENT_WAIT_MS)bool sent_seen; // the model has marked sent_agent's optimistic Working (pod_model_sent) since the stop tapchar seen_agent[ID_MAX]; // the open agent as pod_nav_flip_recaps last saw it (empty: none), and whether it was@@ -51,7 +53,8 @@ typedef enum {POD_A_FOLLOW, // arg: index into model->agents: open that agent from anywhere (Inbox rows with no unread entry); the glue resolves the idPOD_A_SCROLL, // arg: signed delta added to the top frame's scroll (clamped to >= 0): rows, whatever the screen draws as one.POD_A_ENTER_TAB, // arg: tab index, only from the TABS frame: push the TAB frame and the tab's first agent (AGENT_OPEN). An empty or unknown tab: nothing.- POD_A_LEAD // hit only for now (the Swarm card's Lead pets): arg = the Lead's index in its Swarm, hit id = the Swarm's id. The nav ignores it+ POD_A_LEAD, // hit only for now (the Swarm card's Lead pets): arg = the Lead's index in its Swarm, hit id = the Swarm's id. The nav ignores it+ POD_A_SIDE // hit only (the Lead view's PM | Buddy pill): arg = POD_SIDE_PM or POD_SIDE_BUDDY, hit id = the Swarm's id. The nav ignores it; the glue sends supertab.side and never talks on it} pod_action_t;typedef enum { POD_FX_NONE, POD_FX_VOICE_BEGIN, POD_FX_VOICE_END, POD_FX_VOICE_ABORT, POD_FX_AGENT_OPEN } pod_effect_t;diff --git a/devices/harness-pro/firmware/main/pro_app_api.h b/devices/harness-pro/firmware/main/pro_app_api.hindex d96c7bfc2..286178484 100644--- a/devices/harness-pro/firmware/main/pro_app_api.h+++ b/devices/harness-pro/firmware/main/pro_app_api.h@@ -24,6 +24,8 @@// (never NULL when up; NULL when down). Called on the transition, and again if a welcome names another computer.// A drop clears everything the daemon told us: pro_app must forget busy agents, abort a sweep and a recording.void pro_app_link(bool up, const char *machine);+// The welcome's features (CABLE_FEATURE_* bits), once per welcome. A drop clears them with the link (pro_app_link(false)).+void pro_app_features(uint32_t features);// ---- roster ----typedef struct { const char *id, *name, *engine, *machine_id, *machine; } pro_agent_row_t;diff --git a/devices/harness-pro/firmware/test/golden-liberation.txt b/devices/harness-pro/firmware/test/golden-liberation.txtindex 071896ffc..ab57bf0e7 100644--- a/devices/harness-pro/firmware/test/golden-liberation.txt+++ b/devices/harness-pro/firmware/test/golden-liberation.txt@@ -18,6 +18,7 @@0cd4cf539f2f3f8dcc17f28478d50ea641f5a0f6f1a3aa27674ba268e2705e0b recap:desk@50000e6c6e8c472798f787049711849aecaa717179bad00135fa1d0f84d8db09308e lead:loaded@600102064b2c387ab5cd1e0f274a8beaef812acc0db7e93ddaef06ed8d06811398f recap:desk:short@2500+10de042dcacd9357fd6ad5ce609f9cdea408541032fa0dd7b4556232a5f9b4be lead:pill@123411ce48c998ea730350c5fa0430d78275a62dff6d2f19e32343040e9ec47ba28f agent:be:offline@250012c8abf13002e19438133eef0d2947372670cd4657bb519a5cea3c9deb58fd54 lead:remote@6001467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs:0+2@5000@@ -26,6 +27,7 @@1467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs:bell@50001467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs:linkdown@50001467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs@5000+175894a12fad7220c708109646edfdd0e5cfa8b75e41267daae9989f3854092b lead:buddy-dot@12341c6e50dd33838720a245cbfd6fe04539f057cb81232241b66efbe259837f6ee4 toast:swarm@2500@01c6e50dd33838720a245cbfd6fe04539f057cb81232241b66efbe259837f6ee4 toast:swarm@2500@12341c6e50dd33838720a245cbfd6fe04539f057cb81232241b66efbe259837f6ee4 toast:swarm@2500@2500@@ -42,6 +44,7 @@2172692ba9bd2b3b70c08b164e96151763672fbb42893a79755fcefc052720d9 toast:swarm@0@60022083bf5827695add306905a71f6e07a70ec12872d2d4ed3cc043e47de7205cd talk:fw:quiet@60022083bf5827695add306905a71f6e07a70ec12872d2d4ed3cc043e47de7205cd talk:fw@600+23e68560392ecd11064d29d814622477971a19730d14ee5dbb2ade55786f38a9 lead:pill@500024e4b487e56cee7639400ebd1ed0d473a12cf553c31c0f3029edf019e1f36bc0 tabs:5@5000262c9840a592d18fb40f708dd67525bfdb25339f5034f2bef446bc6a3293c84f home:swarm:remote@026a207f8ff8046c6711fdb779b28735365e90b65907cc41f6222b30541d9e5dd tabs:working@0@@ -108,6 +111,7 @@3bcdfa6e218c2e1999bce65a891884f93737cd2aa62534e0f42538422db352d3 home:swarm:stuck@03c50228ed125d5138821ae678ebc8267734a5e79c8878b4e4813ebbcb80b3164 agent:fw:long@12343d43bb7cb2ab0102944745f80af971677a75bec05d5dbc01baaf9003fa4111f9 tabs:5@1234+418614ce34fdeeee7e28d684674adfbd6c89f9b63f71ff66134e5a882361f65d lead:pill@2500447afe7920f02e419734787791934e1785fc29309ee26a1566b5005fb31bee79 lead:group@250044c082278989b9844c91c372d51a9f2b29430bf083fcb2794698e189fe8f2e3d tabs:none@60045de9aa8132e2d8f8e14853abb8ee563e660be15078bc812aa6d4795c95c7cfb tabs:long@5000@@ -129,16 +133,23 @@4e1055e7920922bf2c1ba0212b5860b7cdcc162784a16e1d9abd6c586d38cec0 recap:docs:toast@4900@50004e1055e7920922bf2c1ba0212b5860b7cdcc162784a16e1d9abd6c586d38cec0 recap:docs:toast@4900@6004f2fd4fcf7e132109a5bd14d6b69cf098d67134249386193b386124d7a58ae63 home:swarm:p1@600+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@0+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@1234+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@2500+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@5000+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@60050515880623dbb0b9854175e41174c31d6396b40c576932cad2dcc5e36cff96e tabs:seven@123450e26b3c495b054fb16aaf4e792d49234f9d636fa88c4b3520512e75cdf1dc9d recap:desk:long@5000555f603431f0bf42d41c4d306f98e099d3b22296d9fdf75c78282914f957bb3e home:swarm:p1@0563511c0d14d64810e80ffec87a44aa96ebd49b0d22af294aa6580ad3c715d10 home:swarm:many@05647a2a762bd817469bff3189b4e1162fb3b11acbbc72ad9aee9139e0446a010 recap:docs:long@05647a2a762bd817469bff3189b4e1162fb3b11acbbc72ad9aee9139e0446a010 recap:docs:long@2500+5829a4f1dec01b900a81a0a190a74e5887425211e74a777cd4239d1d756a5f7a lead:pill@05acb2d70fc0480116a86cbbf66fcc15390559f258a7cdacf1c2044615cd7135a lead:remote@12345ce5a5aebccdcd1e858832bd35d7de3235502512ef08f0b337da4fb16ee30791 talk:fw:quiet@05ce5a5aebccdcd1e858832bd35d7de3235502512ef08f0b337da4fb16ee30791 talk:fw@06138d6c974e4bab23a707281fa6fa85203220141424ab54f216b7b6d65f03eab tabs:working@2500+61f0d3f25cc1b39009ab00625771767aa988389805f1e704c55128578231e87d lead:buddy-dot@500061f95986c2394dfd1175e703e8e5b8c011065d8704e8404984b9ddae1473a29c talk:be@066c0d32cef1ff955274fa76dcf012efa2b6fd0306205cfefebfca9d1e5f1a0f3 agent:be@123467b7fd29c369b0f8bbc30460233d7f3a8b5777e2729e4fcb2abbc6396f8e7f67 agent:fw:long@0@@ -186,6 +197,11 @@7e560682e42982215f0b39450ac55bb2059d9b70065772979fcdb7b3c3cf9fe9 lead:none@07e560682e42982215f0b39450ac55bb2059d9b70065772979fcdb7b3c3cf9fe9 lead:none@50007effffc339beb6a37a3cbcc5cb51fe7c836ef949dcb216825da4bfe0129722dd lead:loaded@5000+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@0+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@1234+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@2500+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@5000+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@6007fa039f5ebda47a61985054e836d0373bffba85f07667ef3decc52685b752e01 home:swarm:remote@500081312fbd4dee9803a32e5d3aa5fb3b317eafb965fa337f4fadaec149959bc0fc tabs:seven@081cb592818416fb5bbdc363d609b1f9993a87cf61f00e50b60b83d47821b389a lead:loading@1234@@ -225,6 +241,7 @@9569396d08f53a25947caa402456c5a4b9bfe8dbdd37663d52fc7ce6aed5ccb9 lead:loading@500097096110794ece76a2ab0b9f8d01618e360541a3acf1bd584d8fbaa95b0d0d67 lead:ask@0977bddb50cbd047bb41ea02dc9d04f75518bfefe9e25944de93d0fce40b7e51a talk:cur:send@5000+979c3045417fac9f6e1e33340144b0f2a84168c3e2b49c0c328197f3a8cade05 lead:pill@60097cf9dd9e3d5e04d7b553aa767fc765a3bd47cc1160f327538f227b2fd0fcd5b recap:desk:short@50009a206f39596831defafff0aff579c7b4f52fd61029620d3beb2833b56b8ebb67 lead:loading@6009d4fe63cb69c23d6b2426944145e2b17ce8040e73c703944bc507366a6c40126 lead:group@0@@ -290,6 +307,7 @@ bc53b18da4d7ea38f8dd56e0b4470d4e0c4e2cadde1c06ffea5153c907b15fc2 talk:fw:send@2bc53b18da4d7ea38f8dd56e0b4470d4e0c4e2cadde1c06ffea5153c907b15fc2 talk:fw:send@5000bc53b18da4d7ea38f8dd56e0b4470d4e0c4e2cadde1c06ffea5153c907b15fc2 talk:fw:send@600bc92dbc7694b741e98f74a47554b9e40581c98efc715b713b1feaa73d90e390b recap:desk:medium@1234+bddbf0df0f3592d341a0079483582e8d434401aeefd088b6f5bfac5a9da7cdee lead:buddy-dot@0bea341256b62baa2f37ad783b5921ce770c2a3342e9d5a999322be7c60c5f9ff talk:cur@2500beea941441c90a67801395000a40ac5ae7b3bf55377c95e70b4fa0751b973d95 agent:be:offline@600c158dad57e29a9df5ca9b0169c6f1367dac791a7126326aeca42ee6cfc67e090 tabs:1@2500@@ -362,7 +380,13 @@ e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@1e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@2500e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@5000e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@600+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@0+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@1234+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@2500+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@5000+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@600e1ff6c4a58d744e05300c2a57be4e08d5f29cc531a741a83c649a892ab7de29a recap:desk:long@1234+e44f8afa6ce8902a8193528267edebb50d932a816a61e00e6d728282354a0ba6 lead:buddy-dot@600e55b4e490d71c454af6cd36f6778798a187eacfcce2b18ca7579fffc5b386bb0 agent:cli:banner@600e55b4e490d71c454af6cd36f6778798a187eacfcce2b18ca7579fffc5b386bb0 agent:cli@600e613555b96ab955404f55d39984791e73f9cce4acd1ebaf9b0e735b0c2be7f8e home:swarm:many@600@@ -374,6 +398,7 @@ e652d520e88b1d12b1fe7409e957a1065d69f7683ce6d1e8cd2caaca93c725ad tabs:2+2@600e6a3ea32881c13627d6043a18efae1b4578e2c62467b1989129c0a8da1b57032 lead:none@1234e6a7fa14ee6c9191350176f8dfcf0661da526268a3d14d912f6337e048b39cbf tabs:1@1234e863aabe59e0ae473cf778a960aa06a49b819ccc2af11dd203351c7e5981c94f home:swarm:stuck@5000+e8dff950a5f35185a2195103620b9e15e5f80611b8e20fef3db2eed4604b82dc lead:buddy-dot@2500e8f82832b80bcf61502a843b8ebc9523b41386be13fdafcc1cf2d5f5e00922ad inbox:quiet@0e8f82832b80bcf61502a843b8ebc9523b41386be13fdafcc1cf2d5f5e00922ad inbox:quiet@1234e8f82832b80bcf61502a843b8ebc9523b41386be13fdafcc1cf2d5f5e00922ad inbox:quiet@2500diff --git a/devices/harness-pro/firmware/test/golden.sh b/devices/harness-pro/firmware/test/golden.shindex 0597f6dd1..63e524e57 100644--- a/devices/harness-pro/firmware/test/golden.sh+++ b/devices/harness-pro/firmware/test/golden.sh@@ -30,7 +30,7 @@ python3 "$fw/scripts/gen_fonts.py" ${font_args[@]+"${font_args[@]}"} --out "$outcc -std=c11 -D_DEFAULT_SOURCE -Wall -Wextra -Werror -O1 -g -DHT_FACE_PX=720 -I"$disp" -I"$fw/main" \-o "$out/pod_render" "$here/pod_render.c" "$fw"/main/pod/*.c "$fw"/main/pod/home/*.c "$disp/pro_canvas.c" "$disp/terminal.c" "$out/pro_fonts.c"-screens=(tabs tabs:bell tabs:mock tabs:0+2 tabs:2+2 tabs:long tabs:9 tabs:linkdown tabs:1 tabs:3 tabs:5 tabs:seven tabs:single tabs:notices tabs:working tabs:none home:swarm:p1 home:swarm:p2 home:swarm:stuck home:swarm:done home:swarm:many home:swarm:remote lead:loaded lead:ask lead:loading lead:none lead:remote lead:group lead:pm+screens=(tabs tabs:bell tabs:mock tabs:0+2 tabs:2+2 tabs:long tabs:9 tabs:linkdown tabs:1 tabs:3 tabs:5 tabs:seven tabs:single tabs:notices tabs:working tabs:none home:swarm:p1 home:swarm:p2 home:swarm:stuck home:swarm:done home:swarm:many home:swarm:remote lead:loaded lead:ask lead:loading lead:none lead:remote lead:group lead:pm lead:pill lead:buddy lead:buddy-offline lead:nobuddy lead:buddy-dotagent:fw agent:cli agent:be agent:desk agent:kilo agent:fw:long agent:cli:long agent:be:offline agent:fw:banner agent:cli:banner tabs:banner agent:fw:toast@0 agent:fw:toast@200 agent:fw:toast@2500 agent:fw:toast@4900agent:fw:toast:decision@2500 agent:fw:toast:stuck@9000recap:desk:toast@200 recap:desk:toast@2500 recap:docs:toast@4900diff --git a/devices/harness-pro/firmware/test/golden.txt b/devices/harness-pro/firmware/test/golden.txtindex 071896ffc..ab57bf0e7 100644--- a/devices/harness-pro/firmware/test/golden.txt+++ b/devices/harness-pro/firmware/test/golden.txt@@ -18,6 +18,7 @@0cd4cf539f2f3f8dcc17f28478d50ea641f5a0f6f1a3aa27674ba268e2705e0b recap:desk@50000e6c6e8c472798f787049711849aecaa717179bad00135fa1d0f84d8db09308e lead:loaded@600102064b2c387ab5cd1e0f274a8beaef812acc0db7e93ddaef06ed8d06811398f recap:desk:short@2500+10de042dcacd9357fd6ad5ce609f9cdea408541032fa0dd7b4556232a5f9b4be lead:pill@123411ce48c998ea730350c5fa0430d78275a62dff6d2f19e32343040e9ec47ba28f agent:be:offline@250012c8abf13002e19438133eef0d2947372670cd4657bb519a5cea3c9deb58fd54 lead:remote@6001467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs:0+2@5000@@ -26,6 +27,7 @@1467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs:bell@50001467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs:linkdown@50001467a0558ff261ee1580e2ab811f1d59ed1418cf0566b084ba6697eb487a9618 tabs@5000+175894a12fad7220c708109646edfdd0e5cfa8b75e41267daae9989f3854092b lead:buddy-dot@12341c6e50dd33838720a245cbfd6fe04539f057cb81232241b66efbe259837f6ee4 toast:swarm@2500@01c6e50dd33838720a245cbfd6fe04539f057cb81232241b66efbe259837f6ee4 toast:swarm@2500@12341c6e50dd33838720a245cbfd6fe04539f057cb81232241b66efbe259837f6ee4 toast:swarm@2500@2500@@ -42,6 +44,7 @@2172692ba9bd2b3b70c08b164e96151763672fbb42893a79755fcefc052720d9 toast:swarm@0@60022083bf5827695add306905a71f6e07a70ec12872d2d4ed3cc043e47de7205cd talk:fw:quiet@60022083bf5827695add306905a71f6e07a70ec12872d2d4ed3cc043e47de7205cd talk:fw@600+23e68560392ecd11064d29d814622477971a19730d14ee5dbb2ade55786f38a9 lead:pill@500024e4b487e56cee7639400ebd1ed0d473a12cf553c31c0f3029edf019e1f36bc0 tabs:5@5000262c9840a592d18fb40f708dd67525bfdb25339f5034f2bef446bc6a3293c84f home:swarm:remote@026a207f8ff8046c6711fdb779b28735365e90b65907cc41f6222b30541d9e5dd tabs:working@0@@ -108,6 +111,7 @@3bcdfa6e218c2e1999bce65a891884f93737cd2aa62534e0f42538422db352d3 home:swarm:stuck@03c50228ed125d5138821ae678ebc8267734a5e79c8878b4e4813ebbcb80b3164 agent:fw:long@12343d43bb7cb2ab0102944745f80af971677a75bec05d5dbc01baaf9003fa4111f9 tabs:5@1234+418614ce34fdeeee7e28d684674adfbd6c89f9b63f71ff66134e5a882361f65d lead:pill@2500447afe7920f02e419734787791934e1785fc29309ee26a1566b5005fb31bee79 lead:group@250044c082278989b9844c91c372d51a9f2b29430bf083fcb2794698e189fe8f2e3d tabs:none@60045de9aa8132e2d8f8e14853abb8ee563e660be15078bc812aa6d4795c95c7cfb tabs:long@5000@@ -129,16 +133,23 @@4e1055e7920922bf2c1ba0212b5860b7cdcc162784a16e1d9abd6c586d38cec0 recap:docs:toast@4900@50004e1055e7920922bf2c1ba0212b5860b7cdcc162784a16e1d9abd6c586d38cec0 recap:docs:toast@4900@6004f2fd4fcf7e132109a5bd14d6b69cf098d67134249386193b386124d7a58ae63 home:swarm:p1@600+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@0+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@1234+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@2500+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@5000+4f57dc52df1225779e782842562b10385c41d0e5e861ddda07d1c52663e16c93 lead:buddy@60050515880623dbb0b9854175e41174c31d6396b40c576932cad2dcc5e36cff96e tabs:seven@123450e26b3c495b054fb16aaf4e792d49234f9d636fa88c4b3520512e75cdf1dc9d recap:desk:long@5000555f603431f0bf42d41c4d306f98e099d3b22296d9fdf75c78282914f957bb3e home:swarm:p1@0563511c0d14d64810e80ffec87a44aa96ebd49b0d22af294aa6580ad3c715d10 home:swarm:many@05647a2a762bd817469bff3189b4e1162fb3b11acbbc72ad9aee9139e0446a010 recap:docs:long@05647a2a762bd817469bff3189b4e1162fb3b11acbbc72ad9aee9139e0446a010 recap:docs:long@2500+5829a4f1dec01b900a81a0a190a74e5887425211e74a777cd4239d1d756a5f7a lead:pill@05acb2d70fc0480116a86cbbf66fcc15390559f258a7cdacf1c2044615cd7135a lead:remote@12345ce5a5aebccdcd1e858832bd35d7de3235502512ef08f0b337da4fb16ee30791 talk:fw:quiet@05ce5a5aebccdcd1e858832bd35d7de3235502512ef08f0b337da4fb16ee30791 talk:fw@06138d6c974e4bab23a707281fa6fa85203220141424ab54f216b7b6d65f03eab tabs:working@2500+61f0d3f25cc1b39009ab00625771767aa988389805f1e704c55128578231e87d lead:buddy-dot@500061f95986c2394dfd1175e703e8e5b8c011065d8704e8404984b9ddae1473a29c talk:be@066c0d32cef1ff955274fa76dcf012efa2b6fd0306205cfefebfca9d1e5f1a0f3 agent:be@123467b7fd29c369b0f8bbc30460233d7f3a8b5777e2729e4fcb2abbc6396f8e7f67 agent:fw:long@0@@ -186,6 +197,11 @@7e560682e42982215f0b39450ac55bb2059d9b70065772979fcdb7b3c3cf9fe9 lead:none@07e560682e42982215f0b39450ac55bb2059d9b70065772979fcdb7b3c3cf9fe9 lead:none@50007effffc339beb6a37a3cbcc5cb51fe7c836ef949dcb216825da4bfe0129722dd lead:loaded@5000+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@0+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@1234+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@2500+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@5000+7f05e7c7638dc4a3053534d95688d04eb3f687ded2113ac699da568f7ec04c9f lead:buddy-offline@6007fa039f5ebda47a61985054e836d0373bffba85f07667ef3decc52685b752e01 home:swarm:remote@500081312fbd4dee9803a32e5d3aa5fb3b317eafb965fa337f4fadaec149959bc0fc tabs:seven@081cb592818416fb5bbdc363d609b1f9993a87cf61f00e50b60b83d47821b389a lead:loading@1234@@ -225,6 +241,7 @@9569396d08f53a25947caa402456c5a4b9bfe8dbdd37663d52fc7ce6aed5ccb9 lead:loading@500097096110794ece76a2ab0b9f8d01618e360541a3acf1bd584d8fbaa95b0d0d67 lead:ask@0977bddb50cbd047bb41ea02dc9d04f75518bfefe9e25944de93d0fce40b7e51a talk:cur:send@5000+979c3045417fac9f6e1e33340144b0f2a84168c3e2b49c0c328197f3a8cade05 lead:pill@60097cf9dd9e3d5e04d7b553aa767fc765a3bd47cc1160f327538f227b2fd0fcd5b recap:desk:short@50009a206f39596831defafff0aff579c7b4f52fd61029620d3beb2833b56b8ebb67 lead:loading@6009d4fe63cb69c23d6b2426944145e2b17ce8040e73c703944bc507366a6c40126 lead:group@0@@ -290,6 +307,7 @@ bc53b18da4d7ea38f8dd56e0b4470d4e0c4e2cadde1c06ffea5153c907b15fc2 talk:fw:send@2bc53b18da4d7ea38f8dd56e0b4470d4e0c4e2cadde1c06ffea5153c907b15fc2 talk:fw:send@5000bc53b18da4d7ea38f8dd56e0b4470d4e0c4e2cadde1c06ffea5153c907b15fc2 talk:fw:send@600bc92dbc7694b741e98f74a47554b9e40581c98efc715b713b1feaa73d90e390b recap:desk:medium@1234+bddbf0df0f3592d341a0079483582e8d434401aeefd088b6f5bfac5a9da7cdee lead:buddy-dot@0bea341256b62baa2f37ad783b5921ce770c2a3342e9d5a999322be7c60c5f9ff talk:cur@2500beea941441c90a67801395000a40ac5ae7b3bf55377c95e70b4fa0751b973d95 agent:be:offline@600c158dad57e29a9df5ca9b0169c6f1367dac791a7126326aeca42ee6cfc67e090 tabs:1@2500@@ -362,7 +380,13 @@ e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@1e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@2500e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@5000e1788054013a3e7d0de30c89a433ced3cb54ecca26683ffbff6693e33ab5df09 tabs:notices@600+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@0+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@1234+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@2500+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@5000+e190aa3782735b2af2d3c2dd4e920092439110aff812039ef3d7ad16cb5591f6 lead:nobuddy@600e1ff6c4a58d744e05300c2a57be4e08d5f29cc531a741a83c649a892ab7de29a recap:desk:long@1234+e44f8afa6ce8902a8193528267edebb50d932a816a61e00e6d728282354a0ba6 lead:buddy-dot@600e55b4e490d71c454af6cd36f6778798a187eacfcce2b18ca7579fffc5b386bb0 agent:cli:banner@600e55b4e490d71c454af6cd36f6778798a187eacfcce2b18ca7579fffc5b386bb0 agent:cli@600e613555b96ab955404f55d39984791e73f9cce4acd1ebaf9b0e735b0c2be7f8e home:swarm:many@600@@ -374,6 +398,7 @@ e652d520e88b1d12b1fe7409e957a1065d69f7683ce6d1e8cd2caaca93c725ad tabs:2+2@600e6a3ea32881c13627d6043a18efae1b4578e2c62467b1989129c0a8da1b57032 lead:none@1234e6a7fa14ee6c9191350176f8dfcf0661da526268a3d14d912f6337e048b39cbf tabs:1@1234e863aabe59e0ae473cf778a960aa06a49b819ccc2af11dd203351c7e5981c94f home:swarm:stuck@5000+e8dff950a5f35185a2195103620b9e15e5f80611b8e20fef3db2eed4604b82dc lead:buddy-dot@2500e8f82832b80bcf61502a843b8ebc9523b41386be13fdafcc1cf2d5f5e00922ad inbox:quiet@0e8f82832b80bcf61502a843b8ebc9523b41386be13fdafcc1cf2d5f5e00922ad inbox:quiet@1234e8f82832b80bcf61502a843b8ebc9523b41386be13fdafcc1cf2d5f5e00922ad inbox:quiet@2500diff --git a/devices/harness-pro/firmware/test/pod_render.c b/devices/harness-pro/firmware/test/pod_render.cindex 0e0df65dc..302f2bed6 100644--- a/devices/harness-pro/firmware/test/pod_render.c+++ b/devices/harness-pro/firmware/test/pod_render.c@@ -352,13 +352,15 @@ static void swarm_fixture(const char *kind)}}-// lead:<loaded|ask|loading|none|remote|group|pm>: the Lead view over Home (the mockup swarm-card.html B1, B2, and the loading, no-message and remote-Lead states). loaded: the working+// lead:<loaded|ask|loading|none|remote|group|pm|pill|buddy|buddy-offline|nobuddy|buddy-dot>: the Lead view over Home (the mockup swarm-card.html B1, B2, and the loading, no-message and remote-Lead states). loaded: the working// "harness" Lead (B1); ask: "mobile", which needs you (B2, the orange edge); loading: "website" before its message came; none: "backend", which has said nothing; remote:// a Lead on another person's machine (its owner shown, no talk); group / pm: the loaded Lead with its chat named ("review-cable-fit", "PM").static void lead_fixture(const char *kind){const bool group = !strcmp(kind, "group"), pm = !strcmp(kind, "pm"), remote = !strcmp(kind, "remote");- if (group || pm) kind = "loaded"; // the loaded Lead, with the chat the desktop has open named under the project+ const bool pill = !strcmp(kind, "pill"), buddy = !strcmp(kind, "buddy"), offline = !strcmp(kind, "buddy-offline"), nobuddy = !strcmp(kind, "nobuddy"), dot = !strcmp(kind, "buddy-dot");+ const bool buddies = pill || buddy || offline || nobuddy || dot;+ if (group || pm || buddies) kind = "loaded"; // the loaded Lead, with the chat the desktop has open named under the projectswarm_fixture(remote ? "remote" : "p1");const pod_swarm_t *sw = pod_model_swarm(&M, remote ? "sw2" : "sw1");const int at = remote ? 0 : !strcmp(kind, "loaded") ? 1 : !strcmp(kind, "ask") ? 0 : !strcmp(kind, "loading") ? 2 : 3;@@ -369,7 +371,21 @@ static void lead_fixture(const char *kind)cl->chat = group ? POD_CHAT_GROUP : POD_CHAT_PM;snprintf(cl->chat_name, sizeof cl->chat_name, "%s", group ? "review-cable-fit" : "PM");}- if (!strcmp(kind, "loaded")) asked_recap(&M, sw->id, id, "PR #1492 is merged and backend 1.2.100 is on production. The Pro took the test flash. Next: waiting for you to try it on the device.", 1792560000u, false);+ if (buddies) { // PM | Buddy: the pill on; pill: the PM side; buddy / buddy-offline: Mira, her chat the face; nobuddy: the Buddy side with none; buddy-dot: the PM side with the Buddy's dot+ pod_swarm_t *ws = &M.swarms[0];+ pod_lead_t *cl = &ws->leads[at];+ cl->buddies = true;+ ws->side = buddy || offline || nobuddy ? POD_SIDE_BUDDY : POD_SIDE_PM;+ cl->buddy_unread = dot;+ if (buddy || offline || dot || pill) {+ cl->has_buddy = true;+ snprintf(cl->buddy.chat_id, ID_MAX, "bc1"); snprintf(cl->buddy.name, sizeof cl->buddy.name, "Mira"); snprintf(cl->buddy.engine, sizeof cl->buddy.engine, "claude");+ cl->buddy.cells = 0x2B5D; cl->buddy.color = 0xC49BFF; cl->buddy.live = !offline;+ }+ if (buddy || offline) { cl->chat = POD_CHAT_BUDDY; snprintf(cl->chat_name, sizeof cl->chat_name, "Mira"); }+ }+ if (buddy || offline) asked_recap(&M, sw->id, id, "Morning! I read the Swarm overnight. Two Leads are waiting on you: mobile needs a TestFlight call, and docs wants a review.", 1792560000u, false);+ else if (!strcmp(kind, "loaded")) asked_recap(&M, sw->id, id, "PR #1492 is merged and backend 1.2.100 is on production. The Pro took the test flash. Next: waiting for you to try it on the device.", 1792560000u, false);else if (!strcmp(kind, "ask")) asked_recap(&M, sw->id, id, "iOS 1.0.9 finished building. Do you want it on TestFlight now, or wait for the Android banner fix?", 1792560000u, false);else if (remote) asked_recap(&M, sw->id, id, "Staging is up on the new region. I am moving the queue workers over now; the first batch should land within the hour.", 1792560000u, false);else if (!strcmp(kind, "loading")) pod_model_supertab_loading(&M, sw->id, id);diff --git a/devices/harness-pro/firmware/test/stress_pro_app.c b/devices/harness-pro/firmware/test/stress_pro_app.cindex a14625a11..1cde36e09 100644--- a/devices/harness-pro/firmware/test/stress_pro_app.c+++ b/devices/harness-pro/firmware/test/stress_pro_app.c@@ -63,6 +63,7 @@ void pro_display_power(bool on) { (void)on; }pro_touch_sample_t pro_touch_poll(int *x, int *y) { (void)x; (void)y; return PRO_TOUCH_NONE; }bool pro_cable_send_open(const char *id) { CHECK(LOCK_DEPTH == 0); (void)id; return true; }bool pro_cable_supertab_send(const char *t, const char *tab, const char *lead) { CHECK(LOCK_DEPTH == 0); (void)t; (void)tab; (void)lead; return true; }+bool pro_cable_supertab_side(const char *tab, const char *side) { CHECK(LOCK_DEPTH == 0); (void)tab; (void)side; return true; }bool pro_cable_send_scroll(pro_scroll_phase_t phase, int dy, int velocity) { (void)phase; (void)dy; (void)velocity; return true; }static int lib_req_offset = -1;static uint32_t lib_req_id;@@ -71,7 +72,7 @@ bool pro_cable_library_supported(void) { return true; }cable_link_stats_t cable_link_stats(void) { return (cable_link_stats_t){0}; }uint32_t pro_cable_seq_gaps(void) { return 0; }void pro_cable_counters(uint32_t *bad, uint32_t *unknown) { *bad = 0; *unknown = 0; }-void pro_voice_begin(const char *agent) { (void)agent; }+void pro_voice_begin(const char *agent, bool face) { (void)agent; (void)face; }void pro_voice_end(bool send) { (void)send; }bool pro_voice_open(void) { return false; }unsigned pro_rec_level(void) { return 0; }diff --git a/devices/harness-pro/firmware/test/test_ph_glue.c b/devices/harness-pro/firmware/test/test_ph_glue.cindex d616584cc..02a9ff802 100644--- a/devices/harness-pro/firmware/test/test_ph_glue.c+++ b/devices/harness-pro/firmware/test/test_ph_glue.c@@ -1715,6 +1715,7 @@ static uint32_t NOW = 3000; // the clock a focus is fed (the quiet window counstatic pod_supertab_out_t Q[POD_SUPERTAB_OUT_MAX];static int take(void) { return pod_ui_take_supertab(&U, Q, POD_SUPERTAB_OUT_MAX); }static bool is_q(int i, const char *t, const char *tab, const char *lead) { return !strcmp(Q[i].t, t) && !strcmp(Q[i].tab, tab) && !strcmp(Q[i].lead, lead); }+static int hit_count_of(pod_action_t a) { int n = 0; for (int i = 0; i < U.frame.hit_count; i++) n += U.frame.hits[i].action == a; return n; }static void tap_lead(int k, uint32_t t) { // a tap on the pet of the card's Lead at index k (the page holding it must be on screen)render(t - 50);for (int i = 0; i < U.frame.hit_count; i++)@@ -1773,7 +1774,7 @@ static void swarm_lead_open(int k) { // sw1 on Home, the Lead at index k open}static void swarm_notice_toasts_and_beeps(void) {swarm_lead_open(1); // l1's view: a notice from l2 is for another screen- CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Cable fit now counts tokens. More.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Cable fit now counts tokens. More.", true, 3400));const pod_unread_t *e = pod_model_unread_find(&U.model, "l2");CHECK(e && !strcmp(e->tab, "sw1") && !strcmp(e->chat_id, "c1") && !strcmp(e->name, "proj2") && U.model.unread_count == 1);CHECK(U.ban_on && U.ban_until == 3400 + POD_TOAST_MS && !U.ban_stay);@@ -1785,15 +1786,15 @@ static void swarm_notice_toasts_and_beeps(void) {// a room is a place for it too, and a notice for a Lead the model does not hold is droppedfresh();to_agent(0, 2);- CHECK(!pod_ui_swarm_notice(&U, "sw1", "l9", "c1", "x", true, 4000) && U.model.unread_count == 0);+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l9", "pm", "c1", "x", true, 4000) && U.model.unread_count == 0);swarm_home(4);to_agent(0, 2);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l0", "c1", "Hi.", true, 4000) && U.ban_on);+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l0", "pm", "c1", "Hi.", true, 4000) && U.ban_on);render(4000);CHECK(U.frame.banner);// a dark glass is news: the row, and the caller wakesswarm_lead_open(1);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l1", "c1", "Hi.", false, 4000) && pod_model_unread_find(&U.model, "l1"));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l1", "pm", "c1", "Hi.", false, 4000) && pod_model_unread_find(&U.model, "l1"));}static bool select_taken(void) {const int n = take();@@ -1804,7 +1805,7 @@ static bool select_taken(void) {static void swarm_notice_goes_with_its_swarm(void) {// the Swarm leaves the list while its toast showsswarm_lead_open(1);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Private words.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Private words.", true, 3400));render(3400);CHECK(U.frame.banner);pod_ui_supertab_ids(&U, NULL, 0);@@ -1813,7 +1814,7 @@ static void swarm_notice_goes_with_its_swarm(void) {// a Lead leaves its Swarm while its toast shows; a finger on the toast opens no Lead and sends no selectswarm_lead_open(1);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Private words.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Private words.", true, 3400));render(3400);const pod_hit_t *h = find(POD_A_BANNER);CHECK(h);@@ -1832,7 +1833,7 @@ static void swarm_notice_goes_with_its_swarm(void) {// a finger on a Notices row when the Swarm goes: nothing opens, and the row is off the next frameswarm_home(4);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Private words.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Private words.", true, 3400));act(POD_A_INBOX, 0);render(3420);CHECK(top()->view == POD_V_INBOX);@@ -1849,7 +1850,7 @@ static void swarm_notice_goes_with_its_swarm(void) {}static void notif_replace_keeps_swarm_notices(void) {swarm_lead_open(1);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Merged.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Merged.", true, 3400));pod_model_unread_add(&U.model, "a2", "Beta", "Done.", 20, 3410);pod_ui_notif_begin(&U);CHECK(pod_model_unread_find(&U.model, "l2") && !pod_model_unread_find(&U.model, "a2") && U.model.unread_count == 1);@@ -1858,7 +1859,7 @@ static void notif_replace_keeps_swarm_notices(void) {static void swarm_notice_on_its_lead_view_reads_at_once(void) {swarm_lead_open(1);snprintf(U.model.swarms[0].leads[1].chat_id, ID_MAX, "c1"); // the face shows the chat the notice is for- CHECK(!pod_ui_swarm_notice(&U, "sw1", "l1", "c1", "Seen already.", true, 3400));+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l1", "pm", "c1", "Seen already.", true, 3400));CHECK(U.model.unread_count == 0 && !U.ban_on);render(3500);CHECK(!U.frame.banner);@@ -1866,15 +1867,15 @@ static void swarm_notice_on_its_lead_view_reads_at_once(void) {static void notice_for_other_chat_on_lead_view_files_row(void) {swarm_lead_open(1);snprintf(U.model.swarms[0].leads[1].chat_id, ID_MAX, "g1"); // the face shows g1; the notice is for c1- CHECK(pod_ui_swarm_notice(&U, "sw1", "l1", "c1", "Elsewhere.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l1", "pm", "c1", "Elsewhere.", true, 3400));const pod_unread_t *e = pod_model_unread_find(&U.model, "l1");CHECK(e && !strcmp(e->chat_id, "c1"));}static void notice_for_face_chat_on_lead_view_clears_old_row(void) {swarm_lead_open(1);snprintf(U.model.swarms[0].leads[1].chat_id, ID_MAX, "g1");- CHECK(pod_ui_swarm_notice(&U, "sw1", "l1", "c1", "Older.", true, 3300)); // an older row of this Lead- CHECK(!pod_ui_swarm_notice(&U, "sw1", "l1", "g1", "Seen.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l1", "pm", "c1", "Older.", true, 3300)); // an older row of this Lead+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l1", "pm", "g1", "Seen.", true, 3400));CHECK(!pod_model_unread_find(&U.model, "l1") && U.model.unread_count == 0);}static void chat_switch_asks_recap_at_once(void) {@@ -1896,7 +1897,7 @@ static void chat_switch_asks_recap_at_once(void) {}static void swarm_toast_tap_opens_lead_and_selects(void) {swarm_lead_open(1);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Merged.", true, 3400));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Merged.", true, 3400));render(3400);CHECK(U.frame.banner);pod_out_t o = tap_(360, 80, 3500);@@ -1907,7 +1908,7 @@ static void swarm_toast_tap_opens_lead_and_selects(void) {static void swarm_row_tap_opens_lead_and_selects(void) {swarm_home(4);pod_model_unread_add(&U.model, "a2", "Beta", "Done.", 20, 2100);- CHECK(pod_ui_swarm_notice(&U, "sw1", "l3", "c1", "Merged.", true, 2200));+ CHECK(pod_ui_swarm_notice(&U, "sw1", "l3", "pm", "c1", "Merged.", true, 2200));act(POD_A_INBOX, 0);render(2500);const pod_hit_t *h = NULL;@@ -1921,7 +1922,7 @@ static void swarm_row_tap_opens_lead_and_selects(void) {}static void swarm_notice_read_ends_toast(void) {swarm_lead_open(1);- pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Merged.", true, 3400);+ pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Merged.", true, 3400);render(3400);CHECK(U.frame.banner);pod_ui_swarm_notice_read(&U, "sw1", "l2", "c2"); // another chat's read: the row and the toast stay@@ -1931,9 +1932,9 @@ static void swarm_notice_read_ends_toast(void) {render(3600);CHECK(!U.ban_on && !U.frame.banner && !pod_model_unread_find(&U.model, "l2"));// a read of an entry that is not the toast's leaves that toast up- pod_ui_swarm_notice(&U, "sw1", "l2", "c1", "Merged.", true, 3700);+ pod_ui_swarm_notice(&U, "sw1", "l2", "pm", "c1", "Merged.", true, 3700);pod_model_unread_add(&U.model, "a1", "Alpha", "x", 1, 3700);- pod_ui_swarm_notice(&U, "sw1", "l0", "c5", "Other.", true, 3750); // the newer toast is l0's+ pod_ui_swarm_notice(&U, "sw1", "l0", "pm", "c5", "Other.", true, 3750); // the newer toast is l0'spod_ui_swarm_notice_read(&U, "sw1", "l2", "c1");render(3800);CHECK(U.ban_on && !strcmp(U.ban_agent, "l0") && U.frame.banner);@@ -2082,7 +2083,6 @@ static void lead_talk(void) {swarm_home(4);pod_swarm_t *sw = (pod_swarm_t *)pod_model_swarm(&U.model, "sw1");snprintf(sw->leads[1].local, ID_MAX, "a1"); // Alpha is this Lead's harness- snprintf(sw->leads[2].local, ID_MAX, "nobody"); // a harness the roster does not hold: nothing to talk totap_lead(1, 3000);CHECK(!strcmp(top()->agent, "a1") && take() == 3);render(3500);@@ -2099,7 +2099,7 @@ static void lead_talk(void) {pod_nav_act(&U.nav, &U.model, POD_A_NEXT, 0, 6100);CHECK(top()->view == POD_V_TALK && top()->lead == 1);pod_ui_talk_over(&U);- // a remote Lead, or one whose harness is not on the roster, has no talk control+ // a remote Lead (no local harness, no swarm.remote) has no talk control; one whose local harness is off the roster does: see local_lead_not_in_roster_talks_with_localswipe(600, 400, 200, 410, 7000);CHECK(top()->lead == 2 && !top()->agent[0]);render(7500);@@ -2284,11 +2284,381 @@ static void swarm_card_shrinks(void) {CHECK(!find(POD_A_LEAD) && find(POD_A_ENTER_TAB));}+// A side the person picked is owed to the daemon as supertab.side {tab, side}; it takes a queue slot like the other frames.+static void side_frame_queued(void) {+ swarm_home(4);+ take();+ CHECK(pod_ui_supertab_side(&U, "S1", POD_SIDE_BUDDY));+ CHECK(pod_ui_supertab_side(&U, "S1", POD_SIDE_PM));+ CHECK(!pod_ui_supertab_side(&U, "S1", POD_SIDE_NONE));+ const int n = take();+ CHECK(n == 2 && !strcmp(Q[0].t, "supertab.side") && !strcmp(Q[0].tab, "S1") && !strcmp(Q[0].side, "buddy") && !strcmp(Q[1].side, "pm"));+ for (int i = 0; i < POD_SUPERTAB_OUT_MAX; i++) CHECK(pod_ui_supertab_side(&U, "S1", POD_SIDE_PM));+ CHECK(!pod_ui_supertab_side(&U, "S1", POD_SIDE_PM)); // full: not sent+ take();+}+++// ---- PM | Buddy: the pill on the Lead view (a hit, never a talk), the Buddy's quiet dot ----+static pod_swarm_t *buddy_swarm(void) { return (pod_swarm_t *)pod_model_swarm(&U.model, "sw1"); }+static void buddy_lead_open(void) { // sw1's Lead l1 open (its harness a1, talkable), with a Buddy side+ swarm_home(4);+ pod_swarm_t *sw = buddy_swarm();+ snprintf(sw->leads[1].local, ID_MAX, "a1");+ for (int i = 0; i < 4; i++) { sw->leads[i].buddies = true; sw->leads[i].has_buddy = true; snprintf(sw->leads[i].buddy.chat_id, ID_MAX, "bc%d", i); snprintf(sw->leads[i].buddy.name, sizeof sw->leads[i].buddy.name, "Mira"); }+ sw->side = POD_SIDE_PM;+ tap_lead(1, 3000);+ CHECK(top()->view == POD_V_LEAD && top()->lead == 1);+ take();+ render(3300);+}+static void pill_tap_sends_side(void) {+ buddy_lead_open();+ CHECK(hit_count_of(POD_A_SIDE) == 2);+ pod_out_t o = tap_(435, 38, 4000); // the Buddy segment+ CHECK(o.fx == POD_FX_NONE && top()->view == POD_V_LEAD);+ CHECK(take() == 1 && !strcmp(Q[0].t, "supertab.side") && !strcmp(Q[0].tab, "sw1") && !strcmp(Q[0].side, "buddy"));+ render(4500);+ o = tap_(285, 38, 5000); // PM+ CHECK(o.fx == POD_FX_NONE && take() == 1 && !strcmp(Q[0].t, "supertab.side") && !strcmp(Q[0].side, "pm"));+}+static void pill_tap_never_talks(void) { // the PM segment, as in part 2 (where a Buddy press shows the Buddy side, which did not talk)+ buddy_lead_open();+ t_(true, 285, 38, 4000);+ CHECK(!U.talk_armed);+ pod_out_t o = t_(false, 285, 38, 4050);+ CHECK(o.fx == POD_FX_NONE && top()->view == POD_V_LEAD && !U.hands_free);+ take();+ render(4200);+ t_(true, MID_X, MID_Y, 5000); // an armed talk on the body ...+ CHECK(U.talk_armed);+ t_(true, 285, 38, 5100); // ... is dropped when the finger leaves for the pill+ CHECK(!U.talk_armed);+ o = t_(false, 285, 38, 5150);+ CHECK(o.fx == POD_FX_NONE && top()->view == POD_V_LEAD && !U.hands_free);+ // and the body still talks+ take();+ o = tap_(MID_X, MID_Y, 6000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "a1"));+}+// ---- Talk to a remote Lead and to the Buddy (swarm.remote): voice.begin carries the Lead's id, the talk view signs the Buddy ----+static int talk_bars(void) { int n = 0; for (int i = 0; i < S.count; i++) n += S.runs[i].pro_kind == 4 && S.runs[i].w == 9 && S.runs[i].fg == ht_rgb(0x00FF2F); return n; }+static bool talk_text(const char *t, unsigned rgb) {+ for (int i = 0; i < S.count; i++) if (S.runs[i].pro_kind == 1 && !strcmp(S.runs[i].text, t) && (!rgb || S.runs[i].fg == ht_rgb(rgb))) return true;+ return false;+}+static void remote_lead_talks_with_swarm_remote(void) {+ swarm_home(4);+ pod_ui_set_swarm_remote(&U, true);+ tap_lead(2, 3000); // l2 has no local harness+ take();+ render(3300);+ CHECK(!top()->agent[0]);+ pod_out_t o = tap_(MID_X, MID_Y, 4000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "l2") && top()->view == POD_V_TALK && pod_ui_talking(&U));+ render(4500);+ CHECK(talk_text("Lead", 0)); // no roster agent, but the voice view still draws: the Lead's name, as its who row+ o = tap_(MID_X, MID_Y, 5000);+ CHECK(o.fx == POD_FX_VOICE_END && top()->view == POD_V_TALK);+ // swarm_talk_ends_on_transcript: words for a Swarm face go to its chat, not a terminal turn: the daemon's+ // transcript ends the voice screen at once (pro_app_voice_result), as on the round, instead of 30 s of "sending"+ CHECK(pod_ui_talking_to_swarm(&U));+ pod_ui_talk_over(&U);+ CHECK(top()->view == POD_V_LEAD && !pod_ui_talking_to_swarm(&U));+ // the link going down takes the feature with it+ pod_ui_link(&U, false);+ CHECK(!U.swarm_remote);+}+static void remote_lead_no_talk_without_feature(void) {+ swarm_home(4);+ tap_lead(2, 3000);+ take();+ render(3300);+ CHECK(tap_(MID_X, MID_Y, 4000).fx == POD_FX_NONE && top()->view == POD_V_LEAD && !U.talk_armed);+ pod_ui_set_swarm_remote(&U, true);+ pod_ui_set_swarm_remote(&U, false);+ CHECK(tap_(MID_X, MID_Y, 5000).fx == POD_FX_NONE && top()->view == POD_V_LEAD);+}+static void buddy_screen_talks_with_lead_id(void) {+ buddy_lead_open(); // l1: local a1+ buddy_swarm()->leads[1].chat = POD_CHAT_BUDDY;+ buddy_swarm()->leads[2].chat = POD_CHAT_BUDDY;+ render(3500);+ pod_out_t o = tap_(MID_X, MID_Y, 4000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "a1")); // the same id as the PM side: the daemon picks the Buddy chat from the side it holds+ CHECK(pod_ui_talking_to_swarm(&U)); // a local Lead's face too: the Buddy's chat, never a1's terminal turn+ pod_ui_talk_over(&U);+ buddy_swarm()->leads[1].chat = POD_CHAT_PM;+ render(4500);+ o = tap_(MID_X, MID_Y, 5000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "a1"));+ pod_ui_talk_over(&U);+ // a remote Lead on its Buddy side: its own id+ pod_ui_set_swarm_remote(&U, true);+ pod_nav_act(&U.nav, &U.model, POD_A_NEXT, 0, 6000);+ take();+ CHECK(top()->lead == 2);+ render(6500);+ o = tap_(MID_X, MID_Y, 7000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "l2"));+}+static void buddy_talk_uses_buddy_engine_pet(void) {+ buddy_lead_open(); // the Lead is claude (a pet); give the Buddy an engine without one+ pod_lead_t *l = &buddy_swarm()->leads[1];+ snprintf(l->engine, sizeof l->engine, "claude");+ snprintf(l->buddy.engine, sizeof l->buddy.engine, "cursor");+ l->chat = POD_CHAT_PM;+ render(3500);+ CHECK(tap_(MID_X, MID_Y, 4000).fx == POD_FX_VOICE_BEGIN);+ render(4500);+ CHECK(talk_bars() == 0); // the Lead's own pet+ pod_ui_talk_over(&U);+ l->chat = POD_CHAT_BUDDY;+ render(5000);+ CHECK(tap_(MID_X, MID_Y, 5500).fx == POD_FX_VOICE_BEGIN);+ render(6500);+ CHECK(talk_bars() == 7); // the Buddy's engine has no pet: the round's effect+ CHECK(pod_view_next_ms(&U.nav, &U.model, 6500) == 80 - 6500 % 80);+}+static void buddy_talk_names_buddy(void) {+ buddy_lead_open();+ pod_lead_t *l = &buddy_swarm()->leads[1];+ l->chat = POD_CHAT_BUDDY;+ render(3500);+ CHECK(tap_(MID_X, MID_Y, 4000).fx == POD_FX_VOICE_BEGIN);+ render(4500);+ CHECK(talk_text("Mira", 0xC49BFF) && !talk_text("Alpha", 0));+ pod_ui_talk_over(&U);+ l->chat = POD_CHAT_PM;+ render(5000);+ CHECK(tap_(MID_X, MID_Y, 5500).fx == POD_FX_VOICE_BEGIN);+ render(6500);+ CHECK(talk_text("Alpha", PH_ROOM_INK) && !talk_text("Mira", 0)); // the PM side: the agent, as today+}+static void talk_name_pinned_at_begin(void) {+ buddy_lead_open();+ pod_lead_t *l = &buddy_swarm()->leads[1];+ l->chat = POD_CHAT_BUDDY;+ render(3500);+ CHECK(tap_(MID_X, MID_Y, 4000).fx == POD_FX_VOICE_BEGIN);+ l->chat = POD_CHAT_PM; // a desktop side flip mid-recording: the daemon posts to the face it pinned at voice.begin+ render(4500);+ CHECK(talk_text("Mira", 0xC49BFF) && !talk_text("Alpha", 0) && !talk_text("Lead", 0));+ pod_ui_talk_over(&U);+ render(5000);+ CHECK(tap_(MID_X, MID_Y, 5500).fx == POD_FX_VOICE_BEGIN); // PM side now: the next talk pins the agent+ l->chat = POD_CHAT_BUDDY;+ render(6500);+ CHECK(talk_text("Alpha", PH_ROOM_INK) && !talk_text("Mira", 0));+}+static void local_lead_not_in_roster_talks_with_local(void) {+ swarm_home(4);+ snprintf(buddy_swarm()->leads[2].local, ID_MAX, "zz"); // a harness the Pro's agent list does not hold+ pod_ui_set_swarm_remote(&U, true);+ tap_lead(2, 3000);+ take();+ render(3300);+ pod_out_t o = tap_(MID_X, MID_Y, 4000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "zz")); // the round's rule: `local` whenever set, so the daemon pins the face+ render(4500);+ CHECK(talk_text("Lead", 0));+ pod_ui_talk_over(&U);+ pod_ui_set_swarm_remote(&U, false); // and without swarm.remote it still talks with its local id+ render(5000);+ CHECK(tap_(MID_X, MID_Y, 5500).fx == POD_FX_VOICE_BEGIN);+}+static void buddy_talk_not_blocked_by_question(void) {+ buddy_lead_open(); // l1: local a1+ pod_model_question(&U.model, "a1", "Proceed?"); // the terminal's question: words for a Swarm face go to its chat+ CHECK(pod_model_eff(&U.model, pod_model_find(&U.model, "a1")) == POD_ASKING);+ buddy_swarm()->leads[1].chat = POD_CHAT_BUDDY;+ render(3500);+ CHECK(tap_(MID_X, MID_Y, 4000).fx == POD_FX_VOICE_BEGIN);+ pod_ui_talk_over(&U);+ buddy_swarm()->leads[1].chat = POD_CHAT_PM;+ render(4500);+ CHECK(tap_(MID_X, MID_Y, 5000).fx == POD_FX_VOICE_BEGIN);+}+static void pill_pressed_until_frame(void) {+ buddy_lead_open();+ tap_(435, 38, 4000);+ CHECK(U.model.side_press == POD_SIDE_BUDDY && !strcmp(U.model.side_press_swarm, "sw1") && buddy_swarm()->side == POD_SIDE_PM); // pending, the daemon has not answered+ take();+ render(4200);+ { bool buddy_on = false; for (int i = 0; i < S.count; i++) buddy_on |= S.runs[i].x == 360 && S.runs[i].y == 16 && S.runs[i].w == 150; CHECK(buddy_on); }+ static pod_swarm_t fr; // another Swarm's frame does not end it, this Swarm's does+ memset(&fr, 0, sizeof fr);+ snprintf(fr.id, ID_MAX, "sw2"); snprintf(fr.name, sizeof fr.name, "Solo"); fr.count = 1; fr.lead_n = 1;+ snprintf(fr.leads[0].id, ID_MAX, "s0"); snprintf(fr.leads[0].project, sizeof fr.leads[0].project, "ops"); snprintf(fr.leads[0].engine, sizeof fr.leads[0].engine, "claude");+ pod_ui_supertab(&U, &fr, 4300);+ CHECK(U.model.side_press == POD_SIDE_BUDDY);+ memset(&fr, 0, sizeof fr);+ snprintf(fr.id, ID_MAX, "sw1"); snprintf(fr.tab, ID_MAX, "s1"); snprintf(fr.name, sizeof fr.name, "openharness"); fr.count = 4; fr.lead_n = 4; fr.side = POD_SIDE_BUDDY;+ for (int i = 0; i < 4; i++) { snprintf(fr.leads[i].id, ID_MAX, "l%d", i); snprintf(fr.leads[i].project, sizeof fr.leads[i].project, "proj%d", i); snprintf(fr.leads[i].engine, sizeof fr.leads[i].engine, "claude"); fr.leads[i].buddies = true; }+ pod_ui_supertab(&U, &fr, 4400);+ CHECK(U.model.side_press == POD_SIDE_NONE && buddy_swarm()->side == POD_SIDE_BUDDY);+}+static void buddy_notice_sets_dot_only(void) {+ buddy_lead_open();+ swipe(200, 400, 600, 410, 3500); // l0: a notice for l1's Buddy is for another screen, where a chat's notice would toast+ take();+ render(3700);+ CHECK(top()->lead == 0);+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l1", "buddy", "bc1", "Hello from your Buddy.", true, 4000));+ CHECK(U.model.unread_count == 0 && !U.ban_on && buddy_swarm()->leads[1].buddy_unread && !buddy_swarm()->leads[0].buddy_unread);+ render(4100);+ CHECK(!U.frame.banner);+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l9", "buddy", "bc1", "x", true, 4200)); // an unknown Lead: nothing+ // the same Buddy chat on screen and the glass lit: seen, no dot+ swipe(600, 400, 200, 410, 4300);+ CHECK(top()->lead == 1);+ buddy_swarm()->leads[1].buddy_unread = false;+ buddy_swarm()->leads[1].chat = POD_CHAT_BUDDY;+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l1", "buddy", "bc1", "Seen.", true, 4600) && !buddy_swarm()->leads[1].buddy_unread && U.model.unread_count == 0);+}+static void opening_buddy_clears_dot(void) {+ buddy_lead_open();+ buddy_swarm()->leads[1].buddy_unread = true;+ buddy_swarm()->leads[2].buddy_unread = true; // another Lead's dot is its own+ render(3400);+ tap_(435, 38, 4000);+ CHECK(!buddy_swarm()->leads[1].buddy_unread && buddy_swarm()->leads[2].buddy_unread);+ take();+ // the daemon's read of the Buddy chat clears it too (a lost tap frame never leaves it)+ pod_ui_swarm_notice_read(&U, "sw1", "l2", "bc2");+ CHECK(!buddy_swarm()->leads[2].buddy_unread);+ buddy_swarm()->leads[2].buddy_unread = true;+ pod_ui_swarm_notice_read(&U, "sw1", "l2", "other");+ CHECK(buddy_swarm()->leads[2].buddy_unread);+ // a tap on PM keeps it+ tap_(285, 38, 6000);+ CHECK(buddy_swarm()->leads[2].buddy_unread);+}+static void relink_clears_buddy_dot(void) {+ buddy_lead_open();+ buddy_swarm()->leads[1].buddy_unread = true;+ tap_(285, 38, 4000); // a pending side+ pod_ui_link(&U, false);+ CHECK(U.model.side_press == POD_SIDE_NONE);+ pod_ui_link(&U, true);+ static const char ids[2][ID_MAX] = {"sw1", "sw2"};+ pod_ui_supertab_ids(&U, ids, 2);+ static pod_swarm_t sw;+ memset(&sw, 0, sizeof sw);+ snprintf(sw.id, ID_MAX, "sw1"); snprintf(sw.tab, ID_MAX, "s1"); snprintf(sw.name, sizeof sw.name, "openharness"); sw.count = 4; sw.lead_n = 4; sw.side = POD_SIDE_BUDDY;+ for (int i = 0; i < 4; i++) { snprintf(sw.leads[i].id, ID_MAX, "l%d", i); snprintf(sw.leads[i].project, sizeof sw.leads[i].project, "proj%d", i); snprintf(sw.leads[i].engine, sizeof sw.leads[i].engine, "claude"); sw.leads[i].buddies = true; }+ pod_ui_supertab(&U, &sw, 5000);+ for (int i = 0; i < 4; i++) CHECK(!buddy_swarm()->leads[i].buddy_unread);+ CHECK(buddy_swarm()->side == POD_SIDE_BUDDY); // the side comes from the daemon's frame+}+static void side_kept_across_swipe(void) {+ buddy_lead_open();+ buddy_swarm()->side = POD_SIDE_BUDDY;+ swipe(600, 400, 200, 410, 4000); // NEXT: l2+ CHECK(top()->lead == 2 && buddy_swarm()->side == POD_SIDE_BUDDY && U.model.side_press == POD_SIDE_NONE);+ for (int i = 0, n = take(); i < n; i++) CHECK(strcmp(Q[i].t, "supertab.side")); // nothing is said about the side+ render(4300);+ { bool buddy_on = false; for (int i = 0; i < S.count; i++) buddy_on |= S.runs[i].x == 360 && S.runs[i].y == 16 && S.runs[i].w == 150; CHECK(buddy_on); }+}++// The "No Buddy here yet" screen is not a chat: a tap on it talks to nobody (the words would land in the Lead's shared chat).+static void nobuddy_screen_never_talks(void) {+ pod_out_t o;+ buddy_lead_open();+ buddy_swarm()->leads[1].has_buddy = false;+ buddy_swarm()->side = POD_SIDE_BUDDY;+ render(3400);+ take();+ t_(true, MID_X, MID_Y, 6000);+ CHECK(!U.talk_armed);+ o = t_(false, MID_X, MID_Y, 6050);+ CHECK(o.fx != POD_FX_VOICE_BEGIN && !U.talk_armed && !pod_ui_talking(&U));+ buddy_swarm()->side = POD_SIDE_PM; // and with the PM side up it talks again+ take();+ o = tap_(MID_X, MID_Y, 7000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "a1"));+}+// Review of #2299 (Heron): part 2 kept the Buddy screen from talking, since a Pro's words posted in the Lead's shared chat. In this part the+// Lead view's talk is a Swarm talk: voice.begin says face (pro_app) and the daemon posts in the face chat the side holds, the Buddy chat here.+static void buddy_screen_talks_to_its_chat(void) {+ pod_out_t o;+ buddy_lead_open();+ buddy_swarm()->side = POD_SIDE_BUDDY; // the Buddy side, with a Buddy: avatar and lilac name+ render(3400);+ take();+ o = tap_(MID_X, MID_Y, 6000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "a1") && pod_ui_talking_to_swarm(&U)); // a face talk, never the terminal's+ pod_ui_talk_over(&U);+ buddy_swarm()->side = POD_SIDE_PM;+ buddy_swarm()->leads[1].chat = POD_CHAT_BUDDY; // the desktop has the Buddy chat open: still a face talk+ render(6100);+ take();+ o = tap_(MID_X, MID_Y, 7000);+ CHECK(o.fx == POD_FX_VOICE_BEGIN && pod_ui_talking_to_swarm(&U));+}+// A tapped segment that no frame answers goes back to the Swarm's own side after POD_SUPERTAB_RETRY_MS, and the view wakes to draw it.+static void pressed_side_expires(void) {+ buddy_lead_open();+ tap_(435, 38, 4000); // the press is taken at 4050+ take();+ CHECK(pod_model_side_shown(&U.model, buddy_swarm()) == POD_SIDE_BUDDY);+ render(4100);+ CHECK(ph_lead_next_ms(&U.nav, &U.model, 4100) <= 2950); // wakes at the expiry+ pod_model_clock(&U.model, 4050 + 2999);+ CHECK(pod_model_side_shown(&U.model, buddy_swarm()) == POD_SIDE_BUDDY);+ pod_model_clock(&U.model, 4050 + 3001);+ CHECK(pod_model_side_shown(&U.model, buddy_swarm()) == POD_SIDE_PM);+}+static void pressed_side_cleared_when_send_fails(void) {+ buddy_lead_open();+ tap_(435, 38, 4000);+ take();+ CHECK(U.model.side_press == POD_SIDE_BUDDY);+ pod_ui_side_unsent(&U, "sw2"); // another Swarm's frame+ CHECK(U.model.side_press == POD_SIDE_BUDDY);+ pod_ui_side_unsent(&U, "sw1");+ CHECK(U.model.side_press == POD_SIDE_NONE && pod_model_side_shown(&U.model, buddy_swarm()) == POD_SIDE_PM);+}+// The dot also goes whenever the Buddy chat is on the face of a lit screen (a notice that came while another Lead was shown).+static void buddy_dot_clears_when_buddy_face_shown(void) {+ buddy_lead_open();+ buddy_swarm()->leads[2].chat = POD_CHAT_BUDDY;+ CHECK(!pod_ui_swarm_notice(&U, "sw1", "l2", "buddy", "bc2", "Hi.", true, 3500) && buddy_swarm()->leads[2].buddy_unread);+ tap_(435, 38, 4000); // Buddy on l1+ take();+ swipe(600, 400, 200, 410, 5000);+ CHECK(top()->lead == 2);+ render(5300);+ tap_(285, 38, 6000); // PM+ CHECK(!buddy_swarm()->leads[2].buddy_unread);+}+int main(void) {notify_while_looking();swarm_card_pages();swarm_card_few_leads();swarm_card_tap();+ side_frame_queued();+ pill_tap_sends_side();+ pill_tap_never_talks();+ remote_lead_talks_with_swarm_remote();+ remote_lead_no_talk_without_feature();+ buddy_screen_talks_with_lead_id();+ buddy_talk_uses_buddy_engine_pet();+ buddy_talk_names_buddy();+ talk_name_pinned_at_begin();+ local_lead_not_in_roster_talks_with_local();+ buddy_talk_not_blocked_by_question();+ pill_pressed_until_frame();+ buddy_notice_sets_dot_only();+ opening_buddy_clears_dot();+ relink_clears_buddy_dot();+ side_kept_across_swipe();+ nobuddy_screen_never_talks();+ buddy_screen_talks_to_its_chat();+ pressed_side_expires();+ pressed_side_cleared_when_send_fails();+ buddy_dot_clears_when_buddy_face_shown();notice_opens_lead();swarm_notice_toasts_and_beeps();swarm_notice_on_its_lead_view_reads_at_once();diff --git a/devices/harness-pro/firmware/test/test_ph_views.c b/devices/harness-pro/firmware/test/test_ph_views.cindex bbadae39a..832372f0a 100644--- a/devices/harness-pro/firmware/test/test_ph_views.c+++ b/devices/harness-pro/firmware/test/test_ph_views.c@@ -57,6 +57,11 @@ static void check_baked(void)// Page dots (a small anti-aliased pill in the bottom band, y >= 660): Pets has none on any page.static int dot_runs(void) { int n = 0; for (int i = 0; i < S.count; i++) n += S.runs[i].pro_kind == K_RECT_AA && (S.runs[i].w == 12 || S.runs[i].w == 11 || S.runs[i].w == 32) && S.runs[i].pro_height <= 12 && S.runs[i].y >= 660; return n; }// The run holding the name/title: centred on x 360 within 2 px.+static const ht_run_t *rect_at(int x, int y, int w, int h) {+ for (int i = 0; i < S.count; i++) if (S.runs[i].pro_kind == K_RECT_AA && S.runs[i].x == x && S.runs[i].y == y && S.runs[i].w == w && (!h || S.runs[i].pro_height == h)) return &S.runs[i];+ return NULL;+}+static bool centred_at(const ht_run_t *r, int cx) { return r && r->x + r->w / 2 >= cx - 2 && r->x + r->w / 2 <= cx + 2; }static bool centred_run(const ht_run_t *r) { return r && r->x + r->w / 2 >= 360 - 2 && r->x + r->w / 2 <= 360 + 2; }int main(void) {@@ -1636,6 +1641,95 @@ int main(void) {CHECK(cap && cap->w <= 640 + 2 && strstr(cap->text, "\xe2\x80\xa6") && strlen(cap->text) < 48);cl->chat = POD_CHAT_NONE; cl->chat_name[0] = 0;}+ { // PM | Buddy (mockup pro-swarm-parity 2A, 2A', 3A-3D): the pill, header A, the Buddy screen, no Buddy yet, the dot+ pod_swarm_t *sw = &M.swarms[0];+ pod_lead_t *bl = &sw->leads[2];+ N.stack[1].view = POD_V_LEAD; snprintf(N.stack[1].lead_id, ID_MAX, "l2"); N.stack[1].lead = 2;+ asked_recap(&M, "sw1", "l2", "Deployed.", 1792560000u, false);+ bl->chat = POD_CHAT_NONE; bl->chat_name[0] = 0; bl->buddies = false; bl->has_buddy = false; bl->buddy_unread = false; sw->side = POD_SIDE_NONE; M.side_press = POD_SIDE_NONE;+ // pill_absent_without_buddies: phase 1's view (the header on two lines, at cy 42 and 84), no pill, no hit+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ static ht_run_t plain[HT_RUNS]; const int nplain = S.count; memcpy(plain, S.runs, sizeof(ht_run_t) * (size_t)nplain);+ CHECK(!text_run("PM") && !text_run("Buddy") && hits_of(POD_A_SIDE) == 0 && F.hit_count == 0);+ CHECK(text_run("openharness") && abs(text_run("openharness")->y + ph_sb_22.height * 15 / 32 - 42) <= 2 && abs(text_run("ops")->y + ph_sb_34.height * 15 / 32 - 84) <= 2);+ CHECK(!text_run("No Buddy here yet") && !rect_at(210, 16, 300, 44));+ // Buddies on, the PM side: the pill at (210, 16), the PM segment filled ink with dark text, Buddy muted+ bl->buddies = true; sw->side = POD_SIDE_PM;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ const int npm = S.count; // the run count of this state: constant whichever side is selected (a dot adds its two)+ const ht_run_t *trk = rect_at(210, 16, 300, 44);+ CHECK(trk && trk->radius == 22 && trk->fg == ht_rgb(0x34302C)); // pill_pm_selected+ const ht_run_t *pmf = rect_at(210, 16, 150, 44);+ CHECK(pmf && pmf->radius == 22 && pmf->fg == ht_rgb(PH_ROOM_INK) && !rect_at(360, 16, 150, 44));+ CHECK(text_run("PM") && text_run("PM")->fg == ht_rgb(PH_ROOM_BG) && centred_at(text_run("PM"), 285) && text_run("Buddy") && text_run("Buddy")->fg == ht_rgb(PH_ROOM_MUTED) && centred_at(text_run("Buddy"), 435));+ CHECK(abs(text_run("PM")->y + ph_sb_22.height * 15 / 32 - 38) <= 2);+ CHECK(hits_of(POD_A_SIDE) == 2 && nth_hit(POD_A_SIDE, 0)->x == 210 && nth_hit(POD_A_SIDE, 0)->w == 150 && nth_hit(POD_A_SIDE, 0)->arg == POD_SIDE_PM && !strcmp(nth_hit(POD_A_SIDE, 0)->id, "sw1") &&+ nth_hit(POD_A_SIDE, 1)->x == 360 && nth_hit(POD_A_SIDE, 1)->w == 150 && nth_hit(POD_A_SIDE, 1)->arg == POD_SIDE_BUDDY && !strcmp(nth_hit(POD_A_SIDE, 1)->id, "sw1") && nth_hit(POD_A_SIDE, 0)->y + nth_hit(POD_A_SIDE, 0)->h <= 72);+ // header_a_one_line: the Swarm name (ph_sb_26, purple), " · " (muted) and the project (ph_sb_34) on one line at cy 94, centred together; nothing at cy 42+ const ht_run_t *hp = text_run("ops"), *hs = text_run("openharness"), *hd = text_run(" \xc2\xb7 ");+ CHECK(hp && abs(hp->y + ph_sb_34.height * 15 / 32 - 94) <= 2 && hp->fg == ht_rgb(PH_ROOM_INK));+ CHECK(hs && abs(hs->y + ph_sb_26.height * 15 / 32 - 94) <= 2 && hs->fg == ht_rgb(0xB79CFF) && hd && hd->fg == ht_rgb(PH_ROOM_MUTED));+ CHECK(hs->x + hs->w <= hd->x + 2 && hd->x + hd->w <= hp->x + 2 && abs((hs->x + hp->x + hp->w) / 2 - 360) <= 3);+ for (int i = 0; i < S.count; i++) if (S.runs[i].pro_kind == K_TEXT) { const int c = S.runs[i].y + ph_sb_22.height * 15 / 32; CHECK(!(c >= 40 && c <= 44 && strcmp(S.runs[i].text, "PM") && strcmp(S.runs[i].text, "Buddy"))); }+ CHECK(!text_run("PM")->text[2] && S.count == npm);+ // the Buddy side selected: the segment moves and turns lilac+ sw->side = POD_SIDE_BUDDY; bl->has_buddy = true;+ snprintf(bl->buddy.name, sizeof bl->buddy.name, "Mira"); snprintf(bl->buddy.engine, sizeof bl->buddy.engine, "claude"); bl->buddy.cells = 0x1234; bl->buddy.color = 0xC49BFF; bl->buddy.live = true;+ bl->chat = POD_CHAT_BUDDY; snprintf(bl->chat_name, sizeof bl->chat_name, "Mira");+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ const ht_run_t *bf = rect_at(360, 16, 150, 44); // pill_buddy_selected+ CHECK(bf && bf->fg == ht_rgb(0xC49BFF) && !rect_at(210, 16, 150, 44) && text_run("Buddy")->fg == ht_rgb(PH_ROOM_BG) && text_run("PM")->fg == ht_rgb(PH_ROOM_MUTED));+ // buddy_screen_name_lilac: the name in place of "Lead" (lilac, ph_sb_34 at the status column), the avatar d 120 in the pet's 150 px box instead of the pet, no chat name line at 130+ const ht_run_t *bn = text_run("Mira");+ CHECK(bn && bn->fg == ht_rgb(0xC49BFF) && bn->x == 160 && !text_run("Lead") && !text_run("offline"));+ { int disc = 0; for (int i = 0; i < S.count; i++) disc += S.runs[i].pro_kind == K_RECT_AA && S.runs[i].w == 120 && S.runs[i].pro_height == 120 && S.runs[i].x == 31; CHECK(disc == 1); }+ { int pets = 0; for (int i = 0; i < S.count; i++) pets += S.runs[i].pro_kind == POD_CELL; CHECK(pets == 0); }+ CHECK(text_run("Deployed.") && abs(text_run("Deployed.")->y - 150) < 80); // the bubble stays (the recap)+ // buddy_offline_line: "offline" under the name, muted, ph_sb_22, only while the Buddy is not live+ bl->buddy.live = false;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ const ht_run_t *off = text_run("offline");+ CHECK(off && off->fg == ht_rgb(PH_ROOM_MUTED) && off->x == 160 && off->y > text_run("Mira")->y);+ bl->buddy.live = true;+ // chat_name_at_130_under_pill: a PM or group name moves to cy 130 (the bubble stays at 150), with the pill+ bl->chat = POD_CHAT_GROUP; snprintf(bl->chat_name, sizeof bl->chat_name, "review-cable-fit"); sw->side = POD_SIDE_PM;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ const ht_run_t *c130 = text_run("review-cable-fit");+ CHECK(c130 && c130->fg == ht_rgb(PH_ROOM_MUTED) && centred_run(c130) && abs(c130->y + ph_sb_22.height * 15 / 32 - 130) <= 2 && S.count == npm + 1);+ bl->chat = POD_CHAT_NONE; bl->chat_name[0] = 0;+ // header_a cut: a long Swarm name is shortened first, the project last; the whole line fits 640 px+ snprintf(sw->name, sizeof sw->name, "an-extremely-long-swarm-name-for-the-header-line");+ snprintf(bl->project, sizeof bl->project, "ops");+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ { const ht_run_t *a = text_prefix("an-extremely"), *pj = text_run("ops"), *dd = text_run(" \xc2\xb7 ");+ CHECK(a && strstr(a->text, "\xe2\x80\xa6") && pj && dd && a->x >= 360 - 320 - 2 && pj->x + pj->w <= 360 + 320 + 2); }+ snprintf(sw->name, sizeof sw->name, "openharness");+ // nobuddy_copy: the Buddy side with no Buddy: no bubble and no who row; a dashed circle with "+", then the two lines+ bl->has_buddy = false; bl->chat = POD_CHAT_NONE; sw->side = POD_SIDE_BUDDY;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ const ht_run_t *nb1 = text_run("No Buddy here yet"), *nb2 = text_run("Add one in the Harness app.");+ CHECK(nb1 && nb1->fg == ht_rgb(PH_ROOM_MUTED) && centred_run(nb1) && abs(nb1->y + ph_sb_34.height * 15 / 32 - 364) <= 2);+ CHECK(nb2 && nb2->fg == ht_rgb(PH_ROOM_MUTED) && centred_run(nb2) && abs(nb2->y + ph_rg_28.height * 15 / 32 - 412) <= 2 && text_run("+"));+ CHECK(!text_run("Deployed.") && !text_run("Lead") && !text_run("done") && !rect_at(60, 150, 600, 0) && rect_at(360, 16, 150, 44));+ { int bub = 0; for (int i = 0; i < S.count; i++) bub += S.runs[i].pro_kind == K_RECT_AA && S.runs[i].w == 600 && S.runs[i].fg == ht_rgb(PH_LETTER); CHECK(bub == 0); }+ { int arcs = 0; for (int i = 0; i < S.count; i++) arcs += S.runs[i].pro_kind == POD_ARC; CHECK(arcs >= 8); }+ // the same screen with pending side: the pressed segment wins over the Swarm's side+ sw->side = POD_SIDE_PM; M.side_press = POD_SIDE_BUDDY; snprintf(M.side_press_swarm, ID_MAX, "sw1");+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ CHECK(rect_at(360, 16, 150, 44) && !rect_at(210, 16, 150, 44) && text_run("No Buddy here yet"));+ M.side_press = POD_SIDE_NONE; M.side_press_swarm[0] = 0;+ // buddy_dot_drawn: Buddy spoke while the PM side shows: a 12 px lilac disc with a 3 px track-coloured ring at the Buddy segment's top right; not on the Buddy side+ bl->has_buddy = true; bl->buddy_unread = true; sw->side = POD_SIDE_PM;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ const ht_run_t *dot = rect_at(480, 18, 12, 12), *ring = rect_at(477, 15, 18, 18);+ CHECK(dot && dot->fg == ht_rgb(0xC49BFF) && ring && ring->fg == ht_rgb(0x34302C) && S.count == npm + 2);+ sw->side = POD_SIDE_BUDDY;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ CHECK(!rect_at(480, 18, 12, 12));+ bl->buddy_unread = false; bl->chat = POD_CHAT_NONE; bl->buddies = false; bl->has_buddy = false; sw->side = POD_SIDE_NONE;+ fresh(); ph_view_lead(&F, &N, &M, 1000);+ CHECK(S.count == nplain && !memcmp(plain, S.runs, sizeof(ht_run_t) * (size_t)nplain)); // Buddies off again: byte for byte phase 1's view+ }// The model does not hold the Lead (a dropped link): nothing is drawn, nothing breakspod_model_link(&M, false);fresh(); ph_view_lead(&F, &N, &M, 1000);@@ -1687,6 +1781,37 @@ int main(void) {ph_view_inbox(&F, &N, &M, 2000);CHECK(!text_run("harness") && !text_prefix("\xc2\xb7") && !text_prefix("Cable fit now counts") && hits_of(POD_A_OPEN_NOTIF) == 0);}++ { // The Buddy's avatar (ph_avatar.c): the desktop's 15-bit agent pattern, mirrored, on a disc.+ const int X = 100, Y = 200, D = 120, CELL = 13, OX = X + (D - 5 * CELL) / 2, OY = Y + (D - 5 * CELL) / 2;+ const uint32_t col = 0xB79CFF;+ uint16_t sets[4] = { 1, 1 << 8, 25513, 1 << 7 };+ for (int k = 0; k < 4; k++) {+ fresh();+ ph_buddy_avatar(&S, X, Y, D, sets[k], col, PH_GROUND);+ bool lit[5][5] = { { false } };+ int n = 0;+ for (int i = 0; i < S.count; i++) {+ const ht_run_t *r = &S.runs[i];+ if (r->pro_kind != K_RECT_AA || r->w != CELL) continue;+ CHECK(r->fg == ht_rgb(col) && r->pro_height == CELL);+ int c = (r->x - OX) / CELL, rw = (r->y - OY) / CELL;+ CHECK(c >= 0 && c < 5 && rw >= 0 && rw < 5 && r->x == OX + c * CELL && r->y == OY + rw * CELL);+ lit[rw][c] = true; n++;+ }+ if (k == 0) CHECK(n == 2 && lit[0][0] && lit[0][4]); // avatar_cells_mirror+ if (k == 3) CHECK(n == 2 && lit[2][1] && lit[2][3]); // avatar_bit7: row 2 index 1 mirrors to columns 1 and 3 (the desktop's half[row * 3 + column])+ if (k == 1) CHECK(n == 1 && lit[2][2] && abs(OX + 2 * CELL + CELL / 2 - (X + D / 2)) <= 1); // within a pixel of the disc centre // avatar_bit7_centre (bit 8: row 2, index 2, the middle column)+ if (k == 2) { // avatar_parity_with_desktop+ const char *g[5] = { "#...#", "#.#.#", ".###.", "#...#", ".###." };+ CHECK(n == 13); // the plan says 17; the grid it lists has 13 lit cells+ for (int rw = 0; rw < 5; rw++) for (int c = 0; c < 5; c++) CHECK(lit[rw][c] == (g[rw][c] == '#'));+ }+ }+ fresh();+ ph_buddy_avatar(&S, X, Y, D, 0x7FFF, col, PH_GROUND);+ CHECK(S.count <= 27); // avatar_run_count+ }printf("test_ph_views: %d checks ok\n", checks);return 0;}diff --git a/devices/harness-pro/firmware/test/test_pod_model.c b/devices/harness-pro/firmware/test/test_pod_model.cindex 1a21798c4..e0023cf21 100644--- a/devices/harness-pro/firmware/test/test_pod_model.c+++ b/devices/harness-pro/firmware/test/test_pod_model.c@@ -1266,6 +1266,27 @@ static void pod_model_test_lead_chat(void) {CHECK(M.swarms[0].leads[0].recap == POD_RECAP_LOADED && !strcmp(M.swarms[0].leads[0].text, "named"));pod_model_reset(&M);}+// buddy_unread is the device's own mark: a frame for the same Lead keeps it, a new Lead starts without it.+static void pod_model_test_buddy_unread(void) {+ pod_model_reset(&M);+ const char *l1[] = {"a"};+ pod_swarm_t s = card("S1", "T1", l1, 1);+ s.side = POD_SIDE_PM;+ s.leads[0].buddies = s.leads[0].has_buddy = true;+ s.leads[0].buddy.cells = 25513;+ ids_of("S1", NULL, NULL, NULL);+ pod_model_supertab(&M, &s, 100);+ CHECK(!M.swarms[0].leads[0].buddy_unread && M.swarms[0].side == POD_SIDE_PM && M.swarms[0].leads[0].buddy.cells == 25513);+ M.swarms[0].leads[0].buddy_unread = true;+ s.side = POD_SIDE_BUDDY;+ pod_model_supertab(&M, &s, 200);+ CHECK(M.swarms[0].leads[0].buddy_unread && M.swarms[0].side == POD_SIDE_BUDDY);+ const char *l2[] = {"b", "a"};+ pod_swarm_t t = card("S1", "T1", l2, 2);+ pod_model_supertab(&M, &t, 300);+ CHECK(!M.swarms[0].leads[0].buddy_unread && M.swarms[0].leads[1].buddy_unread); // "a" moved; its mark went with it; "b" is new+ pod_model_reset(&M);+}// A Swarm chat's notice is an unread entry keyed by its Lead: it shares the order and the cap with agent entries, and a read must match its chat.static void swarm_card_for_notices(void) {pod_model_reset(&M);@@ -1403,6 +1424,7 @@ int main(void) {pod_model_test_step_total_and_fresh();pod_model_test_swarm_cards();pod_model_test_lead_chat();+ pod_model_test_buddy_unread();pod_model_test_swarm_notice();printf("Pod model: PASS (%d checks)\n", checks);return 0;diff --git a/devices/harness-pro/firmware/test/test_pro_app.py b/devices/harness-pro/firmware/test/test_pro_app.pyindex 7d2438bcb..e7513b7ac 100644--- a/devices/harness-pro/firmware/test/test_pro_app.py+++ b/devices/harness-pro/firmware/test/test_pro_app.py@@ -111,12 +111,13 @@ static struct { // what the last contact (or call) made the app sendbool abort_was_pending;char open_id[ID_MAX];} R;-static struct { bool open, pending, waiting, hold_pending, refuse; int lost; char agent[ID_MAX]; } V;+static struct { bool open, pending, waiting, hold_pending, refuse, face; int lost; char agent[ID_MAX]; } V;static struct { int n, offset[64]; uint32_t request[64]; bool ok, supported; } LIB = {.ok = true, .supported = true};static struct { int n; ht_scroll_phase_t phase[64]; int dy[64], v[64]; } SC;bool pro_cable_send_open(const char *id) { CHECK(LOCK_DEPTH == 0); R.opens++; snprintf(R.open_id, sizeof R.open_id, "%s", id); return true; }static struct { int n; bool fail; char t[16][24], tab[16][ID_MAX], lead[16][ID_MAX]; } SUP; // the Swarm cards' select / open / recap.get frames+bool pro_cable_supertab_side(const char *tab, const char *side) { CHECK(LOCK_DEPTH == 0); (void)tab; (void)side; return true; }bool pro_cable_supertab_send(const char *t, const char *tab, const char *lead) {CHECK(LOCK_DEPTH == 0);if (SUP.fail) return false;@@ -137,7 +138,8 @@ bool pro_cable_library_supported(void) { return LIB.supported; }cable_link_stats_t cable_link_stats(void) { return (cable_link_stats_t){0}; }void pro_cable_counters(uint32_t *bad, uint32_t *unknown) { *bad = 0; *unknown = 0; }static bool GATE_IN_BEGIN; // the race: an offer's gate lands while a voice start is between its gate check and its begin-void pro_voice_begin(const char *agent) {+void pro_voice_begin(const char *agent, bool face) {+ V.face = face;CHECK(LOCK_DEPTH == 0);if (GATE_IN_BEGIN) (void)pro_app_begin_update_gate();R.begins++;@@ -377,6 +379,23 @@ static int first_text_y(const char *word) { // the y of the drawn run that stafor (int i = 0; i < S.count; i++) if (S.runs[i].text[0] && !strncmp(S.runs[i].text, word, strlen(word))) return S.runs[i].y;return -1;}+// A tap on a Lead view talks to its face chat, and says so (Swarm parity part 3 on part 1's rule): without `face` the daemon posts+// the words in the Lead conversation, so on the Buddy side the person's Buddy words would land in the shared chat.+static void lead_view_talk_says_face(void) {+ setup();+ swarm_feed(3);+ pod_swarm_t *sw = (pod_swarm_t *)pod_model_swarm(&U.model, "sw1");+ snprintf(sw->leads[1].local, ID_MAX, "a1");+ swarm_home_page();+ tap(POD_A_LEAD, 1);+ CHECK(top() == POD_V_LEAD);+ render();+ bool c;+ contact(true, 360, 600, &c);+ contact(false, 360, 600, &c);+ CHECK(R.begins == 1 && !strcmp(V.agent, "a1") && pod_ui_talking(&U));+ CHECK(V.face);+}static void lead_view_scrolls_via_app(void) {setup();swarm_feed(3);@@ -1722,6 +1741,14 @@ static void pro_app_test_voice_gate(void) {CHECK(!strcmp(pro_app_voice_block_reason("a1"), "Answer its question first."));pro_app_question_close("a1");CHECK(pro_app_voice_block_reason("a1") == NULL);+ // buddy_talk_not_blocked_by_question: a talk opened from a Lead view (a Swarm face) goes to its chat, so the terminal's question, pane type and offline machine block nothing+ pro_app_question("a1", "r1", "Which?", NULL, POD_ATTN_NONE);+ memset(&U.nav, 0, sizeof U.nav);+ U.nav.depth = 1; U.nav.stack[0].view = POD_V_TALK; snprintf(U.nav.stack[0].swarm, ID_MAX, "sw1");+ CHECK(pro_app_voice_block_reason("a1") == NULL && pro_app_voice_block_reason("a2") == NULL && pro_app_voice_block_reason("a4") == NULL);+ pod_nav_init(&U.nav);+ CHECK(!strcmp(pro_app_voice_block_reason("a1"), "Answer its question first."));+ pro_app_question_close("a1");// A Super Tab wait is not answered here: talking to the agent is how it is unblocked.pro_app_question("a1", "supertab:as1:needs_human", "Which?", "Launch v2", POD_ATTN_DECISION);CHECK(pro_app_voice_block_reason("a1") == NULL);@@ -2564,6 +2591,7 @@ static void console_tap_talks_on_the_touch_path(void) {CHECK(R.begins == 0 && !V.open && top() == POD_V_AGENT);contact(false, 360, 400, &c); // the lift talks, with no pro_app_tick and no render betweenCHECK(R.begins == 1 && V.open && !strcmp(V.agent, "a1") && pod_ui_talking(&U) && LOCK_DEPTH == 0);+ CHECK(!V.face); // an agent room shows no chat: its words go to the harness, never a Swarm chat (review of #2298)render(); // the Talk frame, whose full-screen hit is topmostcontact(true, 20, 20, &c); // a new tap anywhere (here over the bar) sendscontact(false, 20, 20, &c);@@ -2633,7 +2661,7 @@ int main(int argc, char **argv) {{"library_fills_other_tabs", library_fills_other_tabs}, {"sweep_schedule", sweep_schedule},{"notice_shows_three_seconds", notice_shows_three_seconds}, {"link_drop_keeps_the_stack", link_drop_keeps_the_stack}, {"orphan_recording_is_discarded", orphan_recording_is_discarded}, {"side_button_discards_hands_free", side_button_discards_hands_free},{"send_before_recorder_started", send_before_recorder_started}, {"cap_leaves_talking", cap_leaves_talking},- {"lead_view_via_app", lead_view_via_app}, {"lead_view_scrolls_via_app", lead_view_scrolls_via_app}, {"lead_close_owed_on_busy_link", lead_close_owed_on_busy_link}, {"lead_view_relink_and_focus", lead_view_relink_and_focus}, {"tap_resolves_by_id", tap_resolves_by_id}, {"utf8_cuts", utf8_cuts}, {"clock_wrap", clock_wrap}, {"small_cable_stack", small_cable_stack},+ {"lead_view_via_app", lead_view_via_app}, {"lead_view_scrolls_via_app", lead_view_scrolls_via_app}, {"lead_view_talk_says_face", lead_view_talk_says_face}, {"lead_close_owed_on_busy_link", lead_close_owed_on_busy_link}, {"lead_view_relink_and_focus", lead_view_relink_and_focus}, {"tap_resolves_by_id", tap_resolves_by_id}, {"utf8_cuts", utf8_cuts}, {"clock_wrap", clock_wrap}, {"small_cable_stack", small_cable_stack},{"activity_text_is_stable_through_the_real_cadence", activity_text_is_stable_through_the_real_cadence},{"follow_from_tabs", follow_from_tabs}, {"follow_from_another_agent", follow_from_another_agent}, {"follow_same_agent_is_a_no_op", follow_same_agent_is_a_no_op},{"follow_ignored_while_talking", follow_ignored_while_talking}, {"follow_waits_out_the_users_touch", follow_waits_out_the_users_touch},diff --git a/devices/harness-pro/firmware/test/test_pro_cable.c b/devices/harness-pro/firmware/test/test_pro_cable.cindex 4f0f8a872..386140bee 100644--- a/devices/harness-pro/firmware/test/test_pro_cable.c+++ b/devices/harness-pro/firmware/test/test_pro_cable.c@@ -35,7 +35,7 @@ static int checks;// ---- the recorder --------------------------------------------------------------------------------------enum { EV_STATS, EV_LINK, EV_AGENTS, EV_SWARMS, EV_LIBRARY, EV_CONTEXT, EV_TURN, EV_SUMMARY, EV_QUESTION, EV_QCLOSE, EV_FOCUS,- EV_VOICE, EV_MACHINES, EV_NREPLACE, EV_NSEEN, EV_STIDS, EV_SUPERTAB, EV_STRECAP, EV_STFOCUS, EV_STNOTICE, EV_STNOTICE_READ };+ EV_VOICE, EV_MACHINES, EV_NREPLACE, EV_NSEEN, EV_STIDS, EV_SUPERTAB, EV_STRECAP, EV_STFOCUS, EV_STNOTICE, EV_STNOTICE_READ, EV_FEATURES };typedef struct { int kind; char id[64]; char a[2400], b[2400], c[2400], d[128]; long n1, n2, n3, n4, n5; } ev_t;#define EV_MAX 64static ev_t evs[EV_MAX];@@ -56,6 +56,7 @@ static ev_t *add(int kind, const char *id)}static void put(char *dst, const char *s) { snprintf(dst, 2400, "%s", s ? s : "<null>"); }+void pro_app_features(uint32_t features) { ev_t *e = add(EV_FEATURES, NULL); e->n1 = (long)features; }void pro_app_link(bool up, const char *machine) { ev_t *e = add(EV_LINK, NULL); e->n1 = up; put(e->a, machine); }void pro_app_agents(const pro_agent_row_t *rows, int n){@@ -277,6 +278,27 @@ static void welcome(void)}// ---- cases ---------------------------------------------------------------------------------------------+static void pro_cable_test_welcome_swarm_remote_feature(void)+{+ reset();+ feed("{\"t\":\"welcome\",\"machine\":{\"id\":\"m1\",\"name\":\"Mac\"},\"features\":[\"swarm.remote\"]}");+ int seen = 0;+ for (int i = 0; i < nev; i++) if (evs[i].kind == EV_FEATURES) { seen++; CHECK((evs[i].n1 & CABLE_FEATURE_SWARM_REMOTE) && !(evs[i].n1 & CABLE_FEATURE_PLAYER_LIBRARY)); }+ CHECK(seen == 1);+ reset();+ feed("{\"t\":\"welcome\",\"machine\":{\"id\":\"m1\",\"name\":\"Mac\"},\"features\":[\"player.library\"]}");+ seen = 0;+ for (int i = 0; i < nev; i++) if (evs[i].kind == EV_FEATURES) { seen++; CHECK(!(evs[i].n1 & CABLE_FEATURE_SWARM_REMOTE) && (evs[i].n1 & CABLE_FEATURE_PLAYER_LIBRARY)); }+ CHECK(seen == 1);+}+static void pro_cable_test_voice_error_buddy(void)+{+ welcome();+ reset();+ CHECK(pro_cable_voice_begin("l2", true, NULL, 16000, "upb") && strstr(sent[nsent - 1], "\"agentId\":\"l2\"") && strstr(sent[nsent - 1], "\"face\":true"));+ feed("{\"t\":\"voice.error\",\"uploadId\":\"upb\",\"message\":\"Could not reach your Buddy. Try again.\"}");+ CHECK(nev == 1 && evs[0].kind == EV_VOICE && evs[0].n1 == PRO_VOICE_ERROR && !strcmp(evs[0].a, "Could not reach your Buddy. Try again."));+}static void pro_cable_test_turn_activity(void){welcome(); // frames only count inside a session@@ -548,7 +570,7 @@ static void pro_cable_test_no_session(void)CHECK(nev == 0 && nsent == 1 && strstr(sent[0], "pong")); // the link's own keepalive still answers// After a session ends the same holds: the welcome opens the gate, the silence closes it.welcome();- CHECK(pro_cable_connected() && nev == 1 && evs[0].kind == EV_LINK);+ CHECK(pro_cable_connected() && nev == 2 && evs[0].kind == EV_FEATURES && evs[1].kind == EV_LINK);reset();end_session();reset();@@ -563,12 +585,12 @@ static void test_session_machines_library_voice(void)// welcome: link up, then machines.list + agents.list are asked for; a repeat greeting does nothing more.reset();welcome();- CHECK(nev == 1 && evs[0].kind == EV_LINK && evs[0].n1 == 1 && !strcmp(evs[0].a, "Mac"));+ CHECK(nev == 2 && evs[0].kind == EV_FEATURES && evs[1].kind == EV_LINK && evs[1].n1 == 1 && !strcmp(evs[1].a, "Mac"));CHECK(nsent == 2 && strstr(sent[0], "machines.list") && strstr(sent[1], "agents.list"));CHECK(pro_cable_connected() && pro_cable_library_supported());reset();welcome();- CHECK(nev == 0 && nsent == 0);+ CHECK(nev == 1 && evs[0].kind == EV_FEATURES && nsent == 0); // the features are told again; nothing elsefeed("{\"t\":\"ping\"}");CHECK(nsent == 1 && strstr(sent[0], "pong"));reset();@@ -650,7 +672,7 @@ static void test_session_machines_library_voice(void)// voice: replies for another upload are dropped; a route that needs confirming is confirmedreset();- CHECK(pro_cable_voice_begin("a", NULL, 16000, "up1") && nsent == 1 && strstr(sent[0], "\"lang\":\"en\"") && strstr(sent[0], "\"uploadId\":\"up1\""));+ CHECK(pro_cable_voice_begin("a", false, NULL, 16000, "up1") && nsent == 1 && strstr(sent[0], "\"lang\":\"en\"") && strstr(sent[0], "\"uploadId\":\"up1\"") && !strstr(sent[0], "\"face\""));feed("{\"t\":\"voice.transcript\",\"uploadId\":\"up0\",\"agentId\":\"a\"}");feed("{\"t\":\"voice.error\",\"uploadId\":\"up0\",\"message\":\"no\"}");CHECK(nev == 0);@@ -1141,6 +1163,53 @@ static void test_swarm_chat(void)CHECK(nev == 1 && evs[0].d[0] == 0);}+// Each Lead's Buddy and the Swarm's side (swarmBuddy): a bad field never drops the Lead or the frame.+static void test_swarm_buddy(void)+{+ welcome();+ reset(); // supertab_reads_buddy_block+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"leads\":[{\"id\":\"L1\",\"buddies\":true,\"buddy\":{\"chatId\":\"b1\",\"name\":\"diego's Buddy\","+ "\"engine\":\"codex\",\"cells\":25513,\"color\":\"#d6a79a\",\"live\":true}},{\"id\":\"L2\",\"buddies\":\"yes\"},{\"id\":\"L3\",\"buddies\":true,"+ "\"buddy\":{\"cells\":3,\"color\":\"red\",\"live\":1}}]}");+ CHECK(nev == 1 && rec_card.lead_n == 3);+ const pod_lead_t *l = &rec_card.leads[0];+ CHECK(l->buddies && l->has_buddy && !l->buddy_unread && !strcmp(l->buddy.chat_id, "b1") && !strcmp(l->buddy.name, "diego's Buddy") &&+ !strcmp(l->buddy.engine, "codex") && l->buddy.cells == 25513 && l->buddy.color == 0xD6A79A && l->buddy.live);+ CHECK(!rec_card.leads[1].buddies && !rec_card.leads[1].has_buddy); // buddies is true only for JSON true+ CHECK(rec_card.leads[2].has_buddy && rec_card.leads[2].buddy.cells == 3 && rec_card.leads[2].buddy.color == 0xC49BFF &&+ !rec_card.leads[2].buddy.live && rec_card.leads[2].buddy.chat_id[0] == 0);++ reset(); // buddy_bad_cells_dropped+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"leads\":[{\"id\":\"L1\",\"buddy\":{\"cells\":-1}},{\"id\":\"L2\",\"buddy\":{\"cells\":40000}},"+ "{\"id\":\"L3\",\"buddy\":{\"cells\":\"x\"}},{\"id\":\"L4\",\"buddy\":{}},{\"id\":\"L5\",\"buddy\":7},{\"id\":\"L6\",\"buddy\":{\"cells\":32767}}]}");+ CHECK(nev == 1 && rec_card.lead_n == 6);+ for (int i = 0; i < 5; i++) CHECK(!rec_card.leads[i].has_buddy);+ CHECK(rec_card.leads[5].has_buddy && rec_card.leads[5].buddy.cells == 32767);++ reset(); // buddy_name_cut_on_codepoint: 60 bytes of "é" cut to 48 whole letters+ char *name = repeat("\xc3\xa9", 30);+ feedf("{\"t\":\"supertab\",\"id\":\"S1\",\"leads\":[{\"id\":\"L1\",\"buddy\":{\"cells\":1,\"name\":\"%s\"}}]}", name);+ free(name);+ CHECK(nev == 1 && rec_card.leads[0].has_buddy && strlen(rec_card.leads[0].buddy.name) == 48 && utf8_ok(rec_card.leads[0].buddy.name));++ reset(); // supertab_reads_side+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"side\":\"pm\",\"leads\":[]}");+ CHECK(nev == 1 && rec_card.side == POD_SIDE_PM);+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"side\":\"buddy\",\"leads\":[]}");+ CHECK(rec_card.side == POD_SIDE_BUDDY);+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"side\":\"x\",\"leads\":[]}");+ CHECK(rec_card.side == POD_SIDE_NONE);+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"leads\":[]}");+ CHECK(rec_card.side == POD_SIDE_NONE);+ feed("{\"t\":\"supertab\",\"id\":\"S1\",\"side\":3,\"leads\":[]}");+ CHECK(rec_card.side == POD_SIDE_NONE);++ reset(); // side_frame_written: exactly these keys, only pm / buddy+ CHECK(pro_cable_supertab_side("S1", "buddy") && nsent == 1);+ CHECK(!strcmp(sent[0], "{\"t\":\"supertab.side\",\"tab\":\"S1\",\"side\":\"buddy\"}"));+ CHECK(!pro_cable_supertab_side("S1", "x") && !pro_cable_supertab_side("", "pm") && !pro_cable_supertab_side("S1", NULL) && nsent == 1);+}+// The Swarm cards (the hello's swarmCard:v1 is checked in test_pro_hello.py): supertabs {ids} + one supertab per Swarm +// supertab.recap / supertab.focus in, pro_app_supertab* out.static void test_swarm_cards(void)@@ -1426,6 +1495,8 @@ int main(void)pro_cable_start(); // the lock and the machine table; no tasks run on the hostpro_cable_test_no_session();pro_cable_test_turn_activity();+ pro_cable_test_welcome_swarm_remote_feature();+ pro_cable_test_voice_error_buddy();pro_cable_test_old_daemon();pro_cable_test_oversize();pro_cable_test_ignores_round();@@ -1446,6 +1517,7 @@ int main(void)seq_gaps();test_swarm_cards();test_swarm_chat();+ test_swarm_buddy();test_swarm_notice();self_replug();replug_spares_a_frame_in_flight();diff --git a/devices/harness-pro/firmware/test/test_pro_hello.py b/devices/harness-pro/firmware/test/test_pro_hello.pyindex 214e3e905..f9b36b553 100644--- a/devices/harness-pro/firmware/test/test_pro_hello.py+++ b/devices/harness-pro/firmware/test/test_pro_hello.py@@ -82,6 +82,7 @@ assert pairs == [("superTab", "wait-v1"),("swarmCard", "v1"),("swarmChat", "v1"),+ ("swarmBuddy", "v1"),("ota", "v1"),("mac", "aa"),("settings", "{"),diff --git a/devices/harness-pro/firmware/test/test_pro_voice_gate.py b/devices/harness-pro/firmware/test/test_pro_voice_gate.pyindex 16dee0ad7..6ccf6f4ca 100644--- a/devices/harness-pro/firmware/test/test_pro_voice_gate.py+++ b/devices/harness-pro/firmware/test/test_pro_voice_gate.py@@ -110,6 +110,7 @@ pro_touch_sample_t pro_touch_poll(int *x, int *y) { (void)x; (void)y; return PROstatic struct { int opens, cancels; char cancel_id[24]; } CAB;bool pro_cable_send_open(const char *id) { CHECK(LOCK_DEPTH == 0); (void)id; CAB.opens++; return true; }bool pro_cable_supertab_send(const char *t, const char *tab, const char *lead) { CHECK(LOCK_DEPTH == 0); (void)t; (void)tab; (void)lead; return true; }+bool pro_cable_supertab_side(const char *tab, const char *side) { CHECK(LOCK_DEPTH == 0); (void)tab; (void)side; return true; }bool pro_cable_send_scroll(pro_scroll_phase_t p, int dy, int v) { CHECK(LOCK_DEPTH == 0); (void)p; (void)dy; (void)v; return true; }bool pro_cable_request_library(int offset, uint32_t request) { CHECK(LOCK_DEPTH == 0); (void)offset; (void)request; return true; }bool pro_cable_library_supported(void) { return false; }@@ -126,7 +127,8 @@ static struct {char agent[ID_MAX], lang[CFG_VLANG_MAX], upload[24];} REC;bool pro_rec_init(void) { return REC.init_ok; }-bool pro_rec_start(const char *agent, const char *lang, const char *upload) {+bool pro_rec_start(const char *agent, bool face, const char *lang, const char *upload) {+ (void)face;CHECK(LOCK_DEPTH == 0);if (REC.refuse || REC.active) return false;REC.starts++;@@ -467,7 +469,7 @@ void pro_voice_test_step(int step) {static void begin_is_atomic_to_the_tick(void) {situation();STEPS_SEEN = 0; HOOK_ON = true; REC.tick_inside = true;- pro_voice_begin("a1");+ pro_voice_begin("a1", false);HOOK_ON = false; REC.tick_inside = false;CHECK(STEPS_SEEN == 0x3e); // steps 1..5 all interleavedCHECK(pro_voice_open() && REC.active && REC.recording && !strcmp(REC.agent, "a1"));@@ -475,11 +477,11 @@ static void begin_is_atomic_to_the_tick(void) {// A start the recorder refuses, ticked the same way, closes cleanly and the next begin is not blocked.pro_voice_close(); sender_done();REC.aborts = REC.aborts_quiet = 0; REC.refuse = true; STEPS_SEEN = 0; HOOK_ON = true;- pro_voice_begin("a1");+ pro_voice_begin("a1", false);HOOK_ON = false;CHECK(!pro_voice_open() && !REC.active && REC.starts == 1);REC.refuse = false;- pro_voice_begin("a1");+ pro_voice_begin("a1", false);CHECK(pro_voice_open() && REC.active && REC.starts == 2);// A link drop that lands while the recorder is starting must not leave the microphone streaming.pro_voice_close(); sender_done();@@ -490,7 +492,7 @@ static void link_lost_mid_start_leaves_no_stream(void) {REC.tick_inside = false;// Drop the link from inside pro_rec_start (the cable_link task against the touch task's begin).pro_test_in_start = pro_voice_link_lost;- pro_voice_begin("a1");+ pro_voice_begin("a1", false);pro_test_in_start = NULL;CHECK(!pro_voice_open());CHECK(!REC.recording && REC.aborts >= 1); // the stream that began mid-drop was aborted afterwardsdiff --git a/docs/plans/2026-11-02-harness-shares-list-index-plan.md b/docs/plans/2026-11-02-harness-shares-list-index-plan.mdnew file mode 100644index 000000000..59ba24283--- /dev/null+++ b/docs/plans/2026-11-02-harness-shares-list-index-plan.md@@ -0,0 +1,68 @@+# Harness shares list index Implementation Plan++> **Way of working (project instructions, revision 23):** the Engineer implements this plan task by task, test first; one independent Review step on the pull request. No subagent-driven-development, no execution handoff.++**Goal:** The share list (`GET /api/harness-shares`) reads its rows through an index that also gives the `createdAt` order, so Mongo does no in-memory sort.++**Architecture:** Add `@@index([recipientEmail, autonomousEnv, revokedAt, createdAt, expiresAt])` to `HarnessShare`. The list filters the first two by equality, then `revokedAt`/`expiresAt`, and sorts by `createdAt` ascending with `take: 1000`. Equality fields first (`revokedAt: null` included, so the revoked-but-unexpired shares, about 1,084 of the busiest recipient's 1,116 in prod, are never fetched), then the sort field, lets Mongo walk one recipient's live shares in order and stop at 1000; `expiresAt` last drops an expired share from its key before the fetch. Lead's before numbers on the PR showed the sort is not the cost (32 rows); the fetches are. The existing `(recipientEmail, autonomousEnv, expiresAt)` index stays: nothing is dropped.++**Tech Stack:** Prisma (MongoDB), vitest with a loopback `MongoMemoryReplSet` (`integration/plans.test-support.ts`).++**Spec:** Task #2151 (Ken's prod DB profile, Atlas Performance Advisor item 5: `harness_shares {createdAt: 1}` for the recipientEmail share list, 7 calls, avg 237 ms).++## Global Constraints++- Creating or dropping a production index is a production write: it needs Ken's go before it runs.+- Before/after measurement on prod slow logs, same window length, through the read-only production login only; never print it.+- Full Super Tab integration suite before Ready (`npm run test:super-tabs`).+- Pull request body starts with: `Requested by [email protected] through Harness.`+- Optimizations ship on, with no on/off switch.++## Design++- Growth: one index entry per share row (five small fields). Rows leave with `superTabs/purge.ts` (`deleteMany` by `superTabId`) and when a share is removed; nothing new grows.+- Concurrency: building an index takes a brief exclusive collection lock; the collection is small (shares, not events). Inserts, deletes and a revoke (`revokedAt`) update one more index entry; a rename does not touch it.+- Read cost: the list reads only the recipient's shares, in order, and stops at 1000. Before: an index scan on `(recipientEmail, autonomousEnv, expiresAt)` that fetches every unexpired share of that recipient, revoked ones included, then sorts them.+- Scale 10x: reads stay bounded by one recipient's shares. The warning metric is the list's slow-log count and `docsExamined` per call.+- Compatibility: indexes are invisible to clients; old and new backends read the same rows.+- Migration + rollback: `prisma db push` builds the index; rollback is dropping it (the old index still serves the filter). Both are production writes needing Ken's go.+- Audience: unchanged; the filter is still the signed-in account's email and environment.+- Identity: unchanged.+- Failure: if the build fails, the list works as today through the old index.+- Platforms: backend only.++## Review Focus++- The list returns the same rows in the same `createdAt` order, including a revoked share and an expired share left out.+- Another recipient's shares, and the same email in another `autonomousEnv`, never appear.+- A recipient with more than 1000 shares still gets the oldest 1000 in order.+- A share whose `revokedAt` was never set (missing field) is still listed.+- The old `expiresAt` index is still declared, so no other reader of it loses its plan.++---++### Task 1: Index the share list by recipient, environment and creation time++**Files:**+- Create: `backend/integration/harnessSharesIndexPlan.test.ts`+- Modify: `backend/prisma/schema.prisma:881`+- Modify: `backend/vitest.super-tabs.config.ts` (add the test to `include`)++**Interfaces:**+- Consumes: `planDatabase`, `profiled`, `reads`, `plan` from `integration/plans.test-support.ts`; `harnessShareRoutes` from `src/routes/harnessShares.ts`.+- Produces: the index `HarnessShare_recipientEmail_autonomousEnv_revokedAt_createdAt_expiresAt_idx`.++- [ ] **Step 1: Write the failing test** — seed shares of several recipients (30 revoked but unexpired, one expired, one other environment, explicit `revokedAt: null` as the route writes it), call the list through the route, and expect the share-list read to plan as an `IXSCAN` on the new index and examine no more documents than the 5 it returns.+- [ ] **Step 2: Run it and watch it fail** — `cd backend && NODE_ENV=test npx vitest run --config vitest.super-tabs.config.ts integration/harnessSharesIndexPlan.test.ts`. Expected: FAIL, plan is the `expiresAt` index with a `SORT`.+- [ ] **Step 3: Commit the failing test.**+- [ ] **Step 4: Add `@@index([recipientEmail, autonomousEnv, createdAt])` after the existing index.**+- [ ] **Step 5: Run the test; expect PASS. Run `npm run test:sharing` and `npm run test:super-tabs`.**+- [ ] **Step 6: Commit the schema change.**++### Task 2: Measure on production and record++**Files:**+- Modify: this plan (results section)++- [ ] **Step 1: Before:** with the read-only login from its environment file, count the share-list slow ops over the profile's window length (1 h 48 min) and their average time. Nothing printed but counts.+- [ ] **Step 2: After:** only once Ken has said go, the release has built the index, and a same-length window has passed; same query. Record both in the pull request.diff --git a/docs/plans/2026-11-02-web-new-version-plan.md b/docs/plans/2026-11-02-web-new-version-plan.mdnew file mode 100644index 000000000..a21c166eb--- /dev/null+++ b/docs/plans/2026-11-02-web-new-version-plan.md@@ -0,0 +1,105 @@+# Web new-version notice Implementation Plan++> **For agentic workers:** Work task by task, test first (project instructions, revision 26: Engineer role, not subagent-driven-development). Steps use checkbox (`- [ ]`) syntax. There is no Execution Handoff: the Engineer goes on to implement.++**Goal:** An open Harness web page says so within minutes of a new web release ("A new version of Harness is ready." with Reload), Reload loads the new build, and the account menu shows the running version ("Harness X.Y.Z").++**Architecture:** The host already serves `release.json` (`no-store`, written by `scripts/build-web-release.sh`, read at start-up by `webReleaseVersion` for the running version). A new `WebUpdateWatcher` re-reads it every few minutes, once at start-up and when the tab comes back to the front, and says "new" when it names a version other than the one this page was built as (compiled in by `build-web-release.sh`, since a page an old cache keeps would otherwise take the host's version for its own). A quiet bar at the top of the page (`WebUpdateFrame`, inside the store frame, above the app) shows it; Reload clears any old service worker and its caches, then reloads. The account menu takes the running version as an optional line, given only by the web build. Desktop (native) draws and does nothing new.++**Tech Stack:** Flutter web (`desktop/`), `package:web`, `flutter_test`.++**Spec:** Task #2185 (Huy). Mockup posted in the project chat: a bar "A new version of Harness is ready. Reload", and "Harness 1.3.51" under Settings · Sign out in the account menu. No server or website change: the website's `release.json` and `index.html` are already `no-store` (`website/next.config.js`), and releases already start no service worker (`website/scripts/harness-web-assets.mjs`).++## Design++- growth: N/A because nothing is stored; the page keeps one watcher and one timer.+- concurrency: N/A because the page only reads; two tabs each read for themselves.+- read cost: one small file (`release.json`, `no-store`) per open page every 5 minutes and when the tab comes back to the front; nothing is read once the bar shows.+- scale: 10x the open pages is 10x a few hundred bytes every 5 minutes; the host's request rate for `/harness-web/release.json` is the metric that warns first.+- compatibility: an old page without this code shows nothing and is not affected; a new page on a host without `release.json` (`flutter run`) never shows the bar.+- migration + rollback: none; reverting the PR removes the bar, the timer and the menu line. A build's own version is compiled in (`--dart-define=HARNESS_BUILD_VERSION`), so a page an old cache keeps still knows it is out of date (review of #2622).+- audience: N/A because the file and the version are public.+- identity: N/A because no account is involved.+- failure: an unreadable `release.json` changes nothing (no bar, none cleared); Reload's cleanup steps may each fail and the page still reloads.+- platforms: browser only; Desktop draws and runs nothing new.++## Global Constraints++- The pull request body starts with: `Requested by [email protected] through Harness.`+- Web only; Desktop unchanged: the native app shows no bar and no version line, and runs no timer.+- A change people see follows the Harness design language (the quiet bar matches the store bar's surface and type).+- Before each web release a Tester checks the web build in Safari in the iPhone simulator on Tony's Mac (keyboard, top bar) and in a desktop browser.+- Copy exactly: "A new version of Harness is ready." / "Reload" / "Harness X.Y.Z".++## Review Focus++- A release.json that cannot be read (offline, 404, odd body) never shows the bar and never clears one already shown.+- The same version shows nothing; a different one (a newer release, or a rollback) shows the bar once, however many checks follow.+- A page that could not tell its own version at start-up never shows the bar (it would show for every release).+- The bar must not remount the app below it, and must not sit under a phone's top inset or the store bar.+- Reload with an old service worker or cache registered still loads the new build.+- Desktop's account menu is unchanged (no version line unless the web gives one).++---++### Task 1: The watcher++**Files:**+- Create: `desktop/lib/web/update/web_update_watcher.dart`+- Test: `desktop/test/web_update_watcher_test.dart`++**Interfaces:**+- Produces: `class WebUpdateWatcher extends ChangeNotifier { WebUpdateWatcher({required String? running, required Future<String?> Function() readLatest, Duration every = const Duration(minutes: 5)}); bool get updateReady; Future<void> check(); void start(); void dispose(); }`++- [ ] **Step 1: Write the failing tests** `a different version is ready, the same one is not`, `an unreadable manifest changes nothing, before or after the bar shows`, `a page that does not know its own version never says ready`, `it checks again every interval until disposed`, `many checks tell listeners once`.+- [ ] **Step 2: Run, expect FAIL** (`cd desktop && flutter test --no-pub test/web_update_watcher_test.dart`): file missing.+- [ ] **Step 3: Implement** `WebUpdateWatcher` with `Timer.periodic`; `updateReady` is latched true once a read names a version different from `running`.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 2: The bar++**Files:**+- Create: `desktop/lib/web/update/web_update_bar.dart` (`WebUpdateFrame`, `WebUpdateBar`)+- Modify: `desktop/lib/web/web_entry.dart` (`appFrame`)+- Test: `desktop/test/web_update_bar_test.dart`++**Interfaces:**+- Consumes: Task 1.+- Produces: `WebUpdateFrame({required WebUpdateWatcher watcher, required VoidCallback reload, required Widget child})`; keys `web-update-bar`, `web-update-reload`.++- [ ] **Step 1: Write the failing tests**: ready shows the bar with the exact words and Reload calls `reload` once; not ready shows nothing; the child's state survives the bar appearing; the bar is a quiet strip in the store bar's colors.+- [ ] **Step 2: Run, expect FAIL.**+- [ ] **Step 3: Implement** the frame (one Column shape whether or not the bar shows, `SafeArea(bottom: false)` on the bar, `MediaQuery.removePadding(removeTop: true)` for the child while it shows); wire it in `appFrame` inside `WebAppStoreFrame`.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 3: The account menu's version++**Files:**+- Modify: `desktop/lib/widgets/account_menu.dart`, `desktop/lib/screens/swarm_screen.dart` (`_showAccountMenu`)+- Test: `desktop/test/account_menu_version_test.dart`++**Interfaces:**+- Produces: `AccountMenu(version: String?)` and `showAccountMenu(version:)`; key `account-menu-version`, text `Harness $version` under the last row.++- [ ] **Step 1: Write the failing tests**: with a version the menu says "Harness 1.3.51"; with none (Desktop) there is no such line.+- [ ] **Step 2: Run, expect FAIL.**+- [ ] **Step 3: Implement**; `swarm_screen.dart` passes `declaredAppVersion` only when `kIsWeb`.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 4: Reload that really loads the new build, and the timer++**Files:**+- Modify: `desktop/lib/web/parts/page_reload_web.dart`, `desktop/lib/web/parts/page_reload.dart`, `desktop/lib/web/web_entry.dart`+- Test: `desktop/test/web/web_reload_test.dart` (browser)++**Interfaces:**+- Produces: `Future<void> reloadForNewVersion()`: unregisters every service worker and deletes every cache of the page, then reloads; native is a no-op. The watcher is started in `appFrame` and also checks when the tab turns visible.++- [ ] **Step 1: Write the failing browser test**: with a service worker registration and a cache present, `reloadForNewVersion` removes both before the reload it asks for (reload injected).+- [ ] **Step 2: Run, expect FAIL** (`flutter test --platform chrome test/web/web_reload_test.dart`).+- [ ] **Step 3: Implement** with `package:web`; each step in try/catch so a refusal still reloads.+- [ ] **Step 4: Run, expect PASS; then the whole `test/web` and `analyze`.**+- [ ] **Step 5: Commit** test, then code.diff --git a/docs/plans/2026-11-03-large-repo-clone-plan.md b/docs/plans/2026-11-03-large-repo-clone-plan.mdnew file mode 100644index 000000000..3e9b1750e--- /dev/null+++ b/docs/plans/2026-11-03-large-repo-clone-plan.md@@ -0,0 +1,151 @@+# Large repository clone Implementation Plan++> **For agentic workers:** this project's way of working (project instructions, Engineer role): the Engineer implements+> this plan task by task, test first, committing each failing test before its code. Steps use checkbox (`- [ ]`) syntax.++**Goal:** Agents start on large repositories (lampOS: 576 MB pack, ~4,400 branches) on personal and Team accounts: the+project clone is blob-less and single-branch, gives up only when it stops making progress, and the Team account's clone+no longer fails on a repository that uses Git LFS when git-lfs is not installed.++**Architecture:** `cloneRepository` (cli/src/lib/projectFolder.ts) runs `git clone --progress --filter=blob:none+--single-branch`, then widens `remote.origin.fetch` back to all branches so `git fetch origin X && git checkout X` works as+in a full clone. Its fixed 5-minute deadline becomes a no-progress window: every chunk git writes on stderr (forced with+`--progress`) restarts it. The Team account's clone env (`swarmGitPrepareEnv`, cli/src/lib/swarmGitHub.ts) sets the LFS+filter only when git-lfs is on its PATH. A Swarm start doing another person's work fetches its base branch (not only the+default branch) with the app token and prefetches that tip's file contents, so the offline worktree needs no lazy fetch.++**Tech Stack:** TypeScript (Node 22), git CLI, vitest.++**Spec:** task #2394 brief (Swarm conversation f71071d79e80fffb12f9be82), restated in Findings below.++## Findings (MACs-Mac-Studio, 2026-11-03)++- Team-account env, throwaway clone of lampOS here: full clone 48 s (Homebrew git) — so the Mac Studio failure is not+ the deadline. Blob-less single-branch: 6 s. Longest stderr silence: 2.2 s full, 4.4 s blob-less.+- **Root cause of "Could not clone the repository" here:** lampOS tracks CAD files with Git LFS; git-lfs is not installed+ on this Mac; `swarmGitPrepareEnv` always sets `filter.lfs.process=git-lfs filter-process`. With Apple's git+ (`/usr/bin/git` 2.54, what an account without Homebrew runs) the checkout then fails — `git-lfs: command not found`,+ `fatal: the remote end hung up unexpectedly`, `Clone succeeded, but checkout failed`, exit 128 → CLONE_FAILED's+ generic message. Homebrew git 2.56 only warns and exits 0. Blob-less alone still fails the same way; without the+ filter entries, Apple git clones in 6 s, exit 0. Without git-lfs the LFS files stay pointer files, as in any clone on+ a machine without git-lfs.+- lampOS is public, so lazy blob fetches work there without a login; a private repository on a Team account has no login+ for them, hence Task 4.++## Global Constraints++- Out: a shared per-machine copy reused across agents. Existing project folders keep working (no re-clone forced).+- PR body first line: "Requested by [email protected] through Harness."+- Swarm code stays out of cli/src/core. Never run a test that signs the Mac out of the real CLI.+- Stop only processes you started, by id. Temp files only in mktemp -d folders.+- Optimizations ship on, with no on/off switches.+- Error codes stay what the apps know (CLONE_TIMEOUT, CLONE_FAILED); only the timeout's words change.++## Review Focus++1. A clone that keeps printing progress for longer than the window is never cut off (Task 2 test: slow but steady).+2. A stalled clone's git and its children are stopped, not left running (Task 2 test checks the fake git's pid is gone).+3. Existing full clones are untouched: `holdsRepository` still starts in them; nothing rewrites their config (Task 1 test:+ an existing checkout keeps its refspec).+4. An offline Swarm start never lazily fetches with the machine owner's login (Task 4: `GIT_NO_LAZY_FETCH=1` on the+ offline worktree add, test with an origin that logs any contact).+5. A Swarm start on `refs/remotes/origin/X` in a single-branch clone finds X (Task 4 test).++---++### Task 1: Blob-less single-branch clone that can still fetch other branches++**Files:**+- Modify: `cli/src/lib/projectFolder.ts` (`cloneRepository`, exported for tests)+- Test: `cli/src/lib/projectFolder.spec.ts`++**Interfaces:**+- Produces: `export function cloneRepository(url: string, destination: string, gitEnv?: NodeJS.ProcessEnv,+ options?: { stallMs?: number; git?: string }): Promise<void>` — `git` is the command (default `'git'`), `stallMs`+ the no-progress window (Task 2).++- [ ] **Step 1: Write the failing test** `clones only the default branch without file contents, and fetches another+ branch on demand`: a local origin (`git init`, `uploadpack.allowFilter=true`, `uploadpack.allowAnySHA1InWant=true`,+ commits on `main` and `feature`), `cloneRepository('file://' + origin, dest)`; expect `remote.origin.promisor` =+ `true`, `remote.origin.partialclonefilter` = `blob:none`, no `refs/remotes/origin/feature` after the clone,+ `remote.origin.fetch` = `+refs/heads/*:refs/remotes/origin/*`; then `git fetch origin feature` and+ `git checkout feature` exit 0 and the feature file has its content; `git log` and `git blame` on a main file exit 0.+- [ ] **Step 2: Run it, expect FAIL** (`cloneRepository` not exported). `npx vitest run src/lib/projectFolder.spec.ts`+- [ ] **Step 3: Implement**: args `['clone', '--progress', '--filter=blob:none', '--single-branch', '--', url,+ destination]`; on exit 0, `git -C destination config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'` in the+ same env; a failure there rejects as CLONE_FAILED.+- [ ] **Step 4: Run, expect PASS**; the whole file passes.+- [ ] **Step 5: Commit** test, then code.++### Task 2: Give up only when the clone stops making progress++**Files:**+- Modify: `cli/src/lib/projectFolder.ts` (`cloneRepository` deadline; `CLONE_STALL_MS = 120_000`)+- Test: `cli/src/lib/projectFolder.spec.ts`++**Interfaces:**+- Consumes: Task 1's `cloneRepository(..., { stallMs, git })`.++- [ ] **Step 1: Write the failing tests** with a fake git (an executable sh script in a mktemp folder, passed as `git`):+ - `gives up on a clone that stops making progress`: script prints one progress line, writes its pid to a file, sleeps+ 30 s; `stallMs: 300`; rejects with code `CLONE_TIMEOUT` and message `Cloning stopped making progress. Check the+ connection and retry.` within 5 s; the pid no longer runs.+ - `never cuts off a slow clone that keeps making progress`: script prints a line every 100 ms for 1.5 s (5× the+ window), creates the destination, exits 0; `stallMs: 300`; resolves.+- [ ] **Step 2: Run, expect FAIL**: the stalled one hangs past 5 s (fixed 300 s deadline); old message.+- [ ] **Step 3: Implement**: the timer is (re)armed at spawn and on each stderr chunk (`timer.refresh()`); on expiry,+ SIGTERM then SIGKILL after 2 s, as now.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** tests, then code.++### Task 3: Team clone on an LFS repository without git-lfs++**Files:**+- Modify: `cli/src/lib/swarmGitHub.ts` (`swarmGitPrepareEnv`)+- Test: `cli/src/lib/swarmGitHub.spec.ts`++- [ ] **Step 1: Write the failing test** `sets the LFS filter only when git-lfs is on the clone's PATH`:+ `swarmGitPrepareEnv(token, { PATH: emptyDir })` → `GIT_CONFIG_PARAMETERS` has no `filter.lfs`; with an executable+ `git-lfs` in a mktemp dir on PATH → it has all three `filter.lfs.*` entries.+- [ ] **Step 2: Run, expect FAIL** (entries always present).+- [ ] **Step 3: Implement** `hasGitLfs(path: string | undefined): boolean` (any PATH entry with an executable+ `git-lfs`, `git-lfs.exe` on Windows; `accessSync(X_OK)`), used to include the three entries.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 4: Swarm start for another person's work in a single-branch, blob-less clone++**Files:**+- Modify: `cli/src/lib/gitProject.ts` (`fetchStartBase`, offline `worktreeAdd` env)+- Modify: `cli/src/superTabs/projectFolder.ts` (`prepareSwarmStart` passes `request.branchRef`)+- Test: `cli/src/lib/gitProject.spec.ts`, `cli/src/superTabs/projectFolder.spec.ts`++**Interfaces:**+- Produces: `export async function fetchStartBase(source: string, env: NodeJS.ProcessEnv, branchRef?: string):+ Promise<boolean>` — fetches `branchRef` when it names a remote branch (`refs/remotes/origin/X`), else the origin+ default branch, with exactly that ref's refspec; then, in a partial clone (`remote.origin.promisor`), fetches the+ tip tree's missing objects (`git rev-list --objects --missing=print <tip>^{tree}` → `?oid` lines →+ `git fetch --no-tags --no-write-fetch-head --filter=blob:none --stdin origin`) in the same env. `fetchDefaultBranch`+ stays as `fetchStartBase(source, env)`.+- `prepareSwarmStart`'s `deps.fetch` becomes `typeof fetchStartBase`, called with `request.branchRef` when it is a string.++- [ ] **Step 1: Write the failing tests**:+ - gitProject: `fetches a start's remote base branch and its file contents, so the offline worktree needs no fetch`:+ blob-less clone of a local origin; commit on origin `feature`; `fetchStartBase(clone, env, 'refs/remotes/origin/feature')`+ → true; move the origin away; `prepareGitProject(clone, { worktree: true, offline: true, ref:+ 'refs/remotes/origin/feature', ... })` succeeds and the new file has its content.+ - gitProject: `an offline worktree never fetches missing contents`: blob-less clone, new commit on origin main fetched+ without its blobs (`git fetch` with explicit refspec only); `prepareGitProject(..., offline: true)` rejects and the+ origin's upload-pack was never run (origin's `uploadpack.packObjectsHook` writes a marker file).+ - superTabs/projectFolder: `prepareSwarmStart` passes the request's `branchRef` to `fetch`.+- [ ] **Step 2: Run, expect FAIL** (`fetchStartBase` missing; offline lazy fetch reaches origin; branchRef not passed).+- [ ] **Step 3: Implement** as in Interfaces; the offline worktree add runs with `GIT_NO_LAZY_FETCH=1`.+- [ ] **Step 4: Run, expect PASS**; `gitProject.spec.ts`, `projectFolder.spec.ts` (both), `cloneTrust.spec.ts` pass.+- [ ] **Step 5: Commit** tests, then code.++### Task 5: Evidence++- [ ] Typecheck (`npm run typecheck` in cli) and the affected spec files; red/green evidence as a PR comment.+- [ ] Before/after start times on lampOS in the PR: throwaway clones above, plus a real Team-account start on lampOS+ once the build runs on a Team account (log, blame, checkout of another branch in its folder).+- [ ] PR notes the lampOS LFS case (no git-lfs: pointer files, warnings only on Homebrew git; Apple git failed).diff --git a/docs/plans/2026-11-03-machine-project-limit-plan.md b/docs/plans/2026-11-03-machine-project-limit-plan.mdnew file mode 100644index 000000000..5e1b6bd23--- /dev/null+++ b/docs/plans/2026-11-03-machine-project-limit-plan.md@@ -0,0 +1,129 @@+# A machine's owner chooses which projects may use it Implementation Plan++> Way of working: this project's instructions (Engineer role): implemented by the Engineer task by task, each failing test+> committed before its code; two independent reviews on the pull request (one a security review: it changes who may run+> work where). Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** A contributed machine's owner can limit it to some of the Swarm's projects (default: all, as today); routing+leaves it out for any other project's work and says why, and a start, an assignment or an agent joining there for another+project is refused.++**Architecture:** The machine's contribution gets an optional `projects` list, set by a new owner-only command+`machine.projects` (or the Lead passing on the owner's own chat message, as `machine.engineResume` does). One check,+`machineProjectRefusal`, reads the list (a Mac's Harness Team account reads its Mac's) and is called from `teamWorkCheck`,+which already guards assignment, agents joining a task, the route's recorded candidates, review capacity and restores, and+from `admitMachineStart` for every start with a project (Product Managers included; a Buddy is its owner's own and is not+limited). The CLI route reads the list from the Swarm state and leaves the machine out with the same sentence. Desktop shows+"Projects that may use it" in the owner's machine details.++**Tech Stack:** TypeScript (backend Fastify/Prisma, CLI), Vitest, Flutter (Desktop).++**Spec:** Task #2390 brief (Tony, 11-03) and the mockup River posted to Tony on 11-03 (default 17:30 VN: build as shown):++```+ MacBooks-MacBook-Pro-19 (yours) 4 of 8 slots free+ Projects that may use it: ( ) All projects (•) Only:+ [x] openharness [ ] lampos [ ] spaceship+ [ ] computer [ ] physical-router+```++## Global Constraints++- Default all: a machine whose owner never set the list serves every project, exactly as today.+- Only the machine's owner changes it, or the project's Lead passing on a chat message the owner wrote in the last day+ (`askedIn`, as `machine.engineResume`).+- Route reason, as the brief words it: `<machine> runs only <projects>.`+- Existing agents on the machine keep running; they take no new task for a project not on the list.+- PR body first line: "Requested by [email protected] through Harness."+- Swarm code stays out of `cli/src/core`. Desktop tests use a memory store and a fake sign-in.++## Design++- **Growth:** at most one list per contributed machine (≤ 32 machines, each list ≤ the Swarm's projects); it goes with the+ machine. A deleted project's id is dropped from every list by `project.delete`.+- **Concurrency:** one command on the Swarm's state, under the Swarm's existing write lock, as `machine.pause`.+- **Read cost:** nothing new is read: the list rides in the machine record every read already has.+- **Scale:** 10x projects is a longer list on a 32-machine cap; the check is a list lookup per candidate.+- **Compatibility:** older CLIs don't leave the machine out of their route; the backend still refuses the pick+ (`route.record` → "Route again") and every start or assignment. Older Desktops don't show the setting; the list stays.+- **Migration + rollback:** none: absent means all. Rolling back ignores the field (all projects again).+- **Audience:** the server enforces it on every start, assignment and join; the CLI and Desktop only display it. A reader+ sees only the ids of projects they may read; the route sentence names only public projects and counts the rest+ ("and 1 other project"), so a private project's name never reaches another project's readers.+- **Identity:** the owner is the machine's contributor (`pool.contributorId`), never the machine account's login.+- **Failure:** a refused start or assignment says why (`MACHINE_PROJECTS`, 403); a machine whose list names only deleted+ projects serves none and says so.+- **Platforms:** backend, CLI route, Desktop (macOS/Windows/Linux same widget).++## Review Focus++- A Mac's Harness Team account (a separate pool with `hostMachineId`) must follow its Mac's list, both ways.+- Saving the machine's settings again (`machine.contribute` re-sent by Desktop) must keep the list.+- A teammate (not the owner), a Lead without the owner's message, or a Lead quoting someone else's message cannot change it.+- A project Lead's own start (Product Manager) on a limited machine is refused for another project.+- A private project's name must not appear in another project's route reason.++---++### Task 1: The list and its command (backend)++**Files:**+- Modify: `backend/src/superTabs/machines.ts` (`ContributedMachine.projects?: string[]`, `machineProjectRefusal`)+- Modify: `backend/src/superTabs/commands.ts` (schema + `machine.projects` case; keep on `machine.contribute`; drop ids on+ `project.delete`; askedIn read check)+- Modify: `backend/src/superTabs/model.ts` (`visibleState`: only readable project ids)+- Test: `backend/src/superTabs/machineProjects.test.ts` (unit, on the commands fixture used by `teamRouting.test.ts`)++**Interfaces:**+- Produces: command `{ type: 'machine.projects', machineId, projectIds: string[] | null, askedIn? }` (`null`: all);+ `machineProjectRefusal(state, machineId, project): TeamWorkRefusal | null` with code `MACHINE_PROJECTS`.++- [ ] Failing tests: `the owner limits their machine to some projects, and all again`; `a teammate, a Lead without the+ owner's message, and a Lead quoting another person are refused`; `the Lead passing on the owner's message sets it`;+ `saving the machine again keeps the list`; `a deleted project leaves every list`; `a reader sees only project ids they+ may read`; `unknown or unreadable project ids are refused`.+- [ ] Run red: `cd backend && npm test -- src/superTabs/machineProjects.test.ts`. Commit.+- [ ] Implement; run green; commit.++### Task 2: Enforcement (backend)++**Files:**+- Modify: `backend/src/superTabs/machines.ts` (`teamWorkCheck` first asks `machineProjectRefusal`; `admitMachineStart`+ refuses a start with a project, Product Managers included, Buddies not)+- Test: `backend/src/superTabs/machineProjects.test.ts`; `backend/integration/superTabTeam.test.ts` (one end-to-end case)++- [ ] Failing tests: `a machine limited to openharness refuses a start for lampos, and takes openharness's`; `refuses a+ Product Manager start for another project`; `refuses assigning another project's task to an agent there, and an agent+ there joining it`; `route.record leaves it out with "runs only openharness" and refuses it as the pick`; `a Mac's Team+ account follows its Mac's list`; `a private project is counted, not named, in the reason`; `with no list, every project+ as before`; integration: `Tony's machine, set to openharness only, gets no agent for another project's task`.+- [ ] Run red (unit + `npm run test:super-tabs -- integration/superTabTeam.test.ts`). Commit.+- [ ] Implement; run green; commit.++### Task 3: The route leaves it out (CLI)++**Files:**+- Modify: `cli/src/superTabs/routeCommand.ts` (pool shaping: `projectRefused` from `state.machines[].projects`; new and+ member reasons)+- Test: `cli/src/superTabs/routeCommand.spec.ts`++- [ ] Failing test: `leaves a machine limited to other projects out, new agents and members alike, saying why`, and the+ same machine is offered for a project on its list.+- [ ] Run red: `cd cli && npx vitest run src/superTabs/routeCommand.spec.ts`. Commit. Implement; green; commit.++### Task 4: Manage > Machines (Desktop)++**Files:**+- Modify: `desktop/lib/super_tabs/machines.dart` (owner's machine details: "Projects that may use it" — All projects /+ Only: one checkbox per project; sends `machine.projects`; a teammate sees the line read-only)+- Test: `desktop/test/super_tab_machine_projects_test.dart` (widget test + golden screenshot)++- [ ] Failing widget test: the owner picks Only, ticks openharness, and the command carries `['<openharness id>']`; All sends+ `null`; a teammate sees no controls. Commit red.+- [ ] Implement as the mockup; green; screenshot into the PR; `python3 scripts/check-ui-style.py --only desktop/lib/super_tabs`.++### Task 5: Before Ready++- [ ] Backend unit (`npm test`), full Super Tab integration suite (`npm run test:super-tabs`), typecheck; CLI route specs and+ typecheck; Desktop widget tests touching machines.+- [ ] Red/green PR comment; Ready; two Reviewers by Routing (one security).diff --git a/docs/plans/2026-11-03-personal-tab-projects-plan.md b/docs/plans/2026-11-03-personal-tab-projects-plan.mdnew file mode 100644index 000000000..8b58402f5--- /dev/null+++ b/docs/plans/2026-11-03-personal-tab-projects-plan.md@@ -0,0 +1,62 @@+# Personal Swarm: tab projects and a project that shows its panes Implementation Plan++> **How this plan runs:** by this project's instructions (Engineer role): task by task, test first (the failing test+> committed and watched failing, then the code); the pull request's Review step is the one independent review.++**Goal:** In the person's own Personal Swarm, a pane with no repo joins a project per tab, named after the tab, and+a project whose chat is empty but which has panes says so in its empty view, with a button that opens them.++**Architecture:** `personalPanes` (desktop/lib/super_tabs/personal_projects.dart) gives a pane with no repo the key+`tab:<tab id>` and remembers the tab's name for its project; the key, not the name, finds the project, so a renamed tab+keeps it, and the desk's tab id is the same on each of the person's computers. The project is created with the request+id `personal-tab-<hash of tab id>` and the tab's name. The project still opens on its chat (Dee's agreed design; River,+2026-11-03: no redesign of a screen that works); only the empty chat changes: with panes, the shared `EmptyState` says+"N panes in this project" over the usual "Discuss the plan with …" line, with a Show panes button that does what the+header's terminals button does.++**Tech Stack:** Flutter (Desktop; the web shares the code), widget and unit tests with the launch fixture.++**Spec:** task #2376's brief (Huy, 2026-11-03).++## Root cause of the empty view++Huy's screenshot is the top-left of a wider window: # scratch selected, its chat empty. A Personal project opened on its+project chat, which is empty, and its panes were behind the header's terminals button (out of the shot). Reproduced+with his desk (tabs code and Harness Monitor, agents with no remote): # scratch holds the 3 agent panes+(`Group terminals (3)`), the Harness Monitor's web viewer is left out as a viewer, and the view opens on the empty chat.+His panes have no remote: a folder with no git remote reports none, and `normalizedRemote` reads every remote form the+daemon sends (existing tests).++## Global Constraints++- Out: team projects. Keep the screen's layout; Harness design language.+- Panes with a repo keep grouping by repo.+- Nothing of a pane is sent but its project's name (now a tab's name for a tab project).+- PR body first line: "Requested by [email protected] through Harness."++## Review Focus++1. A tab renamed keeps its project (key is the tab id), and its project keeps the name it has.+2. A pane moved to another tab moves to that tab's project; a tab closed leaves its project as it is.+3. Two tabs of one name are two projects of that name (each tab's panes in its own).+4. A project with no panes, or a chat with messages, looks as it does today.+5. # scratch is no longer made for new panes; an existing # scratch project stays (the person may delete it).++---++### Task 1: An empty project chat with panes says so++**Files:** `desktop/lib/super_tabs/view.dart` (the empty chat); test `desktop/test/super_tab_personal_projects_test.dart`.++- [ ] Failing widget test: Huy's desk; the code project's empty chat shows "2 panes in this project" and Show panes,+ which opens its 2 panes; the Personal project (no panes) still shows "Discuss the plan with Product Manager." alone.+- [ ] Implement in the empty-chat branch, from `_terminalCount`'s Personal part.++### Task 2: Panes with no repo group per tab++**Files:** `desktop/lib/super_tabs/personal_projects.dart`; test as above.++- [ ] Failing tests: no-repo panes in tabs code and Harness Monitor make two projects named code and Harness Monitor,+ each with its own panes; panes with a repo still group by repo; a renamed tab keeps its project; two tabs of one name+ are told apart.+- [ ] Implement: key `tab:<id>`, name from the tab, request id `personal-tab-<hash>`.diff --git a/docs/superpowers/plans/2026-10-30-harness-pro-swarm-parity.md b/docs/superpowers/plans/2026-10-30-harness-pro-swarm-parity.mdindex 7ac20550c..9b84186a5 100644--- a/docs/superpowers/plans/2026-10-30-harness-pro-swarm-parity.md+++ b/docs/superpowers/plans/2026-10-30-harness-pro-swarm-parity.md@@ -345,10 +345,10 @@ Mockup: `devices/harness-pro/mockup/pro-swarm-parity/index.html` in the main che- [ ] **Step 1: Write the failing tests**- `avatar_cells_mirror`: `cells` with only bit 0 lights columns 0 and 4 of row 0, so exactly 2 cell rects.- - `avatar_bit7_centre`: bit 7 lights only row 2 col 2.+ - `avatar_bit7_centre`: bit 8 lights only row 2 col 2 (bit 7 is row 2, cols 1 and 3).- `avatar_parity_with_desktop`: `cells = 25513` (the daemon spec's Buddy) lights exactly the cells of this grid,rows top to bottom, which is desktop `superTabAgentPattern`'s mirror of those bits:- `#...#`, `#.#.#`, `.###.`, `#...#`, `.###.` (17 cell rects).+ `#...#`, `#.#.#`, `.###.`, `#...#`, `.###.` (13 cell rects).- [ ] **Step 2: Run** `run.sh` → FAIL (undefined symbol).- [ ] **Step 3: Implement** with `pod_draw` / `pro_canvas` primitives only, staying under the 4096 B frame cap.- [ ] **Step 4: Run** `run.sh` → PASS.diff --git a/docs/swarms.md b/docs/swarms.mdindex 607348f2d..ad737674d 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -795,7 +795,8 @@ roster, machine rows and mentions. A person sets theirs from their own row inthe roster. They can pick one of eight pictures or upload a PNG, JPEG or WebP.Desktop and the web app crop the upload square and resize it to 256 pixelsbefore sending it. The server accepts only those three formats, judged by the-file's own bytes, and at most 1 MB. Each upload can be used once. Without a picture, a person shows their initial. An+file's own bytes, and at most 1 MB. Each upload can be used once. An upload not used within a day is removed, and so is+a chat file attached but never sent: attach it again to send it. Without a picture, a person shows their initial. Anagent shows a pattern made from its name, the same on every computer, with asmall Claude or Codex badge. Its contributor changes it from the agent'sdetails, and the project's coordinator can change it with `agent.avatar`.