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-05 i1415: #3074 #3105 (#3116)

0xken15cc51da67d660
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index fa46cba45..23a31996c 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -18,6 +18,7 @@ import { recordCheckVerdict } from './checkVerdicts.js'
import { routeRecordSchema, routeTitle, startedAs, type KeptCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSaveSchema } from './routingPolicy.js'
import { askedInSchema, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema } from './rules.js'
+import { accessRefusal, changeAccess, expireAccess, taskAccess } from './machineAccess.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
import { agentsNamedIn, checkMentions, MAX_MENTIONS, namedIn, saysName, textTags, withTags, type MentionTarget } from './mentions.js'
import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'
@@ -143,12 +144,17 @@ const check = z.object({ description: z.string().trim().min(1).max(1000), indepe
/** A task's checks as stored, none passed; `independent` false when a newer client leaves it out, as older readers expect it. */
const storedChecks = (checks: ReadonlyArray<z.infer<typeof check>>, operationId: string): Check[] =>
checks.map((c, i) => ({ description: c.description, independent: c.independent ?? false, id: stableId(operationId, String(i)), evidence: null, passedBy: null }))
+/** An access entry's name and its note or check (machineAccess.ts). */
+const accessName = z.string().trim().min(1).max(60).regex(/^[^\n\r\t]+$/)
+const accessText = z.string().trim().min(1).max(200).regex(/^[^\n\r\t]+$/)
+
const task = z.object({
goal: z.string().trim().min(1).max(8000), changes: z.string().trim().min(1).max(8000),
constraints: z.string().trim().min(1).max(8000), owns: z.array(z.string().trim().min(1).max(4096)).min(1).max(40),
/** model.ts TaskRequirement; `unseenMachines` is only ever read back, never set. */
- requires: z.object({ machines: z.array(id).min(1).max(20).optional(), devices: z.array(path).min(1).max(20).optional() }).strict()
- .refine(r => r.machines || r.devices, 'Require at least one machine or device.').optional(),
+ requires: z.object({ machines: z.array(id).min(1).max(20).optional(), devices: z.array(path).min(1).max(20).optional(),
+ access: z.array(accessName).min(1).max(20).optional() }).strict()
+ .refine(r => r.machines || r.devices || r.access, 'Require at least one machine, device or access.').optional(),
/** model.ts ReviewPlan: what its reviews check first, and 2 for two independent reviews, said in its brief (#2382). */
review: z.object({ focus: z.string().trim().min(1).max(2000).optional(), reviews: z.union([z.literal(1), z.literal(2)]).optional() }).strict()
.refine(r => r.focus !== undefined || r.reviews !== undefined, 'Give the review a focus or a number of reviews.').optional(),
@@ -170,6 +176,12 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('machine.projects'), machineId: id, projectIds: z.array(id).min(1).max(64).nullable(), askedIn: askedInSchema.optional() }).strict(),
// Whether teammates' work may also run in the owner's own account on their machine (Scholes, 11-04): its owner's choice.
z.object({ type: z.literal('machine.ownAccountWork'), machineId: id, allowed: z.boolean(), askedIn: askedInSchema.optional() }).strict(),
+ // One entry of what a machine can reach (machineAccess.ts, task #3047): one at a time, so its owner and a Lead never
+ // overwrite each other's list.
+ z.object({ type: z.literal('machine.access'), machineId: id, action: z.enum(['add', 'change', 'confirm', 'remove']),
+ entryId: z.string().regex(/^[0-9a-f]{16}$/).optional(), name: accessName.optional(), account: z.enum(['own', 'team']).optional(),
+ teammates: z.boolean().optional(), production: z.boolean().optional(), note: accessText.nullable().optional(), check: accessText.nullable().optional(),
+ askedIn: askedInSchema.optional() }).strict(),
z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),
z.object({ type: z.literal('machine.cleaned'), machineId: id, removalId: id }).strict(),
z.object({ type: z.literal('localModels.set'), enabled: z.boolean() }).strict(),
@@ -703,7 +715,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if ('agentId' in command) readAgent(state, actor, command.agentId)
if (command.type === 'agent.start') readConversation(state, actor, command.request.conversationId)
if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
- || command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork') && command.askedIn) {
+ || command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork'
+ || command.type === 'machine.access') && command.askedIn) {
readConversation(state, actor, command.askedIn.conversationId)
}
if ('startId' in command && command.type !== 'route.modelResult') {
@@ -858,6 +871,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
numberConversations(state)
placeRules(state)
expireRemovals(state, context.now)
+ expireAccess(state, context.now)
const deleted = new Set(context.deletedMachineIds ?? [])
if (deleted.size && state.machineCleanups) {
state.machineCleanups = state.machineCleanups.filter(c => !deleted.has(c.machineId))
@@ -1196,13 +1210,15 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A new agent never starts on a Buddy-only machine; an agent its person added there runs as one on a machine outside the Swarm.
if (!member && state.machines?.some(m => m.machineId === candidate.machineId && m.buddyOnly)) return { code: 'NOT_SWARM_MACHINE' as const, reason: NOT_SWARM_MACHINE }
// A new agent on a Mac for a teammate's project runs in the Mac's Harness Team account (machines.ts teamStartRequest).
- const group = conversation(state, conversationId), written = teamWrittenTask(state, group)
- const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle, context.teamMachines, written)
+ const group = conversation(state, conversationId), written = teamWrittenTask(state, group), needed = taskAccess(group)
+ const machineId = member?.machineId ?? teamMachineFor(state, candidate.machineId, project, context.teamAccountsIdle, context.teamMachines, written, needed)
// Team-written code takes a Team account only (audit H2). Its own check below says nothing for the owner's own account.
if (written && !(member ? onTeamAccount(state, member) : teamAccountPool(state.machines?.find(m => m.machineId === machineId)))
&& !(member && ledProject(state, member.id)?.id === project.id)) return { code: 'TEAM_WRITTEN_WORK' as const, reason: TEAM_WRITTEN_REASON }
const contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === machineId)?.contributorId ?? starter
- return teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines, context.otherWorkspaceMachines)
+ // Then what the task needs to reach, in the account it would run in (machineAccess.ts, task #3047).
+ return teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines, context.otherWorkspaceMachines, needed)
+ ?? accessRefusal(state, machineId, project, needed)
}
/**
* Routes a `message.send` in Buddy chat [chat] (buddySessions.ts): whether it is in a session thread (`inSession`, its reply
@@ -1931,6 +1947,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// So is their choice of their own account for teammates' work (machine.ownAccountWork), Desktop's join re-save
// included; not over a removal, so a Mac removed and added again starts Team-account-only.
const ownAccountChoice = state.machines.find(m => m.machineId === command.machineId && !m.buddyOnly && !m.removal)?.ownAccountChoice
+ // And what it can reach (machine.access), the same way: a Mac removed and added again starts with none.
+ const access = state.machines.find(m => m.machineId === command.machineId && !m.buddyOnly && !m.removal)?.access
// Its Agents setting: a client that does not send one (older than #2860) keeps the stored one while the count is the same.
const previous = state.machines.find(m => m.machineId === command.machineId && !m.buddyOnly)
const agents = command.agents ?? (previous?.agents && previous.maxAgents === command.maxAgents ? previous.agents : undefined)
@@ -1943,7 +1961,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...(command.scope ? { scope: command.scope } : {}),
contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused,
...(host ? { hostMachineId: host } : {}), ...(teamAccountOnly ? { teamAccountOnly: true as const } : {}), ...(projects && !host ? { projects } : {}),
- ...(ownAccountChoice && !host ? { ownAccountChoice } : {}),
+ ...(ownAccountChoice && !host ? { ownAccountChoice } : {}), ...(access && !host ? { access } : {}),
...(othersToldWeek != null ? { othersToldWeek } : {}),
// What its readings and starts recorded is not a setting: saving the settings keeps the Lent ledger, the engines'
// failures and suspensions and the last reading (#3043). A machine not listed yet, or Buddy-only, starts clean.
@@ -2015,6 +2033,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...(actor.kind === 'agent' && command.askedIn ? { askedIn: { conversationId: command.askedIn.conversationId, messageId: command.askedIn.messageId } } : {}) }
break
}
+ case 'machine.access': {
+ result.entryId = changeAccess(state, actor, command, context, machineOwnerWord, operationId)
+ break
+ }
case 'machine.remove': {
// Its owner takes the machine out with every Swarm agent on it, each removed like one agent (its host closes the
// session; a Product Manager refuses it, protectLead). A contributed machine then stays listed, paused, while its
@@ -2425,7 +2447,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const startGroup = conversation(state, command.request.conversationId)
marking(startGroup, () => applyPushOrigin(state, startGroup, context.pushOrigin))
const written = teamWrittenTask(state, startGroup)
- const moved = teamStartRequest(state, named, home, context.teamAccountsIdle, context.teamMachines, written)
+ const moved = teamStartRequest(state, named, home, context.teamAccountsIdle, context.teamMachines, written, taskAccess(startGroup))
// Moved to the Mac's Team account: the starter is told why in one line (task #2806).
if (moved.machineId !== named.machineId) {
const mac = state.machines?.find(m => m.machineId === named.machineId)
@@ -2438,6 +2460,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const pool = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)
// Off the Machines list, a teammate's project never runs: nothing there shows a privacy check (machines.ts).
if (!pool) requireTeamWork(state, request.machineId, grant.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
+ // Nor one that needs access: a machine off the list lists nothing it can reach (machineAccess.ts).
+ const unlisted = pool ? null : accessRefusal(state, request.machineId, home, taskAccess(startGroup))
+ if (unlisted) failTeamWork(unlisted)
state.starts.push({ ...(pool ? { poolGeneration: pool.generation } : {}), ...(command.routeDecisionId ? { routeDecisionId: command.routeDecisionId } : {}), id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),
contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,
hostGrant: grant.hostGrant ?? null, request, harnessId: null, dispatched: false, error: null, requestedAt: context.now })
@@ -3488,7 +3513,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
sameProject(state, group, worker)
const home = groupProject(state, group)
// A teammate's agent on a personal machine keeps what it has; it takes no new task for another person's project.
- requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines)
+ requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines, taskAccess(group))
+ // And what the task needs to reach, where it runs (machineAccess.ts): an assignment is held to it as a start is.
+ const unreached = accessRefusal(state, worker.machineId, home, taskAccess(group))
+ if (unreached) failTeamWork(unreached)
// Team-written code runs only in a Team account, and a Team agent's work marks the task (teamWritten.ts, audit H2).
pushedRefusal(group, worker)
requireTeamWrittenAccount(state, group, worker)
diff --git a/backend/src/superTabs/machineAccess.test.ts b/backend/src/superTabs/machineAccess.test.ts
new file mode 100644
index 000000000..7f24a1a78
--- /dev/null
+++ b/backend/src/superTabs/machineAccess.test.ts
@@ -0,0 +1,449 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { type ContributedMachine, type MachinePrivacy } from './machines.js'
+import { createSuperTab, SuperTabError, visibleState, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
+
+// Task #3047, phase 1 of docs/design/2026-11-05-machine-access.md: what each machine can reach. Each risk the design's
+// section 7 names for phase 1 has a test here. Team accounts are required everywhere, the strictest setting.
+beforeEach(() => { process.env.SWARM_TEAM_ACCOUNT_REQUIRED = '1' })
+afterEach(() => { delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED })
+
+const NOW = 50_000_000_000
+const DAY = 24 * 60 * 60_000
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const gray: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'gray', email: '[email protected]' }
+const mate: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'mate', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }
+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,
+ deviceType: null, chip: null, os: null, gpuPercent: null }
+const PASSED: MachinePrivacy = { mode: 'account', passed: true, checkedAt: NOW - 60_000 }
+type Reading = NonNullable<ContributedMachine['observation']>
+const reading = (sessionKind: 'team' | 'computer', privacy?: MachinePrivacy): Reading => ({ generation: 'g1', receivedAt: NOW, sessionKind, resources,
+ tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [], ...(privacy ? { privacy: { ...privacy, seenAt: NOW } } : {}) })
+const refusal = (body: () => unknown): SuperTabError | null => {
+ try { body(); return null } catch (error) { if (error instanceof SuperTabError) return error; throw error }
+}
+/** What the store loads for a command's askedIn (store.ts): who wrote the message, whether it is a system row, and when. */
+const said = (id: string, createdAt = NOW - 1000) => ({ askedIn: { author: { kind: 'person', id } as never, source: false, createdAt } })
+
+/** The owner's Swarm with two teammates. Gray's Mac was added as Gray joined (teamAccountOnly), with its Harness Team
+ * account, whose privacy check passed. The owner's Mac has no Team account. Projects: the owner's 'lead', and Gray's own. */
+function swarm() {
+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = gray, context: Partial<CommandContext> = {}) => {
+ const teamMachines = (state.machines ?? []).filter(m => m.observation?.sessionKind === 'team').map(m => m.machineId)
+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, teamMachines, ...context })
+ state = effects.state
+ return effects
+ }
+ for (const person of [gray, mate]) {
+ const invited = run({ type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' }, owner)
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, person)
+ }
+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation
+ const joined = { contribution: { machineOwnerId: 'gray', contributorId: 'gray', hostGrant: null } }
+ run({ type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4,
+ teamAccountOnly: true }, gray, joined)
+ state.machines!.find(m => m.machineId === 'gray-mac')!.observation = reading('computer')
+ state.machines!.push({ machineId: 'gray-team', name: 'Gray\'s Mac', contributorId: 'gray', membershipGeneration: generation('gray'), generation: 'g1',
+ cwd: '/team-swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4, paused: false, hostMachineId: 'gray-mac', observation: reading('team', PASSED) })
+ state.machines!.push({ machineId: 'owner-mac', name: 'Owner Mac', contributorId: 'owner', membershipGeneration: generation('owner'), generation: 'g1',
+ cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4, paused: false, observation: reading('computer') })
+ const grays = String(run({ type: 'project.create', name: 'Gray\'s', visibility: 'public', brief: '' }, gray).result.projectId)
+ // The project's Lead (the PM), on the owner's Mac.
+ const leadId = String(run({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: 'lead', name: 'Lead', configuration: config, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId)
+ const leadActor: Actor = { kind: 'agent', agentId: leadId, machineOwnerId: 'owner' }
+ const machine = (machineId: string) => state.machines!.find(m => m.machineId === machineId)!
+ const access = (body: Record<string, unknown>, actor: Actor = gray, context: Partial<CommandContext> = {}, machineId = 'gray-mac') =>
+ run({ type: 'machine.access', machineId, ...body } as Command, actor, context)
+ const add = (name: string, extra: Record<string, unknown> = {}, actor: Actor = gray, context: Partial<CommandContext> = {}) =>
+ String(access({ action: 'add', name, ...extra }, actor, context).result.entryId)
+ const entry = (name: string) => machine('gray-mac').access?.find(e => e.name === name)
+ /** An agent of the Swarm on [machineId], by Gray's grant there. */
+ const agent = (id: string, machineId = 'gray-mac', extra: Record<string, unknown> = {}): Actor => {
+ state.agents.push({ id, machineId, harnessId: `harness-${id}`, projectId: 'lead', machineOwnerId: 'gray', contributorId: 'gray',
+ membershipGeneration: generation('gray'), hostGrant: null, name: id, configuration: config, ...extra })
+ return { kind: 'agent', agentId: id, machineOwnerId: 'gray' }
+ }
+ const group = (projectId = 'lead', actor: Actor = owner, requires?: Record<string, unknown>) => String(run({ type: 'conversation.create', projectId, title: 'Work',
+ ...(requires ? { task: { goal: 'Test on a lamp.', changes: 'Firmware.', constraints: 'None.', owns: ['fw'], requires } } : { brief: 'Build it.' }),
+ checks: [] } as Command, actor).result.conversationId)
+ const start = (conversationId: string, actor: Actor = owner, projectId = 'lead') =>
+ run({ type: 'agent.start', request: { conversationId, machineId: 'gray-mac', engine: 'codex', name: 'Builder', cwd: `/swarm/${projectId}`, worktree: true,
+ requirements } }, actor, joined)
+ return { run, machine, access, add, entry, agent, group, start, joined, grays, leadActor, generation, get state() { return state }, set state(s) { state = s } }
+}
+
+describe('the access list and machine.access', () => {
+ it('takes an entry from the machine\'s owner, ok at once, with who added it and when', () => {
+ const f = swarm()
+ const id = f.add('Fusion 360')
+ expect(id).toMatch(/^[0-9a-f]{16}$/)
+ expect(f.entry('Fusion 360')).toEqual({ id, name: 'Fusion 360', account: 'own', state: 'ok', addedBy: 'gray', addedAt: new Date(NOW).toISOString() })
+ f.add('Lamp', { account: 'team', production: true, note: 'connection info in ~/.lamp/config', check: 'lamp-mcp' })
+ expect(f.entry('Lamp')).toMatchObject({ account: 'team', production: true, note: 'connection info in ~/.lamp/config', check: 'lamp-mcp' })
+ })
+
+ it('holds at most 32 entries, and one name once per account, whatever its case', () => {
+ const f = swarm()
+ for (let i = 0; i < 32; i++) f.add(`Thing ${i}`)
+ expect(refusal(() => f.add('One more'))?.code).toBe('ACCESS_FULL')
+ const g = swarm()
+ g.add('Lamp')
+ expect(refusal(() => g.add(' lamp '))?.code).toBe('ACCESS_EXISTS')
+ // The same name in the other account is another entry.
+ g.add('Lamp', { account: 'team' })
+ expect(g.machine('gray-mac').access).toHaveLength(2)
+ })
+
+ it('keeps a Team account\'s entries on its Mac, and none on a Mac without a Team account', () => {
+ const f = swarm()
+ expect(refusal(() => f.access({ action: 'add', name: 'Lamp' }, gray, {}, 'gray-team'))?.code).toBe('NOT_FOUND')
+ expect(refusal(() => f.access({ action: 'add', name: 'Lamp', account: 'team' }, owner, {}, 'owner-mac'))?.code).toBe('NO_TEAM_ACCOUNT')
+ expect(f.machine('gray-team').access).toBeUndefined()
+ })
+
+ it('refuses a name or note that looks like a secret, and takes where the secret lives', () => {
+ const f = swarm()
+ for (const secret of ['ghp_Xk9mQ2vL7pR4tY8wZ3nB6cF1hJ5dS0aE2gK', 'sk-ant-api03-Xk9mQ2vL7pR4tY8wZ3nB6cF1', 'admin:[email protected]',
+ '-----BEGIN OPENSSH PRIVATE KEY-----', 'AKIAIOSFODNN7EXAMPLE', 'key Xk9mQ2vL7pR4tY8wZ3nB6c here', 'xoxb-1234-5678-abcdef']) {
+ expect(refusal(() => f.add(secret))?.code, secret).toBe('ACCESS_SECRET')
+ expect(refusal(() => f.add('Prod DB', { note: secret }))?.code, secret).toBe('ACCESS_SECRET')
+ }
+ expect(f.machine('gray-mac').access ?? []).toEqual([])
+ f.add('Email (dee@)', { note: 'connection info in ~/.argocd/config' })
+ f.add('Prod DB read-only', { note: 'env file /Users/gray/Library/Application Support/harness/prod-read.env' })
+ expect(f.machine('gray-mac').access).toHaveLength(2)
+ })
+
+ it('is changed by nobody else: not the Swarm\'s owner, a teammate, an agent on its own word, or a Buddy', () => {
+ const f = swarm()
+ const worker = f.agent('gray-worker')
+ const buddy = f.agent('gray-buddy', 'gray-mac', { buddyOf: 'gray', buddyScope: 'swarm' })
+ for (const actor of [owner, mate, worker, f.leadActor, buddy]) {
+ expect(['OWNER_REQUIRED', 'BUDDY_FORBIDDEN'], JSON.stringify(actor)).toContain(refusal(() => f.add('Lamp', {}, actor))?.code)
+ }
+ expect(f.machine('gray-mac').access).toBeUndefined()
+ })
+
+ it('takes the Lead passing on the owner\'s own message from the last day, in a chat it leads, as ok', () => {
+ const f = swarm()
+ const askedIn = { conversationId: 'lead', messageId: 'm-gray' }
+ f.add('ArgoCD', { note: 'connection info in ~/.argocd/config', askedIn }, f.leadActor, said('gray'))
+ expect(f.entry('ArgoCD')).toMatchObject({ state: 'ok', addedBy: 'gray', askedIn })
+ })
+
+ it('keeps what anyone else said, an old message or one from a chat it does not lead, unconfirmed', () => {
+ const askedIn = { conversationId: 'lead', messageId: 'm-1' }
+ for (const [context, saidBy] of [[said('owner'), 'owner'], [said('gray', NOW - 2 * DAY), 'gray']] as const) {
+ const f = swarm()
+ f.add('Email', { askedIn }, f.leadActor, context)
+ expect(f.entry('Email')).toMatchObject({ state: 'unconfirmed', saidBy, askedIn, addedBy: saidBy })
+ }
+ // A chat it does not lead: Gray's own message in a task's chat.
+ const f = swarm()
+ const task = f.group()
+ // Its chat names another Lead.
+ f.state.conversations.find(c => c.id === task)!.leadId = 'someone-else'
+ f.add('Email', { askedIn: { conversationId: task, messageId: 'm-2' } }, f.leadActor, said('gray'))
+ expect(f.entry('Email')).toMatchObject({ state: 'unconfirmed', saidBy: 'gray' })
+ // Only a Lead records what people say: any other agent passing on even the owner's message is refused.
+ expect(refusal(() => f.add('Slack', { askedIn }, f.agent('gray-worker'), said('gray')))?.code).toBe('OWNER_REQUIRED')
+ // With no message behind it, or a system row, an agent records nothing.
+ expect(refusal(() => f.add('Slack', {}, f.leadActor))?.code).toBe('OWNER_REQUIRED')
+ expect(refusal(() => f.add('Slack', { askedIn }, f.leadActor, { askedIn: { author: { kind: 'person', id: 'gray' } as never, source: true, createdAt: NOW } }))?.code)
+ .toBe('OWNER_REQUIRED')
+ })
+
+ it('lets only the owner\'s own session share an entry with teammates; the Lead may only stop sharing', () => {
+ const f = swarm()
+ const askedIn = { conversationId: 'lead', messageId: 'm-gray' }
+ expect(refusal(() => f.add('Fusion 360', { teammates: true, askedIn }, f.leadActor, said('gray')))?.code).toBe('OWNER_SESSION_REQUIRED')
+ const id = f.add('Fusion 360')
+ expect(refusal(() => f.access({ action: 'change', entryId: id, teammates: true, askedIn }, f.leadActor, said('gray')))?.code).toBe('OWNER_SESSION_REQUIRED')
+ expect(f.entry('Fusion 360')!.teammates).toBeUndefined()
+ f.access({ action: 'change', entryId: id, teammates: true })
+ expect(f.entry('Fusion 360')!.teammates).toBe(true)
+ f.access({ action: 'change', entryId: id, teammates: false, askedIn }, f.leadActor, said('gray'))
+ expect(f.entry('Fusion 360')!.teammates).toBeUndefined()
+ // Never on a Team account's entry: it always runs teammates' work.
+ const team = f.add('Lamp', { account: 'team' })
+ expect(refusal(() => f.access({ action: 'change', entryId: team, teammates: true }))?.code).toBe('TEAM_ACCOUNT_ENTRY')
+ })
+
+ it('lets only the owner\'s own session rename a shared entry, so sharing never moves to another name (security review 1)', () => {
+ const f = swarm()
+ const askedIn = { conversationId: 'lead', messageId: 'm-gray' }
+ const id = f.add('Lamp')
+ f.access({ action: 'change', entryId: id, teammates: true })
+ expect(refusal(() => f.access({ action: 'change', entryId: id, name: 'Email (dee@)', askedIn }, f.leadActor, said('gray')))?.code).toBe('OWNER_SESSION_REQUIRED')
+ expect(f.entry('Lamp')).toMatchObject({ teammates: true })
+ expect(f.entry('Email (dee@)')).toBeUndefined()
+ // An entry nobody shared is renamed on the owner's word, as before; the owner renames a shared one themselves.
+ const other = f.add('Fusion')
+ f.access({ action: 'change', entryId: other, name: 'Fusion 360', askedIn }, f.leadActor, said('gray'))
+ expect(f.entry('Fusion 360')).toBeDefined()
+ f.access({ action: 'change', entryId: id, name: 'Desk lamp' })
+ expect(f.entry('Desk lamp')).toMatchObject({ teammates: true })
+ })
+
+ it('never lets an agent mark a production entry as not production', () => {
+ const f = swarm()
+ const askedIn = { conversationId: 'lead', messageId: 'm-gray' }
+ const id = f.add('Prod DB read-only', { production: true })
+ expect(refusal(() => f.access({ action: 'change', entryId: id, production: false, askedIn }, f.leadActor, said('gray')))?.code).toBe('OWNER_SESSION_REQUIRED')
+ expect(f.entry('Prod DB read-only')!.production).toBe(true)
+ f.access({ action: 'change', entryId: id, production: false })
+ expect(f.entry('Prod DB read-only')!.production).toBeUndefined()
+ })
+
+ it('is confirmed by the owner, in Machines or by the Lead passing on their word', () => {
+ const askedIn = { conversationId: 'lead', messageId: 'm-1' }
+ for (const confirm of ['owner', 'lead'] as const) {
+ const f = swarm()
+ const id = f.add('Email', { askedIn }, f.leadActor, said('owner'))
+ // Anyone else's word does not confirm it.
+ expect(refusal(() => f.access({ action: 'confirm', entryId: id, askedIn }, f.leadActor, said('mate')))?.code).toBe('OWNER_REQUIRED')
+ if (confirm === 'owner') f.access({ action: 'confirm', entryId: id })
+ else f.access({ action: 'confirm', entryId: id, askedIn }, f.leadActor, said('gray'))
+ expect(f.entry('Email')).toMatchObject({ state: 'ok', addedBy: 'gray' })
+ expect(f.entry('Email')!.saidBy).toBeUndefined()
+ }
+ })
+
+ it('is removed by the owner; the Lead removes an unconfirmed entry, but an ok one only on the owner\'s word', () => {
+ const f = swarm()
+ const askedIn = { conversationId: 'lead', messageId: 'm-1' }
+ const ok = f.add('Fusion 360')
+ const waiting = f.add('Email', { askedIn }, f.leadActor, said('owner'))
+ f.access({ action: 'remove', entryId: waiting }, f.leadActor)
+ expect(f.entry('Email')).toBeUndefined()
+ expect(refusal(() => f.access({ action: 'remove', entryId: ok }, f.leadActor))?.code).toBe('OWNER_REQUIRED')
+ f.access({ action: 'remove', entryId: ok, askedIn }, f.leadActor, said('gray'))
+ expect(f.machine('gray-mac').access).toBeUndefined()
+ expect(refusal(() => f.access({ action: 'remove', entryId: ok }))?.code).toBe('NOT_FOUND')
+ })
+
+ it('drops an unconfirmed entry 7 days after it was added', () => {
+ const f = swarm()
+ f.add('Email', { askedIn: { conversationId: 'lead', messageId: 'm-1' } }, f.leadActor, said('owner'))
+ f.add('Fusion 360')
+ f.machine('gray-mac').access!.forEach(e => { e.addedAt = new Date(NOW - 7 * DAY).toISOString() })
+ f.add('Lamp')
+ expect(f.machine('gray-mac').access!.map(e => e.name)).toEqual(['Fusion 360', 'Lamp'])
+ })
+
+ it('survives Desktop saving the contribution again, and goes with the machine', () => {
+ const f = swarm()
+ f.add('Fusion 360')
+ f.run({ type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 2,
+ teamAccountOnly: true }, gray, f.joined)
+ expect(f.machine('gray-mac').access).toHaveLength(1)
+ f.machine('gray-mac').observation = { ...reading('computer'), receivedAt: 0 }
+ f.machine('gray-team').observation = { ...reading('team', PASSED), receivedAt: 0 }
+ f.run({ type: 'machine.remove', machineId: 'gray-mac' }, gray)
+ for (const cleanup of f.state.machineCleanups ?? []) cleanup.requestedAt = new Date(NOW - 60 * 60_000).toISOString()
+ f.run({ type: 'machine.contribute', machineId: 'gray-mac', name: 'Gray\'s Mac', cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4,
+ teamAccountOnly: true }, gray, f.joined)
+ expect(f.machine('gray-mac').access).toBeUndefined()
+ })
+})
+
+describe('who reads what (design section 4)', () => {
+ /** Gray's Mac with an own-account entry and a Team-account entry, both with a note and a check. */
+ function listed() {
+ const f = swarm()
+ f.add('ArgoCD', { note: 'connection info in ~/.argocd/config', check: 'argocd' })
+ f.add('Lamp', { account: 'team', note: 'lamp MCP server, port 7000', check: 'lamp-mcp' })
+ const read = (actor: Actor) => visibleState(f.state, actor, NOW).machines!.find(m => m.machineId === 'gray-mac')!.access!
+ const named = (actor: Actor, name: string) => read(actor).find(e => e.name === name)!
+ return { f, read, named }
+ }
+
+ it('gives the machine\'s owner everything: the note and the check', () => {
+ const { named } = listed()
+ expect(named(gray, 'ArgoCD')).toMatchObject({ note: 'connection info in ~/.argocd/config', check: 'argocd' })
+ expect(named(gray, 'Lamp')).toMatchObject({ note: 'lamp MCP server, port 7000', check: 'lamp-mcp' })
+ })
+
+ it('gives every other member the names, account and state, never a note or a check', () => {
+ const { read } = listed()
+ for (const reader of [owner, mate]) {
+ const entries = read(reader)
+ expect(entries.map(e => [e.name, e.account, e.state])).toEqual([['ArgoCD', 'own', 'ok'], ['Lamp', 'team', 'ok']])
+ for (const e of entries) {
+ expect(e.note, JSON.stringify(reader)).toBeUndefined()
+ expect(e.check, JSON.stringify(reader)).toBeUndefined()
+ }
+ }
+ })
+
+ it('gives an agent on that machine, in that entry\'s account, the note and never the check', () => {
+ const { f, named } = listed()
+ const onMac = f.agent('mac-worker', 'gray-mac')
+ const onTeam = f.agent('team-worker', 'gray-team')
+ expect(named(onMac, 'ArgoCD')).toMatchObject({ note: 'connection info in ~/.argocd/config' })
+ expect(named(onMac, 'ArgoCD').check).toBeUndefined()
+ expect(named(onMac, 'Lamp').note).toBeUndefined()
+ expect(named(onTeam, 'Lamp')).toMatchObject({ note: 'lamp MCP server, port 7000' })
+ expect(named(onTeam, 'Lamp').check).toBeUndefined()
+ expect(named(onTeam, 'ArgoCD').note).toBeUndefined()
+ })
+
+ it('gives an agent of the owner on another machine, and the Lead that recorded it, no note', () => {
+ const { f, named } = listed()
+ // Gray's own agent, but on the owner's Mac: owner rights are the owner's own session only.
+ const elsewhere = f.agent('gray-elsewhere', 'owner-mac')
+ for (const reader of [elsewhere, f.leadActor]) {
+ for (const name of ['ArgoCD', 'Lamp']) {
+ expect(named(reader, name).note, `${JSON.stringify(reader)} ${name}`).toBeUndefined()
+ expect(named(reader, name).check, `${JSON.stringify(reader)} ${name}`).toBeUndefined()
+ }
+ }
+ })
+
+ it('gives agents no note of an entry waiting for its owner to confirm, and the note once confirmed (security review 1)', () => {
+ const f = swarm()
+ f.add('Email', { note: 'run the mail tool in ~/bin', askedIn: { conversationId: 'lead', messageId: 'm-1' } }, f.leadActor, said('mate'))
+ const onMac = f.agent('mac-worker', 'gray-mac')
+ const read = (actor: Actor) => visibleState(f.state, actor, NOW).machines!.find(m => m.machineId === 'gray-mac')!.access!.find(e => e.name === 'Email')!
+ expect(read(onMac).note).toBeUndefined()
+ // Its owner reads what was said, to confirm it or not.
+ expect(read(gray).note).toBe('run the mail tool in ~/bin')
+ f.access({ action: 'confirm', entryId: f.entry('Email')!.id })
+ expect(read(onMac).note).toBe('run the mail tool in ~/bin')
+ })
+
+ it('leaves the stored list whole', () => {
+ const { f, read } = listed()
+ read(mate)
+ expect(f.entry('ArgoCD')).toMatchObject({ note: 'connection info in ~/.argocd/config', check: 'argocd' })
+ })
+})
+
+describe('requires.access and the start check (design section 3)', () => {
+ const candidate = (id: string, machineId: string) => ({ id, kind: 'new', machineId, engine: 'codex', model: 'default', effort: 'default',
+ quality: 3, cost: 2, title: `${id} on ${machineId}`, label: `Label ${id}` })
+ const record = (candidates: unknown[]) => ({ assessment: { difficulty: 'medium', risk: 'low', why: 'A lamp test.' }, candidates, excluded: [],
+ floor: 2, notes: false, via: 'instructions', p: null, belowFloor: false, why: 'Instructions.' })
+ const lastStart = (f: ReturnType<typeof swarm>) => f.state.starts!.at(-1)!.request
+
+ it('keeps a task\'s access, trimmed', () => {
+ const f = swarm()
+ const work = f.group('lead', owner, { access: ['Lamp', ' Fusion 360 '] })
+ expect(f.state.conversations.find(c => c.id === work)!.task!.requires).toEqual({ access: ['Lamp', 'Fusion 360'] })
+ expect(() => f.group('lead', owner, { access: ['x'.repeat(61)] })).toThrow('expected string to have <=60 characters')
+ })
+
+ it('refuses a start that names no access (an older CLI) where the task\'s access is missing', () => {
+ const f = swarm()
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ expect(refusal(() => f.start(work))).toMatchObject({ code: 'ACCESS_MISSING', message: 'No Lamp here.' })
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
+ it('never counts the owner\'s unshared own-account entry for a teammate\'s task, nor the Team account for it', () => {
+ const f = swarm()
+ f.add('Lamp')
+ // The Swarm owner's project is a teammate's on Gray's Mac: it runs in the Team account, which has no Lamp.
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ expect(refusal(() => f.start(work))).toMatchObject({ code: 'ACCESS_MISSING', message: 'Lamp is in gray\'s own account, not shared with teammates.' })
+ })
+
+ it('keeps a teammate\'s start on the Mac, in the owner\'s account, when the owner shared that entry', () => {
+ const f = swarm()
+ const id = f.add('Lamp')
+ f.access({ action: 'change', entryId: id, teammates: true })
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ const started = f.start(work)
+ expect(lastStart(f).machineId).toBe('gray-mac')
+ expect(started.result.moved).toBeUndefined()
+ // A task that needs nothing shared still goes to the Team account, as before.
+ f.start(f.group('lead', owner))
+ expect(lastStart(f).machineId).toBe('gray-team')
+ })
+
+ it('starts a recorded route\'s Mac candidate on the Mac only for a task that names the shared entry (security review 2)', () => {
+ const f = swarm()
+ const id = f.add('Lamp')
+ f.access({ action: 'change', entryId: id, teammates: true })
+ const named = f.group('lead', owner, { access: ['Lamp'] })
+ const routed = f.run({ type: 'route.record', conversationId: named, decision: record([candidate('c0', 'gray-mac')]) } as Command, owner)
+ expect(routed.routeDecisions[0]).toMatchObject({ op: 'create', record: { candidates: [{ id: 'c0' }], excluded: [] } })
+ f.start(named)
+ expect(lastStart(f).machineId).toBe('gray-mac')
+ // Named in the route alone, not the task: the start goes to the Team account, which the route offers in its place.
+ f.start(f.group('lead', owner))
+ expect(lastStart(f).machineId).toBe('gray-team')
+ })
+
+ it('sends Team-written code to the Team account even for a shared entry, and refuses it there', () => {
+ const f = swarm()
+ const id = f.add('Lamp')
+ f.access({ action: 'change', entryId: id, teammates: true })
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ f.state.conversations.find(c => c.id === work)!.teamWritten = true
+ expect(refusal(() => f.start(work))?.code).toBe('ACCESS_MISSING')
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
+ it('refuses a start on a machine off the Machines list, which lists nothing it can reach', () => {
+ const f = swarm()
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ expect(refusal(() => f.run({ type: 'agent.start', request: { conversationId: work, machineId: 'owner-laptop', engine: 'codex', name: 'Builder',
+ cwd: '/somewhere', worktree: true, requirements } }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })))
+ .toMatchObject({ code: 'ACCESS_MISSING', message: 'No Lamp here.' })
+ })
+
+ it('refuses an entry waiting for its owner to confirm', () => {
+ const f = swarm()
+ f.add('Lamp', { account: 'team', askedIn: { conversationId: 'lead', messageId: 'm-1' } }, f.leadActor, said('owner'))
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ expect(refusal(() => f.start(work))).toMatchObject({ code: 'ACCESS_MISSING', message: 'Lamp on Gray\'s Mac is waiting for gray to confirm.' })
+ })
+
+ it('refuses the owner\'s own task needing a Team-account entry: that account runs only teammates\' work', () => {
+ const f = swarm()
+ f.add('Lamp', { account: 'team' })
+ const work = f.group(f.grays, gray, { access: ['Lamp'] })
+ expect(refusal(() => f.start(work, gray, f.grays))).toMatchObject({ code: 'ACCESS_MISSING',
+ message: 'Lamp is in the Harness Team account on Gray\'s Mac, which runs only teammates\' work.' })
+ // Its own-account entry is the owner's to use.
+ f.add('Lamp')
+ f.start(work, gray, f.grays)
+ expect(lastStart(f).machineId).toBe('gray-mac')
+ })
+
+ it('takes a project\'s former owner for a teammate: their own-account entry needs sharing (with #3073\'s ownsProject)', () => {
+ const f = swarm()
+ f.add('Lamp')
+ const work = f.group(f.grays, gray, { access: ['Lamp'] })
+ // Gray left and came back: the project is no longer theirs to run in their own account.
+ f.state.projects!.find(p => p.id === f.grays)!.ownerGeneration = 'an-earlier-membership'
+ expect(refusal(() => f.start(work, gray, f.grays))).toMatchObject({ code: 'ACCESS_MISSING', message: 'Lamp is in gray\'s own account, not shared with teammates.' })
+ })
+
+ it('matches names without case or spacing, and leaves a start with no requirement as it was', () => {
+ const f = swarm()
+ f.add('Lamp', { account: 'team' })
+ f.start(f.group('lead', owner, { access: [' lamp '] }))
+ expect(lastStart(f).machineId).toBe('gray-team')
+ const g = swarm()
+ g.start(g.group('lead', owner))
+ expect(g.state.starts!.at(-1)!.request.machineId).toBe('gray-team')
+ })
+
+ it('leaves a machine without the access out of a recorded route, and refuses it as the only choice', () => {
+ const f = swarm()
+ const work = f.group('lead', owner, { access: ['Lamp'] })
+ f.add('Lamp', { account: 'team' })
+ expect(refusal(() => f.run({ type: 'route.record', conversationId: work, decision: record([candidate('c0', 'owner-mac')]) } as Command, owner)))
+ .toMatchObject({ code: 'ACCESS_MISSING', message: 'No Lamp here. Route again.' })
+ const routed = f.run({ type: 'route.record', conversationId: work, decision: record([candidate('c0', 'owner-mac'), candidate('c1', 'gray-mac')]) } as Command, owner)
+ expect(routed.routeDecisions[0]).toMatchObject({ op: 'create', record: { candidates: [{ id: 'c1' }],
+ excluded: [{ title: 'c0 on owner-mac', reason: 'No Lamp here.' }] } })
+ })
+})
diff --git a/backend/src/superTabs/machineAccess.ts b/backend/src/superTabs/machineAccess.ts
new file mode 100644
index 000000000..0d32f845d
--- /dev/null
+++ b/backend/src/superTabs/machineAccess.ts
@@ -0,0 +1,240 @@
+import type { Command, CommandContext } from './commands.js'
+import { findCredentials } from './credentials.js'
+import { machineContribution, ownAccountWork, teamPoolsOf, type ContributedMachine, type TeamWorkRefusal } from './machines.js'
+import { fail, stableId, type Actor, type Conversation, type SuperTabState } from './model.js'
+import { shownNameOf } from './personNames.js'
+import { ledProject, ownsProject, type SwarmProject } from './projects.js'
+
+/**
+ * What a machine can reach, by macOS account (task #3047, docs/design/2026-11-05-machine-access.md): short names people
+ * already use ("Lamp", "Fusion 360", "Email (dee@)"), so a task that needs one runs where it is. An entry never holds the
+ * secret itself; a note may say where the connection info lives. Having access listed grants no permission.
+ */
+export interface AccessEntry {
+ /** 16 hex, made by the server. */
+ id: string
+ name: string
+ /** `own`: the machine owner's macOS account; `team`: the Mac's Harness Team account. Both live on the Mac's own entry. */
+ account: 'own' | 'team'
+ /** `unconfirmed`: someone other than the owner said it (or the owner's word could not be checked); it counts for nothing
+ * until the owner confirms, and goes after UNCONFIRMED_ACCESS_MS. */
+ state: 'ok' | 'unconfirmed'
+ /** An own-account entry teammates' tasks that need it may use, in the owner's account: set only from the owner's session. */
+ teammates?: true
+ /** A production system: the route notes that writes still need a person's go. */
+ production?: true
+ /** How the machine could confirm it by itself (phase 2). Only its owner reads it. */
+ check?: string
+ /** How to use it. Only its owner and agents running on that machine, in that entry's account, read it. */
+ note?: string
+ /** The person who added or confirmed it: the owner, or for an unconfirmed entry whoever said it. */
+ addedBy: string
+ addedAt: string
+ /** Whoever's chat message an unconfirmed entry came from, for "waiting for you: Dee said it". */
+ saidBy?: string
+ /** The chat message a Lead passed on. */
+ askedIn?: { conversationId: string; messageId: string }
+}
+
+export const MAX_ACCESS = 32
+export const UNCONFIRMED_ACCESS_MS = 7 * 24 * 60 * 60_000
+
+/** Names match without case or surrounding space: "lamp" is "Lamp". */
+export const accessKey = (name: string): string => name.trim().replace(/\s+/g, ' ').toLowerCase()
+export const sameAccessName = (a: string, b: string): boolean => accessKey(a) === accessKey(b)
+
+const KNOWN_PREFIX = /(^|[^A-Za-z0-9])(sk-|ghp_|gho_|ghs_|ghu_|github_pat_|xox[a-z]-|AKIA|ASIA)[A-Za-z0-9]/
+/** `user:pass@host`: a password in an address. */
+const PASSWORD_IN_ADDRESS = /[^\s:@/]+:[^\s:@/]+@[^\s@]/
+/**
+ * Whether [text] looks like a secret rather than a name or where one lives: whatever chat redaction finds (credentials.ts),
+ * a key block, a known token prefix, a password in an address, or a run of 20 or more key-like characters that mixes letters
+ * and digits. Paths and words pass: "connection info in ~/.argocd/config".
+ */
+export function secretLike(text: string): boolean {
+ if (findCredentials(text).length || text.includes('-----BEGIN') || KNOWN_PREFIX.test(text) || PASSWORD_IN_ADDRESS.test(text)) return true
+ return text.split(/[^A-Za-z0-9+=_-]+/).some(run => run.length >= 20 && /[A-Za-z]/.test(run) && /\d/.test(run))
+}
+
+/** Drops unconfirmed entries nobody confirmed in UNCONFIRMED_ACCESS_MS, on every write and read, as expireRemovals. */
+export function expireAccess(state: Pick<SuperTabState, 'machines'>, now: number): void {
+ for (const pool of state.machines ?? []) {
+ if (!pool.access) continue
+ const kept = pool.access.filter(e => e.state !== 'unconfirmed' || now - Date.parse(e.addedAt) < UNCONFIRMED_ACCESS_MS)
+ if (kept.length === pool.access.length) continue
+ if (kept.length) pool.access = kept
+ else delete pool.access
+ }
+}
+
+/** The Mac a pool is: itself, or for a Harness Team account's pool the Mac it lives on, whose entry holds both lists. */
+export function macOf(state: Pick<SuperTabState, 'machines'>, pool: ContributedMachine): ContributedMachine | undefined {
+ return pool.hostMachineId ? state.machines?.find(m => m.machineId === pool.hostMachineId && m.contributorId === pool.contributorId) : pool
+}
+
+type AccessCommand = Extract<Command, { type: 'machine.access' }>
+type AskedIn = AccessCommand['askedIn']
+
+/**
+ * Applies one machine.access command and returns the entry's id. Its owner changes anything from their own session. A
+ * Lead passes on what people say in chat (design section 2): the owner's own word from the last day, in a chat it leads,
+ * counts at once ([ownerWord], as machine.projects); anything else (someone else's word, an older message, another chat)
+ * is kept unconfirmed until the owner confirms. Sharing an entry with teammates loosens a privacy guard, and marking one
+ * not production hides a warning, so both are the owner's own session only.
+ */
+export function changeAccess(state: SuperTabState, actor: Actor, command: AccessCommand, context: Pick<CommandContext, 'now' | 'askedIn'>,
+ ownerWord: (pool: ContributedMachine, askedIn: AskedIn) => boolean, operationId: string): string {
+ const pool = machineContribution(state, command.machineId)
+ // A Harness Team account's entries live on its Mac: it is that Mac, under its name.
+ if (!pool || pool.hostMachineId || pool.buddyOnly) fail('NOT_FOUND', 'This machine has not been contributed.', 404)
+ if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')
+ const owners = ownerWord(pool, command.askedIn)
+ const session = actor.kind === 'person' && actor.userId === pool.contributorId
+ const lead = actor.kind === 'agent' && !!ledProject(state, actor.agentId)
+ const message = context.askedIn
+ // Whose chat message a Lead records unconfirmed: a person's, not a system row.
+ const saidBy = !owners && lead && command.askedIn && message && message.author.kind === 'person' && !message.source ? message.author.id : undefined
+ const refuseOwner = (): never => fail('OWNER_REQUIRED',
+ "Only the machine's owner, or the Lead passing on a chat message the owner wrote in the last day, changes what it can reach.", 403)
+ const ownerSession = (what: string): never => fail('OWNER_SESSION_REQUIRED', `Only the machine's owner can ${what}, from Harness on their own computer.`, 403)
+ for (const text of [command.name, command.note, command.check]) {
+ if (text && secretLike(text)) fail('ACCESS_SECRET', 'That looks like a password or key. Write where it lives instead, such as a file or profile name.', 400)
+ }
+ if (command.teammates === true && !session) ownerSession('share what it can reach with teammates')
+ if (command.production === false && !session) ownerSession('mark an entry as not a production system')
+ const relayed = actor.kind === 'agent' && command.askedIn
+ ? { askedIn: { conversationId: command.askedIn.conversationId, messageId: command.askedIn.messageId } } : {}
+ const at = new Date(context.now).toISOString()
+ const list = pool.access ?? []
+ const taken = (name: string, account: AccessEntry['account'], except?: string) =>
+ list.some(e => e.id !== except && e.account === account && sameAccessName(e.name, name))
+ const exists = (name: string): never => fail('ACCESS_EXISTS', `${name} is already listed for that account on ${pool.name}.`)
+ if (command.action === 'add') {
+ if (!command.name) fail('INVALID_REQUEST', 'Name the access to add.', 400)
+ if (!owners && !saidBy) refuseOwner()
+ const account = command.account ?? 'own'
+ if (account === 'team' && !teamPoolsOf(state, pool).length) fail('NO_TEAM_ACCOUNT', `${pool.name} has no Harness Team account in this Swarm.`, 400)
+ if (account === 'team' && command.teammates) teamEntry()
+ if (taken(command.name, account)) exists(command.name)
+ if (list.length >= MAX_ACCESS) fail('ACCESS_FULL', `${pool.name} lists ${MAX_ACCESS} things it can reach, the most it keeps. Remove one first.`)
+ const id = stableId(operationId, 'machine.access').slice(0, 16)
+ pool.access = [...list, { id, name: command.name, account, state: owners ? 'ok' : 'unconfirmed',
+ ...(command.teammates ? { teammates: true as const } : {}), ...(command.production ? { production: true as const } : {}),
+ ...(command.check && owners ? { check: command.check } : {}), ...(command.note ? { note: command.note } : {}),
+ addedBy: owners ? pool.contributorId : saidBy!, addedAt: at, ...(owners ? {} : { saidBy }), ...relayed }]
+ return id
+ }
+ const entry = (command.entryId && list.find(e => e.id === command.entryId)) || fail('NOT_FOUND', 'That entry is not on this machine.', 404)
+ if (command.action === 'remove') {
+ // A Lead takes back what it recorded unconfirmed (the owner said "Not right"); anything else is the owner's.
+ if (!owners && !(lead && entry.state === 'unconfirmed')) refuseOwner()
+ const kept = list.filter(e => e !== entry)
+ if (kept.length) pool.access = kept
+ else delete pool.access
+ return entry.id
+ }
+ if (!owners) refuseOwner()
+ if (command.action === 'confirm') {
+ entry.state = 'ok'
+ entry.addedBy = pool.contributorId
+ delete entry.saidBy
+ if (relayed.askedIn) entry.askedIn = relayed.askedIn
+ else delete entry.askedIn
+ return entry.id
+ }
+ if (command.account !== undefined) fail('INVALID_REQUEST', 'Remove the entry and add it again to move it to the other account.', 400)
+ if (command.name !== undefined) {
+ // A shared entry renamed moves its sharing to whatever the new name is: that is sharing anew, the owner's session only.
+ if (entry.teammates && !session && !sameAccessName(command.name, entry.name)) ownerSession('rename an entry shared with teammates')
+ if (taken(command.name, entry.account, entry.id)) exists(command.name)
+ entry.name = command.name
+ }
+ if (command.teammates !== undefined) {
+ if (entry.account === 'team') teamEntry()
+ if (command.teammates) entry.teammates = true
+ else delete entry.teammates
+ }
+ if (command.production !== undefined) {
+ if (command.production) entry.production = true
+ else delete entry.production
+ }
+ for (const key of ['note', 'check'] as const) {
+ const value = command[key]
+ if (value === undefined) continue
+ if (value === null) delete entry[key]
+ else entry[key] = value
+ }
+ return entry.id
+}
+
+const teamEntry = (): never =>
+ fail('TEAM_ACCOUNT_ENTRY', 'A Harness Team account always runs teammates\' work: only an entry in your own account is shared.', 400)
+
+/**
+ * What [actor] reads of a Mac's list (design section 4): everyone who sees the machine reads each entry's name, account and
+ * state; its `check` only the machine's owner, from their own session; its `note` the owner, and once the entry is ok,
+ * agents running on that machine in that entry's account (the Mac for `own`, its Harness Team account's pool for `team`). An agent of the owner on
+ * another machine, or the Lead that recorded it, reads neither.
+ */
+export function visibleAccess(state: Pick<SuperTabState, 'machines' | 'agents'>, pool: ContributedMachine, actor: Actor): AccessEntry[] | undefined {
+ if (!pool.access) return undefined
+ if (actor.kind === 'person' && actor.userId === pool.contributorId) return pool.access
+ const agent = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId) : undefined
+ const runsIn = (entry: AccessEntry): boolean => {
+ if (!agent) return false
+ if (entry.account === 'own') return agent.machineId === pool.machineId
+ const team = state.machines?.find(m => m.machineId === agent.machineId)
+ return !!team && team.hostMachineId === pool.machineId && team.contributorId === pool.contributorId
+ }
+ return pool.access.map(entry => {
+ const { check: _check, note, ...rest } = entry
+ // What someone other than the owner said is no instruction to the owner's agents until the owner confirms it.
+ return note !== undefined && entry.state === 'ok' && runsIn(entry) ? { ...rest, note } : rest
+ })
+}
+
+/** What a task needs to reach (`task.requires.access`), or none. */
+export const taskAccess = (group: Pick<Conversation, 'task'> | undefined): string[] => group?.task?.requires?.access ?? []
+
+const entryFor = (mac: ContributedMachine, name: string, account: AccessEntry['account']): AccessEntry | undefined =>
+ mac.access?.find(e => e.account === account && sameAccessName(e.name, name))
+
+/**
+ * Whether every name in [needed] is an own-account entry of [pool] its owner shared with teammates (`teammates`), ok: a
+ * teammate's task that needs them runs in the owner's own account on that Mac, as with own-account work (design section 4).
+ * Never for a Harness Team account's pool, which keeps no list, and never for a task that needs nothing.
+ */
+export function sharedOwnAccess(pool: ContributedMachine | undefined, needed: readonly string[]): boolean {
+ if (!pool || pool.hostMachineId || pool.buddyOnly || !needed.length) return false
+ return needed.every(name => { const e = entryFor(pool, name, 'own'); return !!e && e.state === 'ok' && e.teammates === true })
+}
+
+/**
+ * Why work for [project] that needs [needed] cannot run on [machineId], the pool it would run in (after teamMachineFor), or
+ * null. It reads the entries of that account only: the Mac's own for the Mac, its Team account's for the Team pool. An entry
+ * counts when it is ok, and an own-account one for a teammate's project only when its owner shared it or lets teammates'
+ * work run in their account (design section 4). The sentence names the first name missing.
+ */
+export function accessRefusal(state: SuperTabState, machineId: string, project: SwarmProject, needed: readonly string[]): TeamWorkRefusal | null {
+ if (!needed.length) return null
+ const pool = state.machines?.find(m => m.machineId === machineId)
+ const mac = pool && macOf(state, pool)
+ const account: AccessEntry['account'] = pool?.hostMachineId ? 'team' : 'own'
+ const refuse = (reason: string): TeamWorkRefusal => ({ code: 'ACCESS_MISSING', reason })
+ for (const name of needed) {
+ if (!pool || !mac) return refuse(`No ${name} here.`)
+ const owner = shownNameOf(state as SuperTabState, mac.contributorId) ?? 'its owner'
+ // Its owner's own project only while they own it (projects.ts ownsProject): one who left is a teammate like any other.
+ const teammate = !ownsProject(state, mac.contributorId, project)
+ const entry = entryFor(mac, name, account)
+ const other = entryFor(mac, name, account === 'own' ? 'team' : 'own')
+ if (!entry) {
+ if (other && account === 'own') return refuse(`${other.name} is in the Harness Team account on ${mac.name}, which runs only teammates' work.`)
+ if (other && account === 'team' && teammate) return refuse(`${other.name} is in ${owner}'s own account, not shared with teammates.`)
+ return refuse(`No ${name} here.`)
+ }
+ if (entry.state !== 'ok') return refuse(`${entry.name} on ${mac.name} is waiting for ${owner} to confirm.`)
+ if (account === 'own' && teammate && !entry.teammates && !ownAccountWork(mac)) return refuse(`${entry.name} is in ${owner}'s own account, not shared with teammates.`)
+ }
+ return null
+}
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 5ab585f50..a8e37fff7 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -1,3 +1,4 @@
+import { accessRefusal, sharedOwnAccess, taskAccess } from './machineAccess.js'
import { createHash } from 'node:crypto'
import { z } from 'zod'
import { engineUnusable } from './engineHealth.js'
@@ -65,6 +66,10 @@ export interface ContributedMachine {
/** The projects whose agents may run here, set by its owner (commands.ts machine.projects, Tony 11-03); absent: every
* project, as before. A Mac's Harness Team account keeps none of its own: it follows its Mac's (machineProjectRefusal). */
projects?: string[]
+ /** What it can reach, by macOS account (machine.access, machineAccess.ts, task #3047): its own account's and its Harness
+ * Team account's, both on the Mac's own entry; never on a Team account's. Kept when the contribution is saved again;
+ * gone with the machine. At most MAX_ACCESS. */
+ access?: import('./machineAccess.js').AccessEntry[]
/** Per engine, its failed starts here in a row, until one runs or they suspend it (engineHealth.ts). */
engineFailures?: Record<string, number>
/** Per engine, a suspension after failed starts: when, and whether its reading already said signed in with quota then. */
@@ -294,7 +299,7 @@ export function observedPrivacy(previous: StoredPrivacy | undefined, reported: M
}
export type TeamWorkCode = 'TEAM_WRITTEN_WORK' | 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'
- | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS'
+ | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS' | 'ACCESS_MISSING'
export interface TeamWorkRefusal { code: TeamWorkCode; reason: string }
/** Refusals that hold until a person acts on the machine; a stale check or an offline machine may pass again by itself. */
export const LASTING_TEAM_REFUSALS: readonly string[] = ['TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED', 'MACHINE_IN_OTHER_WORKSPACE']
@@ -368,7 +373,9 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =
* row is signed in as a team account, read by the store.
*/
export function teamWorkCheck(state: SuperTabState, machineId: string, contributorId: string, project: SwarmProject, now: number,
- teamMachines: readonly string[] = [], otherWorkspaceMachines: readonly string[] = []): TeamWorkRefusal | null {
+ teamMachines: readonly string[] = [], otherWorkspaceMachines: readonly string[] = [],
+ /** What the task needs to reach (machineAccess.ts): own-account entries its owner shared let it run in their account. */
+ access: readonly string[] = []): TeamWorkRefusal | null {
// Its owner kept it for other projects (machine.projects): whoever's project and grant it is.
const kept = machineProjectRefusal(state, machineId, project)
if (kept) return kept
@@ -382,6 +389,9 @@ export function teamWorkCheck(state: SuperTabState, machineId: string, contribut
if (!teamAccountRequired()) return null
return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `This machine is not a Team machine of this Swarm, ${ONLY_OWN}.` }
}
+ // Its owner shared what this task needs from their own account with teammates: the owner's choice, as ownAccountWork, for
+ // the tasks that need it only (design section 4).
+ if (sharedOwnAccess(pool, access)) return null
return teamWorkRefusal(pool, now, teamMachines.includes(machineId), teamAccountRequired(), otherWorkspaceMachines.includes(machineId))
}
@@ -497,13 +507,15 @@ export const movedToTeamAccount = (pool: Pick<ContributedMachine, 'name'>, teamW
/** Where a new agent for [project] runs when a start names [machineId]: the Mac's team account when the project is not
* its contributor's own and the Mac has one in this Swarm, else the machine named. Not when its owner lets teammates'
* work run in their own account there (ownAccountWork), unless a Team agent wrote the code. */
-export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[], teamWritten = false): string {
+export function teamMachineFor(state: SuperTabState, machineId: string, project: SwarmProject, idle = false, live?: readonly string[], teamWritten = false,
+ /** What the task needs to reach: a teammate's task needing only own-account entries its owner shared stays on the Mac. */
+ access: readonly string[] = []): string {
// With no GitHub App on this server a team account cannot fetch or push, so the work stays on the Mac, as before.
if (idle) return machineId
const pool = state.machines?.find(m => m.machineId === machineId)
// [teamWritten]: code a Team agent wrote takes the Team account even in its owner's own project (teamWritten.ts, audit H2).
if (!pool || (!teamWritten && ownsProject(state, pool.contributorId, project))) return machineId
- if (!teamWritten && ownAccountWork(pool)) return machineId
+ if (!teamWritten && (ownAccountWork(pool) || sharedOwnAccess(pool, access))) return machineId
return teamPoolOf(state, pool, live)?.machineId ?? machineId
}
@@ -545,8 +557,8 @@ export function buddyProjectsOn(state: SuperTabState, pool: ContributedMachine,
* stay with the owner's daemon, and a Mac without a team account here refuses it as before (teamWorkCheck).
*/
export function teamStartRequest(state: SuperTabState, request: AgentStartRequest, project: SwarmProject, idle = false,
- live?: readonly string[], teamWritten = false): AgentStartRequest {
- const machineId = teamMachineFor(state, request.machineId, project, idle, live, teamWritten)
+ live?: readonly string[], teamWritten = false, access: readonly string[] = []): AgentStartRequest {
+ const machineId = teamMachineFor(state, request.machineId, project, idle, live, teamWritten, access)
if (machineId === request.machineId) return request
const pool = state.machines!.find(m => m.machineId === request.machineId)!, team = state.machines!.find(m => m.machineId === machineId)!
return { ...request, machineId, cwd: request.cwd === projectFolder(pool, project) ? projectFolder(team, project) : request.cwd }
@@ -816,7 +828,12 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
// Before the request's own fields: a machine that takes none of this project's work says so first. A Buddy is its owner's
// own agent on their own machine (commands.ts buddy.create), as a Lead is: teammates' work rules do not apply to it. Nor to
// a Product Manager outside a Team account: any machine of the Swarm takes it (leadStart.ts, Ken 10-29).
- if (!request.buddyOf && !(request.leadFor && !teamAccountPool(pool))) requireTeamWork(state, pool.machineId, pool.contributorId, project!, now, teamMachines, otherWorkspaceMachines)
+ // What the task needs to reach, checked here for every start whatever the route sent (an older CLI drops needs.access):
+ // a Buddy and a Product Manager need none (design section 3).
+ const needed = !request.buddyOf && !request.leadFor ? taskAccess(group) : []
+ if (!request.buddyOf && !(request.leadFor && !teamAccountPool(pool))) requireTeamWork(state, pool.machineId, pool.contributorId, project!, now, teamMachines, otherWorkspaceMachines, needed)
+ const missing = project ? accessRefusal(state, pool.machineId, project, needed) : null
+ if (missing) failTeamWork(missing)
const cwd = project ? projectFolder(pool, project) : buddyHomeFolder(pool, { id: request.buddyOf!.personId })
// Every refused field is named, with what the machine does accept. Values the caller sent are not echoed: an account
// setting can be a path or a name of the caller's own.
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 2a8d47f87..4dc8b2eff 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -10,6 +10,7 @@ import { swarmUsernames } from './usernames.js'
import { downSince, expireRemovals, startPreparing } from './machines.js'
import { publicReason, readsRawReason } from './startFailure.js'
import { FIRST_INSTRUCTIONS } from './instructions.js'
+import { visibleAccess } from './machineAccess.js'
import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProject, groupProject, ledProject, ownerlessProjects, ownsProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'
export type Role = 'owner' | 'collaborator' | 'viewer'
@@ -298,7 +299,8 @@ export const reviewsWanted = (task: WorkTask | undefined): number => task?.revie
* machine by policy order). `machines`: it runs only there, or on a Mac's Harness Team account of one of them. `devices`:
* full paths every start for it asks its machine to check (cli superTabs/capacity.ts). Never in the rendered brief, since
* a reader may not see the machine. A reader is handed only the machines they see, and how many others (`unseenMachines`). */
-export interface TaskRequirement { machines?: string[]; devices?: string[]; unseenMachines?: number }
+/** `access`: what the work needs to reach, by the names machines list it under (machineAccess.ts, task #3047). */
+export interface TaskRequirement { machines?: string[]; devices?: string[]; access?: string[]; unseenMachines?: number }
/** The machines a reader sees: listed in their visible state, or running an agent they see. */
export const seenMachineIds = (visible: Pick<SuperTabState, 'machines' | 'agents'>): Set<string> =>
@@ -913,6 +915,11 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
const ownRemoved = actor.kind === 'person' ? (visible.removedMachines ?? []).filter(r => r.contributorId === actor.userId).map(r => r.machineId) : []
if (ownRemoved.length) (visible as { removedMachines?: unknown }).removedMachines = ownRemoved
else delete visible.removedMachines
+ // What a machine can reach: its notes and checks only to those section 4 of the design names (machineAccess.ts).
+ for (const pool of visible.machines ?? []) {
+ const access = visibleAccess(state, pool, actor)
+ if (access) pool.access = access
+ }
// Rows by day and project that only the leaderboard read uses, and it takes them from the Swarm itself.
for (const pool of visible.machines ?? []) delete pool.lentDays
// A machine kept for some projects names to each reader only those they may read (machines.ts projects): a private
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index a5824b339..86eff0398 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -3,6 +3,7 @@ import { writeReactionActivity, writeReplyActivity } from './activity.js'
import { phoneNotices, type ReplyRow, type TagRow } from '../push/notices.js'
import type { PhoneNotice } from '../push/sender.js'
import { accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'
+import { expireAccess } from './machineAccess.js'
import { authorForAgent, lazyUsernames, namesPerson, rowForAgent, shownNameOf } from './personNames.js'
import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'
import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'
@@ -713,7 +714,7 @@ export class SuperTabStore {
}
switch (command.type) {
case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.engineResume': case 'machine.projects':
- case 'machine.ownAccountWork': return refuse()
+ case 'machine.ownAccountWork': case 'machine.access': return refuse()
case 'machine.cleaned': case 'tab.project': case 'agent.add':
if (command.machineId !== team) refuse()
return
@@ -1674,7 +1675,8 @@ export class SuperTabStore {
}
if (command.type === 'note.add' || command.type === 'note.remove') context.notes = await readNotes(tx, tabId, command.projectId)
if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'
- || command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork') && command.askedIn) {
+ || command.type === 'machine.engineResume' || command.type === 'machine.projects' || command.type === 'machine.ownAccountWork'
+ || command.type === 'machine.access') && command.askedIn) {
const asked = await tx.superTabMessage.findFirst({ where: { id: command.askedIn.messageId, tabId, conversationId: command.askedIn.conversationId } })
if (asked) context.askedIn = { author: asked.author as unknown as Author, source: !!asked.source, createdAt: asked.createdAt.getTime() }
}
@@ -3532,6 +3534,8 @@ export class SuperTabStore {
// A machine that went silent while cleaning takes the fallback before this fresh reading can bring it back: its records
// go, its cleanup waits for this host, as the next sweep would have done (machines.ts expireRemovals).
expireRemovals(state, now)
+ // So does an unconfirmed access entry nobody confirmed in a week: the reading writes this machine's part anyway.
+ expireAccess(state, now)
const stamp = clock.next(), removedIds: string[] = []
// A reading writes only its machine's part, and an agent's part only when its presence changes (spec); a group's only
// when a task there is lost.
diff --git a/cli/src/superTabs/route.spec.ts b/cli/src/superTabs/route.spec.ts
index d6338b7fe..5375b0add 100644
--- a/cli/src/superTabs/route.spec.ts
+++ b/cli/src/superTabs/route.spec.ts
@@ -42,6 +42,15 @@ describe('assessment', () => {
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { cwd: 'relative' } })).toContain('absolute')
expect(parseAssessment(null)).toContain('difficulty')
})
+ // Task #3047: what the work needs to reach, by the names machines list it under.
+ it('parses needs.access, trimmed and once each, and explains a bad one', () => {
+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { access: [' Lamp ', 'Lamp', 'Fusion 360'] } }))
+ .toMatchObject({ needs: { access: ['Lamp', 'Fusion 360'] } })
+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { access: [] } })).not.toHaveProperty('needs.access')
+ for (const access of ['Lamp', [''], ['x'.repeat(61)], [3]]) {
+ expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', needs: { access } }), JSON.stringify(access)).toContain('needs.access')
+ }
+ })
it('parses the task\'s kind', () => {
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', kind: 'ui' })).toMatchObject({ kind: 'ui' })
expect(parseAssessment({ difficulty: 'low', risk: 'low', why: 'x', kind: 'UI work' })).toContain('kind')
diff --git a/cli/src/superTabs/route.ts b/cli/src/superTabs/route.ts
index b8ae689cd..55c93c449 100644
--- a/cli/src/superTabs/route.ts
+++ b/cli/src/superTabs/route.ts
@@ -21,7 +21,8 @@ export type Size = 'small' | 'medium' | 'large'
* start (machineFit.ts). `needs.ci`: the CI jobs the work starts at once, and how many of them on macOS runners, held against
* the account's running-jobs limit; a need above that limit counts as the limit and the route says so (machineFit.ts). Both are left out when not given, so a request without them answers as before. */
export type HeavyWork = 'build' | 'e2e'
-export interface Needs { tools: string[]; devices: string[]; cwd?: string; heavy?: HeavyWork[]; ci?: { jobs: number; macos: number } }
+/** `access`: what the work needs to reach, by the names machines list it under (backend superTabs/machineAccess.ts, task #3047). */
+export interface Needs { tools: string[]; devices: string[]; access?: string[]; cwd?: string; heavy?: HeavyWork[]; ci?: { jobs: number; macos: number } }
export interface Assessment { difficulty: Level; risk: Level; size: Size; why: string; kind?: string; local?: boolean; model?: string; needs: Needs }
/** A model of the reviewed catalog (backend superTabs/catalog.ts): how strong it is, what it costs, and whether it is offered
* when nobody names it. */
@@ -243,6 +244,9 @@ export function parseAssessment(value: unknown): Assessment | string {
if (v.kind !== undefined && (typeof v.kind !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(v.kind))) return 'Set kind to one lowercase word, such as ui or docs.'
if (v.local !== undefined && typeof v.local !== 'boolean') return 'Set local to true only when a person asked for a local model.'
if (v.model !== undefined && (typeof v.model !== 'string' || !words(v.model).length || v.model.length > 200)) return 'Set model to the model a person named, in their words.'
+ const access = needs.access === undefined ? [] : Array.isArray(needs.access) && needs.access.every(n => typeof n === 'string' && n.trim() && n.trim().length <= 60)
+ ? [...new Set((needs.access as string[]).map(n => n.trim().replace(/\s+/g, ' ')))] : null
+ if (!access) return 'Set needs.access to a list of names of up to 60 characters, such as ["Lamp"].'
const heavy = needs.heavy
if (heavy !== undefined && (!Array.isArray(heavy) || !heavy.every(h => HEAVY_WORK.includes(h)))) return 'Set needs.heavy to a list of build and e2e.'
const ci = needs.ci === undefined ? undefined : object(needs.ci)
@@ -252,7 +256,7 @@ export function parseAssessment(value: unknown): Assessment | string {
}
return { difficulty: v.difficulty as Level, risk: v.risk as Level, size: size as Size, why, ...(v.kind ? { kind: v.kind as string } : {}),
...(v.local === true ? { local: true } : {}), ...(typeof v.model === 'string' ? { model: v.model.trim() } : {}),
- needs: { tools: list(needs.tools), devices: list(needs.devices), ...(cwd ? { cwd } : {}),
+ needs: { tools: list(needs.tools), devices: list(needs.devices), ...(access.length ? { access } : {}), ...(cwd ? { cwd } : {}),
...(Array.isArray(heavy) && heavy.length ? { heavy: [...new Set(heavy as HeavyWork[])] } : {}),
...(ci ? { ci: { jobs: ci.jobs as number, macos: (ci.macos as number | undefined) ?? 0 } } : {}) } }
}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index f8323de9b..a3584e0fb 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -2110,3 +2110,117 @@ describe('routing by measured cost and results', () => {
warnings: expect.arrayContaining(['The routing plug-in "measured results" was skipped: its maker failed. The route is shown without it.']) })
})
})
+
+// Task #3047, phase 1 of docs/design/2026-11-05-machine-access.md: a task names what it needs to reach, and the route leaves
+// out every machine and account that does not have it, with why. The backend refuses those starts too (machineAccess.ts).
+describe('needs.access', () => {
+ const reading = () => ({ receivedAt: Date.now(), resources: { memoryTotalBytes: 32e9, memoryUsedBytes: 2e9, projectDiskFreeBytes: 200e9 },
+ tools: { git: true }, runningHarnessIds: ['h1'], quotas: [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3600000 }] }] })
+ const entry = (name: string, account: 'own' | 'team' = 'own', extra: Record<string, unknown> = {}) =>
+ ({ id: `e${name.length}${account}`, name, account, state: 'ok', addedBy: 'mate', addedAt: '2026-11-05T00:00:00.000Z', ...extra })
+ /** Mate's Mac, with its Harness Team account (healthy), and the list on the Mac's own entry. */
+ const mac = (access?: unknown[]) => ({ machineId: 'm1', name: 'MacBook Pro', scope: 'swarm', cwd: '/mate/swarm', engines: ['claude'], paused: false,
+ contributorId: 'mate', observation: reading(), teamWork: { allowed: true }, ...(access ? { access } : {}) })
+ const team = () => ({ machineId: 'm1-team', hostMachineId: 'm1', name: 'MacBook Pro', scope: 'swarm', cwd: '/team/swarm', engines: ['claude'], paused: false,
+ contributorId: 'mate', observation: reading(), teamWork: { allowed: true } })
+ /** The project owner's own machine. */
+ const other = (access?: unknown[]) => ({ machineId: 'm9', name: 'Studio', scope: 'swarm', cwd: '/owner/swarm', engines: ['claude'], paused: false,
+ contributorId: 'owner', observation: reading(), teamWork: { allowed: true }, ...(access ? { access } : {}) })
+ const people = [{ id: 'owner', name: 'Ken' }, { id: 'mate', name: 'Gray' }]
+ async function route(machines: Record<string, unknown>[], { needs = { access: ['Lamp'] } as Record<string, unknown>, requires, members = [] as unknown[], ownerId = 'owner' }:
+ { needs?: Record<string, unknown>; requires?: Record<string, unknown>; members?: unknown[]; ownerId?: string } = {}) {
+ const groups = conversations().map(g => g.id === 'g1' && requires ? { ...g, task: { requires } } : g)
+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents: members, conversations: groups, machines, people,
+ projects: [{ id: 'lead', ownerId, repository: { repositoryUrl: 'https://github.com/example/project' } }] } },
+ policy: { policy, warnings: [] }, machines: [] } } })
+ const answer = await routeTask({ ...input, assessment: { ...input.assessment, needs } }, s, where, opener())
+ const decision = s.mock.calls.find(c => c[0].action === 'command')?.[0].command.decision
+ return { answer, candidates: (decision?.candidates ?? []) as Array<{ machineId: string; kind: string; title: string; notes?: string[] }>,
+ excluded: (decision?.excluded ?? answer.excluded ?? []) as Array<{ title: string; reason: string }> }
+ }
+ const reasonsFor = (excluded: Array<{ title: string; reason: string }>, name: string) => excluded.filter(e => e.title.includes(name)).map(e => e.reason)
+
+ it('leaves out a machine without it, from needs.access or from the task\'s requires.access, names matched without case', async () => {
+ for (const ask of [{ needs: { access: [' lamp '] } }, { needs: {}, requires: { access: ['Lamp'] } }]) {
+ const { candidates, excluded } = await route([mac([entry('Lamp', 'team')]), team(), other()], ask)
+ expect([...new Set(candidates.filter(c => c.kind === 'new').map(c => c.machineId))], JSON.stringify(ask)).toEqual(['m1-team'])
+ expect(reasonsFor(excluded, 'Studio'), JSON.stringify(ask)).toContain(`No ${ask.requires ? 'Lamp' : 'lamp'} here.`)
+ }
+ })
+
+ it('suggests the closest name it saw when nothing matches', async () => {
+ const { excluded } = await route([other([entry('Desk lamp')])], { ownerId: 'owner' })
+ expect(reasonsFor(excluded, 'Studio')).toContain('No Lamp here. Did you mean Desk lamp?')
+ const far = await route([other([entry('Fusion 360')])])
+ expect(reasonsFor(far.excluded, 'Studio')).toContain('No Lamp here.')
+ // The nearest of several: a letter off beats a longer name holding it.
+ const near = await route([other([entry('Desk lamp'), entry('Lamb'), entry('Lamps and more')])])
+ expect(reasonsFor(near.excluded, 'Studio')).toContain('No Lamp here. Did you mean Lamb?')
+ })
+
+ it('takes the task\'s access beside the Lead\'s, each name once', async () => {
+ const { excluded } = await route([other([entry('Lamp')])], { needs: { access: ['lamp'] }, requires: { access: ['Lamp', 'Fusion 360'] } })
+ expect(reasonsFor(excluded, 'Studio')).toEqual(expect.arrayContaining(['No Fusion 360 here.']))
+ expect(reasonsFor(excluded, 'Studio').some(r => /No lamp here/i.test(r))).toBe(false)
+ })
+
+ it('never offers a teammate\'s task the owner\'s unshared own-account entry, nor counts it for the Team account', async () => {
+ const { answer, excluded } = await route([mac([entry('Lamp')]), team()])
+ expect(answer).toMatchObject({ error: 'NO_CANDIDATE' })
+ expect(excluded.map(e => e.reason)).toContain('Lamp is in Gray\'s own account, not shared with teammates.')
+ })
+
+ it('offers the Mac itself, in its owner\'s account and saying so, when its owner shared that entry and the task names it', async () => {
+ const { answer, candidates } = await route([mac([entry('Lamp', 'own', { teammates: true })]), team()], { needs: {}, requires: { access: ['Lamp'] } })
+ expect([...new Set(candidates.filter(c => c.kind === 'new').map(c => c.machineId))]).toEqual(['m1'])
+ const rows = answer.candidates as Array<{ title: string; notes?: string[] }>
+ expect(rows.length).toBeGreaterThan(0)
+ for (const row of rows) expect(row.notes ?? [], row.title).toContain('MacBook Pro runs this task in Gray\'s own account: Lamp is shared with teammates.')
+ })
+
+ // Security review 2: the start keeps a teammate's task on the Mac only for access its task names (backend teamMachineFor), so
+ // a route asked with needs.access alone never offers the owner's account: it would start in the Team account.
+ it('offers a shared own-account entry only to a task that names it, as the start places it', async () => {
+ const { candidates, excluded } = await route([mac([entry('Lamp', 'own', { teammates: true })]), team()])
+ expect(candidates.some(c => c.kind === 'new' && c.machineId === 'm1')).toBe(false)
+ expect(excluded.map(e => e.reason)).toContain('Lamp is shared from Gray\'s own account only with tasks that name it in their access.')
+ })
+
+ it('notes a production system on every candidate that would use one', async () => {
+ const { answer } = await route([mac([entry('Prod DB read-only', 'team', { production: true })]), team()], { needs: { access: ['Prod DB read-only'] } })
+ const rows = answer.candidates as Array<{ title: string; notes?: string[] }>
+ expect(rows.length).toBeGreaterThan(0)
+ for (const row of rows) expect(row.notes ?? [], row.title).toContain('Prod DB read-only is a production system: writes still need a person\'s go.')
+ const plain = await route([mac([entry('Lamp', 'team')]), team()])
+ expect(JSON.stringify(plain.answer)).not.toContain('production system')
+ })
+
+ it('names every shared entry the task needs on the Mac', async () => {
+ const { answer } = await route([mac([entry('Lamp', 'own', { teammates: true }), entry('Fusion 360', 'own', { teammates: true })]), team()],
+ { needs: {}, requires: { access: ['Lamp', 'Fusion 360'] } })
+ for (const row of answer.candidates as Array<{ title: string; notes?: string[] }>) {
+ expect(row.notes ?? [], row.title).toContain('MacBook Pro runs this task in Gray\'s own account: Lamp, Fusion 360 are shared with teammates.')
+ }
+ })
+
+ it('leaves out an entry waiting for its owner to confirm, and a Team-account entry for the owner\'s own project', async () => {
+ const waiting = await route([mac([entry('Lamp', 'team', { state: 'unconfirmed' })]), team()])
+ expect(waiting.excluded.map(e => e.reason)).toContain('Lamp on MacBook Pro is waiting for Gray to confirm.')
+ const own = await route([mac([entry('Lamp', 'team')]), team()], { ownerId: 'mate' })
+ expect(own.excluded.map(e => e.reason)).toContain('Lamp is in the Harness Team account on MacBook Pro, which runs only teammates\' work.')
+ })
+
+ it('leaves out a member on a machine without it too', async () => {
+ const member = { id: 'a1', name: 'Multiply', machineId: 'm9', harnessId: 'h1', contributorId: 'owner', configuration: { engine: 'claude', model: 'sonnet', effort: 'medium' } }
+ const { candidates, excluded } = await route([mac([entry('Lamp', 'team')]), team(), other()], { members: [member] })
+ expect(candidates.some(c => c.kind === 'member')).toBe(false)
+ expect(reasonsFor(excluded, 'Multiply')).toContain('No Lamp here.')
+ })
+
+ it('adds nothing to a start\'s requirements, which older hosts read strictly', async () => {
+ const { answer } = await route([mac([entry('Lamp', 'team')]), team()])
+ const requirements = String(answer.next).match(/"requirements":\{[^}]*\}/g) ?? []
+ expect(requirements.length).toBeGreaterThan(0)
+ for (const r of requirements) expect(r).not.toContain('access')
+ })
+})
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 86ebe101d..2797e0607 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -46,11 +46,83 @@ const WAITING = 'This task waits for the machine it requires; route it again onc
/** What a group's task requires of where it runs (backend superTabs/model.ts TaskRequirement): the machines it runs on, null
* when it names none, and the devices every start for it asks its machine to check. An agent that does not see a required
* machine reads only that there is one, so the set may be empty and still require. */
-export function taskRequirement(group: Json): { machines: Set<string> | null; devices: string[] } {
+export function taskRequirement(group: Json): { machines: Set<string> | null; devices: string[]; access: string[] } {
const requires = object(object(group.task).requires)
const strings = (value: unknown) => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
const unseen = finite(requires.unseenMachines) && requires.unseenMachines > 0
- return { machines: Array.isArray(requires.machines) || unseen ? new Set(strings(requires.machines)) : null, devices: strings(requires.devices) }
+ return { machines: Array.isArray(requires.machines) || unseen ? new Set(strings(requires.machines)) : null, devices: strings(requires.devices),
+ access: strings(requires.access) }
+}
+
+// ── What a machine can reach (backend superTabs/machineAccess.ts, task #3047) ───────────────────────────────────────────
+const accessKey = (name: string): string => name.trim().replace(/\s+/g, ' ').toLowerCase()
+const entryOf = (mac: Json | undefined, name: string, account: 'own' | 'team'): Json | undefined =>
+ list(mac?.access).find(e => e.account === account && typeof e.name === 'string' && accessKey(e.name) === accessKey(name))
+/** Whether every name [needed] is an own-account entry of the Mac [mac] its owner shared with teammates, ok: a teammate's task
+ * that needs them runs on the Mac, in the owner's account (backend sharedOwnAccess). */
+export function sharedOwnAccess(mac: Json | undefined, needed: readonly string[]): boolean {
+ if (!mac || typeof mac.hostMachineId === 'string' || !needed.length) return false
+ return needed.every(name => { const e = entryOf(mac, name, 'own'); return !!e && e.state === 'ok' && e.teammates === true })
+}
+function editDistance(a: string, b: string): number {
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i)
+ for (let i = 1; i <= a.length; i++) {
+ const next = [i]
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j]! + 1, next[j - 1]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1))
+ row = next
+ }
+ return row[b.length]!
+}
+/** The name of [names] closest to [name], when one is close: one holds the other ("Desk lamp", "Lamp"), or a few letters differ. */
+export function closestAccessName(name: string, names: readonly string[]): string | null {
+ const key = accessKey(name)
+ let best: { name: string; score: number } | null = null
+ for (const other of new Set(names)) {
+ const k = accessKey(other)
+ if (k === key) continue
+ const score = k.includes(key) || key.includes(k) ? Math.abs(k.length - key.length) : editDistance(k, key)
+ const close = k.includes(key) || key.includes(k) || score <= Math.max(1, Math.floor(key.length / 4))
+ if (close && (!best || score < best.score)) best = { name: other, score }
+ }
+ return best?.name ?? null
+}
+/**
+ * Why work for a project owned by [projectOwner] that needs [needed] cannot run in [pool]'s account, one line each, as the
+ * backend's start check says it (machineAccess.ts accessRefusal): the entries of that account only, ok, and an own-account
+ * entry for a teammate's project only when shared or when its owner lets teammates' work run there. [pool] undefined: a
+ * machine off the Machines list, which lists nothing. [names]: every name the Swarm's machines list, for "Did you mean".
+ */
+export function accessReasons(pool: Json | undefined, mac: Json | undefined, projectOwner: unknown, needed: readonly string[], people: Json[],
+ names: readonly string[],
+ /** Whether the task itself names every needed name: a shared own-account entry keeps a start on the Mac only then (backend
+ * teamMachineFor reads the task's access), so a route asked with needs.access alone never counts one. */
+ taskNamed = true): string[] {
+ const account = typeof pool?.hostMachineId === 'string' ? 'team' : 'own'
+ const owner = (() => { const p = people.find(x => x.id === mac?.contributorId); return text(p?.name) ?? text(p?.username) ?? 'its owner' })()
+ const teammate = projectOwner !== mac?.contributorId
+ const ownAccountWork = typeof object(mac?.teamWork).ownAccount === 'string'
+ const onlyNamed = (e: Json) => `${String(e.name)} is shared from ${owner}'s own account only with tasks that name it in their access.`
+ return needed.flatMap(name => {
+ const entry = pool && mac ? entryOf(mac, name, account) : undefined
+ if (!entry) {
+ const other = pool && mac ? entryOf(mac, name, account === 'own' ? 'team' : 'own') : undefined
+ if (other && account === 'own') return [`${String(other.name)} is in the Harness Team account on ${String(mac!.name)}, which runs only teammates' work.`]
+ if (other && teammate && other.teammates === true && other.state === 'ok' && !taskNamed) return [onlyNamed(other)]
+ if (other && teammate) return [`${String(other.name)} is in ${owner}'s own account, not shared with teammates.`]
+ const closest = closestAccessName(name, names)
+ return [`No ${name} here.${closest ? ` Did you mean ${closest}?` : ''}`]
+ }
+ if (entry.state !== 'ok') return [`${String(entry.name)} on ${String(mac!.name)} is waiting for ${owner} to confirm.`]
+ if (account === 'own' && teammate && !ownAccountWork && entry.teammates === true && !taskNamed) return [onlyNamed(entry)]
+ if (account === 'own' && teammate && entry.teammates !== true && !ownAccountWork) return [`${String(entry.name)} is in ${owner}'s own account, not shared with teammates.`]
+ return []
+ })
+}
+/** What the route notes on a candidate whose account would use a production system: access is never permission (design section 4). */
+export function productionNotes(pool: Json | undefined, mac: Json | undefined, needed: readonly string[]): string[] {
+ const account = typeof pool?.hostMachineId === 'string' ? 'team' : 'own'
+ return needed.map(name => entryOf(mac, name, account)).filter((e): e is Json => !!e && e.production === true)
+ .map(e => `${String(e.name)} is a production system: writes still need a person's go.`)
}
/** A note on a new agent there, not a filter (project instructions, phase 4): the agent choosing may still try it. */
export const STALLED = 'Its last 2 starts on this machine started no agent (they failed or were never picked up); its owner can check the machine. This clears once a start there succeeds, its Harness is updated, or 30 minutes pass.'
@@ -252,6 +324,15 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// read, and the server records a decision only for a group in the agent's project.
const required = taskRequirement(group)
if (required.devices.length) assessment = { ...assessment, needs: { ...assessment.needs, devices: [...new Set([...assessment.needs.devices, ...required.devices])] } }
+ // What the task needs to reach joins what the Lead said it needs: the backend holds every start to the task's (machineAccess.ts).
+ if (required.access.length) {
+ const access = [...assessment.needs.access ?? []]
+ for (const name of required.access) if (!access.some(a => accessKey(a) === accessKey(name))) access.push(name)
+ assessment = { ...assessment, needs: { ...assessment.needs, access } }
+ }
+ const needed = assessment.needs.access ?? []
+ // Only what the task itself names keeps a teammate's start in the owner's account (backend teamMachineFor).
+ const taskNamed = needed.length > 0 && needed.every(n => required.access.some(r => accessKey(r) === accessKey(n)))
const projectId = String(group.projectId ?? 'lead')
const project = list(state.projects).find(p => p.id === projectId)
// Every idle agent is a candidate, whatever its role: the coordinator, and an agent an older client started as a Reviewer.
@@ -267,7 +348,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
// (production, 2026-10-21). A member may run on a machine only its collaborator can open; the route tries that machine
// too, but a member there is unknown, never offline.
const swarmMachines = new Set([where.machineId, ...list(state.machines).map(m => String(m.machineId)), ...agents.map(a => String(a.machineId))])
- const machines = new Map<string, { name: string; status: string; account: boolean; pool?: Json; folded?: boolean; unready?: Unready; stalled?: boolean; held?: ReturnType<typeof heldByStarts> }>()
+ const machines = new Map<string, { name: string; status: string; account: boolean; pool?: Json; folded?: boolean; unready?: Unready; stalled?: boolean; held?: ReturnType<typeof heldByStarts>; access?: string[]; accessNotes?: string[] }>()
for (const m of list(value.machines)) if (swarmMachines.has(String(m.machineId))) machines.set(String(m.machineId), { name: String(m.name), status: String(m.status ?? 'unknown'), account: true })
// The routing agent's own machine is the account's even when the list could not be read.
if (!machines.has(where.machineId)) machines.set(where.machineId, { name: where.machineId, status: 'unknown', account: true })
@@ -286,13 +367,22 @@ export async function routeTask(input: { tabId: string; conversationId: string;
return named.length ? `${String(mac.name)} runs only ${named.length > 1 ? `${named.slice(0, -1).join(', ')} and ${named.at(-1)}` : named[0]}.`
: `${String(mac.name)} is kept by its owner for other projects.`
}
+ // A Mac's own entry holds both its accounts' lists (backend machineAccess.ts): a Team account's pool reads its Mac's.
+ const macPoolOf = (m: Json): Json | undefined => typeof m.hostMachineId === 'string'
+ ? list(state.machines).find(x => x.machineId === m.hostMachineId && x.contributorId === m.contributorId) : m
+ const people = list(state.people), accessNames = list(state.machines).flatMap(m => list(m.access).map(e => String(e.name)))
for (const original of list(state.machines)) {
const repository = object(project?.repository)
const teamWork = object(original.teamWork)
+ // A teammate's task that needs only entries its owner shared runs on the Mac, in the owner's account: said, not refused.
+ const shared = projectOwner !== original.contributorId && taskNamed && sharedOwnAccess(original, needed)
+ const ownerName = (() => { const p = people.find(x => x.id === original.contributorId); return text(p?.name) ?? text(p?.username) ?? 'its owner' })()
const pool: Json = { ...original,
// Offline is said once, by the reading's own age below.
- ...(teamWork.allowed === false && teamWork.code !== 'MACHINE_OFFLINE' && typeof teamWork.reason === 'string'
+ ...(teamWork.allowed === false && teamWork.code !== 'MACHINE_OFFLINE' && typeof teamWork.reason === 'string' && !shared
? { teammatesRefused: teamWork.reason, projectOwnerId: projectOwner } : {}),
+ ...(shared ? { ownAccount: `${String(original.name)} runs this task in ${ownerName}'s own account: ${needed.join(', ')} ${needed.length > 1 ? 'are' : 'is'} shared with teammates.`,
+ projectOwnerId: projectOwner } : {}),
// Its owner lets teammates' work run in their own account (backend machines.ts ownAccountWork, task #2806): the teammate
// whose task lands there did not choose that, so the route says it (River, 11-04).
...(teamWork.allowed === true && typeof teamWork.ownAccount === 'string' ? { ownAccount: teamWork.ownAccount, projectOwnerId: projectOwner } : {}),
@@ -308,6 +398,11 @@ export async function routeTask(input: { tabId: string; conversationId: string;
unready: unreadyPool(original, project, projectId, object(value.tab).githubApp === true, projectOwner) })
}
for (const [machineId, machine] of machines) {
+ const listed = list(state.machines).find(m => m.machineId === machineId)
+ if (needed.length) {
+ machine.access = accessReasons(listed, listed && macPoolOf(listed), projectOwner, needed, people, accessNames, taskNamed)
+ machine.accessNotes = productionNotes(listed, listed && macPoolOf(listed), needed)
+ }
machine.stalled = stalled(list(state.starts), machineId, list(state.machines).find(m => m.machineId === machineId))
machine.held = heldByStarts(list(state.starts), machineId)
}
@@ -317,7 +412,9 @@ export async function routeTask(input: { tabId: string; conversationId: string;
for (const [team, mac] of macOf) {
const pool = machines.get(team)?.pool
if (!pool || !machines.has(mac)) continue
- machines.get(projectOwner === pool.contributorId ? team : mac)!.folded = true
+ // A teammate's task needing only what the owner shared stays on the Mac (backend teamMachineFor): its Team account folds.
+ const onMac = projectOwner === pool.contributorId || (taskNamed && sharedOwnAccess(list(state.machines).find(m => m.machineId === mac), needed))
+ machines.get(onMac ? team : mac)!.folded = true
}
// Every row of the catalog is probed: one not offered by default is offered when a person names it (route.ts choose).
const rows = catalog.models
@@ -579,7 +676,7 @@ function loadOf(resources: Json, agents: number | null, cwd: string | undefined)
cpuPercent: finite(resources.cpuPercent) ? resources.cpuPercent : null }
}
-async function probeMachine(machineId: string, { name: machineName, status, account, pool, folded, unready = READY, stalled: stuck = false, held = heldByStarts([], machineId) }: { name: string; status: string; account: boolean; pool?: Json; folded?: boolean; unready?: Unready; stalled?: boolean; held?: ReturnType<typeof heldByStarts> },
+async function probeMachine(machineId: string, { name: machineName, status, account, pool, folded, unready = READY, stalled: stuck = false, held = heldByStarts([], machineId), access: unreached = [], accessNotes: noted = [] }: { name: string; status: string; account: boolean; pool?: Json; folded?: boolean; unready?: Unready; stalled?: boolean; held?: ReturnType<typeof heldByStarts>; access?: string[]; accessNotes?: string[] },
members: Json[], allModels: CatalogModel[], catalog: Catalog, a: Assessment, where: Where, open: typeof openDaemon): Promise<Probe[]> {
const listedEngines = Array.isArray(pool?.engines) ? pool.engines.filter((engine): engine is string => typeof engine === 'string') : []
const legacy = listedEngines.some(engine => !ENGINES.includes(engine))
@@ -599,7 +696,7 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const newProbe = (m: CatalogModel, refusals: string[], quota: Probe['quota'], known: boolean, load: Probe['load'] = UNKNOWN_LOAD, notes: string[] = []): Probe => ({
kind: 'new', machineId, machineName, engine: m.engine, model: m.model, effort: m.effort, quality: m.strength, cost: m.cost,
quota, activity: 'new agent', known, refusals, notes, load })
- const offline = () => models.map(m => newProbe(m, [OFFLINE], UNKNOWN_QUOTA, false))
+ const offline = () => models.map(m => newProbe(m, [OFFLINE, ...unreached], UNKNOWN_QUOTA, false))
const needs = startRequirements(a.needs)
if (pool) {
const observed = object(pool.observation), resources = object(observed.resources)
@@ -635,7 +732,7 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
...(freeMemory === null || freeMemory < needs.memoryBytes ? [`Insufficient measured free memory${setAside(held.memoryBytes)}.`] : []),
...needs.tools.map(t => requiredToolReason(t, tools[t], object(observed.toolProbeErrors)[t])).filter((reason): reason is string => reason !== null),
...(needs.devices.length ? ['Required devices have not been reported.'] : []),
- ...unready.all]
+ ...unready.all, ...unreached]
const pushNote = unready.push ? [unready.push] : []
// What the machine has, for new agents and members alike: heavy work runs on the machine whoever does it (machineFit.ts).
const load: Probe['load'] = { agents: Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.length : null,
@@ -649,18 +746,18 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const running = Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.includes(m.harnessId) : null
const closed = Array.isArray(observed.closedHarnessIds) && observed.closedHarnessIds.includes(m.harnessId)
return { ...memberProbe(m, fresh ? [...memberRefusals(running, closed, needs.tools, needs.devices, tools, object(observed.devices), object(observed.toolProbeErrors)),
- ...kept, ...teammates(m.contributorId)] : [OFFLINE],
- allowance, null, fresh && running === null, [...pushNote, ...usedUp(allowance), ...ownAccount]), ...(fresh ? { load } : {}) }
+ ...kept, ...teammates(m.contributorId), ...unreached] : [OFFLINE],
+ allowance, null, fresh && running === null, [...pushNote, ...usedUp(allowance), ...ownAccount, ...noted]), ...(fresh ? { load } : {}) }
}),
...models.map(m => ({ ...newProbe(m, [...newReasons, ...(unready.engines[m.engine] ? [unready.engines[m.engine]!] : [])], quota(m.engine), fresh && quota(m.engine).known,
- load, [...pushNote, ...(stuck ? [STALLED] : []), ...usedUp(quota(m.engine)), ...ownAccount]) }))]
+ load, [...pushNote, ...(stuck ? [STALLED] : []), ...usedUp(quota(m.engine)), ...ownAccount, ...noted]) }))]
}
// The account says this machine is off, so nothing there can run or be asked.
if (account && status === 'offline') return [...members.map(m => memberProbe(m, [OFFLINE])), ...offline()]
let target: Daemon
try { target = await open(where, machineId) } catch {
// Not being able to open a machine says nothing about the agents already on it; only a new start needs it.
- return [...members.map(m => memberProbe(m)), ...offline()]
+ return [...members.map(m => memberProbe(m, unreached)), ...offline()]
}
try {
const listed = object(await target.request('agents_list', {}, 10_000).catch(() => ({})))
@@ -681,7 +778,7 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const refusals = memberRefusals(live.has(String(m.harnessId)), false, needs.tools, needs.devices,
object(capacity.tools), object(capacity.devices), object(capacity.toolProbeErrors))
const frame = frames.find(f => f.id === m.harnessId)
- probes.push({ ...memberProbe(m, refusals, allowance, frame ? frameOf(frame) : null, false, usedUp(allowance)),
+ probes.push({ ...memberProbe(m, [...refusals, ...unreached], allowance, frame ? frameOf(frame) : null, false, usedUp(allowance)),
load: loadOf(object(capacity.resources), Array.isArray(listed.agents) ? frames.length : null, a.needs.cwd) })
}
for (const m of models) {
@@ -697,7 +794,7 @@ async function probeMachine(machineId: string, { name: machineName, status, acco
const os = String(resources.os)
const unfit = NO_SWARM_AGENTS_ON.includes(os) ? [`Swarm agents do not run on ${os} yet.`] : []
const allowance = quotaOf2(inspected.quota)
- probes.push(newProbe(m, [...(inspected.allowed ? [] : reasons), ...unfit], allowance, inspected.unknown.length === 0 && inspected.quota.known, load,
+ probes.push(newProbe(m, [...(inspected.allowed ? [] : reasons), ...unfit, ...unreached], allowance, inspected.unknown.length === 0 && inspected.quota.known, load,
[...(stuck ? [STALLED] : []), ...usedUp(allowance)]))
}
return probes
diff --git a/desktop/lib/super_tabs/machine_access.dart b/desktop/lib/super_tabs/machine_access.dart
new file mode 100644
index 000000000..95a9df026
--- /dev/null
+++ b/desktop/lib/super_tabs/machine_access.dart
@@ -0,0 +1,741 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart' show mapEquals;
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'detail_dialog.dart';
+import 'dialog_scope.dart';
+
+/// What a machine can reach, by macOS account (task #3047, docs/design/2026-11-05-machine-access.md): short names people
+/// already use ("Lamp", "Fusion 360", "Email (dee@)"), kept on the Mac's own entry in the Swarm (backend
+/// machineAccess.ts `AccessEntry`), both accounts' entries there. The server leaves out `note` for everyone but the
+/// owner and the agents running in that entry's account; having access listed grants no permission.
+class SuperTabAccessEntry {
+ const SuperTabAccessEntry({
+ required this.id,
+ required this.name,
+ required this.team,
+ required this.state,
+ this.teammates = false,
+ this.production = false,
+ this.note,
+ this.saidBy,
+ });
+
+ final String id, name;
+
+ /// In the Mac's Harness Team account; otherwise in its owner's own account.
+ final bool team;
+
+ /// `ok` or `unconfirmed` (phase 1); a newer server's `notWorking` reads as not working, as any other state does.
+ final String state;
+
+ /// An own-account entry its owner lets teammates' tasks use, in the owner's account.
+ final bool teammates;
+ final bool production;
+ final String? note;
+
+ /// Who said an unconfirmed entry, for "waiting for you: Dee said it".
+ final String? saidBy;
+
+ bool get ok => state == 'ok';
+ bool get unconfirmed => state == 'unconfirmed';
+
+ /// The entries [pool] carries, in its order; none for a pool without a list, and none of a shape this app cannot read.
+ static List<SuperTabAccessEntry> listOf(Map<String, dynamic>? pool) => [
+ for (final raw
+ in pool?['access'] is List ? pool!['access'] as List : const [])
+ if (raw case {
+ 'id': final String id,
+ 'name': final String name,
+ 'account': final String account,
+ 'state': final String state,
+ })
+ SuperTabAccessEntry(
+ id: id,
+ name: name,
+ team: account == 'team',
+ state: state,
+ teammates: raw['teammates'] == true,
+ production: raw['production'] == true,
+ note: switch (raw['note']) {
+ final String note when note.trim().isNotEmpty => note.trim(),
+ _ => null,
+ },
+ saidBy: raw['saidBy'] as String?,
+ ),
+ ];
+}
+
+/// [owner]'s first name, for "waiting for Gray"; null without one.
+String? _firstName(String? owner) {
+ final words = owner?.trim().split(RegExp(r'\s+'));
+ return words == null || words.first.isEmpty ? null : words.first;
+}
+
+/// The expanded machine row's Access lines, seen by every member who sees the machine: one per account with entries,
+/// its owner's own first and named as the row names its owner ([ownerName], their shown name), then its Team account.
+/// "Gray's account: Fusion 360 · Email (dee@) waiting for Gray".
+class SuperTabMachineAccessLines extends StatelessWidget {
+ const SuperTabMachineAccessLines({
+ super.key,
+ required this.entries,
+ required this.ownerName,
+ });
+
+ final List<SuperTabAccessEntry> entries;
+ final String? ownerName;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final owner = ownerName?.trim();
+ final waitingFor = _firstName(owner) ?? 'the owner';
+ final quiet = DesktopChrome.text(
+ size: 12,
+ height: 1.35,
+ color: DesktopChrome.muted,
+ );
+ final plain = DesktopChrome.text(size: 12, height: 1.35);
+ Widget line(String label, List<SuperTabAccessEntry> listed) => Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(text: '$label: ', style: quiet),
+ for (final (index, entry) in listed.indexed) ...[
+ if (index > 0) TextSpan(text: ' · ', style: quiet),
+ TextSpan(text: entry.name),
+ if (entry.production) TextSpan(text: ' (production)', style: quiet),
+ if (!entry.ok)
+ TextSpan(
+ text: entry.unconfirmed
+ ? ' waiting for $waitingFor'
+ : ' not working',
+ style: quiet,
+ ),
+ ],
+ ],
+ ),
+ style: plain,
+ );
+ final own = [
+ for (final e in entries)
+ if (!e.team) e,
+ ];
+ final team = [
+ for (final e in entries)
+ if (e.team) e,
+ ];
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (own.isNotEmpty)
+ line(
+ owner == null || owner.isEmpty
+ ? "Owner's account"
+ : "$owner's account",
+ own,
+ ),
+ if (own.isNotEmpty && team.isNotEmpty) const SizedBox(height: 4),
+ if (team.isNotEmpty) line('Team account', team),
+ ],
+ );
+ }
+}
+
+const _busyLine = 'Another action is still being sent. Try again in a moment.';
+
+/// Sends one `machine.access` [command] as its owner, as `machine.ownAccountWork` is sent; null once the server took
+/// it, else the server's refusal in its own words. A lost reply of this same change is checked again under its receipt.
+Future<String?> _send(
+ SuperTabController c,
+ Map<String, dynamic> command,
+) async {
+ final retrying = c.hasPendingAction && mapEquals(c.pendingCommand, command);
+ if (c.saving || (c.hasPendingAction && !retrying)) return _busyLine;
+ final result = retrying ? await c.retry() : await c.command(command);
+ if (result != null) return null;
+ return c.operationError ?? "Couldn't change it. Try again.";
+}
+
+/// Configure's Access section, its owner's only (design section 6): what the Mac can reach, by account, each own-account
+/// entry with Teammates may use, an entry someone else said with Confirm and Not right, and Add access…. Every change
+/// is sent at once, as Projects that may use it is. Nothing for anyone else, nor for a Harness Team account's own
+/// entry, whose list is on its Mac.
+class SuperTabMachineAccessSetting extends StatefulWidget {
+ const SuperTabMachineAccessSetting({
+ super.key,
+ required this.controller,
+ required this.machineId,
+ required this.machineName,
+ });
+
+ final SuperTabController controller;
+ final String machineId;
+
+ /// The machine as Configure titles it, for the warning before sharing.
+ final String machineName;
+
+ @override
+ State<SuperTabMachineAccessSetting> createState() =>
+ _SuperTabMachineAccessSettingState();
+}
+
+class _SuperTabMachineAccessSettingState
+ extends State<SuperTabMachineAccessSetting> {
+ bool _busy = false;
+ String? _error;
+
+ SuperTabController get c => widget.controller;
+
+ Map<String, dynamic> _command(String action, SuperTabAccessEntry entry) => {
+ 'type': 'machine.access',
+ 'machineId': widget.machineId,
+ 'action': action,
+ 'entryId': entry.id,
+ };
+
+ Future<void> _change(Map<String, dynamic> command) async {
+ if (_busy) return;
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await _send(c, command);
+ if (mounted) {
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ }
+ }
+
+ /// Teammates may use: on after the warning, naming the entry, which sends it itself; off at once.
+ Future<void> _share(SuperTabAccessEntry entry, bool on) async {
+ if (!on) {
+ return _change({..._command('change', entry), 'teammates': false});
+ }
+ setState(() => _error = null);
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: _ShareWarning(
+ controller: c,
+ entry: entry,
+ machineName: widget.machineName,
+ command: {..._command('change', entry), 'teammates': true},
+ ),
+ ),
+ );
+ }
+
+ Future<void> _add(bool hasTeam) => showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: _AddAccess(
+ controller: c,
+ machineId: widget.machineId,
+ hasTeam: hasTeam,
+ ),
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ grid.AppTheme.watch(context);
+ final snapshot = c.snapshot;
+ final pool = snapshot?.pool(widget.machineId);
+ if (snapshot == null ||
+ pool == null ||
+ pool['hostMachineId'] is String ||
+ pool['contributorId'] != c.accountId ||
+ !c.canWrite) {
+ return const SizedBox.shrink();
+ }
+ final entries = SuperTabAccessEntry.listOf(pool);
+ final hasTeam = snapshot.teamPoolsOf(widget.machineId).isNotEmpty;
+ final own = [
+ for (final e in entries)
+ if (!e.team) e,
+ ];
+ final team = [
+ for (final e in entries)
+ if (e.team) e,
+ ];
+ String said(SuperTabAccessEntry e) {
+ final who = snapshot.people
+ .where((p) => p.id == e.saidBy)
+ .firstOrNull
+ ?.shownName;
+ return who == null
+ ? 'waiting for you'
+ : 'waiting for you: $who said it';
+ }
+
+ Widget heading(String text) => Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),
+ child: Text(
+ text,
+ style: DesktopChrome.metadata().copyWith(fontWeight: FontWeight.w600),
+ ),
+ );
+
+ return SuperTabDetailSection(
+ key: const ValueKey('machine-access-section'),
+ title: 'Access',
+ children: [
+ if (entries.isEmpty)
+ Text(
+ 'Nothing listed yet. Add what this machine can reach, like Fusion 360 or Lamp, so tasks that need it run here.',
+ style: DesktopChrome.metadata(),
+ ),
+ if (own.isNotEmpty) heading('Your account'),
+ for (final e in own)
+ _EntryRow(
+ entry: e,
+ state: e.unconfirmed ? said(e) : null,
+ busy: _busy,
+ onShare: (on) => unawaited(_share(e, on)),
+ onConfirm: () => unawaited(_change(_command('confirm', e))),
+ onRemove: () => unawaited(_change(_command('remove', e))),
+ ),
+ if (team.isNotEmpty) heading('Team account'),
+ for (final e in team)
+ _EntryRow(
+ entry: e,
+ state: e.unconfirmed ? said(e) : null,
+ busy: _busy,
+ onConfirm: () => unawaited(_change(_command('confirm', e))),
+ onRemove: () => unawaited(_change(_command('remove', e))),
+ ),
+ if (_error case final error?)
+ Padding(
+ key: const ValueKey('machine-access-error'),
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),
+ child: Text(
+ error,
+ style: DesktopChrome.metadata(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),
+ child: TextButton.icon(
+ key: const ValueKey('machine-access-add-open'),
+ style: superTabQuietAction,
+ onPressed: _busy ? null : () => unawaited(_add(hasTeam)),
+ icon: const Icon(AppIcons.plus, size: 14),
+ label: const Text('Add access…'),
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+}
+
+/// One entry in Configure: its name and state, its note under it, and what its owner can do with it.
+class _EntryRow extends StatelessWidget {
+ const _EntryRow({
+ required this.entry,
+ required this.state,
+ required this.busy,
+ required this.onConfirm,
+ required this.onRemove,
+ this.onShare,
+ });
+
+ final SuperTabAccessEntry entry;
+
+ /// An unconfirmed entry's words: who said it.
+ final String? state;
+ final bool busy;
+ final VoidCallback onConfirm, onRemove;
+
+ /// Teammates may use: own-account entries only, since a Team account runs teammates' work anyway.
+ final ValueChanged<bool>? onShare;
+
+ @override
+ Widget build(BuildContext context) {
+ final id = entry.id;
+ final quiet = DesktopChrome.metadata();
+ final controls = <Widget>[
+ if (entry.unconfirmed) ...[
+ TextButton(
+ key: ValueKey('machine-access-confirm-$id'),
+ onPressed: busy ? null : onConfirm,
+ child: const Text('Confirm'),
+ ),
+ TextButton(
+ key: ValueKey('machine-access-not-right-$id'),
+ style: superTabQuietAction,
+ onPressed: busy ? null : onRemove,
+ child: const Text('Not right'),
+ ),
+ ] else ...[
+ if (onShare case final share?)
+ InkWell(
+ borderRadius: BorderRadius.circular(grid.AppControl.radius),
+ onTap: busy ? null : () => share(!entry.teammates),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Checkbox(
+ key: ValueKey('machine-access-teammates-$id'),
+ value: entry.teammates,
+ semanticLabel: 'Teammates may use ${entry.name}',
+ onChanged: busy ? null : (on) => share(on ?? false),
+ ),
+ Text('Teammates may use', style: DesktopChrome.control()),
+ const SizedBox(width: grid.AppDesktop.controlGap / 2),
+ ],
+ ),
+ ),
+ AppIconButton(
+ key: ValueKey('machine-access-remove-$id'),
+ icon: AppIcons.trash2,
+ tooltip: 'Remove ${entry.name}',
+ color: DesktopChrome.muted,
+ destructive: true,
+ onPressed: busy ? null : onRemove,
+ ),
+ ],
+ ];
+ return Padding(
+ key: ValueKey('machine-access-entry-$id'),
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap / 2),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Wrap(
+ spacing: grid.AppDesktop.controlGap,
+ crossAxisAlignment: WrapCrossAlignment.end,
+ children: [
+ Text(entry.name, style: DesktopChrome.control()),
+ if (entry.production) Text('(production)', style: quiet),
+ Text(
+ state ?? (entry.ok ? 'ok' : 'not working'),
+ style: quiet,
+ ),
+ ],
+ ),
+ if (entry.note case final note?)
+ Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.listRowGap),
+ child: Text('Note: $note', style: quiet),
+ ),
+ ],
+ ),
+ ),
+ ...controls,
+ ],
+ ),
+ );
+ }
+}
+
+/// The one warning before an own-account entry is shared, as own-account work's (#2806), naming the entry: teammates'
+/// tasks that need it run as its owner. It sends the change itself and says a refusal's reason while open.
+class _ShareWarning extends StatefulWidget {
+ const _ShareWarning({
+ required this.controller,
+ required this.entry,
+ required this.machineName,
+ required this.command,
+ });
+
+ final SuperTabController controller;
+ final SuperTabAccessEntry entry;
+ final String machineName;
+ final Map<String, dynamic> command;
+
+ @override
+ State<_ShareWarning> createState() => _ShareWarningState();
+}
+
+class _ShareWarningState extends State<_ShareWarning> {
+ bool _busy = false;
+ String? _error;
+
+ Future<void> _allow() async {
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await _send(widget.controller, widget.command);
+ if (!mounted) return;
+ if (error == null) {
+ Navigator.pop(context);
+ } else {
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => PopScope(
+ canPop: !_busy,
+ child: AlertDialog(
+ key: const ValueKey('machine-access-teammates-confirm'),
+ title: const Text("Let teammates' work run in your account?"),
+ content: SizedBox(
+ width: 400,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ "Teammates' tasks in this Swarm that need ${widget.entry.name} will run as you on ${widget.machineName}. "
+ 'They can read your files, your keychain and your signed-in apps. Your other entries stay yours.',
+ ),
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Text(
+ error,
+ key: const ValueKey('machine-access-teammates-reason'),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ autofocus: true,
+ onPressed: _busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const ValueKey('machine-access-teammates-allow'),
+ onPressed: _busy ? null : () => unawaited(_allow()),
+ child: const Text('Let them use it'),
+ ),
+ ],
+ ),
+ );
+}
+
+/// Add access (design section 6): a name, which account it is in (the Team account only on a Mac that has one), whether
+/// it is a production system, and an optional note on how to use it. Never the secret itself: the server refuses one.
+class _AddAccess extends StatefulWidget {
+ const _AddAccess({
+ required this.controller,
+ required this.machineId,
+ required this.hasTeam,
+ });
+
+ final SuperTabController controller;
+ final String machineId;
+ final bool hasTeam;
+
+ @override
+ State<_AddAccess> createState() => _AddAccessState();
+}
+
+class _AddAccessState extends State<_AddAccess> {
+ final _name = TextEditingController();
+ final _note = TextEditingController();
+ bool _team = false, _production = false, _busy = false;
+ String? _error;
+
+ @override
+ void dispose() {
+ _name.dispose();
+ _note.dispose();
+ super.dispose();
+ }
+
+ bool get _ready => !_busy && _name.text.trim().isNotEmpty;
+
+ Future<void> _add() async {
+ if (!_ready) return;
+ final note = _note.text.trim();
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await _send(widget.controller, {
+ 'type': 'machine.access',
+ 'machineId': widget.machineId,
+ 'action': 'add',
+ 'name': _name.text.trim(),
+ 'account': _team && widget.hasTeam ? 'team' : 'own',
+ if (_production) 'production': true,
+ if (note.isNotEmpty) 'note': note,
+ });
+ if (!mounted) return;
+ if (error == null) {
+ Navigator.pop(context);
+ } else {
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ }
+ }
+
+ Widget _where(bool team, String label) => InkWell(
+ borderRadius: BorderRadius.circular(grid.AppControl.radius),
+ onTap: _busy ? null : () => setState(() => _team = team),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Radio<bool>(
+ key: ValueKey('machine-access-where-${team ? 'team' : 'own'}'),
+ value: team,
+ enabled: !_busy,
+ ),
+ Padding(
+ padding: const EdgeInsets.only(right: grid.AppDesktop.controlGap),
+ child: Text(label, style: DesktopChrome.control()),
+ ),
+ ],
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return PopScope(
+ canPop: !_busy,
+ child: SuperTabDetailDialog(
+ title: 'Add access',
+ onClose: _busy ? () {} : null,
+ body: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SuperTabDetailRow(
+ label: 'Name',
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TextField(
+ key: const ValueKey('machine-access-name'),
+ controller: _name,
+ autofocus: true,
+ enabled: !_busy,
+ maxLength: 60,
+ textInputAction: TextInputAction.next,
+ decoration: const InputDecoration(counterText: ''),
+ onChanged: (_) => setState(() => _error = null),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Like: Email (dee@), Prod DB read-only',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ ),
+ SuperTabDetailRow(
+ label: 'Where',
+ child: RadioGroup<bool>(
+ groupValue: _team && widget.hasTeam,
+ onChanged: (team) {
+ if (!_busy && team != null) setState(() => _team = team);
+ },
+ child: Wrap(
+ spacing: grid.AppDesktop.controlGap,
+ children: [
+ _where(false, 'Your account'),
+ if (widget.hasTeam) _where(true, 'Team account'),
+ ],
+ ),
+ ),
+ ),
+ SuperTabDetailRow(
+ label: '',
+ child: InkWell(
+ borderRadius: BorderRadius.circular(grid.AppControl.radius),
+ onTap: _busy
+ ? null
+ : () => setState(() => _production = !_production),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Checkbox(
+ key: const ValueKey('machine-access-production'),
+ value: _production,
+ onChanged: _busy
+ ? null
+ : (on) => setState(() => _production = on ?? false),
+ ),
+ Text('Production system', style: DesktopChrome.control()),
+ ],
+ ),
+ ),
+ ),
+ SuperTabDetailRow(
+ label: 'Note',
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TextField(
+ key: const ValueKey('machine-access-note'),
+ controller: _note,
+ enabled: !_busy,
+ maxLength: 200,
+ decoration: const InputDecoration(counterText: ''),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => unawaited(_add()),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Optional: where its connection info lives, never the password itself.',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ ),
+ if (_error case final error?) ...[
+ const SizedBox(height: grid.AppDesktop.controlGap),
+ Text(
+ error,
+ key: const ValueKey('machine-access-add-error'),
+ style: DesktopChrome.metadata(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ],
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: _busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const ValueKey('machine-access-add'),
+ onPressed: _ready ? () => unawaited(_add()) : null,
+ child: Text(_busy ? 'Adding…' : 'Add'),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index dadf30c6e..c1fca5b95 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -35,6 +35,7 @@ import 'detail_dialog.dart';
import 'dialog_scope.dart';
import 'identity.dart';
import 'local_models.dart';
+import 'machine_access.dart';
import 'machine_projects.dart';
import 'machine_allowance.dart';
import '../models/swarm_models_target.dart' show swarmSharedWithYouShown;
@@ -758,12 +759,13 @@ Future<void> _machineSettingsDialog(
final current = app.stateOf(existingId);
final why = settingsUnavailable();
+ final title = superTabMachineName(
+ current?.machine.displayName ??
+ existing['name'] as String? ??
+ existingId,
+ );
return SuperTabDetailDialog(
- title: superTabMachineName(
- current?.machine.displayName ??
- existing['name'] as String? ??
- existingId,
- ),
+ title: title,
body: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -779,6 +781,12 @@ Future<void> _machineSettingsDialog(
atMostEdited = next;
}),
),
+ // What it can reach (#3047): sent at once, apart from Save; its owner's, on the Mac's own entry.
+ SuperTabMachineAccessSetting(
+ controller: c,
+ machineId: existingId,
+ machineName: title,
+ ),
// Why it cannot be removed, in words rather than a dimmed button alone.
if (view != null && canRemove(view.id))
if (removeReason(view.id) case final reason?) ...[
@@ -1565,6 +1573,8 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
engines: allowed,
allowances: subscriptions.allowances,
subscriptionsAside: subscriptions.aside,
+ // What it can reach, from the Mac's own entry, which holds its Team account's too (#3047).
+ access: SuperTabAccessEntry.listOf(shared),
// What the line leaves out, for hover, focus and a screen reader: whose machine it is and its hardware,
// after its state when that is not online. Never an age. Only current readings are included.
tip: [
@@ -2823,8 +2833,12 @@ class _MachineView {
this.setUpTeamLabel = 'Set up',
this.apiModels = const [],
this.localModels = const [],
+ this.access = const [],
});
+ /// What the machine can reach, by account (#3047): the row's last section, for every member who sees it.
+ final List<SuperTabAccessEntry> access;
+
final String id, name, details, tip;
/// Its [problem] is this Mac's, its own person looking: no Harness Team account yet, which they can set up here.
@@ -3448,6 +3462,17 @@ class _MachineReadings extends StatelessWidget {
],
),
),
+ // Last, by account (#3047, design section 6).
+ if (view.access.isNotEmpty)
+ (
+ 'Access',
+ null,
+ (_) => SuperTabMachineAccessLines(
+ key: ValueKey('super-machine-access-${view.id}'),
+ entries: view.access,
+ ownerName: view.owner?.shownName,
+ ),
+ ),
];
return Padding(
key: ValueKey('super-machine-readings-${view.id}'),
diff --git a/desktop/test/screenshots/machine-access/machine-access-add-dark.png b/desktop/test/screenshots/machine-access/machine-access-add-dark.png
new file mode 100644
index 000000000..5dfb1e2b7
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-add-dark.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-add-light.png b/desktop/test/screenshots/machine-access/machine-access-add-light.png
new file mode 100644
index 000000000..db7f7c1b0
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-add-light.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-configure-dark.png b/desktop/test/screenshots/machine-access/machine-access-configure-dark.png
new file mode 100644
index 000000000..077b51642
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-configure-dark.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-configure-light.png b/desktop/test/screenshots/machine-access/machine-access-configure-light.png
new file mode 100644
index 000000000..b09030b2f
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-configure-light.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-row-dark.png b/desktop/test/screenshots/machine-access/machine-access-row-dark.png
new file mode 100644
index 000000000..c8dd1bec1
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-row-dark.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-row-light.png b/desktop/test/screenshots/machine-access/machine-access-row-light.png
new file mode 100644
index 000000000..a09c84f70
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-row-light.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-share-dark.png b/desktop/test/screenshots/machine-access/machine-access-share-dark.png
new file mode 100644
index 000000000..b8be7535b
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-share-dark.png differ
diff --git a/desktop/test/screenshots/machine-access/machine-access-share-light.png b/desktop/test/screenshots/machine-access/machine-access-share-light.png
new file mode 100644
index 000000000..2c8e97d4a
Binary files /dev/null and b/desktop/test/screenshots/machine-access/machine-access-share-light.png differ
diff --git a/desktop/test/super_tab_machine_access_test.dart b/desktop/test/super_tab_machine_access_test.dart
new file mode 100644
index 000000000..83b494943
--- /dev/null
+++ b/desktop/test/super_tab_machine_access_test.dart
@@ -0,0 +1,775 @@
+// Task #3047 (phase 1, docs/design/2026-11-05-machine-access.md section 6): what each machine can reach, per macOS
+// account. Every member who sees a machine reads its Access on the expanded row; its owner keeps the list in Configure
+// (backend `machine.access`). Memory store and a fake sign-in only: nothing here touches the real CLI.
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/detail_dialog.dart';
+import 'package:harness/super_tabs/machines.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+import 'super_tab_machines_test.dart' show openMachineDetails;
+import 'support/capture.dart';
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];
+
+const _gray = {
+ 'id': 'gray',
+ 'email': '[email protected]',
+ 'role': 'member',
+ 'name': 'Gray',
+};
+const _dee = {
+ 'id': 'dee',
+ 'email': '[email protected]',
+ 'role': 'member',
+ 'name': 'Dee',
+};
+
+Map<String, dynamic> _entry(
+ String id,
+ String name, {
+ String account = 'own',
+ String state = 'ok',
+ bool teammates = false,
+ bool production = false,
+ String? note,
+ String? saidBy,
+}) => {
+ 'id': id,
+ 'name': name,
+ 'account': account,
+ 'state': state,
+ if (teammates) 'teammates': true,
+ if (production) 'production': true,
+ 'note': ?note,
+ 'addedBy': saidBy ?? 'owner',
+ 'addedAt': '2026-11-05T09:00:00Z',
+ 'saidBy': ?saidBy,
+};
+
+/// The owner's list in the mockup: three own entries (one with a note, one Dee said), and two in the Team account.
+final _ownerList = [
+ _entry('a1', 'Fusion 360'),
+ _entry('a2', 'ArgoCD', note: 'connection info in ~/.argocd/config'),
+ _entry('a3', 'Slack (dee@)', state: 'unconfirmed', saidBy: 'dee'),
+ _entry('a4', 'Lamp', account: 'team'),
+ _entry('a5', "Tony's iPhone", account: 'team'),
+];
+
+/// The Mac [id] owned by [contributor], with [access] on its own entry, as the Swarm sends it.
+Map<String, dynamic> _mac(
+ String id, {
+ String contributor = 'owner',
+ String? name,
+ List<Map<String, dynamic>>? access,
+}) => {
+ 'machineId': id,
+ 'name': ?name,
+ 'contributorId': contributor,
+ 'maxAgents': 4,
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
+ 'access': ?access,
+};
+
+/// [mac]'s Harness Team account: its own pool, which never carries a list of its own.
+Map<String, dynamic> _team(String mac, {String contributor = 'owner'}) => {
+ 'machineId': '$mac-team',
+ 'name': '$mac (Team)',
+ 'contributorId': contributor,
+ 'hostMachineId': mac,
+ 'maxAgents': 4,
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
+};
+
+List<Map<String, dynamic>> _accessCommands(ConversationServer server) => [
+ for (final p in server.posts)
+ if ((p['command'] as Map?)?['type'] == 'machine.access')
+ Map<String, dynamic>.from(p['command'] as Map),
+];
+
+void _theme(Brightness brightness) {
+ // The design tokens follow the app's brightness, which main.dart sets from the theme.
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+}
+
+/// The Machines list on [server], read as [account], its machines expanded.
+Future<dynamic> _mountRows(
+ WidgetTester tester,
+ ConversationServer server, {
+ String account = 'owner',
+ Brightness brightness = Brightness.light,
+ GlobalKey? picture,
+}) async {
+ _theme(brightness);
+ final c = server.controller(account: account);
+ await c.refresh();
+ for (final m in server.state['machines'] as List) {
+ if ((m as Map)['hostMachineId'] == null) {
+ c.toggleMachineExpanded(m['machineId'] as String);
+ }
+ }
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: RepaintBoundary(
+ key: picture,
+ child: SuperTabMachines(controller: c, onAddAgent: (_) {}),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+/// The owner's Configure for machine `m`, this computer, as the machine's details open it.
+Future<dynamic> _openConfigure(
+ WidgetTester tester,
+ SuperTabLaunchFixture f, {
+ Brightness brightness = Brightness.light,
+ String row = 'm',
+}) async {
+ _theme(brightness);
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabMachines(
+ controller: c,
+ app: f.app,
+ onAddAgent: (_) {},
+ readLocal: (_) async => null,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await openMachineDetails(tester, find.byKey(ValueKey('super-machine-$row')));
+ await tester.tap(find.widgetWithText(TextButton, 'Configure'));
+ await tester.pumpAndSettle();
+ return c;
+}
+
+SuperTabLaunchFixture _fixture(List<Map<String, dynamic>> machines) {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ _dee,
+ ];
+ f.connection.server.state['machines'] = machines;
+ return f;
+}
+
+Future<void> _doneRows(WidgetTester tester, dynamic c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+Future<void> _doneConfigure(
+ WidgetTester tester,
+ SuperTabLaunchFixture f,
+ dynamic c,
+) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+}
+
+final _configure = find.byType(SuperTabDetailDialog);
+Finder _inConfigure(Finder matching) =>
+ find.descendant(of: _configure, matching: matching);
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ setUp(() {
+ // Room for the Configure dialog's whole Access section.
+ final view =
+ TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;
+ view.physicalSize = const Size(1000, 1100);
+ view.devicePixelRatio = 1;
+ });
+ tearDown(() {
+ final view =
+ TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;
+ view.resetPhysicalSize();
+ view.resetDevicePixelRatio();
+ });
+
+ group('the expanded row', () {
+ testWidgets(
+ "says what it can reach by account, to every member who sees it, its owner's account by name",
+ (tester) async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ _gray,
+ _dee,
+ ];
+ server.state['machines'] = [
+ _mac(
+ 'studio',
+ contributor: 'gray',
+ name: "Gray's Mac",
+ access: [
+ _entry('a1', 'Fusion 360'),
+ _entry('a2', 'Email (dee@)', state: 'unconfirmed', saidBy: 'dee'),
+ _entry('a3', 'Lamp', account: 'team'),
+ _entry('a4', 'Flutter', account: 'team'),
+ ],
+ ),
+ _team('studio', contributor: 'gray'),
+ _mac(
+ 'kiln',
+ contributor: 'gray',
+ name: 'Mac Studio',
+ access: [_entry('b1', 'Prod DB read-only', production: true)],
+ ),
+ ];
+ // Another member reads it: the owner of the Swarm, not of the machine.
+ final c = await _mountRows(tester, server);
+ final studio = find.byKey(
+ const ValueKey('super-machine-access-studio'),
+ );
+ expect(studio, findsOneWidget);
+ expect(
+ find.descendant(
+ of: studio,
+ matching: find.text(
+ "Gray's account: Fusion 360 · Email (dee@) waiting for Gray",
+ findRichText: true,
+ ),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: studio,
+ matching: find.text(
+ 'Team account: Lamp · Flutter',
+ findRichText: true,
+ ),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-machine-access-kiln')),
+ matching: find.text(
+ "Gray's account: Prod DB read-only (production)",
+ findRichText: true,
+ ),
+ ),
+ findsOneWidget,
+ );
+ // Last, under the readings: after Subscriptions.
+ expect(
+ tester.getTopLeft(studio).dy,
+ greaterThan(
+ tester
+ .getTopLeft(
+ find
+ .descendant(
+ of: find.byKey(
+ const ValueKey('super-machine-readings-studio'),
+ ),
+ matching: find.text(
+ 'Subscriptions',
+ findRichText: true,
+ ),
+ )
+ .first,
+ )
+ .dy,
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ await _doneRows(tester, c);
+ },
+ );
+
+ testWidgets(
+ 'an entry not working says so; a machine with nothing listed has no Access',
+ (tester) async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ _gray,
+ ];
+ server.state['machines'] = [
+ _mac(
+ 'studio',
+ contributor: 'gray',
+ access: [
+ // Phase 2's state, from a newer server: shown, never dropped.
+ _entry('a1', 'Email (dee@)', state: 'notWorking'),
+ ],
+ ),
+ _mac('pro', contributor: 'gray'),
+ ];
+ final c = await _mountRows(tester, server);
+ expect(
+ find.text(
+ "Gray's account: Email (dee@) not working",
+ findRichText: true,
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('super-machine-access-pro')),
+ findsNothing,
+ );
+ await _doneRows(tester, c);
+ },
+ );
+ });
+
+ group("the owner's Configure", () {
+ testWidgets(
+ 'lists what it can reach by account, a note under its entry, and who said one not yet confirmed',
+ (tester) async {
+ final f = _fixture([_mac('m', access: _ownerList), _team('m')]);
+ final c = await _openConfigure(tester, f);
+ final section = find.byKey(const ValueKey('machine-access-section'));
+ expect(section, findsOneWidget);
+ expect(_inConfigure(find.text('Access')), findsOneWidget);
+ double top(String text) =>
+ tester.getTopLeft(_inConfigure(find.text(text)).first).dy;
+ expect(top('Your account'), lessThan(top('Fusion 360')));
+ expect(top('Fusion 360'), lessThan(top('ArgoCD')));
+ expect(
+ top('ArgoCD'),
+ lessThan(top('Note: connection info in ~/.argocd/config')),
+ );
+ expect(
+ top('Note: connection info in ~/.argocd/config'),
+ lessThan(top('Slack (dee@)')),
+ );
+ expect(top('Slack (dee@)'), lessThan(top('Team account')));
+ expect(top('Team account'), lessThan(top('Lamp')));
+ expect(top('Lamp'), lessThan(top("Tony's iPhone")));
+ expect(top("Tony's iPhone"), lessThan(top('Add access…')));
+ expect(
+ _inConfigure(find.text('waiting for you: Dee said it')),
+ findsOneWidget,
+ );
+ // Each own-account entry it confirmed can be shared; a Team-account entry runs teammates' work anyway.
+ for (final id in ['a1', 'a2']) {
+ expect(
+ find.byKey(ValueKey('machine-access-teammates-$id')),
+ findsOneWidget,
+ reason: id,
+ );
+ }
+ for (final id in ['a3', 'a4', 'a5']) {
+ expect(
+ find.byKey(ValueKey('machine-access-teammates-$id')),
+ findsNothing,
+ reason: id,
+ );
+ }
+ expect(_inConfigure(find.text('Teammates may use')), findsNWidgets(2));
+ expect(tester.takeException(), isNull);
+ await _doneConfigure(tester, f, c);
+ },
+ );
+
+ testWidgets('a Mac without a Team account lists only Your account', (
+ tester,
+ ) async {
+ final f = _fixture([
+ _mac('m', access: [_entry('a1', 'Fusion 360')]),
+ ]);
+ final c = await _openConfigure(tester, f);
+ expect(_inConfigure(find.text('Your account')), findsOneWidget);
+ expect(_inConfigure(find.text('Team account')), findsNothing);
+ await _doneConfigure(tester, f, c);
+ });
+
+ testWidgets(
+ 'Add access… sends the name, where, Production system and the note',
+ (tester) async {
+ final f = _fixture([_mac('m'), _team('m')]);
+ final c = await _openConfigure(tester, f);
+ await tester.tap(_inConfigure(find.text('Add access…')));
+ await tester.pumpAndSettle();
+ expect(find.text('Add access'), findsOneWidget);
+ expect(
+ find.text('Like: Email (dee@), Prod DB read-only'),
+ findsOneWidget,
+ );
+ expect(find.text('Your account'), findsWidgets);
+ await tester.enterText(
+ find.byKey(const ValueKey('machine-access-name')),
+ 'Prod DB read-only',
+ );
+ await tester.tap(
+ find.byKey(const ValueKey('machine-access-where-team')),
+ );
+ await tester.tap(
+ find.byKey(const ValueKey('machine-access-production')),
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('machine-access-note')),
+ 'profile prod-ro in ~/.pgpass',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('machine-access-add')));
+ await tester.pumpAndSettle();
+ expect(_accessCommands(f.connection.server), [
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'add',
+ 'name': 'Prod DB read-only',
+ 'account': 'team',
+ 'production': true,
+ 'note': 'profile prod-ro in ~/.pgpass',
+ },
+ ]);
+ // Added: the Add dialog closes, Configure stays.
+ expect(find.text('Add access'), findsNothing);
+ expect(_configure, findsOneWidget);
+ await _doneConfigure(tester, f, c);
+ },
+ );
+
+ testWidgets(
+ 'on a Mac without a Team account, Add offers only Your account and sends no empty fields',
+ (tester) async {
+ final f = _fixture([_mac('m')]);
+ final c = await _openConfigure(tester, f);
+ await tester.tap(_inConfigure(find.text('Add access…')));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('machine-access-where-team')),
+ findsNothing,
+ );
+ // Nothing to add until it has a name.
+ final add = find.byKey(const ValueKey('machine-access-add'));
+ expect(tester.widget<FilledButton>(add).onPressed, isNull);
+ await tester.enterText(
+ find.byKey(const ValueKey('machine-access-name')),
+ ' Fusion 360 ',
+ );
+ await tester.pump();
+ await tester.tap(add);
+ await tester.pumpAndSettle();
+ expect(_accessCommands(f.connection.server), [
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'add',
+ 'name': 'Fusion 360',
+ 'account': 'own',
+ },
+ ]);
+ await _doneConfigure(tester, f, c);
+ },
+ );
+
+ testWidgets("a refused add says the server's reason and stays open", (
+ tester,
+ ) async {
+ final f = _fixture([_mac('m')]);
+ f.connection.server
+ ..refuse = {
+ 'code': 'ACCESS_SECRET',
+ 'message': 'That looks like a password or key. Write where it lives instead, such as a file or profile name.',
+ }
+ ..refuseStatus = 400;
+ final c = await _openConfigure(tester, f);
+ await tester.tap(_inConfigure(find.text('Add access…')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('machine-access-name')),
+ 'ghp_abc123',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('machine-access-add')));
+ await tester.pumpAndSettle();
+ expect(find.text('Add access'), findsOneWidget);
+ expect(
+ find.text(
+ 'That looks like a password or key. Write where it lives instead, such as a file or profile name.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));
+ await tester.pumpAndSettle();
+ await _doneConfigure(tester, f, c);
+ });
+
+ testWidgets(
+ 'Teammates may use asks first, naming the entry; Cancel sends nothing, Let them use it sends teammates',
+ (tester) async {
+ final f = _fixture([_mac('m', access: _ownerList), _team('m')]);
+ final c = await _openConfigure(tester, f);
+ final box = find.byKey(const ValueKey('machine-access-teammates-a1'));
+ await tester.tap(box);
+ await tester.pumpAndSettle();
+ expect(
+ find.text("Let teammates' work run in your account?"),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining(
+ "Teammates' tasks in this Swarm that need Fusion 360",
+ ),
+ findsOneWidget,
+ );
+ final cancel = find.widgetWithText(TextButton, 'Cancel').last;
+ expect(tester.widget<TextButton>(cancel).autofocus, isTrue);
+ await tester.tap(cancel);
+ await tester.pumpAndSettle();
+ expect(_accessCommands(f.connection.server), isEmpty);
+ expect(tester.widget<Checkbox>(box).value, isFalse);
+
+ await tester.tap(box);
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('machine-access-teammates-allow')),
+ );
+ await tester.pumpAndSettle();
+ expect(_accessCommands(f.connection.server), [
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'change',
+ 'entryId': 'a1',
+ 'teammates': true,
+ },
+ ]);
+ expect(
+ find.text("Let teammates' work run in your account?"),
+ findsNothing,
+ );
+ await _doneConfigure(tester, f, c);
+ },
+ );
+
+ testWidgets('turning Teammates may use off sends at once', (tester) async {
+ final f = _fixture([
+ _mac('m', access: [_entry('a1', 'Fusion 360', teammates: true)]),
+ ]);
+ final c = await _openConfigure(tester, f);
+ final box = find.byKey(const ValueKey('machine-access-teammates-a1'));
+ expect(tester.widget<Checkbox>(box).value, isTrue);
+ await tester.tap(box);
+ await tester.pumpAndSettle();
+ expect(
+ find.text("Let teammates' work run in your account?"),
+ findsNothing,
+ );
+ expect(_accessCommands(f.connection.server), [
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'change',
+ 'entryId': 'a1',
+ 'teammates': false,
+ },
+ ]);
+ await _doneConfigure(tester, f, c);
+ });
+
+ testWidgets('Confirm and Not right answer an entry someone else said', (
+ tester,
+ ) async {
+ final f = _fixture([_mac('m', access: _ownerList), _team('m')]);
+ final c = await _openConfigure(tester, f);
+ await tester.tap(find.byKey(const ValueKey('machine-access-confirm-a3')));
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('machine-access-not-right-a3')),
+ );
+ await tester.pumpAndSettle();
+ expect(_accessCommands(f.connection.server), [
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'confirm',
+ 'entryId': 'a3',
+ },
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'remove',
+ 'entryId': 'a3',
+ },
+ ]);
+ await _doneConfigure(tester, f, c);
+ });
+
+ testWidgets("Remove sends remove, and a refusal says the server's reason", (
+ tester,
+ ) async {
+ final f = _fixture([_mac('m', access: _ownerList), _team('m')]);
+ final c = await _openConfigure(tester, f);
+ await tester.tap(find.byKey(const ValueKey('machine-access-remove-a4')));
+ await tester.pumpAndSettle();
+ expect(_accessCommands(f.connection.server), [
+ {
+ 'type': 'machine.access',
+ 'machineId': 'm',
+ 'action': 'remove',
+ 'entryId': 'a4',
+ },
+ ]);
+ f.connection.server
+ ..refuse = {
+ 'code': 'MACHINE_REMOVED',
+ 'message': 'This machine is being removed from the Swarm.',
+ }
+ ..refuseStatus = 400;
+ await tester.tap(find.byKey(const ValueKey('machine-access-remove-a1')));
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('machine-access-error')),
+ matching: find.text('This machine is being removed from the Swarm.'),
+ ),
+ findsOneWidget,
+ );
+ await _doneConfigure(tester, f, c);
+ });
+ });
+
+ group('anyone else', () {
+ testWidgets(
+ "a teammate's machine has no Configure, and its details no Access to change",
+ (tester) async {
+ final f = _fixture([_mac('m', contributor: 'dee', access: _ownerList)]);
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMachines(
+ controller: c,
+ app: f.app,
+ onAddAgent: (_) {},
+ readLocal: (_) async => null,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await openMachineDetails(
+ tester,
+ find.byKey(const ValueKey('super-machine-m')),
+ );
+ expect(find.widgetWithText(TextButton, 'Configure'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('machine-access-section')),
+ findsNothing,
+ );
+ expect(find.text('Add access…'), findsNothing);
+ expect(find.byType(Checkbox), findsNothing);
+ await _doneConfigure(tester, f, c);
+ },
+ );
+
+ testWidgets(
+ "a Harness Team account's own row has no Access in its Configure: its list is on its Mac",
+ (tester) async {
+ // Its Mac is not in this Swarm, so the Team account shows on its own row.
+ final f = _fixture([
+ {..._team('elsewhere'), 'machineId': 'm'},
+ ]);
+ final c = await _openConfigure(tester, f);
+ expect(_configure, findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('machine-access-section')),
+ findsNothing,
+ );
+ await _doneConfigure(tester, f, c);
+ },
+ );
+ });
+
+ testWidgets('screenshots', (tester) async {
+ for (final (brightness, name) in [
+ (Brightness.light, 'light'),
+ (Brightness.dark, 'dark'),
+ ]) {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ _gray,
+ _dee,
+ ];
+ server.state['machines'] = [
+ _mac(
+ 'studio',
+ contributor: 'gray',
+ name: "Gray's Mac",
+ access: [
+ _entry('a1', 'Fusion 360'),
+ _entry('a2', 'Email (dee@)', state: 'unconfirmed', saidBy: 'dee'),
+ _entry('a3', 'Lamp', account: 'team'),
+ _entry('a4', 'Flutter', account: 'team'),
+ _entry('a5', "Tony's iPhone", account: 'team'),
+ ],
+ ),
+ _team('studio', contributor: 'gray'),
+ _mac(
+ 'kiln',
+ contributor: 'gray',
+ name: 'Mac Studio',
+ access: [_entry('b1', 'Prod DB read-only', production: true)],
+ ),
+ ];
+ final c = await _mountRows(tester, server, brightness: brightness);
+ await captureWindow(tester, shots, 'machine-access-row-$name');
+ await _doneRows(tester, c);
+
+ final f = _fixture([
+ _mac(
+ 'm',
+ access: [
+ ..._ownerList.take(3),
+ _entry('a6', 'Prod DB read-only', production: true),
+ ..._ownerList.skip(3),
+ ],
+ ),
+ _team('m'),
+ ]);
+ final d = await _openConfigure(tester, f, brightness: brightness);
+ await captureWindow(tester, shots, 'machine-access-configure-$name');
+ await tester.tap(_inConfigure(find.text('Add access…')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('machine-access-name')),
+ 'Fusion 360',
+ );
+ await tester.pump();
+ await captureWindow(tester, shots, 'machine-access-add-$name');
+ await tester.tap(find.widgetWithText(TextButton, 'Cancel').last);
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('machine-access-teammates-a1')),
+ );
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'machine-access-share-$name');
+ await tester.tap(find.widgetWithText(TextButton, 'Cancel').last);
+ await tester.pumpAndSettle();
+ await _doneConfigure(tester, f, d);
+ }
+ }, skip: shots == null);
+}
diff --git a/desktop/web/index.html b/desktop/web/index.html
index 479ab3dcc..2079a65af 100644
--- a/desktop/web/index.html
+++ b/desktop/web/index.html
@@ -82,6 +82,22 @@
}
pin();
new MutationObserver(pin).observe(document.head, { childList: true });
+ // The app is one fixed canvas laid out for the screen minus the keyboard (ViewRoom). When
+ // the keyboard comes up again after it was dismissed, Safari pans the page to reveal the
+ // focused field: the canvas leaves the screen, and the top bar and the message box are
+ // gone above blank space. The app never scrolls the page, so any pan is Safari's; put it
+ // back at the top, unless the visitor pinch-zoomed and is looking around on purpose.
+ var vv = window.visualViewport;
+ function unpan() {
+ if (vv && vv.scale > 1.01) return;
+ var panned = (vv && (vv.offsetTop || vv.offsetLeft)) || window.scrollX || window.scrollY;
+ if (panned) window.scrollTo(0, 0);
+ }
+ window.addEventListener('scroll', unpan);
+ if (vv) {
+ vv.addEventListener('scroll', unpan);
+ vv.addEventListener('resize', unpan);
+ }
})();
</script>
<!-- Inline Flutter's generated loader so startup needs no extra script round trip. -->
diff --git a/docs/plans/2026-11-05-machine-access-plan.md b/docs/plans/2026-11-05-machine-access-plan.md
new file mode 100644
index 000000000..e39a5aa84
--- /dev/null
+++ b/docs/plans/2026-11-05-machine-access-plan.md
@@ -0,0 +1,151 @@
+# What each machine can reach, phase 1 — Implementation Plan
+
+> Task #3047. Worked by the project's Engineer way of working (project instructions, Engineer): each plan task test first,
+> its failing test committed before its code; one independent review per review step on the pull request. Desktop (Task 5)
+> shares no files with Tasks 1–4 and runs in parallel by its own subagent.
+
+**Goal:** Each machine in a Swarm keeps a short Access list ("Lamp", "Fusion 360", "Email (dee@)") per macOS account; a
+task names the access it needs; the route and the backend's start check send the work only to a machine and account that
+has it, and say why when not.
+
+**Architecture:** The list rides on the Mac's own contribution (`ContributedMachine.access`, backend), changed one entry at a
+time by a new command `machine.access`. Who may see `note` and `check` is enforced in `visibleState`. Placement and refusal
+are one helper (`machineAccess.ts`) used by the start (`teamMachineFor`, `admitMachineStart`) and the route-decision check
+(`candidateRefusal`); the CLI route applies the same rule to the machine records it already reads. Desktop adds an Access
+section to Configure and an Access line to the expanded machine row.
+
+**Tech Stack:** TypeScript (backend, zod, vitest; CLI, node test runner), Flutter/Dart (Desktop).
+
+**Spec:** [docs/design/2026-11-05-machine-access.md](../design/2026-11-05-machine-access.md) (PR #3030), phase 1 of its
+section 7, with open questions decided by River (11-05): one list per machine per Swarm; per-entry teammates sharing ships
+now behind the own-account warning; a Team account's MCP server comes only through the owner's Configure copy (phase 3,
+with suggestions); case-insensitive exact names, the route suggests the closest; entries per machine.
+
+## Global Constraints
+
+- At most 32 entries per machine per Swarm; `name` 1 to 60 characters; `note` and `check` at most 200 characters.
+- `account` is `own` or `team`; `team` only on a Mac that has a Harness Team account in this Swarm.
+- `state` is `ok` or `unconfirmed` in phase 1 (`notWorking` is phase 2). Only `ok` counts for routing and starts.
+- An `unconfirmed` entry is removed 7 days after it was added.
+- A name or note that looks like a secret is refused: anything `findCredentials` finds, `-----BEGIN`, `user:pass@`, the
+ prefixes `sk-`, `ghp_`, `gho_`, `ghs_`, `github_pat_`, `xox?-`, `AKIA`, or a run of 20+ key-like characters
+ (`[A-Za-z0-9+=_-]`) that mixes letters and digits.
+- `teammates` is set to true only from the owner's own session (a person actor), never by an agent; an agent never turns
+ `production` off.
+- `check` is read only by the machine's owner. `note` only by the owner and by agents running on that machine in that
+ entry's account (the Mac for `own`, its Team account pool for `team`).
+- Names match case-insensitively, trimmed.
+- Copy (route and start refusals), exact:
+ - `No ${name} here.` + ` Did you mean ${closest}?` (route only, when a close name exists)
+ - `${name} on ${machine} is waiting for ${owner} to confirm.`
+ - `${name} is in ${owner}'s own account, not shared with teammates.`
+ - `${name} is in the Harness Team account on ${machine}, which runs only teammates' work.`
+- Swarm code stays out of `cli/src/core`. Desktop tests use a memory store and a fake sign-in.
+
+## Review Focus
+
+1. A teammate's task needing an own-account entry with `teammates` on, on a Mac with a Team account: the start must stay on
+ the Mac (not move to the Team account), and the route must offer the Mac, not the Team account. (Task 3, Task 4 tests.)
+2. Team-written code needing an own-account entry: it still goes to the Team account, and is refused there for the
+ missing entry, never run in the owner's account. (Task 3 test.)
+3. An agent of the owner (`machineOwnerId` = owner) on another machine reads no `note`: owner rights are the owner's own
+ session only. (Task 2 test.)
+4. Saving the contribution again (Desktop's re-save) keeps the list; removing the machine drops it. (Task 1 test.)
+5. A task's `requires.access` with a different case or spacing (" lamp ") matches "Lamp". (Task 3, Task 4 tests.)
+
+---
+
+### Task 1: The list and `machine.access`
+
+**Files:**
+- Create: `backend/src/superTabs/machineAccess.ts`
+- Modify: `backend/src/superTabs/machines.ts` (`ContributedMachine.access`), `backend/src/superTabs/commands.ts` (schema,
+ handler, kept on `machine.contribute`, prune), `backend/src/superTabs/store.ts` (askedIn loaded, refused for Team
+ sessions, prune on readings)
+- Test: `backend/src/superTabs/machineAccess.test.ts`
+
+**Interfaces:**
+- Produces:
+ - `interface AccessEntry { id: string; name: string; account: 'own' | 'team'; state: 'ok' | 'unconfirmed'; teammates?: true;
+ production?: true; check?: string; note?: string; addedBy: string; addedAt: string; saidBy?: string;
+ askedIn?: { conversationId: string; messageId: string } }`
+ - `ContributedMachine.access?: AccessEntry[]`
+ - `secretLike(text: string): boolean`, `sameAccessName(a: string, b: string): boolean`, `expireAccess(state, now): void`,
+ `MAX_ACCESS = 32`, `UNCONFIRMED_ACCESS_MS = 7 * 86_400_000`
+ - Command `{ type: 'machine.access', machineId, action: 'add' | 'change' | 'confirm' | 'remove', entryId?, name?,
+ account?, teammates?, production?, note?: string | null, check?: string | null, askedIn? }`; result `{ entryId }`.
+
+- [ ] Step 1: failing tests: the owner adds (state ok, addedBy owner, 16-hex id); 33rd refused `ACCESS_FULL`; duplicate name
+ in the same account (any case) refused `ACCESS_EXISTS`; `team` on a Mac without a Team account refused; on a Team
+ account's own pool `NOT_FOUND`; secret-looking name and note refused `ACCESS_SECRET` (`ghp_…`, `sk-…`, `user:pass@host`,
+ `-----BEGIN`, `AKIA…`, a 24-char random run) while "connection info in ~/.argocd/config" and "Email (dee@)" pass; a
+ teammate, the Swarm's owner, a Buddy and a Team session refused; the Lead passing on the owner's message from the last
+ day in a chat it leads adds `ok` with `askedIn`; the Lead passing on someone else's message, an owner's message older
+ than a day, or one in a chat it does not lead adds `unconfirmed` with `saidBy`; with no `askedIn` an agent is refused;
+ the PM can never set `teammates: true` (`OWNER_SESSION_REQUIRED`) nor turn `production` off; confirm by the owner (or
+ the Lead with the owner's word) sets ok; the Lead removes an unconfirmed entry without the owner's word, but no ok one;
+ an unconfirmed entry 7 days old is gone after the next command; re-saving the contribution keeps the list.
+- [ ] Step 2: run `cd backend && npx vitest run src/superTabs/machineAccess.test.ts` — FAIL (`machine.access` unknown).
+- [ ] Step 3: implement; commit.
+
+### Task 2: Who reads what
+
+**Files:** Modify `backend/src/superTabs/model.ts` (`visibleState`); Test `backend/src/superTabs/machineAccess.test.ts`.
+
+**Interfaces:** Consumes `AccessEntry`. Produces `visibleAccess(state, pool, actor): AccessEntry[]` in `machineAccess.ts`.
+
+- [ ] Step 1: failing tests: the owner's read has `check` and `note`; another member's read has neither; an agent on the
+ Mac reads the own entry's note but not the team entry's, an agent on the Team account the reverse; an agent of the owner
+ on another machine reads no note and no check; the entries' names, account and state reach every member who sees the
+ machine.
+- [ ] Step 2: run — FAIL. Step 3: implement; commit.
+
+### Task 3: `requires.access` and the start check
+
+**Files:** Modify `backend/src/superTabs/model.ts` (`TaskRequirement.access`), `commands.ts` (task schema; `agent.start`
+and `candidateRefusal` pass the task's access), `machines.ts` (`teamMachineFor`, `teamWorkCheck`, `teamWorkRefusal`
+take `access`; `admitMachineStart` refuses); Test `backend/src/superTabs/machineAccess.test.ts`.
+
+**Interfaces:**
+- Produces: `accessRefusal(state, machineId, project, needed: string[], ownerName?: string): TeamWorkRefusal | null`
+ (code `ACCESS_MISSING`), `sharedOwnAccess(pool, needed): boolean`, `taskAccess(group): string[]`.
+
+- [ ] Step 1: failing tests: a task with `requires: { access: ['Lamp'] }` is stored; a start of an older CLI (no
+ `needs.access` anywhere in its request) on a machine without Lamp is refused `ACCESS_MISSING` "No Lamp here."; a
+ teammate's start where Lamp is an unshared own entry is refused "… not shared with teammates" and the Team account never
+ counts the own entry; with `teammates` on, the teammate's start stays on the Mac, as the owner; Team-written code still
+ goes to the Team account and is refused; an unconfirmed entry refuses "… waiting for … to confirm"; the owner's own task
+ needing a Team-account entry is refused; " lamp " matches "Lamp"; a start with no requirement is unchanged.
+- [ ] Step 2: run — FAIL. Step 3: implement; commit.
+
+### Task 4: `needs.access` in the route (CLI)
+
+**Files:** Modify `cli/src/superTabs/route.ts` (`Needs.access`, parse), `cli/src/superTabs/routeCommand.ts`
+(`taskRequirement().access`, per-candidate refusal, fold, closest name); Test `cli/src/superTabs/routeCommand.spec.ts`.
+
+**Interfaces:** Consumes the machine records' `access` (Task 1 shape, after Task 2's stripping) and `teamWork.ownAccount`.
+Produces `accessReasons(pool, macPool, projectOwner, needed, people): string[]` in `routeCommand.ts`.
+
+- [ ] Step 1: failing tests: `needs.access: ["Lamp"]` and a task's `requires.access` both leave out a machine without it
+ with "No Lamp here."; "Desk lamp" elsewhere gives " Did you mean Desk lamp?"; a teammate's task is offered the Team
+ account's Lamp and not the owner's unshared own Lamp; with `teammates` on the Mac itself is offered (not folded); an
+ unconfirmed entry is left out with its line; members on a machine without it are left out too; `startRequirements`
+ gains no `access` key (older hosts' strict schema).
+- [ ] Step 2: run `cd cli && npx tsx --test src/superTabs/routeCommand.spec.ts` — FAIL. Step 3: implement; commit.
+
+### Task 5: Desktop — Configure's Access and the expanded row
+
+**Files:** Create `desktop/lib/super_tabs/machine_access.dart`; modify `desktop/lib/super_tabs/machines.dart` (Configure
+dialog section, expanded row line); Test `desktop/test/super_tab_machine_access_test.dart`.
+
+**Interfaces:** Consumes the pool map's `access` list (Task 1 shape) and sends `machine.access` (Task 1 command) as the
+owner, as `machine.ownAccountWork` is sent today.
+
+- [ ] Step 1: failing widget tests (memory store, fake sign-in): the expanded row shows "Access" with "Gray's account: …"
+ and "Team account: …", "not working"/"waiting for …" states, "(production)"; a non-owner sees no Configure Access
+ section; the owner's Configure lists entries by account with the note under its entry, Add access… opens the add dialog
+ (Name, Where, Production system) and sends `machine.access` add; "Teammates may use" asks "Let teammates' work run in
+ your account?" naming the entry before sending `teammates: true`, and Cancel sends nothing; Confirm / Not right on an
+ unconfirmed entry send confirm / remove; remove sends remove.
+- [ ] Step 2: run `cd desktop && flutter test test/super_tab_machine_access_test.dart` — FAIL. Step 3: implement.
+- [ ] Step 4: light and dark screenshots of Configure and the expanded row (golden-style screenshot run); commit.
diff --git a/website/scripts/ios-viewport-pin.test.mjs b/website/scripts/ios-viewport-pin.test.mjs
new file mode 100644
index 000000000..c5a419c34
--- /dev/null
+++ b/website/scripts/ios-viewport-pin.test.mjs
@@ -0,0 +1,113 @@
+// iOS Safari pans the page when the keyboard comes up again after it was dismissed: the visual
+// viewport (or the document) scrolls, the app's fixed canvas leaves the screen, and the top bar and
+// the message box are out of sight above blank space. desktop/web/index.html puts the page back at
+// the top. This runs that inline script against a fake window.
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { runInNewContext } from 'node:vm';
+import { describe, expect, it } from 'vitest';
+
+const page = readFileSync(join(process.cwd(), '..', 'desktop', 'web', 'index.html'), 'utf8');
+const script = [...page.matchAll(/<script>([\s\S]*?)<\/script>/g)]
+ .map((m) => m[1])
+ .find((body) => body.includes('maximum-scale=1.0'));
+
+const iPhone = 'Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 Safari/604.1';
+const android = 'Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36';
+const desktop = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15';
+
+function load({ userAgent = iPhone, platform = 'iPhone', viewport = {} } = {}) {
+ const windowListeners = {};
+ const viewportListeners = {};
+ const scrolls = [];
+ const visualViewport = {
+ offsetTop: 0,
+ offsetLeft: 0,
+ scale: 1,
+ ...viewport,
+ addEventListener(type, listener) { (viewportListeners[type] ||= []).push(listener); },
+ };
+ const win = {
+ scrollX: 0,
+ scrollY: 0,
+ visualViewport: viewport === null ? undefined : visualViewport,
+ addEventListener(type, listener) { (windowListeners[type] ||= []).push(listener); },
+ scrollTo(x, y) { scrolls.push([x, y]); },
+ };
+ const metas = [];
+ runInNewContext(script, {
+ window: win,
+ navigator: { userAgent, platform, maxTouchPoints: platform === 'iPhone' ? 5 : 0 },
+ document: {
+ head: {},
+ querySelectorAll: () => metas,
+ },
+ MutationObserver: class { observe() {} },
+ });
+ return {
+ win,
+ visualViewport,
+ scrolls,
+ fire(target, type) {
+ const listeners = target === win ? windowListeners : viewportListeners;
+ (listeners[type] || []).forEach((listener) => listener({ type }));
+ },
+ listening: () => Object.keys(windowListeners).length + Object.keys(viewportListeners).length,
+ };
+}
+
+describe('iOS Safari keyboard pan', () => {
+ it('puts the page back at the top when the visual viewport is panned down', () => {
+ const page = load();
+ page.visualViewport.offsetTop = 336;
+ page.fire(page.visualViewport, 'scroll');
+ expect(page.scrolls).toEqual([[0, 0]]);
+ });
+
+ it('puts the page back at the top when the keyboard resizes the viewport while it is panned', () => {
+ const page = load();
+ page.visualViewport.offsetTop = 336;
+ page.fire(page.visualViewport, 'resize');
+ expect(page.scrolls).toEqual([[0, 0]]);
+ });
+
+ it('puts the page back at the top when the document itself scrolls', () => {
+ const page = load();
+ page.win.scrollY = 336;
+ page.fire(page.win, 'scroll');
+ expect(page.scrolls).toEqual([[0, 0]]);
+ });
+
+ it('leaves a page that is already at the top alone', () => {
+ const page = load();
+ page.fire(page.visualViewport, 'scroll');
+ page.fire(page.visualViewport, 'resize');
+ page.fire(page.win, 'scroll');
+ expect(page.scrolls).toEqual([]);
+ });
+
+ it('leaves a page the visitor pinch-zoomed alone', () => {
+ const page = load({ viewport: { scale: 2.5, offsetTop: 120, offsetLeft: 40 } });
+ page.fire(page.visualViewport, 'scroll');
+ page.win.scrollY = 120;
+ page.fire(page.win, 'scroll');
+ expect(page.scrolls).toEqual([]);
+ });
+
+ it('does nothing on desktop browsers and Android Chrome', () => {
+ for (const env of [
+ { userAgent: desktop, platform: 'MacIntel' },
+ { userAgent: android, platform: 'Linux armv8l' },
+ ]) {
+ const page = load(env);
+ expect(page.listening()).toBe(0);
+ }
+ });
+
+ it('starts without the visual viewport API', () => {
+ const page = load({ viewport: null });
+ page.win.scrollY = 50;
+ page.fire(page.win, 'scroll');
+ expect(page.scrolls).toEqual([[0, 0]]);
+ });
+});