'use strict'; /** * UI Canvas browser shell: the chrome around the mockup iframe. * * Top bar: viewport presets (desktop, mobile, exact dimensions), edit versus * interact mode, agent presence, undo/redo, Save and Finish. Right rail: * inspector for the selected element (breadcrumb, size, style chips), * the pending edit log, and the conversation with the agent. The mockup * renders at its true CSS pixel size inside a sandboxed iframe and is scaled * down only when the stage is too small, so media queries behave exactly as * they would in production. * * Same design tokens as Plan Canvas and the ECC dashboard. Everything is * served inline; no CDNs. */ 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'); const ICONS = { desktop: '', mobile: '', custom: '', rotate: '', undo: '', redo: '', pause: '', play: '', reload: '', sun: '', moon: '', check: '' }; // Client logic for the shell page (runs in the top window). function uiClientJs() { return String.raw`'use strict'; (() => { const boot = JSON.parse(document.getElementById('uc-session').textContent); const key = boot.key; const PRESETS = boot.presets; const $ = id => document.getElementById(id); const frame = $('artifact'); const device = $('device'); const sizer = $('sizer'); const stage = $('stage'); const viewportEl = $('viewportArea'); const chatLog = $('chatLog'); const input = $('chatInput'); const sendBtn = $('send'); const statusEl = $('sendStatus'); const presence = $('presence'); const hintEl = $('hint'); const readoutEl = $('readout'); const STORE = 'ecc-ui-canvas:' + key; let ended = boot.status === 'ended'; let sending = false; let finishing = false; let mode = 'edit'; let frameReady = false; let selection = null; let anchorEnabled = true; let lastScroll = { x: 0, y: 0 }; let paused = false; let agent = boot.agent || null; let canUndo = false; let canRedo = false; let exportSeq = 0; const exportWaiters = new Map(); const confirmTimers = new Map(); // --- persisted shell state ------------------------------------------------ function readStore() { try { return JSON.parse(sessionStorage.getItem(STORE) || 'null') || {}; } catch (_e) { return {}; } } function writeStore(patch) { try { const next = Object.assign(readStore(), patch); sessionStorage.setItem(STORE, JSON.stringify(next)); } catch (_e) { /* storage blocked: the canvas still works for this page load */ } } const stored = readStore(); const acknowledged = new Set((boot.uiAcknowledged || []).map(batch => batch.id)); const acknowledgedEdits = new Set((boot.uiAcknowledged || []).flatMap(batch => batch.editIds)); let submitted = Array.isArray(boot.uiBatches) ? boot.uiBatches : []; const acceptedEdits = new Set(submitted.flatMap(batch => batch.edits.map(edit => edit.id))); let edits = (Array.isArray(stored.edits) ? stored.edits : []).filter(edit => !acceptedEdits.has(edit.id) && !acknowledgedEdits.has(edit.id)); // Older shells stored only a flat submitted log, with no proof of whether // the file already contains it. Recover it visibly without replaying it. for (const edit of Array.isArray(stored.submitted) ? stored.submitted : []) { if (!acceptedEdits.has(edit.id) && !acknowledgedEdits.has(edit.id)) edits.push({ ...edit, stale: true, unverified: true }); } let deliveryRequest = null; function persistEdits() { writeStore({ edits, submittedBatches: submitted, submitted: [] }); } persistEdits(); ${deliveryClientJs()} // --- theme -------------------------------------------------------------------- const themeKey = 'ecc-plan-canvas:theme'; function applyTheme(t) { if (t === 'light') document.documentElement.setAttribute('data-theme', 'light'); else document.documentElement.removeAttribute('data-theme'); const label = t === 'light' ? 'Switch to dark theme' : 'Switch to light theme'; $('themeBtn').title = label; $('themeBtn').setAttribute('aria-label', label); } let theme = (() => { try { return localStorage.getItem(themeKey); } catch (_e) { return null; } })() || 'dark'; applyTheme(theme); $('themeBtn').addEventListener('click', () => { theme = theme === 'light' ? 'dark' : 'light'; try { localStorage.setItem(themeKey, theme); } catch (_e) { /* blocked */ } applyTheme(theme); }); // --- viewport ------------------------------------------------------------------ const clampDim = n => Math.max(100, Math.min(20000, Math.round(Number(n)) || 100)); function parseViewport(spec) { const custom = typeof spec === 'string' ? spec.match(/^(\d{2,5})x(\d{2,5})$/) : null; if (custom) return { preset: 'custom', width: clampDim(custom[1]), height: clampDim(custom[2]) }; if (spec === 'mobile' || spec === 'custom') return { preset: spec, width: PRESETS[spec].width, height: PRESETS[spec].height }; return { preset: 'desktop', width: PRESETS.desktop.width, height: PRESETS.desktop.height }; } // sessionStorage is editable by hand; only trust a well-formed viewport. function storedViewport(v) { if (!v || ['desktop', 'mobile', 'custom'].indexOf(v.preset) < 0) return null; return { preset: v.preset, width: clampDim(v.width), height: clampDim(v.height), rotated: Boolean(v.rotated) }; } let vp = storedViewport(stored.viewport) || parseViewport(boot.ui && boot.ui.viewport); let actual = { width: vp.width, height: vp.height, scale: 1 }; function layoutStage() { const rect = viewportEl.getBoundingClientRect(); const pad = 24; const availW = Math.max(120, rect.width - pad * 2); const availH = Math.max(120, rect.height - pad * 2); let width = vp.width; let height = vp.height; if (vp.preset === 'desktop') { width = Math.max(320, Math.floor(availW)); height = Math.max(240, Math.floor(availH)); } const bezel = vp.preset === 'mobile' ? 12 : 0; const outerW = width + bezel * 2; const outerH = height + bezel * 2; const scale = vp.preset === 'desktop' ? 1 : Math.min(1, availW / outerW, availH / outerH); device.className = 'device ' + vp.preset; device.style.width = outerW + 'px'; device.style.height = outerH + 'px'; device.style.transform = 'scale(' + scale + ')'; sizer.style.width = Math.round(outerW * scale) + 'px'; sizer.style.height = Math.round(outerH * scale) + 'px'; actual = { width, height, scale }; $('vpW').value = width; $('vpH').value = height; $('vpScale').textContent = scale < 0.995 ? Math.round(scale * 100) + '%' : ''; readoutEl.textContent = width + ' × ' + height + (scale < 0.995 ? ' · shown at ' + Math.round(scale * 100) + '%' : ''); document.querySelectorAll('.seg.viewports button').forEach(b => b.setAttribute('aria-pressed', String(b.getAttribute('data-vp') === vp.preset))); $('rotateBtn').disabled = vp.preset === 'desktop'; writeStore({ viewport: vp }); } document.querySelectorAll('.seg.viewports button').forEach(btn => { btn.addEventListener('click', () => { const preset = btn.getAttribute('data-vp'); if (preset === vp.preset) return; if (preset === 'custom') vp = { preset: 'custom', width: vp.preset === 'desktop' ? actual.width : vp.width, height: vp.preset === 'desktop' ? actual.height : vp.height }; else vp = parseViewport(preset); layoutStage(); }); }); function applyDims() { const width = Math.max(100, Math.min(20000, parseInt($('vpW').value, 10) || actual.width)); const height = Math.max(100, Math.min(20000, parseInt($('vpH').value, 10) || actual.height)); vp = { preset: 'custom', width, height }; layoutStage(); } [$('vpW'), $('vpH')].forEach(box => { box.addEventListener('input', () => { const clean = box.value.replace(/[^0-9]/g, '').slice(0, 5); if (clean !== box.value) box.value = clean; }); box.addEventListener('change', applyDims); box.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); applyDims(); box.blur(); } else if (e.key === 'Escape') { e.preventDefault(); layoutStage(); box.blur(); } else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { e.preventDefault(); box.value = String((parseInt(box.value, 10) || 0) + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1)); applyDims(); } }); }); $('rotateBtn').addEventListener('click', () => { if (vp.preset === 'desktop') return; vp = { preset: vp.preset, width: vp.height, height: vp.width, rotated: !vp.rotated }; layoutStage(); }); if (window.ResizeObserver) new ResizeObserver(() => layoutStage()).observe(viewportEl); window.addEventListener('resize', layoutStage); layoutStage(); // --- mode ----------------------------------------------------------------------- const HINTS = { edit: 'Click to select · double-click edits text · drag handles to resize · drag to reorder · Alt-drag or arrows nudge · Delete removes', interact: 'Interact mode: clicks, hovers and taps reach the component. Switch back to Edit to change things.' }; function setMode(next) { if (finishing) return; mode = next === 'interact' ? 'interact' : 'edit'; document.querySelectorAll('.seg.modes button').forEach(b => b.setAttribute('aria-pressed', String(b.getAttribute('data-mode') === mode))); stage.setAttribute('data-mode', mode); setHint(''); postToFrame({ type: 'uc:set-mode', mode }); } document.querySelectorAll('.seg.modes button').forEach(btn => btn.addEventListener('click', () => setMode(btn.getAttribute('data-mode')))); function setHint(text) { hintEl.classList.toggle('live', Boolean(text)); hintEl.textContent = text || HINTS[mode]; } setHint(''); // --- frame bridge ---------------------------------------------------------------- function postToFrame(msg) { if (finishing && ['uc:style', 'uc:size', 'uc:remove', 'uc:edit-text', 'uc:undo', 'uc:redo', 'uc:reset'].includes(msg.type)) return; if (frame.contentWindow) frame.contentWindow.postMessage(msg, '*'); } function requestExport() { return new Promise((resolve, reject) => { const requestId = 'x' + (++exportSeq); exportWaiters.set(requestId, resolve); deliveryRequest = requestId; postToFrame({ type: 'uc:export', requestId, lock: true }); setTimeout(() => { if (exportWaiters.delete(requestId)) reject(new Error('the preview did not answer; reload and try again')); }, 5000); }); } window.addEventListener('message', e => { if (e.source !== frame.contentWindow) return; const msg = e.data || {}; if (typeof msg.type !== 'string') return; switch (msg.type) { 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, 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': selection = msg.selection || null; if (selection) anchorEnabled = true; renderInspector(); renderAnchor(); break; case 'uc: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 }); renderEdits(); break; case 'uc:status': setHint(msg.text || ''); break; case 'uc:toggle-mode': setMode(mode === 'edit' ? 'interact' : 'edit'); break; case 'uc:scroll': lastScroll = { x: msg.x || 0, y: msg.y || 0 }; break; case 'uc:export': { const resolve = exportWaiters.get(msg.requestId); if (resolve) { exportWaiters.delete(msg.requestId); resolve(msg); } break; } default: break; } }); viewportEl.addEventListener('mousedown', e => { if (e.target === viewportEl && mode === 'edit') postToFrame({ type: 'uc:deselect' }); }); ${inspectorClientJs()} // --- edit log ----------------------------------------------------------------------- function summarize(edit) { const target = edit.selector + (edit.snippet ? ' “' + edit.snippet.slice(0, 40) + (edit.snippet.length > 40 ? '…' : '') + '”' : ''); switch (edit.kind) { case 'text': return target + ': “' + (edit.before || '').slice(0, 40) + '” → “' + (edit.after || '').slice(0, 60) + '”'; case 'resize': return target + ' → ' + (edit.width !== undefined ? edit.width + 'w' : '') + (edit.width !== undefined && edit.height !== undefined ? ' × ' : '') + (edit.height !== undefined ? edit.height + 'h' : '') + (edit.before ? ' (was ' + edit.before.width + ' × ' + edit.before.height + ')' : ''); case 'move': return target + ' → ' + (edit.to && edit.to.parent ? edit.to.parent : 'parent') + ' at ' + (edit.to ? edit.to.index : '?'); case 'nudge': return target + ' by ' + edit.dx + ', ' + edit.dy + 'px'; case 'remove': return target; case 'style': return target + ' ' + edit.property + (edit.after === null ? ' removed' : ' → ' + edit.after) + (edit.before ? ' (was ' + shortValue(edit.before) + ')' : ''); default: return target; } } function renderEdits() { const list = $('editList'); list.innerHTML = ''; $('editCount').textContent = String(edits.length); $('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 || !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'; empty.textContent = 'Your changes to the preview collect here. Apply sends them to the agent to bake into the file; Save and Finish hands over the final design.'; list.appendChild(empty); return; } for (const edit of edits) { const row = document.createElement('div'); row.className = 'edit kind-' + edit.kind + (edit.stale ? ' stale' : ''); const k = document.createElement('span'); k.className = 'k'; k.textContent = edit.kind; const s = document.createElement('span'); s.className = 's'; s.textContent = summarize(edit); row.title = (edit.stale ? 'Could not be re-applied after the last reload.\n' : '') + summarize(edit); row.append(k, s); list.appendChild(row); } list.scrollTop = list.scrollHeight; } $('undoBtn').addEventListener('click', () => postToFrame({ type: 'uc:undo' })); $('redoBtn').addEventListener('click', () => postToFrame({ type: 'uc:redo' })); function twoStep(btn, label, action) { if (confirmTimers.has(btn)) { clearTimeout(confirmTimers.get(btn)); confirmTimers.delete(btn); btn.classList.remove('confirm'); btn.textContent = btn.getAttribute('data-label'); action(); return; } btn.setAttribute('data-label', btn.textContent); btn.textContent = label; btn.classList.add('confirm'); confirmTimers.set(btn, setTimeout(() => { confirmTimers.delete(btn); btn.classList.remove('confirm'); btn.textContent = btn.getAttribute('data-label'); }, 3000)); } $('resetBtn').addEventListener('click', () => twoStep($('resetBtn'), 'Revert all?', () => postToFrame({ type: 'uc:reset' }))); $('pauseBtn').addEventListener('click', () => { paused = !paused; $('pauseBtn').setAttribute('aria-pressed', String(paused)); postToFrame({ type: 'uc:pause-animations', paused }); }); // --- conversation --------------------------------------------------------------------- const typingEl = document.createElement('div'); typingEl.className = 'typing'; typingEl.setAttribute('role', 'status'); const dots = document.createElement('span'); dots.className = 'dots'; dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i')); const typingLabel = document.createElement('span'); typingLabel.className = 'label'; typingEl.append(dots, typingLabel); const stalledEl = document.createElement('div'); stalledEl.className = 'stalled'; stalledEl.setAttribute('role', 'status'); function agentName() { return (agent && agent.name) || 'agent'; } function renderActivity(state) { const typingText = state === 'thinking' ? agentName() + ' is working on it…' : state === 'typing' ? agentName() + ' is typing…' : ''; typingEl.classList.toggle('show', Boolean(typingText)); if (typingText) typingLabel.textContent = typingText; const stalled = state === 'queued'; stalledEl.classList.toggle('show', stalled); if (stalled) stalledEl.textContent = 'Queued. ' + agentName() + ' is not listening right now and picks this up the moment it checks in.'; if (typingText || stalled) scrollToEnd(); } function atBottom() { return chatLog.scrollHeight - chatLog.scrollTop - chatLog.clientHeight < 40; } function scrollToEnd() { chatLog.scrollTop = chatLog.scrollHeight; } function renderChat(entries) { const pinned = atBottom(); chatLog.innerHTML = ''; if (!entries.length) { const empty = document.createElement('div'); empty.className = 'empty'; empty.textContent = 'Select something and describe the change, or just type. Your agent answers here and the preview updates when it edits the file.'; chatLog.appendChild(empty); } else { for (const entry of entries) { const div = document.createElement('div'); div.className = 'msg ' + (entry.role === 'agent' ? 'agent' : 'user') + ' kind-' + (entry.kind || 'chat'); div.textContent = entry.text; const meta = document.createElement('span'); meta.className = 'meta'; meta.textContent = (entry.role === 'agent' ? agentName() : 'you') + ' · ' + new Date(entry.at).toLocaleTimeString(); div.appendChild(meta); chatLog.appendChild(div); } } chatLog.appendChild(typingEl); chatLog.appendChild(stalledEl); if (pinned) scrollToEnd(); } renderChat(boot.chat || []); function renderAnchor() { const show = Boolean(selection) && anchorEnabled; $('anchorChip').hidden = !show; if (show) $('anchorText').textContent = selection.selector; input.placeholder = show ? 'Describe the change to ' + selection.tag + (selection.snippet ? ' “' + selection.snippet.slice(0, 30) + '”' : '') + '…' : 'Ask your agent for a change… Enter to send, Shift+Enter for a new line'; } $('anchorClear').addEventListener('click', () => { anchorEnabled = false; renderAnchor(); }); 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), ...(deliveryId ? { deliveryId } : {}) }) }); if (!res.ok) { const body = await res.json().catch(() => ({})); throw Object.assign(new Error(body.error || ('HTTP ' + res.status)), { definitive: true }); } return res.json(); } function pendingSummaries() { return edits.filter(e => !e.stale).slice(-30).map(summarize); } function describeDelivery(body) { return body.presence === 'thinking' || body.presence === 'typing' || body.presence === 'listening' ? 'Delivered. ' + agentName() + ' has it.' : 'Queued. ' + agentName() + ' picks this up the moment it checks in.'; } async function sendChat() { if (ended || sending) return; const draft = input.value; const text = draft.trim(); if (!text) { statusEl.textContent = 'Type a message first.'; return; } const item = { kind: 'chat', text }; if (selection && anchorEnabled) item.anchor = { selector: selection.selector, tag: selection.tag, snippet: selection.snippet, size: selection.size }; const summaries = pendingSummaries(); if (summaries.length) item.pendingEdits = summaries; sending = true; sendBtn.disabled = true; statusEl.textContent = 'Sending…'; try { const body = await postFeedback([item], false); if (input.value === draft) input.value = ''; statusEl.textContent = describeDelivery(body); if (body.presence) applyPresence(body.presence, agent); } catch (err) { statusEl.textContent = 'Send failed (' + err.message + ').'; } finally { sending = false; sendBtn.disabled = ended; } } sendBtn.addEventListener('click', sendChat); input.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChat(); } }); function freezeForFinish(active) { finishing = active; stage.inert = active; $('groups').inert = active; $('selBody').inert = active; input.disabled = ended || active; $('editTextBtn').disabled = ended || active || !selection || !selection.editable; $('removeBtn').disabled = ended || active; postToFrame({ type: 'uc:set-mode', mode: active ? 'interact' : mode }); } async function sendEdits(kind) { if (ended || sending) return; 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; } const draft = input.value; if (kind === 'finish') freezeForFinish(true); sending = true; sendBtn.disabled = true; $('applyBtn').disabled = true; $('finishBtn').disabled = true; statusEl.textContent = kind === 'finish' ? 'Saving the final design…' : 'Capturing the preview…'; try { 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 (!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 = body.acceptedEditIds; submitted = submitted.concat((body.batches || []).filter(batch => !acknowledged.has(batch.id))); edits = edits.filter(edit => !ids.includes(edit.id)); persistEdits(); 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) { 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, retryPending: Boolean(pendingDelivery), editIds: [] }); if (!pendingDelivery) deliveryRequest = null; } if (kind === 'finish' && !ended && !pendingDelivery) freezeForFinish(false); sending = false; sendBtn.disabled = ended; $('finishBtn').disabled = ended; renderEdits(); } } $('applyBtn').addEventListener('click', () => sendEdits('edits')); $('finishBtn').addEventListener('click', () => sendEdits('finish')); // --- session controls -------------------------------------------------------------------- $('endBtn').addEventListener('click', () => twoStep($('endBtn'), 'End without saving?', async () => { try { await fetch('/api/session/' + key + '/end', { method: 'POST' }); } catch (_e) { /* server gone */ } })); function reloadArtifact() { frameReady = false; const base = frame.getAttribute('data-artifact-src'); frame.src = base + '?t=' + Date.now(); } $('reloadBtn').addEventListener('click', reloadArtifact); function markEnded(endedBy) { ended = true; sendBtn.disabled = true; input.disabled = true; $('finishBtn').disabled = true; $('applyBtn').disabled = true; renderActivity('ended'); presence.setAttribute('data-state', 'ended'); presence.querySelector('.label').textContent = 'session ended'; const overlay = $('endedOverlay'); overlay.classList.add('show'); const finished = endedBy === 'finished'; $('endedTitle').textContent = finished ? 'Saved and handed to ' + agentName() : 'Session ended'; $('endedWho').textContent = finished ? 'Your edits and the final markup are on their way. The agent wires them into the real component next. You can close this tab.' : endedBy === 'agent' ? 'Your agent closed this preview.' : 'You ended this preview. Head back to your agent session.'; $('endedIcon').hidden = !finished; postToFrame({ type: 'uc:set-mode', mode: 'interact' }); 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) { const name = agentName(); return { waiting: name === 'agent' ? 'agent not connected' : name + ' not connected', listening: name + ' listening', thinking: name + ' is working…', typing: name + ' is typing…', queued: 'queued for ' + name, ended: 'session ended' }[state] || state; } function applyPresence(state, who) { if (ended) return; if (who && who.name) agent = who; presence.setAttribute('data-state', state); presence.querySelector('.label').textContent = presenceLabel(state); presence.title = agent && agent.project ? agentName() + ' in ' + agent.project : ''; renderActivity(state); } function connectEvents() { const es = new EventSource('/events/' + key); es.addEventListener('chat-sync', e => renderChat(JSON.parse(e.data).chat || [])); es.addEventListener('presence', e => { const data = JSON.parse(e.data); applyPresence(data.state, data.agent); }); es.addEventListener('ui-ack', e => { const data = JSON.parse(e.data); 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)); edits = edits.filter(edit => !editIds.has(edit.id)); persistEdits(); renderEdits(); if (changed && frameReady) reloadArtifact(); }); // An unrelated agent save is not acknowledgment of queued Apply batches. es.addEventListener('reload', reloadArtifact); 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'); presence.setAttribute('data-state', 'waiting'); presence.querySelector('.label').textContent = 'canvas server offline'; }; } connectEvents(); // --- shell keyboard ------------------------------------------------------------------------- document.addEventListener('keydown', e => { const tag = (e.target && e.target.tagName) || ''; const typing = tag === 'INPUT' || tag === 'TEXTAREA'; const meta = e.metaKey || e.ctrlKey; if (meta && e.key.toLowerCase() === 'i') { e.preventDefault(); setMode(mode === 'edit' ? 'interact' : 'edit'); return; } if (typing) return; if (meta && e.key.toLowerCase() === 'z') { e.preventDefault(); postToFrame({ type: e.shiftKey ? 'uc:redo' : 'uc:undo' }); return; } }); renderInspector(); renderEdits(); renderAnchor(); })();`; } // The shell page: header bar, staged mockup iframe, inspector + edits + chat rail. function renderUiCanvasHtml(session, { clientPath = '/ui-client.js', cssPath = '/ui-canvas.css' } = {}) { const name = path.basename(session.file); const title = session.ui && session.ui.title ? session.ui.title : name; const bootstrap = JSON.stringify({ key: session.key, file: session.file, status: session.status, endedBy: session.endedBy || null, chat: session.chat, agent: session.agent || null, ui: session.ui || { viewport: 'desktop', title: '' }, uiBatches: session.uiBatches || [], uiAcknowledged: session.uiAcknowledged || [], uiDeliveries: session.uiDeliveries || {}, presets: VIEWPORT_PRESETS }).replace(/ ${escapeHtml(title)} · UI Canvas
UI Canvas ${escapeHtml(name)}
×
agent not connected
⌘Z undo⌘I mode⌫ remove

Session ended

`; } module.exports = { ICONS, renderUiCanvasHtml, uiCanvasCss, uiClientJs };