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-03 b2230: #2750 #2787 (#2843)
0xken1522d3a91212f2
diff --git a/backend/integration/superTabPullRequestEvents.test.ts b/backend/integration/superTabPullRequestEvents.test.tsnew file mode 100644index 000000000..3a072e0c2--- /dev/null+++ b/backend/integration/superTabPullRequestEvents.test.ts@@ -0,0 +1,177 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import type { Command } from '../src/superTabs/commands.js'+import { watchPullRequests, type PullRequestReader, type PullRequestWatch } from '../src/superTabs/pullRequestEvents.js'+import { logger } from '../src/utils/logger.js'++// Dee, #1891: GitHub events on an open task's pull request reach the task's Engineer directly, once, without waiting for+// the PM's sync. A fresh loopback replica set, created here.+let replica: MongoMemoryReplSet+let db: PrismaClient+const owner: AuthUser = { sub: '210000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const host: AuthUser = { sub: '210000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }+const HEAD = 'abc1234def5678'+const MINUTE = 60_000++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_pr_events_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ for (const machineId of ['lead-host', 'test-host']) {+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })+ }+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** What a fake GitHub says of each pull request, which a test changes between passes, and which URLs a pass asked about. */+function fakeReader() {+ const pulls = new Map<string, PullRequestWatch>()+ const asked: string[] = []+ const reader: PullRequestReader = {+ watch: async url => { asked.push(url); return pulls.get(url) ?? null },+ botLogin: async () => 'harness[bot]',+ done: async () => {},+ }+ return { pulls, asked, reader }+}+/** Each Swarm's own pull request: a pass reads every Swarm in this database, and the others' are not this fake's. */+let pullNumbers = 100++/** A Swarm with a Lead and a task, "Ship the parser", assigned to a worker that linked [PR] in its status. */+async function swarm() {+ const number = ++pullNumbers, PR = `https://github.com/acme/app/pull/${number}`+ const pull = (patch: Partial<PullRequestWatch> = {}): PullRequestWatch => ({ url: PR, number, state: 'open', draft: false, head: HEAD, base: 'main',+ mergeable: true, checkRuns: [], checkSuites: [], reviews: [], comments: [], ...patch })+ let now = Date.parse('2026-11-03T08:00:00.000Z')+ const store = new SuperTabStore(db, () => now)+ const tab = (await store.create(owner, randomUUID(), 'Events', 'public')).id+ const execute = (command: Command, user = owner, asAgentId?: string) => store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ for (const [machineId, name] of [['lead-host', 'Lead Mac'], ['test-host', 'Worker Mac']]) {+ await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)+ }+ const add = async (conversationId: string, machineId: string, name: string, lead = false) => String((await execute({ type: 'agent.add',+ conversationId, machineId, harnessId: randomUUID(), name, configuration: config, lead })).result.agentId)+ const lead = await add('lead', 'lead-host', 'Lead', true)+ const task = String((await execute({ type: 'conversation.create', title: 'Ship the parser', brief: 'Implement it',+ checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ const worker = await add(task, 'test-host', 'Worker')+ const assignment = String((await execute({ type: 'work.assign', conversationId: task, agentId: worker })).result.assignmentId)+ await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'working', result: `Draft ${PR}` }, host, worker)+ const { pulls, asked, reader } = fakeReader()+ const pass = async () => { now += MINUTE; return watchPullRequests(db, store, reader, now) }+ /** The rows this feature wrote in [conversationId], oldest first. */+ const told = async (conversationId = task) => (await db.superTabMessage.findMany({ where: { tabId: tab, conversationId }, orderBy: { sequence: 'asc' } }))+ .filter(m => m.recipientIds.length > 0 && m.text.includes(PR))+ return { PR, number, pull, store, tab, execute, add, lead, task, worker, assignment, pulls, asked, reader, pass, told, clock: { get now() { return now }, advance(ms: number) { now += ms } } }+}++describe('pull request events', () => {+ it('CI red, CI green, a review and a conflict each post one message to the Engineer', async () => {+ const f = await swarm()+ f.pulls.set(f.PR, f.pull())+ await f.pass()+ expect(await f.told()).toEqual([])+ f.pulls.set(f.PR, f.pull({ checkRuns: [{ name: 'build (ubuntu)', status: 'completed', conclusion: 'failure', completedAt: f.clock.now + 10_000 }] }))+ expect(await f.pass()).toBe(1)+ const head2 = 'fedcba9876543'+ f.pulls.set(f.PR, f.pull({ head: head2, checkRuns: [{ name: 'build (ubuntu)', status: 'completed', conclusion: 'success', completedAt: f.clock.now + 10_000 }],+ checkSuites: [{ status: 'completed', runs: 1 }] }))+ expect(await f.pass()).toBe(1)+ f.pulls.set(f.PR, f.pull({ head: head2, mergeable: false, checkRuns: [{ name: 'build (ubuntu)', status: 'completed', conclusion: 'success', completedAt: f.clock.now }],+ checkSuites: [{ status: 'completed', runs: 1 }], reviews: [{ id: 7, login: 'huy', association: 'MEMBER', state: 'CHANGES_REQUESTED', body: 'Keep the arrow.', url: `${f.PR}#pullrequestreview-7` }] }))+ expect(await f.pass()).toBe(2)+ const rows = await f.told()+ expect(rows.map(r => r.text)).toEqual([+ `CI failed on your pull request #${f.number} (head abc1234): build (ubuntu). ${f.PR}`,+ `CI passed on your pull request #${f.number} (head fedcba9). ${f.PR}`,+ `Your pull request #${f.number} has a merge conflict with main (head fedcba9): merge main into its branch and push. ${f.PR}`,+ `huy asked for changes on your pull request #${f.number}: "Keep the arrow." ${f.PR}#pullrequestreview-7`,+ ])+ for (const row of rows) expect(row.recipientIds).toEqual([f.worker])+ // Each reaches the Engineer's host as any message to it does.+ expect(await db.superTabDelivery.count({ where: { tabId: f.tab, agentId: f.worker, messageId: { in: rows.map(r => r.id) } } })).toBe(4)+ })++ it('a second pass and a retried write post nothing', async () => {+ const f = await swarm()+ f.pulls.set(f.PR, f.pull())+ await f.pass()+ const red = f.pull({ checkRuns: [{ name: 'build', status: 'completed', conclusion: 'failure', completedAt: f.clock.now + 10_000 }] })+ f.pulls.set(f.PR, red)+ expect(await f.pass()).toBe(1)+ expect(await f.pass()).toBe(0)+ // The same write sent again, as a retry would: the group already holds its key.+ expect(await f.store.pullRequestSeen(f.tab, f.task, red, 'harness[bot]')).toBe(0)+ expect(await f.told()).toHaveLength(1)+ })++ it('no Engineer: recorded, not posted, so a later one hears only what is new', async () => {+ const f = await swarm()+ f.pulls.set(f.PR, f.pull())+ await f.pass()+ await f.execute({ type: 'agent.remove', agentId: f.worker })+ f.pulls.set(f.PR, f.pull({ mergeable: false }))+ expect(await f.pass()).toBe(0)+ expect(await f.told()).toEqual([])+ // What the task's next Engineer will not be told again.+ const row = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })+ expect((row.data as { pullRequestEvents?: Record<string, string[]> }).pullRequestEvents?.[f.PR]).toContain(`conflict:${HEAD}`)+ })++ it('a step and a finished task are not read', async () => {+ const f = await swarm()+ const other = 'https://github.com/acme/app/pull/13'+ await f.execute({ type: 'conversation.create', title: 'Review', reviewOf: f.task, step: 'Review', brief: `Review ${other}`,+ checks: [{ description: 'Verdict', independent: false }] } as Command)+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'done', result: `Done ${f.PR}` }, host, f.worker)+ await f.pass()+ // Other tests' Swarms are in this database too: this one's pull requests are the ones not asked about.+ expect(f.asked).not.toContain(f.PR)+ expect(f.asked).not.toContain(other)+ })++ // ENGINEERING.md 4: no loop grows without a bound. A pass reads a capped number of tasks, the most recently active first.+ it('reads at most its cap of tasks a pass, the most recently active first', async () => {+ const f = await swarm()+ f.pulls.set(f.PR, f.pull())+ // Other tests' tasks are in this database too: this one is made the most recently active.+ f.clock.advance(60 * MINUTE)+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'working', result: `Still on ${f.PR}` }, host, f.worker)+ await watchPullRequests(db, f.store, f.reader, f.clock.now + MINUTE, 1)+ expect(f.asked).toEqual([f.PR])+ })++ // ENGINEERING.md 6 and 8: a pull request GitHub cannot read is not skipped in silence, and each pass that did something+ // says how much.+ it('says how many pull requests it could not read', async () => {+ const f = await swarm()+ const warn = vi.spyOn(logger, 'warn')+ try {+ await f.pass()+ expect(warn).toHaveBeenCalledWith('[swarm-pr-events] pass', expect.objectContaining({ unreadable: expect.any(Number), posted: 0 }))+ const line = warn.mock.calls.find(call => call[0] === '[swarm-pr-events] pass')![1] as { unreadable: number; pulls: number; groups: number }+ expect(line.unreadable).toBeGreaterThanOrEqual(1)+ expect(line.pulls).toBeGreaterThanOrEqual(line.unreadable)+ } finally { warn.mockRestore() }+ })+})diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.tsindex 4b5309d36..1fa20900d 100644--- a/backend/integration/workerIndexPlans.test.ts+++ b/backend/integration/workerIndexPlans.test.ts@@ -189,3 +189,30 @@ describe('the usage-receipt sweep\'s stuck check (lib/productUsageReceiptSweep.texpect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(1)})})++// Dee, #1891; ENGINEERING.md 4 and the MongoDB query skill: the minute's pull request watch reads open tasks through the finished+// mark's index, equality on its first two fields and the activity range last, newest first and capped.+describe('the pull request watch', () => {+ it('reads the open tasks active this week by the finished mark index, the newest first, capped', async () => {+ const { watchPullRequests } = await import('../src/superTabs/pullRequestEvents.js')+ let n = 0+ const group = (activeAt: number, patch: { workFinished?: boolean; data?: Record<string, unknown> } = {}) => {+ const key = `g${++n}`+ return { id: `tab-w:${key}`, tabId: 'tab-w', key, version: 1, changedAt: new Date(NOW), ordinal: n, agentIds: [], lastActivityAt: new Date(activeAt),+ workFinished: patch.workFinished ?? false, data: { pullRequestUrls: [`https://github.com/acme/app/pull/${n}`], ...patch.data } }+ }+ // Finished work and work quiet for a month, which a read the index does not bound examines too; a step, which it filters.+ await db.swarmGroup.createMany({ data: [+ ...Array.from({ length: 20 }, () => group(NOW - DAY, { workFinished: true })), ...Array.from({ length: 20 }, () => group(NOW - 30 * DAY)),+ group(NOW - 3 * 3_600_000), group(NOW - 2 * 3_600_000), group(NOW - 3_600_000, { data: { reviewOf: 'g1' } }), group(NOW - 60_000),+ ] })+ const asked: string[] = []+ const reader = { watch: async (url: string) => { asked.push(url); return null }, botLogin: async () => null, done: async () => {} }+ const entries = await profiled(db, () => watchPullRequests(db, { pullRequestSeen: async () => 0 }, reader, NOW, 2))+ expect(asked).toEqual(['https://github.com/acme/app/pull/44', 'https://github.com/acme/app/pull/42'])+ const rows = reads(entries, 'SwarmGroup', ['workFinished', 'lastActivityAt'])+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ workFinished: 1, archived: 1, lastActivityAt: 1/)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(3)+ })+})diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.tsindex 560500051..c24151300 100644--- a/backend/src/github/app.test.ts+++ b/backend/src/github/app.test.ts@@ -1,6 +1,6 @@import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'import { describe, expect, it, vi } from 'vitest'-import { ACTIONS_READ_PERMISSIONS, CI_LOAD_TTL_MS, CI_MAX_CALLS, CI_MAX_RUNS, CI_READS_PER_HOUR, CI_STALE_MS, SERVER_PROCESSES_MAX, cacheSecret, githubAppConfig, GitHubAppError, PULL_READ_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'+import { ACTIONS_READ_PERMISSIONS, CI_LOAD_TTL_MS, CI_MAX_CALLS, CI_MAX_RUNS, CI_READS_PER_HOUR, CI_STALE_MS, SERVER_PROCESSES_MAX, cacheSecret, githubAppConfig, GitHubAppError, PULL_READ_PERMISSIONS, PULL_WATCH_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'import { FAKE_API, fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'import { githubRepository } from './repository.js'import { GitHubApp, HARNESS_CO_AUTHOR } from './app.js'@@ -459,3 +459,71 @@ describe('who pushed a pull request, through the app', () => {expect(logReads()).toBe(settled)})})++// Dee, #1891: a task's pull request is watched for its Engineer (superTabs/pullRequestEvents.ts), with what the app holds.+describe('watching a pull request', () => {+ const HEAD = 'abc1234def5678'+ const seed = (github: ReturnType<typeof fakeGitHub>) => {+ github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: HEAD }, base: { ref: 'main' }, mergeable: false,+ html_url: 'https://github.com/acme/app/pull/12' })+ github.checkRuns.set(`acme/app@${HEAD}`, [{ name: 'build', status: 'completed', conclusion: 'failure', completed_at: '2026-10-24T11:59:00Z' },+ { name: 'lint', status: 'in_progress', conclusion: null, completed_at: null }])+ github.checkSuites.set(`acme/app@${HEAD}`, [{ status: 'in_progress', latest_check_runs_count: 2 }])+ github.reviews.set('acme/app#12', [{ id: 7, user: { login: 'huy' }, author_association: 'MEMBER', state: 'CHANGES_REQUESTED', body: 'Keep the arrow.', html_url: 'https://github.com/acme/app/pull/12#pullrequestreview-7' }])+ github.comments.set('acme/app#12', [{ id: 9, user: { login: 'dee' }, author_association: 'NONE', body: 'Looks good', html_url: 'https://github.com/acme/app/pull/12#issuecomment-9' }])+ }++ it('reads the pull, its head\'s check runs and suites, its reviews and comments, with a read-only token', async () => {+ const { app, github } = setup()+ const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)+ expect(github.calls.at(-1)!.body).toMatchObject({ permissions: { pull_requests: 'read', checks: 'read', metadata: 'read' } })+ expect(Object.keys(PULL_WATCH_PERMISSIONS).sort()).toEqual(['checks', 'metadata', 'pull_requests'])+ for (const name of Object.keys(PULL_WATCH_PERMISSIONS)) expect(TOKEN_PERMISSIONS[name as keyof typeof TOKEN_PERMISSIONS]).toBeDefined()+ seed(github)+ expect(await app.watchPullRequest(repo, 12, token)).toEqual({ url: 'https://github.com/acme/app/pull/12', number: 12, state: 'open', draft: false,+ head: HEAD, base: 'main', mergeable: false,+ checkRuns: [{ name: 'build', status: 'completed', conclusion: 'failure', completedAt: Date.parse('2026-10-24T11:59:00Z') },+ { name: 'lint', status: 'in_progress', conclusion: null, completedAt: null }],+ checkSuites: [{ status: 'in_progress', runs: 2 }],+ reviews: [{ id: 7, login: 'huy', association: 'MEMBER', state: 'CHANGES_REQUESTED', body: 'Keep the arrow.', url: 'https://github.com/acme/app/pull/12#pullrequestreview-7' }],+ comments: [{ id: 9, login: 'dee', association: 'NONE', body: 'Looks good', url: 'https://github.com/acme/app/pull/12#issuecomment-9' }] })+ expect(github.calls.slice(-5).map(c => c.path)).toEqual(['/repos/acme/app/pulls/12', `/repos/acme/app/commits/${HEAD}/check-runs`,+ `/repos/acme/app/commits/${HEAD}/check-suites`, '/repos/acme/app/pulls/12/reviews', '/repos/acme/app/issues/12/comments'])+ })++ it('asks again with If-None-Match and reuses the body of a 304', async () => {+ const { app, github } = setup()+ const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)+ seed(github)+ const first = await app.watchPullRequest(repo, 12, token)+ const again = await app.watchPullRequest(repo, 12, token)+ expect(again).toEqual(first)+ expect(github.calls.slice(-5).every(c => c.ifNoneMatch)).toBe(true)+ github.comments.set('acme/app#12', [])+ expect((await app.watchPullRequest(repo, 12, token))!.comments).toEqual([])+ })++ // Review of #2750, Important 2: GitHub lists reviews and comments oldest first, so the newest are on the last page.+ it('reads the newest reviews and comments from the last page', async () => {+ const { app, github } = setup()+ const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)+ seed(github)+ github.comments.set('acme/app#12', Array.from({ length: 250 }, (_, i) => ({ id: i + 1, user: { login: 'dee' }, author_association: 'MEMBER', body: `note ${i + 1}`,+ html_url: `https://github.com/acme/app/pull/12#issuecomment-${i + 1}` })))+ const ids = (await app.watchPullRequest(repo, 12, token))!.comments.map(c => c.id)+ expect(ids).toContain(250)+ expect(ids).toContain(201)+ // A new comment shows on the next read, even though the first page is unchanged.+ github.comments.get('acme/app#12')!.push({ id: 251, user: { login: 'dee' }, author_association: 'MEMBER', body: 'note 251', html_url: 'x' })+ expect((await app.watchPullRequest(repo, 12, token))!.comments.map(c => c.id)).toContain(251)+ })++ it('answers null when GitHub cannot say', async () => {+ const { app, github } = setup()+ const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)+ expect(await app.watchPullRequest(repo, 12, token)).toBeNull()+ seed(github)+ github.control.down = true+ expect(await app.watchPullRequest(repo, 12, token)).toBeNull()+ })+})diff --git a/backend/src/github/app.ts b/backend/src/github/app.tsindex 93506c8f4..5d0c017ae 100644--- a/backend/src/github/app.ts+++ b/backend/src/github/app.ts@@ -9,6 +9,7 @@import { createPrivateKey, hkdfSync, sign, type KeyObject } from 'node:crypto'import { readPushOrigin, type GitHubRead, type PushOrigin } from './pushOrigin.js'import { githubRepository, type GitHubRepository } from './repository.js'+import type { PullRequestWatch } from '../superTabs/pullRequestEvents.js'/** What a Swarm agent's token may do, and nothing more: push to and read the repository, open and update pull requests,* and read checks and workflow runs to see whether its pull request passes. */@@ -21,6 +22,11 @@ export const PULL_READ_PERMISSIONS = { pull_requests: 'read', metadata: 'read' }export const ACTIONS_READ_PERMISSIONS = { actions: 'read', metadata: 'read' } as const/** What reading who pushed a pull request's commits may do (pushOrigin.ts): read the pull request and the repository's activity log. */export const PUSH_ORIGIN_PERMISSIONS = { contents: 'read', pull_requests: 'read', metadata: 'read' } as const+/** What watching a task's pull request for its Engineer reads (superTabs/pullRequestEvents.ts): the pull request, its reviews+ * and comments, and its head's checks. All already among the app's permissions ([TOKEN_PERMISSIONS]). */+export const PULL_WATCH_PERMISSIONS = { pull_requests: 'read', checks: 'read', metadata: 'read' } as const+/** The watch's answers kept for conditional reads: an unchanged one comes back 304, which GitHub's rate limit does not count. */+const WATCH_KEPT = 2000const PUSH_ORIGINS_KEPT = 1000const PUSH_UNKNOWN_MS = 60_000export type TokenPermissions = Readonly<Record<string, 'read' | 'write'>>@@ -134,6 +140,8 @@ export class GitHubApp {private readonly ciReads = new Map<string, { at: number[]; last: { load: CiLoad | null; at: number } | null }>()/** When each repository's "not installed" was last forgotten on request ([forget]). */private readonly forgotten = new Map<string, number>()+ /** The watch's last answer and its ETag, by path ([watchPullRequest]). */+ private readonly watched = new Map<string, { etag: string; body: Record<string, unknown> | unknown[]; link: string | null }>()constructor(readonly config: GitHubAppConfig, options: GitHubAppOptions = {}) {this.fetch = options.fetch ?? fetch@@ -181,13 +189,14 @@ export class GitHubApp {return jwt}- private async call(method: string, path: string, auth: string | null, body?: unknown): Promise<{ link?: string | null; status: number; body: Record<string, unknown> | unknown[] }> {+ private async call(method: string, path: string, auth: string | null, body?: unknown, headers: Record<string, string> = {}):+ Promise<{ link?: string | null; etag?: string | null; status: number; body: Record<string, unknown> | unknown[] }> {let response: Responsetry {response = await this.fetch(`${this.apiUrl}${path}`, {method, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'harness-backend',- ...(auth ? { Authorization: auth } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },+ ...(auth ? { Authorization: auth } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },...(body ? { body: JSON.stringify(body) } : {}),})} catch {@@ -197,7 +206,7 @@ export class GitHubApp {let parsed: unknown = {}try { parsed = text ? JSON.parse(text) : {} } catch { parsed = {} }return { status: response.status, body: parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {},- link: response.headers.get('link') }+ link: response.headers.get('link'), etag: response.headers.get('etag') }}private misconfigured(): GitHubAppError {@@ -472,6 +481,68 @@ export class GitHubApp {}}+ /**+ * What a task's Engineer is told of its pull request [number] (superTabs/pullRequestEvents.ts): the pull request, its head's+ * latest check runs and its check suites, its reviews and its conversation comments, read with a [PULL_WATCH_PERMISSIONS]+ * token. Each read names the last answer's ETag, and a 304 reuses that answer. Reviews and comments come oldest first, so+ * their last page is read too when there is more than one (review of #2750). Null when GitHub cannot say.+ */+ async watchPullRequest(repository: GitHubRepository, number: number, token: string): Promise<PullRequestWatch | null> {+ const base = `/repos/${repository.owner}/${repository.name}`+ const answerOf = async (path: string, fresh = false): Promise<{ body: Record<string, unknown> | unknown[]; link: string | null } | null> => {+ const kept = this.watched.get(path)+ const answer = await this.call('GET', path, `Bearer ${token}`, undefined, kept && !fresh ? { 'If-None-Match': kept.etag } : {})+ if (answer.status === 304 && kept) return kept+ if (answer.status !== 200) return null+ this.watched.delete(path)+ if (answer.etag) {+ if (this.watched.size >= WATCH_KEPT) this.watched.delete(this.watched.keys().next().value!)+ this.watched.set(path, { etag: answer.etag, body: answer.body, link: answer.link ?? null })+ }+ return { body: answer.body, link: answer.link ?? null }+ }+ const read = async (path: string) => (await answerOf(path))?.body ?? null+ // A full first page is read afresh: a new last page changes its Link, not its body.+ const pages = async (path: string): Promise<unknown[] | null> => {+ const first = await answerOf(path, (this.watched.get(path)?.body as unknown[] | undefined)?.length === 100)+ if (!first || !Array.isArray(first.body)) return null+ const last = /<([^>]+)>;\s*rel="last"/.exec(first.link ?? '')?.[1]+ const lastPath = last?.startsWith(this.apiUrl) ? last.slice(this.apiUrl.length) : null+ if (!lastPath) return first.body+ const tail = await read(lastPath)+ return Array.isArray(tail) ? [...first.body, ...tail] : null+ }+ const text = (value: unknown) => typeof value === 'string' ? value : ''+ const login = (value: unknown) => text((value as { login?: unknown } | null)?.login)+ const at = (value: unknown) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : null+ try {+ const pull = await read(`${base}/pulls/${number}`) as Record<string, unknown> | null+ const head = text((pull?.head as { sha?: unknown } | undefined)?.sha)+ if (!pull || (pull.state !== 'open' && pull.state !== 'closed') || !/^[0-9a-f]{7,64}$/.test(head)) return null+ const [runs, suites, reviews, comments] = await Promise.all([read(`${base}/commits/${head}/check-runs?per_page=100`),+ read(`${base}/commits/${head}/check-suites?per_page=100`), pages(`${base}/pulls/${number}/reviews?per_page=100`),+ pages(`${base}/issues/${number}/comments?per_page=100`)])+ if (!runs || !suites || !Array.isArray(reviews) || !Array.isArray(comments)) return null+ const list = (value: unknown) => Array.isArray(value) ? value as Array<Record<string, unknown>> : []+ return {+ url: text(pull.html_url) || `https://github.com/${repository.owner}/${repository.name}/pull/${number}`, number,+ state: pull.state, draft: pull.draft === true, head, base: text((pull.base as { ref?: unknown } | undefined)?.ref) || 'main',+ mergeable: typeof pull.mergeable === 'boolean' ? pull.mergeable : null,+ checkRuns: list((runs as Record<string, unknown>).check_runs).map(run => ({ name: text(run.name), status: text(run.status),+ conclusion: typeof run.conclusion === 'string' ? run.conclusion : null, completedAt: at(run.completed_at) })),+ checkSuites: list((suites as Record<string, unknown>).check_suites).map(suite => ({ status: text(suite.status),+ runs: typeof suite.latest_check_runs_count === 'number' ? suite.latest_check_runs_count : 0 })),+ reviews: list(reviews).filter(review => typeof review.id === 'number').map(review => ({ id: review.id as number, login: login(review.user),+ association: text(review.author_association) || 'NONE', state: text(review.state), body: text(review.body), url: text(review.html_url) })),+ comments: list(comments).filter(comment => typeof comment.id === 'number').map(comment => ({ id: comment.id as number,+ login: login(comment.user), association: text(comment.author_association) || 'NONE', body: text(comment.body), url: text(comment.html_url) })),+ }+ } catch (error) {+ if (error instanceof GitHubAppError) return null+ throw error+ }+ }+/** The default branch and whether pushing to it straight needs a pull request, read with the agent's own token* (metadata and contents read): rulesets first (GET /repos/{owner}/{repo}/rules/branches/{branch}), then classic* protection's flag on the branch. Remembered ten minutes; a failed read is `unknown`, never a refusal. */diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.tsindex fe67dbe6c..51edd6781 100644--- a/backend/src/github/fakeGitHub.ts+++ b/backend/src/github/fakeGitHub.ts@@ -1,7 +1,7 @@/*** Tests only: a fake GitHub REST API for the Harness GitHub App, and a throwaway RSA key. Nothing here reaches github.com.*/-import { createPublicKey, generateKeyPairSync, verify, type KeyObject } from 'node:crypto'+import { createHash, createPublicKey, generateKeyPairSync, verify, type KeyObject } from 'node:crypto'import { GitHubApp, type GitHubAppConfig } from './app.js'export const FAKE_API = 'https://github.fake.test'@@ -11,7 +11,7 @@ export function throwawayKey(): { privateKey: KeyObject; pem: string; publicKey:return { privateKey, pem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), publicKey: createPublicKey(privateKey) }}-export interface FakeCall { method: string; path: string; auth: string; body: unknown }+export interface FakeCall { method: string; path: string; auth: string; body: unknown; ifNoneMatch?: string }/** One fake GitHub: which repositories have the app (`installed`, by `owner/name`, lower case), what each default branch's* protection is, and every request it was sent. A request whose JWT is not signed by [publicKey] is answered 401. */@@ -22,8 +22,15 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const owners = new Map<string, number>()const renamed = new Map<string, string>()const protection = new Map<string, { rules?: unknown[]; protected?: boolean; branch?: string; fail?: boolean }>()- /** Pull requests by `owner/name#number`, lower case: GitHub's state and when it was merged. */- const pulls = new Map<string, { state: 'open' | 'closed'; merged_at: string | null }>()+ /** Pull requests by `owner/name#number`, lower case: GitHub's state and when it was merged, and what a watch reads. */+ const pulls = new Map<string, { state: 'open' | 'closed'; merged_at: string | null; draft?: boolean; head?: { sha: string }; base?: { ref: string };+ mergeable?: boolean | null; html_url?: string }>()+ /** A head's latest check runs and its check suites, by `owner/name@sha`, lower case. */+ const checkRuns = new Map<string, Array<{ name: string; status: string; conclusion: string | null; completed_at: string | null }>>()+ const checkSuites = new Map<string, Array<{ status: string; latest_check_runs_count: number }>>()+ /** A pull request's reviews and conversation comments, by `owner/name#number`, lower case. */+ const reviews = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; state: string; body: string; html_url: string }>>()+ const comments = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; body: string; html_url: string }>>()/** Workflow runs by `owner/name`, lower case: each run's status and its jobs' statuses and runner labels. */const actions = new Map<string, Array<{ id: number; status: string; jobs: Array<{ status: string; labels: string[] }> }>>()const calls: FakeCall[] = []@@ -47,8 +54,9 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const url = new URL(String(input))const method = init?.method ?? 'GET'const auth = String((init?.headers as Record<string, string> | undefined)?.Authorization ?? '')+ const ifNoneMatch = (init?.headers as Record<string, string> | undefined)?.['If-None-Match']const body = init?.body ? JSON.parse(String(init.body)) : undefined- calls.push({ method, path: url.pathname, auth, body })+ calls.push({ method, path: url.pathname, auth, body, ...(ifNoneMatch ? { ifNoneMatch } : {}) })if (control.down) throw new TypeError('fetch failed')let match: RegExpExecArray | nullif (method === 'GET' && (match = /^\/repos\/([^/]+)\/([^/]+)\/installation$/.exec(url.pathname))) {@@ -105,17 +113,39 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const run = runs.find(r => r.id === Number(jobs[1]))return run ? json(200, { total_count: run.jobs.length, jobs: run.jobs.map((j, i) => ({ id: i, name: `job ${i}`, ...j })) }) : json(404, { message: 'Not Found' })}+ // As GitHub does: each answer carries an ETag, and a request naming the current one is answered 304 with no body.+ const tagged = (value: unknown) => {+ const etag = `"${createHash('sha1').update(JSON.stringify(value)).digest('hex')}"`+ if (ifNoneMatch === etag) return new Response(null, { status: 304, headers: { etag } })+ return new Response(JSON.stringify(value), { status: 200, headers: { etag } })+ }+ const repoKey = `${repoPath[1]}/${repoPath[2]}`.toLowerCase()const pull = /^\/pulls\/(\d+)$/.exec(repoPath[3] ?? '')if (pull) {- const known = pulls.get(`${repoPath[1]}/${repoPath[2]}#${pull[1]}`.toLowerCase())- return known ? json(200, { number: Number(pull[1]), ...known }) : json(404, { message: 'Not Found' })+ const known = pulls.get(`${repoKey}#${pull[1]}`)+ return known ? tagged({ number: Number(pull[1]), ...known }) : json(404, { message: 'Not Found' })+ }+ const head = /^\/commits\/([0-9a-f]+)\/(check-runs|check-suites)$/.exec(repoPath[3] ?? '')+ if (head) {+ const key = `${repoKey}@${head[1]}`+ return head[2] === 'check-runs' ? tagged({ total_count: checkRuns.get(key)?.length ?? 0, check_runs: checkRuns.get(key) ?? [] })+ : tagged({ total_count: checkSuites.get(key)?.length ?? 0, check_suites: checkSuites.get(key) ?? [] })+ }+ const talk = /^\/(pulls|issues)\/(\d+)\/(reviews|comments)$/.exec(repoPath[3] ?? '')+ if (talk) {+ // Oldest first, a page at a time, with a Link to the last page as GitHub sends it.+ const all = (talk[3] === 'reviews' ? reviews : comments).get(`${repoKey}#${talk[2]}`) ?? []+ const size = Number(url.searchParams.get('per_page') ?? 30), page = Number(url.searchParams.get('page') ?? 1), last = Math.max(1, Math.ceil(all.length / size))+ const answer = tagged(all.slice((page - 1) * size, page * size))+ if (last > 1) answer.headers.set('link', `<${FAKE_API}${url.pathname}?per_page=${size}&page=${last}>; rel="last"`)+ return answer}if (repoPath[3] === `/rules/branches/${encodeURIComponent(branch)}`) return json(200, known.rules ?? [])if (repoPath[3] === `/branches/${encodeURIComponent(branch)}`) return json(200, { name: branch, protected: known.protected ?? false })}return json(404, { message: 'Not Found' })}) as typeof globalThis.fetch- return { fetch, calls, installed, owners, renamed, protection, pulls, revoked, issued, control, actions, permissions }+ return { fetch, calls, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, revoked, issued, control, actions, permissions }}/** A configured app talking to [github]. */diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.tsindex c46537021..b924e3163 100644--- a/backend/src/superTabs/buddies.ts+++ b/backend/src/superTabs/buddies.ts@@ -174,7 +174,7 @@ export const buddyReady = (name: string): string => `${name} is ready. Tell it w* model, a terminal alert, its own stop). Every other command is refused, so it can never assign, start, route, ask* decisions or change anything for its owner (spec constraint: PRIVACY-CRITICAL). */const BUDDY_COMMANDS: ReadonlySet<string> = new Set(['message.send', 'message.react', 'buddy.propose', 'agent.configuration', 'agent.alert',- 'agent.stopLease', 'agent.stopRefused', 'agent.remove'])+ 'agent.stopLease', 'agent.stopRefused', 'agent.remove', 'buddy.modelResult'])export function requireBuddyCommand(buddy: Agent, command: { type: string; conversationId?: unknown; agentId?: unknown }, groups: readonly Conversation[]): void {if (!BUDDY_COMMANDS.has(command.type)) fail('BUDDY_FORBIDDEN', 'A Buddy only talks with its owner and sends the proposals they ask for.', 403)diff --git a/backend/src/superTabs/buddyModel.test.ts b/backend/src/superTabs/buddyModel.test.tsnew file mode 100644index 000000000..486e39c3b--- /dev/null+++ b/backend/src/superTabs/buddyModel.test.ts@@ -0,0 +1,369 @@+// A person switches their Buddy between their own subscription and a model shared in the Swarm, and back (task #2354,+// docs/plans/2026-11-03-buddy-model-switch-design.md). The server checks the model against what the Swarm serves now,+// records the request for the Buddy's machine, and writes the outcome in the person's Buddy chat only.+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { createSuperTab, visibleState, type Actor } from './model.js'+import type { ContributedMachine } from './machines.js'+import { swarmBuddyChatId } from './buddies.js'+import { sweepLiveness } from './liveness.js'+import { withoutMachineNames } from './store.js'+import { BUDDY_MODEL_GONE_MS, BUDDY_MODEL_LEASE_MS } from './tidy.js'++const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }+const third: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'third', email: '[email protected]' }+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }+const NOW = 1000+const MODEL = 'deepseek-4.1-flash'+type Reading = NonNullable<ContributedMachine['observation']>+type LocalModel = NonNullable<Reading['localModels']>[number]+const reading = (receivedAt: number, localModels: LocalModel[] = [], capabilities = ['buddySessions', 'swarmBuddy', 'buddyModel']): Reading => ({+ generation: 'g1', receivedAt, sessionKind: 'computer',+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null,+ projectDiskFreeBytes: null, deviceType: null, chip: null, os: null, gpuPercent: null },+ tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [], capabilities, localModels })++/** A Swarm where owner's Mac Studio serves DeepSeek on the Swarm's grid and shares an API, and peer runs their one Buddy on+ * their own Mac in the Swarm's Machines list. */+function setup(options: { buddyCapabilities?: string[] } = {}) {+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: owner.email }, 'test')+ const grid = state.localModels!.grid+ state.people.push({ id: 'peer', email: peer.email, role: 'collaborator', generation: 'first' },+ { id: 'third', email: third.email, role: 'collaborator', generation: 'first' })+ state.people.find(p => p.id === 'owner')!.generation = 'owner-gen'+ const machine = (machineId: string, name: string, contributorId: string, observation: Reading): ContributedMachine => ({ machineId, name, contributorId,+ membershipGeneration: state.people.find(p => p.id === contributorId)!.generation, generation: 'g1', cwd: '/swarm', scope: 'swarm',+ engines: ['claude', 'codex'], maxAgents: 4, paused: false, observation })+ state.machines = [+ machine('owner-studio', 'Mac Studio', 'owner', reading(NOW, [+ { grid, model: MODEL, name: 'DeepSeek 4.1 Flash', contextWindow: 131072, kind: 'local' },+ { grid, model: 'gpt-6.1-sol', kind: 'api' },+ // Shared with owner on another grid: usable on owner's machine alone, never by peer's Buddy.+ { grid: 'friends-grid', model: 'qwen-coder', kind: 'shared' },+ { grid, model: 'starting-model', kind: 'local', starting: true },+ ])),+ machine('peer-mac', 'Peer Mac', 'peer', reading(NOW, [], options.buddyCapabilities)),+ ]+ let next = 0+ const run = (command: Command, actor: Actor = peer, context: Partial<CommandContext> = {}) => {+ const effects = applyCommand(state, actor, command, { operationId: `op${next++}`, now: NOW,+ contribution: { machineOwnerId: 'peer', contributorId: 'peer', hostGrant: null }, ...context })+ state = effects.state+ return effects+ }+ const added = run({ type: 'buddy.create', machineId: 'peer-mac', engine: 'claude' })+ const startId = added.result.startId as string+ const buddyId = run({ type: 'agent.started', startId, harnessId: 'peer-buddy', configuration }).result.agentId as string+ run({ type: 'agent.startSettled', startId, warning: null })+ const chat = swarmBuddyChatId({ id: 'peer', generation: 'first' })+ const buddy = (): Actor => ({ kind: 'agent', agentId: buddyId, machineOwnerId: 'peer' })+ const agent = () => state.agents.find(a => a.id === buddyId)!+ return { run, grid, chat, buddyId, buddy, agent, get state() { return state } }+}+const code = (fn: () => unknown): string | undefined => {+ try { fn() } catch (error) { return (error as { code?: string }).code }+ return undefined+}++describe('asking to switch a Buddy\'s model', () => {+ it('records the request for the Buddy\'s machine, with the window the serving machine reported', () => {+ const f = setup()+ f.run({ type: 'buddy.model', gridModel: MODEL })+ expect(f.agent().modelRequest).toMatchObject({ gridModel: MODEL, gridName: f.grid, contextWindow: 131072, requestedBy: 'peer' })+ })++ it('records a request back to the subscription', () => {+ const f = setup()+ f.agent().gridModel = MODEL+ f.run({ type: 'buddy.model', gridModel: null })+ expect(f.agent().modelRequest).toMatchObject({ gridModel: null, requestedBy: 'peer' })+ })++ it('refuses a model the Swarm does not serve now: unknown, another grid\'s, still starting, or a stale reading', () => {+ for (const model of ['nothing-serves-this', 'qwen-coder', 'starting-model']) {+ const f = setup()+ expect(code(() => f.run({ type: 'buddy.model', gridModel: model }))).toBe('BUDDY_MODEL_UNAVAILABLE')+ expect(f.agent().modelRequest).toBeUndefined()+ }+ const stale = setup()+ stale.state.machines!.find(m => m.machineId === 'owner-studio')!.observation!.receivedAt = NOW - 10 * 60_000+ expect(code(() => stale.run({ type: 'buddy.model', gridModel: MODEL }))).toBe('BUDDY_MODEL_UNAVAILABLE')+ const off = setup()+ off.state.localModels!.enabled = false+ expect(code(() => off.run({ type: 'buddy.model', gridModel: MODEL }))).toBe('BUDDY_MODEL_UNAVAILABLE')+ })++ it('is its owner\'s alone: not another member, not the Swarm\'s owner, not the Buddy itself', () => {+ const f = setup()+ expect(code(() => f.run({ type: 'buddy.model', gridModel: MODEL }, third))).toBe('NO_BUDDY')+ expect(code(() => f.run({ type: 'buddy.model', gridModel: MODEL }, owner))).toBe('NO_BUDDY')+ expect(code(() => f.run({ type: 'buddy.model', gridModel: MODEL }, f.buddy()))).toBe('BUDDY_FORBIDDEN')+ expect(f.agent().modelRequest).toBeUndefined()+ })++ it('refuses a second switch while one is under way', () => {+ const f = setup()+ f.run({ type: 'buddy.model', gridModel: MODEL })+ expect(code(() => f.run({ type: 'buddy.model', gridModel: null }))).toBe('BUDDY_SWITCHING')+ })++ it('refuses a Buddy machine whose Harness cannot switch, one gone quiet, and one outside the Swarm\'s Machines', () => {+ const old = setup({ buddyCapabilities: ['buddySessions', 'swarmBuddy'] })+ expect(code(() => old.run({ type: 'buddy.model', gridModel: MODEL }))).toBe('HOST_OUTDATED')+ const quiet = setup()+ quiet.state.machines!.find(m => m.machineId === 'peer-mac')!.observation!.receivedAt = NOW - 10 * 60_000+ expect(code(() => quiet.run({ type: 'buddy.model', gridModel: MODEL }))).toBe('MACHINE_OFFLINE')+ const only = setup()+ only.state.machines!.find(m => m.machineId === 'peer-mac')!.buddyOnly = true+ expect(code(() => only.run({ type: 'buddy.model', gridModel: MODEL }))).toBe('BUDDY_MODEL_MACHINE')+ })+})++describe('the Buddy\'s machine reporting the switch', () => {+ const asked = (gridModel: string | null = MODEL) => {+ const f = setup()+ f.run({ type: 'buddy.model', gridModel })+ return { f, requestId: f.agent().modelRequest!.id }+ }++ it('lands the Buddy on the model and tells its owner, in their Buddy chat, who serves it', () => {+ const { f, requestId } = asked()+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true }, f.buddy())+ expect(f.agent().gridModel).toBe(MODEL)+ expect(f.agent().modelRequest).toBeUndefined()+ expect(effects.messages.filter(m => m.conversationId === f.chat).map(m => m.text)).toEqual([+ 'Your Buddy now runs on DeepSeek 4.1 Flash, served by Mac Studio.'])+ })++ // Security review 1 of #2787: the machines a line hides are the request's own as well as those serving now.+ it('names no machine to a Buddy reading a failed switch from its subscription, nor one whose machine stopped serving since', () => {+ const buddyRead = (m: unknown) => withoutMachineNames(m as Parameters<typeof withoutMachineNames>[0]).text+ const failed = asked()+ const refused = failed.f.run({ type: 'buddy.modelResult', agentId: failed.f.buddyId, requestId: failed.requestId, ok: false,+ error: "Mac Studio isn't serving DeepSeek 4.1 Flash now" }, failed.f.buddy())+ expect(refused.messages.map(buddyRead).join(' ')).not.toContain('Mac Studio')+ const moved = asked()+ const studio = moved.f.state.machines!.find(m => m.machineId === 'owner-studio')!+ studio.observation!.localModels = studio.observation!.localModels!.filter(l => l.model !== MODEL)+ const landed = moved.f.run({ type: 'buddy.modelResult', agentId: moved.f.buddyId, requestId: moved.requestId, ok: true }, moved.f.buddy())+ expect(landed.messages.map(m => m.text).join(' ')).toContain('Mac Studio')+ expect(landed.messages.map(buddyRead).join(' ')).not.toContain('Mac Studio')+ })++ it('keeps a pending switch out of every Buddy\'s read of the roster: it names the serving machines', () => {+ const { f } = asked()+ const row = visibleState(f.state, f.buddy()).agents.find(a => a.id === f.buddyId)!+ expect(row.modelRequest).toBeUndefined()+ expect(JSON.stringify(row)).not.toContain('Mac Studio')+ expect(visibleState(f.state, peer).agents.find(a => a.id === f.buddyId)!.modelRequest).toMatchObject({ servedBy: ['Mac Studio'] })+ })++ it('records the move on the Buddy\'s thread sessions too, which its machine moved with it', () => {+ const { f, requestId } = asked()+ f.state.agents.push({ ...structuredClone(f.agent()), id: 'session', harnessId: 'h-session', buddySession: { thread: 't', from: 0 } })+ delete f.state.agents.at(-1)!.modelRequest+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true }, f.buddy())+ expect(f.state.agents.find(a => a.id === 'session')!.gridModel).toBe(MODEL)+ f.run({ type: 'buddy.model', gridModel: null })+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy())+ expect(f.state.agents.find(a => a.id === 'session')!.gridModel).toBeUndefined()+ })++ it('names no machine to a Buddy reading these lines: a Buddy reads no machines', () => {+ const { f, requestId } = asked()+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true }, f.buddy())+ const read = effects.messages.map(m => withoutMachineNames(m as unknown as Parameters<typeof withoutMachineNames>[0]).text)+ expect(read).toEqual(['Your Buddy now runs on DeepSeek 4.1 Flash, served by a machine.',+ "peer's Buddy now runs on DeepSeek 4.1 Flash, which your machine serves."])+ })++ it('says which of its thread sessions stayed where they were', () => {+ const { f, requestId } = asked()+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true,+ error: 'A thread session stayed where it was: it was answering' }, f.buddy())+ expect(effects.messages.filter(m => m.conversationId === f.chat).map(m => m.text)).toEqual([+ 'Your Buddy now runs on DeepSeek 4.1 Flash, served by Mac Studio. A thread session stayed where it was: it was answering.'])+ })++ it('says when the conversation was too long and the Buddy started fresh', () => {+ const { f, requestId } = asked()+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true, fresh: true }, f.buddy())+ expect(effects.messages.filter(m => m.conversationId === f.chat).map(m => m.text)).toEqual(['Your Buddy started a fresh session on DeepSeek 4.1 Flash: this conversation is too long '+ + 'for it (128K). Switch back to your subscription to continue the earlier one.'])+ })++ it('names a machine as Desktop does, without its .local', () => {+ const f = setup()+ f.state.machines!.find(m => m.machineId === 'owner-studio')!.name = 'Studio.local'+ f.run({ type: 'buddy.model', gridModel: MODEL })+ expect(f.agent().modelRequest!.servedBy).toEqual(['Studio'])+ })++ it('names a saved API by the member who shares it', () => {+ const f = setup()+ f.run({ type: 'buddy.model', gridModel: 'gpt-6.1-sol' })+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy())+ expect(effects.messages.filter(m => m.conversationId === f.chat).map(m => m.text)).toEqual(["Your Buddy now runs on gpt-6.1-sol, owner's saved API."])+ })++ it('brings the Buddy back to the subscription', () => {+ const f = setup()+ f.agent().gridModel = MODEL+ f.run({ type: 'buddy.model', gridModel: null })+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy())+ expect(f.agent().gridModel).toBeUndefined()+ expect(effects.messages.map(m => m.text)).toEqual(['Your Buddy is back on your subscription.'])+ })++ it('leaves the Buddy where it was on a failure, and says why', () => {+ const { f, requestId } = asked()+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: false,+ error: 'Your Buddy is answering. Try again when it has finished.\n' }, f.buddy())+ expect(f.agent().gridModel).toBeUndefined()+ expect(f.agent().modelRequest).toBeUndefined()+ expect(effects.messages.map(m => m.text)).toEqual([+ "Couldn't switch your Buddy: Your Buddy is answering. Try again when it has finished. It is still on your subscription."])+ })++ it('refuses a result for another request, and from any agent but the Buddy itself', () => {+ const { f, requestId } = asked()+ expect(code(() => f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: 'not-it', ok: true }, f.buddy()))).toBe('STALE_SWITCH')+ const pm: Actor = { kind: 'agent', agentId: 'someone-else', machineOwnerId: 'peer' }+ expect(code(() => f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true }, pm))).not.toBeUndefined()+ expect(code(() => f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId, ok: true }, peer))).not.toBeUndefined()+ expect(f.agent().gridModel).toBeUndefined()+ })++ it('drops a request nobody answered within its lease, and tells the owner', () => {+ const { f } = asked()+ const before = sweepLiveness(f.state, NOW + BUDDY_MODEL_LEASE_MS - 1)+ expect(f.agent().modelRequest).toBeDefined()+ expect(before.map(m => m.text)).not.toContain("Couldn't switch your Buddy: its computer didn't answer. It is still on your subscription.")+ const after = sweepLiveness(f.state, NOW + BUDDY_MODEL_LEASE_MS)+ expect(f.agent().modelRequest).toBeUndefined()+ expect(after.filter(m => m.conversationId === f.chat).map(m => m.text))+ .toEqual(["Couldn't switch your Buddy: its computer didn't answer. It is still on your subscription."])+ })+})++describe('the member who serves the model', () => {+ const landed = (gridModel = MODEL) => {+ const f = setup()+ f.run({ type: 'buddy.model', gridModel })+ return { f, effects: f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy()) }+ }+ const ownerChat = swarmBuddyChatId({ id: 'owner', generation: 'owner-gen' })++ it('is told, in their own Buddy chat, whose Buddy now runs on their machine\'s model', () => {+ const { effects } = landed()+ expect(effects.messages.filter(m => m.conversationId === ownerChat).map(m => m.text))+ .toEqual(["peer's Buddy now runs on DeepSeek 4.1 Flash, which your machine serves."])+ })++ it('is told when it is their saved API', () => {+ const { effects } = landed('gpt-6.1-sol')+ expect(effects.messages.filter(m => m.conversationId === ownerChat).map(m => m.text))+ .toEqual(["peer's Buddy now runs on gpt-6.1-sol, on your saved API."])+ })++ it('is not told about their own Buddy', () => {+ const f = setup()+ f.state.machines!.find(m => m.machineId === 'peer-mac')!.observation!.localModels = [{ grid: f.grid, model: 'peer-model', kind: 'local' }]+ f.run({ type: 'buddy.model', gridModel: 'peer-model' })+ const effects = f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy())+ expect(effects.messages.map(m => m.conversationId)).toEqual([f.chat])+ })+})++describe('a Buddy coming home by itself', () => {+ /** peer's Buddy on DeepSeek, served by owner's Mac Studio. */+ const onModel = () => {+ const f = setup()+ f.run({ type: 'buddy.model', gridModel: MODEL })+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy())+ return f+ }+ const finish = (f: ReturnType<typeof setup>, now = NOW) =>+ f.run({ type: 'buddy.modelResult', agentId: f.buddyId, requestId: f.agent().modelRequest!.id, ok: true }, f.buddy(), { now })++ it('goes back to the subscription when its machine says the model hit a limit', () => {+ const f = onModel()+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())+ expect(f.agent().modelRequest).toMatchObject({ gridModel: null, reason: 'limit' })+ expect(finish(f).messages.map(m => m.text)).toEqual(['DeepSeek 4.1 Flash hit a limit, so your Buddy is back on your subscription.'])+ expect(f.agent().gridModel).toBeUndefined()+ })++ it('goes back when the model keeps failing', () => {+ const f = onModel()+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'model', active: true }, f.buddy())+ expect(f.agent().modelRequest).toMatchObject({ gridModel: null, reason: 'failing' })+ expect(finish(f).messages.map(m => m.text)).toEqual(['DeepSeek 4.1 Flash keeps failing, so your Buddy is back on your subscription.'])+ })++ it('stays put on a limit of its own subscription, and leaves a switch already under way as it is', () => {+ const f = setup()+ f.run({ type: 'agent.alert', agentId: f.buddyId, alert: 'limit', active: true }, f.buddy())+ expect(f.agent().modelRequest).toBeUndefined()+ const g = onModel()+ g.run({ type: 'buddy.model', gridModel: 'gpt-6.1-sol' })+ const pending = g.agent().modelRequest+ g.run({ type: 'agent.alert', agentId: g.buddyId, alert: 'limit', active: true }, g.buddy())+ expect(g.agent().modelRequest).toEqual(pending)+ })++ it('goes back once nobody has served the model for 2 minutes, and not before', () => {+ const f = onModel()+ const studio = f.state.machines!.find(m => m.machineId === 'owner-studio')!+ const peerMac = f.state.machines!.find(m => m.machineId === 'peer-mac')!+ studio.observation!.localModels = studio.observation!.localModels!.filter(l => l.model !== MODEL)+ const at = (now: number) => { peerMac.observation!.receivedAt = now; studio.observation!.receivedAt = now; return sweepLiveness(f.state, now) }+ at(NOW + 1000)+ expect(f.agent().modelRequest).toBeUndefined()+ at(NOW + 1000 + BUDDY_MODEL_GONE_MS - 1)+ expect(f.agent().modelRequest).toBeUndefined()+ at(NOW + 1000 + BUDDY_MODEL_GONE_MS)+ expect(f.agent().modelRequest).toMatchObject({ gridModel: null, reason: 'gone' })+ expect(finish(f, NOW + 1000 + BUDDY_MODEL_GONE_MS).messages.map(m => m.text))+ .toEqual(['Nobody serves DeepSeek 4.1 Flash now, so your Buddy is back on your subscription.'])+ })++ it('stays when the model is served again within the 2 minutes', () => {+ const f = onModel()+ const studio = f.state.machines!.find(m => m.machineId === 'owner-studio')!+ const peerMac = f.state.machines!.find(m => m.machineId === 'peer-mac')!+ const served = studio.observation!.localModels!+ const at = (now: number) => { peerMac.observation!.receivedAt = now; studio.observation!.receivedAt = now; return sweepLiveness(f.state, now) }+ studio.observation!.localModels = served.filter(l => l.model !== MODEL)+ at(NOW + 1000)+ studio.observation!.localModels = served+ at(NOW + 1000 + 60_000)+ studio.observation!.localModels = served.filter(l => l.model !== MODEL)+ at(NOW + 1000 + BUDDY_MODEL_GONE_MS)+ expect(f.agent().modelRequest).toBeUndefined()+ })+})++describe('a Buddy\'s new thread session', () => {+ it('starts on the shared model its Buddy runs on, on the Swarm\'s grid', () => {+ const f = setup()+ f.agent().gridModel = MODEL+ f.agent().configuration = { ...configuration, model: MODEL }+ f.run({ type: 'message.send', conversationId: f.chat, text: 'Look into the CPU spike', replyTo: null, recipientIds: [], newSession: true })+ const request = f.state.starts!.at(-1)!.request+ expect(request).toMatchObject({ gridModel: MODEL, gridName: f.grid })+ expect(request.model).toBeUndefined()+ expect(request.effort).toBeUndefined()+ })++ it('starts on the subscription when nobody serves that model now, never naming the grid model as a Claude model', () => {+ const f = setup()+ f.agent().gridModel = 'gone-model'+ f.agent().configuration = { ...configuration, model: 'gone-model' }+ f.run({ type: 'message.send', conversationId: f.chat, text: 'Look into the CPU spike', replyTo: null, recipientIds: [], newSession: true })+ const request = f.state.starts!.at(-1)!.request+ expect(request.gridModel).toBeUndefined()+ expect(request.model).toBeUndefined()+ })+})diff --git a/backend/src/superTabs/buddyModel.ts b/backend/src/superTabs/buddyModel.tsnew file mode 100644index 000000000..cb15e8b08--- /dev/null+++ b/backend/src/superTabs/buddyModel.ts@@ -0,0 +1,208 @@+/**+ * A person switches their Buddy between their own subscription and a model the Swarm's grid serves, and back (task #2354,+ * docs/plans/2026-11-03-buddy-model-switch-design.md). The person asks here; the Buddy's machine carries it out through its+ * own daemon's model switch (cli superTabs/buddyModel.ts) and reports; the outcome is one line in the person's Buddy chat.+ *+ * The models offered are exactly those a routed start may run on (machines.ts servedLocalModels): on this Swarm's grid, in a+ * fresh reading of a machine in its Machines list. Never a model of another grid a member reads, which only that member's+ * machine can reach.+ *+ * Whoever serves the model is told whose Buddy runs on it, and their limits hold (PRODUCT.md, Contribution): a model that+ * hits a limit, keeps failing or is no longer served sends the Buddy back to its owner's subscription.+ */+import { isSwarmBuddy, openSwarmBuddyChat, swarmBuddyChatId } from './buddies.js'+import { machineOffline, servedLocalModels } from './machines.js'+import { fail, person, type Actor, type Agent, type SuperTabState } from './model.js'+import { usernameOf } from './usernames.js'++/** What a host that switches a Buddy's model says it does (cli superTabs/machines.ts CAPABILITIES). */+export const BUDDY_MODEL_CAPABILITY = 'buddyModel'+/** A switch the Buddy's machine never reported within this long is dropped: the Buddy stays where it was. */+export const BUDDY_MODEL_LEASE_MS = 10 * 60_000+/** How long nobody serves the model a Buddy runs on before it is sent home: a machine's reading may lapse for a moment. */+export const BUDDY_MODEL_GONE_MS = 2 * 60_000++/** One line the switch writes: in a Buddy chat, naming the machines a Buddy reading it must not learn (store.ts+ * withoutMachineNames). */+export interface ModelLine { conversationId: string; text: string; machines: string[] }++const personName = (state: SuperTabState, id: string) =>+ usernameOf(state, id) ?? state.people.find(p => p.id === id)?.email ?? 'A member'++/** Who serves [gridModel] now on the Swarm's grid: each serving machine's name and its member, and whether it is an API. */+function servers(state: SuperTabState, gridModel: string, now: number) {+ return servedLocalModels(state, now).filter(l => l.model === gridModel).map(l => {+ const pool = state.machines!.find(m => m.machineId === l.machineId)!+ // As Desktop names it (identity.dart superTabMachineName), so the picker and the chat line agree.+ return { reading: l, machine: (pool.name ?? 'a machine').replace(/(.)\.local$/i, '$1'), personId: pool.contributorId, api: l.kind === 'api' }+ })+}++/** A model as the person was shown it: its name, who serves it (machines by name, a saved API by its member), and the smallest+ * window a serving machine reported, so the conversation is measured against the tightest one the grid may pick. */+function served(state: SuperTabState, gridModel: string, now: number) {+ const found = servers(state, gridModel, now)+ if (!found.length) return null+ const servedBy = [...new Set(found.map(s => s.api ? `${personName(state, s.personId)}'s saved API` : s.machine))]+ const machines = [...new Set(found.filter(s => !s.api).map(s => s.machine))]+ const windows = found.flatMap(s => typeof s.reading.contextWindow === 'number' ? [s.reading.contextWindow] : [])+ return { name: found.find(s => s.reading.name)?.reading.name ?? gridModel, servedBy, machines,+ ...(windows.length ? { contextWindow: Math.min(...windows) } : {}) }+}++/** The person's own running Buddy for the Swarm: never a thread session, never someone else's. */+function ownBuddy(state: SuperTabState, actor: Actor): Agent {+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person switches their own Buddy.', 403)+ const me = person(state, actor.userId)+ return mainBuddy(state, me.id, me.generation) ?? fail('NO_BUDDY', 'You have no Buddy running.', 404)+}+const mainBuddy = (state: SuperTabState, personId: string, generation: string) =>+ state.agents.find(a => isSwarmBuddy(a) && a.buddyOf!.personId === personId && a.buddyOf!.generation === generation && !a.buddySession)++/** Whether the Buddy's machine can carry a switch out now: in the Swarm's Machines list, reporting, and able to. */+function switchable(state: SuperTabState, buddy: Agent, now: number): { ok: true } | { ok: false; code: string; message: string } {+ const pool = state.machines?.find(m => m.machineId === buddy.machineId)+ const name = pool?.name ?? 'your computer'+ // A Buddy-only machine never joins the Swarm's grid (read/hostRows.ts), so nothing shared there can reach it.+ if (!pool || pool.buddyOnly) return { ok: false, code: 'BUDDY_MODEL_MACHINE', message: `Add ${name} to the Swarm's Machines to use shared models.` }+ if (machineOffline(pool, now)) return { ok: false, code: 'MACHINE_OFFLINE', message: `Wait for a fresh reading from ${name}.` }+ if (!pool.observation!.capabilities?.includes(BUDDY_MODEL_CAPABILITY)) return { ok: false, code: 'HOST_OUTDATED', message: `Update Harness on ${name} to switch your Buddy's model.` }+ return { ok: true }+}++export function askBuddyModel(state: SuperTabState, actor: Actor, gridModel: string | null, requestId: string, now: number): void {+ const buddy = ownBuddy(state, actor)+ const can = switchable(state, buddy, now)+ if (!can.ok) fail(can.code, can.message, 409)+ if (buddy.modelRequest) fail('BUDDY_SWITCHING', 'Your Buddy is already switching.', 409)+ const shown = gridModel === null ? {} : served(state, gridModel, now)+ if (!shown) fail('BUDDY_MODEL_UNAVAILABLE', 'Nobody in the Swarm serves that model now.', 409)+ // The grid its machine moves it onto (agent_retarget's gridName): the Swarm's own, the one the models were checked on.+ buddy.modelRequest = { id: requestId, gridModel, ...(gridModel === null ? {} : { gridName: state.localModels!.grid }), ...shown,+ requestedBy: buddy.buddyOf!.personId, at: new Date(now).toISOString() }+}++/** Sends [buddy]'s main Buddy home to its owner's subscription by itself, unless it is on it, already switching, or its machine+ * cannot carry it out (then its own lines say so: its model fails in its terminal, and the person can switch it). */+export function sendBuddyHome(state: SuperTabState, from: Agent, reason: 'limit' | 'failing' | 'gone', requestId: string, now: number): void {+ if (!from.buddyOf) return+ const buddy = mainBuddy(state, from.buddyOf.personId, from.buddyOf.generation)+ if (!buddy?.gridModel || buddy.modelRequest || !switchable(state, buddy, now).ok) return+ buddy.modelRequest = { id: requestId, gridModel: null, name: current(state, buddy, now), reason,+ requestedBy: buddy.buddyOf!.personId, at: new Date(now).toISOString() }+}++const windowWords = (tokens: number) => `${Math.round(tokens / 1024)}K`+const clean = (text: string) => text.replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/[.\s]+$/, '').trim()+const HOME_WORDS = { limit: 'hit a limit', failing: 'keeps failing' } as const++/** What the Buddy is on now, as its owner reads it. */+function current(state: SuperTabState, buddy: Agent, now: number): string {+ if (!buddy.gridModel) return 'your subscription'+ return served(state, buddy.gridModel, now)?.name ?? buddy.gridModelName ?? buddy.gridModel+}++/** The machines any line about [request] must keep from a Buddy reading it (store.ts withoutMachineNames): those the owner was+ * shown when asking, which a host's refusal repeats, and those serving the request's model or the Buddy's own now. Worked out+ * from the request too, since a machine may stop serving between the ask and the answer (security review 1 of #2787). */+function hiddenMachines(state: SuperTabState, buddy: Agent, request: NonNullable<Agent['modelRequest']>, now: number): string[] {+ const serving = [request.gridModel, buddy.gridModel].flatMap(model => model ? servers(state, model, now).filter(s => !s.api).map(s => s.machine) : [])+ return [...new Set([...(request.machines ?? []), ...serving])]+}++/** The Buddy's machine reports the switch it carried out: the Buddy is on the model, or stays where it was. The first line is+ * the owner's; then one for each other member who serves the model it landed on. */+export function buddyModelResult(state: SuperTabState, actor: Actor,+ command: { agentId: string; requestId: string; ok: boolean; fresh?: boolean; error?: string }, now: number): ModelLine[] {+ const buddy = state.agents.find(a => a.id === command.agentId)+ if (!buddy || actor.kind !== 'agent' || actor.agentId !== buddy.id || !isSwarmBuddy(buddy)) fail('BUDDY_FORBIDDEN', 'Only the Buddy\'s machine reports its switch.', 403)+ const request = buddy.modelRequest+ if (!request || request.id !== command.requestId) fail('STALE_SWITCH', 'This is not the switch your Buddy was asked for.', 409)+ const hidden = hiddenMachines(state, buddy, request, now)+ delete buddy.modelRequest+ const owner = buddy.buddyOf!+ const conversationId = swarmBuddyChatId({ id: owner.personId, generation: owner.generation })+ const mine = (text: string): ModelLine[] => [{ conversationId, text, machines: hidden }]+ if (!command.ok) {+ return mine(`Couldn't switch your Buddy: ${clean(command.error ?? '') || 'it failed'}. It is still on ${current(state, buddy, now)}.`)+ }+ delete buddy.gridModelUnservedSince+ // Its machine moved its thread sessions with it (cli superTabs/buddyModel.ts): what they run on is recorded the same way, so+ // costs and the serving member's "Used by" read it right.+ const sessions = state.agents.filter(a => a.buddySession && a.buddyOf?.personId === owner.personId && a.buddyOf.generation === owner.generation)+ for (const session of sessions) {+ if (request.gridModel === null) delete session.gridModel+ else session.gridModel = request.gridModel+ }+ if (request.gridModel === null) {+ delete buddy.gridModel+ delete buddy.gridModelName+ const left = request.name ?? 'Its model'+ return mine(request.reason === 'gone' ? `Nobody serves ${left} now, so your Buddy is back on your subscription.`+ : request.reason ? `${left} ${HOME_WORDS[request.reason]}, so your Buddy is back on your subscription.`+ : 'Your Buddy is back on your subscription.')+ }+ buddy.gridModel = request.gridModel+ const name = request.name ?? request.gridModel+ buddy.gridModelName = name+ const found = servers(state, request.gridModel, now)+ let text: string+ if (command.fresh) {+ const window = request.contextWindow ? ` (${windowWords(request.contextWindow)})` : ''+ text = `Your Buddy started a fresh session on ${name}: this conversation is too long for it${window}. Switch back to your subscription to continue the earlier one.`+ } else {+ const shown = request.servedBy ?? []+ const by = shown.every(s => s.endsWith("'s saved API")) ? shown.join(', ') : `served by ${shown.join(', ')}`+ text = `Your Buddy now runs on ${name}${shown.length ? `, ${by}` : ''}.`+ }+ // Seen (PRODUCT.md, Contribution): each other member serving it hears whose Buddy runs on their capacity, in their own chat.+ const told = new Set<string>([owner.personId])+ const theirs: ModelLine[] = []+ for (const s of found) {+ if (told.has(s.personId)) continue+ told.add(s.personId)+ const member = state.people.find(p => p.id === s.personId)+ if (!member) continue+ // No machine named: their own Buddy reads this chat, and a Buddy reads no machines.+ theirs.push({ conversationId: openSwarmBuddyChat(state, member).id, machines: [],+ text: `${personName(state, owner.personId)}'s Buddy now runs on ${name}, ${s.api ? 'on your saved API' : 'which your machine serves'}.` })+ }+ // The Buddy moved; a thread session that could not is named, so its owner knows where that thread's answers come from.+ const stayed = clean(command.error ?? '')+ return [...mine(stayed ? `${text} ${stayed}.` : text), ...theirs]+}++/** Requests nobody answered within their lease, dropped, each with the line its owner reads. */+export function expiredModelRequests(state: SuperTabState, now: number): Array<{ buddy: Agent; requestId: string } & ModelLine> {+ const out: Array<{ buddy: Agent; requestId: string } & ModelLine> = []+ for (const buddy of state.agents) {+ const request = buddy.modelRequest+ if (!request || !buddy.buddyOf || now < Date.parse(request.at) + BUDDY_MODEL_LEASE_MS) continue+ delete buddy.modelRequest+ out.push({ buddy, requestId: request.id, conversationId: swarmBuddyChatId({ id: buddy.buddyOf.personId, generation: buddy.buddyOf.generation }),+ machines: hiddenMachines(state, buddy, request, now),+ text: `Couldn't switch your Buddy: its computer didn't answer. It is still on ${current(state, buddy, now)}.` })+ }+ return out+}++/** Buddies on a model nobody has served for BUDDY_MODEL_GONE_MS are sent home; one served again is unmarked. */+export function unservedBuddyModels(state: SuperTabState, now: number, requestId: (buddy: Agent) => string): void {+ for (const buddy of state.agents) {+ if (!buddy.gridModel || buddy.buddySession || !isSwarmBuddy(buddy)) continue+ if (servers(state, buddy.gridModel, now).length) { delete buddy.gridModelUnservedSince; continue }+ buddy.gridModelUnservedSince ??= now+ if (now - buddy.gridModelUnservedSince < BUDDY_MODEL_GONE_MS) continue+ sendBuddyHome(state, buddy, 'gone', requestId(buddy), now)+ if (buddy.modelRequest) delete buddy.gridModelUnservedSince+ }+}++/** A Buddy thread session's model (commands.ts message.send newSession): the shared one its Buddy runs on while it is served, or+ * its owner's subscription with Claude Code's own default, never a grid model's name handed to Claude Code as its own. */+export function sessionModel(state: SuperTabState, main: Agent, now: number): { gridModel?: string; gridName?: string; model?: string; effort?: string } {+ if (main.gridModel) {+ return servers(state, main.gridModel, now).length ? { gridModel: main.gridModel, gridName: state.localModels!.grid } : {}+ }+ return { ...(main.configuration.model ? { model: main.configuration.model } : {}), ...(main.configuration.effort ? { effort: main.configuration.effort } : {}) }+}diff --git a/backend/src/superTabs/closedAgents.ts b/backend/src/superTabs/closedAgents.tsindex 57c93803f..20f9b1b8b 100644--- a/backend/src/superTabs/closedAgents.ts+++ b/backend/src/superTabs/closedAgents.ts@@ -91,7 +91,7 @@ function keepRecord(state: SuperTabState, target: Agent, now: number): void {return}const { downSince: _down, lostTask: _lost, releaseId: _release, idleStop: _idle, idleNoticedAt: _noticed, workDecision: _decision,- switchRequest: _switch, switchLanded: _landed, alerting: _alerting, ...agent } = target+ switchRequest: _switch, switchLanded: _landed, modelRequest: _model, alerting: _alerting, ...agent } = targetconst mine = others.filter(r => r.machineId === target.machineId)const over = mine.length + 1 - REMOVED_KEPTconst dropped = new Set(over > 0 ? [...mine].sort((a, b) => a.removedAt - b.removedAt).slice(0, over) : [])diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex f7381428f..69d78f563 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -50,6 +50,7 @@ import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRoimport { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, proposalTitle, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'+import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'import { launchRefusedLine, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, LEAD_CAPABILITY, placeLead } from './leadStart.js'import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'@@ -240,6 +241,11 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('buddy.rename'), conversationId: id, name: z.string().max(200).nullable() }).strict(),// A person ends a thread session of their own Buddy chat (buddySessions.ts): `ended` from their app, `idle` and `stopped` from// their machine's host, which acts as them. Idempotent: a thread with no session is told so and nothing changes.+ // The person's own Buddy onto a model the Swarm's grid serves now, or back to their subscription (null): buddyModel.ts.+ z.object({ type: z.literal('buddy.model'), gridModel: z.string().trim().min(1).max(200).nullable() }).strict(),+ // What the Buddy's machine reports once it carried the request out: `fresh` when the conversation was too long for the model.+ z.object({ type: z.literal('buddy.modelResult'), agentId: id, requestId: id, ok: z.boolean(), fresh: z.boolean().optional(),+ error: z.string().max(300).optional() }).strict(),z.object({ type: z.literal('buddy.sessionEnd'), conversationId: id, thread: id, reason: z.enum(['ended', 'idle', 'stopped', 'maintenance']) }).strict(),// The PM's private line to one person, in their Buddy chat of its project: Buddies replaced Chat with PM (Ken, 10-29).z.object({ type: z.literal('person.tell'), personId: id, text: z.string().trim().min(1).max(32_000) }).strict(),@@ -347,6 +353,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'agent.start': ['request.name', 'overrideReason'],'agent.startFailed': ['error'],'agent.switchResult': ['error'],+ 'buddy.modelResult': ['error'],'agent.switchHandoff': ['note'],'agent.startSettled': ['warning'],'conversation.create': ['title', 'brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'task.review.focus', 'checks[].description'],@@ -1163,7 +1170,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const folder = project ? { cwd: projectFolder(pool, project), worktree: true, buddyNarrow: true as const }: { cwd: buddyHomeFolder(pool, me), worktree: false, buddyScope: 'swarm' as const, buddyProjects: buddyProjectsOn(state, pool, me) }const request: AgentStartRequest = { conversationId: chat.id, machineId: main.machineId, engine: main.configuration.engine,- ...(main.configuration.model ? { model: main.configuration.model } : {}), ...(main.configuration.effort ? { effort: main.configuration.effort } : {}),+ // The model its Buddy runs on: a shared one starts on the Swarm's grid (buddyModel.ts).+ ...sessionModel(state, main, context.now),name: main.displayName ?? main.name, ...folder, requirements: BUDDY_REQUIREMENTS,buddyOf: { personId: owner.id, generation: owner.generation },// The main chat's sequence before this message: the session's excerpt reads up to it (buddySessions.ts sessionContext).@@ -1466,6 +1474,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const resumeAt = command.alert === 'limit' && command.resetAt && Date.parse(command.resetAt) > context.now? agent(state, command.agentId).limitedUntil ?? undefined : undefinedeffects.messages.push(...loseTasks(state, context.now, worker => worker.id === command.agentId, resumeAt))+ // A Buddy on a shared model goes back to its owner's subscription: the member serving it set that limit (PRODUCT.md,+ // Contribution, Safe), and a model that keeps failing answers nothing.+ sendBuddyHome(state, agent(state, command.agentId), command.alert === 'limit' ? 'limit' : 'failing', operationId, context.now)}break}@@ -2310,6 +2321,19 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,case 'buddy.rename':renameBuddy(state, actor, readConversation(state, actor, command.conversationId), command.name, context.buddyNames)break+ case 'buddy.model':+ askBuddyModel(state, actor, command.gridModel, operationId, context.now)+ break+ case 'buddy.modelResult': {+ // The machines a line names leave a Buddy's read of it (store.ts withoutMachineNames): a Buddy reads no machines.+ buddyModelResult(state, actor, command, context.now).forEach((line, i) => {+ const source = { ...SYSTEM_ROW, ...(line.machines.length ? { machines: line.machines } : {}) }+ if (i === 0) message(line.conversationId, line.text, [], null, source)+ else effects.messages.push({ id: stableId(operationId, 'buddy-model', String(i)), conversationId: line.conversationId, author: sender,+ text: line.text, replyTo: null, recipients: [], source })+ })+ break+ }case 'buddy.sessionEnd': {if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person ends their own Buddy session.', 403)const chat = readConversation(state, actor, command.conversationId)diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex bdd37d825..fd92bbbaa 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -8,7 +8,7 @@ import { askedModel, coordinatorCopy, failureNotice, failureRecipients, leadPickimport { leadOf, toLead } from './terminal.js'import { dropIdleBuddyMachines, MACHINE_FRESH_MS } from './machines.js'import { leadStartFailed } from './leadStart.js'-import { staleSwitches } from './tidy.js'+import { staleModelRequests, staleSwitches } from './tidy.js'import { ledProject, projectsOf } from './projects.js'import { coordinatorNameOf } from './instructions.js'import { waitedOn } from './leaderboard/record.js'@@ -374,7 +374,7 @@ function leadNotice(state: SuperTabState, start: AgentStart, text: string | null/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and* every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */export function sweepLiveness(state: SuperTabState, now: number): MessageDraft[] {- const drafts = [...loseTasks(state, now), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now)]+ const drafts = [...loseTasks(state, now), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now), ...staleModelRequests(state, now)]// A Buddy start that timed out may have been the last on its Buddy-only machine (security review 1 of #2234).dropIdleBuddyMachines(state, now)return draftsdiff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 1b7a9f6eb..570be3b1f 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -75,6 +75,16 @@ export interface Agent {* it still tells the machine owner who asked. */switchLanded?: { id: string; requestedBy: string; candidateAgentId?: string }switchRequest?: { id: string; engine: string; profileId: string; targetMachineId?: string; model?: string; effort?: string; requestedBy: string; at: string; claimedUntil?: string }+ /** A Buddy's owner asked its machine to move it onto a model on the Swarm's grid, or back to their subscription (null)+ * (buddyModel.ts). What they were shown is kept for the line the result writes: the model's name, who serves it and its+ * window, the smallest any serving machine reported. One at a time; the result or the liveness sweep's lease drops it. */+ modelRequest?: { id: string; gridModel: string | null; gridName?: string; name?: string; servedBy?: string[]; machines?: string[]; contextWindow?: number; requestedBy: string; at: string+ /** Set when the Swarm sent the Buddy home by itself: the model hit a limit, kept failing, or nobody served it. */+ reason?: 'limit' | 'failing' | 'gone' }+ /** When the liveness sweep first found nobody serving the Buddy's `gridModel` (ms): two minutes on, it is sent home. */+ gridModelUnservedSince?: number+ /** The name its owner was shown for the Buddy's `gridModel`, for the lines after nobody serves it any more. */+ gridModelName?: string/** The account it runs in on its machine once a switch moved it; absent for the machine's default account. */profileId?: string/** Captured from the original Swarm launch, never inferred from a later live session with the same id. */@@ -341,6 +351,8 @@ export interface Conversation {lastPersonSequence?: number/** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */pullRequestUrls?: string[]+ /** What its Engineer was already told of each linked pull request, newest first (pullRequestEvents.ts): absent until read. */+ pullRequestEvents?: Record<string, string[]>/** Its messages drawn as live cards: its task and each linked pull request (cards.ts). Absent until its first card. */cards?: import('./cards.js').GroupCards/** The last sequence given to a message here. Each conversation numbers its own messages (store by parts). */@@ -645,8 +657,11 @@ export const agentWithoutMachine = <T extends Pick<Agent, 'machineId' | 'harness* person's, so it goes too (delta review 1 of #2258), and so does its host grant, which under an older share policy names* its contributor's email (lib/machineSharePolicy.ts; final check of #2258). */export const agentForBuddy = <T extends Pick<Agent, 'id' | 'machineId' | 'harnessId' | 'machineOwnerId' | 'contributorId' | 'membershipGeneration' | 'hostGrant' | 'teamAccount'- | 'replacement' | 'lostTask'>>(target: T, buddyId: string): T => {- const bare = agentWithoutMachine(target)+ | 'replacement' | 'lostTask' | 'modelRequest'>>(target: T, buddyId: string): T => {+ // A pending model switch names the machines serving the model (buddyModel.ts); its host reads it from its own rows, never here+ // (security review 1 of #2787).+ const { modelRequest: _switching, ...unswitched } = target+ const bare = agentWithoutMachine(unswitched as T)if (target.id === buddyId) return bareconst { teamAccount: _team, ...rest } = barereturn { ...rest, machineOwnerId: '', contributorId: '', membershipGeneration: '', hostGrant: null } as Tdiff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex bf09d99eb..c844cb5b3 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -13,7 +13,7 @@ const assignment: Required<Assignment> = {}const conversation: Required<Conversation> = {id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',- task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', teamWritten: true, step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, lastPersonSequence: 0, pullRequestUrls: [], cards: {},+ task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', teamWritten: true, step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, lastPersonSequence: 0, pullRequestUrls: [], pullRequestEvents: {}, cards: {},messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], buddyDownTold: true, liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 340524f5b..a6af96c23 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status','assignment.lost'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],- unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp',+ unread: ['number', 'brief', 'reviewOf', 'teamWritten', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'lastPersonSequence', 'pullRequestUrls', 'pullRequestEvents', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt', 'assignment.toldEngineerAt','assignment.handoffs', 'assignment.verdicts'],} as constdiff --git a/backend/src/superTabs/pullRequestEvents.test.ts b/backend/src/superTabs/pullRequestEvents.test.tsnew file mode 100644index 000000000..416721fcb--- /dev/null+++ b/backend/src/superTabs/pullRequestEvents.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it } from 'vitest'+import { pullRequestEvents, SEEN_KEPT, type PullRequestWatch } from './pullRequestEvents.js'++// Dee, #1891: what GitHub says about a task's pull request becomes one message per event for its Engineer.+const URL = 'https://github.com/acme/app/pull/12'+const HEAD = 'abc1234def5678'+const NOW = Date.parse('2026-11-03T09:00:00.000Z')+const watch = (patch: Partial<PullRequestWatch> = {}): PullRequestWatch => ({ url: URL, number: 12, state: 'open', draft: false, head: HEAD,+ base: 'main', mergeable: true, checkRuns: [], checkSuites: [], reviews: [], comments: [], ...patch })+const run = (name: string, conclusion: string | null, completedAt: number | null = NOW - 1_000) =>+ ({ name, status: conclusion ? 'completed' : 'in_progress', conclusion, completedAt })+/** Seen before: the pull request was read once already, a draft marked ready long ago. */+const SEEN = [`ready:${NOW - 3_600_000}`]+const events = (w: PullRequestWatch, seen: readonly string[] = SEEN, bot: string | null = 'harness[bot]') => pullRequestEvents(w, seen, bot, NOW)++describe('pullRequestEvents', () => {+ it('posts CI failed with the failing job names', () => {+ const { events: posted } = events(watch({ checkRuns: [run('build (ubuntu)', 'failure'), run('lint', 'success'), run('ci/required', 'failure'), run('test', null)] }))+ expect(posted).toEqual([{ key: `ci-red:${HEAD}`, text: `CI failed on your pull request #12 (head abc1234): build (ubuntu), ci/required. ${URL}` }])+ })++ it('posts CI passed once every suite is done', () => {+ const green = watch({ checkRuns: [run('build', 'success'), run('docs', 'skipped')], checkSuites: [{ status: 'completed', runs: 2 }, { status: 'queued', runs: 0 }] })+ expect(events(green).events).toEqual([{ key: `ci-green:${HEAD}`, text: `CI passed on your pull request #12 (head abc1234). ${URL}` }])+ expect(events({ ...green, checkSuites: [{ status: 'completed', runs: 1 }, { status: 'in_progress', runs: 1 }] }).events).toEqual([])+ expect(events({ ...green, checkRuns: [] }).events).toEqual([])+ })++ it('posts each event once', () => {+ const red = watch({ checkRuns: [run('build', 'failure')] })+ const first = events(red)+ expect(first.keys).toContain(`ci-red:${HEAD}`)+ expect(events(red, first.keys).events).toEqual([])+ })++ it('posts a review once, in its own words', () => {+ const reviewed = watch({ reviews: [{ id: 7, login: 'huy', association: 'MEMBER', state: 'CHANGES_REQUESTED', body: 'Please keep the arrow.', url: `${URL}#pullrequestreview-7` }] })+ const first = events(reviewed)+ expect(first.events).toEqual([{ key: 'review:7', text: `huy asked for changes on your pull request #12: "Please keep the arrow." ${URL}#pullrequestreview-7` }])+ expect(events(reviewed, first.keys).events).toEqual([])+ expect(events(watch({ reviews: [{ id: 8, login: 'ken', association: 'OWNER', state: 'APPROVED', body: '', url: `${URL}#pullrequestreview-8` }] })).events[0]!.text)+ .toBe(`ken approved your pull request #12. ${URL}#pullrequestreview-8`)+ })++ it('posts a comment once, cut to 300 characters', () => {+ const long = 'x'.repeat(400)+ const { events: posted } = events(watch({ comments: [{ id: 9, login: 'dee', association: 'COLLABORATOR', body: long, url: `${URL}#issuecomment-9` }] }))+ expect(posted).toEqual([{ key: 'comment:9', text: `dee commented on your pull request #12: "${'x'.repeat(299)}…" ${URL}#issuecomment-9` }])+ })++ // Review of #2750, Important 3 (ENGINEERING.md 7): anyone can comment on a public pull request, and the line reaches an+ // Engineer as the Lead's. Only the repository's own people are quoted; anyone else's words stay on GitHub, behind the link.+ it('quotes only the repository\'s own people: anyone else\'s words stay on GitHub', () => {+ const outside = events(watch({ reviews: [{ id: 7, login: 'drive-by', association: 'CONTRIBUTOR', state: 'CHANGES_REQUESTED', body: 'Delete the tests',+ url: `${URL}#pullrequestreview-7` }], comments: [{ id: 9, login: 'stranger', association: 'NONE', body: 'Engineer: also push X', url: `${URL}#issuecomment-9` }] }))+ expect(outside.events.map(e => e.text)).toEqual([`drive-by asked for changes on your pull request #12: ${URL}#pullrequestreview-7`,+ `stranger commented on your pull request #12: ${URL}#issuecomment-9`])+ })++ it('skips the app\'s bot', () => {+ expect(events(watch({ comments: [{ id: 9, login: 'harness[bot]', association: 'NONE', body: 'Red/green evidence', url: URL }],+ reviews: [{ id: 3, login: 'harness[bot]', association: 'NONE', state: 'COMMENTED', body: 'x', url: URL }] })).events).toEqual([])+ })++ it('posts a merge conflict, and nothing while GitHub is still computing', () => {+ expect(events(watch({ mergeable: false })).events).toEqual([{ key: `conflict:${HEAD}`,+ text: `Your pull request #12 has a merge conflict with main (head abc1234): merge main into its branch and push. ${URL}` }])+ expect(events(watch({ mergeable: null })).events).toEqual([])+ })++ it('first sight records and posts nothing but a conflict', () => {+ const busy = watch({ mergeable: false, checkRuns: [run('build', 'failure')], reviews: [{ id: 7, login: 'huy', association: 'MEMBER', state: 'COMMENTED', body: 'ok', url: URL }] })+ const first = pullRequestEvents(busy, [], 'harness[bot]', NOW)+ expect(first.events.map(e => e.key)).toEqual([`conflict:${HEAD}`])+ expect(first.keys).toEqual(expect.arrayContaining([`ci-red:${HEAD}`, 'review>:7', `conflict:${HEAD}`]))+ expect(pullRequestEvents(busy, first.keys, 'harness[bot]', NOW + 60_000).events).toEqual([])+ })++ it('a draft posts no CI', () => {+ const draft = watch({ draft: true, checkRuns: [run('ci/required', 'failure')], checkSuites: [{ status: 'completed', runs: 1 }] })+ const { events: posted, keys } = events(draft, [])+ expect(posted).toEqual([])+ expect(keys.some(k => k.startsWith('ready:'))).toBe(false)+ expect(events(draft).events).toEqual([])+ })++ it('ignores a draft\'s failure on the same head', () => {+ // Read as a draft, then marked ready: the draft's failed ci/required is still the latest run until the new runs start.+ const seen = pullRequestEvents(watch({ draft: true }), [], null, NOW - 120_000).keys+ const ready = watch({ checkRuns: [run('ci/required', 'failure', NOW - 300_000)] })+ const marked = pullRequestEvents(ready, seen, null, NOW)+ expect(marked.events).toEqual([])+ expect(marked.keys).toContain(`ready:${NOW}`)+ // The ready run's own failure is news.+ expect(pullRequestEvents(watch({ checkRuns: [run('ci/required', 'failure', NOW + 30_000)] }), marked.keys, null, NOW + 60_000).events.map(e => e.key))+ .toEqual([`ci-red:${HEAD}`])+ })++ // Review of #2750, Important 1: push to a draft, then mark it ready, within one minute. The new head was never read as a+ // draft, and the draft run's failed ci/required is still the latest of its name.+ it('ignores a draft\'s failure when a new head and ready land in the same minute', () => {+ const drafted = pullRequestEvents(watch({ draft: true, head: 'aaaaaaa1111' }), [], null, NOW - 120_000).keys+ const ready = watch({ head: 'bbbbbbb2222', checkRuns: [run('ci/required', 'failure', NOW - 30_000)] })+ expect(pullRequestEvents(ready, drafted, null, NOW).events).toEqual([])+ })++ // Review of #2750, Minor: ready, back to a draft, ready again on the same head: the second draft spell's failure is the draft's too.+ it('a second draft spell is ready again from its own moment', () => {+ let seen = pullRequestEvents(watch({ draft: true }), [], null, NOW - 600_000).keys+ seen = pullRequestEvents(watch(), seen, null, NOW - 500_000).keys+ seen = pullRequestEvents(watch({ draft: true }), seen, null, NOW - 400_000).keys+ expect(pullRequestEvents(watch({ checkRuns: [run('ci/required', 'failure', NOW - 300_000)] }), seen, null, NOW).events).toEqual([])+ })++ it('a new head is news again', () => {+ const red = events(watch({ mergeable: false, checkRuns: [run('build', 'failure')] }))+ const next = watch({ head: 'fff0000aaa', mergeable: false, checkRuns: [run('build', 'failure', NOW + 30_000)] })+ expect(pullRequestEvents(next, red.keys, null, NOW + 60_000).events.map(e => e.key)).toEqual(['ci-red:fff0000aaa', 'conflict:fff0000aaa'])+ })++ // Review of #2750, Important 2: from about the 49th comment the newest fell past the kept keys, and nothing posted again.+ it('posts every new comment however many came before', () => {+ let seen = events(watch()).keys+ for (let count = 1; count <= 60; count++) {+ const comments = Array.from({ length: count }, (_, i) => ({ id: i + 1, login: 'dee', association: 'MEMBER', body: `note ${i + 1}`, url: URL }))+ const result = pullRequestEvents(watch({ comments }), seen, null, NOW)+ expect(result.events.map(e => e.key)).toEqual([`comment:${count}`])+ seen = result.keys+ }+ expect(seen.length).toBeLessThanOrEqual(SEEN_KEPT)+ })++ it('keeps the newest 50 keys, and its marks always', () => {+ const old = Array.from({ length: 60 }, (_, i) => `ci-red:head${i}`)+ const { keys } = events(watch({ comments: [{ id: 100, login: 'dee', association: 'MEMBER', body: 'hi', url: URL }] }), [...SEEN, 'review>:4', ...old])+ expect(keys).toHaveLength(50)+ expect(keys).toEqual(expect.arrayContaining(['comment>:100', 'review>:4']))+ expect(keys.some(k => k.startsWith('ready:'))).toBe(true)+ expect(keys).toContain('ci-red:head0')+ expect(keys).not.toContain('ci-red:head59')+ })+})diff --git a/backend/src/superTabs/pullRequestEvents.ts b/backend/src/superTabs/pullRequestEvents.tsnew file mode 100644index 000000000..437702c4c--- /dev/null+++ b/backend/src/superTabs/pullRequestEvents.ts@@ -0,0 +1,204 @@+// GitHub events on an open task's pull request reach the task's Engineer directly (Dee, #1891, from DeepSeek's Super-agent):+// CI failed or passed, a review or comment, a merge conflict, each once, without waiting for the PM's 30-minute sync. No+// webhook reaches the backend, so the singleton worker reads them every minute with the Harness GitHub App+// (docs/plans/2026-11-03-pr-events-to-engineer-plan.md).+import type { PrismaClient } from '@prisma/client'+import { PULL_WATCH_PERMISSIONS, type GitHubApp } from '../github/app.js'+import { githubRepository, type GitHubRepository } from '../github/repository.js'+import type { SuperTabStore } from './store.js'+import { logger } from '../utils/logger.js'++/** What GitHub says of one pull request, as the watch reads it (github/app.ts watchPullRequest). */+export interface PullRequestWatch {+ url: string+ number: number+ state: 'open' | 'closed'+ draft: boolean+ /** The head commit's SHA. */+ head: string+ /** The branch it merges into. */+ base: string+ /** False on a merge conflict; null while GitHub is still working it out. */+ mergeable: boolean | null+ /** The head's latest check run of each name. */+ checkRuns: Array<{ name: string; status: string; conclusion: string | null; completedAt: number | null }>+ /** The head's check suites, with how many check runs each has. */+ checkSuites: Array<{ status: string; runs: number }>+ /** Each with its author's tie to the repository, GitHub's author_association (OWNER, MEMBER, COLLABORATOR, NONE...). */+ reviews: Array<{ id: number; login: string; association: string; state: string; body: string; url: string }>+ comments: Array<{ id: number; login: string; association: string; body: string; url: string }>+}++/** One message for the Engineer, and the key it is posted under once. */+export interface PullRequestEvent { key: string; text: string }++const FAILED = new Set(['failure', 'timed_out', 'cancelled', 'action_required', 'startup_failure'])+const PASSED = new Set(['success', 'neutral', 'skipped'])+/** The keys a group keeps per pull request: its marks, and its newest heads' CI and conflict keys. */+export const SEEN_KEPT = 50+const QUOTE = 300++const short = (sha: string) => sha.slice(0, 7)+const quoted = (body: string) => {+ const text = body.trim().replace(/\s+/g, ' ')+ return text.length > QUOTE ? `${text.slice(0, QUOTE - 1)}…` : text+}+const REVIEWED: Record<string, string> = { CHANGES_REQUESTED: 'asked for changes on', APPROVED: 'approved' }+/** Whose words reach the Engineer: the repository's own people. Anyone can comment on a public pull request, and the line+ * reaches an agent as its Lead's, so anyone else's text stays on GitHub behind the link (ENGINEERING.md 7, review of #2750). */+const QUOTED = new Set(['OWNER', 'MEMBER', 'COLLABORATOR'])+const said = (association: string, body: string, url: string) => {+ if (!body.trim()) return `. ${url}`+ return QUOTED.has(association) ? `: "${quoted(body)}" ${url}` : `: ${url}`+}++/**+ * What is new in [watch] since the keys in [seen], and the keys to keep from now on. The first read of a pull request+ * ([seen] empty) records what is already there and posts only a merge conflict, which still needs acting on. Nothing from+ * [botLogin], the app's own account, which the Engineer's own comments go out as. While a draft, no CI: a pull request read+ * as a draft (`draft`), whatever its head, is marked when next read as ready (`ready:<ms>`), and a failure finished before+ * that was a draft's own run, still the latest of its name until the ready run starts (review of #2750: a push and Ready+ * in the same minute leave the new head never read as a draft). Reviews and comments are told by their ids: one newer than+ * the highest seen of its kind (`review>:<id>`, `comment>:<id>`) is new, however many came before (review of #2750).+ */+export function pullRequestEvents(watch: PullRequestWatch, seen: readonly string[], botLogin: string | null, now: number): { events: PullRequestEvent[]; keys: string[] } {+ const first = seen.length === 0, known = new Set(seen), events: PullRequestEvent[] = [], found: string[] = []+ const { url, number, head } = watch+ const add = (key: string, text: string, post = !first) => {+ found.push(key)+ if (!known.has(key) && post) events.push({ key, text })+ }+ const readyMark = seen.find(key => key.startsWith('ready:'))+ if (watch.draft) found.push('draft')+ else {+ // Ready since a draft read: from now, unless it was ready already. On the first read everything there is recorded.+ const readyAt = known.has('draft') ? now : readyMark ? Number(readyMark.slice('ready:'.length)) : null+ if (readyAt !== null) found.push(`ready:${readyAt}`)+ const since = !first && readyAt !== null ? readyAt : -Infinity+ const failing = (run: PullRequestWatch['checkRuns'][number]) => !!run.conclusion && FAILED.has(run.conclusion)+ const failed = watch.checkRuns.filter(run => failing(run) && (run.completedAt ?? now) >= since)+ const stale = watch.checkRuns.some(run => failing(run) && (run.completedAt ?? now) < since)+ if (failed.length) add(`ci-red:${head}`, `CI failed on your pull request #${number} (head ${short(head)}): ${failed.map(run => run.name).join(', ')}. ${url}`)+ const suites = watch.checkSuites.filter(suite => suite.runs > 0)+ if (!failed.length && !stale && watch.checkRuns.length && suites.length && suites.every(suite => suite.status === 'completed')+ && watch.checkRuns.every(run => run.status === 'completed' && run.conclusion && PASSED.has(run.conclusion))) {+ add(`ci-green:${head}`, `CI passed on your pull request #${number} (head ${short(head)}). ${url}`)+ }+ }+ if (watch.mergeable === false) {+ add(`conflict:${head}`, `Your pull request #${number} has a merge conflict with ${watch.base} (head ${short(head)}): merge ${watch.base} into its branch and push. ${url}`, true)+ }+ const highest = (kind: string) => Math.max(0, ...seen.filter(key => key.startsWith(`${kind}>:`)).map(key => Number(key.slice(kind.length + 2))))+ const reviewed = highest('review'), commented = highest('comment')+ for (const review of watch.reviews) {+ if (review.login === botLogin || review.id <= reviewed) continue+ add(`review:${review.id}`, `${review.login} ${REVIEWED[review.state] ?? 'reviewed'} your pull request #${number}${said(review.association, review.body, review.url)}`)+ }+ for (const comment of watch.comments) {+ if (comment.login === botLogin || comment.id <= commented) continue+ add(`comment:${comment.id}`, `${comment.login} commented on your pull request #${number}${said(comment.association, comment.body, comment.url)}`)+ }+ // The marks stand for the pull request as it is now and always stay; then its newest CI and conflict keys. A review's or+ // comment's own key is only its message's: the marks say it was told.+ const marks = [...found.filter(key => key === 'draft' || key.startsWith('ready:')),+ `review>:${Math.max(reviewed, ...watch.reviews.map(r => r.id))}`, `comment>:${Math.max(commented, ...watch.comments.map(c => c.id))}`]+ const told = (key: string) => /^(ci-red|ci-green|conflict):/.test(key)+ const kept = [...new Set([...found, ...seen])].filter(told).slice(0, SEEN_KEPT - marks.length)+ return { events, keys: [...marks, ...kept] }+}++/** What a pass asks GitHub: a pull request's watch (null: it cannot say), the app's own login, and `done` once it is over. */+export interface PullRequestReader { watch(url: string): Promise<PullRequestWatch | null>; botLogin(): Promise<string | null>; done(): Promise<void> }++const PULL = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/([1-9][0-9]*)$/+/** A task quiet this long is not watched: its Engineer is not waiting on its pull request. */+export const WATCH_QUIET_MS = 7 * 24 * 3_600_000+/** The most tasks a pass reads, the most recently active first (ENGINEERING.md 4: no read grows without a bound). */+export const WATCH_GROUPS = 200++/** Reads with the Harness GitHub App: one read-only token per repository for the whole pass, revoked when it is done (as the+ * archive pass's, archive.ts). A repository the app is not installed on, or any GitHub failure, reads as null. */+export function appPullRequestWatch(app: GitHubApp): PullRequestReader {+ const tokens = new Map<string, Promise<string | null>>()+ const token = (repository: GitHubRepository) => {+ const key = repository.fullName.toLowerCase()+ if (!tokens.has(key)) tokens.set(key, (async () => {+ const installation = await app.installation(repository)+ return installation === null ? null : (await app.createToken(installation, repository, PULL_WATCH_PERMISSIONS)).token+ })().catch(() => null))+ return tokens.get(key)!+ }+ return {+ async watch(url) {+ const match = PULL.exec(url), repository = match ? githubRepository(`https://github.com/${match[1]}`) : null+ const granted = repository ? await token(repository) : null+ return granted ? app.watchPullRequest(repository!, Number(match![2]), granted) : null+ },+ botLogin: () => app.botLogin(),+ async done() {+ for (const granted of tokens.values()) {+ const value = await granted+ if (value) await app.revoke(value).catch(() => {})+ }+ tokens.clear()+ },+ }+}++/**+ * One pass: open tasks (not steps) active in the last [WATCH_QUIET_MS] that link a pull request, at most [limit] of them, the+ * most recently active first, have each open one read once, and what is new goes to its Engineer (store.ts+ * pullRequestSeen). One group's failure is logged and skips that group alone. A pass that posted, or could not read a pull+ * request, says so in one line: the measure of this feature (ENGINEERING.md 6 and 8). The messages posted.+ */+export async function watchPullRequests(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen'>, reader: PullRequestReader, now: number,+ limit = WATCH_GROUPS): Promise<number> {+ try {+ // The finished mark's index, [workFinished, archived, lastActivityAt]: equality, equality, then the range, which also+ // gives the sort; the rest filters what it fetches. A step's reviewOf is a string and a task has none (null matches it).+ const rows = await db.swarmGroup.aggregateRaw({ pipeline: [+ { $match: { workFinished: false, archived: false, lastActivityAt: { $gte: { $date: new Date(now - WATCH_QUIET_MS).toISOString() } },+ deleted: false, kind: null, 'data.reviewOf': null, 'data.pullRequestUrls.0': { $exists: true } } },+ { $sort: { lastActivityAt: -1 } },+ { $limit: limit },+ { $project: { _id: 0, tabId: 1, key: 1, urls: '$data.pullRequestUrls' } },+ ] }) as unknown as Array<{ tabId: string; key: string; urls: string[] }>+ if (!rows.length) return 0+ const bot = await reader.botLogin()+ // One read per pull request a pass, however many tasks link it.+ const reads = new Map<string, Promise<PullRequestWatch | null>>()+ const watchOf = (url: string) => { if (!reads.has(url)) reads.set(url, reader.watch(url).catch(() => null)); return reads.get(url)! }+ let posted = 0+ for (const row of rows) {+ for (const url of row.urls) {+ try {+ const watch = await watchOf(url)+ if (watch?.state === 'open') posted += await store.pullRequestSeen(row.tabId, row.key, watch, bot)+ } catch (error) {+ logger.warn('[swarm-pr-events] group skipped', { tabId: row.tabId, group: row.key, error: error instanceof Error ? error.message : String(error) })+ }+ }+ }+ const unreadable = (await Promise.all(reads.values())).filter(watch => watch === null).length+ const line = { groups: rows.length, pulls: reads.size, unreadable, posted }+ if (unreadable) logger.warn('[swarm-pr-events] pass', line)+ else if (posted) logger.info('[swarm-pr-events] pass', line)+ return posted+ } finally { await reader.done() }+}++/** Runs the pass every minute in the singleton worker, one at a time. */+export function startPullRequestWatch(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen'>, reader: () => PullRequestReader, everyMs = 60_000): () => void {+ let running = false+ const run = () => {+ if (running) return+ running = true+ void watchPullRequests(db, store, reader(), Date.now())+ .catch(error => logger.warn('[swarm-pr-events] failed', { error: error instanceof Error ? error.message : String(error) }))+ .finally(() => { running = false })+ }+ run()+ const timer = setInterval(run, everyMs)+ timer.unref()+ return () => clearInterval(timer)+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex dc23b081e..bd3ac7a69 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -56,7 +56,8 @@ import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'import type { MachineRename } from './machineRenames.js'import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'import { loadDeliveryParts, ms } from './parts/light.js'-import { endSteps, stepEndedRows, stepsOf } from './steps.js'+import { endSteps, ownerOf, stepEndedRows, stepsOf } from './steps.js'+import { pullRequestEvents, type PullRequestWatch } from './pullRequestEvents.js'import { guardedWrite, partId } from './parts/write.js'import { retryable } from './retry.js'import { touchesFor } from './parts/touches.js'@@ -485,8 +486,14 @@ const receiptOrder = (m: Pick<SuperTabMessage, 'recipientIds'>) => (a: PageDeliv* its source (liveness.ts loseTask), a machine leaving the Swarm (machines.ts removalEnded, commands.ts removeMachine), and* the machine a Product Manager started on (leadStart.ts leadJoined; Diego, 10-30) or a removed session is still held on* (liveness.ts unpurged; review 2 of #2258). */-function withoutMachineNames(m: SuperTabMessage): SuperTabMessage {- const source = m.source as { kind?: unknown; reason?: unknown; machine?: unknown } | null+export function withoutMachineNames(m: SuperTabMessage): SuperTabMessage {+ const source = m.source as { kind?: unknown; reason?: unknown; machine?: unknown; machines?: unknown } | null+ // A Buddy model switch's line names every machine serving the model (buddyModel.ts).+ if (source?.kind === 'system' && Array.isArray(source.machines)) {+ const { machines, ...rest } = source+ const names = (machines as unknown[]).filter((n): n is string => typeof n === 'string' && n.length > 0).sort((a, b) => b.length - a.length)+ return { ...m, text: names.reduce((text, name) => text.split(name).join('a machine'), m.text), source: rest as SuperTabMessage['source'] }+ }if (source?.kind === 'work-lost' && typeof source.reason === 'string') {const reason = lostReasonWithoutMachine(source.reason)return reason === source.reason ? m : { ...m, text: m.text.split(source.reason).join(reason), source: { ...source, reason } as SuperTabMessage['source'] }@@ -3923,6 +3930,39 @@ export class SuperTabStore {return renamed}+ /**+ * What GitHub says of [watch], a pull request linked to the task [groupId] (pullRequestEvents.ts): each event its Engineer+ * was not told yet goes to it as a message in the task, and every event is recorded there, in one write, so a retry or a+ * second pass posts none twice. A task with no Engineer in the Swarm records them and posts nothing. A step, an archived or+ * a finished task, or a pull request it no longer links, is left alone. The messages posted.+ */+ async pullRequestSeen(tabId: string, groupId: string, watch: PullRequestWatch, botLogin: string | null): Promise<number> {+ return transaction(this.db, async tx => {+ const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })+ if (!row || row.deletedAt) return 0+ const loaded = await loadRow(tx, requireParts(row), { groupIds: [groupId] }), state = cloneData(loaded.state)+ const group = state.conversations.find(c => c.id === groupId)+ // A task its agent left (no assignment) records what happens, so its next Engineer hears only what is new.+ if (!group || group.archived || group.reviewOf || !group.pullRequestUrls?.includes(watch.url)+ || ['done', 'cancelled'].includes(group.assignment?.status ?? '')) return 0+ const now = this.now(), seen = group.pullRequestEvents?.[watch.url] ?? []+ const { events, keys } = pullRequestEvents(watch, seen, botLogin, now)+ if (keys.length === seen.length && keys.every((key, i) => key === seen[i])) return 0+ group.pullRequestEvents = { ...group.pullRequestEvents, [watch.url]: keys }+ const ownerId = ownerOf(state, group), owner = ownerId ? state.agents.find(a => a.id === ownerId) : undefined+ // Written as its project's Lead, as the Swarm's own lines are (tidy.ts archiveLine); as the Engineer itself without one.+ const leadId = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)?.leadId+ const by = state.agents.find(a => a.id === leadId) ?? owner+ const rows: MessageDraft[] = owner && by ? events.map(event => ({ id: stableId('pull-request-event', group.id, watch.url, event.key), conversationId: group.id,+ author: { kind: 'agent', id: by.id, name: by.name, displayName: agentDisplayName(state.agents, by.id), membershipGeneration: by.membershipGeneration },+ text: event.text, replyTo: null, recipients: [owner.id], source: { kind: 'system' } })) : []+ const sequences = numberMessages(state, rows, now)+ await this.save(tx, loaded, state, clock.next())+ await this.writeMessages(tx, tabId, state, rows, sequences)+ return rows.length+ })+ }+async archiveFinished(tabId: string, groupId: string, checked: Readonly<Record<string, 'merged' | 'closed'>>, reviewOf?: string): Promise<boolean> {return transaction(this.db, async tx => {const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 2250e34f8..3b3e0d5e7 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -1,5 +1,6 @@import { checksOpenWork, isStep, taskEnded } from './steps.js'import { isBuddy } from './buddies.js'+import { expiredModelRequests, unservedBuddyModels } from './buddyModel.js'import { agentDisplayName } from './agentNames.js'import { githubRepository } from '../github/repository.js'import { activeWork, appendPullRequestUrls, stableId, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'@@ -97,6 +98,20 @@ export function staleSwitches(state: SuperTabState, now: number): MessageDraft[]return rows}+export { BUDDY_MODEL_GONE_MS, BUDDY_MODEL_LEASE_MS } from './buddyModel.js'++/** A Buddy's model switch its machine never reported is dropped (the Buddy stays where it was), and its owner's Buddy chat+ * says so once. Run by the liveness sweep, as staleSwitches is: the Buddy's own machine may be the one down. */+export function staleModelRequests(state: SuperTabState, now: number): MessageDraft[] {+ const drafts = expiredModelRequests(state, now).map(({ buddy, requestId, conversationId, text, machines }): MessageDraft => ({+ id: stableId('buddy-model-stale', buddy.id, requestId), conversationId, replyTo: null, recipients: [], text,+ source: { kind: 'system', ...(machines.length ? { machines } : {}) },+ author: { kind: 'agent', id: buddy.id, name: buddy.name, displayName: agentDisplayName(state.agents, buddy.id), membershipGeneration: buddy.membershipGeneration } }))+ // After the expiry, so a Buddy whose machine never answered one request home is asked again on the next sweep.+ unservedBuddyModels(state, now, buddy => stableId('buddy-model-gone', buddy.id, String(now)))+ return drafts+}+/** A linked task (`reviewOf`) the Swarm does not archive by itself: none of its checks carries evidence, nobody cancelled it,* and the task it links to is still going. Once that task is done or cancelled the link is moot. By hand any agent of the* project or a person archives it (project instructions, phase 4). */diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 1136d273f..75cd8e3ac 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -24,6 +24,7 @@ import { startDeliverySettle } from './superTabs/deliverySettle.js'import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'import { startThreadBackfill } from './superTabs/threadBackfill.js'import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'+import { appPullRequestWatch, startPullRequestWatch } from './superTabs/pullRequestEvents.js'import { SuperTabStore } from './superTabs/store.js'import { announceSwarmDeliveries, announceSwarmTerminal } from './lib/swarmDeliveryPushes.js'import { announceSwarmHostChanges } from './lib/swarmHostPushes.js'@@ -72,6 +73,7 @@ async function start(): Promise<void> {let stopSweeps = (): void => {}let stopLegacyDrop = (): void => {}let stopArchive = (): void => {}+ let stopPullRequestWatch = (): void => {}let stopDeliveries = (): void => {}let stopCompaction = (): void => {}let stopThreadBackfill = (): void => {}@@ -89,6 +91,7 @@ async function start(): Promise<void> {stopSweeps()stopLegacyDrop()stopArchive()+ stopPullRequestWatch()stopDeliveries()stopCompaction()stopReceiptSweep()@@ -137,6 +140,9 @@ async function start(): Promise<void> {// link none do (superTabs/archive.ts).const githubConfig = githubAppConfig(env), githubApp = githubConfig ? new GitHubApp(githubConfig) : nullstopArchive = startSwarmArchive(prisma, swarms, () => githubApp ? appPullRequests(githubApp) : unknownPullRequests)+ // GitHub events on an open task's pull request reach its Engineer within a minute (superTabs/pullRequestEvents.ts): only+ // with the app, which reads them.+ if (githubApp) stopPullRequestWatch = startPullRequestWatch(prisma, swarms, () => appPullRequestWatch(githubApp))// A delivery that can no longer move ends as Not sent, instead of waiting for good (superTabs/deliverySettle.ts).stopDeliveries = startDeliverySettle(prisma, swarms)// Every hour, finished deliveries 14 days old move into their messages' receipts, kept forever (superTabs/deliveryCompaction.ts).diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 27dcd7b6b..35ad8d7db 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/e2e/modelSwitchFresh.e2e.ts b/cli/e2e/modelSwitchFresh.e2e.tsnew file mode 100644index 000000000..12d12b977--- /dev/null+++ b/cli/e2e/modelSwitchFresh.e2e.ts@@ -0,0 +1,61 @@+/**+ * A model switch on the real daemon, as a Buddy's machine makes it (task #2354, superTabs/buddyModel.ts): onto a grid model and+ * back keeps the conversation; a conversation too long for the model starts fresh there, and the way home reopens the one it+ * left, as the same agent. The fake Claude Code (e2e/harness/fakeEngine.mjs) resumes the session `--resume` names, as the real+ * one does.+ */+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++/** A grid as the models service resolves one (gridLaunchWire.ts GridLaunchOverride): the fake engine never calls it. */+const GRID = { networkId: 'net-fixture', networkName: 'fixture-grid', baseUrl: 'https://fixture.invalid/g/net-fixture/relay',+ apiKey: 'fixture-key', model: 'deepseek-4.1-flash', contextWindow: 131072 }++let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })++const row = async (agentId: string) =>+ ((await client!.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents).find(a => a.id === agentId)+/** The agent back up after a move, bound to a conversation other than [not] when one is named. */+const settled = (agentId: string, wanted: (sessionId: string) => boolean, what: string) =>+ until(what, async () => { const agent = await row(agentId); return agent?.status === 'active' && agent.sessionId && wanted(agent.sessionId) ? agent : null }, 60_000, 500)+async function turn(agentId: string, content: string): Promise<void> {+ const ended = client!.next((frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId, 45_000, `turn_ended (${content})`)+ client!.send('message', { agentId, content })+ await ended+}++it('moves onto a grid model and back in the same conversation, and a fresh move comes home to the conversation it left', async () => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ client = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, 'buddy')+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const agentId = created.agent.id as string+ const first = await settled(agentId, () => true, 'the agent to bind its conversation')+ await turn(agentId, 'Remember the word lilac')+ const s1 = first.sessionId as string++ // Resumed: the same conversation on the grid, and the same one home.+ expect(await client.request('agent_retarget', { agentId, grid: GRID }, 60_000)).toMatchObject({ retargeted: true })+ expect((await settled(agentId, id => id === s1, 'the resumed conversation on the grid')).sessionId).toBe(s1)+ expect(await client.request('agent_retarget', { agentId, clearGrid: true }, 60_000)).toMatchObject({ retargeted: true })+ expect((await settled(agentId, id => id === s1, 'the same conversation at home')).sessionId).toBe(s1)++ // Too long for the model: a fresh conversation on the grid, then home to the one it left, as the same agent.+ expect(await client.request('agent_retarget', { agentId, grid: GRID, fresh: true }, 60_000)).toMatchObject({ retargeted: true })+ const onGrid = await settled(agentId, id => id !== s1, 'a fresh conversation on the grid')+ await turn(agentId, 'A question for the shared model')+ expect(await client.request('agent_retarget', { agentId, clearGrid: true }, 60_000)).toMatchObject({ retargeted: true })+ const home = await settled(agentId, id => id === s1, 'the conversation it left, reopened at home')+ expect([home.id, home.sessionId, onGrid.id]).toEqual([agentId, s1, agentId])+ expect((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents.filter(a => a.status === 'active'))+ .toHaveLength(1)+})diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 80d0e55a5..5d033c503 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -3435,6 +3435,18 @@ describe('agent_retarget clearGrid', () => {expect(reply?.payload?.error).toBe('INVALID_GRID')expect(seen).toHaveLength(0)})++ // A fresh session is a grid's or an API's: the way home reopens the conversation a fresh move left.+ it('refuses fresh with clearGrid', async () => {+ const { seen, reply } = await retarget({ requestId: 'r', agentId: 'a1', clearGrid: true, fresh: true })+ expect(reply?.payload?.error).toBe('INVALID_GRID')+ expect(seen).toHaveLength(0)+ })++ it('passes fresh through with a grid', async () => {+ const { seen } = await retarget({ requestId: 'r', agentId: 'a1', grid: WIRE_GRID, fresh: true })+ expect(seen).toEqual([expect.objectContaining({ agentId: 'a1', grid: expect.objectContaining({ networkId: 'grid-abc' }), fresh: true })])+ })})/**@@ -3689,6 +3701,15 @@ describe('a move onto a grid model asks models where it goes', () => {await d.done()})+ it('a fresh move onto a grid model or an API model says so to the move', async () => {+ const d = daemon(vi.fn(async () => ({ target: TARGET })), vi.fn(async () => ({ target: API, apiBase: API.baseUrl })))+ expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Shared-Model', gridName: 'team-grid-0000aaaa', fresh: true })).toMatchObject({ retargeted: true })+ expect(d.retargeted).toHaveBeenLastCalledWith({ agentId: 'a1', grid: TARGET, fresh: true })+ expect(await d.ask('agent_retarget', { agentId: 'a1', apiConnection: 'router', apiModel: 'vendor/model-a', fresh: true })).toMatchObject({ retargeted: true })+ expect(d.retargeted).toHaveBeenLastCalledWith({ agentId: 'a1', grid: API, fresh: true })+ await d.done()+ })+it('says why it cannot move, in models\' words, and moves nothing', async () => {const d = daemon(async () => ({ detail: 'no grid on this computer' }))expect(await d.ask('agent_retarget', { agentId: 'a1', gridModel: 'Shared-Model', gridName: 'team-grid-0000aaaa' }))diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex dcb612505..56b3e263b 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -247,8 +247,11 @@ export class BackendSocket {* Separate from a restart (core/agents/launches.ts) because that one puts the agent back exactly as it* was; this one puts it back somewhere else. They share the swap underneath and differ in what they* hand it.+ *+ * `fresh` (with a grid only): the relaunch starts a new conversation instead of resuming, and the one it+ * leaves on the own login is reopened by the move home (core/agents/retarget.ts).*/- onRetargetAgent: ((input: { agentId: string; grid: GridLaunchOverride | null }) =>+ onRetargetAgent: ((input: { agentId: string; grid: GridLaunchOverride | null; fresh?: boolean }) =>Promise<{ ok: true } | { ok: false; error: string; detail?: string }>) | null = null/** The requests that start an agent's process, answered through their last argument: `agent_create`,* `agent_create_status`, `agent_resume` and `agent_restart`, and `agent_fork` (cli.ts binds@@ -1249,6 +1252,12 @@ export class BackendSocket {if (!agentId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }if (!this.onRetargetAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }const clear = payload.clearGrid === true+ // A new conversation is started on a grid or an API model; the own login reopens the one it left.+ const fresh = payload.fresh === true+ if (fresh && clear) {+ reply(type, requestId, { error: 'INVALID_GRID', detail: 'A fresh session starts on a grid or API model, not on the own login.' })+ return+ }// `gridModel` is the header picker's frame: a model id and nothing else. The endpoint and// the credential are resolved HERE, from this machine's own signed-in `grid`, so neither// ever crosses the relay and the app cannot be the source of truth for an address it does@@ -1305,7 +1314,7 @@ export class BackendSocket {return}const override = target.state === 'ok' ? target.override : null- const moved = await this.onRetargetAgent({ agentId, grid: override })+ const moved = await this.onRetargetAgent({ agentId, grid: override, ...(fresh ? { fresh: true } : {}) })if (!moved.ok) {reply(type, requestId, moved.detail ? { error: moved.error, detail: moved.detail } : { error: moved.error })returndiff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 07a227b67..99e42cc37 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -273,6 +273,18 @@ describe('creating an agent', () => {expect(vi.mocked(agentTmpEnv).mock.calls.length).toBe(calls)})+ // A Buddy starts no MCP server (docs/swarms.md, Buddies): a thread session started on a shared model carries none of the+ // grid's web tools either (task #2354). Another Swarm session on the same grid keeps them.+ it('builds a Buddy\'s grid launch without the grid\'s web MCP', async () => {+ const grid = { baseUrl: 'https://grid.example/relay/v1', networkName: 'g', model: 'm', mcpUrl: 'https://grid.example/v1/grid/web-mcp' }+ vi.mocked(installedDsh).mockReturnValueOnce(installed() as never).mockReturnValueOnce(installed() as never)+ expect(await setup().create(request({ dsh: 'blender', swarmRole: 'buddy', grid }))).toMatchObject({ ok: true })+ expect(buildGridLaunch.mock.calls.at(-1)![0].override).not.toHaveProperty('mcpUrl')+ vi.mocked(installedDsh).mockReturnValueOnce(installed() as never).mockReturnValueOnce(installed() as never)+ expect(await setup().create(request({ dsh: 'blender', swarmRole: 'agent', grid }))).toMatchObject({ ok: true })+ expect(buildGridLaunch.mock.calls.at(-1)![0].override).toMatchObject({ mcpUrl: grid.mcpUrl })+ })+it('keeps a selected Store harness when attaching a Swarm skill', async () => {vi.mocked(installedDsh).mockReturnValueOnce(installed() as never).mockReturnValueOnce(installed() as never)expect(await setup().create(request({ dsh: 'blender', swarmRole: 'agent' }))).toMatchObject({ ok: true })diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex f0a2969c0..cdcc40840 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -226,6 +226,9 @@ export function createAgentCreator({// refusal rather than a fallback — an agent silently started on the engine's own login spends the// wrong account and looks identical to one that worked. Asked of models before a harness's workspace is// laid out or trusted: a create refused here leaves the folder as it was.+ // A Buddy starts no MCP server (docs/swarms.md, Buddies), so none of a grid's web tools either: its permission mode's+ // --strict-mcp-config would otherwise load exactly the grid's server. Relaunches drop it the same way (launchOverrides.ts).+ if (grid && input.swarmRole === 'buddy') { const { mcpUrl: _web, ...withoutWeb } = grid; grid = withoutWeb }const built = grid ? await buildGridLaunch({ engine, override: grid, machine: await gridLaunchMachine(engine, native) }) : nullif (!current()) return stale()if (built && !built.ok) {diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.tsindex 34cc0247a..455992563 100644--- a/cli/src/core/agents/retarget.spec.ts+++ b/cli/src/core/agents/retarget.spec.ts@@ -71,6 +71,7 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDeupdateProcessIdentity: vi.fn(),setGridLaunch: vi.fn(),setSubscriptionModel: vi.fn(),+ setSubscriptionSession: vi.fn(),setActive: vi.fn(),} as unknown as RetargetDeps['registry'],runtimeProfiles: { selectedModel: vi.fn(() => 'runtime-v1:claude:opus') } as never,@@ -685,4 +686,93 @@ describe('retargeting an agent', () => {expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()})})+ // A fresh move starts a new conversation on the grid (a long one would not fit its window) and keeps the one it+ // left; the way home reopens that one, not the grid's (design: "Two generic additions to agent_retarget").+ describe('a fresh session, and the way home to the one it left', () => {+ const onGrid = (over: Partial<RegisteredSession> = {}) =>+ agent({ grid: { baseUrl: 'x' }, gridLaunch: grid, sessionId: 'S2', subscriptionSessionId: 'S1', ...over } as Partial<RegisteredSession>)+ const home = { relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: {} })) as never }+ const order = (fn: unknown) => vi.mocked(fn as () => void).mock.invocationCallOrder[0]++ it('a fresh move onto a grid relaunches without --resume and keeps the session it left', async () => {+ const run = setup(agent({ sessionId: 'S1' }))+ expect(await run.retarget({ agentId: 'a1', grid, fresh: true })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'claude', sessionId: '' })+ expect(run.deps.registry.setSubscriptionSession).toHaveBeenCalledExactlyOnceWith('a1', 'S1')+ // Kept only once the move worked.+ expect(order(run.deps.registry.setSubscriptionSession)).toBeGreaterThan(order(restartAgent))+ })++ it('a fresh Codex move starts a new conversation rather than forking the one it leaves', async () => {+ const run = setup(agent({ engine: 'codex', sessionId: 'S1' }))+ expect(await run.retarget({ agentId: 'a1', grid, fresh: true })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'codex', sessionId: '' })+ expect(run.deps.registry.setSubscriptionSession).toHaveBeenCalledWith('a1', 'S1')+ })++ it('a fresh OpenCode move leaves the model of the session it left as it was', async () => {+ const run = setup(agent({ engine: 'opencode', sessionId: 'S1' }), { relaunchOverrides: vi.fn(async () => ({ ok: true as const,+ overrides: { env: {}, extraArgs: [], clearEnv: [], sessionModel: 'grid/big' } })) })+ expect(await run.retarget({ agentId: 'a1', grid, fresh: true })).toEqual({ ok: true })+ expect(applyOpencodeSessionModel).not.toHaveBeenCalled()+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'opencode', sessionId: '' })+ })++ it('the move home reopens the session a fresh move left, and forgets it once home', async () => {+ const run = setup(onGrid(), home)+ expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'claude', sessionId: 'S1' })+ // The swap prepares, guards and (on a fallback) keeps the conversation it reopens, not the grid's.+ expect(vi.mocked(run.deps.paneSwapDeps).mock.calls[0][5]).toBe('S1')+ expect(run.deps.registry.setSubscriptionSession).toHaveBeenCalledExactlyOnceWith('a1', null)+ expect(order(run.deps.registry.setSubscriptionSession)).toBeGreaterThan(order(restartAgent))+ })++ it('the move home resumes a Codex conversation it left on the own login, without a fork', async () => {+ const run = setup(onGrid({ engine: 'codex' }), home)+ expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'codex', sessionId: 'S1' })+ })++ it('the move home rewrites the model of the OpenCode session it reopens', async () => {+ const run = setup(onGrid({ engine: 'opencode', subscriptionModel: 'anthropic/claude' }), { relaunchOverrides: vi.fn(async () => ({ ok: true as const,+ overrides: { sessionModel: 'anthropic/claude', gridLaunchRecord: null } })) as never })+ expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })+ expect(vi.mocked(applyOpencodeSessionModel).mock.calls[0][0]).toMatchObject({ sessionId: 'S1' })+ })++ it('a grid-to-grid move keeps the remembered session, fresh or resumed', async () => {+ const fresh = setup(onGrid())+ expect(await fresh.retarget({ agentId: 'a1', grid: { ...grid, networkId: 'g2' }, fresh: true })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'claude', sessionId: '' })+ expect(fresh.deps.registry.setSubscriptionSession).not.toHaveBeenCalled()+ const resumed = setup(onGrid())+ expect(await resumed.retarget({ agentId: 'a1', grid: { ...grid, networkId: 'g2' } })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[1][0]).toEqual({ engine: 'claude', sessionId: 'S2' })+ expect(resumed.deps.registry.setSubscriptionSession).not.toHaveBeenCalled()+ })++ it('a move from the own login that keeps its conversation forgets an earlier remembered one', async () => {+ const run = setup(agent({ sessionId: 'S3', subscriptionSessionId: 'S1' } as Partial<RegisteredSession>))+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })+ expect(vi.mocked(restartAgent).mock.calls[0][0]).toEqual({ engine: 'claude', sessionId: 'S3' })+ expect(run.deps.registry.setSubscriptionSession).toHaveBeenCalledExactlyOnceWith('a1', null)+ })++ it('a refused or failed move leaves the remembered session unchanged', async () => {+ // Refused: a turn is open.+ const busyOut = setup(agent({ sessionId: 'S1' }), { sessionTurnOpen: vi.fn(() => true) })+ expect(await busyOut.retarget({ agentId: 'a1', grid, fresh: true })).toMatchObject({ ok: false, error: 'AGENT_BUSY' })+ const busyHome = setup(onGrid(), { ...home, sessionTurnOpen: vi.fn(() => true) })+ expect(await busyHome.retarget({ agentId: 'a1', grid: null })).toMatchObject({ ok: false, error: 'AGENT_BUSY' })+ expect(restartAgent).not.toHaveBeenCalled()+ // Failed: the replacement did not come up.+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: false, detail: 'no process' } as never).mockResolvedValueOnce({ ok: false, detail: 'no process' } as never)+ const failedOut = setup(agent({ sessionId: 'S1' }))+ expect(await failedOut.retarget({ agentId: 'a1', grid, fresh: true })).toMatchObject({ ok: false, error: 'RESPAWN_FAILED' })+ const failedHome = setup(onGrid(), home)+ expect(await failedHome.retarget({ agentId: 'a1', grid: null })).toMatchObject({ ok: false, error: 'RESPAWN_FAILED' })+ for (const run of [busyOut, busyHome, failedOut, failedHome]) expect(run.deps.registry.setSubscriptionSession).not.toHaveBeenCalled()+ })+ })})diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsindex e911a5e2a..c43d28bba 100644--- a/cli/src/core/agents/retarget.ts+++ b/cli/src/core/agents/retarget.ts@@ -79,7 +79,7 @@ export function createAgentRetargeter({}: RetargetDeps) {const authority = createLaunchAuthority({ byAgent: id => registry.byAgent(id),revision: id => restartJobs.revision(id), cancelled: () => false })- const retargetAgent: RetargetAgent = async ({ agentId, grid }) => {+ const retargetAgent: RetargetAgent = async ({ agentId, grid, fresh }) => {if (purgeBusy(agentId)) return { ok: false, error: 'AGENT_BUSY' }// No backend here can respawn a pane (tmux missing, the pty host down): the configured backend's code.if (!terminals.instances().some(canRestart)) return { ok: false, error: noBackendCode }@@ -160,6 +160,14 @@ export function createAgentRetargeter({// "subscription" one and hand it straight back — teaching the bug to itself.? (!session.grid && observed !== grid.model ? observed : (session.subscriptionModel ?? null)): (session.subscriptionModel ?? null)+ // Which conversation the relaunch reopens. `fresh` (a grid's or an API's: the conversation is too long for the+ // model's window) starts a new one, and the one left on the own login is remembered, as the model is above. The+ // way home reopens that one rather than the grid's, so the person is back where they left off. Grid to grid,+ // the remembered one stays: it is still the own login's. '' starts a new conversation (restartAgent).+ const onGrid = !!(session.grid || session.gridLaunch)+ const startsFresh = !!grid && fresh === true+ const homeConversation = !grid && onGrid ? session.subscriptionSessionId ?? null : null+ const reopens = startsFresh ? '' : homeConversation ?? session.sessionId// What this machine cannot do at all is said first, before the pane is even looked at.const target: LaunchSource = {gridLaunch: grid,@@ -182,7 +190,7 @@ export function createAgentRetargeter({// the remembered model carries its provider (`subscriptionModel.ts`), and otherwise the engine// decides, as it always did. v2 switches the model through OpenCode's own API instead and needs no// sqlite3 (`applyOpencodeSessionModel`).- const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId+ const rewritesOpencodeSession = session.engine === 'opencode' && !!reopens&& (!!grid || !!remembered?.includes('/'))const opencode = session.engine === 'opencode' ? opencodeLaunch : nullconst opencodeMajor = native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null@@ -277,7 +285,7 @@ export function createAgentRetargeter({if (model) {nativeEffect = 'uncertain'const written = await opencode.applyOpencodeSessionModel({- opencodeMajor, dbPath: native ? nativeOpencodeStore(native.environment) : opencodeDb, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,+ opencodeMajor, dbPath: native ? nativeOpencodeStore(native.environment) : opencodeDb, sessionId: reopens, model, cwd: session.cwd ?? undefined,// (A model of opencode's own is looked for in its catalogue; a grid's provider lives in// the pane's own config, which the service never reads.)checkCatalog: !grid,@@ -305,20 +313,21 @@ export function createAgentRetargeter({if (retargetPermission.nativeHold || native?.current() === false) return failed('NATIVE_LAUNCH_HELD', retargetPermission.nativeHold ?? 'Waiting for fresh executable and hook evidence.')if (!current()) return changed()// A Codex conversation is bound to its provider (`providerBoundConversations`): moved between a grid and the- // own login it goes on in a fork, its whole history with it; grid to grid is one provider and resumes.+ // own login it goes on in a fork, its whole history with it; grid to grid is one provider and resumes. The+ // conversation a fresh move left was the own login's, so going home it resumes.const movesProvider = !!launchContract(session.engine)?.providerBoundConversations- && !!session.sessionId && !!(session.gridLaunch || session.grid) !== !!grid+ && !!reopens && (homeConversation ? false : onGrid) !== !!gridconst outcome = await restartAgent(- { engine: session.engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}),+ { engine: session.engine, sessionId: reopens, ...(session.resumeOnly ? { resumeOnly: true as const } : {}),...(movesProvider ? { continueInFork: true as const } : {}) },retargetPermission.bypassPermission === true,{ ...paneSwapDeps(session, place, !grid && !backend.clearEnv ? { ...built.overrides, clearPaneEnv: gridEnvVarNames(session.engine) } : built.overrides,- retargetPermission.permissionMode ?? null, dispatchCurrent), isCurrent: dispatchCurrent,+ retargetPermission.permissionMode ?? null, dispatchCurrent, ...(homeConversation ? [homeConversation] as const : [] as const)), isCurrent: dispatchCurrent,...(movesProvider ? { prepareFork: () => {const env: NodeJS.ProcessEnv = { ...process.env, CODEX_HOME: sessionCodexHome(session), ...built.overrides.env, ...built.overrides.native?.environment }if (!grid) for (const name of gridEnvVarNames(session.engine)) delete env[name]return moveCodexConversation({- sessionId: session.sessionId!, toGrid: !!grid, args: built.overrides.extraArgs ?? [], env,+ sessionId: reopens, toGrid: !!grid, args: built.overrides.extraArgs ?? [], env,argv: (codexArgs) => windowsEngineArgv(session.engine, [built.overrides.native?.executable?.command ?? engineBin(session.engine), ...codexArgs]),...(session.cwd ? { cwd: session.cwd } : {}),})@@ -344,6 +353,11 @@ export function createAgentRetargeter({// must not overwrite the model the agent is still sitting on. Survives a daemon restart, so an// agent left on a grid for a week still knows where it came from.if (grid && remembered) registry.setSubscriptionModel(session.agentId, remembered)+ // The conversation: kept on a fresh move from the own login, forgotten on any other move from it (it goes on+ // on the grid) and once home. Grid to grid it stays, like the model.+ const keptConversation = !grid ? null : onGrid ? session.subscriptionSessionId ?? null+ : startsFresh && session.sessionId ? session.sessionId : null+ if ((session.subscriptionSessionId ?? null) !== keptConversation) registry.setSubscriptionSession(session.agentId, keptConversation)registry.setActive(session.agentId, true)const refreshed = registry.byAgent(session.agentId)// The app decides whether to still offer a move from what it is told here, so a silent successdiff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.tsindex d20e7c92b..b00aa2cbc 100644--- a/cli/src/core/agents/swap.spec.ts+++ b/cli/src/core/agents/swap.spec.ts@@ -181,6 +181,21 @@ describe('the pane-process swap', () => {expect(setup().swap.restartJobs).toBeDefined()})+ // A move home after a fresh move reopens the conversation the agent left, not the one it is in (retarget.ts).+ it('prepares, frees and on a fallback keeps the conversation it reopens, while it still stops the process it found', async () => {+ const { deps, swap } = setup(session({ sessionId: 'S2', transcriptPath: '/t/S2.jsonl' }))+ const swapDeps = swap.paneSwapDeps(session({ sessionId: 'S2', transcriptPath: '/t/S2.jsonl' }), place(), {}, null, undefined, 'S1')+ swapDeps.prepareResume?.()+ // Found by its id: the row's transcript is the other conversation's.+ expect(deps.prepareSessionResume).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'S1', transcriptPath: null }))+ swapDeps.keepAbandoned?.()+ expect(deps.keepAbandonedConversation).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'S1', transcriptPath: null }))+ await swapDeps.stopConflictingJob!()+ expect(stopConflictingBackgroundJob).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 'S1' }))+ expect(await swapDeps.terminate()).toEqual({ ok: true })+ expect(terminateDeletedAgent).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 'S2' }), expect.anything(), undefined)+ })+it('prepares the resume, holds the pane open and respawns it in the home folder, saying why when tmux will not', async () => {const { deps, tmuxBackend, swap } = setup()const swapDeps = swap.paneSwapDeps(session(), place(), { env: { GRID_KEY: 'k' } })diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.tsindex 804076689..9ab31d9d3 100644--- a/cli/src/core/agents/swap.ts+++ b/cli/src/core/agents/swap.ts@@ -65,8 +65,13 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon* stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */permissionMode: string | null = session.permissionMode ?? null,current?: () => boolean,+ /** The conversation the relaunch reopens when it is not the row's own: a retarget home reopening the one a+ * fresh move left (retarget.ts). The process stopped is still the row's. */+ reopens?: string,): RestartAgentDeps => {const target = { ...session, processIdentity: session.processIdentity && { ...session.processIdentity } }+ // Found by its id when it is another conversation: the row's transcript is the one it is leaving.+ const conversation = reopens && reopens !== session.sessionId ? { ...session, sessionId: reopens, transcriptPath: null } : sessionconst identity = paneReadIdentity(target)const ownsOriginal = () => current?.() !== false && sameRestartTarget(target)&& paneReadIdentity(byAgent(target.agentId)) === identity@@ -92,9 +97,9 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon})return {...(current ? { isCurrent: current } : {}),- prepareResume: () => prepareSessionResume(session),- // The row as the swap found it: the conversation a fallback to a fresh start leaves behind.- keepAbandoned: () => keepAbandonedConversation(session),+ prepareResume: () => prepareSessionResume(conversation),+ // The conversation the swap meant to reopen: the one a fallback to a fresh start leaves behind.+ keepAbandoned: () => keepAbandonedConversation(conversation),// Only a backend that can refuse is asked (tmux, too old for `-e`); the pty host takes any environment....(backend.respawnRefusal ? { respawnRefusal: () => backend.respawnRefusal!(launch.env ? { env: launch.env } : {}) } : {}),holdOpen: async () => {@@ -172,7 +177,7 @@ export function createPaneSwap({ byAgent, prepareSessionResume, keepAbandonedCon// The exact environment the pane is about to get, the same way `respawn` above builds it: `launch.env`// already carries a native launch's own CLAUDE_CONFIG_DIR (launchOverrides.ts merges `native.environment`// into it), and `engineLaunchEnv` adds Windows's own-process variables.- stopConflictingBackgroundJob({ bin: engineBin(session.engine), sessionId: session.sessionId,+ stopConflictingBackgroundJob({ bin: engineBin(session.engine), sessionId: conversation.sessionId,env: { ...process.env, ...launch.env, ...engineLaunchEnv(session.engine, launch.native) } }) } : {}),log: (message) => console.log(message),}diff --git a/cli/src/lib/conversationSize.spec.ts b/cli/src/lib/conversationSize.spec.tsnew file mode 100644index 000000000..c147173f2--- /dev/null+++ b/cli/src/lib/conversationSize.spec.ts@@ -0,0 +1,48 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { conversationTokens } from './conversationSize.js'++const assistant = (usage: Record<string, number>) => JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [], usage } })+const user = (text: string) => JSON.stringify({ type: 'user', message: { role: 'user', content: text } })+// Sums to 150 000: what the conversation weighs once this answer is in it.+const NEWEST = { input_tokens: 10, cache_read_input_tokens: 140_000, cache_creation_input_tokens: 9_000, output_tokens: 990 }++describe('conversationTokens — how long a Claude Code conversation is now', () => {+ let dir: string+ const transcript = (lines: string[]) => {+ const file = join(dir, 'session.jsonl')+ writeFileSync(file, lines.join('\n') + '\n')+ return file+ }+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'conversation-size-')) })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ it('sums the newest assistant entry\'s usage', async () => {+ expect(await conversationTokens(transcript([user('hi'), assistant({ input_tokens: 5, output_tokens: 5 }), user('more'), assistant(NEWEST)])))+ .toBe(150_000)+ })++ it('is not changed by a later entry that carries no usage', async () => {+ expect(await conversationTokens(transcript([assistant(NEWEST), user('and then?')]))).toBe(150_000)+ })++ it('counts a missing field as nothing', async () => {+ expect(await conversationTokens(transcript([assistant({ input_tokens: 7, output_tokens: 3 })]))).toBe(10)+ })++ it('finds the newest usage in the tail of a long transcript', async () => {+ const filler = user('x'.repeat(1_000))+ const lines = [assistant({ input_tokens: 1, output_tokens: 1 }), ...Array.from({ length: 1_000 }, () => filler), assistant(NEWEST), ...Array.from({ length: 50 }, () => filler)]+ expect(await conversationTokens(transcript(lines))).toBe(150_000)+ })++ it('is null when no assistant entry has usage, skipping malformed lines', async () => {+ expect(await conversationTokens(transcript([user('hi'), '{"type":"assistant","mess', JSON.stringify({ type: 'assistant', message: {} })]))).toBeNull()+ })++ it('is null when the transcript cannot be read', async () => {+ expect(await conversationTokens(join(dir, 'missing.jsonl'))).toBeNull()+ })+})diff --git a/cli/src/lib/conversationSize.ts b/cli/src/lib/conversationSize.tsnew file mode 100644index 000000000..b90a595e6--- /dev/null+++ b/cli/src/lib/conversationSize.ts@@ -0,0 +1,41 @@+/**+ * How long a Claude Code conversation is now, in tokens: what its next turn would send. A Buddy moved onto a shared+ * model starts fresh when its conversation does not fit that model's window (docs/plans/2026-11-03-buddy-model-switch-design.md).+ *+ * The newest assistant entry's usage already counts the whole conversation it answered (input, cached and new) plus+ * its own answer, so only the transcript's tail is read: a long transcript costs no more than a short one.+ */+import { open } from 'node:fs/promises'++const TAIL_BYTES = 256 * 1024++const count = (value: unknown): number => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0++/** The newest assistant entry's tokens in the last 256 KB of a transcript; null when there is none or it cannot be read. */+export async function conversationTokens(transcriptPath: string): Promise<number | null> {+ let text: string+ let partial: boolean+ try {+ const file = await open(transcriptPath, 'r')+ try {+ const { size } = await file.stat()+ const start = Math.max(0, size - TAIL_BYTES)+ const buffer = Buffer.alloc(size - start)+ const { bytesRead } = await file.read(buffer, 0, buffer.length, start)+ text = buffer.subarray(0, bytesRead).toString('utf8')+ partial = start > 0+ } finally { await file.close() }+ } catch { return null }+ const lines = text.split('\n')+ // Read from the middle of the file, the first line is the end of one that started before the tail.+ if (partial) lines.shift()+ for (let i = lines.length - 1; i >= 0; i--) {+ let entry: { type?: unknown; message?: { usage?: unknown } }+ try { entry = JSON.parse(lines[i]) } catch { continue }+ const usage = entry?.type === 'assistant' ? entry.message?.usage : undefined+ if (!usage || typeof usage !== 'object') continue+ const u = usage as Record<string, unknown>+ return count(u.input_tokens) + count(u.cache_read_input_tokens) + count(u.cache_creation_input_tokens) + count(u.output_tokens)+ }+ return null+}diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 405ae3be2..becff907d 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -9,7 +9,8 @@ import { setAgentSettingsForTest, signedOutForTest } from '../testing/agentSettiimport { loadEngine } from '../engines/inProcess.js'import { buildLaunchOverrides, prepareLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'import { DSH_SESSION_ENV } from '../dsh/launch.js'-import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunch.js'+import { GRID_CONFLICTING_ENV_VARS, GRID_KEY_VAR, type GridLaunchOverride } from './gridLaunch.js'+import { CLAUDE_ALLOW_WEB_TOOLS_ARG, CLAUDE_DISALLOW_WEB_TOOLS_ARG } from './gridWebMcp.js'import { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'import { AGENT_ATTRIBUTION_LINE, HARNESS_INSTRUCTIONS } from './agentAttribution.js'import { prepareSwarmSkill } from './swarmSkills.js'@@ -443,6 +444,35 @@ describe('buildLaunchOverrides — machine MCP servers (#1872)', () => {expect(buddy.ok).toBe(true)expect(JSON.stringify(buddy)).not.toContain('lamp-mcp')})++ // The grid's web MCP is a server too: a Buddy moved onto a grid model drops it, and keeps everything that makes it a+ // Buddy (docs/plans/2026-11-03-buddy-model-switch-design.md, "The Buddy's guard on a grid").+ it('a Buddy moved onto a grid gets no web MCP and keeps its Buddy launch (#2354)', async () => {+ const withMcp: GridLaunchOverride = { ...GRID, mcpUrl: 'https://api-grid.example/v1/grid/web-mcp/' }+ const cwd = mkdtempSync(join(tmpdir(), 'overrides-buddy-'))+ const buddy = { startedBy: null, cwd, swarmSkill: { role: 'buddy' as const, key: 'harness-claude-buddy' } }+ const buddyTmp = { TMPDIR: '/data-buddy-tmp/one', CLAUDE_CODE_TMPDIR: '/data-buddy-tmp/one' }+ vi.mocked(buddyTmpEnv).mockReturnValueOnce(buddyTmp).mockReturnValueOnce(buddyTmp)+ const own = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude', buddy, 'a', () => true)+ const grid = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude', { ...buddy, gridLaunch: withMcp }, 'a', () => true)+ if (!own.ok || !grid.ok) throw new Error('Fixture launch failed')+ expect(grid.overrides.extraArgs).not.toContain('--mcp-config')+ expect(grid.overrides.extraArgs).not.toContain(CLAUDE_ALLOW_WEB_TOOLS_ARG)+ expect(grid.overrides.env).not.toHaveProperty(GRID_KEY_VAR)+ expect(JSON.stringify(grid.overrides)).not.toContain(withMcp.mcpUrl)+ // Claude Code's own web tools stay off, as on any grid.+ expect(grid.overrides.extraArgs).toContain(CLAUDE_DISALLOW_WEB_TOOLS_ARG)+ // What it gets on its own login, it gets on the grid: its folder for temporary files and its Buddy instructions.+ expect(grid.overrides.env).toMatchObject(buddyTmp)+ expect(own.overrides.env).toMatchObject(buddyTmp)+ const told = (args: string[]) => args[args.indexOf('--append-system-prompt') + 1]+ expect(told(own.overrides.extraArgs)).toContain('swarm-buddy')+ expect(told(grid.overrides.extraArgs)).toContain(told(own.overrides.extraArgs))+ // A session that is not a Buddy keeps the grid's web tools.+ const agent = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude',+ { startedBy: null, cwd, swarmSkill: { role: 'agent', key: 'harness-claude-plain' }, gridLaunch: withMcp }, 'a', () => true)+ expect(agent.ok && agent.overrides.extraArgs).toEqual(expect.arrayContaining(['--mcp-config', CLAUDE_ALLOW_WEB_TOOLS_ARG]))+ })})describe('buildLaunchOverrides — opencode v2', () => {diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 9cea8e67e..e6dbe27cd 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -232,6 +232,9 @@ export async function prepareLaunchOverrides(const swarm = deps.swarmconst owner = currentsource = structuredClone(source)+ // A Buddy starts no MCP server, and the grid's web tools are one: with `--strict-mcp-config` among its flags it would+ // load exactly that server (docs/swarms.md, Buddies). Launched from the grid without it, as on its own login.+ if (source.swarmSkill?.role === 'buddy' && source.gridLaunch) delete source.gridLaunch.mcpUrlconst inspected = capturedNative ? { ok: true as const, launch: capturedNative } : await deps.native?.(engine, source, { id: configKey, current: owner })if (!current()) return changedif (inspected && !inspected.ok) return inspecteddiff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex 0aaec5dd1..d8ad3df17 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -1889,6 +1889,30 @@ describe('registry across a reboot and pane loss', () => {expect(bound?.entry.subscriptionModel).toBe('opus')})+ // The conversation a fresh move onto a grid left (core/agents/retarget.ts): the way home reopens it.+ it('keeps the remembered subscription session across a reload and the binds on the grid', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ const s1 = join(dataDir, 'S1.jsonl'), s2 = join(dataDir, 'S2.jsonl')+ writeFileSync(s1, '{}\n'); writeFileSync(s2, '{}\n')+ registerProcess(registry, { launcherId: 'agent-1', sessionId: 'S1', transcriptPath: s1, tmuxPane: '%22', cwd: '/tmp/demo' })+ expect(registry.setSubscriptionSession('agent-1', 'S1')).toBe(true)+ expect(registry.setSubscriptionSession('nobody', 'S1')).toBe(false)+ const { registry: reloaded } = await loadRegistryModule()+ reloaded.load()+ expect(reloaded.byAgent('agent-1')?.subscriptionSessionId).toBe('S1')+ // The fresh conversation on the grid reports in: the same agent, the left one still remembered.+ const fresh = reloaded.register({ sessionId: 'S2', transcriptPath: s2, tmuxPane: '%22', cwd: '/tmp/demo' })+ expect(fresh?.entry).toMatchObject({ agentId: 'agent-1', sessionId: 'S2', subscriptionSessionId: 'S1' })+ // Home, the reopened conversation reports in: the same agent bound to it, not a new one.+ const back = reloaded.register({ sessionId: 'S1', transcriptPath: s1, tmuxPane: '%22', cwd: '/tmp/demo' })+ expect(back).toMatchObject({ rebound: 'S2', orphaned: null, entry: { agentId: 'agent-1', sessionId: 'S1' } })+ expect(reloaded.list()).toHaveLength(1)+ expect(reloaded.resolve('S1')?.agentId).toBe('agent-1')+ expect(reloaded.setSubscriptionSession('agent-1', null)).toBe(true)+ expect(reloaded.byAgent('agent-1')?.subscriptionSessionId).toBeUndefined()+ })+it('fills an old supported session role once and persists it through reload', async () => {const { registry } = await loadRegistryModule(); registry.load()const pending = registry.openPendingAgent({ engine: 'claude', cwd: dataDir, runtimes: [{ backend: 'tmux', paneId: '%21' }] })!diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 552a2a1a7..12405f864 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -174,6 +174,12 @@ export interface RegisteredSession {* model when it did.*/subscriptionModel?: string | null+ /**+ * The conversation this agent was in on its own login when a fresh move took it onto a grid+ * (`agent_retarget` with `fresh`: a conversation too long for the grid model's window). The way+ * home reopens it instead of the grid's, and forgets it once home. Absent when there is none.+ */+ subscriptionSessionId?: string/*** The CODEX_HOME folder this agent was launched against, if one was chosen instead of `~/.codex`.* Codex only. Unlike `grid`, this is chosen once at creation and never re-derived from the live@@ -1367,6 +1373,9 @@ class Registry {...(typeof raw?.subscriptionModel === 'string' && raw.subscriptionModel? { subscriptionModel: raw.subscriptionModel }: {}),+ ...(typeof raw?.subscriptionSessionId === 'string' && raw.subscriptionSessionId+ ? { subscriptionSessionId: raw.subscriptionSessionId }+ : {}),...(raw.bypassPermission === true ? { bypassPermission: true } : {}),...(permissionModeName(raw.permissionMode) ? { permissionMode: raw.permissionMode } : {}),...(raw.terminalHost === true || engine === 'terminal' ? { terminalHost: true } : {}),@@ -2045,6 +2054,8 @@ class Registry {// memory the moment the engine reports in. The symptom is a move back to the engine's own// login landing on a house default — the remembered model was there, then a hook bind ate it....(existing?.subscriptionModel ? { subscriptionModel: existing.subscriptionModel } : {}),+ // And for the conversation a fresh move left: the grid's first hook would otherwise forget the way home.+ ...(existing?.subscriptionSessionId ? { subscriptionSessionId: existing.subscriptionSessionId } : {}),defaultName: existing?.defaultName,transcriptPath: effectiveTranscriptPath,projectDir: engine === 'grok' || engine === 'agy' || engine === 'copilot'@@ -2549,6 +2560,18 @@ class Registry {return true}+ /** Remember the conversation a fresh move onto a grid left on the own login, or forget it (null) once+ * the agent is back in it. Kept while the agent is on a grid, across moves between grids. */+ setSubscriptionSession(agentId: string, sessionId: string | null): boolean {+ const session = this.agents.get(agentId)+ if (!session) return false+ if (sessionId) session.subscriptionSessionId = sessionId+ else delete session.subscriptionSessionId+ session.touchedAt = Date.now()+ this.save()+ return true+ }+/*** An app opened this agent: stamp `lastOpenedAt` with THIS daemon's clock. Never takes a time from* the caller — a phone and a laptop whose clocks disagree would otherwise order the same agentsdiff --git a/cli/src/superTabs/buddyModel.spec.ts b/cli/src/superTabs/buddyModel.spec.tsnew file mode 100644index 000000000..86a5122c6--- /dev/null+++ b/cli/src/superTabs/buddyModel.spec.ts@@ -0,0 +1,118 @@+// A Buddy's machine carrying out the model switch its owner asked the Swarm for (task #2354,+// docs/plans/2026-11-03-buddy-model-switch-design.md): it measures each session's conversation against the model's window, moves+// it through its own daemon's agent_retarget, and reports buddy.modelResult once.+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { BuddyModelRequests, type BuddyModelRow } from './buddyModel.js'++const GRID = 'swarm-0123456789ab'+const request = (over: Record<string, unknown> = {}) => ({ id: 'req1', gridModel: 'deepseek-4.1-flash', gridName: GRID, name: 'DeepSeek 4.1 Flash',+ servedBy: ['Mac Studio'], contextWindow: 131072, requestedBy: 'peer', at: '2026-11-03T10:00:00.000Z', ...over })+const main = (modelRequest: Record<string, unknown> | null = request()): BuddyModelRow => ({ tabId: 'tab', agent: { id: 'buddy', harnessId: 'h-main',+ buddyOf: { personId: 'peer', generation: 'first' }, ...(modelRequest ? { modelRequest } : {}) } })+const thread = (harnessId: string): BuddyModelRow => ({ tabId: 'tab', agent: { id: `s-${harnessId}`, harnessId,+ buddyOf: { personId: 'peer', generation: 'first' }, buddySession: { thread: 't', from: 0 } } })++function fixture(options: { tokens?: Record<string, number | null>; answers?: Array<Record<string, unknown>>; dataDir?: string } = {}) {+ const frames: Array<Record<string, unknown>> = []+ const posts: Array<Record<string, unknown>> = []+ const answers = [...(options.answers ?? [])]+ let now = 0+ const runner = new BuddyModelRequests({+ dataDir: options.dataDir ?? mkdtempSync(join(tmpdir(), 'buddy-model-')),+ now: () => now,+ log: () => {},+ open: async () => ({ request: async (type, payload) => { frames.push({ type, ...payload }); return answers.shift() ?? { retargeted: true } }, close: () => {} }),+ post: async (_tabId, agentId, _operationId, command) => { posts.push({ asAgentId: agentId, ...command }) },+ transcript: harnessId => `/transcripts/${harnessId}.jsonl`,+ tokens: async path => options.tokens?.[path.slice('/transcripts/'.length, -'.jsonl'.length)] ?? null,+ })+ return { runner, frames, posts, later: (ms: number) => { now += ms } }+}++describe('carrying out a Buddy\'s model request', () => {+ it('moves a conversation that fits onto the model, resuming it, and reports once', async () => {+ const f = fixture({ tokens: { 'h-main': 40_000 } })+ await f.runner.serve(main(), [])+ expect(f.frames).toEqual([{ type: 'agent_retarget', agentId: 'h-main', gridModel: 'deepseek-4.1-flash', gridName: GRID }])+ expect(f.posts).toEqual([{ asAgentId: 'buddy', type: 'buddy.modelResult', agentId: 'buddy', requestId: 'req1', ok: true }])+ await f.runner.serve(main(), [])+ expect([f.frames.length, f.posts.length]).toEqual([1, 1])+ })++ it('starts a fresh session when the conversation is 80% of the window or more', async () => {+ const f = fixture({ tokens: { 'h-main': 104_858 } })+ await f.runner.serve(main(), [])+ expect(f.frames).toEqual([{ type: 'agent_retarget', agentId: 'h-main', gridModel: 'deepseek-4.1-flash', gridName: GRID, fresh: true }])+ expect(f.posts).toEqual([expect.objectContaining({ ok: true, fresh: true })])+ })++ it('resumes when the window or the conversation\'s size is unknown', async () => {+ for (const [over, tokens] of [[{ contextWindow: undefined }, 120_000], [{}, null]] as const) {+ const f = fixture({ tokens: { 'h-main': tokens } })+ await f.runner.serve(main(request(over)), [])+ expect(f.frames[0]).not.toHaveProperty('fresh')+ }+ })++ it('moves the Buddy home to its own login', async () => {+ const f = fixture()+ await f.runner.serve(main(request({ gridModel: null, gridName: undefined, name: 'DeepSeek 4.1 Flash' })), [])+ expect(f.frames).toEqual([{ type: 'agent_retarget', agentId: 'h-main', clearGrid: true }])+ expect(f.posts).toEqual([expect.objectContaining({ ok: true })])+ })++ it('moves the Buddy\'s thread sessions too, each measured on its own, and names one that stayed', async () => {+ const f = fixture({ tokens: { 'h-main': 1_000, 'h-a': 120_000, 'h-b': 1_000 }, answers: [{ retargeted: true }, { retargeted: true }, { error: 'AGENT_BUSY' }] })+ await f.runner.serve(main(), [thread('h-a'), thread('h-b')])+ expect(f.frames.map(frame => [frame.agentId, frame.fresh ?? false])).toEqual([['h-main', false], ['h-a', true], ['h-b', false]])+ expect(f.posts).toEqual([expect.objectContaining({ ok: true, error: 'A thread session stayed where it was: it was answering' })])+ })++ it('says why a move was refused, in words its owner can act on', async () => {+ const cases: Array<[Record<string, unknown>, string]> = [+ [{ error: 'AGENT_BUSY' }, 'Your Buddy is answering. Try again when it has finished'],+ [{ error: 'GRID_UNAVAILABLE', detail: '/Users/someone/secret path' }, "Mac Studio isn't serving DeepSeek 4.1 Flash now"],+ [{ error: 'RESPAWN_FAILED', detail: 'tmux: /private/path' }, 'its computer could not switch it (RESPAWN_FAILED)'],+ ]+ for (const [answer, error] of cases) {+ const f = fixture({ answers: [answer] })+ await f.runner.serve(main(), [thread('h-a')])+ expect(f.frames).toHaveLength(1)+ expect(f.posts).toEqual([{ asAgentId: 'buddy', type: 'buddy.modelResult', agentId: 'buddy', requestId: 'req1', ok: false, error }])+ }+ })++ it('waits for the turn to end before sending a Buddy home by itself, then moves it', async () => {+ const f = fixture({ answers: [{ error: 'AGENT_BUSY' }, { retargeted: true }] })+ const home = main(request({ gridModel: null, gridName: undefined, reason: 'limit' }))+ await f.runner.serve(home, [])+ expect(f.posts).toEqual([])+ await f.runner.serve(home, [])+ expect(f.frames).toHaveLength(1)+ f.later(15_000)+ await f.runner.serve(home, [])+ expect(f.frames).toHaveLength(2)+ expect(f.posts).toEqual([expect.objectContaining({ ok: true })])+ })++ it('never carries out the same request twice, across a restart, and reports one it carried out but could not report', async () => {+ const dataDir = mkdtempSync(join(tmpdir(), 'buddy-model-'))+ const first = fixture({ dataDir })+ first.runner['deps'].post = async () => { throw new Error('offline') }+ await first.runner.serve(main(), [])+ expect(first.frames).toHaveLength(1)+ const second = fixture({ dataDir })+ await second.runner.serve(main(), [])+ expect(second.frames).toEqual([])+ expect(second.posts).toEqual([expect.objectContaining({ requestId: 'req1', ok: true })])+ })++ it('does nothing for a Buddy with no request', async () => {+ const f = fixture()+ await f.runner.serve(main(null), [])+ expect([f.frames, f.posts]).toEqual([[], []])+ })+})diff --git a/cli/src/superTabs/buddyModel.ts b/cli/src/superTabs/buddyModel.tsnew file mode 100644index 000000000..5cb4f1a26--- /dev/null+++ b/cli/src/superTabs/buddyModel.ts@@ -0,0 +1,157 @@+/**+ * A Buddy's machine carrying out the model switch its owner asked the Swarm for (task #2354,+ * docs/plans/2026-11-03-buddy-model-switch-design.md; backend superTabs/buddyModel.ts). It moves the Buddy, and then each of its+ * thread sessions, through this machine's own daemon's `agent_retarget`, the move a pane's model picker makes: the pane relaunches+ * Claude Code in place and reopens the same conversation. A conversation too long for the model's window starts fresh there+ * instead; the daemon keeps the one it left, which the way home reopens.+ *+ * Each request is carried out once: its outcome is written before it is reported, so a restart reports it rather than moving the+ * Buddy again.+ */+import { createHash } from 'node:crypto'+import { existsSync, renameSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import type { Daemon } from '../agentClient/daemon.js'+import { readPrivateStateFile, secureStateDirectory } from '../lib/secureState.js'+import { identifier, object } from './wire.js'++/** A conversation this share of the model's window or more starts fresh: the rest is the room its next turns need. */+export const FRESH_SHARE = 0.8+/** How long a move may take: the daemon stops the engine, relaunches it and waits for it to come up. */+const MOVE_TIMEOUT_MS = 120_000+/** How soon a request that waits (a Buddy sent home mid-turn) or a report that failed is tried again. */+const RETRY_MS = 15_000++interface ModelRequest { id: string; gridModel: string | null; gridName?: string; name?: string; servedBy?: string[]; contextWindow?: number; reason?: string }+/** A Buddy agent's row as this machine's host reads it (backend read/hostRows.ts). */+export interface BuddyModelRow {+ tabId: string+ agent: { id: string; harnessId: string; buddyOf?: unknown; buddySession?: unknown; modelRequest?: unknown }+}+interface Outcome { ok: boolean; fresh?: true; error?: string }+export interface BuddyModelDeps {+ dataDir: string+ now: () => number+ log: (message: string) => void+ open: () => Promise<Pick<Daemon, 'request' | 'close'>>+ post: (tabId: string, agentId: string, operationId: string, command: Record<string, unknown>) => Promise<unknown>+ /** The Claude Code transcript of this machine's session [harnessId], when it has one. */+ transcript: (harnessId: string) => string | null | undefined+ /** How long that conversation is now, in tokens (lib/conversationSize.ts). */+ tokens: (transcriptPath: string) => Promise<number | null>+}++function requestOf(value: unknown): ModelRequest | null {+ const r = object(value)+ if (!identifier(r.id) || !(r.gridModel === null || typeof r.gridModel === 'string')) return null+ return { id: r.id, gridModel: r.gridModel, ...(typeof r.gridName === 'string' ? { gridName: r.gridName } : {}),+ ...(typeof r.name === 'string' ? { name: r.name } : {}),+ ...(Array.isArray(r.servedBy) ? { servedBy: r.servedBy.filter((s): s is string => typeof s === 'string') } : {}),+ ...(typeof r.contextWindow === 'number' && r.contextWindow > 0 ? { contextWindow: r.contextWindow } : {}),+ ...(typeof r.reason === 'string' ? { reason: r.reason } : {}) }+}++/** Why a move was refused, in words its owner can act on: never the daemon's detail, which can name paths on this machine. */+function refusal(code: string, request: ModelRequest): string {+ if (code === 'AGENT_BUSY') return 'Your Buddy is answering. Try again when it has finished'+ if ((code === 'GRID_UNAVAILABLE' || code === 'API_UNAVAILABLE') && request.gridModel) {+ const name = request.name ?? request.gridModel+ return request.servedBy?.length ? `${request.servedBy.join(', ')} isn't serving ${name} now` : `Nobody serves ${name} now`+ }+ return `its computer could not switch it (${code.replace(/[^A-Z0-9_]/g, '').slice(0, 60) || 'FAILED'})`+}++export class BuddyModelRequests {+ /** Requests reported, or settled elsewhere: never carried out again by this process. */+ private readonly done = new Set<string>()+ private readonly waiting = new Map<string, { busy: boolean; retryAt: number }>()+ constructor(private readonly deps: BuddyModelDeps) {}++ /** One poll of a main Buddy row of this machine, with its thread sessions' rows. */+ async serve(row: BuddyModelRow, sessions: readonly BuddyModelRow[]): Promise<void> {+ const request = requestOf(row.agent.modelRequest)+ if (!request || this.done.has(request.id)) return+ const now = this.deps.now(), held = this.waiting.get(request.id)+ if (held && (held.busy || now < held.retryAt)) return+ this.waiting.set(request.id, { busy: true, retryAt: 0 })+ try {+ const recorded = this.recorded(row.agent.id)+ let outcome = recorded?.requestId === request.id ? recorded.outcome : undefined+ if (!outcome) {+ const carried = await this.carryOut(row, sessions, request)+ if (carried === 'wait') { this.waiting.set(request.id, { busy: false, retryAt: now + RETRY_MS }); return }+ outcome = carried+ this.record(row.agent.id, { requestId: request.id, outcome })+ }+ try {+ await this.deps.post(row.tabId, row.agent.id, `buddy-model-${request.id}`.slice(0, 160),+ { type: 'buddy.modelResult', agentId: row.agent.id, requestId: request.id, ...outcome })+ } catch (failure) {+ // A request the Swarm already settled (its lease ran out) is done; any other failure is reported again later.+ if (object(failure).code !== 'STALE_SWITCH') { this.waiting.set(request.id, { busy: false, retryAt: now + RETRY_MS }); return }+ }+ this.done.add(request.id)+ this.waiting.delete(request.id)+ } catch (error) {+ this.deps.log(`Buddy model: ${error instanceof Error ? error.name : typeof error}`)+ this.waiting.set(request.id, { busy: false, retryAt: now + RETRY_MS })+ }+ }++ private async carryOut(row: BuddyModelRow, sessions: readonly BuddyModelRow[], request: ModelRequest): Promise<Outcome | 'wait'> {+ const daemon = await this.deps.open()+ try {+ const move = async (harnessId: string): Promise<{ error?: string; fresh: boolean }> => {+ const fresh = await this.tooLong(harnessId, request)+ const frame = request.gridModel === null ? { agentId: harnessId, clearGrid: true }+ : { agentId: harnessId, gridModel: request.gridModel, gridName: request.gridName, ...(fresh ? { fresh: true } : {}) }+ const reply = await daemon.request('agent_retarget', frame, MOVE_TIMEOUT_MS).catch(() => ({ error: 'TIMEOUT' }))+ return { ...(typeof reply.error === 'string' ? { error: reply.error } : {}), fresh }+ }+ const moved = await move(row.agent.harnessId)+ if (moved.error) {+ // Sent home by the Swarm (a limit, a model gone) while it answers: moved once the turn ends, within the request's lease.+ if (moved.error === 'AGENT_BUSY' && request.reason) return 'wait'+ return { ok: false, error: refusal(moved.error, request) }+ }+ const stayed: string[] = []+ for (const session of sessions) {+ const result = await move(session.agent.harnessId)+ if (result.error) stayed.push(result.error === 'AGENT_BUSY' ? 'it was answering' : refusal(result.error, request))+ }+ return { ok: true, ...(moved.fresh ? { fresh: true as const } : {}),+ ...(stayed.length === 1 ? { error: `A thread session stayed where it was: ${stayed[0]}` }+ : stayed.length ? { error: `${stayed.length} thread sessions stayed where they were: ${stayed[0]}` } : {}) }+ } finally { daemon.close() }+ }++ /** Whether [harnessId]'s conversation is too long for the model it moves onto. Unknown counts as fitting: it resumes, as a+ * pane's switch does. */+ private async tooLong(harnessId: string, request: ModelRequest): Promise<boolean> {+ if (request.gridModel === null || !request.contextWindow) return false+ const path = this.deps.transcript(harnessId)+ const tokens = path ? await this.deps.tokens(path).catch(() => null) : null+ return tokens !== null && tokens >= FRESH_SHARE * request.contextWindow+ }++ private file(agentId: string): string {+ return join(this.deps.dataDir, 'super-tabs', 'buddy-model', `${createHash('sha256').update(agentId).digest('hex')}.json`)+ }+ /** The last request carried out for this Buddy (one per Buddy, replaced by the next). */+ private recorded(agentId: string): { requestId: string; outcome: Outcome } | null {+ const file = this.file(agentId)+ if (!existsSync(file)) return null+ try {+ const row = object(JSON.parse(readPrivateStateFile(file, 4_096))), outcome = object(row.outcome)+ if (!identifier(row.requestId) || typeof outcome.ok !== 'boolean') return null+ return { requestId: row.requestId, outcome: { ok: outcome.ok, ...(outcome.fresh === true ? { fresh: true } : {}),+ ...(typeof outcome.error === 'string' ? { error: outcome.error.slice(0, 300) } : {}) } }+ } catch { return null }+ }+ private record(agentId: string, value: { requestId: string; outcome: Outcome }): void {+ const file = this.file(agentId)+ secureStateDirectory(join(this.deps.dataDir, 'super-tabs', 'buddy-model'))+ writeFileSync(`${file}.tmp`, JSON.stringify(value), { mode: 0o600 })+ renameSync(`${file}.tmp`, file)+ }+}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 53098effb..d19063ac8 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -3967,6 +3967,26 @@ function lifeFixture(rows: Record<string, unknown>[], options: SuperTabHostOptio}const leadRow = (extra: Record<string, unknown> = {}) => ({ tabId: 'tab', lead: true, active: true, agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }, ...extra })+// Task #2354: the switch its owner asked for reaches the Buddy's machine on its row, and is carried out there with the Buddy's+// thread sessions on this machine (superTabs/buddyModel.ts).+describe('a Buddy\'s model request', () => {+ const BUDDY_OF = { personId: 'peer', generation: 'g' }+ const buddyRow = (agent: Record<string, unknown>) => ({ tabId: 'tab', active: true, agent: { machineId: 'machine-1', buddyOf: BUDDY_OF, ...agent } })++ it('is handed to the Buddy model runner with the Buddy\'s own thread sessions, and no one else\'s', async () => {+ const serve = vi.fn(async () => {})+ const main = buddyRow({ id: 'buddy', harnessId: 'h-main', modelRequest: { id: 'req1', gridModel: 'm' } })+ const session = buddyRow({ id: 'session', harnessId: 'h-session', buddySession: { thread: 't', from: 0 } })+ const other = { tabId: 'tab', active: true, agent: { id: 'other', harnessId: 'h-other', machineId: 'machine-1',+ buddyOf: { personId: 'someone', generation: 'g' }, buddySession: { thread: 'u', from: 0 } } }+ const t = lifeFixture([main, session, other], { buddyModels: { serve } })+ await t.poll()+ await vi.waitFor(() => expect(serve).toHaveBeenCalledTimes(1))+ expect(serve).toHaveBeenCalledWith(expect.objectContaining({ agent: expect.objectContaining({ id: 'buddy' }) }),+ [expect.objectContaining({ agent: expect.objectContaining({ id: 'session' }) })])+ })+})+// Spec 2026-10-30-buddy-thread-sessions: a Buddy's thread session never stays on its person's machine once its thread is done// with it. Its host asks the backend to end it, as the machine's owner, when idle or when its terminal is gone.describe('ending a Buddy\'s thread sessions', () => {diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex b2eb79d1f..48ebb1d1c 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -24,6 +24,9 @@ import { RebindSender, replacementObservations } from './replacements.js'import { TerminalHost } from './terminal.js'import { LimitResume } from './limitResume.js'import { LeadSwitchRequests, type SwitchRow } from './leadSwitchRequest.js'+import { BuddyModelRequests, type BuddyModelRow } from './buddyModel.js'+import { openDaemon } from '../agentClient/daemon.js'+import { conversationTokens } from '../lib/conversationSize.js'import { isTeamDaemon } from './teamDaemon.js'import { HostFeed } from './hostFeed.js'import { SwarmReads } from './swarmReads.js'@@ -203,6 +206,8 @@ export interface SuperTabHostOptions {sources?: SwarmSources/** What the contributed-machine executor reaches the local daemon with (superTabs/machines.ts), for a spec. */machines?: Partial<MachineDeps>+ /** What carries out a Buddy's model switch here (superTabs/buddyModel.ts), for a spec. */+ buddyModels?: Pick<BuddyModelRequests, 'serve'>}const defaultAgentCommand = (core: CoreApi, machineId: string) => agentCommandPrefix(core.daemon, machineId,@@ -509,6 +514,8 @@ export class SuperTabHost {private readonly releases = new Set<string>()/** The switches the Swarm asked of this machine's PMs (leadSwitchRequest.ts). */private readonly leadSwitches: LeadSwitchRequests+ /** The model switches the Swarm asked of this machine's Buddies (buddyModel.ts). */+ private readonly buddyModels: Pick<BuddyModelRequests, 'serve'>private readonly rebinds: RebindSender/** Eligibility and failures belong to this stop and native runtime; a new runtime or stop gets a fresh decision. *//** `failures` counts final answers toward the five tries; `waits` the transient ones behind the current backoff. */@@ -600,6 +607,11 @@ export class SuperTabHost {.some(a => a.tabId === tabId && a.assignmentId === assignmentId && a.harnessId === harnessId) })this.rebinds = new RebindSender((path, body) => backend(this.core, 'POST', path, body), this.now)this.leadSwitches = new LeadSwitchRequests(core, machineId, { now: this.now, log: this.log, team: isTeamDaemon })+ // Over this machine's own daemon socket, which answers as the machine owner: the Buddy runs only on its owner's machine.+ this.buddyModels = options.buddyModels ?? new BuddyModelRequests({ dataDir: core.dataDir, now: this.now, log: this.log,+ open: () => openDaemon({ dataDir: core.dataDir, port: core.daemon.port, machineId }),+ post: (tabId, agentId, operationId, command) => backend(core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId, asAgentId: agentId, command }),+ transcript: harnessId => core.agents.byAgent(harnessId)?.transcriptPath, tokens: conversationTokens })this.sources = options.sources ?? { feed: new HostFeed(core, machineId, { now: this.now }), reads: new SwarmReads(core) }this.journal = { version: 1, machineId, entries: {} }if (existsSync(this.file)) {@@ -779,6 +791,21 @@ export class SuperTabHost {}/** Re-read stop intent and native launch authority; require core evidence before confirming removal. */+ /** A Buddy's model switch (buddyModel.ts): its main row carries the request, and its thread sessions on this machine move with+ * it. Not awaited: a move relaunches Claude Code and must not hold up this poll's deliveries. */+ private serveBuddyModels(data: readonly unknown[]): void {+ const rows = data.map(object).filter(row => identifier(row.tabId) && object(row.agent).machineId === this.machineId+ && identifier(object(row.agent).harnessId) && object(row.agent).buddyOf)+ const ownerOf = (row: Record<string, unknown>) => { const of = object(object(row.agent).buddyOf); return `${row.tabId}\0${of.personId}\0${of.generation}` }+ for (const row of rows) {+ const agent = object(row.agent)+ if (agent.buddySession || !agent.modelRequest) continue+ const sessions = rows.filter(other => object(other.agent).buddySession && ownerOf(other) === ownerOf(row))+ void this.buddyModels.serve(row as unknown as BuddyModelRow, sessions as unknown as BuddyModelRow[])+ .catch(error => this.log(`Buddy model: ${error instanceof Error ? error.name : typeof error}`))+ }+ }+private async releaseWorker(target: HostAgent): Promise<void> {const { tabId, agent } = targetconst key = `${tabId}:${agent.id}`@@ -1083,6 +1110,7 @@ export class SuperTabHost {const listed = new Set<string>()const running: HostAgent[] = []const leads = new Set<string>(), ended = new Set<string>()+ this.serveBuddyModels(data)for (const item of data) {const row = object(item), agent = object(row.agent)if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId) || agent.machineId !== this.machineId) continuediff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex a92516f71..90ab58169 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -343,7 +343,7 @@ describe('contributed machine executor', () => {Object.assign(f.pool, { capabilitiesWanted: true })await f.machine.tick()const posted = (g: typeof f) => g.backend.mock.calls.filter(c => c[1] === 'POST').map(c => c[3] as Record<string, unknown>)- expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'leadSwitch'] })+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'leadSwitch', 'buddyModel'] })// A backend from before them does not ask, and would refuse the field.const older = fixture()await older.machine.tick()diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex f3b45b987..f5f2912ba 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -186,6 +186,9 @@ const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy']/** What this host does for a Product Manager's switch to another engine or account (spec 2026-11-02-pm-switch-engine-account),* said beside the others: the backend refuses a switch to a host that does not. */CAPABILITIES.push('leadSwitch')+/** What this host does for a Buddy's model switch (task #2354, superTabs/buddyModel.ts): the backend refuses a switch to a host+ * that does not say so. */+CAPABILITIES.push('buddyModel')/** The backend's answer that this machine may no longer act in the Swarm: signed out, its contribution revoked or its host* unavailable (backend store.ts observeMachine), or the Swarm gone. */const lostAccess = (error: unknown) => error instanceof SuperTabHostError && [401, 403, 404].includes(error.status)diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dartindex 5146b7cfc..a5eb04023 100644--- a/desktop/lib/super_tabs/buddies.dart+++ b/desktop/lib/super_tabs/buddies.dart@@ -9,6 +9,7 @@ import '../state/app_state.dart';import '../widgets/desktop_chrome.dart';import 'controller.dart';import 'buddy_machines.dart';+import 'buddy_model.dart';import 'dialog_scope.dart';import 'identity.dart';import 'model.dart';@@ -625,7 +626,17 @@ class SuperTabBuddyBar extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.stretch,mainAxisSize: MainAxisSize.min,children: [- Text(where, style: DesktopChrome.metadata()),+ // The one Buddy switches between its person's subscription and a+ // model shared in the Swarm (task #2354); a project's Buddy cannot.+ if (chat.isSwarmBuddyChat)+ BuddyModelLine(+ controller: c,+ agent: agent,+ machine: machine,+ rest: where,+ )+ else+ Text(where, style: DesktopChrome.metadata()),if (agent.downSince != null)Row(children: [diff --git a/desktop/lib/super_tabs/buddy_model.dart b/desktop/lib/super_tabs/buddy_model.dartnew file mode 100644index 000000000..0cec9837e--- /dev/null+++ b/desktop/lib/super_tabs/buddy_model.dart@@ -0,0 +1,238 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_menu.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/finger_target.dart';+import 'controller.dart';+import 'identity.dart';+import 'model.dart';++/// A model a person may switch their Buddy to, and who serves it: machines by+/// name for a model they run, `<member>'s saved API` for an API a member+/// shares. A model several machines serve names them all; the Swarm's grid+/// picks one per request.+typedef BuddyModelOffer = ({String model, String name, List<String> servedBy});++/// What the server lets a Buddy switch to (backend buddyModel.ts, machines.ts+/// `servedLocalModels`): every model on this Swarm's grid in a fresh reading of+/// a machine of the Swarm, once each. Never a model of another grid a member+/// is signed into, which only that member's machine reaches.+List<BuddyModelOffer> buddyModelOffers(+ SuperTabSnapshot snapshot, {+ required DateTime now,+}) {+ final grid = snapshot.localModels?.grid;+ final offers = <String, BuddyModelOffer>{};+ for (final row in superTabLocalModelRows(snapshot, now: now)) {+ if (row.grid != grid || !const {'local', 'api'}.contains(row.kind)) {+ continue;+ }+ final server = row.kind == 'api'+ ? "${_sharer(snapshot, row.machineId)}'s saved API"+ : superTabMachineName(row.machine);+ final offer = offers[row.model] ??= (+ model: row.model,+ name: row.name,+ servedBy: <String>[],+ );+ if (!offer.servedBy.contains(server)) offer.servedBy.add(server);+ }+ return offers.values.toList();+}++String _sharer(SuperTabSnapshot snapshot, String machineId) =>+ snapshot.usernameOf(+ snapshot.pool(machineId)?['contributorId'] as String? ?? '',+ ) ??+ 'a member';++/// Who serves [offer], as the server's lines say it (backend buddyModel.ts).+String _servers(BuddyModelOffer offer) {+ final servers = offer.servedBy.join(', ');+ return offer.servedBy.every((s) => s.endsWith("'s saved API"))+ ? servers+ : 'served by $servers';+}++/// The Buddy bar's line with the model picker first (task #2354): the+/// subscription or the shared model the Buddy runs on and who serves it, then+/// [rest]. While a switch is under way it says where to and opens nothing.+class BuddyModelLine extends StatefulWidget {+ const BuddyModelLine({+ super.key,+ required this.controller,+ required this.agent,+ required this.machine,+ required this.rest,+ });++ final SuperTabController controller;++ /// The reader's own main Buddy.+ final SuperTabAgent agent;++ /// Its machine's name, for the line that asks to add it to the Swarm.+ final String machine;++ /// The bar's line after the picker.+ final String rest;++ @override+ State<BuddyModelLine> createState() => _BuddyModelLineState();+}++class _BuddyModelLineState extends State<BuddyModelLine> {+ final _menu = MenuController();++ SuperTabController get c => widget.controller;++ /// A refusal shows under the chat's composer, as the bar's other Buddy+ /// actions' do (`SuperTabController.composerError`).+ void _pick(String? model) {+ _menu.close();+ if (model == widget.agent.gridModel) return;+ unawaited(c.switchBuddyModel(model));+ }++ @override+ Widget build(BuildContext context) {+ final snapshot = c.snapshot!;+ final agent = widget.agent;+ final now = DateTime.now();+ final offers = buddyModelOffers(snapshot, now: now);+ final current = agent.gridModel;+ final on = offers.where((o) => o.model == current).firstOrNull;+ // A model gone quiet is still named by the last reading that served it.+ String nameOf(String model) =>+ offers.where((o) => o.model == model).firstOrNull?.name ??+ superTabLocalModelRows(+ snapshot,+ now: now,+ freshFor: null,+ ).where((r) => r.model == model).firstOrNull?.name ??+ model;+ final request = agent.modelRequest;+ final phone = workspaceIsCompact(context);+ final busy = !c.canWrite || c.saving || c.hasPendingAction;+ final after = [+ if (request == null && current != null)+ on == null ? 'not served now' : _servers(on),+ widget.rest,+ ].join(' · ');+ final picker = request != null+ ? Text(+ request.gridModel == null+ ? 'Switching to your subscription…'+ : 'Switching to ${request.name ?? nameOf(request.gridModel!)}…',+ style: DesktopChrome.metadata(),+ )+ : _anchor(+ label: current == null ? 'Your subscription' : nameOf(current),+ offers: offers,+ phone: phone,+ busy: busy,+ );+ return Text.rich(+ TextSpan(+ children: [+ WidgetSpan(+ alignment: PlaceholderAlignment.middle,+ child: KeyedSubtree(+ key: const ValueKey('super-buddy-model'),+ child: picker,+ ),+ ),+ TextSpan(text: ' · $after'),+ ],+ ),+ style: DesktopChrome.metadata(),+ );+ }++ Widget _anchor({+ required String label,+ required List<BuddyModelOffer> offers,+ required bool phone,+ required bool busy,+ }) {+ final current = widget.agent.gridModel;+ final pool = c.snapshot!.pool(widget.agent.machineId);+ Widget row(AppMenuItem item) => fingerTarget(enabled: phone, item);+ Widget words(String text) => Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.menuInset,+ ),+ child: Text(text, style: DesktopChrome.metadata()),+ );+ return MenuAnchor(+ controller: _menu,+ consumeOutsideTap: true,+ // Held to the style's width, so the longer lines wrap.+ crossAxisUnconstrained: false,+ alignmentOffset: const Offset(0, grid.AppControl.menuGap),+ style: grid.AppMenu.style(minWidth: 220, maxWidth: 440, maxHeight: 520),+ menuChildren: [+ row(+ AppMenuItem(+ icon: current == null ? AppIcons.check : null,+ label: 'Your subscription',+ note: 'Claude Code',+ expandLabel: true,+ onPressed: () => _pick(null),+ ),+ ),+ const AppMenuDivider(),+ words('SHARED IN THIS SWARM'),+ // A Buddy-only machine never joins the Swarm's grid (backend+ // read/hostRows.ts), so nothing shared reaches a Buddy there.+ if (pool == null || pool['buddyOnly'] == true)+ words(+ "Add ${widget.machine} to the Swarm's Machines to use shared models.",+ )+ else if (offers.isEmpty)+ words('Nobody shares a model in this Swarm yet.')+ else+ for (final offer in offers)+ row(+ AppMenuItem(+ icon: offer.model == current ? AppIcons.check : null,+ label: offer.name,+ // Under the name: a list of servers would be cut short beside it.+ detail: _servers(offer),+ onPressed: () => _pick(offer.model),+ ),+ ),+ const AppMenuDivider(),+ words(+ 'What your Buddy reads and writes goes to the machine or API that serves the model you pick.',+ ),+ ],+ builder: (context, menu, _) => fingerTarget(+ enabled: phone,+ InkWell(+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ onTap: busy ? null : () => menu.isOpen ? menu.close() : menu.open(),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ label,+ style: DesktopChrome.metadata(color: DesktopChrome.foreground),+ ),+ Icon(+ AppIcons.chevronDown,+ size: AppIcons.inlineSize,+ color: DesktopChrome.muted,+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 001452d1f..258f14acf 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -3107,6 +3107,13 @@ class SuperTabController extends ChangeNotifier {null;}+ /// Moves the reader's one Buddy onto [gridModel], a model shared in the+ /// Swarm, or back to their own subscription when null (backend+ /// buddyModel.ts). Its machine carries it out; the Buddy's `modelRequest`+ /// shows it under way. False when refused: [operationError] says why.+ Future<bool> switchBuddyModel(String? gridModel) async =>+ await command({'type': 'buddy.model', 'gridModel': gridModel}) != null;+/// Whether [group] is out of the app: there is no private channel to the/// PM (Ken, 10-29), so no private chat but a Buddy chat is listed or opened,/// the reader's old Chat with PM that an older server still sends included.diff --git a/desktop/lib/super_tabs/local_models.dart b/desktop/lib/super_tabs/local_models.dartindex 3474790d4..bfa4021c5 100644--- a/desktop/lib/super_tabs/local_models.dart+++ b/desktop/lib/super_tabs/local_models.dart@@ -16,6 +16,7 @@ import '../widgets/key_hints.dart';import '../widgets/swarm_resource_preview.dart';import '../widgets/swarm_switcher.dart';import '../ws/ws_conn.dart';+import 'buddies.dart' show buddyPersonName;import 'controller.dart';import 'dialog_scope.dart';import 'model.dart';@@ -564,7 +565,7 @@ class SuperTabMachineLocalModels extends StatelessWidget {// A fresh reading only, as the route reads it; then each model by what it is: an API this machine's person// shares, or a model of theirs running for the Swarm.final fresh = superTabServedModels(pool, local.grid, now: now());- final apis = <String>[], models = <String>[];+ final apis = <SuperTabServedModel>[], models = <SuperTabServedModel>[];final observed = pool?['observation'];for (final min observed is Map && observed['localModels'] is List@@ -576,16 +577,31 @@ class SuperTabMachineLocalModels extends StatelessWidget {if (!fresh.any((f) => f.model == m['model'])) continue;final model = m['model'] as String;if (m['kind'] == 'api') {- apis.add(- model.contains('/')+ apis.add((+ model: model,+ name: model.contains('/')? model.substring(model.lastIndexOf('/') + 1): model,- );+ ));} else {- models.add(m['name'] is String ? m['name'] as String : model);+ models.add((+ model: model,+ name: m['name'] is String ? m['name'] as String : model,+ ));}}- Widget line(String label, List<String> names) => Padding(+ // Whoever serves a model sees whose Buddy runs on it (PRODUCT.md,+ // Contribution: seen), from the Buddies every member's read carries.+ String? usedBy(String model) {+ final people = {+ for (final a in controller.snapshot!.agents)+ if (a.isBuddy && a.gridModel == model)+ "${buddyPersonName(controller, a.buddyOf!)}'s Buddy",+ };+ return people.isEmpty ? null : 'Used by ${people.join(', ')}';+ }++ Widget line(String label, List<SuperTabServedModel> served) => Padding(padding: const EdgeInsets.symmetric(vertical: 5),child: Row(crossAxisAlignment: CrossAxisAlignment.start,@@ -596,12 +612,21 @@ class SuperTabMachineLocalModels extends StatelessWidget {),const SizedBox(width: 16),Expanded(- child: Text(- names.isEmpty ? 'None' : names.join(', '),- style: names.isEmpty- ? DesktopChrome.control(color: DesktopChrome.muted)- : DesktopChrome.control(),- ),+ child: served.isEmpty+ ? Text(+ 'None',+ style: DesktopChrome.control(color: DesktopChrome.muted),+ )+ : Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (final s in served) ...[+ Text(s.name, style: DesktopChrome.control()),+ if (usedBy(s.model) case final used?)+ Text(used, style: DesktopChrome.metadata()),+ ],+ ],+ ),),],),diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 20ee041fa..1a1111384 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -177,6 +177,15 @@ class SuperTabAgent {switchRequest = row['switchRequest'] is Map? Map.unmodifiable(superTabMap(row['switchRequest'])): null,+ gridModel = row['gridModel'] as String?,+ modelRequest = switch (row['modelRequest']) {+ {'id': final String id} && final Map request => (+ id: id,+ gridModel: request['gridModel'] as String?,+ name: request['name'] as String?,+ ),+ _ => null,+ },profileId = row['profileId'] as String?,avatar = SuperTabAvatarPicture.fromJson(row['avatar']),downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),@@ -200,6 +209,15 @@ class SuperTabAgent {/// and not yet done (backend `switchRequest`); null otherwise.final Map<String, dynamic>? switchRequest;+ /// The model on the Swarm's grid it runs on; null on its own subscription+ /// (backend Agent.gridModel).+ final String? gridModel;++ /// A person's switch of their Buddy's model that is asked for and not yet+ /// done (backend buddyModel.ts `modelRequest`); null otherwise. A null+ /// [gridModel] there is the way back to their subscription.+ final ({String id, String? gridModel, String? name})? modelRequest;+/// The account on its machine it runs in; `default` when none is chosen./// Null until the backend reports it: the engine's default account.final String? profileId;@@ -833,6 +851,10 @@ class SuperTabSnapshot {return '${agentName(agentId)} is the ${coordinatorNameOf(project.id)} of project ${project.name}. Delete the project first.';}+ /// The person [personId] by the name the Swarm shows: their username; null for someone not in it.+ String? usernameOf(String personId) =>+ people.where((p) => p.id == personId).firstOrNull?.username;+String agentName(String id, {String fallback = 'Agent'}) =>agent(id)?.displayName ?? agent(id)?.name ?? fallback;@@ -940,35 +962,40 @@ class SuperTabLocalModels {final String? error;}-/// One model the Swarm's agents can run on now, as a machine's fresh reading says: on the Swarm's grid (`local`, a-/// member's engine; `api`, an API a member shares), usable from any machine; or shared with the machine's owner and-/// offered by them (`shared`), usable on that machine alone.+/// One model a machine of the Swarm serves, as its reading says: on the Swarm's grid (`local`, a member's engine;+/// `api`, an API a member shares), usable from any machine; or shared with the machine's owner and offered by them+/// (`shared`), usable on that machine alone.typedef SuperTabLocalModelRow = ({String grid,String model,String name,+ String machineId,String machine,String kind,});-/// Every model the Swarm can use now, once each, from the machines' fresh readings (backend `MACHINE_FRESH_MS`).+/// Every model the Swarm's machines serve now, once per machine, from their fresh readings (backend+/// `MACHINE_FRESH_MS`); with [freshFor] null, from readings of any age. A Buddy-only machine is not one of the Swarm's+/// (backend machines.ts `swarmMachines`).List<SuperTabLocalModelRow> superTabLocalModelRows(SuperTabSnapshot? snapshot, {required DateTime now,- Duration freshFor = const Duration(seconds: 45),+ Duration? freshFor = const Duration(seconds: 45),}) {final local = snapshot?.localModels;if (local == null || !local.enabled) return const [];final rows = <SuperTabLocalModelRow>[];for (final pool in snapshot!.machines) {final observation = pool['observation'];- if (observation is! Map) continue;+ if (pool['buddyOnly'] == true || observation is! Map) continue;final at = observation['receivedAt'];if (at is! num ||- now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) >- freshFor) {+ (freshFor != null &&+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) >+ freshFor)) {continue;}+ final machineId = pool['machineId'] as String? ?? '';for (final min observation['localModels'] is List? observation['localModels'] as List@@ -981,11 +1008,16 @@ List<SuperTabLocalModelRow> superTabLocalModelRows(continue;}final grid = m['grid'] as String, model = m['model'] as String;- if (rows.any((r) => r.grid == grid && r.model == model)) continue;+ if (rows.any(+ (r) => r.machineId == machineId && r.grid == grid && r.model == model,+ )) {+ continue;+ }rows.add((grid: grid,model: model,name: m['name'] is String ? m['name'] as String : model,+ machineId: machineId,machine: pool['name'] as String? ?? 'A machine',kind: m['kind'] is String? m['kind'] as Stringdiff --git a/desktop/test/super_tab_buddies_shots_test.dart b/desktop/test/super_tab_buddies_shots_test.dartindex b8a7453a8..98410aeea 100644--- a/desktop/test/super_tab_buddies_shots_test.dart+++ b/desktop/test/super_tab_buddies_shots_test.dart@@ -83,7 +83,108 @@ void main() {return server;}+ /// Ken's one Buddy and models shared in the Swarm (task #2354): one served+ /// by two machines, an API a member shares.+ ConversationServer sharedModels({String? gridModel}) {+ const swarmGrid = 'swarm-0123456789ab';+ final server = oneBuddySwarm();+ server.state['people'] = [+ ...server.state['people'] as List,+ {'id': 'diego', 'email': '[email protected]', 'role': 'collaborator'},+ ];+ giveSwarmBuddy(server);+ if (gridModel != null) {+ (server.state['agents'] as List).cast<Map>().firstWhere(+ (a) => a['id'] == 'wren',+ )['gridModel'] = gridModel;+ }+ server.state['localModels'] = {+ 'grid': swarmGrid,+ 'enabled': true,+ 'ready': true,+ };+ Map<String, dynamic> machine(+ String id,+ String name,+ String contributor,+ List<(String, String, String)> served,+ ) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': contributor,+ 'scope': 'swarm',+ 'engines': <dynamic>[],+ 'maxAgents': 4,+ 'availableSlots': 4,+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'localModels': [+ for (final (model, name, kind) in served)+ {'grid': swarmGrid, 'model': model, 'name': name, 'kind': kind},+ ],+ },+ };+ server.state['machines'] = [+ (server.state['machines'] as List).first,+ machine('studio', "Ken's Mac Studio", 'owner', [+ ('deepseek-4.1-flash', 'DeepSeek 4.1 Flash', 'local'),+ ('kimi-k3', 'Kimi K3', 'local'),+ ]),+ machine('mini', "Tony's Mac mini", 'owner', [+ ('kimi-k3', 'Kimi K3', 'local'),+ ]),+ machine('diego-mac', 'Diego-MacBook', 'diego', [+ ('openai/gpt-6.1-sol', 'GPT-6.1 Sol', 'api'),+ ]),+ ];+ return server;+ }+for (final brightness in Brightness.values) {+ testWidgets('Buddy model picker in ${brightness.name}', (tester) async {+ if (shots == null) return;+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ tester.view.devicePixelRatio = 2;+ tester.view.physicalSize = const Size(2400, 1400);+ addTearDown(tester.view.reset);+ for (final (name, gridModel) in [('menu', null), ('shared', 'kimi-k3')]) {+ final c = sharedModels(gridModel: gridModel)+ .controller(account: 'peer');+ await c.refresh();+ await c.select('swarm-buddy-peer');+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ if (gridModel == null) {+ await tester.tap(find.byKey(const ValueKey('super-buddy-model')));+ await tester.pumpAndSettle();+ }+ await captureWindow(+ tester,+ shots,+ 'buddy-model-$name-${brightness.name}',+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+testWidgets('Buddies in ${brightness.name}', (tester) async {if (shots == null) return;final previous = grid.AppTheme.brightness.value;diff --git a/desktop/test/super_tab_buddy_model_test.dart b/desktop/test/super_tab_buddy_model_test.dartnew file mode 100644index 000000000..4d0dd4c80--- /dev/null+++ b/desktop/test/super_tab_buddy_model_test.dart@@ -0,0 +1,488 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_icons.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/widgets/app_menu.dart';+import 'package:harness/state/workspace_chrome.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/local_models.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/buddy_fixture.dart';+import 'support/super_tab_fixture.dart';++/// A person switches their Buddy between their own subscription and a model+/// shared in the Swarm (task #2354, docs/plans/2026-11-03-buddy-model-switch-design.md):+/// the bar's picker offers what the server accepts and names who serves each+/// model; whoever serves one sees which Buddies run on it.+void main() {+ const swarmGrid = 'swarm-0123456789ab';++ List<Map<String, dynamic>> commands(ConversationServer server, String type) =>+ [+ for (final post in server.posts)+ if ((post['command'] as Map)['type'] == type)+ Map<String, dynamic>.from(post['command'] as Map),+ ];++ int now() => DateTime.now().millisecondsSinceEpoch;++ Map<String, dynamic> machine(+ String id,+ String name,+ String contributor,+ List<Map<String, dynamic>> served, {+ int? at,+ bool buddyOnly = false,+ }) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': contributor,+ 'scope': 'swarm',+ 'engines': <dynamic>[],+ 'maxAgents': 4,+ 'availableSlots': 4,+ 'buddyOnly': ?(buddyOnly ? true : null),+ 'observation': {'receivedAt': at ?? now(), 'localModels': served},+ };++ /// Ken's (`peer`) one Buddy runs on his Mac; the Swarm's grid is on, and+ /// its members' machines serve models on it, and on others.+ ConversationServer swarm({+ String? gridModel,+ Map<String, dynamic>? modelRequest,+ bool localModels = true,+ bool buddyOnly = false,+ }) {+ final server = oneBuddySwarm();+ server.state['people'] = [+ ...server.state['people'] as List,+ {'id': 'tony', 'email': '[email protected]', 'role': 'collaborator'},+ {'id': 'diego', 'email': '[email protected]', 'role': 'collaborator'},+ ];+ giveSwarmBuddy(server);+ final buddy = (server.state['agents'] as List).cast<Map>().firstWhere(+ (a) => a['id'] == 'wren',+ );+ if (gridModel != null) buddy['gridModel'] = gridModel;+ if (modelRequest != null) buddy['modelRequest'] = modelRequest;+ if (localModels) {+ server.state['localModels'] = {+ 'grid': swarmGrid,+ 'enabled': true,+ 'ready': true,+ };+ }+ final kenMac = (server.state['machines'] as List).first as Map;+ if (buddyOnly) kenMac['buddyOnly'] = true;+ server.state['machines'] = [+ kenMac,+ machine('studio', 'Studio.local', 'owner', [+ {+ 'grid': swarmGrid,+ 'model': 'deepseek-4.1-flash',+ 'name': 'DeepSeek 4.1 Flash',+ 'kind': 'local',+ },+ {'grid': swarmGrid, 'model': 'kimi-k3', 'name': 'Kimi K3'},+ // Still starting: the grid does not list it yet.+ {+ 'grid': swarmGrid,+ 'model': 'qwen-3.6',+ 'name': 'Qwen 3.6',+ 'starting': true,+ },+ // Shared with the owner from another grid: their machine alone.+ {'grid': 'team', 'model': 'muse', 'name': 'Muse', 'kind': 'shared'},+ // Another Swarm's grid.+ {+ 'grid': 'swarm-ffffffffffff',+ 'model': 'other',+ 'name': 'Other Grid',+ 'kind': 'local',+ },+ ]),+ machine('tony-mini', 'Tonys-Mac-mini.local', 'tony', [+ {+ 'grid': swarmGrid,+ 'model': 'kimi-k3',+ 'name': 'Kimi K3',+ 'kind': 'local',+ },+ ]),+ machine('diego-mac', 'Diego-MacBook.local', 'diego', [+ {+ 'grid': swarmGrid,+ 'model': 'openai/gpt-6.1-sol',+ 'name': 'GPT-6.1 Sol',+ 'kind': 'api',+ },+ ]),+ // Its reading is ten minutes old: it says nothing now.+ machine('old-box', 'Old-Box.local', 'owner', [+ {+ 'grid': swarmGrid,+ 'model': 'stale-model',+ 'name': 'Stale Model',+ 'kind': 'local',+ },+ ], at: now() - 10 * 60 * 1000),+ // A Buddy-only machine never joins the Swarm's grid.+ machine('outside', 'Outside.local', 'owner', [+ {+ 'grid': swarmGrid,+ 'model': 'outside-model',+ 'name': 'Outside Model',+ 'kind': 'local',+ },+ ], buddyOnly: true),+ ];+ return server;+ }++ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server, {+ bool phone = false,+ }) async {+ final size = phone ? const Size(390, 844) : const Size(1280, 800);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = size;+ addTearDown(tester.view.reset);+ final c = server.controller(account: 'peer');+ await c.refresh();+ await c.select('swarm-buddy-peer');+ final view = Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Kens-MacBook',+ ),+ );+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ // A phone's browser lays the workspace out compact (web chrome).+ home: phone+ ? WorkspaceChromeScope(+ chrome: WorkspaceChrome(compactBelow: 720),+ child: view,+ )+ : view,+ ),+ );+ await tester.pumpAndSettle();+ return c;+ }++ Future<void> close(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }++ final picker = find.byKey(const ValueKey('super-buddy-model'));+ Finder inPicker(Finder f) => find.descendant(of: picker, matching: f);+ Finder row(String label) => find.widgetWithText(AppMenuItem, label);+ const rest =+ 'Claude on Kens-MacBook · reads all your projects · only you can read this chat';+ const footer =+ 'What your Buddy reads and writes goes to the machine or API that serves the model you pick.';++ Future<void> open(WidgetTester tester) async {+ await tester.tap(picker);+ await tester.pumpAndSettle();+ }++ group('the bar', () {+ testWidgets(+ 'on the subscription, the picker comes first and the rest stays',+ (tester) async {+ final c = await show(tester, swarm());+ expect(inPicker(find.text('Your subscription')), findsOneWidget);+ expect(inPicker(find.byIcon(AppIcons.chevronDown)), findsOneWidget);+ expect(find.textContaining(' · $rest'), findsOneWidget);+ await close(tester, c);+ },+ );++ testWidgets('on a shared model, it names the model and who serves it', (+ tester,+ ) async {+ final c = await show(tester, swarm(gridModel: 'kimi-k3'));+ expect(inPicker(find.text('Kimi K3')), findsOneWidget);+ expect(+ find.textContaining(' · served by Studio, Tonys-Mac-mini · $rest'),+ findsOneWidget,+ );+ await close(tester, c);+ });++ testWidgets("on an API, it names the member's saved API", (tester) async {+ final c = await show(tester, swarm(gridModel: 'openai/gpt-6.1-sol'));+ expect(inPicker(find.text('GPT-6.1 Sol')), findsOneWidget);+ expect(+ find.textContaining(" · diego's saved API · $rest"),+ findsOneWidget,+ );+ await close(tester, c);+ });++ testWidgets('on a model nobody serves now, it says so', (tester) async {+ final c = await show(tester, swarm(gridModel: 'stale-model'));+ expect(inPicker(find.text('Stale Model')), findsOneWidget);+ expect(find.textContaining(' · not served now · $rest'), findsOneWidget);+ await close(tester, c);+ });++ testWidgets(+ 'while a switch is under way, it says where to and opens nothing',+ (tester) async {+ final c = await show(+ tester,+ swarm(+ modelRequest: {+ 'id': 'r1',+ 'gridModel': 'deepseek-4.1-flash',+ 'name': 'DeepSeek 4.1 Flash',+ 'servedBy': ['Studio'],+ 'requestedBy': 'peer',+ 'at': DateTime.now().toUtc().toIso8601String(),+ },+ ),+ );+ expect(+ inPicker(find.text('Switching to DeepSeek 4.1 Flash…')),+ findsOneWidget,+ );+ expect(inPicker(find.byIcon(AppIcons.chevronDown)), findsNothing);+ await open(tester);+ expect(find.text('SHARED IN THIS SWARM'), findsNothing);+ expect(find.byType(AppMenuItem), findsNothing);+ await close(tester, c);+ },+ );++ testWidgets('switching home reads as the subscription', (tester) async {+ final c = await show(+ tester,+ swarm(+ gridModel: 'kimi-k3',+ modelRequest: {+ 'id': 'r2',+ 'gridModel': null,+ 'requestedBy': 'peer',+ 'at': DateTime.now().toUtc().toIso8601String(),+ },+ ),+ );+ expect(+ inPicker(find.text('Switching to your subscription…')),+ findsOneWidget,+ );+ await close(tester, c);+ });+ });++ group('the menu', () {+ testWidgets(+ 'lists the subscription, then exactly the models the server accepts, each with who serves it',+ (tester) async {+ final c = await show(tester, swarm());+ await open(tester);+ expect(+ find.descendant(+ of: row('Your subscription'),+ matching: find.byIcon(AppIcons.check),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: row('Your subscription'),+ matching: find.text('Claude Code'),+ ),+ findsOneWidget,+ );+ expect(find.text('SHARED IN THIS SWARM'), findsOneWidget);+ expect(+ find.descendant(+ of: row('DeepSeek 4.1 Flash'),+ matching: find.text('served by Studio'),+ ),+ findsOneWidget,+ );+ // Served by two machines: the grid picks one per request.+ expect(+ find.descendant(+ of: row('Kimi K3'),+ matching: find.text('served by Studio, Tonys-Mac-mini'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: row('GPT-6.1 Sol'),+ matching: find.text("diego's saved API"),+ ),+ findsOneWidget,+ );+ // The subscription and three models, nothing else.+ expect(find.byType(AppMenuItem), findsNWidgets(4));+ for (final absent in [+ 'Muse',+ 'Other Grid',+ 'Qwen 3.6',+ 'Stale Model',+ 'Outside Model',+ ]) {+ expect(find.text(absent), findsNothing, reason: absent);+ }+ expect(find.text(footer), findsOneWidget);+ await close(tester, c);+ },+ );++ testWidgets(+ 'picking a model sends it; picking the subscription it is on sends nothing',+ (tester) async {+ final server = swarm();+ final c = await show(tester, server);+ await open(tester);+ await tester.tap(row('Kimi K3'));+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.model'), [+ {'type': 'buddy.model', 'gridModel': 'kimi-k3'},+ ]);+ await open(tester);+ await tester.tap(row('Your subscription'));+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.model'), hasLength(1));+ await close(tester, c);+ },+ );++ testWidgets(+ 'on a shared model, it is checked; the subscription sends null; the model again sends nothing',+ (tester) async {+ final server = swarm(gridModel: 'kimi-k3');+ final c = await show(tester, server);+ await open(tester);+ expect(+ find.descendant(+ of: row('Kimi K3'),+ matching: find.byIcon(AppIcons.check),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: row('Your subscription'),+ matching: find.byIcon(AppIcons.check),+ ),+ findsNothing,+ );+ await tester.tap(row('Kimi K3'));+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.model'), isEmpty);+ await open(tester);+ await tester.tap(row('Your subscription'));+ await tester.pumpAndSettle();+ expect(commands(server, 'buddy.model'), [+ {'type': 'buddy.model', 'gridModel': null},+ ]);+ await close(tester, c);+ },+ );++ testWidgets("a refused switch shows the server's reason", (tester) async {+ final server = swarm();+ server.refuse = {+ 'code': 'BUDDY_MODEL_UNAVAILABLE',+ 'message': 'Nobody in the Swarm serves that model now.',+ };+ final c = await show(tester, server);+ await open(tester);+ await tester.tap(row('DeepSeek 4.1 Flash'));+ await tester.pumpAndSettle();+ expect(+ find.text('Nobody in the Swarm serves that model now.'),+ findsOneWidget,+ );+ await close(tester, c);+ });++ testWidgets(+ "on a Buddy-only machine, it says to add the machine and lists no models",+ (tester) async {+ final c = await show(tester, swarm(buddyOnly: true));+ await open(tester);+ expect(+ find.text(+ "Add Kens-MacBook to the Swarm's Machines to use shared models.",+ ),+ findsOneWidget,+ );+ expect(find.text('DeepSeek 4.1 Flash'), findsNothing);+ expect(find.byType(AppMenuItem), findsOneWidget);+ await close(tester, c);+ },+ );++ testWidgets('with no model shared, it says nobody shares one yet', (+ tester,+ ) async {+ final c = await show(tester, swarm(localModels: false));+ await open(tester);+ expect(find.text('SHARED IN THIS SWARM'), findsOneWidget);+ expect(+ find.text('Nobody shares a model in this Swarm yet.'),+ findsOneWidget,+ );+ expect(find.byType(AppMenuItem), findsOneWidget);+ await close(tester, c);+ });++ testWidgets("a phone's rows are a finger's height", (tester) async {+ final c = await show(tester, swarm(), phone: true);+ await open(tester);+ final rows = find.byType(AppMenuItem);+ expect(rows, findsNWidgets(4));+ for (var i = 0; i < 4; i++) {+ expect(tester.getSize(rows.at(i)).height, greaterThanOrEqualTo(44));+ }+ await close(tester, c);+ });+ });++ group("the contributor's models", () {+ testWidgets('name the Buddies that run on each model', (tester) async {+ final server = swarm(gridModel: 'kimi-k3');+ final c = server.controller(account: 'owner');+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabMachineLocalModels(+ controller: c,+ machineId: 'studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('Kimi K3'), findsOneWidget);+ expect(find.text("Used by ken.tran's Buddy"), findsOneWidget);+ // One line, under the model the Buddy runs on alone.+ expect(+ tester.getTopLeft(find.text("Used by ken.tran's Buddy")).dy,+ greaterThan(tester.getTopLeft(find.text('Kimi K3')).dy),+ );+ expect(find.textContaining('Used by'), findsOneWidget);+ await close(tester, c);+ });+ });+}diff --git a/desktop/test/super_tab_sidebar_test.dart b/desktop/test/super_tab_sidebar_test.dartindex ecf88feaf..be946bfbc 100644--- a/desktop/test/super_tab_sidebar_test.dart+++ b/desktop/test/super_tab_sidebar_test.dart@@ -748,7 +748,7 @@ void main() {);test(- 'lists only fresh readings, once each, and none while the add-on is off',+ 'lists only fresh readings, once per machine, and none while the add-on is off',() {final now = DateTime.fromMillisecondsSinceEpoch(1000000);SuperTabSnapshot snapshot({bool enabled = true, int at = 990000}) =>@@ -783,6 +783,7 @@ void main() {grid: swarmGrid,model: 'm',name: 'm',+ machineId: 'b',machine: 'A machine',kind: 'local',),@@ -790,6 +791,7 @@ void main() {grid: 'team',model: 'n',name: 'n',+ machineId: 'b',machine: 'A machine',kind: 'shared',),diff --git a/docs/plans/2026-11-03-buddy-model-switch-design.md b/docs/plans/2026-11-03-buddy-model-switch-design.mdnew file mode 100644index 000000000..28ff8cfb1--- /dev/null+++ b/docs/plans/2026-11-03-buddy-model-switch-design.md@@ -0,0 +1,239 @@+# A Buddy switches between its owner's subscription and a shared model++Task #2354, requested by Scholes. Design for approval before code.++## What the person gets++A person whose Claude subscription runs out (or who just wants a cheaper model) picks one of the models shared in the+Swarm for their Buddy, keeps talking in the same Buddy chat, and later picks **Your subscription** to go back to the+conversation they had.++- The picker is in the Buddy chat's header, on Desktop, the web and the phone (one Flutter screen).+- It lists **Your subscription (Claude Code)** first and always, then every model shared in the Swarm, each naming who+ serves it: "served by Ken's Mac Studio" for a local model, "Diego's saved API" for an API (PM ruling on the task).+- Switching keeps the Buddy chat and its threads. The Buddy's Claude Code relaunches in the same terminal and reopens+ the same conversation, as a pane's model switch does today.+- When the conversation is too long for the chosen model, the Buddy starts a fresh session on it, and says so. Switching+ back to the subscription reopens the earlier conversation.+- Phase 2 (a later task): switching automatically when the subscription hits its limit.++### Mockup (Desktop; the phone shows the same menu as a sheet)++Today the bar under the Buddy chat's header reads+`Claude Code on Scholes's MacBook · reads all your projects · only you can read this chat`. Its first part becomes the+picker; the rest stays as it is.++```+┌─────────────────────────────────────────────────────────────────────────┐+│ Buddy [term] [⋮] │+├─────────────────────────────────────────────────────────────────────────┤+│ Your subscription ▾ · Claude Code on Scholes's MacBook · reads all your │+│ projects · only you can read this chat │+│ ┌──────────────────────────────────────────────────────────────┐ │+│ │ ✓ Your subscription Claude Code │ │+│ │ ──────────────────────────────────────────────────────────── │ │+│ │ SHARED IN THIS SWARM │ │+│ │ DeepSeek 4.1 Flash served by Ken's Mac Studio │ │+│ │ Kimi K3 served by Ken's Mac Studio, Tony's │ │+│ │ Mac mini │ │+│ │ GPT-6.1 Sol Diego's saved API │ │+│ │ ──────────────────────────────────────────────────────────── │ │+│ │ What your Buddy reads and writes goes to the machine or API │ │+│ │ that serves the model you pick. │ │+│ └──────────────────────────────────────────────────────────────┘ │+```++A model served by several machines names them all: the Swarm's grid picks one per request.++While it switches the bar reads `Switching to DeepSeek 4.1 Flash…` and the picker is disabled. Afterwards:++```+│ DeepSeek 4.1 Flash ▾ · served by Ken's Mac Studio · Claude Code on │+│ Scholes's MacBook · reads all your projects · only you can read this… │+├─────────────────────────────────────────────────────────────────────────┤+│ Your Buddy now runs on DeepSeek 4.1 Flash, served by Ken's Mac Studio. │+│ -- or, when the conversation was too long -- │+│ Your Buddy started a fresh session on DeepSeek 4.1 Flash: this │+│ conversation is too long for it (128K). Switch back to your │+│ subscription to continue the earlier one. │+│ -- or, on failure -- │+│ Couldn't switch your Buddy: Ken's Mac Studio isn't serving DeepSeek │+│ 4.1 Flash now. It is still on your subscription. │+```++When the model the Buddy is on stops being served (its machines left or went offline), the bar reads+`DeepSeek 4.1 Flash ▾ · not served now`, so the person knows to pick another or go back.++The lines are written by the server into the owner's Buddy chat only; nobody else reads that chat.++## How it works++### Reused: the move onto a shared model++A pane's model picker already moves a running agent between its own login and a grid model:+`agent_retarget` on the machine's daemon (`cli/src/backendSocket.ts`) resolves the model on this machine's own grid+sign-in (`models().moveTarget({ gridName, model })`), and `core/agents/retarget.ts` respawns the same pane with the+grid's environment and `--resume <session>`. The pane, its agent id and its Swarm identity stay; the conversation comes+back. It keeps the model the agent had on its own login (`subscriptionModel`) for the way home, and keeps a Buddy's+role through the Swarm role lookup (#2255), so the relaunch is a Buddy launch with its guard.++The Buddy switch drives exactly that call on the Buddy's own machine. It adds two things the pane picker does not have:+the server's list of what may be offered, and a fresh session when the conversation does not fit.++### Flow++```+Desktop/web/phone Backend Buddy's machine (host + daemon)+ pick a model ──────────► buddy.model ─┐+ checks: own Buddy, running, │+ model in servedLocalModels, │+ host has the capability │+ records agent.modelRequest ───────┼──► host row carries the request+ │ host: measure the conversation,+ │ agent_retarget { gridModel, gridName,+ │ fresh? } (or clearGrid) per session+ buddy.modelResult ◄───────────────┘ reports ok / fresh / error+ sets agent.gridModel,+ writes the system line+ bar reads gridModel ◄────── change feed+```++This is the same shape as the PM switch (`lead.switch` → `switchRequest` → host → `agent.switchResult`): the person+asks the server, the server decides what is allowed, the host that owns the process carries it out, and the server+records the outcome. The server, not the app, is where the allow list is enforced.++### What may be offered (one server predicate)++The server already has the predicate a routed start on a Swarm model is checked with: `servedLocalModels(state, now)`+in `backend/src/superTabs/machines.ts`, every model on **this Swarm's grid** in a fresh reading of a machine in the+Swarm's Machines list (`kind` `local`, a model a member's machine serves, or `api`, an API a member shares), not one still+starting. `buddy.model` refuses any grid model it does not list, so the Buddy is offered exactly what a Builder may be+started on. Not offered: models of other grids a member is signed into (`kind: shared`, usable only on that member's+machine), models of other Swarms, a machine outside the Swarm. The person's own subscription is always offered.++The Buddy's own machine must be on the Swarm's grid to reach those models; a Buddy-only machine never joins it+(`hostRows.ts`). Then the server refuses with "Add <machine> to the Swarm's Machines to use shared models", and the+picker shows the same line instead of the list.++The picker builds its list from the machine readings the person's own Swarm read already carries (Desktop's+`superTabLocalModelRows`, grouped by model so every serving machine is named, with each machine's person). No new read;+the Buddy agent's own reads still show no machines.++### The switch on the Buddy's machine++New Swarm-side module `cli/src/superTabs/buddyModel.ts` (no Swarm code in `cli/src/core`):++1. Takes a `modelRequest` from the Buddy's host row once (a local record keeps the request id, so a restart never+ repeats it).+2. For each live session of the Buddy on this machine (the main one, then any thread session): if the target is a grid+ model with a known context window, reads the session's current context size: the last assistant turn's+ `input + cache_read + cache_creation + output` tokens from the end of its Claude Code transcript (a bounded tail read,+ `cli/src/lib/conversationSize.ts`). It fits when that is under 80% of the window; unknown size or unknown window counts+ as fitting (the move resumes, as a pane switch does today).+3. Calls its own daemon's `agent_retarget` with `gridModel` + `gridName` (or `clearGrid`), and `fresh: true` when the+ conversation does not fit.+4. Reports `buddy.modelResult { agentId, requestId, ok, fresh, error }`.++Two generic additions to `agent_retarget` (not Swarm code; any pane could use them):++- `fresh: true`: the respawn starts a new session instead of `--resume`, and the registry row keeps the session it left+ as `subscriptionSessionId` (only when leaving the own login, like `subscriptionModel`).+- On the way home (`clearGrid`), a row with `subscriptionSessionId` resumes that session and clears it once the move+ succeeded. A grid-to-grid move keeps it.++### The Buddy's guard on a grid++A grid launch of Claude Code adds the grid's web tools (`--mcp-config` with the grid's web MCP and an allow-tools+argument, `lib/gridLaunch.ts`). A Buddy starts no MCP server (docs/swarms.md, Buddies). So a Buddy's grid launch drops+the web MCP and its allow argument, and keeps every Buddy flag (dontAsk, the guard hook, its own settings only, no+memory files, editing off). A test pins this; it is the main security risk of the change.++### What the server records++`Agent.gridModel` already means "the model on the Swarm's grid this agent runs" (costs and the leaderboard read it).+`buddy.modelResult` sets it when the Buddy lands on a shared model and deletes it when it is back on the subscription.+The request in flight is `Agent.modelRequest { id, gridModel | null, contextWindow?, requestedBy, at }` (the window from the serving reading, for the host's fit check).++### New Buddy thread sessions++A thread session started while the Buddy is on a shared model starts on that model (`gridModel`/`gridName` on its start+request, as a routed Builder's start does today).++### The contributor: seen and safe (PRODUCT.md, Contribution; PM, 2026-11-03)++Whoever serves the model a Buddy runs on is told, and their limits hold:++- **Seen.** When a Buddy lands on a model, each member who serves it (a machine's owner for a local model, the member+ who shares an API) gets one line in their own Buddy chat: `Scholes's Buddy now runs on DeepSeek 4.1 Flash, served+ by your Mac Studio.` (or `…on your saved API`). Not for a person serving their own Buddy. Their Swarm models list+ shows `Used by Scholes's Buddy` under the model while one is on it (from the Buddy agents' `gridModel`, which every+ member's roster read already carries).+- **Safe.** The Buddy goes back to its owner's subscription by itself when:+ - its machine reports the model hit a limit or keeps failing (the host's existing `agent.alert` `limit` or `model`+ on the Buddy while it is on a grid model): `DeepSeek 4.1 Flash hit a limit, so your Buddy is back on your+ subscription.`;+ - nobody in the Swarm has served the model for 2 minutes (the machine left or went quiet, the model stopped, the API+ was unshared): `Nobody serves DeepSeek 4.1 Flash now, so your Buddy is back on your subscription.`+ The server writes the same `modelRequest` home that the person's own pick does (marked with its reason), so the+ Buddy's machine carries it out the same way; a Buddy mid-turn is moved once its turn ends (the host retries within the+ lease). The grid itself still enforces each serving machine's own limits per request.++## Design (docs/feature-design-rules.md)++Reviewed revision: ______ Reviewer: ______++1. **Growth.** Two fields on the Buddy's agent record: `modelRequest` (one at a time; deleted by `buddy.modelResult`, or+ by the liveness sweep after 10 minutes with a "didn't answer" line) and `gridModel` (the current shared model; deleted+ when the Buddy goes back to the subscription, and with the agent when the Buddy is removed, its owner leaves or a+ down Buddy is replaced). On the machine: `subscriptionSessionId` on the daemon's registry row (deleted on the way+ home and with the row), and the host's done-requests file (one id per Buddy, the newest kept). One system line per+ switch in the owner's Buddy chat, under that chat's existing retention.+ | Record | create | update | finish | lost / cancel | delete |+ | --- | --- | --- | --- | --- | --- |+ | modelRequest | buddy.model, or the server on a limit or a model gone 2 min | — | buddy.modelResult | liveness sweep at 10 min | with the agent |+ | gridModel | modelResult ok on a grid | next ok result | modelResult ok home | stays; the bar shows "not served now" | with the agent |+ | subscriptionSessionId | fresh move out | — | move home ok | stays with the row | with the row |+2. **Concurrency.** Each command writes the Swarm state under its existing per-Swarm write; `buddy.model` refuses while a+ `modelRequest` is pending (`BUDDY_SWITCHING`), so one switch runs per Buddy. `buddy.modelResult` must name the+ pending request id. On the machine, retarget already refuses a session mid-turn (`AGENT_BUSY`) and holds the pane's+ terminal control and the reconciler route while it respawns.+3. **Read cost.** The offer list is derived from machine rows the person's read already loads (no new query). It is at+ most the Swarm's machines × 16 models each (the reading's cap), a few KB at 50 machines. `gridModel` and the request add under+ 300 bytes to the Buddy's row. The host's transcript tail read is bounded (last 256 KB). Change-feed: the Buddy's+ agent row already changes when its configuration changes.+4. **Scale.** At 10x (500 machines, 500 Buddies) the offer list stays capped per machine and is sent only to its person+ when the Buddy chat's header is read; switches are person-driven (a handful a day). First warning: the size of the+ person's read of the Buddy chat (existing read-size measure).+5. **Compatibility.** An older app never sends `buddy.model` and shows nothing new (it never reads `modelRequest`; `gridModel` already exists on agents). An older host does not+ report the `buddy-model` capability, so the server refuses the switch with "Update Harness on <machine> to switch+ your Buddy's model" (`HOST_OUTDATED`) and never writes a request an old host would ignore. The host and the daemon+ ship in one CLI, so a host reporting `buddyModel` has a daemon that understands `fresh`. Readers of the agent row (roster, Buddy news, closed agents, leaderboard) get+ two optional fields; `closedAgents.ts` strips them as it strips `switchRequest`.+6. **Migration and rollback.** No migration: new optional fields. Deploy order: backend, then CLI, then apps. Rolling+ the backend back leaves `modelRequest` unread and `gridModel` as a plain record on the record (harmless; the Buddy keeps running on+ whatever its pane has, and the pane picker can move it back). Rolling the CLI back: a Buddy left on a grid stays on+ it (its relaunch keeps the grid launch record, as for any pane) until moved home from the pane picker.+7. **Audience.** `buddy.model` is the Buddy's owner's alone (a person, `buddyOf.personId === actor.userId`); the+ Buddy agent cannot send it (not in `BUDDY_COMMANDS`), nor anyone else. `buddy.modelResult` is accepted only from the+ Buddy's own host (actor is that agent) for the pending request id; it is added to `BUDDY_COMMANDS` with that check.+ The offer list goes only to the person's own read; the system lines go only to their Buddy chat. The model a Buddy+ runs on already shows on its roster row (`configuration.model`) like every agent's; nothing new about the Buddy's+ chat leaves it. Known, accepted by the PM's ruling: on a shared model, what the Buddy sends (which can include anything+ its owner reads) reaches the serving machine or API, so the picker names who serves each model before the switch.+8. **Identity.** The Buddy still runs on its owner's own machine, in their own account, as the real Claude Code CLI.+ The grid is reached with that machine's own Swarm-grid sign-in; an API's key stays on its sharer's machine behind the+ grid. Nothing runs as another person.+9. **Failure.** Every refusal (`AGENT_BUSY` mid-turn, model not served, grid unavailable, daemon outdated, respawn+ failed) comes back in `buddy.modelResult` and is written as "Couldn't switch your Buddy: <reason>. It is still on+ <model>." A host that never answers: the tidy expires the request at 10 minutes with "Your Buddy's computer didn't+ answer." A model that stops being served after the switch: the header says "not served now"; the Buddy's own error+ shows in its terminal; Phase 2 adds the automatic fallback.+10. **Platforms.** The picker: Desktop (macOS, Linux, Windows), web and phone, one Flutter screen. The switch runs where+ Buddies run: macOS and Linux (no Buddy on Windows). Tested: Desktop on a Mac, CLI on a Mac and Linux CI.++## Out of scope++- Automatic fallback at the subscription limit (Phase 2).+- Models of grids other than the Swarm's (`kind: shared`), and a Codex Buddy (still refused).+- Choosing an effort or a Claude model (Opus/Sonnet) for the subscription side: "Your subscription" returns to the+ model the Buddy had there.diff --git a/docs/plans/2026-11-03-buddy-model-switch-plan.md b/docs/plans/2026-11-03-buddy-model-switch-plan.mdnew file mode 100644index 000000000..2a64c32dc--- /dev/null+++ b/docs/plans/2026-11-03-buddy-model-switch-plan.md@@ -0,0 +1,283 @@+# Buddy model switch Implementation Plan++> **For agentic workers:** This plan is carried out by the task's Engineer by the project's instructions (Engineer role):+> task by task, each failing test committed before its code, one pull request, one independent review step at the end.+> Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** A person switches their Buddy between their own Claude subscription and a model shared in the Swarm, and+back, keeping the Buddy chat and its conversation (or a fresh session when the conversation is too long).++**Architecture:** The person asks the server (`buddy.model`); the server checks the model against the Swarm's served+models and records a request on the Buddy's agent; the Buddy's host carries it out through its own daemon's existing+`agent_retarget` (respawn in place with `--resume`), measuring the conversation first and starting fresh when it does+not fit; the host reports `buddy.modelResult`, which sets `Agent.gridModel` and writes the line in the Buddy chat.++**Tech Stack:** TypeScript backend (vitest), TypeScript CLI/daemon (node:test specs), Flutter Desktop (flutter_test).++**Spec:** [docs/plans/2026-11-03-buddy-model-switch-design.md](2026-11-03-buddy-model-switch-design.md)++## Global Constraints++- PR body first line: "Requested by [email protected] through Harness."+- The Buddy guard and Buddy privacy rules stay as they are (docs/swarms.md, Buddies); two security reviews.+- Swarm code stays out of `cli/src/core`; the core change is generic (`fresh` and the remembered session on any pane).+- Never run a test that signs the Mac out of the real CLI; Desktop tests use a memory store and a fake sign-in.+- Before Ready: a failing-then-passing test for every risk below, red/green evidence in a PR comment, the full Super Tab+ integration suite (`npm run test:integration` per docs/validation-and-release.md) for the backend change.+- Copy, exact: `Your subscription`, `SHARED IN THIS SWARM`, `served by <machine>[, <machine>…]`, `<person>'s saved API`,+ `Switching to <model>…`, `not served now`,+ `Your Buddy now runs on <model>, served by <servers>.`,+ `Your Buddy started a fresh session on <model>: this conversation is too long for it (<window>K). Switch back to your subscription to continue the earlier one.`,+ `Your Buddy is back on your subscription.`,+ `Couldn't switch your Buddy: <reason>. It is still on <current>.`,+ `Couldn't switch your Buddy: its computer didn't answer. It is still on <current>.`,+ `<person>'s Buddy now runs on <model>, served by your <machine>.` / `…on your saved API.`,+ `<model> hit a limit, so your Buddy is back on your subscription.`,+ `Nobody serves <model> now, so your Buddy is back on your subscription.`+- Fresh-session threshold: context tokens ≥ 80% of the target's context window. Unknown size or window: resume.+- Request lease: 10 minutes (`BUDDY_MODEL_LEASE_MS = 10 * 60_000`).+- Host capability name: `buddyModel`.+- Platforms: picker on Desktop (macOS/Linux/Windows), web, phone; switch on macOS and Linux hosts.++## Review Focus++1. A Buddy relaunched onto a grid model keeps every Buddy launch flag and gets no MCP server (the grid's web MCP) — the+ guard must hold on the grid. Test in Task 2.+2. The way home after a fresh move resumes the earlier session, not the grid one, and the registry rebinds the agent to+ it rather than minting a new agent. Test in Task 3.+3. A switch asked while the Buddy is mid-turn is refused with the reason, and the Buddy keeps running on its model.+ Test in Task 5.+4. A model that is served when picked but gone when the host carries it out is refused, not half-applied. Test in Task 5.+5. Someone other than the Buddy's owner (another member, the Swarm owner, the Buddy itself) cannot switch it, and a+ result for a stale request id is refused. Test in Task 1.++---++### Task 1: Backend — `buddy.model`, the request, the result and its lines++**Files:**+- Modify: `backend/src/superTabs/model.ts` (Agent: `modelRequest?`)+- Modify: `backend/src/superTabs/commands.ts` (schemas, handlers, `BUDDY_MODEL_CAPABILITY`)+- Modify: `backend/src/superTabs/buddies.ts` (`BUDDY_COMMANDS` gets `buddy.modelResult`; line texts)+- Modify: `backend/src/superTabs/tidy.ts` (expire a request past its lease)+- Modify: `backend/src/superTabs/closedAgents.ts` (strip `modelRequest`)+- Test: `backend/src/superTabs/buddyModel.test.ts`++**Interfaces:**+- Produces: command `{ type: 'buddy.model', gridModel: string | null }` (null = the subscription); the grid is always the+ Swarm's (`state.localModels.grid`).+- Produces: `Agent.modelRequest?: { id: string; gridModel: string | null; requestedBy: string; at: string }`.+- Produces: command `{ type: 'buddy.modelResult', agentId: string, requestId: string, ok: boolean, fresh?: boolean,+ contextWindow?: number, error?: string }` (error ≤ 300 chars, control characters removed).+- Produces: `Agent.gridModel` set on an ok result to a grid model, deleted on an ok result home.++- [ ] **Step 1: Write the failing tests** in `buddyModel.test.ts` (state built as `buddies.test.ts` builds a running+ Swarm Buddy on its owner's machine, the machine reporting `capabilities: [..., 'buddyModel']` and serving+ `deepseek-4.1-flash` on the Swarm grid from another member's machine):+ - `buddy.model` by the owner records `modelRequest { gridModel: 'deepseek-4.1-flash', requestedBy: owner }`.+ - refused `BUDDY_MODEL_UNAVAILABLE` for a model no fresh reading serves on the Swarm grid, for a `kind: shared` model of+ another grid, and when `localModels` is off.+ - refused `BUDDY_OWNER` for another member and for the Swarm's owner; refused `BUDDY_FORBIDDEN` when sent by the Buddy+ agent itself.+ - refused `BUDDY_SWITCHING` while a request is pending; `HOST_OUTDATED` when the machine lacks `buddyModel`;+ `BUDDY_MODEL_MACHINE` when the Buddy runs on a Buddy-only machine; `MACHINE_OFFLINE` when its reading is stale;+ `NO_BUDDY` with no running Buddy.+ - `buddy.modelResult` from the Buddy agent with the pending id and `ok` sets `gridModel`, clears `modelRequest`, and+ writes `Your Buddy now runs on DeepSeek 4.1 Flash, served by Ken's Mac Studio.` in the owner's Buddy chat only;+ with `fresh: true, contextWindow: 131072` writes the fresh-session line with `(128K)`; home with ok deletes+ `gridModel` and writes `Your Buddy is back on your subscription.`; `ok: false` writes the Couldn't-switch line and+ leaves `gridModel` as it was.+ - `buddy.modelResult` with another id → `STALE_SWITCH`; from another agent → `BUDDY_FORBIDDEN`/403.+ - tidy at `at + 10 min` clears the request and writes `Couldn't switch your Buddy: Your Buddy's computer didn't answer. It is still on your subscription.`+- [ ] **Step 2: Run to see them fail**+ Run: `cd backend && npm test -- src/superTabs/buddyModel.test.ts`+ Expected: FAIL (unknown command type `buddy.model`).+- [ ] **Step 3: Implement** the schemas next to `buddy.rename`; the handler checks, in order: person actor, the main+ Swarm Buddy of the actor (`mainBuddyOf`), its machine listed and not `buddyOnly`, fresh, capability, no pending+ request, and for a non-null model `servedLocalModels(state, now).some(l => l.model === gridModel)`. The result handler+ mirrors `agent.switchResult`. Server names: the machines serving the model now (`servedLocalModels`), each by its+ name; an `api` reading by `<person>'s saved API`.+- [ ] **Step 4: Run to see them pass** — same command, Expected: PASS.+- [ ] **Step 5: Commit** — `git commit -m "Swarm: a person asks to switch their Buddy's model; the server checks it and records the outcome (#2354)"`++### Task 1b: Backend — the contributor is told, and a Buddy comes home on a limit or a model gone++**Files:**+- Modify: `backend/src/superTabs/buddyModel.ts` (`modelRequest.reason`, contributor lines, `buddyModelHome`)+- Modify: `backend/src/superTabs/commands.ts` (`agent.alert` on a Buddy on a grid model), `backend/src/superTabs/tidy.ts`+ (the sweep moves a Buddy whose model nobody served for 2 minutes)+- Test: `backend/src/superTabs/buddyModel.test.ts`++**Interfaces:**+- Produces: `Agent.modelRequest.reason?: 'limit' | 'gone'`; `Agent.gridModelUnservedSince?: number` (ms; set by the sweep+ when the model first goes unserved, cleared when it is served again or the Buddy leaves it).+- Produces: `BUDDY_MODEL_GONE_MS = 2 * 60_000`.++- [ ] **Step 1: Failing tests**:+ - an ok result onto `deepseek-4.1-flash` (served by owner's Mac Studio) also writes, in owner's Buddy chat,+ `peer's Buddy now runs on DeepSeek 4.1 Flash, served by your Mac Studio.`; onto owner's API, `…on your saved API.`;+ nothing for a model peer's own machine serves.+ - `agent.alert { alert: 'limit', active: true }` from a Buddy on a grid model records `modelRequest { gridModel: null,+ reason: 'limit' }`; its ok result writes `DeepSeek 4.1 Flash hit a limit, so your Buddy is back on your subscription.`;+ the same alert from a Buddy on its subscription records nothing; a request already pending is left as it is.+ - the sweep with the model unserved for under 2 minutes changes nothing; at 2 minutes records `reason: 'gone'`, whose+ result line is `Nobody serves DeepSeek 4.1 Flash now, so your Buddy is back on your subscription.`; served again+ before then clears the mark.+- [ ] **Step 2: Run** `cd backend && npm test -- src/superTabs/buddyModel.test.ts` — FAIL.+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run** — PASS.+- [ ] **Step 5: Commit** — `Swarm: the member serving a Buddy's model is told, and the Buddy comes home on a limit or when nobody serves it (#2354)`++### Task 2: CLI — a Buddy's grid launch carries no MCP server++**Files:**+- Modify: `cli/src/lib/launchOverrides.ts` (where the grid launch is built for a source)+- Test: `cli/src/lib/launchOverrides.spec.ts`++**Interfaces:**+- Consumes: `LaunchSource.swarmSkill.role === 'buddy'`, `GridLaunchOverride.mcpUrl`.++- [ ] **Step 1: Failing test** `a Buddy moved onto a grid gets no web MCP and keeps its Buddy launch`: build overrides+ for a Buddy source with a grid override carrying `mcpUrl`; assert `extraArgs` has no `--mcp-config` and no allow-web+ argument, `env` has no grid web key variable, and the Buddy's own args (permission mode, settings) are present as in+ the same source without a grid. A non-Buddy source with the same grid still gets `--mcp-config`.+- [ ] **Step 2: Run** `cd cli && node --test --import tsx src/lib/launchOverrides.spec.ts` — Expected: FAIL.+- [ ] **Step 3: Implement**: for a Buddy source the grid override is used without `mcpUrl`.+- [ ] **Step 4: Run** — Expected: PASS.+- [ ] **Step 5: Commit** — `fix(cli): a Buddy on a grid model starts no MCP server, as on its own login (#2354)`++### Task 3: Daemon — `agent_retarget` can start fresh, and the way home reopens the session it left++**Files:**+- Modify: `cli/src/backendSocket.ts` (`agent_retarget`: `fresh: true` accepted with a grid target only)+- Modify: `cli/src/core/agents/retarget.ts` (`retargetAgent({ agentId, grid, fresh })`)+- Modify: `cli/src/lib/registry.ts` (`subscriptionSessionId`, `setSubscriptionSession(agentId, id | null)`)+- Test: `cli/src/core/agents/retarget.spec.ts`, `cli/src/backendSocket.spec.ts`++**Interfaces:**+- Produces: frame `agent_retarget { agentId, gridModel, gridName, fresh?: true }`; `fresh` with `clearGrid` →+ `INVALID_GRID`.+- Produces: `RegisteredSession.subscriptionSessionId?: string`.++- [ ] **Step 1: Failing tests** (retarget.spec.ts, with its existing fake pane/restart deps):+ - `a fresh move onto a grid relaunches without --resume and keeps the session it left`: `restartAgent` receives an+ empty session id; after success `registry.setSubscriptionSession(agentId, 'S1')`.+ - `the move home reopens the session a fresh move left`: a row on a grid with `subscriptionSessionId: 'S1'` and+ `sessionId: 'S2'`; clearGrid relaunches with `--resume S1`; after success the remembered session is cleared.+ - `a grid-to-grid move keeps the remembered session`; `a refused move leaves it unchanged`.+ - backendSocket.spec: `fresh` with `clearGrid` → `INVALID_GRID`; `fresh` is passed through to `onRetargetAgent`.+- [ ] **Step 2: Run** `cd cli && node --test --import tsx src/core/agents/retarget.spec.ts src/backendSocket.spec.ts` — FAIL.+- [ ] **Step 3: Implement**: `fresh` only when leaving the own login records the old id (a grid-to-grid fresh move keeps+ the earlier remembered one); home with a remembered id passes it as the session to resume.+- [ ] **Step 4: Run** — PASS. Also run `cd cli && npm run test:core`.+- [ ] **Step 5: Commit** — `feat(cli): a model switch can start a fresh session and the way home reopens the earlier one (#2354)`++### Task 4: CLI — how long a Claude Code conversation is now++**Files:**+- Create: `cli/src/lib/conversationSize.ts`+- Test: `cli/src/lib/conversationSize.spec.ts`++**Interfaces:**+- Produces: `conversationTokens(transcriptPath: string): Promise<number | null>` — the newest assistant entry's+ `usage.input_tokens + cache_read_input_tokens + cache_creation_input_tokens + output_tokens`, read from at most the last+ 256 KB; null when none is found or the file is unreadable.++- [ ] **Step 1: Failing tests**: a transcript whose last assistant usage sums to 150 000 → 150000; a later user entry+ after it does not change it; a 1 MB transcript whose newest usage is in the last 256 KB → found; none → null; a+ missing file → null.+- [ ] **Step 2: Run** `cd cli && node --test --import tsx src/lib/conversationSize.spec.ts` — FAIL.+- [ ] **Step 3: Implement** with a bounded read from the end (`open` + `read` at `size - 256 KB`), lines parsed newest first.+- [ ] **Step 4: Run** — PASS.+- [ ] **Step 5: Commit** — `feat(cli): read how long a Claude Code conversation is from its transcript's tail (#2354)`++### Task 5: CLI host — carry out a Buddy's model request++**Files:**+- Create: `cli/src/superTabs/buddyModel.ts`+- Modify: `cli/src/superTabs/host.ts` (serve Buddy rows), `cli/src/superTabs/machines.ts` (`CAPABILITIES.push('buddyModel')`)+- Test: `cli/src/superTabs/buddyModel.spec.ts`++**Interfaces:**+- Consumes: Task 3's frame, Task 4's `conversationTokens`, Task 1's commands.+- Produces: `class BuddyModelRequests { serve(row: BuddyModelRow): Promise<void> }`, with deps `{ open, post, now, log,+ sessions(buddyAgentId): RegisteredSession[] }`; the done-ids record under `<dataDir>/super-tabs/buddy-model/`.++- [ ] **Step 1: Failing tests** (fake daemon answering `agent_retarget`, fake post):+ - a request to `deepseek-4.1-flash` with the target window 131072 and a 40 000-token conversation → one+ `agent_retarget { gridModel, gridName: <swarm grid>, }` without `fresh`, then `buddy.modelResult { ok: true }`.+ - a 120 000-token conversation → `fresh: true`, result `{ ok: true, fresh: true, contextWindow: 131072 }`.+ - unknown window or unreadable transcript → no `fresh`.+ - home → `agent_retarget { clearGrid: true }`.+ - a thread session of the same Buddy is moved too; one that fails is named in the result's error, the main move stands.+ - the daemon answers `AGENT_BUSY` → result `{ ok: false, error: 'Your Buddy is answering. Try again when it has finished' }`.+ - `GRID_UNAVAILABLE` → `{ ok: false, error: "<servers> isn't serving <model> now" }`.+ - the same request id seen again (and after a restart, from the record) → no second retarget.+- [ ] **Step 2: Run** `cd cli && node --test --import tsx src/superTabs/buddyModel.spec.ts` — FAIL.+- [ ] **Step 3: Implement**; the target's context window comes from the request's reading (server adds+ `contextWindow` to `modelRequest` from the serving reading) — add it to Task 1's request if missing.+- [ ] **Step 4: Run** — PASS; then `cd cli && npm run test:orchestrator` (host coverage gate).+- [ ] **Step 5: Commit** — `feat(cli): a Buddy's machine switches its model when its owner asks (#2354)`++### Task 6: Backend — a new thread session starts on the Buddy's model++**Files:**+- Modify: `backend/src/superTabs/commands.ts` (`message.send` with `newSession`)+- Test: `backend/src/superTabs/buddyModel.test.ts`++- [ ] **Step 1: Failing test**: with the main Buddy on `gridModel: 'deepseek-4.1-flash'`, a new thread session's start+ request carries `gridModel` and `gridName` = the Swarm grid and no `model`/`effort`; with the model no longer served+ it starts on the subscription.+- [ ] **Step 2: Run** `cd backend && npm test -- src/superTabs/buddyModel.test.ts` — FAIL.+- [ ] **Step 3: Implement** where the thread session's request copies the main Buddy's engine.+- [ ] **Step 4: Run** — PASS.+- [ ] **Step 5: Commit** — `Swarm: a Buddy's new thread session starts on the model its owner chose (#2354)`++### Task 7: Desktop/web/phone — the picker in the Buddy bar++**Files:**+- Create: `desktop/lib/super_tabs/buddy_model.dart` (offers + picker widget)+- Modify: `desktop/lib/super_tabs/buddies.dart` (`SuperTabBuddyBar`), `desktop/lib/super_tabs/controller.dart`+ (`switchBuddyModel(String? gridModel)`), `desktop/lib/super_tabs/model.dart` (`SuperTabAgent.gridModel`,+ `modelRequest`)+- Test: `desktop/test/super_tab_buddy_model_test.dart`++**Interfaces:**+- Produces: `List<BuddyModelOffer> buddyModelOffers(SuperTabSnapshot snapshot, {required DateTime now})` where+ `BuddyModelOffer = ({String model, String name, List<String> servedBy, bool api})`, from+ `superTabLocalModelRows` rows on the Swarm grid, grouped by model; `servedBy` is machine names for `local`, and+ `<person>'s saved API` for `api`.++- [ ] **Step 1: Failing widget tests** (memory store, fake sign-in, snapshot fixture as `super_tab_buddies_test.dart`):+ - the bar shows `Your subscription ▾ · Claude Code on <machine> · …`; opening it lists `Your subscription` checked,+ `SHARED IN THIS SWARM`, `DeepSeek 4.1 Flash served by Ken's Mac Studio`, a two-machine model naming both, an API+ as `Diego's saved API`, and the footer line.+ - a `kind: shared` model, a stale reading and a starting model are not listed.+ - picking a model sends `buddy.model { gridModel }`; picking `Your subscription` sends `gridModel: null`.+ - with `modelRequest` pending the bar reads `Switching to DeepSeek 4.1 Flash…` and the picker is disabled.+ - on `gridModel` no longer served the bar reads `DeepSeek 4.1 Flash ▾ · not served now`.+ - on a Buddy-only machine the menu shows `Add <machine> to the Swarm's Machines to use shared models` and no models.+ - phone width: the menu opens as a sheet with finger-size rows.+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_buddy_model_test.dart` — FAIL.+- [ ] **Step 3: Implement** in the design language (DesktopChrome metadata/control styles, the shared menu anchor the ⋮+ menu uses; phone sheet as other phone menus).+- [ ] **Step 4: Run** — PASS; then `flutter analyze`, `scripts/check-ui-style` and `test/laid_out_list_test.dart`+ (Desktop guard tests before Ready).+- [ ] **Step 5: Commit** — `Desktop: a model picker in the Buddy bar names who serves each model (#2354)`; screenshots+ committed for the PR and removed in the next commit.++### Task 8: Docs++**Files:**+- Modify: `docs/swarms.md` (Buddies: a paragraph on switching the model, who serves it, fresh sessions, the guard on a grid)++- [ ] **Step 1:** Write the paragraph; **Step 2:** commit `Docs: a Buddy's model switch (#2354)`.++### Before Ready++- [ ] `cd backend && npm test` (unit), `npm run test:integration` — the full Super Tab integration suite.+- [ ] `cd cli && npm run test:core && npm run test:orchestrator` and the changed specs.+- [ ] Desktop changed tests + guard tests on this Mac.+- [ ] Red/green evidence comment on the PR, one line per risk with the failing and passing commit.+- [ ] Review steps: two security reviews (Buddy guard and privacy), and a test step on a Mac (Desktop) with a shared+ grid model: switch mid-conversation, keep chatting, switch back.diff --git a/docs/plans/2026-11-03-pr-events-to-engineer-plan.md b/docs/plans/2026-11-03-pr-events-to-engineer-plan.mdnew file mode 100644index 000000000..59e4a7e3c--- /dev/null+++ b/docs/plans/2026-11-03-pr-events-to-engineer-plan.md@@ -0,0 +1,168 @@+# Pull request events reach the task's Engineer Implementation Plan++> Worked by this project's instructions (Engineer role): plan first in a draft pull request, then each task test first+> (failing test committed before its code), one independent Review step on the pull request. Steps use checkbox+> (`- [ ]`) syntax for tracking.++**Goal:** A GitHub event on an open task's pull request (CI failed, CI passed, a review or comment, a merge conflict) lands+once, within about a minute, as a plain message in that task addressed to its current Engineer.++**Architecture:** There is no GitHub webhook receiver today, and the app's webhook is not configured, so this polls. It+works the way the archive pass does (`superTabs/archive.ts`): a pass in the singleton worker, every 60 s, reads the open+task groups that link pull requests and asks GitHub about each pull request through the Harness GitHub App. The token is+read-only (`pull_requests`, `checks` and `metadata` read, all of them permissions the app already holds:+`TOKEN_PERMISSIONS`). Conditional requests (ETag, `If-None-Match`) keep idle pull requests at 304s, which GitHub does not+count against the rate limit. A pure function turns what GitHub says into events, each with a stable key. A store write+then posts the events the group has not seen, to the task's owner (`steps.ts ownerOf`), and records their keys on the+group, all in one transaction, so a retry or a second worker pass posts nothing twice.++**Tech Stack:** TypeScript, Prisma/MongoDB, vitest (unit, and integration with mongodb-memory-server), the existing+`GitHubApp` and `fakeGitHub`.++**Spec:** Task #1891 brief (Dee, part 1; River, 2026-11-03), in the pull request body.++## Global Constraints++- No new GitHub App permissions without Ken's go: only `pull_requests: read`, `checks: read`, `metadata: read`, all already granted to the app.+- One message per event per head: no repeats on retries.+- Messages in plain words, with the pull request link and the failing job name.+- None when the task has no live Engineer. Merges stay in the PM's 30-minute batch: nothing here merges.+- PR body first line: "Requested by [email protected] through Harness."+- Before Ready: a test that fails without the fix for every risk named, red/green evidence in a PR comment, the full Super Tab integration suite.+- Swarm code stays out of cli/src/core.++## Design++- **Events and keys** (head = the pull request's head SHA, short form in text):+ - `ci-red:<head>`: the first latest-per-name check run on the head that concluded `failure`, `timed_out`, `cancelled`,+ `action_required` or `startup_failure`. This one message covers both "a failed check" and "CI finished red": it goes+ as soon as one job fails, without waiting for the rest, and names every job failed so far.+ - `ci-green:<head>`: every check suite on the head that has check runs is `completed`, and every latest check run+ concluded `success`, `neutral` or `skipped`.+ - `review:<id>`: a submitted pull request review (any state) by someone other than the app's bot. Its inline comments+ belong to it, so they make one message.+ - `comment:<id>`: a conversation comment on the pull request by someone other than the app's bot.+ - `conflict:<head>`: `mergeable === false`. A `null` (GitHub still computing) says nothing this pass.+- **Drafts:** no CI event while the pull request is a draft (this repo's drafts skip checks and fail `ci/required` by+ design). The first pass that sees a head as ready records `ready:<head>:<ms>`. Failed runs that completed before that+ time are the draft's and are ignored, so a stale draft failure never reads as red once the PR is marked ready.+- **First sight:** the first time a group's pull request is read, every current key is recorded as seen and nothing is+ posted, except a conflict. Deploying this, or linking a PR, never replays old reviews or CI. A conflict is still+ something to act on, so it posts.+- **Who hears:** the task group itself (never a step), open (`workFinished: false`, not archived, not deleted), active in+ the last 7 days, linking at least one PR. The message goes to `ownerOf(state, task)`. With no owner, the keys are+ recorded and nothing is posted. Author: the project's Lead agent, else the owner itself (as `stepEndedRows`).+ `source: { kind: 'system' }`, so clients draw it as a system line.+- **Storage:** `Conversation.pullRequestEvents?: Record<url, string[]>`, the newest 50 keys per URL.+- **growth:** at most 50 short keys per linked PR per open task. They go with the group's data when it archives.+- **read cost:** one aggregate per pass on `[workFinished, archived, lastActivityAt]`, projecting a few fields. Per PR:+ pull, check runs, check suites, reviews and comments, conditional. 304s are free.+- **concurrency:** the write loads the group in a transaction and recomputes what is new from the stored keys, so two+ passes, or a retry, post once. One pass runs at a time per worker (as the archive's does).+- **failure:** a PR GitHub cannot read (app not installed, error) is skipped this pass, logged once per pass. One group's+ failed write never stops the pass.+- **compatibility:** no schema change, and no client change (a system line with a link, delivered like any message).+- **rollback:** remove the pass. The stored keys are inert.+- **audience:** the message goes to the task's own Engineer in the task's own chat. Review and comment text is the+ public PR's, quoted up to 300 characters.++## Standards (ENGINEERING.md, MongoDB skills)++- **4, push over polling: broken on purpose.** No GitHub webhook reaches the backend, and the app has no webhook URL or+ secret configured. Adding them is an app change that needs Ken's go. What replaces push: one pass a minute, conditional+ reads, so an unchanged pull request costs a free 304 and posts nothing. It reads only open tasks active this week, and+ at most `WATCH_GROUPS` (200) of them, the most recently active first. To be replaced by the app's `pull_request`,+ `pull_request_review`, `issue_comment` and `check_suite` webhook events once Ken approves; the pass then goes.+- **4, every query served by an index; nothing grows without a bound.** The pass's one read is an aggregate on+ `[workFinished, archived, lastActivityAt]`: equality, equality, then the range, with `$sort` on the range field and+ `$limit` (Equality, Sort, Range; the sort comes from the index). `data.*` and `deleted` filter the fetched documents.+ A plan test pins IXSCAN and the documents examined (`integration/workerIndexPlans.test.ts`). No new index. Keys+ stored: at most 50 per linked pull request, on the group, gone with it.+- **MongoDB schema design:** the keys are embedded in the group's data, as the skill's rule for a bounded array read and+ written with its parent: the store write already loads the group, and an event and its key change in one write.+- **6, failures are seen.** A pull request GitHub cannot read is counted, and each pass that could not read one, or+ posted something, logs one `[swarm-pr-events] pass` line with `groups`, `pulls`, `unreadable` and `posted`. Every+ GitHub call has the app's request timeout. A write runs once per event, however often it is retried.+- **8, measurable:** that same line is the measure.+- **10, platforms:** backend only (the worker). Clients draw the messages as any system line.++## Review Focus++- A draft PR's stale failed `ci/required` must not post "CI failed" in the minute after the PR is marked ready, before the new runs exist. (Task 1 test `ignores a draft's failure on the same head`.)+- A force-push (new head) must post that head's CI and conflict once, even when the old head's were already posted. (Task 1 test `a new head is news again`.)+- A worker restart, or two passes at once, must not post again: dedup lives in the group, not in memory. (Task 3 test `a second pass and a retried write post nothing`.)+- The app's own comments (the Engineer's red/green comment pushed with the app's token) must not wake the Engineer. (Task 1 test `skips the app's bot`.)+- A task whose Engineer left must post nothing, and must not flood a new Engineer later with what happened before them. (Task 3 test `no Engineer: recorded, not posted`.)++---++### Task 1: events from what GitHub says++**Files:**+- Create: `backend/src/superTabs/pullRequestEvents.ts`+- Test: `backend/src/superTabs/pullRequestEvents.test.ts`++**Interfaces:**+- Produces:+ - `interface PullRequestWatch { url: string; number: number; state: 'open' | 'closed'; draft: boolean; head: string; base: string; mergeable: boolean | null; checkRuns: Array<{ name: string; status: string; conclusion: string | null; completedAt: number | null }>; checkSuites: Array<{ status: string; runs: number }>; reviews: Array<{ id: number; login: string; state: string; body: string; url: string }>; comments: Array<{ id: number; login: string; body: string; url: string }> }`+ - `interface PullRequestEvent { key: string; text: string }`+ - `pullRequestEvents(watch: PullRequestWatch, seen: readonly string[], botLogin: string | null, now: number): { events: PullRequestEvent[]; keys: string[] }`: `keys` is the new full seen list (newest 50), including the `ready:` mark. `events` are the ones to post (empty on first sight, `seen` empty, except a conflict).++- [ ] **Step 1: Write the failing tests:**+ - `posts CI failed with the failing job names`: a check run failed → one event `ci-red:<head>`, its text `CI failed on your pull request #12 (head abc1234): build (ubuntu), ci/required. <url>`.+ - `posts CI passed once every suite is done`: suites all completed, runs all success → `ci-green:<head>`, with text `CI passed on your pull request #12 (head abc1234). <url>`. With one suite `in_progress` → nothing.+ - `posts a review once`, `posts a comment once`, `skips the app's bot`.+ - `posts a merge conflict`: text `Your pull request #12 has a merge conflict with main (head abc1234): merge main into its branch and push. <url>`.+ - `first sight records and posts nothing but a conflict`.+ - `a draft posts no CI`, `ignores a draft's failure on the same head` (ready mark newer than the failed run's completedAt → no red), `a new head is news again`.+ - `keeps the newest 50 keys`.+- [ ] **Step 2: Run** `npx vitest run src/superTabs/pullRequestEvents.test.ts`. Expect FAIL (module missing).+- [ ] **Step 3: Implement** `pullRequestEvents` as designed above. Review text: `<login> asked for changes on|approved|reviewed your pull request #12: "<body, 300 chars>" <url>`. Comment text: `<login> commented on your pull request #12: "<body, 300 chars>" <url>`.+- [ ] **Step 4: Run** the same command. PASS.+- [ ] **Step 5: Commit** the test, then the code.++### Task 2: the GitHub read++**Files:**+- Modify: `backend/src/github/app.ts` (add `PULL_WATCH_PERMISSIONS`, `watchPullRequest`, conditional GETs)+- Modify: `backend/src/github/fakeGitHub.ts` (pulls with head, draft and mergeable; check runs; check suites; reviews; comments; ETag and 304)+- Test: `backend/src/github/app.test.ts`++**Interfaces:**+- Consumes: `PullRequestWatch` (Task 1).+- Produces:+ - `PULL_WATCH_PERMISSIONS = { pull_requests: 'read', checks: 'read', metadata: 'read' } as const`+ - `GitHubApp.watchPullRequest(repository: GitHubRepository, number: number, token: string): Promise<PullRequestWatch | null>`: null when GitHub cannot say. Remembers each path's ETag and body (at most 2,000 paths) and sends `If-None-Match`. A 304 reuses the body.++- [ ] **Step 1: Write the failing tests:** `watchPullRequest reads the pull, its head's check runs and suites, reviews and comments`; `asks again with If-None-Match and reuses a 304's body`; `a failed read is null`; `the watch token holds only pull_requests, checks and metadata read`.+- [ ] **Step 2: Run** `npx vitest run src/github/app.test.ts`. Expect FAIL.+- [ ] **Step 3: Implement.** Paths: `/pulls/{n}`, `/commits/{head}/check-runs?per_page=100`, `/commits/{head}/check-suites?per_page=100`, `/pulls/{n}/reviews?per_page=100`, `/issues/{n}/comments?per_page=100`. `call` takes optional extra headers and returns the `etag`.+- [ ] **Step 4: Run.** PASS.+- [ ] **Step 5: Commit** the test, then the code.++### Task 3: the store write and the worker pass++**Files:**+- Modify: `backend/src/superTabs/model.ts` (`Conversation.pullRequestEvents?: Record<string, string[]>`)+- Modify: `backend/src/superTabs/store.ts` (`pullRequestSeen`)+- Modify: `backend/src/superTabs/pullRequestEvents.ts` (`watchPullRequests`, `startPullRequestWatch`, `appPullRequestWatch`)+- Modify: `backend/src/worker.ts` (start it next to the archive pass)+- Test: `backend/integration/superTabPullRequestEvents.test.ts` (new; added to `vitest.super-tabs.config.ts`)++**Interfaces:**+- Consumes: `pullRequestEvents`, `PullRequestWatch` (Task 1), `watchPullRequest` (Task 2).+- Produces:+ - `SuperTabStore.pullRequestSeen(tabId: string, groupId: string, watch: PullRequestWatch, botLogin: string | null): Promise<number>`: messages posted.+ - `interface PullRequestReader { watch(url: string): Promise<PullRequestWatch | null>; botLogin(): Promise<string | null>; done(): Promise<void> }`+ - `watchPullRequests(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen'>, reader: PullRequestReader, now: number): Promise<number>`+ - `startPullRequestWatch(db, store, reader: () => PullRequestReader, everyMs = 60_000): () => void`++- [ ] **Step 1: Write the failing tests** (a Swarm with a Lead, a task assigned to a worker agent, the PR linked by its `work.status`, and a fake reader):+ - `CI red, CI green, a review and a conflict each post one message to the Engineer`: after a first pass (baseline), each change posts one message, to `recipientIds: [worker]` in the task, with the PR link and the job name.+ - `a second pass and a retried write post nothing`.+ - `no Engineer: recorded, not posted` (agent removed), and a later Engineer hears only new events.+ - `a step, a finished task and an archived task are not read`.+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabPullRequestEvents.test.ts`. Expect FAIL.+- [ ] **Step 3: Implement.** The pass's aggregate: `{ workFinished: false, archived: false, deleted: false, lastActivityAt: { $gte: now - 7 days }, 'data.reviewOf': { $not: { $type: 'string' } }, 'data.pullRequestUrls.0': { $exists: true } }`. It reads each URL once per pass. The write loads the group (`loadRow` with `groupIds`), skips a group that has ended, computes `pullRequestEvents`, writes the rows (`numberMessages`, `writeMessages`) and saves the keys. Nothing is saved when the keys did not change.+- [ ] **Step 4: Run** the file, then `npm run test:super-tabs`, `npx vitest run src/superTabs src/github` and `npx tsc --noEmit`. PASS.+- [ ] **Step 5: Commit** the test, then the code.diff --git a/docs/swarms.md b/docs/swarms.mdindex ad737674d..6187b2adf 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -359,6 +359,19 @@ Buddies are on in every Swarm; there is no setting. They replaced Chat with PM (person who leaves and joins again starts with a new chat and the default name. Look-alike letters from otherscripts are not compared.- Nobody else is ever added to a Buddy chat, the Swarm's owner and the product manager included.+- **Switching its model** (Scholes, 2026-11-03; docs/plans/2026-11-03-buddy-model-switch-design.md). The bar under the Buddy+ chat's header starts with a picker: **Your subscription** first, then every model the Swarm's grid serves now (a model a+ member's machine serves, or an API a member shares), each naming who serves it. The server accepts only those, the same+ check a routed start gets, and only from the Buddy's owner (`buddy.model`). The Buddy's own machine carries it out:+ its Claude Code relaunches in place on the model and reopens the same conversation, as a pane's model switch does, and+ the Buddy's thread sessions there move with it. A conversation at 80% or more of the model's window starts fresh on it+ instead, and switching back to the subscription reopens the earlier one. One line in the Buddy chat says how it went.+ Whoever serves the model gets a line in their own Buddy chat saying whose Buddy runs on it; a model that hits a limit,+ keeps failing or nobody has served for 2 minutes sends the Buddy back to its owner's subscription by itself. On a+ shared model a Buddy keeps its guard and starts no MCP server: none of the grid's web tools. What it sends, which can+ include anything its owner reads, goes to the machine or API serving the model; the picker names them for that reason.+ A Buddy on a Buddy-only machine cannot reach the Swarm's grid: the picker says to add the machine to the Swarm's+ Machines. A new thread session starts on the model its Buddy runs on.- A proposal is sent only for its owner's own message in their Buddy chat that asked for it: their newest message there,or one from the last hour, and only once for each such message. The server writes the "on behalf of" label, so a Buddy cannot leave it out or change it.- A proposal's files are only ones its owner handed it: a file inside the Buddy's own copy of the project (checked bydiff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 756218395..5fbef0a95 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -177,6 +177,15 @@ class SuperTabAgent {switchRequest = row['switchRequest'] is Map? Map.unmodifiable(superTabMap(row['switchRequest'])): null,+ gridModel = row['gridModel'] as String?,+ modelRequest = switch (row['modelRequest']) {+ {'id': final String id} && final Map request => (+ id: id,+ gridModel: request['gridModel'] as String?,+ name: request['name'] as String?,+ ),+ _ => null,+ },profileId = row['profileId'] as String?,avatar = SuperTabAvatarPicture.fromJson(row['avatar']),downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),@@ -212,6 +221,16 @@ class SuperTabAgent {/// it; null otherwise. Not drawn on the phone yet.final Map<String, dynamic>? switchRequest;+ /// The model on the Swarm's grid it runs on; null on its own subscription+ /// (backend Agent.gridModel), as the desktop's model reads it. The phone+ /// draws no model picker yet (task #2354 is Desktop and web first).+ final String? gridModel;++ /// A person's switch of their Buddy's model that is asked for and not yet+ /// done (backend buddyModel.ts `modelRequest`); null otherwise. A null+ /// [gridModel] there is the way back to their subscription.+ final ({String id, String? gridModel, String? name})? modelRequest;+/// The account on its machine it runs in; `default` when none is chosen./// Null until the backend reports it: the engine's default account. As the/// desktop's model reads it; not drawn on the phone yet.