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(trust): a browser signed in before a computer reaches it without a password
0xken1507a0e33526f0
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 2be00e80a..d1faa4b1e 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -321,7 +321,7 @@ async function authStatusCommand(json: boolean): Promise<void> {type SignInOutcome =/** Signed in — `alreadySignedIn` distinguishes a session that was already there from a fresh one,* which is the one fact a caller cannot re-derive except by watching for an `authorize_url`. */- | { signedIn: true; alreadySignedIn: boolean }+ | { signedIn: true; alreadySignedIn: boolean; stoppedDaemon?: boolean }/** Refused. Under `--json` its own coded result line has already been emitted. */| { signedIn: false }@@ -493,8 +493,10 @@ async function loginCommand(// here would take every local terminal on this computer down for as long as the person is in// the browser. There is nothing to race either: the lock is held, and the identity swap happens// afterwards, once there is an identity to swap to (`restartDaemonForIdentity`).- if (readAuthSession()) await stopDaemonProcess()- return await signIn()+ const stopped = readAuthSession() ? (await stopDaemonProcess()).pid !== null : false+ const outcome = await signIn()+ // The daemon stopped for the switch comes back once it is made (`restartDaemonForIdentity`).+ return outcome.signedIn && stopped ? { ...outcome, stoppedDaemon: true } : outcome}, {onWaiting: (owner) => {// On stdout too, for the app: stderr is a developer's, and a sign-in that shows nothing while@@ -1141,13 +1143,21 @@ async function logout(): Promise<void> {* local binding at once, and the daemon already survives a restart cleanly for every update.** No-op when nothing is running (`harness start` boots on the new session by itself) or when the daemon- * already wears the right id (a `harness login` on a computer that was signed in all along).+ * already wears the right id (a `harness login` on a computer that was signed in all along) — unless the+ * sign-in itself stopped it (`stoppedDaemon`: `login --force` stops a signed-in daemon before switching+ * accounts). That one is started again on the new session: left down, the computer was off the account+ * until someone ran `harness start`, and the web showed it offline.*/-async function restartDaemonForIdentity(): Promise<void> {+async function restartDaemonForIdentity(stoppedDaemon = false): Promise<void> {// OUR daemon, by its pid file and private socket. A login in another HOME must never restart a// different OS user's daemon just because it happens to hold the default TCP port.const pid = readPid()- if (!pid || !isAlive(pid)) return+ if (!pid || !isAlive(pid)) {+ if (!stoppedDaemon) return+ console.log(' starting the daemon again on this account…')+ await launch(false) // prints the status block and exits+ return+ }const daemon = await runningDaemonStatus()if (!daemon) returnif (daemon.machineId === wantedDaemonIdentity()) return@@ -2387,7 +2397,7 @@ switch (cmd) {entryPoint: entryPointFlag(),method: signInMethodFlag(flags) ?? (flags.includes('--json') || !process.stdin.isTTY ? undefined : 'ask'),})- .then((outcome) => outcome.signedIn ? restartDaemonForIdentity() : undefined)+ .then((outcome) => outcome.signedIn ? restartDaemonForIdentity(outcome.stoppedDaemon) : undefined).catch(onError)breakcase 'auth':diff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.tsindex 98ecc0d54..d757d282e 100644--- a/cli/src/gateway/gateway.spec.ts+++ b/cli/src/gateway/gateway.spec.ts@@ -15,6 +15,8 @@ import * as C from '../lib/e2ee/core.js'import { TerminalBinaryKind } from '../lib/terminalBinary.js'import { bindMessageRequest } from '../testing/socketCore.js'import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from '../testing/relaySocket.js'+import type { DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'+import { unknownHelloReader } from './start.js'/** The machine the sessions are bound to: every hello and welcome is signed over it. */const MACHINE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'@@ -258,3 +260,61 @@ describe('the Wi-Fi device, over the gateway\'s sessions', () => {await socket.stop()})})++describe('a hello from a key the device key log may name', () => {+ it('waits for the gateway to read the log, and opens the session the read trusted', async () => {+ const socket = relaySocket(MACHINE)+ const gateway = gatewayOf(socket)+ const identity = C.newIdentity()+ const pub = C.b64e(identity.pub)+ const asked: string[] = []+ gateway.onUnknownHello = async (key) => { asked.push(key); gateway.trustPeer({ pub: key, label: 'Chrome · macOS', kind: 'viewer' }) }+ const eph = C.newEphemeral()+ await dispatchDown(socket, { type: 'e2e_hello', payload: { identityPub: pub, ephPub: C.b64e(eph.pub), sig: C.b64e(C.helloSig(identity.priv, MACHINE, eph.pub)) } }, 'web-1')+ await vi.waitFor(() => expect(queuedFor(socket, 'web-1').some((frame) => frame.type === 'e2e_welcome')).toBe(true))+ expect(asked).toEqual([pub])+ expect(socket.remoteClient('web-1')).toMatchObject({ role: 'web', identity: pub })+ await socket.stop()+ })+})++describe('unknownHelloReader', () => {+ const pub = C.b64e(C.newIdentity().pub)++ it('reads the log for a key, says what it found, and not again for the same key within ten seconds', async () => {+ let now = 1_000+ const lines: string[] = []+ const trustFromLog = vi.fn(async (): Promise<DeviceLogTrustOutcome> => 'absent')+ const read = unknownHelloReader({ trustFromLog }, (line) => lines.push(line), () => now)+ await read(pub)+ const fp = C.fingerprint(C.b64d(pub))+ expect(lines).toEqual([+ `[e2ee] hello from ${fp} is not paired here — re-reading the device log`,+ `[e2ee] ${fp}: not on the account's device list`,+ ])+ now += 9_999+ await read(pub)+ expect(trustFromLog).toHaveBeenCalledTimes(1)+ now += 1+ trustFromLog.mockResolvedValueOnce('trusted')+ await read(pub)+ expect(trustFromLog).toHaveBeenCalledTimes(2)+ expect(lines.at(-1)).toBe(`[e2ee] ${fp}: trusted: it is on the account's device list`)+ })++ it('makes a hello said again while the read is on its way wait for that read, not be denied at once', async () => {+ let finish!: (outcome: DeviceLogTrustOutcome) => void+ const trustFromLog = vi.fn(() => new Promise<DeviceLogTrustOutcome>((resolve) => { finish = resolve }))+ const read = unknownHelloReader({ trustFromLog }, () => {}, () => 1_000)+ let firstDone = false+ let againDone = false+ void read(pub).then(() => { firstDone = true })+ void read(pub).then(() => { againDone = true })+ await Promise.resolve()+ expect(againDone).toBe(false)+ finish('trusted')+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect([firstDone, againDone]).toEqual([true, true])+ expect(trustFromLog).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.tsindex 4a169787f..fd8cf999c 100644--- a/cli/src/gateway/gateway.ts+++ b/cli/src/gateway/gateway.ts@@ -104,6 +104,9 @@ export class RelayGateway implements GatewayPort {onPeerLinked?: (peer: LinkedPeer) => void/** A person unpaired this identity here (not the trust group removing it). */onUnpaired?: (identityPub: string) => void+ /** A hello signed by a key not paired here: the account's device key log may name it (manager.ts+ * `onUnknownHello`). The hello waits for this, a few seconds at most. */+ onUnknownHello: ((identityPub: string) => Promise<void>) | null = nullconstructor({ machineId, auth, computerId = '', autonomousEnv = 'prod', core }: RelayGatewayOptions) {this.machineId = machineId@@ -142,6 +145,7 @@ export class RelayGateway implements GatewayPort {this.onPeerLinked?.(peer)},onUnpaired: (pub) => this.onUnpaired?.(pub),+ onUnknownHello: (pub) => this.onUnknownHello?.(pub) ?? Promise.resolve(),})this.terminalP2p = new TerminalP2pResponderPool({sendSignal: (connId, type, payload) => this.sendP2pSignal(connId, type, payload),diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.tsindex 5b6243e47..71697cbdd 100644--- a/cli/src/gateway/start.ts+++ b/cli/src/gateway/start.ts@@ -25,7 +25,7 @@ import type { AuthSessionManager } from '../lib/authSession.js'import { thisDeviceLabel } from '../lib/daemonState.js'import { b64d, b64e, fingerprint } from '../lib/e2ee/core.js'import { DeviceLogStore } from '../lib/e2ee/deviceLogStore.js'-import { DeviceLogSyncer, type DeviceLogFetched } from '../lib/e2ee/deviceLogSyncer.js'+import { DeviceLogSyncer, type DeviceLogFetched, type DeviceLogTrustOutcome } from '../lib/e2ee/deviceLogSyncer.js'import { GroupSyncer, relayRequester, SELF_STAMP } from '../lib/e2ee/groupSyncer.js'import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'import { E2eeStore } from '../lib/e2ee/store.js'@@ -57,6 +57,48 @@ export interface StartedGateway {stop(): Promise<void>}+/** A key is looked up in the device key log at most this often for a hello: a client that retries its+ * hello every few seconds, or a relay replaying one, reads the log once, not each time. */+const UNKNOWN_HELLO_EVERY_MS = 10_000++/** What `trustFromLog` found, as the log line says it. */+const TRUST_OUTCOME: Record<DeviceLogTrustOutcome, string> = {+ trusted: 'trusted: it is on the account\'s device list',+ self: 'not trusted: it is this machine\'s own key',+ absent: 'not on the account\'s device list',+ suspended: 'not trusted: suspended on the device list until it is reviewed (harness devices)',+ blocked: 'not trusted: blocked, it was unpaired here',+ tombstoned: 'not trusted: removed from this machine\'s trust group',+ frozen: 'not trusted: the device log is frozen here until it is reviewed (harness devices)',+ unavailable: 'not trusted: the device log could not be read',+}++/**+ * The gateway's `onUnknownHello`: a hello from a key not paired here re-reads the account's device key log,+ * which trusts the key if it is on it. A web viewer that signs in before this machine does is added to the+ * log before this machine joins it; its hello was denied as unpaired until the next scheduled read, and+ * the person saw "Link required" for up to ten minutes with nothing in the log to say why.+ */+export function unknownHelloReader(+ devlog: Pick<DeviceLogSyncer, 'trustFromLog'>, log: (line: string) => void, now: () => number = Date.now,+): (identityPub: string) => Promise<void> {+ // A hello said again while its key's read is still on its way waits for that read rather than being+ // denied at once: the browser dials again a second after a denial, and the read that trusts it may+ // well take longer than that.+ const lastRead = new Map<string, { at: number; read: Promise<void> }>()+ return (identityPub) => {+ const at = now()+ for (const [pub, r] of lastRead) if (at - r.at >= UNKNOWN_HELLO_EVERY_MS) lastRead.delete(pub)+ const earlier = lastRead.get(identityPub)+ if (earlier) return earlier.read+ const who = fingerprint(b64d(identityPub))+ log(`[e2ee] hello from ${who} is not paired here — re-reading the device log`)+ const read = devlog.trustFromLog(identityPub).then((outcome) => { log(`[e2ee] ${who}: ${TRUST_OUTCOME[outcome]}`) })+ lastRead.set(identityPub, { at, read })+ return read+ }+}+/** Pairing errors as `harness pair` maps them to HTTP. */const PAIR_STATUS: Record<string, number> = {NO_INTENT: 409, EXPIRED: 409, CODE_MISMATCH: 403, BACKEND_DOWN: 503,@@ -130,7 +172,15 @@ export function startGateway(host: GatewayHost): StartedGateway {// Unpairing a device here takes it out of the account's log too — or the log would trust it again.void devLogSyncer?.remove(pub)}- if (host.signedIn) syncer.start()+ // Started once this machine is signed in: at start, or on the first link-up after a sign-in that the+ // core told it of (`ops.account`).+ let groupStarted = false+ const startGroup = (): void => {+ if (groupStarted || !account.machineId) return+ groupStarted = true+ syncer.start()+ }+ if (host.signedIn) { groupStarted = true; syncer.start() }const devlog = new DeviceLogSyncer({store: new DeviceLogStore(),identity: () => { const id = relayIdentityStore.getIdentity(); return { pub: b64e(id.pub), priv: id.priv } },@@ -164,6 +214,7 @@ export function startGateway(host: GatewayHost): StartedGateway {])],tombstoned: (pub) => !!syncer.tombstoned(pub),blocked: (pub) => !!syncer.isBlocked(pub),+ isTrusted: (pub) => gateway.pairedPeers().some((p) => p.identityPub === pub),announce: (m) => {const fp = fingerprint(b64d(m.pub))console.log(`[devlog] NEW DEVICE on this account: ${m.label || '(no name)'} (${m.kind}) ${fp} — not yours? harness devices remove ${fp}`)@@ -208,14 +259,19 @@ export function startGateway(host: GatewayHost): StartedGateway {if (devlog.list().members.some((m) => m.pub === pub && !m.self)) void devlog.remove(pub)}gateway.onDeviceKeysChanged = () => { void devlog.refresh() }- let devlogTimer: ReturnType<typeof setInterval> | null = null- if (host.signedIn) {- // Every time the link comes up: a sign-in from before the log existed joins it with no one doing- // anything, and one that joined already only reads what it missed while offline.- gateway.onLinkUp = () => { void devlog.register() }- devlogTimer = setInterval(() => { void devlog.refresh() }, 10 * 60_000)- devlogTimer.unref()+ // Every time the link comes up: a sign-in from before the log existed joins it with no one doing+ // anything, and one that joined already only reads what it missed while offline. Wired signed out+ // too, and register() rather than refresh() on the timer: a daemon that was signed out when it started+ // never registered after `harness login` signed it in (register does nothing while signed out).+ gateway.onLinkUp = () => {+ startGroup()+ void devlog.register()}+ const devlogTimer = setInterval(() => { void devlog.register() }, 10 * 60_000)+ devlogTimer.unref()+ // Signed out there is no account, and no device log of one, to find a key on.+ const readForHello = unknownHelloReader(devlog, (line) => console.log(line))+ gateway.onUnknownHello = (pub) => account.machineId ? readForHello(pub) : Promise.resolve()// The Wi-Fi device's direct links, which carry its E2EE sessions: only while its service runs in the// core, or a device it connected would be answered by nothing.@@ -340,7 +396,8 @@ export function startGateway(host: GatewayHost): StartedGateway {revokeIdentity: (identity) => { gateway.e2ee.revoke(fingerprint(b64d(identity))) },account: (next) => {account = next- if (host.signedIn) void devlog.register()+ startGroup()+ void devlog.register()},reachable: (machineIds) => { reachable = machineIds ? new Set(machineIds) : null },}@@ -350,7 +407,7 @@ export function startGateway(host: GatewayHost): StartedGateway {ops,windowRelay: relayPool,stop: async () => {- if (devlogTimer) clearInterval(devlogTimer)+ clearInterval(devlogTimer)syncer.stop()direct?.stop()relayPool.close()diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.tsindex 77c9d2bea..ad53e79d8 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts@@ -69,7 +69,7 @@ class FakeBackend {/** `signIn`: the sign-in's epoch (one starting ADOPTED_SIGN_IN is adopted), made at `signInAt` (the* clock's 5_000 by default — just now). */-function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: string[]; store?: DeviceLogStore; backend?: FakeBackend; signIn?: () => string | null; signInAt?: number | null } = {}) {+function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: string[]; store?: DeviceLogStore; backend?: FakeBackend; signIn?: () => string | null; signInAt?: number | null; isTrusted?: (pub: string) => boolean } = {}) {const backend = opts.backend ?? new FakeBackend()const store = opts.store ?? new DeviceLogStore(join(mkdtempSync(join(tmpdir(), 'devlog-')), 'devlog.json'))const calls = {@@ -94,6 +94,7 @@ function setup(opts: { known?: string[]; tombstoned?: string[]; blocked?: stringtrustedNow: () => [...trusted],tombstoned: (pub) => tombstoned.has(pub),blocked: (pub) => (opts.blocked ?? []).includes(pub),+ ...(opts.isTrusted ? { isTrusted: opts.isTrusted } : {}),announce: calls.announce,removed: calls.removed,conflict: calls.conflict,@@ -358,6 +359,118 @@ describe('DeviceLogSyncer', () => {})})+describe('DeviceLogSyncer — a key the log has and this machine does not trust', () => {+ const adopted = (t: ReturnType<typeof setup>): string[] => t.calls.adopt.mock.calls.flat(2).map((m: { pub: string }) => m.pub)+ it('trustFromLog trusts a key on the log even when the head has not moved since it was read', async () => {+ const t = setup()+ t.backend.add(phone, 'viewer', '', 'phone')+ await t.syncer.register()+ t.calls.adopt.mockClear()+ // The head is the one already verified: reading the log adopts nothing, the key is trusted all the same.+ await t.syncer.refresh()+ expect(t.calls.adopt).not.toHaveBeenCalled()+ expect(await t.syncer.trustFromLog(phone.pub)).toBe('trusted')+ expect(adopted(t)).toEqual([phone.pub])+ expect(t.calls.announce).not.toHaveBeenCalled()+ expect(await t.syncer.trustFromLog(me.pub)).toBe('self')+ })++ it('trustFromLog reads the log first: a key added since the last read is trusted', async () => {+ const t = setup()+ await t.syncer.register()+ t.backend.add(phone, 'viewer', '', 'phone')+ expect(await t.syncer.trustFromLog(phone.pub)).toBe('trusted')+ expect(adopted(t)).toContain(phone.pub)+ })++ it('trustFromLog reads again after a read that was already on its way', async () => {+ const t = setup()+ await t.syncer.register()+ let release: () => void = () => {}+ const gate = new Promise<void>((resolve) => { release = resolve })+ const fetch = t.backend.fetch.getMockImplementation()!+ t.backend.fetch.mockImplementationOnce(async (since) => { const got = await fetch(since); await gate; return got })+ const earlier = t.syncer.refresh()+ t.backend.add(phone, 'viewer', '', 'phone')+ const outcome = t.syncer.trustFromLog(phone.pub)+ release()+ await earlier+ expect(await outcome).toBe('trusted')+ })++ it('trustFromLog says why a key is not trusted', async () => {+ const t = setup({ blocked: [box2.pub], tombstoned: [phone.pub] })+ t.backend.add(box2, 'machine', MID2, 'box2')+ t.backend.add(phone, 'viewer', '', 'phone')+ // Read, not registered: with this machine on the log, it would write the tombstone into it.+ await t.syncer.refresh()+ t.calls.adopt.mockClear()+ expect(await t.syncer.trustFromLog(evil.pub)).toBe('absent')+ expect(await t.syncer.trustFromLog(box2.pub)).toBe('blocked')+ expect(await t.syncer.trustFromLog(phone.pub)).toBe('tombstoned')+ t.store.write({ ...t.store.read(), suspended: [phone.pub] })+ expect(await t.syncer.trustFromLog(phone.pub)).toBe('suspended')+ expect(t.calls.adopt).not.toHaveBeenCalled()+ })++ it('trustFromLog trusts nothing from a frozen log, and nothing without one', async () => {+ const offline = setup()+ offline.backend.offline = true+ expect(await offline.syncer.trustFromLog(phone.pub)).toBe('unavailable')+ const t = setup()+ t.backend.add(phone, 'viewer', '', 'phone')+ await t.syncer.register()+ t.backend.lie = t.backend.entries.slice(0, 1)+ await t.syncer.refresh()+ expect(t.store.read().frozen?.reason).toBe('rollback')+ t.calls.adopt.mockClear()+ expect(await t.syncer.trustFromLog(phone.pub)).toBe('frozen')+ expect(t.calls.adopt).not.toHaveBeenCalled()+ })++ it('every read trusts again an active key this machine does not trust, and announces nothing', async () => {+ const trusted = new Set<string>()+ const t = setup({ isTrusted: (pub) => trusted.has(pub) })+ t.backend.add(box2, 'machine', MID2, 'box2')+ t.backend.add(phone, 'viewer', '', 'phone')+ await t.syncer.register()+ // The adoption trusted box2; phone's was lost (a crash between the head and the trust).+ trusted.add(box2.pub)+ t.calls.adopt.mockClear()+ await t.syncer.refresh()+ expect(t.calls.adopt).toHaveBeenCalledOnce()+ expect(adopted(t)).toEqual([phone.pub])+ expect(t.calls.announce).not.toHaveBeenCalled()+ trusted.add(phone.pub)+ t.calls.adopt.mockClear()+ await t.syncer.refresh()+ expect(t.calls.adopt).not.toHaveBeenCalled()+ })++ it('trusts again no key that is blocked, tombstoned or suspended, nor from a frozen log', async () => {+ const t = setup({ isTrusted: () => false, blocked: [box2.pub], tombstoned: [phone.pub] })+ const viewer = key(4)+ t.backend.add(box2, 'machine', MID2, 'box2')+ t.backend.add(phone, 'viewer', '', 'phone')+ t.backend.add(evil, 'viewer', '', 'evil')+ t.backend.add(viewer, 'viewer', '', 'viewer')+ // Read, not registered: with this machine on the log, it would write the tombstone into it. That this+ // machine's own key is never trusted again is the test above (it is on the log there).+ await t.syncer.refresh()+ t.store.write({ ...t.store.read(), suspended: [evil.pub] })+ expect(t.store.read().state!.active[phone.pub]).toBeDefined()+ t.calls.adopt.mockClear()+ await t.syncer.refresh()+ expect(adopted(t)).toEqual([viewer.pub])+ t.backend.lie = t.backend.entries.slice(0, 1)+ await t.syncer.refresh()+ expect(t.store.read().frozen).not.toBeNull()+ t.calls.adopt.mockClear()+ await t.syncer.refresh()+ expect(t.calls.adopt).not.toHaveBeenCalled()+ })+})+const hashesOf = (state: DevLogState) => state.hashes.map((hash, i) => ({ seq: i + 1, hash }))const MID_HOLDER = MID_MEdiff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.tsindex d380b4351..456e15816 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts@@ -73,6 +73,9 @@ export interface DeviceLogSyncerDeps {tombstoned: (pub: string) => boolean/** Whether this machine's user unpaired `pub` here — a local override the log never beats. */blocked: (pub: string) => boolean+ /** Whether `pub` may open a session here right now (it is paired). Given, every read of the log trusts+ * again an active key that is not: one the adoption of its entry missed stays trusted by no one. */+ isTrusted?: (pub: string) => boolean/** A key joined the log after this machine did: "New device: X". */announce: (member: DevLogMember) => void/** A device was taken out of the log after this machine joined (not by this machine). */@@ -139,6 +142,9 @@ export interface DeviceLogHistory {frozen: DevLogFreeze | null}+/** What `trustFromLog` made of a key: trusted, or why not. */+export type DeviceLogTrustOutcome = 'trusted' | 'self' | 'absent' | 'suspended' | 'blocked' | 'tombstoned' | 'frozen' | 'unavailable'+export type DeviceLogRemoveResult = { ok: true } | { ok: false; error: 'NOT_ACTIVE' | 'NOT_IN_LOG' | 'UNAVAILABLE' | 'REFUSED'; detail?: string }/** `rebaseline(confirm, head)` refused: the backend's list is no longer the one that was previewed@@ -255,6 +261,35 @@ export class DeviceLogSyncer {return this.refreshing}+ /**+ * Read the log now and trust `pub` if it is on it: a hello from a key not paired here may be a device+ * that joined the account after this machine last read the log (a browser signed in before this machine+ * did), and without this it is denied until the next scheduled read. Says why not otherwise. Never throws.+ */+ async trustFromLog(pub: string): Promise<DeviceLogTrustOutcome> {+ try {+ // A read already on its way may have fetched before this key was added: wait for it, then read again.+ const earlier = this.refreshing+ await this.refresh()+ if (earlier) await this.refresh()+ const file = this.deps.store.read()+ if (file.frozen) return 'frozen'+ const state = file.state+ if (!state) return 'unavailable'+ const member = state.active[pub]+ if (!member) return 'absent'+ if (pub === this.deps.identity().pub) return 'self'+ if (this.suspendedKeys().includes(pub)) return 'suspended'+ if (this.deps.blocked(pub)) return 'blocked'+ if (this.deps.tombstoned(pub)) return 'tombstoned'+ this.trustState(state, [member])+ return 'trusted'+ } catch (err) {+ this.deps.log?.(`[devlog] could not read the log for a key: ${err instanceof Error ? err.message : String(err)}`)+ return 'unavailable'+ }+ }+/** The file, with the joined point filled in for one written before it existed (or by a client that* dropped it): everything up to what was already announced is then known, as it was. */private marks(): DevLogFile {@@ -392,6 +427,30 @@ export class DeviceLogSyncer {// stalls the second page would have every key it adds later taken for one there at joining.this.endJoin()}+ this.reconcile()+ }++ /**+ * Trust again every key the log leaves active that is not trusted here. A key is adopted as its entry is+ * verified, and only then: the head is written first, so an adoption that threw, a process that died in+ * between, or a roster that already held the member (nothing new to merge, so nothing trusted) left it+ * untrusted for good — its device saw "Link required" however often it came back. Never announces: what+ * is news was decided when the entry was read. Never throws.+ */+ private reconcile(): void {+ const isTrusted = this.deps.isTrusted+ if (!isTrusted) return+ try {+ const file = this.deps.store.read()+ const state = file.state+ if (file.frozen || !state) return+ const selfPub = this.deps.identity().pub+ const missing = Object.values(state.active).filter((m) => m.pub !== selfPub && !isTrusted(m.pub))+ const adopted = this.trustState(state, missing)+ if (adopted.length) this.deps.log?.(`[devlog] trusting ${adopted.length} key(s) the log has and this machine did not: ${adopted.map((m) => fp(m.pub)).join(', ')}`)+ } catch (err) {+ this.deps.log?.(`[devlog] could not trust what the log has: ${err instanceof Error ? err.message : String(err)}`)+ }}private async readPages(): Promise<void> {@@ -583,12 +642,14 @@ export class DeviceLogSyncer {return true}- private trustState(state: DevLogState, members: DevLogMember[]): void {+ /** Trust those of `members` the log leaves active and nothing here holds back; returns them. */+ private trustState(state: DevLogState, members: DevLogMember[]): DevLogMember[] {const selfPub = this.deps.identity().pubconst suspended = this.suspendedKeys()const adopt = members.filter((m) => m.pub !== selfPub && state.active[m.pub] && !suspended.includes(m.pub)&& !this.deps.blocked(m.pub) && !this.deps.tombstoned(m.pub))if (adopt.length) this.deps.adopt(adopt)+ return adopt}/** A removal made in the trust group before the log existed must not be undone by the log: thisdiff --git a/cli/src/lib/e2ee/groupSyncer.spec.ts b/cli/src/lib/e2ee/groupSyncer.spec.tsindex 9bcd4e519..488b532ff 100644--- a/cli/src/lib/e2ee/groupSyncer.spec.ts+++ b/cli/src/lib/e2ee/groupSyncer.spec.ts@@ -354,6 +354,25 @@ describe('GroupSyncer', () => {expect(a.syncer.tombstoned(phonePub)).toBe(true)for (const n of f.nodes) n.syncer.stop()})++ it('a key the roster holds as the log names it, and this machine does not trust, is trusted again', () => {+ vi.useFakeTimers()+ const f = fleet()+ const a = f.add('a')+ const phonePub = C.b64e(C.newIdentity().pub)+ const phone = { pub: phonePub, kind: 'viewer' as const, machineId: '', label: 'phone', addedAt: 500 }+ a.syncer.adoptFromLog([phone])+ // The trust was lost (a crash between the roster and paired.json): the roster still holds the member+ // exactly as the log names it, so a merge has nothing new to say about it.+ a.trusted.delete(phonePub)+ a.syncer.adoptFromLog([phone])+ expect(a.trusted.has(phonePub)).toBe(true)+ // Not a key this machine's user unpaired.+ a.syncer.unpaired(phonePub)+ a.syncer.adoptFromLog([phone])+ expect(a.trusted.has(phonePub)).toBe(false)+ for (const n of f.nodes) n.syncer.stop()+ })})describe('GroupSyncer — suspended keys', () => {diff --git a/cli/src/lib/e2ee/groupSyncer.ts b/cli/src/lib/e2ee/groupSyncer.tsindex d5d3f6e29..bcb58e3a9 100644--- a/cli/src/lib/e2ee/groupSyncer.ts+++ b/cli/src/lib/e2ee/groupSyncer.ts@@ -139,7 +139,10 @@ export class GroupSyncer {}/** Keys the device key log holds (deviceLogSyncer.ts): members of the group like any link, stamped- * when they joined the log, so a device that predates the log hears of them through the group. */+ * when they joined the log, so a device that predates the log hears of them through the group. A key+ * the roster holds already, as it is, is trusted here too if it is not: the merge has nothing new to+ * say about it, and when it was all that trusted a key, one roster that outran this machine's trust+ * (a crash between the two writes, a peer's roster first) kept that device out for good. */adoptFromLog(members: Array<{ pub: string; kind: GroupMember['kind']; machineId: string; label: string; addedAt: number }>): void {const now = this.now()const parsed = members@@ -147,7 +150,11 @@ export class GroupSyncer {.filter((m): m is GroupMember => m !== null)if (!parsed.length) returnconst before = rosterDigest(this.deps.store.read())- const result = this.deps.store.merge({ members: parsed, removed: [] }, this.selfPub())+ const merged = this.deps.store.merge({ members: parsed, removed: [] }, this.selfPub())+ const paired = new Set(this.deps.paired().map((p) => p.identityPub))+ const untrusted = merged.roster.members.filter((m) =>+ !paired.has(m.pub) && parsed.some((p) => p.pub === m.pub) && !merged.upserted.some((u) => u.pub === m.pub))+ const result = { ...merged, upserted: [...merged.upserted, ...untrusted] }this.apply(result)if (rosterDigest(result.roster) !== before) this.scheduleFanOut(1_000)}diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.tsindex e6b453544..17503a62a 100644--- a/cli/src/lib/e2ee/manager.test.ts+++ b/cli/src/lib/e2ee/manager.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'-import { mkdtempSync, rmSync } from 'fs'+import { mkdtempSync, readFileSync, rmSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'@@ -327,6 +327,99 @@ describe('E2eeManager pairing', () => {expect(mgr.hasSession('c4')).toBe(false)})+ describe('a hello from a key the device key log may name (onUnknownHello)', () => {+ /** A signed-in browser this machine has not trusted yet: the hook stands for the log's read. */+ const label = 'Chrome · macOS'++ it('waits for the log to trust the key, then opens the session', async () => {+ const web = new WebPeer()+ const seen: string[] = []+ const h = machine({+ onUnknownHello: async (pub) => { seen.push(pub); h.mgr.trustPeer({ pub, label, kind: 'viewer' }) },+ })+ h.mgr.handleFrame('w1', web.hello())+ await vi.waitFor(() => expect(h.lastFor('w1', 'e2e_welcome')).toBeTruthy())+ expect(seen).toEqual([C.b64e(web.identity.pub)])+ expect(h.lastFor('w1', 'e2e_denied')).toBeUndefined()+ const machinePub = (JSON.parse(readFileSync(join(process.env.ADAPTER_DATA_DIR as string, 'e2e', 'identity.json'), 'utf8')) as { pub: string }).pub+ web.onWelcome(h.lastFor('w1', 'e2e_welcome')!, C.b64d(machinePub))+ expect(h.mgr.hasSession('w1')).toBe(true)+ })++ it('denies the hello as unpaired when the log does not trust the key within the bound', async () => {+ vi.useFakeTimers()+ try {+ const h = machine({ onUnknownHello: () => new Promise<void>(() => {}) })+ h.mgr.handleFrame('w2', new WebPeer().hello())+ await vi.advanceTimersByTimeAsync(3_999)+ expect(h.lastFor('w2', 'e2e_denied')).toBeUndefined()+ await vi.advanceTimersByTimeAsync(1)+ expect((h.lastFor('w2', 'e2e_denied')!.payload as Record<string, unknown>).reason).toBe('unpaired')+ expect(h.mgr.hasSession('w2')).toBe(false)+ } finally {+ vi.useRealTimers()+ }+ })++ it('denies at once, as unpaired, when the read fails', async () => {+ const h = machine({ onUnknownHello: async () => { throw new Error('offline') } })+ h.mgr.handleFrame('w3', new WebPeer().hello())+ await vi.waitFor(() => expect(h.lastFor('w3', 'e2e_denied')).toBeTruthy())+ expect((h.lastFor('w3', 'e2e_denied')!.payload as Record<string, unknown>).reason).toBe('unpaired')+ })++ it('never reads the log for a hello whose signature does not verify', () => {+ const hook = vi.fn(async () => {})+ const h = machine({ onUnknownHello: hook })+ const hello = new WebPeer().hello()+ ;(hello.payload as Record<string, unknown>).sig = C.b64e(new Uint8Array(64))+ h.mgr.handleFrame('w4', hello)+ expect(hook).not.toHaveBeenCalled()+ expect((h.lastFor('w4', 'e2e_denied')!.payload as Record<string, unknown>).reason).toBe('bad_sig')+ })++ it('drops the answer to a hello a newer one on the same connection replaced', async () => {+ const web = new WebPeer()+ const pending: Array<() => void> = []+ const h = machine({ onUnknownHello: (pub) => new Promise<void>((resolve) => pending.push(() => { h.mgr.trustPeer({ pub, label }); resolve() })) })+ h.mgr.handleFrame('w5', web.hello())+ const first = C.b64e(web.session!.myEph.pub)+ h.mgr.handleFrame('w5', web.hello())+ await vi.waitFor(() => expect(pending).toHaveLength(2))+ // The first read trusts the key; the hello it was for is not answered, the newer one still waits.+ pending[0]()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(h.sent.filter((s) => s.connId === 'w5')).toEqual([])+ pending[1]()+ await vi.waitFor(() => expect(h.lastFor('w5', 'e2e_welcome')).toBeTruthy())+ const answers = h.sent.filter((s) => s.connId === 'w5')+ expect(answers).toHaveLength(1)+ expect((answers[0].frame.payload as Record<string, unknown>).webEphPub).toBe(C.b64e(web.session!.myEph.pub))+ expect((answers[0].frame.payload as Record<string, unknown>).webEphPub).not.toBe(first)+ })++ it('answers nothing for a connection that went while its hello waited', async () => {+ let release: () => void = () => {}+ const h = machine({ onUnknownHello: (pub) => new Promise<void>((resolve) => { release = () => { h.mgr.trustPeer({ pub, label }); resolve() } }) })+ h.mgr.handleFrame('w6', new WebPeer().hello())+ h.mgr.dropSession('w6')+ release()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(h.sent.filter((s) => s.connId === 'w6')).toEqual([])+ expect(h.mgr.hasSession('w6')).toBe(false)+ })++ it('answers a paired key at once, without reading the log', () => {+ const hook = vi.fn(async () => {})+ const h = machine({ onUnknownHello: hook })+ const web = new WebPeer()+ h.mgr.trustPeer({ pub: C.b64e(web.identity.pub), label })+ h.mgr.handleFrame('w7', web.hello())+ expect(h.lastFor('w7', 'e2e_welcome')).toBeTruthy()+ expect(hook).not.toHaveBeenCalled()+ })+ })+it('a second concurrent pair_intent is rejected as PAIRING_BUSY while active', async () => {const { mgr, takeLast } = machine()const web = new WebPeer()diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.tsindex 2a9131696..2c964168a 100644--- a/cli/src/lib/e2ee/manager.ts+++ b/cli/src/lib/e2ee/manager.ts@@ -77,6 +77,10 @@ const ROUND_TIMEOUT_MS = 15_000const RATE_WINDOW_MS = 5 * 60_000const RATE_MAX = 3const MAX_SESSIONS = 64+/** How long a hello from a key not paired here waits for `onUnknownHello` (a re-read of the account's+ * device key log) before it is denied: one backend round trip, with room, and the client waiting on its+ * hello is answered either way. */+const UNKNOWN_HELLO_WAIT_MS = 4_000// Persistent remote-password linking (`harness remote-password set` + `harness link connect`) — a// SEPARATE state machine from PairSlot above: no human "arm" step (a correct password is the only@@ -122,6 +126,11 @@ export interface E2eeManagerDeps {/** A person unpaired `identityPub` (`harness unpair`, or a trusted client's unpair RPC) — not called* for the trust group's own removals, so the group can keep an unpairing from being undone. */onUnpaired?: (identityPub: string) => void+ /** A hello signed by a key not paired here. The account's device key log may name it already and this+ * machine has not adopted it yet (a browser that signed in before this machine did): the caller reads+ * the log and trusts it if so. The hello waits for it, at most UNKNOWN_HELLO_WAIT_MS, then is answered+ * as the key stands. Absent, such a hello is denied at once. */+ onUnknownHello?: (identityPub: string) => Promise<void>}export interface LinkedPeer {@@ -152,6 +161,10 @@ export class E2eeManager {private attempts: number[] = [] // timestamps of FAILED pairings — anti online-guessing rate limitprivate pwSlots = new Map<string, PwPairSlot>() // connId -> in-progress password-PAKE attemptprivate sessionGoneTold = new Map<string, number>() // connId -> when it was last told its session is gone+ /** connId -> the hello waiting on `onUnknownHello` there. A newer hello, or the connection going, ends+ * the wait: the reply to the older one would open a session the client has moved on from. */+ private helloWaits = new Map<string, number>()+ private helloSeq = 0private now: () => number/** Local dashboard port (loopback) — surfaced to the web in e2e_status so it can link there to* approve pairing. Not sensitive (a localhost port); set by the adapter after the hook server binds. */@@ -804,15 +817,47 @@ export class E2eeManager {const sigB64 = String(p.sig ?? '')if (!identityPub || !ephPubB64 || !sigB64) return trueconst webEphPub = C.b64d(ephPubB64)- const role = this.store.pairedRole(identityPub)- if (!role) {- this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'unpaired' } })- return true- }+ // The signature first: only a hello the key's holder signed may make this machine re-read the log, and+ // a forged one must not end the wait of a real one on the same connection.if (!C.helloVerify(C.b64d(identityPub), this.deps.machineId, webEphPub, C.b64d(sigB64))) {this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'bad_sig' } })return true}+ this.helloWaits.delete(connId)+ const role = this.store.pairedRole(identityPub)+ const unknownHello = this.deps.onUnknownHello+ if (role || !unknownHello) {+ this.answerHello(connId, identityPub, ephPubB64, webEphPub, role)+ return true+ }+ void this.answerUnknownHello(connId, identityPub, ephPubB64, webEphPub, unknownHello)+ return true+ }++ /** A browser that signed in before this machine did is in the account's device key log, and the first+ * hello it sent here was denied as unpaired: the log is read only on its own schedule, so the browser+ * showed "Link required" until it was. Its hello now waits for that read. */+ private async answerUnknownHello(connId: string, identityPub: string, ephPubB64: string, webEphPub: Uint8Array, unknownHello: (identityPub: string) => Promise<void>): Promise<void> {+ const seq = ++this.helloSeq+ this.helloWaits.set(connId, seq)+ let timer: ReturnType<typeof setTimeout> | undefined+ await Promise.race([+ Promise.resolve().then(() => unknownHello(identityPub)).catch(() => { /* answered as the key stands */ }),+ new Promise<void>((resolve) => { timer = setTimeout(resolve, UNKNOWN_HELLO_WAIT_MS) }),+ ])+ clearTimeout(timer)+ if (this.helloWaits.get(connId) !== seq) return+ this.helloWaits.delete(connId)+ this.answerHello(connId, identityPub, ephPubB64, webEphPub, this.store.pairedRole(identityPub))+ }++ /** A verified hello, answered under the role its key is paired with: a session and its welcome, or+ * `unpaired` with none. */+ private answerHello(connId: string, identityPub: string, ephPubB64: string, webEphPub: Uint8Array, role: C.PairRole | null): void {+ if (!role) {+ this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'unpaired' } })+ return+ }const eph = C.newEphemeral()// webEphPub is attacker-controlled: a wrong-length or low-order / invalid curve point makes// x25519.getSharedSecret throw. Refuse such a hello instead of letting the throw crash the daemon.@@ -821,7 +866,7 @@ export class E2eeManager {keys = C.sessionKeys(eph.priv, webEphPub, this.deps.machineId, webEphPub, eph.pub)} catch {this.deps.sendTo(connId, { type: 'e2e_denied', payload: { webEphPub: ephPubB64, reason: 'bad_key' } })- return true+ return}this.evictIfFull()this.dropSession(connId)@@ -855,13 +900,14 @@ export class E2eeManager {enc: C.b64e(enc),},})- return true}/** Drop a session when its web connection closes (called from backendSocket on down close is n/a —* connections are relayed; sessions are pruned by LRU + overwrite-on-new-hello). Also cleans up any- * in-progress password-PAKE attempt on this connId — the joiner may have disconnected mid-round. */+ * in-progress password-PAKE attempt on this connId — the joiner may have disconnected mid-round — and+ * a hello waiting on the device key log there, which would open a session for a connection gone. */dropSession(connId: string): void {+ this.helloWaits.delete(connId)if (this.sessions.delete(connId)) this.deps.onSessionDropped?.(connId)this.clearPwSlot(connId)}diff --git a/cli/src/loginForceRace.spec.ts b/cli/src/loginForceRace.spec.tsindex c850bfc3e..f4809cbd1 100644--- a/cli/src/loginForceRace.spec.ts+++ b/cli/src/loginForceRace.spec.ts@@ -197,8 +197,11 @@ describe('login --force beside a start that lands mid-sign-in', () => {await Promise.race([start.exit, start.until((out) => out.includes('waiting for it to finish'))])await fetch(`${redirectUri}?code=code_1&state=state_1`)- expect(await login.exit).toBe(0)+ // The daemon the login stopped is started again on the new account. Here it cannot listen (the+ // control port is 1), so the relaunch fails and the login exits with it, after its result line.+ await login.exitawait start.exit+ expect(login.stdout()).toContain('starting the daemon again on this account')// Nothing acted on the old account once its daemon was stopped: the start resolved its machine// with the NEW session or not at all.@@ -206,8 +209,8 @@ describe('login --force beside a start that lands mid-sign-in', () => {expect(resolves.map((call) => call.bearer)).not.toContain('Bearer tok_old')expect(start.stdout()).toContain('the daemon is being signed in')// The login's pinned contract holds: exactly one result line, and a success.- const results = login.stdout().trim().split('\n').map((line) => JSON.parse(line) as { type: string })- .filter((line) => line.type === 'result')+ const results = login.stdout().trim().split('\n').filter((line) => line.startsWith('{'))+ .map((line) => JSON.parse(line) as { type: string }).filter((line) => line.type === 'result')expect(results).toEqual([expect.objectContaining({ type: 'result', status: 'success' })])expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8'))).toMatchObject({ accessToken: 'tok_new', machineId: 'm_new', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/) })diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex a29971f7f..1a66b1cbe 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -199,6 +199,13 @@ The native desktop target uses the CLI for cloud access and SSO tokens:`LocalCliDiscovery`, which runs `harness start` when needed). The CLI terminates E2EE for relayedmachines; the app carries no crypto. Close code `4404`/`NO_PEER_LINK` means the machine needs`harness link import` — surfaced as `MachineState.needsLink` and polled via `_linkRetryTimers`.+ A viewer build settles its own `NO_PEER_LINK`/`E2E_DENIED` first (`_settleTrust`): it joins the+ device log if it is not in it (`ViewerDeviceLog.ensureRegistered`), reads it and dials again,+ showing the machine as connecting; only a refusal that outlasts two rounds (~15s), or a frozen+ log, asks for the password. The desk frames (`app_focus`, `app_panes`, `app_swarms`, `app_unread`,+ `agent_seen`) are for this computer's daemon and only ride a loopback connection. A viewer with no+ machine connected hears no push, so it re-reads the machine list every 20s while that lasts+ (`deafMachineListInterval`) and when the tab comes back to the front.- **Both REST and the local WS prefer the daemon's Unix socket** (`lib/ws/local_daemon_transport.dart`;CLI `lib/localSocket.ts`): `~/.harness/cli/data/daemon-<port>.sock`, 0600, named for the port in`localCliBaseUrl` so it always leads to the same daemon as the TCP fallback. The loopback port takesdiff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex efe0f261e..b5f29c693 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -64,6 +64,9 @@ const Set<String> encryptedDownTypes = {'fs_list_dir','project_preview','git_project_info',+ // The harness's branch and pull-request history is a machine RPC too (applicationFrames.ts+ // `MACHINE_REQUESTS`): unsealed, the machine answers E2EE_REQUIRED.+ 'git_pull_request',// The trust-group roster swap (`viewer/group_sync.dart`): the keys every member trusts.'group_sync','codex_profiles_list',diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 9a4c15bad..735a88ffa 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -805,7 +805,15 @@ class AppNotifier extends ChangeNotifier {/// Fed by the workspace's [AppLifecycleListener]. A null state is unknown, read as foreground.void appLifecycleChanged(AppLifecycleState? state) {if (_disposed) return;+ final wasForeground = foreground.value;foreground.value = state == null || state == AppLifecycleState.resumed;+ // Back in front: a viewer reads the device log again, and joins it if the boot never got in.+ if (foreground.value && !wasForeground) {+ _refreshDeviceLogAfterReconnect();+ // ...and, hearing no machine at all, looks again for one: the person most likely just went to+ // their computer to sign it in.+ _rereadMachinesWhileDeaf();+ }}/// Bumped once per real agent event (a turn starting or ending, a tool@@ -875,6 +883,9 @@ class AppNotifier extends ChangeNotifier {// independently, with capped backoff and the same in-flight request as a manual retry.Timer? _machineRecoveryTimer;Timer? _sharingDiscoveryTimer;+ // A viewer with no machine socket open hears no push at all — a machine that joins the account is+ // only found by this. See [_rereadMachinesWhileDeaf].+ Timer? _deafMachineListTimer;bool _sharingDiscoveryBusy = false;bool _sharingDiscoveryAgain = false;int _machineRecoveryAttempts = 0;@@ -2929,6 +2940,15 @@ class AppNotifier extends ChangeNotifier {/// was most of the backend's traffic.static const machineListSafetyNetInterval = Duration(minutes: 5);+ /// How often a viewer that has no machine socket open re-reads the machine list. Every push+ /// (`machines_changed`, `device_keys_changed`) reaches a browser over the web socket of a machine+ /// it is connected to; with none connected — the person signed in on the web first and is now+ /// running `harness login` on their computer — nothing tells it that computer has joined, and the+ /// safety net above would leave the person staring at an empty list for five minutes. Only while+ /// it is deaf, so the traffic note above holds for every window that has a machine.+ @visibleForTesting+ Duration deafMachineListInterval = const Duration(seconds: 20);+MachineState? stateOf(String machineId) => machineStates[machineId];// ── the grid ────────────────────────────────────────────────────────────────────────────────────@@ -3329,6 +3349,7 @@ class AppNotifier extends ChangeNotifier {);machine.needsLink = false;_stopLinkRetry(machineId);+ _forgetTrustSettle(machineId);// A daemon that just came up — first connect, or a reconnect after it// restarted — has never been told what is on the grid. Without this// the dial goes back to beeping about tiles in plain sight until the@@ -3397,13 +3418,23 @@ class AppNotifier extends ChangeNotifier {if (machineId != null) _sendAppFocus(machineId, agentId);}+ /// The socket [machineId]'s desk frames ride — `app_focus`, `app_panes`, `app_swarms`, `app_unread`,+ /// `agent_seen` — or null. They are this window's own state for the daemon on this computer+ /// (cli/src/localWsServer.ts), so only a loopback connection carries them: a viewer's are relayed+ /// to the machine, which refuses them unsealed and would hand the relay question prompts and tab+ /// names on the way. A viewer build sends none.+ WsConn? _deskConnection(String machineId, {WsPool? pool}) {+ final connection = (pool ?? _pool)?[machineId];+ return connection != null && connection.isLocal ? connection : null;+ }+void _sendAppFocus(String machineId, String? agentId) {// Never create a socket just to move focus, and never queue stale focus// across a reconnect. The connected callback reasserts the current pane.final send = focusFrameSenderForTest;final pending = send != null? send(machineId, agentId)- : _pool?[machineId]?.sendTerminalFrame('app_focus', {+ : _deskConnection(machineId)?.sendTerminalFrame('app_focus', {'agentId': agentId,if (_deviceFocusRevision != null)'focusRevision': _deviceFocusRevision,@@ -3451,10 +3482,12 @@ class AppNotifier extends ChangeNotifier {/// stays silent, and the alternative is a dial that beeps about tiles you are/// looking straight at.///- /// Sent to EVERY connected daemon, with the full list across all machines.- /// The dial belongs to whichever daemon owns the cable, and only a complete- /// roster lets that one judge; the others store a list they never use, which- /// costs nothing and saves the window from having to know which is which.+ /// Sent to EVERY connected daemon on this computer's loopback, with the full+ /// list across all machines. The dial belongs to whichever daemon owns the+ /// cable, and only a complete roster lets that one judge; the others store a+ /// list they never use, which costs nothing and saves the window from having+ /// to know which is which. Never over a relayed connection: see+ /// [_deskConnection]./// The newest eight unread harnesses, for a dial that has lost its drawer.////// The dial keeps its drawer in RAM, so a reboot — an OTA, a replug, a flash —@@ -3493,7 +3526,7 @@ class AppNotifier extends ChangeNotifier {},];for (final machineId in pool.machineIds) {- pool[machineId]+ _deskConnection(machineId)?.sendTerminalFrame('app_unread', {'items': items}).catchError((_) => false).ignore();@@ -3505,6 +3538,8 @@ class AppNotifier extends ChangeNotifier {/// unchanged and the `foreground` flag riding with it is the point.void announceWindowForeground() => _announceOpenPanesToDial();+ /// The tile roster and the tabs, to every daemon this window reaches over+ /// its loopback ([_deskConnection]) — never a relayed machine's.void _announceOpenPanesToDial() {final pool = _pool;if (pool == null) return;@@ -3580,7 +3615,7 @@ class AppNotifier extends ChangeNotifier {},];for (final machineId in machineStates.keys) {- final connection = pool[machineId];+ final connection = _deskConnection(machineId, pool: pool);if (connection == null) continue;unawaited(connection@@ -4919,11 +4954,14 @@ class AppNotifier extends ChangeNotifier {_desk.reset();_stopAllOfflineRetries();_stopAllLinkRetries();+ _forgetAllTrustSettles();_stopAllAgentSyncTimers();_daemonSupervisionTimer?.cancel();_daemonSupervisionTimer = null;_sharingDiscoveryTimer?.cancel();_sharingDiscoveryTimer = null;+ _deafMachineListTimer?.cancel();+ _deafMachineListTimer = null;_sharingDiscoveryBusy = false;_sharingDiscoveryAgain = false;_daemonGateFailed = false;@@ -5540,9 +5578,32 @@ class AppNotifier extends ChangeNotifier {return;}if (code != 4404) return;+ // A viewer refused for want of trust is usually only early: its key not yet in the account's+ // device log, or the machine not yet in this app's copy of it — a computer signed in after this+ // app did. That is settled first ([_settleTrust]), while the machine keeps showing as connecting;+ // only a refusal that outlasts it asks for a password.+ if (_deviceLog != null &&+ (reason == 'NO_PEER_LINK' || reason == 'E2E_DENIED')) {+ if ((_trustRounds[machineId] ?? 0) < _trustSettleRounds) {+ if (_trustSettling.add(machineId)) {+ unawaited(_settleTrust(machineId, reason));+ }+ return;+ }+ if (!machine.needsLink) {+ appLog.info(+ 'link',+ '${_shortId(machineId)} still refused ($reason) after the device list was checked',+ );+ }+ }// A machine the account's device key log names may simply not have read it yet: read it again,// and the link retry below picks the machine up once it has.if (_deviceLog case final log?) unawaited(log.refresh());+ _markNeedsLink(machineId, machine);+ }++ void _markNeedsLink(String machineId, MachineState machine) {// The local CLI's relay found no linked trust for this machine — it now owns E2EE entirely.// A `harness link connect` run in a terminal (or another app instance) has no way to notify// this one directly, so poll every few seconds until it's picked up instead of waiting for@@ -5564,6 +5625,161 @@ class AppNotifier extends ChangeNotifier {_startLinkRetry(machineId);}+ // -- a viewer refused for want of trust ([_onLocalFailure]) --------------------------------------++ /// How many refusals of each machine were settled since it last connected, and the ones under way —+ /// each with what ends its wait early (a pin landing: [_redialPinnedMachines]).+ final Map<String, int> _trustRounds = {};+ final Set<String> _trustSettling = {};+ final Map<String, Completer<void>> _trustWakes = {};+ static const _trustSettleRounds = 2;++ /// How long one settling round waits for the machine's key to land before dialling again: two+ /// rounds, about fifteen seconds, before a password is asked for.+ @visibleForTesting+ Duration trustSettleRound = const Duration(milliseconds: 7500);++ /// How long a machine that denied this app's key gets to read the account's log again (its CLI+ /// does on a hello from a key it does not know) before the first hello is said again.+ @visibleForTesting+ Duration trustDeniedWait = const Duration(seconds: 1);++ /// Hears every [_redial], for a test with no pool to dial through.+ @visibleForTesting+ void Function(String machineId)? onRedialForTest;++ static String _shortId(String id) => id.length > 8 ? id.substring(0, 8) : id;++ /// One round of settling [machineId]'s refusal ([reason]: `NO_PEER_LINK`, no key here for it, or+ /// `E2E_DENIED`, the machine does not know this app's): put this app into the account's device log+ /// and read it, then dial again — at once when the machine's key just landed, after a moment for a+ /// machine that has to read the log itself. A frozen log can settle nothing: the password it is.+ Future<void> _settleTrust(String machineId, String reason) async {+ final log = _deviceLog;+ if (log == null) return;+ final revision = _authRevision;+ final round = _trustRounds[machineId] = (_trustRounds[machineId] ?? 0) + 1;+ final wake = _trustWakes[machineId] = Completer<void>();+ final short = _shortId(machineId);+ bool current() =>+ !_disposed &&+ _authWorkCurrent(revision) &&+ identical(_trustWakes[machineId], wake) &&+ machineStates.containsKey(machineId);+ final started = Stopwatch()..start();+ try {+ final registration = await log.ensureRegistered().timeout(+ trustSettleRound,+ onTimeout: () => DeviceLogRegistration.missing,+ );+ if (!current()) return;+ if (registration == DeviceLogRegistration.frozen) {+ appLog.info(+ 'link',+ '$short refused ($reason): the device list is frozen',+ );+ // The machine's password prompt says so (deviceListNeedsReview), from the listing.+ unawaited(_syncPendingDevices());+ _trustRounds[machineId] = _trustSettleRounds;+ _endTrustSettle(machineId);+ final machine = machineStates[machineId]!+ ..connectionStatus = ConnectionStatus.disconnected;+ _markNeedsLink(machineId, machine);+ return;+ }+ if (registration == DeviceLogRegistration.registered) {+ appLog.info(+ 'link',+ '$short refused ($reason): this app joined the device list',+ );+ }+ final pinned = await _holdsMachineKey(machineId);+ if (!current()) return;+ if (reason == 'E2E_DENIED' || !pinned) {+ final rest = trustSettleRound - started.elapsed;+ final wait = reason == 'E2E_DENIED' && round == 1+ ? trustDeniedWait+ : rest.isNegative+ ? Duration.zero+ : rest;+ await Future.any([Future<void>.delayed(wait), wake.future]);+ if (!current()) return;+ }+ final now = pinned || await _holdsMachineKey(machineId);+ if (!current()) return;+ appLog.info(+ 'link',+ '$short refused ($reason): ${now ? 'pinned' : 'no key yet'}, dialling again (round $round)',+ );+ _endTrustSettle(machineId);+ _redial(machineId);+ } finally {+ // However the round ended, a machine no longer being settled can be settled again.+ if (identical(_trustWakes[machineId], wake)) _endTrustSettle(machineId);+ }+ }++ void _endTrustSettle(String machineId) {+ _trustSettling.remove(machineId);+ final wake = _trustWakes.remove(machineId);+ if (wake != null && !wake.isCompleted) wake.complete();+ }++ /// [machineId] connected, or the account is left: its refusals start counting again.+ void _forgetTrustSettle(String machineId) {+ _trustRounds.remove(machineId);+ _endTrustSettle(machineId);+ }++ void _forgetAllTrustSettles() {+ for (final machineId in [..._trustRounds.keys, ..._trustSettling]) {+ _forgetTrustSettle(machineId);+ }+ }++ Future<bool> _holdsMachineKey(String machineId) async {+ try {+ return await viewer?.keys.peer(machineId) != null;+ } catch (_) {+ return false;+ }+ }++ /// Dial [machineId] again from scratch: a refused connection is closed for good+ /// ([WsConn.isClosed]), so it is closed and replaced, as the link retry does.+ void _redial(String machineId) {+ final machine = machineStates[machineId];+ if (machine == null) return;+ onRedialForTest?.call(machineId);+ unawaited(_pool?.closeMachine(machineId));+ _connectMachine(machine);+ }++ /// The device log changed: a machine waiting on trust — being settled, or asking for its password —+ /// that this app now holds a key for is dialled again at once rather than on the next retry tick.+ Future<void> _redialPinnedMachines() async {+ final revision = _authRevision;+ for (final entry in [...machineStates.entries]) {+ final machineId = entry.key;+ if (!_trustSettling.contains(machineId) && !entry.value.needsLink) {+ continue;+ }+ if (!await _holdsMachineKey(machineId) || !_authWorkCurrent(revision)) {+ continue;+ }+ if (_trustWakes[machineId] case final wake? when !wake.isCompleted) {+ wake.complete();+ } else if (entry.value.needsLink &&+ identical(machineStates[machineId], entry.value)) {+ appLog.info(+ 'link',+ '${_shortId(machineId)} pinned from the device list, dialling again',+ );+ _redial(machineId);+ }+ }+ }+/// The daemon on this computer closed our select with 4403: it serves a different machine id than/// the row we hold for "this computer". Ask it which (`/api/status.machineId`), say so in the log —/// this used to be a silent reconnect every 30s, forever — and stand its machine up beside the@@ -5640,7 +5856,13 @@ class AppNotifier extends ChangeNotifier {onStatus: (machineId, nextStatus) {final machine = machineStates[machineId];if (machine == null) return;- machine.connectionStatus = nextStatus;+ // A refusal being settled against the device log ([_settleTrust]) is still connecting.+ final settling =+ nextStatus == ConnectionStatus.disconnected &&+ _trustSettling.contains(machineId);+ machine.connectionStatus = settling+ ? ConnectionStatus.connecting+ : nextStatus;if (nextStatus == ConnectionStatus.connected) {_onMachineConnected(machineId, machine);_refreshDeviceLogAfterReconnect();@@ -5665,7 +5887,7 @@ class AppNotifier extends ChangeNotifier {// every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on// purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is// set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).- if (!machine.needsLink) {+ if (!machine.needsLink && !settling) {unawaited(_applyNodeStatus(machine,@@ -6132,9 +6354,34 @@ class AppNotifier extends ChangeNotifier {}unawaited(_rereadMachinesInBackground(pushed: false));});+ if (viewer != null) {+ // Only while the tab is in front: a tab left open behind others, its machines all off,+ // would otherwise ask every 20s for as long as the browser runs. Coming back to it asks at once.+ _deafMachineListTimer ??= Timer.periodic(deafMachineListInterval, (_) {+ if (foreground.value) _rereadMachinesWhileDeaf();+ });+ }notifyListeners();}+ /// Whether this viewer has no machine socket open, so no push can reach it.+ bool get _viewerIsDeaf =>+ viewer != null &&+ !machineStates.values.any(+ (m) =>+ !m.machine.isShared &&+ m.connectionStatus == ConnectionStatus.connected,+ );++ /// A viewer that hears nothing re-reads the machine list: the computer the person is signing in+ /// on right now appears, and the dial that follows reads the device log for its key first.+ void _rereadMachinesWhileDeaf() {+ if (_disposed || status != AppStatus.authenticated || !_viewerIsDeaf) {+ return;+ }+ unawaited(_rereadMachinesInBackground(pushed: false));+ }+/// Re-read the machine list because something other than the person asked:/// a `machines_changed` push, or the safety-net timer.///@@ -6523,6 +6770,17 @@ class AppNotifier extends ChangeNotifier {bool _baselineSeenLocally = false;bool get baselineSeenLocally => _baselineSeenLocally;+ /// Viewer builds only: this app's copy of the device log is frozen, so it pins no machine from it+ /// until someone reviews the list (Settings ▸ Your devices). A machine asking for its password says so.+ bool get deviceListNeedsReview => _deviceListFrozen;+ bool _deviceListFrozen = false;++ @visibleForTesting+ set deviceListNeedsReviewForTest(bool frozen) {+ _deviceListFrozen = frozen;+ notifyListeners();+ }+/// Everything this window said about the account's devices belongs to the account that is leaving/// (logout and a runtime sign-out both): the banners, the unsaved dismissals, and any read still in/// flight, which must not write the old account's listing under the next one.@@ -6535,6 +6793,7 @@ class AppNotifier extends ChangeNotifier {_dismissedConflict = null;_dismissedDevices.clear();_baselineSeenLocally = false;+ _deviceListFrozen = false;_pendingBootReadDone = false;_pendingSyncGeneration++;}@@ -6575,6 +6834,7 @@ class AppNotifier extends ChangeNotifier {onChanged: () {devicesRevision++;unawaited(_syncPendingDevices());+ unawaited(_redialPinnedMachines());if (!_disposed) notifyListeners();},);@@ -6619,8 +6879,9 @@ class AppNotifier extends ChangeNotifier {DateTime? _deviceLogReadAt;- /// A socket came back: a `device_keys_changed` sent while this app was offline reached nobody, so- /// read the log again — at most every half minute, since a reconnect is every machine at once.+ /// A socket came back (or the app is in front again): a `device_keys_changed` sent meanwhile reached+ /// nobody, so read the log again — and put this app's key into it if the boot's register could not —+ /// at most every half minute, since a reconnect is every machine at once.void _refreshDeviceLogAfterReconnect() {final log = _deviceLog;if (log == null) return;@@ -6630,7 +6891,7 @@ class AppNotifier extends ChangeNotifier {return;}_deviceLogReadAt = now;- unawaited(log.refresh());+ unawaited(log.ensureRegistered());}/// A desktop build's link to its own daemon came back: a conflict, a new device or a departed key@@ -6671,8 +6932,10 @@ class AppNotifier extends ChangeNotifier {DeviceConflict? conflict;var daemon = false;var legacyDaemon = false;+ var frozen = false;if (_deviceLog case final log?) {final listing = await log.list();+ frozen = listing.frozen != null;pending = listing.pending;departed = listing.departed;known = [for (final r in listing.members) NewDeviceNotice.fromMember(r.member, suspended: r.suspended)];@@ -6706,14 +6969,16 @@ class AppNotifier extends ChangeNotifier {if (_disposed || generation != _pendingSyncGeneration || status == AppStatus.unauthenticated) return;_pendingBootReadDone = true;if (legacyDaemon) return;+ var changed = frozen != _deviceListFrozen;+ _deviceListFrozen = frozen;// Oldest first: the band names the first, and "(+n more)" the rest.final order = {for (var i = 0; i < pending.length; i++) pending[i]: i};final next = [for (final n in known)if (order.containsKey(n.pub) && !_dismissedDevices.contains(n.pub)) n,]..sort((a, b) => order[a.pub]!.compareTo(order[b.pub]!));- var changed = !_samePubs(newDevices, next);- if (changed) {+ if (!_samePubs(newDevices, next)) {+ changed = true;newDevices..clear()..addAll(next);@@ -7305,12 +7570,53 @@ class AppNotifier extends ChangeNotifier {).machineId;}+ if (_deviceLog case final log?) {+ unawaited(+ _connectAfterDeviceLog(log, [+ for (final machine in machines) machineStates[machine.machineId]!,+ ]),+ );+ return;+ }for (final machine in machines) {_connectMachine(machineStates[machine.machineId]!);unawaited(_loadMachineData(machineStates[machine.machineId]!));}}+ /// Viewer builds: a machine this app holds no key for may only be missing from its copy of the+ /// device log — a computer signed in after this app did — so the log is read first, briefly,+ /// rather than dialling a refusal. Machines with a key, and ones already asking for a password,+ /// dial at once.+ Future<void> _connectAfterDeviceLog(+ ViewerDeviceLog log,+ List<MachineState> states,+ ) async {+ final revision = _authRevision;+ final waiting = <MachineState>[];+ for (final state in states) {+ if (state.machine.isShared ||+ state.needsLink ||+ await _holdsMachineKey(state.machine.machineId)) {+ if (!_authWorkCurrent(revision)) return;+ _connectMachine(state);+ unawaited(_loadMachineData(state));+ } else {+ waiting.add(state);+ }+ }+ if (waiting.isEmpty) return;+ await log.refresh().timeout(const Duration(seconds: 5), onTimeout: () {});+ for (final state in waiting) {+ if (!_authWorkCurrent(revision) ||+ !identical(machineStates[state.machine.machineId], state)) {+ continue;+ }+ _connectMachine(state);+ unawaited(_loadMachineData(state));+ }+ }+/// A user-triggered reload is in flight.////// Read by the rail's reload button, which spins its glyph and stops taking@@ -9280,9 +9586,14 @@ class AppNotifier extends ChangeNotifier {// Through `_conn`, the resolver everything else on this socket uses — it// refuses a shared harness, which this window has no business reporting on// anyway, by throwing rather than by returning null.+ // This window's desk state, for its own daemon only (see [_deskConnection]): a viewer has none,+ // and must not dial a machine just to say it.+ if (viewer != null) return;try {+ final connection = _conn(machineId);+ if (!connection.isLocal) return;unawaited(- _conn(machineId)+ connection.sendTerminalFrame('agent_seen', {'agentId': agentId,'readToken': ?readToken,@@ -15814,6 +16125,14 @@ class AppNotifier extends ChangeNotifier {void daemonSnapshotForTest(LocalCliEndpoint endpoint) =>_updateLocalProjectSnapshot(endpoint);+ /// [connection] as [machineId]'s socket in the pool, which the frames this window broadcasts (the+ /// dial's roster, the unread list) are sent on — [connectionForTest] stands in for `_conn` only.+ @visibleForTesting+ void adoptPoolConnectionForTest(String machineId, WsConn connection) {+ _ensurePool();+ _pool!.adoptForTest(machineId, connection);+ }+/// What the local CLI closing this machine's socket with [code] does to the/// model — the `WsPool.onLocalFailure` path, without a socket.@visibleForTesting@@ -15861,6 +16180,7 @@ class AppNotifier extends ChangeNotifier {agentUnread.dispose();_disposed = true;_sharingDiscoveryTimer?.cancel();+ _deafMachineListTimer?.cancel();_stopMachineRecovery();if (signingIn) cliLogin.cancel();_closedHistory.clear();diff --git a/desktop/lib/viewer/device_log_sync.dart b/desktop/lib/viewer/device_log_sync.dartindex 9248b9c1a..ca1d23bc6 100644--- a/desktop/lib/viewer/device_log_sync.dart+++ b/desktop/lib/viewer/device_log_sync.dart@@ -309,6 +309,10 @@ class DeviceLogRebaseline {final bool otherAccount;}+/// What [ViewerDeviceLog.ensureRegistered] found: this app's key already in the log, put there just now,+/// kept out by a frozen log, or still missing (no log to read, the backend down, a refusal).+enum DeviceLogRegistration { active, registered, frozen, missing }+class ViewerDeviceLog {ViewerDeviceLog({required this.keys,@@ -362,6 +366,10 @@ class ViewerDeviceLog {/// Set while [register] runs.bool _registering = false;+ /// The [register] under way, which [ensureRegistered] lets finish before it judges.+ Future<void>? _registerRun;+ Future<DeviceLogRegistration>? _ensuring;+/// Moves on with each [beginSignIn]: a read that began after one, outside [register], ends what it/// set — a sign-in by hand that never registers must not keep this app's own removal from signing/// it out for good.@@ -399,7 +407,15 @@ class ViewerDeviceLog {/// A sign-in by hand is also what lets this app's copy of the log move to another account (keeping/// the one it leaves, to restore if it comes back) — for a short while after it ([_resetWindowMs])./// Its id is minted by [beginSignIn], which [register] calls itself when it was not called before.- Future<void> register({bool freshSignIn = false}) async {+ Future<void> register({bool freshSignIn = false}) {+ final run = _register(freshSignIn: freshSignIn);+ _registerRun = run;+ return run.whenComplete(() {+ if (identical(_registerRun, run)) _registerRun = null;+ });+ }++ Future<void> _register({required bool freshSignIn}) async {if (freshSignIn && !_freshPending) beginSignIn(fresh: true);final fresh = _freshPending;_freshPending = false;@@ -444,13 +460,43 @@ class ViewerDeviceLog {await _sleep(Duration(milliseconds: 200 + _random.nextInt(800) * (attempt + 1)));}} catch (_) {- // The next sign-in, resume or push tries again.+ // [ensureRegistered] tries again: a machine refusing this app, a socket back, the app in front.} finally {_signingInAgain = false;_registering = false;}}+ /// Put this app's key into the log when it is not there yet. [register] can end without it — no log+ /// to read, the backend down, five lost races, a refusal — and then no machine will trust this app,+ /// so this is asked again whenever that matters: a machine refusing this app, a socket coming back,+ /// the app in front again. A frozen log is left as it is: only a review unfreezes it. Concurrent+ /// calls share one run. Never throws.+ Future<DeviceLogRegistration> ensureRegistered() =>+ _ensuring ??= _ensureRegistered().whenComplete(() => _ensuring = null);++ Future<DeviceLogRegistration> _ensureRegistered() async {+ try {+ // A register already under way (the boot's) decides first: a second one beside it would race it.+ await _registerRun;+ await refresh();+ if (await _registration() case final known?) return known;+ await register();+ return await _registration() == DeviceLogRegistration.active+ ? DeviceLogRegistration.registered+ : DeviceLogRegistration.missing;+ } catch (_) {+ return DeviceLogRegistration.missing;+ }+ }++ /// Where this app's key stands in the file: null when it is not there and nothing keeps it out.+ Future<DeviceLogRegistration?> _registration() async {+ final file = await _read();+ if (file.state?.active.containsKey(await _selfPub()) ?? false) return DeviceLogRegistration.active;+ return file.frozen != null ? DeviceLogRegistration.frozen : null;+ }+/// The app knows who is signed in — call it synchronously, before anything that reads the log (a/// restored pane, a machine list, a connection) can start, then [register]. [fresh]: the person/// signed in by hand just now (`DirectAuth.consumeFreshSignIn()`); its id is minted here, so a readdiff --git a/desktop/lib/widgets/machines_panel.dart b/desktop/lib/widgets/machines_panel.dartindex 1478f850e..38986d5c0 100644--- a/desktop/lib/widgets/machines_panel.dart+++ b/desktop/lib/widgets/machines_panel.dart@@ -26,6 +26,7 @@ import 'link_another_machine_dialog.dart'kLinkServerStartCommand;import 'link_machine_dialog.dart';import 'machine_actions.dart';+import 'new_device_notice.dart' show DeviceListReviewLine;import 'terminal_name_prompt.dart';import 'terminal_prompt.dart';import 'transient_menus.dart';@@ -722,6 +723,7 @@ class _MachinesPanelState extends State<_MachinesPanel>: null,menuBuilder: machine.machine.isShared ? null : menu,offline: offline,+ footer: canConnect ? DeviceListReviewLine(notifier: app) : null,);}@@ -986,6 +988,7 @@ class _MachineRow extends StatelessWidget {this.offline = false,this.onTap,this.hint,+ this.footer,});final String name;final bool local;@@ -998,6 +1001,9 @@ class _MachineRow extends StatelessWidget {final VoidCallback? onTap;final String? hint;+ /// A line under the row, aligned with its text.+ final Widget? footer;+@overrideWidget build(BuildContext context) {final row = Padding(@@ -1075,6 +1081,11 @@ class _MachineRow extends StatelessWidget {padding: const EdgeInsets.only(top: 10),child: Align(alignment: Alignment.centerRight, child: action),),+ if (footer case final footer?)+ Padding(+ padding: const EdgeInsets.only(left: 34, top: 4),+ child: footer,+ ),],);},@@ -1560,6 +1571,7 @@ class _MachinePasswordState extends State<_MachinePassword> {: 'On ${widget.machine.machine.displayName}, open Machines → Set password.',),],+ if (!_local) DeviceListReviewLine(notifier: widget.app),if (_local && _status?.hasPassword == true)Align(alignment: Alignment.centerLeft,diff --git a/desktop/lib/widgets/new_device_notice.dart b/desktop/lib/widgets/new_device_notice.dartindex 61e2fdd4d..78f8d99f7 100644--- a/desktop/lib/widgets/new_device_notice.dart+++ b/desktop/lib/widgets/new_device_notice.dart@@ -275,3 +275,46 @@ class DeviceConflictNoticeBand extends StatelessWidget {);}}++/// Settings ▸ Your devices, from a machine that asks for its password while this app's device list is+/// frozen ([AppNotifier.deviceListNeedsReview]): the list pins no machine again until it is reviewed.+void showDeviceListReview(BuildContext context, AppNotifier notifier) => unawaited(+ showSettingsScreen(+ context,+ notifier,+ initialSection: SettingsSection.accountDevices,+ source: 'needs-link',+ ),+);++/// The line under a machine's password prompt while this app's device list is frozen: the password is+/// one way in, the review the other. Nothing while the list needs no review.+class DeviceListReviewLine extends StatelessWidget {+ const DeviceListReviewLine({super.key, required this.notifier, this.center = false});++ final AppNotifier notifier;+ final bool center;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ if (!notifier.deviceListNeedsReview) return const SizedBox.shrink();+ return Wrap(+ alignment: center ? WrapAlignment.center : WrapAlignment.start,+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 4,+ children: [+ Text(+ 'Your device list needs a review.',+ textAlign: center ? TextAlign.center : TextAlign.start,+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),+ ),+ TextButton(+ key: const Key('device-list-review'),+ onPressed: () => showDeviceListReview(context, notifier),+ child: const Text('Your devices'),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex ca7bdf042..c22cb916f 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -31,6 +31,7 @@ import 'agent_drag.dart';import 'harness_join_guide_screen.dart';import 'link_machine_screen.dart';import 'new_agent_dialog.dart';+import 'new_device_notice.dart' show DeviceListReviewLine, showDeviceListReview;import 'delete_agent_dialog.dart';import 'restart_agent_action.dart';import 'terminal_panel.dart';@@ -1574,11 +1575,15 @@ class _PaneContent extends StatelessWidget {: 'Waiting for this machine. Retained output is read only.',);} else if (needsLink) {+ // A frozen device list may be why it asks: the band says so, beside+ // the password.+ final review = notifier.deviceListNeedsReview;notice = terminalNotice(label: 'Link required',icon: AppIcons.unlink,- detail:- '${machine.machine.displayName} needs linking. Retained output is read only.',+ detail: review+ ? '${machine.machine.displayName} needs linking. Your device list needs a review.'+ : '${machine.machine.displayName} needs linking. Retained output is read only.',// A tile still showing its last screen gets the same way out as an// empty one — the band's button asks for the remote password.actionLabel: 'Link…',@@ -1587,6 +1592,11 @@ class _PaneContent extends StatelessWidget {notifier,pane.machineId,).ignore(),+ secondaryLabel: review ? 'Your devices' : null,+ onSecondary: review+ ? () => showDeviceListReview(context, notifier)+ : null,+ banner: review,);} else if (offline) {notice = terminalNotice(@@ -1749,6 +1759,7 @@ class _PaneContent extends StatelessWidget {notifier,pane.machineId,).ignore(),+ footer: DeviceListReviewLine(notifier: notifier, center: true),);}if (offline) {@@ -2287,6 +2298,7 @@ class _PaneStatus extends StatelessWidget {this.busy = false,this.actionLabel,this.onAction,+ this.footer,});final String title;@@ -2301,6 +2313,10 @@ class _PaneStatus extends StatelessWidget {final String? actionLabel;final VoidCallback? onAction;+ /// Anything more under the way out — a machine asking for its password:+ /// a device list to review.+ final Widget? footer;+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -2342,6 +2358,7 @@ class _PaneStatus extends StatelessWidget {const SizedBox(height: 4),TextButton(onPressed: onAction, child: Text(actionLabel!)),],+ ?footer,],),),diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 5cf1978fc..0f719b26e 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -70,6 +70,11 @@ typedef TerminalNotice = ({String? actionLabel,VoidCallback? onAction,+ /// A second way out, offered on the band only ([banner]) — a machine asking+ /// for its password while this app's device list waits for a review.+ String? secondaryLabel,+ VoidCallback? onSecondary,+/// Whether this one also earns a band above the terminal output./// Startup and failure guidance needs to be read, not hovered./// An offline machine is neither confusing nor rare, and a band on every one@@ -88,6 +93,8 @@ TerminalNotice terminalNotice({required IconData icon,String? actionLabel,VoidCallback? onAction,+ String? secondaryLabel,+ VoidCallback? onSecondary,bool banner = false,}) => (label: label,@@ -95,6 +102,8 @@ TerminalNotice terminalNotice({icon: icon,actionLabel: actionLabel,onAction: onAction,+ secondaryLabel: secondaryLabel,+ onSecondary: onSecondary,banner: banner,);@@ -3418,7 +3427,7 @@ class _ControlBanner extends StatelessWidget {],),);- final button = notice != null+ final primary = notice != null? (notice!.actionLabel == null? null: _ControlBannerButton(@@ -3429,6 +3438,31 @@ class _ControlBanner extends StatelessWidget {: busy? null: _ControlBannerButton(onPressed: onTakeControl);+ final secondary = notice?.secondaryLabel;+ final button = secondary == null+ ? primary+ : Wrap(+ spacing: 8,+ runSpacing: 8,+ alignment: WrapAlignment.end,+ children: [+ TextButton(+ onPressed: notice!.onSecondary,+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 28),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.compact,+ ),+ child: Text(+ secondary,+ style: grid.AppType.mono(+ fontWeight: FontWeight.w500,+ ),+ ),+ ),+ ?primary,+ ],+ );if (narrow) {return Column(crossAxisAlignment: CrossAxisAlignment.stretch,diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex 81d05293c..2f3e6cc6a 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -528,6 +528,10 @@ class WsConn {/// three — only a link can — so this stops and says so the way the CLI's own relay does, with/// 4404.void _refusePeer(String reason) {+ appLog.info(+ 'ws',+ 'refused ${machineId.length > 8 ? machineId.substring(0, 8) : machineId}: $reason',+ );_closing = true;_ready = false;_observerHandshakeTimer?.cancel();diff --git a/desktop/lib/ws/ws_pool.dart b/desktop/lib/ws/ws_pool.dartindex c10618147..9e04fa5c5 100644--- a/desktop/lib/ws/ws_pool.dart+++ b/desktop/lib/ws/ws_pool.dart@@ -109,6 +109,11 @@ class WsPool {WsConn? operator [](String machineId) => _conns[machineId];+ /// Holds [conn] as [machineId]'s socket, as if it had been dialled — for a+ /// test that watches what is sent on which kind of connection+ /// (`AppNotifier.adoptPoolConnectionForTest`).+ void adoptForTest(String machineId, WsConn conn) => _conns[machineId] = conn;+/// The machines this pool holds a socket for. A snapshot, so a caller can send/// on each without a concurrent connect mutating what it is walking.List<String> get machineIds => _conns.keys.toList(growable: false);diff --git a/desktop/test/device_viewer_notices_test.dart b/desktop/test/device_viewer_notices_test.dartindex 2b0c33a67..b8d43f15b 100644--- a/desktop/test/device_viewer_notices_test.dart+++ b/desktop/test/device_viewer_notices_test.dart@@ -3,6 +3,7 @@// removal it reads becomes a band — red when a device nobody has looked at did it.import 'dart:async';+import 'package:flutter/widgets.dart' show AppLifecycleState;import 'package:flutter_test/flutter_test.dart';import 'package:harness/api/api_client.dart';import 'package:harness/auth/auth_session.dart';@@ -169,8 +170,14 @@ class _Api extends ApiClient {};}+ /// How many times the machine list was read.+ int machineReads = 0;+@override- Future<List<Machine>> machines() async => const [];+ Future<List<Machine>> machines() async {+ machineReads++;+ return const [];+ }}/// A viewer that is already signed in when it opens.@@ -291,6 +298,46 @@ void main() {return app;}+ test('with no machine to hear pushes from, the machine list is read again on its own and on coming back to the tab', () async {+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(storage: MemoryStore()),+ configStore: null,+ cliLogin: _SignedIn(),+ viewer: ViewerServices(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryStore()),+ keys: keys,+ ),+ )..deafMachineListInterval = const Duration(milliseconds: 40);+ final api = _Api(backend)..user = 'user-a';+ app.api = api;+ addTearDown(app.dispose);+ await app.bootstrap();+ await settle();+ final afterBoot = api.machineReads;+ expect(afterBoot, greaterThan(0));++ // Nothing connected: no `machines_changed` can reach this tab, so the list is asked for again.+ await Future<void>.delayed(const Duration(milliseconds: 130));+ await settle();+ expect(api.machineReads, greaterThan(afterBoot));++ // Behind other tabs: not asked for at all.+ app.appLifecycleChanged(AppLifecycleState.hidden);+ final hidden = api.machineReads;+ await Future<void>.delayed(const Duration(milliseconds: 130));+ await settle();+ expect(api.machineReads, hidden);++ // Back to the tab (the person was signing in their computer): asked for at once.+ final beforeResume = api.machineReads;+ app.deafMachineListInterval = const Duration(hours: 1);+ app.appLifecycleChanged(AppLifecycleState.resumed);+ await settle();+ expect(api.machineReads, greaterThan(beforeResume));+ });+test('signing in by hand as another account starts that account\'s list over', () async {// Account A: this browser joined its log.await backend.add(box2, 'machine', 'b' * 32, 'box2');@@ -967,4 +1014,127 @@ void main() {expect(app.newDevices, isEmpty);expect(app.deviceRemovals, isEmpty);});++ // A web app signed in first, then `harness login` on a computer: the machine is new to this app's+ // copy of the log (or this app to the machine's), and the refusal says nothing more than "early".+ // It is settled — this app joins the log, reads it, dials again — before a password is asked for.+ group('a machine that refuses this app for want of trust', () {+ final mid = 'b' * 32;++ AppNotifier withMachine() {+ final app = start();+ addTearDown(app.dispose);+ const name = 'box2';+ final machine = Machine(+ machineId: mid,+ authMode: MachineAuthMode.remote,+ name: name,+ );+ app.machines = [machine];+ app.machineStates[mid] = MachineState(machine)..nodeOnline = true;+ return app;+ }++ Future<void> until(bool Function() done) async {+ for (var i = 0; i < 500 && !done(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ }++ test(+ 'the log names it: pinned and dialled again, no password asked',+ () async {+ final app = withMachine();+ await backend.add(box2, 'machine', mid, 'box2');+ expect(+ await keys.peer(mid),+ isNull,+ reason: 'this app has not read the log since',+ );+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;++ app.localFailureForTest(mid, 4404, 'NO_PEER_LINK');+ expect(+ app.stateOf(mid)!.needsLink,+ isFalse,+ reason: 'still connecting while it is settled',+ );+ await until(() => redialled.isNotEmpty);++ expect(redialled, [mid]);+ expect(app.stateOf(mid)!.needsLink, isFalse);+ expect(await keys.peer(mid), isNotNull);+ final me = b64e((await keys.identity()).pub);+ expect(+ backend.state.active[me]?.kind,+ 'viewer',+ reason: 'this app joined the log on the way',+ );+ },+ );++ test('denied once, then let in: never asks for a password', () async {+ final app = withMachine()+ ..trustDeniedWait = const Duration(milliseconds: 10);+ await keys.pin(mid, box2.pub, label: 'box2');+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;++ app.localFailureForTest(mid, 4404, 'E2E_DENIED');+ await until(() => redialled.isNotEmpty);+ await settle();++ expect(redialled, [mid]);+ expect(app.stateOf(mid)!.needsLink, isFalse);+ expect(+ app.stateOf(mid)!.agentLoadStatus,+ isNot(AgentLoadStatus.needsLink),+ );+ });++ test('still refused after the grace: the password it is', () async {+ final app = withMachine()+ ..trustSettleRound = const Duration(milliseconds: 20);+ var redials = 0;+ // Each dial again is refused again: nothing names this machine.+ app.onRedialForTest = (id) {+ redials++;+ scheduleMicrotask(+ () => app.localFailureForTest(id, 4404, 'NO_PEER_LINK'),+ );+ };++ app.localFailureForTest(mid, 4404, 'NO_PEER_LINK');+ await until(() => app.stateOf(mid)!.needsLink);++ expect(app.stateOf(mid)!.needsLink, isTrue);+ expect(app.stateOf(mid)!.agentLoadStatus, AgentLoadStatus.needsLink);+ expect(redials, 2, reason: 'two rounds, then the password');+ });++ test('a frozen log settles nothing: the password at once, and the list asks for a review', () async {+ final app = withMachine();+ await backend.add(box2, 'machine', 'c' * 32, 'box3');+ await logOf(app).refresh();+ final file = Map<String, Object?>.from(await keys.deviceLog() as Map);+ file['frozen'] = {+ 'reason': 'fork',+ 'at': 1,+ 'lastGoodHead': backend.state.head.toJson(),+ };+ await keys.writeDeviceLog(file);+ final redialled = <String>[];+ app.onRedialForTest = redialled.add;++ app.localFailureForTest(mid, 4404, 'NO_PEER_LINK');+ await until(+ () => app.stateOf(mid)!.needsLink && app.deviceListNeedsReview,+ );++ expect(app.stateOf(mid)!.needsLink, isTrue);+ expect(app.deviceListNeedsReview, isTrue);+ expect(redialled, isEmpty);+ });+ });}diff --git a/desktop/test/e2ee/encrypted_down_types_test.dart b/desktop/test/e2ee/encrypted_down_types_test.dartindex cbe25faea..8d3b396ec 100644--- a/desktop/test/e2ee/encrypted_down_types_test.dart+++ b/desktop/test/e2ee/encrypted_down_types_test.dart@@ -7,30 +7,84 @@ import 'package:harness/e2ee/envelope.dart';////// ⚠️ **Read from the CLI's source, not copied into this test.** A type the CLI requires sealed and/// this client does not fails nowhere here — the frame leaves in the clear and the machine answers-/// E2EE_REQUIRED. That is how `agent_resume` and `agent_fork` went unsealed from the web build.-/// Only a test that reads the CLI's list notices the day it grows (mobile has the same test).+/// E2EE_REQUIRED. That is how `agent_resume` and `agent_fork` went unsealed from the web build, and+/// `git_pull_request` after them. Only a test that reads the CLI's lists notices the day they grow+/// (mobile has the same test).+///+/// The CLI's rule is `encryptDownFrame` (`cli/src/lib/e2ee/applicationFrames.ts`): the shared core's+/// `ENCRYPTED_DOWN_TYPES` plus the harness-only extensions declared beside it. Both halves are read.void main() {- test('every frame the shared core requires sealed is sealed', () {- final file = File('../cli/src/lib/e2ee/core.ts');+ String cli(String path) {+ final file = File('../cli/src/$path');if (!file.existsSync()) {throw StateError('${file.path} missing — run from desktop/ in the monorepo',);}- final source = file.readAsStringSync();- const start = 'ENCRYPTED_DOWN_TYPES = new Set<string>([';+ return file.readAsStringSync();+ }++ /// The quoted names in the set literal that follows [start], `//` comments stripped first — the+ /// CLI's comments quote type names too.+ Set<String> namesIn(String source, String start) {final from = source.indexOf(start);- expect(from, greaterThanOrEqualTo(0));- // The CLI's comments quote type names too: strip `//` comments before reading the names.- final code = source- .substring(from, source.indexOf('])', from))+ if (from < 0) throw StateError('could not find $start');+ final body = source.substring(from, source.indexOf('])', from));+ final code = body.split('\n').map((line) => line.split('//').first).join('\n');- final core = {- for (final m in RegExp(r"'([a-z0-9_]+)'").allMatches(code)) m[1]!,+ return {+ for (final match in RegExp(r"'([a-z0-9_]+)'").allMatches(code)) match[1]!,};+ }++ late Set<String> core, machineRequests, unwrapped;+ setUpAll(() {+ core = namesIn(+ cli('lib/e2ee/core.ts'),+ 'ENCRYPTED_DOWN_TYPES = new Set<string>([',+ );+ final frames = cli('lib/e2ee/applicationFrames.ts');+ final relay = cli('lib/relayFrames.ts');+ // `MACHINE_REQUESTS` also spreads the owner commands in; those are read where they are declared.+ machineRequests = {+ ...namesIn(frames, 'MACHINE_REQUESTS = new Set(['),+ ...namesIn(relay, 'OWNER_COMMAND_TYPES = new Set(['),+ };+ unwrapped = {+ ...core,+ ...machineRequests,+ ...namesIn(frames, 'FLEET_REQUESTS = new Set(['),+ ...namesIn(relay, 'PAIR_REQUESTS = new Set(['),+ ...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES = new Set(['),+ ...namesIn(cli('teams/wire.ts'), 'TEAM_REQUEST_TYPES = new Set(['),+ ...namesIn(cli('lib/viewerWire.ts'), 'VIEWER_DOWN_TYPES = new Set(['),+ };+ });++ test('every frame the shared core requires sealed is sealed', () {expect(core, isNotEmpty);expect(core.difference(encryptedDownTypes), isEmpty);});++ test('nothing is sealed that the machine would not open', () {+ expect(encryptedDownTypes.difference(unwrapped), isEmpty);+ });++ test('a machine request this client sends is sealed', () {+ expect(machineRequests, contains('git_pull_request'));+ // Any quoted use outside the list itself counts as sending it.+ final sent = <String>{};+ for (final file in Directory('lib').listSync(recursive: true)) {+ if (file is! File || !file.path.endsWith('.dart')) continue;+ if (file.path.endsWith('e2ee/envelope.dart')) continue;+ final source = file.readAsStringSync();+ for (final type in machineRequests) {+ if (source.contains("'$type'")) sent.add(type);+ }+ }+ expect(sent, contains('git_pull_request'));+ expect(sent.difference(encryptedDownTypes), isEmpty);+ });}diff --git a/desktop/test/e2ee/strict_down_test.dart b/desktop/test/e2ee/strict_down_test.dartindex eefa25891..f5d3b08f5 100644--- a/desktop/test/e2ee/strict_down_test.dart+++ b/desktop/test/e2ee/strict_down_test.dart@@ -68,6 +68,23 @@ void main() {}});+ test('a pull-request lookup is sealed for every machine', () async {+ // A machine RPC (applicationFrames.ts `MACHINE_REQUESTS`): unsealed, the machine refuses it with+ // E2EE_REQUIRED, and the relay reads which harness was asked about.+ for (final features in [+ <String, Object>{},+ <String, Object>{'strictDown': 1},+ ]) {+ final session = await _session(features);+ final out = session.wrapOutgoing({+ 'type': 'git_pull_request',+ 'payload': {'requestId': 'pr-1', 'agentId': 'private-agent'},+ });+ expect(isWrapped(out['payload']), isTrue);+ expect(jsonEncode(out), isNot(contains('private-agent')));+ }+ });+final install = {'type': 'dsh_install','payload': {'requestId': 'r', 'url': 'https://example.invalid/h.git'},diff --git a/desktop/test/machines_panel_test.dart b/desktop/test/machines_panel_test.dartindex f0b7397a6..36e8f85c3 100644--- a/desktop/test/machines_panel_test.dart+++ b/desktop/test/machines_panel_test.dart@@ -591,6 +591,26 @@ void main() {await tester.pumpWidget(const SizedBox());});+ testWidgets('a frozen device list is offered beside a machine\'s password', (+ tester,+ ) async {+ app+ ..add('remote', 'Mac mini')+ ..deviceListNeedsReviewForTest = true;+ await mount(tester);+ // The row, and the form it opens: the password stays, the review sits under it.+ expect(find.text('Your device list needs a review.'), findsOneWidget);+ await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));+ expect(find.text('Your device list needs a review.'), findsOneWidget);+ expect(find.byKey(const Key('device-list-review')), findsOneWidget);+ expect(remoteInput, findsOneWidget);++ app.deviceListNeedsReviewForTest = false;+ await tester.pumpAndSettle();+ expect(find.text('Your device list needs a review.'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ });+testWidgets('connection continues across closing and reopening', (tester,) async {diff --git a/desktop/test/notification_parity_test.dart b/desktop/test/notification_parity_test.dartindex 0d0d8595d..907ea15f9 100644--- a/desktop/test/notification_parity_test.dart+++ b/desktop/test/notification_parity_test.dart@@ -17,8 +17,11 @@ import 'package:harness/ws/ws_conn.dart';import 'swarm_state_test.dart' show createApp;/// Records the frames this window puts on a machine's socket.+///+/// Local by default: this computer's daemon, which is the only one these frames are for. A relayed+/// connection — every one a viewer (web) build has — must hear none of them.class _Conn extends WsConn {- _Conn()+ _Conn({bool local = true}): super(wsBaseUrl: 'ws://fixture.invalid',autonomousEnv: 'test',@@ -27,6 +30,10 @@ class _Conn extends WsConn {onAuthFailure: (_) {},onEvent: (_) {},onStatus: (_) {},+ transportKind: local+ ? WsTransportKind.localPlaintext+ : WsTransportKind.cloudE2ee,+ localWsUri: local ? Uri.parse('ws://127.0.0.1:1/ws') : null,);final sent = <({String type, Map<String, dynamic> payload})>[];@@ -346,4 +353,43 @@ void main() {expect(conn.sent.where((f) => f.type == 'agent_seen'), isEmpty);});});++ // The desk frames are this window's state for the daemon on this computer+ // (cli/src/localWsServer.ts). A relayed connection would carry them to the+ // machine in the clear — refused there as plaintext, and read on the way.+ group('the desk frames stay on this computer', () {+ Future<List<String>> sentOver({required bool local}) async {+ final conn = _Conn(local: local);+ final app = createApp(connectionForTest: (_) => conn, connected: true)+ ..watchedAgents = () => const [];+ addTearDown(app.dispose);+ app.adoptPoolConnectionForTest('m', conn);+ await app.handleEventForTest('m', {+ 'type': 'turn_summary',+ 'agentId': 'a1',+ 'payload': <String, dynamic>{+ 'notification': {'id': 'desk-result', 'kind': 'done'},+ },+ });+ app.announceWindowForeground();+ app.markAgentSeen('m', 'a1');+ await Future<void>.delayed(Duration.zero);+ return [for (final frame in conn.sent) frame.type];+ }++ test('this computer\'s daemon hears them', () async {+ expect(+ await sentOver(local: true),+ containsAll(['app_unread', 'app_panes', 'app_swarms', 'agent_seen']),+ );+ });++ test('a relayed machine hears none of them', () async {+ final sent = await sentOver(local: false);+ expect(+ sent.where((type) => type.startsWith('app_') || type == 'agent_seen'),+ isEmpty,+ );+ });+ });}diff --git a/desktop/test/pane_needs_link_test.dart b/desktop/test/pane_needs_link_test.dartindex da16b6c3e..d845d52af 100644--- a/desktop/test/pane_needs_link_test.dart+++ b/desktop/test/pane_needs_link_test.dart@@ -203,4 +203,46 @@ void main() {expect(find.text('Link…'), findsNothing);await finish(tester);});++ // A browser whose copy of the device log is frozen pins no machine from it until the list is+ // reviewed: the password is one way in, the review the other, and the tile offers both.+ testWidgets('a frozen device list is offered beside the password', (+ tester,+ ) async {+ app = appWith()..deviceListNeedsReviewForTest = true;+ placeEmptyPane();+ await pump(tester);++ expect(find.text('Your device list needs a review.'), findsOneWidget);+ expect(find.byKey(const Key('device-list-review')), findsOneWidget);+ expect(find.text('Link…'), findsOneWidget, reason: 'the password stays');+ await finish(tester);+ });++ testWidgets('…and on a tile still showing its last screen', (tester) async {+ app = appWith()..deviceListNeedsReviewForTest = true;+ final session = terminal('a0', <TerminalBinaryFrame>[]);+ app.adoptSessionForTest(session);+ app.panes.single.machineId = 'remote-1';+ await pump(tester);++ expect(+ find.textContaining('Your device list needs a review.'),+ findsOneWidget,+ );+ expect(find.text('Your devices'), findsOneWidget);+ expect(find.text('Link…'), findsOneWidget, reason: 'the password stays');+ await finish(tester);+ });++ testWidgets('a list that needs no review says nothing about it', (+ tester,+ ) async {+ app = appWith();+ placeEmptyPane();+ await pump(tester);++ expect(find.textContaining('device list'), findsNothing);+ await finish(tester);+ });}diff --git a/desktop/test/viewer/device_log_sync_test.dart b/desktop/test/viewer/device_log_sync_test.dartindex 476fd2ff1..1764ea3a4 100644--- a/desktop/test/viewer/device_log_sync_test.dart+++ b/desktop/test/viewer/device_log_sync_test.dart@@ -321,6 +321,45 @@ void main() {expect((await log.list()).frozen?.reason, 'fork');});+ group('ensureRegistered', () {+ test('a boot that could not register is made good once the backend answers', () async {+ await backend.add(box2, 'machine', _mid2, 'box2');+ final log = makeLog();+ backend.offline = true;+ await log.register();+ final me = b64e((await keys.identity()).pub);+ expect(backend.state.active[me], isNull, reason: 'no log to read, nothing appended');++ backend.offline = false;+ expect(await log.ensureRegistered(), DeviceLogRegistration.registered);+ expect(backend.state.active[me]?.kind, 'viewer');+ expect(await keys.peer(_mid2), isNotNull, reason: 'the read that came with it pinned the machine');+ });++ test('already in the log: reads it and appends nothing', () async {+ final log = makeLog();+ await log.register();+ final entries = backend.entries.length;+ await backend.add(box2, 'machine', _mid2, 'box2');+ expect(await log.ensureRegistered(), DeviceLogRegistration.active);+ expect(backend.entries.length, entries + 1);+ expect(await keys.peer(_mid2), isNotNull);+ });++ test('a frozen log is left as it is', () async {+ await backend.add(box2, 'machine', _mid2, 'box2');+ await backend.add(box3, 'machine', _mid3, 'box3');+ final log = makeLog();+ await log.refresh();+ backend.lie = backend.entries.sublist(0, 1);+ await log.refresh();+ expect((await log.list()).frozen, isNotNull);+ final entries = backend.entries.length;+ expect(await log.ensureRegistered(), DeviceLogRegistration.frozen);+ expect(backend.entries.length, entries);+ });+ });+test('says which machines report a frozen log', () async {await backend.add(box2, 'machine', _mid2, 'box2');final log = makeLog();