The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(share-machine): domain shares work like email shares; faster p2p recovery; shared machines in hn and --machine
bitcoinbuilder69eceffe922f
diff --git a/backend/src/lib/machineAccess.test.ts b/backend/src/lib/machineAccess.test.tsindex dcedd7f9d..13cdacea3 100644--- a/backend/src/lib/machineAccess.test.ts+++ b/backend/src/lib/machineAccess.test.ts@@ -47,15 +47,13 @@ describe('who a share reaches', () => {describe('sharedMachineAccess', () => {beforeEach(() => { vi.resetAllMocks() })- it('lets a named address in, and a colleague only once they added it', async () => {+ // The owner, 2026-10-16: a machine shared with the domain is used as one shared by email is, nothing to add.+ it('lets a named address in, and a colleague at the domain as well, with nothing to add first', async () => {mocks.prisma.machineShare.findUnique.mockResolvedValue(share({ emails: ['[email protected]'] }))expect(await sharedMachineAccess(kim, machine())).toBe('email')mocks.prisma.machineShare.findUnique.mockResolvedValue(share({ domain: 'acme.io' }))- mocks.prisma.machineShareAdd.findUnique.mockResolvedValueOnce(null)- expect(await sharedMachineAccess(kim, machine())).toBeNull()- mocks.prisma.machineShareAdd.findUnique.mockResolvedValueOnce({ machineId: 'm1', userId: 'kim' })expect(await sharedMachineAccess(kim, machine())).toBe('domain')- expect(mocks.prisma.machineShareAdd.findUnique).toHaveBeenCalledWith({ where: { machineId_userId: { machineId: 'm1', userId: 'kim' } } })+ expect(mocks.prisma.machineShareAdd.findUnique).not.toHaveBeenCalled()})it('refuses the owner (no share needed), no share, another owner’s row and another environment', async () => {@@ -83,7 +81,7 @@ describe('machinesSharedWith', () => {mocks.keys.mockResolvedValue([{ machineId: 'm1', pub: pub(1), label: 'studio', kind: 'machine', addedAt: 1, seq: 1 }])})- it('lists named and domain shares, with the owner, the machine key and whether it was added', async () => {+ it('lists named and domain shares alike, with the owner and the machine key', async () => {mocks.prisma.machineShare.findMany.mockResolvedValue([share({ emails: ['[email protected]'] }), share({ machineId: 'm2', domain: 'acme.io' })])mocks.prisma.machine.findMany.mockResolvedValue([machine(), machine({ machineId: 'm2', name: null, hostname: null })])const rows = await machinesSharedWith(kim)@@ -94,8 +92,9 @@ describe('machinesSharedWith', () => {{ machineId: 'm1', name: 'Studio', hostname: 'studio.local', authMode: 'remote', status: 'running', pub: pub(1),share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'email', added: true } },{ machineId: 'm2', name: null, hostname: null, authMode: 'remote', status: 'offline', pub: null,- share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'domain', added: false } },+ share: { ownerName: 'Dee', ownerEmail: '[email protected]', via: 'domain', added: true } },])+ expect(mocks.prisma.machineShareAdd.findMany).not.toHaveBeenCalled()})it('asks no domain at a public one, and drops deleted, suspended and re-owned machines', async () => {@@ -113,10 +112,9 @@ describe('machinesSharedWith', () => {expect(mocks.prisma.machine.findMany).not.toHaveBeenCalled()})- it('names an owner with no name by email, and one gone as a Harness user; an added domain share reads added', async () => {+ it('names an owner with no name by email, and one gone as a Harness user', async () => {mocks.prisma.machineShare.findMany.mockResolvedValue([share({ domain: 'acme.io' })])mocks.prisma.machine.findMany.mockResolvedValue([machine()])- mocks.prisma.machineShareAdd.findMany.mockResolvedValue([{ machineId: 'm1', userId: 'kim' }])mocks.prisma.user.findMany.mockResolvedValueOnce([{ id: 'owner', name: null, email: '[email protected]' }])expect((await machinesSharedWith(kim))[0].share).toEqual({ ownerName: '[email protected]', ownerEmail: '[email protected]', via: 'domain', added: true })mocks.prisma.user.findMany.mockResolvedValueOnce([])@@ -130,21 +128,36 @@ describe('shareMembers', () => {mocks.keys.mockImplementation(async (id: string) => [{ machineId: `${id}-mac`, pub: pub(id.length), label: `${id}'s Mac`, kind: 'machine', addedAt: 1, seq: 1 }])})- it('names the addresses and the colleagues who added it, with their machines’ keys', async () => {- mocks.prisma.machineShareAdd.findMany.mockResolvedValue([{ machineId: 'm1', userId: 'kim' }])- mocks.prisma.user.findMany.mockResolvedValue([- { id: 'ann', email: '[email protected]', name: 'Ann' },- { id: 'kim', email: '[email protected]', name: null },- { id: 'lee', email: '[email protected]', name: 'Lee' }, // at the domain, never added- { id: 'old', email: '[email protected]', name: 'Old' }, // added once, no longer reached- ])+ it('names the addresses, then everyone at the domain, with their machines’ keys', async () => {+ mocks.prisma.user.findMany+ .mockResolvedValueOnce([{ id: 'ann', email: '[email protected]', name: 'Ann' }])+ .mockResolvedValueOnce([+ { id: 'kim', email: '[email protected]', name: null },+ { id: 'old', email: '[email protected]', name: 'Old' }, // not at the domain after all: never trusted+ ])const members = await shareMembers(share({ emails: ['[email protected]'], domain: 'acme.io' }))- expect(mocks.prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: {- autonomousEnv: 'prod', id: { not: 'owner' }, OR: [{ email: { in: ['[email protected]'] } }, { id: { in: ['kim'] } }],+ expect(mocks.prisma.user.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: {+ autonomousEnv: 'prod', id: { not: 'owner' }, email: { in: ['[email protected]'] },+ } }))+ expect(mocks.prisma.user.findMany).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: {+ autonomousEnv: 'prod', id: { notIn: ['owner', 'ann'] }, email: { endsWith: '@acme.io', mode: 'insensitive' },} }))expect(members).toEqual([{ email: '[email protected]', name: 'Ann', via: 'email', machines: [{ machineId: 'ann-mac', name: "ann's Mac", pub: pub(3) }] },{ email: '[email protected]', name: null, via: 'domain', machines: [{ machineId: 'kim-mac', name: "kim's Mac", pub: pub(3) }] },])+ expect(mocks.prisma.machineShareAdd.findMany).not.toHaveBeenCalled()+ })++ it('asks for no one at the domain when it is not shared with the domain, or the domain is a public one', async () => {+ mocks.prisma.user.findMany.mockResolvedValue([{ id: 'ann', email: '[email protected]', name: 'Ann' }])+ await shareMembers(share({ emails: ['[email protected]'] }))+ await shareMembers(share({ emails: ['[email protected]'], domain: 'gmail.com' }))+ expect(mocks.prisma.user.findMany).toHaveBeenCalledTimes(2)+ mocks.prisma.user.findMany.mockClear()+ // Shared with the domain alone: one query, for the domain.+ mocks.prisma.user.findMany.mockResolvedValue([])+ expect(await shareMembers(share({ domain: 'acme.io' }))).toEqual([])+ expect(mocks.prisma.user.findMany).toHaveBeenCalledTimes(1)})})diff --git a/backend/src/lib/machineAccess.ts b/backend/src/lib/machineAccess.tsindex a57caf653..19379a58b 100644--- a/backend/src/lib/machineAccess.ts+++ b/backend/src/lib/machineAccess.ts@@ -1,8 +1,9 @@/*** Who may use a machine another account owns (docs/plans/2026-10-15-share-machine-plan.md). Its owner- * shares it with addresses, and with everyone at the owner's own domain; someone at the domain adds it with- * one click (`MachineShareAdd`), someone the owner named needs none. A shared machine is used with the- * owner's own rights: `machine_select` (lib/webWs.ts) asks `sharedMachineAccess` where it once compared+ * shares it with addresses, and with everyone at the owner's own domain. Either way it is theirs to use at+ * once: a domain share once had to be added first (`MachineShareAdd`, kept only for older apps), and the+ * owner asked for it to work as one by email does (2026-10-16). A shared machine is used with the owner's+ * own rights: `machine_select` (lib/webWs.ts) asks `sharedMachineAccess` where it once compared* owners, and `machinesSharedWith` is the "Shared with you" half of the Machines list.** Only the listing and the relay are decided here. The machine's daemon keeps the policy it published and@@ -34,17 +35,13 @@ export function sharedVia(share: Pick<MachineShare, 'emails' | 'domain'>, email:return null}-/** Whether `user` may use `machine`, which another account owns: how it was shared with them, or null. A- * domain share counts once they added it. */+/** Whether `user` may use `machine`, which another account owns: how it was shared with them, or null. */export async function sharedMachineAccess(user: AuthUser, machine: Pick<Machine, 'machineId' | 'userId' | 'autonomousEnv'>): Promise<ShareVia | null> {if (machine.userId === user.sub) return nullconst share = await prisma.machineShare.findUnique({ where: { machineId: machine.machineId } })if (!share || share.ownerId !== machine.userId || share.autonomousEnv !== user.autonomousEnv|| storedAutonomousEnvironment(machine.autonomousEnv) !== user.autonomousEnv) return null- const via = sharedVia(share, user.email)- if (via !== 'domain') return via- const added = await prisma.machineShareAdd.findUnique({ where: { machineId_userId: { machineId: machine.machineId, userId: user.sub } } })- return added ? via : null+ return sharedVia(share, user.email)}/** A machine shared with the person asking, as their Machines list shows it. `pub` is the machine's own@@ -59,7 +56,7 @@ export interface SharedMachineRow {share: { ownerName: string; ownerEmail: string; via: ShareVia; added: boolean }}-/** The machines other accounts share with `user`: named ones, and those at their domain, added or not. */+/** The machines other accounts share with `user`: named ones, and those at their domain. */export async function machinesSharedWith(user: AuthUser): Promise<SharedMachineRow[]> {const email = normalized(user.email)const domain = emailDomain(email)@@ -85,8 +82,7 @@ export async function machinesSharedWith(user: AuthUser): Promise<SharedMachineRif (!usable.length) return []const ids = usable.map(u => u.machine.machineId)const ownerIds = [...new Set(usable.map(u => u.machine.userId))]- const [adds, owners, presence, keys] = await Promise.all([- prisma.machineShareAdd.findMany({ where: { userId: user.sub, machineId: { in: ids } } }),+ const [owners, presence, keys] = await Promise.all([prisma.user.findMany({ where: { id: { in: ownerIds } }, select: { id: true, name: true, email: true } }),getAgentPresenceMany(ids),Promise.all(ownerIds.map(async id => [id, await activeMachineKeys(id)] as const)),@@ -99,8 +95,8 @@ export async function machinesSharedWith(user: AuthUser): Promise<SharedMachineRmachineId: machine.machineId, name: machine.name ?? null, hostname: machine.hostname ?? null, authMode: 'remote',status: presence.get(machine.machineId) ? 'running' : 'offline',pub: keyOf(machine.userId, machine.machineId),- share: { ownerName: owner?.name || owner?.email || 'Harness user', ownerEmail: owner?.email ?? '', via,- added: via === 'email' || adds.some(a => a.machineId === machine.machineId) },+ // `added` is always true now: an app that still reads it lists the machine as one it uses.+ share: { ownerName: owner?.name || owner?.email || 'Harness user', ownerEmail: owner?.email ?? '', via, added: true },}})}@@ -113,18 +109,24 @@ export interface ShareMember {machines: Array<{ machineId: string; name: string; pub: string }>}-/** The accounts `share` lets use its machine right now: those named, and those at the domain who added it. */+/** The accounts `share` lets use its machine right now: those named, and everyone at the domain when it is+ * shared with the domain. Named ones come first, so the cap never drops someone the owner named. */export async function shareMembers(share: MachineShare): Promise<ShareMember[]> {- const adds = await prisma.machineShareAdd.findMany({ where: { machineId: share.machineId }, take: SHARED_LIST_MAX })- const users = await prisma.user.findMany({- where: { autonomousEnv: share.autonomousEnv, id: { not: share.ownerId },- OR: [{ email: { in: share.emails } }, { id: { in: adds.map(a => a.userId) } }] },- select: { id: true, email: true, name: true }, take: SHARED_LIST_MAX,- })- const members = users.flatMap(user => {+ const domain = share.domain && !isPublicEmailDomain(share.domain) ? share.domain : null+ const select = { id: true, email: true, name: true } as const+ const where = { autonomousEnv: share.autonomousEnv, id: { not: share.ownerId } }+ const named = share.emails.length+ ? await prisma.user.findMany({ where: { ...where, email: { in: share.emails } }, select, take: SHARED_LIST_MAX })+ : []+ const atDomain = domain && named.length < SHARED_LIST_MAX+ ? await prisma.user.findMany({+ where: { ...where, email: { endsWith: `@${domain}`, mode: 'insensitive' }, id: { notIn: [share.ownerId, ...named.map(u => u.id)] } },+ select, orderBy: { createdAt: 'asc' }, take: SHARED_LIST_MAX - named.length,+ })+ : []+ const members = [...named, ...atDomain].flatMap(user => {const via = sharedVia(share, user.email)- if (!via || (via === 'domain' && !adds.some(a => a.userId === user.id))) return []- return [{ user, via }]+ return via ? [{ user, via }] : []})return Promise.all(members.map(async ({ user, via }) => ({email: normalized(user.email), name: user.name ?? null, via,diff --git a/backend/src/routes/machineShares.ts b/backend/src/routes/machineShares.tsindex 9cc7afa49..0b4052490 100644--- a/backend/src/routes/machineShares.ts+++ b/backend/src/routes/machineShares.ts@@ -6,8 +6,9 @@* machine's own daemon from the policy it keeps (cli services/sharedMachines.ts), which reads the members* back to know whose keys to trust.* - `GET /api/machine-shares`: the machines shared with the person asking (also in `GET /api/machines`).- * - `POST|DELETE /api/machine-shares/:machineId/add`: add a machine shared with your domain, or take it- * back out of your list. An address the owner named needs no adding.+ * - `POST|DELETE /api/machine-shares/:machineId/add`: what an older app calls to add a machine shared with+ * its domain, or take it back out. Nothing needs adding any more: a domain share is used as one by email+ * is (lib/machineAccess.ts), so these change no one's access.*/import type { FastifyInstance } from 'fastify'import type { MachineShare } from '@prisma/client'diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex fd4351829..d944636d4 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -63,7 +63,7 @@ import { apiCommand, apiUsage } from './lib/apiCommand.js'import { connectionsCommand, connectionsUsage } from './lib/connectors/command.js'import { remoteCommand } from './remoteCommand.js'import { tuiCommand } from './tui/index.js'-import { newCommand, type NewMachine } from './lib/newCommand.js'+import { machineChoices, newCommand, type MachineRow, type NewMachine } from './lib/newCommand.js'import { gridSetupCommand } from './lib/gridSetupCommand.js'import { WebSocket as NewCommandSocket } from 'ws'import { describeMasterStatus, readStatusFile } from './harnessd/master.js'@@ -2293,6 +2293,14 @@ async function ownedMachines(): Promise<NewMachine[]> {}))}+/** What `--machine` resolves among (`harness new`, `ps`, `show`, `wait`, `close`): the account's machines, then the+ * ones other accounts share with it that it may use (lib/newCommand.ts `machineChoices`). */+async function usableMachines(): Promise<NewMachine[]> {+ const { session, headers } = await controlPlaneAuth()+ const data = await requestJson<{ machines?: MachineRow[]; sharedMachines?: MachineRow[] }>('GET', '/api/machines', undefined, headers)+ return machineChoices(data, session.machineId ?? null)+}+/** True when `id` names this machine — accepts the short prefix the list prints, not just the full id. */function matchesMachineId(machineId: string, id: string): boolean {return machineId === id || machineId.startsWith(id)@@ -2548,7 +2556,7 @@ switch (cmd) {whoamiCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)breakcase 'ps':- psCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)+ psCommand(rest, { machines: usableMachines }).then(code => { process.exitCode = code }).catch(onError)breakcase 'settings':settingsCommand(rest, { port: daemonPort() }).then(code => { process.exitCode = code }).catch(onError)@@ -2559,13 +2567,13 @@ switch (cmd) {break}case 'show':- showCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)+ showCommand(rest, { machines: usableMachines }).then(code => { process.exitCode = code }).catch(onError)breakcase 'wait':- waitCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)+ waitCommand(rest, { machines: usableMachines }).then(code => { process.exitCode = code }).catch(onError)breakcase 'close':- closeCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)+ closeCommand(rest, { machines: usableMachines }).then(code => { process.exitCode = code }).catch(onError)breakcase 'orchestrator':orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)@@ -2676,7 +2684,7 @@ switch (cmd) {port: daemonPort(),localMachineId: wantedDaemonIdentity(),daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),- listMachines: ownedMachines,+ listMachines: usableMachines,connect: (url) => new NewCommandSocket(url),output: (line) => console.log(line),error: (line) => console.error(line),diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.tsindex 7392e4140..a878b9cda 100644--- a/cli/src/lib/newCommand.spec.ts+++ b/cli/src/lib/newCommand.spec.ts@@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events'import { mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { newAgentPayload, newCommand, NewUsageError, parseNewArgs, resolveNewMachine, trustAsked, type NewCommandDeps, type NewSocket } from './newCommand.js'+import { machineChoices, newAgentPayload, newCommand, NewUsageError, parseNewArgs, resolveNewMachine, trustAsked, type NewCommandDeps, type NewSocket } from './newCommand.js'import { SANDBOXED } from './unreachable.js'import { AgentClientError } from '../agentClient/daemon.js'@@ -119,6 +119,39 @@ describe('harness new: the words', () => {expect(() => resolveNewMachine('mac', machines)).toThrow(/could be Mac mini or MacBook Pro/)expect(() => resolveNewMachine('linux', machines)).toThrow(/No machine called/)})++ // Seen 2026-10-16: `harness ps --machine "Mac Auto"` said `No machine called “Mac Auto”` for a machine Tuan+ // shared with this account, which the app opened and created on with the owner's rights.+ it('finds a machine shared with the account, and its own machine wins a name both have', () => {+ const machines = machineChoices({+ machines: [+ { machineId: 'own', name: 'MacBook Pro', hostname: 'mbp.local', status: 'running' },+ { machineId: 'own-mini', name: ' ', hostname: 'Mac mini', status: '' },+ ],+ sharedMachines: [+ { machineId: 'auto', name: 'Mac Auto', status: 'running', share: { ownerName: 'Tuan', added: true } },+ { machineId: 'theirs-mini', name: 'Mac mini', status: 'running', share: { ownerName: 'Dee', added: true } },+ { machineId: 'team', name: 'gpu-box', status: 'running', share: { ownerName: 'Lee', added: false } },+ { machineId: 'nameless', hostname: 'studio.local', share: { ownerName: ' ', added: true } },+ ],+ }, 'own')+ expect(machines.map((machine) => [machine.machineId, machine.label, machine.status, machine.current, machine.sharedBy, machine.toAdd])).toEqual([+ ['own', 'MacBook Pro', 'running', true, undefined, undefined],+ ['own-mini', 'Mac mini', 'unknown', false, undefined, undefined],+ ['auto', 'Mac Auto', 'running', false, 'Tuan', undefined],+ ['theirs-mini', 'Mac mini', 'running', false, 'Dee', undefined],+ ['team', 'gpu-box', 'running', false, 'Lee', true],+ ['nameless', 'studio.local', 'unknown', false, 'another account', undefined],+ ])+ expect(resolveNewMachine('Mac Auto', machines).machineId).toBe('auto')+ expect(resolveNewMachine('auto', machines).machineId).toBe('auto')+ expect(resolveNewMachine('mac mini', machines).machineId).toBe('own-mini')+ // A domain share not added yet is not the account's to use: its machine refuses it. Named, it says how to add it.+ expect(() => resolveNewMachine('gpu-box', machines)).toThrow('Lee shared “gpu-box” with everyone at your company. Add it first: Machines › Shared with your team, in the app or hn.')+ expect(() => resolveNewMachine('team', machines)).toThrow(/Add it first/)+ expect(() => resolveNewMachine('gpu', machines)).toThrow('No machine called “gpu”. Yours: MacBook Pro, Mac mini. Shared with you: Mac Auto, Mac mini, studio.local.')+ expect(() => resolveNewMachine('linux', machineChoices({}, null))).toThrow('No machine called “linux”. Yours: none.')+ })})class FakeSocket extends EventEmitter implements NewSocket {diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.tsindex e5d7ff551..93045e46d 100644--- a/cli/src/lib/newCommand.ts+++ b/cli/src/lib/newCommand.ts@@ -202,10 +202,45 @@ export function newAgentPayload(args: NewArgs, cwd: string | null, baseEngine =}}-export interface NewMachine { machineId: string; label: string; status: string; current: boolean }+export interface NewMachine {+ machineId: string; label: string; status: string; current: boolean+ /** Another account's machine shared with this one: whose it is. */+ sharedBy?: string+ /** Shared with everyone at the account's domain and not added yet: named only to say how to add it. */+ toAdd?: true+}++/** One row of `GET /api/machines`, as far as `--machine` reads it; a shared one carries its `share`. */+export interface MachineRow {+ machineId: string+ name?: string | null+ hostname?: string | null+ status?: string | null+ share?: { ownerName?: string | null; added?: boolean | null } | null+}++/** The machines `--machine` resolves among: the account's own, then those other accounts share with it that it+ * may use — named in the share, or added from one at its domain (`share.added`, as the backend decides). A domain+ * share not added yet is listed as `toAdd`: its machine refuses this account until it is added+ * (backend lib/machineAccess.ts `sharedMachineAccess`), so it is never chosen, only named. */+export function machineChoices(data: { machines?: MachineRow[]; sharedMachines?: MachineRow[] }, currentId: string | null): NewMachine[] {+ const label = (machine: MachineRow): string => machine.name?.trim() || machine.hostname?.trim() || '(unnamed)'+ const choice = (machine: MachineRow): NewMachine => ({+ machineId: machine.machineId, label: label(machine), status: machine.status || 'unknown', current: machine.machineId === currentId,+ })+ return [+ ...(data.machines ?? []).map(choice),+ ...(data.sharedMachines ?? []).map((machine) => ({+ ...choice(machine), current: false, sharedBy: machine.share?.ownerName?.trim() || 'another account',+ ...(machine.share?.added === true ? {} : { toAdd: true as const }),+ })),+ ]+}-/** The machine `--machine <word>` means: an exact id, else a label, case-blind; ambiguity is an error, not a guess. */-export function resolveNewMachine(word: string, machines: NewMachine[]): NewMachine {+/** The machine `--machine <word>` means: an exact id, else a label, case-blind; ambiguity is an error, not a guess.+ * A machine shared with the account answers its name too, but the account's own wins a name both have. */+export function resolveNewMachine(word: string, choices: NewMachine[]): NewMachine {+ const machines = choices.filter((machine) => !machine.toAdd)const byId = machines.find((machine) => machine.machineId === word)if (byId) return byIdconst wanted = word.toLowerCase()@@ -218,11 +253,21 @@ export function resolveNewMachine(word: string, machines: NewMachine[]): NewMachlet matches: NewMachine[] = []for (const tier of tiers) {matches = machines.filter((machine) => tier(machine.label.toLowerCase()))+ const own = matches.filter((machine) => machine.sharedBy === undefined)+ if (own.length > 0) matches = ownif (matches.length > 0) break}if (matches.length === 1) return matches[0]!if (matches.length === 0) {- throw new NewUsageError(`No machine called “${word}”. Yours: ${machines.map((machine) => machine.label).join(', ') || 'none'}.`)+ // Seen 2026-10-16: Mac Auto, shared with everyone at autonomous.ai and not added, read as no machine at all.+ const team = choices.find((machine) => machine.toAdd && (machine.machineId === word || machine.label.toLowerCase() === word.toLowerCase()))+ if (team) {+ throw new NewUsageError(`${team.sharedBy} shared “${team.label}” with everyone at your company. Add it first: Machines › Shared with your team, in the app or hn.`)+ }+ const labels = (shared: boolean) => machines.filter((machine) => (machine.sharedBy !== undefined) === shared).map((machine) => machine.label)+ const shared = labels(true)+ throw new NewUsageError(`No machine called “${word}”. Yours: ${labels(false).join(', ') || 'none'}.`+ + (shared.length ? ` Shared with you: ${shared.join(', ')}.` : ''))}throw new NewUsageError(`“${word}” could be ${matches.map((machine) => machine.label).join(' or ')}. Type more of the name.`)}diff --git a/cli/src/lib/remoteRelay.spec.ts b/cli/src/lib/remoteRelay.spec.tsindex e06910cfa..4fae3d3b0 100644--- a/cli/src/lib/remoteRelay.spec.ts+++ b/cli/src/lib/remoteRelay.spec.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { RemoteRelayPool } from './remoteRelay.js'+import { TerminalP2pInitiator } from './terminalP2p.js'/** Minimal fake of the private `Entry` shape `noteTerminalResponse`/`demoteP2p` operate on — exercised* directly (bypassing the class's `private` marker, the lightest way to unit-test this without a real@@ -191,6 +192,30 @@ describe('RemoteRelayPool p2p retry policy', () => {}})+ // Seen 2026-10-16: one failed negotiation left a shared machine's terminal on the ws relay — every+ // keystroke through the backend — for a whole minute before the first retry.+ it('retries after 5s first, then backs off through 15s and 30s to every minute', () => {+ vi.useFakeTimers()+ const start = vi.spyOn(TerminalP2pInitiator.prototype, 'start').mockImplementation(() => {})+ try {+ const entry = fakeEntry({ p2pPolicy: { enabled: true, protocolVersion: 1, stunUrls: [], openWaitMs: 1500 } })+ ;(pool as unknown as { entries: Map<string, unknown> }).entries.set('machine-1', entry)+ for (const seconds of [5, 15, 30, 60, 60]) {+ pool.scheduleP2pRetry('machine-1', entry)+ expect(logSpy).toHaveBeenLastCalledWith(expect.stringContaining(`[p2p] retry scheduled · machine=machine- in ${seconds}s`))+ vi.advanceTimersByTime(seconds * 1000 - 1)+ expect(entry.p2p, `not before ${seconds}s`).toBeNull()+ vi.advanceTimersByTime(1)+ expect(entry.p2p, `at ${seconds}s`).not.toBeNull()+ entry.p2p = null+ }+ } finally {+ start.mockRestore()+ ;(pool as unknown as { entries: Map<string, unknown> }).entries.delete('machine-1')+ vi.useRealTimers()+ }+ })+it('does not double-schedule while a retry timer is already pending', () => {vi.useFakeTimers()try {@@ -664,6 +689,56 @@ describe('RemoteRelayPool keeps background (isolated) clients cheap', () => {const sink = () => ({ sendFrame: vi.fn(() => true), sendBinary: vi.fn(() => true) })const select = { type: 'machine_select', payload: { relayIsolation: true } }+ // Seen 2026-10-16: every negotiation to a shared machine spent 8–10s timing out direct pairs before+ // settling on the TURN pair it always ended on.+ it('a machine only TURN reached is negotiated TURN-first next time, until a direct pair or a failure', () => {+ vi.useFakeTimers()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const start = vi.spyOn(TerminalP2pInitiator.prototype, 'start').mockImplementation(() => {})+ try {+ const pool = new RemoteRelayPool(...ctorArgs) as unknown as {+ startP2p: (machineId: string, entry: ReturnType<typeof fakeEntry>) => void+ }+ const turn = { urls: ['turn:turn.example:3478'], username: 'u', credential: 'c' }+ type Deps = { relayOnly?: boolean; onState: (state: string, setupMs: number, reason?: string) => void }+ const negotiate = (policy: Record<string, unknown>) => {+ const entry = fakeEntry({ p2pPolicy: { enabled: true, protocolVersion: 1, stunUrls: ['stun:s'], openWaitMs: 1500, ...policy } })+ pool.startP2p('m1', entry)+ const p2p = entry.p2p as unknown as { deps: Deps; transport: string }+ return { relayOnly: !!p2p.deps.relayOnly, p2p, entry }+ }+ const reach = (p2p: { deps: Deps }, via: 'relay' | 'host') => {+ Object.defineProperty(p2p, 'transport', { value: via, configurable: true })+ p2p.deps.onState('direct', 9_000)+ }++ const first = negotiate({ turn })+ expect(first.relayOnly).toBe(false)+ reach(first.p2p, 'relay')+ const second = negotiate({ turn })+ expect(second.relayOnly).toBe(true)+ // Without a TURN credential there is nothing to gather TURN-first.+ expect(negotiate({}).relayOnly).toBe(false)+ // A TURN-first attempt that fails forgets it: the path changed.+ second.p2p.deps.onState('failed', 10_000, 'peer_failed')+ expect(negotiate({ turn }).relayOnly).toBe(false)+ // So does a direct pair, and the memory lasts a working day.+ const third = negotiate({ turn })+ reach(third.p2p, 'relay')+ expect(negotiate({ turn }).relayOnly).toBe(true)+ vi.advanceTimersByTime(12 * 60 * 60 * 1000)+ expect(negotiate({ turn }).relayOnly).toBe(false)+ const fourth = negotiate({ turn })+ reach(fourth.p2p, 'relay')+ reach(negotiate({ turn }).p2p, 'host')+ expect(negotiate({ turn }).relayOnly).toBe(false)+ } finally {+ start.mockRestore()+ vi.restoreAllMocks()+ vi.useRealTimers()+ }+ })+it('a pool built with p2p off never starts a negotiation, even with a policy and on retry', () => {const pool = new RemoteRelayPool(...ctorArgs, { p2p: false }) as unknown as {startP2p: (machineId: string, entry: ReturnType<typeof fakeEntry>) => voiddiff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.tsindex 4aa9a291b..9bac07c5d 100644--- a/cli/src/lib/remoteRelay.ts+++ b/cli/src/lib/remoteRelay.ts@@ -64,7 +64,8 @@ const ISOLATED_IDLE_MAX = 4// A p2p attempt that never reaches 'direct', or one that did and then got demoted mid-session, both// leave the stream(s) on the ws relay with nothing to bring them back — see scheduleP2pRetry(). One-// policy for both cases: retry every 60s, capped at P2P_RETRY_HOURLY_CAP attempts within any trailing+// policy for both cases: retry after 5s, then 15s, 30s and every 60s (P2P_RETRY_DELAYS_MS, by how many+// attempts the trailing hour already holds), capped at P2P_RETRY_HOURLY_CAP attempts within any trailing// hour (tracked in p2pRetryTimestamps, not a plain counter) — a ROLLING window rather than a lifetime// total, deliberately: the underlying reason a connection can't reach p2p is often transient at the// scale of hours (the machine's public IP changed, a router rebooted, a NAT binding thawed), so a@@ -72,12 +73,21 @@ const ISOLATED_IDLE_MAX = 4// staying stuck on relay for the rest of the daemon's uptime. Old attempts simply age out of the// lookback on their own, which is also why there is no separate "reset on a success" step any more —// a connection that's been healthy for a while naturally has an empty recent window already.-const P2P_RETRY_DELAY_MS = 60_000+// The first retry is quick: a terminal left on the ws relay echoes every keystroke through the backend,+// which is what a person typing feels (2026-10-16: one failed negotiation left a shared machine's+// terminal on the relay for a full minute). Later ones back off to the old minute.+const P2P_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000]const P2P_RETRY_WINDOW_MS = 60 * 60 * 1000const P2P_RETRY_HOURLY_CAP = 10// How long a stream may sit in p2pMigrating before the sweep (piggybacked on the liveness tick) gives up// on it and lets the ordinary demote-on-mismatch rule apply again.const P2P_MIGRATION_TTL_MS = 30_000+// A machine reached only through TURN last time is negotiated TURN-first next time (relay candidates+// only), so ICE does not spend ~8s timing out direct pairs before settling on the relay pair it always+// ends on (2026-10-16: every negotiation to a shared machine took 8–10s, one failed outright). The+// TURN-to-direct upgrade below still looks for a direct pair in the background, and finding one, or a+// TURN-first attempt failing, forgets it. Kept for a working day: networks change.+const P2P_TURN_FIRST_MEMORY_MS = 12 * 60 * 60 * 1000// A connection that reached 'direct' only via a Cloudflare TURN relay pair still costs per GB — worth// trying, periodically, for a truly direct pair instead. Unlike p2pRetry* above this NEVER touches the@@ -261,6 +271,8 @@ export class RemoteRelayPool {/** Last failed dial per machine, for the cooldown. Cleared by the next successful dial. */private readonly lastDialFailure: Map<string, { at: number; error: unknown }>private readonly p2pEnabled: boolean+ /** machineId -> when a negotiation last reached it only through TURN (P2P_TURN_FIRST_MEMORY_MS). */+ private readonly turnOnly = new Map<string, number>()private readonly lingerMs: numberprivate readonly dialCooldownMs: numberprivate readonly onSessionReady: ((machineId: string) => void) | null@@ -834,8 +846,11 @@ export class RemoteRelayPool {// through this same method, and a background pool must stay relay-only through every retry too.if (!policy || entry.p2p || !this.p2pEnabled) returnlet wasDirect = false+ const turnFirst = !!policy.turn && Date.now() - (this.turnOnly.get(machineId) ?? -Infinity) < P2P_TURN_FIRST_MEMORY_MS+ if (turnFirst) console.log(`[p2p] turn first · machine=${sid(machineId)} — only TURN reached it last time`)const p2p = new TerminalP2pInitiator({policy,+ relayOnly: turnFirst,sendSignal: (type, payload) => {const wrapped = entry.crypto.wrapOutgoing({ type, payload })try { entry.ws.send(JSON.stringify(wrapped)) } catch { /* relay close handles cleanup */ }@@ -856,6 +871,7 @@ export class RemoteRelayPool {// 'relayed' distinguishes a Cloudflare TURN path from a truly direct one. Both are "p2p" as far// as the terminal is concerned, but only one of them is billed per GB.const relayed = p2p.transport === 'relay'+ if (relayed) this.turnOnly.set(machineId, Date.now()); else this.turnOnly.delete(machineId)console.log(`[p2p] connected · machine=${sid(machineId)} via=${relayed ? 'turn' : 'direct'} setup=${Math.round(setupMs)}ms`)this.reportP2pResult(entry, 'direct', setupMs, relayed ? 'relayed' : undefined)this.promoteOpenStreams(machineId, entry)@@ -864,6 +880,8 @@ export class RemoteRelayPool {console.log(`[p2p] gave up · machine=${sid(machineId)} reason=${reason ?? 'unknown'} after=${Math.round(setupMs)}ms`+ ` · ${p2p.negotiationDetail} — terminals stay on the ws relay`)this.reportP2pResult(entry, reason === 'negotiation_timeout' ? 'timeout' : 'failed', setupMs, reason)+ // TURN-first failing says the path changed: the next attempt gathers everything again.+ if (turnFirst) this.turnOnly.delete(machineId)// Without this the entry is stuck: entry.p2p still points at this now-finished instance, and// startP2p()'s own guard (`if (!policy || entry.p2p) return`) would block every future attempt// forever — previously the only way out was a full entry teardown (network drop).@@ -1014,8 +1032,9 @@ export class RemoteRelayPool {console.log(`[p2p] retry budget exhausted · machine=${sid(machineId)} (${entry.p2pRetryTimestamps.length}/${P2P_RETRY_HOURLY_CAP} in the last hour)`)return}+ const delay = P2P_RETRY_DELAYS_MS[Math.min(entry.p2pRetryTimestamps.length, P2P_RETRY_DELAYS_MS.length - 1)]entry.p2pRetryTimestamps.push(Date.now())- console.log(`[p2p] retry scheduled · machine=${sid(machineId)} in ${P2P_RETRY_DELAY_MS / 1000}s`+ console.log(`[p2p] retry scheduled · machine=${sid(machineId)} in ${delay / 1000}s`+ ` (${entry.p2pRetryTimestamps.length}/${P2P_RETRY_HOURLY_CAP} this hour)`)entry.p2pRetryTimer = setTimeout(() => {entry.p2pRetryTimer = null@@ -1025,7 +1044,7 @@ export class RemoteRelayPool {}entry.p2p = nullthis.startP2p(machineId, entry)- }, P2P_RETRY_DELAY_MS)+ }, delay)entry.p2pRetryTimer.unref?.()}@@ -1202,6 +1221,7 @@ export class RemoteRelayPool {if (acked) {void old.stop('upgraded', false)console.log(`[p2p-upgrade] promoted · machine=${sid(machineId)} attempt=${entry.upgradeAttempts}`)+ this.turnOnly.delete(machineId) // a direct pair exists after all: negotiate it first next time} else {// Ack never arrived — keep OLD alive rather than guess it is safe to close; entry.upgradeOrphan is// closed wherever the entry itself is torn down (invalidate/ws-close/idle-linger).diff --git a/cli/src/lib/terminalP2p.ts b/cli/src/lib/terminalP2p.tsindex 0d58cb373..c8cc51a4c 100644--- a/cli/src/lib/terminalP2p.ts+++ b/cli/src/lib/terminalP2p.ts@@ -117,6 +117,10 @@ export interface TerminalP2pInitiatorDeps {* RemoteRelayPool's TURN-to-direct upgrade), not a fresh session — tags the offer so the responder* routes it to acceptUpgradeOffer() instead of tearing down the connId's live entry. */upgrade?: boolean+ /** Only TURN reached this machine last time (RemoteRelayPool's turn-first memory): gather relay+ * candidates only, so ICE settles on the relay pair at once instead of timing out direct pairs for+ * ~8s first. Ignored without a TURN credential, which would leave nothing to gather. */+ relayOnly?: boolean}type ReadyWaiter = (ready: boolean) => void@@ -139,7 +143,7 @@ interface TurnChoice {credential: string}-function peerConfig(stunUrls: string[], turn?: TurnChoice): ConstructorParameters<typeof RTCPeerConnection>[0] {+function peerConfig(stunUrls: string[], turn?: TurnChoice, relayOnly = false): ConstructorParameters<typeof RTCPeerConnection>[0] {const iceServers: Array<{ urls: string[]; username?: string; credential?: string }> = []if (stunUrls.length > 0) iceServers.push({ urls: stunUrls })if (turn) iceServers.push({ urls: [turn.url], username: turn.username, credential: turn.credential })@@ -148,11 +152,12 @@ function peerConfig(stunUrls: string[], turn?: TurnChoice): ConstructorParameter// Diagnostic only (TERMINAL_P2P_FORCE_RELAY): drops host and srflx so nothing but a TURN// allocation can be nominated. Note it also skips STUN gathering entirely inside werift, which is// why a forced run is fast even on a network where STUN is unreachable.- ...(env.TERMINAL_P2P_FORCE_RELAY ? { iceTransportPolicy: 'relay' as const } : {}),- // Left at the default 'all' deliberately: that is what produces "direct first, relay only if- // nothing else works". werift scores candidates host 126 > srflx 100 > relay 0, so a TURN relay- // pair is only ever nominated once every direct pair has failed. Setting 'relay' here would force- // every session through Cloudflare — and bill for it.+ ...(env.TERMINAL_P2P_FORCE_RELAY || (relayOnly && turn) ? { iceTransportPolicy: 'relay' as const } : {}),+ // Otherwise left at the default 'all' deliberately: that is what produces "direct first, relay only+ // if nothing else works". werift scores candidates host 126 > srflx 100 > relay 0, so a TURN relay+ // pair is only ever nominated once every direct pair has failed. Setting 'relay' for every session+ // would force it through Cloudflare — and bill for it; `relayOnly` is only ever a machine that+ // reached nothing else last time.// Terminal keyframes can approach 480 KiB. SCTP fragments them, but advertise enough room so// the peer never rejects the message at the WebRTC API boundary before fragmentation happens.maxMessageSize: 512 * 1024,@@ -309,7 +314,7 @@ export class TerminalP2pInitiator {// strand it: nothing holds a reference any more, so its UDP sockets would never be closed.if (this.finished) returnthis.step('stun-raced')- const pc = new RTCPeerConnection(peerConfig(stunUrls, turnChoice(this.deps.policy.turn, udpReachable)))+ const pc = new RTCPeerConnection(peerConfig(stunUrls, turnChoice(this.deps.policy.turn, udpReachable), this.deps.relayOnly))const channel = pc.createDataChannel(TERMINAL_P2P_CHANNEL, { ordered: true })this.pc = pcthis.channel = channeldiff --git a/cli/src/lib/terminalP2pTurnFirst.spec.ts b/cli/src/lib/terminalP2pTurnFirst.spec.tsnew file mode 100644index 000000000..f3c809557--- /dev/null+++ b/cli/src/lib/terminalP2pTurnFirst.spec.ts@@ -0,0 +1,41 @@+import { expect, it, vi } from 'vitest'++// What the initiator hands werift, without negotiating: the peer connection is refused at construction.+const configs: Array<{ iceTransportPolicy?: string }> = []+vi.mock('werift', () => ({+ RTCPeerConnection: class {+ constructor(config: { iceTransportPolicy?: string }) {+ configs.push(config)+ throw new Error('construction is all this spec reads')+ }+ },+}))++const { TerminalP2pInitiator } = await import('./terminalP2p.js')++const turn = { urls: ['turn:turn.example:3478?transport=udp'], username: 'u', credential: 'c' }++async function gatherPolicy(relayOnly: boolean, withTurn = true): Promise<string | undefined> {+ let failed!: () => void+ const done = new Promise<void>((resolve) => { failed = resolve })+ const peer = new TerminalP2pInitiator({+ policy: { enabled: true, protocolVersion: 1, stunUrls: [], openWaitMs: 0, ...(withTurn ? { turn } : {}) },+ relayOnly,+ sendSignal() {},+ onData() {},+ selectStunUrls: async () => ({ urls: [], udpReachable: true }),+ onState: (state) => { if (state === 'failed') failed() },+ })+ peer.start()+ await done+ await peer.stop('test_complete', false)+ return configs.pop()?.iceTransportPolicy+}++// Seen 2026-10-16: every negotiation to a machine only TURN reaches spent 8–10s on direct pairs first.+it('a TURN-first negotiation gathers relay candidates only; every other one gathers everything', async () => {+ expect(await gatherPolicy(true)).toBe('relay')+ expect(await gatherPolicy(false)).toBeUndefined()+ // Nothing to gather TURN-first without a TURN credential.+ expect(await gatherPolicy(true, false)).toBeUndefined()+})diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 626d6b3f7..221159280 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1376,6 +1376,10 @@ class AppNotifier extends ChangeNotifier {({String name, String owner})? sharingEnded(String machineId) =>_sharingEnded[machineId];+ /// The "stopped sharing" message [lastError] shows, and for which machine: taken down once that+ /// machine is shared again, rather than left saying something no longer true.+ ({String machineId, String text})? _sharingEndedError;+void _noteSharingEnded(Machine machine) {final share = machine.machineShare;if (share == null) return;@@ -7928,6 +7932,14 @@ class AppNotifier extends ChangeNotifier {}final visible = machines.map((machine) => machine.machineId).toSet();_sharingEnded.removeWhere((id, _) => visible.contains(id));+ // Seen 2026-10-16: "Tuan stopped sharing Mac Auto with you." stayed up after Tuan shared it again.+ final ended = _sharingEndedError;+ if (ended != null &&+ !machinesAreStale &&+ visible.contains(ended.machineId)) {+ _sharingEndedError = null;+ if (_lastError == ended.text) _lastError = null;+ }for (final entry in machineStates.entries) {if (!visible.contains(entry.key)) {// A shared machine that left the list was taken back by its owner (a fresh list says so).@@ -18876,6 +18888,10 @@ class AppNotifier extends ChangeNotifier {_lastError ='${machine.machine.machineShare!.owner} stopped sharing $name with you.';_lastErrorRetryable = false;+ _sharingEndedError = (+ machineId: machine.machine.machineId,+ text: _lastError!,+ );unawaited(refreshMachines());} else {_lastError = machineSelectErrorText(code, name);diff --git a/desktop/lib/widgets/machine_sharing_form.dart b/desktop/lib/widgets/machine_sharing_form.dartindex 33f96afdb..c482d8c5a 100644--- a/desktop/lib/widgets/machine_sharing_form.dart+++ b/desktop/lib/widgets/machine_sharing_form.dart@@ -25,8 +25,9 @@ final _emailPattern = RegExp(r"^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$",);-/// One person in the list: an address the owner named, or a colleague who added a domain share.-typedef _Person = ({String email, bool named, bool usingIt});+/// One person in the list: an address the owner named, and whether they use it now. Everyone at the+/// domain is the switch above the list, never listed one by one.+typedef _Person = ({String email, bool usingIt});/// Sharing one of the account's machines with other accounts/// (docs/plans/2026-10-15-share-machine-plan.md), in the Machines picker's preview like Rename.@@ -156,24 +157,15 @@ class MachineSharingFormState extends State<MachineSharingForm> {];}- /// Everyone in the list: the addresses named, in order, then colleagues who added it through the- /// domain. Whether each uses it now comes from the machine's members.+ /// Everyone in the list: the addresses named, in order. Whether each uses it now comes from the+ /// machine's members. Since 2026-10-16 a domain share is used like an email one, with no add step,+ /// so the members hold everyone at the domain: they are the switch, not rows.List<_Person> get _people {bool usingIt(String email) => _members.any((m) => m['email'] == email && ((m['machines'] as num?) ?? 0) > 0,);return [- for (final email in _emails)- (email: email, named: true, usingIt: usingIt(email)),- for (final member in _members)- if (member['via'] == 'domain' &&- member['email'] is String &&- !_emails.contains(member['email']))- (- email: member['email'] as String,- named: false,- usingIt: usingIt(member['email'] as String),- ),+ for (final email in _emails) (email: email, usingIt: usingIt(email)),];}@@ -321,11 +313,10 @@ class MachineSharingFormState extends State<MachineSharingForm> {: () => unawaited(_add()),),for (final person in _people)- if (person.named)- (- id: 'remove:${person.email}',- run: _busy ? null : () => unawaited(_remove(person.email)),- ),+ (+ id: 'remove:${person.email}',+ run: _busy ? null : () => unawaited(_remove(person.email)),+ ),];}@@ -574,8 +565,8 @@ class MachineSharingFormState extends State<MachineSharingForm> {const SizedBox(height: 2),Text(_sameDomain- ? 'Anyone with an @$domain address can add it from Add machine.'- : 'Let anyone with an @$domain address add it.',+ ? 'Anyone with an @$domain address can use it.'+ : 'Let anyone with an @$domain address use it.',style: DesktopChrome.metadata(),),],@@ -693,12 +684,8 @@ class MachineSharingFormState extends State<MachineSharingForm> {Flexible(child: Text(person.usingIt- ? person.named- ? 'Using it'- : 'Using it · added from $_domain'- : person.named- ? 'Invited · not using it yet'- : 'Added from $_domain',+ ? 'Using it'+ : 'Invited · not using it yet',style: DesktopChrome.metadata(),overflow: TextOverflow.ellipsis,),@@ -708,28 +695,14 @@ class MachineSharingFormState extends State<MachineSharingForm> {],),),- if (person.named)- AppIconButton(- key: ValueKey('machine-sharing:remove:${person.email}'),- icon: AppIcons.close,- tooltip: 'Stop sharing with ${person.email}',- destructive: true,- focusNode: _node('remove:${person.email}'),- onPressed: _busy ? null : () => unawaited(_remove(person.email)),- )- else- Tooltip(- message:- 'Turn off Everyone at $_domain to stop sharing with them',- child: Padding(- padding: const EdgeInsets.all(8),- child: Icon(- AppIcons.globe,- size: AppIcons.inlineSize,- color: DesktopChrome.muted,- ),- ),- ),+ AppIconButton(+ key: ValueKey('machine-sharing:remove:${person.email}'),+ icon: AppIcons.close,+ tooltip: 'Stop sharing with ${person.email}',+ destructive: true,+ focusNode: _node('remove:${person.email}'),+ onPressed: _busy ? null : () => unawaited(_remove(person.email)),+ ),],),);@@ -950,19 +923,14 @@ class MachineSharingFormState extends State<MachineSharingForm> {children: [Expanded(child: line(- '${person.email} ${person.usingIt- ? 'using it'- : person.named- ? 'invited'- : 'added from $_domain'}',+ '${person.email} ${person.usingIt ? 'using it' : 'invited'}',),),- if (person.named)- action(- 'remove:${person.email}',- 'Remove',- _busy ? null : () => unawaited(_remove(person.email)),- ),+ action(+ 'remove:${person.email}',+ 'Remove',+ _busy ? null : () => unawaited(_remove(person.email)),+ ),],),],diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dartindex 74ccba814..0a612beb6 100644--- a/desktop/lib/widgets/swarm_resource_preview.dart+++ b/desktop/lib/widgets/swarm_resource_preview.dart@@ -206,10 +206,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {});}- /// Add a machine shared with this account's domain, from Add machine; or take one back out.- void _addSharedMachine(Machine machine, {bool remove = false}) => unawaited(- _run(() => app.addSharedMachine(machine.machineId, remove: remove)),- );+ /// Add a machine shared with this account's domain, from Add machine. A machine shared with this+ /// account, by its domain or by email alike, is never taken back off its list from here.+ void _addSharedMachine(Machine machine) =>+ unawaited(_run(() => app.addSharedMachine(machine.machineId)));void _closeMachineForm(String? message) {if (!mounted) return;@@ -1080,14 +1080,6 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {busy ? null : _shareMachine,command: 'picker.resource_share',),- if (machine.machine.machineShare case final share? when share.viaDomain)- _ResourceAction(- 'Remove from my list',- busy- ? null- : () => _addSharedMachine(machine.machine, remove: true),- command: 'picker.resource_unshare',- ),...secondary.where((a) => a.command == 'picker.resource_remove'),...secondary.where((a) => a.command == 'picker.device_mine'),if (app.machineListError != null)diff --git a/desktop/test/machine_sharing_ended_test.dart b/desktop/test/machine_sharing_ended_test.dartindex 151860f3c..e80b3a50e 100644--- a/desktop/test/machine_sharing_ended_test.dart+++ b/desktop/test/machine_sharing_ended_test.dart@@ -1,8 +1,91 @@import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:harness/ws/ws_conn.dart';++/// The account's machine list, as `/api/machines` answers it now.+class _Api extends ApiClient {+ _Api() : super(config: AppConfig.dev, session: AuthSession());+ List<Machine> listed = const [];++ @override+ Future<Map<String, dynamic>?> me() async => null;+ @override+ Future<Map<String, dynamic>?> desk() async => null;+ @override+ Future<Map<String, dynamic>?> daemonDevices() async => null;+ @override+ Future<List<Machine>> machines() async => listed;+}++class _Discovery extends LocalCliDiscovery {+ _Discovery() : super(config: AppConfig.dev);+ @override+ Future<String?> computerId() async => 'aabbccddeeff0011';+ @override+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>+ LocalCliEndpoint(+ computerId: 'aabbccddeeff0011',+ wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),+ protocolVersion: localWsProtocolVersion,+ terminalProtocolVersion: 1,+ machineId: 'local-machine',+ backendOnline: true,+ );+}++class _Connection extends WsConn {+ _Connection(String machineId)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async => const {'agents': []};+}++/// Signed in, with this computer's daemon and its machine connections faked.+class _App extends AppNotifier {+ _App(_Api api)+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ localCliDiscovery: _Discovery(),+ connectionForTest: _Connection.new,+ ) {+ this.api = api;+ }+ @override+ Future<void> ensureCliDaemonReady() async {}+}++const _studio = Machine(+ machineId: 'studio',+ authMode: MachineAuthMode.remote,+ name: 'MacBook Pro',+ machineShare: MachineShare(+ ownerName: 'Dee',+ ownerEmail: '[email protected]',+ via: 'email',+ added: true,+ ),+);void main() {TestWidgetsFlutterBinding.ensureInitialized();@@ -52,6 +135,33 @@ void main() {);});+ // Seen 2026-10-16: "Tuan at Autonomous stopped sharing Mac Auto with you." stayed up after Tuan+ // shared it again and the app was using it.+ test(+ 'the stopped-sharing message comes down once the machine is shared again',+ () async {+ final api = _Api();+ app = _App(api)..status = AppStatus.authenticated;+ app.machines = [_studio];+ app.machineStates['studio'] = MachineState(_studio)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ await app.handleEventForTest('studio', {+ 'type': 'machine_select_error',+ 'payload': {'machineId': 'studio', 'error': 'NOT_YOUR_MACHINE'},+ });+ expect(app.lastError, 'Dee stopped sharing MacBook Pro with you.');+ // Still not shared: the list leaves it out, and the message stays.+ await app.refreshMachines();+ expect(app.lastError, 'Dee stopped sharing MacBook Pro with you.');+ // Shared again.+ api.listed = const [_studio];+ await app.refreshMachines();+ expect(app.lastError, isNull);+ expect(app.sharingEnded('studio'), isNull);+ },+ );+test('the account’s own machine refused is said in words, retryable only when retrying can help', () async {app = withMachine(const Machine(diff --git a/desktop/test/machine_sharing_form_test.dart b/desktop/test/machine_sharing_form_test.dartindex 98a5b8bff..c665a7b48 100644--- a/desktop/test/machine_sharing_form_test.dart+++ b/desktop/test/machine_sharing_form_test.dart@@ -200,9 +200,7 @@ void main() {await tester.pumpAndSettle();expect(app.sets.last.sameDomain, isTrue);expect(- find.text(- 'Anyone with an @autonomous.ai address can add it from Add machine.',- ),+ find.text('Anyone with an @autonomous.ai address can use it.'),findsOneWidget,);await _snap(tester, boundary, 'share-people-dark');@@ -253,34 +251,39 @@ void main() {},);- testWidgets('Back with nothing changed closes quietly; light appearance', (- tester,- ) async {- final app = _SharingApp()- ..policy = {- 'emails': ['[email protected]'],- 'sameDomain': true,- 'domain': 'autonomous.ai',- 'members': [- {'email': '[email protected]', 'via': 'email', 'machines': 2},- {'email': '[email protected]', 'via': 'domain', 'machines': 1},- ],- };- final (closed, boundary) = await open(- tester,- app,- brightness: Brightness.light,- );- expect(find.text('Using it · added from autonomous.ai'), findsOneWidget);- expect(- find.byKey(const ValueKey('machine-sharing:remove:[email protected]')),- findsNothing,- );- await _snap(tester, boundary, 'share-people-light');- await tester.tap(find.byKey(const ValueKey('machine-sharing:back')));- await tester.pump();- expect(closed(), '');- });+ testWidgets(+ 'Back with nothing changed closes quietly; light appearance; the domain is not listed person by person',+ (tester) async {+ final app = _SharingApp()+ ..policy = {+ 'emails': ['[email protected]'],+ 'sameDomain': true,+ 'domain': 'autonomous.ai',+ 'members': [+ {'email': '[email protected]', 'via': 'email', 'machines': 2},+ {'email': '[email protected]', 'via': 'domain', 'machines': 1},+ ],+ };+ final (closed, boundary) = await open(+ tester,+ app,+ brightness: Brightness.light,+ );+ // Everyone at the domain is the switch: since 2026-10-16 they use it with no add step, so the+ // members hold the whole domain, and none of them is a row of their own.+ expect(find.text('[email protected]'), findsNothing);+ expect(find.textContaining('added from'), findsNothing);+ expect(find.text('Using it'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('machine-sharing:remove:[email protected]')),+ findsOneWidget,+ );+ await _snap(tester, boundary, 'share-people-light');+ await tester.tap(find.byKey(const ValueKey('machine-sharing:back')));+ await tester.pump();+ expect(closed(), '');+ },+ );testWidgets('a machine that cannot say offers Retry, and no domain at a public one',diff --git a/tui/src/app.rs b/tui/src/app.rsindex 202b072bf..33d0334c5 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -1369,7 +1369,9 @@ impl App {}// This computer first, then the ones that are up.app.fleet.machines.sort_by_key(|m| (!m.local, !m.online(), m.name.to_lowercase()));- let ids: Vec<String> = app.fleet.machines.iter().filter(|m| m.online() && matches!(m.reach, Reach::Unknown | Reach::Error(_))).map(|m| m.id.clone()).collect();+ let ids: Vec<String> = app.fleet.machines.iter()+ .filter(|m| m.online() && (matches!(m.reach, Reach::Unknown | Reach::Error(_)) || (m.reach == Reach::NeedsLink && app.fleet.shares.contains_key(&m.id))))+ .map(|m| m.id.clone()).collect();for id in ids { app.connect(&id) }for machine in app.fleet.machines.iter_mut() { if !machine.online() && machine.reach == Reach::Unknown { machine.reach = Reach::Offline } }crate::workspace_controls::refresh_workspace(app);@@ -1499,7 +1501,10 @@ impl App {agent.activity = crate::activity::Activity::default();agent.activity.unknown = unknown;}- let needs_link = error.code == "NO_PEER_LINK";+ // A machine shared with this account links by its key, never a password: refused, it only+ // means one of the two daemons has not read the sharing yet (the desktop app keeps dialling+ // and gets in). Seen 2026-10-16: hn took it for "not linked", stopped, and showed `?` for good.+ let needs_link = error.code == "NO_PEER_LINK" && !self.fleet.shares.contains_key(&machine_id);// Its owner stopped sharing it: no reconnect brings it back. Say so on its panes and in// the status line, and read the list again, which takes it (and them) away.if error.code == "NOT_YOUR_MACHINE" {@@ -1524,7 +1529,9 @@ impl App {}}if let Some(machine) = self.fleet.machine_mut(&machine_id) {- machine.reach = if needs_link { Reach::NeedsLink } else if machine.online() { Reach::Error(error.to_string()) } else { Reach::Offline };+ machine.reach = if needs_link { Reach::NeedsLink }+ else if error.code == "NO_PEER_LINK" { Reach::Connecting }+ else if machine.online() { Reach::Error(error.to_string()) } else { Reach::Offline };}if machine_id == self.fleet.local_id && !crate::local::is_local(&machine_id) && matches!(error.code.as_str(), "DAEMON_UNREACHABLE" | "HEARTBEAT_TIMEOUT" | "DISCONNECTED") {self.daemon_down = true;@@ -7219,6 +7226,28 @@ mod recovery_tests {assert!(app.links["test-peer"].retry_at.is_none(), "no reconnect is scheduled");}+ // Seen 2026-10-16: a machine shared with this account was refused once (its daemon had not read+ // the sharing yet) and hn showed it `?`, "not linked", for good, while the desktop app got in.+ #[tokio::test]+ async fn a_shared_machine_refused_before_the_sharing_is_read_keeps_dialling() {+ let mut app = fixture();+ app.fleet.shares.insert("test-peer".into(), crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: false });+ app.on_machine("test-peer".into(), 1, MachineEvent::Failed(RpcError::new("NO_PEER_LINK", "")));+ assert_eq!(app.fleet.machines[0].reach, Reach::Connecting, "a shared machine is never asked for a password");+ assert!(app.links["test-peer"].link.is_none());+ assert!(app.links["test-peer"].retry_at.is_some(), "it dials again");+ for id in [1, 2] {+ assert!(matches!(app.panes[&id].phase, Phase::Connecting(_)), "pane {id}: {:?}", app.panes[&id].phase);+ }++ // The account's own machine still needs its password, and is not dialled again by itself.+ let mut app = fixture();+ app.on_machine("test-peer".into(), 1, MachineEvent::Failed(RpcError::new("NO_PEER_LINK", "")));+ assert_eq!(app.fleet.machines[0].reach, Reach::NeedsLink);+ assert!(app.links["test-peer"].retry_at.is_none());+ assert!(matches!(&app.panes[&1].phase, Phase::Card { title, .. } if title == "This machine is not linked here"));+ }+#[tokio::test]async fn expired_lease_recovers_hidden_shells_and_ignores_cancelled_events() {let mut app = fixture();diff --git a/tui/src/devices.rs b/tui/src/devices.rsindex bb8053f44..aa64cc31d 100644--- a/tui/src/devices.rs+++ b/tui/src/devices.rs@@ -147,8 +147,8 @@ pub enum Act {/// This computer shared with these addresses and, or, everyone at its owner's domain; [said] is/// what the footer says once it is.Share { emails: Vec<String>, same_domain: bool, said: String },- /// A machine shared with this account's domain added to its machines, or ([remove]) taken out.- AddShared { machine: String, name: String, remove: bool },+ /// A machine shared with this account's domain added to its machines (an older backend lists one to add).+ AddShared { machine: String, name: String },}/// The panel is asking, in a dialog over it: a line to type (a password shown as dots; the caret@@ -813,21 +813,16 @@ fn run_act(app: &mut App, act: Act) {again(app);});}- Act::AddShared { machine, name, remove } => {- note(app, if remove { "Removing…" } else { "Adding…" });- let payload = json!({ "action": if remove { "remove" } else { "add" }, "machineId": machine });+ // Only an older backend lists a team's machine to add first; a machine shared with you, by email+ // or with your domain, is never taken off your list (owner, 2026-10-16).+ Act::AddShared { machine, name } => {+ note(app, "Adding…");+ let payload = json!({ "action": "add", "machineId": machine });ask(app, Req::Rpc { ty: "shared_machines", payload }, None, move |app, reply| {match shared_answer(reply) {Ok(_) => {- if remove {- app.fleet.shares.remove(&machine);- app.account_machine_removed(&machine);- if app.devices.sub.as_deref() == Some(&format!("m:{machine}")) { app.devices.sub = None }- note(app, format!("Removed {name} from your machines"));- } else {- app.fleet.to_add.retain(|(id, ..)| id != &machine);- note(app, format!("Added {name}. It connects in a moment."));- }+ app.fleet.to_add.retain(|(id, ..)| id != &machine);+ note(app, format!("Added {name}. It connects in a moment."));if app.devices.runner.is_none() { app.refresh_machines() }}Err(message) => fail(app, message),@@ -908,7 +903,7 @@ fn at_char(value: &str, caret: usize) -> usize { value.char_indices().nth(caret)fn confirm(app: &mut App, question: impl Into<String>, act: Act) {app.devices.prompt_actions.set(None);// A destructive yes starts on Cancel, a safe one on Yes.- let risky = matches!(act, Act::ClearPassword | Act::Unlink { .. } | Act::Remove { .. } | Act::Unpair { .. } | Act::AddShared { remove: true, .. });+ let risky = matches!(act, Act::ClearPassword | Act::Unlink { .. } | Act::Remove { .. } | Act::Unpair { .. });app.devices.prompt_row.set(usize::from(!risky));app.devices.prompt_focus.set(true);app.devices.ask = Some(Ask::Confirm { question: question.into(), act });@@ -1142,7 +1137,7 @@ pub fn choose(app: &mut App, view: View, picker: Picker, enter: bool) {(_, "shr") => share_action(app, &rest),(_, "addshared") => {let name = app.fleet.to_add.iter().find(|(id, ..)| *id == rest).map(|(_, name, _)| name.clone()).unwrap_or_else(|| name_of(app, &rest));- run_act(app, Act::AddShared { machine: rest, name, remove: false })+ run_act(app, Act::AddShared { machine: rest, name })}(_, "act") => machine_action(app, &rest),(_, "pw") => match rest.as_str() {@@ -1205,7 +1200,6 @@ fn machine_action(app: &mut App, rest: &str) {match verb {"rename" => entry(app, Entry::Rename { machine, name: name.clone() }, "Machine name", &name, false),"remove" => confirm(app, format!("Delete {name} from your account?"), Act::Remove { machine, name }),- "unshare" => confirm(app, format!("Remove {name} from your machines? You can add it again from Shared with your team."), Act::AddShared { machine, name, remove: true }),"connect" => { switch(app, View::Connect); if let Some(p) = picker_mut(app) { p.select(&format!("m:{machine}")) } start_link(app, machine, name) }"open" => {app.devices.sub = None;@@ -1227,7 +1221,7 @@ fn share_action(app: &mut App, rest: &str) {if same_domain {run_act(app, Act::Share { emails, same_domain: false, said: format!("No longer shared with everyone at @{domain}") })} else {- confirm(app, format!("Share {here} with everyone at @{domain}? They add it from Machines and use it as their own."),+ confirm(app, format!("Share {here} with everyone at @{domain}? They use it as their own: its harnesses, terminals and files."),Act::Share { emails, same_domain: true, said: format!("Shared with everyone at @{domain}") })}}@@ -1401,8 +1395,9 @@ fn machines_rows(app: &App) -> Vec<Row> {for m in app.fleet.machines.iter() {let Some(share) = app.fleet.shares.get(&m.id) else { continue };let (glyph, color, word) = reach(app, m);+ let rtt = app.rtt.get(&m.id).filter(|_| m.usable()).map(|d| format!("{}ms ", d.as_millis())).unwrap_or_default();rows.push(Row::new(format!("m:{}", m.id), m.name.clone()).group(with_you).extra(format!("{} {} {}", m.id, share.owner, share.email)).lead(dot(glyph, color))- .detail(vec![span(format!("shared by {} · ", share.owner), fg(theme::MUTED)), span(word, fg(color))]).right(counts(app, &m.id)));+ .detail(vec![span(format!("shared by {} · ", share.owner), fg(theme::MUTED)), span(word, fg(color))]).right(format!("{rtt}{}", counts(app, &m.id))));}// Shared with this account's domain: Enter adds one.let team = "Shared with your team";@@ -1449,7 +1444,6 @@ fn action_rows(app: &App, id: &str) -> Vec<Row> {// Another account's: its owner renames, removes and shares it.Some(share) => {rows.push(info("shared-by", format!("Shared with you by {}", owner_of(share)), &group));- if share.team { rows.push(act("unshare", "Remove from my machines…", "add it again from Shared with your team", "✗")) }}None => {rows.push(act("rename", "Rename…", "the name every device on the account shows", "✎"));@@ -1475,13 +1469,13 @@ fn share_rows(app: &App) -> Vec<Row> {};if let Some(domain) = &domain {rows.push(Row::new("shr:domain", format!("Everyone at @{domain}")).group(here.clone()).extra("domain team company").lead(dot(if same_domain { "✓" } else { "·" }, if same_domain { theme::ONLINE } else { theme::MUTED }))- .detail(vec![span("they add it from Machines", fg(theme::MUTED))]).right(if same_domain { "on" } else { "off" }));+ .detail(vec![span("they use it as their own", fg(theme::MUTED))]).right(if same_domain { "on" } else { "off" }));}rows.push(Row::new("shr:add", "Add an email…").group(here.clone()).extra("add email person").lead(dot("+", theme::TEAL)).detail(vec![span("they see it in their Machines", fg(theme::MUTED))]));for email in &emails {rows.push(Row::new(format!("shr:rm:{email}"), email.clone()).group(here.clone()).extra("remove").lead(dot("·", theme::MUTED)).right("remove"));}- let using: Vec<String> = sharing_members(app).into_iter().map(|(email, _)| email).collect();+ let using = using_by_email(app);if !using.is_empty() { rows.push(info("share-using", format!("Using it now: {}", using.join(", ")), &here)) }rows}@@ -1492,6 +1486,12 @@ fn sharing_members(app: &App) -> Vec<(String, String)> {.filter_map(|m| Some((m.get("email")?.as_str()?.to_string(), m.get("via").and_then(Value::as_str).unwrap_or("email").to_string()))).collect()}+/// The people this computer is shared with by address who use it now. Everyone at the domain may use it+/// too, and is never named one by one: that is the domain row, not a list of the whole company.+fn using_by_email(app: &App) -> Vec<String> {+ sharing_members(app).into_iter().filter(|(_, via)| via == "email").map(|(email, _)| email).collect()+}+/// A share's owner as people read it: the name, and the address when it says more.fn owner_of(share: &crate::fleet::MachineShare) -> String {if share.email.is_empty() || share.email == share.owner { share.owner.clone() } else { format!("{} ({})", share.owner, share.email) }@@ -1561,7 +1561,6 @@ pub fn preview(app: &App, view: View, id: &str) -> Vec<Line<'static>> {if app.devices.link.as_ref().is_none_or(|l| l.machine != rest) { out.extend(enter_does("type its remote password, then link")) }} else {out.extend(enter_does(match app.fleet.shares.get(rest) {- Some(share) if share.team => "its actions — open, remove from your machines",Some(_) => "its actions — open",None => "its actions — open, connect, rename, remove from account",}));@@ -1576,7 +1575,6 @@ pub fn preview(app: &App, view: View, id: &str) -> Vec<Line<'static>> {"connect" => "asks for its remote password, then links it","rename" => "asks for its new name, then y/n","remove" => "asks y/n, then deletes it from your account",- "unshare" => "asks y/n, then removes it from your machines",_ => "",}));out@@ -1656,7 +1654,7 @@ fn sharing_lines(app: &App) -> Vec<Line<'static>> {if let Some(d) = domain { out.push(kv("domain", format!("everyone at @{d} · {}", if same_domain { "on" } else { "off" }))) }if emails.is_empty() { out.push(kv("people", "nobody yet")) }for (i, email) in emails.iter().enumerate() { out.push(kv(if i == 0 { "people" } else { "" }, email.clone())) }- let using: Vec<String> = sharing_members(app).into_iter().map(|(email, _)| email).collect();+ let using = using_by_email(app);if !using.is_empty() { out.push(kv("using it", using.join(", "))) }out}@@ -1674,10 +1672,8 @@ fn share_preview(app: &App, rest: &str) -> Vec<Line<'static>> {("domain", _) => {let Some(d) = domain else { return vec![] };let mut out = vec![bold(format!("Everyone at @{d}")).into(), Line::raw(""),- Line::raw(format!("Anyone with an @{d} address can add it from Machines and use it as their own.")), Line::raw(""),+ Line::raw(format!("Anyone with an @{d} address can use it as their own: its harnesses, terminals and files.")), Line::raw(""),kv("now", if same_domain { "on" } else { "off" })];- let added: Vec<&str> = members.iter().filter(|(_, via)| via == "domain").map(|(email, _)| email.as_str()).collect();- if !added.is_empty() { out.push(kv("added it", added.join(", "))) }out.extend(enter_does(if same_domain { format!("stops sharing with everyone at @{d}; people you added by email keep it") } else { "asks y/n, then shares it with them".into() }));out}@@ -1828,7 +1824,7 @@ fn ask_title(app: &App, ask: &Ask) -> String {Ask::Confirm { act: Act::Unpair { name, .. }, .. } => format!("Remove Access · {name}"),Ask::Confirm { act: Act::ArmPhone, .. } => "Add Your Phone".into(),Ask::Entry { what: Entry::ShareEmail, .. } | Ask::Confirm { act: Act::Share { .. }, .. } => format!("Share · {}", app.fleet.local_machine_name()),- Ask::Confirm { act: Act::AddShared { name, .. }, .. } => format!("Remove from My Machines · {name}"),+ Ask::Confirm { act: Act::AddShared { name, .. }, .. } => format!("Add to My Machines · {name}"),}}@@ -2098,7 +2094,7 @@ mod tests {}#[test]- fn machines_shared_with_this_account_are_its_to_use_and_the_teams_are_added_with_enter() {+ fn machines_shared_with_this_account_are_its_to_use_and_an_older_backends_team_ones_are_added_with_enter() {const SHARED: &str = "abababababababababababababababab";const TEAM: &str = "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd";let mut app = app((150, 42));@@ -2107,30 +2103,30 @@ mod tests {let dee = crate::fleet::MachineShare { owner: "Dee".into(), email: "[email protected]".into(), team: true };app.fleet.shares.insert(SHARED.into(), dee.clone());app.fleet.to_add.push((TEAM.into(), "gpu-box-2".into(), dee));+ app.rtt.insert(SHARED.into(), std::time::Duration::from_millis(42));open(&mut app, View::Machines);assert_eq!(row_of(&app, &format!("m:{SHARED}")).and_then(|r| r.group.as_deref()), Some("Shared with you"));+ assert!(row_of(&app, &format!("m:{SHARED}")).is_some_and(|r| r.right.starts_with("42ms")), "its round trip, as your own machines show");assert_eq!(row_of(&app, &format!("addshared:{TEAM}")).map(|r| (r.label.as_str(), r.group.as_deref())), Some(("Add gpu-box-2", Some("Shared with your team"))));assert_eq!(row_of(&app, &format!("m:{REMOTE}")).and_then(|r| r.group.as_deref()), Some("Your machines"));- // Enter adds the team's machine, through this computer's daemon.+ // Enter adds the team's machine, through this computer's daemon (an older backend lists it to add first).go_to(&mut app, &format!("addshared:{TEAM}"));press(&mut app, KeyCode::Enter);assert!(has(&log, &rpc("add", json!({ "machineId": TEAM }))));assert!(app.fleet.to_add.is_empty());assert!(app.devices.footer.as_ref().is_some_and(|(t, err, _)| !err && t.starts_with("Added gpu-box-2")));- // A machine shared with you is its owner's to rename or remove; one from the team can leave your list.+ // A machine shared with you is its owner's to rename or remove, and shared with your domain it stays+ // on your list just as one shared by email does (owner, 2026-10-16): no "Remove from my machines".go_to(&mut app, &format!("m:{SHARED}"));press(&mut app, KeyCode::Enter);let here = ids(&app);- assert!(here.contains(&format!("act:unshare:{SHARED}")) && here.contains(&"shared-by".to_string()), "{here:?}");+ assert!(here.contains(&"shared-by".to_string()), "{here:?}");+ assert!(!here.iter().any(|id| id.starts_with("act:unshare:")), "{here:?}");assert!(!here.contains(&format!("act:rename:{SHARED}")) && !here.contains(&format!("act:remove:{SHARED}")));- go_to(&mut app, &format!("act:unshare:{SHARED}"));- press(&mut app, KeyCode::Enter);- press(&mut app, KeyCode::Char('Y'));- assert!(has(&log, &rpc("remove", json!({ "machineId": SHARED }))));- assert!(!app.fleet.shares.contains_key(SHARED));- assert!(app.fleet.machine(SHARED).is_none());+ assert!(!has(&log, &rpc("remove", json!({ "machineId": SHARED }))));+ assert!(app.fleet.shares.contains_key(SHARED));}#[test]@@ -2147,6 +2143,9 @@ mod tests {go_to(&mut app, "shr:domain");press(&mut app, KeyCode::Enter);assert!(app.devices.ask.is_some(), "everyone at the domain is asked first");+ // They use it straight away, as people named by email do: nothing to add first.+ assert!(matches!(&app.devices.ask, Some(Ask::Confirm { question, .. })+ if question.ends_with("with everyone at @acme.io? They use it as their own: its harnesses, terminals and files.")), "{:?}", app.devices.ask);press(&mut app, KeyCode::Char('Y'));assert!(has(&log, &rpc("set", json!({ "emails": [], "sameDomain": true }))));assert_eq!(row_of(&app, "shr:domain").map(|r| r.right.clone()), Some("on".into()));@@ -2198,20 +2197,26 @@ mod tests {assert!(text("account").starts_with("Signed in as [email protected]."), "{}", text("account"));let share = text("share:");- for said in ["get full access", "everyone at @acme.io · on", "[email protected]", "[email protected]", "[email protected], [email protected]"] { assert!(share.contains(said), "{said}: {share}") }- assert!(text("shr:domain").contains("Anyone with an @acme.io address") && text("shr:domain").contains("[email protected]"));- assert!(text("shr:domain").contains("people you added by email keep it"));+ for said in ["get full access", "everyone at @acme.io · on", "[email protected]", "[email protected]", "using it [email protected]"] { assert!(share.contains(said), "{said}: {share}") }+ // Everyone at the domain may use it, and is the domain row: nobody at it is named one by one.+ assert!(!share.contains("[email protected]"), "{share}");+ let domain = text("shr:domain");+ assert!(domain.contains("Anyone with an @acme.io address can use it as their own: its harnesses, terminals and files."), "{domain}");+ assert!(!domain.contains("[email protected]") && !domain.contains("add it from"), "{domain}");+ assert!(domain.contains("people you added by email keep it"));assert!(text("shr:rm:[email protected]").contains("using it") && text("shr:rm:[email protected]").contains("invited · not using it yet"));- assert!(text(&format!("m:{SHARED}")).contains("Dee ([email protected])") && text(&format!("m:{SHARED}")).contains("remove from your machines"));+ assert!(text(&format!("m:{SHARED}")).contains("Dee ([email protected])") && !text(&format!("m:{SHARED}")).contains("remove from your machines"));assert!(text(&format!("addshared:{TEAM}")).contains("Dee ([email protected])"));- for id in ["share:", "shr:domain", "shr:add", "shr:rm:[email protected]", "shr:reload", &format!("addshared:{TEAM}"), &format!("act:unshare:{SHARED}")] {+ for id in ["share:", "shr:domain", "shr:add", "shr:rm:[email protected]", "shr:reload", &format!("addshared:{TEAM}"), &format!("act:open:{SHARED}")] {let said = text(id);assert!(said.lines().any(|l| l.starts_with("enter ") && l.len() > "enter ".len()), "{id}: {said}");}- // And the line in the list itself fits it.+ // And the line in the list itself fits it; the domain row promises no add step.go_to(&mut app, "share:");press(&mut app, KeyCode::Enter);assert!(row_of(&app, "share-what").is_some_and(|r| r.label.chars().count() <= 44));+ assert!(row_of(&app, "shr:domain").is_some_and(|r| r.detail.iter().any(|s| s.content == "they use it as their own")));+ assert_eq!(row_of(&app, "share-using").map(|r| r.label.as_str()), Some("Using it now: [email protected]"));}// Seen 2026-10-16 with a mouse: Share's level had no way out but Esc.