mirror of
https://github.com/affaan-m/ECC.git
synced 2026-12-02 12:45:47 +00:00
fix: publish canvas feedback state only after persistence
This commit is contained in:
4 files changed
+194
-115
No files matched your search
@@ -400,7 +400,8 @@ function createPlanCanvasServer({
|
||||
if (filename && filename !== base) return;
|
||||
clearTimeout(debounce);
|
||||
debounce = setTimeout(() => {
|
||||
try { acknowledgeUiSnapshot(session, fs.readFileSync(session.file)); } catch { /* missing or partial saves do not acknowledge */ }
|
||||
const current = store.get(session.key);
|
||||
try { if (current) acknowledgeUiSnapshot(current, fs.readFileSync(current.file)); } catch { /* missing or partial saves do not acknowledge */ }
|
||||
broadcast(session.key, 'reload', {});
|
||||
}, 150);
|
||||
});
|
||||
@@ -569,6 +570,7 @@ function createPlanCanvasServer({
|
||||
|
||||
if (action === 'feedback') {
|
||||
const body = await readJsonBody(req);
|
||||
const session = store.get(key);
|
||||
let items = Array.isArray(body.items) ? body.items : [];
|
||||
const deliveryId = body.deliveryId;
|
||||
let fingerprint = null;
|
||||
@@ -607,11 +609,12 @@ function createPlanCanvasServer({
|
||||
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));
|
||||
const current = store.get(key);
|
||||
if (deliveryId) return sendJson(res, 200, deliveryResponse(current, current.uiDeliveries[deliveryId], current.pendingFeedback.length));
|
||||
return sendJson(res, 200, {
|
||||
status: 'queued',
|
||||
accepted: result.accepted.length,
|
||||
pending: session.pendingFeedback.length,
|
||||
pending: current.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)
|
||||
});
|
||||
@@ -624,6 +627,7 @@ function createPlanCanvasServer({
|
||||
|
||||
if (action === 'reply') {
|
||||
const body = await readJsonBody(req);
|
||||
const session = store.get(key);
|
||||
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)))) {
|
||||
|
||||
@@ -124,15 +124,24 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function persist() {
|
||||
function persist(candidate = state) {
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
const tmpFile = `${stateFile}.tmp`;
|
||||
fs.writeFileSync(tmpFile, JSON.stringify(state, null, 2));
|
||||
fs.writeFileSync(tmpFile, JSON.stringify(candidate, null, 2));
|
||||
fs.renameSync(tmpFile, stateFile);
|
||||
}
|
||||
|
||||
load();
|
||||
|
||||
// Publish replacement state only after its complete snapshot is durable.
|
||||
// Retained session references remain snapshots, including on failed writes.
|
||||
function commitSession(key, session, feedbackCounter = state.feedbackCounter) {
|
||||
const candidate = { ...state, sessions: { ...state.sessions, [key]: session }, feedbackCounter };
|
||||
persist(candidate);
|
||||
state = candidate;
|
||||
return session;
|
||||
}
|
||||
|
||||
function get(key) {
|
||||
return state.sessions[key] || null;
|
||||
}
|
||||
@@ -194,48 +203,31 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
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;
|
||||
let counter = state.feedbackCounter;
|
||||
const accepted = [];
|
||||
for (const raw of Array.isArray(rawItems) ? rawItems : []) {
|
||||
counter += 1;
|
||||
const item = normalize(raw, counter);
|
||||
if (item) accepted.push(item);
|
||||
}
|
||||
state.feedbackCounter = counter;
|
||||
session.pendingFeedback = [...session.pendingFeedback, ...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) });
|
||||
}
|
||||
}
|
||||
session.chat = [...session.chat];
|
||||
for (const item of accepted) {
|
||||
session.chat.push({ role: 'user', kind: item.kind, text: describe(item), at: item.at });
|
||||
}
|
||||
if (endSession) {
|
||||
session.status = 'ended';
|
||||
session.endedBy = 'user';
|
||||
} else if (accepted.length > 0) {
|
||||
session.status = 'feedback';
|
||||
}
|
||||
if (deliveryId) {
|
||||
const item = accepted[0];
|
||||
session.uiDeliveries = { ...(session.uiDeliveries || {}), [deliveryId]: {
|
||||
const item = accepted[0];
|
||||
const next = {
|
||||
...session,
|
||||
pendingFeedback: [...session.pendingFeedback, ...accepted],
|
||||
...(session.mode === 'ui' ? { uiBatches: [...(session.uiBatches || []), ...accepted.filter(entry => entry.kind === 'edits').map(entry => ({
|
||||
id: entry.id, snapshotHash: entry.snapshotHash, includedBatches: entry.includedBatches || [], edits: entry.edits.filter(edit => !edit.stale)
|
||||
}))] } : {}),
|
||||
chat: [...session.chat, ...accepted.map(entry => ({ role: 'user', kind: entry.kind, text: describe(entry), at: entry.at }))],
|
||||
status: endSession ? 'ended' : accepted.length ? 'feedback' : session.status,
|
||||
...(endSession ? { endedBy: 'user' } : {}),
|
||||
...(deliveryId ? { 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();
|
||||
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 };
|
||||
} } } : {}),
|
||||
updatedAt: nowIso()
|
||||
};
|
||||
commitSession(key, next, counter);
|
||||
return { accepted, pending: next.pendingFeedback.length, session: next };
|
||||
}
|
||||
|
||||
// Acknowledgment is distinct from delivery: taking feedback is not proof
|
||||
@@ -246,13 +238,14 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
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; }
|
||||
commitSession(key, {
|
||||
...session,
|
||||
uiBatches: (session.uiBatches || []).filter(batch => !ids.includes(batch.id)),
|
||||
uiAcknowledged: [...(session.uiAcknowledged || []), ...accepted.map(batch => ({ id: batch.id, editIds: batch.edits.map(edit => edit.id) }))],
|
||||
chat: entry ? [...session.chat, entry] : session.chat,
|
||||
updatedAt: nowIso()
|
||||
});
|
||||
return { batches: accepted.map(batch => ({ id: batch.id, editIds: batch.edits.map(edit => edit.id) })), entry };
|
||||
}
|
||||
|
||||
@@ -263,18 +256,13 @@ 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 };
|
||||
if (session.status === 'ended') {
|
||||
result.sessionEnded = true;
|
||||
result.endedBy = session.endedBy;
|
||||
} else {
|
||||
session.status = 'open';
|
||||
}
|
||||
session.updatedAt = nowIso();
|
||||
try { persist(); } catch (error) { Object.assign(session, previous); throw error; }
|
||||
commitSession(key, { ...session, pendingFeedback: [], status: session.status === 'ended' ? 'ended' : 'open', updatedAt: nowIso() });
|
||||
return result;
|
||||
}
|
||||
if (session.status === 'ended') {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { createSessionStore } = require('../../scripts/lib/plan-canvas/sessions');
|
||||
|
||||
function freeze(value) {
|
||||
if (value && typeof value === 'object') {
|
||||
Object.values(value).forEach(freeze);
|
||||
Object.freeze(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
function test(name, run) {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-ui-immutable-'));
|
||||
try {
|
||||
const store = createSessionStore({ stateDir: directory });
|
||||
const original = store.open(path.join(directory, 'card.html'), { mode: 'ui' }).session;
|
||||
run({ store, original, directory }); passed++; console.log(`PASS ${name}`);
|
||||
} catch (error) { failed++; console.log(`FAIL ${name}: ${error.stack}`); }
|
||||
finally { fs.rmSync(directory, { recursive: true, force: true }); }
|
||||
}
|
||||
const item = { kind: 'edits', edits: [{ id: 'e1', kind: 'nudge', selector: '#a', dx: 1, dy: 0 }], snapshotHash: 'a'.repeat(64) };
|
||||
test('queue replaces state only after persistence and preserves retained snapshots', ({ store, original, directory }) => {
|
||||
const unrelated = store.open(path.join(directory, 'other.html')).session;
|
||||
const before = JSON.stringify(original); freeze(original);
|
||||
const result = store.queueFeedback(original.key, [item], { deliveryId: 'a'.repeat(32), fingerprint: 'proof' });
|
||||
const current = store.get(original.key);
|
||||
assert.notEqual(current, original); assert.equal(result.session, current);
|
||||
assert.equal(JSON.stringify(original), before); assert.equal(store.get(unrelated.key), unrelated);
|
||||
assert.equal(current.pendingFeedback.length, 1); assert.equal(current.uiBatches.length, 1);
|
||||
assert.equal(current.uiDeliveries['a'.repeat(32)].itemIds[0], 'fb-1');
|
||||
assert.deepEqual(createSessionStore({ stateDir: directory }).get(original.key), current);
|
||||
});
|
||||
test('acknowledgment and drain replace sessions without changing prior queue snapshots', ({ store, original }) => {
|
||||
store.queueFeedback(original.key, [item]); const queued = store.get(original.key); freeze(queued);
|
||||
const id = queued.uiBatches[0].id; store.acknowledgeUiBatches(original.key, [id], 'Applied');
|
||||
const acknowledged = store.get(original.key); freeze(acknowledged);
|
||||
assert.notEqual(acknowledged, queued); assert.equal(queued.uiBatches.length, 1);
|
||||
assert.equal(queued.chat.length, 1); assert.equal(acknowledged.uiBatches.length, 0);
|
||||
const result = store.takeFeedback(original.key); const drained = store.get(original.key);
|
||||
assert.notEqual(drained, acknowledged); assert.equal(result.items.length, 1);
|
||||
assert.equal(acknowledged.pendingFeedback.length, 1); assert.equal(drained.pendingFeedback.length, 0);
|
||||
assert.equal(drained.status, 'open'); assert.equal(store.takeFeedback(original.key).status, 'waiting');
|
||||
});
|
||||
test('failed candidate persistence never publishes queue, Finish, ack, drain or counter changes', ({ store, original, directory }) => {
|
||||
const obstacle = path.join(directory, 'sessions.json.tmp');
|
||||
fs.mkdirSync(obstacle); freeze(original);
|
||||
assert.throws(() => store.queueFeedback(original.key, [item], { endSession: true }));
|
||||
assert.equal(store.get(original.key), original); assert.equal(original.status, 'open');
|
||||
fs.rmdirSync(obstacle); store.queueFeedback(original.key, [item], { endSession: true });
|
||||
const queued = store.get(original.key); freeze(queued); assert.equal(queued.pendingFeedback[0].id, 'fb-1');
|
||||
const disk = fs.readFileSync(store.stateFile, 'utf8'); fs.mkdirSync(obstacle);
|
||||
assert.throws(() => store.acknowledgeUiBatches(original.key, ['fb-1'], 'Not saved'));
|
||||
assert.throws(() => store.takeFeedback(original.key));
|
||||
assert.equal(store.get(original.key), queued); assert.equal(fs.readFileSync(store.stateFile, 'utf8'), disk);
|
||||
fs.rmdirSync(obstacle); const result = store.takeFeedback(original.key);
|
||||
assert.equal(result.sessionEnded, true); assert.equal(result.endedBy, 'user');
|
||||
assert.equal(store.get(original.key).status, 'ended'); assert.equal(queued.pendingFeedback.length, 1);
|
||||
});
|
||||
console.log(`Passed: ${passed}, Failed: ${failed}`);
|
||||
process.exitCode = failed ? 1 : 0;
|
||||
@@ -54,67 +54,67 @@ async function fixture(run) {
|
||||
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 }); }
|
||||
try { await run({ store, getSession: () => store.get(session.key), file, directory, port, request, apply, loseResponse, restart }); }
|
||||
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 }) => {
|
||||
await test('taking feedback and unrelated saves do not acknowledge queued Apply batches', () => fixture(async ({ store, getSession, file, request, apply }) => {
|
||||
const id = await apply([edit('a')], '<html><body>applied</body></html>');
|
||||
store.takeFeedback(session.key);
|
||||
store.takeFeedback(getSession().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 request('GET', `/artifact/${getSession().key}/`);
|
||||
assert.deepEqual(getSession().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 }) => {
|
||||
await test('exact snapshot acknowledges its batch and only verified included older batches', () => fixture(async ({ getSession, 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]);
|
||||
await request('GET', `/artifact/${getSession().key}/`);
|
||||
assert.deepEqual(getSession().uiBatches.map(batch => batch.id), [older]);
|
||||
assert.deepEqual(getSession().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 request('GET', `/artifact/${getSession().key}/`);
|
||||
assert.deepEqual(getSession().uiBatches, []);
|
||||
assert.deepEqual(getSession().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 }) => {
|
||||
await test('specific acknowledgment is durable and clears only named known batches', () => fixture(async ({ getSession, 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);
|
||||
const reopened = createSessionStore({ stateDir: path.join(directory, 'state') }).get(getSession().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 }) => {
|
||||
await test('invalid reply fields or mixed unknown IDs have no partial side effects', () => fixture(async ({ getSession, request, apply }) => {
|
||||
const id = await apply([edit('a')], '<html>one</html>');
|
||||
const count = session.chat.length;
|
||||
const count = getSession().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);
|
||||
assert.deepEqual(getSession().uiBatches.map(batch => batch.id), [id]); assert.equal(getSession().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]);
|
||||
assert.deepEqual(getSession().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;
|
||||
await test('state write failure rolls back acknowledgment and its accompanying reply together', () => fixture(async ({ getSession, directory, request, apply }) => {
|
||||
const id = await apply([edit('a')], '<html>one</html>'); const count = getSession().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.equal(response.status, 500); assert.equal(getSession().chat.length, count);
|
||||
assert.deepEqual(getSession().uiBatches.map(batch => batch.id), [id]);
|
||||
const reopened = createSessionStore({ stateDir: path.join(directory, 'state') }).get(getSession().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 }) => {
|
||||
await test('oversized or malformed proof fails before writing an export or queuing anything', () => fixture(async ({ getSession, 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.equal(response.status, 413); assert.equal(getSession().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>' }] });
|
||||
@@ -125,18 +125,18 @@ async function main() {
|
||||
] });
|
||||
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 }) => {
|
||||
await test('actual CLI preserves file/key awaits and plain replies while validating acknowledgments', () => fixture(async ({ getSession, 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);
|
||||
store.takeFeedback(getSession().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, []);
|
||||
assert.deepEqual(getSession().uiBatches.map(batch => batch.id), [second]);
|
||||
await cli('await', '--session-key', getSession().key, '--ack', second, '--timeout-ms', '1');
|
||||
assert.deepEqual(getSession().uiBatches, []);
|
||||
await cli('await', file, '--reply', 'Old reply without ack', '--timeout-ms', '1');
|
||||
assert.equal(session.chat.at(-1).text, 'Old reply without ack');
|
||||
assert.equal(getSession().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; });
|
||||
}));
|
||||
@@ -151,42 +151,42 @@ async function main() {
|
||||
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;
|
||||
await test('failed Apply and Finish persistence restore session/counter so retry queues one batch', () => fixture(async ({ getSession, store, directory, request }) => {
|
||||
const before = JSON.stringify(getSession()); const original = getSession();
|
||||
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: '<html>one nudge</html>' };
|
||||
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(store.get(getSession().key), original, 'Session object identity is preserved');
|
||||
assert.equal(JSON.stringify(getSession()), 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');
|
||||
assert.equal(JSON.stringify(getSession()), 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);
|
||||
assert.equal(getSession().pendingFeedback.length, 1); assert.equal(getSession().uiBatches.length, 1); assert.equal(getSession().chat.length, 1);
|
||||
assert.equal(getSession().uiBatches[0].edits[0].id, 'a'); assert.equal(getSession().status, 'feedback');
|
||||
assert.equal(Object.keys(getSession().uiDeliveries).length, 1);
|
||||
}));
|
||||
await test('readable matching artifact survives acknowledgment write failure without retiring its batch', () => fixture(async ({ session, file, directory, request, apply }) => {
|
||||
await test('readable matching artifact survives acknowledgment write failure without retiring its batch', () => fixture(async ({ getSession, file, directory, request, apply }) => {
|
||||
const html = '<html><body><article id="a" style="position:relative;left:1px">A</article></body></html>';
|
||||
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}/`);
|
||||
const result = await request('GET', `/artifact/${getSession().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');
|
||||
assert.deepEqual(getSession().uiBatches.map(batch => batch.id), [id]);
|
||||
assert.equal((getSession().uiAcknowledged || []).length, 0);
|
||||
assert.ok(result.body.includes(`data-source-sha256="${getSession().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, []);
|
||||
assert.equal((await request('GET', `/artifact/${getSession().key}/`)).status, 200);
|
||||
assert.deepEqual(getSession().uiBatches, []);
|
||||
}));
|
||||
await test('lost successful Apply response retries the same token without another batch or export', () => fixture(async ({ session, directory, request, loseResponse, restart }) => {
|
||||
await test('lost successful Apply response retries the same token without another batch or export', () => fixture(async ({ getSession, directory, request, loseResponse, restart }) => {
|
||||
const item = { kind: 'edits', edits: [edit('a')], html: '<html>original immutable snapshot</html>', 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 files = fs.readdirSync(directory).sort(); const originalId = getSession().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);
|
||||
@@ -196,11 +196,11 @@ async function main() {
|
||||
assert.equal((await request('POST', 'feedback', { ...body, items: [{ ...item, html: '<html>changed payload</html>' }] })).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 }) => {
|
||||
await test('lost Finish response retries before ended rejection and cannot rewrite its final export', () => fixture(async ({ getSession, request, loseResponse, restart }) => {
|
||||
const item = { kind: 'finish', edits: [edit('a')], html: '<html>final immutable design</html>', 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';
|
||||
assert.equal(await loseResponse(body), 200); assert.equal(getSession().status, 'ended');
|
||||
const finalPath = getSession().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);
|
||||
@@ -209,31 +209,52 @@ async function main() {
|
||||
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')], '<html>retained feedback</html>'); const before = JSON.stringify(session);
|
||||
await test('failed drain preserves live feedback and the next await delivers it once', () => fixture(async ({ getSession, directory, request, apply }) => {
|
||||
await apply([edit('a')], '<html>retained feedback</html>'); const before = JSON.stringify(getSession());
|
||||
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);
|
||||
assert.equal((await request('GET', `/api/await?key=${getSession().key}&timeoutMs=1`)).status, 500);
|
||||
assert.equal(JSON.stringify(getSession()), before);
|
||||
fs.rmdirSync(obstacle);
|
||||
const received = await request('GET', `/api/await?key=${session.key}&timeoutMs=1`);
|
||||
const received = await request('GET', `/api/await?key=${getSession().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');
|
||||
assert.equal((await request('GET', `/api/await?key=${getSession().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 test('postcommit drain failure cannot turn durable acceptance into a rejection', () => fixture(async ({ getSession, store, directory, request }) => {
|
||||
const parked = request('GET', `/api/await?key=${getSession().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: '<html>accepted before wake fault</html>' }] };
|
||||
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);
|
||||
assert.equal((await parked).body.status, 'waiting'); assert.equal(getSession().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);
|
||||
assert.equal(retry.status, 200); assert.equal(getSession().uiBatches.length, 1); assert.equal(getSession().chat.length, 1);
|
||||
assert.equal((await request('GET', `/api/await?key=${getSession().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 }) => {
|
||||
await test('immediate long-poll drain returns a fresh receipt and pending count', () => fixture(async ({ getSession, request }) => {
|
||||
const parked = request('GET', `/api/await?key=${getSession().key}&timeoutMs=1000`);
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
const body = { deliveryId: 'f'.repeat(32), items: [{ kind: 'edits', edits: [edit('a')], html: '<html>fresh receipt</html>' }] };
|
||||
const result = await request('POST', 'feedback', body);
|
||||
assert.equal(result.status, 200); assert.deepEqual(result.body.acceptedEditIds, ['a']);
|
||||
assert.equal((await parked).body.items.length, 1);
|
||||
assert.equal(result.body.pending, 0); assert.equal(getSession().pendingFeedback.length, 0);
|
||||
assert.equal((await request('POST', 'feedback', body)).body.pending, 0);
|
||||
assert.equal(getSession().uiBatches.length, 1);
|
||||
}));
|
||||
await test('artifact watcher acknowledges batches from the latest replacement session', () => fixture(async ({ getSession, file, request, apply }) => {
|
||||
assert.equal((await request('POST', '/api/sessions', { file, mode: 'ui' })).status, 200);
|
||||
const html = '<html><body>watcher observes accepted snapshot</body></html>';
|
||||
const id = await apply([edit('a')], html);
|
||||
fs.writeFileSync(file, html);
|
||||
const deadline = Date.now() + 2000;
|
||||
while (getSession().uiBatches.length && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));
|
||||
assert.deepEqual(getSession().uiBatches, []);
|
||||
assert.deepEqual(getSession().uiAcknowledged.map(batch => batch.id), [id]);
|
||||
}));
|
||||
await test('delivery tokens are validated, session scoped, and cannot bypass explicit End', () => fixture(async ({ getSession, store, directory, request }) => {
|
||||
const item = { kind: 'edits', edits: [edit('a')], html: '<html>one</html>' }; 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);
|
||||
@@ -248,7 +269,7 @@ async function main() {
|
||||
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);
|
||||
assert.equal(getSession().pendingFeedback.length, 1);
|
||||
}));
|
||||
console.log(`Passed: ${passed}\nFailed: ${failed}`); process.exitCode = failed ? 1 : 0;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user