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 10-29 ah: 3 reviewed PRs (#2168, #2225, #2163) (#2229)
0xken152a0a936775fb
diff --git a/backend/integration/superTabBuddyProbes.test.ts b/backend/integration/superTabBuddyProbes.test.tsindex 0ce735d3c..358f7e708 100644--- a/backend/integration/superTabBuddyProbes.test.ts+++ b/backend/integration/superTabBuddyProbes.test.ts@@ -11,6 +11,7 @@ import { SuperTabStore } from '../src/superTabs/store.js'import type { Command } from '../src/superTabs/commands.js'import { poolRows } from './hostRows.test-support.js'import { SwarmReads } from '../src/superTabs/read/service.js'+import { stableId } from '../src/superTabs/model.js'// Security review 1 of #2115: its two-person probes, kept as regressions. The three that showed a leak at db0379898// (routing history, archived tasks awaiting a report, sequence-only paging) now assert the fix; the rest are as written.@@ -205,3 +206,137 @@ it('reads a machine leaving the Swarm without its name, in the project chat andexpect(seen.find(m => m.id === removed.id)!.text).toMatch(/^owner removed a machine from the Swarm, and \S+ with it\.$/)expect(JSON.stringify(seen)).not.toContain('OWNER-STUDIO-HOST')})++// Threads (Batch X) through a Buddy's reads, the security reviewer's three cases on the merge of #2115 (Lead, 10-29).+describe('a Buddy and threads', () => {+ const send = (f: Awaited<ReturnType<typeof swarm>>, conversationId: string, text: string, replyTo: string | null = null, user = owner, as?: string) =>+ f.execute({ type: 'message.send', conversationId, text, replyTo, recipientIds: [] }, user, as).then(r => String(r.result.messageId))++ it('reads no thread of a private chat, its root or its replies, though its person still has them on record', async () => {+ // Closed as a Chat with PM before anyone reads the Swarm: the fixture edits the stored row, which no cached read sees.+ const f = await swarm()+ const chat = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Private thread', brief: '', checks: [] })).result.conversationId)+ const root = await send(f, chat, 'PRIVATE ROOT SENTINEL')+ await send(f, chat, 'PRIVATE REPLY SENTINEL', root)+ await closedPmChat(f, chat, [owner.sub, peer.sub])+ const { agentId } = await buddy(f)+ for (const cursor of [{}, { thread: root }, { messageId: root }]) {+ await expect(f.store.messages(peer, f.tab, chat, cursor, agentId)).rejects.toThrow('unavailable')+ }+ const read = await new SwarmReads(f.store).firstLoad(peer, f.tab, agentId)+ expect(JSON.stringify(read)).not.toMatch(/PRIVATE (ROOT|REPLY) SENTINEL/)+ expect(read.groups.map(g => g.key)).not.toContain(chat)+ })++ it('reads no thread in another person\'s Buddy chat', async () => {+ const f = await swarm(), { agentId } = await buddy(f)+ // The owner's own Buddy, on their own Swarm machine, opens their Buddy chat.+ await f.execute({ type: 'machine.contribute', machineId: 'owner-mac', name: 'Owner Mac', cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 2 })+ const gen = (await poolRows(f.store, owner, 'owner-mac')).find(p => p.tabId === f.tab)!.machine.generation+ await f.store.observeMachine(owner, f.tab, 'owner-mac', { generation: gen, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })+ const ownersChat = String((await f.execute({ type: 'buddy.create', projectId: 'lead', machineId: 'owner-mac', engine: 'claude' })).result.conversationId)+ const root = await send(f, ownersChat, 'OWNER BUDDY ROOT')+ await send(f, ownersChat, 'OWNER BUDDY REPLY', root)+ for (const cursor of [{}, { thread: root }, { messageId: root }]) {+ await expect(f.store.messages(peer, f.tab, ownersChat, cursor, agentId)).rejects.toThrow('unavailable')+ }+ const read = await new SwarmReads(f.store).firstLoad(peer, f.tab, agentId)+ expect(read.groups.map(g => g.key)).not.toContain(ownersChat)+ expect(JSON.stringify(read)).not.toMatch(/OWNER BUDDY (ROOT|REPLY)/)+ })++ it('reads the replies to a route row as people wrote them, never the route row, its id or its thread line', async () => {+ const f = await swarm(), { agentId } = await buddy(f)+ const group = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Routed task', brief: '', checks: [] })).result.conversationId)+ const decision: any = { assessment: { difficulty: 'low', risk: 'low', why: 'Small task' },+ candidates: [{ id: 'c0', kind: 'new', machineId: 'owner-mac', engine: 'claude', model: 'fixture-model', effort: 'high', quality: 2, cost: 2,+ title: 'Engineer · Claude fixture-model high · OWNER-PRIVATE-HOST', label: 'Candidate on OWNER-PRIVATE-HOST' }],+ excluded: [], floor: 1, notes: false, pick: 'c0', via: 'only', p: null, belowFloor: false, why: 'Only candidate' }+ await f.execute({ type: 'route.record', conversationId: group, decision }, owner, f.lead)+ const route = (await f.store.messages(owner, f.tab, group, {}, f.lead)).messages.find(m => (m.source as { kind?: string } | null)?.kind === 'route')!+ const reply = await send(f, group, 'Agreed, go ahead.', route.id)+ // A reply from before threads names what it answered and nothing else.+ const legacy = `legacy-${randomUUID()}`+ await db.superTabMessage.create({ data: { id: legacy, tabId: f.tab, conversationId: group, sequence: 900,+ author: { kind: 'person', id: owner.sub, name: owner.email }, text: 'Old reply to the route.', replyTo: route.id, recipientIds: [] } })+ // The PM sees the route row as a thread root with its reply.+ const pm = await f.store.messages(owner, f.tab, group, {}, f.lead)+ expect(pm.threads.map(t => t.id)).toContain(route.id)++ const seen = await f.store.messages(peer, f.tab, group, {}, agentId)+ expect(seen.messages.map(m => m.id)).toContain(reply)+ expect(seen.messages.map(m => m.id)).not.toContain(route.id)+ expect(seen.threads.map(t => t.id)).not.toContain(route.id)+ // The reply reads as a message of its own: no pointer to the row the Buddy may not read.+ expect(seen.messages.find(m => m.id === reply)!.thread ?? null).toBeNull()+ // Its thread reads like a message it may not read and like a thread that is not there: an empty page (review 2 of #2168).+ const empty = { messages: [], next: null, threads: [] }+ expect(await f.store.messages(peer, f.tab, group, { thread: route.id }, agentId)).toMatchObject(empty)+ expect(await f.store.messages(peer, f.tab, group, { thread: 'invented-root' }, agentId)).toMatchObject(empty)+ expect((await f.store.messages(owner, f.tab, group, { thread: route.id }, f.lead)).messages.map(m => m.id)).toEqual([route.id, reply])+ expect(seen.messages.find(m => m.id === legacy)!.replyTo).toBeNull()+ // Nothing names the route row: not a reply's thread or reply-to, not a reply line (review 1 of #2168).+ expect(JSON.stringify(seen)).not.toContain(route.id)+ expect(JSON.stringify(seen)).not.toContain('OWNER-PRIVATE-HOST')+ })+})++// Every reader (review 1 of #2168): a reply to a row the reader may not see, an agent-only note here, names nothing of it.+// Merged with #2177 (main): a new reply to a notice only its recipients read is saved in the chat, not the notice's thread,+// for every reader (commands.ts). The read-side rule still covers a reply saved in such a thread earlier.+it('gives no reader a pointer to, or reply line for, an agent-only note it may not see; its recipient keeps them', async () => {+ const f = await swarm(), { agentId } = await buddy(f)+ // The Lead's note to itself in the project chat, then its own reply to that note.+ const note = String((await f.execute({ type: 'message.send', conversationId: 'lead', text: 'AGENT ONLY NOTE', replyTo: null,+ recipientIds: [f.lead], agentOnly: true }, owner, f.lead)).result.messageId)+ const reply = String((await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Following up on my note.', replyTo: note,+ recipientIds: [] }, owner, f.lead)).result.messageId)+ // A reply saved in the note's thread before #2177 kept such replies in the chat.+ const sent = (await db.superTabMessage.findUnique({ where: { id: reply } }))!+ const earlier = randomUUID().replaceAll('-', '').slice(0, 24)+ await db.superTabMessage.create({ data: { id: earlier, tabId: f.tab, conversationId: 'lead', sequence: sent.sequence + 1,+ author: sent.author as object, text: 'An earlier follow-up.', replyTo: note, thread: note, recipientIds: [], mentions: [] } })++ const lead = await f.store.messages(owner, f.tab, 'lead', {}, f.lead)+ const leadReply = lead.messages.find(m => m.id === reply)!+ expect(leadReply.thread ?? leadReply.id).toBe(reply)+ expect(leadReply.replyTo).toBe(note)+ expect(lead.messages.find(m => m.id === earlier)).toMatchObject({ thread: note, replyTo: note })+ expect(lead.threads.map(t => t.id)).toContain(note)+ expect((await f.store.messages(owner, f.tab, 'lead', { thread: note }, f.lead)).messages.map(m => m.id)).toEqual([note, earlier])+ for (const [user, as] of [[owner, undefined], [peer, agentId]] as const) {+ const read = await f.store.messages(user, f.tab, 'lead', {}, as)+ const shown = read.messages.find(m => m.id === reply)!+ expect(shown.thread ?? shown.id).toBe(reply)+ expect(shown.replyTo).toBeNull()+ expect(read.messages.find(m => m.id === earlier)).toMatchObject({ thread: null, replyTo: null })+ expect(JSON.stringify(read)).not.toContain(note)+ expect(await f.store.messages(user, f.tab, 'lead', { thread: note }, as)).toMatchObject({ messages: [], next: null, threads: [] })+ }+})++// Delta check of the #2168 merge: a task chat's copy of a lost-task notice stored before #2177 marked such copies, whose+// Lead copy reached the PM, is read by no one (pageReads.ts deliveredCopies). Its thread reads as an invented root's for+// every reader, so a page never shows the hidden notice's earlier replies, nor that its thread exists.+it('reads the thread of a hidden task chat copy of a Lead notice as an invented root, for people, the PM and a Buddy', async () => {+ const f = await swarm(), { agentId } = await buddy(f)+ const group = String((await f.execute({ type: 'conversation.create', projectId: 'lead', title: 'Copy probe', brief: '', checks: [] })).result.conversationId)+ const last = await db.superTabMessage.findFirst({ where: { tabId: f.tab }, orderBy: { sequence: 'desc' } })+ const sequence = (last?.sequence ?? 0) + 1, author = { kind: 'agent', id: f.lead, name: 'PM' }+ const copy = randomUUID().replaceAll('-', '').slice(0, 24), earlier = randomUUID().replaceAll('-', '').slice(0, 24)+ await db.superTabMessage.createMany({ data: [+ { id: copy, tabId: f.tab, conversationId: group, sequence, author, text: 'COPY OF A LOST TASK NOTICE', replyTo: null, thread: copy,+ recipientIds: [], mentions: [], source: { kind: 'work-lost' } },+ { id: stableId(copy, 'lead'), tabId: f.tab, conversationId: 'lead', sequence, author, text: 'COPY OF A LOST TASK NOTICE', replyTo: null,+ thread: stableId(copy, 'lead'), recipientIds: [f.lead], mentions: [], source: { kind: 'work-lost' } },+ { id: earlier, tabId: f.tab, conversationId: group, sequence: sequence + 1, author: { kind: 'person', id: owner.sub, name: owner.email },+ text: 'EARLIER REPLY UNDER THE COPY', replyTo: copy, thread: copy, recipientIds: [], mentions: [] }] })++ for (const [user, as] of [[owner, undefined], [owner, f.lead], [peer, agentId]] as const) {+ const invented = await f.store.messages(user, f.tab, group, { thread: 'a'.repeat(24) }, as)+ expect(invented).toMatchObject({ messages: [], next: null, threads: [] })+ expect(await f.store.messages(user, f.tab, group, { thread: copy }, as)).toEqual(invented)+ }+})diff --git a/backend/integration/superTabIndexes.test.ts b/backend/integration/superTabIndexes.test.tsindex 49108cd85..d41752020 100644--- a/backend/integration/superTabIndexes.test.ts+++ b/backend/integration/superTabIndexes.test.ts@@ -118,7 +118,7 @@ describe('message page reads', () => {expect(threads).toHaveLength(130)expect(threads.filter(row => row.id !== row.thread).map(row => row.id).slice(0, 3)).toEqual(['t0-m100-r1', 't0-m100-r2', 't0-m100-r3'])expect(threads[0]).toEqual({ thread: 't0-m100', id: 't0-m100', author: expect.objectContaining({ id: 'owner' }), mentions: [],- sequence: 400, createdAt: new Date(T0 + 400_000), agentOnly: false })+ sequence: 400, createdAt: new Date(T0 + 400_000), agentOnly: false, routing: false })expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, conversationId: 1, thread: 1, sequence: 1 }'], docsExamined: 130, returned: 130 })})diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex c5704593f..ee32ce229 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -102,13 +102,41 @@ describe('a worker left idle', () => {const member = await f.member()expect(member.workDecision).toBe('stop')expect((await rosterRows(f.timed, host, 'test-host')).find(r => r.agent.id === f.worker)!.agent).toMatchObject({ releaseId: member.releaseId })- expect(await f.lines()).toEqual([expect.objectContaining({ conversationId: f.group, recipientIds: [], text: 'Worker stopped: no work for 15 minutes.' })])+ expect(await f.lines()).toEqual([expect.objectContaining({ conversationId: f.group, recipientIds: [f.lead], text: 'Worker stopped: no work for 15 minutes.' })])// A second poll finds it already stopping and writes nothing more.f.clock.now += MINUTEawait f.timed.deliveries(host, f.tab, f.lead)expect(await f.lines()).toHaveLength(1)})+ // Ken, 2026-10-29: the stop is the Lead's to handle. Its line wakes the Lead in that same poll, and no person, nor the+ // stopped worker, reads it in the task's chat or the project chat, or by its id; with the Lead outside the task's chat it+ // hears in its own, and the task's copy is no one's.+ it('wakes the Lead with its line, which no person or other agent reads in the task chat or the project chat', async () => {+ for (const leadInTask of [true, false]) {+ const f = await swarm()+ if (!leadInTask) await f.execute({ type: 'conversation.agent', conversationId: f.group, agentId: f.lead, present: false, lead: false })+ f.clock.now += 15 * MINUTE + 1_000+ await f.observe('test-host', [f.harness.worker], { harnessUncommitted: { [f.harness.worker]: false } })+ const inbox = await f.timed.deliveries(host, f.tab, f.lead)+ const lines = await f.lines()+ const written = leadInTask ? [[f.group, [f.lead]]] : [[f.group, []], ['lead', [f.lead]]]+ expect(lines.map(m => [m.conversationId, m.recipientIds])).toEqual(expect.arrayContaining(written))+ expect(lines).toHaveLength(written.length)+ const heard = lines.find(m => m.recipientIds.includes(f.lead))!+ expect(inbox.map(d => d.messageId)).toContain(heard.id)+ const page = async (user: AuthUser, conversationId: string, query: { messageId?: string } = {}, asAgentId?: string) =>+ (await f.timed.messages(user, f.tab, conversationId, query, asAgentId)).messages.map(m => m.id)+ expect(await page(host, heard.conversationId, {}, f.lead)).toContain(heard.id)+ const ids = lines.map(m => m.id)+ for (const user of [owner, host]) {+ for (const conversationId of [f.group, 'lead']) expect((await page(user, conversationId)).filter(id => ids.includes(id))).toEqual([])+ for (const m of lines) expect(await page(user, m.conversationId, { messageId: m.id })).toEqual([])+ }+ expect((await page(host, f.group, {}, f.worker)).filter(id => ids.includes(id))).toEqual([])+ }+ })+it('is kept while its host reports uncommitted changes, or does not say', async () => {const f = await swarm()f.clock.now += 20 * MINUTE@@ -266,6 +294,18 @@ describe('a review the Swarm opens by itself', () => {expect(queued.map(d => d.conversationId)).toContain(review.id)const leadLine = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, conversationId: review.id, text: { startsWith: 'Review opened by itself' } } })expect(leadLine.text).toBe('Review opened by itself for #2: Reviewer reviews it. Cancel it here if it is not needed.')+ // The Lead's wake (review of #2225): delivered to the Lead and read by it alone; people and the Reviewer read the brief only.+ expect(leadLine.recipientIds).toEqual([f.lead])+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: leadLine.id } })).map(d => d.agentId)).toEqual([f.lead])+ const page = async (user: AuthUser, asAgentId?: string, messageId?: string) =>+ (await f.timed.messages(user, f.tab, review.id, messageId ? { messageId } : {}, asAgentId)).messages.map(m => m.id)+ expect(await page(host, f.lead)).toContain(leadLine.id)+ for (const user of [owner, host]) {+ expect(await page(user)).not.toContain(leadLine.id)+ expect(await page(user, undefined, leadLine.id)).toEqual([])+ }+ expect(await page(host, reviewer)).not.toContain(leadLine.id)+ expect((await page(owner)).length).toBeGreaterThan(0)await f.execute({ type: 'work.cancel', conversationId: review.id, assignmentId: review.assignment!.id, reason: 'Not needed' })await f.execute({ type: 'conversation.archive', conversationId: review.id, archived: true })expect((await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === review.id)?.archived ?? true).toBe(true)diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex b6cf2a1d7..fea613058 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -2136,9 +2136,11 @@ describe('Super Tabs on a real Mongo replica set', () => {const first = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as stringconst second = (await run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).result.routeDecisionId as stringexpect((await store.routeDecision(owner, tab, first)).outcome).toBe('superseded')- const rows = (await store.messages(owner, tab, 'lead', {})).messages+ const rows = await db.superTabMessage.findMany({ where: { tabId: tab, conversationId: 'lead' }, orderBy: { sequence: 'asc' } })expect(rows.at(-1)).toMatchObject({ text: expect.stringContaining('"A small API change."'),source: { kind: 'route', decisionId: second, via: 'order', fallback: 'unsure', why: 'A small API change.' } })+ // The Lead's ruling, 2026-10-29: routing in the project chat is agent bookkeeping, read by no one there (commands.ts).+ expect((await store.messages(owner, tab, 'lead', {})).messages.map(m => m.id)).not.toContain(rows.at(-1)!.id)await expect(run(tab, { type: 'route.override', decisionId: first, candidateId: 'c1', reason: 'Needs Opus.' } as Command)).rejects.toMatchObject({ code: 'ROUTE_CLOSED' })await run(tab, { type: 'route.override', decisionId: second, candidateId: 'c1', reason: 'Needs Opus.' } as Command)@@ -3035,10 +3037,13 @@ describe('Leads conversation', () => {host, lead)).result.conversationId)await run(tab, { type: 'work.define', conversationId: filter, task: task(['desktop/lib/super_tabs']), checks }, host, lead)const leads = (await store.read(owner, tab)).state.leadsConversationId!- const alerts = (await store.messages(owner, tab, leads, {})).messages+ const alerts = await db.superTabMessage.findMany({ where: { tabId: tab, conversationId: leads } })expect(alerts).toEqual([expect.objectContaining({ source: { kind: 'overlap', conversationIds: [filter, roster] }, recipientIds: [docsLead],text: expect.stringContaining('"Agents filter" (Pilot') })])expect((await store.deliveries(host, tab, docsLead)).filter(d => d.conversationId === leads)).toHaveLength(1)+ // The two Leads' to settle (Ken, 2026-10-29): the Lead it reaches reads it; people in the Leads chat do not.+ expect((await store.messages(host, tab, leads, {}, docsLead)).messages.map(m => m.id)).toContain(alerts[0]!.id)+ expect((await store.messages(owner, tab, leads, {})).messages.map(m => m.id)).not.toContain(alerts[0]!.id)})})diff --git a/backend/src/superTabs/autoReview.ts b/backend/src/superTabs/autoReview.tsindex 73d3cbb5e..d7df39d14 100644--- a/backend/src/superTabs/autoReview.ts+++ b/backend/src/superTabs/autoReview.ts@@ -1,6 +1,6 @@import { githubRepository } from '../github/repository.js'import { agentDisplayName } from './agentNames.js'-import { activeWork, agentRole, nextConversationNumber, renderWorkTask, stableId, type Agent, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { activeWork, agentRole, forRecipients, nextConversationNumber, renderWorkTask, stableId, type Agent, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, groupProject, skillSetOf } from './projects.js'import { recordAsked, recordRun } from './leaderboard/record.js'import { renewLease } from './liveness.js'@@ -113,8 +113,8 @@ export function openReview(state: SuperTabState, group: Conversation, handoff: schecks: [{ description: VERDICT_CHECK, independent: false, id: stableId(id, '0'), evidence: null, passedBy: null }] }state.conversations.push(review)recordAsked(review, group.requesterId, context.now)- const row = (key: string, text: string, recipients: string[]): MessageDraft => ({ id: stableId(context.operationId, 'auto-review', key),- conversationId: id, author, text, replyTo: null, recipients, source: { kind: 'auto-review', reviewOf: group.id } })+ const row = (key: string, text: string, recipients: string[], source: Record<string, unknown> = { kind: 'auto-review', reviewOf: group.id }): MessageDraft =>+ ({ id: stableId(context.operationId, 'auto-review', key), conversationId: id, author, text, replyTo: null, recipients, source })const messages = [row('brief', brief, [])]if (reviewer) {review.agentIds.push(reviewer.id)@@ -130,6 +130,8 @@ export function openReview(state: SuperTabState, group: Conversation, handoff: sconst name = reviewer && (reviewer.displayName ?? reviewer.name)if (leadId) messages.push(row('lead', reviewer? `Review opened by itself for #${group.number}: ${name} reviews it. Cancel it here if it is not needed.`- : `Review opened by itself for #${group.number}, but no Reviewer is free. Route it and start one.`, [leadId]))+ : `Review opened by itself for #${group.number}, but no Reviewer is free. Route it and start one.`, [leadId],+ // The Lead's wake, its alone (review of #2225): people read the review's brief and its status.+ forRecipients({ kind: 'auto-review', reviewOf: group.id })))return { review, reviewer, messages }}diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 58720a91b..9359ba7b2 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -531,7 +531,8 @@ describe('a Buddy is never a worker', () => {group(f, f.chat).agentIds.push('builder')Object.assign(f.state.machines![0]!.observation!, { receivedAt: now, runningHarnessIds: ['buddy-harness', 'builder-harness'],harnessUncommitted: { 'buddy-harness': false, 'builder-harness': false } })- expect(stopIdleWorkers(f.state, f.app.projectId, now, new Set()).map(row => row.source)).toEqual([{ kind: 'idle-stop', agentId: 'builder' }])+ // Its line, and the Lead's copy in its own chat (tidy.ts), name only the Engineer.+ expect([...new Set(stopIdleWorkers(f.state, f.app.projectId, now, new Set()).map(row => row.source?.agentId))]).toEqual(['builder'])expect(buddy.workDecision).toBeUndefined()})})diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 9bd2d180f..ba90f0270 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -3,7 +3,7 @@ import { applyCommand, commandSchema, PAIR_CHAIN_LIMIT, swarmGridName, withoutCrimport { CREDENTIAL_MARKER, type CredentialKind } from './credentials.js'import { sweepLiveness } from './liveness.js'import { hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'-import { activeWork, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'+import { activeWork, agentOnly, agentRole, createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'import type { RouteDecision } from './routeRecord.js'import { startFinished } from './parts/write.js'import { agentTarget, broken } from './rules.js'@@ -715,6 +715,50 @@ describe('the Lead\'s last action on a task', () => {})})+// The Lead's ruling, 2026-10-29: the project chat and the Leads chat carry only what people read or decide on, and agent+// bookkeeping (routing, an agent joined or ready) is no one's there; a task's chat keeps it as its record.+describe('agent bookkeeping in the chats people read', () => {+ const shown = (row: { source?: Record<string, unknown>; recipients: string[] }) => !agentOnly(row.source, row.recipients)+ const open = (patch: Record<string, unknown> = {}) => ({ id: 'd1', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null, ...patch }) as unknown as RouteDecision++ it('keeps routing lines out of the project chat, and in a task\'s chat as its record', () => {+ const f = routed(), group = f.group()+ const routing = (conversationId: string) => f.run({ type: 'route.record', conversationId, decision: record() } as Command, f.leadActor, {}).messages+ expect(routing('lead').map(shown)).toEqual([false])+ expect(routing(group).map(shown)).toEqual([true])+ // The Lead choosing otherwise than its route, on a start or an assignment.+ const request = { conversationId: 'lead', machineId: 'machine', engine: 'claude', model: 'sonnet', effort: 'high', name: 'Builder', cwd: '/repo', worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const started = f.run({ type: 'agent.start', request, routeDecisionId: 'd1', overrideReason: 'Sonnet is enough here.' }, f.leadActor, { routeDecision: open(), contribution: f.contribution })+ expect(started.messages.filter(m => m.text.startsWith('Lead started')).map(shown)).toEqual([false])+ f.define(group)+ const assigned = f.run({ type: 'work.assign', conversationId: group, agentId: f.worker, routeDecisionId: 'd1', overrideReason: 'It knows the code.' }, f.leadActor,+ { routeDecision: open({ conversationId: group }) })+ expect(assigned.messages.filter(m => m.text.startsWith('Lead assigned')).map(shown)).toEqual([true])+ // A person's choice is theirs to read wherever it is written.+ const decision = { id: 'd2', conversationId: 'lead', record: record(), final: null, override: null, assignmentId: null, outcome: null } as unknown as RouteDecision+ expect(f.run({ type: 'route.override', decisionId: 'd2', candidateId: 'c1', reason: 'Quota.' }, undefined, { routeDecision: decision }).messages.map(shown)).toEqual([true])+ })++ it('keeps an agent\'s joined and ready lines out of the project chat, and in a task\'s chat', () => {+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()+ const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }+ const contribution = { machineOwnerId: 'target-owner', contributorId: 'owner', hostGrant: 'grant-1' }+ const lines = (conversationId: string, harnessId: string) => {+ const request = { conversationId, machineId: 'host', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,+ requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }+ const startId = f.run({ type: 'agent.start', request, ...via }, actor, { contribution, ...decisionIn(conversationId) }).result.startId as string+ f.run({ type: 'agent.startDispatch', startId }, actor, { contribution })+ f.state.starts!.find(s => s.id === startId)!.poolGeneration = 'pool-1'+ const joined = f.run({ type: 'agent.started', startId, harnessId, configuration: { ...config, engine: 'claude' } }, actor, { contribution }).messages+ const ready = f.run({ type: 'agent.startSettled', startId, warning: null }, actor, { contribution }).messages+ return [...joined, ...ready].map(m => [m.text, shown(m)])+ }+ expect(lines('lead', 'in-lead')).toEqual([['Builder joined. Preparing its model.', false], ['Builder is ready for an assignment.', false]])+ expect(lines(group, 'in-task')).toEqual([['Builder joined. Preparing its model.', true], ['Builder is ready for an assignment.', true]])+ })+})+describe('route.record and route.override', () => {it('records a lead decision as a route message with its id', () => {const f = routed()@@ -1527,6 +1571,9 @@ describe('Reviewer role', () => {expect(toReviewer.text).toBe(`${review.brief}\n\nAcceptance checks:\n- Verdict with the reviewed revision`)const toLead = effects.messages.filter(m => m.conversationId === review.id && m.recipients.includes(lead))expect(toLead.map(m => m.text)).toEqual(['Review opened by itself for #1: Second reviewer reviews it. Cancel it here if it is not needed.'])+ // The Lead's wake is its alone (review of #2225); the review's brief and its Reviewer's assignment stay the people's record.+ expect(effects.messages.filter(m => m.conversationId === review.id).map(m => [m.recipients, agentOnly(m.source, m.recipients)]))+ .toEqual([[[], false], [[fresh], false], [[lead], true]])// Every row of it is the Swarm's own, written as the project's Lead as its other notices are, never as the Engineer.expect(effects.messages.filter(m => m.conversationId === review.id).map(m => [m.author.kind, m.author.id, m.source?.kind])).toEqual([['agent', lead, 'auto-review'], ['agent', lead, 'auto-review'], ['agent', lead, 'auto-review']])@@ -1595,8 +1642,8 @@ describe('Reviewer role', () => {for (const id of [reviewer, fresh]) f.run({ type: 'agent.release', agentId: id, decision: 'stop' }, leadActor)const effects = markReady(`Ready. ${pr}`)expect(reviews()[0]!.assignment).toBeNull()- expect(effects.messages.filter(m => m.recipients.includes(lead) && m.conversationId === reviews()[0]!.id).map(m => m.text))- .toEqual(['Review opened by itself for #1, but no Reviewer is free. Route it and start one.'])+ expect(effects.messages.filter(m => m.recipients.includes(lead) && m.conversationId === reviews()[0]!.id).map(m => [m.text, agentOnly(m.source, m.recipients)]))+ .toEqual([['Review opened by itself for #1, but no Reviewer is free. Route it and start one.', true]])})it('gives a delta review to the Reviewer of the earlier head while it is still free', () => {@@ -2864,6 +2911,8 @@ describe('other projects\' work for Leads', () => {const alert = created.messages.find(m => m.conversationId === alerts())!expect(alert).toMatchObject({ author: { id: lead }, recipients: [docs.lead],source: { kind: 'overlap', conversationIds: [group, roster.group] } })+ // The two Leads' to settle (Ken, 2026-10-29): people in the Leads chat do not read it.+ expect(agentOnly(alert.source, alert.recipients)).toBe(true)expect(alert.text).toBe(`"Agents filter" (Pilot, ${name(lead)}) and "Roster" (Docs, ${name(docs.lead)}) both change `+ 'desktop/lib/super_tabs/roster.dart. Agree an order or a split here, then each tell your own project.')// The same pair is not alerted again.@@ -3468,6 +3517,11 @@ describe('stepping up from a cheap model', () => {expect(new Set(effects.messages.map(m => m.id)).size).toBe(effects.messages.length)expect(effects.messages.find(m => m.recipients.includes(f.lead))!.text).toBe(`#${g().number} stepped up to attempt 2: its first review said Ready no. Route it again: the route leaves out models on the grid and below quality 2, and the new attempt's brief carries the branch, the last result and the findings.`)+ // Ken, 2026-10-29: each its recipient's alone; people read the step on the task's status line and its record.+ for (const to of [kimi, f.lead]) {+ const row = effects.messages.find(m => m.recipients.includes(to) && /stepped/.test(m.text))!+ expect(agentOnly(row.source, row.recipients)).toBe(true)+ }// The next attempt may not go back to the grid; a stronger model takes the carry-over in its brief and the step in its record.f.run({ type: 'agent.release', agentId: kimi, decision: 'stop' }, f.leadActor)const route = (pick: Record<string, unknown>) => f.run({ type: 'route.record', conversationId: group, decision: record({ candidates: [candidate('c0', pick)], pick: 'c0' }) } as Command, f.leadActor)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 0ad679172..36e80ff0e 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -630,6 +630,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma/** Any other row the system writes in the actor's name. Without a source, a notice written as the owner read as the owner* asking, and a Lead could quote it to change rules (review of #1594). Only `message.send` and an initial message stay plain. */const SYSTEM_ROW = { kind: 'system' }+ /** Agent bookkeeping, a routing line or an agent joined or ready: no one's in the project chat or the Leads chat, which+ * carry only what people read or decide on (the Lead's ruling, 2026-10-29); a task's chat keeps it as its record. */+ const bookkeeping = (conversationId: string, source: Record<string, unknown>) =>+ conversationId === state.leadsConversationId || projectsOf(state).some(p => p.leadConversationId === conversationId) ? forRecipients(source) : sourceconst who = sender.kind === 'person' ? sender.name.split('@')[0]! : sender.name/** A hard rule refuses an agent, unless it carries out what a person chose by hand. A person is not blocked: the* command goes through and the group is told. */@@ -676,8 +680,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst steppedUp = (group: Conversation, reason: string, startId?: string) => {const stepped = stepUp(state, group, reason, context.now, startId)if (!stepped) return+ // Each its recipient's alone (Ken, 2026-10-29): people read the step on the task's status line. With no Lead here to+ // hear it, the people do (review of #2177).const row = (key: string, text: string, recipients: string[]) => effects.messages.push({ id: stableId(operationId, 'step-up', key),- conversationId: group.id, author: sender, text, replyTo: null, recipients, source: SYSTEM_ROW })+ conversationId: group.id, author: sender, text, replyTo: null, recipients, source: recipients.length ? forRecipients(SYSTEM_ROW) : SYSTEM_ROW })if (stepped.stopped) row('worker', `The Swarm stepped this task up to a stronger model: ${reason.replace(/^./, c => c.toLowerCase()).replace(/\.$/, '')}. Stop working on it.`, [stepped.stopped])const lead = group.leadId && group.agentIds.includes(group.leadId) ? group.leadId : nullrow('lead', stepped.notice, lead ? [lead] : [])@@ -971,7 +977,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst group = state.conversations.find(c => !c.archived && !isLeads(c) && c.agentIds.includes(target.id)) ?? conversation(state, project.leadConversationId)effects.messages.push({ id: stableId(operationId, 'role-gone', target.id), conversationId: group.id, author: sender, recipients: [target.id], replyTo: null,text: `Custom has no ${agentKind(state, target) === 'reviewer' ? 'Reviewer' : 'Engineer'} role for ${target.displayName ?? target.name}. `- + 'Finish your current work; you take no new work.', source: SYSTEM_ROW })+ + 'Finish your current work; you take no new work.', source: forRecipients(SYSTEM_ROW) })}break}@@ -1456,7 +1462,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma() => ({ kind: 'new', startId: operationId, machineId: r.machineId, engine: r.engine, model, effort,...(r.gridModel && r.gridName ? { gridModel: r.gridModel, gridName: r.gridName } : {}) }), command.overrideReason)if (override) message(r.conversationId, `Lead started ${r.name} instead of ${expected.title}. Reason: ${override.reason}`, [], null,- { kind: 'route-override', decisionId: decision.id, by: 'lead' })+ bookkeeping(r.conversationId, { kind: 'route-override', decisionId: decision.id, by: 'lead' }))personChose = !override && decision.override?.by === 'person'}ruled(startTarget(request), request.conversationId, `${who} started ${request.name}`, personChose)@@ -1594,9 +1600,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (command.type === 'agent.startSettled') {if (!start.poolGeneration || !start.harnessId || start.error) fail('START_PENDING', 'This contributed start is not ready to settle.')// A Product Manager is never assigned work: its conversation already said where it started.+ // A warning is the people's to read (a start that went wrong); being ready is bookkeeping.if (!start.poolSettled && !start.request.leadFor) message(start.request.conversationId, command.warning? `${start.request.name}: ${command.warning}`- : start.request.buddyOf ? buddyReady(start.request.name) : `${start.request.name} is ready for an assignment.`, [], null, SYSTEM_ROW)+ : start.request.buddyOf ? buddyReady(start.request.name) : `${start.request.name} is ready for an assignment.`, [], null,+ command.warning ? SYSTEM_ROW : bookkeeping(start.request.conversationId, SYSTEM_ROW))start.poolSettled = truebreak}@@ -1648,12 +1656,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (start.request.leadFor) {// Taking over from a Lead that left, as agent.add does.if (group.leadId && !group.agentIds.includes(group.leadId)) keepLead(group, agentId)+ // The people's to read: it answers the start a person asked for, whose "Waiting for a machine" line they read.message(group.id, leadJoined(state, start, group, agentId), [], null, SYSTEM_ROW)}// A Buddy always starts on a Swarm machine: its chat hears once it settles, as the Lead does for a worker.else if (!start.request.buddyOf) message(group.id, start.poolGeneration? `${start.request.name} joined. Preparing its model.`- : `${start.request.name} joined. Ready for an assignment.`, [], null, SYSTEM_ROW)+ : `${start.request.name} joined. Ready for an assignment.`, [], null, bookkeeping(group.id, SYSTEM_ROW))break}case 'agent.configuration': {@@ -1974,12 +1983,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaresult.routeDecisionId = operationId// The row quotes the Lead's reason for the task; the verdict's own text stays in the decision record.const reason = decision.assessment.why- message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"`, [], null, {+ message(command.conversationId, `Routed to ${chosen.title} — ${via} · "${reason}"`, [], null, bookkeeping(command.conversationId, {kind: 'route', decisionId: operationId, via: decision.via, p: decision.p, belowFloor: decision.belowFloor, why: reason,...(decision.via === 'order' && decision.fallback ? { fallback: decision.fallback } : {}),pick: { id: chosen.id, title: chosen.title },alternatives: decision.candidates.filter(c => c.id !== chosen.id).map(c => ({ id: c.id, title: c.title })),- })+ }))leadActed(command.conversationId, 'route')break}@@ -2088,7 +2097,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaruled(agentTarget(state, worker), group.id, `${who} assigned ${worker.name}`, personChose)message(group.id, `${group.brief}${carryOver(group)}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`, [worker.id], null, SYSTEM_ROW)if (routeNote) effects.messages.push({ id: stableId(operationId, 'route-override'), conversationId: group.id, author: sender,- text: routeNote.text, replyTo: null, recipients: [], source: { kind: 'route-override', decisionId: routeNote.decisionId, by: 'lead' } })+ text: routeNote.text, replyTo: null, recipients: [], source: bookkeeping(group.id, { kind: 'route-override', decisionId: routeNote.decisionId, by: 'lead' }) })break}case 'work.status': {diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex d9ea7c38b..5846c17bb 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -383,20 +383,39 @@ export interface MessageDraft {}/** A notice for one agent alone (a skill update): delivered to it like any message, never shown to people or other agents. */export const AGENT_ONLY = { kind: 'agent-only' }-/** Notices written for the Lead or an agent, read only by their recipients like an agent-only notice, under their own kind- * so their recipients receive them as before: the Lead's wake for a stalled, lost or resumed task, the old agent's moved- * notice, and the Lead's scheduled report and digest requests. People read the task's state on its status line (Ken,- * 2026-10-29: shown under the Lead's name in the project chat, they read as requests to act). By kind, so the ones already- * stored are hidden as well; but only one that reaches an agent: with no Lead to hear it, a person is the only one who can- * act, so people read it (review of #2177). */-const RECIPIENT_NOTICES = new Set<unknown>(['work-stalled', 'work-lost', 'work-resumed', 'update-request', 'digest-request'])+/** Who reads each kind of notice the Swarm writes into a chat: every kind the code writes has its line (notices.test.ts).+ * `people`: everyone in the chat, its record of what happened or of what someone must act on. `recipients`: written for the+ * Lead or an agent, so only the ones it reaches read it, like an agent-only notice, under its own kind so they receive it as+ * before; a notice that reaches none is for people, the only ones left who can act (review of #2177). `agent`: only its+ * recipients, always. Ken, 2026-10-29: shown under the Lead's name in the project chat, the Lead's wakes read as requests to+ * act; people read a task's state on its status line. By kind, so the ones already stored are hidden as well. A kind people+ * read can still be one row's recipients' alone (forRecipients): a cancel told to its worker, a routing line in the project+ * chat. A kind no code here knows, stored by a newer server, reads as `people`. */+export const NOTICE_READERS = {+ // Only its agent: a skill update (cli host.ts), a decision answered (decisions.ts).+ 'agent-only': 'agent',+ // The Lead's wakes and requests, and the worker's "moved" line (liveness.ts, tidy.ts, projectUpdates.ts, digest.ts); two+ // projects changing the same code, to both their Leads in the Leads chat (commands.ts).+ 'work-stalled': 'recipients', 'work-lost': 'recipients', 'work-resumed': 'recipients', 'idle-stop': 'recipients',+ 'update-request': 'recipients', 'digest-request': 'recipients', overlap: 'recipients',+ // Each its own case in commands.ts, decided by the row (forRecipients): statuses, briefs, merges, starts, removals.+ system: 'people',+ rule: 'people', 'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people',+ 'decision-delegated': 'people', 'machine-removed': 'people', 'machine-left': 'people', ship: 'people', 'auto-review': 'people',+ 'auto-archive': 'people', native: 'people',+ // #2177's rulings: a failed start and a terminal's alert or typed input stay the people's to see.+ 'start-timeout': 'people', 'terminal-alert': 'people', 'terminal-input': 'people',+} as const satisfies Record<string, 'people' | 'recipients' | 'agent'>+const readersOf = (kind: unknown): 'people' | 'recipients' | 'agent' =>+ typeof kind === 'string' && Object.hasOwn(NOTICE_READERS, kind) ? NOTICE_READERS[kind as keyof typeof NOTICE_READERS] : 'people'/** Marks a notice of a kind people also read (a cancel to its worker), or a copy for no one of a notice its recipient hears* elsewhere, as its recipients' alone. */export const forRecipients = (source: Record<string, unknown>) => ({ ...source, recipientsOnly: true as const })/** Whether only the message's recipients read it: never people, nor other agents. */export const agentOnly = (source: unknown, recipients: readonly string[]): boolean => {const notice = source as { kind?: unknown; recipientsOnly?: unknown } | null | undefined- return notice?.kind === AGENT_ONLY.kind || notice?.recipientsOnly === true || (RECIPIENT_NOTICES.has(notice?.kind) && recipients.length > 0)+ const readers = readersOf(notice?.kind)+ return readers === 'agent' || notice?.recipientsOnly === true || (readers === 'recipients' && recipients.length > 0)}/** What a Buddy reads of an agent and of a task: no machine or terminal ids (review 1 of #2115: no machines means none). *//** A lost task's reason without the machine it ran on (lostReason.ts). */diff --git a/backend/src/superTabs/notices.test.ts b/backend/src/superTabs/notices.test.tsnew file mode 100644index 000000000..e6d74805e--- /dev/null+++ b/backend/src/superTabs/notices.test.ts@@ -0,0 +1,102 @@+import { readdirSync, readFileSync } from 'node:fs'+import { dirname, join, relative } from 'node:path'+import { fileURLToPath } from 'node:url'+import ts from 'typescript'+import { describe, expect, it } from 'vitest'+import { agentOnly, forRecipients, NOTICE_READERS } from './model.js'++// Ken, 2026-10-29: notices written for the Lead or an agent showed in the chats people read, one kind at a time (#2177, then+// the idle stop). Every kind the code writes as a message's source is classified in model.ts NOTICE_READERS; this reads the+// code itself, as cli/src/architecture.spec.ts reads its imports, so a new kind with no line there fails here, not in a chat.++const root = dirname(fileURLToPath(import.meta.url))+const sources = (dir: string): string[] => readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory()+ ? sources(join(dir, entry.name))+ : entry.name.endsWith('.ts') && !/\.test(-support)?\.ts$|\.test-d\.ts$/.test(entry.name) ? [join(dir, entry.name)] : [])++/** The kinds `expression` can give a message's source: its object literals' `kind`, through spreads, calls (json,+ * forRecipients), conditionals, casts and variables (the file's own, or another's module constants: AGENT_ONLY). A string+ * counts only as a `kind`'s value. */+function kindsOf(expression: ts.Node, declared: (name: string) => ts.Expression[], inKind = false, seen = new Set<ts.Node>()): string[] {+ if (seen.has(expression)) return []+ seen.add(expression)+ const of = (node: ts.Node, kind = inKind) => kindsOf(node, declared, kind, seen)+ if (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) {+ return of(expression.expression)+ }+ if (ts.isConditionalExpression(expression)) return [...of(expression.whenTrue), ...of(expression.whenFalse)]+ if (ts.isBinaryExpression(expression)) return [...of(expression.left), ...of(expression.right)]+ if (ts.isCallExpression(expression)) return expression.arguments.flatMap(argument => of(argument))+ if (ts.isIdentifier(expression)) return declared(expression.text).flatMap(initializer => of(initializer))+ if (ts.isStringLiteralLike(expression)) return inKind ? [expression.text] : []+ if (!ts.isObjectLiteralExpression(expression)) return []+ return expression.properties.flatMap(property => {+ if (ts.isSpreadAssignment(property)) return of(property.expression, false)+ if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'kind') return of(property.initializer, true)+ return []+ })+}++const add = (map: Map<string, ts.Expression[]>, name: string, initializer: ts.Expression) => map.set(name, [...map.get(name) ?? [], initializer])++/** Every notice kind written as a message's source (a `source` property, or the source argument of commands.ts `message`),+ * with the files that write it. */+function writtenKinds(): Map<string, string[]> {+ const files = sources(root).map(path => ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true))+ const modules = new Map<string, ts.Expression[]>()+ for (const file of files) {+ for (const statement of file.statements) {+ if (!ts.isVariableStatement(statement)) continue+ for (const declaration of statement.declarationList.declarations) {+ if (ts.isIdentifier(declaration.name) && declaration.initializer) add(modules, declaration.name.text, declaration.initializer)+ }+ }+ }+ const written = new Map<string, string[]>()+ for (const file of files) {+ const locals = new Map<string, ts.Expression[]>()+ const at: ts.Node[] = []+ const visit = (node: ts.Node) => {+ // A variable, or a parameter's default (autoReview.ts row's source).+ if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && ts.isIdentifier(node.name) && node.initializer) add(locals, node.name.text, node.initializer)+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === 'source') at.push(node.initializer)+ if (ts.isShorthandPropertyAssignment(node) && node.name.text === 'source') at.push(node.name)+ // message(conversationId, text, recipients, replyTo, source, ...)+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'message' && node.arguments[4]) at.push(node.arguments[4])+ ts.forEachChild(node, visit)+ }+ visit(file)+ const declared = (name: string) => locals.get(name) ?? modules.get(name) ?? []+ for (const kind of new Set(at.flatMap(node => kindsOf(node, declared)))) written.set(kind, [...written.get(kind) ?? [], relative(root, file.fileName)])+ }+ return written+}++describe('the notices the Swarm writes into a chat', () => {+ const written = writtenKinds()++ it('finds the notices it is known to write, so a change in how they are written cannot empty this check', () => {+ expect([...written.keys()]).toEqual(expect.arrayContaining(['system', 'rule', 'agent-only', 'idle-stop', 'work-lost', 'terminal-alert', 'native', 'ship']))+ })++ it('classifies every kind it writes, and only those', () => {+ const unclassified = [...written].filter(([kind]) => !Object.hasOwn(NOTICE_READERS, kind)).map(([kind, files]) => `${kind} (${files.join(', ')})`)+ expect(unclassified, 'add each to NOTICE_READERS in model.ts: who reads it?').toEqual([])+ expect(Object.keys(NOTICE_READERS).filter(kind => !written.has(kind))).toEqual([])+ })++ it('shows people a notice of theirs, and one for an agent only while it reaches none', () => {+ expect(agentOnly({ kind: 'system' }, ['lead'])).toBe(false)+ expect(agentOnly({ kind: 'terminal-alert' }, ['lead'])).toBe(false)+ expect(agentOnly({ kind: 'start-timeout' }, ['lead'])).toBe(false)+ for (const kind of ['idle-stop', 'work-stalled', 'overlap']) {+ expect(agentOnly({ kind }, ['lead'])).toBe(true)+ expect(agentOnly({ kind }, [])).toBe(false)+ }+ expect(agentOnly({ kind: 'agent-only' }, [])).toBe(true)+ // A row of a kind people read can still be its recipients' alone; a kind no code knows (stored by a newer server) shows.+ expect(agentOnly(forRecipients({ kind: 'system' }), [])).toBe(true)+ expect(agentOnly({ kind: 'from-a-newer-server' }, ['lead'])).toBe(false)+ expect(agentOnly(undefined, [])).toBe(false)+ })+})diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex e16fba92e..c3afd78fd 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -1,4 +1,5 @@import type { Prisma, SuperTabDelivery, SuperTabMessage } from '@prisma/client'+import { routingRow } from './buddies.js'import { ms } from './parts/light.js'import type { ReactionRow } from './reactions.js'import { agentOnly, stableId, type Author } from './model.js'@@ -114,7 +115,8 @@ export async function deliveredCopies(tx: Transaction, tabId: string, rows: Readreturn new Set(copies.filter(row => reached.has(stableId(row.id, 'lead'))).map(row => row.id))}-export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean }+/** `routing`: a route, override or rule row (buddies.ts routingRow), which a Buddy never reads, as a reply or a thread's root. */+export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean; routing: boolean }/** Every message of the threads rooted at `roots` in one conversation, roots included, oldest first: what the page's thread* summaries are counted from. Matched as the page reads are, so the tabId+conversationId+thread index bounds it. */@@ -126,5 +128,6 @@ export async function pageThreads(tx: Transaction, tabId: string, conversationId.map(row => ({ id: row._id as string, source: row.source, recipientIds: (row.recipientIds ?? []) as string[] })))return rows.map(row => ({ thread: row.thread as string, id: row._id as string, author: row.author as Author,mentions: (row.mentions ?? []) as string[], sequence: row.sequence as number, createdAt: new Date(ms(row.createdAt)),- agentOnly: copies.has(row._id as string) || agentOnly(row.source, (row.recipientIds ?? []) as string[]) })).sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))+ agentOnly: copies.has(row._id as string) || agentOnly(row.source, (row.recipientIds ?? []) as string[]), routing: routingRow(row.source) }))+ .sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))}diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.tsindex 7aeef1ffe..a1bb28ac2 100644--- a/backend/src/superTabs/projects.test.ts+++ b/backend/src/superTabs/projects.test.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto'import { describe, expect, it } from 'vitest'import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'-import { createSuperTab, SuperTabError, visibleState, type Actor, type MessageDraft } from './model.js'+import { agentOnly, createSuperTab, SuperTabError, visibleState, type Actor, type MessageDraft } from './model.js'import { canReadAgent, canWatchAgent, markConfidential, projectOf, projectsOf, readConversation, skillModeOf, skillSetOf, watchersLost } from './projects.js'import { mayDrive } from './terminal.js'@@ -494,6 +494,10 @@ describe('custom role sets', () => {f.run({ type: 'project.skills', projectId: p.projectId, mode: 'custom' }, peer)expect(f.messages).toEqual(expect.arrayContaining([expect.objectContaining({ recipients: [reviewer],text: expect.stringContaining('has no Reviewer role') })]))+ // The agent's alone (Ken, 2026-10-29): people read the project's set on its own line.+ const gone = f.messages.find(m => m.text.includes('has no Reviewer role'))!+ expect(agentOnly(gone.source, gone.recipients)).toBe(true)+ expect(agentOnly(f.messages.find(m => m.text.startsWith('Skills: '))!.source, [])).toBe(false)expect(f.messages.filter(m => m.recipients.includes(lead))).toEqual([])expect(() => f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Review', brief: 'Check it', reviewOf: build, checks: [] }, peer)).toThrow('no reviewer role')expect(() => f.run({ type: 'agent.start', request: request(p.conversationId, { role: 'reviewer' }) } as Command)).toThrow('no reviewer role')diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 8ca563b97..6caa29008 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1919,6 +1919,19 @@ export class SuperTabStore {// A Buddy reads its project's workgroups but never how work is routed: a route row names the machines that could run it// and why others could not (security review 2 of #2115). Left out like an agent-only notice, so no page is shorter.const buddy = isBuddyReader(state, actor)+ const readable = (m: Pick<SuperTabMessage, 'source' | 'recipientIds'>) => (!agentOnly(m.source, m.recipientIds) || (actor.kind === 'agent' && m.recipientIds.includes(actor.agentId)))+ && !(buddy && routingRow(m.source))+ // One thread is read only through a root this reader may read. A hidden root (an agent-only note to someone else; for a+ // Buddy, a route row) reads as one that is not in this conversation, and as an exact message it may not see: an empty+ // page, never its replies alone (review 2 of #2168). By its id, through the primary key.+ if (cursor.thread) {+ const root = await tx.superTabMessage.findFirst({ where: { tabId, conversationId, id: cursor.thread },+ select: { id: true, source: true, recipientIds: true } })+ // A task chat's copy of a Lead's notice stored before it was marked is read by no one either (pageReads.ts).+ if (!root || !readable(root) || (await deliveredCopies(tx, tabId, [root])).size) {+ return { messages: [], next: null, threads: [], reactionSeq: group.reactionSeq ?? 0 }+ }+ }const forward = cursor.after !== undefined// One thread: its root (its own thread) and its replies.const at = { tabId, conversationId, messageId: cursor.messageId, thread: cursor.thread }@@ -1932,8 +1945,7 @@ export class SuperTabStore {const batch = await messagesPast(tx, at, edge, forward, 101)// A task chat's copy of a Lead's notice stored before it was marked is that notice: read by no one (pageReads.ts).const copies = await deliveredCopies(tx, tabId, batch)- rows.push(...batch.filter(m => !copies.has(m.id) && (!agentOnly(m.source, m.recipientIds) || (actor.kind === 'agent' && m.recipientIds.includes(actor.agentId)))- && !(buddy && routingRow(m.source))))+ rows.push(...batch.filter(m => !copies.has(m.id) && readable(m)))if (batch.length < 101) breakedge = { sequence: batch.at(-1)!.sequence, id: batch.at(-1)!.id }}@@ -1942,17 +1954,24 @@ export class SuperTabStore {if (!forward) page.reverse()const reactions = page.length ? reactionCounts(state, await pageReactions(tx, tabId, page.map(m => m.id))) : new Map()const deliveries = page.length ? await pageDeliveries(tx, tabId, page.map(m => m.id)) : []- // A lost task's rows and a machine leaving name the machine; a Buddy reads them without it (security reviews of #2115).- const shown = buddy ? page.map(withoutMachineNames) : page+ // What the page's rows point at that this reader may not see (an agent-only note to someone else; for a Buddy, a routing+ // row): such a reply reads as a message of its own, with no thread or reply-to naming it and no reply line for it+ // (review 1 of #2168). Rows on the page are readable already; the rest are read by id, at most two per row.+ const onPage = new Set(page.map(m => m.id))+ const pointed = [...new Set(page.flatMap(m => [m.thread, m.replyTo]).filter((id): id is string => !!id && !onPage.has(id)))]+ // A task chat's copy of a Lead's notice stored before it was marked is read by no one (pageReads.ts deliveredCopies).+ const pointedRows = pointed.length ? await tx.superTabMessage.findMany({ where: { tabId, conversationId, id: { in: pointed } },+ select: { id: true, source: true, recipientIds: true } }) : []+ const pointedCopies = pointedRows.length ? await deliveredCopies(tx, tabId, pointedRows) : new Set<string>()+ const hidden = new Set(pointedRows.filter(m => !readable(m) || pointedCopies.has(m.id)).map(m => m.id))// The threads the page's rows are in, so a poll that brings only a reply still moves its root's reply line.- const roots = [...new Set(page.flatMap(m => m.thread ? [m.thread] : []))]+ const roots = [...new Set(page.flatMap(m => m.thread && !hidden.has(m.thread) ? [m.thread] : []))]const threadRows = roots.length ? await pageThreads(tx, tabId, conversationId, roots) : []- // A reply stored in the thread of a notice only its recipients read (the Lead answering a stalled alert before such- // replies started no thread, commands.ts) reads as one in the chat: nobody else can open that thread (review of #2177).- const hiddenRoots = new Set(threadRows.filter(row => row.id === row.thread && row.agentOnly).map(row => row.id))- const threads = threadRows.length ? threadSummaries(state, group, threadRows.filter(row => !hiddenRoots.has(row.thread))) : []- const inChat = (m: SuperTabMessage) => m.thread && m.thread !== m.id && hiddenRoots.has(m.thread) ? { ...m, thread: m.id } : m- return { messages: shown.map(inChat).map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],+ const threads = threadRows.length ? threadSummaries(state, group, buddy ? threadRows.filter(r => !r.routing) : threadRows) : []+ // A lost task's rows and a machine leaving name the machine; a Buddy reads them without it (security reviews of #2115).+ const shown = (buddy ? page.map(withoutMachineNames) : page).map(m => (m.thread && hidden.has(m.thread)) || (m.replyTo && hidden.has(m.replyTo))+ ? { ...m, ...(m.thread && hidden.has(m.thread) ? { thread: null } : {}), ...(m.replyTo && hidden.has(m.replyTo) ? { replyTo: null } : {}) } : m)+ return { messages: shown.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],deliveries: deliveries.filter(d => d.messageId === m.id) })), next, threads,// A poll for new messages learns here that a reaction changed on a message it already shows (reactions.ts).reactionSeq: group.reactionSeq ?? 0 }diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.tsindex 4ef7570e2..254359118 100644--- a/backend/src/superTabs/tidy.test.ts+++ b/backend/src/superTabs/tidy.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import type { Agent, Assignment, Conversation, SuperTabState } from './model.js'+import { agentOnly, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'import { ARCHIVE_QUIET_MS, archivable, IDLE_STOP_MS, stopIdleWorkers } from './tidy.js'const MINUTE = 60_000@@ -32,16 +32,26 @@ const at = START + IDLE_STOP_MSconst target = (state: SuperTabState, id = 'w') => state.agents.find(a => a.id === id)!describe('stopping idle workers', () => {- it('stops a Swarm-started Builder 15 minutes after its last activity, with one quiet line in its last group', () => {+ it('stops a Swarm-started Builder 15 minutes after its last activity, with one line in its last group for the Lead', () => {const state = swarm()const rows = stopIdleWorkers(state, 'lead', at, new Set())expect(target(state)).toMatchObject({ workDecision: 'stop' })expect(target(state).releaseId).toEqual(expect.any(String))// Marked as the idle check's, so its host may withdraw it if its folder changed since (agent.stopRefused).expect(target(state).idleStop).toEqual({ previous: null })- expect(rows).toEqual([expect.objectContaining({ conversationId: 'g1', recipients: [], replyTo: null,+ // Ken, 2026-10-29: the Lead's to handle, delivered to it; people do not read it (model.ts agentOnly).+ expect(rows).toEqual([expect.objectContaining({ conversationId: 'g1', recipients: ['L'], replyTo: null,author: expect.objectContaining({ kind: 'agent', id: 'L' }), text: 'Rowan stopped: no work for 15 minutes.',source: { kind: 'idle-stop', agentId: 'w' } })])+ expect(rows.map(row => agentOnly(row.source, row.recipients))).toEqual([true])+ })++ it('tells a Lead outside the worker\'s last group in its own chat, and hides the copy left in that group for no one', () => {+ const state = swarm({ groups: [group({ agentIds: ['w'] })] })+ const rows = stopIdleWorkers(state, 'lead', at, new Set())+ expect(rows.map(row => [row.conversationId, row.recipients])).toEqual([['g1', []], ['lead', ['L']]])+ expect(rows.map(row => agentOnly(row.source, row.recipients))).toEqual([true, true])+ expect(rows.map(row => row.source?.agentId)).toEqual(['w', 'w'])})it('waits until a full 15 minutes have passed since its group last spoke', () => {@@ -65,7 +75,7 @@ describe('stopping idle workers', () => {it('stops a worker that never got a task, saying so in the Lead conversation when it sits in no group', () => {const state = swarm({ groups: [] })- expect(stopIdleWorkers(state, 'lead', at, new Set())).toEqual([expect.objectContaining({ conversationId: 'lead' })])+ expect(stopIdleWorkers(state, 'lead', at, new Set())).toEqual([expect.objectContaining({ conversationId: 'lead', recipients: ['L'] })])expect(target(state).workDecision).toBe('stop')})diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 1622b438a..4a990d8f2 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -4,6 +4,8 @@ import { agentDisplayName } from './agentNames.js'import { verdictPending } from './autoReview.js'import { activeWork, agentRole, stableId, type Agent, type Assignment, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { agentProjectId, groupProject, projectsOf } from './projects.js'+import { toLead } from './terminal.js'+import { leadNoticeRows } from './liveness.js'// Nobody has to tidy a Swarm by hand (roadmap, December). A Builder left with nothing to do for 15 minutes is stopped, as// its Lead's agent.release stop would: its host closes the session and frees the machine slot (host.ts). Whatever the@@ -114,9 +116,12 @@ export function stopIdleWorkers(state: SuperTabState, projectId: string, now: nuworker.releaseId = stableId('idle-stop', worker.id, String(since))// Only a group the poll loaded takes the line: an asleep one refuses posts, and its refusal would fail the whole poll.const last = groups.filter(g => !g.archived && state.conversations.some(c => c.id === g.id)).sort((a, b) => (time(b.lastActivityAt) ?? 0) - (time(a.lastActivityAt) ?? 0))[0]- rows.push({ id: stableId('idle-stop', worker.id, String(since), 'line'), conversationId: last?.id ?? project.leadConversationId, replyTo: null, recipients: [],+ // The Lead's to handle (Ken, 2026-10-29): delivered to it, in its own chat when it is not in that group, and read by no+ // one else (model.ts agentOnly).+ rows.push(...leadNoticeRows(toLead(state, worker, { id: stableId('idle-stop', worker.id, String(since), 'line'), conversationId: last?.id ?? project.leadConversationId,+ replyTo: null, recipients: [],author: { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration },- text: `${worker.displayName ?? worker.name} stopped: no work for 15 minutes.`, source: { kind: 'idle-stop', agentId: worker.id } })+ text: `${worker.displayName ?? worker.name} stopped: no work for 15 minutes.`, source: { kind: 'idle-stop', agentId: worker.id } })))}return rows}diff --git a/desktop/lib/state/harness_attachments.dart b/desktop/lib/state/harness_attachments.dartindex 3bf0dc43b..de20e2707 100644--- a/desktop/lib/state/harness_attachments.dart+++ b/desktop/lib/state/harness_attachments.dart@@ -36,6 +36,30 @@ class HarnessAttachments extends ChangeNotifier {final void Function(String message)? onDeliveryProblem;final _files = <HarnessAttachment>[];+ int _reading = 0;+ bool _disposed = false;++ /// Whether a picker, a drop or a paste is still reading files for this box.+ /// An owner that would let go of an empty box waits while this is true, so+ /// what the read brings is not lost.+ bool get isReading => _reading > 0;++ /// Runs [read], which ends by adding what it read here, and holds the box+ /// until it is done.+ Future<T> reading<T>(Future<T> Function() read) async {+ _reading++;+ try {+ return await read();+ } finally {+ _reading--;+ }+ }++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }List<HarnessAttachment> get files => List.unmodifiable(_files);bool get isEmpty => _files.isEmpty;@@ -48,6 +72,8 @@ class HarnessAttachments extends ChangeNotifier {Iterable<HarnessAttachment> files, {Iterable<String> oversized = const [],}) {+ // A box given up with its conversation takes nothing more.+ if (_disposed) return null;final tooLarge = [...oversized];var surplus = 0;for (final file in files) {diff --git a/desktop/lib/super_tabs/composer_files.dart b/desktop/lib/super_tabs/composer_files.dartnew file mode 100644index 000000000..54189308e--- /dev/null+++ b/desktop/lib/super_tabs/composer_files.dart@@ -0,0 +1,38 @@+import 'package:flutter/widgets.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../state/harness_attachments.dart';+import '../widgets/new_harness_attachments.dart';+import 'controller.dart';++/// The files waiting in a chat box, as chips above its field. The main chat and the+/// thread pane draw them with this, so a change to the chips reaches both.+class SuperTabComposerChips extends StatelessWidget {+ const SuperTabComposerChips({+ super.key,+ required this.controller,+ required this.files,+ });++ final SuperTabController controller;+ final HarnessAttachments files;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: files,+ builder: (context, _) => files.isEmpty+ ? const SizedBox.shrink()+ : Padding(+ padding: const EdgeInsets.only(+ bottom: grid.AppDesktop.controlGap,+ right: grid.AppDesktop.controlGap,+ ),+ child: NewHarnessAttachmentChips(+ attachments: files,+ enabled: !controller.saving,+ isUploading: controller.isUploading,+ progressOf: controller.uploadProgress,+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/composer_newline.dart b/desktop/lib/super_tabs/composer_newline.dartindex c2e724593..aa727ae33 100644--- a/desktop/lib/super_tabs/composer_newline.dart+++ b/desktop/lib/super_tabs/composer_newline.dart@@ -1,4 +1,5 @@import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';/// The most the Swarm chat box holds; the field's own limit and [withNewline]'s.const kComposerMaxLength = 32000;@@ -19,3 +20,44 @@ TextEditingValue? withNewline(TextEditingValue value) {selection: TextSelection.collapsed(offset: selection.start + 1),);}++/// What a key does in a chat box.+enum ComposerEnter { ignore, newline, send }++/// What [event] does in a chat box holding [value] when [focused]: Enter sends,+/// Shift+Enter and Alt/Option+Enter write another line, Ctrl or Command with Enter and+/// every other key are left to the field, and nothing happens while an input method+/// is composing. The main chat and the thread pane both decide with this.+ComposerEnter composerEnter(+ KeyEvent event, {+ required bool focused,+ required TextEditingValue value,+}) {+ final composing = value.composing;+ if (!focused ||+ event is! KeyDownEvent ||+ event.logicalKey != LogicalKeyboardKey.enter ||+ (composing.isValid && !composing.isCollapsed)) {+ return ComposerEnter.ignore;+ }+ final keys = HardwareKeyboard.instance;+ if (keys.isControlPressed || keys.isMetaPressed) return ComposerEnter.ignore;+ // Shift+Enter and Alt+Enter write the line themselves: the platform gives+ // Option+Return none, and a handled key never reaches it.+ return keys.isShiftPressed || keys.isAltPressed+ ? ComposerEnter.newline+ : ComposerEnter.send;+}++/// Writes a line break into [composer] at the cursor and tells [edited] the new+/// text. The field only reports edits that come from the platform, so this reports+/// its own.+void insertComposerNewline(+ TextEditingController composer,+ ValueChanged<String> edited,+) {+ final value = withNewline(composer.value);+ if (value == null) return;+ composer.value = value;+ edited(value.text);+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 7a1f85c03..0b8d42c34 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -271,7 +271,7 @@ class SuperTabController extends ChangeNotifier {/// Why the files of each conversation's last send did not go up. Kept apart/// from [operationError] so it shows only under its own conversation.- final _uploadErrors = <String, String>{};+ final _uploadErrors = <Object, String>{};/// The conversation the last action that set [operationError] was for, or/// null when it was for none (a machine, a member, the Swarm).@@ -304,6 +304,10 @@ class SuperTabController extends ChangeNotifier {_operationErrorFor = id is String ? id : null;}+ /// The same for the reply box of [root]'s thread in [conversationId].+ String? threadComposerError(String conversationId, String root) =>+ operationError ?? _uploadErrors[(conversationId, root)];+/// One line for the sender after a command succeeds, from the backend: that a/// credential was removed from what they sent and should be revoked.String? operationNotice;@@ -552,12 +556,22 @@ class SuperTabController extends ChangeNotifier {/// The thread open beside the chat.({String conversationId, String root})? openedThread;final _attachments = <String, HarnessAttachments>{};++ /// The files waiting to go with the next reply of each thread, by its+ /// conversation and root: a root id alone is not enough to keep two+ /// conversations' files apart.+ final _threadAttachments = <(String, String), HarnessAttachments>{};// Files already uploaded for the message being sent, so a retry sends their// ids rather than uploading them again.final _uploaded = <HarnessAttachment, String>{};final _progress = <HarnessAttachment, double>{};CancelToken? _cancel;- ({String conversationId, List<HarnessAttachment> files})? _sending;+ ({+ String conversationId,+ HarnessAttachments owner,+ List<HarnessAttachment> files,+ })?+ _sending;int _uploadRun = 0;final _messages = <String, List<SuperTabMessage>>{};@@ -704,23 +718,37 @@ class SuperTabController extends ChangeNotifier {/// The files waiting to go with the next message in a conversation. They/// stay in memory: only the text of a draft is saved.- HarnessAttachments attachments(String id) => _attachments.putIfAbsent(id, () {+ HarnessAttachments attachments(String id) =>+ _attachments.putIfAbsent(id, () => _newFiles(id, id));++ /// The files waiting to go with the next reply of [root]'s thread in+ /// [conversationId]. Like [attachments], they stay in memory, and they are+ /// forgotten with the thread when access to the conversation goes.+ HarnessAttachments threadAttachments(String conversationId, String root) =>+ _threadAttachments.putIfAbsent((+ conversationId,+ root,+ ), () => _newFiles(conversationId, (conversationId, root)));++ /// An empty set of files for a message to [conversationId] whose upload+ /// failures are kept under [errorKey].+ HarnessAttachments _newFiles(String conversationId, Object errorKey) {final files = HarnessAttachments(limitBytes: kSuperTabAttachmentMaxBytes,limitFiles: kSuperTabAttachmentMaxFiles,);files.addListener(() {// Changing the files answers a refused upload.- if (_uploadErrors.remove(id) != null) _changed();+ if (_uploadErrors.remove(errorKey) != null) _changed();// Taking a chip off while its files go up gives the upload up.if (uploading &&- _sending?.conversationId == id &&+ identical(_sending?.owner, files) &&!files.files.toSet().containsAll(_sending!.files)) {cancelUpload();}});return files;- });+ }/// Whether [file] is still on its way to the backend in a send.bool isUploading(HarnessAttachment file) =>@@ -1017,6 +1045,20 @@ class SuperTabController extends ChangeNotifier {};_threadRows.removeWhere((root, _) => roots.contains(root));_threadBefore.removeWhere((root, _) => roots.contains(root));+ final forgotten = <HarnessAttachments>[];+ _threadAttachments.removeWhere((key, files) {+ if (!gone(key.$1)) return false;+ forgotten.add(files);+ return true;+ });+ for (final files in forgotten) {+ // Files on their way for a conversation that is gone are given up.+ if (identical(_sending?.owner, files)) cancelUpload();+ files.dispose();+ }+ _uploadErrors.removeWhere(+ (key, _) => key is (String, String) && gone(key.$1),+ );if (openedThread case final open? when gone(open.conversationId)) {openedThread = null;}@@ -1026,10 +1068,28 @@ class SuperTabController extends ChangeNotifier {bool hasEarlierReplies(String root) => _threadBefore.containsKey(root);bool readingEarlierReplies = false;+ /// Lets go of the empty file sets of threads that are not open, which only+ /// reading a thread's reply box made.+ void _pruneThreadFiles() {+ final open = openedThread;+ _threadAttachments.removeWhere((key, files) {+ // A picker, drop or paste still reading for a box will add to it.+ if (!files.isEmpty ||+ files.isReading ||+ (key.$1 == open?.conversationId && key.$2 == open?.root) ||+ identical(_sending?.owner, files)) {+ return false;+ }+ files.dispose();+ return true;+ });+ }+/// Opens [root]'s thread of the selected conversation beside the chat.void openThread(String root) {if (accessRevoked) return;openedThread = (conversationId: selectedId, root: root);+ _pruneThreadFiles();_seeThread(root);_changed();unawaited(loadThread());@@ -1038,6 +1098,7 @@ class SuperTabController extends ChangeNotifier {void closeThread() {if (openedThread == null) return;openedThread = null;+ _pruneThreadFiles();_changed();}@@ -1129,20 +1190,33 @@ class SuperTabController extends ChangeNotifier {}}- /// Sends the open thread's draft to its root; [alsoSend] shows it in the- /// main stream too.- Future<Map<String, dynamic>?> sendThreadReply({bool alsoSend = false}) async {+ /// Sends the open thread's draft and files to its root; [alsoSend] shows it in the+ /// main stream too. [onSending] is told when the reply is on its way, which+ /// is after its files have gone up.+ Future<Map<String, dynamic>?> sendThreadReply({+ bool alsoSend = false,+ VoidCallback? onSending,+ }) async {final open = openedThread;- final text = threadDraft(open?.root ?? '').trim();- if (open == null ||- text.isEmpty ||+ if (open == null) return null;+ final text = threadDraft(open.root).trim();+ final owner = threadAttachments(open.conversationId, open.root);+ final files = owner.files;+ if ((text.isEmpty && files.isEmpty) ||selected == null ||selected!.archived ||!canWrite ||+ uploading ||saving ||_pending != null) {return null;}+ final ids = await _uploadAll(open.conversationId, owner, (+ open.conversationId,+ open.root,+ ));+ if (ids == null) return null;+ final before = _pending;final sending = command({'type': 'message.send','conversationId': open.conversationId,@@ -1150,12 +1224,19 @@ class SuperTabController extends ChangeNotifier {'replyTo': open.root,'recipientIds': const <String>[],if (alsoSend) 'alsoSend': true,+ if (ids.isNotEmpty) 'attachmentIds': ids,});- if (_pending != null) {- _threadDrafts.remove(open.root);+ if (_pending case final pending? when !identical(pending, before)) {+ // Only a draft still holding what went: more may have been typed since.+ if (_threadDrafts[open.root]?.trim() == text) {+ _threadDrafts.remove(open.root);+ }+ onSending?.call();_changed();}- return await sending;+ final result = await sending;+ _forgetRefusedUploads(result);+ return result;}List<SuperTabMessage> messages(String id) => List.unmodifiable(@@ -2150,6 +2231,7 @@ class SuperTabController extends ChangeNotifier {}_moveView(to: id);openedThread = null;+ _pruneThreadFiles();_viewVersion++;operationNotice = null;_saveSoon();@@ -3003,6 +3085,9 @@ class SuperTabController extends ChangeNotifier {for (final entry in _uploaded.entries.toList()) {if (sent.contains(entry.value)) {_attachments[id]?.remove(entry.key);+ for (final MapEntry(:key, :value) in _threadAttachments.entries) {+ if (key.$1 == id) value.remove(entry.key);+ }_uploaded.remove(entry.key);}}@@ -3152,7 +3237,11 @@ class SuperTabController extends ChangeNotifier {return null;}final conversationId = selectedId;- final ids = await _uploadAll(conversationId, files);+ final ids = await _uploadAll(+ conversationId,+ attachments(conversationId),+ conversationId,+ );if (ids == null) return null;final before = _pending;final tags = Map<String, String>.of(_mentions[conversationId] ?? const {});@@ -3177,14 +3266,18 @@ class SuperTabController extends ChangeNotifier {_changed();}final result = await sending;- // A refusal of the files themselves sends them up once more; one of the- // message (a mention, a recipient) leaves them uploaded.+ _forgetRefusedUploads(result);+ return result;+ }++ /// A refusal of the files themselves sends them up once more; one of the+ /// message (a mention, a recipient) leaves them uploaded.+ void _forgetRefusedUploads(Map<String, dynamic>? result) {if (result == null &&_pending == null &&operationErrorCode?.contains('ATTACHMENT') == true) {_uploaded.clear();}- return result;}/// Uploads each of [files] that has not gone up yet and returns their ids,@@ -3192,15 +3285,17 @@ class SuperTabController extends ChangeNotifier {/// files stay where they are.Future<List<String>?> _uploadAll(String conversationId,- List<HarnessAttachment> files,+ HarnessAttachments owner,+ Object errorKey,) async {- // Any send of this conversation answers its last refused upload.- _uploadErrors.remove(conversationId);+ final files = owner.files;+ // Any send from this box answers its last refused upload.+ _uploadErrors.remove(errorKey);if (files.isEmpty) return const [];final run = ++_uploadRun;uploading = true;operationError = null;- _sending = (conversationId: conversationId, files: files);+ _sending = (conversationId: conversationId, owner: owner, files: files);_uploaded.removeWhere((file, _) => !files.contains(file));_changed();try {@@ -3219,7 +3314,7 @@ class SuperTabController extends ChangeNotifier {} catch (failure) {if (!_disposed && run == _uploadRun) {// Into the conversation the files were for, whichever is shown now.- _uploadErrors[conversationId] = failure is SuperTabFailure+ _uploadErrors[errorKey] = failure is SuperTabFailure? failure.message: failure is TimeoutException? 'The upload stopped moving. Try again.'diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex bebf7bd06..26a725f31 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -1,12 +1,18 @@import 'dart:async';+import 'package:flutter/foundation.dart' show kIsWeb;import 'package:flutter/material.dart';import 'package:flutter/services.dart';import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_icon_button.dart';+import '../state/harness_attachments.dart';import '../widgets/desktop_chrome.dart';+import '../widgets/new_harness_attachments.dart';+import '../widgets/new_harness_paste.dart';+import 'composer_files.dart';+import 'composer_newline.dart';import 'controller.dart';import 'jump_to_latest.dart';import 'model.dart';@@ -157,15 +163,40 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {bool get _writable =>c.canWrite && c.selected?.archived == false && !c.hasPendingAction;+ /// The files waiting to go with this thread's next reply.+ HarnessAttachments get _files =>+ c.threadAttachments(c.selectedId, widget.root);++ /// Whether files are going up or a message is on its way, when the box takes+ /// no more.+ bool get _busy => c.uploading || c.saving;++ /// The box was edited: keep it as this thread's draft.+ void _edited(String text) {+ c.setThreadDraft(widget.root, text);+ setState(() {});+ }+Future<void> _send() async {- if (!_writable || _composer.text.trim().isEmpty) return;- c.setThreadDraft(widget.root, _composer.text);- final sending = c.sendThreadReply(alsoSend: _alsoSend);- if (c.threadDraft(widget.root).isEmpty) {- _composer.clear();- setState(() => _alsoSend = false);+ if (!_writable ||+ _busy ||+ (_composer.text.trim().isEmpty && _files.isEmpty)) {+ return;}- await sending;+ final root = widget.root;+ c.setThreadDraft(root, _composer.text);+ await c.sendThreadReply(+ alsoSend: _alsoSend,+ // The reply is on its way (its files have gone up): the box is free for+ // the next one, unless another thread is shown by now.+ onSending: () {+ if (!mounted || widget.root != root) return;+ if (c.threadDraft(root).isEmpty) {+ _composer.clear();+ setState(() => _alsoSend = false);+ }+ },+ );}@override@@ -226,67 +257,73 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {Expanded(child: Stack(children: [- ListView(- controller: _scroll,- padding: const EdgeInsets.symmetric(- vertical: grid.AppDesktop.controlGap,- ),- children: [- if (root != null) widget.row(root, false),- if (count > 0)- Padding(- key: const ValueKey('super-thread-divider'),- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.groupGap,- vertical: grid.AppDesktop.controlGap,+ // As in the chat, a message's text can be selected and copied.+ SelectionArea(+ child: ListView(+ controller: _scroll,+ padding: const EdgeInsets.symmetric(+ vertical: grid.AppDesktop.controlGap,+ ),+ children: [+ if (root != null) widget.row(root, false),+ if (count > 0)+ Padding(+ key: const ValueKey('super-thread-divider'),+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ child: Row(+ children: [+ Text(+ count == 1 ? '1 reply' : '$count replies',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(+ width: grid.AppDesktop.controlGap,+ ),+ Expanded(+ child: Divider(+ height: 1,+ thickness: 1,+ color: DesktopChrome.rim,+ ),+ ),+ ],+ ),),- child: Row(- children: [- Text(- count == 1 ? '1 reply' : '$count replies',- style: DesktopChrome.metadata(),+ if (c.hasEarlierReplies(widget.root))+ Align(+ alignment: Alignment.centerLeft,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,),- const SizedBox(width: grid.AppDesktop.controlGap),- Expanded(- child: Divider(- height: 1,- thickness: 1,- color: DesktopChrome.rim,+ child: TextButton(+ key: const ValueKey('super-thread-earlier'),+ onPressed: c.readingEarlierReplies+ ? null+ : () => unawaited(+ c.loadThread(earlier: true),+ ),+ child: Text(+ c.readingEarlierReplies+ ? 'Loading earlier replies…'+ : 'Show earlier replies',),),- ],- ),- ),- if (c.hasEarlierReplies(widget.root))- Align(- alignment: Alignment.centerLeft,- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.controlGap,- ),- child: TextButton(- key: const ValueKey('super-thread-earlier'),- onPressed: c.readingEarlierReplies- ? null- : () =>- unawaited(c.loadThread(earlier: true)),- child: Text(- c.readingEarlierReplies- ? 'Loading earlier replies…'- : 'Show earlier replies',- ),),),- ),- for (final (index, reply) in replies.indexed)- widget.row(- reply,- index > 0 &&- replies[index - 1].authorId == reply.authorId &&- replies[index - 1].fromAgent == reply.fromAgent,- ),- for (final sent in pending) widget.outgoing(sent),- ],+ for (final (index, reply) in replies.indexed)+ widget.row(+ reply,+ index > 0 &&+ replies[index - 1].authorId == reply.authorId &&+ replies[index - 1].fromAgent == reply.fromAgent,+ ),+ for (final sent in pending) widget.outgoing(sent),+ ],+ ),),if (_away)Positioned(@@ -322,117 +359,160 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {Widget _composerBox() {final writable = _writable;- return DecoratedBox(- decoration: BoxDecoration(- color: DesktopChrome.field,- borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),- border: Border.all(color: DesktopChrome.rim),- ),- child: Padding(- padding: const EdgeInsets.fromLTRB(- grid.AppDesktop.groupGap,- grid.AppDesktop.controlGap,- grid.AppDesktop.controlGap,- grid.AppDesktop.controlGap,+ final files = _files;+ final busy = _busy;+ final error = c.threadComposerError(c.selectedId, widget.root);+ return NewHarnessDropZone(+ attachments: files,+ enabled: writable && !busy,+ // A folder has no bytes to attach, and its path means nothing to a+ // reader on another computer: say so, as the chat does for a browser.+ onFolders: kIsWeb+ ? null+ : (_) => reportAttachProblem(+ context,+ 'A folder can\'t be attached to a reply. Drop its files instead.',+ ),+ child: DecoratedBox(+ key: const ValueKey('super-thread-composer-surface'),+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ border: Border.all(color: DesktopChrome.rim),),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Focus(- onKeyEvent: (_, event) {- final keys = HardwareKeyboard.instance;- final composing = _composer.value.composing;- if (event is KeyDownEvent &&- event.logicalKey == LogicalKeyboardKey.enter &&- !keys.isShiftPressed &&- !keys.isControlPressed &&- !keys.isMetaPressed &&- !keys.isAltPressed &&- !(composing.isValid && !composing.isCollapsed)) {- unawaited(_send());- return KeyEventResult.handled;- }- return KeyEventResult.ignored;- },- child: TextField(- key: const ValueKey('super-thread-composer'),- controller: _composer,- focusNode: _focus,- enabled: c.canWrite && c.selected?.archived == false,- minLines: 1,- maxLines: 6,- maxLength: 32000,- keyboardType: TextInputType.multiline,- style: DesktopChrome.text(),- decoration: InputDecoration(- isCollapsed: true,- constraints: const BoxConstraints(),- hintText: 'Reply',- hintStyle: DesktopChrome.text(color: DesktopChrome.muted),- contentPadding: EdgeInsets.zero,- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- disabledBorder: InputBorder.none,- filled: false,- counterText: '',- ),- onChanged: (text) {- c.setThreadDraft(widget.root, text);- setState(() {});+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SuperTabComposerChips(controller: c, files: files),+ Focus(+ onKeyEvent: (_, event) {+ switch (composerEnter(+ event,+ focused: _focus.hasFocus,+ value: _composer.value,+ )) {+ case ComposerEnter.ignore:+ return KeyEventResult.ignored;+ case ComposerEnter.newline:+ insertComposerNewline(_composer, _edited);+ return KeyEventResult.handled;+ case ComposerEnter.send:+ unawaited(_send());+ return KeyEventResult.handled;+ }},+ child: NewHarnessPasteTarget(+ attachments: files,+ enabled: writable && !busy,+ focusNode: _focus,+ child: TextField(+ key: const ValueKey('super-thread-composer'),+ controller: _composer,+ focusNode: _focus,+ enabled: c.canWrite && c.selected?.archived == false,+ minLines: 1,+ maxLines: 6,+ maxLength: kComposerMaxLength,+ keyboardType: TextInputType.multiline,+ style: DesktopChrome.text(),+ decoration: InputDecoration(+ isCollapsed: true,+ constraints: const BoxConstraints(),+ hintText: 'Reply',+ hintStyle: DesktopChrome.text(color: DesktopChrome.muted),+ contentPadding: EdgeInsets.zero,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ filled: false,+ counterText: '',+ ),+ onChanged: _edited,+ ),+ ),),- ),- const SizedBox(height: grid.AppDesktop.controlGap),- Row(- children: [- Expanded(- child: MergeSemantics(- child: Row(- children: [- Checkbox(- key: const ValueKey('super-thread-also-send'),- visualDensity: VisualDensity.compact,- materialTapTargetSize:- MaterialTapTargetSize.shrinkWrap,- value: _alsoSend,- onChanged: writable- ? (on) => setState(() => _alsoSend = on ?? false)- : null,- ),- Flexible(- child: GestureDetector(- onTap: writable- ? () => setState(() => _alsoSend = !_alsoSend)+ if (error != null)+ Padding(+ padding: const EdgeInsets.only(+ top: grid.AppDesktop.controlGap,+ ),+ child: Text(+ error,+ key: const ValueKey('super-thread-error'),+ style: DesktopChrome.control(),+ ),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ Row(+ children: [+ Expanded(+ child: MergeSemantics(+ child: Row(+ children: [+ Checkbox(+ key: const ValueKey('super-thread-also-send'),+ visualDensity: VisualDensity.compact,+ materialTapTargetSize:+ MaterialTapTargetSize.shrinkWrap,+ value: _alsoSend,+ onChanged: writable+ ? (on) =>+ setState(() => _alsoSend = on ?? false): null,- child: MouseRegion(- cursor: writable- ? SystemMouseCursors.click- : MouseCursor.defer,- child: Text(- _alsoSendLabel,- style: DesktopChrome.control(),+ ),+ Flexible(+ child: GestureDetector(+ onTap: writable+ ? () => setState(() => _alsoSend = !_alsoSend)+ : null,+ child: MouseRegion(+ cursor: writable+ ? SystemMouseCursors.click+ : MouseCursor.defer,+ child: Text(+ _alsoSendLabel,+ style: DesktopChrome.control(),+ ),),),),- ),- ],+ ],+ ),),),- ),- AppIconButton(- key: const ValueKey('super-thread-send'),- icon: AppIcons.arrowUp,- tooltip: 'Send reply',- color: DesktopChrome.accent,- onPressed: writable && _composer.text.trim().isNotEmpty- ? () => unawaited(_send())- : null,- ),- ],- ),- ],+ NewHarnessAttachButton(+ attachments: files,+ enabled: writable && !busy,+ ),+ ListenableBuilder(+ listenable: files,+ builder: (context, _) => AppIconButton(+ key: const ValueKey('super-thread-send'),+ icon: AppIcons.arrowUp,+ tooltip: 'Send reply',+ color: DesktopChrome.accent,+ onPressed:+ writable &&+ !busy &&+ (_composer.text.trim().isNotEmpty ||+ !files.isEmpty)+ ? () => unawaited(_send())+ : null,+ ),+ ),+ ],+ ),+ ],+ ),),),);diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 4c2dbc47e..e3f77c0fc 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -28,6 +28,7 @@ import 'profile_actions.dart';import 'live_card.dart';import 'pull_request_facts.dart';import 'pull_requests.dart';+import 'composer_files.dart';import 'composer_newline.dart';import 'controller.dart';import 'dialog_scope.dart';@@ -760,12 +761,7 @@ class _SuperTabViewState extends State<SuperTabView>/// A line break at the cursor. The field only calls [_composerEdited] for/// edits that come from the platform, so this reports its own.- void _insertNewline() {- final value = withNewline(_composer.value);- if (value == null) return;- _composer.value = value;- _composerEdited(value.text);- }+ void _insertNewline() => insertComposerNewline(_composer, _composerEdited);void _composerMoved() {if (!mounted) return;@@ -3242,20 +3238,18 @@ class _SuperTabViewState extends State<SuperTabView>_readAll()) {return KeyEventResult.handled;}- final enterDown =- _focus.hasFocus &&- event is KeyDownEvent &&- event.logicalKey == LogicalKeyboardKey.enter &&- !(composing.isValid && !composing.isCollapsed);- if (!enterDown) return KeyEventResult.ignored;- if (keys.isControlPressed || keys.isMetaPressed) {- return KeyEventResult.ignored;- }- // Shift+Enter and Alt+Enter write the line themselves: the platform- // gives Option+Return none, and a handled key never reaches it.- if (keys.isShiftPressed || keys.isAltPressed) {- _insertNewline();- return KeyEventResult.handled;+ switch (composerEnter(+ event,+ focused: _focus.hasFocus,+ value: _composer.value,+ )) {+ case ComposerEnter.ignore:+ return KeyEventResult.ignored;+ case ComposerEnter.newline:+ _insertNewline();+ return KeyEventResult.handled;+ case ComposerEnter.send:+ break;}unawaited(_send());return KeyEventResult.handled;@@ -3286,23 +3280,7 @@ class _SuperTabViewState extends State<SuperTabView>mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.stretch,children: [- ListenableBuilder(- listenable: _files,- builder: (context, _) => _files.isEmpty- ? const SizedBox.shrink()- : Padding(- padding: const EdgeInsets.only(- bottom: 8,- right: 8,- ),- child: NewHarnessAttachmentChips(- attachments: _files,- enabled: !c.saving,- isUploading: c.isUploading,- progressOf: c.uploadProgress,- ),- ),- ),+ SuperTabComposerChips(controller: c, files: _files),ConstrainedBox(constraints: BoxConstraints(minHeight: grid.AppControl.heightFieldScaled,diff --git a/desktop/lib/widgets/new_harness_attachments.dart b/desktop/lib/widgets/new_harness_attachments.dartindex aabb060dc..ee9e4601c 100644--- a/desktop/lib/widgets/new_harness_attachments.dart+++ b/desktop/lib/widgets/new_harness_attachments.dart@@ -11,9 +11,11 @@ import '../state/harness_attachments.dart';import 'desktop_chrome.dart';import 'new_harness_attachment_chip.dart';-/// Reads picked or dropped files into attachments, and says what was left out.-Future<void> _attach(- BuildContext context,+/// Reads picked or dropped files into attachments, and returns what to tell the+/// person about any left out. The files are added even when the box that asked+/// is gone by now: they were picked for [attachments], and only the message about+/// them needs a place to show.+Future<String?> _attach(HarnessAttachments attachments,Iterable<XFile> files,) async {@@ -21,13 +23,12 @@ Future<void> _attach(for (final file in files)HarnessAttachment(file.name, await file.readAsBytes()),];- if (context.mounted) reportAttachProblem(context, attachments.add(read));+ return attachments.add(read);}/// Attaches the dropped files and hands [onFolders] the dropped folders'/// paths, which hold nothing to read.-Future<void> _attachOrPaste(- BuildContext context,+Future<String?> _attachOrPaste(HarnessAttachments attachments,Iterable<DropItem> items,ValueChanged<List<String>> onFolders,@@ -41,9 +42,7 @@ Future<void> _attachOrPaste(folder ? folders.add(item.path) : files.add(item);}if (folders.isNotEmpty) onFolders(folders);- if (files.isNotEmpty && context.mounted) {- await _attach(context, attachments, files);- }+ return files.isEmpty ? null : _attach(attachments, files);}/// Says what an attach left out, when it left anything.@@ -72,11 +71,12 @@ class NewHarnessAttachButton extends StatelessWidget {size: 16,onPressed: !enabled? null- : () async {+ : () => attachments.reading(() async {final files = await openFiles();- if (files.isEmpty || !context.mounted) return;- await _attach(context, attachments, files);- },+ if (files.isEmpty) return;+ final problem = await _attach(attachments, files);+ if (context.mounted) reportAttachProblem(context, problem);+ }),);}@@ -157,15 +157,15 @@ class _NewHarnessDropZoneState extends State<NewHarnessDropZone> {onDragDone: (details) {_hover(false);final onFolders = widget.onFolders;+ // The box the files were dropped on, held until they are read.+ final attachments = widget.attachments;unawaited(- onFolders == null- ? _attach(context, widget.attachments, details.files)- : _attachOrPaste(- context,- widget.attachments,- details.files,- onFolders,- ),+ attachments.reading(() async {+ final problem = onFolders == null+ ? await _attach(attachments, details.files)+ : await _attachOrPaste(attachments, details.files, onFolders);+ if (context.mounted) reportAttachProblem(context, problem);+ }),);},child: Stack(diff --git a/desktop/lib/widgets/new_harness_paste.dart b/desktop/lib/widgets/new_harness_paste.dartindex 2bfa947a6..f59230586 100644--- a/desktop/lib/widgets/new_harness_paste.dart+++ b/desktop/lib/widgets/new_harness_paste.dart@@ -75,24 +75,26 @@ class _NewHarnessPasteTargetState extends State<NewHarnessPasteTarget> {super.dispose();}+ /// Adds [files] to [target], the box the paste was made in: it may be+ /// another box by the time a clipboard answers.void _attach(+ HarnessAttachments target,Iterable<HarnessAttachment> files, {Iterable<String> oversized = const [],}) {- // Reading a clipboard takes a moment the box may not have survived.- if (!mounted || !widget.enabled) return;- reportAttachProblem(- context,- widget.attachments.addPasted(files, oversized: oversized),- );+ final problem = target.addPasted(files, oversized: oversized);+ if (mounted) reportAttachProblem(context, problem);}void _attachFiles(List<PastedFile> files, {Iterable<String> oversized = const [],- }) => _attach([- for (final file in files) HarnessAttachment(file.name, file.bytes),- ], oversized: oversized);+ }) {+ if (!mounted || !widget.enabled) return;+ _attach(widget.attachments, [+ for (final file in files) HarnessAttachment(file.name, file.bytes),+ ], oversized: oversized);+ }/// ⌘V: what the clipboard holds as attachments, or [pasteText] — the/// field's own paste — when text is what was copied.@@ -101,14 +103,32 @@ class _NewHarnessPasteTargetState extends State<NewHarnessPasteTarget> {/// name as text and its icon as a picture, and neither is what was copied.Future<void> _paste(VoidCallback pasteText) async {if (!widget.enabled) return pasteText();- final copied = await widget.readFiles();- if (copied.files.isNotEmpty || copied.tooLarge.isNotEmpty) {- return _attachFiles(copied.files, oversized: copied.tooLarge);- }- if (pastedTextWins(await _clipboardText())) return pasteText();- final image = await widget.readImage();- if (image == null || image.isEmpty) return pasteText();- _attach([HarnessAttachment(kPastedImageName, image)]);+ // The box this paste was made in, held until the clipboard has answered.+ final target = widget.attachments;+ await target.reading(() async {+ final copied = await widget.readFiles();+ if (copied.files.isNotEmpty || copied.tooLarge.isNotEmpty) {+ return _attachCopied(target, copied);+ }+ if (pastedTextWins(await _clipboardText())) {+ return _pasteText(target, pasteText);+ }+ final image = await widget.readImage();+ if (image == null || image.isEmpty) return _pasteText(target, pasteText);+ _attach(target, [HarnessAttachment(kPastedImageName, image)]);+ });+ }++ void _attachCopied(HarnessAttachments target, CopiedFiles copied) => _attach(+ target,+ [for (final file in copied.files) HarnessAttachment(file.name, file.bytes)],+ oversized: copied.tooLarge,+ );++ /// The field's own paste, unless the box moved on to another message while+ /// the clipboard was read: the text would land in the wrong one.+ void _pasteText(HarnessAttachments target, VoidCallback pasteText) {+ if (mounted && identical(widget.attachments, target)) pasteText();}Future<String?> _clipboardText() async {diff --git a/desktop/test/super_tab_thread_composer_shots_test.dart b/desktop/test/super_tab_thread_composer_shots_test.dartnew file mode 100644index 000000000..ae4f477c4--- /dev/null+++ b/desktop/test/super_tab_thread_composer_shots_test.dart@@ -0,0 +1,135 @@+import 'dart:io';+import 'dart:typed_data';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/harness_attachments.dart';+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_THREAD_COMPOSER_SHOTS'];++/// The thread pane as the PR shows it: its text selected as in the chat, and+/// its reply box holding two files, 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.state['people'] as List).add({+ 'id': 'dee',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ const pm = {+ 'kind': 'agent',+ 'id': 'pm',+ 'name': 'Lead',+ 'displayName': 'River',+ };+ const dee = {'kind': 'person', 'id': 'dee', 'name': '[email protected]'};+ final now = DateTime.now().toUtc();+ void say(+ String text,+ Map<String, Object> author, {+ String? thread,+ int minutesAgo = 0,+ }) {+ server.append(text);+ server.messages.last+ ..['author'] = author+ ..['createdAt'] = now+ .subtract(Duration(minutes: minutesAgo))+ .toIso8601String();+ if (thread != null) {+ server.messages.last+ ..['thread'] = thread+ ..['replyTo'] = thread;+ }+ }++ say(+ 'The build fails on the second run. Logs attached below.',+ dee,+ minutesAgo: 30,+ );+ say(+ 'Which machine was it on? Please send the trace.',+ pm,+ thread: 'message-1',+ minutesAgo: 12,+ );+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';+ final c = server.controller(account: 'dee');+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(1280, 720));+ 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();+ await tester.tap(+ find.byKey(const ValueKey('super-thread-line-message-1')),+ );+ await tester.pumpAndSettle();+ c.threadAttachments('lead', 'message-1').add([+ HarnessAttachment('trace.zip', Uint8List.fromList([1, 2, 3])),+ HarnessAttachment('build.log', Uint8List.fromList([4, 5, 6])),+ ]);+ await tester.enterText(+ find.byKey(const ValueKey('super-thread-composer')),+ 'Here is the trace.',+ );+ await tester.pump();+ tester+ .state<SelectableRegionState>(+ find.descendant(+ of: find.byKey(const ValueKey('super-thread-panel')),+ matching: find.byType(SelectableRegion),+ ),+ )+ .selectAll(SelectionChangedCause.keyboard);+ await tester.pump();++ 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/thread-composer-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, skip: shots == null);+ }+}diff --git a/desktop/test/super_tab_thread_composer_test.dart b/desktop/test/super_tab_thread_composer_test.dartnew file mode 100644index 000000000..489147fff--- /dev/null+++ b/desktop/test/super_tab_thread_composer_test.dart@@ -0,0 +1,648 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';+import 'package:flutter/foundation.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/state/harness_attachments.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/widgets/new_harness_paste.dart';++import 'support/super_tab_fixture.dart';++/// A real 1×1 PNG, so a chip has something to draw.+final _png = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA'+ '60e6kgAAAABJRU5ErkJggg==',+);++/// A picked file, which `XFile.fromData` cannot name off the web.+class _Picked extends XFile {+ _Picked(this.name, this.bytes) : super('/picked/$name');++ @override+ final String name;+ final Uint8List bytes;++ @override+ Future<Uint8List> readAsBytes() async => bytes;+}++/// A file chooser that answers when the test says so.+class _SlowPicker extends FileSelectorPlatform {+ final answer = Completer<List<XFile>>();++ @override+ Future<List<XFile>> openFiles({+ List<XTypeGroup>? acceptedTypeGroups,+ String? initialDirectory,+ String? confirmButtonText,+ }) => answer.future;+}++class _Picker extends FileSelectorPlatform {+ _Picker(this.files);+ final List<XFile> files;++ @override+ Future<List<XFile>> openFiles({+ List<XTypeGroup>? acceptedTypeGroups,+ String? initialDirectory,+ String? confirmButtonText,+ }) async => files;+}++/// The thread pane takes what the main chat takes: text that can be selected+/// and copied, Enter / Shift+Enter / Alt+Enter as in the chat box, and files+/// attached by the paperclip, a drop or a paste, uploaded with the reply.+void main() {+ final desktops = TargetPlatformVariant({+ TargetPlatform.macOS,+ TargetPlatform.windows,+ TargetPlatform.linux,+ });+ final composer = find.byKey(const ValueKey('super-thread-composer'));+ final surface = find.byKey(const ValueKey('super-thread-composer-surface'));+ final send = find.byKey(const ValueKey('super-thread-send'));+ final panel = find.byKey(const ValueKey('super-thread-panel'));+ final line = find.byKey(const ValueKey('super-thread-line-message-1'));++ late SuperTabController shown;++ /// A widget test that takes the view down and settles the controller's+ /// draft save before it ends, as the chat's own tests do.+ void testThread(+ String description,+ Future<void> Function(WidgetTester tester) body, {+ TestVariant<Object?> variant = const DefaultTestVariant(),+ }) => testWidgets(description, (tester) async {+ await body(tester);+ await tester.pumpWidget(const SizedBox());+ await shown.flush();+ }, variant: variant);++ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server, {+ String account = 'owner',+ }) async {+ // One logical pixel per device pixel, so the platform's drop position+ // needs no scaling on any host.+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetDevicePixelRatio);+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = shown = 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);+ return c;+ }++ /// A root and two replies in the lead's thread.+ ConversationServer threaded() {+ final server = ConversationServer()..threads = true;+ server.append('Should we do thread replies?');+ server.append('Yes, like Slack.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1';+ server.append('Agreed.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-2';+ // A second thread to switch to.+ server.append('Second topic.');+ server.append('Noted.');+ server.messages.last+ ..['thread'] = 'message-4'+ ..['replyTo'] = 'message-4';+ return server;+ }++ Future<SuperTabController> openThread(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ final c = await show(tester, server);+ await tester.tap(line);+ await tester.pumpAndSettle();+ expect(panel, findsOneWidget);+ return c;+ }++ HarnessAttachments files(SuperTabController c) =>+ c.threadAttachments('lead', 'message-1');+ List<String> names(SuperTabController c) => [+ for (final file in files(c).files) file.name,+ ];+ TextEditingController field(WidgetTester tester) =>+ tester.widget<TextField>(composer).controller!;++ Future<void> platform(String method, Object arguments) =>+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .handlePlatformMessage(+ 'desktop_drop',+ const StandardMethodCodec().encodeMethodCall(+ MethodCall(method, arguments),+ ),+ (_) {},+ );++ group('selecting and copying', () {+ testThread('thread messages can be selected and copied', (tester) async {+ String? copied;+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.setData') {+ copied = (call.arguments as Map)['text'] as String;+ }+ return null;+ });+ addTearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );+ await openThread(tester, threaded());++ final region = tester.state<SelectableRegionState>(+ find.descendant(of: panel, matching: find.byType(SelectableRegion)),+ );+ region.selectAll(SelectionChangedCause.keyboard);+ await tester.pump();+ Actions.invoke(+ tester.element(+ find.descendant(of: panel, matching: find.text('Yes, like Slack.')),+ ),+ CopySelectionTextIntent.copy,+ );+ await tester.pump();+ expect(copied, contains('Should we do thread replies?'));+ expect(copied, contains('Agreed.'));+ expect(copied, contains('Yes, like Slack.'));+ });+ });++ group('the new line', () {+ testThread('Enter sends the reply to the root', (tester) async {+ final server = threaded();+ final c = await openThread(tester, server);+ await tester.tap(composer);+ await tester.enterText(composer, 'On it');+ await tester.pump();++ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();++ final command = server.posts.single['command'] as Map;+ expect(command['text'], 'On it');+ expect(command['replyTo'], 'message-1');+ expect(field(tester).text, isEmpty);+ expect(c.threadDraft('message-1'), isEmpty);+ }, variant: desktops);++ for (final (name, modifier) in [+ ('Shift', LogicalKeyboardKey.shiftLeft),+ ('Alt/Option', LogicalKeyboardKey.altLeft),+ ]) {+ testThread('$name+Enter adds a line at the cursor and does not send', (+ tester,+ ) async {+ final server = threaded();+ final c = await openThread(tester, server);+ await tester.tap(composer);+ await tester.enterText(composer, 'firstsecond');+ field(tester).selection = const TextSelection.collapsed(offset: 5);++ await tester.sendKeyDownEvent(modifier);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(modifier);+ await tester.pump();++ expect(field(tester).text, 'first\nsecond');+ // The draft follows the box, so closing the thread keeps the line.+ expect(c.threadDraft('message-1'), 'first\nsecond');+ expect(+ field(tester).selection,+ const TextSelection.collapsed(offset: 6),+ );+ expect(server.posts, isEmpty);+ expect(+ tester.widget<TextField>(composer).focusNode!.hasPrimaryFocus,+ isTrue,+ );+ }, variant: desktops);+ }++ testThread('Ctrl+Enter is left to the field and does not send', (+ tester,+ ) async {+ final server = threaded();+ await openThread(tester, server);+ await tester.tap(composer);+ await tester.enterText(composer, 'draft');++ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);+ await tester.pump();++ expect(server.posts, isEmpty);+ });+ });++ group('attaching', () {+ testThread('the paperclip picks files into chips', (tester) async {+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _Picker([+ _Picked('trace.zip', Uint8List.fromList([1, 2, 3])),+ ]);+ addTearDown(() => FileSelectorPlatform.instance = original);+ final c = await openThread(tester, threaded());++ await tester.tap(+ find.descendant(+ of: panel,+ matching: find.byKey(const ValueKey('new-harness-attach')),+ ),+ );+ await tester.pumpAndSettle();++ expect(names(c), ['trace.zip']);+ expect(+ find.descendant(+ of: panel,+ matching: find.byKey(+ const ValueKey('new-harness-attachment:trace.zip'),+ ),+ ),+ findsOneWidget,+ );+ // The chat's own box is not given the thread's file.+ expect(c.attachments('lead').isEmpty, isTrue);+ });++ testThread('a paste still being read when another thread opens goes to the '+ 'thread it was made in', (tester) async {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ final read = Completer<Uint8List?>();+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(+ const MethodChannel('harness/clipboard_image'),+ (call) async =>+ call.method == 'readImagePng' ? await read.future : <String>[],+ );+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ return switch (call.method) {+ 'Clipboard.getData' => null,+ 'Clipboard.hasStrings' => {'value': false},+ _ => null,+ };+ });+ addTearDown(() {+ messenger.setMockMethodCallHandler(+ const MethodChannel('harness/clipboard_image'),+ null,+ );+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);+ });+ final c = await openThread(tester, threaded());+ final first = files(c);++ await tester.tap(composer);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pump();+ c.openThread('message-4');+ await tester.pumpAndSettle();+ read.complete(_png);+ await tester.pumpAndSettle();++ expect(first.files.map((f) => f.name), [kPastedImageName]);+ expect(identical(first, files(c)), isTrue);+ expect(c.threadAttachments('lead', 'message-4').isEmpty, isTrue);+ debugDefaultTargetPlatformOverride = null;+ });++ testThread('a file still being picked when another thread opens is not '+ 'lost with the box', (tester) async {+ final picker = _SlowPicker();+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = picker;+ addTearDown(() => FileSelectorPlatform.instance = original);+ final c = await openThread(tester, threaded());+ final first = files(c);++ await tester.tap(+ find.descendant(+ of: panel,+ matching: find.byKey(const ValueKey('new-harness-attach')),+ ),+ );+ await tester.pump();+ c.openThread('message-4');+ await tester.pumpAndSettle();+ picker.answer.complete([+ _Picked('trace.zip', Uint8List.fromList([1, 2, 3])),+ ]);+ await tester.pumpAndSettle();++ expect(first.files.map((f) => f.name), ['trace.zip']);+ expect(identical(first, files(c)), isTrue);+ expect(c.threadAttachments('lead', 'message-4').isEmpty, isTrue);+ });++ testThread('a dropped file becomes a chip', (tester) async {+ final c = await openThread(tester, threaded());+ final file = File('${Directory.systemTemp.path}/swarm-thread-drop.log');+ await tester.runAsync(() => file.writeAsString('boom'));+ addTearDown(() => file.deleteSync());+ final inside = tester.getCenter(surface);++ await platform('entered', [inside.dx, inside.dy]);+ await tester.pump();+ expect(find.text('Drop files to attach'), findsOneWidget);+ await tester.runAsync(() async {+ await platform('performOperation', [file.path]);+ await Future<void>.delayed(const Duration(milliseconds: 100));+ });+ await tester.pumpAndSettle();++ expect(names(c), ['swarm-thread-drop.log']);+ expect(c.attachments('lead').isEmpty, isTrue);+ });++ testThread('a pasted picture becomes a chip', (tester) async {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(+ const MethodChannel('harness/clipboard_image'),+ (call) async => call.method == 'readImagePng' ? _png : <String>[],+ );+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ return switch (call.method) {+ 'Clipboard.getData' => null,+ 'Clipboard.hasStrings' => {'value': false},+ _ => null,+ };+ });+ addTearDown(() {+ messenger.setMockMethodCallHandler(+ const MethodChannel('harness/clipboard_image'),+ null,+ );+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);+ });+ final c = await openThread(tester, threaded());++ await tester.tap(composer);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pumpAndSettle();++ expect(names(c), [kPastedImageName]);+ expect(c.attachments('lead').isEmpty, isTrue);+ debugDefaultTargetPlatformOverride = null;+ });++ testThread('the files upload to the thread\'s chat, then go with the '+ 'reply to the root', (tester) async {+ final server = threaded();+ final c = await openThread(tester, server);+ files(c).add([+ HarnessAttachment('shot.png', _png),+ HarnessAttachment('notes.txt', Uint8List.fromList([104, 105])),+ ]);+ await tester.enterText(composer, 'See these');+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(+ server.uploads.map((u) => (u['conversationId'], u['name'], u['mime'])),+ [+ ('lead', 'shot.png', 'image/png'),+ ('lead', 'notes.txt', 'text/plain'),+ ],+ );+ final command = server.posts.single['command'] as Map;+ expect(command['text'], 'See these');+ expect(command['replyTo'], 'message-1');+ expect(command['attachmentIds'], ['attachment-1', 'attachment-2']);+ expect(files(c).isEmpty, isTrue);+ expect(field(tester).text, isEmpty);+ });++ testThread('a file alone can be sent, and Also send keeps it', (+ tester,+ ) async {+ final server = threaded();+ final c = await openThread(tester, server);+ files(c).add([HarnessAttachment('a.png', _png)]);+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('super-thread-also-send')));+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ final command = server.posts.single['command'] as Map;+ expect(command['text'], '');+ expect(command['alsoSend'], isTrue);+ expect(command['replyTo'], 'message-1');+ expect(command['attachmentIds'], ['attachment-1']);+ });++ testThread('the chat\'s own files do not go with a thread reply', (+ tester,+ ) async {+ final server = threaded();+ final c = await openThread(tester, server);+ c.attachments('lead').add([HarnessAttachment('chat.png', _png)]);+ files(c).add([HarnessAttachment('thread.png', _png)]);+ await tester.enterText(composer, 'Reply');+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(server.uploads.map((u) => u['name']), ['thread.png']);+ expect(c.attachments('lead').files.map((f) => f.name), ['chat.png']);+ });++ testThread('a refused upload says so, keeps the reply and its files, and '+ 'is not stuck uploading', (tester) async {+ final server = threaded()..failUpload = 'big.bin';+ final c = await openThread(tester, server);+ files(c).add([+ HarnessAttachment('big.bin', Uint8List.fromList([1])),+ ]);+ await tester.enterText(composer, 'Reply');+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(server.posts, isEmpty);+ expect(c.uploading, isFalse);+ expect(names(c), ['big.bin']);+ expect(field(tester).text, 'Reply');+ expect(+ find.descendant(+ of: panel,+ matching: find.text('The file is too large.'),+ ),+ findsOneWidget,+ );+ // Taking the file off answers the refusal; the reply then goes alone.+ server.failUpload = null;+ files(c).remove(files(c).files.single);+ await tester.pump();+ expect(find.text('The file is too large.'), findsNothing);+ await tester.tap(send);+ await tester.pumpAndSettle();+ expect(+ (server.posts.single['command'] as Map).containsKey('attachmentIds'),+ isFalse,+ );+ });+ });++ group('privacy and lifecycle', () {+ test('each conversation\'s thread keeps its own files, even for the same '+ 'root id', () {+ final c = ConversationServer().controller();+ addTearDown(c.dispose);+ final here = c.threadAttachments('lead', 'message-1');+ final there = c.threadAttachments('offline', 'message-1');+ expect(identical(here, there), isFalse);+ expect(identical(here, c.threadAttachments('lead', 'message-1')), isTrue);+ expect(identical(here, c.attachments('lead')), isFalse);+ here.add([+ HarnessAttachment('a.txt', Uint8List.fromList([1])),+ ]);+ expect(there.isEmpty, isTrue);+ });++ test('closing a thread lets go of its empty box and keeps a box that '+ 'holds files', () async {+ final c = threaded().controller();+ addTearDown(c.dispose);+ await c.refresh();+ c.openThread('message-1');+ final empty = c.threadAttachments('lead', 'message-1');+ c.closeThread();+ expect(+ identical(empty, c.threadAttachments('lead', 'message-1')),+ isFalse,+ );++ c.openThread('message-1');+ final held = c.threadAttachments('lead', 'message-1')+ ..add([+ HarnessAttachment('a.txt', Uint8List.fromList([1])),+ ]);+ c.closeThread();+ expect(identical(held, c.threadAttachments('lead', 'message-1')), isTrue);+ await c.flush();+ });++ testThread('access revoked while a file is on its way: the files are '+ 'forgotten and the answer sends nothing', (tester) async {+ final server = threaded();+ final reached = Completer<void>();+ final release = Completer<void>();+ final c = shown = server.controller(+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) async {+ reached.complete();+ await release.future;+ // A transport stops when its upload is given up.+ if (cancel.isCancelled) throw StateError('given up');+ return server.upload(+ tabId: tabId,+ conversationId: conversationId,+ name: name,+ mime: mime,+ bytes: bytes,+ cancel: cancel,+ onProgress: onProgress,+ );+ },+ );+ await c.refresh();+ addTearDown(c.dispose);+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(line);+ await tester.pumpAndSettle();+ final held = files(c)..add([HarnessAttachment('a.png', _png)]);+ await tester.enterText(composer, 'Reply');+ await tester.pump();++ await tester.tap(send);+ await tester.pump();+ await reached.future;+ c.revokeAccess('No longer in this team');+ await tester.pump();+ release.complete();+ await tester.pumpAndSettle();++ expect(panel, findsNothing);+ expect(c.openedThread, isNull);+ expect(server.posts, isEmpty);+ // What was held for the thread went with the access.+ expect(+ identical(held, c.threadAttachments('lead', 'message-1')),+ isFalse,+ );+ expect(c.threadAttachments('lead', 'message-1').isEmpty, isTrue);+ });+ });+}diff --git a/scripts/ui-style-allowlist/desktop.json b/scripts/ui-style-allowlist/desktop.jsonindex 1f561008e..86d833c80 100644--- a/scripts/ui-style-allowlist/desktop.json+++ b/scripts/ui-style-allowlist/desktop.json@@ -89,7 +89,7 @@"edge-insets": 2},"desktop/lib/super_tabs/view.dart": {- "edge-insets": 23,+ "edge-insets": 22,"border-radius": 1}}