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
Capture the dial's log where a stuck report can be read from
0xdiego251ce585c73366
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex 45e3ed35c..b5fae8673 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -13,6 +13,7 @@ import { describe, expect, it, vi } from 'vitest'import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'import { CableSession, type CableAgent, type CableHost, type CableMachine, type CablePort } from './cableSession.js'+import { DialLog } from './dialLog.js'/** A port whose two ends are both in this process. */class LoopbackPort implements CablePort {@@ -104,9 +105,12 @@ function makeHost(over: Partial<CableHost> = {}) {}/** Start a session on a loopback and hand back both ends. Never touches the real serial layer. */-async function connect(host: CableHost = makeHost(), logPath = '/dev/null') {+/** A throwaway log directory per session, so no test reads another's lines. */+function tmpLog() { return new DialLog(mkdtempSync(join(tmpdir(), 'cable-'))) }++async function connect(host: CableHost = makeHost(), log = tmpLog()) {let port!: LoopbackPort- const session = new CableSession(host, logPath, async (onData, onClosed) => {+ const session = new CableSession(host, log, async (onData, onClosed) => {port = new LoopbackPort(onData, onClosed)return port})@@ -314,7 +318,7 @@ describe('cable session', () => {vi.useFakeTimers()try {let attempts = 0- const session = new CableSession(makeHost(), '/dev/null', async (onData, onClosed) => {+ const session = new CableSession(makeHost(), tmpLog(), async (onData, onClosed) => {attempts += 1if (attempts === 1) return new Promise<never>(() => {}) // the hangreturn new LoopbackPort(onData, onClosed)@@ -918,10 +922,12 @@ describe('cable session', () => {// The dial has ONE USB port, shared by its console and this protocol. While the daemon holds it,// these frames are the only copy of that console which exists anywhere — `idf.py monitor` cannot open// the port at the same time.- const path = join(mkdtempSync(join(tmpdir(), 'cable-')), 'dial.log')- const { session, port } = await connect(makeHost(), path)+ const log = tmpLog()+ const { session, port } = await connect(makeHost(), log)port.logLine('I (1234) cable: link up')- await vi.waitFor(() => expect(readFileSync(path, 'utf8')).toContain('I (1234) cable: link up'))+ await vi.waitFor(() => expect(readFileSync(log.currentPath, 'utf8')).toContain('I (1234) cable: link up'))+ // The daemon's side of the story lands in the SAME file, marked as the daemon's.+ expect(readFileSync(log.currentPath, 'utf8')).toMatch(/\[daemon\] open on /)await session.stop()})@@ -1127,7 +1133,7 @@ describe('cable session', () => {]const host = makeHost({ listMachines: async () => ({ machines: rows, source: 'backend' as const }) })let port!: SlowPort- const session = new CableSession(host, '/dev/null', async (onData) => {+ const session = new CableSession(host, tmpLog(), async (onData) => {port = new SlowPort(onData)return port})diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 4a4cd32ae..f1ef7237b 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -21,9 +21,9 @@//// 3. SAY NOTHING WHEN NOTHING CHANGED. That is what keeps the link idle during a long turn, and it is// why rule 2 has to exist at all.-import { appendFile } from 'node:fs/promises'import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'+import { DialLog } from './dialLog.js'import { FirmwareTransfer } from './fwPush.js'import { SerialLink, findDialPort } from './serial.js'@@ -411,11 +411,21 @@ export class CableSession {constructor(private readonly host: CableHost,- /** Where framed device logs are appended. The dial has one USB port, so this file is its console. */- private readonly logPath: string,+ /** The dial's console, as a file: framed device logs and this side's `cable:` events, one day each. */+ private readonly dialLog: DialLog,private readonly openPort: PortOpener = openDialPort,) {}+ /**+ * Every `cable:` event goes two ways: to the daemon's console as before, and into the dial's log with a+ * `[daemon]` prefix — the stuck-dial report is read end to end from ONE file, device lines and what the+ * desk did to it interleaved.+ */+ private log(line: string): void {+ this.host.log(line)+ this.dialLog.daemon(line.replace(/^cable: /, ''))+ }+get isConnected(): boolean {return this.link?.isOpen === true && this.greetedMac !== null}@@ -438,6 +448,8 @@ export class CableSession {private async tick(): Promise<void> {if (this.stopped) return+ // The firmware beats once a minute; the gap is marked in the dial's own log, where it is read.+ this.dialLog.tick(this.isConnected)if (!this.link?.isOpen) {await this.tryOpen()return@@ -456,14 +468,14 @@ export class CableSession {// fail to open rather than steal it back — this interval only decides how soon we would find OUR// dial if the user unplugged theirs and plugged ours into the same socket.this.foreignRetryAt = Date.now() + 60_000- this.host.log(`cable: ${this.link.path} is not a Harness dial (${this.bytesSinceOpen} B, no frames) — releasing it`)+ this.log(`cable: ${this.link.path} is not a Harness dial (${this.bytesSinceOpen} B, no frames) — releasing it`)await this.link.close('not ours')this.link = nullreturn}// Rule 2. The read never fails on a dead handle, so silence is the only symptom there is.if (Date.now() - this.lastRx > SILENCE_MS) {- this.host.log('cable: silent, reopening the port')+ this.log('cable: silent, reopening the port')// close() runs onClosed, which is where onDialGone fires — one path for "the dial is not there",// whether the cable was pulled or the far end simply stopped answering.await this.link.close('silence')@@ -559,7 +571,7 @@ export class CableSession {} catch (err) {// A port that another process holds is the ordinary case, not a fault: esptool, a serial monitor,// or a second daemon. Say so and try again on the next tick.- this.host.log(`cable: cannot open the dial: ${(err as Error).message}`)+ this.log(`cable: cannot open the dial: ${(err as Error).message}`)return} finally {this.opening = false@@ -596,11 +608,11 @@ export class CableSession {// keyed by MAC and outlives the port precisely so this one does not have to.this.offered.clear()this.lastRx = Date.now()- this.host.log(`cable: open on ${opened.path}`)+ this.log(`cable: open on ${opened.path}`)}private onClosed(why: string): void {- this.host.log(`cable: closed (${why})`)+ this.log(`cable: closed (${why})`)this.host.onDialGone?.()this.host.onDialStatus?.({ attached: false })this.link = null@@ -637,8 +649,7 @@ export class CableSession {if (frame.type === CableType.Log) {// The dial's console. It shares its one USB port with this protocol, so these frames are the only// way its log survives at all while the daemon holds the port.- const line = Buffer.from(frame.payload).toString('utf8')- void appendFile(this.logPath, `${new Date().toISOString()} ${line}\n`).catch(() => {})+ this.dialLog.device(Buffer.from(frame.payload).toString('utf8'))return}if (frame.type === CableType.Pcm) {@@ -646,7 +657,7 @@ export class CableSession {return}// An unknown type is a dial running ahead of this daemon. Visible, never fatal.- this.host.log(`cable: unknown frame type 0x${frame.type.toString(16)}`)+ this.log(`cable: unknown frame type 0x${frame.type.toString(16)}`)})}@@ -667,7 +678,7 @@ export class CableSession {const product = str('product')if (product !== CABLE_PRODUCT) {if (this.foreignPort !== this.link?.path) {- this.host.log(`cable: greeted by a '${product ?? 'nameless'}' dial, not a ${CABLE_PRODUCT} one — releasing the port`)+ this.log(`cable: greeted by a '${product ?? 'nameless'}' dial, not a ${CABLE_PRODUCT} one — releasing the port`)}this.foreignPort = this.link?.path ?? nullthis.foreignRetryAt = Date.now() + 60_000@@ -699,7 +710,7 @@ export class CableSession {const returning = mac === this.greetedMacthis.greetedMac = macthis.greetedFw = fw- this.host.log(`cable: dial ${mac} ${returning ? 'back ' : ''}on fw ${fw} proto ${msg.proto}`)+ this.log(`cable: dial ${mac} ${returning ? 'back ' : ''}on fw ${fw} proto ${msg.proto}`)this.host.onDialStatus?.({ attached: true, fw })// BEFORE the state push, not after: the push reads the selected machine, and for a remote one// that means an RPC over a lane this is what re-opens.@@ -743,7 +754,7 @@ export class CableSession {try {items = await this.host.listModels(agentId)} catch (err) {- this.host.log(`cable: models for ${agentId} failed (${(err as Error).message})`)+ this.log(`cable: models for ${agentId} failed (${(err as Error).message})`)}// Answered either way. An empty catalog closes the dial's picker cleanly; silence strands it on a// spinner until its own timeout, which reads as a hang rather than "this engine has no choices".@@ -765,7 +776,7 @@ export class CableSession {} else {// SAID OUT LOUD. A dropped report is a dial and a window on different agents, and dropping// it silently is how that state became impossible to explain from the log.- this.host.log(`cable: dropped dial focus ${agentId} — waiting for ${this.expectedAppFocusEcho}`)+ this.log(`cable: dropped dial focus ${agentId} — waiting for ${this.expectedAppFocusEcho}`)}return}@@ -783,7 +794,7 @@ export class CableSession {// is fixed at the source now (carousel_goto in the firmware), which leaves only the stale repeat// of the tile the dial was already on to guard against.if (this.drivingAppFocus && now - this.drivingSince < APP_SWITCH_REPAINT_MS) {- this.host.log(`cable: dropped dial focus ${agentId} — repaint from the switch in flight`)+ this.log(`cable: dropped dial focus ${agentId} — repaint from the switch in flight`)return}// Remember where the dial IS, not just that it said so: followApp() compares against this to@@ -884,7 +895,7 @@ export class CableSession {this.host.onDialStatus?.({ attached: true, fw: this.greetedFw ?? undefined })returndefault:- this.host.log(`cable: unhandled message '${msg.t}'`)+ this.log(`cable: unhandled message '${msg.t}'`)}}@@ -905,13 +916,13 @@ export class CableSession {private mayOffer(mac: string, version: string): boolean {const key = `${mac}:${version}`if (this.written.has(key)) {- this.host.log(`cable: firmware ${version} already written to ${mac} — not offering it again`)+ this.log(`cable: firmware ${version} already written to ${mac} — not offering it again`)return false}const now = Date.now()const recent = (this.writeLog.get(mac) ?? []).filter((at) => now - at < 60 * 60 * 1000)if (recent.length >= FW_WRITES_PER_HOUR) {- this.host.log(`cable: ${mac} has taken ${recent.length} firmware writes this hour — holding off`)+ this.log(`cable: ${mac} has taken ${recent.length} firmware writes this hour — holding off`)return false}this.written.add(key)@@ -933,7 +944,7 @@ export class CableSession {if (!this.mayOffer(mac, candidate.version)) returnthis.offered.add(offerKey)- this.host.log(`cable: offering firmware ${candidate.version} (${candidate.image.length} B)`)+ this.log(`cable: offering firmware ${candidate.version} (${candidate.image.length} B)`)this.offeringTo = candidate.versionthis.transfer = new FirmwareTransfer(candidate.image,@@ -942,7 +953,7 @@ export class CableSession {if (!this.link?.isOpen) throw new Error('port closed mid-transfer')await this.link.write(encodeCableFrame(CableType.Fw, slice))},- (line) => this.host.log(line),+ (line) => this.log(line),)await this.send({ t: 'fw.offer', version: candidate.version, size: candidate.image.length, sha256: candidate.sha256 })}@@ -951,7 +962,7 @@ export class CableSession {if (!this.voice) return // audio outside a turn is a dial that restarted mid-capturethis.voice.bytes += chunk.lengthif (this.voice.bytes > VOICE_MAX_BYTES) {- this.host.log('cable: voice over the length cap, dropped')+ this.log('cable: voice over the length cap, dropped')this.voice = nullreturn}@@ -967,7 +978,7 @@ export class CableSession {}const seconds = turn.bytes / (turn.rate * 2)- this.host.log(`cable: voice ${seconds.toFixed(1)}s (${Math.round(turn.bytes / 1024)} KB) → stt`)+ this.log(`cable: voice ${seconds.toFixed(1)}s (${Math.round(turn.bytes / 1024)} KB) → stt`)let transcript: stringtry {@@ -996,7 +1007,7 @@ export class CableSession {? await this.host.routeInWindow(transcript, turn.cmd): ({ t: 'unavailable' } as const)if (inWindow.t === 'sent') {- this.host.log(`cable: the window routed the spoken task → ${inWindow.agentId.slice(0, 8)}`)+ this.log(`cable: the window routed the spoken task → ${inWindow.agentId.slice(0, 8)}`)await this.send({t: 'voice.transcript',routeId: '',@@ -1025,7 +1036,7 @@ export class CableSession {try {const decision = await this.host.route(transcript, agents)agentId = decision.agentId- this.host.log(`cable: routed → ${agentId} (${decision.reason})`)+ this.log(`cable: routed → ${agentId} (${decision.reason})`)} catch (err) {await this.send({ t: 'voice.error', message: (err as Error).message })return@@ -1050,7 +1061,7 @@ export class CableSession {await this.link.write(encodeCableFrame(CableType.Json, Buffer.from(JSON.stringify(msg), 'utf8')))return true} catch (err) {- this.host.log(`cable: write failed (${(err as Error).message})`)+ this.log(`cable: write failed (${(err as Error).message})`)await this.link.close('write failed')return false}@@ -1089,7 +1100,7 @@ export class CableSession {this.lastAgentsKey = key// Every push, and only pushes. The dial showing a different number from the daemon is a question this// line answers in one look: either the daemon never said it, or it said it and the dial disagreed.- this.host.log(`cable: agents → ${agents.length}${force ? ' (attach)' : ''}`)+ this.log(`cable: agents → ${agents.length}${force ? ' (attach)' : ''}`)await this.send({ t: 'agents.begin' })for (const a of agents) {@@ -1176,7 +1187,7 @@ export class CableSession {const key = `${selected}|${swarms.map((s) => `${s.id}:${s.name}:${s.agents}`).join('|')}`if (!force && key === this.lastSwarmsKey) returnthis.lastSwarmsKey = key- this.host.log(`cable: swarms → ${swarms.length}${selected ? ` (on ${selected})` : ''}${force ? ' [push]' : ''}`)+ this.log(`cable: swarms → ${swarms.length}${selected ? ` (on ${selected})` : ''}${force ? ' [push]' : ''}`)// ONE frame, not a begin/row/end stream: two dozen rows of an id, a name and a count fit in a// kilobyte, and the dial replaces the whole list on arrival either way.await this.send({ t: 'swarms', selected, items: swarms.map((s) => ({ id: s.id, name: s.name, agents: s.agents })) })@@ -1210,7 +1221,7 @@ export class CableSession {const key = CableSession.machinesKey(machines, source, selected)if (!force && key === this.lastMachinesKey) returnthis.lastMachinesKey = key- this.host.log(`cable: machines → ${machines.length} (${source})${force ? ' [push]' : ''}`)+ this.log(`cable: machines → ${machines.length} (${source})${force ? ' [push]' : ''}`)await this.send({ t: 'machines.begin' })for (const m of machines) {@@ -1236,11 +1247,11 @@ export class CableSession {}const result = await this.host.selectMachine(machineId)if (!result.ok) {- this.host.log(`cable: machine.select ${machineId} refused (${result.code})`)+ this.log(`cable: machine.select ${machineId} refused (${result.code})`)await this.send({ t: 'machine.error', machineId, code: result.code, message: result.message })return}- this.host.log(`cable: machine.select → ${machineId}`)+ this.log(`cable: machine.select → ${machineId}`)// REQUIRED, not hygiene: two machines whose agents happen to share names and engines produce an equal// agentsKey, and the new machine's list would then never be sent at all.this.lastAgentsKey = ''@@ -1330,7 +1341,7 @@ export class CableSession {this.drivingAppFocus = truetry {if (machineId && machineId !== this.host.selectedMachine()) {- this.host.log(`cable: following the app to machine ${machineId}`)+ this.log(`cable: following the app to machine ${machineId}`)await this.selectMachine(machineId)}// A newer selection can arrive while the remote machine RPC/list push is in flight. Never let@@ -1340,7 +1351,7 @@ export class CableSession {if (generation !== this.appFocusGeneration || agentId === this.desiredFocus) return// Said before the frame goes out, not after: the frame itself succeeds either way.const unknown = this.host.knows?.(agentId) === false- this.host.log(`cable: following the app to agent ${agentId}${unknown ? ' — NOT in this daemon\'s list, the dial has no tile for it' : ''}`)+ this.log(`cable: following the app to agent ${agentId}${unknown ? ' — NOT in this daemon\'s list, the dial has no tile for it' : ''}`)this.expectedAppFocusEcho = agentIdthis.expectedAppFocusEchoUntil = Date.now() + APP_FOCUS_SETTLE_MS// THE LIST FIRST, THEN THE FOCUS — the fix for "clicking a rail agent that has no tile does not@@ -1368,7 +1379,7 @@ export class CableSession {// fire-and-forgets followApp, so the session log is the only place an unexpected rejection would// otherwise be visible; consume it here rather than creating an unhandled rejection.this.appFocusTail = task.catch((err) => {- this.host.log(`cable: could not follow app focus (${(err as Error).message})`)+ this.log(`cable: could not follow app focus (${(err as Error).message})`)})await this.appFocusTail}diff --git a/cli/src/cable/dialLog.spec.ts b/cli/src/cable/dialLog.spec.tsnew file mode 100644index 000000000..8e2113367--- /dev/null+++ b/cli/src/cable/dialLog.spec.ts@@ -0,0 +1,103 @@+import { mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { DialLog } from './dialLog.js'++const DAY = 86_400_000++function dir() { return mkdtempSync(join(tmpdir(), 'dial-log-')) }++/** A clock the test moves by hand. */+function clock(start = Date.UTC(2026, 8, 15, 12)) {+ let t = start+ return { now: () => t, advance: (ms: number) => { t += ms } }+}++describe('DialLog', () => {+ it('writes device and daemon lines into one dated file, marked apart', async () => {+ const d = dir()+ const c = clock()+ const log = new DialLog(d, { now: c.now })+ log.daemon('open on /dev/cu.usbmodem1')+ log.device('I (1234) touch: press (200,300)')+ await log.flush()+ const text = readFileSync(log.currentPath, 'utf8')+ expect(log.currentPath).toBe(join(d, DialLog.fileName(c.now())))+ expect(text).toMatch(/^\S+ \[daemon\] open on \/dev\/cu\.usbmodem1\n\S+ I \(1234\) touch: press \(200,300\)\n$/)+ })++ it('rolls to a new file at midnight and prunes days past retention', async () => {+ const d = dir()+ const c = clock()+ // Stale files from before the window, and one just inside it.+ const stale = DialLog.fileName(c.now() - 8 * DAY)+ const kept = DialLog.fileName(c.now() - 7 * DAY) // exactly on the edge: kept today, gone tomorrow+ writeFileSync(join(d, stale), 'old\n')+ writeFileSync(join(d, kept), 'recent\n')+ writeFileSync(join(d, 'app-20260101.log'), 'not ours\n')+ const log = new DialLog(d, { now: c.now, retainDays: 7 })+ log.device('day one')+ await log.flush()+ expect(readdirSync(d).sort()).toEqual([ 'app-20260101.log', DialLog.fileName(c.now()), kept ].sort())+ c.advance(DAY)+ log.device('day two')+ await log.flush()+ const names = readdirSync(d)+ expect(names).toContain(DialLog.fileName(c.now()))+ expect(readFileSync(join(d, DialLog.fileName(c.now())), 'utf8')).toContain('day two')+ // The pruned set moves with the day: `kept` is now 8 days old and goes.+ expect(names).not.toContain(kept)+ expect(names).toContain('app-20260101.log')+ })++ it('caps a day and says so once', async () => {+ const d = dir()+ const c = clock()+ const log = new DialLog(d, { now: c.now, maxBytesPerDay: 200 })+ for (let i = 0; i < 20; i++) log.device(`line ${i} ${'x'.repeat(20)}`)+ await log.flush()+ const lines = readFileSync(log.currentPath, 'utf8').trimEnd().split('\n')+ expect(lines.at(-1)).toMatch(/\[daemon\] dial log capped for today/)+ expect(lines.filter((l) => l.includes('capped'))).toHaveLength(1)+ expect(lines.length).toBeLessThan(10)+ // A new day starts clean.+ c.advance(DAY)+ log.device('fresh')+ await log.flush()+ expect(readFileSync(log.currentPath, 'utf8')).toBe(`${new Date(c.now()).toISOString()} fresh\n`)+ })++ it('marks a missing heartbeat once, and its return', async () => {+ const d = dir()+ const c = clock()+ const log = new DialLog(d, { now: c.now, heartbeatGapMs: 90_000 })+ log.device('I (60000) ui: alive up=60s heap=100/200 lv=1 touches=3 last_press=12s')+ c.advance(60_000)+ log.tick(true)+ c.advance(31_000)+ log.tick(true)+ log.tick(true)+ await log.flush()+ let text = readFileSync(log.currentPath, 'utf8')+ expect(text.match(/no dial heartbeat for 91s/g)).toHaveLength(1)+ c.advance(30_000)+ log.device('I (180000) ui: alive up=180s heap=100/200 lv=1 touches=3 last_press=12s')+ await log.flush()+ text = readFileSync(log.currentPath, 'utf8')+ expect(text).toMatch(/dial heartbeat back after 121s/)+ })++ it('does not chase a heartbeat while the port is closed', async () => {+ const d = dir()+ const c = clock()+ const log = new DialLog(d, { now: c.now, heartbeatGapMs: 90_000 })+ log.device('I (60000) ui: alive up=60s')+ log.tick(false) // unplugged+ c.advance(DAY / 2)+ log.tick(true) // back, and the first beat has not arrived yet+ await log.flush()+ const all = readdirSync(d).map((n) => readFileSync(join(d, n), 'utf8')).join('')+ expect(all).not.toMatch(/no dial heartbeat/)+ })+})diff --git a/cli/src/cable/dialLog.ts b/cli/src/cable/dialLog.tsnew file mode 100644index 000000000..46687095a--- /dev/null+++ b/cli/src/cable/dialLog.ts@@ -0,0 +1,157 @@+import { appendFile, mkdir, readdir, unlink } from 'node:fs/promises'+import { join } from 'node:path'++/**+ * The dial's log, as a file somebody can send.+ *+ * The dial has one USB port and no flash log of its own: every `ESP_LOG` line it prints is framed over+ * the cable (type 0x04) and this is where it lands. The daemon's own `cable:` events go into the SAME+ * file, prefixed `[daemon]`, so a report reads end to end from one place — what the device said beside+ * what the desk did to it (opened the port, pushed a focus, saw silence).+ *+ * One file per day, `dial-YYYYMMDD.log`, in `~/.harness/logs` — the directory the desktop app already+ * keeps its own `app-*.log`/`cli-*.log` in and exports from. Days older than `retainDays` are deleted+ * on the first write after midnight; a day past `maxBytesPerDay` gets one `capped` line and then+ * nothing, so a firmware stuck in a log loop cannot fill the disk.+ *+ * Firmware lines keep their own `I (ticks) tag:` prefix beside the wall time, so a reboot shows as+ * ticks going back to zero. The firmware's 60s `alive` heartbeat is watched here too: cable lines+ * continuing while that one stops is what a wedged LVGL task looks like, and its ABSENCE is the+ * evidence, so this marks the gap in the file rather than leaving it to be inferred.+ */+export interface DialLogOptions {+ /** Days of `dial-*.log` to keep. Default 7. */+ retainDays?: number+ /** Bytes per day before the file is capped. Default 20 MB. */+ maxBytesPerDay?: number+ /** How long without an `alive` line from the dial before the gap is marked. Default 90s. */+ heartbeatGapMs?: number+ /** Wall clock, for tests. */+ now?: () => number+}++/** The firmware's liveness line — `ui_screens.c` prints one a minute from the LVGL task. */+const HEARTBEAT = /\balive up=/++export class DialLog {+ private readonly retainDays: number+ private readonly maxBytesPerDay: number+ private readonly heartbeatGapMs: number+ private readonly now: () => number++ private day: string | null = null+ private bytesToday = 0+ private capped = false+ /** Writes are chained so lines land in the order they were logged, and so tests can `flush()`. */+ private chain: Promise<void> = Promise.resolve()++ private lastHeartbeat: number | null = null+ private gapMarked = false++ constructor(readonly dir: string, opts: DialLogOptions = {}) {+ this.retainDays = opts.retainDays ?? 7+ this.maxBytesPerDay = opts.maxBytesPerDay ?? 20 * 1024 * 1024+ this.heartbeatGapMs = opts.heartbeatGapMs ?? 90_000+ this.now = opts.now ?? Date.now+ }++ /** `dial-YYYYMMDD.log` for a moment, in local time like the app's own files. */+ static fileName(at: number | Date): string {+ const d = new Date(at)+ const y = d.getFullYear()+ const m = String(d.getMonth() + 1).padStart(2, '0')+ const day = String(d.getDate()).padStart(2, '0')+ return `dial-${y}${m}${day}.log`+ }++ /** The file the next line would land in. */+ get currentPath(): string {+ return join(this.dir, DialLog.fileName(this.now()))+ }++ /** A line the dial printed, verbatim. */+ device(line: string): void {+ if (HEARTBEAT.test(line)) this.heartbeat()+ this.write(line)+ }++ /** Something the daemon did to, or saw from, the dial. */+ daemon(line: string): void {+ this.write(`[daemon] ${line}`)+ }++ /**+ * Called on the session's tick while the port is open. Marks a missing heartbeat once, and again+ * when it comes back; a closed port resets the watch, since a dial that is not there owes no beat.+ */+ tick(connected: boolean): void {+ if (!connected) {+ this.lastHeartbeat = null+ this.gapMarked = false+ return+ }+ if (this.lastHeartbeat === null || this.gapMarked) return+ const gap = this.now() - this.lastHeartbeat+ if (gap >= this.heartbeatGapMs) {+ this.gapMarked = true+ this.daemon(`no dial heartbeat for ${Math.round(gap / 1000)}s — the cable is up, the UI task may be wedged`)+ }+ }++ /** Every queued write has reached the file. */+ flush(): Promise<void> {+ return this.chain+ }++ private heartbeat(): void {+ const now = this.now()+ if (this.gapMarked && this.lastHeartbeat !== null) {+ this.daemon(`dial heartbeat back after ${Math.round((now - this.lastHeartbeat) / 1000)}s`)+ }+ this.gapMarked = false+ this.lastHeartbeat = now+ }++ private write(text: string): void {+ const at = this.now()+ const file = DialLog.fileName(at)+ const rolled = file !== this.day+ if (rolled) {+ this.day = file+ this.bytesToday = 0+ this.capped = false+ }+ if (this.capped) return+ const line = `${new Date(at).toISOString()} ${text}\n`+ this.bytesToday += Buffer.byteLength(line)+ let out = line+ if (this.bytesToday > this.maxBytesPerDay) {+ this.capped = true+ out = `${new Date(at).toISOString()} [daemon] dial log capped for today at ${this.maxBytesPerDay} B — dropping the rest\n`+ }+ const path = join(this.dir, file)+ this.chain = this.chain+ .then(async () => {+ await mkdir(this.dir, { recursive: true })+ if (rolled) await this.prune(at)+ await appendFile(path, out)+ })+ .catch(() => {})+ }++ /** Delete `dial-*.log` files older than `retainDays` before `at`. Best effort. */+ private async prune(at: number): Promise<void> {+ if (this.retainDays <= 0) return+ const cutoff = DialLog.fileName(at - this.retainDays * 86_400_000)+ let names: string[]+ try {+ names = await readdir(this.dir)+ } catch {+ return+ }+ for (const name of names) {+ if (!/^dial-\d{8}\.log$/.test(name) || name >= cutoff) continue+ await unlink(join(this.dir, name)).catch(() => {})+ }+ }+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 546d8b331..d4164231a 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -29,6 +29,8 @@ import { VERSION } from './version.js'import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'import { warmLoginShellEnvironment } from './lib/loginShellEnv.js'import { ensureUtf8Locale } from './lib/childLocale.js'+import { DialLog } from './cable/dialLog.js'+import { buildLogBundle, bundleFileName, redactSecretsInText } from './lib/logBundle.js'import { CableSession } from './cable/cableSession.js'import { DaemonCableHost, cableEventFor, cableQuestionFor, cableQuestionCloseFor } from './cable/cableHost.js'@@ -283,6 +285,7 @@ Machine:harness stop stop the background adapter (keeps the SSO session)harness reset stop the adapter and clear local CLI stateharness status show whether it's running (+ version)+ harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktopharness machines list the machines on this account (this computer's is marked)harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)harness version print the installed version (v${VERSION})@@ -4291,7 +4294,13 @@ async function runForeground(session: AuthSession): Promise<void> {cableHostRef = cableHost// Anything the window said while this was still being built.cableHost.setDesk(appPaneAgents)- const cable = new CableSession(cableHost, join(env.ADAPTER_DATA_DIR, 'dial.log'))+ // The dial's log now lives with the app's, one file a day — see dialLog.ts. The old unbounded+ // `cli/data/dial.log` is cut down to a pointer, for anyone with a bookmark.+ const legacyDialLog = join(env.ADAPTER_DATA_DIR, 'dial.log')+ if (existsSync(legacyDialLog)) {+ try { writeFileSync(legacyDialLog, `moved to ${join(env.HARNESS_LOGS_DIR, 'dial-YYYYMMDD.log')}\n`) } catch { /* best effort */ }+ }+ const cable = new CableSession(cableHost, new DialLog(env.HARNESS_LOGS_DIR))cableRef = cableautonomousDeviceService = new AutonomousDeviceService({@@ -4439,6 +4448,7 @@ function printInfoBlock(opts: {console.log(row('agents', `${opts.sessions} available`))console.log(row('pid', String(opts.pid)))console.log(row('logs', tildify(LOG_FILE)))+ console.log(row('dial log', tildify(join(env.HARNESS_LOGS_DIR, 'dial-YYYYMMDD.log'))))console.log(row('dashboard', `http://127.0.0.1:${daemonPort()}`))console.log(rule)console.log(' ▸ Open in your browser to chat with this computer:')@@ -5225,6 +5235,37 @@ async function status(): Promise<void> {process.exit(0)}+/**+ * `harness logs export [--to <dir>] [--days N] [--json]` — the last week of every log this product+ * writes, zipped to the Desktop (or `--to`), secrets blanked. The file a bug report is made of; the+ * desktop app's Settings ▸ Debug ▸ Export logs runs this same command.+ */+async function logsExportCommand(json: boolean): Promise<void> {+ const flagValue = (name: string): string | undefined => {+ const at = process.argv.indexOf(name)+ return at >= 0 ? process.argv[at + 1] : undefined+ }+ const days = Math.max(1, Number(flagValue('--days') ?? 7) || 7)+ const desktop = join(homedir(), 'Desktop')+ const to = flagValue('--to') ?? (existsSync(desktop) ? desktop : process.cwd())+ const now = new Date()+ const notes = [`machine: ${readAuthSession()?.machineId ?? 'not signed in'}`]+ const { zip, included } = buildLogBundle({+ logsDir: env.HARNESS_LOGS_DIR, dataDir: env.ADAPTER_DATA_DIR, days, now, version: VERSION, notes,+ redact: redactSecretsInText,+ })+ mkdirSync(to, { recursive: true })+ const path = join(to, bundleFileName(now))+ writeFileSync(path, zip)+ if (json) console.log(JSON.stringify({ path, included, bytes: zip.length }))+ else {+ console.log(`wrote ${tildify(path)} (${Math.round(zip.length / 1024)} KB)`)+ for (const name of included) console.log(` ${name}`)+ if (!included.length) console.log(' (no logs found)')+ }+ process.exit(0)+}+// ── arg parse ──────────────────────────────────────────────────────────────────────────────────const [, , cmd, ...rest] = process.argvconst flags = rest.filter((a) => a.startsWith('-'))@@ -5349,6 +5390,10 @@ switch (cmd) {case 'status':status().catch(onError)break+ case 'logs':+ if (args[0] === 'export') logsExportCommand(flags.includes('--json')).catch(onError)+ else { console.error(`Unknown command: logs ${args[0] ?? ''}`); usage(1) }+ breakcase 'update':updateCommand(flags.includes('--force')).catch(onError)breakdiff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 70345e960..3f48810b4 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -230,6 +230,10 @@ const envSchema = z.object({.default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'devin', 'config.json')),// Where the tmux-session registry and daemon-local state are persisted.ADAPTER_DATA_DIR: z.string().default(adapterDataDir),+ // Logs meant to be READ and sent — the dial's `dial-YYYYMMDD.log` — beside the desktop app's own+ // `app-*.log`/`cli-*.log`, so one directory holds everything a bug report needs. Not the data dir:+ // `harness.log` there is the daemon's console, and `harness reset` wipes it.+ HARNESS_LOGS_DIR: z.string().default(join(adapterRootDir, 'logs')),// This computer's stable id, minted once and never regenerated (see computerIdFile above). Pin it// explicitly on a box with no durable home — a container or CI job that gets a fresh ~/.harness on// every boot would otherwise look like a NEW computer each time and collect a machine per start.diff --git a/cli/src/lib/logBundle.spec.ts b/cli/src/lib/logBundle.spec.tsnew file mode 100644index 000000000..3e6d020d5--- /dev/null+++ b/cli/src/lib/logBundle.spec.ts@@ -0,0 +1,77 @@+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { inflateRawSync } from 'node:zlib'+import { describe, expect, it } from 'vitest'+import { buildLogBundle, bundleFileName, redactSecretsInText } from './logBundle.js'+import { crc32, writeZip } from './zipWriter.js'++/** Enough of a ZIP reader to check what writeZip produced: walks the local headers. */+function readZip(zip: Buffer): Map<string, Buffer> {+ const out = new Map<string, Buffer>()+ let at = 0+ while (zip.readUInt32LE(at) === 0x04034b50) {+ const method = zip.readUInt16LE(at + 8)+ const crc = zip.readUInt32LE(at + 14)+ const csize = zip.readUInt32LE(at + 18)+ const nlen = zip.readUInt16LE(at + 26)+ const name = zip.subarray(at + 30, at + 30 + nlen).toString('utf8')+ const body = zip.subarray(at + 30 + nlen, at + 30 + nlen + csize)+ const data = method === 8 ? inflateRawSync(body) : Buffer.from(body)+ expect(crc32(data)).toBe(crc)+ out.set(name, data)+ at += 30 + nlen + csize+ }+ expect(zip.readUInt32LE(at)).toBe(0x02014b50) // the central directory follows the last entry+ return out+}++describe('zipWriter', () => {+ it('round-trips deflated and stored entries', () => {+ const text = Buffer.from('hello hello hello hello hello hello\n'.repeat(50))+ const noise = Buffer.from(Array.from({ length: 300 }, (_, i) => (i * 7919) % 256))+ const zip = writeZip([{ name: 'a/text.log', data: text }, { name: 'noise.bin', data: noise }])+ const files = readZip(zip)+ expect(files.get('a/text.log')?.equals(text)).toBe(true)+ expect(files.get('noise.bin')?.equals(noise)).toBe(true)+ expect(zip.length).toBeLessThan(text.length) // the repeated text really was compressed+ })++ it('computes the standard CRC-32', () => {+ expect(crc32(Buffer.from('123456789'))).toBe(0xcbf43926)+ })+})++describe('buildLogBundle', () => {+ it('takes the last week of dated logs, the daemon log tail, and redacts', () => {+ const root = mkdtempSync(join(tmpdir(), 'bundle-'))+ const logs = join(root, 'logs'), data = join(root, 'data')+ mkdirSync(logs); mkdirSync(data)+ const now = new Date(2026, 8, 15, 10, 30)+ writeFileSync(join(logs, 'dial-20260915.log'), 'I (1) touch: press\nsession_token: abcdefgh12345\n')+ writeFileSync(join(logs, 'app-20260910.log'), 'in window\n')+ writeFileSync(join(logs, 'app-20260908.log'), 'too old\n')+ writeFileSync(join(logs, 'cli-20260915.log'), 'Bearer abcdefghijklmnop\n')+ writeFileSync(join(logs, 'unrelated.txt'), 'no\n')+ writeFileSync(join(data, 'harness.log'), 'x'.repeat(100) + 'THE END\n')+ const { zip, included } = buildLogBundle({+ logsDir: logs, dataDir: data, now, version: '0.2.21', redact: redactSecretsInText,+ harnessLogTailBytes: 8, notes: ['app: 1.1.22'],+ })+ const files = readZip(zip)+ expect([...files.keys()]).toEqual(['README.txt', 'logs/app-20260910.log', 'logs/cli-20260915.log', 'logs/dial-20260915.log', 'harness.log'])+ expect(files.get('logs/dial-20260915.log')?.toString()).toBe('I (1) touch: press\nsession_token: <redacted>\n')+ expect(files.get('logs/cli-20260915.log')?.toString()).toBe('Bearer <redacted>\n')+ expect(files.get('harness.log')?.toString()).toBe('THE END\n')+ expect(files.get('README.txt')?.toString()).toContain('app: 1.1.22')+ expect(included).toContain('dial-20260915.log')+ expect(bundleFileName(now)).toBe('harness-logs-20260915-1030.zip')+ })++ it('still produces a bundle with a README when there is nothing to include', () => {+ const root = mkdtempSync(join(tmpdir(), 'bundle-'))+ const { zip, included } = buildLogBundle({ logsDir: join(root, 'none'), dataDir: root, version: '0', redact: (s) => s })+ expect(included).toEqual([])+ expect(readZip(zip).get('README.txt')?.toString()).toContain('nothing')+ })+})diff --git a/cli/src/lib/logBundle.ts b/cli/src/lib/logBundle.tsnew file mode 100644index 000000000..2737b5704--- /dev/null+++ b/cli/src/lib/logBundle.ts@@ -0,0 +1,115 @@+import { readdirSync, readFileSync, statSync, openSync, readSync, closeSync } from 'node:fs'+import { join } from 'node:path'+import { writeZip, type ZipEntry } from './zipWriter.js'++/**+ * The file a person sends when the dial got stuck: the last week of every log this product writes, in+ * one zip, secrets blanked.+ *+ * app-YYYYMMDD.log, cli-YYYYMMDD.log the desktop app's own log and its CLI transcript+ * dial-YYYYMMDD.log the dial's console + the daemon's cable events (dialLog.ts)+ * harness.log (tail) the daemon's console — the last few MB, which is where today is+ * README.txt when, which version, what was included+ *+ * Shared by `harness logs export` and the desktop app's Settings ▸ Debug button, so the two produce+ * the same bundle; the app runs this through the CLI rather than carrying a second copy.+ */+export interface LogBundleOptions {+ /** `~/.harness/logs` — the dated files. */+ logsDir: string+ /** `~/.harness/cli/data` — where `harness.log` is. */+ dataDir: string+ /** Days of dated logs to include, counting today. Default 7. */+ days?: number+ /** How much of the end of `harness.log` to take. Default 5 MB. */+ harnessLogTailBytes?: number+ now?: Date+ version: string+ /** Free text for the README — `harness status` output, the app's version, anything else known. */+ notes?: string[]+ /** Runs over every text file before it is written. */+ redact: (text: string) => string+}++const DATED = /^(app|cli|dial)-(\d{8})\.log$/++function ymd(d: Date): string {+ return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`+}++/** `harness-logs-YYYYMMDD-HHMM.zip` — sortable, and says what it is in Finder. */+export function bundleFileName(now: Date): string {+ return `harness-logs-${ymd(now)}-${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}.zip`+}++function readTail(path: string, bytes: number): Buffer {+ const size = statSync(path).size+ const from = Math.max(0, size - bytes)+ const fd = openSync(path, 'r')+ try {+ const out = Buffer.alloc(size - from)+ readSync(fd, out, 0, out.length, from)+ return out+ } finally {+ closeSync(fd)+ }+}++/** The bundle as bytes, plus what went into it — for the README and for the caller's own message. */+export function buildLogBundle(opts: LogBundleOptions): { zip: Buffer; included: string[] } {+ const now = opts.now ?? new Date()+ const days = opts.days ?? 7+ const cutoff = ymd(new Date(now.getTime() - (days - 1) * 86_400_000))+ const entries: ZipEntry[] = []+ const included: string[] = []++ let names: string[] = []+ try { names = readdirSync(opts.logsDir).sort() } catch { /* no logs directory yet */ }+ for (const name of names) {+ const m = DATED.exec(name)+ if (!m || m[2] < cutoff) continue+ const path = join(opts.logsDir, name)+ try {+ const text = readFileSync(path, 'utf8')+ entries.push({ name: `logs/${name}`, data: Buffer.from(opts.redact(text)), mtime: statSync(path).mtime })+ included.push(name)+ } catch { /* unreadable: skipped, said in the README below */ }+ }++ const harnessLog = join(opts.dataDir, 'harness.log')+ try {+ const tail = readTail(harnessLog, opts.harnessLogTailBytes ?? 5 * 1024 * 1024)+ const text = tail.toString('utf8')+ entries.push({ name: 'harness.log', data: Buffer.from(opts.redact(text)), mtime: statSync(harnessLog).mtime })+ included.push(`harness.log (last ${Math.round(tail.length / 1024)} KB)`)+ } catch { /* no daemon log */ }++ const readme = [+ `Harness log bundle`,+ `exported: ${now.toISOString()}`,+ `cli: v${opts.version}`,+ `window: last ${days} day${days === 1 ? '' : 's'} (from ${cutoff})`,+ ...(opts.notes ?? []),+ ``,+ `included:`,+ ...(included.length ? included.map((n) => ` ${n}`) : [' (nothing — no logs were found)']),+ ``,+ `Secrets (tokens, keys, passwords, signed URLs) were blanked before writing.`,+ `dial-*.log: the dial's own console (I/W/E lines, ticks since boot) interleaved with the daemon's`,+ `[daemon] cable events. 'alive up=' once a minute is the UI task's heartbeat; a gap in it while`,+ `[daemon] lines continue is a wedged UI task. 'boot: reset reason' after a session-up says why the`,+ `dial last rebooted; 'last:' lines are its log from just before a crash.`,+ ].join('\n')+ entries.unshift({ name: 'README.txt', data: Buffer.from(readme + '\n'), mtime: now })++ return { zip: writeZip(entries), included }+}++/** The same denylist the desktop app's `redactSecretsInText` applies — keep the two in step. */+export function redactSecretsInText(input: string): string {+ return input+ .replace(/(Bearer\s+)[A-Za-z0-9._-]{8,}/gi, '$1<redacted>')+ .replace(/\bsk-[A-Za-z0-9_-]{8,}/g, 'sk-<redacted>')+ .replace(/(["']?\b\w*(?:token|secret|password|passphrase|credential|api[_-]?key)\w*\b["']?\s*[:=]\s*["']?)([^\s"',}]{6,})/gi, '$1<redacted>')+ .replace(/([?&][^=\s&]*(?:token|key|secret|sig|signature)[^=\s&]*=)[^\s&]+/gi, '$1<redacted>')+}diff --git a/cli/src/lib/zipWriter.ts b/cli/src/lib/zipWriter.tsnew file mode 100644index 000000000..0f0166ab1--- /dev/null+++ b/cli/src/lib/zipWriter.ts@@ -0,0 +1,108 @@+import { deflateRawSync } from 'node:zlib'++/**+ * A ZIP file, written by hand.+ *+ * Node ships zlib and nothing that writes a container, and a log bundle has to be a `.zip` — the one+ * archive a person can open by double-clicking on every desktop this app ships to. The format is small:+ * a local header + deflated bytes per entry, a central directory that repeats the headers, and one+ * end-of-directory record. No zip64, no encryption, no streaming: a bundle is a few dozen files under+ * a hundred megabytes, built in memory.+ */+export interface ZipEntry {+ /** Path inside the archive, `/`-separated. */+ name: string+ data: Buffer+ /** Modification time for the entry. Default: now. */+ mtime?: Date+}++const CRC_TABLE = (() => {+ const t = new Uint32Array(256)+ for (let n = 0; n < 256; n++) {+ let c = n+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1+ t[n] = c >>> 0+ }+ return t+})()++export function crc32(buf: Buffer): number {+ let c = 0xffffffff+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8)+ return (c ^ 0xffffffff) >>> 0+}++/** MS-DOS date and time, the only stamp the classic header carries. Local time, two-second resolution. */+function dosStamp(d: Date): { date: number; time: number } {+ const year = Math.max(1980, d.getFullYear())+ return {+ date: ((year - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),+ time: (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1),+ }+}++export function writeZip(entries: ZipEntry[]): Buffer {+ const locals: Buffer[] = []+ const centrals: Buffer[] = []+ let offset = 0+ for (const entry of entries) {+ const name = Buffer.from(entry.name, 'utf8')+ const deflated = deflateRawSync(entry.data)+ // Store rather than deflate when compression buys nothing (an already-compressed file).+ const stored = deflated.length >= entry.data.length+ const body = stored ? entry.data : deflated+ const method = stored ? 0 : 8+ const crc = crc32(entry.data)+ const { date, time } = dosStamp(entry.mtime ?? new Date())+ // General purpose bit 11: names are UTF-8.+ const flags = 0x0800++ const local = Buffer.alloc(30)+ local.writeUInt32LE(0x04034b50, 0)+ local.writeUInt16LE(20, 4) // version needed+ local.writeUInt16LE(flags, 6)+ local.writeUInt16LE(method, 8)+ local.writeUInt16LE(time, 10)+ local.writeUInt16LE(date, 12)+ local.writeUInt32LE(crc, 14)+ local.writeUInt32LE(body.length, 18)+ local.writeUInt32LE(entry.data.length, 22)+ local.writeUInt16LE(name.length, 26)+ local.writeUInt16LE(0, 28) // extra length+ locals.push(local, name, body)++ const central = Buffer.alloc(46)+ central.writeUInt32LE(0x02014b50, 0)+ central.writeUInt16LE(20, 4) // version made by+ central.writeUInt16LE(20, 6) // version needed+ central.writeUInt16LE(flags, 8)+ central.writeUInt16LE(method, 10)+ central.writeUInt16LE(time, 12)+ central.writeUInt16LE(date, 14)+ central.writeUInt32LE(crc, 16)+ central.writeUInt32LE(body.length, 20)+ central.writeUInt32LE(entry.data.length, 24)+ central.writeUInt16LE(name.length, 28)+ central.writeUInt16LE(0, 30) // extra+ central.writeUInt16LE(0, 32) // comment+ central.writeUInt16LE(0, 34) // disk+ central.writeUInt16LE(0, 36) // internal attrs+ central.writeUInt32LE(0, 38) // external attrs+ central.writeUInt32LE(offset, 42)+ centrals.push(central, name)++ offset += local.length + name.length + body.length+ }+ const directory = Buffer.concat(centrals)+ const end = Buffer.alloc(22)+ end.writeUInt32LE(0x06054b50, 0)+ end.writeUInt16LE(0, 4)+ end.writeUInt16LE(0, 6)+ end.writeUInt16LE(entries.length, 8)+ end.writeUInt16LE(entries.length, 10)+ end.writeUInt32LE(directory.length, 12)+ end.writeUInt32LE(offset, 16)+ end.writeUInt16LE(0, 20)+ return Buffer.concat([...locals, directory, end])+}diff --git a/desktop/lib/core/reveal_folder.dart b/desktop/lib/core/reveal_folder.dartindex bb0bc4001..fd804a8f0 100644--- a/desktop/lib/core/reveal_folder.dart+++ b/desktop/lib/core/reveal_folder.dart@@ -25,3 +25,19 @@ Future<bool> revealFolder(String path) async {return false;}}++/// Selects [path] in the file manager — Finder's "Reveal", or the containing+/// folder where the platform has no such thing. For a file the app just wrote+/// and wants the user to find: the exported log bundle.+Future<bool> revealFile(String path) async {+ if (!File(path).existsSync()) return false;+ if (Platform.isMacOS) {+ try {+ final result = await Process.run('/usr/bin/open', ['-R', path]);+ return result.exitCode == 0;+ } on ProcessException {+ return false;+ }+ }+ return revealFolder(File(path).parent.path);+}diff --git a/desktop/lib/logging/dial_log_tail.dart b/desktop/lib/logging/dial_log_tail.dartnew file mode 100644index 000000000..7fc6b7c27--- /dev/null+++ b/desktop/lib/logging/dial_log_tail.dart@@ -0,0 +1,136 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'app_log.dart';+import 'log_file.dart';+import 'log_stream.dart';++/// Base name of the dial's per-day file under `~/.harness/logs`, written by the+/// CLI daemon (`cli/src/cable/dialLog.ts`), never by this app.+const String kDialLogBase = 'dial';++/// Follows `dial-YYYYMMDD.log` into the in-memory [LogStream], so the dial is+/// a source in Settings ▸ Debug beside the app's own.+///+/// The other sources are *mirrors* — the app writes the file and the ring at+/// once. This one cannot be: the daemon writes the dial's file, and the app+/// only reads it. So it tails: every second it reads whatever bytes were+/// appended since last time, one entry per line, category `dial`. On first+/// start it takes only the last [_catchUpBytes] of today's file, enough for+/// the recent context without replaying a whole day into a 500-entry ring.+///+/// Levels come from the line itself: the firmware's `W (ticks)` / `E (ticks)`+/// prefixes, and a `[daemon]` line is the daemon speaking. The file is the+/// truth; a parse that fails still shows the raw line.+class DialLogTail {+ DialLogTail(+ this.directory,+ this.stream, {+ DateTime Function()? clock,+ this.interval = const Duration(seconds: 1),+ }) : _clock = clock ?? DateTime.now;++ final Directory directory;+ final LogStream stream;+ final Duration interval;+ final DateTime Function() _clock;++ static const int _catchUpBytes = 16 * 1024;++ Timer? _timer;+ String? _day;+ int _offset = 0;+ String _partial = '';+ // Set when the catch-up window opened mid-line: the first "line" read is a+ // fragment and is dropped rather than shown as a half sentence.+ bool _dropFirst = false;++ File get currentFile =>+ File('${directory.path}/${dailyLogName(kDialLogBase, _clock())}');++ void start() {+ _timer ??= Timer.periodic(interval, (_) => unawaited(poll()));+ unawaited(poll());+ }++ void stop() {+ _timer?.cancel();+ _timer = null;+ }++ /// One read of whatever is new. Public so a test can drive it without a+ /// timer; safe to call when nothing changed.+ Future<void> poll() async {+ try {+ final now = _clock();+ final day = dailyLogName(kDialLogBase, now);+ final file = currentFile;+ if (day != _day) {+ // A new day (or the first poll): start from the tail, not the top.+ _day = day;+ _partial = '';+ _offset = 0;+ _dropFirst = false;+ if (await file.exists()) {+ final length = await file.length();+ if (length > _catchUpBytes) {+ _offset = length - _catchUpBytes;+ _dropFirst = true;+ }+ }+ }+ if (!await file.exists()) return;+ final length = await file.length();+ if (length < _offset) _offset = 0; // truncated or replaced — start over+ if (length == _offset) return;+ final handle = await file.open();+ try {+ await handle.setPosition(_offset);+ final bytes = await handle.read(length - _offset);+ _offset = length;+ _ingest(const Utf8Decoder(allowMalformed: true).convert(bytes));+ } finally {+ await handle.close();+ }+ } on Object {+ // A log reader must never become a source of log noise about itself.+ }+ }++ void _ingest(String chunk) {+ final text = _partial + chunk;+ final lines = text.split('\n');+ _partial = lines+ .removeLast(); // '' after a trailing newline, else a fragment+ for (final line in lines) {+ if (_dropFirst) {+ _dropFirst = false;+ continue;+ }+ if (line.isEmpty) continue;+ final parsed = parseDialLine(line);+ stream.add(parsed.level, 'dial', parsed.message);+ }+ }+}++/// One dial log line, minus its wall-clock stamp, with a level read off it.+typedef ParsedDialLine = ({AppLogLevel level, String message});++/// `2026-09-15T03:53:52.001Z W (27793) touch: …` → warn, `W (27793) touch: …`.+/// `2026-09-15T03:56:22.418Z [daemon] following …` → info, `[daemon] following …`.+ParsedDialLine parseDialLine(String line) {+ final space = line.indexOf(' ');+ final message = space > 0 && line[space - 1] == 'Z'+ ? line.substring(space + 1)+ : line;+ final level = message.startsWith('E (')+ ? AppLogLevel.error+ : message.startsWith('W (')+ ? AppLogLevel.warn+ : message.startsWith('D (') || message.startsWith('V (')+ ? AppLogLevel.debug+ : AppLogLevel.info;+ return (level: level, message: message);+}diff --git a/desktop/lib/logging/install.dart b/desktop/lib/logging/install.dartindex 03df5fa28..5bdd96e9e 100644--- a/desktop/lib/logging/install.dart+++ b/desktop/lib/logging/install.dart@@ -1,6 +1,7 @@import 'app_log.dart';import 'cli_log.dart';import 'debug_surface.dart';+import 'dial_log_tail.dart';import 'log_file.dart';import 'log_stream.dart';import 'log_stream_sinks.dart';@@ -32,4 +33,7 @@ void installFileLogs() {// copy is already written.appLog = FanoutAppLog([file, StreamAppLog(logStream)]);cliLog = FanoutCliLog([cli, StreamCliLog(logStream)]);+ // The dial's log is the daemon's to write; this app only reads it. Tailed+ // into the same ring so Settings ▸ Debug has a Dial lens.+ DialLogTail(directory, logStream).start();}diff --git a/desktop/lib/logging/log_export.dart b/desktop/lib/logging/log_export.dartnew file mode 100644index 000000000..d1666dbae--- /dev/null+++ b/desktop/lib/logging/log_export.dart@@ -0,0 +1,55 @@+import 'dart:convert';++import '../core/harness_cli_runner.dart';++/// What `harness logs export --json` answered.+class LogExportResult {+ const LogExportResult({this.path, this.included = const [], this.error});++ /// The zip on disk, or null when the export failed.+ final String? path;+ final List<String> included;+ final String? error;+}++/// Runs `harness logs export --json` through [runner] and reads its one line.+///+/// The CLI owns the bundle (`cli/src/lib/logBundle.ts`): it knows where the+/// daemon's `harness.log` is, it writes the dial's log, and a terminal with no+/// window needs the same export. This app adds nothing to it but a button.+Future<LogExportResult> exportLogs(HarnessCliRunner runner) async {+ try {+ final result = await runner.run(const ['logs', 'export', '--json']);+ final out = (result.stdout as String).trim();+ if (result.exitCode != 0 || out.isEmpty) {+ final err = (result.stderr as String).trim();+ return LogExportResult(+ error: err.isEmpty ? 'harness exited ${result.exitCode}' : err,+ );+ }+ return parseLogExport(out.split('\n').last);+ } on Object catch (e) {+ return LogExportResult(error: '$e');+ }+}++/// `{"path":…,"included":[…],"bytes":…}` → [LogExportResult]. Pure, for tests.+LogExportResult parseLogExport(String line) {+ try {+ final json = jsonDecode(line);+ if (json is! Map<String, dynamic>) {+ return const LogExportResult(error: 'unexpected answer');+ }+ final path = json['path'];+ final included = json['included'];+ return LogExportResult(+ path: path is String ? path : null,+ included: included is List+ ? included.map((e) => '$e').toList()+ : const [],+ error: path is String ? null : 'no path in answer',+ );+ } on FormatException {+ return LogExportResult(error: 'unreadable answer: $line');+ }+}diff --git a/desktop/lib/settings/sections/debug_paths_card.dart b/desktop/lib/settings/sections/debug_paths_card.dartindex 8ceec03b0..b32b508ad 100644--- a/desktop/lib/settings/sections/debug_paths_card.dart+++ b/desktop/lib/settings/sections/debug_paths_card.dart@@ -109,6 +109,11 @@ class _DebugPathsCardState extends State<DebugPathsCard> {'(${environment.harnessSource.name})',),_PathRow(label: 'logs', value: environment.logsDirectory),+ // The daemon's file, not this app's — see logging/dial_log_tail.dart.+ _PathRow(+ label: 'dial',+ value: '${environment.logsDirectory}/dial-YYYYMMDD.log',+ ),],);},diff --git a/desktop/lib/settings/sections/debug_section.dart b/desktop/lib/settings/sections/debug_section.dartindex 411665121..faf679884 100644--- a/desktop/lib/settings/sections/debug_section.dart+++ b/desktop/lib/settings/sections/debug_section.dart@@ -86,9 +86,11 @@ class _DebugSectionState extends State<DebugSection> {return SectionScaffold(title: 'Debug',subtitle:- 'Everything this app logged this session — the same lines '- '${DailyLogFile.defaultDirectory.path} keeps for a fortnight. '- 'Credentials are stripped before anything is written.',+ 'Everything this app logged this session, and the dial\'s own log '+ 'as the daemon writes it — the same lines '+ '${DailyLogFile.defaultDirectory.path} keeps for a fortnight (the '+ 'dial\'s for a week). Credentials are stripped before anything is '+ 'written. Export logs zips the last seven days to the Desktop.',child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [@@ -185,15 +187,17 @@ class _DebugSectionState extends State<DebugSection> {}/// The order the categories read in: the socket the app lives on, then the- /// two CLIs, then its own narrative. Anything new lands after them, in+ /// two CLIs, then the dial (read from the daemon's `dial-*.log`), then its+ /// own narrative. Anything new lands after them, in/// alphabetical order, rather than jumping the queue.static int _categoryRank(String category) => switch (category) {'ws' => 0,'cli' => 1,- 'api' => 2,- 'app' => 3,- 'flutter' => 4,- _ => 5,+ 'dial' => 2,+ 'api' => 3,+ 'app' => 4,+ 'flutter' => 5,+ _ => 6,};Widget _list(bool nothingLogged, List<LogEntry> visible) {diff --git a/desktop/lib/settings/sections/debug_toolbar.dart b/desktop/lib/settings/sections/debug_toolbar.dartindex 9c951c9e6..6f6600117 100644--- a/desktop/lib/settings/sections/debug_toolbar.dart+++ b/desktop/lib/settings/sections/debug_toolbar.dart@@ -3,7 +3,9 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';+import '../../core/harness_cli_runner.dart';import '../../core/reveal_folder.dart';+import '../../logging/log_export.dart';import '../../logging/log_file.dart';import '../../shared/theme/app_theme.dart';import '../../shared/widgets/toolbar_pill.dart';@@ -30,6 +32,8 @@ class DebugToolbar extends StatelessWidget {style: TextStyle(fontSize: 12.5, color: AppPalette.textSecondary),),),+ const _ExportLogsPill(),+ const SizedBox(width: 6),const _OpenLogsPill(),const SizedBox(width: 6),ToolbarPill(@@ -48,6 +52,58 @@ class DebugToolbar extends StatelessWidget {}}+/// Zips the last seven days of every log — this app's, the CLI transcript, the+/// dial's, the daemon's — to the Desktop, secrets blanked, and reveals the file.+///+/// The one thing a bug report needs and the thing nobody could produce before+/// without being walked through a hidden directory. It runs `harness logs+/// export` rather than zipping here, so the bundle is the same whether it was+/// made from this button or from a terminal — see `logging/log_export.dart`.+class _ExportLogsPill extends StatefulWidget {+ const _ExportLogsPill();++ @override+ State<_ExportLogsPill> createState() => _ExportLogsPillState();+}++class _ExportLogsPillState extends State<_ExportLogsPill> {+ bool _busy = false;++ Future<void> _export() async {+ if (_busy) return;+ setState(() => _busy = true);+ final messenger = ScaffoldMessenger.of(context);+ try {+ final result = await exportLogs(HarnessCliRunner());+ if (result.path != null) {+ await revealFile(result.path!);+ messenger.showSnackBar(+ SnackBar(content: Text('Logs exported to ${result.path}')),+ );+ } else {+ messenger.showSnackBar(+ SnackBar(content: Text('Could not export logs: ${result.error}')),+ );+ }+ } finally {+ if (mounted) setState(() => _busy = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ return ToolbarPill(+ onTap: _busy ? null : () => unawaited(_export()),+ rimmed: true,+ child: DebugPillLabel(+ icon: LucideIcons.packageOpen,+ label: _busy ? 'Exporting…' : 'Export logs',+ enabled: !_busy,+ ),+ );+ }+}+/// Opens `~/.harness/logs` in the file manager.////// The list is this session's, held in memory — the files on disk are whatdiff --git a/desktop/test/dial_log_tail_test.dart b/desktop/test/dial_log_tail_test.dartnew file mode 100644index 000000000..f9906d4ee--- /dev/null+++ b/desktop/test/dial_log_tail_test.dart@@ -0,0 +1,94 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/logging/app_log.dart';+import 'package:harness/logging/dial_log_tail.dart';+import 'package:harness/logging/log_export.dart';+import 'package:harness/logging/log_file.dart';+import 'package:harness/logging/log_stream.dart';++void main() {+ test('parseDialLine strips the stamp and reads the level', () {+ final w = parseDialLine('2026-09-15T03:53:52.001Z W (27793) touch: dead');+ expect(w.level, AppLogLevel.warn);+ expect(w.message, 'W (27793) touch: dead');+ final d = parseDialLine('2026-09-15T03:56:22.418Z [daemon] open on /dev/x');+ expect(d.level, AppLogLevel.info);+ expect(d.message, '[daemon] open on /dev/x');+ expect(parseDialLine('no stamp E (1) x').level, AppLogLevel.info);+ expect(parseDialLine('E (1) x').level, AppLogLevel.error);+ });++ test('tails the day file into the stream, only what is new', () async {+ final dir = Directory.systemTemp.createTempSync('dial-tail-');+ addTearDown(() => dir.deleteSync(recursive: true));+ final now = DateTime(2026, 9, 15, 10);+ final file = File('${dir.path}/${dailyLogName(kDialLogBase, now)}');+ file.writeAsStringSync('2026-09-15T03:00:00.000Z I (1) ui: face: agent\n');+ final stream = LogStream();+ final tail = DialLogTail(dir, stream, clock: () => now);+ await tail.poll();+ expect(stream.entries.map((e) => e.message), ['I (1) ui: face: agent']);+ // A partial line waits for its newline.+ file.writeAsStringSync(+ '2026-09-15T03:00:01.000Z W (2) touch: pre',+ mode: FileMode.append,+ );+ await tail.poll();+ expect(stream.entries.length, 1);+ file.writeAsStringSync(+ 'ss (1,2)\n2026-09-15T03:00:02.000Z [daemon] agents → 3\n',+ mode: FileMode.append,+ );+ await tail.poll();+ expect(stream.entries.map((e) => e.message).toList(), [+ '[daemon] agents → 3',+ 'W (2) touch: press (1,2)',+ 'I (1) ui: face: agent',+ ]);+ expect(stream.entries.every((e) => e.category == 'dial'), isTrue);+ expect(stream.entries[1].level, AppLogLevel.warn);+ // Nothing new: nothing added.+ await tail.poll();+ expect(stream.entries.length, 3);+ });++ test(+ 'a big file is joined at its tail, dropping the opening fragment',+ () async {+ final dir = Directory.systemTemp.createTempSync('dial-tail-');+ addTearDown(() => dir.deleteSync(recursive: true));+ final now = DateTime(2026, 9, 15, 10);+ final file = File('${dir.path}/${dailyLogName(kDialLogBase, now)}');+ final sb = StringBuffer();+ for (var i = 0; i < 2000; i++) {+ sb.writeln(+ '2026-09-15T03:00:00.000Z I ($i) ui: line number $i padding padding',+ );+ }+ file.writeAsStringSync(sb.toString());+ final stream = LogStream();+ await DialLogTail(dir, stream, clock: () => now).poll();+ expect(stream.entries.length, lessThan(2000));+ expect(+ stream.entries.first.message,+ 'I (1999) ui: line number 1999 padding padding',+ );+ // Every entry is a whole line — no fragment from the window's opening.+ for (final e in stream.entries) {+ expect(e.message, startsWith('I ('));+ }+ },+ );++ test('parseLogExport reads the CLI answer', () {+ final ok = parseLogExport(+ '{"path":"/x/harness-logs.zip","included":["a"],"bytes":1}',+ );+ expect(ok.path, '/x/harness-logs.zip');+ expect(ok.included, ['a']);+ expect(ok.error, isNull);+ expect(parseLogExport('nope').error, contains('unreadable'));+ expect(parseLogExport('{"bytes":1}').error, 'no path in answer');+ });+}diff --git a/device/esp32-circle/main/CMakeLists.txt b/device/esp32-circle/main/CMakeLists.txtindex d50b8187d..975fed5d1 100644--- a/device/esp32-circle/main/CMakeLists.txt+++ b/device/esp32-circle/main/CMakeLists.txt@@ -8,6 +8,7 @@ idf_component_register("device_mac.c""cable_frame.c""cable_link.c"+ "last_words.c""cable_client.c""cable_machines.c""fw_update.c"diff --git a/device/esp32-circle/main/app_main.c b/device/esp32-circle/main/app_main.cindex f32770263..4e1f4eb70 100644--- a/device/esp32-circle/main/app_main.c+++ b/device/esp32-circle/main/app_main.c@@ -22,6 +22,7 @@#include "cable_client.h"#include "config_store.h"#include "fw_update.h"+#include "last_words.h"#include "driver/gpio.h"#include "esp_heap_caps.h"#include "esp_log.h"@@ -173,6 +174,7 @@ static void refresh_task(void *arg)void app_main(void){ram_telemetry_checkpoint("boot");+ last_words_boot(); // before the first log line, so the previous boot's ring is read, not overwrittenconfig_store_init();if (boot_button_held()) {diff --git a/device/esp32-circle/main/audio_client.c b/device/esp32-circle/main/audio_client.cindex f2707afdf..709347ab8 100644--- a/device/esp32-circle/main/audio_client.c+++ b/device/esp32-circle/main/audio_client.c@@ -233,19 +233,36 @@ void audio_client_start_cable(const char *agent_id, voice_cmd_t cmd)void audio_client_stop(void){- if (s_active) s_stop_req = true;+ if (!s_active) return;+ if (!s_stop_req) ESP_LOGI(TAG, "voice stop requested");+ s_stop_req = true;}void audio_client_abort(void){if (!s_active) return;+ if (!s_abort_req) ESP_LOGI(TAG, "voice abort requested");s_abort_req = true;s_stop_req = true;}+// While a turn is active, touch.c forwards NOTHING to LVGL — a swipe does not switch tiles and the Voice+// button does nothing, while the tile keeps following the app. That is the stuck-dial report to the+// letter, so a turn that never ends is worth a loud line: once past ten minutes, and again every ten.+#define VOICE_LONG_MS (10 * 60 * 1000)+bool audio_client_active(void){- return s_active;+ static int64_t since_us, warned_us;+ if (!s_active) { since_us = 0; return false; }+ int64_t now = esp_timer_get_time();+ if (!since_us) { since_us = now; warned_us = now; }+ if (now - warned_us >= (int64_t)VOICE_LONG_MS * 1000) {+ warned_us = now;+ ESP_LOGW(TAG, "voice turn active for %llu min (recording=%d stop_req=%d abort_req=%d) — touch is held off LVGL",+ (unsigned long long)((now - since_us) / 60000000), s_recording, s_stop_req, s_abort_req);+ }+ return true;}bool audio_client_upload_matches(const char *upload_id)diff --git a/device/esp32-circle/main/cable_client.c b/device/esp32-circle/main/cable_client.cindex 556491899..c6e0b27f2 100644--- a/device/esp32-circle/main/cable_client.c+++ b/device/esp32-circle/main/cable_client.c@@ -12,6 +12,7 @@#include "audio_capture.h" // audio_notify_done() — the completion beep#include "esp_timer.h"#include "fw_update.h"+#include "last_words.h"#include "freertos/FreeRTOS.h"#include "freertos/semphr.h"#include "freertos/task.h"@@ -437,6 +438,9 @@ static void session_up(const cJSON *p)// dial would sit on an empty carousel opposite a daemon convinced it had already spoken.send_json(msg("machines.list"));send_json(msg("agents.list"));+ // Now that someone is listening: why this boot happened, and what was said before it if the+ // answer is a crash. Framed like every other line, so it lands in the same file.+ last_words_report();}}diff --git a/device/esp32-circle/main/cable_link.c b/device/esp32-circle/main/cable_link.cindex 622b34474..f771bf702 100644--- a/device/esp32-circle/main/cable_link.c+++ b/device/esp32-circle/main/cable_link.c@@ -6,6 +6,7 @@#include "driver/usb_serial_jtag.h"#include "esp_log.h"+#include "last_words.h"#include "freertos/FreeRTOS.h"#include "freertos/semphr.h"#include "freertos/task.h"@@ -127,6 +128,8 @@ static int log_vprintf(const char *fmt, va_list args)size_t len = (size_t)n < sizeof(line) - 1 ? (size_t)n : sizeof(line) - 1;// Trailing newline is the console's business, not the protocol's: the frame IS the line.while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) len--;+ // Into the RTC ring first — that copy survives the reboot the next line may be the last before.+ if (len > 0) last_words_add(line, len);if (len > 0) send_locked(CABLE_TYPE_LOG, (const uint8_t *)line, len, pdMS_TO_TICKS(LOG_WRITE_WAIT_MS));}s_in_log_sink = false;diff --git a/device/esp32-circle/main/last_words.c b/device/esp32-circle/main/last_words.cnew file mode 100644index 000000000..c45d6fe08--- /dev/null+++ b/device/esp32-circle/main/last_words.c@@ -0,0 +1,117 @@+#include "last_words.h"++#include <string.h>++#include "esp_attr.h"+#include "esp_log.h"+#include "esp_system.h"+#include "freertos/FreeRTOS.h"++static const char *TAG = "boot";++#define RING_BYTES 4096+#define RING_MAGIC 0x4C575244u // "LWRD"++// RTC_NOINIT: not touched by the bootloader or the startup code, so it holds across a panic, a watchdog+// reset or esp_restart(). A power cut clears it, and that is fine — a power cut is not a bug this can+// name. The magic and a checksum of the header guard against reading garbage on a cold boot.+typedef struct {+ uint32_t magic;+ uint32_t head; // next write position+ uint32_t len; // bytes in use (≤ RING_BYTES)+ uint32_t check; // ~(head ^ len)+ char buf[RING_BYTES];+} ring_t;++static RTC_NOINIT_ATTR ring_t s_ring;+static portMUX_TYPE s_mux = portMUX_INITIALIZER_UNLOCKED;++static esp_reset_reason_t s_reason;+static bool s_abnormal;+// The previous boot's lines, copied out before this boot starts overwriting the ring. Static rather than+// heap: 4 KB of BSS is cheaper than a failed allocation at the one moment it would matter.+static char s_previous[RING_BYTES + 1];+static size_t s_previous_len;+static bool s_reported;++static bool ring_valid(void)+{+ return s_ring.magic == RING_MAGIC && s_ring.len <= RING_BYTES && s_ring.head < RING_BYTES+ && s_ring.check == ~(s_ring.head ^ s_ring.len);+}++static void ring_seal(void) { s_ring.check = ~(s_ring.head ^ s_ring.len); }++static const char *reason_name(esp_reset_reason_t r)+{+ switch (r) {+ case ESP_RST_POWERON: return "power-on";+ case ESP_RST_EXT: return "external pin";+ case ESP_RST_SW: return "software (esp_restart)";+ case ESP_RST_PANIC: return "PANIC";+ case ESP_RST_INT_WDT: return "INTERRUPT WATCHDOG";+ case ESP_RST_TASK_WDT: return "TASK WATCHDOG";+ case ESP_RST_WDT: return "WATCHDOG";+ case ESP_RST_DEEPSLEEP: return "deep sleep";+ case ESP_RST_BROWNOUT: return "BROWNOUT";+ case ESP_RST_SDIO: return "sdio";+ case ESP_RST_USB: return "usb";+ case ESP_RST_JTAG: return "jtag";+ default: return "unknown";+ }+}++void last_words_boot(void)+{+ s_reason = esp_reset_reason();+ s_abnormal = s_reason == ESP_RST_PANIC || s_reason == ESP_RST_INT_WDT || s_reason == ESP_RST_TASK_WDT+ || s_reason == ESP_RST_WDT || s_reason == ESP_RST_BROWNOUT || s_reason == ESP_RST_UNKNOWN;+ if (s_abnormal && ring_valid() && s_ring.len) {+ // Unroll the ring into reading order: oldest byte first.+ uint32_t start = (s_ring.head + RING_BYTES - s_ring.len) % RING_BYTES;+ for (uint32_t i = 0; i < s_ring.len; i++) s_previous[i] = s_ring.buf[(start + i) % RING_BYTES];+ s_previous_len = s_ring.len;+ s_previous[s_previous_len] = '\0';+ }+ s_ring.magic = RING_MAGIC;+ s_ring.head = 0;+ s_ring.len = 0;+ ring_seal();+}++void last_words_add(const char *line, size_t len)+{+ if (!len) return;+ portENTER_CRITICAL(&s_mux);+ if (!ring_valid()) { s_ring.magic = RING_MAGIC; s_ring.head = 0; s_ring.len = 0; }+ for (size_t i = 0; i < len; i++) {+ s_ring.buf[s_ring.head] = line[i];+ s_ring.head = (s_ring.head + 1) % RING_BYTES;+ }+ s_ring.buf[s_ring.head] = '\n';+ s_ring.head = (s_ring.head + 1) % RING_BYTES;+ s_ring.len += len + 1;+ if (s_ring.len > RING_BYTES) s_ring.len = RING_BYTES;+ ring_seal();+ portEXIT_CRITICAL(&s_mux);+}++void last_words_report(void)+{+ if (s_reported) return;+ s_reported = true;+ if (s_abnormal) ESP_LOGW(TAG, "reset reason: %s", reason_name(s_reason));+ else ESP_LOGI(TAG, "reset reason: %s", reason_name(s_reason));+ if (!s_previous_len) return;+ ESP_LOGW(TAG, "last %u bytes of log before that reset follow", (unsigned)s_previous_len);+ // The first line is very likely a fragment (the ring wrapped through it); everything after is whole.+ char *p = s_previous;+ while (p && *p) {+ char *nl = strchr(p, '\n');+ if (nl) *nl = '\0';+ if (*p) ESP_LOGW(TAG, "last: %s", p);+ p = nl ? nl + 1 : NULL;+ }+ ESP_LOGW(TAG, "end of last words");+ s_previous_len = 0;+}diff --git a/device/esp32-circle/main/last_words.h b/device/esp32-circle/main/last_words.hnew file mode 100644index 000000000..34dfee296--- /dev/null+++ b/device/esp32-circle/main/last_words.h@@ -0,0 +1,21 @@+// The last log lines before a reset, and the reason for it.+//+// A dial that panics, trips a watchdog or browns out reboots in under a second and greets the daemon as+// if nothing happened — from the desk it looks like an unplug. This keeps a small ring of the most recent+// log lines in RTC memory that survives a soft reset, and on the next boot, if the reset was not a clean+// one, replays them over the cable once a daemon is listening.+#pragma once++#include <stdbool.h>+#include <stddef.h>++// At boot, before anything logs: read the reset reason, keep the previous boot's ring if the reset was+// abnormal, then arm the ring for this boot.+void last_words_boot(void);++// Append one formatted log line. Called from the log sink; cheap, spinlocked, never blocks.+void last_words_add(const char *line, size_t len);++// Once a daemon is listening (session up): log the reset reason, and the previous boot's last lines if+// that reset was a crash. Logs once per boot.+void last_words_report(void);diff --git a/device/esp32-circle/main/ui/display.c b/device/esp32-circle/main/ui/display.cindex 569d8213d..0fa91c43d 100644--- a/device/esp32-circle/main/ui/display.c+++ b/device/esp32-circle/main/ui/display.c@@ -1,6 +1,7 @@#include "display.h"#include <stdlib.h>#include "touch.h"+#include "ui_screens.h"#include "board_pins.h"#include "ram_telemetry.h"#include "freertos/FreeRTOS.h"@@ -13,6 +14,7 @@#include "esp_heap_caps.h"#include "esp_timer.h"#include "esp_log.h"+#include "esp_task_wdt.h"#include "lvgl.h"// CO5300 power-on / init register sequence, taken verbatim from Waveshare's@@ -78,11 +80,45 @@ static void lvgl_flush(lv_display_t *disp, const lv_area_t *area, uint8_t *px)// LVGL needs a millisecond tick.static void tick_cb(void *arg) { lv_tick_inc(2); }+// ── liveness ────────────────────────────────────────────────────────────────────────────────────────+// One line a minute from THIS task. Its presence says the UI task is turning; its absence, while the+// cable's own lines carry on, is the one signature of a wedged LVGL task there is — the daemon marks the+// gap in the dial's log on its side. The figures beside it are the ones a stuck report asks for first:+// heap, LVGL's pool, and whether touch is alive.+#define HEARTBEAT_MS 60000++static void heartbeat(void)+{+ static uint32_t last;+ if (last && lv_tick_elaps(last) < HEARTBEAT_MS) return;+ last = lv_tick_get();+ touch_stats_t t;+ touch_stats(&t);+ lv_mem_monitor_t m;+ lv_mem_monitor(&m);+ ESP_LOGI(TAG, "alive up=%lus heap=%u/%u psram=%u lv=%u%%used frag=%u%% touches=%lu last_press=%lus%s%s%s",+ (unsigned long)(lv_tick_get() / 1000),+ (unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL),+ (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL),+ (unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM),+ (unsigned)m.used_pct, (unsigned)m.frag_pct,+ (unsigned long)t.presses, (unsigned long)(t.last_press_ms_ago / 1000),+ t.controller_ok ? "" : " TOUCH-DEAD",+ t.read_failures ? " read-fails" : "",+ t.held_now ? " PRESS-HELD" : "");+}+static void lvgl_task(void *arg){+ // Under the task watchdog: a UI task that stops turning used to be a frozen glass with nothing to+ // read; now it is a reboot whose reason and last log lines come back over the cable (last_words.c).+ esp_task_wdt_add(NULL);while (1) {+ esp_task_wdt_reset();display_lock();uint32_t next = lv_timer_handler();+ heartbeat();+ ui_log_state_if_changed();// Idle → turn the panel off to save battery. LVGL resets the inactivity timer on every real// touch (indev read), so this fires only after IDLE_MS with no touch. Fires REGARDLESS of charging// (user wants it to off even while plugged in); plugging in still wakes once (ui_screens tick) and@@ -234,7 +270,31 @@ void display_init(void) { display_init_impl(DRAW_LINES, true); }// WiFi RX buffers) and no touch — just enough to render the OTA progress screen.void display_init_ota(void) { display_init_impl(DRAW_LINES / 4 > 0 ? DRAW_LINES / 4 : 1, false); }-void display_lock(void) { xSemaphoreTakeRecursive(s_lvgl_mutex, portMAX_DELAY); }+// The LVGL lock, with a voice. Every task that draws takes it; the LVGL task takes it every 20ms. A wait+// past LOCK_WARN_MS is not a busy frame — it is a task that took the lock and blocked inside it (a cable+// write that never drains, an I2C reset with its delays), and the line below is the last thing written+// before the screen stops. It names the waiter AND the holder, which is what turns "the dial froze" into+// a pair of function names.+#define LOCK_WARN_MS 2000+#define LOCK_WARN_EVERY_MS 10000+static const char *volatile s_lock_holder = "-";+static const char *volatile s_lock_holder_task = "-";++void display_lock_at(const char *who)+{+ if (xSemaphoreTakeRecursive(s_lvgl_mutex, pdMS_TO_TICKS(LOCK_WARN_MS)) == pdTRUE) goto held;+ uint32_t waited = LOCK_WARN_MS;+ for (;;) {+ ESP_LOGW(TAG, "display_lock: %s (task %s) waiting %lus — held by %s (task %s)", who,+ pcTaskGetName(NULL), (unsigned long)(waited / 1000), s_lock_holder, s_lock_holder_task);+ if (xSemaphoreTakeRecursive(s_lvgl_mutex, pdMS_TO_TICKS(LOCK_WARN_EVERY_MS)) == pdTRUE) break;+ waited += LOCK_WARN_EVERY_MS;+ }+ ESP_LOGW(TAG, "display_lock: %s got it after %lus", who, (unsigned long)(waited / 1000));+held:+ s_lock_holder = who;+ s_lock_holder_task = pcTaskGetName(NULL);+}void display_unlock(void) { xSemaphoreGiveRecursive(s_lvgl_mutex); }bool display_is_asleep(void) { return s_asleep; }diff --git a/device/esp32-circle/main/ui/display.h b/device/esp32-circle/main/ui/display.hindex 58905168a..983a2914d 100644--- a/device/esp32-circle/main/ui/display.h+++ b/device/esp32-circle/main/ui/display.h@@ -16,7 +16,10 @@ void display_set_brightness(uint8_t level);// Lock/unlock the LVGL mutex. ANY code that touches LVGL objects from outside// the LVGL task (e.g. the WiFi/WS tasks via ui_screens.c) must hold this.-void display_lock(void);+// `display_lock()` carries the caller's name so a wait past 2s can be logged with who is waiting and+// who is holding — see display_lock_at. The macro keeps every call site as it was.+void display_lock_at(const char *who);+#define display_lock() display_lock_at(__func__)void display_unlock(void);// Idle battery-save: turn the AMOLED panel off / back on. `display_wake()` repaints the currentdiff --git a/device/esp32-circle/main/ui/touch.c b/device/esp32-circle/main/ui/touch.cindex 4579d4413..4bba478d7 100644--- a/device/esp32-circle/main/ui/touch.c+++ b/device/esp32-circle/main/ui/touch.c@@ -14,6 +14,32 @@static const char *TAG = "touch";static esp_lcd_touch_handle_t s_tp;+static esp_lcd_panel_io_handle_t s_tp_io; // kept so a dead controller can be torn down and brought back++// ── what the log is for ─────────────────────────────────────────────────────────────────────────────+// The dial has been seen to stop taking touch — no swipe, Voice dead, the tile still following the app —+// with nothing to read afterwards. Everything below that prints is there so the NEXT such report has a+// signature: was data arriving from the controller at all, was a press being held by one of the gesture+// flags, did the finger ever lift. One line per press, one per release, one per verdict; never per+// sample. Kept at INFO on purpose — a shipped build has to carry them, because the report comes from a+// shipped build.++// Read failures from the CST9217. The driver resets the chip itself on an I2C error; what it does NOT do+// on a bad ACK is clear its last point, so a controller that stops answering mid-press leaves LVGL — and+// every recognizer in this file — holding a finger that is no longer there. Which is the reported shape.+static uint32_t s_read_fail_total;+static uint32_t s_read_fail_run; // consecutive; reset by any good read+#define READ_FAIL_REINIT 50 // ~1s of nothing but errors → tear the controller down and bring it back+#define READ_FAIL_LOG_EVERY 100+#define REINIT_RETRY_MS 5000 // a reinit that failed is tried again this often++static uint32_t s_presses; // lifetime, for the heartbeat+static uint32_t s_last_press_tick; // lv tick of the last press-down+static uint32_t s_press_t0; // lv tick of the current press-down+static uint16_t s_last_x, s_last_y; // last PRESSED point, so the release line has a place+static bool s_stuck_warned; // the ">held 5s" line for this press already went out+#define STUCK_PRESS_MS 5000+#define STUCK_PRESS_EVERY_MS 30000// How far a finger may drift and still count as "held still". Shared by the near-still TAP test and the// GOAL hold — it outlived the create-project long-press that introduced it.@@ -94,6 +120,10 @@ static bool s_goal_swallow;// (otherwise swipe_track starts mid-gesture on the read after wake and classifies the release as a tap →// stray "open detail" on the very tap that woke the screen).static bool s_swallow_until_release;+// The other two owners of a press, file-scope so the stuck-press line can name them: the Overview's round+// buttons (action_capture) and the notification band (s_band_drag). Set and cleared in touch_read only.+static bool s_action_capture;+static bool s_band_drag;static int s_scroll_acc; // travel not yet reported, device px (positive = down the glass)static uint32_t s_scroll_at; // when the last report went out@@ -221,10 +251,13 @@ static void swipe_track(bool pressed, uint16_t x, uint16_t y)int home_edge = reader ? READER_HOME_EDGE_PX : BOTTOM_EDGE_PX;// HOME gesture: an upward swipe that STARTED at the bottom edge → jump to Overview. (y grows downward;// the driver already applies the panel mirror, so sy near y_max = the physical bottom.)- if (!voice && sy >= home_edge && dy < -SWIPE_MIN_PX && abs(dy) > abs(dx))+ if (!voice && sy >= home_edge && dy < -SWIPE_MIN_PX && abs(dy) > abs(dx)) {+ ESP_LOGI(TAG, "gesture: home (dy=%d)", dy);ui_home_overview();- else if (!voice && (dx > SWIPE_MIN_PX || dx < -SWIPE_MIN_PX) && abs(dx) > abs(dy))+ } else if (!voice && (dx > SWIPE_MIN_PX || dx < -SWIPE_MIN_PX) && abs(dx) > abs(dy)) {+ ESP_LOGI(TAG, "gesture: swipe %+d (dx=%d dy=%d)", dx > 0 ? 1 : -1, dx, dy);ui_swipe_end(dx > 0 ? 1 : -1); // reader → back to the agent; carousel screens → wrap next/prev+ }// A vertical drag is NOT classified here any more — it went out as it happened (above). One// gesture cannot mean two things: while it also opened the detail reader, every scroll ended by// opening a screen nobody asked for. Tapping the recap card opens it, which is the route it kept.@@ -239,40 +272,118 @@ static void swipe_track(bool pressed, uint16_t x, uint16_t y)// because its indicator state is set asynchronously, a few frames later; the cabled path sets// it inline and exposed it. Compare start times: a turn that began at or after this press is// this press's own doing and must not be stopped by its release.- if (rec_at_down && (int32_t)(ui_voice_start_tick() - t0) < 0) ui_voice_stop();- else if (!reader) { s_tap_pending = true; s_tap_pending_ms = t0; s_tap_x = sx; s_tap_y = sy; }+ if (rec_at_down && (int32_t)(ui_voice_start_tick() - t0) < 0) {+ ESP_LOGI(TAG, "gesture: tap (%d,%d) → stop voice", sx, sy);+ ui_voice_stop();+ } else if (!reader) {+ ESP_LOGI(TAG, "gesture: tap (%d,%d) held=%ums%s", sx, sy, (unsigned)lv_tick_elaps(t0),+ voice ? " (voice active — not a UI tap)" : "");+ s_tap_pending = true; s_tap_pending_ms = t0; s_tap_x = sx; s_tap_y = sy;+ }+ } else {+ // Nothing matched. Worth a line precisely because it is the "I swiped and nothing happened"+ // case: it says whether the stroke was too short, too slow, or refused because voice held it.+ ESP_LOGI(TAG, "gesture: none (dx=%d dy=%d held=%ums voice=%d reader=%d)", dx, dy,+ (unsigned)lv_tick_elaps(t0), voice, reader);}- // (a swipe while recording matches none of the above → ignored; only a still tap stops the voice)}prev = pressed;}// LVGL reads the latest touch point. Marshalled by LVGL's own task; reading the// CST9217 over I2C from here is fine (LVGL task holds no conflicting lock).+static bool touch_open(void);+static void touch_reinit(void);+static void touch_read(lv_indev_t *indev, lv_indev_data_t *data){static bool activity_prev;+ static uint32_t reinit_at;(void)indev;- if (!s_tp) { data->state = LV_INDEV_STATE_RELEASED; return; }+ if (!s_tp) {+ // The controller is gone (init or a reinit failed). Keep trying — a touch panel that comes back+ // after a brown moment is worth more than one written off at boot.+ if (lv_tick_elaps(reinit_at) >= REINIT_RETRY_MS) { reinit_at = lv_tick_get(); touch_reinit(); }+ data->state = LV_INDEV_STATE_RELEASED;+ return;+ }uint16_t x = 0, y = 0, strength = 0;uint8_t cnt = 0;- esp_lcd_touch_read_data(s_tp);- bool pressed = esp_lcd_touch_get_coordinates(s_tp, &x, &y, &strength, &cnt, 1) && cnt > 0;- if (pressed && !activity_prev) s_activity_gen++;+ esp_err_t rc = esp_lcd_touch_read_data(s_tp);+ bool pressed;+ static uint32_t ok_reads, stale_reads; // per press, for the release line — see below+ if (rc == ESP_OK) {+ s_read_fail_run = 0;+ pressed = esp_lcd_touch_get_coordinates(s_tp, &x, &y, &strength, &cnt, 1) && cnt > 0;+ if (pressed) ok_reads++;+ } else if (rc == ESP_ERR_INVALID_RESPONSE) {+ // The chip's report has no ACK byte — measured on the desk, this is what EVERY idle read returns+ // (~30/s with no finger near the glass), so it is not an error and never a reason to reinit. The+ // driver leaves its point table untouched on this path, which is the part that matters: what+ // LVGL sees is the LAST ACKED frame. Kept as such here, for now, and counted per press so the+ // release line says how many stale reads a held finger produces — that number decides whether+ // "no ACK" can be read as "no finger" (the fix for a release frame the chip showed once and this+ // task missed, which leaves the glass held forever).+ pressed = esp_lcd_touch_get_coordinates(s_tp, &x, &y, &strength, &cnt, 1) && cnt > 0;+ if (pressed) stale_reads++;+ } else {+ // A real I2C failure. The driver has already reset the chip (with 60ms of delays, on this task).+ // No answer is no finger: the point table is whatever it was, and trusting it is how a finger+ // that lifted during the fault is held forever.+ pressed = false;+ s_read_fail_total++;+ s_read_fail_run++;+ if (s_read_fail_run == 1 || s_read_fail_total % READ_FAIL_LOG_EVERY == 0)+ ESP_LOGW(TAG, "cst9217 read failed: %s (run=%u total=%u)", esp_err_to_name(rc),+ (unsigned)s_read_fail_run, (unsigned)s_read_fail_total);+ if (s_read_fail_run >= READ_FAIL_REINIT) {+ ESP_LOGW(TAG, "cst9217 dead after %u failed reads — reinit", (unsigned)s_read_fail_run);+ s_read_fail_run = 0;+ reinit_at = lv_tick_get();+ touch_reinit();+ }+ }+ if (pressed && !activity_prev) {+ s_activity_gen++;+ s_presses++;+ s_press_t0 = s_last_press_tick = lv_tick_get();+ s_stuck_warned = false;+ ESP_LOGI(TAG, "press (%u,%u)%s", x, y, display_is_asleep() ? " asleep" : "");+ }+ if (pressed) { s_last_x = x; s_last_y = y; }+ if (!pressed && activity_prev) {+ ESP_LOGI(TAG, "release (%u,%u) held=%ums acked=%lu stale=%lu", s_last_x, s_last_y,+ (unsigned)lv_tick_elaps(s_press_t0), (unsigned long)ok_reads, (unsigned long)stale_reads);+ ok_reads = stale_reads = 0;+ }+ // A press that never ends. Either the controller is repeating a stale point, or one of the flags+ // below has taken the finger and the release it is waiting for is not coming. The line names every+ // owner at once, so the report says which.+ if (pressed && lv_tick_elaps(s_press_t0) >= STUCK_PRESS_MS) {+ static uint32_t warned_at;+ if (!s_stuck_warned || lv_tick_elaps(warned_at) >= STUCK_PRESS_EVERY_MS) {+ s_stuck_warned = true;+ warned_at = lv_tick_get();+ ESP_LOGW(TAG, "press held %us at (%u,%u): swallow=%d goal=%d action=%d band=%d voice=%d asleep=%d switch=%d notif=%d",+ (unsigned)(lv_tick_elaps(s_press_t0) / 1000), x, y,+ s_swallow_until_release, s_goal_swallow, s_action_capture, s_band_drag,+ ui_voice_is_active(), display_is_asleep(), ui_switch_is_open(), ui_notif_is_open());+ }+ }activity_prev = pressed;// A touch that STARTS on one of Overview's two round voice actions belongs to that LVGL button until// release. Feed `false` to the screen-wide recognizers for the whole gesture, but keep the real pointer// state for LVGL below. This prevents Voice-button holds/double-taps from also firing the hidden global// Goal/Voice gestures. A drag can still leave the button and scroll the carousel through LVGL normally.- static bool action_prev, action_capture;+ static bool action_prev;if (pressed && !action_prev) {- action_capture = ui_action_hit(x, y);- if (action_capture) s_tap_pending = false;+ s_action_capture = ui_action_hit(x, y);+ if (s_action_capture) { s_tap_pending = false; ESP_LOGI(TAG, "press on a round action — LVGL's until release"); }}- bool action_touch = action_capture && (pressed || action_prev);+ bool action_touch = s_action_capture && (pressed || action_prev);bool gesture_pressed = pressed && !action_touch;- if (!pressed && action_prev) action_capture = false;+ if (!pressed && action_prev) s_action_capture = false;action_prev = pressed;bool dbl = double_tap(gesture_pressed, x, y); // call every read to keep edge tracking valid@@ -285,7 +396,7 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)// feed LVGL only if the drawer is open (so the list scrolls + rows/background tap); otherwise swallow// (a top-zone pull must not drive the projects UI underneath). On release, decide open/close.{- static bool ndrag, nprev; static int ndy0, ndyl;+ static bool nprev; static int ndy0, ndyl;bool ncap = false;if (pressed && !nprev) {// Not on the reader: notifications aren't openable there, and swallowing the top band would break@@ -297,14 +408,18 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)// top of the face, inside a 90px band this would otherwise swallow whole, so the one control// that leaves the screen could never be pressed. A modal chooser also has no business// offering a pull-to-notifications on top of itself.- ndrag = !display_is_asleep() && !ui_reader_is_open() && !ui_switch_is_open() &&+ s_band_drag = !display_is_asleep() && !ui_reader_is_open() && !ui_switch_is_open() &&!ui_picker_is_open() && !ui_notif_pill_hit(x, y) &&(ui_notif_is_open() || y < ui_notif_pull_zone_px());- ndy0 = ndyl = y; ncap = ndrag;- } else if (pressed && ndrag) {+ ndy0 = ndyl = y; ncap = s_band_drag;+ if (s_band_drag) ESP_LOGI(TAG, "band: captured at y=%u (drawer %s)", y, ui_notif_is_open() ? "open" : "closed");+ } else if (pressed && s_band_drag) {ndyl = y; ncap = true;- } else if (!pressed && nprev && ndrag) { // release of a captured gesture+ } else if (!pressed && nprev && s_band_drag) { // release of a captured gestureint d = ndyl - ndy0;+ ESP_LOGI(TAG, "band: released d=%+d → %s", d,+ ui_notif_is_open() ? (d < -SWIPE_MIN_PX ? "close drawer" : "nothing")+ : (d > SWIPE_MIN_PX ? "agent list" : "nothing"));if (ui_notif_is_open()) { if (d < -SWIPE_MIN_PX) ui_notif_swipe_up(); } // up → close (only if list at top)// Pull down from the top → the AGENT LIST (owner, 2026-09-15: "vuốt xuống hiển thị danh// sách agent như cũ"). The notifications are the bell's alone now: the bell is a button,@@ -312,7 +427,7 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)// the capture test above — so a tap on the bell opens the drawer and a tap anywhere else// in the band does nothing.else if (d > SWIPE_MIN_PX) ui_switch_open();- ndrag = false; ncap = true;+ s_band_drag = false; ncap = true;}nprev = pressed;if (ncap) {@@ -341,6 +456,7 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)if (!gmoved && !display_is_asleep() && !ui_voice_is_active() && lv_tick_elaps(gt0) >= GOAL_HOLD_MS) {gfired = true;s_goal_swallow = true; // swallow until the finger lifts (no stray UI tap)+ ESP_LOGI(TAG, "goal hold at (%u,%u) → voice goal, swallowing until release", x, y);ui_voice_start_goal();}}@@ -352,13 +468,17 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)if (dbl) s_tap_pending = false;else if (s_tap_pending && lv_tick_elaps(s_tap_pending_ms) >= DOUBLE_TAP_MS) {s_tap_pending = false;- if (!display_is_asleep() && !ui_voice_is_active()) ui_tap(s_tap_x, s_tap_y);+ if (!display_is_asleep() && !ui_voice_is_active()) {+ ESP_LOGI(TAG, "tap → ui (%d,%d)", s_tap_x, s_tap_y);+ ui_tap(s_tap_x, s_tap_y);+ } else ESP_LOGI(TAG, "tap dropped (asleep=%d voice=%d)", display_is_asleep(), ui_voice_is_active());}// After a double-tap starts voice, the finger is usually STILL down. Keep swallowing until it lifts,// so the two taps don't also land as UI presses (a stray tile/settings click).if (s_swallow_until_release || s_goal_swallow) {if (pressed) { data->state = LV_INDEV_STATE_RELEASED; return; }+ ESP_LOGI(TAG, "swallow cleared (wake=%d goal=%d)", s_swallow_until_release, s_goal_swallow);s_swallow_until_release = false;s_goal_swallow = false; // finger lifted → goal-hold press fully consumed}@@ -366,7 +486,11 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)if (display_is_asleep()) {// Asleep: a SINGLE tap WAKES the screen (Button A also wakes/sleeps). Wake on press-down and swallow// until the finger lifts so the waking tap doesn't fall through as a UI tap / start voice.- if (pressed) { display_wake(); s_swallow_until_release = true; }+ if (pressed) {+ ESP_LOGI(TAG, "wake tap at (%u,%u) — swallowing until release", x, y);+ display_wake();+ s_swallow_until_release = true;+ }data->state = LV_INDEV_STATE_RELEASED;return;}@@ -390,21 +514,21 @@ static void touch_read(lv_indev_t *indev, lv_indev_data_t *data)}}-void touch_init(void)+// Bring the CST9217 up on the shared bus. Everything that can fail, logs and leaves s_tp NULL.+static bool touch_open(void){- // Shared I2C master bus (touch + audio codecs live on the same bus).i2c_master_bus_handle_t bus = board_i2c_get();if (!bus) {ESP_LOGW(TAG, "shared i2c bus unavailable — touch disabled");- return;+ return false;}- esp_lcd_panel_io_handle_t tp_io = NULL;esp_lcd_panel_io_i2c_config_t io_cfg = ESP_LCD_TOUCH_IO_I2C_CST9217_CONFIG();io_cfg.scl_speed_hz = BSP_I2C_FREQ_HZ;- if (esp_lcd_new_panel_io_i2c(bus, &io_cfg, &tp_io) != ESP_OK) {+ if (esp_lcd_new_panel_io_i2c(bus, &io_cfg, &s_tp_io) != ESP_OK) {ESP_LOGW(TAG, "touch panel io failed — touch disabled");- return;+ s_tp_io = NULL;+ return false;}esp_lcd_touch_config_t tp_cfg = {@@ -416,11 +540,40 @@ void touch_init(void)// reversed vs the display (horizontal swipe and vertical scroll/taps). Mirror X and Y..flags = { .swap_xy = 0, .mirror_x = 1, .mirror_y = 1 },};- if (esp_lcd_touch_new_i2c_cst9217(tp_io, &tp_cfg, &s_tp) != ESP_OK) {+ if (esp_lcd_touch_new_i2c_cst9217(s_tp_io, &tp_cfg, &s_tp) != ESP_OK) {ESP_LOGW(TAG, "CST9217 init failed — touch disabled");s_tp = NULL;- return;+ esp_lcd_panel_io_del(s_tp_io);+ s_tp_io = NULL;+ return false;}+ return true;+}++// Tear the controller down and bring it back. Runs on the LVGL task (the indev read), where the driver's+// own I2C use already lives, so nothing else can be mid-transaction with it. The first real FIX in this+// file rather than a description: a controller that stopped answering gets a reset and a fresh init, and+// the log says whether that brought it back.+static void touch_reinit(void)+{+ if (s_tp) { esp_lcd_touch_del(s_tp); s_tp = NULL; }+ if (s_tp_io) { esp_lcd_panel_io_del(s_tp_io); s_tp_io = NULL; }+ if (touch_open()) ESP_LOGI(TAG, "CST9217 back after reinit");+ else ESP_LOGW(TAG, "CST9217 reinit failed — retrying in %ds", REINIT_RETRY_MS / 1000);+}++void touch_stats(touch_stats_t *out)+{+ out->presses = s_presses;+ out->last_press_ms_ago = s_presses ? lv_tick_elaps(s_last_press_tick) : 0;+ out->read_failures = s_read_fail_total;+ out->controller_ok = s_tp != NULL;+ out->held_now = s_stuck_warned;+}++void touch_init(void)+{+ if (!touch_open()) return;lv_indev_t *indev = lv_indev_create();lv_indev_set_type(indev, LV_INDEV_TYPE_POINTER);diff --git a/device/esp32-circle/main/ui/touch.h b/device/esp32-circle/main/ui/touch.hindex 37ca1c23d..04cecfead 100644--- a/device/esp32-circle/main/ui/touch.h+++ b/device/esp32-circle/main/ui/touch.h@@ -12,3 +12,14 @@ void touch_init(void);// Monotonic generation bumped once for every physical touch press. Background rendering, voice, and// programmatic display activity do not affect it, so callers can cheaply detect real user interaction.uint32_t touch_activity_generation(void);++// What the heartbeat prints about touch (display.c, once a minute): whether the controller answers,+// how many presses the glass has seen, and how long ago the last one was. Cheap; no lock.+typedef struct {+ uint32_t presses;+ uint32_t last_press_ms_ago;+ uint32_t read_failures;+ bool controller_ok;+ bool held_now; // a press has been down past the stuck threshold+} touch_stats_t;+void touch_stats(touch_stats_t *out);diff --git a/device/esp32-circle/main/ui/ui_screens.c b/device/esp32-circle/main/ui/ui_screens.cindex 80519831d..161685ca1 100644--- a/device/esp32-circle/main/ui/ui_screens.c+++ b/device/esp32-circle/main/ui/ui_screens.c@@ -8176,3 +8176,45 @@ void ui_voice_stop(void)display_unlock();if (audio_client_active()) audio_client_stop();}++// ── what covers the face, as one line whenever it changes ───────────────────────────────────────────+// A press eaten by an invisible clickable layer is indistinguishable from dead touch, and the dial has+// half a dozen things that can be over a tile: the voice overlay, the dim, the notification drawer, the+// agent switcher, the picker screen, the lock. Rather than a line at every show and hide site (there are+// dozens, on several tasks), this is ONE snapshot, taken on the LVGL task every loop and printed only+// when it differs from the last one. Read beside touch.c's press/release lines, it says what the press+// landed on.+void ui_log_state_if_changed(void)+{+ static uint32_t last;+ lv_obj_t *scr = lv_screen_active();+ int page = scr == scr_projects ? (s_overview_active ? 1 : s_settings_active ? 2 : s_machines_active ? 3 : 4)+ : scr == scr_reader ? 5 : scr == scr_question ? 6 : scr == scr_picker ? 7+ : scr == scr_connecting ? 8 : scr == scr_error ? 9 : 0;+ bool voice_ov = s_voice_overlay && !lv_obj_has_flag(s_voice_overlay, LV_OBJ_FLAG_HIDDEN);+ bool dimmed = s_dim && lv_obj_get_style_bg_opa(s_dim, 0) > LV_OPA_50;+ uint32_t now = (uint32_t)page+ | (uint32_t)(page == 4 ? (s_active_idx & 0xFF) : 0) << 4+ | (uint32_t)voice_ov << 12+ | (uint32_t)ui_voice_is_active() << 13+ | (uint32_t)s_notif_open << 14+ | (uint32_t)ui_switch_is_open() << 15+ | (uint32_t)ui_lock_active() << 16+ | (uint32_t)display_is_asleep() << 17+ | (uint32_t)dimmed << 18+ | (uint32_t)s_connected << 19;+ if (now == last) return;+ last = now;+ static const char *const names[] = { "other", "overview", "settings", "machines", "agent", "reader",+ "question", "picker", "connecting", "error" };+ ESP_LOGI(TAG, "face: %s%s%s%s%s%s%s%s",+ names[page],+ voice_ov ? " +voice-overlay" : "",+ ui_voice_is_active() ? " +voice-active" : "",+ s_notif_open ? " +drawer" : "",+ ui_switch_is_open() ? " +switcher" : "",+ ui_lock_active() ? " +lock" : "",+ display_is_asleep() ? " asleep" : "",+ dimmed ? " dimmed" : "");+ if (page == 4) ESP_LOGI(TAG, "face: agent %d of %d%s", s_active_idx, s_proj_count, s_connected ? "" : " (not connected)");+}diff --git a/device/esp32-circle/main/ui/ui_screens.h b/device/esp32-circle/main/ui/ui_screens.hindex 96f7d1af7..770e3d820 100644--- a/device/esp32-circle/main/ui/ui_screens.h+++ b/device/esp32-circle/main/ui/ui_screens.h@@ -348,3 +348,7 @@ void ui_lock_init_gate(void);void ui_lock_setup(void);// True while the unlock overlay is blocking the UI.bool ui_lock_active(void);++// One line on the log whenever what covers the face changes (screen, overlay, drawer, lock, sleep).+// Called from the LVGL task every loop; cheap when nothing changed.+void ui_log_state_if_changed(void);diff --git a/device/esp32-circle/sdkconfig.defaults b/device/esp32-circle/sdkconfig.defaultsindex 6a46ac6cc..d32084b25 100644--- a/device/esp32-circle/sdkconfig.defaults+++ b/device/esp32-circle/sdkconfig.defaults@@ -103,3 +103,12 @@ CONFIG_COMPILER_OPTIMIZATION_PERF=yCONFIG_ESP_CONSOLE_UART_DEFAULT=nCONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=yCONFIG_ESP_CONSOLE_SECONDARY_NONE=y++# ── a wedged UI task reboots instead of freezing ─────────────────────────────────────────────────────+# The LVGL task subscribes to the task watchdog (display.c). Without PANIC the watchdog only prints a+# warning every few seconds and the glass stays frozen; with it the dial reboots, and the reset reason+# plus the last log lines before it come back over the cable (last_words.c). 10s rather than the 5s+# default: a full-face redraw or a touch-controller reset (60ms of delays inside the indev read) must+# never be mistaken for a hang.+CONFIG_ESP_TASK_WDT_PANIC=y+CONFIG_ESP_TASK_WDT_TIMEOUT_S=10diff --git a/docs/plans/2026-09-15-003-dial-log-capture-plan.md b/docs/plans/2026-09-15-003-dial-log-capture-plan.mdnew file mode 100644index 000000000..e8e5609ff--- /dev/null+++ b/docs/plans/2026-09-15-003-dial-log-capture-plan.md@@ -0,0 +1,127 @@+# Dial log capture: make "the dial got stuck" traceable from a file the user can send++Status: implemented · 2026-09-15++## The problem++A recurring report: the dial **stops taking touch** — no swipe, the Voice button does nothing, the+screen sits on an agent tile — while the cable is plainly alive: switching panes in the app moves the+dial, notifications still ring, "task done" still beeps. So the reader task, the LVGL task and the+panel are all running; what died is the path from the glass to the gesture layer.++Nothing survives to be read afterwards. The dial keeps no log in flash. The daemon does receive the+firmware's log lines over the cable, but it writes them to **one unbounded file** that nobody looks+at and no tool exports:++| what exists today | where | problem |+|---|---|---|+| firmware `ESP_LOG*` lines, INFO level, framed as cable type `0x04` | `cable_link.c` `log_vprintf` | ships every line — but `touch.c` emits **five** lines in total (scroll totals and init failures); a gesture that never fires leaves no trace |+| daemon appends every log frame | `~/.harness/cli/data/dial.log` (`cableSession.ts:641`) | 3.7 MB since 2026-08-24, **never rotated, never pruned**, outside the app's log directory, not in Settings ▸ Debug |+| daemon's own log | `~/.harness/cli/data/harness.log` | has `cable:` open/close/silence/focus lines — the other half of the story, in a different file |+| app logs, per day, 14-day retention | `~/.harness/logs/app-*.log`, `cli-*.log` (`lib/logging/log_file.dart`) | the dial is not a source; there is no "export" — the user has to be walked through Finder |+| firmware reset | — | `esp_reset_reason()` is never logged; no task watchdog on the LVGL task; no last-words buffer — a panic + reboot looks like an unplug |++Bringing the device back to the desk does not help either: whatever happened is gone the moment the+cable is pulled.++## Goal++When it happens again, the person sends **one zip** and the log inside answers, in this order:+was the LVGL task alive · was touch data arriving from the controller · which gesture-layer flag was+holding the press · what was covering the face · did the device reset. Retention **7 days** for the+dial's log, bounded on disk.++## Plan++### 1. Daemon — the dial's log becomes a real log (small, ships first)++`cli/src/cable/cableSession.ts`++- Write log frames to **`~/.harness/logs/dial-YYYYMMDD.log`** — the directory the app already reads+ and prunes — one file per day, rolled at the first line after midnight. Stop writing `cli/data/dial.log`+ (leave a one-line pointer file for anyone with a bookmark).+- **7-day retention**: prune `dial-*.log` older than 7 days on roll-over (the app's `LogFile` does 14+ for its own; the dial's is chattier and the owner asked for 7).+- **Size cap** per day (20 MB): past it, write one `[daemon] dial log capped for today` line and drop+ the rest — a firmware stuck in a log loop must not fill the disk.+- Write the daemon's cable events into the **same file**, prefixed `[daemon]`: port open/close, hello+ (mac, fw, proto), silence-reopen, "not ours" release, focus pushes, agents/ring pushes, turn.started /+ turn.done / question relays, fw.offer. Today these are only in `harness.log`; a stuck report is read+ end to end from one file when both halves are in it.+- Line format stays `ISO-time <text>`; firmware lines keep their `I (ticks) tag:` prefix so the device's+ own clock (ms since boot) is beside wall time — a reboot shows as ticks going back to zero.++### 2. Firmware — say what the gesture layer is doing (the substance)++`device/esp32-circle/main/ui/touch.c`, `ui_screens.c`, `audio_client.c`, `display.c`, `app_main.c`++Throttled INFO lines, each written so a stuck case has a signature:++- **Touch samples.** One line per press (`press (x,y)`) and per release (`release (x,y) held=Nms`), and+ the verdict swipe_track reached (`tap` / `swipe ±` / `home` / `pull-down` / `scroll`). Never per+ sample — a drag is one `scroll:` line, as today.+- **The controller.** `esp_lcd_touch_read_data` returns an `esp_err_t` that `touch_read` ignores. Log the+ first failure and every 100th after it (`cst9217 read failed: 0x%x (n=…)`), and keep a consecutive-+ failure counter: past 50 (~1 s) log `cst9217 dead — reinit` and re-run the init path. This is also+ the first real *fix* candidate, not just a log.+- **The flags that swallow input.** `s_swallow_until_release`, `s_goal_swallow`, `action_capture`, the+ notification band's `ncap`, and `ui_voice_is_active()`: log when each is **set** (with why) and when it+ **clears**. A **stuck watchdog** in `touch_read`: any of them held > 5 s with no release sample →+ `WARN touch: <flag> held 5s, last sample pressed=%d (x,y)` once, then every 30 s. If the report matches+ the symptom, this line names the flag.+- **What covers the face.** `ui_screens.c`: one line on every screen load and on every top-layer overlay+ shown/hidden (voice overlay, dim, notification drawer, agent switcher, picker, lock). A press eaten by+ an invisible clickable overlay is otherwise indistinguishable from dead touch.+- **Voice.** `audio_client_active` transitions with the reason (`begin`/`end`/`abort`/`quota`), and a+ WARN if it stays active > 10 min — touch.c forwards nothing to LVGL while it is, which is exactly the+ reported shape (swipe dead, Voice dead, screen still following the app).+- **`display_lock` contention.** Any wait > 2 s logs the waiting task and the caller (a macro that passes+ `__func__`), so a deadlock between the reader task and the LVGL task is visible as the last line before+ silence.+- **Liveness heartbeat.** Every 60 s from the LVGL task: `alive up=%us heap=%u/%u lv=%u touches=%d+ last_press=%us`. Cable lines continuing while this one stops = the LVGL task is wedged. Its absence is+ the evidence, so the daemon marks the gap: `[daemon] no dial heartbeat for 90s` in the same file.+- **Reset reason and last words.** On boot, log `esp_reset_reason()` right after `hello`. Keep a 4 KB+ ring of the most recent log lines in `RTC_NOINIT_ATTR` memory (survives a soft reset, not a power+ cut); when the reset reason is panic / task WDT / interrupt WDT / brownout, replay the ring after the+ reset line as `last:` lines. Enable the **task watchdog on the LVGL task** (`CONFIG_ESP_TASK_WDT`,+ `esp_task_wdt_add` in the LVGL loop, `esp_task_wdt_reset` per tick) with panic → reboot, so a wedged+ UI task becomes a reboot with a stack in the log instead of a frozen glass.+- **Log level stays INFO**; the new lines are gated by rate, not by level, so a shipped build carries+ them. Budget: under ~40 lines/min in normal use (the heartbeat is one; a busy minute of swiping is a+ few dozen).++### 3. App — Settings ▸ Debug reads it and one button exports it++`desktop/lib/logging/`, `desktop/lib/settings/sections/debug_*.dart`++- A **Dial** source beside App and CLI in Settings ▸ Debug: a mirror of `dial-*.log` through the same+ `installFileLogs` ring, filterable by tag (`touch`, `ui`, `cable_client`, `[daemon]`).+- **Export logs** (toolbar button, also `harness logs export` in the CLI for a desk with no window): zip+ the last **7 days** of `app-*.log`, `cli-*.log`, `dial-*.log`, the tail of `harness.log` (last 5 MB),+ `harness status --json`, the app version and the dial's last hello (fw, mac) into+ `~/Desktop/harness-logs-YYYYMMDD-HHMM.zip`, every line through `redactSecretsInText` first. This is+ the file the owner asks for.+- The Debug pane's paths card lists the dial log beside the others.++### 4. What we expect to learn (the hypotheses the new lines separate)++| if the log shows… | it was… |+|---|---|+| heartbeat stops, cable lines continue | LVGL task wedged (display_lock deadlock line just before, or nothing = hard hang → the task WDT now reboots it with a stack) |+| `cst9217 read failed` runs, presses stop | touch controller / I2C hung → the reinit path either recovers it or names the fault |+| `touch: swallow_until_release held` / `goal_swallow held` | a release the controller never reported left the gesture layer holding the press |+| `audio_client_active` never ended | a voice upload with no terminal frame keeps every touch away from LVGL |+| overlay shown, never hidden | an invisible clickable layer (dim, drawer, picker) eating presses |+| `reset: panic` + `last:` lines | a crash that the daemon's silence-reopen made look like an unplug |++### 5. Order and size++1. Daemon rotation + `[daemon]` markers + 7-day prune — ~half a day, no firmware flash, immediately+ turns the next report into a file.+2. Firmware instrumentation + controller reinit + heartbeat + reset/last-words + task WDT — one to two+ days; the reinit and the WDT are the parts that may *fix* the symptom rather than describe it. Ships+ by `make upload-circle`, so it reaches every dial within ~6 h of publishing.+3. App Dial source + Export — one day.++Nothing here touches the wire protocol (log frames already exist), the ring, or the swarm plumbing.