From 442ca47a1c01ef08805af3447ce5e85ab55e4b77 Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:26:30 -0500 Subject: [PATCH] fix: reject lossy canvas replay before export --- scripts/lib/ui-canvas/server-routes.js | 45 ++++++- .../ui-canvas-replay-validation.test.js | 115 ++++++++++++++++++ 2 files changed, 158 insertions(+), 2 deletions(-) create mode 100644 tests/scripts/ui-canvas-replay-validation.test.js diff --git a/scripts/lib/ui-canvas/server-routes.js b/scripts/lib/ui-canvas/server-routes.js index a8486cd38..e1859f160 100644 --- a/scripts/lib/ui-canvas/server-routes.js +++ b/scripts/lib/ui-canvas/server-routes.js @@ -11,7 +11,7 @@ const crypto = require('crypto'); const { uiEditorJs } = require('./editor'); const { renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('./ui'); -const { MAX_EDITS, MAX_HTML_BYTES, normalizeEdits, writeExport } = require('./feedback'); +const { MAX_EDITS, MAX_HTML_BYTES, normalizeEdit, normalizeEdits, writeExport } = require('./feedback'); const UI_ASSETS = { '/ui-canvas.css': { type: 'text/css; charset=utf-8', body: uiCanvasCss }, @@ -28,6 +28,42 @@ function serveUiAsset(pathname, res) { return true; } +function requireLosslessReplay(raw) { + const edit = normalizeEdit(raw, 0); + if (!edit) return; // Preserve omission of malformed/unknown edit kinds. + const reject = field => { + throw Object.assign(new Error(`replay cannot preserve the edit's ${field}; use a supported value`), { code: 'EUI_REPLAY_LOSSY' }); + }; + if (raw.selector !== edit.selector) reject('selector'); + if (typeof raw.id === 'string' && raw.id !== edit.id) reject('identity'); + if (edit.kind === 'text') { + if (raw.htmlAfter !== undefined) { + if (typeof raw.htmlAfter !== 'string' || raw.htmlAfter !== edit.htmlAfter) reject('markup'); + } else if (raw.after !== undefined && raw.after !== null && raw.after !== edit.after) reject('text'); + } + if (edit.kind === 'style') { + const after = raw.after === null || raw.after === undefined ? null : String(raw.after); + if (after !== edit.after) reject('style value'); + } + const number = (value, normalized) => { + if (value === undefined || value === null) return; + const parsed = typeof value === 'number' ? value : Number.parseFloat(value); + if (!Number.isFinite(parsed) || parsed !== normalized) reject('numeric value'); + }; + if (edit.kind === 'resize') { number(raw.width, edit.width); number(raw.height, edit.height); } + if (edit.kind === 'nudge') { number(raw.dx, edit.dx); number(raw.dy, edit.dy); } + if (edit.kind === 'move') { + if (raw.to.parent !== edit.to.parent) reject('destination selector'); + number(raw.to.index, edit.to.index); + } +} + +function includedBatchIds(session, bakedIds) { + return (session.uiBatches || []) + .filter(batch => batch.edits.length > 0 && batch.edits.every(edit => bakedIds.has(edit.id))) + .map(batch => batch.id); +} + // UI Canvas edit batches arrive with the full DOM snapshot. Write it (and the // edit log) next to the artifact before the item is queued, and hand the agent // paths instead of megabytes of markup. Chat items pass through untouched. @@ -39,6 +75,10 @@ function materializeUiExports(session, items) { || item.bakedEditIds.some(id => typeof id !== 'string' || id.length > 40))) { throw Object.assign(new Error('invalid or oversized applied-edit proof'), { code: 'EUI_PROOF_INVALID' }); } + for (const raw of Array.isArray(item.edits) ? item.edits : []) requireLosslessReplay(raw); + if (includedBatchIds(session, new Set(item.bakedEditIds || [])).length > 49) { + throw Object.assign(new Error('too many unincorporated Apply batches; ask the agent to incorporate them before applying more'), { code: 'EUI_PROOF_INVALID' }); + } if (typeof item.html !== 'string' || !item.html.trim()) throw Object.assign(new Error('html snapshot is required'), { code: 'EUI_HTML_MISSING' }); if (Buffer.byteLength(item.html, 'utf8') > MAX_HTML_BYTES) throw Object.assign(new Error('html snapshot too large'), { code: 'EUI_HTML_TOO_LARGE' }); } @@ -47,7 +87,7 @@ function materializeUiExports(session, items) { // The on-disk log holds the same normalized edits the agent receives. const edits = normalizeEdits(item.edits); const bakedIds = new Set(item.bakedEditIds || []); - const includedBatches = (session.uiBatches || []).filter(batch => batch.edits.every(edit => bakedIds.has(edit.id))).map(batch => batch.id); + const includedBatches = includedBatchIds(session, bakedIds); const written = writeExport(session.file, { html: item.html, edits, @@ -61,6 +101,7 @@ function materializeUiExports(session, items) { // Map an export failure to the HTTP status and message the browser shows. function exportErrorResponse(error) { + if (error.code === 'EUI_REPLAY_LOSSY') return { status: 422, error: error.message }; if (error.code === 'EUI_PROOF_INVALID' || error.code === 'EUI_EDITS_TOO_LARGE') return { status: 413, error: error.message }; if (error.code === 'EUI_HTML_TOO_LARGE') return { status: 413, error: 'html snapshot too large' }; if (error.code === 'EUI_HTML_MISSING') return { status: 400, error: 'edits and finish items need an html snapshot' }; diff --git a/tests/scripts/ui-canvas-replay-validation.test.js b/tests/scripts/ui-canvas-replay-validation.test.js new file mode 100644 index 000000000..71b371ce5 --- /dev/null +++ b/tests/scripts/ui-canvas-replay-validation.test.js @@ -0,0 +1,115 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const http = require('node:http'); +const { createSessionStore } = require('../../scripts/lib/plan-canvas/sessions'); +const { createPlanCanvasServer } = require('../../scripts/lib/plan-canvas/server'); +const { UI_PROFILE } = require('../../scripts/ui-canvas'); + +let passed = 0; +let failed = 0; +async function test(name, run) { + try { await run(); passed++; console.log(`PASS ${name}`); } + catch (error) { failed++; console.log(`FAIL ${name}: ${error.stack}`); } +} +const nudge = id => ({ id, kind: 'nudge', selector: '#a', dx: 1, dy: 0 }); +async function fixture(run) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-ui-replay-validation-')); + const file = path.join(directory, 'card.html'); + fs.writeFileSync(file, '
Original
'); + const store = createSessionStore({ stateDir: path.join(directory, 'state') }); + const { session } = store.open(file, { mode: 'ui' }); + const server = createPlanCanvasServer({ store }); + const { port } = await server.listen(0); + function request(items) { + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, method: 'POST', + path: `/api/session/${session.key}/feedback`, headers: { 'content-type': 'application/json' } }, response => { + let text = ''; response.on('data', chunk => { text += chunk; }); + response.on('end', () => resolve({ status: response.statusCode, body: JSON.parse(text) })); + }); + req.on('error', reject); req.end(JSON.stringify({ items })); + }); + } + function item(edits, extra = {}) { + return { kind: 'edits', html: '
Captured
', edits, ...extra }; + } + try { await run({ directory, file, store, session, request, item }); } + finally { await server.close(); fs.rmSync(directory, { recursive: true, force: true }); } +} + +async function main() { + for (const [label, edit] of [ + ['text markup', { id: 'e1', kind: 'text', selector: '#a', htmlAfter: 'x'.repeat(20001) }], + ['plain text', { id: 'e1', kind: 'text', selector: '#a', after: 'x'.repeat(4001) }], + ['style value', { id: 'e1', kind: 'style', selector: '#a', property: 'color', after: 'x'.repeat(501) }], + ['selector', { ...nudge('e1'), selector: '#' + 'a'.repeat(500) }], + ['edit identity', nudge('e'.repeat(41))], + ['resize bound', { id: 'e1', kind: 'resize', selector: '#a', width: 20001 }], + ['nudge bound', { ...nudge('e1'), dx: -20001 }], + ['fractional nudge', { ...nudge('e1'), dx: 1.5 }], + ['move index', { id: 'e1', kind: 'move', selector: '#a', from: { parent: 'body', index: 0 }, to: { parent: 'body', index: 100001 } }], + ['move parent', { id: 'e1', kind: 'move', selector: '#a', from: { parent: 'body', index: 0 }, to: { parent: '#' + 'a'.repeat(500), index: 0 } }], + ]) { + await test(`rejects lossy ${label} before exports or queue mutation`, () => fixture(async ({ directory, session, request, item }) => { + const before = fs.readdirSync(directory).sort(); + const state = JSON.stringify(session); + const response = await request([item([edit])]); + assert.equal(response.status, 422, JSON.stringify(response.body)); + assert.deepEqual(fs.readdirSync(directory).sort(), before); + assert.equal(JSON.stringify(session), state); + })); + } + await test('a later lossy item prevents exporting an earlier valid item', () => fixture(async ({ directory, request, item }) => { + const before = fs.readdirSync(directory).sort(); + const response = await request([item([nudge('e1')]), item([{ id: 'e2', kind: 'text', selector: '#a', htmlAfter: 'x'.repeat(20001) }])]); + assert.equal(response.status, 422); + assert.deepEqual(fs.readdirSync(directory).sort(), before); + })); + await test('boundary-size text and numeric replay payloads remain complete', () => fixture(async ({ session, request, item }) => { + const text = 'x'.repeat(20000); + const html = `
${text}
`; + const response = await request([item([ + { id: 'text', kind: 'text', selector: '#a', htmlAfter: text }, + { id: 'resize', kind: 'resize', selector: '#a', width: 20000, height: 1 }, + { ...nudge('nudge'), dx: -20000, dy: 20000 }, + ], { html })]); + assert.equal(response.status, 200); + assert.equal(response.body.batches[0].edits[0].htmlAfter, text); + assert.equal(session.uiBatches[0].edits[1].width, 20000); + assert.equal(session.uiBatches[0].edits[2].dx, -20000); + assert.equal(fs.readFileSync(session.pendingFeedback[0].exportPath, 'utf8'), html); + })); + await test('an empty older batch is not covered by unrelated edit IDs', () => fixture(async ({ store, session, request, item }) => { + const empty = store.queueFeedback(session.key, [{ kind: 'edits', edits: [], snapshotHash: 'a'.repeat(64) }]).accepted[0].id; + const response = await request([item([nudge('new')], { bakedEditIds: [] })]); + assert.equal(response.status, 200); + assert.deepEqual(session.uiBatches.at(-1).includedBatches, []); + assert.ok(session.uiBatches.some(batch => batch.id === empty)); + })); + for (const count of [49, 50]) { + await test(`${count} covered older batches ${count === 49 ? 'fit' : 'exceed'} the acknowledgment limit`, () => fixture(async ({ directory, store, session, request, item }) => { + const ids = Array.from({ length: count }, (_, index) => `old-${index}`); + store.queueFeedback(session.key, ids.map(id => ({ kind: 'edits', edits: [nudge(id)], snapshotHash: 'a'.repeat(64) }))); + const before = fs.readdirSync(directory).sort(); + const state = JSON.stringify(session); + const response = await request([item([nudge('latest')], { bakedEditIds: ids })]); + if (count === 50) { + assert.equal(response.status, 413); + assert.equal(JSON.stringify(session), state); + assert.deepEqual(fs.readdirSync(directory).sort(), before); + } else { + assert.equal(response.status, 200); + const latest = session.pendingFeedback.at(-1); + assert.equal(latest.includedBatches.length, 49); + const hint = UI_PROFILE.nextSteps.feedback({ items: session.pendingFeedback }); + assert.equal(hint.match(/--ack ([^ ]+)/)[1].split(',').length, 50); + } + })); + } + console.log(`Passed: ${passed}\nFailed: ${failed}`); process.exitCode = failed ? 1 : 0; +} +main().catch(error => { console.error(error); process.exitCode = 1; });