Files
ECC/scripts/hooks/plan-canvas-pending.js
T
haelyra 283c16aa4e feat(ui-canvas): add hand-editable UI mockup canvas with slider inspector
Add UI Canvas: an agent writes a self-contained HTML mockup, the human edits
it directly in the browser (select, resize, reorder, nudge, edit text,
remove, restyle), checks mobile, desktop, and exact viewports, chats with the
agent, and clicks Save and Finish to export the edited markup and an edit log.

- skills/ui-canvas, commands/ui-canvas.md, bin ecc-ui-canvas
  (scripts/ui-canvas.js), a profile over the Plan Canvas server via a
  session mode of 'ui'.
- scripts/lib/ui-canvas/{editor,feedback,ui,fields}.js: in-page editor,
  feedback normalization, browser shell, and inspector field helpers.
- Inspector: grouped slider rows (size, fill, text, spacing, border,
  effects); double-click any value to type it, sanitized and clamped before
  it reaches the mockup; HSL plus alpha color sliders; per-property clear.
- ECC green accent on near-black, no gradient branding; selection overlay
  is green.
- Plan Canvas: agent identity in presence, mode-aware server and hooks.

Editing conventions credit VisBug and Onlook; the review loop credits
lavish-axi by @kunchenguid.
2026-10-25 18:21:28 -04:00

287 lines
11 KiB
JavaScript

