diff --git a/docs/design/ui-canvas.md b/docs/design/ui-canvas.md index 7aa209bc2..bfcb7ef51 100644 --- a/docs/design/ui-canvas.md +++ b/docs/design/ui-canvas.md @@ -137,3 +137,11 @@ 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. + +Apply and Finish preserve an immutable pending delivery in browser session storage +before posting it. Session-scoped delivery tokens bind the exact payload: a lost +response may be retried without duplicating a batch or overwriting its export, +and a changed payload cannot reuse the token. Only authoritative accepted edit +IDs are retired, so later edits and draft text remain pending. Unknown outcomes +retain the captured undo/coalescing barrier until confirmed; an uncertain Finish +stays read-only. Chat remains outside this delivery-deduplication contract. diff --git a/scripts/lib/plan-canvas/server.js b/scripts/lib/plan-canvas/server.js index 610d0c14f..7aa771f75 100644 --- a/scripts/lib/plan-canvas/server.js +++ b/scripts/lib/plan-canvas/server.js @@ -25,6 +25,7 @@ const { renderMarkdownArtifactHtml, renderSessionListHtml } = require('./ui'); +const { deliveryFingerprint } = require('../ui-canvas/delivery'); const { agentFromParam } = require('./agent-identity'); const { exportErrorResponse, materializeUiExports, renderUiCanvasHtml, serveUiAsset } = require('../ui-canvas/server-routes'); @@ -363,6 +364,14 @@ function createPlanCanvasServer({ // --- artifact watching -------------------------------------------------- + function deliveryResponse(session, receipt, pending) { + const active = new Set(receipt.itemIds); + return { status: 'queued', accepted: receipt.itemIds.length, pending, + acceptedEditIds: receipt.editIds, acceptedText: receipt.text || '', + batches: (session.uiBatches || []).filter(batch => active.has(batch.id)), + presence: presenceFor(session.key), sessionEnded: session.status === 'ended' }; + } + 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 }); @@ -480,7 +489,9 @@ function createPlanCanvasServer({ const timeoutRaw = url.searchParams.get('timeoutMs'); const timeoutMs = timeoutRaw === null ? null : Math.max(0, Number.parseInt(timeoutRaw, 10) || 0); - const first = store.takeFeedback(key); + let first; + try { first = store.takeFeedback(key); } + catch { return sendJson(res, 500, { error: 'could not persist feedback delivery; re-run await' }); } if (first.status !== 'waiting') { if (first.status === 'feedback') markThinking(key); broadcastPresence(key); @@ -508,8 +519,8 @@ function createPlanCanvasServer({ noteConnectionClosed(); }; const onWake = () => { - const result = store.takeFeedback(key); - if (result.status !== 'waiting') finish(result); + try { const result = store.takeFeedback(key); if (result.status !== 'waiting') finish(result); } + catch { finish({ status: 'waiting', note: 'feedback remains queued; re-run await after storage recovers' }); } }; // Settle held polls on shutdown so server.close() can complete; the // CLI tells agents to simply re-run await. @@ -559,6 +570,20 @@ function createPlanCanvasServer({ if (action === 'feedback') { const body = await readJsonBody(req); let items = Array.isArray(body.items) ? body.items : []; + const deliveryId = body.deliveryId; + let fingerprint = null; + if (deliveryId !== undefined) { + if (session.mode !== 'ui' || typeof deliveryId !== 'string' || !/^[a-f0-9]{32}$/.test(deliveryId) + || (body.endSession !== undefined && typeof body.endSession !== 'boolean') + || items.length !== 1 || !['edits', 'finish'].includes(items[0] && items[0].kind) + || Boolean(body.endSession) !== (items[0].kind === 'finish')) return sendJson(res, 400, { error: 'invalid UI delivery token or payload' }); + fingerprint = deliveryFingerprint(items, body.endSession); + const receipt = session.uiDeliveries && session.uiDeliveries[deliveryId]; + if (receipt) { + if (receipt.fingerprint !== fingerprint) return sendJson(res, 409, { error: 'delivery token payload changed' }); + return sendJson(res, 200, deliveryResponse(session, receipt, session.pendingFeedback.length)); + } + } // Checked before any export is written: a stale tab must not replace // the design a finished session already handed over. if (session.status === 'ended') return sendJson(res, 409, { error: 'session already ended' }); @@ -570,21 +595,24 @@ function createPlanCanvasServer({ return sendJson(res, failure.status, { error: failure.error }); } } - const result = store.queueFeedback(key, items, { endSession: Boolean(body.endSession) }); + let result; + try { result = store.queueFeedback(key, items, { endSession: Boolean(body.endSession), deliveryId, fingerprint }); } + catch { return sendJson(res, 500, { error: 'could not persist feedback' }); } if (!result) return sendJson(res, 409, { error: 'session already ended' }); - wake.emit(`wake:${key}`); - broadcast(key, 'chat-sync', { chat: store.get(key).chat }); - if (body.endSession) broadcast(key, 'ended', { endedBy: 'user' }); - // A parked `await` takes the batch synchronously on the wake above, so - // presence is already `thinking` by now; with nobody listening it - // reports `queued`. Either way the browser must be told, which the - // original handler never did, leaving a stale pill on screen. - broadcastPresence(key); + // Acceptance is already durable. Notification failures must not turn + // a committed delivery into a rejection that invites a fresh token. + try { wake.emit(`wake:${key}`); } catch { /* accepted feedback remains discoverable */ } + try { + broadcast(key, 'chat-sync', { chat: store.get(key).chat }); + if (body.endSession) broadcast(key, 'ended', { endedBy: 'user', ...(deliveryId ? { deliveryId, finished: items[0].kind === 'finish' } : {}) }); + broadcastPresence(key); + } catch { /* accepted feedback remains discoverable */ } + if (deliveryId) return sendJson(res, 200, deliveryResponse(session, session.uiDeliveries[deliveryId], session.pendingFeedback.length)); return sendJson(res, 200, { 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) })), + pending: session.pendingFeedback.length, + batches: result.accepted.filter(item => item.kind === 'edits').map(item => ({ id: item.id, snapshotHash: item.snapshotHash, includedBatches: item.includedBatches || [], edits: item.edits.filter(edit => !edit.stale) })), presence: presenceFor(key) }); } @@ -687,7 +715,7 @@ function createPlanCanvasServer({ }); return sendHtml(res, 200, html, { csp: 'artifact' }); } - acknowledgeUiSnapshot(session, content); + try { acknowledgeUiSnapshot(session, content); } catch { /* readable snapshots remain available while acknowledgment persistence recovers */ } const sdkTag = session.mode === 'ui' ? `` : ''; diff --git a/scripts/lib/plan-canvas/sessions.js b/scripts/lib/plan-canvas/sessions.js index 8c35b2fdf..8c58a37ff 100644 --- a/scripts/lib/plan-canvas/sessions.js +++ b/scripts/lib/plan-canvas/sessions.js @@ -189,24 +189,29 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) { // Queue feedback from the browser. Chat-shaped items are mirrored into the // session transcript immediately so the conversation panel stays coherent // across reloads. - function queueFeedback(key, rawItems, { endSession = false } = {}) { + function queueFeedback(key, rawItems, { endSession = false, deliveryId = null, fingerprint = null } = {}) { const session = get(key); if (!session || session.status === 'ended') return null; const normalize = session.mode === 'ui' ? normalizeUiFeedbackItem : normalizeFeedbackItem; const describe = session.mode === 'ui' ? uiChatLineFor : chatLineFor; + const previous = { ...session }; + const previousCounter = state.feedbackCounter; + let counter = previousCounter; const accepted = []; for (const raw of Array.isArray(rawItems) ? rawItems : []) { - state.feedbackCounter += 1; - const item = normalize(raw, state.feedbackCounter); + counter += 1; + const item = normalize(raw, counter); if (item) accepted.push(item); } - session.pendingFeedback.push(...accepted); + state.feedbackCounter = counter; + session.pendingFeedback = [...session.pendingFeedback, ...accepted]; if (session.mode === 'ui') { - session.uiBatches = session.uiBatches || []; + 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) }); } } + session.chat = [...session.chat]; for (const item of accepted) { session.chat.push({ role: 'user', kind: item.kind, text: describe(item), at: item.at }); } @@ -216,8 +221,20 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) { } else if (accepted.length > 0) { session.status = 'feedback'; } + if (deliveryId) { + const item = accepted[0]; + session.uiDeliveries = { ...(session.uiDeliveries || {}), [deliveryId]: { + fingerprint, kind: item.kind, itemIds: accepted.map(entry => entry.id), + editIds: item.edits.filter(edit => !edit.stale).map(edit => edit.id), text: item.text + } }; + } session.updatedAt = nowIso(); - persist(); + try { persist(); } catch (error) { + for (const name of Object.keys(session)) if (!Object.hasOwn(previous, name)) delete session[name]; + Object.assign(session, previous); + state.feedbackCounter = previousCounter; + throw error; + } return { accepted, pending: session.pendingFeedback.length, session }; } @@ -246,6 +263,7 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) { const session = get(key); if (!session) return { status: 'missing' }; if (session.pendingFeedback.length > 0) { + const previous = { pendingFeedback: session.pendingFeedback, status: session.status, updatedAt: session.updatedAt }; const items = session.pendingFeedback; session.pendingFeedback = []; const result = { status: 'feedback', items }; @@ -256,7 +274,7 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) { session.status = 'open'; } session.updatedAt = nowIso(); - persist(); + try { persist(); } catch (error) { Object.assign(session, previous); throw error; } return result; } if (session.status === 'ended') { diff --git a/scripts/lib/ui-canvas/delivery.js b/scripts/lib/ui-canvas/delivery.js new file mode 100644 index 000000000..3c9d59b57 --- /dev/null +++ b/scripts/lib/ui-canvas/delivery.js @@ -0,0 +1,53 @@ +'use strict'; + +const crypto = require('crypto'); +const { stableStringify } = require('../context-profile-support'); + +function deliveryFingerprint(items, endSession) { + return crypto.createHash('sha256').update(stableStringify({ items, endSession: Boolean(endSession) })).digest('hex'); +} + +// A retry carries the original immutable snapshot, not a newer preview that +// happens to contain some of the same edit IDs. This is local UI transport +// state, separate from ECC execution evidence and canonical task state. +function deliveryClientJs() { + return String.raw` function validDelivery(value) { + return value && typeof value.id === 'string' && /^[a-f0-9]{32}$/.test(value.id) && ['edits', 'finish'].includes(value.kind) + && typeof value.snapshotHash === 'string' && /^[a-f0-9]{64}$/.test(value.snapshotHash) + && value.item && value.item.kind === value.kind && typeof value.item.html === 'string' && value.item.html.length <= 6 * 1024 * 1024 + && Array.isArray(value.item.edits) && value.item.edits.length <= 500; + } + let pendingDelivery = validDelivery(stored.pendingDelivery) ? stored.pendingDelivery : null; + if (pendingDelivery && boot.uiDeliveries && boot.uiDeliveries[pendingDelivery.id]) { + const accepted = new Set(boot.uiDeliveries[pendingDelivery.id].editIds || []); + edits = edits.filter(edit => !accepted.has(edit.id)); + pendingDelivery = null; + writeStore({ pendingDelivery: null, edits }); + } + if (pendingDelivery) deliveryRequest = 'retry-' + pendingDelivery.id; + async function prepareDelivery(kind, item, sourceRevision) { + if (pendingDelivery) { + if (pendingDelivery.kind !== kind) throw new Error('Retry the previous delivery before starting another one.'); + return pendingDelivery; + } + const id = crypto.randomUUID().replace(/-/g, ''); + let record; + try { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(item.html)); + const snapshotHash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''); + record = { id, kind, item, snapshotHash, sourceRevision }; + sessionStorage.setItem(STORE, JSON.stringify(Object.assign(readStore(), { pendingDelivery: record }))); + } catch (_error) { + throw Object.assign(new Error('Could not preserve a retryable snapshot in browser storage. Your changes remain in the preview.'), { definitive: true }); + } + pendingDelivery = record; + return record; + } + function clearDelivery() { + pendingDelivery = null; + writeStore({ pendingDelivery: null }); + } +`; +} + +module.exports = { deliveryClientJs, deliveryFingerprint }; diff --git a/scripts/lib/ui-canvas/editor.js b/scripts/lib/ui-canvas/editor.js index 123fbbf3e..32800ef45 100644 --- a/scripts/lib/ui-canvas/editor.js +++ b/scripts/lib/ui-canvas/editor.js @@ -412,7 +412,7 @@ function uiEditorJs() { } if (edit.kind === 'move') { var target = resolveForEdit(edit.to.parent, edit.sourceRevision); - if (!target) return false; + if (!target || target === el || el.contains(target)) return false; edit._fromParent = el.parentElement; edit._fromIndex = indexIn(el.parentElement, el); insertAt(target, el, edit.to.index); @@ -500,16 +500,21 @@ function uiEditorJs() { // 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 }]; + var represented = Object.create(null); + batches.forEach(function (batch) { + if (sourceRevision && batch.snapshotHash === sourceRevision) { represented[batch.id] = true; (batch.includedBatches || []).forEach(function (id) { represented[id] = true; }); } + }); 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++) { + for (var n = 0; !represented[batches[b].id] && n < batchEdits.length; n++) { var candidate = copyEdit(batchEdits[n]); - if (!applyEdit(candidate, null)) { failed = true; break; } + try { if (!applyEdit(candidate, null)) { failed = true; break; } } + catch (_error) { try { revertEdit(candidate); } catch (_rollbackError) { /* keep batch unresolved */ } failed = true; break; } applied.push(candidate); } if (failed) { - for (var r = applied.length - 1; r >= 0; r--) revertEdit(applied[r]); + for (var r = applied.length - 1; r >= 0; r--) { try { revertEdit(applied[r]); } catch (_rollbackError) { /* keep batch unresolved */ } } batchEdits.forEach(function (edit) { edits.push(Object.assign(copyEdit(edit), { stale: true, submitted: true })); }); } else { batchEdits.forEach(function (edit) { bakedEditIds.push(edit.id); }); @@ -523,7 +528,9 @@ function uiEditorJs() { if (incoming[i].submitted) continue; var edit = copyEdit(incoming[i]); delete edit.stale; - if (edit.unverified || !applyEdit(edit, null)) edit.stale = true; + var pending = deliveryRequest && (payload.pendingEditIds || []).indexOf(edit.id) >= 0; + var inSource = pending && sourceRevision && payload.pendingSnapshotHash === sourceRevision; + if (edit.unverified || (!inSource && ((pending && payload.pendingSourceRevision !== sourceRevision) || !applyEdit(edit, null)))) edit.stale = true; if (deliveryRequest) edit._exported = true; edits.push(edit); var seq = parseInt(String(edit.id).slice(1), 10); @@ -740,20 +747,22 @@ ${editorGesturesJs()} case 'uc:redo': redo(); break; case 'uc:reset': resetAll(); break; case 'uc:forget': + if (deliveryRequest) break; // 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; }); + edits = edits.filter(function (edit) { return edit.submitted || (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; }); + var captured = edits.filter(function (edit) { return msg.editIds.indexOf(edit.id) >= 0; }); + var proven = msg.editIds.every(function (id) { return bakedEditIds.indexOf(id) >= 0 || captured.some(function (edit) { return edit.id === id && !edit.stale; }); }); + if (proven) { bakedEditIds = bakedEditIds.concat(msg.editIds); edits = edits.filter(function (edit) { return msg.editIds.indexOf(edit.id) < 0; }); } + else captured.forEach(function (edit) { edit.stale = true; edit.submitted = true; }); } - deliveryRequest = null; - edits.forEach(function (edit) { delete edit._exported; }); + if (!msg.retryPending) { deliveryRequest = null; edits.forEach(function (edit) { delete edit._exported; }); } postEdits(); postSelection(); break; @@ -766,7 +775,7 @@ ${editorGesturesJs()} 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() }); + post({ type: 'uc:export', requestId: msg.requestId, html: exportHtml(), sourceRevision: sourceRevision, edits: edits.map(publicEdit), bakedEditIds: bakedEditIds.slice() }); break; case 'uc:scroll-to': window.scrollTo(msg.x || 0, msg.y || 0); break; default: break; diff --git a/scripts/lib/ui-canvas/ui.js b/scripts/lib/ui-canvas/ui.js index 27aec1d2a..c8d3fc9c6 100644 --- a/scripts/lib/ui-canvas/ui.js +++ b/scripts/lib/ui-canvas/ui.js @@ -19,6 +19,7 @@ const path = require('path'); const { escapeHtml } = require('../plan-canvas/markdown'); const { VIEWPORT_PRESETS } = require('./feedback'); +const { deliveryClientJs } = require('./delivery'); const { inspectorClientJs } = require('./inspector'); const { uiCanvasCss } = require('./ui-css'); @@ -100,6 +101,7 @@ function uiClientJs() { function persistEdits() { writeStore({ edits, submittedBatches: submitted, submitted: [] }); } persistEdits(); +${deliveryClientJs()} // --- theme -------------------------------------------------------------------- const themeKey = 'ecc-plan-canvas:theme'; function applyTheme(t) { @@ -247,7 +249,7 @@ function uiClientJs() { case 'uc:ready': frameReady = true; postToFrame({ type: 'uc:set-mode', mode: finishing ? 'interact' : mode }); - 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 }); + postToFrame({ type: 'uc:restore', baked: submitted.flatMap(batch => batch.edits), batches: submitted, edits, deliveryRequest, pendingSnapshotHash: pendingDelivery && pendingDelivery.snapshotHash, pendingSourceRevision: pendingDelivery && pendingDelivery.sourceRevision, pendingEditIds: pendingDelivery ? pendingDelivery.item.edits.map(edit => edit.id) : [], 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': @@ -257,7 +259,10 @@ function uiClientJs() { renderAnchor(); break; case 'uc:edits': - edits = Array.isArray(msg.edits) ? msg.edits : []; + { + const acceptedIds = new Set(submitted.flatMap(batch => batch.edits.map(edit => edit.id))); + edits = (Array.isArray(msg.edits) ? msg.edits : []).filter(edit => !acknowledgedEdits.has(edit.id) && (edit.submitted || !acceptedIds.has(edit.id))); + } canUndo = Boolean(msg.canUndo); canRedo = Boolean(msg.canRedo); writeStore({ edits }); @@ -296,13 +301,13 @@ ${inspectorClientJs()} const list = $('editList'); list.innerHTML = ''; $('editCount').textContent = String(edits.length); - $('undoBtn').disabled = ended || sending || !canUndo; - $('redoBtn').disabled = ended || sending || !canRedo; + $('undoBtn').disabled = ended || sending || Boolean(pendingDelivery) || !canUndo; + $('redoBtn').disabled = ended || sending || Boolean(pendingDelivery) || !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; + $('finishBtn').disabled = ended || sending || !frameReady || (!pendingDelivery && unresolved) || Boolean(pendingDelivery && pendingDelivery.kind === 'edits'); + $('applyBtn').disabled = ended || sending || finishing || !frameReady || (!pendingDelivery && (unresolved || !edits.some(e => !e.stale))); + $('resetBtn').disabled = ended || sending || Boolean(pendingDelivery) || !edits.length; if (!edits.length) { const empty = document.createElement('div'); empty.className = 'empty'; @@ -412,17 +417,17 @@ ${inspectorClientJs()} } $('anchorClear').addEventListener('click', () => { anchorEnabled = false; renderAnchor(); }); - async function postFeedback(items, endSession) { + async function postFeedback(items, endSession, deliveryId) { const res = await fetch('/api/session/' + key + '/feedback', { method: 'POST', headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ items, endSession: Boolean(endSession) }) + body: JSON.stringify({ items, endSession: Boolean(endSession), ...(deliveryId ? { deliveryId } : {}) }) }); if (!res.ok) { const body = await res.json().catch(() => ({})); - throw new Error(body.error || ('HTTP ' + res.status)); + throw Object.assign(new Error(body.error || ('HTTP ' + res.status)), { definitive: true }); } - return res.json().catch(() => ({})); + return res.json(); } function pendingSummaries() { return edits.filter(e => !e.stale).slice(-30).map(summarize); @@ -473,7 +478,9 @@ ${inspectorClientJs()} } async function sendEdits(kind) { if (ended || sending) return; - if (edits.some(edit => edit.submitted && edit.stale)) { + if (!frameReady) { statusEl.textContent = 'Wait for the preview to finish reloading, then try again.'; return; } + if (pendingDelivery && pendingDelivery.kind !== kind) { statusEl.textContent = 'Retry the previous delivery first.'; return; } + if (!pendingDelivery && 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; } @@ -485,33 +492,40 @@ ${inspectorClientJs()} $('finishBtn').disabled = true; statusEl.textContent = kind === 'finish' ? 'Saving the final design…' : 'Capturing the preview…'; try { - const snapshot = await requestExport(); - 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 snapshot = pendingDelivery ? null : await requestExport(); + const item = pendingDelivery ? pendingDelivery.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 = draft.trim(); - if (note) item.text = note; - const body = await postFeedback([item], kind === 'finish'); - if (input.value === draft) input.value = ''; + if (!pendingDelivery && note) item.text = note; + const delivery = await prepareDelivery(kind, item, snapshot && snapshot.sourceRevision); + const body = await postFeedback([delivery.item], kind === 'finish', delivery.id); + if (!Array.isArray(body.acceptedEditIds)) throw new Error('The delivery receipt was not readable; retry to confirm it.'); + clearDelivery(); + if (input.value === draft && draft.trim() === body.acceptedText) input.value = ''; if (kind === 'finish') { markEnded('finished'); } else { - const ids = (snapshot.edits || []).filter(edit => !edit.stale).map(edit => edit.id); + const ids = body.acceptedEditIds; 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; + reloadArtifact(); renderEdits(); statusEl.textContent = describeDelivery(body) + ' The preview updates when it writes the file.'; if (body.presence) applyPresence(body.presence, agent); } } catch (err) { - statusEl.textContent = (kind === 'finish' ? 'Save failed (' : 'Apply failed (') + err.message + ').'; + if (kind === 'finish' && ended && !pendingDelivery) statusEl.textContent = 'Saved and handed to ' + agentName() + '.'; + else { + if (err.definitive) clearDelivery(); + statusEl.textContent = (kind === 'finish' ? 'Save failed (' : 'Apply failed (') + err.message + ').' + (pendingDelivery ? ' Retry to confirm the saved snapshot.' : ''); + } } finally { if (deliveryRequest) { - postToFrame({ type: 'uc:delivery-end', requestId: deliveryRequest, accepted: false, editIds: [] }); - deliveryRequest = null; + postToFrame({ type: 'uc:delivery-end', requestId: deliveryRequest, accepted: false, retryPending: Boolean(pendingDelivery), editIds: [] }); + if (!pendingDelivery) deliveryRequest = null; } - if (kind === 'finish' && !ended) freezeForFinish(false); + if (kind === 'finish' && !ended && !pendingDelivery) freezeForFinish(false); sending = false; sendBtn.disabled = ended; $('finishBtn').disabled = ended; @@ -552,6 +566,7 @@ ${inspectorClientJs()} if (finished) setTimeout(() => { try { window.close(); } catch (_e) { /* not script-opened */ } }, 900); } if (ended) markEnded(boot.endedBy); + else if (pendingDelivery && pendingDelivery.kind === 'finish') freezeForFinish(true); // --- server events ---------------------------------------------------------------------- function presenceLabel(state) { @@ -582,6 +597,7 @@ ${inspectorClientJs()} const batches = data.batches || []; const ids = new Set(batches.map(batch => batch.id)); const editIds = new Set(batches.flatMap(batch => batch.editIds)); + editIds.forEach(id => acknowledgedEdits.add(id)); 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)); @@ -592,7 +608,12 @@ ${inspectorClientJs()} }); // 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.addEventListener('ended', e => { + const data = JSON.parse(e.data); + const ownFinish = data.finished && pendingDelivery && pendingDelivery.kind === 'finish' && data.deliveryId === pendingDelivery.id; + if (ownFinish) clearDelivery(); + markEnded(ownFinish ? 'finished' : data.endedBy); es.close(); + }); es.onerror = () => { if (ended) return; renderActivity('offline'); @@ -632,6 +653,7 @@ function renderUiCanvasHtml(session, { clientPath = '/ui-client.js', cssPath = ' ui: session.ui || { viewport: 'desktop', title: '' }, uiBatches: session.uiBatches || [], uiAcknowledged: session.uiAcknowledged || [], + uiDeliveries: session.uiDeliveries || {}, presets: VIEWPORT_PRESETS }).replace(/ !ackIds.includes(item.id)) ? ' Resolve any other Apply batches separately; draining them does not acknowledge them.' : ''; + if (ackIds.length > 50) return `Incorporate the latest snapshot at ${applied.exportPath}, then acknowledge its represented IDs in groups of at most 50: ${ackIds.join(',')}. Handle each await result before acknowledging the next group.${remaining}`; 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 ${ack} --reply ""\` only after those batches are incorporated, to keep listening.${remaining}`; } if (result.sessionEnded) { diff --git a/tests/lib/ui-canvas-delivery.test.js b/tests/lib/ui-canvas-delivery.test.js index 7634fbb63..8b33cc352 100644 --- a/tests/lib/ui-canvas-delivery.test.js +++ b/tests/lib/ui-canvas-delivery.test.js @@ -24,7 +24,7 @@ function element() { getBoundingClientRect: () => ({ width: 1200, height: 900 }), }; } -function client({ boot = {}, stored = {} } = {}) { +function client({ boot = {}, stored = {}, storageFailure = false } = {}) { 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 }); @@ -36,21 +36,26 @@ function client({ boot = {}, stored = {} } = {}) { let message; let events; let answer; + let deliverySequence = 0; const context = { + crypto: { randomUUID: () => '00000000-0000-4000-8000-' + String(++deliverySequence).padStart(12, '0'), subtle: { digest: async (_algorithm, bytes) => Uint8Array.from(require('node:crypto').createHash('sha256').update(bytes).digest()).buffer } }, + TextEncoder, 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); } }, + sessionStorage: { getItem: () => JSON.stringify(saved), setItem: (_key, value) => { const next = JSON.parse(value); if (storageFailure && next.pendingDelivery) throw new Error('Storage full'); saved = next; } }, localStorage: { getItem: () => null, setItem() {} }, setTimeout: () => 1, clearTimeout() {}, - EventSource: class { constructor() { events = {}; } addEventListener(type, run) { events[type] = run; } }, + EventSource: class { constructor() { events = {}; } addEventListener(type, run) { events[type] = run; } close() {} }, fetch: (url, options) => { requests.push({ url, body: JSON.parse(options.body) }); return new Promise(resolve => { answer = resolve; }); }, }; vm.runInNewContext(uiClientJs(), context); + message({ source: frame, data: { type: 'uc:ready' } }); return { node, packets, requests, 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 }), + answer: body => answer({ ok: true, json: async () => ({ acceptedEditIds: (body.batches || []).flatMap(batch => batch.edits.map(edit => edit.id)), acceptedText: requests.at(-1).body.items[0].text || '', ...body }) }), + lose: () => answer({ ok: true, json: async () => { throw new Error('Response body lost'); } }), fail: () => answer({ ok: false, status: 500, json: async () => ({ error: 'controlled failure' }) }), }; } @@ -75,9 +80,12 @@ async function main() { 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']); + assert.ok(h.node('artifact').src.includes('?t='), 'Acceptance reconciles against the current source'); + assert.ok(!h.packets.some(item => item.type === 'uc:delivery-end' && item.accepted), 'An old frame receipt cannot promote proof'); + h.message({ type: 'uc:ready' }); + const restored = h.packets.filter(packet => packet.type === 'uc:restore').at(-1); + assert.deepEqual(Array.from(restored.edits, edit => edit.id), ['e2']); + assert.deepEqual(Array.from(restored.batches, batch => batch.id), ['fb-1']); }); 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] }] } }); @@ -103,6 +111,70 @@ async function main() { assert.deepEqual(h.saved().edits, [first, later]); assert.equal(h.packets.find(packet => packet.type === 'uc:delivery-end').accepted, false); }); + await test('late old-frame messages retain new edits without replaying accepted or acknowledged IDs', async () => { + const h = client(); await capture(h); + h.message({ type: 'uc:edits', edits: [first, later], canUndo: true }); + h.answer({ batches: [{ id: 'fb-1', edits: [first] }] }); await tick(); + h.message({ type: 'uc:edits', edits: [first, later], canUndo: true }); + assert.deepEqual(h.saved().edits, [later]); + h.message({ type: 'uc:ready' }); + const restored = h.packets.filter(packet => packet.type === 'uc:restore').at(-1); + assert.deepEqual(Array.from(restored.edits, edit => edit.id), ['e2']); + assert.deepEqual(Array.from(restored.batches[0].edits, edit => edit.id), ['e1']); + h.message({ type: 'uc:edits', edits: [{ ...first, stale: true, submitted: true }, later] }); + assert.equal(h.saved().edits[0].submitted, true, 'Active unresolved submitted rows stay visible'); + h.event('ui-ack', { batches: [{ id: 'fb-1', editIds: ['e1'] }] }); + h.message({ type: 'uc:edits', edits: [{ ...first, stale: true, submitted: true }, later] }); + assert.deepEqual(h.saved().edits, [later], 'An old frame cannot resurrect retired rows'); + }); + await test('unknown Apply outcome retries its immutable item and preserves newer IDs and draft text', async () => { + const h = client(); h.node('chatInput').value = 'Original note'; await capture(h); + const firstRequest = h.requests[0].body; h.lose(); await tick(); + assert.equal(h.saved().pendingDelivery.id, firstRequest.deliveryId); + assert.equal(h.node('undoBtn').disabled, true); assert.equal(h.node('finishBtn').disabled, true); + assert.equal(h.packets.filter(packet => packet.type === 'uc:delivery-end').at(-1).retryPending, true); + h.message({ type: 'uc:edits', edits: [first, later], canUndo: true }); h.node('chatInput').value = 'New unsent draft'; + h.node('applyBtn').handlers.click(); await tick(); + assert.deepEqual(h.requests[1].body, firstRequest, 'Retry must not substitute the newer preview or note'); + h.answer({ acceptedEditIds: ['e1'], acceptedText: 'Original note', batches: [{ id: 'fb-1', edits: [first] }] }); await tick(); + assert.deepEqual(h.saved().edits, [later]); assert.equal(h.node('chatInput').value, 'New unsent draft'); + assert.equal(h.saved().pendingDelivery, null); + h.message({ type: 'uc:ready' }); h.message({ type: 'uc:edits', edits: [later], canUndo: true }); + h.node('applyBtn').handlers.click(); const packet = h.packets.filter(item => item.type === 'uc:export').at(-1); + h.message({ type: 'uc:export', requestId: packet.requestId, edits: [later], html: 'new preview' }); await tick(); + assert.notEqual(h.requests[2].body.deliveryId, firstRequest.deliveryId, 'A later batch needs its own token'); + }); + await test('uncertain Finish stays frozen and retries the original snapshot after a shell reload', async () => { + const h = client(); h.message({ type: 'uc:edits', edits: [first], canUndo: true }); h.node('chatInput').value = 'Final note'; + h.node('finishBtn').handlers.click(); const packet = h.packets.find(item => item.type === 'uc:export'); + h.message({ type: 'uc:export', requestId: packet.requestId, edits: [first], html: 'original final design' }); await tick(); + const original = h.requests[0].body; h.lose(); await tick(); + assert.equal(h.node('stage').inert, true); assert.equal(h.node('chatInput').disabled, true); + const reopened = client({ stored: h.saved() }); assert.equal(reopened.node('stage').inert, true); + reopened.node('finishBtn').handlers.click(); await tick(); + assert.deepEqual(reopened.requests[0].body, original); + reopened.answer({ acceptedEditIds: ['e1'], acceptedText: 'Final note' }); await tick(); + assert.equal(reopened.saved().pendingDelivery, null); assert.equal(reopened.node('finishBtn').disabled, true); + }); + await test('snapshot-storage failure stops submission and leaves the live edits retryable', async () => { + const h = client({ storageFailure: true }); h.node('chatInput').value = 'Unsent note'; await capture(h); + assert.equal(h.requests.length, 0); assert.deepEqual(h.saved().edits, [first]); + assert.equal(h.node('chatInput').value, 'Unsent note'); assert.equal(h.node('applyBtn').disabled, false); + assert.match(h.node('sendStatus').textContent, /preserve a retryable snapshot/); + }); + await test('correlated durable Finish SSE confirms a lost body while explicit End does not', async () => { + async function start() { + const h = client(); h.message({ type: 'uc:edits', edits: [first] }); h.node('finishBtn').handlers.click(); + const packet = h.packets.find(item => item.type === 'uc:export'); + h.message({ type: 'uc:export', requestId: packet.requestId, edits: [first], html: 'final' }); await tick(); return h; + } + const own = await start(); const id = own.requests[0].body.deliveryId; + own.event('ended', { endedBy: 'user', finished: true, deliveryId: id }); own.lose(); await tick(); + assert.equal(own.saved().pendingDelivery, null); assert.equal(own.node('endedTitle').textContent, 'Saved and handed to agent'); + assert.doesNotMatch(own.node('sendStatus').textContent, /failed/); + const other = await start(); other.event('ended', { endedBy: 'user' }); other.lose(); await tick(); + assert.ok(other.saved().pendingDelivery); assert.equal(other.node('endedTitle').textContent, 'Session ended'); + }); await test('Apply captures the original note before export and preserves newer draft input', async () => { const h = client(); h.node('chatInput').value = ' Original Apply note '; h.message({ type: 'uc:edits', edits: [first], canUndo: true }); h.node('applyBtn').handlers.click(); @@ -175,6 +247,13 @@ async function main() { 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); + context.deliveryRequest = 'reloaded'; context.bakedEditIds = []; context.edits = [{ id: 'e1', stale: true }, { id: 'e2' }]; + listener({ source: parent, data: { type: 'uc:delivery-end', requestId: 'reloaded', accepted: true, editIds: ['e1'] } }); + assert.equal(context.edits[0].submitted, true); assert.equal(context.edits[0].stale, true); + assert.deepEqual(context.bakedEditIds, [], 'An accepted old capture cannot prove a stale edit survived the current frame'); + assert.equal(context.edits[1].id, 'e2'); + listener({ source: parent, data: { type: 'uc:forget' } }); + assert.deepEqual(context.edits.map(edit => edit.id), ['e1'], 'Legacy forget clears unsent edits but cannot bypass unresolved-submitted protection'); }); await test('partially replayable submitted batch rolls back represented nudge and survives Reset', () => { const source = uiEditorJs(); @@ -182,7 +261,7 @@ async function main() { 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, + edits: [], bakedEditIds: [], sourceRevision: 'original-source', 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() {}, @@ -200,6 +279,24 @@ async function main() { context.resetAll(); assert.equal(style.left, '1px'); assert.deepEqual(Array.from(context.edits, edit => edit.id), ['e1', 'e2']); + context.sourceRevision = 'known-snapshot'; + context.restore({ batches: [{ id: 'fb-1', snapshotHash: 'known-snapshot', edits: [first] }], edits: [] }); + assert.equal(style.left, '1px', 'An exact already-represented snapshot must not receive its nudge again'); + assert.deepEqual(Array.from(context.bakedEditIds), ['e1']); assert.equal(context.edits.length, 0); + const normalApply = context.applyEdit; + context.applyEdit = (edit, el) => { if (edit.kind === 'move') throw new Error('HierarchyRequestError'); return normalApply(edit, el); }; + context.restore({ batches: [{ edits: [first, { id: 'move', kind: 'move', selector: '#a', to: { parent: '#nested', index: 0 } }] }], edits: [] }); + assert.equal(style.left, '1px', 'Thrown replay must still roll back the earlier nudge'); + assert.equal(context.edits.length, 2); assert.ok(context.edits.every(edit => edit.stale && edit.submitted)); + assert.deepEqual(Array.from(context.bakedEditIds), []); + context.applyEdit = normalApply; context.sourceRevision = 'local-snapshot'; style.left = '1px'; + context.restore({ batches: [], edits: [first, later], deliveryRequest: 'unknown', pendingSnapshotHash: 'local-snapshot', pendingSourceRevision: 'old-source', pendingEditIds: ['e1'] }); + assert.equal(style.left, '2px', 'Exact local snapshot skips only its original pending nudge, preserving newer work'); + assert.deepEqual(Array.from(context.bakedEditIds), [], 'Local preview evidence is not durable submitted proof'); + style.left = '1px'; context.sourceRevision = 'changed-source'; + context.restore({ batches: [], edits: [first, later], deliveryRequest: 'unknown', pendingSnapshotHash: 'local-snapshot', pendingSourceRevision: 'old-source', pendingEditIds: ['e1'] }); + assert.equal(style.left, '2px'); assert.equal(context.edits[0].stale, true); assert.ok(!context.edits[1].stale); + assert.deepEqual(Array.from(context.bakedEditIds), []); }); await test('unresolved submitted rows block Apply and Finish without dropping newer pending edits', () => { const h = client(); const unresolved = { ...first, submitted: true, stale: true }; diff --git a/tests/scripts/ui-canvas-ack.test.js b/tests/scripts/ui-canvas-ack.test.js index 8f67a33b3..923f32526 100644 --- a/tests/scripts/ui-canvas-ack.test.js +++ b/tests/scripts/ui-canvas-ack.test.js @@ -24,8 +24,8 @@ async function fixture(run) { 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); + let server = createPlanCanvasServer({ store }); + let { port } = await server.listen(0); function request(method, suffix, body) { return new Promise((resolve, reject) => { const payload = body ? JSON.stringify(body) : null; @@ -40,7 +40,21 @@ async function fixture(run) { 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 }); } + async function loseResponse(body) { + 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 => { + response.destroy(); resolve(response.statusCode); + }); + req.on('error', reject); req.end(JSON.stringify(body)); + }); + } + async function restart() { + await server.close(); + const reopened = createSessionStore({ stateDir: path.join(directory, 'state') }); + server = createPlanCanvasServer({ store: reopened }); ({ port } = await server.listen(0)); + return reopened.get(session.key); + } + try { await run({ store, session, file, directory, port, request, apply, loseResponse, restart }); } finally { await server.close(); fs.rmSync(directory, { recursive: true, force: true }); } } @@ -134,7 +148,108 @@ async function main() { assert.match(uncovered, /Resolve any other Apply batches separately/); const covered = UI_PROFILE.nextSteps.feedback({ items: [first, { ...latest, includedBatches: ['fb-1'] }] }); assert.match(covered, /--ack fb-2,fb-1 --reply/); assert.doesNotMatch(covered, /Resolve any other/); + const oversized = UI_PROFILE.nextSteps.feedback({ items: [{ ...latest, includedBatches: Array.from({ length: 50 }, (_, index) => `fb-${index + 10}`) }] }); + assert.doesNotMatch(oversized, /--ack /); assert.match(oversized, /groups of at most 50/); }); + await test('failed Apply and Finish persistence restore session/counter so retry queues one batch', () => fixture(async ({ session, store, directory, request }) => { + const before = JSON.stringify(session); const original = session; + const stateFile = path.join(directory, 'state', 'sessions.json'); const beforeState = fs.readFileSync(stateFile, 'utf8'); + const obstacle = path.join(directory, 'state', 'sessions.json.tmp'); fs.mkdirSync(obstacle); + const item = { kind: 'edits', edits: [edit('a')], html: 'one nudge' }; + const deliveryId = 'c'.repeat(32); + assert.equal((await request('POST', 'feedback', { items: [item], deliveryId })).status, 500); + assert.equal(store.get(session.key), original, 'Session object identity is preserved'); + assert.equal(JSON.stringify(session), before); assert.equal(fs.readFileSync(stateFile, 'utf8'), beforeState); + assert.equal((await request('POST', 'feedback', { items: [{ ...item, kind: 'finish' }], endSession: true, deliveryId })).status, 500); + assert.equal(JSON.stringify(session), before, 'Failed Finish must not end the session'); + fs.rmdirSync(obstacle); + const retry = await request('POST', 'feedback', { items: [item], deliveryId }); assert.equal(retry.status, 200); + assert.equal(retry.body.batches[0].id, 'fb-1', 'Failed saves must restore feedbackCounter too'); + assert.equal(session.pendingFeedback.length, 1); assert.equal(session.uiBatches.length, 1); assert.equal(session.chat.length, 1); + assert.equal(session.uiBatches[0].edits[0].id, 'a'); assert.equal(session.status, 'feedback'); + assert.equal(Object.keys(session.uiDeliveries).length, 1); + })); + await test('readable matching artifact survives acknowledgment write failure without retiring its batch', () => fixture(async ({ session, file, directory, request, apply }) => { + const html = '
A
'; + const id = await apply([edit('a')], html); fs.writeFileSync(file, html); + const obstacle = path.join(directory, 'state', 'sessions.json.tmp'); fs.mkdirSync(obstacle); + const result = await request('GET', `/artifact/${session.key}/`); + assert.equal(result.status, 200); assert.match(result.body, /left:1px/); + assert.deepEqual(session.uiBatches.map(batch => batch.id), [id]); + assert.equal((session.uiAcknowledged || []).length, 0); + assert.ok(result.body.includes(`data-source-sha256="${session.uiBatches[0].snapshotHash}"`), 'Current frame can recognize the exact already-represented batch without clearing durable queue state'); + fs.rmdirSync(obstacle); + assert.equal((await request('GET', `/artifact/${session.key}/`)).status, 200); + assert.deepEqual(session.uiBatches, []); + })); + await test('lost successful Apply response retries the same token without another batch or export', () => fixture(async ({ session, directory, request, loseResponse, restart }) => { + const item = { kind: 'edits', edits: [edit('a')], html: 'original immutable snapshot', text: 'original note' }; + const body = { items: [item], deliveryId: 'a'.repeat(32), endSession: false }; + assert.equal(await loseResponse(body), 200); + const files = fs.readdirSync(directory).sort(); const originalId = session.pendingFeedback[0].id; + const reopened = await restart(); + const retry = await request('POST', 'feedback', { deliveryId: body.deliveryId, items: [{ html: item.html, text: item.text, edits: item.edits, kind: item.kind }] }); + assert.equal(retry.status, 200); assert.equal(retry.body.batches[0].id, originalId); + assert.deepEqual(retry.body.acceptedEditIds, ['a']); assert.equal(retry.body.acceptedText, 'original note'); + assert.equal(reopened.pendingFeedback.length, 1); assert.equal(reopened.uiBatches.length, 1); assert.equal(reopened.chat.length, 1); + assert.deepEqual(fs.readdirSync(directory).sort(), files); + assert.equal((await request('POST', 'feedback', { ...body, items: [{ ...item, html: 'changed payload' }] })).status, 409); + assert.deepEqual(fs.readdirSync(directory).sort(), files); assert.equal(reopened.pendingFeedback.length, 1); + })); + await test('lost Finish response retries before ended rejection and cannot rewrite its final export', () => fixture(async ({ session, request, loseResponse, restart }) => { + const item = { kind: 'finish', edits: [edit('a')], html: 'final immutable design', text: 'final note' }; + const body = { items: [item], deliveryId: 'b'.repeat(32), endSession: true }; + assert.equal(await loseResponse(body), 200); assert.equal(session.status, 'ended'); + const finalPath = session.pendingFeedback[0].exportPath; const preserved = finalPath + '.preserved'; + fs.renameSync(finalPath, preserved); fs.mkdirSync(finalPath); + const reopened = await restart(); const retry = await request('POST', 'feedback', body); + assert.equal(retry.status, 200); assert.deepEqual(retry.body.acceptedEditIds, ['a']); assert.equal(retry.body.sessionEnded, true); + assert.equal(reopened.pendingFeedback.length, 1); assert.equal(reopened.chat.length, 1); assert.ok(fs.statSync(finalPath).isDirectory()); + assert.equal((await request('POST', 'feedback', { ...body, deliveryId: 'd'.repeat(32) })).status, 409); + assert.equal((await request('POST', 'feedback', { ...body, items: [{ ...item, text: 'changed note' }] })).status, 409); + assert.ok(fs.statSync(finalPath).isDirectory()); fs.rmdirSync(finalPath); fs.renameSync(preserved, finalPath); + })); + await test('failed drain preserves live feedback and the next await delivers it once', () => fixture(async ({ session, directory, request, apply }) => { + await apply([edit('a')], 'retained feedback'); const before = JSON.stringify(session); + const obstacle = path.join(directory, 'state', 'sessions.json.tmp'); fs.mkdirSync(obstacle); + assert.equal((await request('GET', `/api/await?key=${session.key}&timeoutMs=1`)).status, 500); + assert.equal(JSON.stringify(session), before); + fs.rmdirSync(obstacle); + const received = await request('GET', `/api/await?key=${session.key}&timeoutMs=1`); + assert.equal(received.body.status, 'feedback'); assert.equal(received.body.items.length, 1); + assert.equal((await request('GET', `/api/await?key=${session.key}&timeoutMs=1`)).body.status, 'waiting'); + })); + await test('postcommit drain failure cannot turn durable acceptance into a rejection', () => fixture(async ({ session, store, directory, request }) => { + const parked = request('GET', `/api/await?key=${session.key}&timeoutMs=1000`); + await new Promise(resolve => setTimeout(resolve, 20)); + const original = store.queueFeedback; const obstacle = path.join(directory, 'state', 'sessions.json.tmp'); + store.queueFeedback = (...args) => { const result = original(...args); fs.mkdirSync(obstacle); return result; }; + const body = { deliveryId: 'e'.repeat(32), items: [{ kind: 'edits', edits: [edit('a')], html: 'accepted before wake fault' }] }; + const accepted = await request('POST', 'feedback', body); + assert.equal(accepted.status, 200); assert.deepEqual(accepted.body.acceptedEditIds, ['a']); + assert.equal((await parked).body.status, 'waiting'); assert.equal(session.pendingFeedback.length, 1); + store.queueFeedback = original; fs.rmdirSync(obstacle); + const retry = await request('POST', 'feedback', body); + assert.equal(retry.status, 200); assert.equal(session.uiBatches.length, 1); assert.equal(session.chat.length, 1); + assert.equal((await request('GET', `/api/await?key=${session.key}&timeoutMs=1`)).body.items.length, 1); + })); + await test('delivery tokens are validated, session scoped, and cannot bypass explicit End', () => fixture(async ({ session, store, directory, request }) => { + const item = { kind: 'edits', edits: [edit('a')], html: 'one' }; const before = fs.readdirSync(directory).sort(); + for (const deliveryId of [null, '', 'a'.repeat(31), 'A'.repeat(32), {}, 3]) { + assert.equal((await request('POST', 'feedback', { deliveryId, items: [item] })).status, 400); + assert.deepEqual(fs.readdirSync(directory).sort(), before); + } + const deliveryId = 'f'.repeat(32); const first = await request('POST', 'feedback', { deliveryId, items: [item] }); + const secondFile = path.join(directory, 'second.html'); fs.writeFileSync(secondFile, 'second'); + const second = store.open(secondFile, { mode: 'ui' }).session; + const accepted = await request('POST', `/api/session/${second.key}/feedback`, { deliveryId, items: [item] }); + assert.equal(accepted.status, 200); assert.notEqual(accepted.body.batches[0].id, first.body.batches[0].id); + await request('POST', 'end'); + const files = fs.readdirSync(directory).sort(); + assert.equal((await request('POST', 'feedback', { deliveryId: '0'.repeat(32), endSession: true, items: [{ ...item, kind: 'finish' }] })).status, 409); + assert.deepEqual(fs.readdirSync(directory).sort(), files); + assert.equal(session.pendingFeedback.length, 1); + })); console.log(`Passed: ${passed}\nFailed: ${failed}`); process.exitCode = failed ? 1 : 0; } main().catch(error => { console.error(error); process.exitCode = 1; });