import { test } from 'node:test' import assert from 'node:assert/strict' import * as Y from 'yjs' import { createAssist, buildRequest, readAnswer, errorWord, AssistError, ERROR_WORDS } from './assist.mjs' import { mountAssist } from './assist-panel.mjs' import { applyOps, view } from './ops.mjs' import { el, withDocument } from './dom-stub.mjs' // --- the request --- test('a request is the trimmed prompt, the scope, the slide and the model', () => { assert.deepEqual(buildRequest({ prompt: ' punchier please \n', scope: 'slide', slide: 's1', model: 'm' }), { prompt: 'punchier please', scope: 'slide', slide: 's1', model: 'm' }) // The whole deck carries no slide, whatever the stage shows. assert.deepEqual(buildRequest({ prompt: 'ten slides on tea', scope: 'deck', slide: 's1', model: 'm' }), { prompt: 'ten slides on tea', scope: 'deck', model: 'm' }) }) test('an empty, blank or over-long prompt, or "this slide" with none, is never sent', () => { for (const prompt of ['', ' ', 'x'.repeat(2001)]) { assert.throws(() => buildRequest({ prompt, scope: 'deck' }), e => e instanceof AssistError && e.word === 'prompt') } // Counted in characters, not UTF-16 units: 2000 emoji is allowed. assert.doesNotThrow(() => buildRequest({ prompt: '🍵'.repeat(2000), scope: 'deck' })) assert.throws(() => buildRequest({ prompt: 'hi', scope: 'slide', slide: '' }), e => e.word === 'noslide') }) test('server words map onto the panel\'s strings, and anything else is generic', () => { assert.equal(errorWord('too_large'), 'too-large') assert.equal(errorWord('rate'), 'rate') assert.equal(errorWord('internal'), 'generic') assert.equal(errorWord(undefined), 'generic') for (const w of ERROR_WORDS) assert.equal(new AssistError(w).word, w) }) // --- reading the answer --- const response = (status, body) => ({ ok: status >= 200 && status < 300, status, json: async () => { if (typeof body === 'string') throw new SyntaxError('not json'); return body } }) test('an answer must be a list of op objects; anything else is generic', async () => { assert.deepEqual(await readAnswer(response(200, { ops: [{ op: 'set_meta', title: 'T' }], summary: 'S', focus: 'f' })), { ops: [{ op: 'set_meta', title: 'T' }], summary: 'S', focus: 'f' }) for (const body of [{ summary: 'no ops' }, { ops: 'nope' }, { ops: [1] }, { ops: [[]] }, '']) { await assert.rejects(readAnswer(response(200, body)), e => e.word === 'generic') } await assert.rejects(readAnswer(response(429, { error: 'rate' })), e => e.word === 'rate') await assert.rejects(readAnswer(response(404, 'not found')), e => e.word === 'generic') }) // --- the client --- function rig (over = {}) { const calls = [] const assist = createAssist({ url: '/d/abc/assist', fetch: async (url, init) => { calls.push(['fetch', url, init]); return response(200, { ops: [{ op: 'add_slide', id: 'n1', layout: 'flow' }], summary: 'Added a slide.', focus: 'n1' }) }, commit: async ops => { calls.push(['commit', ops]); return { applied: true, error: null, step: 'step-1' } }, flush: async () => { calls.push(['flush']); return true }, undoStep: async step => { calls.push(['undo', step]); return true }, ...over }) return { assist, calls } } test('an answer is posted as JSON, applied through commit, saved, and focused', async () => { const { assist, calls } = rig() const out = await assist.ask({ prompt: 'a slide', scope: 'deck', model: 'm' }) assert.deepEqual(out, { state: 'applied', summary: 'Added a slide.', focus: 'n1' }) // This tab's unsaved edits go first, so the server's deck is the one // on screen; then the answer is committed and saved. assert.deepEqual(calls.map(c => c[0]), ['flush', 'fetch', 'commit', 'flush']) const [, url, init] = calls[1] assert.equal(url, '/d/abc/assist') assert.equal(init.method, 'POST') assert.equal(init.credentials, 'same-origin') assert.equal(init.headers['Content-Type'], 'application/json') assert.deepEqual(JSON.parse(init.body), { prompt: 'a slide', scope: 'deck', model: 'm' }) assert.deepEqual(calls[2][1], [{ op: 'add_slide', id: 'n1', layout: 'flow' }]) assert.equal(assist.canUndo, true) }) test('a slide is focused only once its save is acknowledged', async () => { const { assist } = rig({ flush: async () => false }) const out = await assist.ask({ prompt: 'a slide', scope: 'deck' }) assert.equal(out.state, 'applied') assert.equal(out.focus, '') }) test('no ops is "nothing", and nothing is committed', async () => { const { assist, calls } = rig({ fetch: async () => response(200, { ops: [], summary: 'There is nothing to split.' }) }) assert.deepEqual(await assist.ask({ prompt: 'split', scope: 'slide', slide: 's' }), { state: 'nothing', summary: 'There is nothing to split.', focus: '' }) assert.deepEqual(calls.map(c => c[0]), ['flush'], 'only the flush before asking; nothing committed') assert.equal(assist.canUndo, false) }) test('every failure is a word, and nothing is applied', async () => { const cases = [ [{ fetch: async () => { throw new TypeError('offline') } }, 'unavailable'], [{ fetch: async () => response(502, { error: 'unavailable' }) }, 'unavailable'], [{ fetch: async () => response(504, { error: 'timeout' }) }, 'timeout'], [{ fetch: async () => response(413, { error: 'too_large' }) }, 'too-large'], [{ fetch: async () => response(422, { error: 'refused' }) }, 'refused'], [{ fetch: async () => response(500, '') }, 'generic'], // This tab's deck moved: the ops module refused the batch whole. [{ commit: async () => ({ applied: false, error: new Error('op 0: no slide "x"'), step: null }) }, 'changed'], // A font the batch needs could not be had. [{ commit: async () => ({ applied: false, error: null, step: null }) }, 'fonts'], [{ commit: async () => { throw new Error('boom') } }, 'generic'] ] for (const [over, word] of cases) { const errors = console.error console.error = () => {} try { const { assist } = rig(over) assert.deepEqual(await assist.ask({ prompt: 'x', scope: 'deck' }), { state: 'error', word }) assert.equal(assist.canUndo, false) } finally { console.error = errors } } const { assist, calls } = rig() assert.deepEqual(await assist.ask({ prompt: '', scope: 'deck' }), { state: 'error', word: 'prompt' }) assert.equal(calls.length, 0, 'an empty prompt reaches no network') }) test('undo takes back the answer\'s own step, once', async () => { const { assist, calls } = rig() await assist.ask({ prompt: 'x', scope: 'deck' }) assert.equal(await assist.undo(), true) assert.deepEqual(calls.at(-1), ['undo', 'step-1']) assert.equal(await assist.undo(), false, 'a second press undoes nothing more') const later = rig({ undoStep: async () => false }) await later.assist.ask({ prompt: 'x', scope: 'deck' }) assert.equal(await later.assist.undo(), false, 'a step something came after is not undone from here') }) // --- the server's batch shape applies in the browser --- test('a batch shaped as the server answers it applies through ops.mjs', () => { const doc = new Y.Doc() applyOps(doc, [{ op: 'add_slide', id: 'aaaaaaaaaaaa', layout: 'flow', template: 'title' }]) // What assist_ops.go sends: minted ids, only each op's own keys, // "after" null or a real id, props as the model wrote them. applyOps(doc, [ { op: 'set_meta', title: 'Tea', theme: 'forest', accent: null }, { op: 'add_block', slide: 'aaaaaaaaaaaa', id: 'bbbbbbbbbbbb', type: 'heading', region: 'heading', props: { level: 1 }, markdown: 'Tea' }, { op: 'add_slide', id: 'cccccccccccc', layout: 'flow', template: 'title-body', after: 'aaaaaaaaaaaa' }, { op: 'add_block', slide: 'cccccccccccc', id: 'dddddddddddd', type: 'list', region: 'body', props: { style: 'bullet' }, markdown: '- China\n- **India**' }, { op: 'set_notes', id: 'cccccccccccc', markdown: 'Kenya exports the most.' }, { op: 'set_slide', id: 'cccccccccccc', transition: 'fade' }, { op: 'duplicate_slide', id: 'cccccccccccc', new_id: 'eeeeeeeeeeee', new_block_ids: ['ffffffffffff'] }, { op: 'set_text', slide: 'eeeeeeeeeeee', id: 'ffffffffffff', markdown: '- Kenya' }, { op: 'move_slide', id: 'eeeeeeeeeeee', after: null } ], 'local') const v = view(doc) assert.equal(v.meta.title, 'Tea') assert.deepEqual(v.slides.map(s => s.id), ['eeeeeeeeeeee', 'aaaaaaaaaaaa', 'cccccccccccc']) assert.equal(v.slides[2].transition, 'fade') assert.equal(v.slides[2].blocks[0].text.length, 2) }) // --- the panel --- function panelRig ({ result = { state: 'applied', summary: 'Made it punchier.', focus: '' }, canUndo = true, slide = 's1' } = {}) { const { document, restore } = withDocument() const prompt = el('textarea', { name: 'slides-assist-prompt' }) prompt.value = 'punchier' const scope = el('select'); scope.value = 'slide' const model = el('select'); model.value = 'm' const form = el('form', { 'slides-assist-form': '' }, [prompt]) form.elements = { namedItem: n => ({ 'slides-assist-prompt': prompt, 'slides-assist-scope': scope, 'slides-assist-model': model })[n] } const askBtn = el('button', { 'slides-assist-ask': '' }) const summary = el('p', { 'slides-assist-summary': '' }) const note = el('p', { 'slides-assist-note': '' }) const outcome = el('div', { 'slides-assist-outcome': '' }, [summary, note]) const undo = el('button', { 'slides-assist-undo': '' }); undo.hidden = true const panel = el('section', { 'slides-assist': '', 'data-max-prompt': '2000', 'data-text-working': 'Working', 'data-text-applied': 'Applied', 'data-text-nothing': 'Nothing', 'data-text-undone': 'Undone', 'data-text-undo-later': 'Later', 'data-text-error-rate': 'Too many', 'data-text-error-generic': 'Oops' }, [form, askBtn, outcome, undo]) let hidden = 0 panel.hidePopover = () => { hidden++ } const toggle = el('button', { 'slides-assist-toggle': '', 'aria-pressed': 'false' }) const root = el('div', {}, [toggle, panel]) const asked = [] const went = [] let undone = 0 const assist = { ask: async req => { asked.push(req); assert.equal(askBtn.getAttribute('aria-busy'), 'true'); assert.equal(askBtn.getAttribute('aria-disabled'), 'true'); return result }, undo: async () => { undone++; return true }, get canUndo () { return canUndo } } const mount = mountAssist({ root, assist, getSlideId: () => slide, go: id => went.push(id), hold: 0 }) const fire = async (node, type, ev = {}) => { for (const l of node.listeners.filter(l => l.type === type)) await l.fn({ preventDefault () {}, stopPropagation () {}, ...ev }) } return { document, restore, mount, root, panel, toggle, form, askBtn, summary, note, outcome, undo, prompt, scope, asked, went, fire, get hidden () { return hidden }, get undone () { return undone } } } test('the toggle is lit while the panel is open, and opening focuses the prompt', async () => { const r = panelRig() try { await r.fire(r.panel, 'toggle', { newState: 'open' }) assert.equal(r.toggle.getAttribute('aria-pressed'), 'true') assert.equal(r.document.activeElement, r.prompt) assert.equal(r.prompt.maxLength, 2000) await r.fire(r.panel, 'toggle', { newState: 'closed' }) assert.equal(r.toggle.getAttribute('aria-pressed'), 'false') assert.equal(r.document.activeElement, r.toggle, 'focus leaves the closed panel for its toggle') await r.fire(r.panel, 'keydown', { key: 'Escape' }) assert.equal(r.hidden, 1) } finally { r.restore() } }) test('a deck with no slide opens on "the whole deck"', async () => { const r = panelRig({ slide: '' }) try { await r.fire(r.panel, 'toggle', { newState: 'open' }) assert.equal(r.scope.value, 'deck') } finally { r.restore() } }) test('asking is busy, then says what was done and offers Undo', async () => { const r = panelRig({ result: { state: 'applied', summary: 'Added two slides.', focus: 'new1' } }) try { await r.fire(r.form, 'submit') assert.deepEqual(r.asked, [{ prompt: 'punchier', scope: 'slide', slide: 's1', model: 'm' }]) assert.equal(r.askBtn.hasAttribute('aria-busy'), false) assert.equal(r.askBtn.hasAttribute('aria-disabled'), false) assert.equal(r.askBtn.querySelector('[rst-spin]'), null, 'the spinner is gone') assert.equal(r.summary.textContent, 'Added two slides.') assert.equal(r.note.textContent, 'Applied') assert.equal(r.undo.hidden, false) assert.deepEqual(r.went, ['new1']) await r.fire(r.undo, 'click') assert.equal(r.undone, 1) assert.equal(r.note.textContent, 'Undone') assert.equal(r.undo.hidden, true) } finally { r.restore() } }) test('an error is said in the catalog\'s words, marked, and offers no Undo', async () => { const r = panelRig({ result: { state: 'error', word: 'rate' } }) try { await r.fire(r.form, 'submit') assert.equal(r.note.textContent, 'Too many') assert.equal(r.outcome.getAttribute('data-tone'), 'error') assert.equal(r.undo.hidden, true) } finally { r.restore() } const g = panelRig({ result: { state: 'error', word: 'noslide' } }) try { await g.fire(g.form, 'submit') assert.equal(g.note.textContent, 'Oops', 'a word with no string falls back to the generic one') } finally { g.restore() } }) test('destroy takes every listener away', () => { const r = panelRig() try { r.mount.destroy() for (const node of [r.panel, r.form, r.undo]) assert.equal(node.listeners.length, 0) } finally { r.restore() } })