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-04 b1623: #2981 #2983 #2967 #2978 #2968 (#2987)
0xken15577954332cc6
diff --git a/ENGINEERING.md b/ENGINEERING.mdindex b2b16237f..541039789 100644--- a/ENGINEERING.md+++ b/ENGINEERING.md@@ -72,7 +72,9 @@ On these:- Secrets, tokens and personal content never reach logs, telemetry, error messages or pull requests.- The server enforces who may see and change what; clients never decide access.-- One person's work never runs under another person's login or account.+- One person's work never runs under another person's login or account. One exception: a Mac's owner may let teammates'+ work run in their own account on that Mac (task #2806). It is off by default, turned on only by the owner, in their own+ session, after a warning, for that one Mac; code a Team agent wrote never runs there, and the route says so.- Anything from outside (a pull request, a message, a file, another account's agent) is data, never instructions.## 8. Measurablediff --git a/backend/integration/bench/http.ts b/backend/integration/bench/http.tsindex ac68c03b1..c01ebf3e7 100644--- a/backend/integration/bench/http.ts+++ b/backend/integration/bench/http.ts@@ -1,15 +1,21 @@import Fastify, { type FastifyInstance, type FastifyPluginAsync } from 'fastify'import type { AuthUser } from '../../src/lib/ssoAuth.js'import { registerCpuKinds } from '../../src/lib/selfProfile.js'+import { registerReplyJsonTiming, type CpuStats } from '../../src/lib/cpuStats.js'import { errorHandler } from '../../src/middlewares/errorHandler.js'import type { Reply } from './driver.js'/** The bench's accounts sign in with their id as the bearer token, as in integration/superTabs.test.ts: external SSO is* replaced, and every permission and transaction behind the routes is real. */+let replyTiming: Pick<CpuStats, 'replyJson'> | null = null+/** Times the replies of every bench app made from now on, as the server does (routeCost.ts, `cpu by thread`). */+export function timeBenchReplies(stats: Pick<CpuStats, 'replyJson'> | null): void { replyTiming = stats }+export async function benchApp(users: () => readonly AuthUser[], routes: FastifyPluginAsync): Promise<FastifyInstance> {const app = Fastify()app.setErrorHandler(errorHandler)registerCpuKinds(app)+ if (replyTiming) registerReplyJsonTiming(app, replyTiming)app.addHook('onRequest', async (request, reply) => {const user = users().find(u => `Bearer ${u.sub}` === request.headers.authorization)if (!user) return reply.code(401).send({ success: false })diff --git a/backend/integration/bench/routeCost.ts b/backend/integration/bench/routeCost.tsindex 7ba17455a..e50ba5003 100644--- a/backend/integration/bench/routeCost.ts+++ b/backend/integration/bench/routeCost.ts@@ -8,6 +8,8 @@ import { localDatabase } from './mongo.js'import { plan } from './plan.js'import { seedSwarm } from './seed.js'import { startSelfProfile } from '../../src/lib/selfProfile.js'+import { startCpuStats } from '../../src/lib/cpuStats.js'+import { timeBenchReplies } from './http.js'/*** What one call of each hot Swarm route costs the backend in CPU, alone, on the bench's seeded Swarm (#314: production@@ -17,12 +19,18 @@ import { startSelfProfile } from '../../src/lib/selfProfile.js'** NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= \* DATABASE_URL=mongodb://127.0.0.1:1/bench-never-used npx tsx integration/bench/routeCost.ts [calls per route]+ *+ * It prints the server's `cpu by thread` every 15 s (lib/cpuStats.ts; on Linux, the split by thread). CPU_STATS=off runs+ * without it, to compare the CPU per call it costs.*/async function main() {const calls = Number(process.argv[2] ?? 200)// CPU_SELF_PROFILE=1: the production self-profile on a short clock, to see its output under this load.const stopProfile = process.env.CPU_SELF_PROFILE === '1'? startSelfProfile({ everyMs: 45_000, profileMs: 20_000, reportMs: 15_000, log: (m, c) => process.stdout.write(`${m} ${JSON.stringify(c, null, 1)}\n`) }) : () => {}+ const cpuStats = process.env.CPU_STATS === 'off' ? null+ : startCpuStats({ everyMs: 15_000, log: (m, c) => process.stdout.write(`${m} ${JSON.stringify(c)}\n`) })+ timeBenchReplies(cpuStats)const config = { ...DEFAULT_CONFIG }const database = await localDatabase()const people = await seedAccounts(database.db, config.machines)@@ -77,6 +85,8 @@ async function main() {process.stdout.write(`| ${label} | ${calls} | ${failed} | ${(ms / calls).toFixed(2)} | ${((performance.now() - wall) / calls).toFixed(2)} | ${(bytes / calls / 1024).toFixed(1)} |\n`)}} finally {+ cpuStats?.flush()+ cpuStats?.stop()stopProfile()await close()await driver.close()diff --git a/backend/integration/ci-durations.json b/backend/integration/ci-durations.jsonindex f28b77b33..51deea5af 100644--- a/backend/integration/ci-durations.json+++ b/backend/integration/ci-durations.json@@ -15,6 +15,7 @@"integration/schemaRelease.test.ts": 15000,"integration/shareRaces.test.ts": 500,"integration/superTabActivity.test.ts": 1900,+ "integration/superTabMessageEdits.test.ts": 1500,"integration/superTabAttemptModels.test.ts": 700,"integration/superTabAutoJoin.test.ts": 4300,"integration/superTabBuddies.test.ts": 22500,diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex 34a83831a..29e5fe3b7 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -1,4 +1,5 @@import { randomUUID } from 'node:crypto'+import { SEED_SETTLE_MS } from '../src/superTabs/proposals.js'import { execFile } from 'node:child_process'import { promisify } from 'node:util'import { join } from 'node:path'@@ -225,6 +226,25 @@ describe('a Buddy through the store', () => {await expect(f.execute({ type: 'message.send', conversationId: 'lead', text: 'Hi PM', replyTo: null, recipientIds: [] }, peer, agentId)).rejects.toThrow('A Buddy posts only in its own chat')})+ // Task #2777: the Tasks view's Proposals read the proposals kept apart, by id, in place of the whole project chat.+ it('keeps its owner\'s proposal in the project\'s open proposals until the PM answers it in its thread', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ const ask = String((await f.execute({ type: 'message.send', conversationId: chat, text: 'Send it to the PM', replyTo: null, recipientIds: [] }, peer)).result.messageId)+ const sent = String((await f.execute({ type: 'buddy.propose', conversationId: chat, ownerMessageId: ask, goal: 'Offline sync', scope: 'Desktop only',+ priority: 'normal' }, peer, agentId)).result.messageId)+ // Written with the proposal itself, before anything reads it.+ expect(await db.superTabOpenProposal.findMany({ where: { tabId: f.tab }, select: { id: true, conversationId: true } })).toEqual([{ id: sent, conversationId: 'lead' }])+ const listed = async () => (await f.store.proposals(owner, f.tab, 'lead')).proposals.map(p => p.messageId)+ expect(await listed()).toEqual([sent])+ // Past the seed's half hour, the read takes the kept proposals alone.+ await db.superTabOpenProposal.update({ where: { id: `seeded:${f.tab}:lead` }, data: { createdAt: new Date(Date.now() - SEED_SETTLE_MS - 1000) } })+ expect(await listed()).toEqual([sent])+ await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Taking it', replyTo: sent, recipientIds: [] }, owner, f.lead)+ expect(await listed()).toEqual([])+ expect(await db.superTabOpenProposal.count({ where: { id: sent } })).toBe(0)+ })+it('reads its project\'s work as its person: which task owns it, its pull request, its state and what blocks it', async () => {const f = await swarm()// Opened before Buddies were on: the owner's private chat with the PM, which their Buddy may never read either.diff --git a/backend/integration/superTabDeletion.test.ts b/backend/integration/superTabDeletion.test.tsindex d6577e5b5..ca68c4632 100644--- a/backend/integration/superTabDeletion.test.ts+++ b/backend/integration/superTabDeletion.test.ts@@ -199,9 +199,12 @@ describe('the purge', () => {expect(await purgeDeletedSwarms(db, files, w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS - 1)).toMatchObject({ waiting: 0 })expect(await db.superTab.count({ where: { id: gone.tab } })).toBe(1)expect(await db.superTabMessage.count({ where: { tabId: gone.tab } })).toBeGreaterThan(0)+ // A project chat's open proposals (proposals.ts, task #2777) go with it.+ await db.superTabOpenProposal.create({ data: { id: `seeded:${gone.tab}:lead`, tabId: gone.tab, conversationId: 'lead', sequence: -1 } })expect(await purgeDeletedSwarms(db, files, w.clock.now + SWARM_DELETE_GRACE_MS + PURGE_MARGIN_MS)).toMatchObject({ waiting: 0 })expect(Object.entries(await counts(gone.tab)).filter(([, n]) => n > 0)).toEqual([])+ expect(await db.superTabOpenProposal.count({ where: { tabId: gone.tab } })).toBe(0)expect(await db.superTab.count({ where: { id: gone.tab } })).toBe(0)const keptKey = (await db.superTabAttachment.findFirstOrThrow({ where: { tabId: kept.tab }, select: { objectKey: true } })).objectKeyexpect([...w.files.objects.keys()]).toEqual([keptKey])diff --git a/backend/integration/superTabMessageEdits.test.ts b/backend/integration/superTabMessageEdits.test.tsnew file mode 100644index 000000000..9acc724d0--- /dev/null+++ b/backend/integration/superTabMessageEdits.test.ts@@ -0,0 +1,237 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { Readable } from 'node:stream'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+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 { EXPIRED_UPLOAD, MemoryAttachmentStore } from '../src/superTabs/attachments.js'+import type { Command } from '../src/superTabs/commands.js'+import { DELETED_TEXT } from '../src/superTabs/messageEdits.js'+import { poolRows } from './hostRows.test-support.js'+import { profiled } from './plans.test-support.js'++// Edit and delete your own message (task #2746): only the author, a person, on their own post. A fresh loopback replica set.+let replica: MongoMemoryReplSet+let db: PrismaClient+const owner: AuthUser = { sub: '330000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const peer: AuthUser = { sub: '330000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const other: AuthUser = { sub: '330000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_message_edits_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const user of [owner, peer, other]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ for (const [machineId, user] of [['owner-mac', owner], ['peer-mac', peer]] as const) {+ await db.machine.create({ data: { machineId, userId: user.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ }+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm with a public project `web` (its PM on the owner's Mac) and a private one `secret` (owner and peer); peer and other+ * are members, peer with a Mac whose host runs peer's Swarm Buddy. */+async function swarm() {+ const files = new MemoryAttachmentStore()+ const store = new SuperTabStore(db, () => Date.now(), { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })+ const tab = (await store.create(owner, randomUUID(), 'Edits', 'public')).id+ const execute = (command: Command, user = owner, asAgentId?: string, hostMachineId?: string) =>+ store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId, hostMachineId)+ for (const person of [peer, other]) {+ const invitation = await execute({ type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)+ }+ const web = (await execute({ type: 'project.create', name: 'Web', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }+ const secret = (await execute({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' })).result as { projectId: string; conversationId: string }+ await execute({ type: 'project.sharing', projectId: secret.projectId, visibility: 'private', memberIds: [owner.sub, peer.sub] })+ const pm = String((await execute({ type: 'agent.add', conversationId: web.conversationId, machineId: 'owner-mac', harnessId: randomUUID(), name: 'PM web',+ configuration: config, lead: true })).result.agentId)+ await execute({ type: 'machine.contribute', machineId: 'peer-mac', name: 'Peer Mac', cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 8 }, peer)+ const generation = (await poolRows(store, peer, 'peer-mac')).find(p => p.tabId === tab)!.machine.generation+ const running: string[] = []+ const report = () => store.observeMachine(peer, tab, 'peer-mac', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [...running], stoppedHarnessIds: [], capabilities: ['buddySessions', 'swarmBuddy'] })+ await report()+ const host = (command: Command) => execute(command, peer, undefined, 'peer-mac')+ /** peer's one Buddy, added from # buddy and started by their Mac's host. */+ const buddy = async () => {+ const added = await execute({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude' }, peer)+ const startId = String(added.result.startId)+ await host({ type: 'agent.startDispatch', startId })+ const harnessId = randomUUID()+ running.push(harnessId)+ const agentId = String((await host({ type: 'agent.started', startId, harnessId, configuration: config })).result.agentId)+ await host({ type: 'agent.startSettled', startId, warning: null })+ await report()+ return { chat: String(added.result.conversationId), agentId }+ }+ const send = async (conversationId: string, text: string, user = peer, extra: Partial<Extract<Command, { type: 'message.send' }>> = {}, asAgentId?: string) =>+ String((await execute({ type: 'message.send', conversationId, text, replyTo: null, recipientIds: [], ...extra }, user, asAgentId)).result.messageId)+ const edit = (conversationId: string, messageId: string, text: string, user = peer, asAgentId?: string) =>+ execute({ type: 'message.edit', conversationId, messageId, text }, user, asAgentId)+ const remove = (conversationId: string, messageId: string, user = peer, asAgentId?: string) =>+ execute({ type: 'message.delete', conversationId, messageId }, user, asAgentId)+ const page = async (conversationId: string, user = owner, cursor: Record<string, unknown> = {}) =>+ (await store.messages(user, tab, conversationId, cursor)) as unknown as { messages: Array<Record<string, any>>; threads: Array<Record<string, any>>; reactionSeq: number }+ const group = async (conversationId: string) => (await store.read(owner, tab)).state.conversations.find(c => c.id === conversationId)!+ return { store, files, tab, execute, web, secret, pm, buddy, send, edit, remove, page, group }+}++const refused = (code: string) => expect.objectContaining({ code })++describe('message.edit', () => {+ it('replaces the author\'s text everywhere it is read, marks it edited and keeps no earlier text', async () => {+ const f = await swarm()+ const id = await f.send(f.web.conversationId, 'The build is green.')+ const before = (await f.page(f.web.conversationId)).reactionSeq+ expect((await f.edit(f.web.conversationId, id, ' The build is green now. ')).result).toMatchObject({ changed: true })+ const read = await f.page(f.web.conversationId)+ expect(read.reactionSeq).toBeGreaterThan(before)+ const shown = read.messages.find(m => m.id === id)!+ expect(shown).toMatchObject({ text: 'The build is green now.', editedAt: expect.any(Date) })+ expect((await f.page(f.web.conversationId, other, { messageId: id })).messages.find(m => m.id === id)?.text).toBe('The build is green now.')+ // No history: the stored row holds the new text alone, and nothing anywhere holds the old.+ const row = await db.superTabMessage.findUniqueOrThrow({ where: { id } })+ expect(JSON.stringify(row)).not.toContain('The build is green.')+ expect(Object.keys(row).filter(k => /history|previous|original/i.test(k))).toEqual([])+ // A credential edited in is removed before it is stored, as in a send (credentials.ts).+ const token = ['ghp', 'Q7mZ2xK9pL4vB8nR1tY6wC3sD5fG0hJ2kM4n'].join('_')+ await f.edit(f.web.conversationId, id, `Token: ${token}`)+ expect(JSON.stringify(await db.superTabMessage.findUniqueOrThrow({ where: { id } }))).not.toContain(token)+ expect((await f.page(f.web.conversationId, other)).messages.find(m => m.id === id)?.text).toBe('Token: [credential removed]')+ await f.edit(f.web.conversationId, id, 'The build is green now.')+ // The same text again changes nothing.+ expect((await f.edit(f.web.conversationId, id, 'The build is green now.')).result).toMatchObject({ changed: false })+ })++ it('only the author: never another person, the owner, the owner\'s PM or the author\'s own Buddy', async () => {+ const f = await swarm()+ const id = await f.send(f.web.conversationId, 'Mine.')+ await expect(f.edit(f.web.conversationId, id, 'Owner rewrites it', owner)).rejects.toThrow(refused('FORBIDDEN'))+ await expect(f.edit(f.web.conversationId, id, 'Other rewrites it', other)).rejects.toThrow(refused('FORBIDDEN'))+ await expect(f.remove(f.web.conversationId, id, other)).rejects.toThrow(refused('FORBIDDEN'))+ await expect(f.edit(f.web.conversationId, id, 'PM rewrites it', owner, f.pm)).rejects.toThrow(expect.objectContaining({ status: 403 }))+ await expect(f.remove(f.web.conversationId, id, owner, f.pm)).rejects.toThrow(expect.objectContaining({ status: 403 }))+ // An agent's own post is not editable either.+ const pmLine = await f.send(f.web.conversationId, 'PM line', owner, {}, f.pm)+ await expect(f.edit(f.web.conversationId, pmLine, 'PM edits', owner, f.pm)).rejects.toThrow(expect.objectContaining({ status: 403 }))+ await expect(f.edit(f.web.conversationId, pmLine, 'Owner edits the PM', owner)).rejects.toThrow(refused('FORBIDDEN'))+ // peer's Buddy, in peer's own chat, on peer's own message: refused.+ const buddy = await f.buddy()+ const own = await f.send(buddy.chat, 'Look into the CPU spike')+ await expect(f.edit(buddy.chat, own, 'Buddy rewrites it', peer, buddy.agentId)).rejects.toThrow(expect.objectContaining({ status: 403 }))+ await expect(f.remove(buddy.chat, own, peer, buddy.agentId)).rejects.toThrow(expect.objectContaining({ status: 403 }))+ expect((await f.page(f.web.conversationId)).messages.find(m => m.id === id)?.text).toBe('Mine.')+ expect((await f.page(buddy.chat, peer)).messages.find(m => m.id === own)?.text).toBe('Look into the CPU spike')+ // The author still can, in their Buddy chat too.+ await f.edit(buddy.chat, own, 'Look into the memory spike')+ expect((await f.page(buddy.chat, peer)).messages.find(m => m.id === own)?.text).toBe('Look into the memory spike')+ })++ it('reads a message the actor cannot see as unavailable: another chat\'s id, a private chat, an agent-only notice', async () => {+ const f = await swarm()+ const secretLine = await f.send(f.secret.conversationId, 'Secret plan')+ // Named under another conversation: not found there.+ await expect(f.edit(f.web.conversationId, secretLine, 'Moved')).rejects.toThrow(refused('NOT_FOUND'))+ // A person who cannot read the private chat learns nothing about the message.+ await expect(f.edit(f.secret.conversationId, secretLine, 'Peeked', other)).rejects.toThrow(expect.objectContaining({ status: 404 }))+ await expect(f.edit(f.web.conversationId, 'no-such-message', 'x')).rejects.toThrow(refused('NOT_FOUND'))+ })+})++describe('message.delete', () => {+ it('removes a message with no replies: its row, reactions, Activity, open deliveries and files', async () => {+ const f = await swarm()+ const root = await f.send(f.web.conversationId, 'Owner root', owner)+ const upload = await f.store.upload(peer, f.tab, f.web.conversationId, { name: 'plan.txt', mime: 'text/plain', body: Readable.from([Buffer.from('plan')]) })+ const fileId = String((upload as { attachment?: { id: string }; id?: string }).attachment?.id ?? (upload as { id?: string }).id)+ const reply = await f.send(f.web.conversationId, 'See the plan', peer, { replyTo: root, attachmentIds: [fileId], recipientIds: [f.pm] })+ await f.execute({ type: 'message.react', conversationId: f.web.conversationId, messageId: reply, emoji: 'thumbs_up', on: true }, owner)+ expect(await db.superTabDelivery.count({ where: { messageId: reply, status: { in: ['queued', 'claimed'] } } })).toBe(1)+ expect((await f.page(f.web.conversationId, owner, { thread: root })).threads.find(t => t.id === root)?.replies).toBe(1)+ expect((await f.remove(f.web.conversationId, reply)).result).toMatchObject({ changed: true, kept: false })+ expect(await db.superTabMessage.findUnique({ where: { id: reply } })).toBeNull()+ expect(await db.superTabReaction.count({ where: { messageId: reply } })).toBe(0)+ expect(await db.superTabActivity.count({ where: { messageId: reply } })).toBe(0)+ expect(await db.superTabDelivery.count({ where: { messageId: reply, status: { in: ['queued', 'claimed', 'gathered'] } } })).toBe(0)+ // Its file goes to the hourly sweep, which removes the stored bytes (lib/attachmentSweep.ts).+ expect((await db.superTabAttachment.findUniqueOrThrow({ where: { id: fileId } })).usedBy).toBe(EXPIRED_UPLOAD)+ // The thread it was in no longer counts it.+ const thread = await f.page(f.web.conversationId, owner, { thread: root })+ expect(thread.messages.map(m => m.id)).toEqual([root])+ expect(thread.threads.find(t => t.id === root)?.replies ?? 0).toBe(0)+ // Gone means gone: no edit, no second delete, no reply to it.+ await expect(f.edit(f.web.conversationId, reply, 'Back')).rejects.toThrow(refused('NOT_FOUND'))+ await expect(f.remove(f.web.conversationId, reply)).rejects.toThrow(refused('NOT_FOUND'))+ })++ it('removes the tags a deleted message gave, so nobody keeps a waiting tag to a message they cannot open', async () => {+ const f = await swarm()+ const tagged = await f.send(f.web.conversationId, '@other can you look?', peer, { mentions: [other.sub] })+ const kept = await f.send(f.web.conversationId, '@other and this one', peer, { mentions: [other.sub] })+ await f.send(f.web.conversationId, 'Looking.', owner, { replyTo: kept })+ expect(await db.superTabMention.count({ where: { messageId: { in: [tagged, kept] } } })).toBe(2)+ await f.remove(f.web.conversationId, tagged)+ await f.remove(f.web.conversationId, kept)+ expect(await db.superTabMention.count({ where: { messageId: { in: [tagged, kept] } } })).toBe(0)+ })++ it('keeps a root with replies as "This message was deleted." and its replies keep their thread', async () => {+ const f = await swarm()+ const root = await f.send(f.web.conversationId, 'Should we ship? Secret detail here.')+ const answer = await f.send(f.web.conversationId, 'Yes, ship it.', owner, { replyTo: root })+ expect((await f.remove(f.web.conversationId, root)).result).toMatchObject({ changed: true, kept: true })+ const main = await f.page(f.web.conversationId, other)+ const tomb = main.messages.find(m => m.id === root)!+ expect(tomb).toMatchObject({ text: DELETED_TEXT, deletedAt: expect.any(Date) })+ expect(tomb.attachments ?? null).toBeNull()+ expect(JSON.stringify(await db.superTabMessage.findUniqueOrThrow({ where: { id: root } }))).not.toContain('Secret detail')+ const thread = await f.page(f.web.conversationId, other, { thread: root })+ expect(thread.messages.map(m => m.id)).toEqual([root, answer])+ expect(thread.threads.find(t => t.id === root)?.replies).toBe(1)+ // A deleted message is not edited back, deleted again or reacted to; its thread still takes replies.+ await expect(f.edit(f.web.conversationId, root, 'Undo')).rejects.toThrow(refused('MESSAGE_DELETED'))+ await expect(f.remove(f.web.conversationId, root)).rejects.toThrow(refused('MESSAGE_DELETED'))+ await f.send(f.web.conversationId, 'Shipped.', owner, { replyTo: root })+ expect((await f.page(f.web.conversationId, other, { thread: root })).messages).toHaveLength(3)+ })++ it('reads and writes every row it touches through an index, never by scanning a collection', async () => {+ const f = await swarm()+ const root = await f.send(f.web.conversationId, 'Owner root', owner)+ const reply = await f.send(f.web.conversationId, 'Reply', peer, { replyTo: root, recipientIds: [f.pm] })+ await f.execute({ type: 'message.react', conversationId: f.web.conversationId, messageId: reply, emoji: 'thumbs_up', on: true }, owner)+ const touched = ['SuperTabMessage', 'SuperTabReaction', 'SuperTabActivity', 'SuperTabDelivery', 'SuperTabAttachment', 'SuperTabThread', 'SuperTabMention']+ const entries = await profiled(db, () => f.remove(f.web.conversationId, reply))+ // The profiler saw the delete's writes (so the check below is not empty by accident).+ for (const c of ['SuperTabMessage', 'SuperTabDelivery', 'SuperTabActivity']) expect(entries.some(e => e.ns.endsWith(`.${c}`))).toBe(true)+ const scans = entries.filter(e => touched.some(c => e.ns.endsWith(`.${c}`)) && /COLLSCAN/.test(String(e.planSummary)))+ expect(scans.map(e => [e.ns, e.op, JSON.stringify(e.command?.filter ?? e.command?.q ?? e.command?.pipeline)])).toEqual([])+ })++ it('steps the chat\'s newest-message counters back, so a deleted newest message leaves nobody unread', async () => {+ const f = await swarm()+ await f.send(f.web.conversationId, 'Earlier', owner)+ const before = await f.group(f.web.conversationId)+ const newest = await f.send(f.web.conversationId, 'Oops, wrong chat')+ expect((await f.group(f.web.conversationId)).lastMainSequence).toBeGreaterThan(before.lastMainSequence!)+ await f.remove(f.web.conversationId, newest)+ const after = await f.group(f.web.conversationId)+ expect(after.lastMainSequence).toBe(before.lastMainSequence)+ expect(after.lastPersonSequence).toBe(before.lastPersonSequence)+ expect(after.lastMessageSequence).toBe(before.lastMessageSequence)+ })+})diff --git a/backend/integration/superTabProposals.test.ts b/backend/integration/superTabProposals.test.tsindex 52a4f2518..1d59b56fc 100644--- a/backend/integration/superTabProposals.test.ts+++ b/backend/integration/superTabProposals.test.ts@@ -4,15 +4,15 @@ import type { PrismaClient } from '@prisma/client'import { applyCommand, type Command } from '../src/superTabs/commands.js'import { createSuperTab, type Actor, type SuperTabState } from '../src/superTabs/model.js'import { listNamedIndexes } from '../src/superTabs/parts/indexed.js'-import { databaseProposalReads, openProposals } from '../src/superTabs/proposals.js'-import { planDatabase } from './plans.test-support.js'+import { databaseProposalReads, openProposals, SEED_SETTLE_MS } from '../src/superTabs/proposals.js'+import { plan, planDatabase, profiled, reads } from './plans.test-support.js'// The Tasks view's Proposals (#2569) read the project chat's proposal roots and their threads as the chat page does. A busy// project chat holds thousands of rows, nearly all task lines and talk: the roots' read must not walk them.let replica: MongoMemoryReplSetlet db: PrismaClientlet state: SuperTabState-const TAB = 'swarm', CHAT = 'lead', CHAT_ROWS = 3_000+const TAB = 'swarm', CHAT = 'lead', SHORT = 'short', CHAT_ROWS = 3_000const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }const T0 = Date.parse('2026-11-01T00:00:00.000Z')@@ -50,6 +50,10 @@ beforeAll(async () => {}// Another proposal last, so the newest rows are not all proposals.rows.push(...proposal('newest', 'Newest'))+ // A short chat with the same proposals and nothing else (task #2777: the read costs the same however long the chat).+ const short = rows.filter(r => /^(open|answered|tasked|newest)/.test(r.id) || r.id === 'old').map(r => ({ ...r, id: `short-${r.id}`, conversationId: SHORT,+ ...r.thread ? { thread: `short-${r.thread}` } : {}, ...r.replyTo ? { replyTo: `short-${r.replyTo}` } : {} }))+ rows.push(...short)await db.superTabMessage.createMany({ data: rows.map(({ thread, ...row }) => ({ ...row, ...thread ? { thread } : {} })) as never })}, 180_000)afterAll(async () => {@@ -66,4 +70,25 @@ describe('the open-proposal read', () => {{ messageId: 'newest', title: 'Newest', personId: 'peer', at: expect.any(Number) },])})++ // Task #2777 (Ken's prod scan 11-04): Desktop reads this every minute, and each read walked the whole project chat.+ it('once seeded, reads the kept proposals by their own index and their roots by id, the same for a chat of 3,000 rows as of 10', async () => {+ const chat = state.conversations.find(c => c.id === CHAT)!+ const answer = await openProposals(state, chat, databaseProposalReads(db, TAB, CHAT))+ await openProposals(state, chat, databaseProposalReads(db, TAB, SHORT))+ const later = Date.now() + SEED_SETTLE_MS + 1000+ expect((await openProposals(state, chat, databaseProposalReads(db, TAB, CHAT), later))).toEqual(answer)+ const shape = (entries: Awaited<ReturnType<typeof profiled>>) => entries.filter(e => /SuperTab/.test(e.ns))+ .map(e => ({ ns: e.ns.slice(e.ns.lastIndexOf('.') + 1), plan: e.planSummary, docsExamined: e.docsExamined, returned: e.nreturned }))+ const long = await profiled(db, () => openProposals(state, chat, databaseProposalReads(db, TAB, CHAT), later))+ const brief = await profiled(db, () => openProposals(state, chat, databaseProposalReads(db, TAB, SHORT), later))+ expect(shape(long).map(e => e.ns)).toEqual(shape(brief).map(e => e.ns))+ expect(shape(long).map(e => e.docsExamined)).toEqual(shape(brief).map(e => e.docsExamined))+ // No read of the chat by its sequence: the walk is gone.+ expect(reads(long, 'SuperTabMessage', ['sequence'])).toEqual([])+ const listed = plan(reads(long, 'SuperTabOpenProposal', ['conversationId']))+ expect(listed).toEqual([expect.objectContaining({ plan: 'IXSCAN { tabId: 1, conversationId: 1, sequence: 1 }' })])+ expect(listed[0]!.docsExamined).toBe(listed[0]!.returned)+ expect(Math.max(...shape(long).map(e => e.docsExamined ?? 0))).toBeLessThanOrEqual(10)+ })})diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 575017cd1..4be1a4457 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -1252,3 +1252,24 @@ describe('a machine its owner keeps for some projects', () => {expect((await store.read(owner, f.tab)).state.machines!.find(m => m.machineId === 'team-mac')!.projects).toBeUndefined()})})++// Task #2806 (Scholes, 11-04): a machine's owner lets teammates' work run in their own account there. A guard loosened by the+// owner alone: never by the Harness Team account that runs on the same Mac as them, nor by anyone else.+describe('teammates\' work in a machine owner\'s own account', () => {+ it('is chosen by its owner alone, never by its Team account session, kept across reads and said on the machine', async () => {+ const f = await fixture()+ const choose = (allowed: boolean, user: AuthUser) => run(f.tab, { type: 'machine.ownAccountWork', machineId: 'team-mac', allowed } as Command, user)+ await expect(choose(true, owner)).rejects.toMatchObject({ code: 'OWNER_REQUIRED' })+ await expect(choose(true, team)).rejects.toMatchObject({ code: 'TEAM_SESSION_LIMITED' })+ expect((await store.read(owner, f.tab)).state.machines!.find(m => m.machineId === 'team-mac')!.ownAccountChoice).toBeUndefined()+ await choose(true, person)+ const seen = (await store.read(owner, f.tab)).state.machines!.find(m => m.machineId === 'team-mac')!+ expect(seen.ownAccountChoice).toMatchObject({ allowed: true, by: person.sub })+ // Whoever routes a teammate's task there reads it.+ expect((seen as unknown as { teamWork: { ownAccount?: string } }).teamWork.ownAccount).toMatch(/runs teammates' work in .+'s own account\.$/)+ await choose(false, person)+ const off = (await store.read(owner, f.tab)).state.machines!.find(m => m.machineId === 'team-mac')!+ expect(off.ownAccountChoice).toMatchObject({ allowed: false, by: person.sub })+ expect((off as unknown as { teamWork: { ownAccount?: string } }).teamWork.ownAccount).toBeUndefined()+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 35fd81e44..5480c44b1 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1127,6 +1127,11 @@ model SuperTabMessage {/// The project a row of a person's one Buddy chat belongs to (superTabs/buddySessions.ts lostProjectRow): a project/// session's thread and a PM's private line. Hidden once its person no longer reads that project.buddyProject String?+ /// When its author last edited its text (superTabs/messageEdits.ts); no earlier text is kept.+ editedAt DateTime?+ /// When its author deleted it while replies hung under it: its text is then DELETED_TEXT and its files are gone. A deleted+ /// message with no replies is removed, row and all.+ deletedAt DateTime?createdAt DateTime @default(now())/// Pages read by (sequence, id): older rows of one command share a sequence.@@ -1286,6 +1291,23 @@ model SuperTabThreadMark {@@index([updatedAt])}+/// A project chat's Buddy proposal roots not yet seen answered (superTabs/proposals.ts), read by the Tasks view's Proposals in place+/// of a walk of the whole chat (task #2777). Written in the transaction that inserts each root (store.ts writeMessages), and by+/// a chat's first reads, which seed it from the chat's rows; a row id `seeded:<tabId>:<conversationId>`, sequence -1, marks a+/// chat seeded. Removed by the read once it finds a root answered or gone, and with its Swarm (purge.ts). Under 10 per project.+model SuperTabOpenProposal {+ /// The root message's id, or the chat's seed mark.+ id String @id @map("_id")+ tabId String+ conversationId String+ /// The root's sequence in its chat; -1 for the seed mark.+ sequence Int+ createdAt DateTime @default(now())++ /// A chat's open roots, newest first (proposals.ts databaseProposalReads listed).+ @@index([tabId, conversationId, sequence])+}+/// One thread with at least one reply, summed up as pageThreads' $facet gives it (pageReads.ts refreshThreads): rewritten in the/// transaction that inserts each reply, and read by root id instead of the $facet once its Swarm is backfilled/// (SuperTabThreadBackfill). No text; never returned as is. Kept with its messages.diff --git a/backend/src/lib/cpuStats.test.ts b/backend/src/lib/cpuStats.test.tsnew file mode 100644index 000000000..47bdba77c--- /dev/null+++ b/backend/src/lib/cpuStats.test.ts@@ -0,0 +1,142 @@+import { gzip } from 'node:zlib'+import { promisify } from 'node:util'+import { afterEach, describe, expect, it } from 'vitest'+import Fastify from 'fastify'+import { parseThreadStat, readThreads, registerReplyJsonTiming, startCpuStats, threadBucket, type ThreadCpu } from './cpuStats.js'++let stop = () => {}+afterEach(() => { stop(); stop = () => {} })++describe('thread CPU', () => {+ it('reads a thread\'s name and its user plus system CPU from its stat line, whatever the name holds', () => {+ // Fields after the name: state ppid pgrp session tty tpgid flags minflt cminflt majflt cmajflt utime stime …+ const line = '4242 (we(ird) name)) S 1 4242 4242 0 -1 4194560 120 0 0 0 1234 56 0 0 20 0 30 0 100 0 0'+ expect(parseThreadStat(line)).toEqual({ name: 'we(ird) name)', cpuMs: 12_900 })+ })++ it('names the bucket of every thread a pod runs (Node 22, Prisma 5.22 library engine), and nothing else', () => {+ const pid = 10+ expect(threadBucket('node', 10, pid)).toBe('main')+ // The main thread is the pid, whatever process.title made its name.+ expect(threadBucket('harness-api', 10, pid)).toBe('main')+ expect(threadBucket('tokio-runtime-w', 11, pid)).toBe('prismaEngine')+ expect(threadBucket('opentelemetry-e', 12, pid)).toBe('prismaEngine')+ expect(threadBucket('libuv-worker', 13, pid)).toBe('libuvPool')+ expect(threadBucket('node', 14, pid)).toBe('v8Workers')+ expect(threadBucket('DelayedTaskSche', 15, pid)).toBe('v8Workers')+ expect(threadBucket('mystery', 16, pid)).toBe('other')+ })++ it.skipIf(process.platform !== 'linux')('reads this process\'s own threads: the main thread with CPU, and the libuv pool after zlib', async () => {+ await promisify(gzip)(Buffer.alloc(1 << 20))+ const threads = readThreads()+ const main = threads.find(thread => thread.tid === process.pid)+ expect(main?.cpuMs).toBeGreaterThan(0)+ expect(threads.some(thread => thread.name === 'libuv-worker')).toBe(true)+ })++ it('fails loudly when the folder cannot be read', () => {+ expect(() => readThreads('/nonexistent-cpu-stats-root')).toThrow()+ })+})++describe('cpu by thread', () => {+ const pid = 10+ /** A fake process: each flush reads `threads` and the process CPU as they are then. */+ function fake(initial: ThreadCpu[], processMs: number) {+ const state = { threads: initial, processMs, loop: 0.5 }+ const logs: Array<{ message: string; context: Record<string, unknown> }> = []+ let gc: ((durationMs: number, major: boolean) => void) | undefined+ const stats = startCpuStats({+ everyMs: 3_600_000, pid,+ log: (message, context) => logs.push({ message, context }),+ threads: () => state.threads,+ cpuUsage: () => ({ user: state.processMs * 1000, system: 0 }),+ loopUtilization: () => state.loop,+ observeGc: onGc => { gc = onGc; return () => { gc = undefined } },+ })+ return { state, logs, stats, gc: (ms: number, major = false) => gc?.(ms, major) }+ }++ it('splits the window\'s process CPU by thread bucket, counting a new thread in full and a gone one as exited', () => {+ const { state, logs, stats } = fake([+ { tid: 10, name: 'node', cpuMs: 1000 }, { tid: 11, name: 'tokio-runtime-w', cpuMs: 500 },+ { tid: 12, name: 'libuv-worker', cpuMs: 10 }, { tid: 13, name: 'node', cpuMs: 200 }, { tid: 14, name: 'tokio-runtime-w', cpuMs: 90 },+ ], 2000)+ state.threads = [+ { tid: 10, name: 'node', cpuMs: 1400 }, { tid: 11, name: 'tokio-runtime-w', cpuMs: 800 },+ { tid: 12, name: 'libuv-worker', cpuMs: 30 }, { tid: 13, name: 'node', cpuMs: 250 },+ // New in the window: all its CPU is the window's.+ { tid: 15, name: 'mystery', cpuMs: 40 },+ // tid 14 exited: its last share is only in the process total.+ ]+ state.processMs = 2000 + 400 + 300 + 20 + 50 + 40 + 90+ stats.flush()+ expect(logs).toHaveLength(1)+ expect(logs[0]!.message).toBe('cpu by thread')+ expect(logs[0]!.context).toMatchObject({+ processCpuMs: 900, mainMs: 400, prismaEngineMs: 300, libuvPoolMs: 20, v8WorkersMs: 50, otherThreadsMs: 40, exitedMs: 90,+ namedPct: 86, otherNames: { mystery: 40 }, loopBusyPct: 50,+ })+ stop = stats.stop+ })++ it('adds the main thread\'s GC pauses and reply JSON, and starts each window from zero', () => {+ const { state, logs, stats, gc } = fake([{ tid: 10, name: 'node', cpuMs: 0 }], 0)+ gc(3); gc(7, true)+ stats.replyJson(2.5, 2048); stats.replyJson(0.5, 1024)+ state.threads = [{ tid: 10, name: 'node', cpuMs: 100 }]; state.processMs = 100+ stats.flush()+ expect(logs[0]!.context).toMatchObject({ gc: { pauseMs: 10, count: 2, majorMs: 7 }, replyJson: { ms: 3, count: 2, kb: 3 } })+ stats.flush()+ expect(logs[1]!.context).toMatchObject({ processCpuMs: 0, mainMs: 0, gc: { pauseMs: 0, count: 0, majorMs: 0 }, replyJson: { ms: 0, count: 0, kb: 0 } })+ stats.stop()+ gc(5)+ stats.flush()+ expect(logs[2]!.context).toMatchObject({ gc: { count: 0 } })+ })++ it('says every window when it cannot read the threads, and still logs the rest', () => {+ const logs: Array<Record<string, unknown>> = []+ const stats = startCpuStats({ everyMs: 3_600_000, log: (_m, context) => logs.push(context), observeGc: () => () => {},+ threads: () => { throw new Error('ENOENT /proc/self/task') } })+ stop = stats.stop+ stats.flush(); stats.flush()+ expect(logs).toHaveLength(2)+ for (const context of logs) {+ expect(context).toMatchObject({ threads: 'unavailable', reason: 'ENOENT /proc/self/task' })+ expect(typeof context.processCpuMs).toBe('number')+ }+ })+})++describe('reply JSON timing', () => {+ it('replies the same bytes as Fastify\'s own JSON, and counts each reply\'s time and size', async () => {+ const replies: Array<[number, number]> = []+ const app = Fastify()+ registerReplyJsonTiming(app, { replyJson: (ms, bytes) => replies.push([ms, bytes]) })+ const payload = { items: [{ id: 'a', text: 'é ✓' }], at: new Date(0), none: null }+ app.register(async child => { child.get('/nested', async () => payload) })+ app.get('/text', async (_request, reply) => reply.type('text/plain').send('plain'))+ const response = await app.inject({ method: 'GET', url: '/nested' })+ expect(response.body).toBe(JSON.stringify(payload))+ expect(response.headers['content-type']).toMatch(/^application\/json/)+ await app.inject({ method: 'GET', url: '/text' })+ expect(replies).toHaveLength(1)+ expect(replies[0]![0]).toBeGreaterThanOrEqual(0)+ expect(replies[0]![1]).toBe(JSON.stringify(payload).length)+ await app.close()+ })++ it('refuses at startup a route whose response schema the timed serializer would bypass', async () => {+ const app = Fastify()+ registerReplyJsonTiming(app, { replyJson: () => {} })+ const schema = { response: { 200: { type: 'object', properties: { ok: { type: 'boolean' } } } } }+ expect(() => app.get('/schema', { schema }, async () => ({ ok: true }))).toThrow(/response schema/)+ // In a plugin, the same refusal fails the server's start.+ const plugin = Fastify()+ registerReplyJsonTiming(plugin, { replyJson: () => {} })+ plugin.register(async child => { child.get('/schema', { schema }, async () => ({ ok: true })) })+ await expect(plugin.ready()).rejects.toThrow(/response schema/)+ })+})diff --git a/backend/src/lib/cpuStats.ts b/backend/src/lib/cpuStats.tsnew file mode 100644index 000000000..4e0dc6dcb--- /dev/null+++ b/backend/src/lib/cpuStats.ts@@ -0,0 +1,185 @@+import { readdirSync, readFileSync } from 'node:fs'+import { constants, performance, PerformanceObserver } from 'node:perf_hooks'+import type { FastifyInstance } from 'fastify'+import { logger } from '../utils/logger.js'++/**+ * Where this process's CPU goes, by thread (Watch Production gap 2, #2801). On 11-04 a pod-minute had 43.9 s of process CPU+ * and `cpu by kind` (lib/selfProfile.ts) named 15.3 s of it: that log sees the main thread only, and ~40% ran off it.+ * Linux names each thread, so one read of `/proc/self/task/<tid>/stat` per thread a minute splits it with nothing per+ * request. Measured on Node 22.23 with Prisma 5.22 (library engine, in-process), arm64 Ubuntu:+ *+ * - the main thread's tid is the pid;+ * - `tokio-runtime-w` (and its tracing exporter `opentelemetry-e`) are the Prisma query engine's: it runs each query,+ * encodes and decodes BSON and builds the JSON string the client then parses;+ * - `libuv-worker` is the libuv pool: zlib, fs, crypto, dns lookups;+ * - `node` threads other than the main one, and `DelayedTaskSche`, are V8's platform workers: concurrent GC and JIT.+ *+ * `cpu by thread`, every minute, always on: process CPU, each bucket's CPU, `exitedMs` (threads that ended inside the+ * window, known only by the process total) and `namedPct`, the four named buckets' share. On the main thread, two+ * counters say what part of it is GC pauses (a `gc` PerformanceObserver) and reply JSON (registerReplyJsonTiming); the+ * rest of it is split by route in `cpu by kind`. Off Linux the thread split says `unavailable` and the rest still logs.+ */++export type ThreadBucket = 'main' | 'prismaEngine' | 'libuvPool' | 'v8Workers' | 'other'+export type ThreadCpu = { tid: number; name: string; cpuMs: number }++/** USER_HZ: the unit of /proc's CPU times, 100 on every Linux architecture the pods run on. */+const TICKS_PER_SECOND = 100++/** A thread's name and its user + system CPU in ms, from its `/proc/<pid>/task/<tid>/stat` line. The name sits between the+ * first `(` and the last `)` and may hold either; utime and stime are the 14th and 15th fields. */+export function parseThreadStat(text: string): { name: string; cpuMs: number } {+ const open = text.indexOf('('), close = text.lastIndexOf(')')+ if (open < 0 || close < open) throw new Error('not a stat line')+ // Fields after the name start at the 3rd (state): utime is the 14th, stime the 15th.+ const fields = text.slice(close + 2).split(' ')+ const ticks = Number(fields[11]) + Number(fields[12])+ if (!Number.isFinite(ticks)) throw new Error('stat line without CPU times')+ return { name: text.slice(open + 1, close), cpuMs: ticks * 1000 / TICKS_PER_SECOND }+}++export function threadBucket(name: string, tid: number, pid: number): ThreadBucket {+ if (tid === pid) return 'main'+ if (name.startsWith('tokio-runtime') || name.startsWith('opentelemetry')) return 'prismaEngine'+ if (name === 'libuv-worker') return 'libuvPool'+ if (name === 'node' || name.startsWith('DelayedTaskSche') || name.startsWith('V8')) return 'v8Workers'+ return 'other'+}++/** Every thread of this process with its CPU so far. A thread that exits between the listing and its read is skipped; an+ * unreadable folder throws (not Linux, or /proc not mounted). */+export function readThreads(root = '/proc/self/task'): ThreadCpu[] {+ const threads: ThreadCpu[] = []+ for (const entry of readdirSync(root)) {+ let text: string+ try { text = readFileSync(`${root}/${entry}/stat`, 'utf8') } catch { continue }+ threads.push({ tid: Number(entry), ...parseThreadStat(text) })+ }+ return threads+}++export type CpuStats = {+ /** One reply's JSON: how long `JSON.stringify` took and the bytes it made. */+ replyJson(ms: number, bytes: number): void+ /** Logs the window now and starts the next one (the timer calls it every minute). */+ flush(): void+ stop(): void+}++export type CpuStatsOptions = {+ everyMs?: number+ log?: (message: string, context: Record<string, unknown>) => void+ pid?: number+ threads?: () => ThreadCpu[]+ cpuUsage?: () => NodeJS.CpuUsage+ /** The main thread's event-loop utilization since the last call, 0 to 1. */+ loopUtilization?: () => number+ /** Calls onGc for every main-thread GC pause; returns its stop. */+ observeGc?: (onGc: (durationMs: number, major: boolean) => void) => () => void+}++const MAX_NAMES = 10++function loopSinceLast(): () => number {+ let last = performance.eventLoopUtilization()+ return () => {+ const now = performance.eventLoopUtilization()+ const since = performance.eventLoopUtilization(now, last)+ last = now+ return since.utilization+ }+}++function gcObserver(onGc: (durationMs: number, major: boolean) => void): () => void {+ const observer = new PerformanceObserver(list => {+ for (const entry of list.getEntries()) {+ const kind = (entry as { detail?: { kind?: number } }).detail?.kind+ onGc(entry.duration, kind === constants.NODE_PERFORMANCE_GC_MAJOR)+ }+ })+ observer.observe({ entryTypes: ['gc'] })+ return () => observer.disconnect()+}++export function startCpuStats({ everyMs = 60_000, log = (message, context) => logger.info(message, context), pid = process.pid,+ threads = () => readThreads(), cpuUsage = () => process.cpuUsage(), loopUtilization = loopSinceLast(),+ observeGc = gcObserver }: CpuStatsOptions = {}): CpuStats {+ const toMs = (usage: NodeJS.CpuUsage) => (usage.user + usage.system) / 1000+ const read = (): { threads: ThreadCpu[] } | { error: string } => {+ try { return { threads: threads() } } catch (error) { return { error: error instanceof Error ? error.message : String(error) } }+ }+ const byTid = (snapshot: ReturnType<typeof read>) => new Map('threads' in snapshot ? snapshot.threads.map(t => [t.tid, t.cpuMs]) : [])+ let processMs = toMs(cpuUsage()), started = performance.now(), before = byTid(read())+ let gc = { pauseMs: 0, count: 0, majorMs: 0 }, json = { ms: 0, count: 0, bytes: 0 }+ let stopGc: (() => void) | undefined = observeGc((ms, major) => {+ if (!stopGc) return+ gc.pauseMs += ms; gc.count+++ if (major) gc.majorMs += ms+ })++ const flush = () => {+ const nowMs = toMs(cpuUsage()), processCpuMs = nowMs - processMs+ const context: Record<string, unknown> = { windowMs: Math.round(performance.now() - started), processCpuMs: Math.round(processCpuMs) }+ const current = read()+ if ('threads' in current) {+ const sums: Record<ThreadBucket, number> = { main: 0, prismaEngine: 0, libuvPool: 0, v8Workers: 0, other: 0 }+ const names = new Map<string, number>()+ let counted = 0+ for (const thread of current.threads) {+ // A thread new in the window has all its CPU in it.+ const delta = Math.max(0, thread.cpuMs - (before.get(thread.tid) ?? 0))+ const bucket = threadBucket(thread.name, thread.tid, pid)+ sums[bucket] += delta; counted += delta+ if (bucket === 'other' && delta > 0) names.set(thread.name, (names.get(thread.name) ?? 0) + delta)+ }+ const named = sums.main + sums.prismaEngine + sums.libuvPool + sums.v8Workers+ Object.assign(context, {+ mainMs: Math.round(sums.main), prismaEngineMs: Math.round(sums.prismaEngine), libuvPoolMs: Math.round(sums.libuvPool),+ v8WorkersMs: Math.round(sums.v8Workers), otherThreadsMs: Math.round(sums.other),+ // Threads that ended inside the window: in the process total, gone from /proc.+ exitedMs: Math.round(Math.max(0, processCpuMs - counted)),+ namedPct: processCpuMs > 0 ? Math.round(Math.min(named, processCpuMs) / processCpuMs * 100) : 0,+ otherNames: Object.fromEntries([...names].sort((a, b) => b[1] - a[1]).slice(0, MAX_NAMES).map(([name, ms]) => [name, Math.round(ms)])),+ })+ } else Object.assign(context, { threads: 'unavailable', reason: current.error })+ Object.assign(context, {+ gc: { pauseMs: Math.round(gc.pauseMs), count: gc.count, majorMs: Math.round(gc.majorMs) },+ replyJson: { ms: Math.round(json.ms), count: json.count, kb: Math.round(json.bytes / 1024) },+ loopBusyPct: Math.round(loopUtilization() * 100),+ })+ log('cpu by thread', context)+ processMs = nowMs; started = performance.now(); before = byTid(current)+ gc = { pauseMs: 0, count: 0, majorMs: 0 }; json = { ms: 0, count: 0, bytes: 0 }+ }++ const timer = setInterval(flush, everyMs)+ timer.unref()+ return {+ replyJson(ms, bytes) { json.ms += ms; json.count++; json.bytes += bytes },+ flush,+ stop() { clearInterval(timer); const stop = stopGc; stopGc = undefined; stop?.() },+ }+}++/**+ * Every object reply's JSON, timed: what `JSON.stringify` of big replies costs the main thread. Fastify's own serializer+ * for a route without a response schema is that same `JSON.stringify` (fastify/lib/reply.js serialize), so the bytes do+ * not change. A response schema would be bypassed by this serializer, so a route declaring one is refused at startup;+ * none has one. Replies sent as strings or buffers are not serialized and not counted. Size is in characters, not bytes,+ * to keep the count free.+ */+export function registerReplyJsonTiming(app: FastifyInstance, stats: Pick<CpuStats, 'replyJson'>): void {+ app.addHook('onRoute', route => {+ if (route.schema?.response) {+ throw new Error(`${String(route.method)} ${route.url}: a response schema would be bypassed by the timed reply serializer ` ++ '(lib/cpuStats.ts registerReplyJsonTiming); serialize in the handler instead')+ }+ })+ app.setReplySerializer(payload => {+ const start = performance.now()+ const text = JSON.stringify(payload)+ stats.replyJson(performance.now() - start, text.length)+ return text+ })+}diff --git a/backend/src/server.ts b/backend/src/server.tsindex a935161c7..54f9265b3 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -35,6 +35,7 @@ import { useSharedRateCounter } from './lib/rateLimit.js'import { createRouteRateLimit } from './middlewares/routeRateLimit.js'import { redisWindowCounter } from './lib/redisRateCounter.js'import { selfProfileFromEnv } from './lib/selfProfile.js'+import { registerReplyJsonTiming, startCpuStats } from './lib/cpuStats.js'import { startRelayUsageFlush } from './lib/productUsage.js'import { registerWorkContext, startQueryStats } from './lib/queryStats.js'import { startRetryStats } from './superTabs/retryStats.js'@@ -149,6 +150,10 @@ async function start(): Promise<void> {registerWorkContext(app)// Off by default: logs this process's CPU by kind of work every minute, and a 30 s profile every 15 min (#314).selfProfileFromEnv(app)+ // Always on, every minute: process CPU by thread (main, Prisma engine, libuv pool, V8 workers), GC pauses and reply JSON.+ // Before any route is added, so every route's object replies are timed (lib/cpuStats.ts).+ const cpuStats = startCpuStats()+ registerReplyJsonTiming(app, cpuStats)// Always on, every minute (DB roadmap Phase 1): queries by model.action, filter shape and route, and each route's p50/p95.const stopQueryStats = startQueryStats()// Every minute, how often Swarm transactions ran again and commands loaded twice (superTabs/retryStats.ts, DB 2.1).@@ -252,6 +257,7 @@ async function start(): Promise<void> {stopDeliveryCalls()stopCacheStats()stopMemoryStats()+ cpuStats.stop()stopRouteLatency()stopMachineReportLog()stopMessageReadStats()diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 3804ced2c..fb5171727 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,6 +1,6 @@import { applyPushOrigin, failPushUnknown, failTeamWritten, hasStep, mainAccountMembers, markTeamWritten, requireNameable, requireTeamWrittenAccount, requireTeamWrittenMachine, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'import type { PushOrigin } from '../github/pushOrigin.js'-import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machinesFull, MACHINES_FULL_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'+import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machinesFull, MACHINES_FULL_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'import { setName, writtenNameOf } from './personNames.js'@@ -36,6 +36,7 @@ import { fixedOriginal, LEDGER_WEEKS, PULL_REQUEST_URL, recordAsked, recordFix,import { othersWorkNotice } from './othersWork.js'import { WEEK_MS } from './leaderboard/week.js'import { react, reactionSchema, type ReactionTarget } from './reactions.js'+import { deleteMessage, editMessage, type MessageChangeTarget } from './messageEdits.js'import { githubRepository } from '../github/repository.js'import { shippedAt } from './ship.js'import { syncTaskLines } from './taskLine.js'@@ -160,6 +161,8 @@ export const commandSchema = z.discriminatedUnion('type', [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(),+ // Whether teammates' work may also run in the owner's own account on their machine (Scholes, 11-04): its owner's choice.+ z.object({ type: z.literal('machine.ownAccountWork'), machineId: id, allowed: z.boolean(), 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(),@@ -323,6 +326,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('message.react'), conversationId: id, messageId: id, emoji: reactionSchema, on: z.boolean(),// As message.send's (security review 1 of #2435).oneBuddy: z.literal(true).optional() }).strict(),+ // The author's own post only (messageEdits.ts); the store finds the row (store.ts messageChangeTarget).+ z.object({ type: z.literal('message.edit'), conversationId: id, messageId: id, text: z.string().trim().max(32_000) }).strict(),+ z.object({ type: z.literal('message.delete'), conversationId: id, messageId: id }).strict(),z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),// A choice, or `delegate`: the person asked leaves it to the PM, who takes its recommended option (decisions.ts answerDecision).z.object({ type: z.literal('decision.answer'), decisionId: id, choice: z.number().int().min(0).optional(), note: z.string().trim().min(1).max(2000).optional(),@@ -362,6 +368,8 @@ export const operationSchema = z.object({ operationId: id, command: commandSchem* chat row is redacted (terminal.ts). Not a role's skill text, which only its project's owner, Lead and hosts read. */const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'message.send': ['text'],+ // An edit is a new text in a row everyone reads: cleaned as a send is (security review 2 of #2967).+ 'message.edit': ['text'],'buddy.propose': ['title', 'goal', 'scope'],'member.status': ['status.text'],'agent.add': ['name', 'initialMessage'],@@ -495,6 +503,8 @@ export interface CommandContext {avatarUpload?: AvatarUpload/** The message `message.react` names, read by the store (reactions.ts). */reaction?: ReactionTarget+ /** The message `message.edit` or `message.delete` names, read by the store (messageEdits.ts). */+ messageChange?: MessageChangeTarget/** Route decisions this tab recorded in the last hour, counted by the store. *//** The decision a command names, read from SuperTabRouteDecision by the store. */routeDecision?: RouteDecision@@ -644,7 +654,7 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS/** Also checked before returning an idempotent receipt: a retry does not retain* access after the person has been removed from a private project. *//** What may name a person's one Buddy chat: posts, reactions, proposals, naming the Buddy and ending a session. */-const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'buddy.propose', 'buddy.rename', 'buddy.sessionEnd'])+const SWARM_BUDDY_CHAT_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'message.edit', 'message.delete', 'buddy.propose', 'buddy.rename', 'buddy.sessionEnd'])export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return@@ -674,7 +684,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.type === 'machine.projects') && command.askedIn) {+ || command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork') && command.askedIn) {readConversation(state, actor, command.askedIn.conversationId)}if ('startId' in command && command.type !== 'route.modelResult') {@@ -1861,6 +1871,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const othersToldWeek = state.machines.find(m => m.machineId === command.machineId)?.othersToldWeek// 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)?.projects+ // So is their choice of their own account for teammates' work (machine.ownAccountWork), Desktop's join re-save+ // included; not over a removal, so a Mac removed and added again starts Team-account-only.+ const ownAccountChoice = state.machines.find(m => m.machineId === command.machineId && !m.buddyOnly && !m.removal)?.ownAccountChoicestate.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@@ -1869,6 +1882,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,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 } : {}), ...(projects && !host ? { projects } : {}),+ ...(ownAccountChoice && !host ? { ownAccountChoice } : {}),...(othersToldWeek != null ? { othersToldWeek } : {}) })// 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)!@@ -1909,6 +1923,27 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,pool.projects = [...new Set(command.projectIds)].map(projectId => readProject(state, asOwner, projectId).id)break}+ case 'machine.ownAccountWork': {+ // Whether teammates' work may run in its owner's own account here, as its owner, instead of moving to its Harness Team+ // account (Scholes, 11-04): its owner's choice, or a Lead's passing on their chat message, as machine.projects. It+ // loosens a privacy guard, so it is set on the Mac's own entry only, and recorded with whose word and when.+ const pool = machineContribution(state, command.machineId) ?? fail('NOT_FOUND', 'This machine has not been contributed.', 404)+ if (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 where teammates' work runs on it.", 403)+ }+ // On is informed consent: the owner's own session, where the app warns them first. A Lead may pass on their word only to+ // turn it off, which tightens the guard (security review 2 of #2981).+ if (command.allowed && actor.kind !== 'person') {+ fail('OWNER_SESSION_REQUIRED', "Only the machine's owner can let teammates' work run in their own account, from Harness on their own computer.", 403)+ }+ if (pool.hostMachineId) fail('TEAM_ACCOUNT_ENTRY', 'A Harness Team account always runs teammates\' work. Choose on its Mac.', 400)+ if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')+ // A Lead's relay keeps the message it passed on, so an audit reads the words behind it (security review 1 of #2981).+ pool.ownAccountChoice = { allowed: command.allowed, by: pool.contributorId, at: new Date(context.now).toISOString(),+ ...(actor.kind === 'agent' && command.askedIn ? { askedIn: { conversationId: command.askedIn.conversationId, messageId: command.askedIn.messageId } } : {}) }+ 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 its@@ -2309,6 +2344,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,marking(startGroup, () => applyPushOrigin(state, startGroup, context.pushOrigin))const written = teamWrittenTask(state, startGroup)const moved = teamStartRequest(state, named, home, context.teamAccountsIdle, context.teamMachines, written)+ // Moved to the Mac's Team account: the starter is told why in one line (task #2806).+ if (moved.machineId !== named.machineId) {+ const mac = state.machines?.find(m => m.machineId === named.machineId)+ if (mac) result.moved = movedToTeamAccount(mac)+ }if (written) requireTeamWrittenMachine(state, startGroup, moved.machineId)// A branch GitHub cannot place stays out of the main account too, unmarked, as it may yet read clean.else if (context.pushOrigin === 'unknown' && !teamAccountPool(state.machines?.find(m => m.machineId === moved.machineId))) failPushUnknown()@@ -3017,6 +3057,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,result.changed = react(group, command.messageId, command.on, context.reaction)break}+ case 'message.edit':+ // `command` is the cleaned one (withoutCredentials): the store writes this text, never the one it was sent.+ result.changed = editMessage(open(state, command.conversationId), actor, command.messageId, command.text, context.messageChange)+ if (result.changed) effects.messageEdit = { messageId: command.messageId, text: command.text }+ break+ case 'message.delete':+ Object.assign(result, { changed: true }, deleteMessage(open(state, command.conversationId), actor, command.messageId, context.messageChange))+ breakcase 'member.avatar':setMemberAvatar(state, actor, command.avatar, context.avatarUpload)breakdiff --git a/backend/src/superTabs/leadStart.test.ts b/backend/src/superTabs/leadStart.test.tsindex 684e2787e..129052396 100644--- a/backend/src/superTabs/leadStart.test.ts+++ b/backend/src/superTabs/leadStart.test.ts@@ -111,6 +111,14 @@ describe('starting a project\'s Product Manager on a Swarm machine', () => {expect(none.state.starts ?? []).toEqual([])})+ // Task #2806: its owner let teammates' work run in their own account there (machine.ownAccountWork).+ it('on a teammate\'s Mac whose owner lets teammates\' work run in their own account, runs on the Mac itself', () => {+ const f = swarm()+ f.machine('mate-mac').teamAccountOnly = true+ f.run({ type: 'machine.ownAccountWork', machineId: 'mate-mac', allowed: true } as Command, mate)+ expect(f.lead('mate-mac').result).toMatchObject({ machineId: 'mate-mac' })+ })+it('on a teammate\'s Mac with no Team account, runs on the Mac itself, whatever the Swarm\'s switch says for workers', () => {process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1'const f = swarm()diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.tsindex 788f91819..7fc0e7b72 100644--- a/backend/src/superTabs/leadStart.ts+++ b/backend/src/superTabs/leadStart.ts@@ -5,7 +5,7 @@* names the machine: only they know which one stays on (Ken, 10-29). Desktop's own-machine flow (project.create, a local* start, agent.add) is unchanged. */import { admitMachineStart, contributedEngines, failTeamWork, machineContribution, projectFolder, projectsOnMachine, teamAccountPool, teamPoolOf,- slotCounter, teamWorkRefusal, type ContributedMachine } from './machines.js'+ slotCounter, teamWorkRefusal, ownAccountWork, type ContributedMachine } from './machines.js'import { actorKey, fail, person, SuperTabError, type AgentStart, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'import { projectsOf, type SwarmProject } from './projects.js'import { failureNotice, publicReason } from './startFailure.js'@@ -87,8 +87,10 @@ export function leadHost(state: SuperTabState, project: SwarmProject, machineId:candidates = [named]} else {const team = teamsWork ? teamPoolOf(state, named, teamMachines) : undefined+ // Its owner lets teammates' work run in their own account there (machines.ts ownAccountWork): the Mac itself, as its owner.+ if (ownAccountWork(named)) candidates = [named]// A Mac added as its person joined, not lent, takes teammates' work only in its Team account (machines.ts teamAccountOnly).- if (named.teamAccountOnly) {+ else if (named.teamAccountOnly) {const pool = team ?? namedconst why = refusal(pool)if (why) failTeamWork(why)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 949764b07..22b7b6cc2 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -39,6 +39,12 @@ export interface ContributedMachine {* its Harness Team account whose privacy check passed, whether or not the Swarm requires that everywhere* (teamWorkRefusal). Kept when the contribution is saved again; gone with the machine. */teamAccountOnly?: true+ /** Its owner's choice whether teammates' work may also run in their own account here (commands.ts machine.ownAccountWork,+ * Scholes 11-04): who chose (the owner, whose word it is) and when. `allowed` lets a teammate's start run on this entry,+ * as its owner, instead of moving to its Harness Team account (ownAccountWork); only the owner's own session turns it on.+ * `askedIn`: the owner's message a Lead passed on to turn it off. Kept when the contribution is saved again;+ * gone with the machine, so a Mac removed and added again starts Team-account-only. Never on a Team account's own entry. */+ ownAccountChoice?: { allowed: boolean; by: string; at: string; askedIn?: { conversationId: string; messageId: string } }/** One of its person's own machines that is not in the Swarm, recorded only so its host starts and watches their Buddies* there (Dee, 10-29: "I don't want to add my machine to the swarm"). It takes no other start, is no route or Product* Manager candidate, serves no local models, and no reader sees it (model.ts visibleState). It goes with its last Buddy@@ -323,6 +329,9 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =// Its last reading stays fresh for a minute, and in that minute it read as taking teammates' work and a Lead's route// named it (local Team account run, 2026-10-28).if (pool.hostMachineId && !teamRow) return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `The Harness Team account on ${name} was removed, ${ONLY_OWN}.` }+ // Its owner let teammates' work run in their own account here: their explicit choice wins over the Swarm-wide rule, for+ // this machine only (River, 11-04).+ if (ownAccountWork(pool)) return nullif (!teamRow && reading?.sessionKind !== 'team' && !required && !pool.teamAccountOnly) return nullif (otherWorkspace) return { code: 'MACHINE_IN_OTHER_WORKSPACE', reason: `The Harness Team account on ${name} also serves another ${WORKSPACE_LABEL}'s Swarms, ${ONLY_OWN} here.` }if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {@@ -436,7 +445,9 @@ export function teamPoolOf(state: SuperTabState, pool: ContributedMachine, live?*/export function machineTeamWork(state: SuperTabState, pool: ContributedMachine, now: number, teamMachines: readonly string[],otherWorkspaceMachines: readonly string[] = []): TeamWorkRefusal | null {- const team = !pool.hostMachineId ? teamPoolOf(state, pool, teamMachines) : undefined+ // Its owner lets teammates' work run in their own account: starts stay on the Mac, so the Mac itself is what routing reads+ // (security review 2 of #2981).+ const team = !pool.hostMachineId && !ownAccountWork(pool) ? teamPoolOf(state, pool, teamMachines) : undefinedconst subject = team ?? poolreturn teamWorkRefusal(subject, now, teamMachines.includes(subject.machineId), teamAccountRequired(), otherWorkspaceMachines.includes(subject.machineId))}@@ -461,14 +472,30 @@ export function productManagerOn(state: SuperTabState, machineId: string): strin}+/** Whether [pool]'s owner lets teammates' work run in their own account there (machine.ownAccountWork): a Mac's own entry+ * only, never its Team account's. */+export const ownAccountWork = (pool: Pick<ContributedMachine, 'ownAccountChoice' | 'hostMachineId' | 'buddyOnly' | 'contributorId'> | undefined): boolean =>+ !!pool && pool.ownAccountChoice?.allowed === true && pool.ownAccountChoice.by === pool.contributorId && !pool.hostMachineId && !pool.buddyOnly++/** What the route and an agent's row say of a machine whose owner lets teammates' work run in their own account there, so+ * whoever routes a teammate's task to it does so knowingly (River, 11-04). */+export const ownAccountNote = (pool: Pick<ContributedMachine, 'name'>, ownerName: string | undefined): string =>+ `${pool.name} runs teammates' work in ${ownerName ?? 'its owner'}'s own account.`++/** What a start moved to [pool]'s Team account says, so it is never moved silently (task #2806). */+export const movedToTeamAccount = (pool: Pick<ContributedMachine, 'name'>): string =>+ `${pool.name} runs teammates' work in its Harness Team account. Its owner can change that in Manage > Machines.`+/** Where a new agent for [project] runs when a start names [machineId]: the Mac's team account when the project is not- * its contributor's own and the Mac has one in this Swarm, else the machine named. */+ * its contributor's own and the Mac has one in this Swarm, else the machine named. Not when its owner lets teammates'+ * work run in their own account there (ownAccountWork), unless a Team agent wrote the code. */export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[], teamWritten = false): string {// With no GitHub App on this server a team account cannot fetch or push, so the work stays on the Mac, as before.if (idle) return machineIdconst pool = state.machines?.find(m => m.machineId === machineId)// [teamWritten]: code a Team agent wrote takes the Team account even in its owner's own project (teamWritten.ts, audit H2).if (!pool || (!teamWritten && project.ownerId === pool.contributorId)) return machineId+ if (!teamWritten && ownAccountWork(pool)) return machineIdreturn teamPoolOf(state, pool, live)?.machineId ?? machineId}diff --git a/backend/src/superTabs/messageEdits.test.ts b/backend/src/superTabs/messageEdits.test.tsnew file mode 100644index 000000000..b6a51bed7--- /dev/null+++ b/backend/src/superTabs/messageEdits.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest'+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'+import { createSuperTab, type Actor } from './model.js'+import type { MessageChangeTarget } from './messageEdits.js'++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }++function fixture() {+ let state = 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: 1000, operationId: `op-${++sequence}`, ...context })+ state = effects.state+ return effects+ }+ const invite = (role: 'viewer' | 'collaborator' = 'collaborator') => {+ const invited = run({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)+ }+ const agent = () => run({ type: 'agent.add', conversationId: 'lead', machineId: 'machine', harnessId: 'h1', name: 'Worker', configuration,+ lead: false }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string+ const lead = () => state.conversations.find(c => c.id === 'lead')!+ return { run, invite, agent, lead }+}++const edit = (text = 'Fixed text'): Command => commandSchema.parse({ type: 'message.edit', conversationId: 'lead', messageId: 'm1', text })+const remove = (): Command => commandSchema.parse({ type: 'message.delete', conversationId: 'lead', messageId: 'm1' })+const target = (extra: Partial<MessageChangeTarget> = {}): Partial<CommandContext> => ({ messageChange: { messageId: 'm1',+ author: { kind: 'person', id: 'owner' }, plain: true, deleted: false, hasFiles: false, hasReplies: false, text: 'Old text', sequence: 1, ...extra } })++describe('message edits', () => {+ it('lets the author edit their own post and bumps the group only on a change', () => {+ const f = fixture()+ expect(f.run(edit(), owner, target()).result).toMatchObject({ changed: true })+ expect(f.lead().reactionSeq).toBe(1)+ expect(f.run(edit('Old text'), owner, target()).result).toMatchObject({ changed: false })+ expect(f.lead().reactionSeq).toBe(1)+ })++ it('lets the author delete their own post, kept as deleted while it has replies', () => {+ const f = fixture()+ expect(f.run(remove(), owner, target()).result).toMatchObject({ changed: true, kept: false })+ expect(f.run(remove(), owner, target({ hasReplies: true })).result).toMatchObject({ changed: true, kept: true })+ expect(f.lead().reactionSeq).toBe(2)+ })++ it('only the author: never another person, a viewer or an agent', () => {+ const f = fixture()+ f.invite()+ for (const command of [edit(), remove()]) {+ expect(() => f.run(command, peer, target())).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))+ }+ const worker = f.agent()+ const asWorker: Actor = { kind: 'agent', agentId: worker, machineOwnerId: 'owner' }+ for (const command of [edit(), remove()]) {+ // The owner's own agent on the owner's own machine cannot change the owner's post either.+ expect(() => f.run(command, asWorker, target())).toThrow(expect.objectContaining({ status: 403 }))+ // Nor its own post: agents' messages are never edited.+ expect(() => f.run(command, asWorker, target({ author: { kind: 'agent', id: worker } }))).toThrow(expect.objectContaining({ status: 403 }))+ }+ expect(f.lead().reactionSeq ?? 0).toBe(0)+ })++ it('refuses a viewer, a system row, a deleted message and a message the store did not find', () => {+ const f = fixture()+ for (const command of [edit(), remove()]) {+ expect(() => f.run(command)).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))+ expect(() => f.run(command, owner, target({ messageId: 'other' }))).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))+ expect(() => f.run(command, owner, target({ plain: false }))).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))+ expect(() => f.run(command, owner, target({ deleted: true }))).toThrow(expect.objectContaining({ code: 'MESSAGE_DELETED' }))+ }+ f.invite('viewer')+ expect(() => f.run(edit(), peer, target({ author: { kind: 'person', id: 'peer' } }))).toThrow(expect.objectContaining({ code: 'READ_ONLY' }))+ })++ it('refuses empty text unless the message has files, and an archived group', () => {+ const f = fixture()+ expect(() => f.run(edit(' '), owner, target())).toThrow(expect.objectContaining({ code: 'INVALID_MESSAGE' }))+ expect(f.run(edit(''), owner, target({ hasFiles: true })).result).toMatchObject({ changed: true })+ const group = f.run({ type: 'conversation.create', title: 'Old', brief: 'Done.', checks: [] }).result.conversationId as string+ f.run({ type: 'conversation.archive', conversationId: group, archived: true })+ expect(() => f.run(commandSchema.parse({ type: 'message.edit', conversationId: group, messageId: 'm1', text: 'x' }), owner, target()))+ .toThrow(expect.objectContaining({ code: 'ARCHIVED' }))+ })++ it('removes a credential edited into a message, as a send does, and tells the author', () => {+ const f = fixture()+ // Built at run time so no token-shaped literal sits in the source.+ const token = ['ghp', 'Q7mZ2xK9pL4vB8nR1tY6wC3sD5fG0hJ2kM4n'].join('_')+ const effects = f.run(edit(`Use ${token} for the deploy`), owner, target())+ expect(effects.result).toMatchObject({ changed: true, credentialNotice: expect.stringContaining('Removed a credential') })+ expect(effects.messageEdit).toEqual({ messageId: 'm1', text: 'Use [credential removed] for the deploy' })+ expect(JSON.stringify(effects)).not.toContain(token)+ })+})diff --git a/backend/src/superTabs/messageEdits.ts b/backend/src/superTabs/messageEdits.tsnew file mode 100644index 000000000..a19dbc8b6--- /dev/null+++ b/backend/src/superTabs/messageEdits.ts@@ -0,0 +1,62 @@+import { fail, type Actor } from './model.js'++/** What a deleted message that keeps its thread reads as, stored as its text so every reader shows it: older apps, the CLI+ * and inbox previews among them. New apps draw it from `deletedAt`. */+export const DELETED_TEXT = 'This message was deleted.'++/** The message `message.edit` or `message.delete` names, found by the store in that conversation and readable by the actor+ * (store.ts messageChangeTarget, the checks reactionTarget makes). Absent when it is not there or the actor may not see it. */+export interface MessageChangeTarget {+ messageId: string+ author: { kind: string; id: string }+ /** A person's own post: no system source (parts/commit.ts counts the same rows as a person's). */+ plain: boolean+ deleted: boolean+ hasFiles: boolean+ /** For a delete: some other row replies in its thread, so it stays as DELETED_TEXT. */+ hasReplies: boolean+ text: string+ sequence: number+ /** For a delete that removes the row: the newest sequence left of each of the group's counters (model.ts lastMessageSequence,+ * lastMainSequence, lastPersonSequence), so a chat whose newest message goes is not left unread. Absent when none was found. */+ before?: { message?: number; main?: number; person?: number }+}++type Counters = { reactionSeq?: number; lastMessageSequence: number; lastMainSequence?: number; lastPersonSequence?: number }++/** Only the author changes a message: a person, on their own plain post. An agent (a Buddy too) never does, for anyone.+ * A message the actor cannot see reads as unavailable, so a refusal tells nothing about it. */+function changeable(actor: Actor, messageId: string, target: MessageChangeTarget | undefined): MessageChangeTarget {+ if (target?.messageId !== messageId) fail('NOT_FOUND', 'This message is unavailable.', 404)+ if (actor.kind !== 'person' || target.author.kind !== 'person' || target.author.id !== actor.userId || !target.plain) {+ fail('FORBIDDEN', 'Only its author can change this message.', 403)+ }+ if (target.deleted) fail('MESSAGE_DELETED', 'This message was deleted.', 409)+ return target+}++/** `message.edit`: the author's new text replaces the old; no earlier text is kept. Empty only for a message with files.+ * A change bumps the group, so every reader's next read takes the page again (reactions.ts). */+export function editMessage(group: { reactionSeq?: number }, actor: Actor, messageId: string, text: string,+ target: MessageChangeTarget | undefined): boolean {+ const found = changeable(actor, messageId, target)+ if (!text && !found.hasFiles) fail('INVALID_MESSAGE', 'Write something, or delete the message.', 400)+ if (found.text === text) return false+ group.reactionSeq = (group.reactionSeq ?? 0) + 1+ return true+}++/** `message.delete`: the row goes, or stays as DELETED_TEXT while replies hang under it. The store removes the rest. */+export function deleteMessage(group: Counters, actor: Actor, messageId: string,+ target: MessageChangeTarget | undefined): { kept: boolean } {+ const found = changeable(actor, messageId, target)+ group.reactionSeq = (group.reactionSeq ?? 0) + 1+ if (found.hasReplies) return { kept: true }+ // Each counter that pointed at the row steps back to the newest row left of its kind (parts/commit.ts numberMessages).+ // One with no row of its kind found within the look-back stays as it was: rare, and safer than saying the chat is empty.+ const before = found.before ?? {}+ if (group.lastMessageSequence === found.sequence && before.message !== undefined) group.lastMessageSequence = before.message+ if (group.lastMainSequence === found.sequence && before.main !== undefined) group.lastMainSequence = before.main+ if (group.lastPersonSequence === found.sequence && before.person !== undefined) group.lastPersonSequence = before.person+ return { kept: false }+}diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 72b612b36..c6e6e98b3 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -702,6 +702,8 @@ export interface CommandEffects {previousAttempts: Array<{ conversationId: string; brief: string; checks: Check[]; assignment: Assignment }>routeDecisions: RouteDecisionEffect[]result: Record<string, unknown>+ /** `message.edit`'s new text, credentials removed (commands.ts WORDS): what the store writes into the row. */+ messageEdit?: { messageId: string; text: string }/** A terminal request or its answer, written outside the tab state by the store (terminal.ts). */terminal?: import('./terminal.js').TerminalEffect/** Decisions asked, and a decision answered, written outside the tab state by the store (decisions.ts). */diff --git a/backend/src/superTabs/ownAccountWork.test.ts b/backend/src/superTabs/ownAccountWork.test.tsnew file mode 100644index 000000000..9037cf76f--- /dev/null+++ b/backend/src/superTabs/ownAccountWork.test.ts@@ -0,0 +1,225 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'+import { machineTeamWork, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'+import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'++// Task #2806 (Scholes, 11-04): a Mac added as its person joined runs teammates' work only in its Harness Team account+// (teamAccountOnly). The lampOS mobile team needs it in the owner's own account on Gray's Mac (Flutter and the phone signing+// are there). The machine's owner, and nobody else, may say that teammates' work may run in their own account; the default+// stays Team-account-only. Everything here runs with Team accounts required everywhere, the strictest setting.+beforeEach(() => { process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1' })+afterEach(() => { delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED })++const NOW = 50_000_000+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const gray: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'gray', email: '[email protected]' }+const mate: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'mate', email: '[email protected]' }+const config: AgentConfiguration = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,+ deviceType: null, chip: null, os: null, gpuPercent: null }+const PASSED: MachinePrivacy = { mode: 'account', passed: true, checkedAt: NOW - 60_000 }+type Reading = NonNullable<ContributedMachine['observation']>+const reading = (sessionKind: 'team' | 'computer', privacy?: MachinePrivacy): Reading => ({ generation: 'g1', receivedAt: NOW, sessionKind, resources,+ tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [], ...(privacy ? { privacy: { ...privacy, seenAt: NOW } } : {}) })+const refusal = (body: () => unknown): SuperTabError | null => {+ try { body(); return null } catch (error) { if (error instanceof SuperTabError) return error; throw error }+}++/** The owner's Swarm with two teammates. Gray's Mac was added as Gray joined (teamAccountOnly), with its Harness Team account,+ * whose privacy check passed. Projects: the owner's 'lead', and Gray's own. */+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 teamMachines = (state.machines ?? []).filter(m => m.observation?.sessionKind === 'team').map(m => m.machineId)+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, teamMachines, ...context })+ state = effects.state+ return effects+ }+ for (const person of [gray, mate]) {+ const invited = run({ type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, person)+ }+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation+ const joined = { contribution: { machineOwnerId: 'gray', contributorId: 'gray', hostGrant: null } }+ // As Desktop adds it when Gray joins: teammates' work only through its Team account.+ run({ type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4,+ teamAccountOnly: true }, gray, joined)+ state.machines!.find(m => m.machineId === 'gray-mac')!.observation = reading('computer')+ state.machines!.push({ machineId: 'gray-team', name: 'Gray\'s Mac', contributorId: 'gray', membershipGeneration: generation('gray'), generation: 'g1',+ cwd: '/team-swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4, paused: false, hostMachineId: 'gray-mac', observation: reading('team', PASSED) })+ state.machines!.push({ machineId: 'owner-mac', name: 'Owner Mac', contributorId: 'owner', membershipGeneration: generation('owner'), generation: 'g1',+ cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4, paused: false, observation: reading('computer') })+ const grays = String(run({ type: 'project.create', name: 'Gray\'s', visibility: 'public', brief: '' }, gray).result.projectId)+ // The project's Lead (the PM), on the owner's Mac.+ const leadId = 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: leadId, machineOwnerId: 'owner' }+ const group = (projectId = 'lead', actor: Actor = owner) => String(run({ type: 'conversation.create', projectId, title: 'Work', brief: 'Build it.',+ checks: [] }, actor).result.conversationId)+ const machine = (machineId: string) => state.machines!.find(m => m.machineId === machineId)!+ const request = (conversationId: string, machineId = 'gray-mac', projectId = 'lead') =>+ ({ conversationId, machineId, engine: 'codex', name: 'Builder', cwd: `/swarm/${projectId}`, worktree: true, requirements })+ const start = (conversationId: string, actor: Actor = owner, projectId = 'lead') =>+ run({ type: 'agent.start', request: request(conversationId, 'gray-mac', projectId) }, actor, joined)+ const choose = (allowed: boolean, actor: Actor = gray, machineId = 'gray-mac', context: Partial<CommandContext> = {}, extra: Record<string, unknown> = {}) =>+ run({ type: 'machine.ownAccountWork', machineId, allowed, ...extra } as Command, actor, context)+ /** An agent of the Swarm, run on Gray's Mac by Gray's grant: a Lead, or a Buddy of Gray's. */+ const agent = (id: string, extra: Record<string, unknown> = {}): Actor => {+ state.agents.push({ id, machineId: 'gray-mac', harnessId: `harness-${id}`, projectId: 'lead', machineOwnerId: 'gray', contributorId: 'gray',+ membershipGeneration: generation('gray'), hostGrant: null, name: id, configuration: config, ...extra })+ return { kind: 'agent', agentId: id, machineOwnerId: 'gray' }+ }+ return { run, group, machine, request, start, choose, agent, joined, grays, leadActor, get state() { return state } }+}++describe('teammates\' work in a Mac owner\'s own account', () => {+ it('is off by default: a teammate\'s start on a Mac added as its person joined goes to its Team account', () => {+ const f = swarm()+ expect(f.machine('gray-mac').ownAccountChoice).toBeUndefined()+ f.start(f.group())+ expect(f.state.starts![0]!.request).toMatchObject({ machineId: 'gray-team', cwd: '/team-swarm/lead' })+ })++ it('is turned on by the machine\'s owner, recording who and when, and then a teammate\'s start runs on the Mac itself', () => {+ const f = swarm()+ f.choose(true)+ expect(f.machine('gray-mac').ownAccountChoice).toEqual({ allowed: true, by: 'gray', at: new Date(NOW).toISOString() })+ // The Team account rule stays: only the move to the Team account is off.+ expect(f.machine('gray-mac').teamAccountOnly).toBe(true)+ f.start(f.group())+ expect(f.state.starts![0]!.request).toMatchObject({ machineId: 'gray-mac', cwd: '/swarm/lead' })+ // Routing reads it as a machine that takes a teammate's work.+ expect(teamWorkRefusal(f.machine('gray-mac'), NOW)).toBeNull()+ expect(machineTeamWork(f.state, f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()+ })++ it('is changed by nobody but the machine\'s owner: not the Swarm\'s owner, a teammate, an agent or a Buddy', () => {+ const f = swarm()+ const worker = f.agent('gray-worker')+ const buddy = f.agent('gray-buddy', { buddyOf: 'gray', buddyScope: 'swarm' })+ for (const actor of [owner, mate, f.leadActor, worker, buddy]) {+ // A Buddy is refused before the owner check, by the rule that it writes nowhere but its own chat.+ expect(['OWNER_REQUIRED', 'BUDDY_FORBIDDEN'], JSON.stringify(actor)).toContain(refusal(() => f.choose(true, actor))?.code)+ }+ expect(f.machine('gray-mac').ownAccountChoice).toBeUndefined()+ expect(commandSchema.safeParse({ type: 'machine.ownAccountWork', machineId: 'gray-mac', allowed: 'yes' }).success).toBe(false)+ })++ 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 = { askedIn: { conversationId: 'lead', messageId: 'm-gray' } }+ const said = (id: string, createdAt = NOW - 1000) => ({ askedIn: { author: { kind: 'person', id } as never, source: false, createdAt } })+ // The Swarm's owner, a teammate, an old message of Gray's, and a Buddy passing Gray's message on: refused.+ for (const [actor, context] of [[f.leadActor, said('owner')], [f.leadActor, said('mate')], [f.leadActor, said('gray', NOW - 2 * 24 * 60 * 60_000)],+ [f.agent('gray-buddy', { buddyOf: 'gray', buddyScope: 'swarm' }), said('gray')]] as const) {+ expect(['OWNER_REQUIRED', 'BUDDY_FORBIDDEN']).toContain(refusal(() => f.choose(true, actor, 'gray-mac', context, askedIn))?.code)+ }+ expect(f.machine('gray-mac').ownAccountChoice).toBeUndefined()+ // Turning it on loosens a privacy guard: only the owner's own session, which shows the warning (security review 2 of+ // #2981). A Lead passing on even the owner's own message cannot.+ expect(refusal(() => f.choose(true, f.leadActor, 'gray-mac', said('gray'), askedIn))?.code).toBe('OWNER_SESSION_REQUIRED')+ expect(f.machine('gray-mac').ownAccountChoice).toBeUndefined()+ f.choose(true)+ // Turning it off only tightens it: the Lead may, on the owner's own message. Recorded as Gray's choice, whose word it is.+ f.choose(false, f.leadActor, 'gray-mac', said('gray'), askedIn)+ // With the message it passed on, so an audit reads the words behind it (security review 1 of #2981).+ expect(f.machine('gray-mac').ownAccountChoice).toEqual({ allowed: false, by: 'gray', at: new Date(NOW).toISOString(),+ askedIn: { conversationId: 'lead', messageId: 'm-gray' } })+ })++ it('counts only a choice recorded as the machine owner\'s', () => {+ const f = swarm()+ f.machine('gray-mac').ownAccountChoice = { allowed: true, by: 'mate', at: new Date(NOW).toISOString() }+ f.start(f.group())+ expect(f.state.starts![0]!.request.machineId).toBe('gray-team')+ })++ it('reads the Mac itself, not its Team account, for routing once it is on', () => {+ const f = swarm()+ // A stale privacy check on the Team account refuses teammates there; with the owner's choice on, starts run on the Mac.+ f.machine('gray-team').observation = { ...reading('team', PASSED), privacy: { ...PASSED, seenAt: NOW - 24 * 60 * 60_000 } }+ expect(machineTeamWork(f.state, f.machine('gray-mac'), NOW, ['gray-team'])?.code).toBe('PRIVACY_CHECK_STALE')+ f.choose(true)+ expect(machineTeamWork(f.state, f.machine('gray-mac'), NOW, ['gray-team'])).toBeNull()+ })++ it('checks the owner before saying an entry is a Team account\'s', () => {+ const f = swarm()+ expect(refusal(() => f.choose(true, mate, 'gray-team'))?.code).toBe('OWNER_REQUIRED')+ })++ it('is set only on a Mac\'s own entry: not on its Team account, a machine being removed, or one not in the Swarm', () => {+ const f = swarm()+ expect(refusal(() => f.choose(true, gray, 'gray-team'))?.code).toBe('TEAM_ACCOUNT_ENTRY')+ expect(refusal(() => f.choose(true, gray, 'nowhere'))?.code).toBe('NOT_FOUND')+ f.machine('gray-mac').removal = { id: 'r', state: 'cleaning', requestedAt: new Date(NOW).toISOString() }+ expect(refusal(() => f.choose(true))?.code).toBe('MACHINE_REMOVED')+ })++ it('survives Desktop saving the contribution again, with or without the join\'s rule', () => {+ const f = swarm()+ f.choose(true)+ const save: Extract<Command, { type: 'machine.contribute' }> = { type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm',+ scope: 'swarm', engines: ['codex'], maxAgents: 2 }+ f.run({ ...save, teamAccountOnly: true }, gray, f.joined)+ expect(f.machine('gray-mac').ownAccountChoice).toMatchObject({ allowed: true, by: 'gray' })+ f.run(save, gray, f.joined)+ expect(f.machine('gray-mac')).toMatchObject({ maxAgents: 2, ownAccountChoice: { allowed: true } })+ })++ it('starts at the safe default when the Mac is removed and added again', () => {+ const f = swarm()+ f.choose(true)+ // Offline: it leaves the list at once.+ f.machine('gray-mac').observation = { ...reading('computer'), receivedAt: 0 }+ f.run({ type: 'machine.remove', machineId: 'gray-mac' }, gray)+ expect(f.state.machines!.some(m => m.machineId === 'gray-mac')).toBe(false)+ // Its host's cleanup is past waiting for (machines.ts cleanupOverdue), so it may be added again.+ for (const cleanup of f.state.machineCleanups ?? []) cleanup.requestedAt = new Date(NOW - 60 * 60_000).toISOString()+ f.run({ type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4,+ teamAccountOnly: true }, gray, f.joined)+ expect(f.machine('gray-mac').ownAccountChoice).toBeUndefined()+ })++ it('starts at the safe default when added again over a removal its host never confirmed', () => {+ const f = swarm()+ f.choose(true)+ f.machine('gray-mac').removal = { id: 'r', state: 'cleaning', requestedAt: new Date(NOW - 60 * 60_000).toISOString() }+ f.run({ type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4,+ teamAccountOnly: true }, gray, f.joined)+ expect(f.machine('gray-mac').ownAccountChoice).toBeUndefined()+ })++ it('turned back off, moves the next start to the Team account again and says why; agents already running stay', () => {+ const f = swarm()+ f.choose(true)+ f.start(f.group())+ const running = f.agent('running', { projectId: 'lead' })+ f.choose(false)+ expect(f.machine('gray-mac').ownAccountChoice).toEqual({ allowed: false, by: 'gray', at: new Date(NOW).toISOString() })+ const moved = f.start(f.group())+ expect(f.state.starts!.at(-1)!.request).toMatchObject({ machineId: 'gray-team' })+ expect(moved.result.moved).toBe('Gray\'s Mac runs teammates\' work in its Harness Team account. Its owner can change that in Manage > Machines.')+ expect(f.state.agents.find(a => a.id === (running as { agentId: string }).agentId)!.machineId).toBe('gray-mac')+ })++ it('says nothing for a start that is not moved: the owner\'s own project stays with the owner', () => {+ const f = swarm()+ const own = f.start(f.group(f.grays, gray), gray, f.grays)+ expect(f.state.starts![0]!.request.machineId).toBe('gray-mac')+ expect(own.result.moved).toBeUndefined()+ })++ it('still sends code a Team agent wrote to the Team account', () => {+ const f = swarm()+ f.choose(true)+ const group = f.group()+ const conversation = f.state.conversations.find(c => c.id === group)!+ Object.assign(conversation, { teamWritten: true })+ const result = refusal(() => f.start(group))+ // Moved or refused, never run as Gray.+ expect(result === null ? f.state.starts!.at(-1)!.request.machineId : result.code).not.toBe('gray-mac')+ })+})diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 166be500f..4b149146f 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -302,8 +302,9 @@ export async function threadsAcross(tx: Transaction, tabId: string, threads: Rea/*** Rewrites the summaries of the threads rooted at `roots` in one conversation from their rows now: one document per thread- * with a reply, as threadFacet gives it. Run in the transaction that inserts a reply (refreshReplies), so a summary holds what- * its rows do: two replies at once write the same document, and one of their transactions runs again.+ * with a reply, as threadFacet gives it, and none for a thread left with no reply. Run in the transaction that inserts a reply+ * (refreshReplies) or deletes one, so a summary holds what its rows do: two replies at once write the same document, and one+ * of their transactions runs again.*/export async function refreshThreads(tx: Transaction, tabId: string, conversationId: string, roots: string[]): Promise<void> {if (!roots.length) return@@ -317,6 +318,9 @@ export async function refreshThreads(tx: Transaction, tabId: string, conversatio})// Raw, so the stored parts read back as the $facet returns them, dates as dates.if (updates.length) await tx.$runCommandRaw({ update: 'SuperTabThread', updates: updates as unknown as Prisma.InputJsonArray })+ // A thread whose last reply was deleted (messageEdits.ts) has no summary left.+ const empty = roots.filter(root => !parts.some(p => p._id.thread === root && !p._id.root))+ if (empty.length) await tx.$runCommandRaw({ delete: 'SuperTabThread', deletes: [{ q: { _id: { $in: empty }, tabId, conversationId }, limit: 0 }] as unknown as Prisma.InputJsonArray })}/** Refreshes the summaries of the threads that `rows`, just inserted, reply in (refreshThreads). A row that is its owndiff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex dc8104ad7..21fe663e9 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -66,6 +66,8 @@ export const NAMED_INDEX = {/** One message. */id: { _id: 1 },},+ /** A project chat's open proposal roots, newest first (proposals.ts). */+ SuperTabOpenProposal: { open: { tabId: 1, conversationId: 1, sequence: 1 }, id: { _id: 1 } },/** A Swarm's newest route decisions: the route-decision list. */SuperTabRouteDecision: { recent: { tabId: 1, createdAt: 1 } },SuperTabDelivery: {diff --git a/backend/src/superTabs/proposals.test.ts b/backend/src/superTabs/proposals.test.tsindex 67b23bf99..292c032a6 100644--- a/backend/src/superTabs/proposals.test.ts+++ b/backend/src/superTabs/proposals.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import { applyCommand, type Command } from './commands.js'import { createSuperTab, type Actor, type Author, type SuperTabState } from './model.js'import type { ThreadReply } from './pageReads.js'-import { MAX_PROPOSALS, openProposals, proposalChat, type ProposalReads, type ProposalRoot } from './proposals.js'+import { MAX_PROPOSALS, openProposals, proposalChat, SEED_SETTLE_MS, type ProposalReads, type ProposalRoot } from './proposals.js'// The Tasks view's Proposals (#2569): a project's Buddy proposals its PM has not answered, by #2867's rule (threads.ts askOf).const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }@@ -36,17 +36,30 @@ const rows = (of: ProposalRoot, ...replies: Array<{ author: Author; ask?: ThreadcreatedAt: new Date(of.createdAt.getTime() + i + 1), agentOnly: false, routing: false, ...reply.ask ? { kind: 'system', ask: reply.ask } : {} })),]-/** The chat as the database reads it: roots newest first before a sequence, and the threads of the roots named. */-function chatReads(roots: ProposalRoot[], threads: ThreadReply[]) {+const NOW = 10_000_000+/** The chat as the database reads it: roots newest first before a sequence, and the threads of the roots named; and its open set+ * (SuperTabOpenProposal): the roots in it, and its seed mark's time. `calls` are the chat scan's; `counts`, every read's. */+function chatReads(roots: ProposalRoot[], threads: ThreadReply[], options: { seededAt?: number; open?: ProposalRoot[] } = {}) {const calls: Array<{ before: number | undefined; take: number }> = []+ const counts = { scan: 0, seededAt: 0, listed: 0, rootsById: 0, threads: 0, seed: 0, forget: 0 }+ const set = new Map((options.open ?? []).map(r => [r.id, r.sequence]))+ const forgotten: string[] = []+ let mark = options.seededAt ?? nullconst reads: ProposalReads = {+ seededAt: async () => { counts.seededAt++; return mark },+ seed: async open => { counts.seed++; for (const r of open) set.set(r.id, r.sequence); mark ??= NOW },+ listed: async (before, take) => { counts.listed++; return [...set].map(([id, sequence]) => ({ id, sequence }))+ .filter(r => before === undefined || r.sequence < before).sort((a, b) => b.sequence - a.sequence).slice(0, take) },+ rootsById: async ids => { counts.rootsById++; return roots.filter(r => ids.includes(r.id)) },roots: async (before, take) => {+ counts.scan++calls.push({ before, take })return roots.filter(r => before === undefined || r.sequence < before).sort((a, b) => b.sequence - a.sequence).slice(0, take)},- threads: async ids => threads.filter(row => ids.includes(row.thread)),+ threads: async ids => { counts.threads++; return threads.filter(row => ids.includes(row.thread)) },+ forget: async ids => { counts.forget++; for (const id of ids) { set.delete(id); forgotten.push(id) } },}- return { reads, calls }+ return { reads, calls, counts, set, forgotten }}describe('a project\'s open proposals', () => {@@ -64,7 +77,7 @@ describe('a project\'s open proposals', () => {...rows(personal, details, { author: person('owner') }),// A proposal from before #2867 with no reply at all has no thread summary: nobody answered it.])- expect(await openProposals(s.state, s.chat(), reads)).toEqual([+ expect(await openProposals(s.state, s.chat(), reads, NOW)).toEqual([{ messageId: 'old', title: 'Old proposal', personId: 'peer', at: 5 },{ messageId: 'open', title: 'Sync edits', personId: 'peer', at: 10 },{ messageId: 'personal', title: 'Offline drafts', personId: 'peer', at: 50 },@@ -75,16 +88,70 @@ describe('a project\'s open proposals', () => {const s = swarm()const roots = Array.from({ length: 250 }, (_, i) => root(`p${i}`, i + 1))const { reads, calls } = chatReads(roots, roots.flatMap(r => rows(r, { author: agent('buddy') })))- const listed = await openProposals(s.state, s.chat(), reads)+ const listed = await openProposals(s.state, s.chat(), reads, NOW)expect(listed).toHaveLength(MAX_PROPOSALS)expect(listed.map(p => p.messageId)).toEqual(roots.slice(-MAX_PROPOSALS).map(r => r.id))expect(calls).toEqual([{ before: undefined, take: MAX_PROPOSALS }])// Answered ones are read past, a batch at a time.const answered = chatReads(roots, roots.flatMap(r => rows(r, { author: agent(r.sequence > 200 ? s.pm : 'buddy') })))- expect((await openProposals(s.state, s.chat(), answered.reads)).map(p => p.messageId)).toEqual(roots.slice(100, 200).map(r => r.id))+ expect((await openProposals(s.state, s.chat(), answered.reads, NOW)).map(p => p.messageId)).toEqual(roots.slice(100, 200).map(r => r.id))expect(answered.calls.map(c => c.before)).toEqual([undefined, 151])})+ // Task #2777 (Ken's prod scan 11-04): Desktop reads this every minute, and the scan above walks the whole project chat.+ it('scans the chat once, keeping its open proposals, then answers the same from them alone, however long the chat', async () => {+ const s = swarm()+ const [open, answered, personal] = [root('open', 10, 'Sync edits'), root('answered', 20), root('personal', 50, 'Offline drafts')]+ const threads = [...rows(open, { author: agent('buddy') }), ...rows(answered, { author: agent(s.pm) }), ...rows(personal, { author: person('owner') })]+ const chat = chatReads([open, answered, personal], threads)+ const first = await openProposals(s.state, s.chat(), chat.reads, NOW)+ expect(first.map(p => p.messageId)).toEqual(['open', 'personal'])+ expect([...chat.set.keys()].sort()).toEqual(['open', 'personal'])+ expect(chat.counts.scan).toBe(1)+ const later = NOW + SEED_SETTLE_MS + 1+ expect(await openProposals(s.state, s.chat(), chat.reads, later)).toEqual(first)+ expect(chat.counts.scan).toBe(1)+ // The same reads for a chat of a thousand answered proposals besides.+ const many = Array.from({ length: 1_000 }, (_, i) => root(`old${i}`, 100 + i))+ const short = chatReads([open, personal], threads, { seededAt: NOW, open: [open, personal] })+ const long = chatReads([open, personal, ...many], [...threads, ...many.flatMap(r => rows(r, { author: agent(s.pm) }))], { seededAt: NOW, open: [open, personal] })+ expect(await openProposals(s.state, s.chat(), short.reads, later)).toEqual(first)+ expect(await openProposals(s.state, s.chat(), long.reads, later)).toEqual(first)+ expect(long.counts).toEqual(short.counts)+ expect(long.counts).toMatchObject({ scan: 0, seededAt: 1, listed: 1, rootsById: 1, threads: 1, seed: 0 })+ })++ it('lists a proposal sent since, and forgets one the PM answered, one a task marks, and one whose root is gone', async () => {+ const s = swarm()+ const [fresh, answered, onIt, gone] = [root('fresh', 60, 'New idea'), root('answered', 20), root('on-it', 30), root('gone', 40)]+ const chat = chatReads([fresh, answered, onIt], [...rows(fresh, { author: agent('buddy') }), ...rows(answered, { author: agent('buddy') }, { author: agent(s.pm) }),+ ...rows(onIt, { author: agent('buddy') }, { author: person('owner'), ask: 'on-it' })], { seededAt: NOW - SEED_SETTLE_MS - 1, open: [fresh, answered, onIt, gone] })+ expect(await openProposals(s.state, s.chat(), chat.reads, NOW)).toEqual([{ messageId: 'fresh', title: 'New idea', personId: 'peer', at: 60 }])+ expect(chat.forgotten.sort()).toEqual(['answered', 'gone', 'on-it'])+ expect([...chat.set.keys()]).toEqual(['fresh'])+ expect(chat.counts.scan).toBe(0)+ // Nothing more to forget: no write.+ await openProposals(s.state, s.chat(), chat.reads, NOW)+ expect(chat.counts.forget).toBe(1)+ })++ it('scans the chat again for half an hour after its seed: a server still on the older release writes no row', async () => {+ const s = swarm()+ const late = root('late', 70, 'Sent during the release')+ const chat = chatReads([late], rows(late, { author: agent('buddy') }), { seededAt: NOW - 60_000 })+ expect((await openProposals(s.state, s.chat(), chat.reads, NOW)).map(p => p.messageId)).toEqual(['late'])+ expect(chat.counts.scan).toBe(1)+ expect([...chat.set.keys()]).toEqual(['late'])+ })++ it('keeps the newest 100 from the open set, read a batch at a time', async () => {+ const s = swarm()+ const roots = Array.from({ length: 250 }, (_, i) => root(`p${i}`, i + 1))+ const chat = chatReads(roots, roots.flatMap(r => rows(r, { author: agent('buddy') })), { seededAt: 0, open: roots })+ expect((await openProposals(s.state, s.chat(), chat.reads, NOW)).map(p => p.messageId)).toEqual(roots.slice(-MAX_PROPOSALS).map(r => r.id))+ expect(chat.counts).toMatchObject({ scan: 0, listed: 1, rootsById: 1, threads: 1 })+ })+it('is read only by those who read the project chat', () => {const s = swarm()expect(proposalChat(s.state, peer, 'lead').id).toBe('lead')diff --git a/backend/src/superTabs/proposals.ts b/backend/src/superTabs/proposals.tsindex 2f3999d78..6fc4d6727 100644--- a/backend/src/superTabs/proposals.ts+++ b/backend/src/superTabs/proposals.ts@@ -1,7 +1,12 @@/*** A project's Buddy proposals its PM has not answered (the Tasks view's Proposals, #2569), by #2867's rule as the chat shows* it (threads.ts askOf): no mark from a task opened from it, and no reply in its thread from the project chat's lead agent.- * Nothing is stored for it: the roots are read from the project chat, and their threads as the chat page reads them.+ *+ * Desktop reads it every minute, and finding the roots among the project chat's rows walked the whole chat each time (Ken's+ * prod scan 11-04, task #2777). So the chat's roots not yet seen answered are kept apart (SuperTabOpenProposal): each root's+ * row is written with it (store.ts writeMessages), and the read takes those roots by id. It reads their threads as the chat+ * page does and forgets the ones it finds answered, which stay answered by that rule: a task's mark never reverts to an ask,+ * and the lead's reply stays in the thread. A chat read before it had any is scanned once, as before, to seed them.*/import type { Prisma } from '@prisma/client'import type { Actor, Conversation, SuperTabState } from './model.js'@@ -20,12 +25,29 @@ export const MAX_ROOTS = 1_000const ROOT_PREFIX = "Let's build: "export interface OpenProposal { messageId: string; title: string; personId?: string; at: number }+/** How long after a chat's seed its reads scan it again: a server still on the release before writes a proposal with no row+ * in the open set, and a rolling release replaces them within minutes. */+export const SEED_SETTLE_MS = 30 * 60_000+/** A proposal's root as the read takes it from the chat. */export interface ProposalRoot { id: string; sequence: number; text: string; source: Record<string, unknown>; createdAt: Date }-/** The chat's proposal roots newest first, before a sequence (all of them without one); and the threads of some roots. */+/** One root in the chat's open set. */+export interface ListedProposal { id: string; sequence: number }export interface ProposalReads {+ /** When the chat's open set was first seeded from its rows; null before. */+ seededAt(): Promise<number | null>+ /** Puts [roots] in the open set and marks the chat seeded, its first seed's time kept. */+ seed(roots: ListedProposal[]): Promise<void>+ /** The open set's roots newest first, before a sequence (all of them without one). */+ listed(before: number | undefined, take: number): Promise<ListedProposal[]>+ /** The chat's proposal roots of [ids]; one not in the chat, or no proposal's root, is left out. */+ rootsById(ids: string[]): Promise<ProposalRoot[]>+ /** The chat's proposal roots newest first, before a sequence: the seed's scan of the chat. */roots(before: number | undefined, take: number): Promise<ProposalRoot[]>+ /** The threads of some roots, as the chat page reads them. */threads(rootIds: string[]): Promise<ThreadReply[]>+ /** Takes [ids] out of the open set. */+ forget(ids: string[]): Promise<void>}/** The project chat [projectId] names, for a reader who may read it, as the messages read checks it; else NOT_FOUND. */@@ -33,40 +55,108 @@ export function proposalChat(state: SuperTabState, actor: Actor, projectId: strireturn readConversation(state, actor, readProject(state, actor, projectId).leadConversationId)}-/** The open proposals in [chat], oldest first: the newest MAX_PROPOSALS, read a batch of roots at a time. */-export async function openProposals(state: SuperTabState, chat: Conversation, reads: ProposalReads): Promise<OpenProposal[]> {- const open: OpenProposal[] = []+/** The open proposals in [chat], oldest first: the newest MAX_PROPOSALS, from its open set once seeded, else from its rows. */+export async function openProposals(state: SuperTabState, chat: Conversation, reads: ProposalReads, now = Date.now()): Promise<OpenProposal[]> {+ const seededAt = await reads.seededAt()+ if (seededAt === null || now - seededAt < SEED_SETTLE_MS) {+ const open = await scanned(state, chat, reads)+ await reads.seed(open.map(root => ({ id: root.id, sequence: root.sequence })))+ return open.map(shown).reverse()+ }+ const open: ProposalRoot[] = []+ for (let before: number | undefined, read = 0; open.length < MAX_PROPOSALS && read < MAX_ROOTS;) {+ const listed = await reads.listed(before, MAX_PROPOSALS)+ if (!listed.length) break+ read += listed.length+ const found = new Map((await reads.rootsById(listed.map(r => r.id))).map(root => [root.id, root]))+ const roots = listed.flatMap(r => found.get(r.id) ?? [])+ const unanswered = new Set(await unansweredOf(state, chat, reads, roots))+ const forget = listed.filter(r => !unanswered.has(r.id)).map(r => r.id)+ if (forget.length) await reads.forget(forget)+ open.push(...roots.filter(root => unanswered.has(root.id)))+ if (listed.length < MAX_PROPOSALS) break+ before = listed.at(-1)!.sequence+ }+ return open.slice(0, MAX_PROPOSALS).map(shown).reverse()+}++/** The ids of [roots] nobody answered. A root with no reply has no summary: nobody answered it. */+async function unansweredOf(state: SuperTabState, chat: Conversation, reads: ProposalReads, roots: ProposalRoot[]): Promise<string[]> {+ if (!roots.length) return []+ const asks = new Map(threadSummaries(state, chat, await reads.threads(roots.map(r => r.id))).map(t => [t.id, t.ask]))+ return roots.filter(root => !asks.has(root.id) || asks.get(root.id) === 'proposal').map(root => root.id)+}++/** The chat's open proposal roots, newest first: the newest MAX_PROPOSALS among its newest MAX_ROOTS, read a batch at a time. */+async function scanned(state: SuperTabState, chat: Conversation, reads: ProposalReads): Promise<ProposalRoot[]> {+ const open: ProposalRoot[] = []for (let before: number | undefined, read = 0; open.length < MAX_PROPOSALS && read < MAX_ROOTS;) {const roots = await reads.roots(before, MAX_PROPOSALS)if (!roots.length) breakread += roots.length- // A root with no reply has no summary: nobody answered it.- const asks = new Map(threadSummaries(state, chat, await reads.threads(roots.map(r => r.id))).map(t => [t.id, t.ask]))- for (const root of roots) {- if (asks.has(root.id) && asks.get(root.id) !== 'proposal') continue- const personId = root.source.personId- open.push({ messageId: root.id, title: root.text.startsWith(ROOT_PREFIX) ? root.text.slice(ROOT_PREFIX.length) : root.text,- ...typeof personId === 'string' ? { personId } : {}, at: root.createdAt.getTime() })- }+ const unanswered = new Set(await unansweredOf(state, chat, reads, roots))+ open.push(...roots.filter(root => unanswered.has(root.id)))if (roots.length < MAX_PROPOSALS) breakbefore = roots.at(-1)!.sequence}- return open.slice(0, MAX_PROPOSALS).reverse()+ return open.slice(0, MAX_PROPOSALS)+}++function shown(root: ProposalRoot): OpenProposal {+ const personId = root.source.personId+ return { messageId: root.id, title: root.text.startsWith(ROOT_PREFIX) ? root.text.slice(ROOT_PREFIX.length) : root.text,+ ...typeof personId === 'string' ? { personId } : {}, at: root.createdAt.getTime() }}const date = (value: unknown): Date => new Date((value as { $date?: string } | null)?.$date ?? value as string)+const OPEN = 'SuperTabOpenProposal'+const ROOT_FIELDS = { $project: { _id: 1, tabId: 1, conversationId: 1, sequence: 1, text: 1, source: 1, thread: 1, createdAt: 1 } }+const rootOf = (row: Record<string, unknown>): ProposalRoot => ({ id: row._id as string, sequence: row.sequence as number, text: row.text as string,+ source: row.source as Record<string, unknown>, createdAt: date(row.createdAt) })+/** Its own thread's root (none before threads), posted by buddy.propose. */+const isRoot = (row: Record<string, unknown>) => (row.source as { kind?: unknown } | null)?.kind === 'buddy-proposal' && (row.thread ?? row._id) === row._id++/** The id of [chatId]'s seed mark in the open set. */+export const seedMarkId = (tabId: string, chatId: string) => `seeded:${tabId}:${chatId}`++/** The open-set rows of the proposal roots among [rows], just inserted (store.ts writeMessages). */+export function openProposalRows(tabId: string, rows: ReadonlyArray<{ id: string; conversationId: string; sequence: number; source?: unknown; thread?: string | null }>):+ Array<{ id: string; tabId: string; conversationId: string; sequence: number }> {+ return rows.filter(row => isRoot({ _id: row.id, source: row.source, thread: row.thread }))+ .map(row => ({ id: row.id, tabId, conversationId: row.conversationId, sequence: row.sequence }))+}-/** The reads of [chatId], from the database: its roots by the conversation's sequence index, newest first; its threads as- * the chat page reads them (pageThreads). A proposal root is the only row of its command, so no other shares its sequence. */+/** The reads of [chatId], from the database. Its open set by its own index, newest first, and its roots by id; its threads as+ * the chat page reads them (pageThreads). The seed's scan reads the chat's roots by the conversation's sequence index, newest+ * first: a proposal root is the only row of its command, so no other shares its sequence. */export function databaseProposalReads(tx: Transaction, tabId: string, chatId: string): ProposalReads {+ const mark = seedMarkId(tabId, chatId)+ const upsert = (id: string, sequence: number) => ({ q: { _id: id },+ u: { $setOnInsert: { tabId, conversationId: chatId, sequence, createdAt: { $date: new Date().toISOString() } } }, upsert: true })return {+ seededAt: async () => {+ const found = (await readBy(tx, OPEN, 'id', [{ $match: { _id: mark } }, { $project: { createdAt: 1 } }]))[0]+ return found ? date(found.createdAt).getTime() : null+ },+ // The roots first and the mark last: a seed that stops between them is run again.+ seed: async roots => {+ await tx.$runCommandRaw({ update: OPEN, updates: [...roots.map(r => upsert(r.id, r.sequence)), upsert(mark, -1)] as unknown as Prisma.InputJsonArray })+ },+ listed: async (before, take) => (await readBy(tx, OPEN, 'open', [+ { $match: { tabId, conversationId: chatId, sequence: before === undefined ? { $gte: 0 } : { $gte: 0, $lt: before } } },+ { $sort: { sequence: -1 } }, { $limit: take }, { $project: { _id: 1, sequence: 1 } }]))+ .map(row => ({ id: row._id as string, sequence: row.sequence as number })),+ // By `_id` alone, then held to this chat: no other index of the collection can serve it and walk the chat.+ rootsById: async ids => ids.length ? (await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: ids } } }, ROOT_FIELDS]))+ .filter(row => row.tabId === tabId && row.conversationId === chatId && isRoot(row)).map(rootOf) : [],roots: async (before, take) => (await readBy(tx, 'SuperTabMessage', 'sequence', [{ $match: { tabId, conversationId: chatId, ...before === undefined ? {} : { sequence: { $lt: before } }, 'source.kind': 'buddy-proposal' } },// Its own thread's root (none before threads).{ $match: { $expr: { $eq: [{ $ifNull: ['$thread', '$_id'] }, '$_id'] } } },- { $sort: { sequence: -1, _id: -1 } }, { $limit: take }, { $project: { _id: 1, sequence: 1, text: 1, source: 1, createdAt: 1 } }]))- .map(row => ({ id: row._id as string, sequence: row.sequence as number, text: row.text as string, source: row.source as Record<string, unknown>,- createdAt: date(row.createdAt) })),+ { $sort: { sequence: -1, _id: -1 } }, { $limit: take }, ROOT_FIELDS])).map(rootOf),threads: rootIds => pageThreads(tx, tabId, chatId, rootIds),+ forget: async ids => {+ if (ids.length) await tx.$runCommandRaw({ delete: OPEN, deletes: [{ q: { _id: { $in: ids }, tabId }, limit: 0 }] as unknown as Prisma.InputJsonArray })+ },}}diff --git a/backend/src/superTabs/purge.ts b/backend/src/superTabs/purge.tsindex 25f294abc..1b5395a8d 100644--- a/backend/src/superTabs/purge.ts+++ b/backend/src/superTabs/purge.ts@@ -17,7 +17,7 @@ export const PURGE_RETRY_MS = 6 * 60 * 60 * 1000/** The records of one Swarm, each by its Swarm id (every one has an index led by it, schema.prisma). Attachments are* removed apart, with their files. */export const PURGED_BY_TAB_ID = ['superTabMessage', 'superTabMention', 'superTabReaction', 'superTabActivity', 'superTabChatSetting', 'superTabReminder', 'superTabReadMark',- 'superTabThreadMark', 'superTabThread', 'superTabDecision', 'superTabOperation', 'superTabNativeContext', 'superTabDelivery', 'superTabReceipt',+ 'superTabThreadMark', 'superTabThread', 'superTabOpenProposal', 'superTabDecision', 'superTabOperation', 'superTabNativeContext', 'superTabDelivery', 'superTabReceipt','superTabRun', 'superTabAttempt', 'superTabRouteDecision', 'superTabModelEvidence', 'superTabModelRecent', 'superTabStopReceipt','superTabRoleText', 'superTabInstructions', 'superTabInstructionsRevision', 'superTabPmNote', 'superTabConfiguration', 'superTabTerminalRequest','gitHubRepositoryApproval', 'gitHubApprovalRefusal', 'swarmHead', 'swarmMember', 'swarmGroup', 'swarmAgent', 'swarmMachine', 'swarmStart',diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 7bf2107b2..bfad7863c 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,6 +1,7 @@import { refusalLogFields, type DeclaredClient } from './refusalLog.js'import { writeReactionActivity, writeReplyActivity } from './activity.js'-import { accountMachineName, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'+import { accountMachineName, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'+import { shownNameOf } from './personNames.js'import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'import { createHash } from 'node:crypto'@@ -21,11 +22,11 @@ import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, LOOP_NOTICE_AT, mayimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCELLABLE_DELIVERY, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, type PageDelivery } from './pageReads.js'+import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCELLABLE_DELIVERY, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, refreshThreads, type PageDelivery } from './pageReads.js'import { deliveriesByMessage } from './read/pageDeliveries.js'import { restoreDelivery } from './deliveryCompaction.js'import { threadSummaries } from './threads.js'-import { databaseProposalReads, openProposals, proposalChat, type OpenProposal } from './proposals.js'+import { databaseProposalReads, openProposalRows, openProposals, proposalChat, type OpenProposal } from './proposals.js'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'@@ -40,6 +41,7 @@ import { cleanPullRequestLinks } from './cards.js'import { accountOf, wordsOf, buddyPerson, canReadAgent, canReadGroup, groupRepositoryUrl, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey, GITHUB_SEEN, type GitHubSeen, type SwarmProject } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { SESSION_ENDED_KIND, sessionContext, sessionReadsRow, type ContextRow } from './buddySessions.js'+import { DELETED_TEXT, type MessageChangeTarget } from './messageEdits.js'import { isBuddy, isBuddyChat, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'import { lostReasonWithoutMachine } from './lostReason.js'import { LEAD_NAME } from './leadStart.js'@@ -105,6 +107,19 @@ import { emailDomain } from '../lib/publicEmailDomains.js'type Transaction = Prisma.TransactionClienttype ReactCommand = Extract<Command, { type: 'message.react' }>+type MessageChangeCommand = Extract<Command, { type: 'message.edit' | 'message.delete' }>+/** How far back a delete looks for the rows its group's counters step back to (messageEdits.ts deleteMessage). */+const COUNTERS_LOOKBACK = 100+/** The newest sequence before `row` of each of a group's counters (parts/commit.ts numberMessages): any shown row, a main-stream+ * row, a person's own main-stream post. Within COUNTERS_LOOKBACK rows; a counter with none found there is left out. */+async function countersBefore(tx: Transaction, tabId: string, conversationId: string, row: { id: string; sequence: number }) {+ const rows = await messagesPast(tx, { tabId, conversationId }, { sequence: row.sequence, id: row.id }, false, COUNTERS_LOOKBACK)+ const shown = rows.filter(m => m.id !== row.id && !agentOnly(m.source, m.recipientIds))+ const main = shown.filter(m => !m.thread || m.thread === m.id || m.alsoInChat)+ const person = main.filter(m => (m.author as { kind?: string } | null)?.kind === 'person' && m.source == null)+ const newest = (list: SuperTabMessage[]) => list.length ? Math.max(...list.map(m => m.sequence)) : undefined+ return { message: newest(shown), main: newest(main), person: newest(person) }+}const reactionId = (tabId: string, actor: Actor, command: ReactCommand) => stableId(tabId, command.messageId, actorKey(actor), command.emoji)const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValuetype SendCommand = Extract<Command, { type: 'message.send' }>@@ -683,7 +698,8 @@ 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': case 'machine.projects': return refuse()+ case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.engineResume': case 'machine.projects':+ case 'machine.ownAccountWork': return refuse()case 'machine.cleaned': case 'tab.project': case 'agent.add':if (command.machineId !== team) refuse()return@@ -1293,7 +1309,9 @@ export class SuperTabStore {const refusal = machineTeamWork(state, stored, now, teamMachines, otherWorkspace)const suspended = suspendedEngines(stored, now)return { ...pool, availableSlots: Math.max(0, pool.maxAgents - slots(stored)),- teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const },+ teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const,+ // Its owner lets teammates' work run in their own account (machines.ts ownAccountWork): the route says so.+ ...(ownAccountWork(stored) ? { ownAccount: ownAccountNote(stored, shownNameOf(state, stored.contributorId)) } : {}) },...(facts.versions[pool.machineId] ? { clientVersion: facts.versions[pool.machineId] } : {}),// What the route leaves out (cli superTabs/routeCommand.ts unreadyPool)....(Object.keys(suspended).length ? { suspendedEngines: suspended } : {}) }@@ -1621,7 +1639,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.type === 'machine.projects') && command.askedIn) {+ || command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork') && 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() }}@@ -1680,6 +1698,7 @@ export class SuperTabStore {}if (command.type === 'buddy.propose' && command.attachmentIds?.length) ({ attachments: context.attachments, claimed, proposed } = await this.proposable(tx, original, actor, command))if (command.type === 'message.react') context.reaction = await this.reactionTarget(tx, tabId, actor, command, original)+ if (command.type === 'message.edit' || command.type === 'message.delete') context.messageChange = await this.messageChangeTarget(tx, tabId, actor, command, original)if ((command.type === 'member.avatar' || command.type === 'agent.avatar') && command.avatar?.kind === 'upload') {context.avatarUpload = await this.avatarUpload(tx, tabId, actor, command.avatar.id)}@@ -1934,6 +1953,11 @@ export class SuperTabStore {}if (command.type === 'mention.done') await markDone(tx, tabId, command.mentionId, context.mention!.personId, context.now)if (command.type === 'message.react') await this.writeReaction(tx, tabId, actor, command, context.now)+ // The cleaned text (commands.ts WORDS), never the command as it was sent (security review 2 of #2967).+ if (effects.messageEdit) {+ await tx.superTabMessage.update({ where: { id: effects.messageEdit.messageId }, data: { text: effects.messageEdit.text, editedAt: new Date(context.now) } })+ }+ if (command.type === 'message.delete') await this.writeDelete(tx, tabId, command, effects.result.kept === true, effects.state.people.map(p => p.id), context.now)if (context.avatarUpload) {// Conflicts with a concurrent use of the same picture: only one command can take it.const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: context.avatarUpload.id, purpose: AVATAR_PURPOSE, ...unused },@@ -2429,6 +2453,65 @@ export class SuperTabStore {messageId: command.messageId, actorKind: actor.kind, actorId, emoji: command.emoji } })}+ /** The message `message.edit` or `message.delete` names (messageEdits.ts), found as a reaction's is (reactionTarget): in that+ * conversation and readable by this actor, else absent, which refuses it as unavailable. A delete also reads whether+ * anything replies in its thread, and the counters' rows before it. */+ private async messageChangeTarget(tx: Transaction, tabId: string, actor: Actor, command: MessageChangeCommand,+ state: SuperTabState): Promise<MessageChangeTarget | undefined> {+ const message = await tx.superTabMessage.findFirst({ where: { id: command.messageId, tabId, conversationId: command.conversationId },+ select: { id: true, source: true, recipientIds: true, thread: true, buddySession: true, author: true, buddyProject: true, text: true,+ attachments: true, sequence: true, deletedAt: true, alsoInChat: true } })+ if (!message || (agentOnly(message.source, message.recipientIds) && !(actor.kind === 'agent' && message.recipientIds.includes(actor.agentId)))) return undefined+ const group = state.conversations.find(c => c.id === command.conversationId)+ const reader = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId) : undefined+ if (group && !sessionReadsRow(reader, group, state)(message)) return undefined+ if ((await deliveredCopies(tx, tabId, [message])).size) return undefined+ const author = message.author as { kind?: string; id?: string } | null+ const target: MessageChangeTarget = { messageId: message.id, author: { kind: String(author?.kind ?? ''), id: String(author?.id ?? '') },+ plain: message.source == null, deleted: !!message.deletedAt, hasFiles: Array.isArray(message.attachments) && message.attachments.length > 0,+ hasReplies: false, text: message.text, sequence: message.sequence }+ // Only an author's delete reads further; anyone else is refused on the row alone.+ if (command.type !== 'message.delete' || actor.kind !== 'person' || target.author.id !== actor.userId) return target+ // A root with replies stays (by the thread index, one reply at most, never itself).+ if (!message.thread || message.thread === message.id) {+ const replies = await messagesPast(tx, { tabId, conversationId: command.conversationId, thread: message.id }, { sequence: message.sequence, id: message.id }, true, 1)+ target.hasReplies = replies.some(r => r.id !== message.id)+ }+ if (!target.hasReplies) target.before = await countersBefore(tx, tabId, command.conversationId, message)+ return target+ }++ /** What a delete removes beside its row (messageEdits.ts): its reactions and their Activity, the Activity of the reply it was,+ * deliveries no agent has taken yet, and its files, which the hourly sweep removes from the bucket (lib/attachmentSweep.ts).+ * A root with replies stays as DELETED_TEXT with nothing else of what it said; a reply's thread summary is written again. */+ private async writeDelete(tx: Transaction, tabId: string, command: Extract<Command, { type: 'message.delete' }>, kept: boolean, people: string[], now: number) {+ const row = await tx.superTabMessage.findUniqueOrThrow({ where: { id: command.messageId }, select: { id: true, conversationId: true, thread: true, attachments: true, mentions: true } })+ const files = Array.isArray(row.attachments) ? (row.attachments as unknown as Attachment[]).map(a => a.id) : []+ // Raw `$in` filters: Prisma sends `in` as $expr, which no index bounds (hotFilters.test.ts). By _id, and by [tabId, messageId].+ if (files.length) await tx.$runCommandRaw({ update: 'SuperTabAttachment', updates: [{ q: { _id: { $in: files }, tabId }, u: { $set: { usedBy: EXPIRED_UPLOAD } }, multi: true }] })+ // Activity has no index by message: its rows go by the ids they were written with (activity.ts), each reaction's from its row,+ // the reply's for every member it could have told.+ const reactions = await tx.superTabReaction.findMany({ where: { tabId, messageId: row.id }, select: { id: true } })+ const activityIds = [...reactions.map(r => stableId(tabId, 'reaction', r.id)), ...people.map(personId => stableId(tabId, 'reply', row.id, personId))]+ await tx.superTabReaction.deleteMany({ where: { tabId, messageId: row.id } })+ if (activityIds.length) await tx.$runCommandRaw({ delete: 'SuperTabActivity', deletes: [{ q: { _id: { $in: activityIds }, tabId }, limit: 0 }] })+ // Its tags (mentions.ts writeMentions ids): nobody keeps a waiting tag to a message they cannot open (security review 1 of #2967).+ const tagIds = (row.mentions ?? []).map(personId => stableId(tabId, row.id, personId))+ if (tagIds.length) await tx.$runCommandRaw({ delete: 'SuperTabMention', deletes: [{ q: { _id: { $in: tagIds }, tabId }, limit: 0 }] })+ await tx.$runCommandRaw({ update: 'SuperTabDelivery', updates: [{ q: { tabId, messageId: row.id, status: { $in: [...CANCELLABLE_DELIVERY] } },+ u: { $set: { status: 'cancelled', holdReason: null, holdSince: null, updatedAt: { $date: new Date(now).toISOString() } } }, multi: true }] })+ if (kept) {+ // Raw: Prisma writes `{ unset: true }` into a Json field as a value instead of removing it.+ await tx.$runCommandRaw({ update: 'SuperTabMessage', updates: [{ q: { _id: row.id, tabId }, u: { $set: { text: DELETED_TEXT, mentions: [],+ deletedAt: { $date: new Date(now).toISOString() } }, $unset: { attachments: '', editedAt: '' } } }] })+ // Its own thread's summary drops the people only this root tagged.+ await refreshThreads(tx, tabId, row.conversationId, [row.id])+ return+ }+ await tx.superTabMessage.delete({ where: { id: row.id } })+ if (row.thread && row.thread !== row.id) await refreshThreads(tx, tabId, row.conversationId, [row.thread])+ }+/** The avatar upload a command names, when it is this actor's, an avatar and unused; otherwise the command refuses it. */private async avatarUpload(tx: Transaction, tabId: string, actor: Actor, id: string): Promise<AvatarUpload | undefined> {const row = await tx.superTabAttachment.findFirst({ where: { tabId, id, actorKey: actorKey(actor), purpose: AVATAR_PURPOSE, ...unused } })@@ -2723,6 +2806,9 @@ export class SuperTabStore {}}if (rows.length) await tx.superTabMessage.createMany({ data: rows })+ // A proposal's root joins its chat's open proposals with it, which the Tasks view reads by id (proposals.ts).+ const proposals = openProposalRows(tabId, rows)+ if (proposals.length) await tx.superTabOpenProposal.createMany({ data: proposals })// A reply's thread summary, in this transaction (pageReads.ts refreshThreads).await refreshReplies(tx, tabId, rows)for (const message of messages) {diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 4505f1b60..1d798e125 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,7 +1,7 @@import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabAutoJoin.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',- 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabReminders.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts',+ 'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.test.ts', 'integration/superTabMessageEdits.test.ts', 'integration/superTabReminders.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.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/superTabMachineLiveness.test.ts', 'integration/superTabHeldParts.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',diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 12bba2109..56572861a 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -1522,6 +1522,18 @@ 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 #2806 (River, 11-04): a machine whose owner lets teammates' work run in their own account (backend machines.ts+ // ownAccountWork). The teammate whose task lands there did not choose it, so the route says so, for new agents and members.+ it('says a machine runs a teammate\'s work in its owner\'s own account, and says nothing for the owner\'s own project', async () => {+ const said = 'Contributed laptop runs teammates\' work in Mate\'s own account.'+ const pool = { ...healthy(), contributorId: 'mate', teamWork: { allowed: true, ownAccount: said } }+ const teammate = (await runPool(pool, true, {}, { id: 'lead', ownerId: 'owner' })).answer+ const rows = [teammate.pick, ...teammate.alternatives as unknown[]] as Array<{ title: string; notes?: string[] }>+ expect(rows.length).toBeGreaterThan(1)+ for (const row of rows) expect(row.notes ?? [], row.title).toContain(said)+ const own = (await runPool(pool, true, {}, { id: 'lead', ownerId: 'mate' })).answer+ expect(JSON.stringify(own)).not.toContain(said)+ })// 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 () => {diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 64646dbc4..5fdcff42f 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -292,6 +292,9 @@ export async function routeTask(input: { tabId: string; conversationId: string;// Offline is said once, by the reading's own age below....(teamWork.allowed === false && teamWork.code !== 'MACHINE_OFFLINE' && typeof teamWork.reason === 'string'? { teammatesRefused: teamWork.reason, projectOwnerId: projectOwner } : {}),+ // Its owner lets teammates' work run in their own account (backend machines.ts ownAccountWork, task #2806): the teammate+ // whose task lands there did not choose that, so the route says it (River, 11-04).+ ...(teamWork.allowed === true && typeof teamWork.ownAccount === 'string' ? { ownAccount: teamWork.ownAccount, projectOwnerId: projectOwner } : {}),...(original.scope === 'swarm' ? { cwd: repository.machineId === original.machineId? repository.cwd : `${String(original.cwd).replace(/\/+$/, '')}/${projectId}` } : {}),...(original.scope !== 'swarm' && projectId !== 'lead' ? { projectUnavailable: true } : {}),@@ -615,6 +618,8 @@ async function probeMachine(machineId: string, { name: machineName, status, acco/** 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 kept = typeof pool.keptForOthers === 'string' ? [pool.keptForOthers] : []+ /** A note, never a refusal: a teammate's work here runs in the machine owner's own account, whoever's grant an agent has. */+ const ownAccount = typeof pool.ownAccount === 'string' && pool.contributorId !== pool.projectOwnerId ? [pool.ownAccount] : []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.'] : []),@@ -638,10 +643,10 @@ async function probeMachine(machineId: string, { name: machineName, status, accoconst closed = Array.isArray(observed.closedHarnessIds) && observed.closedHarnessIds.includes(m.harnessId)return { ...memberProbe(m, fresh ? [...memberRefusals(running, closed, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),...kept, ...teammates(m.contributorId)] : [OFFLINE],- allowance, null, fresh && running === null, [...pushNote, ...usedUp(allowance)]), ...(fresh ? { load } : {}) }+ allowance, null, fresh && running === null, [...pushNote, ...usedUp(allowance), ...ownAccount]), ...(fresh ? { load } : {}) }}),...models.map(m => ({ ...newProbe(m, [...newReasons, ...(unready.engines[m.engine] ? [unready.engines[m.engine]!] : [])], quota(m.engine), fresh && quota(m.engine).known,- load, [...pushNote, ...(stuck ? [STALLED] : []), ...usedUp(quota(m.engine))]) }))]+ load, [...pushNote, ...(stuck ? [STALLED] : []), ...usedUp(quota(m.engine)), ...ownAccount]) }))]}// The account says this machine is off, so nothing there can run or be asked.if (account && status === 'offline') return [...members.map(m => memberProbe(m, [OFFLINE])), ...offline()]diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 5c225489b..8b9b812e1 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -4385,6 +4385,40 @@ class SuperTabController extends ChangeNotifier {return seq is int && known != null && known != seq;}+ /// The rows of [held] that [page], read whole, no longer has: from its+ /// oldest row on (from the start when it reached it) and before [before]+ /// (to the end when null). Each was deleted since it was read.+ static Set<String> _deletedFrom(+ Iterable<SuperTabMessage> held,+ Map<String, dynamic> page,+ int? before,+ ) {+ final rows = [+ for (final row in page['messages'] as List)+ SuperTabMessage.fromJson(superTabMap(row)),+ ];+ if (page['next'] != null && rows.isEmpty) return {};+ final ids = {for (final m in rows) m.id};+ final oldest = page['next'] == null+ ? null+ : rows.reduce((a, b) => superTabMessageOrder(a, b) <= 0 ? a : b);+ return {+ for (final m in held)+ if (!ids.contains(m.id) &&+ (before == null || m.sequence < before) &&+ (oldest == null || superTabMessageOrder(m, oldest) >= 0))+ m.id,+ };+ }++ /// Where a query's page ends: its `before`, or null for the latest page.+ static int? _beforeOf(String query) => int.tryParse(+ Uri.splitQueryString(+ query.startsWith('?') ? query.substring(1) : query,+ )['before'] ??+ '',+ );+static bool _sameMessages(List<SuperTabMessage>? shown,List<SuperTabMessage> next,@@ -4394,6 +4428,8 @@ class SuperTabController extends ChangeNotifier {final a = shown[i], b = next[i];if (a.id != b.id ||a.text != b.text ||+ a.editedAt != b.editedAt ||+ a.deletedAt != b.deletedAt ||a.deliveries.length != b.deliveries.length ||!_sameReactions(a.reactions, b.reactions)) {return false;@@ -4655,21 +4691,29 @@ class SuperTabController extends ChangeNotifier {// below them, and the rest waits for [showLatest].final skipped = query.startsWith('?after=') && answer['next'] != null;final keepPlace = skipped && _readingBack.contains(id);+ // A page read whole, latest or before a point: it holds every row+ // from its oldest on, so a held row it lacks was deleted (an edit or a+ // delete moves `reactionSeq` as a reaction does).+ ({Map<String, dynamic> page, int? before})? whole =+ older || query.startsWith('?after=')+ ? null+ : (page: answer, before: _beforeOf(query));if (!_disposed && skipped && !keepPlace) {answer = await request('GET', _messagesPath(id));+ whole = (page: answer, before: null);} else if (!_disposed && keepPlace) {// A changed reaction refreshes the page ending at the newest held:// the latest page, under rows read back, would leave a gap.- final shown = reacted- ? (await request(- 'GET',- '${_messagesPath(id)}?before=${tail! + 1}',- ))['messages']- as List- : const [];+ final page = reacted+ ? await request('GET', '${_messagesPath(id)}?before=${tail! + 1}')+ : null;+ if (page != null) whole = (page: page, before: tail! + 1);answer = {...answer,- 'messages': [...shown, ...answer['messages'] as List],+ 'messages': [+ ...page?['messages'] as List? ?? const [],+ ...answer['messages'] as List,+ ],};} else if (!_disposed &&reacted &&@@ -4682,10 +4726,12 @@ class SuperTabController extends ChangeNotifier {'GET','$_path/conversations/${Uri.encodeComponent(id)}/messages?before=${tail + 1}',);+ whole = (page: answer, before: tail + 1);} else if (!_disposed && reacted && arrived) {// New messages and a changed reaction at once: the rows already shown// need their counts too, so the latest page is read with the new ones.final page = await request('GET', _messagesPath(id));+ whole = (page: page, before: null);answer = {...answer,'messages': [@@ -4786,6 +4832,12 @@ class SuperTabController extends ChangeNotifier {combined.putIfAbsent(m.id, () => m);}}+ if (whole != null) {+ final gone = _deletedFrom(combined.values, whole.page, whole.before)+ ..removeAll(incoming.map((m) => m.id));+ combined.removeWhere((messageId, _) => gone.contains(messageId));+ _rows[id]?.removeWhere((messageId, _) => gone.contains(messageId));+ }final sorted = combined.values.toList()..sort(superTabMessageOrder);// Past the cap the oldest rows go, where earlier history continues;// never under a reader scrolled up, nor from an older page they askeddiff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex d45a05902..9e6e81c65 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -1572,6 +1572,11 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {String? contributor,) {if (c.snapshot?.hasTeammates != true) return null;+ // Its owner let teammates' work run in their own account (#2806): the Swarm's sentence says so to everyone.+ if (shared?['teamWork'] case {'ownAccount': final String own}+ when own.trim().isNotEmpty) {+ return own.trim();+ }final work = (team ?? shared)?['teamWork'];if (work is! Map || work['allowed'] != false) return null;final code = work['code'];@@ -1614,6 +1619,134 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {(removal is! Map || superTabMap(removal)['state'] != 'cleaning');}+ /// Whether the signed-in person may choose where teammates' work runs on [machineId] (backend+ /// `machine.ownAccountWork`, #2806): only on the Mac they added themselves, never on a Harness Team account's own+ /// entry (it names its Mac as its host) and never while the machine is being removed.+ bool _canChooseOwnAccount(String machineId) {+ if (!c.canWrite) return false;+ final pool = c.snapshot?.pool(machineId);+ return pool != null &&+ pool['contributorId'] == c.accountId &&+ pool['hostMachineId'] == null &&+ pool['removal'] == null;+ }++ /// The owner's choice on [machineId]: teammates' work may run in their own account. Absent until they choose: off.+ bool _ownAccountOn(String machineId) =>+ switch (c.snapshot?.pool(machineId)?['ownAccountChoice']) {+ {'allowed': true} => true,+ _ => false,+ };++ /// Turns teammates' work in the owner's own account on, after the one warning, or off at once. A refusal says its+ /// reason in one line: in the warning while it is open, otherwise below the screen.+ Future<void> _setOwnAccount(_MachineView v, {required bool allowed}) async {+ final id = v.id;+ if (!_canChooseOwnAccount(id)) return;+ Future<Map<String, dynamic>?> send() => c.command({+ 'type': 'machine.ownAccountWork',+ 'machineId': id,+ 'allowed': allowed,+ });+ if (!allowed) {+ void say(String line) => ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(+ key: const ValueKey('super-machine-own-account-refused'),+ content: Text(line, maxLines: 1, overflow: TextOverflow.ellipsis),+ ),+ );+ // The controller sends nothing while another action is being sent or waits to be confirmed: say so rather than+ // leave the owner thinking it is off (review of #2983).+ if (c.saving || c.hasPendingAction) {+ say('Another action is still being sent. Try again in a moment.');+ return;+ }+ final result = await send();+ if (!mounted || result != null) return;+ say(c.operationError ?? 'Could not switch it back. Try again.');+ return;+ }+ final name = superTabMachineName(v.name);+ var busy = false, attempted = false;+ await showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ child: StatefulBuilder(+ builder: (context, update) => ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ // This change's reply never came: Retry checks it, as Remove's does.+ final checking =+ c.pendingCommand?['type'] == 'machine.ownAccountWork' &&+ c.pendingCommand?['machineId'] == id;+ return PopScope(+ canPop: !busy,+ child: AlertDialog(+ key: const ValueKey('super-machine-own-account-confirm'),+ title: const Text("Let teammates' work run in your account?"),+ content: SizedBox(+ width: 400,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ "Teammates' agents will run as you on $name. They can read your files, your keychain and your "+ 'signed-in apps. Agents already running are not moved.',+ ),+ if (attempted && !busy && c.operationError != null) ...[+ const SizedBox(height: 12),+ Text(+ c.operationError!,+ key: const ValueKey(+ 'super-machine-own-account-reason',+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ],+ ],+ ),+ ),+ actions: [+ TextButton(+ autofocus: true,+ onPressed: busy ? null : () => Navigator.pop(context),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('super-machine-own-account-allow'),+ onPressed:+ busy || c.saving || (!checking && c.hasPendingAction)+ ? null+ : () async {+ update(() {+ busy = true;+ attempted = true;+ });+ final result = checking+ ? await c.retry()+ : await send();+ if (!context.mounted) return;+ if (result != null) {+ Navigator.pop(context);+ } else {+ update(() => busy = false);+ }+ },+ child: Text(checking ? 'Retry' : 'Let them run'),+ ),+ ],+ ),+ );+ },+ ),+ ),+ ),+ );+ }+Future<_RemovalPreview> _removalPreview(String machineId) async {final reply = await c.request('GET',@@ -1801,7 +1934,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {);}- /// A machine row's right-click: its details, and Remove from Swarm for whoever may.+ /// A machine row's right-click: its details, for its owner where teammates' work runs (#2806), and Remove from Swarm+ /// for whoever may.Future<void> _menu(_MachineView view, Offset at) async {// The menu's barrier takes the pointer from the row, so a second right-click would bring up the browser's menu// over this one. Off until it closes; dispose lets go too, for a screen that goes with the menu still up.@@ -1813,12 +1947,25 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {choice = await showContextMenuAt<String>(context: context,at: at,+ // Wide enough for "Run teammates' work only in the Team account" on one line.+ width: _canChooseOwnAccount(view.id) ? 340 : 240,children: (close) => [AppMenuItem(label: 'Details',leadingSlot: false,onPressed: () => close('details'),),+ if (_canChooseOwnAccount(view.id))+ AppMenuItem(+ key: const ValueKey('super-machine-menu-own-account'),+ label: _ownAccountOn(view.id)+ ? "Run teammates' work only in the Team account"+ : "Let teammates' work run in my account",+ leadingSlot: false,+ onPressed: () => close(+ _ownAccountOn(view.id) ? 'own-account-off' : 'own-account-on',+ ),+ ),if (_canRemove(view.id))AppMenuItem(key: const ValueKey('super-machine-menu-remove'),@@ -1837,6 +1984,9 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {}if (!mounted) return;if (choice == 'details') await _openDetails(view);+ if (choice == 'own-account-on' || choice == 'own-account-off') {+ await _setOwnAccount(view, allowed: choice == 'own-account-on');+ }if (choice == 'remove' &&_canRemove(view.id) &&_removeReason(view.id) == null) {diff --git a/desktop/lib/super_tabs/message_more_menu.dart b/desktop/lib/super_tabs/message_more_menu.dartindex f9af34a64..6f7563d2c 100644--- a/desktop/lib/super_tabs/message_more_menu.dart+++ b/desktop/lib/super_tabs/message_more_menu.dart@@ -14,17 +14,28 @@ typedef SuperTabMoreAction = ({List<({String label, VoidCallback onPressed})> choices,});+/// A change to the message itself, set apart under a rule at the menu's end:+/// the author's own Edit message and Delete message. [danger] draws it red.+typedef SuperTabMoreChange = ({+ String label,+ IconData icon,+ VoidCallback onPressed,+ bool danger,+});+/// The ⋯ of a message's hover bar: the choices that have no button of their/// own. Each closes the menu, then runs.class SuperTabMessageMoreMenu extends StatefulWidget {const SuperTabMessageMoreMenu({super.key,required this.actions,+ this.changes = const [],this.color,this.hoverColor,this.hoverFill,});final List<SuperTabMoreAction> actions;+ final List<SuperTabMoreChange> changes;/// The ⋯'s ink and lift, for a menu drawn on the picture viewer's veil/// ([AppIconButton] by default).@@ -86,6 +97,16 @@ class _SuperTabMessageMoreMenuState extends State<SuperTabMessageMoreMenu> {AppMenuItem(label: choice.label, onPressed: choice.onPressed),],),+ if (widget.actions.isNotEmpty && widget.changes.isNotEmpty)+ const AppMenuDivider(),+ for (final (index, change) in widget.changes.indexed)+ AppMenuItem(+ focusNode: widget.actions.isEmpty && index == 0 ? _first : null,+ label: change.label,+ icon: change.icon,+ danger: change.danger,+ onPressed: change.onPressed,+ ),],builder: (context, menu, _) => AppIconButton(icon: AppIcons.ellipsis,diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 012b6e777..e783c9765 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -10,6 +10,7 @@ import '../widgets/desktop_chrome.dart';import '../widgets/engine_identity.dart';import '../widgets/finger_target.dart';import 'attachment_chips.dart';+import 'composer_newline.dart';import 'identity.dart';import 'identity_card.dart';import 'machine_status.dart' show superTabAgo;@@ -98,6 +99,8 @@ class SuperTabMessageRow extends StatefulWidget {this.identity,this.onMarkUnread,this.onRemind,+ this.onEdit,+ this.onDelete,});final SuperTabMessage message;@@ -189,6 +192,19 @@ class SuperTabMessageRow extends StatefulWidget {/// The More menu's Remind me, with when. Null where it is not offered.final ValueChanged<SuperTabRemindIn>? onRemind;+ /// The More menu's Edit message: the text turns into a field here, and+ /// this sends what it says once changed. Null where it is not offered (it+ /// is only the author's, on their own plain message).+ final Future<void> Function(String text)? onEdit;++ /// The More menu's Delete message, which asks first. Null where it is not+ /// offered.+ final VoidCallback? onDelete;++ /// What a deleted message that keeps its thread reads as (backend+ /// messageEdits.ts `DELETED_TEXT`).+ static const deletedText = 'This message was deleted.';+// Routing notes share the message body column, including grouped messages.static const horizontalInset = 24.0;static const avatarSize = grid.AppDesktop.messageAvatarSize;@@ -271,14 +287,146 @@ class SuperTabMessageRow extends StatefulWidget {class _SuperTabMessageRowState extends State<SuperTabMessageRow> {final _focus = FocusNode(debugLabel: 'Swarm message actions');+ final _editFocus = FocusNode(debugLabel: 'Swarm message edit');bool _hovered = false, _focused = false;+ /// The text being edited, while Edit message is open; [_saving] while it+ /// is on its way.+ TextEditingController? _editing;+ bool _saving = false;+@overridevoid dispose() {_focus.dispose();+ _editFocus.dispose();+ _editing?.dispose();super.dispose();}+ void _startEdit() {+ _editing?.dispose();+ final text = widget.message.text;+ setState(+ () =>+ _editing = TextEditingController(text: text)+ ..selection = TextSelection.collapsed(offset: text.length),+ );+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _editFocus.requestFocus();+ });+ }++ void _stopEdit() {+ final editing = _editing;+ if (editing == null) return;+ setState(() {+ _editing = null;+ _saving = false;+ });+ // Disposed after the frame that drops its field.+ WidgetsBinding.instance.addPostFrameCallback((_) => editing.dispose());+ widget.onReturnToComposer();+ }++ /// Saves the field: unchanged text only closes it. A refusal is told by+ /// [SuperTabMessageRow.onEdit]'s caller; the row shows the text it has.+ Future<void> _saveEdit() async {+ final editing = _editing, save = widget.onEdit;+ if (editing == null || save == null || _saving || !_canSave) return;+ final text = editing.text.trim();+ if (text == widget.message.text) return _stopEdit();+ setState(() => _saving = true);+ await save(text);+ if (mounted && identical(_editing, editing)) _stopEdit();+ }++ /// Text, or files to stand without it (backend messageEdits.ts).+ bool get _canSave =>+ (_editing?.text.trim().isNotEmpty ?? false) ||+ widget.message.attachments.isNotEmpty;++ /// The in-place editor: the text in a field, Cancel and Save. Enter saves+ /// and Shift+Enter writes another line, as in the composer; Esc cancels.+ Widget _editor(BuildContext context, TextEditingController editing) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ DecoratedBox(+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ border: Border.all(color: DesktopChrome.rim),+ ),+ child: Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.controlGap),+ child: Focus(+ onKeyEvent: (_, event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape) {+ _stopEdit();+ return KeyEventResult.handled;+ }+ switch (composerEnter(+ event,+ focused: _editFocus.hasFocus,+ value: editing.value,+ )) {+ case ComposerEnter.ignore:+ return KeyEventResult.ignored;+ case ComposerEnter.newline:+ insertComposerNewline(editing, (_) => setState(() {}));+ return KeyEventResult.handled;+ case ComposerEnter.send:+ unawaited(_saveEdit());+ return KeyEventResult.handled;+ }+ },+ child: TextField(+ key: ValueKey('super-message-edit-${widget.message.id}'),+ controller: editing,+ focusNode: _editFocus,+ enabled: !_saving,+ minLines: 1,+ maxLines: 12,+ maxLength: kComposerMaxLength,+ keyboardType: TextInputType.multiline,+ style: SwarmType.composer(context),+ decoration: const InputDecoration(+ isCollapsed: true,+ constraints: BoxConstraints(),+ contentPadding: EdgeInsets.zero,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ filled: false,+ counterText: '',+ ),+ onChanged: (_) => setState(() {}),+ ),+ ),+ ),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ TextButton(+ onPressed: _saving ? null : _stopEdit,+ child: const Text('Cancel'),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ FilledButton(+ key: ValueKey('super-message-edit-save-${widget.message.id}'),+ onPressed: _saving || !_canSave+ ? null+ : () => unawaited(_saveEdit()),+ child: const Text('Save'),+ ),+ ],+ ),+ ],+ );+Future<void> _copy() async {await Clipboard.setData(ClipboardData(text: widget.message.text));if (!mounted) return;@@ -318,6 +466,24 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {),];+ /// The author's own changes, under the menu's rule.+ List<SuperTabMoreChange> get _changes => [+ if (widget.onEdit != null)+ (+ label: 'Edit message',+ icon: AppIcons.pencil,+ onPressed: _startEdit,+ danger: false,+ ),+ if (widget.onDelete case final delete?)+ (+ label: 'Delete message',+ icon: AppIcons.trash2,+ onPressed: delete,+ danger: true,+ ),+ ];+Future<void> _copyLink(SwarmMessageLink link) async {await Clipboard.setData(ClipboardData(text: link.url));if (!mounted) return;@@ -638,9 +804,27 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {style: DesktopChrome.metadata(),),),+ if (message.deleted)+ Text(+ SuperTabMessageRow.deletedText,+ key: ValueKey(+ 'super-message-deleted-${message.id}',+ ),+ style: SwarmType.body(+ context,+ color: DesktopChrome.muted,+ ).copyWith(fontStyle: FontStyle.italic),+ )+ else if (_editing case final editing?)+ ConstrainedBox(+ constraints: const BoxConstraints(+ maxWidth: 960,+ ),+ child: _editor(context, editing),+ )// A voice message's text is its words, shown// under its bubble from →A.- if (message.text.isNotEmpty && !voiceMessage)+ else if (message.text.isNotEmpty && !voiceMessage)Opacity(opacity: widget.dimmed ? 0.6 : 1,child: ConstrainedBox(@@ -658,7 +842,18 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {),),),- if (message.attachments.isNotEmpty)+ if (message.editedAt != null &&+ !message.deleted &&+ _editing == null)+ Text(+ '(edited)',+ key: ValueKey(+ 'super-message-edited-${message.id}',+ ),+ style: SwarmType.time(context),+ ),+ if (message.attachments.isNotEmpty &&+ !message.deleted)Opacity(opacity: widget.dimmed ? 0.6 : 1,child: Padding(@@ -675,21 +870,23 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {),),),- widget.card ??- SuperTabPullRequestLinks(message.text),- if (widget.linkTarget case final resolve?)- if (widget.onOpenLink case final open?)- SuperTabMessageLinkPreviews(- message.text,- resolve: resolve,- onOpen: open,- ),- SuperTabReactionBar(- message: message,- readerId: widget.readerId,- nameOf: widget.reactorName ?? (_, id) => id,- onReact: widget.onReact,- ),+ if (!message.deleted) ...[+ widget.card ??+ SuperTabPullRequestLinks(message.text),+ if (widget.linkTarget case final resolve?)+ if (widget.onOpenLink case final open?)+ SuperTabMessageLinkPreviews(+ message.text,+ resolve: resolve,+ onOpen: open,+ ),+ SuperTabReactionBar(+ message: message,+ readerId: widget.readerId,+ nameOf: widget.reactorName ?? (_, id) => id,+ onReact: widget.onReact,+ ),+ ],if ((widget.thread, widget.onOpenThread) case (final thread?,final open?,@@ -713,59 +910,64 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {],),),- Positioned(- top: 0,- right: 12,- child: Opacity(- opacity: active ? 1 : 0,- alwaysIncludeSemantics: true,- child: Material(- color: DesktopChrome.surface,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(- DesktopChrome.controlRadius,+ // A deleted message has nothing left to act on, and one+ // being edited has its own buttons.+ if (!message.deleted && _editing == null)+ Positioned(+ top: 0,+ right: 12,+ child: Opacity(+ opacity: active ? 1 : 0,+ alwaysIncludeSemantics: true,+ child: Material(+ color: DesktopChrome.surface,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(+ DesktopChrome.controlRadius,+ ),+ side: BorderSide(color: DesktopChrome.rim),),- side: BorderSide(color: DesktopChrome.rim),- ),- // A phone's actions are a finger's size each.- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (widget.onReact case final react?)- SuperTabReactionPicker(onReact: react),- if (widget.onReply != null)+ // A phone's actions are a finger's size each.+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (widget.onReact case final react?)+ SuperTabReactionPicker(onReact: react),+ if (widget.onReply != null)+ fingerTarget(+ enabled: phone,+ AppIconButton(+ icon: AppIcons.reply,+ tooltip: 'Reply',+ onPressed: widget.onReply,+ ),+ ),fingerTarget(enabled: phone,AppIconButton(- icon: AppIcons.reply,- tooltip: 'Reply',- onPressed: widget.onReply,+ icon: AppIcons.copy,+ tooltip: 'Copy message',+ onPressed: _copy,),),- fingerTarget(- enabled: phone,- AppIconButton(- icon: AppIcons.copy,- tooltip: 'Copy message',- onPressed: _copy,- ),- ),- if (_moreActions case final actions- when actions.isNotEmpty)- fingerTarget(- enabled: phone,- SuperTabMessageMoreMenu(- key: ValueKey(- 'super-message-more-${message.id}',+ if ((_moreActions, _changes)+ case (final actions, final changes)+ when actions.isNotEmpty || changes.isNotEmpty)+ fingerTarget(+ enabled: phone,+ SuperTabMessageMoreMenu(+ key: ValueKey(+ 'super-message-more-${message.id}',+ ),+ actions: actions,+ changes: changes,),- actions: actions,),- ),- ],+ ],+ ),),),),- ),if (taggedYou)Positioned(left: 0,diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 1c47a0498..502bc0f22 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -1446,6 +1446,8 @@ class SuperTabMessage {author = Map.unmodifiable(superTabMap(row['author'])),source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ editedAt = DateTime.tryParse(row['editedAt'] as String? ?? ''),+ deletedAt = DateTime.tryParse(row['deletedAt'] as String? ?? ''),attachments = _attachments(row['attachments']),reactions = List.unmodifiable(SuperTabReactionCount.listFromJson(row['reactions']),@@ -1494,6 +1496,15 @@ class SuperTabMessage {final Map<String, dynamic> author;final Map<String, dynamic> source;final DateTime? createdAt;++ /// When its author last changed its text, as the backend's `message.edit`+ /// records it; null for one never edited.+ final DateTime? editedAt;++ /// When its author deleted it. Only a message with replies is still read+ /// after that: its tombstone, which keeps its thread.+ final DateTime? deletedAt;+ bool get deleted => deletedAt != null;final List<SuperTabAttachment> attachments;final List<SuperTabReactionCount> reactions;diff --git a/desktop/lib/super_tabs/profile_actions.dart b/desktop/lib/super_tabs/profile_actions.dartindex 4632e2685..ca94db5ca 100644--- a/desktop/lib/super_tabs/profile_actions.dart+++ b/desktop/lib/super_tabs/profile_actions.dart@@ -4,9 +4,10 @@ import 'avatar_upload.dart';import 'controller.dart';import 'model.dart';-/// Status, avatars and reactions. Each is safe to send again, so each goes as-/// its own request rather than waiting behind a message being sent; the-/// answer is null when it went through, or what to tell the person.+/// Status, avatars and reactions, and edits and deletes of the reader's own+/// messages. Each goes as its own request rather than waiting behind a+/// message being sent (the first three are safe to send again); the answer+/// is null when it went through, or what to tell the person.extension SuperTabProfileActions on SuperTabController {Future<String?> setStatus(SuperTabPersonStatus? status) => _profile({'type': 'member.status',@@ -87,6 +88,62 @@ extension SuperTabProfileActions on SuperTabController {return failure;}+ /// Whether the reader may edit or delete [message]: their own plain post+ /// (no `source`: no task line, route or note the server wrote in their+ /// name), not deleted, in a conversation they may write in. The server+ /// decides (backend messageEdits.ts); this only offers the choices.+ bool canChange(SuperTabMessage message) {+ final group = snapshot?.conversation(message.conversationId);+ return canWrite &&+ group != null &&+ !group.archived &&+ !isEarlierBuddyChat(group) &&+ message.author['kind'] == 'person' &&+ message.authorId == accountId &&+ message.source.isEmpty &&+ !message.deleted;+ }++ /// Replaces [message]'s text with [text], trimmed. The same text sends+ /// nothing; empty text only goes for a message with files.+ Future<String?> editMessage(SuperTabMessage message, String text) async {+ final words = text.trim();+ if (words == message.text) return null;+ if (words.isEmpty && message.attachments.isEmpty) {+ return 'A message needs words or a file.';+ }+ return _changeMessage(message, {+ 'type': 'message.edit',+ 'conversationId': message.conversationId,+ 'messageId': message.id,+ 'text': words,+ });+ }++ /// Deletes [message]: one with replies stays as "This message was+ /// deleted.", any other goes.+ Future<String?> deleteMessage(SuperTabMessage message) =>+ _changeMessage(message, {+ 'type': 'message.delete',+ 'conversationId': message.conversationId,+ 'messageId': message.id,+ });++ /// Sends an edit or delete, then reads the page shown, and the open thread+ /// when it is in that conversation, so the change shows at once.+ Future<String?> _changeMessage(+ SuperTabMessage message,+ Map<String, dynamic> command,+ ) async {+ final failure = await _send(command);+ if (failure != null) return failure;+ await loadMessages(message.conversationId);+ if (openedThread?.conversationId == message.conversationId) {+ await loadThread();+ }+ return null;+ }+Future<String?> _profile(Map<String, dynamic> command, {bool viewer = false,diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 573cd5a78..128d8d969 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -3335,6 +3335,49 @@ class _SuperTabViewState extends State<SuperTabView>?.showSnackBar(SnackBar(content: Text(failure)));}+ /// More ▸ Edit message, saved: a refusal says why, and the row keeps the+ /// text it had.+ Future<void> _editMessage(SuperTabMessage message, String text) async {+ final failure = await c.editMessage(message, text);+ if (failure == null || !mounted) return;+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(failure)));+ }++ /// More ▸ Delete message: asks first, and only Delete sends it.+ Future<void> _deleteMessage(SuperTabMessage message) async {+ final confirmed = await showAppDialog<bool>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ conversationId: message.conversationId,+ child: AlertDialog(+ title: const Text('Delete message?'),+ content: Text("This can't be undone.", style: DesktopChrome.text()),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('super-message-delete-confirm'),+ style: FilledButton.styleFrom(+ backgroundColor: grid.AppPalette.dangerFill,+ ),+ onPressed: () => Navigator.pop(context, true),+ child: const Text('Delete'),+ ),+ ],+ ),+ ),+ );+ if (confirmed != true || !mounted) return;+ final failure = await c.deleteMessage(message);+ if (failure == null || !mounted) return;+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(failure)));+ }+SuperTabMessage _outgoingMessage(SuperTabOutgoing sent) {final id = sent.conversationId;final person = c.snapshot?.people@@ -3566,6 +3609,13 @@ class _SuperTabViewState extends State<SuperTabView>? null: () => unawaited(_markUnread(message)),onRemind: (when) => unawaited(_remind(message, when)),+ // Only the author's own plain message (the server decides).+ onEdit: c.canChange(message)+ ? (text) => _editMessage(message, text)+ : null,+ onDelete: c.canChange(message)+ ? () => unawaited(_deleteMessage(message))+ : null,// A message with a thread is answered there; one from before threads// keeps the inline reply.onReply: !writable || inThreaddiff --git a/desktop/test/super_tab_machine_own_account_test.dart b/desktop/test/super_tab_machine_own_account_test.dartnew file mode 100644index 000000000..54ceb2b4e--- /dev/null+++ b/desktop/test/super_tab_machine_own_account_test.dart@@ -0,0 +1,421 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/gestures.dart' show kSecondaryMouseButton;+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/machines.dart';++import 'support/capture.dart';+import 'support/super_tab_fixture.dart';++// Task #2813 (Scholes, 11-04): the Mac's owner lets teammates' work run in their own account on it, after one warning+// (backend `machine.ownAccountWork`, #2806). Only on the Mac its owner added, never on a Harness Team account's entry.+final shots = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];++const _allow = ValueKey('super-machine-own-account-allow');+const _item = ValueKey('super-machine-menu-own-account');++Map<String, dynamic> _machine(+ String id, {+ String contributor = 'owner',+ String? host,+ bool? allowed,+ String? ownAccountLine,+}) => {+ 'machineId': id,+ 'name': id == 'studio' ? "Gray's Mac" : id,+ 'contributorId': contributor,+ 'hostMachineId': ?host,+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},+ if (allowed != null)+ 'ownAccountChoice': {+ 'allowed': allowed,+ 'by': contributor,+ 'at': '2026-11-04T09:00:00Z',+ },+ if (ownAccountLine != null)+ 'teamWork': {'allowed': true, 'ownAccount': ownAccountLine},+};++List<Map<String, dynamic>> _ownAccountCommands(ConversationServer server) => [+ for (final p in server.posts)+ if ((p['command'] as Map?)?['type'] == 'machine.ownAccountWork')+ Map<String, dynamic>.from(p['command'] as Map),+];++Future<dynamic> _mount(+ WidgetTester tester,+ ConversationServer server, {+ Brightness brightness = Brightness.light,+}) async {+ // The design tokens follow the app's brightness, which main.dart sets from the theme.+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabMachines(controller: c, onAddAgent: (_) {}),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return c;+}++Future<void> _rightClick(WidgetTester tester, String id) async {+ await tester.tap(+ find.byKey(ValueKey('super-machine-$id')),+ buttons: kSecondaryMouseButton,+ );+ await tester.pumpAndSettle();+}++/// Whether [text]'s line is cut short where it is laid out: ellipsized, or narrower than the text needs.+bool _cut(WidgetTester tester, String text) {+ final paragraph = tester.renderObject<RenderParagraph>(find.text(text));+ final whole = TextPainter(+ text: paragraph.text,+ textDirection: TextDirection.ltr,+ textScaler: paragraph.textScaler,+ )..layout();+ return paragraph.didExceedMaxLines ||+ paragraph.size.width < whole.width - 0.5;+}++Future<void> _done(WidgetTester tester, dynamic c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+}++void main() {+ setUpAll(() => loadCaptureFonts(shots));++ group("teammates' work in the owner's own account", () {+ testWidgets('only the Mac its owner added offers it', (tester) async {+ final server = ConversationServer();+ server.state['machines'] = [+ _machine('studio'),+ _machine('pro', contributor: 'scholes'),+ // A Harness Team account's own entry, shown on its own row while its Mac is not in this Swarm.+ _machine('studio-team', host: 'gray-mac'),+ ];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ expect(+ find.text("Let teammates' work run in my account"),+ findsOneWidget,+ );+ expect(+ _cut(tester, "Let teammates' work run in my account"),+ isFalse,+ reason: 'the item reads whole, not cut short',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ for (final other in ['pro', 'studio-team']) {+ await _rightClick(tester, other);+ expect(find.text('Details'), findsOneWidget, reason: other);+ expect(find.byKey(_item), findsNothing, reason: other);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ }+ await _done(tester, c);+ });++ testWidgets('it warns once, and Cancel, the default, sends nothing', (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['machines'] = [_machine('studio')];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ expect(+ find.text("Let teammates' work run in your account?"),+ findsOneWidget,+ );+ expect(+ find.text(+ "Teammates' agents will run as you on Gray's Mac. They can read your files, your keychain and your "+ 'signed-in apps. Agents already running are not moved.',+ ),+ findsOneWidget,+ );+ final cancel = find.widgetWithText(TextButton, 'Cancel');+ expect(tester.widget<TextButton>(cancel).autofocus, isTrue);+ await tester.tap(cancel);+ await tester.pumpAndSettle();+ expect(find.byKey(_allow), findsNothing);+ expect(_ownAccountCommands(server), isEmpty);+ await _done(tester, c);+ });++ testWidgets('Let them run sends the choice once', (tester) async {+ final server = ConversationServer();+ server.state['machines'] = [_machine('studio')];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(_allow));+ await tester.pumpAndSettle();+ expect(_ownAccountCommands(server), [+ {+ 'type': 'machine.ownAccountWork',+ 'machineId': 'studio',+ 'allowed': true,+ },+ ]);+ expect(find.byKey(_allow), findsNothing);+ await _done(tester, c);+ });++ testWidgets(+ 'once on, it reads Team account only and switches back with no question',+ (tester) async {+ final server = ConversationServer();+ server.state['machines'] = [_machine('studio', allowed: true)];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ expect(+ find.text("Run teammates' work only in the Team account"),+ findsOneWidget,+ );+ expect(+ find.text("Let teammates' work run in my account"),+ findsNothing,+ );+ expect(+ _cut(tester, "Run teammates' work only in the Team account"),+ isFalse,+ reason: 'the item reads whole, not cut short',+ );+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ expect(+ find.text("Let teammates' work run in your account?"),+ findsNothing,+ );+ expect(_ownAccountCommands(server), [+ {+ 'type': 'machine.ownAccountWork',+ 'machineId': 'studio',+ 'allowed': false,+ },+ ]);+ await _done(tester, c);+ },+ );++ testWidgets('a refusal says its reason in one line', (tester) async {+ final server = ConversationServer()+ ..refuse = {+ 'code': 'OWNER_REQUIRED',+ 'message':+ "Only the machine's owner can change where teammates' work runs.",+ }+ ..refuseStatus = 403;+ server.state['machines'] = [_machine('studio')];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(_allow));+ await tester.pumpAndSettle();+ final reason = find.byKey(+ const ValueKey('super-machine-own-account-reason'),+ );+ expect(reason, findsOneWidget);+ expect(+ tester.widget<Text>(reason).data,+ "Only the machine's owner can change where teammates' work runs.",+ );+ expect(tester.widget<Text>(reason).maxLines, 1);+ // The warning stays up with its reason; nothing changed.+ expect(find.byKey(_allow), findsOneWidget);+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ await _done(tester, c);+ });++ testWidgets('a refused switch back says its reason in one line', (+ tester,+ ) async {+ final server = ConversationServer()+ ..refuse = {+ 'code': 'MACHINE_REMOVED',+ 'message': 'This machine was removed from the Swarm.',+ }+ ..refuseStatus = 404;+ server.state['machines'] = [_machine('studio', allowed: true)];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ final bar = find.byKey(+ const ValueKey('super-machine-own-account-refused'),+ );+ expect(bar, findsOneWidget);+ expect(+ find.descendant(+ of: bar,+ matching: find.text('This machine was removed from the Swarm.'),+ ),+ findsOneWidget,+ );+ await _done(tester, c);+ });++ // Review of #2983 (Avocet4): while another action is still being sent, the controller sends nothing; switching back+ // must say so, never leave the owner thinking it is off.+ testWidgets('switching back while another action is sending says so', (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['machines'] = [_machine('studio', allowed: true)];+ final c = await _mount(tester, server);+ final hold = Completer<void>();+ server.holdCommands = hold;+ final other = c.command({+ 'type': 'machine.pause',+ 'machineId': 'studio',+ 'paused': true,+ });+ await tester.pump();+ await _rightClick(tester, 'studio');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ expect(_ownAccountCommands(server), isEmpty);+ final bar = find.byKey(+ const ValueKey('super-machine-own-account-refused'),+ );+ expect(bar, findsOneWidget);+ expect(+ find.descendant(+ of: bar,+ matching: find.text(+ 'Another action is still being sent. Try again in a moment.',+ ),+ ),+ findsOneWidget,+ );+ hold.complete();+ await other;+ await tester.pumpAndSettle();+ await _done(tester, c);+ });++ // Review of #2983 (Avocet4): a reply that never came says "Retry"; the warning offers it.+ testWidgets('a lost reply offers Retry in the warning, which confirms it', (+ tester,+ ) async {+ final server = ConversationServer()..loseReply = true;+ server.state['machines'] = [_machine('studio')];+ final c = await _mount(tester, server);+ await _rightClick(tester, 'studio');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(_allow));+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-machine-own-account-reason')),+ findsOneWidget,+ );+ final retry = find.byKey(_allow);+ expect(+ find.descendant(of: retry, matching: find.text('Retry')),+ findsOneWidget,+ );+ expect(tester.widget<FilledButton>(retry).onPressed, isNotNull);+ await tester.tap(retry);+ await tester.pumpAndSettle();+ expect(find.byKey(_allow), findsNothing);+ expect(c.hasPendingAction, isFalse);+ // The lost send and its Retry are the same command, sent again under its operation id.+ expect(_ownAccountCommands(server), isNotEmpty);+ expect(+ _ownAccountCommands(server),+ everyElement({+ 'type': 'machine.ownAccountWork',+ 'machineId': 'studio',+ 'allowed': true,+ }),+ );+ await _done(tester, c);+ });++ testWidgets("the row says it runs in the owner's own account", (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['people'] = [+ {+ 'id': 'owner',+ 'email': '[email protected]',+ 'role': 'owner',+ 'name': 'Gray',+ },+ {+ 'id': 'scholes',+ 'email': '[email protected]',+ 'role': 'member',+ 'name': 'Scholes',+ },+ ];+ server.state['machines'] = [+ _machine(+ 'studio',+ allowed: true,+ ownAccountLine:+ "Gray's Mac runs teammates' work in Gray's own account.",+ ),+ ];+ final c = await _mount(tester, server);+ expect(+ find.textContaining("runs teammates' work in Gray's own account"),+ findsOneWidget,+ );+ await _done(tester, c);+ });++ testWidgets('screenshots for Scholes', (tester) async {+ await tester.binding.setSurfaceSize(const Size(900, 560));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ for (final (brightness, name) in [+ (Brightness.light, 'light'),+ (Brightness.dark, 'dark'),+ ]) {+ final server = ConversationServer();+ server.state['machines'] = [_machine('studio')];+ final c = await _mount(tester, server, brightness: brightness);+ await _rightClick(tester, 'studio');+ await captureWindow(tester, shots, 'own-account-menu-$name');+ await tester.tap(find.byKey(_item));+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'own-account-confirm-$name');+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ await _done(tester, c);+ final on = ConversationServer();+ on.state['machines'] = [_machine('studio', allowed: true)];+ final d = await _mount(tester, on, brightness: brightness);+ await _rightClick(tester, 'studio');+ await captureWindow(tester, shots, 'own-account-menu-on-$name');+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ await _done(tester, d);+ }+ }, skip: shots == null);+ });+}diff --git a/desktop/test/super_tab_message_edit_shots_test.dart b/desktop/test/super_tab_message_edit_shots_test.dartnew file mode 100644index 000000000..3b4a5f5ca--- /dev/null+++ b/desktop/test/super_tab_message_edit_shots_test.dart@@ -0,0 +1,137 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/gestures.dart';+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/view.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_MESSAGE_EDIT_SHOTS'];++/// Edit and delete your own message (task #2746): the More menu with Edit+/// message and Delete message, the in-place editor, an edited message and a+/// deleted one that keeps its thread, in both appearances.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final server = ConversationServer()..threads = true;+ server+ ..append('Kicking off the release notes for 1.4.')+ ..append('Draft is in the doc, please have a look.')+ ..append('Looks good to me.')+ ..append('Shipping the notes at 15:00.');+ server.messages[2]+ ..['thread'] = 'message-1'+ ..['author'] = {'kind': 'person', 'id': 'huy', 'name': 'Huy'};+ server.messages[3]['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Avocet',+ };+ server.editMessage('message-2', 'Draft is in the doc, have a look.');+ server.deleteMessage('message-1');+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(900, 560));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('This message was deleted.'), findsOneWidget);+ expect(find.text('(edited)'), findsOneWidget);++ Future<void> shot(String name) async {+ if (shots == null) return;+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/message-edit-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ await shot('rows');++ final row = find.byKey(const ValueKey('super-message-message-2'));+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(row));+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: row,+ matching: find.byKey(const ValueKey('super-message-more-message-2')),+ ),+ );+ await tester.pumpAndSettle();+ await mouse.moveTo(tester.getCenter(find.text('Edit message')));+ await tester.pumpAndSettle();+ await shot('menu');++ await tester.tap(find.text('Edit message'));+ await tester.pumpAndSettle();+ await mouse.removePointer();+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-message-edit-message-2')),+ findsOneWidget,+ );+ await shot('editor');++ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ final mouse2 = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse2.addPointer(location: Offset.zero);+ await mouse2.moveTo(tester.getCenter(row));+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: row,+ matching: find.byKey(const ValueKey('super-message-more-message-2')),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.text('Delete message'));+ await tester.pumpAndSettle();+ await mouse2.removePointer();+ await tester.pumpAndSettle();+ expect(find.text('Delete message?'), findsOneWidget);+ await shot('confirm');+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ });+ }+}diff --git a/desktop/test/super_tab_message_edit_test.dart b/desktop/test/super_tab_message_edit_test.dartnew file mode 100644index 000000000..7cb430789--- /dev/null+++ b/desktop/test/super_tab_message_edit_test.dart@@ -0,0 +1,372 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/widgets/app_menu.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// Edit and delete your own message (task #2746, plan Task 2): the More menu+/// of the reader's own plain message offers Edit message and Delete message;+/// an edit shows "(edited)", a delete with replies leaves "This message was+/// deleted." and one without replies goes.+void main() {+ late SuperTabController c;++ Future<void> show(+ WidgetTester tester,+ ConversationServer server, {+ String account = 'owner',+ }) async {+ await tester.binding.setSurfaceSize(const Size(1200, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ c = server.controller(account: account);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ }++ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));+ Finder more(String id) => find.descendant(+ of: row(id),+ matching: find.byKey(ValueKey('super-message-more-$id')),+ );+ Finder field(String id) => find.byKey(ValueKey('super-message-edit-$id'));++ // One mouse for a whole test, moved from row to row.+ TestGesture? mouse;+ setUp(() => mouse = null);++ Future<void> hover(WidgetTester tester, String id) async {+ if (mouse == null) {+ final added = mouse = await tester.createGesture(+ kind: PointerDeviceKind.mouse,+ );+ await added.addPointer(location: Offset.zero);+ addTearDown(added.removePointer);+ }+ await mouse!.moveTo(tester.getCenter(row(id)));+ await tester.pumpAndSettle();+ }++ Future<void> openMore(WidgetTester tester, String id) async {+ await hover(tester, id);+ await tester.tap(more(id));+ await tester.pumpAndSettle();+ }++ Future<void> choose(WidgetTester tester, String id, String label) async {+ await openMore(tester, id);+ await tester.tap(find.text(label));+ await tester.pumpAndSettle();+ }++ List<Map<String, dynamic>> changes(ConversationServer server) => [+ for (final post in server.posts)+ if (const {+ 'message.edit',+ 'message.delete',+ }.contains((post['command'] as Map)['type']))+ Map<String, dynamic>.from(post['command'] as Map),+ ];++ /// The reader's own message, an agent's and another person's.+ ConversationServer three() {+ final server = ConversationServer()+ ..append('My own words')+ ..append('An agent update', agent: true)+ ..append('Someone else');+ server.messages[2]['author'] = {+ 'kind': 'person',+ 'id': 'huy',+ 'name': 'Huy',+ };+ return server;+ }++ testWidgets('the More menu of your own message offers Edit message and '+ 'Delete message after a divider', (tester) async {+ await show(tester, three());+ await openMore(tester, 'message-1');+ expect(find.text('Edit message'), findsOneWidget);+ expect(find.text('Delete message'), findsOneWidget);+ expect(find.byType(AppMenuDivider), findsOneWidget);+ final rule = tester.getTopLeft(find.byType(AppMenuDivider)).dy;+ expect(rule, greaterThan(tester.getTopLeft(find.text('Remind me')).dy));+ expect(rule, lessThan(tester.getTopLeft(find.text('Edit message')).dy));+ expect(+ tester.getTopLeft(find.text('Edit message')).dy,+ lessThan(tester.getTopLeft(find.text('Delete message')).dy),+ );+ });++ testWidgets('an agent’s and another person’s message offer neither', (+ tester,+ ) async {+ await show(tester, three());+ for (final id in ['message-2', 'message-3']) {+ await openMore(tester, id);+ expect(find.text('Mark unread'), findsOneWidget, reason: id);+ expect(find.text('Edit message'), findsNothing, reason: id);+ expect(find.text('Delete message'), findsNothing, reason: id);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ }+ });++ testWidgets('a reader who may not write here is offered neither', (+ tester,+ ) async {+ final server = three();+ (server.state['conversations'] as List).cast<Map>().first['archived'] =+ true;+ await show(tester, server);+ await openMore(tester, 'message-1');+ expect(find.text('Copy link to message'), findsOneWidget);+ expect(find.text('Edit message'), findsNothing);+ });++ testWidgets('Edit message turns the text into a field; Enter saves the '+ 'new text, which shows with (edited)', (tester) async {+ final server = three();+ await show(tester, server);+ await choose(tester, 'message-1', 'Edit message');+ expect(field('message-1'), findsOneWidget);+ expect(+ tester.widget<TextField>(field('message-1')).controller!.text,+ 'My own words',+ );+ expect(find.text('Save'), findsOneWidget);+ expect(find.text('Cancel'), findsOneWidget);++ await tester.enterText(field('message-1'), ' My better words ');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();++ expect(changes(server), [+ {+ 'type': 'message.edit',+ 'conversationId': 'lead',+ 'messageId': 'message-1',+ 'text': 'My better words',+ },+ ]);+ expect(field('message-1'), findsNothing);+ // Read again at once: the new text, marked edited.+ expect(+ find.descendant(of: row('message-1'), matching: find.text('(edited)')),+ findsOneWidget,+ );+ expect(c.messages('lead').first.text, 'My better words');+ expect(c.messages('lead').first.editedAt, isNotNull);+ });++ testWidgets('Shift+Enter writes another line in the field', (tester) async {+ final server = three();+ await show(tester, server);+ await choose(tester, 'message-1', 'Edit message');+ await tester.enterText(field('message-1'), 'First');+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);+ await tester.pumpAndSettle();+ expect(changes(server), isEmpty);+ expect(+ tester.widget<TextField>(field('message-1')).controller!.text,+ 'First\n',+ );+ });++ testWidgets('Esc and Cancel close the field and send nothing', (+ tester,+ ) async {+ final server = three();+ await show(tester, server);+ await choose(tester, 'message-1', 'Edit message');+ await tester.enterText(field('message-1'), 'Changed my mind');+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(field('message-1'), findsNothing);+ expect(find.text('My own words'), findsOneWidget);++ await choose(tester, 'message-1', 'Edit message');+ await tester.enterText(field('message-1'), 'Changed my mind');+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(field('message-1'), findsNothing);+ expect(changes(server), isEmpty);+ expect(find.text('(edited)'), findsNothing);+ });++ testWidgets('saving the same text just closes the field', (tester) async {+ final server = three();+ await show(tester, server);+ await choose(tester, 'message-1', 'Edit message');+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ expect(field('message-1'), findsNothing);+ expect(changes(server), isEmpty);+ });++ testWidgets('a refused edit says why and keeps the old text', (tester) async {+ final server = three();+ await show(tester, server);+ await choose(tester, 'message-1', 'Edit message');+ server.refuse = {+ 'code': 'FORBIDDEN',+ 'message': 'Only its author can change this message.',+ };+ await tester.enterText(field('message-1'), 'New words');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(find.text('Only its author can change this message.'), findsOne);+ expect(find.text('My own words'), findsOneWidget);+ expect(find.text('(edited)'), findsNothing);+ });++ testWidgets('Delete message asks first and sends only on Delete', (+ tester,+ ) async {+ final server = three();+ await show(tester, server);+ await choose(tester, 'message-1', 'Delete message');+ expect(find.text('Delete message?'), findsOneWidget);+ expect(find.text("This can't be undone."), findsOneWidget);+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ expect(find.text('Delete message?'), findsNothing);+ expect(changes(server), isEmpty);+ expect(find.text('My own words'), findsOneWidget);++ await choose(tester, 'message-1', 'Delete message');+ await tester.tap(find.widgetWithText(FilledButton, 'Delete'));+ await tester.pumpAndSettle();+ expect(changes(server), [+ {+ 'type': 'message.delete',+ 'conversationId': 'lead',+ 'messageId': 'message-1',+ },+ ]);+ // No replies: it goes at once.+ expect(row('message-1'), findsNothing);+ expect(find.text('My own words'), findsNothing);+ });++ testWidgets('a message edited elsewhere shows (edited) after its text', (+ tester,+ ) async {+ final server = three();+ server.messages[0]['editedAt'] = '2026-10-18T00:05:00Z';+ await show(tester, server);+ final mark = find.descendant(+ of: row('message-1'),+ matching: find.text('(edited)'),+ );+ expect(mark, findsOneWidget);+ expect(+ tester.getTopLeft(mark).dy,+ greaterThanOrEqualTo(tester.getTopLeft(find.text('My own words')).dy),+ );+ expect(find.text('(edited)'), findsOneWidget);+ });++ testWidgets('a deleted message with replies shows the deleted line, no '+ 'actions, and keeps its thread line', (tester) async {+ final server = ConversationServer()..threads = true;+ server.append('Root to delete');+ server.append('A reply');+ server.messages[1]['thread'] = 'message-1';+ server.messages[1]['author'] = {+ 'kind': 'person',+ 'id': 'huy',+ 'name': 'Huy',+ };+ server.deleteMessage('message-1');+ await show(tester, server);+ final line = find.descendant(+ of: row('message-1'),+ matching: find.text('This message was deleted.'),+ );+ expect(line, findsOneWidget);+ expect(tester.widget<Text>(line).style?.fontStyle, FontStyle.italic);+ await hover(tester, 'message-1');+ expect(more('message-1'), findsNothing);+ expect(+ find.descendant(+ of: row('message-1'),+ matching: find.byTooltip('Add reaction'),+ ),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('super-thread-line-message-1')),+ findsOneWidget,+ );+ });++ test('a page read again drops a message deleted elsewhere and takes an '+ 'edited text', () async {+ final server = ConversationServer()+ ..append('One')+ ..append('Two')+ ..append('Three');+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ expect(+ [for (final m in c.messages('lead')) m.text],+ ['One', 'Two', 'Three'],+ );++ server.deleteMessage('message-2');+ server.editMessage('message-3', 'Three, edited');+ await c.refresh();+ expect(+ [for (final m in c.messages('lead')) m.text],+ ['One', 'Three, edited'],+ );+ expect(c.messages('lead').last.editedAt, isNotNull);++ // The newest goes too, and then the only one left.+ server.deleteMessage('message-3');+ await c.refresh();+ expect([for (final m in c.messages('lead')) m.id], ['message-1']);+ server.deleteMessage('message-1');+ await c.refresh();+ expect(c.messages('lead'), isEmpty);+ });++ test('a tombstone read again replaces the message it was', () async {+ final server = ConversationServer()..threads = true;+ server.append('Root');+ server.append('Reply');+ server.messages[1]['thread'] = 'message-1';+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ server.deleteMessage('message-1');+ await c.refresh();+ final root = c.messages('lead').firstWhere((m) => m.id == 'message-1');+ expect(root.deletedAt, isNotNull);+ expect(root.deleted, isTrue);+ expect(root.text, 'This message was deleted.');+ });+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex a62dba0fe..a718ca503 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -1010,6 +1010,48 @@ class ConversationServer {return true;}+ /// An edit as the backend keeps it (messageEdits.ts): the new text, when it+ /// changed, and the group's `reactionSeq` moved. False for the same text.+ bool editMessage(String messageId, String text) {+ final message = messages.firstWhere((m) => m['id'] == messageId);+ if (message['text'] == text) return false;+ message+ ..['text'] = text+ ..['editedAt'] = '2026-10-18T00:05:00Z';+ _messageChanged(message['conversationId'] as String);+ return true;+ }++ /// A delete as the backend keeps it (messageEdits.ts): a message with+ /// replies stays as its tombstone, any other goes from every page. Whether+ /// it was kept.+ bool deleteMessage(String messageId) {+ final message = messages.firstWhere((m) => m['id'] == messageId);+ final kept = messages.any(+ (m) => m['thread'] == messageId && m['id'] != messageId,+ );+ if (kept) {+ message+ ..['text'] = 'This message was deleted.'+ ..['deletedAt'] = '2026-10-18T00:06:00Z'+ ..['attachments'] = <dynamic>[]+ ..['mentions'] = <dynamic>[]+ ..['reactions'] = <dynamic>[];+ } else {+ messages.remove(message);+ }+ _messageChanged(message['conversationId'] as String);+ return kept;+ }++ void _messageChanged(String conversationId) {+ final group = (state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == conversationId);+ group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;+ revision++;+ }+/// What the backend does with a file sent to its upload route.Future<Map<String, dynamic>> upload({required String tabId,@@ -1284,6 +1326,14 @@ class ConversationServer {_profile(command, reader ?? 'owner');} else if (command['type'] == 'message.react') {output['changed'] = _react(command, reader ?? 'owner');+ } else if (command['type'] == 'message.edit') {+ output['changed'] = editMessage(+ command['messageId'] as String,+ command['text'] as String,+ );+ } else if (command['type'] == 'message.delete') {+ output['changed'] = true;+ output['kept'] = deleteMessage(command['messageId'] as String);} else if (command['type'] == 'decision.answer') {final id = command['decisionId'] as String;if (command['delegate'] == true) {diff --git a/docs/plans/2026-11-04-cpu-by-thread-plan.md b/docs/plans/2026-11-04-cpu-by-thread-plan.mdnew file mode 100644index 000000000..1ba0e8f66--- /dev/null+++ b/docs/plans/2026-11-04-cpu-by-thread-plan.md@@ -0,0 +1,101 @@+# CPU by thread: name where the backend's CPU goes (Watch Production gap 2) Implementation Plan++> Way of working: written by the Engineer from the task's brief (task #2801), implemented by the same Engineer task by+> task, each failing test committed before its code. One independent review on the pull request.++**Goal:** Every minute, each backend process logs where its CPU went, by thread: the main thread (with its GC pauses and+reply JSON), the Prisma query engine, the libuv pool (zlib, fs, crypto) and V8's helper threads (concurrent GC, JIT),+so ≥ 80% of process CPU has a name. Ken's Watch Production numbers (#2773, 11-04 15:35): 43.9 s of process CPU per+pod-minute, 15.3 s named by kind, ~40% off the main thread with nothing splitting it.++**Architecture:** One always-on module, `backend/src/lib/cpuStats.ts`, started in `server.ts` beside the other+per-minute logs. Once a minute it reads `/proc/self/task/*/stat` (one small file per thread, ~30 threads) and groups+each thread's CPU by the thread's name. Linux names them for us (measured on Node 22.23, Prisma 5.22, arm64 Ubuntu):+the main thread's tid is the pid; `tokio-runtime-w` and `opentelemetry-e` are the Prisma engine's (library engine,+in-process); `libuv-worker` is the libuv pool; `node` (not the main tid) and `DelayedTaskSche` are V8's platform workers.+On the main thread it adds two counters: GC pause time from a `gc` PerformanceObserver, and reply JSON time from a+timed `JSON.stringify` reply serializer. Nothing is done per request beyond two `performance.now()` calls and three+additions. Off Linux (a developer's Mac) the per-thread part says `unavailable` and the rest still logs.++**Tech Stack:** Node 22 (`node:fs`, `node:perf_hooks`), Fastify 5 `setReplySerializer`, Vitest.++**Spec:** task #2801's brief (no separate design doc).++## Global Constraints++- Always on; no env switch (Ken: optimizations ship on). Logs carry thread names and numbers only, no user data.+- No per-request work beyond counters. The `/proc` read runs once a minute, synchronously (~30 tiny reads, well under a+ millisecond).+- Never silent: a route that declares a response schema would lose that schema's serializer to the timed one, so+ registration refuses it at startup (no route has one today).+- Backend only; Swarm code stays out of `cli/src/core`. Red-first tests.++## Design++- growth: N/A because nothing is stored: one log line a minute per pod, kept by the log store's own retention.+- concurrency: N/A because per-process counters on one thread, no shared state.+- read cost: one `/proc` read per thread per minute; per request, two clock reads.+- scale: 10x pods → 10x lines a minute, as the other per-minute logs; 10x threads (a bigger node) → 10x tiny reads a+ minute. The first warning is `exitedMs` growing (threads that came and went between reads, uncounted by name).+- compatibility: a new log message (`cpu by thread`); no existing log changes.+- migration + rollback: none; revert the commit.+- audience: logs only, read by the team through the log store.+- identity: N/A because no user identity is involved.+- failure: a `/proc` read that fails logs `threads: unavailable` with the reason, every minute, instead of dropping it.+- platforms: Linux pods get the full split; macOS/Windows dev runs get process, main-thread busy, GC and reply JSON.++## Review Focus++- Thread-name buckets match what the pods run (Node 22 bookworm image, Prisma 5.22 library engine).+- The reply serializer gives the same bytes as Fastify's default for every route without a response schema.+- The overhead figure: per-request cost of the serializer wrapper and per-minute cost of the read.++## Task 1: Read and bucket thread CPU++**Files:** `backend/src/lib/cpuStats.ts`, `backend/src/lib/cpuStats.test.ts`++**Interfaces:**+- `parseThreadStat(text: string): { name: string; cpuMs: number }` — comm between the first `(` and the last `)`,+ utime + stime (fields 14 and 15) at USER_HZ 100.+- `threadBucket(name: string, tid: number, pid: number): 'main' | 'prismaEngine' | 'libuvPool' | 'v8Workers' | 'other'`+- `readThreads(root?: string): Array<{ tid: number; name: string; cpuMs: number }>` (throws when unreadable)++- [ ] Failing test: a stat line whose comm holds spaces and `)` parses; buckets for each measured name and an unknown one.+- [ ] Failing test (Linux only, skipped elsewhere): the real `/proc/self/task` has this process's main thread, with CPU.+- [ ] Code that passes them.++## Task 2: The per-minute window and its log++**Files:** `backend/src/lib/cpuStats.ts`, `backend/src/lib/cpuStats.test.ts`++**Interfaces:**+- `startCpuStats(options?: { everyMs?; log?; threads?; cpuUsage?; now?; observeGc? }): CpuStats` with+ `{ replyJson(ms: number, bytes: number): void; flush(): void; stop(): void }`.+- Log `cpu by thread`: `windowMs, processCpuMs, mainMs, prismaEngineMs, libuvPoolMs, v8WorkersMs, otherThreadsMs,+ exitedMs, namedPct, gc { pauseMs, count, majorMs }, replyJson { ms, count, kb }, loopBusyPct, otherNames`.++- [ ] Failing test: two fake reads a window apart give each bucket's delta; a thread new in the window counts in full;+ a thread gone counts in `exitedMs` (process CPU minus the threads read); `namedPct` is the four named buckets over+ process CPU.+- [ ] Failing test: GC entries sum into `gc`; reply JSON sums into `replyJson`; counters reset each window.+- [ ] Failing test: an unreadable `/proc` logs `threads: 'unavailable'` with its reason, every window.+- [ ] Code that passes them.++## Task 3: Time reply JSON and start it in the server++**Files:** `backend/src/lib/cpuStats.ts`, `backend/src/lib/cpuStats.test.ts`, `backend/src/server.ts`++**Interfaces:** `registerReplyJsonTiming(app: FastifyInstance, stats: Pick<CpuStats, 'replyJson'>): void`++- [ ] Failing test: a Fastify route returning an object replies the same bytes as `JSON.stringify`, and the stats get+ one reply with its size; a route declaring a response schema makes registration fail at startup.+- [ ] Code that passes it; `server.ts` starts the stats beside the other per-minute logs and stops them on close.++## Task 4: Measure on a seeded load, rank the top three++**Files:** `backend/integration/bench/routeCost.ts`++- [ ] Run the route-cost bench on Linux (a local Lima VM, Node 22) with `cpu by thread` every 15 s; record coverage+ (`namedPct`) and each bucket.+- [ ] Overhead: per-call cost of the timed serializer and per-read cost of `/proc`, against process CPU per minute.+- [ ] PR body: the top three buckets and the change that would cut each.diff --git a/docs/plans/2026-11-04-edit-delete-own-message-plan.md b/docs/plans/2026-11-04-edit-delete-own-message-plan.mdnew file mode 100644index 000000000..2c4c94108--- /dev/null+++ b/docs/plans/2026-11-04-edit-delete-own-message-plan.md@@ -0,0 +1,143 @@+# Edit and delete your own message Implementation Plan++> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,+> Engineer). Tasks 2 and 3 share no files with each other and run in parallel once Task 1's contract is pushed. Two+> independent security reviews on the pull request (it changes who may change a stored message).++**Goal:** A person can edit and delete their own chat messages from the message's More menu on Desktop, web and phone, as+in Slack: an edited message shows "(edited)"; a deleted one shows "This message was deleted." when it has replies and+disappears otherwise (task #2746, mia via anh Dee's notifications thread, 2026-11-04).++**Architecture:** Two new Swarm commands, `message.edit` and `message.delete`, follow `message.react`: the store reads the+named row in the command's transaction (`messageChangeTarget`), the pure command (`messageEdits.ts`) decides who may change+it and bumps the conversation's `reactionSeq`, and the store writes the row. Every reader already re-reads the shown page+when `reactionSeq` moves (that is how reactions reach them), so older apps pick up the new text and the removed row with no+change; new apps also draw "(edited)" and the deleted line. Desktop and web share `desktop/lib/super_tabs`; the phone is+`mobile/lib/swarm`.++**Tech Stack:** TypeScript, Prisma 5 on MongoDB, Vitest (unit + mongodb-memory-server integration); Flutter (Desktop, web,+phone) with widget tests.++**Spec:** task #2746's brief; the ASCII mockup posted in the task thread (2026-11-04 08:08 UTC); River's go (same thread):+say what agents see, and test that a Buddy cannot change its owner's messages.++## Global Constraints++- Only the author changes a message: a person (`actor.kind === 'person'`), whose id is the row's `author.id` with+ `author.kind === 'person'`, on a plain post (`source` null). Agents (a Buddy included), other people, viewers and+ system rows are refused. Team sessions are never the person already (lib/teamSession.ts).+- No edit history is stored or served: an edit overwrites `text` (credentials removed, as a send's) and sets `editedAt`;+ a delete clears `text`, files and mentions, and removes the tags the message gave.+- An edit changes the text only: who it tagged and who it was sent to stay as sent (Slack does not re-notify on an edit+ either). A tag typed into an edit is not a new tag.+- Replies keep their thread: a deleted root with replies stays as a tombstone; its replies stay under it.+- Nothing about who can read a message changes: the target is found with the same checks as `reactionTarget`.+- Copy: "Edit message", "Delete message", "(edited)", "This message was deleted.", dialog "Delete message?" /+ "This can't be undone." / Cancel / Delete. Harness Design Language for every new surface.+- Desktop tests use a memory store and a fake sign-in; never the real CLI login. Swarm code stays out of cli/src/core.+- PR body first line: "Requested by [email protected] through Harness."++## Design++- growth: nothing new grows. A delete removes the row (or leaves one tombstone per deleted root with replies), its+ reactions, its Activity rows, and marks its files for the hourly attachment sweep (lib/attachmentSweep.ts) to remove.+ Tombstones go with their Swarm (purge.ts).+- concurrency: conversation level. Each change bumps the group's `reactionSeq`, so it writes the group part, as+ `message.send` does (`messageSeq`); a reply racing a delete of its root conflicts on the group and runs again, then+ finds the root gone (refused) or a tombstone (kept as a reply). A reply delete also rewrites its thread summary+ (`refreshThreads`), which a concurrent reply writes too.+- read cost: one row by primary key, plus one `findFirst` for "has a reply" on a root delete (index+ `[tabId, conversationId, thread, sequence]`). Readers re-read only the page they show, as for a reaction.+- scale: 10x edits cost 10x single-row writes; the warning metric is the `message page` read count per poll+ (`recordMessageRead`), which `reactionSeq` re-reads move.+- compatibility: older apps re-read the page on `reactionSeq` and show the new text; a tombstone's stored text is the+ words "This message was deleted." so every older app, the CLI and inbox previews show it right. Older backends ignore+ the two new optional row fields. Older apps never send the new commands.+- migration + rollback: no migration (two optional fields). A rollback leaves `editedAt`/`deletedAt` unread and a+ tombstone shows its words; edits stay edited.+- audience: the server enforces it (commands.ts `messageEdits.ts` + store target lookup); the apps only hide the menu+ items.+- identity: the actor is the signed-in person; a Buddy or any agent is refused by kind; never the machine owner's login.+- failure: refusals say why (NOT_FOUND "This message is unavailable.", FORBIDDEN "Only its author can change this+ message.", MESSAGE_DELETED "This message was deleted."); the apps show the refusal as a snackbar and keep the old text.+- platforms: backend; Desktop (macOS, Windows, Linux) and web from one Flutter code base; phone (iOS, Android).++What agents see (River): an edit or delete does not re-deliver to an agent that already read the message; a delivery+not yet claimed is cancelled on delete and reads the new text on edit (it reads the row when claimed). A deleted+message's files are removed for everyone.++## Wire contract (Task 1 produces it, Tasks 2 and 3 consume it)++- `{ "type": "message.edit", "conversationId": ID, "messageId": ID, "text": string }`: `text` trimmed, at most 32,000;+ empty only when the message has files. Result `{ "changed": boolean }` (false when the text is the same).+- `{ "type": "message.delete", "conversationId": ID, "messageId": ID }`. Result `{ "changed": true, "kept": boolean }`+ (`kept`: it stays as "This message was deleted." because it has replies).+- Message rows in pages gain optional `editedAt` (ISO string) and `deletedAt` (ISO string). A tombstone has+ `deletedAt`, `text: "This message was deleted."`, no attachments, no mentions, no reactions.+- The conversation's `reactionSeq` moves on every change.++## Review Focus++1. Another person, a viewer, an agent, the author's own Buddy: each refused for edit and delete (Task 1 tests "only the+ author", "a Buddy cannot").+2. A message hidden from the actor (agent-only notice, another conversation's id): refused as unavailable, never as+ "not yours", so a refusal tells nothing (Task 1 test "hidden reads as unavailable").+3. A deleted root with replies: the replies still read in its thread and the summary still counts them; a deleted reply+ leaves the summary's count and last reply right (Task 1 integration "replies keep their thread").+4. No old text after an edit or delete anywhere a reader can reach: the page, one message by id, the inbox preview+ (Task 1 integration "no history").+5. The chat does not stay unread for a deleted newest message (Task 1 test "counters step back").++---++### Task 1: Backend commands++**Files:**+- Create: `backend/src/superTabs/messageEdits.ts`, `backend/src/superTabs/messageEdits.test.ts`,+ `backend/integration/superTabMessageEdits.test.ts`+- Modify: `backend/src/superTabs/commands.ts` (schema, context, apply), `backend/src/superTabs/store.ts` (target read,+ writes), `backend/prisma/schema.prisma` (`editedAt`, `deletedAt` on SuperTabMessage), `backend/src/superTabs/buddies.ts`+ only if its command list needs the refusal, `hotFilters.allowed.json` for new filters.++**Interfaces:**+- Produces: `MessageChangeTarget { messageId; authorKind; authorId; plain: boolean; deleted: boolean; hasFiles: boolean;+ hasReplies: boolean }`; `editMessage(group, actor, command, target): boolean`; `deleteMessage(group, actor, command,+ target): { kept: boolean }`; `DELETED_TEXT = 'This message was deleted.'`.++- [ ] Step 1: unit tests in messageEdits.test.ts (fail: module missing): only the author edits/deletes; another person,+ a viewer, an agent and the owner's Buddy get FORBIDDEN/READ_ONLY; a sourced row FORBIDDEN; a missing target+ NOT_FOUND; a tombstone MESSAGE_DELETED; empty text without files refused; same text → changed false; each change bumps+ `reactionSeq`; delete with replies → kept.+- [ ] Step 2: implement messageEdits.ts and wire commands.ts; tests pass; commit.+- [ ] Step 3: integration tests (fail): edit then page/message-by-id/inbox show only the new text with `editedAt`; delete+ without replies removes the row, its reactions, Activity and cancels open deliveries; its files are marked for the+ sweep; delete of a root with replies keeps a tombstone and the thread reads whole; delete of a reply refreshes the+ summary; deleting the newest message steps `lastMainSequence`/`lastPersonSequence`/`lastMessageSequence` back; a+ Buddy acting as an agent is refused; an agent-only row reads as unavailable.+- [ ] Step 4: implement store target read and writes; integration and unit tests pass; `npm test`; commit.++### Task 2: Desktop and web++**Files:**+- Modify: `desktop/lib/super_tabs/model.dart` (`editedAt`, `deletedAt` on SuperTabMessage), `controller.dart`+ (`editMessage`, `deleteMessage` sending the commands, re-reading the page), `message_row.dart` (More menu items for own+ plain messages, in-place editor, "(edited)", tombstone line), the row's callers to pass the callbacks.+- Test: `desktop/test/super_tabs/message_edit_test.dart` (new).++- [ ] Step 1: widget tests (fail): own message's More menu lists Edit message and Delete message after a divider; an+ agent's or another person's does not; Edit opens the field with the text, Enter sends `message.edit`, Esc cancels;+ Delete asks "Delete message?" and sends `message.delete` on Delete only; an `editedAt` row shows "(edited)"; a+ `deletedAt` row shows "This message was deleted." in faint italic with no hover actions but its reply line.+- [ ] Step 2: implement; tests pass; screenshots light and dark; commit.++### Task 3: Phone++**Files:**+- Modify: `mobile/lib/swarm/model.dart`, `swarm_reactions.dart` (sheet items), `swarm_message_row.dart` ("(edited)",+ tombstone), `swarm_conversation.dart` (send the commands, re-read).+- Test: `mobile/test/swarm/swarm_message_edit_test.dart` (new).++- [ ] Step 1: widget tests (fail): own message's long-press sheet shows Edit message and Delete message under Copy link+ to message; others' do not; Edit opens a text sheet prefilled, Save sends `message.edit`; Delete confirms then sends+ `message.delete`; "(edited)" and the tombstone line render.+- [ ] Step 2: implement; tests pass; screenshots light and dark; commit.diff --git a/docs/plans/2026-11-04-open-proposals-read-plan.md b/docs/plans/2026-11-04-open-proposals-read-plan.mdnew file mode 100644index 000000000..276212068--- /dev/null+++ b/docs/plans/2026-11-04-open-proposals-read-plan.md@@ -0,0 +1,105 @@+# Open proposals read by id: implementation plan++Way of working: the Engineer implements this plan itself, task by task, test first (project instructions, Engineer). No+Execution Handoff.++**Goal:** The Tasks view's open-proposals read (`GET /api/super-tabs/:tab/proposals`, polled every minute by Desktop)+stops walking the whole project chat. Its query count, and the rows it examines, stay the same however long the chat+grows, and its answers stay the same (task #2777, Ken's prod scan 11-04, index suggestion 3).++**Architecture:** A small collection, `SuperTabOpenProposal`, holds a project chat's proposal roots that have not been+seen answered. One row per root (id = the root message's id), written in the transaction that inserts the root+(`store.ts writeMessages`). The read lists the rows newest first by `{tabId, conversationId, sequence}` and reads those+roots by `_id`. It reads their threads as today (`pageThreads`) and applies today's rule (`threads.ts askOf`). A root it+finds answered, or whose message is gone, it deletes from the set: an answer is permanent under that rule (a task's mark+never reverts to a proposal; a lead's reply stays in the thread). A chat with no seed mark yet (every chat at release)+runs today's scan once and stores its open roots and a seed mark (`seeded:<tab>:<chat>`, sequence -1). For 30 minutes+after the mark, reads run the scan again, so a proposal an older pod wrote during the rolling release (without a row)+still gets one.++**Tech Stack:** TypeScript, Prisma (MongoDB), vitest, mongodb-memory-server integration tests.++**Spec:** task #2777 brief (keep the open set where proposals are written, read by id, one-time seed on first read per+project, no separate backfill, same answers).++## Design++- growth: a row per proposal root that is open or not yet seen answered, plus one seed mark per project chat. The read+ deletes a root once it finds it answered or gone; the Swarm's purge deletes the rest (`purge.ts PURGED_BY_TAB_ID`).+ Open proposals today are under 10 per project.+- concurrency: no locks. The write inserts in the root's own transaction. Seeds are idempotent upserts (`$setOnInsert`),+ and deletes are by id. A seed racing a prune may re-add an answered root, and the next read prunes it again.+- read cost: after the seed, 1 seed-mark read + 1 set page + 1 roots-by-id read + the thread summaries of those roots+ (+1 delete when something was answered). None depends on the chat's length.+- scale: at 10x proposals per project, the set stays the open ones. The first warning metric is the read's+ docsExamined on the set's index, held to rows returned in the integration test.+- compatibility: the endpoint and its answer are unchanged. Old pods during the rollout write roots without rows; the+ 30-minute re-seed window covers them.+- migration + rollback: none to run. The schema push creates the collection and index. A rollback leaves the+ collection unused, but the release rolled back to writes proposal roots with no row. So before releasing this again+ after a rollback, the release owner deletes the seed marks (`_id` starting with `seeded:`), and each chat re-seeds+ on its next read (review of #2968). Without that step, proposals sent during the rollback never show in Tasks+ (they stay in the chat).+- audience: unchanged. The store checks the reader may read the project chat before the read (`proposalChat`).+- identity: N/A because nothing here acts as a person.+- failure: a failed set write fails the proposal's transaction (it is retried, as any write); a failed read fails the+ request as today.+- platforms: server only.++## Global Constraints++- Answers equal today's for every chat (seed path is today's algorithm; set path applies the same rule to the same roots).+ Two bounds differ, both far above today's under 10 open per project: the seed keeps the newest 100 open (today's+ answer), so an older open one past those is not kept; and the set is not limited to the newest 1,000 roots.+- Production: no access; the collection and its index come with the release's schema push (no TTL index, so no+ pre-push step).+- Backend rules (backend/AGENTS.md): the model names what removes it; the new query gets an integration plan test (IXSCAN+ on its index, docs examined close to returned).+- Swarm code stays out of cli/src/core. Temp files only in mktemp -d folders.++## Review Focus++- The prune is sound: an answer under `askOf` never becomes a proposal again (marks, lead replies). The one edge is a lead+ agent replaced: today a proposal its old lead answered would read as open again; with the set it stays answered.+- The write path inserts a row only for a proposal root (`source.kind` `buddy-proposal`, own thread).+- The seed window covers proposals written by old pods during the rolling release.++## Task 1: the read over the open set (`backend/src/superTabs/proposals.ts`)++**Files:** `backend/src/superTabs/proposals.ts`, `backend/src/superTabs/proposals.test.ts`++**Interfaces:**+```ts+export const SEED_SETTLE_MS = 30 * 60_000+export interface ProposalReads {+ seededAt(): Promise<number | null>+ seed(roots: Array<{ id: string; sequence: number }>): Promise<void>+ listed(before: number | undefined, take: number): Promise<Array<{ id: string; sequence: number }>>+ rootsById(ids: string[]): Promise<ProposalRoot[]>+ roots(before: number | undefined, take: number): Promise<ProposalRoot[]> // the seed's chat scan+ threads(rootIds: string[]): Promise<ThreadReply[]>+ forget(ids: string[]): Promise<void>+}+export function openProposals(state, chat, reads, now?: number): Promise<OpenProposal[]>+```++- [ ] Failing tests (fake reads): unseeded chat → today's answer, open roots seeded, mark set; seeded chat → the same+ answer from the set with no chat scan, whatever the chat's length (scan calls 0, set and root reads constant); a new+ proposal in the set is listed; one answered by the PM or marked by a task is not listed and is forgotten; a root+ whose message is gone is forgotten; within the settle window the scan runs again.+- [ ] Watch them fail.+- [ ] Implement; tests pass.++## Task 2: the database side (schema, write path, reads, purge)++**Files:** `backend/prisma/schema.prisma`, `backend/src/superTabs/proposals.ts` (`databaseProposalReads`,+`openProposalRows`), `backend/src/superTabs/store.ts` (`writeMessages`), `backend/src/superTabs/parts/indexed.ts`+(`NAMED_INDEX.SuperTabOpenProposal.open`), `backend/src/superTabs/purge.ts`,+`backend/integration/superTabProposals.test.ts`, `backend/integration/superTabBuddies.test.ts`.++- [ ] Failing integration tests: the store's proposal write adds the root to the set; the read lists it, and drops it+ once the PM answers in its thread; after the seed, the read's operations are the same for a 30-row and a 3,000-row+ chat and the set's read is an IXSCAN on its index with docs examined equal to returned; a purged Swarm leaves no+ rows.+- [ ] Watch them fail.+- [ ] Implement; tests pass. Backend unit tests of what changed; the PR's CI runs the suites.diff --git a/docs/plans/2026-11-04-owner-account-teammates-work-plan.md b/docs/plans/2026-11-04-owner-account-teammates-work-plan.mdnew file mode 100644index 000000000..75d7cc2a9--- /dev/null+++ b/docs/plans/2026-11-04-owner-account-teammates-work-plan.md@@ -0,0 +1,38 @@+# Teammates' work in a Mac owner's own account: plan (backend, PR 1)++**Goal:** a Mac's owner, and nobody else, can let teammates' agents run in their own macOS account on that Mac instead of+always moving to its Harness Team account (task #2806, Scholes, 11-04: the lampOS mobile team needs Flutter and phone+signing, which live in the owner's account on Gray's Mac). The Desktop menu and warning are PR 2 (#2813).++**Architecture:** `machine.ownAccountWork {machineId, allowed, askedIn?}`, shaped as `machine.projects`: the machine's owner+sends it, or the project's Lead passes on the owner's own chat message from the last day (`machineOwnerWord`). It sets+`ContributedMachine.ownAccountChoice = {allowed, by, at}` on the Mac's own entry; never on a Team account's entry, a+Buddy-only machine or one being removed. With `allowed`, `teamWorkRefusal` returns null for that entry (the owner's choice+wins over `SWARM_TEAM_ACCOUNT_REQUIRED` for that Mac only, River 11-04), `teamMachineFor` keeps a teammate's start on the Mac+(unless a Team agent wrote the code, audit H2), and `leadHost` runs a teammate's Product Manager on the Mac. A start still+moved to the Team account returns `moved`, one sentence. The machine reading's `teamWork.ownAccount` and the route's notes+say "<Mac> runs teammates' work in <owner>'s own account."++## Security+- Loosens a privacy guard: two independent security reviews.+- Who may change it: the owner (person session); a Lead only with the owner's own message. Refused: another person (the+ Swarm's owner included), any other agent, a Buddy (refused earlier by the Buddy write rule), a Harness Team account+ session (`store.ts teamCommand`).+- Default unchanged: absent means Team-account-only. `machine.contribute` keeps the choice on re-save (Desktop's join+ re-save included), but not over a removal, so a Mac removed and added again starts at the safe default.+- Agents already running are never moved.++## Design+- growth: one small object per machine entry; removed with the machine.+- concurrency: a command on the Swarm's state, as machine.projects.+- read cost: none new; the reading adds one string.+- compatibility: older clients ignore the new fields; older Desktops never send the command.+- migration + rollback: none; rolling back drops the field's effect (starts move to the Team account again).+- audience: the server checks the caller owns the machine; never trusts the command.+- identity: recorded as the owner's choice (`by`), whoever relayed it.+- failure: a moved start says why; refusals carry a reason.+- platforms: any machine with a Team account entry; Macs today.++## Tests (red first)+`backend/src/superTabs/ownAccountWork.test.ts`, `leadStart.test.ts`, `integration/superTabTeam.test.ts`,+`cli/src/superTabs/routeCommand.spec.ts`.diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex bf2b6da55..49e66811c 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -1395,6 +1395,8 @@ class SuperTabMessage {author = Map.unmodifiable(superTabMap(row['author'])),source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ editedAt = DateTime.tryParse(row['editedAt'] as String? ?? ''),+ deletedAt = DateTime.tryParse(row['deletedAt'] as String? ?? ''),attachments = _attachments(row['attachments']),reactions = List.unmodifiable(SuperTabReactionCount.listFromJson(row['reactions']),@@ -1434,6 +1436,17 @@ class SuperTabMessage {final Map<String, dynamic> author;final Map<String, dynamic> source;final DateTime? createdAt;++ /// When its author last changed its text; null for one never edited+ /// (backend messageEdits.ts). No earlier text is kept anywhere.+ final DateTime? editedAt;++ /// When its author deleted it: kept only as the root of a thread with+ /// replies, its text then the backend's "This message was deleted.", with+ /// no files and no reactions. One without replies leaves the pages.+ final DateTime? deletedAt;++ bool get deleted => deletedAt != null;final List<SuperTabAttachment> attachments;final List<SuperTabReactionCount> reactions;diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 71f3017a2..81214e4bc 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -321,6 +321,13 @@ class SwarmConversation extends ChangeNotifier/// them.final _reacting = <(String, SuperTabReactionEmoji), bool>{};+ /// The messages a read found deleted since they were shown: a thread's+ /// own rows of them go too ([gone]).+ final _gone = <String>{};++ /// Message [id] was shown here and a read since found it deleted.+ bool gone(String id) => _gone.contains(id);+/// Moves when what was read is dropped: a read asked for before then/// answers nothing.int _epoch = 0;@@ -659,6 +666,7 @@ class SwarmConversation extends ChangeNotifier_readingOlder = null;_rereading = null;_reactionSeq = null;+ _gone.clear();_dropReceipt();}@@ -833,6 +841,33 @@ class SwarmConversation extends ChangeNotifierbyId[m.id] = m;changed = true;}+ // The page read again is the backend's word on every message it+ // covers: one shown there that it no longer has was deleted (backend+ // messageEdits.ts). Earlier pages it does not reach keep theirs.+ if (again && tail != null) {+ final covers = answer['next'] == null+ ? 0+ : incoming.isEmpty+ ? null+ : incoming.map((m) => m.sequence).reduce((a, b) => a < b ? a : b);+ if (covers != null) {+ final read = {for (final m in incoming) m.id};+ final gone = [+ for (final m in byId.values)+ if (m.sequence >= covers &&+ m.sequence <= tail &&+ !read.contains(m.id))+ m.id,+ ];+ for (final id in gone) {+ byId.remove(id);+ }+ if (gone.isNotEmpty) {+ _gone.addAll(gone);+ changed = true;+ }+ }+ }if (changed) {messages = List.unmodifiable(byId.values.toList()..sort(superTabMessageOrder),@@ -1143,6 +1178,125 @@ class SwarmConversation extends ChangeNotifierreturn refused == null;}+ /// The person may edit and delete [message]: their own plain post (no+ /// note the server wrote in their name), not deleted, where they may post.+ /// The backend decides again (messageEdits.ts); this only hides the menu.+ bool mayChange(SuperTabMessage message) =>+ canPost &&+ message.author['kind'] == 'person' &&+ message.authorId == reader.accountId &&+ message.source.isEmpty &&+ !message.deleted;++ /// Puts [text], trimmed, in place of [message]'s (backend `message.edit`):+ /// the chat shows it, "(edited)", once the backend has it. Answers why it+ /// was refused, the old text staying; null once done, or when nothing+ /// changed and nothing was sent.+ Future<String?> editMessage(SuperTabMessage message, String text) async {+ final trimmed = text.trim();+ if (trimmed == message.text) return null;+ if (trimmed.isEmpty && message.attachments.isEmpty) {+ return 'Write something, or delete the message.';+ }+ return _change(message, {+ 'type': 'message.edit',+ 'conversationId': id,+ 'messageId': message.id,+ 'text': trimmed,+ }, 'Your edit did not go through. Try again.');+ }++ /// Deletes [message] for everyone (backend `message.delete`): it leaves the+ /// chat, or, as the root of a thread with replies, reads "This message was+ /// deleted." over them. Answers why it was refused; null once done.+ Future<String?> deleteMessage(SuperTabMessage message) => _change(message, {+ 'type': 'message.delete',+ 'conversationId': id,+ 'messageId': message.id,+ }, 'The message was not deleted. Try again.');++ /// Sends the person's change to [message], then reads the page shown again+ /// so it shows at once; one before that page is read by itself.+ Future<String?> _change(+ SuperTabMessage message,+ Map<String, dynamic> command,+ String failed,+ ) async {+ if (_disposed || !mayChange(message)) return failed;+ final epoch = _epoch;+ SuperTabMessage? shown() =>+ messages.where((m) => m.id == message.id).firstOrNull;+ final before = shown();+ Object? answer;+ try {+ answer = await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {'operationId': superTabOperationId(), 'command': command},+ );+ } on SuperTabFailure catch (failure) {+ return failure.message;+ } catch (_) {+ return failed;+ }+ if (_disposed || epoch != _epoch) return null;+ // Deleted with no replies to keep it: gone at once, before any read.+ final result = answer is Map ? answer['result'] : null;+ if (command['type'] == 'message.delete' &&+ result is Map &&+ result['kept'] == false) {+ _drop(message.id);+ }+ unawaited(reader.refresh());+ // A read of the page begun before the backend had it would not show it.+ if (_rereading case final reading?) await reading;+ await _reread();+ if (_disposed || epoch != _epoch) return null;+ // Not on the page read again (one read back, or a thread's): by itself.+ if (shown() case final now? when identical(now, before)) {+ await _readBack(message.id);+ }+ return null;+ }++ /// Takes message [id] out of the chat: deleted.+ void _drop(String id) {+ if (!messages.any((m) => m.id == id)) return;+ messages = List.unmodifiable(messages.where((m) => m.id != id));+ _gone.add(id);+ notifyListeners();+ }++ /// Reads message [id] by itself, after the person changed it where the+ /// page read again does not reach: its row as the backend has it now, or+ /// gone. A failed read keeps the row shown until the next read of it.+ Future<void> _readBack(String messageId) async {+ final epoch = _epoch;+ try {+ final answer = superTabMap(+ await reader.request(+ 'GET',+ '$messagesPath?messageId=${Uri.encodeQueryComponent(messageId)}',+ ),+ );+ if (_disposed || epoch != _epoch) return;+ final fresh = [+ for (final row in answer['messages'] as List)+ SuperTabMessage.fromJson(superTabMap(row)),+ ].where((m) => m.id == messageId && m.conversationId == id).firstOrNull;+ final at = messages.indexWhere((m) => m.id == messageId);+ if (at < 0) return;+ if (fresh == null) {+ _drop(messageId);+ } else if (!_same(messages[at], fresh)) {+ messages = List.unmodifiable([...messages]..[at] = fresh);+ notifyListeners();+ }+ } catch (_) {+ // Shown as it was; the next read of its page brings it.+ }+ }+/// The delivery a person's answer is on its way for, and the answer/// ([resolveDelivery]).(String, String)? get resolving => _resolving;@@ -1288,6 +1442,8 @@ class SwarmConversation extends ChangeNotifiera.replyTo == b.replyTo &&a.authorName == b.authorName &&a.createdAt == b.createdAt &&+ a.editedAt == b.editedAt &&+ a.deletedAt == b.deletedAt &&a.attachments.length == b.attachments.length &&_sameReactions(a.reactions, b.reactions) &&_sameDeliveries(a, b);diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 1207b9a8a..88ab06726 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -44,6 +44,7 @@ import 'swarm_inbox.dart';import 'swarm_reader.dart';import 'swarm_live_card.dart';import 'swarm_link_previews.dart';+import 'swarm_message_edit.dart';import 'swarm_message_link.dart';import 'swarm_message_receipt.dart';import 'swarm_message_row.dart';@@ -1732,17 +1733,61 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>SuperTabMessage? shown() => t.messages.where((m) => m.id == id).firstOrNull;final message = shown();if (message == null) return;+ final mine = c.mayChange(message);final emoji = await showSwarmReactionPicker(context,reactions: c.reactionsOf(message),readerId: c.reader.accountId,react: c.canPost,link: _linkTo(c, id),+ onEdit: mine+ ? () => unawaited(_edit(shown, (m, text) => t.editMessage(m, text)))+ : null,+ onDelete: mine ? () => unawaited(_delete(shown, t.deleteMessage)) : null,);if (emoji == null || !mounted) return;if (shown() case final now?) await t.react(now, emoji);}+ /// Edit message on the message [shown] finds: its text in a sheet, and the+ /// new text through [edit]. A refusal says why at the foot; the old text+ /// stays.+ Future<void> _edit(+ SuperTabMessage? Function() shown,+ Future<String?> Function(SuperTabMessage, String) edit,+ ) async {+ final message = shown();+ if (message == null) return;+ final text = await showSwarmEditMessage(+ context,+ text: message.text,+ hasFiles: message.attachments.isNotEmpty,+ );+ if (text == null || !mounted) return;+ final now = shown();+ if (now == null) return;+ _refusal(await edit(now, text));+ }++ /// Delete message on the message [shown] finds, once the person says so.+ Future<void> _delete(+ SuperTabMessage? Function() shown,+ Future<String?> Function(SuperTabMessage) delete,+ ) async {+ if (!await confirmSwarmDeleteMessage(context) || !mounted) return;+ final now = shown();+ if (now == null) return;+ _refusal(await delete(now));+ }++ /// A change's refusal at the foot of the screen; nothing once it went.+ void _refusal(String? refused) {+ if (refused == null || !mounted) return;+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(content: Text(refused), duration: Durations.extralong4),+ );+ }+/// The reaction picker over message [id]: the pick reacts to the message/// as it is by then. The long-press sheet also copies the message's link;/// the Add reaction chip's ([link] false) offers reactions alone.@@ -1754,12 +1799,16 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>SuperTabMessage? shown() => c.messages.where((m) => m.id == id).firstOrNull;final message = shown();if (message == null) return;+ // Edit and Delete are the long-press sheet's, on the person's own.+ final mine = link && c.mayChange(message);final emoji = await showSwarmReactionPicker(context,reactions: c.reactionsOf(message),readerId: c.reader.accountId,react: c.canPost,link: link ? _linkTo(c, id) : null,+ onEdit: mine ? () => unawaited(_edit(shown, c.editMessage)) : null,+ onDelete: mine ? () => unawaited(_delete(shown, c.deleteMessage)) : null,);if (emoji == null || !mounted) return;if (shown() case final now?) await c.react(now, emoji);diff --git a/mobile/lib/swarm/swarm_message_edit.dart b/mobile/lib/swarm/swarm_message_edit.dartnew file mode 100644index 000000000..1d83a7953--- /dev/null+++ b/mobile/lib/swarm/swarm_message_edit.dart@@ -0,0 +1,149 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_sheet.dart' show confirmPhoneAction;+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';++import 'swarm_style.dart';++/// The longest text a message takes (backend messageEdits.ts).+const swarmMessageMaxLength = 32000;++/// Edit message, from a message's long-press sheet: its [text] in a field to+/// change, Cancel and Save. Answers the new text, trimmed; null for Cancel,+/// or for Save with the text as it was. Empty is saved only for a message+/// with files ([hasFiles]), whose files then say it alone.+Future<String?> showSwarmEditMessage(+ BuildContext context, {+ required String text,+ bool hasFiles = false,+}) => showModalBottomSheet<String>(+ context: context,+ isScrollControlled: true,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ builder: (_) => _EditSheet(text: text, hasFiles: hasFiles),+);++/// Delete message's question: only Delete answers true.+Future<bool> confirmSwarmDeleteMessage(BuildContext context) =>+ confirmPhoneAction(+ context,+ title: 'Delete message?',+ message: "This can't be undone.",+ confirmLabel: 'Delete',+ icon: LucideIcons.trash2300,+ );++class _EditSheet extends StatefulWidget {+ const _EditSheet({required this.text, required this.hasFiles});++ final String text;+ final bool hasFiles;++ @override+ State<_EditSheet> createState() => _EditSheetState();+}++class _EditSheetState extends State<_EditSheet> {+ late final _field = TextEditingController(text: widget.text);++ @override+ void dispose() {+ _field.dispose();+ super.dispose();+ }++ bool get _can => _field.text.trim().isNotEmpty || widget.hasFiles;++ void _save() {+ if (!_can) return;+ final typed = _field.text.trim();+ Navigator.of(context).pop(typed == widget.text ? null : typed);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ // Over the keyboard.+ padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),+ child: SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ AppSpace.l,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The grabber, as the long-press sheet's.+ Center(+ child: Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.m),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ ),+ Text(+ 'Edit message',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ const SizedBox(height: AppSpace.m),+ TextField(+ key: const ValueKey('swarm-edit-field'),+ controller: _field,+ autofocus: true,+ minLines: 3,+ maxLines: 8,+ maxLength: swarmMessageMaxLength,+ keyboardType: TextInputType.multiline,+ textCapitalization: TextCapitalization.sentences,+ style: AppType.body(color: AppPalette.textPrimary),+ decoration: InputDecoration(+ counterText: '',+ filled: true,+ fillColor: AppPalette.swarmField,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ borderSide: BorderSide.none,+ ),+ ),+ onChanged: (_) => setState(() {}),+ ),+ const SizedBox(height: AppSpace.m),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ SwarmButton(+ key: const ValueKey('swarm-edit-cancel'),+ label: 'Cancel',+ style: SwarmButtonStyle.link,+ onPressed: () => Navigator.of(context).pop(),+ ),+ const SizedBox(width: AppSpace.s),+ SwarmButton(+ key: const ValueKey('swarm-edit-save'),+ label: 'Save',+ style: SwarmButtonStyle.fill,+ onPressed: _can ? _save : null,+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dartindex 655e4b21e..60f05a645 100644--- a/mobile/lib/swarm/swarm_message_row.dart+++ b/mobile/lib/swarm/swarm_message_row.dart@@ -11,6 +11,7 @@ import 'package:harness_mobile/phone/tty_controls.dart';import 'package:harness_mobile/shared/theme/app_ink.dart';import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';export 'swarm_file_links.dart' show swarmAttachmentHost, swarmAttachmentLink;export 'swarm_message_style.dart'@@ -248,10 +249,16 @@ class SwarmMessageFrame extends StatelessWidget {);}+/// What a deleted message reads, in place of its text (backend+/// messageEdits.ts `DELETED_TEXT`).+const swarmDeletedText = 'This message was deleted.';+/// One message: avatar, who wrote it, their role and when — none of it for a-/// follow-up — then what it answers, its text, its files, its [reactions] and-/// its [thread]'s line. A tap opens its actions, a long-press [onLongPress];-/// lit for a moment when a quote leads to it.+/// follow-up — then what it answers, its text ("(edited)" under it once its+/// author changed it), its files, its [reactions] and its [thread]'s line. A+/// deleted one keeps only "This message was deleted." and its thread's line.+/// A tap opens its actions, a long-press [onLongPress]; lit for a moment when+/// a quote leads to it.class SwarmMessageRow extends StatelessWidget {const SwarmMessageRow({super.key,@@ -362,7 +369,8 @@ class SwarmMessageRow extends StatelessWidget {/// (swarm_message_receipt.dart); null for every other message.final Widget? receipt;- /// Opens its long-press sheet: reactions, Copy link to message.+ /// Opens its long-press sheet: reactions, Copy link to message, and Edit+ /// and Delete on the reader's own. None for a deleted message.final VoidCallback? onLongPress;/// One of the message's files, with what asks for a fresh link to it@@ -417,6 +425,26 @@ class SwarmMessageRow extends StatelessWidget {String two(int n) => n.toString().padLeft(2, '0');final key = ValueKey('swarm-message-${message.id}');final padding = SwarmMessageFrame.padding(grouped: grouped);+ // A deleted message keeps only its words and its thread's line.+ final deletedBody = !message.deleted+ ? null+ : <Widget>[+ if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),+ ?quote,+ Padding(+ padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),+ child: Text(+ swarmDeletedText,+ key: ValueKey('swarm-deleted-${message.id}'),+ style: swarmChatText(+ 16,+ color: AppPalette.textFaint,+ height: 1.42,+ ).copyWith(fontStyle: FontStyle.italic),+ ),+ ),+ ?thread,+ ];final frame = SwarmMessageFrame(grouped: grouped,onAvatar: onAuthor,@@ -447,60 +475,74 @@ class SwarmMessageRow extends StatelessWidget {style: tty.style(color: AppPalette.textFaint, size: 12.5),),),- body: [- if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),- ?quote,- ?swarmTerminalNote(message),- // A voice message's text is its words: under its bubble, on →A.- if (!message.attachments.any((file) => file.voice != null))- for (final part in swarmTextParts(message.text))- if (part.code)- SwarmCodeBlock(code: part.text, name: part.name, onTap: onTap)- else+ body:+ deletedBody ??+ [+ if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),+ ?quote,+ ?swarmTerminalNote(message),+ // A voice message's text is its words: under its bubble, on →A.+ if (!message.attachments.any((file) => file.voice != null))+ for (final part in swarmTextParts(message.text))+ if (part.code)+ SwarmCodeBlock(code: part.text, name: part.name, onTap: onTap)+ else+ Padding(+ padding: const EdgeInsets.only(+ top: SwarmMessageFrame.bodyGap,+ ),+ child: SwarmMessageText(+ text: part.text,+ mentionNames: mentions.names,+ references: references,+ tagged: tagged,+ addresses: taggedAddresses,+ labels: taggedLabels,+ onTap: onTap,+ onOpenConversation: onOpenConversation,+ ),+ ),+ if (message.editedAt != null)Padding(- padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),- child: SwarmMessageText(- text: part.text,- mentionNames: mentions.names,- references: references,- tagged: tagged,- addresses: taggedAddresses,- labels: taggedLabels,- onTap: onTap,- onOpenConversation: onOpenConversation,+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: Text(+ '(edited)',+ key: ValueKey('swarm-edited-${message.id}'),+ style: AppType.caption(color: AppPalette.textFaint),),),- ?swarmCutShort(message),- for (final file in message.attachments) _attachment(context, file),- ?card,- ?links,- ?reactions,- ?thread,- ?below,- ?receipt,- if (actions)- Padding(- padding: const EdgeInsets.only(top: AppSpace.s),- child: Wrap(- spacing: 6,- runSpacing: 6,- children: [- if (onReply case final reply?)- SwarmSmallButton(- key: ValueKey('swarm-reply-${message.id}'),- icon: inThread- ? LucideIcons.messageSquareReply- : LucideIcons.reply,- label: inThread ? 'Reply in thread' : 'Reply',- onTap: reply,- ),- SwarmCopyButton(text: message.text),- ],- ),- ),- ],+ ?swarmCutShort(message),+ for (final file in message.attachments) _attachment(context, file),+ ?card,+ ?links,+ ?reactions,+ ?thread,+ ?below,+ ?receipt,+ if (actions)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: Wrap(+ spacing: 6,+ runSpacing: 6,+ children: [+ if (onReply case final reply?)+ SwarmSmallButton(+ key: ValueKey('swarm-reply-${message.id}'),+ icon: inThread+ ? LucideIcons.messageSquareReply+ : LucideIcons.reply,+ label: inThread ? 'Reply in thread' : 'Reply',+ onTap: reply,+ ),+ SwarmCopyButton(text: message.text),+ ],+ ),+ ),+ ],);- final held = onLongPress == null+ // A deleted message has nothing left to react to, copy or change.+ final held = onLongPress == null || message.deleted? frame: GestureDetector(behavior: HitTestBehavior.translucent,diff --git a/mobile/lib/swarm/swarm_reactions.dart b/mobile/lib/swarm/swarm_reactions.dartindex 25fa09289..7fff85044 100644--- a/mobile/lib/swarm/swarm_reactions.dart+++ b/mobile/lib/swarm/swarm_reactions.dart@@ -8,6 +8,7 @@ import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/theme/app_type.dart';import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;import 'model.dart';import 'swarm_message_link.dart';@@ -194,14 +195,18 @@ class _AddChip extends StatelessWidget {/// Opens a message's long-press sheet, with a light tap of the phone: the/// reactions it can carry (Desktop's seven, the reader's own marked) where/// the reader may [react], then Copy link to message with its [link], which-/// copies it and says so. Answers the reaction picked, or null when the sheet-/// closed without one.+/// copies it and says so. On the reader's own message, Edit message and+/// Delete message under it: each closes the sheet, then calls [onEdit] or+/// [onDelete]. Answers the reaction picked, or null when the sheet closed+/// without one.Future<SuperTabReactionEmoji?> showSwarmReactionPicker(BuildContext context, {required List<SuperTabReactionCount> reactions,required String readerId,bool react = true,SwarmMessageLink? link,+ VoidCallback? onEdit,+ VoidCallback? onDelete,}) {HapticFeedback.lightImpact();final mine = {@@ -212,16 +217,35 @@ Future<SuperTabReactionEmoji?> showSwarmReactionPicker(context: context,backgroundColor: AppGlass.rowFill,shape: AppControl.sheetShape,- builder: (context) => _Picker(mine: mine, react: react, link: link),+ builder: (context) => _Picker(+ mine: mine,+ react: react,+ link: link,+ onEdit: onEdit,+ onDelete: onDelete,+ ),);}class _Picker extends StatelessWidget {- const _Picker({required this.mine, required this.react, this.link});+ const _Picker({+ required this.mine,+ required this.react,+ this.link,+ this.onEdit,+ this.onDelete,+ });final Set<SuperTabReactionEmoji> mine;final bool react;final SwarmMessageLink? link;+ final VoidCallback? onEdit, onDelete;++ /// The sheet closed, then [act]: what it opens goes over the chat.+ void _then(BuildContext context, VoidCallback act) {+ Navigator.of(context).pop();+ act();+ }/// Desktop's Copy link to message: the link on the clipboard, the sheet/// closed, and "Link copied".@@ -309,45 +333,28 @@ class _Picker extends StatelessWidget {],),if (link case final link?)- SizedBox(- width: double.infinity,- child: Semantics(- button: true,- child: InkWell(- key: const ValueKey('swarm-copy-link'),- borderRadius: BorderRadius.circular(AppControl.radius),- onTap: () => _copy(context, link),- child: ConstrainedBox(- constraints: const BoxConstraints(- minHeight: minTouchTarget,- ),- child: Padding(- padding: EdgeInsets.fromLTRB(- AppSpace.m,- react ? AppSpace.m : AppSpace.s,- AppSpace.m,- AppSpace.s,- ),- child: Row(- children: [- Icon(- LucideIcons.link300,- size: 20,- color: AppPalette.textPrimary,- ),- const SizedBox(width: AppSpace.m),- Text(- 'Copy link to message',- style: AppType.body(- color: AppPalette.textPrimary,- ),- ),- ],- ),- ),- ),- ),- ),+ _Action(+ key: const ValueKey('swarm-copy-link'),+ icon: LucideIcons.link300,+ label: 'Copy link to message',+ top: react ? AppSpace.m : AppSpace.s,+ onTap: () => _copy(context, link),+ ),+ if (onEdit case final edit?)+ _Action(+ key: const ValueKey('swarm-edit-message'),+ icon: LucideIcons.pencil300,+ label: 'Edit message',+ onTap: () => _then(context, edit),+ ),+ if (onDelete case final delete?)+ _Action(+ key: const ValueKey('swarm-delete-message'),+ icon: LucideIcons.trash2300,+ label: 'Delete message',+ // Destructive: the red tuned as ink on a surface.+ color: AppColors.danger,+ onTap: () => _then(context, delete),),],),@@ -355,3 +362,59 @@ class _Picker extends StatelessWidget {);}}++/// One of the sheet's rows under the reactions: its icon and words, a+/// finger's height, the whole width to tap.+class _Action extends StatelessWidget {+ const _Action({+ super.key,+ required this.icon,+ required this.label,+ required this.onTap,+ this.color,+ this.top = AppSpace.s,+ });++ final IconData icon;+ final String label;+ final VoidCallback onTap;++ /// Its ink; the primary text's when null.+ final Color? color;++ /// The room above its words: more under the reactions.+ final double top;++ @override+ Widget build(BuildContext context) {+ final ink = color ?? AppPalette.textPrimary;+ return SizedBox(+ width: double.infinity,+ child: Semantics(+ button: true,+ child: InkWell(+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ child: Padding(+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ top,+ AppSpace.m,+ AppSpace.s,+ ),+ child: Row(+ children: [+ Icon(icon, size: 20, color: ink),+ const SizedBox(width: AppSpace.m),+ Text(label, style: AppType.body(color: ink)),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dartindex cf7a38f36..a1360c2f5 100644--- a/mobile/lib/swarm/swarm_thread.dart+++ b/mobile/lib/swarm/swarm_thread.dart@@ -185,7 +185,9 @@ class SwarmThread extends ChangeNotifierif (!identical(_madeFrom?.$1, _rows) ||!identical(_madeFrom?.$2, chatRows)) {final byId = {- for (final m in _rows) m.id: m,+ // A reply the chat found deleted goes from the thread too.+ for (final m in _rows)+ if (!chat.gone(m.id)) m.id: m,for (final m in chatRows)if (m.thread == root) m.id: m,};@@ -618,7 +620,27 @@ class SwarmThread extends ChangeNotifierreturn done;}- /// The thread's newest page again, over the rows read of it.+ /// Puts [text] in place of [message]'s ([SwarmConversation.editMessage]),+ /// then reads the thread's newest page again so it shows here at once.+ /// Answers why it was refused; null once done or when nothing changed.+ Future<String?> editMessage(SuperTabMessage message, String text) async {+ final refused = await chat.editMessage(message, text);+ if (refused == null && !_disposed && _read) await _reread();+ return refused;+ }++ /// Deletes [message] ([SwarmConversation.deleteMessage]), then reads the+ /// thread's newest page again: a reply leaves it. Answers why it was+ /// refused; null once done.+ Future<String?> deleteMessage(SuperTabMessage message) async {+ final refused = await chat.deleteMessage(message);+ if (refused == null && !_disposed && _read) await _reread();+ return refused;+ }++ /// The thread's newest page again, over the rows read of it: a reply it+ /// covers and no longer has was deleted, and goes. The root stays; deleted,+ /// it is the line its replies hang from.Future<void> _reread() async {final epoch = _epoch;try {@@ -635,9 +657,21 @@ class SwarmThread extends ChangeNotifierreturn;}final rows = {for (final m in _rows) m.id: m};+ final read = <SuperTabMessage>[];for (final row in answer['messages'] as List) {final m = SuperTabMessage.fromJson(superTabMap(row));- if (m.conversationId == chat.id && m.thread == root) rows[m.id] = m;+ if (m.conversationId == chat.id && m.thread == root) read.add(m);+ }+ final covers = answer['next'] == null+ ? 0+ : read.isEmpty+ ? null+ : read.map((m) => m.sequence).reduce((a, b) => a < b ? a : b);+ if (covers != null) {+ rows.removeWhere((id, m) => id != root && m.sequence >= covers);+ }+ for (final m in read) {+ rows[m.id] = m;}_rows = List.unmodifiable(rows.values.toList()..sort(superTabMessageOrder),diff --git a/mobile/test/swarm/swarm_message_edit_shots_test.dart b/mobile/test/swarm/swarm_message_edit_shots_test.dartnew file mode 100644index 000000000..2f75ed309--- /dev/null+++ b/mobile/test/swarm/swarm_message_edit_shots_test.dart@@ -0,0 +1,254 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_chat_cache.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/terminal/terminal_font_store.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of editing and deleting your own message (task #2746):+/// the long-press sheet with Edit message and Delete message, the edit+/// sheet, the delete question, and the chat with an "(edited)" row and a+/// deleted root that keeps its thread. On a 390-point phone in both phone+/// themes, from made-up data only, to the folder `SWARM_MESSAGE_EDIT_SHOTS`+/// names.+final shots = Platform.environment['SWARM_MESSAGE_EDIT_SHOTS'];++void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in {+ '.AppleSystemUIFont',+ 'Roboto',+ AppFont.sans,+ ...AppFont.sansFallback,+ }) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ final terminal = terminalFontStore.value;+ for (final family in {+ '.AppleSystemUIFontMonospaced',+ 'monospace',+ AppFont.mono,+ ...AppFont.monoFallback,+ terminal.fontFamily,+ ...terminal.fontFamilyFallback,+ }) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ Map<String, dynamic> row(+ String id,+ int sequence,+ String text, {+ String author = me,+ String? thread,+ String? editedAt,+ String? deletedAt,+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'thread': ?thread,+ 'editedAt': ?editedAt,+ 'deletedAt': ?deletedAt,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'tony'}+ : {'kind': 'agent', 'id': author, 'name': 'River'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 11, 4, 1, sequence).toIso8601String(),+ };++ testWidgets('Edit message, Delete message and the rows they leave, in both '+ 'phone themes', (tester) async {+ addTearDown(tester.view.reset);+ addTearDown(SwarmChatCache.clear);+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (_) async => null);+ addTearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null),+ );+ debugDisableShadows = false;+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ addTearDown(tester.view.resetPadding);+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ SwarmChatCache.clear();+ const size = Size(390, 844);+ tester.view+ ..physicalSize = size * 3+ ..devicePixelRatio = 3;+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login flake',+ number: 7,+ agentIds: ['agent-lead'],+ lastMessageSequence: 4,+ ),+ ],+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': [+ row(+ 'm4',+ 4,+ 'Can we ship the retry fix today? The flake shows on every '+ 'third run.',+ ),+ row(+ 'm3',+ 3,+ 'The login test waits for the banner now.',+ editedAt: DateTime.utc(2026, 11, 4, 2).toIso8601String(),+ ),+ row(+ 'm2',+ 2,+ 'This message was deleted.',+ thread: 'm2',+ deletedAt: DateTime.utc(2026, 11, 4, 2).toIso8601String(),+ ),+ row('m1', 1, 'Looking at the CI logs.', author: 'agent-lead'),+ ],+ 'next': null,+ 'reactionSeq': 0,+ 'threads': [+ {+ 'id': 'm2',+ 'replies': 2,+ 'lastSequence': 4,+ 'lastAt': DateTime.utc(2026, 11, 4, 1, 4).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ ],+ 'people': <String>[],+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': {'changed': true},+ };+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ )..foreground = false;+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: const Scaffold(+ body: SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ Future<void> capture(String name) async {+ await tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/message-edit-390-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ }++ expect(find.text('(edited)'), findsOneWidget);+ expect(find.text('This message was deleted.'), findsOneWidget);+ await capture('rows');++ await tester.longPress(find.textContaining('ship the retry fix'));+ await tester.pumpAndSettle();+ expect(find.text('Edit message'), findsOneWidget);+ await capture('sheet');++ await tester.tap(find.byKey(const ValueKey('swarm-edit-message')));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('swarm-edit-field')), findsOneWidget);+ await capture('edit');+ await tester.tap(find.byKey(const ValueKey('swarm-edit-cancel')));+ await tester.pumpAndSettle();++ await tester.longPress(find.textContaining('ship the retry fix'));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('swarm-delete-message')));+ await tester.pumpAndSettle();+ expect(find.text('Delete message?'), findsOneWidget);+ await capture('delete');+ await tester.tap(find.widgetWithText(FilledButton, 'Cancel'));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty);++ await tester.pumpWidget(const SizedBox());+ host.dispose();+ }+ debugDisableShadows = true;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_message_edit_test.dart b/mobile/test/swarm/swarm_message_edit_test.dartnew file mode 100644index 000000000..6f808e7a2--- /dev/null+++ b/mobile/test/swarm/swarm_message_edit_test.dart@@ -0,0 +1,678 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_chat_cache.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Editing and deleting your own message on the phone (task #2746, plan+/// Task 3): the long-press sheet offers Edit message and Delete message on the+/// person's own plain message alone, Edit opens its text to change, Delete+/// asks first, and the chat shows "(edited)" and "This message was deleted."+/// as the backend's rows say (`editedAt`, `deletedAt`).+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const commands = '/api/super-tabs/$tab/commands';+ const deleted = 'This message was deleted.';++ /// A row of chat g1: an agent's unless [author] is a person's id ([me] or+ /// `person-*`).+ Map<String, dynamic> message(+ String id,+ int sequence, {+ String text = 'hello',+ String author = me,+ String? thread,+ String? replyTo,+ String? editedAt,+ String? deletedAt,+ Map<String, dynamic>? source,+ List<Map<String, dynamic>> attachments = const [],+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'thread': ?thread,+ 'replyTo': ?replyTo,+ 'editedAt': ?editedAt,+ 'deletedAt': ?deletedAt,+ 'source': ?source,+ 'author': author.startsWith('person')+ ? {+ 'kind': 'person',+ 'id': author,+ 'name': author == me ? 'tony' : 'ann',+ }+ : {+ 'kind': 'agent',+ 'id': author,+ 'name': author == 'agent-lead' ? 'River' : 'Nova',+ },+ 'attachments': attachments,+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 11, 4, 1, sequence).toIso8601String(),+ };++ /// The line under thread root [id]: [replies] replies, the last at [last].+ Map<String, dynamic> line(String id, int replies, int last) => {+ 'id': id,+ 'replies': replies,+ 'lastSequence': last,+ 'lastAt': DateTime.utc(2026, 11, 4, 1, last).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ],+ 'people': <String>[],+ };++ /// One Swarm whose chat g1 reads [page] as its latest messages, with the+ /// lines of [threads]; [members] are who is in it, the reader an owner.+ FakeSwarm backend(+ List<Map<String, dynamic>> page, {+ List<Map<String, dynamic>> threads = const [],+ List<Map<String, dynamic>>? members,+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: page+ .map((m) => m['sequence'] as int)+ .fold(0, (a, b) => a > b ? a : b),+ ),+ ],+ ),+ 'members': [+ for (final member+ in members ?? [person(me), person('person-ann', role: 'member')])+ part(member['id'] as String, 1, member),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': null,+ 'threads': threads,+ 'reactionSeq': 0,+ };+ fake.routes[commands] = (_) => {+ 'result': {'changed': true},+ };+ return fake;+ }++ Future<SwarmHost> pump(WidgetTester tester, FakeSwarm fake) async {+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ final edit = key('swarm-edit-message');+ final delete = key('swarm-delete-message');++ setUp(() {+ // The long-press's light tap of the phone.+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (_) async => null);+ });+ tearDown(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null);+ SwarmChatCache.clear();+ });++ group('the long-press sheet', () {+ testWidgets('on your own message offers Edit message and Delete message '+ 'under Copy link to message', (tester) async {+ await pump(tester, backend([message('m1', 1, text: 'Plan')]));++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();++ expect(find.text('Edit message'), findsOneWidget);+ expect(find.text('Delete message'), findsOneWidget);+ final link = tester.getRect(key('swarm-copy-link'));+ expect(tester.getRect(edit).top, greaterThanOrEqualTo(link.bottom));+ expect(+ tester.getRect(delete).top,+ greaterThanOrEqualTo(tester.getRect(edit).bottom),+ );+ expect(tester.getSize(edit).height, greaterThanOrEqualTo(44));+ expect(tester.getSize(delete).height, greaterThanOrEqualTo(44));+ });++ testWidgets("never on an agent's message, another person's, or a note "+ 'the server wrote in your name', (tester) async {+ await pump(+ tester,+ backend([+ message('m1', 1, text: 'From Nova', author: 'agent-builder'),+ message('m2', 2, text: 'From Ann', author: 'person-ann'),+ message('m3', 3, text: 'Task root', source: {'kind': 'task-line'}),+ ]),+ );++ for (final text in ['From Nova', 'From Ann', 'Task root']) {+ await tester.longPress(find.text(text));+ await tester.pumpAndSettle();+ expect(key('swarm-copy-link'), findsOneWidget, reason: text);+ expect(edit, findsNothing, reason: text);+ expect(delete, findsNothing, reason: text);+ await tester.tapAt(const Offset(20, 20));+ await tester.pumpAndSettle();+ }+ });++ testWidgets('never for a person who may not write here', (tester) async {+ await pump(+ tester,+ backend(+ [message('m1', 1, text: 'Plan')],+ members: [person(me, role: 'viewer')],+ ),+ );++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();++ expect(key('swarm-copy-link'), findsOneWidget);+ expect(edit, findsNothing);+ expect(delete, findsNothing);+ });+ });++ group('Edit message', () {+ testWidgets('opens the text in a field; Save sends message.edit and the '+ 'chat shows the new text, edited', (tester) async {+ final fake = backend([message('m1', 1, text: 'Plan')]);+ fake.routes['$messages?before=2'] = (_) => {+ 'messages': [+ message(+ 'm1',+ 1,+ text: 'Plan B',+ editedAt: DateTime.utc(2026, 11, 4, 2).toIso8601String(),+ ),+ ],+ 'next': null,+ 'reactionSeq': 1,+ };+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ await tester.tap(edit);+ await tester.pumpAndSettle();++ final field = key('swarm-edit-field');+ expect(tester.widget<TextField>(field).controller!.text, 'Plan');+ await tester.enterText(field, ' Plan B \n');+ await tester.tap(key('swarm-edit-save'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {+ 'type': 'message.edit',+ 'conversationId': 'g1',+ 'messageId': 'm1',+ 'text': 'Plan B',+ },+ ]);+ expect(field, findsNothing, reason: 'the sheet closed');+ expect(find.text('Plan B'), findsOneWidget);+ expect(find.text('Plan'), findsNothing);+ expect(find.text('(edited)'), findsOneWidget);+ });++ testWidgets('Save with the text unchanged, or Cancel, sends nothing', (+ tester,+ ) async {+ final fake = backend([message('m1', 1, text: 'Plan')]);+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ await tester.tap(edit);+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-edit-save'));+ await tester.pumpAndSettle();+ expect(key('swarm-edit-field'), findsNothing);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ await tester.tap(edit);+ await tester.pumpAndSettle();+ await tester.enterText(key('swarm-edit-field'), 'Something else');+ await tester.tap(key('swarm-edit-cancel'));+ await tester.pumpAndSettle();++ expect(fake.commands, isEmpty);+ expect(find.text('Plan'), findsOneWidget);+ });++ testWidgets('a refusal says why at the foot and keeps the old text', (+ tester,+ ) async {+ final fake = backend([message('m1', 1, text: 'Plan')]);+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Only its author can change this message.',+ statusCode: 403,+ );+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ await tester.tap(edit);+ await tester.pumpAndSettle();+ await tester.enterText(key('swarm-edit-field'), 'Plan B');+ await tester.tap(key('swarm-edit-save'));+ await tester.pumpAndSettle();++ expect(fake.commands.single['type'], 'message.edit');+ expect(+ find.descendant(+ of: find.byType(SnackBar),+ matching: find.text('Only its author can change this message.'),+ ),+ findsOneWidget,+ );+ expect(find.text('Plan'), findsOneWidget);+ expect(find.text('(edited)'), findsNothing);+ });+ });++ group('Delete message', () {+ testWidgets('asks first: Cancel sends nothing', (tester) async {+ final fake = backend([message('m1', 1, text: 'Plan')]);+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ await tester.tap(delete);+ await tester.pumpAndSettle();++ expect(find.text('Delete message?'), findsOneWidget);+ expect(find.text("This can't be undone."), findsOneWidget);+ await tester.tap(find.widgetWithText(FilledButton, 'Cancel'));+ await tester.pumpAndSettle();++ expect(fake.commands, isEmpty);+ expect(find.text('Plan'), findsOneWidget);+ });++ testWidgets('Delete sends message.delete, and the page read again '+ 'without it drops the row', (tester) async {+ final fake = backend([+ message('m1', 1, text: 'Before', author: 'agent-builder'),+ message('m2', 2, text: 'Plan'),+ ]);+ fake.routes['$messages?before=3'] = (_) => {+ 'messages': [message('m1', 1, text: 'Before', author: 'agent-builder')],+ 'next': null,+ 'reactionSeq': 1,+ };+ // Nothing after it: the backend's newest stepped back (a Swarm read+ // still saying 2 reads on from what is shown).+ fake.routes['$messages?after='] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ 'reactionSeq': 1,+ };+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ await tester.tap(delete);+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Delete'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {'type': 'message.delete', 'conversationId': 'g1', 'messageId': 'm2'},+ ]);+ expect(find.text('Plan'), findsNothing);+ expect(key('swarm-message-m2'), findsNothing);+ expect(find.text('Before'), findsOneWidget);+ });++ testWidgets('in a thread: your own reply is deleted there, and goes', (+ tester,+ ) async {+ final fake = backend(+ [+ message('m1', 1, author: 'agent-lead', text: 'Root', thread: 'm1'),+ message('m2', 2, text: 'My reply', thread: 'm1', replyTo: 'm1'),+ ],+ threads: [line('m1', 1, 2)],+ );+ var thread = [+ message('m2', 2, text: 'My reply', thread: 'm1', replyTo: 'm1'),+ message('m1', 1, author: 'agent-lead', text: 'Root', thread: 'm1'),+ ];+ fake.routes['$messages?thread=m1'] = (_) => {+ 'messages': thread,+ 'next': null,+ 'threads': <Object>[],+ };+ fake.routes['$messages?before=3'] = (_) => {+ 'messages': [+ message('m1', 1, author: 'agent-lead', text: 'Root', thread: 'm1'),+ ],+ 'next': null,+ 'reactionSeq': 1,+ };+ // Nothing after it: the backend's newest stepped back (a Swarm read+ // still saying 2 reads on from what is shown).+ fake.routes['$messages?after='] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ 'reactionSeq': 1,+ };+ await pump(tester, fake);+ await tester.tap(key('swarm-thread-line-m1'));+ await tester.pumpAndSettle();++ final reply = find.descendant(+ of: key('swarm-thread-messages'),+ matching: find.text('My reply'),+ );+ await tester.longPress(reply);+ await tester.pumpAndSettle();+ thread = [+ message('m1', 1, author: 'agent-lead', text: 'Root', thread: 'm1'),+ ];+ await tester.tap(delete);+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Delete'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {'type': 'message.delete', 'conversationId': 'g1', 'messageId': 'm2'},+ ]);+ expect(reply, findsNothing);+ });+ });++ group('the rows', () {+ testWidgets('an edited message says so after its text', (tester) async {+ await pump(+ tester,+ backend([+ message(+ 'm1',+ 1,+ text: 'Plan B',+ author: 'agent-builder',+ editedAt: DateTime.utc(2026, 11, 4, 2).toIso8601String(),+ ),+ message('m2', 2, text: 'Untouched', author: 'agent-builder'),+ ]),+ );++ expect(+ find.descendant(+ of: key('swarm-message-m1'),+ matching: find.text('(edited)'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-message-m2'),+ matching: find.text('(edited)'),+ ),+ findsNothing,+ );+ final text = tester.widget<Text>(+ find.descendant(+ of: key('swarm-message-m1'),+ matching: find.text('(edited)'),+ ),+ );+ expect(text.style?.color, grid.AppPalette.textFaint);+ });++ testWidgets('a deleted message with replies reads "This message was '+ 'deleted." in faint italic, keeps its thread line, and opens no '+ 'sheet', (tester) async {+ final fake = backend(+ [+ message(+ 'm1',+ 1,+ text: deleted,+ thread: 'm1',+ deletedAt: DateTime.utc(2026, 11, 4, 2).toIso8601String(),+ ),+ ],+ threads: [line('m1', 2, 3)],+ );+ await pump(tester, fake);++ final words = find.descendant(+ of: key('swarm-message-m1'),+ matching: find.text(deleted),+ );+ expect(words, findsOneWidget);+ final style = tester.widget<Text>(words).style!;+ expect(style.fontStyle, FontStyle.italic);+ expect(style.color, grid.AppPalette.textFaint);+ expect(key('swarm-thread-line-m1'), findsOneWidget);++ await tester.longPress(words);+ await tester.pumpAndSettle();+ expect(key('swarm-copy-link'), findsNothing);+ expect(edit, findsNothing);+ expect(fake.commands, isEmpty);+ });+ });++ // The chat as a reader holds it (swarm_conversation.dart): a page read again+ // when the reaction counter moves is the backend's word on the messages in+ // it, so one it no longer has is gone, here and in the chat kept for the+ // next open.+ group('a page read again', () {+ ({FakeSwarm swarm, SwarmReader reader}) rig() {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 3,+ ),+ ],+ ),+ 'members': [part(me, 1, person(me))],+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2');+ swarm.routes[messages] = (_) => {+ 'messages': [+ message('m3', 3, text: 'Third'),+ message('m2', 2, text: 'Second', author: 'person-ann'),+ message('m1', 1, text: 'First'),+ ],+ 'next': null,+ 'reactionSeq': 0,+ };+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ addTearDown(reader.dispose);+ return (swarm: swarm, reader: reader);+ }++ /// g1 with its reaction counter at [reactionSeq], as a change read+ /// brings it.+ Map<String, dynamic> moved(int version, int reactionSeq) => changes(+ cursor: 'c$version',+ groups: [+ part('g1', version, {+ ...groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 3,+ ),+ 'reactionSeq': reactionSeq,+ }),+ ],+ );++ List<String> texts(SwarmConversation c) => [+ for (final m in c.messages) m.text,+ ];++ test('without a message drops it, and takes an edited text over the '+ 'old one', () async {+ final r = rig();+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ await c.load();+ expect(texts(c), ['First', 'Second', 'Third']);++ r.swarm.routes['$messages?before=4'] = (_) => {+ 'messages': [+ message(+ 'm3',+ 3,+ text: 'Third, fixed',+ editedAt: DateTime.utc(2026, 11, 4, 2).toIso8601String(),+ ),+ message('m1', 1, text: 'First'),+ ],+ 'next': null,+ 'reactionSeq': 2,+ };+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => moved(30, 2);+ await r.reader.refresh();+ await settle();++ expect(texts(c), ['First', 'Third, fixed']);+ expect(c.messages.last.editedAt, DateTime.utc(2026, 11, 4, 2));+ });++ test('without a message, a chat opened again from what was kept does not '+ 'bring it back', () async {+ final r = rig();+ await r.reader.refresh();+ var c = SwarmConversation(r.reader, 'g1');+ await c.load();+ c.dispose();++ r.swarm.routes['$messages?after=3'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ 'reactionSeq': 2,+ };+ r.swarm.routes['$messages?before=4'] = (_) => {+ 'messages': [+ message('m3', 3, text: 'Third'),+ message('m1', 1, text: 'First'),+ ],+ 'next': null,+ 'reactionSeq': 2,+ };+ c = SwarmConversation(r.reader, 'g1');+ await c.load();+ await settle();+ expect(texts(c), ['First', 'Third']);+ c.dispose();++ c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ expect(texts(c), ['First', 'Third'], reason: 'kept as read again');+ });++ test('that has more before it drops only what it covers', () async {+ final r = rig();+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ await c.load();++ // A page of one: m1 and m2 are before it, not gone.+ r.swarm.routes['$messages?before=4'] = (_) => {+ 'messages': [message('m3', 3, text: 'Third')],+ 'next': {'sequence': 3, 'id': 'm3'},+ 'reactionSeq': 2,+ };+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => moved(30, 2);+ await r.reader.refresh();+ await settle();++ expect(texts(c), ['First', 'Second', 'Third']);+ });+ });++ group('the model', () {+ test('reads editedAt and deletedAt', () {+ final m = SuperTabMessage.fromJson(+ message(+ 'm1',+ 1,+ text: deleted,+ editedAt: '2026-11-04T02:00:00.000Z',+ deletedAt: '2026-11-04T03:00:00.000Z',+ ),+ );+ expect(m.editedAt, DateTime.utc(2026, 11, 4, 2));+ expect(m.deletedAt, DateTime.utc(2026, 11, 4, 3));+ expect(m.deleted, isTrue);+ expect(SuperTabMessage.fromJson(message('m2', 2)).deleted, isFalse);+ });+ });+}