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.

Merge batch 11-05 b1107: #3060 #3065 (#3076)

0xken15aed9c89ba4fe
diff --git a/backend/integration/superTabInstructions.test.ts b/backend/integration/superTabInstructions.test.ts
index a4244115a..5e0697ed4 100644
--- a/backend/integration/superTabInstructions.test.ts
+++ b/backend/integration/superTabInstructions.test.ts
@@ -110,7 +110,10 @@ describe('project instructions storage', () => {
expect(second.json().error).toMatchObject({ code: 'INSTRUCTIONS_STALE', revision: 2, text: 'Reviews run on Opus.' })
expect((await post(peer, tab, save(2, 'Reviews run on Opus.\nTests run on the Mac.', 'Tests run on the Mac'))).statusCode).toBe(200)
const lines = (await store.messages(owner, tab, 'lead', {})).messages.filter(m => (m.source as { kind?: string } | null)?.kind === 'instructions')
- expect(lines.map(m => m.text)).toEqual(['owner changed the instructions: Reviews run on Opus.', 'peer changed the instructions: Tests run on the Mac.'])
+ // Each line shows what its save really changed against the stored revision before it (#3021): the first replaced the template.
+ expect(lines.map(m => m.text)).toEqual([expect.stringMatching(/^owner changed the instructions: Reviews run on Opus\.\n\nRemoved section: Project instructions\n[^]*\n\nand \d+ more changes\.$/),
+ // Its text adds a line to the same paragraph (no blank line), so the paragraph shows whole, as it was and as it is.
+ 'peer changed the instructions: Tests run on the Mac.\n\nRemoved: Reviews run on Opus.\nAdded: Reviews run on Opus. Tests run on the Mac.'])
expect((await db.superTabInstructions.findFirstOrThrow({ where: { tabId: tab, projectId: 'lead' } })).revision).toBe(3)
})
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 500e1f1fd..c59a12f14 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -1829,7 +1829,7 @@ describe('Super Tabs on a real Mongo replica set', () => {
expect((await store.read(owner, tab)).state).not.toHaveProperty('rules')
const rows = (await store.messages(owner, tab, chat, {})).messages.filter(m => m.source).map(m => m.text)
// After the row naming who added the Lead (#2207).
- expect(rows).toEqual([expect.stringMatching(/^owner added [^.]+\.$/), 'Lead changed the instructions for owner: Routing: Only this Mac.'])
+ expect(rows).toEqual([expect.stringMatching(/^owner added [^.]+\.$/), 'Lead changed the instructions for owner: Routing: Only this Mac.\n\nIn Routing:\nAdded: Only this Mac.'])
expect((await store.read(owner, tab)).state.projects!.map(p => p.id)).toEqual([projectId])
})
it('keeps a new Swarm\'s folder from tab.project on its first project, so the repository can be shared and the host uses it', async () => {
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 21219f389..81b538ee9 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -3077,7 +3077,7 @@ describe('the owner\'s rules', () => {
writtenBy: { kind: 'agent', id: f.lead }, askedBy: 'owner', at: 1000 })
expect(f.state.projects![0]).toMatchObject({ instructionsRevision: 2, instructionsHash: instructionsHash(text) })
// One line, as any save: in the writer's name, for the member who asked.
- expect(effects.messages).toEqual([expect.objectContaining({ conversationId: 'lead', text: 'lead changed the instructions for owner: Routing: No Haiku.',
+ expect(effects.messages).toEqual([expect.objectContaining({ conversationId: 'lead', text: 'lead changed the instructions for owner: Routing: No Haiku.\n\nIn Routing:\nAdded: No Haiku.',
source: { kind: 'instructions', projectId: 'lead', revision: 2 } })])
expect(f.state).not.toHaveProperty('rules')
// A project at revision 0 runs on the template: the rule lands in its copy, as revision 1. A person asks for themselves.
@@ -3085,7 +3085,7 @@ describe('the owner\'s rules', () => {
const first = f.run(set({ kind: 'preferIdle' }, 'Idle agents first.'))
expect(first.instructions).toMatchObject({ revision: 1, text: appendRouting(INSTRUCTIONS_TEMPLATE, 'Idle agents first.'), askedBy: 'owner',
writtenBy: { kind: 'person', id: 'owner' } })
- expect(first.messages.map(m => m.text)).toEqual(['owner changed the instructions: Routing: Idle agents first.'])
+ expect(first.messages.map(m => m.text)).toEqual(['owner changed the instructions: Routing: Idle agents first.\n\nIn Routing:\nAdded: Idle agents first.'])
// The stored document must be the revision the state names, or nothing is written.
expect(() => f.run(set({ kind: 'preferIdle' }), owner, { instructions: { revision: 7, text: doc } }))
.toThrow(expect.objectContaining({ code: 'INSTRUCTIONS_UNAVAILABLE' }))
@@ -3225,7 +3225,7 @@ describe('the owner\'s rules in a Swarm of projects', () => {
const added = f.run(machines(f.app), f.lead, { ...said(), ...doc() })
expect(added.instructions).toMatchObject({ projectId: projectOfChat(f, f.app).id, revision: 2, text: appendRouting('# Doc\n\n## Routing\n\n- Opus.', 'Only m1.'),
askedBy: 'owner', summary: 'Routing: Only m1.' })
- expect(added.messages).toEqual([expect.objectContaining({ conversationId: f.app, text: 'app-lead changed the instructions for owner: Routing: Only m1.',
+ expect(added.messages).toEqual([expect.objectContaining({ conversationId: f.app, text: 'app-lead changed the instructions for owner: Routing: Only m1.\n\nIn Routing:\nAdded: Only m1.',
source: { kind: 'instructions', projectId: projectOfChat(f, f.app).id, revision: 2 } })])
expect(f.state).not.toHaveProperty('rules')
expect(f.run({ type: 'rule.remove', ruleId: 'any', askedIn: { conversationId: f.app, messageId: 'm2' } }, f.lead, said()).result).toMatchObject({ ignored: true })
@@ -3263,7 +3263,7 @@ describe('the owner\'s rules in a Swarm of projects', () => {
const mine = f.run({ type: 'project.create', name: 'Peer', visibility: 'private', brief: '' }, peer).result as { projectId: string; conversationId: string }
const added = f.run(forbid(mine.projectId, 'haiku'), peer, doc())
expect(added.instructions).toMatchObject({ projectId: mine.projectId, askedBy: 'peer' })
- expect(added.messages).toEqual([expect.objectContaining({ conversationId: mine.conversationId, text: 'peer changed the instructions: Routing: No haiku.' })])
+ expect(added.messages).toEqual([expect.objectContaining({ conversationId: mine.conversationId, text: 'peer changed the instructions: Routing: No haiku.\n\nIn Routing:\nAdded: No haiku.' })])
expect(() => f.run(forbid(mine.projectId, 'opus'), owner, doc())).toThrow('unavailable')
// Public, any member who reads it writes its instructions, the Swarm owner too.
f.run({ type: 'project.sharing', projectId: mine.projectId, visibility: 'public', memberIds: [] }, peer)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index a18646ee1..024bbb458 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -57,6 +57,7 @@ import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './
import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
+import { instructionsChange } from './instructionsDiff.js'
import { BUILT_IN_HEADING } from './pmSchedule.js'
import { placeAfter, queueSiblings } from './taskQueue.js'
@@ -1107,9 +1108,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
/** Accepted, kept nowhere: an older client's save of what each project's instructions say now (IGNORED_NOTE). */
const ignored = () => Object.assign(result, { ignored: true, note: IGNORED_NOTE })
- /** A new revision of [project]'s instructions from revision [current], with one line in its chat in the writer's name, for
- * the member who asked when that is someone else: what instructions.save and an older client's rule.set write. */
- const saveInstructions = (project: SwarmProject, current: number, text: string, summary: string, askedBy: string) => {
+ /** A new revision of [project]'s instructions from revision [current], whose text was [before] (null when the store could not
+ * read it), with one line in its chat in the writer's name, for the member who asked when that is someone else: what
+ * instructions.save and an older client's rule.set write. The line shows the lines really removed and added under the
+ * writer's summary, so nobody takes the summary's word for what was saved (#3021). */
+ const saveInstructions = (project: SwarmProject, current: number, before: string | null, text: string, summary: string, askedBy: string) => {
const hash = instructionsHash(text)
mutableProjects(state)
Object.assign(projectOf(state, project.id), { instructionsRevision: current + 1, instructionsHash: hash })
@@ -1118,7 +1121,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A save for someone else, a coordinator's or a person's, names the member it was for, so the record never names an asker
// the chat line did not (review of phase 2).
const asked = askedBy !== sender.id ? ` for ${person(state, askedBy).email.split('@')[0]}` : ''
- message(project.leadConversationId, `${who} changed the instructions${asked}: ${summary}${/[.!?]$/.test(summary) ? '' : '.'}`, [], null,
+ message(project.leadConversationId, `${who} changed the instructions${asked}: ${summary}${/[.!?]$/.test(summary) ? '' : '.'}\n\n${instructionsChange(before, text)}`, [], null,
{ kind: 'instructions', projectId: project.id, revision: current + 1 })
Object.assign(result, { projectId: project.id, revision: current + 1, hash })
}
@@ -1789,7 +1792,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
Object.assign(result, { projectId: project.id, revision: current, hash, unchanged: true })
break
}
- saveInstructions(project, current, command.text, command.summary, askedBy)
+ // The text this save replaces, which the store read for the stale check above: what its chat line diffs against.
+ const before = !current ? INSTRUCTIONS_TEMPLATE : context.instructions?.revision === current ? context.instructions.text : null
+ saveInstructions(project, current, before, command.text, command.summary, askedBy)
break
}
case 'note.add': {
@@ -2109,7 +2114,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// Revision 0 runs on the template (design, Migration); otherwise the stored document of this revision, read by the store.
const stored = !current ? INSTRUCTIONS_TEMPLATE : context.instructions?.revision === current ? context.instructions.text
: fail('INSTRUCTIONS_UNAVAILABLE', 'This project\'s instructions cannot be read now. Try again in a moment.', 503)
- saveInstructions(project, current, appendRouting(stored, command.text), routingSummary(command.text), askedBy)
+ saveInstructions(project, current, stored, appendRouting(stored, command.text), routingSummary(command.text), askedBy)
break
}
case 'rule.remove':
diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.ts
index 87ae17363..a53f333cd 100644
--- a/backend/src/superTabs/instructions.test.ts
+++ b/backend/src/superTabs/instructions.test.ts
@@ -11,6 +11,8 @@ const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'own
const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+/** A save's chat line: its summary line, above the change it shows. */
+const firstLine = (text: string) => text.split('\n')[0]
function fixture() {
let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
@@ -245,7 +247,32 @@ describe('instructions.save', () => {
expect(f.state.projects![0]).toMatchObject({ instructionsRevision: 2, instructionsHash: instructionsHash('Reviews run on Opus.') })
expect(effects.messages).toHaveLength(1)
expect(effects.messages[0]).toMatchObject({ conversationId: 'lead', author: { kind: 'person', id: 'owner' }, recipients: [],
- text: 'owner changed the instructions: Reviews run on Opus.', source: { kind: 'instructions', projectId: 'lead', revision: 2 } })
+ source: { kind: 'instructions', projectId: 'lead', revision: 2 } })
+ expect(firstLine(effects.messages[0]!.text)).toBe('owner changed the instructions: Reviews run on Opus.')
+ })
+
+ // Ken, 11-05: the line named only the PM's summary, so "I wrote it into the instructions" could not be checked (#3021).
+ it('posts the lines the save really added and removed, from the revision it replaced, under the summary', () => {
+ const f = fixture()
+ const stored = { instructions: { revision: 1, text: '# Rules\n\n- Opus builds.\n- Haiku reviews.' } }
+ const effects = f.run(save(1, '# Rules\n\n- Opus builds.\n- Sonnet reviews.\n- Tests run first.'), owner, stored)
+ expect(effects.messages).toEqual([expect.objectContaining({ conversationId: 'lead', source: { kind: 'instructions', projectId: 'lead', revision: 2 },
+ text: 'owner changed the instructions: Reviews run on Opus.\n\nIn Rules:\nRemoved: Haiku reviews.\nAdded: Sonnet reviews.\nAdded: Tests run first.' })])
+ // The summary never stands in for the change: a summary claiming a rule shows the lines the text really holds.
+ const claimed = f.run(save(2, '# Rules\n\n- Opus builds.\n- Sonnet reviews.\n- Tests run first.\n- Ship daily.', { summary: 'Added the Haiku ban' }),
+ owner, { instructions: { revision: 2, text: '# Rules\n\n- Opus builds.\n- Sonnet reviews.\n- Tests run first.' } })
+ expect(claimed.messages[0]!.text).toBe('owner changed the instructions: Added the Haiku ban.\n\nIn Rules:\nAdded: Ship daily.')
+ })
+
+ it('shows 12 items of a long change and how many more, and says when the earlier revision could not be read', () => {
+ const f = fixture()
+ const rules = Array.from({ length: 30 }, (_, i) => `- Rule ${i + 1}.`)
+ const long = f.run(save(1, ['# Rules', ...rules].join('\n')), owner, { instructions: { revision: 1, text: '# Rules' } }).messages[0]!.text
+ expect(long).toBe(['owner changed the instructions: Reviews run on Opus.', '', 'In Rules:', ...rules.slice(0, 12).map(r => `Added: ${r.slice(2)}`), '',
+ 'and 18 more changes.'].join('\n'))
+ // The store reads the current revision for every save (store.ts); one it could not read is said, never shown as no change.
+ expect(f.run(save(2, 'Other.'), owner, { instructions: null }).messages[0]!.text)
+ .toBe('owner changed the instructions: Reviews run on Opus.\n\nThe earlier revision could not be read, so the change is not shown.')
})
it('refuses a save on an older revision with the current revision and text, so the caller can merge', () => {
@@ -271,7 +298,8 @@ describe('instructions.save', () => {
expect(() => f.run(save(1, 'PM text.', { askedBy: 'stranger' }), as(lead))).toThrow(expect.objectContaining({ code: 'ASKED_BY_UNAVAILABLE' }))
const effects = f.run(save(1, 'PM text.', { askedBy: 'peer' }), as(lead))
expect(effects.instructions).toMatchObject({ writtenBy: { kind: 'agent', id: lead }, askedBy: 'peer' })
- expect(effects.messages[0]).toMatchObject({ author: { kind: 'agent', id: lead }, text: 'lead changed the instructions for peer: Reviews run on Opus.' })
+ expect(effects.messages[0]).toMatchObject({ author: { kind: 'agent', id: lead } })
+ expect(firstLine(effects.messages[0]!.text)).toBe('lead changed the instructions for peer: Reviews run on Opus.')
expect(() => f.run(save(2, 'Engineer text.', { askedBy: 'owner' }), as(engineer))).toThrow(expect.objectContaining({ code: 'COORDINATOR_REQUIRED' }))
const buddy = f.add('buddy', group)
f.state.agents.find(a => a.id === buddy)!.buddyOf = { personId: 'owner', generation: 'tab' }
@@ -286,8 +314,8 @@ describe('instructions.save', () => {
f.invite()
const effects = f.run(save(1, 'Peer text.', { askedBy: 'peer' }))
expect(effects.instructions).toMatchObject({ writtenBy: { kind: 'person', id: 'owner' }, askedBy: 'peer' })
- expect(effects.messages[0]!.text).toBe('owner changed the instructions for peer: Reviews run on Opus.')
- expect(f.run(save(2, 'Owner text.', { askedBy: 'owner' })).messages[0]!.text).toBe('owner changed the instructions: Reviews run on Opus.')
+ expect(firstLine(effects.messages[0]!.text)).toBe('owner changed the instructions for peer: Reviews run on Opus.')
+ expect(firstLine(f.run(save(2, 'Owner text.', { askedBy: 'owner' })).messages[0]!.text)).toBe('owner changed the instructions: Reviews run on Opus.')
})
it('keeps a document within 64 KB and a summary on one line, and saves nothing new for the same text', () => {
diff --git a/backend/src/superTabs/instructionsDiff.test.ts b/backend/src/superTabs/instructionsDiff.test.ts
new file mode 100644
index 000000000..6a9f31bd0
--- /dev/null
+++ b/backend/src/superTabs/instructionsDiff.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import { instructionsChange, CHANGE_ITEMS, ITEM_CHARS } from './instructionsDiff.js'
+
+/** The words every line of a change starts with: none can open a Markdown block (a heading, list, quote, code or table). */
+const LINE_START = /^(?:In .+:|Added: |Removed: |Added section: |Removed section: |and \d+ more changes?\.$|$)/
+
+describe('instructionsChange', () => {
+ // Ken, 11-05 (#3021): instructions wrap at about 120 characters, so one bullet spans several lines; a one-word edit rewraps
+ // it. Compared by line, it showed fragments, none of them the bullet's start. Compared by item, it shows the whole rule.
+ it('shows a rewrapped bullet\'s whole old and new words, under the section it sits in', () => {
+ const before = '# Project instructions\n\n## Routing\n\n### Models\n\n- No agent runs below high effort,\n and none on Haiku.\n- Reviewers run on Opus.'
+ const after = '# Project instructions\n\n## Routing\n\n### Models\n\n- No agent runs below high\n effort, and none on Claude Haiku.\n- Reviewers run on Opus.'
+ expect(instructionsChange(before, after)).toBe('In Routing › Models:\nRemoved: No agent runs below high effort, and none on Haiku.\n'
+ + 'Added: No agent runs below high effort, and none on Claude Haiku.')
+ })
+
+ it('shows nothing for a rewrap or spacing alone, and says so', () => {
+ const before = '## Workflow\n\nThe PM opens each task with its goal and\n"Done when".\n\n- One request is one task.'
+ expect(instructionsChange(before, '## Workflow\n\n\nThe PM opens each task\nwith its goal and "Done when".\n- One request is one task.\n'))
+ .toBe('Only spacing and line breaks changed.')
+ })
+
+ it('joins a paragraph\'s wrapped lines into one item', () => {
+ expect(instructionsChange('Intro.\n\nEvery agent works by these\ninstructions.', 'Intro.\n\nEvery agent works by these\ninstructions, always.'))
+ .toBe('Removed: Every agent works by these instructions.\nAdded: Every agent works by these instructions, always.')
+ })
+
+ it('shows 12 items of a long change, then how many more changes there are', () => {
+ const rules = Array.from({ length: 20 }, (_, i) => `- Rule ${i + 1}.`)
+ const change = (n: number) => instructionsChange('## Rules\n\n- Rule 0.', ['## Rules', '', '- Rule 0.', ...rules.slice(0, n)].join('\n'))
+ expect(CHANGE_ITEMS).toBe(12)
+ expect(change(20)).toBe(['In Rules:', ...rules.slice(0, 12).map(r => `Added: ${r.slice(2)}`), '', 'and 8 more changes.'].join('\n'))
+ expect(change(13).endsWith('\n\nand 1 more change.')).toBe(true)
+ expect(change(12)).not.toContain('more change')
+ })
+
+ it('drops list markers, so a numbered step inserted shows alone and the steps renumbered after it do not', () => {
+ expect(instructionsChange('## Workflow\n\n1. Plan.\n2. Build.\n3. Ship.', '## Workflow\n\n1. Plan.\n2. Test first.\n3. Build.\n4. Ship.'))
+ .toBe('In Workflow:\nAdded: Test first.')
+ })
+
+ it('names each change\'s own section, a section added too', () => {
+ const before = '# Doc\n\n## Roles\n\n### PM\n\n- Talks with people.\n\n## Routing\n\n- Opus builds.'
+ const after = '# Doc\n\n## Roles\n\n### PM\n\n- Talks with people.\n- Merges work.\n\n## Routing\n\n- Opus builds.\n\n### Testers\n\n- A Mac for Desktop.'
+ expect(instructionsChange(before, after)).toBe('In Roles › PM:\nAdded: Merges work.\n\nIn Routing:\nAdded section: Testers\n\n'
+ + 'In Routing › Testers:\nAdded: A Mac for Desktop.')
+ })
+
+ it('keeps a saved item\'s Markdown from opening a block in the chat', () => {
+ const change = instructionsChange('A.', 'A.\n\n```\ncode\n```\n\n> quote\n\n| a | b |\n|---|---|\n\n---\n\n<details>')
+ for (const line of change.split('\n')) expect(line).toMatch(LINE_START)
+ })
+
+ it('cuts a very long item, never the count', () => {
+ const long = 'x'.repeat(ITEM_CHARS + 50)
+ expect(instructionsChange('A.', `A.\n\n${long}`)).toBe(`Added: ${'x'.repeat(ITEM_CHARS - 1)}…`)
+ })
+
+ it('says when the earlier revision could not be read, rather than showing no change', () => {
+ expect(instructionsChange(null, 'Anything.')).toBe('The earlier revision could not be read, so the change is not shown.')
+ })
+
+ it('shows a rewrite too big to compare item by item as its real removed and added items, quickly', () => {
+ const before = Array.from({ length: 2000 }, (_, i) => `- Old ${i}`).join('\n')
+ const after = Array.from({ length: 2000 }, (_, i) => `- New ${i}`).join('\n')
+ const started = performance.now()
+ const change = instructionsChange(before, after)
+ expect(performance.now() - started).toBeLessThan(500)
+ expect(change).toBe([...Array.from({ length: 12 }, (_, i) => `Removed: Old ${i}`), '', 'and 3988 more changes.'].join('\n'))
+ })
+
+ it('compares a large document\'s small change item by item', () => {
+ const items = Array.from({ length: 2000 }, (_, i) => `- Item ${i}`)
+ const after = [...items.slice(0, 500), '- Inserted', ...items.slice(500, 1500), ...items.slice(1501)]
+ expect(instructionsChange(items.join('\n'), after.join('\n'))).toBe('Added: Inserted\nRemoved: Item 1500')
+ })
+})
diff --git a/backend/src/superTabs/instructionsDiff.ts b/backend/src/superTabs/instructionsDiff.ts
new file mode 100644
index 000000000..6f5de9964
--- /dev/null
+++ b/backend/src/superTabs/instructionsDiff.ts
@@ -0,0 +1,150 @@
+/**
+ * What an instructions save really changed, for the line it posts in the project chat (task #3021, Ken 11-05): the items it
+ * removed and added against the revision it replaced, so a PM's "I wrote it into the instructions" can be checked.
+ * Computed once per save from the two texts the save already holds (commands.ts saveInstructions); nothing is stored or
+ * read for it.
+ *
+ * Instructions are hard-wrapped, so one bullet spans several lines and a one-word edit rewraps it. They are compared by
+ * item instead: a bullet, a numbered step, a paragraph or a fenced block, its wrapped lines joined, its list marker
+ * dropped (so renumbered steps are no change), and each heading. A change is written in words, "Added:" or "Removed:"
+ * under the section it sits in ("In Routing › Models:"), which reads the same in every client with no colouring (Ken's
+ * review; River chose words).
+ */
+
+/** Changed items the chat line shows; the rest are counted. */
+export const CHANGE_ITEMS = 12
+/** Characters of one shown item; a longer one is cut, never left out. */
+export const ITEM_CHARS = 400
+/** Edits compared item by item. Past this a 64 KB rewrite would cost (N+M)·D steps, so the region between the common head
+ * and tail is shown as removed and added whole: still the real items, only not the fewest changes. */
+const MAX_EDITS = 1000
+
+/** One item of a document: its words on one line, the section path it sits under, and whether it is a heading. */
+interface Item { key: string; text: string; path: string; heading: boolean }
+interface Edit { added: boolean; item: Item }
+
+/** The words under the summary of a save from [before] to [after]: each changed item on its own line, starting "Added:" or
+ * "Removed:", grouped under its section, then how many more changes there are. Every line starts with one of those words,
+ * so a saved item's Markdown never opens a heading, list, quote, code block or table in the chat. [before] null is an
+ * earlier revision the store could not read: said, never shown as no change. */
+export function instructionsChange(before: string | null, after: string): string {
+ if (before === null) return 'The earlier revision could not be read, so the change is not shown.'
+ const edits = itemEdits(items(before), items(after))
+ if (!edits.length) return 'Only spacing and line breaks changed.'
+ const lines: string[] = []
+ let section: string | undefined
+ for (const { added, item } of edits.slice(0, CHANGE_ITEMS)) {
+ if (item.path !== section) {
+ if (lines.length) lines.push('')
+ if (item.path) lines.push(`In ${item.path}:`)
+ section = item.path
+ }
+ lines.push(`${added ? 'Added' : 'Removed'}${item.heading ? ' section' : ''}: ${cut(item.text)}`)
+ }
+ const more = edits.length - CHANGE_ITEMS
+ if (more > 0) lines.push('', `and ${more} more change${more === 1 ? '' : 's'}.`)
+ return lines.join('\n')
+}
+
+const HEADING = /^ {0,3}(#{1,6})[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*$/
+const LIST_ITEM = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+(.*)$/
+const FENCE = /^ {0,3}(?:```|~~~)/
+
+/** [text]'s items in document order. A section's path is its headings below the document's title (level 1), or the title
+ * alone when it has no others. */
+function items(text: string): Item[] {
+ const found: Item[] = []
+ const headings: (string | undefined)[] = []
+ const pathOf = (levels: (string | undefined)[]) => {
+ const below = levels.slice(1).filter((h): h is string => !!h)
+ return (below.length ? below : levels.slice(0, 1).filter((h): h is string => !!h)).join(' › ')
+ }
+ let open: string[] | null = null
+ let fenced = false
+ const close = () => {
+ if (open) found.push(item(open.join(' '), pathOf(headings), false))
+ open = null
+ }
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim()
+ if (fenced) {
+ open!.push(line)
+ if (FENCE.test(raw)) { fenced = false; close() }
+ continue
+ }
+ if (!line) { close(); continue }
+ if (FENCE.test(raw)) { close(); open = [line]; fenced = true; continue }
+ const heading = HEADING.exec(raw)
+ if (heading) {
+ close()
+ const level = heading[1]!.length
+ headings.length = level - 1
+ found.push(item(heading[2]!, pathOf(headings), true))
+ headings[level - 1] = heading[2]!.trim()
+ continue
+ }
+ const listed = LIST_ITEM.exec(raw)
+ if (listed) { close(); open = [listed[1]!] } else if (open) (open as string[]).push(line)
+ else open = [line]
+ }
+ close()
+ return found.filter(i => i.text)
+}
+
+function item(words: string, path: string, heading: boolean): Item {
+ const text = words.replace(/\s+/g, ' ').trim()
+ return { key: `${heading ? '#' : '-'}${text}`, text, path, heading }
+}
+
+function cut(text: string): string {
+ if (text.length <= ITEM_CHARS) return text
+ let end = ITEM_CHARS - 1
+ // Never half of a surrogate pair.
+ if (/[\uD800-\uDBFF]/.test(text[end - 1]!)) end -= 1
+ return `${text.slice(0, end)}…`
+}
+
+/** The removals and additions from [a] to [b] in document order, a removal before the addition that replaces it. */
+function itemEdits(a: Item[], b: Item[]): Edit[] {
+ let head = 0
+ while (head < a.length && head < b.length && a[head]!.key === b[head]!.key) head++
+ let tail = 0
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail]!.key === b[b.length - 1 - tail]!.key) tail++
+ const from = a.slice(head, a.length - tail), to = b.slice(head, b.length - tail)
+ return myers(from, to) ?? [...from.map(item => ({ added: false, item })), ...to.map(item => ({ added: true, item }))]
+}
+
+/** Myers' shortest edit script (1986), or null past MAX_EDITS. Each step keeps only its own diagonals -d..d. */
+function myers(a: Item[], b: Item[]): Edit[] | null {
+ const n = a.length, m = b.length
+ if (!n || !m) return [...a.map(item => ({ added: false, item })), ...b.map(item => ({ added: true, item }))]
+ const offset = n + m + 1
+ const v = new Int32Array(2 * offset + 1)
+ const trace: Int32Array[] = []
+ let found = -1
+ for (let d = 0; d <= Math.min(n + m, MAX_EDITS) && found < 0; d++) {
+ for (let k = -d; k <= d; k += 2) {
+ let x = k === -d || (k !== d && v[offset + k - 1]! < v[offset + k + 1]!) ? v[offset + k + 1]! : v[offset + k - 1]! + 1
+ let y = x - k
+ while (x < n && y < m && a[x]!.key === b[y]!.key) { x++; y++ }
+ v[offset + k] = x
+ if (x >= n && y >= m) { found = d; break }
+ }
+ trace.push(v.slice(offset - d, offset + d + 1))
+ }
+ if (found < 0) return null
+ const at = (d: number, k: number) => trace[d]![k + d]!
+ const edits: Edit[] = []
+ let x = n, y = m
+ for (let d = found; d > 0; d--) {
+ const k = x - y
+ const down = k === -d || (k !== d && at(d - 1, k - 1) < at(d - 1, k + 1))
+ const prevK = down ? k + 1 : k - 1
+ const prevX = at(d - 1, prevK), prevY = prevX - prevK
+ while (x > prevX && y > prevY) { x--; y-- }
+ edits.push(down ? { added: true, item: b[prevY]! } : { added: false, item: a[prevX]! })
+ x = prevX
+ y = prevY
+ }
+ return edits.reverse()
+}
diff --git a/desktop/lib/super_tabs/instructions_panel.dart b/desktop/lib/super_tabs/instructions_panel.dart
index 027cccd6a..146ea756f 100644
--- a/desktop/lib/super_tabs/instructions_panel.dart
+++ b/desktop/lib/super_tabs/instructions_panel.dart
@@ -49,26 +49,40 @@ bool _overLimit(String text) {
/// The project's instruction document in the Swarm's details frame: every member reads it, and a member who can
/// write saves a change with a one-line summary on the revision they read (spec: The instruction document).
+/// With [revision], it opens on History with that revision shown: what an
+/// instructions save's chat line links to (#3021).
Future<void> showSuperTabInstructions(
BuildContext context,
SuperTabController c,
- String projectId,
-) => showAppDialog<void>(
+ String projectId, {
+ int? revision,
+}) => showAppDialog<void>(
context: context,
builder: (context) => SuperTabDialogScope(
controller: c,
projectId: projectId,
requireWrite: false,
- child: _InstructionsPanel(controller: c, projectId: projectId),
+ child: _InstructionsPanel(
+ controller: c,
+ projectId: projectId,
+ revision: revision,
+ ),
),
);
class _InstructionsPanel extends StatefulWidget {
- const _InstructionsPanel({required this.controller, required this.projectId});
+ const _InstructionsPanel({
+ required this.controller,
+ required this.projectId,
+ this.revision,
+ });
final SuperTabController controller;
final String projectId;
+ /// The revision to open on, in History; null opens the document.
+ final int? revision;
+
@override
State<_InstructionsPanel> createState() => _InstructionsPanelState();
}
@@ -120,6 +134,11 @@ class _InstructionsPanelState extends State<_InstructionsPanel> {
super.initState();
c.addListener(_onSwarm);
unawaited(_read());
+ if (widget.revision case final revision?) {
+ _view = _View.history;
+ unawaited(_readHistory());
+ unawaited(_pick(revision));
+ }
}
@override
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 0e3351ab3..c59abd464 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -78,6 +78,7 @@ class SuperTabMessageRow extends StatefulWidget {
this.onOpenReply,
this.references = const {},
this.onOpenGroup,
+ this.onOpenInstructions,
this.mentions = const [],
this.mentionAddresses = const {},
this.mentionLabels = const {},
@@ -151,6 +152,10 @@ class SuperTabMessageRow extends StatefulWidget {
final Map<String, String> mentionLabels;
final Map<int, String> references;
final ValueChanged<String>? onOpenGroup;
+
+ /// Opens the revision an instructions save's line names
+ /// ([SuperTabMessage.instructionsSave]), to read the change whole.
+ final ValueChanged<({String projectId, int revision})>? onOpenInstructions;
final String author;
final SuperTabAgent? agent;
@@ -847,6 +852,32 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
),
),
),
+ if ((
+ message.deleted
+ ? null
+ : message.instructionsSave,
+ widget.onOpenInstructions,
+ )
+ case (final saved?, final open?))
+ Padding(
+ padding: const EdgeInsets.only(
+ top: grid.AppDesktop.menuInset,
+ ),
+ child: SuperTabLink(
+ key: ValueKey(
+ 'super-instructions-link-${message.id}',
+ ),
+ label: 'See revision ${saved.revision}',
+ onTap: () => open(saved),
+ child: Text(
+ 'See revision ${saved.revision}',
+ style: DesktopChrome.control(
+ color: DesktopChrome.accent,
+ medium: true,
+ ),
+ ),
+ ),
+ ),
if (message.editedAt != null &&
!message.deleted &&
_editing == null)
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 13008efd9..7c0b8ede4 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -1550,6 +1550,17 @@ class SuperTabMessage {
/// The project chat's line when linked work is Done (ship_row.dart).
bool get shipLine => source['kind'] == 'ship';
+ /// The project and revision an instructions save's chat line names, which
+ /// its "See revision" link opens (#3021); null for any other row.
+ ({String projectId, int revision})? get instructionsSave =>
+ switch ((source['kind'], source['projectId'], source['revision'])) {
+ ('instructions', final String projectId, final num revision) => (
+ projectId: projectId,
+ revision: revision.toInt(),
+ ),
+ _ => null,
+ };
+
/// A line the chat draws as its own row, with no sender's header (view.dart):
/// a message after it has no header to join (Diego, #2547).
bool get drawsOwnRow => shipLine || terminalEvent || route != null;
diff --git a/desktop/lib/super_tabs/task_card.dart b/desktop/lib/super_tabs/task_card.dart
index 02c176da9..c2ff85372 100644
--- a/desktop/lib/super_tabs/task_card.dart
+++ b/desktop/lib/super_tabs/task_card.dart
@@ -1,12 +1,15 @@
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/appearance_prefs_store.dart';
+import '../state/harness_activity.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
import '../widgets/desktop_chrome.dart';
+import '../widgets/harness_activity_mark.dart';
/// One card of a project's Tasks view, on the Board and as a List row alike:
-/// its title (up to [titleLines]), then its caption, and "Needs you" with a red
-/// dot when it waits on the reader. New replies make the title bold with a dot,
-/// said to a screen reader, so colour is never the only signal.
+/// its title (up to [titleLines]), caption and shared activity mark.
///
/// On the Board it is a [tile] (task #2948): an inset tile set into its
/// column's panel, one step less rounded than the panel, with no shadow.
@@ -19,6 +22,7 @@ class SuperTabTaskCard extends StatelessWidget {
required this.caption,
required this.needsYou,
required this.unread,
+ required this.activity,
required this.onOpen,
this.titleLines = 2,
this.tile = false,
@@ -28,6 +32,7 @@ class SuperTabTaskCard extends StatelessWidget {
final String title, caption;
final bool needsYou, unread;
+ final HarnessActivity activity;
final VoidCallback onOpen;
final int titleLines;
final bool tile, selected;
@@ -37,22 +42,20 @@ class SuperTabTaskCard extends StatelessWidget {
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final muted = DesktopChrome.metadata();
- final dot = SizedBox.square(
- dimension: grid.AppDesktop.controlGap,
- child: DecoratedBox(
- decoration: ShapeDecoration(
- color: grid.AppPalette.dangerFill,
- shape: const CircleBorder(),
- ),
- ),
- );
return Semantics(
button: true,
selected: selected ? true : null,
label: [
title,
caption,
- if (needsYou) 'Needs you',
+ if (!needsYou)
+ switch (activity) {
+ HarnessActivity.starting => 'Queued',
+ HarnessActivity.needsInput => 'Waiting on a person',
+ HarnessActivity.offline => 'Blocked or agent lost',
+ HarnessActivity.done => 'Shipped',
+ _ => activity.label,
+ },
if (unread) 'New replies',
].join(', '),
excludeSemantics: true,
@@ -71,27 +74,17 @@ class SuperTabTaskCard extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (needsYou)
- Row(
- children: [
- dot,
- const SizedBox(width: grid.AppDesktop.menuInset),
- Text(
- 'Needs you',
- style: DesktopChrome.metadata(
- color: DesktopChrome.foreground,
- ),
- ),
- ],
- ),
Text(
title,
maxLines: titleLines,
overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(
- color: DesktopChrome.foreground,
- medium: unread,
- ),
+ style:
+ DesktopChrome.control(color: DesktopChrome.foreground)
+ .copyWith(
+ fontWeight: unread
+ ? FontWeight.w600
+ : FontWeight.w400,
+ ),
),
if (caption.isNotEmpty)
Text(
@@ -103,23 +96,25 @@ class SuperTabTaskCard extends StatelessWidget {
],
),
),
- if (unread) ...[
- const SizedBox(width: grid.AppDesktop.menuInset),
- Padding(
- padding: const EdgeInsets.only(
- top: grid.AppDesktop.menuInset,
- ),
- child: SizedBox.square(
- dimension: grid.AppDesktop.controlGap,
- child: DecoratedBox(
- decoration: ShapeDecoration(
- color: grid.AppPalette.accent,
- shape: const CircleBorder(),
- ),
+ const SizedBox(width: grid.AppDesktop.menuInset),
+ ListenableBuilder(
+ listenable: Listenable.merge([
+ terminalThemeStore,
+ appearancePrefsStore,
+ ]),
+ builder: (context, _) => ActivityMark(
+ activity: activity,
+ color: activityColor(
+ activity,
+ terminalThemeFor(
+ grid.AppTheme.surfacePalette,
+ terminalThemeStore.value,
),
+ color: appearancePrefsStore.value.prompt.color,
),
+ tooltip: false,
),
- ],
+ ),
?trailing,
],
),
diff --git a/desktop/lib/super_tabs/tasks_view.dart b/desktop/lib/super_tabs/tasks_view.dart
index 6a0156e6b..64858c7d7 100644
--- a/desktop/lib/super_tabs/tasks_view.dart
+++ b/desktop/lib/super_tabs/tasks_view.dart
@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';
import '../core/local_key_value_store.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
+import '../state/harness_activity.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/laid_out_list.dart';
import 'attention.dart';
@@ -326,14 +327,56 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
}
final task = entry.task!;
final agentId = task.assignment?['agentId'];
+ final agent = agentId is String && snapshot != null
+ ? snapshot.agentName(agentId, fallback: '')
+ : '';
+ final waitingOnReader =
+ entry.needsYou &&
+ !superTabTaskShipped(task) &&
+ (task.assignment?['status'] == 'needs_human' ||
+ task.liveness?['why'] == 'person');
return [
?_person(task.requesterId),
if (agentId is String && snapshot != null)
- snapshot.agentName(agentId, fallback: 'Agent unavailable'),
- ?entry.state,
+ if (agent.isNotEmpty)
+ agent
+ else if (!superTabTaskShipped(task))
+ 'Agent unavailable',
+ if (entry.needsYou) 'Needs you',
+ if (!waitingOnReader) ?entry.state,
].join(' · ');
}
+ HarnessActivity _activity(SuperTabTaskEntry entry) {
+ if (entry.needsYou) return HarnessActivity.needsInput;
+ final task = entry.task;
+ if (task == null) return HarnessActivity.starting;
+ if (superTabTaskShipped(task)) return HarnessActivity.done;
+ final status = task.assignment?['status'];
+ final state = task.liveness?['state'];
+ final why = task.liveness?['why'];
+ if (status == 'failed') return HarnessActivity.failed;
+ if (status == 'blocked' ||
+ status == 'lost' ||
+ state == 'orphaned' ||
+ state == 'quiet' ||
+ state == 'waiting' && why == 'blocked') {
+ return HarnessActivity.offline;
+ }
+ if (status == 'needs_human' ||
+ status == 'review' ||
+ status == 'done' ||
+ state == 'waiting' &&
+ (why == 'person' || why == 'review' || why == 'revision')) {
+ return HarnessActivity.needsInput;
+ }
+ if (task.assignment?['agentId'] is! String ||
+ state == 'waiting' && why == 'queued') {
+ return HarnessActivity.starting;
+ }
+ return HarnessActivity.working;
+ }
+
Widget _card(SuperTabTaskEntry entry, DateTime now, {required bool list}) {
final task = entry.task;
final id = task?.id ?? entry.proposal!.messageId;
@@ -343,6 +386,7 @@ class _SuperTabTasksViewState extends State<SuperTabTasksView> {
caption: _caption(entry, now),
needsYou: entry.needsYou,
unread: task != null && widget.controller.unreadShown(task),
+ activity: _activity(entry),
titleLines: list ? 1 : 3,
tile: !list,
selected: id == widget.selectedId,
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index e094d5568..b7d2dcdbf 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -4009,6 +4009,14 @@ class _SuperTabViewState extends State<SuperTabView>
username: name,
},
references: _references,
+ onOpenInstructions: (saved) => unawaited(
+ showSuperTabInstructions(
+ context,
+ c,
+ saved.projectId,
+ revision: saved.revision,
+ ),
+ ),
onOpenGroup: (id) {
setState(() => _showPullRequests = _showTasks = false);
c.select(id);
diff --git a/desktop/test/super_tab_instructions_shots_test.dart b/desktop/test/super_tab_instructions_shots_test.dart
new file mode 100644
index 000000000..9d3fcfa8b
--- /dev/null
+++ b/desktop/test/super_tab_instructions_shots_test.dart
@@ -0,0 +1,132 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/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_INSTRUCTIONS_SHOTS'];
+
+/// An instructions save's line in the project chat and the revision its link
+/// opens (Ken, 11-05, #3021), in both appearances, from made-up data only.
+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();
+ server.state['projects'] = [
+ {
+ ...projectFixture('lead', 'openharness', 'lead'),
+ 'coordinatorName': 'Product Manager',
+ 'instructionsRevision': 68,
+ },
+ ];
+ server.instructions['lead'] = {
+ 'projectId': 'lead',
+ 'revision': 68,
+ 'hash': 'hash-lead-68',
+ 'text': '## Routing\n\n### Models\n\n- Reviewers run on Opus.\n',
+ 'template': false,
+ 'coordinatorName': 'Product Manager',
+ 'notesRevision': 0,
+ 'notes': <dynamic>[],
+ };
+ final now = DateTime.now().toUtc();
+ server.instructionRevisions['lead'] = [
+ {
+ 'revision': 68,
+ 'hash': 'hash-lead-68',
+ 'summary': 'Routing: no Haiku.',
+ 'writtenBy': {'kind': 'agent', 'id': 'pm'},
+ 'askedBy': 'owner',
+ 'at': now.subtract(const Duration(minutes: 3)).toIso8601String(),
+ 'text':
+ '## Routing\n\n### Models\n\n- No agent runs below high effort, '
+ 'and none on Claude Haiku.\n- Reviewers run on Opus.\n',
+ },
+ ];
+ server.append(
+ 'River changed the instructions for owner: Routing: no Haiku.\n\n'
+ 'In Routing › Models:\n'
+ 'Removed: No agent runs below high effort.\n'
+ 'Added: No agent runs below high effort, and none on Claude Haiku.\n'
+ 'Added: Reviewers run on Opus.\n\n'
+ 'In Workflow:\n'
+ 'Added: The Engineer adds the review step when the pull request is '
+ 'ready.\n\n'
+ 'and 9 more changes.',
+ );
+ server.messages.last
+ ..['author'] = const {
+ 'kind': 'agent',
+ 'id': 'pm',
+ 'name': 'Lead',
+ 'displayName': 'River',
+ }
+ ..['createdAt'] = now
+ .subtract(const Duration(minutes: 3))
+ .toIso8601String()
+ ..['source'] = const {
+ 'kind': 'instructions',
+ 'projectId': 'lead',
+ 'revision': 68,
+ };
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.binding.setSurfaceSize(const Size(1280, 860));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('See revision 68'), findsOneWidget);
+
+ Future<void> shot(String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/instructions-$name-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ await shot('chat');
+ await tester.tap(find.text('See revision 68'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-revision-text')), findsOneWidget);
+ await shot('revision');
+ });
+ }
+}
diff --git a/desktop/test/super_tab_instructions_test.dart b/desktop/test/super_tab_instructions_test.dart
index b61489ee4..b60f0a2ff 100644
--- a/desktop/test/super_tab_instructions_test.dart
+++ b/desktop/test/super_tab_instructions_test.dart
@@ -27,8 +27,16 @@ void main() {
WidgetTester tester, {
String account = 'owner',
bool instructions = true,
+ List<Map<String, dynamic>> messages = const [],
}) async {
final server = ConversationServer();
+ server.messages.addAll(messages);
+ if (messages.isNotEmpty) {
+ (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'lead')['lastMessageSequence'] =
+ messages.length;
+ }
server.state['projects'] = [
{
...projectFixture('lead', 'Pilot', 'lead'),
@@ -561,6 +569,68 @@ void main() {
expect(editorText(tester), 'Text of revision 7');
});
+ // Ken, 11-05 (#3021): the save's chat line shows the lines it changed, and opens the revision it saved to read it whole.
+ testWidgets(
+ 'an instructions line in the chat opens the revision it saved',
+ (tester) async {
+ final (server, _) = await mount(
+ tester,
+ account: 'peer',
+ messages: [
+ {
+ 'id': 'saved',
+ 'conversationId': 'lead',
+ 'sequence': 1,
+ 'text':
+ 'owner changed the instructions: Reviews run on Opus.\n\n'
+ 'In Routing › Models:\nRemoved: Haiku reviews.\n'
+ 'Added: Opus reviews.\n\nand 3 more changes.',
+ 'createdAt': ago(const Duration(minutes: 5)),
+ 'author': {'kind': 'person', 'id': 'owner', 'name': 'owner'},
+ 'source': {
+ 'kind': 'instructions',
+ 'projectId': 'lead',
+ 'revision': 8,
+ },
+ },
+ {
+ 'id': 'plain',
+ 'conversationId': 'lead',
+ 'sequence': 2,
+ 'text': 'Thanks, I read it.',
+ 'createdAt': ago(const Duration(minutes: 4)),
+ 'author': {'kind': 'person', 'id': 'peer', 'name': 'peer'},
+ },
+ ],
+ );
+ seed(server);
+ expect(find.textContaining('Haiku reviews.'), findsOneWidget);
+ expect(find.textContaining('and 3 more changes.'), findsOneWidget);
+ // One link, on the save's line only.
+ final link = find.byKey(
+ const ValueKey('super-instructions-link-saved'),
+ );
+ expect(link, findsOneWidget);
+ expect(find.text('See revision 8'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-instructions-link-plain')),
+ findsNothing,
+ );
+ await tester.tap(link);
+ await tester.pumpAndSettle();
+ expect(find.text('Instructions › History'), findsOneWidget);
+ expect(
+ server.instructionReads.where((r) => r.endsWith('/revisions/8')),
+ hasLength(1),
+ );
+ final text = tester.widget<TextField>(
+ find.byKey(const ValueKey('super-revision-text')),
+ );
+ expect(text.readOnly, isTrue);
+ expect(text.controller!.text, 'Text of revision 8');
+ },
+ );
+
testWidgets('a viewer has no Restore', (tester) async {
final (server, _) = await mount(tester, account: 'viewer');
seed(server);
diff --git a/desktop/test/super_tab_task_activity_test.dart b/desktop/test/super_tab_task_activity_test.dart
new file mode 100644
index 000000000..ef394be8a
--- /dev/null
+++ b/desktop/test/super_tab_task_activity_test.dart
@@ -0,0 +1,395 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/state/harness_activity.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/task_card.dart';
+import 'package:harness/super_tabs/tasks_view.dart';
+import 'package:harness/terminal/terminal_theme.dart';
+import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/widgets/harness_activity_mark.dart';
+
+import 'super_tab_tasks_view_test.dart' show tasksServer, taskFixture;
+import 'support/memory_key_value_store.dart';
+import 'support/super_tab_fixture.dart';
+
+final _now = DateTime(2026, 11, 4, 9);
+
+Finder _card(String id) => find.byKey(ValueKey('super-task-card-$id'));
+Finder _mark(String id) =>
+ find.descendant(of: _card(id), matching: find.byType(ActivityMark));
+
+Future<SuperTabController> _show(
+ WidgetTester tester,
+ ConversationServer server, {
+ bool list = false,
+ bool reduceMotion = true,
+ Set<String> asking = const {},
+}) async {
+ await tester.binding.setSurfaceSize(const Size(1600, 1200));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final controller = server.controller();
+ addTearDown(controller.dispose);
+ await controller.refresh();
+ final storage = MemoryKeyValueStore();
+ if (list) {
+ await storage.write(
+ SuperTabTasksView.storageKey(controller.accountId),
+ '{"layout":"list"}',
+ );
+ }
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabTasksView(
+ controller: controller,
+ project: controller.snapshot!.projects.single,
+ storage: storage,
+ needsHuman: (task) => asking.contains(task.id) ? 1 : 0,
+ onOpenTask: (_) {},
+ onOpenProposal: (_) {},
+ now: () => _now,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 50));
+ if (list) {
+ await tester.tap(find.byKey(const ValueKey('super-tasks-heading-shipped')));
+ await tester.pump();
+ }
+ return controller;
+}
+
+ConversationServer _server(Map<String, dynamic> task) {
+ final server = tasksServer(empty: true);
+ (server.state['conversations'] as List).add(task);
+ return server;
+}
+
+void main() {
+ for (final list in [false, true]) {
+ final layout = list ? 'List' : 'Board';
+ for (final (status, liveness, merged, activity)
+ in <(String?, Map<String, dynamic>?, bool, HarnessActivity)>[
+ (null, null, false, HarnessActivity.starting),
+ ('working', null, false, HarnessActivity.working),
+ (
+ 'needs_human',
+ {'state': 'waiting', 'why': 'person', 'personId': 'tony'},
+ false,
+ HarnessActivity.needsInput,
+ ),
+ ('review', null, false, HarnessActivity.needsInput),
+ ('done', null, false, HarnessActivity.needsInput),
+ ('blocked', null, false, HarnessActivity.offline),
+ ('lost', null, false, HarnessActivity.offline),
+ (
+ 'working',
+ {'state': 'orphaned', 'why': 'agent'},
+ false,
+ HarnessActivity.offline,
+ ),
+ (
+ 'working',
+ {'state': 'waiting', 'why': 'queued'},
+ false,
+ HarnessActivity.starting,
+ ),
+ ('failed', null, false, HarnessActivity.failed),
+ ('done', null, true, HarnessActivity.done),
+ ]) {
+ testWidgets('$layout $status $liveness merged=$merged uses $activity', (
+ tester,
+ ) async {
+ await _show(
+ tester,
+ _server(
+ taskFixture(
+ 'task',
+ 'A task',
+ 30,
+ status: status,
+ liveness: liveness,
+ merged: merged,
+ pullRequest: merged || status == 'done' ? 3007 : null,
+ shippedAt: merged ? _now : null,
+ ),
+ ),
+ list: list,
+ );
+ expect(_mark('task'), findsOneWidget);
+ expect(tester.widget<ActivityMark>(_mark('task')).activity, activity);
+ expect(
+ tester.widget<ActivityMark>(_mark('task')).color,
+ activityColor(
+ activity,
+ terminalThemeFor(
+ grid.AppTheme.surfacePalette,
+ terminalThemeStore.value,
+ ),
+ color: appearancePrefsStore.value.prompt.color,
+ ),
+ );
+ expect(
+ find.descendant(
+ of: _mark('task'),
+ matching: find.text(activity.mark),
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Needs you'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ testWidgets('$layout reader attention is ? with Needs you in caption', (
+ tester,
+ ) async {
+ await _show(
+ tester,
+ _server(
+ taskFixture(
+ 'task',
+ 'Shipped asks for a check',
+ 31,
+ status: 'done',
+ merged: true,
+ pullRequest: 3007,
+ shippedAt: _now,
+ ),
+ ),
+ list: list,
+ asking: {'task'},
+ );
+ expect(
+ tester.widget<ActivityMark>(_mark('task')).activity,
+ HarnessActivity.needsInput,
+ );
+ final card = tester.widget<SuperTabTaskCard>(_card('task'));
+ expect(card.caption, contains('Needs you'));
+ expect(
+ find.descendant(of: _card('task'), matching: find.text('Needs you')),
+ findsNothing,
+ );
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('$layout mark follows terminal theme and monochrome live', (
+ tester,
+ ) async {
+ final oldTheme = terminalThemeStore.value;
+ final oldAppearance = appearancePrefsStore.value;
+ addTearDown(() {
+ terminalThemeStore.value = oldTheme;
+ appearancePrefsStore.value = oldAppearance;
+ });
+ terminalThemeStore.value = TerminalThemeChoice.light;
+ appearancePrefsStore.value = oldAppearance.copyWith(
+ prompt: oldAppearance.prompt.copyWith(color: true),
+ );
+ await _show(
+ tester,
+ _server(taskFixture('task', 'Failed', 37, status: 'failed')),
+ list: list,
+ );
+ Color color() => tester.widget<ActivityMark>(_mark('task')).color;
+ expect(
+ color(),
+ terminalThemeFor(
+ grid.AppTheme.surfacePalette,
+ TerminalThemeChoice.light,
+ ).red,
+ );
+ terminalThemeStore.value = TerminalThemeChoice.dark;
+ await tester.pump();
+ expect(
+ color(),
+ terminalThemeFor(
+ grid.AppTheme.surfacePalette,
+ TerminalThemeChoice.dark,
+ ).red,
+ );
+ appearancePrefsStore.value = oldAppearance.copyWith(
+ prompt: oldAppearance.prompt.copyWith(color: false),
+ );
+ await tester.pump();
+ expect(
+ color(),
+ terminalThemeFor(
+ grid.AppTheme.surfacePalette,
+ TerminalThemeChoice.dark,
+ ).foreground,
+ );
+ terminalThemeStore.value = TerminalThemeChoice.light;
+ await tester.pump();
+ expect(
+ color(),
+ terminalThemeFor(
+ grid.AppTheme.surfacePalette,
+ TerminalThemeChoice.light,
+ ).foreground,
+ );
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('$layout reader decision caption does not repeat who waits', (
+ tester,
+ ) async {
+ await _show(
+ tester,
+ _server(
+ taskFixture(
+ 'task',
+ 'A decision',
+ 36,
+ requester: 'ken',
+ status: 'needs_human',
+ liveness: {
+ 'state': 'waiting',
+ 'why': 'person',
+ 'personId': 'owner',
+ },
+ ),
+ ),
+ list: list,
+ );
+ expect(
+ tester.widget<SuperTabTaskCard>(_card('task')).caption,
+ 'ken15 · Finch2 · Needs you',
+ );
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('$layout shipped missing agent is omitted, known agent stays', (
+ tester,
+ ) async {
+ final server = _server(
+ taskFixture(
+ 'missing',
+ 'Missing agent',
+ 32,
+ status: 'done',
+ agent: 'gone',
+ merged: true,
+ pullRequest: 3007,
+ shippedAt: _now,
+ ),
+ );
+ (server.state['conversations'] as List).add(
+ taskFixture(
+ 'known',
+ 'Known agent',
+ 33,
+ status: 'done',
+ merged: true,
+ pullRequest: 3008,
+ shippedAt: _now,
+ ),
+ );
+ await _show(tester, server, list: list);
+ expect(find.textContaining('Agent unavailable'), findsNothing);
+ expect(
+ tester.widget<SuperTabTaskCard>(_card('known')).caption,
+ contains('Finch2'),
+ );
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ testWidgets('unread is bold without dots and mark stays top right', (
+ tester,
+ ) async {
+ final server = _server(
+ taskFixture(
+ 'task',
+ 'A long unread title that wraps over several lines of the tile',
+ 34,
+ ),
+ );
+ final task = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .last;
+ task['lastMessageSequence'] = 10;
+ await _show(tester, server);
+ final card = tester.widget<SuperTabTaskCard>(_card('task'));
+ expect(card.unread, isTrue);
+ final title = find.descendant(
+ of: _card('task'),
+ matching: find.text(card.title),
+ );
+ expect(
+ tester.widget<Text>(title).style!.fontWeight!.value,
+ greaterThanOrEqualTo(FontWeight.w600.value),
+ );
+ final circles = find.descendant(
+ of: _card('task'),
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is DecoratedBox &&
+ widget.decoration is ShapeDecoration &&
+ (widget.decoration as ShapeDecoration).shape is CircleBorder,
+ ),
+ );
+ expect(circles, findsNothing);
+ expect(tester.getTopLeft(_mark('task')).dy, tester.getTopLeft(title).dy);
+ expect(
+ tester.getTopLeft(_mark('task')).dx,
+ greaterThan(tester.getTopLeft(title).dx),
+ );
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ for (final reduceMotion in [false, true]) {
+ testWidgets(
+ 'working mark ${reduceMotion ? 'freezes' : 'spins'} with Reduce Motion=$reduceMotion',
+ (tester) async {
+ await _show(
+ tester,
+ _server(taskFixture('task', 'Working', 35, status: 'working')),
+ reduceMotion: reduceMotion,
+ );
+ final text = find.descendant(
+ of: _mark('task'),
+ matching: find.byType(Text),
+ );
+ expect(text, findsOneWidget);
+ final mark = tester.widget<ActivityMark>(_mark('task'));
+ var now = DateTime(2026, 11, 5);
+ final clock = ActivityClock(now: () => now);
+ addTearDown(clock.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: MediaQuery(
+ data: MediaQueryData(disableAnimations: reduceMotion),
+ child: ActivityMark(
+ activity: mark.activity,
+ color: mark.color,
+ clock: clock,
+ ),
+ ),
+ ),
+ );
+ final animatedText = find.descendant(
+ of: find.byType(ActivityMark),
+ matching: find.byType(Text),
+ );
+ final before = tester.widget<Text>(animatedText).data;
+ now = now.add(activityFrameInterval);
+ await tester.pump(activityFrameInterval);
+ final after = tester.widget<Text>(animatedText).data;
+ expect(after, reduceMotion ? before : isNot(before));
+ expect(clock.running, !reduceMotion);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+}
diff --git a/desktop/test/super_tab_tasks_header_test.dart b/desktop/test/super_tab_tasks_header_test.dart
index c71484799..b23f51bbe 100644
--- a/desktop/test/super_tab_tasks_header_test.dart
+++ b/desktop/test/super_tab_tasks_header_test.dart
@@ -23,6 +23,10 @@ Future<SuperTabController> _showView(
await tester.pumpWidget(
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: child!,
+ ),
home: Scaffold(
body: SuperTabView(
controller: c,
diff --git a/desktop/test/super_tab_tasks_shots_test.dart b/desktop/test/super_tab_tasks_shots_test.dart
index 9d8579983..7fdade3a0 100644
--- a/desktop/test/super_tab_tasks_shots_test.dart
+++ b/desktop/test/super_tab_tasks_shots_test.dart
@@ -1,6 +1,7 @@
import 'dart:io';
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/super_tabs/view.dart';
@@ -17,14 +18,25 @@ final shots = Platform.environment['SUPER_TAB_TASKS_SHOTS'];
/// is empty and says so, and the task just opened from the board shows
/// selected on coming back.
void main() {
- setUpAll(() => loadCaptureFonts(shots));
+ setUpAll(() async {
+ await loadCaptureFonts(shots);
+ if (shots != null && Platform.isMacOS) {
+ for (final (family, path) in [
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(path).readAsBytes());
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ }
+ });
for (final brightness in Brightness.values) {
for (final layout in ['board', 'list']) {
testWidgets('screenshots for review ($layout, ${brightness.name})', (
tester,
) async {
- await tester.binding.setSurfaceSize(const Size(1440, 820));
+ await tester.binding.setSurfaceSize(const Size(1900, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
final before = grid.AppTheme.brightness.value;
grid.AppTheme.brightness.value = brightness;
@@ -55,7 +67,38 @@ void main() {
17,
requester: 'tony',
),
+ taskFixture(
+ 'lost',
+ 'Phone tests: a picture test',
+ 18,
+ status: 'lost',
+ agent: 'gone',
+ ),
+ taskFixture(
+ 'failed',
+ 'A failed build reports its error',
+ 19,
+ status: 'failed',
+ ),
+ taskFixture(
+ 'shipped-gone',
+ 'Tasks board looks finished',
+ 20,
+ requester: 'scholes',
+ status: 'done',
+ agent: 'gone',
+ merged: true,
+ pullRequest: 3007,
+ shippedAt: DateTime(2026, 11, 5),
+ ),
]);
+ final conversations = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>();
+ conversations.firstWhere((task) => task['id'] == 'sender')['liveness'] =
+ {'state': 'waiting', 'why': 'person', 'personId': 'owner'};
+ conversations.firstWhere(
+ (task) => task['id'] == 'tag',
+ )['lastMessageSequence'] = 10;
// A promise the PM keeps, as the mockup's preview route.
(server.state['conversations'] as List)
.cast<Map<String, dynamic>>()
@@ -69,6 +112,10 @@ void main() {
MaterialApp(
debugShowCheckedModeBanner: false,
theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: child!,
+ ),
home: Scaffold(
body: SuperTabView(
controller: c,
@@ -94,7 +141,13 @@ void main() {
);
await tester.pumpAndSettle();
}
- expect(find.text('Needs you'), findsOneWidget);
+ if (layout == 'list') {
+ await tester.tap(
+ find.byKey(const ValueKey('super-tasks-heading-shipped')),
+ );
+ await tester.pumpAndSettle();
+ }
+ expect(find.textContaining('Needs you'), findsNWidgets(2));
expect(find.byKey(const ValueKey('super-tasks-badge')), findsOneWidget);
expect(tester.takeException(), isNull);
await captureWindow(tester, shots, 'tasks-$layout-${brightness.name}');
diff --git a/desktop/test/super_tab_tasks_view_test.dart b/desktop/test/super_tab_tasks_view_test.dart
index cb9f60510..7ce087edf 100644
--- a/desktop/test/super_tab_tasks_view_test.dart
+++ b/desktop/test/super_tab_tasks_view_test.dart
@@ -164,6 +164,10 @@ Future<SuperTabController> _show(
await tester.pumpWidget(
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: child!,
+ ),
home: Scaffold(
body: SuperTabTasksView(
controller: c,
@@ -428,7 +432,7 @@ void main() {
expect(inCard('shipped-means', 'scholes'), findsOneWidget);
expect(inCard('sender', 'scholes · Finch2 · PR #2870'), findsOneWidget);
expect(
- inCard('test-copy', 'ken15 · Finch2 · dee to decide'),
+ inCard('test-copy', 'ken15 · Finch2 · Needs you'),
findsOneWidget,
);
// No task numbers, machines or models.
@@ -454,11 +458,17 @@ void main() {
final c = await _show(tester, server);
expect(_cardsIn(tester, 'waiting'), ['test-copy', 'later']);
expect(
- find.descendant(of: _card('test-copy'), matching: find.text('Needs you')),
+ find.descendant(
+ of: _card('test-copy'),
+ matching: find.textContaining('Needs you'),
+ ),
findsOneWidget,
);
expect(
- find.descendant(of: _card('later'), matching: find.text('Needs you')),
+ find.descendant(
+ of: _card('later'),
+ matching: find.textContaining('Needs you'),
+ ),
findsNothing,
);
await _close(tester, c);
diff --git a/docs/plans/2026-11-05-instructions-save-diff-plan.md b/docs/plans/2026-11-05-instructions-save-diff-plan.md
new file mode 100644
index 000000000..95437632f
--- /dev/null
+++ b/docs/plans/2026-11-05-instructions-save-diff-plan.md
@@ -0,0 +1,95 @@
+# Instructions save shows the real change: implementation plan
+
+**Goal:** The project-chat line an instructions save posts shows the items the save really added and removed, so a PM's
+"I wrote it into the instructions" can be checked against the saved text.
+
+**Architecture:** The save already holds both texts: the store loads the current revision into the command context
+(`context.instructions`, store.ts) to refuse a stale save, and the command carries the new one. `saveInstructions`
+(commands.ts) compares the two once, at save, by item: a bullet, a numbered step, a paragraph or a fenced block with its
+wrapped lines joined and its list marker dropped, and each heading (Ken's review: instructions are hard-wrapped, so a
+line diff showed a rewrapped bullet as fragments). The notice's text writes each changed item in words, "Added:" or
+"Removed:", under its section path ("In Routing › Models:"): at most 12 items, then "and N more changes." No diff block
+and no colouring (River's call on Ken's review), so it reads the same on Desktop, web, phone, CLI agents and older
+clients. The notice's `source` keeps `{ kind: 'instructions', projectId,
+revision }`; Desktop/web and phone add a "See revision N" link under it, which opens that revision in the existing
+Instructions panel (Desktop) or a read-only revision page (phone).
+
+**Tech Stack:** TypeScript and Vitest (backend), Flutter and flutter_test (desktop, mobile).
+
+**Spec:** Swarm task #3021, "An instructions save shows the real lines added and removed", requested by Ken.
+
+**Execution:** Task by task, each failing test committed before its code, by the project's Engineer workflow.
+
+## Global Constraints
+
+- No new query anywhere: the diff uses the text the save path already reads, computed once per save.
+- The PM's summary stays the notice's first line; it never replaces the diff.
+- The change is bounded: at most 12 items shown, each cut to 400 characters; the item comparison is bounded in work,
+ and past that bound it reports the changed region as removed and added (still real items, never invented).
+- Every line of the change starts with "In", "Added", "Removed" or "and", so a saved item's Markdown cannot open a
+ heading, list, quote, code block or table in the chat. The row carries no mentions, so an `@name` in it tags nobody.
+- When the earlier text cannot be read, the notice says so instead of showing no change.
+- Swarm code stays out of cli/src/core. Desktop tests use a memory store and a fake sign-in.
+- PR body starts with "Requested by 0xKen15 through Harness."
+
+## Design
+
+- Growth: N/A because nothing new is stored beyond about 2 KB more text in a notice row the save already writes; rows go
+ with their conversation as today.
+- Concurrency: unchanged; the save's existing Swarm transaction and revision check.
+- Read cost: no new read; the previous text is already in `context.instructions` for both `instructions.save` and
+ `rule.set`.
+- Scale: a 64 KB document is at most about 2,000 items; the comparison trims the common head and tail and runs Myers'
+ diff up to 1,000 edits (about 2 MB of trace), so a save costs milliseconds. Warns first: save latency in the command
+ timing log.
+- Compatibility: old clients render the new text as plain lines and show no link; new clients reading old notices show
+ the link only (old text has no change). No command or field changes.
+- Migration + rollback: none; reverting restores summary-only notices, and posted notices keep their text.
+- Audience: the notice goes to the project chat, whose readers are the project's readers, who already read the whole
+ document; the revision link uses the existing revision read and its server checks.
+- Identity: the notice is written in the saver's name as today; never the machine owner's login.
+- Failure: an unreadable earlier revision says "The earlier revision could not be read, so the change is not shown."; a
+ revision no longer kept says so on the revision page.
+- Platforms: backend for everyone; Desktop on macOS, Windows, Linux and web share the row; phone on iOS and Android.
+
+## Review Focus
+
+- The diff is computed from the stored previous revision and the saved text, never from the summary.
+- Long changes show exactly 12 items and the right "and N more changes" count (singular for 1).
+- A rewrap alone is no change; renumbered steps are no change; each change names its own section.
+- A saved item holding a heading, fence, quote or table cannot open a block in the chat.
+- `rule.set`, a first save from the template (revision 0) and an unchanged save keep working.
+
+## Task 1: The line diff and the notice text (backend)
+
+**Files:** `backend/src/superTabs/instructionsDiff.ts` (new), `backend/src/superTabs/instructionsDiff.test.ts` (new),
+`backend/src/superTabs/commands.ts` (`saveInstructions`, `instructions.save`, `rule.set`),
+`backend/src/superTabs/instructions.test.ts`, `backend/src/superTabs/commands.test.ts`.
+
+**Interfaces:** `instructionsChange(before: string | null, after: string): string` returns the words that follow the
+notice's summary line.
+
+- [x] Tests: a save posts the added and removed items of the real revision; a long change shows 12 items and "and N
+ more changes"; rewraps and spacing alone; joined paragraphs; renumbered steps; section paths; no block can open;
+ unreadable earlier text says so; rule.set shows its added item.
+- [x] Run them and record the failures.
+- [x] Implement `instructionsChange` and pass the previous text into `saveInstructions`.
+
+## Task 2: "See revision N" on Desktop and web
+
+**Files:** `desktop/lib/super_tabs/model.dart`, `desktop/lib/super_tabs/message_row.dart`,
+`desktop/lib/super_tabs/instructions_panel.dart`, `desktop/lib/super_tabs/view.dart`, and their tests.
+
+**Interfaces:** `SuperTabMessage.instructionsRevision` (int?, from a source of kind `instructions`);
+`showSuperTabInstructions(context, c, projectId, {int? revision})` opens History with that revision picked.
+
+- [x] Widget test: an instructions notice shows "See revision N", and tapping it opens the panel on that revision.
+- [ ] Implement; light and dark screenshots.
+
+## Task 3: "See revision N" on the phone
+
+**Files:** `mobile/lib/swarm/model.dart`, `mobile/lib/swarm/swarm_message_row.dart`,
+`mobile/lib/swarm/swarm_instructions_page.dart`, and their tests.
+
+- [ ] Widget test: the notice shows the link; the page opened with a revision reads that revision, read-only.
+- [ ] Implement; light and dark screenshots.
diff --git a/docs/plans/2026-11-05-task-activity-marks-plan.md b/docs/plans/2026-11-05-task-activity-marks-plan.md
new file mode 100644
index 000000000..a3734ee30
--- /dev/null
+++ b/docs/plans/2026-11-05-task-activity-marks-plan.md
@@ -0,0 +1,77 @@
+# Tasks Activity Marks Implementation Plan
+
+> Implement task-by-task with test-driven development, following the project's Engineer workflow.
+
+**Goal:** Replace Tasks board/list notification dots with the existing activity vocabulary and keep unread titles bold.
+
+**Architecture:** Board and List share `SuperTabTaskCard` in `task_card.dart`, populated by `tasks_view.dart` (not the separate Backlog). Derive presentation activity from the existing task entry without changing grouping, persistence, or wire contracts. Reuse `ActivityMark` so its shared clock and Reduce Motion behavior remain authoritative.
+
+**Tech Stack:** Flutter/Dart, existing widget test fixtures, shared activity widgets.
+
+**Spec:** Swarm task #3007 and River's approved ASCII mockup in the project chat, November 5, 2026; `desktop/design/desktop-design-system.md` and `desktop/design/icon-design-system.md`.
+
+## Global Constraints
+
+- One top-right status cell: queued ◌, working Braille spinner, person ?, blocked/lost ⊘, shipped ✓, failed ✗.
+- Unread is a bold title with no dot. “Needs you” is caption content only for the reader.
+- Shipped cards omit unavailable agents; preserve actual known agent names.
+- Preserve Board/List layout, selection, navigation, grouping and column counts.
+- No sidebar or theme edits, new dependencies, data storage, or backend changes.
+- Fake sign-in/memory stores only. Stop only owned processes; temporary output uses mktemp directories.
+
+## Review Focus
+
+- Shipped tasks with pending reader attention need ? rather than losing that attention under ✓.
+- Blocked/lost and failed assignments must not display a working spinner.
+- Another person's decision needs ? but never “Needs you”.
+- Queued and unassigned proposals must not imply active execution.
+- Long/wrapped unread titles keep the mark aligned at the top right; Reduce Motion freezes working marks.
+
+## Task 1: Activity marks and captions
+
+**Files:** Modify `desktop/lib/super_tabs/task_card.dart`, `desktop/lib/super_tabs/tasks_view.dart`; add regression coverage in `desktop/test/super_tab_task_activity_test.dart`; adjust affected existing Tasks fixtures only as needed for live animation.
+
+**Interfaces:** Consume existing `SuperTabTaskEntry`, `HarnessActivity`, `ActivityMark`; add an activity argument to the shared card. No controller or server API changes.
+
+- [x] Commit failing widget tests for the six marks, unread/no dots, caption attention, shipped unavailable agents, stable status placement and Reduce Motion.
+- [x] Run those tests and record expected failures before production edits.
+- [x] Implement minimal shared-card presentation and activity mapping.
+- [x] Run affected Tasks view/group/column/header and activity tests, analyzing only changed Dart files; record red/green evidence.
+
+## Task 2: Visual verification and handoff
+
+**Files:** Existing `desktop/test/super_tab_tasks_shots_test.dart` screenshot fixture; no new production interfaces.
+
+- [x] Run `python3 scripts/check-ui-style.py --only desktop/lib/super_tabs`, `desktop/test/laid_out_list_test.dart`, and icon audit.
+- [x] Capture and inspect light/dark Board and List screenshots; attach them to task #3007 and notify Dee with a person line.
+- [x] Record validation timings, commands, toolchain and screenshots in the PR; mark Ready after required local checks.
+- [ ] Add independent Review and Test steps, route their agents, and request both in parallel. Complete the task only after both verdicts pass; merge/publication belong to the PM.
+
+## Validation Scope
+
+Deterministic checks cover changed Dart files and their Tasks widget callers with the repository lockfile and installed pinned Flutter/Dart SDK. Targeted tests and Desktop guards run locally on macOS; PR CI supplies the Desktop VM suite. No second local full suite. Capture test-fixture rendering timing before/after on the same fixture; native user testing is an independent Tester step. No backend, CLI, mobile or release checks are affected. Track implementation, validation, review/CI waiting, merge and publication separately; this task does not authorize a release.
+
+### Local Evidence (November 5, 2026)
+
+- Source: implementation `c724e90976a69042d40e78ac7ef81e460b849225`, based on `7802e5756`; Flutter 3.47.2 / Dart 3.13.2 on macOS arm64, unchanged `pubspec.lock`.
+- Red: final 31 activity regression tests all fail against the unchanged production files from the base. Initial failing tests were committed before implementation; the concise reader-caption regression separately failed twice before its fix.
+- Green: `flutter test --no-pub` with `super_tab_task_activity_test.dart`, `super_tab_tasks_view_test.dart`, `super_tab_task_groups_test.dart`, `super_tab_task_columns_test.dart`, `super_tab_tasks_header_test.dart`, `super_tab_tasks_shots_test.dart`, `harness_activity_test.dart`, `laid_out_list_test.dart`: 91 passed, 7.89 seconds wall time. This is affected coverage, not a full Desktop suite.
+- Analyze: both production files, new activity tests, screenshot and header fixtures: no issues (7.5 seconds). The changed existing Tasks view test file has a pre-existing single-cascade lint at line 102, outside these edits; it was reported, not fixed as unrelated cleanup.
+- Guards: UI style checker passed; icon audit passed (953 Dart files, 181 catalogue symbols, 853 references); `git diff --check` passed. LaidOutList guard is included in the 91 passing tests.
+- Screenshots: four 1900×900 fixture renders, Board/List in light/dark, inspected and attached to task #3007; Dee also received a person line. System SF Mono and Apple Symbols are explicitly loaded in the macOS screenshot fixture so activity glyphs are real glyphs rather than Ahem boxes. Runtime/native verification remains a separate Test step, not claimed by widget screenshots.
+- Rendering measurement: identical 300-task Board mount workload, 2 warmups and 20 samples, real fonts, Reduce Motion enabled, same machine/toolchain. Base median 53.523 ms / p95 74.708 ms; implementation median 55.238 ms / p95 85.439 ms. These are whole test-fixture mount costs, not native frame latency. ENGINEERING §4 exception: adding a status cell to previously unmarked cards costs 1.715 ms median in this workload (+3.2%); the replacement criterion is bounded mount cost with no new reads/polling and animation confined to the existing lifecycle-aware shared repaint boundary. Do not call this a speedup or claim unchanged performance; independent runtime review must judge responsiveness.
+- Clock: task requested at 02:00:27 UTC; implementation committed at 02:17:47 UTC (17m20s including inspection, test-first cycles and local validation). Validation time is recorded separately above and overlaps implementation. Independent review/test and CI waiting start afterward; merge and publication have not happened and belong to the PM.
+
+### Review Correction: Shared Activity Colors
+
+- Reviewer Heron7 required the peer surfaces' `activityColor` resolver and live terminal-theme/monochrome preference handling. The earlier neutral mark did not meet the icon system. Minor findings remain recorded in the Review step rather than expanding this fix.
+- Test-first commit `70b95432f`: per-state colors and live terminal-theme/monochrome updates on both Board and List. Against the previous implementation: 24 expected failures, 9 other regressions pass. No preference setters or disk persistence are used by these tests.
+- Fix `96604dfc7b16c56f3336e62f68d68a981ab9e2ab`: only the mark subtree listens to the two existing preference stores and resolves the shared activity color; the card, title, layout and activity clock are unchanged.
+- Affected validation: 82 tests pass in 8.23 seconds (activity regression, Tasks view/header/screenshots, shared activity and LaidOutList). The 11 unchanged grouping/column checks retain their previous evidence: the correction touches neither their source nor their interfaces. Changed card and activity test analyze clean in 6.0 seconds; style and icon guards pass again.
+- Refreshed light/dark Board/List screenshots are attached to #3007 and Dee received a new person line. This is rendered fixture evidence, not a native build.
+- Same 300-task mount benchmark after the color correction: median 57.152 ms / p95 88.090 ms, compared with the original base 53.523 / 74.708 ms. The final delta is +3.629 ms median (+6.8%), p95 +17.9%. The explicit ENGINEERING §4 exception above applies to these final numbers; no speedup or unchanged-performance claim is made. Preference changes rebuild only the mark subtree; there is no new polling or data read.
+- The independent Tester verified the previous head's rendered main flow on macOS with Flutter 3.47.9 and fake sign-in/memory stores. That Team account has no Xcode, so a native macOS build/real window remains unverified. Final-head color/preference verification and re-review are pending. Initial review/CI waiting and this corrective test-first cycle are separate from initial implementation; the color fix committed at 02:31:13 UTC. Merge and publication are still pending PM work.
+
+## Design
+
+N/A for growth, locks, incremental reads, 10x data scale, migration/rollback, audience and identity: presentation-only, no stored or exposed data added. Compatibility and failure: existing task fields stay unchanged; explicit failed/lost marks remain visible. Platforms: shared Flutter desktop/web presentation; macOS local widget/screenshots and independent runtime testing, Linux VM coverage in PR CI.
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index cb9bf856b..c20fdb8c8 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -1467,6 +1467,17 @@ class SuperTabMessage {
SuperTabRoute? get route => SuperTabRoute.fromSource(source);
bool get routeOverride => source['kind'] == 'route-override';
+ /// The project and revision an instructions save's chat line names, which
+ /// its "See revision" link opens (#3021); null for any other row.
+ ({String projectId, int revision})? get instructionsSave =>
+ switch ((source['kind'], source['projectId'], source['revision'])) {
+ ('instructions', final String projectId, final num revision) => (
+ projectId: projectId,
+ revision: revision.toInt(),
+ ),
+ _ => null,
+ };
+
/// A task's root the server posted in its person's name (plain chat, #2294):
/// theirs to read, not their own writing, so it reads nothing before it and
/// is unread for them as anyone else's message is.
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index ae0fa4829..73c3351a7 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -50,6 +50,7 @@ import 'swarm_link_previews.dart';
import 'swarm_message_edit.dart';
import 'swarm_message_link.dart';
import 'swarm_message_receipt.dart';
+import 'swarm_instructions_page.dart' show openSwarmInstructionsRevision;
import 'swarm_message_row.dart';
import 'swarm_need_rows.dart';
import 'swarm_paste.dart';
@@ -2266,6 +2267,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
readerId: c.reader.accountId,
references: references,
onOpenConversation: (id) => _openNumberedConversation(c, id),
+ onOpenInstructions: (saved) => openSwarmInstructionsRevision(
+ context,
+ reader: c.reader,
+ projectId: saved.projectId,
+ revision: saved.revision,
+ ),
grouped: grouped,
lit: lit,
followed: followed,
diff --git a/mobile/lib/swarm/swarm_instructions_page.dart b/mobile/lib/swarm/swarm_instructions_page.dart
index 875790448..e9c62c372 100644
--- a/mobile/lib/swarm/swarm_instructions_page.dart
+++ b/mobile/lib/swarm/swarm_instructions_page.dart
@@ -31,6 +31,202 @@ void openSwarmInstructions(
),
);
+/// Opens one saved revision of [projectId]'s instructions, read only: where an
+/// instructions save's line in the chat leads (#3021).
+void openSwarmInstructionsRevision(
+ BuildContext context, {
+ required SwarmReader reader,
+ required String projectId,
+ required int revision,
+}) => unawaited(
+ Navigator.of(context).push(
+ phoneRoute(
+ (_) => SwarmInstructionsRevisionPage(
+ reader: reader,
+ projectId: projectId,
+ revision: revision,
+ ),
+ ),
+ ),
+);
+
+/// One kept revision of a project's instructions: its text, who saved it, when
+/// and their summary. Read once when it opens, and again on a pull; a revision
+/// no longer kept says so.
+class SwarmInstructionsRevisionPage extends StatefulWidget {
+ const SwarmInstructionsRevisionPage({
+ super.key,
+ required this.reader,
+ required this.projectId,
+ required this.revision,
+ });
+
+ final SwarmReader reader;
+ final String projectId;
+ final int revision;
+
+ @override
+ State<SwarmInstructionsRevisionPage> createState() =>
+ _SwarmInstructionsRevisionPageState();
+}
+
+class _SwarmInstructionsRevisionPageState
+ extends State<SwarmInstructionsRevisionPage> {
+ SuperTabRevision? _saved;
+ String? _error;
+ bool _gone = false;
+
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_read());
+ }
+
+ Future<void> _read() async {
+ final reader = widget.reader;
+ try {
+ final answer = superTabMap(
+ await reader.request(
+ 'GET',
+ superTabInstructionsPath(
+ reader.tabId,
+ widget.projectId,
+ revision: widget.revision,
+ ),
+ ),
+ );
+ if (!mounted) return;
+ setState(() {
+ _saved = SuperTabRevision.fromJson(answer);
+ _error = null;
+ });
+ } on SuperTabFailure catch (failure) {
+ if (!mounted) return;
+ setState(() {
+ _gone = failure.statusCode == 404;
+ _error = failure.message;
+ });
+ } on Object {
+ if (!mounted) return;
+ setState(() => _error = 'Couldn’t read this revision.');
+ }
+ }
+
+ /// Who saved it: a person by name, an agent by its name, else Harness.
+ String _writer(SuperTabRevision saved) {
+ final snapshot = widget.reader.snapshot;
+ final by = saved.writtenBy;
+ return switch (by.kind) {
+ 'person' =>
+ snapshot?.people.where((p) => p.id == by.id).firstOrNull?.shownName ??
+ 'a member',
+ 'agent' =>
+ snapshot?.agentName(by.id, fallback: 'Product Manager') ??
+ 'Product Manager',
+ _ => 'Harness',
+ };
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final project = widget.reader.snapshot?.projects
+ .where((p) => p.id == widget.projectId)
+ .firstOrNull;
+ final saved = _saved;
+ final quiet = Tty.of(context)
+ .style(color: AppPalette.textFaint, size: 12.5);
+ final error = _error;
+ return Scaffold(
+ backgroundColor: AppPalette.windowBg,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SwarmTopBar(
+ leading: SwarmBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ title: 'Instructions',
+ subtitle: [
+ if (project != null) '#${project.name}',
+ 'revision ${widget.revision}',
+ ].join(' · '),
+ ),
+ Expanded(
+ child: RefreshIndicator(
+ onRefresh: _read,
+ child: SelectionArea(
+ child: ListView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: EdgeInsets.fromLTRB(
+ AppSpace.m,
+ AppSpace.xs,
+ AppSpace.m,
+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,
+ ),
+ children: [
+ if (saved != null) ...[
+ Text(
+ '${_writer(saved)} · '
+ '${relativeAgo(saved.at, clock.now())} · '
+ '${saved.summary}',
+ key: const ValueKey('swarm-revision-saved'),
+ style: quiet,
+ ),
+ const SizedBox(height: AppSpace.s),
+ for (final part in swarmTextParts(saved.text ?? ''))
+ if (part.code)
+ SwarmCodeBlock(code: part.text, name: part.name)
+ else
+ Padding(
+ padding: const EdgeInsets.only(
+ bottom: AppSpace.s,
+ ),
+ child: Text(part.text, style: swarmChatText(15)),
+ ),
+ ] else if (_gone)
+ Text(
+ 'Revision ${widget.revision} is no longer kept: '
+ 'a project keeps its last 50.',
+ key: const ValueKey('swarm-revision-gone'),
+ style: swarmChatText(
+ 15,
+ color: AppPalette.textSecondary,
+ ),
+ )
+ else if (error != null) ...[
+ Text(
+ error,
+ key: const ValueKey('swarm-revision-error'),
+ style: swarmChatText(
+ 15,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ const SizedBox(height: AppSpace.s),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: SwarmButton(
+ label: 'Try again',
+ onPressed: () => unawaited(_read()),
+ ),
+ ),
+ ] else
+ Text('Loading…', style: quiet),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
/// A project's instruction document and its coordinator's notes (project
/// instructions, decisions 15 and 16). Read when it opens and again when the
/// project's `instructionsRevision` or `notesRevision` moves in the Swarm read;
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 1edd45f43..9f4c572e8 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -293,6 +293,7 @@ class SwarmMessageRow extends StatelessWidget {
this.onLongPress,
this.references = const {},
this.onOpenConversation,
+ this.onOpenInstructions,
});
final SuperTabMessage message;
@@ -343,6 +344,10 @@ class SwarmMessageRow extends StatelessWidget {
/// Opens a conversation resolved from [references].
final ValueChanged<String>? onOpenConversation;
+ /// Opens the revision an instructions save's line names
+ /// ([SuperTabMessage.instructionsSave]), to read the change whole.
+ final ValueChanged<({String projectId, int revision})>? onOpenInstructions;
+
/// Null where the person cannot post, or in the thread itself.
final VoidCallback? onReply;
@@ -510,6 +515,22 @@ class SwarmMessageRow extends StatelessWidget {
onOpenConversation: onOpenConversation,
),
),
+ if ((message.instructionsSave, onOpenInstructions) case (
+ final saved?,
+ final open?,
+ ))
+ TtyTap(
+ key: ValueKey('swarm-instructions-link-${message.id}'),
+ semanticsLabel: 'See revision ${saved.revision}',
+ onTap: () => open(saved),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),
+ child: Text(
+ 'See revision ${saved.revision}',
+ style: swarmChatText(14, color: AppPalette.accentOnSurface),
+ ),
+ ),
+ ),
if (message.editedAt != null)
Padding(
padding: const EdgeInsets.only(top: AppSpace.xs),
diff --git a/mobile/test/swarm/swarm_instructions_line_test.dart b/mobile/test/swarm/swarm_instructions_line_test.dart
new file mode 100644
index 000000000..9b22fb545
--- /dev/null
+++ b/mobile/test/swarm/swarm_instructions_line_test.dart
@@ -0,0 +1,69 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+
+/// An instructions save's line in the project chat shows what it changed and
+/// opens the revision it saved (Ken, 11-05, #3021).
+void main() {
+ Widget row(
+ Map<String, dynamic> source,
+ void Function(({String projectId, int revision}))? open,
+ ) => MaterialApp(
+ home: Scaffold(
+ body: ListView(
+ children: [
+ SwarmMessageRow(
+ message: SuperTabMessage.fromJson({
+ 'id': 'saved',
+ 'conversationId': 'lead',
+ 'text':
+ 'owner changed the instructions: Reviews run on Opus.\n\n'
+ 'In Routing › Models:\nRemoved: Haiku reviews.\n'
+ 'Added: Opus reviews.\n\nand 3 more changes.',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': 'owner', 'name': 'owner'},
+ 'createdAt': DateTime.utc(2026, 11, 5).toIso8601String(),
+ 'source': source,
+ }),
+ name: 'owner',
+ look: (picture: null, status: null),
+ role: null,
+ mentions: SwarmMentions(const []),
+ grouped: false,
+ lit: false,
+ quote: null,
+ actions: false,
+ onTap: () {},
+ onReply: null,
+ onOpenInstructions: open,
+ ),
+ ],
+ ),
+ ),
+ );
+
+ testWidgets('shows the change and opens the revision it saved', (
+ tester,
+ ) async {
+ final opened = <({String projectId, int revision})>[];
+ await tester.pumpWidget(
+ row({
+ 'kind': 'instructions',
+ 'projectId': 'p1',
+ 'revision': 8,
+ }, opened.add),
+ );
+ expect(find.textContaining('Removed: Haiku reviews.'), findsOneWidget);
+ expect(find.textContaining('and 3 more changes.'), findsOneWidget);
+ await tester.tap(find.text('See revision 8'));
+ expect(opened, [(projectId: 'p1', revision: 8)]);
+ });
+
+ testWidgets('no link on any other line', (tester) async {
+ await tester.pumpWidget(row({'kind': 'ship'}, (_) {}));
+ expect(find.textContaining('See revision'), findsNothing);
+ await tester.pumpWidget(row({'kind': 'instructions'}, (_) {}));
+ expect(find.textContaining('See revision'), findsNothing);
+ });
+}
diff --git a/mobile/test/swarm/swarm_instructions_page_test.dart b/mobile/test/swarm/swarm_instructions_page_test.dart
index 84fc3e801..3178ac484 100644
--- a/mobile/test/swarm/swarm_instructions_page_test.dart
+++ b/mobile/test/swarm/swarm_instructions_page_test.dart
@@ -58,6 +58,7 @@ void main() {
int revision = 3,
Object? Function(Map<String, dynamic>? body)? commands,
String role = 'owner',
+ int? saved,
}) async {
final fake = FakeSwarm();
fake.routes['/api/super-tabs/$tab/parts'] = (_) {
@@ -69,7 +70,7 @@ void main() {
return load;
};
fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
- fake.routes[path] = route;
+ fake.routes[saved == null ? path : '$path/revisions/$saved'] = route;
if (commands != null) {
fake.routes['/api/super-tabs/$tab/commands'] = commands;
}
@@ -82,7 +83,13 @@ void main() {
await reader.refresh();
await tester.pumpWidget(
MaterialApp(
- home: SwarmInstructionsPage(reader: reader, projectId: project),
+ home: saved == null
+ ? SwarmInstructionsPage(reader: reader, projectId: project)
+ : SwarmInstructionsRevisionPage(
+ reader: reader,
+ projectId: project,
+ revision: saved,
+ ),
),
);
await tester.pumpAndSettle();
@@ -156,6 +163,51 @@ void main() {
expect(reads(fake), 2);
});
+ // Ken, 11-05 (#3021): an instructions save's chat line opens the revision
+ // it saved, to read the change whole.
+ group('one revision', () {
+ testWidgets('reads that revision alone and shows its text read only', (
+ tester,
+ ) async {
+ final (:fake, reader: _) = await open(
+ tester,
+ saved: 7,
+ route: (_) => {
+ 'projectId': project,
+ 'revision': 7,
+ 'hash': 'h7',
+ 'text': '## Routing\n- Reviews run on Opus.',
+ 'summary': 'Reviews run on Opus',
+ 'writtenBy': {'kind': 'person', 'id': me},
+ 'askedBy': me,
+ 'at': '2026-10-29T01:00:00.000Z',
+ },
+ );
+ expect(fake.paths.where((p) => p == '$path/revisions/7'), hasLength(1));
+ expect(reads(fake), 0);
+ expect(find.textContaining('revision 7'), findsOneWidget);
+ expect(find.textContaining('Reviews run on Opus.'), findsWidgets);
+ expect(find.textContaining('ken · '), findsOneWidget);
+ expect(find.text('Delete'), findsNothing);
+ });
+
+ testWidgets('one no longer kept says so', (tester) async {
+ await open(
+ tester,
+ saved: 2,
+ route: (_) => throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'This revision is unavailable.',
+ statusCode: 404,
+ ),
+ );
+ expect(
+ find.text('Revision 2 is no longer kept: a project keeps its last 50.'),
+ findsOneWidget,
+ );
+ });
+ });
+
testWidgets('a backend without instructions says so', (tester) async {
await open(
tester,
diff --git a/mobile/test/swarm/swarm_instructions_shots_test.dart b/mobile/test/swarm/swarm_instructions_shots_test.dart
index b8b61859c..586d7971d 100644
--- a/mobile/test/swarm/swarm_instructions_shots_test.dart
+++ b/mobile/test/swarm/swarm_instructions_shots_test.dart
@@ -8,7 +8,9 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/model.dart';
import 'package:harness_mobile/swarm/swarm_instructions_page.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
import 'package:harness_mobile/swarm/swarm_reader.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
@@ -151,4 +153,138 @@ void main() {
}
debugDisableShadows = true;
}, skip: shots == null);
+
+ // Ken, 11-05 (#3021): the save's line says what changed, and opens the
+ // revision it saved.
+ testWidgets('pictures of an instructions line and its revision', (
+ tester,
+ ) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ tester.view
+ ..physicalSize = const Size(390, 844) * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/projects/$project/instructions/revisions/68'] =
+ (_) => {
+ 'projectId': project,
+ 'revision': 68,
+ 'hash': 'h68',
+ 'text':
+ '## Routing\n\n### Models\n\n- No agent runs below high '
+ 'effort, and none on Claude Haiku.\n- Reviewers run on Opus.',
+ 'summary': 'Routing: no Haiku.',
+ 'writtenBy': {'kind': 'person', 'id': me},
+ 'askedBy': me,
+ 'at': DateTime.now()
+ .subtract(const Duration(minutes: 3))
+ .toIso8601String(),
+ };
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(reader.dispose);
+ await tester.runAsync(reader.refresh);
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ home: Builder(
+ builder: (context) => Scaffold(
+ backgroundColor: AppPalette.windowBg,
+ body: SafeArea(
+ child: ListView(
+ children: [
+ SwarmMessageRow(
+ message: SuperTabMessage.fromJson({
+ 'id': 'saved',
+ 'conversationId': 'lead',
+ 'text':
+ 'River changed the instructions for ken: '
+ 'Routing: no Haiku.\n\n'
+ 'In Routing › Models:\n'
+ 'Removed: No agent runs below high effort.\n'
+ 'Added: No agent runs below high effort, and '
+ 'none on Claude Haiku.\n'
+ 'Added: Reviewers run on Opus.\n\n'
+ 'and 9 more changes.',
+ 'sequence': 1,
+ 'author': {
+ 'kind': 'agent',
+ 'id': 'pm',
+ 'name': 'River',
+ },
+ 'createdAt': DateTime.now()
+ .subtract(const Duration(minutes: 3))
+ .toIso8601String(),
+ 'source': {
+ 'kind': 'instructions',
+ 'projectId': project,
+ 'revision': 68,
+ },
+ }),
+ name: 'River',
+ look: (picture: null, status: null),
+ role: 'PM',
+ pm: true,
+ mentions: SwarmMentions(const []),
+ grouped: false,
+ lit: false,
+ quote: null,
+ actions: false,
+ onTap: () {},
+ onReply: null,
+ onOpenInstructions: (saved) =>
+ openSwarmInstructionsRevision(
+ context,
+ reader: reader,
+ projectId: saved.projectId,
+ revision: saved.revision,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/instructions-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ await capture('line');
+ await tester.tap(find.text('See revision 68'));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('none on Claude Haiku.'), findsOneWidget);
+ await capture('revision');
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
}