From 9f9be5f41af2b833c0d726b9e4b00921427c0ed5 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 1 Nov 2026 12:16:59 -0800 Subject: [PATCH] Sitesmith modal: Clear chat explains a refusal and is disabled while a job runs Reproduced in the e2e mock (now stateful: history + clear_history with the server's 409 while a job is live): the normal two-step clear works (first click arms the confirm by design), but a confirm while a job is live -- e.g. the self-review follow-up that starts right after a send -- was refused by the server and the modal showed the raw code 'job_in_progress', so the chat looked like it would not clear on the first try. Now the server's sentence is shown, and the button is disabled (with a tooltip) while a send, resume or self-review is running. e2e scenarios 9, 9b (failed before), 9c (Firefox + Chromium). Co-Authored-By: Claude Opus 5.5 --- craft/scripts/e2e-sitesmith-mock-server.mjs | 24 +++++++- craft/scripts/e2e-sitesmith.mjs | 56 +++++++++++++++++++ craft/src/hooks/useSitesmith.ts | 2 +- craft/src/panels/sitesmith/SitesmithModal.tsx | 11 +++- 4 files changed, 86 insertions(+), 7 deletions(-) diff --git a/craft/scripts/e2e-sitesmith-mock-server.mjs b/craft/scripts/e2e-sitesmith-mock-server.mjs index 2dd4d37..920d469 100644 --- a/craft/scripts/e2e-sitesmith-mock-server.mjs +++ b/craft/scripts/e2e-sitesmith-mock-server.mjs @@ -127,6 +127,7 @@ export async function createMockServer(o) { uploads: [], // {fields, name, size, mime, id} imageDeletes: [], // ids refCalls: [], // {action, body} + clearCalls: [], // clear_history bodies saves: 0, }; @@ -153,6 +154,10 @@ export async function createMockServer(o) { const toResult = (r) => (r && typeof r === 'object' && 'ok' in r ? r : { ok: true, response: r }); + // Thread history as the server keeps it: the user turn at start, the answer when the job finishes. + const history = []; + const msg = (role, content, type = null) => ({ role, content, response_type: type, created_at: new Date().toISOString() }); + function newJob(result) { const id = crypto.randomBytes(8).toString('hex'); const job = { id, created: Math.floor(Date.now() / 1000), startedAt: Date.now(), step: 0, lastAdvance: 0, status: 'running', result: toResult(result ?? results.shift() ?? defaultResult()), polls: 0 }; @@ -200,7 +205,8 @@ export async function createMockServer(o) { release() { slow = false; for (const j of jobs.values()) if (j.status === 'running') j.step = PHASES.length - 1; }, /** Forget refs/images/jobs/recordings between scenarios (keeps knobs at their defaults). */ reset() { - for (const k of ['requests', 'starts', 'cancels', 'uploads', 'imageDeletes', 'refCalls']) s[k].length = 0; + for (const k of ['requests', 'starts', 'cancels', 'uploads', 'imageDeletes', 'refCalls', 'clearCalls']) s[k].length = 0; + history.length = 0; results.length = 0; jobs.clear(); images.clear(); refs = []; refSeq = 1; activeJobId = null; vision = true; phaseDelayMs = 300; slow = false; uploadFailStatus = 0; enabled = true; }, @@ -237,7 +243,7 @@ export async function createMockServer(o) { case 'history': { const aj = activeJobId ? jobs.get(activeJobId) : null; const live = aj && aj.status === 'running' ? jobView(aj) : null; - return json(res, 200, { ok: true, messages: [], active_job: live ? { job_id: live.job_id, status: live.status, phase: live.phase, elapsed_s: live.elapsed_s, created_at: live.created_at } : null }); + return json(res, 200, { ok: true, messages: history.slice(), active_job: live ? { job_id: live.job_id, status: live.status, phase: live.phase, elapsed_s: live.elapsed_s, created_at: live.created_at } : null }); } case 'job_active': { const aj = activeJobId ? jobs.get(activeJobId) : null; @@ -248,6 +254,7 @@ export async function createMockServer(o) { for (const j of jobs.values()) if (j.status === 'running') return json(res, 409, { ok: false, error: 'job_in_progress', status: 'JOB_IN_PROGRESS', message: 'Sitesmith is already working on a request for this site.', job_id: j.id }); const job = newJob(); activeJobId = job.id; + history.push(msg('user', String(body.message ?? ''))); return json(res, 200, { ok: true, job_id: job.id, status: 'running', phase: 'queued', created_at: job.created }); } case 'poll': { @@ -256,7 +263,11 @@ export async function createMockServer(o) { stepJob(job); const v = jobView(job); if (job.status === 'cancelled') return json(res, 200, { ...v, ok: true, result: { ok: false, status: 'CANCELLED', message: 'The request was cancelled.' } }); - if (job.status === 'done') { if (activeJobId === job.id) activeJobId = null; return json(res, 200, { ...v, ok: true, result: job.result }); } + if (job.status === 'done') { + if (activeJobId === job.id) activeJobId = null; + if (!job.logged) { job.logged = true; history.push(msg('assistant', JSON.stringify(job.result.response ?? job.result), job.result.response?.type ?? 'error')); } + return json(res, 200, { ...v, ok: true, result: job.result }); + } return json(res, 200, { ...v, ok: true, retry_after_ms: phaseDelayMs }); } case 'cancel': { @@ -316,6 +327,13 @@ export async function createMockServer(o) { res.statusCode = 200; res.setHeader('content-type', im.mime); res.setHeader('x-content-type-options', 'nosniff'); return res.end(im.bytes); } + case 'clear_history': { + s.clearCalls.push(body); + // the real endpoint refuses while a job is live (it would orphan the answer) + for (const j of jobs.values()) if (j.status === 'running') return json(res, 409, { ok: false, error: 'job_in_progress', message: 'Sitesmith is still working on your previous request for this site. Please wait for it to finish.' }); + const n = history.length; history.length = 0; + return json(res, 200, { ok: true, cleared: n }); + } case 'assets': return json(res, 200, { ok: true, assets: DEFAULT_ASSETS.map((a) => ({ filename: a.filename, relUrl: `assets/${a.filename}`, url: `/mock-assets/${a.filename}`, width: a.width, height: a.height, caption: a.caption, alt: a.alt })) }); default: diff --git a/craft/scripts/e2e-sitesmith.mjs b/craft/scripts/e2e-sitesmith.mjs index 926bfca..ea9b9c4 100644 --- a/craft/scripts/e2e-sitesmith.mjs +++ b/craft/scripts/e2e-sitesmith.mjs @@ -308,6 +308,62 @@ scenario('7', 'vision unavailable', async ({ page, name, ok }) => { ok('text-only send works end to end', srv.starts.length === 1 && !srv.starts[0].mockup_ids, JSON.stringify(srv.starts[0]?.mockup_ids)); }); +scenario('9', 'Clear chat: confirm clears the history (and stays cleared after reopening)', async ({ page, name, ok }) => { + srv.setNextResult(pageResult('Heading before clearing')); + await openModal(page); + await sendMsg(page, 'Please remember this line'); + await waitCanvas(page, 'Heading before clearing'); + const dlg = page.locator('[role=dialog]'); + await page.waitForFunction(() => (document.querySelector('[role=dialog]')?.textContent ?? '').includes('Please remember this line'), null, { timeout: 15000 }); + await page.waitForSelector('[role=dialog] button:has-text("Clear chat")', { timeout: 10000 }); + await page.click('[role=dialog] button:has-text("Clear chat")'); + ok('first click asks for confirmation (no request yet)', (await dlg.locator('button:has-text("Confirm clear?")').count()) === 1 && srv.clearCalls.length === 0, String(srv.clearCalls.length)); + await page.click('[role=dialog] button:has-text("Confirm clear?")'); + await page.waitForFunction(() => !(document.querySelector('[role=dialog]')?.textContent ?? '').includes('Please remember this line'), null, { timeout: 10000 }).catch(() => {}); + const txt = (await dlg.textContent()) ?? ''; + ok('confirm sends exactly one clear_history', srv.clearCalls.length === 1, String(srv.clearCalls.length)); + ok('the history is gone from the modal after the confirm', !txt.includes('Please remember this line'), txt.slice(0, 200)); + ok('no error shown', (await page.locator('[data-testid=ss-error]').count()) === 0); + await page.click('[role=dialog] button[aria-label=Close]'); + await openModal(page); + await page.waitForTimeout(800); + ok('still cleared after closing and reopening the modal', !(((await page.locator('[role=dialog]').textContent()) ?? '').includes('Please remember this line'))); + await modalShot(page, name, '09-cleared.png'); +}); + +scenario('9b', 'Clear chat while a job is running: a plain message, nothing lost', async ({ page, ok }) => { + srv.setNextResult(pageResult('First heading')); + await openModal(page); + await sendMsg(page, 'First request'); + await waitCanvas(page, 'First heading'); + await page.waitForSelector('[role=dialog] button:has-text("Clear chat")', { timeout: 10000 }); + srv.setActiveJob({ phase: 'generating' }); + srv.setSlow(true); + await page.click('[role=dialog] button:has-text("Clear chat")'); + await page.click('[role=dialog] button:has-text("Confirm clear?")'); + await page.waitForSelector('[data-testid=ss-error]', { timeout: 10000 }); + const err = (await page.textContent('[data-testid=ss-error]')) ?? ''; + ok('the refusal is a readable sentence, not an error code', /still working/i.test(err) && !/job_in_progress/.test(err), err); + srv.release(); +}); + +scenario('9c', 'Clear chat is disabled while Sitesmith is working', async ({ page, ok }) => { + srv.setNextResult(pageResult('Done heading')); + await openModal(page); + await sendMsg(page, 'One'); + await waitCanvas(page, 'Done heading'); + await page.waitForSelector('[data-testid=ss-clear-chat]:not([disabled])', { timeout: 10000 }); + srv.setSlow(true); + srv.setNextResult(pageResult('Later heading')); + await sendMsg(page, 'Two'); + await page.waitForSelector('[data-testid=ss-job-status]', { timeout: 10000 }); + ok('while a job runs the button is disabled', await page.locator('[data-testid=ss-clear-chat]').isDisabled()); + srv.release(); + await waitCanvas(page, 'Later heading'); + await page.waitForSelector('[data-testid=ss-clear-chat]:not([disabled])', { timeout: 10000 }); + ok('enabled again when the job has finished', true); +}); + scenario('8', 'self-review round trip (one round)', async ({ page, name, ok }) => { srv.setNextResult(pageResult('First pass heading', { id: 'fp-h' })); srv.setNextResult({ type: 'patch', message: 'Fixed spacing.', ops: [{ op: 'update_props', node_id: 'fp-h', props: { text: 'Reviewed heading' } }] }); diff --git a/craft/src/hooks/useSitesmith.ts b/craft/src/hooks/useSitesmith.ts index 0c8986c..7c62fe5 100644 --- a/craft/src/hooks/useSitesmith.ts +++ b/craft/src/hooks/useSitesmith.ts @@ -425,7 +425,7 @@ export function useSitesmith(siteId: number) { return pr; }, [activeJob, pollJob, finalize]); - const clearHistory = useCallback(async (): Promise<{ ok: boolean; cleared?: number; error?: string }> => { + const clearHistory = useCallback(async (): Promise<{ ok: boolean; cleared?: number; error?: string; message?: string }> => { if (!whpConfig) return { ok: false, error: 'No WHP config' }; try { const r = await fetch(`${apiBase(whpConfig.apiUrl)}?action=clear_history`, { diff --git a/craft/src/panels/sitesmith/SitesmithModal.tsx b/craft/src/panels/sitesmith/SitesmithModal.tsx index 7e2d731..9e0d3ef 100644 --- a/craft/src/panels/sitesmith/SitesmithModal.tsx +++ b/craft/src/panels/sitesmith/SitesmithModal.tsx @@ -100,6 +100,8 @@ export const SitesmithModal: React.FC = ({ onClose, target }) => { const canChat = !!summary && (summary.status === 'OK_BONUS' || summary.status === 'OK_MONTHLY'); const running = busy || !!activeJob; + /** Sitesmith has a live job (a send, a resume or the self-review follow-up): the server refuses clear_history then. */ + const working = running || reviewing; const wizardFired = useRef(false); useEffect(() => { @@ -335,7 +337,8 @@ export const SitesmithModal: React.FC = ({ onClose, target }) => { } cancelClearChat(); const r = await clearHistory(); - if (!r.ok) setError(r.error || 'Failed to clear history'); + // the server answers 409 job_in_progress while a job (e.g. the self-review follow-up) is live: show its sentence, never the code + if (!r.ok) setError(friendly(r.message || (r.error === 'job_in_progress' ? 'Sitesmith is still working on a request for this site. Clear the chat when it has finished.' : 'The chat could not be cleared. Please try again.'))); }; if (wantsWizard) return null; @@ -380,8 +383,10 @@ export const SitesmithModal: React.FC = ({ onClose, target }) => { ) : (