Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(swarm): a reply's delivery quotes the message it answers (#1800)

0xken15ade4fbfdf477
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 107d2aee9..6cad536f8 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -251,6 +251,104 @@ describe('Super Tab native delivery handoff', () => {
expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('Leads coordinate: assign multi-part or 15+ minute work to Swarm agent groups; do only answers, lookups and work under 15 minutes yourself; your subagents only read/look up.')
})
+ describe('the replied-to message', () => {
+ const earlier = (fields: Record<string, unknown> = {}) => ({ id: 'question-2', tabId: 'tab', conversationId: 'lead', sequence: 7,
+ author: { kind: 'agent', id: 'lead-agent', name: 'Lead', displayName: 'River' }, source: null,
+ text: 'Plan B: ship the reply quote, then the cleanup.', attachments: [{ id: 'f1', name: 'plan.md', mime: 'text/markdown', size: 9, url: 'https://files/plan.md' }],
+ replyTo: null, recipientIds: [], mentions: [], createdAt: '2026-10-27T08:07:27.418Z', deliveries: [], ...fields })
+ /** The conversation's one-message read answers with `read`; every other call keeps the setup's answer. */
+ const serve = (t: ReturnType<typeof setup>, read: () => unknown) => {
+ const original = vi.mocked(t.call).getMockImplementation()!
+ const reads: string[] = []
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {
+ if (method === 'GET' && path.includes('/messages?')) { reads.push(path); return { status: 200, body: { success: true, data: read() } } }
+ return original(method, path, body)
+ })
+ return reads
+ }
+ const delivered = (t: ReturnType<typeof setup>) => String(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1])
+
+ it('quotes it, as this agent may read it in that conversation, before the answer', async () => {
+ const t = setup({ replyTo: 'question-2', text: 'GO' })
+ const reads = serve(t, () => ({ messages: [earlier()], next: null }))
+ await t.open().tick()
+ expect(reads).toEqual(['/api/super-tabs/tab/conversations/lead/messages?asAgentId=agent&messageId=question-2'])
+ expect(delivered(t)).toContain('Replying to Lead (2026-10-27 08:07 UTC): Plan B: ship the reply quote, then the cleanup.\n'
+ + 'Its attachments: plan.md\n\nMessage message from Collaborator:\nGO')
+ expect(delivered(t)).not.toContain('Read it before interpreting the answer')
+ })
+ it('cuts a long one at 600 characters and says how to read the rest', async () => {
+ const t = setup({ replyTo: 'question-2', text: 'GO' })
+ serve(t, () => ({ messages: [earlier({ text: `${'a'.repeat(600)}THE-END`, attachments: null })], next: null }))
+ await t.open().tick()
+ expect(delivered(t)).toContain(`Replying to Lead (2026-10-27 08:07 UTC): ${'a'.repeat(600)}… (cut; read it all: `)
+ expect(delivered(t)).toContain(`message 'lead' 'question-2')\n\nMessage message from Collaborator:\nGO`)
+ expect(delivered(t)).not.toContain('THE-END')
+ })
+ it('falls back to the command when the read fails, and reads again for the next try', async () => {
+ const t = setup({ replyTo: 'question-2', text: 'GO' })
+ let fail = true
+ const reads = serve(t, () => { if (fail) throw new Error('backend down'); return { messages: [earlier()], next: null } })
+ const host = t.open()
+ await host.tick()
+ expect(delivered(t)).toContain(`In reply to message question-2. Read it before interpreting the answer: `)
+ expect(delivered(t)).not.toContain('Replying to')
+ fail = false
+ t.event('rejected', 'team_waiting_busy')
+ await host.tick()
+ expect(reads).toHaveLength(2)
+ expect(String(vi.mocked(t.core.turns.deliver).mock.calls[1]?.[1])).toContain('Replying to Lead')
+ })
+ it('reads it once per delivery while the terminal holds the input', async () => {
+ const t = setup({ replyTo: 'question-2', text: 'GO' })
+ const reads = serve(t, () => ({ messages: [earlier()], next: null }))
+ const host = t.open()
+ await host.tick()
+ t.event('rejected', 'team_waiting_busy')
+ await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(2)
+ expect(reads).toHaveLength(1)
+ expect(String(vi.mocked(t.core.turns.deliver).mock.calls[1]?.[1])).toContain('Replying to Lead')
+ })
+ it('never types a kept quote once the server refuses the held input, as when the agent left the conversation', async () => {
+ const t = setup({ replyTo: 'question-2', text: 'GO' })
+ serve(t, () => ({ messages: [earlier()], next: null }))
+ const host = t.open()
+ await host.tick()
+ expect(delivered(t)).toContain('Replying to Lead')
+ // Each try claims again; the server refuses a claim for an agent no longer in the conversation (deliveryAllowed).
+ const original = vi.mocked(t.call).getMockImplementation()!
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => (body as Record<string, unknown> | undefined)?.type === 'claim'
+ ? { status: 403, body: { success: false, error: { code: 'DELIVERY_REVOKED', message: 'This instruction is no longer authorized.' } } }
+ : original(method, path, body))
+ t.event('rejected', 'team_waiting_busy')
+ await host.tick().catch(() => {})
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ })
+ it.each([
+ ['the server does not show it to this agent', { messages: [], next: null }],
+ ['it is another agent\'s private notice', { messages: [earlier({ source: { kind: 'agent-only' }, recipientIds: ['someone-else'] })], next: null }],
+ ['it belongs to another conversation', { messages: [earlier({ conversationId: 'elsewhere' })], next: null }],
+ ['it is another message', { messages: [earlier({ id: 'question-3' })], next: null }],
+ ])('never quotes it when %s', async (_case, page) => {
+ const t = setup({ replyTo: 'question-2', text: 'GO' })
+ serve(t, () => page)
+ await t.open().tick()
+ expect(delivered(t)).not.toContain('Replying to')
+ expect(delivered(t)).not.toContain('Plan B')
+ expect(delivered(t)).toContain('In reply to message question-2. Read it before interpreting the answer: ')
+ })
+ it('reads nothing for a message that replies to nothing, or for an agent-only notice', async () => {
+ for (const fields of [{}, { replyTo: 'question-2', source: { kind: 'agent-only' } }]) {
+ const t = setup(fields)
+ const reads = serve(t, () => ({ messages: [earlier()], next: null }))
+ await t.open().tick()
+ expect(reads).toEqual([])
+ expect(delivered(t)).not.toContain('Replying to')
+ }
+ })
+ })
+
it('types only the notice for an agent-only delivery, with no invitation to reply in the conversation', async () => {
const t = setup({ text: 'Harness updated your built-in swarm-lead skill.', source: { kind: 'agent-only' } })
await t.open().tick()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 7b9ac8b78..4587a92bc 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -4,7 +4,7 @@ import { SwarmGrids } from './swarmGrids.js'
import { retainContributions } from './retention.js'
import { configurationObservation } from './configuration.js'
import { NativeRecorder, nativeJournalFile } from './native.js'
-import { attachedFiles } from './attachments.js'
+import { attachedFiles, attachmentsOf } from './attachments.js'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
@@ -25,6 +25,8 @@ import { SwarmReads } from './swarmReads.js'
import { UPDATE_REQUIRED } from './readContract.js'
type Json = Record<string, unknown>
+const agentCommandOf = (entry: Entry, prefix: string) => `${prefix} --tab ${shellQuote(entry.tabId)} --agent ${shellQuote(entry.agentId)}`
+const readCommand = (entry: Entry, prefix: string, group: string, id: string) => `${agentCommandOf(entry, prefix)} message ${shellQuote(group)} ${shellQuote(id)}`
export { backend, identifier, object, SuperTabHostError } from './wire.js'
import { backend, ENDED_WORK, identifier, object, SuperTabHostError } from './wire.js'
import { recordSwarmSkillNotice, refreshSwarmSkill, type SkillRefresh, type SwarmSkillGrant, type SwarmSkillMode } from '../lib/swarmSkills.js'
@@ -186,6 +188,9 @@ export class SuperTabHost {
/** Each delivery's downloaded files, so input held by a busy terminal is not downloaded again on every retry. Only a
* complete download is kept: a failed one is tried again before the next delivery of the same message. */
private readonly files = new Map<string, string>()
+ /** Each delivery's quote of the message it replies to ('' when none is shown), read once like its files. A failed read is
+ * not kept, so the next try reads again. */
+ private readonly quotes = new Map<string, string>()
private readonly active = new Set<string>()
private readonly authorized = new Map<string, number>()
private readonly withheld = new WithheldDeliveries()
@@ -665,6 +670,7 @@ export class SuperTabHost {
else if (key.startsWith('claim:') && listsRead.has(agentKey) && !listed.has(key.slice('claim:'.length))) this.deliveryRetries.delete(key)
}
for (const deliveryId of this.files.keys()) if (!this.journal.entries[deliveryId]) this.files.delete(deliveryId)
+ for (const deliveryId of this.quotes.keys()) if (!this.journal.entries[deliveryId]) this.quotes.delete(deliveryId)
for (const entry of Object.values(this.journal.entries)) {
const id = typedId(entry)
if (!seen.has(entry.deliveryId)) {
@@ -1000,6 +1006,11 @@ export class SuperTabHost {
}
this.prefix ??= this.agentCommand(this.core, this.machineId).catch(() => fullCommandPrefix(this.core.daemon, this.machineId))
const command = await this.prefix
+ let quote = this.quotes.get(deliveryId)
+ if (quote === undefined) {
+ quote = await this.repliedTo(entry, message, command)
+ if (quote !== undefined) this.quotes.set(deliveryId, quote)
+ }
if (this.stopped || this.journal.entries[deliveryId] !== entry) return
this.authorized.set(id, this.now() + 2_500)
if (!(await this.leases()) || this.stopped) { this.authorized.delete(id); return }
@@ -1009,7 +1020,32 @@ export class SuperTabHost {
entry.stage = 'submitting'
this.persist()
this.active.add(id)
- this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, files, command), id)
+ this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, files, command, quote ?? ''), id)
+ }
+
+ /** The message a reply answers, quoted into the delivery: agents skipped the command that reads it, and a Lead took Ken's
+ * "GO" as approving a different plan. It is read as this agent through the conversation's own one-message read, so the
+ * server shows only what this agent may already read there; what comes back must still be that message, in that
+ * conversation, and not another agent's private notice. '' when nothing may be quoted, undefined when the read failed. */
+ private async repliedTo(entry: Entry, message: Json, prefix: string): Promise<string | undefined> {
+ const group = message.conversationId as string, id = message.replyTo
+ if (!identifier(id) || object(message.source).kind === 'agent-only') return ''
+ let page: Json
+ try {
+ page = object(await backend(this.core, 'GET', `/api/super-tabs/${entry.tabId}/conversations/${group}/messages?asAgentId=${entry.agentId}&messageId=${id}`))
+ } catch (error) {
+ this.log(`reply ${id} for delivery ${entry.deliveryId} unreadable: ${error instanceof Error ? error.message : String(error)}`)
+ return undefined
+ }
+ const quoted = (Array.isArray(page.messages) ? page.messages : []).map(object).find(m => m.id === id && m.conversationId === group)
+ if (!quoted || typeof quoted.text !== 'string') return ''
+ if (object(quoted.source).kind === 'agent-only' && !(Array.isArray(quoted.recipientIds) && quoted.recipientIds.includes(entry.agentId))) return ''
+ const at = typeof quoted.createdAt === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(quoted.createdAt) ? ` (${quoted.createdAt.slice(0, 16).replace('T', ' ')} UTC)` : ''
+ const names = attachmentsOf(quoted).map(a => a.name)
+ // About 600 characters keeps a long plan from crowding out the answer; the cut says where the rest is.
+ const text = quoted.text.length > 600 ? `${quoted.text.slice(0, 600)}… (cut; read it all: ${readCommand(entry, prefix, group, id)})` : quoted.text
+ return `Replying to ${String(object(quoted.author).name ?? 'a collaborator')}${at}: ${text}\n`
+ + (names.length ? `Its attachments: ${names.join(', ')}\n` : '') + '\n'
}
private async recordConfigurations(rows: unknown[]): Promise<void> {
@@ -1033,12 +1069,12 @@ export class SuperTabHost {
} catch (error) { this.log(error instanceof Error ? error.message : String(error)) }
}
- private prompt(entry: Entry, message: Json, files: string, prefix: string): string {
- const command = `${prefix} --tab ${shellQuote(entry.tabId)} --agent ${shellQuote(entry.agentId)}`
+ private prompt(entry: Entry, message: Json, files: string, prefix: string, quote: string): string {
+ const command = agentCommandOf(entry, prefix)
const group = message.conversationId as string
- const reply = identifier(message.replyTo)
- ? `In reply to message ${message.replyTo}. Read it before interpreting the answer: ${command} message ${shellQuote(group)} ${shellQuote(message.replyTo)}\n\n`
- : ''
+ const reply = quote || (identifier(message.replyTo)
+ ? `In reply to message ${message.replyTo}. Read it before interpreting the answer: ${readCommand(entry, prefix, group, message.replyTo)}\n\n`
+ : '')
const source = object(message.source)
// A notice for this agent alone (a skill update): nobody else sees it, so nothing invites a reply in the conversation.
if (source.kind === 'agent-only') return String(message.text)