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 b1951: #2803 #2795 (#2821)
0xken15286ba50834e3
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.tsindex ca3ee3904..e860f4eac 100644--- a/backend/integration/superTabTeam.test.ts+++ b/backend/integration/superTabTeam.test.ts@@ -16,6 +16,7 @@ import { stableId, type SuperTabState } from '../src/superTabs/model.js'import { roleVersion } from '../src/superTabs/projects.js'import { assignmentRows, poolRows, rosterRows } from './hostRows.test-support.js'import { logger } from '../src/utils/logger.js'+import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'// A team session (docs/plans/2026-10-24-swarm-team-account.md, Task 1) is the owner's account signed in on a second// macOS user of the owner's Mac. In a Swarm it may host its own machine and speak as the agents running there, and@@ -395,6 +396,26 @@ describe('a team session speaking in a Swarm', () => {expect(await store.githubAssignment(person, f.tab, f.personal, 'personal-mac')).toMatchObject({ agentId: f.personal })})+ it('reads costs and CI load and sends a file over the form\'s 10 MB only as an agent on its own machine', async () => {+ const f = await fixture()+ const files = new MemoryAttachmentStore()+ const attaching = new SuperTabStore(db, Date.now, { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })+ // As its own agent: the route's measures, and a file sent by link (`post --attach` past the form's limit).+ expect(await attaching.costSummary(team, f.tab, 7, f.builder)).toMatchObject({ rows: expect.any(Array) })+ expect(await attaching.ciRepository(team, f.tab, 'lead', f.builder)).toEqual({ repositoryUrl: null })+ const { upload } = await attaching.uploadLink(team, f.tab, f.teamGroup, { name: 'trace.zip', mime: 'application/zip', size: 5 }, f.builder)+ expect(await files.receive(upload.url, upload.headers, Buffer.from('hello'))).toBe(200)+ expect((await attaching.completeUpload(team, f.tab, upload.id, f.builder)).attachment).toMatchObject({ id: upload.id, size: 5 })+ // As the person, or as the person's agent on their personal Mac: refused before anything is read or signed.+ for (const as of [undefined, f.personal]) {+ await expect(attaching.costSummary(team, f.tab, 7, as)).rejects.toMatchObject(LIMITED)+ await expect(attaching.ciRepository(team, f.tab, 'lead', as)).rejects.toMatchObject(LIMITED)+ await expect(attaching.uploadLink(team, f.tab, f.personalGroup, { name: 'trace.zip', mime: 'application/zip', size: 5 }, as))+ .rejects.toMatchObject(LIMITED)+ await expect(attaching.completeUpload(team, f.tab, upload.id, as)).rejects.toMatchObject(LIMITED)+ }+ })+it('reads a custom role text only for its own machine\'s agents, never as the project\'s owner', async () => {const f = await fixture()const roles = [{ id: 'lead', name: 'Product Manager', kind: 'lead' as const, text: 'LEAD-TEXT' },diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 8b3816dd6..4c4444f5b 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -2098,6 +2098,53 @@ describe('Super Tabs on a real Mongo replica set', () => {expect(history.json().data.messages.find((m: { text: string; source?: unknown }) => !memberRow(m)).text).toBe('A shared conversation.')})+ // Tony, 2026-11-03 (#2458): New Harness from a project chat records the person's first message beside the row naming who+ // added the harness. Both took the operation id, so the join answered 500 and the harness never joined.+ it('joins a harness started from the project chat with a first message, through the HTTP API', async () => {+ const { tab } = await fixture()+ const headers = { authorization: `Bearer ${owner.sub}` }+ const operationId = randomUUID()+ const join = () => app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`, headers,+ payload: { operationId, command: { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: 'new-pm-personal',+ name: 'Kai', configuration: config, lead: false, initialMessage: 'Hi New PM Personal' } } })+ const joined = await join()+ expect(joined.statusCode, joined.body).toBe(200)+ const agentId = joined.json().data.result.agentId as string+ expect((await storedState(tab)).agents.map(a => a.id)).toContain(agentId)+ const rows = (await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages`, headers })).json().data.messages as+ Array<{ id: string; text: string; source?: unknown }>+ const first = rows.find(m => m.text === 'Hi New PM Personal'), added = rows.find(m => / added "Kai" to the project\./.test(m.text))+ // The person's message is the one the receipt names; the row naming who added the harness has its own id.+ expect(first?.id).toBe(joined.json().data.result.messageId)+ expect(added?.id).toBeDefined()+ expect(added?.id).not.toBe(first?.id)+ // The same request again answers the same and writes nothing twice.+ const again = await join()+ expect(again.statusCode).toBe(200)+ expect(again.json().data.result.agentId).toBe(agentId)+ const after = (await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages`, headers })).json().data.messages as Array<{ text: string }>+ expect(after.filter(m => m.text === 'Hi New PM Personal')).toHaveLength(1)+ })++ it('joins a Product Manager with a first message and a launch-refused note, through the HTTP API', async () => {+ const tab = (await store.create(owner, randomUUID(), 'Personal')).id+ const headers = { authorization: `Bearer ${owner.sub}` }+ const operationId = randomUUID()+ const joined = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`, headers,+ payload: { operationId, command: { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: 'new-pm',+ name: 'Lead', configuration: config, lead: true, initialMessage: 'Hi New PM Personal',+ launchRefused: { model: 'opus', effort: 'xhigh' } } } })+ expect(joined.statusCode, joined.body).toBe(200)+ const rows = (await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages`, headers })).json().data.messages as+ Array<{ id: string; text: string }>+ const first = rows.find(m => m.text === 'Hi New PM Personal')+ expect(first?.id).toBe(joined.json().data.result.messageId)+ const refused = rows.find(m => m.text.includes('could not launch it with them'))+ expect(refused?.id).toBeDefined()+ expect(refused?.id).not.toBe(first?.id)+ expect((await storedState(tab)).conversations.find(c => c.id === 'lead')?.leadId).toBe(joined.json().data.result.agentId)+ })+it('rechecks the machine share at delivery even while the contributor remains in the tab', async () => {const { tab } = await fixture()await invite(tab)diff --git a/backend/src/lib/teamSession.test.ts b/backend/src/lib/teamSession.test.tsindex 8a56b6b5a..845328f07 100644--- a/backend/src/lib/teamSession.test.ts+++ b/backend/src/lib/teamSession.test.ts@@ -179,6 +179,12 @@ describe('a team session on its own machine', () => {['GET', '/api/super-tabs/tab-1/projects/project-1/instructions?asAgentId=agent-1', undefined, 'instructions'],['GET', '/api/super-tabs/tab-1/projects/project-1/instructions/revisions?asAgentId=agent-1', undefined, 'instructionRevisions'],['GET', '/api/super-tabs/tab-1/projects/project-1/instructions/revisions/3?asAgentId=agent-1', undefined, 'instructionRevision'],+ // The route's measures and a file over the form's 10 MB (2026-11-03: refused here, so a Team PM routed without the CI hold+ // and a Team Engineer could not attach a big file). Each store method holds the agent to this machine (integration test).+ ['GET', '/api/super-tabs/tab-1/costs?days=7&asAgentId=agent-1', undefined, 'costSummary'],+ ['GET', '/api/super-tabs/tab-1/projects/project-1/ci-load?asAgentId=agent-1', undefined, 'ciRepository'],+ ['POST', '/api/super-tabs/tab-1/attachments/uploads?asAgentId=agent-1', { conversationId: 'lead', name: 'trace.zip', mime: 'application/zip', size: 20_000_000 }, 'uploadLink'],+ ['POST', '/api/super-tabs/tab-1/attachments/uploads/upload-1/complete?asAgentId=agent-1', {}, 'completeUpload'],]for (const [method, url, payload, reached] of own) {it(`${method} ${url.split('?')[0]} reaches the store as the team session`, async () => {@@ -265,6 +271,10 @@ describe('a team session reaching past its own machine', () => {'/api/super-tabs/tab-1/projects/project-1/instructions', '/api/super-tabs/tab-1/projects/project-1/instructions/revisions','/api/super-tabs/tab-1/projects/project-1/instructions/revisions/3']) limited(await call('GET', url))limited(await call('POST', '/api/super-tabs/tab-1/attachments'))+ limited(await call('GET', '/api/super-tabs/tab-1/costs?days=7'))+ limited(await call('GET', '/api/super-tabs/tab-1/projects/project-1/ci-load'))+ limited(await call('POST', '/api/super-tabs/tab-1/attachments/uploads', { conversationId: 'lead', name: 'trace.zip', mime: 'application/zip', size: 20_000_000 }))+ limited(await call('POST', '/api/super-tabs/tab-1/attachments/uploads/upload-1/complete', {}))expect(store.calls).toEqual([])})diff --git a/backend/src/lib/teamSession.ts b/backend/src/lib/teamSession.tsindex 12002a224..d0070a530 100644--- a/backend/src/lib/teamSession.ts+++ b/backend/src/lib/teamSession.ts@@ -137,6 +137,10 @@ export const TEAM_ROUTES: readonly TeamRoute[] = [{ method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/instructions', scope: 'agent' },{ method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/instructions/revisions', scope: 'agent' },{ method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/instructions/revisions/:revision', scope: 'agent' },+ // What the route ranks by: the project's measured costs and its CI load (superTabs/costs/read.ts, github/ciLoad.ts). Missing+ // here until 2026-11-03, so a Team PM routed without them and the CI hold never applied.+ { method: 'GET', url: '/api/super-tabs/:tabId/costs', scope: 'agent' },+ { method: 'GET', url: '/api/super-tabs/:tabId/projects/:projectId/ci-load', scope: 'agent' },// The decisions its agent asked of people, and their answers (superTabs/decisions.ts).{ method: 'GET', url: '/api/super-tabs/:tabId/decisions', scope: 'agent' },{ method: 'GET', url: '/api/super-tabs/:tabId/conversations/:conversationId/messages', scope: 'agent' },@@ -145,6 +149,9 @@ export const TEAM_ROUTES: readonly TeamRoute[] = [{ method: 'GET', url: '/api/super-tabs/:tabId/conversations/:conversationId/attempts', scope: 'agent' },{ method: 'GET', url: '/api/super-tabs/:tabId/terminal/:requestId', scope: 'agent' },{ method: 'POST', url: '/api/super-tabs/:tabId/attachments', scope: 'agent' },+ // A file over the form's 10 MB: a signed link to the bucket, then its check (store.ts uploadLink, completeUpload).+ { method: 'POST', url: '/api/super-tabs/:tabId/attachments/uploads', scope: 'agent' },+ { method: 'POST', url: '/api/super-tabs/:tabId/attachments/uploads/:uploadId/complete', scope: 'agent' },// Its agent's one-hour GitHub token for the repository of its task (Task 4); the body's machine must be its own.{ method: 'POST', url: '/api/super-tabs/:tabId/github-token', scope: 'agent', bodyMachine: true },// Commands as one of its agents, its agents' deliveries, stops and native terminals, its agents' role texts.diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 2a6fe197d..03d7bde84 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -863,8 +863,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,brief: group.brief, checks: group.checks, assignment: group.assignment }))}const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>,- attachments?: Attachment[], mentions?: string[], holdMentions?: true) => {- effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}),+ attachments?: Attachment[], mentions?: string[], holdMentions?: true, id = operationId) => {+ effects.messages.push({ id, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}),...(attachments?.length ? { attachments } : {}), ...(mentions?.length ? { mentions } : {}), ...(holdMentions ? { holdMentions } : {}) })result.messageId = operationId}@@ -2109,7 +2109,8 @@ 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)+ 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)if (command.lead) {keepLead(group, agentId)@@ -2126,7 +2127,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,}// A Product Manager started on its person's own Mac says, as one the Swarm starts does (leadJoined), when it does not// run the model its role asked for.- if (command.lead && command.launchRefused) message(group.id, launchRefusedLine(command.launchRefused, coordinatorNameOf(project)), [], null, SYSTEM_ROW)+ if (command.lead && command.launchRefused) message(group.id, launchRefusedLine(command.launchRefused, coordinatorNameOf(project)), [], null, SYSTEM_ROW,+ undefined, undefined, undefined, stableId(operationId, 'launch-refused'))break}case 'agent.start': {diff --git a/cli/src/superTabs/routeMeasured.spec.ts b/cli/src/superTabs/routeMeasured.spec.tsindex 6cea80825..e7460645b 100644--- a/cli/src/superTabs/routeMeasured.spec.ts+++ b/cli/src/superTabs/routeMeasured.spec.ts@@ -1,5 +1,5 @@// cli/src/superTabs/routeMeasured.spec.ts-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { choose, type Assessment, type Catalog, type Probe } from './route.js'import { MEASURED, MEASURED_MAKER, measuredFrom, measuredPlugin, readMeasured, type MeasuredRow } from './routeMeasured.js'import { ROUTE_PLUGIN_MAKERS, type PluginInput } from './routePlugins.js'@@ -172,6 +172,24 @@ describe('reading the measures', () => {expect(read).toEqual({ rows: [row({})], truncated: true })})+ it('logs a refused or failed read once per reason, never its detail, so a Team account\'s refusal is seen', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ // A fresh module: what it already said is kept per process.+ vi.resetModules()+ const { readMeasured } = await import('./routeMeasured.js')+ try {+ const refused = async () => ({ error: 'TEAM_SESSION_LIMITED', detail: 'A team sign-in can only run Swarm agents on its own machine.', status: 403 })+ expect(await readMeasured(refused)).toBeNull()+ expect(await readMeasured(refused)).toBeNull()+ expect(await readMeasured(async () => { throw new Error('socket closed') })).toBeNull()+ expect(await readMeasured(async () => { throw new Error('socket closed again') })).toBeNull()+ expect(warn.mock.calls.map(c => String(c[0]))).toEqual([+ '[super-tabs] the route could not read cost results: TEAM_SESSION_LIMITED (403); it ranks without them',+ '[super-tabs] the route could not read cost results: the request failed; it ranks without them',+ ])+ } finally { warn.mockRestore() }+ })+it('a refusal, a failure, a slow read or an answer it cannot read gives no measures, so the route ranks as today', async () => {expect(await readMeasured(async () => ({ error: 'FORBIDDEN' }))).toBeNull()expect(await readMeasured(async () => { throw new Error('gone') })).toBeNull()diff --git a/cli/src/superTabs/routeMeasured.ts b/cli/src/superTabs/routeMeasured.tsindex 071f8fb60..83f693c5f 100644--- a/cli/src/superTabs/routeMeasured.ts+++ b/cli/src/superTabs/routeMeasured.ts@@ -59,11 +59,23 @@ export function measuredFrom(answer: unknown): Measured | null {return { rows, truncated: value.truncated === true }}+/** Each reason a read failed, said once per process: the route runs about 30 times an hour, and a refusal that lasts (a Team+ * account refused the costs route until 2026-11-03) would otherwise fill the log or, as before, say nothing at all. */+const saidWhy = new Set<string>()+function sayOnce(why: string): void {+ if (saidWhy.has(why)) return+ saidWhy.add(why)+ console.warn(`[super-tabs] the route could not read cost results: ${why}; it ranks without them`)+}+const reasonOf = (answer: Record<string, unknown>) =>+ `${String(answer.error)}${Number.isInteger(answer.status) ? ` (${answer.status as number})` : ''}`+/** The project's measures, read through the route's own backend request: null when refused, failed, slower than [ms] or- * unreadable, so the route ranks as today. The route runs about 30 times an hour; the read is the costs command's, about- * 0.1 to 0.3 s beyond a plain request on the openharness Swarm (2026-10-31). */+ * unreadable, so the route ranks as today. A refusal is logged by its code, never its detail. The read is the costs+ * command's, about 0.1 to 0.3 s beyond a plain request on the openharness Swarm (2026-10-31). */export async function readMeasured(request: ScopedRequest, ms = READ_MS): Promise<Measured | null> {- const answer = await within(request({ action: 'costs', days: DAYS }).catch(() => null), ms)+ const answer = await within(request({ action: 'costs', days: DAYS }).catch(() => { sayOnce('the request failed'); return null }), ms)+ if (answer && typeof answer.error === 'string') sayOnce(reasonOf(answer))return answer ? measuredFrom(answer) : null}diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex 214e729b0..55a1403d4 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -50,15 +50,37 @@ class SuperTabLaunch {if (app.currentUser?.id != account) {throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');}+ // A project with no coordinator gets its Product Manager from New Harness+ // in its chat, the person's first message going to it (River, 11-03,+ // #2458: Tony's Personal project had none and joined a worker instead).+ SuperTabSnapshot? snapshot;+ if (raw == null && tab.superTabId != null && !newProject) {+ snapshot = await app.superTabs.readSnapshot(tab.superTabId!);+ if (app.currentUser?.id != account) {+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');+ }+ }+ final unled = snapshot?.projectFor(conversationId);+ final coordinator =+ unled != null &&+ unled.leadConversationId == conversationId &&+ snapshot!.leadOf(unled.id) == null;final saved = raw == null? <String, dynamic>{'operationId': superTabOperationId(),'joinId': superTabOperationId(),'tabId': tab.superTabId,'conversationId': conversationId,- 'lead': tab.superTabId == null || newProject,+ 'lead': tab.superTabId == null || newProject || coordinator,'newSwarm': tab.superTabId == null,'newProject': newProject,+ // It leads a project already there: its and the Swarm's names+ // and visibility stay as they are.+ if (coordinator) ...{+ 'coordinator': true,+ 'title': unled.name,+ 'coordinatorName': snapshot.coordinatorNameOf(unled.id),+ },'visibility': 'public',if (!newProject) 'projectId': 'lead',}@@ -70,8 +92,9 @@ class SuperTabLaunch {// Swarm (no coordinator name on the project) has no such field.List<String>? roleSuggestions;if (saved['lead'] != true && tab.superTabId != null) {- final snapshot = await app.superTabs.readSnapshot(tab.superTabId!);- final project = snapshot.projectFor(conversationId);+ final project =+ (snapshot ?? await app.superTabs.readSnapshot(tab.superTabId!))+ .projectFor(conversationId);if (project != null && project.hasInstructions) {roleSuggestions = await launch.readRoleSuggestions(tab.superTabId!,@@ -144,13 +167,14 @@ class SuperTabLaunch {: saved['roleName'] as String?,actionLabel: saved['newProject'] == true? 'New Project'- : saved['lead'] == true+ : saved['lead'] == true && saved['coordinator'] != true? 'New Swarm': 'New Harness',// Routing reads quota for Claude Code and Codex only, so a Lead is one// of them; the agents it starts may be anything.engines: saved['lead'] == true ? const ['claude', 'codex'] : null,- projectVisibility: saved['lead'] == true+ projectVisibility:+ saved['lead'] == true && saved['coordinator'] != true? saved['visibility'] as String? ?? 'public': null,projectVisibilityLocked:@@ -279,7 +303,12 @@ class SuperTabLaunch {/// A native start was asked for, so the journal must outlive this form.bool get started =>saved['phase'] == 'starting' || saved['phase'] == 'joining';- String get who => saved['lead'] == true ? 'Lead' : 'harness';++ /// The coordinator as the project calls it: never "Lead" on screen (Naming+ /// System; River, #2458).+ String get who => saved['lead'] == true+ ? saved['coordinatorName'] as String? ?? kDefaultCoordinatorName+ : 'harness';String get machineName {final machine = saved['machineId'] as String?;if (machine == null) return 'the machine';@@ -296,7 +325,7 @@ class SuperTabLaunch {saved['title'] ??(saved['newProject'] == true ? 'New project' : 'Swarm');return saved['lead'] == true- ? 'Waiting for $machineName to start the Lead for “$title”.'+ ? 'Waiting for $machineName to start the $who for “$title”.': 'Waiting for $machineName to start the harness.';}@@ -918,6 +947,25 @@ class SuperTabLaunch {'Waiting for the new harness to appear on its machine.',);}+ // Whether it leads was read when the box opened. A project that got its+ // Product Manager since keeps it: agent.add would make this one its lead+ // (Hollis, review of #2803). This one was started as a PM, so it does not+ // join as a worker either; it keeps running, and its person decides.+ if (saved['coordinator'] == true) {+ final fresh = await app.superTabs.readSnapshot(saved['tabId'] as String);+ checkAccount();+ final project = fresh.projectFor(saved['conversationId'] as String);+ final lead = project == null ? null : fresh.leadOf(project.id);+ if (lead != null &&+ (lead.machineId != machine || lead.harnessId != harnessId)) {+ throw SuperTabFailure(+ 'COORDINATOR_TAKEN',+ 'Another $who joined this project while this one was starting. '+ 'This one keeps running on $machineName: Discard request to '+ 'leave it out of the project.',+ );+ }+ }final project = native.project ?? app.stateOf(machine)?.projectOf(native);saved['command'] ??= {'type': 'agent.add',@@ -975,7 +1023,8 @@ class SuperTabLaunch {// Waking the exact host starts only its authorized contributions. It is// safe to retry, and never grants machine access to the tab's members.await app.wakeSuperTabHost(machine);- if (saved['lead'] == true) {+ // A new Swarm or project takes its Lead's name; one already there keeps its own.+ if (saved['lead'] == true && saved['coordinator'] != true) {final name = Swarm.titleFor(native);final title =saved['title'] as String? ??@@ -1040,7 +1089,9 @@ class SuperTabLaunch {saved.remove('files');await persist();}- if (saved['lead'] == true && saved['newProject'] != true) {+ if (saved['lead'] == true &&+ saved['newProject'] != true &&+ saved['coordinator'] != true) {app.bindSuperTab(swarmId,tabId,@@ -1066,6 +1117,7 @@ class SuperTabLaunch {if (const {'ACCOUNT_CHANGED','AGENT_UNAVAILABLE',+ 'COORDINATOR_TAKEN','FILES_UNCONFIRMED',}.contains(failure.code)) {rethrow;@@ -1076,11 +1128,26 @@ class SuperTabLaunch {}}- SuperTabFailure _joinFailed(Object failure) => SuperTabFailure(- 'JOIN_FAILED',- 'The $who started on $machineName. Joining it to the project failed: '- '${'$failure'.replaceFirst(RegExp(r'\.$'), '')}. Check status to try again.',- );+ /// The join's failure in the person's words: what happened, and what to do.+ /// A server's own error is never a reason to give up on the harness, and a+ /// refusal names the server's reason (Tony, #2458: "An internal server error+ /// occurred" told him neither).+ SuperTabFailure _joinFailed(Object failure) {+ final reason = '$failure'.replaceFirst(RegExp(r'\.$'), '');+ return SuperTabFailure('JOIN_FAILED', switch (failure) {+ SuperTabFailure(statusCode: >= 500) =>+ 'The $who started on $machineName and keeps running there, but the '+ 'Harness server had an error adding it to the project. Check '+ 'status to try again.',+ SuperTabFailure(statusCode: >= 400) when reason.isNotEmpty =>+ 'The $who started on $machineName and keeps running there, but the '+ 'project did not take it: $reason. Discard request, or Check '+ 'status once that changes.',+ _ =>+ 'The $who started on $machineName. Joining it to the project failed: '+ '$reason. Check status to try again.',+ });+ }Future<void> resume() async {checkAccount();diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex 8b0b15088..d1cc2258b 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -76,6 +76,9 @@ class SuperTabFixtureConnection extends WsConn {/// What starting the account's setup answers (`teamSetup`, `manual`).Map<String, dynamic> teamRun = {'state': 'started'};bool loseCreate = false, loseJoin = false;++ /// Refuses the next join as the backend would, before anything is written.+ SuperTabFailure? failJoin;bool failNative = false;WsRequestFailure? backendFailure;@@ -262,6 +265,10 @@ class SuperTabFixtureConnection extends WsConn {if (body?['command'] case final Map commandwhen command['type'] == 'agent.add') {joins.add(Map<String, dynamic>.from(body!));+ if (failJoin case final failure?) {+ failJoin = null;+ throw failure;+ }// As the backend: a deleted project's conversation is not found.if (!(server.state['conversations'] as List).cast<Map>().any((g) => g['id'] == command['conversationId'],@@ -414,6 +421,25 @@ class SuperTabFixtureConnection extends WsConn {}}+/// Gives the fixture Swarm's project chat a Product Manager, as a project that+/// has one: New Harness there then joins a worker (#2458).+void withCoordinator(SuperTabLaunchFixture f) {+ (f.connection.server.state['agents'] as List).add({+ 'id': 'pm',+ 'machineId': 'pm-host',+ 'harnessId': 'pm-harness',+ 'name': 'Lead',+ 'contributorId': 'owner',+ 'projectId': 'lead',+ 'configuration': {'engine': 'claude', 'model': 'opus', 'effort': 'high'},+ });+ final chat = (f.connection.server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((c) => c['id'] == 'lead');+ chat['leadId'] = 'pm';+ (chat['agentIds'] as List).add('pm');+}+class SuperTabLaunchFixture {SuperTabLaunchFixture({bool local = false,@@ -507,6 +533,7 @@ void main() {for (final engine in ['opencode', 'hermes']) {final f = SuperTabLaunchFixture();f.connection.extraEngines.add(engine);+ withCoordinator(f);f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');final box = await f.box(engine: engine);expect(@@ -538,6 +565,7 @@ void main() {engine,setup: LaunchSetup(engine: engine, permissionMode: 'ask'),);+ if (kind == 'member') withCoordinator(f);if (kind != 'new Swarm') {f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');}@@ -2399,6 +2427,7 @@ void main() {for (final engine in ['claude', 'codex']) {test('a Desktop $engine Swarm worker gets the DEV role', () async {final f = SuperTabLaunchFixture();+ withCoordinator(f);f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');final box = await f.box(engine: engine);expect(await box.create(), NewHarnessOutcome.created, reason: box.error);@@ -2418,6 +2447,7 @@ void main() {f.connection.server.state['projects'] = [{...projectFixture('lead', 'Company', 'lead'), 'skillMode': 'default'},];+ withCoordinator(f);f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');final box = await f.box();expect(await box.create(), NewHarnessOutcome.created, reason: box.error);@@ -2454,6 +2484,7 @@ void main() {'notesRevision': 0,'notes': <dynamic>[],};+ withCoordinator(f);f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');return f;}@@ -2645,6 +2676,98 @@ void main() {expect(box.integration!.swarmRole, 'lead');});+ // Tony, 11-03 (#2458): his Personal project had no Product Manager, and New+ // Harness in its chat joined a worker. River: a project with no coordinator+ // gets its PM from New Harness in its chat, the first message going to it.+ test('New Harness in a project chat with no coordinator starts its '+ 'Product Manager, keeping the project and Swarm names', () async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');+ final box = await f.box(engine: 'claude', task: 'Hi New PM Personal');+ expect(box.integration!.swarmRole, 'lead');+ expect(box.integration!.roleSuggestions, isNull);+ // The project and its visibility exist already.+ expect(box.integration!.projectVisibility, isNull);+ expect(box.integration!.actionLabel, 'New Harness');+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ final create = f.connection.calls+ .firstWhere((c) => c.$1 == 'agent_create')+ .$2;+ expect(create['swarmRole'], 'lead');+ final join = f.connection.joins.single['command'] as Map;+ expect(join['lead'], isTrue);+ expect(join['conversationId'], 'lead');+ expect(join['initialMessage'], 'Hi New PM Personal');+ expect(+ f.connection.server.posts.map((p) => (p['command'] as Map)['type']),+ isNot(anyOf(contains('project.rename'), contains('tab.rename'))),+ );+ });++ // Hollis's review of #2803: a PM start decided when the box opened, retried+ // after another PM joined, must not take the project from that one.+ test(+ 'a PM start retried after another PM joined leaves that one the PM',+ () async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');+ f.connection.failJoin = const SuperTabFailure(+ 'INTERNAL_ERROR',+ 'An internal server error occurred',+ statusCode: 500,+ );+ final box = await f.box(engine: 'claude', task: 'Hi New PM Personal');+ expect(box.integration!.swarmRole, 'lead');+ expect(await box.create(), NewHarnessOutcome.failed);+ // Meanwhile the project got its Product Manager.+ withCoordinator(f);+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(+ box.error,+ 'Another Product Manager joined this project while this one was '+ 'starting. This one keeps running on Test host: Discard request to '+ 'leave it out of the project.',+ );+ expect(f.connection.joins, hasLength(1));+ final chat = (f.connection.server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((c) => c['id'] == 'lead');+ expect(chat['leadId'], 'pm');+ expect(box.canDiscardPending, isTrue);+ },+ );++ test(+ 'a PM start retried while the project still has none joins as its PM',+ () async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');+ f.connection.failJoin = const SuperTabFailure(+ 'INTERNAL_ERROR',+ 'An internal server error occurred',+ statusCode: 500,+ );+ final box = await f.box(engine: 'claude', task: 'Hi New PM Personal');+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ expect(f.connection.joins, hasLength(2));+ expect((f.connection.joins.last['command'] as Map)['lead'], isTrue);+ },+ );++ test(+ 'New Harness in a project chat with a coordinator joins a worker',+ () async {+ final f = SuperTabLaunchFixture();+ withCoordinator(f);+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');+ final box = await f.box(engine: 'claude');+ expect(box.integration!.swarmRole, 'dev');+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ expect((f.connection.joins.single['command'] as Map)['lead'], isFalse);+ },+ );+test('account switch during role lookup closes the old launch', () async {final f = SuperTabLaunchFixture()..connection.changeAccountOnProjectRead = true;@@ -2698,6 +2821,7 @@ void main() {);expect(inherited.engine, isIn(['claude', 'codex']));+ withCoordinator(f);f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');final member = NewHarnessController(f.app,diff --git a/desktop/test/swarm_join_error_shots_test.dart b/desktop/test/swarm_join_error_shots_test.dartnew file mode 100644index 000000000..c05ce8c06--- /dev/null+++ b/desktop/test/swarm_join_error_shots_test.dart@@ -0,0 +1,104 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/new_harness.dart';+import 'package:harness/widgets/new_harness_form.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'swarm_launch_recovery_test.dart' show reopen, stuckProject;++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SWARM_JOIN_ERROR_SHOTS'];++/// Tony, 11-03 (#2458): a join that failed said only "An internal server+/// error occurred". The New Harness box now says what happened and what to do,+/// for a server error and for a refusal with its reason.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ const cases = {+ 'server-error': (+ code: 'INTERNAL_ERROR',+ message: 'An internal server error occurred',+ status: 500,+ shows: 'the Harness server had an error adding it to the project',+ ),+ 'refused': (+ code: 'TEAM_ACCOUNT_HELD',+ message:+ 'This machine\'s Harness Team account runs another project\'s '+ 'Product Manager, so it takes only that project\'s work for now.',+ status: 403,+ shows: 'but the project did not take it: This machine\'s Harness Team',+ ),+ };++ for (final brightness in Brightness.values) {+ for (final MapEntry(key: name, value: refusal) in cases.entries) {+ testWidgets('the New Harness box after a $name join '+ '(${brightness.name})', (tester) async {+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ final picture = GlobalKey();+ late NewHarnessController box;+ await tester.runAsync(() async {+ final f = await stuckProject();+ box = await reopen(f);+ f.connection.server+ ..refuse = {'code': refusal.code, 'message': refusal.message}+ ..refuseStatus = refusal.status;+ expect(await box.create(), NewHarnessOutcome.failed);+ });+ await tester.binding.setSurfaceSize(const Size(900, 560));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 850,+ height: 520,+ child: NewHarnessForm(+ controller: box,+ desktop: true,+ onClose: () {},+ onCreated: () {},+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(find.textContaining(refusal.shows), findsOneWidget);+ expect(find.text('Discard request'), findsOneWidget);+ expect(find.text('Check status'), findsOneWidget);+ if (shots != null) {+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(+ format: ui.ImageByteFormat.png,+ );+ await Directory(shots!).create(recursive: true);+ await File('$shots/join-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }+ await tester.pumpWidget(const SizedBox());+ });+ }+ }+}diff --git a/desktop/test/swarm_launch_recovery_test.dart b/desktop/test/swarm_launch_recovery_test.dartindex a349566fa..2ccaa1281 100644--- a/desktop/test/swarm_launch_recovery_test.dart+++ b/desktop/test/swarm_launch_recovery_test.dart@@ -7,7 +7,8 @@ import 'package:harness/state/new_harness.dart';import 'package:harness/super_tabs/launch.dart';import 'package:harness/widgets/new_harness_form.dart';-import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'super_tab_launch_test.dart'+ show SuperTabLaunchFixture, tabId, withCoordinator;Map<String, dynamic>? journal(SuperTabLaunchFixture f) => f.store.values.entries.where((e) => e.key.startsWith('super_tab.launch.'))@@ -88,7 +89,9 @@ void main() {);await tester.pump();expect(- find.text('Waiting for Test host to start the Lead for “New project”.'),+ find.text(+ 'Waiting for Test host to start the Product Manager for “New project”.',+ ),findsOneWidget,);await tester.tap(find.text('Discard request'));@@ -135,7 +138,7 @@ void main() {expect(box.discarded, isFalse);expect(box.error,- 'The Lead started on Test host. Check status to add it to the project.',+ 'The Product Manager started on Test host. Check status to add it to the project.',);expect(journal(f)!['phase'], 'starting');expect(await box.create(), NewHarnessOutcome.created, reason: box.error);@@ -145,20 +148,24 @@ void main() {test('Discard after a failed join leaves the Lead running', () async {final f = await stuckProject();final box = await reopen(f);- f.connection.server.refuse = {- 'code': 'INTERNAL',- 'message': 'An internal server error occurred',- };+ // The backend's answer to an error of its own (errorHandler.ts).+ f.connection.server+ ..refuse = {+ 'code': 'INTERNAL_ERROR',+ 'message': 'An internal server error occurred',+ }+ ..refuseStatus = 500;expect(await box.create(), NewHarnessOutcome.failed);+ // It says what failed and what to do, not the server's bare words (#2458).expect(box.error,- 'The Lead started on Test host. Joining it to the project failed: '- 'An internal server error occurred. Check status to try again.',+ 'The Product Manager started on Test host and keeps running there, but the Harness '+ 'server had an error adding it to the project. Check status to try again.',);expect(journal(f)!['phase'], 'joining');expect(await box.discardPending(),- 'The Lead keeps running on Test host. Remove this request?',+ 'The Product Manager keeps running on Test host. Remove this request?',);expect(journal(f), isNotNull);final projectId = journal(f)!['projectId'];@@ -176,6 +183,33 @@ void main() {);});+ test('a refused join says why, and that the Lead keeps running', () async {+ final f = await stuckProject();+ final box = await reopen(f);+ f.connection.server+ ..refuse = {+ 'code': 'TEAM_ACCOUNT_HELD',+ 'message':+ 'This machine\'s Harness Team account runs another project\'s '+ 'Product Manager, so it takes only that project\'s work for now.',+ }+ ..refuseStatus = 403;+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(+ box.error,+ 'The Product Manager started on Test host and keeps running there, but the project '+ 'did not take it: This machine\'s Harness Team account runs another '+ 'project\'s Product Manager, so it takes only that project\'s work for '+ 'now. Discard request, or Check status once that changes.',+ );+ expect(journal(f)!['phase'], 'joining');+ expect(box.canDiscardPending, isTrue);+ // Once the server takes it, Check status joins the same harness.+ f.connection.server.refuse = null;+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ expect(journal(f), isNull);+ });+test('a failed creation gives the form back without Discard', () async {final f = await stuckProject();final box = await reopen(f);@@ -202,7 +236,7 @@ void main() {throw StateError('Connection lost');expect(await box.discardPending(),- 'Could not reach Test host, so it may still start the Lead. Discard anyway?',+ 'Could not reach Test host, so it may still start the Product Manager. Discard anyway?',);expect(journal(f), isNotNull);expect(await box.discardPending(anyway: true), isNull);@@ -243,7 +277,7 @@ void main() {);await tester.pump();const question =- 'Could not reach Test host, so it may still start the Lead. '+ 'Could not reach Test host, so it may still start the Product Manager. ''Discard anyway?';await tester.tap(find.text('Discard request'));@@ -360,6 +394,7 @@ void main() {() async {// A new Lead cannot choose a terminal at all; an agent joining it can.final f = SuperTabLaunchFixture();+ withCoordinator(f);f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');final box = await f.box(engine: 'terminal');expect(await box.create(), NewHarnessOutcome.failed);diff --git a/docs/plans/2026-11-03-personal-project-join-500-plan.md b/docs/plans/2026-11-03-personal-project-join-500-plan.mdnew file mode 100644index 000000000..59ad05ec9--- /dev/null+++ b/docs/plans/2026-11-03-personal-project-join-500-plan.md@@ -0,0 +1,104 @@+# Personal Project Join 500 Implementation Plan++> Way of working: this project's Engineer role (test first, each failing test committed before its code, one pull+> request, one independent review step). No execution handoff.++**Goal:** A harness started with a first message from a project chat joins the project instead of failing with an+internal server error; in a project with no coordinator it becomes the project's Product Manager; and a join that is+still refused tells the person why and what to do.++**Architecture:** `agent.add` (backend/src/superTabs/commands.ts) records two rows in the project chat in one command:+the system row naming who added the harness (or a Product Manager's launch-refused note) and the person's first+message. Both took the command's operation id, so the command's duplicate-id guard threw a plain `Error` and the route+answered 500. The system rows get ids derived from the operation id; the first message keeps it. Desktop's join failure+(desktop/lib/super_tabs/launch.dart `_joinFailed`) names a server error or a refusal separately, each with its next step.++**Tech Stack:** TypeScript, Fastify, Prisma on MongoDB, Vitest (Super Tab integration suite); Flutter/Dart (Desktop).++**Spec:** Task #2458 (Tony, 2026-11-03). Root cause, confirmed by replaying Desktop's join command against Tony's+production Swarm state, read-only: his Personal project (`lead`) had no coordinator, so New Harness joined it as a+worker (`lead` absent) with "Hi New PM Personal"; "tony added … to the project" and the message shared one id.+Without the first message the same join succeeds. Pike's #2700 (task #2296) fixes the same collision; the id lines+here match its lines so the two merge cleanly.++## Global Constraints++- PR body first line: "Requested by [email protected] through Harness."+- Backend change: the full Super Tab integration suite (`npx vitest run -c vitest.super-tabs.config.ts`) passes before+ Ready; take the team suite lock when others run suites on this Mac.+- Desktop copy follows docs/naming-system.md; design-system roles only (`python3 scripts/check-ui-style.py`).+- Desktop tests use a memory store and a fake sign-in; nothing signs the Mac out of the real CLI.+- Swarm code stays out of cli/src/core.++## Review Focus++- A first message from the project chat (worker join): both rows stored, distinct ids, the message keeps the+ operation id (its receipt), HTTP 200.+- A Product Manager's join with a first message and a launch-refused note: both rows stored, HTTP 200.+- Replaying the same operation id returns the same result and writes nothing twice.+- Desktop, server error (HTTP 5xx): says the Harness server failed, the harness keeps running, Check status retries.+- Desktop, refusal (HTTP 4xx with a reason): shows the reason, the harness keeps running, Discard request or Check status.+- Desktop, a project chat with no coordinator: New Harness starts the PM (lead, PM prompt) and leaves the project's and+ the Swarm's names and visibility alone; a project chat with a coordinator still joins a worker.++## Tasks++### Task 1: The join with a first message answers 200 (backend)++**Files:**+- Test: `backend/integration/superTabs.test.ts`+- Modify: `backend/src/superTabs/commands.ts`++**Interfaces:**+- Consumes: `POST /api/super-tabs/:id/commands` with `agent.add` (`initialMessage`, `lead`, `launchRefused`).+- Produces: `message()` takes an optional id; the shared-to-project row uses `stableId(operationId, 'shared-to-project')`+ and the launch-refused row `stableId(operationId, 'launch-refused')`.++- [ ] Integration test through the route: a Swarm whose project chat has a coordinator; a second harness joins the+ project chat with a first message (no `lead`). Expect 200, the first message under the operation id, the system row+ under another id, and a replay of the operation id answering the same.+- [ ] Same file: a Product Manager join with `initialMessage` and `launchRefused` into a project chat with no+ coordinator. Expect 200 and both rows.+- [ ] Run both: they fail with 500 on main. Commit the failing tests.+- [ ] Give `message()` an optional id and the two system rows their derived ids. Run both: 200. Commit.++### Task 2: Desktop says why a join failed and what to do++**Files:**+- Test: `desktop/test/swarm_launch_recovery_test.dart`+- Modify: `desktop/lib/super_tabs/launch.dart`++**Interfaces:**+- Consumes: `SuperTabFailure.statusCode` and `message` from the join's command post.+- Produces: `_joinFailed` copy:+ - 5xx: "The {who} started on {machine} and keeps running there, but the Harness server had an error adding it to the+ project. Check status to try again."+ - 4xx with a reason: "The {who} started on {machine} and keeps running there, but the project did not take it:+ {reason}. Discard request, or Check status once that changes."+ - Anything else (no answer): today's copy.++- [ ] Tests: a 500 join shows the server-error copy; a 403 with a reason shows the refusal copy; Discard and Check status+ still work as before. Run: they fail on today's copy. Commit the failing tests.+- [ ] Change `_joinFailed`. Run the recovery tests and the style check. Commit.+- [ ] Screenshot of both messages in the New Harness box (in-memory render), light and dark, for the PR.++### Task 3: New Harness in a project with no coordinator starts its Product Manager (Desktop)++River, 2026-11-03: "a project with no coordinator gets its PM from New Harness in its chat, and that person's first+message goes to the PM."++**Files:**+- Test: `desktop/test/super_tab_launch_test.dart`+- Modify: `desktop/lib/super_tabs/launch.dart`++**Interfaces:**+- Consumes: `SuperTabSnapshot.projectFor`, `leadOf` (no coordinator: null).+- Produces: a launch journal with `lead: true` and `coordinator: true` for an existing project chat with no coordinator;+ `agent.add` with `lead: true`; no `project.rename`, `tab.rename` or rebinding of the Swarm's name; no visibility field.++- [ ] Tests: New Harness in a project chat with no coordinator sends `swarmRole: lead` and joins with `lead: true`, the+ first message in that join, and posts no rename; with a coordinator it stays a worker (existing tests get a+ coordinator in their fixture). Run: they fail. Commit the failing tests.+- [ ] `SuperTabLaunch.open` reads the snapshot for a new journal in an existing Swarm and marks the coordinator start;+ `complete` skips the renames and rebinding for it; the visibility field is for new Swarms and projects only.+ Run the launch and recovery tests. Commit.