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
feat(devices): show device key codes where they can be compared
0xken15aaabc2109777
diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 6009e0eb1..c8c963069 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -1,14 +1,16 @@import { spawn, spawnSync } from 'child_process'import { createServer, type Server } from 'http'import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs'-import { tmpdir } from 'os'+import { hostname, tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'import { afterEach, describe, expect, it } from 'vitest'+import { b64d, b64e, fingerprint, newIdentity } from './lib/e2ee/core.js'const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')+const FP = /^[0-9A-F]{4}(·[0-9A-F]{4}){3}$/const dirs: string[] = []const servers: Server[] = []@@ -136,6 +138,32 @@ function later<T>(ms: number, value: T): Promise<T> {return new Promise((resolve) => setTimeout(() => resolve(value), ms))}+const identityFile = (root: string): string => join(root, 'data', 'e2e', 'identity.json')++/** This machine's device key, as the daemon would have written it; returns its fingerprint. */+function seedIdentity(root: string): { pub: string; fp: string } {+ const id = newIdentity()+ mkdirSync(join(root, 'data', 'e2e'), { recursive: true })+ writeFileSync(identityFile(root), JSON.stringify({ priv: b64e(id.priv), pub: b64e(id.pub) }))+ return { pub: b64e(id.pub), fp: fingerprint(id.pub) }+}++/** The fingerprint of whatever identity.json holds now. */+function fingerprintOnDisk(root: string): string {+ const raw = JSON.parse(readFileSync(identityFile(root), 'utf8')) as { pub: string }+ return fingerprint(b64d(raw.pub))+}++/** The account's device log as this machine verified it: `active` and `removed` pubs only. */+function seedDevLog(root: string, active: string[], removed: string[]): void {+ mkdirSync(join(root, 'data', 'e2e'), { recursive: true })+ const member = (pub: string) => ({ pub, kind: 'machine', machineId: 'm_seeded', label: 'box', addedAt: Date.now() - 86_400_000, seq: 1 })+ writeFileSync(join(root, 'data', 'e2e', 'devlog.json'), JSON.stringify({+ state: { acct: 'acct', head: { seq: 1, hash: 'h' }, hashes: ['h'], active: Object.fromEntries(active.map((p) => [p, member(p)])), removed },+ recent: [], frozen: null, notifiedUpTo: 1,+ }))+}+describe('harness auth status --json', () => {it('reports loggedIn:false with no saved session, and never touches the network', () => {const root = tempRoot()@@ -180,6 +208,99 @@ describe('harness auth status --json', () => {expect(result.status).toBe(0)expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: true, offline: true, machineId: 'm_seeded' })})++ it('carries this machine\'s fingerprint when its key is on disk', () => {+ const root = tempRoot()+ seedSession(root)+ const { fp } = seedIdentity(root)+ const result = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1')+ expect(result.status).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: true, fingerprint: fp })+ expect(fp).toMatch(FP)+ })++ it('leaves fingerprint out without a key, and never makes one by asking', () => {+ const root = tempRoot()+ const signedOut = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1')+ expect(JSON.parse(signedOut.stdout.trim())).not.toHaveProperty('fingerprint')+ seedSession(root)+ const signedIn = runSync(root, ['auth', 'status', '--json'], 'http://127.0.0.1:1')+ expect(JSON.parse(signedIn.stdout.trim())).not.toHaveProperty('fingerprint')+ expect(existsSync(identityFile(root))).toBe(false)+ })+})++describe('harness status — device row', () => {+ const deviceLine = (stdout: string): string | undefined => stdout.split('\n').find((l) => /^\s+device\s/.test(l))++ it('says the key is in the account when the device log holds it', () => {+ const root = tempRoot()+ seedSession(root)+ const { pub, fp } = seedIdentity(root)+ seedDevLog(root, [pub], [])+ const result = runSync(root, ['status'])+ expect(result.status).toBe(0)+ expect(result.stdout).toContain('○ stopped')+ expect(deviceLine(result.stdout)).toBe(` device ${fp} (in your account)`)+ // After `machine` (when named) and before `version`.+ const lines = result.stdout.split('\n')+ expect(lines.findIndex((l) => l.includes('device '))).toBeLessThan(lines.findIndex((l) => /^\s+version\s/.test(l)))+ })++ it('says the key was removed when the log took it out', () => {+ const root = tempRoot()+ seedSession(root)+ const { pub, fp } = seedIdentity(root)+ seedDevLog(root, [], [pub])+ expect(deviceLine(runSync(root, ['status']).stdout)).toBe(` device ${fp} (removed — run harness login)`)+ })++ it('says not registered yet with a key and no device log', () => {+ const root = tempRoot()+ seedSession(root)+ const { fp } = seedIdentity(root)+ expect(deviceLine(runSync(root, ['status']).stdout)).toBe(` device ${fp} (not registered yet)`)+ })++ it('says removed with only a retired key on disk, and makes no new one', () => {+ const root = tempRoot()+ seedSession(root)+ mkdirSync(join(root, 'data', 'e2e'), { recursive: true })+ writeFileSync(join(root, 'data', 'e2e', 'identity.json.removed-1'), '{}')+ expect(deviceLine(runSync(root, ['status']).stdout)).toBe(' device (removed — run harness login)')+ expect(existsSync(identityFile(root))).toBe(false)+ })++ it('prints no device row with no key at all, and makes no new one', () => {+ const root = tempRoot()+ seedSession(root)+ const result = runSync(root, ['status'])+ expect(result.status).toBe(0)+ expect(result.stdout).toContain('○ stopped')+ expect(deviceLine(result.stdout)).toBeUndefined()+ expect(existsSync(identityFile(root))).toBe(false)+ })++ it('says removed after being removed from the account, which also signed this machine out', () => {+ // The daemon spends the key (identity.json → .removed-*) and clears the session in one go.+ const root = tempRoot()+ mkdirSync(join(root, 'data', 'e2e'), { recursive: true })+ writeFileSync(join(root, 'data', 'e2e', 'identity.json.removed-1'), '{}')+ const result = runSync(root, ['status'])+ expect(result.status).toBe(0)+ expect(deviceLine(result.stdout)).toBe(' device (removed — run harness login)')+ expect(existsSync(identityFile(root))).toBe(false)+ })++ it('says nothing about the account once signed out, even if the last account\'s log is still on disk', () => {+ // logout leaves devlog.json behind; reading it as "in your account" would be false.+ const root = tempRoot()+ const { pub } = seedIdentity(root)+ seedDevLog(root, [pub], [])+ const result = runSync(root, ['status'])+ expect(result.status).toBe(0)+ expect(deviceLine(result.stdout)).toBeUndefined()+ })})/** A `harness … --json` child driven the way the desktop app drives it: stdin left open (closing it is@@ -287,7 +408,7 @@ describe('harness login --json', () => {expect(await login.next()).toMatchObject({ type: 'qr' })expect(await login.next()).toEqual({ type: 'confirm', email: '[email protected]' })login.child.stdin.end('yes\n')- expect(await login.next()).toEqual({ type: 'result', status: 'success', email: '[email protected]' })+ expect(await login.next()).toEqual({ type: 'result', status: 'success', email: '[email protected]', fingerprint: expect.stringMatching(FP) })expect(await login.exit).toBe(0)const session = JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')) as Record<string, unknown>expect(session).toMatchObject({ accessToken: 'tok_qr', method: 'qr' })@@ -304,7 +425,7 @@ describe('harness login --json', () => {})const login = jsonChild(root, base, ['login', '--json'])login.child.stdin.end()- expect(await login.next()).toEqual({ type: 'result', status: 'success', alreadySignedIn: true })+ expect(await login.next()).toEqual({ type: 'result', status: 'success', alreadySignedIn: true, fingerprint: expect.stringMatching(FP) })expect(await login.exit).toBe(0)expect(await login.rest()).toEqual([])}, 15_000)@@ -321,7 +442,7 @@ describe('harness login --json', () => {const lines = result.stdout.trim().split('\n').map((l) => JSON.parse(l))// Harness only: grid is an add-on, signed in the first time a grid feature is used — so the line// says nothing about grid, and not one `grid` command ran, though a `grid` was right there.- expect(lines).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true }])+ expect(lines).toEqual([{ type: 'result', status: 'success', alreadySignedIn: true, fingerprint: expect.stringMatching(FP) }])expect(existsSync(gridCalls)).toBe(false)})@@ -373,7 +494,42 @@ describe('harness login --json', () => {// Drain any trailing buffered line after exit.if (stdout.trim()) lines.push(JSON.parse(stdout.trim()))// Same contract as the already-signed-in line: a fresh Harness sign-in signs in to Harness alone.- expect(lines[1]).toEqual({ type: 'result', status: 'success' })+ expect(lines[1]).toEqual({ type: 'result', status: 'success', fingerprint: expect.stringMatching(FP) })+ expect(lines[1].fingerprint).toBe(fingerprintOnDisk(root))expect(existsSync(gridCalls)).toBe(false)}, 15_000)++ it('already signed in with no key yet: makes the key and reports its fingerprint', async () => {+ const root = tempRoot()+ seedSession(root)+ const { base } = await fakeBackend({ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }) })+ expect(existsSync(identityFile(root))).toBe(false)+ const result = await runAsync(root, ['login', '--json'], base)+ expect(result.status).toBe(0)+ const [line] = result.stdout.trim().split('\n').map((l) => JSON.parse(l))+ expect(line.fingerprint).toBe(fingerprintOnDisk(root))+ })++ it('already signed in with a key: reports that key, not a new one', async () => {+ const root = tempRoot()+ seedSession(root)+ const { fp } = seedIdentity(root)+ const { base } = await fakeBackend({ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }) })+ const result = await runAsync(root, ['login', '--json'], base)+ const [line] = result.stdout.trim().split('\n').map((l) => JSON.parse(l))+ expect(line).toEqual({ type: 'result', status: 'success', alreadySignedIn: true, fingerprint: fp })+ expect(fingerprintOnDisk(root)).toBe(fp)+ })+})++describe('harness login (human)', () => {+ it('already signed in: names this machine and its key code, then the start hint', async () => {+ const root = tempRoot()+ seedSession(root)+ const { fp } = seedIdentity(root)+ const { base } = await fakeBackend({ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }) })+ const result = await runAsync(root, ['login'], base)+ expect(result.status).toBe(0)+ expect(result.stdout).toContain(` ✓ Already signed in — this machine is "${hostname().slice(0, 60)}" · ${fp}\n Run \`harness start\` to connect this computer.`)+ })})diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex bc2c8cb81..f012aa380 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -233,7 +233,8 @@ import {import type { CableAgent } from './cable/cableSession.js'import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'-import { E2eeStore } from './lib/e2ee/store.js'+import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'+import { confirmsRemoval, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceList, logOrder, removeConfirmation } from './lib/e2ee/deviceDisplay.js'import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'import { b64e } from './lib/e2ee/core.js'import { MachinePeerStore } from './lib/e2ee/machinePeers.js'@@ -489,7 +490,9 @@ every future connect, until you change or clear it:harness group remove <id> drop a member (machine id, # or fingerprint) from every memberharness devices list the account's devices — signing in on one is what makes the others trustit; a device you do not recognise is someone else signed in as you- harness devices remove <fp> take a device (# or fingerprint) out of the account on every device+ harness devices show <#|fp> one device in full: its key code and how to check it on that device+ harness devices remove <fp> take a device out of the account on every device, by key code (or its+ first 4+ characters); a # or a shorter start asks first, --yes skips itharness devices rebaseline the device list froze (the backend served one that does not match whatthis machine verified): show what changed, --yes to trust it again(both \`remote-password set\` and \`link connect\` prompt for the password interactively, or read one@@ -688,6 +691,19 @@ async function resolveComputerMachine(signal?: AbortSignal): Promise<AuthSessionreturn next}+/** The name this machine goes by in the account's device list — what the daemon registers itself as. */+const thisDeviceLabel = (): string => hostname().slice(0, 60)++/** This machine's device key code. Signing in is what puts the key into the account, so `create` makes+ * the identity when it is missing; the read-only commands (`status`, `auth status`) only look, and+ * show nothing rather than mint a key. Null whenever it cannot be had. */+function thisDeviceFingerprint(create: boolean): string | null {+ try {+ const pub = create ? b64e(new E2eeStore().init().pub) : peekIdentityPub()+ return pub ? e2eeCoreFingerprint(e2eeCoreDecode(pub)) : null+ } catch { return null }+}+/** `harness auth status --json` — one JSON line, always exit 0; logged-out is a valid answer, not a* process failure. Reuses AuthSessionManager.accessToken() (not a raw file read) so a session that's* on-disk-but-about-to-expire gets refreshed here rather than reporting loggedIn:true and 401ing on@@ -716,6 +732,7 @@ async function authStatusCommand(json: boolean): Promise<void> {}const latest = readAuthSession()const signedIn = loggedIn && latest !== null+ const fingerprintNow = thisDeviceFingerprint(false)const payload = {loggedIn: signedIn,...(signedIn && offline ? { offline: true } : {}),@@ -724,6 +741,8 @@ async function authStatusCommand(json: boolean): Promise<void> {autonomousEnv: latest?.autonomousEnv,expiresAt: latest?.expiresAt,method: latest?.method ?? 'sso',+ // Read-only: a machine that has not signed in yet has no key, and asking must not make one.+ ...(fingerprintNow ? { fingerprint: fingerprintNow } : {}),}if (json) console.log(JSON.stringify(payload))else {@@ -813,9 +832,17 @@ async function loginCommand(// browser — and never as a side effect of signing in to Harness.const succeed = async (alreadySignedIn: boolean, email?: string): Promise<SignInOutcome> => {if (opts.chained) return { signedIn: true, alreadySignedIn }- if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true } : { type: 'result', status: 'success', ...(email ? { email } : {}) })- else if (alreadySignedIn) console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')- else console.log(`\n ✓ Signed in${email ? ` as ${email}` : ''}. Run \`harness start\` to connect this computer.\n`)+ // The key code is what the person compares on their other devices, so it is said at the moment the+ // machine joins them. Left out when it cannot be computed: the line is then exactly what it was.+ const fp = thisDeviceFingerprint(true)+ const device = fp ? ` · ${fp}` : ''+ if (json) emit(alreadySignedIn ? { type: 'result', status: 'success', alreadySignedIn: true, ...(fp ? { fingerprint: fp } : {}) } : { type: 'result', status: 'success', ...(email ? { email } : {}), ...(fp ? { fingerprint: fp } : {}) })+ else {+ const hint = ' Run `harness start` to connect this computer.'+ if (!fp) console.log(alreadySignedIn ? '\n ✓ Already signed in. Run `harness start` to connect this computer.\n' : `\n ✓ Signed in${email ? ` as ${email}` : ''}. Run \`harness start\` to connect this computer.\n`)+ else if (alreadySignedIn) console.log(`\n ✓ Already signed in — this machine is "${thisDeviceLabel()}"${device}\n${hint}\n`)+ else console.log(`\n ✓ Signed in${email ? ` as ${email}` : ''} — this machine joins your devices as "${thisDeviceLabel()}"${device}\n${hint}\n`)+ }return { signedIn: true, alreadySignedIn }}// SSO in the browser, or a QR the phone scans. Asked only of a person at a terminal with no flag; a@@ -4597,7 +4624,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {devLogSyncer = new DeviceLogSyncer({store: new DeviceLogStore(),identity: () => { const id = relayIdentityStore.getIdentity(); return { pub: b64e(id.pub), priv: id.priv } },- self: () => ({ machineId: readAuthSession()?.machineId ?? null, label: hostname().slice(0, 60) }),+ self: () => ({ machineId: readAuthSession()?.machineId ?? null, label: thisDeviceLabel() }),fetch: async (since) => {const r = await proxyBackend('GET', `/api/device-keys?since=${since}`)const data = r.status === 200 ? r.body.data as Partial<DeviceLogFetched> | undefined : undefined@@ -7425,6 +7452,8 @@ async function runningDaemonVersion(): Promise<string> {// "● connected", never a one-shot never-updating "connecting…"); `status` prints running/stopped.function printInfoBlock(opts: {status: string; pid: number; machineId?: string; sessions: number; version: string+ /** The `device` row's text (this machine's key code and whether the account holds it); only `status` shows it. */+ device?: string}): void {const row = (k: string, v: string): string => ` ${k.padEnd(10)} ${v}`const rule = ' ' + '─'.repeat(37)@@ -7437,6 +7466,7 @@ function printInfoBlock(opts: {try { return readFileSync(MACHINE_NAME_FILE, 'utf-8').trim() } catch { return '' }})()if (machineName) console.log(row('machine', machineName))+ if (opts.device) console.log(row('device', opts.device))console.log(row('version', `v${opts.version}`))console.log(row('backend', readAuthSession() ? env.BACKEND_WS_URL : 'not signed in · harness login'))console.log(row('agents', `${opts.sessions} available`))@@ -8157,7 +8187,7 @@ async function groupCommand(sub: string | undefined, arg: string | undefined, jsprocess.exit(1)}-/** `harness devices list|remove|rebaseline` — the account's device key log, as this machine verified it. */+/** `harness devices list|show|remove|rebaseline` — the account's device key log, as this machine verified it. */async function devicesCommand(sub: string | undefined, arg: string | undefined, flags: string[]): Promise<void> {const json = flags.includes('--json')const call = async (method: 'GET' | 'POST', path: string, body?: unknown): Promise<{ status: number; json: Record<string, unknown> }> => {@@ -8169,7 +8199,7 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,process.exit(1)}}- type Row = { pub: string; label: string; kind: string; machineId: string; addedAt: number; fingerprint: string; self: boolean }+ type Row = { pub: string; label: string; kind: string; machineId: string; addedAt: number; fingerprint: string; self: boolean; seq?: number; firstSeen?: number }const listing = async (): Promise<{ members: Row[]; frozen: { reason: string } | null; frozenPeers: string[]; lastSeen?: Record<string, number> }> => {const { status, json: out } = await call('GET', '/api/devices')if (status !== 200) { console.error('\n ✗ The device list is not available (is this machine signed in?).\n'); process.exit(1) }@@ -8180,25 +8210,61 @@ async function devicesCommand(sub: string | undefined, arg: string | undefined,if (json) { console.log(JSON.stringify(out)); process.exit(0) }if (out.frozen) console.log(`\n ⚠ FROZEN (${out.frozen.reason}): the backend served a device list that does not match what this machine verified. No device is added until you review it: harness devices rebaseline`)if (out.frozenPeers.length) console.log(`\n ⚠ Frozen on: ${out.frozenPeers.join(', ')}`)- console.log('\n Devices on this account — each one trusts every other:\n')- out.members.forEach((m, i) => {- const what = m.kind === 'machine' ? `machine ${m.machineId.slice(0, 8)}` : 'app'- const seen = out.lastSeen?.[m.pub]- console.log(` ${String(i + 1).padStart(2)}. ${m.label || '(no name)'} ${what} ${m.fingerprint} added ${new Date(m.addedAt).toLocaleString()}`- + `${seen ? ` last seen ${new Date(seen).toLocaleDateString()}` : ''}${m.self ? ' (this machine)' : ''}`)- })- console.log('\n Not yours? harness devices remove <#|fingerprint>\n')+ // This machine's own code is shown even before the log holds it, from the key on disk (read-only).+ const pub = peekIdentityPub()+ const selfFp = pub ? thisDeviceFingerprint(false) : null+ for (const line of formatDeviceList(out, Date.now(), selfFp ? { label: thisDeviceLabel(), fp: selfFp } : undefined)) console.log(line)process.exit(0)}- if (sub === 'remove') {- if (!arg) { console.error('Usage: harness devices remove <#|fingerprint> (see: harness devices list)'); process.exit(1) }- const { members } = await listing()+ // A device by its number in the list (its place in the log, which `list` prints on each row and+ // which only shifts when a device is removed) or by the start of its fingerprint; `show` and+ // `remove` resolve it the same way. The number is NOT the display position: that moves with activity.+ //+ // An all-digit argument is a list number, never a key-code prefix, unless it has 4 or more digits and+ // names no device in the list: then it is the start of a key code ("1111·2222" typed as 1111). A short+ // number out of range is an error rather than a prefix match, because `remove` cannot be undone and+ // `remove 4` must not take out whichever device's key code happens to start with 4.+ // Decided on the selector as matched (spaces and separators dropped), so " 1" is #1 and not the+ // key code starting with 1. `key` is what `remove` echoes when it is a number.+ const resolve = (arg: string, members: Row[]): { row: Row; byNumber: boolean; key: string } => {const norm = (v: string): string => v.toUpperCase().replace(/[·\s-]/g, '')- const byIndex = /^\d+$/.test(arg) ? members[Number(arg) - 1] : undefined- const matches = byIndex ? [byIndex] : members.filter((m) => norm(m.fingerprint).startsWith(norm(arg)))+ const key = norm(arg)+ // Only spaces and separators: an empty prefix would match every device.+ if (key === '') { console.error('Usage: harness devices show|remove <#|fingerprint> (see: harness devices list)'); process.exit(1) }+ const ordered = logOrder(members)+ if (/^\d+$/.test(key)) {+ const byIndex = ordered[Number(key) - 1]+ if (byIndex) return { row: byIndex, byNumber: true, key }+ if (key.length < 4) { console.error(`\n ✗ No device #${key} (see: harness devices list)\n`); process.exit(1) }+ }+ const matches = ordered.filter((m) => norm(m.fingerprint).startsWith(key))if (matches.length !== 1) { console.error(`\n ✗ ${matches.length ? 'More than one device matches' : 'No device matches'} "${arg}".\n`); process.exit(1) }- const target = matches[0]+ return { row: matches[0], byNumber: false, key }+ }+ if (sub === 'show') {+ if (!arg) { console.error('Usage: harness devices show|remove <#|fingerprint> (see: harness devices list)'); process.exit(1) }+ const { members, lastSeen } = await listing()+ const { row: target } = resolve(arg, members)+ if (json) { console.log(JSON.stringify({ ...target, lastSeen: lastSeen?.[target.pub] })); process.exit(0) }+ for (const line of formatDeviceDetail(target, lastSeen?.[target.pub], Date.now())) console.log(line)+ process.exit(0)+ }+ if (sub === 'remove') {+ if (!arg) { console.error('Usage: harness devices show|remove <#|fingerprint> (see: harness devices list)'); process.exit(1) }+ const { members } = await listing()+ const { row: target, byNumber, key } = resolve(arg, members)if (target.self) { console.error('\n ✗ That is this machine. Sign out with: harness logout\n'); process.exit(1) }+ // A number or a short (under 4) key-code start is echoed and confirmed first (see removeConfirmation);+ // a longer start of the key code needs no echo.+ const confirm = removeConfirmation({ byNumber, key }, { yes: flags.includes('--yes'), interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY) })+ if (confirm === 'refuse') {+ console.error(`\n ✗ Not removing "${arg}" without a terminal to confirm. Use the key code instead: harness devices remove ${target.fingerprint}\n`)+ process.exit(1)+ }+ if (confirm === 'ask') {+ const answer = await askLine(`\n Remove "${target.label || '(no name)'}" ${target.fingerprint}? It is signed out and its key is spent. [y/N] `)+ if (!confirmsRemoval(answer)) { console.log('\n Cancelled — nothing removed.\n'); process.exit(0) }+ }const { status, json: out } = await call('POST', '/api/devices/remove', { pub: target.pub })if (status !== 200) { console.error(`\n ✗ Could not remove ${target.label}: ${String(out.error ?? status)}${out.detail ? ` (${String(out.detail)})` : ''}\n`); process.exit(1) }console.log(`\n ✓ Removed ${target.label}. Every device stops trusting it; it is signed out.\n`)@@ -8376,6 +8442,20 @@ async function status(): Promise<void> {sessions: daemonStatus?.sessions ?? 0,// A stopped daemon answers nothing, so this falls back to the local build — which is what will run.version: daemonStatus?.version ?? VERSION,+ // Read from disk, not the daemon: it answers the same with the daemon stopped.+ // Signed out, devlog.json is the last account's copy: claiming membership from it would be wrong.+ // It is left on disk at logout on purpose: clearing it would drop the freeze and the rollback+ // protection with it. The stale window is after signing in again, possibly to a different account:+ // devlog.json still holds the previous account's log until the devlog syncer replaces it, so+ // `status` can say "(in your account)" from it for a while; that window is accepted.+ // A retired key with none in its place still says something, though: being removed from the+ // account is itself what signs a machine out (the daemon clears the session as it spends the key).+ device: deviceStatusValue(+ thisDeviceFingerprint(false),+ session+ ? deviceRegistration(peekIdentityPub(), new DeviceLogStore().read(), identitySpent())+ : !peekIdentityPub() && identitySpent() ? 'removed' : null,+ ) ?? undefined,})process.exit(0)}diff --git a/cli/src/devicesCommand.spec.ts b/cli/src/devicesCommand.spec.tsnew file mode 100644index 000000000..5b994f0d0--- /dev/null+++ b/cli/src/devicesCommand.spec.ts@@ -0,0 +1,338 @@+import { execFileSync, spawn, spawnSync } from 'child_process'+import { createServer, type Server } from 'http'+import { createWriteStream, mkdtempSync, rmSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { fileURLToPath } from 'url'+import { afterEach, describe, expect, it } from 'vitest'++const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))+const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')+const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')+const DAY = 86_400_000+const dirs: string[] = []+const servers: Server[] = []++afterEach(async () => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ for (const server of servers.splice(0)) {+ server.closeAllConnections?.()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+})++// Log order is deliberately not the display order: `old` was added first, this machine second, the+// new app last. The `#` printed on each row is its log position, so it survives the display re-sorting.+const now = Date.now()+const MEMBERS = [+ { pub: 'pub-old', kind: 'machine', machineId: 'm_old0000000', label: 'old-box', addedAt: now - 90 * DAY, seq: 1, fingerprint: 'AAAA·BBBB·CCCC·DDDD', self: false },+ { pub: 'pub-self', kind: 'machine', machineId: 'm_self000000', label: 'mbp', addedAt: now - 100 * DAY, seq: 2, fingerprint: 'E2FB·0DF5·5FD8·E6C7', self: true },+ { pub: 'pub-new', kind: 'viewer', machineId: '', label: 'phone', addedAt: now - 2 * DAY, seq: 3, firstSeen: now - 2 * DAY, fingerprint: '1111·2222·3333·4444', self: false },+]++/** A daemon that answers the two device routes `harness devices` calls; records each removal. */+function fakeDaemon(lastSeen: Record<string, number> = { 'pub-old': now - 3 * DAY }, members: typeof MEMBERS = MEMBERS): Promise<{ port: number; removed: string[] }> {+ const removed: string[] = []+ return new Promise((resolve) => {+ const server = createServer((req, res) => {+ let raw = ''+ req.on('data', (c) => { raw += c })+ req.on('end', () => {+ res.writeHead(200, { 'content-type': 'application/json' })+ if (req.method === 'GET' && req.url === '/api/devices') {+ res.end(JSON.stringify({ head: null, frozen: null, self: 'pub-self', members, frozenPeers: [], lastSeen }))+ } else if (req.method === 'POST' && req.url === '/api/devices/remove') {+ removed.push((JSON.parse(raw) as { pub: string }).pub)+ res.end(JSON.stringify({ ok: true }))+ } else {+ res.writeHead(404)+ res.end('{}')+ }+ })+ })+ servers.push(server)+ server.listen(0, '127.0.0.1', () => {+ const address = server.address()+ resolve({ port: typeof address === 'object' && address ? address.port : 0, removed })+ })+ })+}++function cliEnv(port: number): NodeJS.ProcessEnv {+ const root = mkdtempSync(join(tmpdir(), 'harness-cli-devices-'))+ dirs.push(root)+ return {+ ...process.env,+ HOME: root,+ HARNESS_AUTH_DIR: join(root, 'auth'),+ ADAPTER_DATA_DIR: join(root, 'data'),+ ADAPTER_RUNTIME_DIR: join(root, 'runtime'),+ ADAPTER_CLI_DIR: join(root, 'cli'),+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_UPDATE_DISABLE: 'true',+ PORT: String(port),+ }+}++function run(port: number, args: string[]): Promise<{ status: number | null; stdout: string; stderr: string }> {+ return new Promise((resolve) => {+ const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'devices', ...args], { cwd: CLI_ROOT, env: cliEnv(port) })+ let stdout = ''+ let stderr = ''+ child.stdout.on('data', (c: Buffer) => { stdout += c.toString() })+ child.stderr.on('data', (c: Buffer) => { stderr += c.toString() })+ child.once('close', (status) => resolve({ status, stdout, stderr }))+ })+}++const quote = (v: string): string => `'${v.replace(/'/g, `'\\''`)}'`+/** `script(1)` gives the CLI a terminal (stdin and stdout both a TTY) without node-pty. BSD and+ * util-linux spell it differently; anything else skips the terminal tests. */+const HAS_SCRIPT = (process.platform === 'darwin' || process.platform === 'linux') && spawnSync('sh', ['-c', 'command -v script && command -v mkfifo'], { stdio: 'ignore' }).status === 0++/** Run `harness devices …` at a terminal and, once it asks `[y/N]`, type `answer` + Enter — after the+ * question, as a person would. `pipeOut` sends its stdout to a pipe, so only stdin is a terminal.+ * Returns everything the terminal showed. */+function runAtTerminal(port: number, args: string[], answer: string, pipeOut = false): Promise<{ status: number | null; screen: string }> {+ const cmd = [process.execPath, TSX, CLI_SOURCE, 'devices', ...args].map(quote).join(' ') + (pipeOut ? ' | cat; exit "${PIPESTATUS[0]:-$?}"' : '')+ const shell = pipeOut ? `bash -c ${quote(cmd)}` : cmd+ // The keyboard is a FIFO piped in by cat: BSD script refuses a socket or a FIFO as stdin, not a pipe.+ const dir = mkdtempSync(join(tmpdir(), 'harness-cli-tty-'))+ dirs.push(dir)+ const keyboard = join(dir, 'keyboard')+ execFileSync('mkfifo', [keyboard])+ const script = process.platform === 'darwin' ? `script -q /dev/null sh -c ${quote(shell)}` : `script -qec ${quote(shell)} /dev/null`+ return new Promise((resolve) => {+ const child = spawn('sh', ['-c', `cat ${quote(keyboard)} | ${script}`], { cwd: CLI_ROOT, env: cliEnv(port), stdio: ['ignore', 'pipe', 'pipe'] })+ const keys = createWriteStream(keyboard)+ keys.on('error', () => {})+ // With stdout piped no question may appear: nothing to wait for, so the keyboard just closes.+ if (pipeOut) keys.end()+ let screen = ''+ let typed = false+ const seen = (c: Buffer): void => {+ screen += c.toString()+ if (!typed && !pipeOut && screen.includes('[y/N]')) { typed = true; keys.end(`${answer}\n`) }+ }+ child.stdout.on('data', seen)+ child.stderr.on('data', seen)+ child.once('close', (status) => { keys.destroy(); resolve({ status, screen: screen.replace(/\r/g, '') }) })+ })+}++describe('harness devices', () => {+ it('lists this machine, then the new device, then the rest, each row keeping its log-order number', async () => {+ const { port } = await fakeDaemon()+ const { status, stdout } = await run(port, ['list'])+ expect(status).toBe(0)+ expect(stdout).toContain('This machine: mbp E2FB·0DF5·5FD8·E6C7')+ const rows = stdout.split('\n').filter((l) => /^\s+\d+\. /.test(l))+ expect(rows).toEqual([+ ' 2. mbp computer m_self00 E2FB·0DF5·5FD8·E6C7 added 3 months ago (this machine)',+ ' 3. phone app 1111·2222·3333·4444 added 2 days ago new',+ ' 1. old-box computer m_old000 AAAA·BBBB·CCCC·DDDD last active 3 days ago',+ ])+ expect(stdout).toContain('harness devices remove <fingerprint>')+ expect(stdout).not.toMatch(/\d{4}-\d{2}-\d{2}/)+ }, 20_000)++ it('numbers do not move when activity reorders the display', async () => {+ // The unknown laptop opening a session must not hand its number to another device.+ const { port } = await fakeDaemon({ 'pub-old': now - 1000, 'pub-new': now - 2000 })+ const { stdout } = await run(port, ['list'])+ const rows = stdout.split('\n').filter((l) => /^\s+\d+\. /.test(l)).map((l) => l.trim().split(' ')[0])+ expect(rows.slice().sort()).toEqual(['1. old-box', '2. mbp', '3. phone'])+ const shown = await run(port, ['show', '1'])+ expect(shown.stdout).toContain('old-box')+ }, 20_000)++ it('show resolves the number the list prints; remove by number needs --yes without a terminal', async () => {+ const daemon = await fakeDaemon()+ const shown = await run(daemon.port, ['show', '1'])+ expect(shown.status).toBe(0)+ expect(shown.stdout).toContain('old-box')+ expect(shown.stdout).toContain('key code AAAA·BBBB·CCCC·DDDD')+ expect(shown.stdout).toContain('Not yours? harness devices remove AAAA·BBBB·CCCC·DDDD')+ const refused = await run(daemon.port, ['remove', '1'])+ expect(refused.status).toBe(1)+ expect(refused.stderr).toContain('without a terminal to confirm')+ expect(refused.stderr).toContain('harness devices remove AAAA·BBBB·CCCC·DDDD')+ expect(daemon.removed).toEqual([])+ const removed = await run(daemon.port, ['remove', '1', '--yes'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-old'])+ }, 30_000)++ it('remove by key code needs no confirmation and hits exactly that device', async () => {+ const daemon = await fakeDaemon()+ const removed = await run(daemon.port, ['remove', '1111·2222'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-new'])+ }, 20_000)++ it('show by fingerprint prefix, and --json adds lastSeen', async () => {+ const { port } = await fakeDaemon()+ const { status, stdout } = await run(port, ['show', 'aaaa-bb', '--json'])+ expect(status).toBe(0)+ expect(JSON.parse(stdout.trim())).toEqual({ ...MEMBERS[0], lastSeen: now - 3 * DAY })+ }, 20_000)++ it('a number past the end of the list is an error, never a key-code prefix; nothing is removed', async () => {+ // 4 is out of range with 3 devices; no key code here starts with 4, but 1 and 2 would if numbers fell through.+ const daemon = await fakeDaemon()+ for (const n of ['4', '9', '12']) {+ const shown = await run(daemon.port, ['show', n])+ expect(shown.status).toBe(1)+ expect(shown.stderr).toContain(`No device #${n} (see: harness devices list)`)+ const removed = await run(daemon.port, ['remove', n, '--yes'])+ expect(removed.status).toBe(1)+ expect(removed.stderr).toContain(`No device #${n} (see: harness devices list)`)+ }+ expect(daemon.removed).toEqual([])+ }, 60_000)++ it('an in-range number still resolves; a 4+ digit key-code prefix out of range still matches by key code', async () => {+ const daemon = await fakeDaemon()+ const three = await run(daemon.port, ['show', '3'])+ expect(three.status).toBe(0)+ expect(three.stdout).toContain('phone')+ const shown = await run(daemon.port, ['show', '1111'])+ expect(shown.status).toBe(0)+ expect(shown.stdout).toContain('phone')+ // Matched by key code, so no number to echo: it removes without --yes or a terminal.+ const removed = await run(daemon.port, ['remove', '1111'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-new'])+ }, 40_000)++ it('a short number with stray spaces or separators is still a list number, never a key-code prefix', async () => {+ // " 1" stripped to "1" would prefix-match phone (1111·…); it must name #1 (old-box) and be confirmed.+ const daemon = await fakeDaemon()+ const shown = await run(daemon.port, ['show', ' 1'])+ expect(shown.status).toBe(0)+ expect(shown.stdout).toContain('old-box')+ expect((await run(daemon.port, ['show', '03 '])).stdout).toContain('phone')+ const refused = await run(daemon.port, ['remove', '1 '])+ expect(refused.status).toBe(1)+ expect(refused.stderr).toContain('without a terminal to confirm')+ for (const n of [' 4', '0', '00']) {+ const out = await run(daemon.port, ['remove', n, '--yes'])+ expect(out.status).toBe(1)+ expect(out.stderr).toContain(`No device #${n.trim()} (see: harness devices list)`)+ }+ expect(daemon.removed).toEqual([])+ const removed = await run(daemon.port, ['remove', ' 1', '--yes'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-old'])+ }, 60_000)++ it('a selector of only spaces or separators is a usage error for show and remove; nothing is removed', async () => {+ const daemon = await fakeDaemon()+ for (const sub of ['show', 'remove']) {+ for (const sel of [' ', '·', '· ', '-']) {+ const out = await run(daemon.port, sub === 'remove' ? [sub, sel, '--yes'] : [sub, sel])+ expect(out.status).toBe(1)+ expect(out.stderr).toContain('Usage: harness devices show|remove <#|fingerprint>')+ }+ }+ expect(daemon.removed).toEqual([])+ }, 60_000)++ it('a key-code start under 4 characters is confirmed like a number: refused without a terminal, --yes echoes and removes', async () => {+ const daemon = await fakeDaemon()+ for (const sel of ['a', 'AA', 'aaa']) {+ const refused = await run(daemon.port, ['remove', sel])+ expect(refused.status).toBe(1)+ expect(refused.stderr).toContain('without a terminal to confirm')+ expect(refused.stderr).toContain('harness devices remove AAAA·BBBB·CCCC·DDDD')+ }+ expect(daemon.removed).toEqual([])+ const removed = await run(daemon.port, ['remove', 'aa', '--yes'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-old'])+ }, 60_000)++ it('a key-code start of 4 or more characters still removes without --yes', async () => {+ const daemon = await fakeDaemon()+ const removed = await run(daemon.port, ['remove', 'aaaa'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-old'])+ }, 30_000)++ it('a letter key-code prefix works for show and remove', async () => {+ const daemon = await fakeDaemon()+ expect((await run(daemon.port, ['show', 'AAAA·B'])).stdout).toContain('old-box')+ expect((await run(daemon.port, ['remove', 'aaaabbbb'])).status).toBe(0)+ expect(daemon.removed).toEqual(['pub-old'])+ }, 30_000)++ it('a key-code prefix that matches more than one device is refused for show and remove, even with --yes', async () => {+ // A twin of old-box whose key code shares its first two groups: AAAA·BBBB names neither.+ const twin = { pub: 'pub-twin', kind: 'machine', machineId: 'm_twin00000', label: 'twin-box', addedAt: now - 50 * DAY, seq: 4, fingerprint: 'AAAA·BBBB·9999·0000', self: false }+ const daemon = await fakeDaemon(undefined, [...MEMBERS, twin])+ for (const sel of ['a', 'AAAA', 'aaaa-bbbb', 'AAAA·BBBB']) {+ const shown = await run(daemon.port, ['show', sel])+ expect(shown.status).toBe(1)+ expect(shown.stderr).toContain(`More than one device matches "${sel}"`)+ for (const args of [['remove', sel], ['remove', sel, '--yes']]) {+ const out = await run(daemon.port, args)+ expect(out.status).toBe(1)+ expect(out.stderr).toContain(`More than one device matches "${sel}"`)+ }+ }+ expect(daemon.removed).toEqual([])+ // One character more tells them apart.+ expect((await run(daemon.port, ['show', 'AAAA·BBBB·9'])).stdout).toContain('twin-box')+ const removed = await run(daemon.port, ['remove', 'AAAA·BBBB·9'])+ expect(removed.status).toBe(0)+ expect(daemon.removed).toEqual(['pub-twin'])+ }, 90_000)++ it('show on this machine says so', async () => {+ const { port } = await fakeDaemon()+ const { stdout } = await run(port, ['show', '2'])+ expect(stdout).toContain('mbp (this machine)')+ expect(stdout).toContain('This is this machine.')+ }, 20_000)++ it('an unknown or missing selector fails with the usual message', async () => {+ const { port } = await fakeDaemon()+ const none = await run(port, ['show', '9'])+ expect(none.status).toBe(1)+ expect(none.stderr).toContain('No device #9')+ const noPrefix = await run(port, ['show', 'ZZZZ'])+ expect(noPrefix.stderr).toContain('No device matches "ZZZZ"')+ const usage = await run(port, ['show'])+ expect(usage.status).toBe(1)+ expect(usage.stderr).toContain('Usage: harness devices show|remove <#|fingerprint>')+ }, 20_000)++ it.skipIf(!HAS_SCRIPT)('remove by number at a terminal names the device and removes it on y', async () => {+ const daemon = await fakeDaemon()+ const { status, screen } = await runAtTerminal(daemon.port, ['remove', '1'], 'y')+ expect(screen).toContain('Remove "old-box" AAAA·BBBB·CCCC·DDDD? It is signed out and its key is spent. [y/N]')+ expect(screen).toContain('Removed old-box')+ expect(status).toBe(0)+ expect(daemon.removed).toEqual(['pub-old'])+ }, 30_000)++ it.skipIf(!HAS_SCRIPT)('remove by number at a terminal removes nothing on anything but yes', async () => {+ const daemon = await fakeDaemon()+ const no = await runAtTerminal(daemon.port, ['remove', '3'], 'n')+ expect(no.screen).toContain('Remove "phone" 1111·2222·3333·4444?')+ expect(no.screen).toContain('Cancelled — nothing removed.')+ expect(no.status).toBe(0)+ const enter = await runAtTerminal(daemon.port, ['remove', '3'], '')+ expect(enter.screen).toContain('Cancelled — nothing removed.')+ expect(daemon.removed).toEqual([])+ }, 30_000)++ it.skipIf(!HAS_SCRIPT)('remove by number refuses when only stdin is a terminal (the question would not be seen)', async () => {+ const daemon = await fakeDaemon()+ const { status, screen } = await runAtTerminal(daemon.port, ['remove', '1'], 'y', true)+ expect(screen).toContain('without a terminal to confirm')+ expect(screen).not.toContain('[y/N]')+ expect(status).not.toBe(0)+ expect(daemon.removed).toEqual([])+ }, 30_000)+})diff --git a/cli/src/lib/e2ee/deviceDisplay.spec.ts b/cli/src/lib/e2ee/deviceDisplay.spec.tsnew file mode 100644index 000000000..d504e2199--- /dev/null+++ b/cli/src/lib/e2ee/deviceDisplay.spec.ts@@ -0,0 +1,219 @@+import { describe, expect, it } from 'vitest'+import {+ activityPhrase, COMPARE_HINT, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceList, fullDateTime, isNewDevice,+ confirmsRemoval, logOrder, orderDevices, relativeAgo, removeConfirmation, type DeviceRow,+} from './deviceDisplay.js'++const NOW = Date.UTC(2026, 9, 1, 12, 0, 0)+const MIN = 60_000+const H = 60 * MIN+const D = 24 * H++describe('relativeAgo', () => {+ const cases: Array<[number, string]> = [+ [0, 'just now'], [59_000, 'just now'], [MIN, '1 minute ago'], [59 * MIN, '59 minutes ago'],+ [H, '1 hour ago'], [23 * H, '23 hours ago'], [24 * H, 'yesterday'], [47 * H, 'yesterday'],+ [2 * D, '2 days ago'], [13 * D, '13 days ago'], [14 * D, '2 weeks ago'], [59 * D, '8 weeks ago'],+ [60 * D, '2 months ago'], [364 * D, '12 months ago'], [365 * D, 'over a year ago'], [-5 * MIN, 'just now'],+ ]+ it.each(cases)('%i ms ago reads %s', (ago, text) => expect(relativeAgo(NOW - ago, NOW)).toBe(text))+})++describe('fullDateTime', () => {+ it('spells the local date and 24-hour time', () => {+ expect(fullDateTime(new Date(2026, 9, 1, 14, 5).getTime())).toBe('1 Oct 2026, 14:05')+ })+})++describe('activityPhrase', () => {+ it('says active now, last active, or added', () => {+ expect(activityPhrase(NOW - MIN, NOW - D, NOW)).toBe('active now')+ expect(activityPhrase(NOW - 2 * D, NOW - 30 * D, NOW)).toBe('last active 2 days ago')+ expect(activityPhrase(undefined, NOW - 21 * D, NOW)).toBe('added 3 weeks ago')+ })+ it('stops reading active now at 5 minutes', () => {+ expect(activityPhrase(NOW - 5 * MIN + 1, NOW - D, NOW)).toBe('active now')+ expect(activityPhrase(NOW - 5 * MIN, NOW - D, NOW)).toBe('last active 5 minutes ago')+ })+})++const row = (pub: string, addedAt: number, over: Partial<DeviceRow> = {}): DeviceRow =>+ ({ pub, label: pub, kind: 'viewer', machineId: '', addedAt, fingerprint: pub, self: false, ...over })++describe('orderDevices / isNewDevice', () => {+ it('puts this machine, then new devices (newest log entry first), then the rest by activity; ties keep log order', () => {+ const rows = [+ row('old-a', NOW - 90 * D, { seq: 1 }), row('self', NOW - 100 * D, { self: true, seq: 2 }), row('new-1', NOW - 2 * D, { seq: 3, firstSeen: NOW - 2 * D }),+ row('old-b', NOW - 80 * D, { seq: 4 }), row('new-2', NOW - D, { seq: 5, firstSeen: NOW - D }), row('old-c', NOW - 90 * D, { seq: 6 }),+ ]+ const out = orderDevices(rows, { 'old-a': NOW - 10 * D }, NOW).map((r) => r.pub)+ expect(out).toEqual(['self', 'new-2', 'new-1', 'old-a', 'old-b', 'old-c'])+ })+ it('orders the rest by addedAt when never seen, and a fresh lastSeen lifts an old device', () => {+ const rows = [row('a', NOW - 300 * D), row('b', NOW - 200 * D), row('c', NOW - 100 * D)]+ expect(orderDevices(rows, undefined, NOW).map((r) => r.pub)).toEqual(['c', 'b', 'a'])+ expect(orderDevices(rows, { a: NOW - MIN }, NOW).map((r) => r.pub)).toEqual(['a', 'c', 'b'])+ })+ it('does not reorder the input array', () => {+ const rows = [row('a', NOW - 300 * D), row('b', NOW - D)]+ orderDevices(rows, undefined, NOW)+ expect(rows.map((r) => r.pub)).toEqual(['a', 'b'])+ })+ it('flags a non-self device this machine first saw under 7 days ago', () => {+ expect(isNewDevice(row('x', 0, { firstSeen: NOW - 7 * D + 1 }), NOW)).toBe(true)+ expect(isNewDevice(row('x', 0, { firstSeen: NOW - 7 * D }), NOW)).toBe(false)+ expect(isNewDevice(row('x', 0, { firstSeen: NOW - D, self: true }), NOW)).toBe(false)+ })+ it('does not let the adding device hide itself by backdating its entry', () => {+ // `addedAt` is the entry's own `at`; the flag and the new-group order must not read it.+ const rows = [row('old', NOW - 90 * D, { seq: 1 }), row('liar', NOW - 400 * D, { seq: 2, firstSeen: NOW - 60_000 })]+ expect(isNewDevice(rows[1], NOW)).toBe(true)+ expect(orderDevices(rows, { old: NOW - D }, NOW).map((r) => r.pub)).toEqual(['liar', 'old'])+ })+ it('flags nothing when the daemon sent no firstSeen, even for a just-added row', () => {+ expect(isNewDevice(row('x', NOW - 60_000), NOW)).toBe(false)+ })+})++describe('logOrder', () => {+ it('sorts by seq and keeps array order without one', () => {+ expect(logOrder([row('b', 0, { seq: 5 }), row('a', 0, { seq: 2 })]).map((r) => r.pub)).toEqual(['a', 'b'])+ expect(logOrder([row('b', 0), row('a', 0)]).map((r) => r.pub)).toEqual(['b', 'a'])+ })+ it('is unaffected by activity or newness, so a number keeps naming one device', () => {+ const rows = [row('p', NOW - 50 * D, { seq: 1 }), row('q', NOW - 40 * D, { seq: 2 })]+ const before = logOrder(rows).map((r) => r.pub)+ // q opens a session: the display order flips, the numbering does not.+ expect(orderDevices(rows, { q: NOW - MIN }, NOW).map((r) => r.pub)).toEqual(['q', 'p'])+ expect(logOrder(rows).map((r) => r.pub)).toEqual(before)+ })+})++describe('deviceRegistration', () => {+ const file = (active: string[], removed: string[]) => ({+ state: { active: Object.fromEntries(active.map((p) => [p, {}])), removed },+ recent: [], frozen: null, notifiedUpTo: 0,+ }) as never+ it('tells the three states and the spent identity apart', () => {+ expect(deviceRegistration('p', file(['p'], []), false)).toBe('active')+ expect(deviceRegistration('p', file([], ['p']), false)).toBe('removed')+ expect(deviceRegistration('p', file([], []), false)).toBe('unregistered')+ expect(deviceRegistration(null, file([], []), true)).toBe('removed')+ expect(deviceRegistration(null, file([], []), false)).toBeNull()+ })+ it('words the status value', () => {+ expect(deviceStatusValue('AAAA', 'active')).toBe('AAAA (in your account)')+ expect(deviceStatusValue(null, 'removed')).toBe('(removed — run harness login)')+ expect(deviceStatusValue(null, null)).toBeNull()+ })+})++const FP_SELF = 'E2FB·0DF5·5FD8·E6C7'+const FP_NEW = '1111·2222·3333·4444'+const FP_OLD = 'AAAA·BBBB·CCCC·DDDD'+const listing = () => ({+ members: [+ row('old', NOW - 90 * D, { seq: 1, label: 'old-mac', kind: 'machine', machineId: 'm_0123456789abcdef', fingerprint: FP_OLD }),+ row('self', NOW - 100 * D, { seq: 2, label: 'mbp', kind: 'machine', machineId: 'm_selfselfself', fingerprint: FP_SELF, self: true }),+ row('new', NOW - 2 * D, { seq: 3, firstSeen: NOW - 2 * D, label: '', fingerprint: FP_NEW }),+ ],+ lastSeen: { old: NOW - 3 * D, self: NOW - MIN },+})++describe('formatDeviceList', () => {+ it('shows self, new, rest in that order, each row keeping its stable log-order number', () => {+ const lines = formatDeviceList(listing(), NOW)+ expect(lines).toContain(` This machine: mbp ${FP_SELF}`)+ const rows = lines.filter((l) => /^\s+\d+\. /.test(l))+ expect(rows).toEqual([+ ` 2. mbp computer m_selfse ${FP_SELF} active now (this machine)`,+ ` 3. (no name) app ${FP_NEW} added 2 days ago new`,+ ` 1. old-mac computer m_012345 ${FP_OLD} last active 3 days ago`,+ ])+ expect(lines.join('\n')).toContain('harness devices show <#|fingerprint>')+ // Removal is offered by key code, which cannot drift the way a number can.+ expect(lines.join('\n')).toContain('harness devices remove <fingerprint>')+ expect(lines.join('\n')).not.toContain('remove <#')+ })+ it('never prints an ISO-style date', () => {+ expect(formatDeviceList(listing(), NOW).join('\n')).not.toMatch(/\d{4}-\d{2}-\d{2}/)+ })+ it('falls back to the identity on disk when the log has no row for this machine', () => {+ const l = listing()+ l.members = l.members.filter((m) => !m.self)+ const lines = formatDeviceList(l, NOW, { label: 'mbp', fp: FP_SELF })+ expect(lines).toContain(` This machine: mbp ${FP_SELF} (not registered yet)`)+ expect(lines.join('\n')).not.toContain('(this machine)')+ })+ it('prints no header at all without a self row or fallback', () => {+ const l = listing()+ l.members = l.members.filter((m) => !m.self)+ expect(formatDeviceList(l, NOW).join('\n')).not.toContain('This machine:')+ })+})++describe('formatDeviceDetail', () => {+ it('shows a computer in full, with the guidance and the remove hint', () => {+ const old = listing().members[0]+ const text = formatDeviceDetail(old, NOW - 3 * D, NOW).join('\n')+ expect(text).toContain('kind Computer')+ expect(text).toContain(`added ${fullDateTime(NOW - 90 * D)} (3 months ago)`)+ expect(text).toContain(`last active 3 days ago (${fullDateTime(NOW - 3 * D)})`)+ expect(text).toContain('machine m_012345')+ expect(text).toContain(`key code ${FP_OLD}`)+ expect(text).toContain(COMPARE_HINT)+ expect(text).toContain(`Not yours? harness devices remove ${FP_OLD}`)+ expect(text).not.toContain('This is this machine.')+ })+ it('shows an app without a machine row, and unknown activity', () => {+ const app = listing().members[2]+ const text = formatDeviceDetail(app, undefined, NOW).join('\n')+ expect(text).toContain('kind App')+ expect(text).toContain('last active unknown')+ expect(text).not.toContain('machine ')+ expect(text).toContain('(no name)')+ })+ it('says this is this machine instead of offering removal', () => {+ const self = listing().members[1]+ const text = formatDeviceDetail(self, NOW - MIN, NOW).join('\n')+ expect(text).toContain('mbp (this machine)')+ expect(text).toContain('This is this machine.')+ expect(text).not.toContain('Not yours?')+ expect(text).toContain(COMPARE_HINT)+ })+})++describe('removeConfirmation', () => {+ const num = (key: string) => ({ byNumber: true, key })+ const code = (key: string) => ({ byNumber: false, key })+ it('asks before removing by number at a terminal', () => {+ expect(removeConfirmation(num('2'), { yes: false, interactive: true })).toBe('ask')+ })+ it('refuses a number when nobody can see or answer the question', () => {+ expect(removeConfirmation(num('2'), { yes: false, interactive: false })).toBe('refuse')+ })+ it('goes ahead on a number or a short key-code start with --yes, terminal or not', () => {+ expect(removeConfirmation(num('2'), { yes: true, interactive: false })).toBe('go')+ expect(removeConfirmation(num('2'), { yes: true, interactive: true })).toBe('go')+ expect(removeConfirmation(code('1A'), { yes: true, interactive: false })).toBe('go')+ })+ it('treats a key-code start under 4 characters like a number', () => {+ expect(removeConfirmation(code('1A'), { yes: false, interactive: false })).toBe('refuse')+ expect(removeConfirmation(code('AAA'), { yes: false, interactive: true })).toBe('ask')+ })+ it('never asks for a key-code start of 4 or more characters, digits or not', () => {+ expect(removeConfirmation(code('AAAA'), { yes: false, interactive: false })).toBe('go')+ expect(removeConfirmation(code('E2FB0DF5'), { yes: false, interactive: false })).toBe('go')+ expect(removeConfirmation(code('12AB'), { yes: false, interactive: true })).toBe('go')+ expect(removeConfirmation(code('1111'), { yes: false, interactive: false })).toBe('go')+ })+ it('a list number is confirmed however many digits it has', () => {+ expect(removeConfirmation(num('1111'), { yes: false, interactive: false })).toBe('refuse')+ expect(removeConfirmation(num('1111'), { yes: false, interactive: true })).toBe('ask')+ })+})++describe('confirmsRemoval', () => {+ it.each(['y', 'Y', 'yes', 'YES', ' y ', 'yes\n'])('%j removes', (a) => expect(confirmsRemoval(a)).toBe(true))+ it.each(['', 'n', 'no', 'yep', 'sure', 'y y', '\n'])('%j does not', (a) => expect(confirmsRemoval(a)).toBe(false))+})diff --git a/cli/src/lib/e2ee/deviceDisplay.ts b/cli/src/lib/e2ee/deviceDisplay.tsnew file mode 100644index 000000000..d059c16db--- /dev/null+++ b/cli/src/lib/e2ee/deviceDisplay.ts@@ -0,0 +1,160 @@+/**+ * How `harness` shows the account's devices: the order, the "last active" wording, and the lines of+ * `devices list|show` and the `status` row. Pure — the clock is passed in — so the same rules the+ * desktop and mobile apps follow (their `relative_time.dart`) are pinned by one spec here.+ */+import type { DevLogFile } from './deviceLogStore.js'+import type { DeviceLogListing } from './deviceLogSyncer.js'++/** The fields of a listing row this module reads. `seq` (log position) and `firstSeen` (when this+ * machine first applied the add) are the two a device cannot choose for itself; both optional so a+ * daemon that predates them still lists, just without `new`. */+export type DeviceRow = Pick<DeviceLogListing['members'][number], 'pub' | 'label' | 'machineId' | 'addedAt' | 'fingerprint' | 'self'> & {+ kind: string+ seq?: number+ firstSeen?: number+}++const MIN = 60_000+const HOUR = 60 * MIN+const DAY = 24 * HOUR+/** A device seen this recently reads as "active now" rather than "5 minutes ago". */+const ACTIVE_NOW_MS = 5 * MIN+/** A device this machine first learned of this recently, that is not this machine, is flagged `new`. */+const NEW_DEVICE_MS = 7 * DAY++const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']++/** What to do to check a device's key code. Shown under `devices show`. */+export const COMPARE_HINT =+ 'To check it is really that device: open Your devices on it — the code under "This device" must match. On a computer, `harness status` shows it too.'++const plural = (n: number, unit: string): string => `${n} ${unit}${n === 1 ? '' : 's'} ago`++/** "2 days ago". Coarse on purpose: the person is deciding "do I recognise this", not auditing a log. */+export function relativeAgo(at: number, now: number): string {+ const d = Math.max(0, now - at)+ if (d < MIN) return 'just now'+ if (d < HOUR) return plural(Math.floor(d / MIN), 'minute')+ if (d < DAY) return plural(Math.floor(d / HOUR), 'hour')+ if (d < 2 * DAY) return 'yesterday'+ const days = Math.floor(d / DAY)+ if (days < 14) return `${days} days ago`+ if (days < 60) return `${Math.floor(days / 7)} weeks ago`+ if (days < 365) return `${Math.floor(days / 30)} months ago`+ return 'over a year ago'+}++/** `1 Oct 2026, 14:05` in local time — spelled out so it reads the same in every locale. */+export function fullDateTime(at: number): string {+ const d = new Date(at)+ const pad = (n: number): string => String(n).padStart(2, '0')+ return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}, ${pad(d.getHours())}:${pad(d.getMinutes())}`+}++/** `active now` / `last active 2 days ago` / `added 3 weeks ago` (no session ever recorded for it). */+export function activityPhrase(lastSeen: number | undefined, addedAt: number, now: number): string {+ if (lastSeen === undefined) return `added ${relativeAgo(addedAt, now)}`+ return now - lastSeen < ACTIVE_NOW_MS ? 'active now' : `last active ${relativeAgo(lastSeen, now)}`+}++/** `new` rests on when THIS machine applied the add, never the entry's `at`: the adding device picks+ * that itself, and a backdated one would hide exactly the device the flag is for. */+export function isNewDevice(row: Pick<DeviceRow, 'self' | 'firstSeen'>, now: number): boolean {+ return !row.self && row.firstSeen !== undefined && now - row.firstSeen < NEW_DEVICE_MS+}++/** Log order — the order devices were added, which only shifts when one is removed. The `#` of+ * `list`, `show` and `remove` is the position here, so a number read from the list still names that+ * device when activity reorders the display or a device is added before the person types it. */+export function logOrder<T extends DeviceRow>(members: T[]): T[] {+ return members.map((m, i) => ({ m, i })).sort((a, b) => (a.m.seq ?? a.i) - (b.m.seq ?? b.i) || a.i - b.i).map((x) => x.m)+}++/** This machine first, then the new ones (newest log entry first), then the rest by last activity.+ * Ties keep log order. Display only — numbering is `logOrder`. */+export function orderDevices<T extends DeviceRow>(members: T[], lastSeen: Record<string, number> | undefined, now: number): T[] {+ const indexed = logOrder(members).map((m, i) => ({ m, i }))+ const rank = (m: T): number => (m.self ? 0 : isNewDevice(m, now) ? 1 : 2)+ // The log position is the unforgeable "when" for the new group; activity (else the add date) for the rest.+ const when = (x: { m: T; i: number }): number => (rank(x.m) === 2 ? lastSeen?.[x.m.pub] ?? x.m.addedAt : x.i)+ indexed.sort((a, b) => rank(a.m) - rank(b.m) || when(b) - when(a) || a.i - b.i)+ return indexed.map((x) => x.m)+}++/** Whether `devices remove` goes ahead, asks first, or refuses, given how the selector resolved:+ * `byNumber` when it named a list number, else `key` is the key-code start it matched (normalised:+ * upper case, no spaces or separators). A number is a guess about what the person last read, and a+ * removal cannot be undone (the key is spent): it is echoed and confirmed at a terminal, and without+ * one it needs `--yes`. A key-code start of 4 or more characters names the device and needs neither,+ * digits or not ("1111" that is not a list number is the start of 1111·…); one under 4 ("1A") is as+ * much a guess as a number and is treated like it.+ * `interactive` means someone can both see the question and answer it (stdin AND stdout a TTY). */+export function removeConfirmation(+ sel: { byNumber: boolean; key: string },+ opts: { yes: boolean; interactive: boolean },+): 'go' | 'ask' | 'refuse' {+ if (opts.yes || (!sel.byNumber && sel.key.length >= 4)) return 'go'+ return opts.interactive ? 'ask' : 'refuse'+}++/** The answer to `remove`'s `[y/N]`: only an explicit yes removes. */+export const confirmsRemoval = (answer: string): boolean => /^y(es)?$/i.test(answer.trim())++export type DeviceRegistration = 'active' | 'removed' | 'unregistered'++/** Whether the account's device log holds this machine's key. No key on disk but a retired one means+ * this machine was signed out of the account; neither means there is nothing to say. */+export function deviceRegistration(pub: string | null, file: DevLogFile, spent: boolean): DeviceRegistration | null {+ if (!pub) return spent ? 'removed' : null+ if (file.state?.active[pub]) return 'active'+ if (file.state?.removed.includes(pub)) return 'removed'+ return 'unregistered'+}++/** The text after `device ` in `harness status`, or null for no row. */+export function deviceStatusValue(fp: string | null, reg: DeviceRegistration | null): string | null {+ if (!reg) return null+ const note = reg === 'active' ? 'in your account' : reg === 'removed' ? 'removed — run harness login' : 'not registered yet'+ return fp ? `${fp} (${note})` : `(${note})`+}++const nameOf = (row: Pick<DeviceRow, 'label'>): string => row.label || '(no name)'+const kindOf = (row: Pick<DeviceRow, 'kind' | 'machineId'>): string => (row.kind === 'machine' ? `computer ${row.machineId.slice(0, 8)}` : 'app')++/** The lines of `harness devices list`: shown in `orderDevices` order, each row keeping its `logOrder`+ * number. `selfFallback` is this machine's own+ * key code for when the log has no row for it yet. */+export function formatDeviceList(+ listing: { members: DeviceRow[]; lastSeen?: Record<string, number> },+ now: number,+ selfFallback?: { label: string; fp: string },+): string[] {+ const numbers = new Map(logOrder(listing.members).map((m, i) => [m.pub, i + 1]))+ const rows = orderDevices(listing.members, listing.lastSeen, now)+ const lines: string[] = ['']+ const self = rows.find((r) => r.self)+ if (self) lines.push(` This machine: ${nameOf(self)} ${self.fingerprint}`, '')+ else if (selfFallback) lines.push(` This machine: ${selfFallback.label} ${selfFallback.fp} (not registered yet)`, '')+ lines.push(' Devices on this account — each one trusts every other:', '')+ rows.forEach((m) => {+ const flag = m.self ? ' (this machine)' : isNewDevice(m, now) ? ' new' : ''+ lines.push(` ${String(numbers.get(m.pub)).padStart(2)}. ${nameOf(m)} ${kindOf(m)} ${m.fingerprint} ${activityPhrase(listing.lastSeen?.[m.pub], m.addedAt, now)}${flag}`)+ })+ // `remove` takes the key code here, not a number: a code names one device however the list moves.+ lines.push('', ' Details: harness devices show <#|fingerprint> Not yours? harness devices remove <fingerprint>', '')+ return lines+}++/** The lines of `harness devices show`: everything known about one device, and how to check it. */+export function formatDeviceDetail(row: DeviceRow, lastSeen: number | undefined, now: number): string[] {+ const lines = ['', ` ${nameOf(row)}${row.self ? ' (this machine)' : ''}`, '']+ lines.push(` kind ${row.kind === 'machine' ? 'Computer' : 'App'}`)+ lines.push(` added ${fullDateTime(row.addedAt)} (${relativeAgo(row.addedAt, now)})`)+ lines.push(` last active ${lastSeen === undefined ? 'unknown' : `${relativeAgo(lastSeen, now)} (${fullDateTime(lastSeen)})`}`)+ if (row.kind === 'machine') lines.push(` machine ${row.machineId.slice(0, 8)}`)+ lines.push(` key code ${row.fingerprint}`, '')+ lines.push(` ${COMPARE_HINT}`, '')+ lines.push(row.self ? ' This is this machine.' : ` Not yours? harness devices remove ${row.fingerprint}`, '')+ return lines+}diff --git a/cli/src/lib/e2ee/deviceLogStore.spec.ts b/cli/src/lib/e2ee/deviceLogStore.spec.tsnew file mode 100644index 000000000..20d617530--- /dev/null+++ b/cli/src/lib/e2ee/deviceLogStore.spec.ts@@ -0,0 +1,44 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { afterEach, describe, expect, it } from 'vitest'+import { DeviceLogStore, type DevLogFile } from './deviceLogStore.js'++const dirs: string[] = []+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })+const file = (): string => {+ const dir = mkdtempSync(join(tmpdir(), 'harness-devlog-store-'))+ dirs.push(dir)+ return join(dir, 'devlog.json')+}++const state = { acct: 'acct', head: { seq: 1, hash: 'h' }, hashes: ['h'], active: {}, removed: [] }++describe('DeviceLogStore — firstSeen across versions', () => {+ it('reads a devlog.json written before firstSeen existed, with nothing marked as first seen', () => {+ const path = file()+ writeFileSync(path, JSON.stringify({ state, recent: [], frozen: null, notifiedUpTo: 1 }))+ const read = new DeviceLogStore(path).read()+ expect(read.state).toEqual(state)+ expect(read.notifiedUpTo).toBe(1)+ expect(read.firstSeen).toBeUndefined()+ })++ it('keeps firstSeen through a write and a read', () => {+ const path = file()+ const store = new DeviceLogStore(path)+ const next: DevLogFile = { state: state as DevLogFile['state'], recent: [], frozen: null, notifiedUpTo: 1, firstSeen: { a: 5 } }+ store.write(next)+ expect(store.read().firstSeen).toEqual({ a: 5 })+ // The other fields an older CLI reads are where they always were.+ expect(JSON.parse(readFileSync(path, 'utf-8'))).toMatchObject({ state, recent: [], frozen: null, notifiedUpTo: 1 })+ })++ it('drops a firstSeen that is not an object rather than failing the whole read', () => {+ const path = file()+ writeFileSync(path, JSON.stringify({ state, recent: [], frozen: null, notifiedUpTo: 1, firstSeen: 'junk' }))+ const read = new DeviceLogStore(path).read()+ expect(read.state).toEqual(state)+ expect(read.firstSeen).toBeUndefined()+ })+})diff --git a/cli/src/lib/e2ee/deviceLogStore.ts b/cli/src/lib/e2ee/deviceLogStore.tsindex 0baa50107..345139296 100644--- a/cli/src/lib/e2ee/deviceLogStore.ts+++ b/cli/src/lib/e2ee/deviceLogStore.ts@@ -28,6 +28,9 @@ export interface DevLogFile {frozen: DevLogFreeze | null/** Entries up to this seq have been announced ("New device: X") — never twice. */notifiedUpTo: number+ /** When THIS machine first applied each key's add. The entry's own `at` is picked by the adding+ * device, so "new" cannot rest on it; absent for keys already in the log at first read. */+ firstSeen?: Record<string, number>}const empty = (): DevLogFile => ({ state: null, recent: [], frozen: null, notifiedUpTo: 0 })@@ -43,6 +46,7 @@ export class DeviceLogStore {recent: Array.isArray(raw.recent) ? raw.recent : [],frozen: raw.frozen && typeof raw.frozen === 'object' ? raw.frozen : null,notifiedUpTo: typeof raw.notifiedUpTo === 'number' ? raw.notifiedUpTo : 0,+ firstSeen: raw.firstSeen && typeof raw.firstSeen === 'object' ? raw.firstSeen : undefined,}} catch { return empty() }}diff --git a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts b/cli/src/lib/e2ee/deviceLogSyncer.spec.tsindex 5932abd1c..16e39920b 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.spec.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.spec.ts@@ -121,6 +121,21 @@ describe('DeviceLogSyncer', () => {expect(t.calls.announce).toHaveBeenCalledWith(expect.objectContaining({ pub: box2.pub, label: 'box2' }))})+ it('records when it first applied a new key, ignoring the entry\'s own backdated time, and not for the first read', async () => {+ t.backend.add(box2, 'machine', MID2, 'box2')+ await t.syncer.register()+ expect(t.store.read().firstSeen?.[box2.pub]).toBeUndefined()+ t.backend.add(phone, 'viewer', '', 'phone', 1) // the adding device claims it happened long ago+ await t.syncer.refresh()+ const file = t.store.read()+ expect(file.firstSeen?.[phone.pub]).toBe(5_000) // this machine's clock (setup `now`)+ expect(t.syncer.list().members.find((m) => m.pub === phone.pub)).toMatchObject({ firstSeen: 5_000, addedAt: 1 })+ expect(t.syncer.list().members.find((m) => m.pub === box2.pub)?.firstSeen).toBeUndefined()+ t.backend.removeBy(phone.pub, me)+ await t.syncer.refresh()+ expect(t.store.read().firstSeen?.[phone.pub]).toBeUndefined()+ })+it('does not announce a device this machine already trusted before the log', async () => {t = setup({ known: [box2.pub] })await t.syncer.register()diff --git a/cli/src/lib/e2ee/deviceLogSyncer.ts b/cli/src/lib/e2ee/deviceLogSyncer.tsindex c44e25b60..8e163301b 100644--- a/cli/src/lib/e2ee/deviceLogSyncer.ts+++ b/cli/src/lib/e2ee/deviceLogSyncer.ts@@ -59,7 +59,7 @@ export interface DeviceLogListing {head: DevLogHead | nullfrozen: DevLogFreeze | nullself: string- members: Array<DevLogMember & { fingerprint: string; self: boolean }>+ members: Array<DevLogMember & { fingerprint: string; self: boolean; firstSeen?: number }>/** Machines whose own copy of the log is frozen, as their last `group_sync` said. */frozenPeers: string[]}@@ -165,6 +165,17 @@ export class DeviceLogSyncer {}}+ /** `firstSeen` plus now for each newly applied key, minus keys no longer active (keeps the file small). */+ private stamp(prev: Record<string, number> | undefined, added: readonly DevLogMember[], state: DevLogState): Record<string, number> {+ const at = this.now()+ const out: Record<string, number> = {}+ for (const pub of Object.keys(state.active)) {+ const t = prev?.[pub] ?? (added.some((m) => m.pub === pub) ? at : undefined)+ if (t !== undefined) out[pub] = t+ }+ return out+ }+/** Apply entries that continue this machine's log; freeze on anything that does not. */private accept(entries: readonly unknown[], bootstrap: boolean): boolean {const file = this.deps.store.read()@@ -186,6 +197,7 @@ export class DeviceLogSyncer {recent: [...file.recent, ...parsed].slice(-DEVLOG_RECENT),frozen: null,notifiedUpTo: applied.state.head.seq,+ firstSeen: bootstrap ? file.firstSeen : this.stamp(file.firstSeen, applied.added, applied.state),})this.trustState(applied.state, bootstrap ? Object.values(applied.state.active) : [...applied.added, ...applied.relabeled])for (const m of applied.removed) this.deps.drop(m.pub)@@ -298,7 +310,10 @@ export class DeviceLogSyncer {const removed = Object.values(before).filter((m) => !next.active[m.pub])if (confirm) {const parsed = entries.map((e) => parseDevLogEntry(e)).filter((e): e is DevLogEntry => e !== null)- this.deps.store.write({ state: next, recent: parsed.slice(-DEVLOG_RECENT), frozen: null, notifiedUpTo: next.head.seq })+ this.deps.store.write({+ state: next, recent: parsed.slice(-DEVLOG_RECENT), frozen: null, notifiedUpTo: next.head.seq,+ firstSeen: this.stamp(file.firstSeen, added, next),+ })this.trustState(next, Object.values(next.active))for (const m of removed) this.deps.drop(m.pub)this.deps.changed?.()@@ -353,6 +368,8 @@ export class DeviceLogSyncer {.map((m) => ({ ...m, fingerprint: fingerprint(b64d(m.pub)), self: m.pub === selfPub }))const labels = new Map(members.map((m) => [m.pub, m.label]))const frozenPeers = [...this.frozenPeers].filter(([, frozen]) => frozen).map(([pub]) => labels.get(pub) ?? fingerprint(b64d(pub)))- return { head: file.state?.head ?? null, frozen: file.frozen, self: selfPub, members, frozenPeers }+ // Each row carries when this machine first applied it (never the entry's self-chosen `at`).+ const withSeen = members.map((m) => (file.firstSeen?.[m.pub] === undefined ? m : { ...m, firstSeen: file.firstSeen[m.pub] }))+ return { head: file.state?.head ?? null, frozen: file.frozen, self: selfPub, members: withSeen, frozenPeers }}}diff --git a/cli/src/lib/e2ee/store.spec.ts b/cli/src/lib/e2ee/store.spec.tsnew file mode 100644index 000000000..c92d3163d--- /dev/null+++ b/cli/src/lib/e2ee/store.spec.ts@@ -0,0 +1,96 @@+import * as fs from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { b64d as b64, b64e } from './core.js'+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Every read of identity.json goes through this hook, so a test can play the other process: the one+// that creates the key between this store's look and its own create.+let onIdentityRead: ((reads: number) => void) | null = null+let identityReads = 0+vi.mock('fs', async (importOriginal) => {+ const real = await importOriginal<typeof import('fs')>()+ return {+ ...real,+ readFileSync: ((file: fs.PathOrFileDescriptor, options?: unknown) => {+ if (typeof file === 'string' && file.endsWith(join('e2e', 'identity.json')) && onIdentityRead) onIdentityRead(++identityReads)+ return (real.readFileSync as (f: fs.PathOrFileDescriptor, o?: unknown) => string | Buffer)(file, options)+ }) as typeof real.readFileSync,+ }+})++const { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } = fs+// The store resolves its directory when the module loads, so point it at a scratch dir first.+const root = mkdtempSync(join(tmpdir(), 'harness-e2ee-store-'))+vi.stubEnv('ADAPTER_DATA_DIR', root)+const { E2eeStore, peekIdentityPub } = await import('./store.js')+const identityFile = join(root, 'e2e', 'identity.json')+const onDisk = (): { priv: string; pub: string } => JSON.parse(readFileSync(identityFile, 'utf-8')) as { priv: string; pub: string }+const enoent = (): Error => Object.assign(new Error('ENOENT: no such file'), { code: 'ENOENT' })++beforeEach(() => {+ rmSync(join(root, 'e2e'), { recursive: true, force: true })+ onIdentityRead = null+ identityReads = 0+})+afterEach(() => { onIdentityRead = null })+afterAll(() => rmSync(root, { recursive: true, force: true }))++describe('E2eeStore.init identity', () => {+ it('mints a key once and every later store adopts it', () => {+ const first = new E2eeStore().init()+ expect(new E2eeStore().init().pub).toEqual(first.pub)+ expect(b64(onDisk().pub)).toEqual(first.pub)+ })++ it('a store that lost the create race adopts the winner key instead of overwriting it', () => {+ // Between this store finding no key and writing its own, another process (login vs the daemon) wins.+ let winnerPub: Uint8Array | null = null+ onIdentityRead = (n) => {+ if (n !== 1) return+ onIdentityRead = null+ winnerPub = new E2eeStore().init().pub // writes identity.json; the loser's look still found nothing+ onIdentityRead = () => {}+ throw enoent()+ }+ const loser = new E2eeStore().init()+ expect(winnerPub).not.toBeNull()+ expect(loser.pub).toEqual(winnerPub)+ expect(b64(onDisk().pub)).toEqual(winnerPub)+ })++ it('a store that finds the winner key half-written waits for it rather than overwriting it', () => {+ // An exclusive create makes the file before its bytes land: the loser can read it empty.+ const winner = { priv: 'd2lubmVyLXByaXY=', pub: 'd2lubmVyLXB1Yg==' }+ onIdentityRead = (n) => {+ if (n === 1) {+ mkdirSync(join(root, 'e2e'), { recursive: true })+ writeFileSync(identityFile, '') // the winner has opened the file, not written it yet+ throw enoent()+ }+ if (n === 3) writeFileSync(identityFile, JSON.stringify(winner)) // ...and finishes a moment later+ }+ const loser = new E2eeStore().init()+ expect(identityReads).toBeGreaterThanOrEqual(3) // it read the empty file and did not give up on it+ expect(b64e(loser.pub)).toBe(winner.pub)+ expect(onDisk()).toEqual(winner)+ })++ it('replaces an unreadable identity file as it always did', () => {+ mkdirSync(join(root, 'e2e'), { recursive: true })+ writeFileSync(identityFile, 'not json')+ const id = new E2eeStore().init()+ expect(new E2eeStore().init().pub).toEqual(id.pub)+ expect(b64(onDisk().pub)).toEqual(id.pub)+ })++ it('mints a fresh key after the old one was spent (renamed away), and peek sees only the new one', () => {+ const old = new E2eeStore().init()+ renameSync(identityFile, `${identityFile}.removed-1`)+ expect(peekIdentityPub()).toBeNull()+ const next = new E2eeStore().init()+ expect(next.pub).not.toEqual(old.pub)+ expect(existsSync(identityFile)).toBe(true)+ expect(peekIdentityPub()).toBe(b64e(next.pub))+ })+})diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.tsindex 946bafa6d..effbdec54 100644--- a/cli/src/lib/e2ee/store.ts+++ b/cli/src/lib/e2ee/store.ts@@ -4,7 +4,7 @@* mode 0600 (pairs are rare — no debounce needed). The identity key is the root of trust; losing it* forces every browser to re-pair.*/-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'import { join } from 'path'import { env } from '../../config/env.js'import { newIdentity, newPairId, b64e, b64d, fingerprint, type Identity, type PairRole } from './core.js'@@ -13,6 +13,22 @@ import { stretchPassword } from './passwordPake.js'const DIR = join(env.ADAPTER_DATA_DIR, 'e2e')const IDENTITY_FILE = join(DIR, 'identity.json')const PAIRED_FILE = join(DIR, 'paired.json')++/** This computer's identity public key (base64) as already on disk, or null. Unlike `E2eeStore.init()`+ * it never creates a key and writes nothing, so a read-only command can show the fingerprint without+ * minting an identity as a side effect. */+export function peekIdentityPub(): string | null {+ try {+ const raw = JSON.parse(readFileSync(IDENTITY_FILE, 'utf-8')) as { pub?: unknown }+ return typeof raw.pub === 'string' && raw.pub ? raw.pub : null+ } catch { return null }+}++/** Whether an identity was retired here (`identity.json.removed-*`, left by signing this device out of+ * the account), so "no identity" can be told apart from "never had one". */+export function identitySpent(): boolean {+ try { return readdirSync(DIR).some((f) => f.startsWith('identity.json.removed-')) } catch { return false }+}const REMOTE_PASSWORD_FILE = join(DIR, 'remotePassword.json')// Remote-password lockout tuning (anti online-guessing for a reusable, human-memorable secret — see@@ -47,9 +63,14 @@ export interface PairedClient {/** What a password-linked peer is: another harness machine (which also serves, so it can be dialed back)* or a viewer app (mobile / viewer desktop — dial-out only). */export type PeerKind = 'machine' | 'viewer'-function writeSecure(file: string, data: unknown): void {+/** How long `init()` waits for another process's just-created identity file to be written (10 × 20 ms). */+const IDENTITY_READ_RETRIES = 10+const IDENTITY_READ_RETRY_MS = 20+const sleepSync = (ms: number): void => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }++function writeSecure(file: string, data: unknown, flag: 'w' | 'wx' = 'w'): void {mkdirSync(DIR, { recursive: true, mode: 0o700 })- writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 })+ writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600, flag })}export class E2eeStore {@@ -61,13 +82,26 @@ export class E2eeStore {* Idempotent. */init(): Identity {if (this.identity) return this.identity- try {+ const readIdentity = (): Identity => {const raw = JSON.parse(readFileSync(IDENTITY_FILE, 'utf-8')) as { priv: string; pub: string }- this.identity = { priv: b64d(raw.priv), pub: b64d(raw.pub) }- } catch {+ return { priv: b64d(raw.priv), pub: b64d(raw.pub) }+ }+ // `harness login` and a booting daemon can both get here: exclusive create so exactly one key is+ // ever minted, and the loser adopts the winner's instead of overwriting it. The create makes the+ // file before its bytes land, so a loser that reads it empty waits a moment and reads again; only+ // a file still unreadable after that is taken as broken and replaced, as before.+ for (let attempt = 0; !this.identity; attempt++) {+ try { this.identity = readIdentity(); break } catch { /* missing, half-written or broken */ }const id = newIdentity()- writeSecure(IDENTITY_FILE, { priv: b64e(id.priv), pub: b64e(id.pub) })- this.identity = id+ try {+ writeSecure(IDENTITY_FILE, { priv: b64e(id.priv), pub: b64e(id.pub) }, 'wx')+ this.identity = id+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err+ if (attempt < IDENTITY_READ_RETRIES) { sleepSync(IDENTITY_READ_RETRY_MS); continue }+ writeSecure(IDENTITY_FILE, { priv: b64e(id.priv), pub: b64e(id.pub) })+ this.identity = id+ }}try {const arr = JSON.parse(readFileSync(PAIRED_FILE, 'utf-8')) as Array<PairedClient & { role?: PairRole }>diff --git a/desktop/lib/core/relative_time.dart b/desktop/lib/core/relative_time.dartnew file mode 100644index 000000000..d11d742d0--- /dev/null+++ b/desktop/lib/core/relative_time.dart@@ -0,0 +1,54 @@+/// A device seen this recently reads as "active now" rather than "5 minutes ago".+const activeNowWithin = Duration(minutes: 5);++const _months = [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+];++String _ago(int n, String unit) => '$n $unit${n == 1 ? '' : 's'} ago';++/// "2 days ago". Coarse on purpose: the person is deciding "do I recognise this device", not auditing+/// a log. The same wording as `harness devices list` and the mobile app, so one device reads the same+/// everywhere. A time in the future (clock skew) reads as "just now".+String relativeAgo(DateTime at, DateTime now) {+ final d = now.difference(at);+ if (d.isNegative || d < const Duration(minutes: 1)) return 'just now';+ if (d < const Duration(hours: 1)) return _ago(d.inMinutes, 'minute');+ if (d < const Duration(days: 1)) return _ago(d.inHours, 'hour');+ if (d < const Duration(days: 2)) return 'yesterday';+ final days = d.inDays;+ if (days < 14) return '$days days ago';+ if (days < 60) return '${days ~/ 7} weeks ago';+ if (days < 365) return '${days ~/ 30} months ago';+ return 'over a year ago';+}++/// `1 Oct 2026, 14:05` in local time — spelled out so it reads the same in every locale.+String fullDateTime(DateTime at) {+ final local = at.toLocal();+ String two(int n) => n.toString().padLeft(2, '0');+ return '${local.day} ${_months[local.month - 1]} ${local.year}, ${two(local.hour)}:${two(local.minute)}';+}++/// `active now` / `last active 2 days ago` / `added 3 weeks ago` (no session was ever recorded for it).+String activityPhrase({+ DateTime? lastSeen,+ required DateTime addedAt,+ required DateTime now,+}) {+ if (lastSeen == null) return 'added ${relativeAgo(addedAt, now)}';+ return now.difference(lastSeen) < activeNowWithin+ ? 'active now'+ : 'last active ${relativeAgo(lastSeen, now)}';+}diff --git a/desktop/lib/notify/system_notifications.dart b/desktop/lib/notify/system_notifications.dartindex cb9298137..db3737339 100644--- a/desktop/lib/notify/system_notifications.dart+++ b/desktop/lib/notify/system_notifications.dart@@ -365,15 +365,26 @@ class SystemNotifications {);}+ /// What a device notice puts in the `machineId` slot of a click. The slots carry an agent's address+ /// and the native side hands them back unchanged, so this marks "not an agent" without a new field+ /// in the Swift code; [postNotice] puts the device's key in the `agentId` slot.+ static const deviceNoticeMachine = '@device';+/// News about the ACCOUNT rather than an agent — a device joined it. The same switch and the same- /// rules as [post]; a click on it opens no agent.- void postNotice({required String id, required String title, required String body}) {+ /// rules as [post]; a click on it opens that device ([devicePub]) when given, else nothing.+ void postNotice({required String id, required String title, required String body, String? devicePub}) {if (!store.value || !supported) return;if (permission.value == NotificationPermission.unavailable) return;_ordered(id,() => notifier- .show(id: id, title: title, body: body, machineId: '', agentId: '')+ .show(+ id: id,+ title: title,+ body: body,+ machineId: devicePub == null ? '' : deviceNoticeMachine,+ agentId: devicePub ?? '',+ ).then((answer) {if (answer != NotificationPermission.unknown) {permission.value = answer;diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 3de1e0883..781af8a8e 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -24,6 +24,8 @@ import '../models/api_connections_controller.dart' show agentOnApiModel;import '../models/models_panel.dart';import '../models/model_search_catalog.dart';import '../widgets/resting_section.dart' show confirmSwitchAnyway;+import '../notify/system_notifications.dart';+import '../settings/sections/account_device_detail.dart';import '../settings/settings_screen.dart';import '../settings/settings_section.dart';import '../shared/theme/app_theme.dart' as grid;@@ -608,6 +610,19 @@ class _SwarmScreenState extends State<SwarmScreen> {app.systemNotifications.onTap = (machineId, agentId) async {await revealWindow();if (!mounted) return;+ // A device notice puts its marker where an agent's machine goes and the device's key where the+ // agent goes: the click opens that device.+ if (machineId == SystemNotifications.deviceNoticeMachine) {+ unawaited(+ showAccountDeviceDetail(+ context,+ app,+ pub: agentId,+ isNew: app.newDevices.any((d) => d.pub == agentId),+ ),+ );+ return;+ }try {await app.revealAgentFromAlert(machineId, agentId);} catch (_) {diff --git a/desktop/lib/settings/sections/account_device_detail.dart b/desktop/lib/settings/sections/account_device_detail.dartnew file mode 100644index 000000000..aac7d45d6--- /dev/null+++ b/desktop/lib/settings/sections/account_device_detail.dart@@ -0,0 +1,311 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../../core/relative_time.dart';+import '../../shared/theme/app_theme.dart' as grid;+import '../../shared/widgets/app_dialog.dart';+import '../../shared/widgets/fingerprint_text.dart';+import '../../state/account_devices.dart';+import '../../state/app_state.dart';++/// What removing a device does, said in the confirm and nowhere else so the two entry points (the list+/// row and the detail) cannot word it differently.+const removeDeviceDetail =+ 'It stops reaching your machines on every device, and is signed out. '+ 'Signing in on it again adds it back as a new device.';++/// A yes/no question in the app's dialog. True only on the confirming button.+Future<bool> confirmDeviceAction(+ BuildContext context,+ String title,+ String detail,+ String action, {+ bool destructive = false,+}) async =>+ await showAppDialog<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(title),+ content: SizedBox(+ width: 360,+ child: Text(detail, style: grid.AppType.body(height: 1.4)),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context, false),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ overlayColor: grid.AppSurface.hoverFill,+ ),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const Key('account-device-confirm'),+ style: destructive+ ? FilledButton.styleFrom(+ backgroundColor: grid.AppPalette.dangerFill,+ overlayColor: const Color(0x1FFFFFFF),+ )+ : null,+ onPressed: () => Navigator.pop(context, true),+ child: Text(action),+ ),+ ],+ ),+ ) ??+ false;++/// One device in full: its facts, its whole key code to compare on that device, and what to do about+/// it. [device] is the row the list already holds; without it (the banner and the notification only+/// know the key) the account's list is read, and until then — or when it cannot be — the new-device+/// notice for [pub] stands in. [isNew] offers "It’s mine"; [onMine] tells the caller it was used.+Future<void> showAccountDeviceDetail(+ BuildContext context,+ AppNotifier app, {+ required String pub,+ AccountDevice? device,+ bool isNew = false,+ VoidCallback? onMine,+}) => showAppDialog<void>(+ context: context,+ builder: (context) => _AccountDeviceDetail(+ app: app,+ pub: pub,+ device: device,+ isNew: isNew,+ onMine: onMine,+ ),+);++class _AccountDeviceDetail extends StatefulWidget {+ const _AccountDeviceDetail({+ required this.app,+ required this.pub,+ required this.device,+ required this.isNew,+ required this.onMine,+ });++ final AppNotifier app;+ final String pub;+ final AccountDevice? device;+ final bool isNew;+ final VoidCallback? onMine;++ @override+ State<_AccountDeviceDetail> createState() => _AccountDeviceDetailState();+}++class _AccountDeviceDetailState extends State<_AccountDeviceDetail> {+ AccountDevice? _device;+ bool _loading = false;+ bool _removing = false;+ String? _error;++ @override+ void initState() {+ super.initState();+ _device = widget.device;+ if (_device == null) {+ _loading = true;+ unawaited(_load());+ }+ }++ Future<void> _load() async {+ // A list that cannot be read leaves the notice standing in (or "no longer on your account"),+ // never a dialog stuck on Loading….+ AccountDevices? devices;+ try {+ devices = await widget.app.loadDevices();+ } catch (_) {+ devices = null;+ }+ if (!mounted) return;+ setState(() {+ _loading = false;+ if (devices != null) {+ for (final d in devices.devices) {+ if (d.pub == widget.pub) _device = d;+ }+ }+ });+ }++ NewDeviceNotice? get _notice {+ for (final n in widget.app.newDevices) {+ if (n.pub == widget.pub) return n;+ }+ return null;+ }++ Future<void> _remove(String name) async {+ final confirmed = await confirmDeviceAction(+ context,+ 'Remove $name?',+ removeDeviceDetail,+ 'Remove',+ destructive: true,+ );+ if (!confirmed || !mounted) return;+ setState(() {+ _removing = true;+ _error = null;+ });+ final error = await widget.app.removeDevice(widget.pub);+ if (!mounted) return;+ if (error == null) {+ Navigator.pop(context);+ return;+ }+ setState(() {+ _removing = false;+ _error = "Couldn't remove $name ($error). Try again.";+ });+ }++ void _mine() {+ widget.app.dismissNewDevice(widget.pub);+ widget.onMine?.call();+ Navigator.pop(context);+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final device = _device;+ final notice = _notice;+ final closeButton = TextButton(+ key: const Key('device-detail-close'),+ onPressed: () => Navigator.pop(context),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ overlayColor: grid.AppSurface.hoverFill,+ ),+ child: const Text('Close'),+ );+ if (device == null && notice == null) {+ return AlertDialog(+ title: const Text('Device'),+ content: SizedBox(+ width: 420,+ child: Text(+ _loading ? 'Loading…' : 'This device is no longer on your account.',+ key: const Key('device-detail-gone'),+ style: grid.AppType.body(color: grid.AppPalette.textSecondary),+ ),+ ),+ actions: [closeButton],+ );+ }+ // The list's row when there is one; the notice when the list could not say (it has no times).+ final label = (device?.label ?? notice!.label).trim();+ final name = label.isEmpty ? 'Unnamed device' : label;+ final isMachine = device?.isMachine ?? notice!.kind == 'machine';+ final fp = device?.fingerprint ?? notice!.fingerprint;+ final machineId = device?.machineId ?? '';+ final lastSeen = device?.lastSeen;+ final now = DateTime.now();+ final self = device?.self ?? false;+ return AlertDialog(+ title: Text(name),+ content: SizedBox(+ width: 420,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _Fact('Kind', isMachine ? 'Computer' : 'App'),+ if (device != null) _Fact('Added', fullDateTime(device.addedAt)),+ if (lastSeen != null)+ _Fact('Last active', relativeAgo(lastSeen, now)),+ if (isMachine && machineId.isNotEmpty)+ _Fact(+ 'Machine',+ machineId.substring(+ 0,+ machineId.length < 8 ? machineId.length : 8,+ ),+ ),+ const SizedBox(height: 14),+ if (fp.isNotEmpty) ...[+ FingerprintText(+ fp,+ large: true,+ copyKey: const Key('device-detail-copy'),+ ),+ const SizedBox(height: 8),+ Text(+ fingerprintHowToCompare(computer: isMachine),+ style: grid.AppType.body(+ color: grid.AppPalette.textSecondary,+ height: 1.4,+ ),+ ),+ ],+ if (_error case final error?) ...[+ const SizedBox(height: 12),+ Text(+ error,+ key: const Key('device-detail-error'),+ style: grid.AppType.body(color: grid.AppPalette.warn),+ ),+ ],+ ],+ ),+ ),+ ),+ actions: [+ closeButton,+ if (widget.isNew)+ TextButton(+ key: const Key('device-detail-mine'),+ onPressed: _removing ? null : _mine,+ child: const Text('It’s mine'),+ ),+ if (!self)+ FilledButton(+ key: const Key('device-detail-remove'),+ style: FilledButton.styleFrom(+ backgroundColor: grid.AppPalette.dangerFill,+ overlayColor: const Color(0x1FFFFFFF),+ ),+ onPressed: _removing ? null : () => unawaited(_remove(name)),+ child: Text(_removing ? 'Removing…' : 'Remove'),+ ),+ ],+ );+ }+}++class _Fact extends StatelessWidget {+ const _Fact(this.label, this.value);++ final String label, value;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ SizedBox(+ width: 96,+ child: Text(+ label,+ style: grid.AppType.caption(color: grid.AppPalette.textSecondary),+ ),+ ),+ Expanded(+ child: Text(+ value,+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),+ ),+ ),+ ],+ ),+ );+}diff --git a/desktop/lib/settings/sections/account_devices_section.dart b/desktop/lib/settings/sections/account_devices_section.dartindex de622061f..14d183a69 100644--- a/desktop/lib/settings/sections/account_devices_section.dart+++ b/desktop/lib/settings/sections/account_devices_section.dart@@ -2,13 +2,16 @@ import 'dart:async';import 'package:flutter/material.dart';+import '../../core/relative_time.dart';import '../../shared/theme/app_theme.dart' as grid;-import '../../shared/widgets/app_dialog.dart';+import '../../shared/widgets/fingerprint_text.dart';+import '../../shared/widgets/section_heading.dart';import '../../shared/widgets/section_scaffold.dart';import '../../shared/widgets/setting_row.dart';import '../../shared/widgets/skeleton.dart';import '../../state/account_devices.dart';import '../../state/app_state.dart';+import 'account_device_detail.dart';/// Settings ▸ Your devices — every computer and app signed in to this account. Signing in on one is/// what makes the others trust it (the device key log), so this list is also the one place to see a@@ -29,12 +32,17 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {final Set<String> _removing = {};String? _error;+ /// The devices that were new when this list opened: they keep their `New` badge for the visit, though+ /// opening the list clears the banner that announced them.+ late final Set<String> _newPubs;+AppNotifier get _app => widget.notifier;@overridevoid initState() {super.initState();_app.addListener(_changed);+ _newPubs = {for (final d in _app.newDevices) d.pub};unawaited(_load());// Looking at the list IS reviewing the new devices: the banner that pointed here is done.WidgetsBinding.instance.addPostFrameCallback((_) {@@ -64,10 +72,10 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {Future<void> _remove(AccountDevice device) async {final name = device.label.isEmpty ? 'this device' : device.label;- final confirmed = await _confirm(+ final confirmed = await confirmDeviceAction(+ context,'Remove $name?',- 'It stops reaching your machines on every device, and is signed out. '- 'Signing in on it again adds it back as a new device.',+ removeDeviceDetail,'Remove',destructive: true,);@@ -87,9 +95,10 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {bool _removingUnused = false;Future<void> _removeUnused(List<AccountDevice> unused) async {- final confirmed = await _confirm(+ final confirmed = await confirmDeviceAction(+ context,'Remove ${unused.length} unused app${unused.length == 1 ? '' : 's'}?',- [for (final d in unused) '${d.label.isEmpty ? 'Unnamed app' : d.label} — last seen ${_date(d.lastSeen!)}'].join('\n'),+ [for (final d in unused) '${d.label.isEmpty ? 'Unnamed app' : d.label} — last active ${relativeAgo(d.lastSeen!, DateTime.now())}'].join('\n'),'Remove',destructive: true,);@@ -120,7 +129,8 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {for (final name in preview.added) '+ $name',for (final name in preview.removed) '− $name',];- final confirmed = await _confirm(+ final confirmed = await confirmDeviceAction(+ context,'Trust this device list again?',lines.isEmpty? 'It changes no device. Continue only if you expected this.'@@ -131,39 +141,16 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {await _app.rebaselineDevices(confirm: true);}- Future<bool> _confirm(String title, String detail, String action, {bool destructive = false}) async =>- await showAppDialog<bool>(- context: context,- builder: (context) => AlertDialog(- title: Text(title),- content: SizedBox(- width: 360,- child: Text(detail, style: grid.AppType.body(height: 1.4)),- ),- actions: [- TextButton(- onPressed: () => Navigator.pop(context, false),- style: TextButton.styleFrom(- foregroundColor: grid.AppPalette.textSecondary,- overlayColor: grid.AppSurface.hoverFill,- ),- child: const Text('Cancel'),- ),- FilledButton(- key: const Key('account-device-confirm'),- style: destructive- ? FilledButton.styleFrom(- backgroundColor: grid.AppPalette.dangerFill,- overlayColor: const Color(0x1FFFFFFF),- )- : null,- onPressed: () => Navigator.pop(context, true),- child: Text(action),- ),- ],- ),- ) ??- false;+ void _open(AccountDevice device) => unawaited(+ showAccountDeviceDetail(+ context,+ _app,+ pub: device.pub,+ device: device,+ isNew: _newPubs.contains(device.pub),+ onMine: () => setState(() => _newPubs.remove(device.pub)),+ ),+ );@overrideWidget build(BuildContext context) {@@ -203,23 +190,56 @@ class _AccountDevicesSectionState extends State<AccountDevicesSection> {'The device list is not available here yet.',style: grid.AppType.body(color: grid.AppPalette.textSecondary),)- else- for (final device in devices.devices)+ else ...[+ if (devices.self case final self?) ...[+ const SectionHeading('This device'),+ const SizedBox(height: 8),+ SettingRow(+ key: const Key('account-device-this'),+ title: self.label.trim().isEmpty ? 'Unnamed device' : self.label,+ detail: 'This is the code your other devices show for this device.',+ control: const SizedBox.shrink(),+ footer: FingerprintText(self.fingerprint, large: false, copyKey: const Key('this-device-copy')),+ ),+ const SizedBox(height: 16),+ ],+ for (final device in devices.listed(_newPubs))Padding(padding: const EdgeInsets.only(bottom: 8),- child: SettingRow(- key: ValueKey('account-device-${device.pub}'),- title: '${device.label.isEmpty ? 'Unnamed device' : device.label}${device.self ? ' (this device)' : ''}',- detail: '${device.isMachine ? 'Computer' : 'App'} · added ${_date(device.addedAt)}'- '${device.lastSeen != null ? ' · last seen ${_date(device.lastSeen!)}' : ''} · ${device.fingerprint}',- control: device.self- ? const SizedBox.shrink()- : OutlinedButton(- onPressed: _removing.contains(device.pub) ? null : () => unawaited(_remove(device)),- child: Text(_removing.contains(device.pub) ? 'Removing…' : 'Remove'),- ),+ child: MouseRegion(+ cursor: SystemMouseCursors.click,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => _open(device),+ child: SettingRow(+ key: ValueKey('account-device-${device.pub}'),+ title: device.label.trim().isEmpty ? 'Unnamed device' : device.label,+ badge: _newPubs.contains(device.pub) ? 'New' : null,+ detail: deviceDetailLine(+ device,+ now: DateTime.now(),+ sameName: devices.sharedNames.contains(device.label.trim()),+ ),+ control: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ TextButton(+ key: ValueKey('account-device-details-${device.pub}'),+ onPressed: () => _open(device),+ child: const Text('Details'),+ ),+ const SizedBox(width: 6),+ OutlinedButton(+ onPressed: _removing.contains(device.pub) ? null : () => unawaited(_remove(device)),+ child: Text(_removing.contains(device.pub) ? 'Removing…' : 'Remove'),+ ),+ ],+ ),+ ),+ ),),),+ ],],),),@@ -268,8 +288,3 @@ class _FrozenLine extends StatelessWidget {);}}--String _date(DateTime at) {- String two(int n) => n.toString().padLeft(2, '0');- return '${at.year}-${two(at.month)}-${two(at.day)}';-}diff --git a/desktop/lib/shared/widgets/fingerprint_text.dart b/desktop/lib/shared/widgets/fingerprint_text.dartnew file mode 100644index 000000000..52f6666d1--- /dev/null+++ b/desktop/lib/shared/widgets/fingerprint_text.dart@@ -0,0 +1,103 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../theme/app_icons.dart';+import '../theme/app_theme.dart' as grid;++/// A device's key code spelled for a screen reader: `Key code E 2 F B, 0 D F 5, 5 F D 8, E 6 C 7` —+/// letter by letter, so it is not read as a word.+String fingerprintSpoken(String fingerprint) =>+ 'Key code ${fingerprint.split('·').map((group) => group.split('').join(' ')).join(', ')}';++/// How to check a key code, shown under it in a device's detail. [computer] adds the CLI route, which+/// only a computer has.+String fingerprintHowToCompare({required bool computer}) => computer+ ? 'This device’s own key code. Open Your devices on that computer — the code under “This device” '+ 'must match — or run harness status on it.'+ : 'This device’s own key code. Open Your devices on that device — the code under “This device” must match.';++/// A key code (`E2FB·0DF5·5FD8·E6C7`) set in mono, selectable, with a Copy button.+///+/// The code is what a person reads out or compares against another screen, so it is never truncated or+/// restyled into something that is hard to select; the Copy button puts the exact string on the+/// clipboard. [large] is the detail's size, small the one inside the "This device" card.+class FingerprintText extends StatefulWidget {+ const FingerprintText(+ this.fingerprint, {+ super.key,+ this.large = true,+ this.copyKey,+ });++ final String fingerprint;+ final bool large;++ /// Key of the Copy button, for tests.+ final Key? copyKey;++ @override+ State<FingerprintText> createState() => _FingerprintTextState();+}++class _FingerprintTextState extends State<FingerprintText> {+ Timer? _timer;+ String? _message;+ int _attempt = 0;++ @override+ void dispose() {+ _timer?.cancel();+ super.dispose();+ }++ // Same flow as the Copy buttons in the machines panel: a later tap supersedes an earlier one still+ // waiting on the clipboard, and the answer clears itself after a few seconds.+ Future<void> _copy() async {+ final attempt = ++_attempt;+ try {+ await Clipboard.setData(ClipboardData(text: widget.fingerprint));+ if (!mounted || attempt != _attempt) return;+ setState(() => _message = 'Copied');+ } catch (_) {+ if (!mounted || attempt != _attempt) return;+ setState(() => _message = 'Couldn’t copy. Try again');+ }+ _timer?.cancel();+ _timer = Timer(const Duration(seconds: 3), () {+ if (mounted) setState(() => _message = null);+ });+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final message = _message;+ return Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 12,+ runSpacing: 4,+ children: [+ Semantics(+ label: fingerprintSpoken(widget.fingerprint),+ excludeSemantics: true,+ child: SelectableText(+ widget.fingerprint,+ style: grid.AppType.mono(color: grid.AppPalette.textPrimary)+ .copyWith(fontSize: widget.large ? 20 : 15, letterSpacing: 0.5),+ ),+ ),+ TextButton.icon(+ key: widget.copyKey,+ onPressed: _copy,+ icon: Icon(+ message == 'Copied' ? AppIcons.check : AppIcons.copy,+ size: 16,+ ),+ label: Text(message ?? 'Copy'),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/shared/widgets/setting_row.dart b/desktop/lib/shared/widgets/setting_row.dartindex e05375a74..e8488203e 100644--- a/desktop/lib/shared/widgets/setting_row.dart+++ b/desktop/lib/shared/widgets/setting_row.dart@@ -19,6 +19,7 @@ class SettingRow extends StatelessWidget {this.controlSemanticLabel,this.footer,this.alignTop = false,+ this.badge,});final String title;@@ -37,6 +38,9 @@ class SettingRow extends StatelessWidget {/// Align taller controls with the title; compact controls stay centered.final bool alignTop;+ /// A small tag after the title, such as `New`. Null draws the title alone.+ final String? badge;+/// Fixed, so every control on this screen lines up on one right edge.static const double controlWidth = 188;@@ -51,7 +55,21 @@ class SettingRow extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,children: [- Text(title, style: Theme.of(context).textTheme.titleSmall),+ if (badge case final badge?)+ Row(+ children: [+ Flexible(+ child: Text(+ title,+ style: Theme.of(context).textTheme.titleSmall,+ ),+ ),+ const SizedBox(width: 6),+ _Badge(badge),+ ],+ )+ else+ Text(title, style: Theme.of(context).textTheme.titleSmall),if (detail case final detail?) ...[const SizedBox(height: 2),Text(detail, style: Theme.of(context).textTheme.bodySmall),@@ -109,3 +127,21 @@ class SettingRow extends StatelessWidget {);}}++class _Badge extends StatelessWidget {+ const _Badge(this.text);++ final String text;++ @override+ Widget build(BuildContext context) => DecoratedBox(+ decoration: BoxDecoration(+ color: AppPalette.warn.withValues(alpha: 0.12),+ borderRadius: BorderRadius.circular(4),+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),+ child: Text(text, style: AppType.caption(color: AppPalette.warn)),+ ),+ );+}diff --git a/desktop/lib/state/account_devices.dart b/desktop/lib/state/account_devices.dartindex a502e4d16..9706a9dbe 100644--- a/desktop/lib/state/account_devices.dart+++ b/desktop/lib/state/account_devices.dart@@ -1,3 +1,6 @@+import '../core/relative_time.dart';+import '../e2ee/bytes.dart';+import '../e2ee/keys.dart' as keys;import '../viewer/device_log.dart';import '../viewer/device_log_sync.dart';@@ -79,6 +82,43 @@ class AccountDevices {if (!d.self && !d.isMachine && d.lastSeen != null && now.difference(d.lastSeen!) > unusedAfter) d,];+ /// This computer (or app): shown on its own in the "This device" card, so the list below leaves it out.+ AccountDevice? get self {+ for (final d in devices) {+ if (d.self) return d;+ }+ return null;+ }++ /// The rows under the "This device" card: the new devices (those in [newPubs]) first, newest first,+ /// then the rest by last activity. Ties keep log order — `List.sort` is not stable, so the index breaks them.+ List<AccountDevice> listed(Set<String> newPubs) {+ final rows = [+ for (var i = 0; i < devices.length; i++)+ if (!devices[i].self) (index: i, device: devices[i], isNew: newPubs.contains(devices[i].pub)),+ ];+ rows.sort((a, b) {+ if (a.isNew != b.isNew) return a.isNew ? -1 : 1;+ final byTime = (b.isNew ? b.device.addedAt : b.device.lastSeen ?? b.device.addedAt).compareTo(+ a.isNew ? a.device.addedAt : a.device.lastSeen ?? a.device.addedAt,+ );+ return byTime != 0 ? byTime : a.index.compareTo(b.index);+ });+ return [for (final r in rows) r.device];+ }++ /// Names more than one device goes by (trimmed; an empty name counts as one name). Their rows add the+ /// start of the key code, since two rows that read the same cannot be told apart otherwise.+ Set<String> get sharedNames {+ final seen = <String>{};+ final shared = <String>{};+ for (final d in devices) {+ final name = d.label.trim();+ if (!seen.add(name)) shared.add(name);+ }+ return shared;+ }+AccountDevices withLastSeen(Map<String, int> seen) => AccountDevices(devices: [for (final d in devices)@@ -132,12 +172,26 @@ class DevicesRebaseline {/// A device that joined the account and this end had never trusted: "New device: X".class NewDeviceNotice {- const NewDeviceNotice({required this.pub, required this.label, required this.kind});+ const NewDeviceNotice({required this.pub, required this.label, required this.kind, this.frameFingerprint});final String pub;final String label;final String kind;+ /// The key code the `device_key_added` frame carried, when it did.+ final String? frameFingerprint;++ /// The key code to compare on the device itself: the frame's, else worked out from the key.+ String get fingerprint {+ final fromFrame = frameFingerprint;+ if (fromFrame != null && fromFrame.isNotEmpty) return fromFrame;+ try {+ return keys.fingerprint(b64d(pub));+ } catch (_) {+ return '';+ }+ }+String get sentence {final name = label.isEmpty ? 'A device' : label;return kind == 'machine'@@ -154,3 +208,13 @@ Map<String, int> parseLastSeen(Object? raw) => {for (final e in raw.entries)if (e.key is String && e.value is int) e.key as String: e.value as int,};++/// The line under a device's name in the list: `Computer · active now`, `App · last active 2 days ago`.+/// With [sameName] — another device goes by the same name — it ends in the first group of the key code,+/// the one thing that tells the two apart without putting the whole code in the row.+String deviceDetailLine(AccountDevice d, {required DateTime now, required bool sameName}) {+ final what = d.isMachine ? 'Computer' : 'App';+ final when = activityPhrase(lastSeen: d.lastSeen, addedAt: d.addedAt, now: now);+ final tail = sameName && d.fingerprint.isNotEmpty ? ' · ${d.fingerprint.split('·').first}…' : '';+ return '$what · $when$tail';+}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 18693033b..fc47dedef 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -5818,7 +5818,8 @@ class AppNotifier extends ChangeNotifier {systemNotifications.postNotice(id: 'harness-device:${notice.pub}',title: 'New device on your account',- body: '${notice.sentence} Not yours? Remove it in Settings ▸ Devices.',+ body: '${notice.sentence} Not yours? Remove it in Settings ▸ Your devices.',+ devicePub: notice.pub,);notifyListeners();}@@ -13442,7 +13443,8 @@ class AppNotifier extends ChangeNotifier {if (viewer == null) {final pub = payload['pub'], label = payload['label'], kind = payload['kind'];if (pub is String && kind is String) {- _announceDevice(NewDeviceNotice(pub: pub, label: label is String ? label : '', kind: kind));+ final fp = payload['fingerprint'];+ _announceDevice(NewDeviceNotice(pub: pub, label: label is String ? label : '', kind: kind, frameFingerprint: fp is String ? fp : null));}}break;diff --git a/desktop/lib/widgets/new_device_notice.dart b/desktop/lib/widgets/new_device_notice.dartindex f50ec4898..331abdc34 100644--- a/desktop/lib/widgets/new_device_notice.dart+++ b/desktop/lib/widgets/new_device_notice.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:harness/shared/theme/app_icons.dart';+import '../settings/sections/account_device_detail.dart';import '../settings/settings_screen.dart';import '../settings/settings_section.dart';import '../shared/theme/app_theme.dart' as grid;@@ -57,15 +58,18 @@ class NewDeviceNotice extends StatelessWidget {const SizedBox(width: 6),OutlinedButton(key: const Key('new-device-review'),+ // One new device goes straight to its key code; several go to the list, where each is a row.onPressed: () => unawaited(- showSettingsScreen(- context,- notifier,- initialSection: SettingsSection.accountDevices,- source: 'new-device-notice',- ),+ more == 0+ ? showAccountDeviceDetail(context, notifier, pub: notice.pub, isNew: true)+ : showSettingsScreen(+ context,+ notifier,+ initialSection: SettingsSection.accountDevices,+ source: 'new-device-notice',+ ),),- child: const Text('Review devices'),+ child: Text(more == 0 ? 'Review' : 'Review devices'),),],),diff --git a/desktop/test/account_device_detail_test.dart b/desktop/test/account_device_detail_test.dartnew file mode 100644index 000000000..f6e3235ea--- /dev/null+++ b/desktop/test/account_device_detail_test.dart@@ -0,0 +1,248 @@+// One device in full (Settings ▸ Your devices ▸ a row, the banner's Review, a notification click):+// its facts, its whole key code, how to compare it, and what can be done about it.+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/settings/sections/account_device_detail.dart';+import 'package:harness/shared/widgets/fingerprint_text.dart';+import 'package:harness/state/account_devices.dart';++import 'support/devices_app.dart';++const fp = fakeFingerprint;++void main() {+ late FakeDevicesApp app;++ setUp(() => app = FakeDevicesApp());+ tearDown(() => app.dispose());++ /// Opens the detail from a button, as the list and the banner do; [mine] counts `onMine` calls.+ Future<List<String>> open(+ WidgetTester tester, {+ required String pub,+ AccountDevice? device,+ bool isNew = false,+ }) async {+ final mine = <String>[];+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => unawaited(+ showAccountDeviceDetail(+ context,+ app,+ pub: pub,+ device: device,+ isNew: isNew,+ onMine: () => mine.add(pub),+ ),+ ),+ child: const Text('open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pump();+ await tester.pump();+ return mine;+ }++ testWidgets(+ 'an app: kind, added, last active, the code and how to check it on the app',+ (tester) async {+ final seen = DateTime.now().subtract(const Duration(days: 2, hours: 1));+ await open(+ tester,+ pub: 'p1',+ device: fakeDevice(+ 'p1',+ seen: seen,+ added: DateTime(2026, 9, 1, 9, 30),+ ),+ );+ expect(find.text('iPad'), findsOneWidget);+ expect(find.text('Kind'), findsOneWidget);+ expect(find.text('App'), findsOneWidget);+ expect(find.text('1 Sep 2026, 09:30'), findsOneWidget);+ expect(find.text('2 days ago'), findsOneWidget);+ expect(find.text('Machine'), findsNothing);+ expect(find.text(fp), findsOneWidget);+ expect(find.byKey(const Key('device-detail-copy')), findsOneWidget);+ expect(+ find.text(fingerprintHowToCompare(computer: false)),+ findsOneWidget,+ );+ expect(find.byKey(const Key('device-detail-remove')), findsOneWidget);+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);+ expect(app.loads, 0, reason: 'the row it came from is used as is');+ },+ );++ testWidgets(+ 'a computer: its machine, no last active when unknown, the CLI route',+ (tester) async {+ await open(+ tester,+ pub: 'box',+ device: fakeDevice('box', label: 'box9', kind: 'machine'),+ );+ expect(find.text('Computer'), findsOneWidget);+ expect(find.text('abcdef01'), findsOneWidget);+ expect(find.text('Last active'), findsNothing);+ expect(+ find.text(fingerprintHowToCompare(computer: true)),+ findsOneWidget,+ );+ },+ );++ testWidgets('this device: no Remove, only Close', (tester) async {+ await open(tester, pub: 'me', device: fakeDevice('me', self: true));+ expect(find.byKey(const Key('device-detail-remove')), findsNothing);+ await tester.tap(find.byKey(const Key('device-detail-close')));+ await tester.pump();+ expect(find.text(fp), findsNothing);+ });++ testWidgets('It’s mine dismisses the notice, tells the list, and closes', (+ tester,+ ) async {+ app.newDevices.add(+ const NewDeviceNotice(pub: 'p1', label: 'iPad', kind: 'viewer'),+ );+ final mine = await open(+ tester,+ pub: 'p1',+ device: fakeDevice('p1'),+ isNew: true,+ );+ await tester.tap(find.byKey(const Key('device-detail-mine')));+ await tester.pump();+ expect(app.newDevices, isEmpty);+ expect(mine, ['p1']);+ expect(find.text(fp), findsNothing);+ });++ testWidgets('Remove asks first; a no leaves the device alone', (+ tester,+ ) async {+ await open(tester, pub: 'p1', device: fakeDevice('p1'));+ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pump();+ expect(find.text('Remove iPad?'), findsOneWidget);+ expect(find.text(removeDeviceDetail), findsOneWidget);+ await tester.tap(find.text('Cancel'));+ await tester.pump();+ expect(app.removed, isEmpty);+ expect(find.text(fp), findsOneWidget);+ });++ testWidgets('Remove, confirmed, takes the device out and closes', (+ tester,+ ) async {+ await open(tester, pub: 'p1', device: fakeDevice('p1'));+ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pump();+ await tester.tap(find.byKey(const Key('account-device-confirm')));+ await tester.pump();+ await tester.pump();+ expect(app.removed, ['p1']);+ expect(find.text(fp), findsNothing);+ expect(find.text('Remove iPad?'), findsNothing);+ });++ testWidgets('a removal that fails says why and stays open to try again', (+ tester,+ ) async {+ app.removeError = 'UNAVAILABLE';+ await open(tester, pub: 'p1', device: fakeDevice('p1'));+ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pump();+ await tester.tap(find.byKey(const Key('account-device-confirm')));+ await tester.pump();+ await tester.pump();+ expect(app.removed, ['p1']);+ expect(+ find.text("Couldn't remove iPad (UNAVAILABLE). Try again."),+ findsOneWidget,+ );+ expect(find.text(fp), findsOneWidget);+ expect(find.text('Remove'), findsOneWidget);+ });++ testWidgets(+ 'from the banner: the notice stands in while the list loads, then the list row takes over',+ (tester) async {+ app.loadGate = Completer<void>();+ app.newDevices.add(+ const NewDeviceNotice(+ pub: 'p1',+ label: 'Test iPad',+ kind: 'viewer',+ frameFingerprint: fp,+ ),+ );+ app.devices = AccountDevices(+ devices: [+ fakeDevice(+ 'p1',+ label: 'Test iPad',+ added: DateTime(2026, 9, 30, 8, 5),+ ),+ ],+ );+ await open(tester, pub: 'p1', isNew: true);+ expect(find.text('Test iPad'), findsOneWidget);+ expect(find.text(fp), findsOneWidget);+ expect(find.text('Added'), findsNothing);+ expect(find.byKey(const Key('device-detail-mine')), findsOneWidget);+ app.loadGate!.complete();+ await tester.pump();+ await tester.pump();+ expect(app.loads, 1);+ expect(find.text('30 Sep 2026, 08:05'), findsOneWidget);+ expect(find.text(fp), findsOneWidget);+ },+ );++ testWidgets('a list that cannot be read leaves the notice standing in', (+ tester,+ ) async {+ app.loadError = StateError('daemon down');+ app.newDevices.add(+ const NewDeviceNotice(+ pub: 'p1',+ label: 'Test iPad',+ kind: 'machine',+ frameFingerprint: fp,+ ),+ );+ await open(tester, pub: 'p1', isNew: true);+ await tester.pump();+ expect(find.text('Test iPad'), findsOneWidget);+ expect(find.text('Computer'), findsOneWidget);+ expect(find.text(fp), findsOneWidget);+ });++ testWidgets('a device no longer on the account says so, with only Close', (+ tester,+ ) async {+ app.devices = AccountDevices(devices: [fakeDevice('other')]);+ await open(tester, pub: 'gone');+ await tester.pump();+ expect(+ find.text('This device is no longer on your account.'),+ findsOneWidget,+ );+ expect(find.byKey(const Key('device-detail-remove')), findsNothing);+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);+ expect(find.byKey(const Key('device-detail-close')), findsOneWidget);+ expect(find.byType(FingerprintText), findsNothing);+ });+}diff --git a/desktop/test/account_devices_section_test.dart b/desktop/test/account_devices_section_test.dartindex 72ba759d0..885e0fe1c 100644--- a/desktop/test/account_devices_section_test.dart+++ b/desktop/test/account_devices_section_test.dart@@ -4,8 +4,11 @@ import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';import 'package:harness/settings/sections/account_devices_section.dart';import 'package:harness/state/account_devices.dart';+import 'package:harness/shared/widgets/fingerprint_text.dart';import 'package:harness/state/app_state.dart';+import 'support/devices_app.dart';+/// Settings ▸ Your devices: opening it is reviewing the devices the banner announced.void main() {testWidgets('opening the devices list takes the new-device banner down', (tester) async {@@ -21,4 +24,132 @@ void main() {await tester.pumpWidget(const SizedBox());await tester.pump(const Duration(minutes: 1));});+ group('the list', () {+ final now = DateTime.now();+ late FakeDevicesApp app;++ setUp(() {+ app = FakeDevicesApp()+ ..devices = AccountDevices(devices: [+ fakeDevice('old', label: 'Old laptop', kind: 'machine', added: now.subtract(const Duration(days: 300)),+ seen: now.subtract(const Duration(days: 40)), fingerprint: 'AAAA·0001·0001·0001'),+ fakeDevice('me', label: 'MacBook', kind: 'machine', self: true, added: now.subtract(const Duration(days: 200)),+ seen: now, fingerprint: 'E2FB·0DF5·5FD8·E6C7'),+ fakeDevice('phone-a', label: 'iPhone', added: now.subtract(const Duration(days: 100)),+ seen: now.subtract(const Duration(minutes: 2)), fingerprint: 'BBBB·0002·0002·0002'),+ fakeDevice('phone-b', label: 'iPhone', added: now.subtract(const Duration(days: 50)), fingerprint: 'CCCC·0003·0003·0003'),+ fakeDevice('twin', label: 'MacBook', added: now.subtract(const Duration(days: 30)),+ seen: now.subtract(const Duration(days: 3)), fingerprint: 'DDDD·0004·0004·0004'),+ fakeDevice('new', label: 'Test iPad', added: now.subtract(const Duration(hours: 3)), fingerprint: 'EEEE·0005·0005·0005'),+ ]);+ app.newDevices.add(const NewDeviceNotice(pub: 'new', label: 'Test iPad', kind: 'viewer'));+ });+ tearDown(() => app.dispose());++ Future<void> openList(WidgetTester tester) async {+ tester.view.physicalSize = const Size(1200, 1600);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));+ await tester.pump();+ await tester.pump();+ }++ String detailOf(WidgetTester tester, String pub) {+ final row = find.byKey(ValueKey('account-device-$pub'));+ return tester.widgetList<Text>(find.descendant(of: row, matching: find.byType(Text))).map((t) => t.data ?? '').join('\n');+ }++ testWidgets('this device is a card on top with its whole code, and is not a row again', (tester) async {+ await openList(tester);+ final card = find.byKey(const Key('account-device-this'));+ expect(card, findsOneWidget);+ expect(find.descendant(of: card, matching: find.text('MacBook')), findsOneWidget);+ expect(find.descendant(of: card, matching: find.text('This is the code your other devices show for this device.')), findsOneWidget);+ expect(find.descendant(of: card, matching: find.text('E2FB·0DF5·5FD8·E6C7')), findsOneWidget);+ expect(find.descendant(of: card, matching: find.byKey(const Key('this-device-copy'))), findsOneWidget);+ expect(find.byKey(const ValueKey('account-device-me')), findsNothing);+ expect(find.text('This device'), findsOneWidget);+ });++ testWidgets('rows: new first with a badge, then by activity; no whole code, the start of it only for a shared name', (tester) async {+ await openList(tester);+ double top(String pub) => tester.getTopLeft(find.byKey(ValueKey('account-device-$pub'))).dy;+ final order = ['new', 'phone-a', 'twin', 'old', 'phone-b'];+ for (var i = 1; i < order.length; i++) {+ expect(top(order[i - 1]), lessThan(top(order[i])), reason: '${order[i - 1]} above ${order[i]}');+ }+ expect(top('new'), greaterThan(tester.getTopLeft(find.byKey(const Key('account-device-this'))).dy));+ // Opening the list took the banner down, but this visit still shows which device was new.+ expect(app.newDevices, isEmpty);+ expect(find.descendant(of: find.byKey(const ValueKey('account-device-new')), matching: find.text('New')), findsOneWidget);+ expect(find.text('New'), findsOneWidget);++ expect(detailOf(tester, 'new'), contains('App · added 3 hours ago'));+ expect(detailOf(tester, 'phone-a'), contains('App · active now · BBBB…'));+ expect(detailOf(tester, 'phone-b'), contains('App · added 7 weeks ago · CCCC…'));+ // Shares its name with this device's card.+ expect(detailOf(tester, 'twin'), contains('App · last active 3 days ago · DDDD…'));+ expect(detailOf(tester, 'old'), contains('Computer · last active 5 weeks ago'));+ expect(detailOf(tester, 'old'), isNot(contains('AAAA')));+ expect(detailOf(tester, 'new'), isNot(contains('EEEE')));+ for (final pub in order) {+ expect(detailOf(tester, pub), isNot(matches(RegExp(r'[0-9A-F]{4}·[0-9A-F]{4}'))), reason: pub);+ }+ final everything = tester.widgetList<Text>(find.byType(Text)).map((t) => t.data ?? '').join('\n');+ expect(everything, isNot(matches(RegExp(r'\d{4}-\d{2}-\d{2}'))));+ });++ testWidgets('a row, or its Details button, opens that device with its whole code', (tester) async {+ await openList(tester);+ await tester.tap(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('Old laptop')));+ await tester.pump();+ await tester.pump();+ expect(find.text('AAAA·0001·0001·0001'), findsOneWidget);+ expect(find.text(fingerprintHowToCompare(computer: true)), findsOneWidget);+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);+ await tester.tap(find.byKey(const Key('device-detail-close')));+ await tester.pump();+ expect(find.text('AAAA·0001·0001·0001'), findsNothing);++ await tester.tap(find.byKey(const ValueKey('account-device-details-phone-b')));+ await tester.pump();+ await tester.pump();+ expect(find.text('CCCC·0003·0003·0003'), findsOneWidget);+ expect(find.text(fingerprintHowToCompare(computer: false)), findsOneWidget);+ expect(app.loads, 1, reason: 'the detail uses the row, it does not read the list again');+ });++ testWidgets('It’s mine in a new device’s detail takes its badge off; closing without it does not', (tester) async {+ await openList(tester);+ final badge = find.descendant(of: find.byKey(const ValueKey('account-device-new')), matching: find.text('New'));+ await tester.tap(find.byKey(const ValueKey('account-device-details-new')));+ await tester.pump();+ await tester.pump();+ await tester.tap(find.byKey(const Key('device-detail-close')));+ await tester.pump();+ expect(badge, findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('account-device-details-new')));+ await tester.pump();+ await tester.pump();+ await tester.tap(find.byKey(const Key('device-detail-mine')));+ await tester.pump();+ expect(find.text('EEEE·0005·0005·0005'), findsNothing);+ expect(badge, findsNothing);+ });++ testWidgets('Remove on a row still asks first, then takes the device out of the list', (tester) async {+ await openList(tester);+ await tester.tap(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('Remove')));+ await tester.pump();+ expect(find.text('Remove Old laptop?'), findsOneWidget);+ await tester.tap(find.byKey(const Key('account-device-confirm')));+ await tester.pump();+ await tester.pump();+ await tester.pump();+ expect(app.removed, ['old']);+ expect(find.byKey(const ValueKey('account-device-old')), findsNothing);+ });+ });}diff --git a/desktop/test/account_devices_test.dart b/desktop/test/account_devices_test.dartindex 69a451522..0f2290002 100644--- a/desktop/test/account_devices_test.dart+++ b/desktop/test/account_devices_test.dart@@ -1,4 +1,6 @@import 'package:flutter_test/flutter_test.dart';+import 'package:harness/e2ee/bytes.dart';+import 'package:harness/e2ee/keys.dart' as keys;import 'package:harness/state/account_devices.dart';/// The Devices list's model (`lib/state/account_devices.dart`): what a daemon answers, and which apps@@ -24,6 +26,18 @@ void main() {expect(devices.devices[1].lastSeen, isNull);});+ test('a daemon row carrying seq and firstSeen (newer daemons) reads the same as one without', () {+ final devices = AccountDevices.fromDaemon({+ 'members': [+ {...row('new'), 'seq': 3, 'firstSeen': DateTime(2026, 9, 30).millisecondsSinceEpoch},+ {...row('me', self: true), 'seq': 2},+ ],+ })!;+ expect(devices.devices.map((d) => d.pub), ['new', 'me']);+ expect(devices.devices.first.fingerprint, 'FP');+ expect(devices.devices.last.self, isTrue);+ });+test('offers only apps seen long ago — never this one, a computer, or one never recorded', () {final long = DateTime(2026, 5, 1).millisecondsSinceEpoch;final devices = AccountDevices.fromDaemon({@@ -37,4 +51,62 @@ void main() {})!;expect(devices.unused(now).map((d) => d.pub), ['stale']);});+ AccountDevice device(String pub, {String? label, String kind = 'viewer', bool self = false, DateTime? added, DateTime? seen, String fp = 'E2FB·0DF5·5FD8·E6C7'}) => AccountDevice(+ pub: pub, label: label ?? pub, kind: kind, machineId: kind == 'machine' ? 'abcdef0123456789' : '',+ addedAt: added ?? DateTime(2026, 1, 1), fingerprint: fp, self: self, lastSeen: seen,+ );++ test('lists this device apart, then the new ones newest first, then the rest by last activity', () {+ final devices = AccountDevices(devices: [+ device('old-a', added: DateTime(2026, 2, 1)),+ device('me', self: true, seen: now),+ device('new-1', added: DateTime(2026, 9, 28)),+ device('busy', added: DateTime(2025, 1, 1), seen: DateTime(2026, 9, 30)),+ device('new-2', added: DateTime(2026, 9, 30)),+ device('old-b', added: DateTime(2026, 2, 1)),+ // In the new set but added long ago: new devices sort by when they were added, not by activity.+ device('new-old', added: DateTime(2025, 6, 1), seen: now),+ ]);+ expect(devices.self?.pub, 'me');+ expect(devices.listed({'new-1', 'new-2', 'new-old'}).map((d) => d.pub),+ ['new-2', 'new-1', 'new-old', 'busy', 'old-a', 'old-b']);+ // Nothing new: activity alone; equal times keep the log's order, whatever the sort does.+ expect(devices.listed({}).map((d) => d.pub), ['new-old', 'busy', 'new-2', 'new-1', 'old-a', 'old-b']);+ expect(const AccountDevices(devices: []).self, isNull);+ });++ test('a name shared by two devices (this one included, blank names alike) is a shared name', () {+ final devices = AccountDevices(devices: [+ device('a', label: 'iPhone '), device('b', label: 'iPhone'), device('c', label: 'box'),+ device('d', label: ''), device('e', label: ' '),+ // This device counts: its card shows its name, so a row going by the same name needs telling apart.+ device('me', label: 'MacBook', self: true), device('f', label: 'MacBook'),+ ]);+ expect(devices.sharedNames, {'iPhone', '', 'MacBook'});+ });++ test('a row says what and when, with only the start of the key code when its name is shared', () {+ final app = device('a', seen: now.subtract(const Duration(days: 2)));+ expect(deviceDetailLine(app, now: now, sameName: false), 'App · last active 2 days ago');+ expect(deviceDetailLine(app, now: now, sameName: true), 'App · last active 2 days ago · E2FB…');+ final box = device('b', kind: 'machine', seen: now.subtract(const Duration(minutes: 4)));+ expect(deviceDetailLine(box, now: now, sameName: false), 'Computer · active now');+ final quiet = device('c', added: now.subtract(const Duration(days: 21)));+ expect(deviceDetailLine(quiet, now: now, sameName: false), 'App · added 3 weeks ago');+ for (final line in [deviceDetailLine(app, now: now, sameName: true), deviceDetailLine(box, now: now, sameName: true)]) {+ expect(line, isNot(contains('0DF5')));+ expect(line, isNot(matches(RegExp(r'\d{4}-\d{2}-\d{2}'))));+ }+ });++ test('a notice shows the key code the frame carried, else the one its key works out to', () {+ final pub = b64e(List<int>.generate(32, (i) => i * 7 % 256));+ expect(const NewDeviceNotice(pub: 'x', label: 'iPad', kind: 'viewer', frameFingerprint: 'AAAA·BBBB·CCCC·DDDD').fingerprint,+ 'AAAA·BBBB·CCCC·DDDD');+ final computed = NewDeviceNotice(pub: pub, label: 'iPad', kind: 'viewer').fingerprint;+ expect(computed, keys.fingerprint(b64d(pub)));+ expect(computed, matches(RegExp(r'^[0-9A-F]{4}(·[0-9A-F]{4}){3}$')));+ expect(NewDeviceNotice(pub: pub, label: 'iPad', kind: 'viewer', frameFingerprint: '').fingerprint, computed);+ expect(const NewDeviceNotice(pub: '%%not base64%%', label: '', kind: 'viewer').fingerprint, '');+ });}diff --git a/desktop/test/fingerprint_text_test.dart b/desktop/test/fingerprint_text_test.dartnew file mode 100644index 000000000..98b7a77e3--- /dev/null+++ b/desktop/test/fingerprint_text_test.dart@@ -0,0 +1,92 @@+// A device's key code as the detail and the "This device" card show it: the exact string on the+// clipboard, a spelled-out label for a screen reader, and the comparison wording.+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/widgets/fingerprint_text.dart';++const _fp = 'E2FB·0DF5·5FD8·E6C7';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ String? clipboard;+ var failCopy = false;++ setUp(() {+ clipboard = null;+ failCopy = false;+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.setData') {+ if (failCopy) throw PlatformException(code: 'no-clipboard');+ clipboard = (call.arguments as Map)['text'] as String?;+ }+ return null;+ });+ });+ tearDown(+ () => messenger.setMockMethodCallHandler(SystemChannels.platform, null),+ );++ Future<void> pump(WidgetTester tester) => tester.pumpWidget(+ const MaterialApp(+ home: Scaffold(body: FingerprintText(_fp, copyKey: Key('copy'))),+ ),+ );++ testWidgets('Copy puts the exact code on the clipboard and says so for 3 s', (+ tester,+ ) async {+ await pump(tester);+ expect(find.text(_fp), findsOneWidget);+ await tester.tap(find.byKey(const Key('copy')));+ await tester.pump();+ expect(clipboard, _fp);+ expect(find.text('Copied'), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 2900));+ expect(find.text('Copied'), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.text('Copied'), findsNothing);+ expect(find.text('Copy'), findsOneWidget);+ });++ testWidgets('a clipboard that refuses says to try again', (tester) async {+ failCopy = true;+ await pump(tester);+ await tester.tap(find.byKey(const Key('copy')));+ await tester.pump();+ expect(clipboard, isNull);+ expect(find.text('Couldn’t copy. Try again'), findsOneWidget);+ await tester.pump(const Duration(seconds: 3));+ expect(find.text('Copy'), findsOneWidget);+ });++ testWidgets(+ 'a screen reader hears the code group by group, letter by letter',+ (tester) async {+ final semantics = tester.ensureSemantics();+ await pump(tester);+ expect(+ find.bySemanticsLabel('Key code E 2 F B, 0 D F 5, 5 F D 8, E 6 C 7'),+ findsOneWidget,+ );+ semantics.dispose();+ },+ );++ test('the explanation names the device kind and, on a computer, the CLI', () {+ expect(+ fingerprintSpoken(_fp),+ 'Key code E 2 F B, 0 D F 5, 5 F D 8, E 6 C 7',+ );+ expect(+ fingerprintHowToCompare(computer: false),+ 'This device’s own key code. Open Your devices on that device — the code under “This device” must match.',+ );+ expect(+ fingerprintHowToCompare(computer: true),+ 'This device’s own key code. Open Your devices on that computer — the code under “This device” must match — or run harness status on it.',+ );+ });+}diff --git a/desktop/test/new_device_notice_test.dart b/desktop/test/new_device_notice_test.dartnew file mode 100644index 000000000..afd06e67b--- /dev/null+++ b/desktop/test/new_device_notice_test.dart@@ -0,0 +1,143 @@+// The band a new device raises across the window: one device goes straight to its key code, several+// go to Settings ▸ Your devices, where each is a row.+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/settings/sections/account_devices_section.dart';+import 'package:harness/state/account_devices.dart' hide NewDeviceNotice;+import 'package:harness/state/account_devices.dart'+ as model+ show NewDeviceNotice;+import 'package:harness/widgets/new_device_notice.dart';++import 'support/devices_app.dart';++void main() {+ late FakeDevicesApp app;++ setUp(() => app = FakeDevicesApp());+ tearDown(() => app.dispose());++ Future<void> mount(WidgetTester tester) async {+ tester.view.physicalSize = const Size(1200, 900);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ // As the app shell draws it: rebuilt whenever the app changes.+ body: ListenableBuilder(+ listenable: app,+ builder: (context, _) => Column(+ children: [+ NewDeviceNotice(notifier: app),+ const Expanded(child: SizedBox()),+ ],+ ),+ ),+ ),+ ),+ );+ }++ testWidgets('one new device: Review opens that device, offering It’s mine', (+ tester,+ ) async {+ app.newDevices.add(+ const model.NewDeviceNotice(+ pub: 'p1',+ label: 'Test iPad',+ kind: 'viewer',+ frameFingerprint: 'AAAA·BBBB·CCCC·DDDD',+ ),+ );+ app.devices = AccountDevices(+ devices: [+ fakeDevice(+ 'p1',+ label: 'Test iPad',+ fingerprint: 'AAAA·BBBB·CCCC·DDDD',+ ),+ ],+ );+ await mount(tester);+ final review = find.byKey(const Key('new-device-review'));+ expect(+ find.descendant(of: review, matching: find.text('Review')),+ findsOneWidget,+ );+ // The banner's sentence carries no key code.+ expect(find.textContaining('AAAA'), findsNothing);+ await tester.tap(review);+ await tester.pump();+ await tester.pump();+ expect(find.text('AAAA·BBBB·CCCC·DDDD'), findsOneWidget);+ expect(find.byKey(const Key('device-detail-mine')), findsOneWidget);+ expect(find.byType(AccountDevicesSection), findsNothing);+ // It’s mine there is the banner's It’s mine.+ await tester.tap(find.byKey(const Key('device-detail-mine')));+ await tester.pump();+ expect(app.newDevices, isEmpty);+ expect(find.byKey(const Key('new-device-notice')), findsNothing);+ });++ testWidgets(+ 'two new devices: Review devices opens the list, the new ones on top',+ (tester) async {+ final now = DateTime.now();+ app.newDevices+ ..add(+ const model.NewDeviceNotice(+ pub: 'p1',+ label: 'Test iPad',+ kind: 'viewer',+ ),+ )+ ..add(+ const model.NewDeviceNotice(+ pub: 'p2',+ label: 'box9',+ kind: 'machine',+ ),+ );+ app.devices = AccountDevices(+ devices: [+ fakeDevice(+ 'old',+ label: 'Old phone',+ added: now.subtract(const Duration(days: 90)),+ seen: now,+ ),+ fakeDevice(+ 'p1',+ label: 'Test iPad',+ added: now.subtract(const Duration(hours: 2)),+ ),+ fakeDevice(+ 'p2',+ label: 'box9',+ kind: 'machine',+ added: now.subtract(const Duration(hours: 1)),+ ),+ ],+ );+ await mount(tester);+ expect(find.textContaining('(+1 more)'), findsOneWidget);+ final review = find.byKey(const Key('new-device-review'));+ expect(+ find.descendant(of: review, matching: find.text('Review devices')),+ findsOneWidget,+ );+ await tester.tap(review);+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(find.byType(AccountDevicesSection), findsOneWidget);+ double top(String pub) =>+ tester.getTopLeft(find.byKey(ValueKey('account-device-$pub'))).dy;+ expect(top('p2'), lessThan(top('p1')));+ expect(top('p1'), lessThan(top('old')));+ expect(find.text('New'), findsNWidgets(2));+ expect(app.newDevices, isEmpty);+ },+ );+}diff --git a/desktop/test/relative_time_test.dart b/desktop/test/relative_time_test.dartnew file mode 100644index 000000000..52d148fd7--- /dev/null+++ b/desktop/test/relative_time_test.dart@@ -0,0 +1,54 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/relative_time.dart';++void main() {+ final now = DateTime(2026, 10, 1, 12);+ String ago(Duration d) => relativeAgo(now.subtract(d), now);++ test('relativeAgo follows the boundaries the CLI and mobile use', () {+ expect(ago(Duration.zero), 'just now');+ expect(ago(const Duration(seconds: 59)), 'just now');+ expect(ago(const Duration(minutes: 1)), '1 minute ago');+ expect(ago(const Duration(minutes: 59)), '59 minutes ago');+ expect(ago(const Duration(hours: 1)), '1 hour ago');+ expect(ago(const Duration(hours: 23)), '23 hours ago');+ expect(ago(const Duration(hours: 24)), 'yesterday');+ expect(ago(const Duration(hours: 47)), 'yesterday');+ expect(ago(const Duration(days: 2)), '2 days ago');+ expect(ago(const Duration(days: 13)), '13 days ago');+ expect(ago(const Duration(days: 14)), '2 weeks ago');+ expect(ago(const Duration(days: 59)), '8 weeks ago');+ expect(ago(const Duration(days: 60)), '2 months ago');+ expect(ago(const Duration(days: 364)), '12 months ago');+ expect(ago(const Duration(days: 365)), 'over a year ago');+ expect(relativeAgo(now.add(const Duration(minutes: 5)), now), 'just now');+ });++ test('fullDateTime spells the local date and 24-hour time', () {+ expect(fullDateTime(DateTime(2026, 10, 1, 14, 5)), '1 Oct 2026, 14:05');+ });++ test('activityPhrase says active now, last active, or added', () {+ final added = now.subtract(const Duration(days: 30));+ expect(+ activityPhrase(+ lastSeen: now.subtract(const Duration(minutes: 1)),+ addedAt: added,+ now: now,+ ),+ 'active now',+ );+ expect(+ activityPhrase(+ lastSeen: now.subtract(const Duration(days: 2)),+ addedAt: added,+ now: now,+ ),+ 'last active 2 days ago',+ );+ expect(+ activityPhrase(addedAt: now.subtract(const Duration(days: 21)), now: now),+ 'added 3 weeks ago',+ );+ });+}diff --git a/desktop/test/support/devices_app.dart b/desktop/test/support/devices_app.dartnew file mode 100644index 000000000..b4425f098--- /dev/null+++ b/desktop/test/support/devices_app.dart@@ -0,0 +1,70 @@+import 'dart:async';++import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/state/account_devices.dart';+import 'package:harness/state/app_state.dart';++const fakeFingerprint = 'E2FB·0DF5·5FD8·E6C7';++/// An app whose account device list and removal are canned, so the Devices screens' own code runs+/// unmodified with no daemon.+class FakeDevicesApp extends AppNotifier {+ FakeDevicesApp()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );++ AccountDevices? devices;+ Completer<void>? loadGate;+ Object? loadError;+ String? removeError;+ final removed = <String>[];+ int loads = 0;++ @override+ Future<AccountDevices?> loadDevices() async {+ loads++;+ await loadGate?.future;+ if (loadError case final error?) throw error;+ return devices;+ }++ @override+ Future<String?> removeDevice(String pub) async {+ removed.add(pub);+ if (removeError == null) {+ newDevices.removeWhere((d) => d.pub == pub);+ devices = AccountDevices(+ devices: [+ for (final d in devices?.devices ?? const <AccountDevice>[])+ if (d.pub != pub) d,+ ],+ );+ }+ devicesRevision++;+ notifyListeners();+ return removeError;+ }+}++AccountDevice fakeDevice(+ String pub, {+ String label = 'iPad',+ String kind = 'viewer',+ bool self = false,+ DateTime? added,+ DateTime? seen,+ String fingerprint = fakeFingerprint,+}) => AccountDevice(+ pub: pub,+ label: label,+ kind: kind,+ machineId: kind == 'machine' ? 'abcdef0123456789' : '',+ addedAt: added ?? DateTime(2026, 9, 1, 9, 30),+ fingerprint: fingerprint,+ self: self,+ lastSeen: seen,+);diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dartindex da12f5ca7..fd852aa4c 100644--- a/desktop/test/system_notifications_test.dart+++ b/desktop/test/system_notifications_test.dart@@ -380,6 +380,63 @@ void main() {expect(taps, ['m1/a1']);mac.onTap = null;});++ test('a click on a device notice comes back as that device', () async {+ final mac = MacSystemNotifier(channel: channel);+ final taps = <String>[];+ mac.onTap = (m, a) => taps.add('$m/$a');+ Future<void> tap(Map<String, String> args) =>+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(+ MethodCall('tapped', args),+ ),+ (_) {},+ );+ await tap({'machineId': SystemNotifications.deviceNoticeMachine, 'agentId': 'pub-1'});+ // A device notice with no key in it opens nothing.+ await tap({'machineId': SystemNotifications.deviceNoticeMachine, 'agentId': ''});+ expect(taps, ['@device/pub-1']);+ mac.onTap = null;+ });+ });++ group('device notices', () {+ test('carry the device in the click slots; an account notice without one carries nothing', () async {+ final os = _Recorder();+ final system = SystemNotifications(store: store(), notifier: os);+ system.postNotice(id: 'harness-device:p', title: 'New device on your account', body: 'b', devicePub: 'p');+ system.postNotice(id: 'harness-other', title: 't', body: 'b');+ await Future<void>.delayed(Duration.zero);+ expect(SystemNotifications.deviceNoticeMachine, '@device');+ expect(os.shown.map((s) => (s.machineId, s.agentId)), [('@device', 'p'), ('', '')]);+ });++ test('a device the daemon announces reaches the system, naming the device and where to remove it', () async {+ final os = _Recorder();+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ systemNotifications: SystemNotifications(store: store(), notifier: os),+ );+ addTearDown(app.dispose);+ app.machines = [_machine];+ app.machineStates['m1'] = MachineState(_machine);+ await app.handleEventForTest('m1', {+ 'type': 'device_key_added',+ 'payload': {'pub': 'pub-1', 'label': 'Test iPad', 'kind': 'viewer', 'fingerprint': 'AAAA·BBBB·CCCC·DDDD'},+ });+ await Future<void>.delayed(Duration.zero);+ expect(app.newDevices.single.pub, 'pub-1');+ expect(app.newDevices.single.fingerprint, 'AAAA·BBBB·CCCC·DDDD');+ final shown = os.shown.single;+ expect(shown.title, 'New device on your account');+ expect(shown.body, endsWith('Not yours? Remove it in Settings ▸ Your devices.'));+ expect(shown.body, contains('Test iPad'));+ expect((shown.machineId, shown.agentId), ('@device', 'pub-1'));+ });});group('Linux', () {diff --git a/mobile/lib/core/relative_time.dart b/mobile/lib/core/relative_time.dartnew file mode 100644index 000000000..d11d742d0--- /dev/null+++ b/mobile/lib/core/relative_time.dart@@ -0,0 +1,54 @@+/// A device seen this recently reads as "active now" rather than "5 minutes ago".+const activeNowWithin = Duration(minutes: 5);++const _months = [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+];++String _ago(int n, String unit) => '$n $unit${n == 1 ? '' : 's'} ago';++/// "2 days ago". Coarse on purpose: the person is deciding "do I recognise this device", not auditing+/// a log. The same wording as `harness devices list` and the mobile app, so one device reads the same+/// everywhere. A time in the future (clock skew) reads as "just now".+String relativeAgo(DateTime at, DateTime now) {+ final d = now.difference(at);+ if (d.isNegative || d < const Duration(minutes: 1)) return 'just now';+ if (d < const Duration(hours: 1)) return _ago(d.inMinutes, 'minute');+ if (d < const Duration(days: 1)) return _ago(d.inHours, 'hour');+ if (d < const Duration(days: 2)) return 'yesterday';+ final days = d.inDays;+ if (days < 14) return '$days days ago';+ if (days < 60) return '${days ~/ 7} weeks ago';+ if (days < 365) return '${days ~/ 30} months ago';+ return 'over a year ago';+}++/// `1 Oct 2026, 14:05` in local time — spelled out so it reads the same in every locale.+String fullDateTime(DateTime at) {+ final local = at.toLocal();+ String two(int n) => n.toString().padLeft(2, '0');+ return '${local.day} ${_months[local.month - 1]} ${local.year}, ${two(local.hour)}:${two(local.minute)}';+}++/// `active now` / `last active 2 days ago` / `added 3 weeks ago` (no session was ever recorded for it).+String activityPhrase({+ DateTime? lastSeen,+ required DateTime addedAt,+ required DateTime now,+}) {+ if (lastSeen == null) return 'added ${relativeAgo(addedAt, now)}';+ return now.difference(lastSeen) < activeNowWithin+ ? 'active now'+ : 'last active ${relativeAgo(lastSeen, now)}';+}diff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dartindex 695daf213..3525149ef 100644--- a/mobile/lib/notify/system_notices.dart+++ b/mobile/lib/notify/system_notices.dart@@ -36,8 +36,12 @@ abstract interface class SystemNotices {/// null by whoever acts on it.ValueNotifier<AgentRef?> get opened;+ /// The key of the device whose notice was tapped last — what the shell opens. Reset to null by+ /// whoever acts on it.+ ValueNotifier<String?> get openedDevice;+/// News about the ACCOUNT rather than an agent: a device joined it. [key] names the notice, so the- /// same news posted twice replaces itself. Tapping it just opens the app, where the banner waits.+ /// same news posted twice replaces itself. Tapping it opens that device's page ([key] is its key).Future<void> showAccountNotice({required String key, required String title, required String body});}@@ -46,6 +50,9 @@ class SilentSystemNotices implements SystemNotices {@overridefinal opened = ValueNotifier<AgentRef?>(null);+ @override+ final openedDevice = ValueNotifier<String?>(null);+@overrideFuture<void> requestPermission() async {}@@ -59,6 +66,10 @@ class SilentSystemNotices implements SystemNotices {Future<void> showAccountNotice({required String key, required String title, required String body}) async {}}+/// What a device notice's payload starts with; the device's key follows. An agent notice's payload+/// is `machine\nagent`, so the two never read as each other.+const _devicePayload = 'device:';+/// The real centre, through flutter_local_notifications.////// Started lazily on first use, so a launch that never needs it — and every@@ -73,6 +84,9 @@ class LocalSystemNotices implements SystemNotices {@overridefinal opened = ValueNotifier<AgentRef?>(null);+ @override+ final openedDevice = ValueNotifier<String?>(null);+/// One Android channel per kind, so a person can silence finished turns and/// still hear questions — the two are not equally urgent. Also the iOS/// thread each kind is grouped under.@@ -121,6 +135,11 @@ class LocalSystemNotices implements SystemNotices {}void _open(String? payload) {+ // A device notice carries `device:<key>` — no newline, so it never reads as an agent's payload.+ if (payload != null && payload.startsWith(_devicePayload)) {+ openedDevice.value = payload.substring(_devicePayload.length);+ return;+ }final agent = decodeAgentPayload(payload);if (agent != null) opened.value = agent;}@@ -195,6 +214,7 @@ class LocalSystemNotices implements SystemNotices {),iOS: DarwinNotificationDetails(threadIdentifier: 'account-device'),),+ payload: '$_devicePayload$key',);} catch (error) {appLog.warn('notify', 'account notice failed', error: error);diff --git a/mobile/lib/phone/device_detail_page.dart b/mobile/lib/phone/device_detail_page.dartnew file mode 100644index 000000000..265fba675--- /dev/null+++ b/mobile/lib/phone/device_detail_page.dart@@ -0,0 +1,179 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/core/relative_time.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/viewer/device_log_sync.dart';++import 'fingerprint_text.dart';+import 'phone_sheet.dart';+import 'settings_row.dart';+import 'tty.dart';+import 'tty_controls.dart';++/// One device in full: its facts, its whole key code to compare on that device, and what to do about+/// it. [isNew] offers "It’s mine"; [onMine] tells the page that opened this one it was used.+class DeviceDetailPage extends StatefulWidget {+ const DeviceDetailPage({+ super.key,+ required this.notifier,+ required this.row,+ this.lastSeen,+ this.isNew = false,+ this.onMine,+ });++ final AppNotifier notifier;+ final DeviceLogRow row;++ /// When this key last opened a session (ms since the epoch), when the backend said.+ final int? lastSeen;+ final bool isNew;+ final VoidCallback? onMine;++ @override+ State<DeviceDetailPage> createState() => _DeviceDetailPageState();+}++class _DeviceDetailPageState extends State<DeviceDetailPage> {+ bool _removing = false;+ String? _error;++ DeviceLogRow get _row => widget.row;+ String get _name =>+ _row.member.label.trim().isEmpty ? 'Unnamed device' : _row.member.label;++ Future<void> _remove() async {+ final name = _row.member.label.isEmpty ? 'this device' : _row.member.label;+ final confirmed = await confirmPhoneAction(+ context,+ title: 'Remove $name?',+ message:+ 'It stops reaching your machines on every device, and is signed out. '+ 'Signing in on it again adds it back as a new device.',+ confirmLabel: 'Remove',+ icon: LucideIcons.shieldOff300,+ );+ if (!confirmed || !mounted) return;+ setState(() {+ _removing = true;+ _error = null;+ });+ final error = await widget.notifier.removeDevice(_row.member.pub);+ if (!mounted) return;+ if (error == null) {+ Navigator.of(context).pop();+ return;+ }+ setState(() {+ _removing = false;+ _error = "Couldn't remove $name. Try again.";+ });+ }++ void _mine() {+ widget.notifier.dismissNewDevice(_row.member.pub);+ widget.onMine?.call();+ Navigator.of(context).pop();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final member = _row.member;+ final isMachine = member.kind == 'machine';+ final lastSeen = widget.lastSeen;+ final now = DateTime.now();+ final fp = _row.fingerprint;+ return Scaffold(+ backgroundColor: tty.ground,+ body: SafeArea(+ bottom: false,+ child: ListView(+ padding: EdgeInsets.fromLTRB(+ Tty.origin,+ 12,+ Tty.origin,+ MediaQuery.paddingOf(context).bottom + 24,+ ),+ children: [+ TtyText(_name, size: TtySize.title, weight: FontWeight.w600),+ const SizedBox(height: 12),+ SettingsGroup(+ children: [+ SettingsRow(+ title: 'Kind',+ value: isMachine ? 'Computer' : 'App',+ ),+ SettingsRow(+ title: 'Added',+ value: fullDateTime(+ DateTime.fromMillisecondsSinceEpoch(member.addedAt),+ ),+ ),+ if (lastSeen != null)+ SettingsRow(+ title: 'Last active',+ value: relativeAgo(+ DateTime.fromMillisecondsSinceEpoch(lastSeen),+ now,+ ),+ ),+ if (isMachine && member.machineId.isNotEmpty)+ SettingsRow(+ title: 'Machine',+ value: member.machineId.substring(+ 0,+ member.machineId.length < 8 ? member.machineId.length : 8,+ ),+ ),+ ],+ ),+ if (fp.isNotEmpty) ...[+ const SizedBox(height: 16),+ FingerprintBlock(+ fp,+ large: true,+ copyKey: const Key('device-detail-copy'),+ ),+ const SizedBox(height: 8),+ // Wraps: the explanation is a sentence, not a terminal line.+ Text(+ fingerprintHowToCompare(computer: isMachine),+ style: tty.style(color: tty.dim),+ ),+ ],+ if (_error case final error?) ...[+ const SizedBox(height: 12),+ TtyText(error, color: tty.red),+ ],+ if (widget.isNew || !_row.self) ...[+ const SizedBox(height: 16),+ SettingsGroup(+ children: [+ if (widget.isNew)+ SettingsRow(+ key: const Key('device-detail-mine'),+ title: 'It’s mine',+ onTap: _removing ? null : _mine,+ ),+ if (!_row.self)+ SettingsRow(+ key: const Key('device-detail-remove'),+ title: _removing ? 'Removing…' : 'Remove this device',+ destructive: true,+ onTap: _removing ? null : () => unawaited(_remove()),+ ),+ ],+ ),+ ],+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/phone/device_rows.dart b/mobile/lib/phone/device_rows.dartnew file mode 100644index 000000000..2b05005be--- /dev/null+++ b/mobile/lib/phone/device_rows.dart@@ -0,0 +1,82 @@+import 'package:harness_mobile/core/relative_time.dart';+import 'package:harness_mobile/e2ee/bytes.dart';+import 'package:harness_mobile/e2ee/keys.dart' as keys;+import 'package:harness_mobile/viewer/device_log.dart';+import 'package:harness_mobile/viewer/device_log_sync.dart';++/// This phone's own row, which the Devices page shows on its own card rather than in the list.+DeviceLogRow? selfRow(List<DeviceLogRow> rows) {+ for (final row in rows) {+ if (row.self) return row;+ }+ return null;+}++/// The rows under the "This device" card: the new devices (those in [newPubs]) first, newest first,+/// then the rest by last activity ([seen], `{pub: ms}`), falling back to when they were added. Ties+/// keep log order — `List.sort` is not stable, so the index breaks them.+List<DeviceLogRow> orderDeviceRows(+ List<DeviceLogRow> rows,+ Map<String, int> seen,+ Set<String> newPubs,+) {+ final listed = [+ for (var i = 0; i < rows.length; i++)+ if (!rows[i].self)+ (index: i, row: rows[i], isNew: newPubs.contains(rows[i].member.pub)),+ ];+ int when(({int index, DeviceLogRow row, bool isNew}) r) => r.isNew+ ? r.row.member.addedAt+ : seen[r.row.member.pub] ?? r.row.member.addedAt;+ listed.sort((a, b) {+ if (a.isNew != b.isNew) return a.isNew ? -1 : 1;+ final byTime = when(b).compareTo(when(a));+ return byTime != 0 ? byTime : a.index.compareTo(b.index);+ });+ return [for (final r in listed) r.row];+}++/// Names more than one device goes by (trimmed; an empty name counts as one name). Their rows add the+/// start of the key code, since two rows that read the same cannot be told apart otherwise.+Set<String> sharedNames(List<DeviceLogRow> rows) {+ final seen = <String>{};+ final shared = <String>{};+ for (final row in rows) {+ final name = row.member.label.trim();+ if (!seen.add(name)) shared.add(name);+ }+ return shared;+}++/// The line under a device's name in the list: `Computer · active now`, `App · last active 2 days ago`.+/// With [sameName] it ends in the first group of the key code, the one thing that tells two devices+/// of the same name apart without putting the whole code in the row.+String deviceDetailLine(+ DeviceLogRow row,+ int? seenMs,+ DateTime now, {+ required bool sameName,+}) {+ final what = row.member.kind == 'machine' ? 'Computer' : 'App';+ final when = activityPhrase(+ lastSeen: seenMs == null+ ? null+ : DateTime.fromMillisecondsSinceEpoch(seenMs),+ addedAt: DateTime.fromMillisecondsSinceEpoch(row.member.addedAt),+ now: now,+ );+ final tail = sameName && row.fingerprint.isNotEmpty+ ? ' · ${row.fingerprint.split('·').first}…'+ : '';+ return '$what · $when$tail';+}++/// A row for a device only known from its log entry (a new-device notice), with its key code worked+/// out from the key. Never this phone: a notice is about a device this phone had not trusted.+DeviceLogRow rowFromMember(DevLogMember m) {+ var fp = '';+ try {+ fp = keys.fingerprint(b64d(m.pub));+ } catch (_) {}+ return DeviceLogRow(m, fingerprint: fp, self: false);+}diff --git a/mobile/lib/phone/devices_page.dart b/mobile/lib/phone/devices_page.dartindex a3f19c0a2..afa25d069 100644--- a/mobile/lib/phone/devices_page.dart+++ b/mobile/lib/phone/devices_page.dart@@ -7,6 +7,10 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/viewer/device_log_sync.dart';+import 'device_detail_page.dart';+import 'device_rows.dart';+import 'fingerprint_text.dart';+import 'phone_navigation.dart' show phoneRoute;import 'phone_sheet.dart';import 'settings_row.dart';import 'tty.dart';@@ -29,15 +33,19 @@ class _DevicesPageState extends State<DevicesPage> {Map<String, int> _seen = const {};bool _removingUnused = false;int _revision = -1;- final Set<String> _removing = {};String? _error;+ /// The devices that were new when this page opened: they keep their `New` badge for the visit,+ /// though opening the page clears the banner that announced them.+ late final Set<String> _newPubs;+AppNotifier get _app => widget.notifier;@overridevoid initState() {super.initState();_app.addListener(_changed);+ _newPubs = {for (final m in _app.newDevices) m.pub};unawaited(_load());// Looking at the list IS reviewing the new devices: the banner that pointed here is done.WidgetsBinding.instance.addPostFrameCallback((_) {@@ -57,38 +65,28 @@ class _DevicesPageState extends State<DevicesPage> {Future<void> _load() async {_revision = _app.devicesRevision;- final listing = await _app.deviceLog?.list();+ final listing = await _app.deviceListing();final seen = await _app.devicesLastSeen();if (!mounted) return;setState(() {- _listing = listing ?? DeviceLogListing.empty;+ _listing = listing;_seen = seen;});}- Future<void> _remove(DeviceLogRow row) async {- final name = row.member.label.isEmpty ? 'this device' : row.member.label;- final confirmed = await confirmPhoneAction(- context,- title: 'Remove $name?',- message:- 'It stops reaching your machines on every device, and is signed out. '- 'Signing in on it again adds it back as a new device.',- confirmLabel: 'Remove',- icon: LucideIcons.shieldOff300,- );- if (!confirmed || !mounted) return;- setState(() {- _removing.add(row.member.pub);- _error = null;- });- final error = await _app.removeDevice(row.member.pub);- if (!mounted) return;- setState(() {- _removing.remove(row.member.pub);- _error = error == null ? null : "Couldn't remove $name. Try again.";- });- }+ void _open(DeviceLogRow row) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => DeviceDetailPage(+ notifier: _app,+ row: row,+ lastSeen: _seen[row.member.pub],+ isNew: _newPubs.contains(row.member.pub),+ onMine: () => setState(() => _newPubs.remove(row.member.pub)),+ ),+ ),+ ),+ );/// Apps not seen in 90 days: most likely a browser whose data was cleared, which never signs its/// own removal. Never this phone, never a computer, never one the backend has no record of.@@ -238,31 +236,43 @@ class _DevicesPageState extends State<DevicesPage> {const SizedBox(height: 12),if (listing == null)const SizedBox.shrink()- else+ else ...[+ if (selfRow(listing.members) case final self?) ...[+ SettingsGroup(+ children: [+ _ThisDeviceCard(+ key: const Key('account-device-this'),+ row: self,+ ),+ ],+ ),+ const SizedBox(height: 12),+ ],SettingsGroup(children: [- for (final row in listing.members)+ for (final row in orderDeviceRows(+ listing.members,+ _seen,+ _newPubs,+ ))SettingsRow(key: ValueKey('account-device-${row.member.pub}'),- title:- '${row.member.label.isEmpty ? 'Unnamed device' : row.member.label}'- '${row.self ? ' (this phone)' : ''}',- detail:- '${row.member.kind == 'machine' ? 'Computer' : 'App'}'- '${_seen[row.member.pub] != null ? ' · last seen ${_date(_seen[row.member.pub]!)}' : ''}'- ' · ${row.fingerprint}',- destructive: !row.self,- value: row.self- ? null- : (_removing.contains(row.member.pub)- ? 'Removing…'- : 'Remove'),- onTap: row.self || _removing.contains(row.member.pub)- ? null- : () => unawaited(_remove(row)),+ title: row.member.label.trim().isEmpty+ ? 'Unnamed device'+ : row.member.label,+ detail: deviceDetailLine(+ row,+ _seen[row.member.pub],+ DateTime.now(),+ sameName: sharedNames(listing.members)+ .contains(row.member.label.trim()),+ ),+ value: _newPubs.contains(row.member.pub) ? 'New' : null,+ onTap: () => _open(row),),],),+ ],],),),@@ -270,8 +280,49 @@ class _DevicesPageState extends State<DevicesPage> {}}-String _date(int ms) {- final at = DateTime.fromMillisecondsSinceEpoch(ms);- String two(int n) => n.toString().padLeft(2, '0');- return '${at.year}-${two(at.month)}-${two(at.day)}';+/// This phone's own name and key code, copyable, with what it is for: the code the other devices+/// show for this one.+class _ThisDeviceCard extends StatelessWidget {+ const _ThisDeviceCard({super.key, required this.row});++ final DeviceLogRow row;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final name = row.member.label.trim().isEmpty+ ? 'Unnamed device'+ : row.member.label;+ return Padding(+ padding: const EdgeInsets.fromLTRB(13, 12, 13, 12),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'This device · $name',+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: 15,+ fontWeight: FontWeight.w500,+ ),+ ),+ const SizedBox(height: 8),+ FingerprintBlock(+ row.fingerprint,+ large: false,+ copyKey: const Key('this-device-copy'),+ ),+ const SizedBox(height: 4),+ Text(+ 'This is the code your other devices show for this device.',+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontSize: 12.5,+ height: 1.4,+ ),+ ),+ ],+ ),+ );+ }}diff --git a/mobile/lib/phone/fingerprint_text.dart b/mobile/lib/phone/fingerprint_text.dartnew file mode 100644index 000000000..57ed7e203--- /dev/null+++ b/mobile/lib/phone/fingerprint_text.dart@@ -0,0 +1,92 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++/// A device's key code spelled for a screen reader: `Key code E 2 F B, 0 D F 5, 5 F D 8, E 6 C 7` —+/// letter by letter, so it is not read as a word.+String fingerprintSpoken(String fingerprint) =>+ 'Key code ${fingerprint.split('·').map((group) => group.split('').join(' ')).join(', ')}';++/// How to check a key code, shown under it in a device's detail. [computer] adds the CLI route, which+/// only a computer has.+String fingerprintHowToCompare({required bool computer}) => computer+ ? 'This device’s own key code. Open Your devices on that computer — the code under “This device” '+ 'must match — or run harness status on it.'+ : 'This device’s own key code. Open Your devices on that device — the code under “This device” must match.';++/// A key code (`E2FB·0DF5·5FD8·E6C7`) set in mono, selectable, with a Copy button.+///+/// The code is what a person reads out or compares against another screen, so it is never truncated;+/// Copy puts the exact string on the clipboard. [large] is the detail page's size, small the one in+/// the "This device" card.+class FingerprintBlock extends StatefulWidget {+ const FingerprintBlock(+ this.fingerprint, {+ super.key,+ this.large = true,+ this.copyKey,+ });++ final String fingerprint;+ final bool large;++ /// Key of the Copy button, for tests.+ final Key? copyKey;++ @override+ State<FingerprintBlock> createState() => _FingerprintBlockState();+}++class _FingerprintBlockState extends State<FingerprintBlock> {+ Timer? _timer;+ bool _copied = false;++ @override+ void dispose() {+ _timer?.cancel();+ super.dispose();+ }++ void _copy() {+ unawaited(Clipboard.setData(ClipboardData(text: widget.fingerprint)));+ HapticFeedback.selectionClick();+ _timer?.cancel();+ setState(() => _copied = true);+ _timer = Timer(const Duration(seconds: 2), () {+ if (mounted) setState(() => _copied = false);+ });+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Row(+ children: [+ Expanded(+ child: Semantics(+ label: fingerprintSpoken(widget.fingerprint),+ excludeSemantics: true,+ child: SelectableText(+ widget.fingerprint,+ style: TextStyle(+ fontFamily: AppFont.mono,+ fontFamilyFallback: AppFont.monoFallback,+ fontSize: widget.large ? 22 : 16,+ letterSpacing: 0.5,+ color: AppPalette.textPrimary,+ ),+ ),+ ),+ ),+ TextButton(+ key: widget.copyKey,+ onPressed: _copy,+ child: Text(_copied ? 'Copied' : 'Copy'),+ ),+ ],+ );+ }+}diff --git a/mobile/lib/phone/new_device_banner.dart b/mobile/lib/phone/new_device_banner.dartindex 68e93d2fb..35e3dbdce 100644--- a/mobile/lib/phone/new_device_banner.dart+++ b/mobile/lib/phone/new_device_banner.dart@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/state/app_state.dart';+import 'device_detail_page.dart';+import 'device_rows.dart';import 'devices_page.dart';import 'phone_navigation.dart' show phoneRoute;import 'tty.dart';@@ -49,9 +51,18 @@ class NewDeviceBanner extends StatelessWidget {child: const Text('Mine'),),TextButton(+ // One new device goes straight to its key code; several go to the list, where each is a row.onPressed: () => unawaited(navigator.currentState?.push(- phoneRoute((_) => DevicesPage(notifier: notifier)),+ phoneRoute(+ (_) => more == 0+ ? DeviceDetailPage(+ notifier: notifier,+ row: rowFromMember(m),+ isNew: true,+ )+ : DevicesPage(notifier: notifier),+ ),),),child: const Text('Review'),diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex a13184f21..9ae126966 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -1,11 +1,18 @@+import 'dart:async';+import 'new_device_banner.dart';import 'package:flutter/material.dart';import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/viewer/device_log_sync.dart';import '../p2p/phone_terminal_p2p.dart';import 'agent_home.dart';+import 'device_detail_page.dart';+import 'device_rows.dart';+import 'devices_page.dart';+import 'phone_navigation.dart' show phoneRoute;import 'phone_shell_scope.dart';/// The signed-in phone app: one page stack, rooted in [AgentHome] — the terminal the phone opens@@ -41,6 +48,16 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {WidgetsBinding.instance.addObserver(this);final notices = widget.notifier.agentNotices.system;notices.opened.addListener(_openNoticedAgent);+ notices.openedDevice.addListener(_openNoticedDevice);+ // A tap that launched the app is read before this shell exists, so its value is already set and+ // no listener will ever fire for it: take it once the navigator is up.+ if (notices.opened.value != null || notices.openedDevice.value != null) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ _openNoticedAgent();+ _openNoticedDevice();+ });+ }// ⚠️ Not asked here any more. Signed in with nothing on screen, "Harness would like to send you// notifications" is a question with no reason attached. It is asked the first time a harness// is on screen — see `FocusHints.onDone` in `terminal_page.dart`.@@ -52,6 +69,9 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {widget.notifier.agentNotices.system.opened.removeListener(_openNoticedAgent,);+ widget.notifier.agentNotices.system.openedDevice.removeListener(+ _openNoticedDevice,+ );_linkedMachineId.dispose();_openAgentRequest.dispose();_heroController.dispose();@@ -122,6 +142,49 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {_openAgentAtHome(agent.machineId, agent.agentId);}+ /// A tapped "new device" notice: that device's page. One this phone has just been told of opens as+ /// new; one it no longer lists as new but the account still holds opens plain; one that is gone+ /// opens the list, which says so by not showing it.+ void _openNoticedDevice() {+ final opened = widget.notifier.agentNotices.system.openedDevice;+ final pub = opened.value;+ if (pub == null) return;+ opened.value = null;+ unawaited(_showDevice(pub));+ }++ Future<void> _showDevice(String pub) async {+ final navigator = _navigator.currentState;+ if (navigator == null) return;+ for (final m in widget.notifier.newDevices) {+ if (m.pub != pub) continue;+ await navigator.push(+ phoneRoute(+ (_) => DeviceDetailPage(+ notifier: widget.notifier,+ row: rowFromMember(m),+ isNew: true,+ ),+ ),+ );+ return;+ }+ final DeviceLogListing listing = await widget.notifier.deviceListing();+ if (!mounted) return;+ for (final row in listing.members) {+ if (row.member.pub != pub) continue;+ await navigator.push(+ phoneRoute(+ (_) => DeviceDetailPage(notifier: widget.notifier, row: row),+ ),+ );+ return;+ }+ await navigator.push(+ phoneRoute((_) => DevicesPage(notifier: widget.notifier)),+ );+ }+/// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine/// socket the phone lost while it was away. Going to the background needs nothing — the OS/// suspends the socket, and the redial tears the old wire down and negotiates a fresh one.diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 9fa347a25..65534a6c5 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -2041,6 +2041,10 @@ class AppNotifier extends ChangeNotifier {/// When each of the account's keys last opened a session (`{pub: ms}`), for the Devices page.Future<Map<String, int>> devicesLastSeen() => api.deviceKeysSeen();+ /// The account's devices as this phone verified them. A seam of its own so a test can answer+ /// without a real device log.+ Future<DeviceLogListing> deviceListing() async => await _deviceLog?.list() ?? DeviceLogListing.empty;+DateTime? _deviceLogReadAt;/// A socket came back: a `device_keys_changed` sent while this phone was offline reached nobody, sodiff --git a/mobile/test/core/relative_time_test.dart b/mobile/test/core/relative_time_test.dartnew file mode 100644index 000000000..f2d0f4cd7--- /dev/null+++ b/mobile/test/core/relative_time_test.dart@@ -0,0 +1,54 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/relative_time.dart';++void main() {+ final now = DateTime(2026, 10, 1, 12);+ String ago(Duration d) => relativeAgo(now.subtract(d), now);++ test('relativeAgo follows the boundaries the CLI and mobile use', () {+ expect(ago(Duration.zero), 'just now');+ expect(ago(const Duration(seconds: 59)), 'just now');+ expect(ago(const Duration(minutes: 1)), '1 minute ago');+ expect(ago(const Duration(minutes: 59)), '59 minutes ago');+ expect(ago(const Duration(hours: 1)), '1 hour ago');+ expect(ago(const Duration(hours: 23)), '23 hours ago');+ expect(ago(const Duration(hours: 24)), 'yesterday');+ expect(ago(const Duration(hours: 47)), 'yesterday');+ expect(ago(const Duration(days: 2)), '2 days ago');+ expect(ago(const Duration(days: 13)), '13 days ago');+ expect(ago(const Duration(days: 14)), '2 weeks ago');+ expect(ago(const Duration(days: 59)), '8 weeks ago');+ expect(ago(const Duration(days: 60)), '2 months ago');+ expect(ago(const Duration(days: 364)), '12 months ago');+ expect(ago(const Duration(days: 365)), 'over a year ago');+ expect(relativeAgo(now.add(const Duration(minutes: 5)), now), 'just now');+ });++ test('fullDateTime spells the local date and 24-hour time', () {+ expect(fullDateTime(DateTime(2026, 10, 1, 14, 5)), '1 Oct 2026, 14:05');+ });++ test('activityPhrase says active now, last active, or added', () {+ final added = now.subtract(const Duration(days: 30));+ expect(+ activityPhrase(+ lastSeen: now.subtract(const Duration(minutes: 1)),+ addedAt: added,+ now: now,+ ),+ 'active now',+ );+ expect(+ activityPhrase(+ lastSeen: now.subtract(const Duration(days: 2)),+ addedAt: added,+ now: now,+ ),+ 'last active 2 days ago',+ );+ expect(+ activityPhrase(addedAt: now.subtract(const Duration(days: 21)), now: now),+ 'added 3 weeks ago',+ );+ });+}diff --git a/mobile/test/notify/agent_announcer_test.dart b/mobile/test/notify/agent_announcer_test.dartindex ac22b8934..7feb5debb 100644--- a/mobile/test/notify/agent_announcer_test.dart+++ b/mobile/test/notify/agent_announcer_test.dart@@ -13,6 +13,9 @@ class _RecordingNotices implements SystemNotices {@overridefinal opened = ValueNotifier<AgentRef?>(null);+ @override+ final openedDevice = ValueNotifier<String?>(null);+@overrideFuture<void> requestPermission() async {}diff --git a/mobile/test/notify/local_system_notices_test.dart b/mobile/test/notify/local_system_notices_test.dartindex fd047c6d5..44f46897f 100644--- a/mobile/test/notify/local_system_notices_test.dart+++ b/mobile/test/notify/local_system_notices_test.dart@@ -41,6 +41,32 @@ void main() {expect(shown.details!.android!.channelId, 'account-device');expect(shown.details!.iOS!.threadIdentifier, 'account-device');expect(decodeAgentPayload(shown.payload), isNull);+ // A tap opens that device's page: the payload names the device, never an agent.+ expect(shown.payload, 'device:pub-1');+ });++ test('a tap on a device notice opens that device, not an agent', () async {+ await notices.showAccountNotice(key: 'pub-1', title: 'New device on your account', body: 'iPad signed in.');+ plugin.onResponse!(+ const NotificationResponse(+ notificationResponseType: NotificationResponseType.selectedNotification,+ payload: 'device:pub-1',+ ),+ );+ expect(notices.openedDevice.value, 'pub-1');+ expect(notices.opened.value, isNull);+ });++ test('a tap on an agent notice opens no device', () async {+ await notices.show(message(NoticeKind.done));+ plugin.onResponse!(+ NotificationResponse(+ notificationResponseType: NotificationResponseType.selectedNotification,+ payload: encodeAgentPayload(ref),+ ),+ );+ expect(notices.opened.value, ref);+ expect(notices.openedDevice.value, isNull);});test('nothing starts until a notice is first needed', () {diff --git a/mobile/test/phone/device_detail_page_test.dart b/mobile/test/phone/device_detail_page_test.dartnew file mode 100644index 000000000..cbb7ea4c8--- /dev/null+++ b/mobile/test/phone/device_detail_page_test.dart@@ -0,0 +1,266 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/relative_time.dart';+import 'package:harness_mobile/phone/device_detail_page.dart';+import 'package:harness_mobile/phone/fingerprint_text.dart';+import 'package:harness_mobile/viewer/device_log_sync.dart';++import 'devices_fixture.dart';++/// One device in full on the phone: what it is, its whole key code to compare, and what to do.+void main() {+ late List<String?> clipboard;++ setUp(() {+ clipboard = [];+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.setData') {+ clipboard.add((call.arguments as Map)['text'] as String?);+ }+ return null;+ });+ });++ tearDown(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null);+ });++ final addedAt = DateTime(2026, 9, 3, 9, 7);++ DeviceLogRow computer({bool self = false}) => row(+ member(+ pubOf(1),+ label: 'mbp',+ kind: 'machine',+ machineId: 'abcdef1234567890',+ addedAt: addedAt.millisecondsSinceEpoch,+ ),+ self: self,+ );++ DeviceLogRow app() => row(+ member(pubOf(2), label: 'iPad', addedAt: addedAt.millisecondsSinceEpoch),+ );++ /// The detail pushed over a page with an "Opened" marker, so a pop is something to see.+ Future<void> pump(+ WidgetTester tester,+ DevicesApp notifier,+ DeviceLogRow row, {+ int? lastSeen,+ bool isNew = false,+ VoidCallback? onMine,+ }) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => Scaffold(+ body: TextButton(+ onPressed: () => Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => DeviceDetailPage(+ notifier: notifier,+ row: row,+ lastSeen: lastSeen,+ isNew: isNew,+ onMine: onMine,+ ),+ ),+ ),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ }++ testWidgets('a computer: its facts, its whole key code, and how to check it '+ 'there', (tester) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ final r = computer();+ final seen = DateTime.now().subtract(const Duration(days: 2));+ await pump(tester, notifier, r, lastSeen: seen.millisecondsSinceEpoch);++ expect(find.text('mbp'), findsOneWidget);+ expect(find.text('Computer'), findsOneWidget);+ expect(find.text(fullDateTime(addedAt)), findsOneWidget);+ expect(find.text('3 Sep 2026, 09:07'), findsOneWidget);+ expect(find.text('Last active'), findsOneWidget);+ expect(find.text('2 days ago'), findsOneWidget);+ expect(find.text('Machine'), findsOneWidget);+ expect(find.text('abcdef12'), findsOneWidget);+ expect(find.text(r.fingerprint), findsOneWidget);+ expect(+ find.text(+ 'This device’s own key code. Open Your devices on that computer — the code under '+ '“This device” must match — or run harness status on it.',+ ),+ findsOneWidget,+ );+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);+ expect(find.byKey(const Key('device-detail-remove')), findsOneWidget);+ });++ testWidgets('an app: no machine row, no last active when never seen, and the '+ 'app wording', (tester) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ await pump(tester, notifier, app());++ expect(find.text('App'), findsOneWidget);+ expect(find.text('Added'), findsOneWidget);+ expect(find.text('Last active'), findsNothing);+ expect(find.text('Machine'), findsNothing);+ expect(+ find.text(+ 'This device’s own key code. Open Your devices on that device — the code under '+ '“This device” must match.',+ ),+ findsOneWidget,+ );+ });++ testWidgets('Copy puts the exact key code on the clipboard and says Copied '+ 'for two seconds; a reader hears it letter by letter', (tester) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ final r = app();+ await pump(tester, notifier, r);++ final handle = tester.ensureSemantics();+ expect(find.bySemanticsLabel(fingerprintSpoken(r.fingerprint)), findsOne);+ final groups = r.fingerprint.split('·');+ expect(+ fingerprintSpoken(r.fingerprint),+ 'Key code ${groups.map((g) => g.split('').join(' ')).join(', ')}',+ );+ handle.dispose();++ await tester.tap(find.byKey(const Key('device-detail-copy')));+ await tester.pump();+ expect(clipboard, [r.fingerprint]);+ expect(r.fingerprint, contains('·'));+ expect(find.text('Copied'), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 1900));+ expect(find.text('Copied'), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.text('Copied'), findsNothing);+ expect(find.text('Copy'), findsOneWidget);+ });++ test('fingerprintSpoken spells each group', () {+ expect(+ fingerprintSpoken('E2FB·0DF5·5FD8·E6C7'),+ 'Key code E 2 F B, 0 D F 5, 5 F D 8, E 6 C 7',+ );+ });++ testWidgets('It’s mine dismisses the notice, tells the opener, and closes', (+ tester,+ ) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ final r = app();+ notifier.newDevices.add(r.member);+ var mine = 0;+ await pump(tester, notifier, r, isNew: true, onMine: () => mine++);++ await tester.tap(find.byKey(const Key('device-detail-mine')));+ await tester.pumpAndSettle();++ expect(notifier.newDevices, isEmpty);+ expect(mine, 1);+ expect(find.byType(DeviceDetailPage), findsNothing);+ expect(notifier.removed, isEmpty);+ });++ testWidgets('Remove asks first; backing out removes nothing', (tester) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ await pump(tester, notifier, app());++ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pumpAndSettle();+ expect(find.text('Remove iPad?'), findsOneWidget);+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();++ expect(notifier.removed, isEmpty);+ expect(find.byType(DeviceDetailPage), findsOneWidget);+ });++ testWidgets('confirming Remove removes that device and closes', (+ tester,+ ) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ final r = app();+ await pump(tester, notifier, r);++ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Remove'));+ await tester.pumpAndSettle();++ expect(notifier.removed, [r.member.pub]);+ expect(find.byType(DeviceDetailPage), findsNothing);+ });++ testWidgets('while a removal is in flight the row says Removing… and takes '+ 'no second tap', (tester) async {+ final notifier = DevicesApp()..removeGate = Completer<void>();+ addTearDown(notifier.dispose);+ final r = app();+ await pump(tester, notifier, r, isNew: true);++ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Remove'));+ await tester.pumpAndSettle();+ expect(find.text('Removing…'), findsOneWidget);+ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.tap(find.byKey(const Key('device-detail-mine')));+ await tester.pumpAndSettle();+ expect(find.text('Remove iPad?'), findsNothing);+ expect(notifier.removed, [r.member.pub]);++ notifier.removeGate!.complete();+ await tester.pumpAndSettle();+ expect(find.byType(DeviceDetailPage), findsNothing);+ });++ testWidgets('a Remove that fails stays open and says so', (tester) async {+ final notifier = DevicesApp()..removeError = 'UNAVAILABLE';+ addTearDown(notifier.dispose);+ await pump(tester, notifier, app());++ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Remove'));+ await tester.pumpAndSettle();++ expect(find.byType(DeviceDetailPage), findsOneWidget);+ expect(find.text("Couldn't remove iPad. Try again."), findsOneWidget);+ expect(find.text('Remove this device'), findsOneWidget);+ });++ testWidgets('this phone itself has no Remove and no It’s mine', (+ tester,+ ) async {+ final notifier = DevicesApp();+ addTearDown(notifier.dispose);+ await pump(tester, notifier, computer(self: true));++ expect(find.byKey(const Key('device-detail-remove')), findsNothing);+ expect(find.byKey(const Key('device-detail-mine')), findsNothing);+ });+}diff --git a/mobile/test/phone/device_rows_test.dart b/mobile/test/phone/device_rows_test.dartnew file mode 100644index 000000000..3daf2fc36--- /dev/null+++ b/mobile/test/phone/device_rows_test.dart@@ -0,0 +1,173 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/device_rows.dart';++import 'devices_fixture.dart';++/// The rules of the Your devices list on the phone: who goes where, and what a row says.+void main() {+ final now = DateTime(2026, 10, 1, 12);+ int ago(Duration d) => now.subtract(d).millisecondsSinceEpoch;+ final hexGroup = RegExp(r'[0-9A-F]{4}·[0-9A-F]{4}');++ group('orderDeviceRows', () {+ test('new devices first (newest first), then the rest by last activity, '+ 'falling back to when added; this phone is not listed', () {+ final self = row(+ member(+ pubOf(0),+ label: 'This phone',+ addedAt: ago(const Duration(days: 100)),+ ),+ self: true,+ );+ final oldA = row(+ member(pubOf(1), addedAt: ago(const Duration(days: 90))),+ );+ final new1 = row(member(pubOf(2), addedAt: ago(const Duration(days: 2))));+ final oldB = row(+ member(pubOf(3), addedAt: ago(const Duration(days: 80))),+ );+ final new2 = row(member(pubOf(4), addedAt: ago(const Duration(days: 1))));+ final out = orderDeviceRows(+ [oldA, self, new1, oldB, new2],+ {pubOf(1): ago(const Duration(days: 10))},+ {pubOf(2), pubOf(4)},+ );+ expect(out, [new2, new1, oldA, oldB]);+ });++ test(+ 'a device recently added but not in the new set is ordered by activity',+ () {+ final recent = row(+ member(pubOf(1), addedAt: ago(const Duration(days: 1))),+ );+ final seenToday = row(+ member(pubOf(2), addedAt: ago(const Duration(days: 300))),+ );+ final out = orderDeviceRows(+ [recent, seenToday],+ {pubOf(2): ago(const Duration(hours: 1))},+ const {},+ );+ expect(out, [seenToday, recent]);+ },+ );++ test('ties keep log order', () {+ final at = ago(const Duration(days: 30));+ final rows = [+ for (var i = 1; i <= 12; i++) row(member(pubOf(i), addedAt: at)),+ ];+ expect(orderDeviceRows(rows, const {}, const {}), rows);+ final newRows = orderDeviceRows(rows, const {}, {+ for (final r in rows) r.member.pub,+ });+ expect(newRows, rows);+ });+ });++ test('selfRow finds this phone, or nothing', () {+ final self = row(member(pubOf(0), addedAt: 0), self: true);+ final other = row(member(pubOf(1), addedAt: 0));+ expect(selfRow([other, self]), same(self));+ expect(selfRow([other]), isNull);+ });++ test(+ 'sharedNames: trimmed, empty names count as one, and this phone counts',+ () {+ final rows = [+ row(member(pubOf(0), label: 'iPhone', addedAt: 0), self: true),+ row(member(pubOf(1), label: 'iPhone ', addedAt: 0)),+ row(member(pubOf(2), label: '', addedAt: 0)),+ row(member(pubOf(3), label: ' ', addedAt: 0)),+ row(member(pubOf(4), label: 'MacBook', addedAt: 0)),+ ];+ expect(sharedNames(rows), {'iPhone', ''});+ },+ );++ group('deviceDetailLine', () {+ final app = row(+ member(pubOf(1), label: 'iPad', addedAt: ago(const Duration(days: 21))),+ );+ final computer = row(+ member(+ pubOf(2),+ label: 'mbp',+ kind: 'machine',+ machineId: 'abcdef123456',+ addedAt: ago(const Duration(days: 40)),+ ),+ );++ test(+ 'kind and activity, and no part of the key code for a unique name',+ () {+ final seen4m = ago(const Duration(minutes: 4));+ expect(+ deviceDetailLine(computer, seen4m, now, sameName: false),+ 'Computer · active now',+ );+ expect(+ deviceDetailLine(+ app,+ ago(const Duration(days: 2)),+ now,+ sameName: false,+ ),+ 'App · last active 2 days ago',+ );+ expect(+ deviceDetailLine(app, null, now, sameName: false),+ 'App · added 3 weeks ago',+ );+ expect(+ deviceDetailLine(+ computer,+ ago(const Duration(minutes: 5)),+ now,+ sameName: false,+ ),+ 'Computer · last active 5 minutes ago',+ );+ for (final line in [+ deviceDetailLine(app, null, now, sameName: false),+ deviceDetailLine(computer, seen4m, now, sameName: false),+ ]) {+ expect(line, isNot(contains(hexGroup)));+ expect(line, isNot(contains(RegExp(r'\d{4}-\d{2}-\d{2}'))));+ }+ },+ );++ test(+ 'a shared name ends in the first group of the key code and an ellipsis',+ () {+ final line = deviceDetailLine(app, null, now, sameName: true);+ final first = app.fingerprint.split('·').first;+ expect(line, 'App · added 3 weeks ago · $first…');+ expect(line, isNot(contains(hexGroup)));+ },+ );+ });++ test('rowFromMember: the key code from the key, never this phone, and '+ 'the member with its added time kept', () {+ final m = member(+ pubOf(5),+ label: 'iPad',+ addedAt: ago(const Duration(hours: 3)),+ );+ final r = rowFromMember(m);+ expect(r.fingerprint, fpOf(pubOf(5)));+ expect(r.fingerprint, matches(RegExp(r'^[0-9A-F]{4}(·[0-9A-F]{4}){3}$')));+ expect(r.self, isFalse);+ expect(r.member.addedAt, m.addedAt);+ expect(+ rowFromMember(member('not base64!', addedAt: 0)).fingerprint,+ isEmpty,+ );+ });+}diff --git a/mobile/test/phone/devices_fixture.dart b/mobile/test/phone/devices_fixture.dartnew file mode 100644index 000000000..58c1a3f2a--- /dev/null+++ b/mobile/test/phone/devices_fixture.dart@@ -0,0 +1,80 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/e2ee/bytes.dart';+import 'package:harness_mobile/e2ee/keys.dart' as keys;+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/viewer/device_log.dart';+import 'package:harness_mobile/viewer/device_log_sync.dart';++/// A 32-byte key, distinct per [n], base64 — what a device log carries as `pub`.+String pubOf(int n) =>+ b64e(Uint8List.fromList(List.generate(32, (i) => (i * 7 + n) & 0xff)));++/// The key code the app shows for [pub].+String fpOf(String pub) => keys.fingerprint(b64d(pub));++DevLogMember member(+ String pub, {+ String label = 'Device',+ String kind = 'viewer',+ String machineId = '',+ required int addedAt,+ int seq = 1,+}) => DevLogMember(+ pub: pub,+ kind: kind,+ machineId: machineId,+ label: label,+ addedAt: addedAt,+ seq: seq,+);++DeviceLogRow row(DevLogMember m, {bool self = false}) =>+ DeviceLogRow(m, fingerprint: fpOf(m.pub), self: self);++/// An app whose device list, last-seen times and removal are canned, so a page test is about what the+/// page does with them.+class DevicesApp extends AppNotifier {+ DevicesApp({this.rows = const [], this.seen = const {}})+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );++ List<DeviceLogRow> rows;+ Map<String, int> seen;++ /// What [removeDevice] answers: null is done, else why not.+ String? removeError;+ final removed = <String>[];++ /// When set, a removal waits on it — to see the page while the removal is in flight.+ Completer<void>? removeGate;++ @override+ Future<DeviceLogListing> deviceListing() async =>+ DeviceLogListing(members: rows, frozen: null, frozenPeers: const []);++ @override+ Future<Map<String, int>> devicesLastSeen() async => seen;++ @override+ Future<String?> removeDevice(String pub) async {+ removed.add(pub);+ await removeGate?.future;+ if (removeError == null) {+ rows = [+ for (final r in rows)+ if (r.member.pub != pub) r,+ ];+ newDevices.removeWhere((d) => d.pub == pub);+ }+ devicesRevision++;+ notifyListeners();+ return removeError;+ }+}diff --git a/mobile/test/phone/devices_page_test.dart b/mobile/test/phone/devices_page_test.dartnew file mode 100644index 000000000..1e480ec77--- /dev/null+++ b/mobile/test/phone/devices_page_test.dart@@ -0,0 +1,206 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/device_detail_page.dart';+import 'package:harness_mobile/phone/devices_page.dart';+import 'package:harness_mobile/phone/settings_row.dart';++import 'devices_fixture.dart';++/// Settings ▸ Your devices on the phone: this phone's own code on a card, then the other devices —+/// new ones on top — with no key code in a row unless two rows share a name.+void main() {+ final fullCode = RegExp(r'[0-9A-F]{4}·[0-9A-F]{4}');+ int ago(Duration d) => DateTime.now().subtract(d).millisecondsSinceEpoch;++ late DevicesApp app;+ late String selfPub, oldPub, newPub, twinPub;++ setUp(() {+ selfPub = pubOf(0);+ oldPub = pubOf(1);+ newPub = pubOf(2);+ twinPub = pubOf(3);+ app = DevicesApp(+ rows: [+ row(+ member(+ selfPub,+ label: 'My iPhone',+ addedAt: ago(const Duration(days: 200)),+ ),+ self: true,+ ),+ row(+ member(+ oldPub,+ label: 'mbp',+ kind: 'machine',+ machineId: 'abcdef1234',+ addedAt: ago(const Duration(days: 100)),+ ),+ ),+ row(+ member(newPub, label: 'iPad', addedAt: ago(const Duration(days: 30))),+ ),+ // Shares this phone's name: its row has to say which one it is.+ row(+ member(+ twinPub,+ label: 'My iPhone',+ addedAt: ago(const Duration(days: 150)),+ ),+ ),+ ],+ seen: {+ oldPub: ago(const Duration(minutes: 2)),+ twinPub: ago(const Duration(days: 3)),+ },+ );+ app.newDevices.add(app.rows[2].member);+ });++ tearDown(() => app.dispose());++ Future<void> pump(WidgetTester tester) async {+ await tester.pumpWidget(MaterialApp(home: DevicesPage(notifier: app)));+ await tester.pumpAndSettle();+ }++ List<String> rowOrder(WidgetTester tester) => [+ for (final r in tester.widgetList<SettingsRow>(+ find.byWidgetPredicate(+ (w) =>+ w is SettingsRow &&+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith('account-device-'),+ ),+ ))+ (r.key! as ValueKey<String>).value.substring('account-device-'.length),+ ];++ SettingsRow rowFor(WidgetTester tester, String pub) =>+ tester.widget<SettingsRow>(find.byKey(ValueKey('account-device-$pub')));++ testWidgets('this phone is a card with its whole code, copyable, and is not '+ 'listed again', (tester) async {+ await pump(tester);+ final card = find.byKey(const Key('account-device-this'));+ expect(card, findsOneWidget);+ expect(+ find.descendant(of: card, matching: find.text('This device · My iPhone')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: card, matching: find.text(fpOf(selfPub))),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: card,+ matching: find.text(+ 'This is the code your other devices show for this device.',+ ),+ ),+ findsOneWidget,+ );+ expect(find.byKey(const Key('this-device-copy')), findsOneWidget);+ expect(find.byKey(ValueKey('account-device-$selfPub')), findsNothing);+ });++ testWidgets('no row holds a whole key code; a shared name shows only the '+ 'first group', (tester) async {+ await pump(tester);+ for (final pub in [oldPub, newPub, twinPub]) {+ final r = rowFor(tester, pub);+ expect(r.title, isNot(contains(fullCode)));+ expect(r.detail, isNot(contains(fullCode)));+ expect(r.detail, isNot(contains(RegExp(r'\d{4}-\d{2}-\d{2}'))));+ }+ expect(rowFor(tester, oldPub).detail, 'Computer · active now');+ expect(rowFor(tester, newPub).detail, 'App · added 4 weeks ago');+ expect(+ rowFor(tester, twinPub).detail,+ 'App · last active 3 days ago · ${fpOf(twinPub).split('·').first}…',+ );+ });++ testWidgets('a new device is on top with New; the rest follow by activity', (+ tester,+ ) async {+ await pump(tester);+ expect(rowOrder(tester), [newPub, oldPub, twinPub]);+ expect(rowFor(tester, newPub).value, 'New');+ expect(rowFor(tester, oldPub).value, isNull);+ expect(rowFor(tester, twinPub).value, isNull);+ });++ testWidgets(+ 'opening the list clears the banner, yet New stays for this visit',+ (tester) async {+ expect(app.newDevices, hasLength(1));+ await pump(tester);+ expect(app.newDevices, isEmpty);+ expect(rowFor(tester, newPub).value, 'New');+ expect(rowOrder(tester).first, newPub);+ },+ );++ testWidgets(+ 'tapping a row opens that device, Remove lives there, and It’s mine '+ 'clears its New',+ (tester) async {+ await pump(tester);+ expect(find.text('Remove'), findsNothing, reason: 'no Remove on a row');++ await tester.tap(find.byKey(ValueKey('account-device-$newPub')));+ await tester.pumpAndSettle();+ final page = tester.widget<DeviceDetailPage>(+ find.byType(DeviceDetailPage),+ );+ expect(page.row.member.pub, newPub);+ expect(page.isNew, isTrue);+ expect(find.text(fpOf(newPub)), findsOneWidget);+ expect(find.byKey(const Key('device-detail-remove')), findsOneWidget);++ await tester.tap(find.byKey(const Key('device-detail-mine')));+ await tester.pumpAndSettle();+ expect(find.byType(DeviceDetailPage), findsNothing);+ expect(rowFor(tester, newPub).value, isNull);+ },+ );++ testWidgets('a device opened and closed without a choice keeps its New', (+ tester,+ ) async {+ await pump(tester);+ await tester.tap(find.byKey(ValueKey('account-device-$newPub')));+ await tester.pumpAndSettle();+ Navigator.of(tester.element(find.byType(DeviceDetailPage))).pop();+ await tester.pumpAndSettle();+ expect(rowFor(tester, newPub).value, 'New');+ });++ testWidgets('a device removed from its page leaves the list', (tester) async {+ await pump(tester);+ await tester.tap(find.byKey(ValueKey('account-device-$oldPub')));+ await tester.pumpAndSettle();+ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));+ expect(page.isNew, isFalse);+ expect(page.lastSeen, app.seen[oldPub]);+ await tester.tap(find.byKey(const Key('device-detail-remove')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Remove'));+ await tester.pumpAndSettle();++ expect(app.removed, [oldPub]);+ expect(find.byType(DeviceDetailPage), findsNothing);+ expect(find.byKey(ValueKey('account-device-$oldPub')), findsNothing);+ });++ testWidgets('no row for this phone: no card', (tester) async {+ app.rows = app.rows.where((r) => !r.self).toList();+ await pump(tester);+ expect(find.byKey(const Key('account-device-this')), findsNothing);+ expect(rowOrder(tester), hasLength(3));+ });+}diff --git a/mobile/test/phone/new_device_banner_test.dart b/mobile/test/phone/new_device_banner_test.dartnew file mode 100644index 000000000..b4ae53964--- /dev/null+++ b/mobile/test/phone/new_device_banner_test.dart@@ -0,0 +1,88 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/device_detail_page.dart';+import 'package:harness_mobile/phone/devices_page.dart';+import 'package:harness_mobile/phone/new_device_banner.dart';++import 'devices_fixture.dart';++/// "New device: X" — Review goes to that device when there is one, to the list when there are more.+void main() {+ late DevicesApp app;+ final nav = GlobalKey<NavigatorState>();++ setUp(() => app = DevicesApp());+ tearDown(() => app.dispose());++ Future<void> pump(WidgetTester tester) async {+ await tester.pumpWidget(+ MaterialApp(+ navigatorKey: nav,+ home: Scaffold(+ body: NewDeviceBanner(notifier: app, navigator: nav),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ testWidgets('one new device: Review opens its page, as new, with its whole '+ 'code; the sentence has no code', (tester) async {+ final m = member(+ pubOf(7),+ label: 'iPad',+ addedAt: DateTime.now()+ .subtract(const Duration(hours: 1))+ .millisecondsSinceEpoch,+ );+ app.newDevices.add(m);+ await pump(tester);+ expect(find.text('New device: iPad'), findsOneWidget);+ expect(find.textContaining('·'), findsNothing);++ await tester.tap(find.text('Review'));+ await tester.pumpAndSettle();++ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));+ expect(page.row.member.pub, m.pub);+ expect(page.isNew, isTrue);+ expect(find.text(fpOf(m.pub)), findsOneWidget);+ expect(find.text('Added'), findsOneWidget);+ expect(find.byKey(const Key('device-detail-mine')), findsOneWidget);+ expect(find.byType(DevicesPage), findsNothing);+ });++ testWidgets('two new devices: Review opens the list, the newest on top', (+ tester,+ ) async {+ final now = DateTime.now();+ final older = member(+ pubOf(7),+ label: 'iPad',+ addedAt: now.subtract(const Duration(hours: 5)).millisecondsSinceEpoch,+ );+ final newer = member(+ pubOf(8),+ label: 'Pixel',+ addedAt: now.subtract(const Duration(hours: 1)).millisecondsSinceEpoch,+ );+ app+ ..rows = [row(older), row(newer)]+ ..newDevices.addAll([older, newer]);+ await pump(tester);+ expect(find.text('New device: iPad +1'), findsOneWidget);++ await tester.tap(find.text('Review'));+ await tester.pumpAndSettle();++ expect(find.byType(DevicesPage), findsOneWidget);+ expect(find.byType(DeviceDetailPage), findsNothing);+ final newerTop = tester.getTopLeft(+ find.byKey(ValueKey('account-device-${newer.pub}')),+ );+ final olderTop = tester.getTopLeft(+ find.byKey(ValueKey('account-device-${older.pub}')),+ );+ expect(newerTop.dy, lessThan(olderTop.dy));+ });+}diff --git a/mobile/test/phone/phone_shell_device_notice_test.dart b/mobile/test/phone/phone_shell_device_notice_test.dartnew file mode 100644index 000000000..5d645dc69--- /dev/null+++ b/mobile/test/phone/phone_shell_device_notice_test.dart@@ -0,0 +1,82 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/device_detail_page.dart';+import 'package:harness_mobile/phone/devices_page.dart';+import 'package:harness_mobile/phone/phone_shell.dart';++import 'devices_fixture.dart';++/// A tapped "new device" notice opens that device's page: as new while it is still news, plain once+/// it is only on the list, and the list when the account no longer holds it.+void main() {+ late DevicesApp app;+ final at = DateTime(2026, 9, 30, 8).millisecondsSinceEpoch;++ setUp(() => app = DevicesApp());+ tearDown(() => app.dispose());++ Future<void> pumpShell(WidgetTester tester) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ }++ Future<void> tapNotice(WidgetTester tester, String pub) async {+ app.agentNotices.system.openedDevice.value = pub;+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ }++ testWidgets('a device still news opens as new, and the tap is consumed', (+ tester,+ ) async {+ final m = member(pubOf(3), label: 'iPad', addedAt: at);+ app.newDevices.add(m);+ await pumpShell(tester);++ await tapNotice(tester, m.pub);++ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));+ expect(page.row.member.pub, m.pub);+ expect(page.isNew, isTrue);+ expect(find.text(fpOf(m.pub)), findsOneWidget);+ expect(app.agentNotices.system.openedDevice.value, isNull);+ });++ testWidgets('a tap that launched the app still opens the device', (+ tester,+ ) async {+ // The launch tap is read before the shell exists, so no listener sees it change.+ final m = member(pubOf(5), label: 'iPad', addedAt: at);+ app.newDevices.add(m);+ app.agentNotices.system.openedDevice.value = m.pub;+ await pumpShell(tester);+ await tester.pump(const Duration(seconds: 1));++ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));+ expect(page.row.member.pub, m.pub);+ expect(app.agentNotices.system.openedDevice.value, isNull);+ });++ testWidgets('a device only on the list opens plain', (tester) async {+ final m = member(pubOf(4), label: 'Pixel', addedAt: at);+ app.rows = [row(m)];+ await pumpShell(tester);++ await tapNotice(tester, m.pub);++ final page = tester.widget<DeviceDetailPage>(find.byType(DeviceDetailPage));+ expect(page.row.member.pub, m.pub);+ expect(page.isNew, isFalse);+ });++ testWidgets('a device the account no longer holds opens the list', (+ tester,+ ) async {+ await pumpShell(tester);++ await tapNotice(tester, pubOf(5));++ expect(find.byType(DeviceDetailPage), findsNothing);+ expect(find.byType(DevicesPage), findsOneWidget);+ });+}