#!/usr/bin/env node
/**
* Plan Canvas and UI Canvas undelivered-feedback guard (Stop)
*
* Cross-platform (Windows, macOS, Linux)
*
* Browser feedback only reaches an agent while that agent is parked inside
* `ecc-plan-canvas await`. The moment a turn ends, nothing is listening, so
* messages the human sends land in sessions.json and stay there: the canvas
* looks alive, the agent never hears a word.
*
* This hook closes that gap. On Stop it drains any undelivered feedback for
* the current project and blocks the stop, handing the messages to the agent
* as its next input, so a canvas message is delivered even when no `await`
* was running.
*
* Scope: sessions whose artifact lives under the hook's cwd, so parallel
* agents in other repos cannot swallow a message meant for this one. Set
* ECC_PLAN_CANVAS_STOP_SCOPE=all to consider every open session.
*
* Never blocks on failure: any error, unreachable server, or undrainable
* queue exits 0 with stdin passed through.
*/
'use strict';
const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
// Loopback only, and short: a Stop hook must not stall the turn if the canvas
// server is wedged. Falling back to the state file keeps delivery working.
const SERVER_TIMEOUT_MS = 1000;
const MAX_ITEMS_REPORTED = 20;
const SESSION_KEY_PATTERN = /^[a-f0-9]{12}$/;
const LOOPBACK_HOST = '127.0.0.1';
function validServerPort(port) {
return Number.isInteger(port) && port >= 1 && port <= 65535;
}
function validSessionKey(key) {
return typeof key === 'string' && SESSION_KEY_PATTERN.test(key);
}
// Resolve the Claude profile directory the same way everywhere.
//
// Duplicated rather than imported on purpose: hooks ship in managed installs
// that carry top-level `scripts/` without `scripts/lib/` (see #3259), so a
// require into lib/ would make the hook unloadable there. `~` is expanded the
// way `scripts/lib/agent-data-home.js` expands it, so a profile written as
// `~/.claude-work` resolves to one place rather than two.
function claudeConfigDir() {
const configured = process.env.CLAUDE_CONFIG_DIR;
const trimmed = configured ? String(configured).trim() : '';
if (!trimmed) return path.join(os.homedir(), '.claude');
if (trimmed.startsWith('~')) {
const remainder = trimmed.slice(1).replace(/^[/\\]+/, '');
return remainder ? path.join(os.homedir(), remainder) : os.homedir();
}
return path.resolve(trimmed);
}
function stateDir() {
const override = process.env.ECC_PLAN_CANVAS_STATE_DIR;
if (override && override.trim()) return path.resolve(override.trim());
return path.join(claudeConfigDir(), 'plan-canvas');
}
function readState() {
try {
const parsed = JSON.parse(fs.readFileSync(path.join(stateDir(), 'sessions.json'), 'utf8'));
return parsed && typeof parsed === 'object' && parsed.sessions ? parsed : null;
} catch {
return null;
}
}
function readServerPort() {
try {
const info = JSON.parse(fs.readFileSync(path.join(stateDir(), 'server.json'), 'utf8'));
return info && !Array.isArray(info) && validServerPort(info.port) ? info.port : undefined;
} catch (error) {
// A missing locator permits offline delivery; malformed metadata does not
// establish that the server is down, so leave its queue untouched.
return error.code === 'ENOENT' ? null : undefined;
}
}
function isInside(dir, file) {
if (!dir) return true;
const base = path.resolve(dir);
const target = path.resolve(file);
return target === base || target.startsWith(base + path.sep);
}
/**
* Sessions holding feedback the agent has never seen, oldest activity first.
*/
function pendingSessions(state, cwd, env = process.env) {
const scopeAll = String(env.ECC_PLAN_CANVAS_STOP_SCOPE || '').trim().toLowerCase() === 'all';
return Object.values((state && state.sessions) || {})
.filter(session => session && validSessionKey(session.key) && typeof session.file === 'string' && session.file.length > 0 && session.status !== 'ended')
.filter(session => Array.isArray(session.pendingFeedback) && session.pendingFeedback.length > 0)
.filter(session => (scopeAll ? true : isInside(cwd, session.file)))
.sort((a, b) => String(a.updatedAt || '').localeCompare(String(b.updatedAt || '')));
}
/**
* Ask the running server to hand over the batch. The server owns sessions.json
* while it is up, so this is the only race-free way to drain. timeoutMs=0
* makes /api/await return immediately instead of long polling.
*/
function drainViaServer(port, key) {
// Expected local IPC: server.json locates the bound loopback port; the only
// file-derived query value is a non-secret 12-hex artifact identifier.
// Validate at the HTTP boundary as well as during session selection.
if (!validServerPort(port) || !validSessionKey(key)) return Promise.resolve(null);
return new Promise(resolve => {
const req = http.request(
{
host: LOOPBACK_HOST,
port,
method: 'GET',
path: `/api/await?key=${key}&timeoutMs=0`,
agent: false
},
res => {
if (res.statusCode !== 200) {
res.resume();
resolve(null);
return;
}
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
try {
const parsed = JSON.parse(data.trim() || '{}');
resolve(parsed.status === 'feedback' && Array.isArray(parsed.items) ? parsed : null);
} catch {
resolve(null);
}
});
}
);
req.setTimeout(SERVER_TIMEOUT_MS, () => {
req.destroy();
resolve(null);
});
req.on('error', () => resolve(null));
req.end();
});
}
/**
* Drain straight from disk. Only safe when no server is listening, which is
* exactly when this path runs: with the server down nothing else mutates the
* file, and leaving the items queued would re-block on every future Stop.
*/
function drainViaFile(key) {
const file = path.join(stateDir(), 'sessions.json');
try {
const state = JSON.parse(fs.readFileSync(file, 'utf8'));
const session = state.sessions && state.sessions[key];
if (!session || !Array.isArray(session.pendingFeedback) || session.pendingFeedback.length === 0) {
return null;
}
const items = session.pendingFeedback;
const sessionEnded = session.status === 'ended';
session.pendingFeedback = [];
if (!sessionEnded) session.status = 'open';
session.updatedAt = new Date().toISOString();
const tmp = `${file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
fs.renameSync(tmp, file);
return { status: 'feedback', items, sessionEnded };
} catch {
return null;
}
}
function describeItem(item) {
if (!item || typeof item !== 'object') return null;
if (item.kind === 'verdict') {
const label = item.verdict === 'approve' ? 'APPROVED the plan' : 'REQUESTED CHANGES';
return item.text ? `${label}: ${item.text}` : label;
}
if (item.kind === 'annotation') {
const anchor = item.anchor || {};
const where = anchor.snippet || anchor.selector || 'the artifact';
return item.text ? `on "${where}": ${item.text}` : null;
}
// UI Canvas batches: the snapshot lives on disk; only paths travel here.
if (item.kind === 'finish' || item.kind === 'edits') {
const count = Number(item.editCount) || (Array.isArray(item.edits) ? item.edits.length : 0);
const label = item.kind === 'finish' ? 'SAVED AND FINISHED' : 'APPLIED EDITS TO THE PREVIEW';
const where = [item.exportPath ? `final markup: ${item.exportPath}` : null, item.editsPath ? `edit log: ${item.editsPath}` : null]
.filter(Boolean)
.join(', ');
return `${label} (${count} edit${count === 1 ? '' : 's'})${where ? ` - ${where}` : ''}${item.text ? `: ${item.text}` : ''}`;
}
if (item.kind === 'chat' && item.anchor && item.text) {
const where = item.anchor.snippet || item.anchor.selector;
return where ? `on "${where}": ${item.text}` : item.text;
}
return item.text || null;
}
function buildReason(delivered) {
const allUi = delivered.length > 0 && delivered.every(entry => entry.mode === 'ui');
const lines = [
`${allUi ? 'UI Canvas' : 'Plan Canvas'}: the human sent feedback in the browser that was never delivered to you.`,
'Handle it now instead of ending the turn.',
''
];
for (const entry of delivered) {
const bin = entry.mode === 'ui' ? 'ecc-ui-canvas' : 'ecc-plan-canvas';
lines.push(`Artifact: ${entry.file}`);
for (const text of entry.messages.slice(0, MAX_ITEMS_REPORTED)) lines.push(` - ${text}`);
const extra = entry.messages.length - MAX_ITEMS_REPORTED;
if (extra > 0) lines.push(` - (+${extra} more)`);
if (entry.sessionEnded && entry.mode === 'ui') {
lines.push(' The user saved and finished (or ended) this preview after sending. Read the exported markup');
lines.push(' named above, reproduce that exact design in the real component, and report back in your');
lines.push(' normal reply; do not reopen the canvas.');
} else if (entry.sessionEnded) {
lines.push(' The user ended this review after sending. Address the feedback and report back in');
lines.push(' your normal reply; do not reopen the canvas.');
} else {
lines.push(' Reply IN THE CANVAS so the human sees it, and keep listening, with one command:');
lines.push(` ${bin} await ${JSON.stringify(entry.file)} --reply "<what you did>"`);
}
lines.push('');
}
lines.push('Run that await in the background so the next message reaches you without another Stop.');
return lines.join('\n');
}
async function collectDeliveries(sessions, port) {
const delivered = [];
for (const session of sessions) {
const result = port ? await drainViaServer(port, session.key) : drainViaFile(session.key);
// A failed drain is deliberately not reported: blocking on feedback that
// is still queued would re-fire on every subsequent Stop.
if (!result) continue;
const messages = result.items.map(describeItem).filter(Boolean);
if (messages.length === 0) continue;
delivered.push({ file: session.file, mode: session.mode === 'ui' ? 'ui' : 'plan', messages, sessionEnded: Boolean(result.sessionEnded) });
}
return delivered;
}
async function run(rawInput) {
const passThrough = { stdout: rawInput || '', exitCode: 0 };
let payload = {};
try {
payload = JSON.parse(rawInput || '{}');
} catch {
return passThrough;
}
// The harness sets this once it has already resumed the agent from a Stop
// hook. Blocking again from here is how a hook wedges a session.
if (payload.stop_hook_active) return passThrough;
const state = readState();
if (!state) return passThrough;
const sessions = pendingSessions(state, payload.cwd || process.cwd());
if (sessions.length === 0) return passThrough;
const port = readServerPort();
if (port === undefined) return passThrough;
const delivered = await collectDeliveries(sessions, port);
if (delivered.length === 0) return passThrough;
return {
stdout: JSON.stringify({ decision: 'block', reason: buildReason(delivered) }),
exitCode: 0
};
}
module.exports = { run, pendingSessions, describeItem, buildReason, drainViaFile, drainViaServer };