mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 08:15:29 +00:00
fix: preserve immutable UI deliveries through retry and reload
This commit is contained in:
9 files changed
+419
-68
No files matched your search
@@ -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'
|
||||
? `<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>';
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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 };
|
||||
@@ -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;
|
||||
|
||||
+46
-24
@@ -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(/</g, '\\u003c');
|
||||
const artifactSrc = `/artifact/${session.key}/`;
|
||||
|
||||
Reference in new issue
Block a user