Skip to content

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

Merge batch 11-03 bz: #2717 (#2754)

0xken15f1b9764d5e23
diff --git a/backend/integration/superTabMachineNames.test.ts b/backend/integration/superTabMachineNames.test.ts
new file mode 100644
index 000000000..368d71324
--- /dev/null
+++ b/backend/integration/superTabMachineNames.test.ts
@@ -0,0 +1,194 @@
+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, beforeEach, describe, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore, type SwarmChanged } from '../src/superTabs/store.js'
+import { localReportMemory, machineReportLine } from '../src/superTabs/machineReports.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { poolRows } from './hostRows.test-support.js'
+
+// A Swarm machine goes by the name its owner gave it in Machines (Dee, #2308: Mac 3 kept showing as Macs-Mac-Studio-2 in
+// New Project). The server takes it from the owner's own account row, never from what a client sends. A fresh loopback
+// replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let store: SuperTabStore
+let pushes: SwarmChanged[] = []
+const TEAM_COMPUTER = 'tttttttttttttttttttttttttttttttt'
+const dee: AuthUser = { sub: '400000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const huy: AuthUser = { sub: '400000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const deeTeam: AuthUser = { ...dee, harnessSessionId: 'dee-team-session', harnessSessionKind: 'team', harnessComputerId: TEAM_COMPUTER }
+const run = (tab: string, command: Command, user: AuthUser = dee) => store.execute(user, tab, { operationId: randomUUID(), command })
+const reading = (generation: string) => ({ generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,
+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Desktop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] }) as Parameters<SuperTabStore['observeMachine']>[3]
+const rename = (machineId: string, name: string | null) => db.machine.update({ where: { machineId }, data: { name } })
+const contribute = (tab: string, machineId: string, name: string, user: AuthUser = dee, extra: Partial<Extract<Command, { type: 'machine.contribute' }>> = {}) =>
+ run(tab, { type: 'machine.contribute', machineId, name, cwd: '/work', scope: 'swarm', engines: ['codex'], maxAgents: 3, ...extra }, user)
+const nameIn = async (tab: string, machineId: string, user: AuthUser = dee) =>
+ (await store.read(user, tab)).state.machines!.find(m => m.machineId === machineId)!.name
+/** The machine's host reports once, as its own session. */
+const report = async (tab: string, machineId: string, user: AuthUser = dee): Promise<'fast' | 'full'> => {
+ const generation = (await poolRows(store, user, machineId)).find(p => p.tabId === tab)!.machine.generation
+ machineReportLine(0)
+ await store.observeMachine(user, tab, machineId, reading(generation))
+ return machineReportLine(0).fast ? 'fast' : 'full'
+}
+
+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(`super_tab_machine_names_${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 } } })
+ // Sweeps never due, so a report takes the fast path whenever its reading alone changed (machineReports.ts).
+ const memory = localReportMemory(Date.now)
+ store = new SuperTabStore(db, Date.now, null, { reports: { get: (t, m) => memory.get(t, m), set: (t, m, r) => memory.set(t, m, r), sweepDue: async () => false },
+ swarmChanged: change => pushes.push(change) })
+ for (const user of [dee, huy]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: 'prod' } })
+ const machine = (machineId: string, userId: string, computerId: string, sessionKind: string, hostMachineId?: string) => db.machine.create({ data: {
+ machineId, userId, computerId, sessionKind, ...hostMachineId ? { hostMachineId } : {}, hostname: 'Macs-Mac-Studio-2.local',
+ apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ await machine('studio-2', dee.sub, 'ssssssssssssssssssssssssssssssss', 'computer')
+ await machine('studio-2-team', dee.sub, TEAM_COMPUTER, 'team', 'studio-2')
+ await machine('huy-mini', huy.sub, 'hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh', 'computer')
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+beforeEach(async () => {
+ // Seeded from the computer's hostname on its first connect (MachineService), as an account row is until its owner renames it.
+ await rename('studio-2', 'Macs-Mac-Studio-2.local')
+ await rename('studio-2-team', 'Macs-Mac-Studio-2 · Team')
+ await rename('huy-mini', 'Huy Mini')
+})
+
+async function swarm() {
+ const tab = (await store.create(dee, randomUUID(), 'Names')).id
+ const invitation = await run(tab, { type: 'invite.create', email: huy.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, huy)
+ return tab
+}
+
+describe('a machine joins under the name its owner gave it', () => {
+ it('takes the account name over the name its client sent', async () => {
+ await rename('studio-2', 'Mac 3')
+ const tab = await swarm()
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ expect(await nameIn(tab, 'studio-2')).toBe('Mac 3')
+ })
+
+ it('keeps its computer name while never renamed', async () => {
+ const tab = await swarm()
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ // Clients drop '.local' (Desktop superTabMachineName); the Swarm keeps the account's name as it is.
+ expect(await nameIn(tab, 'studio-2')).toBe('Macs-Mac-Studio-2.local')
+ })
+
+ it('keeps the name its client sent when its account row has none', async () => {
+ await rename('studio-2', null)
+ const tab = await swarm()
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ expect(await nameIn(tab, 'studio-2')).toBe('Macs-Mac-Studio-2')
+ })
+
+ it('shows a teammate\'s machine by the name its owner gave it', async () => {
+ const tab = await swarm()
+ await contribute(tab, 'huy-mini', 'huys-mac-mini.local', huy)
+ expect(await nameIn(tab, 'huy-mini', dee)).toBe('Huy Mini')
+ })
+})
+
+describe('a rename after joining', () => {
+ it('shows in the Swarm on its machine\'s next reading, and the one after is fast again', async () => {
+ const tab = await swarm()
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await report(tab, 'studio-2')
+ expect(await report(tab, 'studio-2')).toBe('fast')
+ await rename('studio-2', 'Mac 3')
+ pushes = []
+ expect(await report(tab, 'studio-2')).toBe('full')
+ expect(await nameIn(tab, 'studio-2')).toBe('Mac 3')
+ expect(await nameIn(tab, 'studio-2', huy)).toBe('Mac 3')
+ // Its members' clients are told, so the next refresh reads it.
+ expect(pushes.find(p => p.tabId === tab)).toMatchObject({ userIds: expect.arrayContaining([dee.sub, huy.sub]), parts: expect.arrayContaining(['main']) })
+ // The rename moved the Swarm's main stamp, so the report after runs in full once more, then they are fast again.
+ expect([await report(tab, 'studio-2'), await report(tab, 'studio-2')]).toEqual(['full', 'fast'])
+ })
+
+ it('renames it in every Swarm it is in', async () => {
+ const [one, two] = [await swarm(), await swarm()]
+ for (const tab of [one, two]) await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await rename('studio-2', 'Mac 3')
+ for (const tab of [one, two]) await report(tab, 'studio-2')
+ expect([await nameIn(one, 'studio-2'), await nameIn(two, 'studio-2')]).toEqual(['Mac 3', 'Mac 3'])
+ })
+
+ it('renames its Mac\'s Team account with it, which its own reading never renames to its account\'s name', async () => {
+ const tab = await swarm()
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await contribute(tab, 'studio-2-team', 'Macs-Mac-Studio-2 · Team', dee, { ifMissing: true, maxAgents: 1 })
+ expect(await nameIn(tab, 'studio-2-team')).toBe('Macs-Mac-Studio-2.local')
+ await rename('studio-2', 'Mac 3')
+ await report(tab, 'studio-2')
+ expect(await nameIn(tab, 'studio-2-team')).toBe('Mac 3')
+ await report(tab, 'studio-2-team', deeTeam)
+ expect(await nameIn(tab, 'studio-2-team')).toBe('Mac 3')
+ })
+
+ it('keeps the Swarm\'s name when its owner clears it back to none', async () => {
+ const tab = await swarm()
+ await rename('studio-2', 'Mac 3')
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await rename('studio-2', null)
+ await report(tab, 'studio-2')
+ expect(await nameIn(tab, 'studio-2')).toBe('Mac 3')
+ })
+})
+
+// Review of #2717: a machine renamed while offline sends no reading, so a rename in Machines reaches its Swarms by itself
+// (MachineService.rename → store.machineRenamed); the heartbeat stays the backstop.
+describe('a rename in Machines', () => {
+ const renamed = (machineId: string, owner: AuthUser = dee) => store.machineRenamed({ machineId, ownerId: owner.sub, autonomousEnv: 'prod' })
+
+ it('reaches every Swarm the machine is in at once, its Team account with it, with no reading', async () => {
+ const [one, two] = [await swarm(), await swarm()]
+ for (const tab of [one, two]) {
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await contribute(tab, 'studio-2-team', 'Macs-Mac-Studio-2 · Team', dee, { ifMissing: true, maxAgents: 1 })
+ await contribute(tab, 'huy-mini', 'Huy Mini', huy)
+ }
+ await rename('studio-2', 'Mac 3')
+ pushes = []
+ await renamed('studio-2')
+ for (const tab of [one, two]) {
+ expect([await nameIn(tab, 'studio-2', huy), await nameIn(tab, 'studio-2-team'), await nameIn(tab, 'huy-mini')]).toEqual(['Mac 3', 'Mac 3', 'Huy Mini'])
+ expect(pushes.find(p => p.tabId === tab)).toMatchObject({ userIds: expect.arrayContaining([dee.sub, huy.sub]), parts: expect.arrayContaining(['main']) })
+ }
+ })
+
+ it('keeps the Swarm\'s name when the name was cleared', async () => {
+ const tab = await swarm()
+ await rename('studio-2', 'Mac 3')
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await rename('studio-2', null)
+ await renamed('studio-2')
+ expect(await nameIn(tab, 'studio-2')).toBe('Mac 3')
+ })
+
+ it('changes nothing for anyone but the machine\'s owner', async () => {
+ const tab = await swarm()
+ await contribute(tab, 'studio-2', 'Macs-Mac-Studio-2')
+ await rename('studio-2', 'Mac 3')
+ await renamed('studio-2', huy)
+ expect(await nameIn(tab, 'studio-2')).toBe('Macs-Mac-Studio-2.local')
+ })
+})
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index e1517d652..f445b6556 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -40,6 +40,7 @@ import type { AuthUser } from '../lib/ssoAuth.js'
import { DEFAULT_DAYS, MAX_DAYS } from '../superTabs/costs/read.js'
import { WORKSPACE_ACCESS_REVOKED } from '../superTabs/workspaceStore.js'
import { markNothingNew } from '../lib/routeLatency.js'
+import { onMachineRenamed } from '../superTabs/machineRenames.js'
/** Runs a poll and marks its reply nothing-new for `route latency` when `empty` says so (spec 2026-11-02 poll cost, Part 0). */
const noting = <T>(req: FastifyRequest, run: () => Promise<T>, empty: (result: T) => boolean) => async (): Promise<T> => {
@@ -276,6 +277,8 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
+ 'so teammates\' agents get no access to it. Someone who can push to it approves it in Harness: Project details, GitHub access.', 403)
}
const store = options.store ?? await productionStore(github)
+ // A rename in Machines reaches the Swarms the machine is in at once (MachineService.rename).
+ onMachineRenamed(rename => store.machineRenamed(rename))
const reads = options.reads ?? new SwarmReads(store, { githubApp: !!github })
const hosts = options.hosts ?? new HostReads(store, { githubApp: !!github, teamAccountsIdle: !github })
// Members' apps read a project's GitHub access again when its revision moves (projects.ts githubRevision). A move that
diff --git a/backend/src/services/MachineService.rename.test.ts b/backend/src/services/MachineService.rename.test.ts
new file mode 100644
index 000000000..4b1aaa9ec
--- /dev/null
+++ b/backend/src/services/MachineService.rename.test.ts
@@ -0,0 +1,73 @@
+/**
+ * A rename in Machines reaches the Swarms the machine is in (Dee, #2308; review of #2717): its Mac's Harness Team account rows
+ * take the new name with their ' · Team' suffix, and the Swarms are told at once, so an offline machine is not left with its
+ * old name there until it reports again.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const findUnique = vi.hoisted(() => vi.fn())
+const update = vi.hoisted(() => vi.fn())
+const updateMany = vi.hoisted(() => vi.fn())
+const machineRenamed = vi.hoisted(() => vi.fn())
+
+vi.mock('../lib/prisma.js', () => ({
+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },
+ prisma: { machine: { findUnique, update, updateMany } },
+}))
+vi.mock('../lib/bus.js', () => ({
+ getAgentPresence: vi.fn(), readAgentPresence: vi.fn(), clearAgentPresence: vi.fn(), pub: {}, consumeNewIdQuota: vi.fn(),
+ publishDown: vi.fn(async () => {}), publishDeviceMachineListChanged: vi.fn(async () => {}),
+}))
+vi.mock('../config/env.js', () => ({ env: {} }))
+vi.mock('../lib/managers.js', () => ({ selectManagerId: vi.fn() }))
+vi.mock('../lib/provision.js', () => ({ provisionViaManager: vi.fn() }))
+vi.mock('../lib/machineLifecycle.js', () => ({ ensureMachineReady: vi.fn(), publishMachineLifecycle: vi.fn() }))
+vi.mock('../lib/machineCredential.js', () => ({ encryptMachineCredential: vi.fn() }))
+vi.mock('./MachineBillingService.js', () => ({ machineBillingService: {} }))
+vi.mock('../superTabs/machineRenames.js', () => ({ machineRenamed }))
+const warn = vi.hoisted(() => vi.fn())
+vi.mock('../utils/logger.js', () => ({ logger: { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() } }))
+
+const { machineService } = await import('./MachineService.js')
+
+const MAC = 'a'.repeat(32)
+const owner = { sub: 'owner-1', role: 'user', autonomousEnv: 'prod' } as const
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ findUnique.mockResolvedValue({ machineId: MAC, userId: owner.sub, managerId: '', autonomousEnv: 'prod', authMode: 'remote', deletedAt: null })
+ update.mockResolvedValue({})
+ updateMany.mockResolvedValue({ count: 1 })
+ machineRenamed.mockResolvedValue(undefined)
+})
+
+describe('rename', () => {
+ it('names the Mac\'s Team account rows "<new name> · Team"', async () => {
+ await machineService.rename(MAC, owner, 'Mac 3')
+ expect(updateMany).toHaveBeenCalledWith({ where: expect.objectContaining({ userId: owner.sub, autonomousEnv: 'prod', hostMachineId: MAC,
+ sessionKind: 'team' }), data: { name: 'Mac 3 · Team' } })
+ })
+
+ it('keeps a 40-character name whole before the suffix, as the CLI names a Team account after a longer hostname', async () => {
+ const long = 'M'.repeat(40)
+ await machineService.rename(MAC, owner, long)
+ expect(updateMany.mock.calls[0]![0].data).toEqual({ name: `${long} · Team` })
+ })
+
+ it('leaves the Team account rows as they are when the name is cleared', async () => {
+ await machineService.rename(MAC, owner, null)
+ expect(updateMany).not.toHaveBeenCalled()
+ })
+
+ it('tells the Swarms the machine is in, as its owner\'s', async () => {
+ await machineService.rename(MAC, owner, 'Mac 3')
+ expect(machineRenamed).toHaveBeenCalledWith({ machineId: MAC, ownerId: owner.sub, autonomousEnv: 'prod' })
+ })
+
+ it('still renames when the Swarms cannot be told, and says so in the log', async () => {
+ machineRenamed.mockRejectedValue(new Error('swarm down'))
+ await expect(machineService.rename(MAC, owner, 'Mac 3')).resolves.toBeUndefined()
+ expect(update).toHaveBeenCalledWith({ where: { machineId: MAC }, data: { name: 'Mac 3' } })
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Swarm'), expect.objectContaining({ machineId: MAC }))
+ })
+})
diff --git a/backend/src/services/MachineService.ts b/backend/src/services/MachineService.ts
index eda270fcf..59195a81b 100644
--- a/backend/src/services/MachineService.ts
+++ b/backend/src/services/MachineService.ts
@@ -16,6 +16,7 @@ import { machineBillingService } from './MachineBillingService.js'
import { storedAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'
import { TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'
import type { AuthUser } from '../lib/ssoAuth.js'
+import { machineRenamed } from '../superTabs/machineRenames.js'
/** The agent's tier / how it runs Claude, resolved through its plan.
* 'self' | 'managed' = a docker agent-node on a manager host; 'remote' = the user's own computer
@@ -651,6 +652,16 @@ export const machineService = {
assertRequesterEnvironment(binding, requester)
assertMachineBillingActive(binding)
await prisma.machine.update({ where: { machineId }, data: { name } })
+ // Its Mac's Harness Team accounts go by "<Mac> · Team" (cli/src/team/command.ts), and keep that after the new name; the
+ // suffix runs past the 40 characters a rename takes, as it does after a longer hostname. A cleared name leaves them.
+ if (name) {
+ await prisma.machine.updateMany({ where: { userId: binding.userId, autonomousEnv: binding.autonomousEnv, hostMachineId: machineId,
+ sessionKind: 'team', ...machineAlive }, data: { name: `${name} · Team` } })
+ }
+ // Every Swarm it is in shows the new name now, not on its next reading, which an offline machine never sends (#2308).
+ await machineRenamed({ machineId, ownerId: binding.userId, autonomousEnv: binding.autonomousEnv }).catch(error => {
+ logger.warn('machine rename did not reach its Swarms; their next reading of it will', { machineId, error: error instanceof Error ? error.message : String(error) })
+ })
await publishDeviceMachineListChanged(binding.userId, { reason: 'renamed' }).catch(() => { /* best effort */ })
if (binding.managerId === '') {
// Remote machine: a live adapter mirrors the name locally (`machine status`) — push it the new one.
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 82dbf756b..dd74f6f6b 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -397,6 +397,8 @@ export interface CommandContext {
deletedMachineIds?: string[]
/** Read from host ownership/access records by the store, never copied from the request. */
contribution?: { machineOwnerId: string; contributorId: string; hostGrant?: string | null
+ /** The name the machine's owner gave it, from its account row (machines.ts accountMachineName); absent when it has none. */
+ machineName?: string
/** A Harness Team account's machine: the Mac it lives on, from its account row (machines.ts ContributedMachine). */
hostMachineId?: string
/** The machine's account row is signed in as a Harness Team account (lib/teamSession.ts), with or without a Mac. */
@@ -1713,7 +1715,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
state.machineCleanups = state.machineCleanups?.filter(c => c.machineId !== command.machineId)
if (!state.machineCleanups?.length) delete state.machineCleanups
const host = context.contribution?.hostMachineId
- state.machines.push({ machineId: command.machineId, name: mac?.name ?? command.name, cwd: command.cwd, engines: [...new Set(command.engines)],
+ state.machines.push({ machineId: command.machineId, name: mac?.name ?? context.contribution?.machineName ?? command.name, cwd: command.cwd, engines: [...new Set(command.engines)],
maxAgents: mac?.maxAgents ?? command.maxAgents, ...(command.scope ? { scope: command.scope } : {}),
contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused,
...(host ? { hostMachineId: host } : {}), ...(teamAccountOnly ? { teamAccountOnly: true as const } : {}) })
diff --git a/backend/src/superTabs/machineRenames.ts b/backend/src/superTabs/machineRenames.ts
new file mode 100644
index 000000000..8af34655f
--- /dev/null
+++ b/backend/src/superTabs/machineRenames.ts
@@ -0,0 +1,17 @@
+/** A machine its owner renamed in Machines (routes/machines.ts → MachineService.rename). Its Swarms read the new name from
+ * its account row (machines.ts accountMachineName), never from here. */
+export interface MachineRename { machineId: string; ownerId: string; autonomousEnv: string }
+
+type Listener = (rename: MachineRename) => Promise<unknown>
+let listener: Listener | null = null
+
+/** The Swarm routes' store takes renames from here (routes/superTabs.ts), so MachineService loads no Swarm code. */
+export function onMachineRenamed(next: Listener | null): void {
+ listener = next
+}
+
+/** Tells the Swarms the machine is in at once (Dee, #2308; review of #2717): one renamed while offline sends no reading,
+ * so it would keep its old name there until it reports again. Nothing to do when no Swarm routes run here. */
+export async function machineRenamed(rename: MachineRename): Promise<void> {
+ await listener?.(rename)
+}
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 0a62c2a1c..3bbc5bd87 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -357,6 +357,26 @@ export function teamPoolsOf(state: SuperTabState, pool: ContributedMachine): Con
return state.machines?.filter(m => m.hostMachineId === pool.machineId && m.contributorId === pool.contributorId) ?? []
}
+/** The name a machine's owner gave it in Machines (its account row, routes/machines.ts rename), which every Swarm list shows
+ * (Dee, #2308): seeded from its computer's hostname, so a machine never renamed keeps that. Null when the row has none. */
+export function accountMachineName(row: { name: string | null } | null | undefined): string | null {
+ return row?.name?.trim() || null
+}
+
+/** Whether [pool] shows another name than [name], its owner's (accountMachineName). A Team account's pool goes by its Mac's
+ * name, never its own account's "<Mac> · Team": it follows its Mac (followAccountName). */
+export function renamedBy(pool: ContributedMachine, name: string | null): name is string {
+ return !!name && !pool.hostMachineId && pool.name !== name
+}
+
+/** Renames [pool], and its Mac's Team account pools, to [name] when its owner renamed it (renamedBy); whether it did. Its
+ * host's readings call it, so a rename shows in every Swarm the machine is in by its next heartbeat. */
+export function followAccountName(state: SuperTabState, pool: ContributedMachine, name: string | null): boolean {
+ if (!renamedBy(pool, name)) return false
+ for (const each of [pool, ...teamPoolsOf(state, pool)]) each.name = name
+ return true
+}
+
/** The one of them that runs teammates' work on the Mac: not being removed, and the last to report. Undefined when none. */
export function teamPoolOf(state: SuperTabState, pool: ContributedMachine, live?: readonly string[]): ContributedMachine | undefined {
// [live]: the account rows still signed in as team accounts (store.ts teamMachines). One removed since (`harness team
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index edef3b137..fe8da1c60 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1,5 +1,5 @@
import { writeReactionActivity, writeReplyActivity } from './activity.js'
-import { expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, recordAgentPresence, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'
+import { accountMachineName, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'
import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'
import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'
import { createHash } from 'node:crypto'
@@ -51,7 +51,8 @@ import { judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWE
import { archivable, archiveLine, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'
import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'
-import { autoJoinSwarms, memberSwarms } from './swarmRows.js'
+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'
@@ -105,6 +106,8 @@ const PROPOSED = 'This file already went with a proposal. Ask your owner to send
const hash = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex')
/** The fields of a Swarm's row the store reads. A migrated row still keeps its whole old state (`legacyState`, about 1 MB
* for a busy Swarm) until the maintenance script removes it, and every command and read loads this row. */
+/** The most Swarms a rename reaches at once, as many as a host reads (read/host.ts FULL_TABS); its readings do the rest. */
+const MACHINE_RENAME_SWARMS = 500
const SWARM_ROW = { id: true, ownerId: true, revision: true, format: true, deletedAt: true } satisfies Prisma.SuperTabSelect
export type SwarmRow = Prisma.SuperTabGetPayload<{ select: typeof SWARM_ROW }>
/** A Swarm whose state still waits for its split into parts (design section 6.1) is not served until it is split. */
@@ -955,8 +958,11 @@ export class SuperTabStore {
person(state, contributorId)
const machine = await tx.machine.findFirst({ where: { machineId: command.machineId, autonomousEnv: state.environment, ...machineAlive } })
if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This machine is unavailable.', 403)
+ // Its owner's name for it, from its account row: the name a client sends may be the computer's (#2308).
+ const named = accountMachineName(machine)
// A Mac's Harness Team account names its Mac from its own account row, which only its owner's sign-in set (machines.ts).
- const host = { ...(machine.sessionKind === 'team' && machine.hostMachineId ? { hostMachineId: machine.hostMachineId } : {}),
+ const host = { ...(named ? { machineName: named } : {}),
+ ...(machine.sessionKind === 'team' && machine.hostMachineId ? { hostMachineId: machine.hostMachineId } : {}),
// A Team sign-in with no Mac (`harness team on`) is no person's own machine either (commands.ts buddy.create).
...(machine.sessionKind === 'team' ? { teamSession: true as const } : {}) }
if (pooled) {
@@ -3068,6 +3074,8 @@ export class SuperTabStore {
const part = loaded !== undefined ? loaded : (await loadMachineParts(this.db, [partId(tabId, machineId)])).get(partId(tabId, machineId))
const pool = part && !part.deleted ? part.data.contribution : null
if (!part || !pool || pool.contributorId !== user.sub || pool.generation !== observation.generation || pool.removal) return null
+ // Renamed by its owner since: the full report renames it, and its Team account's pools with it (#2308).
+ if (renamedBy(pool, accountMachineName(host.owned))) return null
const data = structuredClone(part.data), mine = data.contribution!
const reading = storedObservation(mine, observation, { team: isTeamSession(user), now, preparable: id => record.preparable.includes(id) })
if (!readingOnly(mine.observation, reading)) return null
@@ -3160,6 +3168,8 @@ export class SuperTabStore {
preparable: id => !!state.starts?.some(s => s.id === id && preparableStart(s, machineId)) })
accrueLent(state, pool, now)
pool.observation = reading
+ // The name its owner gave it in Machines, which a rename there changes (#2308).
+ followAccountName(state, pool, accountMachineName(owned))
// A reading that shows a suspended engine signed in with quota offered again (engineHealth.ts); posts nothing.
readingClearsSuspensions(pool, now)
// Current-generation physical stop proof also finishes a close whose membership was already withdrawn.
@@ -3855,6 +3865,34 @@ export class SuperTabStore {
* needs `reviewOf`, the group the pass read as its task, which this write reads again: it stays open unless that task is
* done or cancelled and that task's pull requests are settled too. A review nobody is reviewing closes the same way
* (tidy.ts reviewClosable). True when it archived. */
+ /**
+ * A machine its owner renamed (machineRenames.ts): every Swarm it is in shows the name from its owner's account row now, its
+ * Mac's Team account pools with it (machines.ts followAccountName), as its next reading would. One Swarm at a time, each
+ * written only when its name differs; a Swarm that fails is logged and left to that reading. The Swarms renamed.
+ */
+ async machineRenamed({ machineId, ownerId, autonomousEnv }: MachineRename): Promise<number> {
+ const row = await this.db.machine.findFirst({ where: { machineId, userId: ownerId, autonomousEnv, ...machineAlive }, select: { name: true } })
+ const name = accountMachineName(row)
+ if (!name) return 0
+ let renamed = 0
+ for (const tabId of await machineSwarms(this.db, autonomousEnv, machineId, MACHINE_RENAME_SWARMS)) {
+ try {
+ if (await transaction(this.db, async tx => {
+ const swarm = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
+ if (!swarm || swarm.deletedAt) return false
+ const loaded = await loadRow(tx, requireParts(swarm)), state = cloneData(loaded.state)
+ const pool = machineContribution(state, machineId)
+ if (!pool || pool.removal || !followAccountName(state, pool, name)) return false
+ await this.save(tx, loaded, state, clock.next())
+ return true
+ })) renamed++
+ } catch (error) {
+ logger.warn('[swarm] a machine rename did not reach a Swarm', { tabId, machineId, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ return renamed
+ }
+
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/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 2542fcaae..30d797693 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/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'], 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'], 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/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 9d2bd4b6f..32dcc01b8 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -1138,6 +1138,65 @@ void main() {
expect(find.textContaining('.local'), findsNothing);
});
+ // #2308: Dee renamed his Mac Studio 2 to 'Mac 3' in Machines and New
+ // Project still listed it by its computer name. The Swarm's machine record
+ // carries the name its owner gave it (backend machines.ts
+ // accountMachineName); the menu shows that, never the computer's own name.
+ testWidgets('New Project lists a renamed machine by the name its owner '
+ 'gave it, not its computer name', (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.connection.server.state['machines'] = [
+ machineRow('studio-2', 'Mac 3', contributor: 'owner', lead: true),
+ ];
+ // This computer knows the machine by its hostname too.
+ const studio = Machine(
+ machineId: 'studio-2',
+ authMode: MachineAuthMode.remote,
+ name: 'Macs-Mac-Studio-2.local',
+ );
+ f.app.machines = [...f.app.machines, studio];
+ f.app.machineStates['studio-2'] = MachineState(studio)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = [];
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = (await tester.runAsync(() => f.box(newProject: true)))!;
+ expect(
+ box.integration!.leadMachines!.singleWhere((m) => m.id == 'studio-2'),
+ isA<LeadMachine>()
+ .having((m) => m.name, 'name', 'Mac 3')
+ .having((m) => m.inSwarm, 'inSwarm', isTrue),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 1200,
+ height: 800,
+ child: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-machine')));
+ await tester.pump();
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('new-harness-lead-machine-studio-2')),
+ matching: find.text('Mac 3'),
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Macs-Mac-Studio-2'), findsNothing);
+ });
+
// Security reviews 1 and 2 of #2228: the server decides where a teammate's
// Mac runs the PM, by engine (backend leadStart.ts leadChoices), and New
// Project shows that rather than working it out from the readings.
diff --git a/docs/plans/2026-11-03-swarm-machine-names-plan.md b/docs/plans/2026-11-03-swarm-machine-names-plan.md
new file mode 100644
index 000000000..66f8ac8ab
--- /dev/null
+++ b/docs/plans/2026-11-03-swarm-machine-names-plan.md
@@ -0,0 +1,117 @@
+# Swarm machine names follow the account name Implementation Plan
+
+> Worked by this project's instructions (Engineer role): plan first in a draft pull request, then each task test first,
+> one independent Review step on the pull request. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Every Swarm machine list shows the name the machine's owner gave it in Machines, follows a rename within one
+refresh, and a never-renamed machine keeps its computer name (clients already drop `.local`).
+
+**Architecture:** The Swarm's machine record (`ContributedMachine.name`) is stamped by the server from its contributor's
+own account row (`Machine.name`), never from what a client sends. Two places write it: `machine.contribute` (join and
+settings saves) and every host reading (the 15 s heartbeat), which the server already authenticates against that same
+account row (`MachineHost.owned`). A reading whose pool name differs from the account name takes the full path and
+renames the pool and its Mac's Harness Team account pools; the next reading is fast again. Clients keep reading
+`machines[].name`; none keeps a copy.
+
+**Tech Stack:** TypeScript, Prisma/MongoDB, vitest with mongodb-memory-server (backend); Flutter 3.47.2 (Desktop).
+
+**Spec:** Task #2308 brief (Dee, 2026-11-03), in the pull request body.
+
+## Global Constraints
+
+- Owner's own machine names only: a teammate's machine shows the name its owner gave it, never anything private.
+- The Team account entry keeps its '· Team' suffix after the new name (its account row; in the Swarm a Team pool shows its Mac's name).
+- PR body first line: "Requested by [email protected] through Harness."
+- Before Ready: a test that fails without the fix for every risk, red/green evidence in a PR comment, the full Super Tab integration suite.
+- Swarm code stays out of cli/src/core. Desktop tests use a memory store and a fake sign-in.
+
+## Design
+
+- growth: none; one string per Swarm machine record, replaced in place.
+- concurrency: the machine part's guarded write, as every reading takes.
+- read cost: none added; the account row is already read once per report call (`machineHost`).
+- scale: a rename costs one full reading per Swarm the machine is in, then fast again; metric: `machineReportLine` full share.
+- compatibility: old clients send a name in `machine.contribute`; the server ignores it when the account row has one. Old hosts unchanged.
+- migration + rollback: none; stale names correct themselves on the next heartbeat. Rollback leaves the stamped names, which are correct.
+- audience: the name comes from the contributor's own row (`userId = reporter`), so only the owner's choice is shown; Buddies still read no machine names.
+- identity: never the machine owner's login; only their machine's display name.
+- failure: an account row with no name keeps the pool's current name; nothing fails.
+- platforms: Desktop, web and phone read `machines[].name`; no client change.
+
+## Review Focus
+
+- A Team account's reading must not rename its pool to its own row's "<host> · Team" name: it follows its Mac. (Task 2 test.)
+- An account row whose name was cleared (null) or is blank keeps the Swarm's current name, never empties it. (Task 1 and 2 tests.)
+- A shared (lent) machine reports under its owner; the name is the owner's, never the borrowing contributor's. Covered by the reporter check: `owned` is the reporter's own row.
+- The fast path must not keep a stale name forever: a differing name forces the full path once. (Task 2 test checks paths.)
+- A renamed Mac's Team pool in the same Swarm shows the new name too. (Task 2 test.)
+
+---
+
+### Task 1: `machine.contribute` takes the account's name
+
+**Files:**
+- Modify: `backend/src/superTabs/machines.ts` (add `accountMachineName`)
+- Modify: `backend/src/superTabs/store.ts:947-975` (`contribution` returns `machineName`)
+- Modify: `backend/src/superTabs/commands.ts:397` (context type), `:1700` (pool name)
+- Test: `backend/integration/superTabMachineNames.test.ts` (new; add to `vitest.super-tabs.config.ts`)
+
+**Interfaces:**
+- Produces: `accountMachineName(row: { name: string | null } | null | undefined): string | null` — the trimmed name, or null when none.
+- Produces: `context.contribution.machineName?: string` — set when the account row has a name.
+
+- [ ] **Step 1: Write the failing test** `a machine joins under its account name, not the name Desktop sent`: account row
+ `name: 'Mac 3', hostname: 'Macs-Mac-Studio-2.local'`; `machine.contribute` with `name: 'Macs-Mac-Studio-2'`; the read's
+ `machines[0].name` is `'Mac 3'`. And `a never-renamed machine joins under its computer name`: row `name: 'Macs-Mac-Studio-2.local'`
+ → `'Macs-Mac-Studio-2.local'` (clients drop `.local`). And a row with `name: null` keeps the sent name.
+- [ ] **Step 2: Run** `npx vitest run --config vitest.super-tabs.config.ts integration/superTabMachineNames.test.ts`; expect the first to FAIL with `'Macs-Mac-Studio-2'`.
+- [ ] **Step 3: Implement**: `contribution()` adds `machineName` from `accountMachineName(machine)`; the pool's name is `mac?.name ?? context.contribution.machineName ?? command.name`.
+- [ ] **Step 4: Run** the same command; PASS.
+- [ ] **Step 5: Commit** test, then code.
+
+### Task 2: a reading renames the pool and its Team pools
+
+**Files:**
+- Modify: `backend/src/superTabs/machines.ts` (add `followAccountName`)
+- Modify: `backend/src/superTabs/store.ts` `fastReading` and `fullReading`
+- Test: `backend/integration/superTabMachineNames.test.ts`
+
+**Interfaces:**
+- Produces: `followAccountName(state: SuperTabState, pool: ContributedMachine, name: string | null): boolean` — sets
+ `pool.name` and each `teamPoolsOf(state, pool)` name to `name`; false (and nothing changed) when `name` is null, the
+ pool is a Team pool (`hostMachineId`), or the names already match.
+
+- [ ] **Step 1: Write the failing tests**: `a rename after joining shows on the next reading` — contribute with row name
+ 'Macs-Mac-Studio-2.local', set the row's name to 'Mac 3', one `observeMachine`; the read's name is 'Mac 3', and the
+ swarmChanged push includes the owner. `a renamed Mac's Team pool follows it`: a Team account row (`sessionKind: 'team'`,
+ `hostMachineId`, name 'Macs-Mac-Studio-2 · Team') contributed after its Mac; rename the Mac; the Mac's reading renames
+ both pools to 'Mac 3'; the Team account's own reading leaves its pool 'Mac 3'. `a cleared name keeps the Swarm's name`:
+ set row name null; a reading leaves 'Mac 3'. `the next reading is fast again`: after the renaming reading, `settle` ends 'fast'.
+- [ ] **Step 2: Run**; expect FAIL with the old name.
+- [ ] **Step 3: Implement**: `fastReading` returns null when `accountMachineName(host.owned)` differs from a non-Team pool's
+ name; `fullReading` calls `followAccountName(state, pool, accountMachineName(owned))` before saving.
+- [ ] **Step 4: Run** the file, then the whole Super Tab integration suite (`npm run test:super-tabs`) and `npx tsc --noEmit`; PASS.
+- [ ] **Step 5: Commit** test, then code.
+
+### Task 3: Desktop's New Project menu shows the Swarm's name
+
+**Files:**
+- Test: `desktop/test/super_tab_launch_test.dart`
+
+- [ ] **Step 1: Write the test** `New Project shows a renamed machine by its new name after a refresh`: own pool 'm' named
+ 'Macs-Mac-Studio-2.local' while this computer's Machine row is also that; the menu row shows 'Macs-Mac-Studio-2'; the
+ server's pool becomes 'Mac 3' and the form refreshes (`leadMachinesOf` of a fresh read); the menu row shows 'Mac 3' and no
+ 'Macs-Mac-Studio-2'. Desktop reads the Swarm's name already, so this pins it rather than failing first; the red/green
+ evidence for the fix is Tasks 1–2.
+- [ ] **Step 2: Run** `flutter test test/super_tab_launch_test.dart --plain-name 'renamed machine'`; PASS.
+- [ ] **Step 3: Commit.**
+
+### Task 4 (review of #2717): a rename in Machines reaches the Swarms at once, and the Team rows
+
+**Files:**
+- Create: `backend/src/superTabs/machineRenames.ts` (`onMachineRenamed`, `machineRenamed(rename: MachineRename): Promise<void>`)
+- Modify: `backend/src/services/MachineService.ts` `rename`; `backend/src/superTabs/store.ts` (`machineRenamed`); `backend/src/routes/superTabs.ts` (wires the store)
+- Test: `backend/src/services/MachineService.rename.test.ts`, `backend/integration/superTabMachineNames.test.ts`
+
+- [x] Failing tests: an offline machine's rename shows in every Swarm with no reading, its Team pool too, members pushed; a cleared name keeps the Swarm's; another person's call changes nothing; the Mac's Team rows become "<name> · Team" (a 40-character name kept whole: the suffix runs past it, as the CLI's does after a 60-character hostname); a cleared name leaves them; a Swarm that cannot be told is logged and the rename still succeeds.
+- [x] Implement: the store reads the owner's row itself (never a name passed in) and renames by `followAccountName`; the heartbeat stays the backstop.