Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(vscode): visualization panels from the shared UI library (#649)
Raghav Chamadiyaf5a53cd6dacb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f9086e90b..c316d25a4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -127,6 +127,12 @@ jobs:- name: Build (asserts bundle size budget)run: npm run build --workspace packages/vscode+ - name: Build webviews (reports chunk sizes)+ run: npm run build:webview --workspace packages/vscode++ - name: Webview unit tests+ run: npm run test:webview --workspace packages/vscode+- name: Smoke test under a virtual displayrun: xvfb-run -a npm run test --workspace packages/vscodediff --git a/package-lock.json b/package-lock.jsonindex 3ae9523ff..17db4f884 100644--- a/package-lock.json+++ b/package-lock.json@@ -759,7 +759,6 @@"os": ["aix"],- "peer": true,"engines": {"node": ">=18"}@@ -777,7 +776,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -795,7 +793,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -813,7 +810,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -831,7 +827,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">=18"}@@ -849,7 +844,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">=18"}@@ -867,7 +861,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">=18"}@@ -885,7 +878,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">=18"}@@ -903,7 +895,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -921,7 +912,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -939,7 +929,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -957,7 +946,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -975,7 +963,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -993,7 +980,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1011,7 +997,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1029,7 +1014,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1047,7 +1031,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -1065,7 +1048,6 @@"os": ["netbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1083,7 +1065,6 @@"os": ["netbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1101,7 +1082,6 @@"os": ["openbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1119,7 +1099,6 @@"os": ["openbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -1137,7 +1116,6 @@"os": ["openharmony"],- "peer": true,"engines": {"node": ">=18"}@@ -1155,7 +1133,6 @@"os": ["sunos"],- "peer": true,"engines": {"node": ">=18"}@@ -1173,7 +1150,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -1191,7 +1167,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -1209,7 +1184,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -3737,8 +3711,7 @@"optional": true,"os": ["android"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-android-arm64": {"version": "4.60.2",@@ -3752,8 +3725,7 @@"optional": true,"os": ["android"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-darwin-arm64": {"version": "4.60.2",@@ -3767,8 +3739,7 @@"optional": true,"os": ["darwin"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-darwin-x64": {"version": "4.60.2",@@ -3782,8 +3753,7 @@"optional": true,"os": ["darwin"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-freebsd-arm64": {"version": "4.60.2",@@ -3797,8 +3767,7 @@"optional": true,"os": ["freebsd"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-freebsd-x64": {"version": "4.60.2",@@ -3812,8 +3781,7 @@"optional": true,"os": ["freebsd"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm-gnueabihf": {"version": "4.60.2",@@ -3827,8 +3795,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm-musleabihf": {"version": "4.60.2",@@ -3842,8 +3809,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm64-gnu": {"version": "4.60.2",@@ -3857,8 +3823,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm64-musl": {"version": "4.60.2",@@ -3872,8 +3837,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-loong64-gnu": {"version": "4.60.2",@@ -3887,8 +3851,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-loong64-musl": {"version": "4.60.2",@@ -3902,8 +3865,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-ppc64-gnu": {"version": "4.60.2",@@ -3917,8 +3879,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-ppc64-musl": {"version": "4.60.2",@@ -3932,8 +3893,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-riscv64-gnu": {"version": "4.60.2",@@ -3947,8 +3907,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-riscv64-musl": {"version": "4.60.2",@@ -3962,8 +3921,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-s390x-gnu": {"version": "4.60.2",@@ -3977,8 +3935,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-x64-gnu": {"version": "4.60.2",@@ -3992,8 +3949,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-x64-musl": {"version": "4.60.2",@@ -4007,8 +3963,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-openbsd-x64": {"version": "4.60.2",@@ -4022,8 +3977,7 @@"optional": true,"os": ["openbsd"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-openharmony-arm64": {"version": "4.60.2",@@ -4037,8 +3991,7 @@"optional": true,"os": ["openharmony"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-arm64-msvc": {"version": "4.60.2",@@ -4052,8 +4005,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-ia32-msvc": {"version": "4.60.2",@@ -4067,8 +4019,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-x64-gnu": {"version": "4.60.2",@@ -4082,8 +4033,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-x64-msvc": {"version": "4.60.2",@@ -4097,8 +4047,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rtsao/scc": {"version": "1.1.0",@@ -4735,6 +4684,285 @@"tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1"}},+ "node_modules/@tailwindcss/vite": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.2.tgz",+ "integrity": "sha512-eHpMeX4JXfVNJDEcsouTeCBubJBTcTLigeaw/NTUW6PB5ATKKXdyonnXgTBX2VuRbjz1hjfz6C5XAhr52ImQXA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@tailwindcss/node": "4.3.2",+ "@tailwindcss/oxide": "4.3.2",+ "tailwindcss": "4.3.2"+ },+ "peerDependencies": {+ "vite": "^5.2.0 || ^6 || ^7 || ^8"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/node": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.2.tgz",+ "integrity": "sha512-yWP/sqEcBLaD8JuA6zNwxoYKr75qxTioYwlRwekj5Jr/I5GXnoJfjetH/psLUIv74cYTH2lBUEzBkinthoYcBg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/remapping": "^2.3.5",+ "enhanced-resolve": "5.21.6",+ "jiti": "^2.7.0",+ "lightningcss": "1.32.0",+ "magic-string": "^0.30.21",+ "source-map-js": "^1.2.1",+ "tailwindcss": "4.3.2"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.2.tgz",+ "integrity": "sha512-z8ZgnzX8gdNoWLBLqBPoh/sjnxkwvf9ZuWjnO0l0yIzbLa5/9S+eC5QxGZKRobVHIC3/1BoMWjHblqWjcgFgag==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 20"+ },+ "optionalDependencies": {+ "@tailwindcss/oxide-android-arm64": "4.3.2",+ "@tailwindcss/oxide-darwin-arm64": "4.3.2",+ "@tailwindcss/oxide-darwin-x64": "4.3.2",+ "@tailwindcss/oxide-freebsd-x64": "4.3.2",+ "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.2",+ "@tailwindcss/oxide-linux-arm64-gnu": "4.3.2",+ "@tailwindcss/oxide-linux-arm64-musl": "4.3.2",+ "@tailwindcss/oxide-linux-x64-gnu": "4.3.2",+ "@tailwindcss/oxide-linux-x64-musl": "4.3.2",+ "@tailwindcss/oxide-wasm32-wasi": "4.3.2",+ "@tailwindcss/oxide-win32-arm64-msvc": "4.3.2",+ "@tailwindcss/oxide-win32-x64-msvc": "4.3.2"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-android-arm64": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.2.tgz",+ "integrity": "sha512-WHxqIuHpvZ5VtdX6GTl1Ik/Vp2YuN42Et+0CdeaVd/frQ9jAvGmvR8vLT+jk3e8/Q3x8kECB9+R17pgpp2BulA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-darwin-arm64": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.2.tgz",+ "integrity": "sha512-GZypeUY/IDJW3877KeM+O67vbXr3MBnbtEL4aYhNErv/JWZhye2vGSWWG9tB6iiqR2MqRNkY8IOUy4NdSZV26w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-darwin-x64": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.2.tgz",+ "integrity": "sha512-UIIzmefR6KO1sDU7MzRqAxC8iBpft/VhkGjTjnhoS6k7Z3rQ9wEgA1ODSiyH/tcSYssulNm4Ci3hOeK1jH7ccQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-freebsd-x64": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.2.tgz",+ "integrity": "sha512-GN+uAmcI6DNspnCDwtOAZrTz6oukJnp337qZvxqCGLd3BHBzJpO0ZbTLRvJNdztOeAmTzewewGIMPb0tk2R4WA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.2.tgz",+ "integrity": "sha512-4ABn7qSbdHRwTiDiuWNegCyb5+2FJ4vKIKc3DmKrvAFw7MU1Lm11dIkTPwUaFdTzc7IsOpDbqBrlh0x6y36U/w==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-arm64-gnu": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.2.tgz",+ "integrity": "sha512-wDgEIGwoM8w8pufh9LVt1PahDgNdKXrLC2qfAnV3vAmococ9RWbxeAw4pxPttd/TsJfwjyLf90Dg1y9y8I6Emw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-arm64-musl": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.2.tgz",+ "integrity": "sha512-J5Nuk0uZQIiMTJj3LEx4sAA9tMFUoXQZFv1J6An+QGYe53HKRJuFDi0rpq/tuouCZeAbOBY3kQ6g8qeD4TUjtA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-x64-gnu": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.2.tgz",+ "integrity": "sha512-kqCZpSKOBEJO4mz7OqWoofBZeXTAwaVGPj0ErAj7CojmhKpWVWVOnrt9dE8odoIraZq4oj3ausM37kXi+Tow8w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-x64-musl": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.2.tgz",+ "integrity": "sha512-cixpqbh2toJDmkuCRI68nXA8ZxNmdK9Y+9v5h3MC3ZQKy/0BO8AWzlkWyRM7JAFSGBlfig4YVTPsK6MVgqz1uw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-wasm32-wasi": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.2.tgz",+ "integrity": "sha512-4ec2Z/LOmRsAgU23CS4xeJfcJlmRg94A/XrbGRCF1gyU/zdDfRLYDVsS+ynSZCmGNxQ1jQriQOKMQeQxBA3Isw==",+ "bundleDependencies": [+ "@napi-rs/wasm-runtime",+ "@emnapi/core",+ "@emnapi/runtime",+ "@tybys/wasm-util",+ "@emnapi/wasi-threads",+ "tslib"+ ],+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "^1.11.1",+ "@emnapi/runtime": "^1.11.1",+ "@emnapi/wasi-threads": "^1.2.2",+ "@napi-rs/wasm-runtime": "^1.1.4",+ "@tybys/wasm-util": "^0.10.2",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-win32-arm64-msvc": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.2.tgz",+ "integrity": "sha512-Zyr/M0+XcYZu3bZrUytc7TXvrk0ftWfl8gN2MwekNDzhqhKRUucMPSeOzM0o0wH5AWOU49BsKRrfKxI2atCPMQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-win32-x64-msvc": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.2.tgz",+ "integrity": "sha512-QI9BO7KlNZsp2GuO0jwAAj5jCDABOKXRkCk2XuKTSaNEFSdfzqswYVTtCHBNKHLsqyjFyFkqlDiwkNbTYSssMQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@tailwindcss/vite/node_modules/tailwindcss": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.2.tgz",+ "integrity": "sha512-WtctNNSH8A9jlMIqxzuYumOHU5uGZyRv0Q5svQl+oEPy5w84YpBxdb7MdqyiSPQge5jTJ6zFQLq0PFygdccSBA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@tanstack/react-virtual": {"version": "3.14.3","resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.3.tgz",@@ -7198,6 +7426,16 @@"node": ">=14.14.0"}},+ "node_modules/cac": {+ "version": "6.7.14",+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/call-bind": {"version": "1.0.8","resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",@@ -7368,6 +7606,16 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/check-error": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ }+ },"node_modules/cheerio": {"version": "1.2.0","resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.2.0.tgz",@@ -8435,6 +8683,16 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/deep-eql": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/deep-extend": {"version": "0.6.0","resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",@@ -8812,14 +9070,14 @@}},"node_modules/enhanced-resolve": {- "version": "5.20.1",- "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.20.1.tgz",- "integrity": "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==",+ "version": "5.21.6",+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz",+ "integrity": "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ==","dev": true,"license": "MIT","dependencies": {"graceful-fs": "^4.2.4",- "tapable": "^2.3.0"+ "tapable": "^2.3.3"},"engines": {"node": ">=10.13.0"@@ -9085,7 +9343,6 @@"dev": true,"hasInstallScript": true,"license": "MIT",- "peer": true,"bin": {"esbuild": "bin/esbuild"},@@ -11595,9 +11852,9 @@}},"node_modules/jiti": {- "version": "2.6.1",- "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz",- "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==",+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==","dev": true,"license": "MIT","bin": {@@ -12330,6 +12587,13 @@"loose-envify": "cli.js"}},+ "node_modules/loupe": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/lru-cache": {"version": "5.1.1","resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",@@ -14823,6 +15087,16 @@"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==","license": "MIT"},+ "node_modules/pathval": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14.16"+ }+ },"node_modules/pend": {"version": "1.2.0","resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",@@ -15921,7 +16195,6 @@"integrity": "sha512-J9qZyW++QK/09NyN/zeO0dG/1GdGfyp9lV8ajHnRVLfo/uFsbji5mHnDgn/qYdUHyCkM2N+8VyspgZclfAh0eQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/estree": "1.0.8"},@@ -16921,6 +17194,26 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/strip-literal": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",+ "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^9.0.1"+ },+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/strip-literal/node_modules/js-tokens": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",+ "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/structured-source": {"version": "4.0.0","resolved": "https://registry.npmjs.org/structured-source/-/structured-source-4.0.0.tgz",@@ -17113,9 +17406,9 @@"license": "MIT"},"node_modules/tapable": {- "version": "2.3.0",- "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz",- "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==",+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz",+ "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==","dev": true,"license": "MIT","engines": {@@ -17290,6 +17583,16 @@"url": "https://github.com/sponsors/SuperchupuDev"}},+ "node_modules/tinypool": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.0.0 || >=20.0.0"+ }+ },"node_modules/tinyrainbow": {"version": "3.1.0","resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",@@ -17300,6 +17603,16 @@"node": ">=14.0.0"}},+ "node_modules/tinyspy": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",+ "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },"node_modules/tldts": {"version": "6.1.86","resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",@@ -18042,7 +18355,6 @@"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",@@ -18112,6 +18424,36 @@}}},+ "node_modules/vite-node": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",+ "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cac": "^6.7.14",+ "debug": "^4.4.1",+ "es-module-lexer": "^1.7.0",+ "pathe": "^2.0.3",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"+ },+ "bin": {+ "vite-node": "vite-node.mjs"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/vite-node/node_modules/es-module-lexer": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/vitest": {"version": "4.1.5","resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.5.tgz",@@ -19140,14 +19482,27 @@"@repowise-dev/api-client": "*","@repowise-dev/types": "*","@repowise-dev/ui": "*",+ "@tailwindcss/typography": "^0.5.15",+ "@tailwindcss/vite": "^4.0.0",+ "@testing-library/react": "^16.1.0","@types/mocha": "^10.0.0","@types/node": "^20",+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0","@types/vscode": "~1.101.0",+ "@vitejs/plugin-react": "^5.0.0","@vscode/test-cli": "^0.0.10","@vscode/test-electron": "^3.0.0","@vscode/vsce": "^3.0.0","esbuild": "^0.28.0",- "typescript": "^5.7.2"+ "jsdom": "^26.0.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "swr": "^2.2.5",+ "tailwindcss": "^4.0.0",+ "typescript": "^5.7.2",+ "vite": "^7.0.0",+ "vitest": "^3.0.0"},"engines": {"node": ">=20.0.0",@@ -19596,6 +19951,13 @@"node": ">=18"}},+ "packages/vscode/node_modules/@rolldown/pluginutils": {+ "version": "1.0.0-rc.3",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",+ "integrity": "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==",+ "dev": true,+ "license": "MIT"+ },"packages/vscode/node_modules/@types/node": {"version": "20.19.43","resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",@@ -19606,6 +19968,132 @@"undici-types": "~6.21.0"}},+ "packages/vscode/node_modules/@vitejs/plugin-react": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz",+ "integrity": "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.29.0",+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",+ "@rolldown/pluginutils": "1.0.0-rc.3",+ "@types/babel__core": "^7.20.5",+ "react-refresh": "^0.18.0"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "peerDependencies": {+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "packages/vscode/node_modules/@vitest/expect": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.6.tgz",+ "integrity": "sha512-1+7q9BtaKzEmO+fmNT3kYvoNn5Y71XWAx2Q5HRim4tTVRQVRv4uJFAQ5FbK0OPUeNP/WmVCpxYxoJdvuHVjzBQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/chai": "^5.2.2",+ "@vitest/spy": "3.2.6",+ "@vitest/utils": "3.2.6",+ "chai": "^5.2.0",+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "packages/vscode/node_modules/@vitest/pretty-format": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.6.tgz",+ "integrity": "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "packages/vscode/node_modules/@vitest/runner": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.6.tgz",+ "integrity": "sha512-HYcoSj1w5tcgUnzoF0HcyaAQjpA1gj9ftUJ7iSJSuipc02jW9gKkigwZbjFldAfYHA1fa8UZVRftdMY5msWM9Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "3.2.6",+ "pathe": "^2.0.3",+ "strip-literal": "^3.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "packages/vscode/node_modules/@vitest/snapshot": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.6.tgz",+ "integrity": "sha512-H+ZjNTWGpObenh0YnlBctAPnJSI20P81PL8BPzWpx54YXLLTm8hEsWawtcYLMrwvpK48hGxLLbCS+1KRXhsKhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "3.2.6",+ "magic-string": "^0.30.17",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "packages/vscode/node_modules/@vitest/spy": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.6.tgz",+ "integrity": "sha512-oq6BbH68WzcWmwtBrU9nqLeaXTR4XwJF7FSLkKEZo4i6eoXcrxjcwSuTvWBIRUTC6VC72nXYunzqgZA+IKdtxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyspy": "^4.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "packages/vscode/node_modules/@vitest/utils": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.6.tgz",+ "integrity": "sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "3.2.6",+ "loupe": "^3.1.4",+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "packages/vscode/node_modules/chai": {+ "version": "5.3.3",+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "assertion-error": "^2.0.1",+ "check-error": "^2.1.1",+ "deep-eql": "^5.0.1",+ "loupe": "^3.1.0",+ "pathval": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"packages/vscode/node_modules/esbuild": {"version": "0.28.1","resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",@@ -19648,6 +20136,187 @@"@esbuild/win32-x64": "0.28.1"}},+ "packages/vscode/node_modules/jsdom": {+ "version": "26.1.0",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",+ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cssstyle": "^4.2.1",+ "data-urls": "^5.0.0",+ "decimal.js": "^10.5.0",+ "html-encoding-sniffer": "^4.0.0",+ "http-proxy-agent": "^7.0.2",+ "https-proxy-agent": "^7.0.6",+ "is-potential-custom-element-name": "^1.0.1",+ "nwsapi": "^2.2.16",+ "parse5": "^7.2.1",+ "rrweb-cssom": "^0.8.0",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^5.1.1",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^7.0.0",+ "whatwg-encoding": "^3.1.1",+ "whatwg-mimetype": "^4.0.0",+ "whatwg-url": "^14.1.1",+ "ws": "^8.18.0",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "packages/vscode/node_modules/react-refresh": {+ "version": "0.18.0",+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",+ "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "packages/vscode/node_modules/rrweb-cssom": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",+ "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",+ "dev": true,+ "license": "MIT"+ },+ "packages/vscode/node_modules/std-env": {+ "version": "3.10.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",+ "dev": true,+ "license": "MIT"+ },+ "packages/vscode/node_modules/tinyexec": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",+ "dev": true,+ "license": "MIT"+ },+ "packages/vscode/node_modules/tinyrainbow": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",+ "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "packages/vscode/node_modules/vitest": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.6.tgz",+ "integrity": "sha512-xejya+bT/j/+R/AGa1XOfRxLmNUlLtlwjRsFUILF+xHfzElmGcmFydy2gqqIrd62ptIEfwVMofd19uNWD9L7Nw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/chai": "^5.2.2",+ "@vitest/expect": "3.2.6",+ "@vitest/mocker": "3.2.6",+ "@vitest/pretty-format": "^3.2.6",+ "@vitest/runner": "3.2.6",+ "@vitest/snapshot": "3.2.6",+ "@vitest/spy": "3.2.6",+ "@vitest/utils": "3.2.6",+ "chai": "^5.2.0",+ "debug": "^4.4.1",+ "expect-type": "^1.2.1",+ "magic-string": "^0.30.17",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.2",+ "std-env": "^3.9.0",+ "tinybench": "^2.9.0",+ "tinyexec": "^0.3.2",+ "tinyglobby": "^0.2.14",+ "tinypool": "^1.1.1",+ "tinyrainbow": "^2.0.0",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",+ "vite-node": "3.2.4",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@types/debug": "^4.1.12",+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",+ "@vitest/browser": "3.2.6",+ "@vitest/ui": "3.2.6",+ "happy-dom": "*",+ "jsdom": "*"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@types/debug": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ }+ }+ },+ "packages/vscode/node_modules/vitest/node_modules/@vitest/mocker": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.6.tgz",+ "integrity": "sha512-EZOrpDbkKotFAP7wPAQV1UIyoGOk4oX7ynWhBhLB7v+meMHbQhU16oPpIYGTTe4oFlhpryGpgpcZP/sin3hYuw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "3.2.6",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.17"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },"packages/web": {"name": "repowise-web","version": "0.3.0",diff --git a/packages/ui/src/c4/hooks/use-architecture-layout.ts b/packages/ui/src/c4/hooks/use-architecture-layout.tsindex 8d1dade58..0ebb70b13 100644--- a/packages/ui/src/c4/hooks/use-architecture-layout.ts+++ b/packages/ui/src/c4/hooks/use-architecture-layout.ts@@ -22,7 +22,6 @@ import {type ContainerAtom,type PortalSpec,} from "../layout/two-stage-layout";-import { THEME, edgeColor } from "../theme/theme-variables";export interface ArchitectureLayoutResult {nodes: Node[];diff --git a/packages/ui/src/c4/panels/ArchNodeInfo.tsx b/packages/ui/src/c4/panels/ArchNodeInfo.tsxindex 8ccb2797b..87f7eb73e 100644--- a/packages/ui/src/c4/panels/ArchNodeInfo.tsx+++ b/packages/ui/src/c4/panels/ArchNodeInfo.tsx@@ -199,12 +199,7 @@ export function ArchNodeInfo(props: ArchNodeInfoProps) {</Section>)}- {props.health && (- <HealthSection- health={props.health}- node={node}- />- )}+ {props.health && <HealthSection health={props.health} />}<OwnershipSectionprimaryOwner={node.primary_owner}@@ -319,13 +314,7 @@ function HeaderSection({);}-function HealthSection({- health,- node,-}: {- health: ArchNodeHealth;- node: { primary_owner: string | null; bus_factor: number | null };-}) {+function HealthSection({ health }: { health: ArchNodeHealth }) {return (<Section title="Health"><div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>diff --git a/packages/ui/src/c4/panels/NodeTypeCategoryFilters.tsx b/packages/ui/src/c4/panels/NodeTypeCategoryFilters.tsxindex 8d6d92c19..6d928d4c9 100644--- a/packages/ui/src/c4/panels/NodeTypeCategoryFilters.tsx+++ b/packages/ui/src/c4/panels/NodeTypeCategoryFilters.tsx@@ -25,7 +25,6 @@ const CATEGORY_ICON_KIND: Record<string, string> = {export function NodeTypeCategoryFilters() {const nodeTypeFilters = useArchitectureStore((s) => s.nodeTypeFilters);- const setNodeTypeFilter = useArchitectureStore((s) => s.setNodeTypeFilter);const handleToggle = useCallback((category: string) => {diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex a66fc10b5..7ed243b2b 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -1139,6 +1139,7 @@ export function GraphFlow(props: GraphFlowProps) {}}onFitView={handleFitView}showPathFinder={showPathFinder}+ pathFinderAvailable={Boolean(renderPathFinder)}onTogglePathFinder={() => {// Path finder and flows share the same overlay slot — opening// one always closes the other.diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsxindex 0c501a9cd..c6c058415 100644--- a/packages/ui/src/graph/graph-toolbar.tsx+++ b/packages/ui/src/graph/graph-toolbar.tsx@@ -80,6 +80,8 @@ interface GraphToolbarProps {onFitView: () => void;showPathFinder: boolean;onTogglePathFinder: () => void;+ /** Hosts without a path-finder implementation hide the toggle entirely. */+ pathFinderAvailable?: boolean;showFlows: boolean;onToggleFlows: () => void;searchQuery: string;@@ -141,6 +143,7 @@ export const GraphToolbar = memo(function GraphToolbar({onFitView,showPathFinder,onTogglePathFinder,+ pathFinderAvailable = true,showFlows,onToggleFlows,searchQuery,@@ -333,7 +336,7 @@ export const GraphToolbar = memo(function GraphToolbar({</Button>{/* Path finder / execution flows operate on file-level nodes anddon't apply to the community constellation — hidden there. */}- {!isConstellation && (+ {!isConstellation && pathFinderAvailable && (<Buttonsize="sm"variant="ghost"diff --git a/packages/vscode/.vscodeignore b/packages/vscode/.vscodeignoreindex 40849edc7..db7c022a0 100644--- a/packages/vscode/.vscodeignore+++ b/packages/vscode/.vscodeignore@@ -3,6 +3,7 @@.vscode-test.mjsout-test/**src/**+webview/**node_modules/**tsconfig.jsontsconfig.test.jsondiff --git a/packages/vscode/package.json b/packages/vscode/package.jsonindex bf15e8e9b..af2c56561 100644--- a/packages/vscode/package.json+++ b/packages/vscode/package.json@@ -178,6 +178,30 @@"command": "repowise.openDocs","title": "Open Docs for This File","category": "Repowise"+ },+ {+ "command": "repowise.showHealthDashboard",+ "title": "Show Health Dashboard",+ "category": "Repowise",+ "icon": "$(dashboard)"+ },+ {+ "command": "repowise.showArchitecture",+ "title": "Show Architecture Map",+ "category": "Repowise",+ "icon": "$(layers)"+ },+ {+ "command": "repowise.showKnowledgeGraph",+ "title": "Show Knowledge Graph",+ "category": "Repowise",+ "icon": "$(type-hierarchy)"+ },+ {+ "command": "repowise.showDecisionTimeline",+ "title": "Show Decision Timeline",+ "category": "Repowise",+ "icon": "$(milestone)"}],"menus": {@@ -187,6 +211,18 @@"group": "navigation","when": "scmProvider == git && repowise.state == 'ready'"}+ ],+ "view/title": [+ {+ "command": "repowise.showHealthDashboard",+ "group": "navigation",+ "when": "view == repowise.healthView"+ },+ {+ "command": "repowise.showDecisionTimeline",+ "group": "navigation",+ "when": "view == repowise.decisionsView"+ }]},"viewsContainers": {@@ -307,23 +343,38 @@},"scripts": {"build": "node esbuild.mjs",+ "build:webview": "vite build --config webview/vite.config.mts","watch": "node esbuild.mjs --watch",- "type-check": "tsc --noEmit",- "pretest": "npm run build && tsc -p tsconfig.test.json",+ "type-check": "tsc --noEmit && tsc -p webview/tsconfig.json",+ "pretest": "npm run build && npm run build:webview && tsc -p tsconfig.test.json","test": "vscode-test",+ "test:webview": "vitest run --config webview/vitest.config.mts","package": "vsce package --no-dependencies"},"devDependencies": {"@repowise-dev/api-client": "*","@repowise-dev/types": "*","@repowise-dev/ui": "*",+ "@tailwindcss/typography": "^0.5.15",+ "@tailwindcss/vite": "^4.0.0",+ "@testing-library/react": "^16.1.0","@types/mocha": "^10.0.0","@types/node": "^20",+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0","@types/vscode": "~1.101.0",+ "@vitejs/plugin-react": "^5.0.0","@vscode/test-cli": "^0.0.10","@vscode/test-electron": "^3.0.0","@vscode/vsce": "^3.0.0","esbuild": "^0.28.0",- "typescript": "^5.7.2"+ "jsdom": "^26.0.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "swr": "^2.2.5",+ "tailwindcss": "^4.0.0",+ "typescript": "^5.7.2",+ "vite": "^7.0.0",+ "vitest": "^3.0.0"}}diff --git a/packages/vscode/src/constants.ts b/packages/vscode/src/constants.tsindex 7faf3dade..7ba66a5fd 100644--- a/packages/vscode/src/constants.ts+++ b/packages/vscode/src/constants.ts@@ -27,6 +27,10 @@ export const Commands = {updateIndex: "repowise.updateIndex",showFileHealth: "repowise.showFileHealth",openDocs: "repowise.openDocs",+ showHealthDashboard: "repowise.showHealthDashboard",+ showArchitecture: "repowise.showArchitecture",+ showKnowledgeGraph: "repowise.showKnowledgeGraph",+ showDecisionTimeline: "repowise.showDecisionTimeline",} as const;/**diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.tsnew file mode 100644index 000000000..d5dad39a5--- /dev/null+++ b/packages/vscode/src/core/webviewApi.ts@@ -0,0 +1,146 @@+import * as vscode from "vscode";+import {+ getChurnComplexity,+ getHealthOverview,+ getHealthTrend,+ listHealthFiles,+} from "@repowise-dev/api-client/code-health";+import { getArchitectureView } from "@repowise-dev/api-client/c4";+import { getFileContent, getFileDetail } from "@repowise-dev/api-client/files";+import {+ getArchitectureCommunityGraph,+ getCommunities,+ getCommunitySlice,+ getDeadCodeGraph,+ getExecutionFlows,+ getGraph,+ getHotFilesGraph,+ getModuleGraph,+} from "@repowise-dev/api-client/graph";+import {+ getRefactoringPlan,+ getRefactoringTargets,+} from "@repowise-dev/api-client/refactoring";+import { listDecisions } from "@repowise-dev/api-client/decisions";+import { getPageById, listAllPages } from "@repowise-dev/api-client/pages";+import { getRiskRange } from "@repowise-dev/api-client/risk";+import { buildRefactoringPlanPrompt } from "@repowise-dev/ui/health/ai-prompt-builder";+import { CONFIG_SECTION } from "../constants";+import type { HostApi, RiskRangeReport } from "../shared/webviewMessages";+import type { RepowiseContext } from "./context";+import { getCurrentBranchName } from "./gitApi";++/** Thrown by the dispatcher when a request arrives while disconnected. */+class NotReadyError extends Error {+ constructor() {+ super("The Repowise server is not connected.");+ }+}++/**+ * Host-side implementation of the webview data contract. Every method runs an+ * api-client fetcher against the connected server, memoized in the shared+ * cache under the indexed head commit plus a refresh epoch the panel manager+ * bumps on every refresh broadcast (so a null or unchanged head commit can+ * never serve stale data after an index update). Branch risk is the+ * exception: it scores the working HEAD, which moves independently of the+ * index, so it always fetches fresh.+ *+ * Cache keys are namespaced `wv:` to stay clear of the tree/hover/lens keys.+ */+export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostApi {+ function repoId(): string {+ const id = ctx.repoId;+ if (!id || ctx.getExtensionState() !== "ready") throw new NotReadyError();+ return id;+ }++ // Concurrent callers of the same key share one request instead of racing+ // (two panels opening together, or one view fanning out related slices).+ const inFlight = new Map<string, Promise<unknown>>();++ /** Serves from the tagged cache; concurrent misses share one request. */+ function cached<T>(key: string, load: (id: string) => Promise<T>): Promise<T> {+ const id = repoId();+ const tag = `${ctx.repo?.head_commit ?? ""}#${epoch()}`;+ const hit = ctx.cache.get<T>(id, `wv:${key}`, tag);+ if (hit !== undefined) return Promise.resolve(hit);+ const flightKey = `${id}|${key}|${tag}`;+ const pending = inFlight.get(flightKey);+ if (pending) return pending as Promise<T>;+ const request = load(id)+ .then((value) => {+ ctx.cache.set(id, `wv:${key}`, tag, value);+ return value;+ })+ .finally(() => {+ inFlight.delete(flightKey);+ });+ inFlight.set(flightKey, request);+ return request;+ }++ return {+ // Health dashboard+ healthOverview: (limit) => cached(`health:overview:${limit ?? ""}`, (id) => getHealthOverview(id, limit)),+ healthFiles: (query) =>+ cached(`health:files:${JSON.stringify(query ?? {})}`, (id) => listHealthFiles(id, query)),+ healthTrend: (limit) => cached(`health:trend:${limit ?? ""}`, (id) => getHealthTrend(id, limit)),+ churnComplexity: (limit) =>+ cached(`health:churn:${limit ?? ""}`, (id) => getChurnComplexity(id, limit != null ? { limit } : undefined)),++ // Architecture map+ architectureView: () => cached("arch:view", (id) => getArchitectureView(id)),+ // Working-tree content, not index content: never cached under head_commit.+ fileContent: (filePath) => getFileContent(repoId(), filePath),++ // Knowledge graph+ moduleGraph: () => cached("graph:modules", (id) => getModuleGraph(id)),+ fullGraph: (limit) => cached(`graph:full:${limit ?? ""}`, (id) => getGraph(id, limit)),+ architectureCommunityGraph: () =>+ cached("graph:architecture", (id) => getArchitectureCommunityGraph(id)),+ communities: () => cached("graph:communities", (id) => getCommunities(id)),+ communitySlice: (communityId) =>+ cached(`graph:slice:${communityId}`, (id) => getCommunitySlice(id, communityId)),+ deadCodeGraph: () => cached("graph:dead", (id) => getDeadCodeGraph(id)),+ hotFilesGraph: () => cached("graph:hot", (id) => getHotFilesGraph(id)),+ executionFlows: () => cached("graph:flows", (id) => getExecutionFlows(id)),++ // Refactoring+ refactoringTargets: (filePath) =>+ cached(`refactor:targets:${filePath ?? ""}`, (id) =>+ getRefactoringTargets(id, filePath ? { filePath } : {}),+ ),+ refactoringPlan: (suggestionId) =>+ cached(`refactor:plan:${suggestionId}`, (id) => getRefactoringPlan(id, suggestionId)),+ refactoringPrompt: async (suggestionId, flavor) => {+ const plan = await cached(`refactor:plan:${suggestionId}`, (id) =>+ getRefactoringPlan(id, suggestionId),+ );+ const repoName = ctx.repo?.name;+ return buildRefactoringPlanPrompt({ plan, flavor, ...(repoName ? { repoName } : {}) });+ },++ // Decisions+ decisionsList: () =>+ cached("decisions:timeline", (id) => listDecisions(id, { include_proposed: true, limit: 500 })),++ // Docs+ pagesList: () => cached("docs:pages", (id) => listAllPages(id)),+ pageById: (pageId) => cached(`docs:page:${pageId}`, () => getPageById(pageId)),+ fileDetail: (relPath) => cached(`docs:file:${relPath}`, (id) => getFileDetail(id, relPath)),++ // Branch risk+ riskRange: async (): Promise<RiskRangeReport> => {+ const id = repoId();+ const configured = vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<string>("risk.baseBranch", "")+ .trim();+ const base = configured || ctx.repo?.default_branch || "main";+ const result = await getRiskRange(id, { base, head: "HEAD" });+ const branch = await getCurrentBranchName(ctx.workspace.repoRoot ?? "");+ return { base, branch, result };+ },+ };+}diff --git a/packages/vscode/src/core/webviews.ts b/packages/vscode/src/core/webviews.tsnew file mode 100644index 000000000..93ddfe1d0--- /dev/null+++ b/packages/vscode/src/core/webviews.ts@@ -0,0 +1,302 @@+import * as vscode from "vscode";+import * as path from "node:path";+import { randomBytes } from "node:crypto";+import type { RepowiseContext } from "./context";+import { createHostApi } from "./webviewApi";+import type {+ HostApi,+ HostToWebviewMessage,+ RepoInit,+ ViewParams,+ WebviewToHostMessage,+ WebviewViewId,+} from "../shared/webviewMessages";++interface ViewMeta {+ title: string;+ /**+ * Keep the DOM alive while the tab is hidden. Off by default: panels are+ * cheap to rebuild from the host cache. At most one heavy graph view earns+ * this, decided from measurements, not taste.+ */+ retainContextWhenHidden: boolean;+}++const VIEW_META: Record<WebviewViewId, ViewMeta> = {+ health: { title: "Repowise Health", retainContextWhenHidden: false },+ architecture: { title: "Repowise Architecture", retainContextWhenHidden: false },+ graph: { title: "Repowise Knowledge Graph", retainContextWhenHidden: false },+ refactoring: { title: "Repowise Refactoring Plan", retainContextWhenHidden: false },+ decisions: { title: "Repowise Decisions", retainContextWhenHidden: false },+ docs: { title: "Repowise Docs", retainContextWhenHidden: false },+ risk: { title: "Repowise Branch Risk", retainContextWhenHidden: false },+};++/** Singleton wired by registerWebviews(); features open panels through it. */+let manager: WebviewManager | null = null;++/**+ * Opens (or reveals) the panel for a view. When the panel is already open,+ * fresh params are pushed as a new init message so e.g. a different+ * refactoring plan replaces the current one instead of spawning a second tab.+ */+export function openViewPanel<V extends WebviewViewId>(+ ctx: RepowiseContext,+ view: V,+ params?: ViewParams[V],+): void {+ if (ctx.getExtensionState() !== "ready" || !ctx.repoId) {+ void vscode.window.showWarningMessage(+ "Connect to the Repowise server to open this view.",+ );+ return;+ }+ if (!manager) {+ ctx.log.error("openViewPanel called before registerWebviews");+ return;+ }+ manager.open(view, params ?? ({} as ViewParams[V]));+}++/** Registers the panel infrastructure. Idle until the first open. */+export function registerWebviews(+ ctx: RepowiseContext,+ extensionUri: vscode.Uri,+): vscode.Disposable {+ manager = new WebviewManager(ctx, extensionUri);+ return {+ dispose(): void {+ manager?.dispose();+ manager = null;+ },+ };+}++class WebviewManager {+ private readonly panels = new Map<WebviewViewId, vscode.WebviewPanel>();+ private readonly params = new Map<WebviewViewId, unknown>();+ private readonly hostApi: HostApi;+ private freshnessSub: vscode.Disposable | null = null;+ private readonly disposables: vscode.Disposable[] = [];+ /**+ * Folded into the host cache tag so every refresh broadcast forces fresh+ * fetches even when the server reports an unchanged (or null) head commit.+ */+ private epoch = 0;++ constructor(+ private readonly ctx: RepowiseContext,+ private readonly extensionUri: vscode.Uri,+ ) {+ this.hostApi = createHostApi(ctx, () => this.epoch);+ // A reconnect can resolve a different repo (or a moved index) without an+ // indexChanged event; re-init open panels so they never mix repos.+ this.disposables.push(+ ctx.onDidChangeExtensionState((state) => {+ if (state !== "ready") return;+ this.epoch += 1;+ this.broadcastRefresh();+ }),+ );+ }++ private broadcastRefresh(): void {+ const repo = this.repoInit();+ for (const panel of this.panels.values()) {+ void panel.webview.postMessage({ kind: "refresh", repo } satisfies HostToWebviewMessage);+ }+ }++ open(view: WebviewViewId, params: unknown): void {+ this.params.set(view, params);+ const existing = this.panels.get(view);+ if (existing) {+ existing.reveal(undefined, false);+ this.postInit(view, existing);+ return;+ }++ const meta = VIEW_META[view];+ const panel = vscode.window.createWebviewPanel(+ `repowise.${view}`,+ meta.title,+ vscode.ViewColumn.Active,+ {+ enableScripts: true,+ retainContextWhenHidden: meta.retainContextWhenHidden,+ localResourceRoots: [vscode.Uri.joinPath(this.extensionUri, "dist", "webview")],+ },+ );+ panel.iconPath = vscode.Uri.joinPath(this.extensionUri, "media", "repowise.svg");+ panel.webview.html = this.renderHtml(view, panel.webview);+ // Per-panel subscriptions are released with the panel, not the manager,+ // so open/close cycles never accumulate dead listeners.+ const msgSub = panel.webview.onDidReceiveMessage((msg: WebviewToHostMessage) =>+ void this.onMessage(view, panel, msg),+ );+ const dispSub = panel.onDidDispose(() => {+ this.panels.delete(view);+ this.params.delete(view);+ msgSub.dispose();+ dispSub.dispose();+ });+ this.panels.set(view, panel);+ this.ensureFreshness();+ }++ /** One freshness subscription for all panels, created on first open. */+ private ensureFreshness(): void {+ if (this.freshnessSub) return;+ const events = this.ctx.events();+ if (!events) return;+ this.freshnessSub = events.onDidChange((kind) => {+ if (kind !== "indexChanged") return;+ this.epoch += 1;+ void this.ctx.refreshRepo().then(() => this.broadcastRefresh());+ });+ }++ private repoInit(): RepoInit {+ const repo = this.ctx.repo;+ return {+ id: repo?.id ?? "",+ name: repo?.name ?? path.basename(this.ctx.workspace.repoRoot ?? "repository"),+ headCommit: repo?.head_commit ?? null,+ defaultBranch: repo?.default_branch ?? null,+ };+ }++ private postInit(view: WebviewViewId, panel: vscode.WebviewPanel): void {+ const message = {+ kind: "init",+ view,+ repo: this.repoInit(),+ params: (this.params.get(view) ?? {}) as ViewParams[typeof view],+ } satisfies HostToWebviewMessage;+ void panel.webview.postMessage(message);+ }++ private async onMessage(+ view: WebviewViewId,+ panel: vscode.WebviewPanel,+ msg: WebviewToHostMessage,+ ): Promise<void> {+ try {+ await this.handleMessage(view, panel, msg);+ } catch (err) {+ // Webview payloads are untrusted input; a malformed one is logged, never+ // an unhandled rejection.+ this.ctx.log.warn(`webview ${view} message failed: ${String(err)}`);+ }+ }++ private async handleMessage(+ view: WebviewViewId,+ panel: vscode.WebviewPanel,+ msg: WebviewToHostMessage,+ ): Promise<void> {+ switch (msg.kind) {+ case "ready":+ this.postInit(view, panel);+ return;+ case "rpc-request": {+ let response: HostToWebviewMessage;+ try {+ // Own-property check keeps inherited Object.prototype members+ // (constructor, toString, ...) out of the dispatch surface.+ if (!Object.hasOwn(this.hostApi, msg.method)) {+ throw new Error(`Unknown method: ${String(msg.method)}`);+ }+ const method = this.hostApi[msg.method] as (...a: unknown[]) => Promise<unknown>;+ const result = await method.apply(this.hostApi, msg.args);+ response = { kind: "rpc-response", id: msg.id, ok: true, result };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ this.ctx.log.warn(`webview ${view} ${String(msg.method)} failed: ${message}`);+ response = { kind: "rpc-response", id: msg.id, ok: false, error: message };+ }+ void panel.webview.postMessage(response);+ return;+ }+ case "open-file": {+ const root = this.ctx.workspace.repoRoot;+ if (!root || typeof msg.path !== "string") return;+ // Clamp to the workspace: a repo-relative path from a webview must+ // never escape the root.+ const abs = path.resolve(root, msg.path);+ if (abs !== path.resolve(root) && !abs.startsWith(path.resolve(root) + path.sep)) {+ this.ctx.log.warn(`webview ${view} tried to open a path outside the repo: ${msg.path}`);+ return;+ }+ const options: vscode.TextDocumentShowOptions = { preview: true };+ if (typeof msg.line === "number" && Number.isFinite(msg.line)) {+ options.selection = new vscode.Range(Math.max(0, msg.line - 1), 0, Math.max(0, msg.line - 1), 0);+ }+ try {+ await vscode.window.showTextDocument(vscode.Uri.file(abs), options);+ } catch {+ void vscode.window.showWarningMessage(`Could not open ${msg.path}.`);+ }+ return;+ }+ case "copy-text":+ if (typeof msg.text !== "string") return;+ await vscode.env.clipboard.writeText(msg.text);+ void vscode.window.showInformationMessage(+ typeof msg.toast === "string" ? msg.toast : "Copied to clipboard.",+ );+ return;+ case "open-external":+ if (typeof msg.url === "string" && /^https?:\/\//.test(msg.url)) {+ void vscode.env.openExternal(vscode.Uri.parse(msg.url));+ }+ return;+ }+ }++ private renderHtml(view: WebviewViewId, webview: vscode.Webview): string {+ const dist = vscode.Uri.joinPath(this.extensionUri, "dist", "webview");+ const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(dist, `${view}.js`));+ const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(dist, "webview.css"));+ const nonce = createNonce();+ // script-src needs cspSource beyond the nonce: the entry module lazily+ // imports its chunks (shiki, mermaid, view code), and those loads are+ // validated against the source list, not the entry's nonce.+ const csp = [+ "default-src 'none'",+ `img-src ${webview.cspSource} data:`,+ `style-src ${webview.cspSource} 'unsafe-inline'`,+ `font-src ${webview.cspSource}`,+ `script-src 'nonce-${nonce}' ${webview.cspSource}`,+ ].join("; ");+ return [+ "<!DOCTYPE html>",+ `<html lang="en">`,+ "<head>",+ `<meta charset="UTF-8" />`,+ `<meta http-equiv="Content-Security-Policy" content="${csp}" />`,+ `<meta name="viewport" content="width=device-width, initial-scale=1.0" />`,+ `<link rel="stylesheet" href="${styleUri.toString()}" />`,+ `<title>${VIEW_META[view].title}</title>`,+ "</head>",+ "<body>",+ `<div id="root"></div>`,+ `<script type="module" nonce="${nonce}" src="${scriptUri.toString()}"></script>`,+ "</body>",+ "</html>",+ ].join("\n");+ }++ dispose(): void {+ this.freshnessSub?.dispose();+ this.freshnessSub = null;+ for (const panel of this.panels.values()) panel.dispose();+ this.panels.clear();+ for (const d of this.disposables) d.dispose();+ this.disposables.length = 0;+ }+}++function createNonce(): string {+ return randomBytes(16).toString("base64");+}diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.tsindex 78cab2d46..a7cd11ecb 100644--- a/packages/vscode/src/extension.ts+++ b/packages/vscode/src/extension.ts@@ -21,6 +21,8 @@ import { registerBranchRisk } from "./features/branchRisk";import { registerStaleness } from "./features/staleness";import { registerRefactoringLens } from "./features/refactoringLens";import { registerDocs } from "./features/docs";+import { registerWebviews } from "./core/webviews";+import { registerDashboards } from "./features/dashboards";let rootContext: RepowiseContext | undefined;@@ -89,6 +91,8 @@ export function activate(extCtx: vscode.ExtensionContext): void {registerStaleness(ctx),registerRefactoringLens(ctx),registerDocs(ctx),+ registerWebviews(ctx, extCtx.extensionUri),+ registerDashboards(ctx),);// Workspace-folder changes are handled by the server manager, which ownsdiff --git a/packages/vscode/src/features/branchRisk.ts b/packages/vscode/src/features/branchRisk.tsindex 90d238eab..1dd3d49fb 100644--- a/packages/vscode/src/features/branchRisk.ts+++ b/packages/vscode/src/features/branchRisk.ts@@ -1,169 +1,17 @@import * as vscode from "vscode";-import { ApiClientError } from "@repowise-dev/api-client";-import { getRiskRange } from "@repowise-dev/api-client/risk";-import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";-import { CONFIG_SECTION, Commands } from "../constants";+import { Commands } from "../constants";import type { RepowiseContext } from "../core/context";-import { getCurrentBranchName } from "../core/gitApi";--/** Virtual-document scheme the rendered risk report is served on. */-const RISK_SCHEME = "repowise-risk";-/** Fixed virtual-document path; its basename becomes the preview title. */-const RISK_URI = vscode.Uri.parse(`${RISK_SCHEME}:/Branch Risk.md`);--/** Human-readable names for the raw change features the endpoint returns. */-const FEATURE_LABELS: ReadonlyArray<readonly [string, string]> = [- ["la", "Lines added"],- ["ld", "Lines deleted"],- ["nf", "Files changed"],- ["nd", "Directories changed"],- ["ns", "Subsystems changed"],- ["entropy", "Change entropy"],- ["exp", "Author experience"],-];+import { openViewPanel } from "../core/webviews";/**- * Scores the working branch against a base and renders the result as a markdown- * preview. Bound to the palette command and the SCM title button (both call- * `Commands.checkBranchRisk`). No caching: risk reflects the working HEAD, so- * each invocation fetches fresh.+ * Opens the branch-risk webview, which scores the working branch against a base+ * and renders the result. Bound to the palette command and the SCM title button+ * (both call `Commands.checkBranchRisk`). The webview owns fetching, so this+ * only opens the panel; openViewPanel guards the ready state and warns when the+ * server is not connected or the repository is not indexed.*/export function registerBranchRisk(ctx: RepowiseContext): vscode.Disposable {- let content = "";- const changeEmitter = new vscode.EventEmitter<vscode.Uri>();-- const provider: vscode.TextDocumentContentProvider = {- onDidChange: changeEmitter.event,- provideTextDocumentContent: () => content,- };-- async function run(): Promise<void> {- if (ctx.getExtensionState() !== "ready") {- void vscode.window.showWarningMessage(- "Connect to the Repowise server before scoring branch risk.",- );- return;- }- const repoId = ctx.repoId;- if (!repoId) {- void vscode.window.showWarningMessage(- "This repository is not indexed by the Repowise server.",- );- return;- }-- // Base resolution: explicit setting, else the server's default branch,- // else "main". An empty setting means "auto".- const configured = vscode.workspace- .getConfiguration(CONFIG_SECTION)- .get<string>("risk.baseBranch", "")- .trim();- const base = configured || ctx.repo?.default_branch || "main";-- const result = await vscode.window.withProgress(- {- location: vscode.ProgressLocation.Notification,- title: `Scoring branch risk against ${base}`,- },- async (): Promise<RiskRangeResponse | null> => {- try {- return await getRiskRange(repoId, { base, head: "HEAD" });- } catch (err) {- if (err instanceof ApiClientError) {- // The server rev-parses inputs and returns 400 on an unknown rev.- void vscode.window.showWarningMessage(- `Could not score branch risk: ${err.detail}`,- );- return null;- }- ctx.log.error(`branch risk failed: ${String(err)}`);- void vscode.window.showWarningMessage(- "Could not score branch risk. See the Repowise log for details.",- );- return null;- }- },- );- if (!result) return;-- const branch = await getCurrentBranchName(ctx.workspace.repoRoot ?? "");- content = renderReport(result, base, branch);- changeEmitter.fire(RISK_URI);- // Ensure the preview re-reads the updated content on a repeat invocation.- await vscode.workspace.openTextDocument(RISK_URI);- await vscode.commands.executeCommand("markdown.showPreview", RISK_URI);- }-- const disposables: vscode.Disposable[] = [- vscode.workspace.registerTextDocumentContentProvider(RISK_SCHEME, provider),- vscode.commands.registerCommand(Commands.checkBranchRisk, () => void run()),- changeEmitter,- ];-- return {- dispose(): void {- for (const d of disposables) d.dispose();- },- };-}--/** Formats a contribution with an explicit sign (positive raises risk). */-function signed(value: number): string {- return `${value >= 0 ? "+" : ""}${value.toFixed(2)}`;-}--/** Builds the markdown body for a scored range. */-function renderReport(- r: RiskRangeResponse,- base: string,- branch: string | null,-): string {- const lines: string[] = [];- const head = branch ?? "HEAD";-- lines.push(`# Branch risk: ${r.score.toFixed(1)}/10 (${r.level})`);- lines.push("");- lines.push(`\`${head}\` vs \`${base}\``);- lines.push("");- lines.push(`- Defect probability: ${(r.probability * 100).toFixed(1)}%`);- if (r.risk_percentile !== null) {- // Served as 0-100 already, not a fraction.- lines.push(`- Risk percentile: ${r.risk_percentile.toFixed(0)}%`);- }- if (r.review_priority !== null) {- lines.push(`- Review priority: ${r.review_priority}`);- }- if (r.is_fix) {- lines.push("- Classified as a fix change.");- }-- if (r.drivers.length > 0) {- lines.push("");- lines.push("## Drivers");- lines.push("");- const ordered = [...r.drivers].sort(- (a, b) => Math.abs(b.contribution) - Math.abs(a.contribution),- );- for (const d of ordered) {- lines.push(`- ${d.label}: ${signed(d.contribution)}`);- }- }-- // A feature can be null (author experience on shallow history); skip those.- const featureRows = FEATURE_LABELS.filter(- ([key]) => key in r.features && r.features[key] != null,+ return vscode.commands.registerCommand(Commands.checkBranchRisk, () =>+ openViewPanel(ctx, "risk", {}),);- if (featureRows.length > 0) {- lines.push("");- lines.push("## Features");- lines.push("");- lines.push("| Feature | Value |");- lines.push("| --- | --- |");- for (const [key, label] of featureRows) {- lines.push(`| ${label} | ${r.features[key]} |`);- }- }-- lines.push("");- return lines.join("\n");}diff --git a/packages/vscode/src/features/dashboards.ts b/packages/vscode/src/features/dashboards.tsnew file mode 100644index 000000000..9487337ab--- /dev/null+++ b/packages/vscode/src/features/dashboards.ts@@ -0,0 +1,32 @@+import * as vscode from "vscode";+import { Commands } from "../constants";+import type { RepowiseContext } from "../core/context";+import { openViewPanel } from "../core/webviews";++/**+ * Palette commands for the standalone dashboard panels. The other panel+ * surfaces open from their owning features (docs command, branch risk+ * command, refactoring lens and tree), so this module stays a thin command+ * fan-out with no data logic.+ */+export function registerDashboards(ctx: RepowiseContext): vscode.Disposable {+ const disposables = [+ vscode.commands.registerCommand(Commands.showHealthDashboard, () =>+ openViewPanel(ctx, "health"),+ ),+ vscode.commands.registerCommand(Commands.showArchitecture, () =>+ openViewPanel(ctx, "architecture"),+ ),+ vscode.commands.registerCommand(Commands.showKnowledgeGraph, () =>+ openViewPanel(ctx, "graph"),+ ),+ vscode.commands.registerCommand(Commands.showDecisionTimeline, () =>+ openViewPanel(ctx, "decisions"),+ ),+ ];+ return {+ dispose(): void {+ for (const d of disposables) d.dispose();+ },+ };+}diff --git a/packages/vscode/src/features/docs.ts b/packages/vscode/src/features/docs.tsindex c346d1535..fe3c69445 100644--- a/packages/vscode/src/features/docs.ts+++ b/packages/vscode/src/features/docs.ts@@ -1,102 +1,21 @@import * as vscode from "vscode";-import { getFileDetail } from "@repowise-dev/api-client/files";import { Commands } from "../constants";import type { RepowiseContext } from "../core/context";import { repoRelativePath } from "../core/fileSignals";--/** Virtual-document scheme for the rendered wiki page preview. */-const DOCS_SCHEME = "repowise-docs";+import { openViewPanel } from "../core/webviews";/**- * Docs command: renders the wiki page for the active editor's file. The page- * body ships inline on the file-detail aggregate, so one request maps a- * repo-relative path to its content. The rendered markdown is cached per file- * under the head-commit tag and shown as a markdown preview.+ * Docs command: opens the docs browser panel focused on the active editor's+ * file. Resolution of the file's wiki page happens inside the panel; here we+ * only translate the editor uri to a repo-relative path. With no active+ * editor the panel opens on the repository overview.*/export function registerDocs(ctx: RepowiseContext): vscode.Disposable {- // Rendered page markdown, keyed by virtual-doc uri, for this session.- const docContent = new Map<string, string>();- const contentProvider: vscode.TextDocumentContentProvider = {- provideTextDocumentContent: (uri) => docContent.get(uri.toString()) ?? "",- };-- return vscode.Disposable.from(- vscode.workspace.registerTextDocumentContentProvider(DOCS_SCHEME, contentProvider),- vscode.commands.registerCommand(Commands.openDocs, () => openDocs(ctx, docContent)),- );+ return vscode.commands.registerCommand(Commands.openDocs, () => openDocs(ctx));}-async function openDocs(- ctx: RepowiseContext,- docContent: Map<string, string>,-): Promise<void> {+function openDocs(ctx: RepowiseContext): void {const editor = vscode.window.activeTextEditor;- if (!editor) {- void vscode.window.showInformationMessage("Open a file to see its Repowise docs.");- return;- }-- const relPath = repoRelativePath(ctx, editor.document.uri);- if (!relPath) {- void vscode.window.showInformationMessage(- "This file is not part of the indexed repository.",- );- return;- }-- if (ctx.getExtensionState() !== "ready" || !ctx.repoId) {- void vscode.window.showInformationMessage(- "Start the Repowise server to load docs for this file.",- );- return;- }-- const repoId = ctx.repoId;- const tag = ctx.repo?.head_commit ?? "";- const key = `docs:${relPath}`;-- let markdown = ctx.cache.get<string>(repoId, key, tag);- if (markdown === undefined) {- let rendered: string | null;- try {- const detail = await getFileDetail(repoId, relPath);- rendered = detail.wiki_page ? renderPage(detail.wiki_page) : null;- } catch (err) {- ctx.log.error(`openDocs(${relPath}) failed: ${String(err)}`);- void vscode.window.showErrorMessage(- "Could not load docs for this file. See the Repowise log for details.",- );- return;- }- if (rendered === null) {- void vscode.window.showInformationMessage("No docs indexed for this file.");- return;- }- markdown = rendered;- ctx.cache.set(repoId, key, tag, markdown);- }-- // Tag the uri with the head commit so a reindex yields a fresh preview rather- // than a stale cached render.- const uri = vscode.Uri.from({- scheme: DOCS_SCHEME,- path: `/${relPath}.md`,- query: tag,- });- docContent.set(uri.toString(), markdown);- await vscode.commands.executeCommand("markdown.showPreview", uri);-}--/** Wiki page as markdown, with any human-curated note quoted above the body. */-function renderPage(page: {- content: string;- human_notes: string | null;-}): string {- const notes = page.human_notes?.trim();- if (!notes) return page.content;- const quoted = notes- .split("\n")- .map((line) => `> ${line}`)- .join("\n");- return `${quoted}\n\n${page.content}`;+ const relPath = editor ? repoRelativePath(ctx, editor.document.uri) : null;+ openViewPanel(ctx, "docs", relPath ? { filePath: relPath } : {});}diff --git a/packages/vscode/src/features/refactoringLens.ts b/packages/vscode/src/features/refactoringLens.tsindex ba86861a8..a90e58d5d 100644--- a/packages/vscode/src/features/refactoringLens.ts+++ b/packages/vscode/src/features/refactoringLens.ts@@ -1,22 +1,12 @@import * as vscode from "vscode";-import * as path from "node:path";import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";import { typeMeta } from "@repowise-dev/ui/refactoring/meta";-import {- blastCount,- blastFiles,- evidenceRows,- planSynopsis,- planWins,- type RefactoringPlan,-} from "@repowise-dev/ui/refactoring/types";+import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";import { CONFIG_SECTION, InternalCommands } from "../constants";import type { RepowiseContext } from "../core/context";import { repoRelativePath } from "../core/fileSignals";import { getPlansForFile } from "../core/plans";--/** Virtual-document scheme for the rendered refactoring plan preview. */-const PLAN_SCHEME = "repowise-plan";+import { openViewPanel } from "../core/webviews";/** The four agent prompt flavors, in QuickPick order (first is the default). */const FLAVOR_ITEMS: { label: string; flavor: AiPromptFlavor }[] = [@@ -27,23 +17,16 @@ const FLAVOR_ITEMS: { label: string; flavor: AiPromptFlavor }[] = [];/**- * Refactoring CodeLens: renders one lens per detected refactoring plan above the+ * Refactoring CodeLens: renders lenses per detected refactoring plan above the* plan's start line, gated on the `repowise.codeLens.enabled` setting and the- * `ready` state. Owns the two internal commands the lens fans out to: opening a- * rendered plan preview and copying a ready-to-paste agent prompt.+ * `ready` state. Owns the two internal commands the lens fans out to: opening+ * the plan panel and copying a ready-to-paste agent prompt.*/export function registerRefactoringLens(ctx: RepowiseContext): vscode.Disposable {const onDidChangeCodeLenses = new vscode.EventEmitter<void>();const provider = createProvider(ctx, onDidChangeCodeLenses.event);- // Rendered plan markdown, keyed by virtual-doc uri. Kept for the session so a- // reopened preview does not need to re-render.- const planDocs = new Map<string, string>();- const planContentProvider: vscode.TextDocumentContentProvider = {- provideTextDocumentContent: (uri) => planDocs.get(uri.toString()) ?? "",- };-let watcherSub: vscode.Disposable | undefined;/** Subscribe to index-change events once, lazily (never during activate). */function ensureWatcher(): void {@@ -73,9 +56,8 @@ export function registerRefactoringLens(ctx: RepowiseContext): vscode.Disposablereturn vscode.Disposable.from(vscode.languages.registerCodeLensProvider({ scheme: "file" }, provider),- vscode.workspace.registerTextDocumentContentProvider(PLAN_SCHEME, planContentProvider),vscode.commands.registerCommand(InternalCommands.openRefactoringPlan, (plan: RefactoringPlan) =>- openRefactoringPlan(planDocs, plan),+ openRefactoringPlan(ctx, plan),),vscode.commands.registerCommand(InternalCommands.copyRefactoringPrompt, (plan: RefactoringPlan) =>copyRefactoringPrompt(plan),@@ -115,6 +97,11 @@ function createProvider(command: InternalCommands.openRefactoringPlan,arguments: [plan],}),+ new vscode.CodeLens(range, {+ title: "Copy for agent",+ command: InternalCommands.copyRefactoringPrompt,+ arguments: [plan],+ }),);}return lenses;@@ -124,106 +111,15 @@ function createProvider(};}-/** "Repowise: Extract Class (impact 1.20, M)". */+/** "Repowise: Extract Class plan (impact 1.20)". */function lensTitle(plan: RefactoringPlan): string {- return `Repowise: ${typeMeta(plan.refactoring_type).label} (impact ${plan.impact_delta.toFixed(- 2,- )}, ${plan.effort_bucket})`;-}--/** `path:start-end` (or `path:start`, or `path`) for the plan's target. */-function planLocation(plan: RefactoringPlan): string {- if (plan.line_start == null) return plan.file_path;- if (plan.line_end != null && plan.line_end !== plan.line_start) {- return `${plan.file_path}:${plan.line_start}-${plan.line_end}`;- }- return `${plan.file_path}:${plan.line_start}`;-}--/** Human-readable plan preview (distinct from the agent prompt). */-function renderPlanMarkdown(plan: RefactoringPlan): string {- const meta = typeMeta(plan.refactoring_type);- const affected = blastFiles(plan).filter((f) => f !== plan.file_path);- const count = blastCount(plan);- const wins = planWins(plan);- const evidence = evidenceRows(plan);-- const lines: string[] = [- `# ${meta.label}`,- "",- planSynopsis(plan) || meta.blurb,- "",- "## Target",- "",- `- Location: \`${planLocation(plan)}\``,- ...(plan.target_symbol ? [`- Symbol: \`${plan.target_symbol}\``] : []),- `- Confidence: ${plan.confidence}`,- `- Effort: ${plan.effort_bucket}`,- `- Impact: ${plan.impact_delta.toFixed(2)} health points`,- "",- ];-- if (wins.length > 0) {- lines.push("## What you gain", "");- for (const win of wins) lines.push(`- ${win.label}`);- lines.push("");- }-- if (evidence.length > 0) {- lines.push("## Evidence", "");- for (const row of evidence) lines.push(`- ${row.label}: ${row.value}`);- lines.push("");- }-- lines.push("## Blast radius", "");- if (affected.length > 0) {- lines.push(`${count} file${count === 1 ? "" : "s"} to keep consistent:`, "");- for (const file of affected.slice(0, 20)) lines.push(`- \`${file}\``);- if (affected.length > 20) lines.push(`- ...and ${affected.length - 20} more`);- } else {- lines.push(- count > 0- ? `${count} dependent${count === 1 ? "" : "s"} affected.`- : "No dependent files recorded.",- );- }- lines.push("");-- lines.push(- "---",- "",- 'Run "Repowise: Copy plan for agent" (the action on this preview) to copy a ready-to-paste prompt for an AI coding agent.',- );-- return lines.join("\n");+ return `Repowise: ${typeMeta(plan.refactoring_type).label} plan (impact ${plan.impact_delta.toFixed(2)})`;}-/** Render the plan into a virtual markdown doc and open its preview. */-async function openRefactoringPlan(- planDocs: Map<string, string>,- plan: RefactoringPlan,-): Promise<void> {+/** Open the designed plan panel, seeded with this plan (and its file for the list). */+function openRefactoringPlan(ctx: RepowiseContext, plan: RefactoringPlan): void {if (!plan) return;- const meta = typeMeta(plan.refactoring_type);- const base = path.basename(plan.file_path) || "file";- // Unique per plan id so distinct plans get distinct previews; readable path so- // the preview tab shows the refactoring type.- const uri = vscode.Uri.from({- scheme: PLAN_SCHEME,- path: `/${meta.label} - ${base}.md`,- query: plan.id,- });- planDocs.set(uri.toString(), renderPlanMarkdown(plan));-- await vscode.commands.executeCommand("markdown.showPreview", uri);-- const choice = await vscode.window.showInformationMessage(- `Repowise refactoring plan: ${meta.label}`,- "Copy plan for agent",- );- if (choice === "Copy plan for agent") {- await vscode.commands.executeCommand(InternalCommands.copyRefactoringPrompt, plan);- }+ openViewPanel(ctx, "refactoring", { planId: plan.id, filePath: plan.file_path });}/** Pick a prompt flavor and copy the shared agent prompt for this plan. */diff --git a/packages/vscode/src/features/trees/refactoring.ts b/packages/vscode/src/features/trees/refactoring.tsindex 87e652505..d19988cd4 100644--- a/packages/vscode/src/features/trees/refactoring.ts+++ b/packages/vscode/src/features/trees/refactoring.ts@@ -40,7 +40,10 @@ class RefactoringTreeProvider extends RepowiseTreeProvider {const targets = await this.cached(PLANS_KEY, () =>getRefactoringTargets(repoId, { minConfidence: "medium" }),);- this.setBadge(targets.summary.total, `${targets.summary.total} refactoring targets`);+ // Badge what the tree actually lists (medium+ confidence, top-N), not the+ // server's global total: a four-digit badge on the activity bar is noise.+ const listed = Math.min(targets.plans.length, MAX_PLANS);+ this.setBadge(listed, `${listed} ranked refactoring plans`);if (targets.plans.length === 0) {return [this.messageNode("No refactoring targets")];diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.tsnew file mode 100644index 000000000..cf70fee4b--- /dev/null+++ b/packages/vscode/src/shared/webviewMessages.ts@@ -0,0 +1,187 @@+/**+ * Typed message contract between the extension host and the webviews.+ *+ * This module is imported by BOTH bundles (esbuild host bundle and the Vite+ * webview bundles), so it must stay free of 'vscode' imports and of any+ * runtime dependency beyond type-only imports. Webviews never fetch: every+ * data need is an RpcRequest the host serves from the shared api-client and+ * cache; everything else is a one-way notification.+ */++import type {+ ChurnComplexityResponse,+ HealthFilesQuery,+ HealthFilesResponse,+ HealthOverviewResponse,+ HealthTrendResponse,+} from "@repowise-dev/types/health";+import type { FileDetailResponse } from "@repowise-dev/types/files";+import type {+ ArchitectureGraphResponse,+ CommunitySliceResponse,+ CommunitySummaryItem,+ DeadCodeGraphResponse,+ DecisionRecordResponse,+ ExecutionFlowsResponse,+ GraphExportResponse,+ HotFilesGraphResponse,+ ModuleGraphResponse,+ PageResponse,+} from "@repowise-dev/api-client/types";+import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";+import type { ArchitectureView } from "@repowise-dev/ui/c4";+import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring/types";+import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";++/** Every webview panel the extension can open. */+export type WebviewViewId =+ | "health"+ | "architecture"+ | "graph"+ | "refactoring"+ | "decisions"+ | "docs"+ | "risk";++/** Per-view open parameters, carried in the init message. */+export interface ViewParams {+ health: Record<string, never>;+ architecture: { selectPath?: string };+ graph: { selectNode?: string };+ refactoring: { planId?: string; filePath?: string };+ decisions: Record<string, never>;+ docs: { pageId?: string; filePath?: string };+ risk: Record<string, never>;+}++/** Repo facts the webview needs for labels and cache-busting. */+export interface RepoInit {+ id: string;+ name: string;+ headCommit: string | null;+ defaultBranch: string | null;+}++/**+ * Data the host can serve. One method per need; the webview client is a+ * Proxy over this interface and the host dispatcher implements it, so the+ * two sides cannot drift.+ */+export interface HostApi {+ // Health dashboard+ healthOverview(limit?: number): Promise<HealthOverviewResponse>;+ healthFiles(query?: HealthFilesQuery): Promise<HealthFilesResponse>;+ healthTrend(limit?: number): Promise<HealthTrendResponse>;+ churnComplexity(limit?: number): Promise<ChurnComplexityResponse>;+ // Architecture map+ architectureView(): Promise<ArchitectureView>;+ fileContent(filePath: string): Promise<string>;+ // Knowledge graph+ moduleGraph(): Promise<ModuleGraphResponse>;+ fullGraph(limit?: number): Promise<GraphExportResponse>;+ architectureCommunityGraph(): Promise<ArchitectureGraphResponse>;+ communities(): Promise<CommunitySummaryItem[]>;+ communitySlice(communityId: number): Promise<CommunitySliceResponse>;+ deadCodeGraph(): Promise<DeadCodeGraphResponse>;+ hotFilesGraph(): Promise<HotFilesGraphResponse>;+ executionFlows(): Promise<ExecutionFlowsResponse>;+ // Refactoring+ refactoringTargets(filePath?: string): Promise<RefactoringTargets>;+ refactoringPlan(suggestionId: string): Promise<RefactoringPlan>;+ /** Built host-side so the prompt matches the CodeLens copy path exactly. */+ refactoringPrompt(suggestionId: string, flavor: AiPromptFlavor): Promise<string>;+ // Decisions+ decisionsList(): Promise<DecisionRecordResponse[]>;+ // Docs+ pagesList(): Promise<PageResponse[]>;+ pageById(pageId: string): Promise<PageResponse>;+ fileDetail(relPath: string): Promise<FileDetailResponse>;+ // Branch risk+ riskRange(): Promise<RiskRangeReport>;+}++/** Branch risk payload: the endpoint response plus the refs it compared. */+export interface RiskRangeReport {+ base: string;+ branch: string | null;+ result: RiskRangeResponse;+}++export type HostApiMethod = keyof HostApi;++// ---------------------------------------------------------------------------+// Envelopes+// ---------------------------------------------------------------------------++/** Webview -> host: invoke a HostApi method. */+export interface RpcRequestMessage {+ kind: "rpc-request";+ id: number;+ method: HostApiMethod;+ args: unknown[];+}++/** Host -> webview: RPC outcome. */+export interface RpcResponseMessage {+ kind: "rpc-response";+ id: number;+ ok: boolean;+ /** Present when ok. */+ result?: unknown;+ /** Present when not ok; already user-presentable. */+ error?: string;+}++/** Webview -> host: bootstrapped and listening; host replies with init. */+export interface ReadyMessage {+ kind: "ready";+}++/** Host -> webview: everything the view needs to render. */+export interface InitMessage<V extends WebviewViewId = WebviewViewId> {+ kind: "init";+ view: V;+ repo: RepoInit;+ params: ViewParams[V];+}++/**+ * Host -> webview: the index moved under the panel (repowise update finished+ * or HEAD changed). Views refetch what they show; repo.headCommit is fresh.+ */+export interface RefreshMessage {+ kind: "refresh";+ repo: RepoInit;+}++/** Webview -> host: open a repo file in an editor column. */+export interface OpenFileMessage {+ kind: "open-file";+ /** Repo-relative path. */+ path: string;+ /** 1-based line to reveal. */+ line?: number;+}++/** Webview -> host: put text on the clipboard and confirm via toast. */+export interface CopyTextMessage {+ kind: "copy-text";+ text: string;+ /** Confirmation toast; defaults to a generic one. */+ toast?: string;+}++/** Webview -> host: open an external URL in the default browser. */+export interface OpenExternalMessage {+ kind: "open-external";+ url: string;+}++export type WebviewToHostMessage =+ | ReadyMessage+ | RpcRequestMessage+ | OpenFileMessage+ | CopyTextMessage+ | OpenExternalMessage;++export type HostToWebviewMessage = InitMessage | RefreshMessage | RpcResponseMessage;diff --git a/packages/vscode/webview/src/runtime/mount.tsx b/packages/vscode/webview/src/runtime/mount.tsxnew file mode 100644index 000000000..aa314e890--- /dev/null+++ b/packages/vscode/webview/src/runtime/mount.tsx@@ -0,0 +1,114 @@+/**+ * Shared bootstrap for every webview entry: theme sync, host handshake,+ * loading state, error boundary, and re-init when the host pushes new params+ * into an already-open panel.+ */++import { Component, StrictMode, useEffect, useState, type ReactNode } from "react";+import { createRoot } from "react-dom/client";+import type {+ InitMessage,+ RepoInit,+ ViewParams,+ WebviewViewId,+} from "../../../src/shared/webviewMessages";+import { createHost, type WebviewHost } from "./rpc";+import { initTheme } from "./theme";++/** Everything a view component receives. */+export interface ViewProps<V extends WebviewViewId> {+ host: WebviewHost;+ repo: RepoInit;+ params: ViewParams[V];+ /** Increments when the index moves; refetch effects key on it. */+ refreshToken: number;+}++export function mountView<V extends WebviewViewId>(+ view: V,+ App: React.ComponentType<ViewProps<V>>,+): void {+ initTheme();+ const host = createHost();+ const container = document.getElementById("root");+ if (!container) throw new Error("Webview root element missing");+ createRoot(container).render(+ <StrictMode>+ <Bootstrap view={view} host={host} App={App} />+ </StrictMode>,+ );+ host.ready();+}++interface BootstrapProps<V extends WebviewViewId> {+ view: V;+ host: WebviewHost;+ App: React.ComponentType<ViewProps<V>>;+}++function Bootstrap<V extends WebviewViewId>({ view, host, App }: BootstrapProps<V>): ReactNode {+ const [init, setInit] = useState<InitMessage | null>(null);+ const [initSeq, setInitSeq] = useState(0);+ const [repo, setRepo] = useState<RepoInit | null>(null);+ const [refreshToken, setRefreshToken] = useState(0);++ useEffect(() => {+ const offInit = host.onInit((msg) => {+ setInit(msg);+ setRepo(msg.repo);+ // A repeat init (same panel, new params) resets the view subtree.+ setInitSeq((n) => n + 1);+ });+ const offRefresh = host.onRefresh((msg) => {+ setRepo(msg.repo);+ setRefreshToken((n) => n + 1);+ });+ return () => {+ offInit();+ offRefresh();+ };+ }, [host]);++ if (!init || !repo) {+ return (+ <div className="flex h-screen items-center justify-center text-[var(--color-text-tertiary)]">+ Loading…+ </div>+ );+ }++ return (+ <ErrorBoundary key={initSeq}>+ <App+ host={host}+ repo={repo}+ params={init.params as ViewParams[V]}+ refreshToken={refreshToken}+ />+ </ErrorBoundary>+ );+}++interface ErrorBoundaryState {+ error: Error | null;+}++class ErrorBoundary extends Component<{ children: ReactNode }, ErrorBoundaryState> {+ state: ErrorBoundaryState = { error: null };++ static getDerivedStateFromError(error: Error): ErrorBoundaryState {+ return { error };+ }++ render(): ReactNode {+ if (this.state.error) {+ return (+ <div className="m-6 rounded-lg border border-[var(--color-error)] p-4 text-sm">+ <p className="font-medium text-[var(--color-error)]">This view hit an error.</p>+ <p className="mt-2 text-[var(--color-text-secondary)]">{this.state.error.message}</p>+ </div>+ );+ }+ return this.props.children;+ }+}diff --git a/packages/vscode/webview/src/runtime/rpc.test.ts b/packages/vscode/webview/src/runtime/rpc.test.tsnew file mode 100644index 000000000..e1c9d2612--- /dev/null+++ b/packages/vscode/webview/src/runtime/rpc.test.ts@@ -0,0 +1,108 @@+/**+ * Round-trip test of the message contract: a scripted "host" answers the+ * webview client through the same envelopes core/webviews.ts uses, so a+ * protocol drift on either side fails here before it fails in the editor.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type {+ HostToWebviewMessage,+ InitMessage,+ WebviewToHostMessage,+} from "../../../src/shared/webviewMessages";++const INIT: InitMessage = {+ kind: "init",+ view: "health",+ repo: { id: "r1", name: "repo", headCommit: "abc", defaultBranch: "main" },+ params: {},+};++function postToWebview(msg: HostToWebviewMessage): void {+ window.dispatchEvent(new MessageEvent("message", { data: msg }));+}++/** Installs acquireVsCodeApi with a scripted host on the other side. */+function installHost() {+ const received: WebviewToHostMessage[] = [];+ (globalThis as Record<string, unknown>).acquireVsCodeApi = () => ({+ postMessage(msg: WebviewToHostMessage) {+ received.push(msg);+ if (msg.kind === "ready") {+ postToWebview(INIT);+ } else if (msg.kind === "rpc-request") {+ if (msg.method === "healthTrend") {+ postToWebview({ kind: "rpc-response", id: msg.id, ok: true, result: { history: [] } });+ } else {+ postToWebview({ kind: "rpc-response", id: msg.id, ok: false, error: "Unknown method" });+ }+ }+ },+ getState: () => undefined,+ setState: () => {},+ });+ return received;+}++describe("webview rpc round trip", () => {+ beforeEach(() => {+ // The singleton caches acquireVsCodeApi's result; a fresh module registry+ // per test keeps hosts isolated.+ vi.resetModules();+ });++ afterEach(() => {+ delete (globalThis as Record<string, unknown>).acquireVsCodeApi;+ });++ it("delivers init to subscribers, including late ones", async () => {+ installHost();+ const { createHost } = await import("./rpc");+ const host = createHost();++ const early: InitMessage[] = [];+ host.onInit((msg) => early.push(msg));+ host.ready();+ expect(early).toHaveLength(1);+ expect(early[0]?.repo.id).toBe("r1");++ // A subscriber attaching after the reply still receives the buffered init.+ const late: InitMessage[] = [];+ host.onInit((msg) => late.push(msg));+ expect(late).toHaveLength(1);+ });++ it("resolves rpc calls and rejects unknown methods with the host error", async () => {+ installHost();+ const { createHost } = await import("./rpc");+ const host = createHost();++ await expect(host.api.healthTrend(5)).resolves.toEqual({ history: [] });+ await expect(host.api.decisionsList()).rejects.toThrow("Unknown method");+ });++ it("routes one-way services with their payloads", async () => {+ const received = installHost();+ const { createHost } = await import("./rpc");+ const host = createHost();++ host.openFile("src/a.py", 12);+ host.copyText("hello", "Copied.");+ host.openExternal("https://example.com");++ expect(received).toContainEqual({ kind: "open-file", path: "src/a.py", line: 12 });+ expect(received).toContainEqual({ kind: "copy-text", text: "hello", toast: "Copied." });+ expect(received).toContainEqual({ kind: "open-external", url: "https://example.com" });+ });++ it("ignores garbage messages without breaking pending calls", async () => {+ installHost();+ const { createHost } = await import("./rpc");+ const host = createHost();++ postToWebview(null as unknown as HostToWebviewMessage);+ postToWebview({ kind: "rpc-response", id: 999, ok: true } as HostToWebviewMessage);++ await expect(host.api.healthTrend()).resolves.toEqual({ history: [] });+ });+});diff --git a/packages/vscode/webview/src/runtime/rpc.ts b/packages/vscode/webview/src/runtime/rpc.tsnew file mode 100644index 000000000..842ddef15--- /dev/null+++ b/packages/vscode/webview/src/runtime/rpc.ts@@ -0,0 +1,99 @@+/**+ * Webview side of the message contract. Webviews never fetch: `host.api` is a+ * Proxy that turns every HostApi call into an rpc-request the extension host+ * serves from its shared cache and api-client.+ */++import type {+ HostApi,+ HostApiMethod,+ HostToWebviewMessage,+ InitMessage,+ RefreshMessage,+} from "../../../src/shared/webviewMessages";+import { getVsCodeApi } from "./vscodeApi";++export interface WebviewHost {+ /** Typed data calls served by the extension host. */+ api: HostApi;+ /** Fires once per init push (first load and any re-open with new params). */+ onInit(cb: (msg: InitMessage) => void): () => void;+ /** Fires when the index moved and the view should refetch. */+ onRefresh(cb: (msg: RefreshMessage) => void): () => void;+ /** Tell the host we are listening; it answers with init. */+ ready(): void;+ openFile(path: string, line?: number): void;+ copyText(text: string, toast?: string): void;+ openExternal(url: string): void;+}++interface Pending {+ resolve: (value: unknown) => void;+ reject: (err: Error) => void;+}++export function createHost(): WebviewHost {+ const vscode = getVsCodeApi();+ const pending = new Map<number, Pending>();+ const initSubs = new Set<(msg: InitMessage) => void>();+ const refreshSubs = new Set<(msg: RefreshMessage) => void>();+ // Buffered so a subscriber attaching after the host already replied to+ // ready() (possible if React yields before the effect commits) still gets it.+ let lastInit: InitMessage | null = null;+ let nextId = 1;++ window.addEventListener("message", (event: MessageEvent<HostToWebviewMessage>) => {+ const msg = event.data;+ if (!msg || typeof msg !== "object") return;+ switch (msg.kind) {+ case "rpc-response": {+ const entry = pending.get(msg.id);+ if (!entry) return;+ pending.delete(msg.id);+ if (msg.ok) entry.resolve(msg.result);+ else entry.reject(new Error(msg.error ?? "Request failed."));+ return;+ }+ case "init":+ lastInit = msg;+ for (const cb of initSubs) cb(msg);+ return;+ case "refresh":+ for (const cb of refreshSubs) cb(msg);+ return;+ }+ });++ const api = new Proxy({} as HostApi, {+ get(_target, prop: string) {+ return (...args: unknown[]) =>+ new Promise((resolve, reject) => {+ const id = nextId++;+ pending.set(id, { resolve, reject });+ vscode.postMessage({+ kind: "rpc-request",+ id,+ method: prop as HostApiMethod,+ args,+ });+ });+ },+ });++ return {+ api,+ onInit(cb) {+ initSubs.add(cb);+ if (lastInit) cb(lastInit);+ return () => initSubs.delete(cb);+ },+ onRefresh(cb) {+ refreshSubs.add(cb);+ return () => refreshSubs.delete(cb);+ },+ ready: () => vscode.postMessage({ kind: "ready" }),+ openFile: (path, line) => vscode.postMessage({ kind: "open-file", path, line }),+ copyText: (text, toast) => vscode.postMessage({ kind: "copy-text", text, toast }),+ openExternal: (url) => vscode.postMessage({ kind: "open-external", url }),+ };+}diff --git a/packages/vscode/webview/src/runtime/theme.ts b/packages/vscode/webview/src/runtime/theme.tsnew file mode 100644index 000000000..55f57e2ec--- /dev/null+++ b/packages/vscode/webview/src/runtime/theme.ts@@ -0,0 +1,58 @@+/**+ * Follows the editor theme. VS Code stamps the webview body with+ * `vscode-light` / `vscode-dark` / `vscode-high-contrast` /+ * `vscode-high-contrast-light`; the shared UI package derives its entire+ * palette from a `.dark` class on the root element. This module keeps the two+ * in sync and exposes a subscription for code that needs the resolved kind+ * (the next-themes shim, canvas renderers).+ */++export type ThemeKind = "light" | "dark";++const subscribers = new Set<(kind: ThemeKind) => void>();+let current: ThemeKind = "light";+let started = false;++function compute(): ThemeKind {+ const cls = document.body.classList;+ // High-contrast without the -light suffix is the dark HC theme.+ if (cls.contains("vscode-dark")) return "dark";+ if (cls.contains("vscode-high-contrast") && !cls.contains("vscode-high-contrast-light")) {+ return "dark";+ }+ return "light";+}++function apply(kind: ThemeKind): void {+ document.documentElement.classList.toggle("dark", kind === "dark");+ if (kind === current) return;+ current = kind;+ for (const cb of subscribers) cb(kind);+}++/** Idempotent; called by the mount helper before first render. */+export function initTheme(): void {+ if (started) return;+ started = true;+ apply(compute());+ const observer = new MutationObserver(() => apply(compute()));+ observer.observe(document.body, { attributes: true, attributeFilter: ["class"] });+}++export function getThemeKind(): ThemeKind {+ return current;+}++/**+ * User-initiated override from an in-view toggle (e.g. the graph's light/dark+ * switch). Applies immediately; the next editor theme change wins again via+ * the body-class observer.+ */+export function setThemeOverride(kind: ThemeKind): void {+ apply(kind);+}++export function subscribeTheme(cb: (kind: ThemeKind) => void): () => void {+ subscribers.add(cb);+ return () => subscribers.delete(cb);+}diff --git a/packages/vscode/webview/src/runtime/vscodeApi.ts b/packages/vscode/webview/src/runtime/vscodeApi.tsnew file mode 100644index 000000000..9f30890f6--- /dev/null+++ b/packages/vscode/webview/src/runtime/vscodeApi.ts@@ -0,0 +1,18 @@+/** Singleton wrapper over acquireVsCodeApi (callable exactly once per page). */++import type { WebviewToHostMessage } from "../../../src/shared/webviewMessages";++interface VsCodeApi {+ postMessage(message: WebviewToHostMessage): void;+ getState(): unknown;+ setState(state: unknown): void;+}++declare function acquireVsCodeApi(): VsCodeApi;++let instance: VsCodeApi | null = null;++export function getVsCodeApi(): VsCodeApi {+ if (!instance) instance = acquireVsCodeApi();+ return instance;+}diff --git a/packages/vscode/webview/src/shims/dotlottie-react.tsx b/packages/vscode/webview/src/shims/dotlottie-react.tsxnew file mode 100644index 000000000..b4495de49--- /dev/null+++ b/packages/vscode/webview/src/shims/dotlottie-react.tsx@@ -0,0 +1,20 @@+/**+ * Build-time replacement for @lottiefiles/dotlottie-react (aliased in+ * vite.config). The real component fetches a WASM renderer and a Lottie JSON+ * at runtime; both are blocked by the webview CSP and only produce console+ * noise. A token-driven pulse stands in for the brand animation.+ */++import type { CSSProperties } from "react";++export function DotLottieReact(props: { style?: CSSProperties; [key: string]: unknown }) {+ return (+ <div+ style={props.style}+ className="flex items-center justify-center"+ aria-hidden+ >+ <div className="h-10 w-10 animate-pulse rounded-full border-4 border-[var(--color-accent-muted)] border-t-[var(--color-accent-primary)]" />+ </div>+ );+}diff --git a/packages/vscode/webview/src/shims/next-themes.ts b/packages/vscode/webview/src/shims/next-themes.tsnew file mode 100644index 000000000..b2d4295ec--- /dev/null+++ b/packages/vscode/webview/src/shims/next-themes.ts@@ -0,0 +1,36 @@+/**+ * Build-time replacement for the `next-themes` peer the shared UI package+ * expects (aliased in vite.config). Inside a webview the theme is dictated by+ * the editor, so `setTheme` is a no-op and the resolved theme mirrors the+ * body classes VS Code maintains.+ */++import { useSyncExternalStore, type ReactNode } from "react";+import { getThemeKind, setThemeOverride, subscribeTheme } from "../runtime/theme";++export interface UseThemeProps {+ theme: string | undefined;+ resolvedTheme: string | undefined;+ setTheme: (theme: string) => void;+ themes: string[];+ systemTheme: string | undefined;+}++export function useTheme(): UseThemeProps {+ const kind = useSyncExternalStore(subscribeTheme, getThemeKind, () => "light" as const);+ return {+ theme: kind,+ resolvedTheme: kind,+ setTheme: (theme: string) => {+ // In-view toggles override until the next editor theme change, which+ // the body-class observer applies over this.+ if (theme === "dark" || theme === "light") setThemeOverride(theme);+ },+ themes: ["light", "dark"],+ systemTheme: kind,+ };+}++export function ThemeProvider(props: { children: ReactNode }): ReactNode {+ return props.children;+}diff --git a/packages/vscode/webview/src/styles/index.css b/packages/vscode/webview/src/styles/index.cssnew file mode 100644index 000000000..5f046e9ba--- /dev/null+++ b/packages/vscode/webview/src/styles/index.css@@ -0,0 +1,10 @@+/*+ * Single stylesheet for every webview (cssCodeSplit is off; the host HTML+ * links dist/webview/webview.css). The shared UI stylesheet carries the+ * Tailwind v4 setup, the full design-token palette, and an @source directive+ * that scans the ui package's own sources for utility classes; the @source+ * below adds this package's webview sources to that scan.+ */+@import "@repowise-dev/ui/styles.css";+@source "../**/*.{ts,tsx}";+@import "./theme-bridge.css";diff --git a/packages/vscode/webview/src/styles/theme-bridge.css b/packages/vscode/webview/src/styles/theme-bridge.cssnew file mode 100644index 000000000..5c68ebf9a--- /dev/null+++ b/packages/vscode/webview/src/styles/theme-bridge.css@@ -0,0 +1,30 @@+/*+ * Editor integration layer. The shared palette ships its own light and dark+ * values keyed off a `.dark` root class, which the theme runtime toggles from+ * the editor's theme; the panels deliberately keep that brand palette instead+ * of remapping every token onto --vscode-* (a full remap flattens the data+ * visualizations into editor grays). Only the pieces that must match the+ * editor chrome are bridged here: typography and the page background seam.+ */++:root {+ --font-sans: var(--vscode-font-family, ui-sans-serif, system-ui, sans-serif);+ --font-mono: var(--vscode-editor-font-family, ui-monospace, monospace);+}++html,+body {+ margin: 0;+ padding: 0;+ height: 100%;+}++body {+ background: var(--color-bg-root);+ color: var(--color-text-primary);+ font-family: var(--font-sans);+}++#root {+ height: 100%;+}diff --git a/packages/vscode/webview/src/views/architecture/App.test.tsx b/packages/vscode/webview/src/views/architecture/App.test.tsxnew file mode 100644index 000000000..8c0e71a1d--- /dev/null+++ b/packages/vscode/webview/src/views/architecture/App.test.tsx@@ -0,0 +1,133 @@+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen, waitFor } from "@testing-library/react";+import type { ArchitectureView } from "@repowise-dev/ui/c4";+import type { WebviewHost } from "../../runtime/rpc";+import { App } from "./App";++// React Flow observes canvas size and visibility; jsdom ships neither.+beforeAll(() => {+ class ObserverStub {+ observe(): void {}+ unobserve(): void {}+ disconnect(): void {}+ takeRecords(): [] {+ return [];+ }+ }+ vi.stubGlobal("ResizeObserver", ObserverStub);+ vi.stubGlobal("IntersectionObserver", ObserverStub);+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++function makeNode(id: string, filePath: string | null): ArchitectureView["nodes"][number] {+ return {+ id,+ node_type: "file",+ name: id,+ file_path: filePath,+ line_range: null,+ summary: "",+ complexity: "simple",+ tags: [],+ language: "typescript",+ pagerank: 0,+ pagerank_percentile: 0,+ betweenness: 0,+ in_degree: 0,+ out_degree: 0,+ community_id: null,+ is_entry_point: false,+ is_test: false,+ is_hotspot: false,+ is_dead: false,+ has_doc: false,+ primary_owner: null,+ primary_owner_pct: null,+ bus_factor: null,+ };+}++const FIXTURE: ArchitectureView = {+ project_name: "demo",+ project_description: "A demo system.",+ layers: [+ {+ id: "layer:app",+ name: "Application",+ description: "App layer",+ node_ids: ["a", "b"],+ file_count: 2,+ complexity_distribution: { simple: 2 },+ health_score: 8,+ sub_groups: [],+ display_order: 0,+ },+ ],+ nodes: [makeNode("a", "src/a.ts"), makeNode("b", "src/b.ts")],+ edges: [{ source: "a", target: "b", edge_type: "import", direction: "forward", weight: 1, confidence: 1 }],+ tour: [],+ total_files: 2,+ total_symbols: 2,+ total_edges: 1,+ languages: ["typescript"],+ frameworks: [],+ external_systems: [],+ entry_points: [],+ entry_candidates: [],+};++function makeHost(overrides: Partial<WebviewHost["api"]> = {}): WebviewHost {+ const api = {+ architectureView: vi.fn().mockResolvedValue(FIXTURE),+ fileContent: vi.fn().mockResolvedValue(""),+ ...overrides,+ } as unknown as WebviewHost["api"];+ return {+ api,+ onInit: () => () => {},+ onRefresh: () => () => {},+ ready: () => {},+ openFile: vi.fn(),+ copyText: vi.fn(),+ openExternal: vi.fn(),+ };+}++describe("architecture App", () => {+ it("renders the header and canvas shell from an architectureView fixture", async () => {+ const host = makeHost();+ render(+ <App+ host={host}+ repo={{ id: "r1", name: "acme/widgets", headCommit: null, defaultBranch: null }}+ params={{}}+ refreshToken={0}+ />,+ );++ expect(await screen.findByText("acme/widgets")).toBeDefined();+ expect(screen.getByTestId("architecture-shell")).toBeDefined();+ expect(screen.getByTestId("architecture-canvas")).toBeDefined();+ await waitFor(() => expect(host.api.architectureView).toHaveBeenCalledTimes(1));+ });++ it("surfaces a styled error when the RPC rejects", async () => {+ const host = makeHost({+ architectureView: vi.fn().mockRejectedValue(new Error("index unavailable")),+ });+ render(+ <App+ host={host}+ repo={{ id: "r1", name: "acme/widgets", headCommit: null, defaultBranch: null }}+ params={{}}+ refreshToken={0}+ />,+ );++ expect(await screen.findByText("index unavailable")).toBeDefined();+ });+});diff --git a/packages/vscode/webview/src/views/architecture/App.tsx b/packages/vscode/webview/src/views/architecture/App.tsxnew file mode 100644index 000000000..3d663afb6--- /dev/null+++ b/packages/vscode/webview/src/views/architecture/App.tsx@@ -0,0 +1,268 @@+/**+ * Architecture map webview.+ *+ * Reimplements the web Knowledge Graph orchestration (packages/web+ * c4-view.tsx) natively in the editor: the shared c4 canvas, store, layout+ * hook, legend, controls, minimap, and detail panels, driven by one+ * architectureView() RPC instead of a fetch. The web version syncs its+ * navigation to URL query params via nuqs; a webview has no URL, so the same+ * state lives in the shared Zustand store and the only external seam is the+ * optional `selectPath` open-parameter, applied once after the data lands.+ */++import { useCallback, useEffect, useRef, useState } from "react";+import {+ ReactFlowProvider,+ useReactFlow,+ type Node,+} from "@xyflow/react";+import {+ ArchBreadcrumb,+ ArchCanvas,+ ArchTourButton,+ CodeViewer,+ FilterPanel,+ NodeTypeCategoryFilters,+ PathFinderModal,+ PersonaSelector,+ SearchBar,+ Sidebar,+ useArchitectureLayout,+ useArchitectureNavigation,+ useArchitectureStore,+ type ArchitectureView,+} from "@repowise-dev/ui/c4";+import type { ViewProps } from "../../runtime/mount";+import type { WebviewHost } from "../../runtime/rpc";++// Double-click drills into structural nodes; the same event on a file-backed+// node opens it in an editor column instead. Single click always selects.+const DRILL_CLUSTER = "layerCluster";+const DRILL_SUBGROUP = "subGroupCluster";+const DRILL_CONTAINER = "archContainer";+const FILE_NODE = "archFile";+// Portals and the scope frame are wayfinding stubs, not selectable entities.+const SYNTHETIC_NODE_TYPES = new Set(["portal", "scopeFrame"]);++export function App(props: ViewProps<"architecture">) {+ return (+ <ReactFlowProvider>+ <ArchitectureMap {...props} />+ </ReactFlowProvider>+ );+}++function ArchitectureMap({ host, repo, params, refreshToken }: ViewProps<"architecture">) {+ const { view, error, loading } = useArchitectureData(host, refreshToken);++ const setView = useArchitectureStore((s) => s.setView);+ const selectNode = useArchitectureStore((s) => s.selectNode);+ const drillIntoLayer = useArchitectureStore((s) => s.drillIntoLayer);+ const navigationLevel = useArchitectureStore((s) => s.navigationLevel);+ const activeLayerId = useArchitectureStore((s) => s.activeLayerId);+ const selectedNodeId = useArchitectureStore((s) => s.selectedNodeId);+ const setReactFlowInstance = useArchitectureStore((s) => s.setReactFlowInstance);+ const pathFinderOpen = useArchitectureStore((s) => s.pathFinderOpen);+ const nodesById = useArchitectureStore((s) => s.nodesById);++ useArchitectureNavigation();+ const { nodes, edges, loading: layoutLoading, hiddenEdgeCount } = useArchitectureLayout();+ const { fitView } = useReactFlow();++ // Feed the store from the RPC payload; setView resets navigation to the+ // overview, which is the right landing tier after a (re)fetch.+ useEffect(() => {+ if (view) setView(view);+ }, [view, setView]);++ // `selectPath` reveals a file's node once the data is in the store. Applied+ // a single time per data load so a later manual selection is never yanked+ // back. Missing paths degrade to the plain overview.+ const preselectAppliedRef = useRef(false);+ useEffect(() => {+ preselectAppliedRef.current = false;+ }, [view]);+ useEffect(() => {+ if (!view || preselectAppliedRef.current) return;+ preselectAppliedRef.current = true;+ const target = params.selectPath;+ if (!target) return;+ const match = view.nodes.find((n) => n.file_path === target);+ if (match) selectNode(match.id);+ }, [view, params.selectPath, selectNode]);++ // Frame the tier after a level change (drill in/out), matching the web+ // camera behaviour so the new scope lands centered.+ const pendingFitRef = useRef(false);+ const prevNavRef = useRef({ navigationLevel, activeLayerId });+ useEffect(() => {+ if (+ prevNavRef.current.navigationLevel !== navigationLevel ||+ prevNavRef.current.activeLayerId !== activeLayerId+ ) {+ pendingFitRef.current = true;+ prevNavRef.current = { navigationLevel, activeLayerId };+ }+ }, [navigationLevel, activeLayerId]);+ useEffect(() => {+ if (!pendingFitRef.current || nodes.length === 0) return;+ pendingFitRef.current = false;+ const raf = requestAnimationFrame(() => fitView({ duration: 400, padding: 0.2 }));+ return () => cancelAnimationFrame(raf);+ }, [nodes, fitView]);++ // Ease onto a freshly selected node once, without re-centering after the+ // user pans away (dimming refreshes must not steal the camera).+ const lastEasedRef = useRef<string | null>(null);+ useEffect(() => {+ if (!selectedNodeId) {+ lastEasedRef.current = null;+ return;+ }+ if (lastEasedRef.current === selectedNodeId) return;+ if (!nodes.some((n) => n.id === selectedNodeId)) return;+ lastEasedRef.current = selectedNodeId;+ const raf = requestAnimationFrame(() =>+ fitView({ nodes: [{ id: selectedNodeId }], duration: 250, padding: 0.4, maxZoom: 1.15 }),+ );+ return () => cancelAnimationFrame(raf);+ }, [selectedNodeId, nodes, fitView]);++ const handleNodeClick = useCallback(+ (_: React.MouseEvent, node: Node) => {+ if (SYNTHETIC_NODE_TYPES.has(node.type ?? "")) return;+ selectNode(node.id);+ },+ [selectNode],+ );++ const handleNodeDoubleClick = useCallback(+ (_: React.MouseEvent, node: Node) => {+ const store = useArchitectureStore.getState();+ if (node.type === DRILL_CLUSTER) {+ drillIntoLayer(node.id);+ } else if (node.type === DRILL_SUBGROUP) {+ store.drillIntoSubGroup(node.id);+ } else if (node.type === DRILL_CONTAINER) {+ store.toggleContainer(node.id);+ } else if (node.type === FILE_NODE) {+ const archNode = nodesById.get(node.id);+ if (archNode?.file_path) {+ host.openFile(archNode.file_path, archNode.line_range?.[0]);+ }+ }+ },+ [drillIntoLayer, nodesById, host],+ );++ const handlePaneClick = useCallback(() => selectNode(null), [selectNode]);++ // The in-panel code viewer reads bytes over the same RPC seam the web build+ // reads from the file-content endpoint.+ const fetchContent = useCallback(+ (filePath: string) => host.api.fileContent(filePath),+ [host],+ );++ const anyLoading = loading || layoutLoading;+ const levelLabel =+ navigationLevel === "layer-detail"+ ? "Detail"+ : navigationLevel === "layer-groups"+ ? "Groups"+ : "Overview";++ return (+ <div+ data-testid="architecture-shell"+ className="flex h-screen flex-col bg-[var(--color-bg-root)] text-[var(--color-text-primary)]"+ >+ <header className="shrink-0 border-b border-[var(--color-border-default)] px-4 py-3">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <h1 className="truncate text-sm font-semibold text-[var(--color-text-primary)]">+ {repo.name}+ </h1>+ <span className="rounded-full border border-[var(--color-border-default)] px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">+ {levelLabel}+ </span>+ </div>+ <p className="mt-0.5 truncate text-xs text-[var(--color-text-secondary)]">+ {view?.project_description || "Curated layered view of the system."}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-3">+ <ArchTourButton />+ <PersonaSelector />+ <NodeTypeCategoryFilters />+ </div>+ </div>+ <div className="mt-2 flex flex-wrap items-center gap-4">+ <SearchBar />+ <ArchBreadcrumb />+ </div>+ </header>++ <div data-testid="architecture-canvas" className="relative min-h-0 flex-1">+ <ArchCanvas+ nodes={nodes}+ edges={edges}+ loading={anyLoading}+ error={error ? { message: error.message } : null}+ hiddenEdgeCount={hiddenEdgeCount}+ onInit={setReactFlowInstance}+ onNodeClick={handleNodeClick}+ onNodeDoubleClick={handleNodeDoubleClick}+ onPaneClick={handlePaneClick}+ errorTitle="Couldn't load the architecture map"+ loadingLabel="Loading architecture…"+ >+ <Sidebar />+ <FilterPanel />+ <CodeViewer fetchContent={fetchContent} />+ {pathFinderOpen && <PathFinderModal />}+ </ArchCanvas>+ </div>+ </div>+ );+}++interface ArchitectureData {+ view: ArchitectureView | null;+ error: Error | null;+ loading: boolean;+}++/** One architectureView() call, refetched when the index moves. */+function useArchitectureData(host: WebviewHost, refreshToken: number): ArchitectureData {+ const [state, setState] = useState<ArchitectureData>({+ view: null,+ error: null,+ loading: true,+ });++ useEffect(() => {+ let cancelled = false;+ setState((s) => ({ ...s, loading: true, error: null }));+ host.api.architectureView().then(+ (view) => {+ if (!cancelled) setState({ view, error: null, loading: false });+ },+ (err: unknown) => {+ if (!cancelled) {+ setState({+ view: null,+ error: err instanceof Error ? err : new Error(String(err)),+ loading: false,+ });+ }+ },+ );+ return () => {+ cancelled = true;+ };+ }, [host, refreshToken]);++ return state;+}diff --git a/packages/vscode/webview/src/views/architecture/main.tsx b/packages/vscode/webview/src/views/architecture/main.tsxnew file mode 100644index 000000000..5617bbfa9--- /dev/null+++ b/packages/vscode/webview/src/views/architecture/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("architecture", App);diff --git a/packages/vscode/webview/src/views/decisions/App.test.tsx b/packages/vscode/webview/src/views/decisions/App.test.tsxnew file mode 100644index 000000000..3f05a1c19--- /dev/null+++ b/packages/vscode/webview/src/views/decisions/App.test.tsx@@ -0,0 +1,77 @@+import { describe, it, expect, vi, afterEach } from "vitest";+import { render, screen, fireEvent, cleanup } from "@testing-library/react";+import { App } from "./App";+import type { WebviewHost } from "../../runtime/rpc";+import type { RepoInit } from "../../../../src/shared/webviewMessages";+import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";++function decision(over: Partial<DecisionRecordResponse>): DecisionRecordResponse {+ return {+ id: "d",+ repository_id: "r1",+ title: "Untitled",+ status: "active",+ context: "",+ decision: "",+ rationale: "",+ alternatives: [],+ consequences: [],+ affected_files: [],+ affected_modules: [],+ tags: [],+ source: "cli",+ evidence_commits: [],+ evidence_file: null,+ evidence_line: null,+ confidence: 1,+ staleness_score: 0,+ superseded_by: null,+ last_code_change: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...over,+ };+}++const DECISIONS: DecisionRecordResponse[] = [+ decision({ id: "a", title: "Adopt hexagonal ports", status: "active", context: "We split the app." }),+ decision({ id: "b", title: "Deprecate the legacy client", status: "deprecated" }),+];++const REPO: RepoInit = { id: "r1", name: "repo", headCommit: null, defaultBranch: "main" };++function makeHost(list: DecisionRecordResponse[]): WebviewHost {+ return {+ api: { decisionsList: vi.fn().mockResolvedValue(list) } as unknown as WebviewHost["api"],+ onInit: () => () => {},+ onRefresh: () => () => {},+ ready: () => {},+ openFile: () => {},+ copyText: () => {},+ openExternal: () => {},+ };+}++describe("decisions App", () => {+ afterEach(() => cleanup());++ it("renders decision items and the detail pane", async () => {+ render(<App host={makeHost(DECISIONS)} repo={REPO} params={{}} refreshToken={0} />);++ // The first record shows in both the list and the auto-selected detail pane.+ expect((await screen.findAllByText("Adopt hexagonal ports")).length).toBeGreaterThan(0);+ expect(screen.getByText("Deprecate the legacy client")).toBeTruthy();+ // First record auto-selects; its context markdown shows in the detail pane.+ expect(screen.getByText("We split the app.")).toBeTruthy();+ });++ it("filters the list by status chip", async () => {+ render(<App host={makeHost(DECISIONS)} repo={REPO} params={{}} refreshToken={0} />);+ await screen.findAllByText("Adopt hexagonal ports");++ fireEvent.click(screen.getByRole("button", { name: /^Deprecated/ }));++ expect(screen.queryByText("Adopt hexagonal ports")).toBeNull();+ expect(screen.getAllByText("Deprecate the legacy client").length).toBeGreaterThan(0);+ });+});diff --git a/packages/vscode/webview/src/views/decisions/App.tsx b/packages/vscode/webview/src/views/decisions/App.tsxnew file mode 100644index 000000000..e76a28b9d--- /dev/null+++ b/packages/vscode/webview/src/views/decisions/App.tsx@@ -0,0 +1,321 @@+import { useEffect, useMemo, useState } from "react";+import { FileText, Landmark, Lightbulb } from "lucide-react";+import { Badge, Card, CardContent } from "@repowise-dev/ui/ui";+import { EmptyState } from "@repowise-dev/ui/shared";+import { WikiMarkdown } from "@repowise-dev/ui/wiki/wiki-markdown";+import { formatRelativeTime, stripMarkdown } from "@repowise-dev/ui/lib/format";+import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";+import type { ViewProps } from "../../runtime/mount";++type Status = DecisionRecordResponse["status"];++const STATUS_ORDER: readonly Status[] = ["active", "proposed", "deprecated", "superseded"];++/** Left dot / accent per status, matching the shared decisions widget. */+const STATUS_DOT: Record<Status, string> = {+ active: "var(--color-success)",+ proposed: "var(--color-info)",+ deprecated: "var(--color-error)",+ superseded: "var(--color-text-tertiary)",+};++function statusLabel(status: Status): string {+ return status.charAt(0).toUpperCase() + status.slice(1);+}++function StatusBadge({ status }: { status: Status }) {+ const color = STATUS_DOT[status];+ return (+ <span+ className="inline-flex items-center rounded border px-2 py-0.5 text-[11px] font-medium"+ style={{ color, borderColor: `color-mix(in srgb, ${color} 35%, transparent)` }}+ >+ {statusLabel(status)}+ </span>+ );+}++function recencyKey(d: DecisionRecordResponse): number {+ const raw = d.updated_at || d.created_at;+ const t = raw ? new Date(raw).getTime() : 0;+ return Number.isNaN(t) ? 0 : t;+}++export function App({ host, refreshToken }: ViewProps<"decisions">) {+ const [decisions, setDecisions] = useState<DecisionRecordResponse[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [filter, setFilter] = useState<Status | "all">("all");+ const [selectedId, setSelectedId] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ setError(null);+ host.api+ .decisionsList()+ .then((list) => {+ if (cancelled) return;+ const sorted = [...list].sort((a, b) => recencyKey(b) - recencyKey(a));+ setDecisions(sorted);+ setSelectedId((prev) =>+ prev && sorted.some((d) => d.id === prev) ? prev : (sorted[0]?.id ?? null),+ );+ })+ .catch((err: unknown) => {+ if (cancelled) return;+ setError(err instanceof Error ? err.message : "Could not load decisions.");+ });+ return () => {+ cancelled = true;+ };+ }, [host, refreshToken]);++ const counts = useMemo(() => {+ const c = new Map<Status, number>();+ for (const d of decisions ?? []) c.set(d.status, (c.get(d.status) ?? 0) + 1);+ return c;+ }, [decisions]);++ const visible = useMemo(+ () => (decisions ?? []).filter((d) => filter === "all" || d.status === filter),+ [decisions, filter],+ );++ const selected = useMemo(+ () => visible.find((d) => d.id === selectedId) ?? visible[0] ?? null,+ [visible, selectedId],+ );++ if (error) {+ return (+ <div className="p-6">+ <EmptyState+ icon={<Lightbulb className="h-8 w-8" />}+ title="Could not load decisions"+ description={error}+ />+ </div>+ );+ }++ if (decisions === null) {+ return (+ <div className="flex h-screen items-center justify-center text-[var(--color-text-tertiary)]">+ Loading decisions…+ </div>+ );+ }++ if (decisions.length === 0) {+ return (+ <div className="p-6">+ <EmptyState+ icon={<Lightbulb className="h-8 w-8" />}+ title="No decisions recorded"+ description="No architectural decisions have been detected in this repository yet."+ />+ </div>+ );+ }++ const chips: Array<{ key: Status | "all"; label: string; count: number }> = [+ { key: "all", label: "All", count: decisions.length },+ ...STATUS_ORDER.filter((s) => (counts.get(s) ?? 0) > 0).map((s) => ({+ key: s,+ label: statusLabel(s),+ count: counts.get(s) ?? 0,+ })),+ ];++ return (+ <div className="flex h-screen flex-col">+ <header className="border-b border-[var(--color-border-default)] px-6 py-4">+ <h1 className="flex items-center gap-2 text-lg font-semibold text-[var(--color-text-primary)]">+ <Landmark className="h-5 w-5 text-[var(--color-text-secondary)]" />+ Decisions+ </h1>+ <div className="mt-3 flex flex-wrap gap-2">+ {chips.map((chip) => {+ const on = filter === chip.key;+ return (+ <button+ key={chip.key}+ type="button"+ onClick={() => setFilter(chip.key)}+ className={+ "inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors " ++ (on+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-hover)]")+ }+ >+ {chip.label}+ <span className="text-[var(--color-text-tertiary)]">{chip.count}</span>+ </button>+ );+ })}+ </div>+ </header>++ <div className="flex min-h-0 flex-1">+ <ul className="w-80 shrink-0 overflow-y-auto border-r border-[var(--color-border-default)] p-3">+ {visible.map((d) => {+ const on = selected?.id === d.id;+ return (+ <li key={d.id}>+ <button+ type="button"+ onClick={() => setSelectedId(d.id)}+ className={+ "flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors " ++ (on+ ? "bg-[var(--color-bg-elevated)]"+ : "hover:bg-[var(--color-bg-elevated)]")+ }+ >+ <span+ className="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full"+ style={{ backgroundColor: STATUS_DOT[d.status] }}+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-[var(--color-text-primary)]">+ {stripMarkdown(d.title)}+ </span>+ <span className="mt-0.5 block text-[11px] text-[var(--color-text-tertiary)]">+ {formatRelativeTime(d.updated_at || d.created_at)}+ {d.source ? ` · ${d.source.replace(/_/g, " ")}` : ""}+ </span>+ </span>+ </button>+ </li>+ );+ })}+ </ul>++ <div className="min-w-0 flex-1 overflow-y-auto p-6">+ {selected ? <Detail host={host} decision={selected} /> : null}+ </div>+ </div>+ </div>+ );+}++function Detail({+ host,+ decision,+}: {+ host: ViewProps<"decisions">["host"];+ decision: DecisionRecordResponse;+}) {+ const sections: Array<{ heading: string; body: string }> = [+ { heading: "Context", body: decision.context },+ { heading: "Decision", body: decision.decision },+ { heading: "Rationale", body: decision.rationale },+ ].filter((s) => s.body && s.body.trim().length > 0);++ return (+ <article className="mx-auto max-w-2xl space-y-5">+ <div className="space-y-3">+ <StatusBadge status={decision.status} />+ <h2 className="text-xl font-semibold leading-snug text-[var(--color-text-primary)]">+ {stripMarkdown(decision.title)}+ </h2>+ {decision.tags.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {decision.tags.map((tag) => (+ <Badge key={tag} variant="outline">+ {tag}+ </Badge>+ ))}+ </div>+ )}+ </div>++ {sections.map((s) => (+ <section key={s.heading} className="space-y-1.5">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {s.heading}+ </h3>+ <div className="prose-sm max-w-none text-sm text-[var(--color-text-secondary)]">+ <WikiMarkdown content={s.body} />+ </div>+ </section>+ ))}++ {decision.alternatives.length > 0 && (+ <ListSection heading="Alternatives considered" items={decision.alternatives} />+ )}+ {decision.consequences.length > 0 && (+ <ListSection heading="Consequences" items={decision.consequences} />+ )}++ {decision.affected_files.length > 0 && (+ <section className="space-y-1.5">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">+ Affected files+ </h3>+ <ul className="space-y-1">+ {decision.affected_files.map((path) => (+ <li key={path}>+ <FileRef host={host} path={path} />+ </li>+ ))}+ </ul>+ </section>+ )}++ {decision.evidence_file && (+ <Card>+ <CardContent className="py-3">+ <h3 className="mb-1.5 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">+ Evidence+ </h3>+ <FileRef+ host={host}+ path={decision.evidence_file}+ line={decision.evidence_line ?? undefined}+ />+ </CardContent>+ </Card>+ )}+ </article>+ );+}++function ListSection({ heading, items }: { heading: string; items: string[] }) {+ return (+ <section className="space-y-1.5">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {heading}+ </h3>+ <ul className="list-disc space-y-1 pl-5 text-sm text-[var(--color-text-secondary)]">+ {items.map((item, i) => (+ <li key={i}>{item}</li>+ ))}+ </ul>+ </section>+ );+}++function FileRef({+ host,+ path,+ line,+}: {+ host: ViewProps<"decisions">["host"];+ path: string;+ line?: number;+}) {+ return (+ <button+ type="button"+ onClick={() => host.openFile(path, line)}+ className="inline-flex items-center gap-1.5 text-sm text-[var(--color-accent-primary)] hover:underline"+ >+ <FileText className="h-3.5 w-3.5 shrink-0" />+ <span className="break-all text-left">+ {path}+ {line != null ? `:${line}` : ""}+ </span>+ </button>+ );+}diff --git a/packages/vscode/webview/src/views/decisions/main.tsx b/packages/vscode/webview/src/views/decisions/main.tsxnew file mode 100644index 000000000..d123ff637--- /dev/null+++ b/packages/vscode/webview/src/views/decisions/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("decisions", App);diff --git a/packages/vscode/webview/src/views/docs/App.test.tsx b/packages/vscode/webview/src/views/docs/App.test.tsxnew file mode 100644index 000000000..a0d631bbe--- /dev/null+++ b/packages/vscode/webview/src/views/docs/App.test.tsx@@ -0,0 +1,103 @@+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import type { DocPage } from "@repowise-dev/types/docs";+import type { WebviewHost } from "../../runtime/rpc";+import { App } from "./App";++// jsdom omits a couple of browser APIs the shared reader touches (the table of+// contents observes headings; the reader scrolls to top on page change). Stub+// them so mounting DocsReader doesn't throw.+beforeAll(() => {+ Element.prototype.scrollTo = vi.fn();+ class NoopObserver {+ observe(): void {}+ unobserve(): void {}+ disconnect(): void {}+ takeRecords(): [] {+ return [];+ }+ }+ (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver = NoopObserver;+});++afterEach(cleanup);++function makePage(overrides: Partial<DocPage>): DocPage {+ return {+ id: "id",+ repository_id: "repo-1",+ page_type: "file_page",+ title: "Untitled",+ content: "",+ target_path: "",+ source_hash: "hash",+ model_name: "test-model",+ provider_name: "test",+ input_tokens: 100,+ output_tokens: 200,+ cached_tokens: 0,+ generation_level: 0,+ version: 1,+ confidence: 1,+ freshness_status: "fresh",+ metadata: {},+ human_notes: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++const PAGES: DocPage[] = [+ makePage({+ id: "ov",+ page_type: "repo_overview",+ title: "Project Overview",+ target_path: "",+ content: "# Project Overview\n\nOverview intro paragraph rendered by the reader.",+ }),+ makePage({+ id: "fp",+ page_type: "file_page",+ title: "app.ts",+ target_path: "src/app.ts",+ content: "# app.ts\n\nThe application entry point.",+ }),+];++function mockHost(pages: DocPage[]): WebviewHost {+ return {+ api: {+ pagesList: vi.fn().mockResolvedValue(pages),+ fileDetail: vi.fn(),+ } as unknown as WebviewHost["api"],+ onInit: () => () => {},+ onRefresh: () => () => {},+ ready: () => {},+ openFile: vi.fn(),+ copyText: vi.fn(),+ openExternal: vi.fn(),+ };+}++describe("docs App", () => {+ it("renders the page tree and the selected page's markdown", async () => {+ const host = mockHost(PAGES);+ render(+ <App+ host={host}+ repo={{ id: "repo-1", name: "demo", headCommit: null, defaultBranch: null }}+ params={{}}+ refreshToken={0}+ />,+ );++ // Tree lists both pages (file leaf shows its basename).+ expect(await screen.findByText("app.ts")).toBeTruthy();++ // With no params, the reader lands on the repo overview page.+ expect(+ await screen.findByText("Overview intro paragraph rendered by the reader."),+ ).toBeTruthy();+ });+});diff --git a/packages/vscode/webview/src/views/docs/App.tsx b/packages/vscode/webview/src/views/docs/App.tsxnew file mode 100644index 000000000..9984cc8c8--- /dev/null+++ b/packages/vscode/webview/src/views/docs/App.tsx@@ -0,0 +1,261 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ AlertCircle,+ BookOpen,+ FileCode,+ Loader2,+ PanelLeft,+ PanelLeftClose,+} from "lucide-react";+import type { DocPage } from "@repowise-dev/types/docs";+import { DocsTree } from "@repowise-dev/ui/docs/docs-tree";+import { DocsReader, type ReaderLinkComponent } from "@repowise-dev/ui/docs/docs-reader";+import { DEFAULT_PERSONA } from "@repowise-dev/ui/docs/reader-persona";+import type { ViewProps } from "../../runtime/mount";+import type { WebviewHost } from "../../runtime/rpc";++/**+ * Docs browser panel: a page tree on the left and the shared wiki reader on+ * the right. Pages ship with their markdown inline on `pagesList()`, so the+ * tree data and the reading pane draw from one fetch; only initial file->page+ * resolution needs a second call.+ */+export function App({ host, repo, params, refreshToken }: ViewProps<"docs">) {+ const [pages, setPages] = useState<DocPage[] | null>(null);+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [treeOpen, setTreeOpen] = useState(true);+ // Initial page is resolved once per mount; a refresh refetch must not yank+ // the reader back to the overview while the user is mid-read.+ const resolvedRef = useRef(false);++ const resolveInitial = useCallback(+ async (docs: DocPage[]): Promise<string | null> => {+ if (params.pageId) return params.pageId;+ if (params.filePath) {+ const byPath = docs.find((p) => p.target_path === params.filePath);+ if (byPath) return byPath.id;+ try {+ const detail = await host.api.fileDetail(params.filePath);+ if (detail.wiki_page) return detail.wiki_page.id;+ } catch {+ // No page for this file; land on the overview instead.+ }+ }+ const overview = docs.find((p) => p.page_type === "repo_overview");+ return overview?.id ?? docs[0]?.id ?? null;+ },+ [host, params.pageId, params.filePath],+ );++ useEffect(() => {+ let cancelled = false;+ setError(null);+ host.api+ .pagesList()+ .then(async (list) => {+ if (cancelled) return;+ const docs = list as unknown as DocPage[];+ setPages(docs);+ if (resolvedRef.current) return;+ resolvedRef.current = true;+ const initial = await resolveInitial(docs);+ if (!cancelled) setSelectedId(initial);+ })+ .catch((err: unknown) => {+ if (!cancelled) setError(err instanceof Error ? err.message : String(err));+ });+ return () => {+ cancelled = true;+ };+ }, [host, refreshToken, resolveInitial]);++ const selectedPage = useMemo(+ () => (pages && selectedId ? pages.find((p) => p.id === selectedId) ?? null : null),+ [pages, selectedId],+ );++ const navigate = useCallback((pageId: string) => setSelectedId(pageId), []);++ // Backlink anchors carry ``?page=`` hrefs; intercept plain clicks for+ // in-panel nav and route real URLs to the editor's external handler.+ const LinkComponent = useMemo<ReaderLinkComponent>(+ () => makeLink(host, navigate),+ [host, navigate],+ );++ const buildPageHref = useCallback(+ (pageId: string) => `?page=${encodeURIComponent(pageId)}`,+ [],+ );++ // Markdown external links render as bare anchors (target=_blank) that the+ // reader does not own; hand http(s) clicks to the editor so they open in the+ // system browser rather than trying to navigate the webview.+ const onPaneClickCapture = useCallback(+ (event: React.MouseEvent) => {+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return;+ const anchor = (event.target as HTMLElement).closest("a");+ const href = anchor?.getAttribute("href");+ if (href && /^https?:\/\//i.test(href)) {+ event.preventDefault();+ host.openExternal(href);+ }+ },+ [host],+ );++ if (error) {+ return (+ <CenteredState+ icon={<AlertCircle className="h-8 w-8 text-[var(--color-error)]" />}+ title="Could not load docs"+ detail={error}+ />+ );+ }++ if (!pages) {+ return (+ <CenteredState+ icon={<Loader2 className="h-6 w-6 animate-spin text-[var(--color-accent-primary)]" />}+ title="Loading docs…"+ />+ );+ }++ if (pages.length === 0) {+ return (+ <CenteredState+ icon={<BookOpen className="h-8 w-8 text-[var(--color-text-tertiary)]" />}+ title="No documentation yet"+ detail="Run a Repowise generation for this repository to browse its docs here."+ />+ );+ }++ const sourcePath =+ selectedPage?.page_type === "file_page" && selectedPage.target_path+ ? selectedPage.target_path+ : null;++ return (+ <div className="flex h-screen bg-[var(--color-bg-root)]">+ {treeOpen && (+ <aside className="w-[280px] shrink-0 border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">+ <DocsTree+ pages={pages}+ selectedPageId={selectedId}+ onSelectPage={(page) => setSelectedId(page.id)}+ />+ </aside>+ )}++ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex items-center gap-2 border-b border-[var(--color-border-default)] px-3 py-2">+ <button+ onClick={() => setTreeOpen((open) => !open)}+ aria-label={treeOpen ? "Hide pages" : "Show pages"}+ aria-expanded={treeOpen}+ className="rounded-md p-1 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ >+ {treeOpen ? (+ <PanelLeftClose className="h-4 w-4" />+ ) : (+ <PanelLeft className="h-4 w-4" />+ )}+ </button>+ <span className="truncate text-xs font-medium text-[var(--color-text-secondary)]">+ {repo.name}+ </span>+ <div className="flex-1" />+ {sourcePath && (+ <button+ onClick={() => host.openFile(sourcePath)}+ className="flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-accent)] hover:text-[var(--color-accent-primary)]"+ >+ <FileCode className="h-3.5 w-3.5" />+ Open source file+ </button>+ )}+ </div>++ <div className="min-h-0 flex-1" onClickCapture={onPaneClickCapture}>+ <DocsReader+ page={selectedPage}+ pages={pages}+ repoId={repo.id}+ onSelectPage={(page) => setSelectedId(page.id)}+ onNavigatePageId={navigate}+ persona={DEFAULT_PERSONA}+ sidebarOpen+ buildPageHref={buildPageHref}+ LinkComponent={LinkComponent}+ />+ </div>+ </div>+ </div>+ );+}++/** Anchor that keeps in-panel navigation local and defers real URLs to the host. */+function makeLink(host: WebviewHost, navigate: (pageId: string) => void): ReaderLinkComponent {+ return function PanelLink({+ href,+ className,+ title,+ children,+ }: {+ href: string;+ className?: string;+ title?: string;+ children: React.ReactNode;+ }) {+ return (+ <a+ href={href}+ className={className}+ title={title}+ onClick={(event) => {+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return;+ if (/^https?:\/\//i.test(href)) {+ event.preventDefault();+ host.openExternal(href);+ return;+ }+ try {+ const pid = new URL(href, window.location.href).searchParams.get("page");+ if (pid) {+ event.preventDefault();+ navigate(pid);+ }+ } catch {+ // Malformed href: fall through to default navigation.+ }+ }}+ >+ {children}+ </a>+ );+ };+}++function CenteredState({+ icon,+ title,+ detail,+}: {+ icon: React.ReactNode;+ title: string;+ detail?: string;+}) {+ return (+ <div className="flex h-screen flex-col items-center justify-center gap-3 px-8 text-center">+ {icon}+ <p className="text-sm font-semibold text-[var(--color-text-primary)]">{title}</p>+ {detail && (+ <p className="max-w-sm text-xs text-[var(--color-text-secondary)]">{detail}</p>+ )}+ </div>+ );+}diff --git a/packages/vscode/webview/src/views/docs/main.tsx b/packages/vscode/webview/src/views/docs/main.tsxnew file mode 100644index 000000000..e133f054f--- /dev/null+++ b/packages/vscode/webview/src/views/docs/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("docs", App);diff --git a/packages/vscode/webview/src/views/graph/App.test.tsx b/packages/vscode/webview/src/views/graph/App.test.tsxnew file mode 100644index 000000000..b02501a6a--- /dev/null+++ b/packages/vscode/webview/src/views/graph/App.test.tsx@@ -0,0 +1,89 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, render, renderHook, screen } from "@testing-library/react";++afterEach(cleanup);+import type { WebviewHost } from "../../runtime/rpc";+import { useGraphData } from "./use-graph-data";+import { GraphHeader } from "./graph-header";++/** A WebviewHost whose every api method is a vi.fn resolving to empty data, so a+ * test can assert exactly which slices a scope requested. */+function mockHost(): { host: WebviewHost; api: Record<string, ReturnType<typeof vi.fn>> } {+ const api = {+ moduleGraph: vi.fn().mockResolvedValue({ nodes: [], edges: [] }),+ fullGraph: vi.fn().mockResolvedValue({ nodes: [], links: [] }),+ architectureCommunityGraph: vi.fn().mockResolvedValue({ nodes: [], edges: [] }),+ communities: vi.fn().mockResolvedValue([]),+ communitySlice: vi+ .fn()+ .mockResolvedValue({ nodes: [], links: [], community_id: 0, member_count: 0 }),+ deadCodeGraph: vi.fn().mockResolvedValue({ nodes: [], links: [] }),+ hotFilesGraph: vi.fn().mockResolvedValue({ nodes: [], links: [] }),+ executionFlows: vi.fn().mockResolvedValue({ total_entry_points: 0, flows: [] }),+ };+ const host = {+ api: api as unknown as WebviewHost["api"],+ onInit: () => () => {},+ onRefresh: () => () => {},+ ready: () => {},+ openFile: vi.fn(),+ copyText: vi.fn(),+ openExternal: vi.fn(),+ } satisfies WebviewHost;+ return { host, api };+}++describe("useGraphData", () => {+ it("requests only the constellation scope on mount", () => {+ const { host, api } = mockHost();+ renderHook(() => useGraphData(host, 0));++ // Default scope = radial community constellation.+ expect(api.architectureCommunityGraph).toHaveBeenCalledTimes(1);+ expect(api.communities).toHaveBeenCalledTimes(1);++ // Nothing that a different scope renders is fetched upfront.+ expect(api.moduleGraph).not.toHaveBeenCalled();+ expect(api.fullGraph).not.toHaveBeenCalled();+ expect(api.deadCodeGraph).not.toHaveBeenCalled();+ expect(api.hotFilesGraph).not.toHaveBeenCalled();+ expect(api.executionFlows).not.toHaveBeenCalled();+ expect(api.communitySlice).not.toHaveBeenCalled();+ });++ it("fetches the file graph and flows only on switch to the full scope", () => {+ const { host, api } = mockHost();+ const { result } = renderHook(() => useGraphData(host, 0));++ expect(api.fullGraph).not.toHaveBeenCalled();++ act(() => result.current.setViewMode("full"));++ expect(api.fullGraph).toHaveBeenCalledTimes(1);+ expect(api.executionFlows).toHaveBeenCalledTimes(1);+ // The constellation graph is not refetched on the switch.+ expect(api.architectureCommunityGraph).toHaveBeenCalledTimes(1);+ });++ it("fetches a slice for each newly-expanded hub exactly once", () => {+ const { host, api } = mockHost();+ const { result } = renderHook(() => useGraphData(host, 0));++ act(() => result.current.setExpandedHubs([1, 2]));+ expect(api.communitySlice).toHaveBeenCalledTimes(2);++ // Re-expanding an already-loaded hub does not refetch it.+ act(() => result.current.setExpandedHubs([1, 2, 3]));+ expect(api.communitySlice).toHaveBeenCalledTimes(3);+ });+});++describe("GraphHeader", () => {+ it("renders the repo name and node/edge counts", () => {+ render(<GraphHeader repoName="acme/repo" stats={{ nodes: 2048, edges: 5120 }} />);+ expect(screen.getByText("Knowledge Graph")).toBeTruthy();+ expect(screen.getByText("acme/repo")).toBeTruthy();+ expect(screen.getByText("2,048")).toBeTruthy();+ expect(screen.getByText("5,120")).toBeTruthy();+ });+});diff --git a/packages/vscode/webview/src/views/graph/App.tsx b/packages/vscode/webview/src/views/graph/App.tsxnew file mode 100644index 000000000..f0bd707ce--- /dev/null+++ b/packages/vscode/webview/src/views/graph/App.tsx@@ -0,0 +1,97 @@+/**+ * Knowledge Graph webview: mounts the shared radial-constellation GraphFlow+ * shell against host RPC data. The shell keeps its own toolbar/legend/controls;+ * this view adds only a slim header and wires the shell's structural callbacks+ * back into the lazy data hook so scope changes fetch just what they render.+ */++import { useCallback } from "react";+import {+ GraphFlow,+ type GraphFlowProps as GraphFlowShellProps,+} from "@repowise-dev/ui/graph/graph-flow";+import type {+ ArchitectureGraph,+ CommunitySlice,+ CommunitySummaryItem,+ ExecutionFlows,+ GraphExport,+ ModuleGraph,+} from "@repowise-dev/types/graph";+import type { ViewProps } from "../../runtime/mount";+import { useGraphData } from "./use-graph-data";+import { GraphHeader } from "./graph-header";++/** Hub (`__community__N`) and repo-core (`__repo_core__`) ids are synthetic and+ * not backed by a file; everything else the shell hands us is a repo path. */+function isFileBackedNodeId(nodeId: string): boolean {+ return !nodeId.startsWith("__");+}++export function App({ host, params, repo, refreshToken }: ViewProps<"graph">) {+ const data = useGraphData(host, refreshToken);++ const openIfFile = useCallback(+ (nodeId: string) => {+ if (isFileBackedNodeId(nodeId)) host.openFile(nodeId);+ },+ [host],+ );++ const handleNodeClick = useCallback<NonNullable<GraphFlowShellProps["onNodeClick"]>>(+ (nodeId, nodeType) => {+ if (nodeType === "file") host.openFile(nodeId);+ },+ [host],+ );++ return (+ <div className="flex h-screen flex-col">+ <GraphHeader repoName={repo.name} stats={data.stats} />+ <div className="relative min-h-0 flex-1">+ {data.error ? (+ <div className="flex h-full items-center justify-center p-6">+ <div className="max-w-md rounded-lg border border-[var(--color-error)] bg-[var(--color-bg-elevated)] p-4 text-sm">+ <p className="font-medium text-[var(--color-error)]">+ Could not load the knowledge graph.+ </p>+ <p className="mt-2 text-[var(--color-text-secondary)]">{data.error}</p>+ </div>+ </div>+ ) : (+ <GraphFlow+ moduleGraph={data.moduleGraph as ModuleGraph | undefined}+ isLoadingModuleGraph={data.isLoadingModuleGraph}+ fullGraph={data.fullGraph as GraphExport | undefined}+ isLoadingFullGraph={data.isLoadingFullGraph}+ // Legacy file-level architecture graph is unused by the constellation+ // scope; the ui prop is still required, so pass an empty pair.+ architectureGraph={undefined}+ isLoadingArchitectureGraph={false}+ constellationGraph={data.constellationGraph as ArchitectureGraph | undefined}+ isLoadingConstellationGraph={data.isLoadingConstellationGraph}+ constellationSlices={+ data.constellationSlices as Map<number, CommunitySlice>+ }+ onExpandedHubsChange={data.setExpandedHubs}+ repoName={repo.name}+ deadCodeGraph={data.deadCodeGraph as GraphExport | undefined}+ isLoadingDeadCodeGraph={data.isLoadingDeadCodeGraph}+ hotFilesGraph={data.hotFilesGraph as GraphExport | undefined}+ isLoadingHotFilesGraph={data.isLoadingHotFilesGraph}+ communities={data.communities as CommunitySummaryItem[] | undefined}+ executionFlows={data.executionFlows as ExecutionFlows | undefined}+ initialSelectedNode={params.selectNode ?? null}+ onViewModeChange={data.setViewMode}+ onModulePathChange={data.setModulePath}+ onExpandedModulesChange={(expanded) =>+ data.setHasExpandedModules(expanded.size > 0)+ }+ onNodeClick={handleNodeClick}+ onNodeViewDocs={openIfFile}+ />+ )}+ </div>+ </div>+ );+}diff --git a/packages/vscode/webview/src/views/graph/graph-header.tsx b/packages/vscode/webview/src/views/graph/graph-header.tsxnew file mode 100644index 000000000..ead4ae011--- /dev/null+++ b/packages/vscode/webview/src/views/graph/graph-header.tsx@@ -0,0 +1,37 @@+/** Slim chrome above the graph canvas: repo name plus live node/edge counts. */++export interface GraphHeaderProps {+ repoName: string;+ stats: { nodes: number; edges: number } | null;+}++export function GraphHeader({ repoName, stats }: GraphHeaderProps) {+ return (+ <header className="flex shrink-0 items-center justify-between gap-3 border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-2">+ <div className="flex min-w-0 items-center gap-2">+ <span className="text-sm font-medium text-[var(--color-text-primary)]">+ Knowledge Graph+ </span>+ <span className="truncate text-xs text-[var(--color-text-tertiary)]">+ {repoName}+ </span>+ </div>+ {stats && (+ <div className="flex shrink-0 items-center gap-3 text-xs text-[var(--color-text-tertiary)]">+ <span>+ <span className="font-medium text-[var(--color-text-secondary)]">+ {stats.nodes.toLocaleString()}+ </span>{" "}+ nodes+ </span>+ <span>+ <span className="font-medium text-[var(--color-text-secondary)]">+ {stats.edges.toLocaleString()}+ </span>{" "}+ edges+ </span>+ </div>+ )}+ </header>+ );+}diff --git a/packages/vscode/webview/src/views/graph/main.tsx b/packages/vscode/webview/src/views/graph/main.tsxnew file mode 100644index 000000000..df3bfae12--- /dev/null+++ b/packages/vscode/webview/src/views/graph/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("graph", App);diff --git a/packages/vscode/webview/src/views/graph/use-graph-data.ts b/packages/vscode/webview/src/views/graph/use-graph-data.tsnew file mode 100644index 000000000..facd65198--- /dev/null+++ b/packages/vscode/webview/src/views/graph/use-graph-data.ts@@ -0,0 +1,273 @@+/**+ * Data orchestration for the Knowledge Graph webview.+ *+ * The web page fetches every graph slice through SWR hooks; a webview never+ * fetches, so this reimplements that orchestration against the typed host RPC+ * with plain React state. It is deliberately LAZY: this panel runs on a+ * 2,000+ node index, so each slice is requested only when the view mode that+ * renders it becomes active, and each slice is fetched at most once (a ref+ * guard survives StrictMode's double-invoke). The default mode is the radial+ * community constellation, so a fresh mount touches only the community+ * super-graph and the community summaries.+ */++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { WebviewHost } from "../../runtime/rpc";+import type {+ ArchitectureGraph,+ CommunitySlice,+ CommunitySummaryItem,+ ExecutionFlows,+ GraphExport,+ ModuleGraph,+} from "@repowise-dev/types/graph";++export type ViewMode =+ | "module"+ | "full"+ | "architecture"+ | "dead"+ | "hotfiles"+ | "unified";++/** Default scope: the radial community constellation (matches the ui shell). */+const DEFAULT_VIEW_MODE: ViewMode = "architecture";++export interface GraphData {+ moduleGraph: ModuleGraph | undefined;+ isLoadingModuleGraph: boolean;+ fullGraph: GraphExport | undefined;+ isLoadingFullGraph: boolean;+ constellationGraph: ArchitectureGraph | undefined;+ isLoadingConstellationGraph: boolean;+ constellationSlices: Map<number, CommunitySlice>;+ deadCodeGraph: GraphExport | undefined;+ isLoadingDeadCodeGraph: boolean;+ hotFilesGraph: GraphExport | undefined;+ isLoadingHotFilesGraph: boolean;+ communities: CommunitySummaryItem[] | undefined;+ executionFlows: ExecutionFlows | undefined;+ /** First error hit while loading the active scope, already user-presentable. */+ error: string | null;+ /** Node/edge counts of the graph the active scope renders (header chrome). */+ stats: { nodes: number; edges: number } | null;+ viewMode: ViewMode;+ setViewMode: (mode: ViewMode) => void;+ /** Legacy breadcrumb drill-down state, owned by the ui shell. */+ setModulePath: (path: string[]) => void;+ setHasExpandedModules: (expanded: boolean) => void;+ /** Currently-expanded constellation hubs; drives the incremental slice fetch. */+ setExpandedHubs: (ids: number[]) => void;+}++/**+ * A single lazily-loaded slice: fetched once when {@link enabled} first turns+ * true, and re-fetched whenever {@link resetToken} changes (index moved).+ */+function useHostSlice<T>(+ enabled: boolean,+ resetToken: number,+ fetcher: () => Promise<T>,+ onError: (message: string) => void,+): { data: T | undefined; isLoading: boolean } {+ const [data, setData] = useState<T | undefined>(undefined);+ const [isLoading, setIsLoading] = useState(false);+ const requested = useRef(false);++ // The index moved under the panel: drop the cache so the gate below refetches.+ // Declared before the fetch effect so it resets `requested` first on a reset.+ useEffect(() => {+ requested.current = false;+ setData(undefined);+ setIsLoading(false);+ }, [resetToken]);++ useEffect(() => {+ if (!enabled || requested.current) return;+ requested.current = true;+ setIsLoading(true);+ let cancelled = false;+ void fetcher()+ .then((value) => {+ if (!cancelled) setData(value);+ })+ .catch((err: unknown) => {+ if (!cancelled) onError(err instanceof Error ? err.message : String(err));+ })+ .finally(() => {+ if (!cancelled) setIsLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [enabled, resetToken, fetcher, onError]);++ return { data, isLoading };+}++export function useGraphData(host: WebviewHost, refreshToken: number): GraphData {+ const [viewMode, setViewMode] = useState<ViewMode>(DEFAULT_VIEW_MODE);+ const [modulePath, setModulePath] = useState<string[]>([]);+ const [hasExpandedModules, setHasExpandedModules] = useState(false);+ const [expandedHubs, setExpandedHubs] = useState<number[]>([]);+ const [error, setError] = useState<string | null>(null);++ const onError = useCallback((message: string) => setError(message), []);++ // Clear the surfaced error whenever the scope changes or the index moves, so+ // a stale message never lingers over a healthy view.+ useEffect(() => {+ setError(null);+ }, [viewMode, refreshToken]);++ const isDrilledDown = modulePath.length > 0;+ // The full file graph backs the drill-down, the flat file/unified scopes, and+ // module expansion; execution flows only trace a file-level path, so they+ // ride the same gate rather than fetching on the constellation mount.+ const needsFullGraph =+ isDrilledDown ||+ viewMode === "full" ||+ viewMode === "unified" ||+ hasExpandedModules;++ // Stable fetchers (host is created once at mount) so the slice effects don't+ // re-run on every render.+ const fetchModuleGraph = useCallback(() => host.api.moduleGraph(), [host]);+ const fetchFullGraph = useCallback(() => host.api.fullGraph(), [host]);+ const fetchConstellation = useCallback(+ () => host.api.architectureCommunityGraph(),+ [host],+ );+ const fetchCommunities = useCallback(() => host.api.communities(), [host]);+ const fetchDeadCode = useCallback(() => host.api.deadCodeGraph(), [host]);+ const fetchHotFiles = useCallback(() => host.api.hotFilesGraph(), [host]);+ const fetchExecutionFlows = useCallback(() => host.api.executionFlows(), [host]);++ const moduleSlice = useHostSlice(+ viewMode === "module",+ refreshToken,+ fetchModuleGraph,+ onError,+ );+ const fullSlice = useHostSlice(needsFullGraph, refreshToken, fetchFullGraph, onError);+ const constellationSlice = useHostSlice(+ viewMode === "architecture",+ refreshToken,+ fetchConstellation,+ onError,+ );+ // Community labels feed the legend and inspection panel across every scope;+ // the constellation (default) mode needs them immediately.+ const communitiesSlice = useHostSlice(true, refreshToken, fetchCommunities, onError);+ const deadSlice = useHostSlice(+ viewMode === "dead",+ refreshToken,+ fetchDeadCode,+ onError,+ );+ const hotSlice = useHostSlice(+ viewMode === "hotfiles",+ refreshToken,+ fetchHotFiles,+ onError,+ );+ const flowsSlice = useHostSlice(+ needsFullGraph,+ refreshToken,+ fetchExecutionFlows,+ onError,+ );++ // Constellation blossom: fetch each newly-expanded hub's member slice once and+ // merge it into the Map incrementally (already-loaded ids are never refetched).+ const [constellationSlices, setConstellationSlices] = useState<+ Map<number, CommunitySlice>+ >(() => new Map());+ const requestedHubs = useRef<Set<number>>(new Set());++ useEffect(() => {+ for (const id of expandedHubs) {+ if (requestedHubs.current.has(id)) continue;+ requestedHubs.current.add(id);+ void host.api+ .communitySlice(id)+ .then((slice) => {+ setConstellationSlices((prev) => {+ const next = new Map(prev);+ next.set(id, slice as CommunitySlice);+ return next;+ });+ })+ .catch((err: unknown) =>+ onError(err instanceof Error ? err.message : String(err)),+ );+ }+ }, [expandedHubs, host, onError]);++ // Index moved: drop the accumulated slices so expanded hubs refetch fresh.+ useEffect(() => {+ requestedHubs.current = new Set();+ setConstellationSlices(new Map());+ }, [refreshToken]);++ const moduleGraph = moduleSlice.data as ModuleGraph | undefined;+ const fullGraph = fullSlice.data as GraphExport | undefined;+ const constellationGraph = constellationSlice.data as+ | ArchitectureGraph+ | undefined;+ const deadCodeGraph = deadSlice.data as GraphExport | undefined;+ const hotFilesGraph = hotSlice.data as GraphExport | undefined;+ const communities = communitiesSlice.data as CommunitySummaryItem[] | undefined;+ const executionFlows = flowsSlice.data as ExecutionFlows | undefined;++ const stats = useMemo<GraphData["stats"]>(() => {+ switch (viewMode) {+ case "architecture":+ return constellationGraph+ ? {+ nodes: constellationGraph.nodes.length,+ edges: constellationGraph.edges.length,+ }+ : null;+ case "module":+ return moduleGraph+ ? { nodes: moduleGraph.nodes.length, edges: moduleGraph.edges.length }+ : null;+ case "dead":+ return deadCodeGraph+ ? { nodes: deadCodeGraph.nodes.length, edges: deadCodeGraph.links.length }+ : null;+ case "hotfiles":+ return hotFilesGraph+ ? { nodes: hotFilesGraph.nodes.length, edges: hotFilesGraph.links.length }+ : null;+ default:+ return fullGraph+ ? { nodes: fullGraph.nodes.length, edges: fullGraph.links.length }+ : null;+ }+ }, [viewMode, constellationGraph, moduleGraph, deadCodeGraph, hotFilesGraph, fullGraph]);++ return {+ moduleGraph,+ isLoadingModuleGraph: moduleSlice.isLoading,+ fullGraph,+ isLoadingFullGraph: fullSlice.isLoading,+ constellationGraph,+ isLoadingConstellationGraph: constellationSlice.isLoading,+ constellationSlices,+ deadCodeGraph,+ isLoadingDeadCodeGraph: deadSlice.isLoading,+ hotFilesGraph,+ isLoadingHotFilesGraph: hotSlice.isLoading,+ communities,+ executionFlows,+ error,+ stats,+ viewMode,+ setViewMode,+ setModulePath,+ setHasExpandedModules,+ setExpandedHubs,+ };+}diff --git a/packages/vscode/webview/src/views/health/App.test.tsx b/packages/vscode/webview/src/views/health/App.test.tsxnew file mode 100644index 000000000..798bee89f--- /dev/null+++ b/packages/vscode/webview/src/views/health/App.test.tsx@@ -0,0 +1,172 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import type {+ ChurnComplexityResponse,+ HealthFilesResponse,+ HealthOverviewResponse,+ HealthTrendResponse,+} from "@repowise-dev/types/health";+import type { WebviewHost } from "../../runtime/rpc";+import { App } from "./App";++// jsdom has no ResizeObserver; the code map observes its container, so stub it.+class ResizeObserverStub {+ observe(): void {}+ unobserve(): void {}+ disconnect(): void {}+}+globalThis.ResizeObserver = ResizeObserverStub as unknown as typeof ResizeObserver;++const overview: HealthOverviewResponse = {+ summary: {+ file_count: 128,+ average_health: 7.4,+ hotspot_health: 5.1,+ worst_performer_path: "src/worst.py",+ worst_performer_score: 2.3,+ open_findings: 42,+ band: "warning",+ maintainability_average: 8.2,+ performance_average: 9.9,+ maintainability_findings: 6,+ performance_findings: 0,+ },+ distribution: {+ total_files: 128,+ total_nloc: 10000,+ bands: {+ healthy: { files: 80, nloc: 6000, pct: 60 },+ warning: { files: 40, nloc: 3000, pct: 30 },+ alert: { files: 8, nloc: 1000, pct: 10 },+ },+ },+ files: [],+ top_findings: [],+};++const files: HealthFilesResponse = {+ total: 128,+ offset: 0,+ limit: 2000,+ files: [+ {+ file_path: "src/worst.py",+ score: 2.3,+ max_ccn: 40,+ max_nesting: 6,+ nloc: 320,+ has_test_file: false,+ line_coverage_pct: 12,+ module: "core",+ },+ ],+};++const trend: HealthTrendResponse = {+ history: [+ {+ taken_at: "2026-06-01",+ hotspot_health: 5.0,+ average_health: 7.2,+ worst_performer_path: "src/worst.py",+ worst_performer_score: 2.1,+ },+ {+ taken_at: "2026-07-01",+ hotspot_health: 5.1,+ average_health: 7.4,+ worst_performer_path: "src/worst.py",+ worst_performer_score: 2.3,+ },+ ],+ summary: {+ current_hotspot_health: 5.1,+ current_average_health: 7.4,+ previous_hotspot_health: 5.0,+ previous_average_health: 7.2,+ hotspot_delta: 0.1,+ average_delta: 0.2,+ },+ alerts: [],+ file_deltas: [],+ snapshot_count: 2,+};++const churn: ChurnComplexityResponse = {+ total: 1,+ points: [+ {+ file_path: "src/worst.py",+ commit_count_90d: 12,+ max_ccn: 40,+ nloc: 320,+ score: 2.3,+ churn_percentile: 98,+ },+ ],+};++function makeHost(): { host: WebviewHost; openFile: ReturnType<typeof vi.fn> } {+ const openFile = vi.fn();+ const host = {+ api: {+ healthOverview: () => Promise.resolve(overview),+ healthFiles: () => Promise.resolve(files),+ healthTrend: () => Promise.resolve(trend),+ churnComplexity: () => Promise.resolve(churn),+ },+ openFile,+ } as unknown as WebviewHost;+ return { host, openFile };+}++afterEach(cleanup);++describe("Health dashboard", () => {+ it("renders the KPI header and the map section from host data", async () => {+ const { host } = makeHost();+ render(+ <App+ host={host}+ repo={{ id: "r1", name: "demo-repo", headCommit: "abcdef1234567", defaultBranch: "main" }}+ params={{}}+ refreshToken={0}+ />,+ );++ // KPI header: the three co-equal signal tiles.+ expect(await screen.findByText("Defect risk")).toBeTruthy();+ expect(screen.getByText("Maintainability")).toBeTruthy();+ expect(screen.getByText("Performance")).toBeTruthy();++ // The map is the hero section.+ expect(screen.getByText("Code health map")).toBeTruthy();++ // Repo identity is surfaced in the header.+ expect(screen.getByText("demo-repo")).toBeTruthy();+ });++ it("shows an error panel when the host fails", async () => {+ const host = {+ api: {+ healthOverview: () => Promise.reject(new Error("server down")),+ healthFiles: () => Promise.resolve(files),+ healthTrend: () => Promise.resolve(trend),+ churnComplexity: () => Promise.resolve(churn),+ },+ openFile: vi.fn(),+ } as unknown as WebviewHost;++ render(+ <App+ host={host}+ repo={{ id: "r1", name: "demo-repo", headCommit: null, defaultBranch: "main" }}+ params={{}}+ refreshToken={0}+ />,+ );++ expect(await screen.findByText("Health data is unavailable")).toBeTruthy();+ expect(screen.getByText("server down")).toBeTruthy();+ });+});diff --git a/packages/vscode/webview/src/views/health/App.tsx b/packages/vscode/webview/src/views/health/App.tsxnew file mode 100644index 000000000..ecc4cafc3--- /dev/null+++ b/packages/vscode/webview/src/views/health/App.tsx@@ -0,0 +1,159 @@+/**+ * Health dashboard: a KPI header over the three health signals, the circle-pack+ * code map as the hero, and the churn-versus-complexity quadrant on a tab. Every+ * file click opens the file in an editor column via the host.+ */++import { useMemo, useState } from "react";+import { HealthKpiCards } from "@repowise-dev/ui/health/kpi-cards";+import { CodeHealthMap, type CodeHealthOverlay } from "@repowise-dev/ui/health/code-health-map";+import { ChurnComplexityQuadrant } from "@repowise-dev/ui/health/churn-complexity-quadrant";+import type { HealthDimension } from "@repowise-dev/types/health";+import type { ViewProps } from "../../runtime/mount";+import { useDashboardData, type DashboardData } from "./useDashboardData";+import { DashboardError, DashboardSkeleton, SectionHeading } from "./chrome";++type HeroTab = "map" | "quadrant";++/** The KPI pillar tiles map onto the code map's lenses (defect is "health"). */+const PILLAR_TO_OVERLAY: Record<HealthDimension, CodeHealthOverlay> = {+ defect: "health",+ maintainability: "maintainability",+ performance: "performance",+};++export function App({ host, repo, refreshToken }: ViewProps<"health">) {+ const { data, error, loading } = useDashboardData(host, refreshToken);++ if (error) {+ return <DashboardError message={error} />;+ }+ if (loading || !data) {+ return <DashboardSkeleton />;+ }++ return <Dashboard host={host} repo={repo} data={data} />;+}++function Dashboard({+ host,+ repo,+ data,+}: {+ host: ViewProps<"health">["host"];+ repo: ViewProps<"health">["repo"];+ data: DashboardData;+}) {+ const { overview, files, trend, churn } = data;+ const [overlay, setOverlay] = useState<CodeHealthOverlay>("health");+ const [tab, setTab] = useState<HeroTab>("map");++ // KPI sparklines want oldest-first series; the trend history is newest-first.+ const kpiTrend = useMemo(() => {+ const history = trend.history ?? [];+ const asc = history.slice().reverse();+ const out: {+ averageHistory?: number[];+ hotspotHistory?: number[];+ worstHistory?: number[];+ averageDelta?: number;+ hotspotDelta?: number;+ } = {+ averageHistory: asc.map((p) => p.average_health),+ hotspotHistory: asc.map((p) => p.hotspot_health),+ worstHistory: asc.map((p) => p.worst_performer_score ?? 0),+ };+ if (trend.summary?.average_delta != null) out.averageDelta = trend.summary.average_delta;+ if (trend.summary?.hotspot_delta != null) out.hotspotDelta = trend.summary.hotspot_delta;+ return out;+ }, [trend]);++ const headCommit = repo.headCommit ? repo.headCommit.slice(0, 7) : null;++ return (+ <div className="mx-auto max-w-[1400px] space-y-8 px-6 py-6">+ <header className="space-y-1">+ <h1 className="text-xl font-semibold tracking-tight text-[var(--color-text-primary)]">+ Code health+ </h1>+ <p className="text-sm text-[var(--color-text-secondary)]">+ {repo.name}+ {headCommit ? (+ <span className="ml-2 font-mono text-xs text-[var(--color-text-tertiary)]">+ {headCommit}+ </span>+ ) : null}+ </p>+ </header>++ <section aria-label="Health signals">+ <HealthKpiCards+ summary={overview.summary}+ distribution={overview.distribution ?? null}+ {...kpiTrend}+ onSelectPillar={(pillar) => {+ setOverlay(PILLAR_TO_OVERLAY[pillar]);+ setTab("map");+ }}+ />+ </section>++ <section aria-label="Health explorer" className="space-y-4">+ <div className="flex items-center justify-between gap-3">+ <SectionHeading+ title={tab === "map" ? "Code health map" : "Churn versus complexity"}+ subtitle={+ tab === "map"+ ? `${files.total.toLocaleString()} files · click a galaxy to zoom, a file to open`+ : `${churn.total.toLocaleString()} changed files · the top-right corner is the refactor zone`+ }+ />+ <TabSwitch tab={tab} onChange={setTab} />+ </div>++ {tab === "map" ? (+ <CodeHealthMap+ files={files.files}+ overlay={overlay}+ onOverlayChange={setOverlay}+ onSelectFile={(path) => host.openFile(path)}+ minHeight={640}+ />+ ) : (+ <ChurnComplexityQuadrant+ points={churn.points}+ height={520}+ onSelect={(point) => host.openFile(point.file_path)}+ />+ )}+ </section>+ </div>+ );+}++/** A two-button segmented control switching the hero between map and quadrant. */+function TabSwitch({ tab, onChange }: { tab: HeroTab; onChange: (tab: HeroTab) => void }) {+ const tabs: { id: HeroTab; label: string }[] = [+ { id: "map", label: "Map" },+ { id: "quadrant", label: "Quadrant" },+ ];+ return (+ <div className="inline-flex shrink-0 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-0.5 text-xs">+ {tabs.map((t) => (+ <button+ key={t.id}+ type="button"+ onClick={() => onChange(t.id)}+ aria-pressed={tab === t.id}+ className={+ tab === t.id+ ? "rounded-md bg-[var(--color-accent-primary)] px-3 py-1 font-medium text-[var(--color-text-inverse)]"+ : "rounded-md px-3 py-1 text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)]"+ }+ >+ {t.label}+ </button>+ ))}+ </div>+ );+}diff --git a/packages/vscode/webview/src/views/health/chrome.tsx b/packages/vscode/webview/src/views/health/chrome.tsxnew file mode 100644index 000000000..e0e287a5b--- /dev/null+++ b/packages/vscode/webview/src/views/health/chrome.tsx@@ -0,0 +1,64 @@+/**+ * Presentational chrome for the Health dashboard: section heading, the loading+ * skeleton that mirrors the real layout, and the error panel. All token-driven+ * so both editor themes render correctly via the `.dark` class on the root.+ */++/** A section title with a muted supporting line. */+export function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) {+ return (+ <div className="min-w-0">+ <h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {title}+ </h2>+ {subtitle ? (+ <p className="mt-0.5 truncate text-xs text-[var(--color-text-tertiary)]">{subtitle}</p>+ ) : null}+ </div>+ );+}++/** A pulsing placeholder block. */+function Block({ className }: { className: string }) {+ return (+ <div+ className={`animate-pulse rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] ${className}`}+ />+ );+}++/** Skeleton laid out like the loaded dashboard so the transition is calm. */+export function DashboardSkeleton() {+ return (+ <div className="mx-auto max-w-[1400px] space-y-8 px-6 py-6" aria-busy="true" aria-label="Loading health">+ <div className="space-y-2">+ <Block className="h-6 w-40 border-0" />+ <Block className="h-4 w-64 border-0" />+ </div>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-3">+ <Block className="h-32" />+ <Block className="h-32" />+ <Block className="h-32" />+ </div>+ <Block className="h-10" />+ <Block className="h-[640px]" />+ </div>+ );+}++/** Error panel shown when the host could not serve the health payloads. */+export function DashboardError({ message }: { message: string }) {+ return (+ <div className="mx-auto max-w-[1400px] px-6 py-6">+ <div className="rounded-xl border border-[var(--color-error)] bg-[var(--color-bg-surface)] p-6">+ <h2 className="text-sm font-semibold text-[var(--color-error)]">+ Health data is unavailable+ </h2>+ <p className="mt-2 text-sm text-[var(--color-text-secondary)]">{message}</p>+ <p className="mt-3 text-xs text-[var(--color-text-tertiary)]">+ Make sure the local Repowise server is running and this repository is indexed.+ </p>+ </div>+ </div>+ );+}diff --git a/packages/vscode/webview/src/views/health/main.tsx b/packages/vscode/webview/src/views/health/main.tsxnew file mode 100644index 000000000..db88c76e7--- /dev/null+++ b/packages/vscode/webview/src/views/health/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("health", App);diff --git a/packages/vscode/webview/src/views/health/useDashboardData.ts b/packages/vscode/webview/src/views/health/useDashboardData.tsnew file mode 100644index 000000000..81a0bdbaf--- /dev/null+++ b/packages/vscode/webview/src/views/health/useDashboardData.ts@@ -0,0 +1,75 @@+/**+ * Loads every payload the Health dashboard renders in one pass and refetches+ * the whole set when the index moves under the panel. Webviews never fetch:+ * each call is an RPC the host serves from its shared cache and api-client.+ */++import { useEffect, useState } from "react";+import type {+ ChurnComplexityResponse,+ HealthOverviewResponse,+ HealthFilesResponse,+ HealthTrendResponse,+} from "@repowise-dev/types/health";+import type { WebviewHost } from "../../runtime/rpc";++/** Files pulled for the map: biggest first, capped so the galaxy stays legible. */+const MAP_FILE_LIMIT = 2000;+/** Overview + trend history windows the KPI header reads. */+const OVERVIEW_LIMIT = 25;+const TREND_LIMIT = 20;+/** Points for the churn-versus-complexity scatter. */+const QUADRANT_LIMIT = 400;++export interface DashboardData {+ overview: HealthOverviewResponse;+ files: HealthFilesResponse;+ trend: HealthTrendResponse;+ churn: ChurnComplexityResponse;+}++export interface DashboardState {+ data: DashboardData | null;+ error: string | null;+ loading: boolean;+}++/**+ * Fetch the four health payloads together. `refreshToken` is the only+ * dependency: it changes on first mount (0) and whenever the host reports the+ * index moved, so the effect re-runs and re-pulls the set.+ */+export function useDashboardData(host: WebviewHost, refreshToken: number): DashboardState {+ const [state, setState] = useState<DashboardState>({+ data: null,+ error: null,+ loading: true,+ });++ useEffect(() => {+ let cancelled = false;+ setState((prev) => ({ ...prev, loading: true, error: null }));++ Promise.all([+ host.api.healthOverview(OVERVIEW_LIMIT),+ host.api.healthFiles({ limit: MAP_FILE_LIMIT, sort: "nloc", order: "desc" }),+ host.api.healthTrend(TREND_LIMIT),+ host.api.churnComplexity(QUADRANT_LIMIT),+ ])+ .then(([overview, files, trend, churn]) => {+ if (cancelled) return;+ setState({ data: { overview, files, trend, churn }, error: null, loading: false });+ })+ .catch((err: unknown) => {+ if (cancelled) return;+ const message = err instanceof Error ? err.message : "Could not load health data.";+ setState({ data: null, error: message, loading: false });+ });++ return () => {+ cancelled = true;+ };+ }, [host, refreshToken]);++ return state;+}diff --git a/packages/vscode/webview/src/views/refactoring/App.test.tsx b/packages/vscode/webview/src/views/refactoring/App.test.tsxnew file mode 100644index 000000000..8fef72231--- /dev/null+++ b/packages/vscode/webview/src/views/refactoring/App.test.tsx@@ -0,0 +1,72 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen, fireEvent, waitFor } from "@testing-library/react";++afterEach(cleanup);+import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";+import { App } from "./App";+import type { WebviewHost } from "../../runtime/rpc";++const PLAN: RefactoringPlan = {+ id: "plan-1",+ refactoring_type: "extract_method",+ file_path: "packages/core/src/big.py",+ target_symbol: "process_everything",+ line_start: 40,+ line_end: 120,+ plan: { span: { start: 60, end: 90 }, params: ["items"], returns: ["total"], suggested_name: "sum_items" },+ evidence: { ccn_removed: 7 },+ impact_delta: 1.4,+ effort_bucket: "M",+ blast_radius: { files: ["packages/core/src/caller.py"], file_count: 1 },+ confidence: "high",+ source_biomarker: "complexity",+ rank_score: 0.9,+};++const REPO = { id: "r1", name: "repo", headCommit: "abc", defaultBranch: "main" } as const;++function makeHost(overrides: Partial<WebviewHost["api"]> = {}): {+ host: WebviewHost;+ refactoringPrompt: ReturnType<typeof vi.fn>;+ copyText: ReturnType<typeof vi.fn>;+} {+ const refactoringPrompt = vi.fn().mockResolvedValue("GENERATED PROMPT");+ const copyText = vi.fn();+ const api = {+ refactoringPlan: vi.fn().mockResolvedValue(PLAN),+ refactoringPrompt,+ ...overrides,+ } as unknown as WebviewHost["api"];+ const host = {+ api,+ onInit: () => () => {},+ onRefresh: () => () => {},+ ready: () => {},+ openFile: vi.fn(),+ copyText,+ openExternal: () => {},+ } as unknown as WebviewHost;+ return { host, refactoringPrompt, copyText };+}++describe("refactoring App detail page", () => {+ it("renders the plan header and copies a flavored prompt on click", async () => {+ const { host, refactoringPrompt, copyText } = makeHost();++ render(<App host={host} repo={REPO} params={{ planId: "plan-1" }} refreshToken={0} />);++ // Header renders from the fetched plan.+ await screen.findByRole("heading", { name: "process_everything" });+ expect(screen.getByText("Extract Method")).toBeTruthy();++ // Clicking a flavor button builds that flavor's prompt and copies it.+ fireEvent.click(screen.getByRole("button", { name: "Claude Code + Repowise MCP" }));++ await waitFor(() => expect(refactoringPrompt).toHaveBeenCalledWith("plan-1", "claude-code-mcp"));+ await waitFor(() => expect(copyText).toHaveBeenCalledTimes(1));+ expect(copyText).toHaveBeenCalledWith(+ "GENERATED PROMPT",+ "Plan prompt copied for Claude Code + Repowise MCP.",+ );+ });+});diff --git a/packages/vscode/webview/src/views/refactoring/App.tsx b/packages/vscode/webview/src/views/refactoring/App.tsxnew file mode 100644index 000000000..d7c985f87--- /dev/null+++ b/packages/vscode/webview/src/views/refactoring/App.tsx@@ -0,0 +1,480 @@+import { useCallback, useEffect, useState, type ReactNode } from "react";+import { ArrowLeft, Layers, Sparkles } from "lucide-react";+import {+ CONFIDENCE_DOT,+ CONFIDENCE_LABEL,+ EFFORT_LABEL,+ typeAccent,+ typeMeta,+} from "@repowise-dev/ui/refactoring/meta";+import { PlanDetail } from "@repowise-dev/ui/refactoring/plan-detail";+import { RefactoringPlanCard } from "@repowise-dev/ui/refactoring/refactoring-plan-card";+import {+ blastCount,+ blastFiles,+ evidenceRows,+ planWins,+ type Confidence,+ type EffortBucket,+ type RefactoringPlan,+ type RefactoringTargets,+} from "@repowise-dev/ui/refactoring/types";+import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";+import type { ViewProps } from "../../runtime/mount";+import type { WebviewHost } from "../../runtime/rpc";++/**+ * Refactoring panel. Opened two ways:+ * - with a `planId` (from a CodeLens or a tree item) → the detail page is the+ * root and there is no list to fall back to;+ * - without one → a ranked list of plans; clicking a card opens the detail+ * in-panel, and a back control returns to the list.+ * All data arrives over the typed host RPC; file references route through+ * `host.openFile`.+ */+export function App({ host, params, refreshToken }: ViewProps<"refactoring">) {+ // A plan opened directly is the initial (and only) selection. A card click+ // sets its own; Back clears it, but only when we arrived via the list.+ const [selectedId, setSelectedId] = useState<string | null>(params.planId ?? null);++ // The host can push new params into an already-open panel; honor them.+ useEffect(() => {+ setSelectedId(params.planId ?? null);+ }, [params.planId]);++ const rootIsDetail = params.planId != null;++ if (selectedId != null) {+ return (+ <PlanDetailView+ host={host}+ planId={selectedId}+ refreshToken={refreshToken}+ onBack={rootIsDetail ? undefined : () => setSelectedId(null)}+ />+ );+ }++ return (+ <PlanListView+ host={host}+ filePath={params.filePath}+ refreshToken={refreshToken}+ onOpen={(plan) => setSelectedId(plan.id)}+ />+ );+}++// ── Async state helper ─────────────────────────────────────────────────────++type AsyncState<T> =+ | { status: "loading" }+ | { status: "error"; message: string }+ | { status: "ok"; data: T };++function useAsync<T>(load: () => Promise<T>, deps: unknown[]): AsyncState<T> {+ const [state, setState] = useState<AsyncState<T>>({ status: "loading" });+ useEffect(() => {+ let cancelled = false;+ setState({ status: "loading" });+ load().then(+ (data) => {+ if (!cancelled) setState({ status: "ok", data });+ },+ (err: unknown) => {+ if (!cancelled) {+ setState({ status: "error", message: err instanceof Error ? err.message : String(err) });+ }+ },+ );+ return () => {+ cancelled = true;+ };+ // load is recreated per render; deps carry the real inputs.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, deps);+ return state;+}++// ── File reference bridge ──────────────────────────────────────────────────+//+// PlanDetail renders file references as anchors via a `fileHref` callback. In a+// webview a real navigation would blow away the panel, so we encode the path+// into a custom-scheme href and intercept the click to call host.openFile.++const FILE_HREF_PREFIX = "repowise-open:";++function fileHref(path: string, line?: number | null): string {+ const query = line != null ? `?line=${line}` : "";+ return `${FILE_HREF_PREFIX}${encodeURIComponent(path)}${query}`;+}++function useFileClickHandler(host: WebviewHost) {+ return useCallback(+ (event: React.MouseEvent<HTMLElement>) => {+ const anchor = (event.target as HTMLElement).closest("a");+ const href = anchor?.getAttribute("href");+ if (!href || !href.startsWith(FILE_HREF_PREFIX)) return;+ event.preventDefault();+ const [encodedPath, query] = href.slice(FILE_HREF_PREFIX.length).split("?");+ const path = decodeURIComponent(encodedPath ?? "");+ const rawLine = query?.startsWith("line=") ? Number(query.slice("line=".length)) : NaN;+ if (Number.isFinite(rawLine)) host.openFile(path, rawLine);+ else host.openFile(path);+ },+ [host],+ );+}++// ── Detail page ────────────────────────────────────────────────────────────++const FLAVORS: { label: string; flavor: AiPromptFlavor }[] = [+ { label: "Generic", flavor: "generic" },+ { label: "Claude Code", flavor: "claude-code" },+ { label: "Claude Code + Repowise MCP", flavor: "claude-code-mcp" },+ { label: "Cursor", flavor: "cursor" },+];++interface PlanDetailViewProps {+ host: WebviewHost;+ planId: string;+ refreshToken: number;+ /** Present only when a plan list exists to return to. */+ onBack?: (() => void) | undefined;+}++function PlanDetailView({ host, planId, refreshToken, onBack }: PlanDetailViewProps) {+ const state = useAsync(() => host.api.refactoringPlan(planId), [planId, refreshToken]);+ const onFileClick = useFileClickHandler(host);++ if (state.status === "loading") return <CenteredNote>Loading plan…</CenteredNote>;+ if (state.status === "error") {+ return <ErrorNote title="Could not load this refactoring plan.">{state.message}</ErrorNote>;+ }++ const plan = state.data;+ const wins = planWins(plan);+ const evidence = evidenceRows(plan);+ const affected = blastFiles(plan).filter((f) => f !== plan.file_path);+ const blast = blastCount(plan);++ return (+ <div className="mx-auto max-w-3xl px-6 py-6" onClick={onFileClick}>+ {onBack ? (+ <button+ type="button"+ onClick={onBack}+ className="mb-4 inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ All refactoring plans+ </button>+ ) : null}++ <PlanHeader plan={plan} onOpenFile={() => host.openFile(plan.file_path, plan.line_start ?? undefined)} />++ {wins.length > 0 ? (+ <div className="mt-5 flex flex-wrap gap-2">+ {wins.map((win, i) => (+ <span+ key={i}+ className={+ win.hero+ ? "inline-flex items-center gap-1.5 rounded-full bg-[var(--color-success)]/10 px-3 py-1 text-xs font-semibold text-[var(--color-success)]"+ : "inline-flex items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1 text-xs text-[var(--color-text-secondary)]"+ }+ >+ {win.label}+ </span>+ ))}+ </div>+ ) : null}++ <Section title="The plan">+ <PlanDetail plan={plan} fileHref={fileHref} />+ </Section>++ {evidence.length > 0 ? (+ <Section title="Evidence">+ <dl className="grid grid-cols-2 gap-2 sm:grid-cols-3">+ {evidence.map((row) => (+ <div+ key={row.label}+ className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2"+ >+ <dt className="text-[10px] uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {row.label}+ </dt>+ <dd className="mt-0.5 font-mono text-sm tabular-nums text-[var(--color-text-primary)]">+ {row.value}+ </dd>+ </div>+ ))}+ </dl>+ </Section>+ ) : null}++ <Section title="Blast radius">+ <div className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <Layers className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />+ {affected.length > 0+ ? `${affected.length} other file${affected.length === 1 ? "" : "s"} to keep consistent`+ : blast > 0+ ? `${blast} dependent${blast === 1 ? "" : "s"} affected`+ : "No dependent files recorded."}+ </div>+ {affected.length > 0 ? (+ <ul className="mt-2 divide-y divide-[var(--color-border-default)] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">+ {affected.slice(0, 25).map((file) => (+ <li key={file} className="px-3.5 py-2">+ <a+ href={fileHref(file)}+ className="block truncate font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"+ title={file}+ >+ {file}+ </a>+ </li>+ ))}+ {affected.length > 25 ? (+ <li className="px-3.5 py-2 text-[11px] text-[var(--color-text-tertiary)]">+ +{affected.length - 25} more+ </li>+ ) : null}+ </ul>+ ) : null}+ </Section>++ <CopyForAgentRow host={host} planId={planId} />+ </div>+ );+}++function PlanHeader({ plan, onOpenFile }: { plan: RefactoringPlan; onOpenFile: () => void }) {+ const meta = typeMeta(plan.refactoring_type);+ const accent = typeAccent(plan.refactoring_type);+ const { Icon } = meta;+ const effort = (plan.effort_bucket || "M") as EffortBucket;+ const confidence = (plan.confidence || "medium") as Confidence;++ return (+ <header>+ <div className="flex flex-wrap items-center gap-3">+ <span+ className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-sm font-semibold"+ style={{ backgroundColor: `color-mix(in srgb, ${accent} 14%, transparent)`, color: accent }}+ >+ <Icon className="h-4 w-4" />+ {meta.label}+ </span>+ {plan.impact_delta > 0 ? (+ <Badge title="Health recovered if applied" tone="success">+ +{plan.impact_delta.toFixed(1)} health+ </Badge>+ ) : null}+ <Badge title={`Effort: ${EFFORT_LABEL[effort]}`}>+ {effort} · {EFFORT_LABEL[effort]}+ </Badge>+ <Badge title={`Detector confidence: ${CONFIDENCE_LABEL[confidence]}`}>+ <span className={`h-1.5 w-1.5 rounded-full ${CONFIDENCE_DOT[confidence]}`} />+ {CONFIDENCE_LABEL[confidence]} confidence+ </Badge>+ </div>++ <h1 className="mt-3 text-lg font-semibold text-[var(--color-text-primary)]">+ {plan.target_symbol || meta.label}+ </h1>+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">{meta.blurb}</p>+ <button+ type="button"+ onClick={onOpenFile}+ className="mt-1.5 inline-block max-w-full truncate font-mono text-xs text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline"+ title={plan.file_path}+ >+ {plan.file_path}+ {plan.line_start != null ? (+ <span className="text-[var(--color-text-tertiary)]">:{plan.line_start}</span>+ ) : null}+ </button>+ </header>+ );+}++function CopyForAgentRow({ host, planId }: { host: WebviewHost; planId: string }) {+ const [busy, setBusy] = useState<AiPromptFlavor | null>(null);+ const [copyError, setCopyError] = useState<string | null>(null);++ async function copy(flavor: AiPromptFlavor, label: string): Promise<void> {+ setBusy(flavor);+ setCopyError(null);+ try {+ const prompt = await host.api.refactoringPrompt(planId, flavor);+ host.copyText(prompt, `Plan prompt copied for ${label}.`);+ } catch (err) {+ setCopyError(err instanceof Error ? err.message : "Could not build the prompt.");+ } finally {+ setBusy(null);+ }+ }++ return (+ <div className="sticky bottom-0 mt-8 -mx-6 border-t border-[var(--color-border-default)] bg-[var(--color-bg-root)]/95 px-6 py-3 backdrop-blur">+ <div className="mb-2 flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">+ <Sparkles className="h-3.5 w-3.5" />+ Copy for agent+ </div>+ <div className="flex flex-wrap gap-2">+ {FLAVORS.map(({ label, flavor }) => (+ <button+ key={flavor}+ type="button"+ disabled={busy != null}+ onClick={() => void copy(flavor, label)}+ className="inline-flex items-center rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:opacity-50"+ >+ {label}+ </button>+ ))}+ </div>+ {copyError ? (+ <p className="mt-2 text-xs text-[var(--color-error)]">{copyError}</p>+ ) : null}+ </div>+ );+}++// ── List page ──────────────────────────────────────────────────────────────++interface PlanListViewProps {+ host: WebviewHost;+ filePath?: string | undefined;+ refreshToken: number;+ onOpen: (plan: RefactoringPlan) => void;+}++function PlanListView({ host, filePath, refreshToken, onOpen }: PlanListViewProps) {+ const state = useAsync(+ () => host.api.refactoringTargets(filePath),+ [filePath, refreshToken],+ );++ if (state.status === "loading") return <CenteredNote>Loading refactoring plans…</CenteredNote>;+ if (state.status === "error") {+ return <ErrorNote title="Could not load refactoring plans.">{state.message}</ErrorNote>;+ }++ const targets: RefactoringTargets = state.data;+ if (targets.plans.length === 0) {+ return (+ <CenteredNote>+ {filePath ? `No refactoring plans for ${filePath}.` : "No refactoring plans found."}+ </CenteredNote>+ );+ }++ return (+ <div className="mx-auto max-w-5xl px-6 py-6">+ <SummaryStrip summary={targets.summary} filePath={filePath} />+ <div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {targets.plans.map((plan) => (+ <RefactoringPlanCard key={plan.id} plan={plan} onOpen={onOpen} />+ ))}+ </div>+ </div>+ );+}++function SummaryStrip({+ summary,+ filePath,+}: {+ summary: RefactoringTargets["summary"];+ filePath?: string | undefined;+}) {+ return (+ <div className="rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-5 py-4">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <span className="text-2xl font-semibold tabular-nums text-[var(--color-text-primary)]">+ {summary.total}+ </span>+ <span className="text-sm text-[var(--color-text-secondary)]">+ refactoring plan{summary.total === 1 ? "" : "s"}+ {filePath ? (+ <>+ {" in "}+ <span className="font-mono text-xs text-[var(--color-text-tertiary)]">{filePath}</span>+ </>+ ) : null}+ </span>+ </div>+ {summary.by_type.length > 0 ? (+ <div className="mt-3 flex flex-wrap gap-x-4 gap-y-1.5">+ {summary.by_type.map((row) => (+ <span key={row.type} className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <span+ className="h-2 w-2 rounded-full"+ style={{ backgroundColor: typeAccent(row.type) }}+ aria-hidden+ />+ {typeMeta(row.type).label}+ <span className="tabular-nums text-[var(--color-text-tertiary)]">{row.count}</span>+ </span>+ ))}+ </div>+ ) : null}+ </div>+ );+}++// ── Shared bits ────────────────────────────────────────────────────────────++function Section({ title, children }: { title: string; children: ReactNode }) {+ return (+ <section className="mt-6">+ <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {title}+ </h2>+ {children}+ </section>+ );+}++function Badge({+ children,+ title,+ tone = "neutral",+}: {+ children: ReactNode;+ title?: string;+ tone?: "neutral" | "success";+}) {+ const cls =+ tone === "success"+ ? "bg-[var(--color-success)]/10 text-[var(--color-success)]"+ : "border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-secondary)]";+ return (+ <span+ className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium tabular-nums ${cls}`}+ title={title}+ >+ {children}+ </span>+ );+}++function CenteredNote({ children }: { children: ReactNode }) {+ return (+ <div className="flex h-screen items-center justify-center px-6 text-center text-sm text-[var(--color-text-tertiary)]">+ {children}+ </div>+ );+}++function ErrorNote({ title, children }: { title: string; children: ReactNode }) {+ return (+ <div className="m-6 rounded-lg border border-[var(--color-error)] p-4 text-sm">+ <p className="font-medium text-[var(--color-error)]">{title}</p>+ <p className="mt-2 text-[var(--color-text-secondary)]">{children}</p>+ </div>+ );+}diff --git a/packages/vscode/webview/src/views/refactoring/main.tsx b/packages/vscode/webview/src/views/refactoring/main.tsxnew file mode 100644index 000000000..31ddfc113--- /dev/null+++ b/packages/vscode/webview/src/views/refactoring/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("refactoring", App);diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxnew file mode 100644index 000000000..a6fd064db--- /dev/null+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -0,0 +1,69 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";+import { App } from "./App";+import type { WebviewHost } from "../../runtime/rpc";+import type { RepoInit } from "../../../../src/shared/webviewMessages";+import type { RiskRangeReport } from "../../../../src/shared/webviewMessages";++const REPORT: RiskRangeReport = {+ base: "main",+ branch: "feat/thing",+ result: {+ base: "main",+ head: "HEAD",+ score: 7.4,+ probability: 0.63,+ level: "high",+ risk_percentile: 88,+ review_priority: "high",+ is_fix: false,+ features: { la: 120, ld: 30, nf: 6, nd: 2, ns: 1, entropy: 2.31, exp: null },+ drivers: [+ { feature: "la", value: 120, contribution: 1.8, label: "Lines added" },+ { feature: "exp", value: null, contribution: -0.5, label: "Author experience" },+ ],+ },+};++const REPO: RepoInit = { id: "r1", name: "repo", headCommit: null, defaultBranch: "main" };++function makeHost(riskRange: WebviewHost["api"]["riskRange"]): WebviewHost {+ return {+ api: { riskRange } as WebviewHost["api"],+ onInit: () => () => {},+ onRefresh: () => () => {},+ ready: () => {},+ openFile: () => {},+ copyText: () => {},+ openExternal: () => {},+ };+}++describe("risk App", () => {+ beforeEach(() => vi.clearAllMocks());+ afterEach(() => cleanup());++ it("renders the score, level, and drivers from a fixture", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);++ expect(await screen.findByText("7.4")).toBeTruthy();+ expect(screen.getByText("high risk")).toBeTruthy();+ expect(screen.getByText("+1.80")).toBeTruthy();+ expect(screen.getByText("−0.50")).toBeTruthy();+ // The change-shape table renders labelled features and skips null ones.+ expect(screen.getByText("Change entropy")).toBeTruthy();+ expect(screen.getByText("120")).toBeTruthy();+ });++ it("refetches when Run again is clicked", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);++ await screen.findByText("7.4");+ expect(riskRange).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByRole("button", { name: /run again/i }));+ await waitFor(() => expect(riskRange).toHaveBeenCalledTimes(2));+ });+});diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxnew file mode 100644index 000000000..fff32a57e--- /dev/null+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -0,0 +1,251 @@+import { useCallback, useEffect, useState } from "react";+import { GitCompare, RotateCw, ShieldCheck } from "lucide-react";+import { Badge, Button, Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui";+import { EmptyState } from "@repowise-dev/ui/shared";+import type { ViewProps } from "../../runtime/mount";+import type { RiskRangeReport } from "../../../../src/shared/webviewMessages";++/** Human labels for the raw change features the endpoint returns, in report order. */+const FEATURE_LABELS: ReadonlyArray<readonly [string, string]> = [+ ["la", "Lines added"],+ ["ld", "Lines deleted"],+ ["nf", "Files changed"],+ ["nd", "Directories changed"],+ ["ns", "Subsystems changed"],+ ["entropy", "Change entropy"],+ ["exp", "Author experience"],+];++type Tone = "low" | "medium" | "high";++/** Buckets a 0-10 score into the three risk tones the palette defines. */+function scoreTone(score: number): Tone {+ if (score >= 6.5) return "high";+ if (score >= 3.5) return "medium";+ return "low";+}++const TONE_VAR: Record<Tone, string> = {+ low: "var(--color-risk-low)",+ medium: "var(--color-risk-medium)",+ high: "var(--color-risk-high)",+};++/** Formats a contribution with an explicit sign (positive raises risk). */+function signed(value: number): string {+ return `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(2)}`;+}++function formatFeatureValue(value: number): string {+ return Number.isInteger(value) ? String(value) : value.toFixed(2);+}++export function App({ host, repo, refreshToken }: ViewProps<"risk">) {+ const [report, setReport] = useState<RiskRangeReport | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);++ const load = useCallback(() => {+ setLoading(true);+ setError(null);+ host.api+ .riskRange()+ .then((r) => {+ setReport(r);+ setLoading(false);+ })+ .catch((err: unknown) => {+ setError(err instanceof Error ? err.message : "Could not score branch risk.");+ setLoading(false);+ });+ }, [host]);++ // Refetch on mount and whenever the index moves under the panel. Risk+ // reflects the working HEAD, so there is no cache to reuse.+ useEffect(() => {+ load();+ }, [load, refreshToken]);++ const branch = report?.branch ?? repo.defaultBranch ?? "HEAD";+ const base = report?.base ?? "";++ return (+ <div className="mx-auto max-w-3xl space-y-5 p-6">+ <header className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">Branch risk</h1>+ <p className="mt-1 flex items-center gap-2 text-sm text-[var(--color-text-secondary)]">+ <GitCompare className="h-4 w-4 shrink-0" />+ <span className="truncate">+ <code className="text-[var(--color-text-primary)]">{branch}</code>+ <span className="mx-1.5 text-[var(--color-text-tertiary)]">vs</span>+ <code className="text-[var(--color-text-primary)]">{base || "base"}</code>+ </span>+ </p>+ </div>+ <Button variant="outline" size="sm" onClick={load} disabled={loading}>+ <RotateCw className={loading ? "animate-spin" : undefined} />+ Run again+ </Button>+ </header>++ {loading && !report ? (+ <LoadingCard base={base} />+ ) : error ? (+ <EmptyState+ icon={<ShieldCheck className="h-8 w-8" />}+ title="Could not score branch risk"+ description={error}+ action={{ label: "Try again", onClick: load }}+ />+ ) : report ? (+ <Report report={report} />+ ) : null}+ </div>+ );+}++function LoadingCard({ base }: { base: string }) {+ return (+ <Card>+ <CardContent className="flex flex-col items-center gap-3 py-16 text-center">+ <RotateCw className="h-6 w-6 animate-spin text-[var(--color-accent-primary)]" />+ <p className="text-sm text-[var(--color-text-secondary)]">+ Scoring the working tree{base ? ` against ${base}` : ""}+ </p>+ </CardContent>+ </Card>+ );+}++function Report({ report }: { report: RiskRangeReport }) {+ const r = report.result;+ const tone = scoreTone(r.score);+ const color = TONE_VAR[tone];++ const drivers = [...r.drivers].sort(+ (a, b) => Math.abs(b.contribution) - Math.abs(a.contribution),+ );+ const maxDriver = drivers.reduce((m, d) => Math.max(m, Math.abs(d.contribution)), 0);++ const featureRows = FEATURE_LABELS.filter(+ ([key]) => r.features[key] != null,+ ) as ReadonlyArray<readonly [string, string]>;++ return (+ <div className="space-y-5">+ {/* Score hero */}+ <Card>+ <CardContent className="flex flex-wrap items-center gap-6 py-6">+ <div+ className="flex h-24 w-24 shrink-0 flex-col items-center justify-center rounded-2xl border"+ style={{+ borderColor: `color-mix(in srgb, ${color} 45%, transparent)`,+ backgroundColor: `color-mix(in srgb, ${color} 12%, transparent)`,+ }}+ >+ <span className="text-3xl font-bold leading-none" style={{ color }}>+ {r.score.toFixed(1)}+ </span>+ <span className="mt-1 text-[11px] text-[var(--color-text-tertiary)]">out of 10</span>+ </div>+ <div className="min-w-0 flex-1 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <span+ className="inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium capitalize"+ style={{+ color,+ borderColor: `color-mix(in srgb, ${color} 40%, transparent)`,+ }}+ >+ {r.level} risk+ </span>+ {r.is_fix && (+ <Badge variant="outline" title="Classified as a fix change">+ fix+ </Badge>+ )}+ </div>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Estimated defect probability{" "}+ <span className="font-semibold text-[var(--color-text-primary)]">+ {(r.probability * 100).toFixed(1)}%+ </span>+ </p>+ <div className="flex flex-wrap gap-2 pt-1">+ {r.risk_percentile != null && (+ <Badge variant="default">+ {r.risk_percentile.toFixed(0)}th percentile+ </Badge>+ )}+ {r.review_priority && (+ <Badge variant="accent" className="capitalize">+ {r.review_priority} review priority+ </Badge>+ )}+ </div>+ </div>+ </CardContent>+ </Card>++ {/* Drivers */}+ {drivers.length > 0 && (+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-sm">What moves the score</CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ {drivers.map((d) => {+ const raises = d.contribution >= 0;+ const barColor = raises ? "var(--color-error)" : "var(--color-success)";+ const pct = maxDriver > 0 ? (Math.abs(d.contribution) / maxDriver) * 100 : 0;+ return (+ <div key={d.feature} className="flex items-center gap-3 text-sm">+ <span className="w-40 shrink-0 truncate text-[var(--color-text-secondary)]">+ {d.label}+ </span>+ <div className="h-2 flex-1 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">+ <div+ className="h-full rounded-full"+ style={{ width: `${pct}%`, backgroundColor: barColor }}+ />+ </div>+ <span+ className="w-14 shrink-0 text-right font-medium tabular-nums"+ style={{ color: barColor }}+ >+ {signed(d.contribution)}+ </span>+ </div>+ );+ })}+ </CardContent>+ </Card>+ )}++ {/* Change features */}+ {featureRows.length > 0 && (+ <Card>+ <CardHeader className="pb-3">+ <CardTitle className="text-sm">Change shape</CardTitle>+ </CardHeader>+ <CardContent>+ <dl className="grid grid-cols-1 gap-x-8 gap-y-2 sm:grid-cols-2">+ {featureRows.map(([key, label]) => (+ <div+ key={key}+ className="flex items-baseline justify-between gap-3 border-b border-[var(--color-border-default)] py-1.5 last:border-b-0"+ >+ <dt className="text-sm text-[var(--color-text-secondary)]">{label}</dt>+ <dd className="text-sm font-medium tabular-nums text-[var(--color-text-primary)]">+ {formatFeatureValue(r.features[key] as number)}+ </dd>+ </div>+ ))}+ </dl>+ </CardContent>+ </Card>+ )}+ </div>+ );+}diff --git a/packages/vscode/webview/src/views/risk/main.tsx b/packages/vscode/webview/src/views/risk/main.tsxnew file mode 100644index 000000000..6042e6cd6--- /dev/null+++ b/packages/vscode/webview/src/views/risk/main.tsx@@ -0,0 +1,5 @@+import "../../styles/index.css";+import { mountView } from "../../runtime/mount";+import { App } from "./App";++mountView("risk", App);diff --git a/packages/vscode/webview/tsconfig.json b/packages/vscode/webview/tsconfig.jsonnew file mode 100644index 000000000..764eeb53d--- /dev/null+++ b/packages/vscode/webview/tsconfig.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "jsx": "react-jsx",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "types": ["vite/client"],+ "strict": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "skipLibCheck": true,+ "esModuleInterop": true,+ "isolatedModules": true,+ "forceConsistentCasingInFileNames": true,+ "paths": {+ "next-themes": ["./src/shims/next-themes.ts"]+ }+ },+ "include": ["src", "vite.config.mts", "vitest.config.mts", "../src/shared/webviewMessages.ts"]+}diff --git a/packages/vscode/webview/vite.config.mts b/packages/vscode/webview/vite.config.mtsnew file mode 100644index 000000000..f83233389--- /dev/null+++ b/packages/vscode/webview/vite.config.mts@@ -0,0 +1,61 @@+import * as path from "node:path";+import { fileURLToPath } from "node:url";+import { defineConfig } from "vite";+import react from "@vitejs/plugin-react";+import tailwindcss from "@tailwindcss/vite";++const here = path.dirname(fileURLToPath(import.meta.url));++/** One entry per panel; the host HTML loads dist/webview/<view>.js. */+const VIEWS = [+ "health",+ "architecture",+ "graph",+ "refactoring",+ "decisions",+ "docs",+ "risk",+] as const;++export default defineConfig({+ root: here,+ plugins: [react(), tailwindcss()],+ resolve: {+ alias: {+ // The shared UI package peers on next-themes; inside a webview the+ // editor owns the theme, so the hook is served by a local shim.+ "next-themes": path.resolve(here, "src/shims/next-themes.ts"),+ // The Lottie loader fetches WASM + JSON at runtime; both are blocked by+ // the webview CSP, so loading states render a CSS spinner instead.+ "@lottiefiles/dotlottie-react": path.resolve(here, "src/shims/dotlottie-react.tsx"),+ },+ },+ build: {+ outDir: path.resolve(here, "../dist/webview"),+ emptyOutDir: true,+ target: "chrome120",+ // One stylesheet for all views: the palette is global anyway, and a+ // fixed name keeps the host HTML builder trivial.+ cssCodeSplit: false,+ sourcemap: false,+ rollupOptions: {+ input: Object.fromEntries(+ VIEWS.map((view) => [view, path.resolve(here, `src/views/${view}/main.tsx`)]),+ ),+ output: {+ entryFileNames: "[name].js",+ chunkFileNames: "chunks/[name]-[hash].js",+ assetFileNames: (info) =>+ info.names?.some((n) => n.endsWith(".css"))+ ? "webview.css"+ : "assets/[name]-[hash][extname]",+ },+ onwarn(warning, warn) {+ // "use client" directives from the shared UI sources are meaningless+ // outside an RSC bundler and safe to drop silently.+ if (warning.code === "MODULE_LEVEL_DIRECTIVE") return;+ warn(warning);+ },+ },+ },+});diff --git a/packages/vscode/webview/vitest.config.mts b/packages/vscode/webview/vitest.config.mtsnew file mode 100644index 000000000..4cfe47fda--- /dev/null+++ b/packages/vscode/webview/vitest.config.mts@@ -0,0 +1,14 @@+import { defineConfig, mergeConfig } from "vitest/config";+import viteConfig from "./vite.config.mts";++export default mergeConfig(+ viteConfig,+ defineConfig({+ test: {+ environment: "jsdom",+ include: ["src/**/*.test.{ts,tsx}"],+ globals: false,+ passWithNoTests: true,+ },+ }),+);