From 6dbaa347886b4e022f4cd4b0a192d86e04183f84 Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:56:55 -0500 Subject: [PATCH] fix: publish canvas feedback state only after persistence --- scripts/lib/plan-canvas/server.js | 10 +- scripts/lib/plan-canvas/sessions.js | 84 +++++------ tests/lib/ui-canvas-state-immutable.test.js | 66 +++++++++ tests/scripts/ui-canvas-ack.test.js | 149 +++++++++++--------- 4 files changed, 194 insertions(+), 115 deletions(-) create mode 100644 tests/lib/ui-canvas-state-immutable.test.js diff --git a/scripts/lib/plan-canvas/server.js b/scripts/lib/plan-canvas/server.js index 7aa771f75..28c6bc4b3 100644 --- a/scripts/lib/plan-canvas/server.js +++ b/scripts/lib/plan-canvas/server.js @@ -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)))) { diff --git a/scripts/lib/plan-canvas/sessions.js b/scripts/lib/plan-canvas/sessions.js index 8c58a37ff..09870af99 100644 --- a/scripts/lib/plan-canvas/sessions.js +++ b/scripts/lib/plan-canvas/sessions.js @@ -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') { diff --git a/tests/lib/ui-canvas-state-immutable.test.js b/tests/lib/ui-canvas-state-immutable.test.js new file mode 100644 index 000000000..4f3d2b57e --- /dev/null +++ b/tests/lib/ui-canvas-state-immutable.test.js @@ -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; diff --git a/tests/scripts/ui-canvas-ack.test.js b/tests/scripts/ui-canvas-ack.test.js index 923f32526..1da9903fa 100644 --- a/tests/scripts/ui-canvas-ack.test.js +++ b/tests/scripts/ui-canvas-ack.test.js @@ -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')], '
applied'); - store.takeFeedback(session.key); + store.takeFeedback(getSession().key); fs.writeFileSync(file, 'earlier chat save'); - 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')], 'first snapshot'); const newer = await apply([edit('b')], 'partial older snapshot', ['a']); fs.writeFileSync(file, 'partial older snapshot'); - 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')], 'all represented', ['a', 'missing']); fs.writeFileSync(file, 'all represented'); - 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')], 'one'); const second = await apply([edit('b')], 'two'); 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')], 'one'); - 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')], 'one'); 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')], 'one'); 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: 'snapshot', 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: 'snapshot' }] }); @@ -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')], 'one'); const second = await apply([edit('b')], 'two'); - 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: '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(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 = '