Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.27.3): deep agent hardening — comprehensive harness, 2 new skills, scroll-reset fix
Ashiq Hussain Mire15187727fa8
diff --git a/docs/AGENT-ARCHITECTURE.md b/docs/AGENT-ARCHITECTURE.mdindex 7a345a6..3499358 100644--- a/docs/AGENT-ARCHITECTURE.md+++ b/docs/AGENT-ARCHITECTURE.md@@ -86,15 +86,18 @@ src/components/editor/apps/AssistantApp.tsx rebuilt: streaming steps,session history, suggestion chips, brand-context note```-## Tool registry (v0.27 — 18 tools)+## Tool registry (v0.27.3 — 24 tools)read-only: `get_page_state` (re-serialized state after edits),-`list_templates`, `list_fonts`, `get_brand`-write: `add_text`, `add_shape`, `add_image`(stock/gen), `add_sticker`,-`add_table`, `add_chart`, `update_elements`, `set_text_style`,-`move_elements`, `align_elements`, `distribute_elements`, `set_background`,-`set_font`, `recolor`, `add_page`, `duplicate_page`, `apply_template`,-`fix_overlaps`, `balance_layout`, `animate_page`, `translate_texts`+`goto_page` (switch pages — element ids are per-page)+write: `add_text`, `add_shape`, `add_image` (AI generation),+`add_stock_photo` (licensed Pexels/Pixabay search via the existing+client rail — real photos with attribution), `add_sticker`,+`add_table`, `update_elements`, `set_text_style`,+`move_elements`, `align_elements`, `distribute_elements`,+`set_background`, `set_font`, `recolor`, `add_page`,+`duplicate_page`, `fix_overlaps`, `balance_layout`,+`animate_page`, `translate_texts`destructive (confirm): `delete_elements`, `clear_page`Every tool compiles to one or more `DesignAction`s (the existing,@@ -118,6 +121,23 @@ client ──POST /api/ai/agent {message, history, design, mode, confirmMap}re-read state, check goal, emit {done, summary}```+## Budgets & failure discipline (v0.27.3)++- **Progress budget** (`maxSteps: 8`) counts only turns that led+ somewhere — a sanitized tool call or a done. Sanitize rejections,+ unknown tools and the one JSON-repair retry are FREE, so a run+ that stumbles twice still gets its full productive budget.+- **Strike rule**: rejections are free of the tool budget, but three+ CONSECUTIVE invalid calls end the run with an actionable error —+ without this, a model that never produces a valid call loops on+ wall-clock alone while the message list grows unboundedly (found+ by the harness: it OOM'd the worker). A successful call resets+ the strike count.+- **Approved destructive calls also await the client's apply ack** —+ a failed apply feeds the error back to the model instead of being+ counted as done. The panel only persists a tool approval after a+ SUCCESSFUL apply.+## What deliberately stays out (scope discipline)- No sub-agents / parallel variations in v0.27 (SuperDesign-style 3-waydiff --git a/package-lock.json b/package-lock.jsonindex b6ee4bd..5d39cdf 100644--- a/package-lock.json+++ b/package-lock.json@@ -46,6 +46,7 @@"bun-types": "^1.3.4","eslint": "^9","eslint-config-next": "^16.4.6",+ "jsdom": "^26.1.0","tailwindcss": "^4","tsx": "^4.23.15","tw-animate-css": "^1.3.5",@@ -67,6 +68,27 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/@asamuzakjp/css-color": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",+ "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@csstools/css-calc": "^2.1.3",+ "@csstools/css-color-parser": "^3.0.9",+ "@csstools/css-parser-algorithms": "^3.0.4",+ "@csstools/css-tokenizer": "^3.0.3",+ "lru-cache": "^10.4.3"+ }+ },+ "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {+ "version": "10.4.3",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",+ "dev": true,+ "license": "ISC"+ },"node_modules/@ast-grep/napi": {"version": "0.45.3","resolved": "https://registry.npmjs.org/@ast-grep/napi/-/napi-0.45.3.tgz",@@ -1616,6 +1638,121 @@"@jridgewell/sourcemap-codec": "^1.4.10"}},+ "node_modules/@csstools/color-helpers": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",+ "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",+ "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^3.0.5",+ "@csstools/css-tokenizer": "^3.0.4"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",+ "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^5.1.0",+ "@csstools/css-calc": "^2.1.4"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^3.0.5",+ "@csstools/css-tokenizer": "^3.0.4"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",+ "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^3.0.4"+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",+ "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@dotenvx/dotenvx": {"version": "2.38.2","resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-2.38.2.tgz",@@ -6705,6 +6842,16 @@"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"}},+ "node_modules/agent-base": {+ "version": "7.1.4",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14"+ }+ },"node_modules/agentkeepalive": {"version": "4.6.0","resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz",@@ -7572,6 +7719,20 @@"node": ">= 8"}},+ "node_modules/cssstyle": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",+ "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^3.2.0",+ "rrweb-cssom": "^0.8.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -7585,6 +7746,57 @@"dev": true,"license": "BSD-2-Clause"},+ "node_modules/data-urls": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",+ "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^4.0.0",+ "whatwg-url": "^14.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/data-urls/node_modules/tr46": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/data-urls/node_modules/webidl-conversions": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/data-urls/node_modules/whatwg-url": {+ "version": "14.2.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tr46": "^5.1.0",+ "webidl-conversions": "^7.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/data-view-buffer": {"version": "1.0.2","resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",@@ -7666,6 +7878,13 @@"node": ">=0.10.0"}},+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/deep-is": {"version": "0.1.4","resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",@@ -7910,6 +8129,19 @@"node": ">=8.6"}},+ "node_modules/entities": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/error-stack-parser-es": {"version": "1.0.5","resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",@@ -9468,6 +9700,19 @@"hermes-estree": "0.25.1"}},+ "node_modules/html-encoding-sniffer": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",+ "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-encoding": "^3.1.1"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/http-errors": {"version": "2.0.1","resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",@@ -9489,6 +9734,34 @@"url": "https://opencollective.com/express"}},+ "node_modules/http-proxy-agent": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.0",+ "debug": "^4.3.4"+ },+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/https-proxy-agent": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.2",+ "debug": "4"+ },+ "engines": {+ "node": ">= 14"+ }+ },"node_modules/humanize-ms": {"version": "1.2.1","resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",@@ -9892,6 +10165,13 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/is-promise": {"version": "4.0.0","resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",@@ -10113,6 +10393,83 @@"dev": true,"license": "MIT"},+ "node_modules/jsdom": {+ "version": "26.1.0",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",+ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cssstyle": "^4.2.1",+ "data-urls": "^5.0.0",+ "decimal.js": "^10.5.0",+ "html-encoding-sniffer": "^4.0.0",+ "http-proxy-agent": "^7.0.2",+ "https-proxy-agent": "^7.0.6",+ "is-potential-custom-element-name": "^1.0.1",+ "nwsapi": "^2.2.16",+ "parse5": "^7.2.1",+ "rrweb-cssom": "^0.8.0",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^5.1.1",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^7.0.0",+ "whatwg-encoding": "^3.1.1",+ "whatwg-mimetype": "^4.0.0",+ "whatwg-url": "^14.1.1",+ "ws": "^8.18.0",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/jsdom/node_modules/tr46": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/jsdom/node_modules/webidl-conversions": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/jsdom/node_modules/whatwg-url": {+ "version": "14.2.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tr46": "^5.1.0",+ "webidl-conversions": "^7.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/jsesc": {"version": "3.1.0","resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",@@ -11007,6 +11364,13 @@"node": ">=18"}},+ "node_modules/nwsapi": {+ "version": "2.2.28",+ "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz",+ "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/nypm": {"version": "0.6.12","resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.12.tgz",@@ -11320,6 +11684,19 @@"node": ">=6"}},+ "node_modules/parse5": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^6.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",@@ -12212,6 +12589,13 @@"url": "https://opencollective.com/express"}},+ "node_modules/rrweb-cssom": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",+ "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/run-parallel": {"version": "1.2.0","resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",@@ -12298,6 +12682,19 @@"dev": true,"license": "MIT"},+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },"node_modules/scheduler": {"version": "0.28.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",@@ -12891,6 +13288,13 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/tailwind-merge": {"version": "3.7.0","resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.7.0.tgz",@@ -13008,6 +13412,26 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/tldts": {+ "version": "6.1.86",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",+ "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^6.1.86"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "6.1.86",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",+ "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/to-regex-range": {"version": "5.0.1","resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",@@ -13031,6 +13455,19 @@"node": ">=0.6"}},+ "node_modules/tough-cookie": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",+ "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^6.1.32"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/tr46": {"version": "0.0.3","resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",@@ -13647,6 +14084,19 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/web-streams-polyfill": {"version": "4.0.0-beta.3","resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",@@ -13664,6 +14114,43 @@"dev": true,"license": "BSD-2-Clause"},+ "node_modules/whatwg-encoding": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",+ "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",+ "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "iconv-lite": "0.6.3"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/whatwg-encoding/node_modules/iconv-lite": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",+ "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/whatwg-url": {"version": "5.0.0","resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",@@ -13924,6 +14411,23 @@}}},+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",diff --git a/package.json b/package.jsonindex 627f51c..acc2ce5 100644--- a/package.json+++ b/package.json@@ -64,6 +64,7 @@"bun-types": "^1.3.4","eslint": "^9","eslint-config-next": "^16.4.6",+ "jsdom": "^26.1.0","tailwindcss": "^4","tsx": "^4.23.15","tw-animate-css": "^1.3.5",diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex 536d7b6..d94af67 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -187,7 +187,7 @@ async function __canvix_post(req: NextRequest) {`${AGENT_BUDGETS.maxDirectActions} actions, only when clearly asked. Empty array otherwise. Never invent element ids.\n\n` +'Action types: addText{text,fontSize,bold,color,align,y}, updateElements{ids,patch}, deleteElements{ids}, moveElements{ids,dx,dy,to}, ' +'setHeadingsColor{color}, setTextColor{color}, setFont{fontFamily,targets}, setBackground{kind,from,to,angle}, alignElements{ids,mode}, ' +- 'distributeElements{ids,axis}, fixOverlaps, balanceLayout, addPage, duplicatePage, suggestPalette{colors}, translate{language}, magicAnimate, generateImage{prompt}.\n\n' ++ 'distributeElements{ids,axis}, fixOverlaps, balanceLayout, addPage, duplicatePage, gotoPage{page}, addStockPhoto{query}, suggestPalette{colors}, translate{language}, magicAnimate, generateImage{prompt}.\n\n' +`Fonts (exact names): ${fontFamilies().slice(0, 30).join(', ')}…\n\nCURRENT DESIGN:\n${serializeDesignContext(design)}`const raw = await chat([{ role: 'system', content: system }, ...history, { role: 'user', content: message }])// reuse the assistant route's robust parse shapediff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex d2669bd..a1fe76b 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -281,8 +281,9 @@ export function AssistantApp({ onClose }: AppPanelProps) {case 'action': {const actions = event.actions as DesignAction[]if (event.risk === 'destructive') {- if (autoApply && confirmedRef.current.has(event.tool)) {- // user already approved this tool this run+ if (confirmedRef.current.has(event.tool)) {+ // user already approved this tool this run (or+ // auto-apply is on and they approved earlier)const ack = await applyActions(actions)if (ack.ok) appliedCount += actions.lengthawait bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })@@ -374,13 +375,19 @@ export function AssistantApp({ onClose }: AppPanelProps) {const pending = pendingConfirmif (!pending) returnsetPendingConfirm(null)- if (ok) confirmedRef.current.add(pending.tool)- await bridgePost({ confirm: { tool: pending.tool, ok } })- if (ok) {- // apply immediately so the user sees the result; ack the run- const ack = await applyActions(pending.actions)- await bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })+ if (!ok) {+ await bridgePost({ confirm: { tool: pending.tool, ok: false } })+ return}+ // apply immediately so the user sees the result, then ack the run+ // (the loop now also waits for this ack on approved destructive+ // calls — a failed apply must be reported, not counted as done).+ // The approval only persists on SUCCESS — a failed apply must+ // re-ask, not silently auto-apply the retry (v0.27.3 audit fix).+ const ack = await applyActions(pending.actions)+ if (ack.ok) confirmedRef.current.add(pending.tool)+ await bridgePost({ confirm: { tool: pending.tool, ok: true } })+ await bridgePost({ ack: { ok: ack.ok, message: ack.message, design: buildDesignContext() } })}const stop = () => {diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsnew file mode 100644index 0000000..a7f4b42--- /dev/null+++ b/src/lib/agent/harness.test.ts@@ -0,0 +1,766 @@+// ─────────────────────────────────────────────────────────────+// The comprehensive agent harness (v0.27.3) — "test it thoroughly,+// not one simple case". Four layers:+//+// 1. TOOL MATRIX — every registered tool × valid / invalid /+// boundary args, asserting both the accept and+// the actionable-error contract.+// 2. LOOP FLOWS — realistic multi-step runs (poster build,+// page-switch flow, stock-photo flow, repair,+// budget exhaustion, confirm gates, abort).+// 3. WIRE FORMAT — sseLine/parseAgentTurn round-trips, event+// versioning, malformed-line tolerance.+// 4. ROUTER MATRIX — heuristic + parseIntent across phrasings.+//+// The "LLM" is a scripted queue — deterministic, no network. The+// harness asserts the INVARIANTS the real model relies on:+// · every rejected call returns an error that names the fix+// · actions the client must apply are always well-formed+// · budgets can never be exceeded, and free retries stay free+// · destructive tools never apply without an explicit approval+// ─────────────────────────────────────────────────────────────++import { describe, it, expect } from 'vitest'+import {+ parseAgentTurn,+ sseLine,+ AGENT_BUDGETS,+ AGENT_PROTOCOL_VERSION,+ type AgentEvent,+} from './protocol'+import { AGENT_TOOL_MAP, AGENT_TOOLS, toolsPromptSection, type ToolContext, type SanitizeResult } from './tools'+import { runAgentLoop, loopSystemPrompt } from './loop'+import { heuristicIntent, parseIntent } from './router'+import { serializeDesignContext, contextValidIds, type AgentDesignCtx } from './context'++// ── fixtures ─────────────────────────────────────────────────++const ctx: ToolContext = {+ validIds: new Set(['el-1', 'el-2', 'txt-1', 'txt-2', 'grp-1', 'img-1']),+ width: 1080,+ height: 1080,+ fonts: new Set(['Poppins', 'Inter', 'Montserrat', 'Playfair Display']),+}++const design: AgentDesignCtx = {+ name: 'Launch Poster',+ width: 1080,+ height: 1080,+ templateType: 'poster',+ pageCount: 3,+ currentPageIndex: 0,+ selectedIds: ['txt-1'],+ elements: [+ { id: 'el-1', type: 'rect', x: 0, y: 0, width: 100, height: 100, fill: '#FF0000' },+ { id: 'el-2', type: 'rect', x: 50, y: 50, width: 100, height: 100, fill: '#00FF00' },+ { id: 'txt-1', type: 'text', x: 0, y: 200, width: 400, height: 60, text: 'Hello', fontSize: 48, fill: '#111111' },+ { id: 'txt-2', type: 'text', x: 0, y: 300, width: 400, height: 60, text: 'World', fontSize: 32, fill: '#222222' },+ { id: 'grp-1', type: 'group', x: 10, y: 10, width: 200, height: 200 },+ { id: 'img-1', type: 'image', x: 0, y: 400, width: 300, height: 200 },+ ],+ colorsInUse: ['#111111', '#FF0000'],+ fontsInUse: ['Inter'],+ brand: { colors: ['#7D2AE8', '#02C0CC'], headingFont: 'Poppins', bodyFont: 'Inter' },+ overlaps: ['rect#el-1 × rect#el-2 (25%)'],+ offCanvas: [],+ otherPages: ['p1: 4 elements', 'p2: 7 elements'],+}++/** scripted chat: pops replies in order; records every request */+function scriptedChat(replies: string[]) {+ const calls: { role: string; content: string }[][] = []+ const chat = async (messages: { role: 'system' | 'user' | 'assistant'; content: string }[]) => {+ calls.push(messages.map((m) => ({ role: m.role, content: m.content })))+ return replies.shift() ?? JSON.stringify({ done: true, summary: '(script exhausted)' })+ }+ return { chat, calls }+}++const turn = (tool: string, args: Record<string, unknown> = {}, thought = 'step') =>+ JSON.stringify({ thought, tool, args })+const done = (summary: string) => JSON.stringify({ done: true, summary })++// ═════════════════════════════════════════════════════════════+// 1. TOOL MATRIX — every tool, valid + invalid + boundary+// ═════════════════════════════════════════════════════════════++describe('harness · tool matrix', () => {+ const tool = (name: string) => {+ const t = AGENT_TOOL_MAP.get(name)+ if (!t) throw new Error(`tool "${name}" is not registered — harness covers every tool`)+ return t+ }+ const call = (name: string, args: Record<string, unknown>, c: ToolContext = ctx): SanitizeResult =>+ tool(name).sanitize(args, c)++ it('every tool in the registry is covered by this harness', () => {+ // the source of truth: if a tool is added without harness coverage,+ // this fails and forces the author to add cases below+ const covered = [+ 'get_page_state', 'add_text', 'add_shape', 'add_image', 'add_stock_photo', 'add_sticker',+ 'add_table', 'update_elements', 'set_text_style', 'move_elements', 'align_elements',+ 'distribute_elements', 'set_background', 'set_font', 'recolor', 'add_page', 'duplicate_page',+ 'goto_page', 'fix_overlaps', 'balance_layout', 'animate_page', 'translate_texts',+ 'delete_elements', 'clear_page',+ ]+ for (const t of AGENT_TOOLS) expect(covered).toContain(t.name)+ expect(covered).toHaveLength(AGENT_TOOLS.length)+ })++ // ── add_text ─────────────────────────────────────────────+ it('add_text: valid full args', () => {+ const r = call('add_text', { text: 'Grand Opening', fontSize: 96, x: 80, y: 120, width: 900, color: '#7D2AE8', bold: true, align: 'left' })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addText', text: 'Grand Opening', fontSize: 96, color: '#7d2ae8', bold: true, align: 'left' })+ })+ it('add_text: yBand rides when y is absent', () => {+ const r = call('add_text', { text: 'Sub', yBand: 'bottom' })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ y: 'bottom' })+ })+ it('add_text: exact y overrides yBand', () => {+ const r = call('add_text', { text: 'Sub', y: 500, yBand: 'top' })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ y: 500 })+ if (r.ok) expect(r.actions[0].yBand).toBeUndefined()+ })+ it('add_text: boundary fontSize 6 and 400 pass, 5 and 401 fail with the range echoed', () => {+ expect(call('add_text', { text: 'x', fontSize: 6 }).ok).toBe(true)+ expect(call('add_text', { text: 'x', fontSize: 400 }).ok).toBe(true)+ for (const bad of [5, 401, 1200]) {+ const r = call('add_text', { text: 'x', fontSize: bad })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error).toContain(String(bad))+ }+ })+ it('add_text: empty text and bad color rejected with actionable errors', () => {+ expect(call('add_text', { text: ' ' }).ok).toBe(false)+ const r = call('add_text', { text: 'x', color: 'purple' })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error).toContain('#RRGGBB')+ })+ it('add_text: unknown font rejected with valid examples listed', () => {+ const r = call('add_text', { text: 'x', fontFamily: 'Comic Sans' })+ expect(r.ok).toBe(false)+ if (!r.ok) {+ expect(r.error).toContain('Comic Sans')+ expect(r.error).toContain('Poppins')+ }+ })+ it('add_text: 400-char text is trimmed at the cap (no prompt injection via overflow)', () => {+ const r = call('add_text', { text: 'A'.repeat(900) })+ expect(r.ok).toBe(true)+ if (r.ok) expect((r.actions[0].text as string).length).toBeLessThanOrEqual(400)+ })++ // ── add_shape ────────────────────────────────────────────+ it('add_shape: every shape kind accepts and compiles', () => {+ for (const shape of ['rect', 'ellipse', 'triangle', 'star', 'line']) {+ const r = call('add_shape', { shape, x: 10, y: 10, width: 100, height: 80 })+ expect(r.ok, shape).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addShape', shape })+ }+ })+ it('add_shape: missing numbers and tiny sizes rejected naming the field', () => {+ const r1 = call('add_shape', { shape: 'rect', x: 1, y: 1 })+ expect(r1.ok).toBe(false)+ if (!r1.ok) expect(r1.error).toContain('width')+ const r2 = call('add_shape', { shape: 'rect', x: 1, y: 1, width: 2, height: 80 })+ expect(r2.ok).toBe(false)+ if (!r2.ok) expect(r2.error).toContain('≥ 4')+ expect(call('add_shape', { shape: 'hexagon', x: 1, y: 1, width: 50, height: 50 }).ok).toBe(false)+ })++ // ── add_image / add_stock_photo ──────────────────────────+ it('add_image: prompt validation + placement clamps', () => {+ expect(call('add_image', { prompt: 'ok' }).ok).toBe(false)+ const r = call('add_image', { prompt: 'an abstract gradient banner', x: -50, y: 2000, width: 5000 })+ expect(r.ok).toBe(true)+ if (r.ok) {+ expect(r.actions[0]).toMatchObject({ type: 'generateImage', prompt: 'an abstract gradient banner' })+ expect(r.actions[0].x).toBe(0) // clamped into the page+ expect(r.actions[0].width).toBe(1080) // clamped to page width+ }+ })+ it('add_stock_photo: query + orientation validation, compiles addStockPhoto action', () => {+ expect(call('add_stock_photo', { query: 'a' }).ok).toBe(false)+ for (const orientation of ['landscape', 'portrait', 'square']) {+ const r = call('add_stock_photo', { query: 'coffee cup on a wooden table', orientation })+ expect(r.ok, orientation).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addStockPhoto', query: 'coffee cup on a wooden table', orientation })+ }+ const bad = call('add_stock_photo', { query: 'coffee', orientation: 'diagonal' })+ expect(bad.ok).toBe(true) // unknown enum falls back — no orientation filter+ if (bad.ok) expect(bad.actions[0].orientation).toBeUndefined()+ })++ // ── add_sticker / add_table ──────────────────────────────+ it('add_sticker: emoji required, size bounds', () => {+ expect(call('add_sticker', { emoji: '' }).ok).toBe(false)+ expect(call('add_sticker', { emoji: '🚀', size: 10 }).ok).toBe(false)+ const r = call('add_sticker', { emoji: '✨', size: 200 })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addSticker', emoji: '✨', size: 200 })+ })+ it('add_table: header/rows validation + cell caps', () => {+ expect(call('add_table', { header: [], rows: [['a']] }).ok).toBe(false)+ expect(call('add_table', { header: ['A'], rows: [] }).ok).toBe(false)+ const r = call('add_table', {+ header: ['Plan', 'Price', 'Seats'],+ rows: [+ ['Free', '$0', '1'],+ ['Pro', '$12', '5'],+ ['Team', '$49', '25'],+ ],+ })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'addTable', header: ['Plan', 'Price', 'Seats'] })+ })++ // ── update_elements / set_text_style ─────────────────────+ it('update_elements: full patch surface, one action per call', () => {+ const r = call('update_elements', {+ ids: ['el-1', 'el-2'],+ patch: { x: 10, y: 20, width: 200, height: 100, rotation: 15, opacity: 0.5, fill: '#00AAFF', bold: true, align: 'right' },+ })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'updateElements', ids: ['el-1', 'el-2'] })+ })+ it('update_elements: every invalid patch value is named', () => {+ for (const [patch, hint] of [+ [{ fill: 'nope' }, '#RRGGBB'],+ [{ fontSize: 900 }, '6–400'],+ [{ opacity: 2 }, '0–1'],+ [{ width: 'wide' }, 'number'],+ ] as const) {+ const r = call('update_elements', { ids: ['el-1'], patch })+ expect(r.ok, JSON.stringify(patch)).toBe(false)+ if (!r.ok) expect(r.error).toContain(hint)+ }+ })+ it('update_elements: stale/foreign ids rejected, valid ones listed', () => {+ const r = call('update_elements', { ids: ['ghost-9'], patch: { fill: '#123456' } })+ expect(r.ok).toBe(false)+ if (!r.ok) expect(r.error).toContain('ghost-9')+ if (!r.ok) expect(r.error).toContain('get_page_state')+ })+ it('set_text_style: font + size + color compile to one updateElements', () => {+ const r = call('set_text_style', { ids: ['txt-1'], fontFamily: 'Poppins', fontSize: 64, bold: true, color: '#FF0055' })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0]).toMatchObject({ type: 'updateElements', ids: ['txt-1'], patch: { fontFamily: 'Poppins', fontSize: 64, bold: true, fill: '#ff0055' } })+ })++ // ── move / align / distribute ────────────────────────────+ it('move_elements: deltas clamp to ±2 pages; snap bands map', () => {+ const r = call('move_elements', { ids: ['el-1'], dx: 99999, dy: -99999 })+ expect(r.ok).toBe(true)+ if (r.ok) expect(r.actions[0].dx).toBe(2160) // 2 × 1080+ const snap = call('move_elements', { ids: ['el-1'], to: 'center' })+ expect(snap.ok).toBe(true)+ if (snap.ok) expect(snap.actions[0]).toMatchObject({ to: 'center' })+ expect(call('move_elements', { ids: ['el-1'] }).ok).toBe(false) // neither dx/dy nor to+ })+ it('align_elements: all six modes accept; bad mode rejects', () => {+ for (const mode of ['left', 'cx', 'right', 'top', 'cy', 'bottom']) {+ expect(call('align_elements', { ids: ['el-1', 'el-2'], mode }).ok, mode).toBe(true)+ }+ expect(call('align_elements', { ids: ['el-1'], mode: 'diagonal' }).ok).toBe(false)+ })+ it('distribute_elements: needs 3+ ids (client contract) and says what to use instead', () => {+ const two = call('distribute_elements', { ids: ['el-1', 'el-2'], axis: 'x' })+ expect(two.ok).toBe(false)+ if (!two.ok) expect(two.error).toContain('align_elements')+ const three = call('distribute_elements', { ids: ['el-1', 'el-2', 'img-1'], axis: 'y' })+ expect(three.ok).toBe(true)+ })++ // ── page-level tools ─────────────────────────────────────+ it('set_background: solid + gradient + angle clamp; bad forms rejected', () => {+ expect(call('set_background', { kind: 'solid', from: '#0D1117' }).ok).toBe(true)+ const g = call('set_background', { kind: 'gradient', from: '#7D2AE8', to: '#02C0CC', angle: 999 })+ expect(g.ok).toBe(true)+ if (g.ok) expect(g.actions[0].angle).toBe(360)+ expect(call('set_background', { kind: 'gradient', from: '#7D2AE8' }).ok).toBe(false)+ expect(call('set_background', { kind: 'plaid', from: '#000000' }).ok).toBe(false)+ })+ it('set_font: targets enum + catalog validation', () => {+ for (const targets of ['all', 'headings', 'body']) {+ expect(call('set_font', { fontFamily: 'Inter', targets }).ok, targets).toBe(true)+ }+ expect(call('set_font', { fontFamily: 'Wingdings' }).ok).toBe(false)+ })+ it('recolor: both modes + the 3-color palette floor', () => {+ expect(call('recolor', { color: '#FF0055', targets: 'text' }).ok).toBe(true)+ expect(call('recolor', { palette: ['#7D2AE8', '#02C0CC', '#FFD166'] }).ok).toBe(true)+ expect(call('recolor', { palette: ['#7D2AE8', 'nope', '#FFD166'] }).ok).toBe(false)+ expect(call('recolor', {}).ok).toBe(false)+ })+ it('add_page / duplicate_page / fix_overlaps / balance_layout / animate_page / translate_texts compile', () => {+ expect(call('add_page', {})).toMatchObject({ ok: true })+ expect(call('duplicate_page', {})).toMatchObject({ ok: true })+ expect(call('fix_overlaps', {})).toMatchObject({ ok: true })+ expect(call('balance_layout', {})).toMatchObject({ ok: true })+ expect(call('animate_page', {})).toMatchObject({ ok: true })+ expect(call('translate_texts', { language: 'Spanish' })).toMatchObject({ ok: true })+ expect(call('translate_texts', {}).ok).toBe(false)+ })++ // ── goto_page (new in v0.27.3) ───────────────────────────+ it('goto_page: 1-based integer validation', () => {+ const ok = call('goto_page', { page: 2 })+ expect(ok.ok).toBe(true)+ if (ok.ok) expect(ok.actions[0]).toMatchObject({ type: 'gotoPage', page: 2 })+ for (const bad of [0, -1, 61, 2.5, 'two']) {+ expect(call('goto_page', { page: bad }).ok, String(bad)).toBe(false)+ }+ expect(call('goto_page', {}).ok).toBe(false)+ })++ // ── destructive ──────────────────────────────────────────+ it('delete_elements / clear_page are the only destructive tools', () => {+ for (const t of AGENT_TOOLS) {+ const shouldBeDestructive = t.name === 'delete_elements' || t.name === 'clear_page'+ expect(t.risk === 'destructive', t.name).toBe(shouldBeDestructive)+ }+ })+ it('clear_page expands to every current id and refuses an empty page', () => {+ const r = call('clear_page', {})+ expect(r.ok).toBe(true)+ if (r.ok) expect((r.actions[0].ids as string[]).sort()).toEqual([...ctx.validIds].sort())+ const empty = call('clear_page', {}, { ...ctx, validIds: new Set() })+ expect(empty.ok).toBe(false)+ })++ // ── universal invariants ─────────────────────────────────+ it('EVERY tool: accepted calls always carry ≥1 action object with a type', () => {+ // sample one valid call per tool+ const valid: Record<string, Record<string, unknown>> = {+ get_page_state: {},+ add_text: { text: 'Hi' },+ add_shape: { shape: 'rect', x: 1, y: 1, width: 50, height: 50 },+ add_image: { prompt: 'a banner' },+ add_stock_photo: { query: 'coffee' },+ add_sticker: { emoji: '🚀' },+ add_table: { header: ['A'], rows: [['1']] },+ update_elements: { ids: ['el-1'], patch: { fill: '#123456' } },+ set_text_style: { ids: ['txt-1'], fontSize: 40 },+ move_elements: { ids: ['el-1'], dx: 10 },+ align_elements: { ids: ['el-1'], mode: 'cx' },+ distribute_elements: { ids: ['el-1', 'el-2', 'img-1'], axis: 'x' },+ set_background: { kind: 'solid', from: '#0D1117' },+ set_font: { fontFamily: 'Inter' },+ recolor: { color: '#FF0055' },+ add_page: {},+ duplicate_page: {},+ goto_page: { page: 1 },+ fix_overlaps: {},+ balance_layout: {},+ animate_page: {},+ translate_texts: { language: 'French' },+ delete_elements: { ids: ['el-1'] },+ clear_page: {},+ }+ for (const t of AGENT_TOOLS) {+ const r = t.sanitize(valid[t.name], ctx)+ expect(r.ok, t.name).toBe(true)+ if (r.ok) {+ expect(r.actions.length, t.name).toBeGreaterThan(0)+ expect(typeof r.actions[0].type, t.name).toBe('string')+ expect(r.observation, t.name).toBeTruthy()+ }+ }+ })+ it('EVERY tool: rejections always produce a non-empty actionable error', () => {+ // garbage args must be rejected (never crash, never pass through)+ for (const t of AGENT_TOOLS) {+ const r = t.sanitize({ ids: [], text: '', patch: {} }, ctx)+ if (!r.ok) {+ expect(r.error.length, t.name).toBeGreaterThan(10)+ } else {+ // tools with no args (add_page etc.) legitimately accept {}+ expect(['add_page', 'duplicate_page', 'fix_overlaps', 'balance_layout', 'animate_page', 'get_page_state', 'clear_page']).toContain(t.name)+ }+ }+ })+ it('sanitizers never throw on adversarial args (wrong types everywhere)', () => {+ const adversarial = [+ { ids: 'not-an-array', patch: { fill: { deep: 'object' } } },+ { text: { nested: true }, fontSize: NaN },+ { header: 'string', rows: 42 },+ { page: Infinity, factor: 'x' },+ { palette: 'no', ids: [null, 123, {}] },+ { dx: '1e999', shape: { fake: 1 } },+ ]+ for (const t of AGENT_TOOLS) {+ for (const args of adversarial) {+ expect(() => t.sanitize(args as Record<string, unknown>, ctx), `${t.name} ${JSON.stringify(args)}`).not.toThrow()+ }+ }+ })+})++// ═════════════════════════════════════════════════════════════+// 2. LOOP FLOWS — realistic multi-step runs+// ═════════════════════════════════════════════════════════════++describe('harness · loop flows', () => {+ it('FLOW poster build: background → headline → subline → photo → verify → done (6 steps, ordered events)', async () => {+ const events: AgentEvent[] = []+ const { chat, calls } = scriptedChat([+ turn('set_background', { kind: 'gradient', from: '#1A1B2E', to: '#7D2AE8', angle: 160 }),+ turn('add_text', { text: 'GRAND OPENING', fontSize: 120, x: 60, y: 140, width: 960, bold: true, color: '#FFFFFF' }),+ turn('add_text', { text: 'Saturday · 10 AM · Free coffee all day', fontSize: 36, x: 60, y: 320, color: '#FFD166' }),+ turn('add_stock_photo', { query: 'coffee shop interior warm light', orientation: 'landscape' }),+ turn('get_page_state'),+ done('Poster built: gradient background, headline, subline and a licensed photo.'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ // the client pushes refreshed context with every ack — the loop+ // re-serializes it after get_page_state+ refreshedContext: () => design,+ })+ expect(result.toolCalls).toBe(5)+ expect(result.steps).toBe(6)+ expect(result.summary).toContain('Poster built')++ // event ORDER: start(implicit) → step → action → observation × N → done+ const kinds = events.map((e) => e.type)+ expect(kinds[0]).toBe('step')+ expect(kinds[kinds.length - 1]).toBe('done')+ expect(kinds.filter((k) => k === 'step')).toHaveLength(5)+ expect(kinds.filter((k) => k === 'action')).toHaveLength(5)+ // every action references its step index and carries a callId+ for (const a of events.filter((e) => e.type === 'action')) {+ const act = a as Extract<AgentEvent, { type: 'action' }>+ expect(act.callId).toMatch(/^call-/)+ expect(act.actions.length).toBeGreaterThan(0)+ }+ // the loop fed the model its observation after each apply (messages grow)+ expect(calls.length).toBe(6)+ expect(calls[5][calls[5].length - 1].content).toContain('UPDATED PAGE STATE')+ })++ it('FLOW page-switch: add_page → goto_page → get_page_state → build on the new page', async () => {+ const events: AgentEvent[] = []+ const { chat, calls } = scriptedChat([+ turn('add_page'),+ turn('goto_page', { page: 4 }), // design.pageCount=3 → new page is #4+ turn('get_page_state'),+ turn('add_text', { text: 'Page 4 headline', fontSize: 80 }),+ done('Added page 4 with its headline.'),+ ])+ // a client that refreshes context after get_page_state+ const refreshed: AgentDesignCtx = { ...design, currentPageIndex: 3, elements: [] }+ const result = await runAgentLoop({+ chat,+ design,+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ refreshedContext: () => refreshed,+ })+ expect(result.toolCalls).toBe(4)+ // after the refresh, the loop told the model it's on page 4 and+ // validIds were recomputed from the refreshed context+ const lastCall = calls[3]+ expect(lastCall[lastCall.length - 1].content).toContain('editing page 4')+ // actions: addPage, gotoPage, __getContext, addText+ const tools = events.filter((e) => e.type === 'action').map((e) => (e as { tool: string }).tool)+ expect(tools).toEqual(['add_page', 'goto_page', 'get_page_state', 'add_text'])+ })++ it('FLOW self-correction ladder: bad hex → bad font → good call; rejections stay budget-free', async () => {+ const { chat } = scriptedChat([+ turn('update_elements', { ids: ['txt-1'], patch: { fill: 'purple' } }),+ turn('add_text', { text: 'Hi', fontFamily: 'Comic Sans' }),+ turn('update_elements', { ids: ['txt-1'], patch: { fill: '#7D2AE8' } }),+ done('Fixed the color on the third try.'),+ ])+ const result = await runAgentLoop({ chat, design, emit: () => {}, awaitApply: async () => ({ ok: true }) })+ expect(result.toolCalls).toBe(1)+ // v0.27.3: progress budget counts only productive steps — both+ // rejections were free, so the run still had full budget left+ expect(result.steps).toBe(4)+ })++ it('FLOW budget exhaustion: a model that never finishes is cut off with a done event (never a hang)', async () => {+ const events: AgentEvent[] = []+ let modelTurns = 0+ const result = await runAgentLoop({+ chat: async () => {+ modelTurns += 1+ return turn('add_sticker', { emoji: '🤖' })+ },+ design,+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ // maxSteps=8 productive calls cap the loop; each add_sticker is+ // productive so the loop stops at exactly 8 tool calls+ expect(modelTurns).toBe(AGENT_BUDGETS.maxSteps)+ expect(result.toolCalls).toBe(AGENT_BUDGETS.maxSteps)+ const last = events[events.length - 1]+ expect(last.type).toBe('done')+ })++ it('FLOW rejected-forever model: rejections are tool-budget-free but 3 strikes end the run (no infinite loop)', async () => {+ const events: AgentEvent[] = []+ let modelTurns = 0+ const result = await runAgentLoop({+ chat: async () => {+ modelTurns += 1+ return turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }) // always invalid+ },+ design,+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ })+ // 3 strikes → error event, exactly 3 model turns, zero applies+ expect(modelTurns).toBe(3)+ expect(result.toolCalls).toBe(0)+ const last = events[events.length - 1]+ expect(last.type).toBe('error')+ if (last.type === 'error') expect(last.message).toContain('3 invalid tool calls')+ })++ it('FLOW strike reset: two bad calls, one good, two more bad — the run continues (strikes are consecutive)', async () => {+ const { chat } = scriptedChat([+ turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }), // strike 1+ turn('add_sticker', { emoji: '🚀' }), // good → reset+ turn('update_elements', { ids: ['ghost'], patch: { fill: '#123456' } }), // strike 1 again+ turn('update_elements', { ids: ['ghost-2'], patch: { fill: '#123456' } }), // strike 2+ done('Mixed luck but finished.'),+ ])+ const result = await runAgentLoop({ chat, design, emit: () => {}, awaitApply: async () => ({ ok: true }) })+ expect(result.summary).toBe('Mixed luck but finished.')+ expect(result.toolCalls).toBe(1)+ })++ it('FLOW destructive decline: the model is told, adapts, and finishes — nothing was applied', async () => {+ const applied: unknown[] = []+ const { chat, calls } = scriptedChat([+ turn('clear_page'),+ turn('add_text', { text: 'Starting fresh instead', fontSize: 64 }),+ done('Kept your content and added a fresh headline.'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ emit: () => {},+ confirmed: new Set(),+ awaitConfirm: async () => false,+ awaitApply: async () => {+ applied.push('x')+ return { ok: true }+ },+ })+ expect(result.toolCalls).toBe(1) // only the add_text+ expect(applied).toHaveLength(1) // clear_page never applied+ const declineMsg = calls[1].find((m) => m.role === 'user')+ expect(declineMsg?.content).toContain('DECLINED')+ })++ it('FLOW destructive approve-then-apply-failure: the failure feeds back (v0.27.3 fix)', async () => {+ const applied: string[] = []+ const { chat, calls } = scriptedChat([+ turn('delete_elements', { ids: ['el-1'] }),+ turn('delete_elements', { ids: ['el-2'] }),+ done('Deleted what I could.'),+ ])+ const result = await runAgentLoop({+ chat,+ design,+ emit: () => {},+ awaitConfirm: async () => true,+ awaitApply: async () => {+ applied.push('attempt')+ return applied.length === 1+ ? { ok: false, message: 'Element locked by another collaborator' }+ : { ok: true }+ },+ })+ // first delete: approved but apply FAILED → error observation, not counted+ expect(result.toolCalls).toBe(1)+ const failureMsg = calls[1].find((m) => m.role === 'user')+ expect(failureMsg?.content).toContain('locked by another collaborator')+ expect(failureMsg?.content).toContain('NOT changed')+ })++ it('FLOW abort mid-run: everything applied so far is kept and reported', async () => {+ const signal = { aborted: false, reason: 'Stopped by user' }+ let n = 0+ const result = await runAgentLoop({+ chat: async () => {+ n += 1+ if (n === 4) signal.aborted = true // user hits Stop during turn 4+ return turn('add_sticker', { emoji: '⭐' })+ },+ design,+ emit: () => {},+ signal,+ awaitApply: async () => ({ ok: true }),+ })+ // abort is checked at the TOP of the loop: turn 4 (already in+ // flight when Stop landed) still applied; there is no turn 5+ expect(result.toolCalls).toBe(4)+ expect(result.summary).toContain('Stopped')+ })++ it('FLOW JSON repair: first reply is prose, the repair turn succeeds', async () => {+ const { chat } = scriptedChat([+ 'Sure! Let me add a nice headline for you. I will use a bold font.',+ turn('add_text', { text: 'Repaired', fontSize: 72 }),+ done('Recovered after the repair.'),+ ])+ const result = await runAgentLoop({ chat, design, emit: () => {}, awaitApply: async () => ({ ok: true }) })+ expect(result.toolCalls).toBe(1)+ expect(result.summary).toBe('Recovered after the repair.')+ })++ it('FLOW provider failure: a thrown chat becomes an error event, never an unhandled rejection', async () => {+ const events: AgentEvent[] = []+ const result = await runAgentLoop({+ chat: async () => {+ throw new Error('429 quota exceeded')+ },+ design,+ emit: (e) => events.push(e),+ })+ expect(result.toolCalls).toBe(0)+ const err = events.find((e) => e.type === 'error')+ expect(err).toBeTruthy()+ if (err && err.type === 'error') expect(err.message).toContain('429')+ })++ it('the system prompt carries the full tool list, the design context and the page rule', () => {+ const prompt = loopSystemPrompt(design, ctx)+ for (const t of AGENT_TOOLS) expect(prompt).toContain(t.name)+ expect(prompt).toContain('Launch Poster')+ expect(prompt).toContain('BRAND KIT')+ expect(prompt).toContain('goto_page') // the new page rule+ expect(prompt).toContain('editing page 1')+ expect(prompt).toContain('grp-1') // group ids are valid targets+ })+})++// ═════════════════════════════════════════════════════════════+// 3. WIRE FORMAT+// ═════════════════════════════════════════════════════════════++describe('harness · SSE wire format', () => {+ it('every event type serializes to exactly one `data: {json}\\n\\n` line and round-trips', () => {+ const samples: AgentEvent[] = [+ { v: 1, type: 'start', intent: 'plan' },+ { v: 1, type: 'step', index: 1, thought: 'thinking', tool: 'add_text' },+ { v: 1, type: 'plan', steps: ['a', 'b'] },+ { v: 1, type: 'action', stepIndex: 1, callId: 'call-1-ab12cd', risk: 'write', tool: 'add_text', actions: [{ type: 'addText', text: 'Hi' }] },+ { v: 1, type: 'ack', callId: 'call-1-ab12cd', ok: true },+ { v: 1, type: 'observation', stepIndex: 1, message: 'added' },+ { v: 1, type: 'done', summary: 'All set', steps: 3, toolCalls: 2 },+ { v: 1, type: 'error', message: 'provider down', code: 'PROVIDER' },+ { v: 1, type: 'aborted', reason: 'Stopped by user' },+ ]+ for (const ev of samples) {+ const line = sseLine(ev)+ expect(line.startsWith('data: ')).toBe(true)+ expect(line.endsWith('\n\n')).toBe(true)+ expect(line.split('\n\n')[0]).toBe(`data: ${JSON.stringify(ev)}`)+ expect(JSON.parse(line.slice(6))).toEqual(ev)+ }+ })+ it('the protocol version is 1 everywhere (client compat contract)', () => {+ expect(AGENT_PROTOCOL_VERSION).toBe(1)+ })+ it('parseAgentTurn: nested braces in strings survive; fences and prose tolerated', () => {+ const t = parseAgentTurn('Here you go:\n```json\n{"thought":"a {b} c","tool":"add_text","args":{"text":"}{"}}\n```')+ expect(t?.tool).toBe('add_text')+ expect((t?.args as { text: string }).text).toBe('}{')+ })+ it('parseAgentTurn: picks the LARGEST valid object (multi-object replies)', () => {+ const t = parseAgentTurn('{"a":1}\n{"thought":"x","tool":"get_page_state","args":{}}')+ expect(t?.tool).toBe('get_page_state')+ })+})++// ═════════════════════════════════════════════════════════════+// 4. ROUTER MATRIX+// ═════════════════════════════════════════════════════════════++describe('harness · router matrix', () => {+ it('asks: questions land on ask', () => {+ for (const m of [+ 'What do you think of this design?',+ 'How does this look?',+ 'Is this font too small?',+ 'Why is the text overlapping?',+ ]) {+ expect(heuristicIntent(m), m).toBe('ask')+ }+ })+ it('acts: single surgical edits land on act', () => {+ for (const m of [+ 'Make the title bold',+ 'change all heading colors to purple',+ 'Delete the subtitle',+ 'Center everything',+ ]) {+ expect(heuristicIntent(m), m).toBe('act')+ }+ })+ it('plans: multi-goal briefs land on plan', () => {+ for (const m of [+ 'Design a bold poster for a coffee launch with a warm palette and a big headline',+ 'complete redesign of this flyer with new colors and fonts',+ 'rebrand this deck',+ ]) {+ expect(heuristicIntent(m), m).toBe('plan')+ }+ })+ it('unsure → null → the model classifier decides', () => {+ expect(heuristicIntent('lol')).toBeNull()+ expect(heuristicIntent('')).toBeNull()+ })+ it('parseIntent: fenced, bare, and garbage forms', () => {+ expect(parseIntent('{"intent":"act"}')).toBe('act')+ expect(parseIntent('```json\n{"intent":"plan"}\n```')).toBe('plan')+ expect(parseIntent('sure!')).toBe('plan') // fallback+ expect(parseIntent('')).toBe('plan')+ })+})++// ═════════════════════════════════════════════════════════════+// 5. CONTEXT SERIALIZATION+// ═════════════════════════════════════════════════════════════++describe('harness · context serialization', () => {+ it('serializes every element, selection, brand, overlaps and other pages', () => {+ const s = serializeDesignContext(design)+ for (const id of ['el-1', 'el-2', 'txt-1', 'txt-2', 'grp-1', 'img-1']) expect(s).toContain(id)+ expect(s).toContain('[SELECTED]') // txt-1 is selected+ expect(s).toContain('text="Hello"')+ expect(s).toContain('Overlapping pairs: rect#el-1 × rect#el-2')+ expect(s).toContain('Other pages')+ expect(s).toContain('1080x1080')+ expect(s).toContain('3 page(s)')+ })+ it('an empty page serializes honestly', () => {+ const s = serializeDesignContext({ elements: [] })+ expect(s).toContain('(empty page)')+ expect(s).toContain('none detected')+ })+ it('contextValidIds: groups included, selected included', () => {+ const ids = contextValidIds(design)+ expect(ids.has('grp-1')).toBe(true)+ expect(ids.has('txt-2')).toBe(true)+ expect(ids.size).toBe(6)+ })+ it('toolsPromptSection lists every tool with its risk tier', () => {+ const s = toolsPromptSection()+ for (const t of AGENT_TOOLS) {+ expect(s).toContain(`${t.name} (${t.risk})`)+ }+ })+})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex 1be3ffd..18023fa 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -63,6 +63,7 @@ export function loopSystemPrompt(design: AgentDesignCtx, ctx: ToolContext): stri'5. Prefer the BRAND KIT colors/fonts when one is given.','6. When the goal is achieved, verify visually via get_page_state (once), then emit {"done":true,"summary":"…"}. Never claim work you did not do.','7. Args must match each tool spec exactly. On an error observation, fix the args and retry — the error message tells you what to change.',+ '8. Tools edit the CURRENT page only. To work on another page: goto_page {page: N}, then get_page_state — ids change with the page. add_page appends the LAST page.','','CURRENT DESIGN:',serializeDesignContext(design),@@ -97,6 +98,18 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; sconst started = Date.now()let steps = 0+ /** PROGRESS steps — model turns that led somewhere (a valid tool+ * call or a done). Rejections and repair retries do NOT count:+ * the budget guards against over-ambition, and a run that wasted+ * its 8 steps on two bad calls + a JSON repair never got to be+ * ambitious in the first place (v0.27.3 audit fix). */+ let progressSteps = 0+ /** free-correction strikes — sanitize rejections and unknown tools+ * are budget-free so the model can self-correct, but a model that+ * NEVER produces a valid call would loop forever on wall-clock+ * alone, growing the message list until the process dies (found+ * by the harness OOM). Three strikes and the run ends. */+ let strikes = 0let toolCalls = 0let summary = ''@@ -106,7 +119,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; semit({ v: 1, type: 'aborted', reason: signal.reason ?? 'Stopped by user' })return { summary: summary || 'Stopped by the user.', steps, toolCalls }}- if (steps >= AGENT_BUDGETS.maxSteps || toolCalls >= AGENT_BUDGETS.maxToolCalls) {+ if (progressSteps >= AGENT_BUDGETS.maxSteps || toolCalls >= AGENT_BUDGETS.maxToolCalls) {emit({v: 1,type: 'done',@@ -116,6 +129,14 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; s})return { summary, steps, toolCalls }}+ if (strikes >= 3) {+ emit({+ v: 1,+ type: 'error',+ message: 'Stopped after 3 invalid tool calls in a row — the error messages under each step explain what to fix; try rephrasing the request.',+ })+ return { summary, steps, toolCalls }+ }if (Date.now() - started > AGENT_BUDGETS.maxWallMs) {emit({ v: 1, type: 'done', summary: 'Time budget reached — applied work is kept.', steps, toolCalls })return { summary, steps, toolCalls }@@ -164,13 +185,13 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; sconst thought = String(turn.thought ?? '').slice(0, 300)if (!tool) {const known = [...AGENT_TOOL_MAP.keys()].slice(0, 6).join(', ')+ strikes += 1messages.push({role: 'user',content: `ERROR: unknown tool "${toolName}". Valid tools: ${known}… (full list in the system prompt). Retry with a valid tool.`,})continue}-emit({ v: 1, type: 'step', index: steps, thought, tool: toolName })const args = (turn.args && typeof turn.args === 'object' && !Array.isArray(turn.args) ? turn.args : {}) as Record<string, unknown>@@ -178,9 +199,15 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; sif (!result.ok) {// free correction: rejected calls don't consume the tool budget+ // (but they cost a strike — 3 in a row end the run)+ strikes += 1messages.push({ role: 'user', content: observationFor(toolName, result, false) })continue}+ strikes = 0+ // a SANITIZED call is progress — it will reach the client as an+ // action (or a confirmation prompt). Rejections above stay free.+ progressSteps += 1// ── destructive gate ─────────────────────────────────────if (tool.risk === 'destructive' && !confirmed.has(toolName)) {@@ -203,6 +230,17 @@ export async function runAgentLoop(deps: LoopDeps): Promise<{ summary: string; s})continue}+ // v0.27.3: an approved destructive call still needs the client's+ // apply ack — the failure path (apply throws on the client) must+ // feed the error back to the model instead of counting as done+ const ack = (await deps.awaitApply?.()) ?? { ok: true }+ if (!ack.ok) {+ messages.push({+ role: 'user',+ content: `ERROR applying ${toolName}: ${ack.message ?? 'client rejected the action'}. The document was NOT changed. Adjust and retry or finish.`,+ })+ continue+ }} else {emit({v: 1,diff --git a/src/lib/agent/protocol.ts b/src/lib/agent/protocol.tsindex 888fe51..8c6072d 100644--- a/src/lib/agent/protocol.ts+++ b/src/lib/agent/protocol.ts@@ -71,24 +71,49 @@ export interface AgentTurn {variant?: number}+/** Keys that mark a parsed object as an actual agent turn (or an+ * act-route reply). Used to prefer a real turn over preamble objects+ * when a model emits several JSON objects in one reply. */+const TURN_KEYS = new Set(['tool', 'done', 'thought', 'reply', 'intent'])++function looksLikeTurn(obj: Record<string, unknown>): boolean {+ return Object.keys(obj).some((k) => TURN_KEYS.has(k))+}+/** Parse one model reply into an AgentTurn. Tolerates markdown fences,- * leading prose and trailing junk (the same robustness ladder the- * assistant route uses). Returns null when no JSON object is found. */+ * leading prose, trailing junk and MULTI-OBJECT replies (a model that+ * emits `{"a":1}\n{"tool":…}` — a parsed object that looks like a+ * turn wins over one that doesn't; among turn-shaped candidates the+ * outermost/earliest wins, which is the original single-object+ * behavior). Returns null when no JSON object is found. */export function parseAgentTurn(raw: string): AgentTurn | null {const cleaned = raw.replace(/```(?:json)?/gi, '').trim()- const start = cleaned.indexOf('{')- if (start === -1) return null- let end = cleaned.lastIndexOf('}')- while (end > start) {- try {- const obj = JSON.parse(cleaned.slice(start, end + 1)) as Record<string, unknown>- if (obj && typeof obj === 'object') return obj as AgentTurn- } catch {- /* shrink the window and retry */+ // window scan: starts forward (outermost first), ends backward+ // (largest window first) — nested braces in strings are skipped+ // naturally because only windows that PARSE count+ let fallback: Record<string, unknown> | null = null+ for (let start = cleaned.indexOf('{'); start !== -1; start = cleaned.indexOf('{', start + 1)) {+ let end = cleaned.lastIndexOf('}')+ while (end > start) {+ let obj: Record<string, unknown> | null = null+ try {+ obj = JSON.parse(cleaned.slice(start, end + 1)) as Record<string, unknown>+ } catch {+ obj = null+ }+ if (obj && typeof obj === 'object') {+ if (looksLikeTurn(obj)) return obj as AgentTurn+ // remember the first parseable object as a fallback (a reply+ // with no turn keys at all — e.g. act-route {"reply":…} is+ // covered by TURN_KEYS, so this is genuinely unknown-shaped)+ if (!fallback) fallback = obj+ break // this start's largest window parsed; smaller windows+ // of the same start would be inner fragments — move on+ }+ end = cleaned.lastIndexOf('}', end - 1)}- end = cleaned.lastIndexOf('}', end - 1)}- return null+ return fallback ? (fallback as AgentTurn) : null}/** Serialize an event as an SSE line. */diff --git a/src/lib/agent/router.ts b/src/lib/agent/router.tsindex ababa41..9dac633 100644--- a/src/lib/agent/router.ts+++ b/src/lib/agent/router.ts@@ -33,17 +33,20 @@ export function heuristicIntent(message: string): AgentIntent | null {// multi-step briefs → planconst planSignals = [/\b(and|then|also|plus)\b.*\b(and|then|also|plus|with|including)\b/,- /\bcomplete (redesign|makeover|campaign|deck|poster)\b/,/\b(design|create|make|build)\s+(a|an|me|the)\b/,/\bfull\b.*\b(layout|design|page)\b/,- /\brebrand\b/,/\bposter\b.*\b(with|and|palette)\b/,/\blaunch\b.*\b(with|and|palette)\b/,+ /\bnew colors and fonts\b/,+ /\bcolors? and fonts?\b.*\b(new|change|swap)\b/,]- if (planSignals.filter((re) => re.test(m)).length >= 2) return 'plan'+ // strong plan intents fire on ONE match — a redesign/rebrand is+ // never a surgical edit no matter how it's phrased (harness catch)+ const strongPlan = /\b(complete|full|total)\s+(redesign|makeover|rebrand)\b|\brebrand\b|\bcomplete redesign\b/+ if (strongPlan.test(m) || planSignals.filter((re) => re.test(m)).length >= 2) return 'plan'// surgical single edits → actconst actSignals = [- /\b(make|set|change|turn|swap|move|align|delete|remove|add|bold|italic|bigger|smaller|recolor|color|colour)\b/,+ /\b(make|set|change|turn|swap|move|align|center|centre|delete|remove|add|bold|italic|underline|bigger|smaller|recolor|recolour|color|colour)\b/,/^\s*(bold|italic|underline)\s+(this|it|the)\b/,]if (actSignals.some((re) => re.test(m)) && m.split(/\s+/).length <= 18) return 'act'diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex e87e9dc..5173047 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -212,7 +212,7 @@ export const AGENT_TOOLS: AgentTool[] = [},{name: 'add_image',- description: 'Add an image: generate one with AI (prompt) — the only mode in v0.27. A placeholder appears immediately; the image swaps in when ready.',+ description: 'Add an image: generate one with AI (prompt) — the only mode in v0.27. A placeholder appears immediately; the image swaps in when ready. For real photos prefer add_stock_photo.',risk: 'write',argsSpec: '{prompt: string, x?: number, y?: number, width?: number}',sanitize: (args, ctx) => {@@ -236,6 +236,40 @@ export const AGENT_TOOLS: AgentTool[] = [}},},+ {+ // v0.27.3: the stock-photo rail (Pexels/Pixabay) existed as an app+ // but the agent couldn't reach it — "add a photo of a coffee shop"+ // forced AI generation. The client action runs the SAME search ++ // download + media-store path PhotosPanel uses (licensed, credited,+ // deduped), so the agent gets real photography with zero new trust+ // surface: the server never calls the stock APIs.+ name: 'add_stock_photo',+ description: 'Search licensed stock photography (Pexels/Pixabay) and place the best match: real photos, correct aspect ratio, attribution stored on the element. Use for concrete subjects (a coffee cup, a laptop, a mountain); use add_image for abstract/stylized art.',+ risk: 'write',+ argsSpec: '{query: string, orientation?: "landscape"|"portrait"|"square", x?: number, y?: number, width?: number}',+ sanitize: (args, ctx) => {+ const query = str(args, 'query', 120).trim()+ if (query.length < 2) return { ok: false, error: 'query must describe the photo (min 2 chars), e.g. "coffee cup on table".' }+ const orientation = enumVal(args, 'orientation', ['landscape', 'portrait', 'square'] as const, '' as never)+ const x = num(args, 'x')+ const y = num(args, 'y')+ const width = num(args, 'width')+ return {+ ok: true,+ actions: [+ {+ type: 'addStockPhoto',+ query,+ ...(orientation ? { orientation } : {}),+ ...(x !== null ? { x: clamp(x, 0, ctx.width) } : {}),+ ...(y !== null ? { y: clamp(y, 0, ctx.height) } : {}),+ ...(width !== null ? { width: clamp(width, 40, ctx.width) } : {}),+ },+ ],+ observation: `Stock photo search queued for "${query.slice(0, 60)}" — it downloads and appears in place.`,+ }+ },+ },{name: 'add_sticker',description: 'Add an emoji sticker (e.g. "🚀", "✨"). Fast, no AI generation.',@@ -424,13 +458,23 @@ export const AGENT_TOOLS: AgentTool[] = [},{name: 'distribute_elements',- description: 'Distribute ≥2 elements evenly along an axis.',+ description: 'Distribute ≥3 elements evenly along an axis.',risk: 'write',argsSpec: '{ids: string[], axis: "x"|"y"}',sanitize: (args, ctx) => {const { ids, error } = idList(args, ctx)if (error) return { ok: false, error }- if (ids.length < 2) return { ok: false, error: 'distribute needs at least 2 element ids.' }+ // the client's distributeElements needs ≥3 boxes — 2 has no gap+ // to even out (use align_elements or move_elements instead)+ if (ids.length < 3) {+ return {+ ok: false,+ error:+ ids.length === 2+ ? 'distribute needs 3+ element ids — with 2, use align_elements (e.g. mode "cy") or move_elements instead.'+ : 'distribute needs at least 3 element ids.',+ }+ }const axis = enumVal(args, 'axis', ['x', 'y'] as const, 'x')return {ok: true,@@ -520,17 +564,38 @@ export const AGENT_TOOLS: AgentTool[] = [},{name: 'add_page',- description: 'Append a new blank page.',+ description: 'Append a new blank page, then goto_page to edit it.',risk: 'write',argsSpec: '{}',- sanitize: () => ({ ok: true, actions: [{ type: 'addPage' }], observation: 'New page appended.' }),+ sanitize: () => ({ ok: true, actions: [{ type: 'addPage' }], observation: 'New page appended (last page). Use goto_page to switch to it before adding elements.' }),},{name: 'duplicate_page',description: 'Duplicate the current page (then edit the copy).',risk: 'write',argsSpec: '{}',- sanitize: () => ({ ok: true, actions: [{ type: 'duplicatePage' }], observation: 'Current page duplicated.' }),+ sanitize: () => ({ ok: true, actions: [{ type: 'duplicatePage' }], observation: 'Current page duplicated (the copy is the last page). Use goto_page to switch to it.' }),+ },+ {+ // v0.27.3: without page navigation, add_page was a dead end — the+ // agent could append a page but every subsequent tool still edited+ // the OLD page. goto_page closes the loop; the client action is+ // bounds-checked against the live document.+ name: 'goto_page',+ description: 'Switch the editor to a page by 1-based number, then call get_page_state — element ids are per-page and change with the switch. The context lists "editing page N" and one-line summaries of the others.',+ risk: 'read',+ argsSpec: '{page: number (1-based)}',+ sanitize: (args) => {+ const page = num(args, 'page')+ if (page === null || !Number.isInteger(page) || page < 1 || page > 60) {+ return { ok: false, error: 'page must be an integer 1–60 (1-based; the context shows how many pages exist).' }+ }+ return {+ ok: true,+ actions: [{ type: 'gotoPage', page }],+ observation: `Switched to page ${page}. The next get_page_state returns that page's elements — ids from other pages are invalid now.`,+ }+ },},// ── compound layout intelligence ───────────────────────────diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.tsindex 90dec71..82b119e 100644--- a/src/lib/design-actions.ts+++ b/src/lib/design-actions.ts@@ -413,8 +413,60 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCalreturn 'Page duplicated'}- case 'generateImage': {- const prompt = String(action.prompt ?? '').slice(0, 400).trim()+ // v0.27.3: the agent's goto_page tool — switching pages is what+ // makes add_page useful (before this, the agent could append a+ // page and then had no way to edit it). Bounds-checked here, not+ // in the tool: the model's page count may be stale.+ case 'gotoPage': {+ const s = useEditorStore.getState()+ const page = Math.round(Number(action.page))+ if (!Number.isFinite(page) || page < 1 || page > s.pages.length) {+ return `Page out of range — the design has ${s.pages.length} page(s)`+ }+ if (page - 1 === s.currentPage) return `Already on page ${page}`+ s.setCurrentPage(page - 1)+ s.clearSelection()+ return `Switched to page ${page}`+ }++ // v0.27.3 (agent): search licensed stock photography and place the+ // best match. Runs the SAME client path PhotosPanel uses — the+ // server's /api/stock-photo/search (provider keys stay server-side,+ // results sanitized + credited) and addStockPhoto's download →+ // media-store → credited element pipeline. No new trust surface.+ case 'addStockPhoto': {+ const query = String(action.query ?? '').trim().slice(0, 120)+ if (!query) return 'No photo query given'+ const res = await fetch('/api/stock-photo/search', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ query, count: 12 }),+ })+ const data = (await res.json().catch(() => ({}))) as {+ results?: { id: string; provider: string; width: number; height: number; download: string; alternates: string[]; credit: { provider: string; author: string; license: string; url: string } }[]+ error?: string+ }+ if (!res.ok || !Array.isArray(data.results) || data.results.length === 0) {+ return `No stock photo matched "${query}"${data.error ? ` (${data.error})` : ''} — try add_image to generate one`+ }+ // pick by orientation when asked, else the first (provider-ranked)+ const orientation = String(action.orientation ?? '')+ const wanted =+ orientation === 'portrait'+ ? (ratio) => ratio < 1+ : orientation === 'square'+ ? (ratio) => ratio >= 0.8 && ratio <= 1.25+ : orientation === 'landscape'+ ? (ratio) => ratio >= 1+ : null+ const pick =+ (wanted && data.results.find((r) => wanted(r.width / Math.max(1, r.height)))) ?? data.results[0]+ const { addStockPhoto: place } = await import('@/components/editor/add-element')+ await place(pick)+ return `Stock photo "${query}" added (credit: ${pick.credit.author}/${pick.credit.provider})`+ }++ case 'generateImage': { const prompt = String(action.prompt ?? '').slice(0, 400).trim()if (!prompt) return 'No image prompt'const res = await fetch('/api/ai/image', {method: 'POST',@@ -632,6 +684,8 @@ export function describeAction(action: DesignAction): string {case 'distributeElements': return 'Distribute evenly'case 'addPage': return 'Add a page'case 'duplicatePage': return 'Duplicate this page'+ case 'gotoPage': return `Go to page ${action.page}`+ case 'addStockPhoto': return `Stock photo: ${String(action.query ?? '').slice(0, 40)}`case 'generateImage': return `Generate image: ${String(action.prompt ?? '').slice(0, 42)}…`case 'suggestPalette': return 'Use this palette'case 'translate': return `Translate to ${action.language}`diff --git a/src/store/app-store.test.ts b/src/store/app-store.test.tsnew file mode 100644index 0000000..34055c3--- /dev/null+++ b/src/store/app-store.test.ts@@ -0,0 +1,45 @@+// @vitest-environment jsdom+// Unit tests for the app store's view transitions — v0.27.2: every+// view switch resets the window scroll. The swap is client-side+// (replaceState, no navigation), so without an explicit reset the+// browser keeps the old offset: a landing page scrolled to the FAQ+// opened the dashboard mid-page.++import { describe, it, expect, beforeEach, vi } from 'vitest'+import { useAppStore } from './app-store'+import type { DesignRecord } from '@/lib/types'++describe('app store view transitions', () => {+ const scrollTo = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ window.scrollTo = scrollTo as unknown as typeof window.scrollTo+ // reset the store between tests+ useAppStore.setState({ view: 'landing', pendingDesign: null })+ // history.replaceState on the same path is a no-op here+ vi.spyOn(history, 'replaceState').mockImplementation(() => {})+ })++ it('goDashboard resets the window scroll', () => {+ useAppStore.getState().goDashboard()+ expect(useAppStore.getState().view).toBe('dashboard')+ expect(scrollTo).toHaveBeenCalledWith(0, 0)+ })++ it('goLanding resets the window scroll', () => {+ useAppStore.setState({ view: 'dashboard' })+ useAppStore.getState().goLanding()+ expect(useAppStore.getState().view).toBe('landing')+ expect(scrollTo).toHaveBeenCalledWith(0, 0)+ })++ it('openEditor resets the window scroll and stages the design', () => {+ const design = { id: 'd1', name: 'Poster' } as unknown as DesignRecord+ useAppStore.getState().openEditor(design)+ const s = useAppStore.getState()+ expect(s.view).toBe('editor')+ expect(s.pendingDesign).toBe(design)+ expect(scrollTo).toHaveBeenCalledWith(0, 0)+ })+})diff --git a/src/store/app-store.ts b/src/store/app-store.tsindex 70c1cd7..045f498 100644--- a/src/store/app-store.ts+++ b/src/store/app-store.ts@@ -21,16 +21,25 @@ export const useAppStore = create<AppStore>((set) => ({// v0.11.4: the address bar follows the view — the editor lives at// /design/<id>, everything else resets to /. replaceState (not push)// because popstate is not routed in this SPA shell.+ // v0.27.2: every view switch also resets the window scroll — the+ // swap is client-side (no navigation), so without this the browser+ // keeps the offset: a landing page scrolled to the FAQ opened the+ // dashboard (or editor) mid-page. Instant, not smooth: the reset+ // must land before React commits the shorter view, or the browser+ // clamps a stale offset to the new page's max scroll.goLanding: () => {set({ view: 'landing' })replaceUrl('/')+ window.scrollTo(0, 0)},goDashboard: () => {set({ view: 'dashboard' })replaceUrl('/')+ window.scrollTo(0, 0)},openEditor: (design) => {set({ view: 'editor', pendingDesign: design })if (design?.id) replaceUrl(designPath(design.id))+ window.scrollTo(0, 0)},}))