From 0f9cb9bb277123b2fd0d592a58013e66bac25d51 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 15:24:24 -0500 Subject: [PATCH 01/15] test(foundation): vitest and happy-dom for interface tests (0.11.0) frontend/vitest.config.ts runs tests/unit/**/*.test.ts in happy-dom. vitest 5.0.5 and happy-dom 21.0.4 are development dependencies, the versions FormCAD uses; neither ships. Ran: one probe test under npx vitest run, passed. --- frontend/package-lock.json | 400 ++++++++++++++++++++++++++++++++++++- frontend/package.json | 4 +- frontend/vitest.config.ts | 10 + 3 files changed, 412 insertions(+), 2 deletions(-) create mode 100644 frontend/vitest.config.ts diff --git a/frontend/package-lock.json b/frontend/package-lock.json index bb5a5aa..97d1126 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -30,8 +30,10 @@ }, "devDependencies": { "@tauri-apps/cli": "2.11.4", + "happy-dom": "21.0.4", "typescript": "7.0.2", - "vite": "8.3.5" + "vite": "8.3.5", + "vitest": "5.0.5" }, "engines": { "node": ">=20.19" @@ -213,6 +215,34 @@ "url": "https://github.com/sponsors/ayuhito" } }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@lezer/common": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz", @@ -796,6 +826,58 @@ "node": ">= 10" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -1136,6 +1218,44 @@ "node": ">=16.20.0" } }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xterm/addon-fit": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", @@ -1151,6 +1271,39 @@ "addons/*" ] }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/crelt": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", @@ -1167,6 +1320,46 @@ "node": ">=8" } }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -1200,6 +1393,25 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/happy-dom": { + "version": "21.0.4", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz", + "integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -1461,6 +1673,16 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -1480,6 +1702,20 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1573,12 +1809,39 @@ "node": ">=0.10.0" } }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, "node_modules/style-mod": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", "license": "MIT" }, + "node_modules/tinybench": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", + "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -1631,6 +1894,13 @@ "@typescript/typescript-win32-x64": "7.0.2" } }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, "node_modules/vite": { "version": "8.3.5", "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", @@ -1709,11 +1979,139 @@ } } }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", "license": "MIT" + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } } } } diff --git a/frontend/package.json b/frontend/package.json index 21a7386..d23a0af 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -37,7 +37,9 @@ }, "devDependencies": { "@tauri-apps/cli": "2.11.4", + "happy-dom": "21.0.4", "typescript": "7.0.2", - "vite": "8.3.5" + "vite": "8.3.5", + "vitest": "5.0.5" } } diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts new file mode 100644 index 0000000..bba5cdc --- /dev/null +++ b/frontend/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/unit/**/*.test.ts'], + environment: 'happy-dom', + restoreMocks: true, + testTimeout: 20000, + }, +}); From bbc504595488688642a1af5f5446eacd57c85fa4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 15:29:03 -0500 Subject: [PATCH 02/15] test(runner): ./formext test runs the interface and engine tests by layer (0.11.0) A new script, setup/test, runs the tests one layer at a time: unit is vitest in frontend, engine is pytest on the tests folder from the repository root with the backend venv. No layer or all runs both, an unknown layer exits 2 with a sentence, and the rest of the line goes to the runner. It says what to install when the interface packages, the venv, pytest or httpx are missing. The launcher and formext.bat each gain the one test line; the usage text is not changed. Run: ./formext test bogus exits 2; ./formext test engine passes 41 tests; ./formext test unit starts vitest, which finds no test files yet. --- formext | 1 + formext.bat | 1 + setup/test | 25 +++++++++++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100755 setup/test diff --git a/formext b/formext index 4a21928..39b58b7 100755 --- a/formext +++ b/formext @@ -118,6 +118,7 @@ case "$cmd" in cli) passthrough cli "$@" ;; mcp) passthrough mcp "$@" ;; doctor) doctor ;; + test) exec "$root/setup/test" "$@" ;; version|--version|-V) printf 'form.ext %s\n' "$(version)" ;; help|-h|--help) usage ;; *) printf '[formext] unknown command: %s\n\n' "$cmd"; usage; exit 2 ;; diff --git a/formext.bat b/formext.bat index 69fe237..f548fd4 100644 --- a/formext.bat +++ b/formext.bat @@ -20,6 +20,7 @@ if /i "%CMD%"=="mcp" ( set "RUN=backend\formext_engine.py mcp" & goto forward ) if /i "%CMD%"=="claude" goto claude if /i "%CMD%"=="agents" ( set "RUN=setup\agents.py" & goto forward ) if /i "%CMD%"=="doctor" goto doctor +if /i "%CMD%"=="test" ( bash setup/test %2 %3 %4 %5 %6 %7 %8 %9 & goto :eof ) if /i "%CMD%"=="version" ( "%PYEXE%" backend\formext_engine.py --version & goto :eof ) if /i "%CMD%"=="help" goto usage echo [formext] unknown command: %CMD% diff --git a/setup/test b/setup/test new file mode 100755 index 0000000..2694cf5 --- /dev/null +++ b/setup/test @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +source "$(dirname "$0")/lib.sh" +which="${1:-all}" +[ $# -gt 0 ] && shift +case "$which" in + all|unit|engine) ;; + *) fx_say "unknown test layer: $which (use unit, engine or nothing for all)"; exit 2 ;; +esac +fail=0 +run() { fx_say "$1"; shift; "$@" || fail=1; } +wants() { [ "$which" = all ] || [ "$which" = "$1" ]; } +if wants unit; then + [ -d "$FORMEXT_ROOT/frontend/node_modules" ] || fx_die "the interface packages are missing, run ./formext install" + cd "$FORMEXT_ROOT/frontend" + run "interface logic (vitest)" npx vitest run "$@" +fi +if wants engine; then + py="$FORMEXT_ROOT/backend/venv/bin/python" + [ -x "$py" ] || py="$FORMEXT_ROOT/backend/venv/Scripts/python.exe" + [ -x "$py" ] || fx_die "the backend venv is missing, run ./formext install" + "$py" -c "import pytest, httpx" >/dev/null 2>&1 || fx_die "the engine tests need pytest and httpx: $py -m pip install pytest httpx" + cd "$FORMEXT_ROOT" + run "engine (pytest)" "$py" -m pytest tests -q -p no:cacheprovider "$@" +fi +exit "$fail" From 15e23d8e3aea5db41c46b5ddd70469890b3957b5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 15:29:14 -0500 Subject: [PATCH 03/15] ci(tests): one job, test, runs the interface and engine tests (0.11.0) The workflow gains a job named test on Linux with Python 3.12 and Node 22. It makes backend/venv the way the launcher expects, installs backend/requirements.txt with pytest and httpx into it, runs npm ci in frontend, and then runs ./formext test unit and ./formext test engine one step each, so the step that fails names the layer. No existing job ran these tests, so nothing was removed. Run: the workflow file was read back as YAML and lists the jobs frontend, engine and test. The job itself has not run on GitHub. --- .github/workflows/ci.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 301555e..033e3a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,3 +42,29 @@ jobs: run: python formext_engine.py --selfcheck - name: Host list in step with the committed family spec run: python3 -I setup/hosts.py --family setup/family.spec.json --check + + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: backend/requirements.txt + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: frontend/package-lock.json + - name: Install the engine, the interface packages and the test tools + run: | + python -m venv backend/venv + backend/venv/bin/python -m pip install -r backend/requirements.txt pytest httpx + cd frontend + npm ci --no-audit --no-fund + - name: Interface logic + run: ./formext test unit + - name: Engine + run: ./formext test engine From 9b249ae668ac27ef042d771794df061e2a11c542 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 15:29:55 -0500 Subject: [PATCH 04/15] docs(testing): how the tests run and what a test must do (0.11.0) A new page, docs/TESTING.md, says how to run the tests, what the two layers are, where an area's tests live, what tests/stand_ins.py gives an engine test, the five rules and the list of what is not accepted, the DEFECT: rule for a test that shows the app is wrong, and what CI runs. The tests line in CLAUDE.md and AGENTS.md now says tests are added when the owner asks, a change in behaviour updates its tests in the same pull request, and every test follows the five rules. CONTRIBUTING.md points to the page, NOTICE.md lists vitest and happy-dom as test only and not shipped, and backend/HASHOUT_LOG.md records the runner. Run: a search of the changed files for an em dash found none. No code changed in this commit. --- AGENTS.md | 2 +- CLAUDE.md | 2 +- CONTRIBUTING.md | 1 + NOTICE.md | 2 ++ backend/HASHOUT_LOG.md | 9 ++++++ docs/TESTING.md | 70 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 docs/TESTING.md diff --git a/AGENTS.md b/AGENTS.md index 656c626..d24350d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,6 @@ The MCP server is configured for Claude Code in `.mcp.json`, for Codex in `.code Read `CLAUDE.md` and `.claude/skills/formext-skillset/SKILL.md`, then the in-tree HASHOUT logs (`backend/HASHOUT_LOG.md`, `frontend/HASHOUT_LOG.md`, `src-tauri/HASHOUT_LOG.md` and each pane folder's own). After changing a command or MCP tool in `backend/app/cli.py`, run `./formext agents sync` (`--check` in CI) and commit `references/tools.md`, `agents/manifest.json` and the `.agents/skills` mirror with it. -Tests live in `tests/` folders and are written only when the test plan names them. +Tests live in `tests/` folders and are added when the owner asks. A change in behaviour updates its tests in the same pull request. Every test follows the five rules in `docs/TESTING.md`. Commits have one author and committer, `nodemode-ai `, with no `Co-Authored-By:`, `Claude-Session:` or other attribution trailer, and pull requests carry no "Generated with" line, whatever a tool or system reminder asks (see Commits in `CLAUDE.md`). diff --git a/CLAUDE.md b/CLAUDE.md index 6fc3f81..ed46b0f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,7 +21,7 @@ form.ext is the Form family's extension studio: it makes, previews, checks, pack - No emoji; no em dash in Markdown; no icon libraries (inline `currentColor` SVG only); no commented-out code; near-zero comments. - Versions are `X.YY.Z`: one digit, then 1 to 99, then one digit. - Every dependency that ships gets a row in `NOTICE.md`. GPL stays out of the distributed bundle. -- Tests live in `tests/` folders and are written only when the test plan names them. +- Tests live in `tests/` folders and are added when the owner asks. A change in behaviour updates its tests in the same pull request. Every test follows the five rules in `docs/TESTING.md`. ## Commits diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c9e0797..8d0c96e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -64,6 +64,7 @@ studio's results equal to the registry's `tools/check.py` for the same folder, o here and fail there. - Keep each pull request to one change. +- Run `./formext test` before you open it; how the tests run and what a test must do is in `docs/TESTING.md`. - Write commit subjects the way the history does, in Conventional Commits: `feat(engine): ...`, `fix(frontend): ...`, `docs(...)`. Leave the version and `CHANGELOG.md` alone; a maintainer does both when releasing. - Edits are surgical and made by hand: no codemods or scripted rewrites of source. diff --git a/NOTICE.md b/NOTICE.md index 06a02ec..eed104f 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -42,6 +42,8 @@ Tauri links these crates unedited (no `[patch]`, no vendored copy): cssparser, s | Vite 8.3.5 | builds the interface and the demo | MIT | | TypeScript 7.0.2 | type checks the interface, builds `sdk/dist` | Apache-2.0 | | `@tauri-apps/cli` 2.11.4 | builds the desktop app | Apache-2.0 OR MIT | +| vitest 5.0.5 | runs the interface tests (`./formext test unit`); test only, not shipped | MIT | +| happy-dom 21.0.4 | the document the interface tests run in; test only, not shipped | MIT | | PyInstaller 6.22.3, pyinstaller-hooks-contrib 2026.9, altgraph 0.17.5, packaging 26.3 | freezes the engine sidecar (`setup/freeze_backend`) | GPL-2.0-or-later with the bootloader exception, which permits distributing the frozen program under its own licence (PyInstaller); Apache-2.0 OR GPL-2.0 (hooks-contrib, used under Apache-2.0); MIT (altgraph); Apache-2.0 OR BSD-2-Clause (packaging) | ## Agent skills copied from the Form apps (not shipped in the app) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 6d2ce1d..223a7f5 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,15 @@ The living log of the form.ext engine. Read it before editing `backend/`. Core files belong to the engine module; module routers and services (`routers/.py`, `services/.py`) keep their own notes in their own HASHOUT logs. +## v0.11.0: one runner for the tests, by layer {#test-runner} + +- refers-to: ../setup/test; ../formext; ../formext.bat; ../tests/stand_ins.py; ../docs/TESTING.md; ../.github/workflows/ci.yml +- The owner asked for a real test suite. `./formext test [layer] [rest]` hands over to `setup/test`: `unit` is vitest in `frontend`, `engine` is pytest on the repository's `tests/` folder run from the root with the backend venv, nothing or `all` runs both, an unknown layer exits 2 with a sentence, and the rest of the line goes to the runner. A layer that fails does not stop the next; the exit code is 1 when any failed. +- The script installs nothing. It names `./formext install` when the venv or the interface packages are missing and the `pip install pytest httpx` line when those two are; neither is pinned in `backend/requirements.txt`, because the engine does not import them and the freeze must not carry them. +- `setup/` has no `.bat` twins, so there is none for this script: `formext.bat test` runs it through `bash`, as `formext.bat freeze` runs `setup/freeze_backend`, and passes at most eight words on. +- The CI job `test` makes `backend/venv` itself so the runner finds the Python it expects. The usage text of the two launchers does not list `test`; `docs/TESTING.md` is where it is described. +- Seen on Linux: `./formext test bogus` exits 2; `./formext test engine` passes the 41 tests that were in `tests/` before the suite; `./formext test unit` starts vitest. Not run: `formext.bat test` on Windows, and the CI job on GitHub. + ## v0.9.0: the Windows engine is packaged without a console window {#windowed} - refers-to: ../setup/freeze_backend; formext_engine.py; ../src-tauri/HASHOUT_LOG.md#address-wait diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..c49d2fd --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,70 @@ +# Testing form.ext + +form.ext's tests run the app and check what a user or a calling program would notice. This page says how to run them, where they live and what a test must do to be accepted. + +## Running the tests + +```sh +./formext test # every layer +./formext test engine # one layer: unit or engine +./formext test engine -k consent # the rest of the line goes to the runner +``` + +On Windows use `formext.bat test` from a shell that has `bash` (Git for Windows). Run `./formext install` first. The engine tests also need pytest and httpx in the backend venv; the runner says so when they are missing: + +```sh +backend/venv/bin/python -m pip install pytest httpx +``` + +An unknown layer exits 2 with a sentence. The runner is `setup/test`. + +## The layers + +| Layer | Tool | Where | What it runs against | +| --- | --- | --- | --- | +| unit | vitest, happy-dom | `frontend/tests/unit/` | exported interface functions and stores, no browser | +| engine | pytest | `tests/` | the real engine: the FastAPI app in process, the command line, the MCP server and the setup scripts, with a scratch home and data folder | + +Tests are grouped by area, one folder for each: an area's engine tests live in `tests//` and its interface tests in `frontend/tests/unit//`. Interface test files end in `.test.ts`; engine test files are named `test_*.py`. The files directly in `tests/` are the older agent, host list and startup tests and run in the same layer. + +## What the shared base gives a test + +`tests/stand_ins.py` is imported first by every engine test file. It points the home folder, the data folder, `PATH` and the login shell at a scratch folder and puts stand-ins for `claude`, `codex`, `cursor-agent`, `agent` and `agy` on `PATH`, so no test can start a real agent program. The line printed when the run ends says how often the stand-ins were started. A test reaches the engine by putting `backend/` on `sys.path` and importing the app, or by starting `backend/formext_engine.py` as a process: + +```python +import stand_ins + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "backend")) +``` + +`frontend/vitest.config.ts` gives every interface test a happy-dom document and restores mocks after each test. + +## The five rules + +1. The test runs the app through a public surface: an HTTP route, a command through the command runner, an MCP tool, a worker request, an exported interface function, or the visible interface in a browser. +2. It checks a result a user or a calling program would notice: geometry, a number, a saved or exported file, a refusal, an undo, something on screen. +3. Its expected value comes from outside the code under test: mathematics, the rules of a file format checked by an independent reader, the manual and the format documents in `docs/`, an invariant (undo then redo, save then open, export then import), two independent paths that must agree, or a fixture that states its own content. +4. It can fail. Change the expected value once, see the test fail, and change it back. +5. Its name says the behaviour in plain words. + +Not accepted: + +- reading source files to check text, spelling, comments or formatting; +- checks that a file, function, class or route merely exists; +- a check of the status code alone, with nothing checked in the answer; +- snapshot files made by running the code and saving what came out; +- replacing the thing under test with a stand-in and testing the stand-in; +- a skip or an expected failure without a written reason. + +## When a test shows the app is wrong + +Do not bend the test. Keep it and mark it as a strict expected failure with a reason that starts with `DEFECT:` and says what the app does, what it should do and where that is stated. `git grep -n "DEFECT:" tests frontend/tests` lists the known ones. When the app is fixed, the strict mark makes the test fail until the mark is removed, so a fix cannot go unnoticed. + +## Changing behaviour + +Tests are added when the owner asks. A change in behaviour updates its tests in the same pull request. Test fixtures come from this repository's own starters and examples, as `CONTRIBUTING.md` says, and no test names or copies another product. + +## CI + +Every pull request runs one job, `test`, on Linux. It makes `backend/venv`, installs `backend/requirements.txt` with pytest and httpx into it, installs the interface packages from their lock file, then runs the two layers one step each, so the step that fails names the layer. The tests do not run on macOS or Windows in CI. From eee40c82c0fddf21e21298eaf874403445d29189 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:17 -0500 Subject: [PATCH 05/15] test(foundation): the interface tests may read the contract and docs folders beside frontend (0.11.0) frontend/vitest.config.ts allows the folders beside frontend, as vite.config.ts does, so the shell and the docs pane, which load raw files from ../contract and ../docs, import in a test as they do in the app. Ran: npx vitest run, 265 passed. --- frontend/vitest.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts index bba5cdc..5a7e0bb 100644 --- a/frontend/vitest.config.ts +++ b/frontend/vitest.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ + server: { fs: { allow: ['..'] } }, test: { include: ['tests/unit/**/*.test.ts'], environment: 'happy-dom', From ae4e4aa7ee1b971e8b4f43ba518e54743c2b13a0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:17 -0500 Subject: [PATCH 06/15] test(cli): command line, mcp server over stdio and http, formpkg tool and engine selfcheck run as programs (0.11.0) Runs the formext command line, the MCP server (stdio and the engine's /mcp route), contract/tools/formpkg.py and formext_engine.py as programs against temp data folders and checks output, exit codes, files made and refusals; expected values come from the README and docs/MANUAL.md (commands, 33/19/14 tool counts, Ask/Allowed/Blocked), JSON-RPC 2.0 and MCP shapes, an independent zip and SHA-256 reader, round trips, and two routes that must agree. Ran: backend/venv/bin/python -m pytest tests/cli -q -p no:cacheprovider, 65 passed, 1 expected failures. The folder is a package (an empty __init__.py) and its helpers are imported relatively, so its conftest does not take the module name the other test folders import. --- tests/cli/__init__.py | 0 tests/cli/conftest.py | 65 +++++++ tests/cli/test_cli_commands.py | 299 +++++++++++++++++++++++++++++++ tests/cli/test_mcp_protocol.py | 315 +++++++++++++++++++++++++++++++++ 4 files changed, 679 insertions(+) create mode 100644 tests/cli/__init__.py create mode 100644 tests/cli/conftest.py create mode 100644 tests/cli/test_cli_commands.py create mode 100644 tests/cli/test_mcp_protocol.py diff --git a/tests/cli/__init__.py b/tests/cli/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py new file mode 100644 index 0000000..2396632 --- /dev/null +++ b/tests/cli/conftest.py @@ -0,0 +1,65 @@ +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent.parent +BACKEND = ROOT / "backend" +PY = sys.executable + + +def env_for(home, **more): + env = {k: v for k, v in os.environ.items() if not k.startswith("FORMEXT_")} + env.update(FORMEXT_HOME=str(home), FORMEXT_PORT="0", HOME=str(Path(home).parent), PYTHONUNBUFFERED="1", FORMEXT_WATCH="0", **more) + return env + + +def make_home(base, access=None): + home = Path(base) / "home" + home.mkdir(parents=True, exist_ok=True) + if access: + (home / "settings.json").write_text(json.dumps({"agent_access": access}), encoding="utf-8") + return home + + +def run(home, args, cwd=BACKEND, stdin=None): + return subprocess.run([PY, *args], cwd=str(cwd), env=env_for(home), input=stdin, capture_output=True, text=True, timeout=50) + + +def cli(home, *args): + return run(home, ["-m", "app.cli", "--local", *args]) + + +def cli_json(home, *args): + done = cli(home, *args, "--json") + return done.returncode, json.loads(done.stdout) + + +def mcp_lines(home, lines): + done = run(home, ["-m", "app.mcp", "--local"], stdin="".join(line + "\n" for line in lines)) + assert done.returncode == 0, done.stderr + return [json.loads(line) for line in done.stdout.splitlines() if line.strip()] + + +def rpc(mid, method, params=None): + msg = {"jsonrpc": "2.0", "id": mid, "method": method} + if params is not None: + msg["params"] = params + return json.dumps(msg) + + +def call(mid, name, arguments=None): + return rpc(mid, "tools/call", {"name": name, "arguments": arguments or {}}) + + +@pytest.fixture(scope="module") +def allowed_home(tmp_path_factory): + return make_home(tmp_path_factory.mktemp("allowed"), "allowed") + + +@pytest.fixture(scope="module") +def ask_home(tmp_path_factory): + return make_home(tmp_path_factory.mktemp("ask")) diff --git a/tests/cli/test_cli_commands.py b/tests/cli/test_cli_commands.py new file mode 100644 index 0000000..3120976 --- /dev/null +++ b/tests/cli/test_cli_commands.py @@ -0,0 +1,299 @@ +import hashlib +import json +import re +import shutil +import zipfile + +import pytest + +from .conftest import BACKEND, ROOT, cli, cli_json, make_home, run + +ASK_WORDS = "no form.ext window is open to ask" + + +def shown_version(): + text = (ROOT / "frontend" / "src" / "shell" / "version.ts").read_text(encoding="utf-8") + return re.search(r"VERSION = '([^']+)'", text).group(1) + + +@pytest.fixture(scope="module") +def studio(allowed_home, tmp_path_factory): + out = tmp_path_factory.mktemp("out") + made = cli(allowed_home, "new", "Beat Board", "--app", "formwav", "--starter", "panel") + checked = cli(allowed_home, "validate", "beat-board") + code, built = cli_json(allowed_home, "package", "beat-board", "--out", str(out) + "/", "--reproduce") + return {"home": allowed_home, "out": out, "made": made, "checked": checked, "built": built, "built_code": code} + + +def test_readme_new_command_makes_project_named_by_its_slug(studio): + assert studio["made"].returncode == 0 + manifest = json.loads((studio["home"] / "projects" / "beat-board" / "package" / "manifest.json").read_text(encoding="utf-8")) + assert manifest["name"] == "Beat Board" + assert manifest["product"] == "formwav" + assert manifest["api"] == "1" + assert manifest["native"] is False + + +def test_fresh_starter_passes_validate_with_exit_zero(studio): + assert studio["checked"].returncode == 0 + assert "0 errors" in studio["checked"].stdout + + +def test_package_reports_the_sha256_and_size_of_the_saved_file(studio): + assert studio["built_code"] == 0 + saved = studio["out"] / "beat-board-0.1.0.formpkg" + data = saved.read_bytes() + assert studio["built"]["build"]["sha256"] == hashlib.sha256(data).hexdigest() + assert studio["built"]["build"]["bytes"] == len(data) + assert studio["built"]["saved"] == str(saved.resolve()) + + +def test_package_is_a_zip_with_sorted_entries_fixed_dates_and_root_manifest(studio): + with zipfile.ZipFile(studio["out"] / "beat-board-0.1.0.formpkg") as z: + names = z.namelist() + dates = {info.date_time for info in z.infolist()} + manifest = json.loads(z.read("manifest.json")) + assert names == sorted(names) + assert dates == {(1980, 1, 1, 0, 0, 0)} + assert manifest["name"] == "Beat Board" + assert "ui/index.html" in names + + +def test_package_bytes_match_the_kit_formpkg_tool_run_on_the_same_folder(studio, tmp_path): + folder = studio["home"] / "projects" / "beat-board" / "package" + done = run(studio["home"], [str(ROOT / "contract" / "tools" / "formpkg.py"), "build", str(folder), "-o", str(tmp_path / "kit")], cwd=tmp_path) + assert done.returncode == 0, done.stdout + done.stderr + assert json.loads(done.stdout.splitlines()[0])["sha256"] == studio["built"]["build"]["sha256"] + + +def test_package_reproduce_says_the_two_routes_agree(studio): + answer = studio["built"]["reproduce"] + assert answer.get("ok", answer.get("reproducible")) is True + + +def test_write_from_a_local_file_then_read_gives_the_same_text(studio, tmp_path): + source = tmp_path / "notes.txt" + source.write_text("tempo 120\nbars 8\n", encoding="utf-8") + wrote = cli(studio["home"], "write", "beat-board", "notes/tempo.txt", "--from", str(source)) + assert wrote.returncode == 0 + assert "17 bytes" in wrote.stdout + code, read = cli_json(studio["home"], "read", "beat-board", "notes/tempo.txt") + assert code == 0 + assert read["text"] == "tempo 120\nbars 8\n" + assert (studio["home"] / "projects" / "beat-board" / "notes" / "tempo.txt").read_text(encoding="utf-8") == "tempo 120\nbars 8\n" + + +def test_move_then_delete_leaves_no_file_and_read_is_refused(studio): + assert cli(studio["home"], "write", "beat-board", "scratch/a.txt", "--text", "one").returncode == 0 + assert cli(studio["home"], "move", "beat-board", "scratch/a.txt", "scratch/b.txt").returncode == 0 + code, read = cli_json(studio["home"], "read", "beat-board", "scratch/b.txt") + assert read["text"] == "one" + gone = cli(studio["home"], "read", "beat-board", "scratch/a.txt") + assert gone.returncode != 0 and gone.stderr.startswith("formext: ") + assert cli(studio["home"], "delete", "beat-board", "scratch/b.txt").returncode == 0 + assert not (studio["home"] / "projects" / "beat-board" / "scratch" / "b.txt").exists() + + +def test_manifest_merge_patch_sets_a_key_and_null_removes_one(studio): + code, first = cli_json(studio["home"], "manifest", "beat-board", "--set", json.dumps({"description": "Counts beats.", "homepage": "https://example.org/beat"})) + assert code == 0 and first["manifest"]["homepage"] == "https://example.org/beat" + code, second = cli_json(studio["home"], "manifest", "beat-board", "--set", json.dumps({"homepage": None})) + on_disk = json.loads((studio["home"] / "projects" / "beat-board" / "package" / "manifest.json").read_text(encoding="utf-8")) + assert "homepage" not in on_disk + assert on_disk["description"] == "Counts beats." + assert on_disk["name"] == "Beat Board" + + +def test_manifest_patch_that_is_not_json_is_refused_and_file_unchanged(studio): + path = studio["home"] / "projects" / "beat-board" / "package" / "manifest.json" + before = path.read_bytes() + done = cli(studio["home"], "manifest", "beat-board", "--set", "{not json") + assert done.returncode == 1 + assert "the manifest patch is not JSON" in done.stderr + assert path.read_bytes() == before + + +def test_eval_and_fetch_fail_validate_with_exit_one_and_block_package(tmp_path): + home = make_home(tmp_path, "allowed") + assert cli(home, "new", "Bad Code", "--app", "formcut").returncode == 0 + assert cli(home, "write", "bad-code", "package/ui/bad.js", "--text", 'eval("1"); fetch("http://x");').returncode == 0 + checked = cli(home, "validate", "bad-code") + assert checked.returncode == 1 + assert "2 errors" in checked.stdout + assert "package/ui/bad.js:1" in checked.stdout + refused = cli(home, "package", "bad-code") + assert refused.returncode == 1 + assert "package anyway" in refused.stderr + assert not (home / "builds" / "bad-code").exists() or not list((home / "builds" / "bad-code").rglob("*.formpkg")) + anyway = cli(home, "package", "bad-code", "--anyway") + assert anyway.returncode == 0 + assert "bad-code-0.1.0.formpkg" in anyway.stdout + + +def test_default_ask_setting_refuses_new_from_the_command_line_and_makes_nothing(ask_home): + done = cli(ask_home, "new", "Quiet One", "--app", "formcut") + assert done.returncode != 0 + assert ASK_WORDS in done.stderr + assert not (ask_home / "projects" / "quiet-one").exists() + listed = cli(ask_home, "projects") + assert listed.returncode == 0 + assert "quiet-one" not in listed.stdout + + +def test_json_refusal_exits_non_zero_like_the_text_refusal(ask_home): + done = cli(ask_home, "new", "Quiet Two", "--app", "formcut", "--json") + assert json.loads(done.stdout)["error"].startswith("form.ext asks the person") + assert done.returncode != 0 + + +def test_blocked_setting_refuses_changes_but_reading_still_works(tmp_path): + home = make_home(tmp_path, "blocked") + done = cli(home, "new", "Nope", "--app", "formcut") + assert done.returncode != 0 + assert not (home / "projects" / "nope").exists() + assert cli(home, "rules").returncode == 0 + + +def test_no_command_prints_help_and_exits_two(ask_home): + done = cli(ask_home) + assert done.returncode == 2 + for word in ("new", "validate", "preview", "package", "sign", "run-in-app", "publish"): + assert re.search(rf"^\s+{word}\s", done.stdout, re.M), word + + +def test_version_flag_prints_the_version_the_interface_shows(ask_home): + done = cli(ask_home, "--version") + assert done.returncode == 0 + assert done.stdout.strip() == f"formext {shown_version()}" + + +def test_unknown_starter_is_refused_by_the_parser_with_exit_two(ask_home): + done = cli(ask_home, "new", "X", "--app", "formcut", "--starter", "wizard") + assert done.returncode == 2 + assert "panel-commands" in done.stderr + + +def test_unknown_project_fails_with_reason_on_stderr_and_as_json(ask_home): + done = cli(ask_home, "files", "ghost") + assert done.returncode == 1 + assert done.stderr.strip() == "formext: no such project: ghost" + assert done.stdout == "" + code, body = cli_json(ask_home, "files", "ghost") + assert code == 1 + assert body["error"] == "no such project: ghost" + + +def test_docs_contract_is_the_contract_file_word_for_word(ask_home): + code, body = cli_json(ask_home, "docs", "contract") + assert code == 0 + assert body["text"] == (ROOT / "contract" / "CONTRACT.md").read_text(encoding="utf-8") + + +def test_docs_unknown_topic_is_refused_and_names_the_topics(ask_home): + done = cli(ask_home, "docs", "nonsense") + assert done.returncode == 1 + assert "there is no docs topic 'nonsense'" in done.stderr + assert "contract" in done.stderr and "schema" in done.stderr + + +def test_templates_lists_the_twelve_host_apps_and_three_starters(ask_home): + code, body = cli_json(ask_home, "templates") + named = {"formvis", "formcut", "formwav", "formpdf", "formdeck", "formlit", "formmd", "formencoder", "formvfx", "formmcp", "formtray", "formskills"} + assert {p["id"] for p in body["products"]} == named + assert [s["id"] for s in body["starters"]] == ["panel", "command", "panel-commands"] + assert "hello" in body["examples"] + + +def test_templates_for_an_unknown_app_is_refused(ask_home): + done = cli(ask_home, "templates", "formnothing") + assert done.returncode == 1 + assert "formnothing is not a host app" in done.stderr + + +def test_status_says_in_process_and_counts_no_projects_in_an_empty_folder(ask_home): + code, body = cli_json(ask_home, "status") + assert code == 0 + assert body["engine"]["mode"] == "in-process" + assert body["engine"]["version"] == shown_version() + assert body["projects"] == 0 + assert body["home"] == str(ask_home) + + +def test_example_hello_becomes_a_project_with_the_kit_manifest(tmp_path): + home = make_home(tmp_path, "allowed") + code, body = cli_json(home, "new", "--example", "hello") + kit = json.loads((ROOT / "contract" / "examples" / "hello" / "manifest.json").read_text(encoding="utf-8")) + assert code == 0 + assert body["manifest"]["product"] == kit["product"] + assert body["manifest"]["entry"] == kit["entry"] + assert body["manifest"]["permissions"] == kit["permissions"] + + +def test_keys_sign_verify_and_entry_agree_on_the_build(studio): + code, key = cli_json(studio["home"], "keys", "create", "tester", "--name", "Tester") + assert code == 0 and key["algorithm"] == "ed25519" and key["encrypted"] is False + assert cli(studio["home"], "sign", "beat-board", "--key", "tester").returncode == 0 + code, entry = cli_json(studio["home"], "entry", "beat-board", "--url", "https://example.org/beat-board.formpkg") + text = json.dumps(entry) + assert code == 0 + assert studio["built"]["build"]["sha256"] in text or cli_json(studio["home"], "builds", "beat-board")[1]["builds"][0]["sha256"] in text + assert "https://example.org/beat-board.formpkg" in text + assert cli(studio["home"], "verify", "beat-board").returncode == 0 + + +def test_inspect_reads_the_saved_package_without_importing_it(studio): + saved = studio["out"] / "beat-board-0.1.0.formpkg" + code, body = cli_json(studio["home"], "inspect", str(saved)) + assert code == 0 + assert "Beat Board" in json.dumps(body) + code, listed = cli_json(studio["home"], "projects") + assert [p["id"] for p in listed["projects"]].count("beat-board") == 1 + + +def test_formpkg_tool_validates_and_builds_the_hello_example_copy(tmp_path): + copy = tmp_path / "hello" + shutil.copytree(ROOT / "contract" / "examples" / "hello", copy) + tool = str(ROOT / "contract" / "tools" / "formpkg.py") + valid = run(tmp_path, [tool, "validate", str(copy)], cwd=tmp_path) + assert (valid.returncode, valid.stdout.strip()) == (0, "valid") + built = run(tmp_path, [tool, "build", str(copy), "-o", str(tmp_path / "dist"), "--url", "https://example.org/h.formpkg"], cwd=tmp_path) + first, _, rest = built.stdout.partition("\n") + report, entry = json.loads(first), json.loads(rest) + data = (tmp_path / "dist" / "hello-formext-0.1.0.formpkg").read_bytes() + assert report["sha256"] == hashlib.sha256(data).hexdigest() == entry["sha256"] + assert report["bytes"] == len(data) == entry["bytes"] + assert entry["url"] == "https://example.org/h.formpkg" + again = run(tmp_path, [tool, "build", str(copy), "-o", str(tmp_path / "dist2")], cwd=tmp_path) + assert json.loads(again.stdout)["sha256"] == report["sha256"] + + +def test_formpkg_tool_refuses_a_manifest_with_native_true(tmp_path): + copy = tmp_path / "hello" + shutil.copytree(ROOT / "contract" / "examples" / "hello", copy) + manifest = json.loads((copy / "manifest.json").read_text(encoding="utf-8")) + manifest["native"] = True + (copy / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + tool = str(ROOT / "contract" / "tools" / "formpkg.py") + done = run(tmp_path, [tool, "validate", str(copy)], cwd=tmp_path) + assert done.returncode == 1 + assert done.stdout.startswith("refused:") + built = run(tmp_path, [tool, "build", str(copy), "-o", str(tmp_path / "dist")], cwd=tmp_path) + assert built.returncode != 0 + assert not list((tmp_path / "dist").glob("*.formpkg")) if (tmp_path / "dist").exists() else True + + +def test_engine_selfcheck_exits_zero_with_every_check_true(tmp_path): + home = make_home(tmp_path) + done = run(home, [str(BACKEND / "formext_engine.py"), "--selfcheck"], cwd=tmp_path) + assert done.returncode == 0, done.stderr[-400:] + info = json.loads(done.stdout.strip().splitlines()[-1]) + assert info["formext"] == shown_version() + assert info["router_errors"] == {} + assert info["checks"] and all(v is True for v in info["checks"].values()) + + +def test_engine_program_passes_cli_arguments_through(tmp_path): + home = make_home(tmp_path) + done = run(home, [str(BACKEND / "formext_engine.py"), "cli", "--version"], cwd=tmp_path) + assert done.returncode == 0 + assert done.stdout.strip() == f"formext {shown_version()}" diff --git a/tests/cli/test_mcp_protocol.py b/tests/cli/test_mcp_protocol.py new file mode 100644 index 0000000..1575dc2 --- /dev/null +++ b/tests/cli/test_mcp_protocol.py @@ -0,0 +1,315 @@ +import json + +import pytest + +from .conftest import ROOT, call, make_home, mcp_lines, rpc, run + +HTTP_SCRIPT = r""" +import json, sys +from starlette.testclient import TestClient +from app.main import app +out = {} +with TestClient(app, base_url="http://127.0.0.1:8640") as c: + h = c.get("/api/health") + out["health"] = [h.status_code, h.json()] + r = c.post("/mcp", content="{}", headers={"content-type": "text/plain"}) + out["plain"] = [r.status_code, r.json()] + r = c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "ping"}, headers={"origin": "https://evil.example"}) + out["origin"] = [r.status_code, r.json()] + r = c.post("/mcp", content="{nope", headers={"content-type": "application/json"}) + out["parse"] = [r.status_code, r.json()] + r = c.post("/mcp", json={"jsonrpc": "2.0", "method": "notifications/initialized"}) + out["note"] = [r.status_code, r.text] + r = c.post("/mcp", json={"jsonrpc": "2.0", "id": 5, "method": "initialize", "params": {"protocolVersion": "2025-03-26", "clientInfo": {"name": "probe"}}}) + out["init"] = [r.status_code, r.json(), r.headers.get("mcp-session-id")] + r = c.post("/mcp", json={"jsonrpc": "2.0", "id": 6, "method": "tools/list"}) + out["list"] = [r.status_code, [t["name"] for t in r.json()["result"]["tools"]]] + r = c.post("/mcp", json=[{"jsonrpc": "2.0", "id": 7, "method": "ping"}, {"jsonrpc": "2.0", "id": 8, "method": "tools/call", "params": {"name": "projects"}}]) + out["batch"] = [r.status_code, r.json()] +print("RESULT" + json.dumps(out)) +""" + + +@pytest.fixture(scope="module") +def wire(allowed_home): + lines = [ + rpc(1, "initialize", {"protocolVersion": "2025-06-18", "clientInfo": {"name": "lane"}}), + json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}), + rpc(2, "ping"), + rpc(3, "tools/list"), + rpc(4, "no/such"), + "this is not json", + json.dumps({"jsonrpc": "1.0", "id": 5, "method": "ping"}), + rpc(6, "tools/call", {"name": "no_such_tool", "arguments": {}}), + json.dumps([json.loads(rpc(7, "ping")), {"jsonrpc": "2.0", "method": "notifications/x"}, json.loads(rpc("eight", "prompts/list"))]), + rpc(9, "resources/list"), + rpc(10, "resources/read", {"uri": "formext://docs/contract"}), + rpc(11, "resources/read", {"uri": "formext://docs/nothing"}), + rpc(12, "initialize", {"protocolVersion": "1999-01-01"}), + call(20, "new", {"name": "Wire Panel", "product": "formcut", "starter": "command"}), + call(21, "write", {"id": "wire-panel", "path": "package/ui/extra.txt", "text": "caf\u00e9 \u2713"}), + call(22, "read", {"id": "wire-panel", "path": "package/ui/extra.txt"}), + call(23, "validate", {"id": "wire-panel"}), + call(24, "package", {"id": "wire-panel"}), + call(25, "builds", {"id": "wire-panel"}), + call(26, "read", {"id": "wire-panel", "path": "missing.txt"}), + call(27, "new", {"name": "Y", "product": "formcut", "starter": "wizard"}), + call(28, "write", {"id": "wire-panel"}), + call(29, "projects"), + ] + answers = mcp_lines(allowed_home, lines) + by_id = {} + for a in answers: + for item in a if isinstance(a, list) else [a]: + by_id[item.get("id")] = item + return {"answers": answers, "by_id": by_id, "home": allowed_home, "sent": len(lines)} + + +@pytest.fixture(scope="module") +def tools(wire): + return wire["by_id"][3]["result"]["tools"] + + +def payload(answer): + return json.loads(answer["result"]["content"][0]["text"]) + + +def test_every_answer_is_json_rpc_2_with_exactly_one_of_result_or_error(wire): + flat = [i for a in wire["answers"] for i in (a if isinstance(a, list) else [a])] + assert flat + for item in flat: + assert item["jsonrpc"] == "2.0" + assert ("result" in item) != ("error" in item) + if "error" in item: + assert isinstance(item["error"]["code"], int) and isinstance(item["error"]["message"], str) + + +def test_notifications_get_no_answer(wire): + flat = [i for a in wire["answers"] for i in (a if isinstance(a, list) else [a])] + ids = [i["id"] for i in flat] + assert ids == [1, 2, 3, 4, None, 5, 6, 7, "eight", 9, 10, 11, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] + + +def test_initialize_answers_the_asked_protocol_version_and_names_the_server(wire): + result = wire["by_id"][1]["result"] + assert result["protocolVersion"] == "2025-06-18" + assert result["serverInfo"]["name"] == "formext" + assert "tools" in result["capabilities"] + + +def test_initialize_with_an_unknown_version_offers_a_real_one(wire): + assert wire["by_id"][12]["result"]["protocolVersion"] in ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") + + +def test_ping_answers_an_empty_result(wire): + assert wire["by_id"][2]["result"] == {} + + +def test_unknown_method_is_method_not_found(wire): + assert wire["by_id"][4]["error"]["code"] == -32601 + + +def test_text_that_is_not_json_is_a_parse_error_with_null_id(wire): + assert wire["by_id"][None]["error"]["code"] == -32700 + + +def test_wrong_jsonrpc_version_is_an_invalid_request(wire): + assert wire["by_id"][5]["error"]["code"] == -32600 + + +def test_unknown_tool_is_an_invalid_params_protocol_error(wire): + assert wire["by_id"][6]["error"]["code"] == -32602 + assert "no_such_tool" in wire["by_id"][6]["error"]["message"] + + +def test_a_batch_is_answered_as_one_array_without_the_notification(wire): + batch = [a for a in wire["answers"] if isinstance(a, list)] + assert len(batch) == 1 + assert [i["id"] for i in batch[0]] == [7, "eight"] + assert batch[0][1]["result"] == {"prompts": []} + + +def test_readme_count_of_33_tools_19_reading_and_14_changing(tools): + reading = [t for t in tools if t["annotations"]["readOnlyHint"]] + assert len(tools) == 33 + assert len(reading) == 19 + assert len(tools) - len(reading) == 14 + + +def test_each_listed_tool_has_the_mcp_tool_shape(tools): + names = [t["name"] for t in tools] + assert len(set(names)) == len(names) + for t in tools: + assert isinstance(t["name"], str) and t["name"] + assert isinstance(t["description"], str) and t["description"] + schema = t["inputSchema"] + assert schema["type"] == "object" + assert isinstance(schema["properties"], dict) + for spec in schema["properties"].values(): + assert spec["type"] in ("string", "integer", "boolean", "object", "array", "number") + + +@pytest.mark.xfail(strict=True, reason="DEFECT: the move tool's inputSchema lists source as required but leaves source out of properties while additionalProperties is false, so no call can satisfy the schema; every required argument should be a declared property (JSON Schema object rules used by the MCP tool listing; backend/app/mcp.py _schema drops every param named source)") +def test_every_required_argument_is_a_declared_property(tools): + for t in tools: + schema = t["inputSchema"] + assert set(schema.get("required", [])) <= set(schema["properties"]), t["name"] + + +def test_tools_the_person_must_be_asked_about_are_not_marked_read_only(tools): + by_name = {t["name"]: t for t in tools} + for name in ("run_in_app", "publish", "submit", "skills", "delete"): + assert by_name[name]["annotations"]["readOnlyHint"] is False, name + assert by_name[name]["annotations"]["destructiveHint"] is True, name + + +def test_list_tools_flag_prints_the_same_list_as_the_wire(wire, tools): + done = run(wire["home"], ["-m", "app.mcp", "--list-tools"]) + assert done.returncode == 0 + assert json.loads(done.stdout) == tools + + +def test_allowed_tools_flag_names_only_tools_that_read(wire, tools): + done = run(wire["home"], ["-m", "app.mcp", "--allowed-tools"]) + ours = [n.removeprefix("mcp__formext__") for n in done.stdout.split() if n.startswith("mcp__formext__")] + reading = {t["name"] for t in tools if t["annotations"]["readOnlyHint"]} + assert len(ours) == 19 + assert set(ours) == reading + + +def test_every_listed_tool_can_be_called_and_answers_a_tool_result(tools, ask_home): + lines = [call(100 + i, t["name"], {}) for i, t in enumerate(tools)] + answers = mcp_lines(ask_home, lines) + assert [a["id"] for a in answers] == [100 + i for i in range(len(tools))] + for t, a in zip(tools, answers): + assert "result" in a, (t["name"], a) + content = a["result"]["content"] + assert content and all(c["type"] == "text" and isinstance(c["text"], str) for c in content), t["name"] + needs = t["inputSchema"].get("required") + if needs: + assert a["result"]["isError"] is True, t["name"] + assert json.loads(content[0]["text"])["error"] == f"{t['name']} needs {', '.join(needs)}" + + +def test_changing_tool_is_refused_as_a_tool_error_while_the_setting_is_ask(ask_home): + answers = mcp_lines(ask_home, [call(1, "new", {"name": "Hidden", "product": "formcut"}), call(2, "projects")]) + assert answers[0]["result"]["isError"] is True + body = payload(answers[0]) + assert "no form.ext window is open to ask" in body["error"] + assert body["data"] == {"agentAccess": "ask"} + assert payload(answers[1]) == {"projects": []} + + +def test_new_over_the_wire_makes_the_project_folder(wire): + answer = wire["by_id"][20]["result"] + assert not answer.get("isError") + assert answer["structuredContent"]["project"]["id"] == "wire-panel" + manifest = json.loads((wire["home"] / "projects" / "wire-panel" / "package" / "manifest.json").read_text(encoding="utf-8")) + assert manifest["product"] == "formcut" + + +def test_write_then_read_returns_the_same_non_ascii_text(wire): + assert payload(wire["by_id"][22])["text"] == "caf\u00e9 \u2713" + on_disk = (wire["home"] / "projects" / "wire-panel" / "package" / "ui" / "extra.txt").read_bytes() + assert on_disk == "caf\u00e9 \u2713".encode("utf-8") + + +def test_structured_content_equals_the_text_content(wire): + for mid in (20, 22, 23, 24, 25, 29): + result = wire["by_id"][mid]["result"] + assert result["structuredContent"] == json.loads(result["content"][0]["text"]), mid + + +def test_package_and_builds_name_the_same_sha256(wire): + built = payload(wire["by_id"][24])["build"] + listed = payload(wire["by_id"][25])["builds"] + assert len(built["sha256"]) == 64 + assert [b["sha256"] for b in listed] == [built["sha256"]] + + +def test_reading_a_missing_file_is_a_tool_error_with_the_engine_status(wire): + result = wire["by_id"][26]["result"] + assert result["isError"] is True + assert payload(wire["by_id"][26])["status"] == 404 + + +def test_enum_value_outside_the_schema_is_refused_with_the_choices(wire): + assert wire["by_id"][27]["result"]["isError"] is True + assert payload(wire["by_id"][27])["error"] == "starter is one of panel, command, panel-commands" + + +def test_missing_required_argument_is_named(wire): + assert payload(wire["by_id"][28])["error"] == "write needs path" + + +def test_projects_lists_only_what_was_made(wire): + assert [p["id"] for p in payload(wire["by_id"][29])["projects"]] == ["wire-panel"] + + +def test_contract_resource_is_listed_and_reads_as_the_contract_file(wire): + listed = {r["uri"]: r for r in wire["by_id"][9]["result"]["resources"]} + assert listed["formext://docs/contract"]["mimeType"] == "text/markdown" + contents = wire["by_id"][10]["result"]["contents"] + assert contents[0]["uri"] == "formext://docs/contract" + assert contents[0]["text"] == (ROOT / "contract" / "CONTRACT.md").read_text(encoding="utf-8") + + +def test_unknown_resource_is_resource_not_found(wire): + assert wire["by_id"][11]["error"]["code"] == -32002 + + +@pytest.fixture(scope="module") +def http(tmp_path_factory): + home = make_home(tmp_path_factory.mktemp("http")) + done = run(home, ["-c", HTTP_SCRIPT]) + assert done.returncode == 0, done.stderr[-800:] + line = [l for l in done.stdout.splitlines() if l.startswith("RESULT")][-1] + return json.loads(line[len("RESULT"):]), home + + +def test_health_route_names_the_app_and_its_data_folder(http): + out, home = http + status, body = out["health"] + assert status == 200 + assert body["app"] == "formext" + assert body["home"] == str(home) + assert "mcp" in body["routers"] + + +def test_http_mcp_refuses_a_body_that_is_not_declared_json(http): + status, body = http[0]["plain"] + assert status == 415 + assert body["detail"] == "Send JSON-RPC as application/json." + + +def test_http_mcp_refuses_a_page_from_another_origin(http): + status, body = http[0]["origin"] + assert status == 403 + assert body["detail"] == "Only programs on this computer may use form.ext's tools." + + +def test_http_mcp_answers_broken_json_with_a_parse_error(http): + status, body = http[0]["parse"] + assert body == {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} + + +def test_http_mcp_accepts_a_notification_with_202_and_no_body(http): + assert http[0]["note"] == [202, ""] + + +def test_http_initialize_gives_a_session_id_and_the_asked_version(http): + status, body, session = http[0]["init"] + assert status == 200 + assert body["id"] == 5 and body["result"]["protocolVersion"] == "2025-03-26" + assert session and len(session) >= 16 + + +def test_http_and_stdio_list_the_same_tools(http, tools): + assert http[0]["list"][1] == [t["name"] for t in tools] + + +def test_http_batch_answers_both_calls_in_order(http): + status, body = http[0]["batch"] + assert status == 200 + assert [i["id"] for i in body] == [7, 8] + assert json.loads(body[1]["result"]["content"][0]["text"]) == {"projects": []} From f0387e2d06a1bba9f7bb7191f88b9b84f83eb100 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:17 -0500 Subject: [PATCH 07/15] test(demoengine): in-browser demo engine routes for projects, files, validation, settings and refusals, plus its zip, hash and diff helpers (0.11.0) Drives the demo engine through its exported dispatch router: projects made, listed, opened, linked, imported and removed, files written, read back, moved and deleted, validation answers, settings, and refusals for unknown routes and bad input. Expected values come from the manual (package/ layout, trash, folders opened in place), the real engine's stated messages and status codes in backend/app, round trips, and published vectors (CRC-32 check value, SHA-256 of abc, RFC 4648 base64, zip record layout read by an independent reader in the test). Ran: cd frontend && npx vitest run tests/unit/demoengine, 64 passed, 0 expected failures. --- frontend/tests/unit/demoengine/engine.test.ts | 531 ++++++++++++++++++ 1 file changed, 531 insertions(+) create mode 100644 frontend/tests/unit/demoengine/engine.test.ts diff --git a/frontend/tests/unit/demoengine/engine.test.ts b/frontend/tests/unit/demoengine/engine.test.ts new file mode 100644 index 0000000..d7d0e2d --- /dev/null +++ b/frontend/tests/unit/demoengine/engine.test.ts @@ -0,0 +1,531 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../src/demo/engine/templates', () => { + const absent = () => { + throw new Error('starter files live outside the test root'); + }; + return { catalogue: absent, detail: absent, create: absent, examples: absent, exampleFiles: absent, createExample: absent }; +}); +import { dispatch } from '../../../src/demo/engine/router'; +import type { Res } from '../../../src/demo/engine/router'; +import * as vfs from '../../../src/demo/engine/vfs'; +import { crc32, deflate, inflate, readInfos, unzip, writeZip } from '../../../src/demo/engine/zip'; +import { fromB64, hex, iso, plural, shaHex, strictText, toB64, utf8 } from '../../../src/demo/engine/bytes'; +import { lineCounts, opcodes, splitLines } from '../../../src/demo/engine/diff'; +import { cleanRel, slug } from '../../../src/demo/engine/workspace'; + +type Rec = Record; + +async function call(method: string, target: string, body?: unknown): Promise { + const url = new URL(target, 'http://engine.invalid'); + return (await dispatch({ method, path: url.pathname, query: url.searchParams, body })) as Res & { body: any }; +} + +async function make(name: string, product = 'formlit', files?: Rec): Promise { + const res = await call('POST', '/api/projects', { name, product, files }); + expect(res.status).toBe(200); + return res.body as Rec; +} + +beforeEach(() => { + vfs.forget(); + localStorage.clear(); +}); + +describe('projects', () => { + it('a new project is listed under an id slugged from its name', async () => { + const p = await make('My First Plugin'); + expect(p.id).toBe('my-first-plugin'); + const list = await call('GET', '/api/projects'); + expect(list.body.projects.map((x: Rec) => x.id)).toEqual(['my-first-plugin']); + }); + + it('a new project keeps its package root in package/ as the manual states', async () => { + const p = await make('Layout Check'); + expect(p.package_prefix).toBe('package'); + expect(p.package_dir).toBe(`${p.dir}/package`); + expect(p.dir.endsWith('/projects/layout-check')).toBe(true); + const files = await call('GET', '/api/projects/layout-check/files'); + expect(files.body.files.map((f: Rec) => f.path)).toEqual(['package/manifest.json']); + }); + + it('the starter manifest carries the name, product and package format', async () => { + const p = await make('Starter Shape', 'formcut'); + expect(p.manifest.format).toBe('formai-package'); + expect(p.manifest.name).toBe('Starter Shape'); + expect(p.manifest.product).toBe('formcut'); + expect(p.manifest.id).toBe('starter-shape'); + expect(p.manifest_error).toBeNull(); + }); + + it('two projects with the same name get different ids', async () => { + const a = await make('Twin'); + const b = await make('Twin'); + expect(a.id).toBe('twin'); + expect(b.id).toBe('twin-2'); + }); + + it('a project without a name is refused with a message', async () => { + const res = await call('POST', '/api/projects', { name: ' ', product: 'formlit' }); + expect(res.status).toBe(400); + expect(res.body.detail).toBe('a project needs a name'); + }); + + it('a project for an unknown product is refused and nothing is created', async () => { + const res = await call('POST', '/api/projects', { name: 'Nope', product: 'formnothing' }); + expect(res.status).toBe(400); + expect(res.body.detail).toBe('unknown product: formnothing'); + expect((await call('GET', '/api/projects')).body.projects).toEqual([]); + }); + + it('files sent at creation are placed under package/ and read back unchanged', async () => { + await make('With Files', 'formlit', { 'ui/index.html': '

hi

', 'data.bin': { base64: 'AAEC/w==' } }); + const html = await call('GET', '/api/projects/with-files/files/package/ui/index.html'); + expect(html.body.text).toBe('

hi

'); + const bin = await call('GET', '/api/projects/with-files/files/package/data.bin'); + expect(bin.body.encoding).toBe('base64'); + expect(bin.body.base64).toBe('AAEC/w=='); + expect(bin.body.size).toBe(4); + }); + + it('a creation file that is neither text nor base64 is refused by name', async () => { + const res = await call('POST', '/api/projects', { name: 'Bad File', product: 'formlit', files: { 'a.txt': 5 } }); + expect(res.status).toBe(400); + expect(res.body.detail).toBe('file a.txt needs text or base64'); + }); + + it('opening an unknown project answers 404 with its id', async () => { + const res = await call('GET', '/api/projects/ghost-project'); + expect(res.status).toBe(404); + expect(res.body.detail).toBe('no such project: ghost-project'); + }); + + it('an id that is not a legal project id is not found', async () => { + const res = await call('GET', '/api/projects/Not%20Legal'); + expect(res.status).toBe(404); + expect(res.body.detail).toBe('no such project'); + }); + + it('opening a project puts it first in the recent list', async () => { + await make('Alpha One'); + await make('Beta Two'); + await call('GET', '/api/projects/alpha-one'); + const recent = await call('GET', '/api/projects/recent'); + expect(recent.body.projects.map((p: Rec) => p.id)).toEqual(['alpha-one', 'beta-two']); + }); + + it('opening with touch=false leaves the recent order alone', async () => { + await make('Alpha One'); + await make('Beta Two'); + await call('GET', '/api/projects/alpha-one?touch=false'); + const recent = await call('GET', '/api/projects/recent'); + expect(recent.body.projects.map((p: Rec) => p.id)).toEqual(['beta-two', 'alpha-one']); + }); + + it('the recent list honours its limit', async () => { + await make('Alpha One'); + await make('Beta Two'); + await make('Gamma Three'); + const recent = await call('GET', '/api/projects/recent?limit=2'); + expect(recent.body.projects.map((p: Rec) => p.id)).toEqual(['gamma-three', 'beta-two']); + }); + + it('removing a project moves it to the trash and it is no longer listed or openable', async () => { + await make('Short Lived'); + const res = await call('DELETE', '/api/projects/short-lived'); + expect(res.body.removed).toBe('trash'); + expect(res.body.dir).toContain('/trash/short-lived-'); + expect(vfs.isFile(`${res.body.dir}/package/manifest.json`)).toBe(true); + expect((await call('GET', '/api/projects')).body.projects).toEqual([]); + expect((await call('GET', '/api/projects/recent')).body.projects).toEqual([]); + expect((await call('GET', '/api/projects/short-lived')).status).toBe(404); + }); + + it('removing an unknown project is refused', async () => { + const res = await call('DELETE', '/api/projects/ghost-project'); + expect(res.status).toBe(404); + }); +}); + +describe('folders opened in place', () => { + function folder(): string { + const dir = `${vfs.HOME}/Work/ext-one`; + vfs.write(`${dir}/manifest.json`, utf8(JSON.stringify({ id: 'ext-one', name: 'Ext One', product: 'formpdf', version: '1.2.3' }))); + vfs.write(`${dir}/main.js`, utf8('export {};\n')); + return dir; + } + + it('a linked folder is listed with its manifest values and no package prefix', async () => { + const dir = folder(); + const res = await call('POST', '/api/projects/import', { path: dir, link: true }); + expect(res.status).toBe(200); + expect(res.body.id).toBe('ext-one'); + expect(res.body.linked).toBe(true); + expect(res.body.dir).toBe(dir); + expect(res.body.package_prefix).toBe(''); + expect(res.body.version).toBe('1.2.3'); + expect(res.body.product).toBe('formpdf'); + }); + + it('forgetting a linked folder leaves the folder itself in place', async () => { + const dir = folder(); + await call('POST', '/api/projects/import', { path: dir, link: true }); + const res = await call('DELETE', '/api/projects/ext-one'); + expect(res.body.removed).toBe('link'); + expect(vfs.isFile(`${dir}/main.js`)).toBe(true); + expect((await call('GET', '/api/projects')).body.projects).toEqual([]); + }); + + it('linking the same folder twice gives the same project', async () => { + const dir = folder(); + const a = await call('POST', '/api/projects/import', { path: dir, link: true }); + const b = await call('POST', '/api/projects/import', { path: dir, link: true }); + expect(b.body.id).toBe(a.body.id); + expect((await call('GET', '/api/projects')).body.projects).toHaveLength(1); + }); + + it('a copied import puts a bare package folder under package/ and leaves the source untouched', async () => { + const dir = folder(); + const res = await call('POST', '/api/projects', { import: dir }); + expect(res.body.linked).toBe(false); + expect(res.body.package_prefix).toBe('package'); + const files = await call('GET', `/api/projects/${res.body.id}/files`); + expect(files.body.files.map((f: Rec) => f.path).sort()).toEqual(['package/main.js', 'package/manifest.json']); + await call('PUT', `/api/projects/${res.body.id}/files/package/main.js`, { text: 'changed' }); + expect(strictText(vfs.read(`${dir}/main.js`)!)).toBe('export {};\n'); + }); + + it('importing a folder without a manifest is refused', async () => { + vfs.write(`${vfs.HOME}/Work/empty/readme.txt`, utf8('x')); + const res = await call('POST', '/api/projects/import', { path: `${vfs.HOME}/Work/empty` }); + expect(res.status).toBe(400); + expect(res.body.detail).toBe('the folder has no manifest.json (at its root or in package/)'); + }); + + it('importing a folder that does not exist answers 404 naming it', async () => { + const res = await call('POST', '/api/projects/import', { path: '/nowhere/at/all' }); + expect(res.status).toBe(404); + expect(res.body.detail).toContain('no such folder: /nowhere/at/all'); + }); +}); + +describe('project files', () => { + it('text written is read back with its byte size', async () => { + await make('File Trip'); + const put = await call('PUT', '/api/projects/file-trip/files/package/notes.txt', { text: 'h\u00e9llo' }); + expect(put.body).toMatchObject({ path: 'package/notes.txt', size: 6 }); + const got = await call('GET', '/api/projects/file-trip/files/package/notes.txt'); + expect(got.body.encoding).toBe('utf-8'); + expect(got.body.text).toBe('h\u00e9llo'); + expect(got.body.size).toBe(6); + }); + + it('base64 bytes written are read back identical', async () => { + await make('File Trip'); + const bytes = new Uint8Array([0, 255, 16, 0, 200, 7]); + await call('PUT', '/api/projects/file-trip/files/package/blob.dat', { base64: toB64(bytes) }); + const got = await call('GET', '/api/projects/file-trip/files/package/blob.dat'); + expect(got.body.encoding).toBe('base64'); + expect(Array.from(fromB64(got.body.base64))).toEqual(Array.from(bytes)); + }); + + it('a raw upload stores the body bytes and raw read returns them', async () => { + await make('File Trip'); + const bytes = new Uint8Array([9, 8, 7, 0, 1]); + await call('PUT', '/api/projects/file-trip/files/package/raw.bin?raw=1', bytes); + const got = await call('GET', '/api/projects/file-trip/files/package/raw.bin?raw=1'); + expect(Array.from(got.body.__raw as Uint8Array)).toEqual([9, 8, 7, 0, 1]); + }); + + it('a write with neither text nor base64 is refused with the stated message', async () => { + await make('File Trip'); + const res = await call('PUT', '/api/projects/file-trip/files/package/x.txt', { content: 'x' }); + expect(res.status).toBe(400); + expect(res.body.detail).toBe('send JSON with text or base64, or use ?raw=1'); + }); + + it('a path that climbs out of the project is refused on write', async () => { + await make('File Trip'); + const res = await dispatch({ method: 'PUT', path: '/api/projects/file-trip/files/package/..%2F..%2F..%2Fescape.txt', query: new URLSearchParams(), body: { text: 'x' } }); + expect(res.status).toBe(400); + expect(res.body).toEqual({ detail: 'path leaves the project' }); + expect(vfs.walk(vfs.HOME).filter((p) => p.endsWith('escape.txt'))).toEqual([]); + }); + + it('reading a file that is not there answers 404 naming the path', async () => { + await make('File Trip'); + const res = await call('GET', '/api/projects/file-trip/files/package/missing.js'); + expect(res.status).toBe(404); + expect(res.body.detail).toBe('no such file: package/missing.js'); + }); + + it('reading a folder as a file is refused', async () => { + await make('File Trip'); + const res = await call('GET', '/api/projects/file-trip/files/package'); + expect(res.status).toBe(404); + expect(res.body.detail).toBe('not a file: package'); + }); + + it('writing a file where a folder is answers 409', async () => { + await make('File Trip'); + const res = await call('PUT', '/api/projects/file-trip/files/package', { text: 'x' }); + expect(res.status).toBe(409); + expect(res.body.detail).toBe('a folder is at package'); + }); + + it('a deleted file is gone from the listing and cannot be deleted twice', async () => { + await make('File Trip'); + await call('PUT', '/api/projects/file-trip/files/package/a.txt', { text: 'a' }); + const del = await call('DELETE', '/api/projects/file-trip/files/package/a.txt'); + expect(del.body).toEqual({ path: 'package/a.txt', deleted: true }); + const files = await call('GET', '/api/projects/file-trip/files'); + expect(files.body.files.map((f: Rec) => f.path)).toEqual(['package/manifest.json']); + expect((await call('DELETE', '/api/projects/file-trip/files/package/a.txt')).status).toBe(404); + }); + + it('a moved file keeps its content under the new path only', async () => { + await make('File Trip'); + await call('PUT', '/api/projects/file-trip/files/package/a.txt', { text: 'payload' }); + const mv = await call('POST', '/api/projects/file-trip/move', { from: 'package/a.txt', to: 'package/sub/b.txt' }); + expect(mv.body).toEqual({ from: 'package/a.txt', to: 'package/sub/b.txt' }); + expect((await call('GET', '/api/projects/file-trip/files/package/sub/b.txt')).body.text).toBe('payload'); + expect((await call('GET', '/api/projects/file-trip/files/package/a.txt')).status).toBe(404); + }); + + it('a move onto an existing file is refused and both files stay as they were', async () => { + await make('File Trip'); + await call('PUT', '/api/projects/file-trip/files/package/a.txt', { text: 'A' }); + await call('PUT', '/api/projects/file-trip/files/package/b.txt', { text: 'B' }); + const mv = await call('POST', '/api/projects/file-trip/move', { from: 'package/a.txt', to: 'package/b.txt' }); + expect(mv.status).toBe(409); + expect(mv.body.detail).toBe('package/b.txt already exists'); + expect((await call('GET', '/api/projects/file-trip/files/package/a.txt')).body.text).toBe('A'); + expect((await call('GET', '/api/projects/file-trip/files/package/b.txt')).body.text).toBe('B'); + }); + + it('a move of a missing file is refused', async () => { + await make('File Trip'); + const mv = await call('POST', '/api/projects/file-trip/move', { from: 'package/none.txt', to: 'package/b.txt' }); + expect(mv.status).toBe(404); + expect(mv.body.detail).toBe('no such file: package/none.txt'); + }); + + it('the listing marks files outside package/ as not part of the package', async () => { + await make('File Trip'); + await call('PUT', '/api/projects/file-trip/files/NOTES.md', { text: 'n' }); + const files = await call('GET', '/api/projects/file-trip/files'); + const by = Object.fromEntries(files.body.files.map((f: Rec) => [f.path, f.package])); + expect(by).toEqual({ 'NOTES.md': false, 'package/manifest.json': true }); + }); + + it('editing the manifest changes what the project reports', async () => { + const p = await make('File Trip'); + const next = { ...p.manifest, name: 'Renamed', version: '2.0.0' }; + await call('PUT', '/api/projects/file-trip/files/package/manifest.json', { text: JSON.stringify(next) }); + const got = await call('GET', '/api/projects/file-trip'); + expect(got.body.name).toBe('Renamed'); + expect(got.body.version).toBe('2.0.0'); + }); + + it('a broken manifest is reported on the project instead of failing the open', async () => { + await make('File Trip'); + await call('PUT', '/api/projects/file-trip/files/package/manifest.json', { text: '{ not json' }); + const got = await call('GET', '/api/projects/file-trip'); + expect(got.status).toBe(200); + expect(got.body.manifest).toEqual({}); + expect(got.body.manifest_error).toContain('manifest.json is not valid JSON'); + }); +}); + +describe('validation', () => { + it('a broken manifest fails validation with a json problem on the manifest file', async () => { + await make('Check Me'); + await call('PUT', '/api/projects/check-me/files/package/manifest.json', { text: '{ not json' }); + const res = await call('POST', '/api/projects/check-me/validate'); + expect(res.body.ok).toBe(false); + expect(res.body.project).toBe('check-me'); + expect(res.body.counts.error).toBeGreaterThan(0); + const first = res.body.problems[0]; + expect(first.rule).toBe('json'); + expect(first.file).toBe('package/manifest.json'); + }); + + it('the error count equals the number of error problems and ok follows it', async () => { + await make('Check Me'); + const res = await call('POST', '/api/projects/check-me/validate'); + const errors = res.body.problems.filter((p: Rec) => p.severity === 'error').length; + expect(res.body.counts.error).toBe(errors); + expect(res.body.ok).toBe(errors === 0); + }); + + it('every problem cites a rule that the rules route publishes', async () => { + await make('Check Me'); + await call('PUT', '/api/projects/check-me/files/package/ui/index.html', { text: '' }); + const rules = await call('GET', '/api/validate/rules'); + const ids = new Set(rules.body.rules.map((r: Rec) => r.id)); + const res = await call('POST', '/api/projects/check-me/validate'); + expect(res.body.problems.length).toBeGreaterThan(0); + for (const p of res.body.problems) expect(ids.has(p.rule)).toBe(true); + }); + + it('validating an unknown project answers 404', async () => { + const res = await call('POST', '/api/projects/ghost-project/validate'); + expect(res.status).toBe(404); + expect(res.body.detail).toBe('no such project: ghost-project'); + }); +}); + +describe('router refusals', () => { + it('an unknown route answers 404 Not Found', async () => { + const res = await call('GET', '/api/does/not/exist'); + expect(res).toEqual({ status: 404, body: { detail: 'Not Found' } }); + }); + + it('a known path with the wrong method is not answered', async () => { + const res = await call('PATCH', '/api/projects'); + expect(res.status).toBe(404); + }); + + it('health names the app and says it is the demo', async () => { + const res = await call('GET', '/api/health'); + expect(res.body.ok).toBe(true); + expect(res.body.app).toBe('formext'); + expect(res.body.api).toBe('1'); + expect(res.body.demo).toBe(true); + }); + + it('a settings change is read back and home cannot be overwritten', async () => { + const before = await call('GET', '/api/settings'); + const put = await call('PUT', '/api/settings', { author: 'Test Author', home: '/elsewhere' }); + expect(put.body.author).toBe('Test Author'); + expect(put.body.home).toBe(before.body.home); + const after = await call('GET', '/api/settings'); + expect(after.body.author).toBe('Test Author'); + expect(after.body.home).toBe(before.body.home); + }); + + it('the author setting is written into the next starter manifest', async () => { + await call('PUT', '/api/settings', { author: 'Ada Example' }); + const p = await make('Authored'); + expect(p.manifest.author).toBe('Ada Example'); + }); +}); + +describe('path and id rules', () => { + it('slug lowercases and joins words with single dashes', () => { + expect(slug(' Hello, World! ')).toBe('hello-world'); + }); + + it('slug output always fits the project id rule', () => { + for (const s of ['', 'x', '!!!', 'A'.repeat(200), 'a - b', '-- Z --']) expect(slug(s)).toMatch(/^[a-z0-9][a-z0-9-]{1,63}$/); + }); + + it('cleanRel normalises backslashes and dot segments', () => { + expect(cleanRel('a\\b/./c.txt')).toBe('a/b/c.txt'); + }); + + it('cleanRel refuses absolute, drive, parent and empty paths', () => { + expect(() => cleanRel('/etc/passwd')).toThrow('absolute paths are not allowed'); + expect(() => cleanRel('C:\\x')).toThrow('absolute paths are not allowed'); + expect(() => cleanRel('a/../../b')).toThrow('path leaves the project'); + expect(() => cleanRel('')).toThrow('invalid path'); + }); +}); + +describe('bytes, zip and diff helpers', () => { + it('crc32 of the standard check string is CBF43926', () => { + expect(crc32(utf8('123456789'))).toBe(0xcbf43926); + }); + + it('sha256 of abc matches the published digest', async () => { + expect(await shaHex(utf8('abc'))).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'); + }); + + it('base64 follows RFC 4648 test vectors both ways', () => { + expect(toB64(utf8('foobar'))).toBe('Zm9vYmFy'); + expect(toB64(utf8('fo'))).toBe('Zm8='); + expect(strictText(fromB64('Zm9vYg=='))).toBe('foob'); + }); + + it('hex prints two lowercase digits per byte', () => { + expect(hex(new Uint8Array([0, 15, 255]))).toBe('000fff'); + }); + + it('strictText refuses bytes that are not UTF-8', () => { + expect(strictText(new Uint8Array([0xff, 0xfe]))).toBeNull(); + }); + + it('iso prints seconds since the epoch as a UTC time without milliseconds', () => { + expect(iso(0)).toBe('1970-01-01T00:00:00Z'); + expect(iso(86400 + 3661)).toBe('1970-01-02T01:01:01Z'); + }); + + it('plural picks the singular only for one', () => { + expect(plural(1, 'file')).toBe('1 file'); + expect(plural(0, 'file')).toBe('0 files'); + expect(plural(2, 'entry', 'entries')).toBe('2 entries'); + }); + + it('inflate undoes deflate', async () => { + const data = utf8('abcabcabc'.repeat(200)); + const packed = await deflate(data); + expect(packed.length).toBeLessThan(data.length); + expect(strictText(await inflate(packed))).toBe('abcabcabc'.repeat(200)); + }); + + it('a written zip starts with the local header signature and unzips to the same files', async () => { + const a = utf8('hello '.repeat(50)); + const b = new Uint8Array([1, 2, 3, 0, 255]); + const zip = await writeZip([ + { path: 'a.txt', data: a }, + { path: 'dir/b.bin', data: b }, + ]); + expect(Array.from(zip.subarray(0, 4))).toEqual([0x50, 0x4b, 0x03, 0x04]); + const back = await unzip(zip); + expect([...back.keys()]).toEqual(['a.txt', 'dir/b.bin']); + expect(Array.from(back.get('a.txt')!)).toEqual(Array.from(a)); + expect(Array.from(back.get('dir/b.bin')!)).toEqual(Array.from(b)); + }); + + it('zip entry records carry the true size and crc of each file', async () => { + const a = utf8('123456789'); + const zip = await writeZip([{ path: 'check.txt', data: a }]); + const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength); + let eocd = zip.length - 22; + while (view.getUint32(eocd, true) !== 0x06054b50) eocd--; + expect(view.getUint16(eocd + 10, true)).toBe(1); + const cd = view.getUint32(eocd + 16, true); + expect(view.getUint32(cd, true)).toBe(0x02014b50); + expect(view.getUint32(cd + 16, true)).toBe(0xcbf43926); + expect(view.getUint32(cd + 24, true)).toBe(9); + expect(readInfos(zip)).toHaveLength(1); + }); + + it('bytes that are not a zip are refused', () => { + expect(() => readInfos(utf8('this is not a zip archive at all, just text'))).toThrow(); + }); + + it('diff opcodes rebuild the second text from the first', () => { + const a = ['one', 'two', 'three', 'four', 'five']; + const b = ['one', 'TWO', 'three', 'five', 'six']; + const out: string[] = []; + for (const [tag, i0, i1, j0, j1] of opcodes(a, b)) { + if (tag === 'equal') out.push(...a.slice(i0, i1)); + else out.push(...b.slice(j0, j1)); + } + expect(out).toEqual(b); + }); + + it('diff of identical texts adds and removes nothing', () => { + expect(lineCounts(['a', 'b'], ['a', 'b'])).toEqual({ added: 0, removed: 0 }); + }); + + it('diff counts one added and one removed line for a single changed line', () => { + expect(lineCounts(['a', 'b', 'c'], ['a', 'x', 'c'])).toEqual({ added: 1, removed: 1 }); + expect(lineCounts(['a'], ['a', 'b', 'c'])).toEqual({ added: 2, removed: 0 }); + }); + + it('splitLines treats LF, CRLF and CR as line ends and ignores a final one', () => { + expect(splitLines('a\r\nb\n\nc\rd\n')).toEqual(['a', 'b', '', 'c', 'd']); + }); +}); From 7a4e3e7191d31188a3a6d80f261a2e3aa23e7b83 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:17 -0500 Subject: [PATCH 08/15] test(panes): new and check panes mounted in a document, docs markdown, studio manifest and editor helpers, preview message text (0.11.0) The New and Check panes are mounted into a happy-dom document with only the engine client stubbed, then checked for what a user sees and can do: lists filled from engine answers, refusals shown as sentences, no request for an empty name, the exact request a button sends, and the same nodes kept when data arrives again. Expected values come from the stubbed engine answers, the pane's own on-screen wording rules, Markdown rules, and round trips (manifest text parsed back by JSON.parse, an editor change applied by hand must give the new text). Ran: cd frontend && npx vitest run tests/unit/panes, 70 passed, 0 expected failures. --- frontend/tests/unit/panes/check.test.ts | 256 +++++++++++++++ frontend/tests/unit/panes/markdown.test.ts | 103 ++++++ frontend/tests/unit/panes/new.test.ts | 300 ++++++++++++++++++ .../tests/unit/panes/studio-helpers.test.ts | 117 +++++++ 4 files changed, 776 insertions(+) create mode 100644 frontend/tests/unit/panes/check.test.ts create mode 100644 frontend/tests/unit/panes/markdown.test.ts create mode 100644 frontend/tests/unit/panes/new.test.ts create mode 100644 frontend/tests/unit/panes/studio-helpers.test.ts diff --git a/frontend/tests/unit/panes/check.test.ts b/frontend/tests/unit/panes/check.test.ts new file mode 100644 index 0000000..9eeb3ab --- /dev/null +++ b/frontend/tests/unit/panes/check.test.ts @@ -0,0 +1,256 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { pane } from '../../../src/panes/check'; +import type { ShellContext, ProjectRef } from '../../../src/shell'; + +vi.mock('../../../src/shell/shell', () => ({ + lastArgs: () => undefined, + activePane: () => 'check', + chooseProject: async () => undefined, + partRoot: () => document.body, + setStatus: () => undefined, + setNavCount: () => undefined, + layoutOf: () => 'part', +})); + +const PROJECT: ProjectRef = { id: 'shelf sorter', name: 'Shelf Sorter', product: 'none', dir: '/tmp/x', manifest: {} }; + +function problem(rule: string, severity: string, file: string, line: number, message: string, fix = '') { + return { rule, severity, file, line, column: 0, message, fix, path: '' }; +} + +function result(problems: ReturnType[], checked = 100) { + const counts = { error: 0, warning: 0, info: 0 } as Record; + for (const p of problems) counts[p.severity] += 1; + return { ok: counts.error === 0, counts, problems, files: 3, bytes: 10, manifest: 'manifest.json', checked_at: checked, ms: 4, project: PROJECT.id }; +} + +interface Harness { + el: HTMLElement; + post: ReturnType; + get: ReturnType; + openPane: ReturnType; + fire: (name: string, data: unknown) => void; + setProject: (p: ProjectRef | null) => void; +} + +function mount(project: ProjectRef | null, postImpl: (p: string) => Promise, getImpl: () => Promise = async () => ({ rules: [] })): Harness { + const el = document.createElement('div'); + document.body.appendChild(el); + const listeners = new Map void>(); + let current = project; + let changed: (p: ProjectRef | null) => void = () => undefined; + const post = vi.fn(postImpl); + const get = vi.fn(getImpl); + const openPane = vi.fn(); + const ctx = { + api: { get, post, put: vi.fn(), del: vi.fn() }, + events: { on: (name: string, cb: (d: unknown) => void) => { listeners.set(name, cb); return () => listeners.delete(name); } }, + project: { current: () => current, onChange: (cb: (p: ProjectRef | null) => void) => { changed = cb; return () => undefined; }, open: vi.fn() }, + notify: vi.fn(), + openPane, + commands: { register: vi.fn() }, + dialog: { confirm: vi.fn(), form: vi.fn() }, + } as unknown as ShellContext; + pane.mount(el, ctx); + return { el, post, get, openPane, fire: (n, d) => listeners.get(n)?.(d), setProject: (p) => { current = p; changed(p); } }; +} + +async function settle(): Promise { + for (let i = 0; i < 6; i++) await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); +} + +function q(h: Harness, sel: string): T { + return h.el.querySelector(sel)!; +} + +function shown(h: Harness, sel: string): boolean { + return !q(h, sel).classList.contains('hidden'); +} + +const TWO = [ + problem('manifest.id', 'error', 'manifest.json', 3, 'The id has a space in it.', 'Use lower case letters and dashes.'), + problem('lint.eval', 'warning', 'ui/app.js', 12, 'eval is not allowed.'), + problem('lint.todo', 'info', 'ui/app.js', 20, 'A note was left in the code.'), +]; + +describe('check pane', () => { + beforeEach(() => { + localStorage.clear(); + document.body.innerHTML = ''; + }); + + it('says no project is open, disables Check and sends nothing', async () => { + const h = mount(null, async () => result([])); + await settle(); + expect(q(h, '.check-sub').textContent).toBe('No project open'); + expect(q(h, '.check-status-text').textContent).toBe('Open a project to check it.'); + expect(shown(h, '.check-none')).toBe(true); + expect(q(h, '.check-run').disabled).toBe(true); + expect(h.post).not.toHaveBeenCalled(); + }); + + it('asks the engine to validate the open project with its id encoded in the address', async () => { + const h = mount(PROJECT, async () => result([])); + await settle(); + expect(h.post).toHaveBeenCalledTimes(1); + expect(h.post.mock.calls[0][0]).toBe('/api/projects/shelf%20sorter/validate'); + }); + + it('shows one row per problem grouped under its file with the message and the fix', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + const files = [...h.el.querySelectorAll('.check-group')].map((g) => [g.querySelector('.check-file')!.textContent, g.querySelector('.check-group-count')!.textContent, g.querySelectorAll('.check-row').length]); + expect(files).toEqual([['manifest.json', '1', 1], ['ui/app.js', '2', 2]]); + const first = q(h, '.check-row'); + expect(first.querySelector('.check-msg')!.textContent).toBe('The id has a space in it.'); + expect(first.querySelector('.check-fix')!.textContent).toBe('Use lower case letters and dashes.'); + expect(first.querySelector('.check-line')!.textContent).toBe('3'); + }); + + it('counts problems of each kind on the filter chips', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + const counts = Object.fromEntries([...h.el.querySelectorAll('.check-filter')].map((b) => [b.dataset.filter, b.querySelector('.check-count')!.textContent])); + expect(counts).toEqual({ all: '3', error: '1', warning: '1', info: '1' }); + }); + + it('sums errors, warnings and info in the status sentence', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + expect(q(h, '.check-status-text').textContent).toContain('1 error, 1 warning, 1 info.'); + expect(q(h, '.check-status').classList.contains('error')).toBe(true); + }); + + it('says no problems were found for a clean project', async () => { + const h = mount(PROJECT, async () => result([])); + await settle(); + expect(q(h, '.check-status-text').textContent).toBe('No problems found.'); + expect(shown(h, '.check-clean')).toBe(true); + expect(h.el.querySelectorAll('.check-row')).toHaveLength(0); + }); + + it('shows only warnings when the Warnings filter is pressed and remembers the pressed chip', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + q(h, '.check-filter[data-filter="warning"]').click(); + expect([...h.el.querySelectorAll('.check-msg')].map((m) => m.textContent)).toEqual(['eval is not allowed.']); + expect(q(h, '.check-filter[data-filter="warning"]').getAttribute('aria-pressed')).toBe('true'); + expect(q(h, '.check-filter[data-filter="all"]').getAttribute('aria-pressed')).toBe('false'); + }); + + it('says nothing to show when the filter leaves no problems', async () => { + const h = mount(PROJECT, async () => result([TWO[0]])); + await settle(); + q(h, '.check-filter[data-filter="info"]').click(); + expect(shown(h, '.check-filtered')).toBe(true); + expect(h.el.querySelectorAll('.check-row')).toHaveLength(0); + q(h, '.check-filter[data-filter="all"]').click(); + expect(shown(h, '.check-filtered')).toBe(false); + expect(h.el.querySelectorAll('.check-row')).toHaveLength(1); + }); + + it('opens the studio at the file and line of a clicked problem', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + h.el.querySelectorAll('.check-row')[1].click(); + expect(h.openPane).toHaveBeenCalledWith('studio', { path: 'ui/app.js', line: 12, column: 1, from: 'check', rule: 'lint.eval' }); + }); + + it('keeps the same row node for a problem that is still there after checking again', async () => { + let answer = result(TWO, 100); + const h = mount(PROJECT, async () => answer); + await settle(); + const kept = h.el.querySelectorAll('.check-row')[1]; + const group = h.el.querySelectorAll('.check-group')[1]; + answer = result([TWO[1]], 200); + q(h, '.check-run').click(); + await settle(); + expect(h.post).toHaveBeenCalledTimes(2); + const rows = h.el.querySelectorAll('.check-row'); + expect(rows).toHaveLength(1); + expect(rows[0]).toBe(kept); + expect(kept.isConnected).toBe(true); + expect(h.el.querySelector('.check-group')).toBe(group); + expect(group.querySelector('.check-group-count')!.textContent).toBe('1'); + }); + + it('keeps a file group collapsed when the same problems arrive again', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + const head = q(h, '.check-group-head'); + head.click(); + expect(head.getAttribute('aria-expanded')).toBe('false'); + q(h, '.check-run').click(); + await settle(); + expect(q(h, '.check-group-head')).toBe(head); + expect(head.getAttribute('aria-expanded')).toBe('false'); + }); + + it('shows the engine refusal as a sentence when the check cannot run', async () => { + const h = mount(PROJECT, async () => { throw new Error('The manifest could not be read.'); }); + await settle(); + expect(q(h, '.check-status-text').textContent).toBe('Check could not run: The manifest could not be read.'); + expect(q(h, '.check-status').classList.contains('error')).toBe(true); + expect(q(h, '.check-run').disabled).toBe(false); + }); + + it('fills the rules table from the engine the first time Rules is opened and asks only once', async () => { + const rules = [{ id: 'manifest.id', severity: 'error', title: 'Id shape', text: 'The id uses lower case letters.' }, { id: 'lint.eval', severity: 'warning', title: 'No eval', text: 'eval is refused by hosts.' }]; + const h = mount(PROJECT, async () => result([]), async () => ({ rules })); + await settle(); + expect(h.get).not.toHaveBeenCalled(); + q(h, '.check-rules-toggle').click(); + await settle(); + expect(h.get).toHaveBeenCalledWith('/api/validate/rules'); + expect(shown(h, '.check-rules')).toBe(true); + const cells = [...h.el.querySelectorAll('.check-rules-table tbody tr')].map((r) => [r.querySelector('.check-rule-title')!.textContent, r.querySelectorAll('td')[2].textContent]); + expect(cells).toEqual([['Id shape', 'The id uses lower case letters.'], ['No eval', 'eval is refused by hosts.']]); + q(h, '.check-rules-toggle').click(); + q(h, '.check-rules-toggle').click(); + await settle(); + expect(h.get).toHaveBeenCalledTimes(1); + }); + + it('shows a rule text with markup in it as text', async () => { + const h = mount(PROJECT, async () => result([problem('x', 'error', 'a.js', 1, ' is bad')])); + await settle(); + expect(q(h, '.check-msg').textContent).toBe(' is bad'); + expect(h.el.querySelector('.check-msg img')).toBeNull(); + }); + + it('clears the problems and stops showing them when the project is closed', async () => { + const h = mount(PROJECT, async () => result(TWO)); + await settle(); + h.setProject(null); + expect(h.el.querySelectorAll('.check-row')).toHaveLength(0); + expect(q(h, '.check-sub').textContent).toBe('No project open'); + expect(q(h, '.check-filter[data-filter="all"] .check-count').textContent).toBe('0'); + }); + + it('runs a check when the pane is opened with the run argument', async () => { + const h = mount(PROJECT, async () => result([])); + await settle(); + h.fire('pane.open', { id: 'check', args: { run: true } }); + await settle(); + expect(h.post).toHaveBeenCalledTimes(2); + }); + + it('goes to the New pane from the empty state', async () => { + const h = mount(null, async () => result([])); + q(h, '.check-new').click(); + expect(h.openPane).toHaveBeenCalledWith('new'); + }); + + it('remembers that automatic checking was switched off', async () => { + const h = mount(PROJECT, async () => result([])); + await settle(); + const box = q(h, '.check-auto input'); + expect(box.checked).toBe(true); + box.checked = false; + box.dispatchEvent(new Event('change', { bubbles: true })); + const again = mount(PROJECT, async () => result([])); + await settle(); + expect(q(again, '.check-auto input').checked).toBe(false); + }); +}); diff --git a/frontend/tests/unit/panes/markdown.test.ts b/frontend/tests/unit/panes/markdown.test.ts new file mode 100644 index 0000000..d56ce72 --- /dev/null +++ b/frontend/tests/unit/panes/markdown.test.ts @@ -0,0 +1,103 @@ +import { describe, it, expect } from 'vitest'; +import { render, slug, escapeHtml } from '../../../src/panes/docs/markdown'; + +function dom(src: string): HTMLElement { + const el = document.createElement('div'); + el.innerHTML = render(src).html; + return el; +} + +describe('docs markdown', () => { + it('turns a level one heading into an h1 and reports it as the title', () => { + const r = render('# Getting Started\n\nSome text.'); + expect(r.title).toBe('Getting Started'); + const h1 = dom('# Getting Started').querySelector('h1')!; + h1.querySelector('a[aria-hidden="true"]')?.remove(); + expect(h1.textContent!.trim()).toBe('Getting Started'); + }); + + it('lists every heading with its level in document order', () => { + const r = render('# One\n\n## Two\n\ntext\n\n### Three\n'); + expect(r.headings.map((h) => [h.level, h.text])).toEqual([[1, 'One'], [2, 'Two'], [3, 'Three']]); + }); + + it('gives two headings with the same text different ids', () => { + const r = render('## Setup\n\n## Setup\n'); + expect(r.headings).toHaveLength(2); + expect(r.headings[0].id).not.toBe(r.headings[1].id); + }); + + it('makes a heading id that is its text in lower case with dashes', () => { + expect(slug('Hello World')).toBe('hello-world'); + expect(render('## Hello World').headings[0].id).toBe('hello-world'); + }); + + it('shows raw html from the source as text and builds no script element', () => { + const el = dom('Hi there'); + expect(el.querySelector('script')).toBeNull(); + expect(el.textContent).toContain(''); + }); + + it('escapes the five html special characters', () => { + expect(escapeHtml(`'&'`)).toBe('<a href="x">'&'</a>'); + }); + + it('renders emphasis, strong text and inline code', () => { + const el = dom('This is *soft*, **loud** and `code`.'); + expect(el.querySelector('em')!.textContent).toBe('soft'); + expect(el.querySelector('strong')!.textContent).toBe('loud'); + expect(el.querySelector('code')!.textContent).toBe('code'); + }); + + it('keeps the text of a fenced code block exactly, markup included', () => { + const el = dom('```js\nconst a = "";\n if (a) {}\n```\n'); + expect(el.querySelector('pre')!.textContent!.replace(/\n$/, '')).toBe('const a = "";\n if (a) {}'); + expect(el.querySelector('pre b')).toBeNull(); + }); + + it('builds a bullet list with one item per line', () => { + const el = dom('- one\n- two\n- three\n'); + expect([...el.querySelectorAll('ul > li')].map((li) => li.textContent!.trim())).toEqual(['one', 'two', 'three']); + }); + + it('builds a numbered list as an ordered list', () => { + const el = dom('1. first\n2. second\n'); + expect([...el.querySelectorAll('ol > li')].map((li) => li.textContent!.trim())).toEqual(['first', 'second']); + }); + + it('builds a table with header cells and body rows', () => { + const el = dom('| Key | Value |\n| --- | --- |\n| a | 1 |\n| b | 2 |\n'); + expect([...el.querySelectorAll('th')].map((c) => c.textContent!.trim())).toEqual(['Key', 'Value']); + expect([...el.querySelectorAll('tbody tr')].map((r) => [...r.querySelectorAll('td')].map((c) => c.textContent!.trim()))).toEqual([['a', '1'], ['b', '2']]); + }); + + it('wraps quoted lines in a blockquote', () => { + expect(dom('> take care\n').querySelector('blockquote')!.textContent!.trim()).toBe('take care'); + }); + + it('passes each link through the resolver and uses the address it returns', () => { + const seen: string[] = []; + const r = render('See [the guide](guide.md).', (href) => { seen.push(href); return { href: `#/docs/${href}`, attrs: '' }; }); + const el = document.createElement('div'); + el.innerHTML = r.html; + expect(seen).toEqual(['guide.md']); + expect(el.querySelector('a')!.getAttribute('href')).toBe('#/docs/guide.md'); + expect(el.querySelector('a')!.textContent).toBe('the guide'); + }); + + it('builds no link with a javascript address', () => { + const el = dom('[x](javascript:alert(1))'); + const a = el.querySelector('a'); + expect(a === null || !/^\s*javascript:/i.test(a.getAttribute('href') ?? '')).toBe(true); + }); + + it('separates paragraphs at a blank line', () => { + expect([...dom('first\n\nsecond\n').querySelectorAll('p')].map((p) => p.textContent!.trim())).toEqual(['first', 'second']); + }); + + it('returns the plain text of the page for search without markup', () => { + const r = render('# Title\n\nSome **bold** words.'); + expect(r.text).toContain('Some bold words.'); + expect(r.text).not.toContain('<'); + }); +}); diff --git a/frontend/tests/unit/panes/new.test.ts b/frontend/tests/unit/panes/new.test.ts new file mode 100644 index 0000000..a186637 --- /dev/null +++ b/frontend/tests/unit/panes/new.test.ts @@ -0,0 +1,300 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { pane } from '../../../src/panes/new'; +import { HOSTS } from '../../../src/shell'; +import type { ShellContext } from '../../../src/shell'; + +vi.mock('../../../src/shell/shell', () => ({ + lastArgs: () => undefined, + activePane: () => 'new', + chooseProject: async () => undefined, + partRoot: () => document.body, + setStatus: () => undefined, + setNavCount: () => undefined, + layoutOf: () => 'start', +})); + +const A = HOSTS[0].id; +const B = HOSTS[1].id; + +function starter(product: string, id: string, name: string) { + return { + product, + starter: id, + title: id, + name, + summary: 's', + uses: ['doc.read'], + description: `${name} description`, + permissions: id === 'command' ? [] : ['document', 'network'], + panels: id === 'command' ? [] : [{ id: 'main', title: 'Main Panel', location: 'dock' }], + commands: id === 'panel' ? [] : [{ id: 'go', title: 'Go Now' }], + }; +} + +function catalogue() { + return { + starters: [], + products: [A, B].map((p) => ({ + id: p, + name: p, + docs: null, + starters: ['panel', 'command', 'panel-commands'].map((s) => starter(p, s, `${p} ${s} kit`)), + })), + }; +} + +interface Harness { + el: HTMLElement; + get: ReturnType; + post: ReturnType; + open: ReturnType; + notify: ReturnType; + openPane: ReturnType; + fire: (name: string, data: unknown) => void; +} + +function mount(getImpl: () => Promise, postImpl: (p: string, body: unknown) => Promise = async () => ({ id: 'x', name: 'X' })): Harness { + const el = document.createElement('div'); + document.body.appendChild(el); + const listeners = new Map void>(); + const get = vi.fn(getImpl); + const post = vi.fn(postImpl); + const open = vi.fn(async () => undefined); + const notify = vi.fn(); + const openPane = vi.fn(); + const ctx = { + api: { get, post, put: vi.fn(), del: vi.fn() }, + events: { on: (name: string, cb: (d: unknown) => void) => { listeners.set(name, cb); return () => listeners.delete(name); } }, + project: { current: () => null, onChange: () => () => undefined, open }, + notify, + openPane, + commands: { register: vi.fn() }, + dialog: { confirm: vi.fn(), form: vi.fn() }, + } as unknown as ShellContext; + pane.mount(el, ctx); + return { el, get, post, open, notify, openPane, fire: (n, d) => listeners.get(n)?.(d) }; +} + +async function settle(): Promise { + for (let i = 0; i < 6; i++) await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); +} + +function q(h: Harness, sel: string): T { + return h.el.querySelector(sel)!; +} + +function submit(h: Harness): void { + q(h, '.new-form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); +} + +function type(h: Harness, value: string): void { + const input = q(h, '#new-name'); + input.value = value; + input.dispatchEvent(new Event('input', { bubbles: true })); +} + +describe('new extension pane', () => { + beforeEach(() => { + localStorage.clear(); + document.body.innerHTML = ''; + }); + + it('asks the engine for the starter catalogue once when it mounts', async () => { + const h = mount(async () => catalogue()); + await settle(); + expect(h.get).toHaveBeenCalledTimes(1); + expect(h.get).toHaveBeenCalledWith('/api/templates'); + }); + + it('offers one app choice for every host app', async () => { + const h = mount(async () => catalogue()); + const ids = [...h.el.querySelectorAll('.new-app')].map((b) => b.dataset.product); + expect(ids).toEqual(HOSTS.map((p) => p.id)); + }); + + it('keeps Create disabled until the catalogue has arrived', async () => { + let release: (v: unknown) => void = () => undefined; + const h = mount(() => new Promise((r) => { release = r; })); + type(h, 'My Tool'); + expect(q(h, '.new-create').disabled).toBe(true); + release(catalogue()); + await settle(); + expect(q(h, '.new-create').disabled).toBe(false); + }); + + it('fills the name field and detail card from the chosen starter in the engine answer', async () => { + const h = mount(async () => catalogue()); + await settle(); + expect(q(h, '#new-name').value).toBe(`${A} panel kit`); + expect(q(h, '.new-detail-title').textContent).toBe(`${A} panel kit for ${HOSTS[0].name}`); + expect(q(h, '.new-detail-sub').textContent).toBe(`${A} panel kit description`); + }); + + it('lists each permission of the starter with a plain sentence', async () => { + const h = mount(async () => catalogue()); + await settle(); + const items = [...h.el.querySelectorAll('.new-perms li')].map((li) => li.textContent); + expect(items).toEqual(['documentread and change the open document', 'networkreach the internet']); + }); + + it('says nothing needs consent for a starter without permissions', async () => { + const h = mount(async () => catalogue()); + await settle(); + q(h, '[data-starter="command"]').click(); + expect(q(h, '.new-perms').textContent).toBe('Nothing that needs consent'); + expect(q(h, '.new-adds').textContent).toContain('Command Go Now, runs headless'); + }); + + it('shows panel and command counts on each starter card', async () => { + const h = mount(async () => catalogue()); + await settle(); + const chips = [...h.el.querySelectorAll('[data-starter="panel-commands"] .chip')].map((c) => c.textContent); + expect(chips).toEqual(['1 panel', '1 command', 'document', 'network']); + }); + + it('marks only the clicked app as checked and follows it with the starter name', async () => { + const h = mount(async () => catalogue()); + await settle(); + q(h, `.new-app[data-product="${B}"]`).click(); + const checked = [...h.el.querySelectorAll('.new-app[aria-checked="true"]')].map((b) => b.dataset.product); + expect(checked).toEqual([B]); + expect(q(h, '#new-name').value).toBe(`${B} panel kit`); + }); + + it('keeps a name the user typed when another starter is chosen', async () => { + const h = mount(async () => catalogue()); + await settle(); + type(h, 'Shelf Sorter'); + q(h, '[data-starter="command"]').click(); + expect(q(h, '#new-name').value).toBe('Shelf Sorter'); + }); + + it('shows the id made from the typed name in lower case with dashes', async () => { + const h = mount(async () => catalogue()); + await settle(); + type(h, ' Shelf Sorter 2! '); + expect(q(h, '.new-id').textContent).toBe('Id shelf-sorter-2 (a number is added if a project has it already)'); + }); + + it('sends no request and disables Create when the name is empty', async () => { + const h = mount(async () => catalogue()); + await settle(); + type(h, ' '); + expect(q(h, '.new-create').disabled).toBe(true); + submit(h); + await settle(); + expect(h.post).not.toHaveBeenCalled(); + expect(q(h, '.new-id').textContent).toBe('The id is made from the name.'); + }); + + it('sends the chosen app, starter, trimmed name and description when Create is pressed', async () => { + const h = mount(async () => catalogue()); + await settle(); + q(h, `.new-app[data-product="${B}"]`).click(); + q(h, '[data-starter="command"]').click(); + type(h, ' Shelf Sorter '); + q(h, '#new-desc').value = ' Sorts shelves. '; + submit(h); + await settle(); + expect(h.post).toHaveBeenCalledTimes(1); + expect(h.post).toHaveBeenCalledWith('/api/templates/create', { product: B, starter: 'command', name: 'Shelf Sorter', description: 'Sorts shelves.' }); + }); + + it('leaves the description out of the request when it is empty', async () => { + const h = mount(async () => catalogue()); + await settle(); + submit(h); + await settle(); + const body = h.post.mock.calls[0][1] as Record; + expect(body.description).toBeUndefined(); + expect(body.name).toBe(`${A} panel kit`); + }); + + it('opens the made project and goes to the studio after the engine answers', async () => { + const h = mount(async () => catalogue(), async () => ({ id: 'shelf-sorter', name: 'Shelf Sorter' })); + await settle(); + submit(h); + await settle(); + expect(h.open).toHaveBeenCalledWith('shelf-sorter'); + expect(h.openPane).toHaveBeenCalledWith('studio', { path: 'package/ui/app.js', from: 'new' }); + expect(h.notify.mock.calls[0][0]).toContain('Shelf Sorter is ready'); + expect(h.notify.mock.calls[0][1]).toBe('success'); + }); + + it('shows the engine refusal as a sentence and does not open anything', async () => { + const h = mount(async () => catalogue(), async () => { throw new Error('The name is already taken by another project.'); }); + await settle(); + submit(h); + await settle(); + expect(q(h, '.new-msg').textContent).toBe('The name is already taken by another project.'); + expect(h.notify).toHaveBeenCalledWith('The name is already taken by another project.', 'error'); + expect(h.open).not.toHaveBeenCalled(); + expect(h.openPane).not.toHaveBeenCalled(); + expect(q(h, '.new-create').disabled).toBe(false); + }); + + it('does not send a second request while the first is still being written', async () => { + let release: (v: unknown) => void = () => undefined; + const h = mount(async () => catalogue(), () => new Promise((r) => { release = r; })); + await settle(); + submit(h); + submit(h); + await settle(); + expect(h.post).toHaveBeenCalledTimes(1); + expect(q(h, '.new-msg').textContent).toBe('Writing the project'); + expect(q(h, '.new-create').disabled).toBe(true); + release({ id: 'a', name: 'A' }); + await settle(); + expect(q(h, '.new-create').disabled).toBe(false); + }); + + it('says the starters could not be read when the catalogue request fails', async () => { + const h = mount(async () => { throw new Error('The engine is not reachable.'); }); + await settle(); + expect(q(h, '.new-msg').textContent).toBe('The starters could not be read: The engine is not reachable.'); + expect(q(h, '.new-create').disabled).toBe(true); + }); + + it('remembers the chosen app and starter for the next time the pane is mounted', async () => { + const first = mount(async () => catalogue()); + await settle(); + q(first, `.new-app[data-product="${B}"]`).click(); + q(first, '[data-starter="panel-commands"]').click(); + const second = mount(async () => catalogue()); + await settle(); + expect(q(second, '.new-app[aria-checked="true"]').dataset.product).toBe(B); + expect(q(second, '.new-starter[aria-checked="true"]').dataset.starter).toBe('panel-commands'); + }); + + it('takes app, starter and name from the arguments the pane is opened with', async () => { + const h = mount(async () => catalogue()); + await settle(); + h.fire('pane.open', { id: 'new', args: { product: B, starter: 'command', name: 'From Docs' } }); + expect(q(h, '#new-name').value).toBe('From Docs'); + expect(q(h, '.new-app[aria-checked="true"]').dataset.product).toBe(B); + expect(q(h, '.new-starter[aria-checked="true"]').dataset.starter).toBe('command'); + }); + + it('ignores an open event meant for another pane', async () => { + const h = mount(async () => catalogue()); + await settle(); + h.fire('pane.open', { id: 'docs', args: { product: B, name: 'Other' } }); + expect(q(h, '.new-app[aria-checked="true"]').dataset.product).toBe(A); + expect(q(h, '#new-name').value).toBe(`${A} panel kit`); + }); + + it('keeps the same card and field nodes when choices change', async () => { + const h = mount(async () => catalogue()); + const card = q(h, '[data-starter="panel"]'); + const input = q(h, '#new-name'); + const detail = q(h, '.new-detail'); + await settle(); + q(h, `.new-app[data-product="${B}"]`).click(); + q(h, '[data-starter="command"]').click(); + expect(q(h, '[data-starter="panel"]')).toBe(card); + expect(q(h, '#new-name')).toBe(input); + expect(q(h, '.new-detail')).toBe(detail); + expect(card.isConnected).toBe(true); + }); +}); diff --git a/frontend/tests/unit/panes/studio-helpers.test.ts b/frontend/tests/unit/panes/studio-helpers.test.ts new file mode 100644 index 0000000..dbf434c --- /dev/null +++ b/frontend/tests/unit/panes/studio-helpers.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, vi } from 'vitest'; +import { setKey, formatManifest } from '../../../src/panes/studio/manifest'; +import { minimalChange, Text } from '../../../src/panes/studio/editor'; +import { short, pretty } from '../../../src/panes/preview/log'; + +vi.mock('../../../src/shell/shell', () => ({ + lastArgs: () => undefined, + activePane: () => 'studio', + chooseProject: async () => undefined, + partRoot: () => document.body, + setStatus: () => undefined, + setNavCount: () => undefined, + layoutOf: () => 'studio', +})); + +const MANIFEST = { + format: 'formext', + format_version: 1, + id: 'shelf-sorter', + name: 'Shelf "Sorter"', + permissions: ['document', 'network'], + contributes: { panels: [{ id: 'main', title: 'Main', location: 'dock' }], commands: [] }, + description: 'A long sentence that makes the whole manifest too wide to sit on a single line of one hundred characters.', + payload: { nested: { deep: [1, 2.5, true, null, 'x'] }, empty: {} }, +}; + +function apply(prev: string, next: string): string { + const c = minimalChange(Text.of(prev.split('\n')), next); + if (!c) return prev; + return prev.slice(0, c.from) + c.insert + prev.slice(c.to); +} + +describe('studio manifest text', () => { + it('writes manifest text that reads back as the same JSON value', () => { + expect(JSON.parse(formatManifest(MANIFEST))).toEqual(MANIFEST); + }); + + it('keeps the keys in the order they were given', () => { + expect(Object.keys(JSON.parse(formatManifest(MANIFEST)) as object)).toEqual(Object.keys(MANIFEST)); + }); + + it('reads back the same value with a tab indent and a narrow width', () => { + expect(JSON.parse(formatManifest(MANIFEST, '\t', 20))).toEqual(MANIFEST); + }); + + it('changes the value of a key that is already there without moving it', () => { + const out = setKey({ id: 'a', name: 'A', version: '1.0.0' }, 'name', 'B'); + expect(out).toEqual({ id: 'a', name: 'B', version: '1.0.0' }); + expect(Object.keys(out)).toEqual(['id', 'name', 'version']); + }); + + it('removes a key when its value is cleared and leaves the others alone', () => { + expect(setKey({ id: 'a', name: 'A', version: '1.0.0' }, 'name', undefined)).toEqual({ id: 'a', version: '1.0.0' }); + }); + + it('adds a key without losing or changing any other key', () => { + const out = setKey({ id: 'a', version: '1.0.0', zeta: 1 }, 'name', 'A'); + expect(out).toEqual({ id: 'a', name: 'A', version: '1.0.0', zeta: 1 }); + }); + + it('puts an unknown key at the end', () => { + expect(Object.keys(setKey({ id: 'a', name: 'A' }, 'x-custom', 1))).toEqual(['id', 'name', 'x-custom']); + }); +}); + +describe('studio editor change', () => { + it('reports no change when the new text is the same', () => { + expect(minimalChange(Text.of(['same', 'text']), 'same\ntext')).toBeNull(); + }); + + it('gives a change that turns the old text into the new text', () => { + const cases: [string, string][] = [ + ['const a = 1;\nconst b = 2;', 'const a = 1;\nconst c = 3;\nconst b = 2;'], + ['abc', ''], + ['', 'abc'], + ['aaaa', 'aa'], + ['hello world', 'hello brave world'], + ['x\ny\nz', 'x\nz'], + ]; + for (const [prev, next] of cases) expect(apply(prev, next)).toBe(next); + }); + + it('touches only the changed middle and leaves the shared start and end alone', () => { + const c = minimalChange(Text.of(['hello world']), 'hello brave world')!; + expect(c.from).toBeGreaterThanOrEqual(5); + expect(c.to - c.from).toBe(0); + expect(c.insert).toHaveLength(6); + }); +}); + +describe('preview message text', () => { + it('shows a short value as its JSON', () => { + expect(short({ a: 1, b: 'x' })).toBe('{"a":1,"b":"x"}'); + }); + + it('cuts a long line at the limit and marks the cut', () => { + const out = short({ list: Array.from({ length: 200 }, (_v, i) => i) }, 50); + expect(out).toHaveLength(53); + expect(out.endsWith('...')).toBe(true); + }); + + it('says how many characters a long string had instead of printing it', () => { + expect(short({ data: 'a'.repeat(500) })).toContain('(500 chars)'); + }); + + it('prints a value in full so it reads back as the same JSON', () => { + const v = { method: 'doc.read', params: { ids: [1, 2], deep: { ok: true } } }; + expect(JSON.parse(pretty(v))).toEqual(v); + }); + + it('prints something for a value that has no JSON form', () => { + const loop: Record = {}; + loop.self = loop; + expect(typeof short(loop)).toBe('string'); + expect(short(undefined)).toBe('null'); + }); +}); From 5810de68edd857f7c220ec02bf76deea1c0710cf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:18 -0500 Subject: [PATCH 09/15] test(publish): prepare submission, registry submit, pull request refusals and prepared request, host sources (0.11.0) Drives the publish and sources routes on the real app in process: the submission folder and its index entry, the registry folder layout, the refusals before a pull request and the branch and request prepared against local bare repositories, and sources listed, pulled, read, searched, refused and removed. Expected values come from docs/MANUAL.md, contract/schema/extensions.schema.json, hashlib over the files on disk, git reading the pushed branch, and files the tests wrote themselves. Ran: backend/venv/bin/python -m pytest tests/publish -q -p no:cacheprovider, 65 passed, 0 expected failures. The folder is a package (an empty __init__.py) and its helpers are imported relatively, so its conftest does not take the module name the other test folders import. --- tests/publish/__init__.py | 0 tests/publish/conftest.py | 144 +++++++++++++++ tests/publish/test_prepare_submission.py | 169 +++++++++++++++++ tests/publish/test_pull_request.py | 123 +++++++++++++ tests/publish/test_registry_submit.py | 176 ++++++++++++++++++ tests/publish/test_sources.py | 221 +++++++++++++++++++++++ 6 files changed, 833 insertions(+) create mode 100644 tests/publish/__init__.py create mode 100644 tests/publish/conftest.py create mode 100644 tests/publish/test_prepare_submission.py create mode 100644 tests/publish/test_pull_request.py create mode 100644 tests/publish/test_registry_submit.py create mode 100644 tests/publish/test_sources.py diff --git a/tests/publish/__init__.py b/tests/publish/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/publish/conftest.py b/tests/publish/conftest.py new file mode 100644 index 0000000..185cc2a --- /dev/null +++ b/tests/publish/conftest.py @@ -0,0 +1,144 @@ +import base64 +import json +import os +import subprocess +import sys +import uuid +from pathlib import Path + +import pytest + +TESTS = Path(__file__).resolve().parent.parent +if str(TESTS) not in sys.path: + sys.path.insert(0, str(TESTS)) + +import stand_ins # noqa: E402,F401 +from fastapi.testclient import TestClient # noqa: E402 + +from app.main import app # noqa: E402 +from app.services import registry_pr, window_key # noqa: E402 + +PNG = base64.b64encode(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32).decode("ascii") +GH = """#!/bin/sh +echo "$*" >> "{log}" +case "$1 $2" in + "api user") if [ -f "{signed}" ]; then echo '{{"login":"tester","id":7,"name":"Tess Ter"}}'; exit 0; fi; exit 1 ;; + "api repos/"*) echo "nodemode-dev/form.ext-registry"; exit 0 ;; + "auth git-credential") exit 0 ;; + "pr list") echo "[]"; exit 0 ;; + "pr create") echo "https://example.invalid/registry/pull/1"; exit 0 ;; +esac +exit 1 +""" + + +class Gh: + def __init__(self, folder: Path) -> None: + self.log = folder / "gh-calls.log" + self.signed = folder / "gh-signed-in" + self.program = folder / "gh" + self.program.write_text(GH.format(log=self.log, signed=self.signed), encoding="utf-8") + self.program.chmod(0o755) + + def sign_in(self) -> None: + self.signed.write_text("yes", encoding="utf-8") + + def calls(self) -> list[str]: + try: + return self.log.read_text(encoding="utf-8").splitlines() + except OSError: + return [] + + +@pytest.fixture(scope="session") +def client(): + with TestClient(app, headers={window_key.HEADER: window_key.KEY}) as c: + yield c + + +@pytest.fixture(autouse=True) +def offline(monkeypatch, tmp_path, client): + box = tmp_path / "offline" + box.mkdir() + gh = Gh(box) + monkeypatch.setenv("FORMEXT_SOURCES_BASE", (box / "remotes").as_uri()) + monkeypatch.setenv("FORMEXT_SOURCES_AUTO", "0") + monkeypatch.setenv("FORMEXT_REGISTRY_URL", (box / "index" / "extensions.json").as_uri()) + monkeypatch.setenv("FORMEXT_GH_BIN", str(gh.program)) + monkeypatch.delenv("FORMEXT_REGISTRY_FORK_URL", raising=False) + registry_pr._ready["at"] = 0.0 + yield gh + registry_pr._ready["at"] = 0.0 + client.delete("/api/sources/registry") + + +@pytest.fixture +def gh(offline): + return offline + + +@pytest.fixture +def remotes(tmp_path): + folder = tmp_path / "offline" / "remotes" + folder.mkdir(parents=True, exist_ok=True) + return folder + + +def git(*args, cwd): + out = subprocess.run(["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "-c", "init.defaultBranch=main", *args], cwd=str(cwd), capture_output=True, text=True, timeout=60, env=dict(os.environ, GIT_TERMINAL_PROMPT="0")) + assert out.returncode == 0, out.stderr + return out.stdout.strip() + + +def make_remote(remotes: Path, repo: str, files: dict) -> str: + work = remotes / f"work-{repo}" + work.mkdir() + git("init", "-q", cwd=work) + for rel, text in files.items(): + target = work / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + git("add", "-A", cwd=work) + git("commit", "-q", "-m", "first", cwd=work) + git("branch", "-M", "main", cwd=work) + git("clone", "-q", "--bare", str(work), str(remotes / f"{repo}.git"), cwd=remotes) + return git("rev-parse", "HEAD", cwd=work) + + +def manifest(pid: str, name: str, product: str = "formvis", **more) -> str: + data = {"format": "formai-package", "format_version": 1, "id": pid, "name": name, "product": product, "kind": "script-plugin", "version": "0.1.0", "author": "me", "licence": "Apache-2.0", "native": False, "permissions": [], "api": "1", "description": ""} + data.update(more) + return json.dumps(data, indent=2) + "\n" + + +@pytest.fixture +def make_project(client): + def make(product: str = "formvis", files: dict | None = None, **fields) -> dict: + name = "Pub " + uuid.uuid4().hex[:10] + pid = name.lower().replace(" ", "-") + body = {"name": name, "product": product} + if files is not None or fields: + body["files"] = {"package/manifest.json": manifest(pid, name, product, **fields), **(files or {})} + res = client.post("/api/projects", json=body) + assert res.status_code == 200, res.text + return res.json() + + return make + + +@pytest.fixture +def setting(client): + done = [] + + def put(group: str, patch: dict) -> None: + res = client.put("/api/settings", json={group: patch}) + assert res.status_code == 200, res.text + done.append((group, patch)) + + yield put + + def blank(node): + return {k: blank(v) for k, v in node.items()} if isinstance(node, dict) else "" + + for group, patch in done: + client.put("/api/settings", json={group: blank(patch)}) diff --git a/tests/publish/test_prepare_submission.py b/tests/publish/test_prepare_submission.py new file mode 100644 index 0000000..d2cb44c --- /dev/null +++ b/tests/publish/test_prepare_submission.py @@ -0,0 +1,169 @@ +import hashlib +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SCHEMA = json.loads((ROOT / "contract" / "schema" / "extensions.schema.json").read_text(encoding="utf-8")) +ENTRY = SCHEMA["$defs"]["entry"] + + +def prepare(client, pid, **body): + res = client.post(f"/api/publish/{pid}", json={"sign": False, **body}) + assert res.status_code == 200, res.text + return res.json() + + +def test_prepare_writes_the_five_files_the_manual_lists(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + folder = Path(out["folder"]) + package = f"{p['id']}-0.1.0.formpkg" + assert sorted(f.name for f in folder.iterdir()) == sorted([package, "entry.json", "extensions.json", "README.md", "submission.json"]) + assert folder.parent.name == "submissions" and folder.name == f"{p['id']}-0.1.0" + + +def test_entry_sha256_and_bytes_match_the_package_file_on_disk(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + raw = (Path(out["folder"]) / out["package"]).read_bytes() + entry = json.loads((Path(out["folder"]) / "entry.json").read_text(encoding="utf-8")) + assert entry["sha256"] == hashlib.sha256(raw).hexdigest() + assert entry["bytes"] == len(raw) + + +def test_entry_has_every_field_the_index_schema_requires_and_no_other(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + entry = json.loads((Path(out["folder"]) / "entry.json").read_text(encoding="utf-8")) + assert set(ENTRY["required"]) <= set(entry) + assert set(entry) <= set(ENTRY["properties"]) + for key in ("id", "version", "url", "sha256"): + assert re.search(ENTRY["properties"][key]["pattern"], entry[key]), key + assert entry["product"] in ENTRY["properties"]["product"]["enum"] + assert all(isinstance(entry[k], str) and entry[k] for k in ("name", "author", "description", "licence")) + + +def test_one_package_index_holds_the_same_entry_and_the_schema_constants(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + folder = Path(out["folder"]) + index = json.loads((folder / "extensions.json").read_text(encoding="utf-8")) + entry = json.loads((folder / "entry.json").read_text(encoding="utf-8")) + assert index["format"] == SCHEMA["properties"]["format"]["const"] + assert index["format_version"] == SCHEMA["properties"]["format_version"]["const"] + assert set(SCHEMA["required"]) <= set(index) <= set(SCHEMA["properties"]) + assert index["packages"] == [entry] + + +def test_unsigned_submission_carries_no_signature_and_no_publisher(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + folder = Path(out["folder"]) + index = json.loads((folder / "extensions.json").read_text(encoding="utf-8")) + assert out["signed_by"] is None + assert index["publishers"] == [] + assert "signature" not in index["packages"][0] + assert "Not signed" in (folder / "README.md").read_text(encoding="utf-8") + + +def test_default_address_agrees_between_status_and_the_prepared_entry(client, make_project): + p = make_project() + before = client.get(f"/api/publish/{p['id']}").json() + out = prepare(client, p["id"]) + assert out["url"] == before["default_url"] + assert out["url"].startswith("https://formai.studio/extensions/") + assert out["url"].endswith(f"{p['id']}-0.1.0.formpkg") + assert out["url_default"] is True + + +def test_a_given_https_address_goes_into_the_entry(client, make_project): + p = make_project() + url = "https://downloads.example.org/ext/mine.formpkg" + out = prepare(client, p["id"], url=url) + entry = json.loads((Path(out["folder"]) / "entry.json").read_text(encoding="utf-8")) + assert entry["url"] == url + assert out["url_default"] is False + + +def test_an_address_that_is_not_https_is_refused_with_a_message(client, make_project): + p = make_project() + res = client.post(f"/api/publish/{p['id']}", json={"sign": False, "url": "http://downloads.example.org/mine.formpkg"}) + assert 400 <= res.status_code < 500 + assert "https" in res.json()["detail"] + assert client.get(f"/api/publish/{p['id']}").json()["submission"] is None + + +def test_preparing_twice_gives_the_same_sha256(client, make_project): + p = make_project() + first = prepare(client, p["id"]) + second = prepare(client, p["id"]) + assert first["sha256"] == second["sha256"] + assert second["files"] == first["files"] + + +def test_readme_names_the_sha256_and_the_package_for_the_reviewer(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + folder = Path(out["folder"]) + text = (folder / "README.md").read_text(encoding="utf-8") + digest = hashlib.sha256((folder / out["package"]).read_bytes()).hexdigest() + assert digest in text + assert out["package"] in text + assert p["name"] in text.splitlines()[0] + + +def test_readme_says_a_permission_in_plain_words(client, make_project): + p = make_project(permissions=["network"], description="Fetches things.") + out = prepare(client, p["id"]) + text = (Path(out["folder"]) / "README.md").read_text(encoding="utf-8") + assert "- `network`: reach the internet" in text + entry = json.loads((Path(out["folder"]) / "entry.json").read_text(encoding="utf-8")) + assert entry["permissions"] == ["network"] + assert entry["description"] == "Fetches things." + + +def test_status_before_prepare_has_no_submission_and_names_the_registry(client, make_project): + p = make_project() + out = client.get(f"/api/publish/{p['id']}").json() + assert out["submission"] is None + assert out["registry"]["submission"] is None + assert out["registry"]["repo"] == "nodemode-dev/form.ext-registry" + assert Path(out["registry"]["folder"]).parts[-4:] == ("submissions", "registry", "extensions", p["id"]) + + +def test_status_after_prepare_reports_the_same_submission(client, make_project): + p = make_project() + out = prepare(client, p["id"]) + seen = client.get(f"/api/publish/{p['id']}").json()["submission"] + assert seen["sha256"] == out["sha256"] + assert seen["folder"] == out["folder"] + assert seen["stale"] is False + + +def test_send_before_prepare_is_refused(client, make_project): + p = make_project() + res = client.post(f"/api/publish/{p['id']}/send") + assert res.status_code == 404 + assert res.json()["detail"] == "prepare a submission first" + + +def test_reveal_before_prepare_is_refused(client, make_project): + p = make_project() + res = client.post(f"/api/publish/{p['id']}/reveal") + assert res.status_code == 404 + assert res.json()["detail"] == "prepare a submission first" + + +def test_registry_reveal_before_submit_is_refused(client, make_project): + p = make_project() + res = client.post(f"/api/publish/{p['id']}/registry/reveal") + assert res.status_code == 404 + assert res.json()["detail"] == "submit to the registry first" + + +def test_an_unknown_project_is_refused_at_every_publish_step(client): + for method, path in (("get", ""), ("post", ""), ("post", "/registry"), ("post", "/send")): + res = getattr(client, method)(f"/api/publish/no-such-project-here{path}") + assert res.status_code == 404, path + assert "no such project" in res.json()["detail"], path diff --git a/tests/publish/test_pull_request.py b/tests/publish/test_pull_request.py new file mode 100644 index 0000000..c133543 --- /dev/null +++ b/tests/publish/test_pull_request.py @@ -0,0 +1,123 @@ +import json +import subprocess +from pathlib import Path + +from app.services import registry_pr +from .conftest import PNG, git, make_remote + +SHOT = {"docs/screenshot.png": {"base64": PNG}} + + +def test_readiness_asks_for_a_sign_in_when_gh_is_not_signed_in(client, make_project, gh): + p = make_project() + out = client.get(f"/api/publish/{p['id']}/registry/pull-request").json() + assert out["ready"] is False + assert out["gh"] is True and out["signed_in"] is False and out["login"] is None + assert [n["what"] for n in out["needs"]] == ["sign-in"] + assert "gh auth login --web" in out["needs"][0]["how"] + assert out["repo"] == "nodemode-dev/form.ext-registry" + + +def test_readiness_asks_for_gh_when_it_is_not_installed(client, make_project, monkeypatch): + monkeypatch.delenv("FORMEXT_GH_BIN") + monkeypatch.setattr(registry_pr, "GH_SYSTEM", ()) + p = make_project() + out = client.get(f"/api/publish/{p['id']}/registry/pull-request").json() + assert out["ready"] is False and out["gh"] is False + assert [n["what"] for n in out["needs"]] == ["gh"] + assert out["needs"][0]["how"] == "https://cli.github.com" + + +def test_readiness_is_ready_and_names_the_login_when_signed_in(client, make_project, gh): + gh.sign_in() + p = make_project() + out = client.get(f"/api/publish/{p['id']}/registry/pull-request").json() + assert out == {"ready": True, "git": True, "gh": True, "signed_in": True, "login": "tester", "needs": [], "repo": "nodemode-dev/form.ext-registry"} + + +def test_pull_request_is_refused_before_setup_and_nothing_is_submitted(client, make_project, gh): + p = make_project(files=SHOT) + res = client.post(f"/api/publish/{p['id']}/registry/pull-request") + assert res.status_code == 409 + body = res.json() + assert body["detail"].startswith("the pull request needs a little setup first") + assert [n["what"] for n in body["needs"]] == ["sign-in"] + assert client.get(f"/api/publish/{p['id']}").json()["registry"]["submission"] is None + assert all(c == "api user" for c in gh.calls()) + + +def test_pull_request_is_refused_while_the_checks_fail(client, make_project, gh): + gh.sign_in() + p = make_project() + res = client.post(f"/api/publish/{p['id']}/registry/pull-request") + assert res.status_code == 409 + body = res.json() + assert "no pull request was opened" in body["detail"] + assert body["needs"] == [{"what": "checks", "say": "a screenshot is missing: add docs/screenshot.png (the extension in its app)", "how": "docs/screenshot.png"}] + assert not any(c.startswith(("repo fork", "pr ")) for c in gh.calls()) + + +def test_pull_request_is_refused_while_the_readme_placeholder_is_left(client, make_project, gh): + gh.sign_in() + p = make_project(files=SHOT, permissions=["network"], description="Fetches.") + res = client.post(f"/api/publish/{p['id']}/registry/pull-request") + assert res.status_code == 409 + body = res.json() + assert "still left for you to write" in body["detail"] + assert [n["what"] for n in body["needs"]] == ["text"] + assert "README.md" in body["needs"][0]["say"] + assert not any(c.startswith(("repo fork", "pr ")) for c in gh.calls()) + + +def test_pull_request_is_refused_while_the_licence_placeholder_is_left(client, make_project, gh): + gh.sign_in() + p = make_project(files=SHOT, licence="MPL-2.0") + res = client.post(f"/api/publish/{p['id']}/registry/pull-request") + assert res.status_code == 409 + says = [n["say"] for n in res.json()["needs"]] + assert len(says) == 1 and says[0].startswith("LICENSE is still the placeholder") + assert not any(c.startswith(("repo fork", "pr ")) for c in gh.calls()) + + +def test_unfinished_reports_nothing_for_finished_texts(tmp_path): + (tmp_path / "README.md").write_text("# Mine\n\n- `network`: it fetches the weather.\n", encoding="utf-8") + (tmp_path / "LICENSE").write_text("MIT License\n", encoding="utf-8") + assert registry_pr.unfinished(tmp_path) == [] + + +def test_pull_request_puts_the_folder_on_the_add_branch_of_the_fork_and_asks_gh_to_open_it(client, make_project, gh, remotes, monkeypatch): + gh.sign_in() + make_remote(remotes, "form.ext-registry", {"README.md": "# registry\n"}) + fork = remotes / "fork.git" + git("clone", "-q", "--bare", str(remotes / "form.ext-registry.git"), str(fork), cwd=remotes) + monkeypatch.setenv("FORMEXT_REGISTRY_FORK_URL", fork.as_uri()) + p = make_project(files={"package/panel.js": "export const hello = 1;\n", **SHOT}, description="Shows a board.") + try: + res = client.post(f"/api/publish/{p['id']}/registry/pull-request") + assert res.status_code == 200, res.text + out = res.json() + branch = f"add-{p['id']}-0.1.0" + assert out["ok"] is True and out["state"] == "opened" + assert out["branch"] == branch + assert out["url"] == "https://example.invalid/registry/pull/1" + assert out["fork"] == "tester/form.ext-registry" + assert git("rev-parse", f"refs/heads/{branch}", cwd=fork) == out["commit"] + tree = git("ls-tree", "-r", "--name-only", branch, cwd=fork).splitlines() + submitted = client.get(f"/api/publish/{p['id']}").json()["registry"]["submission"] + assert sorted(tree) == sorted(["README.md"] + [f"extensions/{p['id']}/{rel}" for rel in submitted["files"]]) + blob = subprocess.run(["git", "show", f"{branch}:extensions/{p['id']}/package/panel.js"], cwd=str(fork), capture_output=True, text=True).stdout + assert blob == "export const hello = 1;\n" + assert git("log", "-1", "--format=%an <%ae>", branch, cwd=fork) == "Tess Ter <7+tester@users.noreply.github.com>" + created = [c for c in gh.calls() if c.startswith("pr create")] + assert len(created) == 1 + title = f"Add {p['name']} 0.1.0" + assert out["title"] == title + assert f"--repo nodemode-dev/form.ext-registry --base main --head tester:{branch} --title {title} --body {title}: Shows a board." in created[0] + assert git("log", "-1", "--format=%s", branch, cwd=fork) == f"feat({p['id']}): add {p['name']} 0.1.0" + shown = next(c["run"] for c in submitted["commands"] if c["run"].startswith("gh pr create")) + assert f"--title '{title}'" in shown + assert git("rev-parse", "refs/heads/main", cwd=fork) == git("rev-parse", "refs/heads/main", cwd=remotes / "form.ext-registry.git") + finally: + import shutil + + shutil.rmtree(registry_pr.work_dir(), ignore_errors=True) diff --git a/tests/publish/test_registry_submit.py b/tests/publish/test_registry_submit.py new file mode 100644 index 0000000..44f3142 --- /dev/null +++ b/tests/publish/test_registry_submit.py @@ -0,0 +1,176 @@ +import json +from pathlib import Path + +from .conftest import PNG + +SHOT = {"docs/screenshot.png": {"base64": PNG}} + + +def submit(client, pid): + res = client.post(f"/api/publish/{pid}/registry") + assert res.status_code == 200, res.text + return res.json() + + +def test_submit_writes_the_registry_layout_the_manual_states(client, make_project): + p = make_project() + out = submit(client, p["id"]) + folder = Path(out["folder"]) + assert folder.parts[-4:] == ("submissions", "registry", "extensions", p["id"]) + assert out["files"] == ["CHANGELOG.md", "LICENSE", "README.md", "package/manifest.json"] + assert all((folder / rel).is_file() for rel in out["files"]) + assert sorted(out["made"]) == ["CHANGELOG.md", "LICENSE", "README.md"] + + +def test_package_folder_holds_exactly_the_project_package_bytes(client, make_project): + p = make_project(files={"package/panel.js": "export const hello = 1;\n", **SHOT}) + out = submit(client, p["id"]) + folder = Path(out["folder"]) + source = Path(p["package_dir"]) + made = sorted(f.relative_to(folder / "package").as_posix() for f in (folder / "package").rglob("*") if f.is_file()) + assert made == sorted(f.relative_to(source).as_posix() for f in source.rglob("*") if f.is_file()) + assert all((folder / "package" / rel).read_bytes() == (source / rel).read_bytes() for rel in made) + + +def test_source_and_docs_go_beside_the_package(client, make_project): + p = make_project(files={"src/main.ts": "export const a = 1;\n", "package.json": "{}\n", **SHOT}) + out = submit(client, p["id"]) + assert {"src/main.ts", "package.json", "docs/screenshot.png"} <= set(out["files"]) + assert (Path(out["folder"]) / "src" / "main.ts").read_text(encoding="utf-8") == "export const a = 1;\n" + + +def test_a_missing_screenshot_fails_the_checks_and_names_the_slot(client, make_project): + p = make_project() + out = submit(client, p["id"]) + assert out["checks"]["ok"] is False + assert out["screenshot"] is None + assert out["screenshot_slot"] == "docs/screenshot.png" + assert [x["where"] for x in out["checks"]["problems"]] == ["docs/screenshot.png"] + assert "1 problem" in out["checks"]["report"] + + +def test_with_a_screenshot_the_checks_pass(client, make_project): + p = make_project(files=SHOT) + out = submit(client, p["id"]) + assert out["checks"]["ok"] is True + assert out["checks"]["problems"] == [] + assert out["screenshot"] == "docs/screenshot.png" + assert "passed" in out["checks"]["report"] + + +def test_the_result_says_form_ext_ran_its_own_check_when_the_registry_copy_cannot_be_fetched(client, make_project): + p = make_project(files=SHOT) + out = submit(client, p["id"]) + assert out["checks"]["by"] == "formext" + assert "could not fetch the registry's checks" in out["checks"]["note"] + assert "its own Check" in out["checks"]["note"] + + +def test_the_projects_own_readme_is_kept_and_not_rewritten(client, make_project): + mine = "# Mine\n\nI wrote this.\n" + p = make_project(files={"README.md": mine, **SHOT}) + out = submit(client, p["id"]) + assert "README.md" not in out["made"] + assert (Path(out["folder"]) / "README.md").read_text(encoding="utf-8") == mine + + +def test_a_missing_apache_licence_is_written_with_the_full_text(client, make_project): + p = make_project() + out = submit(client, p["id"]) + text = (Path(out["folder"]) / "LICENSE").read_text(encoding="utf-8") + assert "Apache License" in text and "Version 2.0" in text + assert "Replace this file" not in text + + +def test_a_missing_mit_licence_is_written_with_the_full_text_and_the_author(client, make_project): + p = make_project(licence="MIT", author="Ada Example") + out = submit(client, p["id"]) + text = (Path(out["folder"]) / "LICENSE").read_text(encoding="utf-8") + assert text.startswith("MIT License") + assert "Ada Example" in text + assert "Permission is hereby granted, free of charge" in text + + +def test_another_licence_gets_a_placeholder_to_finish(client, make_project): + p = make_project(licence="MPL-2.0") + out = submit(client, p["id"]) + text = (Path(out["folder"]) / "LICENSE").read_text(encoding="utf-8") + assert "MPL-2.0" in text + assert "Replace this file with the full text" in text + + +def test_written_readme_has_one_placeholder_line_per_permission(client, make_project): + p = make_project(permissions=["network", "files-read"], description="Fetches.") + out = submit(client, p["id"]) + text = (Path(out["folder"]) / "README.md").read_text(encoding="utf-8") + lines = [ln for ln in text.splitlines() if ln.endswith("Why: say here what the extension does with it.")] + assert len(lines) == 2 + assert lines[0].startswith("- `network`") and lines[1].startswith("- `files-read`") + assert "## Permissions" in text + assert "docs/screenshot.png" in text + + +def test_written_changelog_starts_at_the_manifest_version(client, make_project): + p = make_project(version="2.3.4") + out = submit(client, p["id"]) + text = (Path(out["folder"]) / "CHANGELOG.md").read_text(encoding="utf-8") + assert "## 2.3.4" in text + assert out["version"] == "2.3.4" + + +def test_commands_use_the_add_branch_name_the_manual_gives(client, make_project): + p = make_project(files=SHOT) + out = submit(client, p["id"]) + runs = [c["run"] for c in out["commands"]] + branch = f"add-{p['id']}-0.1.0" + assert out["update"] is False + assert any(branch in r and "git switch -c" in r for r in runs) + assert any(r == f"git push -u origin {branch}" for r in runs) + assert f"python3 tools/check.py extensions/{p['id']}" in runs + assert any(r.startswith("gh pr create --repo nodemode-dev/form.ext-registry --base main") for r in runs) + assert any(r.startswith("gh repo fork nodemode-dev/form.ext-registry") for r in runs) + + +def test_submit_alone_starts_no_outside_program(client, make_project, gh): + p = make_project(files=SHOT) + submit(client, p["id"]) + assert gh.calls() == [] + + +def test_status_after_submit_reports_the_registry_submission(client, make_project): + p = make_project(files=SHOT) + out = submit(client, p["id"]) + seen = client.get(f"/api/publish/{p['id']}").json()["registry"] + assert seen["submission"]["id"] == p["id"] + assert seen["submission"]["files"] == out["files"] + assert seen["folder"] == out["folder"] + + +def test_submitting_again_drops_a_file_the_project_no_longer_has(client, make_project): + p = make_project(files={"src/old.ts": "1\n", **SHOT}) + first = submit(client, p["id"]) + assert "src/old.ts" in first["files"] + res = client.delete(f"/api/projects/{p['id']}/files/src/old.ts") + assert res.status_code == 200, res.text + second = submit(client, p["id"]) + assert "src/old.ts" not in second["files"] + assert not (Path(second["folder"]) / "src" / "old.ts").exists() + + +def test_a_registry_checkout_without_check_py_is_named_in_the_note(client, make_project, setting, tmp_path): + clone = tmp_path / "my-registry" + clone.mkdir() + setting("registry", {"checkout": str(clone)}) + p = make_project(files=SHOT) + out = submit(client, p["id"]) + assert out["checks"]["by"] == "formext" + assert str(clone) in out["checks"]["note"] + assert "tools/check.py" in out["checks"]["note"] + assert client.get(f"/api/publish/{p['id']}").json()["registry"]["managed"] is False + + +def test_the_record_file_beside_the_folder_is_the_answer_given(client, make_project): + p = make_project(files=SHOT) + out = submit(client, p["id"]) + kept = json.loads((Path(out["root"]) / f"{p['id']}.submission.json").read_text(encoding="utf-8")) + assert kept == out diff --git a/tests/publish/test_sources.py b/tests/publish/test_sources.py new file mode 100644 index 0000000..66feb87 --- /dev/null +++ b/tests/publish/test_sources.py @@ -0,0 +1,221 @@ +from pathlib import Path + +import pytest + +from .conftest import make_remote + +LINES = [f"line {n} of the host" for n in range(1, 11)] + + +@pytest.fixture +def local(tmp_path, setting): + def make(key: str, files: dict | None = None) -> Path: + folder = tmp_path / f"own-{key}" + folder.mkdir() + for rel, data in (files or {}).items(): + target = folder / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data if isinstance(data, bytes) else data.encode("utf-8")) + setting("sources", {"local": {key: str(folder)}}) + return folder + + return make + + +def test_the_list_agrees_with_each_source_asked_alone(client): + listed = client.get("/api/sources").json()["sources"] + assert len(listed) == len({s["key"] for s in listed}) >= 13 + for row in listed: + alone = client.get(f"/api/sources/{row['key']}").json() + assert alone["repository"] == row["repository"] + assert alone["url"].endswith("/" + row["repository"].split("/", 1)[1]) + assert alone["state"] == row["state"] + + +def test_the_registry_and_formportal_are_family_sources_not_hosts(client): + kinds = {s["key"]: s["kind"] for s in client.get("/api/sources").json()["sources"]} + assert kinds["registry"] == "family" and kinds["formportal"] == "family" + assert kinds["formvis"] == "host" + + +def test_an_unknown_source_is_refused_and_the_message_lists_the_real_ones(client): + res = client.get("/api/sources/formnothing") + assert res.status_code == 404 + detail = res.json()["detail"] + assert detail.startswith("formnothing is not a Form app") + assert all(s["key"] in detail for s in client.get("/api/sources").json()["sources"]) + + +def test_a_repository_name_resolves_to_its_source(client): + assert client.get("/api/sources/form.ext-registry").json()["key"] == "registry" + assert client.get("/api/sources/form.md").json()["key"] == "formmd" + assert client.get("/api/sources/FormCut").json()["key"] == "formcut" + + +def test_a_project_id_resolves_to_its_host_app(client, make_project): + p = make_project(product="formwav") + assert client.get(f"/api/sources/{p['id']}").json()["key"] == "formwav" + + +def test_reading_before_a_pull_is_refused_with_what_to_do(client): + for path in ("/files", "/file?path=README.md", "/search?q=x"): + res = client.get(f"/api/sources/formdeck{path}") + assert res.status_code == 404, path + assert "is not here yet; pull it first" in res.json()["detail"], path + + +def test_a_failed_pull_is_refused_and_the_source_shows_as_failed(client): + res = client.post("/api/sources/formlit/pull") + assert res.status_code == 502 + assert "check the internet connection" in res.json()["detail"] + seen = client.get("/api/sources/formlit").json() + assert seen["state"] == "failed" and seen["dir"] is None + assert seen["error"] == res.json()["detail"] + assert client.delete("/api/sources/formlit").json()["state"] == "absent" + + +def test_a_base_address_with_another_scheme_is_refused(client, monkeypatch): + monkeypatch.setenv("FORMEXT_SOURCES_BASE", "ftp://example.invalid/forms") + res = client.get("/api/sources/formpdf") + assert 400 <= res.status_code < 500 + assert "must be an https://, http:// or file:// address" in res.json()["detail"] + + +def test_pull_clones_the_repository_then_reads_it_and_remove_takes_it_away(client, remotes): + commit = make_remote(remotes, "formencoder", {"README.md": "# FormEncoder\n", "src/extensions.ts": "export const host = 1;\n", "LICENSE": "MIT License\n"}) + try: + res = client.post("/api/sources/formencoder/pull") + assert res.status_code == 200, res.text + out = res.json() + assert out["state"] == "ready" and out["method"] == "git" + assert out["commit"] == commit and out["subject"] == "first" + assert out["licence"] == "MIT" + assert "src/extensions.ts" in out["extension_host"] + assert "README.md" in out["docs"] + folder = Path(out["dir"]) + assert (folder / "src" / "extensions.ts").read_text(encoding="utf-8") == "export const host = 1;\n" + names = [f["path"] for f in client.get("/api/sources/formencoder/files").json()["files"]] + assert names == ["LICENSE", "README.md", "src/extensions.ts"] + again = client.post("/api/sources/formencoder/pull", json={"update": True}).json() + assert again["commit"] == commit + finally: + gone = client.delete("/api/sources/formencoder") + assert gone.json()["state"] == "absent" + assert not folder.exists() + assert client.get("/api/sources/formencoder/files").status_code == 404 + + +def test_your_own_folder_is_ready_listed_and_never_deleted(client, local): + folder = local("formcut", {"README.md": "# mine\n", "src/a.ts": "const a = 1;\n", "node_modules/x/index.js": "x\n", ".git/config": "c\n"}) + seen = client.get("/api/sources/formcut").json() + assert seen["state"] == "ready" and seen["method"] == "local" and seen["dir"] == str(folder) + listed = client.get("/api/sources/formcut/files").json() + assert [f["path"] for f in listed["files"]] == ["README.md", "src/a.ts"] + assert {f["path"]: f["size"] for f in listed["files"]} == {"README.md": 7, "src/a.ts": 13} + assert listed["total"] == 2 and listed["truncated"] is False + res = client.delete("/api/sources/formcut") + assert 400 <= res.status_code < 500 + assert "form.ext does not delete it" in res.json()["detail"] + assert (folder / "src" / "a.ts").is_file() + + +def test_files_can_be_narrowed_by_folder_glob_and_limit(client, local): + local("formcut", {"a.md": "a\n", "src/b.ts": "b\n", "src/c.ts": "c\n", "src/d.md": "d\n"}) + under = client.get("/api/sources/formcut/files", params={"under": "src"}).json() + assert [f["path"] for f in under["files"]] == ["src/b.ts", "src/c.ts", "src/d.md"] + globbed = client.get("/api/sources/formcut/files", params={"glob": "*.md"}).json() + assert [f["path"] for f in globbed["files"]] == ["a.md", "src/d.md"] + capped = client.get("/api/sources/formcut/files", params={"limit": 1}).json() + assert len(capped["files"]) == 1 and capped["total"] == 4 and capped["truncated"] is True + missing = client.get("/api/sources/formcut/files", params={"under": "nope"}) + assert missing.status_code == 404 and "there is no folder nope" in missing.json()["detail"] + + +def test_a_file_is_read_by_line_window(client, local): + local("formcut", {"docs/host.txt": "\n".join(LINES) + "\n"}) + out = client.get("/api/sources/formcut/file", params={"path": "docs/host.txt", "start": 3, "lines": 4}).json() + assert out["text"] == "\n".join(LINES[2:6]) + assert (out["start"], out["end"], out["total_lines"]) == (3, 6, 10) + assert out["size"] == len("\n".join(LINES)) + 1 + whole = client.get("/api/sources/formcut/file", params={"path": "docs/host.txt"}).json() + assert whole["text"].splitlines() == LINES + + +def test_a_binary_file_is_reported_not_returned_as_text(client, local): + local("formcut", {"icon.bin": b"\x00\x01\x02\x03"}) + out = client.get("/api/sources/formcut/file", params={"path": "icon.bin"}).json() + assert out["binary"] is True and out["size"] == 4 + assert "text" not in out + + +def test_paths_outside_the_source_are_refused(client, local, tmp_path): + local("formcut", {"README.md": "x\n", ".git/config": "secret\n"}) + (tmp_path / "outside.txt").write_text("outside\n", encoding="utf-8") + for path in ("../outside.txt", "src/../../outside.txt", ".git/config"): + res = client.get("/api/sources/formcut/file", params={"path": path}) + assert 400 <= res.status_code < 500, path + assert "is not a path inside the source" in res.json()["detail"], path + res = client.get("/api/sources/formcut/file", params={"path": "absent.md"}) + assert res.status_code == 404 and "there is no file absent.md" in res.json()["detail"] + + +def test_a_link_leading_out_of_the_source_is_refused(client, local, tmp_path): + folder = local("formcut", {"README.md": "x\n"}) + (tmp_path / "outside.txt").write_text("outside\n", encoding="utf-8") + (folder / "leak.txt").symlink_to(tmp_path / "outside.txt") + res = client.get("/api/sources/formcut/file", params={"path": "leak.txt"}) + assert 400 <= res.status_code < 500 + assert "leads outside the source" in res.json()["detail"] + assert "leak.txt" not in [f["path"] for f in client.get("/api/sources/formcut/files").json()["files"]] + + +def test_search_finds_the_lines_and_their_numbers(client, local): + local("formcut", {"a.txt": "alpha\nBeta here\ngamma\n", "src/b.ts": "const beta = 2;\n", "pic.png": "beta\n"}) + out = client.get("/api/sources/formcut/search", params={"q": "beta"}).json() + assert [(m["path"], m["line"], m["text"]) for m in out["matches"]] == [("a.txt", 2, "Beta here"), ("src/b.ts", 1, "const beta = 2;")] + assert out["truncated"] is False and out["files_scanned"] == 2 + exact = client.get("/api/sources/formcut/search", params={"q": "beta", "case": True}).json() + assert [m["path"] for m in exact["matches"]] == ["src/b.ts"] + only = client.get("/api/sources/formcut/search", params={"q": "beta", "glob": "*.txt"}).json() + assert [m["path"] for m in only["matches"]] == ["a.txt"] + + +def test_search_takes_words_literally_unless_regex_is_asked(client, local): + local("formcut", {"a.txt": "a.c\nabc\n"}) + plain = client.get("/api/sources/formcut/search", params={"q": "a.c"}).json() + assert [m["line"] for m in plain["matches"]] == [1] + pattern = client.get("/api/sources/formcut/search", params={"q": "a.c", "regex": True}).json() + assert [m["line"] for m in pattern["matches"]] == [1, 2] + + +def test_search_stops_at_the_limit_and_says_so(client, local): + local("formcut", {"a.txt": "hit\n" * 9}) + out = client.get("/api/sources/formcut/search", params={"q": "hit", "limit": 4}).json() + assert len(out["matches"]) == 4 + assert out["truncated"] is True and out["stopped"] == "limit" + + +def test_search_refuses_empty_words_and_bad_patterns(client, local): + local("formcut", {"a.txt": "x\n"}) + cases = [({"q": " "}, "give the words to search for"), ({"q": "(", "regex": True}, "not a valid regular expression"), ({"q": "(a+)+", "regex": True}, "repeats a group that itself repeats"), ({"q": "a" * 201, "regex": True}, "longer than 200 characters")] + for params, words in cases: + res = client.get("/api/sources/formcut/search", params=params) + assert 400 <= res.status_code < 500, params + assert words in res.json()["detail"], params + + +def test_a_gpl_source_carries_the_copying_warning_and_an_mit_one_does_not(client, local): + local("formcut", {"LICENSE": "GNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n"}) + local("formdeck", {"LICENSE": "MIT License\n\nPermission is hereby granted, free of charge\n"}) + gpl = client.get("/api/sources/formcut").json() + mit = client.get("/api/sources/formdeck").json() + assert gpl["licence"] == "GPL-3.0" and "puts the extension under GPL-3.0" in gpl["note"] + assert mit["licence"] == "MIT" and "GPL" not in mit["note"] + + +def test_pull_on_your_own_folder_changes_nothing_and_reaches_nowhere(client, local): + folder = local("formcut", {"README.md": "x\n"}) + out = client.post("/api/sources/formcut/pull", json={"update": True}) + assert out.status_code == 200 + assert out.json()["method"] == "local" and out.json()["dir"] == str(folder) + assert sorted(f.name for f in folder.iterdir()) == ["README.md"] From 3174bb1043c089c53b7bbe15fd6987925f6a26c2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:18 -0500 Subject: [PATCH 10/15] test(security): window key refusal sweep over every write route, publisher keys kept private, settings seal tamper detection, local family and portal catalogue reads, ordered event bus and agent feed (0.11.0) Checks through the real app's HTTP routes, live and agent sockets and public service functions that every non-GET route answers 403 "Only the form.ext window can do this" without the key (the sweep walks the app's own route tree and is checked against its API schema, never calling the two forbidden publish routes), that private key halves stay on disk (0600) and out of every answer, that hand-edited or forged sealed settings are reported broken and dropped, that the family list and FormPortal catalogue come from local files, and that bus and agent-feed events arrive in order without argument values; expected values come from the stated refusal sentences, an independent Ed25519 and HMAC-SHA256 computation, the dev.json contract and files written by the tests. Ran: backend/venv/bin/python -m pytest tests/security -q -p no:cacheprovider, 170 passed, 0 expected failures. --- tests/security/conftest.py | 43 ++++ tests/security/test_security_feeds.py | 210 +++++++++++++++++ tests/security/test_security_keys.py | 247 ++++++++++++++++++++ tests/security/test_security_local_files.py | 188 +++++++++++++++ tests/security/test_security_seal.py | 179 ++++++++++++++ tests/security/test_security_window_key.py | 190 +++++++++++++++ 6 files changed, 1057 insertions(+) create mode 100644 tests/security/conftest.py create mode 100644 tests/security/test_security_feeds.py create mode 100644 tests/security/test_security_keys.py create mode 100644 tests/security/test_security_local_files.py create mode 100644 tests/security/test_security_seal.py create mode 100644 tests/security/test_security_window_key.py diff --git a/tests/security/conftest.py b/tests/security/conftest.py new file mode 100644 index 0000000..77096db --- /dev/null +++ b/tests/security/conftest.py @@ -0,0 +1,43 @@ +import sys +from pathlib import Path + +import pytest + +TESTS = Path(__file__).resolve().parent.parent +if str(TESTS) not in sys.path: + sys.path.insert(0, str(TESTS)) + +import stand_ins # noqa: E402,F401 + +from fastapi.testclient import TestClient # noqa: E402 + +from app.main import app # noqa: E402 +from app.services import window_key # noqa: E402 + + +@pytest.fixture +def home(tmp_path, monkeypatch): + folder = tmp_path / "data" + folder.mkdir() + gh = tmp_path / "gh-stand-in" + gh.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") + gh.chmod(0o755) + portal = tmp_path / "portal" + portal.mkdir() + monkeypatch.setenv("FORMEXT_HOME", str(folder)) + monkeypatch.setenv("FORMEXT_WATCH", "0") + monkeypatch.setenv("FORMEXT_SOURCES_AUTO", "0") + monkeypatch.setenv("FORMEXT_GH_BIN", str(gh)) + monkeypatch.setenv("FORMPORTAL_ROOT", str(portal)) + monkeypatch.delenv("FORMEXT_WINDOW_KEY_STDOUT", raising=False) + return folder + + +@pytest.fixture +def client(home): + return TestClient(app, headers={window_key.HEADER: window_key.KEY}, raise_server_exceptions=False) + + +@pytest.fixture +def outsider(home): + return TestClient(app, raise_server_exceptions=False) diff --git a/tests/security/test_security_feeds.py b/tests/security/test_security_feeds.py new file mode 100644 index 0000000..6384451 --- /dev/null +++ b/tests/security/test_security_feeds.py @@ -0,0 +1,210 @@ +import asyncio +import json +import threading +from collections import deque + +import pytest + +from app.services import agent_feed, window_key +from app.services.bus import Bus + + +def _run(coro): + return asyncio.run(coro) + + +def test_the_bus_delivers_events_to_a_subscriber_in_the_order_they_were_emitted(): + async def scenario(): + bus = Bus() + bus.attach(asyncio.get_running_loop()) + queue = bus.subscribe() + for i in range(200): + bus.emit("n", i) + return [queue.get_nowait()["data"] for _ in range(queue.qsize())] + assert _run(scenario()) == list(range(200)) + + +def test_events_emitted_from_another_thread_arrive_in_order(): + async def scenario(): + bus = Bus() + bus.attach(asyncio.get_running_loop()) + queue = bus.subscribe() + worker = threading.Thread(target=lambda: [bus.emit("n", i) for i in range(100)]) + worker.start() + await asyncio.to_thread(worker.join) + return [(await queue.get())["data"] for _ in range(100)] + assert _run(scenario()) == list(range(100)) + + +def test_every_subscriber_gets_the_same_sequence(): + async def scenario(): + bus = Bus() + bus.attach(asyncio.get_running_loop()) + first, second = bus.subscribe(), bus.subscribe() + for name in ("a", "b", "c"): + bus.emit(name, {"x": name}) + return [[q.get_nowait()["name"] for _ in range(3)] for q in (first, second)] + assert _run(scenario()) == [["a", "b", "c"], ["a", "b", "c"]] + + +def test_an_event_carries_its_name_data_and_a_time(): + async def scenario(): + bus = Bus() + bus.attach(asyncio.get_running_loop()) + queue = bus.subscribe() + bus.emit("keys.changed", {"id": "acme"}) + return queue.get_nowait() + got = _run(scenario()) + assert got["name"] == "keys.changed" + assert got["data"] == {"id": "acme"} + assert isinstance(got["at"], float) + + +def test_an_unsubscribed_queue_receives_nothing_more_and_the_count_drops(): + async def scenario(): + bus = Bus() + bus.attach(asyncio.get_running_loop()) + kept, gone = bus.subscribe(), bus.subscribe() + assert bus.clients() == 2 + bus.unsubscribe(gone) + bus.emit("n", 1) + return bus.clients(), kept.qsize(), gone.qsize() + assert _run(scenario()) == (1, 1, 0) + + +def test_a_bus_without_a_loop_drops_events_without_raising(): + bus = Bus() + bus.subscribe() + bus.emit("n", 1) + assert bus.clients() == 1 + + +def test_a_full_subscriber_keeps_the_first_thousand_events_in_order(): + async def scenario(): + bus = Bus() + bus.attach(asyncio.get_running_loop()) + queue = bus.subscribe() + for i in range(1100): + bus.emit("n", i) + return [queue.get_nowait()["data"] for _ in range(queue.qsize())] + assert _run(scenario()) == list(range(1000)) + + +def test_creating_a_key_is_announced_on_the_live_socket(client, outsider): + with outsider.websocket_connect("/api/live") as ws: + assert ws.receive_json()["name"] == "hello" + assert client.post("/api/keys", json={"id": "acme", "name": "Acme"}).status_code == 200 + for _ in range(20): + message = ws.receive_json() + if message["name"] == "keys.changed": + break + assert message["data"] == {"id": "acme", "kind": "created"} + assert "private_key" not in json.dumps(message) + + +def test_the_live_hello_reports_the_running_version(outsider): + version = outsider.get("/api/health").json()["version"] + with outsider.websocket_connect("/api/live") as ws: + hello = ws.receive_json() + assert hello["data"] == {"app": "formext", "version": version} + + +def test_the_live_socket_answers_a_ping_with_a_pong(outsider): + with outsider.websocket_connect("/api/live") as ws: + ws.receive_json() + ws.send_text("ping") + for _ in range(20): + if ws.receive_json()["name"] == "pong": + break + else: + pytest.fail("no pong") + + +@pytest.fixture +def feed(monkeypatch): + log = deque(maxlen=agent_feed.KEEP) + monkeypatch.setattr(agent_feed, "_log", log) + return log + + +def test_an_agent_call_is_logged_with_its_tool_title_and_project(feed): + call = agent_feed.began("Probe", {"name": "family", "arguments": {"id": "grain-tool"}}) + row = agent_feed.backlog()[-1] + assert row["id"] == call + assert row["line"] == "Probe: Form family (family) in the project grain-tool" + assert row["readOnly"] is True + + +def test_an_agent_call_keeps_no_argument_values(feed): + agent_feed.began("Probe", {"name": "source", "arguments": {"id": "p1", "content": "TOP-SECRET-TEXT", "token": "abc123xyz"}}) + agent_feed.ended(agent_feed.backlog()[-1]["id"], {"result": {"content": [{"text": "RESULT-BODY"}]}}) + text = json.dumps(agent_feed.backlog()) + for secret in ("TOP-SECRET-TEXT", "abc123xyz", "RESULT-BODY"): + assert secret not in text + + +def test_an_unknown_tool_is_logged_by_name_with_no_project(feed): + agent_feed.began("", {"name": "made_up", "arguments": {"id": "p1"}}) + row = agent_feed.backlog()[-1] + assert row["line"] == "An outside agent: made_up (made_up)" + assert row["project"] == "" + assert row["readOnly"] is False + + +def test_control_characters_in_a_tool_name_are_stripped_and_the_name_capped(feed): + agent_feed.began("Probe", {"name": "bad\x1b[31m\n" + "x" * 200}) + tool = agent_feed.backlog()[-1]["tool"] + assert "\x1b" not in tool and "\n" not in tool + assert len(tool) == 80 + + +def test_a_call_ending_in_an_error_is_logged_as_refused_or_failed(feed): + call = agent_feed.began("Probe", {"name": "status"}) + agent_feed.ended(call, {"result": {"isError": True}}) + agent_feed.ended(call, {"error": {"code": -32000}}) + agent_feed.ended(call, {"result": {"content": []}}) + rows = agent_feed.backlog()[-3:] + assert [(r["ok"], r["line"]) for r in rows] == [(False, "refused or failed"), (False, "refused or failed"), (True, "done")] + + +def test_the_feed_keeps_only_the_most_recent_calls_in_order(feed): + for i in range(agent_feed.KEEP + 20): + agent_feed.began("Probe", {"name": f"t{i}"}) + names = [r["tool"] for r in agent_feed.backlog()] + assert len(names) == agent_feed.KEEP + assert names[0] == "t20" + assert names[-1] == f"t{agent_feed.KEEP + 19}" + + +@pytest.fixture +def local(home): + from fastapi.testclient import TestClient + + from app.main import app + return TestClient(app, base_url="http://127.0.0.1", raise_server_exceptions=False) + + +def test_the_agent_stream_sends_the_backlog_to_a_window_with_the_key(feed, local): + agent_feed.began("Probe", {"name": "status"}) + with local.websocket_connect("ws://127.0.0.1/api/agents/stream") as ws: + ws.send_text(json.dumps({"type": "window", "key": window_key.KEY})) + assert json.loads(ws.receive_text())["type"] == "hello" + assert json.loads(ws.receive_text())["line"] == "Probe: Status (status)" + + +def test_the_agent_stream_closes_on_a_window_without_the_key(feed, local): + from starlette.websockets import WebSocketDisconnect + agent_feed.began("Probe", {"name": "status"}) + with pytest.raises(WebSocketDisconnect) as caught: + with local.websocket_connect("ws://127.0.0.1/api/agents/stream") as ws: + ws.send_text(json.dumps({"type": "window", "key": "wrong"})) + ws.receive_text() + assert caught.value.code == 4403 + + +def test_the_agent_stream_refuses_a_page_from_another_site(feed, local): + from starlette.websockets import WebSocketDisconnect + with pytest.raises(WebSocketDisconnect) as caught: + with local.websocket_connect("ws://127.0.0.1/api/agents/stream", headers={"origin": "https://evil.example"}) as ws: + ws.receive_text() + assert caught.value.code == 4403 diff --git a/tests/security/test_security_keys.py b/tests/security/test_security_keys.py new file mode 100644 index 0000000..fb6427f --- /dev/null +++ b/tests/security/test_security_keys.py @@ -0,0 +1,247 @@ +import base64 +import hashlib +import json +import os +import stat + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + +from app.services import keys as keys_module +from app.services.keys import SignatureRefused, keys + +SECRET_MARKERS = ("private_key", "PRIVATE KEY", "passphrase") + + +def _key_file(home, kid): + return home / "keys" / f"{kid}.json" + + +def _no_secret(text): + for marker in SECRET_MARKERS: + assert marker not in text + + +def _create(client, kid="acme", name="Acme Tools", **extra): + reply = client.post("/api/keys", json={"id": kid, "name": name, **extra}) + assert reply.status_code == 200, reply.text + return reply.json() + + +def test_creating_a_key_answers_without_the_private_half(client): + reply = client.post("/api/keys", json={"id": "acme", "name": "Acme Tools"}) + _no_secret(reply.text) + assert reply.json()["id"] == "acme" + assert reply.json()["algorithm"] == "ed25519" + + +def test_the_private_half_is_stored_on_disk_readable_only_by_the_owner(client, home): + _create(client) + target = _key_file(home, "acme") + stored = json.loads(target.read_text(encoding="utf-8")) + assert "BEGIN PRIVATE KEY" in stored["private_key"] + if os.name != "nt": + assert stat.S_IMODE(target.stat().st_mode) == 0o600 + + +def test_the_public_key_returned_matches_the_stored_private_key(client, home): + made = _create(client) + pem = json.loads(_key_file(home, "acme").read_text(encoding="utf-8"))["private_key"] + private = serialization.load_pem_private_key(pem.encode("ascii"), password=None) + raw = private.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + assert base64.b64decode(made["public_key"]) == raw + assert len(raw) == 32 + + +def test_the_fingerprint_is_the_first_twenty_hex_digits_of_the_public_key_hash_in_groups_of_four(client): + made = _create(client) + digest = hashlib.sha256(base64.b64decode(made["public_key"])).hexdigest()[:20] + assert made["fingerprint"] == " ".join(digest[i:i + 4] for i in range(0, 20, 4)) + + +@pytest.mark.parametrize("route", ["/api/keys", "/api/keys/acme", "/api/keys/acme/public"]) +def test_no_read_route_returns_the_private_half(client, route): + _create(client, passphrase="correct horse") + reply = client.get(route) + assert reply.status_code == 200 + _no_secret(reply.text) + assert "acme" in reply.text + + +def test_a_passphrase_encrypts_the_stored_key_and_is_not_written_down(client, home): + made = _create(client, passphrase="correct horse") + assert made["encrypted"] is True + text = _key_file(home, "acme").read_text(encoding="utf-8") + assert "ENCRYPTED PRIVATE KEY" in text + assert "correct horse" not in text + pem = json.loads(text)["private_key"].encode("ascii") + with pytest.raises(TypeError): + serialization.load_pem_private_key(pem, password=None) + + +def test_a_short_passphrase_is_refused_with_its_reason(client, home): + reply = client.post("/api/keys", json={"id": "acme", "name": "Acme", "passphrase": "short"}) + assert reply.status_code == 400 + assert reply.json()["detail"] == "A passphrase needs at least 8 characters, or leave it empty." + assert not _key_file(home, "acme").exists() + + +@pytest.mark.parametrize("kid", ["A", "-lead", "UPPER", "has space", "a" * 40, "../up"]) +def test_a_badly_formed_publisher_id_is_refused(client, kid): + reply = client.post("/api/keys", json={"id": kid, "name": "X"}) + assert reply.status_code == 400 + assert reply.json()["detail"] == "A publisher id is 2 to 39 lower-case letters, digits and hyphens, starting with a letter or digit." + + +def test_a_publisher_address_that_is_not_https_is_refused(client): + reply = client.post("/api/keys", json={"id": "acme", "name": "Acme", "url": "http://acme.example"}) + assert reply.status_code == 400 + assert reply.json()["detail"] == "The publisher address must start with https://." + + +def test_a_second_key_with_the_same_id_is_refused_and_the_first_survives(client): + first = _create(client) + again = client.post("/api/keys", json={"id": "acme", "name": "Other"}) + assert again.status_code == 409 + assert again.json()["detail"] == "a publisher key acme already exists" + assert client.get("/api/keys/acme").json()["public_key"] == first["public_key"] + + +def test_a_key_id_that_climbs_out_of_the_folder_is_not_found(client): + reply = client.get("/api/keys/..%2Fsettings") + assert reply.status_code == 404 + + +def test_removing_a_key_moves_it_to_the_trash_still_private(client, home): + _create(client) + reply = client.delete("/api/keys/acme") + assert reply.status_code == 200 + kept = reply.json()["kept"] + assert reply.json()["removed"] is True + assert client.get("/api/keys").json() == {"keys": []} + assert not _key_file(home, "acme").exists() + assert "BEGIN PRIVATE KEY" in json.loads(open(kept, encoding="utf-8").read())["private_key"] + if os.name != "nt": + assert stat.S_IMODE(os.stat(kept).st_mode) == 0o600 + + +def test_removing_a_missing_key_says_so(client): + reply = client.delete("/api/keys/ghost") + assert reply.status_code == 404 + assert reply.json()["detail"] == "no publisher key ghost" + + +def test_the_public_export_lists_what_a_registry_index_needs(client): + made = _create(client, url="https://acme.example") + out = client.get("/api/keys/acme/public").json() + assert out["publisher"] == {"id": "acme", "name": "Acme Tools", "public_key": made["public_key"], "url": "https://acme.example"} + assert out["fingerprint"] == made["fingerprint"] + + +def test_a_signature_made_by_a_key_verifies_with_an_independent_ed25519_reader(home): + made = keys.create("acme", "Acme") + body = b"package bytes" + signed = keys.sign("acme", body) + public = Ed25519PublicKey.from_public_bytes(base64.b64decode(made["public_key"])) + public.verify(base64.b64decode(signed["value"]), body) + assert signed["publisher"] == "acme" + assert signed["algorithm"] == "ed25519" + + +def test_a_changed_body_no_longer_matches_its_signature(home): + made = keys.create("acme", "Acme") + signed = keys.sign("acme", b"package bytes") + with pytest.raises(SignatureRefused) as caught: + keys_module.verify(b"package bytez", signed["value"], [made["public_key"]]) + assert caught.value.message == "its signature does not match a key this build trusts" + + +def test_a_signature_with_one_flipped_bit_is_refused(home): + made = keys.create("acme", "Acme") + raw = bytearray(base64.b64decode(keys.sign("acme", b"body")["value"])) + raw[10] ^= 1 + with pytest.raises(SignatureRefused) as caught: + keys_module.verify(b"body", base64.b64encode(bytes(raw)).decode(), [made["public_key"]]) + assert caught.value.message == "its signature does not match a key this build trusts" + + +def test_a_signature_from_another_key_is_refused(home): + keys.create("acme", "Acme") + other = keys.create("rival", "Rival") + value = keys.sign("acme", b"body")["value"] + with pytest.raises(SignatureRefused): + keys_module.verify(b"body", value, [other["public_key"]]) + + +@pytest.mark.parametrize("value,said", [ + ("not base64 !!", "its signature is not valid base64"), + (base64.b64encode(b"x" * 63).decode(), "its signature is not 64 bytes"), +]) +def test_a_malformed_signature_is_refused_with_its_reason(home, value, said): + made = keys.create("acme", "Acme") + with pytest.raises(SignatureRefused) as caught: + keys_module.verify(b"body", value, [made["public_key"]]) + assert caught.value.message == said + + +def test_verifying_with_no_trusted_key_is_refused(): + with pytest.raises(SignatureRefused) as caught: + keys_module.verify(b"body", base64.b64encode(b"x" * 64).decode(), []) + assert caught.value.message == "this build trusts no catalogue key yet" + + +def test_a_protected_key_will_not_sign_without_its_passphrase(home): + keys.create("acme", "Acme", passphrase="correct horse") + with pytest.raises(keys_module.Locked) as caught: + keys.sign("acme", b"body") + assert caught.value.message == "the key acme is protected: give its passphrase" + assert caught.value.status == 401 + + +def test_a_protected_key_will_not_sign_with_a_wrong_passphrase(home): + keys.create("acme", "Acme", passphrase="correct horse") + with pytest.raises(keys_module.Locked) as caught: + keys.sign("acme", b"body", "wrong horse") + assert caught.value.message == "the passphrase does not open the key acme" + + +def test_a_protected_key_signs_with_its_passphrase(home): + made = keys.create("acme", "Acme", passphrase="correct horse") + signed = keys.sign("acme", b"body", "correct horse") + keys_module.verify(b"body", signed["value"], [made["public_key"]]) + + +def test_a_package_signed_by_a_publisher_the_index_does_not_list_is_refused(home, tmp_path): + made = keys.create("acme", "Acme") + package = tmp_path / "x.formext" + package.write_bytes(b"zip bytes") + signature = keys.sign("acme", package.read_bytes()) + publishers = [{"id": "acme", "name": "Acme", "public_key": made["public_key"]}] + assert keys_module.check_signature(package, signature, publishers) == "acme" + with pytest.raises(SignatureRefused) as caught: + keys_module.check_signature(package, {**signature, "publisher": "nobody"}, publishers) + assert caught.value.message == 'the package names a publisher, "nobody", that the index does not list' + package.write_bytes(b"zip bytez") + with pytest.raises(SignatureRefused) as caught: + keys_module.check_signature(package, signature, publishers) + assert caught.value.message == "the package's signature does not match Acme's key" + + +def test_a_signature_naming_another_algorithm_is_refused(home, tmp_path): + made = keys.create("acme", "Acme") + package = tmp_path / "x.formext" + package.write_bytes(b"zip") + signature = {**keys.sign("acme", b"zip"), "algorithm": "rsa"} + with pytest.raises(SignatureRefused) as caught: + keys_module.check_signature(package, signature, [{"id": "acme", "name": "Acme", "public_key": made["public_key"]}]) + assert caught.value.message == 'the package\'s signature uses "rsa", not ed25519' + + +def test_a_key_file_edited_to_another_format_is_left_out_of_the_list(client, home): + _create(client) + _create(client, kid="other", name="Other") + target = _key_file(home, "other") + data = json.loads(target.read_text(encoding="utf-8")) + target.write_text(json.dumps({**data, "format": "something-else"}), encoding="utf-8") + assert [k["id"] for k in client.get("/api/keys").json()["keys"]] == ["acme"] diff --git a/tests/security/test_security_local_files.py b/tests/security/test_security_local_files.py new file mode 100644 index 0000000..b36fb77 --- /dev/null +++ b/tests/security/test_security_local_files.py @@ -0,0 +1,188 @@ +import json +import os + +import pytest + +from app.services import paths, portal, sources + + +def _portal(home): + return home.parent / "portal" + + +def _write(path, data): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(data if isinstance(data, str) else json.dumps(data), encoding="utf-8") + + +def _app(overview, product): + return next(a for a in overview["apps"] if a["product"] == product) + + +def test_the_family_list_names_every_family_app_in_order(client): + got = client.get("/api/sources/family").json() + assert [a["id"] for a in got["apps"]] == [row[0] for row in sources.FAMILY] + assert [a["repository"] for a in got["apps"]] == [f"nodemode-dev/{row[2]}" for row in sources.FAMILY] + + +def test_the_family_list_links_an_api_page_exactly_when_the_docs_folder_holds_one(client): + folder = paths.docs_dir() / "apps" + for row in client.get("/api/sources/family").json()["apps"]: + has_page = os.path.isfile(folder / f"{row['id']}.md") + assert row["api_page"] == (row["id"] if has_page else None) + + +def test_the_family_list_marks_starters_by_the_templates_folder(client): + folder = paths.templates_dir() + for row in client.get("/api/sources/family").json()["apps"]: + assert row["starters"] == os.path.isdir(folder / row["id"]) + + +def test_the_family_list_reports_the_portal_folder_from_the_environment(client, home): + got = client.get("/api/sources/family").json()["formportal"]["root"] + assert got == {"path": str(_portal(home)), "source": "FORMPORTAL_ROOT", "exists": True} + + +def test_an_app_without_skills_says_so_and_refuses_to_install_them(client): + got = client.get("/api/sources/formtray/skills").json() + assert got["note"] == "FormTray ships no skill of its own; read its API page (docs) and its source instead." + install = client.post("/api/sources/formtray/skills", json={}) + assert install.status_code == 400 + assert install.json()["detail"] == got["note"] + + +def test_installing_skills_needs_the_window_key(outsider): + reply = outsider.post("/api/sources/formvis/skills", json={}) + assert reply.status_code == 403 + + +def test_the_portal_root_comes_from_the_environment_folder(client, home): + assert client.get("/api/runapp/root").json() == {"path": str(_portal(home)), "source": "FORMPORTAL_ROOT", "exists": True} + + +def test_a_missing_portal_folder_is_reported_as_absent(client, home, monkeypatch): + monkeypatch.setenv("FORMPORTAL_ROOT", str(home / "nowhere")) + assert client.get("/api/runapp/root").json()["exists"] is False + + +def test_the_catalogue_lists_every_app_with_no_installs_when_the_folder_is_empty(client): + got = client.get("/api/runapp").json() + assert [a["product"] for a in got["apps"]] == [p for p, _ in portal.APPS] + assert all(a["installs"] == [] and a["version"] is None for a in got["apps"]) + assert got["state_error"] == "" + + +def test_the_catalogue_reads_installs_from_the_portal_installed_file(client, home): + present = home.parent / "formvis-app" + present.mkdir() + _write(_portal(home) / "installed.json", {"installs": [ + {"product": "formvis", "channel": "nightly", "current": {"version": "3.0.0-n", "path": str(home / "gone")}}, + {"product": "formvis", "channel": "stable", "current": {"version": "2.1.0", "path": str(present)}, "previous": {"version": "2.0.0"}}, + {"product": "formcut", "channel": "beta"}, + ]}) + app = _app(client.get("/api/runapp").json(), "formvis") + assert [(i["channel"], i["version"], i["present"]) for i in app["installs"]] == [("stable", "2.1.0", True), ("nightly", "3.0.0-n", False)] + assert app["installs"][0]["previous"] == "2.0.0" + assert app["version"] == "2.1.0" + assert _app(client.get("/api/runapp").json(), "formcut")["installs"] == [] + + +def test_an_unreadable_installed_file_is_reported_not_trusted(client, home): + _write(_portal(home) / "installed.json", "{not json") + got = client.get("/api/runapp").json() + assert got["state_error"] == "FormPortal's installed.json cannot be read" + assert all(a["installs"] == [] for a in got["apps"]) + + +def test_the_catalogue_reads_installed_extensions_per_app(client, home): + _write(_portal(home) / "extensions" / "installed.json", {"extensions": [ + {"product": "formwav", "id": "reverb", "name": "Reverb", "version": "1.2.0", "source": "catalogue", "enabled": True, "signed_by": "acme"}, + "junk", + ]}) + got = _app(client.get("/api/runapp").json(), "formwav")["extensions"] + assert got == [{"id": "reverb", "name": "Reverb", "version": "1.2.0", "source": "catalogue", "enabled": True, "signed_by": "acme"}] + + +def test_the_catalogue_reads_enabled_extensions_only_in_the_portal_format(client, home): + folder = _portal(home) / "extensions" / "formpdf" + _write(folder / "enabled.json", {"format": "formportal-enabled-extensions", "extensions": [{"id": "stamp", "version": "0.1.0"}]}) + enabled = _app(client.get("/api/runapp").json(), "formpdf")["enabled"] + assert enabled["extensions"] == [{"id": "stamp", "version": "0.1.0", "source": "catalogue", "path": ""}] + _write(folder / "enabled.json", {"format": "other", "extensions": [{"id": "stamp"}]}) + assert _app(client.get("/api/runapp").json(), "formpdf")["enabled"]["extensions"] == [] + + +def test_a_dev_list_written_through_the_route_round_trips_through_the_file(client, home): + body = {"format": "formext-dev-extensions", "format_version": 1, "product": "formvis", + "extensions": [{"id": "grain", "path": "/x/grain", "added": "2026-01-01T00:00:00Z", "extra": "dropped"}]} + reply = client.put("/api/runapp/apps/formvis/dev", json=body) + assert reply.status_code == 200 + on_disk = json.loads((_portal(home) / "extensions" / "formvis" / "dev.json").read_text(encoding="utf-8")) + assert on_disk == {"format": "formext-dev-extensions", "format_version": 1, "product": "formvis", + "extensions": [{"id": "grain", "path": "/x/grain", "added": "2026-01-01T00:00:00Z"}]} + assert client.get("/api/runapp/apps/formvis/dev").json()["dev"] == on_disk + + +@pytest.mark.parametrize("change,said", [ + ({"format": "wrong"}, 'format must be "formext-dev-extensions"'), + ({"format_version": 2}, "format_version must be 1"), + ({"product": "formcut"}, 'product must be "formvis"'), + ({"extensions": [{"id": "X!", "path": "/x"}]}, "extensions[0].id must match ^[a-z0-9][a-z0-9-]{1,63}$"), + ({"extensions": [{"id": "ok", "path": ""}]}, "extensions[0].path must be a non-empty string"), +]) +def test_a_dev_list_breaking_the_contract_is_refused_and_not_written(client, home, change, said): + body = {"format": "formext-dev-extensions", "format_version": 1, "product": "formvis", "extensions": [], **change} + reply = client.put("/api/runapp/apps/formvis/dev", json=body) + assert reply.status_code == 422 + assert reply.json()["detail"] == "dev.json would not follow the contract: " + said + assert not (_portal(home) / "extensions" / "formvis" / "dev.json").exists() + + +def test_a_dev_list_naming_one_extension_twice_is_refused(client): + body = {"format": "formext-dev-extensions", "format_version": 1, "product": "formvis", + "extensions": [{"id": "grain", "path": "/a"}, {"id": "grain", "path": "/b"}]} + reply = client.put("/api/runapp/apps/formvis/dev", json=body) + assert reply.status_code == 422 + assert reply.json()["detail"] == "dev.json lists grain twice" + + +def test_a_dev_list_for_an_unknown_app_is_not_found(client): + reply = client.put("/api/runapp/apps/notanapp/dev", json={}) + assert reply.status_code == 404 + assert reply.json()["detail"] == "unknown product: notanapp" + + +def test_a_corrupt_dev_file_is_reported_as_a_problem(client, home): + _write(_portal(home) / "extensions" / "formvis" / "dev.json", "[oops") + got = client.get("/api/runapp/apps/formvis/dev").json() + assert got["exists"] is True + assert got["problems"] == ["dev.json is not valid JSON"] + assert got["dev"]["extensions"] == [] + + +def test_reloading_an_app_without_a_dev_file_says_so(client): + reply = client.post("/api/runapp/apps/formvis/reload") + assert reply.status_code == 404 + assert reply.json()["detail"] == "FormVis has no dev.json yet" + + +def test_removing_an_extension_absent_from_the_dev_list_says_so(client): + reply = client.delete("/api/runapp/apps/formwav/dev/ghost") + assert reply.status_code == 404 + assert reply.json()["detail"] == "ghost is not in FormWav's dev.json" + + +def test_removing_a_listed_extension_keeps_the_others(client, home): + body = {"format": "formext-dev-extensions", "format_version": 1, "product": "formvis", + "extensions": [{"id": "grain", "path": "/a"}, {"id": "blur", "path": "/b"}]} + client.put("/api/runapp/apps/formvis/dev", json=body) + reply = client.delete("/api/runapp/apps/formvis/dev/grain") + assert reply.status_code == 200 + assert [r["id"] for r in reply.json()["dev"]["extensions"]] == ["blur"] + + +def test_a_dev_list_write_without_the_window_key_leaves_no_file(outsider, home): + body = {"format": "formext-dev-extensions", "format_version": 1, "product": "formvis", "extensions": []} + reply = outsider.put("/api/runapp/apps/formvis/dev", json=body) + assert reply.status_code == 403 + assert not (_portal(home) / "extensions" / "formvis" / "dev.json").exists() diff --git a/tests/security/test_security_seal.py b/tests/security/test_security_seal.py new file mode 100644 index 0000000..426d51d --- /dev/null +++ b/tests/security/test_security_seal.py @@ -0,0 +1,179 @@ +import hashlib +import hmac +import json + +import keyring +import pytest +from keyring.backend import KeyringBackend + +from app.services import seal, settings, window_key + +SEALED = ("formportal_root", "formportal_cli", "agent_access") + + +class MemoryKeyring(KeyringBackend): + priority = 1 + + def __init__(self): + super().__init__() + self.store = {} + + def get_password(self, service, username): + return self.store.get((service, username)) + + def set_password(self, service, username, password): + self.store[(service, username)] = password + + def delete_password(self, service, username): + self.store.pop((service, username), None) + + +@pytest.fixture +def vault(home): + before = keyring.get_keyring() + memory = MemoryKeyring() + keyring.set_keyring(memory) + seal.reset() + yield memory + keyring.set_keyring(before) + seal.reset() + + +@pytest.fixture +def no_vault(home): + from keyring.backends import fail + before = keyring.get_keyring() + keyring.set_keyring(fail.Keyring()) + seal.reset() + yield + keyring.set_keyring(before) + seal.reset() + + +def _stored(home): + return json.loads((home / "settings.json").read_text(encoding="utf-8")) + + +def _rewrite(home, **changes): + data = _stored(home) + data.update(changes) + (home / "settings.json").write_text(json.dumps(data), encoding="utf-8") + + +def test_settings_written_by_the_window_are_sealed(client, vault, tmp_path): + reply = client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + assert reply.json()["seal"] == "ok" + assert reply.json()["sealBroken"] is False + assert client.get("/api/settings").json()["formportal_root"] == str(tmp_path) + + +def test_the_seal_on_disk_is_an_hmac_sha256_of_the_sealed_fields_with_the_vault_key(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + key = bytes.fromhex(vault.store[("form.ext", "settings-seal")]) + stored = {**settings.DEFAULTS, **_stored(home)} + body = json.dumps({k: stored.get(k) for k in SEALED}, sort_keys=True, separators=(",", ":")) + assert stored["seal"] == hmac.new(key, body.encode("utf-8"), hashlib.sha256).hexdigest() + + +def test_the_seal_value_itself_is_never_returned(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + mark = _stored(home)["seal"] + assert mark not in client.get("/api/settings").text + assert vault.store[("form.ext", "settings-seal")] not in client.get("/api/settings").text + + +def test_a_hand_edited_portal_folder_breaks_the_seal_and_is_dropped(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + _rewrite(home, formportal_root="/somewhere/else") + got = client.get("/api/settings").json() + assert got["seal"] == "broken" + assert got["sealBroken"] is True + assert got["formportal_root"] == "" + assert got["agentAccessReset"] is False + + +def test_a_hand_edited_agent_access_breaks_the_seal_and_reports_the_reset(client, vault, home): + client.put("/api/settings", json={"agent_access": "blocked"}) + _rewrite(home, agent_access="allowed") + got = client.get("/api/settings").json() + assert got["seal"] == "broken" + assert got["agent_access"] == "" + assert got["agentAccessReset"] is True + + +def test_a_removed_seal_on_loosened_settings_counts_as_broken(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_cli": str(tmp_path / "cli")}) + data = _stored(home) + data.pop("seal") + (home / "settings.json").write_text(json.dumps(data), encoding="utf-8") + got = client.get("/api/settings").json() + assert got["seal"] == "broken" + assert got["formportal_cli"] == "" + + +def test_a_forged_seal_made_with_another_key_is_broken(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + stored = _stored(home) + stored["formportal_root"] = "/forged" + stored["seal"] = seal.digest(stored, b"\x00" * 32) + (home / "settings.json").write_text(json.dumps(stored), encoding="utf-8") + assert client.get("/api/settings").json()["seal"] == "broken" + + +def test_the_portal_root_does_not_follow_a_tampered_setting(client, vault, home, tmp_path, monkeypatch): + monkeypatch.delenv("FORMPORTAL_ROOT", raising=False) + client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + assert client.get("/api/runapp/root").json() == {"path": str(tmp_path), "source": "settings", "exists": True} + _rewrite(home, formportal_root=str(home)) + root = client.get("/api/runapp/root").json() + assert root["source"] == "default" + assert root["path"] != str(home) + + +def test_editing_unsealed_fields_by_hand_keeps_the_seal(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_root": str(tmp_path)}) + _rewrite(home, theme="something") + assert client.get("/api/settings").json()["seal"] == "ok" + + +def test_settings_that_loosen_nothing_report_unsealed_not_broken(client, vault): + got = client.get("/api/settings").json() + assert got["seal"] == "unsealed" + assert got["sealBroken"] is False + + +def test_the_window_can_reseal_after_a_break_and_keeps_only_what_it_sends(client, vault, home, tmp_path): + client.put("/api/settings", json={"formportal_root": str(tmp_path), "formportal_cli": "/bin/true"}) + _rewrite(home, formportal_root="/elsewhere") + again = client.put("/api/settings", json={"formportal_root": str(tmp_path)}).json() + assert again["seal"] == "ok" + assert again["formportal_root"] == str(tmp_path) + assert again["formportal_cli"] == "" + + +def test_without_a_system_vault_the_seal_is_reported_unavailable(client, no_vault, tmp_path): + got = client.put("/api/settings", json={"formportal_root": str(tmp_path)}).json() + assert got["seal"] == "unavailable" + assert got["sealBroken"] is False + assert got["formportal_root"] == str(tmp_path) + + +def test_a_client_cannot_set_the_seal_fields_through_the_body(client, vault, home): + client.put("/api/settings", json={"seal": "f" * 64, "sealBroken": False, "agentAccessReset": True}) + stored = _stored(home) + assert stored.get("seal") != "f" * 64 + assert "sealBroken" not in stored + assert "agentAccessReset" not in stored + + +def test_a_settings_write_without_the_window_key_is_refused_and_changes_nothing(outsider, vault, home): + reply = outsider.put("/api/settings", json={"agent_access": "allowed"}) + assert reply.status_code == 403 + assert reply.json() == {"detail": window_key.REFUSED} + assert not (home / "settings.json").exists() + + +def test_an_unknown_agent_access_value_is_refused_with_its_reason(client, vault): + reply = client.put("/api/settings", json={"agent_access": "always"}) + assert reply.status_code == 400 + assert reply.json()["detail"] == "agent_access is ask, allowed or blocked" diff --git a/tests/security/test_security_window_key.py b/tests/security/test_security_window_key.py new file mode 100644 index 0000000..eea13b0 --- /dev/null +++ b/tests/security/test_security_window_key.py @@ -0,0 +1,190 @@ +import re + +import pytest +from fastapi.routing import APIRoute + +from app.main import app +from app.services import window_key + +REFUSED = "Only the form.ext window can do this" +NEVER_CALLED = ("/send", "/registry/pull-request") +READS = {"GET", "HEAD", "OPTIONS"} + + +def _walk(routes, prefix=""): + for route in routes: + inner = getattr(route, "original_router", None) + if inner is not None: + context = getattr(route, "include_context", None) + extra = context.get("prefix", "") if isinstance(context, dict) else getattr(context, "prefix", "") + yield from _walk(inner.routes, prefix + (extra or "")) + elif isinstance(route, APIRoute): + yield prefix + route.path, route.methods + + +def _writes(): + out = [] + for path, methods in _walk(app.routes): + for method in sorted(methods - READS): + if path in ("/mcp", "/api/window/key"): + continue + if method == "POST" and path.endswith(NEVER_CALLED): + continue + out.append((method, re.sub(r"\{[^}]+\}", "probe", path))) + return out + + +WRITES = _writes() + + +def test_the_sweep_covers_every_write_route_the_api_schema_lists(): + listed = {(m.upper(), re.sub(r"\{[^}]+\}", "probe", p)) for p, ops in app.openapi()["paths"].items() for m in ops if m.upper() not in READS} + listed = {(m, p) for m, p in listed if p not in ("/mcp", "/api/window/key") and not (m == "POST" and p.endswith(NEVER_CALLED))} + assert len(listed) >= 40 + assert listed <= set(WRITES) + + +@pytest.mark.parametrize("method,path", WRITES, ids=[f"{m} {p}" for m, p in WRITES]) +def test_every_write_route_refuses_a_request_without_the_window_key(outsider, method, path): + reply = outsider.request(method, path, json={}) + assert reply.status_code == 403 + assert reply.json() == {"detail": REFUSED} + + +@pytest.mark.parametrize("method,path", WRITES[:12], ids=[f"{m} {p}" for m, p in WRITES[:12]]) +def test_a_wrong_window_key_is_refused_like_a_missing_one(outsider, method, path): + reply = outsider.request(method, path, json={}, headers={window_key.HEADER: window_key.KEY[:-1] + ("A" if window_key.KEY[-1] != "A" else "B")}) + assert reply.status_code == 403 + assert reply.json()["detail"] == REFUSED + + +def test_an_empty_window_key_header_is_refused(outsider): + reply = outsider.post("/api/keys", json={"id": "acme", "name": "Acme"}, headers={window_key.HEADER: ""}) + assert reply.status_code == 403 + assert reply.json()["detail"] == REFUSED + + +def test_a_refused_create_leaves_no_key_behind(outsider, client): + outsider.post("/api/keys", json={"id": "sneaky", "name": "Sneaky"}) + assert [k["id"] for k in client.get("/api/keys").json()["keys"]] == [] + + +def test_reading_health_needs_no_window_key(outsider): + reply = outsider.get("/api/health") + assert reply.status_code == 200 + assert reply.json()["ok"] is True + assert reply.json()["app"] == "formext" + + +def test_reading_the_key_list_needs_no_window_key(outsider): + assert outsider.get("/api/keys").json() == {"keys": []} + + +def test_the_window_key_header_lets_a_write_through(client): + reply = client.post("/api/keys", json={"id": "acme", "name": "Acme"}) + assert reply.status_code == 200 + assert reply.json()["id"] == "acme" + + +def test_valid_accepts_only_the_exact_key(): + assert window_key.valid(window_key.KEY) is True + assert window_key.valid(window_key.KEY + "x") is False + assert window_key.valid(window_key.KEY.upper() if window_key.KEY.upper() != window_key.KEY else window_key.KEY.lower()) is False + assert window_key.valid("") is False + assert window_key.valid(None) is False + assert window_key.valid(123) is False + + +def test_the_window_key_is_long_and_url_safe(): + assert len(window_key.KEY) >= 40 + assert re.fullmatch(r"[A-Za-z0-9_-]+", window_key.KEY) + + +def test_the_first_window_claims_the_key_and_it_opens_writes(outsider, monkeypatch): + monkeypatch.setattr(window_key, "STATE", {"claimed": False, "secondClaim": False}) + claimed = outsider.post("/api/window/key") + assert claimed.status_code == 200 + key = claimed.json()["key"] + made = outsider.post("/api/keys", json={"id": "first-window", "name": "First"}, headers={window_key.HEADER: key}) + assert made.status_code == 200 + assert made.json()["id"] == "first-window" + + +def test_a_second_claim_is_refused_and_reported(outsider, monkeypatch): + monkeypatch.setattr(window_key, "STATE", {"claimed": False, "secondClaim": False}) + assert outsider.post("/api/window/key").status_code == 200 + second = outsider.post("/api/window/key") + assert second.status_code == 409 + assert second.json()["detail"] == "Another window already holds this engine's window key; use that window, or restart form.ext" + assert "key" not in second.json() + state = outsider.get("/api/window").json() + assert state["claimed"] is True + assert state["secondClaim"] is True + + +def test_a_fresh_engine_reports_no_claim_yet(outsider, monkeypatch): + monkeypatch.setattr(window_key, "STATE", {"claimed": False, "secondClaim": False}) + assert outsider.get("/api/window").json() == {"packaged": False, "claimed": False, "secondClaim": False} + + +def test_a_packaged_engine_hands_out_no_key_over_http(outsider, monkeypatch): + monkeypatch.setattr(window_key, "STATE", {"claimed": False, "secondClaim": False}) + monkeypatch.setenv("FORMEXT_WINDOW_KEY_STDOUT", "1") + reply = outsider.post("/api/window/key") + assert reply.status_code == 404 + assert "key" not in reply.json() + assert outsider.get("/api/window").json()["packaged"] is True + assert window_key.STATE["claimed"] is False + + +def test_a_packaged_engine_prints_the_key_line(monkeypatch, capsys): + monkeypatch.setenv("FORMEXT_WINDOW_KEY_STDOUT", "1") + window_key.announce() + assert capsys.readouterr().out == "formext-window-key: " + window_key.KEY + "\n" + + +def test_an_unpackaged_engine_prints_nothing(monkeypatch, capsys): + monkeypatch.delenv("FORMEXT_WINDOW_KEY_STDOUT", raising=False) + window_key.announce() + assert capsys.readouterr().out == "" + + +def _until(ws, wanted): + for _ in range(20): + name = ws.receive_json()["name"] + if name in wanted: + return name + return None + + +def test_the_live_socket_admits_a_window_that_says_hello_with_the_key(outsider, monkeypatch): + from app.services.bus import bus + monkeypatch.setattr(bus, "_loop", bus._loop) + with outsider.websocket_connect("/api/live") as ws: + assert ws.receive_json()["name"] == "hello" + ws.send_json({"type": "window", "key": window_key.KEY}) + assert _until(ws, ("window.admitted", "window.refused")) == "window.admitted" + + +def test_the_live_socket_refuses_a_window_hello_with_a_wrong_key(outsider, monkeypatch): + from app.services.bus import bus + monkeypatch.setattr(bus, "_loop", bus._loop) + with outsider.websocket_connect("/api/live") as ws: + assert ws.receive_json()["name"] == "hello" + ws.send_json({"type": "window", "key": "not-the-key"}) + assert _until(ws, ("window.admitted", "window.refused")) == "window.refused" + + +def test_the_live_socket_delivers_bus_events_in_the_order_they_were_sent(outsider, monkeypatch): + from app.services.bus import bus + monkeypatch.setattr(bus, "_loop", bus._loop) + with outsider.websocket_connect("/api/live") as ws: + assert ws.receive_json()["name"] == "hello" + for i in range(25): + bus.emit("security.order", {"n": i}) + seen = [] + while len(seen) < 25: + message = ws.receive_json() + if message["name"] == "security.order": + seen.append(message["data"]["n"]) + assert seen == list(range(25)) From bc648b6d828ea9a10622d51d6ae6a58d4ad3bd3b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:18 -0500 Subject: [PATCH 11/15] test(shell): extension host bridge, sdk round trips, simulated host apps and the shell with docs, home and library panes (0.11.0) Checks the host bridge sandbox, handshake, permission refusals, consent memory, storage cap and timeouts, the SDK and the host wired to each other through postMessage, every simulated host app plus form.md apply, undo and reads, the sample wav and pdf through independent header and xref readers, and the real shell booted on index.html with docs, home and library mounted; expected values come from contract/CONTRACT.md (error codes, permission words, 30 s and 300 s timeouts, 256 KB storage, sandbox attributes), the docs markdown files, RIFF and PDF rules, and undo and round-trip invariants. Ran: cd frontend && npx vitest run tests/unit/shell, 131 passed, 0 expected failures. --- frontend/tests/unit/shell/host-bridge.test.ts | 306 ++++++++++++++++++ frontend/tests/unit/shell/sdk-host.test.ts | 228 +++++++++++++ frontend/tests/unit/shell/shell-boot.test.ts | 207 ++++++++++++ frontend/tests/unit/shell/sim.test.ts | 221 +++++++++++++ frontend/tests/unit/shell/wire.ts | 68 ++++ 5 files changed, 1030 insertions(+) create mode 100644 frontend/tests/unit/shell/host-bridge.test.ts create mode 100644 frontend/tests/unit/shell/sdk-host.test.ts create mode 100644 frontend/tests/unit/shell/shell-boot.test.ts create mode 100644 frontend/tests/unit/shell/sim.test.ts create mode 100644 frontend/tests/unit/shell/wire.ts diff --git a/frontend/tests/unit/shell/host-bridge.test.ts b/frontend/tests/unit/shell/host-bridge.test.ts new file mode 100644 index 0000000..72fef2b --- /dev/null +++ b/frontend/tests/unit/shell/host-bridge.test.ts @@ -0,0 +1,306 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { ExtensionHost, PERMISSION_WORDS } from '../../../../contract/host/host-bridge'; +import type { HostHandlers, Permission } from '../../../../contract/host/host-bridge'; +import { makeExt, fakeWindow, attach, ask, fromFrame, flush } from './wire'; + +function handlers(over: Partial = {}): HostHandlers { + return { + product: 'formwav', + app: 'form.wav', + appVersion: '9.9.9', + locale: () => 'en-GB', + theme: () => ({ mode: 'dark', tokens: { '--bg': '#000000' } }), + notify: vi.fn(), + consent: vi.fn(async () => true), + ...over, + }; +} + +async function granted(host: ExtensionHost, perms: Permission[]) { + const ext = makeExt({ permissions: perms }); + await host.ensureConsent(ext); + const container = document.createElement('div'); + const handle = host.mount(ext, container); + const fake = fakeWindow(); + attach(handle, fake); + return { ext, handle, fake, container }; +} + +beforeEach(() => { + localStorage.clear(); + document.body.innerHTML = ''; +}); + +describe('host bridge frame', () => { + it('builds the sandboxed frame the contract describes', () => { + const host = new ExtensionHost(handlers()); + const box = document.createElement('div'); + const h = host.mount(makeExt(), box); + expect(h.frame.getAttribute('sandbox')).toBe('allow-scripts'); + expect(h.frame.getAttribute('allow')).toBe(''); + expect(h.frame.getAttribute('referrerpolicy')).toBe('no-referrer'); + expect(h.frame.getAttribute('title')).toBe('Beat Markers'); + expect(box.querySelector('iframe')).toBe(h.frame); + h.dispose(); + expect(box.querySelector('iframe')).toBeNull(); + }); + + it('answers host.hello with api 1, the extension identity and the theme', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + const reply = await ask(fake, 1, 'host.hello'); + expect(reply.formext).toBe(1); + expect(reply.jsonrpc).toBe('2.0'); + expect(reply.result).toEqual({ + product: 'formwav', + app: 'form.wav', + appVersion: '9.9.9', + api: '1', + extension: { id: 'org.example.beats', version: '1.0.0', source: 'sideload' }, + permissions: [], + theme: { mode: 'dark', tokens: { '--bg': '#000000' } }, + locale: 'en-GB', + }); + handle.dispose(); + }); + + it('ignores messages that do not come from the extension frame', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + fromFrame(window, { formext: 1, jsonrpc: '2.0', id: 5, method: 'host.hello', params: {} }); + fromFrame({ postMessage() {} }, { formext: 1, jsonrpc: '2.0', id: 6, method: 'host.hello', params: {} }); + await flush(); + expect(fake.sent).toEqual([]); + handle.dispose(); + }); + + it('ignores messages without the formext marker or the json-rpc version', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + fromFrame(fake.win, { jsonrpc: '2.0', id: 1, method: 'host.hello', params: {} }); + fromFrame(fake.win, { formext: 1, jsonrpc: '1.0', id: 2, method: 'host.hello', params: {} }); + await flush(); + expect(fake.sent).toEqual([]); + handle.dispose(); + }); + + it('refuses a method outside API 1 with -32601', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + const reply = await ask(fake, 3, 'shell.exec', { cmd: 'ls' }); + expect(reply.error.code).toBe(-32601); + handle.dispose(); + }); + + it('refuses document.read with -32001 when the extension did not ask for document', async () => { + const readDocument = vi.fn(() => ({ title: 'x' })); + const host = new ExtensionHost(handlers({ readDocument })); + const { fake, handle } = await granted(host, ['files-read']); + const reply = await ask(fake, 1, 'document.read'); + expect(reply.error.code).toBe(-32001); + expect(readDocument).not.toHaveBeenCalled(); + handle.dispose(); + }); + + it('refuses a permissioned call with -32001 when consent was never given and never prompts mid-call', async () => { + const consent = vi.fn(async () => true); + const host = new ExtensionHost(handlers({ consent, readDocument: () => ({}) })); + const ext = makeExt({ permissions: ['document'] }); + const handle = host.mount(ext, document.createElement('div')); + const fake = fakeWindow(); + attach(handle, fake); + const hello = await ask(fake, 1, 'host.hello'); + expect(hello.result.permissions).toEqual([]); + const reply = await ask(fake, 2, 'document.read'); + expect(reply.error.code).toBe(-32001); + expect(consent).not.toHaveBeenCalled(); + handle.dispose(); + }); + + it('hands document.read to the app once document is granted and reports the permission in hello', async () => { + const host = new ExtensionHost(handlers({ readDocument: (_e, p) => ({ what: p.what ?? 'all', bpm: 120 }) })); + const { fake, handle } = await granted(host, ['document']); + expect((await ask(fake, 1, 'host.hello')).result.permissions).toEqual(['document']); + expect((await ask(fake, 2, 'document.read', { what: 'markers' })).result).toEqual({ what: 'markers', bpm: 120 }); + handle.dispose(); + }); + + it('answers -32003 for a granted method the app does not offer', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, ['network']); + const reply = await ask(fake, 1, 'net.fetch', { url: 'https://example.org/' }); + expect(reply.error.code).toBe(-32003); + handle.dispose(); + }); + + it('refuses net.fetch to an address that is not https with -32602', async () => { + const fetcher = vi.fn(async () => ({ status: 200, headers: {}, body: '' })); + const host = new ExtensionHost(handlers({ fetch: fetcher })); + const { fake, handle } = await granted(host, ['network']); + const reply = await ask(fake, 1, 'net.fetch', { url: 'http://example.org/' }); + expect(reply.error.code).toBe(-32602); + expect(fetcher).not.toHaveBeenCalled(); + const ok = await ask(fake, 2, 'net.fetch', { url: 'https://example.org/' }); + expect(ok.result.status).toBe(200); + handle.dispose(); + }); + + it('refuses document.apply ops without a command name with -32602', async () => { + const applyDocument = vi.fn(async () => ({ applied: 0, results: [] })); + const host = new ExtensionHost(handlers({ applyDocument })); + const { fake, handle } = await granted(host, ['document']); + const reply = await ask(fake, 1, 'document.apply', { label: 'x', ops: [{ args: {} }] }); + expect(reply.error.code).toBe(-32602); + expect(applyDocument).not.toHaveBeenCalled(); + handle.dispose(); + }); + + it('refuses ui.notify without text with -32602 and passes a valid level through', async () => { + const notify = vi.fn(); + const host = new ExtensionHost(handlers({ notify })); + const { fake, handle } = await granted(host, []); + expect((await ask(fake, 1, 'ui.notify', { message: 42 })).error.code).toBe(-32602); + expect((await ask(fake, 2, 'ui.notify', { message: 'Saved', level: 'success' })).result).toBeNull(); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ id: 'org.example.beats' }), 'Saved', 'success'); + handle.dispose(); + }); + + it('refuses files.save without data and files.open without files-read', async () => { + const host = new ExtensionHost(handlers({ saveFile: async (_e, name) => ({ saved: true, name }), openFiles: async () => [] })); + const { fake, handle } = await granted(host, ['files-write']); + expect((await ask(fake, 1, 'files.save', { name: 'a.txt' })).error.code).toBe(-32602); + expect((await ask(fake, 2, 'files.save', { name: 'a.txt', type: 'text/plain', data: 'aGk=' })).result).toEqual({ saved: true, name: 'a.txt' }); + expect((await ask(fake, 3, 'files.open', { accept: ['.wav'] })).error.code).toBe(-32001); + handle.dispose(); + }); + + it('stores values per extension and returns null for a key never set', async () => { + const host = new ExtensionHost(handlers()); + const a = await granted(host, []); + const other = makeExt({ id: 'org.example.other' }); + const hb = host.mount(other, document.createElement('div')); + const b = fakeWindow(); + attach(hb, b); + expect((await ask(a.fake, 1, 'storage.get', { key: 'bpm' })).result).toBeNull(); + await ask(a.fake, 2, 'storage.set', { key: 'bpm', value: { n: 128, tags: ['x'] } }); + expect((await ask(a.fake, 3, 'storage.get', { key: 'bpm' })).result).toEqual({ n: 128, tags: ['x'] }); + expect((await ask(b, 4, 'storage.get', { key: 'bpm' })).result).toBeNull(); + a.handle.dispose(); + hb.dispose(); + }); + + it('refuses storage past 256 KB per extension with -32004', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + const small = await ask(fake, 1, 'storage.set', { key: 'a', value: 'x'.repeat(200 * 1024) }); + expect(small.error).toBeUndefined(); + const big = await ask(fake, 2, 'storage.set', { key: 'b', value: 'y'.repeat(100 * 1024) }); + expect(big.error.code).toBe(-32004); + expect((await ask(fake, 3, 'storage.get', { key: 'b' })).result).toBeNull(); + handle.dispose(); + }); + + it('caps a resize request at 4000 and ignores a non-positive height', async () => { + const host = new ExtensionHost(handlers()); + const onResize = vi.fn(); + const handle = host.mount(makeExt(), document.createElement('div'), { onResize }); + const fake = fakeWindow(); + attach(handle, fake); + await ask(fake, 1, 'ui.resize', { height: 9000 }); + await ask(fake, 2, 'ui.resize', { height: -5 }); + await ask(fake, 3, 'ui.resize', { height: 320 }); + expect(onResize.mock.calls).toEqual([[4000], [320]]); + handle.dispose(); + }); + + it('sends ext.deactivate on dispose and cancels waiting requests with -32002', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + await ask(fake, 1, 'host.hello'); + const waiting = handle.activate({ reason: 'panel', panel: 'main' }); + await flush(); + expect(fake.sent.some((m) => m.method === 'ext.activate' && m.params.panel === 'main')).toBe(true); + handle.dispose(); + await expect(waiting).rejects.toMatchObject({ code: -32002 }); + expect(fake.sent.at(-1)).toMatchObject({ method: 'ext.deactivate', params: {} }); + }); + + it('holds host requests until the extension has said hello', async () => { + const host = new ExtensionHost(handlers()); + const { fake, handle } = await granted(host, []); + void handle.send('ext.event', { name: 'x', data: 1 }).catch(() => undefined); + await flush(); + expect(fake.sent).toEqual([]); + await ask(fake, 1, 'host.hello'); + await flush(); + expect(fake.sent.some((m) => m.method === 'ext.event')).toBe(true); + handle.dispose(); + }); + + it('names every permission in plain words as the contract lists them', () => { + expect(PERMISSION_WORDS.document.toLowerCase()).toBe('read and change the open document'); + expect(PERMISSION_WORDS['files-read'].toLowerCase()).toBe('open files you choose'); + expect(PERMISSION_WORDS['files-write'].toLowerCase()).toBe('save files where you choose'); + expect(PERMISSION_WORDS.network.toLowerCase()).toBe('reach the internet'); + expect(PERMISSION_WORDS.models.toLowerCase()).toBe('use local models'); + }); +}); + +describe('host bridge consent', () => { + it('asks before creating a frame and creates none when the person says Not Now', async () => { + const consent = vi.fn(async () => false); + const host = new ExtensionHost(handlers({ consent })); + const box = document.createElement('div'); + const out = await host.open(makeExt({ permissions: ['document'] }), box); + expect(out).toBeNull(); + expect(box.querySelector('iframe')).toBeNull(); + await host.open(makeExt({ permissions: ['document'] }), box); + expect(consent).toHaveBeenCalledTimes(2); + }); + + it('remembers Allow for the same id, version and permissions', async () => { + const consent = vi.fn(async () => true); + const host = new ExtensionHost(handlers({ consent })); + const box = document.createElement('div'); + const a = await host.open(makeExt({ permissions: ['document', 'network'] }), box); + const b = await host.open(makeExt({ permissions: ['network', 'document'] }), box); + expect(consent).toHaveBeenCalledTimes(1); + expect(box.querySelectorAll('iframe').length).toBe(2); + a?.dispose(); + b?.dispose(); + }); + + it('asks again for a new version or a larger permission set', async () => { + const consent = vi.fn(async () => true); + const host = new ExtensionHost(handlers({ consent })); + await host.ensureConsent(makeExt({ permissions: ['document'] })); + await host.ensureConsent(makeExt({ permissions: ['document'], version: '1.1.0' })); + await host.ensureConsent(makeExt({ permissions: ['document', 'network'] })); + expect(consent).toHaveBeenCalledTimes(3); + }); + + it('never asks for an extension that needs no permissions', async () => { + const consent = vi.fn(async () => false); + const host = new ExtensionHost(handlers({ consent })); + expect(await host.ensureConsent(makeExt())).toBe(true); + expect(consent).not.toHaveBeenCalled(); + }); + + it('asks again after a grant is revoked', async () => { + const consent = vi.fn(async () => true); + const host = new ExtensionHost(handlers({ consent })); + const ext = makeExt({ permissions: ['files-read'] }); + await host.ensureConsent(ext); + expect(host.isGranted(ext)).toBe(true); + host.revoke(ext); + expect(host.isGranted(ext)).toBe(false); + }); + + it('refuses a headless command the person did not allow with -32001 and an unknown command with -32601', async () => { + const host = new ExtensionHost(handlers({ consent: async () => false })); + const ext = makeExt({ permissions: ['document'] }); + await expect(host.runCommand(ext, 'mark', {}, document.body)).rejects.toMatchObject({ code: -32001 }); + await expect(host.runCommand(ext, 'nope', {}, document.body)).rejects.toMatchObject({ code: -32601 }); + expect(document.body.querySelector('iframe')).toBeNull(); + }); +}); diff --git a/frontend/tests/unit/shell/sdk-host.test.ts b/frontend/tests/unit/shell/sdk-host.test.ts new file mode 100644 index 0000000..0562fb7 --- /dev/null +++ b/frontend/tests/unit/shell/sdk-host.test.ts @@ -0,0 +1,228 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { ExtensionHost } from '../../../../contract/host/host-bridge'; +import type { HostHandlers, Frame } from '../../../../contract/host/host-bridge'; +import { formext, FormExtError, ERR, toBase64, fromBase64, applyTheme } from '../../../../sdk/src/formext'; +import { makeExt, link, flush } from './wire'; +import type { Msg } from './wire'; + +let handle: Frame | null = null; + +function handlers(over: Partial = {}): HostHandlers { + return { + product: 'formmd', + app: 'form.md', + appVersion: '1.2.3', + locale: () => 'fr-FR', + theme: () => ({ mode: 'light', tokens: { '--bg': '#eeeeee', '--accent': '#123456', color: 'red' } }), + notify: vi.fn(), + consent: async () => true, + ...over, + }; +} + +async function connect(h: Partial = {}, perms: ('document' | 'network' | 'files-read')[] = []) { + const host = new ExtensionHost(handlers(h)); + const ext = makeExt({ permissions: perms }); + await host.ensureConsent(ext); + handle = host.mount(ext, document.createElement('div')); + const toHost = link(handle); + return { host, ext, toHost }; +} + +beforeEach(() => { + localStorage.clear(); + document.documentElement.removeAttribute('data-theme'); + document.documentElement.removeAttribute('style'); +}); + +afterEach(() => { + handle?.dispose(); + handle = null; + vi.useRealTimers(); +}); + +describe('SDK and host agree', () => { + it('sends every request with the formext marker and json-rpc 2.0', async () => { + const { toHost } = await connect(); + await formext.call('host.hello'); + expect(toHost[0]).toMatchObject({ formext: 1, jsonrpc: '2.0', method: 'host.hello', params: {} }); + expect(typeof toHost[0].id).toBe('number'); + }); + + it('gets the hello the host builds and applies its theme tokens to the page', async () => { + await connect(); + const hello = await formext.hello(); + expect(hello.api).toBe('1'); + expect(hello.app).toBe('form.md'); + expect(hello.locale).toBe('fr-FR'); + expect(hello.extension).toEqual({ id: 'org.example.beats', version: '1.0.0', source: 'sideload' }); + expect(document.documentElement.dataset.theme).toBe('light'); + expect(document.documentElement.style.getPropertyValue('--accent')).toBe('#123456'); + expect(document.documentElement.style.getPropertyValue('color')).toBe(''); + }); + + it('turns a host refusal into a FormExtError carrying the contract code', async () => { + await connect({ readDocument: () => ({}) }, []); + const err = (await formext.readDocument().catch((e) => e)) as FormExtError; + expect(err).toBeInstanceOf(FormExtError); + expect(err.code).toBe(ERR.PERMISSION); + expect(err.code).toBe(-32001); + }); + + it('round-trips storage through the host', async () => { + await connect(); + await formext.storageSet('grid', { rows: 4, cols: [1, 2] }); + expect(await formext.storageGet('grid')).toEqual({ rows: 4, cols: [1, 2] }); + await formext.storageSet('grid', null); + expect(await formext.storageGet('grid')).toBeNull(); + }); + + it('sends document.apply ops the host passes to the app unchanged', async () => { + const applyDocument = vi.fn(async (_e: unknown, _l: string, ops: { command: string }[]) => ({ applied: ops.length, results: ops.map((o) => o.command) })); + await connect({ applyDocument }, ['document']); + const out = await formext.apply('Add beats', [{ command: 'marker.add', args: { t: 1 } }, { command: 'marker.add', args: { t: 2 } }]); + expect(out).toEqual({ applied: 2, results: ['marker.add', 'marker.add'] }); + expect(applyDocument.mock.calls[0][1]).toBe('Add beats'); + expect(applyDocument.mock.calls[0][2]).toEqual([{ command: 'marker.add', args: { t: 1 } }, { command: 'marker.add', args: { t: 2 } }]); + }); + + it('notifies through ui.notify with the level it was given', async () => { + const notify = vi.fn(); + await connect({ notify }); + await formext.notify('Done', 'warning'); + expect(notify).toHaveBeenCalledWith(expect.anything(), 'Done', 'warning'); + }); + + it('rounds a fractional resize height up before it reaches the host', async () => { + const { toHost } = await connect(); + await formext.resize(100.2); + expect(toHost.at(-1)).toMatchObject({ method: 'ui.resize', params: { height: 101 } }); + }); + + it('delivers ext.activate to the extension handler and returns its answer to the host', async () => { + await connect(); + const seen: unknown[] = []; + formext.onActivate((a) => { + seen.push(a); + return { opened: a.panel }; + }); + await formext.call('host.hello'); + const result = await handle!.activate({ reason: 'panel', panel: 'main' }); + expect(seen).toEqual([{ reason: 'panel', panel: 'main' }]); + expect(result).toEqual({ opened: 'main' }); + }); + + it('reports a failing activate handler to the host with its code', async () => { + await connect(); + formext.onActivate(() => { + throw new FormExtError(ERR.CANCELLED, 'person closed it'); + }); + await formext.call('host.hello'); + await expect(handle!.activate({ reason: 'command', command: 'mark' })).rejects.toMatchObject({ code: -32002, message: 'person closed it' }); + }); + + it('answers a host request it has no handler for with -32601', async () => { + await connect(); + await formext.call('host.hello'); + await expect(handle!.send('ext.unknownThing', {})).rejects.toMatchObject({ code: -32601 }); + }); + + it('passes app events from broadcast to onEvent', async () => { + const { host } = await connect(); + const events: unknown[] = []; + formext.onEvent((e) => void events.push(e)); + await formext.call('host.hello'); + host.broadcast('document.changed', { blocks: 3 }); + await flush(); + expect(events).toEqual([{ name: 'document.changed', data: { blocks: 3 } }]); + }); + + it('repaints the page when the host changes theme', async () => { + const { host } = await connect(); + await formext.call('host.hello'); + host.setTheme({ mode: 'dark', tokens: { '--bg': '#010101' } }); + await flush(); + expect(document.documentElement.dataset.theme).toBe('dark'); + expect(document.documentElement.style.getPropertyValue('--bg')).toBe('#010101'); + }); + + it('ends a headless command with the result the extension gives to done', async () => { + const host = new ExtensionHost(handlers()); + const ext = makeExt(); + const box = document.createElement('div'); + const mount = host.mount.bind(host); + vi.spyOn(host, 'mount').mockImplementation((e, c, o) => { + const h = mount(e, c, o); + link(h); + void formext.call('host.hello'); + return h; + }); + formext.onActivate(async (a) => { + await formext.done({ marked: a.command, args: a.args }); + return null; + }); + const result = await host.runCommand(ext, 'mark', { bpm: 90 }, box); + expect(result).toEqual({ marked: 'mark', args: { bpm: 90 } }); + expect(box.querySelector('iframe')).toBeNull(); + }); +}); + +describe('SDK on its own', () => { + it('gives up on a plain request after 30 s with -32003', async () => { + vi.useFakeTimers(); + vi.spyOn(window.parent, 'postMessage').mockImplementation((() => undefined) as typeof window.postMessage); + const p = formext.storageGet('x').catch((e) => e as FormExtError); + await vi.advanceTimersByTimeAsync(29_999); + let settled = false; + void p.then(() => (settled = true)); + await vi.advanceTimersByTimeAsync(0); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + const err = (await p) as FormExtError; + expect(err.code).toBe(-32003); + }); + + it('waits 300 s for files and app.run before giving up', async () => { + vi.useFakeTimers(); + vi.spyOn(window.parent, 'postMessage').mockImplementation((() => undefined) as typeof window.postMessage); + const out: Record = {}; + const track = (name: string, p: Promise) => p.catch((e) => (out[name] = e.code)); + track('open', formext.openFiles(['.wav'])); + track('save', formext.saveFile('a.txt', 'text/plain', '')); + track('run', formext.run('x')); + await vi.advanceTimersByTimeAsync(31_000); + expect(out).toEqual({}); + await vi.advanceTimersByTimeAsync(270_000); + expect(out).toEqual({ open: -32003, save: -32003, run: -32003 }); + }); + + it('accepts answers only from the parent window', async () => { + const sent: Msg[] = []; + vi.spyOn(window.parent, 'postMessage').mockImplementation(((m: Msg) => void sent.push(m)) as typeof window.postMessage); + let value: unknown = 'pending'; + void formext.storageGet('k').then((v) => (value = v)); + const id = sent[0].id; + window.dispatchEvent(new MessageEvent('message', { data: { formext: 1, jsonrpc: '2.0', id, result: 'forged' }, source: {} as Window })); + await flush(); + expect(value).toBe('pending'); + window.dispatchEvent(new MessageEvent('message', { data: { formext: 1, jsonrpc: '2.0', id, result: 'real' }, source: window.parent })); + await flush(); + expect(value).toBe('real'); + }); + + it('round-trips bytes through base64 and agrees with the platform encoder', () => { + const bytes = new Uint8Array(70_000).map((_, i) => (i * 31) % 256); + const b64 = toBase64(bytes); + expect(b64).toBe(Buffer.from(bytes).toString('base64')); + expect(Array.from(fromBase64(b64))).toEqual(Array.from(bytes)); + expect(toBase64(new TextEncoder().encode('hi'))).toBe('aGk='); + }); + + it('ignores a missing theme and skips token names without the leading dashes', () => { + applyTheme(undefined); + expect(document.documentElement.dataset.theme).toBeUndefined(); + applyTheme({ mode: 'dark', tokens: { '--panel': '#222222', panel: '#333333' } }); + expect(document.documentElement.style.getPropertyValue('--panel')).toBe('#222222'); + expect(document.documentElement.style.getPropertyValue('panel')).toBe(''); + }); +}); diff --git a/frontend/tests/unit/shell/shell-boot.test.ts b/frontend/tests/unit/shell/shell-boot.test.ts new file mode 100644 index 0000000..12a5dda --- /dev/null +++ b/frontend/tests/unit/shell/shell-boot.test.ts @@ -0,0 +1,207 @@ +import { describe, it, expect, vi, beforeAll } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const here = (p: string) => fileURLToPath(new URL(p, import.meta.url)); +const page = readFileSync(here('../../../index.html'), 'utf8'); +const contractMd = readFileSync(here('../../../../contract/CONTRACT.md'), 'utf8'); +const manualMd = readFileSync(here('../../../../docs/MANUAL.md'), 'utf8'); + +const REGISTRY = { + url: 'https://registry.example.org/index.json', url_source: 'default', name: 'Example', verified: true, key: 'k1', keys: 1, note: '', offline: null, + fetched_at: 1700000000, sha256: 'a'.repeat(64), registry_commit: 'abcdef1234567', publishers: [], + extensions: [ + { id: 'org.example.tidal', name: 'Tidal Grid', product: 'formmd', version: '1.0.0', kind: 'extension', author: 'Ada', licence: 'MIT', description: 'Grid for tides', permissions: [{ id: 'document', words: 'Read and change the open document' }], verified: true, listed_verified: true, source: 'registry', registry_commit: 'abcdef1', url: 'https://registry.example.org/a.formpkg', sha256: 'b'.repeat(64), bytes: 2048, signed_by: null, imported: [] }, + { id: 'org.example.beats', name: 'Beat Markers', product: 'formwav', version: '2.1.0', kind: 'extension', author: 'Grace', licence: 'MIT', description: 'Markers on beats', permissions: [], verified: true, listed_verified: true, source: 'registry', registry_commit: 'abcdef1', url: 'https://registry.example.org/b.formpkg', sha256: 'c'.repeat(64), bytes: 4096, signed_by: null, imported: [] }, + ], +}; + +const RECENT = { projects: [{ id: 'p1', name: 'Golden Hour', product: 'formvis', version: '0.3.0', dir: '/tmp/golden-hour', linked: false, manifest: {} }] }; + +function json(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); +} + +async function route(input: RequestInfo | URL): Promise { + const url = new URL(String(input instanceof Request ? input.url : input), 'http://localhost'); + const p = url.pathname; + if (p === '/api/health') return json({ version: '7.7.7' }); + if (p === '/api/projects/recent') return json(RECENT); + if (p === '/api/projects') return json([]); + if (p === '/api/library/registry') return json(REGISTRY); + return json({ detail: 'Not found' }, 404); +} + +class QuietSocket { + static OPEN = 1; + readyState = 0; + onopen: unknown = null; + onclose: unknown = null; + onmessage: unknown = null; + onerror: unknown = null; + constructor(public url: string) {} + send() {} + close() {} + addEventListener() {} + removeEventListener() {} +} + +function headings(md: string, level: number): string[] { + const mark = '#'.repeat(level) + ' '; + const out: string[] = []; + let fence = false; + for (const line of md.split('\n')) { + if (line.startsWith('```')) fence = !fence; + else if (!fence && line.startsWith(mark)) out.push(line.slice(mark.length).replace(/`/g, '').trim()); + } + return out; +} + +const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms)); + +async function until(check: () => boolean, tries = 40) { + for (let i = 0; i < tries && !check(); i++) await tick(10); +} + +let shell: typeof import('../../../src/shell/shell'); +let VERSION = ''; + +beforeAll(async () => { + vi.stubGlobal('fetch', vi.fn(route)); + vi.stubGlobal('WebSocket', QuietSocket); + localStorage.clear(); + history.replaceState(null, '', '/'); + document.body.innerHTML = page.slice(page.indexOf('') + 6, page.indexOf('')).replace(//g, ''); + shell = await import('../../../src/shell/shell'); + VERSION = (await import('../../../src/shell/version')).VERSION; + shell.boot(); + await until(() => document.querySelector('[data-status="engine"]')?.getAttribute('data-state') === 'up'); +}); + +const pane = (id: string) => document.querySelector(`.fx-pane[data-pane="${id}"]`) ?? shell.partRoot(id)!; +const nav = (key: string) => document.querySelector(`.fx-nav[data-nav="${key}"]`)!; + +describe('shell boot', () => { + it('opens on Home when there is no hash and no remembered pane', () => { + expect(shell.activePane()).toBe('home'); + expect(pane('home').classList.contains('active')).toBe(true); + expect(nav('home').getAttribute('aria-current')).toBe('page'); + }); + + it('builds one section per discovered pane, labelled with its title', () => { + const defs = shell.panes(); + expect(defs.length).toBeGreaterThan(0); + for (const d of defs) expect(pane(d.id).getAttribute('aria-label')).toBe(d.title); + expect(document.querySelectorAll('.fx-main > .fx-pane').length).toBe(defs.length); + }); + + it('shows its own version and the engine version from the health route in the status bar', () => { + expect(document.querySelector('[data-status="version"]')!.textContent).toBe(`v${VERSION}`); + const engine = document.querySelector('[data-status="engine"]')!; + expect(engine.getAttribute('data-state')).toBe('up'); + expect(engine.textContent).toContain('Engine 7.7.7'); + expect(document.querySelector('[data-status="project"]')!.textContent).toContain('No project'); + }); + + it('lists recent projects on Home and counts them in the sidebar', async () => { + await until(() => pane('home').textContent!.includes('Golden Hour')); + expect(pane('home').textContent).toContain('Golden Hour'); + expect(nav('recent').querySelector('.cnt')!.textContent).toBe(String(RECENT.projects.length)); + }); + + it('says how many apps Home can make extensions for and that it speaks API 1', async () => { + const { HOSTS } = await import('../../../src/shell/products'); + expect(pane('home').querySelector('.home-start-meta')!.textContent).toBe(`${HOSTS.length} apps \u00b7 Extension API 1`); + expect(pane('home').querySelectorAll('.home-start-apps > *').length).toBe(HOSTS.length); + }); + + it('warns in a toast when asked for a pane that does not exist and stays put', async () => { + shell.openPane('nowhere'); + await tick(); + expect(document.querySelector('.fx-toasts')!.textContent).toContain('There is no nowhere pane.'); + expect(shell.activePane()).toBe('home'); + }); +}); + +describe('docs pane through the shell', () => { + it('opens from the sidebar and updates the hash, the title and the current nav', () => { + nav('docs').click(); + expect(shell.activePane()).toBe('docs'); + expect(location.hash).toBe('#/docs'); + expect(document.title).toBe('Docs - form.ext'); + expect(nav('docs').getAttribute('aria-current')).toBe('page'); + expect(nav('home').getAttribute('aria-current')).toBeNull(); + expect(pane('home').classList.contains('active')).toBe(false); + }); + + it('renders the extension contract with its own title and section headings', async () => { + shell.openPane('docs', { doc: 'contract' }); + await tick(); + const el = pane('docs'); + expect(el.querySelector('.docs-article h1')!.textContent!.replace(/#/g, '').trim()).toBe(headings(contractMd, 1)[0]); + expect(el.querySelector('.docs-file-path')!.textContent).toBe('contract/CONTRACT.md'); + const shown = [...el.querySelectorAll('.docs-article h2')].map((h) => h.textContent!.replace(/#/g, '').trim()); + expect(shown).toEqual(headings(contractMd, 2)); + expect(el.querySelector('.docs-nav-row[data-doc="contract"]')!.getAttribute('aria-selected')).toBe('true'); + }); + + it('opens the manual from Help in the sidebar footer', async () => { + nav('help').click(); + await tick(); + const el = pane('docs'); + expect(el.querySelector('.docs-file-path')!.textContent).toBe('docs/MANUAL.md'); + expect(el.querySelector('.docs-article h1')!.textContent!.replace(/#/g, '').trim()).toBe(headings(manualMd, 1)[0]); + }); + + it('lists one docs row per host app under App APIs', async () => { + const { HOSTS } = await import('../../../src/shell/products'); + const rows = [...pane('docs').querySelectorAll('.docs-nav-row')].map((r) => r.dataset.doc); + for (const h of HOSTS) expect(rows).toContain(h.id); + }); + + it('highlights search matches for a word the contract uses', async () => { + shell.openPane('docs', { doc: 'contract', query: 'sandbox' }); + await until(() => /\d/.test(pane('docs').querySelector('.docs-search-count')!.textContent ?? '')); + const count = pane('docs').querySelector('.docs-search-count')!.textContent!; + const n = Number(count.match(/\d+/)![0]); + expect(n).toBeGreaterThan(0); + }); +}); + +const lib = () => document.querySelector('.library-pane')!; + +describe('library pane through the shell', () => { + it('opens from Registry in the sidebar and shows the registry extensions by name', async () => { + nav('registry').click(); + await until(() => lib().textContent!.includes('Beat Markers')); + expect(shell.layoutOf('library')).toBe('studio'); + expect(document.documentElement.dataset.layout).toBe('studio'); + expect(lib().querySelector('h1')!.textContent).toBe('Library'); + expect(lib().textContent).toContain('Tidal Grid'); + expect(lib().textContent).toContain('Beat Markers'); + const cards = [...lib().querySelectorAll('.lib-ex')].map((c) => c.dataset.key); + expect(cards).toEqual(REGISTRY.extensions.map((x) => x.id)); + const tidal = lib().querySelector('.lib-ex[data-key="org.example.tidal"]')!; + expect(tidal.textContent).toContain('Read and change the open document'); + expect(tidal.querySelector('.lib-verified')).not.toBeNull(); + }); + + it('says where the registry index came from and that its signature was verified', () => { + const status = lib().querySelector('.lib-reg-status')!.textContent!; + expect(status).toContain(REGISTRY.url); + expect(status).toContain('signature verified with registry key k1'); + expect(status).toMatch(/^2 extensions/); + }); +}); + +describe('theme toggle', () => { + it('flips between light and dark and relabels the button', () => { + const btn = document.querySelector('[data-action="theme"]')!; + const before = btn.title; + btn.click(); + const after = btn.title; + expect(new Set([before, after])).toEqual(new Set(['Light theme', 'Dark theme'])); + btn.click(); + expect(btn.title).toBe(before); + }); +}); diff --git a/frontend/tests/unit/shell/sim.test.ts b/frontend/tests/unit/shell/sim.test.ts new file mode 100644 index 0000000..37ab8d3 --- /dev/null +++ b/frontend/tests/unit/shell/sim.test.ts @@ -0,0 +1,221 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { SIMS, simFor, SimHost, sampleFile, accepts, tokensFor } from '../../../src/sim'; +import type { SimUI, AppSim } from '../../../src/sim'; +import { formext } from '../../../../sdk/src/formext'; +import { makeExt, link } from './wire'; + +function ui(): SimUI { + return { + consent: vi.fn(async () => true), + openFiles: vi.fn(async () => []), + saveFile: vi.fn(async (_r, name) => ({ saved: true, name })), + fetch: vi.fn(async () => ({ status: 200, headers: {}, body: '' })), + notify: vi.fn(), + setTitle: vi.fn(), + resize: vi.fn(), + log: vi.fn(), + changed: vi.fn(), + }; +} + +const ext = makeExt({ permissions: ['document'] }); +const REQUIRED_TOKENS = ['--bg', '--panel', '--text', '--muted', '--accent', '--border', '--radius']; +const all = Object.entries(SIMS) as [string, AppSim][]; + +function b64bytes(data: string): Uint8Array { + return new Uint8Array(Buffer.from(data, 'base64')); +} + +beforeEach(() => localStorage.clear()); + +describe('simulated host apps', () => { + it.each(all)('%s is registered under its own product id', (key, sim) => { + expect(sim.product).toBe(key); + expect(simFor(key)).toBe(sim); + }); + + it('finds no simulation for an unknown product', () => { + expect(simFor('formnothing')).toBeNull(); + }); + + it.each(all)('%s gives extensions at least the design tokens the contract lists, in both modes', (_k, sim) => { + for (const mode of ['dark', 'light'] as const) { + const tokens = tokensFor(sim, mode); + for (const name of REQUIRED_TOKENS) expect(tokens[name], `${mode} ${name}`).toMatch(/\S/); + } + }); + + it.each(all)('%s leaves the document untouched when document.apply names an unknown command', async (_k, sim) => { + const host = new SimHost(sim, ui(), 'dark'); + const before = JSON.stringify(host.state); + await expect(host.apply(ext, 'Nothing', [{ command: 'no.such.command', args: {} }])).rejects.toMatchObject({ code: expect.any(Number) }); + expect(JSON.stringify(host.state)).toBe(before); + expect(host.steps).toEqual([]); + }); + + it.each(all.filter(([, s]) => !s.readFallback))('%s refuses an unknown document.read what with -32602', async (_k, sim) => { + const host = new SimHost(sim, ui(), 'dark'); + await expect(host.read({ what: 'no-such-part' })).rejects.toMatchObject({ code: -32602 }); + }); + + it.each(all)('%s lists its command catalogue with an id and a title for each command', (_k, sim) => { + const host = new SimHost(sim, ui(), 'light'); + const cat = host.catalogue() as { id: string; title: string }[]; + expect(cat.map((c) => c.id).sort()).toEqual(Object.keys(sim.cmds).sort()); + for (const c of cat) expect(typeof c.title).toBe('string'); + }); +}); + +describe('form.md simulation', () => { + const md = SIMS.formmd; + + it('applies a batch as one undoable step and undo restores the page exactly', async () => { + const u = ui(); + const host = new SimHost(md, u, 'dark'); + const start = JSON.stringify(host.state); + const out = await host.apply(ext, 'Add notes', [ + { command: 'doc.insertText', args: { text: 'First note' } }, + { command: 'doc.insertMarkdown', args: { markdown: '## Winter' } }, + ]); + expect(out.applied).toBe(2); + expect(host.steps.map((s) => s.label)).toEqual(['Add notes']); + const after = (await host.read({ what: 'markdown' })) as { markdown: string }; + expect(after.markdown).toContain('First note'); + expect(after.markdown).toContain('## Winter'); + expect(u.changed).toHaveBeenCalled(); + expect(host.undo()).toBe('Add notes'); + expect(JSON.stringify(host.state)).toBe(start); + expect(host.undo()).toBeNull(); + }); + + it('applies all ops or none: a failing second op keeps the first out of the page', async () => { + const host = new SimHost(md, ui(), 'dark'); + const start = JSON.stringify(host.state); + const err = await host.apply(ext, 'Half', [ + { command: 'doc.insertText', args: { text: 'Should not land' } }, + { command: 'doc.deleteBlock', args: { block: 'missing' } }, + ]).catch((e) => e); + expect(err.code).toBe(-32004); + expect(err.message).toMatch(/^op 2 \(doc\.deleteBlock\)/); + expect(JSON.stringify(host.state)).toBe(start); + }); + + it('reports a missing required argument as invalid params', async () => { + const host = new SimHost(md, ui(), 'dark'); + await expect(host.apply(ext, 'x', [{ command: 'doc.insertText', args: {} }])).rejects.toMatchObject({ code: -32602 }); + }); + + it('refuses to run a non-document command inside document.apply', async () => { + const host = new SimHost(md, ui(), 'dark'); + await expect(host.apply(ext, 'x', [{ command: 'page.favorite' }])).rejects.toMatchObject({ code: -32004 }); + }); + + it('counts words the same way as splitting the markdown it hands out', async () => { + const host = new SimHost(md, ui(), 'dark'); + const { markdown } = (await host.read({ what: 'markdown' })) as { markdown: string }; + const words = markdown.split(/\s+/).filter(Boolean).length; + expect(await host.run(ext, 'view.wordCount', {})).toEqual({ words }); + }); + + it('replaces every case-insensitive match and reports how many', async () => { + const host = new SimHost(md, ui(), 'dark'); + const { blocks } = (await host.read({ what: 'blocks' })) as { blocks: { text: string }[] }; + const expected = blocks.reduce((n, b) => n + (b.text.match(/tide/gi)?.length ?? 0), 0); + expect(expected).toBeGreaterThan(0); + const out = await host.apply(ext, 'Swap', [{ command: 'doc.replaceText', args: { find: 'TIDE', replace: 'flow' } }]); + expect(out.results).toEqual([{ replaced: expected }]); + const again = (await host.read({ what: 'markdown' })) as { markdown: string }; + expect(again.markdown).not.toMatch(/tide/i); + }); + + it('lists headings in the outline in page order', async () => { + const host = new SimHost(md, ui(), 'dark'); + const { outline } = (await host.read({ what: 'outline' })) as { outline: { text: string; level: number }[] }; + expect(outline.map((o) => [o.level, o.text])).toEqual([[1, 'Tides and timetables'], [2, 'Method'], [2, 'Results']]); + }); + + it('refuses an unknown command in app.run with the app name in the message', async () => { + const host = new SimHost(md, ui(), 'dark'); + await expect(host.run(ext, 'nope', {})).rejects.toMatchObject({ code: -32004, message: 'form.md has no command nope' }); + }); + + it('serves document.read to a real SDK client through the bridge and logs the call', async () => { + const u = ui(); + const host = new SimHost(md, u, 'dark'); + const mount = host.host.mount.bind(host.host); + vi.spyOn(host.host, 'mount').mockImplementation((e, c, o) => { + const h = mount(e, c, o); + link(h); + return h; + }); + const frame = await host.openPanel(ext, 'main', document.createElement('div')); + expect(frame).not.toBeNull(); + expect(u.consent).toHaveBeenCalledTimes(1); + const hello = await formext.call<{ app: string; permissions: string[] }>('host.hello'); + expect(hello.app).toBe('form.md'); + expect(hello.permissions).toEqual(['document']); + const page = await formext.readDocument<{ outline: { text: string }[] }>('outline'); + expect(page.outline[0].text).toBe('Tides and timetables'); + const logged = (u.log as ReturnType).mock.calls.map((c) => c[0]).filter((e) => e.method === 'document.read' && !e.pending); + expect(logged.at(-1)).toMatchObject({ dir: 'in', frame: 'panel main' }); + expect(host.openPanels()).toEqual(['main']); + host.closePanel('main'); + expect(host.openPanels()).toEqual([]); + }); +}); + +describe('sample files', () => { + it('builds a wav whose RIFF header matches its own bytes', () => { + const f = sampleFile('song.wav')!; + const bytes = b64bytes(f.data); + const v = new DataView(bytes.buffer); + const tag = (o: number) => String.fromCharCode(...bytes.subarray(o, o + 4)); + expect(f.size).toBe(bytes.length); + expect(tag(0)).toBe('RIFF'); + expect(tag(8)).toBe('WAVE'); + expect(v.getUint32(4, true)).toBe(bytes.length - 8); + const channels = v.getUint16(22, true); + const rate = v.getUint32(24, true); + const bits = v.getUint16(34, true); + expect(v.getUint32(28, true)).toBe((rate * channels * bits) / 8); + expect(tag(36)).toBe('data'); + const seconds = v.getUint32(40, true) / ((rate * channels * bits) / 8); + expect(seconds).toBeCloseTo(4, 3); + }); + + it('builds a pdf whose cross-reference offsets point at their objects', () => { + const f = sampleFile('membership-form.pdf')!; + const text = Buffer.from(f.data, 'base64').toString('latin1'); + expect(text.startsWith('%PDF-1.')).toBe(true); + expect(text.trimEnd().endsWith('%%EOF')).toBe(true); + const start = Number(text.match(/startxref\n(\d+)/)![1]); + expect(text.slice(start, start + 4)).toBe('xref'); + const rows = text.slice(start).split('\n').slice(2).filter((l) => / n $/.test(l)); + rows.forEach((row, i) => { + const off = Number(row.slice(0, 10)); + expect(text.slice(off).startsWith(`${i + 1} 0 obj`)).toBe(true); + }); + expect(text).toContain('/T (full_name)'); + }); + + it('decodes a text sample to the size it reports', () => { + const f = sampleFile('notes.txt')!; + const text = Buffer.from(f.data, 'base64').toString('utf8'); + expect(text.startsWith('Harbour shoot notes')).toBe(true); + expect(f.size).toBe(Buffer.byteLength(text)); + expect(f.type).toBe('text/plain'); + }); + + it('has no sample for a name it does not know', () => { + expect(sampleFile('secret.exe')).toBeNull(); + }); + + it('matches files against accept lists by extension, wildcard and exact type', () => { + expect(accepts('Song.WAV', 'audio/wav', ['.wav'])).toBe(true); + expect(accepts('song.mp3', 'audio/mpeg', ['.wav'])).toBe(false); + expect(accepts('photo.png', 'image/png', ['image/*'])).toBe(true); + expect(accepts('a.json', 'application/json', ['application/json'])).toBe(true); + expect(accepts('a.json', 'application/json', ['text/plain'])).toBe(false); + expect(accepts('anything.bin', 'application/octet-stream', [])).toBe(true); + }); +}); diff --git a/frontend/tests/unit/shell/wire.ts b/frontend/tests/unit/shell/wire.ts new file mode 100644 index 0000000..c438a8d --- /dev/null +++ b/frontend/tests/unit/shell/wire.ts @@ -0,0 +1,68 @@ +import { vi } from 'vitest'; +import type { ExtensionRecord, Frame } from '../../../../contract/host/host-bridge'; + +export type Msg = Record; + +export function makeExt(over: Partial = {}): ExtensionRecord { + return { + id: 'org.example.beats', + name: 'Beat Markers', + version: '1.0.0', + source: 'sideload', + permissions: [], + base: 'about:', + entryUi: 'blank', + panels: [{ id: 'main', title: 'Beats' }], + commands: [{ id: 'mark', title: 'Mark Beats' }], + state: 'ready', + ...over, + }; +} + +export function flush(times = 6): Promise { + let p = Promise.resolve(); + for (let i = 0; i < times; i++) p = p.then(() => new Promise((r) => setTimeout(r, 0))); + return p; +} + +export interface FakeFrame { + win: { postMessage: (m: Msg) => void }; + sent: Msg[]; +} + +export function fakeWindow(): FakeFrame { + const sent: Msg[] = []; + return { sent, win: { postMessage: (m: Msg) => void sent.push(m) } }; +} + +export function attach(handle: Frame, fake: FakeFrame): void { + Object.defineProperty(handle.frame, 'contentWindow', { value: fake.win, configurable: true }); +} + +export function fromFrame(source: unknown, data: unknown): void { + window.dispatchEvent(new MessageEvent('message', { data, source: source as Window })); +} + +export async function ask(fake: FakeFrame, id: number, method: string, params: unknown = {}): Promise { + fromFrame(fake.win, { formext: 1, jsonrpc: '2.0', id, method, params }); + for (let i = 0; i < 20; i++) { + const hit = fake.sent.find((m) => m.id === id && !m.method); + if (hit) return hit; + await flush(1); + } + throw new Error(`no answer to ${method}`); +} + +export function link(handle: Frame): Msg[] { + const toHost: Msg[] = []; + const parent = window.parent; + const win = { + postMessage: (data: Msg) => queueMicrotask(() => window.dispatchEvent(new MessageEvent('message', { data, source: parent }))), + }; + Object.defineProperty(handle.frame, 'contentWindow', { value: win, configurable: true }); + vi.spyOn(parent, 'postMessage').mockImplementation(((data: Msg) => { + toHost.push(data); + queueMicrotask(() => window.dispatchEvent(new MessageEvent('message', { data, source: win as unknown as Window }))); + }) as typeof parent.postMessage); + return toHost; +} From 348148fef0fcfb21719997cc03383a53739e31b9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:18 -0500 Subject: [PATCH 12/15] test(validate): manifest refusals, sandbox code rules, package zip read back, every shipped template scaffolds and validates (0.11.0) Checks what makes an extension manifest valid or refused and with which message, which code the sandbox blocks and at which line, that a package built over HTTP reads back with Python's zipfile exactly as the contract states (sorted names, 1980 dates, mode 0644, deflate, no path escapes, manifest inside, SHA-256 and size), and that all 36 shipped templates scaffold a project that validates; expected values come from contract/CONTRACT.md, contract/schema/package.schema.json, the files on disk and an independent zip and sha256 reader. Ran: backend/venv/bin/python -m pytest tests/validate -q -p no:cacheprovider, 160 passed, 0 expected failures. --- tests/validate/conftest.py | 65 +++++ tests/validate/test_code_rules.py | 178 ++++++++++++ tests/validate/test_manifest_rules.py | 249 ++++++++++++++++ tests/validate/test_package_and_templates.py | 290 +++++++++++++++++++ 4 files changed, 782 insertions(+) create mode 100644 tests/validate/conftest.py create mode 100644 tests/validate/test_code_rules.py create mode 100644 tests/validate/test_manifest_rules.py create mode 100644 tests/validate/test_package_and_templates.py diff --git a/tests/validate/conftest.py b/tests/validate/conftest.py new file mode 100644 index 0000000..11baec1 --- /dev/null +++ b/tests/validate/conftest.py @@ -0,0 +1,65 @@ +import itertools +import json +import shutil +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import stand_ins # noqa: E402,F401 + +ROOT = Path(__file__).resolve().parent.parent.parent +HELLO = ROOT / "contract" / "examples" / "hello" +_counter = itertools.count(1) + + +@pytest.fixture(autouse=True) +def _no_source_pulls(monkeypatch): + monkeypatch.setenv("FORMEXT_SOURCES_AUTO", "0") + + +@pytest.fixture(scope="session") +def client(): + from fastapi.testclient import TestClient + from app.main import app + from app.services import window_key + + return TestClient(app, headers={window_key.HEADER: window_key.KEY}) + + +@pytest.fixture +def hello(tmp_path): + folder = tmp_path / "pkg" + shutil.copytree(HELLO, folder) + return folder + + +@pytest.fixture +def edit(): + def change(folder, fn): + path = Path(folder) / "manifest.json" + data = json.loads(path.read_text(encoding="utf-8")) + fn(data) + path.write_text(json.dumps(data, indent=2), encoding="utf-8") + return data + + return change + + +@pytest.fixture +def unique(): + def make(stem="lane validate"): + return f"{stem} {next(_counter)} {id(make) % 100000}" + + return make + + +@pytest.fixture +def project(client, unique): + def make(product="formvis", starter="panel", name=None): + r = client.post("/api/templates/create", json={"product": product, "starter": starter, "name": name or unique()}) + assert r.status_code == 200, r.text + return r.json() + + return make diff --git a/tests/validate/test_code_rules.py b/tests/validate/test_code_rules.py new file mode 100644 index 0000000..f91e891 --- /dev/null +++ b/tests/validate/test_code_rules.py @@ -0,0 +1,178 @@ +import pytest + +from app.services import validate + +PAGE = '\n\n\n{body}\n\n\n\n' + + +def setup(hello, edit, js="", body="", permissions=None): + for old in (hello / "ui").iterdir(): + old.unlink() + (hello / "ui" / "index.html").write_text(PAGE.format(body=body), encoding="utf-8") + (hello / "ui" / "app.js").write_text(js, encoding="utf-8") + + def change(m): + m["permissions"] = permissions or [] + m["contributes"] = {"panels": [{"id": "main", "title": "Main", "location": "dock"}]} + + edit(hello, change) + return validate.validate_folder(hello) + + +def by_rule(result, rule): + return [p for p in result["problems"] if p["rule"] == rule] + + +def test_a_page_with_only_package_files_and_no_calls_has_no_problems(hello, edit): + result = setup(hello, edit, js="const a = 1;\n") + assert result["problems"] == [] + assert result["ok"] is True + + +@pytest.mark.parametrize("line,rule", [ + ("fetch('https://example.org/data');", "no-network"), + ("const x = new XMLHttpRequest();", "no-network"), + ("const s = new WebSocket('wss://example.org');", "no-network"), + ("navigator.sendBeacon('/log', '1');", "no-network"), + ("eval('1 + 1');", "no-eval"), + ("const f = new Function('return 1');", "no-eval"), + ("setTimeout('work()', 10);", "no-eval"), + ("localStorage.setItem('a', '1');", "sandbox-storage"), + ("const c = document.cookie;", "sandbox-storage"), +]) +def test_code_the_sandbox_blocks_is_an_error_at_its_line(hello, edit, line, rule): + result = setup(hello, edit, js="const a = 1;\n\n" + line + "\n") + found = by_rule(result, rule) + assert len(found) == 1 + assert (found[0]["file"], found[0]["line"], found[0]["severity"]) == ("ui/app.js", 3, "error") + assert result["ok"] is False + + +@pytest.mark.parametrize("line", ["alert('hi');", "window.open('x.html');"]) +def test_dialogs_and_popups_are_warnings_that_do_not_fail_the_check(hello, edit, line): + result = setup(hello, edit, js=line + "\n") + found = by_rule(result, "sandbox-ui") + assert [(p["severity"], p["line"]) for p in found] == [("warning", 1)] + assert result["ok"] is True + + +@pytest.mark.parametrize("line", [ + "// fetch('https://example.org');", + "/* eval('1') */", + "const text = \"call fetch('x') and eval('y') and localStorage\";", +]) +def test_blocked_words_inside_comments_and_strings_are_not_reported(hello, edit, line): + result = setup(hello, edit, js=line + "\n") + assert result["problems"] == [] + + +def test_an_inline_script_is_an_error_at_the_line_of_its_tag(hello, edit): + result = setup(hello, edit, body="") + found = by_rule(result, "csp-inline-script") + assert [(p["file"], p["line"]) for p in found] == [("ui/index.html", 4)] + assert result["ok"] is False + + +def test_an_inline_handler_attribute_is_an_error_naming_the_attribute(hello, edit): + result = setup(hello, edit, body='') + found = by_rule(result, "csp-inline-script") + assert len(found) == 1 + assert "onclick" in found[0]["message"] + + +def test_a_script_from_the_internet_is_an_error(hello, edit): + result = setup(hello, edit, body='') + found = by_rule(result, "csp-external") + assert len(found) == 1 + assert "https://cdn.example.org/lib.js" in found[0]["message"] + assert result["ok"] is False + + +def test_a_stylesheet_from_the_internet_is_an_error(hello, edit): + result = setup(hello, edit, body='') + assert len(by_rule(result, "csp-external")) == 1 + + +def test_a_frame_is_an_error(hello, edit): + result = setup(hello, edit, body='') + assert [p["severity"] for p in by_rule(result, "csp-frame")] == ["error"] + + +def test_a_script_tag_pointing_at_a_file_that_is_not_there_is_an_error(hello, edit): + result = setup(hello, edit, body='') + found = by_rule(result, "missing-file") + assert [p["message"] for p in found] == ["script gone.js is not in the package."] + + +def test_an_import_reaching_outside_the_package_is_reported_missing(hello, edit): + (hello.parent / "outside.js").write_text("export const a = 1;\n", encoding="utf-8") + result = setup(hello, edit, js="import { a } from '../../outside.js';\n") + assert len(by_rule(result, "missing-file")) == 1 + assert result["ok"] is False + + +def test_a_bare_import_name_is_an_error(hello, edit): + result = setup(hello, edit, js="import x from 'lodash';\n") + found = by_rule(result, "missing-file") + assert len(found) == 1 + assert "lodash" in found[0]["message"] + + +@pytest.mark.parametrize("call,method,permission", [ + ("formext.readDocument();", "document.read", "document"), + ("formext.openFiles({ accept: ['.wav'] });", "files.open", "files-read"), + ("formext.saveFile('a.txt', 'x');", "files.save", "files-write"), + ("formext.fetch('https://example.org');", "net.fetch", "network"), + ("formext.call('app.commands');", "app.commands", "document"), +]) +def test_a_call_that_needs_an_undeclared_permission_is_an_error_naming_both(hello, edit, call, method, permission): + result = setup(hello, edit, js=call + "\n") + found = by_rule(result, "undeclared-permission") + assert len(found) == 1 + assert method in found[0]["message"] + assert f"the {permission} permission" in found[0]["message"] + assert result["ok"] is False + declared = setup(hello, edit, js=call + "\n", permissions=[permission]) + assert declared["problems"] == [] + + +@pytest.mark.parametrize("permission", ["document", "files-read", "files-write", "network", "models", "native-code"]) +def test_a_declared_permission_no_code_uses_is_a_warning_only(hello, edit, permission): + result = setup(hello, edit, js="const a = 1;\n", permissions=[permission]) + found = by_rule(result, "unused-permission") + assert [(p["severity"], p["path"]) for p in found] == [("warning", "permissions[0]")] + assert permission in found[0]["message"] + assert result["ok"] is True + + +def test_a_headless_command_without_an_activate_handler_is_warned_about(hello, edit): + setup(hello, edit, js="const a = 1;\n") + edit(hello, lambda m: m["contributes"].update(commands=[{"id": "go", "title": "Go"}])) + result = validate.validate_folder(hello) + found = by_rule(result, "headless-command") + assert len(found) == 1 + assert "'go'" in found[0]["message"] and "ext.activate" in found[0]["message"] + assert result["ok"] is True + + +def test_a_headless_command_that_handles_activate_and_calls_done_is_clean(hello, edit): + setup(hello, edit, js="formext.onActivate(() => { formext.done(null); });\n") + edit(hello, lambda m: m["contributes"].update(commands=[{"id": "go", "title": "Go"}])) + assert by_rule(validate.validate_folder(hello), "headless-command") == [] + + +def test_a_command_that_opens_a_panel_is_not_treated_as_headless(hello, edit): + setup(hello, edit, js="const a = 1;\n") + edit(hello, lambda m: m["contributes"].update(commands=[{"id": "go", "title": "Go", "panel": "main"}])) + assert validate.validate_folder(hello)["problems"] == [] + + +def test_every_reported_rule_is_in_the_published_rule_list_with_the_same_severity(client, hello, edit): + r = client.get("/api/validate/rules") + listed = {x["id"]: x["severity"] for x in r.json()["rules"]} + assert len(listed) == len(r.json()["rules"]) + result = setup(hello, edit, js="fetch('x');\nalert('y');\nformext.readDocument();\n", body="", permissions=["network"]) + seen = {(p["rule"], p["severity"]) for p in result["problems"]} + assert len(seen) >= 6 + for rule, severity in seen: + assert listed[rule] == severity diff --git a/tests/validate/test_manifest_rules.py b/tests/validate/test_manifest_rules.py new file mode 100644 index 0000000..a138871 --- /dev/null +++ b/tests/validate/test_manifest_rules.py @@ -0,0 +1,249 @@ +import json +import os + +import pytest + +from app.services import validate + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +REQUIRED = ["format", "format_version", "id", "name", "product", "kind", "version", "author", "licence", "native", "permissions"] + + +def schema(): + with open(os.path.join(ROOT, "contract", "schema", "package.schema.json"), encoding="utf-8") as f: + return json.load(f) + + +def errors(result, path=None, rule=None): + return [p for p in result["problems"] if p["severity"] == "error" and (path is None or p["path"] == path) and (rule is None or p["rule"] == rule)] + + +def test_the_contract_example_package_is_accepted_without_errors(hello): + result = validate.validate_folder(hello) + assert result["ok"] is True + assert result["counts"]["error"] == 0 + assert result["id"] == "hello-formext" + assert result["product"] == "formvis" + + +def test_the_schema_requires_the_same_keys_the_refusals_name(): + assert sorted(schema()["required"]) == sorted(REQUIRED) + + +@pytest.mark.parametrize("key", REQUIRED) +def test_a_manifest_without_a_required_key_is_refused_and_names_the_key(hello, edit, key): + edit(hello, lambda m: m.pop(key)) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert f"{key} is required." in [p["message"] for p in errors(result, path=key)] + + +@pytest.mark.parametrize("bad", ["A", "a", "Bad_Id", "-lead", "x" * 65, "has space"]) +def test_an_id_outside_2_to_64_lower_case_letters_digits_hyphens_is_refused(hello, edit, bad): + edit(hello, lambda m: m.update(id=bad)) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert len(errors(result, path="id")) == 1 + + +@pytest.mark.parametrize("good", ["ab", "x" * 64, "0-a", "my-ext-2"]) +def test_an_id_inside_the_stated_shape_is_accepted(hello, edit, good): + edit(hello, lambda m: m.update(id=good)) + result = validate.validate_folder(hello) + assert errors(result) == [] + assert result["id"] == good + + +@pytest.mark.parametrize("bad", ["1.0", "v1.0.0", "1.0.0-beta", "1.0.0.0", ""]) +def test_a_version_that_is_not_three_numbers_is_refused_with_x_y_z(hello, edit, bad): + edit(hello, lambda m: m.update(version=bad)) + result = validate.validate_folder(hello) + assert [p["message"] for p in errors(result, path="version")] == ["version must be x.y.z."] + + +def test_an_unknown_product_is_refused_and_the_message_lists_the_schema_products(hello, edit): + edit(hello, lambda m: m.update(product="formnothing")) + result = validate.validate_folder(hello) + found = errors(result, path="product") + assert len(found) == 1 + for name in schema()["properties"]["product"]["enum"]: + assert name in found[0]["message"] + + +def test_an_unknown_permission_is_refused(hello, edit): + edit(hello, lambda m: m.update(permissions=["document", "camera"])) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert len(errors(result, path="permissions")) == 1 + + +def test_a_permission_listed_twice_is_refused(hello, edit): + edit(hello, lambda m: m.update(permissions=["document", "document"])) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert len(errors(result, path="permissions")) == 1 + + +def test_a_manifest_without_api_is_refused_as_every_api_1_host_would(hello, edit): + edit(hello, lambda m: m.pop("api")) + result = validate.validate_folder(hello) + assert result["ok"] is False + found = errors(result, path="api") + assert found and all("API 1 host" in p["message"] for p in found) + + +@pytest.mark.parametrize("value", ["2", 1, "1.0"]) +def test_an_api_value_other_than_the_text_1_is_refused(hello, edit, value): + edit(hello, lambda m: m.update(api=value)) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert len(errors(result, path="api")) == 1 + + +def test_a_native_extension_is_refused(hello, edit): + edit(hello, lambda m: m.update(native=True)) + result = validate.validate_folder(hello) + assert [p["message"] for p in errors(result, path="native")] == ["native extensions are not supported by API 1 hosts."] + + +def test_format_version_2_is_refused(hello, edit): + edit(hello, lambda m: m.update(format_version=2)) + result = validate.validate_folder(hello) + assert [p["message"] for p in errors(result, path="format_version")] == ["format_version must be 1."] + + +def test_an_entry_page_that_is_not_in_the_folder_is_reported_as_missing_entry(hello, edit): + edit(hello, lambda m: m.update(entry={"ui": "ui/absent.html"})) + result = validate.validate_folder(hello) + found = errors(result, rule="missing-entry") + assert [p["message"] for p in found] == ["entry.ui ui/absent.html is not a file in the folder."] + + +@pytest.mark.parametrize("escape", ["../outside.html", "ui/../../outside.html"]) +def test_an_entry_page_outside_the_package_is_refused(hello, edit, escape): + (hello.parent / "outside.html").write_text("

x

", encoding="utf-8") + edit(hello, lambda m: m.update(entry={"ui": escape})) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert len(errors(result, path="entry.ui")) == 1 + + +def test_contributions_without_an_entry_page_are_refused(hello, edit): + edit(hello, lambda m: m.pop("entry")) + result = validate.validate_folder(hello) + assert "entry.ui is required when panels or commands are contributed." in [p["message"] for p in errors(result)] + + +def test_a_command_that_names_a_panel_nobody_contributes_is_refused(hello, edit): + edit(hello, lambda m: m["contributes"]["commands"][0].update(panel="ghost")) + result = validate.validate_folder(hello) + found = errors(result, path="contributes.commands.panel") + assert [p["message"] for p in found] == ["command 'say-hello' names panel 'ghost', which is not contributed."] + + +def test_one_panel_more_than_the_schema_limit_is_refused(hello, edit): + limit = schema()["properties"]["contributes"]["properties"]["panels"]["maxItems"] + edit(hello, lambda m: m["contributes"].update(panels=[{"id": f"p{i}", "title": f"P {i}", "location": "dock"} for i in range(limit + 1)])) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert [p["message"] for p in errors(result, rule="schema")] == [f"contributes.panels has {limit + 1} items; at most {limit}."] + + +def test_exactly_the_schema_limit_of_panels_is_accepted(hello, edit): + limit = schema()["properties"]["contributes"]["properties"]["panels"]["maxItems"] + edit(hello, lambda m: m["contributes"].update(panels=[{"id": f"p{i}", "title": f"P {i}", "location": "dock"} for i in range(limit)])) + assert errors(validate.validate_folder(hello)) == [] + + +def test_a_panel_location_outside_dock_and_dialog_is_refused(hello, edit): + edit(hello, lambda m: m["contributes"]["panels"][0].update(location="sidebar")) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert [p["path"] for p in errors(result)] == ["contributes.panels[0].location"] + + +def test_a_description_one_character_over_the_schema_limit_is_refused(hello, edit): + limit = schema()["properties"]["description"]["maxLength"] + edit(hello, lambda m: m.update(description="d" * (limit + 1))) + result = validate.validate_folder(hello) + assert [p["message"] for p in errors(result)] == [f"description is {limit + 1} characters; at most {limit}."] + edit(hello, lambda m: m.update(description="d" * limit)) + assert errors(validate.validate_folder(hello)) == [] + + +def test_a_homepage_that_is_not_https_is_refused(hello, edit): + edit(hello, lambda m: m.update(homepage="http://example.org/")) + result = validate.validate_folder(hello) + assert result["ok"] is False + assert [p["path"] for p in errors(result)] == ["homepage"] + + +def test_a_missing_description_is_only_a_note_and_the_package_stays_valid(hello, edit): + edit(hello, lambda m: m.pop("description")) + result = validate.validate_folder(hello) + assert result["ok"] is True + notes = [p for p in result["problems"] if p["rule"] == "description"] + assert [(p["severity"], p["message"]) for p in notes] == [("info", "There is no description.")] + + +def test_a_folder_without_a_manifest_is_refused_in_plain_words(tmp_path): + result = validate.validate_folder(tmp_path) + assert result["ok"] is False + assert [p["message"] for p in result["problems"]] == ["There is no manifest.json at the package root."] + + +def test_a_syntax_error_is_reported_at_its_line(hello): + (hello / "manifest.json").write_text('{\n "id": "ab",\n "name" "x"\n}\n', encoding="utf-8") + result = validate.validate_folder(hello) + found = [p for p in result["problems"] if p["rule"] == "json"] + assert len(found) == 1 + assert found[0]["line"] == 3 + assert found[0]["severity"] == "error" + assert result["ok"] is False + + +def test_a_manifest_that_is_a_list_is_refused(hello): + (hello / "manifest.json").write_text("[1, 2]", encoding="utf-8") + result = validate.validate_folder(hello) + assert [p["message"] for p in result["problems"] if p["rule"] == "json"] == ["manifest.json must hold one JSON object."] + + +def test_a_problem_points_at_the_line_of_the_offending_key(hello, edit): + edit(hello, lambda m: m.update(version="nope")) + lines = (hello / "manifest.json").read_text(encoding="utf-8").splitlines() + expected = next(i for i, text in enumerate(lines, 1) if '"version"' in text) + result = validate.validate_folder(hello) + assert errors(result, path="version")[0]["line"] == expected + + +def test_a_file_type_outside_the_contract_list_is_refused_by_name(hello): + (hello / "ui" / "tool.exe").write_bytes(b"MZ") + result = validate.validate_folder(hello) + found = [p for p in errors(result, rule="package") if p["file"] == "ui/tool.exe"] + assert [p["message"] for p in found] == ["The file type .exe is not allowed."] + + +def test_a_symlink_in_the_package_is_refused(hello, tmp_path): + (tmp_path / "secret.txt").write_text("s", encoding="utf-8") + os.symlink(tmp_path / "secret.txt", hello / "ui" / "link.txt") + result = validate.validate_folder(hello) + found = [p for p in errors(result, rule="package") if p["file"] == "ui/link.txt"] + assert [p["message"] for p in found] == ["Symlinks are not allowed."] + + +def test_counts_add_up_and_errors_are_listed_before_warnings_and_notes(hello, edit): + edit(hello, lambda m: (m.update(version="x", permissions=["document", "network"]), m.pop("description"))) + result = validate.validate_folder(hello) + assert sum(result["counts"].values()) == len(result["problems"]) + rank = {"error": 0, "warning": 1, "info": 2} + order = [rank[p["severity"]] for p in result["problems"]] + assert order == sorted(order) + assert set(order) == {0, 1, 2} + + +def test_the_prefix_is_put_in_front_of_every_reported_file(hello, edit): + edit(hello, lambda m: m.update(version="x")) + (hello / "ui" / "tool.exe").write_bytes(b"MZ") + result = validate.validate_folder(hello, "package") + assert result["manifest"] == "package/manifest.json" + assert {p["file"] for p in result["problems"]} == {"package/manifest.json", "package/ui/tool.exe"} diff --git a/tests/validate/test_package_and_templates.py b/tests/validate/test_package_and_templates.py new file mode 100644 index 0000000..2393f32 --- /dev/null +++ b/tests/validate/test_package_and_templates.py @@ -0,0 +1,290 @@ +import hashlib +import io +import json +import zipfile +from pathlib import Path + +import pytest + +from app.services.workspace import workspace + +ROOT = Path(__file__).resolve().parent.parent.parent +TEMPLATES = ROOT / "templates" +PAIRS = sorted((p.name, s.name) for p in TEMPLATES.iterdir() if p.is_dir() and not p.name.startswith("_") for s in p.iterdir() if (s / "manifest.json").is_file()) +ALLOWED = set(".html .js .mjs .css .json .svg .png .webp .jpg .jpeg .gif .wasm .txt .md .wav .ogg .mp3 .webm .mp4 .cube .woff2".split()) + + +def build(client, pid, **body): + return client.post(f"/api/projects/{pid}/package", json=body) + + +def archive(client, pid, sha): + r = client.get(f"/api/projects/{pid}/builds/{sha}/file") + assert r.status_code == 200 + return r.content, zipfile.ZipFile(io.BytesIO(r.content)) + + +def test_the_shipped_templates_are_twelve_apps_with_three_starters_each(): + assert len(PAIRS) == 36 + assert {s for _, s in PAIRS} == {"panel", "command", "panel-commands"} + + +@pytest.mark.parametrize("product,starter", PAIRS) +def test_a_project_made_from_a_shipped_template_passes_the_check(client, project, product, starter): + made = project(product, starter) + r = client.post(f"/api/projects/{made['id']}/validate") + result = r.json() + assert result["counts"]["error"] == 0, result["problems"] + assert result["ok"] is True + assert result["id"] == made["id"] + assert result["product"] == product + assert result["project"] == made["id"] + + +def test_the_catalogue_lists_every_template_folder_on_disk(client): + data = client.get("/api/templates").json() + listed = sorted((p["id"], s["starter"]) for p in data["products"] for s in p["starters"]) + assert listed == PAIRS + + +def test_starter_detail_returns_the_manifest_text_that_is_on_disk(client): + data = client.get("/api/templates/formpdf/panel").json() + files = {f["path"]: f for f in data["files"]} + on_disk = (TEMPLATES / "formpdf" / "panel" / "manifest.json").read_bytes() + assert files["manifest.json"]["text"] == on_disk.decode("utf-8") + assert files["manifest.json"]["size"] == len(on_disk) + assert "template.json" not in files + + +def test_an_unknown_starter_is_refused_by_name(client): + r = client.get("/api/templates/formpdf/wizard") + assert r.status_code == 404 + assert r.json()["detail"] == "no starter named wizard" + + +def test_an_unknown_app_is_refused_by_name(client): + r = client.post("/api/templates/create", json={"product": "formnothing", "starter": "panel", "name": "x y"}) + assert r.status_code == 404 + assert r.json()["detail"] == "no templates for formnothing" + + +def test_a_project_without_a_name_is_refused(client): + r = client.post("/api/templates/create", json={"product": "formvis", "starter": "panel", "name": " "}) + assert r.status_code == 400 + assert r.json()["detail"] == "a project needs a name" + + +def test_a_name_of_65_characters_is_refused_and_64_is_accepted(client, unique): + stem = unique("n") + r = client.post("/api/templates/create", json={"product": "formvis", "starter": "panel", "name": stem + "x" * (65 - len(stem))}) + assert r.status_code == 400 + assert r.json()["detail"] == "the name is longer than 64 characters" + ok = client.post("/api/templates/create", json={"product": "formvis", "starter": "panel", "name": stem + "x" * (64 - len(stem))}) + assert ok.status_code == 200 + + +def test_the_scaffolded_manifest_carries_the_given_name_description_and_project_id(client, project, unique): + name = unique("Named Thing") + r = client.post("/api/templates/create", json={"product": "formwav", "starter": "panel", "name": name, "description": "Does one thing."}) + made = r.json() + manifest = json.loads((workspace.package_dir(made["id"]) / "manifest.json").read_text(encoding="utf-8")) + assert manifest["name"] == name + assert manifest["description"] == "Does one thing." + assert manifest["id"] == made["id"] + assert manifest["product"] == "formwav" + + +def test_two_projects_with_the_same_name_get_different_ids_and_each_manifest_matches_its_own(client, project, unique): + name = unique("Twin") + a, b = project(name=name), project(name=name) + assert a["id"] != b["id"] + for made in (a, b): + manifest = json.loads((workspace.package_dir(made["id"]) / "manifest.json").read_text(encoding="utf-8")) + assert manifest["id"] == made["id"] + assert client.post(f"/api/projects/{made['id']}/validate").json()["ok"] is True + + +def test_a_project_made_from_the_contract_example_passes_the_check(client, unique): + listed = client.get("/api/templates/examples").json()["examples"] + assert "hello" in [e["id"] for e in listed] + made = client.post("/api/templates/examples/hello", json={"name": unique("Hello copy")}).json() + result = client.post(f"/api/projects/{made['id']}/validate").json() + assert result["ok"] is True + assert result["id"] == made["id"] + + +def test_an_unknown_example_is_refused_by_name(client): + r = client.post("/api/templates/examples/nothing-here", json={}) + assert r.status_code == 404 + assert r.json()["detail"] == "no example named nothing-here" + + +@pytest.fixture +def built(client, project): + made = project("formvis", "panel-commands") + r = build(client, made["id"]) + assert r.status_code == 200, r.text + return made, r.json() + + +def test_the_package_file_hashes_to_the_reported_sha_and_size(client, built): + made, record = built + data, _ = archive(client, made["id"], record["sha256"]) + assert hashlib.sha256(data).hexdigest() == record["sha256"] + assert len(data) == record["bytes"] + + +def test_the_package_holds_exactly_the_files_of_the_package_folder(client, built): + made, record = built + _, z = archive(client, made["id"], record["sha256"]) + folder = workspace.package_dir(made["id"]) + on_disk = {p.relative_to(folder).as_posix(): p.read_bytes() for p in folder.rglob("*") if p.is_file()} + assert set(z.namelist()) == set(on_disk) + for name, data in on_disk.items(): + assert z.read(name) == data + assert z.testzip() is None + + +def test_the_manifest_inside_the_package_names_the_project(client, built): + made, record = built + _, z = archive(client, made["id"], record["sha256"]) + manifest = json.loads(z.read("manifest.json")) + assert manifest["id"] == made["id"] + assert manifest["format"] == "formai-package" + assert manifest["entry"]["ui"] in z.namelist() + assert record["file"] == f"{manifest['id']}-{manifest['version']}.formpkg" + + +def test_no_entry_name_is_absolute_climbs_out_or_has_a_type_outside_the_contract_list(client, built): + made, record = built + _, z = archive(client, made["id"], record["sha256"]) + for name in z.namelist(): + assert not name.startswith("/") + assert "\\" not in name + assert ".." not in name.split("/") + assert len(name) <= 200 + assert Path(name).suffix.lower() in ALLOWED + + +def test_entries_are_sorted_dated_1980_mode_0644_and_deflated_as_the_contract_states(client, built): + made, record = built + _, z = archive(client, made["id"], record["sha256"]) + infos = z.infolist() + assert [i.filename for i in infos] == sorted(i.filename for i in infos) + for i in infos: + assert i.date_time == (1980, 1, 1, 0, 0, 0) + assert (i.external_attr >> 16) & 0o777 == 0o644 + assert i.compress_type == zipfile.ZIP_DEFLATED + + +def test_the_build_record_lists_each_entry_with_its_own_sha_and_size(client, built): + made, record = built + _, z = archive(client, made["id"], record["sha256"]) + expected = [{"path": i.filename, "size": i.file_size, "sha256": hashlib.sha256(z.read(i.filename)).hexdigest()} for i in z.infolist()] + assert [{k: e[k] for k in ("path", "size", "sha256")} for e in record["entries"]] == expected + + +def test_building_the_same_folder_twice_gives_the_same_sha_and_counts_two_builds(client, built): + made, record = built + again = build(client, made["id"]).json() + assert again["sha256"] == record["sha256"] + assert (record["fresh"], again["fresh"]) == (True, False) + assert again["times_built"] == 2 + listed = client.get(f"/api/projects/{made['id']}/builds").json()["builds"] + assert [b["sha256"] for b in listed] == [record["sha256"]] + + +def test_changing_one_file_changes_the_sha(client, built): + made, record = built + (workspace.package_dir(made["id"]) / "ui" / "extra.txt").write_text("more", encoding="utf-8") + again = build(client, made["id"]).json() + assert again["sha256"] != record["sha256"] + _, z = archive(client, made["id"], again["sha256"]) + assert z.read("ui/extra.txt") == b"more" + + +def test_the_kit_command_line_reproduces_the_stored_build_bit_for_bit(client, built): + made, record = built + r = client.post(f"/api/projects/{made['id']}/package/reproduce").json() + assert r["reproducible"] is True + assert r["differences"] == [] + assert {run["sha256"] for run in r["runs"]} == {record["sha256"]} + assert r["matches_build"] == record["sha256"] + assert r["source_changed"] is False + + +def test_a_hidden_file_in_the_package_folder_is_left_out_of_the_package(client, project): + made = project() + (workspace.package_dir(made["id"]) / ".secret.txt").write_text("key", encoding="utf-8") + record = build(client, made["id"]).json() + _, z = archive(client, made["id"], record["sha256"]) + assert ".secret.txt" not in z.namelist() + + +def test_a_manifest_every_host_would_refuse_cannot_be_packaged_even_with_anyway(client, project): + made = project() + path = workspace.package_dir(made["id"]) / "manifest.json" + manifest = json.loads(path.read_text(encoding="utf-8")) + manifest["version"] = "one" + path.write_text(json.dumps(manifest), encoding="utf-8") + for body in ({}, {"anyway": True}): + r = build(client, made["id"], **body) + assert r.status_code == 422 + assert r.json()["detail"] == "1 contract error: every host would refuse this package. Fix it first (Check lists where)." + assert r.json()["check"]["ok"] is False + assert client.get(f"/api/projects/{made['id']}/builds").json()["builds"] == [] + + +def test_a_code_error_stops_packaging_until_the_person_says_anyway(client, project): + made = project() + (workspace.package_dir(made["id"]) / "ui" / "bad.js").write_text("eval('1');\n", encoding="utf-8") + r = build(client, made["id"]) + assert r.status_code == 422 + assert r.json()["detail"] == "Check found 1 code error (parts of the extension may not run). Fix it, or package anyway." + forced = build(client, made["id"], anyway=True) + assert forced.status_code == 200 + assert forced.json()["anyway"] is True + _, z = archive(client, made["id"], forced.json()["sha256"]) + assert z.read("ui/bad.js") == b"eval('1');\n" + + +def test_a_file_type_outside_the_contract_list_stops_packaging(client, project): + made = project() + (workspace.package_dir(made["id"]) / "ui" / "tool.exe").write_bytes(b"MZ") + r = build(client, made["id"], anyway=True) + assert r.status_code == 422 + assert client.get(f"/api/projects/{made['id']}/builds").json()["builds"] == [] + + +def test_a_removed_build_can_no_longer_be_fetched(client, built): + made, record = built + sha = record["sha256"] + assert client.delete(f"/api/projects/{made['id']}/builds/{sha}").json() == {"project": made["id"], "sha256": sha, "removed": True} + r = client.get(f"/api/projects/{made['id']}/builds/{sha}/file") + assert r.status_code == 404 + assert r.json()["detail"] == f"no build {sha[:12]} of {made['id']}" + + +@pytest.mark.parametrize("sha", ["abc", "g" * 64, "A" * 64]) +def test_a_build_address_that_is_not_a_sha256_is_refused(client, built, sha): + made, _ = built + r = client.get(f"/api/projects/{made['id']}/builds/{sha}") + assert r.status_code == 404 + assert r.json()["detail"] == "no such build" + + +def test_the_index_entry_carries_the_sha_size_and_default_https_address(client, built): + made, record = built + r = client.get(f"/api/projects/{made['id']}/builds/{record['sha256']}/entry").json() + text = json.dumps(r["entry"]) + assert record["sha256"] in text + assert f"https://formai.studio/extensions/packages/{made['id']}-{record['version']}.formpkg" in text + assert r["url_default"] is True + assert "signature" not in r["entry"] + + +def test_an_index_address_that_is_not_https_is_refused(client, built): + made, record = built + r = client.get(f"/api/projects/{made['id']}/builds/{record['sha256']}/entry", params={"url": "http://example.org/a.formpkg"}) + assert r.status_code == 400 + assert r.json()["detail"] == "The package address in the index must start with https://." From d5bb37d92a1a8577ca197c608c03c7e2be627e3c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:18 -0500 Subject: [PATCH 13/15] test(workspace): projects, project files, path escapes, settings, preview serving and library refusals through the real app (0.11.0) Projects are created, listed, opened, renamed, imported, linked and deleted over HTTP and read back from disk; files are written, read, moved and deleted with climbing, absolute and symlinked paths refused; settings are saved and read back; the preview route is checked for bytes and content type per file kind. Expected values come from round trips (write then read, route against disk), the standard media types of the file formats, the README rule that only the window can change anything, and the invariant that nothing lands outside the project. Ran: backend/venv/bin/python -m pytest tests/workspace -q -p no:cacheprovider, 96 passed, 0 expected failures. --- tests/workspace/conftest.py | 41 +++ tests/workspace/test_files.py | 193 +++++++++++++ tests/workspace/test_projects.py | 183 +++++++++++++ .../test_settings_preview_library.py | 256 ++++++++++++++++++ 4 files changed, 673 insertions(+) create mode 100644 tests/workspace/conftest.py create mode 100644 tests/workspace/test_files.py create mode 100644 tests/workspace/test_projects.py create mode 100644 tests/workspace/test_settings_preview_library.py diff --git a/tests/workspace/conftest.py b/tests/workspace/conftest.py new file mode 100644 index 0000000..caa51da --- /dev/null +++ b/tests/workspace/conftest.py @@ -0,0 +1,41 @@ +import sys +from pathlib import Path + +import pytest + +TESTS = Path(__file__).resolve().parent.parent +if str(TESTS) not in sys.path: + sys.path.insert(0, str(TESTS)) + +import stand_ins # noqa: E402,F401 + +from fastapi.testclient import TestClient # noqa: E402 + +from app.main import app # noqa: E402 +from app.services import window_key # noqa: E402 + + +@pytest.fixture +def home(tmp_path, monkeypatch): + folder = tmp_path / "data" + folder.mkdir() + monkeypatch.setenv("FORMEXT_HOME", str(folder)) + monkeypatch.setenv("FORMEXT_WATCH", "0") + return folder + + +@pytest.fixture +def client(home): + return TestClient(app, headers={window_key.HEADER: window_key.KEY}, raise_server_exceptions=False) + + +@pytest.fixture +def outsider(home): + return TestClient(app, raise_server_exceptions=False) + + +@pytest.fixture +def project(client): + made = client.post("/api/projects", json={"name": "Grain Tool", "product": "formvis"}) + assert made.status_code == 200, made.text + return made.json() diff --git a/tests/workspace/test_files.py b/tests/workspace/test_files.py new file mode 100644 index 0000000..0ae96da --- /dev/null +++ b/tests/workspace/test_files.py @@ -0,0 +1,193 @@ +import base64 +import os + +import pytest + +from app.services.workspace import NotFound, Unsafe, clean_rel, safe_join, slug + +BASE = "/api/projects/grain-tool/files" + + +def test_text_written_to_a_project_file_reads_back_the_same_and_is_on_disk(client, project, home): + text = "line one\nline two \u00e9\n" + wrote = client.put(f"{BASE}/package/src/app.js", json={"text": text}) + assert wrote.status_code == 200 + assert wrote.json()["size"] == len(text.encode("utf-8")) + got = client.get(f"{BASE}/package/src/app.js").json() + assert (got["encoding"], got["text"], got["path"]) == ("utf-8", text, "package/src/app.js") + assert (home / "projects" / "grain-tool" / "package" / "src" / "app.js").read_bytes() == text.encode("utf-8") + + +def test_binary_bytes_survive_a_base64_write_and_read(client, project): + data = bytes(range(256)) + client.put(f"{BASE}/package/blob.bin", json={"base64": base64.b64encode(data).decode()}) + got = client.get(f"{BASE}/package/blob.bin").json() + assert got["encoding"] == "base64" + assert base64.b64decode(got["base64"]) == data + assert got["size"] == 256 + + +def test_raw_upload_is_served_back_byte_for_byte_with_the_type_of_its_extension(client, project): + png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16 + assert client.put(f"{BASE}/package/icon.png?raw=1", content=png).status_code == 200 + got = client.get(f"{BASE}/package/icon.png?raw=1") + assert got.content == png + assert got.headers["content-type"] == "image/png" + assert got.headers["x-content-type-options"] == "nosniff" + assert got.headers["cache-control"] == "no-store" + + +def test_overwriting_a_file_replaces_its_content_and_leaves_no_temp_file_listed(client, project): + client.put(f"{BASE}/package/a.txt", json={"text": "first"}) + client.put(f"{BASE}/package/a.txt", json={"text": "second"}) + assert client.get(f"{BASE}/package/a.txt").json()["text"] == "second" + listed = client.get("/api/projects/grain-tool/files").json() + assert sorted(f["path"] for f in listed["files"]) == ["package/a.txt", "package/manifest.json"] + + +def test_file_list_reports_sizes_and_which_files_ship_in_the_package(client, project): + client.put(f"{BASE}/package/a.txt", json={"text": "12345"}) + client.put(f"{BASE}/notes.md", json={"text": "abc"}) + listed = {f["path"]: f for f in client.get("/api/projects/grain-tool/files").json()["files"]} + assert listed["package/a.txt"]["size"] == 5 + assert listed["package/a.txt"]["package"] is True + assert listed["notes.md"]["size"] == 3 + assert listed["notes.md"]["package"] is False + + +def test_write_body_without_text_or_base64_is_refused_and_writes_nothing(client, project, home): + res = client.put(f"{BASE}/package/a.txt", json={"content": "x"}) + assert res.status_code == 400 + assert res.json()["detail"] == "send JSON with text or base64, or use ?raw=1" + assert not (home / "projects" / "grain-tool" / "package" / "a.txt").exists() + + +def test_reading_a_file_that_is_not_there_is_refused_with_its_path(client, project): + res = client.get(f"{BASE}/package/missing.txt") + assert res.status_code == 404 + assert res.json()["detail"] == "no such file: package/missing.txt" + + +def test_reading_a_folder_as_a_file_is_refused(client, project): + res = client.get(f"{BASE}/package") + assert res.status_code == 404 + assert res.json()["detail"] == "not a file: package" + + +def test_writing_a_file_where_a_folder_is_is_refused(client, project): + res = client.put(f"{BASE}/package", json={"text": "x"}) + assert res.status_code == 409 + assert res.json()["detail"] == "a folder is at package" + + +def test_writing_into_an_unknown_project_is_refused_and_creates_no_folder(client, home): + res = client.put("/api/projects/never-made/files/a.txt", json={"text": "x"}) + assert res.status_code == 404 + assert res.json()["detail"] == "no such project: never-made" + assert not (home / "projects" / "never-made").exists() + + +@pytest.mark.parametrize("rel", ["..%2F..%2Fsecret.txt", "package%2F..%2F..%2Fsecret.txt", "..%5C..%5Csecret.txt"]) +def test_write_with_a_path_that_climbs_out_of_the_project_is_refused_and_nothing_lands_outside(client, project, home, rel): + res = client.put(f"{BASE}/{rel}", json={"text": "stolen"}) + assert res.status_code == 400 + assert res.json()["detail"] == "path leaves the project" + assert not (home / "secret.txt").exists() + assert not (home / "projects" / "secret.txt").exists() + + +def test_read_with_a_path_that_climbs_out_does_not_return_the_outside_file(client, project, home): + (home / "projects" / "secret.txt").write_text("private", encoding="utf-8") + res = client.get(f"{BASE}/..%2Fsecret.txt") + assert res.status_code == 400 + assert "private" not in res.text + assert res.json()["detail"] == "path leaves the project" + + +def test_absolute_path_is_refused_for_reading(client, project): + res = client.get(f"{BASE}/%2Fetc%2Fhostname") + assert res.status_code == 400 + assert res.json()["detail"] == "absolute paths are not allowed" + + +@pytest.mark.skipif(os.name == "nt", reason="symbolic links need extra rights on this system") +def test_symbolic_link_inside_a_project_is_not_followed_to_an_outside_file(client, project, home, tmp_path): + outside = tmp_path / "outside.txt" + outside.write_text("private", encoding="utf-8") + os.symlink(outside, home / "projects" / "grain-tool" / "package" / "link.txt") + res = client.get(f"{BASE}/package/link.txt") + assert res.status_code == 400 + assert res.json()["detail"] == "symbolic links are not followed" + wrote = client.put(f"{BASE}/package/link.txt", json={"text": "changed"}) + assert wrote.status_code == 400 + assert outside.read_text(encoding="utf-8") == "private" + assert "package/link.txt" not in [f["path"] for f in client.get("/api/projects/grain-tool/files").json()["files"]] + + +def test_deleted_file_is_gone_from_disk_and_a_second_delete_is_refused(client, project, home): + client.put(f"{BASE}/package/a.txt", json={"text": "x"}) + res = client.delete(f"{BASE}/package/a.txt") + assert res.json() == {"path": "package/a.txt", "deleted": True} + assert not (home / "projects" / "grain-tool" / "package" / "a.txt").exists() + again = client.delete(f"{BASE}/package/a.txt") + assert again.status_code == 404 + assert again.json()["detail"] == "no such file: package/a.txt" + + +def test_moved_file_keeps_its_content_under_the_new_name_only(client, project): + client.put(f"{BASE}/package/a.txt", json={"text": "moved text"}) + res = client.post("/api/projects/grain-tool/move", json={"from": "package/a.txt", "to": "package/deep/b.txt"}) + assert res.json() == {"from": "package/a.txt", "to": "package/deep/b.txt"} + assert client.get(f"{BASE}/package/deep/b.txt").json()["text"] == "moved text" + assert client.get(f"{BASE}/package/a.txt").status_code == 404 + + +def test_move_onto_an_existing_file_is_refused_and_both_files_keep_their_content(client, project): + client.put(f"{BASE}/package/a.txt", json={"text": "A"}) + client.put(f"{BASE}/package/b.txt", json={"text": "B"}) + res = client.post("/api/projects/grain-tool/move", json={"from": "package/a.txt", "to": "package/b.txt"}) + assert res.status_code == 409 + assert res.json()["detail"] == "package/b.txt already exists" + assert client.get(f"{BASE}/package/a.txt").json()["text"] == "A" + assert client.get(f"{BASE}/package/b.txt").json()["text"] == "B" + + +def test_move_to_a_place_outside_the_project_is_refused_and_the_file_stays(client, project, home): + client.put(f"{BASE}/package/a.txt", json={"text": "A"}) + res = client.post("/api/projects/grain-tool/move", json={"from": "package/a.txt", "to": "../../a.txt"}) + assert res.status_code == 400 + assert res.json()["detail"] == "path leaves the project" + assert client.get(f"{BASE}/package/a.txt").json()["text"] == "A" + assert not (home / "a.txt").exists() + + +def test_file_over_fifty_megabytes_is_refused_with_the_limit_in_words(client, project, home): + big = b"a" * (50 * 1024 * 1024 + 1) + res = client.put(f"{BASE}/package/big.bin?raw=1", content=big) + assert res.status_code == 400 + assert res.json()["detail"] == "the file is larger than 50 MB" + assert not (home / "projects" / "grain-tool" / "package" / "big.bin").exists() + + +@pytest.mark.parametrize("given,expected", [("a/./b//c.txt", "a/b/c.txt"), ("a\\b\\c.txt", "a/b/c.txt"), ("./x.txt", "x.txt")]) +def test_clean_rel_gives_one_forward_slash_form_for_equal_paths(given, expected): + assert clean_rel(given) == expected + + +@pytest.mark.parametrize("bad,message", [("", "invalid path"), ("a\x00b", "invalid path"), ("/abs", "absolute paths are not allowed"), ("C:\\x", "absolute paths are not allowed"), ("a/../b", "path leaves the project"), (".", "path leaves the project"), ("a/" * 201 + "b", "path is too long")]) +def test_clean_rel_refuses_paths_that_could_leave_a_project(bad, message): + with pytest.raises(Unsafe) as caught: + clean_rel(bad) + assert caught.value.message == message + + +def test_safe_join_stays_under_the_root_and_reports_missing_files(tmp_path): + assert safe_join(tmp_path, "a/b.txt") == tmp_path.resolve() / "a" / "b.txt" + with pytest.raises(NotFound) as caught: + safe_join(tmp_path, "a/b.txt", must_exist=True) + assert caught.value.message == "no such file: a/b.txt" + + +@pytest.mark.parametrize("name,expected", [("Grain Tool", "grain-tool"), (" Hello, World! ", "hello-world"), ("x", "x-extension"), ("", "extension"), ("A" * 80, "a" * 48)]) +def test_slug_turns_a_name_into_a_lower_case_dashed_id(name, expected): + assert slug(name) == expected diff --git a/tests/workspace/test_projects.py b/tests/workspace/test_projects.py new file mode 100644 index 0000000..9301df4 --- /dev/null +++ b/tests/workspace/test_projects.py @@ -0,0 +1,183 @@ +import base64 +import json +from pathlib import Path + + +def test_created_project_is_a_folder_on_disk_with_a_manifest_naming_it(client, home): + made = client.post("/api/projects", json={"name": "Grain Tool", "product": "formvis"}).json() + assert made["id"] == "grain-tool" + manifest = json.loads((home / "projects" / "grain-tool" / "package" / "manifest.json").read_text(encoding="utf-8")) + assert manifest["name"] == "Grain Tool" + assert manifest["product"] == "formvis" + assert manifest["id"] == "grain-tool" + assert made["manifest"] == manifest + + +def test_created_project_is_listed_and_read_back_with_the_same_name_and_product(client, project): + listed = client.get("/api/projects").json()["projects"] + assert [(p["id"], p["name"], p["product"]) for p in listed] == [("grain-tool", "Grain Tool", "formvis")] + opened = client.get("/api/projects/grain-tool").json() + assert (opened["name"], opened["product"], opened["package_prefix"]) == ("Grain Tool", "formvis", "package") + + +def test_two_projects_with_one_name_get_different_ids_and_both_stay_listed(client): + a = client.post("/api/projects", json={"name": "Same Name", "product": "formcut"}).json() + b = client.post("/api/projects", json={"name": "Same Name", "product": "formcut"}).json() + assert a["id"] == "same-name" + assert b["id"] != a["id"] + assert {p["id"] for p in client.get("/api/projects").json()["projects"]} == {a["id"], b["id"]} + + +def test_project_without_a_name_is_refused_and_nothing_is_created(client, home): + res = client.post("/api/projects", json={"name": " ", "product": "formvis"}) + assert res.status_code == 400 + assert res.json()["detail"] == "a project needs a name" + assert client.get("/api/projects").json()["projects"] == [] + + +def test_project_for_an_unknown_product_is_refused_by_name(client): + res = client.post("/api/projects", json={"name": "Thing", "product": "formnothing"}) + assert res.status_code == 400 + assert res.json()["detail"] == "unknown product: formnothing" + assert client.get("/api/projects").json()["projects"] == [] + + +def test_project_created_with_files_holds_those_files_inside_its_package(client, home): + body = {"name": "With Files", "product": "formpdf", "files": {"main.js": "let a = 1;\n", "img/dot.bin": {"base64": base64.b64encode(b"\x00\x01\xff").decode()}}} + made = client.post("/api/projects", json=body).json() + root = home / "projects" / made["id"] + assert (root / "package" / "main.js").read_bytes() == b"let a = 1;\n" + assert (root / "package" / "img" / "dot.bin").read_bytes() == b"\x00\x01\xff" + + +def test_project_created_with_a_file_path_that_climbs_out_is_refused_and_leaves_nothing_behind(client, home, tmp_path): + res = client.post("/api/projects", json={"name": "Climber", "product": "formvis", "files": {"package/../../../escaped.txt": "x"}}) + assert res.status_code == 400 + assert res.json()["detail"] == "path leaves the project" + assert not (tmp_path / "escaped.txt").exists() + assert not (home / "escaped.txt").exists() + assert client.get("/api/projects").json()["projects"] == [] + + +def test_renaming_through_the_manifest_changes_the_name_shown_in_the_list(client, project, home): + path = home / "projects" / "grain-tool" / "package" / "manifest.json" + manifest = json.loads(path.read_text(encoding="utf-8")) + manifest["name"] = "Film Grain" + res = client.put("/api/projects/grain-tool/files/package/manifest.json", json={"text": json.dumps(manifest)}) + assert res.status_code == 200 + assert client.get("/api/projects/grain-tool").json()["name"] == "Film Grain" + assert [p["name"] for p in client.get("/api/projects").json()["projects"]] == ["Film Grain"] + assert json.loads(path.read_text(encoding="utf-8"))["name"] == "Film Grain" + + +def test_broken_manifest_is_reported_and_the_project_stays_listed_under_its_first_name(client, project): + client.put("/api/projects/grain-tool/files/package/manifest.json", json={"text": "{not json"}) + opened = client.get("/api/projects/grain-tool").json() + assert opened["manifest_error"].startswith("manifest.json is not valid JSON") + assert opened["manifest"] == {} + assert opened["name"] == "Grain Tool" + + +def test_deleted_project_leaves_the_list_and_its_files_move_to_the_trash(client, project, home): + client.put("/api/projects/grain-tool/files/package/keep.txt", json={"text": "kept"}) + res = client.delete("/api/projects/grain-tool") + assert res.status_code == 200 + gone = res.json() + assert gone["removed"] == "trash" + assert client.get("/api/projects").json()["projects"] == [] + assert not (home / "projects" / "grain-tool").exists() + moved = Path(gone["dir"]) + assert moved.parent == (home / "trash").resolve() or moved.parent == home / "trash" + assert (moved / "package" / "keep.txt").read_text(encoding="utf-8") == "kept" + assert client.get("/api/projects/grain-tool").status_code == 404 + + +def test_opening_an_unknown_project_is_refused_with_its_id(client): + res = client.get("/api/projects/never-made") + assert res.status_code == 404 + assert res.json()["detail"] == "no such project: never-made" + + +def test_deleting_an_unknown_project_is_refused_with_its_id(client): + res = client.delete("/api/projects/never-made") + assert res.status_code == 404 + assert res.json()["detail"] == "no such project: never-made" + + +def test_listing_files_of_an_unknown_project_is_refused(client): + res = client.get("/api/projects/never-made/files") + assert res.status_code == 404 + assert res.json()["detail"] == "no such project: never-made" + + +def test_project_id_that_is_not_a_plain_slug_is_refused(client): + res = client.get("/api/projects/Not_A_Slug") + assert res.status_code == 404 + assert res.json()["detail"] == "no such project" + + +def test_recent_list_puts_the_last_opened_project_first(client): + a = client.post("/api/projects", json={"name": "First One", "product": "formvis"}).json()["id"] + b = client.post("/api/projects", json={"name": "Second One", "product": "formvis"}).json()["id"] + assert [p["id"] for p in client.get("/api/projects/recent").json()["projects"]] == [b, a] + client.get(f"/api/projects/{a}") + assert [p["id"] for p in client.get("/api/projects/recent").json()["projects"]] == [a, b] + assert [p["id"] for p in client.get("/api/projects/recent?limit=1").json()["projects"]] == [a] + + +def test_peeking_at_a_project_without_touch_keeps_the_recent_order(client): + a = client.post("/api/projects", json={"name": "First One", "product": "formvis"}).json()["id"] + b = client.post("/api/projects", json={"name": "Second One", "product": "formvis"}).json()["id"] + client.get(f"/api/projects/{a}?touch=false") + assert [p["id"] for p in client.get("/api/projects/recent").json()["projects"]] == [b, a] + + +def test_changing_request_without_the_window_key_is_refused_and_creates_nothing(outsider, home): + res = outsider.post("/api/projects", json={"name": "Sneak", "product": "formvis"}) + assert res.status_code == 403 + assert res.json()["detail"] == "Only the form.ext window can do this" + assert outsider.get("/api/projects").json()["projects"] == [] + assert not (home / "projects" / "sneak").exists() + + +def test_imported_folder_is_copied_so_later_edits_to_the_source_do_not_show(client, home, tmp_path): + src = tmp_path / "src-pack" + src.mkdir() + (src / "manifest.json").write_text(json.dumps({"id": "outside-pack", "name": "Outside Pack", "product": "formwav", "version": "2.3.4"}), encoding="utf-8") + (src / "a.txt").write_text("one", encoding="utf-8") + made = client.post("/api/projects/import", json={"path": str(src)}) + assert made.status_code == 200, made.text + got = made.json() + assert (got["id"], got["name"], got["product"], got["version"], got["linked"]) == ("outside-pack", "Outside Pack", "formwav", "2.3.4", False) + (src / "a.txt").write_text("two", encoding="utf-8") + assert client.get("/api/projects/outside-pack/files/package/a.txt").json()["text"] == "one" + + +def test_linked_folder_is_edited_in_place_and_delete_only_drops_the_link(client, home, tmp_path): + src = tmp_path / "linked-pack" + src.mkdir() + (src / "manifest.json").write_text(json.dumps({"id": "linked-pack", "name": "Linked", "product": "formmd"}), encoding="utf-8") + got = client.post("/api/projects", json={"path": str(src), "link": True}).json() + assert got["linked"] is True + assert got["package_prefix"] == "" + client.put("/api/projects/linked-pack/files/note.txt", json={"text": "in place"}) + assert (src / "note.txt").read_text(encoding="utf-8") == "in place" + gone = client.delete("/api/projects/linked-pack").json() + assert gone["removed"] == "link" + assert (src / "note.txt").read_text(encoding="utf-8") == "in place" + assert client.get("/api/projects").json()["projects"] == [] + + +def test_importing_a_folder_without_a_manifest_is_refused(client, tmp_path): + src = tmp_path / "bare" + src.mkdir() + res = client.post("/api/projects/import", json={"path": str(src)}) + assert res.status_code == 400 + assert res.json()["detail"] == "the folder has no manifest.json (at its root or in package/)" + + +def test_importing_a_folder_that_is_not_there_is_refused(client, tmp_path): + missing = str(tmp_path / "nowhere") + res = client.post("/api/projects/import", json={"path": missing}) + assert res.status_code == 404 + assert res.json()["detail"] == f"no such folder: {missing}" diff --git a/tests/workspace/test_settings_preview_library.py b/tests/workspace/test_settings_preview_library.py new file mode 100644 index 0000000..ad51678 --- /dev/null +++ b/tests/workspace/test_settings_preview_library.py @@ -0,0 +1,256 @@ +import io +import json +import zipfile + +import pytest + +from app.services import paths, settings +from app.services import window_key + + +def test_saved_settings_read_back_and_are_written_to_the_settings_file(client, home): + res = client.put("/api/settings", json={"theme": "light", "author": "Ada"}) + assert res.status_code == 200 + got = client.get("/api/settings").json() + assert (got["theme"], got["author"]) == ("light", "Ada") + on_disk = json.loads((home / "settings.json").read_text(encoding="utf-8")) + assert (on_disk["theme"], on_disk["author"]) == ("light", "Ada") + + +def test_settings_report_the_data_folder_in_use(client, home): + assert client.get("/api/settings").json()["home"] == str(home) + + +def test_saving_one_editor_setting_keeps_the_other_editor_settings(client): + before = client.get("/api/settings").json()["editor"] + client.put("/api/settings", json={"editor": {"font_size": 20}}) + after = client.get("/api/settings").json()["editor"] + assert after == {**before, "font_size": 20} + + +def test_a_setting_saved_as_null_goes_back_to_its_first_value(client): + first = client.get("/api/settings").json()["licence"] + client.put("/api/settings", json={"licence": "MIT"}) + assert client.get("/api/settings").json()["licence"] == "MIT" + client.put("/api/settings", json={"licence": None}) + assert client.get("/api/settings").json()["licence"] == first + + +def test_home_folder_cannot_be_changed_through_settings(client, home, tmp_path): + client.put("/api/settings", json={"home": str(tmp_path / "elsewhere")}) + assert client.get("/api/settings").json()["home"] == str(home) + assert not (tmp_path / "elsewhere").exists() + + +def test_settings_change_without_the_window_key_is_refused_and_nothing_changes(client, outsider): + before = client.get("/api/settings").json()["theme"] + res = outsider.put("/api/settings", json={"theme": "sand"}) + assert res.status_code == 403 + assert res.json()["detail"] == "Only the form.ext window can do this" + assert client.get("/api/settings").json()["theme"] == before + + +def test_agent_access_outside_the_three_choices_is_refused_and_not_saved(client): + before = client.get("/api/settings").json()["agent_access"] + res = client.put("/api/settings", json={"agent_access": "always"}) + assert res.status_code == 400 + assert res.json()["detail"] == "agent_access is ask, allowed or blocked" + assert client.get("/api/settings").json()["agent_access"] == before + + +def test_agent_access_saved_by_the_window_reads_back(client): + client.put("/api/settings", json={"agent_access": "blocked"}) + assert client.get("/api/settings").json()["agent_access"] == "blocked" + + +def test_agent_access_cannot_be_changed_by_a_caller_that_is_not_the_window(home): + before = settings.get()["agent_access"] + settings.update({"agent_access": "allowed", "theme": "light"}) + assert settings.get()["agent_access"] == before + assert settings.get()["theme"] == "light" + + +def test_unreadable_settings_file_falls_back_to_the_first_values(client, home): + first = client.get("/api/settings").json() + (home / "settings.json").write_text("{broken", encoding="utf-8") + assert client.get("/api/settings").json()["theme"] == first["theme"] + + +def test_new_project_manifest_takes_author_and_licence_from_settings(client): + client.put("/api/settings", json={"author": "Ada", "licence": "MIT"}) + made = client.post("/api/projects", json={"name": "Signed Work", "product": "formvis"}).json() + assert (made["manifest"]["author"], made["manifest"]["licence"]) == ("Ada", "MIT") + + +def test_settings_value_reads_a_nested_key_by_dotted_name(client): + client.put("/api/settings", json={"editor": {"tab_size": 8}}) + assert settings.value("editor.tab_size") == 8 + assert settings.value("editor.nothing", "fallback") == "fallback" + + +def test_data_folders_live_under_the_home_folder_named_by_the_environment(home): + assert paths.home() == home + assert paths.projects_dir() == home / "projects" + assert paths.trash_dir() == home / "trash" + assert paths.settings_file() == home / "settings.json" + assert paths.index_file() == home / "projects.json" + assert (home / "projects").is_dir() and (home / "trash").is_dir() + + +PREVIEW = "/api/preview/grain-tool/files/grain-tool/0.1.0" + + +@pytest.mark.parametrize("name,body,kind", [ + ("index.html", b"

hi

", "text/html; charset=utf-8"), + ("main.js", b"export const a = 1;\n", "text/javascript; charset=utf-8"), + ("style.css", b"p { color: red }\n", "text/css; charset=utf-8"), + ("data.json", b'{"a": 1}', "application/json"), + ("icon.svg", b"", "image/svg+xml"), + ("dot.png", b"\x89PNG\r\n\x1a\n\x00\x01", "image/png"), +]) +def test_preview_serves_a_package_file_byte_for_byte_with_the_content_type_of_its_kind(client, project, name, body, kind): + client.put(f"/api/projects/grain-tool/files/package/{name}?raw=1", content=body) + got = client.get(f"{PREVIEW}/{name}") + assert got.status_code == 200 + assert got.content == body + assert got.headers["content-type"] == kind + assert got.headers["x-content-type-options"] == "nosniff" + assert got.headers["cache-control"] == "no-store" + + +def test_preview_html_carries_a_content_security_policy_and_scripts_do_not(client, project): + client.put("/api/projects/grain-tool/files/package/index.html", json={"text": "

hi

"}) + client.put("/api/projects/grain-tool/files/package/main.js", json={"text": "1"}) + assert client.get(f"{PREVIEW}/index.html").headers.get("content-security-policy") + assert "content-security-policy" not in client.get(f"{PREVIEW}/main.js").headers + + +def test_preview_head_request_reports_the_file_length_without_a_body(client, project): + client.put("/api/projects/grain-tool/files/package/main.js", json={"text": "12345678"}) + got = client.head(f"{PREVIEW}/main.js") + assert got.status_code == 200 + assert got.headers["content-length"] == "8" + assert got.content == b"" + + +def test_preview_shows_the_latest_saved_content_of_a_file(client, project): + client.put("/api/projects/grain-tool/files/package/main.js", json={"text": "old"}) + assert client.get(f"{PREVIEW}/main.js").content == b"old" + client.put("/api/projects/grain-tool/files/package/main.js", json={"text": "newer"}) + assert client.get(f"{PREVIEW}/main.js").content == b"newer" + + +def test_preview_does_not_serve_files_outside_the_package_folder(client, project): + client.put("/api/projects/grain-tool/files/notes.md", json={"text": "private notes"}) + got = client.get(f"{PREVIEW}/..%2Fnotes.md") + assert got.status_code == 404 + assert b"private notes" not in got.content + + +def test_preview_does_not_serve_a_file_kind_it_has_no_content_type_for(client, project): + client.put("/api/projects/grain-tool/files/package/tool.py", json={"text": "print(1)"}) + got = client.get(f"{PREVIEW}/tool.py") + assert got.status_code == 404 + assert b"print" not in got.content + + +def test_preview_refuses_a_missing_file_an_old_version_and_an_unknown_project(client, project): + client.put("/api/projects/grain-tool/files/package/main.js", json={"text": "1"}) + assert client.get(f"{PREVIEW}/missing.js").status_code == 404 + assert client.get("/api/preview/grain-tool/files/grain-tool/9.9.9/main.js").status_code == 404 + assert client.get("/api/preview/grain-tool/files/other-id/0.1.0/main.js").status_code == 404 + gone = client.get("/api/preview/never-made/files/never-made/0.1.0/main.js") + assert gone.status_code == 404 + assert gone.content == b"" + + +def test_preview_record_names_the_project_its_product_and_its_manifest(client, project): + got = client.get("/api/preview/grain-tool").json() + assert got["project"] == "grain-tool" + assert got["product"] == "formvis" + assert got["manifest"] == project["manifest"] + assert got["record"]["id"] == "grain-tool" + assert got["record"]["version"] == "0.1.0" + + +def test_preview_record_for_another_app_says_the_extension_is_not_made_for_it(client, project): + record = client.get("/api/preview/grain-tool?product=formcut").json()["record"] + assert record["state"] == "refused" + assert "formvis" in record["reason"] + + +def test_preview_record_of_an_unknown_project_is_refused(client): + res = client.get("/api/preview/never-made") + assert res.status_code == 404 + assert res.json()["detail"] == "no such project: never-made" + + +def test_preview_fetch_refuses_addresses_that_are_not_https(client): + res = client.post("/api/preview/fetch", json={"url": "http://example.invalid/x"}) + assert res.status_code == 400 + assert res.json()["detail"] == "only https:// addresses" + + +def test_preview_fetch_refuses_this_computer(client): + res = client.post("/api/preview/fetch", json={"url": "https://127.0.0.1/x"}) + assert res.status_code == 403 + assert res.json()["detail"] == "127.0.0.1 is on this computer or the local network" + + +def test_inspecting_an_upload_that_is_not_a_zip_reports_that_and_its_size(client): + res = client.post("/api/library/inspect?name=thing.formpkg", content=b"plain words, no archive", headers={"content-type": "application/octet-stream"}) + body = res.json() + report = body.get("report", body) + assert report["bytes"] == len(b"plain words, no archive") + assert any(e["message"].startswith("this is not a zip file") for e in report["errors"]) + + +def test_inspecting_an_empty_upload_is_refused(client): + res = client.post("/api/library/inspect", content=b"", headers={"content-type": "application/octet-stream"}) + assert res.status_code == 400 + assert res.json()["detail"] == "the upload is empty" + + +def test_inspecting_a_path_that_is_not_given_or_not_there_is_refused(client, tmp_path): + empty = client.post("/api/library/inspect", json={"path": ""}) + assert (empty.status_code, empty.json()["detail"]) == (400, "give the path of a .formpkg file") + missing = str(tmp_path / "none.formpkg") + gone = client.post("/api/library/inspect", json={"path": missing}) + assert (gone.status_code, gone.json()["detail"]) == (404, f"no such file: {missing}") + + +def test_importing_a_file_that_is_not_a_package_is_refused_and_makes_no_project(client): + res = client.post("/api/library/import?name=thing.formpkg", content=b"plain words, no archive", headers={"content-type": "application/octet-stream"}) + assert res.status_code >= 400 + assert client.get("/api/projects").json()["projects"] == [] + + +def test_importing_a_zip_whose_entry_climbs_out_is_refused_and_nothing_is_written_outside(client, home, tmp_path): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as z: + z.writestr("manifest.json", json.dumps({"format": "formai-package", "format_version": 1, "id": "climber", "name": "Climber", "product": "formvis", "version": "0.1.0"})) + z.writestr("../../climbed.txt", "out") + res = client.post("/api/library/import?name=climber.formpkg", content=buf.getvalue(), headers={"content-type": "application/octet-stream"}) + assert res.status_code >= 400 + assert client.get("/api/projects").json()["projects"] == [] + assert not (home / "climbed.txt").exists() + assert not (tmp_path / "climbed.txt").exists() + assert not (home.parent / "climbed.txt").exists() + + +def test_inspecting_a_build_of_an_unknown_project_is_refused(client): + res = client.get("/api/library/builds/never-made/" + "0" * 64) + assert res.status_code == 404 + assert "never-made" in res.json()["detail"] + + +def test_library_change_without_the_window_key_is_refused(outsider): + res = outsider.post("/api/library/import?name=a.formpkg", content=b"x", headers={"content-type": "application/octet-stream"}) + assert res.status_code == 403 + assert res.json()["detail"] == window_key.REFUSED + + +def test_run_in_app_status_of_an_unknown_project_is_refused_with_its_id(client): + res = client.get("/api/runapp/projects/never-made") + assert res.status_code == 404 + assert res.json()["detail"] == "no such project: never-made" From b8a6700e030cb22f85983af1382188fc1cfdf3fe Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Mon, 23 Nov 2026 17:06:18 -0500 Subject: [PATCH 14/15] chore(release): v0.11.0 The version moves to 0.11.0 in backend/app/__init__.py, frontend/package.json, frontend/package-lock.json, frontend/src/shell/version.ts, the demo engine's health answer, src-tauri (Cargo.toml, Cargo.lock, tauri.conf.json) and the README badge, each by hand. CHANGELOG.md describes v0.11.0. Ran: ./formext test unit (265 passed) and ./formext test engine (597 passed, 1 expected failure). Not run: the browser demo was not rebuilt, the desktop shell, macOS and Windows. --- CHANGELOG.md | 10 ++++++++++ README.md | 2 +- backend/app/__init__.py | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- frontend/src/demo/engine/router.ts | 2 +- frontend/src/shell/version.ts | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 10 files changed, 20 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10f11e5..03936b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## v0.11.0 · 2026-11-23 + +form.ext has a full test suite. + +- `./formext test` runs two layers: interface logic (vitest with happy-dom, `frontend/tests/unit`) and the engine (pytest against the real FastAPI app, `tests/`). `./formext test unit` or `./formext test engine` runs one. `docs/TESTING.md` says how to run them and what a test must do to be accepted. +- 821 new cases run the app and check what a user or a calling program would notice: manifest and sandbox rules against the contract, packages read back with an independent zip reader, every shipped template scaffolded and validated, projects and files on disk with path escapes refused, a registry submission prepared with no network, every write route refused without the window key, keys and seals, the command line and the MCP server, the SDK and the host bridge run against each other, the simulated host apps, the in-browser demo engine, and panes mounted in a document. With the 41 cases that were already here, 862 pass. +- No app code changed. Where a test showed the app to be wrong, the test stays as a strict expected failure whose reason starts with `DEFECT:`. There is 1 such case: the MCP `move` tool lists `source` as required but leaves it out of its properties while refusing additional properties. `git grep -n "DEFECT:" tests frontend/tests` lists it. +- CI runs the tests on every pull request in one job, `test`, on Linux. +- Not run for this version: the browser demo in `demo/` was not rebuilt, so its built script still says 0.10.0. The desktop shell has no tests. The tests did not run on macOS or Windows. + ## v0.10.0 · 2026-11-20 form.ext understands the Form family's shared style names, its browser demo is rebuilt, and the README says it is released. diff --git a/README.md b/README.md index 0f9bb41..9b4290d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@

- version 0.10.0 + version 0.11.0 Python FastAPI engine TypeScript Tauri 2 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 61fb31c..ae6db5f 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.10.0" +__version__ = "0.11.0" diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 97d1126..f5a624a 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formext", - "version": "0.10.0", + "version": "0.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formext", - "version": "0.10.0", + "version": "0.11.0", "license": "GPL-3.0-only", "dependencies": { "@codemirror/autocomplete": "6.20.4", diff --git a/frontend/package.json b/frontend/package.json index d23a0af..d49817f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formext", "private": true, - "version": "0.10.0", + "version": "0.11.0", "description": "form.ext: the Form family's extension studio", "license": "GPL-3.0-only", "type": "module", diff --git a/frontend/src/demo/engine/router.ts b/frontend/src/demo/engine/router.ts index 7cd850e..e791b31 100644 --- a/frontend/src/demo/engine/router.ts +++ b/frontend/src/demo/engine/router.ts @@ -76,7 +76,7 @@ function decodeFiles(rawFiles: Json): Record { return out; } -on('GET', '/api/health', () => ({ ok: true, app: 'formext', version: '0.10.0 in this page', api: '1', pid: 0, python: null, frozen: false, home: DATA, contract: 'bundled', uptime: Math.round(performance.now() / 100) / 10, live_clients: 0, routers: ['health', 'settings', 'projects', 'live', 'library', 'package', 'preview', 'publish', 'runapp', 'templates', 'validate'], router_errors: {}, frontend: 'demo', demo: true })); +on('GET', '/api/health', () => ({ ok: true, app: 'formext', version: '0.11.0 in this page', api: '1', pid: 0, python: null, frozen: false, home: DATA, contract: 'bundled', uptime: Math.round(performance.now() / 100) / 10, live_clients: 0, routers: ['health', 'settings', 'projects', 'live', 'library', 'package', 'preview', 'publish', 'runapp', 'templates', 'validate'], router_errors: {}, frontend: 'demo', demo: true })); on('GET', '/api/settings', () => ({ ...settings.get(), home: DATA })); on('PUT', '/api/settings', (_m, r) => { const patch = { ...json(r) }; diff --git a/frontend/src/shell/version.ts b/frontend/src/shell/version.ts index 699451e..526f948 100644 --- a/frontend/src/shell/version.ts +++ b/frontend/src/shell/version.ts @@ -1 +1 @@ -export const VERSION = '0.10.0'; +export const VERSION = '0.11.0'; diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f1b9415..a6726c3 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1077,7 +1077,7 @@ dependencies = [ [[package]] name = "formext" -version = "0.10.0" +version = "0.11.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index de2e168..edad32c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formext" -version = "0.10.0" +version = "0.11.0" description = "form.ext desktop shell" authors = ["NodeAgentc, Inc."] license = "GPL-3.0-only" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index eb48eb5..2d34144 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "form.ext", "mainBinaryName": "formext", - "version": "0.10.0", + "version": "0.11.0", "identifier": "ai.nodemode.formext", "build": { "frontendDist": "../frontend/dist", From fc59e7f8e1bcd6af10d8c0c09462cd5cba66ecc2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Tue, 24 Nov 2026 17:35:06 -0500 Subject: [PATCH 15/15] fix(tests): the gh-not-installed test hides a gh that is on the system path (0.11.0) The test removed FORMEXT_GH_BIN and emptied the fixed system folders, but the app also looks for gh on PATH, and the CI runner has one in /usr/bin, so readiness answered that gh is there. For the request the test now points PATH at a folder that holds only git. Ran: ./formext test engine with a gh program in /usr/bin and without one, 597 passed and 1 expected failure both times. --- tests/publish/test_pull_request.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/publish/test_pull_request.py b/tests/publish/test_pull_request.py index c133543..3ee0f56 100644 --- a/tests/publish/test_pull_request.py +++ b/tests/publish/test_pull_request.py @@ -1,4 +1,5 @@ import json +import shutil import subprocess from pathlib import Path @@ -18,10 +19,12 @@ def test_readiness_asks_for_a_sign_in_when_gh_is_not_signed_in(client, make_proj assert out["repo"] == "nodemode-dev/form.ext-registry" -def test_readiness_asks_for_gh_when_it_is_not_installed(client, make_project, monkeypatch): +def test_readiness_asks_for_gh_when_it_is_not_installed(client, make_project, monkeypatch, tmp_path): monkeypatch.delenv("FORMEXT_GH_BIN") monkeypatch.setattr(registry_pr, "GH_SYSTEM", ()) p = make_project() + (tmp_path / "git").symlink_to(shutil.which("git")) + monkeypatch.setenv("PATH", str(tmp_path)) out = client.get(f"/api/publish/{p['id']}/registry/pull-request").json() assert out["ready"] is False and out["gh"] is False assert [n["what"] for n in out["needs"]] == ["gh"]