mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 00:05:27 +00:00
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.
This commit is contained in:
49 files changed
+5216
-81
No files matched your search
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: ui-canvas
|
||||
description: Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You then turn the exported edited markup into the production component. Use before committing or rebuilding a feature just to check a visual change.
|
||||
metadata:
|
||||
origin: ECC
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# UI Canvas
|
||||
|
||||
Approve-before-you-build loop for user interface work: you write a quick,
|
||||
self-contained HTML mockup of the component, the human opens it in the
|
||||
browser and adjusts it by hand like a website builder, and **Save and
|
||||
Finish** hands you the exact result to wire into the real code. Nobody has to
|
||||
rebuild and rerun the whole app to check a padding change.
|
||||
|
||||
Any component qualifies: a card, a sidebar, a modal, a settings pane, a
|
||||
single button state, an animation, a page section. Any harness qualifies:
|
||||
the loop is a CLI that prints JSON.
|
||||
|
||||
Shares its server, state, and hooks with `plan-canvas` (inspired by
|
||||
[lavish-axi](https://github.com/kunchenguid/lavish-axi) by @kunchenguid).
|
||||
Editing conventions follow
|
||||
[VisBug](https://github.com/GoogleChromeLabs/ProjectVisBug) and
|
||||
[Onlook](https://github.com/onlook-dev/onlook): Enter/Shift+Enter walk the
|
||||
tree, Delete removes, an edit/interact mode switch.
|
||||
|
||||
## When to Use
|
||||
|
||||
- The user asks to redesign, restyle, or add a UI component and wants to see
|
||||
it before you commit, rerun, or rebuild.
|
||||
- Feedback is visual ("make it tighter", "move that up", "lose the border")
|
||||
and is faster done by hand than typed.
|
||||
- Mobile and desktop both matter and the user wants to check the component
|
||||
at exact dimensions.
|
||||
- The user asks for `/ui-canvas`, a preview, a mockup, "show me first".
|
||||
|
||||
Do NOT use for: plan or document review (`/plan-canvas`), running the real
|
||||
app, remote URLs, or components you cannot render as plain HTML/CSS/JS in one
|
||||
file. The canvas serves local files only.
|
||||
|
||||
## How It Works
|
||||
|
||||
Invoke the CLI as `ecc-ui-canvas` (bin from the `ecc-universal` package, on
|
||||
PATH after a global or plugin install; `node "$CLAUDE_PLUGIN_ROOT/scripts/ui-canvas.js"`
|
||||
also works). It runs the same detached loopback server as `plan-canvas`
|
||||
(`127.0.0.1:4517`), keyed by artifact path; there are no session ids.
|
||||
|
||||
### 1. Write the mockup
|
||||
|
||||
Write one self-contained `.html` file (for example `.claude/previews/<name>.html`
|
||||
or next to the component): markup, a `<style>` block, and any `<script>` the
|
||||
component needs to behave (tabs, toggles, open/close, animation). Rules:
|
||||
|
||||
- Use the project's real brand tokens, fonts, copy, and realistic data. Read
|
||||
the existing CSS or theme file first; do not invent a palette.
|
||||
- Give meaningful elements an `id` or a distinctive class. The canvas records
|
||||
every human edit against a CSS selector; stable names make the export map
|
||||
cleanly back to your code.
|
||||
- Keep it faithful to production: same breakpoints, same `max-width`, same
|
||||
states. The canvas renders at true CSS-pixel viewport sizes, so media
|
||||
queries behave exactly as they would in the app.
|
||||
- Sibling assets (images, fonts) may sit next to the file and be referenced by
|
||||
relative path; a `data:` URI or an inline SVG also works.
|
||||
- Inline only what the component needs. A mockup is a sketch, not the app.
|
||||
|
||||
### 2. Open and listen
|
||||
|
||||
```bash
|
||||
ecc-ui-canvas open .claude/previews/pricing-card.html --viewport desktop --title "Pricing card"
|
||||
ecc-ui-canvas await .claude/previews/pricing-card.html # run in the background; leave it running
|
||||
```
|
||||
|
||||
`--viewport` takes `mobile` (393×852), `desktop` (fills the window), `custom`,
|
||||
or exact `WxH` such as `1024x768`. Run `await` in the background if your
|
||||
harness time-limits foreground commands; re-run it if interrupted, queued
|
||||
feedback is never lost. While it runs, the canvas shows "<your harness>
|
||||
listening" so the human knows you are connected.
|
||||
|
||||
### 3. Handle what comes back
|
||||
|
||||
`await` prints JSON when the human acts. Items:
|
||||
|
||||
```json
|
||||
{ "kind": "chat", "text": "change this to dark gray in the brand colors",
|
||||
"anchor": { "selector": "#pricing-card", "tag": "article", "snippet": "Most popular Team plan…", "size": { "width": 720, "height": 388 } },
|
||||
"pendingEdits": ["resized img.art to 220px wide, 220px tall (was 260×260)", "removed button.btn.secondary"] }
|
||||
```
|
||||
|
||||
- `chat` is a request. `anchor` is the element the human had selected when
|
||||
they sent it; `pendingEdits` summarizes hand edits they have made that are
|
||||
**not yet in your file**. Make the requested change in the mockup file.
|
||||
The preview reloads within a second and re-applies their pending edits on
|
||||
top, so do **not** bake `pendingEdits` into the file yourself: they are
|
||||
context, and doubling them up would misplace things. Answer in the canvas
|
||||
and keep listening with one command:
|
||||
|
||||
```bash
|
||||
ecc-ui-canvas await <file> --reply "Background is now var(--gray-800) from the brand tokens."
|
||||
```
|
||||
|
||||
Speed matters here. Run `ecc-ui-canvas typing <file> --state thinking`
|
||||
the moment you start, edit the file, then reply. Under two seconds from
|
||||
request to repaint is the target for a one-property change.
|
||||
|
||||
```json
|
||||
{ "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ],
|
||||
"viewport": { "preset": "mobile", "width": 393, "height": 852 },
|
||||
"exportPath": "/abs/.claude/previews/pricing-card.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.edits.json" }
|
||||
```
|
||||
|
||||
- `edits` means the human clicked **Apply to file**: they want their hand
|
||||
edits written into the mockup now. Replace the mockup file with the
|
||||
contents of `exportPath` (it is the full DOM they are looking at, with
|
||||
their inline-style changes), tidy it into real CSS if it is messy, keep it
|
||||
self-contained, and reply. The canvas clears its pending list, so nothing
|
||||
is applied twice.
|
||||
|
||||
```json
|
||||
{ "kind": "finish", "editCount": 5, "edits": [ "…" ], "viewport": { "preset": "desktop", "width": 1412, "height": 806 },
|
||||
"exportPath": "…/pricing-card.edited.html", "editsPath": "…/pricing-card.edits.json" }
|
||||
```
|
||||
|
||||
- `finish` means the human clicked **Save and Finish**. The session is over
|
||||
(`sessionEnded: true`). Read `exportPath`, diff it against your original
|
||||
mockup, read `editsPath` for the intent behind each change, and reproduce
|
||||
that exact look in the real component with full functionality: real
|
||||
tokens, responsive rules, accessible markup, the project's framework.
|
||||
Then commit per the repo's rules and report in chat. Do not reopen the
|
||||
canvas.
|
||||
|
||||
Edit kinds you will see in `edits`: `text` (before/after, plus `htmlAfter`
|
||||
when inline markup was kept), `resize` (border-box px), `move` (from/to
|
||||
parent selector and index), `nudge` (dx/dy px offsets the human applied by
|
||||
dragging with Alt or arrow keys; translate to margin or alignment, not
|
||||
`position: relative`), `remove`, and `style` (`property`, computed `before`,
|
||||
`after`; `after: null` means they deleted the property, so border → none,
|
||||
box-shadow → none, padding → 0). An edit flagged `stale: true` could not be
|
||||
re-applied after one of your reloads; ask about it rather than guessing.
|
||||
|
||||
### 4. End
|
||||
|
||||
`ecc-ui-canvas end <file>` closes a session you opened and no longer need.
|
||||
`{"status":"ended","endedBy":"user"}` means the human closed it without
|
||||
saving: stop polling and do not reopen unless asked (`open --reopen`).
|
||||
|
||||
## What the Human Can Do
|
||||
|
||||
Edit mode (default): click selects, with hover and selection outlines and a
|
||||
size badge; double-click edits text; corner and edge handles resize (images
|
||||
keep their ratio unless Shift is held); dragging reorders among siblings or
|
||||
into another container with an insertion marker; Alt-drag or arrow keys
|
||||
nudge (Shift for 10 px); Delete or Backspace removes; Enter steps into the
|
||||
first child, Shift+Enter to the parent, Tab between siblings; Cmd/Ctrl+Z and
|
||||
Shift+Cmd/Ctrl+Z undo and redo. The inspector shows the selected element's
|
||||
breadcrumb and grouped slider rows (size, fill, text, spacing, border,
|
||||
effects). Drag a slider, or double-click a value to type one (sanitized and
|
||||
clamped; arrow keys step). A color swatch opens hue, saturation, lightness,
|
||||
and alpha sliders; the hex field also takes rgb() or a color name; the x
|
||||
button clears a property.
|
||||
|
||||
Interact mode (Cmd/Ctrl+I): clicks, hovers, and keyboard reach the component
|
||||
so they can try the tabs, toggles, and animations exactly as a user would.
|
||||
A pause button freezes animations and transitions for inspection.
|
||||
|
||||
Viewport bar: desktop (fills the stage), mobile (iPhone-class 393×852 with a
|
||||
device frame), or exact width × height; a rotate button swaps the two. The
|
||||
preview scales down only when the stage is smaller than the chosen size,
|
||||
never the other way, so media queries are honest.
|
||||
|
||||
## Rules
|
||||
|
||||
- One self-contained `.html` file per component. Markdown is not accepted;
|
||||
use `plan-canvas` for documents.
|
||||
- Edit the artifact file to revise. The canvas live-reloads on save and
|
||||
restores the human's pending edits, selection, and scroll. Never re-run
|
||||
`open` to refresh.
|
||||
- Never apply `pendingEdits` from a `chat` item into the file. Apply edits
|
||||
only from an `edits` or `finish` payload, from `exportPath`.
|
||||
- Reply in the canvas (`await --reply`), not only in the terminal, while the
|
||||
session is open.
|
||||
- The exported `.edited.html` and `.edits.json` are review artifacts, not
|
||||
production code. Do not commit them unless the repo keeps previews.
|
||||
- The server is loopback-only, idles out after 30 minutes
|
||||
(`ECC_PLAN_CANVAS_IDLE_MS`), and keeps state in `~/.claude/plan-canvas/`
|
||||
(`ECC_PLAN_CANVAS_STATE_DIR`). `ECC_CANVAS_AGENT` overrides the detected
|
||||
harness name shown in the browser.
|
||||
|
||||
## Examples
|
||||
|
||||
**Redesign with preview before commit**
|
||||
|
||||
```bash
|
||||
# user: "Make the pricing card friendlier, then show me before you commit."
|
||||
# → write .claude/previews/pricing-card.html using tokens from src/styles/tokens.css
|
||||
ecc-ui-canvas open .claude/previews/pricing-card.html --title "Pricing card"
|
||||
ecc-ui-canvas await .claude/previews/pricing-card.html
|
||||
# → {"status":"feedback","items":[{"kind":"chat","text":"change this to dark gray in the brand colors","anchor":{"selector":"#pricing-card",…},"pendingEdits":[…]}]}
|
||||
ecc-ui-canvas typing .claude/previews/pricing-card.html --state thinking
|
||||
# → edit the file: background: var(--gray-800)
|
||||
ecc-ui-canvas await .claude/previews/pricing-card.html --reply "Card background is now --gray-800."
|
||||
# → {"status":"feedback","sessionEnded":true,"items":[{"kind":"finish","editCount":5,"exportPath":"…/pricing-card.edited.html",…}]}
|
||||
# → read the export, port the look into src/components/PricingCard.tsx, commit
|
||||
```
|
||||
|
||||
**Mobile check of an existing component**
|
||||
|
||||
```bash
|
||||
ecc-ui-canvas open .claude/previews/sidebar.html --viewport mobile
|
||||
ecc-ui-canvas await .claude/previews/sidebar.html
|
||||
```
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Opening the real app's URL. The canvas serves one local file; mock the
|
||||
component instead.
|
||||
- Building the mockup with a framework build step. Plain HTML renders in
|
||||
milliseconds and reloads in under a second; that is the point.
|
||||
- Re-applying `pendingEdits` yourself, then watching the canvas apply them
|
||||
again.
|
||||
- Polling with `--timeout-ms` in a loop; leave the plain `await` running.
|
||||
- Letting a `chat` request sit. The human is watching the preview; signal
|
||||
`typing --state thinking` and move.
|
||||
- Committing `*.edited.html` or `*.edits.json`.
|
||||
@@ -0,0 +1,7 @@
|
||||
interface:
|
||||
display_name: "UI Canvas"
|
||||
short_description: "Hand-edit a UI mockup in the browser, then build it"
|
||||
brand_color: "#E26A9E"
|
||||
default_prompt: "Use $ui-canvas to preview a UI component mockup in the browser so the human can resize, move, restyle, and approve it before you build it."
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -11,7 +11,7 @@
|
||||
{
|
||||
"name": "ecc",
|
||||
"source": "./",
|
||||
"description": "Harness-native ECC operator layer - 71 agents, 311 skills, 97 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
|
||||
"description": "Harness-native ECC operator layer - 71 agents, 312 skills, 98 legacy command shims, reusable hooks, rules, selective install profiles, and production-ready workflows for Claude Code, Codex, OpenCode, Cursor, and related agent harnesses",
|
||||
"version": "2.2.3",
|
||||
"author": {
|
||||
"name": "Affaan Mustafa",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ecc",
|
||||
"version": "2.2.3",
|
||||
"description": "Harness-native ECC plugin for engineering teams - 71 agents, 311 skills, 97 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
|
||||
"description": "Harness-native ECC plugin for engineering teams - 71 agents, 312 skills, 98 legacy command shims, reusable hooks, rules, MCP conventions, and operator workflows for Claude Code plus adjacent agent harnesses",
|
||||
"author": {
|
||||
"name": "Affaan Mustafa",
|
||||
"url": "https://x.com/affaanmustafa"
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ This file provides Gemini CLI with the baseline ECC workflow, review standards,
|
||||
|
||||
## Overview
|
||||
|
||||
ECC is a cross-harness coding system with 71 specialized agents, 311 skills, and 97 commands.
|
||||
ECC is a cross-harness coding system with 71 specialized agents, 312 skills, and 98 commands.
|
||||
|
||||
Gemini support is currently focused on a strong project-local instruction layer via `.gemini/GEMINI.md`, plus the shared MCP catalog and package-manager setup assets shipped by the installer.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ECC — Agent Instructions
|
||||
|
||||
This is a **production-ready AI coding plugin** providing 71 specialized agents, 311 skills, 97 commands, and automated hook workflows for software development.
|
||||
This is a **production-ready AI coding plugin** providing 71 specialized agents, 312 skills, 98 commands, and automated hook workflows for software development.
|
||||
|
||||
**Version:** 2.2.3
|
||||
|
||||
@@ -202,8 +202,8 @@ Troubleshoot failures: check test isolation → verify mocks → fix implementat
|
||||
|
||||
```
|
||||
agents/ — 71 specialized subagents
|
||||
skills/ — 311 workflow skills and domain knowledge
|
||||
commands/ — 97 slash commands
|
||||
skills/ — 312 workflow skills and domain knowledge
|
||||
commands/ — 98 slash commands
|
||||
hooks/ — Trigger-based automations
|
||||
rules/ — Always-follow guidelines (common + per-language)
|
||||
scripts/ — Cross-platform Node.js utilities
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
|
||||
- UI Canvas (`/ui-canvas`, `ecc-ui-canvas`, `skills/ui-canvas`): a browser preview for UI component mockups. The agent writes a self-contained HTML file; the human selects, drags to reorder, resizes with handles, double-clicks to edit text, deletes elements or style properties, switches between desktop, mobile (393×852 with a device frame), and exact width × height, toggles an interact mode to try the component, pauses animations, and chats with the agent about the selected element. Save and Finish exports the edited DOM to `<name>.edited.html` plus a structured edit log in `<name>.edits.json`, which `await` hands to the agent to implement for real. Shares the Plan Canvas loopback server, state, and Stop/SessionStart hooks; the presence pill now names the connected harness (Claude Code, Codex, Cursor, …). Conventions borrowed from VisBug and Onlook; protocol lineage from lavish-axi.
|
||||
|
||||
### Changed
|
||||
|
||||
- GateGuard first-touch denials ask questions that fit the target: by class (instruction, test, prose, config, code) on its project-relative path, and for code by what the change touches. An edit that changes no public declaration asks for the in-module call sites instead of importers and public API, and the data-schema question is dropped when the change handles no data. Changes the hook cannot read with confidence keep the original four questions word for word.
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|---------|-------------|
|
||||
| `/plan` | Restate requirements, assess risks, write step-by-step implementation plan — **waits for your confirm before touching code** |
|
||||
| `/plan-canvas` | Open a plan or HTML artifact in the browser Plan Canvas for annotate-and-approve review |
|
||||
| `/ui-canvas` | Preview a UI component mockup in the browser UI Canvas: the user hand-edits, tests viewports, chats, and finishes with an exported design |
|
||||
| `/plan-prd` | Generate a lean, problem-first PRD and hand off to `/plan` for implementation planning |
|
||||
| `/feature-dev` | Guided feature development with codebase understanding and architecture focus |
|
||||
| `/code-review` | Code review — local uncommitted changes or GitHub PR (pass PR number/URL for PR mode) |
|
||||
|
||||
@@ -141,13 +141,13 @@ Instead of rebuilding that process in every prompt, you install it once and make
|
||||
|
||||
ECC is MIT-licensed open source. It works best with Claude Code today, has native Codex and Qoder plugin paths, and provides capability-limited adapters for Cursor, OpenCode, Gemini, Zed, GitHub Copilot, Antigravity, Qwen, and other harnesses. See the [support status matrix](#platform-support) before assuming feature parity.
|
||||
|
||||
Access to 71 agents, 311 skills, and 97 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
|
||||
Access to 71 agents, 312 skills, and 98 legacy command shims, plus hooks, rules, memory, continuous learning, and AgentShield security scanning. The agents are specialized for planning, review, build repair, security, architecture, and domain work.
|
||||
|
||||
| Included | Count | What it gives you |
|
||||
| ---------------- | ----------: | ------------------------------------------------------------------------------------ |
|
||||
| Agents | 71 agents | Planning, review, build repair, security, architecture, and domain work |
|
||||
| Skills | 311 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
|
||||
| Commands | 97 commands | Convenient entry points while ECC moves to a skills-first surface |
|
||||
| Skills | 312 skills | TDD, research, security, docs, frontend, data, ML, operations, and more |
|
||||
| Commands | 98 commands | Convenient entry points while ECC moves to a skills-first surface |
|
||||
| Hooks and memory | Runtime | Enforcement, session summaries, continuous learning, instincts, and context controls |
|
||||
| Rules | Selective | Always-loaded standards you choose by language or project |
|
||||
| AgentShield | Included | Scanning for prompts, hooks, MCP config, permissions, secrets, and agent files |
|
||||
@@ -859,8 +859,8 @@ Stable graduation of the 2.0 line: control-pane substrate, worktree lifecycle se
|
||||
```text
|
||||
ECC/
|
||||
|-- agents/ # 71 specialized subagents for delegation
|
||||
|-- skills/ # 311 reusable workflows loaded on demand
|
||||
|-- commands/ # 97 maintained slash-command shims
|
||||
|-- skills/ # 312 reusable workflows loaded on demand
|
||||
|-- commands/ # 98 maintained slash-command shims
|
||||
|-- rules/ # opt-in common and language standards
|
||||
|-- hooks/ # runtime automation and enforcement
|
||||
|-- scripts/ # install, repair, sync, orchestration, and checks
|
||||
|
||||
+1
-1
@@ -200,7 +200,7 @@ Copy-Item -Recurse rules/typescript "$HOME/.claude/rules/"
|
||||
/plugin list ecc@ecc
|
||||
```
|
||||
|
||||
**完成!** 你现在可以使用 71 个代理、311 个技能和 97 个命令。
|
||||
**完成!** 你现在可以使用 71 个代理、312 个技能和 98 个命令。
|
||||
|
||||
### multi-* 命令需要额外配置
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Soul
|
||||
|
||||
## Core Identity
|
||||
ECC is a production-ready AI coding plugin with 71 specialized agents, 311 skills, 97 commands, and automated hook workflows for software development.
|
||||
ECC is a production-ready AI coding plugin with 71 specialized agents, 312 skills, 98 commands, and automated hook workflows for software development.
|
||||
|
||||
## Core Principles
|
||||
1. **Agent-First** — route work to the right specialist as early as possible.
|
||||
|
||||
@@ -122,6 +122,7 @@ skills:
|
||||
- perl-testing
|
||||
- plankton-code-quality
|
||||
- plan-canvas
|
||||
- ui-canvas
|
||||
- plan-orchestrate
|
||||
- postgres-patterns
|
||||
- product-lens
|
||||
@@ -239,6 +240,7 @@ commands:
|
||||
- orch-review
|
||||
- plan
|
||||
- plan-canvas
|
||||
- ui-canvas
|
||||
- plan-prd
|
||||
- pm2
|
||||
- projects
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
description: Preview a UI component mockup in the browser UI Canvas where the user hand-edits it (move, resize, text, delete, restyle), tests it across viewports, chats with you, and clicks Save and Finish; you then build the exported design for real. Thin entrypoint over the ui-canvas skill.
|
||||
argument-hint: "[path/to/component.html] [--viewport mobile|desktop|WxH]"
|
||||
---
|
||||
|
||||
# UI Canvas Command
|
||||
|
||||
Opens a self-contained HTML mockup in the UI Canvas, ECC's browser preview
|
||||
surface, where the user adjusts the component directly, switches between
|
||||
desktop, mobile, and exact dimensions, chats with you, and finishes with the
|
||||
edited design exported for you to implement.
|
||||
|
||||
This command is a thin entry point over the `ui-canvas` skill. Follow that
|
||||
skill for the mockup rules, the feedback JSON, and what to do with the
|
||||
export.
|
||||
|
||||
## What This Command Does
|
||||
|
||||
1. Resolve the mockup: the given path, else write one for the component the
|
||||
user is discussing (`.claude/previews/<name>.html`, real brand tokens,
|
||||
realistic copy), else ask what to preview.
|
||||
2. `ecc-ui-canvas open <file> [--viewport …] [--title …]` opens the browser.
|
||||
3. `ecc-ui-canvas await <file>` blocks (run it in the background) until the
|
||||
user chats, clicks Apply to file, clicks Save and Finish, or ends.
|
||||
4. On `chat`: signal `typing --state thinking`, edit the mockup file (the
|
||||
preview live-reloads and keeps their pending edits), answer with
|
||||
`await <file> --reply "…"`, repeat.
|
||||
5. On `edits`: rewrite the mockup from `exportPath`, reply, keep listening.
|
||||
6. On `finish`: read `exportPath` and `editsPath`, implement that exact
|
||||
design in the real component, commit per repo rules, report in chat.
|
||||
|
||||
## Example
|
||||
|
||||
```
|
||||
User: /ui-canvas .claude/previews/pricing-card.html --viewport mobile
|
||||
|
||||
Assistant: (runs open + await, browser opens on the mobile frame)
|
||||
...user resizes the image, deletes the secondary button, selects the card and sends "change this to dark gray in the brand colors"...
|
||||
Assistant: (typing → edits background to var(--gray-800) → replies in-canvas → awaits)
|
||||
...user clicks Save and Finish...
|
||||
Assistant: Pricing card approved in the canvas: 5 hand edits plus the gray background. Porting the exported design into PricingCard.tsx now.
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
- `ui-canvas` skill: mockup rules, feedback JSON shapes, export handling
|
||||
- `/plan-canvas`: the document review counterpart (same server)
|
||||
- `frontend-design-direction`, `artifact-design`: visual guidance for the mockup
|
||||
- Source: `scripts/ui-canvas.js`, `scripts/lib/ui-canvas/`
|
||||
@@ -6,6 +6,7 @@ This document lists each slash command and the primary agent(s) or skills it inv
|
||||
|---------|------------------|--------|
|
||||
| `/plan` | planner | Implementation planning before code |
|
||||
| `/plan-canvas` | — (skill: plan-canvas) | Browser review canvas for plan artifacts: annotate, chat, approve/request changes |
|
||||
| `/ui-canvas` | none (skill: ui-canvas) | Browser preview canvas for UI mockups: move, resize, edit, restyle, test viewports, Save and Finish |
|
||||
| `/tdd` | tdd-guide | Test-driven development |
|
||||
| `/code-review` | code-reviewer | Quality and security review |
|
||||
| `/build-fix` | build-error-resolver | Fix build/type errors |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"totalCommands": 97,
|
||||
"totalCommands": 98,
|
||||
"commands": [
|
||||
{
|
||||
"command": "aside",
|
||||
@@ -1021,6 +1021,18 @@
|
||||
],
|
||||
"path": "commands/token-card.md"
|
||||
},
|
||||
{
|
||||
"command": "ui-canvas",
|
||||
"description": "Preview a UI component mockup in the browser UI Canvas where the user hand-edits it (move, resize, text, delete, restyle), tests it across viewports, chats with you, and clicks Save and Finish; you then build the exported design for real. Thin entrypoint over the ui-canvas skill.",
|
||||
"type": "testing",
|
||||
"primaryAgents": [],
|
||||
"allAgents": [],
|
||||
"skills": [
|
||||
"plan-canvas",
|
||||
"ui-canvas"
|
||||
],
|
||||
"path": "commands/ui-canvas.md"
|
||||
},
|
||||
{
|
||||
"command": "update-codemaps",
|
||||
"description": "Scan project structure and generate token-lean architecture codemaps.",
|
||||
@@ -1065,7 +1077,7 @@
|
||||
"planning": 2,
|
||||
"refactoring": 1,
|
||||
"review": 15,
|
||||
"testing": 53
|
||||
"testing": 54
|
||||
},
|
||||
"topAgents": [
|
||||
{
|
||||
@@ -1138,6 +1150,10 @@
|
||||
"skill": "orch-fix-defect",
|
||||
"count": 3
|
||||
},
|
||||
{
|
||||
"skill": "plan-canvas",
|
||||
"count": 3
|
||||
},
|
||||
{
|
||||
"skill": "rust-patterns",
|
||||
"count": 3
|
||||
@@ -1145,10 +1161,6 @@
|
||||
{
|
||||
"skill": "cpp-coding-standards",
|
||||
"count": 2
|
||||
},
|
||||
{
|
||||
"skill": "cpp-testing",
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# UI Canvas: hand-editable component preview in the browser
|
||||
|
||||
Status: implemented (`feat/ui-canvas`), local testing before PR
|
||||
Lineage: shares its server and protocol with [Plan Canvas](plan-canvas.md), itself inspired by
|
||||
[lavish-axi](https://github.com/kunchenguid/lavish-axi) by @kunchenguid. Editing conventions
|
||||
borrow from [VisBug](https://github.com/GoogleChromeLabs/ProjectVisBug) (Adam Argyle,
|
||||
Apache-2.0: Enter/Shift+Enter tree walking, Delete removes, Alt+Delete-style property stripping)
|
||||
and [Onlook](https://github.com/onlook-dev/onlook) (Apache-2.0: the design/preview mode split).
|
||||
No third-party code is vendored; the editor is an original, dependency-free implementation.
|
||||
|
||||
## Problem
|
||||
|
||||
Checking a visual change today means asking the agent to edit the real component, rebuild,
|
||||
rerun, and look. A padding tweak costs a full feature cycle, and the feedback is typed
|
||||
("move the button up a bit") when it would be faster shown. Lovable-style products solve this
|
||||
with a hosted editor coupled to one framework. ECC needs the same loop for any component, any
|
||||
harness, and nothing heavier than a loopback server.
|
||||
|
||||
## What it is
|
||||
|
||||
The agent writes one self-contained `.html` mockup. `ecc-ui-canvas open <file>` shows it in a
|
||||
browser shell where the human:
|
||||
|
||||
- clicks to select (hover and selection outlines, size badge), double-clicks to edit text,
|
||||
drags eight handles to resize (images keep ratio unless Shift), drags to reorder among
|
||||
siblings or into another container, Alt-drags or arrows to nudge, presses Delete to remove;
|
||||
- edits style properties from a grouped inspector (size, fill, text, spacing, border, effects)
|
||||
with sliders, double-click-to-type values that are sanitized and clamped before they reach
|
||||
the mockup, HSL plus alpha color sliders, and a clear button per property;
|
||||
- switches between desktop (fills the stage), mobile (393×852 with a device frame), and exact
|
||||
width × height, rotates, and scales the stage down only when it is too small, so media queries
|
||||
behave as in production;
|
||||
- toggles an interact mode where clicks reach the component, and pauses animations;
|
||||
- chats with the agent about the selected element while the agent is parked in
|
||||
`ecc-ui-canvas await`; the presence pill names the harness that is listening;
|
||||
- clicks **Apply to file** to have the agent bake the hand edits into the mockup, or
|
||||
**Save and Finish** to hand over the final design.
|
||||
|
||||
Every change is recorded as a structured edit (`text`, `resize`, `move`, `nudge`, `remove`,
|
||||
`style`) against a CSS selector. The log is re-applied when the agent's file edit live-reloads
|
||||
the frame, undone with Cmd/Ctrl+Z, and exported with a clean DOM snapshot to
|
||||
`<name>.edited.html` and `<name>.edits.json` next to the artifact. The agent reads those and
|
||||
reproduces the look in the real component.
|
||||
|
||||
## How it fits ECC
|
||||
|
||||
| Piece | Location | Notes |
|
||||
|---|---|---|
|
||||
| CLI entry | `scripts/ui-canvas.js` (npm bin `ecc-ui-canvas`) | A profile over `scripts/plan-canvas.js`: same transport, `mode: ui`, its own usage and next-step guidance |
|
||||
| Server | `scripts/lib/plan-canvas/server.js` | Mode-aware routes: `/canvas/:key` renders the UI shell, `/artifact/:key/` injects the editor, `/ui-editor.js`, `/ui-client.js`, `/ui-canvas.css`; `edits`/`finish` batches are written to disk before queueing |
|
||||
| Sessions | `scripts/lib/plan-canvas/sessions.js` | `mode`, `ui` options (viewport, title), `agent` descriptor; UI feedback normalized by `ui-canvas/feedback.js` |
|
||||
| Feedback schema | `scripts/lib/ui-canvas/feedback.js` | Edit kinds, clamps, summaries, viewport presets, export writer |
|
||||
| Shell | `scripts/lib/ui-canvas/ui.js` | Top bar, stage with device frame and scaling, inspector, edit log, conversation; ECC design tokens |
|
||||
| Editor | `scripts/lib/ui-canvas/editor.js` | Script injected into the sandboxed frame; shadow-root overlay, gestures, edit log, restore, export |
|
||||
| Agent identity | `scripts/lib/plan-canvas/agent-identity.js` | Harness detection from environment markers; `ECC_CANVAS_AGENT` override |
|
||||
| Hooks | `scripts/hooks/plan-canvas-pending.js`, `plan-canvas-sessions.js` | Understand `edits`/`finish`, name the right bin per session mode |
|
||||
| Skill | `skills/ui-canvas/SKILL.md` (+ `.agents/skills/ui-canvas/` for Codex) | Mockup rules, feedback shapes, finish handling |
|
||||
| Command | `commands/ui-canvas.md` | Thin entrypoint |
|
||||
| Tests | `tests/lib/ui-canvas-*.test.js`, `tests/lib/plan-canvas-agent-identity.test.js`, `tests/scripts/ui-canvas.test.js`, `tests/integration/ui-canvas-e2e.test.js` | Schema, shell/editor contract, server mode, CLI flow |
|
||||
|
||||
Registration mirrors plan-canvas: `package.json` (`bin`, `files`), `manifests/install-components.json`
|
||||
and `install-modules.json` (workflow-quality), `manifests/pi-core.json` exclusions, `agent.yaml`,
|
||||
`docs/COMMAND-REGISTRY.json`, `COMMANDS-QUICK-REF.md`, `docs/COMMAND-AGENT-MAP.md`.
|
||||
|
||||
## Protocol
|
||||
|
||||
Shell and editor talk only over `postMessage` (the frame is sandboxed without
|
||||
`allow-same-origin`, exactly like Plan Canvas, so a hostile mockup cannot reach the loopback API).
|
||||
|
||||
Editor → shell: `uc:ready`, `uc:selection` (descriptor, style report, breadcrumb), `uc:edits`
|
||||
(log plus undo/redo availability), `uc:status`, `uc:toggle-mode`, `uc:scroll`, `uc:export`.
|
||||
Shell → editor: `uc:set-mode`, `uc:restore` (edits, scroll, selection after a reload),
|
||||
`uc:select`, `uc:deselect`, `uc:style`, `uc:size`, `uc:remove`, `uc:edit-text`, `uc:undo`,
|
||||
`uc:redo`, `uc:reset`, `uc:forget`, `uc:pause-animations`, `uc:export`.
|
||||
|
||||
Browser → server feedback items (`POST /api/session/:key/feedback`):
|
||||
|
||||
- `chat` with optional `anchor` (selected element) and `pendingEdits` (one-line summaries of
|
||||
hand edits not yet in the file; context only, never to be applied by the agent);
|
||||
- `edits` (Apply to file) and `finish` (Save and Finish) with `edits`, `viewport`, and `html`.
|
||||
The server writes `html` to `<name>.edited.html`, the log to `<name>.edits.json`, and queues
|
||||
the item with `exportPath`/`editsPath` instead of markup. `finish` ends the session.
|
||||
|
||||
Agent `await` adds `agent=<descriptor>` so the presence pill reads "Claude Code · listening".
|
||||
|
||||
## Responsiveness
|
||||
|
||||
The slow path in earlier Plan Canvas sessions was delivery: feedback only reached an agent
|
||||
parked in `await`, and presence lied while nothing listened. UI Canvas inherits the fixes
|
||||
(honest presence with expiry, Stop-hook drain, `pending`) and adds: the shell keeps the human's
|
||||
edits client-side and replays them after every reload, so the agent's file write is the only
|
||||
work between a chat request and the repaint (file watcher debounce 150 ms, reload, restore).
|
||||
The skill tells the agent to signal `typing --state thinking` immediately and reply with
|
||||
`await --reply`.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Framework-aware code generation. The export is DOM plus an edit log; translating it into
|
||||
React/Vue/Swift is the agent's job, guided by the skill.
|
||||
- Multi-file apps or remote URLs. One local file per session.
|
||||
- Pixel-exact device emulation (user agent, touch events, DPR). The viewport is exact in CSS
|
||||
pixels; hover and pointer media features follow the real browser.
|
||||
- Collaborative sessions. One browser, one agent, one file.
|
||||
|
||||
## Verification
|
||||
|
||||
`node tests/lib/ui-canvas-feedback.test.js`, `node tests/lib/ui-canvas-ui.test.js`,
|
||||
`node tests/lib/plan-canvas-agent-identity.test.js`, `node tests/scripts/ui-canvas.test.js`,
|
||||
`node tests/integration/ui-canvas-e2e.test.js`, plus the existing Plan Canvas suites, run under
|
||||
`node tests/run-all.js`. Manual browser QA uses a mockup opened with
|
||||
`ECC_PLAN_CANVAS_STATE_DIR=/tmp/uc ECC_PLAN_CANVAS_PORT=4599 node scripts/ui-canvas.js open <file> --no-open`.
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# ECC — Agent Talimatları
|
||||
|
||||
Bu, yazılım geliştirme için 71 özel agent, 311 skill, 97 command ve otomatik hook iş akışları sağlayan **üretime hazır bir AI kodlama eklentisidir**.
|
||||
Bu, yazılım geliştirme için 71 özel agent, 312 skill, 98 command ve otomatik hook iş akışları sağlayan **üretime hazır bir AI kodlama eklentisidir**.
|
||||
|
||||
**Sürüm:** 2.2.3
|
||||
|
||||
@@ -142,8 +142,8 @@ Başarısızlık sorunlarını giderin: test izolasyonunu kontrol edin → mockl
|
||||
|
||||
```
|
||||
agents/ — 71 özel subagent
|
||||
skills/ — 311 iş akışı skillleri ve alan bilgisi
|
||||
commands/ — 97 slash command
|
||||
skills/ — 312 iş akışı skillleri ve alan bilgisi
|
||||
commands/ — 98 slash command
|
||||
hooks/ — Tetikleyici tabanlı otomasyonlar
|
||||
rules/ — Her zaman uyulması gereken kurallar (ortak + dile özel)
|
||||
scripts/ — Platformlar arası Node.js yardımcı programları
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ECC — 智能体指令
|
||||
|
||||
这是一个**生产就绪的 AI 编码插件**,提供 71 个专业代理、311 项技能、97 条命令以及自动化钩子工作流,用于软件开发。
|
||||
这是一个**生产就绪的 AI 编码插件**,提供 71 个专业代理、312 项技能、98 条命令以及自动化钩子工作流,用于软件开发。
|
||||
|
||||
**版本:** 2.2.3
|
||||
|
||||
@@ -147,8 +147,8 @@
|
||||
|
||||
```
|
||||
agents/ — 71 个专业子代理
|
||||
skills/ — 311 个工作流技能和领域知识
|
||||
commands/ — 97 个斜杠命令
|
||||
skills/ — 312 个工作流技能和领域知识
|
||||
commands/ — 98 个斜杠命令
|
||||
hooks/ — 基于触发的自动化
|
||||
rules/ — 始终遵循的指导方针(通用 + 每种语言)
|
||||
scripts/ — 跨平台 Node.js 实用工具
|
||||
|
||||
@@ -264,7 +264,7 @@ Copy-Item -Recurse rules/typescript "$HOME/.claude/rules/"
|
||||
/plugin list ecc@ecc
|
||||
```
|
||||
|
||||
**搞定!** 你现在可以使用 71 个智能体、311 项技能和 97 个命令了。
|
||||
**搞定!** 你现在可以使用 71 个智能体、312 项技能和 98 个命令了。
|
||||
|
||||
***
|
||||
|
||||
@@ -1177,8 +1177,8 @@ opencode
|
||||
| 功能特性 | Claude Code | OpenCode | 状态 |
|
||||
|---------|---------------|----------|--------|
|
||||
| 智能体 | PASS: 71 个 | PASS: 12 个 | **Claude Code 领先** |
|
||||
| 命令 | PASS: 97 个 | PASS: 35 个 | **Claude Code 领先** |
|
||||
| 技能 | PASS: 311 项 | PASS: 37 项 | **Claude Code 领先** |
|
||||
| 命令 | PASS: 98 个 | PASS: 35 个 | **Claude Code 领先** |
|
||||
| 技能 | PASS: 312 项 | PASS: 37 项 | **Claude Code 领先** |
|
||||
| 钩子 | PASS: 8 种事件类型 | PASS: 11 种事件 | **OpenCode 更多!** |
|
||||
| 规则 | PASS: 29 条 | PASS: 13 条指令 | **Claude Code 领先** |
|
||||
| MCP 服务器 | PASS: 14 个 | PASS: 完整 | **完全对等** |
|
||||
@@ -1285,8 +1285,8 @@ ECC 是**第一个最大化利用每个主要 AI 编码工具的插件**。以
|
||||
| 功能特性 | Claude Code | Cursor IDE | Codex CLI | OpenCode |
|
||||
|---------|-----------------------|------------|-----------|----------|
|
||||
| **智能体** | 71 | 共享 (AGENTS.md) | 共享 (AGENTS.md) | 12 |
|
||||
| **命令** | 97 | 共享 | 基于指令 | 35 |
|
||||
| **技能** | 311 | 共享 | 10 (原生格式) | 37 |
|
||||
| **命令** | 98 | 共享 | 基于指令 | 35 |
|
||||
| **技能** | 312 | 共享 | 10 (原生格式) | 37 |
|
||||
| **钩子事件** | 8 种类型 | 15 种类型 | SessionStart(1 种类型) | 11 种类型 |
|
||||
| **钩子脚本** | 20+ 个脚本 | 16 个脚本 (DRY 适配器) | 1 个 SessionStart 引导脚本 | 插件钩子 |
|
||||
| **规则** | 34 (通用 + 语言) | 34 (YAML 前页) | 基于指令 | 13 条指令 |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"coverage": {
|
||||
"skills": 311,
|
||||
"withTriggers": 33
|
||||
"skills": 312,
|
||||
"withTriggers": 34
|
||||
},
|
||||
"generatedAt": "2026-09-24T23:51:22.784Z",
|
||||
"id": "skill-triggers@1",
|
||||
@@ -10,7 +10,7 @@
|
||||
"id": "hand-seeded",
|
||||
"source": "manual-curation-pending-regeneration"
|
||||
},
|
||||
"registryDigest": "846ac8826dd91e81cd838c2b55d7be536af427eb453efa127501f891e5778ff8",
|
||||
"registryDigest": "ae8ae2053706c96b5c1e842d9c0c66b8403761ac35f7b32855ed80407179c7f8",
|
||||
"schemaVersion": 1,
|
||||
"triggers": {
|
||||
"skill:agent-runtime-gateway-smoke-test": [
|
||||
@@ -283,6 +283,16 @@
|
||||
"regression test first",
|
||||
"write a regression test"
|
||||
],
|
||||
"skill:ui-canvas": [
|
||||
"preview the component before committing",
|
||||
"show me a mockup in the browser",
|
||||
"ui canvas",
|
||||
"let me resize and move elements myself",
|
||||
"edit the mockup by hand then build it",
|
||||
"check the design on mobile and desktop",
|
||||
"approve the ui before you implement it",
|
||||
"lovable style visual editing"
|
||||
],
|
||||
"skill:verification-loop": [
|
||||
"pre pr checks",
|
||||
"verification report",
|
||||
@@ -291,5 +301,5 @@
|
||||
"before creating a pr"
|
||||
]
|
||||
},
|
||||
"triggersDigest": "054898acb769893c46e5bd7037141f7be83fb775515ea1dbb52fb1c18aca19e6"
|
||||
"triggersDigest": "296375253fe5f4fe1278024d2dc9ead550c5eb464581fef9692ee34f841ee816"
|
||||
}
|
||||
@@ -502,6 +502,14 @@
|
||||
"workflow-quality"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "skill:ui-canvas",
|
||||
"family": "skill",
|
||||
"description": "Browser preview canvas for UI component mockups: the human moves, resizes, edits, restyles, tests across viewports, and hands the edited design back.",
|
||||
"modules": [
|
||||
"workflow-quality"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "skill:unified-memory",
|
||||
"family": "skill",
|
||||
|
||||
@@ -403,6 +403,7 @@
|
||||
"skills/hookify-rules",
|
||||
"skills/iterative-retrieval",
|
||||
"skills/plan-canvas",
|
||||
"skills/ui-canvas",
|
||||
"skills/plankton-code-quality",
|
||||
"skills/production-audit",
|
||||
"skills/skill-comply",
|
||||
|
||||
@@ -285,6 +285,7 @@
|
||||
"orch-pipeline": "Claude-Code-only orch-* orchestration",
|
||||
"orch-refine-code": "Claude-Code-only orch-* orchestration",
|
||||
"plan-canvas": "Claude-Code-only plan canvas server",
|
||||
"ui-canvas": "Claude-Code-only ui canvas server",
|
||||
"plan-orchestrate": "ECC orchestration prompt generator over the full catalog",
|
||||
"plankton-code-quality": "Claude-Code-only write-time hooks",
|
||||
"prediction-market-oracle-research": "venture-specific prediction-market-*",
|
||||
@@ -427,6 +428,7 @@
|
||||
"orch-refine-code.md": "Claude-Code-only orch-* orchestration",
|
||||
"orch-review.md": "Claude-Code-only orch-* orchestration",
|
||||
"plan-canvas.md": "Claude-Code-only plan canvas server",
|
||||
"ui-canvas.md": "Claude-Code-only ui canvas server",
|
||||
"pm2.md": "PM2 runtime process manager ops",
|
||||
"project-init.md": "ECC install-manifest onboarding plan",
|
||||
"projects.md": "instincts (continuous-learning)",
|
||||
|
||||
Generated
+1
@@ -21,6 +21,7 @@
|
||||
"ecc-install": "scripts/install-apply.js",
|
||||
"ecc-memory-mcp": "scripts/memory-mcp.mjs",
|
||||
"ecc-plan-canvas": "scripts/plan-canvas.js",
|
||||
"ecc-ui-canvas": "scripts/ui-canvas.js",
|
||||
"ecc-universal": "scripts/ecc.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -157,6 +157,7 @@
|
||||
"scripts/list-installed.js",
|
||||
"scripts/loop-status.js",
|
||||
"scripts/plan-canvas.js",
|
||||
"scripts/ui-canvas.js",
|
||||
"scripts/orchestration-status.js",
|
||||
"scripts/orchestrate-codex-worker.sh",
|
||||
"scripts/orchestrate-worktrees.js",
|
||||
@@ -321,6 +322,7 @@
|
||||
"skills/perl-security/",
|
||||
"skills/perl-testing/",
|
||||
"skills/plan-canvas/",
|
||||
"skills/ui-canvas/",
|
||||
"skills/plankton-code-quality/",
|
||||
"skills/parallel-execution-optimizer/",
|
||||
"skills/postgres-patterns/",
|
||||
@@ -499,6 +501,7 @@
|
||||
"ecc-install": "scripts/install-apply.js",
|
||||
"ecc-memory-mcp": "scripts/memory-mcp.mjs",
|
||||
"ecc-plan-canvas": "scripts/plan-canvas.js",
|
||||
"ecc-ui-canvas": "scripts/ui-canvas.js",
|
||||
"ecc-universal": "scripts/ecc.js"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -135,6 +135,7 @@ Exclude anything that:
|
||||
| `orch-pipeline` | Claude-Code-only orch-* orchestration |
|
||||
| `orch-refine-code` | Claude-Code-only orch-* orchestration |
|
||||
| `plan-canvas` | Claude-Code-only plan canvas server |
|
||||
| `ui-canvas` | Claude-Code-only ui canvas server |
|
||||
| `plan-orchestrate` | ECC orchestration prompt generator over the full catalog |
|
||||
| `plankton-code-quality` | Claude-Code-only write-time hooks |
|
||||
| `prediction-market-oracle-research` | venture-specific prediction-market-* |
|
||||
@@ -252,6 +253,7 @@ Exclude anything that:
|
||||
| `orch-refine-code` | Claude-Code-only orch-* orchestration |
|
||||
| `orch-review` | Claude-Code-only orch-* orchestration |
|
||||
| `plan-canvas` | Claude-Code-only plan canvas server |
|
||||
| `ui-canvas` | Claude-Code-only ui canvas server |
|
||||
| `pm2` | PM2 runtime process manager ops |
|
||||
| `project-init` | ECC install-manifest onboarding plan |
|
||||
| `projects` | instincts (continuous-learning) |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Plan Canvas undelivered-feedback guard (Stop)
|
||||
* Plan Canvas and UI Canvas undelivered-feedback guard (Stop)
|
||||
*
|
||||
* Cross-platform (Windows, macOS, Linux)
|
||||
*
|
||||
@@ -193,26 +193,45 @@ function describeItem(item) {
|
||||
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 = [
|
||||
'Plan Canvas: the human sent feedback in the browser that was never delivered to you.',
|
||||
`${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) {
|
||||
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(` ecc-plan-canvas await ${JSON.stringify(entry.file)} --reply "<what you did>"`);
|
||||
lines.push(` ${bin} await ${JSON.stringify(entry.file)} --reply "<what you did>"`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
@@ -229,7 +248,7 @@ async function collectDeliveries(sessions, port) {
|
||||
if (!result) continue;
|
||||
const messages = result.items.map(describeItem).filter(Boolean);
|
||||
if (messages.length === 0) continue;
|
||||
delivered.push({ file: session.file, messages, sessionEnded: Boolean(result.sessionEnded) });
|
||||
delivered.push({ file: session.file, mode: session.mode === 'ui' ? 'ui' : 'plan', messages, sessionEnded: Boolean(result.sessionEnded) });
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Plan Canvas open-session surfacing (SessionStart)
|
||||
* Plan Canvas and UI Canvas open-session surfacing (SessionStart)
|
||||
*
|
||||
* Cross-platform (Windows, macOS, Linux)
|
||||
*
|
||||
@@ -58,11 +58,15 @@ function buildContext(sessions) {
|
||||
];
|
||||
for (const session of sessions.slice(0, 5)) {
|
||||
const pending = session.pendingFeedback && session.pendingFeedback.length;
|
||||
lines.push(` - ${session.file}${pending ? ` (${pending} undelivered feedback item${pending === 1 ? '' : 's'})` : ''}`);
|
||||
const tag = session.mode === 'ui' ? ' [ui canvas]' : '';
|
||||
lines.push(` - ${session.file}${tag}${pending ? ` (${pending} undelivered feedback item${pending === 1 ? '' : 's'})` : ''}`);
|
||||
}
|
||||
lines.push(
|
||||
'Resume with `node scripts/plan-canvas.js await <file>` (plan-canvas skill), or `end <file>` if the review is obsolete.'
|
||||
);
|
||||
if (sessions.some(session => session.mode === 'ui')) {
|
||||
lines.push('Sessions tagged [ui canvas] resume with `node scripts/ui-canvas.js await <file>` (ui-canvas skill) instead.');
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Which coding agent is driving a canvas session.
|
||||
*
|
||||
* The browser shows "Claude Code · listening" instead of an anonymous pill so
|
||||
* the human can tell which terminal to look at. Detection is best effort and
|
||||
* environment-based: every harness exports at least one distinctive variable
|
||||
* into the shells it spawns. `ECC_CANVAS_AGENT` overrides the guess outright.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const HARNESS_MARKERS = [
|
||||
['Claude Code', ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_SSE_PORT']],
|
||||
['Codex', ['CODEX_SANDBOX', 'CODEX_SANDBOX_NETWORK_DISABLED', 'CODEX_THREAD_ID', 'CODEX_CI']],
|
||||
['Cursor', ['CURSOR_AGENT', 'CURSOR_TRACE_ID', 'CURSOR_SESSION_ID']],
|
||||
['Gemini CLI', ['GEMINI_CLI', 'GEMINI_CLI_SESSION']],
|
||||
['OpenCode', ['OPENCODE', 'OPENCODE_SESSION_ID', 'OPENCODE_SERVER_URL']],
|
||||
['Copilot', ['COPILOT_AGENT', 'GITHUB_COPILOT_CLI', 'COPILOT_CLI_SESSION']],
|
||||
['Kimi', ['KIMI_CLI', 'KIMI_SESSION_ID']],
|
||||
['Qwen Code', ['QWEN_CODE', 'QWEN_CLI']]
|
||||
];
|
||||
|
||||
function detectAgentName(env = process.env) {
|
||||
const override = env.ECC_CANVAS_AGENT;
|
||||
if (typeof override === 'string' && override.trim()) return override.trim().slice(0, 60);
|
||||
for (const [name, markers] of HARNESS_MARKERS) {
|
||||
if (markers.some(marker => typeof env[marker] === 'string' && env[marker] !== '')) return name;
|
||||
}
|
||||
return 'agent';
|
||||
}
|
||||
|
||||
// Compact descriptor the CLI attaches to `await` so the server can show who
|
||||
// is listening. The cwd is reduced to its basename: enough to tell projects
|
||||
// apart without leaking a full path into the browser.
|
||||
function agentDescriptor({ env = process.env, cwd = process.cwd() } = {}) {
|
||||
return {
|
||||
name: detectAgentName(env),
|
||||
project: path.basename(cwd) || cwd
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeAgentDescriptor(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const name = typeof raw.name === 'string' ? raw.name.trim().slice(0, 60) : '';
|
||||
if (!name) return null;
|
||||
const descriptor = { name };
|
||||
if (typeof raw.project === 'string' && raw.project.trim()) descriptor.project = raw.project.trim().slice(0, 120);
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
module.exports = { HARNESS_MARKERS, agentDescriptor, detectAgentName, sanitizeAgentDescriptor };
|
||||
@@ -24,11 +24,18 @@ const {
|
||||
renderMarkdownArtifactHtml,
|
||||
renderSessionListHtml
|
||||
} = require('./ui');
|
||||
const { sanitizeAgentDescriptor } = require('./agent-identity');
|
||||
const { uiEditorJs } = require('../ui-canvas/editor');
|
||||
const { renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('../ui-canvas/ui');
|
||||
const { normalizeEdits, writeExport } = require('../ui-canvas/feedback');
|
||||
|
||||
const DEFAULT_PORT = 4517;
|
||||
const DEFAULT_HOST = '127.0.0.1';
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
const MAX_BODY_BYTES = 1024 * 1024;
|
||||
// UI Canvas ships a serialized DOM snapshot with its edit batches, and a
|
||||
// mockup with inline images can run to a few megabytes; the snapshot itself is
|
||||
// capped separately in ui-canvas/feedback.js.
|
||||
const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
||||
// How long the "agent is thinking" indicator survives without the agent
|
||||
// checking back in, before presence decays to the honest queued/waiting.
|
||||
const DEFAULT_THINKING_STALE_MS = 90 * 1000;
|
||||
@@ -229,6 +236,25 @@ function readSiblingAsset(baseDir, resolved) {
|
||||
return { data, realTarget };
|
||||
}
|
||||
|
||||
// UI Canvas edit batches arrive with the full DOM snapshot. Write it (and the
|
||||
// edit log) next to the artifact before the item is queued, and hand the agent
|
||||
// paths instead of megabytes of markup. Chat items pass through untouched.
|
||||
function materializeUiExports(session, items) {
|
||||
return items.map(item => {
|
||||
if (!item || typeof item !== 'object' || (item.kind !== 'edits' && item.kind !== 'finish')) return item;
|
||||
// The on-disk log holds the same normalized edits the agent receives.
|
||||
const edits = normalizeEdits(item.edits);
|
||||
const written = writeExport(session.file, {
|
||||
html: item.html,
|
||||
edits,
|
||||
viewport: item.viewport || null,
|
||||
kind: item.kind
|
||||
});
|
||||
const { html: _html, ...rest } = item;
|
||||
return { ...rest, edits, exportPath: written.exportPath, editsPath: written.editsPath };
|
||||
});
|
||||
}
|
||||
|
||||
function createPlanCanvasServer({
|
||||
store,
|
||||
host = DEFAULT_HOST,
|
||||
@@ -291,10 +317,15 @@ function createPlanCanvasServer({
|
||||
for (const client of clients) client.write(frameText);
|
||||
}
|
||||
|
||||
function presencePayload(key) {
|
||||
const session = store.get(key);
|
||||
return { state: presenceFor(key), agent: (session && session.agent) || null };
|
||||
}
|
||||
|
||||
function broadcastPresence(key) {
|
||||
const state = presenceFor(key);
|
||||
lastPresence.set(key, state);
|
||||
broadcast(key, 'presence', { state });
|
||||
const payload = presencePayload(key);
|
||||
lastPresence.set(key, payload.state);
|
||||
broadcast(key, 'presence', payload);
|
||||
}
|
||||
|
||||
// Re-broadcast only where an expiry actually changed the answer, so an
|
||||
@@ -406,7 +437,15 @@ function createPlanCanvasServer({
|
||||
if (!fs.existsSync(path.resolve(body.file))) {
|
||||
return sendJson(res, 404, { error: `artifact not found: ${body.file}` });
|
||||
}
|
||||
const { session, refused } = store.open(body.file, { reopen: Boolean(body.reopen) });
|
||||
const mode = body.mode === 'ui' ? 'ui' : 'plan';
|
||||
if (mode === 'ui' && !/\.html?$/i.test(body.file)) {
|
||||
return sendJson(res, 400, { error: 'ui canvas sessions require an .html artifact' });
|
||||
}
|
||||
const { session, refused } = store.open(body.file, {
|
||||
reopen: Boolean(body.reopen),
|
||||
mode,
|
||||
ui: body.ui && typeof body.ui === 'object' ? body.ui : null
|
||||
});
|
||||
if (refused) {
|
||||
return sendJson(res, 409, {
|
||||
status: 'user-ended',
|
||||
@@ -420,6 +459,7 @@ function createPlanCanvasServer({
|
||||
status: 'open',
|
||||
key: session.key,
|
||||
file: session.file,
|
||||
mode: session.mode || 'plan',
|
||||
url: `/canvas/${session.key}`
|
||||
});
|
||||
}
|
||||
@@ -436,6 +476,12 @@ function createPlanCanvasServer({
|
||||
const session = keyParam ? store.get(keyParam) : store.findByFile(file);
|
||||
if (!session) return sendJson(res, 200, { status: 'missing' });
|
||||
const key = session.key;
|
||||
const agentParam = url.searchParams.get('agent');
|
||||
if (agentParam) {
|
||||
let descriptor = null;
|
||||
try { descriptor = sanitizeAgentDescriptor(JSON.parse(agentParam)); } catch { descriptor = sanitizeAgentDescriptor({ name: agentParam }); }
|
||||
if (descriptor) store.setAgent(key, descriptor);
|
||||
}
|
||||
const timeoutRaw = url.searchParams.get('timeoutMs');
|
||||
const timeoutMs = timeoutRaw === null ? null : Math.max(0, Number.parseInt(timeoutRaw, 10) || 0);
|
||||
|
||||
@@ -517,7 +563,17 @@ function createPlanCanvasServer({
|
||||
|
||||
if (action === 'feedback') {
|
||||
const body = await readJsonBody(req);
|
||||
const result = store.queueFeedback(key, body.items, { endSession: Boolean(body.endSession) });
|
||||
let items = Array.isArray(body.items) ? body.items : [];
|
||||
if (session.mode === 'ui') {
|
||||
try {
|
||||
items = materializeUiExports(session, items);
|
||||
} catch (error) {
|
||||
if (error.code === 'EUI_HTML_TOO_LARGE') return sendJson(res, 413, { error: 'html snapshot too large' });
|
||||
if (error.code === 'EUI_HTML_MISSING') return sendJson(res, 400, { error: 'edits and finish items need an html snapshot' });
|
||||
return sendJson(res, 500, { error: `could not write the export next to the artifact: ${error.message}` });
|
||||
}
|
||||
}
|
||||
const result = store.queueFeedback(key, items, { endSession: Boolean(body.endSession) });
|
||||
if (!result) return sendJson(res, 409, { error: 'session already ended' });
|
||||
wake.emit(`wake:${key}`);
|
||||
broadcast(key, 'chat-sync', { chat: store.get(key).chat });
|
||||
@@ -581,7 +637,7 @@ function createPlanCanvasServer({
|
||||
connection: 'keep-alive'
|
||||
});
|
||||
res.write(`event: chat-sync\ndata: ${JSON.stringify({ chat: session.chat })}\n\n`);
|
||||
res.write(`event: presence\ndata: ${JSON.stringify({ state: presenceFor(key) })}\n\n`);
|
||||
res.write(`event: presence\ndata: ${JSON.stringify(presencePayload(key))}\n\n`);
|
||||
if (!sseClients.has(key)) sseClients.set(key, new Set());
|
||||
sseClients.get(key).add(res);
|
||||
lastPresence.set(key, presenceFor(key));
|
||||
@@ -621,7 +677,9 @@ function createPlanCanvasServer({
|
||||
});
|
||||
return sendHtml(res, 200, html, { csp: 'artifact' });
|
||||
}
|
||||
const sdkTag = '<script src="/sdk.js"></script>';
|
||||
const sdkTag = session.mode === 'ui'
|
||||
? '<script src="/ui-editor.js" data-ecc-ui-canvas="editor"></script>'
|
||||
: '<script src="/sdk.js"></script>';
|
||||
const injected = content.includes('</body>')
|
||||
? content.replace('</body>', `${sdkTag}\n</body>`)
|
||||
: `${content}\n${sdkTag}`;
|
||||
@@ -696,11 +754,23 @@ function createPlanCanvasServer({
|
||||
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(artifactSdkJs());
|
||||
}
|
||||
if (req.method === 'GET' && pathname === '/ui-canvas.css') {
|
||||
res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(uiCanvasCss());
|
||||
}
|
||||
if (req.method === 'GET' && pathname === '/ui-client.js') {
|
||||
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(uiClientJs());
|
||||
}
|
||||
if (req.method === 'GET' && pathname === '/ui-editor.js') {
|
||||
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(uiEditorJs());
|
||||
}
|
||||
const canvasMatch = pathname.match(/^\/canvas\/([a-f0-9]{12})$/);
|
||||
if (req.method === 'GET' && canvasMatch) {
|
||||
const session = store.get(canvasMatch[1]);
|
||||
if (!session) return sendHtml(res, 404, '<h1>Unknown session</h1>');
|
||||
return sendHtml(res, 200, renderCanvasHtml(session));
|
||||
return sendHtml(res, 200, session.mode === 'ui' ? renderUiCanvasHtml(session) : renderCanvasHtml(session));
|
||||
}
|
||||
const eventsMatch = pathname.match(/^\/events\/([a-f0-9]{12})$/);
|
||||
if (req.method === 'GET' && eventsMatch) {
|
||||
|
||||
@@ -13,8 +13,15 @@ const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { normalizeUiFeedbackItem, uiChatLineFor } = require('../ui-canvas/feedback');
|
||||
const { sanitizeAgentDescriptor } = require('./agent-identity');
|
||||
|
||||
const FEEDBACK_KINDS = new Set(['chat', 'annotation', 'verdict']);
|
||||
const VERDICTS = new Set(['approve', 'request-changes']);
|
||||
// A session renders either as a Plan Canvas review (markdown or HTML with the
|
||||
// annotation layer) or as a UI Canvas editing surface (HTML mockup with the
|
||||
// in-page editor). Both share one server, one state file, and one queue.
|
||||
const SESSION_MODES = new Set(['plan', 'ui']);
|
||||
|
||||
// The producer and the SessionStart/Stop hooks must land on one directory. The
|
||||
// hooks resolve CLAUDE_CONFIG_DIR (they cannot require this file: managed
|
||||
@@ -138,7 +145,7 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
// Open (or resume) a session. A session the *user* ended from the browser
|
||||
// is sticky: it refuses a plain reopen so agents do not pop the browser
|
||||
// back up uninvited. Pass reopen:true only when the human asked.
|
||||
function open(filePath, { reopen = false } = {}) {
|
||||
function open(filePath, { reopen = false, mode = 'plan', ui = null } = {}) {
|
||||
const canonical = canonicalizeArtifactPath(filePath);
|
||||
const key = sessionKeyFor(canonical);
|
||||
const existing = state.sessions[key];
|
||||
@@ -152,6 +159,12 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
pendingFeedback: [],
|
||||
createdAt: nowIso()
|
||||
};
|
||||
session.mode = SESSION_MODES.has(mode) ? mode : 'plan';
|
||||
if (session.mode === 'ui') {
|
||||
session.ui = sanitizeUiOptions(ui, existing && existing.ui);
|
||||
} else {
|
||||
delete session.ui;
|
||||
}
|
||||
session.status = 'open';
|
||||
delete session.endedBy;
|
||||
session.updatedAt = nowIso();
|
||||
@@ -160,21 +173,36 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
return { session, refused: false };
|
||||
}
|
||||
|
||||
// Record which agent process is (or was last) listening on a session so the
|
||||
// browser can name it. Kept in state so a reconnecting browser sees it too.
|
||||
function setAgent(key, descriptor) {
|
||||
const session = get(key);
|
||||
if (!session) return null;
|
||||
const agent = sanitizeAgentDescriptor(descriptor);
|
||||
if (!agent) return session.agent || null;
|
||||
agent.seenAt = nowIso();
|
||||
session.agent = agent;
|
||||
persist();
|
||||
return agent;
|
||||
}
|
||||
|
||||
// Queue feedback from the browser. Chat-shaped items are mirrored into the
|
||||
// session transcript immediately so the conversation panel stays coherent
|
||||
// across reloads.
|
||||
function queueFeedback(key, rawItems, { endSession = false } = {}) {
|
||||
const session = get(key);
|
||||
if (!session || session.status === 'ended') return null;
|
||||
const normalize = session.mode === 'ui' ? normalizeUiFeedbackItem : normalizeFeedbackItem;
|
||||
const describe = session.mode === 'ui' ? uiChatLineFor : chatLineFor;
|
||||
const accepted = [];
|
||||
for (const raw of Array.isArray(rawItems) ? rawItems : []) {
|
||||
state.feedbackCounter += 1;
|
||||
const item = normalizeFeedbackItem(raw, state.feedbackCounter);
|
||||
const item = normalize(raw, state.feedbackCounter);
|
||||
if (item) accepted.push(item);
|
||||
}
|
||||
session.pendingFeedback.push(...accepted);
|
||||
for (const item of accepted) {
|
||||
session.chat.push({ role: 'user', kind: item.kind, text: chatLineFor(item), at: item.at });
|
||||
session.chat.push({ role: 'user', kind: item.kind, text: describe(item), at: item.at });
|
||||
}
|
||||
if (endSession) {
|
||||
session.status = 'ended';
|
||||
@@ -237,9 +265,11 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
return Object.values(state.sessions).map(session => ({
|
||||
key: session.key,
|
||||
file: session.file,
|
||||
mode: session.mode || 'plan',
|
||||
status: session.status,
|
||||
endedBy: session.endedBy,
|
||||
pending: session.pendingFeedback.length,
|
||||
agent: session.agent || null,
|
||||
updatedAt: session.updatedAt
|
||||
}));
|
||||
}
|
||||
@@ -257,12 +287,26 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
queueFeedback,
|
||||
takeFeedback,
|
||||
addAgentReply,
|
||||
setAgent,
|
||||
end,
|
||||
list,
|
||||
hasOpenSessions
|
||||
};
|
||||
}
|
||||
|
||||
// UI Canvas options travel with the session so a reconnecting browser opens
|
||||
// on the viewport the agent asked for. Unknown presets fall back to desktop.
|
||||
function sanitizeUiOptions(raw, previous) {
|
||||
const base = previous && typeof previous === 'object' ? { ...previous } : {};
|
||||
const input = raw && typeof raw === 'object' ? raw : {};
|
||||
const out = { viewport: base.viewport || 'desktop', title: base.title || '' };
|
||||
if (typeof input.viewport === 'string' && /^(mobile|desktop|custom|\d{2,5}x\d{2,5})$/.test(input.viewport.trim())) {
|
||||
out.viewport = input.viewport.trim();
|
||||
}
|
||||
if (typeof input.title === 'string' && input.title.trim()) out.title = sanitizeText(input.title.trim(), 120);
|
||||
return out;
|
||||
}
|
||||
|
||||
// One-line rendering of a feedback item for the conversation transcript.
|
||||
function chatLineFor(item) {
|
||||
if (item.kind === 'verdict') {
|
||||
@@ -277,9 +321,11 @@ function chatLineFor(item) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SESSION_MODES,
|
||||
canonicalizeArtifactPath,
|
||||
createSessionStore,
|
||||
normalizeFeedbackItem,
|
||||
resolveStateDir,
|
||||
sanitizeUiOptions,
|
||||
sessionKeyFor
|
||||
};
|
||||
@@ -589,7 +589,8 @@ function renderSessionListHtml(sessions) {
|
||||
const link = s.status === 'ended'
|
||||
? escapeHtml(path.basename(s.file))
|
||||
: `<a href="/canvas/${escapeHtml(s.key)}">${escapeHtml(path.basename(s.file))}</a>`;
|
||||
return `<tr><td>${link}</td><td class="mono">${escapeHtml(s.file)}</td><td><span class="badge ${escapeHtml(s.status)}">${status}</span></td></tr>`;
|
||||
const mode = s.mode === 'ui' ? '<span class="badge mode">ui canvas</span> ' : '';
|
||||
return `<tr><td>${mode}${link}</td><td class="mono">${escapeHtml(s.file)}</td><td><span class="badge ${escapeHtml(s.status)}">${status}</span></td></tr>`;
|
||||
}).join('\n');
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
@@ -609,17 +610,19 @@ ${TOKENS_CSS}
|
||||
.mono{font-family:var(--mono);font-size:11.5px;color:var(--text2)}
|
||||
.badge{font-size:11px;padding:2px 8px;border-radius:99px;background:var(--bg3);border:1px solid var(--border);color:var(--text2)}
|
||||
.badge.open,.badge.feedback{color:var(--green);border-color:var(--green);background:var(--green-glow)}
|
||||
.badge.mode{color:var(--pink);border-color:var(--pink);background:var(--pink-glow);margin-right:6px}
|
||||
.empty{margin-top:24px;color:var(--text3);font-size:13px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<span class="logo">E</span><h1>Plan Canvas sessions</h1>
|
||||
${sessions.length ? `<table><thead><tr><th>Artifact</th><th>Path</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<p class="empty">No sessions yet. Ask your agent to open a plan with the plan-canvas skill.</p>'}
|
||||
${sessions.length ? `<table><thead><tr><th>Artifact</th><th>Path</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<p class="empty">No sessions yet. Ask your agent to open a plan with the plan-canvas skill or a mockup with the ui-canvas skill.</p>'}
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TOKENS_CSS,
|
||||
canvasCss,
|
||||
canvasClientJs,
|
||||
renderCanvasHtml,
|
||||
|
||||
@@ -0,0 +1,969 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* UI Canvas in-page editor: the script injected into the mockup iframe.
|
||||
*
|
||||
* Runs inside the sandboxed artifact frame (opaque origin, postMessage only)
|
||||
* and turns the rendered component into something the reviewer can edit
|
||||
* directly: hover and click to select, drag the eight handles to resize,
|
||||
* drag the body to reorder, Alt-drag or arrow keys to nudge, double-click to
|
||||
* edit text, Delete to remove. Every change is recorded as a structured edit
|
||||
* that can be re-applied after the agent live-reloads the file, undone, and
|
||||
* exported together with a clean DOM snapshot.
|
||||
*
|
||||
* All editor UI lives in a shadow root so it never styles, selects, or
|
||||
* exports itself. Served as a string so coverage and lint treat it as data;
|
||||
* it is syntax-checked by tests/lib/ui-canvas-editor.test.js.
|
||||
*
|
||||
* Conventions borrowed, with thanks: Enter/Shift+Enter to walk the tree and
|
||||
* Delete to remove from VisBug (GoogleChromeLabs/ProjectVisBug), the
|
||||
* design/preview mode split from Onlook (onlook-dev/onlook).
|
||||
*/
|
||||
|
||||
function uiEditorJs() {
|
||||
return String.raw`'use strict';
|
||||
(() => {
|
||||
if (window.parent === window) return;
|
||||
if (window.__eccUiCanvasEditor) return;
|
||||
window.__eccUiCanvasEditor = true;
|
||||
|
||||
var post = function (msg) { window.parent.postMessage(msg, '*'); };
|
||||
|
||||
// ---- state -------------------------------------------------------------
|
||||
var mode = 'edit';
|
||||
var selected = null;
|
||||
var hovered = null;
|
||||
var editing = null;
|
||||
var edits = [];
|
||||
var redoStack = [];
|
||||
var editSeq = 0;
|
||||
var gesture = null;
|
||||
var animationsPaused = false;
|
||||
var ACCENT = '#22c55e';
|
||||
|
||||
var RESET_VALUES = {
|
||||
'background-color': 'transparent', 'background-image': 'none', 'color': 'inherit',
|
||||
'border': 'none', 'border-radius': '0', 'box-shadow': 'none', 'padding': '0',
|
||||
'margin': '0', 'gap': '0', 'font-size': 'inherit', 'font-weight': 'normal',
|
||||
'line-height': 'normal', 'opacity': '1', 'text-align': 'start', 'outline': 'none'
|
||||
};
|
||||
var NON_TEXT_TAGS = { IMG: 1, VIDEO: 1, AUDIO: 1, SVG: 1, CANVAS: 1, IFRAME: 1, INPUT: 1, SELECT: 1, TEXTAREA: 1, HR: 1, BR: 1, PICTURE: 1, SOURCE: 1, OBJECT: 1, EMBED: 1 };
|
||||
|
||||
// ---- overlay host --------------------------------------------------------
|
||||
var host = document.createElement('div');
|
||||
host.setAttribute('data-ecc-ui-canvas', 'overlay');
|
||||
host.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;pointer-events:none';
|
||||
var root = host.attachShadow({ mode: 'open' });
|
||||
root.innerHTML = '' +
|
||||
'<style>' +
|
||||
':host{all:initial}' +
|
||||
'.hover{position:fixed;pointer-events:none;display:none;border:1px dashed ' + ACCENT + ';border-radius:3px;box-sizing:border-box}' +
|
||||
'.sel{position:fixed;pointer-events:none;display:none;outline:2px solid ' + ACCENT + ';outline-offset:-1px;border-radius:3px;box-sizing:border-box}' +
|
||||
'.sel.editing{outline-style:dashed}' +
|
||||
'.sel.dragging{opacity:.35}' +
|
||||
'.handle{position:absolute;width:10px;height:10px;margin:-5px;background:#fff;border:1.5px solid ' + ACCENT + ';border-radius:2.5px;box-sizing:border-box;pointer-events:auto;box-shadow:0 1px 3px rgba(0,0,0,.35)}' +
|
||||
'.sel.editing .handle,.sel.dragging .handle{display:none}' +
|
||||
'.handle[data-dir="n"]{top:0;left:50%;cursor:ns-resize}.handle[data-dir="s"]{top:100%;left:50%;cursor:ns-resize}' +
|
||||
'.handle[data-dir="e"]{top:50%;left:100%;cursor:ew-resize}.handle[data-dir="w"]{top:50%;left:0;cursor:ew-resize}' +
|
||||
'.handle[data-dir="ne"]{top:0;left:100%;cursor:nesw-resize}.handle[data-dir="sw"]{top:100%;left:0;cursor:nesw-resize}' +
|
||||
'.handle[data-dir="nw"]{top:0;left:0;cursor:nwse-resize}.handle[data-dir="se"]{top:100%;left:100%;cursor:nwse-resize}' +
|
||||
'.label{position:absolute;left:-1px;top:-26px;background:#101218;color:#dfe2e9;border:1px solid #272c3e;border-radius:6px;padding:3px 8px;font:600 10.5px/1.3 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;white-space:nowrap;pointer-events:none;box-shadow:0 4px 16px rgba(0,0,0,.45)}' +
|
||||
'.label.inside{top:4px;left:4px}' +
|
||||
'.label b{color:#4acb8a;font-weight:600}.label span{color:#80859a;margin-left:6px;font-weight:500}' +
|
||||
'.drop{position:fixed;pointer-events:none;display:none;background:' + ACCENT + ';border-radius:2px;box-shadow:0 0 0 2px rgba(34,197,94,.25)}' +
|
||||
'.ghost{position:fixed;pointer-events:none;display:none;border:1px solid ' + ACCENT + ';background:rgba(34,197,94,.12);border-radius:3px;box-sizing:border-box}' +
|
||||
'.toast{position:fixed;left:50%;bottom:14px;transform:translateX(-50%);display:none;background:#101218;color:#dfe2e9;border:1px solid #272c3e;border-radius:99px;padding:6px 14px;font:500 11.5px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;box-shadow:0 8px 32px rgba(0,0,0,.5);white-space:nowrap}' +
|
||||
'</style>' +
|
||||
'<div class="hover"></div>' +
|
||||
'<div class="sel">' +
|
||||
'<div class="label"><b></b><span></span></div>' +
|
||||
'<div class="handle" data-dir="n"></div><div class="handle" data-dir="s"></div>' +
|
||||
'<div class="handle" data-dir="e"></div><div class="handle" data-dir="w"></div>' +
|
||||
'<div class="handle" data-dir="ne"></div><div class="handle" data-dir="nw"></div>' +
|
||||
'<div class="handle" data-dir="se"></div><div class="handle" data-dir="sw"></div>' +
|
||||
'</div>' +
|
||||
'<div class="drop"></div><div class="ghost"></div><div class="toast"></div>';
|
||||
var hoverBox = root.querySelector('.hover');
|
||||
var selBox = root.querySelector('.sel');
|
||||
var labelEl = selBox.querySelector('.label');
|
||||
var dropEl = root.querySelector('.drop');
|
||||
var ghostEl = root.querySelector('.ghost');
|
||||
var toastEl = root.querySelector('.toast');
|
||||
var pauseStyle = document.createElement('style');
|
||||
pauseStyle.setAttribute('data-ecc-ui-canvas', 'pause');
|
||||
pauseStyle.textContent = '*,*::before,*::after{animation-play-state:paused!important;transition:none!important}';
|
||||
|
||||
function attachHost() { if (document.body && !host.isConnected) document.body.appendChild(host); }
|
||||
attachHost();
|
||||
|
||||
var toastTimer = null;
|
||||
function toast(text) {
|
||||
toastEl.textContent = text;
|
||||
toastEl.style.display = 'block';
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(function () { toastEl.style.display = 'none'; }, 1800);
|
||||
}
|
||||
|
||||
// ---- element helpers ---------------------------------------------------------
|
||||
function isOurs(node) {
|
||||
return node === host || (node && node.getRootNode && node.getRootNode() === root) || (node && node.hasAttribute && node.hasAttribute('data-ecc-ui-canvas'));
|
||||
}
|
||||
function isElement(node) { return node && node.nodeType === 1; }
|
||||
function selectable(node) {
|
||||
return isElement(node) && !isOurs(node) && node !== document.documentElement;
|
||||
}
|
||||
function esc(value) {
|
||||
return (window.CSS && CSS.escape) ? CSS.escape(value) : String(value).replace(/[^a-zA-Z0-9_-]/g, function (c) { return '\\' + c; });
|
||||
}
|
||||
function elementChildren(parent) {
|
||||
var out = [];
|
||||
for (var i = 0; i < parent.children.length; i++) if (!isOurs(parent.children[i])) out.push(parent.children[i]);
|
||||
return out;
|
||||
}
|
||||
function indexIn(parent, el) { return elementChildren(parent).indexOf(el); }
|
||||
function nthOfType(el) {
|
||||
var n = 1;
|
||||
var sib = el;
|
||||
while ((sib = sib.previousElementSibling)) if (sib.tagName === el.tagName) n++;
|
||||
return n;
|
||||
}
|
||||
function stepFor(el) {
|
||||
var tag = el.tagName.toLowerCase();
|
||||
if (tag === 'body' || tag === 'html') return tag;
|
||||
var classes = Array.prototype.filter.call(el.classList, function (c) { return /^[A-Za-z_][\w-]*$/.test(c); }).slice(0, 2);
|
||||
var step = tag + classes.map(function (c) { return '.' + esc(c); }).join('');
|
||||
return step + ':nth-of-type(' + nthOfType(el) + ')';
|
||||
}
|
||||
// Prefer a unique id, else a type path scoped to the nearest id. Verified
|
||||
// unique so re-application after a reload lands on the same node.
|
||||
function selectorFor(el) {
|
||||
if (!isElement(el)) return 'body';
|
||||
if (el.id && /^[A-Za-z_][\w-]*$/.test(el.id) && document.querySelectorAll('#' + esc(el.id)).length === 1) return '#' + esc(el.id);
|
||||
var parts = [];
|
||||
var node = el;
|
||||
while (node && isElement(node) && node !== document.documentElement) {
|
||||
if (node !== el && node.id && /^[A-Za-z_][\w-]*$/.test(node.id) && document.querySelectorAll('#' + esc(node.id)).length === 1) {
|
||||
parts.unshift('#' + esc(node.id));
|
||||
break;
|
||||
}
|
||||
parts.unshift(stepFor(node));
|
||||
if (node.tagName === 'BODY') break;
|
||||
node = node.parentElement;
|
||||
}
|
||||
var selector = parts.join(' > ');
|
||||
try { if (document.querySelectorAll(selector).length === 1) return selector; } catch (_e) { /* fall through */ }
|
||||
return selector;
|
||||
}
|
||||
function resolve(selector) {
|
||||
try { var el = document.querySelector(selector); return el && !isOurs(el) ? el : null; } catch (_e) { return null; }
|
||||
}
|
||||
function snippetFor(el) {
|
||||
if (!isElement(el)) return '';
|
||||
if (el.tagName === 'IMG') return el.getAttribute('alt') || (el.getAttribute('src') || '').split('/').pop().slice(0, 80);
|
||||
if (el.tagName === 'INPUT') return el.getAttribute('placeholder') || el.value || el.type;
|
||||
return (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 120);
|
||||
}
|
||||
function labelFor(el) {
|
||||
var tag = el.tagName.toLowerCase();
|
||||
var ident = el.id ? '#' + el.id : (el.classList.length ? '.' + Array.prototype.slice.call(el.classList, 0, 2).join('.') : '');
|
||||
return tag + ident;
|
||||
}
|
||||
function isTextEditable(el) {
|
||||
if (!isElement(el) || NON_TEXT_TAGS[el.tagName]) return false;
|
||||
if (el === document.body) return false;
|
||||
for (var i = 0; i < el.childNodes.length; i++) {
|
||||
var child = el.childNodes[i];
|
||||
if (child.nodeType === 3 && child.textContent.trim()) return true;
|
||||
}
|
||||
return el.children.length > 0 && !hasBlockChildren(el) && (el.innerText || '').trim().length > 0;
|
||||
}
|
||||
function hasBlockChildren(el) {
|
||||
for (var i = 0; i < el.children.length; i++) {
|
||||
var display = getComputedStyle(el.children[i]).display;
|
||||
if (display !== 'inline' && display !== 'inline-block') return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function px(value) { var n = parseFloat(value); return isFinite(n) ? n : 0; }
|
||||
function sides(cs, prefix, suffix) {
|
||||
var t = cs.getPropertyValue(prefix + '-top' + suffix), r = cs.getPropertyValue(prefix + '-right' + suffix);
|
||||
var b = cs.getPropertyValue(prefix + '-bottom' + suffix), l = cs.getPropertyValue(prefix + '-left' + suffix);
|
||||
if (t === r && r === b && b === l) return t;
|
||||
if (t === b && r === l) return t + ' ' + r;
|
||||
return t + ' ' + r + ' ' + b + ' ' + l;
|
||||
}
|
||||
function borderSummary(cs) {
|
||||
var width = cs.borderTopWidth;
|
||||
if (px(width) === 0 && px(cs.borderRightWidth) === 0 && px(cs.borderBottomWidth) === 0 && px(cs.borderLeftWidth) === 0) return 'none';
|
||||
return width + ' ' + cs.borderTopStyle + ' ' + cs.borderTopColor;
|
||||
}
|
||||
function styleReport(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
var isFlexOrGrid = cs.display.indexOf('flex') >= 0 || cs.display.indexOf('grid') >= 0;
|
||||
var rows = [
|
||||
['background-color', cs.backgroundColor],
|
||||
['background-image', cs.backgroundImage === 'none' ? null : cs.backgroundImage],
|
||||
['color', cs.color],
|
||||
['border', borderSummary(cs)],
|
||||
['border-radius', sides(cs, 'border', '-radius').replace(/-top-left|-top-right|-bottom-right|-bottom-left/g, '')],
|
||||
['box-shadow', cs.boxShadow],
|
||||
['padding', sides(cs, 'padding', '')],
|
||||
['margin', sides(cs, 'margin', '')],
|
||||
['gap', isFlexOrGrid ? (cs.rowGap === cs.columnGap ? cs.rowGap : cs.rowGap + ' ' + cs.columnGap) : null],
|
||||
['font-size', cs.fontSize],
|
||||
['font-weight', cs.fontWeight],
|
||||
['line-height', cs.lineHeight],
|
||||
['text-align', cs.textAlign],
|
||||
['opacity', cs.opacity],
|
||||
['display', cs.display]
|
||||
];
|
||||
var out = [];
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
if (rows[i][1] === null || rows[i][1] === undefined || rows[i][1] === '') continue;
|
||||
out.push({ property: rows[i][0], value: rows[i][1], inline: el.style.getPropertyValue(rows[i][0]) || '', resettable: Object.prototype.hasOwnProperty.call(RESET_VALUES, rows[i][0]) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function describe(el) {
|
||||
var rect = el.getBoundingClientRect();
|
||||
return {
|
||||
selector: selectorFor(el),
|
||||
tag: el.tagName.toLowerCase(),
|
||||
id: el.id || '',
|
||||
classes: Array.prototype.slice.call(el.classList, 0, 6),
|
||||
snippet: snippetFor(el),
|
||||
size: { width: Math.round(rect.width), height: Math.round(rect.height) },
|
||||
editable: isTextEditable(el),
|
||||
isImage: el.tagName === 'IMG'
|
||||
};
|
||||
}
|
||||
function breadcrumbFor(el) {
|
||||
var trail = [];
|
||||
var node = el;
|
||||
while (node && isElement(node) && node !== document.documentElement) {
|
||||
trail.unshift({ selector: selectorFor(node), label: labelFor(node) });
|
||||
if (node.tagName === 'BODY') break;
|
||||
node = node.parentElement;
|
||||
}
|
||||
return trail.slice(-6);
|
||||
}
|
||||
|
||||
// ---- overlay positioning -------------------------------------------------
|
||||
function place(box, rect) {
|
||||
box.style.display = 'block';
|
||||
box.style.left = rect.left + 'px';
|
||||
box.style.top = rect.top + 'px';
|
||||
box.style.width = Math.max(0, rect.width) + 'px';
|
||||
box.style.height = Math.max(0, rect.height) + 'px';
|
||||
}
|
||||
function updateBoxes() {
|
||||
if (mode !== 'edit') { hoverBox.style.display = 'none'; selBox.style.display = 'none'; return; }
|
||||
if (hovered && hovered.isConnected && hovered !== selected) place(hoverBox, hovered.getBoundingClientRect());
|
||||
else hoverBox.style.display = 'none';
|
||||
if (selected && selected.isConnected) {
|
||||
var rect = selected.getBoundingClientRect();
|
||||
place(selBox, rect);
|
||||
labelEl.querySelector('b').textContent = labelFor(selected);
|
||||
labelEl.querySelector('span').textContent = Math.round(rect.width) + ' × ' + Math.round(rect.height);
|
||||
labelEl.classList.toggle('inside', rect.top < 30);
|
||||
} else {
|
||||
selBox.style.display = 'none';
|
||||
if (selected && !selected.isConnected) { selected = null; postSelection(); }
|
||||
}
|
||||
}
|
||||
var rafPending = false;
|
||||
function scheduleBoxes() {
|
||||
if (rafPending) return;
|
||||
rafPending = true;
|
||||
requestAnimationFrame(function () { rafPending = false; updateBoxes(); });
|
||||
}
|
||||
|
||||
// ---- selection -----------------------------------------------------------------
|
||||
function postSelection() {
|
||||
if (!selected || !selected.isConnected) { post({ type: 'uc:selection', selection: null }); return; }
|
||||
var info = describe(selected);
|
||||
info.styles = styleReport(selected);
|
||||
info.breadcrumb = breadcrumbFor(selected);
|
||||
post({ type: 'uc:selection', selection: info });
|
||||
}
|
||||
function select(el) {
|
||||
if (editing && editing.el !== el) commitTextEdit();
|
||||
selected = selectable(el) ? el : null;
|
||||
updateBoxes();
|
||||
postSelection();
|
||||
}
|
||||
function deselect() { select(null); }
|
||||
|
||||
// ---- edit log -----------------------------------------------------------------
|
||||
function newEdit(kind, el, detail) {
|
||||
editSeq += 1;
|
||||
var edit = { id: 'e' + editSeq + '-' + Date.now().toString(36), kind: kind, selector: selectorFor(el), tag: el.tagName.toLowerCase(), snippet: snippetFor(el), at: new Date().toISOString() };
|
||||
for (var key in detail) if (Object.prototype.hasOwnProperty.call(detail, key)) edit[key] = detail[key];
|
||||
return edit;
|
||||
}
|
||||
function publicEdit(edit) {
|
||||
var out = {};
|
||||
for (var key in edit) if (Object.prototype.hasOwnProperty.call(edit, key) && key.charAt(0) !== '_') out[key] = edit[key];
|
||||
return out;
|
||||
}
|
||||
function postEdits() {
|
||||
post({ type: 'uc:edits', edits: edits.map(publicEdit), canUndo: edits.some(function (e) { return !e.stale; }), canRedo: redoStack.length > 0 });
|
||||
}
|
||||
function record(edit) {
|
||||
edits.push(edit);
|
||||
redoStack = [];
|
||||
postEdits();
|
||||
postSelection();
|
||||
scheduleBoxes();
|
||||
}
|
||||
function insertAt(parent, el, index) {
|
||||
var kids = elementChildren(parent).filter(function (k) { return k !== el; });
|
||||
var ref = index < kids.length ? kids[index] : null;
|
||||
parent.insertBefore(el, ref);
|
||||
}
|
||||
function applyInline(el, values) {
|
||||
for (var prop in values) if (Object.prototype.hasOwnProperty.call(values, prop)) {
|
||||
if (values[prop] === '' || values[prop] === null || values[prop] === undefined) el.style.removeProperty(prop);
|
||||
else el.style.setProperty(prop, values[prop]);
|
||||
}
|
||||
}
|
||||
function captureInline(el, props) {
|
||||
var out = {};
|
||||
for (var i = 0; i < props.length; i++) out[props[i]] = el.style.getPropertyValue(props[i]);
|
||||
return out;
|
||||
}
|
||||
function contentBoxDelta(el, cs) {
|
||||
if (cs.boxSizing === 'border-box') return { w: 0, h: 0 };
|
||||
return {
|
||||
w: px(cs.paddingLeft) + px(cs.paddingRight) + px(cs.borderLeftWidth) + px(cs.borderRightWidth),
|
||||
h: px(cs.paddingTop) + px(cs.paddingBottom) + px(cs.borderTopWidth) + px(cs.borderBottomWidth)
|
||||
};
|
||||
}
|
||||
function sizeStyles(el, width, height) {
|
||||
var cs = getComputedStyle(el);
|
||||
var delta = contentBoxDelta(el, cs);
|
||||
var out = {};
|
||||
if (width !== undefined && width !== null) out.width = Math.max(1, Math.round(width - delta.w)) + 'px';
|
||||
if (height !== undefined && height !== null) out.height = Math.max(1, Math.round(height - delta.h)) + 'px';
|
||||
var parent = el.parentElement;
|
||||
if (parent && getComputedStyle(parent).display.indexOf('flex') >= 0 && cs.flexGrow !== '0') out.flex = '0 0 auto';
|
||||
if (el.tagName === 'IMG' && (width !== undefined || height !== undefined)) {
|
||||
if (width !== undefined && height === undefined) out.height = 'auto';
|
||||
out['max-width'] = 'none';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Apply a recorded edit to the live document. The el argument is the element the
|
||||
// edit targets (resolved by selector during re-application). Returns false
|
||||
// when the document no longer matches, so the edit can be flagged stale.
|
||||
function applyEdit(edit, el) {
|
||||
el = el || resolve(edit.selector);
|
||||
if (edit.kind === 'remove') {
|
||||
if (!el) return false;
|
||||
var parent = el.parentElement;
|
||||
edit._el = el;
|
||||
edit._parent = parent;
|
||||
edit._index = indexIn(parent, el);
|
||||
el.remove();
|
||||
return true;
|
||||
}
|
||||
if (!el) return false;
|
||||
if (edit.kind === 'text') {
|
||||
if (edit._htmlBefore === undefined) edit._htmlBefore = el.innerHTML;
|
||||
el.innerHTML = edit.htmlAfter !== undefined ? edit.htmlAfter : '';
|
||||
if (edit.htmlAfter === undefined) el.textContent = edit.after;
|
||||
edit._el = el;
|
||||
return true;
|
||||
}
|
||||
if (edit.kind === 'resize') {
|
||||
var styles = sizeStyles(el, edit.width, edit.height);
|
||||
if (!edit._inlineBefore) edit._inlineBefore = captureInline(el, Object.keys(styles));
|
||||
applyInline(el, styles);
|
||||
edit._el = el;
|
||||
return true;
|
||||
}
|
||||
if (edit.kind === 'nudge') {
|
||||
var cs = getComputedStyle(el);
|
||||
if (!edit._inlineBefore) edit._inlineBefore = captureInline(el, ['position', 'left', 'top']);
|
||||
var baseLeft = px(el.style.left), baseTop = px(el.style.top);
|
||||
var next = { left: (baseLeft + edit.dx) + 'px', top: (baseTop + edit.dy) + 'px' };
|
||||
if (cs.position === 'static') next.position = 'relative';
|
||||
applyInline(el, next);
|
||||
edit._el = el;
|
||||
return true;
|
||||
}
|
||||
if (edit.kind === 'move') {
|
||||
var target = resolve(edit.to.parent);
|
||||
if (!target) return false;
|
||||
edit._fromParent = el.parentElement;
|
||||
edit._fromIndex = indexIn(el.parentElement, el);
|
||||
insertAt(target, el, edit.to.index);
|
||||
edit._el = el;
|
||||
return true;
|
||||
}
|
||||
if (edit.kind === 'style') {
|
||||
if (!edit._inlineBefore) edit._inlineBefore = captureInline(el, [edit.property]);
|
||||
var value = edit.after === null ? RESET_VALUES[edit.property] : edit.after;
|
||||
if (value === undefined) return false;
|
||||
el.style.setProperty(edit.property, value);
|
||||
edit._el = el;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function revertEdit(edit) {
|
||||
if (edit.stale) return false;
|
||||
var el = edit._el && edit._el.isConnected ? edit._el : (edit.kind === 'remove' ? edit._el : resolve(edit.selector));
|
||||
if (edit.kind === 'remove') {
|
||||
if (!el || !edit._parent) return false;
|
||||
insertAt(edit._parent, el, edit._index);
|
||||
return true;
|
||||
}
|
||||
if (!el) return false;
|
||||
if (edit.kind === 'text') { el.innerHTML = edit._htmlBefore !== undefined ? edit._htmlBefore : edit.before; return true; }
|
||||
if (edit.kind === 'resize' || edit.kind === 'nudge' || edit.kind === 'style') { applyInline(el, edit._inlineBefore || {}); return true; }
|
||||
if (edit.kind === 'move') {
|
||||
if (!edit._fromParent) return false;
|
||||
insertAt(edit._fromParent, el, edit._fromIndex);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function undo() {
|
||||
for (var i = edits.length - 1; i >= 0; i--) {
|
||||
if (edits[i].stale) continue;
|
||||
var edit = edits.splice(i, 1)[0];
|
||||
revertEdit(edit);
|
||||
redoStack.push(edit);
|
||||
if (edit.kind === 'remove' && edit._el) select(edit._el);
|
||||
toast('Undid ' + edit.kind);
|
||||
break;
|
||||
}
|
||||
postEdits();
|
||||
postSelection();
|
||||
scheduleBoxes();
|
||||
}
|
||||
function redo() {
|
||||
var edit = redoStack.pop();
|
||||
if (!edit) return;
|
||||
if (applyEdit(edit, edit._el && edit._el.isConnected ? edit._el : null)) { edits.push(edit); toast('Redid ' + edit.kind); }
|
||||
postEdits();
|
||||
postSelection();
|
||||
scheduleBoxes();
|
||||
}
|
||||
function resetAll() {
|
||||
for (var i = edits.length - 1; i >= 0; i--) revertEdit(edits[i]);
|
||||
edits = [];
|
||||
redoStack = [];
|
||||
postEdits();
|
||||
postSelection();
|
||||
scheduleBoxes();
|
||||
toast('All edits reverted');
|
||||
}
|
||||
// After the agent rewrites the file the frame reloads from scratch; the
|
||||
// shell hands back the edit log and we replay it in order. Edits whose
|
||||
// selector no longer resolves stay in the log, flagged stale, so the human
|
||||
// and the agent both see what did not survive.
|
||||
function restore(payload) {
|
||||
var incoming = Array.isArray(payload.edits) ? payload.edits : [];
|
||||
edits = [];
|
||||
redoStack = [];
|
||||
for (var i = 0; i < incoming.length; i++) {
|
||||
var edit = {};
|
||||
for (var key in incoming[i]) if (Object.prototype.hasOwnProperty.call(incoming[i], key)) edit[key] = incoming[i][key];
|
||||
delete edit.stale;
|
||||
if (!applyEdit(edit, null)) edit.stale = true;
|
||||
edits.push(edit);
|
||||
var seq = parseInt(String(edit.id).slice(1), 10);
|
||||
if (seq > editSeq) editSeq = seq;
|
||||
}
|
||||
if (payload.scroll) window.scrollTo(payload.scroll.x || 0, payload.scroll.y || 0);
|
||||
if (payload.selection) { var el = resolve(payload.selection); if (el) selected = el; }
|
||||
updateBoxes();
|
||||
postEdits();
|
||||
postSelection();
|
||||
}
|
||||
|
||||
// ---- text editing ----------------------------------------------------------
|
||||
function startTextEdit(el) {
|
||||
if (!isTextEditable(el)) { toast('This element has no editable text'); return; }
|
||||
if (editing) commitTextEdit();
|
||||
editing = { el: el, before: el.innerText, htmlBefore: el.innerHTML };
|
||||
el.setAttribute('contenteditable', 'true');
|
||||
el.setAttribute('data-ecc-ui-canvas-editing', '');
|
||||
el.focus();
|
||||
try {
|
||||
var range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
var sel = window.getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
} catch (_e) { /* selection APIs unavailable */ }
|
||||
selBox.classList.add('editing');
|
||||
post({ type: 'uc:status', text: 'Editing text · Enter saves · Shift+Enter for a new line · Esc cancels' });
|
||||
}
|
||||
function finishTextEdit(cancel) {
|
||||
if (!editing) return;
|
||||
var el = editing.el;
|
||||
el.removeAttribute('contenteditable');
|
||||
el.removeAttribute('data-ecc-ui-canvas-editing');
|
||||
selBox.classList.remove('editing');
|
||||
var state = editing;
|
||||
editing = null;
|
||||
if (cancel) { el.innerHTML = state.htmlBefore; post({ type: 'uc:status', text: '' }); scheduleBoxes(); return; }
|
||||
if (el.innerHTML !== state.htmlBefore) {
|
||||
var edit = newEdit('text', el, { before: state.before, after: el.innerText, htmlAfter: el.innerHTML });
|
||||
edit._htmlBefore = state.htmlBefore;
|
||||
edit._el = el;
|
||||
record(edit);
|
||||
toast('Text updated');
|
||||
}
|
||||
post({ type: 'uc:status', text: '' });
|
||||
scheduleBoxes();
|
||||
}
|
||||
function commitTextEdit() { finishTextEdit(false); }
|
||||
|
||||
// ---- gestures: resize, move, nudge -----------------------------------------
|
||||
function startResize(dir, event) {
|
||||
if (!selected) return;
|
||||
var rect = selected.getBoundingClientRect();
|
||||
gesture = { kind: 'resize', dir: dir, el: selected, x0: event.clientX, y0: event.clientY, w0: rect.width, h0: rect.height, inlineBefore: captureInline(selected, ['width', 'height', 'flex', 'max-width']), ratio: rect.height ? rect.width / rect.height : 1, moved: false };
|
||||
document.documentElement.style.cursor = getComputedStyle(root.querySelector('.handle[data-dir="' + dir + '"]')).cursor;
|
||||
document.documentElement.setAttribute('data-ecc-ui-canvas-noselect', '');
|
||||
}
|
||||
function doResize(event) {
|
||||
var g = gesture;
|
||||
var dx = event.clientX - g.x0, dy = event.clientY - g.y0;
|
||||
var width = g.w0, height = g.h0;
|
||||
if (g.dir.indexOf('e') >= 0) width = g.w0 + dx;
|
||||
if (g.dir.indexOf('w') >= 0) width = g.w0 - dx;
|
||||
if (g.dir.indexOf('s') >= 0) height = g.h0 + dy;
|
||||
if (g.dir.indexOf('n') >= 0) height = g.h0 - dy;
|
||||
var corner = g.dir.length === 2;
|
||||
if (g.el.tagName === 'IMG' && corner && !event.shiftKey) {
|
||||
if (Math.abs(width - g.w0) >= Math.abs(height - g.h0)) height = width / g.ratio; else width = height * g.ratio;
|
||||
}
|
||||
width = Math.max(8, Math.round(width));
|
||||
height = Math.max(8, Math.round(height));
|
||||
var wantsW = g.dir.indexOf('e') >= 0 || g.dir.indexOf('w') >= 0 || (g.el.tagName === 'IMG' && corner && !event.shiftKey);
|
||||
var wantsH = g.dir.indexOf('n') >= 0 || g.dir.indexOf('s') >= 0 || (g.el.tagName === 'IMG' && corner && !event.shiftKey);
|
||||
g.width = wantsW ? width : undefined;
|
||||
g.height = wantsH ? height : undefined;
|
||||
applyInline(g.el, sizeStyles(g.el, g.width, g.height));
|
||||
g.moved = true;
|
||||
scheduleBoxes();
|
||||
}
|
||||
function endResize() {
|
||||
var g = gesture;
|
||||
document.documentElement.style.cursor = '';
|
||||
document.documentElement.removeAttribute('data-ecc-ui-canvas-noselect');
|
||||
if (!g.moved) return;
|
||||
var rect = g.el.getBoundingClientRect();
|
||||
var edit = newEdit('resize', g.el, { width: g.width !== undefined ? Math.round(rect.width) : undefined, height: g.height !== undefined ? Math.round(rect.height) : undefined, before: { width: Math.round(g.w0), height: Math.round(g.h0) } });
|
||||
if (edit.width === undefined) delete edit.width;
|
||||
if (edit.height === undefined) delete edit.height;
|
||||
edit._inlineBefore = g.inlineBefore;
|
||||
edit._el = g.el;
|
||||
record(edit);
|
||||
toast('Resized to ' + Math.round(rect.width) + ' × ' + Math.round(rect.height));
|
||||
}
|
||||
|
||||
function axisOf(container) {
|
||||
var cs = getComputedStyle(container);
|
||||
if (cs.display.indexOf('flex') >= 0) return cs.flexDirection.indexOf('row') === 0 ? 'x' : 'y';
|
||||
if (cs.display.indexOf('grid') >= 0) return 'grid';
|
||||
var kids = elementChildren(container);
|
||||
if (kids.length > 1) {
|
||||
var inlineish = kids.every(function (k) { var d = getComputedStyle(k).display; return d.indexOf('inline') === 0 || k.tagName === 'IMG' || k.tagName === 'BUTTON' || k.tagName === 'A' || k.tagName === 'SPAN'; });
|
||||
if (inlineish) return 'x';
|
||||
}
|
||||
return 'y';
|
||||
}
|
||||
function dropPlan(x, y, dragged) {
|
||||
var under = document.elementFromPoint(x, y);
|
||||
if (!under || isOurs(under)) return null;
|
||||
if (under === document.documentElement) under = document.body;
|
||||
if (!under || under === dragged || dragged.contains(under)) return null;
|
||||
var container, index, indicator;
|
||||
if (under === dragged.parentElement || under.contains(dragged)) {
|
||||
container = under;
|
||||
var kids = elementChildren(container).filter(function (k) { return k !== dragged; });
|
||||
if (!kids.length) { index = 0; indicator = inner(container.getBoundingClientRect()); }
|
||||
else {
|
||||
var axis = axisOf(container);
|
||||
var best = null, bestDist = Infinity;
|
||||
for (var i = 0; i < kids.length; i++) {
|
||||
var r = kids[i].getBoundingClientRect();
|
||||
var cx = r.left + r.width / 2, cy = r.top + r.height / 2;
|
||||
var dist = axis === 'x' ? Math.abs(cx - x) : axis === 'y' ? Math.abs(cy - y) : Math.hypot(cx - x, cy - y);
|
||||
if (dist < bestDist) { bestDist = dist; best = { el: kids[i], i: i, rect: r }; }
|
||||
}
|
||||
var after = axis === 'x' ? x > best.rect.left + best.rect.width / 2 : axis === 'y' ? y > best.rect.top + best.rect.height / 2 : (x > best.rect.left + best.rect.width / 2);
|
||||
index = best.i + (after ? 1 : 0);
|
||||
indicator = edge(best.rect, axis === 'grid' ? 'x' : axis, after);
|
||||
}
|
||||
} else {
|
||||
container = under.parentElement;
|
||||
if (!container) return null;
|
||||
var axis2 = axisOf(container);
|
||||
var rect = under.getBoundingClientRect();
|
||||
var after2 = axis2 === 'y' ? y > rect.top + rect.height / 2 : x > rect.left + rect.width / 2;
|
||||
var siblings = elementChildren(container).filter(function (k) { return k !== dragged; });
|
||||
index = siblings.indexOf(under) + (after2 ? 1 : 0);
|
||||
indicator = edge(rect, axis2 === 'grid' ? 'x' : axis2, after2);
|
||||
}
|
||||
return { container: container, index: index, indicator: indicator };
|
||||
}
|
||||
function edge(rect, axis, after) {
|
||||
if (axis === 'y') return { left: rect.left, top: (after ? rect.bottom : rect.top) - 1, width: rect.width, height: 3 };
|
||||
return { left: (after ? rect.right : rect.left) - 1, top: rect.top, width: 3, height: rect.height };
|
||||
}
|
||||
function inner(rect) { return { left: rect.left + 4, top: rect.top + 4, width: Math.max(0, rect.width - 8), height: 3 }; }
|
||||
|
||||
function startPress(el, event) {
|
||||
gesture = { kind: 'press', el: el, x0: event.clientX, y0: event.clientY, nudge: event.altKey, started: false };
|
||||
}
|
||||
function beginDrag(event) {
|
||||
var g = gesture;
|
||||
g.started = true;
|
||||
if (g.nudge) {
|
||||
g.kind = 'nudge';
|
||||
g.inlineBefore = captureInline(g.el, ['position', 'left', 'top']);
|
||||
g.baseLeft = px(g.el.style.left);
|
||||
g.baseTop = px(g.el.style.top);
|
||||
if (getComputedStyle(g.el).position === 'static') g.el.style.position = 'relative';
|
||||
post({ type: 'uc:status', text: 'Nudging · release to keep the offset' });
|
||||
} else {
|
||||
g.kind = 'move';
|
||||
g.fromParent = g.el.parentElement;
|
||||
g.fromIndex = indexIn(g.fromParent, g.el);
|
||||
g.el.style.pointerEvents = 'none';
|
||||
selBox.classList.add('dragging');
|
||||
post({ type: 'uc:status', text: 'Reordering · drop between siblings or into a container · hold Alt to nudge instead' });
|
||||
}
|
||||
document.documentElement.setAttribute('data-ecc-ui-canvas-noselect', '');
|
||||
event.preventDefault();
|
||||
}
|
||||
function doDrag(event) {
|
||||
var g = gesture;
|
||||
if (g.kind === 'nudge') {
|
||||
applyInline(g.el, { left: (g.baseLeft + event.clientX - g.x0) + 'px', top: (g.baseTop + event.clientY - g.y0) + 'px' });
|
||||
scheduleBoxes();
|
||||
return;
|
||||
}
|
||||
var rect = g.el.getBoundingClientRect();
|
||||
place(ghostEl, { left: rect.left + (event.clientX - g.x0), top: rect.top + (event.clientY - g.y0), width: rect.width, height: rect.height });
|
||||
var plan = dropPlan(event.clientX, event.clientY, g.el);
|
||||
g.plan = plan;
|
||||
if (plan && plan.indicator) place(dropEl, plan.indicator); else dropEl.style.display = 'none';
|
||||
}
|
||||
function endDrag() {
|
||||
var g = gesture;
|
||||
document.documentElement.removeAttribute('data-ecc-ui-canvas-noselect');
|
||||
post({ type: 'uc:status', text: '' });
|
||||
if (g.kind === 'nudge') {
|
||||
var dx = px(g.el.style.left) - g.baseLeft, dy = px(g.el.style.top) - g.baseTop;
|
||||
if (dx === 0 && dy === 0) { applyInline(g.el, g.inlineBefore); return; }
|
||||
var edit = newEdit('nudge', g.el, { dx: dx, dy: dy });
|
||||
edit._inlineBefore = g.inlineBefore;
|
||||
edit._el = g.el;
|
||||
record(edit);
|
||||
toast('Nudged ' + dx + ', ' + dy + 'px');
|
||||
return;
|
||||
}
|
||||
g.el.style.pointerEvents = '';
|
||||
if (!g.el.getAttribute('style')) g.el.removeAttribute('style');
|
||||
selBox.classList.remove('dragging');
|
||||
ghostEl.style.display = 'none';
|
||||
dropEl.style.display = 'none';
|
||||
var plan = g.plan;
|
||||
if (!plan) return;
|
||||
var sameSpot = plan.container === g.fromParent && (plan.index === g.fromIndex || plan.index === g.fromIndex + 1);
|
||||
if (sameSpot) return;
|
||||
var fromSelector = selectorFor(g.el);
|
||||
var fromParentSelector = selectorFor(g.fromParent);
|
||||
insertAt(plan.container, g.el, plan.index);
|
||||
var moveEdit = newEdit('move', g.el, { from: { parent: fromParentSelector, index: g.fromIndex }, to: { parent: selectorFor(plan.container), index: indexIn(plan.container, g.el) } });
|
||||
moveEdit.selector = fromSelector;
|
||||
moveEdit.selectorAfter = selectorFor(g.el);
|
||||
moveEdit._fromParent = g.fromParent;
|
||||
moveEdit._fromIndex = g.fromIndex;
|
||||
moveEdit._el = g.el;
|
||||
record(moveEdit);
|
||||
toast('Moved ' + labelFor(g.el));
|
||||
}
|
||||
|
||||
function nudgeBy(dx, dy) {
|
||||
if (!selected) return;
|
||||
var last = edits.length ? edits[edits.length - 1] : null;
|
||||
if (last && last.kind === 'nudge' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 1500) {
|
||||
applyInline(selected, { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' });
|
||||
last.dx += dx;
|
||||
last.dy += dy;
|
||||
last.at = new Date().toISOString();
|
||||
postEdits();
|
||||
scheduleBoxes();
|
||||
return;
|
||||
}
|
||||
var edit = newEdit('nudge', selected, { dx: dx, dy: dy });
|
||||
edit._inlineBefore = captureInline(selected, ['position', 'left', 'top']);
|
||||
edit._el = selected;
|
||||
var cs = getComputedStyle(selected);
|
||||
var next = { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' };
|
||||
if (cs.position === 'static') next.position = 'relative';
|
||||
applyInline(selected, next);
|
||||
record(edit);
|
||||
}
|
||||
|
||||
function removeSelected() {
|
||||
if (!selected || selected === document.body) { toast('Select an element to remove'); return; }
|
||||
var el = selected;
|
||||
var parent = el.parentElement;
|
||||
var edit = newEdit('remove', el, { outerHTML: el.outerHTML.slice(0, 20000), from: { parent: selectorFor(parent), index: indexIn(parent, el) } });
|
||||
edit._el = el;
|
||||
edit._parent = parent;
|
||||
edit._index = indexIn(parent, el);
|
||||
el.remove();
|
||||
selected = parent && parent !== document.documentElement ? parent : null;
|
||||
record(edit);
|
||||
toast('Removed ' + edit.tag + ' · Cmd/Ctrl+Z to undo');
|
||||
}
|
||||
function setStyle(property, value) {
|
||||
if (!selected) return;
|
||||
if (!/^[a-z][a-z0-9-]*$/.test(property)) return;
|
||||
var cs = getComputedStyle(selected);
|
||||
var before = cs.getPropertyValue(property);
|
||||
var last = edits.length ? edits[edits.length - 1] : null;
|
||||
if (last && last.kind === 'style' && last.property === property && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) {
|
||||
selected.style.setProperty(property, value === null ? RESET_VALUES[property] : value);
|
||||
last.after = value;
|
||||
last.at = new Date().toISOString();
|
||||
postEdits();
|
||||
postSelection();
|
||||
scheduleBoxes();
|
||||
return;
|
||||
}
|
||||
var edit = newEdit('style', selected, { property: property, before: before, after: value });
|
||||
edit._inlineBefore = captureInline(selected, [property]);
|
||||
edit._el = selected;
|
||||
if (!applyEdit(edit, selected)) { toast('Cannot change ' + property); return; }
|
||||
record(edit);
|
||||
}
|
||||
function setSize(width, height) {
|
||||
if (!selected) return;
|
||||
var last = edits.length ? edits[edits.length - 1] : null;
|
||||
if (last && last.kind === 'resize' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) {
|
||||
if (width !== null && width !== undefined) last.width = Math.round(width);
|
||||
if (height !== null && height !== undefined) last.height = Math.round(height);
|
||||
var next = sizeStyles(selected, last.width, last.height);
|
||||
// A dimension first touched now still needs its original value for undo.
|
||||
last._inlineBefore = last._inlineBefore || {};
|
||||
for (var key in next) if (!Object.prototype.hasOwnProperty.call(last._inlineBefore, key)) last._inlineBefore[key] = selected.style.getPropertyValue(key);
|
||||
applyInline(selected, next);
|
||||
last.at = new Date().toISOString();
|
||||
postEdits();
|
||||
postSelection();
|
||||
scheduleBoxes();
|
||||
return;
|
||||
}
|
||||
var rect = selected.getBoundingClientRect();
|
||||
var edit = newEdit('resize', selected, { before: { width: Math.round(rect.width), height: Math.round(rect.height) } });
|
||||
if (width !== null && width !== undefined) edit.width = Math.round(width);
|
||||
if (height !== null && height !== undefined) edit.height = Math.round(height);
|
||||
if (edit.width === undefined && edit.height === undefined) return;
|
||||
edit._el = selected;
|
||||
applyEdit(edit, selected);
|
||||
record(edit);
|
||||
}
|
||||
|
||||
// ---- export -------------------------------------------------------------------
|
||||
function exportHtml() {
|
||||
if (editing) commitTextEdit();
|
||||
var clone = document.documentElement.cloneNode(true);
|
||||
var junk = clone.querySelectorAll('[data-ecc-ui-canvas],[data-ecc-plan-canvas]');
|
||||
for (var i = 0; i < junk.length; i++) junk[i].remove();
|
||||
var scripts = clone.querySelectorAll('script[src*="/ui-editor.js"],script[src*="/sdk.js"]');
|
||||
for (var j = 0; j < scripts.length; j++) scripts[j].remove();
|
||||
var marked = clone.querySelectorAll('[contenteditable],[data-ecc-ui-canvas-editing]');
|
||||
for (var k = 0; k < marked.length; k++) { marked[k].removeAttribute('contenteditable'); marked[k].removeAttribute('data-ecc-ui-canvas-editing'); }
|
||||
clone.removeAttribute('data-ecc-ui-canvas-noselect');
|
||||
var doctype = document.doctype ? '<!DOCTYPE ' + document.doctype.name + '>\n' : '<!DOCTYPE html>\n';
|
||||
return doctype + clone.outerHTML + '\n';
|
||||
}
|
||||
|
||||
// ---- DOM events ----------------------------------------------------------------
|
||||
var noSelectStyle = document.createElement('style');
|
||||
noSelectStyle.setAttribute('data-ecc-ui-canvas', 'noselect');
|
||||
noSelectStyle.textContent = '[data-ecc-ui-canvas-noselect] *{user-select:none!important;cursor:inherit}';
|
||||
document.head && document.head.appendChild(noSelectStyle);
|
||||
|
||||
document.addEventListener('mousemove', function (e) {
|
||||
if (gesture) {
|
||||
if (gesture.kind === 'resize') { doResize(e); return; }
|
||||
if (gesture.kind === 'press') {
|
||||
if (Math.hypot(e.clientX - gesture.x0, e.clientY - gesture.y0) > 4) beginDrag(e);
|
||||
return;
|
||||
}
|
||||
doDrag(e);
|
||||
return;
|
||||
}
|
||||
if (mode !== 'edit' || editing) return;
|
||||
var target = e.target;
|
||||
hovered = selectable(target) && !(editing && editing.el === target) ? target : null;
|
||||
scheduleBoxes();
|
||||
}, true);
|
||||
|
||||
document.addEventListener('mousedown', function (e) {
|
||||
if (mode !== 'edit' || e.button !== 0) return;
|
||||
var path = e.composedPath ? e.composedPath() : [e.target];
|
||||
var first = path[0];
|
||||
if (first && first.classList && first.classList.contains('handle') && first.getRootNode() === root) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
startResize(first.getAttribute('data-dir'), e);
|
||||
return;
|
||||
}
|
||||
var target = e.target;
|
||||
if (editing && editing.el.contains(target)) return;
|
||||
if (editing) commitTextEdit();
|
||||
if (!selectable(target)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (target !== selected) select(target);
|
||||
if (target !== document.body) startPress(target, e);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('mouseup', function (e) {
|
||||
if (!gesture) return;
|
||||
var g = gesture;
|
||||
gesture = null;
|
||||
if (g.kind === 'resize') { endResize(); e.preventDefault(); e.stopPropagation(); return; }
|
||||
if (g.kind === 'press') return;
|
||||
endDrag();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}, true);
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
if (mode !== 'edit') return;
|
||||
if (editing && editing.el.contains(e.target)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}, true);
|
||||
|
||||
document.addEventListener('dblclick', function (e) {
|
||||
if (mode !== 'edit') return;
|
||||
if (editing && editing.el.contains(e.target)) return;
|
||||
if (!selectable(e.target)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
select(e.target);
|
||||
startTextEdit(e.target);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
var meta = e.metaKey || e.ctrlKey;
|
||||
if (meta && e.key.toLowerCase() === 'i' && !editing) { e.preventDefault(); post({ type: 'uc:toggle-mode' }); return; }
|
||||
if (editing) {
|
||||
if (e.key === 'Escape') { e.preventDefault(); finishTextEdit(true); }
|
||||
else if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); commitTextEdit(); }
|
||||
return;
|
||||
}
|
||||
if (mode !== 'edit') return;
|
||||
if (meta && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) redo(); else undo(); return; }
|
||||
if (meta && e.key.toLowerCase() === 'y') { e.preventDefault(); redo(); return; }
|
||||
if (e.key === 'Escape') { if (selected) { e.preventDefault(); deselect(); } return; }
|
||||
if (!selected) return;
|
||||
if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); removeSelected(); return; }
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (e.shiftKey) { if (selected.parentElement && selectable(selected.parentElement)) select(selected.parentElement); }
|
||||
else { var kids = elementChildren(selected); if (kids.length) select(kids[0]); else startTextEdit(selected); }
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
var next = e.shiftKey ? selected.previousElementSibling : selected.nextElementSibling;
|
||||
while (next && isOurs(next)) next = e.shiftKey ? next.previousElementSibling : next.nextElementSibling;
|
||||
if (next) select(next);
|
||||
return;
|
||||
}
|
||||
var step = e.shiftKey ? 10 : 1;
|
||||
if (e.key === 'ArrowLeft') { e.preventDefault(); nudgeBy(-step, 0); }
|
||||
else if (e.key === 'ArrowRight') { e.preventDefault(); nudgeBy(step, 0); }
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); nudgeBy(0, -step); }
|
||||
else if (e.key === 'ArrowDown') { e.preventDefault(); nudgeBy(0, step); }
|
||||
}, true);
|
||||
|
||||
document.addEventListener('focusout', function (e) {
|
||||
if (editing && e.target === editing.el) setTimeout(function () { if (editing && editing.el === e.target) commitTextEdit(); }, 0);
|
||||
}, true);
|
||||
|
||||
var scrollTimer = null;
|
||||
window.addEventListener('scroll', function () {
|
||||
scheduleBoxes();
|
||||
if (scrollTimer) return;
|
||||
scrollTimer = setTimeout(function () { scrollTimer = null; post({ type: 'uc:scroll', x: window.scrollX, y: window.scrollY }); }, 120);
|
||||
}, { passive: true, capture: true });
|
||||
window.addEventListener('resize', function () { scheduleBoxes(); post({ type: 'uc:viewport', width: window.innerWidth, height: window.innerHeight }); });
|
||||
|
||||
if (window.ResizeObserver) {
|
||||
var observer = new ResizeObserver(function () { scheduleBoxes(); });
|
||||
observer.observe(document.documentElement);
|
||||
}
|
||||
if (window.MutationObserver) {
|
||||
var mutations = new MutationObserver(function () { scheduleBoxes(); });
|
||||
mutations.observe(document.documentElement, { childList: true, subtree: true, attributes: true });
|
||||
}
|
||||
|
||||
// ---- shell bridge ---------------------------------------------------------------
|
||||
window.addEventListener('message', function (e) {
|
||||
var msg = e.data || {};
|
||||
if (typeof msg.type !== 'string' || msg.type.indexOf('uc:') !== 0) return;
|
||||
switch (msg.type) {
|
||||
case 'uc:set-mode':
|
||||
if (editing) commitTextEdit();
|
||||
mode = msg.mode === 'interact' ? 'interact' : 'edit';
|
||||
if (mode === 'interact') { hovered = null; }
|
||||
updateBoxes();
|
||||
break;
|
||||
case 'uc:restore': restore(msg); break;
|
||||
case 'uc:select': { var el = resolve(msg.selector); if (el) { select(el); try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } catch (_e) { /* older engines */ } } break; }
|
||||
case 'uc:deselect': deselect(); break;
|
||||
case 'uc:style': setStyle(msg.property, msg.value === undefined ? null : msg.value); break;
|
||||
case 'uc:size': setSize(msg.width, msg.height); break;
|
||||
case 'uc:remove': removeSelected(); break;
|
||||
case 'uc:edit-text': if (selected) startTextEdit(selected); break;
|
||||
case 'uc:undo': undo(); break;
|
||||
case 'uc:redo': redo(); break;
|
||||
case 'uc:reset': resetAll(); break;
|
||||
case 'uc:forget':
|
||||
// The agent baked the current edits into the file: drop the log
|
||||
// without touching the DOM so nothing is replayed twice.
|
||||
edits = [];
|
||||
redoStack = [];
|
||||
postEdits();
|
||||
break;
|
||||
case 'uc:pause-animations':
|
||||
animationsPaused = Boolean(msg.paused);
|
||||
if (animationsPaused) document.head.appendChild(pauseStyle); else pauseStyle.remove();
|
||||
break;
|
||||
case 'uc:export':
|
||||
post({ type: 'uc:export', requestId: msg.requestId, html: exportHtml(), edits: edits.map(publicEdit) });
|
||||
break;
|
||||
case 'uc:scroll-to': window.scrollTo(msg.x || 0, msg.y || 0); break;
|
||||
default: break;
|
||||
}
|
||||
});
|
||||
|
||||
function announceReady() {
|
||||
attachHost();
|
||||
post({ type: 'uc:ready', title: document.title || '', viewport: { width: window.innerWidth, height: window.innerHeight }, scroll: { x: window.scrollX, y: window.scrollY } });
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', announceReady);
|
||||
else announceReady();
|
||||
})();`;
|
||||
}
|
||||
|
||||
module.exports = { uiEditorJs };
|
||||
@@ -0,0 +1,318 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* UI Canvas feedback schema.
|
||||
*
|
||||
* The browser editor records every change the human makes to a mockup as a
|
||||
* structured edit and ships the edit log, plus a serialized DOM snapshot, to
|
||||
* the agent through the same session queue Plan Canvas uses. This module owns
|
||||
* the shape of that payload: validation of what the browser submits, the
|
||||
* on-disk export of the snapshot, the one-line summaries agents and hooks
|
||||
* print, and the viewport presets the shell offers.
|
||||
*
|
||||
* Nothing here trusts the browser. Every field is clamped, every kind is
|
||||
* allow-listed, and the HTML snapshot never enters sessions.json: it is
|
||||
* written next to the artifact and only its path travels with the item.
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const UI_FEEDBACK_KINDS = new Set(['chat', 'edits', 'finish']);
|
||||
const EDIT_KINDS = new Set(['text', 'resize', 'move', 'nudge', 'remove', 'style']);
|
||||
const VIEWPORT_IDS = new Set(['mobile', 'desktop', 'custom']);
|
||||
|
||||
const MAX_EDITS = 500;
|
||||
const MAX_EDIT_SUMMARIES = 60;
|
||||
const MAX_HTML_BYTES = 6 * 1024 * 1024;
|
||||
const MAX_SNIPPET = 200;
|
||||
const MAX_SELECTOR = 500;
|
||||
const MAX_TEXT = 4000;
|
||||
const MAX_MARKUP = 20000;
|
||||
const MAX_STYLE_VALUE = 500;
|
||||
const MAX_DIMENSION = 20000;
|
||||
|
||||
// CSS pixel presets. Mobile tracks the current iPhone class; desktop fills the
|
||||
// stage and only falls back to these numbers when the stage is smaller.
|
||||
const VIEWPORT_PRESETS = Object.freeze({
|
||||
mobile: Object.freeze({ id: 'mobile', label: 'Mobile', width: 393, height: 852 }),
|
||||
desktop: Object.freeze({ id: 'desktop', label: 'Desktop', width: 1440, height: 900 }),
|
||||
custom: Object.freeze({ id: 'custom', label: 'Custom', width: 1280, height: 800 })
|
||||
});
|
||||
|
||||
function clampText(value, max) {
|
||||
if (typeof value !== 'string') return '';
|
||||
return value.slice(0, max);
|
||||
}
|
||||
|
||||
function clampInt(value, { min = 0, max = MAX_DIMENSION } = {}) {
|
||||
const number = typeof value === 'number' ? value : Number.parseFloat(value);
|
||||
if (!Number.isFinite(number)) return null;
|
||||
return Math.min(max, Math.max(min, Math.round(number)));
|
||||
}
|
||||
|
||||
// A dimension of zero or less is "not provided", never a 1px viewport.
|
||||
function positiveInt(value) {
|
||||
const number = typeof value === 'number' ? value : Number.parseFloat(value);
|
||||
if (!Number.isFinite(number) || number < 1) return null;
|
||||
return Math.min(MAX_DIMENSION, Math.round(number));
|
||||
}
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function normalizeAnchor(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
if (typeof raw.selector !== 'string' || !raw.selector.trim()) return null;
|
||||
const anchor = {
|
||||
selector: clampText(raw.selector, MAX_SELECTOR),
|
||||
tag: clampText(raw.tag, 60),
|
||||
snippet: clampText(raw.snippet, MAX_SNIPPET)
|
||||
};
|
||||
if (raw.size && typeof raw.size === 'object') {
|
||||
const width = clampInt(raw.size.width);
|
||||
const height = clampInt(raw.size.height);
|
||||
if (width !== null && height !== null) anchor.size = { width, height };
|
||||
}
|
||||
return anchor;
|
||||
}
|
||||
|
||||
function normalizeViewport(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const preset = VIEWPORT_IDS.has(raw.preset) ? raw.preset : 'custom';
|
||||
const fallback = VIEWPORT_PRESETS[preset];
|
||||
const width = positiveInt(raw.width) ?? fallback.width;
|
||||
const height = positiveInt(raw.height) ?? fallback.height;
|
||||
return { preset, width, height };
|
||||
}
|
||||
|
||||
function normalizePosition(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const index = clampInt(raw.index, { min: 0, max: 100000 });
|
||||
if (index === null) return null;
|
||||
return { parent: clampText(raw.parent, MAX_SELECTOR), index };
|
||||
}
|
||||
|
||||
// One browser-recorded edit. Returns null for anything unusable so a single
|
||||
// malformed record never blocks the batch it arrived in.
|
||||
function normalizeEdit(raw, position) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
if (!EDIT_KINDS.has(raw.kind)) return null;
|
||||
if (typeof raw.selector !== 'string' || !raw.selector.trim()) return null;
|
||||
const edit = {
|
||||
id: clampText(typeof raw.id === 'string' ? raw.id : `edit-${position + 1}`, 40),
|
||||
kind: raw.kind,
|
||||
selector: clampText(raw.selector, MAX_SELECTOR),
|
||||
tag: clampText(raw.tag, 60),
|
||||
snippet: clampText(raw.snippet, MAX_SNIPPET),
|
||||
at: typeof raw.at === 'string' && raw.at ? clampText(raw.at, 40) : nowIso()
|
||||
};
|
||||
if (raw.stale === true) edit.stale = true;
|
||||
|
||||
switch (raw.kind) {
|
||||
case 'text': {
|
||||
edit.before = clampText(raw.before, MAX_TEXT);
|
||||
edit.after = clampText(raw.after, MAX_TEXT);
|
||||
if (typeof raw.htmlAfter === 'string') edit.htmlAfter = clampText(raw.htmlAfter, MAX_MARKUP);
|
||||
return edit;
|
||||
}
|
||||
case 'resize': {
|
||||
const width = clampInt(raw.width, { min: 1 });
|
||||
const height = clampInt(raw.height, { min: 1 });
|
||||
if (width === null && height === null) return null;
|
||||
if (width !== null) edit.width = width;
|
||||
if (height !== null) edit.height = height;
|
||||
if (raw.before && typeof raw.before === 'object') {
|
||||
edit.before = {};
|
||||
const beforeWidth = clampInt(raw.before.width, { min: 0 });
|
||||
const beforeHeight = clampInt(raw.before.height, { min: 0 });
|
||||
if (beforeWidth !== null) edit.before.width = beforeWidth;
|
||||
if (beforeHeight !== null) edit.before.height = beforeHeight;
|
||||
}
|
||||
return edit;
|
||||
}
|
||||
case 'move': {
|
||||
const from = normalizePosition(raw.from);
|
||||
const to = normalizePosition(raw.to);
|
||||
if (!from || !to) return null;
|
||||
edit.from = from;
|
||||
edit.to = to;
|
||||
return edit;
|
||||
}
|
||||
case 'nudge': {
|
||||
const dx = clampInt(raw.dx, { min: -MAX_DIMENSION });
|
||||
const dy = clampInt(raw.dy, { min: -MAX_DIMENSION });
|
||||
if (dx === null || dy === null) return null;
|
||||
edit.dx = dx;
|
||||
edit.dy = dy;
|
||||
return edit;
|
||||
}
|
||||
case 'remove': {
|
||||
edit.outerHTML = clampText(raw.outerHTML, MAX_MARKUP);
|
||||
const position = normalizePosition(raw.from);
|
||||
if (position) edit.from = position;
|
||||
return edit;
|
||||
}
|
||||
case 'style': {
|
||||
if (typeof raw.property !== 'string' || !/^[a-z][a-z0-9-]{0,59}$/.test(raw.property)) return null;
|
||||
edit.property = raw.property;
|
||||
edit.before = clampText(raw.before, MAX_STYLE_VALUE);
|
||||
edit.after = raw.after === null || raw.after === undefined ? null : clampText(String(raw.after), MAX_STYLE_VALUE);
|
||||
return edit;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEdits(rawEdits) {
|
||||
const edits = [];
|
||||
for (const raw of Array.isArray(rawEdits) ? rawEdits.slice(0, MAX_EDITS) : []) {
|
||||
const edit = normalizeEdit(raw, edits.length);
|
||||
if (edit) edits.push(edit);
|
||||
}
|
||||
return edits;
|
||||
}
|
||||
|
||||
function where(edit) {
|
||||
const label = edit.snippet ? `"${edit.snippet.slice(0, 48)}${edit.snippet.length > 48 ? '…' : ''}"` : '';
|
||||
const target = edit.tag ? `<${edit.tag}>` : '';
|
||||
return [edit.selector, target, label].filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
// Human-readable one-liner for an edit, used by chat transcripts, the Stop
|
||||
// hook, and the agent-facing summary. Never includes markup.
|
||||
function summarizeEdit(edit) {
|
||||
if (!edit || typeof edit !== 'object') return '';
|
||||
const target = where(edit);
|
||||
const stale = edit.stale ? ' (could not be re-applied after the last reload)' : '';
|
||||
switch (edit.kind) {
|
||||
case 'text':
|
||||
return `text of ${target}: "${edit.before}" → "${edit.after}"${stale}`;
|
||||
case 'resize': {
|
||||
const size = [edit.width !== undefined ? `${edit.width}px wide` : null, edit.height !== undefined ? `${edit.height}px tall` : null]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
const before = edit.before && (edit.before.width !== undefined || edit.before.height !== undefined)
|
||||
? ` (was ${edit.before.width ?? '?'}×${edit.before.height ?? '?'})`
|
||||
: '';
|
||||
return `resized ${target} to ${size}${before}${stale}`;
|
||||
}
|
||||
case 'move':
|
||||
return `moved ${target} from ${edit.from.parent || 'its parent'}[${edit.from.index}] to ${edit.to.parent || 'its parent'}[${edit.to.index}]${stale}`;
|
||||
case 'nudge':
|
||||
return `nudged ${target} by ${edit.dx}px, ${edit.dy}px${stale}`;
|
||||
case 'remove':
|
||||
return `removed ${target}${stale}`;
|
||||
case 'style':
|
||||
return edit.after === null
|
||||
? `removed ${edit.property} from ${target} (was ${edit.before || 'unset'})${stale}`
|
||||
: `set ${edit.property} on ${target} to ${edit.after} (was ${edit.before || 'unset'})${stale}`;
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize one browser-submitted UI Canvas feedback item into the shape the
|
||||
// agent receives. Mirrors plan-canvas's normalizeFeedbackItem contract: null
|
||||
// for unusable input, never a throw.
|
||||
function normalizeUiFeedbackItem(raw, counter) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
if (!UI_FEEDBACK_KINDS.has(raw.kind)) return null;
|
||||
const item = {
|
||||
id: `fb-${counter}`,
|
||||
kind: raw.kind,
|
||||
text: clampText(raw.text, MAX_TEXT).trim(),
|
||||
at: nowIso()
|
||||
};
|
||||
if (raw.kind === 'chat') {
|
||||
if (!item.text) return null;
|
||||
const anchor = normalizeAnchor(raw.anchor);
|
||||
if (anchor) item.anchor = anchor;
|
||||
if (Array.isArray(raw.pendingEdits) && raw.pendingEdits.length) {
|
||||
item.pendingEdits = raw.pendingEdits
|
||||
.slice(0, MAX_EDIT_SUMMARIES)
|
||||
.map(entry => (typeof entry === 'string' ? clampText(entry, 240) : summarizeEdit(normalizeEdit(entry, 0))))
|
||||
.filter(Boolean);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
item.edits = normalizeEdits(raw.edits);
|
||||
item.editCount = item.edits.length;
|
||||
const viewport = normalizeViewport(raw.viewport);
|
||||
if (viewport) item.viewport = viewport;
|
||||
if (typeof raw.exportPath === 'string' && raw.exportPath) item.exportPath = raw.exportPath;
|
||||
if (typeof raw.editsPath === 'string' && raw.editsPath) item.editsPath = raw.editsPath;
|
||||
return item;
|
||||
}
|
||||
|
||||
function exportPathsFor(artifactFile) {
|
||||
const dir = path.dirname(artifactFile);
|
||||
const ext = path.extname(artifactFile);
|
||||
const base = path.basename(artifactFile, ext);
|
||||
return {
|
||||
exportPath: path.join(dir, `${base}.edited${ext || '.html'}`),
|
||||
editsPath: path.join(dir, `${base}.edits.json`)
|
||||
};
|
||||
}
|
||||
|
||||
function writeAtomic(file, data) {
|
||||
const tmp = `${file}.tmp-${process.pid}`;
|
||||
fs.writeFileSync(tmp, data);
|
||||
fs.renameSync(tmp, file);
|
||||
}
|
||||
|
||||
// Persist the reviewer's snapshot next to the artifact so the agent (or a
|
||||
// Stop hook running with no server) can read the exact DOM the human saw.
|
||||
function writeExport(artifactFile, { html, edits = [], viewport = null, kind = 'edits' } = {}) {
|
||||
if (typeof html !== 'string' || !html.trim()) {
|
||||
throw Object.assign(new Error('html snapshot is required'), { code: 'EUI_HTML_MISSING' });
|
||||
}
|
||||
const bytes = Buffer.byteLength(html, 'utf8');
|
||||
if (bytes > MAX_HTML_BYTES) {
|
||||
throw Object.assign(new Error(`html snapshot exceeds ${MAX_HTML_BYTES} bytes`), { code: 'EUI_HTML_TOO_LARGE' });
|
||||
}
|
||||
const { exportPath, editsPath } = exportPathsFor(artifactFile);
|
||||
writeAtomic(exportPath, html);
|
||||
writeAtomic(
|
||||
editsPath,
|
||||
`${JSON.stringify({ artifact: artifactFile, kind, at: nowIso(), viewport, edits }, null, 2)}\n`
|
||||
);
|
||||
return { exportPath, editsPath, bytes };
|
||||
}
|
||||
|
||||
function uiChatLineFor(item) {
|
||||
if (item.kind === 'finish') {
|
||||
const count = item.editCount || 0;
|
||||
const base = `Saved and finished with ${count} edit${count === 1 ? '' : 's'}`;
|
||||
return item.text ? `${base}: ${item.text}` : base;
|
||||
}
|
||||
if (item.kind === 'edits') {
|
||||
const count = item.editCount || 0;
|
||||
const base = `Applied ${count} edit${count === 1 ? '' : 's'} to the preview`;
|
||||
return item.text ? `${base}: ${item.text}` : base;
|
||||
}
|
||||
if (item.anchor) {
|
||||
const label = item.anchor.snippet || item.anchor.selector;
|
||||
return `[${label}] ${item.text}`;
|
||||
}
|
||||
return item.text;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
EDIT_KINDS,
|
||||
MAX_EDITS,
|
||||
MAX_HTML_BYTES,
|
||||
UI_FEEDBACK_KINDS,
|
||||
VIEWPORT_PRESETS,
|
||||
exportPathsFor,
|
||||
normalizeAnchor,
|
||||
normalizeEdit,
|
||||
normalizeEdits,
|
||||
normalizeUiFeedbackItem,
|
||||
normalizeViewport,
|
||||
summarizeEdit,
|
||||
uiChatLineFor,
|
||||
writeExport
|
||||
};
|
||||
@@ -0,0 +1,190 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* UI Canvas inspector field helpers: parse, sanitize, and format the values
|
||||
* a reviewer types or drags in the inspector (lengths, ratios, colors, free
|
||||
* CSS text) before they reach the mockup.
|
||||
*
|
||||
* These are plain functions with no closure state so the browser shell can
|
||||
* inline their source (see FIELD_HELPERS_JS) while Node tests exercise the
|
||||
* exact same code. Keep them self-contained: no requires, no module-level
|
||||
* constants, and only reference each other by name.
|
||||
*/
|
||||
|
||||
function clampNumber(value, min, max) {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
function roundToStep(value, step) {
|
||||
if (!step) return value;
|
||||
const decimals = (String(step).split('.')[1] || '').length;
|
||||
const rounded = Math.round(value / step) * step;
|
||||
return Number(rounded.toFixed(Math.min(decimals, 6)));
|
||||
}
|
||||
|
||||
// Shortest readable form: 16, 1.5, 0.25 (no trailing zeros, at most 2 decimals).
|
||||
function formatNumber(value) {
|
||||
if (!Number.isFinite(value)) return '';
|
||||
return String(Number(value.toFixed(2)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize one typed number against a field spec.
|
||||
* spec: { min, max, step, unit, units, ratio }
|
||||
* unit default unit when none is typed ('' for unitless)
|
||||
* units accepted units; anything else is rejected
|
||||
* ratio value is 0..1 and the human may type 50, 50% or 0.5
|
||||
* Returns { ok: true, value, unit, css } or { ok: false, error }.
|
||||
*/
|
||||
function sanitizeNumber(raw, spec) {
|
||||
const text = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().replace(/,/g, '.');
|
||||
if (!text) return { ok: false, error: 'Enter a number' };
|
||||
const match = text.match(/^([+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*([a-z%]*)$/);
|
||||
if (!match) return { ok: false, error: 'Not a number' };
|
||||
let value = Number(match[1]);
|
||||
if (!Number.isFinite(value)) return { ok: false, error: 'Not a number' };
|
||||
const units = spec.units || [spec.unit || ''];
|
||||
let unit = match[2];
|
||||
if (spec.ratio) {
|
||||
if (unit === '%' || value > 1) value /= 100;
|
||||
else if (unit) return { ok: false, error: 'Use a percentage, like 50%' };
|
||||
unit = '';
|
||||
} else {
|
||||
if (!unit) unit = spec.unit || '';
|
||||
if (units.indexOf(unit) < 0) {
|
||||
const listed = units.filter(Boolean);
|
||||
return { ok: false, error: listed.length ? 'Use ' + listed.join(', ') : 'Use a plain number' };
|
||||
}
|
||||
}
|
||||
const min = spec.min === undefined ? -Infinity : spec.min;
|
||||
const max = spec.max === undefined ? Infinity : spec.max;
|
||||
value = roundToStep(clampNumber(value, min, max), spec.step);
|
||||
return { ok: true, value, unit, css: formatNumber(value) + unit };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a 1-4 part box value such as padding "8 16" or margin "0 auto".
|
||||
* spec: sanitizeNumber spec plus { maxParts, allowAuto }.
|
||||
*/
|
||||
function sanitizeBoxList(raw, spec) {
|
||||
const parts = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().split(/[\s,]+/).filter(Boolean);
|
||||
const maxParts = spec.maxParts || 4;
|
||||
if (!parts.length) return { ok: false, error: 'Enter a value' };
|
||||
if (parts.length > maxParts) return { ok: false, error: 'Use at most ' + maxParts + ' values' };
|
||||
const out = [];
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
if (parts[i] === 'auto' && spec.allowAuto) { out.push('auto'); continue; }
|
||||
const result = sanitizeNumber(parts[i], spec);
|
||||
if (!result.ok) return result;
|
||||
out.push(result.value === 0 ? '0' : result.css);
|
||||
}
|
||||
return { ok: true, css: out.join(' ') };
|
||||
}
|
||||
|
||||
function hexPair(value) {
|
||||
return Math.round(clampNumber(value, 0, 255)).toString(16).padStart(2, '0');
|
||||
}
|
||||
|
||||
// Parse #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba() (comma or space syntax)
|
||||
// and transparent into { r, g, b, a }. Returns null for anything else.
|
||||
function parseColor(raw) {
|
||||
const text = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase();
|
||||
if (text === 'transparent') return { r: 0, g: 0, b: 0, a: 0 };
|
||||
let hex = text.match(/^#?([0-9a-f]{3,8})$/);
|
||||
if (hex && [3, 4, 6, 8].indexOf(hex[1].length) >= 0) {
|
||||
hex = hex[1];
|
||||
if (hex.length <= 4) hex = hex.split('').map(c => c + c).join('');
|
||||
return {
|
||||
r: parseInt(hex.slice(0, 2), 16),
|
||||
g: parseInt(hex.slice(2, 4), 16),
|
||||
b: parseInt(hex.slice(4, 6), 16),
|
||||
a: hex.length === 8 ? Number((parseInt(hex.slice(6, 8), 16) / 255).toFixed(3)) : 1
|
||||
};
|
||||
}
|
||||
const fn = text.match(/^rgba?\(\s*([^)]*)\)$/);
|
||||
if (!fn) return null;
|
||||
const nums = fn[1].split(/[\s,/]+/).filter(Boolean);
|
||||
if (nums.length < 3 || nums.length > 4) return null;
|
||||
const channel = part => (/%$/.test(part) ? parseFloat(part) * 2.55 : parseFloat(part));
|
||||
const rgb = nums.slice(0, 3).map(channel);
|
||||
let alpha = nums.length === 4 ? (/%$/.test(nums[3]) ? parseFloat(nums[3]) / 100 : parseFloat(nums[3])) : 1;
|
||||
if (rgb.some(n => !Number.isFinite(n)) || !Number.isFinite(alpha)) return null;
|
||||
alpha = clampNumber(alpha, 0, 1);
|
||||
return { r: Math.round(clampNumber(rgb[0], 0, 255)), g: Math.round(clampNumber(rgb[1], 0, 255)), b: Math.round(clampNumber(rgb[2], 0, 255)), a: Number(alpha.toFixed(3)) };
|
||||
}
|
||||
|
||||
// '#rrggbb' when opaque, else rgba() so the mockup CSS stays readable.
|
||||
function formatColor(color) {
|
||||
if (color.a >= 1) return '#' + hexPair(color.r) + hexPair(color.g) + hexPair(color.b);
|
||||
return 'rgba(' + Math.round(color.r) + ', ' + Math.round(color.g) + ', ' + Math.round(color.b) + ', ' + formatNumber(color.a) + ')';
|
||||
}
|
||||
|
||||
// Display form for the inspector: uppercase hex, alpha shown separately.
|
||||
function colorHex(color) {
|
||||
return ('#' + hexPair(color.r) + hexPair(color.g) + hexPair(color.b)).toUpperCase();
|
||||
}
|
||||
|
||||
function rgbToHsl(color) {
|
||||
const r = color.r / 255, g = color.g / 255, b = color.b / 255;
|
||||
const max = Math.max(r, g, b), min = Math.min(r, g, b);
|
||||
const l = (max + min) / 2;
|
||||
let h = 0, s = 0;
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
|
||||
else if (max === g) h = (b - r) / d + 2;
|
||||
else h = (r - g) / d + 4;
|
||||
h *= 60;
|
||||
}
|
||||
return { h: Math.round(h) % 360, s: Math.round(s * 100), l: Math.round(l * 100), a: color.a };
|
||||
}
|
||||
|
||||
function hslToRgb(hsl) {
|
||||
const h = (((hsl.h % 360) + 360) % 360) / 360, s = clampNumber(hsl.s, 0, 100) / 100, l = clampNumber(hsl.l, 0, 100) / 100;
|
||||
if (s === 0) { const v = Math.round(l * 255); return { r: v, g: v, b: v, a: hsl.a }; }
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
const hue = t => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
return { r: Math.round(hue(h + 1 / 3) * 255), g: Math.round(hue(h) * 255), b: Math.round(hue(h - 1 / 3) * 255), a: hsl.a };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize typed free CSS (box-shadow, background-image, a named color).
|
||||
* Rejects declaration breakers and markup so a value can never close the
|
||||
* rule or smuggle another property. The browser additionally checks
|
||||
* CSS.supports before applying.
|
||||
*/
|
||||
function sanitizeCssText(raw, maxLength) {
|
||||
const text = String(raw === undefined || raw === null ? '' : raw).replace(/\s+/g, ' ').trim();
|
||||
if (!text) return { ok: false, error: 'Enter a value' };
|
||||
if (text.length > (maxLength || 300)) return { ok: false, error: 'Too long' };
|
||||
if (/[;{}<>\\]|\/\*|!important|expression\s*\(|javascript:/i.test(text)) return { ok: false, error: 'Remove ; { } < > and comments' };
|
||||
return { ok: true, css: text };
|
||||
}
|
||||
|
||||
// Order matters only for readability; every helper is hoisted once inlined.
|
||||
const FIELD_HELPERS = [clampNumber, roundToStep, formatNumber, sanitizeNumber, sanitizeBoxList, hexPair, parseColor, formatColor, colorHex, rgbToHsl, hslToRgb, sanitizeCssText];
|
||||
const FIELD_HELPERS_JS = FIELD_HELPERS.map(fn => fn.toString()).join('\n');
|
||||
|
||||
module.exports = {
|
||||
FIELD_HELPERS_JS,
|
||||
clampNumber,
|
||||
colorHex,
|
||||
formatColor,
|
||||
formatNumber,
|
||||
hslToRgb,
|
||||
parseColor,
|
||||
rgbToHsl,
|
||||
roundToStep,
|
||||
sanitizeBoxList,
|
||||
sanitizeCssText,
|
||||
sanitizeNumber
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
+64
-26
@@ -28,6 +28,7 @@ const {
|
||||
sessionKeyFor
|
||||
} = require('./lib/plan-canvas/sessions');
|
||||
const { openBrowser } = require('./lib/platform-launch');
|
||||
const { agentDescriptor } = require('./lib/plan-canvas/agent-identity');
|
||||
const {
|
||||
DEFAULT_HOST,
|
||||
createPlanCanvasServer,
|
||||
@@ -78,6 +79,31 @@ function valueAfter(args, name) {
|
||||
return index >= 0 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
function binForMode(mode) {
|
||||
return mode === 'ui' ? 'ecc-ui-canvas' : 'ecc-plan-canvas';
|
||||
}
|
||||
|
||||
// A profile is the only thing that differs between the Plan Canvas CLI and
|
||||
// the UI Canvas CLI (scripts/ui-canvas.js): which session mode `open` asks
|
||||
// for, what the bin is called in agent-facing hints, and the next-step text
|
||||
// that teaches the agent what to do with each payload. The server, state
|
||||
// dir, and transport are shared.
|
||||
const PLAN_PROFILE = {
|
||||
mode: 'plan',
|
||||
bin: 'ecc-plan-canvas',
|
||||
tag: 'plan-canvas',
|
||||
usage,
|
||||
nextSteps: {
|
||||
open: 'Run `ecc-plan-canvas await <file>` and leave it running; it returns when the human sends feedback, a verdict, or ends the session.',
|
||||
feedback: result => (result.sessionEnded
|
||||
? 'The user sent this feedback and ended the session. Address it and report in chat; do not reopen the canvas uninvited.'
|
||||
: 'Address the feedback, then run `ecc-plan-canvas await <file> --reply "<what you changed>"` to answer in the canvas and keep listening.'),
|
||||
ended: result => (result.endedBy === 'user'
|
||||
? 'The user ended this review. Stop polling and deliver any remaining updates in chat; do not reopen uninvited.'
|
||||
: 'Session ended. Stop polling.')
|
||||
}
|
||||
};
|
||||
|
||||
function serverInfoPath(stateDir) {
|
||||
return path.join(stateDir, 'server.json');
|
||||
}
|
||||
@@ -171,9 +197,9 @@ function sleep(ms) {
|
||||
// Start (or reuse) the detached canvas server and return its port. A version
|
||||
// mismatch after an ECC update restarts the server so browser and CLI never
|
||||
// disagree about the protocol.
|
||||
async function ensureServer({ stateDir, port }) {
|
||||
async function ensureServer({ stateDir, port, force = false }) {
|
||||
const health = await healthCheck(port);
|
||||
if (health && health.version === VERSION) return port;
|
||||
if (health && health.version === VERSION && !force) return port;
|
||||
if (health) {
|
||||
await request(port, 'POST', '/shutdown').catch(() => {});
|
||||
for (let i = 0; i < 20 && (await healthCheck(port)); i++) await sleep(100);
|
||||
@@ -209,14 +235,24 @@ async function cmdStatus({ stateDir, port }) {
|
||||
return { server: `http://${DEFAULT_HOST}:${port}`, version: health.version, sessions: sessions.body.sessions };
|
||||
}
|
||||
|
||||
async function cmdOpen(file, args, { stateDir, port }) {
|
||||
async function cmdOpen(file, args, { stateDir, port }, profile = PLAN_PROFILE) {
|
||||
if (!file) throw new Error('open requires a file path');
|
||||
if (!fs.existsSync(path.resolve(file))) throw new Error(`artifact not found: ${file}`);
|
||||
if (profile.validateFile) profile.validateFile(file);
|
||||
await ensureServer({ stateDir, port });
|
||||
const res = await request(port, 'POST', '/api/sessions', {
|
||||
const body = {
|
||||
file: path.resolve(file),
|
||||
reopen: args.includes('--reopen')
|
||||
});
|
||||
reopen: args.includes('--reopen'),
|
||||
...(profile.openBody ? profile.openBody(args) : {})
|
||||
};
|
||||
let res = await request(port, 'POST', '/api/sessions', body);
|
||||
// A server from an older install reports the same version string but does
|
||||
// not know this profile's mode (it answers without one). Restart it on the
|
||||
// current code and open again so the browser never gets the wrong canvas.
|
||||
if (res.statusCode === 200 && profile.mode !== 'plan' && res.body.mode !== profile.mode) {
|
||||
await ensureServer({ stateDir, port, force: true });
|
||||
res = await request(port, 'POST', '/api/sessions', body);
|
||||
}
|
||||
if (res.statusCode === 409) return res.body;
|
||||
if (res.statusCode !== 200) throw new Error(res.body.error || `open failed (HTTP ${res.statusCode})`);
|
||||
const url = `http://${DEFAULT_HOST}:${port}${res.body.url}`;
|
||||
@@ -227,15 +263,16 @@ async function cmdOpen(file, args, { stateDir, port }) {
|
||||
url,
|
||||
browser: launched ? 'launch requested' : 'not opened',
|
||||
browserReason: launchResult.reason,
|
||||
next_step:
|
||||
'Run `ecc-plan-canvas await <file>` and leave it running; it returns when the human sends feedback, a verdict, or ends the session.'
|
||||
next_step: profile.nextSteps.open
|
||||
};
|
||||
}
|
||||
|
||||
function awaitRequest(port, key, timeoutMs) {
|
||||
function awaitRequest(port, key, timeoutMs, agent = null) {
|
||||
if (!/^[a-f0-9]{12}$/.test(key)) throw new Error('invalid plan-canvas session key');
|
||||
const params = new URLSearchParams({ key });
|
||||
if (timeoutMs !== null) params.set('timeoutMs', String(timeoutMs));
|
||||
// Tell the browser who is listening so its presence pill can name the agent.
|
||||
if (agent) params.set('agent', JSON.stringify(agent));
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request(
|
||||
requestOptions(port, 'GET', `/api/await?${params}`, {}),
|
||||
@@ -259,7 +296,7 @@ function awaitRequest(port, key, timeoutMs) {
|
||||
});
|
||||
}
|
||||
|
||||
async function cmdAwait(file, args, { stateDir, port }) {
|
||||
async function cmdAwait(file, args, { stateDir, port }, profile = PLAN_PROFILE) {
|
||||
if (!file) throw new Error('await requires a file path');
|
||||
if (!(await healthCheck(port))) {
|
||||
return { status: 'no-server', hint: 'no canvas server is running; use `open` first', stateDir };
|
||||
@@ -271,17 +308,12 @@ async function cmdAwait(file, args, { stateDir, port }) {
|
||||
}
|
||||
const timeoutRaw = valueAfter(args, '--timeout-ms');
|
||||
const timeoutMs = timeoutRaw === null ? null : Number.parseInt(timeoutRaw, 10) || 0;
|
||||
process.stderr.write('[plan-canvas] waiting for human feedback... leave this running (re-run if interrupted; queued feedback is never lost)\n');
|
||||
const result = await awaitRequest(port, sessionKeyFor(canonicalizeArtifactPath(file)), timeoutMs);
|
||||
process.stderr.write(`[${profile.tag}] waiting for human feedback... leave this running (re-run if interrupted; queued feedback is never lost)\n`);
|
||||
const result = await awaitRequest(port, sessionKeyFor(canonicalizeArtifactPath(file)), timeoutMs, agentDescriptor());
|
||||
if (result.status === 'feedback') {
|
||||
result.next_step = result.sessionEnded
|
||||
? 'The user sent this feedback and ended the session. Address it and report in chat; do not reopen the canvas uninvited.'
|
||||
: 'Address the feedback, then run `ecc-plan-canvas await <file> --reply "<what you changed>"` to answer in the canvas and keep listening.';
|
||||
result.next_step = profile.nextSteps.feedback(result, file);
|
||||
} else if (result.status === 'ended') {
|
||||
result.next_step =
|
||||
result.endedBy === 'user'
|
||||
? 'The user ended this review. Stop polling and deliver any remaining updates in chat; do not reopen uninvited.'
|
||||
: 'Session ended. Stop polling.';
|
||||
result.next_step = profile.nextSteps.ended(result, file);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -305,7 +337,13 @@ function cmdPending({ stateDir }) {
|
||||
const waiting = store
|
||||
.list()
|
||||
.filter(session => session.status !== 'ended' && session.pending > 0)
|
||||
.map(session => ({ file: session.file, pending: session.pending, updatedAt: session.updatedAt }));
|
||||
.map(session => ({
|
||||
file: session.file,
|
||||
mode: session.mode || 'plan',
|
||||
pending: session.pending,
|
||||
updatedAt: session.updatedAt,
|
||||
resume: `${binForMode(session.mode)} await ${JSON.stringify(session.file)}`
|
||||
}));
|
||||
return {
|
||||
status: waiting.length ? 'pending' : 'clear',
|
||||
sessions: waiting,
|
||||
@@ -366,10 +404,10 @@ async function cmdServer(args, { stateDir, port }) {
|
||||
return new Promise(() => {}); // run until a signal or idle shutdown
|
||||
}
|
||||
|
||||
async function main(argv = process.argv.slice(2)) {
|
||||
async function main(argv = process.argv.slice(2), profile = PLAN_PROFILE) {
|
||||
const args = argv.slice();
|
||||
if (args.includes('--help') || args.includes('-h')) {
|
||||
process.stdout.write(`${usage()}\n`);
|
||||
process.stdout.write(`${profile.usage()}\n`);
|
||||
return 0;
|
||||
}
|
||||
const command = args[0] && !args[0].startsWith('--') ? args.shift() : null;
|
||||
@@ -379,15 +417,15 @@ async function main(argv = process.argv.slice(2)) {
|
||||
const context = { stateDir, port: (recorded && recorded.port) || resolvePort() };
|
||||
try {
|
||||
if (command === null) output(await cmdStatus(context));
|
||||
else if (command === 'open') output(await cmdOpen(args[0], args, context));
|
||||
else if (command === 'await') output(await cmdAwait(args[0], args, context));
|
||||
else if (command === 'open') output(await cmdOpen(args[0], args, context, profile));
|
||||
else if (command === 'await') output(await cmdAwait(args[0], args, context, profile));
|
||||
else if (command === 'pending') output(cmdPending(context));
|
||||
else if (command === 'typing') output(await cmdTyping(args[0], args, context));
|
||||
else if (command === 'end') output(await cmdEnd(args[0], context));
|
||||
else if (command === 'stop') output(await cmdStop(context));
|
||||
else if (command === 'server') await cmdServer(args, context);
|
||||
else {
|
||||
process.stderr.write(`Unknown command: ${command}\n\n${usage()}\n`);
|
||||
process.stderr.write(`Unknown command: ${command}\n\n${profile.usage()}\n`);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
@@ -403,4 +441,4 @@ if (require.main === module) {
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { main, ensureServer, healthCheck };
|
||||
module.exports = { PLAN_PROFILE, binForMode, main, ensureServer, healthCheck, valueAfter };
|
||||
Executable
+103
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* UI Canvas CLI: preview and hand-edit UI component mockups in the browser.
|
||||
*
|
||||
* node scripts/ui-canvas.js open components/card.html --viewport mobile
|
||||
* node scripts/ui-canvas.js await components/card.html
|
||||
* node scripts/ui-canvas.js await <file> --reply "Background is now brand gray."
|
||||
* node scripts/ui-canvas.js end <file>
|
||||
*
|
||||
* The agent writes a self-contained HTML mockup, `open` shows it in the UI
|
||||
* Canvas where the human selects, drags, resizes, edits text, deletes, and
|
||||
* switches viewports, and `await` blocks until they chat, apply edits, or
|
||||
* click Save and Finish. Finish delivers the edit log plus the path of the
|
||||
* exported final markup; the agent turns that into the production component.
|
||||
*
|
||||
* Shares the Plan Canvas loopback server, state dir, and Stop/SessionStart
|
||||
* hooks; only the session mode and the agent-facing guidance differ.
|
||||
*/
|
||||
|
||||
const { PLAN_PROFILE, main, valueAfter } = require('./plan-canvas');
|
||||
|
||||
function usage() {
|
||||
return [
|
||||
'UI Canvas - preview, hand-edit, and approve UI component mockups in the browser',
|
||||
'',
|
||||
'Usage:',
|
||||
' node scripts/ui-canvas.js Show server status and sessions',
|
||||
' node scripts/ui-canvas.js open <file.html> Open (or resume) a preview session',
|
||||
' node scripts/ui-canvas.js await <file.html> Block until the human chats, applies edits, or finishes',
|
||||
' node scripts/ui-canvas.js pending Show feedback queued for no listener',
|
||||
' node scripts/ui-canvas.js typing <file.html> Show a thinking/typing indicator in chat',
|
||||
' node scripts/ui-canvas.js end <file.html> End a session as the agent',
|
||||
' node scripts/ui-canvas.js stop Shut down the shared canvas server',
|
||||
' node scripts/ui-canvas.js server Run the server in the foreground',
|
||||
'',
|
||||
'Options:',
|
||||
' open: --viewport <mobile|desktop|custom|WxH> Initial viewport (default desktop)',
|
||||
' --title <text> Tab title shown in the browser',
|
||||
' --no-open Do not launch a browser window',
|
||||
' --reopen Reopen a session the user ended from the browser',
|
||||
' await: --reply <msg> Show an agent reply in the canvas chat before waiting',
|
||||
' --timeout-ms <n> Return {status:"waiting"} after n ms (tests/debug only)',
|
||||
' typing: --state <thinking|typing|idle> Defaults to typing',
|
||||
' server: --port <n> --host <h>',
|
||||
'',
|
||||
'Finish payloads name <file>.edited.html (final markup) and <file>.edits.json (edit log) next to the artifact.',
|
||||
'Environment: ECC_PLAN_CANVAS_PORT, ECC_PLAN_CANVAS_STATE_DIR, ECC_PLAN_CANVAS_IDLE_MS, ECC_CANVAS_AGENT'
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const UI_PROFILE = {
|
||||
...PLAN_PROFILE,
|
||||
mode: 'ui',
|
||||
bin: 'ecc-ui-canvas',
|
||||
tag: 'ui-canvas',
|
||||
usage,
|
||||
validateFile(file) {
|
||||
if (!/\.html?$/i.test(file)) {
|
||||
throw new Error('ui-canvas opens self-contained .html mockups; write the component to an .html file first');
|
||||
}
|
||||
},
|
||||
openBody(args) {
|
||||
const ui = {};
|
||||
const viewport = valueAfter(args, '--viewport');
|
||||
if (viewport) ui.viewport = viewport;
|
||||
const title = valueAfter(args, '--title');
|
||||
if (title) ui.title = title;
|
||||
return { mode: 'ui', ui };
|
||||
},
|
||||
nextSteps: {
|
||||
open: 'Run `ecc-ui-canvas await <file>` in the background and leave it running; it returns when the human chats, applies edits, or clicks Save and Finish.',
|
||||
feedback(result) {
|
||||
const items = Array.isArray(result.items) ? result.items : [];
|
||||
const finish = items.find(item => item.kind === 'finish');
|
||||
const applied = items.find(item => item.kind === 'edits');
|
||||
if (finish) {
|
||||
return `The human clicked Save and Finish. Read the final markup at ${finish.exportPath} (edit log: ${finish.editsPath}), reproduce that exact look in the real component with full functionality, and report in chat. Do not reopen the canvas.`;
|
||||
}
|
||||
if (applied) {
|
||||
return `The human applied ${applied.editCount} edit(s) to the preview. Rewrite the mockup file from ${applied.exportPath} (keep it self-contained), then run \`ecc-ui-canvas await <file> --reply "<what you changed>"\` to keep listening.`;
|
||||
}
|
||||
if (result.sessionEnded) {
|
||||
return 'The human sent this and ended the preview. Address it and report in chat; do not reopen the canvas uninvited.';
|
||||
}
|
||||
return 'Make the requested change in the mockup file; the preview live-reloads within a second and re-applies the human\'s pending edits. Then run `ecc-ui-canvas await <file> --reply "<what you changed>"` to answer and keep listening.';
|
||||
},
|
||||
ended(result) {
|
||||
return result.endedBy === 'user'
|
||||
? 'The human ended the preview without saving. Stop polling and report in chat; do not reopen uninvited.'
|
||||
: 'Session ended. Stop polling.';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (require.main === module) {
|
||||
main(process.argv.slice(2), UI_PROFILE).then(code => {
|
||||
process.exitCode = code;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { UI_PROFILE, main: argv => main(argv, UI_PROFILE), usage };
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: ui-canvas
|
||||
description: Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You then turn the exported edited markup into the production component. Use before committing or rebuilding a feature just to check a visual change.
|
||||
metadata:
|
||||
origin: ECC
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# UI Canvas
|
||||
|
||||
Approve-before-you-build loop for user interface work: you write a quick,
|
||||
self-contained HTML mockup of the component, the human opens it in the
|
||||
browser and adjusts it by hand like a website builder, and **Save and
|
||||
Finish** hands you the exact result to wire into the real code. Nobody has to
|
||||
rebuild and rerun the whole app to check a padding change.
|
||||
|
||||
Any component qualifies: a card, a sidebar, a modal, a settings pane, a
|
||||
single button state, an animation, a page section. Any harness qualifies:
|
||||
the loop is a CLI that prints JSON.
|
||||
|
||||
Shares its server, state, and hooks with `plan-canvas` (inspired by
|
||||
[lavish-axi](https://github.com/kunchenguid/lavish-axi) by @kunchenguid).
|
||||
Editing conventions follow
|
||||
[VisBug](https://github.com/GoogleChromeLabs/ProjectVisBug) and
|
||||
[Onlook](https://github.com/onlook-dev/onlook): Enter/Shift+Enter walk the
|
||||
tree, Delete removes, an edit/interact mode switch.
|
||||
|
||||
## When to Use
|
||||
|
||||
- The user asks to redesign, restyle, or add a UI component and wants to see
|
||||
it before you commit, rerun, or rebuild.
|
||||
- Feedback is visual ("make it tighter", "move that up", "lose the border")
|
||||
and is faster done by hand than typed.
|
||||
- Mobile and desktop both matter and the user wants to check the component
|
||||
at exact dimensions.
|
||||
- The user asks for `/ui-canvas`, a preview, a mockup, "show me first".
|
||||
|
||||
Do NOT use for: plan or document review (`/plan-canvas`), running the real
|
||||
app, remote URLs, or components you cannot render as plain HTML/CSS/JS in one
|
||||
file. The canvas serves local files only.
|
||||
|
||||
## How It Works
|
||||
|
||||
Invoke the CLI as `ecc-ui-canvas` (bin from the `ecc-universal` package, on
|
||||
PATH after a global or plugin install; `node "$CLAUDE_PLUGIN_ROOT/scripts/ui-canvas.js"`
|
||||
also works). It runs the same detached loopback server as `plan-canvas`
|
||||
(`127.0.0.1:4517`), keyed by artifact path; there are no session ids.
|
||||
|
||||
### 1. Write the mockup
|
||||
|
||||
Write one self-contained `.html` file (for example `.claude/previews/<name>.html`
|
||||
or next to the component): markup, a `<style>` block, and any `<script>` the
|
||||
component needs to behave (tabs, toggles, open/close, animation). Rules:
|
||||
|
||||
- Use the project's real brand tokens, fonts, copy, and realistic data. Read
|
||||
the existing CSS or theme file first; do not invent a palette.
|
||||
- Give meaningful elements an `id` or a distinctive class. The canvas records
|
||||
every human edit against a CSS selector; stable names make the export map
|
||||
cleanly back to your code.
|
||||
- Keep it faithful to production: same breakpoints, same `max-width`, same
|
||||
states. The canvas renders at true CSS-pixel viewport sizes, so media
|
||||
queries behave exactly as they would in the app.
|
||||
- Sibling assets (images, fonts) may sit next to the file and be referenced by
|
||||
relative path; a `data:` URI or an inline SVG also works.
|
||||
- Inline only what the component needs. A mockup is a sketch, not the app.
|
||||
|
||||
### 2. Open and listen
|
||||
|
||||
```bash
|
||||
ecc-ui-canvas open .claude/previews/pricing-card.html --viewport desktop --title "Pricing card"
|
||||
ecc-ui-canvas await .claude/previews/pricing-card.html # run in the background; leave it running
|
||||
```
|
||||
|
||||
`--viewport` takes `mobile` (393×852), `desktop` (fills the window), `custom`,
|
||||
or exact `WxH` such as `1024x768`. Run `await` in the background if your
|
||||
harness time-limits foreground commands; re-run it if interrupted, queued
|
||||
feedback is never lost. While it runs, the canvas shows "<your harness>
|
||||
listening" so the human knows you are connected.
|
||||
|
||||
### 3. Handle what comes back
|
||||
|
||||
`await` prints JSON when the human acts. Items:
|
||||
|
||||
```json
|
||||
{ "kind": "chat", "text": "change this to dark gray in the brand colors",
|
||||
"anchor": { "selector": "#pricing-card", "tag": "article", "snippet": "Most popular Team plan…", "size": { "width": 720, "height": 388 } },
|
||||
"pendingEdits": ["resized img.art to 220px wide, 220px tall (was 260×260)", "removed button.btn.secondary"] }
|
||||
```
|
||||
|
||||
- `chat` is a request. `anchor` is the element the human had selected when
|
||||
they sent it; `pendingEdits` summarizes hand edits they have made that are
|
||||
**not yet in your file**. Make the requested change in the mockup file.
|
||||
The preview reloads within a second and re-applies their pending edits on
|
||||
top, so do **not** bake `pendingEdits` into the file yourself: they are
|
||||
context, and doubling them up would misplace things. Answer in the canvas
|
||||
and keep listening with one command:
|
||||
|
||||
```bash
|
||||
ecc-ui-canvas await <file> --reply "Background is now var(--gray-800) from the brand tokens."
|
||||
```
|
||||
|
||||
Speed matters here. Run `ecc-ui-canvas typing <file> --state thinking`
|
||||
the moment you start, edit the file, then reply. Under two seconds from
|
||||
request to repaint is the target for a one-property change.
|
||||
|
||||
```json
|
||||
{ "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ],
|
||||
"viewport": { "preset": "mobile", "width": 393, "height": 852 },
|
||||
"exportPath": "/abs/.claude/previews/pricing-card.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.edits.json" }
|
||||
```
|
||||
|
||||
- `edits` means the human clicked **Apply to file**: they want their hand
|
||||
edits written into the mockup now. Replace the mockup file with the
|
||||
contents of `exportPath` (it is the full DOM they are looking at, with
|
||||
their inline-style changes), tidy it into real CSS if it is messy, keep it
|
||||
self-contained, and reply. The canvas clears its pending list, so nothing
|
||||
is applied twice.
|
||||
|
||||
```json
|
||||
{ "kind": "finish", "editCount": 5, "edits": [ "…" ], "viewport": { "preset": "desktop", "width": 1412, "height": 806 },
|
||||
"exportPath": "…/pricing-card.edited.html", "editsPath": "…/pricing-card.edits.json" }
|
||||
```
|
||||
|
||||
- `finish` means the human clicked **Save and Finish**. The session is over
|
||||
(`sessionEnded: true`). Read `exportPath`, diff it against your original
|
||||
mockup, read `editsPath` for the intent behind each change, and reproduce
|
||||
that exact look in the real component with full functionality: real
|
||||
tokens, responsive rules, accessible markup, the project's framework.
|
||||
Then commit per the repo's rules and report in chat. Do not reopen the
|
||||
canvas.
|
||||
|
||||
Edit kinds you will see in `edits`: `text` (before/after, plus `htmlAfter`
|
||||
when inline markup was kept), `resize` (border-box px), `move` (from/to
|
||||
parent selector and index), `nudge` (dx/dy px offsets the human applied by
|
||||
dragging with Alt or arrow keys; translate to margin or alignment, not
|
||||
`position: relative`), `remove`, and `style` (`property`, computed `before`,
|
||||
`after`; `after: null` means they deleted the property, so border → none,
|
||||
box-shadow → none, padding → 0). An edit flagged `stale: true` could not be
|
||||
re-applied after one of your reloads; ask about it rather than guessing.
|
||||
|
||||
### 4. End
|
||||
|
||||
`ecc-ui-canvas end <file>` closes a session you opened and no longer need.
|
||||
`{"status":"ended","endedBy":"user"}` means the human closed it without
|
||||
saving: stop polling and do not reopen unless asked (`open --reopen`).
|
||||
|
||||
## What the Human Can Do
|
||||
|
||||
Edit mode (default): click selects, with hover and selection outlines and a
|
||||
size badge; double-click edits text; corner and edge handles resize (images
|
||||
keep their ratio unless Shift is held); dragging reorders among siblings or
|
||||
into another container with an insertion marker; Alt-drag or arrow keys
|
||||
nudge (Shift for 10 px); Delete or Backspace removes; Enter steps into the
|
||||
first child, Shift+Enter to the parent, Tab between siblings; Cmd/Ctrl+Z and
|
||||
Shift+Cmd/Ctrl+Z undo and redo. The inspector shows the selected element's
|
||||
breadcrumb and grouped slider rows (size, fill, text, spacing, border,
|
||||
effects). Drag a slider, or double-click a value to type one (sanitized and
|
||||
clamped; arrow keys step). A color swatch opens hue, saturation, lightness,
|
||||
and alpha sliders; the hex field also takes rgb() or a color name; the x
|
||||
button clears a property.
|
||||
|
||||
Interact mode (Cmd/Ctrl+I): clicks, hovers, and keyboard reach the component
|
||||
so they can try the tabs, toggles, and animations exactly as a user would.
|
||||
A pause button freezes animations and transitions for inspection.
|
||||
|
||||
Viewport bar: desktop (fills the stage), mobile (iPhone-class 393×852 with a
|
||||
device frame), or exact width × height; a rotate button swaps the two. The
|
||||
preview scales down only when the stage is smaller than the chosen size,
|
||||
never the other way, so media queries are honest.
|
||||
|
||||
## Rules
|
||||
|
||||
- One self-contained `.html` file per component. Markdown is not accepted;
|
||||
use `plan-canvas` for documents.
|
||||
- Edit the artifact file to revise. The canvas live-reloads on save and
|
||||
restores the human's pending edits, selection, and scroll. Never re-run
|
||||
`open` to refresh.
|
||||
- Never apply `pendingEdits` from a `chat` item into the file. Apply edits
|
||||
only from an `edits` or `finish` payload, from `exportPath`.
|
||||
- Reply in the canvas (`await --reply`), not only in the terminal, while the
|
||||
session is open.
|
||||
- The exported `.edited.html` and `.edits.json` are review artifacts, not
|
||||
production code. Do not commit them unless the repo keeps previews.
|
||||
- The server is loopback-only, idles out after 30 minutes
|
||||
(`ECC_PLAN_CANVAS_IDLE_MS`), and keeps state in `~/.claude/plan-canvas/`
|
||||
(`ECC_PLAN_CANVAS_STATE_DIR`). `ECC_CANVAS_AGENT` overrides the detected
|
||||
harness name shown in the browser.
|
||||
|
||||
## Examples
|
||||
|
||||
**Redesign with preview before commit**
|
||||
|
||||
```bash
|
||||
# user: "Make the pricing card friendlier, then show me before you commit."
|
||||
# → write .claude/previews/pricing-card.html using tokens from src/styles/tokens.css
|
||||
ecc-ui-canvas open .claude/previews/pricing-card.html --title "Pricing card"
|
||||
ecc-ui-canvas await .claude/previews/pricing-card.html
|
||||
# → {"status":"feedback","items":[{"kind":"chat","text":"change this to dark gray in the brand colors","anchor":{"selector":"#pricing-card",…},"pendingEdits":[…]}]}
|
||||
ecc-ui-canvas typing .claude/previews/pricing-card.html --state thinking
|
||||
# → edit the file: background: var(--gray-800)
|
||||
ecc-ui-canvas await .claude/previews/pricing-card.html --reply "Card background is now --gray-800."
|
||||
# → {"status":"feedback","sessionEnded":true,"items":[{"kind":"finish","editCount":5,"exportPath":"…/pricing-card.edited.html",…}]}
|
||||
# → read the export, port the look into src/components/PricingCard.tsx, commit
|
||||
```
|
||||
|
||||
**Mobile check of an existing component**
|
||||
|
||||
```bash
|
||||
ecc-ui-canvas open .claude/previews/sidebar.html --viewport mobile
|
||||
ecc-ui-canvas await .claude/previews/sidebar.html
|
||||
```
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Opening the real app's URL. The canvas serves one local file; mock the
|
||||
component instead.
|
||||
- Building the mockup with a framework build step. Plain HTML renders in
|
||||
milliseconds and reloads in under a second; that is the point.
|
||||
- Re-applying `pendingEdits` yourself, then watching the canvas apply them
|
||||
again.
|
||||
- Polling with `--timeout-ms` in a loop; leave the plain `await` running.
|
||||
- Letting a `chat` request sit. The human is watching the preview; signal
|
||||
`typing --state thinking` and move.
|
||||
- Committing `*.edited.html` or `*.edits.json`.
|
||||
@@ -0,0 +1,66 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"><head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Pricing card mockup</title>
|
||||
<style>
|
||||
:root{--brand:#6885e8;--brand-2:#e26a9e;--ink:#181b23;--muted:#585e6e;--line:#dde1e8;--bg:#f4f5f7}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Inter,sans-serif;color:var(--ink);padding:24px}
|
||||
.card{width:min(720px,100%);display:grid;grid-template-columns:260px 1fr;gap:28px;background:#fff;border:2px solid var(--line);border-radius:18px;padding:28px;box-shadow:0 20px 60px rgba(24,27,35,.08)}
|
||||
.card .art{width:100%;aspect-ratio:1/1;border-radius:14px;background:linear-gradient(135deg,var(--brand),var(--brand-2));display:block}
|
||||
.badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--brand);background:rgba(104,133,232,.12);border-radius:99px;padding:4px 10px;margin-bottom:12px}
|
||||
.badge i{width:7px;height:7px;border-radius:99px;background:var(--brand);animation:pulse 1.4s infinite}
|
||||
@keyframes pulse{0%,100%{transform:scale(1);opacity:1}50%{transform:scale(1.5);opacity:.5}}
|
||||
h1{margin:0 0 8px;font-size:28px;letter-spacing:-.02em}
|
||||
p{margin:0 0 18px;color:var(--muted);line-height:1.55}
|
||||
.price{display:flex;align-items:baseline;gap:6px;margin-bottom:18px}
|
||||
.price b{font-size:40px;letter-spacing:-.03em}
|
||||
.price span{color:var(--muted)}
|
||||
.toggle{display:inline-flex;background:var(--bg);border-radius:99px;padding:3px;margin-bottom:18px}
|
||||
.toggle button{border:0;background:transparent;padding:6px 14px;border-radius:99px;font:600 12px inherit;color:var(--muted);cursor:pointer}
|
||||
.toggle button.on{background:#fff;color:var(--ink);box-shadow:0 1px 3px rgba(0,0,0,.12)}
|
||||
.actions{display:flex;gap:10px}
|
||||
.btn{height:42px;padding:0 18px;border-radius:10px;font:600 14px inherit;cursor:pointer;border:1px solid transparent}
|
||||
.btn.primary{background:var(--brand);color:#fff}
|
||||
.btn.secondary{background:#fff;color:var(--ink);border-color:var(--line)}
|
||||
.card{animation:bubble-in .7s both;transform-origin:50% 50%}
|
||||
@keyframes bubble-in{
|
||||
0%{transform:scale(.05);opacity:0;animation-timing-function:cubic-bezier(.2,.9,.3,1)}
|
||||
40%{transform:scale(1.08);opacity:1;animation-timing-function:ease-in-out}
|
||||
58%{transform:scale(.95,1.04)}
|
||||
74%{transform:scale(1.03,.98)}
|
||||
88%{transform:scale(.99,1.01)}
|
||||
100%{transform:scale(1)}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){.card{animation:none}}
|
||||
@media (max-width:600px){.card{grid-template-columns:1fr;padding:20px}.card .art{aspect-ratio:16/9}h1{font-size:24px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<article class="card" id="pricing-card">
|
||||
<img class="art" alt="Plan illustration" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%236885e8'/%3E%3Cstop offset='1' stop-color='%23e26a9e'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='10' height='10' fill='url(%23g)'/%3E%3C/svg%3E">
|
||||
<div class="body">
|
||||
<span class="badge"><i></i>Most posdlkfjhlskjdfklsfpular</span>
|
||||
<h1 id="plan-title">Team plan</h1>
|
||||
<p>Everything in Starter, plus shared memory, hosted CI tiers, and priority support for up to 25 seats.</p>
|
||||
<div class="toggle" role="group"><button class="on" data-period="monthly">Monthly</button><button data-period="yearly">Yearly</button></div>
|
||||
<div class="price"><b id="price">$49</b><span id="period">/ seat / month</span></div>
|
||||
<div class="actions">
|
||||
<button class="btn primary" style="background-color: rgb(0, 0, 0);">Start free trial</button>
|
||||
<button class="btn secondary">Talk to sales</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<script>
|
||||
document.querySelectorAll('.toggle button').forEach(b => b.addEventListener('click', () => {
|
||||
document.querySelectorAll('.toggle button').forEach(x => x.classList.toggle('on', x === b));
|
||||
const yearly = b.dataset.period === 'yearly';
|
||||
document.getElementById('price').textContent = yearly ? '$39' : '$49';
|
||||
document.getElementById('period').textContent = yearly ? '/ seat / month, billed yearly' : '/ seat / month';
|
||||
}));
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
</body></html>
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"artifact": "/Users/hira/Documents/ECC/ecc-ui-canvas/tests/fixtures/ui-canvas/pricing-card.html",
|
||||
"kind": "finish",
|
||||
"at": "2026-10-16T22:17:40.722Z",
|
||||
"viewport": {
|
||||
"preset": "desktop",
|
||||
"width": 1034,
|
||||
"height": 666
|
||||
},
|
||||
"edits": [
|
||||
{
|
||||
"id": "e1-mvbj1riu",
|
||||
"kind": "text",
|
||||
"selector": "#pricing-card > div.body:nth-of-type(1) > span.badge:nth-of-type(1)",
|
||||
"tag": "span",
|
||||
"snippet": "MOST POSDLKFJHLSKJDFKLSFPULAR",
|
||||
"at": "2026-10-16T22:16:25.494Z",
|
||||
"before": "MOST POPULAR",
|
||||
"after": "MOST POSDLKFJHLSKJDFKLSFPULAR",
|
||||
"htmlAfter": "<i></i>Most posdlkfjhlskjdfklsfpular"
|
||||
},
|
||||
{
|
||||
"id": "e2-mvbj1utl",
|
||||
"kind": "style",
|
||||
"selector": "#pricing-card > div.body:nth-of-type(1) > div.actions:nth-of-type(3) > button.btn.primary:nth-of-type(1)",
|
||||
"tag": "button",
|
||||
"snippet": "Start free trial",
|
||||
"at": "2026-10-16T22:16:29.770Z",
|
||||
"property": "background-color",
|
||||
"before": "rgb(104, 133, 232)",
|
||||
"after": "#6885e8"
|
||||
},
|
||||
{
|
||||
"id": "e3-mvbj203j",
|
||||
"kind": "style",
|
||||
"selector": "#pricing-card > div.body:nth-of-type(1) > div.actions:nth-of-type(3) > button.btn.primary:nth-of-type(1)",
|
||||
"tag": "button",
|
||||
"snippet": "Start free trial",
|
||||
"at": "2026-10-16T22:16:36.607Z",
|
||||
"property": "background-color",
|
||||
"before": "rgb(104, 133, 232)",
|
||||
"after": "rgb(0,0,0)"
|
||||
}
|
||||
]
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Pricing card mockup</title>
|
||||
<style>
|
||||
:root{--brand:#6885e8;--brand-2:#e26a9e;--ink:#181b23;--muted:#585e6e;--line:#dde1e8;--bg:#f4f5f7}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Inter,sans-serif;color:var(--ink);padding:24px}
|
||||
.card{width:min(720px,100%);display:grid;grid-template-columns:260px 1fr;gap:28px;background:#fff;border:2px solid var(--line);border-radius:18px;padding:28px;box-shadow:0 20px 60px rgba(24,27,35,.08)}
|
||||
.card .art{width:100%;aspect-ratio:1/1;border-radius:14px;background:linear-gradient(135deg,var(--brand),var(--brand-2));display:block}
|
||||
.badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--brand);background:rgba(104,133,232,.12);border-radius:99px;padding:4px 10px;margin-bottom:12px}
|
||||
.badge i{width:7px;height:7px;border-radius:99px;background:var(--brand);animation:pulse 1.4s infinite}
|
||||
@keyframes pulse{0%,100%{transform:scale(1);opacity:1}50%{transform:scale(1.5);opacity:.5}}
|
||||
h1{margin:0 0 8px;font-size:28px;letter-spacing:-.02em}
|
||||
p{margin:0 0 18px;color:var(--muted);line-height:1.55}
|
||||
.price{display:flex;align-items:baseline;gap:6px;margin-bottom:18px}
|
||||
.price b{font-size:40px;letter-spacing:-.03em}
|
||||
.price span{color:var(--muted)}
|
||||
.toggle{display:inline-flex;background:var(--bg);border-radius:99px;padding:3px;margin-bottom:18px}
|
||||
.toggle button{border:0;background:transparent;padding:6px 14px;border-radius:99px;font:600 12px inherit;color:var(--muted);cursor:pointer}
|
||||
.toggle button.on{background:#fff;color:var(--ink);box-shadow:0 1px 3px rgba(0,0,0,.12)}
|
||||
.actions{display:flex;gap:10px}
|
||||
.btn{height:42px;padding:0 18px;border-radius:10px;font:600 14px inherit;cursor:pointer;border:1px solid transparent}
|
||||
.btn.primary{background:var(--brand);color:#fff}
|
||||
.btn.secondary{background:#fff;color:var(--ink);border-color:var(--line)}
|
||||
.card{animation:bubble-in .7s both;transform-origin:50% 50%}
|
||||
@keyframes bubble-in{
|
||||
0%{transform:scale(.05);opacity:0;animation-timing-function:cubic-bezier(.2,.9,.3,1)}
|
||||
40%{transform:scale(1.08);opacity:1;animation-timing-function:ease-in-out}
|
||||
58%{transform:scale(.95,1.04)}
|
||||
74%{transform:scale(1.03,.98)}
|
||||
88%{transform:scale(.99,1.01)}
|
||||
100%{transform:scale(1)}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){.card{animation:none}}
|
||||
@media (max-width:600px){.card{grid-template-columns:1fr;padding:20px}.card .art{aspect-ratio:16/9}h1{font-size:24px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<article class="card" id="pricing-card">
|
||||
<img class="art" alt="Plan illustration" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%236885e8'/%3E%3Cstop offset='1' stop-color='%23e26a9e'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='10' height='10' fill='url(%23g)'/%3E%3C/svg%3E">
|
||||
<div class="body">
|
||||
<span class="badge"><i></i>Most popular</span>
|
||||
<h1 id="plan-title">Team plan</h1>
|
||||
<p>Everything in Starter, plus shared memory, hosted CI tiers, and priority support for up to 25 seats.</p>
|
||||
<div class="toggle" role="group"><button class="on" data-period="monthly">Monthly</button><button data-period="yearly">Yearly</button></div>
|
||||
<div class="price"><b id="price">$49</b><span id="period">/ seat / month</span></div>
|
||||
<div class="actions">
|
||||
<button class="btn primary">Start free trial</button>
|
||||
<button class="btn secondary">Talk to sales</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<script>
|
||||
document.querySelectorAll('.toggle button').forEach(b => b.addEventListener('click', () => {
|
||||
document.querySelectorAll('.toggle button').forEach(x => x.classList.toggle('on', x === b));
|
||||
const yearly = b.dataset.period === 'yearly';
|
||||
document.getElementById('price').textContent = yearly ? '$39' : '$49';
|
||||
document.getElementById('period').textContent = yearly ? '/ seat / month, billed yearly' : '/ seat / month';
|
||||
}));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* End-to-end test for UI Canvas through the real CLI (scripts/ui-canvas.js)
|
||||
* and a real detached canvas server, with the browser side simulated over
|
||||
* the same HTTP surface the shell uses.
|
||||
*
|
||||
* Flow under test:
|
||||
* agent: open --no-open --viewport mobile → server starts, ui session opens
|
||||
* agent: open on a markdown file → refused before touching the server
|
||||
* agent: await (blocking child) → long poll, agent identity recorded
|
||||
* browser: POST chat with anchor → await resolves with ui guidance
|
||||
* agent: await --reply + browser finish → export written, finish guidance
|
||||
* agent: pending / status / end / stop
|
||||
*
|
||||
* Run with: node tests/integration/ui-canvas-e2e.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawn, spawnSync } = require('child_process');
|
||||
|
||||
const CLI = path.join(__dirname, '..', '..', 'scripts', 'ui-canvas.js');
|
||||
|
||||
const results = [];
|
||||
async function test(name, fn) {
|
||||
try {
|
||||
await fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
results.push(true);
|
||||
} catch (err) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${err.stack || err.message}`);
|
||||
results.push(false);
|
||||
}
|
||||
}
|
||||
|
||||
function cli(env, args, { timeoutMs = 15000 } = {}) {
|
||||
const result = spawnSync('node', [CLI, ...args], { encoding: 'utf8', timeout: timeoutMs, env: { ...process.env, ...env } });
|
||||
let parsed = null;
|
||||
try { parsed = JSON.parse(result.stdout.trim()); } catch { /* callers assert */ }
|
||||
return { ...result, parsed };
|
||||
}
|
||||
|
||||
function request(port, method, requestPath, body = null) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const payload = body === null ? null : JSON.stringify(body);
|
||||
const req = http.request(
|
||||
{ host: '127.0.0.1', port, method, path: requestPath, headers: payload ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) } : {} },
|
||||
res => {
|
||||
let data = '';
|
||||
res.on('data', chunk => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try { resolve({ statusCode: res.statusCode, body: JSON.parse(data.trim() || '{}') }); } catch { resolve({ statusCode: res.statusCode, body: data }); }
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on('error', reject);
|
||||
if (payload) req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function startAwait(env, file, extra = []) {
|
||||
const child = spawn('node', [CLI, 'await', file, ...extra], { env: { ...process.env, ...env, ECC_CANVAS_AGENT: 'Test Harness' } });
|
||||
let stdout = '';
|
||||
child.stdout.on('data', chunk => { stdout += chunk; });
|
||||
child.stderr.on('data', () => {});
|
||||
const done = new Promise(resolve => child.on('close', () => resolve(stdout)));
|
||||
return { child, done };
|
||||
}
|
||||
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
async function main() {
|
||||
console.log('ui-canvas e2e');
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ui-canvas-e2e-'));
|
||||
const stateDir = path.join(tmp, 'state');
|
||||
const port = 20000 + Math.floor(Math.random() * 20000);
|
||||
const env = { ECC_PLAN_CANVAS_STATE_DIR: stateDir, ECC_PLAN_CANVAS_PORT: String(port) };
|
||||
const mockup = path.join(tmp, 'card.html');
|
||||
fs.writeFileSync(mockup, '<!DOCTYPE html><html><body><article id="card"><h1>Hi</h1></article></body></html>');
|
||||
let key = null;
|
||||
|
||||
try {
|
||||
await test('open refuses non-HTML before starting a server', async () => {
|
||||
const plan = path.join(tmp, 'plan.md');
|
||||
fs.writeFileSync(plan, '# plan');
|
||||
const res = cli(env, ['open', plan, '--no-open']);
|
||||
assert.ok(res.parsed && /\.html/.test(res.parsed.error), res.stdout);
|
||||
assert.strictEqual(cli(env, []).parsed.server, 'not running');
|
||||
});
|
||||
|
||||
await test('open starts the shared server and opens a ui session', async () => {
|
||||
const res = cli(env, ['open', mockup, '--no-open', '--viewport', 'mobile', '--title', 'Card']);
|
||||
assert.strictEqual(res.parsed.status, 'open', res.stdout);
|
||||
assert.match(res.parsed.url, new RegExp(`^http://127\\.0\\.0\\.1:${port}/canvas/[a-f0-9]{12}$`));
|
||||
assert.match(res.parsed.next_step, /ecc-ui-canvas await/);
|
||||
key = res.parsed.url.split('/').pop();
|
||||
const status = cli(env, []);
|
||||
assert.strictEqual(status.parsed.sessions[0].mode, 'ui');
|
||||
const state = JSON.parse(fs.readFileSync(path.join(stateDir, 'sessions.json'), 'utf8'));
|
||||
assert.deepStrictEqual(state.sessions[key].ui, { viewport: 'mobile', title: 'Card' });
|
||||
});
|
||||
|
||||
await test('await records the agent and resolves with ui guidance on chat', async () => {
|
||||
const waiting = startAwait(env, mockup);
|
||||
await sleep(500);
|
||||
const sessions = await request(port, 'GET', '/api/sessions');
|
||||
assert.strictEqual(sessions.body.sessions[0].agent.name, 'Test Harness');
|
||||
await request(port, 'POST', `/api/session/${key}/feedback`, {
|
||||
items: [{ kind: 'chat', text: 'make it gray', anchor: { selector: '#card', tag: 'article', snippet: 'Hi' }, pendingEdits: ['removed h1'] }]
|
||||
});
|
||||
const out = JSON.parse(await waiting.done);
|
||||
assert.strictEqual(out.status, 'feedback');
|
||||
assert.strictEqual(out.items[0].anchor.selector, '#card');
|
||||
assert.match(out.next_step, /live-reloads/);
|
||||
assert.match(out.next_step, /ecc-ui-canvas await <file> --reply/);
|
||||
});
|
||||
|
||||
await test('await --reply lands in chat and finish delivers export paths', async () => {
|
||||
const waiting = startAwait(env, mockup, ['--reply', 'Gray it is.']);
|
||||
await sleep(500);
|
||||
const sessions = await request(port, 'GET', '/api/sessions');
|
||||
assert.strictEqual(sessions.body.sessions[0].status, 'open');
|
||||
await request(port, 'POST', `/api/session/${key}/feedback`, {
|
||||
items: [{ kind: 'finish', html: '<!DOCTYPE html>\n<html><body><article id="card" style="background:#333"><h1>Hi</h1></article></body></html>\n', edits: [{ kind: 'style', selector: '#card', property: 'background-color', before: 'white', after: '#333' }], viewport: { preset: 'mobile', width: 393, height: 852 } }],
|
||||
endSession: true
|
||||
});
|
||||
const out = JSON.parse(await waiting.done);
|
||||
assert.strictEqual(out.sessionEnded, true);
|
||||
const finish = out.items[0];
|
||||
assert.strictEqual(finish.kind, 'finish');
|
||||
assert.strictEqual(finish.exportPath, path.join(fs.realpathSync(tmp), 'card.edited.html'));
|
||||
assert.ok(fs.existsSync(finish.exportPath));
|
||||
assert.match(out.next_step, /Save and Finish/);
|
||||
assert.ok(out.next_step.includes(finish.exportPath));
|
||||
const state = JSON.parse(fs.readFileSync(path.join(stateDir, 'sessions.json'), 'utf8'));
|
||||
const chat = state.sessions[key].chat.map(entry => entry.text);
|
||||
assert.ok(chat.includes('Gray it is.'));
|
||||
assert.ok(chat.includes('Saved and finished with 1 edit'));
|
||||
});
|
||||
|
||||
await test('a user-finished session refuses a plain reopen and reports ended on await', async () => {
|
||||
const reopen = cli(env, ['open', mockup, '--no-open']);
|
||||
assert.strictEqual(reopen.parsed.status, 'user-ended');
|
||||
const ended = cli(env, ['await', mockup, '--timeout-ms', '200']);
|
||||
assert.strictEqual(ended.parsed.status, 'ended');
|
||||
assert.match(ended.parsed.next_step, /ended the preview/);
|
||||
});
|
||||
|
||||
await test('pending lists ui sessions with a ui-canvas resume command', async () => {
|
||||
const other = path.join(tmp, 'sidebar.html');
|
||||
fs.writeFileSync(other, '<html><body><nav>x</nav></body></html>');
|
||||
const opened = cli(env, ['open', other, '--no-open']);
|
||||
assert.strictEqual(opened.parsed.status, 'open');
|
||||
const otherKey = opened.parsed.url.split('/').pop();
|
||||
await request(port, 'POST', `/api/session/${otherKey}/feedback`, { items: [{ kind: 'chat', text: 'queued for nobody' }] });
|
||||
const pending = cli(env, ['pending']);
|
||||
assert.strictEqual(pending.parsed.status, 'pending');
|
||||
assert.strictEqual(pending.parsed.sessions[0].mode, 'ui');
|
||||
assert.strictEqual(pending.parsed.sessions[0].resume, `ecc-ui-canvas await ${JSON.stringify(fs.realpathSync(other))}`);
|
||||
const ended = cli(env, ['end', other]);
|
||||
assert.strictEqual(ended.parsed.status, 'ended');
|
||||
});
|
||||
|
||||
await test('stop shuts the shared server down', async () => {
|
||||
const stop = cli(env, ['stop']);
|
||||
assert.strictEqual(stop.parsed.status, 'stopping');
|
||||
let gone = false;
|
||||
for (let i = 0; i < 30 && !gone; i++) {
|
||||
await sleep(100);
|
||||
gone = cli(env, []).parsed.server === 'not running';
|
||||
}
|
||||
assert.ok(gone, 'server should stop listening after stop');
|
||||
});
|
||||
} finally {
|
||||
cli(env, ['stop']);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const passed = results.filter(Boolean).length;
|
||||
const failed = results.length - passed;
|
||||
console.log('\n' + '='.repeat(40));
|
||||
console.log(`Passed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
console.log('='.repeat(40));
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err);
|
||||
console.log('Passed: 0');
|
||||
console.log('Failed: 1');
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Tests for harness detection shown in the canvas presence pill
|
||||
* (scripts/lib/plan-canvas/agent-identity.js).
|
||||
*
|
||||
* Run with: node tests/lib/plan-canvas-agent-identity.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const path = require('path');
|
||||
|
||||
const identity = require('../../scripts/lib/plan-canvas/agent-identity');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` PASS ${name}`);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.log(` FAIL ${name}\n ${error.stack || error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('plan-canvas agent identity');
|
||||
|
||||
test('detectAgentName recognizes each harness marker and falls back to agent', () => {
|
||||
assert.strictEqual(identity.detectAgentName({}), 'agent');
|
||||
assert.strictEqual(identity.detectAgentName({ CLAUDECODE: '1' }), 'Claude Code');
|
||||
assert.strictEqual(identity.detectAgentName({ CODEX_SANDBOX: 'seatbelt' }), 'Codex');
|
||||
assert.strictEqual(identity.detectAgentName({ CURSOR_TRACE_ID: 'x' }), 'Cursor');
|
||||
assert.strictEqual(identity.detectAgentName({ GEMINI_CLI: '1' }), 'Gemini CLI');
|
||||
assert.strictEqual(identity.detectAgentName({ OPENCODE: '1' }), 'OpenCode');
|
||||
assert.strictEqual(identity.detectAgentName({ COPILOT_AGENT: '1' }), 'Copilot');
|
||||
assert.strictEqual(identity.detectAgentName({ KIMI_CLI: '1' }), 'Kimi');
|
||||
assert.strictEqual(identity.detectAgentName({ QWEN_CODE: '1' }), 'Qwen Code');
|
||||
assert.strictEqual(identity.detectAgentName({ CLAUDECODE: '' }), 'agent', 'empty markers do not count');
|
||||
});
|
||||
|
||||
test('ECC_CANVAS_AGENT overrides detection and is clamped', () => {
|
||||
assert.strictEqual(identity.detectAgentName({ CLAUDECODE: '1', ECC_CANVAS_AGENT: ' Fleet worker 3 ' }), 'Fleet worker 3');
|
||||
assert.strictEqual(identity.detectAgentName({ ECC_CANVAS_AGENT: 'x'.repeat(100) }).length, 60);
|
||||
});
|
||||
|
||||
test('agentDescriptor reports the name and the project basename only', () => {
|
||||
const descriptor = identity.agentDescriptor({ env: { CODEX_THREAD_ID: 't' }, cwd: path.join('/Users', 'someone', 'repos', 'shop') });
|
||||
assert.deepStrictEqual(descriptor, { name: 'Codex', project: 'shop' });
|
||||
});
|
||||
|
||||
test('sanitizeAgentDescriptor drops junk and clamps lengths', () => {
|
||||
assert.strictEqual(identity.sanitizeAgentDescriptor(null), null);
|
||||
assert.strictEqual(identity.sanitizeAgentDescriptor({ name: ' ' }), null);
|
||||
assert.deepStrictEqual(identity.sanitizeAgentDescriptor({ name: ' Claude Code ', project: 'ecc', extra: 1 }), { name: 'Claude Code', project: 'ecc' });
|
||||
const long = identity.sanitizeAgentDescriptor({ name: 'n'.repeat(80), project: 'p'.repeat(200) });
|
||||
assert.strictEqual(long.name.length, 60);
|
||||
assert.strictEqual(long.project.length, 120);
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Unit tests for the UI Canvas feedback schema (scripts/lib/ui-canvas/feedback.js).
|
||||
*
|
||||
* Run with: node tests/lib/ui-canvas-feedback.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const feedback = require('../../scripts/lib/ui-canvas/feedback');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` PASS ${name}`);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.log(` FAIL ${name}\n ${error.stack || error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('ui-canvas feedback');
|
||||
|
||||
test('normalizeEdit accepts every supported kind and clamps fields', () => {
|
||||
const text = feedback.normalizeEdit({ kind: 'text', selector: '#t', tag: 'h1', snippet: 'x'.repeat(500), before: 'Old', after: 'New', htmlAfter: '<b>New</b>' }, 0);
|
||||
assert.strictEqual(text.kind, 'text');
|
||||
assert.strictEqual(text.snippet.length, 200);
|
||||
assert.strictEqual(text.htmlAfter, '<b>New</b>');
|
||||
assert.strictEqual(text.id, 'edit-1');
|
||||
|
||||
const resize = feedback.normalizeEdit({ kind: 'resize', selector: 'img.art', width: '220.4', height: 180, before: { width: 260, height: 260 } }, 3);
|
||||
assert.deepStrictEqual([resize.width, resize.height, resize.before], [220, 180, { width: 260, height: 260 }]);
|
||||
|
||||
const move = feedback.normalizeEdit({ kind: 'move', selector: 'button', from: { parent: 'div.a', index: 2 }, to: { parent: 'div.b', index: 0 } }, 0);
|
||||
assert.deepStrictEqual(move.to, { parent: 'div.b', index: 0 });
|
||||
|
||||
const nudge = feedback.normalizeEdit({ kind: 'nudge', selector: 'p', dx: -4, dy: 10.6 }, 0);
|
||||
assert.deepStrictEqual([nudge.dx, nudge.dy], [-4, 11]);
|
||||
|
||||
const remove = feedback.normalizeEdit({ kind: 'remove', selector: 'button.secondary', outerHTML: '<button>x</button>', from: { parent: 'div.actions', index: 1 } }, 0);
|
||||
assert.strictEqual(remove.outerHTML, '<button>x</button>');
|
||||
assert.strictEqual(remove.from.index, 1);
|
||||
|
||||
const style = feedback.normalizeEdit({ kind: 'style', selector: '#card', property: 'border', before: '2px solid rgb(1, 2, 3)', after: null, stale: true }, 0);
|
||||
assert.strictEqual(style.after, null);
|
||||
assert.strictEqual(style.stale, true);
|
||||
});
|
||||
|
||||
test('normalizeEdit rejects unknown kinds, bad selectors, and bad properties', () => {
|
||||
assert.strictEqual(feedback.normalizeEdit({ kind: 'bogus', selector: 'x' }, 0), null);
|
||||
assert.strictEqual(feedback.normalizeEdit({ kind: 'text', selector: '' }, 0), null);
|
||||
assert.strictEqual(feedback.normalizeEdit({ kind: 'style', selector: 'x', property: 'Background;drop' }, 0), null);
|
||||
assert.strictEqual(feedback.normalizeEdit({ kind: 'resize', selector: 'x' }, 0), null);
|
||||
assert.strictEqual(feedback.normalizeEdit({ kind: 'move', selector: 'x', from: { index: 0 } }, 0), null);
|
||||
assert.strictEqual(feedback.normalizeEdit(null, 0), null);
|
||||
});
|
||||
|
||||
test('normalizeEdits caps the batch and drops unusable records', () => {
|
||||
const raw = Array.from({ length: feedback.MAX_EDITS + 20 }, (_, i) => ({ kind: i % 2 ? 'nudge' : 'bogus', selector: 'p', dx: 1, dy: 1 }));
|
||||
const edits = feedback.normalizeEdits(raw);
|
||||
assert.ok(edits.length <= feedback.MAX_EDITS);
|
||||
assert.ok(edits.every(edit => edit.kind === 'nudge'));
|
||||
});
|
||||
|
||||
test('summarizeEdit renders a readable, markup-free line per kind', () => {
|
||||
const lines = [
|
||||
feedback.summarizeEdit({ kind: 'text', selector: 'h1', tag: 'h1', snippet: 'Team plan', before: 'Team plan', after: 'Team plan+' }),
|
||||
feedback.summarizeEdit({ kind: 'resize', selector: 'img.art', tag: 'img', width: 220, height: 220, before: { width: 260, height: 260 } }),
|
||||
feedback.summarizeEdit({ kind: 'move', selector: 'button', from: { parent: 'div.a', index: 1 }, to: { parent: 'div.b', index: 0 } }),
|
||||
feedback.summarizeEdit({ kind: 'nudge', selector: 'p', dx: 3, dy: -2 }),
|
||||
feedback.summarizeEdit({ kind: 'remove', selector: 'button.secondary', tag: 'button', stale: true }),
|
||||
feedback.summarizeEdit({ kind: 'style', selector: '#card', property: 'border', before: '2px solid', after: null }),
|
||||
feedback.summarizeEdit({ kind: 'style', selector: '#card', property: 'background-color', before: 'white', after: '#333' })
|
||||
];
|
||||
assert.match(lines[0], /text of h1 <h1> "Team plan": "Team plan" → "Team plan\+"/);
|
||||
assert.match(lines[1], /resized img\.art <img> to 220px wide, 220px tall \(was 260×260\)/);
|
||||
assert.match(lines[2], /moved button from div\.a\[1\] to div\.b\[0\]/);
|
||||
assert.match(lines[3], /nudged p by 3px, -2px/);
|
||||
assert.match(lines[4], /removed button\.secondary <button> \(could not be re-applied/);
|
||||
assert.match(lines[5], /removed border from #card \(was 2px solid\)/);
|
||||
assert.match(lines[6], /set background-color on #card to #333/);
|
||||
assert.strictEqual(feedback.summarizeEdit(null), '');
|
||||
assert.ok(lines.every(line => !line.includes('<div')));
|
||||
});
|
||||
|
||||
test('normalizeUiFeedbackItem: chat needs text, keeps anchor and edit summaries', () => {
|
||||
assert.strictEqual(feedback.normalizeUiFeedbackItem({ kind: 'chat', text: ' ' }, 1), null);
|
||||
assert.strictEqual(feedback.normalizeUiFeedbackItem({ kind: 'verdict', verdict: 'approve' }, 1), null);
|
||||
const item = feedback.normalizeUiFeedbackItem({
|
||||
kind: 'chat',
|
||||
text: 'make it gray',
|
||||
anchor: { selector: '#card', tag: 'article', snippet: 'Team plan', size: { width: 720.4, height: 361 } },
|
||||
pendingEdits: ['resized img', { kind: 'remove', selector: 'button.x', tag: 'button' }, 42]
|
||||
}, 7);
|
||||
assert.strictEqual(item.id, 'fb-7');
|
||||
assert.deepStrictEqual(item.anchor, { selector: '#card', tag: 'article', snippet: 'Team plan', size: { width: 720, height: 361 } });
|
||||
assert.deepStrictEqual(item.pendingEdits, ['resized img', 'removed button.x <button>']);
|
||||
const bare = feedback.normalizeUiFeedbackItem({ kind: 'chat', text: 'hi', anchor: { selector: 7 } }, 8);
|
||||
assert.strictEqual(bare.anchor, undefined);
|
||||
});
|
||||
|
||||
test('normalizeUiFeedbackItem: edits and finish normalize edits, viewport, and export paths', () => {
|
||||
const item = feedback.normalizeUiFeedbackItem({
|
||||
kind: 'finish',
|
||||
text: 'ship it',
|
||||
edits: [{ kind: 'resize', selector: 'img', width: 100 }, { kind: 'nope', selector: 'x' }],
|
||||
viewport: { preset: 'tablet', width: 'wide', height: 900 },
|
||||
exportPath: '/tmp/a.edited.html',
|
||||
editsPath: '/tmp/a.edits.json',
|
||||
html: '<html></html>'
|
||||
}, 2);
|
||||
assert.strictEqual(item.kind, 'finish');
|
||||
assert.strictEqual(item.editCount, 1);
|
||||
assert.deepStrictEqual(item.viewport, { preset: 'custom', width: feedback.VIEWPORT_PRESETS.custom.width, height: 900 });
|
||||
assert.strictEqual(item.exportPath, '/tmp/a.edited.html');
|
||||
assert.strictEqual(item.html, undefined, 'html never rides along with the queued item');
|
||||
const applied = feedback.normalizeUiFeedbackItem({ kind: 'edits', edits: 'not-an-array' }, 3);
|
||||
assert.strictEqual(applied.editCount, 0);
|
||||
assert.strictEqual(applied.viewport, undefined);
|
||||
});
|
||||
|
||||
test('normalizeViewport honours presets and falls back per dimension', () => {
|
||||
assert.deepStrictEqual(feedback.normalizeViewport({ preset: 'mobile' }), { preset: 'mobile', width: 393, height: 852 });
|
||||
assert.deepStrictEqual(feedback.normalizeViewport({ preset: 'custom', width: 1024, height: 0 }), { preset: 'custom', width: 1024, height: 800 });
|
||||
assert.strictEqual(feedback.normalizeViewport('mobile'), null);
|
||||
});
|
||||
|
||||
test('uiChatLineFor describes each kind for the transcript', () => {
|
||||
assert.strictEqual(feedback.uiChatLineFor({ kind: 'finish', editCount: 1 }), 'Saved and finished with 1 edit');
|
||||
assert.strictEqual(feedback.uiChatLineFor({ kind: 'finish', editCount: 3, text: 'ship' }), 'Saved and finished with 3 edits: ship');
|
||||
assert.strictEqual(feedback.uiChatLineFor({ kind: 'edits', editCount: 0 }), 'Applied 0 edits to the preview');
|
||||
assert.strictEqual(feedback.uiChatLineFor({ kind: 'chat', text: 'hi', anchor: { selector: '#a', snippet: 'Title' } }), '[Title] hi');
|
||||
assert.strictEqual(feedback.uiChatLineFor({ kind: 'chat', text: 'hi' }), 'hi');
|
||||
});
|
||||
|
||||
test('exportPathsFor keeps the artifact extension and sits beside it', () => {
|
||||
const paths = feedback.exportPathsFor('/work/previews/card.html');
|
||||
assert.strictEqual(paths.exportPath, path.join('/work/previews', 'card.edited.html'));
|
||||
assert.strictEqual(paths.editsPath, path.join('/work/previews', 'card.edits.json'));
|
||||
assert.strictEqual(feedback.exportPathsFor('/work/card').exportPath, path.join('/work', 'card.edited.html'));
|
||||
});
|
||||
|
||||
test('writeExport writes markup and edit log atomically and rejects bad snapshots', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uc-feedback-'));
|
||||
try {
|
||||
const artifact = path.join(dir, 'card.html');
|
||||
fs.writeFileSync(artifact, '<html></html>');
|
||||
const written = feedback.writeExport(artifact, {
|
||||
html: '<!DOCTYPE html>\n<html><body>x</body></html>\n',
|
||||
edits: [{ kind: 'remove', selector: 'b' }],
|
||||
viewport: { preset: 'mobile', width: 393, height: 852 },
|
||||
kind: 'finish'
|
||||
});
|
||||
assert.strictEqual(fs.readFileSync(written.exportPath, 'utf8'), '<!DOCTYPE html>\n<html><body>x</body></html>\n');
|
||||
const log = JSON.parse(fs.readFileSync(written.editsPath, 'utf8'));
|
||||
assert.strictEqual(log.kind, 'finish');
|
||||
assert.strictEqual(log.artifact, artifact);
|
||||
assert.strictEqual(log.edits.length, 1);
|
||||
assert.deepStrictEqual(log.viewport, { preset: 'mobile', width: 393, height: 852 });
|
||||
assert.ok(!fs.readdirSync(dir).some(name => name.includes('.tmp-')), 'no temp files left behind');
|
||||
assert.throws(() => feedback.writeExport(artifact, { html: '' }), /code: 'EUI_HTML_MISSING'|html snapshot is required/);
|
||||
assert.throws(() => feedback.writeExport(artifact, { html: 'x'.repeat(feedback.MAX_HTML_BYTES + 1) }), /exceeds/);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* Tests for the UI Canvas inspector field helpers
|
||||
* (scripts/lib/ui-canvas/fields.js): typed-value sanitization, color
|
||||
* parsing and conversion, and the inlined browser source.
|
||||
*
|
||||
* Run with: node tests/lib/ui-canvas-fields.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const vm = require('vm');
|
||||
|
||||
const fields = require('../../scripts/lib/ui-canvas/fields');
|
||||
const {
|
||||
FIELD_HELPERS_JS,
|
||||
clampNumber,
|
||||
colorHex,
|
||||
formatColor,
|
||||
formatNumber,
|
||||
hslToRgb,
|
||||
parseColor,
|
||||
rgbToHsl,
|
||||
roundToStep,
|
||||
sanitizeBoxList,
|
||||
sanitizeCssText,
|
||||
sanitizeNumber
|
||||
} = fields;
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` PASS ${name}`);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.log(` FAIL ${name}\n ${error.stack || error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const PX = { unit: 'px', units: ['px', 'rem', 'em', '%'], min: 0, max: 999, step: 1 };
|
||||
|
||||
console.log('ui-canvas field helpers');
|
||||
|
||||
test('numbers clamp, round to step and format without trailing zeros', () => {
|
||||
assert.strictEqual(clampNumber(5, 0, 3), 3);
|
||||
assert.strictEqual(clampNumber(-1, 0, 3), 0);
|
||||
assert.strictEqual(roundToStep(1.234, 0.05), 1.25);
|
||||
assert.strictEqual(roundToStep(7.6, 1), 8);
|
||||
assert.strictEqual(roundToStep(7.6, 0), 7.6);
|
||||
assert.strictEqual(formatNumber(1.81818), '1.82');
|
||||
assert.strictEqual(formatNumber(16), '16');
|
||||
assert.strictEqual(formatNumber(NaN), '');
|
||||
});
|
||||
|
||||
test('sanitizeNumber accepts plain numbers, units and spacing', () => {
|
||||
assert.deepStrictEqual(sanitizeNumber('16', PX), { ok: true, value: 16, unit: 'px', css: '16px' });
|
||||
assert.strictEqual(sanitizeNumber(' 1.5 rem ', { ...PX, step: 0.1 }).css, '1.5rem');
|
||||
assert.strictEqual(sanitizeNumber('12PX', PX).css, '12px');
|
||||
assert.strictEqual(sanitizeNumber('2,5', { ...PX, step: 0.5 }).css, '2.5px', 'comma decimal');
|
||||
assert.strictEqual(sanitizeNumber('.5', { unit: '', units: [''], step: 0.1 }).css, '0.5');
|
||||
assert.strictEqual(sanitizeNumber(7, { unit: '', units: [''] }).css, '7', 'missing min/max/step means unbounded');
|
||||
});
|
||||
|
||||
test('sanitizeNumber clamps out-of-range values instead of rejecting them', () => {
|
||||
assert.strictEqual(sanitizeNumber('5000', PX).value, 999);
|
||||
assert.strictEqual(sanitizeNumber('-4', PX).value, 0);
|
||||
});
|
||||
|
||||
test('sanitizeNumber rejects junk and unknown units with a readable error', () => {
|
||||
assert.deepStrictEqual(sanitizeNumber('', PX), { ok: false, error: 'Enter a number' });
|
||||
assert.strictEqual(sanitizeNumber(null, PX).ok, false);
|
||||
assert.strictEqual(sanitizeNumber('abc', PX).error, 'Not a number');
|
||||
assert.strictEqual(sanitizeNumber('12px;color:red', PX).ok, false);
|
||||
assert.strictEqual(sanitizeNumber('1e999', PX).ok, false);
|
||||
assert.strictEqual(sanitizeNumber('12vw', PX).error, 'Use px, rem, em, %');
|
||||
assert.strictEqual(sanitizeNumber('3px', { unit: '', units: [''] }).error, 'Use a plain number');
|
||||
});
|
||||
|
||||
test('ratio fields take 50, 50% or 0.5 and land on 0..1', () => {
|
||||
const ratio = { ratio: true, min: 0, max: 1, step: 0.01 };
|
||||
assert.strictEqual(sanitizeNumber('50', ratio).value, 0.5);
|
||||
assert.strictEqual(sanitizeNumber('50%', ratio).value, 0.5);
|
||||
assert.strictEqual(sanitizeNumber('0.5', ratio).value, 0.5);
|
||||
assert.strictEqual(sanitizeNumber('1', ratio).value, 1);
|
||||
assert.strictEqual(sanitizeNumber('250%', ratio).value, 1);
|
||||
assert.strictEqual(sanitizeNumber('0.5px', ratio).ok, false);
|
||||
});
|
||||
|
||||
test('sanitizeBoxList handles 1 to 4 sides, auto and part limits', () => {
|
||||
assert.deepStrictEqual(sanitizeBoxList('8 16', PX), { ok: true, css: '8px 16px' });
|
||||
assert.strictEqual(sanitizeBoxList('0 auto', { ...PX, allowAuto: true }).css, '0 auto');
|
||||
assert.strictEqual(sanitizeBoxList('1,2,3,4', PX).css, '1px 2px 3px 4px');
|
||||
assert.strictEqual(sanitizeBoxList('0 auto', PX).ok, false, 'auto only where allowed');
|
||||
assert.strictEqual(sanitizeBoxList('1 2 3', { ...PX, maxParts: 2 }).error, 'Use at most 2 values');
|
||||
assert.strictEqual(sanitizeBoxList(' ', PX).error, 'Enter a value');
|
||||
assert.strictEqual(sanitizeBoxList(undefined, PX).ok, false);
|
||||
});
|
||||
|
||||
test('parseColor reads hex, rgb(), rgba(), space syntax and transparent', () => {
|
||||
assert.deepStrictEqual(parseColor('#16a34a'), { r: 22, g: 163, b: 74, a: 1 });
|
||||
assert.deepStrictEqual(parseColor('fff'), { r: 255, g: 255, b: 255, a: 1 });
|
||||
assert.deepStrictEqual(parseColor('#0008'), { r: 0, g: 0, b: 0, a: 0.533 });
|
||||
assert.deepStrictEqual(parseColor('#00000080'), { r: 0, g: 0, b: 0, a: 0.502 });
|
||||
assert.deepStrictEqual(parseColor('rgb(22, 163, 74)'), { r: 22, g: 163, b: 74, a: 1 });
|
||||
assert.deepStrictEqual(parseColor('rgba(22, 163, 74, 0.12)'), { r: 22, g: 163, b: 74, a: 0.12 });
|
||||
assert.deepStrictEqual(parseColor('rgb(100% 0% 0% / 50%)'), { r: 255, g: 0, b: 0, a: 0.5 });
|
||||
assert.deepStrictEqual(parseColor('transparent'), { r: 0, g: 0, b: 0, a: 0 });
|
||||
assert.deepStrictEqual(parseColor('rgba(300, -5, 0, 4)'), { r: 255, g: 0, b: 0, a: 1 }, 'channels clamp');
|
||||
});
|
||||
|
||||
test('parseColor rejects anything it cannot read', () => {
|
||||
for (const bad of ['', null, 'red', '#12', '#12345', 'rgb(1,2)', 'rgb(a,b,c)', 'rgb(1,2,3,4,5)', 'hsl(0,0%,0%)']) {
|
||||
assert.strictEqual(parseColor(bad), null, String(bad));
|
||||
}
|
||||
});
|
||||
|
||||
test('formatColor and colorHex round-trip opaque and translucent colors', () => {
|
||||
assert.strictEqual(formatColor({ r: 22, g: 163, b: 74, a: 1 }), '#16a34a');
|
||||
assert.strictEqual(formatColor({ r: 22, g: 163, b: 74, a: 0.5 }), 'rgba(22, 163, 74, 0.5)');
|
||||
assert.strictEqual(colorHex({ r: 22, g: 163, b: 74, a: 0.2 }), '#16A34A');
|
||||
assert.deepStrictEqual(parseColor(formatColor({ r: 1, g: 2, b: 3, a: 0.25 })), { r: 1, g: 2, b: 3, a: 0.25 });
|
||||
});
|
||||
|
||||
test('rgbToHsl and hslToRgb convert both ways, including grays', () => {
|
||||
assert.deepStrictEqual(rgbToHsl({ r: 255, g: 0, b: 0, a: 1 }), { h: 0, s: 100, l: 50, a: 1 });
|
||||
assert.deepStrictEqual(rgbToHsl({ r: 0, g: 255, b: 0, a: 1 }), { h: 120, s: 100, l: 50, a: 1 });
|
||||
assert.deepStrictEqual(rgbToHsl({ r: 0, g: 0, b: 255, a: 1 }), { h: 240, s: 100, l: 50, a: 1 });
|
||||
assert.deepStrictEqual(rgbToHsl({ r: 128, g: 128, b: 128, a: 0.5 }), { h: 0, s: 0, l: 50, a: 0.5 });
|
||||
assert.deepStrictEqual(rgbToHsl({ r: 200, g: 230, b: 210, a: 1 }).s > 0, true);
|
||||
assert.deepStrictEqual(hslToRgb({ h: 0, s: 0, l: 50, a: 1 }), { r: 128, g: 128, b: 128, a: 1 });
|
||||
assert.deepStrictEqual(hslToRgb({ h: -120, s: 100, l: 50, a: 1 }), { r: 0, g: 0, b: 255, a: 1 }, 'negative hue wraps');
|
||||
for (const color of [{ r: 22, g: 163, b: 74, a: 1 }, { r: 236, g: 168, b: 90, a: 1 }, { r: 74, g: 203, b: 190, a: 1 }]) {
|
||||
const back = hslToRgb(rgbToHsl(color));
|
||||
for (const k of ['r', 'g', 'b']) assert.ok(Math.abs(back[k] - color[k]) <= 3, k + ' drift ' + back[k] + ' vs ' + color[k]);
|
||||
}
|
||||
});
|
||||
|
||||
test('sanitizeCssText keeps valid CSS and blocks rule breakers', () => {
|
||||
assert.deepStrictEqual(sanitizeCssText(' 0 1px 2px rgba(0,0,0,.2) '), { ok: true, css: '0 1px 2px rgba(0,0,0,.2)' });
|
||||
assert.strictEqual(sanitizeCssText('').error, 'Enter a value');
|
||||
assert.strictEqual(sanitizeCssText(null).ok, false);
|
||||
assert.strictEqual(sanitizeCssText('x'.repeat(301)).error, 'Too long');
|
||||
assert.strictEqual(sanitizeCssText('red', 2).error, 'Too long');
|
||||
for (const bad of ['red; display:none', 'none}body{x:y', '<b>', 'red /* c */', 'red !important', 'expression(alert(1))', 'url(javascript:alert(1))', 'a\\62 c']) {
|
||||
assert.strictEqual(sanitizeCssText(bad).ok, false, bad);
|
||||
}
|
||||
});
|
||||
|
||||
test('inlined helper source runs standalone and matches the module', () => {
|
||||
const sandbox = {};
|
||||
vm.runInNewContext(FIELD_HELPERS_JS + '\nthis.out = { n: sanitizeNumber("1.5rem", { unit: "px", units: ["px", "rem"], step: 0.1 }), c: formatColor(hslToRgb(rgbToHsl(parseColor("#16a34a")))), b: sanitizeBoxList("4 8", { unit: "px", units: ["px"] }).css, t: sanitizeCssText("a;b").ok };', sandbox);
|
||||
assert.deepStrictEqual(JSON.parse(JSON.stringify(sandbox.out)), {
|
||||
n: sanitizeNumber('1.5rem', { unit: 'px', units: ['px', 'rem'], step: 0.1 }),
|
||||
c: formatColor(hslToRgb(rgbToHsl(parseColor('#16a34a')))),
|
||||
b: '4px 8px',
|
||||
t: false
|
||||
});
|
||||
assert.ok(!/require\(|module\.exports/.test(FIELD_HELPERS_JS), 'helpers stay self-contained');
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Tests for the UI Canvas browser shell and in-page editor sources
|
||||
* (scripts/lib/ui-canvas/ui.js, scripts/lib/ui-canvas/editor.js).
|
||||
*
|
||||
* The browser code ships as strings, so these tests compile them with the
|
||||
* V8 parser, check the shell/editor message contract stays in sync, and
|
||||
* make sure the rendered shell carries every element the client binds to.
|
||||
*
|
||||
* Run with: node tests/lib/ui-canvas-ui.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const vm = require('vm');
|
||||
|
||||
const { ICONS, renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('../../scripts/lib/ui-canvas/ui');
|
||||
const { uiEditorJs } = require('../../scripts/lib/ui-canvas/editor');
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` PASS ${name}`);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
console.log(` FAIL ${name}\n ${error.stack || error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function messageNames(source, direction) {
|
||||
// direction 'post' finds messages a script sends; 'case' finds ones it handles.
|
||||
const pattern = direction === 'post'
|
||||
? /post(?:ToFrame)?\(\{\s*type:\s*'(uc:[a-z-]+)'/g
|
||||
: /case '(uc:[a-z-]+)'/g;
|
||||
return new Set([...source.matchAll(pattern)].map(match => match[1]));
|
||||
}
|
||||
|
||||
console.log('ui-canvas shell + editor');
|
||||
|
||||
test('editor and client scripts parse as JavaScript', () => {
|
||||
assert.doesNotThrow(() => new vm.Script(uiEditorJs(), { filename: 'ui-editor.js' }));
|
||||
assert.doesNotThrow(() => new vm.Script(uiClientJs(), { filename: 'ui-client.js' }));
|
||||
});
|
||||
|
||||
test('editor only talks to the shell through uc:* messages it declares', () => {
|
||||
const editor = uiEditorJs();
|
||||
const client = uiClientJs();
|
||||
const editorPosts = messageNames(editor, 'post');
|
||||
const clientHandles = messageNames(client, 'case');
|
||||
for (const name of editorPosts) {
|
||||
if (name === 'uc:viewport') continue; // informational; the shell measures the stage itself
|
||||
assert.ok(clientHandles.has(name), `shell does not handle ${name}`);
|
||||
}
|
||||
const clientPosts = messageNames(client, 'post');
|
||||
const editorHandles = messageNames(editor, 'case');
|
||||
for (const name of clientPosts) assert.ok(editorHandles.has(name), `editor does not handle ${name}`);
|
||||
assert.ok(editorHandles.has('uc:restore') && editorHandles.has('uc:export') && editorHandles.has('uc:forget'));
|
||||
});
|
||||
|
||||
test('editor never selects or exports its own overlay', () => {
|
||||
const editor = uiEditorJs();
|
||||
assert.ok(editor.includes("setAttribute('data-ecc-ui-canvas', 'overlay')"));
|
||||
assert.ok(editor.includes('[data-ecc-ui-canvas],[data-ecc-plan-canvas]'), 'export strips injected nodes');
|
||||
assert.ok(editor.includes('if (window.parent === window) return;'));
|
||||
assert.ok(editor.includes('attachShadow'));
|
||||
});
|
||||
|
||||
test('rendered shell contains every element the client binds and escapes the bootstrap', () => {
|
||||
const session = {
|
||||
key: 'abcdefabcdef',
|
||||
file: '/tmp/demo/<card>.html',
|
||||
status: 'open',
|
||||
chat: [{ role: 'user', kind: 'chat', text: '</script><script>alert(1)</script>', at: '2026-01-01T00:00:00.000Z' }],
|
||||
ui: { viewport: 'mobile', title: 'Card & co' },
|
||||
agent: { name: 'Claude Code', project: 'demo' }
|
||||
};
|
||||
const html = renderUiCanvasHtml(session);
|
||||
const client = uiClientJs();
|
||||
const ids = new Set([...client.matchAll(/\$\('([A-Za-z]+)'\)/g)].map(match => match[1]));
|
||||
assert.ok(ids.size > 20, 'client binds many ids');
|
||||
for (const id of ids) assert.ok(html.includes(`id="${id}"`), `shell is missing #${id}`);
|
||||
assert.ok(!html.includes('</script><script>alert(1)'), 'bootstrap JSON must escape <');
|
||||
assert.ok(html.includes('\\u003c/script>'));
|
||||
assert.ok(html.includes('Card & co · UI Canvas'));
|
||||
assert.ok(html.includes('sandbox="allow-scripts allow-forms allow-popups"'), 'iframe stays sandboxed without same-origin');
|
||||
assert.ok(html.includes('data-vp="mobile"') && html.includes('data-vp="desktop"') && html.includes('data-vp="custom"'));
|
||||
assert.ok(html.includes(ICONS.mobile) && html.includes(ICONS.desktop) && html.includes(ICONS.custom));
|
||||
assert.ok(html.includes('Save and Finish'));
|
||||
});
|
||||
|
||||
test('shell falls back to the file name when no title is set', () => {
|
||||
const html = renderUiCanvasHtml({ key: 'abcdefabcdef', file: '/tmp/sidebar.html', status: 'open', chat: [] });
|
||||
assert.ok(html.includes('<title>sidebar.html · UI Canvas</title>'));
|
||||
assert.ok(html.includes('"ui":{"viewport":"desktop","title":""}'));
|
||||
});
|
||||
|
||||
test('shell css carries the shared ECC tokens and the device frame styles', () => {
|
||||
const css = uiCanvasCss();
|
||||
assert.ok(css.includes('--bg:#080a0e'), 'shares the Plan Canvas and dashboard tokens');
|
||||
assert.ok(css.includes('.device.mobile'));
|
||||
assert.ok(css.includes('.presence[data-state="listening"]'));
|
||||
assert.ok(css.includes('.range::-webkit-slider-thumb') && css.includes('.numedit.invalid'), 'slider rows and typed values are styled');
|
||||
});
|
||||
|
||||
test('ui canvas chrome is ECC green with no decorative gradients', () => {
|
||||
const css = uiCanvasCss();
|
||||
assert.ok(css.includes(':root{--accent:#4acb8a'), 'accent overrides the shared blue');
|
||||
const rule = selector => {
|
||||
const start = css.indexOf('\n ' + selector + '{');
|
||||
return start < 0 ? '' : css.slice(start, css.indexOf('}', start) + 1);
|
||||
};
|
||||
for (const selector of ['.brand .logo', '.primary', '.composer .send']) {
|
||||
assert.ok(rule(selector), selector + ' rule exists');
|
||||
assert.ok(!/gradient/.test(rule(selector)), selector + ' must not use a gradient');
|
||||
}
|
||||
const editor = uiEditorJs();
|
||||
assert.ok(editor.includes("var ACCENT = '#22c55e'"), 'selection overlay is green');
|
||||
assert.ok(!/#6885e8|104,133,232|#8fa4f0/i.test(editor), 'no leftover blue in the overlay');
|
||||
});
|
||||
|
||||
test('inspector inlines the tested field helpers and drops the old chip strip', () => {
|
||||
const client = uiClientJs();
|
||||
for (const name of ['sanitizeNumber', 'sanitizeBoxList', 'parseColor', 'hslToRgb', 'sanitizeCssText']) {
|
||||
assert.ok(client.includes('function ' + name + '('), name + ' is inlined');
|
||||
}
|
||||
assert.ok(!client.includes('${FIELD_HELPERS_JS}'), 'helpers are interpolated, not left as a placeholder');
|
||||
assert.ok(!client.includes('selectedChip') && !client.includes("type = 'color'"), 'native color input and chips are gone');
|
||||
const html = renderUiCanvasHtml({ key: 'abcdefabcdef', file: '/tmp/x.html', status: 'open', chat: [] });
|
||||
assert.ok(html.includes('id="vpW" type="text" inputmode="numeric"'), 'viewport width is a sanitized text field');
|
||||
assert.ok(!html.includes('type="number"'), 'no browser number spinners remain');
|
||||
});
|
||||
|
||||
test('theme toggle keeps its icons instead of overwriting them with text', () => {
|
||||
const client = uiClientJs();
|
||||
assert.ok(!client.includes("$('themeBtn').textContent"), 'textContent would wipe the sun and moon icons');
|
||||
assert.ok(client.includes("$('themeBtn').setAttribute('aria-label', label)"));
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
@@ -95,6 +95,7 @@ function buildExpectedPublishPaths(repoRoot) {
|
||||
"scripts/nasiko.js",
|
||||
"scripts/observability-readiness.js",
|
||||
"scripts/plan-canvas.js",
|
||||
"scripts/ui-canvas.js",
|
||||
"scripts/operator-readiness-dashboard.js",
|
||||
"scripts/platform-audit.js",
|
||||
"scripts/preview-pack-smoke.js",
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Integration tests for UI Canvas sessions on the shared canvas server
|
||||
* (scripts/lib/plan-canvas/server.js in `ui` mode, scripts/lib/ui-canvas/).
|
||||
*
|
||||
* Spins up the real HTTP server in-process and drives it the way the shell
|
||||
* (fetch + SSE) and the agent CLI (long poll) do.
|
||||
*
|
||||
* Run with: node tests/scripts/ui-canvas.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { createSessionStore, sanitizeUiOptions } = require('../../scripts/lib/plan-canvas/sessions');
|
||||
const { createPlanCanvasServer } = require('../../scripts/lib/plan-canvas/server');
|
||||
const pendingHook = require('../../scripts/hooks/plan-canvas-pending');
|
||||
const sessionsHook = require('../../scripts/hooks/plan-canvas-sessions');
|
||||
|
||||
const results = [];
|
||||
async function test(name, fn) {
|
||||
try {
|
||||
await fn();
|
||||
console.log(` PASS ${name}`);
|
||||
results.push(true);
|
||||
} catch (error) {
|
||||
console.log(` FAIL ${name}\n ${error.stack || error.message}`);
|
||||
results.push(false);
|
||||
}
|
||||
}
|
||||
|
||||
function request(port, method, requestPath, body = null, { raw = false, headers = {} } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const payload = body === null ? null : JSON.stringify(body);
|
||||
const req = http.request(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
method,
|
||||
path: requestPath,
|
||||
headers: payload
|
||||
? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload), ...headers }
|
||||
: headers
|
||||
},
|
||||
res => {
|
||||
let data = '';
|
||||
res.on('data', chunk => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
let parsed = data;
|
||||
if (!raw) {
|
||||
try { parsed = JSON.parse(data.trim() || '{}'); } catch { parsed = data; }
|
||||
}
|
||||
resolve({ statusCode: res.statusCode, headers: res.headers, body: parsed });
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on('error', reject);
|
||||
if (payload) req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// Open an SSE stream and resolve with the first `presence` frame.
|
||||
function firstPresence(port, key) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.get({ host: '127.0.0.1', port, path: `/events/${key}` }, res => {
|
||||
let buffer = '';
|
||||
res.on('data', chunk => {
|
||||
buffer += chunk;
|
||||
const match = buffer.match(/event: presence\ndata: (.*)\n/);
|
||||
if (match) {
|
||||
req.destroy();
|
||||
resolve(JSON.parse(match[1]));
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', error => (error.code === 'ECONNRESET' ? null : reject(error)));
|
||||
setTimeout(() => { req.destroy(); reject(new Error('no presence frame')); }, 3000).unref();
|
||||
});
|
||||
}
|
||||
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
async function main() {
|
||||
console.log('ui-canvas server');
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ui-canvas-test-'));
|
||||
const artifact = path.join(tmp, 'card.html');
|
||||
fs.writeFileSync(artifact, '<!DOCTYPE html><html><head><title>Card</title></head><body><article id="card"><h1>Hi</h1><button class="x">Go</button></article></body></html>');
|
||||
const store = createSessionStore({ stateDir: path.join(tmp, 'state') });
|
||||
const canvas = createPlanCanvasServer({ store, version: '9.9.9-test' });
|
||||
const { port } = await canvas.listen(0);
|
||||
let key = null;
|
||||
|
||||
try {
|
||||
await test('POST /api/sessions opens a ui session with viewport options', async () => {
|
||||
const res = await request(port, 'POST', '/api/sessions', { file: artifact, mode: 'ui', ui: { viewport: '1024x768', title: 'Card' } });
|
||||
assert.strictEqual(res.statusCode, 200);
|
||||
assert.strictEqual(res.body.mode, 'ui');
|
||||
key = res.body.key;
|
||||
const session = store.get(key);
|
||||
assert.deepStrictEqual(session.ui, { viewport: '1024x768', title: 'Card' });
|
||||
});
|
||||
|
||||
await test('ui sessions refuse non-HTML artifacts', async () => {
|
||||
const plan = path.join(tmp, 'plan.md');
|
||||
fs.writeFileSync(plan, '# plan');
|
||||
const res = await request(port, 'POST', '/api/sessions', { file: plan, mode: 'ui' });
|
||||
assert.strictEqual(res.statusCode, 400);
|
||||
assert.match(res.body.error, /\.html/);
|
||||
});
|
||||
|
||||
await test('GET /canvas/:key renders the UI Canvas shell for ui sessions', async () => {
|
||||
const res = await request(port, 'GET', `/canvas/${key}`, null, { raw: true });
|
||||
assert.strictEqual(res.statusCode, 200);
|
||||
assert.ok(res.body.includes('UI Canvas'));
|
||||
assert.ok(res.body.includes('/ui-client.js'));
|
||||
assert.ok(!res.body.includes('Approve plan'));
|
||||
});
|
||||
|
||||
await test('GET /artifact/:key/ injects the editor instead of the annotation sdk and keeps the sandbox CSP', async () => {
|
||||
const res = await request(port, 'GET', `/artifact/${key}/`, null, { raw: true });
|
||||
assert.strictEqual(res.statusCode, 200);
|
||||
assert.ok(res.body.includes('<script src="/ui-editor.js" data-ecc-ui-canvas="editor"></script>'));
|
||||
assert.ok(!res.body.includes('/sdk.js'));
|
||||
assert.strictEqual(res.headers['content-security-policy'], 'sandbox allow-scripts allow-forms allow-popups');
|
||||
});
|
||||
|
||||
await test('shell assets are served inline with no-store caching', async () => {
|
||||
for (const [assetPath, type, marker] of [
|
||||
['/ui-editor.js', 'text/javascript', '__eccUiCanvasEditor'],
|
||||
['/ui-client.js', 'text/javascript', 'uc:restore'],
|
||||
['/ui-canvas.css', 'text/css', '.device.mobile']
|
||||
]) {
|
||||
const res = await request(port, 'GET', assetPath, null, { raw: true });
|
||||
assert.strictEqual(res.statusCode, 200, assetPath);
|
||||
assert.ok(res.headers['content-type'].startsWith(type), assetPath);
|
||||
assert.strictEqual(res.headers['cache-control'], 'no-store');
|
||||
assert.ok(res.body.includes(marker), `${assetPath} lacks ${marker}`);
|
||||
}
|
||||
});
|
||||
|
||||
await test('await records the agent descriptor and presence names it', async () => {
|
||||
const agent = encodeURIComponent(JSON.stringify({ name: 'Claude Code', project: 'shop', junk: true }));
|
||||
const parked = request(port, 'GET', `/api/await?key=${key}&agent=${agent}`);
|
||||
await sleep(50);
|
||||
const presence = await firstPresence(port, key);
|
||||
assert.strictEqual(presence.state, 'listening');
|
||||
assert.deepStrictEqual({ name: presence.agent.name, project: presence.agent.project }, { name: 'Claude Code', project: 'shop' });
|
||||
assert.ok(presence.agent.seenAt);
|
||||
const listed = await request(port, 'GET', '/api/sessions');
|
||||
assert.strictEqual(listed.body.sessions[0].mode, 'ui');
|
||||
assert.strictEqual(listed.body.sessions[0].agent.name, 'Claude Code');
|
||||
|
||||
// A chat item with an anchor and pending-edit summaries reaches the parked await.
|
||||
const fb = await request(port, 'POST', `/api/session/${key}/feedback`, {
|
||||
items: [{ kind: 'chat', text: 'make it gray', anchor: { selector: '#card', tag: 'article', snippet: 'Hi Go' }, pendingEdits: ['resized h1'] }]
|
||||
});
|
||||
assert.strictEqual(fb.statusCode, 200);
|
||||
const delivered = await parked;
|
||||
assert.strictEqual(delivered.body.status, 'feedback');
|
||||
assert.strictEqual(delivered.body.items[0].anchor.selector, '#card');
|
||||
assert.deepStrictEqual(delivered.body.items[0].pendingEdits, ['resized h1']);
|
||||
assert.strictEqual(store.get(key).chat.at(-1).text, '[Hi Go] make it gray');
|
||||
});
|
||||
|
||||
await test('a plain agent name in the await query still names the agent', async () => {
|
||||
const parked = request(port, 'GET', `/api/await?key=${key}&agent=Codex&timeoutMs=50`);
|
||||
await parked;
|
||||
assert.strictEqual(store.get(key).agent.name, 'Codex');
|
||||
});
|
||||
|
||||
await test('edits batches write the export beside the artifact and strip html from the queue', async () => {
|
||||
const parked = request(port, 'GET', `/api/await?key=${key}`);
|
||||
await sleep(30);
|
||||
const html = '<!DOCTYPE html>\n<html><body><article id="card" style="border:none"><h1 style="width:300px">Hi</h1></article></body></html>\n';
|
||||
const fb = await request(port, 'POST', `/api/session/${key}/feedback`, {
|
||||
items: [{
|
||||
kind: 'edits',
|
||||
html,
|
||||
viewport: { preset: 'mobile', width: 393, height: 852 },
|
||||
edits: [
|
||||
{ kind: 'resize', selector: 'h1', tag: 'h1', width: 300, before: { width: 200, height: 40 } },
|
||||
{ kind: 'remove', selector: 'button.x', tag: 'button', outerHTML: '<button class="x">Go</button>', from: { parent: '#card', index: 1 } },
|
||||
{ kind: 'nonsense', selector: 'z' }
|
||||
]
|
||||
}]
|
||||
});
|
||||
assert.strictEqual(fb.statusCode, 200);
|
||||
const delivered = await parked;
|
||||
const item = delivered.body.items[0];
|
||||
assert.strictEqual(item.kind, 'edits');
|
||||
assert.strictEqual(item.editCount, 2);
|
||||
assert.ok(!('html' in item), 'html must not travel with the item');
|
||||
// The session file is canonicalized (realpath), so the export sits beside the real path.
|
||||
assert.strictEqual(item.exportPath, path.join(fs.realpathSync(tmp), 'card.edited.html'));
|
||||
assert.strictEqual(item.editsPath, path.join(fs.realpathSync(tmp), 'card.edits.json'));
|
||||
assert.strictEqual(fs.readFileSync(item.exportPath, 'utf8'), html);
|
||||
const log = JSON.parse(fs.readFileSync(item.editsPath, 'utf8'));
|
||||
assert.strictEqual(log.kind, 'edits');
|
||||
assert.strictEqual(log.edits.length, 2);
|
||||
assert.deepStrictEqual(log.viewport, { preset: 'mobile', width: 393, height: 852 });
|
||||
assert.ok(!JSON.stringify(JSON.parse(fs.readFileSync(store.stateFile, 'utf8'))).includes('<article'), 'sessions.json never stores markup');
|
||||
assert.strictEqual(store.get(key).chat.at(-1).text, 'Applied 2 edits to the preview');
|
||||
});
|
||||
|
||||
await test('edits batches without a snapshot or with an oversized one are refused', async () => {
|
||||
const missing = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', edits: [] }] });
|
||||
assert.strictEqual(missing.statusCode, 400);
|
||||
const huge = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', edits: [], html: 'x'.repeat(6 * 1024 * 1024 + 10) }] });
|
||||
assert.strictEqual(huge.statusCode, 413);
|
||||
assert.strictEqual(store.get(key).pendingFeedback.length, 0, 'nothing queued on refusal');
|
||||
});
|
||||
|
||||
await test('finish ends the session for the user and is delivered with export paths', async () => {
|
||||
const parked = request(port, 'GET', `/api/await?key=${key}`);
|
||||
await sleep(30);
|
||||
const fb = await request(port, 'POST', `/api/session/${key}/feedback`, {
|
||||
items: [{ kind: 'finish', text: 'ship it', html: '<!DOCTYPE html>\n<html><body>done</body></html>\n', edits: [{ kind: 'nudge', selector: 'h1', dx: 2, dy: 0 }], viewport: { preset: 'desktop', width: 1412, height: 806 } }],
|
||||
endSession: true
|
||||
});
|
||||
assert.strictEqual(fb.statusCode, 200);
|
||||
const delivered = await parked;
|
||||
assert.strictEqual(delivered.body.status, 'feedback');
|
||||
assert.strictEqual(delivered.body.sessionEnded, true);
|
||||
assert.strictEqual(delivered.body.endedBy, 'user');
|
||||
const item = delivered.body.items[0];
|
||||
assert.strictEqual(item.kind, 'finish');
|
||||
assert.strictEqual(item.text, 'ship it');
|
||||
assert.strictEqual(fs.readFileSync(item.exportPath, 'utf8').trim(), '<!DOCTYPE html>\n<html><body>done</body></html>');
|
||||
assert.strictEqual(store.get(key).status, 'ended');
|
||||
assert.strictEqual(store.get(key).chat.at(-1).text, 'Saved and finished with 1 edit: ship it');
|
||||
const again = await request(port, 'GET', `/api/await?key=${key}&timeoutMs=10`);
|
||||
assert.deepStrictEqual(again.body, { status: 'ended', endedBy: 'user' });
|
||||
});
|
||||
|
||||
await test('plan sessions still render Plan Canvas and reject ui-only kinds', async () => {
|
||||
const plan = path.join(tmp, 'notes.html');
|
||||
fs.writeFileSync(plan, '<html><body><p>plan</p></body></html>');
|
||||
const open = await request(port, 'POST', '/api/sessions', { file: plan });
|
||||
assert.strictEqual(open.body.mode, 'plan');
|
||||
const shell = await request(port, 'GET', `/canvas/${open.body.key}`, null, { raw: true });
|
||||
assert.ok(shell.body.includes('Approve plan'));
|
||||
const art = await request(port, 'GET', `/artifact/${open.body.key}/`, null, { raw: true });
|
||||
assert.ok(art.body.includes('/sdk.js') && !art.body.includes('/ui-editor.js'));
|
||||
const fb = await request(port, 'POST', `/api/session/${open.body.key}/feedback`, { items: [{ kind: 'finish', html: '<html></html>', edits: [] }] });
|
||||
assert.strictEqual(fb.body.accepted, 0, 'finish is not a plan-canvas kind');
|
||||
const list = await request(port, 'GET', '/', null, { raw: true });
|
||||
assert.ok(list.body.includes('ui canvas'), 'session list tags ui sessions');
|
||||
});
|
||||
|
||||
await test('sanitizeUiOptions keeps known presets and WxH, defaults otherwise', () => {
|
||||
assert.deepStrictEqual(sanitizeUiOptions({ viewport: 'mobile', title: ' Card ' }), { viewport: 'mobile', title: 'Card' });
|
||||
assert.deepStrictEqual(sanitizeUiOptions({ viewport: '800x600' }), { viewport: '800x600', title: '' });
|
||||
assert.deepStrictEqual(sanitizeUiOptions({ viewport: 'javascript:alert(1)' }, { viewport: 'custom', title: 'old' }), { viewport: 'custom', title: 'old' });
|
||||
assert.deepStrictEqual(sanitizeUiOptions(null), { viewport: 'desktop', title: '' });
|
||||
});
|
||||
|
||||
await test('Stop hook describes ui batches and points at the ui-canvas bin', () => {
|
||||
assert.strictEqual(
|
||||
pendingHook.describeItem({ kind: 'finish', editCount: 2, exportPath: '/p/card.edited.html', editsPath: '/p/card.edits.json' }),
|
||||
'SAVED AND FINISHED (2 edits) - final markup: /p/card.edited.html, edit log: /p/card.edits.json'
|
||||
);
|
||||
assert.strictEqual(pendingHook.describeItem({ kind: 'edits', edits: [{}], text: 'note' }), 'APPLIED EDITS TO THE PREVIEW (1 edit): note');
|
||||
assert.strictEqual(pendingHook.describeItem({ kind: 'chat', text: 'gray', anchor: { snippet: 'Card' } }), 'on "Card": gray');
|
||||
const reason = pendingHook.buildReason([{ file: '/p/card.html', mode: 'ui', messages: ['x'], sessionEnded: false }]);
|
||||
assert.match(reason, /^UI Canvas:/);
|
||||
assert.match(reason, /ecc-ui-canvas await "\/p\/card\.html" --reply/);
|
||||
const finished = pendingHook.buildReason([{ file: '/p/card.html', mode: 'ui', messages: ['x'], sessionEnded: true }]);
|
||||
assert.match(finished, /reproduce that exact design/);
|
||||
const mixed = pendingHook.buildReason([{ file: '/p/a.md', mode: 'plan', messages: ['x'], sessionEnded: false }, { file: '/p/card.html', mode: 'ui', messages: ['y'], sessionEnded: false }]);
|
||||
assert.match(mixed, /^Plan Canvas:/);
|
||||
assert.match(mixed, /ecc-plan-canvas await "\/p\/a\.md"/);
|
||||
});
|
||||
|
||||
await test('SessionStart hook tags ui sessions and names the ui-canvas resume command', () => {
|
||||
const context = sessionsHook.buildContext([
|
||||
{ file: '/p/plan.md', pendingFeedback: [] },
|
||||
{ file: '/p/card.html', mode: 'ui', pendingFeedback: [{}, {}] }
|
||||
]);
|
||||
assert.match(context, /\/p\/card\.html \[ui canvas\] \(2 undelivered feedback items\)/);
|
||||
assert.match(context, /node scripts\/ui-canvas\.js await <file>/);
|
||||
const planOnly = sessionsHook.buildContext([{ file: '/p/plan.md', pendingFeedback: [] }]);
|
||||
assert.ok(!planOnly.includes('ui-canvas'));
|
||||
});
|
||||
} finally {
|
||||
await canvas.close().catch(() => {});
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const passed = results.filter(Boolean).length;
|
||||
const failed = results.length - passed;
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
console.log('Passed: 0');
|
||||
console.log('Failed: 1');
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user