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
Renaming a harness renames its agent in the Swarm (#2912) (#3015)
harness-for-autonomous[bot]b7aae02b3bb8
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex 4be1a4457..aa5aca7cb 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -272,6 +272,24 @@ describe('a team session speaking in a Swarm', () => {await expect(store.start(team, f.tab, f.startId)).rejects.toMatchObject(LIMITED)})+ // Task #2912 (security review 2 of #3015): an agent's name is its person's to give, so its machine's Team account, which is+ // that person signed in with no person to be, renames nothing: not as the person, and not as the agent it hosts.+ it('renames no agent, as the person or as its own machine\'s agent', async () => {+ const f = await fixture()+ const rename = (agentId: string): Command => ({ type: 'agent.rename', agentId, name: 'Renamed' })+ const names = async () => (await storedState(f.tab)).agents.map(a => [a.id, a.name, a.displayName])+ const before = await names()+ await expect(run(f.tab, rename(f.builder), team)).rejects.toMatchObject(LIMITED)+ await expect(run(f.tab, rename(f.personal), team)).rejects.toMatchObject(LIMITED)+ await expect(run(f.tab, rename(f.builder), team, f.builder)).rejects.toMatchObject({ code: 'FORBIDDEN', status: 403 })+ // The person's agent on another machine is not even one it can read.+ await expect(run(f.tab, rename(f.personal), team, f.builder)).rejects.toThrow('unavailable')+ expect(await names()).toEqual(before)+ // The person's own sign-in, the Team machine's owner, still renames the agent there.+ await run(f.tab, rename(f.builder), person)+ expect((await storedState(f.tab)).agents.find(a => a.id === f.builder)!.displayName).toBe('Renamed')+ })+it('cannot contribute, pause or remove a machine, or start, add or drive anything on the person\'s other machines', async () => {const f = await fixture()const commands: Command[] = [diff --git a/backend/src/superTabs/agentNames.ts b/backend/src/superTabs/agentNames.tsindex 1e541e07c..dd75baeab 100644--- a/backend/src/superTabs/agentNames.ts+++ b/backend/src/superTabs/agentNames.ts@@ -51,7 +51,7 @@ export function assignAgentDisplayNames(agents: NamedAgent[]): void {/** Read-only callers (native observations and legacy snapshots) get the same* names as the next authorized transaction, without mutating stored state. */-export function agentDisplayName(agents: NamedAgent[], id: string): string | undefined {+export function agentDisplayName(agents: readonly NamedAgent[], id: string): string | undefined {const member = agents.find(agent => agent.id === id)if (!member) return undefinedif (member.displayName && !reviewer.test(member.displayName.trim())) return member.displayNamediff --git a/backend/src/superTabs/agentRename.ts b/backend/src/superTabs/agentRename.tsnew file mode 100644index 000000000..ef09a075e--- /dev/null+++ b/backend/src/superTabs/agentRename.ts@@ -0,0 +1,65 @@+import { isRoleName } from './agentNames.js'+import { fail, type Actor, type Agent, type SuperTabState } from './model.js'+import { nameRefusal } from './personNames.js'+import { printable } from './profile.js'+import { agentNamesSeenBy, nameKey, swarmUsernames } from './usernames.js'++/** Characters, not UTF-16 units, as a person's name counts (personNames.ts). */+const AGENT_NAME_LENGTH = 60+/** What hides a name: the default-ignorables, and the Braille blank U+2800, which no category marks. */+const HIDDEN = /[\p{Default_Ignorable_Code_Point}\u2800]/u++/**+ * `agent.rename`: the name a person gave their agent with Rename Harness, which every reader's list shows. Only the agent's+ * contributor or its machine's owner, as a person, may (security review 2 of #3015). The name passes what a person's does+ * (personNames.ts `nameRefusal`: no web address, no role's or the Swarm's own name) and is not a name or username or email+ * of anyone here, nor another agent's that [actor] can read: a name nobody can take to pass as someone else, and a refusal+ * that never tells them an agent they cannot read exists.+ */+type Checked = { name: string } | { code: 'INVALID_AGENT_NAME' | 'AGENT_NAME_ROLE' | 'AGENT_NAME_TAKEN'; message: string; status: 400 | 409 }++/** [input] as the name of [exceptId]'s agent (or a new one), for what [actor] reads, or why it is refused. */+function checkedAgentName(state: SuperTabState, actor: Actor, exceptId: string | null, input: string): Checked {+ const name = input.normalize('NFKC').replace(/\s+/g, ' ').trim()+ if (!name || [...name].length > AGENT_NAME_LENGTH || !printable(name) || HIDDEN.test(name)) {+ return { code: 'INVALID_AGENT_NAME', message: `Use 1 to ${AGENT_NAME_LENGTH} characters, with no hidden ones.`, status: 400 }+ }+ const refused = nameRefusal(name)+ if (refused) return { code: refused.code === 'NAME_RESERVED' ? 'AGENT_NAME_ROLE' : 'INVALID_AGENT_NAME', message: refused.message, status: 400 }+ const key = nameKey(name)+ const usernames = swarmUsernames(state)+ const others = state.people.flatMap(p => [p.name, usernames.get(p.id), p.email])+ const agents = agentNamesSeenBy({ ...state, agents: state.agents.filter(a => a.id !== exceptId) }, actor)+ if ([...others, ...agents].some(other => other && nameKey(other) === key)) {+ return { code: 'AGENT_NAME_TAKEN', message: `${name} is taken in this Swarm. Choose another.`, status: 409 }+ }+ return { name }+}++/**+ * `agent.rename`: the name a person gave their agent with Rename Harness, which every reader's list shows. Only the agent's+ * contributor or its machine's owner, as a person, may (security review 2 of #3015). The name passes what a person's does+ * (personNames.ts `nameRefusal`: no web address, no role's or the Swarm's own name) and is not a name or username or email+ * of anyone here, nor another agent's that [actor] can read: a name nobody can take to pass as someone else, and a refusal+ * that never tells them an agent they cannot read exists.+ */+export function renameAgentTo(state: SuperTabState, actor: Actor, target: Agent, input: string): void {+ if (actor.kind !== 'person' || (actor.userId !== target.contributorId && actor.userId !== target.machineOwnerId)) {+ fail('FORBIDDEN', 'Only the person who runs this agent, or its machine\'s owner, can rename it.', 403)+ }+ const checked = checkedAgentName(state, actor, target.id, input)+ if ('code' in checked) fail(checked.code, checked.message, checked.status)+ target.displayName = checked.name+}++/**+ * The name `agent.add` gives a session a person shares, which Desktop takes from the harness's own name: the same rules, but+ * a name that fails them never stops the add. It is left for a member name (a role's name already is: agentNames.ts), so a+ * harness called "System" or "Quinn" joins as someone else's name never would.+ */+export function addedAgentName(state: SuperTabState, actor: Actor, input: string): string {+ const checked = checkedAgentName(state, actor, null, input)+ // A role's name stays as it always did: the agent is given a member name for it (agentNames.ts).+ if (isRoleName(input.normalize('NFKC'))) return input+ return 'name' in checked ? checked.name : 'Agent'+}diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 0c601bc4c..b1ce73390 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -5566,3 +5566,149 @@ describe('assigning an agent whose session was closed', () => {expect(resumed.f.state.conversations.find(c => c.id === resumed.group)!.assignment).toMatchObject({ agentId: resumed.worker })})})++describe('agent.rename (renaming a harness renames its agent, task #2912)', () => {+ const rename = (agentId: string, name: string): Command => ({ type: 'agent.rename', agentId, name })+ const shownTo = (f: ReturnType<typeof fixture>, reader: Actor, agentId: string) =>+ visibleState(f.state, reader).agents.find(a => a.id === agentId)!.displayName+ const peerContributorAgent = (f: ReturnType<typeof fixture>) => { f.invite(); return f.add('mine', 'peer') }++ it('lets the agent\'s contributor rename it, and every reader sees the new name', () => {+ const f = fixture(), agentId = peerContributorAgent(f)+ f.run(rename(agentId, ' Darren\'s PM '), peer)+ expect(shownTo(f, owner, agentId)).toBe('Darren\'s PM')+ expect(shownTo(f, peer, agentId)).toBe('Darren\'s PM')+ // A later command does not hand it a generated name again.+ f.run({ type: 'conversation.create', title: 'Later', brief: 'Anything.', checks: [] })+ expect(shownTo(f, owner, agentId)).toBe('Darren\'s PM')+ })++ it('lets the machine owner rename it', () => {+ const f = fixture(), agentId = peerContributorAgent(f)+ f.state.people.push({ id: 'host-owner', email: '[email protected]', role: 'collaborator', generation: 'g' } as never)+ f.run(rename(agentId, 'Studio'), { kind: 'person', userId: 'host-owner', email: '[email protected]' })+ expect(shownTo(f, owner, agentId)).toBe('Studio')+ })++ it('refuses a teammate who is neither, the Swarm owner, an agent and a Buddy, writing nothing', () => {+ const f = fixture(), agentId = peerContributorAgent(f), other = f.add('other', 'owner')+ const buddyId = f.add('buddy', 'owner')+ f.state.agents.find(a => a.id === buddyId)!.buddyOf = { personId: 'owner', projectId: 'lead', generation: 'g' } as never+ const before = JSON.stringify(f.state)+ for (const [actor, code] of [+ [owner, 'FORBIDDEN'],+ [{ kind: 'agent', agentId: other, machineOwnerId: 'host-owner' }, 'FORBIDDEN'],+ [{ kind: 'agent', agentId, machineOwnerId: 'host-owner' }, 'FORBIDDEN'],+ [{ kind: 'agent', agentId: buddyId, machineOwnerId: 'host-owner' }, 'BUDDY_FORBIDDEN'],+ ] as Array<[Actor, string]>) {+ expect(() => f.run(rename(agentId, 'Stolen'), actor), JSON.stringify(actor)).toThrow(expect.objectContaining({ code }))+ }+ expect(JSON.stringify(f.state)).toBe(before)+ })++ it('refuses a role\'s name, another agent\'s name, an empty or invisible name', () => {+ const f = fixture(), agentId = f.add('mine'), taken = f.add('taken')+ f.run(rename(taken, 'Quinn'))+ for (const name of ['Lead', 'Engineer 2', 'Reviewer', 'quinn', ' ', '']) {+ expect(() => f.run(rename(agentId, name)), name).toThrow(expect.objectContaining({ code: expect.stringMatching(/^(AGENT_NAME_ROLE|AGENT_NAME_TAKEN|INVALID_AGENT_NAME)$/) }))+ }+ expect(commandSchema.safeParse(rename(agentId, 'x'.repeat(201))).success).toBe(false)+ // Its own name again is no conflict.+ f.run(rename(taken, 'Quinn'))+ })++ // Security review 2 of #3015: an agent's name passes every rule a person's does, and tells nobody what they cannot read.+ it('refuses the Swarm\'s own voices, a web address or link, and a blank made of Braille (security review 2)', () => {+ const f = fixture(), agentId = f.add('mine')+ for (const name of ['System', 'Harness', 'Admin', 'Everyone', 'You', 'Someone 2', 'Tester', 'www.evil.example', '[Approve](https://ev.il)', '[Approve](//ev.il)',+ 'Lead\u2800', '\u2800', '\u2800\u2800\u2800']) {+ expect(() => f.run(rename(agentId, name)), name).toThrow(expect.objectContaining({ code: expect.stringMatching(/^(INVALID_AGENT_NAME|AGENT_NAME_ROLE|INVALID_NAME|NAME_RESERVED)$/) }))+ }+ })++ it('refuses a name a person here goes by: their name, username or email', () => {+ const f = fixture(), agentId = f.add('mine')+ f.invite()+ f.state.people.find(p => p.id === 'peer')!.name = 'Minh Nguyen'+ for (const name of ['minh nguyen', 'Minh Nguyen', 'peer', '@Peer', '[email protected]', 'owner']) {+ expect(() => f.run(rename(agentId, name)), name).toThrow(expect.objectContaining({ code: expect.stringMatching(/^(AGENT_NAME_TAKEN|NAME_TAKEN)$/) }))+ }+ })++ it('does not tell a reader that an agent they cannot read has a name (security review 2)', () => {+ const f = fixture()+ f.invite()+ const other = f.run({ type: 'project.create', name: 'Other', visibility: 'private', brief: '' }).result+ const hidden = f.add('hidden', 'owner', other.conversationId as string)+ f.run(rename(hidden, 'Quinn'))+ const mine = f.add('mine', 'peer')+ // The peer reads nothing of the private project: the name is not taken for them, and no refusal says it exists.+ f.run(rename(mine, 'Quinn'), peer)+ expect(shownTo(f, peer, mine)).toBe('Quinn')+ // The owner reads both, so a second Quinn is refused for them.+ const third = f.add('third', 'owner')+ expect(() => f.run(rename(third, 'Quinn'))).toThrow(expect.objectContaining({ code: 'AGENT_NAME_TAKEN' }))+ })++ it('refuses a viewer', () => {+ const f = fixture()+ f.invite()+ const agentId = f.add('mine', 'peer')+ f.state.people.find(p => p.id === 'peer')!.role = 'viewer'+ expect(() => f.run(rename(agentId, 'Studio'), peer)).toThrow(expect.objectContaining({ code: 'READ_ONLY' }))+ })++ it('refuses a non-member and an agent of the machine owner\'s Team account, writing nothing', () => {+ const f = fixture()+ f.invite()+ const agentId = f.add('mine', 'peer')+ const team = f.add('team-agent', 'owner')+ const before = JSON.stringify(f.state)+ // Not a member of this Swarm at all.+ expect(() => f.run(rename(agentId, 'Studio'), { kind: 'person', userId: 'stranger', email: '[email protected]' }), 'non-member').toThrow()+ // A Team account's session acts as an agent, here one the machine owner runs: never as the person.+ expect(() => f.run(rename(agentId, 'Studio'), { kind: 'agent', agentId: team, machineOwnerId: 'host-owner' }), 'team session').toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))+ expect(JSON.stringify(f.state)).toBe(before)+ })++ // Task #2912, security review 2: Add agent sends the typed harness name, so it gets the same rules; a name that fails them+ // gives the agent a member name instead, as a role's name does, and the add still succeeds.+ it('agent.add gives a member name to a name that is the Swarm\'s voice, a link, a person\'s or another agent\'s', () => {+ const f = fixture()+ f.invite()+ f.state.people.find(p => p.id === 'peer')!.name = 'Minh Nguyen'+ f.run(rename(f.add('first'), 'Quinn'))+ const group = f.group()+ const named = (name: string, harnessId: string) => {+ const id = f.run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId, name, configuration: config, lead: false },+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string+ f.run({ type: 'conversation.create', title: `After ${harnessId}`, brief: 'Anything.', checks: [] })+ return f.state.agents.find(a => a.id === id)!.displayName+ }+ for (const [i, name] of ['System', 'Everyone', '[Approve](https://ev.il)', 'minh nguyen', '[email protected]', 'quinn', 'Lead\u2800'].entries()) {+ expect(named(name, `h${i}`), name).not.toBe(name)+ expect(named(name, `h${i}`)).toBeTruthy()+ }+ expect(named('Release notes', 'ok')).toBe('Release notes')+ })++ // The row Add agent writes in the project chat names the agent as readers see it, never the name the rules refused.+ it('agent.add in the project chat writes no refused name into its row', () => {+ const f = fixture()+ for (const [i, name] of ['[Approve](https://ev.il)', '[Approve](//ev.il)', 'System'].entries()) {+ const effects = f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: `p${i}`, name, configuration: config, lead: false },+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } })+ const row = effects.messages.find(m => m.text.includes('to the project'))!.text+ expect(row, name).not.toContain(name)+ // Both halves name the agent as its readers' lists show it: its member name, not "Agent".+ const shown = visibleState(f.state, owner).agents.find(a => a.id === effects.result.agentId)!.displayName!+ expect(row, name).toBe(`owner added "${shown}" to the project. The project chat holds only its coordinator among agents, so "${shown}" works in its tasks.`)+ }+ })++ it('cleans credentials out of the name', () => {+ const github = ['ghp', 'Fixture0Token1Not2Real3Value4abcdefgh'].join('_'), removed: CredentialKind[] = []+ expect(withoutCredentials(rename('a', github), removed)).toMatchObject({ name: CREDENTIAL_MARKER })+ expect(removed).toEqual(['github'])+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 5b00172bf..3accc3f51 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -2,6 +2,7 @@ import { applyPushOrigin, failPushUnknown, failTeamWritten, hasStep, mainAccountimport type { PushOrigin } from '../github/pushOrigin.js'import { admitByRoom, admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'+import { addedAgentName, renameAgentTo } from './agentRename.js'import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'import { setName, writtenNameOf } from './personNames.js'import { z } from 'zod'@@ -294,6 +295,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('agent.switchResult'), agentId: id, switchId: id, ok: z.boolean(), error: z.string().trim().min(1).max(300).optional(), down: z.boolean().optional() }).strict(),z.object({ type: z.literal('agent.stopRefused'), agentId: id, releaseId: id }).strict(),z.object({ type: z.literal('agent.remove'), agentId: id, releaseId: id.optional() }).strict(),+ // Rename Harness on the agent's Mac renames the agent for every reader (task #2912); the contributor or machine owner only.+ z.object({ type: z.literal('agent.rename'), agentId: id, name: z.string().max(200) }).strict(),z.object({ type: z.literal('agent.release'), agentId: id, decision: z.enum(['keep', 'stop']) }).strict(),z.object({ type: z.literal('agent.sessionClosed'), agentId: id, harnessId: id }).strict(),z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),@@ -377,6 +380,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'buddy.propose': ['title', 'goal', 'scope'],'member.status': ['status.text'],'agent.add': ['name', 'initialMessage'],+ 'agent.rename': ['name'],'agent.start': ['request.name', 'overrideReason'],'agent.startFailed': ['error'],'agent.switchResult': ['error'],@@ -2257,6 +2261,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// agent it re-added a person's Buddy to a task, added to the project chat, and registered any session of its// contributor's machines, the Swarm's or not, past conversation.agent's checks (security review S2).if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person adds a session already running. Start a new agent instead.', 403)+ const addedName = addedAgentName(state, actor, command.name)const group = open(state, command.conversationId)const project = groupProject(state, group)if (state.projects && group.id === project.leadConversationId && command.lead && command.project) {@@ -2308,7 +2313,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,...(state.projects ? { projectId: project.id } : {}),machineOwnerId: grant.machineOwnerId, contributorId: grant.contributorId, membershipGeneration: contributor.generation,hostGrant: grant.hostGrant ?? null,- name: command.name, configuration: command.configuration, configurationVersion: operationId,+ name: addedName, configuration: command.configuration, configurationVersion: operationId,...(roleKind === 'reviewer' ? { role: 'reviewer' as const } : {}), ...(command.roleId ? { roleId: command.roleId } : {}),...(roleName ? { roleName } : {}),...(teamPool ? { teamAccount: true as const } : {}) })@@ -2318,9 +2323,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (existing && (existing.hostGrant ?? null) !== (grant.hostGrant ?? null)) {fail('CONTRIBUTION_REVOKED', 'Reconcile and remove this old contribution before adding it under the new machine share.', 403)}- if (sharedHere && !existing) message(group.id, `${who} added ${quotedName(command.name)} to the project. The project chat holds only its coordinator among agents, so ${quotedName(command.name)} works in its tasks.`, [], null, SYSTEM_ROW,- undefined, undefined, undefined, stableId(operationId, 'shared-to-project'))- else if (!group.agentIds.includes(agentId)) group.agentIds.push(agentId)+ // Named as readers' lists show it, never the name the rules refused (security review 2 of #3015).+ if (sharedHere && !existing) {+ const shown = quotedName(agentDisplayName(state.agents, agentId) ?? addedName)+ message(group.id, `${who} added ${shown} to the project. The project chat holds only its coordinator among agents, so ${shown} works in its tasks.`, [], null, SYSTEM_ROW,+ undefined, undefined, undefined, stableId(operationId, 'shared-to-project'))+ } else if (!group.agentIds.includes(agentId)) group.agentIds.push(agentId)if (command.lead) {keepLead(group, agentId)if (group.leadId && group.leadId !== agentId && activeWork(group)) fail('WORK_ACTIVE', 'Reconcile active work before replacing its lead.')@@ -2972,6 +2980,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,result.expiresAt = context.now + 120_000break}+ case 'agent.rename':+ renameAgentTo(state, actor, agent(state, command.agentId), command.name)+ breakcase 'agent.remove': {const target = agent(state, command.agentId)const hostStop = actor.kind === 'agent' && actor.agentId === target.id && target.workDecision === 'stop'diff --git a/backend/src/superTabs/personNames.test.ts b/backend/src/superTabs/personNames.test.tsindex c8240a27b..a4daaf8c5 100644--- a/backend/src/superTabs/personNames.test.ts+++ b/backend/src/superTabs/personNames.test.ts@@ -161,7 +161,7 @@ describe('member.name', () => {it('refuses a web address as a name, which server lines would show as a link (review 2 of #2794)', () => {const f = fixture()- for (const name of ['https://ev.il/x', 'ev.il://x', 'www.ev.il', 'WWW.EV.IL']) {+ for (const name of ['https://ev.il/x', 'ev.il://x', 'www.ev.il', 'WWW.EV.IL', '//ev.il', '[Ken](//ev.il)']) {expect(() => f.setName(name), name).toThrow(expect.objectContaining({ code: 'INVALID_NAME' }))}})diff --git a/backend/src/superTabs/personNames.ts b/backend/src/superTabs/personNames.tsindex 0888f7d9e..a4690238c 100644--- a/backend/src/superTabs/personNames.ts+++ b/backend/src/superTabs/personNames.ts@@ -15,8 +15,9 @@ export const MAX_NAME_LENGTH = 40export function nameRefusal(name: string): { code: 'INVALID_NAME' | 'NAME_RESERVED'; message: string } | null {// Read as every compare here reads it: width variants folded (NFKC), so `PM` is `PM` (review 2 of #2794).const folded = name.normalize('NFKC')- // A web address would show as a link in the lines the server writes (review 2 of #2794).- if (/:\/\/|^www\./i.test(folded)) return { code: 'INVALID_NAME', message: 'Use a name, not a web address.' }+ // A web address would show as a link in the lines the server writes (review 2 of #2794), a protocol-relative one too+ // ("//ev.il", security review 2 of #3015).+ if (/\/\/|^www\./i.test(folded)) return { code: 'INVALID_NAME', message: 'Use a name, not a web address.' }// A role's or the Swarm's own voice, as a Buddy may not take (buddies.ts), and the words readers put in place of a name.if (isRoleName(folded) || reserved(folded) || /^(?:tester|you|someone)(?:[\s#-]+\d+)?$/i.test(folded)) {return { code: 'NAME_RESERVED', message: `${name} is a role's name. Choose another.` }diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 23e71d6ce..d2a4f58dd 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -17188,6 +17188,23 @@ class AppNotifier extends ChangeNotifier {return;}_renameAgent(request.machine, agentId, name);+ // The Swarms that hold this harness show its agent by their own name:+ // the rename reaches everyone's sidebar (task #2912).+ try {+ final swarmErrors = await superTabs.renameHarnessAgent(+ machineId,+ agentId,+ name,+ );+ if (swarmErrors.isNotEmpty) {+ error =+ 'Renamed here, but the Swarm kept the old name: ${swarmErrors.first}';+ }+ } catch (_) {+ // The harness is renamed; only the Swarm could not be reached.+ error =+ 'Renamed here, but could not reach the Swarm to rename it there.';+ }} catch (failure) {error = failure is WsRequestTimeout? 'Could not confirm the rename. Refresh harnesses to check the name.'diff --git a/desktop/lib/super_tabs/actions.dart b/desktop/lib/super_tabs/actions.dartindex d0c0082c2..fcb762881 100644--- a/desktop/lib/super_tabs/actions.dart+++ b/desktop/lib/super_tabs/actions.dart@@ -1,6 +1,14 @@+import '../core/models.dart';import '../state/app_state.dart';import 'controller.dart';+/// The name an agent is added to the Swarm with: the name its person gave the+/// harness, else `Agent`, which the Swarm answers with a member name. Never the+/// harness's session title, which an automatic name shows instead (a terminal+/// title such as "cd /Users/…"; task #2912).+String superTabAddName(Agent native) =>+ isAutomaticHarnessName(native.name) ? 'Agent' : native.name;+Future<void> addSuperTabAgent(AppNotifier app,String tabId,@@ -39,7 +47,7 @@ Future<void> addSuperTabAgent('conversationId': conversationId,'machineId': machineId,'harnessId': harnessId,- 'name': native.displayName,+ 'name': superTabAddName(native),'lead': false,'configuration': {'engine': native.engine ?? '',diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 954a99d9b..73e823a5b 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -393,6 +393,27 @@ class SuperTabClient {String? leadProtectionReasonForHarness(String machineId, String harnessId) =>_leadOfHarness(machineId, harnessId)?.reason;+ /// Renames the agent a harness is in every loaded Swarm that holds it+ /// (Rename Harness, task #2912): each Swarm shows the agent by its own+ /// name, so the rename reaches everyone's sidebar. Why each Swarm that+ /// refused did, empty when all took it or none holds the harness.+ Future<List<String>> renameHarnessAgent(+ String machineId,+ String harnessId,+ String name,+ ) async {+ final errors = <String>[];+ for (final controller in loadedControllers.toList()) {+ final agent = controller.snapshot?.agents+ .where((a) => a.machineId == machineId && a.harnessId == harnessId)+ .firstOrNull;+ if (agent == null) continue;+ final error = await controller.renameAgent(agent.id, name);+ if (error != null) errors.add(error);+ }+ return errors;+ }+/// The coordinator's name in the project the machine's harness coordinates.String? leadCoordinatorForHarness(String machineId, String harnessId) =>_leadOfHarness(machineId, harnessId)?.coordinator;diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 830935435..975d548b8 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -3133,6 +3133,20 @@ class SuperTabController extends ChangeNotifier {null;}+ /// Renames the agent [agentId] for everyone in the Swarm (backend+ /// `agent.rename`): only the person who runs it, or its machine's owner, may.+ /// Null once the server took it; otherwise why it did not.+ Future<String?> renameAgent(String agentId, String name) async {+ final done = await command({+ 'type': 'agent.rename',+ 'agentId': agentId,+ 'name': name.trim(),+ });+ return done != null+ ? null+ : operationError ?? 'Another change is on its way. Try again.';+ }+/// Moves [taskId] right after [after] in its project's shared Next up, or to/// its top when [after] is null, for everyone (backend taskQueue.ts). Null/// once the server took it; otherwise why it did not.diff --git a/desktop/lib/super_tabs/import_agent.dart b/desktop/lib/super_tabs/import_agent.dartindex 0ec595783..fb68f6bcf 100644--- a/desktop/lib/super_tabs/import_agent.dart+++ b/desktop/lib/super_tabs/import_agent.dart@@ -11,6 +11,7 @@ import '../state/agent_handoff_file.dart';import '../state/app_state.dart';import '../state/harness_attachments.dart';import '../widgets/engine_identity.dart';+import 'actions.dart';import 'controller.dart';import 'identity.dart';import 'model.dart';@@ -386,7 +387,8 @@ Future<ImportResult> importAgent('conversationId': conversation,'machineId': teamId,'engine': agent.agent.engine,- 'name': name,+ // Never the session title an automatic name shows (task #2912).+ 'name': superTabAddName(agent.agent),'cwd': cwd,'roleName': 'Engineer','worktree': true,diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex 55a1403d4..f4829cec5 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -13,6 +13,7 @@ import '../state/harness_launch_integration.dart';import '../state/lead_placement.dart';import '../state/swarm.dart';import 'attachment_upload.dart';+import 'actions.dart';import 'controller.dart';import 'machine_icon.dart';import 'machine_status.dart';@@ -972,7 +973,7 @@ class SuperTabLaunch {'conversationId': saved['conversationId'],'machineId': machine,'harnessId': harnessId,- 'name': saved['lead'] == true ? 'Lead' : native.displayName,+ 'name': saved['lead'] == true ? 'Lead' : superTabAddName(native),'lead': saved['lead'],// A journal from an older Desktop keeps the id it chose.if (saved['roleId'] case final String roleId) 'roleId': roleId,diff --git a/desktop/test/super_tab_agent_rename_test.dart b/desktop/test/super_tab_agent_rename_test.dartnew file mode 100644index 000000000..c119c0fc7--- /dev/null+++ b/desktop/test/super_tab_agent_rename_test.dart@@ -0,0 +1,191 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/actions.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/controller.dart';++import 'super_tab_roster_test.dart' show RosterFixture;+import 'support/capture.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show MemoryStore;++/// Renaming a harness renames its agent in the Swarm (task #2912, Darren): the+/// sidebar Agents list showed the name the agent was added with, and a terminal+/// title when the pane had no name of its own.+void main() {+ final captureDir = Platform.environment['HARNESS_ROSTER_CAPTURE_DIR'];+ setUpAll(() => loadCaptureFonts(captureDir));++ group('Add agent names the agent', () {+ test('an explicit harness name is sent as it is', () {+ expect(+ superTabAddName(const Agent(id: 'a', name: 'Release notes')),+ 'Release notes',+ );+ });++ test('an automatic name is never its terminal title', () {+ // `displayName` of an automatic name is the session title: the+ // "cd /Users/…" row. The Swarm gives such an agent a member name.+ const agent = Agent(+ id: 'a',+ name: 'harness-3',+ title: 'cd /Users/macbookpro/projects/lamp',+ );+ expect(agent.displayName, startsWith('cd /Users'));+ expect(superTabAddName(agent), 'Agent');+ expect(+ superTabAddName(+ const Agent(id: 'a', name: 'Claude harness 11-04 09:30'),+ ),+ 'Agent',+ );+ });+ });++ group('Rename Harness reaches the Swarm', () {+ late RosterFixture f;+ setUp(() async {+ f = RosterFixture();+ await f.initialize();+ });++ test('its person renames it, and the Swarm shows the new name', () async {+ expect(f.controller.snapshot!.agentName('agent-1'), 'Sage');+ expect(await f.controller.renameAgent('agent-1', ' Darren PM '), isNull);+ expect(f.controller.snapshot!.agentName('agent-1'), 'Darren PM');+ });++ testWidgets('the sidebar row shows the Swarm\'s current name, in its list '+ 'and under Idle', (tester) async {+ // Built inside the test: its server and controller run on the test's clock.+ final f = RosterFixture();+ await f.initialize();+ await f.show(tester);+ expect(find.text('Sage'), findsOneWidget);+ (f.server.state['agents'] as List)[1]['displayName'] = 'Darren PM';+ (f.server.state['agents'] as List)[3]['displayName'] = 'Idle PM';+ await f.controller.refresh();+ await tester.pumpAndSettle();+ expect(find.text('Darren PM'), findsOneWidget);+ expect(find.text('Idle PM'), findsOneWidget);+ expect(find.text('Sage'), findsNothing);+ await f.close(tester);+ });++ test(+ 'a teammate who does not run the agent is refused, with why',+ () async {+ final teammate = RosterFixture(account: 'peer');+ await teammate.initialize();+ final refused = await teammate.controller.renameAgent(+ 'agent-1',+ 'Stolen',+ );+ expect(refused, contains('Only the person who runs this agent'));+ expect(teammate.controller.snapshot!.agentName('agent-1'), 'Sage');+ },+ );++ for (final brightness in [Brightness.light, Brightness.dark]) {+ testWidgets(+ 'the Agents list before and after a rename, ${brightness.name}',+ (tester) async {+ final f = RosterFixture();+ await f.initialize();+ await tester.binding.setSurfaceSize(const Size(560, 420));+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final agents = f.server.state['agents'] as List;+ // As Darren's list was: the name the agent was added with, and a+ // terminal title.+ agents[1]['displayName'] = 'cd /Users/macbookpro/proj…';+ agents[3]['displayName'] = 'Divide';+ await f.controller.refresh();+ await f.show(tester, brightness: brightness);+ await captureBoundary(+ tester,+ f.boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary,+ captureDir,+ 'agents-before-${brightness.name}',+ );+ agents[1]['displayName'] = 'Release PM';+ agents[3]['displayName'] = 'Docs writer';+ await f.controller.refresh();+ await tester.pumpAndSettle();+ expect(find.text('Release PM'), findsOneWidget);+ expect(find.text('Docs writer'), findsOneWidget);+ expect(find.textContaining('cd /Users'), findsNothing);+ await captureBoundary(+ tester,+ f.boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary,+ captureDir,+ 'agents-after-${brightness.name}',+ );+ await f.close(tester);+ },+ );+ }++ test('the client renames the agent in every loaded Swarm that holds '+ 'the harness, and no other', () async {+ final holder = ConversationServer()..state['id'] = 'tab';+ holder.state['agents'] = [+ {+ 'id': 'pm',+ 'name': 'Lead',+ 'displayName': 'Quinn',+ 'machineId': 'm',+ 'harnessId': 'native-pm',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ },+ ];+ final bystander = ConversationServer()..state['id'] = 'other';+ final servers = {'tab': holder, 'other': bystander};+ final client = SuperTabClient(+ transport: (method, path, {body}) async {+ if (Uri.parse(path).path == '/api/super-tabs/list') {+ return {+ 'tabs': [+ {'id': 'tab', 'name': 'Pilot'},+ {'id': 'other', 'name': 'Other'},+ ],+ 'next': null,+ };+ }+ return servers[Uri.parse(path).pathSegments[2]]!.request(+ method,+ path,+ body: body,+ );+ },+ storage: MemoryStore(),+ onTabs: (_, _) {},+ )..bind('owner');+ final tab = await client.open('tab');+ await client.open('other');+ final errors = await client.renameHarnessAgent(+ 'm',+ 'native-pm',+ 'Darren',+ );+ expect(errors, isEmpty);+ await tab.refresh();+ expect(tab.snapshot!.agentName('pm'), 'Darren');+ expect(+ await client.renameHarnessAgent('m', 'not-in-a-swarm', 'Nobody'),+ isEmpty,+ );+ client.dispose();+ });+ });+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 228832152..9df90c6fc 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -1567,6 +1567,21 @@ class ConversationServer {agent['displayName'] = shown;}}+ } else if (command['type'] == 'agent.rename') {+ // As the backend's: its contributor renames it, for every reader.+ final agent = (state['agents'] as List)+ .cast<Map<String, dynamic>>()+ .where((a) => a['id'] == command['agentId'])+ .firstOrNull;+ if (agent == null || agent['contributorId'] != (reader ?? 'owner')) {+ throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Only the person who runs this agent can rename it.',+ statusCode: 403,+ );+ }+ revision++;+ agent['displayName'] = (command['name'] as String).trim();} else if (command['type'] == 'buddy.remove') {revision++;final person = reader ?? 'owner';diff --git a/docs/plans/2026-11-04-agent-rename-swarm-plan.md b/docs/plans/2026-11-04-agent-rename-swarm-plan.mdnew file mode 100644index 000000000..f7dd42829--- /dev/null+++ b/docs/plans/2026-11-04-agent-rename-swarm-plan.md@@ -0,0 +1,78 @@+# Renaming a harness renames its agent in the Swarm Implementation Plan++> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,+> Engineer). One independent review on the pull request.++**Goal:** A name a person gives an agent with Rename Harness shows in every reader's sidebar Agents list (and its+Idle group), at once, on Desktop, web and phone. A terminal title never becomes an agent's Swarm name (task #2912,+Darren, 2026-11-04).++**Architecture:** Today Rename Harness (`AppNotifier.renameAgent`) renames the harness on the Mac's daemon and nothing+else. The Swarm keeps the name the agent was added with (`agent.add`'s `name`), and `agent.add` sends the pane's+session title when the pane has no explicit name; that is the "cd /Users/…" row.++- Backend: one command, `agent.rename {agentId, name}`. Only a person who is the agent's contributor or its machine's+ owner may send it; a teammate, an agent (a Buddy included) and a Team session are refused. It sets the agent's+ `displayName`, the name every list reads (`agentNames.ts`, `SuperTabAgent.displayName` on the client).+- Desktop: after the daemon confirms a rename, `SuperTabClient.renameHarnessAgent(machineId, harnessId, name)` sends+ the command for each loaded Swarm that holds that harness. A refusal is shown on the rename dialog, which already+ shows the daemon's errors.+- Desktop: `agent.add` (`addSuperTabAgent`, the launch journal) sends the harness's explicit name, never its session+ title; an automatic name sends `Agent`, and the backend gives the agent a member name.++**Tech Stack:** TypeScript (backend, vitest), Flutter (Desktop and web share this code).++**Spec:** task #2912's brief and River's ruling in the task thread: the Swarm renames, not only the local row.++## Global Constraints++- Red first for the permission (owner yes; teammate, agent, Buddy and Team session no), the name another reader+ sees, and no terminal title on add.+- Names are words people read: cleaned like other commands' words (`WORDS`), not a role's name, not another agent's.+- Swarm code stays out of `cli/src/core`. Desktop tests use a memory store and a fake sign-in.++## Design++- growth: N/A because it replaces one existing field on an agent; nothing accumulates.+- concurrency: the Swarm's one transaction per command, as every command; two renames to one name never both pass.+- read cost: N/A because no read is added; the name rides the agents the Swarm already sends.+- scale: N/A because one command per rename by one person.+- compatibility: an older client never sends the command and keeps showing `displayName`; an older backend refuses the+ unknown command, so Desktop shows the refusal and the local rename stands.+- migration + rollback: N/A because no stored shape changes; revert the commit and names stay as last set.+- audience: the server enforces it: contributor or machine owner only, as `agent.remove` does.+- identity: the signed-in person's id, never the machine owner's login.+- failure: a refused rename says why on the rename dialog; the local name stands.+- platforms: shared Flutter code and the backend.++## Review Focus++- `agent.rename` refuses every actor but the agent's contributor or machine owner; the Buddy command allowlist+ (`buddies.ts`) does not include it.+- A name that is a role's or another agent's is refused.+- A rename in one Swarm does not touch another Swarm's agent.++## Task 1: backend `agent.rename`++**Files:** `backend/src/superTabs/commands.ts`, `backend/src/superTabs/agentNames.ts`,+`backend/src/superTabs/commands.test.ts`++- [ ] Failing tests: owner renames, a reader sees the new name; teammate, agent, Buddy refused; role and taken names+ refused; credentials cleaned.+- [ ] Add the schema, `WORDS` entry and the case.++## Task 2: Desktop sends the rename with the local rename++**Files:** `desktop/lib/super_tabs/client.dart`, `desktop/lib/state/app_state.dart`,+`desktop/test/super_tab_agent_rename_test.dart`++- [ ] Failing test: a rename of a harness in a loaded Swarm sends `agent.rename`; the sidebar row shows the new name.+- [ ] Add `renameHarnessAgent` and call it after the daemon confirms.++## Task 3: no terminal title on add++**Files:** `desktop/lib/super_tabs/actions.dart`, `desktop/lib/super_tabs/launch.dart`,+`desktop/test/super_tab_agent_rename_test.dart`++- [ ] Failing test: adding a harness with an automatic name sends `Agent`, with an explicit name sends it.+- [ ] Add one helper both use.