The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-05 i1640: #3134 #3140 #3141 #3078 (#3143)
0xken150c47f4f880b6
diff --git a/backend/integration/superTabPmSchedule.test.ts b/backend/integration/superTabPmSchedule.test.tsindex 7e6db9ae9..936725161 100644--- a/backend/integration/superTabPmSchedule.test.ts+++ b/backend/integration/superTabPmSchedule.test.ts@@ -80,8 +80,10 @@ async function swarm({ fresh = false, told }: { fresh?: boolean; told?: string[]// Its own first: a machine's report also judges the others', and one not heard from in 2 minutes loses its work.for (const machineId of ['test-host', 'lead-host']) await timed.observeMachine(host, tab, machineId, { generation: generations.get(machineId)!,resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },- quotas: [], tools: {}, runningHarnessIds: [harnessOf.get(machineId)!], stoppedHarnessIds: [] })+ quotas: machineId === 'lead-host' ? readings.lead : [], tools: {}, runningHarnessIds: [harnessOf.get(machineId)!], stoppedHarnessIds: [] })}+ /** What the coordinator's machine reports of its week: nothing, until a test sets it. */+ const readings = { lead: [] as unknown[] }const poll = async () => {// Its worker keeps saying where it is, as a live one does; a finished task refuses the line and nothing changes.await execute({ type: 'work.status', conversationId: group, assignmentId, status: 'working', result: randomUUID() }, host, worker).catch(() => {})@@ -110,7 +112,7 @@ async function swarm({ fresh = false, told }: { fresh?: boolean; told?: string[]})return id}- return { timed, tab, execute, lead, group, worker, assignmentId, clock, poll, status, write, add }+ return { timed, tab, execute, lead, group, worker, assignmentId, clock, poll, status, write, add, readings }}const rowsOf = (tabId: string, where: Record<string, unknown> = {}) => db.superTabDelivery.findMany({ where: { tabId, ...where }, orderBy: { createdAt: 'asc' } })@@ -143,6 +145,26 @@ describe('the built-in schedule on the coordinator\'s poll', () => {expect((await projectOf(f)).schedule).toMatchObject({ lastSlot: scheduleSlot(f.clock.now) })})+ it('ends the wake with where the coordinator runs and its week left when its machine reports it, and says nothing when it does not (Ken, 11-05)', async () => {+ const reported = { engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 30, resetsAt: Date.parse('2026-11-04T06:30:00.000Z') + 4 * 86_400_000 }] }+ const f = await swarm()+ f.readings.lead = [reported]+ wantSchedule()+ await unassigned(f)+ await f.poll()+ const [known] = await schedules(f.tab)+ expect(known!.text).toMatch(/\n\nYou run on Lead Mac, host's own account: weekly 70% left, resets in \d+[dhm]\.$/)+ expect(known!.text).not.toContain('@')+ // The same wake with no reading: the line is left out, not guessed.+ const g = await swarm()+ wantSchedule()+ await unassigned(g)+ await g.poll()+ const [unknown] = await schedules(g.tab)+ expect(unknown).toBeDefined()+ expect(unknown!.text).not.toContain('You run on')+ })+it('is the coordinator\'s alone: no person sees it in the chat, and no other agent reads it', async () => {const f = await swarm()wantSchedule()diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.tsindex 85b3ce389..89a3be289 100644--- a/backend/src/superTabs/instructions.test.ts+++ b/backend/src/superTabs/instructions.test.ts@@ -89,6 +89,16 @@ describe('the built-in template', () => {expect(role('Engineer', 'Reviewer')).toContain(line)expect(role('Reviewer', 'Tester')).toContain(line)})+ // Ken and Dee, 11-05: lamp-gtm's PM held dee's build behind its weekly line and asked dee three options. Nobody is asked+ // about quota now; an account any project's PM runs on keeps 20% of its weekly quota for that PM, and every other is used.+ it('keeps 20% of the week on an account any project\'s PM runs on, uses every other account, and asks no one', () => {+ const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\s+/g, ' ')+ expect(routing).toContain('2. An account any project\'s PM runs on (this project\'s or another\'s; the route notes it) keeps 20% of its weekly quota for that PM: below 20% left it takes no new work and idle agents there are not reused. Above that it is used like any other account.')+ expect(routing).toContain('- Nobody is asked about quota or whose account to use. When no account fits, the work waits for the soonest reset, and the task says so.')+ expect(routing).toContain('or whose account is a PM\'s and falls below 20%, hands its pushed branch')+ for (const gone of ['share of its week left', 'owner asks for', 'takes work as any other account does']) expect(routing).not.toContain(gone)+ })+it('describes the spec\'s roles, workflow and routing in one short document', () => {for (const heading of ['## Roles', '## Workflow', '## Routing', '### PM', '### Engineer', '### Reviewer', '### Tester']) {expect(INSTRUCTIONS_TEMPLATE).toContain(heading)@@ -109,6 +119,26 @@ describe('the built-in template', () => {expect(pm).toContain('- When the project owner answers Yes to a nightly routing proposal, writes its line into Routing, naming the owner as who asked.')expect(Buffer.byteLength(INSTRUCTIONS_TEMPLATE)).toBeLessThan(16_384)})+ // Ken, 11-05: openharness's and lamp's PMs own their projects; what made them owners is every new project's PM's now.+ it('gives every new project\'s PM the owner\'s lines: it owns the project, decides, says no, moves fast and reports what is stuck', () => {+ const pm = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('### PM'), INSTRUCTIONS_TEMPLATE.indexOf('### Engineer')).replace(/\s+/g, ' ')+ for (const line of [+ 'Owns the project: its roadmap, deadlines, progress and quality, and every task and pull request.',+ 'Decides, doesn\'t ask: it decides and reports the result.',+ 'It never asks "OK to build?", "should I" or "do you want", and never offers a choice it can make itself: it picks, says why in one line, and goes.',+ 'Says no by default to new features and growing scope: it answers each request Accept, Reshape, Later (and when) or No, naming why.',+ 'Thinks fast and slow:',+ 'A bug that breaks what already ships, or stops people\'s or agents\' work, is a hotfix at once; it never waits for someone to say "urgent".',+ 'Sets deadlines for today, in hours.',+ 'Each hour it finds where work waits and fixes the slowest step itself, without waiting to be told.',+ 'A status gives the goal, what must exist today, and what is stuck (owner and time); never what is already done.',+ 'Before answering a message in a task, reads that task\'s state and its latest messages.',+ 'Links every issue and pull request number it names.',+ ]) expect(pm).toContain(line)+ // Shared lines name no person (instructions attribution).+ expect(pm).not.toMatch(/\((Ken|Dee|Leo)[,)]/)+ })+it('keeps a Reviewer or Tester working on its step while the Engineer fixes findings: blocked is for a person', () => {// Ken, 2026-11-02: 47 of a day's "Stuck" statuses reached the PM from Reviewers waiting on the Engineer's fixes.const workflow = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Workflow'), INSTRUCTIONS_TEMPLATE.indexOf('## Routing'))@@ -132,8 +162,7 @@ describe('the built-in template', () => {// window is never hit, so only the weekly quota counts. No plan size here: projects differ.const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\n +/g, ' ')expect(routing).toContain('Every assignment (an Engineer, a Reviewer, a Tester, an idle agent reused) picks in this order:')- expect(routing).toContain('The PM\'s own account (the engine it runs on, on its machine) keeps the PM running for the whole week.')- expect(routing).toContain('weekly quota left above the share of its week left (with 5 of 7 days to go, above 71%)')+ expect(routing).toContain('keeps 20% of its weekly quota for that PM')expect(routing).toContain('Every other account is used while it has weekly quota left: the one resetting soonest first')expect(routing).toContain('An idle agent is reused only between candidates equal so far')expect(routing).toContain('"Idle" or "first in the list" is not a reason.')@@ -141,11 +170,6 @@ describe('the built-in template', () => {expect(routing).toContain('Urgent work (production down, security) ignores quota.')for (const gone of ['share per day', '5-hour', 'Engineers move to the next model', 'Max 20x']) expect(routing).not.toContain(gone)})- it('lets the PM\'s own account take work as any other once no other account has weekly quota left', () => {- // Ken, 2026-11-03: with every other account out, work should not wait on the PM's weekly line.- const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\n +/g, ' ')- expect(routing).toContain('- When no other account has weekly quota left, the PM\'s account takes work as any other account does.')- })it('says the route lists every engine on every machine with its weekly quota, which the PM orders by itself', () => {// Ken, 2026-11-03: the route's rows now carry each account's quota, and no account is cut from them.const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\n +/g, ' ')diff --git a/backend/src/superTabs/instructionsTemplate.ts b/backend/src/superTabs/instructionsTemplate.tsindex 7187e81f1..a557a52a9 100644--- a/backend/src/superTabs/instructionsTemplate.ts+++ b/backend/src/superTabs/instructionsTemplate.ts@@ -13,6 +13,27 @@ export const TEMPLATE_ROLES = `## Roles### PM- Talks with people in the project chat and finds out what they want.+- Owns the project: its roadmap, deadlines, progress and quality, and every task and pull request. It works without pause+ toward the project's goal, with every machine and agent the Swarm has.+- Decides, doesn't ask: it decides and reports the result. It asks a person only where a rule names that person, or for+ a step only that person can do (a sign-in, adding a machine), and then with its recommendation and a default it applies+ at a stated time. It never asks "OK to build?", "should I" or "do you want", and never offers a choice it can make+ itself: it picks, says why in one line, and goes.+- Says no by default to new features and growing scope: it answers each request Accept, Reshape, Later (and when) or No,+ naming why. A fix to what already ships, a security fix, and anything that makes the crew faster or more reliable is a+ yes at once.+- Thinks fast and slow: fast for what is cheap to undo (fixes, merges, routing, unblocking an agent), decided in the same+ turn; slow for what is hard to undo (a new feature, deleting data, production writes, spending money): it reads the+ evidence, writes down its reasoning, then decides.+- A bug that breaks what already ships, or stops people's or agents' work, is a hotfix at once; it never waits for+ someone to say "urgent".+- Sets deadlines for today, in hours. Work over an hour late moves to another agent, and blockers (reads, tests, lifting+ a hold) run in parallel, never one after another.+- Each hour it finds where work waits and fixes the slowest step itself, without waiting to be told.+- A status gives the goal, what must exist today, and what is stuck (owner and time); never what is already done.+- Before answering a message in a task, reads that task's state and its latest messages. It tags a person only when+ answering them or when they must act; a message asking an agent to act tags the person who owns that agent.+- Links every issue and pull request number it names.- Turns each request into a task with a goal and a "Done when".- Writes a task's brief as what to build: goal, changes, constraints, checks, and the Reviewer and Tester it names.It copies no workflow into a brief: how agents work is in these instructions, and a brief line that disagrees with them@@ -102,22 +123,23 @@ export const TEMPLATE_ROUTING = `## Routingfirmware. The machine comes before the model. A mid-strength model is enough for most testing.- Every assignment (an Engineer, a Reviewer, a Tester, an idle agent reused) picks in this order:1. What the work needs: the machine, a model strong enough, a machine not paused.- 2. The PM's own account (the engine it runs on, on its machine) keeps the PM running for the whole week. It takes- other work only while ahead of its week: weekly quota left above the share of its week left (with 5 of 7 days- to go, above 71%). At or below that line it takes no new work and idle agents there are not reused.+ 2. An account any project's PM runs on (this project's or another's; the route notes it) keeps 20% of its weekly+ quota for that PM: below 20% left it takes no new work and idle agents there are not reused. Above that it is used like any+ other account.3. Every other account is used while it has weekly quota left: the one resetting soonest first, then the one withthe most left.4. An idle agent is reused only between candidates equal so far, except the same Reviewer for its next round andwork that follows straight on from what the agent just did.5. Between equals, the machine with fewer agents working. Then price.-- When no other account has weekly quota left, the PM's account takes work as any other account does.+- Nobody is asked about quota or whose account to use. When no account fits, the work waits for the soonest reset, and+ the task says so.- The route lists the best new agent and the best idle agent of every engine on every machine, each with its quota:fits or short, weekly quota left and reset time. It lists them by machine name, with no ranking and no pick: the PMapplies this order itself. Every start or assignment from a route gives as its reason the rule above that chose it:urgency, context or a machine the work needs where it departs from the order. "Idle" or "first in the list" is not areason.-- An agent whose account runs out of weekly quota mid-task, or whose account is the PM's and falls below its line,- hands its pushed branch to an agent on another account.+- An agent whose account runs out of weekly quota mid-task, or whose account is a PM's and falls below 20%, hands its+ pushed branch to an agent on another account.- Urgent work (production down, security) ignores quota.`/** The title and the opening words, which say what the document is for. */diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex b961b4ef9..6dbbd00ee 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -484,6 +484,8 @@ export interface SuperTabState {overlapAlerts?: string[]/** Read-only, for a Lead's own reads (visibleState): the active work of the other projects it may know about. */otherProjectsWork?: OtherProjectWork[]+ /** Read-only, for a project agent's reads (visibleState): the account every project's PM runs on, for the route's notes. */+ pmAccounts?: PmAccount[]/** Read-only, for the Swarm owner's reads (visibleState): the projects nobody owns, by name and size (projects.ts). */ownerlessProjects?: Array<{ id: string; name: string; conversations: number }>ownerId: string@@ -557,6 +559,26 @@ export interface SwarmLocalModels {ready?: booleanerror?: string}+/** An account a project's PM runs on (Ken, 11-05): its machine (a Mac's Harness Team account names that Mac too, whose+ * subscription it spends) and engine. A project the reader may not read is "another project", its PM unnamed. */+export interface PmAccount { machineId: string; hostMachineId?: string; engine: string; project: string; pm: string }++/** Every project's PM account (PmAccount): a PM could drain the account another project's PM ran on, and the route, reading+ * as an agent of one project, saw no other project's PM (review of #3134). */+export function pmAccounts(state: SuperTabState, actor: Actor): PmAccount[] {+ return projectsOf(state).flatMap(project => {+ const leadId = state.conversations.find(c => c.id === project.leadConversationId)?.leadId+ const pm = leadId ? state.agents.find(a => a.id === leadId) : undefined+ const engine = pm?.configuration?.engine+ if (!pm || !engine) return []+ const host = state.machines?.find(m => m.machineId === pm.machineId)?.hostMachineId+ // A public project is named to every project agent, as otherProjectsWork names it (sharedWithLeads).+ const readable = canReadProject(state, actor, project) || sharedWithLeads(project)+ return [{ machineId: pm.machineId, ...(host ? { hostMachineId: host } : {}), engine,+ project: readable ? project.name : 'another project', pm: readable ? pm.displayName ?? pm.name : 'its PM' }]+ })+}+export interface OtherProjectWork {conversationId: stringprojectName: string@@ -1055,5 +1077,10 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(}const seen = seenMachineIds(visible)visible.conversations = visible.conversations.map(c => withSeenRequirement(c, seen))+ // A project agent's route notes the accounts PMs run on, on machines it may see: after the Buddy's machines are gone.+ if (actor.kind === 'agent' && visible.machines?.length) {+ const machines = new Set(visible.machines.map(m => m.machineId))+ visible.pmAccounts = pmAccounts(state, actor).filter(a => machines.has(a.machineId) || (a.hostMachineId !== undefined && machines.has(a.hostMachineId)))+ }return visible}diff --git a/backend/src/superTabs/othersWork.ts b/backend/src/superTabs/othersWork.tsindex 06f54c81d..e7820beba 100644--- a/backend/src/superTabs/othersWork.ts+++ b/backend/src/superTabs/othersWork.ts@@ -12,7 +12,7 @@ import { canReadProject, groupProject, ledProject } from './projects.js'import { usernameOf } from './usernames.js'/** "3d", "5h", "20m": how long until [ms] from [now], as the Machines screen says a reset. */-function until(ms: number, now: number): string {+export function until(ms: number, now: number): string {const left = Math.max(0, ms - now)if (left >= 86_400_000) return `${Math.floor(left / 86_400_000)}d`if (left >= 3_600_000) return `${Math.floor(left / 3_600_000)}h`diff --git a/backend/src/superTabs/parts/shape.ts b/backend/src/superTabs/parts/shape.tsindex a078dfc87..485932624 100644--- a/backend/src/superTabs/parts/shape.ts+++ b/backend/src/superTabs/parts/shape.ts@@ -13,7 +13,7 @@ const PART_ONLY_GROUP_FIELDS = ['messageSeq', 'reportSeq', 'dormant', 'lastActiv/** Optional lists of `SuperTab.state` an empty one of which differs from an absent one (`[]` after the last machine left). */const LISTS = ['parkedConversations', 'starts', 'machines', 'harnessReservations', 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups'] as constconst STATE_ONLY = ['people', 'agents', 'conversations', 'parkedConversations', 'starts', 'machines', 'harnessReservations',- 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups', 'otherProjectsWork', 'groupCounter', 'sequenceBase'] as const+ 'releasedHarnesses', 'closingSessions', 'removedSessions', 'machineCleanups', 'otherProjectsWork', 'pmAccounts', 'groupCounter', 'sequenceBase'] as constconst isLegacyProgress = (progress: unknown): progress is LegacyProgress =>!!progress && typeof progress === 'object' && 'dirtyRevision' in progressdiff --git a/backend/src/superTabs/parts/types.ts b/backend/src/superTabs/parts/types.tsindex faefc0261..21b0a48fd 100644--- a/backend/src/superTabs/parts/types.ts+++ b/backend/src/superTabs/parts/types.ts@@ -29,7 +29,7 @@ export type HeadProject = Omit<SwarmProject, 'progress'>/** The head: everything in `SuperTabState` that is not one of the other parts. */export type HeadData = Omit<SuperTabState, 'people' | 'agents' | 'conversations' | 'parkedConversations' | 'starts' | 'machines'- | 'harnessReservations' | 'releasedHarnesses' | 'closingSessions' | 'removedSessions' | 'machineCleanups' | 'otherProjectsWork' | 'projects'+ | 'harnessReservations' | 'releasedHarnesses' | 'closingSessions' | 'removedSessions' | 'machineCleanups' | 'otherProjectsWork' | 'pmAccounts' | 'projects'| 'groupCounter' | 'sequenceBase'> & { projects?: HeadProject[]/** Which optional lists the state had, so an empty one comes back as `[]` and an absent one stays absent. */presentLists?: string[] }diff --git a/backend/src/superTabs/pmAccounts.test.ts b/backend/src/superTabs/pmAccounts.test.tsnew file mode 100644index 000000000..b97ca0e65--- /dev/null+++ b/backend/src/superTabs/pmAccounts.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'+import { pmAccounts, visibleState, type Actor } from './model.js'+import { fullSwarm, NOW, owner } from './read/fixture.test-support.js'++const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: `${owner.userId}-machine` })++/** fullSwarm with a PM for the private project "Secret" too, on [machineId]. */+function twoPms(machineId = 'host') {+ const s = fullSwarm()+ s.edit(draft => {+ const lead = draft.agents.find(a => a.id === s.lead)!+ draft.agents.push({ ...structuredClone(lead), id: 'secret-pm', harnessId: 'secret-pm-harness', name: 'Lead', displayName: 'Sage', machineId })+ const chat = draft.projects!.find(p => p.id === s.secret)!.leadConversationId+ draft.conversations.find(c => c.id === chat)!.leadId = 'secret-pm'+ })+ return s+}++// Ken, 11-05: a PM could drain the account another project's PM ran on, and the route, reading as that PM, saw only its own+// project. The read now carries every project's PM account, naming only projects the reader may read.+describe('pmAccounts', () => {+ it('lists every project\'s PM account for an agent\'s read, naming a project it cannot read only as another project', () => {+ const s = twoPms()+ const lead = s.state.agents.find(a => a.id === s.lead)!+ const engine = lead.configuration!.engine+ const first = s.state.projects!.find(p => p.leadConversationId === 'lead')!.name+ expect(visibleState(s.state, agentActor(s.lead), NOW).pmAccounts).toEqual([+ { machineId: 'host', engine, project: first, pm: lead.displayName ?? lead.name },+ { machineId: 'host', engine, project: 'another project', pm: 'its PM' },+ ])+ })++ // Review of #3134: an agent reads only its own project, so a public project was "another project" too.+ it('names a public project to every project agent, as otherProjectsWork does', () => {+ const s = twoPms()+ s.edit(draft => { draft.projects!.find(p => p.id === s.secret)!.visibility = 'public' })+ expect(visibleState(s.state, agentActor(s.lead), NOW).pmAccounts!.map(a => a.project)).toContain('Secret')+ })++ it('names the private project to a reader who may read it', () => {+ const s = twoPms()+ expect(pmAccounts(s.state, owner).map(a => a.project)).toContain('Secret')+ expect(pmAccounts(s.state, owner).find(a => a.project === 'Secret')!.pm).toBe('Sage')+ })++ it('gives a person\'s read and a Buddy\'s none', () => {+ const s = twoPms()+ expect(visibleState(s.state, owner, NOW)).not.toHaveProperty('pmAccounts')+ expect(visibleState(s.state, agentActor(s.buddy), NOW)).not.toHaveProperty('pmAccounts')+ })++ it('names the Mac of a PM on a Harness Team account, and leaves out a PM on a machine the reader cannot see', () => {+ const s = twoPms('host-team')+ s.edit(draft => { draft.machines!.push({ ...structuredClone(draft.machines!.find(m => m.machineId === 'host')!), machineId: 'host-team', name: 'host', hostMachineId: 'host' }) })+ expect(pmAccounts(s.state, owner).find(a => a.pm === 'Sage')).toMatchObject({ machineId: 'host-team', hostMachineId: 'host' })+ const hidden = twoPms('nowhere')+ expect(visibleState(hidden.state, agentActor(hidden.lead), NOW).pmAccounts!.map(a => a.pm)).not.toContain('its PM')+ })++ it('skips a project whose PM is gone or has no engine', () => {+ const s = twoPms()+ s.edit(draft => {+ draft.agents = draft.agents.filter(a => a.id !== 'secret-pm')+ draft.agents.find(a => a.id === s.lead)!.configuration = undefined as never+ })+ expect(pmAccounts(s.state, owner)).toEqual([])+ })+})diff --git a/backend/src/superTabs/pmFooting.test.ts b/backend/src/superTabs/pmFooting.test.tsnew file mode 100644index 000000000..68fab2af7--- /dev/null+++ b/backend/src/superTabs/pmFooting.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest'+import type { Agent, MessageDraft, SuperTabState } from './model.js'+import { addFooting, pmFooting } from './pmFooting.js'++const NOW = Date.UTC(2026, 10, 5, 3, 0)+const DAY = 86_400_000++const agent = (id: string, machineId: string, engine = 'claude'): Agent => ({ id, name: id, contributorId: 'ken', membershipGeneration: 'g', machineId, harnessId: `h-${id}`,+ machineOwnerId: 'ken', configuration: { engine, model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } } as unknown as Agent)++/** A Mac "Mac Studio" owned by ken, with a Harness Team account pool on it, and one reading of Claude's week on the Mac. */+function swarm(quotas: unknown, pmMachine = 'mac'): SuperTabState {+ const base = { contributorId: 'ken', membershipGeneration: 'g', generation: 'g', cwd: '/x', engines: ['claude'], maxAgents: 4, paused: false }+ return {+ version: 1, id: 'tab', name: 'Swarm', ownerId: 'ken', environment: 'prod', paused: false, invitations: [],+ people: [{ id: 'ken', email: '[email protected]', username: 'ken', role: 'owner', generation: 'g' }],+ agents: [agent('pm', pmMachine)], conversations: [],+ projects: [{ id: 'p1', name: 'openharness', ownerId: 'ken', leadConversationId: 'lead-p1', visibility: 'public', members: [], updateMinutes: 5 }],+ machines: [{ ...base, machineId: 'mac', name: 'Mac Studio', observation: { receivedAt: NOW, quotas } },+ { ...base, machineId: 'team', name: 'Mac Studio', hostMachineId: 'mac' }],+ } as unknown as SuperTabState+}+const known = [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 10, resetsAt: null }, { name: 'weekly', usedPercent: 38, resetsAt: NOW + 3 * DAY + 3_600_000 }] }]+const pm = (state: SuperTabState) => state.agents[0]!++describe('the PM\'s footing line in every built-in wake', () => {+ it('says the machine, the account and the weekly quota left with its reset, when the reading is known', () => {+ expect(pmFooting(swarm(known), pm(swarm(known)), NOW)).toBe('You run on Mac Studio, ken\'s own account: weekly 62% left, resets in 3d.')+ })+ it('names a Harness Team account as that, with its Mac\'s name and the Mac\'s reading', () => {+ const state = swarm(known, 'team')+ expect(pmFooting(state, pm(state), NOW)).toBe('You run on Mac Studio, the Harness Team account: weekly 62% left, resets in 3d.')+ })+ it('leaves the reset out when only it is unknown, and says nothing at all when the week is unknown', () => {+ const noReset = [{ engine: 'claude', known: true, windows: [{ name: 'weekly', usedPercent: 38, resetsAt: null }] }]+ expect(pmFooting(swarm(noReset), pm(swarm(noReset)), NOW)).toBe('You run on Mac Studio, ken\'s own account: weekly 62% left.')+ for (const quotas of [undefined, [], [{ engine: 'claude', known: false, windows: [] }], [{ engine: 'codex', known: true, windows: [{ name: 'weekly', usedPercent: 1, resetsAt: null }] }],+ [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 1, resetsAt: null }] }]]) {+ const state = swarm(quotas)+ expect(pmFooting(state, pm(state), NOW), JSON.stringify(quotas)).toBeNull()+ }+ })+ it('names the other account a PM runs on by its label, with that account\'s own reading, and says nothing when that reading is missing', () => {+ const profile = (leftPercent: number | null) => ({ engine: 'claude', id: 'a'.repeat(16), label: 'Work Max', leftPercent, resetsAt: new Date(NOW + 2 * DAY + 3_600_000).toISOString() })+ const withProfile = (profiles: unknown[] | undefined, profileId: string | null = 'a'.repeat(16)) => {+ const state = swarm(known)+ ;(state.machines![0] as { observation: { profiles?: unknown[] } }).observation.profiles = profiles+ state.agents[0]!.profileId = profileId ?? undefined+ return state+ }+ let state = withProfile([profile(71)])+ expect(pmFooting(state, pm(state), NOW)).toBe('You run on Mac Studio, Work Max: weekly 71% left, resets in 2d.')+ // Its own account's reading, never the machine's default one.+ for (const missing of [withProfile([profile(null)]), withProfile(undefined), withProfile([{ ...profile(50), id: 'b'.repeat(16) }])]) expect(pmFooting(missing, pm(missing), NOW)).toBeNull()+ state = withProfile([profile(71)], null)+ expect(pmFooting(state, pm(state), NOW)).toBe('You run on Mac Studio, ken\'s own account: weekly 62% left, resets in 3d.')+ })+ it('says nothing for a machine the Swarm does not list, and never names an email', () => {+ const state = swarm(known, 'gone')+ expect(pmFooting(state, pm(state), NOW)).toBeNull()+ const noName = swarm(known)+ noName.people[0]!.username = undefined+ expect(pmFooting(noName, pm(noName), NOW) ?? '').not.toMatch(/@|example\.com/)+ })+ it('adds it once to each built-in wake the PM gets, and to no other message', () => {+ const state = swarm(known)+ const draft = (kind: string, over: Partial<MessageDraft> = {}) => ({ id: kind, conversationId: 'lead-p1', text: `A ${kind}.`, recipients: ['pm'], source: { kind }, ...over }) as unknown as MessageDraft+ const wakes = ['schedule-request', 'update-request', 'digest-request', 'notice-digest', 'work-lost', 'work-stalled', 'idle'].map(k => draft(k))+ const others = [draft('review-failed'), draft('idle', { id: 'to-other', recipients: ['eng'] })]+ const line = 'You run on Mac Studio, ken\'s own account: weekly 62% left, resets in 3d.'+ addFooting(state, pm(state), [...wakes, ...others], NOW)+ for (const w of wakes) expect(w.text, w.id).toBe(`A ${w.id}.\n\n${line}`)+ expect(others.map(o => o.text)).toEqual(['A review-failed.', 'A idle.'])+ addFooting(state, pm(state), wakes, NOW)+ for (const w of wakes) expect(w.text.split('You run on ').length, w.id).toBe(2)+ })+ it('leaves every wake as it is when the reading is unknown', () => {+ const state = swarm(undefined)+ const wake = { id: 'w', conversationId: 'lead-p1', text: 'Built-in schedule.', recipients: ['pm'], source: { kind: 'schedule-request' } } as unknown as MessageDraft+ addFooting(state, pm(state), [wake], NOW)+ expect(wake.text).toBe('Built-in schedule.')+ })+})diff --git a/backend/src/superTabs/pmFooting.ts b/backend/src/superTabs/pmFooting.tsnew file mode 100644index 000000000..c436dc29c--- /dev/null+++ b/backend/src/superTabs/pmFooting.ts@@ -0,0 +1,49 @@+/**+ * The coordinator's own footing (Ken, 2026-11-05, follow-up to #3134): every built-in wake ends with where its PM runs and+ * how much of its week is left, so it spends its own quota knowing it. Names only, from the machine's last reading; a reading+ * the Swarm does not have leaves the line out rather than guessing it.+ */+import { weeklyUse } from './leaderboard/brought.js'+import type { Agent, MessageDraft, SuperTabState } from './model.js'+import { until } from './othersWork.js'+import { usernameOf } from './usernames.js'++/** The messages the Swarm's built-in schedule wakes the coordinator with: the schedule, the update request, the morning+ * digest, the notice digest, and the lost, stalled and idle notices. */+const WAKE_KINDS = new Set(['schedule-request', 'update-request', 'digest-request', 'notice-digest', 'work-lost', 'work-stalled', 'idle'])+const MARK = 'You run on '++/** "You run on <machine>, <account>: weekly X% left, resets in <time>." for [pm]'s machine and account, null when the+ * machine, the account's name or its weekly reading is unknown. A PM on another account (profileId) is named by that+ * account's label, with that account's own reading, never the machine's default one. A Harness Team account is named as+ * that, with its Mac's name and the Mac's reading; the default account is its owner's username's, never an email. */+export function pmFooting(state: SuperTabState, pm: Agent, now: number): string | null {+ const pool = state.machines?.find(m => m.machineId === pm.machineId)+ if (!pool) return null+ const home = (pool.hostMachineId && state.machines?.find(m => m.machineId === pool.hostMachineId)) || pool+ const engine = pm.configuration.engine+ let account: string | undefined, usedPercent: number | null, resetsAt: number | null+ if (pm.profileId) {+ const profile = (pool.observation?.profiles ?? []).find(p => p.engine === engine && p.id === pm.profileId)+ if (!profile || profile.leftPercent == null) return null+ account = profile.label+ usedPercent = 100 - profile.leftPercent+ resetsAt = profile.resetsAt ? Date.parse(profile.resetsAt) : null+ if (resetsAt != null && Number.isNaN(resetsAt)) resetsAt = null+ } else {+ const owner = usernameOf(state, pool.contributorId)+ account = pool.hostMachineId ? 'the Harness Team account' : owner && `${owner}'s own account`+ ;({ usedPercent, resetsAt } = weeklyUse(home, engine))+ }+ if (!account || usedPercent == null || !Number.isFinite(usedPercent)) return null+ const left = Math.min(100, Math.max(0, Math.round(100 - usedPercent)))+ return `${MARK}${home.name}, ${account}: weekly ${left}% left${resetsAt == null ? '' : `, resets in ${until(resetsAt, now)}`}.`+}++/** Ends each built-in wake in [drafts] that goes to [pm] with its footing line, once; the other messages and a wake that+ * already has it stay as they are. */+export function addFooting(state: SuperTabState, pm: Agent, drafts: readonly MessageDraft[], now: number): void {+ const wakes = drafts.filter(d => WAKE_KINDS.has(String(d.source?.kind)) && d.recipients?.includes(pm.id) && !d.text.includes(MARK))+ const line = wakes.length ? pmFooting(state, pm, now) : null+ if (line) for (const draft of wakes) draft.text = `${draft.text}\n\n${line}`+}diff --git a/backend/src/superTabs/pmSchedule.test.ts b/backend/src/superTabs/pmSchedule.test.tsindex 41dc1cf7a..76ceaff52 100644--- a/backend/src/superTabs/pmSchedule.test.ts+++ b/backend/src/superTabs/pmSchedule.test.ts@@ -226,6 +226,30 @@ describe('the built-in wake\'s jobs for what people teach the coordinator', () =expect(wake(state, T + 2 * SCHEDULE_SLOT_MS)).toBeNull()})+ // Ken, 11-05: lamp-gtm's PM saved dee's "start what dee asks at once, on the PM's account if needed" (revision 14) beside+ // the older routing line that keeps the PM's own account for the PM, left both, and then asked dee three options.+ it('tells the coordinator to fix a contradicted line in the same save, and to settle a conflict without asking', () => {+ const text = PM_SCHEDULE_TEXT.replace(/\s+/g, ' ')+ expect(text).toContain('fix every line it contradicts in that same save')+ // Review of #3134: replacing a line drops another person's rule, which the tidy keeps.+ expect(text).toContain('replace a line only when it names no one or the same person gave both')+ expect(text).toContain('When two rules still disagree, don\'t ask; settle it by the first that applies')+ // A rule that says to ask a person (spending money, say) is never overridden by this order.+ expect(text).toContain('a rule that says to ask a person still holds')+ expect(text).toContain('an account owner\'s rule beats a default about their account; the newer beats the older')+ expect(text).toContain('say what you changed')+ })++ // Ken, 11-05: a project's own instructions guard only its own PM's account, and a copy made before this rule has none.+ it('tells the coordinator an account any project\'s PM runs on keeps that PM running for its week', () => {+ const text = PM_SCHEDULE_TEXT.replace(/\s+/g, ' ')+ expect(text).toContain('Never ask anyone about quota or whose account to use: pick by Routing and go.')+ expect(text).toContain('An account the route notes as running a PM, yours or another project\'s, takes no new work while it has less than 20% of its weekly quota left')+ // Review of #3134: a project copied before this keeps an older line about its own PM's account; this one still holds.+ expect(text).toContain('even where an older Routing line in your instructions says otherwise')+ expect(text).not.toContain('except work that account\'s owner asks for')+ })+it('says in the built-in section when the Swarm wakes it for them', () => {expect(PM_SCHEDULE_TEXT).toContain('when a person wrote to you since the last wake')expect(PM_SCHEDULE_TEXT).toContain('Once a day, when the instructions changed')diff --git a/backend/src/superTabs/pmSchedule.ts b/backend/src/superTabs/pmSchedule.tsindex c3b8a26fe..e663634fa 100644--- a/backend/src/superTabs/pmSchedule.ts+++ b/backend/src/superTabs/pmSchedule.ts@@ -44,6 +44,10 @@ How you work:- Hand long reading (a pull request's diff, CI logs, a long thread, production numbers) to a subagent that runs in thebackground when your tool has them, and take back only its summary: your own context stays small, so these instructionsstay in it. A subagent never writes code and never decides; you do.+- Never ask anyone about quota or whose account to use: pick by Routing and go. An account the route notes as running a+ PM, yours or another project's, takes no new work while it has less than 20% of its weekly quota left, even where an older+ Routing line in your instructions says otherwise; every other account is used without asking. When no account fits,+ the work waits for the soonest reset, and the task says so.- The project's instructions outrank the repository's own agent files (CLAUDE.md, AGENTS.md). When they conflict, followthe instructions and say so.@@ -52,6 +56,11 @@ What people teach you:- When a person corrects you or gives a lasting rule ("from now on", "always", "don't", "I told you", "again you forgot","remember"), save it into the instructions in that same turn, before you answer, naming who said it. Don't ask whether tosave it. Then answer, and work by it from then on.+- When you save a rule, fix every line it contradicts in that same save, so the instructions never say two things: add+ the exception, and replace a line only when it names no one or the same person gave both. When two rules still+ disagree, don't ask; settle it by the first that applies: a rule that says to ask a person still holds; the rule written+ for this case beats the general one; an account owner's rule beats a default about their account; the newer beats the+ older. Act on it, then fix the instructions in that same turn and say what you changed.- Save each rule once, where it belongs, in as few words as it takes. When a save takes the instructions past 150 lines,merge duplicate lines and drop stale ones in that same save.- A person telling you again something they already taught you is a repeat: fix what you did against it, and save it onlydiff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 11c835f1f..6a0cf3c04 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -73,6 +73,8 @@ export interface Derived {lead?: Record<string, { machineId: string } | { refused: string }> }>/** A Lead agent only. */otherProjectsWork?: OtherProjectWorkView[]+ /** A project agent only: the account each project's PM runs on, a project it may not read named "another project". */+ pmAccounts?: Array<{ machineId: string; hostMachineId?: string; engine: string; project: string; pm: string }>/** The Swarm's owner only: projects nobody owns, which they may delete but never read (projects.ts ownerlessProjects). */ownerlessProjects?: Array<{ id: string; name: string; conversations: number }>/** A person only. */diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 6682dcbb8..c7a526feb 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -151,6 +151,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:roleName: roleNameOf(state, state.agents.find(a => a.id === seen.id)!) }])),machines: Object.fromEntries((visible.machines ?? []).map(machine)),...(visible.otherProjectsWork ? { otherProjectsWork: visible.otherProjectsWork } : {}),+ ...(visible.pmAccounts ? { pmAccounts: visible.pmAccounts } : {}),...(visible.ownerlessProjects ? { ownerlessProjects: visible.ownerlessProjects } : {}),...(actor.kind === 'person' && extras.mentionsWaiting !== undefined ? { mentionsWaiting: extras.mentionsWaiting } : {}),...(actor.kind === 'person' && extras.mentionsDigest !== undefined ? { mentionsDigest: extras.mentionsDigest } : {}),diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 1614278dc..297d63385 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -89,6 +89,7 @@ import { QUIET_CLAIM, type HoldReason } from './holdReason.js'import { stuck } from './deliverySettle.js'import { digestIsDue, digestMessage, digestText, doneRow, endedAlert, GATHERED_LIMIT_MS, gatheredNotice, NOTICE_DIGEST_MAX, noticeLine } from './noticeDigest.js'import { PM_SCHEDULE_TEXT, recordWake, scheduleRequest } from './pmSchedule.js'+import { addFooting } from './pmFooting.js'import { agentDisplayName } from './agentNames.js'import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'import { accrueLent, addLent, lentAgents, lentProjects } from './leaderboard/lent.js'@@ -3969,6 +3970,8 @@ export class SuperTabStore {await this.releaseRuns(tx, tabId, await this.staleRuns(tx, tabId, state))}// One write for all: the time checks' changes, the digest and the wake-ups'.+ // Every built-in wake ends with where its PM runs and its week's quota (pmFooting.ts), once the wakes are merged.+ addFooting(state, target, written, this.now())const sequences = numberMessages(state, written, this.now())// A loss or a start's failure was judged from a machine's report: a newer report makes this write retry.await this.save(tx, loaded, state, clock.next(), [...judgedMachines(loaded.state, state, written),diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex 3f9384b90..07c1ebdc4 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -148,9 +148,11 @@ describe('built-in Swarm skills', () => {+ '- When the project\'s instructions name an agent or a person for a job (an order, a queue, a device, a release), you do not do that job yourself, even when it is urgent. Message that owner with the priority or the change you want, and wait for them.\n'+ '- An urgent case means telling the owner first, at once and with the reason; it never means taking over.\n'+ '- Setting priorities is not doing the owner\'s job: ask for the order you want, and never reorder, stop or restart their work yourself.\n\n'- // The quota section (Dee, 2026-11-05; task #3180): the Lead's alone, in both modes, right after the named-owner section.- const quota = '## Spending a person\'s quota\n'- + '- You may spend a requester\'s own account quota on that person\'s own task without asking, as long as that account has more than 10% of its week left. Below 10%, ask the person, with your recommendation.\n\n'+ // The quota section (Ken and Dee, 2026-11-05; replaces #3180's 10% ask): the Lead's alone, in both modes, right after the+ // named-owner section. Never ask about quota; only an account a PM runs on stops taking work, below 20% of its weekly quota.+ const quota = '## Quota\n'+ + '- Never ask anyone about quota or whose account to use: pick by your project\'s Routing and go. When no account fits, the work waits for the soonest reset, and the task says so.\n'+ + '- An account any project\'s PM runs on (the route notes it) takes no new work while it has less than 20% of its weekly quota left. Every other account is used without asking.\n\n'// Last in the Default Lead text, which has no red flags: after a blank line, ending the text.const requestsLast = `\n${requests.trimEnd()}\n`// The shared-machine rules (Ken, 2026-10-28): the Builder's and the Reviewer's alone, in both modes, in a section of their@@ -451,12 +453,14 @@ describe('built-in Swarm skills', () => {}}})- it('lets each Lead, and no other role, spend a requester\'s own quota on their task above 10% of the week, and ask below it', () => {+ // Dee, 11-05: asking a person about quota is bad UX ("why restrict, why ask"); Ken kept one line: a PM's account below 20%.+ it('tells each Lead, and no other role, never to ask about quota, and to keep an account a PM runs on below 20% free of new work', () => {for (const mode of ['orchestration', 'default'] as const) {const lead = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode }).file, 'utf8')- for (const part of ['## Spending a person\'s quota', 'a requester\'s own account quota on that person\'s own task without asking', 'more than 10% of its week left', 'Below 10%, ask the person, with your recommendation']) expect(lead).toContain(part)+ for (const part of ['## Quota', 'Never ask anyone about quota or whose account to use', 'less than 20% of its weekly quota left', 'Every other account is used without asking']) expect(lead).toContain(part)+ for (const gone of ['10% of its week', 'ask the person, with your recommendation', '## Spending a person']) expect(lead).not.toContain(gone)for (const role of ['dev', 'review', 'buddy'] as const) {- expect(readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')).not.toContain('## Spending a person')+ expect(readFileSync(prepareSwarmSkill(fixture(), { role, key: 'session', mode }).file, 'utf8')).not.toContain('## Quota')}}})diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex b4aac10dd..8f6aa6c22 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -181,8 +181,9 @@ For large work, post the group plan and get the owner's ok before assigning; onc- An urgent case means telling the owner first, at once and with the reason; it never means taking over.- Setting priorities is not doing the owner's job: ask for the order you want, and never reorder, stop or restart their work yourself.-## Spending a person's quota-- You may spend a requester's own account quota on that person's own task without asking, as long as that account has more than 10% of its week left. Below 10%, ask the person, with your recommendation.+## Quota+- Never ask anyone about quota or whose account to use: pick by your project's Routing and go. When no account fits, the work waits for the soonest reset, and the task says so.+- An account any project's PM runs on (the route notes it) takes no new work while it has less than 20% of its weekly quota left. Every other account is used without asking.## Requests and Done- When you open a group for a person's request, asked in the project chat or proposed by their Buddy on their behalf, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote. Name the message it came from as well: proposalMessageId for their Buddy's proposal, requestMessageId for their own message in the project chat. That message stays the task's one message in the chat; without one, the Swarm posts the title as them, marked as a task. The Swarm replies in its thread at each change, so you post no progress there.@@ -519,8 +520,9 @@ When the project owner asks in chat to switch this project's skills (Default or- An urgent case means telling the owner first, at once and with the reason; it never means taking over.- Setting priorities is not doing the owner's job: ask for the order you want, and never reorder, stop or restart their work yourself.-## Spending a person's quota-- You may spend a requester's own account quota on that person's own task without asking, as long as that account has more than 10% of its week left. Below 10%, ask the person, with your recommendation.+## Quota+- Never ask anyone about quota or whose account to use: pick by your project's Routing and go. When no account fits, the work waits for the soonest reset, and the task says so.+- An account any project's PM runs on (the route notes it) takes no new work while it has less than 20% of its weekly quota left. Every other account is used without asking.## Requests and Done- When you open a group for a person's request, asked in the project chat or proposed by their Buddy on their behalf, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote. Name the message it came from as well: proposalMessageId for their Buddy's proposal, requestMessageId for their own message in the project chat. That message stays the task's one message in the chat; without one, the Swarm posts the title as them, marked as a task. The Swarm replies in its thread at each change, so you post no progress there.diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.tsindex 9b8b06635..32aa74fed 100644--- a/cli/src/lib/swarmTools.ts+++ b/cli/src/lib/swarmTools.ts@@ -93,7 +93,7 @@ Swarm and machine settings (each refused unless you may change that setting; a p- \`local\` only when a person asked for a local model. When a person names a model, set \`model\` to their words ("deepseek 4.1 flash"): the route then offers that model alone, unrated when the catalog does not list it.- It leaves out what cannot run (a machine offline, paused or full, an engine signed out or suspended, tools or devices the work needs, a machine that cannot take a teammate's project), and says why.- ${CHEAP_FIRST_HELP}- - It ranks nothing and names no pick: the rest come by machine name, then engine, each with its facts (model, effort, the catalog's strength and price, quota fit with weekly % left and reset time, the agents on its machine, idle or new). What else it knows is a note on the candidate: a used-up quota, a lost task, a machine whose last starts failed, a task requirement naming another machine, a model not offered by default, a plug-in's finding. The first row is first by its machine's name, not by merit: choose by your project's Routing instructions.+ - It ranks nothing and names no pick: the rest come by machine name, then engine, each with its facts (model, effort, the catalog's strength and price, quota fit with weekly % left and reset time, the agents on its machine, idle or new). What else it knows is a note on the candidate: a used-up quota, a lost task, a machine whose last starts failed, a task requirement naming another machine, a model not offered by default, an account a project's PM runs on (which PM), a plug-in's finding. The first row is first by its machine's name, not by merit: choose by your project's Routing instructions.- A candidate on a model served on the Swarm's grid starts with the \`gridModel\` and \`gridName\` its row gives, in place of model and effort.- Start or assign the candidate you chose with the decision's \`routeDecisionId\` and \`overrideReason\`: the Routing rule that chose it, in one sentence. The decision records the candidate the start or assignment matches.- \`plan [JSON]\` places all open groups at once on machines and models (needs Python 3 and OR-Tools; without them it says how to install). JSON optional: \`{"groups":{"GROUP":{"difficulty":"...","risk":"...","size":"...","kind":"optional","after":["GROUP"]}}}\`. It records nothing: route each group, then start the plan's pick with the route's \`routeDecisionId\`.diff --git a/cli/src/superTabs/pmAccounts.spec.ts b/cli/src/superTabs/pmAccounts.spec.tsnew file mode 100644index 000000000..11a05ea00--- /dev/null+++ b/cli/src/superTabs/pmAccounts.spec.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'+import { PM_ACCOUNT_NOTE, withPmAccounts } from './pmAccounts.js'+import type { Probe } from './route.js'++const probe = (patch: Partial<Probe> = {}): Probe => ({ kind: 'new', machineId: 'studio', machineName: 'Studio', engine: 'claude', model: 'opus',+ effort: 'high', quality: 3, cost: 3, quota: { known: true, leftPercent: 17, resetsAt: 1_000 }, activity: 'new', known: true, refusals: [], notes: [], ...patch })++/** What the backend sends an agent of openharness: its own PM, and lamp's (a project it may read) on the same Studio. */+const read = (over: Record<string, unknown> = {}) => ({+ pmAccounts: [{ machineId: 'studio', engine: 'claude', project: 'openharness', pm: 'River' }, { machineId: 'studio', engine: 'claude', project: 'lamp', pm: 'Faye' }],+ machines: [{ machineId: 'studio' }, { machineId: 'studio-team', hostMachineId: 'studio' }, { machineId: 'gray' }],+ ...over,+})+const both = PM_ACCOUNT_NOTE(['openharness (River)', 'lamp (Faye)'])++// Ken, 11-05: a PM started work on a machine and account another project's PM ran on, and could drain it until that PM+// stopped; the route said nothing about whose PM an account keeps alive.+describe('withPmAccounts', () => {+ it('notes every candidate on an account a PM runs on, naming each project and its PM', () => {+ const [onStudio, codex, elsewhere] = withPmAccounts(read(), [probe(), probe({ engine: 'codex' }), probe({ machineId: 'gray', machineName: 'Gray' })])+ expect(onStudio!.notes).toEqual([both])+ expect(PM_ACCOUNT_NOTE(['lamp (Faye)'])).toBe('This account runs the PM of lamp (Faye).')+ expect(codex!.notes).toEqual([])+ expect(elsewhere!.notes).toEqual([])+ })++ // As in production: a pool machine's probe names no subscription (machineId:engine), and a Team account's names its Mac+ // only while the relayed reading is fresh (review of #3134).+ it('counts a Mac\'s Harness Team account as the Mac\'s account, fresh relay or not', () => {+ const stale = probe({ machineId: 'studio-team' })+ const fresh = probe({ machineId: 'studio-team', quota: { known: true, leftPercent: 17, resetsAt: 1_000, account: 'studio:claude' } })+ expect(withPmAccounts(read(), [stale, fresh]).map(p => p.notes)).toEqual([[both], [both]])+ // A PM on the Team account, as the backend names it: its Mac.+ const onTeam = read({ pmAccounts: [{ machineId: 'studio-team', hostMachineId: 'studio', engine: 'claude', project: 'lamp', pm: 'Faye' }] })+ expect(withPmAccounts(onTeam, [probe()])[0]!.notes).toEqual([PM_ACCOUNT_NOTE(['lamp (Faye)'])])+ })++ it('follows the subscription a reading on the PM\'s Mac names to another machine signed in to it', () => {+ const own = probe({ quota: { known: true, leftPercent: 17, resetsAt: 1_000, account: 'sub-1' } })+ const sameSubscription = probe({ machineId: 'gray', quota: { known: true, leftPercent: 17, resetsAt: 1_000, account: 'sub-1' } })+ const other = probe({ machineId: 'gray', quota: { known: true, leftPercent: 80, resetsAt: 1_000, account: 'sub-2' } })+ expect(withPmAccounts(read(), [own, sameSubscription, other]).map(p => p.notes.length)).toEqual([1, 1, 0])+ })++ it('names a project the reader may not read as the backend sends it, and fills a missing name', () => {+ const hidden = read({ pmAccounts: [{ machineId: 'studio', engine: 'claude', project: 'another project', pm: 'its PM' }, { machineId: 'studio', engine: 'claude' }] })+ expect(withPmAccounts(hidden, [probe()])[0]!.notes).toEqual([PM_ACCOUNT_NOTE(['another project (its PM)'])])+ })++ it('leaves grid models and accounts with no machine or engine alone, and keeps a probe\'s own notes', () => {+ expect(withPmAccounts(read(), [probe({ gridModel: 'kimi', gridName: 'kimi' })])[0]!.notes).toEqual([])+ expect(withPmAccounts(read(), [probe({ notes: ['Its screen showed a usage limit.'] })])[0]!.notes).toEqual(['Its screen showed a usage limit.', both])+ expect(withPmAccounts(read({ pmAccounts: [{ machineId: 'studio' }, { engine: 'claude' }, 'x'] }), [probe()])[0]!.notes).toEqual([])+ })++ it('falls back, with a backend from before pmAccounts, to the PMs of the projects the reader sees', () => {+ const older = { projects: [{ id: 'p1', name: 'openharness', leadConversationId: 'lead-p1' }], conversations: [{ id: 'lead-p1', leadId: 'river' }],+ agents: [{ id: 'river', name: 'Lead', displayName: 'River', machineId: 'studio', configuration: { engine: 'claude' } }] }+ expect(withPmAccounts(older, [probe()])[0]!.notes).toEqual([PM_ACCOUNT_NOTE(['openharness (River)'])])+ // A project and a PM with no name read by their ids; a Swarm from before projects has its Lead conversation, `lead`.+ const bare = { projects: [{ id: 'p9', leadConversationId: 'lead-p9' }], conversations: [{ id: 'lead-p9', leadId: 'x' }],+ agents: [{ id: 'x', machineId: 'studio', configuration: { engine: 'claude' } }] }+ expect(withPmAccounts(bare, [probe()])[0]!.notes).toEqual([PM_ACCOUNT_NOTE(['p9 (x)'])])+ const legacy = { name: 'My Swarm', conversations: [{ id: 'lead', leadId: 'x' }], agents: [{ id: 'x', name: 'Lead', machineId: 'studio', configuration: { engine: 'claude' } }] }+ expect(withPmAccounts(legacy, [probe()])[0]!.notes).toEqual([PM_ACCOUNT_NOTE(['My Swarm (Lead)'])])+ expect(withPmAccounts({ conversations: [{ id: 'lead' }], agents: null }, [probe()])[0]!.notes).toEqual([])+ })+})diff --git a/cli/src/superTabs/pmAccounts.ts b/cli/src/superTabs/pmAccounts.tsnew file mode 100644index 000000000..4fc05233b--- /dev/null+++ b/cli/src/superTabs/pmAccounts.ts@@ -0,0 +1,53 @@+/**+ * Which route candidates spend the account a project's PM runs on, any project's in the Swarm (Ken, 11-05). A PM routed work+ * onto a machine and account another project's PM ran on, and could drain it until that PM stopped mid-week. The note is a+ * fact on the candidate; the project's Routing says what it means (below 20% of its weekly quota, no new work there).+ *+ * The route reads the Swarm as one project's agent, which sees no other project, so the backend sends every project's PM+ * account in the read (`pmAccounts`, backend superTabs/model.ts), naming a project the reader may not read only as+ * "another project" (review of #3134). A backend from before it sends none: the route then knows its own project's PM.+ */+import { accountOf, type Probe } from './route.js'++type Json = Record<string, unknown>+const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}+const list = (value: unknown): Json[] => Array.isArray(value) ? value.map(object) : []+const text = (value: unknown): string | undefined => typeof value === 'string' && value ? value : undefined++export const PM_ACCOUNT_NOTE = (pms: string[]) => `This account runs the PM of ${pms.join(' and ')}.`++/** The PM accounts the read carries, or, from an older backend, those of the projects the reader sees (a Swarm from before+ * projects has one, its Lead conversation `lead`). */+function accountsOf(state: Json): Json[] {+ if (Array.isArray(state.pmAccounts)) return list(state.pmAccounts)+ const conversations = list(state.conversations), agents = list(state.agents)+ const projects = Array.isArray(state.projects) ? list(state.projects) : [{ id: 'lead', name: state.name, leadConversationId: 'lead' }]+ return projects.flatMap(project => {+ const pm = agents.find(a => a.id === conversations.find(c => c.id === project.leadConversationId)?.leadId)+ return pm ? [{ machineId: pm.machineId, engine: object(pm.configuration).engine, project: text(project.name) ?? text(project.id),+ pm: text(pm.displayName) ?? text(pm.name) ?? pm.id }] : []+ })+}++/** [probes] with PM_ACCOUNT_NOTE on each one that spends an account a project's PM runs on. A Mac and its Harness Team account+ * spend one subscription, so an account is the Mac and the engine; and the subscription a reading on that Mac names+ * (route.ts accountOf), wherever else it is signed in. Grid models spend no subscription. */+export function withPmAccounts(state: Json, probes: Probe[]): Probe[] {+ const macOf = new Map(list(state.machines).filter(m => text(m.hostMachineId)).map(m => [String(m.machineId), String(m.hostMachineId)]))+ const mac = (machineId: string) => macOf.get(machineId) ?? machineId+ const pms = new Map<string, Set<string>>()+ const add = (key: string, name: string) => pms.set(key, (pms.get(key) ?? new Set()).add(name))+ for (const account of accountsOf(state)) {+ const machineId = text(account.machineId), engine = text(account.engine)+ if (!machineId || !engine) continue+ const name = `${text(account.project) ?? 'another project'} (${text(account.pm) ?? 'its PM'})`+ const home = text(account.hostMachineId) ?? mac(machineId)+ add(`${home}:${engine}`, name)+ for (const p of probes) if (!p.gridModel && p.engine === engine && mac(p.machineId) === home) add(accountOf(p), name)+ }+ return probes.map(p => {+ if (p.gridModel) return p+ const runs = new Set([...pms.get(`${mac(p.machineId)}:${p.engine}`) ?? [], ...pms.get(accountOf(p)) ?? []])+ return runs.size ? { ...p, notes: [...p.notes, PM_ACCOUNT_NOTE([...runs])] } : p+ })+}diff --git a/cli/src/superTabs/readContract.ts b/cli/src/superTabs/readContract.tsindex 0bbe6abbd..e086f8391 100644--- a/cli/src/superTabs/readContract.ts+++ b/cli/src/superTabs/readContract.ts@@ -33,6 +33,8 @@ export interface Derived {machines: Record<string, Json>/** A Lead agent only. */otherProjectsWork?: Json[]+ /** A project agent only: the account each project's PM runs on (backend superTabs/model.ts pmAccounts). */+ pmAccounts?: Json[]/** A person only. */mentionsWaiting?: number/** A person only: a digest of which of their tags wait, moving when one is made, answered or expires. */diff --git a/cli/src/superTabs/reassemble.spec.ts b/cli/src/superTabs/reassemble.spec.tsindex 8e48b81d6..193443c57 100644--- a/cli/src/superTabs/reassemble.spec.ts+++ b/cli/src/superTabs/reassemble.spec.ts@@ -67,4 +67,13 @@ describe('the old Swarm state, rebuilt from parts', () => {expect(state.mentionsWaiting).toBe(2)expect(state).not.toHaveProperty('projects')})++ // Ken, 11-05: the route reads every project's PM account from the derived summary (pmAccounts.ts).+ it('carries the PM accounts a project agent\'s read sends, and none when it sends none', () => {+ const first = readFixture<FirstLoad>('parts-builder')+ expect(reassemble(storeOf(first))).not.toHaveProperty('pmAccounts')+ const accounts = [{ machineId: 'm1', engine: 'claude', project: 'another project', pm: 'its PM' }]+ first.derived.pmAccounts = accounts+ expect(reassemble(storeOf(first)).pmAccounts).toEqual(accounts)+ })})diff --git a/cli/src/superTabs/reassemble.ts b/cli/src/superTabs/reassemble.tsindex b6da716fb..3598bf668 100644--- a/cli/src/superTabs/reassemble.ts+++ b/cli/src/superTabs/reassemble.ts@@ -61,6 +61,8 @@ export function reassemble(store: PartsStore): Json {})}if (derived.otherProjectsWork !== undefined) state.otherProjectsWork = derived.otherProjectsWork+ // Every project's PM account, for the route's notes (pmAccounts.ts).+ if (derived.pmAccounts !== undefined) state.pmAccounts = derived.pmAccountsif (derived.mentionsWaiting !== undefined) state.mentionsWaiting = derived.mentionsWaitingif (derived.mentionsDigest !== undefined) state.mentionsDigest = derived.mentionsDigestreturn statediff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 6608bbc1e..6b3c0e84b 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -3,6 +3,7 @@ import type { openDaemon } from '../agentClient/daemon.js'import { mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { PM_ACCOUNT_NOTE } from './pmAccounts.js'import { ELSEWHERE, heldByStarts, heldLocalModels, leftOut, localProbes, NO_SWARM_AGENTS_ON, offlineModels, routeTask, servedModels, STALL_RETRY_MS, stalled } from './routeCommand.js'import type { describeScmProject } from '../scm/scmProjects.js'import { admission, quotaOf, RELAYED_QUOTA, USED_UP_WINDOW } from './capacity.js'@@ -242,6 +243,18 @@ describe('routeTask', () => {expect(request.heavy).toEqual(['build'])expect(placedHeavyWork([{ request, requestedAt: Date.now() }], Date.now()).get('m1')).toMatchObject({ agents: 1, memoryBytes: 8e9 })})+ // Ken, 11-05: a PM put work on the account another project's PM ran on; the row now says whose PM it keeps running.+ it('notes on each candidate whose account a project\'s PM runs on which project and PM that is', async () => {+ const project = { id: 'p1', name: 'openharness', leadConversationId: 'lead' }+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents, conversations: conversations(), projects: [project] } },+ policy: { policy, warnings: [] }, machines: [] } } })+ const answer = await routeTask(input, s, where as never, opener(), () => 'op') as { candidates: Array<{ machineId: string; engine?: string; title: string; notes?: string[] }> }+ const onPm = answer.candidates.filter(c => c.machineId === 'm1' && c.title.includes('Claude'))+ expect(onPm.length).toBeGreaterThan(0)+ for (const row of onPm) expect(row.notes).toContain(PM_ACCOUNT_NOTE(['openharness (Lead)']))+ expect(answer.candidates.filter(c => !(c.machineId === 'm1' && c.title.includes('Claude'))).every(c => !(c.notes ?? []).some(n => n.startsWith('This account runs the PM')))).toBe(true)+ })+it('does not offer a member whose task is working', async () => {const state = tab({ id: 'x', agentId: 'a1', status: 'working' })const s = scoped({ tab: state })@@ -312,7 +325,8 @@ describe('routeTask', () => {const { result, candidates } = await route([...marked, healthy],[earlier({ id: 'y', agentId: 'a3', status: 'working' }, { lostAttempt: { id: 'x', agentId: 'a1' } })])expect(lineOf(candidates, 'Multiply')).toContain(note)- expect(result).toMatchObject({ ok: true, candidates: expect.arrayContaining([expect.objectContaining({ kind: 'member', agentId: 'a1', notes: [note] })]) })+ // a1 shares the Lead's account (m1, Claude), so the PM-account note sits beside it (pmAccounts.ts).+ expect(result).toMatchObject({ ok: true, candidates: expect.arrayContaining([expect.objectContaining({ kind: 'member', agentId: 'a1', notes: [note, PM_ACCOUNT_NOTE(['lead (Lead)'])] })]) })})it('carries no note once it finished a new task, which clears its mark', async () => {const { candidates } = await route([...agents, healthy],diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 5c3164b5f..386ab0f59 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -9,6 +9,7 @@ import { RELAYED_QUOTA, requiredToolReason, startRequirements, USED_UP_WINDOW }import { START_DEADLINE_MS, START_WINDOW_MS } from './reservations.js'import { inspectCapacity, type ScopedRequest } from './start.js'import { ENDED_WORK, object, within } from './wire.js'+import { withPmAccounts } from './pmAccounts.js'import { accountOf, API_BUILDERS, bytes, machineBrief, catalogFrom, catalogRow, choose, decide, gridStrength, parseAssessment, OLD_RECORD_MAX, quotaBrief, quotaOf2, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type Shown, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'import { makePlugins, ROUTE_PLUGIN_MAKERS, type PluginMaker } from './routePlugins.js'import { CI_HOLD_OPENING, CI_RETRY_MINUTES, heavyOfStart, MACHINE_FIT_MAKER } from './machineFit.js'@@ -490,6 +491,8 @@ export async function routeTask(input: { tabId: string; conversationId: string;...(avoid.has(accountOf(p)) ? [AVOIDED] : [])]if (notes.length) probes[i] = { ...p, notes: [...p.notes, ...notes] }}+ // Whose PM an account keeps running, any project's (pmAccounts.ts): the project's Routing guards that PM's week.+ probes.splice(0, probes.length, ...withPmAccounts(state, probes))// Picks started or assigned and still at work hold part of their account's quota; the log, and so this, is per Swarm.const working = (decisions ?? []).filter(d => d.final && d.outcome === null && typeof d.account === 'string').map(d => ({ account: d.account, spend: object(d.spend), size: d.size, createdAt: Date.parse(String(d.createdAt)) }) as Commitment)diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 723124fa2..ad0d076fc 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -172,7 +172,8 @@ const POOLS_FRESH_MS = 5_000* any other agent reads none of it. Nobody reads the Leads conversation, removed on 10-31, even from an older server* that still sends it. */function statusView(answer: Record<string, unknown>, agentId: string): Record<string, unknown> {- const { otherProjectsWork, leadsConversationId, ...state } = object(answer.state)+ // The PM accounts are the route's (pmAccounts.ts), not a roster line.+ const { otherProjectsWork, leadsConversationId, pmAccounts: _pmAccounts, ...state } = object(answer.state)const shown = list(state.conversations).filter(c => c.kind !== 'leads' && (leadsConversationId == null || c.id !== leadsConversationId))// A task's steps are printed under it, not as rows of their own (task steps design); one whose task is not here stays a row.const ids = new Set(shown.map(c => c.id))diff --git a/cli/vitest.super-tabs.config.ts b/cli/vitest.super-tabs.config.tsindex 5ea365918..5ccd8e73d 100644--- a/cli/vitest.super-tabs.config.ts+++ b/cli/vitest.super-tabs.config.ts@@ -9,6 +9,8 @@ const IN_CORE = ['adoption', 'agents', 'attention', 'cards', 'deliveries', 'launconst FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts', 'src/superTabs/routePlugins.ts', 'src/superTabs/shortCommand.ts', ...IN_CORE,// The routing plug-ins (routePlugins.ts), one line each.'src/superTabs/routeCheapFirst.ts', 'src/superTabs/routeMeasured.ts', 'src/superTabs/windowPull.ts', 'src/superTabs/machineFit.ts',+ // Whose PM an account runs (Ken, 11-05).+ 'src/superTabs/pmAccounts.ts',]export default defineConfig({test: {diff --git a/desktop/lib/super_tabs/chat_scroll.dart b/desktop/lib/super_tabs/chat_scroll.dartindex 8b5cc5303..0293c4efc 100644--- a/desktop/lib/super_tabs/chat_scroll.dart+++ b/desktop/lib/super_tabs/chat_scroll.dart@@ -22,6 +22,7 @@ class SuperTabChatScroll extends ScrollController {ScrollPosition? oldPosition,) => _AnchoredPosition(rows: rows,+ holdsEnd: () => _holdingFor != null,physics: physics,context: context,initialPixels: initialScrollOffset,@@ -37,11 +38,35 @@ class SuperTabChatScroll extends ScrollController {if (position is _AnchoredPosition) position._moveContent(by);}}++ /// The list was rebuilt around a new dividing row: the view starts at it+ /// and keeps nothing of where it was. Set before the list is laid out, so+ /// no row between the old place and the new one is laid out on the way.+ void restart() {+ for (final position in positions) {+ if (position is _AnchoredPosition) position._restart();+ }+ }++ /// A jump to the end, named by [jump], is under way: a view left past the+ /// end, as an end estimated from rows not yet laid out leaves it, is put+ /// at the end before anything is painted. Without it a Mac's bouncing+ /// scroll shows no row until the view springs back (Huy, #3049). Null+ /// ends any jump, as the reader taking the list does.+ void holdEnd(int? jump) => _holdingFor = jump;++ /// Ends the hold of [jump], unless a later jump holds the end now.+ void releaseEnd(int jump) {+ if (_holdingFor == jump) _holdingFor = null;+ }++ int? _holdingFor;}class _AnchoredPosition extends ScrollPositionWithSingleContext {_AnchoredPosition({required this.rows,+ required this.holdsEnd,required super.physics,required super.context,super.initialPixels,@@ -57,6 +82,10 @@ class _AnchoredPosition extends ScrollPositionWithSingleContext {// Where the last finished layout left the view.double? _settledPixels, _settledMax;+ /// Whether a jump to the end is under way ([SuperTabChatScroll.holdEnd]):+ /// asked of the controller, which may be told before this is attached.+ final bool Function() holdsEnd;+bool get _wasAtEnd =>_settledPixels != null && _settledPixels! >= _settledMax! - .5;@@ -94,8 +123,22 @@ class _AnchoredPosition extends ScrollPositionWithSingleContext {if (_settledMax != null) _settledMax = _settledMax! + by;}+ void _restart() {+ goIdle();+ correctPixels(0);+ _anchor = null;+ _settledPixels = _settledMax = null;+ }+@overridebool applyContentDimensions(double minScrollExtent, double maxScrollExtent) {+ if (holdsEnd() && pixels > maxScrollExtent + .5) {+ // Past the end only because the end was estimated: laid out there,+ // the list knows its end exactly.+ goIdle();+ correctPixels(maxScrollExtent);+ return false;+ }// Nothing the chat does leaves the view past the end of the list: the// newest row shrinking under a kept place, or a jump to a row, would show// blank under it until a Mac's bouncing scroll sprang back, every fewdiff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 3e7769d47..0c4d10429 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -246,6 +246,9 @@ class _SuperTabViewState extends State<SuperTabView>final _anchors = <String, ({String messageId, double top})>{};// Each list's dividing row: see [_splitAt].final _split = <String, SuperTabMessage>{};+ // Each list's rebuilds around a new dividing row ([_restartAtEnd]): its+ // rows' slivers are keyed by it, so a restart lays out no old row.+ final _restarts = <String, int>{};final _newerRows = UniqueKey();// The composer's completions are drawn by builders of their own, so typing// and choosing among them never rebuild the transcript.@@ -446,6 +449,7 @@ class _SuperTabViewState extends State<SuperTabView>}_scroll.clear();_split.clear();+ _restarts.clear();_latest.clear();_following.clear();_newAfter.clear();@@ -559,6 +563,7 @@ class _SuperTabViewState extends State<SuperTabView>final request = ++_scrollRequest;final sequence = _latest[id] ?? 0;_jumpingToEnd = true;+ _scroll[id]?.holdEnd(request);void advance(int attempt) {WidgetsBinding.instance.addPostFrameCallback((_) {final scroll = _scroll[id];@@ -567,6 +572,7 @@ class _SuperTabViewState extends State<SuperTabView>c.selectedId != id ||scroll == null ||!scroll.hasClients) {+ scroll?.releaseEnd(request);return;}scroll.jumpTo(scroll.position.maxScrollExtent);@@ -577,12 +583,20 @@ class _SuperTabViewState extends State<SuperTabView>request != _scrollRequest ||c.selectedId != id ||!scroll.hasClients) {+ scroll.releaseEnd(request);return;}- if (scroll.position.extentAfter > 1 && attempt < 12) {+ // Short of the end, or past it: an end estimated from rows not yet+ // laid out moves once they are, and on a Mac's bouncing scroll a+ // view left past it shows no row until it springs back.+ final position = scroll.position;+ if ((position.extentAfter > 1 ||+ position.pixels > position.maxScrollExtent + 1) &&+ attempt < 12) {advance(attempt + 1);} else {_jumpingToEnd = false;+ scroll.releaseEnd(request);if (scroll.position.extentAfter < 40) {_readToEnd(id, sequence);}@@ -1001,15 +1015,53 @@ class _SuperTabViewState extends State<SuperTabView>void _jumpToLatest() {final id = c.selectedId;_focus.requestFocus();- if (!c.hasNewer(id)) return _followEnd(id);+ if (!c.hasNewer(id)) {+ if (_farFromEnd(id)) _restartAtEnd(id);+ return _followEnd(id);+ }// More are waiting than were read: the latest page first, then its end.unawaited(c.showLatest(id).then((_) {- if (mounted && c.selectedId == id) _followEnd(id);+ if (!mounted || c.selectedId != id) return;+ _restartAtEnd(id);+ _followEnd(id);}),);}+ /// At most this many rows lie below a list's dividing row after a+ /// restart: all a jump to the end lays out.+ static const _restartRows = 40;++ /// Whether more rows lie below the top of [id]'s view than a restart+ /// keeps below its dividing row. A list reaches a row of unknown height+ /// only by laying out every row on the way, so a jump across thousands+ /// of them took seconds, and an end estimated from rows of very different+ /// heights left the view past the last row, showing none (Huy, #3049).+ bool _farFromEnd(String id) {+ final top = _rowAtTop();+ final own = _ownShown(id);+ final at = top == null ? -1 : own.indexWhere((m) => m.id == top);+ return at < 0 ? own.length > _restartRows : own.length - at > _restartRows;+ }++ /// Rebuilds [id]'s list around its newest rows instead of travelling to+ /// them: the dividing row moves to the newest [_restartRows], both of its+ /// slivers start empty, and the view starts at the dividing row. The rows+ /// above it read back as the reader scrolls up, as from a first open.+ void _restartAtEnd(String id) {+ final own = _ownShown(id);+ if (own.isEmpty) return;+ final first = own[(own.length - _restartRows).clamp(0, own.length - 1)];+ _split[id] = first;+ c.keepFrom(id, first);+ _restarts[id] = (_restarts[id] ?? 0) + 1;+ _anchors.remove(id);+ _scrollRequest++;+ _scroll[id]?.restart();+ setState(() {});+ }+void _noticesLeave(SuperTabController controller) {final notices = SuperTabChatNotices.of(controller);if (notices.chatShown == _chatShown) notices.chatShown = null;@@ -1535,9 +1587,36 @@ class _SuperTabViewState extends State<SuperTabView>Future<void> _earlier() => _loadEarlier(c.selectedId);- /// A scroll ending near the top reads the earlier page with no click.- void _readEarlierNearTop(String id, ScrollMetrics metrics) {- if (metrics.extentBefore > 400 ||+ /// Older pages are read while fewer rows than this are above the view: a+ /// page takes about a second to arrive, and in a busy chat most of its+ /// rows are thread replies, so a reader who scrolled to the top waited at+ /// a spinner every few rows (#3049). Counted in rows, not pixels: the+ /// height above the rows laid out is an estimate, and one not laid out+ /// again while the view stands still.+ static const _readAheadRows = 40;++ /// The list's rows as last built, by row key: their place in it.+ Map<String, int> _rowPlaces = const {};++ /// Whether the reader is near the top of what is read: once a scroll+ /// ends, within 400 px; reading [ahead] (moving up, or pages read on),+ /// fewer than [_readAheadRows] rows above the view, never by pixels.+ bool _nearTop(ScrollMetrics metrics, {required bool ahead}) {+ if (!ahead) return metrics.extentBefore <= 400;+ final top = _rowAtTop();+ final at = top == null ? null : _rowPlaces[_rowKey(c.messageIdentity(top))];+ return at != null && at < _readAheadRows;+ }++ /// A scroll near the top reads the earlier page with no click: [ahead]+ /// while it moves up or pages read on, and once it ends. A scroll that+ /// ends at the bottom, as opening a chat does, reads nothing ahead.+ void _readEarlierNearTop(+ String id,+ ScrollMetrics metrics, {+ bool ahead = false,+ }) {+ if (!_nearTop(metrics, ahead: ahead) ||_finding != null ||_find?.reading != null ||_loadingOlder.contains(id) ||@@ -1545,11 +1624,13 @@ class _SuperTabViewState extends State<SuperTabView>!c.hasOlder(id)) {return;}- WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted && c.selectedId == id && !_loadingOlder.contains(id)) {- unawaited(_loadEarlier(id));- }- });+ WidgetsBinding.instance+ ..addPostFrameCallback((_) {+ if (mounted && c.selectedId == id && !_loadingOlder.contains(id)) {+ unawaited(_loadEarlier(id));+ }+ })+ ..scheduleFrame();}/// Reads the page before those loaded, keeping what is on screen in place:@@ -1585,7 +1666,23 @@ class _SuperTabViewState extends State<SuperTabView>_olderFailed.remove(id);}});- if (anchor != null) await _keepRow(id, anchor, request: request);+ // While the reader scrolls, the list keeps their place as it lays the+ // page out (SuperTabChatScroll); a jump now would cut their scroll short.+ final scrolling =+ scroll.hasClients && scroll.position.isScrollingNotifier.value;+ if (anchor != null && !scrolling) {+ await _keepRow(id, anchor, request: request);+ }+ // Still near the top once the page is laid out, as after a page of+ // thread replies: the next one.+ if (!mounted || c.selectedId != id) return;+ WidgetsBinding.instance+ ..addPostFrameCallback((_) {+ if (mounted && c.selectedId == id && scroll.hasClients) {+ _readEarlierNearTop(id, scroll.position, ahead: true);+ }+ })+ ..scheduleFrame();}/// The row of [keep] when it is built, else the topmost row, and its top.@@ -4521,6 +4618,7 @@ class _SuperTabViewState extends State<SuperTabView>for (final (index, message) in messages.indexed)_rowKey(c.messageIdentity(message.id)): index,};+ _rowPlaces = rowIndex;// A row stays the same row as pages arrive above it, state and all.int? rowOf(Key key) => key is ValueKey<String> ? rowIndex[key.value] : null;final split = _splitAt(c.selectedId, ownMessages);@@ -4778,15 +4876,22 @@ class _SuperTabViewState extends State<SuperTabView>event.dragDetails != null) {_scrollRequest++;_jumpingToEnd = false;+ _scroll[c.selectedId]?.holdEnd(null);}if (_jumpingToEnd) return false;final id = c.selectedId;final atEnd = event.metrics.extentAfter < 40;_follow(id, atEnd);- // Once the scroll ends, so keeping the place never- // cuts a drag short.+ // Moving up, or once the scroll ends.if (event is ScrollEndNotification) {_readEarlierNearTop(id, event.metrics);+ } else if (event is ScrollUpdateNotification &&+ (event.scrollDelta ?? 0) < 0) {+ _readEarlierNearTop(+ id,+ event.metrics,+ ahead: true,+ );}if (atEnd) {// A row still sending has no place in the transcript.@@ -4831,6 +4936,9 @@ class _SuperTabViewState extends State<SuperTabView>),),LaidOutSliverList(+ key: ValueKey(+ 'super-older-rows-${_restarts[c.selectedId] ?? 0}',+ ),delegate: SliverChildBuilderDelegate((context, index) =>row(split - 1 - index),@@ -4849,6 +4957,9 @@ class _SuperTabViewState extends State<SuperTabView>bottom: grid.AppDesktop.controlGap,),sliver: LaidOutSliverList(+ key: ValueKey(+ 'super-newer-rows-${_restarts[c.selectedId] ?? 0}',+ ),delegate: SliverChildBuilderDelegate(// Messages on their way end the list.(context, index) =>diff --git a/desktop/test/super_tab_big_chat_jump_test.dart b/desktop/test/super_tab_big_chat_jump_test.dartnew file mode 100644index 000000000..06caeeedc--- /dev/null+++ b/desktop/test/super_tab_big_chat_jump_test.dart@@ -0,0 +1,221 @@+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/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// A chat with a very large history (Huy, 2026-11-05, #3049): scrolled far+/// up, Jump to latest still shows the newest messages.+void main() {+ const jump = ValueKey('super-jump-latest');+ const peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};+ const newMessages = ValueKey('super-new-messages');++ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server,+ ) async {+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ ScrollController chatScroll(WidgetTester tester) => tester+ .widget<ScrollView>(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ )+ .controller!;++ // Rows of very different heights, as in the openharness project chat:+ // line counts of 40 of its rows in a row, and now and then a report of+ // a hundred lines.+ const lines = [+ 3, 2, 2, 5, 1, 1, 3, 25, 2, 1, 3, 2, 2, 27, 1, 1, 16, 1, 4, //+ 2, 5, 1, 6, 26, 11, 13, 5, 1, 5, 2, 1, 8, 2, 4, 16, 54, 3, 1, 4, 3,+ ];+ String text(int i) {+ final count = i % 200 == 0 ? 100 : lines[i % lines.length];+ return [+ 'Update $i: checking the offline queue and reconnect.',+ for (var line = 1; line < count; line++) 'Line $line of update $i.',+ ].join('\n');+ }++ ConversationServer chat(int count) {+ final server = ConversationServer();+ for (var i = 1; i <= count; i++) {+ server.append(text(i));+ }+ return server;+ }++ /// How many message rows are on screen in the chat's view.+ int visibleRows(WidgetTester tester) {+ final view = tester.getRect(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ );+ var visible = 0;+ for (final row+ in find+ .byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith('super-row-'),+ )+ .evaluate()) {+ final box = row.renderObject;+ if (box is! RenderBox || !box.attached || !box.hasSize) continue;+ if ((box.localToGlobal(Offset.zero) & box.size).overlaps(view)) visible++;+ }+ return visible;+ }++ /// Scrolls to the top again and again, each time reading the page above,+ /// as a reader dragging far up does.+ Future<void> scrollFarUp(WidgetTester tester, int pages) async {+ for (var i = 0; i < pages; i++) {+ final scroll = chatScroll(tester);+ scroll.jumpTo(scroll.position.minScrollExtent);+ await tester.pumpAndSettle();+ }+ }++ testWidgets('Jump to latest after scrolling far up shows the newest '+ 'messages', (tester) async {+ final c = await show(tester, chat(1500));+ await scrollFarUp(tester, 15);+ expect(c.hasOlder('lead'), isFalse);+ expect(find.text(text(1500)), findsNothing);++ await tester.tap(find.byKey(jump));+ // Every frame of the way shows rows: none is an empty list.+ for (var frame = 0; frame < 30; frame++) {+ await tester.pump(const Duration(milliseconds: 16));+ expect(visibleRows(tester), greaterThan(0), reason: 'frame $frame');+ }+ await tester.pumpAndSettle();++ expect(find.text(text(1500)), findsOneWidget);+ expect(chatScroll(tester).position.extentAfter, lessThan(40));+ expect(find.byKey(jump), findsNothing);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('Jump to latest after scrolling far up while many messages '+ 'arrived shows the newest messages', (tester) async {+ final server = chat(1500);+ final c = await show(tester, server);+ await scrollFarUp(tester, 15);+ for (var i = 1501; i <= 2100; i++) {+ server.append(text(i));+ }+ for (var poll = 0; poll < 5; poll++) {+ await c.refresh();+ await tester.pumpAndSettle();+ }+ expect(c.hasNewer('lead'), isTrue);++ await tester.tap(find.byKey(newMessages));+ for (var frame = 0; frame < 30; frame++) {+ await tester.pump(const Duration(milliseconds: 16));+ expect(visibleRows(tester), greaterThan(0), reason: 'frame $frame');+ }+ await tester.pumpAndSettle();++ expect(find.text(text(2100)), findsOneWidget);+ expect(chatScroll(tester).position.extentAfter, lessThan(40));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('scrolling up without letting go reads the page above while '+ 'the reader is still screens below the top', (tester) async {+ final server = chat(400);+ final older = <double>[];+ final c = await show(tester, server);+ server.onRead = (path) {+ if (path.contains('before=')) {+ older.add(chatScroll(tester).position.extentBefore);+ }+ };+ final view = find.byKey(const PageStorageKey('super-messages-tab-lead'));+ final drag = await tester.startGesture(tester.getCenter(view));+ // A steady drag down the list, as a trackpad scrolls up: never let go.+ for (var step = 0; step < 400 && older.isEmpty; step++) {+ await drag.moveBy(const Offset(0, 100));+ await tester.pump(const Duration(milliseconds: 16));+ }+ expect(older, isNotEmpty);+ expect(older.first, greaterThan(900));+ await drag.up();+ await tester.pumpAndSettle();+ expect(c.messages('lead').length, greaterThan(100));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('a page of mostly thread replies reads the next one by itself '+ 'while the rows read stay near the top', (tester) async {+ final server = ConversationServer()+ ..threads = true+ ..messagePage = 20;+ for (var i = 1; i <= 2000; i++) {+ server.append(text(i));+ // Nine of every ten are replies in a thread, as in a busy project chat.+ if (i % 10 != 0) server.messages.last['thread'] = 'message-10';+ // Rows from different people, so none folds into the one before.+ if ((i ~/ 10).isEven) server.messages.last['author'] = peer;+ }+ final reads = <String>[];+ server.onRead = (path) {+ if (path.contains('before=')) reads.add(path);+ };+ final c = await show(tester, server);+ final scroll = chatScroll(tester);+ scroll.jumpTo(scroll.position.minScrollExtent);+ await tester.pumpAndSettle();++ // Read on while few rows stand above the view, not the whole history:+ // two of each page's twenty rows show.+ expect(reads.length, inInclusiveRange(10, 30));+ expect(c.hasOlder('lead'), isTrue);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));++ testWidgets('opening a big chat at its end reads no older page', (+ tester,+ ) async {+ final server = chat(400);+ final reads = <String>[];+ server.onRead = (path) {+ if (path.contains('before=')) reads.add(path);+ };+ final c = await show(tester, server);+ expect(chatScroll(tester).position.extentAfter, lessThan(40));+ expect(reads, isEmpty);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+}diff --git a/desktop/test/super_tab_chat_scroll_test.dart b/desktop/test/super_tab_chat_scroll_test.dartindex 054417df5..ddc6215a7 100644--- a/desktop/test/super_tab_chat_scroll_test.dart+++ b/desktop/test/super_tab_chat_scroll_test.dart@@ -256,7 +256,8 @@ void main() {await tester.pumpAndSettle();- expect(c.messages('lead').length, 40);+ // The page above, and the rest read ahead of the reader.+ expect(c.messages('lead').length, greaterThanOrEqualTo(40));for (final id in shown) {expect(top(tester, id), moreOrLessEquals(tops[id]!, epsilon: .5));}diff --git a/desktop/test/super_tab_find_in_chat_test.dart b/desktop/test/super_tab_find_in_chat_test.dartindex 6dcfa1f3c..b383337e8 100644--- a/desktop/test/super_tab_find_in_chat_test.dart+++ b/desktop/test/super_tab_find_in_chat_test.dart@@ -158,7 +158,9 @@ void main() {testWidgets('a search reads at most 50 older pages, then says so', (tester,) async {- final server = chat(80, matching: {80})..messagePage = 1;+ // Long enough that what the list reads ahead by itself leaves more+ // than 50 pages.+ final server = chat(200, matching: {200})..messagePage = 1;final reads = <String>[];await show(tester, server);server.onRead = reads.add;diff --git a/docs/plans/2026-11-05-big-chat-jump-and-paging-plan.md b/docs/plans/2026-11-05-big-chat-jump-and-paging-plan.mdnew file mode 100644index 000000000..c12118a76--- /dev/null+++ b/docs/plans/2026-11-05-big-chat-jump-and-paging-plan.md@@ -0,0 +1,69 @@+# Big chats: Jump to latest and smooth scrolling up — plan++**Goal:** In a chat with a very large history (the openharness project chat, ~4,100 messages in 42+pages), Jump to latest always shows the newest messages at once, and scrolling far up reads older+pages without the reader waiting at the top (task #3049, Huy, 2026-11-05).++**Architecture:** The Swarm chat is one `CustomScrollView` split at a dividing row: older pages+grow upward in one `SliverList`, newer rows downward in another (`desktop/lib/super_tabs/view.dart`).+A `SliverList` of rows of unknown height can only reach a row by laying out every row between,+so a jump from the top of 4,000 rows to the end lays out all of them in one frame. It then jumps to+an extent estimated from rows of very different heights, lands thousands of pixels past the real+end, and on the Mac's bouncing scroll the list shows no row while it springs back. The fix restarts+the list at the newest rows instead of travelling there: the dividing row moves to the newest rows,+both slivers are rebuilt empty under a new key, and the view starts at the dividing row, so the+jump lays out only the rows below it. Reading older pages starts while the reader is still a few+screens below the top, and keeps going while the rows read stay within that distance.++**Tech Stack:** Flutter 3.47 (Desktop), `flutter_test` widget tests with `ConversationServer`.++**Spec:** task #3049 brief (conversation a3ea0edbcbc1bf1d891250be).++This plan is implemented by its Engineer task by task, test first, as the project instructions say.++## Global Constraints++- Owns `desktop/lib/super_tabs/view.dart`, `desktop/lib/super_tabs/chat_scroll.dart` and their tests.+ No backend or CLI change; Swarm code stays out of `cli/src/core`.+- Desktop tests use a memory store and a fake sign-in; none signs the Mac out of the real CLI.+- Measured with the real openharness chat's pages replayed headless (`flutter test`, debug, Mac+ scroll physics) before and after; the replay and the chat's data stay local and are never committed.++## Review Focus++- The restart keeps nothing on screen from the old position: no row is anchored across it, and a+ later poll still cuts the held rows above the new dividing row.+- Jump to latest from near the end is unchanged (no restart, no rebuilt rows).+- Prefetching older pages during a drag never jumps the view (the anchored position keeps it).++## Task 1: Jump to latest restarts the list at the newest rows++**Files:** `desktop/lib/super_tabs/view.dart`, `desktop/lib/super_tabs/chat_scroll.dart`,+`desktop/test/super_tab_big_chat_jump_test.dart`++**Interfaces:** `SuperTabChatScroll.restart()` puts the view at the dividing row and forgets the+place it kept; the view's `_restartAtEnd(id)` moves the dividing row to the newest rows and rekeys+both slivers.++- [ ] Failing test: a 1,500-row chat with rows of the real chat's heights, scrolled to its top on+ Mac physics; after Jump to latest every frame shows a row and the newest row shows at the end.+- [ ] Failing test: the same after more than a page arrived while scrolled up (the latest page read).+- [ ] Code: `_jumpToLatest` restarts when more than a screenful of rows lies below the view or newer+ pages wait; `_followEnd` jumps again when it landed past the end.++## Task 2: Older pages are read before the reader reaches the top++**Files:** `desktop/lib/super_tabs/view.dart`, `desktop/test/super_tab_big_chat_jump_test.dart`++**Interfaces:** `_readEarlierNearTop` takes scroll updates too, within `_readAhead` of the top.++- [ ] Failing test: scrolling up steadily without stopping, the next page is read while the reader+ is still more than a screen below the top.+- [ ] Failing test: a page that brings few rows (most are thread replies) reads the next one by itself+ while the rows stay within the distance.+- [ ] Code: read on scroll updates within the distance; after a page lands, read the next while+ still within it.++## Task 3: Measure again++- [ ] The same replay as before the change; numbers and a screenshot to Huy in the task.