fix: preserve UI Canvas edits through delivery and reload

This commit is contained in:
haelyra committed 2026-11-19 17:40:32 -05:00
1 parent ccd8da1a72
commit 6edc259654
18 files changed
+577 -71

No files matched your search

+10 -3
View File
@@ -104,7 +104,7 @@ listening" so the human knows you are connected.
request to repaint is the target for a one-property change.
```json
{ "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ],
{ "id": "fb-123", "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ],
"viewport": { "preset": "mobile", "width": 393, "height": 852 },
"exportPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edits.json" }
```
@@ -115,14 +115,21 @@ listening" so the human knows you are connected.
their inline-style changes), tidy it into real CSS if it is messy, keep it
self-contained, and reply. Each Apply writes its own
`<name>.apply-<batch>.*` pair, so a queued earlier batch keeps its own
snapshot. The canvas keeps showing the applied edits until your write to
the mockup reloads it, then drops them, so nothing is applied twice.
snapshot. The canvas keeps showing submitted edits until it recognizes the
exact exported snapshot or you explicitly acknowledge the incorporated batch.
After incorporating a batch, acknowledge its feedback ID with
`ecc-ui-canvas await <file> --ack fb-123 --reply "Applied the requested changes."`.
Multiple IDs may be comma-separated. Do not acknowledge a queued batch while
answering an earlier chat. Exact copies of exported snapshots are recognized
automatically; an unrelated file save is not acknowledgment. If a submitted
batch no longer matches the file, resolve it before applying more changes.
```json
{ "kind": "finish", "editCount": 5, "edits": [ "…" ], "viewport": { "preset": "desktop", "width": 1412, "height": 806 },
"exportPath": "…/pricing-card.edited.html", "editsPath": "…/pricing-card.edits.json" }
```
- `finish` means the human clicked **Save and Finish**. The session is over
(`sessionEnded: true`). Read `exportPath`, diff it against your original
mockup, read `editsPath` for the intent behind each change, and reproduce
+1 -1
View File
@@ -25,7 +25,7 @@ export.
4. On `chat`: signal `typing --state thinking`, edit the mockup file (the
preview live-reloads and keeps their pending edits), answer with
`await <file> --reply "…"`, repeat.
5. On `edits`: rewrite the mockup from `exportPath`, reply, keep listening.
5. On `edits`: rewrite the mockup from `exportPath`, then acknowledge its feedback ID with `await <file> --ack fb-123 --reply "…"` and keep listening. Acknowledge only batches actually incorporated; unrelated saves retain queued edits.
6. On `finish`: read `exportPath` and `editsPath`, implement that exact
design in the real component, commit per repo rules, report in chat.
+12
View File
@@ -125,3 +125,15 @@ The skill tells the agent to signal `typing --state thinking` immediately and re
`node tests/integration/ui-canvas-e2e.test.js`, plus the existing Plan Canvas suites, run under
`node tests/run-all.js`. Manual browser QA uses a mockup opened with
`ECC_PLAN_CANVAS_STATE_DIR=/tmp/uc ECC_PLAN_CANVAS_PORT=4599 node scripts/ui-canvas.js open <file> --no-open`.
Replay identifies a target only when its selector has exactly one match. Unique
`#id` targets (and `body`/`html`) may survive an unrelated save; positional paths
and positional move parents replay only against their captured source revision.
Changed positional targets and duplicate IDs stay stale rather than editing a
different element. Submitted batches replay atomically: if any target cannot be
resolved safely, the whole batch stays visibly unresolved and Apply/Finish wait
for agent resolution. Reset reverts unsent edits and retains unresolved submitted
changes. The agent may acknowledge specific incorporated batches using UI Canvas
`await --ack fb-123`; merely draining feedback or saving another change is not
acknowledgment. An exact exported snapshot can acknowledge only the batch and
older batches proven completely represented in that snapshot.
@@ -10,7 +10,7 @@
"id": "hand-seeded",
"source": "manual-curation-pending-regeneration"
},
"registryDigest": "27e0424730a1ad30f57f210cdfc8f8d72493cfe8f5ffc9d3ead4b2943e1131ed",
"registryDigest": "b03d62b492f06ea616820e28e85a13244b48fbd60e9b8fad380c6d90191d6f49",
"schemaVersion": 1,
"triggers": {
"skill:agent-runtime-gateway-smoke-test": [
+42 -6
View File
@@ -11,6 +11,7 @@
const { EventEmitter } = require('events');
const fs = require('fs');
const crypto = require('crypto');
const http = require('http');
const path = require('path');
@@ -362,6 +363,24 @@ function createPlanCanvasServer({
// --- artifact watching --------------------------------------------------
function acknowledgeUiBatches(session, ids, reload = false, replyText) {
const result = store.acknowledgeUiBatches(session.key, ids, replyText);
if (result && result.batches.length) broadcast(session.key, 'ui-ack', { batches: result.batches, reload });
return result;
}
function acknowledgeUiSnapshot(session, content) {
if (session.mode !== 'ui' || !(session.uiBatches || []).length) return;
const hash = crypto.createHash('sha256').update(content).digest('hex');
const index = session.uiBatches.findIndex(batch => batch.snapshotHash === hash);
// Only the exact batch and earlier batches the editor successfully
// replayed are known to be present; unresolved selectors stay queued.
if (index >= 0) {
const batch = session.uiBatches[index];
acknowledgeUiBatches(session, [batch.id, ...(batch.includedBatches || []).filter(id => session.uiBatches.some(known => known.id === id))]);
}
}
function watchSession(session) {
if (watchers.has(session.key)) return;
const dir = path.dirname(session.file);
@@ -371,7 +390,10 @@ function createPlanCanvasServer({
const watcher = fs.watch(dir, (eventType, filename) => {
if (filename && filename !== base) return;
clearTimeout(debounce);
debounce = setTimeout(() => broadcast(session.key, 'reload', {}), 150);
debounce = setTimeout(() => {
try { acknowledgeUiSnapshot(session, fs.readFileSync(session.file)); } catch { /* missing or partial saves do not acknowledge */ }
broadcast(session.key, 'reload', {});
}, 150);
});
watcher.on('error', () => watchers.delete(session.key));
watchers.set(session.key, watcher);
@@ -562,6 +584,7 @@ function createPlanCanvasServer({
status: 'queued',
accepted: result.accepted.length,
pending: result.pending,
batches: result.accepted.filter(item => item.kind === 'edits').map(item => ({ id: item.id, edits: item.edits.filter(edit => !edit.stale) })),
presence: presenceFor(key)
});
}
@@ -573,14 +596,25 @@ function createPlanCanvasServer({
if (action === 'reply') {
const body = await readJsonBody(req);
if (!body.text || typeof body.text !== 'string') {
return sendJson(res, 400, { error: 'text is required' });
const ids = body.acknowledge;
if (ids !== undefined && (session.mode !== 'ui' || !Array.isArray(ids) || !ids.length || ids.length > 50
|| ids.some(id => typeof id !== 'string' || !/^fb-[1-9][0-9]{0,15}$/.test(id)))) {
return sendJson(res, 400, { error: 'acknowledge requires known UI batch IDs' });
}
const entry = store.addAgentReply(key, body.text);
if (body.text !== undefined && (typeof body.text !== 'string' || !body.text.trim())) {
return sendJson(res, 400, { error: 'text must be a nonempty string' });
}
if (body.text === undefined && ids === undefined) return sendJson(res, 400, { error: 'text is required' });
let acknowledgment = null;
try {
if (ids) acknowledgment = acknowledgeUiBatches(session, ids, true, body.text);
} catch { return sendJson(res, 500, { error: 'could not persist UI acknowledgment' }); }
if (ids && acknowledgment === null) return sendJson(res, 400, { error: 'unknown UI batch ID' });
const entry = ids ? acknowledgment.entry : store.addAgentReply(key, body.text);
clearAgentActivity(key);
broadcast(key, 'chat-sync', { chat: store.get(key).chat });
broadcastPresence(key);
return sendJson(res, 200, { status: 'sent', at: entry.at });
return sendJson(res, 200, { status: 'sent', ...(entry ? { at: entry.at } : {}) });
}
// Agents drive the chat indicator explicitly: `thinking` while they work,
@@ -613,6 +647,7 @@ function createPlanCanvasServer({
});
res.write(`event: chat-sync\ndata: ${JSON.stringify({ chat: session.chat })}\n\n`);
res.write(`event: presence\ndata: ${JSON.stringify(presencePayload(key))}\n\n`);
if (session.mode === 'ui') res.write(`event: ui-ack\ndata: ${JSON.stringify({ batches: session.uiAcknowledged || [] })}\n\n`);
if (!sseClients.has(key)) sseClients.set(key, new Set());
sseClients.get(key).add(res);
lastPresence.set(key, presenceFor(key));
@@ -652,8 +687,9 @@ function createPlanCanvasServer({
});
return sendHtml(res, 200, html, { csp: 'artifact' });
}
acknowledgeUiSnapshot(session, content);
const sdkTag = session.mode === 'ui'
? '<script src="/ui-editor.js" data-ecc-ui-canvas="editor"></script>'
? `<script src="/ui-editor.js" data-ecc-ui-canvas="editor" data-source-sha256="${crypto.createHash('sha256').update(content).digest('hex')}"></script>`
: '<script src="/sdk.js"></script>';
const injected = content.includes('</body>')
? content.replace('</body>', `${sdkTag}\n</body>`)
+25
View File
@@ -201,6 +201,12 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
if (item) accepted.push(item);
}
session.pendingFeedback.push(...accepted);
if (session.mode === 'ui') {
session.uiBatches = session.uiBatches || [];
for (const item of accepted) {
if (item.kind === 'edits') session.uiBatches.push({ id: item.id, snapshotHash: item.snapshotHash, includedBatches: item.includedBatches || [], edits: item.edits.filter(edit => !edit.stale) });
}
}
for (const item of accepted) {
session.chat.push({ role: 'user', kind: item.kind, text: describe(item), at: item.at });
}
@@ -215,6 +221,24 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
return { accepted, pending: session.pendingFeedback.length, session };
}
// Acknowledgment is distinct from delivery: taking feedback is not proof
// that the agent has incorporated it into the artifact.
function acknowledgeUiBatches(key, ids, replyText) {
const session = get(key);
if (!session || session.mode !== 'ui') return null;
const known = [...(session.uiBatches || []), ...(session.uiAcknowledged || [])];
if (ids.some(id => !known.some(batch => batch.id === id))) return null;
const accepted = (session.uiBatches || []).filter(batch => ids.includes(batch.id));
const previous = { uiBatches: session.uiBatches, uiAcknowledged: session.uiAcknowledged, chat: session.chat, updatedAt: session.updatedAt };
const entry = replyText ? { role: 'agent', kind: 'chat', text: sanitizeText(replyText), at: nowIso() } : null;
session.uiBatches = (session.uiBatches || []).filter(batch => !ids.includes(batch.id));
session.uiAcknowledged = [...(session.uiAcknowledged || []), ...accepted.map(batch => ({ id: batch.id, editIds: batch.edits.map(edit => edit.id) }))];
if (entry) session.chat = [...session.chat, entry];
session.updatedAt = nowIso();
try { persist(); } catch (error) { Object.assign(session, previous); throw error; }
return { batches: accepted.map(batch => ({ id: batch.id, editIds: batch.edits.map(edit => edit.id) })), entry };
}
// Deliver-and-drain: feedback is handed to exactly one await call, after
// which the session flips back to open. An ended session keeps reporting
// ended (with attribution) so agents know to stop polling.
@@ -286,6 +310,7 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
findByFile,
queueFeedback,
takeFeedback,
acknowledgeUiBatches,
addAgentReply,
setAgent,
end,
+4 -4
View File
@@ -161,7 +161,7 @@ function editorGesturesJs() {
dropEl.style.display = 'none';
var plan = g.plan;
if (!plan) return;
var sameSpot = plan.container === g.fromParent && (plan.index === g.fromIndex || plan.index === g.fromIndex + 1);
var sameSpot = plan.container === g.fromParent && plan.index === g.fromIndex;
if (sameSpot) return;
var fromSelector = selectorFor(g.el);
var fromParentSelector = selectorFor(g.fromParent);
@@ -179,7 +179,7 @@ function editorGesturesJs() {
function nudgeBy(dx, dy) {
if (!selected) return;
var last = edits.length ? edits[edits.length - 1] : null;
if (last && last.kind === 'nudge' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 1500) {
if (last && !last._exported && last.kind === 'nudge' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 1500) {
applyInline(selected, { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' });
last.dx += dx;
last.dy += dy;
@@ -217,7 +217,7 @@ function editorGesturesJs() {
var cs = getComputedStyle(selected);
var before = cs.getPropertyValue(property);
var last = edits.length ? edits[edits.length - 1] : null;
if (last && last.kind === 'style' && last.property === property && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) {
if (last && !last._exported && last.kind === 'style' && last.property === property && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) {
selected.style.setProperty(property, value === null ? RESET_VALUES[property] : value);
last.after = value;
last.at = new Date().toISOString();
@@ -235,7 +235,7 @@ function editorGesturesJs() {
function setSize(width, height) {
if (!selected) return;
var last = edits.length ? edits[edits.length - 1] : null;
if (last && last.kind === 'resize' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) {
if (last && !last._exported && last.kind === 'resize' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) {
if (width !== null && width !== undefined) last.width = Math.round(width);
if (height !== null && height !== undefined) last.height = Math.round(height);
var next = sizeStyles(selected, last.width, last.height);
+66 -22
View File
@@ -29,6 +29,7 @@ function uiEditorJs() {
if (window.__eccUiCanvasEditor) return;
window.__eccUiCanvasEditor = true;
var sourceRevision = document.currentScript && document.currentScript.getAttribute('data-source-sha256');
var post = function (msg) { window.parent.postMessage(msg, '*'); };
// ---- state -------------------------------------------------------------
@@ -37,6 +38,8 @@ function uiEditorJs() {
var hovered = null;
var editing = null;
var edits = [];
var deliveryRequest = null;
var bakedEditIds = [];
var redoStack = [];
var editSeq = 0;
var gesture = null;
@@ -137,7 +140,7 @@ function uiEditorJs() {
return step + ':nth-of-type(' + nthOfType(el) + ')';
}
// Prefer a unique id, else a type path scoped to the nearest id. Verified
// unique so re-application after a reload lands on the same node.
// unique within this source revision; positional paths cannot prove identity after a rewrite.
function selectorFor(el) {
if (!isElement(el)) return 'body';
if (el.id && /^[A-Za-z_][\w-]*$/.test(el.id) && document.querySelectorAll('#' + esc(el.id)).length === 1) return '#' + esc(el.id);
@@ -157,7 +160,11 @@ function uiEditorJs() {
return selector;
}
function resolve(selector) {
try { var el = document.querySelector(selector); return el && !isOurs(el) ? el : null; } catch (_e) { return null; }
try { var matches = document.querySelectorAll(selector); return matches.length === 1 && !isOurs(matches[0]) ? matches[0] : null; } catch (_e) { return null; }
}
function resolveForEdit(selector, revision) {
if (!/^(#[A-Za-z_][\w-]*|body|html)$/.test(selector) && (!revision || revision !== sourceRevision)) return null;
return resolve(selector);
}
function snippetFor(el) {
if (!isElement(el)) return '';
@@ -237,7 +244,7 @@ function uiEditorJs() {
function describe(el) {
var rect = el.getBoundingClientRect();
return {
selector: selectorFor(el),
selector: selectorFor(el), sourceRevision: sourceRevision,
tag: el.tagName.toLowerCase(),
id: el.id || '',
classes: Array.prototype.slice.call(el.classList, 0, 6),
@@ -307,7 +314,7 @@ function uiEditorJs() {
// ---- edit log -----------------------------------------------------------------
function newEdit(kind, el, detail) {
editSeq += 1;
var edit = { id: 'e' + editSeq + '-' + Date.now().toString(36), kind: kind, selector: selectorFor(el), tag: el.tagName.toLowerCase(), snippet: snippetFor(el), at: new Date().toISOString() };
var edit = { id: 'e' + editSeq + '-' + Date.now().toString(36), kind: kind, selector: selectorFor(el), sourceRevision: sourceRevision, tag: el.tagName.toLowerCase(), snippet: snippetFor(el), at: new Date().toISOString() };
for (var key in detail) if (Object.prototype.hasOwnProperty.call(detail, key)) edit[key] = detail[key];
return edit;
}
@@ -368,7 +375,7 @@ function uiEditorJs() {
// edit targets (resolved by selector during re-application). Returns false
// when the document no longer matches, so the edit can be flagged stale.
function applyEdit(edit, el) {
el = el || resolve(edit.selector);
el = el || resolveForEdit(edit.selector, edit.sourceRevision);
if (edit.kind === 'remove') {
if (!el) return false;
var parent = el.parentElement;
@@ -404,7 +411,7 @@ function uiEditorJs() {
return true;
}
if (edit.kind === 'move') {
var target = resolve(edit.to.parent);
var target = resolveForEdit(edit.to.parent, edit.sourceRevision);
if (!target) return false;
edit._fromParent = el.parentElement;
edit._fromIndex = indexIn(el.parentElement, el);
@@ -424,7 +431,7 @@ function uiEditorJs() {
}
function revertEdit(edit) {
if (edit.stale) return false;
var el = edit._el && edit._el.isConnected ? edit._el : (edit.kind === 'remove' ? edit._el : resolve(edit.selector));
var el = edit._el && edit._el.isConnected ? edit._el : (edit.kind === 'remove' ? edit._el : resolveForEdit(edit.selector, edit.sourceRevision));
if (edit.kind === 'remove') {
if (!el || !edit._parent) return false;
insertAt(edit._parent, el, edit._index);
@@ -441,6 +448,7 @@ function uiEditorJs() {
return false;
}
function undo() {
if (deliveryRequest) return;
for (var i = edits.length - 1; i >= 0; i--) {
if (edits[i].stale) continue;
var edit = edits.splice(i, 1)[0];
@@ -455,6 +463,7 @@ function uiEditorJs() {
scheduleBoxes();
}
function redo() {
if (deliveryRequest) return;
var edit = redoStack.pop();
if (!edit) return;
if (applyEdit(edit, edit._el && edit._el.isConnected ? edit._el : null)) { edits.push(edit); toast('Redid ' + edit.kind); }
@@ -463,13 +472,14 @@ function uiEditorJs() {
scheduleBoxes();
}
function resetAll() {
if (deliveryRequest) return;
for (var i = edits.length - 1; i >= 0; i--) revertEdit(edits[i]);
edits = [];
edits = edits.filter(function (edit) { return edit.submitted; });
redoStack = [];
postEdits();
postSelection();
scheduleBoxes();
toast('All edits reverted');
toast(edits.length ? 'Pending edits reverted; applied changes still need agent resolution' : 'All edits reverted');
}
// After the agent rewrites the file the frame reloads from scratch; the
// shell hands back the edit log and we replay it in order. Edits whose
@@ -484,24 +494,43 @@ function uiEditorJs() {
var incoming = Array.isArray(payload.edits) ? payload.edits : [];
var baked = Array.isArray(payload.baked) ? payload.baked : [];
edits = [];
bakedEditIds = [];
deliveryRequest = payload.deliveryRequest || null;
redoStack = [];
// Applied but not yet written to the file: re-apply without logging them,
// so the preview keeps showing what the human handed over.
for (var b = 0; b < baked.length; b++) {
applyEdit(copyEdit(baked[b]), null);
var bakedSeq = parseInt(String(baked[b].id).slice(1), 10);
if (bakedSeq > editSeq) editSeq = bakedSeq;
// Replay submitted batches atomically. A missing target must not leave
// the represented part of a batch applied twice on a partially edited file.
var batches = Array.isArray(payload.batches) ? payload.batches : [{ edits: baked }];
for (var b = 0; b < batches.length; b++) {
var applied = [], failed = false;
var batchEdits = batches[b].edits || [];
for (var n = 0; n < batchEdits.length; n++) {
var candidate = copyEdit(batchEdits[n]);
if (!applyEdit(candidate, null)) { failed = true; break; }
applied.push(candidate);
}
if (failed) {
for (var r = applied.length - 1; r >= 0; r--) revertEdit(applied[r]);
batchEdits.forEach(function (edit) { edits.push(Object.assign(copyEdit(edit), { stale: true, submitted: true })); });
} else {
batchEdits.forEach(function (edit) { bakedEditIds.push(edit.id); });
}
batchEdits.forEach(function (edit) {
var seq = parseInt(String(edit.id).slice(1), 10);
if (seq > editSeq) editSeq = seq;
});
}
for (var i = 0; i < incoming.length; i++) {
if (incoming[i].submitted) continue;
var edit = copyEdit(incoming[i]);
delete edit.stale;
if (!applyEdit(edit, null)) edit.stale = true;
if (edit.unverified || !applyEdit(edit, null)) edit.stale = true;
if (deliveryRequest) edit._exported = true;
edits.push(edit);
var seq = parseInt(String(edit.id).slice(1), 10);
if (seq > editSeq) editSeq = seq;
}
if (payload.scroll) window.scrollTo(payload.scroll.x || 0, payload.scroll.y || 0);
if (payload.selection) { var el = resolve(payload.selection); if (el) selected = el; }
if (payload.selection) { var el = resolveForEdit(payload.selection, payload.selectionRevision); if (el) selected = el; }
updateBoxes();
postEdits();
postSelection();
@@ -711,18 +740,33 @@ ${editorGesturesJs()}
case 'uc:redo': redo(); break;
case 'uc:reset': resetAll(); break;
case 'uc:forget':
// The agent baked the current edits into the file: drop the log
// without touching the DOM so nothing is replayed twice.
edits = [];
redoStack = [];
// Compatibility with an older shell: a scoped acknowledgment should
// always supply IDs so edits created after capture stay undoable.
edits = edits.filter(function (edit) { return !Array.isArray(msg.editIds) || msg.editIds.indexOf(edit.id) < 0; });
postEdits();
postSelection();
break;
case 'uc:delivery-end':
if (deliveryRequest !== msg.requestId) break;
if (msg.accepted) {
bakedEditIds = bakedEditIds.concat(msg.editIds);
edits = edits.filter(function (edit) { return msg.editIds.indexOf(edit.id) < 0; });
}
deliveryRequest = null;
edits.forEach(function (edit) { delete edit._exported; });
postEdits();
postSelection();
break;
case 'uc:pause-animations':
animationsPaused = Boolean(msg.paused);
if (animationsPaused) document.head.appendChild(pauseStyle); else pauseStyle.remove();
break;
case 'uc:export':
post({ type: 'uc:export', requestId: msg.requestId, html: exportHtml(), edits: edits.map(publicEdit) });
if (msg.lock) {
deliveryRequest = msg.requestId;
edits.forEach(function (edit) { edit._exported = true; });
}
post({ type: 'uc:export', requestId: msg.requestId, html: exportHtml(), edits: edits.map(publicEdit), bakedEditIds: bakedEditIds.slice() });
break;
case 'uc:scroll-to': window.scrollTo(msg.x || 0, msg.y || 0); break;
default: break;
+3
View File
@@ -109,6 +109,7 @@ function normalizeEdit(raw, position) {
snippet: clampText(raw.snippet, MAX_SNIPPET),
at: typeof raw.at === 'string' && raw.at ? clampText(raw.at, 40) : nowIso()
};
if (typeof raw.sourceRevision === 'string' && /^[a-f0-9]{64}$/.test(raw.sourceRevision)) edit.sourceRevision = raw.sourceRevision;
if (raw.stale === true) edit.stale = true;
switch (raw.kind) {
@@ -239,6 +240,8 @@ function normalizeUiFeedbackItem(raw, counter) {
}
return item;
}
if (typeof raw.snapshotHash === 'string' && /^[a-f0-9]{64}$/.test(raw.snapshotHash)) item.snapshotHash = raw.snapshotHash;
if (Array.isArray(raw.includedBatches)) item.includedBatches = raw.includedBatches.filter(id => typeof id === 'string' && /^fb-[1-9][0-9]{0,15}$/.test(id));
item.edits = normalizeEdits(raw.edits);
item.editCount = item.edits.length;
const viewport = normalizeViewport(raw.viewport);
+17 -2
View File
@@ -7,9 +7,11 @@
* session mode.
*/
const crypto = require('crypto');
const { uiEditorJs } = require('./editor');
const { renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('./ui');
const { normalizeEdits, writeExport } = require('./feedback');
const { MAX_EDITS, MAX_HTML_BYTES, normalizeEdits, writeExport } = require('./feedback');
const UI_ASSETS = {
'/ui-canvas.css': { type: 'text/css; charset=utf-8', body: uiCanvasCss },
@@ -30,10 +32,22 @@ function serveUiAsset(pathname, res) {
// 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.
function materializeUiExports(session, items) {
for (const item of items) {
if (!item || typeof item !== 'object' || (item.kind !== 'edits' && item.kind !== 'finish')) continue;
if (Array.isArray(item.edits) && item.edits.length > MAX_EDITS) throw Object.assign(new Error('too many edits in one Apply'), { code: 'EUI_EDITS_TOO_LARGE' });
if (item.bakedEditIds !== undefined && (!Array.isArray(item.bakedEditIds) || item.bakedEditIds.length > 5000
|| 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' });
}
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' });
}
return items.map(item => {
if (!item || typeof item !== 'object' || (item.kind !== 'edits' && item.kind !== 'finish')) return item;
// 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 written = writeExport(session.file, {
html: item.html,
edits,
@@ -41,12 +55,13 @@ function materializeUiExports(session, items) {
kind: item.kind
});
const { html: _html, ...rest } = item;
return { ...rest, edits, exportPath: written.exportPath, editsPath: written.editsPath };
return { ...rest, edits, includedBatches, snapshotHash: crypto.createHash('sha256').update(item.html).digest('hex'), exportPath: written.exportPath, editsPath: written.editsPath };
});
}
// Map an export failure to the HTTP status and message the browser shows.
function exportErrorResponse(error) {
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' };
return { status: 500, error: `could not write the export next to the artifact: ${error.message}` };
+54 -21
View File
@@ -85,10 +85,19 @@ function uiClientJs() {
} catch (_e) { /* storage blocked: the canvas still works for this page load */ }
}
const stored = readStore();
let edits = Array.isArray(stored.edits) ? stored.edits : [];
// Applied edits the agent has not written into the file yet. They replay
// silently on any reload until the file itself changes.
let submitted = Array.isArray(stored.submitted) ? stored.submitted : [];
const acknowledged = new Set((boot.uiAcknowledged || []).map(batch => batch.id));
const acknowledgedEdits = new Set((boot.uiAcknowledged || []).flatMap(batch => batch.editIds));
let submitted = Array.isArray(boot.uiBatches) ? boot.uiBatches : [];
const acceptedEdits = new Set(submitted.flatMap(batch => batch.edits.map(edit => edit.id)));
let edits = (Array.isArray(stored.edits) ? stored.edits : []).filter(edit => !acceptedEdits.has(edit.id) && !acknowledgedEdits.has(edit.id));
// Older shells stored only a flat submitted log, with no proof of whether
// the file already contains it. Recover it visibly without replaying it.
for (const edit of Array.isArray(stored.submitted) ? stored.submitted : []) {
if (!acceptedEdits.has(edit.id) && !acknowledgedEdits.has(edit.id)) edits.push({ ...edit, stale: true, unverified: true });
}
let deliveryRequest = null;
function persistEdits() { writeStore({ edits, submittedBatches: submitted, submitted: [] }); }
persistEdits();
// --- theme --------------------------------------------------------------------
const themeKey = 'ecc-plan-canvas:theme';
@@ -220,7 +229,8 @@ function uiClientJs() {
return new Promise((resolve, reject) => {
const requestId = 'x' + (++exportSeq);
exportWaiters.set(requestId, resolve);
postToFrame({ type: 'uc:export', requestId });
deliveryRequest = requestId;
postToFrame({ type: 'uc:export', requestId, lock: true });
setTimeout(() => {
if (exportWaiters.delete(requestId)) reject(new Error('the preview did not answer; reload and try again'));
}, 5000);
@@ -234,7 +244,7 @@ function uiClientJs() {
case 'uc:ready':
frameReady = true;
postToFrame({ type: 'uc:set-mode', mode });
postToFrame({ type: 'uc:restore', baked: submitted, edits, scroll: lastScroll, selection: selection ? selection.selector : null });
postToFrame({ type: 'uc:restore', baked: submitted.flatMap(batch => batch.edits), batches: submitted, edits, deliveryRequest, scroll: lastScroll, selection: selection ? selection.selector : null, selectionRevision: selection ? selection.sourceRevision : null });
if (paused) postToFrame({ type: 'uc:pause-animations', paused: true });
break;
case 'uc:selection':
@@ -283,10 +293,13 @@ ${inspectorClientJs()}
const list = $('editList');
list.innerHTML = '';
$('editCount').textContent = String(edits.length);
$('undoBtn').disabled = ended || !canUndo;
$('redoBtn').disabled = ended || !canRedo;
$('applyBtn').disabled = ended || !edits.some(e => !e.stale);
$('resetBtn').disabled = ended || !edits.length;
$('undoBtn').disabled = ended || sending || !canUndo;
$('redoBtn').disabled = ended || sending || !canRedo;
const unresolved = edits.some(edit => edit.submitted && edit.stale);
if (unresolved && !sending) statusEl.textContent = 'Some applied changes no longer match the file. Ask the agent to resolve them before applying more.';
$('finishBtn').disabled = ended || sending || unresolved;
$('applyBtn').disabled = ended || sending || unresolved || !edits.some(e => !e.stale);
$('resetBtn').disabled = ended || sending || !edits.length;
if (!edits.length) {
const empty = document.createElement('div');
empty.className = 'empty';
@@ -446,6 +459,10 @@ ${inspectorClientJs()}
async function sendEdits(kind) {
if (ended || sending) return;
if (edits.some(edit => edit.submitted && edit.stale)) {
statusEl.textContent = 'Some applied changes no longer match the file. Ask the agent to resolve them before applying more.';
return;
}
sending = true;
sendBtn.disabled = true;
$('applyBtn').disabled = true;
@@ -453,7 +470,7 @@ ${inspectorClientJs()}
statusEl.textContent = kind === 'finish' ? 'Saving the final design…' : 'Capturing the preview…';
try {
const snapshot = await requestExport();
const item = { kind, edits: snapshot.edits || edits, html: snapshot.html, viewport: { preset: vp.preset, width: actual.width, height: actual.height } };
const item = { kind, edits: (snapshot.edits || edits).filter(edit => !edit.submitted), bakedEditIds: snapshot.bakedEditIds || [], html: snapshot.html, viewport: { preset: vp.preset, width: actual.width, height: actual.height } };
const note = input.value.trim();
if (note) item.text = note;
const body = await postFeedback([item], kind === 'finish');
@@ -461,10 +478,12 @@ ${inspectorClientJs()}
if (kind === 'finish') {
markEnded('finished');
} else {
postToFrame({ type: 'uc:forget' });
submitted = submitted.concat((snapshot.edits || edits).filter(e => !e.stale));
edits = [];
writeStore({ edits: [], submitted });
const ids = (snapshot.edits || []).filter(edit => !edit.stale).map(edit => edit.id);
submitted = submitted.concat((body.batches || []).filter(batch => !acknowledged.has(batch.id)));
edits = edits.filter(edit => !ids.includes(edit.id));
persistEdits();
postToFrame({ type: 'uc:delivery-end', requestId: deliveryRequest, accepted: true, editIds: ids });
deliveryRequest = null;
renderEdits();
statusEl.textContent = describeDelivery(body) + ' The preview updates when it writes the file.';
if (body.presence) applyPresence(body.presence, agent);
@@ -472,6 +491,10 @@ ${inspectorClientJs()}
} catch (err) {
statusEl.textContent = (kind === 'finish' ? 'Save failed (' : 'Apply failed (') + err.message + ').';
} finally {
if (deliveryRequest) {
postToFrame({ type: 'uc:delivery-end', requestId: deliveryRequest, accepted: false, editIds: [] });
deliveryRequest = null;
}
sending = false;
sendBtn.disabled = ended;
$('finishBtn').disabled = ended;
@@ -537,13 +560,21 @@ ${inspectorClientJs()}
const es = new EventSource('/events/' + key);
es.addEventListener('chat-sync', e => renderChat(JSON.parse(e.data).chat || []));
es.addEventListener('presence', e => { const data = JSON.parse(e.data); applyPresence(data.state, data.agent); });
// The file changed on disk: the agent has written the applied edits in,
// so they must not replay on top of the new markup.
es.addEventListener('reload', () => {
submitted = [];
writeStore({ submitted: [] });
reloadArtifact();
es.addEventListener('ui-ack', e => {
const data = JSON.parse(e.data);
const batches = data.batches || [];
const ids = new Set(batches.map(batch => batch.id));
const editIds = new Set(batches.flatMap(batch => batch.editIds));
batches.forEach(batch => acknowledged.add(batch.id));
const changed = submitted.some(batch => ids.has(batch.id)) || edits.some(edit => editIds.has(edit.id));
submitted = submitted.filter(batch => !ids.has(batch.id));
edits = edits.filter(edit => !editIds.has(edit.id));
persistEdits();
renderEdits();
if (changed && frameReady) reloadArtifact();
});
// An unrelated agent save is not acknowledgment of queued Apply batches.
es.addEventListener('reload', reloadArtifact);
es.addEventListener('ended', e => { markEnded(JSON.parse(e.data).endedBy); es.close(); });
es.onerror = () => {
if (ended) return;
@@ -582,6 +613,8 @@ function renderUiCanvasHtml(session, { clientPath = '/ui-client.js', cssPath = '
chat: session.chat,
agent: session.agent || null,
ui: session.ui || { viewport: 'desktop', title: '' },
uiBatches: session.uiBatches || [],
uiAcknowledged: session.uiAcknowledged || [],
presets: VIEWPORT_PRESETS
}).replace(/</g, '\\u003c');
const artifactSrc = `/artifact/${session.key}/`;
+7 -2
View File
@@ -304,13 +304,18 @@ async function cmdAwait(file, args, { stateDir, port }, profile = PLAN_PROFILE)
throw new Error('await --session-key requires a 12-character lowercase hexadecimal key');
}
if (!file && !requestedKey) throw new Error('await requires a file path');
const ack = valueAfter(args, '--ack');
const acknowledge = ack ? ack.split(',') : null;
if (args.includes('--ack') && (profile.mode !== 'ui' || !acknowledge || acknowledge.length > 50
|| acknowledge.some(id => !/^fb-[1-9][0-9]{0,15}$/.test(id)))) throw new Error('await --ack requires comma-separated UI batch IDs');
if (!(await healthCheck(port))) {
return { status: 'no-server', hint: 'no canvas server is running; use `open` first', stateDir };
}
const reply = valueAfter(args, '--reply');
const key = requestedKey || sessionKeyFor(canonicalizeArtifactPath(file));
if (reply) {
await request(port, 'POST', `/api/session/${key}/reply`, { text: reply });
if (reply || acknowledge) {
const sent = await request(port, 'POST', `/api/session/${key}/reply`, { ...(reply ? { text: reply } : {}), ...(acknowledge ? { acknowledge } : {}) });
if (sent.statusCode !== 200) throw new Error(sent.body.error || 'could not send reply');
}
const timeoutRaw = valueAfter(args, '--timeout-ms');
const timeoutMs = timeoutRaw === null ? null : Number.parseInt(timeoutRaw, 10) || 0;
+4 -2
View File
@@ -42,6 +42,7 @@ function usage() {
' --reopen Reopen a session the user ended from the browser',
' await: --session-key <key> Resume by an opaque session key instead of a file path',
' --reply <msg> Show an agent reply in the canvas chat before waiting',
' --ack <fb-id[,fb-id]> Confirm specific Apply batches are incorporated into the file',
' --timeout-ms <n> Return {status:"waiting"} after n ms (tests/debug only)',
' typing: --state <thinking|typing|idle> Defaults to typing',
' server: --port <n> --host <h>',
@@ -76,12 +77,13 @@ const UI_PROFILE = {
feedback(result) {
const items = Array.isArray(result.items) ? result.items : [];
const finish = items.find(item => item.kind === 'finish');
const applied = items.find(item => item.kind === 'edits');
const appliedItems = items.filter(item => item.kind === 'edits');
const applied = appliedItems[appliedItems.length - 1];
if (finish) {
return `The human clicked Save and Finish. Read the final markup at ${finish.exportPath} (edit log: ${finish.editsPath}), reproduce that exact look in the real component with full functionality, and report in chat. Do not reopen the canvas.`;
}
if (applied) {
return `The human applied ${applied.editCount} edit(s) to the preview. Rewrite the mockup file from ${applied.exportPath} (keep it self-contained), then run \`ecc-ui-canvas await <file> --reply "<what you changed>"\` to keep listening.`;
return `The human applied ${applied.editCount} edit(s) to the preview. Rewrite the mockup file from ${applied.exportPath} (keep it self-contained), then run \`ecc-ui-canvas await <file> --ack ${appliedItems.map(item => item.id).join(',')} --reply "<what you changed>"\` only after those batches are incorporated, to keep listening.`;
}
if (result.sessionEnded) {
return 'The human sent this and ended the preview. Address it and report in chat; do not reopen the canvas uninvited.';
+10 -3
View File
@@ -104,7 +104,7 @@ listening" so the human knows you are connected.
request to repaint is the target for a one-property change.
```json
{ "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ],
{ "id": "fb-123", "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ],
"viewport": { "preset": "mobile", "width": 393, "height": 852 },
"exportPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edits.json" }
```
@@ -115,14 +115,21 @@ listening" so the human knows you are connected.
their inline-style changes), tidy it into real CSS if it is messy, keep it
self-contained, and reply. Each Apply writes its own
`<name>.apply-<batch>.*` pair, so a queued earlier batch keeps its own
snapshot. The canvas keeps showing the applied edits until your write to
the mockup reloads it, then drops them, so nothing is applied twice.
snapshot. The canvas keeps showing submitted edits until it recognizes the
exact exported snapshot or you explicitly acknowledge the incorporated batch.
After incorporating a batch, acknowledge its feedback ID with
`ecc-ui-canvas await <file> --ack fb-123 --reply "Applied the requested changes."`.
Multiple IDs may be comma-separated. Do not acknowledge a queued batch while
answering an earlier chat. Exact copies of exported snapshots are recognized
automatically; an unrelated file save is not acknowledgment. If a submitted
batch no longer matches the file, resolve it before applying more changes.
```json
{ "kind": "finish", "editCount": 5, "edits": [ "…" ], "viewport": { "preset": "desktop", "width": 1412, "height": 806 },
"exportPath": "…/pricing-card.edited.html", "editsPath": "…/pricing-card.edits.json" }
```
- `finish` means the human clicked **Save and Finish**. The session is over
(`sessionEnded: true`). Read `exportPath`, diff it against your original
mockup, read `editsPath` for the intent behind each change, and reproduce
+184
View File
@@ -0,0 +1,184 @@
'use strict';
const assert = require('node:assert/strict');
const vm = require('node:vm');
const { uiClientJs } = require('../../scripts/lib/ui-canvas/ui');
const { uiEditorJs } = require('../../scripts/lib/ui-canvas/editor');
const { editorGesturesJs } = require('../../scripts/lib/ui-canvas/editor-gestures');
let passed = 0;
let failed = 0;
const tick = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };
async function test(name, run) {
try { await run(); passed++; console.log(`PASS ${name}`); }
catch (error) { failed++; console.log(`FAIL ${name}: ${error.stack}`); }
}
function element() {
const handlers = {};
return {
handlers, value: '', textContent: '', innerHTML: '', style: {}, disabled: false,
classList: { add() {}, remove() {}, toggle() {} },
addEventListener(type, run) { handlers[type] = run; },
setAttribute() {}, removeAttribute() {}, getAttribute() { return '/artifact/test/'; },
append() {}, appendChild() {}, querySelector: () => element(),
getBoundingClientRect: () => ({ width: 1200, height: 900 }),
};
}
function client({ boot = {}, stored = {} } = {}) {
const nodes = new Map();
const node = id => { if (!nodes.has(id)) nodes.set(id, element()); return nodes.get(id); };
node('uc-session').textContent = JSON.stringify({ key: 'abcdefabcdef', status: 'open', chat: [], presets: { desktop: { width: 1200, height: 900 } }, ...boot });
const packets = [];
const frame = { postMessage: packet => packets.push(packet) };
node('artifact').contentWindow = frame;
let saved = stored;
let message;
let events;
let answer;
const context = {
document: { addEventListener() {}, getElementById: node, querySelectorAll: () => [], createElement: element, documentElement: element(), activeElement: null },
window: { addEventListener(type, run) { if (type === 'message') message = run; } },
sessionStorage: { getItem: () => JSON.stringify(saved), setItem: (_key, value) => { saved = JSON.parse(value); } },
localStorage: { getItem: () => null, setItem() {} },
setTimeout: () => 1, clearTimeout() {},
EventSource: class { constructor() { events = {}; } addEventListener(type, run) { events[type] = run; } },
fetch: () => new Promise(resolve => { answer = resolve; }),
};
vm.runInNewContext(uiClientJs(), context);
return {
node, packets, saved: () => saved,
message: data => message({ source: frame, data }),
event: (name, data = {}) => events[name]({ data: JSON.stringify(data) }),
answer: body => answer({ ok: true, json: async () => body }),
fail: () => answer({ ok: false, status: 500, json: async () => ({ error: 'controlled failure' }) }),
};
}
const first = { id: 'e1', kind: 'nudge', selector: '#a', dx: 1, dy: 0 };
const later = { id: 'e2', kind: 'nudge', selector: '#a', dx: 1, dy: 0 };
async function capture(harness) {
harness.message({ type: 'uc:edits', edits: [first], canUndo: true });
harness.node('applyBtn').handlers.click();
const packet = harness.packets.find(item => item.type === 'uc:export');
harness.message({ type: 'uc:export', requestId: packet.requestId, edits: [first], html: '<html></html>' });
await tick();
return packet;
}
async function main() {
await test('delayed Apply removes only captured edits and preserves later undoable work', async () => {
const h = client();
const packet = await capture(h);
assert.equal(packet.lock, true);
h.message({ type: 'uc:edits', edits: [first, later], canUndo: true });
h.answer({ batches: [{ id: 'fb-1', edits: [first] }] });
await tick();
assert.deepEqual(h.saved().edits, [later]);
assert.deepEqual(h.saved().submittedBatches.map(batch => batch.id), ['fb-1']);
const completed = h.packets.find(item => item.type === 'uc:delivery-end');
assert.equal(completed.accepted, true);
assert.deepEqual(Array.from(completed.editIds), ['e1']);
});
await test('unrelated reload retains submitted batches; explicit ack clears only known batch', () => {
const h = client({ boot: { uiBatches: [{ id: 'fb-1', edits: [first] }, { id: 'fb-2', edits: [later] }] } });
h.event('reload'); h.message({ type: 'uc:ready' });
assert.deepEqual(h.saved().submittedBatches.map(batch => batch.id), ['fb-1', 'fb-2']);
const restored = h.packets.filter(packet => packet.type === 'uc:restore').pop();
assert.deepEqual(Array.from(restored.baked, edit => edit.id), ['e1', 'e2']);
h.event('ui-ack', { batches: [{ id: 'fb-1', editIds: ['e1'] }] });
assert.deepEqual(h.saved().submittedBatches.map(batch => batch.id), ['fb-2']);
});
await test('ack arriving before delayed Apply response does not resurrect submitted edits', async () => {
const h = client(); await capture(h);
h.message({ type: 'uc:edits', edits: [first, later], canUndo: true });
h.event('ui-ack', { batches: [{ id: 'fb-1', editIds: ['e1'] }] });
h.answer({ batches: [{ id: 'fb-1', edits: [first] }] }); await tick();
assert.deepEqual(h.saved().edits, [later]);
assert.deepEqual(h.saved().submittedBatches, []);
});
await test('failed Apply retains all edits and releases the snapshot lock', async () => {
const h = client(); await capture(h);
h.message({ type: 'uc:edits', edits: [first, later], canUndo: true });
h.fail(); await tick();
assert.deepEqual(h.saved().edits, [first, later]);
assert.equal(h.packets.find(packet => packet.type === 'uc:delivery-end').accepted, false);
});
await test('snapshot boundary prevents rapid nudge, style and resize coalescing', () => {
const source = editorGesturesJs();
const start = source.indexOf(' function nudgeBy(');
const end = source.indexOf('\n function removeSelected', start);
const selected = { style: { left: '1px', top: '0px' } };
const edits = [{ kind: 'nudge', _el: selected, _exported: true, dx: 1, dy: 0, at: new Date().toISOString() }];
const context = { selected, edits, px: parseFloat, applyInline: (el, values) => Object.assign(el.style, values), captureInline: () => ({}), getComputedStyle: () => ({ position: 'relative' }), newEdit: (kind, _el, detail) => ({ kind, ...detail }), record: edit => edits.push(edit), postEdits() {}, scheduleBoxes() {} };
vm.runInNewContext(source.slice(start, end) + '\nnudgeBy(1,0);', context);
assert.equal(edits.length, 2); assert.equal(edits[0].dx, 1); assert.equal(edits[1].dx, 1);
assert.equal((source.match(/last && !last\._exported/g) || []).length, 3);
});
await test('forward reorder A after B uses the post-removal index', () => {
const source = editorGesturesJs(); const start = source.indexOf(' function endDrag('); const end = source.indexOf('\n function nudgeBy', start);
const a = { id: 'a', style: {}, getAttribute: () => '', removeAttribute() {} }; const b = { id: 'b' }; const c = { id: 'c' }; const parent = { children: [a, b, c] };
const recorded = [];
vm.runInNewContext(source.slice(start, end) + '\nendDrag(g);', {
g: { kind: 'move', el: a, fromParent: parent, fromIndex: 0, plan: { container: parent, index: 1 } },
document: { documentElement: { removeAttribute() {} } }, post() {}, selBox: { classList: { remove() {} } }, ghostEl: { style: {} }, dropEl: { style: {} },
selectorFor: el => el.id || '#cards', insertAt: (container, el, index) => { container.children = container.children.filter(child => child !== el); container.children.splice(index, 0, el); }, indexIn: (container, el) => container.children.indexOf(el),
newEdit: (kind, _el, detail) => ({ kind, ...detail }), record: edit => recorded.push(edit), toast() {}, labelFor: () => 'a',
});
assert.deepEqual(parent.children.map(child => child.id), ['b', 'a', 'c']); assert.equal(recorded.length, 1);
});
await test('delivery acknowledgment preserves later editor edits and refreshes inspector selection', () => {
const source = uiEditorJs(); const start = source.indexOf("window.addEventListener('message', function (e) {"); const end = source.indexOf('\n });', start) + 6;
let listener; let selectionUpdates = 0; const parent = {};
const context = { window: { parent, addEventListener: (_event, run) => { listener = run; } }, deliveryRequest: 'x1', bakedEditIds: [], edits: [{ id: 'e1' }, { id: 'e2' }], postEdits() {}, postSelection: () => selectionUpdates++ };
vm.runInNewContext(source.slice(start, end), context);
listener({ source: parent, data: { type: 'uc:delivery-end', requestId: 'x1', accepted: true, editIds: ['e1'] } });
assert.deepEqual(context.edits.map(edit => edit.id), ['e2']); assert.equal(selectionUpdates, 1); assert.equal(context.deliveryRequest, null);
});
await test('partially replayable submitted batch rolls back represented nudge and survives Reset', () => {
const source = uiEditorJs();
const section = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
const style = { left: '1px', top: '0px', position: 'relative', getPropertyValue(name) { return this[name] || ''; }, setProperty(name, value) { this[name] = value; }, removeProperty(name) { delete this[name]; } };
const target = { style, isConnected: true };
const context = {
edits: [], bakedEditIds: [], editSeq: 0, redoStack: [], deliveryRequest: null,
resolve: selector => selector === '#a' ? target : null, resolveForEdit: selector => selector === '#a' ? target : null,
px: value => Number.parseFloat(value) || 0, getComputedStyle: () => ({ position: 'relative' }),
copyEdit: edit => ({ ...edit }), postEdits() {}, postSelection() {}, updateBoxes() {}, scheduleBoxes() {}, toast() {},
};
vm.createContext(context);
vm.runInContext(section(' function applyInline(', ' function contentBoxDelta(')
+ section(' function applyEdit(', ' function undo(')
+ section(' function resetAll(', ' // After the agent')
+ section(' function restore(', ' // ---- text editing'), context);
context.restore({ batches: [{ edits: [first, { ...later, selector: '#missing' }] }], edits: [] });
assert.equal(style.left, '1px', 'A failed later target must roll back the already-represented nudge');
assert.deepEqual(Array.from(context.bakedEditIds), []);
assert.equal(context.edits.length, 2); assert.ok(context.edits.every(edit => edit.stale && edit.submitted));
context.edits.push({ id: 'unsent', kind: 'nudge', _el: target, _inlineBefore: { left: '1px' } }); style.left = '2px';
context.resetAll();
assert.equal(style.left, '1px');
assert.deepEqual(Array.from(context.edits, edit => edit.id), ['e1', 'e2']);
});
await test('unresolved submitted rows block Apply and Finish without dropping newer pending edits', () => {
const h = client(); const unresolved = { ...first, submitted: true, stale: true };
h.message({ type: 'uc:edits', edits: [unresolved, later], canUndo: true });
h.node('applyBtn').handlers.click(); h.node('finishBtn').handlers.click();
assert.equal(h.node('applyBtn').disabled, true); assert.equal(h.node('finishBtn').disabled, true);
assert.equal(h.packets.filter(packet => packet.type === 'uc:export').length, 0);
assert.deepEqual(h.saved().edits, [unresolved, later]);
assert.match(h.node('sendStatus').textContent, /resolve/);
});
await test('replay requires unique identity and original revision for positional targets', () => {
const source = uiEditorJs(); const start = source.indexOf(' function resolve('); const end = source.indexOf(' function snippetFor(', start);
const original = {}; const inserted = {}; let matches = [inserted];
const context = { sourceRevision: 'new-revision', isOurs: () => false, document: { querySelectorAll: () => matches } };
vm.runInNewContext(source.slice(start, end), context);
assert.equal(context.resolveForEdit('#cards > article:nth-of-type(1)', 'old-revision'), null, 'A shifted selector must not target the new sibling');
matches = [original];
assert.equal(context.resolveForEdit('#cards > article:nth-of-type(1)', 'new-revision'), original);
assert.equal(context.resolveForEdit('#stable', 'old-revision'), original, 'Unique stable ID survives an unrelated save');
matches = [original, inserted];
assert.equal(context.resolveForEdit('#stable', 'old-revision'), null, 'Duplicate IDs are ambiguous');
});
console.log(`Passed: ${passed}\nFailed: ${failed}`); process.exitCode = failed ? 1 : 0;
}
main().catch(error => { console.error(error); process.exitCode = 1; });
+4 -3
View File
@@ -167,11 +167,12 @@ test('editor reports border-radius from real corner properties', () => {
assert.ok(editor.includes('cs.borderTopLeftRadius') && !editor.includes("sides(cs, 'border', '-radius')"));
});
test('applied edits keep replaying until the agent rewrites the file', () => {
test('applied batches replay until specific acknowledgment, not an unrelated reload', () => {
const client = uiClientJs();
const editor = uiEditorJs();
assert.ok(client.includes("type: 'uc:restore', baked: submitted, edits"), 'reloads replay submitted edits');
assert.ok(/addEventListener\('reload', \(\) => \{\s*submitted = \[\];/.test(client), 'a file change drops them');
assert.ok(client.includes("type: 'uc:restore', baked: submitted.flatMap(batch => batch.edits), batches: submitted, edits"), 'reloads replay submitted edits');
assert.ok(client.includes("es.addEventListener('reload', reloadArtifact)"));
assert.ok(client.includes("es.addEventListener('ui-ack'"));
assert.ok(editor.includes('var baked = Array.isArray(payload.baked) ? payload.baked : [];'));
});
+130
View File
@@ -0,0 +1,130 @@
'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 { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const { createSessionStore } = require('../../scripts/lib/plan-canvas/sessions');
const { createPlanCanvasServer } = require('../../scripts/lib/plan-canvas/server');
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 edit = id => ({ id, kind: 'nudge', selector: `#${id}`, dx: 1, dy: 0 });
async function fixture(run) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-ui-ack-'));
const file = path.join(directory, 'card.html');
fs.writeFileSync(file, '<html><body>original</body></html>');
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(method, suffix, body) {
return new Promise((resolve, reject) => {
const payload = body ? JSON.stringify(body) : null;
const req = http.request({ host: '127.0.0.1', port, method, path: suffix.startsWith('/') ? suffix : `/api/session/${session.key}/${suffix}`, headers: payload ? { 'content-type': 'application/json' } : {} }, response => {
let text = ''; response.on('data', chunk => { text += chunk; });
response.on('end', () => { let body; try { body = JSON.parse(text); } catch { body = text; } resolve({ status: response.statusCode, body }); });
});
req.on('error', reject); if (payload) req.end(payload); else req.end();
});
}
async function apply(edits, html, bakedEditIds = []) {
const response = await request('POST', 'feedback', { items: [{ kind: 'edits', edits, html, bakedEditIds }] });
assert.equal(response.status, 200); return response.body.batches[0].id;
}
try { await run({ store, session, file, directory, port, request, apply }); }
finally { await server.close(); fs.rmSync(directory, { recursive: true, force: true }); }
}
async function main() {
await test('taking feedback and unrelated saves do not acknowledge queued Apply batches', () => fixture(async ({ store, session, file, request, apply }) => {
const id = await apply([edit('a')], '<html><body>applied</body></html>');
store.takeFeedback(session.key);
fs.writeFileSync(file, '<html><body>earlier chat save</body></html>');
await request('GET', `/artifact/${session.key}/`);
assert.deepEqual(session.uiBatches.map(batch => batch.id), [id]);
}));
await test('exact snapshot acknowledges its batch and only verified included older batches', () => fixture(async ({ session, file, request, apply }) => {
const older = await apply([edit('a'), edit('missing')], '<html><body>first snapshot</body></html>');
const newer = await apply([edit('b')], '<html><body>partial older snapshot</body></html>', ['a']);
fs.writeFileSync(file, '<html><body>partial older snapshot</body></html>');
await request('GET', `/artifact/${session.key}/`);
assert.deepEqual(session.uiBatches.map(batch => batch.id), [older]);
assert.deepEqual(session.uiAcknowledged.map(batch => batch.id), [newer]);
const all = await apply([edit('c')], '<html><body>all represented</body></html>', ['a', 'missing']);
fs.writeFileSync(file, '<html><body>all represented</body></html>');
await request('GET', `/artifact/${session.key}/`);
assert.deepEqual(session.uiBatches, []);
assert.deepEqual(session.uiAcknowledged.map(batch => batch.id).sort(), [newer, all, older].sort());
}));
await test('specific acknowledgment is durable and clears only named known batches', () => fixture(async ({ session, directory, request, apply }) => {
const first = await apply([edit('a')], '<html>one</html>'); const second = await apply([edit('b')], '<html>two</html>');
const response = await request('POST', 'reply', { acknowledge: [first], text: 'Applied first only' });
assert.equal(response.status, 200);
const reopened = createSessionStore({ stateDir: path.join(directory, 'state') }).get(session.key);
assert.deepEqual(reopened.uiBatches.map(batch => batch.id), [second]);
assert.deepEqual(reopened.uiAcknowledged.map(batch => batch.id), [first]);
assert.equal((await request('POST', 'reply', { acknowledge: [first] })).status, 200, 'acknowledgment is idempotent');
assert.equal((await request('POST', 'reply', { text: 'Legacy reply remains valid' })).status, 200);
}));
await test('invalid reply fields or mixed unknown IDs have no partial side effects', () => fixture(async ({ session, request, apply }) => {
const id = await apply([edit('a')], '<html>one</html>');
const count = session.chat.length;
for (const acknowledge of [null, [], 'fb-1', ['fb-0'], [1], [id, 'fb-999999']]) {
assert.equal((await request('POST', 'reply', { acknowledge, text: 'must not publish' })).status, 400);
assert.deepEqual(session.uiBatches.map(batch => batch.id), [id]); assert.equal(session.chat.length, count);
}
for (const text of [3, null, '', ' ']) {
assert.equal((await request('POST', 'reply', { acknowledge: [id], text })).status, 400);
assert.deepEqual(session.uiBatches.map(batch => batch.id), [id]);
}
}));
await test('state write failure rolls back acknowledgment and its accompanying reply together', () => fixture(async ({ session, directory, request, apply }) => {
const id = await apply([edit('a')], '<html>one</html>'); const count = session.chat.length;
fs.mkdirSync(path.join(directory, 'state', 'sessions.json.tmp'));
const response = await request('POST', 'reply', { acknowledge: [id], text: 'must not partially publish' });
assert.equal(response.status, 500); assert.equal(session.chat.length, count);
assert.deepEqual(session.uiBatches.map(batch => batch.id), [id]);
const reopened = createSessionStore({ stateDir: path.join(directory, 'state') }).get(session.key);
assert.deepEqual(reopened.uiBatches.map(batch => batch.id), [id]); assert.equal(reopened.chat.length, count);
}));
await test('oversized or malformed proof fails before writing an export or queuing anything', () => fixture(async ({ session, directory, request }) => {
const before = fs.readdirSync(directory).sort();
for (const bakedEditIds of [Array(5001).fill('e1'), ['x'.repeat(41)], [3], 'e1']) {
const response = await request('POST', 'feedback', { items: [{ kind: 'edits', edits: [edit('a')], html: '<html>snapshot</html>', bakedEditIds }] });
assert.equal(response.status, 413); assert.equal(session.pendingFeedback.length, 0);
assert.deepEqual(fs.readdirSync(directory).sort(), before);
}
const response = await request('POST', 'feedback', { items: [{ kind: 'edits', edits: Array(501).fill(edit('a')), html: '<html>snapshot</html>' }] });
assert.equal(response.status, 413); assert.deepEqual(fs.readdirSync(directory).sort(), before);
const mixed = await request('POST', 'feedback', { items: [
{ kind: 'edits', edits: [edit('a')], html: '<html>valid first item</html>' },
{ kind: 'edits', edits: [edit('b')], html: '<html>invalid later item</html>', bakedEditIds: Array(5001).fill('e1') },
] });
assert.equal(mixed.status, 413); assert.deepEqual(fs.readdirSync(directory).sort(), before);
}));
await test('actual CLI preserves file/key awaits and plain replies while validating acknowledgments', () => fixture(async ({ session, store, file, directory, port, apply }) => {
const first = await apply([edit('a')], '<html>one</html>'); const second = await apply([edit('b')], '<html>two</html>');
store.takeFeedback(session.key);
const cli = (...args) => promisify(execFile)(process.execPath, [path.join(__dirname, '../../scripts/ui-canvas.js'), ...args], {
env: { ...process.env, ECC_PLAN_CANVAS_PORT: String(port), ECC_PLAN_CANVAS_STATE_DIR: path.join(directory, 'state') }, timeout: 5000,
});
await cli('await', file, '--ack', first, '--reply', 'First incorporated', '--timeout-ms', '1');
assert.deepEqual(session.uiBatches.map(batch => batch.id), [second]);
await cli('await', '--session-key', session.key, '--ack', second, '--timeout-ms', '1');
assert.deepEqual(session.uiBatches, []);
await cli('await', file, '--reply', 'Old reply without ack', '--timeout-ms', '1');
assert.equal(session.chat.at(-1).text, 'Old reply without ack');
await assert.rejects(cli('await', file, '--ack', 'fb-0'), error => { assert.match(error.stdout, /requires comma-separated UI batch IDs/); return true; });
await assert.rejects(cli('await', file, '--ack', 'fb-999999'), error => { assert.match(error.stdout, /unknown UI batch ID/); return true; });
}));
console.log(`Passed: ${passed}\nFailed: ${failed}`); process.exitCode = failed ? 1 : 0;
}
main().catch(error => { console.error(error); process.exitCode = 1; });
+3 -1
View File
@@ -10,6 +10,7 @@
const assert = require('assert');
const fs = require('fs');
const crypto = require('crypto');
const http = require('http');
const os = require('os');
const path = require('path');
@@ -122,7 +123,8 @@ async function main() {
await test('GET /artifact/:key/ injects the editor instead of the annotation sdk and keeps the sandbox CSP', async () => {
const res = await request(port, 'GET', `/artifact/${key}/`, null, { raw: true });
assert.strictEqual(res.statusCode, 200);
assert.ok(res.body.includes('<script src="/ui-editor.js" data-ecc-ui-canvas="editor"></script>'));
const revision = crypto.createHash('sha256').update(fs.readFileSync(artifact)).digest('hex');
assert.ok(res.body.includes(`<script src="/ui-editor.js" data-ecc-ui-canvas="editor" data-source-sha256="${revision}"></script>`));
assert.ok(!res.body.includes('/sdk.js'));
assert.strictEqual(res.headers['content-security-policy'], 'sandbox allow-scripts allow-forms allow-popups');
});