The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-02 1102-m: #2587 #2581 (#2589)
0xken15f377d15db10d
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0dc9b4ca8..e032c8180 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -51,6 +51,7 @@ import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE, typeimport { ancestorsOnce, removeSignIn, SIGN_OUT_BUTTON_FLAG, signOutAsked, type Asker, type SignOutAsked } from './lib/signOut.js'import { AUTH_DIR, AuthSessionError, AuthSessionManager, harnessSessionRequest, knownSsoClientId, newSignInEpoch, readAuthSession, readSignedOut, ssoClientIdFor, updateAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'import { revokeHarnessRefresh } from './team/handoff.js'+import { TEAM_RELAY_GRANT_FILE } from './team/relay.js'import { handOffToGrid } from './lib/gridHandoff.js'import { claimTicket, qrSignIn, type QrSignInTokens } from './lib/qrSignIn.js'import { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'@@ -1767,6 +1768,8 @@ function clearAdapterState(): void {'summaries.json','summary-scratch','e2e',+ // The Team account's kept relay grant (team/relay.ts): a reset starts its token over.+ TEAM_RELAY_GRANT_FILE,// The session search index (lib/sessionSearch/): rebuilt from the transcripts on the next start.SESSION_SEARCH_FILE,`${SESSION_SEARCH_FILE}-wal`,diff --git a/cli/src/lib/subscriptionRelay.spec.ts b/cli/src/lib/subscriptionRelay.spec.tsindex 6c4e9d6af..721e6da85 100644--- a/cli/src/lib/subscriptionRelay.spec.ts+++ b/cli/src/lib/subscriptionRelay.spec.ts@@ -99,6 +99,32 @@ describe('the guest token', () => {})})+describe('a relay started again on its own port', () => {+ const start = (port?: number) => startSubscriptionRelay({ owner: owner({}).subscriptions, ...(port ? { port } : {}) })+ const answers = async (relay: SubscriptionRelay, token: string) => (await fetch(`${relay.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: '{}' })).status++ it('listens on the port it is given, and refuses one that is taken', async () => {+ const first = await start()+ const taken = await start(first.port).then(() => null, (error: NodeJS.ErrnoException) => error.code)+ expect(taken).toBe('EADDRINUSE')+ const { port } = first+ await first.close()+ const again = await start(port)+ expect(again.url).toBe(`http://127.0.0.1:${port}`)+ await again.close()+ })++ it('takes a token back as its own, refuses any other, and a revoke cuts it', async () => {+ const relay = await start()+ relay.adoptToken('[email protected]', 'kept-token-kept-token-kept-token')+ expect(await answers(relay, 'kept-token-kept-token-kept-token')).not.toBe(401)+ expect(await answers(relay, 'other-token-other-token-other-tok')).toBe(401)+ relay.revoke('[email protected]')+ expect(await answers(relay, 'kept-token-kept-token-kept-token')).toBe(401)+ await relay.close()+ })+})+describe('Claude', () => {it('goes upstream with the owner\'s bearer and the OAuth beta, and never the guest\'s token', async () => {await start(ok, owner({ claude: claude(OWNER_CLAUDE) }).subscriptions)diff --git a/cli/src/lib/subscriptionRelay.ts b/cli/src/lib/subscriptionRelay.tsindex 2f18257c9..f1ab97144 100644--- a/cli/src/lib/subscriptionRelay.ts+++ b/cli/src/lib/subscriptionRelay.ts@@ -67,6 +67,8 @@ export interface SubscriptionRelayDeps {fetchImpl?: typeof fetchupstream?: Partial<Record<SubscriptionProvider, string>>now?: () => number+ /** The port to listen on, to come back where running agents expect it (team/relay.ts). Taken, the start fails with EADDRINUSE. */+ port?: number/** One line per request: provider, status, a short guest fingerprint. Never a token. */log?: (line: string) => void}@@ -77,6 +79,8 @@ export interface SubscriptionRelay {url: string/** A new token for [guestEmail]; a guest may hold several (one per harness). */mintToken(guestEmail: string): string+ /** Takes back a token this relay's previous run minted, as a running agent still presents it. */+ adoptToken(guestEmail: string, token: string): void/** Every token [guestEmail] holds stops working at once. */revoke(guestEmail: string): voidclose(): Promise<void>@@ -189,19 +193,23 @@ export async function startSubscriptionRelay(deps: SubscriptionRelayDeps): Promiawait new Promise<void>((resolve, reject) => {server.once('error', reject)- server.listen(0, '127.0.0.1', () => resolve())+ server.listen(deps.port ?? 0, '127.0.0.1', () => resolve())})const port = (server.address() as AddressInfo).port+ const adopt = (guestEmail: string, token: string) => {+ const digest = createHash('sha256').update(token).digest()+ tokens.set(digest.toString('hex'), { guest: guestEmail.toLowerCase(), digest })+ }return {port,url: `http://127.0.0.1:${port}`,mintToken(guestEmail) {const token = randomBytes(32).toString('base64url')- const digest = createHash('sha256').update(token).digest()- tokens.set(digest.toString('hex'), { guest: guestEmail.toLowerCase(), digest })+ adopt(guestEmail, token)return token},+ adoptToken: adopt,revoke(guestEmail) {const guest = guestEmail.toLowerCase()for (const [key, entry] of tokens) if (entry.guest === guest) tokens.delete(key)diff --git a/cli/src/services/guestLaunches.spec.ts b/cli/src/services/guestLaunches.spec.tsindex 371f53cac..2edc0edad 100644--- a/cli/src/services/guestLaunches.spec.ts+++ b/cli/src/services/guestLaunches.spec.ts@@ -17,7 +17,7 @@ function setup(over: {let n = 0const relay: SubscriptionRelay = {port: 41234, url: 'http://127.0.0.1:41234',- mintToken: vi.fn((guest: string) => `token-${guest}-${++n}`),+ adoptToken: () => {}, mintToken: vi.fn((guest: string) => `token-${guest}-${++n}`),revoke: vi.fn((guest: string) => { revoked.push(guest) }),close: vi.fn(async () => {}),}@@ -54,7 +54,7 @@ describe('a guest\'s harness, as shared machines builds it', () => {})it('works with the defaults: no log, the machine\'s helper and LANG, no folders', async () => {- const relay = { port: 1, url: 'http://127.0.0.1:1', mintToken: () => 't', revoke: () => {}, close: async () => {} }+ const relay = { port: 1, url: 'http://127.0.0.1:1', adoptToken: () => {}, mintToken: () => 't', revoke: () => {}, close: async () => {} }const shareFolders = vi.fn(async () => {})const launches = createGuestLaunches({ accounts: { ensureGuest: async () => ({ user: KIM, home: '/g', workspace: '/g/work' }), shareFolders, guests: () => [KIM] } as unknown as GuestAccounts,helperState: async () => 'ready', startRelay: async () => relay })@@ -89,7 +89,7 @@ describe('a guest\'s harness, as shared machines builds it', () => {it('starts the relay again for the next harness when it could not start', async () => {let fails = true- const relay = { port: 1, url: 'http://127.0.0.1:1', mintToken: () => 't', revoke: () => {}, close: async () => {} }+ const relay = { port: 1, url: 'http://127.0.0.1:1', adoptToken: () => {}, mintToken: () => 't', revoke: () => {}, close: async () => {} }const { launches, startRelay } = setup({ relay: async () => { if (fails) throw new Error('EADDRINUSE'); return relay } })expect(await launches.launch(input)).toEqual({ ok: false, error: 'GUEST_RELAY_FAILED', detail: expect.any(String) })await flush()diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 8b17cded4..060a1426b 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -23,7 +23,7 @@ import { teamEngineReporter, type TeamEngineReporter } from '../team/engines.js'import { AUTO_SETUP_REASONS, realTeamAutoSetup, type AutoSetupReason, type TeamAutoSetup } from '../team/autoSetup.js'import { openDaemon } from '../agentClient/daemon.js'import { readTeamConfig } from '../team/config.js'-import { realTeamRelayPublisher, type TeamRelayPublisher } from '../team/relay.js'+import { realTeamRelayPublisher, TEAM_RELAY_GRANT_FILE, type TeamRelayPublisher } from '../team/relay.js'import { readLastTry, refreshCreationId, refreshTeamAccount, teamRefreshFile, writeLastTry, type TeamRefreshDeps } from '../team/refresh.js'import { readTeamStatus } from '../team/privacy.js'import { ensureTeamTmux, TMUX_MANIFEST_URL, tmuxRunsAt, untarGz, type TeamTmuxDeps, type TeamTmuxOutcome } from '../team/tmux.js'@@ -363,8 +363,10 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =// On the Mac's owner's daemon, while a Harness Team account exists here: the owner's subscriptions for it, through a// relay of its own (team/relay.ts). Kept through a lost backend connection, which running agents do not need.const relay = (options.teamRelay ?? (() => realTeamRelayPublisher(- () => startSubscriptionRelay({ owner: createOwnerSubscriptions(), log: line => console.log(`[team] relay · ${line}`) }),+ port => startSubscriptionRelay({ owner: createOwnerSubscriptions(), log: line => console.log(`[team] relay · ${line}`), ...(port ? { port } : {}) }),() => readTeamConfig(), options.team ?? (() => readAuthSession()?.kind === 'team'), line => console.log(`[team] ${line}`),+ // In the owner's closed home: a running Team agent's relay outlives this daemon (task #2125).+ join(core.dataDir, TEAM_RELAY_GRANT_FILE),// A team account still on a build that cannot use the relay is updated from here (team/refresh.ts).(publishedAt) => refreshTeamAccount(realTeamRefreshDeps(core, publishedAt)))))()let autoSetup: Promise<Pick<TeamAutoSetup, 'offer' | 'decline'> & Partial<Pick<TeamAutoSetup, 'status'>>> | null = nulldiff --git a/cli/src/team/relay.spec.ts b/cli/src/team/relay.spec.tsindex de0abc8cc..56330ecfd 100644--- a/cli/src/team/relay.spec.ts+++ b/cli/src/team/relay.spec.ts@@ -1,15 +1,17 @@-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'+import { createServer } from 'node:http'+import type { AddressInfo } from 'node:net'import { tmpdir } from 'node:os'import { dirname, join } from 'node:path'import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'-import { CODEX_RELAY_ACCOUNT, type SubscriptionRelay } from '../lib/subscriptionRelay.js'+import { CODEX_RELAY_ACCOUNT, startSubscriptionRelay, type SubscriptionRelay } from '../lib/subscriptionRelay.js'import { engineAccount } from '../lib/engineAccount.js'import type { TeamConfig } from './config.js'import {- publishTeamRelay, publishWindowsTeamRelay, readTeamRelay, readWindowsTeamRelay, setfaclGrant, TEAM_RELAY_GUEST, teamRelayDir, teamRelayFile,+ publishTeamRelay, publishWindowsTeamRelay, readRememberedGrant, readTeamRelay, writeRememberedGrant, readWindowsTeamRelay, setfaclGrant, TEAM_RELAY_GUEST, teamRelayDir, teamRelayFile,teamRelayLaunch, teamRelayPublished, NO_PM_RELAY, type OwnerRelayLaunch, TeamRelayPublisher, prepareCodexHome, installedCodexVersion,CODEX_CLIENT_VERSION_FALLBACK, settleCodexModel, offeredCodexModels, codexModelNotOffered,- type TeamRelayLaunchDeps, type TeamRelayPublisherDeps, type TeamRelayReadDeps, type WindowsRelayFs,+ type TeamRelayGrant, type TeamRelayLaunchDeps, type TeamRelayPublisherDeps, type TeamRelayReadDeps, type WindowsRelayFs,} from './relay.js'const config = { user: 'harnessteam', owner: 'owner', ownerHome: '/Users/owner' } as TeamConfig@@ -18,7 +20,7 @@ const cleanup: string[] = []afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })function relay(): SubscriptionRelay {- return { port: 9, url: 'http://127.0.0.1:9', mintToken: vi.fn(() => TOKEN), revoke: vi.fn(), close: vi.fn(async () => {}) }+ return { port: 9, url: 'http://127.0.0.1:9', mintToken: vi.fn(() => TOKEN), adoptToken: vi.fn(), revoke: vi.fn(), close: vi.fn(async () => {}) }}function publisher(over: Partial<TeamRelayPublisherDeps> = {}) {@@ -75,6 +77,181 @@ describe('the owner\'s daemon, for the Harness Team account', () => {expect(f.deps.withdraw).toHaveBeenCalledTimes(2)})+ // Task #2125: a running Team agent keeps the address and token it launched with, so a restart of this daemon stranded it.+ describe('across a restart of this daemon', () => {+ const KEPT = { url: 'http://127.0.0.1:61375', token: 'k'.repeat(43), mintedAt: 1_000 }+ const taken = () => Object.assign(new Error('taken'), { code: 'EADDRINUSE' })++ it('comes back on the same port, takes the same token back and publishes the same grant', async () => {+ const f = publisher({ remembered: () => KEPT, remember: vi.fn(), forget: vi.fn(), now: () => 2_000 })+ await f.p.tick()+ expect(f.deps.startRelay).toHaveBeenCalledWith(61375)+ expect(f.running.adoptToken).toHaveBeenCalledWith(TEAM_RELAY_GUEST, KEPT.token)+ expect(f.running.mintToken).not.toHaveBeenCalled()+ expect(f.deps.publish).toHaveBeenCalledWith(config, { url: KEPT.url, token: KEPT.token })+ })++ it('remembers a new grant before it publishes it', async () => {+ const remember = vi.fn()+ const f = publisher({ remembered: () => null, remember, forget: vi.fn(), now: () => 5_000 })+ await f.p.tick()+ expect(f.deps.startRelay).toHaveBeenCalledWith(undefined)+ expect(remember).toHaveBeenCalledWith({ url: 'http://127.0.0.1:9', token: TOKEN, mintedAt: 5_000 })+ })++ it('waits for a port the old daemon is still closing', async () => {+ const running = relay(), wait = vi.fn(async () => {})+ const startRelay = vi.fn<TeamRelayPublisherDeps['startRelay']>().mockRejectedValueOnce(taken()).mockRejectedValueOnce(taken()).mockResolvedValue(running)+ const f = publisher({ remembered: () => KEPT, remember: vi.fn(), forget: vi.fn(), startRelay, wait, now: () => 2_000 })+ await f.p.tick()+ expect(wait).toHaveBeenCalledTimes(2)+ expect(running.adoptToken).toHaveBeenCalledWith(TEAM_RELAY_GUEST, KEPT.token)+ expect(f.deps.publish).toHaveBeenCalledWith(config, { url: KEPT.url, token: KEPT.token })+ })++ it('gives up a port held for good: a new port and a new token, so what its holder heard is dead', async () => {+ const running = relay(), remember = vi.fn()+ const startRelay = vi.fn<TeamRelayPublisherDeps['startRelay']>(async port => { if (port) throw taken(); return running })+ const f = publisher({ remembered: () => KEPT, remember, forget: vi.fn(), startRelay, wait: async () => {}, now: () => 2_000 })+ await f.p.tick()+ expect(startRelay).toHaveBeenLastCalledWith(undefined)+ expect(startRelay.mock.calls.filter(([port]) => port === 61375)).toHaveLength(10)+ expect(running.adoptToken).not.toHaveBeenCalled()+ expect(remember).toHaveBeenCalledWith({ url: 'http://127.0.0.1:9', token: TOKEN, mintedAt: 2_000 })+ expect(f.deps.publish).toHaveBeenCalledWith(config, { url: 'http://127.0.0.1:9', token: TOKEN })+ })++ it('gives the token an end: at a restart past 30 days it starts with a new port and token, and says running agents need a restart', async () => {+ const DAY = 86_400_000+ for (const [age, kept] of [[29 * DAY, true], [31 * DAY, false]] as const) {+ const remember = vi.fn()+ const f = publisher({ remembered: () => KEPT, remember, forget: vi.fn(), now: () => KEPT.mintedAt + age })+ await f.p.tick()+ expect(f.deps.startRelay, String(age)).toHaveBeenCalledWith(kept ? 61375 : undefined)+ expect(remember).toHaveBeenCalledTimes(kept ? 0 : 1)+ if (!kept) expect(JSON.stringify(vi.mocked(f.deps.log).mock.calls)).toContain('restart')+ }+ })++ it('never takes a grant dated in the future as young', async () => {+ const f = publisher({ remembered: () => ({ ...KEPT, mintedAt: 9_000 }), remember: vi.fn(), forget: vi.fn(), now: () => 2_000 })+ await f.p.tick()+ expect(f.deps.startRelay).toHaveBeenCalledWith(undefined)+ })++ it('drops the old grant before anything else when it gives way: a failed save never revives the old token on the old port', async () => {+ for (const over of [+ { now: () => KEPT.mintedAt + 31 * 86_400_000 },+ { now: () => 2_000, wait: async () => {}, startRelay: vi.fn<TeamRelayPublisherDeps['startRelay']>(async port => { if (port) throw taken(); return relay() }) },+ ] as Array<Partial<TeamRelayPublisherDeps>>) {+ const order: string[] = []+ const f = publisher({ remembered: () => KEPT, forget: () => order.push('forget'), remember: () => { order.push('remember'); throw new Error('disk full') }, ...over })+ await f.p.tick()+ expect(order).toEqual(['forget', 'remember'])+ }+ })++ it('falls through to a new port on any other failure to listen there, and says why', async () => {+ const running = relay()+ const startRelay = vi.fn<TeamRelayPublisherDeps['startRelay']>(async port => { if (port) throw new Error('bad port'); return running })+ const f = publisher({ remembered: () => KEPT, remember: vi.fn(), forget: vi.fn(), startRelay, now: () => 2_000 })+ await f.p.tick()+ expect(startRelay).toHaveBeenCalledTimes(2)+ expect(f.deps.publish).toHaveBeenCalledWith(config, { url: 'http://127.0.0.1:9', token: TOKEN })+ expect(JSON.stringify(vi.mocked(f.deps.log).mock.calls)).toContain('bad port')+ })++ it('does not swallow another failure to start', async () => {+ const f = publisher({ remembered: () => KEPT, remember: vi.fn(), forget: vi.fn(), startRelay: vi.fn(async () => { throw new Error('no sockets') }), now: () => 2_000 })+ await f.p.tick()+ expect(f.deps.publish).not.toHaveBeenCalled()+ expect(f.deps.log).toHaveBeenCalledWith('team relay: no sockets')+ })++ it('still publishes when the grant cannot be remembered, and says so without the token', async () => {+ const f = publisher({ remembered: () => null, remember: () => { throw new Error('disk full') }, forget: vi.fn() })+ await f.p.tick()+ expect(f.deps.publish).toHaveBeenCalled()+ expect(JSON.stringify(vi.mocked(f.deps.log).mock.calls)).toContain('disk full')+ expect(JSON.stringify(vi.mocked(f.deps.log).mock.calls)).not.toContain(TOKEN)+ })++ it('keeps the grant when it stops, and forgets it once the team account is gone', async () => {+ let present: TeamConfig | null = config+ const forget = vi.fn()+ const f = publisher({ config: () => present, remembered: () => null, remember: vi.fn(), forget })+ await f.p.tick()+ await f.p.stop()+ expect(f.deps.withdraw).toHaveBeenCalledWith('owner')+ expect(forget).not.toHaveBeenCalled()+ present = null+ await f.p.tick()+ expect(forget).toHaveBeenCalled()+ })++ it('reaches the model through a real relay before and after: what a running agent holds keeps working', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'team-relay-restart-')); cleanup.push(dir)+ const file = join(dir, 'team-relay-grant.json')+ const owner = { read: async () => ({ provider: 'claude' as const, accessToken: 'owner-fixture', expiresAt: null, accountId: null }), refresh: async () => null }+ const upstream = createServer((_req, res) => { res.writeHead(200); res.end('{}') })+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve))+ onTestFinished(() => { upstream.closeAllConnections(); upstream.close() })+ const claude = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`+ const run = () => {+ let present = false+ const published: TeamRelayGrant[] = []+ const p = new TeamRelayPublisher({ config: () => config, user: () => 'owner', team: () => false,+ startRelay: port => startSubscriptionRelay({ owner, upstream: { claude }, ...(port ? { port } : {}) }),+ publish: async (_c, grant) => { present = true; published.push(grant) }, published: () => present, withdraw: () => { present = false }, log: () => {},+ remembered: () => readRememberedGrant(file), remember: grant => writeRememberedGrant(file, grant), forget: () => rmSync(file, { force: true }), wait: async () => {} })+ return { p, published }+ }+ const first = run()+ await first.p.tick()+ const agent = first.published[0]!+ const ask = async () => (await fetch(`${agent.url}/claude/v1/messages`, { method: 'POST', headers: { authorization: `Bearer ${agent.token}` }, body: '{}' })).status+ expect(await ask()).toBe(200)+ await first.p.stop()+ await expect(ask()).rejects.toThrow()+ const second = run()+ await second.p.tick()+ expect(second.published[0]).toEqual(agent)+ expect(Object.keys(agent).sort()).toEqual(['token', 'url'])+ expect(await ask()).toBe(200)+ await second.p.stop()+ })+ })++ describe('the kept grant on disk', () => {+ const KEPT = { url: 'http://127.0.0.1:61375', token: 'k'.repeat(43), mintedAt: 1_000 }+ const folder = () => { const dir = mkdtempSync(join(tmpdir(), 'team-relay-grant-')); cleanup.push(dir); return dir }++ it('round-trips, closed to everyone else', () => {+ const file = join(folder(), 'grant.json')+ writeRememberedGrant(file, KEPT)+ expect(readRememberedGrant(file)).toEqual(KEPT)+ expect(statSync(file).mode & 0o777).toBe(0o600)+ writeRememberedGrant(file, { ...KEPT, url: 'http://127.0.0.1:61376' })+ expect(readRememberedGrant(file)?.url).toBe('http://127.0.0.1:61376')+ })++ it.each([+ ['missing', () => {}],+ ['corrupt', (file: string) => writeFileSync(file, 'not json', { mode: 0o600 })],+ ['open to others', (file: string) => writeFileSync(file, JSON.stringify(KEPT), { mode: 0o644 })],+ ['another address', (file: string) => writeFileSync(file, JSON.stringify({ ...KEPT, url: 'http://evil.example:1' }), { mode: 0o600 })],+ ['a bad token', (file: string) => writeFileSync(file, JSON.stringify({ ...KEPT, token: 'short' }), { mode: 0o600 })],+ ['a port past the last', (file: string) => writeFileSync(file, JSON.stringify({ ...KEPT, url: 'http://127.0.0.1:70000' }), { mode: 0o600 })],+ ['port zero', (file: string) => writeFileSync(file, JSON.stringify({ ...KEPT, url: 'http://127.0.0.1:0' }), { mode: 0o600 })],+ ['undated', (file: string) => { const { mintedAt: _m, ...rest } = KEPT; writeFileSync(file, JSON.stringify(rest), { mode: 0o600 }) }],+ ['a link', (file: string) => { const real = `${file}.real`; writeFileSync(real, JSON.stringify(KEPT), { mode: 0o600 }); symlinkSync(real, file) }],+ ])('ignores a file that is %s', (_name, make) => {+ const file = join(folder(), 'grant.json')+ make(file)+ expect(readRememberedGrant(file)).toBeNull()+ })+ })+it('starts a relay that failed again on the next look, and says why', async () => {const f = publisher()vi.mocked(f.deps.startRelay).mockRejectedValueOnce(new Error('no port'))diff --git a/cli/src/team/relay.ts b/cli/src/team/relay.tsindex befa3b3c2..45d70d3ce 100644--- a/cli/src/team/relay.ts+++ b/cli/src/team/relay.ts@@ -54,7 +54,13 @@ export interface TeamRelayPublisherDeps {user(): string/** Whether this daemon runs team work only: it never publishes. */team(): boolean- startRelay(): Promise<SubscriptionRelay>+ /** [port]: where to listen, to come back where running agents expect it; EADDRINUSE if taken. */+ startRelay(port?: number): Promise<SubscriptionRelay>+ /** The grant this daemon's previous run kept (readRememberedGrant). A running agent still holds it. Absent: none is kept. */+ remembered?(): RememberedGrant | null+ remember?(grant: RememberedGrant): void+ forget?(): void+ wait?(ms: number): Promise<void>publish(config: TeamConfig, grant: TeamRelayGrant): Promise<void>/** Whether the published file is still there (someone may have removed the folder). */published(config: TeamConfig): boolean@@ -69,6 +75,38 @@ export interface TeamRelayPublisherDeps {/** How often the owner's daemon looks again: a team account set up later gets its relay within this long. */export const TEAM_RELAY_CHECK_MS = 60_000+/** How long a kept token lives: one heard once would otherwise spend the owner's subscription until the account is removed+ * (security review 1 of #2587). A restart past this strands running agents, at most once a month. */+export const TEAM_RELAY_TOKEN_MS = 30 * 86_400_000+/** The grant, and when it was minted, as this daemon keeps it. The team account reads only the grant. */+export interface RememberedGrant extends TeamRelayGrant { mintedAt: number }+/** The kept grant's name in the owner's data folder. */+export const TEAM_RELAY_GRANT_FILE = 'team-relay-grant.json'+const PORT_TRIES = 10+const PORT_WAIT_MS = 1_000++/** The grant its previous run left, for this daemon's next start: null unless it is a plain file of this user's, closed to+ * everyone else, naming a loopback address and a token of the shape this relay mints. Windows has no mode to check: the+ * owner's data folder is closed by its ACL. */+export function readRememberedGrant(file: string): RememberedGrant | null {+ try {+ const info = lstatSync(file)+ if (!info.isFile()) return null+ if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) return null+ const value = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>+ if (typeof value.url !== 'string' || !RELAY_URL.test(value.url) || typeof value.token !== 'string' || !TOKEN.test(value.token)) return null+ const port = Number(value.url.slice(value.url.lastIndexOf(':') + 1))+ if (!(port >= 1 && port <= 65535) || typeof value.mintedAt !== 'number' || !Number.isFinite(value.mintedAt)) return null+ return { url: value.url, token: value.token, mintedAt: value.mintedAt }+ } catch { return null }+}++export function writeRememberedGrant(file: string, grant: RememberedGrant): void {+ const next = `${file}.${process.pid}.tmp`+ rmSync(next, { force: true })+ writeFileSync(next, `${JSON.stringify(grant)}\n`, { mode: 0o600, flag: 'wx' })+ renameSync(next, file)+}export class TeamRelayPublisher {private timer: ReturnType<typeof setInterval> | null = null@@ -96,18 +134,56 @@ export class TeamRelayPublisher {if (this.deps.team()) returnconst config = this.deps.config()// Only the Mac's owner's daemon holds the owner's sign-ins: another account's daemon on this Mac publishes nothing.- if (!config || config.owner !== this.deps.user()) { await this.close(); return }+ if (!config || config.owner !== this.deps.user()) { await this.close(); this.deps.forget?.(); return }if (this.grant && this.owner === config.owner && this.deps.published(config)) return- this.relay ??= this.deps.startRelay()+ this.relay ??= this.openRelay()// A relay that could not start is started again on the next pass.const relay = await this.relay.catch((error: unknown) => { this.relay = null; throw error })- this.grant ??= { url: relay.url, token: relay.mintToken(TEAM_RELAY_GUEST) }+ if (!this.grant) {+ this.grant = { url: relay.url, token: relay.mintToken(TEAM_RELAY_GUEST) }+ try { this.deps.remember?.({ ...this.grant, mintedAt: (this.deps.now ?? Date.now)() }) } catch (error) {+ this.deps.log(`team relay: could not keep its address for the next restart: ${error instanceof Error ? error.message : String(error)}`)+ }+ }await this.deps.publish(config, this.grant)this.publishedAt = (this.deps.now ?? Date.now)()this.owner = config.ownerthis.deps.log('team relay: the Harness Team account uses this Mac\'s subscriptions')}+ /**+ * The relay, where running agents expect it (task #2125): they keep the address and token they launched with, so a relay on a+ * new port with a new token strands every one of them. The old daemon may still be closing, so a taken port is tried for ten+ * seconds. Held for good, it gives way to a new port and a new token, so what the port's holder heard is dead. Running agents still+ * send their requests to that holder until they restart, as they did to any old port before this.+ */+ private async openRelay(): Promise<SubscriptionRelay> {+ const kept = this.deps.remembered?.()+ const age = kept ? (this.deps.now ?? Date.now)() - kept.mintedAt : 0+ if (kept && (age < 0 || age > TEAM_RELAY_TOKEN_MS)) this.deps.log('team relay: its token reached its age, so it has a new one, and running agents need a restart')+ else if (kept) {+ const port = Number(new URL(kept.url).port)+ for (let attempt = 1; attempt <= PORT_TRIES; attempt++) {+ try {+ const relay = await this.deps.startRelay(port)+ relay.adoptToken(TEAM_RELAY_GUEST, kept.token)+ this.grant = { url: kept.url, token: kept.token }+ return relay+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') {+ this.deps.log(`team relay: could not listen on its kept port: ${error instanceof Error ? error.message : String(error)}`)+ break+ }+ if (attempt === PORT_TRIES) this.deps.log(`team relay: port ${port} stayed taken, so running agents keep sending their requests to whatever holds it until they restart`)+ else await (this.deps.wait ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))))(PORT_WAIT_MS)+ }+ }+ }+ // Dropped first: a save that fails next must never bring this token back on this port at the next start.+ if (kept) this.deps.forget?.()+ return this.deps.startRelay(undefined)+ }+private async close(): Promise<void> {if (this.owner) this.deps.withdraw(this.owner)this.owner = null@@ -244,8 +320,8 @@ export const teamRelayPublished = (config: TeamConfig, exists: (path: string) =>try { lstatSync(path); return true } catch { return false }}, platform: NodeJS.Platform = 'darwin') => exists(teamRelayFile(config.owner, platform))-export function realTeamRelayPublisher(startRelay: () => Promise<SubscriptionRelay>, config: () => TeamConfig | null,- team: () => boolean, log: (line: string) => void, afterPass?: (publishedAt: number | null) => Promise<void>): TeamRelayPublisher {+export function realTeamRelayPublisher(startRelay: (port?: number) => Promise<SubscriptionRelay>, config: () => TeamConfig | null,+ team: () => boolean, log: (line: string) => void, grantFile: string, afterPass?: (publishedAt: number | null) => Promise<void>): TeamRelayPublisher {return new TeamRelayPublisher({...(afterPass ? { afterPass } : {}),// Tests inject a publisher: a test never reads this Mac's own team account, starts a relay on the owner's sign-ins,@@ -257,6 +333,9 @@ export function realTeamRelayPublisher(startRelay: () => Promise<SubscriptionRel: publishTeamRelay(c, grant, process.getuid?.() ?? -1, grantFor(process.platform), teamRelayDir(c.owner, process.platform)),published: (c) => teamRelayPublished(c, undefined, process.platform),withdraw: (owner) => withdrawTeamRelay(owner, process.platform),+ remembered: () => readRememberedGrant(grantFile),+ remember: (grant) => writeRememberedGrant(grantFile, grant),+ forget: () => rmSync(grantFile, { force: true }),})}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex f13b9e336..c327d40ef 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -2285,7 +2285,11 @@ class _SuperTabViewState extends State<SuperTabView>Widget _header(SuperTabConversation? group, bool narrow, bool showRoster) =>Container(constraints: const BoxConstraints(minHeight: 52),- padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),+ // A phone's rows line up (Huy, 2026-11-02): the sidebar icon starts at+ // the top bar's edge, and the people icon sits under its avatar.+ padding: _phone+ ? kPhoneBarRowPadding+ : const EdgeInsets.symmetric(horizontal: 20, vertical: 6),decoration: BoxDecoration(border: Border(bottom: BorderSide(color: DesktopChrome.rim)),),diff --git a/desktop/lib/widgets/finger_target.dart b/desktop/lib/widgets/finger_target.dartindex 557d4756d..445a6f006 100644--- a/desktop/lib/widgets/finger_target.dart+++ b/desktop/lib/widgets/finger_target.dart@@ -2,6 +2,7 @@ import 'dart:math' as math;import 'package:flutter/widgets.dart';+import '../shared/theme/app_icons.dart';import '../state/workspace_chrome.dart';/// The smallest target a finger can hit, both ways (audit finding S1).@@ -14,6 +15,16 @@ const double kPhoneBarIcon = 20;/// How far the phone's top bar keeps what it draws from the screen's edges.const double kPhoneBarGutter = 16;+/// A row under the phone's top bar with its own finger-wide icons at each end,+/// so that they line up with it: the first icon starts at [kPhoneBarGutter], where+/// the bar's text does, and the last is centred under the bar's last icon.+const EdgeInsets kPhoneBarRowPadding = EdgeInsets.fromLTRB(+ kPhoneBarGutter - (kFingerTarget - AppIcons.inlineSize) / 2,+ 6,+ kPhoneBarGutter + (kPhoneBarIcon - kFingerTarget) / 2,+ 6,+);+/// One icon of the phone's top bar: exactly a finger's square, whatever the/// terminal font's cell, so the icons sit side by side at an even spacing.Widget phoneBarCell(Widget child) =>diff --git a/desktop/test/web_chrome_menus_test.dart b/desktop/test/web_chrome_menus_test.dartindex 1b0d5aa63..225306ca8 100644--- a/desktop/test/web_chrome_menus_test.dart+++ b/desktop/test/web_chrome_menus_test.dart@@ -15,6 +15,7 @@ import 'package:harness/widgets/workspace_account_button.dart';import 'support/capture.dart';import 'support/real_fonts.dart';+import 'support/super_tab_phone.dart';import 'swarm_state_test.dart' show createApp;/// The web bar after Huy's ask (2026-11-02): no left menu; the avatar's account@@ -358,6 +359,44 @@ void main() {}}+ // Huy, 2026-11-02: each row was even on its own, but not with the other.+ for (final width in [360.0, 390.0]) {+ testWidgets('the Swarm header under it shares its edges at $width', (+ tester,+ ) async {+ final size = Size(width, 740);+ final app = await _mount(tester, size);+ final name = tester.getRect(+ find+ .descendant(+ of: find.byKey(const ValueKey('web-tab-switcher')),+ matching: find.byType(Text),+ )+ .first,+ );+ final avatar = tester.getRect(+ find+ .descendant(of: _avatar, matching: find.byType(AccountAvatar))+ .first,+ );+ await _done(tester, app);++ final (_, controller) = await mountPhoneSuperTab(tester, size);+ Rect icon(String tooltip) => tester.getRect(+ find+ .descendant(+ of: find.byTooltip(tooltip),+ matching: find.byType(Icon),+ )+ .first,+ );+ expect(icon('Conversations').left, name.left);+ expect(icon('Members and machines').center.dx, avatar.center.dx);+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, controller);+ });+ }+testWidgets('Machines and Models stay in the phone footer\'s menu', (tester,) async {diff --git a/docs/plans/2026-11-02-team-relay-survives-restart-plan.md b/docs/plans/2026-11-02-team-relay-survives-restart-plan.mdnew file mode 100644index 000000000..98434c3ac--- /dev/null+++ b/docs/plans/2026-11-02-team-relay-survives-restart-plan.md@@ -0,0 +1,91 @@+# Team Relay Survives Its Owner's Restart Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task.++**Goal:** A running Team agent keeps reaching the model after its owner's daemon restarts.++**Architecture:** The owner's daemon runs the Team account's relay on a random port with a new token each start, and a running agent keeps the address and token it launched with. So every restart strands every running Team Claude agent with "Connection refused". The daemon now keeps its grant in a private file and, at its next start, binds the same port and accepts the same token. If the port is taken, it falls back to a new port and a new token, as today.++**Tech Stack:** TypeScript, Node `http`, Vitest.++**Spec:** Task #2125. The Lead confirmed the cause on Mac Pro-9: a fresh Team agent answers at once, while running ones get ECONNREFUSED on their launch port. #2550, #2558 and #2576 are not the cause; the dev build's install restarted the owner's daemons.++## Global Constraints++- Never print or log a token. It lives only in the private file, the published file and the launched engine's environment.+- The private file is the owner's: mode 0600, in the owner's Harness data folder, inside the closed home. Ignored unless it is a plain file of this user's, closed to everyone else.+- Stopping the daemon still withdraws the published file, so nothing new launches against a stopped relay.+- A Team account's removal forgets the private file too. The next account gets a new token.+- Swarm code stays out of `cli/src/core`. Two security reviews (this touches a credential): Reed and Cleo.++## Review Focus++1. The old daemon is still closing when the new one binds: it retries for 10 seconds before it gives up the port.+2. Another process holds the port: a new port and a **new** token, so whatever that process heard is dead.+3. A private file that is corrupt, a link, someone else's or open to others: ignored, with a new grant and no crash.+4. A token heard on the port while the daemon was down keeps working once it returns, because the token is reused. This is new, and stays as a named limit, ended by a 30-day rotation at a restart: see Design.+5. Revoking the Team account's token cuts a reused token as it does a minted one.++## Design++- **Growth:** one file, replaced in place, deleted with the Team account.+- **Concurrency:** one daemon owns the file. A write is a temporary file and a rename.+- **Read cost:** one read at the daemon's start.+- **Scale:** N/A because it is one grant per Mac.+- **Compatibility:** Team daemons are unchanged, as they read the same published file. The first restart onto this build still strands running agents, since the old daemon saved no grant.+- **Migration and rollback:** none. Rolling back leaves an unused file.+- **Audience:** the port still takes only the token. Reading the token needs the owner's account.+- **Identity:** N/A because no login changes.+- **Failure:** a failed save is logged, and only continuity is lost. The port taken gets a logged fallback.+- **Platforms:** the same code on macOS, Linux and Windows. Windows skips the mode check, as the folder's ACL covers it.+- **Security limit:** while the daemon is down, a local account that takes the port hears the token from running agents, and could reuse it once the daemon returns if it let the port go first. Today it could hear the old token too, but that token dies at the restart. The token only spends model calls through the relay's allowed paths (#2541), never the owner's sign-in. A restart more than 30 days after it was minted starts a new one (security review 1).++---++### Task 1: The relay takes a port and an existing token++**Files:**+- Modify: `cli/src/lib/subscriptionRelay.ts`+- Test: `cli/src/lib/subscriptionRelay.spec.ts`++**Interfaces:**+- Produces: `SubscriptionRelayDeps.port?: number`; `SubscriptionRelay.adoptToken(guestEmail: string, token: string): void`.++- [ ] **Step 1: Write the failing tests:** a relay started with a taken port rejects with `EADDRINUSE`; one started with a free port listens there; an adopted token is accepted and another refused; revoking the guest cuts the adopted token.+- [ ] **Step 2: Run them:** `npx vitest run --no-coverage src/lib/subscriptionRelay.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement** `deps.port ?? 0` in `listen`, and `adoptToken` by the same digest map as `mintToken`.+- [ ] **Step 4: Run them.** Expected: PASS.+- [ ] **Step 5: Commit.**++### Task 2: The publisher keeps its grant across a restart++**Files:**+- Modify: `cli/src/team/relay.ts`, `cli/src/superTabs/service.ts`+- Test: `cli/src/team/relay.spec.ts`++**Interfaces:**+- Consumes: Task 1.+- Produces: `TeamRelayPublisherDeps.startRelay(port?: number)`, `remembered(): TeamRelayGrant | null`, `remember(grant): void`, `forget(): void`, `wait?(ms: number): Promise<void>`; `readRememberedGrant(file)`, `writeRememberedGrant(file, grant)`.++- [ ] **Step 1: Write the failing tests:**+ - a new publisher with a remembered grant starts on its port, adopts its token and publishes the same grant;+ - end to end with two real relays and a fake upstream: an agent's address and token work before and after a restart, on main they get refused;+ - a port still closing is retried, then taken;+ - a port held for good gets a new port and a new token, and the new grant is remembered;+ - `stop()` withdraws the published file and keeps the private one; the account's removal withdraws and forgets;+ - `readRememberedGrant` ignores a corrupt file, a link, a file open to others, and a url or token of the wrong shape.+- [ ] **Step 2: Run them:** `npx vitest run --no-coverage src/team/relay.spec.ts`. Expected: FAIL.+- [ ] **Step 3: Implement** in `pass()`, with the file `team-relay-grant.json` in the data folder, passed in from `service.ts`.+- [ ] **Step 4: Run them.** Expected: PASS.+- [ ] **Step 5: Commit.**++### Task 3: Proof and notes++**Files:**+- Modify: `docs/security/2026-11-02-team-account-boundary.md`++- [ ] **Step 1: Add the limit** to the security notes, beside M4's line about the one token.+- [ ] **Step 2: Run** `npm run test:core` and the affected Team and Swarm specs. Expected: no new failures.+- [ ] **Step 3: Commit, open the pull request,** and ask Reed and Cleo.++Not in this task: machine sharing's relay for guests (`services/sharedMachines.ts`) has the same restart behaviour. It stays as a follow-up.diff --git a/docs/security/2026-11-02-team-account-boundary.md b/docs/security/2026-11-02-team-account-boundary.mdindex ac5830fdb..be09650ea 100644--- a/docs/security/2026-11-02-team-account-boundary.md+++ b/docs/security/2026-11-02-team-account-boundary.md@@ -153,7 +153,16 @@ owner's own token is not returned. No live request was sent with the owner's sigwould hand over a lasting credential.**Fix:** allow only the paths and methods the engines use, and refuse encoded separators. The one token is shared by every Team-agent, and lasts until the daemon restarts; a per-launch token would limit a leak (M2).+agent, and lasts until the daemon's first restart past 30 days (task #2125); a per-launch token, or a check that the caller is the Team+account, would limit a leak (M2).++**Since task #2125:** the Team account's token and port now outlive a restart of the owner's daemon, so running agents keep reaching the+model. Any leak of the token now lasts until the first restart past 30 days, or until the port is lost or the Team account goes.+While the daemon is down, a local account that takes the port hears the token from running agents, and could reuse it if it let+the port go before the daemon returned. It only spends model calls through the relay's allowed paths, never the owner's sign-in, and+it ends: a restart more than 30 days after the token was minted starts a new one, which strands running agents once. If the port stays+taken, the daemon moves to a new port and a new token, but running agents keep sending their whole requests to the port's holder, who+can answer them, until they restart. That is as before this change, and only a log line says so.### M5. A Team agent can stop the owner's Swarm service (Medium)