Skip to content

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.

fix(cable): stop sending a firmware slice twice when an ack lands mid-write

0xdiego25b1092249fa1f
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 3ce3b9654..9bdf17420 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -121,6 +121,7 @@ export class CableSession {
private decoder = new CableDecoder()
private timer: NodeJS.Timeout | null = null
private greetedMac: string | null = null
+ private greetedFw: string | null = null
private lastRx = 0
private stopped = false
@@ -212,6 +213,7 @@ export class CableSession {
// half-frame in front of the first real frame of the new one.
this.decoder.reset()
this.greetedMac = null
+ this.greetedFw = null
this.lastAgentsKey = '' // a new port is a new dial until proven otherwise; tell it everything
this.lastRx = Date.now()
this.host.log(`cable: open on ${opened.path}`)
@@ -221,6 +223,7 @@ export class CableSession {
this.host.log(`cable: closed (${why})`)
this.link = null
this.greetedMac = null
+ this.greetedFw = null
this.lastAgentsKey = ''
this.voice = null
// The dial keeps its running image; the half-written slot is erased again by the next accepted offer.
@@ -274,9 +277,20 @@ export class CableSession {
machine: { id: mac, name: this.host.machineName() },
voiceLang: this.host.voiceLang(),
})
- if (mac !== this.greetedMac) {
+ // Log a dial that is new OR that came back running something else. The version half of that test
+ // is not decoration: a dial reboots into its new image after an update and greets with the SAME
+ // mac, so keying the line on the mac alone suppresses the one line anybody wants after an OTA —
+ // "it came back, and on which version". Losing it left a successful 0.0.37 install unverifiable
+ // from the log on 2026-08-24.
+ const fw = str('fw') ?? '?'
+ if (mac !== this.greetedMac || fw !== this.greetedFw) {
+ const returning = mac === this.greetedMac
this.greetedMac = mac
- this.host.log(`cable: dial ${mac} on fw ${str('fw') ?? '?'} proto ${msg.proto}`)
+ this.greetedFw = fw
+ this.host.log(`cable: dial ${mac} ${returning ? 'back ' : ''}on fw ${fw} proto ${msg.proto}`)
+ // Both halves of the test above mean the same thing to this line: a dial with nothing on its
+ // screen. A repeat greeting from the same dial on the same image is a keepalive and is skipped,
+ // which is the whole reason the branch exists.
await this.pushAgents()
}
// Offered on every greeting, but only ONCE per version per session: accepting makes the dial erase
diff --git a/cli/src/cable/fwPush.spec.ts b/cli/src/cable/fwPush.spec.ts
index fe4f91ee4..571cd229f 100644
--- a/cli/src/cable/fwPush.spec.ts
+++ b/cli/src/cable/fwPush.spec.ts
@@ -78,6 +78,48 @@ describe('FirmwareTransfer', () => {
expect(sent.at(-1)).toBe(123) // the tail is short, not padded
})
+ it('sends every slice exactly once when acks land mid-write', async () => {
+ // THE FIELD FAILURE, REPRODUCED. On 2026-08-24 a 3,091,648-byte push reached the dial with slice 130
+ // written twice — once where it belonged and once over slice 131, which never arrived at all. Both
+ // writes were a full 8192 bytes, so the dial's counter read 3091648/3091648 and the daemon logged a
+ // complete transfer; only esp_ota_end caught it, as a checksum error that pointed nowhere near here.
+ //
+ // The cause was ordinary: pump() advanced `offset` AFTER awaiting the write, and `fw.progress` — which
+ // the read loop dispatches while that write is parked — called pump() again, which read the same
+ // unadvanced offset and sent the same slice.
+ //
+ // Every other test in this file passes a sendSlice that returns immediately, which is why none of them
+ // saw it: with no await gap there is no window for the ack to arrive in. This one parks, acks from
+ // inside the write, and asserts on the reassembled BYTES rather than their count — the count was the
+ // one thing that stayed correct.
+ const slices = 40
+ const size = FW_SLICE_BYTES * slices
+ const image = Buffer.alloc(size)
+ for (let i = 0; i < size; i++) image[i] = Math.floor(i / FW_SLICE_BYTES) & 0xff // each slice, its own byte
+
+ const sent: Buffer[] = []
+ let acked = 0
+ let transfer: FirmwareTransfer
+ transfer = new FirmwareTransfer(
+ image,
+ '1.2.3',
+ async (slice) => {
+ sent.push(Buffer.from(slice)) // a copy: the argument is a view into the image
+ await Promise.resolve() // a real write parks here, several times, on a tty
+ if (acked < size) {
+ acked += FW_SLICE_BYTES
+ void transfer.onProgress(acked) // the read loop does not wait for the writer, and neither does this
+ }
+ },
+ () => {},
+ )
+
+ await transfer.pump()
+
+ expect(sent.length).toBe(slices)
+ expect(Buffer.concat(sent).equals(image)).toBe(true)
+ })
+
it('says how far it got when it is cut off', async () => {
const log = vi.fn()
const image = Buffer.alloc(100_000)
diff --git a/cli/src/cable/fwPush.ts b/cli/src/cable/fwPush.ts
index 39da8057e..ff63d5888 100644
--- a/cli/src/cable/fwPush.ts
+++ b/cli/src/cable/fwPush.ts
@@ -111,6 +111,7 @@ export class FirmwareTransfer {
private acked = 0
private offset = 0
private done = false
+ private pumping = false
constructor(
private readonly image: Buffer,
@@ -123,12 +124,40 @@ export class FirmwareTransfer {
return this.done
}
- /** Push as much as the credit window allows. Called on accept and again on every `fw.progress`. */
+ /**
+ * Push as much as the credit window allows. Called on accept and again on every `fw.progress`.
+ *
+ * ⚠️ RE-ENTRANT BY DESIGN, AND BOTH GUARDS BELOW ARE LOAD-BEARING. This loop parks inside the write, and
+ * the ack that wakes the credit arrives DURING that park — `fw.progress` is dispatched from the read
+ * loop and calls straight back in here. So a second pump() running while the first is mid-slice is the
+ * normal case, not a pathological one.
+ *
+ * Measured on hardware 2026-08-24, and it is worth stating exactly because the symptom hid the cause:
+ * one slice of a 3,091,648-byte image went out TWICE and the next never went out at all. The dial wrote
+ * both, 8192 bytes each, so its byte counter reported a perfect 3091648/3091648 while the image in flash
+ * had slice 130 sitting where slice 131 belonged. It failed at esp_ota_end with a checksum error, which
+ * reads as a corrupt download rather than as a bug on this side. Reading the slot back and diffing it
+ * against the published image is what named it.
+ *
+ * · `offset` ADVANCES BEFORE THE AWAIT. Reserving the range first is what makes a concurrent entry
+ * pick up the NEXT slice instead of resending the one already on the wire.
+ * · `pumping` keeps the second caller out entirely. This side has no equivalent of the firmware's
+ * tx lock, so two loops on one port would interleave the halves of two frames. The running loop
+ * re-reads `acked` every iteration, so the credit the second caller brought is not lost by turning
+ * it away.
+ */
async pump(): Promise<void> {
- while (!this.done && this.offset < this.image.length && this.offset - this.acked < FW_WINDOW_BYTES) {
- const end = Math.min(this.offset + FW_SLICE_BYTES, this.image.length)
- await this.sendSlice(this.image.subarray(this.offset, end))
- this.offset = end
+ if (this.pumping) return
+ this.pumping = true
+ try {
+ while (!this.done && this.offset < this.image.length && this.offset - this.acked < FW_WINDOW_BYTES) {
+ const end = Math.min(this.offset + FW_SLICE_BYTES, this.image.length)
+ const slice = this.image.subarray(this.offset, end)
+ this.offset = end
+ await this.sendSlice(slice)
+ }
+ } finally {
+ this.pumping = false
}
}
diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.ts
index 2de514398..aa51a16f9 100644
--- a/cli/src/cable/serial.ts
+++ b/cli/src/cable/serial.ts
@@ -183,8 +183,31 @@ export class SerialLink {
this.onClosed(why)
}
- /** Write every byte, looping over short writes. Rejects only when the port is gone. */
+ /**
+ * Write every byte of ONE frame, looping over short writes. Rejects only when the port is gone.
+ *
+ * ⚠️ SERIALISED, AND NOT AS A PRECAUTION. A tty accepts a few hundred bytes at a time, so an 8 KB
+ * firmware slice takes several passes through the loop below and parks on an await between each. Frames
+ * come from several places at once — the 5-second ping, the per-tick agent sync, a slice pump — and
+ * without this queue a JSON frame lands in the MIDDLE of a firmware slice. The dial's decoder resyncs
+ * past the wreckage, which costs it both frames, and the transfer then fails at the far end with a
+ * checksum error that says nothing about whose fault it was.
+ *
+ * The firmware holds exactly this invariant on its own side (`s_tx_lock` in cable_link.c, "two tasks
+ * sending at once cannot interleave halves of two frames"). This is the mirror of it. A failed write
+ * must not strand the writes queued behind it, so the tail deliberately swallows the rejection — the
+ * caller still receives it.
+ */
async write(bytes: Uint8Array): Promise<void> {
+ if (this.closed) throw new Error('port closed')
+ const next = this.tail.then(() => this.writeFrame(bytes))
+ this.tail = next.catch(() => {})
+ return next
+ }
+
+ private tail: Promise<void> = Promise.resolve()
+
+ private async writeFrame(bytes: Uint8Array): Promise<void> {
if (this.closed) throw new Error('port closed')
let off = 0
while (off < bytes.length) {