The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
merge: der Design- und Technik-Audit-Strom kommt in die 2.6.8-Linie
purple4fa3919bab6e
diff --cc package-lock.jsonindex 4965601d,377e5a7d..635a5af4--- a/package-lock.json+++ b/package-lock.json@@@ -50,7 -49,7 +50,8 @@@"eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.5.2","globals": "^17.4.0",+ "jsdom": "^30.0.1",+ "madge": "^8.0.0","typescript": "~5.9.3","typescript-eslint": "^8.57.0","vite": "^8.0.1",@@@ -362,159 -308,20 +363,173 @@@"node": ">=6.9.0"}},+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",+ "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz",+ "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.2.tgz",+ "integrity": "sha512-3QKjR/vxyjcSXBLgb6lP0S3MGdvwbmqSsvLPbYdVORqPDc8FX1HAJ0Spk38bxaRXgvENTA47tlhhbb5Z2e8hEg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.1",+ "@csstools/css-calc": "^3.3.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.12.tgz",+ "integrity": "sha512-3vLQK+dXxhBMR2Wx99PTCifE+vHtW2ndZWyla8yK813ev6oGhyn8Lja8jCyGAWTJ+LEYZK7EVtJxrDj8ztevJw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",+ "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@dependents/detective-less": {+ "version": "5.0.3",+ "resolved": "https://registry.npmjs.org/@dependents/detective-less/-/detective-less-5.0.3.tgz",+ "integrity": "sha512-v6oD9Ukp+N7V4n6p5I/+mM5fIohSfkrDSGlFm5w/pYmchvbk+sMIHsLxrFJ5Lnujewj1BzWL0K84d88lwZAMQA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "gonzales-pe": "^4.3.0",+ "node-source-walk": "^7.0.1"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@dimforge/rapier3d-compat": {"version": "0.12.0","resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",@@@ -2065,55 -1879,96 +2105,145 @@@"@tauri-apps/api": "^2.10.1"}},+ "node_modules/@testing-library/dom": {+ "version": "10.4.1",+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",+ "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@babel/code-frame": "^7.10.4",+ "@babel/runtime": "^7.12.5",+ "@types/aria-query": "^5.0.1",+ "aria-query": "5.3.0",+ "dom-accessibility-api": "^0.5.9",+ "lz-string": "^1.5.0",+ "picocolors": "1.1.1",+ "pretty-format": "^27.0.2"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@testing-library/react": {+ "version": "16.3.3",+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz",+ "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.5"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@testing-library/dom": "^10.0.0",+ "@types/react": "^18.0.0 || ^19.0.0",+ "@types/react-dom": "^18.0.0 || ^19.0.0",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@ts-graphviz/adapter": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/@ts-graphviz/adapter/-/adapter-2.0.6.tgz",+ "integrity": "sha512-kJ10lIMSWMJkLkkCG5gt927SnGZcBuG0s0HHswGzcHTgvtUe7yk5/3zTEr0bafzsodsOq5Gi6FhQeV775nC35Q==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ts-graphviz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ts-graphviz"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@ts-graphviz/common": "^2.1.5"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@ts-graphviz/ast": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@ts-graphviz/ast/-/ast-2.0.7.tgz",+ "integrity": "sha512-e6+2qtNV99UT6DJSoLbHfkzfyqY84aIuoV8Xlb9+hZAjgpum8iVHprGeAMQ4rF6sKUAxrmY8rfF/vgAwoPc3gw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ts-graphviz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ts-graphviz"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@ts-graphviz/common": "^2.1.5"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@ts-graphviz/common": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@ts-graphviz/common/-/common-2.1.5.tgz",+ "integrity": "sha512-S6/9+T6x8j6cr/gNhp+U2olwo1n0jKj/682QVqsh7yXWV6ednHYqxFw0ZsY3LyzT0N8jaZ6jQY9YD99le3cmvg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ts-graphviz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ts-graphviz"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@ts-graphviz/core": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@ts-graphviz/core/-/core-2.0.7.tgz",+ "integrity": "sha512-w071DSzP94YfN6XiWhOxnLpYT3uqtxJBDYdh6Jdjzt+Ce6DNspJsPQgpC7rbts/B8tEkq0LHoYuIF/O5Jh5rPg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ts-graphviz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ts-graphviz"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@ts-graphviz/ast": "^2.0.7",+ "@ts-graphviz/common": "^2.1.5"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@tweenjs/tween.js": {"version": "23.1.3","resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",@@@ -6191,10 -6832,20 +7299,20 @@@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/pluralize": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz",+ "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },"node_modules/postcss": {- "version": "8.5.15",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",- "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",- "version": "8.5.26",- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",- "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",++ "version": "8.5.28",++ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",++ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==","funding": [{"type": "opencollective",@@@ -6211,7 -6862,7 +7329,7 @@@],"license": "MIT","dependencies": {- "nanoid": "^3.3.12",- "nanoid": "^3.3.17",++ "nanoid": "^3.3.18","picocolors": "^1.1.1","source-map-js": "^1.2.1"},@@@ -6235,36 -6944,22 +7411,52 @@@"node": ">= 0.8.0"}},+ "node_modules/pretty-format": {+ "version": "27.5.1",+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",+ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "ansi-regex": "^5.0.1",+ "ansi-styles": "^5.0.0",+ "react-is": "^17.0.1"+ },+ "engines": {+ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"+ }+ },+ "node_modules/pretty-format/node_modules/ansi-styles": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/pretty-ms": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-7.0.1.tgz",+ "integrity": "sha512-973driJZvxiGOQ5ONsFhOF/DtzPMOMtgC11kCpUrPGMTgqp2q/1gwzCquocrN33is0VZ5GFHXZYMM9l6h67v2Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "parse-ms": "^2.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/prismjs": {"version": "1.30.0","resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",@@@ -6613,19 -7407,33 +7912,46 @@@"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==","license": "MIT"},+ "node_modules/sass-lookup": {+ "version": "6.1.2",+ "resolved": "https://registry.npmjs.org/sass-lookup/-/sass-lookup-6.1.2.tgz",+ "integrity": "sha512-GjmndmKQBtlPil79RK72L7yc5kDXZPCQeH97bP8R8DcxtXQJO6vECExb3WP/m6+cxaV9h4ZxrSRvCkPG2v/VSw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "commander": "^12.1.0",+ "enhanced-resolve": "^5.20.0"+ },+ "bin": {+ "sass-lookup": "bin/cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/sass-lookup/node_modules/commander": {+ "version": "12.1.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",+ "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",@@@ -7544,19 -8435,26 +9016,39 @@@}}},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/walkdir": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/walkdir/-/walkdir-0.4.1.tgz",+ "integrity": "sha512-3eBwRyEln6E1MSzcxcVpQIhRG8Q1jLvEqRmCZqS3dsfXEDR/AhOF4d+jHg1qvDCpYaVRZjENPQyrVxAkQqxPgQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/wcwidth": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",+ "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "defaults": "^1.0.3"+ }+ },"node_modules/web-namespaces": {"version": "2.0.1","resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz",diff --cc package.jsonindex f9348b32,a8a38fbb..87b82425--- a/package.json+++ b/package.json@@@ -76,7 -78,7 +79,8 @@@"eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.5.2","globals": "^17.4.0",+ "jsdom": "^30.0.1",+ "madge": "^8.0.0","typescript": "~5.9.3","typescript-eslint": "^8.57.0","vite": "^8.0.1",diff --cc src-tauri/src/app_identity.rsindex 00000000,6ce4d989..244a3e59mode 000000,100644..100644--- a/src-tauri/src/app_identity.rs+++ b/src-tauri/src/app_identity.rs@@@ -1,0 -1,311 +1,150 @@@+ //! Die Namen der app-eigenen Verzeichnisse — an EINER Stelle.+ //!+ //! ## Warum es diese Datei gibt+ //!-//! Dieser Branch (`experiment/audits-komplett`) hat **bewusst ein eigenes-//! Datenverzeichnis** und teilt nichts mit der installierten echten App.++//! Der Verzeichnisname wird auf der Rust-Seite **nicht** aus der++//! Tauri-`identifier` abgeleitet. Er stand als String an acht Stellen im++//! Quelltext, jede davon ein `dirs::*` plus ein angehängtes Literal. Ein++//! eigener `identifier` in `tauri.conf.json` trennt deshalb WebView-Speicher++//! und Single-Instance-Socket, aber eben nicht diese Pfade.+ //!-//! Am 2026-08-31 hat der erste echte Start des Experiment-Builds-//! (`npm run tauri dev`) in `~/Library/Application Support/lu-labs/`-//! geschrieben — dem Datenverzeichnis der ECHTEN App. Dabei wurde-//! `stores/store_backup.json` überschrieben und `lu-providers` auf einen-//! Zustand aus einem fremden Lauf zurückgesetzt (`lu-cloud` von `enabled:-//! true` auf `false`). Dass die 6,7 MB echter Chats überlebt haben, lag-//! allein an der Merge-Rettung in `commands::system` (`keys_lost` /-//! `merged_backup`) — das ist ein Sicherheitsnetz, keine Isolation.-//!-//! Die Ursache: der Verzeichnisname wird auf der Rust-Seite **nicht** aus der-//! Tauri-`identifier` abgeleitet, sondern war als String an acht Stellen-//! hartkodiert. Ein eigener `identifier` in `tauri.conf.json` trennt daher-//! WebView-Speicher und Single-Instance-Socket, aber eben nicht die Pfade, die-//! sich aus `dirs::*` und einem angehängten Literal zusammensetzen.++//! Was daran gefährlich ist, hat sich am 2026-08-31 gezeigt: ein Build, der++//! sich für eine andere App hielt, schrieb in++//! `~/Library/Application Support/lu-labs/`, überschrieb dort++//! `stores/store_backup.json` und setzte `lu-providers` auf den Zustand eines++//! fremden Laufs zurück. Dass 6,7 MB echter Chats überlebt haben, lag allein++//! an der Merge-Rettung in `commands::system` (`keys_lost` / `merged_backup`)++//! — ein Sicherheitsnetz, keine Trennung.+ //!+ //! ## Wie es jetzt läuft+ //!-//! [`branch_dir_suffix!`] ist der einzige Schalter. Er hängt an jeden Namen,-//! den diese App auf der Platte (und im Schlüsselbund) besitzt. Für die-//! **echte App gehört hier `""` hin** — `lu-labs`, `locally-uncensored`,-//! `Locally Uncensored` und `agent-workspace` sind dort die richtigen Namen-//! und dürfen sich nicht ändern. Nur dieser Branch setzt einen Suffix.++//! Jeder Name, den diese App auf der Platte und im Schlüsselbund besitzt,++//! steht genau einmal hier und wird überall von hier geholt. Diese Konstanten++//! sind die Namen der echten App und dürfen sich nicht ändern: ein anderer++//! `APP_DIR` lässt die App die Daten des Nutzers nicht mehr finden, ein++//! anderer `KEYCHAIN_SERVICE` verwaist seine gespeicherten Schlüssel.+ //!-//! Wer den Suffix auf `""` zurückdreht, fällt in-//! [`tests::keiner_der_namen_ist_der_name_der_echten_app`] und-//! [`tests::kein_abgeleiteter_pfad_zeigt_in_ein_verzeichnis_der_echten_app`]-//! durch. Das ist Absicht.++//! Festgenagelt wird beides von zwei Tests:++//! [`tests::die_namen_sind_die_der_echten_app`] hält die fünf Werte fest, und++//! [`tests::keine_quelldatei_baut_einen_pfad_der_echten_app_von_hand`] liest++//! alle eigenen Quellen und findet jede Stelle, die einen dieser Namen wieder++//! selbst zusammensetzt statt ihn hier zu holen. Der zweite ist der++//! eigentliche Zweck der Datei: eine Sammelstelle, an der niemand vorbeikommt,++//! ist eine Sammelstelle, die nur so lange hält, wie das jemand prüft.+ //!+ //! ## Was hier NICHT drin steht+ //!+ //! * Die Tauri-`identifier` (`tauri.conf.json`) — sie steuert+ //! `app_data_dir()`/`app_config_dir()`, den Single-Instance-Socket und den-//! WebView-Speicher **gebündelter** Builds; die ist bereits getrennt.++//! WebView-Speicher **gebündelter** Builds.+ //! * Der Binärname (`Cargo.toml`, `[package] name`) — er steuert unter macOS+ //! im `tauri dev`-Modus das WebKit-Verzeichnis (`~/Library/WebKit/<Name>`).-//! Die ausführliche Begründung steht als Kommentar in `Cargo.toml`;-//! festgenagelt wird er von-//! [`tests::der_binaername_ist_nicht_der_der_echten_app`].--/// **Der einzige Schalter.** Suffix an jedem app-eigenen Verzeichnisnamen.-///-/// * Echte App / upstream: `""`-/// * Branch `experiment/audits-komplett`: `"-experiment"`-///-/// Ein Makro (und nicht eine `const`), weil `concat!` nur Literale-/// zusammensetzen kann — so bleibt jeder Name unten eine echte-/// Compile-Zeit-Konstante statt eines `format!` zur Laufzeit.-macro_rules! branch_dir_suffix {- () => {- "-experiment"- };-}++ /// Haupt-Datenverzeichnis dieser App unter `data_local_dir()`, `cache_dir()`+ /// und `config_dir()`.+ ///+ /// * macOS: `~/Library/Application Support/<APP_DIR>`+ /// * Windows: `%LOCALAPPDATA%\<APP_DIR>`+ /// * Linux: `~/.local/share/<APP_DIR>`, `~/.cache/<APP_DIR>`,+ /// `~/.config/<APP_DIR>`-pub const APP_DIR: &str = concat!("lu-labs", branch_dir_suffix!());++pub const APP_DIR: &str = "lu-labs";++ /// Älterer Ordner unter `config_dir()` bzw. `data_local_dir()`: hält+ /// `config.json` (ComfyUI-Pfad/-Port, Ollama-Basis, Trainer-Root) und+ /// `bin/cloudflared`.-pub const APP_CONFIG_DIR: &str = concat!("locally-uncensored", branch_dir_suffix!());++pub const APP_CONFIG_DIR: &str = "locally-uncensored";++ /// Die Anzeige-Schreibweise desselben Namens. Zwei Verwendungen:+ /// `%APPDATA%\<APP_DISPLAY_DIR>` (Store-Backups + Onboarding-Marker, Windows)+ /// und `<data_dir>/<APP_DISPLAY_DIR>/models` (Modelle der eingebauten Engine).-pub const APP_DISPLAY_DIR: &str = concat!("Locally Uncensored", branch_dir_suffix!());++pub const APP_DISPLAY_DIR: &str = "Locally Uncensored";++ /// Sandkasten-Wurzel der Agenten unter `$HOME`. Pro Chat entsteht darin ein+ /// Unterordner; der Agent darf nichts außerhalb anfassen.-pub const AGENT_WORKSPACE_DIR: &str = concat!("agent-workspace", branch_dir_suffix!());++pub const AGENT_WORKSPACE_DIR: &str = "agent-workspace";++ /// Service-Name im OS-Schlüsselbund (macOS Keychain / Windows Credential+ /// Manager) für Provider-Schlüssel und die Cloud-Sitzung.+ ///+ /// Gehört hierher, obwohl es kein Pfad ist: der Name war ebenfalls-/// hartkodiert, und ohne Suffix läse und **überschriebe** der-/// Experiment-Build die echten API-Schlüssel des Nutzers. In der echten App-/// muss er stabil bleiben — ein geänderter Service-Name verwaist die dort-/// gespeicherten Schlüssel.-pub const KEYCHAIN_SERVICE: &str =- concat!("com.locallyuncensored.providerkeys", branch_dir_suffix!());++/// hartkodiert, und wer ihn ändert, verwaist alle Schlüssel, die der Nutzer++/// unter dem alten Namen gespeichert hat. Ein Build mit einem abweichenden++/// Service-Namen liest und **überschreibt** außerdem fremde Einträge.++pub const KEYCHAIN_SERVICE: &str = "com.locallyuncensored.providerkeys";++ #[cfg(test)]+ mod tests {+ use super::*;- use std::path::{Component, Path};+- /// Die Namen, die der ECHTEN App gehören.++ /// Die Namen, die dieser App gehören.+ ///+ /// Bewusst als eigene Literale wiederholt und **nicht** aus den- /// Konstanten oben abgeleitet: ein Test, der seine Erwartung aus dem- /// prüft, was er absichern soll, prüft nichts.++ /// Konstanten oben abgeleitet: ein Test, der seine Erwartung aus dem holt,++ /// was er absichern soll, prüft nichts.+ const NAMEN_DER_ECHTEN_APP: [&str; 4] = [+ "lu-labs",+ "locally-uncensored",+ "Locally Uncensored",+ "agent-workspace",+ ];+- /// Mutationsprobe: `branch_dir_suffix!()` auf `""` zurückdrehen lässt- /// genau diesen Test rot werden.- #[test]- fn keiner_der_namen_ist_der_name_der_echten_app() {- for name in [- APP_DIR,- APP_CONFIG_DIR,- APP_DISPLAY_DIR,- AGENT_WORKSPACE_DIR,- ] {- assert!(- !NAMEN_DER_ECHTEN_APP.contains(&name),- "'{name}' ist der Verzeichnisname der ECHTEN App — dieser Build \- würde in die Daten des Nutzers schreiben. branch_dir_suffix!() prüfen."- );- }- assert_ne!(- KEYCHAIN_SERVICE, "com.locallyuncensored.providerkeys",- "der Experiment-Build teilte sonst den Schlüsselbund-Eintrag der echten App"- );- }-- /// Der WebView-Speicher hängt unter macOS im `tauri dev`-Modus NICHT an- /// der Tauri-`identifier`, sondern am Namen der laufenden Datei: ein nicht- /// gebündeltes Programm hat keine Bundle-ID, also nimmt WebKit- /// `processName` (= Dateiname) und legt localStorage/IndexedDB unter- /// `~/Library/WebKit/<Dateiname>/` ab. `cargo run` benennt die Datei nach- /// `[package] name`.- ///- /// Solange der `locally-uncensored` hieß, teilte dieser Build denselben- /// localStorage mit jedem `tauri dev` aus dem echten Repo. Deshalb steht- /// der Name hier unter Test — er ist Isolation, nicht Kosmetik.- #[test]- fn der_binaername_ist_nicht_der_der_echten_app() {- assert_ne!(- env!("CARGO_PKG_NAME"),- "locally-uncensored",- "der Dateiname der ausführbaren Datei bestimmt unter macOS das \- WebKit-Verzeichnis im dev-Modus — mit diesem Namen teilt der \- Experiment-Build localStorage mit dem echten Repo"- );- if let Some(bin) = option_env!("CARGO_BIN_NAME") {- assert_ne!(bin, "locally-uncensored");- }- }-- /// Der Suffix muss auch wirklich trennen und nicht nur anders aussehen.++ /// Ein Build, der unter einem anderen Namen läuft, findet die Daten des++ /// Nutzers nicht mehr und legt daneben neue an. Genau das ist am++ /// 2026-08-31 passiert, nur in die andere Richtung. Die fünf Werte stehen++ /// deshalb doppelt: einmal als Auslieferungscode, einmal hier.+ #[test]- fn suffix_ist_nicht_leer_und_haengt_an_jedem_namen() {- let suffix = branch_dir_suffix!();- assert!(!suffix.is_empty(), "ohne Suffix gibt es keine Trennung");- for name in [- APP_DIR,- APP_CONFIG_DIR,- APP_DISPLAY_DIR,- AGENT_WORKSPACE_DIR,- KEYCHAIN_SERVICE,- ] {++ fn die_namen_sind_die_der_echten_app() {++ assert_eq!(APP_DIR, "lu-labs");++ assert_eq!(APP_CONFIG_DIR, "locally-uncensored");++ assert_eq!(APP_DISPLAY_DIR, "Locally Uncensored");++ assert_eq!(AGENT_WORKSPACE_DIR, "agent-workspace");++ assert_eq!(KEYCHAIN_SERVICE, "com.locallyuncensored.providerkeys");++ // Und kein Name trägt einen Anhang: ein Build aus einem++ // Experimentierzweig darf nicht versehentlich ausgeliefert werden.++ for name in [APP_DIR, APP_CONFIG_DIR, APP_DISPLAY_DIR, AGENT_WORKSPACE_DIR] {+ assert!(- name.ends_with(suffix),- "'{name}' trägt den Branch-Suffix nicht"++ NAMEN_DER_ECHTEN_APP.contains(&name),++ "'{name}' ist keiner der Namen dieser App"+ );+ }+ }+- /// Ein Pfadbestandteil, der einem Verzeichnis der echten App entspricht.- ///- /// Verglichen wird **komponentenweise und exakt**, nicht mit `starts_with`- /// auf dem ganzen Pfad: `lu-labs-experiment` ist erlaubt, `lu-labs` nicht,- /// und ein Präfix-Vergleich könnte die beiden nicht auseinanderhalten.- /// Zusätzlich case-insensitiv, weil macOS (APFS) und Windows- /// Groß-/Kleinschreibung in Pfaden nicht unterscheiden — `LU-LABS` wäre- /// dort dasselbe Verzeichnis.- fn kollidierende_komponente(pfad: &Path) -> Option<String> {- for c in pfad.components() {- if let Component::Normal(os) = c {- let s = os.to_string_lossy();- if let Some(hit) = NAMEN_DER_ECHTEN_APP- .iter()- .find(|n| n.eq_ignore_ascii_case(&s))- {- return Some((*hit).to_string());- }- }- }- None- }-- /// Jeder Pfad, den dieser Build sich selbst zusammenbaut — einmal- /// aufgezählt, einmal geprüft. Kommt eine neue Ableitung dazu, gehört sie- /// hier hinein.- fn alle_abgeleiteten_pfade() -> Vec<(&'static str, std::path::PathBuf)> {- use crate::os_paths as p;- vec![- ("data_dir", p::data_dir()),- ("cache_dir", p::cache_dir()),- ("config_root", p::config_root()),- ("log_dir", p::log_dir()),- ("app_config_dir", p::app_config_dir()),- ("app_config_json", p::app_config_json()),- ("tools_bin_dir", p::tools_bin_dir()),- ("builtin_models_dir", p::builtin_models_dir()),- ("agent_workspace_root", p::agent_workspace_root()),- ("default_comfyui_dir", p::default_comfyui_dir()),- ("mlx_root", p::data_dir().join("mlx")),- ("stores_dir", p::data_dir().join("stores")),- ("crash_log", crate::crash_report::crash_log_path()),- ("images_root", crate::commands::mlx::images_root()),- ("video_models_root", crate::commands::video::models_root()),- ("video_outputs_root", crate::commands::video::outputs_root()),- (- "persistent_dir",- crate::commands::system::persistent_dir().expect("persistent_dir"),- ),- ]- }-- /// Mutationsprobe: `branch_dir_suffix!()` auf `""` zurückdrehen lässt auch- /// diesen Test rot werden — und zwar für jeden einzelnen Pfad.- #[test]- fn kein_abgeleiteter_pfad_zeigt_in_ein_verzeichnis_der_echten_app() {- // Alle Verstöße sammeln statt beim ersten abzubrechen: wer den Suffix- // zurückdreht, soll die ganze Liste sehen und nicht einen Pfad nach- // dem anderen.- let mut verstoesse: Vec<String> = Vec::new();- for (name, pfad) in alle_abgeleiteten_pfade() {- if let Some(treffer) = kollidierende_komponente(&pfad) {- verstoesse.push(format!("{name} = {} (via '{treffer}')", pfad.display()));- }- }- assert!(- verstoesse.is_empty(),- "diese Pfade zeigen in ein Verzeichnis der ECHTEN App — dieser Build \- darf dort weder lesen noch schreiben:\n {}",- verstoesse.join("\n ")- );- }-- /// Gegenprobe zur Prüfmethode selbst: sie muss einen Treffer auch finden.- /// Ohne das wäre ein immer-`None` liefernder Prüfer ein grüner Test.- #[test]- fn die_pruefung_erkennt_einen_echten_treffer() {- let echt = Path::new("/Users/x/Library/Application Support/lu-labs/stores");- assert_eq!(kollidierende_komponente(echt).as_deref(), Some("lu-labs"));-- let gross = Path::new("/Users/x/AppData/Local/LU-LABS/logs");- assert_eq!(kollidierende_komponente(gross).as_deref(), Some("lu-labs"));-- // …und ein Suffix-Name ist ausdrücklich KEIN Treffer.- let unser = Path::new("/Users/x/Library/Application Support/lu-labs-experiment/stores");- assert_eq!(kollidierende_komponente(unser), None);- }-- /// Die Präfix-Falle: `lu-labs-experiment` fängt mit `lu-labs` an. Sobald- /// irgendwo im Code ein Präfix-Vergleich oder ein Glob auf dem nackten- /// Namen steht, erwischt das beide Verzeichnisse und die Trennung ist- /// wieder weg. Genauso wandert ein neu angehängtes Literal an der- /// Konstante vorbei.- ///- /// Deshalb scannt dieser Test die eigenen Quellen. Die Nadeln werden zur- /// Laufzeit gebaut, damit der Test sich nicht selbst findet.+ #[test]+ fn keine_quelldatei_baut_einen_pfad_der_echten_app_von_hand() {+ let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");+ let mut funde: Vec<String> = Vec::new();++ for eintrag in walkdir::WalkDir::new(&src)+ .into_iter()+ .filter_map(Result::ok)+ .filter(|e| e.path().extension().is_some_and(|x| x == "rs"))+ {+ let Ok(inhalt) = std::fs::read_to_string(eintrag.path()) else {+ continue;+ };+ for name in NAMEN_DER_ECHTEN_APP {+ for nadel in [+ format!(".join(\"{name}\")"),+ format!("starts_with(\"{name}\")"),+ format!("\"{name}*\""),+ format!("\"{name}/"),+ format!("\"{name}\\\\"),+ ] {+ if inhalt.contains(&nadel) {+ funde.push(format!(+ "{}: {nadel}",+ eintrag.path().strip_prefix(&src).unwrap_or(eintrag.path()).display()+ ));+ }+ }+ }+ }++ assert!(+ funde.is_empty(),+ "Pfade der ECHTEN App im Quelltext zusammengebaut — jeder dieser Namen \+ gehört über die Konstanten in app_identity abgeleitet:\n {}",+ funde.join("\n ")+ );+ }+ }diff --cc src-tauri/src/commands/agent.rsindex 16a04fb4,6468b29f..0dda977b--- a/src-tauri/src/commands/agent.rs+++ b/src-tauri/src/commands/agent.rs@@@ -269,7 -391,7 +391,7 @@@ mod path_tests/// Runs on the blocking pool: the poll loop below waits for the Python process/// for up to `timeout_ms`, and a sync #[command] would spend all of that on the--/// Tauri main thread with the window frozen (same class as install.rs and the++/// Tauri main thread with the window frozen (same class as the installer tree and the/// built-in engine). The shell tool next door already did it this way.#[tauri::command]pub async fn execute_code(diff --cc src-tauri/src/commands/bg_tasks.rsindex 12166d53,601438e0..0e259839--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@@ -604,17 -1098,175 +1098,175 @@@ mod cwd_default_tests.expect("start");let id = start["id"].as_str().unwrap().to_string();- let mut seen = String::new();- for _ in 0..40 {- tokio::time::sleep(std::time::Duration::from_millis(50)).await;- let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();- seen = st["output_tail"].as_str().unwrap_or("").to_string();- if !seen.trim().is_empty() {- break;+ let seen = reported_directory(&id).await;+ assert!(+ same_directory(&seen, &b),+ "the explicit cwd lost: reported {seen:?}, wanted {b:?}",+ );+ // Negative control: the folder that must NOT have won.+ assert!(!same_directory(&seen, &a), "the task ran in the fallback {a:?}");+ }+ }++ /// The background task and its foreground twin, held against each other.+ ///+ /// They are the same tool with two lifetimes: `shell_execute` waits,+ /// `shell_execute` with `background: true` hands back a task id. A caller that+ /// names a shell must get that shell, invoked the same way, on either path.+ /// They drifted apart once — this file built PowerShell's argument form for+ /// every program on Windows while the foreground built it from the shell's+ /// name — and the drift was invisible to every non-Windows test run.+ #[cfg(test)]+ mod foreground_parity_tests {+ use super::*;++ /// A shell that is deliberately NOT the platform default, so the `shell`+ /// field is actually exercised rather than skipped.+ ///+ /// Windows: `cmd`, the exact value that used to be handed+ /// `-NoProfile -NonInteractive -Command` and fail. Unix: `sh`, which is+ /// not the `bash` default and is present on every machine this runs on.+ fn a_named_shell() -> &'static str {+ if cfg!(target_os = "windows") {+ "cmd"+ } else {+ "sh"+ }+ }++ /// One line, one word of output, and the same source text in cmd.exe and+ /// in a POSIX shell — so the assertion is about the invocation, not about+ /// a dialect difference in the command itself.+ const TOKEN: &str = "lu-parity-7f3a";++ fn the_command() -> String {+ format!("echo {TOKEN}")+ }++ /// A directory both runs can start in, so neither path has to fall back to+ /// the per-chat workspace and touch the user's home.+ ///+ /// `os_paths::test_dir` statt eines selbstgebauten `temp_dir().join(…)`:+ /// das Aufräumen hängt dort am `Drop` und läuft deshalb auch dann, wenn+ /// eine der Assertions dazwischen scheitert — die letzte Zeile des Tests+ /// tat das nicht, und genau im Fehlerfall blieb der Ordner liegen. Der+ /// Name trägt zusätzlich die ThreadId, und unter Windows liegt er unter+ /// `target/`, wo ein `cargo clean` ihn erwischt.+ fn a_directory() -> crate::os_paths::TestDir {+ crate::os_paths::test_dir("parity")+ }++ async fn what_the_foreground_printed(dir: &std::path::Path) -> (String, i64) {+ let out = crate::commands::shell::shell_execute(+ the_command(),+ None,+ Some(dir.to_string_lossy().to_string()),+ Some(20_000),+ Some(a_named_shell().to_string()),+ None,+ None,+ None,+ )+ .await+ .expect("the foreground shell tool ran");+ (+ out["stdout"].as_str().unwrap_or_default().trim().to_string(),+ out["exitCode"].as_i64().unwrap_or(-1),+ )+ }++ async fn what_the_background_printed(dir: &std::path::Path) -> (String, i64) {+ let start = shell_task_start_impl(&json!({+ "command": the_command(),+ "shell": a_named_shell(),+ "cwd": dir.to_string_lossy(),+ }))+ .await+ .expect("the background task started");+ let id = start["id"].as_str().expect("id").to_string();+ for _ in 0..200 {+ let st = shell_task_status_impl(&json!({ "id": id })).await.expect("status");+ if !st["running"].as_bool().unwrap_or(true) {+ return (+ st["output_tail"].as_str().unwrap_or_default().trim().to_string(),+ st["exit_code"].as_i64().unwrap_or(-1),+ );}+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;}- assert_eq!(seen.trim(), expected.to_string_lossy());- let _ = std::fs::remove_dir_all(&a);- let _ = std::fs::remove_dir_all(&b);+ panic!("the background task never finished");+ }++ /// The behavioural half: same shell, same command, same result.+ ///+ /// On Windows this fails outright without the shared argument builder —+ /// `cmd -NoProfile -NonInteractive -Command echo …` prints cmd.exe's usage+ /// complaint and never echoes the token. On Unix it holds `sh` to the same+ /// contract on both paths, which is the property that has to keep holding+ /// for the Windows one to stay true.+ ///+ /// The isolation guard is held across the awaits below, on purpose and like+ /// every other test here that stands up a live task: it is what keeps the+ /// shutdown-sweep tests from killing this task's child mid-run. It used to+ /// carry an `#[allow(clippy::await_holding_lock)]` for that; the lock is an+ /// async mutex now, so there is nothing left to allow.+ #[tokio::test]+ async fn a_named_shell_behaves_the_same_in_the_background_as_in_the_foreground() {+ let _isolation = super::sweep_isolation().await;+ let dir = a_directory();++ let (foreground, fg_code) = what_the_foreground_printed(&dir).await;+ let (background, bg_code) = what_the_background_printed(&dir).await;++ // Both really ran — without this the assertion below would also pass+ // on two empty strings, i.e. on two equally broken paths.+ assert!(+ foreground.contains(TOKEN),+ "the foreground shell tool printed {foreground:?} with shell {:?}",+ a_named_shell(),+ );+ assert!(+ background.contains(TOKEN),+ "the background task printed {background:?} with shell {:?} — \+ the shell it was given was invoked with the wrong argument form",+ a_named_shell(),+ );+ assert_eq!(+ foreground, background,+ "the same command in the same shell came out differently on the two paths",+ );+ assert_eq!((fg_code, bg_code), (0, 0), "one of the two paths failed");+ // Kein `remove_dir_all` mehr: `dir` ist ein `TestDir` und räumt beim+ // Verlassen selbst auf, auch wenn eine Assertion oben vorher panickt.+ }++ /// The structural half: this file must not grow a second copy of the+ /// branch. The behavioural test above can only observe ONE shell per+ /// platform per run; a re-inlined branch that breaks a different shell+ /// would slip past it, and that is exactly how the original bug survived.+ ///- /// Scoped to this file on purpose: `system.rs` and `install.rs` also spawn++ /// Scoped to this file on purpose: `system.rs` and the `install/` tree also spawn+ /// PowerShell with these flags, but they hardcode PowerShell for scripts of+ /// their own and never take a shell from a caller, so they are not twins of+ /// anything and are none of this test's business.+ #[test]+ fn the_background_path_builds_no_shell_flags_of_its_own() {+ const BG_TASKS_RS: &str = include_str!("bg_tasks.rs");+ // Split out of one string rather than written as separate literals:+ // a list of quoted flags would itself be the quoted flag this test+ // searches for, and the test would trip over its own source.+ for flag in "-NoProfile -NonInteractive -Command /C -c".split(' ') {+ let literal = format!("{:?}", flag);+ assert!(+ !BG_TASKS_RS.contains(&literal),+ "bg_tasks.rs builds the shell argument {flag} itself again — \+ that branch belongs in shell::shell_argv, which the foreground \+ path uses too",+ );+ }+ assert!(+ BG_TASKS_RS.contains("shell::shell_argv("),+ "the background path no longer goes through the shared argument builder",+ );}}diff --cc src-tauri/src/commands/custom_models.rsindex c80ada56,00000000..05dd5d88mode 100644,000000..100644--- a/src-tauri/src/commands/custom_models.rs+++ b/src-tauri/src/commands/custom_models.rs@@@ -1,506 -1,0 +1,506 @@@+//! The user's own model folder, handed to ComfyUI.+//!+//! GH #122 (zrmdsxa) plus the Discord thread "Read me first" (ever.noob):+//! the folder under Settings → Model Storage was a download target and nothing+//! more. Chat GGUFs in it are read by `engine::scan_gguf_roots` now, but a+//! `.safetensors` is a different problem: LU never scans image or video models+//! off the disk at all. That inventory comes out of ComfyUI's own `/object_info`+//! enums, and ComfyUI only lists what sits under its own `models/` tree.+//!+//! So the honest way in is ComfyUI's own mechanism: an extra-model-paths config.+//! We write our own file and pass it with `--extra-model-paths-config`, so a+//! hand written `extra_model_paths.yaml` in the ComfyUI folder is never touched+//! and nothing changes for a user who set none. Two limits are real and the+//! Settings text says both: it reaches a ComfyUI that LU starts, and it takes+//! effect the next time ComfyUI starts.+//!+//! Only subfolders NAMED like ComfyUI's model folders are mapped. A flat dump+//! of mixed files is left alone on purpose: mapping it into every key would+//! offer one checkpoint as a LoRA, a VAE and a ControlNet at the same time.++use std::path::{Path, PathBuf};++/// The `folder_paths` keys ComfyUI accepts in an extra-model-paths file, which+/// are also the folder names it uses on disk.+///+/// Two directions to keep straight, and a test for each. Every folder LU's own+/// inventory reads has to be in here, or a file the app can see would be one+/// LU never hands over (`subfolderForSource` in `src/api/comfyui.ts`). And+/// every entry here has to be a key ComfyUI really has, or the config file+/// carries a line ComfyUI ignores at best.+///+/// `clip` and `unet` are ComfyUI's older names for `text_encoders` and+/// `diffusion_models`; both are still live keys and a folder filed under the+/// old name is common. `audio_encoders` is the newer audio lane. None of the+/// three appears in `subfolderForSource`, which is why the first test can only+/// check one direction.+pub(crate) const COMFY_MODEL_FOLDERS: &[&str] = &[+ "audio_encoders",+ "checkpoints",+ "clip",+ "clip_vision",+ "controlnet",+ "diffusion_models",+ "embeddings",+ "loras",+ "style_models",+ "text_encoders",+ "unet",+ "upscale_models",+ "vae",+];++/// Which ComfyUI-shaped folders exist below `root`.+///+/// Both layouts count: the folder the user picked may itself be a ComfyUI-style+/// tree (`G:\AI\Models\loras`) or may hold one (`G:\AI\Models\models\loras`).+/// Returned in the order of `COMFY_MODEL_FOLDERS` so the written file is stable+/// and a rewrite with nothing changed produces the same bytes.+pub(crate) fn comfy_shaped_subdirs(root: &Path) -> Vec<(&'static str, PathBuf)> {+ let mut out = Vec::new();+ for key in COMFY_MODEL_FOLDERS {+ for candidate in [root.join(key), root.join("models").join(key)] {+ if candidate.is_dir() {+ out.push((*key, candidate));+ break;+ }+ }+ }+ out+}++/// The YAML ComfyUI reads, or `None` when the folder holds nothing ComfyUI+/// could place. Absolute paths per key rather than one `base_path`, because the+/// two layouts above can be mixed inside one folder.+///+/// SINGLE quotes, and every `'` inside the path doubled. A double-quoted YAML+/// scalar treats the backslash as an escape character, so a Windows path is not+/// a string there at all: PyYAML reads `"G:\AI\Models\loras"` as+/// `unknown escape character 'A'` and `"D:\text_encoders"` as `D:<TAB>ext_...`.+/// ComfyUI's `load_extra_path_config` runs without a try/except, so a file like+/// that does not cost the folder mapping, it costs ComfyUI: the Windows user+/// this whole fix exists for would have been left without one. A single-quoted+/// scalar has no escapes at all, which is exactly what a path needs.+///+/// A path carrying a line break or another control character is dropped instead+/// of quoted. No model folder has one, and a broken line would take the other+/// folders in the file down with it.+pub(crate) fn build_extra_model_paths_yaml(root: &Path) -> Option<String> {+ let found: Vec<(&str, PathBuf)> = comfy_shaped_subdirs(root)+ .into_iter()+ .filter(|(_, p)| !p.to_string_lossy().chars().any(|c| c.is_control()))+ .collect();+ if found.is_empty() {+ return None;+ }+ let mut s = String::from(+ "# Written by Locally Uncensored from Settings -> Model Storage.\n\+ # Edit the folder in the app, not this file: it is rewritten on every change.\n\+ lu_custom_models:\n",+ );+ for (key, path) in found {+ s.push_str(&yaml_path_line(key, &path));+ }+ Some(s)+}++/// One `key: path` line. The single place the quoting rule above lives, so a+/// test can hold a literal Windows path against the SHIPPED formatting instead+/// of against a copy of it.+pub(crate) fn yaml_path_line(key: &str, path: &Path) -> String {+ format!(+ " {}: '{}'\n",+ key,+ path.to_string_lossy().replace('\'', "''")+ )+}++/// Where the generated file lives: beside the app's own models dir, never+/// inside the user's ComfyUI folder.+pub(crate) fn extra_model_paths_file() -> Result<PathBuf, String> {+ let base = dirs::data_dir().ok_or("Cannot resolve app data directory")?;- let dir = base.join("Locally Uncensored");++ let dir = base.join(crate::app_identity::APP_DISPLAY_DIR);+ std::fs::create_dir_all(&dir)+ .map_err(|e| format!("Create app data dir: {}", crate::os_error::english(&e)))?;+ Ok(dir.join("lu_extra_model_paths.yaml"))+}++/// The file to pass to ComfyUI, or `None` when there is nothing to pass.+/// Called from the ComfyUI start path, so it never creates anything.+pub fn extra_model_paths_arg() -> Option<PathBuf> {+ let base = dirs::data_dir()?;+ let file = base- .join("Locally Uncensored")++ .join(crate::app_identity::APP_DISPLAY_DIR)+ .join("lu_extra_model_paths.yaml");+ if file.is_file() {+ Some(file)+ } else {+ None+ }+}++/// Is this a path we can even ask the file system about?+///+/// A relative path would resolve against whatever the app's working directory+/// happens to be, and `~/models` is a shell convention the OS does not expand.+/// Both used to produce silence: no folders, no file, no word about it.+pub(crate) fn is_usable_root(root: &Path) -> bool {+ !root.as_os_str().is_empty() && root.is_absolute()+}++/// One syscall that answers "is the folder there and readable" before the+/// per-key stats run. On a dead network drive every stat blocks for the SMB+/// timeout, so asking twenty times what one call already answered is twenty+/// times the wait.+pub(crate) fn root_reachable(root: &Path) -> bool {+ std::fs::read_dir(root).is_ok()+}++/// What the folder is currently worth to ComfyUI.+pub(crate) fn folder_status(root: &Path) -> &'static str {+ if !is_usable_root(root) {+ "unusable"+ } else if !root_reachable(root) {+ "unreachable"+ } else {+ "ok"+ }+}++/// Write (or remove) the extra-model-paths file for the folder under Model+/// Storage. Idempotent, and safe to call on every settings change.+///+/// ASYNC + spawn_blocking, like `list_bundled_models`: a synchronous Tauri+/// command runs on the MAIN thread, and this one stats a path the user chose.+/// Point it at a network drive that went away and the whole window freezes+/// until the mount times out. Same pattern, same reason.+#[tauri::command]+pub async fn sync_custom_model_paths(dir: Option<String>) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || sync_custom_model_paths_blocking(dir.as_deref()))+ .await+ .map_err(|e| format!("sync_custom_model_paths task: {e}"))?+}++/// Reports what it did, so the Settings panel can name the folders it found,+/// or say why there were none, instead of claiming a success the user cannot+/// check.+pub(crate) fn sync_custom_model_paths_blocking(+ dir: Option<&str>,+) -> Result<serde_json::Value, String> {+ let file = extra_model_paths_file()?;+ // The Mac runs local media on MLX and never starts ComfyUI+ // (process::comfy_supported_here), so there is nobody to hand the folder+ // to. Say that instead of writing a file no process will ever open, and+ // clear one an earlier build may have left behind.+ if !crate::commands::process::comfy_supported_here() {+ let mut res = sync_custom_model_paths_to(&file, None)?;+ res["status"] = serde_json::json!("unsupported");+ return Ok(res);+ }+ sync_custom_model_paths_to(&file, dir)+}++/// The same work against a named file. The target is a parameter so the tests+/// write into a temp file of their own: the real one lives in the app data dir+/// and belongs to the installed app, not to a test run.+pub(crate) fn sync_custom_model_paths_to(+ file: &Path,+ dir: Option<&str>,+) -> Result<serde_json::Value, String> {+ let trimmed = dir.unwrap_or("").trim().to_string();+ let (status, folders, yaml) = if trimmed.is_empty() {+ ("off", Vec::new(), None)+ } else {+ let root = Path::new(&trimmed);+ match folder_status(root) {+ "ok" => {+ let found = comfy_shaped_subdirs(root);+ let names: Vec<String> = found.iter().map(|(k, _)| k.to_string()).collect();+ let yaml = build_extra_model_paths_yaml(root);+ // The names come from the same walk that produced the file, so+ // a folder that was dropped for an unquotable path can never be+ // reported as handed over.+ let names = if yaml.is_some() { names } else { Vec::new() };+ ("ok", names, yaml)+ }+ other => (other, Vec::new(), None),+ }+ };+ match &yaml {+ Some(text) => {+ std::fs::write(file, text)+ .map_err(|e| format!("Write model paths file: {}", crate::os_error::english(&e)))?;+ }+ None => {+ // A folder that stopped being ComfyUI-shaped, or that went away+ // with its drive, must not keep feeding ComfyUI the old paths.+ if file.exists() {+ std::fs::remove_file(file).map_err(|e| {+ format!("Remove model paths file: {}", crate::os_error::english(&e))+ })?;+ }+ }+ }+ Ok(serde_json::json!({+ // True only when a file is on disk for ComfyUI to read. It used to be+ // derived from the folder list, which said "written" for a folder whose+ // only mappable path had been dropped.+ "written": yaml.is_some(),+ "status": status,+ "file": file.to_string_lossy(),+ "folders": folders,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tmp(name: &str) -> PathBuf {+ let dir = std::env::temp_dir()+ .join("lu-custom-models-tests")+ .join(format!("{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn finds_comfy_shaped_folders_in_both_layouts() {+ let root = tmp("both-layouts");+ std::fs::create_dir_all(root.join("loras")).unwrap();+ std::fs::create_dir_all(root.join("models").join("checkpoints")).unwrap();+ let found = comfy_shaped_subdirs(&root);+ let keys: Vec<&str> = found.iter().map(|(k, _)| *k).collect();+ assert_eq!(keys, vec!["checkpoints", "loras"]);+ assert_eq!(found[0].1, root.join("models").join("checkpoints"));+ assert_eq!(found[1].1, root.join("loras"));+ }++ #[test]+ fn the_direct_layout_wins_over_the_nested_one() {+ // Both exist: the folder the user pointed at is the one he meant.+ let root = tmp("direct-wins");+ std::fs::create_dir_all(root.join("vae")).unwrap();+ std::fs::create_dir_all(root.join("models").join("vae")).unwrap();+ let found = comfy_shaped_subdirs(&root);+ assert_eq!(found.len(), 1);+ assert_eq!(found[0].1, root.join("vae"));+ }++ /// Negative control: a folder full of models but with no ComfyUI folder+ /// name in it produces NO file. Mapping a flat dump into every key would+ /// offer one checkpoint as a LoRA and a ControlNet at the same time.+ #[test]+ fn a_flat_folder_produces_no_config() {+ let root = tmp("flat");+ std::fs::write(root.join("juggernautXL_v9.safetensors"), b"x").unwrap();+ std::fs::create_dir_all(root.join("Text Generation")).unwrap();+ assert!(comfy_shaped_subdirs(&root).is_empty());+ assert!(build_extra_model_paths_yaml(&root).is_none());+ }++ /// The bug this file exists to avoid, held against a real YAML parser+ /// rather than against a count of quote characters.+ ///+ /// A double-quoted YAML scalar treats the backslash as an escape, so the+ /// shipped writer produced a file PyYAML refuses: `unknown escape+ /// character 'A'` for `G:\AI\...`, and a silent `D:<TAB>ext_encoders` for+ /// `D:\text_encoders`. ComfyUI reads that file without a try/except, so the+ /// Windows user this fix is for would have lost ComfyUI itself.+ #[test]+ fn a_literal_windows_path_survives_a_real_yaml_parser() {+ for raw in [+ r"G:\AI\Models",+ r"C:\Users\bob\models",+ r"D:",+ // The apostrophe is the one character a single-quoted scalar has to+ // handle, and a real folder can carry one.+ r"E:\Bob's Models",+ ] {+ let root = PathBuf::from(raw);+ // The folders are built by hand here: these paths do not exist on+ // the machine running the test, and the question is the QUOTING.+ let found = vec![+ ("loras", root.join("loras")),+ ("text_encoders", root.join("text_encoders")),+ ("vae", root.join("vae")),+ ];+ let mut yaml = String::from("lu_custom_models:\n");+ for (key, path) in &found {+ yaml.push_str(&yaml_path_line(key, path));+ }++ let parsed: serde_yaml::Value =+ serde_yaml::from_str(&yaml).unwrap_or_else(|e| panic!("{raw}: {e}\n{yaml}"));+ let block = parsed.get("lu_custom_models").expect("block missing");+ for (key, path) in &found {+ let got = block.get(*key).and_then(|v| v.as_str()).unwrap_or("");+ assert_eq!(+ got,+ path.to_string_lossy(),+ "{raw}: {key} came back mangled",+ );+ }+ }+ }++ /// Negative control for the same parser: the shipped double-quoted form is+ /// genuinely broken, so the test above is not passing by accident.+ #[test]+ fn the_old_double_quoted_form_would_have_broken_comfyui() {+ let broken = "lu_custom_models:\n loras: \"G:\\AI\\Models\\loras\"\n";+ assert!(+ serde_yaml::from_str::<serde_yaml::Value>(broken).is_err(),+ "a double-quoted Windows path must not parse: {broken}",+ );+ // And the quieter half: this one parses, into the wrong string.+ let silent = "lu_custom_models:\n text_encoders: \"D:\\text_encoders\"\n";+ let parsed: serde_yaml::Value = serde_yaml::from_str(silent).expect("parses");+ let got = parsed["lu_custom_models"]["text_encoders"].as_str().unwrap();+ assert_ne!(got, r"D:\text_encoders");+ assert!(got.contains('\t'), "the \\t escape ate the folder name: {got:?}");+ }++ #[test]+ fn the_generated_file_parses_and_names_every_folder() {+ let root = tmp("yaml");+ std::fs::create_dir_all(root.join("loras")).unwrap();+ std::fs::create_dir_all(root.join("vae")).unwrap();+ let text = build_extra_model_paths_yaml(&root).unwrap();+ assert!(text.starts_with("# Written by Locally Uncensored"));++ let parsed: serde_yaml::Value = serde_yaml::from_str(&text).expect("must parse");+ let block = &parsed["lu_custom_models"];+ assert_eq!(block["loras"].as_str().unwrap(), root.join("loras").to_string_lossy());+ assert_eq!(block["vae"].as_str().unwrap(), root.join("vae").to_string_lossy());+ }++ /// The other direction of the drift test in+ /// `src/lib/__tests__/custom-model-dir-comfy.test.ts`, which can only prove+ /// that everything LU lists is mapped. This one pins the list against+ /// ComfyUI's own `folder_paths` keys, so a typo or an invented folder name+ /// cannot ride along into a config file ComfyUI then ignores.+ #[test]+ fn every_mapped_folder_is_a_key_comfyui_actually_has() {+ // ComfyUI folder_paths keys, as its own extra_model_paths.yaml.example+ // lists them. A copy on purpose: it is the thing being checked.+ const COMFYUI_KEYS: &[&str] = &[+ "audio_encoders", "checkpoints", "clip", "clip_vision", "configs",+ "controlnet", "diffusion_models", "embeddings", "gligen", "hypernetworks",+ "loras", "photomaker", "style_models", "text_encoders", "unet",+ "upscale_models", "vae", "vae_approx",+ ];+ for key in COMFY_MODEL_FOLDERS {+ assert!(COMFYUI_KEYS.contains(key), "{key} is not a ComfyUI folder_paths key");+ }+ // Negative control: the list is sorted and free of duplicates, so a+ // second entry for the same folder cannot write two lines for it.+ let mut sorted = COMFY_MODEL_FOLDERS.to_vec();+ sorted.sort_unstable();+ sorted.dedup();+ assert_eq!(sorted.as_slice(), COMFY_MODEL_FOLDERS);+ // And a folder that is not a model folder is not in here.+ assert!(!COMFY_MODEL_FOLDERS.contains(&"custom_nodes"));+ assert!(!COMFY_MODEL_FOLDERS.contains(&"output"));+ }++ // ── The folder the user typed, before any stat ────────────────────────++ #[test]+ fn a_relative_path_or_a_tilde_is_refused_instead_of_silently_doing_nothing() {+ assert!(!is_usable_root(Path::new("models")));+ assert!(!is_usable_root(Path::new("../models")));+ assert!(!is_usable_root(Path::new("~/models")));+ assert!(!is_usable_root(Path::new("")));+ assert_eq!(folder_status(Path::new("~/models")), "unusable");+ }++ /// Negative control: a real absolute folder is usable and reachable, so the+ /// guard above cannot be refusing everything.+ #[test]+ fn a_real_absolute_folder_passes_both_guards() {+ let root = tmp("guards");+ assert!(is_usable_root(&root));+ assert!(root_reachable(&root));+ assert_eq!(folder_status(&root), "ok");+ }++ #[test]+ fn a_folder_that_is_gone_reads_as_unreachable_not_as_empty() {+ let root = tmp("vanished");+ std::fs::remove_dir_all(&root).unwrap();+ assert!(is_usable_root(&root));+ assert!(!root_reachable(&root));+ assert_eq!(folder_status(&root), "unreachable");+ }++ // ── What the Settings panel is told ───────────────────────────────────++ #[test]+ fn the_sync_reports_the_folders_it_wrote_and_says_written_only_then() {+ let root = tmp("sync-ok");+ std::fs::create_dir_all(root.join("loras")).unwrap();+ let file = tmp("sync-ok-out").join("lu_extra_model_paths.yaml");+ let res = sync_custom_model_paths_to(&file, Some(root.to_str().unwrap())).unwrap();+ assert_eq!(res["status"], "ok");+ assert_eq!(res["written"], true);+ assert_eq!(res["folders"][0], "loras");+ let on_disk = std::fs::read_to_string(&file).unwrap();+ let parsed: serde_yaml::Value = serde_yaml::from_str(&on_disk).expect("must parse");+ assert_eq!(+ parsed["lu_custom_models"]["loras"].as_str().unwrap(),+ root.join("loras").to_string_lossy(),+ );+ }++ /// Negative control, and the bug in the first cut: a folder ComfyUI cannot+ /// use wrote no file and still reported `written: true`, and the same call+ /// has to take an older file away with it.+ #[test]+ fn a_flat_folder_writes_nothing_says_so_and_clears_an_older_file() {+ let file = tmp("sync-clear-out").join("lu_extra_model_paths.yaml");+ let good = tmp("sync-clear-good");+ std::fs::create_dir_all(good.join("vae")).unwrap();+ sync_custom_model_paths_to(&file, Some(good.to_str().unwrap())).unwrap();+ assert!(file.exists(), "precondition: a file was written");++ let flat = tmp("sync-clear-flat");+ std::fs::write(flat.join("sdxl.safetensors"), b"x").unwrap();+ let res = sync_custom_model_paths_to(&file, Some(flat.to_str().unwrap())).unwrap();+ assert_eq!(res["status"], "ok", "the folder itself is readable");+ assert_eq!(res["written"], false);+ assert_eq!(res["folders"].as_array().unwrap().len(), 0);+ assert!(!file.exists(), "the old file must not keep feeding ComfyUI");+ }++ #[test]+ fn an_unreachable_or_relative_folder_is_named_as_such_and_writes_nothing() {+ let gone = tmp("sync-gone");+ std::fs::remove_dir_all(&gone).unwrap();+ let file = tmp("sync-bad-out").join("lu_extra_model_paths.yaml");+ let res = sync_custom_model_paths_to(&file, Some(gone.to_str().unwrap())).unwrap();+ assert_eq!(res["status"], "unreachable");+ assert_eq!(res["written"], false);++ let res = sync_custom_model_paths_to(&file, Some("~/models")).unwrap();+ assert_eq!(res["status"], "unusable");+ assert_eq!(res["written"], false);++ // Negative control: no folder at all is not a fault, it is "off".+ let res = sync_custom_model_paths_to(&file, Some(" ")).unwrap();+ assert_eq!(res["status"], "off");+ assert_eq!(res["written"], false);+ }++ /// Negative control: a missing folder is not an error and not a config.+ #[test]+ fn a_folder_that_is_not_there_yields_nothing() {+ let root = std::env::temp_dir()+ .join("lu-custom-models-tests")+ .join(format!("nope-not-here-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ assert!(comfy_shaped_subdirs(&root).is_empty());+ assert!(build_extra_model_paths_yaml(&root).is_none());+ }+}diff --cc src-tauri/src/commands/download.rsindex 7cd5979f,148c049e..db55909b--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@@ -42,180 -43,6 +43,191 @@@ fn safe_subfolder(subfolder: &str) -> ROk(())}+#[cfg(test)]+mod delete_message_tests {+ use super::not_ours_to_delete;++ fn scratch(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir()+ .join("lu-delete-msg")+ .join(format!("{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ /// The button used to end in a flat "was not found" for a LoRA that lives+ /// in the user's own folder, which reads like a bug. LU still does not+ /// delete it: the folder is his.+ #[test]+ fn a_file_in_the_users_own_folder_is_named_as_such() {+ let root = scratch("own-folder");+ std::fs::create_dir_all(root.join("loras")).unwrap();+ std::fs::write(root.join("loras").join("pixelart.safetensors"), b"x").unwrap();++ let msg = not_ours_to_delete(+ "pixelart.safetensors",+ "pixelart.safetensors",+ &[root.to_string_lossy().to_string()],+ );+ assert!(msg.contains("your own model folder"), "{msg}");+ assert!(msg.contains(&root.join("loras").display().to_string()), "{msg}");+ assert!(msg.contains("Remove the file there"), "{msg}");++ std::fs::remove_dir_all(&root).ok();+ }++ /// Negative control: a name that is in no folder at all keeps the short+ /// answer. Blaming the custom folder for every miss would be its own lie.+ #[test]+ fn a_file_that_is_nowhere_keeps_the_short_answer() {+ let root = scratch("own-folder-empty");+ std::fs::create_dir_all(root.join("loras")).unwrap();++ let msg = not_ours_to_delete(+ "ghost.safetensors",+ "ghost.safetensors",+ &[root.to_string_lossy().to_string()],+ );+ assert_eq!(msg, "ghost.safetensors was not found in the ComfyUI models folders");++ // And with no custom folder set at all.+ let msg = not_ours_to_delete("ghost.safetensors", "ghost.safetensors", &[]);+ assert_eq!(msg, "ghost.safetensors was not found in the ComfyUI models folders");+ let msg = not_ours_to_delete("ghost.safetensors", "ghost.safetensors", &[" ".to_string()]);+ assert_eq!(msg, "ghost.safetensors was not found in the ComfyUI models folders");++ std::fs::remove_dir_all(&root).ok();+ }+}++#[cfg(test)]+mod civitai_auth_tests {- use super::{download_http_error, is_civitai_host};++ use super::{download_http_error, http_error_message, is_civitai_host};++ #[test]+ fn the_key_goes_to_civitai_and_its_mirror_and_nowhere_else() {+ assert!(is_civitai_host("https://civitai.com/api/download/models/12345"));+ assert!(is_civitai_host("https://CIVITAI.COM/api/download/models/1"));+ // GH #53: the mirror LU offers where .com is blocked.+ assert!(is_civitai_host("https://civitai.red/api/download/models/1"));+ assert!(is_civitai_host("https://api.civitai.com/v1/x"));+ }++ /// Negative control, and the reason the check is on the HOST: a URL that+ /// merely mentions civitai must never collect the user's API key.+ #[test]+ fn a_url_that_only_mentions_civitai_gets_no_key() {+ assert!(!is_civitai_host("https://evil.test/?x=civitai.com"));+ assert!(!is_civitai_host("https://civitai.com.evil.test/file"));+ assert!(!is_civitai_host("https://notcivitai.com/file"));+ assert!(!is_civitai_host("https://huggingface.co/repo/resolve/main/m.safetensors"));+ // A userinfo prefix is not a host either.+ assert!(!is_civitai_host("https://[email protected]/file"));+ assert!(!is_civitai_host("not a url"));+ }++ /// The backslash forms the hand written parser got wrong.+ ///+ /// In a special scheme the backslash ends the authority. The old check+ /// split the string by hand and disagreed with the transport in BOTH+ /// directions: `https://evil.test\.civitai.com/x` goes to `evil.test` and+ /// was called CivitAI, so the Bearer token would have ridden along, and+ /// `https://civitai.com\@evil.test/x` goes to `civitai.com` and was called+ /// something else. The frontend gates on `new URL()` too, so the app could+ /// not produce the first one, but a second gate that disagrees with the+ /// transport is not a gate.+ ///+ /// The property is the agreement itself: the check answers what the+ /// request will actually do, because it asks the same parser.+ #[test]+ fn the_check_agrees_with_the_host_the_request_will_reach() {+ for u in [+ "https://evil.test\\.civitai.com/x",+ "https://civitai.com\\@evil.test/x",+ "https://civitai.com\\.evil.test/x",+ "https://civitai.com/api/download/models/1",+ "https://evil.test/?x=civitai.com",+ ] {+ let host = url::Url::parse(u).unwrap().host_str().unwrap().to_ascii_lowercase();+ let reaches_civitai = host == "civitai.com"+ || host == "civitai.red"+ || host.ends_with(".civitai.com")+ || host.ends_with(".civitai.red");+ assert_eq!(+ is_civitai_host(u),+ reaches_civitai,+ "{u} really goes to {host}",+ );+ }+ }++ /// Negative control for the one that matters: the smuggling form must be+ /// refused, not merely "agree".+ #[test]+ fn a_backslash_cannot_send_the_key_to_another_host() {+ assert!(!is_civitai_host("https://evil.test\\.civitai.com/x"));+ assert_eq!(+ url::Url::parse("https://evil.test\\.civitai.com/x")+ .unwrap()+ .host_str()+ .unwrap(),+ "evil.test",+ "precondition: this URL really does reach evil.test",+ );+ }++ #[test]+ fn a_refused_civitai_download_names_the_field_instead_of_a_bare_number() {+ // goonerforporn, 2026-08-28: the download died on a bare HTTP 400 and+ // the field it was asking for was not in the interface at all.+ for status in [400u16, 401, 403] {- let msg = download_http_error("https://civitai.com/api/download/models/1", status, false);++ let msg = download_http_error(++ "https://civitai.com/api/download/models/1",++ status,++ false,++ "pony.safetensors",++ );+ assert!(msg.contains(&format!("HTTP {status}")), "{msg}");+ assert!(msg.contains("API key"), "{msg}");+ assert!(msg.contains("Settings > AI Backends > Model Storage"), "{msg}");++ // A key the user can go and add is not a dead address: the++ // `(HTTP nnn)` shape would hide the Retry button he needs.++ assert!(!msg.contains(&format!("(HTTP {status})")), "{msg}");+ }+ }++ #[test]+ fn a_key_that_was_sent_and_refused_says_so() {- let msg = download_http_error("https://civitai.com/api/download/models/1", 401, true);++ let msg = download_http_error(++ "https://civitai.com/api/download/models/1",++ 401,++ true,++ "pony.safetensors",++ );+ assert!(msg.contains("was sent and rejected"), "{msg}");+ // and does NOT tell the user to add a key he already has.+ assert!(!msg.contains("Add one under"), "{msg}");+ }+- /// Negative control: every other host and every other status keeps the- /// short form. A dead HuggingFace link must not send people to the CivitAI- /// setting.++ /// Negative control: every other host and every other status is answered++ /// by `http_error_message` word for word. A dead HuggingFace link must not++ /// send people to the CivitAI setting.+ #[test]- fn other_hosts_and_other_statuses_keep_the_short_form() {- assert_eq!(- download_http_error("https://huggingface.co/repo/resolve/main/m.gguf", 401, false),- "HTTP 401",- );- assert_eq!(- download_http_error("https://civitai.com/api/download/models/1", 404, false),- "HTTP 404",- );- assert_eq!(- download_http_error("https://civitai.com/api/download/models/1", 500, true),- "HTTP 500",- );++ fn other_hosts_and_other_statuses_get_no_civitai_hint() {++ for (url, status, sent) in [++ ("https://huggingface.co/repo/resolve/main/m.gguf", 401u16, false),++ ("https://civitai.com/api/download/models/1", 404, false),++ ("https://civitai.com/api/download/models/1", 500, true),++ ] {++ let msg = download_http_error(url, status, sent, "m.gguf");++ assert_eq!(msg, http_error_message(status, "m.gguf"), "{msg}");++ assert!(!msg.contains("API key"), "{msg}");++ assert!(!msg.contains("Model Storage"), "{msg}");++ }+ }+}+#[cfg(test)]mod download_security_tests {use super::{checked_model_path, safe_subfolder, sanitize_filename};@@@ -424,10 -210,7 +436,11 @@@ pub async fn download_modelsubfolder: String,filename: String,expectedBytes: Option<u64>,+ expectedSha256: Option<String>,+ // The CivitAI API key, when the caller has one. Sent as a Bearer header+ // and ONLY to a CivitAI host (see do_download). Absent for every other+ // catalog, which is every other download in the app.+ authToken: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {let expected_bytes = expectedBytes;@@@ -508,7 -300,8 +531,8 @@@let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, auth_token.as_deref()).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset,- CatalogClaims { expected_bytes, expected_sha256 }).await {++ CatalogClaims { expected_bytes, expected_sha256, auth_token }).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@@ -662,51 -567,98 +798,155 @@@ fn gib(bytes: u64) -> Stringformat!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))}+/// Is this a CivitAI download URL?+///+/// `civitai.red` is the mirror LU offers for regions where `.com` is blocked+/// (GH #53), so both count. Parsed with the same URL parser the request itself+/// goes through, never picked apart by hand: a hand written host split does not+/// know that a backslash ends the host in a special scheme, so+/// `https://evil.test\.civitai.com/x` read as a CivitAI host here while reqwest+/// sent the Bearer token to `evil.test`. Same rule for+/// `https://civitai.com\@evil.test`.+pub(crate) fn is_civitai_host(url: &str) -> bool {+ let host = match url::Url::parse(url) {+ Ok(u) => u.host_str().unwrap_or("").to_ascii_lowercase(),+ Err(_) => return false,+ };+ host == "civitai.com"+ || host == "civitai.red"+ || host.ends_with(".civitai.com")+ || host.ends_with(".civitai.red")+}++/// What the user reads when a download comes back refused.+///+/// goonerforporn, Discord #bug-reports 2026-08-28: CivitAI downloads ended in a+/// bare `HTTP 400` with nothing to act on, because the API key field had gone+/// missing from the interface and nobody could tell that a key was the point.- /// A refusal from CivitAI now names the field and the way to it. Every other- /// host and every other status keeps the short form: inventing a CivitAI hint- /// for a dead HuggingFace link would send people to the wrong setting.- pub(crate) fn download_http_error(url: &str, status: u16, sent_token: bool) -> String {++/// A refusal from CivitAI names the field and the way to it. Everything else++/// goes to `http_error_message`: inventing a CivitAI hint for a dead++/// HuggingFace link would send people to the wrong setting.++///++/// The CivitAI text carries its status WITHOUT the `(HTTP nnn)` brackets on++/// purpose. That shape is the contract `isPermanentDownloadError` reads in++/// src/api/discover.ts to replace Retry with "Unavailable", and a missing API++/// key is the one refusal the user can go and fix, so the button has to stay.++pub(crate) fn download_http_error(url: &str, status: u16, sent_token: bool, filename: &str) -> String {+ let refused = matches!(status, 400 | 401 | 403);+ if is_civitai_host(url) && refused {+ return if sent_token {+ format!(- "CivitAI refused this download (HTTP {status}). Your CivitAI API key was sent and rejected. \++ "CivitAI refused this download with HTTP {status}. Your CivitAI API key was sent and rejected. \+ Check it under Settings > AI Backends > Model Storage, and check that your CivitAI account \+ is allowed to download this model."+ )+ } else {+ format!(- "CivitAI refused this download (HTTP {status}). Most CivitAI downloads need an API key. \++ "CivitAI refused this download with HTTP {status}. Most CivitAI downloads need an API key. \+ Add one under Settings > AI Backends > Model Storage, then start this download again."+ )+ };+ }- format!("HTTP {status}")++ http_error_message(status, filename)++}+++ /// One reqwest client, built the same way for every request this module makes.+ ///+ /// The SSRF guard is not optional and not a per-call decision: model downloads+ /// come from public catalogs, and a crafted catalog or model URL must not be+ /// able to reach an internal service or 169.254.169.254 — on the first hop or+ /// on any redirect.+ fn download_client(connect_secs: u64, read_secs: u64) -> Result<reqwest::Client, String> {+ reqwest::Client::builder()+ .user_agent("LocallyUncensored/1.5")+ .redirect(crate::commands::proxy::ssrf_safe_redirect_policy(10))+ .connect_timeout(std::time::Duration::from_secs(connect_secs))+ .read_timeout(std::time::Duration::from_secs(read_secs))+ .build()+ .map_err(|e| os_error::english(&e))+ }++ /// The exact byte count the SERVER states for `url`, or None when it will not+ /// state one (offline, HEAD refused, chunked transfer, a probe that errors).+ ///+ /// This is the only trustworthy size in the whole download path. The catalog's+ /// `sizeGB` is a rounded human number — "9.2" for a file of 9 874 331 648 bytes+ /// — so it can size a progress bar or refuse a full drive, but it can never+ /// certify that a file on disk is the whole file.+ /// Short timeouts, because this runs INSIDE the install click. A machine with+ /// no network must cost the user a moment, not half a minute — the answer for+ /// an unreachable host is "cannot tell", and arriving at it slowly helps+ /// nobody.+ async fn exact_remote_size(url: &str) -> Option<u64> {+ crate::commands::proxy::validate_public_url(url).ok()?;+ let client = download_client(8, 15).ok()?;++ // A transport error means offline or a black-holed host. Retrying the same+ // unreachable address with a second request only doubles the wait.+ let head = client.head(url).send().await.ok()?;+ if head.status().is_success() {+ if let Some(n) = head.content_length() {+ if n > 0 {+ return Some(n);+ }+ }+ }++ // The host answered, just not usefully: some CDNs reply 405 to HEAD, or drop+ // the length from it. A one byte ranged GET costs one more round trip and+ // carries the whole size in Content-Range.+ let r = client.get(url).header("Range", "bytes=0-0").send().await.ok()?;+ let v = r.headers().get(reqwest::header::CONTENT_RANGE)?.to_str().ok()?;+ total_from_content_range(v)+ }++ /// SHA256 of the first `len` bytes of `path`.+ ///+ /// Only needed when a transfer RESUMES with a digest to check: the bytes+ /// already on disk never passed through the hasher, so without replaying them+ /// the final digest would be the hash of the tail alone and every resumed+ /// download would look corrupt. Reading a large partial back costs seconds;+ /// throwing the partial away costs hours.+ async fn digest_of_prefix(path: &Path, len: u64) -> Result<Sha256, String> {+ use tokio::io::AsyncReadExt;+ let mut f = tokio::fs::File::open(path)+ .await+ .map_err(|e| format!("Open partial file for hashing: {}", os_error::english(&e)))?;+ let mut hasher = Sha256::new();+ let mut buf = vec![0u8; 1 << 20];+ let mut done: u64 = 0;+ while done < len {+ let want = std::cmp::min(buf.len() as u64, len - done) as usize;+ let n = f+ .read(&mut buf[..want])+ .await+ .map_err(|e| format!("Read partial file for hashing: {}", os_error::english(&e)))?;+ if n == 0 {+ break;+ }+ hasher.update(&buf[..n]);+ done += n as u64;+ }+ Ok(hasher)+ }+-/// What the catalog entry claims about the file, as opposed to what the server-/// says on the wire. The two travel together everywhere and are the only-/// arguments `do_download` takes that are not about the transfer itself, so-/// they ride as one — which also puts the argument count back under-/// `clippy::too_many_arguments`'s threshold without an `allow`.++/// What the caller knows about a file and where it comes from, as opposed to++/// what the server says on the wire. These travel together everywhere and are++/// the only arguments `do_download` takes that are not about the transfer++/// itself, so they ride as one. That also keeps the argument count under++/// `clippy::too_many_arguments`'s threshold without an `allow`, which the++/// CivitAI key would otherwise have pushed it over.+ struct CatalogClaims {+ /// Catalog estimate. Plans the space guard when the server states no length;+ /// never decides that a transfer is finished.+ expected_bytes: Option<u64>,+ /// Digest from the catalog entry, already normalised. `None` means the+ /// content of this file cannot be verified at all.+ expected_sha256: Option<String>,++ /// The user's CivitAI API key, when there is one. Goes out as a Bearer++ /// header and ONLY to a CivitAI host; every other catalog in the app++ /// downloads without one.++ auth_token: Option<String>,}async fn do_download(@@@ -716,8 -668,9 +956,9 @@@id: &str,token: CancellationToken,resume_offset: u64,- auth_token: Option<&str>,+ claims: CatalogClaims,) -> Result<(), String> {- let CatalogClaims { expected_bytes, expected_sha256 } = claims;++ let CatalogClaims { expected_bytes, expected_sha256, auth_token } = claims;// SSRF guard: model downloads come from public catalogs (HuggingFace,// civitai, ollama). Block private/loopback/metadata hosts and re-validate// every redirect hop so a crafted catalog/model URL can't pull from an@@@ -743,19 -690,6 +978,21 @@@let mut request = client.get(url);+ // The CivitAI API key, as a Bearer header rather than a `?token=` query+ // parameter: a key in the URL is written into the download meta the app+ // persists, printed in the log line above and kept in the browser history+ // of the web build. Only for a CivitAI host, so an HF or catalog URL never+ // carries it. reqwest strips Authorization itself when a redirect leaves+ // the host, which is exactly right: CivitAI hands the file to a signed CDN+ // URL that must not see the key.+ let civitai = is_civitai_host(url);- let sent_token = auth_token.filter(|t| !t.trim().is_empty() && civitai);++ // as_deref, damit der Griff kopierbar bleibt: weiter unten fragt die++ // Fehlermeldung noch einmal, ob ein Schluessel mitgegangen ist.++ let sent_token = auth_token.as_deref().filter(|t| !t.trim().is_empty() && civitai);+ if let Some(t) = sent_token {+ request = request.bearer_auth(t.trim());+ }+// Resume support: request only remaining bytesif resume_offset > 0 {request = request.header("Range", format!("bytes={}-", resume_offset));@@@ -769,7 -703,11 +1006,11 @@@let status = response.status();if !status.is_success() && status.as_u16() != 206 {- return Err(download_http_error(url, status.as_u16(), sent_token.is_some()));+ let name = dest+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_else(|| "this file".to_string());- return Err(http_error_message(status.as_u16(), &name));++ return Err(download_http_error(url, status.as_u16(), sent_token.is_some(), &name));}let already_on_disk = resumed_bytes(resume_offset, status.as_u16());@@@ -993,10 -1281,15 +1584,17 @@@ pub async fn resume_downloadid: String,url: String,subfolder: String,+ expectedBytes: Option<u64>,+ expectedSha256: Option<String>,+ authToken: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {+ let expected_bytes = expectedBytes;+ let expected_sha256 = match expectedSha256.as_deref() {+ Some(s) => Some(normalize_sha256(s)?),+ None => None,+ };+ let auth_token = authToken;let comfy_path = {let p = state.comfy_path.lock().unwrap();p.clone()@@@ -1042,7 -1335,8 +1640,8 @@@let id_clone = id.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, auth_token.as_deref()).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset,- CatalogClaims { expected_bytes, expected_sha256 }).await {++ CatalogClaims { expected_bytes, expected_sha256, auth_token }).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@@ -1203,63 -1497,6 +1802,62 @@@ pub fn detect_model_path(provider: Stri}}+/// Where LM Studio keeps its models, and whether LM Studio is on this machine+/// at all. Reads only: nothing is created.+///+/// `detect_model_path` cannot answer this. It is a DOWNLOAD TARGET, so for+/// Ollama and LM Studio it creates the folder when it is missing, which is+/// right for a download and wrong for a panel whose whole job is to say+/// "LM Studio is not installed". Asking it here would create+/// `~/.lmstudio/models` on a machine that has never seen LM Studio and then+/// report that folder as evidence of an install.+///+/// Installed is answered from the folder first because that is free on every- /// platform, and only then from `os_paths::lmstudio_installed()`, which knows- /// the `lms` CLI and the app bundle. A user who has LM Studio but has not- /// downloaded a model yet is therefore still recognised.++/// platform, and only then from `install::lmstudio_lms_path()`, which knows the++/// `lms` CLI on every layout. A user who has LM Studio but has not downloaded a++/// model yet is therefore still recognised.+///+/// ASYNC + spawn_blocking, the same shape as `list_bundled_models`: a+/// SYNCHRONOUS Tauri command runs on the MAIN thread, and neither half of this+/// one is cheap enough for that. `lmstudio_dir_in` touches the disk, and- /// `lmstudio_installed()` reaches `spotlight_app()`, which spawns `mdfind` and- /// waits for it. Settings opens this on mount, so on a Mac with a busy- /// Spotlight index that was the window freezing while a panel drew one line- /// of grey text. That is the same mistake the Mac ComfyUI search made in- /// 2.6.8, one door further along.++/// `lmstudio_lms_path()` walks several fixed paths and falls back to a `which`++/// lookup, which spawns a process. Settings opens this on mount, so that was++/// the window freezing while a panel drew one line of grey text. That is the++/// same mistake the Mac ComfyUI search made in 2.6.8, one door further along.+#[tauri::command]+pub async fn lmstudio_model_dir() -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(lmstudio_model_dir_blocking)+ .await+ .map_err(|e| format!("lmstudio_model_dir task: {e}"))?+}++fn lmstudio_model_dir_blocking() -> Result<serde_json::Value, String> {+ let home = dirs::home_dir().ok_or("Cannot find home directory")?;+ let found = lmstudio_dir_in(&home);- let installed = found.is_some() || crate::os_paths::lmstudio_installed();++ let installed = found.is_some() || crate::commands::install::lmstudio_lms_path().is_some();+ Ok(serde_json::json!({+ "installed": installed,+ "path": found.map(|p| p.to_string_lossy().to_string()),+ }))+}++/// The LM Studio models folder under a given home, or None. Creates nothing.+///+/// Split out from the command so the "creates nothing" half can be proven+/// against a throwaway home directory instead of the tester's own.+///+/// Same two candidates and the same order as detect_model_path: LM Studio+/// 0.3.x writes ~/.lmstudio/models on all three platforms, 0.2.x used+/// ~/.cache/lm-studio/models.+pub fn lmstudio_dir_in(home: &Path) -> Option<PathBuf> {+ [+ home.join(".lmstudio").join("models"),+ home.join(".cache").join("lm-studio").join("models"),+ ]+ .into_iter()+ .find(|p| p.is_dir())+}+#[allow(non_snake_case)]#[tauri::command]pub async fn download_model_to_path(@@@ -1322,9 -1575,8 +1936,10 @@@let filename_clone = filename.clone();tokio::spawn(async move {+ // No auth token here: download_model_to_path serves the text-model+ // lane (HuggingFace GGUFs into the app models dir), never CivitAI.- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, None).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset,- CatalogClaims { expected_bytes, expected_sha256 }).await {++ CatalogClaims { expected_bytes, expected_sha256, auth_token: None }).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {diff --cc src-tauri/src/commands/engine.rsindex 83f4d76d,621c3165..ba9456cd--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@@ -326,159 -321,43 +326,155 @@@ pub(crate) fn split_shard_stem(stem: &s/// "models" that can never load. A set with missing parts is not listed at/// all, so a paused or aborted multi-part download never impersonates an/// installed model (same rule a9ea114 established for MLX downloads).-/// Accumulator for multi-part GGUF sets: `(dir, base, total)` →-/// `(part numbers seen, path of part 1, byte sum)`.+// Only the tests call this since the listing went multi-root, and they are the+// reason to keep it: every scan rule that predates GH #122 is pinned through+// this one-root door, so a change to the walk still has to survive them.+#[allow(dead_code)]+pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {+ scan_gguf_roots(&[ScanRoot { dir, max_depth: MAX_SCAN_DEPTH }]).models+}++/// One folder the GGUF scan walks, and how deep it may go there.+pub(crate) struct ScanRoot<'a> {+ pub dir: &'a Path,+ pub max_depth: usize,+}++/// How one root fared. The Model Storage panel reads this, because "no models"+/// and "I could not finish looking" are different answers and the user is the+/// only one who can act on the difference.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum RootStatus {+ /// Walked to the end, within the budget.+ Ok,+ /// The deadline or the entry budget ran out. What was found is real, the+ /// list is not complete.+ Truncated,+ /// `read_dir` on the root itself failed: gone, unplugged, unreadable.+ Unreachable,+ /// Not a path the OS can resolve on its own: relative, or a shell `~`.+ Unusable,+}++impl RootStatus {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ RootStatus::Ok => "ok",+ RootStatus::Truncated => "truncated",+ RootStatus::Unreachable => "unreachable",+ RootStatus::Unusable => "unusable",+ }+ }+}++/// What a scan of several roots produced, and how each root fared.+pub(crate) struct ScanOutcome {+ pub models: Vec<BundledModel>,+ /// One entry per root, in the order the roots were given.+ pub statuses: Vec<RootStatus>,+}++/// Wall-clock ceiling for ONE root.///-/// The directory is part of the key: two unrelated split sets that share a base-/// name in different subfolders must never merge into one entry. Named because-/// the bare type is what `clippy::type_complexity` fires on, and a name says-/// what the tuples mean better than the tuples do.-type GgufSplitSets =- std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>;+/// The walk has no idea what it was pointed at. Four levels below `C:\` or a+/// home directory is tens of thousands of `read_dir` calls, and `fetchModels`+/// awaits this: the Models tab, every picker and onboarding sit and wait for it.+/// A partial answer within a few seconds beats a complete one nobody stayed for,+/// and the panel says the answer is partial.+const SCAN_DEADLINE: Duration = Duration::from_secs(5);++/// Directory entries one root may look at. A second ceiling because a fast+/// local SSD can burn a very long list well inside the deadline, and because a+/// symlink loop is bounded by this and not by the clock.+const SCAN_ENTRY_BUDGET: usize = 20_000;++/// The ceilings for one root, carried down the walk.+struct ScanBudget {+ deadline: Instant,+ entries_left: usize,+ truncated: bool,+}-pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {- let mut out = Vec::new();- let mut sets: GgufSplitSets = GgufSplitSets::new();- scan_gguf_dir(dir, 0, &mut out, &mut sets);- for ((_dir, base, total), (mut parts, first_path, size)) in sets {- parts.sort_unstable();- parts.dedup();- let complete = parts.len() as u32 == total && parts.first() == Some(&1);- if let (true, Some(path)) = (complete, first_path) {- out.push(BundledModel {- name: base,- path,- size,- });+impl ScanBudget {+ fn new() -> Self {+ Self {+ deadline: Instant::now() + SCAN_DEADLINE,+ entries_left: SCAN_ENTRY_BUDGET,+ truncated: false,}}- // A name is the picker id, so it has to be unique. The shallowest copy- // wins (the flat app dir is the canonical place); ties fall to the path.- out.sort_by(|a, b| {++ /// True while there is room for one more entry. Flips `truncated` the first+ /// time there is not, so the caller can say so instead of reporting a short+ /// list as the whole truth.+ fn take(&mut self) -> bool {+ if self.entries_left == 0 || Instant::now() >= self.deadline {+ self.truncated = true;+ return false;+ }+ self.entries_left -= 1;+ true+ }+}++/// The same scan over SEVERAL folders, in priority order.+///+/// GH #122 (zrmdsxa, 2026-08-28): the folder the user names under Model+/// Storage was a download target and nothing else. A GGUF that was already+/// sitting in `G:\AI\Models`, or one an earlier LU download had put there,+/// was never looked at, so the Models tab stayed empty and the file could not+/// be loaded at all. The app models dir is root 0 and still wins every name+/// collision, so adding a custom folder can never displace what the app+/// installed itself.+pub(crate) fn scan_gguf_roots(roots: &[ScanRoot]) -> ScanOutcome {+ // (root index, model). The index is the first tie-break below, so an+ // earlier root always wins a duplicate name.+ let mut ranked: Vec<(usize, BundledModel)> = Vec::new();+ let mut statuses: Vec<RootStatus> = Vec::with_capacity(roots.len());+ for (rank, root) in roots.iter().enumerate() {+ if !crate::commands::custom_models::is_usable_root(root.dir) {+ statuses.push(RootStatus::Unusable);+ continue;+ }+ // One call answers "is it there and readable" before the walk, so a+ // dead mount costs one timeout instead of one per directory.+ if std::fs::read_dir(root.dir).is_err() {+ statuses.push(RootStatus::Unreachable);+ continue;+ }+ let mut out = Vec::new();- // (dir, base, total) → (part-numbers seen, path of part 1, byte sum).- // The directory is part of the key: two unrelated split sets that share- // a base name in different subfolders must never merge into one entry.- let mut sets: std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)> =- std::collections::HashMap::new();++ let mut sets = GgufSplitSets::new();+ let mut budget = ScanBudget::new();+ scan_gguf_dir(root.dir, 0, root.max_depth, &mut budget, &mut out, &mut sets);+ for ((_dir, base, total), (mut parts, first_path, size)) in sets {+ parts.sort_unstable();+ parts.dedup();+ let complete = parts.len() as u32 == total && parts.first() == Some(&1);+ if let (true, Some(path)) = (complete, first_path) {+ out.push(BundledModel {+ name: base,+ path,+ size,+ });+ }+ }+ statuses.push(if budget.truncated { RootStatus::Truncated } else { RootStatus::Ok });+ ranked.extend(out.into_iter().map(|m| (rank, m)));+ }+ // A name is the picker id, so it has to be unique. The earlier root wins,+ // then the shallowest copy (the flat app dir is the canonical place);+ // ties fall to the path.+ ranked.sort_by(|a, b| {let depth = |p: &str| p.matches(['/', '\\']).count();- a.name- .cmp(&b.name)- .then(depth(&a.path).cmp(&depth(&b.path)))- .then(a.path.cmp(&b.path))+ a.1.name+ .cmp(&b.1.name)+ .then(a.0.cmp(&b.0))+ .then(depth(&a.1.path).cmp(&depth(&b.1.path)))+ .then(a.1.path.cmp(&b.1.path))});- out.dedup_by(|a, b| a.name == b.name);- out+ let mut models: Vec<BundledModel> = ranked.into_iter().map(|(_, m)| m).collect();+ models.dedup_by(|a, b| a.name == b.name);+ ScanOutcome { models, statuses }}/// How far below the app models dir the scan walks. 0 alone was the shipped@@@ -491,21 -370,13 +487,31 @@@/// levels reach them, so those installs heal on the next model refresh instead/// of asking the user to download everything a second time. Deeper than that/// buys nothing and only costs directory reads.-const MAX_SCAN_DEPTH: usize = 2;+pub(crate) const MAX_SCAN_DEPTH: usize = 2;++/// How far the scan walks below a folder the USER named under Model Storage.+/// Deeper than the app dir on purpose: a grown model library is filed by hand+/// (`G:\AI\Models\Text Generation\<author>\<repo>\file.gguf` in GH #122's+/// screenshots), and two levels stop one folder short of exactly that.+pub(crate) const MAX_CUSTOM_SCAN_DEPTH: usize = 4;+++/// Accumulator for multi-part GGUF sets: `(dir, base, total)` maps to++/// `(part numbers seen, path of part 1, byte sum)`.++///++/// The directory is part of the key: two unrelated split sets that share a base++/// name in different subfolders must never merge into one entry. Named because++/// the bare type is what `clippy::type_complexity` fires on, and a name says++/// what the tuples mean better than the tuples do.++type GgufSplitSets =++ std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>;+fn scan_gguf_dir(dir: &Path,depth: usize,+ max_depth: usize,+ budget: &mut ScanBudget,out: &mut Vec<BundledModel>,- sets: &mut std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>,+ sets: &mut GgufSplitSets,) {let entries = match std::fs::read_dir(dir) {Ok(e) => e,@@@ -589,10 -446,10 +595,10 @@@/// download / scan just works on a fresh box. This is the same path/// `detect_model_path("builtin")` returns.pub fn builtin_models_dir() -> Result<PathBuf, String> {- let base = dirs::data_dir().ok_or("Cannot resolve app data directory")?;- let dir = base.join("Locally Uncensored").join("models");+ dirs::data_dir().ok_or("Cannot resolve app data directory")?;+ let dir = crate::os_paths::builtin_models_dir();std::fs::create_dir_all(&dir)- .map_err(|e| format!("Create built-in models dir: {}", os_error::english(&e)))?;+ .map_err(|e| format!("Create LU Engine models folder: {}", os_error::english(&e)))?;Ok(dir)}@@@ -3056,406 -2102,7 +3080,405 @@@ mod testsassert!(began.elapsed() < Duration::from_secs(5));}+ // ── A15, the two engine findings of the Windows Nachlauf ───────────────++ /// One engine handle around an arbitrary child, for the reaping tests.+ fn engine_around(child: std::process::Child, port: u16) -> Option<BundledEngine> {+ Some(BundledEngine {+ child,+ model_path: "/tmp/does-not-matter.gguf".into(),+ port,+ ctx: Some(8192),+ args: Vec::new(),+ })+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn an_engine_killed_from_outside_stops_counting_as_running() {+ // The box: `Stop-Process` on lu-llama-server, and the line kept saying+ // "Engine running / Port: 8127" for as long as anyone watched.+ let mut child = std::process::Command::new("sh")+ .args(["-c", "exit 0"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a child that exits immediately");+ // Let it actually die before asking, otherwise the test races the OS.+ let _ = child.wait();+ let mut slot = engine_around(child, DEFAULT_ENGINE_PORT);++ assert!(reap_dead_engine(&mut slot), "a dead process was not noticed");+ assert!(slot.is_none(), "the handle survived its process");+ // And a second look is quiet: nothing left to reap, nothing to log.+ assert!(!reap_dead_engine(&mut slot));+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn a_living_engine_is_left_exactly_where_it_is() {+ // Negative control. Without it the test above would pass on a function+ // that simply cleared the slot every time.+ let child = std::process::Command::new("sh")+ .args(["-c", "sleep 30"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a long lived child");+ let mut slot = engine_around(child, DEFAULT_ENGINE_PORT);++ assert!(!reap_dead_engine(&mut slot), "a live engine was declared dead");+ assert!(slot.is_some());+ assert_eq!(slot.as_ref().unwrap().port, DEFAULT_ENGINE_PORT);++ let mut engine = slot.take().unwrap();+ let _ = engine.child.kill();+ let _ = engine.child.wait();+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn a_status_read_reports_nothing_for_a_sidecar_whose_process_is_gone() {+ // The embeddings server had no reaping at all, so a killed sidecar kept+ // answering "running" on 8128 the way the chat engine used to on 8127.+ // Both status commands go through live_sidecar now, so this covers the+ // pair (A15 review).+ let mut child = std::process::Command::new("sh")+ .args(["-c", "exit 0"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a child that exits immediately");+ let _ = child.wait();+ let mut slot = engine_around(child, DEFAULT_EMBED_PORT);++ assert_eq!(live_sidecar(&mut slot), None, "a dead sidecar was reported as running");+ assert!(slot.is_none(), "the handle survived its process");+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn a_status_read_reports_a_sidecar_that_is_really_there() {+ // Negative control for the test above: live_sidecar must not simply+ // answer None.+ let child = std::process::Command::new("sh")+ .args(["-c", "sleep 30"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a long lived child");+ let mut slot = engine_around(child, DEFAULT_EMBED_PORT);++ let seen = live_sidecar(&mut slot);+ assert_eq!(seen.as_ref().map(|(p, _, _)| *p), Some(DEFAULT_EMBED_PORT));+ assert!(slot.is_some());++ let mut engine = slot.take().unwrap();+ let _ = engine.child.kill();+ let _ = engine.child.wait();+ }++ // ── A16: the watch that says a sidecar died without being asked ─────────++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn the_watch_names_the_port_of_a_sidecar_that_died() {+ // What the loop does once per tick. The port has to come out of the+ // slot before the reap clears it, which is the whole reason this is a+ // function and not two lines inside the thread.+ let mut child = std::process::Command::new("sh")+ .args(["-c", "exit 0"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a child that exits immediately");+ let _ = child.wait();+ let mut slot = engine_around(child, DEFAULT_ENGINE_PORT);++ assert_eq!(+ reaped_sidecar_port(&mut slot),+ Some(DEFAULT_ENGINE_PORT),+ "the watch could not say which sidecar had gone",+ );+ assert!(slot.is_none(), "the handle survived its process");+ // A second tick has nothing to report: the event fires once, not on+ // every tick for the rest of the session.+ assert_eq!(reaped_sidecar_port(&mut slot), None);+ }++ #[test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ fn the_watch_stays_quiet_about_a_sidecar_that_is_still_running() {+ // Negative control. Without it the test above would pass on a watch+ // that announced a death on every tick and cleared the slot with it,+ // which would take the running engine off the screen.+ let child = std::process::Command::new("sh")+ .args(["-c", "sleep 30"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn a long lived child");+ let mut slot = engine_around(child, DEFAULT_EMBED_PORT);++ assert_eq!(reaped_sidecar_port(&mut slot), None, "a live sidecar was declared dead");+ assert!(slot.is_some());++ let mut engine = slot.take().unwrap();+ let _ = engine.child.kill();+ let _ = engine.child.wait();+ }++ #[test]+ fn the_watch_looks_often_enough_to_beat_the_five_second_promise() {+ // The display has to be right within five seconds of a kill. The tick+ // is the coarse half of that budget (the UI's own poll is the other),+ // so a tick slower than the promise would break it silently.+ assert!(+ SIDECAR_WATCH_INTERVAL <= Duration::from_secs(2),+ "the sidecar watch ticks too slowly to keep the five second promise",+ );+ }++ #[test]+ fn an_empty_slot_has_nothing_to_reap() {+ let mut slot: Option<BundledEngine> = None;+ assert!(!reap_dead_engine(&mut slot));+ assert!(slot.is_none());+ }++ #[test]+ fn a_restart_takes_the_default_port_back_as_soon_as_it_is_free() {+ // The exact walk from the box: 8127 held, engine moves to 8129, the+ // blocker goes away, "Apply & Restart Engine" is pressed.+ let moved = DEFAULT_ENGINE_PORT + 2;+ assert!(+ !may_keep_engine_where_it_is(moved, DEFAULT_ENGINE_PORT, || true),+ "the engine stayed on the fallback port with 8127 free, which is the bug"+ );+ // While the blocker is still there, the fallback is the right place and+ // nothing is torn down for nothing.+ assert!(may_keep_engine_where_it_is(moved, DEFAULT_ENGINE_PORT, || false));+ // An engine already on the preferred port is kept without asking, which+ // is what keeps a bind probe off the common path.+ assert!(may_keep_engine_where_it_is(+ DEFAULT_ENGINE_PORT,+ DEFAULT_ENGINE_PORT,+ || panic!("the free-port probe must not run for an engine already at home"),+ ));+ }++ // ── GH #118, the port half ─────────────────────────────────────────────++ #[test]+ fn the_preferred_port_comes_first_and_the_embed_port_is_never_offered() {+ let c = engine_port_candidates(DEFAULT_ENGINE_PORT);+ assert_eq!(c[0], DEFAULT_ENGINE_PORT, "the preferred port is tried first");+ assert!(+ !c.contains(&DEFAULT_EMBED_PORT),+ "taking 8128 would break Document-Chat instead of fixing chat: {c:?}"+ );+ assert_eq!(c.len(), PORT_SEARCH_SPAN as usize + 1, "the walk stays bounded");+ // Negative control: without the skip the second candidate WOULD be the+ // embed port, so the assertion above is really testing the skip.+ assert_eq!(DEFAULT_ENGINE_PORT + 1, DEFAULT_EMBED_PORT);+ assert_eq!(c[1], DEFAULT_EMBED_PORT + 1);+ }++ #[test]+ fn the_walk_ends_instead_of_wrapping_at_the_top_of_the_range() {+ let c = engine_port_candidates(u16::MAX - 2);+ assert_eq!(c, vec![u16::MAX - 2, u16::MAX - 1, u16::MAX]);+ }++ #[test]+ fn a_taken_preferred_port_becomes_the_next_free_one() {+ // The 2.6.6 answer to this situation was an error telling the user to+ // quit a process or reboot. It is a port, and there are others.+ let c = engine_port_candidates(DEFAULT_ENGINE_PORT);+ let taken = [DEFAULT_ENGINE_PORT, DEFAULT_EMBED_PORT + 1];+ let picked = first_usable_port(&c, |p| !taken.contains(&p));+ assert_eq!(picked, Some(DEFAULT_EMBED_PORT + 2));+ // Negative control: nothing free at all is the one case that has to+ // become a message rather than a silent hop.+ assert_eq!(first_usable_port(&c, |_| false), None);+ }++ #[test]+ fn a_completely_blocked_block_says_which_ports_it_tried() {+ let c = engine_port_candidates(DEFAULT_ENGINE_PORT);+ let msg = no_free_port_message(DEFAULT_ENGINE_PORT, *c.last().unwrap());+ assert!(msg.contains("8127"), "{msg}");+ assert!(msg.contains(&c.last().unwrap().to_string()), "{msg}");+ assert!(+ !msg.contains('\u{2014}') && !msg.contains('\u{2013}'),+ "no dashes: {msg}"+ );+ }++ #[test]+ fn a_bind_failure_is_recognised_on_every_platform_wording() {+ // llama.cpp on Linux/macOS, plus the two Winsock numbers Windows uses.+ // 10013 is the one that matters most: a port inside a reserved range+ // answers "permission denied" while nothing is listening on it.+ assert!(stderr_blames_the_port("error: bind: Address already in use"));+ assert!(stderr_blames_the_port("failed to bind to 127.0.0.1:8127"));+ assert!(stderr_blames_the_port("bind error 10048"));+ assert!(stderr_blames_the_port("WSAEACCES (10013)"));+ // Negative control: a GPU death must not be mistaken for a port death,+ // or the retry would move the port and change nothing.+ assert!(!stderr_blames_the_port(+ "ggml_backend_alloc: CUDA error: out of memory"+ ));+ assert!(!stderr_blames_the_port("failed to load model"));+ }++ #[test]+ fn a_port_death_gets_its_own_sentence_instead_of_the_reinstall_advice() {+ let failure = StartFailure {+ died: true,+ port_taken: false,+ stderr: "bind: Address already in use".into(),+ };+ let msg = start_failure_message(&failure, 8127, Duration::from_secs(60));+ assert!(msg.contains("could not open port 8127"), "{msg}");+ assert!(+ !msg.contains("Reinstall"),+ "a busy port is not a broken installation: {msg}"+ );+ // Negative control: an unclassified death keeps the old advice.+ let other = StartFailure {+ died: true,+ port_taken: false,+ stderr: "something went wrong".into(),+ };+ assert!(start_failure_message(&other, 8127, Duration::from_secs(60)).contains("Reinstall"));+ }++ #[test]+ fn a_cuda_allocation_that_happens_to_contain_10048_is_not_a_busy_port() {+ // S1. llama.cpp prints allocation sizes in MiB, so a 10 GB buffer reads+ // "10048.00 MiB". As a bare substring that number used to make a CUDA+ // out-of-memory look like a taken port: the user lost the GPU-Layers+ // way out and the retry hopped to another port for nothing.+ let oom = "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 10048.00 MiB on device 0 failed\nCUDA error: out of memory";+ assert!(!stderr_blames_the_port(oom));+ assert!(stderr_blames_the_gpu(oom));+ let failure = StartFailure { died: true, port_taken: false, stderr: oom.into() };+ let msg = start_failure_message(&failure, 8127, Duration::from_secs(60));+ assert!(msg.contains("GPU Layers to 0"), "the way out has to survive: {msg}");+ assert!(!msg.contains("could not open port"), "{msg}");+ }++ #[test]+ fn a_winsock_number_still_counts_on_a_line_that_is_about_a_socket() {+ // The same number, in the sentence it actually belongs to.+ assert!(stderr_blames_the_port(+ "bind() failed with WSAGetLastError 10048"+ ));+ assert!(stderr_blames_the_port(+ "error creating server socket: 10013"+ ));+ // Negative control: the number alone, on a line about nothing else.+ assert!(!stderr_blames_the_port("model buffer size = 10013.50 MiB"));+ // Negative control across lines: a socket word elsewhere in the tail+ // must not lend context to a number on a different line.+ assert!(!stderr_blames_the_port(+ "srv start: listening\nkv cache size = 10048.00 MiB"+ ));+ }++ #[test]+ fn a_real_bind_sentence_on_an_nvidia_box_still_reads_as_a_port() {+ // Every start on an NVIDIA box drags "cuda" through the log, so the+ // graphics branch must not adopt a failure that names the socket. This+ // is the bundled binary's own wording, measured 2026-09-02.+ let stderr = "ggml_cuda_init: found 1 CUDA devices\nsrv start: couldn't bind HTTP server socket, hostname: 127.0.0.1, port: 8127";+ assert!(stderr_blames_the_gpu(stderr), "the cuda line is really there");+ let failure = StartFailure { died: true, port_taken: false, stderr: stderr.into() };+ let msg = start_failure_message(&failure, 8127, Duration::from_secs(60));+ assert!(msg.contains("could not open port 8127"), "{msg}");+ assert!(!msg.contains("GPU Layers"), "a busy port is not freed by CPU mode: {msg}");+ }++ #[test]+ fn the_retry_moves_to_another_port_only_when_the_port_was_the_cause() {+ // S7: the decision the retry makes, without spawning anything. This is+ // the shape of the code in start_bundled_engine_blocking.+ let hop = |stderr: &str, tried: u16| -> u16 {+ if stderr_blames_the_port(stderr) {+ let rest: Vec<u16> = engine_port_candidates(DEFAULT_ENGINE_PORT)+ .into_iter()+ .filter(|p| *p != tried)+ .collect();+ first_usable_port(&rest, |p| p != tried).unwrap_or(tried)+ } else {+ tried+ }+ };+ assert_ne!(+ hop("srv start: couldn't bind HTTP server socket", DEFAULT_ENGINE_PORT),+ DEFAULT_ENGINE_PORT,+ "a port death has to land somewhere else"+ );+ // Negative control: a GPU death retries on the SAME port, because the+ // VRAM this function asked for is released asynchronously and the port+ // was never the problem.+ assert_eq!(+ hop("CUDA error: out of memory", DEFAULT_ENGINE_PORT),+ DEFAULT_ENGINE_PORT+ );+ assert_eq!(hop("10048.00 MiB", DEFAULT_ENGINE_PORT), DEFAULT_ENGINE_PORT);+ }++ #[test]+ fn a_slow_load_stays_recognisable_as_a_timeout_for_the_frontend() {+ // Contract with lib/engine-start-failure.ts: the boot resume may only+ // repeat a start that DIED. Repeating a start that merely ran out of+ // its budget spends the same budget again (up to 10 minutes on a big+ // GGUF) and re-runs the ComfyUI and Ollama evictions each time.+ let slow = StartFailure { died: false, port_taken: false, stderr: String::new() };+ let msg = start_failure_message(&slow, 8127, Duration::from_secs(60));+ assert!(+ msg.contains("did not become healthy"),+ "the frontend matches on this phrase: {msg}"+ );+ // Negative control: no death message may carry it, or every failure+ // would be treated as a slow load and never retried.+ for stderr in [+ "srv start: couldn't bind HTTP server socket",+ "CUDA error: out of memory",+ "failed to load model",+ "something went wrong",+ ] {+ let died = StartFailure { died: true, port_taken: false, stderr: stderr.into() };+ let m = start_failure_message(&died, 8127, Duration::from_secs(60));+ assert!(!m.contains("did not become healthy"), "{m}");+ }+ }++ #[test]+ fn a_port_this_process_holds_is_not_offered_to_the_engine() {+ // The one socket-level check: bind a port, then ask for it.+ let held = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("bind an ephemeral port");+ let taken = held.local_addr().unwrap().port();+ assert!(!port_is_bindable(taken), "port {taken} is held by this test");+ let candidates = engine_port_candidates(taken);+ let picked = first_usable_port(&candidates, port_is_bindable);+ assert!(picked.is_some(), "the walk has to find a way out");+ assert_ne!(picked, Some(taken));+ // Negative control: the held port is still FIRST in the walk, so it was+ // the bind check that skipped it and not the order of the candidates.+ assert_eq!(first_usable_port(&candidates, |_| true), Some(taken));+ drop(held);+ }+#[test]- #[cfg_attr(target_os = "windows", ignore = "uses sleep")]fn a_child_that_is_still_loading_is_left_alone_until_the_budget_ends() {// Negative control for the check above: a LIVE child must still get// its full budget, or a big GGUF on a cold disk would be declared deaddiff --cc src-tauri/src/commands/gguf.rsindex c50ad14a,16287490..7ece1c54--- a/src-tauri/src/commands/gguf.rs+++ b/src-tauri/src/commands/gguf.rs@@@ -260,13 -279,145 +279,102 @@@ mod testsassert_eq!(context_length(t.to_str().unwrap()), None);}+ // ── The one check in this file against a GGUF this module did not write ──+ //+ // Everything above parses bytes produced by `W`, the writer twenty lines+ // up. That cannot catch the failure both halves share a wrong assumption+ // about; only a file llama.cpp produced can. So this probe is worth+ // keeping — but the way it was written, it was worth nothing:+ //+ // let home = std::env::var("HOME").unwrap_or_default();+ // let p = format!("{home}/Library/Application Support/Locally \+ // Uncensored/models/Qwen2.5-0.5B-Instruct-Q8_0.gguf");+ // if Path::new(&p).exists() { assert_eq!(...) }+ //+ // Two things were wrong with that.+ //+ // 1. It built the path by hand, so it was macOS-only and it named the+ // directory of the PRODUCTION app directly instead of going through+ // `os_paths`, which is the single place that knows the app directory+ // and, on this branch, its isolation suffix. Reading is not a violation+ // — but a hand-built copy of a path is how a WRITE ends up in the+ // user's real data later.+ // 2. It turned itself off in silence. On every machine without that exact+ // file — CI, Windows, Linux, a fresh checkout — it passed while+ // asserting nothing, and said so nowhere. A test that quietly checks+ // nothing is worse than a red one: the red one gets fixed.+ //+ // What replaces it: the path build is pinned by a test that always runs+ // and always asserts, and the file-dependent half announces its skip on a+ // stream the test harness does not capture.++ /// The model the built-in engine ships with. Its trained context length is+ /// a property of the file, not of this repo.+ const REAL_MODEL_FILE: &str = "Qwen2.5-0.5B-Instruct-Q8_0.gguf";+ const REAL_MODEL_CONTEXT: u32 = 32768;+- /// The production app's directory name.- ///- /// A literal on purpose, and the only one in this file: derived from- /// `APP_DISPLAY_DIR` it would follow whatever that constant becomes, and- /// the assertion below — that this build's directory is NOT the- /// production one — would then be checking itself. Same reasoning as- /// `NAMEN_DER_ECHTEN_APP` in `app_identity`.- const PRODUCTION_DISPLAY_DIR: &str = "Locally Uncensored";-- /// Where a real GGUF may be found, most-owned first.- ///- /// 1. This build's own model directory, straight from `os_paths`.- /// 2. The production install's model directory — same parent, same- /// `models` leaf, directory name without this branch's suffix. READ- /// ONLY: on a dev machine that is the only place a real model is, and- /// the isolated build never downloads one.- fn real_gguf_candidates() -> Vec<std::path::PathBuf> {- let own = crate::os_paths::builtin_models_dir();- let mut out = vec![own.join(REAL_MODEL_FILE)];- // <data_dir>/<APP_DISPLAY_DIR>/models -> <data_dir>/<production>/models- if let Some(data_dir) = own.parent().and_then(|p| p.parent()) {- out.push(- data_dir- .join(PRODUCTION_DISPLAY_DIR)- .join("models")- .join(REAL_MODEL_FILE),- );- }- out++ /// Wo ein echtes GGUF liegt: das Modellverzeichnis der eingebauten Engine,++ /// direkt aus `os_paths`. Bewusst kein hier zusammengebauter Pfad — ein++ /// von Hand gebauter Pfad ist genau der Weg, auf dem ein Testlauf spaeter++ /// in die echten Daten des Nutzers schreibt.++ fn real_gguf_path() -> std::path::PathBuf {++ crate::os_paths::builtin_models_dir().join(REAL_MODEL_FILE)+ }+- /// Always runs, always asserts: the probe looks where `os_paths` says, and- /// this build's own directory is not the production one.++ /// Laeuft immer, prueft immer: die Sonde schaut dorthin, wo `os_paths` es++ /// sagt, und nicht auf einen hier zusammengesetzten Namen.#[test]- fn real_bundled_gguf_if_present() {- // Best-effort against the dev machine's local test model; absent in CI.- let home = std::env::var("HOME").unwrap_or_default();- let p = format!("{home}/Library/Application Support/Locally Uncensored/models/Qwen2.5-0.5B-Instruct-Q8_0.gguf");- if std::path::Path::new(&p).exists() {- assert_eq!(super::context_length(&p), Some(32768));+ fn the_real_gguf_probe_goes_through_the_central_path_builder() {+ use crate::app_identity::APP_DISPLAY_DIR;+- let candidates = real_gguf_candidates();- assert_eq!(candidates.len(), 2, "{candidates:?}");-- // #1 is os_paths' own answer, not a string built here.++ let pfad = real_gguf_path();+ assert_eq!(- candidates[0],++ pfad,+ crate::os_paths::builtin_models_dir().join(REAL_MODEL_FILE)+ );++ assert!(pfad.ends_with(REAL_MODEL_FILE));+- // The isolation suffix is real and this build carries it.- assert_ne!(- APP_DISPLAY_DIR, PRODUCTION_DISPLAY_DIR,- "this build reads and would write the production app's model directory"- );- let own_dir = candidates[0]- .parent()- .and_then(|p| p.parent())- .and_then(|p| p.file_name())- .expect("no app directory in the built path");- assert_eq!(own_dir, APP_DISPLAY_DIR);-- // #2 differs from #1 in exactly that one component.- let prod_dir = candidates[1]++ // Und der Pfad steht wirklich unter dem Verzeichnis dieser App, nicht++ // unter irgendeinem: <data_dir>/<APP_DISPLAY_DIR>/models/<datei>.++ let app_dir = pfad+ .parent()+ .and_then(|p| p.parent())+ .and_then(|p| p.file_name())- .expect("no app directory in the production path");- assert_eq!(prod_dir, PRODUCTION_DISPLAY_DIR);- assert_eq!(- candidates[0].parent().and_then(|p| p.parent()).and_then(|p| p.parent()),- candidates[1].parent().and_then(|p| p.parent()).and_then(|p| p.parent()),- "the two candidates are not siblings under the same data dir"- );- assert!(candidates.iter().all(|c| c.ends_with(REAL_MODEL_FILE)));++ .expect("kein App-Verzeichnis im gebauten Pfad");++ assert_eq!(app_dir, APP_DISPLAY_DIR);+ }++ /// Parses a real GGUF when one is on this machine — and says out loud when+ /// there is none, instead of passing in silence.+ ///+ /// The skip notice is written straight to `stderr` rather than through+ /// `eprintln!`: libtest's capture swaps the sink the print macros use, so+ /// a macro line from a PASSING test is swallowed, while a direct write to+ /// the handle reaches the terminal. Verified on this machine, 2026-09-01.+ #[test]+ fn a_real_gguf_parses_or_the_run_says_why_it_could_not() {- let candidates = real_gguf_candidates();- match candidates.iter().find(|p| p.exists()) {- Some(path) => {++ let pfad = real_gguf_path();++ match pfad.exists() {++ true => {++ let path = &pfad;+ assert_eq!(+ context_length(path.to_str().expect("non-UTF-8 model path")),+ Some(REAL_MODEL_CONTEXT),+ "parsing the real model at {} gave the wrong context length",+ path.display()+ );+ }- None => {++ false => {+ use std::io::Write;- let looked: Vec<String> =- candidates.iter().map(|p| p.display().to_string()).collect();+ let _ = writeln!(+ std::io::stderr(),+ "\n SKIPPED gguf::a_real_gguf_parses_or_the_run_says_why_it_could_not\n \+ reason: no real {REAL_MODEL_FILE} on this machine, so the parser was \+ not checked against a file llama.cpp produced.\n looked at:\n {}\n \+ to run it for real, download the built-in engine's model once.\n",- looked.join("\n ")++ pfad.display()+ );+ }}}}diff --cc src-tauri/src/commands/gpu.rsindex 475a10c7,65f84233..95005d5f--- a/src-tauri/src/commands/gpu.rs+++ b/src-tauri/src/commands/gpu.rs@@@ -219,40 -177,7 +228,39 @@@ fn detect_other_via_lspci(have_rocm: bo/// `lspci -nn` output instead of whatever the build machine happens to have./// Deliberately NOT gated on Linux: a parser that only compiles on the target/// is a parser only the target ever proves, and the CI runners are not Linux.-fn detect_other_via_lspci_from(raw: &str, have_rocm: bool) -> Vec<DetectedGpu> {+///+/// Dazu kommen die schon eingelesenen sysfs-Eintraege. Eine AMD-Karte holt+/// ihre Speichergroesse daraus, denn lspci selbst nennt keine. Eine leere+/// Liste ist der Normalfall auf jeder Maschine ohne amdgpu und aendert nichts.+/// Ist diese `lspci -nn` Zeile ein Geraet, das rechnen kann?+///+/// Die drei Grafikklassen und dazu die Rechenbeschleuniger. Die vierte kam+/// dazu, nachdem eine MI325X am 03.09.2026 in tor1 gemessen wurde: eine+/// Instinct hat keinen Bildausgang und meldet deshalb Klasse 1200,+/// "Processing accelerators", nicht 0300. Der alte Filter kannte nur die+/// Grafikklassen, also war die Karte fuer LU schlicht nicht vorhanden, und+/// zwar auf jeder Maschine ohne rocm-smi, weil erst danach der Rueckfall+/// greift. Kein Testrechner hier hat so eine Karte, deswegen fiel es nie auf.+///+/// Geprueft wird gegen die Zahl in eckigen Klammern UND gegen den Klartext.+/// Die Zahl ist die eigentliche Auskunft, der Klartext kommt aus der lokalen+/// pci.ids und fehlt, sobald die Datei alt ist.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn is_graphics_or_compute_class(lower: &str) -> bool {+ lower.contains("[0300]") // VGA compatible controller+ || lower.contains("[0302]") // 3D controller+ || lower.contains("[0380]") // Display controller+ || lower.contains("[1200]") // Processing accelerators+ || lower.contains("vga")+ || lower.contains("3d controller")+ || lower.contains("display controller")+ || lower.contains("processing accelerator")+}++fn detect_other_via_lspci_from(+ raw: &str,+ have_rocm: bool,+ sysfs: &[SysfsDrmCard],+) -> Vec<DetectedGpu> {let mut gpus: Vec<DetectedGpu> = Vec::new();// Per-vendor counters: HIP_VISIBLE_DEVICES and ONEAPI_DEVICE_SELECTOR are// both vendor-scoped, so a machine with an Intel iGPU and an AMD card must@@@ -340,260 -247,6 +348,248 @@@ fn lspci_device_name(line: &str) -> Strif out.is_empty() { "GPU".to_string() } else { out }}+// ----------------------------------------------------------------------+// Linux ohne ROCm: die Groesse steht im Kernel, nicht im ROCm-Paket+//+// Arch-Linux-Kunde, September 2026: "app still does not recognize my VRAM in+// troubleshoot probe", und mehrere Meldungen mit genau diesem Wortlaut. Ohne+// rocm-smi faellt die AMD-Erkennung auf lspci zurueck, und lspci nennt nur den+// Namen. Die Karte stand damit in der Liste, aber ohne Zahl, und alles was+// gegen die Zahl rechnet entschied so, als haette die Maschine gar keinen+// Grafikspeicher.+//+// Der amdgpu-Treiber legt die Zahl selbst offen, ohne jedes ROCm-Paket:+// /sys/class/drm/card<N>/device/mem_info_vram_total Byte, dezimal als Text+// /sys/class/drm/card<N>/device/vendor 0x1002 bei AMD+// "device" ist dabei ein Verweis auf den PCI-Pfad, dessen letzter Bestandteil+// die PCI-Adresse traegt (0000:03:00.0). Dieselbe Adresse steht vorne in jeder+// lspci-Zeile (03:00.0), und genau darueber laeuft die Zuordnung. Nicht ueber+// die Reihenfolge: zwei AMD-Karten in einer Maschine duerfen nicht tauschen,+// sonst zeigt HIP_VISIBLE_DEVICES am Ende auf die andere.+//+// Lesen und Auswerten sind getrennt, wie bei lspci, wmic und der Registry+// auch. Die Maschine, die den Fehler zeigt, ist nicht die Maschine, auf der+// die Tests laufen: hier steckt keine AMD-Karte.+//+// Wo das hier aufhoert, ausgeschrieben statt verschwiegen: gelesen wird nur+// fuer Karten, die lspci schon gefunden hat. Fehlt lspci selbst, weil pciutils+// nicht installiert ist, bleibt die Liste leer wie bisher. sysfs kennt zwar+// die Groesse, aber keinen Namen, nur die Geraetenummer, und eine Liste aus+// Nummern ist eine zweite Aenderung mit einer eigenen Beweislast.++/// Die PCI-Herstellernummer von AMD, wie sie in /sys/.../vendor steht. lspci+/// druckt dieselbe Zahl als [1002:....].- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const PCI_VENDOR_AMD: u16 = 0x1002;++/// Hoechstens so viele Bytes werden aus einer sysfs-Datei gelesen.+///+/// Die Dateien hier tragen eine einzige kurze Zeile. Ein Pfad, der wider+/// Erwarten auf etwas Grosses zeigt, soll den Hardware-Dialog nicht mit einem+/// Dateiinhalt vollaufen lassen.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const SYSFS_READ_LIMIT: u64 = 256;++/// Untergrenze fuer die Zahl aus dem Kernel.+///+/// Eine integrierte AMD-Grafik meldet in mem_info_vram_total den fest+/// abgezweigten Anteil, ab Werk oft 512 MiB, und nicht das GTT-Budget, aus dem+/// sie wirklich rechnet. Diese Zahl als Grafikspeicher zu melden waere+/// schlechter als gar keine: der Fit-Check wuerde Modelle ablehnen, die die+/// APU sehr wohl laedt. Unterhalb der Grenze bleibt die Groesse deshalb+/// ungesetzt, also genau der Zustand, den dieselbe Karte auch heute schon hat.+/// Wer im BIOS bewusst mehr abzweigt, bekommt seine Zahl gemeldet, denn dann+/// ist der Speicher wirklich fuer die Grafik reserviert.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const SYSFS_MIN_TRUSTED_MIB: u64 = 1024;++/// Obergrenze, aus demselben Grund von der anderen Seite. Die groessten+/// Beschleuniger liegen heute im dreistelligen GB-Bereich; ein Vielfaches+/// davon ist kein Speicher mehr, sondern ein missratener Registerwert, und ein+/// zu grosses Versprechen laesst den Fit-Check eine Ladung zusagen, die nie+/// passt.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+const SYSFS_MAX_TRUSTED_MIB: u64 = 1024 * 1024;++/// Ein Verzeichnis /sys/class/drm/card<N>/device, schon eingelesen.+///+/// Die Felder sind Text, genau wie er in den Dateien steht. Was daraus eine+/// Zahl wird, entscheiden die reinen Funktionen darunter, damit echte+/// Beispieldaten einer Kundenmaschine im Test stehen koennen statt einer+/// Nachbildung des Dateisystems.+#[derive(Debug, Clone, PartialEq)]- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+struct SysfsDrmCard {+ /// Letzter Bestandteil des device-Verweises, also die PCI-Adresse.+ pci_address: String,+ /// Inhalt von "vendor", oder None wenn die Datei fehlt oder zu ist.+ vendor_id: Option<String>,+ /// Inhalt von "mem_info_vram_total", ungeprueft.+ vram_total: Option<String>,+}++/// Der Slot vorne in einer lspci-Zeile, also "03:00.0".- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn lspci_slot(line: &str) -> &str {+ line.split_whitespace().next().unwrap_or("")+}++/// "03:00.0" und "0000:03:00.0" auf eine Schreibweise gebracht.+///+/// lspci druckt die PCI-Domain nur, wenn sie nicht null ist; sysfs schreibt sie+/// immer aus. Beide Schreibweisen muessen gleich sein, sonst greift die+/// Zuordnung auf jeder normalen Maschine mit einer einzigen Domain ins Leere.+/// Was nicht wie eine Adresse aussieht, gibt None, damit nichts zusammenfaellt,+/// das nur aehnlich aussieht.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn normalised_pci_address(raw: &str) -> Option<String> {+ let text = raw.trim().to_ascii_lowercase();+ let (domain, rest) = match text.matches(':').count() {+ 2 => text.split_once(':')?,+ 1 => ("0000", text.as_str()),+ _ => return None,+ };+ let (bus, device_function) = rest.split_once(':')?;+ let (device, function) = device_function.split_once('.')?;+ // from_str_radix schluckt ein fuehrendes Pluszeichen, deshalb steht die+ // Zeichenpruefung davor.+ let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());+ if !(hex(domain) && hex(bus) && hex(device) && hex(function)) {+ return None;+ }+ let domain = u32::from_str_radix(domain, 16).ok()?;+ let bus = u32::from_str_radix(bus, 16).ok()?;+ let device = u32::from_str_radix(device, 16).ok()?;+ let function = u32::from_str_radix(function, 16).ok()?;+ // Die Breiten stehen in der PCI-Spezifikation: 16 Bit Domain, 8 Bit Bus,+ // 5 Bit Geraet, 3 Bit Funktion.+ if domain > 0xffff || bus > 0xff || device > 0x1f || function > 0x7 {+ return None;+ }+ Some(format!("{domain:04x}:{bus:02x}:{device:02x}.{function}"))+}++/// "0x1002" als Zahl. Alles andere gibt None.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn parse_sysfs_hex_id(raw: &str) -> Option<u16> {+ let text = raw.trim().to_ascii_lowercase();+ let digits = text.strip_prefix("0x")?;+ if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {+ return None;+ }+ u16::from_str_radix(digits, 16).ok()+}++/// mem_info_vram_total in MiB, oder None wenn die Zahl nicht zu gebrauchen ist.+///+/// Die Datei traegt eine Dezimalzahl in Byte. Alles andere, was dort stehen+/// kann, ist keine Groesse: eine leere Datei, eine Fehlerzeile eines Treibers,+/// eine Zahl mit Einheit dahinter. Statt zu raten bleibt die Groesse dann+/// unbekannt, denn der Fit-Check rechnet gegen diesen Wert.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn parse_sysfs_vram_mib(raw: &str) -> Option<u64> {+ let text = raw.trim();+ if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ let mib = text.parse::<u64>().ok()? / 1024 / 1024;+ if !(SYSFS_MIN_TRUSTED_MIB..=SYSFS_MAX_TRUSTED_MIB).contains(&mib) {+ return None;+ }+ Some(mib)+}++/// Die Speichergroesse zu einer PCI-Adresse, wenn sysfs sie hergibt.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn sysfs_vram_mib_for(pci_address: &str, cards: &[SysfsDrmCard]) -> Option<u64> {+ let wanted = normalised_pci_address(pci_address)?;+ let card = cards+ .iter()+ .find(|c| normalised_pci_address(&c.pci_address).as_deref() == Some(wanted.as_str()))?;+ // Sagt die Karte im sysfs etwas anderes als lspci, wird geschwiegen. Eine+ // unlesbare vendor-Datei ist dagegen kein Widerspruch, sondern eine+ // Auskunft weniger, und die Adresse allein ist eindeutig.+ let disagrees = card+ .vendor_id+ .as_deref()+ .is_some_and(|id| parse_sysfs_hex_id(id) != Some(PCI_VENDOR_AMD));+ if disagrees {+ return None;+ }+ parse_sysfs_vram_mib(card.vram_total.as_deref()?)+}++/// Nur "card0", "card1" und so weiter. "card0-DP-1" ist ein Anschluss und+/// "renderD128" der Renderknoten; beide tragen keine eigene Karte.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn is_drm_card_dir(name: &str) -> bool {+ name.strip_prefix("card")+ .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))+}++/// Eine einzeilige sysfs-Datei, oder None.+///+/// Kein unwrap und kein Panic: auf jeder Maschine ohne amdgpu fehlt hier+/// alles, und das ist der Normalfall, nicht die Ausnahme. Gelesen wird+/// gedeckelt, genommen wird die erste Zeile, und was kein UTF-8 ist faellt+/// still durch.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn read_sysfs_value(path: &std::path::Path) -> Option<String> {+ use std::io::Read;+ let file = std::fs::File::open(path).ok()?;+ let mut text = String::new();+ file.take(SYSFS_READ_LIMIT).read_to_string(&mut text).ok()?;+ let first = text.lines().next()?.trim().to_string();+ if first.is_empty() {+ None+ } else {+ Some(first)+ }+}++/// Die PCI-Adresse aus dem device-Verweis.+///+/// card0/device zeigt auf den PCI-Pfad, meist relativ ("../../0000:03:00.0").+/// Der letzte Bestandteil ist die Adresse. read_link zuerst, weil es den+/// Verweis nicht aufloesen muss; canonicalize als Rueckfall, falls dort kein+/// Verweis liegt, sondern ein echtes Verzeichnis.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn sysfs_pci_address(device_dir: &std::path::Path) -> Option<String> {+ let target = std::fs::read_link(device_dir)+ .or_else(|_| std::fs::canonicalize(device_dir))+ .ok()?;+ let last = target.file_name()?.to_string_lossy().into_owned();+ // Was sich nicht als Adresse lesen laesst, ist keine.+ normalised_pci_address(&last).map(|_| last)+}++/// Alle Karten unter einem Wurzelverzeichnis, eingelesen und sonst nichts.+///+/// Nimmt die Wurzel als Parameter statt sie fest zu verdrahten, damit ein Test+/// einen echten kleinen Baum anlegen und diesen Weg auch ohne AMD-Karte+/// abgehen kann. Ein Verzeichnis, das es nicht gibt, gibt eine leere Liste:+/// das ist jede Nicht-Linux-Maschine und jeder Rechner ohne DRM-Treiber.- #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+fn read_sysfs_drm_cards_at(root: &std::path::Path) -> Vec<SysfsDrmCard> {+ let mut cards: Vec<SysfsDrmCard> = Vec::new();+ let Ok(entries) = std::fs::read_dir(root) else {+ return cards;+ };+ for entry in entries.flatten() {+ let name = entry.file_name().to_string_lossy().into_owned();+ if !is_drm_card_dir(&name) {+ continue;+ }+ let device = entry.path().join("device");+ let Some(pci_address) = sysfs_pci_address(&device) else {+ continue;+ };+ cards.push(SysfsDrmCard {+ pci_address,+ vendor_id: read_sysfs_value(&device.join("vendor")),+ vram_total: read_sysfs_value(&device.join("mem_info_vram_total")),+ });+ }+ cards+}++/// Der Ort, an dem der Kernel die Karten auflistet.- #[cfg(target_os = "linux")]++///++/// Ungegatet, aus demselben Grund, den `detect_other_via_lspci` fuer sich++/// nennt: der einzige Aufruf steht hinter dessen Laufzeit-Weiche, und ein++/// `#[cfg]` hier haette die ganze sysfs-Kette auf macOS und Windows ohne++/// Aufrufer zurueckgelassen. Ausserhalb von Linux gibt es das Verzeichnis++/// nicht, und dann kommt eine leere Liste zurueck.+fn read_sysfs_drm_cards() -> Vec<SysfsDrmCard> {+ read_sysfs_drm_cards_at(std::path::Path::new("/sys/class/drm"))+}+- #[cfg(not(target_os = "linux"))]- fn detect_other_via_lspci(_have_rocm: bool) -> Vec<DetectedGpu> { vec![] }-#[cfg(target_os = "macos")]fn detect_macos() -> Vec<DetectedGpu> {// macOS uses Metal/MPS via the unified GPU. We surface a single entry sodiff --cc src-tauri/src/commands/health.rsindex 15ef8b40,15ef8b40..94ea600f--- a/src-tauri/src/commands/health.rs+++ b/src-tauri/src/commands/health.rs@@@ -140,7 -140,7 +140,7 @@@ async fn probe_http(url: &str) -> Backe/// `"24576, 23000"` (values in MiB, `nounits` strips the " MiB"). Returns/// `(total_gb, free_gb)` for the GPU with the most total memory — picking the/// biggest card matches the "what can I fit a model into?" question and--/// mirrors install.rs taking the highest compute-cap across GPUs.++/// mirrors the ComfyUI installer taking the highest compute-cap across GPUs.////// Returns `None` on empty / unparseable output. Conversion uses 1024 MiB =/// 1 GiB (nvidia-smi reports MiB), rounded to 1 decimal to match ram_gb.diff --cc src-tauri/src/commands/install/comfy_install.rsindex 00000000,6aec89ea..716b186fmode 000000,100644..100644--- a/src-tauri/src/commands/install/comfy_install.rs+++ b/src-tauri/src/commands/install/comfy_install.rs@@@ -1,0 -1,762 +1,878 @@@+ //! Die Erstinstallation von ComfyUI, vom leeren Ordner bis zum gespeicherten Pfad.+ //!+ //! Der geteilte Zustand ist das ZIELVERZEICHNIS, und zwar über die ganze+ //! Laufzeit des Auftrags hinweg: erst als Frage (ist da genug Platz? was liegt+ //! schon drin?), dann als Baustelle (Clone, venv, PyTorch, Requirements) und+ //! am Ende als Tatsache, die in `config.json` geschrieben wird und dort jeden+ //! späteren Aufruf von `find_comfyui_path` bestimmt.+ //!+ //! Deshalb liegen die Torwächter hier und nicht bei den allgemeinen Helfern.+ //! `classify_existing_target` beantwortet die Frage, die git mit+ //! "already exists" verschluckt — jedes nicht leere Verzeichnis bekommt diese+ //! Antwort, auch ein Downloads-Ordner. Und `comfy_install_looks_finished` ist+ //! das letzte Tor davor, dass ein Lauf sich selbst einen Erfolg nennt und+ //! seinen Pfad festschreibt. Beide gehören zum Zielverzeichnis, beide sind+ //! reine Pfadarbeit, und beide waren einmal nicht da: das ist der P14-Rumpf.++ use std::io::Read as IoRead;+ use std::path::{Path, PathBuf};+ use std::process::{Command, Stdio};+ use std::sync::atomic::Ordering;++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::State;+ use tracing::{error, info};++ use crate::state::AppState;++use crate::os_error;++use super::comfy_job::{finished_notice, requirements_fallback_log};++use super::env_check::verify_and_heal_environment;++use super::pip::{pip_install_streaming_with_retry_raw, requirements_failure_reason_for, should_retry_in_user_site};++ use super::children::TrackedInstallerChild;+ use super::comfy_job::{ComfyJob, COMFY_JOB};+ use super::comfy_job::comfy_job_busy_message;+ use super::pip::pip_install_streaming_with_retry_cancellable;+ use super::torch::plan_pytorch_install;+ use super::venv::{create_comfyui_venv, is_pep668_protected};+ #[cfg(target_os = "windows")]+ use super::git::{windows_git_install_hint, windows_git_probe, WindowsGitState};+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ── Disk-pressure pre-flight (Bug #1 — techx69 100%-busy-drive hang) ────────+ //+ // FREE SPACE IS THE ONLY THING MEASURED HERE, and that is deliberate. The doc+ // comment below used to promise a second check as well — "or its pending I/O+ // queue suggests sustained 100% utilisation" — which no version of this+ // function ever performed (KF-28, read at HEAD 01.09.2026). Three reasons it+ // stays that way rather than being built:+ //+ // * Nothing consumes such a verdict. The one caller (`install_comfyui`)+ // pushes whatever string comes back into the install log and starts the+ // install regardless — it does not gate, retry or choose a drive. A+ // queue reading would produce a second sentence and change nothing.+ // * The busy-drive case in Bug #1 is answered somewhere else entirely, and+ // was already when this comment was written: the install became+ // CANCELLABLE (`state.comfyui_install_cancel`, polled between steps and+ // inside the pip retry loop, killing the live git/pip child). That is+ // what turned the 45-minute hang into something a user can leave. A+ // pre-flight guess about the drive is no substitute for a stop button.+ // * There is no reading to take. `sysinfo` 0.33 exposes `Disk::usage()` →+ // `DiskUsage`, which is four byte counters (read/written, total and+ // since-last-refresh). No queue depth, no utilisation percentage, on any+ // platform. Deriving "100% busy" from two byte deltas would be a guess+ // wearing a number.+ //+ // `disk_pressure_doc_matches_body` at the bottom of this file holds the two+ // halves together, in both directions: promise without probe is red, and so+ // is probe without promise. The "why not" lives up here, in a plain comment,+ // so that the doc comment below can say only what the function does.++ /// Return a human-readable warning when the target install drive is short on+ /// free space — under 5 GB, since ComfyUI plus the PyTorch wheels need about+ /// that much. That is the whole check; a drive with room comes back `None`.+ ///+ /// Best-effort in the other direction too: `None` when `sysinfo` lists no+ /// mount point that is a prefix of `target_dir`, so a probing flake never+ /// blocks a well-meaning install.+ fn check_install_disk_pressure(target_dir: &Path) -> Option<String> {+ use sysinfo::Disks;+ let disks = Disks::new_with_refreshed_list();+ // Find the disk that contains the target dir. sysinfo's Disk::mount_point+ // is a PathBuf — pick the longest mount that is a prefix of target_dir.+ let normalized = target_dir.to_path_buf();+ let mut best: Option<&sysinfo::Disk> = None;+ let mut best_len: usize = 0;+ for d in &disks {+ let mp = d.mount_point();+ if normalized.starts_with(mp) {+ let len = mp.as_os_str().len();+ if len > best_len {+ best_len = len;+ best = Some(d);+ }+ }+ }+ let disk = best?;++ let free_bytes = disk.available_space();+ let total_bytes = disk.total_space();+ let needed_bytes: u64 = 5 * 1024 * 1024 * 1024; // 5 GB+ if free_bytes < needed_bytes {+ return Some(format!(+ "⚠ Low disk space on {}: {:.1} GB free of {:.1} GB total. \+ ComfyUI + PyTorch need about 5 GB. Consider freeing space or \+ choosing a drive with more room before continuing.",+ disk.mount_point().to_string_lossy(),+ free_bytes as f64 / 1_073_741_824.0,+ total_bytes as f64 / 1_073_741_824.0,+ ));+ }+ None+ }++ // ── OI-2: what git actually means by "already exists" ───────────────────────++ /// What a clone target that git refused with `already exists` really is.+ ///+ /// `git clone` prints "destination path '…' already exists and is not an empty+ /// directory" for ANY non-empty directory — a Downloads folder, a half-cloned+ /// ComfyUI, someone else's repo. The installer read that one string as "a+ /// ComfyUI is already there, pull it", ran a `git pull` whose exit status it+ /// threw away, and then walked the whole PyTorch + requirements path against a+ /// directory that may never have held ComfyUI. Two GB later it reported+ /// "ComfyUI installed successfully!" and persisted `comfyui_path` to that+ /// directory, which then poisoned `find_comfyui_path` for every future call.+ ///+ /// That is the P14 torso, re-entered through the back door. This type is the+ /// gate: the branch has to know what it is looking at before it spends the+ /// user's bandwidth.+ #[derive(Debug, PartialEq, Eq, Clone, Copy)]+ pub(crate) enum ExistingTarget {+ /// `.git` + `main.py`: a real ComfyUI checkout. Pull and carry on.+ ComfyCheckout,+ /// `.git` but no `main.py`: a git repo that is not ComfyUI, or a clone+ /// that died before checkout. Never install into it, never overwrite it.+ ForeignOrIncompleteRepo,+ /// Not a git repo at all. Whatever the user has in there, it is not+ /// something a `git pull` can turn into ComfyUI.+ NotARepo,+ }++ /// Classify a clone target. Pure path logic so the branch is testable without+ /// git, a network, or a 2 GB download.+ pub(crate) fn classify_existing_target(dir: &Path) -> ExistingTarget {+ if !dir.join(".git").exists() {+ return ExistingTarget::NotARepo;+ }+ if dir.join("main.py").exists() {+ ExistingTarget::ComfyCheckout+ } else {+ ExistingTarget::ForeignOrIncompleteRepo+ }+ }++ /// The message the user gets when the install refuses a target it cannot+ /// safely use. Says which directory, what is wrong with it, and what to do —+ /// a bare "install failed" on a path the user picked themselves is the same+ /// dead end as the silent success it replaces.+ pub(crate) fn existing_target_refusal(dir: &Path, verdict: ExistingTarget) -> String {+ match verdict {+ ExistingTarget::ComfyCheckout => String::new(),+ ExistingTarget::ForeignOrIncompleteRepo => format!(+ "{} is a git repository, but it is not a ComfyUI checkout (no main.py). \+ LU will not install into it — pick an empty folder, or delete this one \+ first if it is a failed download.",+ dir.display()+ ),+ ExistingTarget::NotARepo => format!(+ "{} already exists and is not a ComfyUI checkout. git refuses to clone \+ into a non-empty folder, and LU will not install on top of files it did \+ not put there. Pick an empty folder, or move this one aside and retry.",+ dir.display()+ ),+ }+ }++ /// The end-of-install gate: a finished ComfyUI has `main.py`. Checked before+ /// success is reported AND before `comfyui_path` is persisted, because the+ /// persisted path is what `find_comfyui_path` hands to every later call — a+ /// wrong value there outlives the failed install by the whole lifetime of the+ /// config file.+ pub(crate) fn comfy_install_looks_finished(dir: &Path) -> bool {+ dir.join("main.py").exists()+ }++ #[tauri::command]+ pub fn install_comfyui(+ install_path: Option<String>,+ state: State<'_, AppState>,+ ) -> Result<serde_json::Value, String> {+ // Never on macOS: local media there is MLX. Refusing before we touch the+ // install slot means a stray call cannot even leave the status machine in+ // "installing" — see start_comfyui for why the guard lives in Rust and not+ // only in the UI that hides these buttons.+ if !crate::commands::process::comfy_supported_here() {+ return Err(crate::commands::process::MACOS_COMFY_REFUSAL.to_string());+ }++ // OI-5: take the runtime before touching the shared status slot. A second+ // click on Install is idempotent; a repair or update arriving mid-install+ // is refused loudly rather than allowed to delete the venv underneath us.+ let job_guard = match COMFY_JOB.try_acquire(ComfyJob::Install) {+ Ok(g) => g,+ Err(ComfyJob::Install) => return Ok(serde_json::json!({"status": "already_installing"})),+ Err(running) => return Err(comfy_job_busy_message(ComfyJob::Install, running)),+ };++ let mut install = state.install_status.lock().unwrap();+ install.status = "installing".to_string();+ install.logs.clear();++ install.notice.clear();++ install.notice_kind.clear();+ install.logs.push("Starting ComfyUI installation...".to_string());+ drop(install);++ info!("comfyui install start");++ // Reset cancel flag (Bug #1) — a previous cancelled install would+ // otherwise short-circuit the new run on first poll.+ state.comfyui_install_cancel.store(false, Ordering::SeqCst);+ let cancel_flag = state.comfyui_install_cancel.clone();++ let target_dir = install_path+ .map(PathBuf::from)+ .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("ComfyUI"));++ // Bug #1 (techx69): pre-flight disk pressure check. On a drive sitting+ // at 100% utilisation the install hangs for 45+ minutes and the app+ // OOMs. Surface the risk BEFORE we start — the user can free space+ // or pick a different drive instead of staring at a frozen progress+ // log. We don't refuse to start: some users will accept the slow path.+ if let Some(warning) = check_install_disk_pressure(&target_dir) {+ if let Ok(mut s) = state.install_status.lock() {+ s.logs.push(warning);+ }+ }++ // Pre-flight: refuse to start ComfyUI install without a real Python.+ // The frontend is expected to call `install_python` first when this+ // returns the "no python" error — that flow shows a Python-install+ // progress card before re-firing `install_comfyui`. The ComfyUI carcass+ // bug (P14) was caused by skipping this check: pip got fed the Microsoft+ // Store stub `python.exe`, which exit-1'd, leaving a half-cloned+ // ComfyUI dir on disk that LU then mistakenly detected as "installed".+ let python_bin = state.python_bin.lock().unwrap().clone();+ if python_bin.is_empty() || !crate::python::is_real_python(&python_bin) {+ // Reset install state so the frontend's polling sees the error+ // immediately — without this the spawned thread below never runs and+ // the UI sits on "installing" forever.+ let mut install = state.install_status.lock().unwrap();+ install.status = "error".to_string();+ install.logs.push(+ "Python is not installed on this machine. \+ Install Python first (Settings → ComfyUI → Install Python, \+ or click 'Install Python' in the onboarding ComfyUI step), \+ then retry the ComfyUI install."+ .to_string(),+ );+ error!("comfyui install aborted: no usable python");+ return Err(+ "no_python: Python must be installed before ComfyUI. Call install_python first."+ .to_string(),+ );+ }+ let install_status = state.install_status.clone();+ // Cloned into the worker so a custom install target can be persisted as+ // the active ComfyUI path once the install completes (andy_38747).+ let comfy_path_slot = state.comfy_path.clone();++ std::thread::spawn(move || {+ // Held for the whole job: dropping it hands the runtime back, and it+ // drops on every exit path from this closure, panics included.+ let _job_guard = job_guard;++ // Helper to update install status + logs+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_status.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };+++ // Set when `pip install -r requirements.txt` failed and the run carried++ // on with LU's own package list. Folder plus reason, so the live log++ // line and the line the finished run leaves behind agree (A15).++ let mut requirements_fallback: Option<(String, &'static str)> = None;+++ let cancelled = || cancel_flag.load(Ordering::SeqCst);++ if cancelled() {+ update("cancelled", "Install cancelled before it started.");+ return;+ }++ // Bug N (juliandiggins-stack issue #40, 2026-05-18) — probe Windows+ // git BEFORE clone so a WSL/non-native git on PATH surfaces a clear+ // hint instead of failing the clone halfway with cryptic stderr.+ #[cfg(target_os = "windows")]+ {+ let probe = windows_git_probe();+ if let Some(hint) = windows_git_install_hint(&probe) {+ if probe == WindowsGitState::Missing {+ update("error", &hint);+ return;+ }+ // NonNative — log the warning to the install panel but+ // proceed; many MSYS/Cygwin gits handle Windows paths fine.+ update("downloading", &hint);+ }+ }++ // Step 1: Git clone — spawn+poll instead of cmd.output() so the+ // Cancel button can kill an in-flight clone (Bug #1).+ println!("[Install] Cloning ComfyUI to {:?}", target_dir);- update("downloading", "Step 1/3: Downloading ComfyUI repository...");++ update("downloading", "Step 1/4: Downloading ComfyUI repository...");++ let mut cmd = Command::new("git");+ cmd.args(["clone", "https://github.com/comfyanonymous/ComfyUI.git"])+ .arg(&target_dir)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let mut clone_child = match cmd.spawn() {+ Ok(c) => c,+ Err(e) => {- let err = format!("Git is not installed or not in PATH: {}", e);++ let err = format!("Git is not installed or not in PATH: {}", os_error::english(&e));+ println!("[Install] {}", err);+ update("error", &err);+ return;+ }+ };+ // OI-7: same registration as the pip runs. `git clone` spawns its own+ // fetch/index-pack helpers, which a plain kill leaves writing.+ let clone_pid = clone_child.id();+ let _tracked_clone = TrackedInstallerChild::register(clone_pid);+ let clone_exit = loop {+ if cancelled() {+ crate::commands::shell::kill_tree(clone_pid);+ let _ = clone_child.kill();+ let _ = clone_child.wait();+ update("cancelled", "Install cancelled during git clone.");+ return;+ }+ match clone_child.try_wait() {+ Ok(Some(s)) => break s,+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(250)),+ Err(e) => {- update("error", &format!("git wait failed: {}", e));++ update("error", &format!("git wait failed: {}", os_error::english(&e)));+ return;+ }+ }+ };++ if clone_exit.success() {+ println!("[Install] Git clone successful");+ update("installing", "Repository cloned successfully.");+ } else {+ let mut stderr = String::new();+ if let Some(mut e) = clone_child.stderr.take() {+ let _ = e.read_to_string(&mut stderr);+ }+ if stderr.contains("already exists") {+ // OI-2: "already exists" is git's answer for ANY non-empty+ // directory. Find out what is actually in there before+ // spending 2 GB of the user's bandwidth on it.+ let verdict = classify_existing_target(&target_dir);+ if verdict != ExistingTarget::ComfyCheckout {+ let err = existing_target_refusal(&target_dir, verdict);+ println!("[Install] {}", err);+ error!(target = %target_dir.display(), ?verdict, "comfyui install refused an unusable clone target");+ update("error", &err);+ return;+ }+ println!("[Install] ComfyUI directory already exists, updating...");+ update("installing", "ComfyUI already exists, pulling latest...");+ if cancelled() {+ update("cancelled", "Install cancelled.");+ return;+ }+ let mut pull = Command::new("git");+ pull.args(["pull"]).current_dir(&target_dir)+ .stdout(Stdio::piped()).stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ pull.creation_flags(CREATE_NO_WINDOW);++ // Hier landet auch ein Ordner, der gar kein git-Checkout ist:++ // eine Installation, die von einem anderen Rechner per Stick++ // kopiert wurde, so kam falconbob_20415 zu einem ComfyUI mit++ // fehlenden Dateien. Auch das wird gesagt statt still weiterzulaufen.+ // The pull's result was discarded outright before. It is not+ // fatal — the checkout is already a ComfyUI, so an offline box+ // or a diverged branch should still get its dependencies —+ // but it must be SAID, or the user reads "installed+ // successfully" over a core that never moved.+ match pull.output() {+ Ok(o) if o.status.success() => {+ update("installing", "Repository updated to the latest ComfyUI.");+ }+ Ok(o) => {+ let detail = String::from_utf8_lossy(&o.stderr).trim().to_string();+ update(+ "installing",+ &format!(+ "git pull did not succeed, continuing with the ComfyUI already \+ on disk. If nodes are missing afterwards, update it manually.\n{}",+ detail.chars().take(400).collect::<String>()+ ),+ );+ }+ Err(e) => {+ update(+ "installing",+ &format!(+ "Could not run git pull ({}), continuing with the ComfyUI \+ already on disk.",+ e+ ),+ );+ }+ }+ } else {+ let err = format!("Git clone failed: {}", stderr);+ println!("[Install] {}", err);+ update("error", &err);+ return;+ }+ }++ if cancelled() {+ update("cancelled", "Install cancelled after clone.");+ return;+ }++ // Bug E (rzgrozt — Arch GH #32 comment, 2026-05-08): if the system+ // Python is PEP 668 protected (Arch, Debian 12+, Fedora 38+, Ubuntu+ // 23.04+), a bare `python -m pip install ...` exits with+ // `error: externally-managed-environment` and leaves the user with+ // a half-cloned ComfyUI dir and no diagnostic. Detect the marker+ // file via the system Python, then create a venv inside the+ // ComfyUI folder and use the venv's Python for every subsequent+ // pip step. The launcher in `process.rs` mirrors this check and+ // prefers the venv when starting ComfyUI, so the user gets a+ // consistent isolated environment without ever touching pacman.- let effective_python = if is_pep668_protected(&python_bin) {++ // A venv that is already there wins over everything below. The++ // launcher starts ComfyUI out of it (process.rs) and update_comfyui++ // installs into it, so an installer that reached past it would put the++ // packages in one interpreter and start another: press Install after a++ // Repair and the requirements land in the system Python while ComfyUI++ // keeps running out of the venv that still has the hole.++ let existing_venv = crate::python::resolve_comfyui_venv_python(&target_dir);++ let effective_python = if let Some(venv_py) = existing_venv {++ update(++ "installing",++ &format!(++ "This ComfyUI already has its own environment. Installing into {venv_py}."++ ),++ );++ venv_py++ } else if is_pep668_protected(&python_bin) {+ update(+ "installing",+ "Python is PEP 668 protected (Arch / Debian 12+ / Fedora 38+ / \+ Ubuntu 23.04+). Creating an isolated venv at ComfyUI/venv so \+ pip can install PyTorch + ComfyUI deps without touching your \+ system Python …",+ );+ match create_comfyui_venv(&target_dir, &python_bin) {+ Ok(venv_py) => {+ let p = venv_py.to_string_lossy().to_string();+ update(+ "installing",- &format!("venv ready — using {} for the install.", p),++ &format!("venv ready, using {} for the install.", p),+ );+ p+ }+ Err(e) => {+ update("error", &format!("venv creation failed.\n\n{}", e));+ return;+ }+ }+ } else {+ python_bin.clone()+ };++ // Step 2: Detect GPU and install PyTorch (probe + wheel choice shared+ // with repair_comfyui_env via plan_pytorch_install).+ let (torch_args, gpu_info) = plan_pytorch_install();+ println!("[Install] {}", gpu_info);- update("installing", &format!("Step 2/3: {}", gpu_info));++ update("installing", &format!("Step 2/4: {}", gpu_info));+ update(+ "installing",+ "Downloading PyTorch + Torchvision + Torchaudio (~2 GB total). \+ On a typical home connection this takes 10–15 minutes; on slower \+ links it can be longer. Live pip output below — if you see new \+ lines appearing, the install is making progress, not hung.",+ );++ let torch_arg_refs: Vec<&str> = torch_args.iter().map(|s| s.as_str()).collect();+ match pip_install_streaming_with_retry_cancellable(&torch_arg_refs, &effective_python, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => {+ update("installing", "PyTorch installed successfully.");+ }+ Err(diagnosis) if diagnosis == "cancelled" => {+ update("cancelled", "Install cancelled during PyTorch download.");+ return;+ }+ Err(diagnosis) => {+ let err = format!("PyTorch installation failed.\n\n{}", diagnosis);+ println!("[Install] {}", err);+ update("error", &err);+ return;+ }+ }++ if cancelled() {+ update("cancelled", "Install cancelled before requirements install.");+ return;+ }++ // Step 3: Install ComfyUI requirements+ println!("[Install] Installing ComfyUI requirements...");- update("installing", "Step 3/3: Installing ComfyUI dependencies (live pip output below)...");++ update("installing", "Step 3/4: Installing ComfyUI dependencies (live pip output below)...");+++ // A3: a folder without requirements.txt is not a ComfyUI checkout, and++ // skipping the step silently is how falconbob_20415's copied install++ // reached "installed successfully" with nothing in it. The clone above++ // treats an existing folder as "pull and carry on", so this is the++ // place that notices.+ let reqs = target_dir.join("requirements.txt");- if reqs.exists() {++ if !reqs.exists() {++ update(++ "error",++ &format!(++ "The folder {} has no requirements.txt, so it is not a complete ComfyUI \++ checkout and its dependencies cannot be installed. Rename or delete that \++ folder and run the install again.",++ target_dir.display()++ ),++ );++ return;++ }++ {+ let reqs_str = reqs.to_string_lossy().to_string();+ let req_args = vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "-r", reqs_str.as_str(),+ ];- match pip_install_streaming_with_retry_cancellable(&req_args, &effective_python, 3, &install_status, Some(&cancel_flag)) {++ match pip_install_streaming_with_retry_raw(&req_args, &effective_python, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => {+ update("installing", "Dependencies installed successfully.");+ }- Err(diagnosis) if diagnosis == "cancelled" => {++ Err(f) if f.diagnosis == "cancelled" => {+ update("cancelled", "Install cancelled during requirements install.");+ return;+ }- Err(diagnosis) => {- // Don't fail the whole install — some optional deps may fail- // but ComfyUI can still start and the user can fix them later.- println!("[Install] Requirements install warning: {}", diagnosis);- update("installing", "Some optional dependencies had warnings (non-critical, ComfyUI should still start).");++ Err(f) => {++ let diagnosis = f.diagnosis.clone();++ // A python.org install under Program Files has an++ // admin-only site-packages, and without a venv the first++ // wheel that is not already there dies on it. The same++ // escape the custom node path has used since 2026-07-19,++ // and only where no venv was built: a venv rejects --user.++ // Decided on the RAW stderr: the diagnosis keeps only the++ // first 400 characters of the log, and pip prints the++ // permission line at the end of a long one.++ let retried = if should_retry_in_user_site(++ effective_python != python_bin,++ &f.stderr,++ ) {++ update(++ "installing",++ "The dependencies could not be written to the shared site-packages. \++ Retrying into the per user site, which needs no administrator.",++ );++ let mut user_args = req_args.clone();++ user_args.push("--user");++ pip_install_streaming_with_retry_cancellable(&user_args, &effective_python, 2, &install_status, Some(&cancel_flag)).is_ok()++ } else {++ false++ };++ if retried {++ update("installing", "Dependencies installed successfully.");++ } else {++ // Not fatal on its own: the import check below decides++ // whether the environment can actually start. What is++ // gone is the old "non-critical" verdict, which called++ // a broken environment a finished one.++ println!("[Install] Requirements install warning: {}", diagnosis);++ let reason = requirements_failure_reason_for(&f);++ let folder = target_dir.display().to_string();++ requirements_fallback = Some((folder.clone(), reason));++ update("installing", &requirements_fallback_log(&folder, reason));++ update(++ "installing",++ &format!(++ "Not every dependency installed. Checking what is really missing.\n\n{}",++ diagnosis++ ),++ );++ }+ }+ }+ }++ // OI-2: the last gate before this run is allowed to call itself a+ // success. Everything above can have gone through — clone reported+ // fine, pip reported fine — and still leave a directory with no+ // ComfyUI in it, and the persist step below writes that directory+ // into config.json where `find_comfyui_path` will keep handing it out+ // long after the install is forgotten.+ if !comfy_install_looks_finished(&target_dir) {+ let err = format!(+ "The install finished but {} has no main.py, so there is no ComfyUI to \+ start. Nothing was saved as your ComfyUI path. Check the log above for \+ the step that failed, then retry into an empty folder.",+ target_dir.display()+ );+ println!("[Install] {}", err);+ error!(target = %target_dir.display(), "comfyui install produced no main.py");+ update("error", &err);+ return;+ }+++ if cancelled() {++ update("cancelled", "Install cancelled before the environment check.");++ return;++ }++++ // Step 4: the environment has to prove it starts. Everything above++ // reads pip exit codes; this reads the interpreter.++ update("installing", "Step 4/4: Checking that the environment really starts...");++ match verify_and_heal_environment(&effective_python, &reqs, &install_status, Some(&cancel_flag)) {++ Ok(()) => {}++ Err(e) if e == "cancelled" => {++ update("cancelled", "Install cancelled during the environment check.");++ return;++ }++ Err(e) => {++ error!("comfyui install finished with an environment that does not import");++ update("error", &format!("ComfyUI was downloaded, but its Python environment is not usable.\n\n{}", e));++ return;++ }++ }+++ println!("[Install] ComfyUI installation complete");++ // andy_38747 (Discord): the install target is user-configurable now.+ // Persist it exactly like `set_comfyui_path` does (memory + config.json),+ // otherwise a non-default target (e.g. D:\ComfyUI) is installed fine but+ // never found again — `find_comfyui_path` only scans standard locations.+ let dir_str = target_dir.to_string_lossy().to_string();+ {+ let mut p = comfy_path_slot.lock().unwrap();+ *p = Some(dir_str.clone());+ }+ {+ let app_config = crate::os_paths::app_config_dir();+ let _ = std::fs::create_dir_all(&app_config);+ let config_file = app_config.join("config.json");+ let mut config: serde_json::Value = std::fs::read_to_string(&config_file)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_else(|| serde_json::json!({}));+ config["comfyui_path"] = serde_json::json!(dir_str);+ let _ = std::fs::write(+ &config_file,+ serde_json::to_string_pretty(&config).unwrap_or_default(),+ );+ }+++ if let Ok(mut s) = install_status.lock() {++ let (line, kind) = finished_notice(++ "Install finished. ComfyUI is ready to start.",++ requirements_fallback.as_ref(),++ );++ s.notice = line;++ s.notice_kind = kind.to_string();++ }+ update("complete", "ComfyUI installed successfully!");+ });++ Ok(serde_json::json!({"status": "installing"}))+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ // ── OI-2: "ComfyUI installed successfully!" for an empty directory ────+ //+ // git says "already exists" for ANY non-empty target. The installer read+ // that as "a ComfyUI is there", threw the following pull's exit status+ // away, never checked for `.git`, never checked for main.py, and 2 GB+ // later persisted the directory as `comfyui_path` — which then poisoned+ // `find_comfyui_path` for the rest of the config file's life.+ //+ // These tests cover the classification and the final gate. NOT covered:+ // that git actually prints "already exists" for the cases below — that is+ // git's documented behaviour, not ours, and reproducing it needs a real+ // clone into a real directory.++ fn dir_with(entries: &[&str]) -> tempfile::TempDir {+ let tmp = tempfile::tempdir().unwrap();+ for e in entries {+ if e.ends_with('/') {+ std::fs::create_dir_all(tmp.path().join(e.trim_end_matches('/'))).unwrap();+ } else {+ std::fs::write(tmp.path().join(e), b"x").unwrap();+ }+ }+ tmp+ }++ #[test]+ fn a_real_comfyui_checkout_is_the_only_target_worth_pulling() {+ let d = dir_with(&[".git/", "main.py"]);+ assert_eq!(classify_existing_target(d.path()), ExistingTarget::ComfyCheckout);+ // And the refusal text for it is empty — there is nothing to refuse.+ assert!(existing_target_refusal(d.path(), ExistingTarget::ComfyCheckout).is_empty());+ }++ #[test]+ fn a_plain_non_empty_folder_is_refused_not_installed_into() {+ // The user pointed the installer at their Downloads folder, or at a+ // directory a previous run left half-populated. git refuses to clone+ // into it and says "already exists" — which is NOT permission to+ // spend 2 GB and call it a ComfyUI.+ let d = dir_with(&["some-file.txt", "notes/"]);+ assert_eq!(classify_existing_target(d.path()), ExistingTarget::NotARepo);+ let msg = existing_target_refusal(d.path(), ExistingTarget::NotARepo);+ assert!(msg.contains(&d.path().display().to_string()), "{msg}");+ assert!(msg.to_lowercase().contains("empty folder"), "{msg}");+ }++ #[test]+ fn a_git_repo_that_is_not_comfyui_is_refused() {+ // Someone else's checkout, or a clone that died before checkout. A+ // `git pull` in there succeeds and still leaves no ComfyUI.+ let d = dir_with(&[".git/", "README.md"]);+ assert_eq!(+ classify_existing_target(d.path()),+ ExistingTarget::ForeignOrIncompleteRepo+ );+ let msg = existing_target_refusal(d.path(), ExistingTarget::ForeignOrIncompleteRepo);+ assert!(msg.contains("main.py"), "{msg}");+ }++ #[test]+ fn an_empty_or_missing_directory_is_not_a_repo() {+ let d = dir_with(&[]);+ assert_eq!(classify_existing_target(d.path()), ExistingTarget::NotARepo);+ assert_eq!(+ classify_existing_target(&d.path().join("does-not-exist")),+ ExistingTarget::NotARepo+ );+ }++ #[test]+ fn the_final_gate_is_main_py_and_nothing_else_counts() {+ // The gate that has to hold before "installed successfully!" is said+ // and before the path is written into config.json. A directory with a+ // venv, a .git and requirements.txt but no main.py is the P14 torso.+ let torso = dir_with(&[".git/", "requirements.txt", "venv/"]);+ assert!(!comfy_install_looks_finished(torso.path()));+ let real = dir_with(&[".git/", "main.py"]);+ assert!(comfy_install_looks_finished(real.path()));+ }++ }++ /// KF-28: der Doc-Kommentar über `check_install_disk_pressure` darf nur+ /// versprechen, was der Rumpf auch tut.+ ///+ /// Er versprach zwei Prüfungen — „<5 GB frei" UND „or its pending I/O queue+ /// suggests sustained 100% utilisation". Die zweite gab es nie; der Rumpf+ /// prüft `available_space()` und gibt danach `None` zurück. Die Überschrift+ /// des Blocks nennt sogar den Anlass (Bug #1, 100%-busy-drive), also genau+ /// den Fall, den die erfundene Hälfte abzufangen schien.+ ///+ /// Diese Wache liest den Quelltext und vergleicht die beiden Hälften+ /// miteinander, in BEIDE Richtungen: ein Versprechen ohne Prüfung ist rot,+ /// eine Prüfung ohne Versprechen ebenso. Wer die Queue-Prüfung eines Tages+ /// wirklich baut, wird hier daran erinnert, den Kommentar mitzunehmen —+ /// und wer nur den Kommentar aufhübscht, kommt nicht durch.+ #[cfg(test)]+ mod disk_pressure_doc_matches_body {+ /// Die eigene Quelle. `include_str!` statt eines Laufzeit-Pfades, damit+ /// der Test nicht davon abhängt, aus welchem Verzeichnis `cargo test`+ /// gestartet wurde.+ const SOURCE: &str = include_str!("comfy_install.rs");++ const SIGNATURE: &str = "fn check_install_disk_pressure";++ /// Die `///`-Zeilen unmittelbar über der Signatur.+ fn doc_comment() -> String {+ let lines: Vec<&str> = SOURCE.lines().collect();+ let at = lines+ .iter()+ .position(|l| l.contains(SIGNATURE) && !l.trim_start().starts_with("//"))+ .expect("check_install_disk_pressure steht noch in dieser Datei");+ let mut doc: Vec<&str> = Vec::new();+ for line in lines[..at].iter().rev() {+ let t = line.trim_start();+ if !t.starts_with("///") {+ break;+ }+ doc.push(t.trim_start_matches("///").trim());+ }+ doc.reverse();+ doc.join(" ").to_lowercase()+ }++ /// Der Rumpf: ab der Signatur bis zur schließenden Klammer in Spalte 0.+ fn body() -> String {+ let lines: Vec<&str> = SOURCE.lines().collect();+ let at = lines+ .iter()+ .position(|l| l.contains(SIGNATURE) && !l.trim_start().starts_with("//"))+ .expect("check_install_disk_pressure steht noch in dieser Datei");+ let end = lines[at..]+ .iter()+ .position(|l| *l == "}")+ .expect("die Funktion wird in Spalte 0 geschlossen");+ lines[at..=at + end].join("\n")+ }++ /// Sagt der Kommentar eine Warteschlangen- oder Auslastungsprüfung zu?+ fn doc_promises_queue(doc: &str) -> bool {+ ["i/o queue", "queue", "utilisation", "utilization", "busy"]+ .iter()+ .any(|w| doc.contains(w))+ }++ /// Steht im Rumpf irgendetwas, das eine solche Prüfung sein könnte?+ /// `sysinfo`-0.33 kennt dafür nur `Disk::usage()` → `DiskUsage`, und das+ /// sind Byte-Zähler seit dem letzten Refresh, keine Warteschlangenlänge.+ fn body_probes_queue(body: &str) -> bool {+ ["usage()", "DiskUsage", "read_bytes", "written_bytes"]+ .iter()+ .any(|w| body.contains(w))+ }++ #[test]+ fn the_comment_promises_exactly_what_the_body_checks() {+ let doc = doc_comment();+ let body = body();++ // Der Teil, der wahr ist und wahr bleiben soll.+ assert!(+ body.contains("available_space()"),+ "der Rumpf prüft den freien Platz nicht mehr — dann stimmt auch \+ der erste Satz des Kommentars nicht mehr"+ );+ assert!(+ doc.contains("free space") || doc.contains("5 gb"),+ "der Kommentar sagt den freien Platz nicht mehr an, den der Rumpf prüft"+ );++ // Und die eigentliche Aussage.+ assert_eq!(+ doc_promises_queue(&doc),+ body_probes_queue(&body),+ "Kommentar und Rumpf sind auseinander: der Kommentar {} von einer \+ Warteschlangen-/Auslastungsprüfung, der Rumpf {}. Beide Hälften \+ gehören zusammen geändert — und das „warum nicht\" steht im \+ Blockkommentar über der Funktion, nicht im Doc-Kommentar, damit \+ eine Absage nicht wie eine Zusage aussieht.\n\n\+ Kommentar:\n{doc}\n",+ if doc_promises_queue(&doc) { "spricht" } else { "spricht NICHT" },+ if body_probes_queue(&body) { "enthält eine" } else { "enthält KEINE" },+ );+ }+ }diff --cc src-tauri/src/commands/install/comfy_job.rsindex 00000000,3bc03f37..afe69659mode 000000,100644..100644--- a/src-tauri/src/commands/install/comfy_job.rs+++ b/src-tauri/src/commands/install/comfy_job.rs@@@ -1,0 -1,239 +1,348 @@@+ //! Wer gerade an ComfyUI arbeiten darf — und wie die Oberfläche davon erfährt.+ //!+ //! Drei Befehle greifen auf dasselbe ComfyUI-Verzeichnis zu: Installation,+ //! Reparatur, Update. Sie teilen sich zwei Dinge, und beide liegen hier.+ //!+ //! Das erste ist der BESITZ. Bis 2.6.8 bewachte sich jeder der drei selbst,+ //! indem er die Statuszeichenkette verglich — und zwar uneinheitlich, sodass+ //! während des Clones (`"downloading"`) die Reparatur durchkam und das venv+ //! unter einer laufenden Installation löschte. Eine Statuszeichenkette kann+ //! "besetzt" nicht ausdrücken, weil sie zugleich der Fortschrittskanal der+ //! Oberfläche ist. Also bekommt der Besitz ein eigenes Schloss.+ //!+ //! Das zweite ist der KANAL selbst: `install_comfyui_status` liest den+ //! Statusschlitz, den alle drei beschreiben, und `cancel_comfyui_install`+ //! setzt das Abbruchmerker-Flag, das alle drei in ihren Warteschleifen+ //! abfragen. Beide gehören keinem der drei Aufträge allein — sie sind die+ //! Bedienfläche über dem, was gerade läuft.++ use std::sync::atomic::Ordering;+ use std::sync::{Arc, Mutex};++ use tauri::{Manager, State};++ use crate::state::AppState;++ // ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.+ // The State borrow cannot cross into the blocking pool, so the handle is+ // re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).+ #[tauri::command]+ pub async fn cancel_comfyui_install(app: tauri::AppHandle) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || {+ let state = app.state::<AppState>();+ cancel_comfyui_install_blocking(&state)+ })+ .await+ .map_err(|e| format!("cancel_comfyui_install task: {e}"))?+ }++ fn cancel_comfyui_install_blocking(state: &AppState) -> Result<serde_json::Value, String> {+ // OI-7: the flag is still what cancel uses, deliberately. It is scoped to+ // the ComfyUI install — the poll loops that watch it now take the child's+ // whole TREE down (see `pip_install_streaming_with_retry_cancellable` and+ // the clone loop), which is what was missing, and they notice within+ // ~200 ms. `kill_installer_children` is NOT called here: the registry it+ // walks also holds the pip runs of the whisper, Piper, custom-node and+ // trainer installers, and "Cancel ComfyUI install" must not take those+ // with it. That registry's kill belongs to shutdown, where killing+ // everything is the correct answer.+ state.comfyui_install_cancel.store(true, Ordering::SeqCst);+ if let Ok(mut s) = state.install_status.lock() {+ // Mark as cancelling immediately so the UI can switch to a+ // "Cancelling…" indicator even before the spawn loop notices.+ if s.status == "installing" || s.status == "downloading" {+ s.status = "cancelling".to_string();- s.logs.push("Cancellation requested — waiting for active subprocess to exit…".to_string());++ s.logs.push("Cancellation requested, waiting for the active subprocess to exit...".to_string());+ }+ }+ Ok(serde_json::json!({"status": "cancelling"}))+ }++ // ── OI-5: one job per runtime, held by a lock and not by a string ───────────++ /// The three commands that own ComfyUI's install directory: `install_comfyui`,+ /// `repair_comfyui_env`, `update_comfyui`.+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]+ pub(crate) enum ComfyJob {+ Install,+ Repair,+ Update,+ }++ impl ComfyJob {+ /// What to call this job in a sentence aimed at the user.+ pub(crate) fn label(self) -> &'static str {+ match self {+ ComfyJob::Install => "a ComfyUI installation",+ ComfyJob::Repair => "a ComfyUI environment repair",+ ComfyJob::Update => "a ComfyUI update",+ }+ }+ }++ /// Mutual exclusion for those three commands.+ ///+ /// They all narrate into ONE `install_status` slot and all write the same+ /// directory, and until 2.6.8 each guarded itself by comparing that slot's+ /// status string — inconsistently: install and repair refused only on+ /// `"installing"`, update refused on `"installing"` or `"downloading"`. The+ /// installer sets `"downloading"` for the whole git clone, so during a clone+ /// the repair's guard was open: it would delete the venv out from under a+ /// running install, both would report success over a half-built environment,+ /// and their log lines would interleave in the one panel the user is watching.+ ///+ /// A status string cannot express "busy" because the status is also the UI's+ /// progress channel — it changes for reasons that have nothing to do with+ /// ownership. So ownership gets its own slot and a real lock: `Some(job)`+ /// means that job owns the runtime until its guard drops, which happens when+ /// its worker thread ends, however it ends, including a panic.+ #[derive(Clone, Default)]+ pub(crate) struct ComfyJobSlot {+ current: Arc<Mutex<Option<ComfyJob>>>,+ }++ /// Ownership of the ComfyUI runtime. Dropping it releases the runtime, so it+ /// is moved into the worker thread and lives exactly as long as the job.+ #[derive(Debug)]+ pub(crate) struct ComfyJobGuard {+ current: Arc<Mutex<Option<ComfyJob>>>,+ }++ impl Drop for ComfyJobGuard {+ fn drop(&mut self) {+ // A poisoned mutex must not wedge the runtime for the rest of the+ // session, and a panic inside Drop during an unwind aborts the+ // process — so recover the guard rather than unwrapping it.+ let mut g = self.current.lock().unwrap_or_else(|e| e.into_inner());+ *g = None;+ }+ }++ impl ComfyJobSlot {+ /// Take the runtime for `job`, or report which job already holds it.+ pub(crate) fn try_acquire(&self, job: ComfyJob) -> Result<ComfyJobGuard, ComfyJob> {+ let mut g = self.current.lock().unwrap_or_else(|e| e.into_inner());+ match *g {+ Some(running) => Err(running),+ None => {+ *g = Some(job);+ Ok(ComfyJobGuard { current: self.current.clone() })+ }+ }+ }++ /// Which job owns the runtime right now, if any. Used by the tests to+ /// assert the guard releases; production code only ever needs `try_acquire`.+ #[allow(dead_code)]+ pub(crate) fn current(&self) -> Option<ComfyJob> {+ *self.current.lock().unwrap_or_else(|e| e.into_inner())+ }+ }++ /// The process-wide slot. There is exactly one ComfyUI runtime per running+ /// app, so there is exactly one of these; the type stays instantiable so the+ /// tests exercise their own instead of racing on this one.+ pub(super) static COMFY_JOB: once_cell::sync::Lazy<ComfyJobSlot> =+ once_cell::sync::Lazy::new(ComfyJobSlot::default);++ /// Refusal text for a job that arrived while another one owns the runtime.+ ///+ /// Returned as an `Err`, which matters for the self-healing path: the Create+ /// tab fires `repair_comfyui_env` and then polls `install_comfyui_status`+ /// until it reads `"complete"`. An `Ok` here would let it read the OTHER+ /// job's completion as "environment repaired" and hand the user a repair that+ /// never happened.+ pub(crate) fn comfy_job_busy_message(wanted: ComfyJob, running: ComfyJob) -> String {+ format!(+ "Cannot start {} while {} is running — they share one ComfyUI folder and would \+ corrupt each other's environment. Wait for the running job to finish (its \+ progress is in the same panel), then retry.",+ wanted.label(),+ running.label()+ )+ }++ #[tauri::command]+ pub fn install_comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.install_status.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,++ // Empty for every run that has nothing to add. A finished run that had++ // to skip the ComfyUI requirements.txt puts its one closing line here,++ // because the log itself is dropped the moment the panel goes idle.++ "notice": install.notice,++ "notice_kind": install.notice_kind,+ "download_progress": install.download_progress,+ "download_total": install.download_total,+ "download_speed": install.download_speed,+ }))+ }+++++++/// The live log line that names the fallback while it happens.++pub(crate) fn requirements_fallback_log(folder: &str, reason: &str) -> String {++ format!(++ "requirements.txt in {} could not be used ({}), installing LU's own package list instead.",++ folder, reason++ )++}++++/// The line every finished run leaves behind.++///++/// David, 03.09.: a run that worked has to say so. The cancel already had a++/// closing sentence and the success had none, so the abort was better labelled++/// than the success (A13 Befund 1a), and three full repairs of six to eight++/// minutes each ended with the card simply vanishing. The requirements hint is++/// appended rather than substituted: the run did finish, and the user needs++/// both halves of that.++pub(crate) fn finished_notice(++ done: &str,++ fallback: Option<&(String, &'static str)>,++) -> (String, &'static str) {++ match fallback {++ Some((folder, reason)) => (++ format!("{} {}", done, requirements_fallback_notice(folder, reason)),++ "warn",++ ),++ None => (done.to_string(), "ok"),++ }++}++++/// The half sentence about a requirements.txt the run had to pass over. Without++/// it the panel goes back to idle and every word about the skipped file scrolls++/// away with the log.++pub(crate) fn requirements_fallback_notice(folder: &str, reason: &str) -> String {++ format!(++ "The requirements.txt in {} could not be used ({}), so LU installed its own package \++ list instead. Anything that file asks for on top of that list is not installed.",++ folder, reason++ )++}+++ #[cfg(test)]+ mod tests {+ use super::*;++ use super::super::pip::{requirements_failure_reason, INVENTED_PACKAGE};++ // ── OI-5: install / repair / update share one runtime ─────────────────+ //+ // They guarded themselves by comparing the shared status string, and+ // inconsistently: install and repair refused only on "installing", update+ // also on "downloading". The installer sets "downloading" for the whole+ // git clone, so a repair started during a clone walked straight past the+ // guard and deleted the venv under a running install.+ //+ // The tests drive the lock itself. NOT covered: that a real concurrent+ // install and repair now interleave correctly — that needs two real+ // 2 GB installs.++ #[test]+ fn a_second_job_cannot_take_a_runtime_that_is_already_owned() {+ let slot = ComfyJobSlot::default();+ let held = slot.try_acquire(ComfyJob::Install).expect("free runtime");+ assert_eq!(slot.current(), Some(ComfyJob::Install));+ // This is the exact sequence that used to corrupt the venv: a repair+ // arriving while the installer is cloning.+ assert_eq!(slot.try_acquire(ComfyJob::Repair).err(), Some(ComfyJob::Install));+ assert_eq!(slot.try_acquire(ComfyJob::Update).err(), Some(ComfyJob::Install));+ drop(held);+ assert_eq!(slot.current(), None);+ assert!(slot.try_acquire(ComfyJob::Repair).is_ok());+ }++ #[test]+ fn the_runtime_comes_back_when_the_job_thread_panics() {+ // Guards are moved into worker threads. A thread that dies must not+ // leave ComfyUI locked for the rest of the session.+ let slot = ComfyJobSlot::default();+ let guard = slot.try_acquire(ComfyJob::Install).unwrap();+ let handle = std::thread::spawn(move || {+ let _g = guard;+ panic!("pip exploded");+ });+ assert!(handle.join().is_err());+ assert_eq!(slot.current(), None, "a panicking job left the runtime locked");+ }++ #[test]+ fn the_same_job_twice_is_told_it_is_already_running() {+ // Double-clicking Install is idempotent, not an error.+ let slot = ComfyJobSlot::default();+ let _held = slot.try_acquire(ComfyJob::Install).unwrap();+ assert_eq!(slot.try_acquire(ComfyJob::Install).err(), Some(ComfyJob::Install));+ }++ #[test]+ fn the_busy_message_names_both_jobs_and_says_why() {+ // This text is what the self-healing path surfaces instead of+ // silently reporting a repair that never ran.+ let msg = comfy_job_busy_message(ComfyJob::Repair, ComfyJob::Install);+ assert!(msg.contains("repair"), "{msg}");+ assert!(msg.contains("installation"), "{msg}");+ assert!(msg.to_lowercase().contains("corrupt"), "{msg}");+ }+++++ #[test]++ fn the_closing_line_says_what_is_missing_afterwards() {++ let notice = requirements_fallback_notice(++ "C:\\Users\\ddrob\\ComfyUI",++ requirements_failure_reason(INVENTED_PACKAGE),++ );++ assert!(notice.contains("C:\\Users\\ddrob\\ComfyUI"), "got: {notice}");++ assert!(notice.contains("LU installed its own package list instead"), "got: {notice}");++ // The half the report asked for: the user has to learn that ComfyUI is++ // now short of whatever that file wanted.++ assert!(notice.contains("is not installed"), "got: {notice}");++ }++++++ /// Negative control on the state itself: nothing is carried over from a++ /// run that never happened.++ #[test]++ fn a_fresh_install_state_carries_no_closing_line() {++ let fresh = crate::state::InstallState::default();++ assert!(fresh.notice.is_empty());++ assert!(fresh.notice_kind.is_empty());++ let json = serde_json::to_value(&fresh).expect("serialises");++ assert_eq!(json["notice"], serde_json::json!(""));++ assert_eq!(json["notice_kind"], serde_json::json!(""));++ }++++ /// David, 03.09.: a run that worked says so, every time. And it does not++ /// say it in the colour of a warning (A15 review).++ #[test]++ fn a_run_that_worked_leaves_a_closing_line_of_its_own() {++ for done in [++ "Install finished. ComfyUI is ready to start.",++ "Repair finished. ComfyUI is ready.",++ "Update finished. Restart ComfyUI to load the new nodes.",++ ] {++ let (line, kind) = finished_notice(done, None);++ assert_eq!(line, done);++ assert_eq!(kind, "ok");++ }++ }++++ /// And a run that had to skip the requirements.txt says both halves, in++ /// that order: it finished, and here is what it could not use. That one is++ /// a warning.++ #[test]++ fn a_finished_run_that_skipped_the_file_says_both_halves() {++ let fallback = (++ "C:\\Users\\ddrob\\ComfyUI".to_string(),++ requirements_failure_reason(INVENTED_PACKAGE),++ );++ let (line, kind) = finished_notice("Repair finished. ComfyUI is ready.", Some(&fallback));++ assert!(line.starts_with("Repair finished. ComfyUI is ready. "), "got: {line}");++ assert!(line.contains("could not be used"), "got: {line}");++ assert!(line.contains("C:\\Users\\ddrob\\ComfyUI"), "got: {line}");++ // Negative control on the substitution: the success half is not++ // replaced by the warning, which is what a run that finished deserves.++ assert!(line.contains("Repair finished"), "got: {line}");++ assert_eq!(kind, "warn");++ }+++ }diff --cc src-tauri/src/commands/install/comfy_repair.rsindex 00000000,fab28af7..e5238bcdmode 000000,100644..100644--- a/src-tauri/src/commands/install/comfy_repair.rs+++ b/src-tauri/src/commands/install/comfy_repair.rs@@@ -1,0 -1,473 +1,701 @@@+ //! Die zwei Eingriffe an einer ComfyUI, die schon da ist.+ //!+ //! Der geteilte Zustand ist eine BESTEHENDE Installation — beide Befehle+ //! fangen dort an, wo `comfy_install` aufhört, und beide müssen sie erst+ //! finden, bevor sie etwas anfassen dürfen. Was sie unterscheidet, ist die+ //! Hälfte, die sie ersetzen: die Reparatur wirft das venv weg und baut es+ //! neu, das Update holt den Kern nach und lässt das venv stehen.+ //!+ //! Sie stehen zusammen, weil ihre Fehlerfälle dieselben sind und in beiden+ //! Richtungen aufeinander zeigen. Beide brechen ab, wenn kein brauchbarer+ //! Python da ist; beide behandeln fehlgeschlagene optionale Abhängigkeiten+ //! als Warnung und nicht als Abbruch, weil ComfyUI danach trotzdem startet;+ //! und beide erzählen in denselben Statusschlitz, den `install_comfyui_status`+ //! ausliest. Wer die eine Regel ändert, muss die andere danebenlegen.+ //!+ //! Die Reparatur trägt zusätzlich die Pflicht, die ihr Auslöser ihr+ //! aufgibt: sie läuft automatisch nach einem ComfyUI-Absturz, und sie+ //! löscht dabei ein venv, in dem faster-whisper und Piper mitwohnen. Was sie+ //! wegnimmt, muss sie am Ende wieder hinstellen — und es sagen, sonst liest+ //! der Nutzer nur "die Sprachausgabe ist plötzlich weg".++ use std::path::PathBuf;+ use std::process::{Command, Stdio};+ use std::sync::atomic::Ordering;++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::State;+ use tracing::{error, info};++ use crate::state::AppState;++use crate::os_error;++use std::path::Path;++use super::comfy_job::{finished_notice, requirements_fallback_log};++use super::env_check::verify_and_heal_environment;++use super::pip::{pip_install_streaming_with_retry_raw, requirements_failure_reason_for};++use super::venv::venv_removal_error;++ use super::comfy_job::{ComfyJob, COMFY_JOB};+ use super::comfy_job::comfy_job_busy_message;+ use super::pip::pip_install_streaming_with_retry_cancellable;+ use super::torch::plan_pytorch_install;+ use super::venv::{create_comfyui_venv, detect_venv_passengers};+ #[cfg(target_os = "windows")]+ use super::git::{windows_git_install_hint, windows_git_probe, WindowsGitState};+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ /// GH #98 (joelnewswanger, 2026-08-14): ComfyUI installed once, then died at+ /// import time on every start. His torch lived in the SHARED system Python's+ /// site-packages, where anything the user ever pip-installed can break us,+ /// and clicking install again changed nothing because pip saw every package+ /// as "already satisfied". kryptoxide's night (same issue) was the same trap+ /// from the other side: a stray `comfy 0.0.1` on the system Python shadowed+ /// ComfyUI's own package.+ ///+ /// The repair builds what those installs never had: a fresh venv inside the+ /// ComfyUI folder, with PyTorch and the requirements installed into it. The+ /// launcher already prefers ComfyUI/venv over the system Python, so the next+ /// start picks it up with no further wiring. The system Python, models,+ /// outputs and custom nodes are left alone. Progress goes through the same+ /// install_status slot, so install_comfyui_status polling just works.+ #[tauri::command]+ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ if !crate::commands::process::comfy_supported_here() {+ return Err(crate::commands::process::MACOS_COMFY_REFUSAL.to_string());+ }+ // OI-5: acquired before any of the checks below, because every one of them+ // reads state a concurrent install is actively changing. Dropped again on+ // each early return.+ let job_guard = match COMFY_JOB.try_acquire(ComfyJob::Repair) {+ Ok(g) => g,+ Err(ComfyJob::Repair) => return Ok(serde_json::json!({"status": "already_installing"})),+ Err(running) => return Err(comfy_job_busy_message(ComfyJob::Repair, running)),+ };+ let comfy_dir = {+ let p = state.comfy_path.lock().unwrap().clone();+ p.or_else(crate::commands::process::find_comfyui_path)+ };+ let Some(comfy_dir) = comfy_dir else {+ return Err(+ "ComfyUI is not installed, so there is no environment to repair. Use Install ComfyUI instead."+ .to_string(),+ );+ };+ let comfy_dir = PathBuf::from(comfy_dir);+ // Portable installs bring their own python_embeded and the launcher+ // prefers it over any venv, so a rebuilt venv would never be used.+ let embeded_here = comfy_dir.join("python_embeded").join("python.exe").exists();+ let embeded_beside = comfy_dir+ .parent()+ .map(|p| p.join("python_embeded").join("python.exe").exists())+ .unwrap_or(false);+ if embeded_here || embeded_beside {+ return Err(+ "This is a portable ComfyUI with its own bundled Python. Re-extract the portable \+ package to repair it; the app cannot rebuild that environment."+ .to_string(),+ );+ }+ let python_bin = state.python_bin.lock().unwrap().clone();+ if python_bin.is_empty() || !crate::python::is_real_python(&python_bin) {+ return Err(+ "no_python: Python must be installed before the environment can be rebuilt. Call install_python first."+ .to_string(),+ );+ }+ {+ let mut install = state.install_status.lock().unwrap();+ install.status = "installing".to_string();+ install.logs.clear();++ install.notice.clear();++ install.notice_kind.clear();+ install.logs.push("Repairing the ComfyUI environment...".to_string());+ }+ info!("comfyui env repair start");+ // A tracked child would hold venv files open on Windows; it is dead or+ // dying anyway (the repair only runs after a startup crash).+ {+ let mut proc = state.comfy_process.lock().unwrap();+ if let Some(mut child) = proc.take() {+ let _ = child.kill();+ let _ = child.wait();+ }+ }+ state.comfyui_install_cancel.store(false, Ordering::SeqCst);+ let cancel_flag = state.comfyui_install_cancel.clone();+ let install_status = state.install_status.clone();+ // OI-3: the whisper server runs FROM this venv's Python. On Windows a+ // running interpreter holds its own files open, so leaving it up makes+ // `remove_dir_all` fail and the repair dies at step one with "close+ // anything using it and retry" — naming nothing the user can close.+ // Stopping it is also free: `ensure_whisper_running` brings it back on+ // the next voice input, then against the rebuilt venv.+ let whisper = state.whisper.clone();++ std::thread::spawn(move || {+ let _job_guard = job_guard;+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_status.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };+++ // Set when `pip install -r requirements.txt` failed and the run carried++ // on with LU's own package list. Folder plus reason, so the live log++ // line and the line the finished run leaves behind agree (A15).++ let mut requirements_fallback: Option<(String, &'static str)> = None;++++ // A16 (A15-2): before anything is deleted and before anything is++ // downloaded. A folder with no requirements.txt is not a ComfyUI++ // checkout, and nothing later in this run can change that, so there is++ // no reason to spend three minutes and two gigabytes finding out, nor++ // to throw away a venv for a rebuild that cannot finish.++ if let Err(msg) = repair_precheck(&comfy_dir) {++ update("error", &msg);++ return;++ }+++ // A broken venv must go entirely: pip inside it would report the+ // damaged packages as already satisfied, which is the exact dead end+ // this command exists to break.+ let venv_dir = comfy_dir.join("venv");+ // OI-3: faster-whisper and Piper live in this venv too. Take stock+ // BEFORE the delete, because afterwards there is nothing left to read.+ let passengers = detect_venv_passengers(&venv_dir);+ if !passengers.is_empty() {+ let names: Vec<&str> = passengers.iter().map(|p| p.label).collect();+ // The connection has to be in the log the user is looking at. Its+ // absence is what turned this into "Voice just stopped": two+ // unrelated-looking features died during a ComfyUI repair the+ // Create tab started on its own.+ info!(passengers = ?names, "comfyui repair will rebuild venv passengers");+ update(+ "installing",+ &format!(+ "This venv also holds {}. Rebuilding it removes them, so LU will \+ reinstall them at the end of the repair — do not close the app until \+ that step is done.",+ names.join(" and ")+ ),+ );+ }+ if venv_dir.exists() {+ // Before the delete: nothing of ours may still be running out of+ // this venv (see the `whisper` clone above).+ if let Ok(mut w) = whisper.lock() {+ if w.is_running() {+ update(+ "installing",+ "Stopping the voice-input server, which runs from this venv. It \+ restarts by itself the next time you use voice input.",+ );+ w.stop();+ }+ }+ update(+ "installing",+ "Removing the old venv (models, outputs and custom nodes stay untouched)...",+ );+ if let Err(e) = std::fs::remove_dir_all(&venv_dir) {- update(- "error",- &format!(- "Could not remove the old venv at {}: {}. Close anything using it and retry.",- venv_dir.display(),- e- ),- );++ update("error", &venv_removal_error(&venv_dir, &e));+ return;+ }+ }++ update(+ "installing",- "Step 1/3: Creating a fresh isolated venv inside the ComfyUI folder...",++ "Step 1/4: Creating a fresh isolated venv inside the ComfyUI folder...",+ );+ let venv_py = match create_comfyui_venv(&comfy_dir, &python_bin) {+ Ok(p) => p.to_string_lossy().to_string(),+ Err(e) => {+ update("error", &format!("venv creation failed.\n\n{}", e));+ return;+ }+ };+ if cancel_flag.load(Ordering::SeqCst) {+ update("cancelled", "Repair cancelled.");+ return;+ }++ let (torch_args, gpu_info) = plan_pytorch_install();- update("installing", &format!("Step 2/3: {}", gpu_info));++ update("installing", &format!("Step 2/4: {}", gpu_info));+ update(+ "installing",+ "Downloading PyTorch into the fresh venv (~2 GB). Live pip output below.",+ );+ let refs: Vec<&str> = torch_args.iter().map(|s| s.as_str()).collect();+ match pip_install_streaming_with_retry_cancellable(&refs, &venv_py, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => update("installing", "PyTorch installed."),+ Err(d) if d == "cancelled" => {+ update("cancelled", "Repair cancelled during the PyTorch download.");+ return;+ }+ Err(d) => {+ update("error", &format!("PyTorch installation failed.\n\n{}", d));+ return;+ }+ }++ let reqs = comfy_dir.join("requirements.txt");- if reqs.exists() {++ // Checked once at the top already. Kept as a guard for the file being++ // renamed or deleted while the rebuild was running, which is a real++ // few minutes on a slow line.++ if !reqs.exists() {++ update("error", &missing_requirements_for_repair(&comfy_dir));++ return;++ }++ {+ update(+ "installing",- "Step 3/3: Installing ComfyUI dependencies into the venv...",++ "Step 3/4: Installing ComfyUI dependencies into the venv...",+ );+ let reqs_str = reqs.to_string_lossy().to_string();+ let req_args = vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "-r", reqs_str.as_str(),+ ];- match pip_install_streaming_with_retry_cancellable(&req_args, &venv_py, 3, &install_status, Some(&cancel_flag)) {++ match pip_install_streaming_with_retry_raw(&req_args, &venv_py, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => update("installing", "Dependencies installed."),- Err(d) if d == "cancelled" => {++ Err(f) if f.diagnosis == "cancelled" => {+ update("cancelled", "Repair cancelled during the requirements install.");+ return;+ }- Err(d) => update(- "installing",- &format!("Some optional dependencies had warnings (non-critical): {}", d),- ),++ Err(f) => {++ let reason = requirements_failure_reason_for(&f);++ let folder = comfy_dir.display().to_string();++ requirements_fallback = Some((folder.clone(), reason));++ update("installing", &requirements_fallback_log(&folder, reason));++ update(++ "installing",++ &format!(++ "Not every dependency installed. Checking what is really missing.\n\n{}",++ f.diagnosis++ ),++ );++ }+ }+ }++ // OI-3: put the passengers back. Failures here are reported but do not+ // fail the repair — ComfyUI itself is rebuilt at this point, and+ // burying a working ComfyUI under a Piper wheel error would trade one+ // silent loss for another. What must never happen again is the repair+ // finishing without saying what happened to Voice.+ let mut lost: Vec<&str> = Vec::new();+ for p in &passengers {+ update(+ "installing",+ &format!("Reinstalling {} into the fresh venv...", p.label),+ );+ let args = vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ p.pip_name,+ ];+ match pip_install_streaming_with_retry_cancellable(&args, &venv_py, 3, &install_status, Some(&cancel_flag)) {+ Ok(()) => update("installing", &format!("{} is back.", p.label)),+ Err(d) if d == "cancelled" => {+ update(+ "cancelled",+ &format!(+ "Repair cancelled while reinstalling {}. It is NOT installed — \+ reinstall it from Settings.",+ p.label+ ),+ );+ return;+ }+ Err(d) => {+ error!(package = p.pip_name, error = %d, "venv passenger reinstall failed after comfyui repair");+ lost.push(p.label);+ update(+ "installing",+ &format!("Could not reinstall {}: {}", p.label, d),+ );+ }+ }+ }+- let closing = if lost.is_empty() {- "Environment repaired. ComfyUI now runs from its own venv; start it again.".to_string()++ // A3: this is the step the button was missing. Two of the five++ // reporters pressed Repair environment and nothing changed, because a++ // rebuild that trusts pip's exit code rebuilds the same hole.++ update("installing", "Step 4/4: Checking that the environment really starts...");++ match verify_and_heal_environment(&venv_py, &reqs, &install_status, Some(&cancel_flag)) {++ Ok(()) => {}++ Err(e) if e == "cancelled" => {++ update("cancelled", "Repair cancelled during the environment check.");++ return;++ }++ Err(e) => {++ error!("comfyui env repair left an environment that does not import");++ update("error", &format!("The environment was rebuilt, but it still does not start.\n\n{}", e));++ return;++ }++ }++++ let (notice_text, closing) = if lost.is_empty() {++ (++ "Repair finished. ComfyUI is ready.".to_string(),++ "Environment repaired. ComfyUI now runs from its own venv; start it again."++ .to_string(),++ )+ } else {- format!(- "ComfyUI's environment is repaired and can be started again, but {} could not \- be reinstalled into the new venv and {} not available until you install {} \- again from Settings.",- lost.join(" and "),- if lost.len() == 1 { "is" } else { "are" },- if lost.len() == 1 { "it" } else { "them" },++ let names = lost.join(" and ");++ (++ format!("Repair finished, but {} could not be reinstalled.", names),++ format!(++ "ComfyUI's environment is repaired and can be started again, but {} could not \++ be reinstalled into the new venv and {} not available until you install {} \++ again from Settings.",++ names,++ if lost.len() == 1 { "is" } else { "are" },++ if lost.len() == 1 { "it" } else { "them" },++ ),+ )+ };++ if let Ok(mut s) = install_status.lock() {++ let (line, kind) = finished_notice(¬ice_text, requirements_fallback.as_ref());++ s.notice = line;++ s.notice_kind = kind.to_string();++ }+ update("complete", &closing);+ });++ Ok(serde_json::json!({"status": "installing"}))+ }++ /// Update an existing ComfyUI install in place: `git pull --ff-only` plus a+ /// venv-aware `pip install -r requirements.txt`. The 2.5.8 local Create lanes+ /// (music / talking character / extend / motion) need node classes that ship+ /// with current ComfyUI cores, and the UI gates on node PRESENCE — when the+ /// nodes are missing this command is the one-click "Update ComfyUI" path.+ /// Progress streams through the same `install_status` channel the installer+ /// uses, so the existing `install_comfyui_status` polling UI works unchanged.+ #[tauri::command]+ pub fn update_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ // OI-5: same lock as install and repair. This command's old guard was the+ // strictest of the three ("installing" OR "downloading"), which is exactly+ // why the inconsistency was invisible from here — it was the other two+ // that let a job in mid-clone.+ let job_guard = match COMFY_JOB.try_acquire(ComfyJob::Update) {+ Ok(g) => g,+ Err(ComfyJob::Update) => return Ok(serde_json::json!({"status": "already_installing"})),+ Err(running) => return Err(comfy_job_busy_message(ComfyJob::Update, running)),+ };+ {+ let mut install = state.install_status.lock().unwrap();+ install.status = "installing".to_string();+ install.logs.clear();++ install.notice.clear();++ install.notice_kind.clear();+ install.logs.push("Updating ComfyUI...".to_string());+ }++ info!("comfyui update start");++ let comfy_dir = {+ let p = state.comfy_path.lock().unwrap().clone();+ p.or_else(crate::commands::process::find_comfyui_path)+ .map(PathBuf::from)+ };+ let fail = |state: &State<'_, AppState>, msg: &str| -> Result<serde_json::Value, String> {+ let mut install = state.install_status.lock().unwrap();+ install.status = "error".to_string();+ install.logs.push(msg.to_string());+ error!("comfyui update aborted: {}", msg);+ Err(msg.to_string())+ };+ let Some(comfy_dir) = comfy_dir else {+ return fail(&state, "ComfyUI not found. Install ComfyUI first.");+ };+ if !comfy_dir.join(".git").exists() {+ // Portable / zip installs carry no git metadata — nothing to pull.+ return fail(+ &state,+ "This ComfyUI was not installed from git, so it can't be updated in place. \+ Update it with its own updater, or reinstall from Settings.",+ );+ }++ // Prefer the install's venv Python (same preference the launcher uses);+ // refuse without a usable interpreter — a pulled core with stale+ // requirements is worse than no update (frontend package pins move often).+ let python_bin = crate::python::resolve_comfyui_venv_python(&comfy_dir)+ .unwrap_or_else(|| state.python_bin.lock().unwrap().clone());+ if python_bin.is_empty() || !crate::python::is_real_python(&python_bin) {+ return fail(+ &state,+ "No usable Python found for this ComfyUI. Install Python first, then retry the update.",+ );+ }++ let install_status = state.install_status.clone();++ // The update runs through the same status slot, the same panel and the++ // same Cancel button as the install, so it gets the same flag. Reset++ // first, for the reason install_comfyui resets it (Bug #1): a previously++ // cancelled run would otherwise abort this one on the first poll.++ state.comfyui_install_cancel.store(false, Ordering::SeqCst);++ let cancel_flag = state.comfyui_install_cancel.clone();+ std::thread::spawn(move || {+ let _job_guard = job_guard;+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_status.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };+++ // Set when `pip install -r requirements.txt` failed and the run carried++ // on with LU's own package list. Folder plus reason, so the live log++ // line and the line the finished run leaves behind agree (A15).++ let mut requirements_fallback: Option<(String, &'static str)> = None;+++ #[cfg(target_os = "windows")]+ {+ let probe = windows_git_probe();+ if probe == WindowsGitState::Missing {+ update("error", &windows_git_install_hint(&probe).unwrap_or_default());+ return;+ }+ }+- update("installing", "Step 1/2: Pulling the latest ComfyUI...");++ update("installing", "Step 1/3: Pulling the latest ComfyUI...");+ let mut pull = Command::new("git");+ // --ff-only: a user-modified checkout must not silently merge; surface+ // the divergence honestly instead.+ pull.args(["pull", "--ff-only"])+ .current_dir(&comfy_dir)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ pull.creation_flags(CREATE_NO_WINDOW);+ match pull.output() {+ Ok(o) if o.status.success() => {+ let out = String::from_utf8_lossy(&o.stdout);+ let line = out.lines().last().unwrap_or("").trim().to_string();+ update(+ "installing",+ if line.is_empty() { "Repository updated." } else { &line },+ );+ }+ Ok(o) => {+ let stderr = String::from_utf8_lossy(&o.stderr);+ update(+ "error",+ &format!(+ "git pull failed. If you changed files inside the ComfyUI folder, \+ stash or revert them and retry.\n\n{}",+ stderr.trim(),+ ),+ );+ return;+ }+ Err(e) => {- update("error", &format!("Could not run git: {}", e));++ update("error", &format!("Could not run git: {}", os_error::english(&e)));+ return;+ }+ }++ update(+ "installing",- "Step 2/2: Updating Python dependencies (live pip output below)...",++ "Step 2/3: Updating Python dependencies (live pip output below)...",+ );+ let reqs = comfy_dir.join("requirements.txt");- if reqs.exists() {++ if !reqs.exists() {++ update(++ "error",++ &format!(++ "The folder {} has no requirements.txt after the pull, so its dependencies \++ cannot be updated. Reinstall ComfyUI from Settings.",++ comfy_dir.display()++ ),++ );++ return;++ }++ {+ let reqs_str = reqs.to_string_lossy().to_string();+ let req_args = vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "-r", reqs_str.as_str(),+ ];- match pip_install_streaming_with_retry_cancellable(++ match pip_install_streaming_with_retry_raw(+ &req_args,+ &python_bin,+ 3,+ &install_status,- None,++ Some(&cancel_flag),+ ) {+ Ok(()) => update("installing", "Dependencies updated."),- Err(diagnosis) => {- // Same stance as the installer's step 3: optional deps may- // fail while ComfyUI still starts — log, don't abort.- println!("[Update] Requirements warning: {}", diagnosis);++ Err(f) if f.diagnosis == "cancelled" => {++ update("cancelled", "Update cancelled during the requirements install.");++ return;++ }++ Err(f) => {++ println!("[Update] Requirements warning: {}", f.diagnosis);++ let reason = requirements_failure_reason_for(&f);++ let folder = comfy_dir.display().to_string();++ requirements_fallback = Some((folder.clone(), reason));++ update("installing", &requirements_fallback_log(&folder, reason));+ update(+ "installing",- "Some dependencies had warnings (non-critical, ComfyUI should still start).",++ &format!(++ "Not every dependency updated. Checking what is really missing.\n\n{}",++ f.diagnosis++ ),+ );+ }+ }+ }+++ // A pull that brings new requirements is the third way into A3: the++ // core moves on, one wheel does not land, and the update reports++ // finished over an environment that no longer imports.++ update("installing", "Step 3/3: Checking that the environment really starts...");++ if let Err(e) = verify_and_heal_environment(&python_bin, &reqs, &install_status, Some(&cancel_flag)) {++ if e == "cancelled" {++ update("cancelled", "Update cancelled during the environment check.");++ return;++ }++ error!("comfyui update left an environment that does not import");++ update("error", &format!("ComfyUI was updated, but its Python environment is not usable.\n\n{}", e));++ return;++ }+++ println!("[Update] ComfyUI update complete");++ if let Ok(mut s) = install_status.lock() {++ let (line, kind) = finished_notice(++ "Update finished. Restart ComfyUI to load the new nodes.",++ requirements_fallback.as_ref(),++ );++ s.notice = line;++ s.notice_kind = kind.to_string();++ }+ update(+ "complete",+ "ComfyUI updated. Restart ComfyUI to load the new nodes.",+ );+ });++ Ok(serde_json::json!({"status": "installing"}))+ }++++++/// What Repair says about a folder with no requirements.txt.++///++/// A16 (A15-2), Windows counter-check 02.09.: the sentence itself was right and++/// arrived after 181,6 seconds, because the file was only looked at when pip++/// was about to be pointed at it, which is after the venv has been deleted and++/// PyTorch has been downloaded into the new one. Three minutes and two++/// gigabytes to learn that the folder was never a ComfyUI checkout, and a++/// half-built environment left behind for it. The check runs before any of++/// that now, and the wording is here so the early check and the late one, kept++/// as a guard against the file going away mid run, cannot drift apart.++fn missing_requirements_for_repair(dir: &Path) -> String {++ format!(++ "The folder {} has no requirements.txt, so it is not a complete ComfyUI \++ checkout and the environment cannot be rebuilt from it. Rename or delete \++ that folder and install ComfyUI again.",++ dir.display()++ )++}++++/// Everything Repair can rule out before it destroys or downloads anything.++///++/// One function so the order is not a matter of where a call happens to sit:++/// this is called first in the run, and what it refuses costs the user++/// nothing.++fn repair_precheck(comfy_dir: &Path) -> Result<(), String> {++ if !comfy_dir.join("requirements.txt").exists() {++ return Err(missing_requirements_for_repair(comfy_dir));++ }++ Ok(())++}++++#[cfg(test)]++mod tests {++ use super::*;++++ #[test]++ fn repair_refuses_a_folder_without_requirements_before_it_spends_anything() {++ // The counter-check renamed requirements.txt and pressed Repair. The++ // run deleted the venv, downloaded two gigabytes of PyTorch and then,++ // after 181,6 seconds, said the folder was never a ComfyUI checkout.++ let tmp = tempfile::tempdir().unwrap();++ let comfy = tmp.path().join("ComfyUI");++ std::fs::create_dir(&comfy).unwrap();++ std::fs::create_dir(comfy.join("venv")).unwrap();++++ let refused = repair_precheck(&comfy).expect_err("a folder with no requirements.txt was accepted");++++ assert!(refused.contains("requirements.txt"), "the file is not named: {refused}");++ assert!(refused.contains(&comfy.display().to_string()), "the folder is not named: {refused}");++ assert!(refused.contains("install ComfyUI again"), "no way out is offered: {refused}");++ // Nothing was touched on the way to that answer.++ assert!(comfy.join("venv").exists(), "the venv was removed by a run that could not finish");++ }++++ #[test]++ fn repair_lets_a_real_checkout_through() {++ // Negative control. Without it the check above would pass on a++ // precheck that refused every folder, which would kill Repair outright.++ let tmp = tempfile::tempdir().unwrap();++ let comfy = tmp.path().join("ComfyUI");++ std::fs::create_dir(&comfy).unwrap();++ std::fs::write(comfy.join("requirements.txt"), "torch\n").unwrap();++++ assert!(repair_precheck(&comfy).is_ok(), "a real ComfyUI checkout was refused");++ }++++ #[test]++ fn the_repair_precheck_really_runs_before_the_venv_and_the_download() {++ // The weaker proof, and labelled as such: the repair body is a thread++ // inside a Tauri command and cannot be driven from here, so the ORDER++ // is pinned by reading this file. It catches the check drifting back++ // down the function, which is exactly what the counter-check found.++ //++ // Every needle is assembled from two halves, and that is not cosmetic.++ // Written whole, each one would stand in THIS file as well, `find`++ // would return the position of the copy in this test body whenever the++ // real line was gone, and the `.expect` beside it could never fire. A++ // guard that cannot fail is not a guard. Split, the halves never form++ // a contiguous match in the source, so a missing line is a `None` and++ // the message next to it is the one the reader gets.++ let src = include_str!("comfy_repair.rs");++ let needle = |head: &str, tail: &str| format!("{head}{tail}");++ let call = src.find(&needle("if let Err(msg) = repair_prech", "eck(&comfy_dir) {"))++ .expect("Repair no longer prechecks at all");++ let venv = src.find(&needle("\"Removing the old venv (models, outputs", " and custom nodes stay untouched)...\","))++ .expect("the venv removal step is gone");++ let torch = src.find(&needle("\"Downloading PyTorch into the fresh venv", " (~2 GB). Live pip output below.\","))++ .expect("the PyTorch step is gone");++ assert!(call < venv, "the precheck runs after the venv is deleted");++ assert!(call < torch, "the precheck runs after the PyTorch download");++++ // And the guard on the guard: each needle occurs EXACTLY once in the++ // file. Two occurrences would mean this test body carries a copy of++ // the line it is looking for, which is how the three `.expect`s above++ // became unreachable in the first place.++ for (what, n) in [++ ("the precheck call", needle("if let Err(msg) = repair_prech", "eck(&comfy_dir) {")),++ ("the venv step", needle("\"Removing the old venv (models, outputs", " and custom nodes stay untouched)...\",")),++ ("the PyTorch step", needle("\"Downloading PyTorch into the fresh venv", " (~2 GB). Live pip output below.\",")),++ ] {++ assert_eq!(++ src.matches(&n).count(),++ 1,++ "{what}: the search string finds itself in this test, so its .expect can never fire",++ );++ }++ }++++}diff --cc src-tauri/src/commands/install/custom_nodes.rsindex 00000000,fc0e3efe..7fce0030mode 000000,100644..100644--- a/src-tauri/src/commands/install/custom_nodes.rs+++ b/src-tauri/src/commands/install/custom_nodes.rs@@@ -1,0 -1,419 +1,390 @@@+ //! Ein Node-Paket in ComfyUIs `custom_nodes/` bringen und lauffähig halten.+ //!+ //! Der geteilte Zustand ist ein einzelnes Verzeichnis unter `custom_nodes/`,+ //! das in drei Zuständen angetroffen werden kann: gar nicht da, als+ //! git-Checkout, oder als Rest eines abgebrochenen Versuchs. Alle Funktionen+ //! hier arbeiten an diesem einen Verzeichnis, und die Naht läuft genau darum+ //! herum.+ //!+ //! Aus #72 stammt die Regel, die das Modul zusammenhält: der Klon-Weg und der+ //! Aktualisierungs-Weg müssen BEIDE die `requirements.txt` einspielen. Solange+ //! nur der Klon das tat, konnte sich ein Paket, dessen Requirements einmal+ //! gescheitert waren, nie wieder erholen — ComfyUI meldete weiter IMPORT+ //! FAILED, und der Knoten tauchte nie auf. Deshalb ist+ //! `install_node_requirements` eine eigene Funktion und wird von beiden Wegen+ //! gerufen.+ //!-//! `is_permission_denied_pip_error` steht daneben, weil es dieselbe Stelle-//! rettet: eine python.org-Installation unter Program Files hat ein-//! Administrator-eigenes `site-packages`, und dort scheitert das erste Paket,-//! das ein NEUES Wheel zieht — während Pakete mit schon vorhandenen-//! Abhängigkeiten durchlaufen.++//! Warum die Rechte-Erkennung NICHT mehr hier steht: sie deutet eine++//! pip-Ausgabe, und das tut `pip`. Der Fall, den sie rettet, ist trotzdem++//! genau dieser hier — eine python.org-Installation unter Program Files hat++//! ein Administrator-eigenes `site-packages`, und dort scheitert das erste++//! Paket, das ein NEUES Wheel zieht, während Pakete mit schon vorhandenen++//! Abhängigkeiten durchlaufen. Deshalb ruft dieses Modul++//! `super::pip::is_permission_denied_pip_error` und deutet nichts selbst.++ use std::fs;+ use std::path::PathBuf;++use crate::python::python_command;++use super::pip::is_permission_denied_pip_error;+ use std::process::{Command, Stdio};++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::State;+ use tracing::{error, info};++ use crate::os_error;+ use crate::state::AppState;++ use super::pip::diagnose_pip_error;+ #[cfg(target_os = "windows")]+ use super::git::{windows_git_install_hint, windows_git_probe, WindowsGitState};+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ──────────────────────────────────────────────────────────────────────────────++ #[allow(non_snake_case)]+ #[tauri::command]+ pub async fn install_custom_node(+ state: State<'_, AppState>,+ repoUrl: String,+ nodeName: String,+ ) -> Result<serde_json::Value, String> {+ // Snapshot the state the blocking worker needs before spawning it: a Tauri+ // `State` (and the MutexGuard behind it) is not Send, so clone the values+ // out and move owned copies into the worker.+ let comfy_path = { state.comfy_path.lock().unwrap().clone() };+ let fallback_python = { state.python_bin.lock().unwrap().clone() };+ // Freeze fix (David 2026-07-04): the git clone + pip below are blocking. As+ // a plain sync #[command] they ran on the Tauri main thread and froze the+ // WebView2 window for the entire 30s-2min install with no feedback ("hängt+ // sich auf, keine Rückmeldung"). Run them on the blocking pool so the UI+ // stays responsive and the staged status messages actually paint — the JS+ // caller still awaits this command's result exactly as before.+ tauri::async_runtime::spawn_blocking(move || {+ install_custom_node_blocking(repoUrl, nodeName, comfy_path, &fallback_python)+ })+ .await+ .map_err(|e| format!("Custom node install task failed to run: {e}"))?+ }++ /// Blocking half of `install_custom_node`, run on the blocking pool. Holds all+ /// the ComfyUI-path resolution, git clone/pull healing (#72) and pip work so+ /// the async command above never stalls the UI thread.+ #[allow(non_snake_case)]+ fn install_custom_node_blocking(+ repoUrl: String,+ nodeName: String,+ comfy_path: Option<String>,+ fallback_python: &str,+ ) -> Result<serde_json::Value, String> {+ let repo_url = repoUrl;+ let node_name = nodeName;++ // Security review 2.5.7: this clones `repo_url` and joins `node_name` under+ // custom_nodes/. Every in-app caller passes a hardcoded registry entry, so+ // these are trusted today — but a single renderer foothold could call the+ // command with a hostile value, so validate defensively. Reject anything that+ // isn't a plain https:// URL: git's `ext::`/`file::`/`ssh` transports execute+ // commands, and a leading `-` would be parsed as a git flag. Reject any path+ // syntax in `node_name` (`/`, `\`, `..`, `:`, leading `-`/`.`) — an absolute+ // or `..` component makes `custom_nodes_dir.join(node_name)` escape the dir.+ if !repo_url.starts_with("https://")+ || repo_url.len() > 512+ || repo_url.contains(|c: char| c.is_whitespace() || c.is_control())+ {+ return Err("Refusing to install: repository URL must be a plain https:// URL.".to_string());+ }+ if node_name.is_empty()+ || node_name.len() > 128+ || node_name.contains('/')+ || node_name.contains('\\')+ || node_name.contains("..")+ || node_name.contains(':')+ || node_name.starts_with('-')+ || node_name.starts_with('.')+ {+ return Err("Refusing to install: invalid custom-node name.".to_string());+ }++ info!(node = %node_name, "custom node install start");++ let comfy_dir = match comfy_path {+ Some(p) => PathBuf::from(p),+ None => {+ // Try to find it+ match crate::commands::process::find_comfyui_path() {+ Some(p) => PathBuf::from(p),+ None => {+ error!(node = %node_name, "custom node install failed: comfyui not found");+ return Err("ComfyUI not found. Install ComfyUI first.".to_string());+ }+ }+ }+ };++ let custom_nodes_dir = comfy_dir.join("custom_nodes");+ let target_dir = custom_nodes_dir.join(&node_name);++ // Create custom_nodes dir if it doesn't exist+ if !custom_nodes_dir.exists() {+ fs::create_dir_all(&custom_nodes_dir)+ .map_err(|e| format!("Failed to create custom_nodes directory: {}", os_error::english(&e)))?;+ }++ // Bug N — same git probe as install_comfyui. Block on missing git, log+ // a soft hint when a non-native git is first on PATH.+ #[cfg(target_os = "windows")]+ {+ let probe = windows_git_probe();+ if probe == WindowsGitState::Missing {+ return Err(windows_git_install_hint(&probe).unwrap_or_default());+ }+ if probe == WindowsGitState::NonNative {+ if let Some(hint) = windows_git_install_hint(&probe) {+ println!("[Install] {}", hint);+ }+ }+ }++ // #72 (bob, discussion 72): three silent failure modes lived here.+ // 1. A leftover non-repo dir (aborted clone, manual unzip) made `git pull`+ // fail forever, and the failure came back as Ok(status="update_failed")+ // — the UI treated it as success, so the install dialog looped with no+ // error and video gen kept falling back to .webp.+ // 2. The exists/update path never installed requirements.txt, so a repo+ // whose requirements failed once could never heal (ComfyUI keeps+ // reporting IMPORT FAILED and the node never shows up).+ // Now: a non-repo leftover is moved aside (".disabled" so ComfyUI ignores+ // it) and re-cloned, a failed pull is a real Err, and requirements are+ // ensured on BOTH the clone and the update path.+ let mut fresh_clone = true;+ if target_dir.exists() {+ if target_dir.join(".git").exists() {+ println!("[Install] Custom node {} already exists, updating...", node_name);+ let mut cmd = Command::new("git");+ cmd.args(["pull"]).current_dir(&target_dir)+ .stdout(Stdio::piped()).stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let output = cmd.output()+ .map_err(|e| format!("Git pull failed: {}", os_error::english(&e)))?;+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ error!(node = %node_name, "custom node git pull failed");+ return Err(format!(+ "Failed to update {} (git pull): {}\n\nIf this keeps failing, \+ delete the folder {} and try the install again.",+ node_name, stderr.trim(), target_dir.to_string_lossy()+ ));+ }+ fresh_clone = false;+ } else {+ // Not a git repo — pull can never succeed. Move it aside and re-clone.+ let moved_to = move_aside_broken_node_dir(&target_dir)?;+ println!(+ "[Install] Custom node {} folder exists but is not a git repo — moved aside to {}, re-cloning",+ node_name,+ moved_to.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()+ );+ }+ }++ if fresh_clone {+ println!("[Install] Cloning custom node {} from {}", node_name, repo_url);+ let mut cmd = Command::new("git");+ cmd.args(["clone", &repo_url]).arg(&target_dir)+ .stdout(Stdio::piped()).stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let output = cmd.output()+ .map_err(|e| format!("Git clone failed: {}", os_error::english(&e)))?;+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ error!(node = %node_name, "custom node clone failed");+ return Err(format!("Failed to clone {}: {}", node_name, stderr));+ }+ }++ install_node_requirements(&comfy_dir, &target_dir, &node_name, fallback_python)?;++ Ok(serde_json::json!({+ "status": if fresh_clone { "installed" } else { "updated" },+ "path": target_dir.to_string_lossy(),+ }))+ }++ /// Move a non-repo custom-node leftover out of the way so a fresh clone can+ /// land. The ".disabled" suffix matches the ComfyUI(-Manager) convention, so+ /// ComfyUI never tries to load the moved-aside folder as a node pack.+ fn move_aside_broken_node_dir(target_dir: &std::path::Path) -> Result<PathBuf, String> {+ let base = target_dir.to_string_lossy().into_owned();+ let mut backup = PathBuf::from(format!("{}.broken.disabled", base));+ let mut n = 1;+ while backup.exists() {+ n += 1;+ backup = PathBuf::from(format!("{}.broken{}.disabled", base, n));+ }+ fs::rename(target_dir, &backup).map_err(|e| {+ format!(+ "The folder {} exists but is not a valid git checkout, and it could \+ not be moved aside: {}. Delete it manually and try again.",- target_dir.display(), e++ target_dir.display(),++ os_error::english(&e)+ )+ })?;+ Ok(backup)+ }++ /// Install a custom node's requirements.txt (when present) into the Python+ /// that ComfyUI actually runs with. Shared by the clone AND the update path+ /// of `install_custom_node` — #72 was partly caused by the update path+ /// skipping this entirely.+ ///+ /// Bug F (discovered during Arch live test on 2026-05-17): ComfyUI was+ /// installed into a venv by the Bug E path, but this used to call pip against+ /// `state.python_bin` (the system Python). On Arch / Debian 12+ / Fedora 38++ /// that hits PEP 668's `externally-managed-environment` and the requirements+ /// install silently fails. Prefer the ComfyUI venv's Python (matches the+ /// launcher in `process.rs::start_comfyui` and the installer in+ /// `install_comfyui`) so requirements land in the same site-packages ComfyUI+ /// actually imports from, and surface a useful error when pip fails.+ fn install_node_requirements(+ comfy_dir: &std::path::Path,+ target_dir: &std::path::Path,+ node_name: &str,+ fallback_python: &str,+ ) -> Result<(), String> {+ let reqs = target_dir.join("requirements.txt");+ if !reqs.exists() {+ return Ok(());+ }+ let venv_python = crate::python::resolve_comfyui_venv_python(comfy_dir);+ let python_bin = venv_python.unwrap_or_else(|| fallback_python.to_string());+ if python_bin.is_empty() {+ return Err(format!(+ "Custom node {} cloned, but cannot install requirements: \+ no Python available. Install Python first \+ (Settings → ComfyUI → Install Python).",+ node_name+ ));+ }+ println!("[Install] Installing requirements for {} via {}", node_name, python_bin);+ let run_pip = |extra: &[&str]| -> Result<std::process::Output, String> {- let mut pip = Command::new(&python_bin);++ let mut pip = python_command(&python_bin);+ pip.args(["-m", "pip", "install", "--no-input"]);+ pip.args(extra);+ pip.arg("-r").arg(&reqs);+ pip.stdout(Stdio::piped()).stderr(Stdio::piped());- #[cfg(target_os = "windows")]- pip.creation_flags(CREATE_NO_WINDOW);+ pip.output()+ .map_err(|e| format!("Failed to spawn pip for {} requirements: {}", node_name, os_error::english(&e)))+ };+ let pip_out = run_pip(&[])?;+ if !pip_out.status.success() {+ let stderr = String::from_utf8_lossy(&pip_out.stderr);+ let stdout = String::from_utf8_lossy(&pip_out.stdout);+ let combined = format!("{}{}", stdout, stderr);+ // python.org installs under Program Files have an admin-only+ // site-packages: the first node pack whose requirements pull a NEW+ // wheel dies with a permission error, while packs whose deps are+ // already present sail through (why RMBG/VHS installs passed and+ // controlnet_aux stranded the Motion install card, 2026-07-19).+ // Retry into the per-user site — the same interpreter imports from+ // there, no admin needed. The Windows twin of the PEP 668 --user+ // escape above; a venv Python never hits a permission error here,+ // and if the retry fails too we surface the original diagnosis.+ if is_permission_denied_pip_error(&combined) {+ println!(+ "[Install] {} requirements hit a permission error — retrying into the user site (--user)",+ node_name+ );+ if let Ok(user_out) = run_pip(&["--user"]) {+ if user_out.status.success() {+ return Ok(());+ }+ }+ }+ // Reuse the install_comfyui diagnose path so PEP 668 ++ // friends produce actionable messages here too.+ let diagnosis = diagnose_pip_error(&combined);+ error!(node = %node_name, "custom node requirements install failed");+ return Err(format!(+ "Custom node {} is cloned, but its requirements install failed.\n\n{}",+ node_name, diagnosis+ ));+ }+ Ok(())+ }+-/// True iff a failed pip run died on filesystem permissions (admin-only-/// site-packages, e.g. python.org installs under Program Files on Windows).-/// Those are fixable by re-running the same install with `--user`.-fn is_permission_denied_pip_error(output: &str) -> bool {- let lower = output.to_lowercase();- lower.contains("permission denied")- || lower.contains("errno 13")- || lower.contains("access is denied")- || lower.contains("winerror 5")-}++ #[cfg(test)]+ mod tests {+ use super::*;++ // ── install_custom_node helpers (#72 bob: VHS install loop) ─────────++ #[test]+ fn move_aside_renames_non_repo_dir_to_disabled() {+ let tmp = tempfile::tempdir().unwrap();+ let node_dir = tmp.path().join("ComfyUI-VideoHelperSuite");+ std::fs::create_dir(&node_dir).unwrap();+ std::fs::write(node_dir.join("leftover.txt"), "junk").unwrap();++ let moved = move_aside_broken_node_dir(&node_dir).unwrap();++ assert!(!node_dir.exists(), "original dir must be gone");+ assert!(moved.exists(), "moved-aside dir must exist");+ let name = moved.file_name().unwrap().to_string_lossy().into_owned();+ assert!(+ name.ends_with(".disabled"),+ "must end with .disabled so ComfyUI never loads it, got {name}"+ );+ assert!(moved.join("leftover.txt").exists(), "content preserved");+ }++ #[test]+ fn move_aside_picks_a_fresh_name_when_backup_exists() {+ let tmp = tempfile::tempdir().unwrap();+ let node_dir = tmp.path().join("SomeNode");+ std::fs::create_dir(&node_dir).unwrap();+ // First backup slot already taken+ std::fs::create_dir(tmp.path().join("SomeNode.broken.disabled")).unwrap();++ let moved = move_aside_broken_node_dir(&node_dir).unwrap();++ assert!(!node_dir.exists());+ let name = moved.file_name().unwrap().to_string_lossy().into_owned();+ assert_eq!(name, "SomeNode.broken2.disabled");+ }++ #[test]+ fn requirements_install_is_a_noop_without_requirements_txt() {+ let tmp = tempfile::tempdir().unwrap();+ let comfy = tmp.path().join("comfy");+ let node = tmp.path().join("comfy/custom_nodes/NoReqs");+ std::fs::create_dir_all(&node).unwrap();++ // No requirements.txt → must succeed without ever spawning pip+ // (an empty fallback python would otherwise be an instant Err).+ assert!(install_node_requirements(&comfy, &node, "NoReqs", "").is_ok());+ }++ #[test]+ fn requirements_install_without_python_is_actionable() {+ let tmp = tempfile::tempdir().unwrap();+ let comfy = tmp.path().join("comfy");+ let node = tmp.path().join("comfy/custom_nodes/WithReqs");+ std::fs::create_dir_all(&node).unwrap();+ std::fs::write(node.join("requirements.txt"), "imageio-ffmpeg").unwrap();++ let err = install_node_requirements(&comfy, &node, "WithReqs", "").unwrap_err();+ assert!(err.contains("no Python available"), "got: {err}");+ }++ // ── permission-denied → --user retry (Motion install card, 2026-07-19) ──+- #[test]- fn permission_predicate_matches_windows_and_unix_denials() {- assert!(is_permission_denied_pip_error(- "ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: 'C:\\\\Program Files\\\\Python311\\\\Lib\\\\site-packages\\\\onnxruntime'"- ));- assert!(is_permission_denied_pip_error(- "PermissionError: [WinError 5] Access is denied"- ));- assert!(is_permission_denied_pip_error("EACCES: permission denied"));- }+- #[test]- fn permission_predicate_rejects_other_pip_failures() {- assert!(!is_permission_denied_pip_error(- "error: externally-managed-environment"- ));- assert!(!is_permission_denied_pip_error(- "ReadTimeoutError: HTTPSConnectionPool(host='pypi.org')"- ));- assert!(!is_permission_denied_pip_error(- "ERROR: Could not find a version that satisfies the requirement onnxruntime-gpu"- ));- }++ }diff --cc src-tauri/src/commands/install/download.rsindex 00000000,ee610999..6e762681mode 000000,100644..100644--- a/src-tauri/src/commands/install/download.rs+++ b/src-tauri/src/commands/install/download.rs@@@ -1,0 -1,434 +1,437 @@@+ //! Eine Datei holen — und prüfen, bevor sie ausgeführt wird.+ //!+ //! Der geteilte Zustand ist die heruntergeladene Datei selbst. Sie entsteht in+ //! `download_file_blocking` und wird in `verify_downloaded_installer` wieder+ //! aufgemacht: Größe, angehefteter Prüfwert, Authenticode-Signatur. Beide+ //! Hälften an einem Ort zu halten ist der ganze Punkt dieser Naht — der+ //! Fehler, den sie verhindert, entsteht genau dazwischen. Ein Portal-Login+ //! oder eine abgeschnittene Uebertragung kommt als HTTP 200 an, wird+ //! klaglos auf die Platte geschrieben und danach mit `/S` gestartet.+ //!+ //! Die Regeln sind absichtlich einzeln und rein: `installer_size_verdict` ist+ //! der generische Boden, `installer_exact_size_verdict` die scharfe Regel für+ //! eine unveränderliche URL, `parse_authenticode_status` die Abbildung der+ //! Windows-Statusnamen. So bleibt jede von ihnen auf einem Mac prüfbar,+ //! obwohl nur Windows eine Signatur zu lesen hat.+ //!+ //! Welche Prüfwerte für welches Produkt gelten, steht NICHT hier, sondern+ //! beim jeweiligen Installer — die Zahl und die URL, aus der sie gemessen+ //! wurde, müssen zusammen wandern.++ use std::fs;+ use std::io::Read as IoRead;+ use std::path::{Path, PathBuf};+ use std::sync::{Arc, Mutex};+ use std::time::Instant;++ #[cfg(target_os = "windows")]+ use std::process::{Command, Stdio};++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tracing::info;++ use crate::os_error;+ use crate::state::InstallState;++ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ── Shared helper: download a file with progress tracking ────────────────────++ pub(super) fn download_file_blocking(+ url: &str,+ dest: &PathBuf,+ install_state: &Arc<Mutex<InstallState>>,+ ) -> Result<(), String> {+ let client = reqwest::blocking::Client::builder()+ .user_agent("LocallyUncensored/2.3")+ .redirect(reqwest::redirect::Policy::limited(10))+ // This path pulls installers and archives (hundreds of MB), so the+ // whole-request deadline still fits. The blocking client has no+ // read_timeout; the model downloader, which handles the 40 GB+ files,+ // uses the async client and bounds the stall instead of the size.+ .connect_timeout(std::time::Duration::from_secs(30))+ .timeout(std::time::Duration::from_secs(7200))+ .build()- .map_err(|e| format!("HTTP client error: {}", e))?;++ .map_err(|e| format!("HTTP client error: {}", os_error::english(&e)))?;++ let response = client.get(url).send().map_err(|e| format!("Request failed: {}", os_error::english(&e)))?;++ if !response.status().is_success() {+ return Err(format!("HTTP {}", response.status()));+ }++ let total = response.content_length().unwrap_or(0);+ if let Ok(mut s) = install_state.lock() {+ s.download_total = total;+ s.status = "downloading".to_string();+ }++ let mut file = fs::File::create(dest).map_err(|e| format!("Create file: {}", os_error::english(&e)))?;+ let mut reader = std::io::BufReader::new(response);+ let mut downloaded: u64 = 0;+ let start = Instant::now();+ let mut last_update = Instant::now();+ let mut buf = [0u8; 65536]; // 64KB chunks++ loop {- let n = reader.read(&mut buf).map_err(|e| format!("Read error: {}", e))?;++ let n = reader++ .read(&mut buf)++ .map_err(|e| format!("Read error: {}", os_error::english(&e)))?;+ if n == 0 {+ break;+ }- std::io::Write::write_all(&mut file, &buf[..n]).map_err(|e| format!("Write: {}", e))?;++ std::io::Write::write_all(&mut file, &buf[..n])++ .map_err(|e| format!("Write: {}", os_error::english(&e)))?;+ downloaded += n as u64;++ if last_update.elapsed().as_millis() > 500 {+ let elapsed = start.elapsed().as_secs_f64().max(0.001);+ let speed = downloaded as f64 / elapsed;+ if let Ok(mut s) = install_state.lock() {+ s.download_progress = downloaded;+ s.download_speed = speed;+ }+ last_update = Instant::now();+ }+ }++ // Final update+ if let Ok(mut s) = install_state.lock() {+ s.download_progress = downloaded;+ s.download_total = downloaded; // in case Content-Length was missing+ s.download_speed = 0.0;+ }++ Ok(())+ }++ // ── OI-8: nothing we downloaded gets executed unverified ────────────────────++ /// Smallest plausible size for a Windows installer LU downloads. Anything+ /// under it is not an installer: it is an error page, a captive-portal login,+ /// or a truncated transfer — and `download_file_blocking` writes all three to+ /// disk without complaint, because all three arrive as HTTP 200.+ pub(super) const MIN_INSTALLER_BYTES: u64 = 1_000_000;++ /// Hex SHA-256 of a file, streamed in chunks — a 570 MB installer must not+ /// need 570 MB of memory to be checked.+ pub(crate) fn sha256_file(path: &Path) -> Result<String, String> {+ use sha2::{Digest, Sha256};+ let mut file = fs::File::open(path)+ .map_err(|e| format!("Could not open {} to hash it: {}", path.display(), os_error::english(&e)))?;+ let mut hasher = Sha256::new();+ let mut buf = vec![0u8; 1 << 20];+ loop {+ let n = file+ .read(&mut buf)+ .map_err(|e| format!("Could not read {} while hashing: {}", path.display(), os_error::english(&e)))?;+ if n == 0 {+ break;+ }+ hasher.update(&buf[..n]);+ }+ Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())+ }++ /// Digest comparison that tolerates the shapes people paste: upper or lower+ /// case, and `certutil`'s space-separated groups.+ pub(crate) fn digest_matches(expected: &str, actual: &str) -> bool {+ let norm = |s: &str| -> String {+ s.chars()+ .filter(|c| !c.is_whitespace())+ .flat_map(|c| c.to_lowercase())+ .collect()+ };+ let (e, a) = (norm(expected), norm(actual));+ !e.is_empty() && e == a+ }++ /// What `Get-AuthenticodeSignature` said about a file.+ ///+ /// Compiled everywhere so the status mapping stays under test on the machines+ /// LU is developed on; only Windows has a signature to read.+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]+ #[derive(Debug, PartialEq, Eq, Clone, Copy)]+ pub(crate) enum SignatureVerdict {+ /// Signed by a trusted publisher and the file matches its signature.+ Valid,+ /// Signed, but the signature does not hold — tampered, or the publisher+ /// is not trusted on this machine.+ Invalid,+ /// No signature at all.+ Unsigned,+ /// The check itself did not produce an answer we can read.+ Unknown,+ }++ /// Read the `.Status` line PowerShell prints for a signature check.+ ///+ /// Kept separate from the process spawn so the mapping is testable on a Mac,+ /// where `Get-AuthenticodeSignature` does not exist. The status names come+ /// from `System.Management.Automation.SignatureStatus`.+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]+ pub(crate) fn parse_authenticode_status(stdout: &str) -> SignatureVerdict {+ let line = stdout+ .lines()+ .map(str::trim)+ .find(|l| !l.is_empty())+ .unwrap_or("")+ .to_ascii_lowercase();+ match line.as_str() {+ "valid" => SignatureVerdict::Valid,+ "notsigned" => SignatureVerdict::Unsigned,+ "hashmismatch" | "nottrusted" | "unknownerror" | "notsupportedfileformat"+ | "incompatible" => SignatureVerdict::Invalid,+ _ => SignatureVerdict::Unknown,+ }+ }++ /// Is this file big enough to be an installer at all?+ ///+ /// Pulled out as its own rule because it is the check that catches the case+ /// nobody thinks about: a proxy or captive portal answering the download with+ /// a 2 KB HTML login page, saved as `OllamaSetup.exe` and then executed.+ pub(crate) fn installer_size_verdict(bytes: u64) -> Result<(), String> {+ if bytes >= MIN_INSTALLER_BYTES {+ return Ok(());+ }+ Err(format!(+ "The downloaded installer is only {} bytes, far too small to be one — the \+ download was probably intercepted by a proxy or captive portal, or cut short. \+ LU will not run it. Download the installer yourself from the vendor's site \+ instead.",+ bytes+ ))+ }++ /// Ask Windows whether an executable's Authenticode signature is valid.+ ///+ /// Windows PowerShell 5.1 ships with every Windows 10/11, so the check is+ /// always available on the only platform that runs these installers. A file+ /// that is not `Valid` is not executed: the point of the check is that LU+ /// refuses, not that it warns and proceeds anyway.+ #[cfg(target_os = "windows")]+ fn authenticode_verdict(path: &Path) -> SignatureVerdict {+ // -LiteralPath so a path with brackets is not read as a wildcard; single+ // quotes doubled so a quote in the path cannot end the string early.+ let escaped = path.to_string_lossy().replace('\'', "''");+ let mut cmd = Command::new("powershell");+ cmd.args([+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ &format!("(Get-AuthenticodeSignature -LiteralPath '{escaped}').Status"),+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(o) if o.status.success() => {+ parse_authenticode_status(&String::from_utf8_lossy(&o.stdout))+ }+ _ => SignatureVerdict::Unknown,+ }+ }++ /// Is this file exactly the size the immutable URL is known to serve?+ ///+ /// Only ever called for a URL whose bytes are supposed to never change. A+ /// mismatch means one of two things and both are refusals: the transfer was+ /// cut short / rewritten, or the vendor replaced a file LU treats as fixed.+ pub(crate) fn installer_exact_size_verdict(expected: u64, actual: u64, label: &str) -> Result<(), String> {+ if expected == actual {+ return Ok(());+ }+ Err(format!(+ "The downloaded {label} installer is {actual} bytes; the version-pinned \+ download URL is known to serve exactly {expected}. Either the transfer \+ was altered or cut short, or the vendor replaced a file at a URL that \+ is supposed to be immutable. LU will not run it — install {label} from \+ the vendor's own site instead."+ ))+ }++ /// Everything that has to be true before LU executes a file it downloaded:+ /// it is big enough to be an installer, it is exactly the size an immutable+ /// URL is known to serve (when there is one), it matches its pinned digest if+ /// one exists, and on Windows it carries a valid Authenticode signature.+ ///+ /// `label` names the product in the error text — the user has to know which+ /// download to fetch by hand when LU refuses.+ pub(super) fn verify_downloaded_installer(+ path: &Path,+ expected_sha256: Option<&str>,+ expected_bytes: Option<u64>,+ label: &str,+ ) -> Result<(), String> {+ let size = fs::metadata(path)+ .map_err(|e| format!("Could not stat the downloaded {label} installer: {}", os_error::english(&e)))?+ .len();+ installer_size_verdict(size)?;++ if let Some(expected) = expected_bytes {+ installer_exact_size_verdict(expected, size, label)?;+ info!(label, bytes = size, "installer matched its pinned size");+ }++ if let Some(pin) = expected_sha256 {+ let actual = sha256_file(path)?;+ if !digest_matches(pin, &actual) {+ return Err(format!(+ "The downloaded {label} installer does not match its pinned SHA-256, so LU \+ will not run it.\nexpected: {pin}\ngot: {actual}\nDownload {label} \+ from the vendor's site by hand instead."+ ));+ }+ info!(label, "installer matched its pinned sha-256");+ }++ #[cfg(target_os = "windows")]+ {+ match authenticode_verdict(path) {+ SignatureVerdict::Valid => {}+ verdict => {+ return Err(format!(+ "The downloaded {label} installer has no valid code signature \+ ({verdict:?}), so LU will not run it. Download {label} from the \+ vendor's own site and install it yourself."+ ));+ }+ }+ }+ Ok(())+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ // ── OI-8: nothing downloaded is executed unverified ───────────────────+ //+ // Runnable here: the digest, the comparison, the size rule and the+ // signature-status mapping. NOT runnable here: the Authenticode check+ // itself — `Get-AuthenticodeSignature` is Windows-only, and this was+ // written on macOS, so the spawn is verified by review only.++ #[test]+ fn sha256_matches_the_published_vector_for_abc() {+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("abc.bin");+ std::fs::write(&f, b"abc").unwrap();+ assert_eq!(+ sha256_file(&f).unwrap(),+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"+ );+ }++ #[test]+ fn sha256_of_an_empty_file_is_the_known_empty_digest() {+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("empty.bin");+ std::fs::write(&f, b"").unwrap();+ assert_eq!(+ sha256_file(&f).unwrap(),+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ );+ }++ #[test]+ fn sha256_streams_a_file_larger_than_its_buffer() {+ // The buffer is 1 MiB; a 570 MB installer must not be read in one go,+ // so the chunk loop has to be right across a boundary.+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("big.bin");+ std::fs::write(&f, vec![0x5au8; (1 << 20) + 12345]).unwrap();+ let digest = sha256_file(&f).unwrap();+ assert_eq!(digest.len(), 64);+ assert!(digest.chars().all(|c| c.is_ascii_hexdigit()));+ }++ #[test]+ fn sha256_of_a_missing_file_is_an_error_not_a_panic() {+ assert!(sha256_file(Path::new("/definitely/not/here.exe")).is_err());+ }++ #[test]+ fn digests_compare_across_the_shapes_people_paste() {+ let lower = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";+ assert!(digest_matches(lower, lower));+ assert!(digest_matches(&lower.to_uppercase(), lower));+ // certutil prints space-separated groups.+ assert!(digest_matches("ba78 16bf 8f01 cfea", "ba7816bf8f01cfea"));+ // Negative controls: a different digest, and an empty pin, which must+ // never read as "matches everything".+ assert!(!digest_matches(lower, &lower.replace("ba78", "ba79")));+ assert!(!digest_matches("", lower));+ assert!(!digest_matches(" ", lower));+ }++ #[test]+ fn a_captive_portal_login_page_is_not_an_installer() {+ // The case the size rule exists for: HTTP 200, 2 KB of HTML, saved as+ // OllamaSetup.exe and then executed.+ let err = installer_size_verdict(2_048).unwrap_err();+ assert!(err.contains("2048"), "{err}");+ assert!(err.to_lowercase().contains("will not run it"), "{err}");+ assert!(installer_size_verdict(0).is_err());+ // A real installer passes.+ assert!(installer_size_verdict(570_000_000).is_ok());+ assert!(installer_size_verdict(MIN_INSTALLER_BYTES).is_ok());+ }++ #[test]+ fn only_a_valid_authenticode_status_reads_as_valid() {+ assert_eq!(parse_authenticode_status("Valid\n"), SignatureVerdict::Valid);+ assert_eq!(parse_authenticode_status(" valid "), SignatureVerdict::Valid);+ assert_eq!(parse_authenticode_status("NotSigned"), SignatureVerdict::Unsigned);+ for bad in ["HashMismatch", "NotTrusted", "UnknownError", "NotSupportedFileFormat"] {+ assert_eq!(+ parse_authenticode_status(bad),+ SignatureVerdict::Invalid,+ "{bad} must not pass"+ );+ }+ // Anything unreadable is Unknown, and Unknown is not Valid — the+ // caller refuses on everything that is not Valid.+ assert_eq!(parse_authenticode_status(""), SignatureVerdict::Unknown);+ assert_eq!(parse_authenticode_status("\n\n"), SignatureVerdict::Unknown);+ assert_eq!(+ parse_authenticode_status("The term 'Get-AuthenticodeSignature' is not recognized"),+ SignatureVerdict::Unknown+ );+ }++ #[test]+ fn a_truncated_download_is_refused_before_it_is_executed() {+ // End to end over the parts that run off-Windows: a file that is too+ // small never gets as far as the digest or the signature.+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("Setup.exe");+ std::fs::write(&f, b"<html>captive portal</html>").unwrap();+ let err = verify_downloaded_installer(&f, None, None, "LM Studio").unwrap_err();+ assert!(err.to_lowercase().contains("too small"), "{err}");+ }++ #[test]+ fn a_wrong_pinned_digest_refuses_and_shows_both_hashes() {+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("Setup.exe");+ std::fs::write(&f, vec![0u8; MIN_INSTALLER_BYTES as usize + 1]).unwrap();+ let err = verify_downloaded_installer(&f, Some("deadbeef"), None, "LM Studio").unwrap_err();+ assert!(err.contains("deadbeef"), "{err}");+ assert!(err.contains("expected") && err.contains("got"), "{err}");+ assert!(err.contains("LM Studio"), "{err}");+ }++ #[test]+ fn the_exact_size_rule_passes_only_on_an_exact_match() {+ assert!(installer_exact_size_verdict(221_768_208, 221_768_208, "LM Studio").is_ok());+ assert!(installer_exact_size_verdict(221_768_208, 221_768_207, "LM Studio").is_err());+ assert!(installer_exact_size_verdict(221_768_208, 221_768_209, "LM Studio").is_err());+ assert!(installer_exact_size_verdict(221_768_208, 0, "LM Studio").is_err());+ }++ }diff --cc src-tauri/src/commands/install/env_check.rsindex 00000000,00000000..23687cd1new file mode 100644--- /dev/null+++ b/src-tauri/src/commands/install/env_check.rs@@@ -1,0 -1,0 +1,1296 @@@++//! Der Beweis, dass eine Python-Umgebung wirklich startet.++//!++//! Der geteilte Zustand ist ein einziger Lauf des Prüfskripts: `probe_targets`++//! entscheidet, was importiert wird, `import_probe_script` schreibt das++//! Skript, `run_import_probe_bounded` startet es mit Frist und Abbruch,++//! `parse_import_probe` liest seine Zeilen zurück, und `probe_verdict` fällt++//! aus genau diesem Bericht das Urteil. Sie teilen sich ein Protokoll aus vier++//! Wörtern, das nur hier steht und nirgends sonst gebraucht wird. Läge das++//! Urteil woanders, müsste das Protokoll zweimal gepflegt werden.++//!++//! Warum es ein eigenes Modul ist und nicht bei `comfy_install` liegt: die++//! Prüfung ist der letzte Schritt von DREI Wegen, nämlich Installation,++//! Reparatur und Update. Zwei davon stehen in `comfy_repair`. Ein Modul, das++//! aus zwei anderen gerufen wird, gehört keinem von beiden.++//!++//! Was hier NICHT liegt: die Deutung von pip-Ausgaben. Ob ein Fehlschlag am++//! Netz, an den Rechten oder an einer fehlenden Laufzeit-DLL liegt,++//! entscheidet `pip`, und dieses Modul fragt dort nach. Es entscheidet nur,++//! WAS geheilt wird, nicht, warum ein pip-Lauf misslang.++++use std::fs;++use std::io::{BufRead, BufReader};++use std::process::Stdio;++use std::sync::atomic::AtomicU64;++use std::time::Instant;++use crate::os_error;++use crate::commands::torch_wheels;++use std::path::Path;++use std::sync::atomic::{AtomicBool, Ordering};++use std::sync::{Arc, Mutex};++++use crate::python::python_command;++use crate::state::InstallState;++++use super::pip::{++ pip_failure_hint, pip_failure_kind, pip_install_streaming_with_retry_raw, push_install_log,++ should_retry_in_user_site, PipFailureKind,++};++++/// Import names for the distributions ComfyUI's requirements.txt names.++///++/// ONLY distributions listed here are probed. Deriving an import name from a++/// distribution name is a guess (pyyaml imports as `yaml`, pillow as `PIL`),++/// and a wrong guess would turn a healthy environment into a false alarm and++/// send the customer to Repair environment for nothing. Anything the table++/// does not know is installed but not probed, which is exactly the behaviour++/// before this change.++///++/// The list is names only. It pins no version, and a requirements.txt that++/// stops naming a package stops it being probed.++pub(crate) const KNOWN_IMPORT_NAMES: &[(&str, &str)] = &[++ ("torch", "torch"),++ ("torchvision", "torchvision"),++ ("torchaudio", "torchaudio"),++ ("torchsde", "torchsde"),++ ("numpy", "numpy"),++ ("einops", "einops"),++ ("transformers", "transformers"),++ ("tokenizers", "tokenizers"),++ ("sentencepiece", "sentencepiece"),++ ("safetensors", "safetensors"),++ ("aiohttp", "aiohttp"),++ ("yarl", "yarl"),++ ("pyyaml", "yaml"),++ ("pillow", "PIL"),++ ("scipy", "scipy"),++ ("tqdm", "tqdm"),++ ("psutil", "psutil"),++ ("alembic", "alembic"),++ ("sqlalchemy", "sqlalchemy"),++ ("av", "av"),++ ("kornia", "kornia"),++ ("spandrel", "spandrel"),++ ("soundfile", "soundfile"),++ ("pydantic", "pydantic"),++ ("pydantic-settings", "pydantic_settings"),++ ("requests", "requests"),++ ("filelock", "filelock"),++ ("blake3", "blake3"),++ ("simpleeval", "simpleeval"),++];++++/// The comment ComfyUI's own requirements.txt uses to separate the packages a++/// core needs from the ones it can start without. Everything below it is++/// reported and logged when it will not import, but it never fails an install:++/// kornia, spandrel, pydantic and friends live down there, and refusing to++/// finish over one of them would trade A3 for a worse bug.++///++/// Matched on the words, not on the exact line, so a reflow of that comment++/// does not silently turn six optional packages back into mandatory ones.++pub(crate) fn is_optional_section_marker(comment: &str) -> bool {++ let c = comment.to_ascii_lowercase();++ (c.contains("non essential") || c.contains("non-essential") || c.contains("optional"))++ && c.contains("dependencies")++}++++/// One package the probe can ask about: what pip calls it, what Python calls++/// it, and whether a core can start without it.++#[derive(Debug, Clone, PartialEq, Eq)]++pub(crate) struct ProbeTarget {++ pub(crate) dist: String,++ pub(crate) module: &'static str,++ pub(crate) essential: bool,++}++++/// PEP 503 name normalisation, so `PyYAML`, `pyyaml` and `Py_YAML` are one++/// package.++pub(crate) fn normalize_dist(name: &str) -> String {++ let mut out = String::with_capacity(name.len());++ let mut last_dash = false;++ for c in name.trim().to_ascii_lowercase().chars() {++ let c = if c == '_' || c == '.' { '-' } else { c };++ if c == '-' {++ if !last_dash {++ out.push('-');++ }++ last_dash = true;++ } else {++ out.push(c);++ last_dash = false;++ }++ }++ out.trim_matches('-').to_string()++}++++/// One line of a requirements.txt, as far as the probe cares.++#[derive(Debug, Clone, PartialEq, Eq)]++pub(crate) struct RequirementLine {++ pub(crate) dist: String,++ /// False below the optional-dependencies comment: reported, never fatal.++ pub(crate) essential: bool,++}++++/// Distribution names a requirements.txt asks for. Options (`-r`, `-e`,++/// `--index-url`), comments, blank lines and URLs are dropped; version++/// specifiers and extras are cut off.++///++/// A line carrying an environment marker (`foo ; sys_platform == "win32"`) is++/// dropped entirely rather than stripped down to its name. pip decides whether++/// that line applies to this machine, and the probe has no business asking for++/// a Windows only package on Linux and then calling the environment broken.++pub(crate) fn parse_requirement_lines(text: &str) -> Vec<RequirementLine> {++ let mut out: Vec<RequirementLine> = Vec::new();++ let mut essential = true;++ for raw in text.lines() {++ let (code, comment) = match raw.split_once('#') {++ Some((c, rest)) => (c.trim(), rest),++ None => (raw.trim(), ""),++ };++ if is_optional_section_marker(comment) {++ essential = false;++ }++ if code.is_empty() || code.starts_with('-') {++ continue;++ }++ // pip owns the marker, so a line that has one is installed but not++ // probed.++ if code.contains(';') {++ continue;++ }++ // `name @ url` is still a name; a bare URL is not.++ let head = code.split('@').next().unwrap_or("").trim();++ if head.is_empty() || head.contains("://") {++ continue;++ }++ let end = head++ .find(|c: char| "[<>=!~ \t,(".contains(c))++ .unwrap_or(head.len());++ let dist = normalize_dist(&head[..end]);++ if dist.is_empty() || out.iter().any(|l| l.dist == dist) {++ continue;++ }++ out.push(RequirementLine { dist, essential });++ }++ out++}++++/// What the probe should import for a given requirements.txt. torch always++/// comes first and always comes along: it is installed in its own step, it is++/// the one package whose failure is a native library fault rather than a++/// missing file, and it is the canary for every DLL report in A3.++pub(crate) fn probe_targets(requirements: &str) -> Vec<ProbeTarget> {++ let mut out = vec![ProbeTarget {++ dist: "torch".to_string(),++ module: "torch",++ essential: true,++ }];++ for line in parse_requirement_lines(requirements) {++ if line.dist == "torch" {++ continue;++ }++ if let Some((_, module)) = KNOWN_IMPORT_NAMES.iter().find(|(d, _)| *d == line.dist) {++ out.push(ProbeTarget {++ dist: line.dist,++ module,++ essential: line.essential,++ });++ }++ }++ out++}++++/// The Python program the probe runs. It announces each module BEFORE trying++/// it and flushes, so an import that takes the whole interpreter down with it++/// (0xC0000005, reported by petermanmancusso) still leaves its name in the++/// output instead of an empty log and an exit code.++pub(crate) fn import_probe_script(modules: &[&str]) -> String {++ let list = modules++ .iter()++ .map(|m| format!("\"{m}\""))++ .collect::<Vec<_>>()++ .join(", ");++ format!(++ "import importlib, sys\n\++ sys.stdout.write(\"PROBE_VENV \" + (\"1\" if sys.prefix != sys.base_prefix else \"0\") + \"\\n\"); sys.stdout.flush()\n\++ for m in [{list}]:\n\++ \x20 sys.stdout.write(\"PROBE_TRY \" + m + \"\\n\"); sys.stdout.flush()\n\++ \x20 try:\n\++ \x20 importlib.import_module(m)\n\++ \x20 sys.stdout.write(\"PROBE_OK \" + m + \"\\n\")\n\++ \x20 except BaseException as e:\n\++ \x20 sys.stdout.write(\"PROBE_FAIL \" + m + \" :: \" + type(e).__name__ + \": \" + \" \".join(str(e).split()) + \"\\n\")\n\++ \x20 sys.stdout.flush()\n\++ sys.stdout.write(\"PROBE_DONE\\n\"); sys.stdout.flush()\n"++ )++}++++/// How long the probe may take before it counts as hung. Twenty four imports++/// on a cold Windows drive is minutes of disk, and torch alone can take most++/// of one; a Windows loader dialog behind the app takes forever. Generous++/// enough for a slow spinning disk, short enough that 4/4 is not a dead end.++const IMPORT_PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(300);++++/// What the probe found. `missing` is the healable half (pip can put those++/// back), everything else is not: no amount of pip fixes an absent Visual C++++/// runtime, a hung loader or an interpreter that dies on exit.++#[derive(Debug, Default, PartialEq, Eq)]++pub(crate) struct ImportProbeReport {++ pub(crate) missing: Vec<String>,++ pub(crate) broken: Vec<(String, String)>,++ /// Every failure's own words, keyed by the module we asked for. `missing`++ /// and `broken` say what to do; this says what Python said.++ pub(crate) reasons: Vec<(String, String)>,++ pub(crate) crashed: Option<String>,++ pub(crate) finished: bool,++ /// The probe hit its deadline and was killed.++ pub(crate) timed_out: bool,++ /// The interpreter walked the whole list and still exited non zero, which++ /// is a native library dying on shutdown. Every field above can be clean++ /// and the environment still be broken, so this one has to count.++ pub(crate) exited_badly: bool,++ /// The interpreter runs inside a virtual environment, so a `--user`++ /// install would be refused. Read from the probe itself rather than++ /// guessed from the path.++ pub(crate) in_venv: bool,++}++++impl ImportProbeReport {++ pub(crate) fn is_healthy(&self) -> bool {++ self.finished++ && self.missing.is_empty()++ && self.broken.is_empty()++ && self.crashed.is_none()++ && !self.timed_out++ && !self.exited_badly++ }++}++++/// The module name a `No module named 'X'` blames, which is not always the++/// module we asked for: a package whose own dependency chain is broken names++/// the dependency, and quoting only our side turns that into a riddle.++pub(crate) fn module_named_in_error(reason: &str) -> Option<String> {++ let at = reason.find("No module named")? + "No module named".len();++ let rest = reason[at..].trim_start();++ let quote = rest.chars().next()?;++ if quote != '\'' && quote != '"' {++ return None;++ }++ let inner = &rest[quote.len_utf8()..];++ let end = inner.find(quote)?;++ let name = inner[..end].trim();++ (!name.is_empty()).then(|| name.to_string())++}++++/// Read the probe's output. `interpreter_survived` is the process exit status:++/// an interpreter that died mid import leaves a `PROBE_TRY` with nothing after++/// it, and that name is the module that killed it.++pub(crate) fn parse_import_probe(stdout: &str, interpreter_survived: bool) -> ImportProbeReport {++ let mut report = ImportProbeReport::default();++ let mut pending: Option<String> = None;++ for line in stdout.lines() {++ let line = line.trim();++ if let Some(v) = line.strip_prefix("PROBE_VENV ") {++ report.in_venv = v.trim() == "1";++ } else if let Some(m) = line.strip_prefix("PROBE_TRY ") {++ pending = Some(m.trim().to_string());++ } else if let Some(m) = line.strip_prefix("PROBE_OK ") {++ if pending.as_deref() == Some(m.trim()) {++ pending = None;++ }++ } else if let Some(rest) = line.strip_prefix("PROBE_FAIL ") {++ let (module, reason) = match rest.split_once(" :: ") {++ Some((m, r)) => (m.trim().to_string(), r.trim().to_string()),++ None => (rest.trim().to_string(), "no detail from python".to_string()),++ };++ if pending.as_deref() == Some(module.as_str()) {++ pending = None;++ }++ report.reasons.push((module.clone(), reason.clone()));++ // A plain ModuleNotFoundError is a file that is not there, which++ // is the sqlalchemy / pyyaml case and the only one pip can fix.++ if reason.to_ascii_lowercase().contains("modulenotfounderror") {++ report.missing.push(module);++ } else {++ report.broken.push((module, reason));++ }++ } else if line == "PROBE_DONE" {++ report.finished = true;++ pending = None;++ }++ }++ if !report.finished || !interpreter_survived {++ report.crashed = pending;++ }++ report.exited_badly = !interpreter_survived;++ report++}++++/// Move a crash into `broken` only when the interpreter's dying words say++/// something we can name.++///++/// Torch and transformers write warnings to stderr on almost every start, so++/// the LAST stderr line of a crashed run is usually a deprecation notice.++/// Promoting on that turned an access violation into "Press Repair++/// environment" with no cause named, which is the message the crash case++/// exists to avoid.++pub(crate) fn promote_crash_from_stderr(report: &mut ImportProbeReport, stderr: &str) {++ let Some(module) = report.crashed.clone() else {++ return;++ };++ let named = stderr++ .lines()++ .map(str::trim)++ .filter(|l| !l.is_empty())++ .rev()++ .find(|l| pip_failure_kind(l) != PipFailureKind::Unknown);++ if let Some(line) = named {++ report.broken.push((module, line.to_string()));++ report.crashed = None;++ }++}++++/// What to do about a probe result. Pure, so every branch is testable without++/// an interpreter, a network or a card.++#[derive(Debug, PartialEq, Eq)]++pub(crate) enum ProbeVerdict {++ /// Nothing to do.++ Healthy,++ /// Install these distributions, then probe once more.++ Heal(Vec<String>),++ /// Say it in the log, finish anyway. Only optional packages are affected.++ Warn(String),++ /// Stop, with a finished sentence for the status line.++ Fail(String),++}++++/// The distributions a heal step should install: every missing module we can++/// name a package for.++///++/// PyTorch is never in the list. It comes from a channel the card decides++/// (`plan_pytorch_install`), and a bare `pip install torch` would take whatever++/// PyPI serves by default, which is how a machine ends up with a build that has++/// no kernels for its own card. A torch that is missing after its own step is a++/// failed install, and the rebuild is the answer.++pub(crate) fn dists_to_heal(targets: &[ProbeTarget], report: &ImportProbeReport) -> Vec<String> {++ if report++ .missing++ .iter()++ .any(|m| torch_wheels::TORCH_TRIO.contains(&m.as_str()))++ {++ return Vec::new();++ }++ let mut out: Vec<String> = Vec::new();++ for module in &report.missing {++ if let Some(t) = targets.iter().find(|t| t.module == module.as_str()) {++ if !out.contains(&t.dist) {++ out.push(t.dist.clone());++ }++ }++ }++ out++}++++++/// True for a module the core cannot start without.++fn is_essential(targets: &[ProbeTarget], module: &str) -> bool {++ targets++ .iter()++ .find(|t| t.module == module)++ .map(|t| t.essential)++ .unwrap_or(true)++}++++/// The whole decision, in one place. `already_healed` says whether the heal++/// step has already run, so a second look never sends the caller round the pip++/// loop again.++pub(crate) fn probe_verdict(++ targets: &[ProbeTarget],++ report: &ImportProbeReport,++ already_healed: bool,++) -> ProbeVerdict {++ if report.is_healthy() {++ return ProbeVerdict::Healthy;++ }++ if report.timed_out {++ let what = report++ .crashed++ .clone()++ .map(|m| format!(" It was importing {m}."))++ .unwrap_or_default();++ return ProbeVerdict::Fail(format!(++ "The check of the ComfyUI environment did not finish within {} minutes and was \++ stopped.{what} A Windows dialog from the library loader sitting behind the app will \++ do that. Bring any hidden dialog to the front and close it, then press Repair \++ environment.",++ IMPORT_PROBE_DEADLINE.as_secs() / 60++ ));++ }++ if let Some(module) = &report.crashed {++ return ProbeVerdict::Fail(format!(++ "The Python environment crashed while importing {module}, so it cannot start ComfyUI. \++ A crash at import time (0xC0000005 on Windows) means a native library the package \++ loads does not match this machine. {}",++ pip_failure_hint(PipFailureKind::NativeLoadFailure, "")++ ));++ }++ // A hard failure that is about a package the core needs beats everything++ // below, so it is asked for first.++ if let Some((module, reason)) = report++ .broken++ .iter()++ .find(|(m, _)| is_essential(targets, m))++ {++ let hint = pip_failure_hint(pip_failure_kind(reason), reason);++ let hint = if hint.is_empty() {++ "Press Repair environment to rebuild the environment from scratch.".to_string()++ } else {++ hint++ };++ return ProbeVerdict::Fail(format!(++ "The ComfyUI environment cannot import {module}: {reason}\n\n{hint}"++ ));++ }++ if report++ .missing++ .iter()++ .any(|m| torch_wheels::TORCH_TRIO.contains(&m.as_str()))++ {++ return ProbeVerdict::Fail(format!(++ "PyTorch is not in the ComfyUI environment at all ({} could not be imported), so the \++ install did not finish. Press Repair environment: it rebuilds the environment and \++ fetches the PyTorch build that matches the card in this machine.",++ report.missing.join(", ")++ ));++ }++ if !already_healed {++ let heal = dists_to_heal(targets, report);++ if !heal.is_empty() {++ return ProbeVerdict::Heal(heal);++ }++ }++ let hard: Vec<String> = report++ .missing++ .iter()++ .filter(|m| is_essential(targets, m))++ .map(|m| describe_missing(report, m))++ .collect();++ if !hard.is_empty() {++ return ProbeVerdict::Fail(format!(++ "These packages are still missing from the ComfyUI environment after a reinstall: {}. \++ ComfyUI cannot start without them. Press Repair environment to rebuild the \++ environment from scratch, and if that fails too, send us the install log.",++ hard.join(", ")++ ));++ }++ if !report.finished {++ return ProbeVerdict::Fail(++ "The check of the ComfyUI environment did not run to the end, so the environment \++ cannot be called ready. Press Repair environment to rebuild it."++ .to_string(),++ );++ }++ if report.exited_badly {++ return ProbeVerdict::Fail(format!(++ "Every package imported, but the interpreter itself then ended with an error, which \++ is a native library failing as it unloads. {}",++ pip_failure_hint(PipFailureKind::NativeLoadFailure, "")++ ));++ }++ // Only the packages below the optional-dependencies line are left. Say so++ // and finish: refusing to complete over one of those would trade A3 for a++ // worse bug.++ let soft: Vec<String> = report++ .missing++ .iter()++ .map(|m| describe_missing(report, m))++ .chain(report.broken.iter().map(|(m, r)| format!("{m} ({r})")))++ .collect();++ if !soft.is_empty() {++ return ProbeVerdict::Warn(format!(++ "These optional packages do not import: {}. ComfyUI starts without them, but the \++ nodes that use them will not appear.",++ soft.join(", ")++ ));++ }++ ProbeVerdict::Healthy++}++++/// `spandrel` when spandrel itself is gone, `spandrel (needs timm)` when the++/// import died on somebody else's package.++fn describe_missing(report: &ImportProbeReport, module: &str) -> String {++ let named = report++ .reasons++ .iter()++ .find(|(m, _)| m == module)++ .and_then(|(_, r)| module_named_in_error(r));++ match named {++ Some(dep) if dep != module => format!("{module} (needs {dep})"),++ _ => module.to_string(),++ }++}++++/// The line the install panel shows for a probe line, if any. Twenty four++/// silent imports on a cold drive look exactly like a hung installer, so 4/4++/// says what it is doing.++pub(crate) fn probe_progress_line(line: &str) -> Option<String> {++ if let Some(m) = line.strip_prefix("PROBE_TRY ") {++ return Some(format!("Importing {}...", m.trim()));++ }++ if let Some(rest) = line.strip_prefix("PROBE_FAIL ") {++ let module = rest.split(" :: ").next().unwrap_or(rest).trim();++ return Some(format!("{module} does not import."));++ }++ None++}++++/// Run the probe against one interpreter, with a hard deadline and the same++/// cancel flag every other step honours.++///++/// `Command::output()` waits forever. Twenty four imports on a cold Windows++/// drive is a minute of disk with no output at all, and a library loader that++/// puts up a modal dialog behind the app waits for a click that will never++/// come. Both leave the installer sitting on 4/4 with no way out, which is a++/// worse failure than the one this probe exists to catch. Modelled on++/// `shell::output_bounded`, extended to carry stderr, the exit status and the++/// cancel flag.++///++/// Err is only ever "cancelled". Everything else is a report: a probe that++/// could not start, timed out or died is reported, never called healthy.++fn run_import_probe(++ python_bin: &str,++ modules: &[&str],++ install_status: Option<&Arc<Mutex<InstallState>>>,++ cancel: Option<&Arc<AtomicBool>>,++) -> Result<ImportProbeReport, String> {++ run_import_probe_bounded(python_bin, modules, install_status, cancel, IMPORT_PROBE_DEADLINE)++}++++/// Same, with the deadline as a parameter so a test can drive the timeout and++/// the cancel paths in a second instead of in five minutes.++fn run_import_probe_bounded(++ python_bin: &str,++ modules: &[&str],++ install_status: Option<&Arc<Mutex<InstallState>>>,++ cancel: Option<&Arc<AtomicBool>>,++ max: std::time::Duration,++) -> Result<ImportProbeReport, String> {++ let script = import_probe_script(modules);++ // Die Begruendung fuer die Kodierung wohnt jetzt in python_command, weil++ // sie fuer jeden Python-Start gilt und nicht nur fuer diesen hier++ // (Ticket 003).++ let mut cmd = python_command(python_bin);++ cmd.arg("-c").arg(&script);++ cmd.stdin(Stdio::null())++ .stdout(Stdio::piped())++ .stderr(Stdio::piped());++ let mut child = match cmd.spawn() {++ Ok(c) => c,++ Err(e) => {++ return Ok(ImportProbeReport {++ broken: vec![("python".to_string(), os_error::english(&e))],++ ..Default::default()++ })++ }++ };++++ let out_lines: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));++ let err_lines: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));++ let readers_done = Arc::new(AtomicU64::new(0));++ if let Some(stdout) = child.stdout.take() {++ let sink = out_lines.clone();++ let done = readers_done.clone();++ let status = install_status.cloned();++ std::thread::spawn(move || {++ for line in BufReader::new(stdout).lines().map_while(Result::ok) {++ let line = line.trim().to_string();++ if line.is_empty() {++ continue;++ }++ if let (Some(state), Some(msg)) = (status.as_ref(), probe_progress_line(&line)) {++ push_install_log(state, &msg);++ }++ if let Ok(mut v) = sink.lock() {++ v.push(line);++ }++ }++ done.fetch_add(1, Ordering::Release);++ });++ } else {++ readers_done.fetch_add(1, Ordering::Release);++ }++ if let Some(stderr) = child.stderr.take() {++ let sink = err_lines.clone();++ let done = readers_done.clone();++ std::thread::spawn(move || {++ for line in BufReader::new(stderr).lines().map_while(Result::ok) {++ let line = line.trim().to_string();++ if !line.is_empty() {++ if let Ok(mut v) = sink.lock() {++ v.push(line);++ }++ }++ }++ done.fetch_add(1, Ordering::Release);++ });++ } else {++ readers_done.fetch_add(1, Ordering::Release);++ }++++ let deadline = Instant::now() + max;++ let mut timed_out = false;++ let exit = loop {++ if cancel.map(|c| c.load(Ordering::SeqCst)).unwrap_or(false) {++ crate::commands::shell::kill_tree(child.id());++ let _ = child.kill();++ let _ = child.wait();++ return Err("cancelled".to_string());++ }++ match child.try_wait() {++ Ok(Some(status)) => break Some(status),++ Ok(None) => {++ if Instant::now() >= deadline {++ // The tree, not just the child: a loader dialog belongs to++ // this process, but a probe that spawned anything would++ // otherwise keep the pipe open.++ crate::commands::shell::kill_tree(child.id());++ let _ = child.kill();++ let _ = child.wait();++ timed_out = true;++ break None;++ }++ std::thread::sleep(std::time::Duration::from_millis(200));++ }++ Err(_) => break None,++ }++ };++ // The reader threads are deliberately not joined: the same reason++ // `run_streamed` gives, a surviving grandchild can hold the pipe open and++ // the join would hang instead of returning what we already have.++ let settle = Instant::now() + std::time::Duration::from_millis(500);++ while readers_done.load(Ordering::Acquire) < 2 && Instant::now() < settle {++ std::thread::sleep(std::time::Duration::from_millis(10));++ }++++ let stdout_text = out_lines.lock().map(|v| v.join("\n")).unwrap_or_default();++ let stderr_text = err_lines.lock().map(|v| v.join("\n")).unwrap_or_default();++ // A localised Windows wording in the interpreter's own words would++ // otherwise be quoted straight into an English message.++ let stderr_text = os_error::sanitize_os_wording(&stderr_text).into_owned();++ let survived = exit.map(|s| s.success()).unwrap_or(false);++ let mut report = parse_import_probe(&stdout_text, survived);++ report.timed_out = timed_out;++ if timed_out {++ report.finished = false;++ }++ promote_crash_from_stderr(&mut report, &stderr_text);++ Ok(report)++}++++/// Import every package we can name, install back what is missing, import++/// again. Ok means the environment really starts; Err carries a finished++/// sentence for the status line.++///++/// This is the step "Repair environment" was missing. It rebuilt the venv and++/// then trusted pip's exit code, which is the same trust that produced the++/// broken environment in the first place.++pub(super) fn verify_and_heal_environment(++ python_bin: &str,++ requirements: &Path,++ install_status: &Arc<Mutex<InstallState>>,++ cancel: Option<&Arc<AtomicBool>>,++) -> Result<(), String> {++ let text = fs::read_to_string(requirements).unwrap_or_default();++ let targets = probe_targets(&text);++ let modules: Vec<&str> = targets.iter().map(|t| t.module).collect();++ push_install_log(++ install_status,++ &format!("Checking the environment: importing {} packages...", modules.len()),++ );++++ let report = run_import_probe(python_bin, &modules, Some(install_status), cancel)?;++ let heal = match probe_verdict(&targets, &report, false) {++ ProbeVerdict::Healthy => {++ push_install_log(install_status, "All packages import cleanly.");++ return Ok(());++ }++ ProbeVerdict::Warn(msg) => {++ push_install_log(install_status, &msg);++ return Ok(());++ }++ ProbeVerdict::Fail(msg) => return Err(msg),++ ProbeVerdict::Heal(dists) => dists,++ };++++ // Self-heal before the error message: the packages the mods were++ // installing by hand get installed here instead.++ push_install_log(++ install_status,++ &format!(++ "These packages are missing and are being installed now: {}.",++ heal.join(", ")++ ),++ );++ let mut args: Vec<&str> = vec!["-m", "pip", "install", "--progress-bar", "off", "--no-input"];++ args.extend(heal.iter().map(|s| s.as_str()));++ match pip_install_streaming_with_retry_raw(&args, python_bin, 3, install_status, cancel) {++ Ok(()) => {}++ Err(f) if f.diagnosis == "cancelled" => return Err("cancelled".to_string()),++ Err(f) => {++ // The same admin-only site-packages escape the requirements step++ // takes. Without it the heal dies on exactly the machine the heal++ // exists for: a python.org install under Program Files, where the++ // first wheel that is not already there cannot be written.++ let escaped = should_retry_in_user_site(report.in_venv, &f.stderr)++ && {++ push_install_log(++ install_status,++ "The missing packages could not be written to the shared site-packages. \++ Retrying into the per user site, which needs no administrator.",++ );++ let mut user_args = args.clone();++ user_args.push("--user");++ pip_install_streaming_with_retry_raw(&user_args, python_bin, 2, install_status, cancel)++ .is_ok()++ };++ if !escaped {++ return Err(format!(++ "The ComfyUI environment is missing {} and they could not be installed.\n\n{}",++ heal.join(", "),++ f.diagnosis++ ));++ }++ }++ }++++ let second = run_import_probe(python_bin, &modules, Some(install_status), cancel)?;++ match probe_verdict(&targets, &second, true) {++ ProbeVerdict::Healthy => {++ push_install_log(install_status, "All packages import cleanly now.");++ Ok(())++ }++ ProbeVerdict::Warn(msg) => {++ push_install_log(install_status, &msg);++ Ok(())++ }++ ProbeVerdict::Heal(_) | ProbeVerdict::Fail(_) => {++ Err(match probe_verdict(&targets, &second, true) {++ ProbeVerdict::Fail(msg) => msg,++ _ => "The ComfyUI environment still does not import. Press Repair environment."++ .to_string(),++ })++ }++ }++}++++#[cfg(test)]++mod tests {++ use super::*;++ use super::super::pip::VC_REDIST_PAGE;++++ /// The shape of ComfyUI's own requirements.txt, including the comment that++ /// splits it and the two names the mods were typing into the ticket.++ const COMFY_REQUIREMENTS: &str = "comfyui-frontend-package\n\++ torch\n\++ torchsde\n\++ torchvision\n\++ numpy>=1.25.0\n\++ PyYAML\n\++ Pillow\n\++ SQLAlchemy\n\++ alembic\n\++ av\n\++ #non essential dependencies:\n\++ kornia>=0.7.1\n\++ spandrel\n\++ pydantic~=2.0\n\++ pydantic-settings~=2.0\n";++++ #[test]++ fn the_two_packages_the_mods_installed_by_hand_are_in_the_probe() {++ let targets = probe_targets(COMFY_REQUIREMENTS);++ let modules: Vec<&str> = targets.iter().map(|t| t.module).collect();++ assert!(modules.contains(&"yaml"), "pyyaml is not probed: {modules:?}");++ assert!(modules.contains(&"sqlalchemy"), "sqlalchemy is not probed: {modules:?}");++ assert!(modules.contains(&"PIL"), "pillow is not probed: {modules:?}");++ // torch leads, and it comes along even when it is installed in its own++ // step: it is the canary for every DLL report in A3.++ assert_eq!(targets[0].module, "torch");++ assert_eq!(targets.iter().filter(|t| t.module == "torch").count(), 1);++ // pip has to be handed the DISTRIBUTION name back, not the import name.++ let yaml = targets.iter().find(|t| t.module == "yaml").expect("pyyaml");++ assert_eq!(yaml.dist, "pyyaml");++ }++++ #[test]++ fn the_packages_below_the_non_essential_comment_never_fail_an_install() {++ // requirements.txt splits itself, and kornia, spandrel and pydantic++ // live on the far side of that line. Treating them as mandatory would++ // trade A3 for a worse bug: an install that refuses to finish over a++ // package ComfyUI starts without.++ let targets = probe_targets(COMFY_REQUIREMENTS);++ let essential = |m: &str| targets.iter().find(|t| t.module == m).map(|t| t.essential);++ assert_eq!(essential("sqlalchemy"), Some(true), "above the line, so mandatory");++ assert_eq!(essential("yaml"), Some(true));++ assert_eq!(essential("torch"), Some(true));++ for soft in ["kornia", "spandrel", "pydantic", "pydantic_settings"] {++ assert_eq!(essential(soft), Some(false), "{soft} would fail an install");++ }++ // Negative control: without that comment the very same lines are++ // mandatory, so the split really comes from the file and not from a++ // hard-coded package list.++ let flat = COMFY_REQUIREMENTS.replace("#non essential dependencies:\n", "");++ let flat_targets = probe_targets(&flat);++ assert_eq!(++ flat_targets.iter().find(|t| t.module == "kornia").map(|t| t.essential),++ Some(true),++ );++ }++++ #[test]++ fn a_line_with_an_environment_marker_is_installed_but_never_probed() {++ // pip owns the marker. Probing a Windows only package on Linux and++ // then calling the environment broken is a bug we would have shipped.++ let with_marker = "torch\nsoundfile ; sys_platform == \"win32\"\n";++ let modules: Vec<&str> = probe_targets(with_marker).iter().map(|t| t.module).collect();++ assert_eq!(modules, vec!["torch"], "a marked line was probed: {modules:?}");++ // Negative control: the same package without a marker IS probed, so++ // the rule is about the marker and not about soundfile.++ let plain: Vec<&str> = probe_targets("torch\nsoundfile\n").iter().map(|t| t.module).collect();++ assert!(plain.contains(&"soundfile"), "{plain:?}");++ }++++ #[test]++ fn a_package_whose_import_name_we_do_not_know_is_never_guessed() {++ // Negative control: guessing would turn a healthy environment into a++ // false alarm and send the customer to Repair environment for nothing.++ let targets = probe_targets("comfyui-workflow-templates\nsome-brand-new-thing\n");++ let modules: Vec<&str> = targets.iter().map(|t| t.module).collect();++ assert_eq!(modules, vec!["torch"], "an unknown package was guessed at: {modules:?}");++ }++++ #[test]++ fn requirements_parsing_drops_the_lines_that_are_not_packages() {++ let reqs = "# a comment\n\n-r other.txt\n--index-url https://example.invalid/simple\nhttps://example.invalid/wheel.whl\ntorch==2.9.1\nPyYAML\nspandrel ; python_version >= \"3.10\"\nkornia[extra]>=0.7\n";++ let dists: Vec<String> = parse_requirement_lines(reqs).into_iter().map(|l| l.dist).collect();++ assert_eq!(dists, vec!["torch", "pyyaml", "kornia"], "got {dists:?}");++ }++++ #[test]++ fn distribution_names_are_normalised_the_way_pip_normalises_them() {++ for name in ["Py_YAML", "py.yaml", " py--yaml ", "PY-Yaml"] {++ assert_eq!(normalize_dist(name), "py-yaml", "{name}");++ }++ assert_eq!(normalize_dist("PyYAML"), "pyyaml");++ assert_eq!(normalize_dist("pydantic_settings"), "pydantic-settings");++ }++++ #[test]++ fn the_optional_marker_is_read_from_the_words_not_from_one_exact_line() {++ assert!(is_optional_section_marker("non essential dependencies:"));++ assert!(is_optional_section_marker(" Non-Essential Dependencies "));++ assert!(is_optional_section_marker("optional dependencies below"));++ // Negative control: an ordinary comment must not silently turn the++ // rest of the file optional.++ assert!(!is_optional_section_marker(" pinned for the frontend package"));++ assert!(!is_optional_section_marker(" dependencies"));++ }++++ #[test]++ fn a_probe_where_everything_imports_is_healthy() {++ let out = "PROBE_VENV 1\nPROBE_TRY torch\nPROBE_OK torch\nPROBE_TRY yaml\nPROBE_OK yaml\nPROBE_DONE\n";++ let report = parse_import_probe(out, true);++ assert!(report.is_healthy(), "{report:?}");++ assert!(report.in_venv, "the venv flag was not read");++ assert_eq!(probe_verdict(&probe_targets("torch\nPyYAML\n"), &report, false), ProbeVerdict::Healthy);++ }++++ #[test]++ fn a_probe_that_finished_but_exited_non_zero_is_not_healthy() {++ // A native library that dies as it unloads walks the whole list first++ // and only then takes the process down. Every field was clean and the++ // exit status was the one thing nobody looked at.++ let out = "PROBE_VENV 0\nPROBE_TRY torch\nPROBE_OK torch\nPROBE_DONE\n";++ let bad = parse_import_probe(out, false);++ assert!(!bad.is_healthy(), "a non zero exit passed as healthy: {bad:?}");++ assert!(bad.exited_badly);++ let msg = match probe_verdict(&probe_targets("torch\n"), &bad, true) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("{other:?}"),++ };++ assert!(msg.contains("unloads"), "{msg}");++ // Negative control: the identical output with exit 0 is healthy, so++ // the verdict really turns on the status and not on the log.++ assert!(parse_import_probe(out, true).is_healthy());++ }++++ #[test]++ fn a_module_that_is_simply_not_installed_is_healed_before_it_is_reported() {++ let out = "PROBE_VENV 1\nPROBE_TRY torch\nPROBE_OK torch\n\++ PROBE_TRY sqlalchemy\nPROBE_FAIL sqlalchemy :: ModuleNotFoundError: No module named 'sqlalchemy'\n\++ PROBE_TRY yaml\nPROBE_FAIL yaml :: ModuleNotFoundError: No module named 'yaml'\n\++ PROBE_DONE\n";++ let report = parse_import_probe(out, true);++ assert!(!report.is_healthy());++ assert_eq!(report.missing, vec!["sqlalchemy", "yaml"]);++ assert!(report.broken.is_empty());++ assert!(report.crashed.is_none());++ let targets = probe_targets(COMFY_REQUIREMENTS);++ // The heal list is what pip is handed: distribution names, so yaml has++ // to come back out as pyyaml.++ assert_eq!(dists_to_heal(&targets, &report), vec!["sqlalchemy", "pyyaml"]);++ assert_eq!(++ probe_verdict(&targets, &report, false),++ ProbeVerdict::Heal(vec!["sqlalchemy".to_string(), "pyyaml".to_string()]),++ );++ // Negative control: after the heal has run, the same result is a++ // failure and not another trip round the pip loop.++ assert!(matches!(probe_verdict(&targets, &report, true), ProbeVerdict::Fail(_)));++ }++++ #[test]++ fn a_missing_torch_is_never_reinstalled_from_plain_pypi() {++ // Negative control for the heal path: torch comes from the channel the++ // card decides. A bare `pip install torch` would hand a Blackwell box++ // whatever PyPI serves by default, which is the bug the wheel planner++ // exists to prevent.++ let out = "PROBE_VENV 1\nPROBE_TRY torch\nPROBE_FAIL torch :: ModuleNotFoundError: No module named 'torch'\nPROBE_DONE\n";++ let report = parse_import_probe(out, true);++ let targets = probe_targets(COMFY_REQUIREMENTS);++ assert_eq!(report.missing, vec!["torch"]);++ assert!(dists_to_heal(&targets, &report).is_empty(), "the heal would fetch a wheel nobody chose");++ let msg = match probe_verdict(&targets, &report, false) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("{other:?}"),++ };++ assert!(msg.contains("Repair environment"), "{msg}");++ assert!(msg.contains("matches the card"), "{msg}");++ }++++ #[test]++ fn only_the_optional_half_missing_still_finishes_the_install() {++ // kornia below the non essential line: say it, log it, complete.++ let out = "PROBE_VENV 1\nPROBE_TRY torch\nPROBE_OK torch\n\++ PROBE_TRY kornia\nPROBE_FAIL kornia :: ModuleNotFoundError: No module named 'kornia'\n\++ PROBE_DONE\n";++ let report = parse_import_probe(out, true);++ let targets = probe_targets(COMFY_REQUIREMENTS);++ let verdict = probe_verdict(&targets, &report, true);++ let msg = match &verdict {++ ProbeVerdict::Warn(m) => m.clone(),++ other => panic!("an optional package stopped the install: {other:?}"),++ };++ assert!(msg.contains("kornia"), "{msg}");++ assert!(msg.contains("optional"), "{msg}");++ // Negative control: the same failure for a package ABOVE the line++ // stops the install.++ let hard = parse_import_probe(++ "PROBE_VENV 1\nPROBE_TRY sqlalchemy\nPROBE_FAIL sqlalchemy :: ModuleNotFoundError: No module named 'sqlalchemy'\nPROBE_DONE\n",++ true,++ );++ assert!(matches!(probe_verdict(&targets, &hard, true), ProbeVerdict::Fail(_)));++ }++++ #[test]++ fn a_dll_failure_is_never_treated_as_something_pip_can_fix() {++ // Reinstalling a package cannot put a Visual C++ runtime on the++ // machine, so the probe must not send the installer round the pip loop.++ let out = "PROBE_VENV 1\nPROBE_TRY torch\nPROBE_FAIL torch :: OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading \"c10.dll\"\nPROBE_DONE\n";++ let report = parse_import_probe(out, true);++ let targets = probe_targets(COMFY_REQUIREMENTS);++ assert!(dists_to_heal(&targets, &report).is_empty());++ let msg = match probe_verdict(&targets, &report, false) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("pip is being asked to fix a DLL: {other:?}"),++ };++ assert!(msg.contains("torch"), "{msg}");++ assert!(msg.contains(VC_REDIST_PAGE), "no way out of the DLL failure: {msg}");++ }++++ #[test]++ fn an_interpreter_that_dies_mid_import_names_the_module_that_killed_it() {++ // petermanmancusso: "Process exited with code 0xC0000005". No++ // traceback, no last line, just a dead process. The PROBE_TRY line++ // written before the import is the only thing left.++ let report = parse_import_probe("PROBE_VENV 1\nPROBE_TRY torch\n", false);++ assert_eq!(report.crashed.as_deref(), Some("torch"));++ assert!(!report.is_healthy());++ let msg = match probe_verdict(&probe_targets("torch\n"), &report, false) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("{other:?}"),++ };++ assert!(msg.contains("torch"), "{msg}");++ assert!(msg.contains("0xC0000005"), "the crash is not named: {msg}");++ assert!(msg.contains(VC_REDIST_PAGE), "{msg}");++ }++++ #[test]++ fn a_crash_is_only_explained_by_a_stderr_line_that_says_something() {++ // torch and transformers write warnings on nearly every start, so the++ // LAST stderr line of a crashed run is usually a deprecation notice.++ // Promoting on that turned an access violation into a shrug.++ let mut noisy = parse_import_probe("PROBE_TRY torch\n", false);++ promote_crash_from_stderr(++ &mut noisy,++ "UserWarning: torchvision is out of date\n warnings.warn(msg)\n",++ );++ assert_eq!(noisy.crashed.as_deref(), Some("torch"), "a warning stole the crash");++ assert!(noisy.broken.is_empty());++ // And a line that DOES say something is taken, with the file named.++ let mut named = parse_import_probe("PROBE_TRY torch\n", false);++ promote_crash_from_stderr(++ &mut named,++ "UserWarning: something noisy\nImportError: VCOMP140.DLL was not found\n",++ );++ assert!(named.crashed.is_none(), "{named:?}");++ assert_eq!(named.broken.len(), 1);++ let msg = match probe_verdict(&probe_targets("torch\n"), &named, false) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("{other:?}"),++ };++ assert!(msg.contains("VCOMP140.DLL"), "{msg}");++ }++++ #[test]++ fn a_probe_that_never_reached_the_end_is_not_called_healthy() {++ // Negative control: exit code 0 with a truncated log used to be++ // indistinguishable from success, which is the whole class of bug A3++ // is made of.++ let report = parse_import_probe("PROBE_VENV 1\nPROBE_TRY torch\nPROBE_OK torch\n", true);++ assert!(!report.is_healthy(), "an unfinished probe passed as healthy: {report:?}");++ assert!(matches!(probe_verdict(&probe_targets("torch\n"), &report, true), ProbeVerdict::Fail(_)));++ }++++ #[test]++ fn a_timed_out_probe_names_the_hidden_dialog_and_never_passes() {++ let mut report = parse_import_probe("PROBE_VENV 0\nPROBE_TRY torch\n", false);++ report.timed_out = true;++ assert!(!report.is_healthy());++ let msg = match probe_verdict(&probe_targets("torch\n"), &report, false) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("a hung probe did not stop the install: {other:?}"),++ };++ assert!(msg.contains("did not finish"), "{msg}");++ assert!(msg.contains("torch"), "the module it hung on is unnamed: {msg}");++ assert!(msg.contains("dialog"), "the usual cause is unnamed: {msg}");++ }++++ #[test]++ fn a_broken_dependency_chain_names_the_package_that_is_really_gone() {++ // spandrel imports and dies on timm. Quoting only our own side turns++ // that into a riddle.++ assert_eq!(++ module_named_in_error("ModuleNotFoundError: No module named 'timm'").as_deref(),++ Some("timm"),++ );++ assert_eq!(module_named_in_error("OSError: something else"), None);++ let report = parse_import_probe(++ "PROBE_VENV 1\nPROBE_TRY spandrel\nPROBE_FAIL spandrel :: ModuleNotFoundError: No module named 'timm'\nPROBE_DONE\n",++ true,++ );++ let targets = probe_targets("torch\nspandrel\n");++ let msg = match probe_verdict(&targets, &report, true) {++ ProbeVerdict::Fail(m) => m,++ other => panic!("{other:?}"),++ };++ assert!(msg.contains("spandrel (needs timm)"), "{msg}");++ }++++ #[test]++ fn the_probe_script_announces_a_module_before_it_imports_it() {++ let script = import_probe_script(&["torch", "yaml"]);++ let try_at = script.find("PROBE_TRY").expect("no try marker");++ let import_at = script.find("importlib.import_module").expect("no import");++ assert!(try_at < import_at, "the name is written after the crash could happen");++ assert!(script.contains("flush()"), "an unflushed line is lost in a crash");++ assert!(script.contains("\"torch\", \"yaml\""), "modules missing: {script}");++ assert!(script.contains("BaseException"), "a SystemExit from an import would escape");++ assert!(script.contains("PROBE_VENV"), "nothing says whether --user would be refused");++ }++++ #[test]++ fn the_user_site_escape_is_taken_exactly_where_it_can_work() {++ // The heal step used to lack this entirely, so it died on precisely++ // the machine it exists for: a python.org install under Program Files,++ // where the first wheel that is not already there cannot be written.++ let denied = "ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\Program Files\\Python312\\Lib\\site-packages'";++ assert!(should_retry_in_user_site(false, denied), "the escape is never taken");++ // Negative control one: a venv REFUSES --user, so retrying there swaps++ // one failure for another.++ assert!(!should_retry_in_user_site(true, denied), "a venv would reject --user");++ // Negative control two: a network failure would just fail again.++ assert!(!should_retry_in_user_site(false, "ConnectionResetError: connection reset by peer"));++ }++++ #[test]++ fn the_install_panel_says_which_package_it_is_importing() {++ // Twenty four silent imports on a cold drive look exactly like a hung++ // installer, which is the state 4/4 must never be mistaken for.++ assert_eq!(probe_progress_line("PROBE_TRY torch").as_deref(), Some("Importing torch..."));++ assert_eq!(++ probe_progress_line("PROBE_FAIL yaml :: ModuleNotFoundError: x").as_deref(),++ Some("yaml does not import."),++ );++ // Negative control: the protocol's own bookkeeping is not shown.++ assert_eq!(probe_progress_line("PROBE_OK torch"), None);++ assert_eq!(probe_progress_line("PROBE_VENV 1"), None);++ assert_eq!(probe_progress_line("PROBE_DONE"), None);++ }++++ /// PYTHONPATH is process wide and the test runner is threaded, so the live++ /// probe tests take turns. Without this they steal each other's module++ /// folder and fail for a reason that has nothing to do with the probe.++ static PROBE_ENV_LOCK: Mutex<()> = Mutex::new(());++++ /// Write a throwaway python module and put its folder on PYTHONPATH, so++ /// the probe can be driven against a real interpreter with a module that++ /// behaves exactly like the customer reports. Returns the module name.++ fn stage_probe_module(dir: &std::path::Path, name: &str, body: &str) -> String {++ std::fs::create_dir_all(dir).expect("probe dir");++ std::fs::write(dir.join(format!("{name}.py")), body).expect("probe module");++ std::env::set_var("PYTHONPATH", dir);++ name.to_string()++ }++++ /// The interpreter the live probe tests run against, found the way the++ /// product finds it.++ ///++ /// Not the literal "python3": the CI matrix runs this suite on++ /// windows-latest too, where the interpreter is `python`, lives under++ /// Program Files, or answers only through the `py` launcher. Borrowing the++ /// product's own resolver means these tests cover Windows instead of being++ /// skipped there, and it returns the empty string when the box has no++ /// usable Python, which is the clean skip.++ fn probe_python() -> Option<String> {++ let bin = crate::python::get_python_bin();++ (!bin.is_empty() && crate::python::is_real_python(&bin)).then_some(bin)++ }++++ /// The deadline the live tests use. The product waits five minutes for a++ /// cold drive; a test that waited that long would be a CI outage, and a++ /// test that never reaches its deadline proves nothing.++ const TEST_PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_millis(1200);++++ /// Long enough that only a broken cancel reaches it, short enough that a++ /// broken cancel fails the job in seconds instead of a minute.++ const TEST_CANCEL_DEADLINE: std::time::Duration = std::time::Duration::from_secs(8);++++ /// The script is generated as text, so a stray indent or quote would only++ /// show up on a customer machine. Run it through a real interpreter here.++ /// Skipped where the test box has no python3, which is honest: this asserts++ /// nothing about Windows, only that the program we emit is valid Python.++ #[test]++ fn the_generated_script_is_valid_python_and_speaks_the_parsers_protocol() {++ let _turn = PROBE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ let Some(python) = probe_python() else {++ eprintln!("no usable Python on this box, skipping the live probe check");++ return;++ };++ let report = run_import_probe(&python, &["json", "definitely_not_a_real_module_lu"], None, None)++ .expect("not cancelled");++ assert_eq!(report.missing, vec!["definitely_not_a_real_module_lu"], "{report:?}");++ assert!(report.broken.is_empty(), "{report:?}");++ assert!(report.finished, "the DONE marker never arrived: {report:?}");++ assert!(!report.exited_badly, "{report:?}");++ }++++ /// The whole reason `promote_crash_from_stderr` is careful: a real child++ /// that warns and then dies without a traceback.++ #[test]++ fn a_real_child_that_warns_then_dies_keeps_its_crash_unexplained() {++ let _turn = PROBE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ let Some(python) = probe_python() else {++ eprintln!("no usable Python on this box, skipping the live probe check");++ return;++ };++ let dir = std::env::temp_dir().join("lu-probe-crash-noisy");++ let name = stage_probe_module(++ &dir,++ "lu_probe_boom_noisy",++ "import sys, os\n\++ sys.stderr.write('UserWarning: a library being noisy\\n')\n\++ sys.stderr.flush()\n\++ os._exit(3)\n",++ );++ let report = run_import_probe(&python, &[&name], None, None).expect("not cancelled");++ std::env::remove_var("PYTHONPATH");++ let _ = std::fs::remove_dir_all(&dir);++ assert_eq!(report.crashed.as_deref(), Some(name.as_str()), "{report:?}");++ assert!(report.broken.is_empty(), "a warning was sold as the cause: {report:?}");++ assert!(!report.finished, "{report:?}");++ }++++ /// And the same child whose last words DO name a cause.++ #[test]++ fn a_real_child_that_names_a_dll_before_it_dies_gets_that_cause() {++ let _turn = PROBE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ let Some(python) = probe_python() else {++ eprintln!("no usable Python on this box, skipping the live probe check");++ return;++ };++ let dir = std::env::temp_dir().join("lu-probe-crash-named");++ let name = stage_probe_module(++ &dir,++ "lu_probe_boom_named",++ "import sys, os\n\++ sys.stderr.write('UserWarning: a library being noisy\\n')\n\++ sys.stderr.write('ImportError: VCOMP140.DLL was not found\\n')\n\++ sys.stderr.flush()\n\++ os._exit(3)\n",++ );++ let report = run_import_probe(&python, &[&name], None, None).expect("not cancelled");++ std::env::remove_var("PYTHONPATH");++ let _ = std::fs::remove_dir_all(&dir);++ assert!(report.crashed.is_none(), "{report:?}");++ assert_eq!(report.broken.len(), 1, "{report:?}");++ assert!(report.broken[0].1.contains("VCOMP140.DLL"), "{report:?}");++ }++++ /// An import that never returns is the failure mode a modal loader dialog++ /// produces on Windows, and `Command::output()` would have waited for a++ /// click that never comes.++ #[test]++ fn a_probe_that_hangs_is_killed_at_the_deadline_and_never_passes() {++ let _turn = PROBE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ let Some(python) = probe_python() else {++ eprintln!("no usable Python on this box, skipping the live probe check");++ return;++ };++ let dir = std::env::temp_dir().join("lu-probe-hang");++ let name = stage_probe_module(&dir, "lu_probe_hang", "import time\ntime.sleep(120)\n");++ let started = std::time::Instant::now();++ let report = run_import_probe_bounded(&python, &[&name], None, None, TEST_PROBE_DEADLINE)++ .expect("not cancelled");++ std::env::remove_var("PYTHONPATH");++ let _ = std::fs::remove_dir_all(&dir);++ assert!(started.elapsed() < std::time::Duration::from_secs(30), "the deadline did not bite");++ assert!(report.timed_out, "{report:?}");++ assert!(!report.is_healthy(), "a hung probe passed as healthy: {report:?}");++ }++++ /// Cancel has to reach the probe too, or the button stops working exactly++ /// at 4/4.++ #[test]++ fn cancel_stops_the_probe_instead_of_waiting_it_out() {++ let _turn = PROBE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ let Some(python) = probe_python() else {++ eprintln!("no usable Python on this box, skipping the live probe check");++ return;++ };++ let dir = std::env::temp_dir().join("lu-probe-cancel");++ let name = stage_probe_module(&dir, "lu_probe_cancel", "import time\ntime.sleep(120)\n");++ let flag = Arc::new(AtomicBool::new(false));++ let trip = flag.clone();++ std::thread::spawn(move || {++ std::thread::sleep(std::time::Duration::from_millis(400));++ trip.store(true, Ordering::SeqCst);++ });++ let started = std::time::Instant::now();++ let out = run_import_probe_bounded(&python, &[&name], None, Some(&flag), TEST_CANCEL_DEADLINE);++ std::env::remove_var("PYTHONPATH");++ let _ = std::fs::remove_dir_all(&dir);++ assert_eq!(out.err().as_deref(), Some("cancelled"));++ assert!(started.elapsed() < TEST_CANCEL_DEADLINE, "cancel waited the probe out");++ }++++}diff --cc src-tauri/src/commands/install/lmstudio.rsindex 00000000,445be1b4..2a667346mode 000000,100644..100644--- a/src-tauri/src/commands/install/lmstudio.rs+++ b/src-tauri/src/commands/install/lmstudio.rs@@@ -1,0 -1,530 +1,530 @@@+ //! Das `lms`-CLI finden und den laufenden LM-Studio-Server bedienen.+ //!+ //! Der geteilte Zustand ist eine fremde, bereits laufende Anwendung: ein Port+ //! auf dem Loopback und ein Kommandozeilenwerkzeug irgendwo auf der Platte.+ //! Alles hier dreht sich um diese zwei und um nichts sonst — den Server+ //! starten, seinen Zustand abfragen, Modelle laden und entladen.+ //!+ //! Die Naht gegen `lmstudio_install` verläuft entlang des Zustands, nicht+ //! entlang des Themas: dort wird ein `InstallState` gefüllt, hier wird ein+ //! laufender Dienst angesprochen. Der Modellwähler fragt dieses Modul im+ //! Sekundentakt ab, während die Installation genau einmal im Leben läuft.+ //!+ //! Daraus folgt die auffälligste Eigenheit hier: `lmstudio_port_open` mit+ //! seinen 300 ms geht JEDER HTTP-Anfrage voraus. Ein einfaches GET gegen+ //! einen geschlossenen Port braucht auf manchen Windows-Kisten zwei bis+ //! sieben Sekunden, und der Wähler fragt alle 1,5 s — das war die Ursache+ //! des eingefrorenen Fensters, nicht die Anfrage selbst.++ use std::path::{Path, PathBuf};+ use std::process::{Command, Stdio};++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use crate::os_error;++ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ pub(super) const LMSTUDIO_DEFAULT_PORT: u16 = 1234;+-pub(super) fn lmstudio_lms_path() -> Option<PathBuf> {++pub(crate) fn lmstudio_lms_path() -> Option<PathBuf> {+ // Every branch below is a Windows-ism (`lms.exe`, LOCALAPPDATA/PROGRAMFILES,+ // the registry, `where`), so on macOS/Linux this returned None even with LM+ // Studio installed — breaking lmstudio_load/unload/server there. The+ // cross-platform helper already handles the Unix layout (`lms` with no+ // extension at ~/.lmstudio/bin, plus Spotlight), so delegate to it.+ #[cfg(not(target_os = "windows"))]+ {+ return crate::os_paths::find_lms_cli();+ }+ // Post-bootstrap: `lms bootstrap` materialises the launcher here and adds+ // the same path to PATH. Cheapest check first.+ #[allow(unreachable_code)]+ let direct = dirs::home_dir().map(|h| h.join(".lmstudio").join("bin").join("lms.exe"));+ if let Some(ref p) = direct {+ if p.exists() {+ return direct;+ }+ }++ // Pre-bootstrap: on a fresh install, lms.exe ships inside the GUI app's+ // resources dir before `lms bootstrap` ever runs. Calling this binary+ // directly is how we *do* the bootstrap on a brand-new box — without it+ // the user has to open LM Studio once from the Start menu just to seed+ // the CLI, which is exactly the noob-cliff this sweep is removing.+ let webpack_suffix = ["resources", "app", ".webpack", "lms.exe"];+ if let Ok(la) = std::env::var("LOCALAPPDATA") {+ let mut pre_bootstrap = PathBuf::from(la);+ pre_bootstrap.push("Programs");+ pre_bootstrap.push("LM Studio");+ for s in &webpack_suffix { pre_bootstrap.push(s); }+ if pre_bootstrap.exists() {+ return Some(pre_bootstrap);+ }+ }++ // System-wide install path: when LM Studio's installer is run "for all+ // users" (or installed via an MSI deployment), it lands in+ // %PROGRAMFILES%\LM Studio\. techx69 confirmed (2026-05-06): the+ // per-user-only lookup made LU report "no LM Studio detected" even with+ // `~/.lmstudio/models/` already populated.+ for env_var in ["PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432"] {+ if let Ok(pf) = std::env::var(env_var) {+ let mut sys_wide = PathBuf::from(pf);+ sys_wide.push("LM Studio");+ for s in &webpack_suffix { sys_wide.push(s); }+ if sys_wide.exists() {+ return Some(sys_wide);+ }+ }+ }++ // Registry-based fallback: LM Studio's installer writes its install dir+ // under HKCU or HKLM Uninstall keys. Reading the registry lets us catch+ // exotic install dirs (e.g. user moved it to D:\Apps\LM Studio\).+ #[cfg(target_os = "windows")]+ if let Some(p) = lmstudio_path_from_registry() {+ let candidate = p.join("resources").join("app").join(".webpack").join("lms.exe");+ if candidate.exists() {+ return Some(candidate);+ }+ // Some builds drop lms.exe at the install root.+ let root_candidate = p.join("lms.exe");+ if root_candidate.exists() {+ return Some(root_candidate);+ }+ }++ // Last resort: PATH lookup. Catches non-standard installs (Chocolatey,+ // user-relocated install dir, etc.). CREATE_NO_WINDOW so this `where` probe+ // never flashes a console window at the end user.+ let mut where_cmd = Command::new("where");+ where_cmd.arg("lms");+ #[cfg(target_os = "windows")]+ where_cmd.creation_flags(CREATE_NO_WINDOW);+ if let Ok(out) = where_cmd.output() {+ if out.status.success() {+ let s = String::from_utf8_lossy(&out.stdout);+ if let Some(line) = s.lines().next() {+ let p = PathBuf::from(line.trim());+ if p.exists() {+ return Some(p);+ }+ }+ }+ }++ None+ }++ /// Soft-detect LM Studio by scanning `~/.lmstudio/models/` for GGUF files.+ /// Returns the number of GGUF files found (0 if the dir is missing or empty).+ ///+ /// Rationale: even when `lms.exe` isn't on any search path (system-wide+ /// install missed by our fallback, GUI never launched, etc.), the presence+ /// of GGUFs in the canonical models dir is a strong signal that the user+ /// *has* LM Studio and just hasn't started the server. Surfacing that in the+ /// onboarding lets us show "LM Studio models detected — start server?" instead+ /// of the dead-end "no LM Studio".+ fn lmstudio_models_present() -> u32 {+ let home = match dirs::home_dir() {+ Some(h) => h,+ None => return 0,+ };+ let models_dir = home.join(".lmstudio").join("models");+ if !models_dir.exists() {+ return 0;+ }+ // The standard layout is ~/.lmstudio/models/<publisher>/<repo>/<file>.gguf —+ // up to three levels deep. We walk lazily and stop after the first 1000+ // matches; the user does not care about the exact count past "many".+ fn walk(dir: &Path, depth: u32, found: &mut u32) {+ if *found >= 1000 || depth > 4 {+ return;+ }+ let entries = match std::fs::read_dir(dir) {+ Ok(e) => e,+ Err(_) => return,+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ walk(&path, depth + 1, found);+ } else if path.extension().and_then(|e| e.to_str()).map(|s| s.eq_ignore_ascii_case("gguf")).unwrap_or(false) {+ *found += 1;+ if *found >= 1000 {+ return;+ }+ }+ }+ }+ let mut count: u32 = 0;+ walk(&models_dir, 0, &mut count);+ count+ }++ #[cfg(target_os = "windows")]+ fn lmstudio_path_from_registry() -> Option<PathBuf> {+ // Read InstallLocation from LM Studio's Uninstall entry. We try HKCU+ // first (per-user installs) then HKLM (system-wide). The display name+ // varies slightly between installer builds, so we scan for any subkey+ // whose DisplayName starts with "LM Studio".+ use winreg::enums::*;+ use winreg::RegKey;+ for hive in [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] {+ let root = RegKey::predef(hive);+ for uninstall_path in [+ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",+ r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",+ ] {+ let Ok(uninstall) = root.open_subkey(uninstall_path) else { continue };+ for key_res in uninstall.enum_keys() {+ let Ok(key) = key_res else { continue };+ let Ok(sub) = uninstall.open_subkey(&key) else { continue };+ let name: String = sub.get_value("DisplayName").unwrap_or_default();+ if name.eq_ignore_ascii_case("LM Studio") || name.starts_with("LM Studio") {+ if let Ok(loc) = sub.get_value::<String, _>("InstallLocation") {+ let p = PathBuf::from(loc);+ if p.exists() {+ return Some(p);+ }+ }+ }+ }+ }+ }+ None+ }++ /// Path to the LM Studio GUI executable on Windows. We only need to launch+ /// this in the rare case where `lms bootstrap` from the pre-bootstrap binary+ /// reports success but `~/.lmstudio/` is still missing — some installs+ /// require a one-time GUI launch to populate user-data dirs before+ /// `lms bootstrap` will register the CLI on PATH.+ pub(super) fn lmstudio_gui_exe() -> Option<PathBuf> {+ let la = std::env::var("LOCALAPPDATA").ok()?;+ let p = PathBuf::from(la)+ .join("Programs")+ .join("LM Studio")+ .join("LM Studio.exe");+ if p.exists() { Some(p) } else { None }+ }++ /// Fast, BOUNDED reachability probe for the LM Studio server. A plain HTTP GET+ /// to a DOWN server is catastrophically slow on some Windows boxes: connecting+ /// to a closed `127.0.0.1:<port>` can take ~2 s to refuse (the IPv4 loopback+ /// SYN is silently dropped by the firewall → TCP retransmit timeout), and+ /// `reqwest`'s request `timeout` does NOT bound the connect phase tightly, so+ /// the GET ran 2–7 s. Worse, the model-selector re-polls the LM-Studio+ /// loaded-state every ~1.5 s while open, and the commands were SYNCHRONOUS+ /// (→ main thread), so each stacked multi-second probe froze the whole UI.+ /// `TcpStream::connect_timeout` hard-caps the down-case at 300 ms; the explicit+ /// `127.0.0.1` (not `localhost`) skips the slow IPv4/IPv6 happy-eyeballs dance.+ fn lmstudio_port_open() -> bool {+ use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};+ let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), LMSTUDIO_DEFAULT_PORT);+ TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300)).is_ok()+ }++ pub(super) fn lmstudio_server_running() -> bool {+ // Bail in <=300 ms when nothing is listening — see lmstudio_port_open.+ if !lmstudio_port_open() {+ return false;+ }+ let client = reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_millis(800))+ .connect_timeout(std::time::Duration::from_millis(400))+ .no_proxy()+ .build();+ if let Ok(c) = client {+ return c+ .get(format!("http://127.0.0.1:{}/v1/models", LMSTUDIO_DEFAULT_PORT))+ .send()+ .map(|r| r.status().is_success() || r.status() == 401)+ .unwrap_or(false);+ }+ false+ }++ /// Best-effort: spawn `lms server start` so we don't make the user open the+ /// LM Studio GUI just to flip the Server toggle. Idempotent — quick early-exit+ /// if the server is already responding.+ // ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread,+ // so every millisecond spent here is a frozen window. Same treatment+ // `lmstudio_server_status` already got — this one was simply missed.+ #[tauri::command]+ pub async fn start_lmstudio_server() -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(start_lmstudio_server_blocking)+ .await+ .map_err(|e| format!("start_lmstudio_server task: {e}"))?+ }++ fn start_lmstudio_server_blocking() -> Result<serde_json::Value, String> {+ if lmstudio_server_running() {+ return Ok(serde_json::json!({"status": "already_running"}));+ }+ match lmstudio_lms_path() {+ Some(p) => {+ let mut srv = Command::new(&p);+ srv.args(["server", "start", "--cors", "--port"])+ .arg(LMSTUDIO_DEFAULT_PORT.to_string())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ srv.creation_flags(CREATE_NO_WINDOW);+ srv.spawn()+ .map_err(|e| format!("spawn lms: {}", os_error::english(&e)))?;+ Ok(serde_json::json!({"status": "starting"}))+ }+ None => Err(+ "LM Studio is not installed (no lms.exe found). Use Settings → Install LM Studio first."+ .to_string(),+ ),+ }+ }++ // ASYNC + spawn_blocking: this command does a (now-bounded) blocking TCP/HTTP+ // probe + filesystem scan. A SYNCHRONOUS Tauri command runs on the MAIN thread,+ // so the model-selector's on-open + 1.5 s poll froze the UI. Running the+ // blocking body on the blocking pool keeps the webview responsive even if a+ // probe is slow. (reqwest::blocking also panics inside an async runtime, so the+ // blocking work MUST live in spawn_blocking, not a bare async body.)+ #[tauri::command]+ pub async fn lmstudio_server_status() -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(|| -> Result<serde_json::Value, String> {+ let model_count = lmstudio_models_present();+ Ok(serde_json::json!({+ "running": lmstudio_server_running(),+ "port": LMSTUDIO_DEFAULT_PORT,+ "lms_present": lmstudio_lms_path().is_some(),+ // Soft-detect signals — onboarding shows "Start LM Studio server?"+ // when models are present even if lms.exe couldn't be located.+ "models_detected": model_count > 0,+ "model_count": model_count,+ }))+ })+ .await+ .map_err(|e| format!("lmstudio_server_status task: {e}"))?+ }++ // ── Per-model load / unload ────────────────────────────────────+ //+ // LM Studio's HTTP API has no load/unload endpoints; we drive the `lms`+ // CLI for state changes and read the list of loaded models from the v0+ // REST API (`/api/v0/models` returns each entry with `state: "loaded" |+ // "not-loaded"`). This mirrors the Ollama per-row toggle in the model+ // selector — without it LM-Studio rows have no on/off affordance even+ // though the underlying engine does the same load-into-VRAM dance.+ //+ // Backport from uselu E2E pass (2026-05-19). Body is 1:1; signature+ // adapted from uselu's bridge-daemon convention to Tauri command, and+ // the lms-CLI lookup uses desktop's richer `lmstudio_lms_path()` helper+ // instead of uselu's lighter `os_paths::find_lms_cli()`.++ // ASYNC + spawn_blocking + fast port pre-check (see lmstudio_server_status /+ // lmstudio_port_open). Polled every ~1.5 s by the model selector while open —+ // the old sync + slow-localhost-probe form was the main cause of the dropdown+ // freeze.+ #[tauri::command]+ pub async fn lmstudio_list_loaded() -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(|| -> Result<serde_json::Value, String> {+ let empty = || serde_json::json!({ "loaded": Vec::<String>::new() });+ // Down server → return empty in <=300 ms instead of a 2–7 s connect.+ if !lmstudio_port_open() {+ return Ok(empty());+ }+ let client = reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_millis(1500))+ .connect_timeout(std::time::Duration::from_millis(400))+ .no_proxy()+ .build()+ .map_err(|e| e.to_string())?;+ let url = format!("http://127.0.0.1:{}/api/v0/models", LMSTUDIO_DEFAULT_PORT);+ let resp = match client.get(&url).send() {+ Ok(r) => r,+ Err(_) => return Ok(empty()),+ };+ if !resp.status().is_success() {+ return Ok(empty());+ }+ let body: serde_json::Value = resp.json().map_err(|e| e.to_string())?;+ let loaded: Vec<String> = body+ .get("data")+ .and_then(|d| d.as_array())+ .map(|arr| {+ arr.iter()+ .filter(|m| m.get("state").and_then(|s| s.as_str()) == Some("loaded"))+ .filter_map(|m| m.get("id").and_then(|i| i.as_str()).map(String::from))+ .collect()+ })+ .unwrap_or_default();+ Ok(serde_json::json!({ "loaded": loaded }))+ })+ .await+ .map_err(|e| format!("lmstudio_list_loaded task: {e}"))?+ }++ // ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread,+ // so every millisecond spent here is a frozen window. Same treatment+ // `lmstudio_server_status` already got — this one was simply missed.+ #[tauri::command]+ #[allow(non_snake_case)]+ pub async fn lmstudio_load_model(model: String, contextLength: Option<u32>) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || lmstudio_load_model_blocking(model, contextLength))+ .await+ .map_err(|e| format!("lmstudio_load_model task: {e}"))?+ }++ #[allow(non_snake_case)]+ fn lmstudio_load_model_blocking(model: String, contextLength: Option<u32>) -> Result<serde_json::Value, String> {+ let lms = lmstudio_lms_path()+ .ok_or_else(|| "lms CLI not found — install LM Studio first".to_string())?;+ // `lms load` blocks until the model is in memory. The caller is expected+ // to render a spinner while the request is in flight (same pattern as+ // the Ollama per-row toggle).+ //+ // `-y` / --yes is REQUIRED here, not optional: per `lms load --help`, when+ // the model key is ambiguous (multiple quant/variant matches) or the CLI+ // wants to confirm a device, `lms load` drops into an INTERACTIVE picker+ // that reads from stdin. We capture output with no stdin attached, so that+ // picker blocks forever — the command never returns and the model-selector+ // spinner hangs indefinitely with no error surfaced (observed live on+ // 2026-06-01 with qwen2.5-0.5b-instruct@q4_k_m). `-y` auto-approves and+ // loads the first/preferred match, which is exactly the scripted behaviour+ // we want. Verified: `lms load -y <key>` returns in ~4s and `lms ps` shows+ // the model loaded.+ //+ // contextLength: LM Studio fixes the context window at LOAD time (the+ // OpenAI-compat HTTP API has no per-request num_ctx). To CHANGE it we must+ // reload — so when a context length is requested we unload the current+ // instance first (best-effort; a no-op if nothing is loaded) and reload+ // with `-c <N>` (`lms load --context-length`). Without a context length+ // this stays a plain load (the B3 power toggle path, unchanged).+ if contextLength.is_some() {+ // Hide the console window the `lms` CLI would otherwise flash on+ // Windows (CREATE_NO_WINDOW) — these run during normal model+ // switching / the VRAM hand-off, not just at install time.+ let mut unload = Command::new(&lms);+ unload.args(["unload", &model]);+ #[cfg(target_os = "windows")]+ unload.creation_flags(CREATE_NO_WINDOW);+ let _ = unload.output();+ }+ let ctx = contextLength.unwrap_or(0);+ let ctx_str = ctx.to_string();+ let mut args: Vec<&str> = vec!["load", model.as_str(), "-y"];+ if ctx > 0 {+ args.push("-c");+ args.push(ctx_str.as_str());+ }+ let mut cmd = Command::new(&lms);+ cmd.args(&args);+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let output = cmd+ .output()+ .map_err(|e| format!("spawn lms load: {}", os_error::english(&e)))?;+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stdout = String::from_utf8_lossy(&output.stdout);+ eprintln!(+ "[lmstudio_load_model] FAILED model='{}' ctx={:?} code={:?}\n stderr={:?}\n stdout={:?}",+ model,+ contextLength,+ output.status.code(),+ stderr.trim(),+ stdout.trim()+ );+ return Err(format!("lms load failed: {}", stderr.trim()));+ }+ eprintln!("[lmstudio_load_model] OK model='{}' ctx={:?}", model, contextLength);+ Ok(serde_json::json!({ "ok": true, "model": model, "contextLength": contextLength }))+ }++ /// Read a model's context window from LM Studio's enhanced REST API+ /// (`GET /api/v0/models`). Returns `loaded_context_length` (what the model is+ /// ACTUALLY running with right now — the value the chat truly uses) and+ /// `max_context_length` (the model's ceiling). Both are null when LM Studio+ /// isn't running or the model isn't found. Reading the list endpoint (not the+ /// per-id one) sidesteps URL-encoding issues with publisher/slash ids.+ // ASYNC + spawn_blocking + fast port pre-check — same freeze class as+ // lmstudio_list_loaded; this one feeds the header token counter.+ #[tauri::command]+ pub async fn lmstudio_model_context(model: String) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || -> Result<serde_json::Value, String> {+ let null_json = || serde_json::json!({ "loaded": serde_json::Value::Null, "max": serde_json::Value::Null, "state": serde_json::Value::Null });+ if !lmstudio_port_open() {+ return Ok(null_json());+ }+ let client = match reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_millis(2000))+ .connect_timeout(std::time::Duration::from_millis(400))+ .no_proxy()+ .build()+ {+ Ok(c) => c,+ Err(_) => return Ok(null_json()),+ };+ let url = format!("http://127.0.0.1:{}/api/v0/models", LMSTUDIO_DEFAULT_PORT);+ let resp = match client.get(&url).send() {+ Ok(r) => r,+ Err(_) => return Ok(null_json()),+ };+ if !resp.status().is_success() {+ return Ok(null_json());+ }+ let body: serde_json::Value = match resp.json() {+ Ok(b) => b,+ Err(_) => return Ok(null_json()),+ };+ let entry = body+ .get("data")+ .and_then(|d| d.as_array())+ .and_then(|arr| arr.iter().find(|m| m.get("id").and_then(|i| i.as_str()) == Some(model.as_str())));+ match entry {+ Some(m) => {+ let loaded = m.get("loaded_context_length").and_then(|v| v.as_u64());+ let max = m+ .get("max_context_length")+ .and_then(|v| v.as_u64())+ .or_else(|| m.get("context_length").and_then(|v| v.as_u64()));+ let state = m.get("state").and_then(|v| v.as_str());+ Ok(serde_json::json!({ "loaded": loaded, "max": max, "state": state }))+ }+ None => Ok(null_json()),+ }+ })+ .await+ .map_err(|e| format!("lmstudio_model_context task: {e}"))?+ }++ // ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread,+ // so every millisecond spent here is a frozen window. Same treatment+ // `lmstudio_server_status` already got — this one was simply missed.+ #[tauri::command]+ pub async fn lmstudio_unload_model(model: String) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || lmstudio_unload_model_blocking(model))+ .await+ .map_err(|e| format!("lmstudio_unload_model task: {e}"))?+ }++ fn lmstudio_unload_model_blocking(model: String) -> Result<serde_json::Value, String> {+ let lms = lmstudio_lms_path()+ .ok_or_else(|| "lms CLI not found".to_string())?;+ let mut cmd = Command::new(&lms);+ cmd.args(["unload", &model]);+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let output = cmd+ .output()+ .map_err(|e| format!("spawn lms unload: {}", os_error::english(&e)))?;+ if !output.status.success() {+ return Err(format!(+ "lms unload failed: {}",+ String::from_utf8_lossy(&output.stderr).trim()+ ));+ }+ Ok(serde_json::json!({ "ok": true, "model": model }))+ }diff --cc src-tauri/src/commands/install/lmstudio_install.rsindex 00000000,a12cddf9..5b4923a2mode 000000,100644..100644--- a/src-tauri/src/commands/install/lmstudio_install.rs+++ b/src-tauri/src/commands/install/lmstudio_install.rs@@@ -1,0 -1,495 +1,496 @@@+ //! LM Studio auf Windows installieren — und was dabei angeheftet ist.+ //!+ //! Der geteilte Zustand ist der `InstallState` für LM Studio: der lange+ //! Windows-Weg erzählt hinein, `install_lmstudio_status` liest ihn aus, und+ //! sonst niemand.+ //!+ //! Die drei Konstanten oben liegen hier und nicht bei den Prüfregeln, weil+ //! sie EIN Fakt in drei Zeilen sind: die versionsfeste URL, die genaue+ //! Byte-Zahl, die sie ausliefert, und der Platz für den Prüfwert, sobald+ //! ihn jemand an der Datei selbst gemessen hat. Wer die URL bewegt, muss die+ //! Zahl neu messen; ein Test unten hält genau diese Kopplung fest. Wären+ //! sie bei den allgemeinen Regeln gelandet, wäre die Kopplung an die URL+ //! nur noch ein Kommentar.+ //!+ //! Der Bootstrap-Tanz danach ist kein Beiwerk, sondern der Grund, warum diese+ //! Installation überhaupt Plug & Play heißt: ohne ihn muss der Nutzer LM+ //! Studio einmal von Hand öffnen und den Server-Schalter umlegen.++ use std::fs;+ use std::process::{Command, Stdio};++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::State;+++use crate::os_error;+ use crate::state::AppState;++ use super::download::{download_file_blocking, verify_downloaded_installer};+ use super::lmstudio::{lmstudio_gui_exe, lmstudio_lms_path, lmstudio_server_running,+ LMSTUDIO_DEFAULT_PORT};+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ /// SHA-256 of the LM Studio installer at [`LMSTUDIO_INSTALLER_URL`].+ ///+ /// That URL is version-pinned and immutable (`0.3.16-6`), so its bytes never+ /// change and this digest is an integrity guarantee for an executable LU runs+ /// with `/S`.+ ///+ /// MEASURED, not copied. On a real Windows machine, 2026-09-01, from that exact+ /// URL:+ ///+ /// ```text+ /// BYTES = 221768208 (delta to LMSTUDIO_INSTALLER_BYTES: 0)+ /// SHA256 = 4c49a4ae378b6c1ae36b6cb7fd73b295a80af44f3d5c3e1da63c530342327208+ /// SIGNATURE = Valid, CN=Element Labs Inc., O=Element Labs Inc., Brooklyn NY US+ /// ```+ ///+ /// A guessed or mistyped value here would not weaken the check — it would break+ /// every Windows LM Studio install outright. So it stayed `None` until someone+ /// could measure it, and this is that measurement.+ ///+ /// WHAT THIS DIGEST IS AND IS NOT. The vendor publishes no checksum to compare+ /// against: `<url>.sha256`, `.sha256sum`, `.SHA256`, `.checksum` and the+ /// directory index all answer 404 (checked 2026-09-01). The digest therefore+ /// comes from the file itself, fetched over the same unauthenticated channel+ /// the app downloads through — trust-on-first-use. It pins against a LATER+ /// substitution at that URL; it cannot prove the first download was clean.+ ///+ /// What closes that gap is the Authenticode check below, and the two are not+ /// redundant. The signature was `Valid` and chains to a CA-issued Extended+ /// Validation certificate for Element Labs Inc., the company behind LM Studio —+ /// an anchor that does NOT run through the download channel. Digest and+ /// signature answer two different questions: "are these the bytes we saw" and+ /// "did the publisher sign them". Neither alone is the answer.+ ///+ /// The exact size match is corroboration, not a third check: it was established+ /// months earlier from the vendor's own `content-length` header, over the same+ /// channel, and a same-length forgery would pass it.+ ///+ /// MAINTENANCE DUTY. `LMSTUDIO_INSTALLER_URL`, this constant and+ /// `LMSTUDIO_INSTALLER_BYTES` move together or not at all. If LM Studio ever+ /// re-uploads different bytes at this version-pinned path, the install fails+ /// loudly instead of silently running new, unchecked bytes. That is the+ /// intended direction.+ ///+ /// Ollama's installer gets no pin at all and cannot: its URL+ /// (`ollama.com/download/OllamaSetup.exe`) always serves the current release,+ /// so its bytes change with every version. Signature + size is the whole+ /// answer available there.+ const LMSTUDIO_INSTALLER_SHA256: Option<&str> =+ Some("4c49a4ae378b6c1ae36b6cb7fd73b295a80af44f3d5c3e1da63c530342327208");++ /// Exact byte count of the file at [`LMSTUDIO_INSTALLER_URL`].+ ///+ /// The half of the pin that CAN be established without the file: the vendor's+ /// own server reports it in one header request, so anyone can re-check it in a+ /// second instead of moving 211 MiB.+ ///+ /// ```text+ /// curl -sI https://installers.lmstudio.ai/win32/x64/0.3.16-6/LM-Studio-0.3.16-6-x64.exe+ /// ```+ ///+ /// Measured 2026-09-01: `content-length: 221768208`, `last-modified: Fri, 23+ /// May 2025 22:14:17 GMT`, `etag: "4c5f34448d76416730ec408b05a54270"` (32 hex+ /// chars, no `-N` part suffix — a single-part object). A `last-modified` 15+ /// months in the past under a version-pinned path is the evidence that this URL+ /// is immutable; this constant is what turns that evidence from an ASSUMPTION+ /// into something the code enforces.+ ///+ /// It is deliberately much weaker than a digest — it catches a truncated or+ /// substituted transfer of a different length, not a same-length forgery — and+ /// it carries the same maintenance duty: if LM Studio ever re-uploads different+ /// bytes here, the install fails loudly instead of silently running new,+ /// unchecked bytes. That is the intended direction. `LMSTUDIO_INSTALLER_URL`+ /// and this constant have to move together.+ const LMSTUDIO_INSTALLER_BYTES: Option<u64> = Some(221_768_208);++ // ── LM Studio Install (Windows) ─────────────────────────────────────────────+ //+ // LM Studio doesn't run as a Windows service like Ollama — it's a desktop app+ // whose embedded server is started via either the GUI ("Server" tab) or the+ // `lms` CLI (`lms server start`). The install flow here:+ // 1. Download the official LM Studio installer .exe+ // 2. Silent install with /S (NSIS / electron-builder convention)+ // 3. Run `lms bootstrap` to register the CLI on PATH+ // 4. Start the server on port 1234 via `lms server start --cors`+ //+ // Step 4 is what makes this Plug & Play — without it the user has to manually+ // open the app and toggle the server, which is exactly the "version one+ // usability cliff" we're trying to remove. If lms isn't on PATH yet (e.g.+ // install is too fresh), we look in `%USERPROFILE%/.lmstudio/bin/lms.exe`+ // directly.+ //+ // The hard-coded URL points to a known-stable release. LM Studio's installer+ // host doesn't expose a /latest redirect — every version is its own URL — so+ // the alternative would be to bake in a remote-version-check, which adds an+ // extra failure mode for offline users. A stale URL just means the user gets+ // a slightly older LM Studio; functionally fine.+ const LMSTUDIO_INSTALLER_URL: &str =+ "https://installers.lmstudio.ai/win32/x64/0.3.16-6/LM-Studio-0.3.16-6-x64.exe";++ #[tauri::command]+ pub fn install_lmstudio(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let mut install = state.lmstudio_install.lock().unwrap();+ if install.status == "downloading"+ || install.status == "installing"+ || install.status == "starting"+ {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }++ install.status = "downloading".to_string();+ install.logs.clear();+ install.download_progress = 0;+ install.download_total = 0;+ install.download_speed = 0.0;+ install+ .logs+ .push("Downloading LM Studio installer...".to_string());+ drop(install);++ let lms_state = state.lmstudio_install.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = lms_state.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ // Bug H (discovered during 2026-05-17 Arch live test): pre-fix+ // install_lmstudio unconditionally downloaded LMStudioSetup.exe+ // (Windows installer) and tried to `cmd.arg("/S")` it. On Linux+ // the execve crashes with "Exec format error"; on macOS the+ // mismatch is the same. LM Studio's Linux distribution is an+ // AppImage whose URL rotates with every release, so we can't+ // mirror it from a stable in-binary string — surface a clear+ // download pointer instead of pretending to auto-install.+ if cfg!(target_os = "linux") {+ update(+ "error",+ "LM Studio's Linux distribution is an AppImage with a URL that \+ rotates per release. Download it from https://lmstudio.ai/download \+ (pick 'Linux AppImage'), `chmod +x` the file, run it once to \+ finish bootstrap, then come back to LU and click Re-detect.\n\n\+ Tip: if you prefer the CLI-only path, the `lms` CLI ships with \+ the AppImage and lands at ~/.lmstudio/bin/lms after first run.",+ );+ }+ if cfg!(target_os = "macos") {+ update(+ "error",+ "On macOS, download LM Studio.app from https://lmstudio.ai/download, \+ drag it to /Applications, launch it once to finish setup, then \+ come back to LU and click Re-detect.",+ );+ }++ // ── The Windows path ────────────────────────────────────────────────+ //+ // Everything below is the winget install. It used to sit behind the two+ // `return`s above, which made rustc call it an `unreachable statement`+ // on macOS and Linux — correct about the control flow, and saying+ // nothing about the code: this is not dead code, it is the OTHER+ // platform's implementation.+ //+ // `if cfg!` and not `#[cfg]`, for the reason `test_support.rs` states at+ // its top: a `#[cfg]` would delete this whole branch from a macOS build,+ // and with it the type-checking of ~150 lines of Windows installer plus+ // the dozen helpers it is the only caller of (`sha256_file`,+ // `installer_size_verdict`, `windows_git_probe_from_output` …), which+ // would then read as dead code here. Compiled-and-never-taken keeps the+ // Windows half honest on the machine this is developed on.+ //+ // The condition is `not(linux or macos)` rather than `windows` so the+ // set of targets that run it is exactly the set that ran it before.+ if !cfg!(any(target_os = "linux", target_os = "macos")) {+ // Pre-check: if LM Studio is already installed (an `lms.exe` is+ // findable in any of the locations `lmstudio_lms_path()` knows about)+ // we skip the ~570 MB download entirely. Re-installing on a box where+ // it's already there was the previous behaviour and made the+ // "LM Studio detected but server offline" Plug-and-Play scenario+ // turn into a 5-minute no-op download. The bootstrap + server-start+ // steps below are idempotent, so the same code path now serves both+ // first-install and offline-reactivation users.+ let already_installed = lmstudio_lms_path().is_some();+ if already_installed && lmstudio_server_running() {+ update(+ "complete",+ "LM Studio is already installed and the server is up on localhost:1234.",+ );+ return;+ }++ if already_installed {+ update(+ "starting",+ "LM Studio is already installed — skipping download. Bootstrapping CLI and starting server…",+ );+ } else {+ let temp_dir = std::env::temp_dir();+ let installer_path = temp_dir.join("LMStudioSetup.exe");++ println!("[LMStudio] Downloading {}", LMSTUDIO_INSTALLER_URL);+ if let Err(e) =+ download_file_blocking(LMSTUDIO_INSTALLER_URL, &installer_path, &lms_state)+ {+ let err = format!(+ "Download failed: {}. If the network is fine, the installer URL may have rotated — fall back to https://lmstudio.ai/download in your browser.",+ e+ );+ println!("[LMStudio] {}", err);+ update("error", &err);+ return;+ }++ // OI-8: verified before it is executed. Digest, exact size+ // and Authenticode all have to agree; see+ // LMSTUDIO_INSTALLER_SHA256 for what each of the three+ // actually proves and what none of them does.+ if let Err(e) = verify_downloaded_installer(+ &installer_path,+ LMSTUDIO_INSTALLER_SHA256,+ LMSTUDIO_INSTALLER_BYTES,+ "LM Studio",+ ) {+ let _ = fs::remove_file(&installer_path);+ println!("[LMStudio] {}", e);+ update("error", &e);+ return;+ }++ update(+ "installing",+ "Download complete. Running silent installer (this can take a minute)...",+ );++ // electron-builder NSIS supports /S for silent install. Ignore exit+ // code: real failures surface via the absence of lms.exe afterwards.+ let mut cmd = Command::new(&installer_path);+ cmd.arg("/S");+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(_) => println!("[LMStudio] Installer finished"),+ Err(e) => {- let err = format!("Could not run installer: {}", e);++ let err = format!("Could not run installer: {}", os_error::english(&e));+ println!("[LMStudio] {}", err);+ update("error", &err);+ return;+ }+ }++ let _ = fs::remove_file(&installer_path);+ }++ // Bootstrap the lms CLI. We do this in two passes:+ // (1) Run `lms bootstrap` from whatever path `lmstudio_lms_path()`+ // resolves — on a fresh install that's the pre-bootstrap binary+ // inside `resources/app/.webpack/lms.exe`. This alone is enough+ // on most boxes.+ // (2) Verify that ~/.lmstudio/bin/lms.exe now exists. If not, some+ // LM Studio builds require the GUI to run once to populate+ // ~/.lmstudio/ before the bootstrap registers a launcher there.+ // In that case we briefly launch the GUI, wait for ~/.lmstudio/+ // to appear, retry bootstrap, then move on. The user sees the+ // GUI flash up — not ideal, but strictly better than the old+ // "Open LM Studio once from the Start menu" error dialog and a+ // failed install.+ update("starting", "Bootstrapping `lms` CLI...");+ let initial_lms = lmstudio_lms_path();+ match &initial_lms {+ Some(p) => {+ let mut bs = Command::new(p);+ bs.arg("bootstrap");+ #[cfg(target_os = "windows")]+ bs.creation_flags(CREATE_NO_WINDOW);+ let _ = bs.output();+ }+ None => {+ update(+ "error",+ "LM Studio installed but `lms.exe` not found in any expected location. \+ The installer may have failed silently. Try installing LM Studio manually \+ from https://lmstudio.ai/download and then click Re-Scan.",+ );+ return;+ }+ }++ // Did pass 1 produce ~/.lmstudio/bin/lms.exe? If yes, skip the GUI+ // dance entirely. If no, fall back to launching the GUI so it seeds+ // its user-data dir, then retry bootstrap.+ let post_bootstrap_path = dirs::home_dir()+ .map(|h| h.join(".lmstudio").join("bin").join("lms.exe"));+ let needs_gui_seed = post_bootstrap_path+ .as_ref()+ .map(|p| !p.exists())+ .unwrap_or(true);++ if needs_gui_seed {+ update(+ "starting",+ "Launching LM Studio briefly to finalise CLI setup (you may see the window flash)...",+ );+ if let Some(gui) = lmstudio_gui_exe() {+ let mut g = Command::new(&gui);+ #[cfg(target_os = "windows")]+ g.creation_flags(CREATE_NO_WINDOW);+ let _ = g.spawn();+ }++ // Wait up to 30 s for ~/.lmstudio/ to appear. The first GUI launch+ // typically writes this within 3–8 s, but on a slow VM 30 s is a+ // safer ceiling than failing the install.+ let lmstudio_dir = dirs::home_dir().map(|h| h.join(".lmstudio"));+ for _ in 0..30 {+ std::thread::sleep(std::time::Duration::from_secs(1));+ if let Some(d) = &lmstudio_dir {+ if d.exists() {+ break;+ }+ }+ }++ // Retry bootstrap from the (now possibly different) lms.exe.+ // After GUI launch the .lmstudio dir might already contain a+ // launcher; if not, the pre-bootstrap path is still valid.+ if let Some(p) = lmstudio_lms_path() {+ let mut bs = Command::new(&p);+ bs.arg("bootstrap");+ #[cfg(target_os = "windows")]+ bs.creation_flags(CREATE_NO_WINDOW);+ let _ = bs.output();+ }+ }++ // Start the embedded server. `lms server start` is non-blocking — it+ // detaches a background httpd. --cors so LU's web view (which is on a+ // tauri:// origin) isn't blocked by the SOP. Port matches the+ // provider-store default of 1234 so user config Just Works.+ // Re-resolve the path because the bootstrap dance above may have+ // promoted us from the pre-bootstrap path to ~/.lmstudio/bin/lms.exe.+ update("starting", "Starting LM Studio server on port 1234...");+ if let Some(p) = lmstudio_lms_path() {+ let mut srv = Command::new(&p);+ srv.args(["server", "start", "--cors", "--port"])+ .arg(LMSTUDIO_DEFAULT_PORT.to_string())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ srv.creation_flags(CREATE_NO_WINDOW);+ let _ = srv.spawn();+ }++ // Wait for the server to respond. LM Studio's server typically takes+ // ~3-5 s to bind in a fresh install (it loads its model index first).+ update("starting", "Waiting for LM Studio server...");+ let mut ready = false;+ for i in 0..15 {+ std::thread::sleep(std::time::Duration::from_secs(2));+ if lmstudio_server_running() {+ ready = true;+ break;+ }+ println!("[LMStudio] Server not ready, attempt {}/15", i + 1);+ }++ if ready {+ update("complete", "LM Studio server is up on localhost:1234.");+ } else {+ update(+ "error",+ "LM Studio installed but the server didn't come up. Open LM Studio from the Start menu and toggle the Server tab on, then click Re-Scan.",+ );+ }+ }+ });++ Ok(serde_json::json!({"status": "downloading"}))+ }++ #[tauri::command]+ pub fn install_lmstudio_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.lmstudio_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ "download_progress": install.download_progress,+ "download_total": install.download_total,+ "download_speed": install.download_speed,+ }))+ }++ #[cfg(test)]+ mod tests {+ use super::*;+ use super::super::download::{installer_size_verdict, verify_downloaded_installer,+ MIN_INSTALLER_BYTES};++ /// T-72 — the size pin for the immutable installer URL.+ ///+ /// WHAT THIS DOES NOT PROVE: that 221_768_208 is still what the vendor+ /// serves. That is one header request away (`curl -sI <url>`), and the+ /// constant's doc comment carries both the command and the date it was+ /// last measured. No test can hold that for you without going to the+ /// network on every run.+ #[test]+ fn a_file_of_the_wrong_length_from_the_immutable_url_is_refused() {+ let expected = LMSTUDIO_INSTALLER_BYTES.expect("the size pin was removed");+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("LMStudioSetup.exe");++ // Big enough to clear the generic floor, wrong for THIS url.+ std::fs::write(&f, vec![0u8; MIN_INSTALLER_BYTES as usize + 7]).unwrap();+ let err = verify_downloaded_installer(&f, None, Some(expected), "LM Studio").unwrap_err();+ assert!(err.contains(&expected.to_string()), "{err}");+ assert!(err.contains("immutable"), "{err}");+ assert!(err.contains("LM Studio"), "{err}");++ // The generic floor alone would have let it through — that is the gap+ // this pin closes.+ assert!(installer_size_verdict(MIN_INSTALLER_BYTES + 7).is_ok());+ }++ /// The URL and the size are one fact in two places. Moving one without the+ /// other is the failure mode this pin introduces, so it gets its own guard.+ #[test]+ fn the_pinned_url_and_the_pinned_size_belong_to_the_same_version() {+ assert!(+ LMSTUDIO_INSTALLER_URL.contains("0.3.16-6"),+ "the installer URL moved: re-measure LMSTUDIO_INSTALLER_BYTES with \+ `curl -sI {LMSTUDIO_INSTALLER_URL}` and update it in the same commit"+ );+ // A plausible installer size, not a placeholder someone left behind.+ let bytes = LMSTUDIO_INSTALLER_BYTES.expect("the size pin was removed");+ assert!(bytes > MIN_INSTALLER_BYTES, "the size pin is below the generic floor");+ }++ #[test]+ fn the_lmstudio_digest_is_pinned_and_is_a_real_sha256() {+ // Two assertions, and the first one is the one that changed.+ //+ // While the pin was `None` this test could only say "if there is a+ // value, it looks like a digest" — it was a guard rail for whoever+ // would fill it in. The value is filled in now (measured on a real+ // Windows machine, 2026-09-01), so the test says the stronger thing:+ // it has to STAY filled in. Dropping it back to `None` would silently+ // downgrade an executed installer to size-plus-signature, and nobody+ // running on macOS would notice — this whole path is Windows-only.+ //+ // The second assertion is the original guard rail and still earns its+ // place: a half-typed or truncated digest breaks every Windows install+ // outright, and that failure, too, would only ever show up on Windows.+ let pin = LMSTUDIO_INSTALLER_SHA256+ .expect("the digest pin was removed — see the constant's doc comment");+ let clean: String = pin.chars().filter(|c| !c.is_whitespace()).collect();+ assert_eq!(clean.len(), 64, "pinned digest is not 64 hex chars: {pin}");+ assert!(clean.chars().all(|c| c.is_ascii_hexdigit()), "not hex: {pin}");+ }++ }diff --cc src-tauri/src/commands/install/mod.rsindex 00000000,6896394a..26ee486amode 000000,100644..100644--- a/src-tauri/src/commands/install/mod.rs+++ b/src-tauri/src/commands/install/mod.rs@@@ -1,0 -1,81 +1,285 @@@+ //! Alles, was LU für den Nutzer nachinstalliert — ComfyUI, Ollama, LM Studio,+ //! Python, die Sprachpakete und die Custom Nodes.+ //!+ //! Diese Datei ist die öffentliche Fläche und sonst nichts: der Modulbaum,+ //! der Re-Export der Namen, die früher direkt hier standen, und die eine+ //! Konstante, die wirklich alle brauchen. Kein Aufrufer außerhalb dieses+ //! Baums muss sich ändern — `crate::commands::install::…` führt weiterhin zu+ //! jedem Symbol, das von dort gebraucht wird.+ //!+ //! Geschnitten wurde nach GETEILTEM ZUSTAND, nicht nach Themen. Drei Gruppen+ //! ergeben sich daraus:+ //!+ //! * Das Werkzeug, das alle Installer benutzen: `pip` führt einen pip-Lauf+ //! durch und deutet sein Scheitern, `torch` wählt das PyTorch-Rad, `venv`+ //! weiß, welcher Python gemeint ist, `download` holt eine Datei und prüft+ //! sie vor der Ausführung, `git` beantwortet, ob geklont werden kann, und+ //! `children` führt Buch über die laufenden Kindprozesse.+ //!+ //! * ComfyUI, dessen drei Aufträge sich ein Verzeichnis und einen+ //! Statuskanal teilen: `comfy_job` hält das Schloss und die Bedienfläche,+ //! `comfy_install` baut neu, `comfy_repair` greift in Bestehendes ein.+ //!+ //! * Je ein Modul pro fremdem Produkt, das seinen eigenen `InstallState` hat:+ //! `ollama`, `lmstudio` (der laufende Dienst) und `lmstudio_install` (der+ //! Windows-Installer), `python`, `voice`, `custom_nodes`.+ //!+ //! Der Re-Export steht bewusst als Glob. Ein `#[tauri::command]` erzeugt+ //! neben der Funktion ein gleichnamiges `__cmd__`-Makro, und `generate_handler!`+ //! in `main.rs` sucht beides unter DIESEM Pfad — ein Glob nimmt beide mit,+ //! ohne dass jeder Befehl zweimal aufgezählt werden muss.+ //!+ //! Sie steht auf `pub(crate)` und nicht auf `pub`, weil genau das ihre Aufgabe+ //! ist: `main.rs`, `state.rs`, `tts.rs`, `whisper.rs` und `trainer.rs` sollen+ //! `crate::commands::install::…` weiter auflösen können. Nach außen war+ //! hier ohnehin nie etwas erreichbar — dies ist eine Binärkiste ohne+ //! lib-Ziel —, und ein `pub` hätte die gemessene öffentliche Fläche um eine+ //! Zeile wachsen lassen, ohne dass ein einziges Symbol dazugekommen wäre.+ //!-//! Zwei Module fehlen in dieser Liste, und zwar mit Absicht: `pip` und-//! `download` haben außerhalb dieses Baums keinen einzigen Nutzer. Ein++//! Drei Module fehlen in dieser Liste, und zwar mit Absicht: `pip`,++//! `download` und `env_check` werden über ihren eigenen Pfad gerufen, nicht++//! über diese Fläche. Ein+ //! Re-Export wäre ein toter Import, den `-D warnings` zu Recht ablehnt, und+ //! der einzige Weg daran vorbei wäre ein `#[allow]`. Wer sie braucht, nimmt-//! `super::pip::…` bzw. `super::download::…` — das steht ohnehin in jedem-//! Geschwistermodul, das sie benutzt.++//! `super::pip::…`, `super::download::…` bzw. `super::env_check::…` — das++//! steht ohnehin in jedem Geschwistermodul, das sie benutzt. `pip` steht auf++//! `pub(crate)`, weil `process.rs` und `trainer.rs` seine Fehlerdeutung++//! mitbenutzen: sie starten eigene pip-Läufe und sollen deren Ausgabe nicht++//! ein zweites Mal deuten. Sie schreiben den vollen Pfad,++//! `crate::commands::install::pip::…`, damit an der Aufrufstelle steht, wessen++//! Deutung das ist.++ /// Windows: hide console windows for spawned processes+ #[cfg(target_os = "windows")]+ pub(crate) const CREATE_NO_WINDOW: u32 = 0x08000000;+++ mod children;-mod pip;++pub(crate) mod pip;+ mod torch;+ mod venv;+ mod download;+ mod git;+ mod comfy_job;+ mod comfy_install;+ mod comfy_repair;++mod env_check;+ mod ollama;+ mod lmstudio;+ mod lmstudio_install;+ mod python;+ mod voice;+ mod custom_nodes;++ pub(crate) use self::{+ children::*,+ torch::*,+ venv::*,+ git::*,+ comfy_job::*,+ comfy_install::*,+ comfy_repair::*,+ ollama::*,+ lmstudio::*,+ lmstudio_install::*,+ python::*,+ voice::*,+ custom_nodes::*,+ };++++#[cfg(test)]++mod tests {++ /// Jede Datei dieses Baums, mit ihrem Namen. `include_str!` löst relativ++ /// zu dieser Datei auf, die Prüfungen unten lesen also genau die Module,++ /// die daneben liegen. Wer ein Modul hinzufügt, trägt es hier ein; der++ /// Test darunter merkt es, wenn nicht.++ const BAUM: &[(&str, &str)] = &[++ ("children.rs", include_str!("children.rs")),++ ("comfy_install.rs", include_str!("comfy_install.rs")),++ ("comfy_job.rs", include_str!("comfy_job.rs")),++ ("comfy_repair.rs", include_str!("comfy_repair.rs")),++ ("custom_nodes.rs", include_str!("custom_nodes.rs")),++ ("download.rs", include_str!("download.rs")),++ ("env_check.rs", include_str!("env_check.rs")),++ ("git.rs", include_str!("git.rs")),++ ("lmstudio.rs", include_str!("lmstudio.rs")),++ ("lmstudio_install.rs", include_str!("lmstudio_install.rs")),++ ("ollama.rs", include_str!("ollama.rs")),++ ("pip.rs", include_str!("pip.rs")),++ ("python.rs", include_str!("python.rs")),++ ("torch.rs", include_str!("torch.rs")),++ ("venv.rs", include_str!("venv.rs")),++ ("voice.rs", include_str!("voice.rs")),++ ];++++ /// Nur die ausgelieferte Hälfte einer Datei. Die Prüfungen unten zitieren++ /// die Zeichenketten, die sie verbieten, und diese Zitate stehen in++ /// Testcode. Ohne den Schnitt fänden sie sich selbst.++ fn ausgeliefert(quelle: &str) -> &str {++ quelle.split("#[cfg(test)]").next().unwrap_or(quelle)++ }++++ fn datei(name: &str) -> &'static str {++ BAUM.iter()++ .find(|(n, _)| *n == name)++ .unwrap_or_else(|| panic!("{name} steht nicht in BAUM"))++ .1++ }++++ /// Der Waechter über dem Waechter: eine neue Datei im Verzeichnis, die++ /// niemand in `BAUM` eingetragen hat, wäre von allem hier unbeobachtet.++ /// Die Prüfung läuft nur, wenn der Quelltext beim Testlauf wirklich++ /// dort liegt; fehlt er, prüfen die anderen Tests trotzdem weiter.++ #[test]++ fn jede_datei_dieses_baums_steht_in_der_liste() {++ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))++ .join("src")++ .join("commands")++ .join("install");++ let Ok(eintraege) = std::fs::read_dir(&dir) else { return };++ let mut fehlen = Vec::new();++ for e in eintraege.flatten() {++ let name = e.file_name().to_string_lossy().to_string();++ if !name.ends_with(".rs") || name == "mod.rs" {++ continue;++ }++ if !BAUM.iter().any(|(n, _)| *n == name) {++ fehlen.push(name);++ }++ }++ assert!(++ fehlen.is_empty(),++ "diese Module stehen in {} und in keiner Baum-Liste: {:?}",++ dir.display(),++ fehlen++ );++ }++++ // ── A3: die drei Wege enden auf der Umgebungspruefung ──────────────────++++ #[test]++ fn install_and_repair_both_end_on_the_environment_check() {++ // Quelltext-Anker, wie ihn der Trainer für seine Sackgassen hat: die++ // Prüfung ist wertlos, wenn einer der drei Wege ohne sie bis++ // "complete" kommt. Seit der Zerlegung stehen die Wege in zwei++ // Dateien, also liest der Wächter beide.++ for (name, marker, was) in [++ (++ "comfy_install.rs",++ "update(\"complete\", \"ComfyUI installed successfully!\");",++ "the install",++ ),++ ("comfy_repair.rs", "\"Environment repaired.", "the repair"),++ (++ "comfy_repair.rs",++ "\"ComfyUI updated. Restart ComfyUI",++ "the update",++ ),++ ] {++ let src = ausgeliefert(datei(name));++ let before = src.split(marker).next().expect(was);++ let last_check = before++ .rfind("verify_and_heal_environment(")++ .unwrap_or_else(|| panic!("{was} never checks the environment"));++ let between = &before[last_check..];++ assert!(++ !between.contains("\nfn ") && !between.contains("\npub fn "),++ "{was} runs the check in a different function than the one that declares success",++ );++ assert!(++ between.contains("update(\"error\""),++ "{was} does not stop when the check fails",++ );++ }++++ for (name, src) in BAUM {++ let src = ausgeliefert(src);++ assert!(++ !src.contains("non-critical, ComfyUI should still start"),++ "{name}: a failed requirements install is still waved through as non-critical",++ );++ assert!(++ !src.contains("Some optional dependencies had warnings (non-critical)"),++ "{name}: the repair still waves a failed requirements install through",++ );++ // Jeder Weg gibt der Prüfung das Abbruch-Fähnchen mit. Eine Prüfung++ // mit Frist, aber ohne Cancel, sind fünf Minuten, aus denen der++ // Nutzer nicht herauskommt.++ assert!(++ !src.contains("verify_and_heal_environment(&python_bin, &reqs, &install_status, None)"),++ "{name}: a path runs the environment check with no way to cancel it",++ );++ }++++ // Der Install muss nach einem vorhandenen venv greifen, bevor er nach++ // dem System-Python greift: Launcher und Updater benutzen dieses venv,++ // also legt ein Install daran vorbei die Pakete in den falschen++ // Interpreter.++ let install_body = ausgeliefert(datei("comfy_install.rs"))++ .split("pub fn install_comfyui(")++ .nth(1)++ .expect("install_comfyui");++ let venv_at = install_body++ .find("resolve_comfyui_venv_python")++ .expect("install_comfyui ignores an existing venv");++ let pep_at = install_body++ .find("is_pep668_protected")++ .expect("the PEP 668 branch");++ assert!(++ venv_at < pep_at,++ "the venv is only considered after the PEP 668 branch"++ );++ }++++ // ── Ticket 003: jeder Python-Start setzt die Kodierung ─────────────────++++ #[test]++ fn every_python_start_in_this_tree_goes_through_python_command() {++ // anglefire (Ticket 003, 03.09.): sein Windows-Benutzer heisst++ // "1 בוגר", also stehen in jedem Pfad, den ein Kind druckt, Zeichen++ // ausserhalb der alten Codepage. Genau eine Startstelle hat sich davor++ // geschuetzt, run_import_probe_bounded, und ihre Begruendung gilt++ // woertlich fuer jede andere: ein Python-Kind mit umgeleiteter Ausgabe++ // kodiert unter Windows mit der alten Codepage, und ein Text mit einem++ // Zeichen ausserhalb von ASCII bricht den Lauf dann mit einem++ // UnicodeEncodeError ab. Fuenf von sechs Stellen waren ungeschuetzt,++ // darunter beide pip-Laeufe, die am meisten Pfade drucken.++ let mut daneben: Vec<String> = Vec::new();++ let mut ueber_die_hilfe = 0usize;++ for (name, src) in BAUM {++ let src = ausgeliefert(src);++ ueber_die_hilfe += src.matches("python_command(").count();++ for line in src.lines() {++ let Some(at) = line.find("Command::new(") else {++ continue;++ };++ let rest = &line[at + "Command::new(".len()..];++ let arg = rest.split(')').next().unwrap_or(rest).to_ascii_lowercase();++ if arg.contains("python") || arg.contains("pip") {++ daneben.push(format!("{name}: {}", line.trim()));++ }++ }++ // Und niemand setzt die beiden Variablen noch einmal von Hand:++ // zwei Pfade, einer gepflegt, ist genau die Krankheit dieses Falls.++ for var in ["PYTHONIOENCODING", "PYTHONUTF8"] {++ assert!(++ !src.contains(var),++ "{var} wird in {name} von Hand gesetzt statt in python_command",++ );++ }++ }++ assert!(++ daneben.is_empty(),++ "diese Python-Starts gehen an python_command vorbei und laufen ohne \++ PYTHONIOENCODING/PYTHONUTF8:\n{}",++ daneben.join("\n"),++ );++ // Der Waechter muss die Starts auch wirklich sehen: die Hilfsfunktion++ // wird oft genug benutzt, dass ein stilles Zurueckdrehen auffaellt.++ assert!(++ ueber_die_hilfe >= 8,++ "es gibt weniger Python-Starts ueber die Hilfsfunktion als erwartet \++ ({ueber_die_hilfe}), wurde einer wieder direkt gebaut?",++ );++ }++}diff --cc src-tauri/src/commands/install/ollama.rsindex 00000000,836b2e6c..300a9ca4mode 000000,100644..100644--- a/src-tauri/src/commands/install/ollama.rs+++ b/src-tauri/src/commands/install/ollama.rs@@@ -1,0 -1,452 +1,458 @@@+ //! Ollama installieren und den Dienst danach am Leben lassen.+ //!+ //! Der geteilte Zustand ist zweigeteilt, und beide Hälften erklären, warum+ //! dieses Modul so geschnitten ist. Die eine ist der `InstallState` für+ //! Ollama, in den alle drei Plattformwege erzählen und den+ //! `install_ollama_status` ausliest. Die andere ist der Prozessschlitz für+ //! `ollama serve`: der Dienst, den wir starten, gehört uns, also muss sein+ //! Handle dort landen, wo das App-Ende ihn wieder einsammelt.+ //!+ //! Genau daran war der Fehler. Alle drei Wege starteten `serve` von Hand und+ //! ließen das `Child` in der nächsten Zeile fallen — womit die Lesenden der+ //! Pipes zugingen und der Daemon an seiner ersten Logzeile starb. Deshalb+ //! gibt es hier genau EINEN Weg, `serve` zu starten, und alle drei+ //! Plattformzweige gehen durch ihn.+ //!+ //! Die Plattformzweige selbst sind der Rest: Windows lädt und führt aus,+ //! Linux verweist auf den Paketmanager (die Release-Tarballs sind mehrere GB+ //! groß und gehören nicht hinter einen Installationsknopf), macOS auf die+ //! signierte App. Was sie eint, ist der Schluss — starten und warten, ob die+ //! API antwortet.++ use std::process::{Command, Stdio};+ use std::sync::{Arc, Mutex};++ #[cfg(target_os = "windows")]+ use std::fs;+ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::{Manager, State};+ use tracing::info;+ #[cfg(target_os = "windows")]+ use tracing::error;++ use crate::state::{AppState, InstallState};++ #[cfg(target_os = "windows")]+ use super::download::{download_file_blocking, verify_downloaded_installer};+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ── Ollama Install ──────────────────────────────────────────────────────────++ #[tauri::command]+ pub fn install_ollama(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let mut install = state.ollama_install.lock().unwrap();+ if install.status == "downloading" || install.status == "installing" || install.status == "starting" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }++ install.status = "downloading".to_string();+ install.logs.clear();+ install.download_progress = 0;+ install.download_total = 0;+ install.download_speed = 0.0;+ install.logs.push("Downloading Ollama installer...".to_string());+ drop(install);++ info!("ollama install start");++ let ollama_state = state.ollama_install.clone();+ // OI-4: the serve we are about to spawn belongs to LU, so its handle goes+ // into the same slot `start_ollama` uses and gets reaped on quit.+ let serve_slot = state.ollama_process.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = ollama_state.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ // Bug G (discovered during 2026-05-17 Arch live test): pre-fix+ // install_ollama unconditionally downloaded OllamaSetup.exe (a+ // Windows-only NSIS installer) and tried to execute it with /S.+ // On Linux that fails with "Exec format error" and on macOS with+ // a similar binary-format mismatch — the user sees a cryptic+ // install failure with no path forward. Dispatch by platform.+ #[cfg(target_os = "windows")]+ {+ install_ollama_windows_impl(&ollama_state, &serve_slot, update);+ }+ #[cfg(target_os = "linux")]+ {+ install_ollama_linux_impl(&ollama_state, &serve_slot, update);+ }+ #[cfg(target_os = "macos")]+ {+ install_ollama_macos_impl(&ollama_state, &serve_slot, update);+ }+ });++ Ok(serde_json::json!({"status": "downloading"}))+ }++ /// Start `ollama serve` so that it SURVIVES the installer, and hand the child+ /// to the slot that reaps it on quit.+ ///+ /// OI-4: all three install paths used to do this by hand as+ /// `Command::new("ollama").arg("serve").stdout(piped).stderr(piped).spawn()`+ /// with the returned `Child` dropped on the next line. Dropping a `Child`+ /// closes the read ends of both pipes, so the very first line Ollama logs+ /// gets EPIPE / SIGPIPE and the daemon dies seconds after we started it. The+ /// install then waited 30 s, reported "installed but not responding" and told+ /// the user to go run `ollama serve` in a terminal themselves — for a daemon+ /// that had been alive and was killed by us.+ ///+ /// `Stdio::null()` on all three handles is the fix and it is also what the+ /// rest of the repo already does: `process::start_ollama` and+ /// `auto_start_ollama` have spawned it this way since kj103x's orphan report.+ /// Following that pattern to the end means keeping the `Child` (so a quit+ /// reaps it instead of orphaning a daemon we started) and registering the pid+ /// with the kill-on-close job on Windows.+ fn spawn_ollama_serve(slot: &Arc<Mutex<Option<std::process::Child>>>) -> std::io::Result<()> {+ let mut cmd = Command::new("ollama");+ cmd.arg("serve")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ let child = cmd.spawn()?;+ crate::commands::process::tie_child_to_app_lifetime(child.id());+ if let Ok(mut g) = slot.lock() {+ // Whatever was in the slot is a handle to a process we no longer+ // manage; replacing it would leak the old one, so reap it first.+ if let Some(mut old) = g.take() {+ let _ = old.kill();+ let _ = old.wait();+ }+ *g = Some(child);+ }+ Ok(())+ }++ /// Wait for Ollama HTTP API to respond on the default port (best-effort+ /// shared startup probe used after every platform-specific install path).+ fn wait_for_ollama_ready() -> bool {+ let client = reqwest::blocking::Client::builder()+ .timeout(std::time::Duration::from_secs(3))+ .build()+ .unwrap_or_default();+ for i in 0..15 {+ std::thread::sleep(std::time::Duration::from_secs(2));+ match client.get("http://localhost:11434/api/tags").send() {+ Ok(res) if res.status().is_success() => return true,+ _ => println!("[Ollama] Not ready yet, attempt {}/15", i + 1),+ }+ }+ false+ }++ #[cfg(target_os = "windows")]+ fn install_ollama_windows_impl<F: Fn(&str, &str)>(+ ollama_state: &Arc<Mutex<InstallState>>,+ serve_slot: &Arc<Mutex<Option<std::process::Child>>>,+ update: F,+ ) {+ let temp_dir = std::env::temp_dir();+ let installer_path = temp_dir.join("OllamaSetup.exe");+ println!("[Ollama] Downloading OllamaSetup.exe...");+ if let Err(e) = download_file_blocking(+ "https://ollama.com/download/OllamaSetup.exe",+ &installer_path,+ ollama_state,+ ) {+ update("error", &format!("Download failed: {}", e));+ return;+ }+ // OI-8: verified before it is executed. Ollama's URL always serves the+ // current release, so there is no immutable digest to pin here — the size+ // and Authenticode checks are the whole answer available.+ if let Err(e) = verify_downloaded_installer(&installer_path, None, None, "Ollama") {+ let _ = fs::remove_file(&installer_path);+ error!(error = %e, "refused to execute an unverified Ollama installer");+ update("error", &e);+ return;+ }+ update("installing", "Download complete. Installing Ollama...");+ let mut cmd = Command::new(&installer_path);+ cmd.arg("/S");+ cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(o) => {+ let code = o.status.code().unwrap_or(-1);+ update("starting", &format!("Installer finished (code {}). Starting Ollama...", code));+ }+ Err(e) => {- update("error", &format!("Could not run installer: {}", e));++ update("error", &format!("Could not run installer: {}", os_error::english(&e)));+ return;+ }+ }+ let _ = fs::remove_file(&installer_path);+ if let Err(e) = spawn_ollama_serve(serve_slot) {+ update(+ "error",+ &format!(+ "Ollama installed, but `ollama serve` could not be started: {}. Open a \+ terminal and run `ollama serve` to see what it says.",+ e+ ),+ );+ return;+ }+ update("starting", "Waiting for Ollama to start...");+ if wait_for_ollama_ready() {+ update("complete", "Ollama is ready!");+ } else {+ update("error", "Ollama installed but not responding. Try restarting the app.");+ }+ }++ #[cfg(target_os = "linux")]+ fn install_ollama_linux_impl<F: Fn(&str, &str)>(+ _ollama_state: &Arc<Mutex<InstallState>>,+ serve_slot: &Arc<Mutex<Option<std::process::Child>>>,+ update: F,+ ) {+ // If `ollama` is already on PATH (pacman -S ollama, manual install, etc.),+ // skip ahead to spawning the service.+ let already_installed = Command::new("which")+ .arg("ollama")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false);++ if !already_installed {+ // Bug G revisit (2026-05-17 live test on Arch VM): Ollama's GitHub+ // release assets changed format. The old `ollama-linux-amd64` raw+ // binary URL now returns 404 — current releases ship as+ // `ollama-linux-amd64.tar.zst` which bundles the CUDA runtime libs+ // (multi-GB tarball). Auto-downloading 2-3 GB from a desktop-app+ // install button isn't user-friendly, so we surface a clear distro-+ // specific install hint instead. Every modern Linux distro ships an+ // ollama package or accepts ollama.com/install.sh; pointing at the+ // right command beats a stuck 2-GB progress bar.+ let os_release = std::fs::read_to_string("/etc/os-release").unwrap_or_default();+ let suggestion = linux_ollama_install_hint(&os_release);+ update(+ "error",+ &format!(+ "Ollama auto-install on Linux isn't supported — current releases \+ are multi-GB tarballs with bundled CUDA libs that are too large \+ to fetch from an install button.\n\n\+ Install via your distro: {}\n\n\+ After install, click 'Re-detect' here.",+ suggestion+ ),+ );+ return;+ }++ // ollama is already on PATH — spawn it and poll the API.+ update("starting", "Ollama is already installed — starting service...");+ if let Err(e) = spawn_ollama_serve(serve_slot) {+ update(+ "error",- &format!("Could not start `ollama serve`: {}. Try running it in a terminal.", e),++ &format!(++ "Could not start `ollama serve`: {}. Try running it in a terminal.",++ crate::os_error::english(&e)++ ),+ );+ return;+ }++ update("starting", "Waiting for Ollama to start...");+ if wait_for_ollama_ready() {+ update("complete", "Ollama is ready!");+ } else {+ update(+ "error",+ "Ollama is installed but the API isn't responding on localhost:11434. \+ Open a terminal and run `ollama serve` manually to see the failure \+ message — common causes: another process already binding 11434, or \+ missing GPU drivers.",+ );+ }+ }++ /// Bug G revisit — distro-specific install command for `ollama`. Same parsing+ /// shape as `linux_python_install_hint` (ID + ID_LIKE tokens, quoted values+ /// handled). Falls back to ollama.com/install.sh for unknown distros.+ /// Dead off Linux: the only production caller is `install_ollama_linux_impl`,+ /// which is `#[cfg(target_os = "linux")]` as a whole. The function itself is+ /// left compiled everywhere so its distro table stays unit-tested here.+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+ pub fn linux_ollama_install_hint(os_release: &str) -> String {+ let mut families: Vec<String> = Vec::new();+ for line in os_release.lines() {+ let trimmed = line.trim();+ let (key, value) = match trimmed.split_once('=') {+ Some(kv) => kv,+ None => continue,+ };+ let key = key.trim().to_lowercase();+ if key != "id" && key != "id_like" {+ continue;+ }+ let value = value.trim().trim_matches('"').trim_matches('\'');+ for token in value.split_whitespace() {+ families.push(token.to_lowercase());+ }+ }+ let has = |needle: &str| families.iter().any(|f| f == needle);+ if has("arch") || has("manjaro") || has("endeavouros") || has("garuda") {+ "`sudo pacman -S ollama`".to_string()+ } else if has("debian") || has("ubuntu") || has("linuxmint") || has("pop") || has("elementary") {+ "`sudo apt install ollama` (Debian 12+ / Ubuntu 23.10+) or `curl -fsSL https://ollama.com/install.sh | sh`".to_string()+ } else if has("fedora") || has("rhel") || has("centos") || has("rocky") || has("almalinux") {+ "`curl -fsSL https://ollama.com/install.sh | sh`".to_string()+ } else if has("opensuse") || has("opensuse-tumbleweed") || has("opensuse-leap") || has("suse") {+ "`sudo zypper install ollama` (Tumbleweed) or `curl -fsSL https://ollama.com/install.sh | sh`".to_string()+ } else {+ "`curl -fsSL https://ollama.com/install.sh | sh` (official) or download manually from https://ollama.com/download/linux".to_string()+ }+ }++ #[cfg(target_os = "macos")]+ fn install_ollama_macos_impl<F: Fn(&str, &str)>(+ _ollama_state: &Arc<Mutex<InstallState>>,+ serve_slot: &Arc<Mutex<Option<std::process::Child>>>,+ update: F,+ ) {+ if Command::new("which").arg("ollama").output().map(|o| o.status.success()).unwrap_or(false) {+ update("starting", "Ollama already installed — starting service...");+ if let Err(e) = spawn_ollama_serve(serve_slot) {+ update(+ "error",- &format!("Could not start `ollama serve`: {}. Try running it in a terminal.", e),++ &format!(++ "Could not start `ollama serve`: {}. Try running it in a terminal.",++ crate::os_error::english(&e)++ ),+ );+ return;+ }+ if wait_for_ollama_ready() {+ update("complete", "Ollama is ready!");+ } else {+ update("error", "Ollama is installed but the API isn't responding. Try restarting Ollama.app.");+ }+ return;+ }+ // We don't auto-install on macOS because the official distribution is+ // the signed Ollama.app from ollama.com/download/mac. Surfacing a clear+ // pointer beats trying to script around macOS gatekeeper.+ update(+ "error",+ "On macOS, download Ollama.app from https://ollama.com/download/mac and \+ move it to /Applications, then come back here and click Re-detect.",+ );+ }++ // ASYNC + spawn_blocking: a SYNCHRONOUS Tauri command runs on the MAIN thread.+ // The State borrow cannot cross into the blocking pool, so the handle is+ // re-resolved there from the AppHandle (same pattern as engine.rs/whisper.rs).+ #[tauri::command]+ pub async fn install_ollama_status(app: tauri::AppHandle) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || {+ let state = app.state::<AppState>();+ install_ollama_status_blocking(&state)+ })+ .await+ .map_err(|e| format!("install_ollama_status task: {e}"))?+ }++ fn install_ollama_status_blocking(state: &AppState) -> Result<serde_json::Value, String> {+ let install = state.ollama_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ "download_progress": install.download_progress,+ "download_total": install.download_total,+ "download_speed": install.download_speed,+ }))+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ /// Ollama's URL always serves the current release, so pinning either its+ /// size or its digest would break the install on every Ollama release.+ /// Neither may be passed for it.+ #[test]+ fn the_moving_ollama_url_is_never_pinned() {+ const SRC: &str = include_str!("ollama.rs");+ assert!(+ SRC.contains(concat!("verify_downloaded_installer", "(&installer_path, None, None, \"Ollama\")")),+ "the Ollama installer path acquired a pin it cannot keep"+ );+ }++ // ── Bug G revisit — linux_ollama_install_hint distro detection ────────+ //+ // Bug G's original "auto-download raw binary" fix shipped broken because+ // Ollama removed the raw `ollama-linux-amd64` asset in late 2025 — current+ // releases ship as multi-GB tarballs with bundled CUDA libs. Auto-download+ // isn't user-friendly at that size, so we surface distro-specific install+ // commands instead. These tests pin the matrix.++ #[test]+ fn ollama_hint_arch_recommends_pacman_ollama() {+ let release = "NAME=\"Arch Linux\"\nID=arch\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("pacman -S ollama"), "got: {}", hint);+ }++ #[test]+ fn ollama_hint_manjaro_via_id_like_arch() {+ let release = "NAME=\"Manjaro\"\nID=manjaro\nID_LIKE=arch\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("pacman -S ollama"), "got: {}", hint);+ }++ #[test]+ fn ollama_hint_ubuntu_recommends_apt_or_install_sh() {+ let release = "NAME=\"Ubuntu\"\nID=ubuntu\nID_LIKE=debian\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("apt install ollama"), "got: {}", hint);+ assert!(hint.contains("install.sh"), "should also offer official installer, got: {}", hint);+ }++ #[test]+ fn ollama_hint_fedora_recommends_official_install_sh() {+ let release = "NAME=\"Fedora Linux\"\nID=fedora\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("install.sh"), "got: {}", hint);+ }++ #[test]+ fn ollama_hint_rocky_via_id_like_rhel() {+ let release = "NAME=\"Rocky Linux\"\nID=rocky\nID_LIKE=\"rhel centos fedora\"\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("install.sh"), "RHEL-family should get install.sh, got: {}", hint);+ }++ #[test]+ fn ollama_hint_opensuse_recommends_zypper_or_install_sh() {+ let release = "NAME=\"openSUSE Tumbleweed\"\nID=opensuse-tumbleweed\nID_LIKE=\"opensuse suse\"\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("zypper install ollama") || hint.contains("install.sh"), "got: {}", hint);+ }++ #[test]+ fn ollama_hint_unknown_distro_falls_back_to_install_sh() {+ let release = "NAME=\"Some Custom Distro\"\nID=mystery\n";+ let hint = linux_ollama_install_hint(release);+ assert!(hint.contains("install.sh") || hint.contains("ollama.com"), "got: {}", hint);+ }++ #[test]+ fn ollama_hint_empty_input_falls_back() {+ let hint = linux_ollama_install_hint("");+ assert!(hint.contains("install.sh") || hint.contains("ollama.com"));+ }++ }diff --cc src-tauri/src/commands/install/pip.rsindex 00000000,303a8b48..3f4bf62bmode 000000,100644..100644--- a/src-tauri/src/commands/install/pip.rs+++ b/src-tauri/src/commands/install/pip.rs@@@ -1,0 -1,821 +1,1397 @@@+ //! Ein pip-Lauf: durchführen, mitschreiben, wiederholen, deuten.+ //!+ //! Der geteilte Zustand ist der `InstallState` des jeweiligen Installers.+ //! Alles hier schreibt in dieselben drei Felder — `logs` für die Zeilen, die+ //! der Nutzer im Panel liest, und `download_progress`/`download_total`/+ //! `download_speed` für den Balken daneben. Deshalb liegen der Streaming-Lauf,+ //! das Zählen der angekündigten Wheel-Größen und das Auslesen der+ //! gelesenen Bytes des Kindprozesses zusammen: sie füllen ein und dieselbe+ //! Anzeige, und ein Wiederholungsversuch muss sie gemeinsam zurücksetzen,+ //! sonst zählt er dieselben Wheels ein zweites Mal.+ //!+ //! Die Fehlerdeutung gehört dazu und nicht woandershin: `is_transient_pip_error`+ //! entscheidet, ob überhaupt wiederholt wird, und `diagnose_pip_error_*`+ //! macht aus dem, was nach dem letzten Versuch übrig ist, einen Satz, den der+ //! Nutzer befolgen kann. Beide lesen denselben stderr-Text desselben Laufs.+ //!+ //! Was hier NICHT liegt: welche Pakete installiert werden. Das entscheidet+ //! `torch`, `voice` oder der Aufrufer — dieses Modul bekommt fertige+ //! Argumente und führt sie aus.++ use std::io::{BufRead, BufReader};-use std::process::{Command, Stdio};++use std::process::Stdio;+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+ use std::sync::{Arc, Mutex};+ use std::time::Instant;++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use crate::state::InstallState;++use crate::os_error;++use crate::python::python_command;++ use super::children::TrackedInstallerChild;+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ── pip helpers (issue #32: PyTorch / ComfyUI install reliability) ───────────++ /// Push a log line to the shared install state. Best-effort — silently+ /// no-ops if the mutex is poisoned (which only happens if a thread panicked+ /// while holding the lock; the install is already broken at that point).-fn push_install_log(state: &Arc<Mutex<InstallState>>, msg: &str) {++pub(super) fn push_install_log(state: &Arc<Mutex<InstallState>>, msg: &str) {+ if let Ok(mut s) = state.lock() {+ s.logs.push(msg.to_string());+ }+ }++ /// Detect pip errors that warrant an automatic retry with backoff.+ /// Conservative — only retries on errors caused by transient network+ /// conditions, not on auth, permission, disk-full, or python-side bugs.+ fn is_transient_pip_error(stderr: &str) -> bool {+ let lower = stderr.to_lowercase();+ lower.contains("403 ")+ || lower.contains("502 ")+ || lower.contains("503 ")+ || lower.contains("504 ")+ || lower.contains("429 ")+ || lower.contains("sslerror")+ || lower.contains("ssl: ")+ || lower.contains("readtimeouterror")+ || lower.contains("connecttimeouterror")+ || lower.contains("connectiontimeouterror")+ || lower.contains("connectionerror")+ || lower.contains("connectionreseterror")+ || lower.contains("connection reset")+ || lower.contains("connection aborted")+ || lower.contains("connection refused")+ || lower.contains("incompleteread")+ || lower.contains("temporary failure")+ || lower.contains("network is unreachable")+ || lower.contains("could not fetch")+ || lower.contains("read timed out")+ || lower.contains("eof occurred in violation of protocol")+ || lower.contains("max retries exceeded")+ }++ /// Turn raw pip stderr into a user-friendly hint with troubleshooting+ /// guidance. The first line of the returned string is a short diagnosis;+ /// the rest is the truncated original error for context.+ /// "Python 3.8.10 at C:\Python38\python.exe", or just the path when the+ /// interpreter will not say. Costs one process launch, which is fine on an+ /// error path and is the single fact that turns "no matching wheel" from a+ /// riddle into an instruction: willes0504 (Discord 2026-07-28) had a stray+ /// 3.8 first in PATH and needed a volunteer plus a day to find that out.+ fn interpreter_description(python_bin: &str) -> String {- let mut cmd = Command::new(python_bin);++ let mut cmd = python_command(python_bin);+ cmd.arg("--version");- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(out) => {+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ let version = text.trim().lines().next().unwrap_or("").trim().to_string();+ if version.is_empty() {+ python_bin.to_string()+ } else {+ format!("{version} at {python_bin}")+ }+ }+ Err(_) => python_bin.to_string(),+ }+ }++ pub(super) fn diagnose_pip_error(stderr: &str) -> String {+ diagnose_pip_error_for(stderr, None)+ }++ /// Same diagnosis, plus which interpreter produced it when the caller knows.+ /// Version-shaped failures are unanswerable without that line.-fn diagnose_pip_error_for(stderr: &str, python_bin: Option<&str>) -> String {++pub(super) fn diagnose_pip_error_for(stderr: &str, python_bin: Option<&str>) -> String {+ let base = diagnose_pip_error_inner(stderr);+ let needs_interpreter = {+ let lower = stderr.to_lowercase();+ lower.contains("could not find a version")+ || lower.contains("no matching distribution")+ || lower.contains("no module named")+ || lower.contains("modulenotfounderror")+ };+ match (needs_interpreter, python_bin) {+ (true, Some(bin)) => format!("{base}\n\nLU used {}.", interpreter_description(bin)),+ _ => base,+ }+ }++ fn diagnose_pip_error_inner(stderr: &str) -> String {- let lower = stderr.to_lowercase();+ let snippet: String = stderr.chars().take(400).collect();++ let hint = pip_failure_hint(pip_failure_kind(stderr), stderr);+- let hint = if lower.contains("externally-managed-environment")- || lower.contains("error: externally-managed")- {- "Your Python is PEP 668 protected (Arch Linux, Debian 12+, Fedora 38+, \- Ubuntu 23.04+ block system-wide pip installs by default). LU should have \- created a venv inside the ComfyUI folder automatically — if you see this \- error, the venv module is missing. Install it and retry:\n\- • Arch: sudo pacman -S python-virtualenv\n\- • Debian/Ubuntu: sudo apt install python3-venv\n\- • Fedora: sudo dnf install python3-virtualenv"++ if hint.is_empty() {++ snippet++ } else {++ format!("{}\n\n--- pip output ---\n{}", hint, snippet)++ }++}++++/// The plain form every existing caller uses: the diagnosis only.++pub fn pip_install_streaming_with_retry_cancellable(++ args: &[&str],++ python_bin: &str,++ max_attempts: u32,++ install_state: &Arc<Mutex<InstallState>>,++ cancel: Option<&Arc<AtomicBool>>,++) -> Result<(), String> {++ pip_install_streaming_with_retry_raw(args, python_bin, max_attempts, install_state, cancel)++ .map_err(|f| f.diagnosis)++}++++/// Bytes a pip "Downloading <thing> (<size>)" stdout line announces. pip++/// prints decimal units, kB means 1000 bytes. "Using cached" lines are not++/// network traffic and must not count.++pub(crate) fn parse_pip_download_size(line: &str) -> Option<u64> {++ let rest = line.trim().strip_prefix("Downloading ")?;++ let inner = rest[rest.rfind('(')? + 1..].strip_suffix(')')?;++ let mut parts = inner.split_whitespace();++ let num: f64 = parts.next()?.parse().ok()?;++ let unit = parts.next()?;++ if parts.next().is_some() {++ return None;++ }++ let factor = match unit {++ "bytes" | "B" => 1.0,++ "kB" => 1e3,++ "MB" => 1e6,++ "GB" => 1e9,++ _ => return None,++ };++ Some((num * factor).round() as u64)++}++++/// Cumulative bytes the process has read from files and sockets. pip++/// downloads in-process, so this is the live counter behind the progress++/// display next to the rebuild spinner. None where the platform has no++/// cheap probe and on any probe error; the caller then keeps the plain++/// spinner instead of guessing.++#[cfg(target_os = "windows")]++pub(crate) fn process_read_bytes(pid: u32) -> Option<u64> {++ #[repr(C)]++ struct IoCounters {++ read_ops: u64,++ write_ops: u64,++ other_ops: u64,++ read_bytes: u64,++ write_bytes: u64,++ other_bytes: u64,++ }++ #[link(name = "kernel32")]++ extern "system" {++ fn OpenProcess(access: u32, inherit: i32, pid: u32) -> isize;++ fn GetProcessIoCounters(handle: isize, counters: *mut IoCounters) -> i32;++ fn CloseHandle(handle: isize) -> i32;++ }++ const PROCESS_QUERY_INFORMATION: u32 = 0x0400;++ unsafe {++ let handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);++ if handle == 0 {++ return None;++ }++ let mut counters = std::mem::zeroed::<IoCounters>();++ let ok = GetProcessIoCounters(handle, &mut counters);++ CloseHandle(handle);++ (ok != 0).then_some(counters.read_bytes)++ }++}++++#[cfg(target_os = "linux")]++pub(crate) fn process_read_bytes(pid: u32) -> Option<u64> {++ std::fs::read_to_string(format!("/proc/{}/io", pid))++ .ok()?++ .lines()++ .find_map(|l| l.strip_prefix("rchar:"))++ .and_then(|v| v.trim().parse().ok())++}++++#[cfg(not(any(target_os = "windows", target_os = "linux")))]++pub(crate) fn process_read_bytes(_pid: u32) -> Option<u64> {++ None++}++++// ── tests (issue #32: PyTorch / ComfyUI install reliability) ────────────────++++/// The Visual C++ runtime files a PyTorch wheel loads and that Windows does++/// not ship on its own. Named rather than guessed: the whole point of the++/// diagnosis is to tell the customer which file Windows went looking for.++/// A3 (falconbob_20415, anglefire, hypocritical_rj, petermanmancusso,++/// jamiet99uk, Discord 2026-08-26 to 2026-09-02): "VCOMP140.DLL was not++/// found" and "[WinError 1114] ... c10.dll" were shown to five customers as++/// a raw crash with no sentence attached.++pub(crate) const VC_RUNTIME_DLLS: &[&str] = &[++ "vcomp140.dll",++ "vcomp140_1.dll",++ "vcruntime140.dll",++ "vcruntime140_1.dll",++ "msvcp140.dll",++ "msvcp140_1.dll",++ "concrt140.dll",++];++++/// Where Microsoft publishes the current x64 redistributable. The page is++/// version free on purpose: linking a numbered installer would pin a version++/// that goes stale the moment Microsoft ships the next one.++pub(crate) const VC_REDIST_PAGE: &str = "https://learn.microsoft.com/cpp/windows/latest-supported-vc-redist";++++/// The wording Windows and Python use when a library is not there.++///++/// `winerror` carries the weight on a non English Windows: the bracketed code++/// is not localised, while the sentence after it is. Everything else here is++/// an English phrase and is only ever a second chance.++fn reads_as_missing(lower: &str) -> bool {++ // R1: a file that is THERE and refused, or THERE and locked, is not a file++ // that is absent. `winerror` alone would read both as missing, and pip++ // names the blocked path in the same line: "[WinError 5] Access is denied:++ // '...\\torch\\lib\\msvcp140.dll'". That sent the customer after a++ // redistributable they already have, and it cost them the --user escape,++ // because the permission arm never saw the failure.++ if reads_as_refused(lower) {++ return false;++ }++ lower.contains("winerror")++ || lower.contains("not found")++ || lower.contains("could not be found")++ || lower.contains("error loading")++ || lower.contains("dll load failed")++ || lower.contains("cannot open shared object file")++}++++/// A file the process may not write, or may not touch because something else++/// holds it. Both are answered by installing somewhere else, which is what the++/// per user site is for.++fn reads_as_refused(lower: &str) -> bool {++ lower.contains("access is denied")++ || lower.contains("permission denied")++ || lower.contains("winerror 5]")++ || lower.contains("winerror 32]")++ || lower.contains("errno 13")++ || lower.contains("used by another process")++}++++/// The Visual C++ runtime file a failure names, when it names one.++///++/// Asked PER LINE, not over the whole log. `torch\lib` ships msvcp140.dll and++/// vcomp140.dll itself, so any log that lists that directory mentions both++/// names; a whole log that also contains the word "missing" somewhere else++/// would otherwise be read as a missing runtime.++pub(crate) fn missing_runtime_library(text: &str) -> Option<&'static str> {++ for raw in text.lines() {++ let line = raw.to_ascii_lowercase();++ let Some(dll) = VC_RUNTIME_DLLS.iter().copied().find(|d| line.contains(d)) else {++ continue;++ };++ if reads_as_missing(&line) {++ return Some(dll);++ }++ }++ None++}++++/// What went wrong, decided once and reused. The trainer's setup step reads++/// the same verdict, which is how A2 stage one gets fixed: every failure++/// there was dressed as "check that you are online", including the ones that++/// had nothing to do with the network.++#[derive(Debug, Clone, Copy, PartialEq, Eq)]++pub(crate) enum PipFailureKind {++ ExternallyManaged,++ PythonWithoutSsl,++ MissingRuntimeLibrary,++ NativeLoadFailure,++ TorchWithoutGpuSupport,++ Ssl,++ Forbidden,++ RateLimited,++ Timeout,++ Network,++ DiskFull,++ Permission,++ PipBroken,++ NoMatchingWheel,++ Unknown,++}++++/// Classify raw pip / interpreter output.++///++/// Order matters twice. The native library arms sit before the broad++/// `contains("connection")` and permission arms, because a Windows DLL message++/// carries words those would otherwise swallow. And the disk and PEP 668 arms++/// sit before the native ones, because a rollback on a full drive prints a++/// `Moving to ...torch\lib\....dll` line for every file it moves.++pub(crate) fn pip_failure_kind(text: &str) -> PipFailureKind {++ let lower = text.to_lowercase();++ if lower.contains("externally-managed-environment") || lower.contains("error: externally-managed") {++ PipFailureKind::ExternallyManaged+ } else if lower.contains("ssl module in python is not available") {- // numbrain (Discord, 2026-08-02): a pyenv/source-built python without- // the _ssl extension can't reach pypi AT ALL, and the generic SSL hint- // below (antivirus/clock) sent him in the wrong direction.- "This Python was built without the ssl module, so pip cannot reach \- pypi.org at all. Use your distro's regular python3 (it ships with \- ssl): check with python3 -c \"import ssl\" — if that fails, \- reinstall python3 via your package manager (pyenv builds need the \- OpenSSL headers installed first, e.g. libssl-dev / openssl-devel), \- then retry."++ PipFailureKind::PythonWithoutSsl++ // Before the native arms: a full disk rolls torch back file by file, and++ // every one of those lines names a DLL under torch\lib.++ } else if lower.contains("no space") || lower.contains("errno 28") {++ PipFailureKind::DiskFull++ // R1, and for the same reason as the disk arm above it: pip names the++ // blocked file in the message, and under Program Files that file is++ // regularly one of the runtime DLLs torch ships.++ } else if is_permission_denied_pip_error(text) {++ PipFailureKind::Permission++ } else if missing_runtime_library(text).is_some() {++ PipFailureKind::MissingRuntimeLibrary++ } else if lower.contains("winerror 1114")++ || lower.contains("winerror 126")++ || lower.contains("winerror 127")++ || lower.contains("dll load failed")++ || lower.contains("initialization routine failed")++ || lower.contains("0xc0000005")++ || lower.contains("exception_access_violation")++ {++ PipFailureKind::NativeLoadFailure++ } else if lower.contains("torch not compiled with cuda enabled")++ || lower.contains("no kernel image is available")++ {++ PipFailureKind::TorchWithoutGpuSupport+ } else if lower.contains("ssl") {- "SSL error reaching pypi.org. Often caused by an antivirus / firewall \- intercepting TLS, or a stale system clock. Disable TLS interception \- for python.exe, fix the system clock, then retry."++ PipFailureKind::Ssl+ } else if lower.contains("403 ") {- "HTTP 403 from pypi.org or pytorch.org. The mirror may be blocked on \- your network. Try a different network or VPN, then retry."++ PipFailureKind::Forbidden+ } else if lower.contains("429 ") {- "Rate limited (HTTP 429). Wait a few minutes and retry."++ PipFailureKind::RateLimited+ } else if lower.contains("timeout") || lower.contains("timed out") {- "Network timeout. Slow connection or congested mirror. Retry on a \- faster network, or run the install during off-peak hours."++ PipFailureKind::Timeout+ } else if lower.contains("connection") {- "Connection error. Check internet connectivity, restart the app, \- and retry."- } else if lower.contains("no space") || lower.contains("errno 28") {- "Out of disk space. PyTorch + dependencies need ~5 GB free. Free up \- space and retry."- } else if lower.contains("permission") || lower.contains("errno 13") {- "Permission denied. Make sure no other process is using Python, then \- retry. On Windows: close any open Python REPLs / Jupyter / IDE \- debuggers."++ PipFailureKind::Network+ } else if lower.contains("no module named") || lower.contains("modulenotfounderror") {- "Python install is missing pip or is broken. Reinstall Python 3.10+ \- from python.org with 'Add to PATH' checked."++ PipFailureKind::PipBroken+ } else if lower.contains("could not find a version") {- "No matching wheel for your Python version. ComfyUI needs Python \- 3.10, 3.11, or 3.12. Reinstall a supported Python version."++ PipFailureKind::NoMatchingWheel+ } else {- ""- };++ PipFailureKind::Unknown++ }++}+- if hint.is_empty() {- snippet- } else {- format!("{}\n\n--- pip output ---\n{}", hint, snippet)++/// The sentence that belongs to a verdict. Empty for `Unknown`, where the++/// caller falls back to quoting the log.++pub(crate) fn pip_failure_hint(kind: PipFailureKind, text: &str) -> String {++ match kind {++ PipFailureKind::ExternallyManaged =>++ "Your Python is PEP 668 protected (Arch Linux, Debian 12+, Fedora 38+, \++ Ubuntu 23.04+ block system-wide pip installs by default). LU should have \++ created a venv inside the ComfyUI folder automatically. If you see this \++ error, the venv module is missing. Install it and retry:\n\++ • Arch: sudo pacman -S python-virtualenv\n\++ • Debian/Ubuntu: sudo apt install python3-venv\n\++ • Fedora: sudo dnf install python3-virtualenv".to_string(),++ // numbrain (Discord, 2026-08-02): a pyenv/source-built python without++ // the _ssl extension can't reach pypi AT ALL, and the generic SSL hint++ // below (antivirus/clock) sent him in the wrong direction.++ PipFailureKind::PythonWithoutSsl =>++ "This Python was built without the ssl module, so pip cannot reach \++ pypi.org at all. Use your distro's regular python3 (it ships with \++ ssl): check with python3 -c \"import ssl\". If that fails, \++ reinstall python3 via your package manager (pyenv builds need the \++ OpenSSL headers installed first, e.g. libssl-dev / openssl-devel), \++ then retry.".to_string(),++ // Ticket 007: beide Saetze endeten auf "then press Repair environment"++ // und widersprachen sich damit selbst, der erste sogar im selben Absatz++ // ("nothing pip does can fix this"). Ein Neubau des venv holt dieselben++ // Wheels an dieselbe Stelle; was fehlt, wohnt in Windows. falcon bob hat++ // die Reparatur gedrueckt, den Neubau abgewartet und stand vor derselben++ // Meldung. Der Satz sagt jetzt, was wirklich hilft.++ PipFailureKind::MissingRuntimeLibrary => {++ let dll = missing_runtime_library(text).unwrap_or("VCOMP140.DLL").to_uppercase();++ format!(++ "A Microsoft Visual C++ runtime library is missing on this machine: {dll}. \++ PyTorch loads it at import time and Windows does not install it on its own, \++ so nothing pip does can fix this. Install the current Visual C++ \++ Redistributable for x64 from {VC_REDIST_PAGE}, restart Windows, then start \++ ComfyUI again. Repair environment does not help here: the missing library \++ belongs to Windows, not to the ComfyUI folder."++ )++ }++ PipFailureKind::NativeLoadFailure => format!(++ "PyTorch is on disk but its native libraries will not load on this machine. \++ Two things cause that, in this order: the Microsoft Visual C++ Redistributable \++ for x64 is missing or out of date (install the current one from {VC_REDIST_PAGE} \++ and restart Windows), or the GPU driver is older than the CUDA build that was \++ installed (update the graphics driver). Do both, then start ComfyUI again. \++ Repair environment does not help here: it rebuilds the folder, and both of \++ these live outside it."++ ),++ PipFailureKind::TorchWithoutGpuSupport =>++ "The PyTorch in this environment carries no support for the card in this machine, \++ so it can only run on the processor. Press Repair environment: the rebuild probes \++ the card again and picks the matching wheels.".to_string(),++ PipFailureKind::Ssl =>++ "SSL error reaching pypi.org. Often caused by an antivirus / firewall \++ intercepting TLS, or a stale system clock. Disable TLS interception \++ for python.exe, fix the system clock, then retry.".to_string(),++ PipFailureKind::Forbidden =>++ "HTTP 403 from pypi.org or pytorch.org. The mirror may be blocked on \++ your network. Try a different network or VPN, then retry.".to_string(),++ PipFailureKind::RateLimited => "Rate limited (HTTP 429). Wait a few minutes and retry.".to_string(),++ PipFailureKind::Timeout =>++ "Network timeout. Slow connection or congested mirror. Retry on a \++ faster network, or run the install during off-peak hours.".to_string(),++ PipFailureKind::Network =>++ "Connection error. Check internet connectivity, restart the app, \++ and retry.".to_string(),++ PipFailureKind::DiskFull =>++ "Out of disk space. PyTorch + dependencies need ~5 GB free. Free up \++ space and retry.".to_string(),++ PipFailureKind::Permission =>++ "Permission denied. Make sure no other process is using Python, then \++ retry. On Windows: close any open Python REPLs / Jupyter / IDE \++ debuggers.".to_string(),++ PipFailureKind::PipBroken =>++ "Python install is missing pip or is broken. Reinstall Python 3.10+ \++ from python.org with 'Add to PATH' checked.".to_string(),++ PipFailureKind::NoMatchingWheel =>++ "No matching wheel for your Python version. ComfyUI needs Python \++ 3.10, 3.11, or 3.12. Reinstall a supported Python version.".to_string(),++ PipFailureKind::Unknown => String::new(),+ }+ }++ /// Run a `python -m pip install ...` command, streaming its stdout + stderr+ /// line-by-line into the install state's `logs` so the user sees live+ /// progress instead of a frozen UI. Retries up to `max_attempts` times on+ /// transient network errors with exponential backoff (10s, 30s, 90s).+ ///+ /// On non-transient errors or after exhausting retries, returns Err with a+ /// human-readable diagnosis prepended to the truncated original error.+ /// Streaming pip install with retry. When `cancel` is `Some`, polls the+ /// shared flag between line reads and waits, and kills the pip child on+ /// cancel — used by `install_comfyui` so the user's Cancel button+ /// (Bug #1 — techx69 v2.4.3) actually stops the running install instead+ /// of waiting for pip to finish naturally. When `cancel` is `None`, the+ /// install runs to completion as before — used by `install_python` and+ /// callers that haven't been wired up to the new cancel flow.-pub fn pip_install_streaming_with_retry_cancellable(++/// A pip run that failed: the sentence for the customer, and the raw stderr++/// behind it.++///++/// The two are not interchangeable. `diagnosis` carries a hint plus the FIRST++/// 400 characters of the log, so a decision taken on it (retry into the user++/// site, say) is taken on a string that may have cut the deciding line off.++pub(crate) struct PipFailure {++ pub(crate) diagnosis: String,++ pub(crate) stderr: String,++ /// How far the run got. A15 review: this used to be inferred from an empty++ /// `stderr`, which is true for a spawn that failed and equally true for a++ /// pip that ran, printed nothing and exited non-zero, and for a `try_wait`++ /// that failed on a live process. Two of those three were then reported as++ /// "pip could not be started", which is a lie the log cannot correct.++ pub(crate) stage: PipStage,++}++++/// How far a failed pip run got before it failed.++#[derive(Debug, Clone, Copy, PartialEq, Eq)]++pub(crate) enum PipStage {++ /// No process. The spawn failed, or the cancel arrived before pip was ever++ /// asked to start.++ NotStarted,++ /// pip was a live process. It may have exited non-zero, printed nothing, or++ /// refused to be reaped, but it ran.++ Ran,++}++++impl PipFailure {++ /// A failure with no pip log behind it. The stage says whether that is++ /// because pip never started or because it left nothing behind.++ fn bare(stage: PipStage, diagnosis: &str) -> Self {++ PipFailure { diagnosis: diagnosis.to_string(), stderr: String::new(), stage }++ }++}++++pub(crate) fn pip_install_streaming_with_retry_raw(+ args: &[&str],+ python_bin: &str,+ max_attempts: u32,+ install_state: &Arc<Mutex<InstallState>>,+ cancel: Option<&Arc<AtomicBool>>,-) -> Result<(), String> {++) -> Result<(), PipFailure> {+ let mut delay_seconds = 10u64;+ let mut last_stderr = String::new();++ for attempt in 1..=max_attempts {+ if cancel.as_ref().map(|c| c.load(Ordering::SeqCst)).unwrap_or(false) {- return Err("cancelled".to_string());++ return Err(PipFailure::bare(PipStage::NotStarted, "cancelled"));+ }+ if attempt > 1 {+ push_install_log(+ install_state,+ &format!(- "Transient network error — retry {}/{} after {}s wait...",++ "Transient network error, retry {}/{} after {}s wait...",+ attempt, max_attempts, delay_seconds+ ),+ );+ // Sleep in 1-second chunks so cancel reacts within ~1s.+ for _ in 0..delay_seconds {+ if cancel.as_ref().map(|c| c.load(Ordering::SeqCst)).unwrap_or(false) {- return Err("cancelled".to_string());++ return Err(PipFailure::bare(PipStage::NotStarted, "cancelled"));+ }+ std::thread::sleep(std::time::Duration::from_secs(1));+ }+ delay_seconds = (delay_seconds * 3).min(180);+ }++ // Fresh download stats per pip run; a retry must not double the+ // announced total by counting the same wheels twice.+ if let Ok(mut s) = install_state.lock() {+ s.download_progress = 0;+ s.download_total = 0;+ s.download_speed = 0.0;+ }+ let announced_total = Arc::new(AtomicU64::new(0));+- let mut cmd = Command::new(python_bin);++ let mut cmd = python_command(python_bin);+ cmd.args(args)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);++ let mut child = match cmd.spawn() {+ Ok(c) => c,- Err(e) => return Err(format!("Could not start pip ({}). Is Python on PATH?", e)),++ Err(e) => {++ return Err(PipFailure::bare(++ PipStage::NotStarted,++ &format!(++ "Could not start pip ({}). Is Python on PATH?",++ os_error::english(&e)++ ),++ ))++ }+ };+ // OI-7: registered for the whole run, so Cancel and Quit can reach+ // pip's build subprocesses and not just pip. Dropped on every exit+ // path below, including the `?`-free early returns and a panic.+ let _tracked = TrackedInstallerChild::register(child.id());++ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ let stderr_capture: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));++ // Stream stdout to install logs+ let stdout_state = install_state.clone();+ let announced = announced_total.clone();+ let stdout_handle = std::thread::spawn(move || {+ if let Some(out) = stdout {+ let reader = BufReader::new(out);+ for line in reader.lines().map_while(Result::ok) {+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ if let Some(bytes) = parse_pip_download_size(trimmed) {+ announced.fetch_add(bytes, Ordering::Relaxed);+ }+ if let Ok(mut s) = stdout_state.lock() {+ s.logs.push(trimmed.to_string());+ }+ }+ }+ }+ });++ // Stream stderr to install logs AND capture for retry decision+ let stderr_state = install_state.clone();+ let stderr_capture_clone = stderr_capture.clone();+ let stderr_handle = std::thread::spawn(move || {+ if let Some(err) = stderr {+ let reader = BufReader::new(err);+ for line in reader.lines().map_while(Result::ok) {+ if let Ok(mut buf) = stderr_capture_clone.lock() {+ buf.push_str(&line);+ buf.push('\n');+ }+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ if let Ok(mut s) = stderr_state.lock() {+ s.logs.push(trimmed.to_string());+ }+ }+ }+ }+ });++ // Poll for either the child to exit or the cancel flag to flip.+ // try_wait avoids blocking the cancel check; sleep keeps CPU idle.+ // Once a second the child's cumulative read bytes turn the announced+ // wheel sizes into progress and speed for the install status, which+ // the UI renders next to the rebuild spinner.+ let pid = child.id();+ let mut io_baseline: Option<(u64, Instant)> = None;+ let mut tick: u32 = 0;+ let exit_status = loop {+ if cancel.as_ref().map(|c| c.load(Ordering::SeqCst)).unwrap_or(false) {+ // Kill the child so pip doesn't keep saturating disk — the+ // TREE, not just pip: a source wheel that is mid-compile has+ // its own descendants, and `Child::kill` never reached them.+ crate::commands::shell::kill_tree(pid);+ let _ = child.kill();+ let _ = child.wait();+ let _ = stdout_handle.join();+ let _ = stderr_handle.join();- return Err("cancelled".to_string());++ return Err(PipFailure::bare(PipStage::Ran, "cancelled"));+ }+ match child.try_wait() {+ Ok(Some(s)) => break s,+ Ok(None) => {+ tick += 1;+ if tick.is_multiple_of(5) {+ let total = announced_total.load(Ordering::Relaxed);+ if total > 0 {+ if let Some(read) = process_read_bytes(pid) {+ let (base, since) =+ *io_baseline.get_or_insert((read, Instant::now()));+ let progress = read.saturating_sub(base).min(total);+ let elapsed = since.elapsed().as_secs_f64();+ let speed =+ if elapsed > 0.5 { progress as f64 / elapsed } else { 0.0 };+ if let Ok(mut s) = install_state.lock() {+ s.download_progress = progress;+ s.download_total = total;+ s.download_speed = speed;+ }+ }+ }+ }+ std::thread::sleep(std::time::Duration::from_millis(200));+ }- Err(e) => return Err(format!("pip wait failed: {}", e)),++ Err(e) => {++ return Err(PipFailure::bare(++ PipStage::Ran,++ &format!("pip wait failed: {}", os_error::english(&e)),++ ))++ }+ }+ };+ let _ = stdout_handle.join();+ let _ = stderr_handle.join();++ // The run is over either way; a frozen speed would read as a live+ // download next to a finished or failed step.+ if let Ok(mut s) = install_state.lock() {+ if exit_status.success() && s.download_total > 0 {+ s.download_progress = s.download_total;+ }+ s.download_speed = 0.0;+ }++ if exit_status.success() {+ return Ok(());+ }++ last_stderr = stderr_capture+ .lock()+ .map(|s| s.clone())+ .unwrap_or_default();++ if !is_transient_pip_error(&last_stderr) {- return Err(diagnose_pip_error_for(&last_stderr, Some(python_bin)));++ return Err(PipFailure {++ diagnosis: diagnose_pip_error_for(&last_stderr, Some(python_bin)),++ stderr: last_stderr,++ stage: PipStage::Ran,++ });+ }+ }+- Err(format!(- "Exhausted {} retry attempts for transient network errors.\n\n{}",- max_attempts,- diagnose_pip_error_for(&last_stderr, Some(python_bin))- ))++ Err(PipFailure {++ diagnosis: format!(++ "Exhausted {} retry attempts for transient network errors.\n\n{}",++ max_attempts,++ diagnose_pip_error_for(&last_stderr, Some(python_bin))++ ),++ stderr: last_stderr,++ stage: PipStage::Ran,++ })+ }+-/// Bytes a pip "Downloading <thing> (<size>)" stdout line announces. pip-/// prints decimal units, kB means 1000 bytes. "Using cached" lines are not-/// network traffic and must not count.-pub(crate) fn parse_pip_download_size(line: &str) -> Option<u64> {- let rest = line.trim().strip_prefix("Downloading ")?;- let inner = rest[rest.rfind('(')? + 1..].strip_suffix(')')?;- let mut parts = inner.split_whitespace();- let num: f64 = parts.next()?.parse().ok()?;- let unit = parts.next()?;- if parts.next().is_some() {- return None;++/// Why a requirements.txt could not be installed, in a few words.++///++/// A15, Windows Nachlauf 02.09.: a requirements.txt whose first line named a++/// package that does not exist made `pip install -r` fail, the run went on with++/// LU's own package list, and it ended on "Environment repaired" with nothing++/// said. The fallback itself is right, because a core whose file will not++/// resolve must not block a rebuild. The silence is not: the user is left with++/// a ComfyUI missing whatever that file asked for on top of our list.++pub(crate) fn requirements_failure_reason(pip_output: &str) -> &'static str {++ match pip_failure_kind(pip_output) {++ PipFailureKind::NoMatchingWheel => "pip found no installable version for a package it names",++ PipFailureKind::Network++ | PipFailureKind::Timeout++ | PipFailureKind::Ssl++ | PipFailureKind::Forbidden++ | PipFailureKind::RateLimited => "pip could not reach the package index",++ PipFailureKind::Permission => "pip was not allowed to write the packages",++ PipFailureKind::DiskFull => "the disk ran out of space",++ PipFailureKind::ExternallyManaged => "this Python refuses installs outside a venv",++ PipFailureKind::PipBroken | PipFailureKind::PythonWithoutSsl => {++ "pip in this environment is not usable"++ }++ PipFailureKind::MissingRuntimeLibrary++ | PipFailureKind::NativeLoadFailure++ | PipFailureKind::TorchWithoutGpuSupport => {++ "a package in it will not load on this machine"++ }++ PipFailureKind::Unknown => "pip exited with an error",+ }- let factor = match unit {- "bytes" | "B" => 1.0,- "kB" => 1e3,- "MB" => 1e6,- "GB" => 1e9,- _ => return None,- };- Some((num * factor).round() as u64)+ }+-/// Cumulative bytes the process has read from files and sockets. pip-/// downloads in-process, so this is the live counter behind the progress-/// display next to the rebuild spinner. None where the platform has no-/// cheap probe and on any probe error; the caller then keeps the plain-/// spinner instead of guessing.-#[cfg(target_os = "windows")]-pub(crate) fn process_read_bytes(pid: u32) -> Option<u64> {- #[repr(C)]- struct IoCounters {- read_ops: u64,- write_ops: u64,- other_ops: u64,- read_bytes: u64,- write_bytes: u64,- other_bytes: u64,- }- #[link(name = "kernel32")]- extern "system" {- fn OpenProcess(access: u32, inherit: i32, pid: u32) -> isize;- fn GetProcessIoCounters(handle: isize, counters: *mut IoCounters) -> i32;- fn CloseHandle(handle: isize) -> i32;- }- const PROCESS_QUERY_INFORMATION: u32 = 0x0400;- unsafe {- let handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);- if handle == 0 {- return None;- }- let mut counters = std::mem::zeroed::<IoCounters>();- let ok = GetProcessIoCounters(handle, &mut counters);- CloseHandle(handle);- (ok != 0).then_some(counters.read_bytes)++/// The same question asked of a whole pip failure rather than of its text.++///++/// The stage decides, not the emptiness of the log. A pip that never started++/// says so; a pip that ran is judged on what it printed, and a run that printed++/// nothing at all still exited with an error rather than failing to start.++pub(crate) fn requirements_failure_reason_for(f: &PipFailure) -> &'static str {++ match f.stage {++ PipStage::NotStarted => "pip could not be started",++ // It ran. Whatever it left behind is what decides, and a run that left++ // nothing behind still exited with an error.++ PipStage::Ran => requirements_failure_reason(&f.stderr),+ }+ }+-#[cfg(target_os = "linux")]-pub(crate) fn process_read_bytes(pid: u32) -> Option<u64> {- std::fs::read_to_string(format!("/proc/{}/io", pid))- .ok()?- .lines()- .find_map(|l| l.strip_prefix("rchar:"))- .and_then(|v| v.trim().parse().ok())++/// Whether a failed pip run should be tried again into the per user site.++///++/// Two conditions, and both matter. A venv REFUSES `--user` ("Can not perform++/// a '--user' install"), so retrying there swaps one failure for another. And++/// only a refused write is worth retrying at all: a network failure would just++/// fail again, twice as slowly.++pub(crate) fn should_retry_in_user_site(in_venv: bool, stderr: &str) -> bool {++ !in_venv && pip_failure_kind(stderr) == PipFailureKind::Permission+ }+-#[cfg(not(any(target_os = "windows", target_os = "linux")))]-pub(crate) fn process_read_bytes(_pid: u32) -> Option<u64> {- None++/// True iff a failed pip run died on filesystem permissions (admin-only++/// site-packages, e.g. python.org installs under Program Files on Windows).++/// Those are fixable by re-running the same install with `--user`.++pub(super) fn is_permission_denied_pip_error(output: &str) -> bool {++ let lower = output.to_lowercase();++ lower.contains("permission denied")++ || lower.contains("errno 13")++ || lower.contains("access is denied")++ || lower.contains("winerror 5")++ // A DLL another process still holds open is the same dead end with a++ // different code, and it has the same way out: install into the per++ // user site instead of into the one that is locked.++ || lower.contains("winerror 32]")++ || lower.contains("used by another process")+ }+-// ── tests (issue #32: PyTorch / ComfyUI install reliability) ────────────────++/// Die exakte pip-Ausgabe der Gegenprobe: ein erfundenes Paket auf Zeile 1++/// von ComfyUIs requirements.txt. Zwei Testmodule prüfen gegen genau diesen++/// Text, deshalb steht er einmal hier und nicht zweimal.++#[cfg(test)]++pub(super) const INVENTED_PACKAGE: &str = "ERROR: Could not find a version that satisfies the \++ requirement lu-gegenprobe-gibt-es-nicht-4711==9.9.9 (from versions: none)\n\++ ERROR: No matching distribution found for lu-gegenprobe-gibt-es-nicht-4711==9.9.9";++ #[cfg(test)]+ mod tests {+ use super::*;++ use super::super::comfy_job::requirements_fallback_log;++ // ── Download-Anzeige am Rebuilding-Spinner (#162) ───────────────────++ #[test]+ fn pip_download_size_parses_decimal_units() {+ assert_eq!(+ parse_pip_download_size(+ "Downloading torch-2.5.1+cu121-cp311-cp311-win_amd64.whl (2445.5 MB)"+ ),+ Some(2_445_500_000)+ );+ assert_eq!(+ parse_pip_download_size(+ "Downloading https://download.pytorch.org/whl/jinja2-3.1.6-py3-none-any.whl (134 kB)"+ ),+ Some(134_000)+ );+ assert_eq!(+ parse_pip_download_size("Downloading foo-1.0.tar.gz (1.2 GB)"),+ Some(1_200_000_000)+ );+ assert_eq!(+ parse_pip_download_size("Downloading mdurl-0.1.2-py3-none-any.whl.metadata (1.6 kB)"),+ Some(1_600)+ );+ }++ #[test]+ fn pip_download_size_ignores_lines_that_are_no_download() {+ // Negative controls: cache hits and chatter must not inflate the total.+ assert_eq!(+ parse_pip_download_size("Using cached torch-2.5.1-cp311-win_amd64.whl (2445.5 MB)"),+ None+ );+ assert_eq!(parse_pip_download_size("Installing collected packages: torch"), None);+ assert_eq!(parse_pip_download_size("Downloading build artifacts"), None);+ assert_eq!(+ parse_pip_download_size("Collecting torch (from -r requirements.txt (line 10))"),+ None+ );+ }++ // ── is_transient_pip_error ────────────────────────────────────────────++ #[test]+ fn transient_detects_403() {+ assert!(is_transient_pip_error(+ "ERROR: HTTP error 403 while getting https://files.pythonhosted.org/packages/.../torch.whl"+ ));+ }++ #[test]+ fn transient_detects_502() {+ assert!(is_transient_pip_error(+ "WARNING: Retrying after connection broken by 'NewConnectionError: 502 Bad Gateway'"+ ));+ }++ #[test]+ fn transient_detects_503() {+ assert!(is_transient_pip_error(+ "HTTP 503 service unavailable from pypi"+ ));+ }++ #[test]+ fn transient_detects_429_rate_limit() {+ assert!(is_transient_pip_error(+ "ERROR: 429 Too Many Requests"+ ));+ }++ #[test]+ fn transient_detects_ssl_error() {+ assert!(is_transient_pip_error(+ "SSLError(SSLZeroReturnError(...)) caused TLS handshake failure"+ ));+ }++ #[test]+ fn transient_detects_read_timeout() {+ assert!(is_transient_pip_error(+ "ReadTimeoutError(HTTPSConnectionPool(host='pypi.org', port=443): Read timed out.)"+ ));+ }++ #[test]+ fn transient_detects_connect_timeout() {+ assert!(is_transient_pip_error(+ "ConnectTimeoutError reaching pypi.org"+ ));+ }++ #[test]+ fn transient_detects_connection_reset() {+ assert!(is_transient_pip_error(+ "ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)"+ ));+ }++ #[test]+ fn transient_detects_connection_aborted() {+ assert!(is_transient_pip_error(+ "ConnectionError: ('Connection aborted.', RemoteDisconnected(...))"+ ));+ }++ #[test]+ fn transient_detects_connection_refused() {+ assert!(is_transient_pip_error(+ "ConnectionRefusedError: [Errno 111] Connection refused"+ ));+ }++ #[test]+ fn transient_detects_incomplete_read() {+ assert!(is_transient_pip_error(+ "IncompleteRead(0 bytes read, 1024 more expected)"+ ));+ }++ #[test]+ fn transient_detects_max_retries() {+ assert!(is_transient_pip_error(+ "Max retries exceeded with url: /packages/torch.whl"+ ));+ }++ #[test]+ fn transient_rejects_permission_error() {+ assert!(!is_transient_pip_error(+ "PermissionError: [Errno 13] Permission denied: 'C:\\\\Python\\\\Lib\\\\site-packages\\\\torch'"+ ));+ }++ #[test]+ fn transient_rejects_no_module_error() {+ assert!(!is_transient_pip_error(+ "ModuleNotFoundError: No module named 'pip'"+ ));+ }++ #[test]+ fn transient_rejects_disk_full() {+ assert!(!is_transient_pip_error(+ "OSError: [Errno 28] No space left on device"+ ));+ }++ #[test]+ fn transient_rejects_no_matching_distribution() {+ assert!(!is_transient_pip_error(+ "ERROR: Could not find a version that satisfies the requirement torch (from versions: none)"+ ));+ }++ #[test]+ fn transient_rejects_404_missing_package() {+ // 404 means the file genuinely doesn't exist — retry won't help.+ assert!(!is_transient_pip_error(+ "ERROR: HTTP error 404 while getting nonexistent-package.whl"+ ));+ }++ // ── diagnose_pip_error ────────────────────────────────────────────────++ #[test]+ fn diagnose_ssl_includes_antivirus_hint() {+ let msg = diagnose_pip_error("SSLError(SSLZeroReturnError(...))");+ let lower = msg.to_lowercase();+ assert!(lower.contains("antivirus") || lower.contains("firewall") || lower.contains("clock"));+ }++ #[test]+ fn a_python_without_ssl_is_named_not_blamed_on_antivirus() {+ // numbrain's exact pip wording (Discord 2026-08-02): the interpreter+ // itself has no _ssl, so the antivirus/clock hint is the wrong trail.+ let msg = diagnose_pip_error(+ "WARNING: pip is configured with locations that require TLS/SSL, \+ however the ssl module in Python is not available.",+ );+ let lower = msg.to_lowercase();+ assert!(lower.contains("built without the ssl module"));+ assert!(lower.contains("import ssl"));+ assert!(!lower.contains("antivirus"));+ }++ #[test]+ fn diagnose_403_suggests_vpn() {+ let msg = diagnose_pip_error("HTTP 403 from pytorch.org");+ let lower = msg.to_lowercase();+ assert!(lower.contains("vpn") || lower.contains("network") || lower.contains("blocked"));+ }++ #[test]+ fn diagnose_429_mentions_rate_limit() {+ let msg = diagnose_pip_error("HTTP 429 Too Many Requests");+ assert!(msg.to_lowercase().contains("rate limit"));+ }++ #[test]+ fn diagnose_disk_full_mentions_space() {+ let msg = diagnose_pip_error("OSError: [Errno 28] No space left on device");+ assert!(msg.to_lowercase().contains("disk") || msg.to_lowercase().contains("space"));+ }++ #[test]+ fn diagnose_permission_suggests_close_python() {+ let msg = diagnose_pip_error("PermissionError: [Errno 13] Permission denied");+ let lower = msg.to_lowercase();+ assert!(lower.contains("permission") && (lower.contains("python") || lower.contains("close") || lower.contains("ide")));+ }++ #[test]+ fn diagnose_no_module_suggests_python_reinstall() {+ let msg = diagnose_pip_error("ModuleNotFoundError: No module named 'pip'");+ let lower = msg.to_lowercase();+ assert!(lower.contains("python") && (lower.contains("reinstall") || lower.contains("3.10")));+ }++ #[test]+ fn diagnose_no_matching_version_suggests_python_version() {+ let msg = diagnose_pip_error("ERROR: Could not find a version that satisfies the requirement torch");+ let lower = msg.to_lowercase();+ assert!(lower.contains("python") || lower.contains("version") || lower.contains("3.10"));+ }++ /// willes0504 (Discord 2026-07-28) read "ComfyUI needs Python 3.10, 3.11+ /// or 3.12" while a stray 3.8 sat first in PATH. Naming the interpreter we+ /// actually used is the difference between a riddle and an instruction.+ #[test]+ fn a_version_failure_names_the_interpreter_lu_used() {+ let msg = diagnose_pip_error_for(+ "ERROR: Could not find a version that satisfies the requirement torch (from versions: none)",+ Some("/definitely/not/a/real/python-zzz"),+ );+ assert!(msg.contains("LU used"), "got: {msg}");+ assert!(msg.contains("/definitely/not/a/real/python-zzz"), "got: {msg}");+ }++ #[test]+ fn a_missing_module_failure_also_names_the_interpreter() {+ let msg = diagnose_pip_error_for(+ "ModuleNotFoundError: No module named 'encodings'",+ Some("/definitely/not/a/real/python-zzz"),+ );+ assert!(msg.contains("LU used"), "got: {msg}");+ }++ #[test]+ fn unrelated_failures_do_not_get_an_interpreter_line() {+ // A disk-full or permission problem says nothing about the version.+ let msg = diagnose_pip_error_for(+ "OSError: [Errno 28] No space left on device",+ Some("/definitely/not/a/real/python-zzz"),+ );+ assert!(!msg.contains("LU used"), "got: {msg}");+ }++ #[test]+ fn without_an_interpreter_the_diagnosis_is_unchanged() {+ let stderr = "ERROR: Could not find a version that satisfies the requirement torch";+ assert_eq!(diagnose_pip_error(stderr), diagnose_pip_error_for(stderr, None));+ }++ #[test]+ fn diagnose_unknown_error_falls_through_to_snippet() {+ let raw = "some_completely_random_error_we_haven_t_categorized";+ let msg = diagnose_pip_error(raw);+ assert!(msg.contains(raw));+ }++ #[test]+ fn diagnose_truncates_giant_stderr_to_400_chars_snippet_block() {+ let huge: String = "x".repeat(2000);+ let raw = format!("SSLError: {}", huge);+ let msg = diagnose_pip_error(&raw);+ // Snippet portion is bounded to 400 chars; full message includes hint + label+ // so it should be much shorter than the raw 2000-char input.+ assert!(msg.len() < 1200, "diagnose output was {} chars", msg.len());+ }++ // ── push_install_log ──────────────────────────────────────────────────++ #[test]+ fn push_install_log_appends_to_logs() {+ let state = Arc::new(Mutex::new(InstallState::default()));+ push_install_log(&state, "first");+ push_install_log(&state, "second");+ let s = state.lock().unwrap();+ assert_eq!(s.logs, vec!["first", "second"]);+ }++ #[test]+ fn push_install_log_does_not_clobber_status() {+ let state = Arc::new(Mutex::new(InstallState::default()));+ {+ let mut s = state.lock().unwrap();+ s.status = "installing".to_string();+ }+ push_install_log(&state, "log line");+ let s = state.lock().unwrap();+ assert_eq!(s.status, "installing");+ assert_eq!(s.logs, vec!["log line"]);+ }++ #[test]+ fn diagnose_externally_managed_mentions_venv() {+ let raw = "error: externally-managed-environment\n\+ × This environment is externally managed\n\+ ╰─> To install Python packages system-wide, try 'pacman -S python-xyz'";+ let msg = diagnose_pip_error(raw);+ let lower = msg.to_lowercase();+ assert!(+ lower.contains("pep 668") || lower.contains("externally") || lower.contains("venv"),+ "diagnose did not surface PEP 668 context: {}",+ msg+ );+ }++ #[test]+ fn diagnose_externally_managed_includes_distro_install_commands() {+ let raw = "error: externally-managed-environment";+ let msg = diagnose_pip_error(raw);+ let lower = msg.to_lowercase();+ // We want at least one of the platform-specific install commands so+ // the user has something to copy-paste instead of just an error.+ assert!(+ lower.contains("pacman") || lower.contains("apt") || lower.contains("dnf"),+ "diagnose did not include a distro install command: {}",+ msg+ );+ }++ #[test]+ fn diagnose_externally_managed_alt_format_matches() {+ // The exact wording on Arch 2026 is `error: externally-managed`+ // without the `-environment` suffix — make sure the matcher covers+ // both spellings.+ let raw = "error: externally-managed (pip blocked by PEP 668)";+ let msg = diagnose_pip_error(raw);+ let lower = msg.to_lowercase();+ assert!(+ lower.contains("pacman") || lower.contains("apt"),+ "diagnose missed the alt spelling: {}",+ msg+ );+ }++ #[test]+ fn transient_rejects_externally_managed() {+ // PEP 668 errors are deterministic — retrying without venv would+ // just loop forever. Must NOT be classified as transient.+ assert!(!is_transient_pip_error(+ "error: externally-managed-environment"+ ));+ }+++ /// A pip that never started is not a pip that exited with an error.++ #[test]++ fn a_pip_that_never_ran_is_not_reported_as_a_pip_that_failed() {++ let never_ran = PipFailure::bare(++ PipStage::NotStarted,++ "Could not start pip (not found). Is Python on PATH?",++ );++ assert_eq!(requirements_failure_reason_for(&never_ran), "pip could not be started");++ // Negative control: a real pip failure keeps its own classification and++ // does not fall into the "could not be started" arm.++ let really_failed = PipFailure {++ diagnosis: "whatever the hint says".to_string(),++ stderr: INVENTED_PACKAGE.to_string(),++ stage: PipStage::Ran,++ };++ assert_eq!(++ requirements_failure_reason_for(&really_failed),++ "pip found no installable version for a package it names"++ );++ }++++ /// The two cases the empty-stderr shortcut used to get wrong. Both are a++ /// pip that RAN, so neither may claim it could not be started.++ #[test]++ fn a_pip_that_ran_is_never_reported_as_one_that_could_not_start() {++ // The reaping failed on a live child. pip was there.++ let wait_failed = PipFailure::bare(PipStage::Ran, "pip wait failed: interrupted");++ assert_eq!(requirements_failure_reason_for(&wait_failed), "pip exited with an error");++ // And a silent non-zero exit: it ran, it failed, it printed nothing.++ let silent = PipFailure {++ diagnosis: String::new(),++ stderr: String::new(),++ stage: PipStage::Ran,++ };++ assert_eq!(requirements_failure_reason_for(&silent), "pip exited with an error");++ }++++ #[test]++ fn a_missing_visual_cpp_runtime_is_named_and_not_read_as_a_network_fault() {++ let text = "ImportError: VCOMP140.DLL was not found. Error loading \"C:\\ComfyUI\\venv\\Lib\\site-packages\\torch\\lib\\c10.dll\"";++ assert_eq!(pip_failure_kind(text), PipFailureKind::MissingRuntimeLibrary);++ assert_eq!(missing_runtime_library(text), Some("vcomp140.dll"));++ let hint = pip_failure_hint(PipFailureKind::MissingRuntimeLibrary, text);++ assert!(hint.contains("VCOMP140.DLL"), "the file is not named: {hint}");++ assert!(hint.contains(VC_REDIST_PAGE), "no way to get the runtime: {hint}");++ // The page is deliberately the version free one: a numbered installer++ // link goes stale the moment Microsoft ships the next build.++ assert!(!hint.contains("vc_redist"), "pins a numbered installer: {hint}");++ assert!(!hint.to_lowercase().contains("online"), "still blames the network: {hint}");++ }++++ #[test]++ fn a_dll_that_is_only_mentioned_is_not_a_missing_runtime() {++ // Negative control: torch\lib SHIPS msvcp140.dll and vcomp140.dll, so++ // any log that lists that directory names them. Asking the whole log++ // whether it also contains the word "missing" somewhere turned every++ // such log into a redistributable problem.++ let text = "Collecting torch\n\++ Installing collected packages: torch\n\++ Copying torch\\lib\\msvcp140.dll\n\++ ERROR: some other package is missing a build backend";++ assert_eq!(missing_runtime_library(text), None, "read the wrong line");++ assert_ne!(pip_failure_kind(text), PipFailureKind::MissingRuntimeLibrary);++ }++++ #[test]++ fn a_rollback_on_a_full_drive_is_a_disk_failure_not_a_dll_failure() {++ // The exact shape measured on the box on 2026-08-15: pip moves every++ // file aside before it replaces it, and each of those lines names a++ // DLL under torch\lib. The disk arm has to be asked first.++ let mut log = String::from(++ "ERROR: Could not install packages due to an OSError: [Errno 28] No space left on device\n",++ );++ for name in ["msvcp140.dll", "vcomp140.dll", "c10.dll"] {++ log.push_str(&format!("Moving to c:\\comfyui\\venv\\lib\\site-packages\\torch\\lib\\{name}\n"));++ }++ assert_eq!(pip_failure_kind(&log), PipFailureKind::DiskFull, "{log}");++ }++++ #[test]++ fn winerror_1114_reads_as_a_native_load_failure_not_a_connection_error() {++ let text = "OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading \"c10.dll\" or one of its dependencies.";++ assert_eq!(pip_failure_kind(text), PipFailureKind::NativeLoadFailure);++ let hint = pip_failure_hint(PipFailureKind::NativeLoadFailure, text);++ assert!(hint.contains(VC_REDIST_PAGE), "{hint}");++ assert!(hint.to_lowercase().contains("driver"), "the second cause is unnamed: {hint}");++ }++++ #[test]++ fn a_dll_line_in_another_language_is_still_recognised() {++ // The bracketed WinError code is not localised; the sentence after it++ // is. A German Windows says "Eine DLL-Initialisierungsroutine ist++ // fehlgeschlagen", which contains not one English word we matched on.++ let text = "OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden. VCOMP140.DLL";++ assert_eq!(missing_runtime_library(text), Some("vcomp140.dll"), "{text}");++ let text2 = "OSError: [WinError 1114] Eine DLL-Initialisierungsroutine ist fehlgeschlagen.";++ assert_eq!(pip_failure_kind(text2), PipFailureKind::NativeLoadFailure);++ }++++ #[test]++ fn an_access_violation_is_a_native_load_failure() {++ assert_eq!(++ pip_failure_kind("Process exited with code 0xC0000005"),++ PipFailureKind::NativeLoadFailure++ );++ }++++ #[test]++ fn a_torch_without_kernels_for_this_card_points_at_repair_not_at_the_network() {++ let text = "AssertionError: Torch not compiled with CUDA enabled";++ assert_eq!(pip_failure_kind(text), PipFailureKind::TorchWithoutGpuSupport);++ let hint = pip_failure_hint(PipFailureKind::TorchWithoutGpuSupport, text);++ assert!(hint.contains("Repair environment"), "{hint}");++ }++++ #[test]++ fn the_windows_wordings_for_a_refused_write_count_as_permission() {++ // python.org under Program Files answers with these, and neither one++ // contains the word permission. The custom node path has known them++ // since 2026-07-19; the classifier did not, so the ComfyUI++ // requirements step never took the --user escape.++ for text in [++ "ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\Program Files\\Python312\\Lib\\site-packages\\yaml'",++ "ERROR: Access is denied",++ "PermissionError: [Errno 13] Permission denied",++ ] {++ assert_eq!(pip_failure_kind(text), PipFailureKind::Permission, "{text}");++ }++ // Negative control: a plain HTTP failure must not become a permission++ // problem just because pip mentions access somewhere.++ assert_eq!(++ pip_failure_kind("ERROR: 403 Forbidden from pypi.org "),++ PipFailureKind::Forbidden++ );++ }++++ #[test]++ fn a_runtime_dll_that_is_blocked_is_a_permission_failure_not_a_missing_file() {++ // R1. pip names the file it could not write, and under Program Files++ // that file is regularly one of the DLLs torch ships. Reading those++ // two lines as a missing runtime sent the customer after a++ // redistributable they already have AND cost them the --user escape,++ // because should_retry_in_user_site never saw a permission failure.++ for line in [++ "ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\Program Files\\Python312\\Lib\\site-packages\\torch\\lib\\msvcp140.dll'",++ "ERROR: Could not install packages due to an OSError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Program Files\\Python312\\Lib\\site-packages\\torch\\lib\\vcomp140.dll'",++ ] {++ assert_eq!(pip_failure_kind(line), PipFailureKind::Permission, "{line}");++ assert_eq!(missing_runtime_library(line), None, "read a blocked file as an absent one: {line}");++ assert!(should_retry_in_user_site(false, line), "the escape is lost: {line}");++ let hint = pip_failure_hint(pip_failure_kind(line), line);++ assert!(!hint.contains(VC_REDIST_PAGE), "still sends them to microsoft.com: {hint}");++ }++ }++++ #[test]++ fn a_runtime_dll_that_is_really_absent_is_still_a_missing_file() {++ // Negative control for the arm above: the genuine case must not be++ // swept into the permission arm along with it.++ let line = "OSError: [WinError 126] The specified module could not be found. Error loading \"vcomp140.dll\"";++ assert_eq!(pip_failure_kind(line), PipFailureKind::MissingRuntimeLibrary, "{line}");++ assert_eq!(missing_runtime_library(line), Some("vcomp140.dll"));++ assert!(!should_retry_in_user_site(false, line), "a --user retry cannot install a runtime");++ assert!(pip_failure_hint(pip_failure_kind(line), line).contains(VC_REDIST_PAGE));++ }++++ #[test]++ fn the_old_verdicts_still_come_out_of_the_new_classifier() {++ // The rewrite must not move any existing case: these are the arms the++ // shipped diagnoses were built on.++ for (text, kind) in [++ ("error: externally-managed-environment", PipFailureKind::ExternallyManaged),++ ("the ssl module in Python is not available", PipFailureKind::PythonWithoutSsl),++ ("SSLError: certificate verify failed", PipFailureKind::Ssl),++ ("ERROR: 403 Forbidden ", PipFailureKind::Forbidden),++ ("ERROR: 429 Too Many Requests ", PipFailureKind::RateLimited),++ ("ReadTimeoutError: read timed out", PipFailureKind::Timeout),++ ("ConnectionResetError: connection reset by peer", PipFailureKind::Network),++ ("OSError: [Errno 28] No space left on device", PipFailureKind::DiskFull),++ ("PermissionError: [Errno 13] Permission denied", PipFailureKind::Permission),++ ("No module named pip", PipFailureKind::PipBroken),++ ("ERROR: Could not find a version that satisfies", PipFailureKind::NoMatchingWheel),++ ("something nobody has seen before", PipFailureKind::Unknown),++ ] {++ assert_eq!(pip_failure_kind(text), kind, "wrong verdict for {text:?}");++ }++ }++++++ #[test]++ fn a_requirements_file_pip_cannot_resolve_is_named_with_its_reason() {++ let reason = requirements_failure_reason(INVENTED_PACKAGE);++ assert_eq!(reason, "pip found no installable version for a package it names");++ let line = requirements_fallback_log("C:\\Users\\ddrob\\ComfyUI", reason);++ assert!(line.starts_with("requirements.txt in C:\\Users\\ddrob\\ComfyUI could not be used ("), "got: {line}");++ assert!(line.ends_with("installing LU's own package list instead."), "got: {line}");++ assert!(line.contains(reason), "got: {line}");++ }++++ /// Every pip failure gets a reason, and none of them reads as a sentence++ /// fragment inside "could not be used (...)".++ #[test]++ fn every_pip_failure_has_a_short_lowercase_reason() {++ for output in [++ INVENTED_PACKAGE,++ "ERROR: Connection broken: ConnectionResetError",++ "ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied",++ "OSError: [Errno 28] No space left on device",++ "error: externally-managed-environment",++ "read timed out",++ "",++ ] {++ let r = requirements_failure_reason(output);++ assert!(!r.is_empty());++ assert!(r.chars().next().unwrap().is_lowercase(), "capitalised: {r}");++ assert!(!r.ends_with('.'), "the reason carries its own full stop: {r}");++ }++ }++++ #[test]++ fn permission_predicate_matches_windows_and_unix_denials() {++ assert!(is_permission_denied_pip_error(++ "ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: 'C:\\\\Program Files\\\\Python311\\\\Lib\\\\site-packages\\\\onnxruntime'"++ ));++ assert!(is_permission_denied_pip_error(++ "PermissionError: [WinError 5] Access is denied"++ ));++ assert!(is_permission_denied_pip_error("EACCES: permission denied"));++ }++++ #[test]++ fn permission_predicate_rejects_other_pip_failures() {++ assert!(!is_permission_denied_pip_error(++ "error: externally-managed-environment"++ ));++ assert!(!is_permission_denied_pip_error(++ "ReadTimeoutError: HTTPSConnectionPool(host='pypi.org')"++ ));++ assert!(!is_permission_denied_pip_error(++ "ERROR: Could not find a version that satisfies the requirement onnxruntime-gpu"++ ));++ }+++ }diff --cc src-tauri/src/commands/install/python.rsindex 00000000,17b5cfbe..e08f05e2mode 000000,100644..100644--- a/src-tauri/src/commands/install/python.rs+++ b/src-tauri/src/commands/install/python.rs@@@ -1,0 -1,435 +1,436 @@@+ //! Einen systemweiten Python beschaffen, bevor irgendetwas anderes anfängt.+ //!+ //! Der geteilte Zustand sind zwei Schlitze im `AppState`, die zusammengehören:+ //! der `InstallState` für den Fortschritt und `python_bin` für das Ergebnis.+ //! Alle drei Befehle hier fassen beide an — die Installation füllt sie, die+ //! Statusabfrage liest den einen, und `python_check` löst den anderen neu auf,+ //! wenn er veraltet ist.+ //!+ //! Genau dieses Nachauflösen ist der Grund für die Naht. Auf einer frischen+ //! Windows-Kiste ist `python.exe` der Store-Platzhalter, der nichts tut außer+ //! mit Code 1 zu enden; wird während der Laufzeit ein echter Python+ //! nachinstalliert, muss der zwischengespeicherte Pfad aktualisiert werden,+ //! sonst meldet LU bis zum nächsten Start "kein Python gefunden". Diese+ //! Regel gilt für alle drei Befehle und für keinen außerhalb dieser Datei.+ //!+ //! `linux_python_install_hint` steht dabei, weil auf Linux gar nicht+ //! installiert wird: dort ist die einzige richtige Antwort der passende+ //! Befehl für die vorliegende Distribution.++ use std::io::{BufRead, BufReader};+ use std::process::{Command, Stdio};++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::State;+ use tracing::info;+++use crate::os_error;+ use crate::state::AppState;++ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ /// Bug I — Linux distro detection for the install_python error hint.+ /// Parses `/etc/os-release` line-by-line, collects `ID` and `ID_LIKE`+ /// tokens (stripping the quotes that systemd allows around multi-value+ /// fields like `ID_LIKE="rhel centos fedora"`), and returns a distro+ /// family install command. Pulled out so we can unit test the matching+ /// logic without writing to /etc on the test box.+ pub fn linux_python_install_hint(os_release: &str) -> String {+ // Collect family tokens from ID and ID_LIKE.+ let mut families: Vec<String> = Vec::new();+ for line in os_release.lines() {+ let trimmed = line.trim();+ let (key, value) = match trimmed.split_once('=') {+ Some(kv) => kv,+ None => continue,+ };+ let key = key.trim().to_lowercase();+ if key != "id" && key != "id_like" {+ continue;+ }+ // Strip surrounding quotes if present, then split on whitespace+ // (ID_LIKE often carries multiple space-separated tokens).+ let value = value.trim().trim_matches('"').trim_matches('\'');+ for token in value.split_whitespace() {+ families.push(token.to_lowercase());+ }+ }+ let has = |needle: &str| families.iter().any(|f| f == needle);++ if has("arch") || has("manjaro") || has("endeavouros") || has("garuda") {+ "`sudo pacman -S python python-pip`".to_string()+ } else if has("debian") || has("ubuntu") || has("linuxmint") || has("pop") || has("elementary") {+ "`sudo apt install python3 python3-pip python3-venv`".to_string()+ } else if has("fedora") || has("rhel") || has("centos") || has("rocky") || has("almalinux") {+ "`sudo dnf install python3 python3-pip`".to_string()+ } else if has("opensuse") || has("opensuse-tumbleweed") || has("opensuse-leap") || has("suse") || has("sles") {+ "`sudo zypper install python3 python3-pip`".to_string()+ } else {+ "your distro's package manager".to_string()+ }+ }++ // ── Python Auto-Install (P14: Plug-and-Play, blocking pre-req for ComfyUI) ──+ //+ // On a fresh Windows box `python.exe` is the Microsoft Store stub at+ // `%LOCALAPPDATA%\Microsoft\WindowsApps\python.exe` — it prints "Python was+ // not found, run without arguments to install from the Microsoft Store" and+ // exits 1. That kills `pip install torch ...` 200 ms in, leaves a half-cloned+ // ComfyUI dir on disk, and the user sees "ComfyUI not responding". The+ // only Plug-and-Play fix for newbies is to install Python ourselves; this is+ // what `install_python` does. Same shape as `install_ollama` /+ // `install_lmstudio`: kick off a background thread, surface status via a+ // shared `InstallState`, and re-resolve `python_bin` once it finishes so+ // subsequent `install_comfyui` calls find it without an app restart.++ #[tauri::command]+ pub fn install_python(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ // If Python is already there, short-circuit so the UI can skip the+ // install card and go straight to ComfyUI. is_real_python rejects+ // the empty sentinel and WindowsApps stub paths.+ {+ let current = state.python_bin.lock().unwrap().clone();+ if crate::python::is_real_python(¤t) {+ return Ok(serde_json::json!({"status": "already_installed", "path": current}));+ }+ }++ let mut install = state.python_install.lock().unwrap();+ if install.status == "downloading"+ || install.status == "installing"+ || install.status == "starting"+ {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }++ install.status = "installing".to_string();+ install.logs.clear();+ install.download_progress = 0;+ install.download_total = 0;+ install.download_speed = 0.0;+ install+ .logs+ .push("Installing Python 3.12 via winget (~30 MB)…".to_string());+ drop(install);++ info!("python install start");++ let py_state = state.python_install.clone();+ let py_bin_slot = state.python_bin.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = py_state.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ // Bug I (discovered during 2026-05-17 Arch live test): pre-fix+ // install_python unconditionally invoked `winget` which is+ // Windows-exclusive. On Linux that fails with "winget: command+ // not found" and the user gets stuck. In practice every modern+ // Linux distro ships Python in the base group so the install+ // button rarely needs to fire — but when it does, surfacing the+ // right distro-specific install command beats a cryptic spawn+ // error.+ if cfg!(target_os = "linux") {+ let os_release = std::fs::read_to_string("/etc/os-release").unwrap_or_default();+ let suggestion = linux_python_install_hint(&os_release);+ update(+ "error",+ &format!(+ "Python isn't installed system-wide. On Linux, install it via {} \+ then click Re-detect. (LU's auto-installer is Windows-only — on \+ Linux your package manager is the right tool.)",+ suggestion+ ),+ );+ }+ if cfg!(target_os = "macos") {+ update(+ "error",+ "Python isn't installed system-wide. On macOS, install it via \+ `brew install python` (Homebrew) or download Python 3.12+ from \+ https://www.python.org/downloads/macos/ then click Re-detect.",+ );+ }++ // ── The Windows path ────────────────────────────────────────────────+ //+ // Everything below is the winget install. It used to sit behind the two+ // `return`s above, which made rustc call it an `unreachable statement`+ // on macOS and Linux — correct about the control flow, and saying+ // nothing about the code: this is not dead code, it is the OTHER+ // platform's implementation.+ //+ // `if cfg!` and not `#[cfg]`, for the reason `test_support.rs` states at+ // its top: a `#[cfg]` would delete this whole branch from a macOS build,+ // and with it the type-checking of ~150 lines of Windows installer plus+ // the dozen helpers it is the only caller of (`sha256_file`,+ // `installer_size_verdict`, `windows_git_probe_from_output` …), which+ // would then read as dead code here. Compiled-and-never-taken keeps the+ // Windows half honest on the machine this is developed on.+ //+ // The condition is `not(linux or macos)` rather than `windows` so the+ // set of targets that run it is exactly the set that ran it before.+ if !cfg!(any(target_os = "linux", target_os = "macos")) {+ // Stream-friendly winget invocation. `--silent --accept-*-agreements`+ // drops the EULA prompts; without them winget will sit and wait for+ // user input forever inside our background thread. Python.Python.3.12+ // is the canonical winget id for the python.org installer (matches+ // `winget search python` top result).+ update("installing", "Running: winget install Python.Python.3.12 --silent --accept-package-agreements --accept-source-agreements");++ let mut cmd = Command::new("winget");+ cmd.args([+ "install",+ "Python.Python.3.12",+ "--silent",+ "--accept-package-agreements",+ "--accept-source-agreements",+ "--scope",+ "user",+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let child = match cmd.spawn() {+ Ok(c) => c,+ Err(e) => {+ update(+ "error",+ &format!(+ "Could not run winget: {}. winget ships with Windows 10/11 — \+ if it's missing, run 'Get App Installer' from the Microsoft \+ Store (free) and retry.",+ e+ ),+ );+ return;+ }+ };++ // Stream stdout + stderr line-by-line so the UI's log card animates+ // as winget extracts and installs (otherwise it freezes for 1–2 min).+ let mut child = child;+ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ let stdout_state = py_state.clone();+ let stdout_handle = std::thread::spawn(move || {+ if let Some(out) = stdout {+ let reader = BufReader::new(out);+ for line in reader.lines().map_while(Result::ok) {+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ if let Ok(mut s) = stdout_state.lock() {+ s.logs.push(trimmed.to_string());+ }+ }+ }+ }+ });+ let stderr_state = py_state.clone();+ let stderr_handle = std::thread::spawn(move || {+ if let Some(err) = stderr {+ let reader = BufReader::new(err);+ for line in reader.lines().map_while(Result::ok) {+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ if let Ok(mut s) = stderr_state.lock() {+ s.logs.push(trimmed.to_string());+ }+ }+ }+ }+ });++ let exit_status = match child.wait() {+ Ok(s) => s,+ Err(e) => {- update("error", &format!("winget wait failed: {}", e));++ update("error", &format!("winget wait failed: {}", os_error::english(&e)));+ return;+ }+ };+ let _ = stdout_handle.join();+ let _ = stderr_handle.join();++ if !exit_status.success() {+ // winget exit codes are HRESULT-shaped; -1978335189 (0x8A150011)+ // means "no upgrade applicable" which is fine if Python is+ // already present. Anything else is a real failure.+ let code = exit_status.code().unwrap_or(-1);+ // Re-resolve regardless: Python may already be on the box from+ // a previous install attempt that the original where-scan+ // missed (e.g. Add-to-PATH was unchecked).+ let resolved = crate::python::get_python_bin();+ if crate::python::is_real_python(&resolved) {+ if let Ok(mut slot) = py_bin_slot.lock() {+ *slot = resolved.clone();+ }+ update(+ "complete",+ &format!("Python ready (winget exit {} ignored, Python detected at {})", code, resolved),+ );+ return;+ }+ update(+ "error",+ &format!(+ "winget exited with code {}. Python was not detected after \+ install. Try installing manually from python.org with the \+ 'Add Python to PATH' checkbox on, then return here and \+ click Re-Scan.",+ code+ ),+ );+ return;+ }++ update("starting", "winget finished. Re-resolving Python…");++ // Give the freshly installed Python a moment to settle (winget can+ // signal completion before the file is fully linked into PATH on+ // some boxes), then re-resolve and persist.+ for attempt in 0..15 {+ std::thread::sleep(std::time::Duration::from_secs(1));+ let resolved = crate::python::get_python_bin();+ if crate::python::is_real_python(&resolved) {+ if let Ok(mut slot) = py_bin_slot.lock() {+ *slot = resolved.clone();+ }+ update(+ "complete",+ &format!("Python ready at {}", resolved),+ );+ return;+ }+ println!("[Python] post-install resolve attempt {}/15 — not yet on PATH", attempt + 1);+ }++ update(+ "error",+ "winget reported success but Python is still not on PATH. \+ Restart Locally Uncensored — sometimes Windows needs the new PATH \+ to take effect. If it still doesn't show up, install manually \+ from python.org with 'Add Python to PATH' on.",+ );+ }+ });++ Ok(serde_json::json!({"status": "installing"}))+ }++ #[tauri::command]+ pub fn install_python_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.python_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ "download_progress": install.download_progress,+ "download_total": install.download_total,+ "download_speed": install.download_speed,+ }))+ }++ /// Cheap synchronous probe: is there a real Python on the box? The frontend+ /// calls this before kicking off `install_comfyui` so it can decide whether+ /// to show the Python install step first. Returns the resolved path on+ /// success so the UI can display it ("Found Python at C:\\…").+ #[tauri::command]+ pub fn python_check(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let current = state.python_bin.lock().unwrap().clone();+ if crate::python::is_real_python(¤t) {+ return Ok(serde_json::json!({"available": true, "path": current}));+ }++ // The slot may have been empty at startup (fresh box) and Python may+ // have been installed since (e.g. via this same install_python flow on+ // another launch). Re-resolve as a refresh.+ let resolved = crate::python::get_python_bin();+ if crate::python::is_real_python(&resolved) {+ if let Ok(mut slot) = state.python_bin.lock() {+ *slot = resolved.clone();+ }+ Ok(serde_json::json!({"available": true, "path": resolved}))+ } else {+ Ok(serde_json::json!({"available": false, "path": null}))+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ // ── Bug I — linux_python_install_hint distro detection ────────────────++ #[test]+ fn linux_hint_arch_via_id_field() {+ let release = "NAME=\"Arch Linux\"\nID=arch\nID_LIKE=archlinux\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("pacman"), "got: {}", hint);+ assert!(hint.contains("python") && hint.contains("pip"));+ }++ #[test]+ fn linux_hint_manjaro_via_id_like_arch() {+ let release = "NAME=\"Manjaro\"\nID=manjaro\nID_LIKE=arch\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("pacman"), "Manjaro should map to Arch family, got: {}", hint);+ }++ #[test]+ fn linux_hint_ubuntu_via_id_like_debian() {+ let release = "NAME=\"Ubuntu\"\nID=ubuntu\nID_LIKE=debian\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("apt"), "got: {}", hint);+ assert!(hint.contains("python3"));+ }++ #[test]+ fn linux_hint_debian_via_id() {+ let release = "NAME=\"Debian GNU/Linux\"\nID=debian\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("apt"), "got: {}", hint);+ }++ #[test]+ fn linux_hint_fedora_via_id() {+ let release = "NAME=\"Fedora Linux\"\nID=fedora\nID_LIKE=\"fedora\"\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("dnf"), "got: {}", hint);+ }++ #[test]+ fn linux_hint_rocky_via_id_like_rhel() {+ let release = "NAME=\"Rocky Linux\"\nID=rocky\nID_LIKE=\"rhel centos fedora\"\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("dnf"), "RHEL-family should suggest dnf, got: {}", hint);+ }++ #[test]+ fn linux_hint_opensuse_via_id_like() {+ let release = "NAME=\"openSUSE Tumbleweed\"\nID=opensuse-tumbleweed\nID_LIKE=\"opensuse suse\"\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("zypper"), "got: {}", hint);+ }++ #[test]+ fn linux_hint_unknown_distro_falls_back() {+ let release = "NAME=\"Some Custom Distro\"\nID=mystery\n";+ let hint = linux_python_install_hint(release);+ assert!(hint.contains("package manager"), "got: {}", hint);+ }++ #[test]+ fn linux_hint_empty_input_falls_back() {+ let hint = linux_python_install_hint("");+ assert!(hint.contains("package manager"));+ }++ }diff --cc src-tauri/src/commands/install/venv.rsindex 00000000,2efb7a36..9354ea14mode 000000,100644..100644--- a/src-tauri/src/commands/install/venv.rs+++ b/src-tauri/src/commands/install/venv.rs@@@ -1,0 -1,430 +1,486 @@@+ //! Der Python, in den LU installiert, und was sonst noch darin wohnt.+ //!+ //! Der geteilte Zustand ist ein Verzeichnis auf der Platte: `ComfyUI/venv`.+ //! `resolve_lu_python` zeigt darauf, `create_comfyui_venv` legt es an,+ //! `venv_site_packages` findet seine `site-packages` in beiden+ //! Plattform-Layouts, und `detect_venv_passengers` liest ab, welche+ //! LU-eigenen Pakete darin liegen, die ComfyUI nicht gehören.+ //!+ //! Genau diese Mitfahrer sind der Grund für die Naht. faster-whisper und+ //! Piper landen in ComfyUIs venv, weil das "LUs Python" ist; die Reparatur+ //! löscht dieses venv im Ganzen. Wer eines von beidem ändert, muss das+ //! andere vor Augen haben — also stehen sie in einer Datei. `is_pep668_protected`+ //! gehört dazu, weil es die Frage beantwortet, ob überhaupt ein venv nötig+ //! ist: auf einer PEP-668-Distribution ist es der einzige Weg, überhaupt zu+ //! installieren.++ use std::path::{Path, PathBuf};-use std::process::{Command, Stdio};++use crate::python::python_command;++use std::process::Stdio;++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use crate::os_error;+ use crate::python::venv_python_path;+ use crate::state::AppState;++ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ── PEP 668 / venv helpers (Bug E — rzgrozt Arch externally-managed) ─────────++ /// True iff the Python pointed to by `python_bin` is PEP 668 protected+ /// (Arch Linux, Debian 12+, Fedora 38+, Ubuntu 23.04+ ship Python with an+ /// `EXTERNALLY-MANAGED` marker file in the stdlib dir, which makes+ /// `python -m pip install ...` exit with+ /// `error: externally-managed-environment` unless `--break-system-packages`+ /// is passed). We probe by asking Python itself whether the marker exists+ /// — robust against distro-specific path layouts and avoids parsing locale+ /// dependent pip error strings.+ ///+ /// Returns `false` on any probe error (Python missing, sysconfig broken,+ /// stdout unparseable). That is the safe default: a false negative just+ /// means we install without a venv exactly like LU did before this bug,+ /// which is fine on every distro that *isn't* PEP 668 protected.+ pub fn is_pep668_protected(python_bin: &str) -> bool {+ if python_bin.is_empty() {+ return false;+ }- let mut cmd = Command::new(python_bin);++ let mut cmd = python_command(python_bin);+ cmd.args([+ "-c",+ "import os, sysconfig; \+ d = sysconfig.get_path('stdlib'); \+ print('YES' if os.path.exists(os.path.join(d, 'EXTERNALLY-MANAGED')) else 'NO')",+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);+ let Ok(out) = cmd.output() else { return false };+ if !out.status.success() {+ return false;+ }+ String::from_utf8_lossy(&out.stdout).trim() == "YES"+ }+-/// Create a venv inside `comfyui_dir/venv` using the system `python_bin`.-/// Returns the path to the venv's Python interpreter on success. On Arch-/// boxes that haven't installed the `python-virtualenv` package this can-/// fail with `No module named venv` — we surface that with an actionable-/// hint pointing at the right pacman / apt invocation.+ pub fn create_comfyui_venv(comfyui_dir: &Path, python_bin: &str) -> Result<PathBuf, String> {+ let venv_dir = comfyui_dir.join("venv");+ // venv is idempotent: re-running on an existing dir just no-ops, but be+ // explicit so the log reads cleanly.+ let already_existed = venv_dir.exists() && venv_python_path(comfyui_dir).exists();+ if already_existed {+ return Ok(venv_python_path(comfyui_dir));+ }+- let mut cmd = Command::new(python_bin);++ let mut cmd = python_command(python_bin);+ cmd.args(["-m", "venv", venv_dir.to_string_lossy().as_ref()])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);++ let out = cmd+ .output()+ .map_err(|e| format!("Could not spawn `python -m venv`: {}", os_error::english(&e)))?;++ if !out.status.success() {+ let stderr = String::from_utf8_lossy(&out.stderr);+ let lower = stderr.to_lowercase();+ // Most common Arch / minimal-Python failure: stdlib venv module+ // isn't available because the distro packages it separately.+ if lower.contains("no module named venv") || lower.contains("ensurepip") {+ return Err(format!(+ "Python's `venv` module is not available. Install it first:\n\+ • Arch: sudo pacman -S python-virtualenv\n\+ • Debian/Ubuntu: sudo apt install python3-venv\n\+ • Fedora: sudo dnf install python3-virtualenv\n\+ Then retry the ComfyUI install.\n\n--- python output ---\n{}",+ stderr.chars().take(400).collect::<String>()+ ));+ }+ return Err(format!(+ "venv creation failed: {}",+ stderr.chars().take(400).collect::<String>()+ ));+ }++ let venv_py = venv_python_path(comfyui_dir);+ if !venv_py.exists() {+ return Err(format!(+ "venv was created at {} but no Python binary appeared at {}. \+ This usually means the venv module is broken — try `sudo pacman -S python-virtualenv` (Arch) or the equivalent on your distro.",+ venv_dir.display(),+ venv_py.display()+ ));+ }+ Ok(venv_py)+ }++ // ── OI-3: the repair must not silently uninstall Voice ──────────────────────++ /// A package LU installs into the ComfyUI venv that is NOT ComfyUI's.+ ///+ /// `resolve_lu_python` sends faster-whisper (STT) and Piper (TTS) into+ /// `ComfyUI/venv` whenever one exists, because that is "LU's Python". The+ /// repair then deletes that venv wholesale and rebuilds it with PyTorch and+ /// ComfyUI's requirements — and nothing else. Two features the user paid+ /// bandwidth for disappear as a side effect of a repair they did not ask for+ /// (the Create tab fires `repair_comfyui_env` automatically after a ComfyUI+ /// startup crash), with not one log line connecting the two. What the user+ /// experiences is "Voice just stopped".+ ///+ /// Keeping them out of the venv was the other option and it is worse: LU+ /// would have to maintain a second interpreter, and the TTS synthesizer and+ /// whisper server both start with whatever `resolve_lu_python` returns, so+ /// they would then be started from an env they were not installed into. The+ /// venv stays the one Python; the repair takes responsibility for refilling it.+ pub(crate) struct VenvPassenger {+ /// The import-name directory as it appears inside `site-packages`.+ pub marker: &'static str,+ /// What to hand pip.+ pub pip_name: &'static str,+ /// What the user calls the feature.+ pub label: &'static str,+ }++ pub(crate) const VENV_PASSENGERS: [VenvPassenger; 2] = [+ VenvPassenger { marker: "faster_whisper", pip_name: "faster-whisper", label: "Voice input (faster-whisper)" },+ VenvPassenger { marker: "piper", pip_name: "piper-tts", label: "Neural voice output (Piper TTS)" },+ ];++ /// Every `site-packages` a venv can have, across both platform layouts.+ /// Pure path math — enumerated rather than guessed, because the Unix minor+ /// version (`lib/python3.12`) is whatever built the env.+ pub(crate) fn venv_site_packages(venv_dir: &Path) -> Vec<PathBuf> {+ let mut candidates: Vec<PathBuf> = Vec::new();+ // Windows: <venv>/Lib/site-packages+ candidates.push(venv_dir.join("Lib").join("site-packages"));+ // Unix: <venv>/lib/python3.X/site-packages (and lib64 on some distros)+ for lib_name in ["lib", "lib64"] {+ let lib = venv_dir.join(lib_name);+ candidates.push(lib.join("site-packages"));+ if let Ok(entries) = std::fs::read_dir(&lib) {+ for e in entries.flatten() {+ candidates.push(e.path().join("site-packages"));+ }+ }+ }++ // Both probes hit the same directory on a case-insensitive filesystem+ // (macOS, Windows), where `Lib` and `lib` are one directory. Dedupe by+ // canonical path so a caller counting the result gets the number of real+ // site-packages, not the number of spellings that reached them.+ let mut out: Vec<PathBuf> = Vec::new();+ let mut seen: Vec<PathBuf> = Vec::new();+ for c in candidates {+ if !c.is_dir() {+ continue;+ }+ let key = std::fs::canonicalize(&c).unwrap_or_else(|_| c.clone());+ if seen.contains(&key) {+ continue;+ }+ seen.push(key);+ out.push(c);+ }+ out+ }++ /// Which LU-owned passengers are in this venv right now. Read BEFORE the venv+ /// is deleted; the result is what the repair has to put back.+ pub(crate) fn detect_venv_passengers(venv_dir: &Path) -> Vec<&'static VenvPassenger> {+ let site_dirs = venv_site_packages(venv_dir);+ VENV_PASSENGERS+ .iter()+ .filter(|p| site_dirs.iter().any(|d| d.join(p.marker).exists()))+ .collect()+ }++ // ── Piper neural TTS installer (David 2026-06-06 — local neural TTS) ──────────++ /// Resolve the Python LU's tooling uses: the ComfyUI venv when present, else+ /// the resolved system Python. Shared by the faster-whisper + Piper-TTS+ /// installers and the TTS synthesizer so they all target the same interpreter.+ pub fn resolve_lu_python(state: &AppState) -> String {+ let comfy_dir: Option<PathBuf> = {+ let p = state.comfy_path.lock().unwrap().clone();+ p.map(PathBuf::from)+ .or_else(|| crate::commands::process::find_comfyui_path().map(PathBuf::from))+ };+ let venv_python = comfy_dir+ .as_deref()+ .and_then(crate::python::resolve_comfyui_venv_python);+ if let Some(v) = venv_python {+ return v;+ }+ // System Python: use the cached resolution, but if it's empty/stale —+ // Python may have been installed AFTER launch (Bug B8) — re-resolve once and+ // refresh the cache so install_tts/install_whisper don't wrongly report "no+ // Python found" until the next restart.+ let cached = state.python_bin.lock().map(|g| g.clone()).unwrap_or_default();+ if crate::python::is_real_python(&cached) {+ return cached;+ }+ let resolved = crate::python::get_python_bin();+ if crate::python::is_real_python(&resolved) {+ if let Ok(mut slot) = state.python_bin.lock() {+ *slot = resolved.clone();+ }+ }+ resolved+ }+++/// Create a venv inside `comfyui_dir/venv` using the system `python_bin`.++/// Returns the path to the venv's Python interpreter on success. On Arch++/// boxes that haven't installed the `python-virtualenv` package this can++/// fail with `No module named venv` — we surface that with an actionable++/// hint pointing at the right pacman / apt invocation.++/// The card the user reads when Repair environment cannot delete the old venv.++///++/// A15, Windows Nachlauf 02.09.: this exact sentence carried the German++/// "Der Prozess kann nicht auf die Datei zugreifen, da sie von einem anderen++/// Prozess verwendet wird. (os error 32)" into an English app, because it++/// rendered the `io::Error` itself and Windows answers FormatMessageW in the++/// system language. Split out of the caller so the wording is testable without++/// a locked folder, and without Windows.++pub(crate) fn venv_removal_error(venv_dir: &Path, e: &std::io::Error) -> String {++ format!(++ "Could not remove the old venv at {}: {}. Close anything using it and retry.",++ venv_dir.display(),++ os_error::io_english(e)++ )++}+++ #[cfg(test)]+ mod tests {+ use super::*;++ // ── OI-3: the repair must not silently uninstall Voice ────────────────+ //+ // `resolve_lu_python` puts faster-whisper and Piper into ComfyUI's venv,+ // and `repair_comfyui_env` deletes that venv — automatically, after a+ // ComfyUI startup crash the user did not connect to Voice at all.+ // Detection is pure path work, so it is fully testable; the reinstall+ // itself is a pip run and needs a real network.++ fn venv_with_packages(names: &[&str], layout: &str) -> tempfile::TempDir {+ let tmp = tempfile::tempdir().unwrap();+ let site = match layout {+ "windows" => tmp.path().join("venv").join("Lib").join("site-packages"),+ _ => tmp+ .path()+ .join("venv")+ .join("lib")+ .join("python3.12")+ .join("site-packages"),+ };+ std::fs::create_dir_all(&site).unwrap();+ for n in names {+ std::fs::create_dir_all(site.join(n)).unwrap();+ }+ tmp+ }++ #[test]+ fn both_voice_packages_are_seen_in_a_unix_venv() {+ let tmp = venv_with_packages(&["faster_whisper", "piper", "torch"], "unix");+ let found = detect_venv_passengers(&tmp.path().join("venv"));+ let names: Vec<&str> = found.iter().map(|p| p.pip_name).collect();+ assert_eq!(names, vec!["faster-whisper", "piper-tts"]);+ }++ #[test]+ fn both_voice_packages_are_seen_in_a_windows_venv() {+ // The layout LU's own Windows installs use, checked from a Unix box.+ let tmp = venv_with_packages(&["faster_whisper", "piper"], "windows");+ let found = detect_venv_passengers(&tmp.path().join("venv"));+ assert_eq!(found.len(), 2);+ }++ #[test]+ fn a_venv_without_voice_has_nothing_to_reinstall() {+ // Negative control: a plain ComfyUI venv must not trigger the extra+ // pip runs, or every repair would install Piper on machines that+ // never had it.+ let tmp = venv_with_packages(&["torch", "torchvision"], "unix");+ assert!(detect_venv_passengers(&tmp.path().join("venv")).is_empty());+ // And a venv that does not exist at all reads as empty, not an error:+ // the repair runs on installs that never had one.+ let missing = tempfile::tempdir().unwrap();+ assert!(detect_venv_passengers(&missing.path().join("venv")).is_empty());+ }++ #[test]+ fn only_the_whisper_half_is_detected_when_only_it_is_installed() {+ let tmp = venv_with_packages(&["faster_whisper"], "unix");+ let found = detect_venv_passengers(&tmp.path().join("venv"));+ assert_eq!(found.len(), 1);+ assert_eq!(found[0].pip_name, "faster-whisper");+ assert!(found[0].label.to_lowercase().contains("voice"));+ }++ #[test]+ fn site_packages_are_found_in_both_layouts_and_nowhere_else() {+ let unix = venv_with_packages(&[], "unix");+ assert_eq!(venv_site_packages(&unix.path().join("venv")).len(), 1);+ let win = venv_with_packages(&[], "windows");+ assert_eq!(venv_site_packages(&win.path().join("venv")).len(), 1);+ // A directory that is not a venv has none.+ let plain = tempfile::tempdir().unwrap();+ assert!(venv_site_packages(plain.path()).is_empty());+ }++ // ── Bug E (rzgrozt — Arch PEP 668 externally-managed) ─────────────────+ //+ // The detection function spawns a Python subprocess, so we can't unit+ // test it without a Python install. We DO test the safety guarantees:+ // empty `python_bin` returns false (regression-safe default), and the+ // diagnose path surfaces a useful hint when the marker error reaches+ // the user despite the auto-venv path.++ #[test]+ fn is_pep668_protected_returns_false_for_empty_bin() {+ // Empty sentinel from python.rs::get_python_bin must short-circuit+ // to false so a missing Python doesn't accidentally trigger venv+ // creation (which would also fail and confuse the error chain).+ assert!(!is_pep668_protected(""));+ }++ #[test]+ fn is_pep668_protected_returns_false_for_garbage_bin() {+ // Probing a non-existent path can't crash — the function must+ // swallow the spawn error and return false so install proceeds as+ // it always did on systems that aren't PEP 668 protected.+ assert!(!is_pep668_protected("/definitely/not/a/real/python-9.99"));+ }++ // ── Bug E — LIVE integration test ──────────────────────────────────────+ //+ // Runs against a real Python install with a real EXTERNALLY-MANAGED+ // marker planted in its stdlib. Requires the caller to point+ // `LU_PEP668_TEST_PYTHON` env var at a Python whose stdlib is writable+ // (typically a temp copy of system Python — see+ // `LU-E2E-Test-Kit/scripts/pep668_live_test.ps1` for the setup helper).+ //+ // Skipped by default via `#[ignore]` because:+ // 1. needs a real, modifiable Python install (not safe to mutate the+ // system Python's stdlib — wedges every pip command on the box).+ // 2. writes to the filesystem and spawns 4-5 Python subprocesses.+ //+ // Run with: `cargo test --release --bins -- --ignored pep668_e2e_live`++ #[test]+ #[ignore]+ fn pep668_e2e_live_detect_and_create_venv() {+ let fake_python = std::env::var("LU_PEP668_TEST_PYTHON")+ .expect("set LU_PEP668_TEST_PYTHON to the fake-python path before running");+ assert!(+ std::path::Path::new(&fake_python).exists(),+ "LU_PEP668_TEST_PYTHON does not exist: {}",+ fake_python+ );++ // The helper script must have planted the marker BEFORE this test+ // runs. If it didn't, the detection should return false — that's+ // also informative, so we don't fail outright here; we just print+ // and check the more interesting assertions.++ // ── Phase 1: PEP 668 detection ──+ let detected = is_pep668_protected(&fake_python);+ assert!(+ detected,+ "is_pep668_protected({}) returned false — was the EXTERNALLY-MANAGED \+ marker planted in this Python's stdlib?",+ fake_python+ );+ println!("[live E2E] ✓ is_pep668_protected detected the marker");++ // ── Phase 2: create_comfyui_venv ──+ let comfy_root = std::env::temp_dir().join("lu-pep668-live-comfyui");+ let _ = std::fs::remove_dir_all(&comfy_root);+ std::fs::create_dir_all(&comfy_root).expect("temp dir create");++ let venv_py = create_comfyui_venv(&comfy_root, &fake_python)+ .expect("create_comfyui_venv should succeed against fake python");++ assert!(venv_py.exists(), "venv python at {} should exist", venv_py.display());+ assert!(venv_py.starts_with(&comfy_root), "venv python should be inside comfy dir");+ println!("[live E2E] ✓ create_comfyui_venv produced {}", venv_py.display());++ // ── Phase 3: nested venv's pip should be UNBLOCKED ──+ // The venv has its own site-packages, so PEP 668 doesn't apply to+ // it — this is the whole point of the fix. Verify pip install+ // works inside the nested venv. We use `--dry-run` so we don't+ // actually download anything heavy; the test is whether pip+ // refuses or proceeds.+ let pip_out = std::process::Command::new(venv_py.to_string_lossy().as_ref())+ .args(["-m", "pip", "install", "--dry-run", "--no-input", "pip"])+ .output()+ .expect("nested venv pip should spawn");+ let combined = format!(+ "{}{}",+ String::from_utf8_lossy(&pip_out.stdout),+ String::from_utf8_lossy(&pip_out.stderr)+ );+ assert!(+ !combined.to_lowercase().contains("externally-managed"),+ "nested venv pip was STILL blocked — PEP 668 leaked through. \+ Output:\n{}",+ combined+ );+ assert!(pip_out.status.success(), "nested venv pip exit code != 0:\n{}", combined);+ println!("[live E2E] ✓ nested venv pip runs without PEP 668 block");++ // ── Phase 4: idempotency — second create_comfyui_venv must no-op ──+ let venv_py_again = create_comfyui_venv(&comfy_root, &fake_python)+ .expect("second create_comfyui_venv should idempotently return existing venv");+ assert_eq!(venv_py, venv_py_again);+ println!("[live E2E] ✓ create_comfyui_venv is idempotent");++ // Cleanup+ let _ = std::fs::remove_dir_all(&comfy_root);+ println!("[live E2E] ALL ASSERTIONS PASSED");+ }+++ /// What code 32 reads as on the machine the test runs on. Windows means++ /// ERROR_SHARING_VIOLATION, which is the code from the box; every unix++ /// errno 32 is EPIPE. Both answers are ours, and neither is read off the++ /// operating system.++ #[cfg(windows)]++ const VENV_BUSY: &str = "the file is in use by another process (os error 32)";++++ #[cfg(not(windows))]++ const VENV_BUSY: &str = "broken pipe (os error 32)";++++ #[test]++ fn a_venv_held_by_another_process_is_reported_in_our_words() {++ let dir = PathBuf::from("C:\\Users\\ddrob\\ComfyUI\\venv");++ let e = std::io::Error::from_raw_os_error(32);++ let msg = venv_removal_error(&dir, &e);++ assert_eq!(++ msg,++ format!(++ "Could not remove the old venv at {}: {}. Close anything using it and retry.",++ dir.display(),++ VENV_BUSY++ )++ );++ // The finding itself: on the German box this sentence carried++ // "Der Prozess kann nicht auf die Datei zugreifen ...". Whatever this++ // machine's language calls code 32, that wording is not in here.++ assert!(!msg.contains(&e.to_string()), "the system wording survived: {msg}");++ assert!(msg.is_ascii(), "a localised message would not be ascii: {msg}");++ }++++ /// Negative control: an error Rust worded itself is already English, and++ /// rewriting it would only lose the detail it carries.++ #[test]++ fn a_venv_failure_rust_worded_itself_is_passed_through_unchanged() {++ let e = std::io::Error::new(++ std::io::ErrorKind::InvalidInput,++ "the venv path is not a directory",++ );++ let msg = venv_removal_error(Path::new("/tmp/ComfyUI/venv"), &e);++ assert!(msg.contains("the venv path is not a directory"), "got: {msg}");++ assert!(msg.starts_with("Could not remove the old venv at /tmp/ComfyUI/venv: "), "got: {msg}");++ }+++ }diff --cc src-tauri/src/commands/install/voice.rsindex 00000000,43063712..232418e4mode 000000,100644..100644--- a/src-tauri/src/commands/install/voice.rs+++ b/src-tauri/src/commands/install/voice.rs@@@ -1,0 -1,346 +1,344 @@@+ //! Die beiden Sprachhälften nachinstallieren: Zuhören und Sprechen.+ //!+ //! Der geteilte Zustand ist der Interpreter, in den beide gehen. faster-whisper+ //! und Piper werden in DENSELBEN Python installiert, den `resolve_lu_python`+ //! liefert — in aller Regel ComfyUIs venv — und aus genau diesem Python+ //! werden sie später auch gestartet. Fällt das auseinander, ist der Import+ //! zur Laufzeit nicht da, obwohl die Installation gemeldet hat, sie sei+ //! fertig.+ //!+ //! Deshalb stehen sie zusammen und nicht bei ihren jeweiligen Funktionen.+ //! Beide brauchen denselben PEP-668-Ausweg, wenn der Zielpython doch der des+ //! Systems ist; beide melden ihren Fehler im `error`-Feld und nicht nur im+ //! Log, weil die Oberfläche sonst ein blankes "Install failed." zeigt; und+ //! beide sind die Mitfahrer, die `venv::detect_venv_passengers` aufzählt und+ //! die ComfyUI-Reparatur wieder einsetzen muss.+-use std::process::{Command, Stdio};++use std::process::Stdio;++ #[cfg(target_os = "windows")]+ use std::os::windows::process::CommandExt;++ use tauri::{Manager, State};+ use tracing::{error, info};++ use crate::state::AppState;++use crate::os_error;++use crate::python::python_command;++ use super::pip::pip_install_streaming_with_retry_cancellable;+ use super::venv::{is_pep668_protected, resolve_lu_python};+ #[cfg(target_os = "windows")]+ use super::CREATE_NO_WINDOW;++ // ── Whisper (faster-whisper) installer (§24.9 — STT install affordance) ──────++ /// The pip args to install faster-whisper. Extracted as a pure helper so the+ /// exact invocation is unit-testable (and so the package name lives in one+ /// place — the STT backend `whisper_server.py` imports `faster_whisper`, so+ /// that's what we install). Mirrors the flags the ComfyUI installer uses:+ /// `--no-input` (never block on a prompt) and `--progress-bar off` (the live+ /// pip bars are noise in our log stream).+ fn build_whisper_pip_args() -> Vec<&'static str> {+ vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "faster-whisper",+ ]+ }++ /// §24.9 — Install faster-whisper so STT works, then start the persistent+ /// whisper server so the Settings STT badge flips ✗ → ✓ without a restart.+ ///+ /// Installs into the SAME Python the rest of LU's Python tooling uses: the+ /// ComfyUI venv when one exists (matches `install_custom_node` /+ /// `start_comfyui`), else the resolved system Python. The whisper server is+ /// then started with that exact interpreter — critical, because starting it+ /// with a different Python than we installed into would fail the+ /// `import faster_whisper` check and leave the badge red.+ #[tauri::command]+ pub fn install_whisper(+ app: tauri::AppHandle,+ state: State<'_, AppState>,+ ) -> Result<serde_json::Value, String> {+ {+ let mut install = state.whisper_install.lock().unwrap();+ if install.status == "installing" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }+ install.status = "installing".to_string();+ install.logs.clear();+ install.logs.push("Starting faster-whisper installation...".to_string());+ }++ info!("whisper install start");++ // Resolve the target Python: ComfyUI venv (if present) → system Python,+ // re-resolving a stale cache (Bug B8 — Python installed after launch).+ let target_python = resolve_lu_python(state.inner());++ if target_python.is_empty() || !crate::python::is_real_python(&target_python) {+ let mut install = state.whisper_install.lock().unwrap();+ install.status = "error".to_string();+ install.logs.push(+ "No Python found. Install Python first (Settings → ComfyUI → Install Python), \+ then retry the Whisper install."+ .to_string(),+ );+ error!("whisper install aborted: no usable python");+ return Err("no_python: Python must be installed before faster-whisper.".to_string());+ }++ let install_state = state.whisper_install.clone();+ let whisper = state.whisper.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_state.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ update("installing", &format!("Installing faster-whisper via {} (this can take a few minutes)…", target_python));++ let mut args = build_whisper_pip_args();+ // Arch / Debian 12+ / Fedora 38+ system Python is PEP 668 protected, so a+ // bare `pip install` dies with externally-managed-environment. When that's+ // the target (no ComfyUI venv absorbed it), install into the user site+ // with the escape hatch so STT installs there too (joerack, Arch). No-op+ // on Windows/macOS/venv Pythons (not PEP 668 protected).+ if is_pep668_protected(&target_python) {+ args.push("--break-system-packages");+ args.push("--user");+ }+ // No cancel flag — this single pip install is short relative to the+ // ComfyUI PyTorch download, so we run it to completion like install_python.+ match pip_install_streaming_with_retry_cancellable(&args, &target_python, 3, &install_state, None) {+ Ok(()) => {+ update("installing", "faster-whisper installed. Starting the speech-to-text server…");+ // Start the persistent server with the SAME Python we installed+ // into, so the import check passes and whisper_status flips to+ // available without an app restart. auto_start_whisper_sync+ // re-checks `import faster_whisper` and locates whisper_server.py+ // from bundled resources (prod) or ./public (dev).+ {+ let already_running = whisper.lock().map(|w| w.ready).unwrap_or(false);+ if !already_running {+ let _ = crate::commands::whisper::auto_start_whisper_sync(&app, &target_python, &whisper);+ }+ }+ let started = whisper.lock().map(|w| w.ready).unwrap_or(false);+ if started {+ update("complete", "Speech-to-text is ready.");+ } else {+ // Install succeeded but the server didn't come up (e.g. model+ // download still pending). Still a success for the install+ // itself — the badge re-check / next launch will pick it up.+ update("complete", "faster-whisper installed. The STT server will finish loading shortly (or on next launch).");+ }+ }+ Err(diagnosis) => {+ let err = format!("faster-whisper installation failed.\n\n{}", diagnosis);+ println!("[Whisper Install] {}", err);+ update("error", &err);+ }+ }+ });++ Ok(serde_json::json!({"status": "installing"}))+ }++ /// §24.9 — Poll the faster-whisper install progress (mirrors the other+ /// `*_status` commands). The frontend re-runs `checkWhisperAvailable` when+ /// this reports `complete`.+ #[tauri::command]+ pub fn install_whisper_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.whisper_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ // The frontend shows `error` verbatim; without it every failure read+ // as a bare "Install failed." while the diagnosis sat in `logs`.+ "error": if install.status == "error" { install.logs.last().cloned() } else { None },+ "download_progress": install.download_progress,+ "download_total": install.download_total,+ "download_speed": install.download_speed,+ }))+ }++ /// pip args to install Piper TTS. `piper-tts` ships the `piper` CLI + the+ /// `piper.download_voices` helper. Same flags as the whisper installer.+ fn build_tts_pip_args() -> Vec<&'static str> {+ vec![+ "-m", "pip", "install",+ "--progress-bar", "off",+ "--no-input",+ "piper-tts",+ ]+ }++ /// Install Piper (neural TTS) into LU's Python, then download the default voice+ /// model into `<app_data>/piper_voices/`. Mirrors `install_whisper`. Progress+ /// is polled via `install_tts_status`; `tts_status` reports usability.+ #[tauri::command]+ pub fn install_tts(+ app: tauri::AppHandle,+ state: State<'_, AppState>,+ ) -> Result<serde_json::Value, String> {+ {+ let mut install = state.tts_install.lock().unwrap();+ if install.status == "installing" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }+ install.status = "installing".to_string();+ install.logs.clear();+ install.logs.push("Starting neural TTS (Piper) installation...".to_string());+ }++ info!("tts install start");++ let target_python = resolve_lu_python(state.inner());+ if target_python.is_empty() || !crate::python::is_real_python(&target_python) {+ let mut install = state.tts_install.lock().unwrap();+ install.status = "error".to_string();+ install.logs.push(+ "No Python found. Install Python first (Settings → ComfyUI → Install Python), \+ then retry the neural TTS install."+ .to_string(),+ );+ error!("tts install aborted: no usable python");+ return Err("no_python: Python must be installed before Piper TTS.".to_string());+ }++ let voices_dir = app+ .path()+ .app_data_dir()- .map_err(|e| format!("no app data dir: {}", e))?++ .map_err(|e| format!("no app data dir: {}", os_error::english(&e)))?+ .join("piper_voices");++ let install_state = state.tts_install.clone();++ std::thread::spawn(move || {+ let update = |status: &str, msg: &str| {+ if let Ok(mut s) = install_state.lock() {+ s.status = status.to_string();+ s.logs.push(msg.to_string());+ }+ };++ // When `piper.download_voices` already imports (package AND its deps),+ // pip would only re-resolve pins — and that upgrade can collide with a+ // python process using the same site-packages: live repro 2026-07-31+ // (Windows), the app's own running ComfyUI held onnxruntime's DLL and+ // pip died on WinError 5, so read-aloud never got its voice. All that+ // is actually missing then is the voice file — go straight to it.+ let piper_ready = {- let mut probe = Command::new(&target_python);++ let mut probe = python_command(&target_python);+ probe+ .args(["-c", "import piper.download_voices"])+ .stdout(Stdio::null())+ .stderr(Stdio::null());- #[cfg(target_os = "windows")]- probe.creation_flags(CREATE_NO_WINDOW);+ probe.status().map(|s| s.success()).unwrap_or(false)+ };++ let pip_result = if piper_ready {+ update("installing", "piper-tts is already installed — skipping pip.");+ Ok(())+ } else {+ update(+ "installing",+ &format!("Installing piper-tts via {} (this can take a few minutes)…", target_python),+ );+ let mut args = build_tts_pip_args();+ // PEP 668 escape hatch (Arch / Debian 12+ / Fedora 38+) — see+ // install_whisper. No-op on Windows/macOS/venv Pythons.+ if is_pep668_protected(&target_python) {+ args.push("--break-system-packages");+ args.push("--user");+ }+ pip_install_streaming_with_retry_cancellable(&args, &target_python, 3, &install_state, None)+ };+ match pip_result {+ Ok(()) => {+ update(+ "installing",+ &format!(+ "piper-tts installed. Downloading the {} voice (~63 MB)…",+ crate::commands::tts::PIPER_VOICE+ ),+ );+ let _ = std::fs::create_dir_all(&voices_dir);- let mut cmd = Command::new(&target_python);++ let mut cmd = python_command(&target_python);+ cmd.args([+ "-m",+ "piper.download_voices",+ crate::commands::tts::PIPER_VOICE,+ "--download-dir",+ &voices_dir.to_string_lossy(),+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(o) if o.status.success() => {+ update("complete", "Neural TTS is ready.");+ }+ Ok(o) => {+ update(+ "error",+ &format!("Voice download failed:\n{}", String::from_utf8_lossy(&o.stderr)),+ );+ }+ Err(e) => {- update("error", &format!("Voice download could not start: {}", e));++ update("error", &format!("Voice download could not start: {}", os_error::english(&e)));+ }+ }+ }+ Err(diagnosis) => {+ let err = format!("piper-tts installation failed.\n\n{}", diagnosis);+ println!("[TTS Install] {}", err);+ update("error", &err);+ }+ }+ });++ Ok(serde_json::json!({"status": "installing"}))+ }++ /// Poll the Piper-TTS install progress (mirrors `install_whisper_status`).+ #[tauri::command]+ pub fn install_tts_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.tts_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ // Same contract as install_whisper_status: the frontend reads `error`.+ "error": if install.status == "error" { install.logs.last().cloned() } else { None },+ }))+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ // ── §24.9 — Whisper pip args builder ──────────────────────────────────++ #[test]+ fn whisper_pip_args_install_faster_whisper() {+ let args = build_whisper_pip_args();+ // Drives `python -m pip install … faster-whisper` — the package the+ // STT backend (whisper_server.py) actually imports.+ assert_eq!(&args[..3], &["-m", "pip", "install"]);+ assert!(args.contains(&"faster-whisper"), "must install faster-whisper: {:?}", args);+ // Non-interactive + quiet progress, matching the ComfyUI installer.+ assert!(args.contains(&"--no-input"), "must pass --no-input: {:?}", args);+ let pos = args.iter().position(|a| *a == "--progress-bar");+ assert!(pos.is_some(), "must set --progress-bar: {:?}", args);+ assert_eq!(args[pos.unwrap() + 1], "off");+ // The package name is the LAST arg (after all flags) so pip parses it+ // as the install target, not as a flag value.+ assert_eq!(*args.last().unwrap(), "faster-whisper");+ }++ }diff --cc src-tauri/src/commands/local_api.rsindex 00000000,94862a09..43b5bd79mode 000000,100644..100644--- a/src-tauri/src/commands/local_api.rs+++ b/src-tauri/src/commands/local_api.rs@@@ -1,0 -1,2226 +1,2235 @@@+ //! Die lokale Modell-API — ein Router vor dem, was ohnehin schon laeuft.+ //!+ //! ── WARUM DAS EIN ROUTER IST UND KEIN SERVER ───────────────────────────────+ //!+ //! Auftrag am 02.09.2026: "eine API nicht nur fuer die Cloud-Modelle, sondern+ //! fuer ALLE lokalen" — Ollama, LM Studio, LU Engine. Der erste Reflex waere,+ //! eine Inferenz-Schicht zu bauen. Nachgesehen hat sich das erledigt: alle drei+ //! sprechen bereits OpenAI.+ //!+ //! LU Engine llama-server auf 127.0.0.1:8127/v1 (engine.rs::DEFAULT_ENGINE_PORT)+ //! Ollama 127.0.0.1:11434/v1+ //! LM Studio 127.0.0.1:1234/v1+ //!+ //! Was fehlt, ist nicht Inferenz, sondern EINE Adresse davor: ein Verzeichnis+ //! ueber alle drei, eine Weiterleitung, ein Token. Genau das steht hier.+ //!+ //! ── WARUM EIN EIGENER LAUSCHER UND NICHT remote.rs ─────────────────────────+ //!+ //! remote.rs bindet auf 0.0.0.0:11435 — mit Absicht, denn das Handy soll sich+ //! im WLAN verbinden koennen, und davor steht ein Paarungsablauf mit QR-Code+ //! und JWT. Haengte man `/v1` dort an, waere die Modell-API vom ersten Tag an+ //! im ganzen Netz sichtbar. Davids Entscheidung war das Gegenteil: "Localhost ab+ //! Werk, LAN einstellbar". Ein eigener Lauscher haelt beide Sicherheitsmodelle+ //! auseinander, statt sie zu vermischen.+ //!+ //! ── DIE DREI REGELN, DIE NICHT VERHANDELBAR SIND ───────────────────────────+ //!+ //! 1. **Token immer.** Auch auf 127.0.0.1. Auf einem Mehrbenutzer-Rechner ist+ //! localhost keine Grenze, und jedes Programm des Nutzers — jede Webseite+ //! ueber einen neugierigen fetch — erreicht 127.0.0.1. Ein LEERES Token+ //! darf deshalb niemals passen: sonst hiesse "nicht eingerichtet" in der+ //! Wirkung "offen". `token_matches` gibt bei leerem Erwartungswert `false`.+ //! 2. **LAN ist aus, bis jemand sie einschaltet.** `bind_addr(false, _)` ist+ //! 127.0.0.1, und der Vorgabewert von `lan` ist `false`.+ //! 3. **Das Token des Aufrufers geht nie nach oben weiter.** Wir leiten an+ //! llama-server / Ollama / LM Studio weiter; deren Authorization-Kopfzeile+ //! ist unsere Sache, nicht die des Clients. `forward_headers` streicht sie.+ //!+ //! ── WAS HIER STEHT UND WAS NICHT ───────────────────────────────────────────+ //!+ //! Diese Datei traegt zuerst den ENTSCHEIDBAREN Teil: Namensaufloesung,+ //! Bindeadresse, Tokenvergleich, Kopfzeilenfilter. Alles reine Funktionen ohne+ //! Netz, alle unten geprueft. Der Lauscher und die Tauri-Befehle bauen darauf+ //! auf und haben nichts zu entscheiden.++ use std::collections::BTreeMap;+ use std::net::{IpAddr, Ipv4Addr, SocketAddr};++ /// Der Vorgabeport der lokalen API.+ ///+ /// 8129 und nicht 8127: 8127 ist die LU Engine selbst (engine.rs), 8128 laesst+ /// Platz fuer einen zweiten Engine-Prozess (der Embedder laeuft heute schon als+ /// eigener `bundled_embed`). Wer beide Zahlen nebeneinander sieht, soll nicht+ /// raten muessen, welche welche ist.+ pub const DEFAULT_LOCAL_API_PORT: u16 = 8129;++ /// Woher ein Modell kommt.+ ///+ /// Die Reihenfolge ist nicht beliebig: sie bestimmt, in welcher Folge+ /// `/v1/models` die Lanes auflistet, und damit, was ein Mensch zuerst sieht.+ /// Die eigene Engine zuerst, dann die zwei fremden Programme.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+ pub enum Lane {+ Engine,+ Ollama,+ LmStudio,+ }++ impl Lane {+ /// Das Namenspraefix nach aussen. Kurz, weil es der Nutzer tippt.+ pub fn prefix(self) -> &'static str {+ match self {+ Lane::Engine => "lu",+ Lane::Ollama => "ollama",+ Lane::LmStudio => "lmstudio",+ }+ }++ pub fn from_prefix(p: &str) -> Option<Lane> {+ match p {+ "lu" => Some(Lane::Engine),+ "ollama" => Some(Lane::Ollama),+ "lmstudio" => Some(Lane::LmStudio),+ _ => None,+ }+ }++ /// Wie die Lane in einer Fehlermeldung heisst — fuer Menschen, nicht fuer URLs.+ pub fn label(self) -> &'static str {+ match self {+ Lane::Engine => "LU Engine",+ Lane::Ollama => "Ollama",+ Lane::LmStudio => "LM Studio",+ }+ }++ pub const ALL: [Lane; 3] = [Lane::Engine, Lane::Ollama, Lane::LmStudio];+ }++ /// Der nach aussen sichtbare Name eines Modells: `lane/upstream-id`.+ ///+ /// Immer qualifiziert, auch wenn der blosse Name eindeutig waere. Ein Client,+ /// der `lu/qwen3-8b` speichert, bekommt morgen dasselbe Modell — auch wenn+ /// jemand inzwischen ein gleichnamiges in Ollama gezogen hat.+ pub fn qualified_id(lane: Lane, upstream_id: &str) -> String {+ format!("{}/{}", lane.prefix(), upstream_id)+ }++ /// Schreibt `model` in einem ANTWORT-Koerper auf die qualifizierte ID zurueck.+ ///+ /// Der Kunden-Testbericht vom 02.09.2026 nennt das seinen haertesten Fund: man+ /// schickt `ollama/llama3.2:3b`, zurueck kommt `"model":"llama3.2:3b"` — die ID+ /// aus der Antwort steht damit NICHT in `/v1/models`. Wer sie weiterverwendet+ /// (Protokoll, Kostenzuordnung, Modellumschalter, Cache-Schluessel), greift ins+ /// Leere; und fuehren zwei Lanes ein gleichnamiges Modell, ist hinterher nicht+ /// mehr feststellbar, wer geantwortet hat. Hin qualifiziert, zurueck nackt, ist+ /// kein Round-Trip.+ ///+ /// Gibt `true` zurueck, wenn wirklich etwas geaendert wurde.+ pub fn modell_zurueckschreiben(json: &mut serde_json::Value, qualifiziert: &str) -> bool {+ match json.get_mut("model") {+ Some(m) if m.is_string() => {+ *m = serde_json::Value::String(qualifiziert.to_string());+ true+ }+ _ => false,+ }+ }++ /// Dasselbe fuer den Streaming-Fall, ohne das Streaming zu zerstoeren.+ ///+ /// Der Antwortkoerper laeuft ungepuffert durch — das ist die Eigenschaft, wegen+ /// der jemand `stream: true` schreibt, und sie darf ein Namensfix nicht kosten.+ /// Also wird zeilenweise umgeschrieben statt am Stueck: was an ganzen Zeilen da+ /// ist, geht sofort weiter; ein angebrochener Rest wartet auf den naechsten+ /// Schub. Ein `"model":"…"` DARF ueber eine Chunk-Grenze fallen, und genau+ /// daran scheitert jede Fassung, die einfach im Bytestrom sucht.+ ///+ /// Zwei Folgen, die ich nicht verschweige: umgeschriebene Zeilen werden neu+ /// serialisiert, deshalb stehen ihre Schluessel danach alphabetisch statt in+ /// Upstream-Reihenfolge, und Gleitkommazahlen bekommen ihre kuerzeste Form.+ /// Beides ist wertgleich (serde_json serialisiert f64 ueber ryu, also exakt+ /// round-trip-fest); die Reihenfolge von JSON-Schluesseln bedeutet nichts.+ /// Zeilen ohne `model` und Zeilen, die nicht als JSON lesbar sind, werden+ /// unveraendert durchgereicht — wir zerstoeren nie, was wir nicht verstehen.+ pub struct SseModellUmschreiber {+ qualifiziert: String,+ rest: Vec<u8>,+ }++ impl SseModellUmschreiber {+ pub fn neu(qualifiziert: &str) -> Self {+ Self { qualifiziert: qualifiziert.to_string(), rest: Vec::new() }+ }++ /// Ein Schub roher Upstream-Bytes rein, die fertigen Zeilen raus.+ pub fn schub(&mut self, chunk: &[u8]) -> Vec<u8> {+ self.rest.extend_from_slice(chunk);+ let mut aus = Vec::new();+ while let Some(nl) = self.rest.iter().position(|b| *b == b'\n') {+ let zeile: Vec<u8> = self.rest.drain(..=nl).collect();+ aus.extend_from_slice(&self.zeile_umschreiben(&zeile));+ }+ aus+ }++ /// Was am Ende noch im Puffer liegt. Nie verschlucken.+ pub fn schluss(&mut self) -> Vec<u8> {+ if self.rest.is_empty() {+ return Vec::new();+ }+ let zeile: Vec<u8> = self.rest.drain(..).collect();+ self.zeile_umschreiben(&zeile)+ }++ fn zeile_umschreiben(&self, zeile: &[u8]) -> Vec<u8> {+ let Ok(text) = std::str::from_utf8(zeile) else {+ return zeile.to_vec(); // kein UTF-8 — nicht unser Protokoll+ };+ // Zeilenende abtrennen und WOERTLICH aufheben: \n und \r\n sind beide+ // gueltig, und wer hier normalisiert, verschiebt fremde Byteanzahlen.+ let (rumpf, ende) = match text.strip_suffix('\n') {+ Some(r) => match r.strip_suffix('\r') {+ Some(r2) => (r2, "\r\n"),+ None => (r, "\n"),+ },+ None => (text, ""),+ };+ let Some(nutz) = rumpf.strip_prefix("data:") else {+ return zeile.to_vec(); // `:`-Kommentar, `event:`, Leerzeile+ };+ let nutz_trim = nutz.trim_start();+ if nutz_trim == "[DONE]" {+ return zeile.to_vec();+ }+ let Ok(mut json) = serde_json::from_str::<serde_json::Value>(nutz_trim) else {+ return zeile.to_vec(); // nicht lesbar — durchreichen, nicht raten+ };+ if !modell_zurueckschreiben(&mut json, &self.qualifiziert) {+ return zeile.to_vec(); // nichts zu tun, also nichts anfassen+ }+ format!("data: {}{}", json, ende).into_bytes()+ }+ }++ /// Ein aufgeloestes Modell.+ #[derive(Debug, Clone, PartialEq, Eq)]+ pub struct ModelRef {+ pub lane: Lane,+ pub upstream_id: String,+ }++ /// Warum ein Name nicht aufgeloest werden konnte.+ #[derive(Debug, Clone, PartialEq, Eq)]+ pub enum ResolveError {+ /// Kein Modell dieses Namens, in keiner Lane.+ Unknown(String),+ /// Blosser Name, den mehrere Lanes fuehren. Wir raten NICHT.+ Ambiguous { requested: String, candidates: Vec<String> },+ /// Der Name nennt eine Lane, die es gibt — die aber gerade nichts fuehrt.+ ///+ /// Aus dem Kundenbericht vom 02.09.2026, Fund 1: von drei beworbenen Lanes+ /// lief eine, und wer `lu/…` anfragte, bekam „Unknown model". Das ist+ /// wahr und trotzdem irrefuehrend — das Modell ist nicht unbekannt, die+ /// Lane ist aus. Der Kunde hielt das Drei-Wege-Versprechen deshalb fuer+ /// unbelegt, und er konnte es nicht besser wissen: die Schnittstelle hat+ /// es ihm nicht gesagt.+ LaneLeer { lane: Lane, requested: String },+ }++ impl ResolveError {+ /// Der Text, der beim Client ankommt. Er nennt immer den Ausweg.+ pub fn message(&self) -> String {+ match self {+ ResolveError::Unknown(id) => format!(+ "Unknown model '{}'. Call GET /v1/models to see what is loaded locally.",+ id+ ),+ ResolveError::Ambiguous { requested, candidates } => format!(+ "Model '{}' exists in more than one local backend ({}). Use the qualified id so the choice is yours, not ours.",+ requested,+ candidates.join(", ")+ ),+ ResolveError::LaneLeer { lane, requested } => format!(+ "Model '{}' asks for the {} lane, but {} currently reports no models — it is most likely not running. Start it, then call GET /v1/models. GET /lu/v1/health shows every lane and what it holds.",+ requested,+ lane.label(),+ lane.label()+ ),+ }+ }++ /// Der `code`-Wert im Fehlerobjekt. Clients pruefen darauf, statt+ /// englische Saetze zu vergleichen.+ pub fn code(&self) -> &'static str {+ match self {+ ResolveError::Unknown(_) => "model_not_found",+ ResolveError::Ambiguous { .. } => "model_ambiguous",+ ResolveError::LaneLeer { .. } => "lane_unavailable",+ }+ }+ }++ /// Was an einem Anfragekoerper fehlt, bevor er ueberhaupt weitergereicht wird.+ ///+ /// Aus dem Kundenbericht, Fund 4: ohne `messages` kam eine durchgereichte+ /// Ollama-Schemameldung („[] is too short - 'messages'") beim Kunden an. Sie+ /// ist kryptisch, sie nennt unser Feld nicht, und sie wechselt mit dem+ /// Upstream. Eine Pflichtfeldpruefung gehoert vor die Weiterleitung, nicht+ /// dahinter.+ #[derive(Debug, Clone, PartialEq, Eq)]+ pub struct FeldFehler {+ pub param: String,+ pub nachricht: String,+ }++ /// Prueft die Felder, ohne die eine Anfrage keinen Sinn hat.+ ///+ /// `pflichtfeld` ist das, was der jeweilige Endpunkt braucht: `messages` beim+ /// Chat, `prompt` bei Completions, `input` bei Embeddings.+ pub fn koerper_pruefen(json: &serde_json::Value, pflichtfeld: &str) -> Result<(), FeldFehler> {+ let modell = json.get("model").and_then(|m| m.as_str()).unwrap_or("").trim();+ if modell.is_empty() {+ return Err(FeldFehler {+ param: "model".into(),+ nachricht: "Missing required parameter: 'model'. Call GET /v1/models for the ids this server accepts.".into(),+ });+ }+ match json.get(pflichtfeld) {+ None | Some(serde_json::Value::Null) => Err(FeldFehler {+ param: pflichtfeld.into(),+ nachricht: format!("Missing required parameter: '{}'.", pflichtfeld),+ }),+ Some(serde_json::Value::Array(a)) if a.is_empty() => Err(FeldFehler {+ param: pflichtfeld.into(),+ nachricht: format!("'{}' is empty. Send at least one entry.", pflichtfeld),+ }),+ _ => Ok(()),+ }+ }++ /// Loest den `model`-Wert einer Anfrage auf.+ ///+ /// `katalog` ist, was die Lanes gerade wirklich fuehren — Paare aus Lane und+ /// der ID, unter der die Lane das Modell kennt.+ ///+ /// Zwei Wege, und der zweite ist der Grund fuer die Laenge dieser Funktion:+ ///+ /// 1. **Qualifiziert** (`ollama/llama3.2:3b`): Praefix abschneiden, in genau+ /// dieser Lane exakt suchen.+ /// 2. **Blosser Name** (`llama3.2:3b`): in allen Lanes suchen. Genau einer →+ /// gut. Mehrere → Fehler mit beiden Namen, NIE eine stille Wahl. Der Nutzer+ /// hat in dem Fall zwei verschiedene Modelle, und welches er meint, weiss+ /// er, wir nicht.+ ///+ /// Der Sonderfall, an dem eine naive Fassung scheitert: Ollama-IDs enthalten+ /// selbst Schraegstriche (`huihui_ai/qwen3-abliterated:4b`). Faengt so eine ID+ /// zufaellig mit `lu/` an, waere sie sonst als LU-Engine-Modell gelesen und+ /// nicht gefunden. Deshalb faellt Weg 1 bei Misserfolg auf Weg 2 zurueck,+ /// statt sofort aufzugeben.+ pub fn resolve_model(requested: &str, katalog: &[(Lane, String)]) -> Result<ModelRef, ResolveError> {+ let req = requested.trim();+ if req.is_empty() {+ return Err(ResolveError::Unknown(String::new()));+ }++ if let Some((pre, rest)) = req.split_once('/') {+ if let Some(lane) = Lane::from_prefix(pre) {+ if let Some((l, id)) = katalog.iter().find(|(l, id)| *l == lane && id == rest) {+ return Ok(ModelRef { lane: *l, upstream_id: id.clone() });+ }+ // Kein Treffer unter dieser Deutung — weiter mit Weg 2, statt hier+ // zu enden. Siehe der `huihui_ai/`-Fall im Kommentar oben.+ }+ }++ let treffer: Vec<&(Lane, String)> = katalog.iter().filter(|(_, id)| id == req).collect();+ match treffer.len() {+ 0 => {+ // Bevor „unbekannt" gesagt wird: nannte der Name eine Lane, die+ // gerade ueberhaupt nichts fuehrt? Dann ist nicht das Modell das+ // Problem, sondern dass das Programm dahinter nicht laeuft — und+ // das ist die Auskunft, mit der jemand etwas anfangen kann.+ if let Some((pre, _)) = req.split_once('/') {+ if let Some(lane) = Lane::from_prefix(pre) {+ if !katalog.iter().any(|(l, _)| *l == lane) {+ return Err(ResolveError::LaneLeer { lane, requested: req.to_string() });+ }+ }+ }+ Err(ResolveError::Unknown(req.to_string()))+ }+ 1 => Ok(ModelRef { lane: treffer[0].0, upstream_id: treffer[0].1.clone() }),+ _ => Err(ResolveError::Ambiguous {+ requested: req.to_string(),+ candidates: treffer.iter().map(|(l, id)| qualified_id(*l, id)).collect(),+ }),+ }+ }++ /// Darf diese Herkunft im Browser mitlesen?+ ///+ /// Aus dem Kundenbericht vom 02.09.2026, Fund 3: der Preflight scheiterte an+ /// der Auth, es gab keinen einzigen `Access-Control-*`-Kopf, und damit war+ /// „jedes Programm, das mit OpenAI spricht" fuer Weboberflaechen schlicht+ /// falsch. Das war kein Versehen — Regel 1 im Kopf dieser Datei nennt genau+ /// die neugierige Webseite als Grund. Aber „gar nicht" ist die falsche Antwort+ /// auf einen echten Bedarf. Die richtige hat dieselbe Form wie der LAN-+ /// Schalter: eine Liste, ab Werk LEER, die der Nutzer selbst fuellt.+ ///+ /// **Kein `*`.** Ein Platzhalter macht aus der Liste wieder „jede Webseite",+ /// und der ganze Wert dieser Liste ist, dass jemand die Herkunft BENENNT, der+ /// er seinen lokalen Modellverkehr zeigen will. Wer `*` eintraegt, bekommt+ /// deshalb keine Freigabe, sondern nichts — lieber ein Eintrag, der sichtbar+ /// nicht wirkt, als eine Tuer, die man versehentlich ganz aufmacht.+ pub fn cors_erlaubt(origin: &str, liste: &[String]) -> bool {+ let o = origin.trim();+ if o.is_empty() || o == "null" || o == "*" {+ return false;+ }+ liste+ .iter()+ .any(|e| !e.trim().is_empty() && e.trim() != "*" && e.trim().eq_ignore_ascii_case(o))+ }++ /// Auf welcher Adresse gelauscht wird.+ ///+ /// `lan == false` ist die Werkseinstellung und heisst 127.0.0.1 — erreichbar+ /// nur von diesem Rechner. `true` heisst 0.0.0.0, also jedes Interface. Es gibt+ /// hier absichtlich keinen dritten Fall und keine Hostnamen: eine Adresse, die+ /// man falsch lesen kann, ist eine Adresse, die man falsch einstellt.+ pub fn bind_addr(lan: bool, port: u16) -> SocketAddr {+ let ip = if lan {+ IpAddr::V4(Ipv4Addr::UNSPECIFIED)+ } else {+ IpAddr::V4(Ipv4Addr::LOCALHOST)+ };+ SocketAddr::new(ip, port)+ }++ /// Tokenvergleich in konstanter Zeit — und leer passt nie.+ ///+ /// Die zweite Haelfte ist die wichtigere. Ein leeres `expected` entsteht ganz+ /// von selbst: Einstellung noch nie geoeffnet, Datei frisch, Feld geleert. Ein+ /// gewoehnliches `expected == presented` machte daraus einen Server, den jeder+ /// mit leerem Token bedienen kann — der Zustand "noch nicht eingerichtet" waere+ /// in der Wirkung "offen fuer alle". Deshalb: leer heisst immer nein.+ ///+ /// Die konstante Zeit ist die kleinere Sorge (ein lokaler Angreifer hat+ /// meistens Besseres), kostet aber nichts.+ pub fn token_matches(expected: &str, presented: &str) -> bool {+ if expected.is_empty() || presented.is_empty() {+ return false;+ }+ let a = expected.as_bytes();+ let b = presented.as_bytes();+ // Die Laenge ist kein Geheimnis (sie ist von uns erzeugt und immer gleich),+ // der Inhalt schon. Ungleiche Laenge -> nein, aber trotzdem durchlaufen.+ let mut diff: u8 = if a.len() == b.len() { 0 } else { 1 };+ let n = a.len().max(b.len());+ for i in 0..n {+ let x = *a.get(i).unwrap_or(&0);+ let y = *b.get(i).unwrap_or(&0);+ diff |= x ^ y;+ }+ diff == 0+ }++ /// Holt das Token aus einer Anfrage: `Authorization: Bearer …` oder `x-api-key`.+ ///+ /// Beide, weil beide in freier Wildbahn vorkommen: OpenAI-Clients schicken+ /// Bearer, Anthropic-Clients `x-api-key`, und wer eine App auf diese API+ /// umbiegt, tauscht selten mehr als die Basis-URL.+ pub fn presented_token(headers: &BTreeMap<String, String>) -> String {+ if let Some(v) = headers.get("authorization") {+ if let Some(b) = v.strip_prefix("Bearer ") {+ return b.trim().to_string();+ }+ if let Some(b) = v.strip_prefix("bearer ") {+ return b.trim().to_string();+ }+ }+ headers.get("x-api-key").map(|v| v.trim().to_string()).unwrap_or_default()+ }++ /// Kopfzeilen, die NIE nach oben weitergereicht werden.+ ///+ /// `authorization` und `x-api-key` stehen hier aus dem Grund, der oben unter+ /// Regel 3 steht: das Token des Aufrufers ist fuer UNS, der Upstream bekommt+ /// seins von uns. Der Rest sind Hop-by-Hop-Kopfzeilen (RFC 9110 §7.6.1) plus+ /// `host` und `content-length`, die der weiterleitende Client selbst setzt —+ /// stehen sie doppelt drin, antwortet der Upstream mit 400.+ const NIE_WEITERLEITEN: [&str; 10] = [+ "authorization",+ "x-api-key",+ "host",+ "content-length",+ "connection",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization",+ "te",+ "transfer-encoding",+ ];++ /// Filtert die Kopfzeilen einer eingehenden Anfrage fuer die Weiterleitung.+ pub fn forward_headers(eingehend: &BTreeMap<String, String>) -> BTreeMap<String, String> {+ eingehend+ .iter()+ .filter(|(k, _)| !NIE_WEITERLEITEN.contains(&k.to_ascii_lowercase().as_str()))+ .map(|(k, v)| (k.to_ascii_lowercase(), v.clone()))+ .collect()+ }++ /// Ein neues Zufallstoken.+ ///+ /// 32 Bytes aus dem Systemzufall, hex — 256 Bit. Laenger als noetig und kuerzer+ /// als unhandlich; es soll in eine Umgebungsvariable passen, die jemand von+ /// Hand kopiert.+ pub fn generate_token() -> String {+ use rand::RngCore;+ let mut b = [0u8; 32];+ rand::thread_rng().fill_bytes(&mut b);+ b.iter().map(|x| format!("{:02x}", x)).collect()+ }+++ // ─────────────────────────────────────────────────────────────────────────────+ // Der Lauscher+ // ─────────────────────────────────────────────────────────────────────────────++ use axum::body::Body;+ use axum::extract::State as AxumState;+ use axum::http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode};+ use axum::response::{IntoResponse, Response};+ use axum::routing::{get, post};+ use axum::{Json, Router};+ use serde::{Deserialize, Serialize};+ use std::sync::Arc;+ use tokio::sync::RwLock;++ /// Wie eine Lane erreicht wird. `base` endet OHNE Schraegstrich und schliesst+ /// `/v1` ein, weil genau das die Adresse ist, die alle drei Programme anbieten.+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+ pub struct Upstream {+ pub lane_prefix: String,+ pub base: String,+ }++ impl Upstream {+ pub fn lane(&self) -> Option<Lane> {+ Lane::from_prefix(&self.lane_prefix)+ }+ }++ /// Die Vorgabe-Upstreams — dieselben Adressen, die die App ohnehin benutzt.+ ///+ /// Sie stehen hier als FALLBACK, nicht als Wahrheit: der Aufrufer aus dem+ /// Frontend kennt den echten Ollama-Base (der Nutzer kann ihn umstellen) und+ /// den Port, auf dem die Engine gerade wirklich laeuft. Wer nichts uebergibt,+ /// bekommt die Werkswerte statt eine leere Liste.+ pub fn default_upstreams() -> Vec<Upstream> {+ vec![+ Upstream { lane_prefix: "lu".into(), base: format!("http://127.0.0.1:{}/v1", crate::commands::engine::DEFAULT_ENGINE_PORT) },+ Upstream { lane_prefix: "ollama".into(), base: "http://127.0.0.1:11434/v1".into() },+ Upstream { lane_prefix: "lmstudio".into(), base: "http://127.0.0.1:1234/v1".into() },+ ]+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct LocalApiConfig {+ pub port: u16,+ /// Werkseinstellung `false`. Siehe Regel 2 im Kopf dieser Datei.+ pub lan: bool,+ pub token: String,+ pub upstreams: Vec<Upstream>,+ /// Herkuenfte, die im Browser mitlesen duerfen. Ab Werk leer — siehe+ /// `cors_erlaubt`.+ #[serde(default)]+ pub cors_origins: Vec<String>,+ }++ impl Default for LocalApiConfig {+ fn default() -> Self {+ Self {+ port: DEFAULT_LOCAL_API_PORT,+ lan: false,+ token: String::new(),+ upstreams: default_upstreams(),+ cors_origins: Vec::new(),+ }+ }+ }++ #[derive(Clone)]+ pub struct LocalApiState {+ pub cfg: Arc<RwLock<LocalApiConfig>>,+ pub http: reqwest::Client,+ }++ /// Was `stop` braucht, um wirklich zu stoppen.+ pub struct LocalApiServer {+ pub addr: SocketAddr,+ pub shutdown: Option<tokio::sync::oneshot::Sender<()>>,+ pub handle: Option<tauri::async_runtime::JoinHandle<()>>,+ }++ impl LocalApiServer {+ pub fn stop(&mut self) {+ if let Some(tx) = self.shutdown.take() {+ let _ = tx.send(());+ }+ if let Some(h) = self.handle.take() {+ h.abort();+ }+ }+ }++ /// Kopfzeilen einer axum-Anfrage in die Form, die die reinen Funktionen oben+ /// lesen. Kleingeschrieben, weil HTTP das ohnehin so meint.+ fn header_map_to_btree(h: &HeaderMap) -> BTreeMap<String, String> {+ h.iter()+ .filter_map(|(k, v)| v.to_str().ok().map(|s| (k.as_str().to_ascii_lowercase(), s.to_string())))+ .collect()+ }++ fn fehler(code: StatusCode, typ: &str, msg: &str) -> Response {+ fehler_mit(code, typ, msg, None, None)+ }++ /// Die Fehlerform von OpenAI — vollstaendig, samt `param` und `code`.+ ///+ /// Aus dem Kundenbericht, Fund 4: beide Felder waren ausnahmslos `null`. Ein+ /// Client, der auf `error.code == "model_not_found"` verzweigt oder dem Nutzer+ /// das falsche Feld markieren will, bekam nichts. `null` ist in OpenAIs Form+ /// erlaubt und heisst „trifft hier nicht zu" — wir hatten es als „haben wir+ /// nicht ausgefuellt" benutzt, und das ist ein anderer Satz.+ fn fehler_mit(code: StatusCode, typ: &str, msg: &str, param: Option<&str>, fehlercode: Option<&str>) -> Response {+ let mut antwort = (code, Json(serde_json::json!({+ "error": {+ "message": msg,+ "type": typ,+ "param": param.map(serde_json::Value::from).unwrap_or(serde_json::Value::Null),+ "code": fehlercode.map(serde_json::Value::from).unwrap_or(serde_json::Value::Null),+ }+ }))).into_response();+ if code == StatusCode::UNAUTHORIZED {+ // RFC 9110: eine 401 OHNE WWW-Authenticate ist protokollwidrig. Manche+ // HTTP-Bibliotheken warten darauf, bevor sie ueberhaupt an Zugangsdaten+ // denken.+ antwort.headers_mut().insert(+ header::WWW_AUTHENTICATE,+ HeaderValue::from_static("Bearer realm=\"LU local API\""),+ );+ }+ antwort+ }++ /// Token-Schranke. Kein Pfad hinter dem Router ist oeffentlich — auch+ /// `/v1/models` nicht, denn die Modellliste verraet, was auf diesem Rechner+ /// liegt, und das ist bei einer App namens Locally Uncensored eine Auskunft+ /// ueber den Nutzer.+ async fn auth(+ AxumState(state): AxumState<LocalApiState>,+ req: axum::extract::Request,+ next: axum::middleware::Next,+ ) -> Response {+ let erwartet = state.cfg.read().await.token.clone();+ let gezeigt = presented_token(&header_map_to_btree(req.headers()));+ if !token_matches(&erwartet, &gezeigt) {+ return fehler_mit(+ StatusCode::UNAUTHORIZED,+ "invalid_request_error",+ if erwartet.is_empty() {+ "The local API has no token yet. Open Settings and generate one — until then it answers nobody."+ } else {+ "Missing or wrong API key. Send it as `Authorization: Bearer <token>` or `x-api-key`."+ },+ None,+ Some("invalid_api_key"),+ );+ }+ next.run(req).await+ }++ #[derive(Serialize)]+ struct ModelZeile {+ id: String,+ object: &'static str,+ created: u64,+ owned_by: String,+ }++ /// Fragt eine Lane nach ihren Modellen. Ein Fehler ist KEIN Abbruch: eine+ /// nicht laufende Lane ist der Normalfall (wer nutzt schon alle drei+ /// gleichzeitig), und sie darf die Liste der anderen nicht mitnehmen.+ async fn lane_modelle(http: &reqwest::Client, up: &Upstream) -> Vec<String> {+ let url = format!("{}/models", up.base.trim_end_matches('/'));+ let r = match http.get(&url).timeout(std::time::Duration::from_secs(4)).send().await {+ Ok(r) if r.status().is_success() => r,+ _ => return Vec::new(),+ };+ let v: serde_json::Value = match r.json().await {+ Ok(v) => v,+ Err(_) => return Vec::new(),+ };+ v.get("data")+ .and_then(|d| d.as_array())+ .map(|a| a.iter().filter_map(|m| m.get("id").and_then(|i| i.as_str()).map(str::to_string)).collect())+ .unwrap_or_default()+ }++ /// Der aktuelle Katalog ueber alle Lanes, in Lane-Reihenfolge.+ async fn katalog(state: &LocalApiState) -> Vec<(Lane, String)> {+ let ups = state.cfg.read().await.upstreams.clone();+ let mut raus: Vec<(Lane, String)> = Vec::new();+ for lane in Lane::ALL {+ for up in ups.iter().filter(|u| u.lane() == Some(lane)) {+ for id in lane_modelle(&state.http, up).await {+ raus.push((lane, id));+ }+ }+ }+ raus+ }++ async fn handle_models(AxumState(state): AxumState<LocalApiState>) -> Response {+ let k = katalog(&state).await;+ let data: Vec<ModelZeile> = k+ .iter()+ .map(|(l, id)| ModelZeile {+ id: qualified_id(*l, id),+ object: "model",+ created: 0,+ owned_by: l.label().to_string(),+ })+ .collect();+ Json(serde_json::json!({ "object": "list", "data": data })).into_response()+ }++ /// Die gemeinsame Weiterleitung fuer alles, was ein `model`-Feld traegt.+ ///+ /// Streaming laeuft als Durchreiche: der Koerper der Upstream-Antwort wird+ /// ohne Zwischenspeicher weitergegeben. Alles andere waere ein Puffer, der+ /// genau die Eigenschaft zerstoert, wegen der jemand `stream: true` schreibt.+ async fn weiterleiten(state: LocalApiState, pfad: &str, pflichtfeld: &str, headers: HeaderMap, body: axum::body::Bytes) -> Response {+ let mut json: serde_json::Value = match serde_json::from_slice(&body) {+ Ok(v) => v,+ Err(e) => {+ return fehler_mit(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ &format!("Body is not JSON: {}", e),+ None,+ Some("invalid_body"),+ )+ }+ };++ // Erst die eigenen Pflichtfelder, dann erst nach oben. Was hier durchfaellt,+ // faellt sonst beim Upstream durch — in dessen Worten, ueber dessen Felder.+ if let Err(f) = koerper_pruefen(&json, pflichtfeld) {+ return fehler_mit(+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ &f.nachricht,+ Some(&f.param),+ Some("missing_required_parameter"),+ );+ }++ let gewuenscht = json.get("model").and_then(|m| m.as_str()).unwrap_or("").to_string();+ let k = katalog(&state).await;+ let ziel = match resolve_model(&gewuenscht, &k) {+ Ok(m) => m,+ Err(e) => {+ let code = match e {+ ResolveError::Ambiguous { .. } => StatusCode::BAD_REQUEST,+ ResolveError::Unknown(_) | ResolveError::LaneLeer { .. } => StatusCode::NOT_FOUND,+ };+ return fehler_mit(code, "invalid_request_error", &e.message(), Some("model"), Some(e.code()));+ }+ };++ // Nach oben geht die ID, die die Lane kennt — nicht unsere qualifizierte.+ if let Some(m) = json.get_mut("model") {+ *m = serde_json::Value::String(ziel.upstream_id.clone());+ }++ let stream_gewuenscht = json.get("stream").and_then(|v| v.as_bool()).unwrap_or(false);++ let base = {+ let cfg = state.cfg.read().await;+ match cfg.upstreams.iter().find(|u| u.lane() == Some(ziel.lane)) {+ Some(u) => u.base.trim_end_matches('/').to_string(),+ None => return fehler(StatusCode::BAD_GATEWAY, "api_error", &format!("{} has no configured address.", ziel.lane.label())),+ }+ };++ let mut req = state.http.post(format!("{}{}", base, pfad));+ for (k, v) in forward_headers(&header_map_to_btree(&headers)) {+ if let (Ok(name), Ok(val)) = (HeaderName::try_from(k.as_str()), HeaderValue::from_str(&v)) {+ req = req.header(name, val);+ }+ }+ let antwort = match req.json(&json).send().await {+ Ok(r) => r,+ Err(e) => {+ return fehler(+ StatusCode::BAD_GATEWAY,+ "api_error",- &format!("{} did not answer at {}: {}", ziel.lane.label(), base, e),++ &format!(++ "{} did not answer at {}: {}",++ ziel.lane.label(),++ base,++ crate::os_error::english(&e)++ ),+ )+ }+ };++ let status = antwort.status();+ let ctype = antwort+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("application/json")+ .to_string();++ let mut out = Response::builder().status(status);+ if let Ok(v) = HeaderValue::from_str(&ctype) {+ out = out.header(header::CONTENT_TYPE, v);+ }++ // Auf dem Rueckweg traegt `model` wieder die qualifizierte ID. Ohne das+ // steht in der Antwort ein Name, den `/v1/models` nicht kennt.+ let qualifiziert = qualified_id(ziel.lane, &ziel.upstream_id);++ if !stream_gewuenscht {+ // Eine einzelne JSON-Antwort. Sie zu puffern kostet nichts: es gibt+ // hier nichts zu streamen, was ein Client frueher sehen koennte.+ let bytes = match antwort.bytes().await {+ Ok(b) => b,+ Err(e) => {+ return fehler(+ StatusCode::BAD_GATEWAY,+ "api_error",- &format!("{} broke off mid-answer: {}", ziel.lane.label(), e),++ &format!(++ "{} broke off mid-answer: {}",++ ziel.lane.label(),++ crate::os_error::english(&e)++ ),+ )+ }+ };+ let raus = match serde_json::from_slice::<serde_json::Value>(&bytes) {+ Ok(mut v) => {+ modell_zurueckschreiben(&mut v, &qualifiziert);+ Body::from(v.to_string())+ }+ // Kein JSON (etwa ein HTML-Fehler eines Proxys davor): unveraendert+ // weitergeben. Der Client soll sehen, was wirklich kam.+ Err(_) => Body::from(bytes),+ };+ return out+ .body(raus)+ .unwrap_or_else(|_| fehler(StatusCode::INTERNAL_SERVER_ERROR, "api_error", "Could not build the response."));+ }++ // Streaming: zeilenweise umschreiben, ohne zu puffern. `unfold` traegt den+ // Umschreiber ueber die Chunk-Grenzen und gibt am Schluss noch heraus, was+ // im Rest liegt — ein abgerissener Upstream soll Bytes verlieren duerfen,+ // wir nicht.+ let quelle = antwort.bytes_stream();+ let strom = futures_util::stream::unfold(+ (quelle, SseModellUmschreiber::neu(&qualifiziert), false),+ |(mut quelle, mut um, fertig)| async move {+ use futures_util::StreamExt;+ if fertig {+ return None;+ }+ match quelle.next().await {+ Some(Ok(chunk)) => {+ let raus = um.schub(&chunk);+ Some((Ok::<_, std::io::Error>(axum::body::Bytes::from(raus)), (quelle, um, false)))+ }+ Some(Err(e)) => Some((+ Err(std::io::Error::other(e.to_string())),+ (quelle, um, true),+ )),+ None => {+ let rest = um.schluss();+ Some((Ok(axum::body::Bytes::from(rest)), (quelle, um, true)))+ }+ }+ },+ );++ out.body(Body::from_stream(strom))+ .unwrap_or_else(|_| fehler(StatusCode::INTERNAL_SERVER_ERROR, "api_error", "Could not build the response."))+ }++ async fn handle_chat(AxumState(state): AxumState<LocalApiState>, headers: HeaderMap, body: axum::body::Bytes) -> Response {+ weiterleiten(state, "/chat/completions", "messages", headers, body).await+ }++ async fn handle_completions(AxumState(state): AxumState<LocalApiState>, headers: HeaderMap, body: axum::body::Bytes) -> Response {+ weiterleiten(state, "/completions", "prompt", headers, body).await+ }++ async fn handle_embeddings(AxumState(state): AxumState<LocalApiState>, headers: HeaderMap, body: axum::body::Bytes) -> Response {+ weiterleiten(state, "/embeddings", "input", headers, body).await+ }++ /// Was gerade laeuft und wohin geleitet wird. Auch das steht hinter dem Token.+ async fn handle_health(AxumState(state): AxumState<LocalApiState>) -> Response {+ let cfg = state.cfg.read().await.clone();+ let k = katalog(&state).await;+ let mut je_lane = serde_json::Map::new();+ for lane in Lane::ALL {+ je_lane.insert(+ lane.prefix().to_string(),+ serde_json::json!({+ "label": lane.label(),+ "base": cfg.upstreams.iter().find(|u| u.lane() == Some(lane)).map(|u| u.base.clone()),+ "models": k.iter().filter(|(l, _)| *l == lane).count(),+ }),+ );+ }+ Json(serde_json::json!({+ "ok": true,+ "reach": if cfg.lan { "lan" } else { "localhost" },+ "port": cfg.port,+ "lanes": je_lane,+ }))+ .into_response()+ }++ /// Die LU-Werkzeuge, die ein Agent auf diesem Rechner hat — mitsamt der Frage,+ /// welche Erlaubnis jedes braucht.+ ///+ /// ── WOZU DAS GUT IST ───────────────────────────────────────────────────────+ ///+ /// Ein Programm, das die lokale API benutzt, kann /v1/chat/completions rufen+ /// und bekommt ein Modell. Was es NICHT weiss: dass dieser Rechner Dateien+ /// lesen, im Netz suchen und Code ausfuehren kann, und was davon der Nutzer+ /// freigegeben hat. Diese Liste ist die Antwort darauf, und sie ist ehrlich —+ /// die Namen und Erlaubnisstufen sind DIESELBEN, die `gate_for` in remote.rs+ /// durchsetzt, nicht eine gepflegte Zweitliste.+ ///+ /// ── WAS HIER (NOCH) NICHT STEHT ────────────────────────────────────────────+ ///+ /// Ein Endpunkt, der einen ganzen Agentenlauf ausfuehrt — Modell rufen,+ /// Werkzeugaufrufe lesen, ausfuehren, zurueckgeben, wiederholen. Der Grund ist+ /// nicht Zeitmangel allein, sondern wo der Ausfuehrer heute steht: er ist ein+ /// rund 400 Zeilen langes `match` INNERHALB von `handle_agent_tool` in+ /// remote.rs, verwoben mit `RemoteState`, dem Erlaubnis-Schloss und dem+ /// Arbeitsordner-Ueberschreiben je Chat. Ihn herauszuloesen ist ein Eingriff in+ /// eine 4.900-Zeilen-Datei, an der gerade parallel gearbeitet wird — und ihn+ /// hier ein zweites Mal zu schreiben, waere genau die Zweitliste, vor der der+ /// Kommentar bei GATE_KEYWORDS warnt.+ ///+ /// Der Weg dahin ist vorgezeichnet: `gate_for` und der `match`-Block wandern in+ /// ein eigenes Modul mit einer Signatur ohne `RemoteState`, dann rufen ihn+ /// beide Server. Das ist eine Aufgabe fuer sich, mit eigenen Sperren.+ fn lu_werkzeuge() -> serde_json::Value {+ // (Name, Erlaubnis, was es tut) — Erlaubnis `null` heisst: immer offen.+ let liste: [(&str, Option<&str>, &str); 13] = [+ ("file_read", Some("filesystem"), "Read a file, windowed by offset/limit."),+ ("file_write", Some("filesystem"), "Write a file inside the agent workspace."),+ ("file_list", Some("filesystem"), "List a directory."),+ ("file_search", Some("filesystem"), "Search file contents."),+ ("screenshot", Some("filesystem"), "Capture the screen."),+ ("shell_execute", Some("shell"), "Run a shell command. RCE-class, off by default."),+ ("code_execute", Some("shell"), "Run code. RCE-class, off by default."),+ ("image_generate", Some("process_control"), "Generate an image via the local pipeline."),+ ("web_search", None, "Search the web."),+ ("web_fetch", None, "Read a URL."),+ ("process_list", Some("process_control"), "List running processes."),+ ("system_info", None, "OS, CPU and memory of this machine."),+ ("get_current_time", None, "The clock of this machine."),+ ];+ serde_json::json!({+ "object": "list",+ "data": liste.iter().map(|(name, perm, was)| serde_json::json!({+ "name": name,+ "requires_permission": perm,+ "description": was,+ })).collect::<Vec<_>>(),+ // Ehrlich dazugesagt, statt es den Aufrufer selbst herausfinden zu+ // lassen: diese Liste sagt, was es GIBT, nicht was gerade erlaubt ist.+ // Der Erlaubnisstand haengt am Remote-Panel des Nutzers und wird hier+ // bewusst nicht gespiegelt — eine gespiegelte Erlaubnis, die hinter der+ // echten herhinkt, ist gefaehrlicher als gar keine Angabe.+ "note": "Availability depends on the permissions the user granted in Settings → Remote Access. This list is the catalogue, not the current grant.",+ // Fund 7 des Kundenberichts: 13 Werkzeuge auflisten und keinen Weg+ // anbieten, eines aufzurufen, ist schlechter als sie wegzulassen. Der+ // Katalog bleibt trotzdem — er beantwortet „was kann dieses Geraet",+ // und das ist eine eigene Frage. Er sagt jetzt nur unmissverstaendlich,+ // dass es hier keinen Aufrufweg gibt, und wo einer ist. (Die vorige+ // Fassung verwies auf eine Quelldatei, die kein Kunde hat.)+ "callable_here": false,+ "how_to_call": "This endpoint is a catalogue, not a call surface: there is no POST here. These tools run inside LU itself — from a chat, or over Remote Access after pairing in Settings → Remote Access. An HTTP endpoint for agent runs is planned and not built yet.",+ })+ }++ async fn handle_tools() -> Response {+ Json(lu_werkzeuge()).into_response()+ }++ /// Die Selbstauskunft.+ ///+ /// Aus dem Kundenbericht, Fund 5: `/docs` und `/openapi.json` waren beide 404,+ /// und dass das Lane-Praefix optional ist, wie die Lanes heissen und welche+ /// Parameter durchgereicht werden, hat der Kunde ausschliesslich durch+ /// Ausprobieren herausgefunden. Genau das steht jetzt hier — an einer Adresse,+ /// die der 404 auch nennt.+ fn lu_doku() -> serde_json::Value {+ serde_json::json!({+ "object": "documentation",+ "name": "LU local model API",+ "summary": "One OpenAI-compatible address in front of every model backend on this machine.",+ "auth": {+ "required": "always, also on 127.0.0.1",+ "headers": ["Authorization: Bearer <token>", "x-api-key: <token>"],+ "where_from": "Settings → Local API in the LU app generates it.",+ },+ "model_names": {+ "form": "<lane>/<id as the backend knows it>",+ "lanes": Lane::ALL.iter().map(|l| serde_json::json!({+ "prefix": l.prefix(),+ "name": l.label(),+ })).collect::<Vec<_>>(),+ "prefix_optional": "A bare id works when exactly one lane holds it. When two lanes hold the same name the request is refused rather than guessed — send the qualified id.",+ "round_trip": "Responses echo the qualified id, so what comes back is always findable in GET /v1/models.",+ },+ "routes": [+ { "method": "GET", "path": "/v1/models", "note": "Every model across every running lane." },+ { "method": "POST", "path": "/v1/chat/completions", "note": "Requires `model` and `messages`. `stream: true` streams." },+ { "method": "POST", "path": "/v1/completions", "note": "Requires `model` and `prompt`." },+ { "method": "POST", "path": "/v1/embeddings", "note": "Requires `model` and `input`." },+ { "method": "GET", "path": "/lu/v1/health", "note": "Per-lane state: address, reachable, model count." },+ { "method": "GET", "path": "/lu/v1/tools", "note": "Catalogue of LU agent tools. Not callable over HTTP yet." },+ { "method": "GET", "path": "/lu/v1/docs", "note": "This page." },+ ],+ "passthrough": "Everything other than `model` goes to the backend untouched — temperature, tools, response_format, and whatever else that backend supports. What a lane cannot do, this API cannot add.",+ "errors": {+ "shape": "OpenAI's: { error: { message, type, param, code } }",+ "codes": ["invalid_api_key", "invalid_body", "missing_required_parameter", "model_not_found", "model_ambiguous", "lane_unavailable"],+ "lane_unavailable": "The name asked for a real lane that currently holds no models — that backend is most likely not running.",+ },+ "cors": "Off until you list an origin under Settings → Local API. No wildcard: name the origin you want to let read your local model traffic.",+ "request_id": "Every response carries `x-request-id`. Send your own and it is kept, so a report can be correlated.",+ })+ }++ async fn handle_docs() -> Response {+ Json(lu_doku()).into_response()+ }++ /// Eine Kennung pro Anfrage, damit ein Fehlerbericht etwas hat, worauf er+ /// zeigen kann.+ ///+ /// Aus dem Kundenbericht, Fund 8: die Antworten trugen `content-type`, `date`+ /// und `transfer-encoding` — sonst nichts. Wer einen Fehler meldet, kann ihn+ /// mit nichts abgleichen. Eine mitgeschickte eigene Kennung wird UEBERNOMMEN+ /// statt ueberschrieben; genau das macht Korrelation ueber mehrere Schichten+ /// hinweg erst moeglich.+ fn naechste_request_id(eigen: Option<&str>) -> String {+ use std::sync::atomic::{AtomicU64, Ordering};+ static ZAEHLER: AtomicU64 = AtomicU64::new(0);+ static START: std::sync::OnceLock<String> = std::sync::OnceLock::new();+ if let Some(e) = eigen {+ let e = e.trim();+ // Fremde Kennungen begrenzen: sie landen in einem Antwortkopf, und ein+ // Kopf, dessen Laenge der Aufrufer bestimmt, ist ein Hebel.+ if !e.is_empty() && e.len() <= 200 && e.chars().all(|c| c.is_ascii_graphic()) {+ return e.to_string();+ }+ }+ let start = START.get_or_init(|| generate_token()[..8].to_string());+ format!("req_{}_{:x}", start, ZAEHLER.fetch_add(1, Ordering::Relaxed))+ }++ /// Setzt `x-request-id` auf jede Antwort, auch auf Fehler.+ async fn request_id(req: axum::extract::Request, next: axum::middleware::Next) -> Response {+ let id = naechste_request_id(req.headers().get("x-request-id").and_then(|v| v.to_str().ok()));+ let mut res = next.run(req).await;+ if let Ok(v) = HeaderValue::from_str(&id) {+ res.headers_mut().insert(HeaderName::from_static("x-request-id"), v);+ }+ res+ }++ /// Die CORS-Schranke. Sitzt VOR der Token-Schranke, weil ein Browser dem+ /// Preflight nie Zugangsdaten mitgibt — eine 401 auf OPTIONS ist der Grund,+ /// warum beim Kunden jede Weboberflaeche scheiterte.+ async fn cors(+ AxumState(state): AxumState<LocalApiState>,+ req: axum::extract::Request,+ next: axum::middleware::Next,+ ) -> Response {+ let herkunft = req+ .headers()+ .get(header::ORIGIN)+ .and_then(|v| v.to_str().ok())+ .map(|s| s.to_string());+ let erlaubt = match &herkunft {+ Some(o) => {+ let liste = state.cfg.read().await.cors_origins.clone();+ cors_erlaubt(o, &liste).then(|| o.clone())+ }+ None => None,+ };++ let ist_preflight = req.method() == Method::OPTIONS;+ let mut res = if ist_preflight {+ // Nie an die Token-Schranke weitergeben: der Preflight KANN sie nicht+ // bestehen. Ist die Herkunft nicht freigegeben, kommt eine leere 204+ // ohne CORS-Koepfe zurueck — der Browser blockt dann von selbst, und+ // wir haben nichts verraten.+ StatusCode::NO_CONTENT.into_response()+ } else {+ next.run(req).await+ };++ if let Some(o) = erlaubt {+ let k = res.headers_mut();+ if let Ok(v) = HeaderValue::from_str(&o) {+ k.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, v);+ }+ k.insert(header::ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("GET, POST, OPTIONS"));+ k.insert(+ header::ACCESS_CONTROL_ALLOW_HEADERS,+ HeaderValue::from_static("authorization, x-api-key, content-type, x-request-id"),+ );+ k.insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, HeaderValue::from_static("x-request-id"));+ k.insert(header::ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("600"));+ }+ // Die Antwort haengt von der Herkunft ab — ohne `Vary` liefert jeder Cache+ // davor irgendwann die Freigabe an den Falschen aus.+ res.headers_mut().insert(header::VARY, HeaderValue::from_static("Origin"));+ res+ }++ pub fn build_local_api_router(state: LocalApiState) -> Router {+ // Die Schichtreihenfolge ist Sicherheit, nicht Geschmack: axum wickelt von+ // unten nach oben, `cors` steht also GANZ AUSSEN und `auth` darunter. Nur+ // so faellt der Preflight nicht in die Token-Schranke. Umgekehrt darf CORS+ // nie eine Anfrage durchlassen, die auth abgelehnt haette — tut es auch+ // nicht: ausser OPTIONS geht alles durch `next`, also durch auth.+ Router::new()+ .route("/v1/models", get(handle_models))+ .route("/v1/chat/completions", post(handle_chat))+ .route("/v1/completions", post(handle_completions))+ .route("/v1/embeddings", post(handle_embeddings))+ .route("/lu/v1/health", get(handle_health))+ .route("/lu/v1/tools", get(handle_tools))+ .route("/lu/v1/docs", get(handle_docs))+ .fallback(|method: Method, uri: axum::http::Uri| async move {+ fehler(+ StatusCode::NOT_FOUND,+ "invalid_request_error",+ &format!("No route {} {}. This server speaks /v1/models, /v1/chat/completions, /v1/completions, /v1/embeddings, /lu/v1/health, /lu/v1/tools and /lu/v1/docs — the last one describes all of them.", method, uri.path()),+ )+ })+ .layer(axum::middleware::from_fn_with_state(state.clone(), auth))+ .layer(axum::middleware::from_fn_with_state(state.clone(), cors))+ .layer(axum::middleware::from_fn(request_id))+ .with_state(state)+ }+++ // ─────────────────────────────────────────────────────────────────────────────+ // Start, Stopp, Auskunft — die Tauri-Befehle+ // ─────────────────────────────────────────────────────────────────────────────++ /// Startet die lokale API. Ein zweiter Aufruf stoppt zuerst den alten Lauscher,+ /// damit ein Portwechsel nicht zwei Server hinterlaesst.+ ///+ /// Ohne Token wird NICHT gestartet. Das ist kein Komfortverlust, sondern die+ /// einzige Stelle, an der Regel 1 wirklich durchgesetzt werden kann: ein+ /// laufender Server ohne Token waere auch mit `token_matches`-Schutz eine+ /// offene Tuer, die nur zufaellig zu ist.+ #[tauri::command]+ pub async fn start_local_api(+ state: tauri::State<'_, crate::state::AppState>,+ port: Option<u16>,+ lan: Option<bool>,+ token: String,+ upstreams: Option<Vec<Upstream>>,+ cors_origins: Option<Vec<String>>,+ ) -> Result<serde_json::Value, String> {+ if token.trim().is_empty() {+ return Err("The local API needs a token before it can start. Generate one in Settings.".into());+ }++ stop_local_api_inner(&state);++ let cfg = LocalApiConfig {+ port: port.unwrap_or(DEFAULT_LOCAL_API_PORT),+ lan: lan.unwrap_or(false),+ token: token.trim().to_string(),+ upstreams: upstreams.unwrap_or_else(default_upstreams),+ // Ab Werk leer, und `None` heisst leer — nicht „wie zuletzt". Eine+ // Freigabe, die ein Aufrufer versehentlich weglaesst, soll erloeschen.+ cors_origins: cors_origins+ .unwrap_or_default()+ .into_iter()+ .map(|o| o.trim().to_string())+ .filter(|o| !o.is_empty())+ .collect(),+ };+ let addr = bind_addr(cfg.lan, cfg.port);++ let api_state = LocalApiState {+ cfg: Arc::new(RwLock::new(cfg.clone())),+ http: reqwest::Client::builder()+ // Kein Gesamt-Timeout: ein langer Stream ist der Normalfall, kein+ // Fehler. Nur das Verbinden bekommt eine Frist, damit ein totes+ // Backend nicht ewig haengt.+ .connect_timeout(std::time::Duration::from_secs(5))+ .build()+ .map_err(|e| e.to_string())?,+ };++ let listener = tokio::net::TcpListener::bind(addr)+ .await+ .map_err(|e| format!("Could not listen on {}: {}", addr, e))?;+ let echte_addr = listener.local_addr().map_err(|e| e.to_string())?;++ let (tx, rx) = tokio::sync::oneshot::channel::<()>();+ let router = build_local_api_router(api_state);+ let handle = tauri::async_runtime::spawn(async move {+ let _ = axum::serve(listener, router)+ .with_graceful_shutdown(async {+ let _ = rx.await;+ })+ .await;+ });++ if let Ok(mut slot) = state.local_api.lock() {+ *slot = Some(LocalApiServer { addr: echte_addr, shutdown: Some(tx), handle: Some(handle) });+ }++ Ok(serde_json::json!({+ "running": true,+ "address": echte_addr.to_string(),+ "reach": if cfg.lan { "lan" } else { "localhost" },+ "baseUrl": format!("http://{}/v1", if cfg.lan { format!("<this-machine>:{}", echte_addr.port()) } else { echte_addr.to_string() }),+ }))+ }++ fn stop_local_api_inner(state: &crate::state::AppState) {+ if let Ok(mut slot) = state.local_api.lock() {+ if let Some(mut s) = slot.take() {+ s.stop();+ }+ }+ }++ #[tauri::command]+ pub async fn stop_local_api(state: tauri::State<'_, crate::state::AppState>) -> Result<serde_json::Value, String> {+ stop_local_api_inner(&state);+ Ok(serde_json::json!({ "running": false }))+ }++ #[tauri::command]+ pub async fn local_api_status(state: tauri::State<'_, crate::state::AppState>) -> Result<serde_json::Value, String> {+ let laeuft = state+ .local_api+ .lock()+ .ok()+ .and_then(|s| s.as_ref().map(|x| x.addr))+ .map(|a| serde_json::json!({ "running": true, "address": a.to_string() }))+ .unwrap_or_else(|| serde_json::json!({ "running": false }));+ Ok(laeuft)+ }++ /// Ein frisches Token. Aufbewahrt wird es vom Frontend (dort liegt der+ /// Schluesselbund-Pfad mitsamt Linux-Rueckfall); hier wird es nur erzeugt,+ /// damit der Zufall aus dem System kommt und nicht aus `Math.random`.+ #[tauri::command]+ pub fn local_api_new_token() -> String {+ generate_token()+ }+++ /// Echte Laeufe gegen ein echtes Backend.+ ///+ /// Kein Mock, keine Attrappe: dieser Modul startet den ECHTEN Router auf einem+ /// freien Port und schickt echte HTTP-Anfragen hindurch an das Ollama, das auf+ /// diesem Rechner laeuft. Was hier gruen ist, ist im Betrieb gruen.+ ///+ /// Netzabhaengig und maschinenabhaengig, deshalb hinter einem Schalter:+ ///+ /// LIVE_LOCAL_API=1 cargo test local_api_echt -- --nocapture --test-threads=1+ ///+ /// Was er NICHT beweist: dass das Token des Aufrufers nicht nach oben geht.+ /// Das braeuchte einen mithoerenden Upstream, also eine Attrappe — und die+ /// waere hier genau das Falsche. Diese Zusicherung steht als reine Funktion+ /// im Modul `tests` oben (`das_token_des_aufrufers_geht_nicht_nach_oben`).+ #[cfg(test)]+ mod werkzeugliste {+ use super::*;++ /// Die Liste in `lu_werkzeuge` und das Schloss `gate_for` in remote.rs+ /// muessen dasselbe sagen.+ ///+ /// Der Fehler, den das verhindert, ist leise: jemand nimmt ein Werkzeug in+ /// `gate_for` auf oder verschiebt es auf eine strengere Erlaubnis, und die+ /// Liste hier sagt weiter das Alte. Ein Programm, das sie liest, plant dann+ /// mit einem Werkzeug, das es nicht bekommt — oder haelt eines fuer+ /// gesperrt, das offen ist. Beides merkt niemand, weil beide Seiten fuer+ /// sich stimmen.+ ///+ /// Gelesen wird der QUELLTEXT von remote.rs, nicht eine Kopie: eine+ /// gepflegte Zweitliste waere genau das Problem, das hier bewacht wird.+ #[test]+ fn sie_sagt_dasselbe_wie_das_schloss_in_remote_rs() {+ let hier = std::path::Path::new(file!()).parent().unwrap().to_path_buf();+ let remote = std::fs::read_to_string(hier.join("remote.rs"))+ .expect("remote.rs liegt nicht mehr neben local_api.rs");++ let anfang = remote.find("fn gate_for(tool: &str) -> ToolGate {")+ .expect("gate_for heisst nicht mehr so");+ let block = &remote[anfang..anfang + remote[anfang..].find("\n}\n").unwrap()];++ // Zeilenumbrueche raus, bevor gesucht wird: ein Zweig darf ueber+ // mehrere Zeilen gehen, und genau daran ist meine erste Fassung+ // gescheitert — sie las acht von zehn Eintraegen und haette den Rest+ // stillschweigend als "nicht vorhanden" gewertet. Ein Waechter, der+ // die Haelfte uebersieht, ist schlimmer als keiner.+ let flach = block.split_whitespace().collect::<Vec<_>>().join(" ");+ let teile: Vec<&str> = flach.split("=>").collect();++ let mut aus_remote: std::collections::BTreeMap<String, Option<String>> = Default::default();+ for i in 0..teile.len().saturating_sub(1) {+ let links = teile[i];+ let rechts = teile[i + 1];+ let erlaubnis = if rechts.trim_start().starts_with("ToolGate::Open") {+ None+ } else if let Some(j) = rechts.find("Needs(\"") {+ // Nur wenn das Needs VOR dem naechsten Zweig steht.+ if j > 40 { continue }+ let rest = &rechts[j + 7..];+ Some(rest[..rest.find('"').unwrap()].to_string())+ } else {+ continue // der Unknown-Zweig+ };+ // Der linke Teil endet auf den Mustern dieses Zweigs; alles davor+ // gehoert zum vorigen. Vom Ende her lesen.+ for name in links.rsplit('|') {+ let n = name.trim().trim_matches(|c| c == '"' || c == ' ' || c == '}' || c == '{');+ let n = n.rsplit(' ').next().unwrap_or(n).trim_matches('"');+ if n.is_empty() || n == "_" || n.contains('(') { break }+ aus_remote.insert(n.to_string(), erlaubnis.clone());+ }+ }+ assert!(aus_remote.len() >= 10, "gate_for wurde nicht gelesen: {:?}", aus_remote);++ let liste = lu_werkzeuge();+ let mut aus_liste: std::collections::BTreeMap<String, Option<String>> = Default::default();+ for e in liste["data"].as_array().unwrap() {+ aus_liste.insert(+ e["name"].as_str().unwrap().to_string(),+ e["requires_permission"].as_str().map(str::to_string),+ );+ }++ assert_eq!(+ aus_liste, aus_remote,+ "\nlu_werkzeuge() und gate_for() sind auseinandergelaufen.\n\+ links = die Liste, die die lokale API ausgibt\n\+ rechts = das Schloss, das wirklich entscheidet\n"+ );+ }+ }++ #[cfg(test)]+ mod local_api_echt {+ use super::*;+ use std::future::IntoFuture;++ const TOKEN: &str = "pruefzeichen-0123456789abcdef";++ fn an() -> bool {+ std::env::var("LIVE_LOCAL_API").ok().as_deref() == Some("1")+ }++ /// Startet den echten Router auf einem freien Port. Gibt die Basis-URL zurueck.+ async fn starte() -> Option<(String, tokio::task::JoinHandle<()>)> {+ starte_mit(Vec::new()).await+ }++ /// Dasselbe, aber mit einer CORS-Erlaubnisliste.+ async fn starte_mit(cors: Vec<String>) -> Option<(String, tokio::task::JoinHandle<()>)> {+ let http = reqwest::Client::builder()+ .connect_timeout(std::time::Duration::from_secs(5))+ .build()+ .ok()?;+ // Vorpruefung: laeuft ueberhaupt eine Lane? Ohne das ist der Lauf+ // aussagelos, und ein gruener aussageloser Lauf ist schlimmer als+ // gar keiner.+ let ollama_da = http+ .get("http://127.0.0.1:11434/v1/models")+ .timeout(std::time::Duration::from_secs(3))+ .send()+ .await+ .map(|r| r.status().is_success())+ .unwrap_or(false);+ if !ollama_da {+ eprintln!("[local_api_echt] Ollama antwortet nicht auf 11434 — uebersprungen");+ return None;+ }++ let cfg = LocalApiConfig {+ port: 0,+ lan: false,+ token: TOKEN.to_string(),+ upstreams: default_upstreams(),+ cors_origins: cors,+ };+ let state = LocalApiState { cfg: Arc::new(RwLock::new(cfg)), http };+ let l = tokio::net::TcpListener::bind(bind_addr(false, 0)).await.ok()?;+ let addr = l.local_addr().ok()?;+ let router = build_local_api_router(state);+ let h = tokio::spawn(async move {+ let _ = axum::serve(l, router).await;+ });+ Some((format!("http://{}", addr), h))+ }++ #[tokio::test]+ async fn ohne_token_antwortet_sie_niemandem() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();++ for (was, req) in [+ ("gar kein Token", c.get(format!("{}/v1/models", base))),+ ("falsches Token", c.get(format!("{}/v1/models", base)).bearer_auth("falsch")),+ ("leeres Token", c.get(format!("{}/v1/models", base)).bearer_auth("")),+ ] {+ let r = req.send().await.expect("Anfrage");+ assert_eq!(r.status(), 401, "{} kam durch", was);+ }++ // Und das Gegenstueck: mit dem richtigen Token geht es.+ let r = c.get(format!("{}/v1/models", base)).bearer_auth(TOKEN).send().await.unwrap();+ assert_eq!(r.status(), 200);+ h.abort();+ }++ #[tokio::test]+ async fn die_modellliste_traegt_qualifizierte_namen() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let v: serde_json::Value = reqwest::Client::new()+ .get(format!("{}/v1/models", base))+ .bearer_auth(TOKEN)+ .send().await.unwrap().json().await.unwrap();+ let ids: Vec<String> = v["data"].as_array().unwrap().iter()+ .map(|m| m["id"].as_str().unwrap().to_string()).collect();+ eprintln!("[local_api_echt] {} Modelle: {:?}", ids.len(), &ids[..ids.len().min(4)]);+ assert!(!ids.is_empty(), "keine Modelle — laeuft Ollama wirklich?");+ // Jede ID traegt ihre Lane. Ohne das kann ein Client nicht wissen,+ // welches Programm ihm antwortet.+ assert!(ids.iter().all(|i| i.starts_with("lu/") || i.starts_with("ollama/") || i.starts_with("lmstudio/")),+ "unqualifizierte ID dabei: {:?}", ids);+ assert!(ids.iter().any(|i| i.starts_with("ollama/")), "Ollama fehlt in der Liste");+ h.abort();+ }++ #[tokio::test]+ async fn ein_echter_zug_kommt_durch() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();+ let Some(modell) = kleinstes_ollama_modell(&c, &base).await else { h.abort(); return };+ eprintln!("[local_api_echt] Zug ueber {}", modell);++ let r = c.post(format!("{}/v1/chat/completions", base))+ .bearer_auth(TOKEN)+ .json(&serde_json::json!({+ "model": modell,+ "messages": [{"role": "user", "content": "Answer with the single word: ready"}],+ "max_tokens": 16,+ "temperature": 0,+ }))+ .timeout(std::time::Duration::from_secs(180))+ .send().await.expect("Anfrage");+ assert_eq!(r.status(), 200, "Antwort: {:?}", r.text().await);+ let v: serde_json::Value = r.json().await.unwrap();+ let text = v["choices"][0]["message"]["content"].as_str().unwrap_or("");+ eprintln!("[local_api_echt] Antwort: {:?}", text);+ assert!(!text.trim().is_empty(), "leere Antwort: {}", v);+ h.abort();+ }++ #[tokio::test]+ async fn ein_strom_kommt_in_stuecken_an_und_nicht_am_stueck() {+ if !an() { return }+ use futures_util::StreamExt;+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();+ let Some(modell) = kleinstes_ollama_modell(&c, &base).await else { h.abort(); return };++ let r = c.post(format!("{}/v1/chat/completions", base))+ .bearer_auth(TOKEN)+ .json(&serde_json::json!({+ "model": modell,+ "messages": [{"role": "user", "content": "Count from one to ten in words."}],+ "max_tokens": 64,+ "temperature": 0,+ "stream": true,+ }))+ .timeout(std::time::Duration::from_secs(180))+ .send().await.expect("Anfrage");+ assert_eq!(r.status(), 200);++ let mut stuecke = 0usize;+ let mut bytes = 0usize;+ let mut strom = r.bytes_stream();+ while let Some(Ok(b)) = strom.next().await {+ stuecke += 1;+ bytes += b.len();+ }+ eprintln!("[local_api_echt] Strom: {} Stuecke, {} Bytes", stuecke, bytes);+ assert!(bytes > 0, "nichts angekommen");+ // Der eigentliche Punkt: mehr als EIN Stueck. Wer die Antwort+ // zwischenspeichert und am Ende ausliefert, kommt hier auf 1 — und+ // genau dafuer schreibt niemand `stream: true`.+ assert!(stuecke > 1, "in einem Stueck angekommen — da puffert jemand");+ h.abort();+ }++ #[tokio::test]+ async fn ein_unbekanntes_modell_sagt_wo_man_nachsieht() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let r = reqwest::Client::new()+ .post(format!("{}/v1/chat/completions", base))+ .bearer_auth(TOKEN)+ // Die Nutzlast ist ansonsten GUELTIG. Vorher stand hier+ // `"messages": []`, und der 404 kam nur, weil niemand die leere+ // Liste prueste — seit `koerper_pruefen` faengt die sie vorher ab,+ // und der Test haette eine 400 fuer einen Modellbefund gehalten.+ .json(&serde_json::json!({+ "model": "gibtsnicht-42",+ "messages": [{"role": "user", "content": "hi"}],+ }))+ .send().await.unwrap();+ assert_eq!(r.status(), 404);+ let v: serde_json::Value = r.json().await.unwrap();+ let m = v["error"]["message"].as_str().unwrap_or("");+ assert!(m.contains("/v1/models"), "Fehlertext hilft nicht weiter: {}", m);+ assert_eq!(v["error"]["code"], "model_not_found");+ h.abort();+ }++ #[tokio::test]+ async fn die_auskunft_sagt_wie_weit_sie_reicht() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let v: serde_json::Value = reqwest::Client::new()+ .get(format!("{}/lu/v1/health", base))+ .bearer_auth(TOKEN)+ .send().await.unwrap().json().await.unwrap();+ assert_eq!(v["reach"], "localhost");+ assert!(v["lanes"]["ollama"]["models"].as_u64().unwrap_or(0) > 0);+ h.abort();+ }++ /// Haelt den ECHTEN Server auf einem festen Port offen, damit ihn jemand+ /// benutzen kann, der nichts von diesem Code weiss.+ ///+ /// Das ist kein Test im ueblichen Sinn — er prueft nichts. Er ist das+ /// Labor fuer den Persona-Durchlauf: derselbe Router, dieselbe+ /// Token-Schranke, dieselbe Weiterleitung wie im Betrieb, nur ohne das+ /// App-Fenster, das die Einstellungen sonst bedient.+ ///+ /// LIVE_LOCAL_API_HOLD=1 LU_API_PORT=8129 LU_API_TOKEN=... \+ /// cargo test halte_die_api_offen -- --nocapture --test-threads=1+ #[tokio::test]+ async fn halte_die_api_offen() {+ if std::env::var("LIVE_LOCAL_API_HOLD").ok().as_deref() != Some("1") { return }+ let port: u16 = std::env::var("LU_API_PORT").ok().and_then(|s| s.parse().ok())+ .unwrap_or(DEFAULT_LOCAL_API_PORT);+ let token = std::env::var("LU_API_TOKEN").unwrap_or_else(|_| generate_token());+ let minuten: u64 = std::env::var("LU_API_MINUTES").ok().and_then(|s| s.parse().ok()).unwrap_or(20);++ let state = LocalApiState {+ cfg: Arc::new(RwLock::new(LocalApiConfig {+ port, lan: false, token: token.clone(), upstreams: default_upstreams(),+ // Damit auch eine Weboberflaeche gegen diesen Halter geprueft+ // werden kann: LU_API_CORS="http://localhost:3000".+ cors_origins: std::env::var("LU_API_CORS")+ .unwrap_or_default()+ .split(',')+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ .collect(),+ })),+ http: reqwest::Client::builder()+ .connect_timeout(std::time::Duration::from_secs(5)).build().unwrap(),+ };+ let l = tokio::net::TcpListener::bind(bind_addr(false, port)).await+ .unwrap_or_else(|e| panic!("Port {} nicht frei: {}", port, e));+ eprintln!("[halte_die_api_offen] http://127.0.0.1:{}/v1 · Token {}", port, token);+ eprintln!("[halte_die_api_offen] {} Minuten offen", minuten);+ let _ = tokio::time::timeout(+ std::time::Duration::from_secs(minuten * 60),+ axum::serve(l, build_local_api_router(state)).into_future(),+ ).await;+ }++ #[tokio::test]+ async fn die_werkzeugliste_kommt_durch_und_nur_mit_token() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();++ // Auch die Werkzeugliste ist keine oeffentliche Auskunft: sie sagt,+ // was auf DIESEM Rechner moeglich ist.+ assert_eq!(c.get(format!("{}/lu/v1/tools", base)).send().await.unwrap().status(), 401);++ let v: serde_json::Value = c.get(format!("{}/lu/v1/tools", base))+ .bearer_auth(TOKEN).send().await.unwrap().json().await.unwrap();+ let namen: Vec<&str> = v["data"].as_array().unwrap().iter()+ .map(|e| e["name"].as_str().unwrap()).collect();+ assert!(namen.contains(&"file_read"));+ assert!(namen.contains(&"shell_execute"));+ // Und der ehrliche Zusatz: die Liste ist der Katalog, nicht die+ // aktuelle Freigabe.+ assert!(v["note"].as_str().unwrap().contains("permissions"));+ h.abort();+ }++ /// Sucht das kleinste laufbereite Ollama-Modell. Klein, weil der Test+ /// schnell sein soll — nicht, weil die Groesse etwas beweist.+ async fn kleinstes_ollama_modell(c: &reqwest::Client, base: &str) -> Option<String> {+ let v: serde_json::Value = c.get(format!("{}/v1/models", base))+ .bearer_auth(TOKEN).send().await.ok()?.json().await.ok()?;+ let ids: Vec<String> = v["data"].as_array()?.iter()+ .filter_map(|m| m["id"].as_str())+ .filter(|i| i.starts_with("ollama/"))+ // Embedder koennen nicht chatten.+ .filter(|i| !i.contains("embed"))+ .map(str::to_string).collect();+ for bevorzugt in ["smollm2:135m", "smollm2:360m", "qwen2.5:0.5b"] {+ if let Some(i) = ids.iter().find(|i| i.ends_with(bevorzugt)) { return Some(i.clone()) }+ }+ ids.into_iter().next()+ }++ // ── Der Kundenbericht vom 02.09.2026, gegen den echten Server ────────+ //+ // Diese neun Tests sind die Gegenprobe zu einem Bericht, den ein Agent+ // ohne jede Kenntnis des Codes geschrieben hat. Sie pruefen NICHT, was der+ // Code tut, sondern was der Kunde vermisst hat.++ #[tokio::test]+ async fn was_zurueckkommt_steht_auch_in_der_liste() {+ // Fund 2, der haerteste: `ollama/llama3.2:3b` rein, `llama3.2:3b` raus.+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();++ let liste: serde_json::Value = c.get(format!("{}/v1/models", base)).bearer_auth(TOKEN)+ .send().await.unwrap().json().await.unwrap();+ let ids: Vec<String> = liste["data"].as_array().unwrap().iter()+ .map(|m| m["id"].as_str().unwrap().to_string()).collect();+ let Some(erstes) = ids.first().cloned() else {+ eprintln!("[local_api_echt] keine Modelle geladen — uebersprungen");+ h.abort();+ return;+ };++ let r: serde_json::Value = c.post(format!("{}/v1/chat/completions", base)).bearer_auth(TOKEN)+ .json(&serde_json::json!({+ "model": erstes, "max_tokens": 1,+ "messages": [{"role": "user", "content": "hi"}],+ }))+ .send().await.unwrap().json().await.unwrap();+ let zurueck = r["model"].as_str().unwrap_or("");+ assert_eq!(zurueck, erstes, "Round-Trip gebrochen: rein {}, raus {}", erstes, zurueck);+ assert!(ids.contains(&zurueck.to_string()), "{} steht nicht in /v1/models", zurueck);+ h.abort();+ }++ #[tokio::test]+ async fn auch_jeder_streaming_chunk_traegt_ihn() {+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();+ let liste: serde_json::Value = c.get(format!("{}/v1/models", base)).bearer_auth(TOKEN)+ .send().await.unwrap().json().await.unwrap();+ let Some(erstes) = liste["data"].as_array().unwrap().first()+ .map(|m| m["id"].as_str().unwrap().to_string()) else { h.abort(); return };++ let text = c.post(format!("{}/v1/chat/completions", base)).bearer_auth(TOKEN)+ .json(&serde_json::json!({+ "model": erstes, "stream": true, "max_tokens": 3,+ "messages": [{"role": "user", "content": "zaehl bis drei"}],+ }))+ .send().await.unwrap().text().await.unwrap();++ let mut gesehen = 0usize;+ for zeile in text.lines().filter(|l| l.starts_with("data: ") && !l.contains("[DONE]")) {+ let v: serde_json::Value = match serde_json::from_str(&zeile[6..]) { Ok(v) => v, Err(_) => continue };+ if let Some(m) = v["model"].as_str() {+ assert_eq!(m, erstes, "Chunk traegt {} statt {}", m, erstes);+ gesehen += 1;+ }+ }+ assert!(gesehen > 0, "kein einziger Chunk mit model-Feld:\n{}", text);+ // Und das Protokoll ist heil geblieben.+ assert!(text.contains("data: [DONE]"), "kein [DONE]:\n{}", text);+ h.abort();+ }++ #[tokio::test]+ async fn eine_stille_lane_wird_als_solche_gemeldet() {+ // Fund 1. LM Studio laeuft auf dieser Maschine nicht — genau der Fall.+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();+ let r = c.post(format!("{}/v1/chat/completions", base)).bearer_auth(TOKEN)+ .json(&serde_json::json!({+ "model": "lmstudio/gibt-es-hier-nicht",+ "messages": [{"role": "user", "content": "hi"}],+ }))+ .send().await.unwrap();+ assert_eq!(r.status(), 404);+ let v: serde_json::Value = r.json().await.unwrap();+ let code = v["error"]["code"].as_str().unwrap_or("");+ let msg = v["error"]["message"].as_str().unwrap_or("");+ // Laeuft LM Studio doch, ist „unbekannt" die richtige Antwort — dann+ // prueft dieser Test die andere Haelfte derselben Regel.+ assert!(+ code == "lane_unavailable" || code == "model_not_found",+ "unerwarteter code {}: {}", code, msg+ );+ if code == "lane_unavailable" {+ assert!(msg.contains("LM Studio") && msg.contains("not running"), "{}", msg);+ }+ assert_eq!(v["error"]["param"], "model");+ h.abort();+ }++ #[tokio::test]+ async fn fehlende_pflichtfelder_heissen_beim_namen() {+ // Fund 4: „[] is too short - 'messages'" kam vom Upstream durch.+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();++ let r = c.post(format!("{}/v1/chat/completions", base)).bearer_auth(TOKEN)+ .json(&serde_json::json!({ "model": "ollama/irgendwas" }))+ .send().await.unwrap();+ assert_eq!(r.status(), 400);+ let v: serde_json::Value = r.json().await.unwrap();+ assert_eq!(v["error"]["param"], "messages");+ assert_eq!(v["error"]["code"], "missing_required_parameter");+ assert!(!v["error"]["message"].as_str().unwrap().contains("too short"),+ "Upstream-Meldung durchgereicht: {}", v["error"]["message"]);++ let r = c.post(format!("{}/v1/chat/completions", base)).bearer_auth(TOKEN)+ .json(&serde_json::json!({ "messages": [{"role": "user", "content": "hi"}] }))+ .send().await.unwrap();+ let v: serde_json::Value = r.json().await.unwrap();+ assert_eq!(v["error"]["param"], "model");+ h.abort();+ }++ #[tokio::test]+ async fn ohne_freigabe_bleibt_der_browser_draussen_mit_freigabe_nicht() {+ // Fund 3. Beide Haelften, sonst prueft der Test nur eine Meinung.+ if !an() { return }+ let c = reqwest::Client::new();++ // Zu: kein einziger CORS-Kopf, auch nicht fuer eine freundliche Seite.+ let Some((base, h)) = starte().await else { return };+ let r = c.request(reqwest::Method::OPTIONS, format!("{}/v1/chat/completions", base))+ .header("Origin", "http://localhost:3000")+ .header("Access-Control-Request-Method", "POST")+ .send().await.unwrap();+ assert!(r.headers().get("access-control-allow-origin").is_none(),+ "Freigabe ohne Eintrag erteilt");+ h.abort();++ // Offen: der Preflight geht durch, OHNE Token — der Browser sendet nie+ // eines mit, und genau daran scheiterte der Kunde.+ let Some((base, h)) = starte_mit(vec!["http://localhost:3000".into()]).await else { return };+ let r = c.request(reqwest::Method::OPTIONS, format!("{}/v1/chat/completions", base))+ .header("Origin", "http://localhost:3000")+ .header("Access-Control-Request-Method", "POST")+ .send().await.unwrap();+ assert!(r.status().is_success(), "Preflight kam mit {} zurueck", r.status());+ assert_eq!(r.headers()["access-control-allow-origin"], "http://localhost:3000");+ assert!(r.headers()["access-control-allow-headers"].to_str().unwrap().contains("authorization"));++ // Eine andere Herkunft bekommt trotzdem nichts.+ let r = c.request(reqwest::Method::OPTIONS, format!("{}/v1/chat/completions", base))+ .header("Origin", "https://boese.example")+ .header("Access-Control-Request-Method", "POST")+ .send().await.unwrap();+ assert!(r.headers().get("access-control-allow-origin").is_none(), "fremde Herkunft freigegeben");++ // Und die Freigabe ersetzt das Token NICHT.+ let r = c.get(format!("{}/v1/models", base)).header("Origin", "http://localhost:3000")+ .send().await.unwrap();+ assert_eq!(r.status(), 401, "CORS hat die Token-Schranke uebersprungen");+ h.abort();+ }++ #[tokio::test]+ async fn die_selbstauskunft_ist_erreichbar_und_der_404_nennt_sie() {+ // Fund 5: /docs und /openapi.json waren beide 404, und alles musste+ // erraten werden.+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();++ let v: serde_json::Value = c.get(format!("{}/lu/v1/docs", base)).bearer_auth(TOKEN)+ .send().await.unwrap().json().await.unwrap();+ assert!(v["routes"].as_array().unwrap().len() >= 7);+ assert!(v["model_names"]["prefix_optional"].is_string());++ // Der Weg dorthin steht im 404 — so hat der Kunde die Routen gefunden.+ let v: serde_json::Value = c.get(format!("{}/docs", base)).bearer_auth(TOKEN)+ .send().await.unwrap().json().await.unwrap();+ assert!(v["error"]["message"].as_str().unwrap().contains("/lu/v1/docs"),+ "der 404 nennt die Doku nicht: {}", v["error"]["message"]);+ h.abort();+ }++ #[tokio::test]+ async fn jede_antwort_traegt_eine_kennung() {+ // Fund 8: es gab nichts zu korrelieren.+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();++ // Auch auf dem 401 — gerade dort, denn darueber wird berichtet.+ let r = c.get(format!("{}/v1/models", base)).send().await.unwrap();+ assert_eq!(r.status(), 401);+ assert!(r.headers().contains_key("x-request-id"));+ assert!(r.headers().contains_key("www-authenticate"), "401 ohne WWW-Authenticate");++ let a = c.get(format!("{}/v1/models", base)).bearer_auth(TOKEN).send().await.unwrap();+ let b = c.get(format!("{}/v1/models", base)).bearer_auth(TOKEN).send().await.unwrap();+ assert_ne!(a.headers()["x-request-id"], b.headers()["x-request-id"]);++ // Eine mitgebrachte Kennung bleibt erhalten.+ let r = c.get(format!("{}/v1/models", base)).bearer_auth(TOKEN)+ .header("x-request-id", "kunde-4711").send().await.unwrap();+ assert_eq!(r.headers()["x-request-id"], "kunde-4711");+ h.abort();+ }++ #[tokio::test]+ async fn die_werkzeugantwort_nennt_keine_quelldatei() {+ // Fund 6/7.+ if !an() { return }+ let Some((base, h)) = starte().await else { return };+ let c = reqwest::Client::new();+ let t = c.get(format!("{}/lu/v1/tools", base)).bearer_auth(TOKEN)+ .send().await.unwrap().text().await.unwrap();+ assert!(!t.contains("local_api.rs"), "Quelldateiverweis beim Kunden: {}", t);+ assert!(t.contains("\"callable_here\":false"), "sagt nicht, dass hier nichts aufrufbar ist");+ h.abort();+ }++ }++ #[cfg(test)]+ mod tests {+ use super::*;++ fn katalog() -> Vec<(Lane, String)> {+ vec![+ (Lane::Engine, "qwen3-8b".into()),+ (Lane::Ollama, "llama3.2:3b".into()),+ (Lane::Ollama, "huihui_ai/qwen3-abliterated:4b".into()),+ (Lane::Ollama, "qwen3-8b".into()),+ (Lane::LmStudio, "mistral-7b-instruct".into()),+ ]+ }++ // ── Namensaufloesung ──────────────────────────────────────────────────++ #[test]+ fn qualifizierter_name_trifft_genau_eine_lane() {+ let r = resolve_model("ollama/qwen3-8b", &katalog()).unwrap();+ assert_eq!(r.lane, Lane::Ollama);+ assert_eq!(r.upstream_id, "qwen3-8b");++ let r = resolve_model("lu/qwen3-8b", &katalog()).unwrap();+ assert_eq!(r.lane, Lane::Engine);+ }++ #[test]+ fn blosser_name_geht_wenn_er_eindeutig_ist() {+ let r = resolve_model("mistral-7b-instruct", &katalog()).unwrap();+ assert_eq!(r.lane, Lane::LmStudio);+ }++ #[test]+ fn blosser_name_in_zwei_lanes_wird_nicht_geraten() {+ // Der Fall, um den es geht: `qwen3-8b` liegt in der Engine UND in+ // Ollama. Eine stille Wahl waere hier das Schlimmste — der Nutzer+ // bekaeme Antworten von einem Modell, das er nicht gemeint hat, und+ // nichts im Ablauf sagte es ihm.+ let e = resolve_model("qwen3-8b", &katalog()).unwrap_err();+ match &e {+ ResolveError::Ambiguous { candidates, .. } => {+ assert_eq!(candidates, &vec!["lu/qwen3-8b".to_string(), "ollama/qwen3-8b".to_string()]);+ }+ other => panic!("erwartet Ambiguous, war {:?}", other),+ }+ assert!(e.message().contains("lu/qwen3-8b"));+ assert!(e.message().contains("ollama/qwen3-8b"));+ }++ #[test]+ fn eine_ollama_id_mit_schraegstrich_bleibt_lesbar() {+ // `huihui_ai/…` faengt mit einem Segment an, das keine Lane ist — das+ // ist der leichte Teil.+ let r = resolve_model("huihui_ai/qwen3-abliterated:4b", &katalog()).unwrap();+ assert_eq!(r.lane, Lane::Ollama);+ // Und qualifiziert davor gestellt ebenfalls.+ let r = resolve_model("ollama/huihui_ai/qwen3-abliterated:4b", &katalog()).unwrap();+ assert_eq!(r.lane, Lane::Ollama);+ assert_eq!(r.upstream_id, "huihui_ai/qwen3-abliterated:4b");+ }++ #[test]+ fn ein_modellname_der_wie_ein_praefix_beginnt_geht_nicht_verloren() {+ // Der Fall, an dem eine naive Fassung scheitert: jemand zieht bei+ // Ollama ein Modell, dessen Namensraum zufaellig "lu" heisst. Wer nach+ // dem Praefix-Fehlschlag aufgibt, meldet "unbekannt" fuer ein Modell,+ // das direkt vor ihm liegt.+ let k = vec![(Lane::Ollama, "lu/experiment:latest".to_string())];+ let r = resolve_model("lu/experiment:latest", &k).unwrap();+ assert_eq!(r.lane, Lane::Ollama);+ }++ #[test]+ fn unbekannt_nennt_den_weg_nach_draussen() {+ let e = resolve_model("gibtsnicht", &katalog()).unwrap_err();+ assert_eq!(e, ResolveError::Unknown("gibtsnicht".into()));+ assert!(e.message().contains("/v1/models"));+ }++ #[test]+ fn leerer_name_ist_unbekannt_und_stuerzt_nicht_ab() {+ assert!(matches!(resolve_model("", &katalog()), Err(ResolveError::Unknown(_))));+ assert!(matches!(resolve_model(" ", &katalog()), Err(ResolveError::Unknown(_))));+ }++ // ── Bindeadresse ──────────────────────────────────────────────────────++ #[test]+ fn ab_werk_hoert_nur_dieser_rechner_zu() {+ assert_eq!(bind_addr(false, 8129).ip(), IpAddr::V4(Ipv4Addr::LOCALHOST));+ assert_eq!(bind_addr(false, 8129).port(), 8129);+ }++ #[test]+ fn lan_bedeutet_alle_interfaces_und_nur_wenn_gewaehlt() {+ assert_eq!(bind_addr(true, 8129).ip(), IpAddr::V4(Ipv4Addr::UNSPECIFIED));+ }++ // ── Token ─────────────────────────────────────────────────────────────++ #[test]+ fn ein_leeres_token_passt_zu_nichts() {+ // Die wichtigste Zusicherung dieser Datei. Ohne sie heisst "noch nicht+ // eingerichtet" in der Wirkung "offen fuer alle".+ assert!(!token_matches("", ""));+ assert!(!token_matches("", "irgendwas"));+ assert!(!token_matches("geheim", ""));+ }++ #[test]+ fn gleiches_token_passt_ungleiches_nicht() {+ assert!(token_matches("abc123", "abc123"));+ assert!(!token_matches("abc123", "abc124"));+ assert!(!token_matches("abc123", "abc1234"));+ assert!(!token_matches("abc123", "abc12"));+ }++ #[test]+ fn erzeugte_token_sind_lang_und_verschieden() {+ let a = generate_token();+ let b = generate_token();+ assert_eq!(a.len(), 64, "32 Bytes hex");+ assert_ne!(a, b);+ assert!(a.chars().all(|c| c.is_ascii_hexdigit()));+ }++ #[test]+ fn das_token_kommt_aus_beiden_ueblichen_kopfzeilen() {+ let mut h = BTreeMap::new();+ h.insert("authorization".to_string(), "Bearer geheim".to_string());+ assert_eq!(presented_token(&h), "geheim");++ let mut h = BTreeMap::new();+ h.insert("x-api-key".to_string(), "geheim".to_string());+ assert_eq!(presented_token(&h), "geheim");++ assert_eq!(presented_token(&BTreeMap::new()), "");+ }++ #[test]+ fn ein_authorization_ohne_bearer_gilt_nicht_als_token() {+ // `Basic …` ist kein Bearer, und wir wollen keinen Zufallstreffer.+ let mut h = BTreeMap::new();+ h.insert("authorization".to_string(), "Basic YWJjOmRlZg==".to_string());+ assert_eq!(presented_token(&h), "");+ }++ // ── Weiterleitung ─────────────────────────────────────────────────────++ #[test]+ fn das_token_des_aufrufers_geht_nicht_nach_oben() {+ // Regel 3. Ohne sie reichte die lokale API das Token des Clients an+ // llama-server / Ollama / LM Studio durch — an Programme, die es nichts+ // angeht, und in deren Logs es dann steht.+ let mut h = BTreeMap::new();+ h.insert("authorization".to_string(), "Bearer geheim".to_string());+ h.insert("x-api-key".to_string(), "auchgeheim".to_string());+ h.insert("content-type".to_string(), "application/json".to_string());+ let raus = forward_headers(&h);+ assert!(!raus.contains_key("authorization"));+ assert!(!raus.contains_key("x-api-key"));+ assert_eq!(raus.get("content-type").map(String::as_str), Some("application/json"));+ }++ #[test]+ fn hop_by_hop_kopfzeilen_bleiben_hier() {+ let mut h = BTreeMap::new();+ for k in ["host", "content-length", "connection", "transfer-encoding", "te"] {+ h.insert(k.to_string(), "x".to_string());+ }+ h.insert("accept".to_string(), "text/event-stream".to_string());+ let raus = forward_headers(&h);+ assert_eq!(raus.len(), 1, "nur accept bleibt uebrig: {:?}", raus);+ assert!(raus.contains_key("accept"));+ }++ #[test]+ fn grossschreibung_schuetzt_keine_kopfzeile() {+ // HTTP-Kopfzeilen sind ohne Ruecksicht auf Gross- und Kleinschreibung.+ // Ein Filter, der das vergisst, laesst `Authorization` durch und+ // streicht nur `authorization` — und niemand sieht es.+ let mut h = BTreeMap::new();+ h.insert("Authorization".to_string(), "Bearer geheim".to_string());+ h.insert("X-Api-Key".to_string(), "geheim".to_string());+ let raus = forward_headers(&h);+ assert!(raus.is_empty(), "durchgerutscht: {:?}", raus);+ }++ // ── Namen nach aussen ─────────────────────────────────────────────────++ #[test]+ fn jede_lane_hat_ein_eigenes_praefix_und_es_geht_hin_und_zurueck() {+ let mut gesehen = std::collections::HashSet::new();+ for l in Lane::ALL {+ assert!(gesehen.insert(l.prefix()), "Praefix doppelt: {}", l.prefix());+ assert_eq!(Lane::from_prefix(l.prefix()), Some(l));+ }+ assert_eq!(Lane::from_prefix("openai"), None);+ }++ #[test]+ fn qualifizierte_namen_sehen_aus_wie_erwartet() {+ assert_eq!(qualified_id(Lane::Engine, "qwen3-8b"), "lu/qwen3-8b");+ assert_eq!(qualified_id(Lane::Ollama, "llama3.2:3b"), "ollama/llama3.2:3b");+ assert_eq!(qualified_id(Lane::LmStudio, "m"), "lmstudio/m");+ }++ // ── Round-Trip: was rausgeht, muss in /v1/models stehen ───────────────+ //+ // Aus dem Kundenbericht vom 02.09.2026, Fund 2. Diese Tests beschreiben+ // NICHT den Code, sondern was der Kunde erwartet hat und nicht bekam.++ #[test]+ fn die_antwort_nennt_das_modell_so_wie_die_liste_es_fuehrt() {+ let mut v: serde_json::Value =+ serde_json::from_str(r#"{"id":"chatcmpl-1","model":"llama3.2:3b","object":"chat.completion"}"#).unwrap();+ assert!(modell_zurueckschreiben(&mut v, "ollama/llama3.2:3b"));+ assert_eq!(v["model"], "ollama/llama3.2:3b");+ // Der Rest bleibt unangetastet.+ assert_eq!(v["id"], "chatcmpl-1");+ assert_eq!(v["object"], "chat.completion");+ }++ #[test]+ fn ohne_modellfeld_wird_nichts_erfunden() {+ // Fehlerantworten des Upstreams haben kein `model`. Eines einzusetzen+ // hiesse, eine Auskunft zu erfinden, die niemand gegeben hat.+ let mut v: serde_json::Value = serde_json::from_str(r#"{"error":{"message":"nope"}}"#).unwrap();+ assert!(!modell_zurueckschreiben(&mut v, "ollama/llama3.2:3b"));+ assert!(v.get("model").is_none());+ }++ #[test]+ fn jeder_streaming_chunk_traegt_die_qualifizierte_id() {+ let mut u = SseModellUmschreiber::neu("ollama/llama3.2:3b");+ let ein = b"data: {\"model\":\"llama3.2:3b\",\"choices\":[]}\n\ndata: [DONE]\n\n";+ let aus = String::from_utf8(u.schub(ein)).unwrap();+ assert!(aus.contains(r#""model":"ollama/llama3.2:3b""#), "kam an: {}", aus);+ assert!(!aus.contains(r#""model":"llama3.2:3b""#), "nackte ID uebrig: {}", aus);+ // Das Abschlusszeichen des Protokolls bleibt, sonst haengt jeder Client.+ assert!(aus.contains("data: [DONE]"), "kam an: {}", aus);+ assert!(u.schluss().is_empty());+ }++ #[test]+ fn ein_modellname_ueber_der_chunk_grenze_ueberlebt() {+ // Der Fall, an dem jede Fassung scheitert, die im Bytestrom sucht:+ // TCP zerlegt, wo es will, auch mitten im Namen.+ let mut u = SseModellUmschreiber::neu("lu/qwen3-8b");+ let mut aus = u.schub(b"data: {\"model\":\"qwen3");+ aus.extend(u.schub(b"-8b\",\"object\":\"chat.completion.chunk\"}\n"));+ aus.extend(u.schluss());+ let s = String::from_utf8(aus).unwrap();+ assert!(s.contains(r#""model":"lu/qwen3-8b""#), "kam an: {}", s);+ }++ #[test]+ fn unlesbare_zeilen_gehen_unveraendert_durch() {+ // Kommentarzeilen (`: ping`) und alles, was wir nicht als JSON lesen,+ // sind fremdes Protokoll. Durchreichen, nicht raten.+ let mut u = SseModellUmschreiber::neu("ollama/x");+ let aus = String::from_utf8(u.schub(b": ping\ndata: kein-json\n")).unwrap();+ assert_eq!(aus, ": ping\ndata: kein-json\n");+ }++ // ── Was der Kunde gemeldet hat, Punkt fuer Punkt ──────────────────────++ #[test]+ fn eine_stille_lane_sagt_dass_sie_still_ist() {+ // Fund 1: nur Ollama lief. `lu/…` beantwortete das mit „Unknown model",+ // und der Kunde schloss daraus, das Drei-Wege-Versprechen sei unbelegt.+ let nur_ollama = vec![(Lane::Ollama, "llama3.2:3b".to_string())];+ let e = resolve_model("lu/qwen3-8b", &nur_ollama).unwrap_err();+ assert_eq!(e, ResolveError::LaneLeer { lane: Lane::Engine, requested: "lu/qwen3-8b".into() });+ assert_eq!(e.code(), "lane_unavailable");+ let m = e.message();+ assert!(m.contains("LU Engine"), "{}", m);+ assert!(m.contains("not running"), "{}", m);+ assert!(m.contains("/lu/v1/health"), "{}", m);+ }++ #[test]+ fn eine_laufende_lane_sagt_weiter_unbekannt() {+ // Die Gegenprobe, ohne die der Fix nur eine Umbenennung waere: fuehrt+ // die Lane etwas, ist ein Fehlgriff wieder schlicht ein Fehlgriff.+ let e = resolve_model("ollama/gibt-es-nicht", &katalog()).unwrap_err();+ assert_eq!(e.code(), "model_not_found");+ }++ #[test]+ fn pflichtfelder_werden_hier_geprueft_und_nicht_oben() {+ // Fund 4: ohne `messages` kam eine Ollama-Schemameldung beim Kunden an.+ let ohne_messages: serde_json::Value = serde_json::from_str(r#"{"model":"ollama/llama3.2:3b"}"#).unwrap();+ let f = koerper_pruefen(&ohne_messages, "messages").unwrap_err();+ assert_eq!(f.param, "messages");+ assert!(f.nachricht.contains("Missing required parameter"), "{}", f.nachricht);++ let ohne_modell: serde_json::Value = serde_json::from_str(r#"{"messages":[]}"#).unwrap();+ let f = koerper_pruefen(&ohne_modell, "messages").unwrap_err();+ assert_eq!(f.param, "model", "fehlendes model muss model heissen, nicht „Unknown model ''\u{22}");++ // Leere Liste ist kein gueltiges Gespraech.+ let leer: serde_json::Value = serde_json::from_str(r#"{"model":"x","messages":[]}"#).unwrap();+ assert_eq!(koerper_pruefen(&leer, "messages").unwrap_err().param, "messages");++ // Und der Normalfall geht durch — sonst waere die Pruefung eine Mauer.+ let gut: serde_json::Value =+ serde_json::from_str(r#"{"model":"x","messages":[{"role":"user","content":"hi"}]}"#).unwrap();+ assert!(koerper_pruefen(&gut, "messages").is_ok());+ // Jeder Endpunkt hat sein eigenes Pflichtfeld.+ let emb: serde_json::Value = serde_json::from_str(r#"{"model":"x","input":"hi"}"#).unwrap();+ assert!(koerper_pruefen(&emb, "input").is_ok());+ assert_eq!(koerper_pruefen(&emb, "prompt").unwrap_err().param, "prompt");+ }++ #[test]+ fn cors_ist_zu_bis_jemand_eine_herkunft_benennt() {+ // Fund 3, und Regel 1 im Dateikopf gleichzeitig.+ assert!(!cors_erlaubt("http://localhost:3000", &[]));+ assert!(cors_erlaubt("http://localhost:3000", &["http://localhost:3000".into()]));+ // Gross/klein ist bei Hostnamen bedeutungslos.+ assert!(cors_erlaubt("http://LocalHost:3000", &["http://localhost:3000".into()]));+ // Eine andere Herkunft bleibt draussen, auch wenn eine freigegeben ist.+ assert!(!cors_erlaubt("https://boese.example", &["http://localhost:3000".into()]));+ }++ #[test]+ fn der_platzhalter_oeffnet_nichts() {+ // Absicht, nicht Versehen: `*` in der Liste ist wieder „jede Webseite",+ // und damit waere die Liste sinnlos. Sie wirkt sichtbar nicht, statt+ // still alles aufzumachen.+ assert!(!cors_erlaubt("https://irgendwas.example", &["*".into()]));+ assert!(!cors_erlaubt("*", &["*".into()]));+ assert!(!cors_erlaubt("null", &["null".into()]));+ assert!(!cors_erlaubt("", &["".into()]));+ }++ #[test]+ fn jede_antwort_ist_zuordenbar_und_eigene_kennungen_bleiben() {+ // Fund 8. Eine eigene Kennung UEBERNEHMEN ist der ganze Punkt —+ // sonst korreliert man nur mit sich selbst.+ assert_eq!(naechste_request_id(Some("kunde-42")), "kunde-42");+ let a = naechste_request_id(None);+ let b = naechste_request_id(None);+ assert_ne!(a, b, "zwei Anfragen duerfen nicht dieselbe Kennung tragen");+ assert!(a.starts_with("req_"), "{}", a);+ // Muell wird nicht uebernommen: der Wert landet in einem Antwortkopf.+ assert!(naechste_request_id(Some("")).starts_with("req_"));+ assert!(naechste_request_id(Some(&"x".repeat(500))).starts_with("req_"));+ assert!(naechste_request_id(Some("zeile\numbruch")).starts_with("req_"));+ }++ #[test]+ fn die_doku_beschreibt_die_routen_die_es_wirklich_gibt() {+ // Fund 5 — und eine Doku, die von den Routen abweicht, ist schlimmer+ // als keine. Dieser Test faellt, sobald eine Route dazukommt und die+ // Selbstauskunft sie verschweigt.+ let d = lu_doku();+ let beschrieben: Vec<String> = d["routes"]+ .as_array()+ .unwrap()+ .iter()+ .map(|r| r["path"].as_str().unwrap().to_string())+ .collect();+ for pfad in [+ "/v1/models",+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/embeddings",+ "/lu/v1/health",+ "/lu/v1/tools",+ "/lu/v1/docs",+ ] {+ assert!(beschrieben.contains(&pfad.to_string()), "{} fehlt in der Doku", pfad);+ }+ // Alle Fehlercodes, die der Code wirklich sendet, stehen drin.+ let codes = d["errors"]["codes"].to_string();+ for c in ["invalid_api_key", "missing_required_parameter", "model_not_found", "model_ambiguous", "lane_unavailable"] {+ assert!(codes.contains(c), "{} fehlt in der Doku", c);+ }+ // Und jede Lane nennt sich so, wie das Praefix wirklich heisst.+ let lanes = d["model_names"]["lanes"].to_string();+ for l in Lane::ALL {+ assert!(lanes.contains(l.prefix()), "{} fehlt", l.prefix());+ }+ }++ #[test]+ fn die_werkzeugliste_verweist_nicht_auf_den_quelltext() {+ // Fund 6: „see the comment on lu_werkzeuge() in local_api.rs" stand+ // woertlich in einer Kundenantwort. Der Kunde hat kein local_api.rs.+ let w = lu_werkzeuge().to_string();+ assert!(!w.contains(".rs"), "interner Dateiverweis in der Antwort: {}", w);+ assert!(!w.contains("lu_werkzeuge"), "interner Funktionsname in der Antwort");+ // Stattdessen wird gesagt, dass es hier keinen Aufrufweg gibt.+ assert_eq!(lu_werkzeuge()["callable_here"], false);+ }+ }diff --cc src-tauri/src/commands/process.rsindex 4bd8a0e6,869cef69..98b041b4--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@@ -296,62 -305,6 +310,62 @@@ pub fn comfy_env_failure(tail: &[String|| (joined.contains("Traceback (most recent call last)") && joined.contains("site-packages"))}+/// Was die letzte Ausgabe eines Startversuchs bedeutet: darf die Selbstheilung+/// laufen, und welcher Satz gehoert unter die Ausgabe.+pub(crate) struct ComfyCrashVerdict {+ /// Ein Absturz, den ein Neubau des venv beheben kann (GH #98).+ pub env_broken: bool,+ /// Der konkrete Rat aus dem Einordner des Installers, sonst leer.+ pub hint: String,+}++/// Die Einordnung eines Startabsturzes, mit genau dem Einordner, den der+/// Installer schon hat. Kein zweiter Einordner und kein zweiter Hinweistext:+/// `pip_failure_kind` und `pip_failure_hint` wissen seit 2.6.7, was WinError+/// 1114 bedeutet, sie wurden auf diesem Weg nur nie gefragt.+///+/// falcon bob (Ticket 007, 01.09. bis 02.09.): sein torch starb an einem+/// c10.dll im venv, LU nannte das eine kaputte Umgebung und baute das venv+/// automatisch neu. Ein nativer Ladefehler hat seine Ursache AUSSERHALB des+/// venv, in der Visual-C++-Laufzeit oder im Grafiktreiber, also endet der+/// Neubau nach Minuten auf derselben Meldung. Genau diese Schleife hat er+/// berichtet. Alle uebrigen Faelle heilen sich weiter selbst.+pub(crate) fn comfy_crash_verdict(lines: &[String], exited: bool) -> ComfyCrashVerdict {- use crate::commands::install::{pip_failure_hint, pip_failure_kind, PipFailureKind};++ use crate::commands::install::pip::{pip_failure_hint, pip_failure_kind, PipFailureKind};+ let joined = lines.join("\n");+ let kind = pip_failure_kind(&joined);+ // Eine Auswahl ueber den vorhandenen Einordner, kein zweiter Einordner:+ // diese vier Saetze beschreiben die Maschine selbst und stimmen deshalb+ // auch, wenn nicht pip sie gedruckt hat, sondern ComfyUI beim Start. Die+ // uebrigen Saetze reden von pip und vom Paketindex, die hier gar nicht+ // gelaufen sind. Der schlimmste davon ist PipBroken: anglefires fehlendes+ // sqlalchemy wuerde damit ein "Reinstall Python 3.10+ from python.org"+ // bekommen, obwohl sein Python heil ist und die Reparatur der Weg ist.+ let hint = match kind {+ PipFailureKind::MissingRuntimeLibrary+ | PipFailureKind::NativeLoadFailure+ | PipFailureKind::TorchWithoutGpuSupport+ | PipFailureKind::DiskFull => pip_failure_hint(kind, &joined),+ _ => String::new(),+ };+ ComfyCrashVerdict {+ env_broken: exited && comfy_env_failure(lines) && venv_rebuild_can_fix(kind),+ hint,+ }+}++/// Kann ein Neubau des venv dieses Fehlerbild ueberhaupt beheben?+///+/// Nein, sobald das fehlende Stueck ausserhalb des venv liegt: die+/// Visual-C++-Laufzeit und der Grafiktreiber wohnen in Windows, und ein+/// frisches venv laedt dieselben Wheels an dieselbe Stelle. Alles andere+/// bleibt bei Ja, damit die Selbstheilung aus GH #98 nur enger wird und nicht+/// verschwindet.- pub(crate) fn venv_rebuild_can_fix(kind: crate::commands::install::PipFailureKind) -> bool {- use crate::commands::install::PipFailureKind as K;++pub(crate) fn venv_rebuild_can_fix(kind: crate::commands::install::pip::PipFailureKind) -> bool {++ use crate::commands::install::pip::PipFailureKind as K;+ !matches!(kind, K::NativeLoadFailure | K::MissingRuntimeLibrary)+}+/// Pure decision (all probes done by the caller): pass `--cpu` to ComfyUI?////// - `baseline_needs_cpu`: `needs_cpu_fallback()` — false when NVIDIA present or macOS.@@@ -2470,14 -2578,157 +2793,165 @@@ mod utf8_start_waechtermod tests {use super::*;+ /// The Mac never runs ComfyUI, so it must never search the disk for one:+ /// the home walk crosses ~/Desktop and ~/Music and macOS turns the first+ /// touch of each into a permission dialog at launch.+ #[test]+ fn comfyui_disk_search_is_off_on_macos_and_on_elsewhere() {+ assert_eq!(comfyui_disk_search_allowed(), !cfg!(target_os = "macos"));+ }++ // ── OI-1: "your working ComfyUI is a broken torso" ───────────────────+ //+ // The probe answered `false` for every from-source Linux install and for+ // every install on any platform that had been through `repair_comfyui_env`,+ // because (a) it never looked inside ComfyUI's own venv, which is where+ // both of those put torch, and (b) its system-Python branch was dead code:+ // the candidate list held the bare string "python3",+ // `Path::new("python3").parent()` is `Some("")`, and `"".parent()` is+ // `None`, so the Unix arm could not be reached and the Windows arm+ // degenerated to the relative path `Lib/site-packages/torch`.+ //+ // Both prefix layouts are built as fixture directories and the interpreter+ // list is injected, so the Windows layout is checked on Unix and vice+ // versa. What is NOT checked here: that a real ComfyUI with a real torch- // starts — that needs an actual 2 GB install.++ // starts, which needs an actual 2 GB install.++ /// Lay out `<root>/<rel>/torch` as a directory, creating parents.+ fn touch_torch(root: &Path, rel: &str) {+ let dir = root.join(rel).join("torch");+ std::fs::create_dir_all(&dir).unwrap();+ }++ fn comfy_fixture() -> (tempfile::TempDir, PathBuf) {+ let tmp = tempfile::tempdir().unwrap();+ let comfy = tmp.path().join("ComfyUI");+ std::fs::create_dir_all(&comfy).unwrap();+ std::fs::write(comfy.join("main.py"), b"# comfy").unwrap();+ (tmp, comfy)+ }++ #[test]+ fn a_main_py_only_carcass_is_still_incomplete() {+ // P14's guarantee must survive the OI-1 fix: a half-cloned dir with+ // nothing but main.py has no torch anywhere and stays incomplete.+ let (_tmp, comfy) = comfy_fixture();+ assert!(!is_comfyui_install_complete_with(&comfy, &[]));+ }++ #[test]+ fn a_directory_without_main_py_is_not_a_comfyui_at_all() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join("NotComfy");+ // Even with a fully populated venv: no main.py, nothing to start.+ touch_torch(&dir, "venv/lib/python3.12/site-packages");+ assert!(!is_comfyui_install_complete_with(&dir, &[]));+ }++ #[test]+ fn torch_in_comfyuis_own_venv_unix_layout_is_complete() {+ // The Linux from-source install and EVERY repaired install. This is+ // the case that reported "broken torso" to every affected user.+ let (_tmp, comfy) = comfy_fixture();+ touch_torch(&comfy, "venv/lib/python3.12/site-packages");+ assert!(is_comfyui_install_complete_with(&comfy, &[]));+ }++ #[test]+ fn torch_in_comfyuis_own_venv_windows_layout_is_complete() {+ let (_tmp, comfy) = comfy_fixture();+ touch_torch(&comfy, "venv/Lib/site-packages");+ assert!(is_comfyui_install_complete_with(&comfy, &[]));+ }++ #[test]+ fn a_dot_venv_counts_like_a_venv() {- // `uv` and a modern `python -m venv .venv` — same install, other name++ // `uv` and a modern `python -m venv .venv`: same install, other name+ // (issue #51, adhney; `resolve_comfyui_venv_python` already knows it).+ let (_tmp, comfy) = comfy_fixture();+ touch_torch(&comfy, ".venv/lib/python3.11/site-packages");+ assert!(is_comfyui_install_complete_with(&comfy, &[]));+ }++ #[test]+ fn a_venv_without_torch_is_not_complete() {+ // Negative control: the venv exists (a repair that died during the+ // PyTorch download) but holds no torch, so it cannot start.+ let (_tmp, comfy) = comfy_fixture();+ std::fs::create_dir_all(comfy.join("venv").join("lib").join("python3.12").join("site-packages")).unwrap();+ assert!(!is_comfyui_install_complete_with(&comfy, &[]));+ }++ #[test]+ fn a_portable_python_embeded_still_counts_inside_or_beside() {+ let (_tmp, comfy) = comfy_fixture();+ touch_torch(&comfy, "python_embeded/Lib/site-packages");+ assert!(is_comfyui_install_complete_with(&comfy, &[]));++ // The other portable shape: python_embeded is a SIBLING of ComfyUI.+ let (_tmp2, comfy2) = comfy_fixture();+ let beside = comfy2.parent().unwrap().to_path_buf();+ touch_torch(&beside, "python_embeded/Lib/site-packages");+ assert!(is_comfyui_install_complete_with(&comfy2, &[]));+ }++ #[test]+ fn a_unix_system_python_prefix_is_read_through_bin() {+ // /usr/bin/python3 → prefix /usr → /usr/lib/python3.12/site-packages.+ // The interpreter is one level BELOW its prefix on Unix, which is why+ // the probe has to try the parent too.+ let (_tmp, comfy) = comfy_fixture();+ let root = comfy.parent().unwrap().join("usr");+ std::fs::create_dir_all(root.join("bin")).unwrap();+ let py = root.join("bin").join("python3");+ std::fs::write(&py, b"stub").unwrap();+ touch_torch(&root, "lib/python3.12/site-packages");+ assert!(is_comfyui_install_complete_with(+ &comfy,+ &[py.to_string_lossy().to_string()]+ ));+ }++ #[test]+ fn a_windows_system_python_prefix_is_read_next_to_the_exe() {+ // C:\Python312\python.exe → C:\Python312\Lib\site-packages. Here the+ // interpreter sits IN its prefix, not one below it.+ let (_tmp, comfy) = comfy_fixture();+ let root = comfy.parent().unwrap().join("Python312");+ std::fs::create_dir_all(&root).unwrap();+ let py = root.join("python.exe");+ std::fs::write(&py, b"stub").unwrap();+ touch_torch(&root, "Lib/site-packages");+ assert!(is_comfyui_install_complete_with(+ &comfy,+ &[py.to_string_lossy().to_string()]+ ));+ }++ #[test]+ fn a_bare_interpreter_name_can_never_answer_yes() {+ // The mechanism of the bug, pinned. `Path::new("python3").parent()`+ // is `Some("")`; joining onto it makes a RELATIVE path that resolves+ // against LU's working directory, and `"".parent()` is `None`, which+ // is what made the Unix arm unreachable.+ assert_eq!(Path::new("python3").parent(), Some(Path::new("")));+ assert_eq!(Path::new("").parent(), None);+ assert!(!python_prefix_has_torch(Path::new("python3")));+ assert!(!python_prefix_has_torch(Path::new("python")));+ assert!(!prefix_has_torch(Path::new("")));+ }++ #[test]+ fn every_candidate_python_is_an_absolute_path() {+ // The callers derive a prefix from these strings, so a bare name is+ // not a weaker answer, it is a wrong one.+ for p in collect_candidate_pythons() {+ assert!(+ Path::new(&p).is_absolute(),+ "candidate python is not absolute: {p}"+ );+ }+ }// ── E16: a start that fails has to say so ────────────────────────────//diff --cc src-tauri/src/commands/proxy.rsindex 33ed5fb6,731f8dee..cfeff5ec--- a/src-tauri/src/commands/proxy.rs+++ b/src-tauri/src/commands/proxy.rs@@@ -41,73 -83,14 +83,45 @@@ fn validate_external_url(raw: &str) ->Ok(())}+/// A URL fit to appear in an error message or a log line.+///+/// The query string is dropped, and so is any userinfo. A secret in a URL is a+/// secret in every log that ever quotes the URL, and the log scrubber cannot+/// see a token that is just another substring of a URL. The CivitAI search used+/// to put the user's API key there, and this function is the second half of+/// closing that: the first half is not putting it there at all.+pub(crate) fn redact_url(raw: &str) -> String {+ match url::Url::parse(raw) {+ Ok(mut u) => {+ u.set_query(None);+ u.set_fragment(None);+ let _ = u.set_username("");+ let _ = u.set_password(None);+ u.to_string()+ }+ // Unparseable: say nothing rather than echo whatever it was.+ Err(_) => "the requested URL".to_string(),+ }+}+/// Generic HTTP proxy — fetch any external URL and return body as string./// Used for CivitAI API calls, workflow JSON downloads, etc.+///+/// `authToken` is the user's CivitAI API key and is sent as a Bearer header,+/// ONLY to a CivitAI host, exactly like the download path. It is not a generic+/// "send this to whatever host" parameter: a bearer that follows any URL a+/// catalogue hands us is a credential leak waiting for a redirect.+#[allow(non_snake_case)]#[tauri::command]-pub async fn fetch_external(url: String) -> Result<String, String> {- let resp = ssrf_safe_fetch(&url, "fetch_external", Duration::from_secs(60), 10).await?;+pub async fn fetch_external(url: String, authToken: Option<String>) -> Result<String, String> {- validate_public_url(&url)?;-- let client = reqwest::Client::builder()- .user_agent("LocallyUncensored/2.0")- .timeout(std::time::Duration::from_secs(60))- .redirect(ssrf_safe_redirect_policy(10))- .build()- .map_err(|e| os_error::english(&e))?;-- let mut request = client.get(&url);- if let Some(t) = authToken++ let bearer = authToken+ .as_deref()+ .map(str::trim)- .filter(|t| !t.is_empty() && crate::commands::download::is_civitai_host(&url))- {- request = request.bearer_auth(t);- }-- let resp = request- .send()- .await- .map_err(|e| format!("fetch_external: {}", os_error::english(&e)))?;++ .filter(|t| !t.is_empty());++ let resp = ssrf_safe_fetch(&url, "fetch_external", Duration::from_secs(60), 10, bearer).await?;if !resp.status().is_success() {- return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));+ return Err(format!("HTTP {}: {}", resp.status().as_u16(), redact_url(&url)));}resp.text().await.map_err(|e| os_error::english(&e))@@@ -117,22 -100,10 +131,10 @@@/// Used for downloading ZIP files, images, model files.#[tauri::command]pub async fn fetch_external_bytes(url: String) -> Result<Vec<u8>, String> {- validate_public_url(&url)?;-- let client = reqwest::Client::builder()- .user_agent("LocallyUncensored/2.0")- .timeout(std::time::Duration::from_secs(300))- .redirect(ssrf_safe_redirect_policy(10))- .build()- .map_err(|e| os_error::english(&e))?;-- let resp = client.get(&url)- .send()- .await- .map_err(|e| format!("fetch_external_bytes: {}", os_error::english(&e)))?;- let resp = ssrf_safe_fetch(&url, "fetch_external_bytes", Duration::from_secs(300), 10).await?;++ let resp = ssrf_safe_fetch(&url, "fetch_external_bytes", Duration::from_secs(300), 10, None).await?;if !resp.status().is_success() {- return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));+ return Err(format!("HTTP {}: {}", resp.status().as_u16(), redact_url(&url)));}resp.bytes().await.map(|b| b.to_vec()).map_err(|e| os_error::english(&e))@@@ -236,6 -286,70 +317,82 @@@ pub(crate) fn ssrf_safe_redirect_policy})}+ /// A client pinned to the addresses the gate just approved. Without the pin the+ /// name is resolved a SECOND time when the socket is opened, and a resolver that+ /// answers a public IP to the check and 127.0.0.1 to the connect (DNS rebinding)+ /// walks through untouched. `resolve_to_addrs` overrides only the address — the+ /// port always comes from the URL.+ fn pinned_client(host: &str, addrs: &[SocketAddr], timeout: Duration) -> Result<reqwest::Client, String> {+ let mut builder = reqwest::Client::builder()+ .user_agent("LocallyUncensored/2.0")+ .timeout(timeout)+ // Redirects are followed by hand in `ssrf_safe_fetch` so every hop gets+ // its own check AND its own pin; letting reqwest follow them would+ // re-resolve the next host behind our back.+ .redirect(reqwest::redirect::Policy::none());+ if parse_ip_host(host).is_none() {+ builder = builder.resolve_to_addrs(host, addrs);+ }+ builder.build().map_err(|e| os_error::english(&e))+ }++ /// GET a renderer-supplied URL with the SSRF gate applied to EVERY hop, each one+ /// connected to the address that hop was checked against.+ ///+ /// reqwest's default policy follows up to 10 redirects and checks nothing on the+ /// way, so a public URL answering `302 Location: http://169.254.169.254/…` (or+ /// `http://127.0.0.1:11434/…`) reached the blocked host through the front door.++///++/// `bearer` is the user's CivitAI API key. It is attached per hop and ONLY while++/// that hop is a CivitAI host, so a redirect off CivitAI drops the credential++/// instead of handing it to whoever the catalogue pointed at.+ async fn ssrf_safe_fetch(+ url: &str,+ label: &str,+ timeout: Duration,+ max_hops: usize,++ bearer: Option<&str>,+ ) -> Result<reqwest::Response, String> {+ let mut current = url.to_string();+ for _ in 0..=max_hops {+ let target = current.clone();+ // The resolver blocks; keep it off the reactor.+ let addrs = tokio::task::spawn_blocking(move || validate_public_url_addrs(&target))+ .await+ .map_err(|e| format!("{}: resolver task failed: {}", label, e))??;+ let parsed = url::Url::parse(¤t).map_err(|e| format!("Invalid URL: {}", e))?;+ let host = parsed.host_str().unwrap_or("").to_string();+ let client = pinned_client(&host, &addrs, timeout)?;- let resp = client- .get(current.clone())++ let mut request = client.get(current.clone());++ // Jeder Sprung wird neu geprueft, der Bearer folgt nie einer Umleitung++ // von CivitAI weg.++ if let Some(token) =++ bearer.filter(|_| crate::commands::download::is_civitai_host(¤t))++ {++ request = request.bearer_auth(token);++ }++ let resp = request+ .send()+ .await+ .map_err(|e| format!("{}: {}", label, os_error::english(&e)))?;+ // Only the statuses reqwest itself would have followed. 300 and 304 are+ // redirection-class but carry no target, and handing those back to the+ // caller is what happened before.+ if !matches!(resp.status().as_u16(), 301 | 302 | 303 | 307 | 308) {+ return Ok(resp);+ }+ let location = match resp.headers().get(reqwest::header::LOCATION).and_then(|v| v.to_str().ok()) {+ Some(l) => l.to_string(),+ None => return Ok(resp),+ };+ current = parsed+ .join(&location)+ .map_err(|e| format!("Invalid redirect target: {}", e))?+ .to_string();+ }+ Err(format!("{}: too many redirects", label))+ }+/// True only for private/LAN hosts a user could legitimately point a local/// backend at. `register_openai_host` requires this so the RUST boundary — not/// the JS caller — enforces the LAN-only intent and can't be tricked intodiff --cc src-tauri/src/commands/repo_map.rsindex c3c5a9f1,95fb79c2..072ac47d--- a/src-tauri/src/commands/repo_map.rs+++ b/src-tauri/src/commands/repo_map.rs@@@ -94,7 -94,7 +94,7 @@@ const MAX_PARSE_BYTES: u64 = 512 * 1024/// instead of a repo is an easy mistake, and without a bound the walk/// enumerated the whole tree and then read and parsed every source file in it,/// for a map that returns at most 200 entries. Same lock-up class the ComfyUI--/// detection had to bound (install.rs, 200k-file home dir).++/// detection had to bound (the ComfyUI installer, 200k-file home dir).const MAX_WALK_FILES: usize = 20_000;// ── Import-parsing regexes ─────────────────────────────────────────diff --cc src-tauri/src/commands/secret.rsindex 4593a0e5,49446a40..42689296--- a/src-tauri/src/commands/secret.rs+++ b/src-tauri/src/commands/secret.rs@@@ -105,12 -183,8 +183,10 @@@ mod chunked}pub fn set(account: &str, value: &str) -> Result<(), String> {- // MAX_UNITS is usize::MAX off Windows, so clippy calls this comparison- // absurd there. It is the honest shape: only Windows chunks, and the- // bound belongs next to the platform that needs it.- #[allow(clippy::absurd_extreme_comparisons)]- let fits_in_head = value.encode_utf16().count() <= MAX_UNITS;- if fits_in_head {- // No budget (macOS) means it always fits; with a budget, measure.++ // Only Windows carries a budget, and the bound sits next to the++ // platform that needs it. No budget means the value always fits in the++ // head; with a budget, measure before deciding to chunk.+ let Some(max_units) = MAX_UNITS.filter(|max| value.encode_utf16().count() > *max) else {entry(account)?.set_password(value).map_err(|e| e.to_string())?;// Drop every chunk: this value lives in the head alone now.let _ = sweep_chunks_from(account, 0);diff --cc src-tauri/src/commands/torch_wheels.rsindex 88fef746,f3835584..5774c503--- a/src-tauri/src/commands/torch_wheels.rs+++ b/src-tauri/src/commands/torch_wheels.rs@@@ -1,7 -1,7 +1,7 @@@//! Which PyTorch wheels belong on THIS machine.//!//! Two environments in the app build a Python venv and put torch in it: the--//! ComfyUI environment (`install.rs`) and the character trainer (`trainer.rs`).++//! ComfyUI environment (`install/`) and the character trainer (`trainer.rs`).//! Both used to ask `nvidia-smi` and nothing else, so an AMD card was//! indistinguishable from a machine with no card at all and got the wheels a//! card-less box gets. On the ComfyUI side that is exactly what numbrain,@@@ -421,7 -399,7 +421,7 @@@ fn nvidia_plan(cap: Option<(u32, u32)>/// starts from.////// It lives here alone because two environments have to say it, and a fact that--/// is written twice is a fact that gets updated once. `install.rs` puts the++/// is written twice is a fact that gets updated once. `install/torch.rs` puts the/// ComfyUI consequence behind it, `trainer.rs` puts the trainer's behind it,/// and neither restates the measurement.///diff --cc src-tauri/src/commands/trainer.rsindex b876d05e,e99b294e..4247598b--- a/src-tauri/src/commands/trainer.rs+++ b/src-tauri/src/commands/trainer.rs@@@ -509,55 -509,6 +509,55 @@@ pub(crate) fn useful_tail(text: &str) -lines[lines.len().saturating_sub(3)..].join(" | ")}+/// The dead ends that are neither the network nor the disk, and that the one+/// generic step sent people to look in the wrong place for. A2 stage one+/// (aikabatzu, aldrich_ironhart, Z0mbieK, Discord and GH #121, 2026-08-27 and+/// 2026-08-29): "Setting up the trainer environment failed. Check that you are+/// online" while online, with the firewall off, confirmed by a second user.+///+/// Windows and the rest get different sentences, because the Visual C+++/// Redistributable does not exist off Windows and sending a Linux user to+/// microsoft.com is the same class of mistake as sending an online user to+/// their router. Both texts compile everywhere and the OS is a parameter, the+/// way `torch_wheels` does it, so a Mac can test the Windows wording.+const WINDOWS_REDIST_NEXT_STEP: &str = "A Microsoft Visual C++ runtime library is missing, and PyTorch cannot load without it. Install the current Visual C++ Redistributable for x64 from https://learn.microsoft.com/cpp/windows/latest-supported-vc-redist, restart Windows, then press Set up trainer in Character Studio.";+const UNIX_LIBRARY_NEXT_STEP: &str = "A system library PyTorch loads is missing on this machine; the log line above names the file. Install it with your package manager, then press Set up trainer in Character Studio.";+const WINDOWS_NATIVE_NEXT_STEP: &str = "PyTorch is on disk but its native libraries will not load. Install the current Visual C++ Redistributable for x64 from https://learn.microsoft.com/cpp/windows/latest-supported-vc-redist, update the graphics driver, restart Windows, then press Set up trainer in Character Studio.";+const UNIX_NATIVE_NEXT_STEP: &str = "PyTorch is on disk but its native libraries will not load. Update the graphics driver and the system libraries, restart the machine, then press Set up trainer in Character Studio.";+/// A wrong wheel, not a broken machine. The setup probes the card again, so it+/// is the same button and a completely different reason.+const WHEEL_NEXT_STEP: &str = "The PyTorch that was installed carries no support for the card in this machine, so it can only run on the processor. Press Set up trainer in Character Studio: the setup probes the card again and picks the matching wheel.";+const PYTHON_VERSION_NEXT_STEP: &str = "No wheel exists for the Python version LU is using here. Install Python 3.10, 3.11 or 3.12 from python.org with 'Add to PATH' checked, then press Set up trainer in Character Studio.";+const PERMISSION_NEXT_STEP: &str = "The installer was not allowed to write into the Python folder. Close every open Python, Jupyter or IDE debugger, and if that changes nothing, install Python for your own user instead of for all users, then press Set up trainer in Character Studio.";+const PEP668_NEXT_STEP: &str = "This Python refuses installs outside a virtual environment and the venv module is missing. Install it from your package manager (python3-venv on Debian and Ubuntu, python-virtualenv on Arch, python3-virtualenv on Fedora), then press Set up trainer in Character Studio.";++/// The way out that fits what actually failed, on the platform it failed on.+/// The old code offered exactly one, "check that you are online and that the+/// drive has room", for every failure class there is.+pub(crate) fn next_step_for_log(log: &str, fallback: &'static str, os: &str) -> &'static str {- use crate::commands::install::PipFailureKind as K;++ use crate::commands::install::pip::PipFailureKind as K;+ let windows = os == "windows";+ if out_of_disk(log) {+ return DISK_NEXT_STEP;+ }- match crate::commands::install::pip_failure_kind(log) {++ match crate::commands::install::pip::pip_failure_kind(log) {+ K::MissingRuntimeLibrary => {+ if windows { WINDOWS_REDIST_NEXT_STEP } else { UNIX_LIBRARY_NEXT_STEP }+ }+ K::NativeLoadFailure => {+ if windows { WINDOWS_NATIVE_NEXT_STEP } else { UNIX_NATIVE_NEXT_STEP }+ }+ K::TorchWithoutGpuSupport => WHEEL_NEXT_STEP,+ K::NoMatchingWheel => PYTHON_VERSION_NEXT_STEP,+ K::Permission => PERMISSION_NEXT_STEP,+ K::ExternallyManaged => PEP668_NEXT_STEP,+ K::DiskFull => DISK_NEXT_STEP,+ // Network failures and everything we cannot name keep the old text.+ // Naming the network for a failure that is not one is the whole bug.+ _ => fallback,+ }+}+/// One shape for every dead end in the trainer environment: what is wrong, what/// to press, and a short tail that says why. In that order, because the user/// reads the first sentence and the last one.diff --cc src-tauri/src/main.rsindex e396258f,97860ddd..48f04b25--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@@ -69,8 -123,27 +123,27 @@@ fn file_log_writer() -> Option<(tracing/// because most desktop users just want a readable terminal.////// `RUST_LOG` is honored as the filter — common values are `info`,- /// `locally_uncensored=debug`, or a per-module spec.- fn init_tracing() {-/// `lu_experiment=debug` (der Crate-Name, siehe Cargo.toml), or a per-module spec.++/// `locally_uncensored=debug` (the crate name, see Cargo.toml), or a per-module spec.+ ///+ /// Audit finding #01: until now this was the stdout layer and nothing else,+ /// and a shipped desktop app has no stdout. On Windows the release binary is+ /// built with `windows_subsystem = "windows"`; on macOS it is launched from+ /// Finder; the DevTools console only opens under `debug_assertions`. Every+ /// line the app produced went nowhere, so a crash on a user's machine left no+ /// artefact at all and any bug that did not reproduce locally was unreachable.+ /// A rolling file layer is added ALONGSIDE the console layer — the terminal+ /// output a developer runs `cargo tauri dev` for is unchanged, there is simply+ /// now also a file to ask a user for.+ ///+ /// The file layer is always the plain text formatter, even under+ /// `LU_LOG_FORMAT=json`: that switch exists for someone piping stdout into a+ /// log processor, whereas the file's reader is a human reading a support+ /// attachment. ANSI is off for the same reason — escape codes in a file the+ /// user opens in Notepad are noise.+ ///+ /// Returns the writer's `WorkerGuard`, which the caller MUST keep alive.+ #[must_use = "the WorkerGuard must outlive the app or the log file stays empty"]+ fn init_tracing() -> Option<tracing_appender::non_blocking::WorkerGuard> {use tracing_subscriber::{fmt, prelude::*, EnvFilter};// `try_init` instead of `init` so we never panic if something else// (a test harness, a re-import) already set the global subscriber.@@@ -268,9 -365,12 +365,13 @@@ fn main()commands::download::download_progress,commands::download::pause_download,commands::download::cancel_download,+ commands::download::clear_download_entry,+ commands::download::check_download_space,+ commands::download::find_orphan_downloads,+ commands::download::delete_orphan_download,commands::download::resume_download,commands::download::detect_model_path,+ commands::download::lmstudio_model_dir,commands::download::check_model_sizes,commands::download::delete_comfy_model,// Built-in inference engine (bundled llama-server, P1)@@@ -379,41 -491,35 +494,43 @@@let _ = window.set_shadow(false);}- // ─── Bug D (surfingbird1010): force-show fallback ───- // The window starts hidden (visible:false in tauri.conf.json) and is- // normally revealed by the frontend's invoke('show_window') once React- // mounts (App.tsx). If the WebView never loads, or a render/hydration- // throw happens before that effect runs (corrupt persisted state,- // GPU/WebView2 fault), the window would stay hidden forever and the app- // looks like it "runs with no window". Reveal it unconditionally after a- // timeout so the user always gets a window. The frontend's earlier- // show_window is idempotent, so a healthy launch sees no double-show /- // flicker. 10 s is comfortably longer than a normal cold React mount- // (~1-2 s) yet short enough not to feel broken on a slow i7/8 GB box.- {- let handle = app.handle().clone();- std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_secs(10));- if let Some(window) = handle.get_webview_window("main") {- // Treat "unknown" as hidden → show (a redundant show on an- // already-visible window is a harmless no-op).- if !window.is_visible().unwrap_or(false) {- println!("[Window] Force-show fallback fired (frontend never called show_window)");- let _ = window.show();- let _ = window.set_focus();- }- }- });+ // ─── Erststart: Onboarding im eigenen Fenster ───+ // Decided HERE, before any window is visible, from the marker file+ // (and the store backup, for installs older than the marker). With+ // the onboarding pending, a small centred window carries the wizard+ // and the main window stays hidden until the marker is written —+ // see onboarding_window.rs for the whole hand-over. A failure to+ // build that window fails setup: a hidden main window plus no+ // onboarding window would be an app without a window.+ if onboarding_window::decide_first_window() == onboarding_window::FirstWindow::Onboarding {+ onboarding_window::open(app.handle())?;}+ // ─── Bug D (surfingbird1010): force-show fallback ───+ // Every window starts hidden (visible:false in tauri.conf.json, and+ // the onboarding window is built the same way) and is normally+ // revealed by the frontend's invoke('show_window') once React+ // mounts. If the WebView never loads, or a render/hydration throw+ // happens before that effect runs (corrupt persisted state,+ // GPU/WebView2 fault), the window would stay hidden forever and the+ // app looks like it "runs with no window". Reveal the FRONT window- // after a timeout so the user always gets one — through the same- // rule as show_window, so the fallback can never pop the main- // window up over a running onboarding. The frontend's earlier++ // after a timeout so the user always gets one. The fallback goes++ // through the same rule as show_window, so it can never pop the++ // main window up over a running onboarding. The frontend's earlier+ // show_window is idempotent, so a healthy launch sees no+ // double-show / flicker. 10 s is comfortably longer than a normal+ // cold React mount (~1-2 s) yet short enough not to feel broken on+ // a slow i7/8 GB box.+ onboarding_window::force_show_after(app.handle().clone(), onboarding_window::FORCE_SHOW_DELAY);++ // ─── The watch on the two llama-server sidecars ───+ // A16: a sidecar killed from outside (Task Manager, a crash, a+ // driver reset) was only noticed when something asked for its+ // status, and Settings asks once per mount. The watch asks on a+ // timer and emits `lu-sidecar-gone`, so the panel can be right+ // while it is standing open.+ commands::engine::spawn_sidecar_watch(app.handle().clone());+// ─── System Tray ───let show = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?;let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;@@@ -781,8 -884,156 +895,156 @@@ mod log_english_tests// out byte for byte, fields and all.#[test]fn an_ordinary_line_is_logged_unchanged() {-- let out = logged(|| tracing::info!(version = "2.6.7", "LU starting"));++ let out = logged(|| tracing::info!(version = "2.6.8", "LU starting"));assert!(out.contains("LU starting"), "got: {out}");-- assert!(out.contains("version=\"2.6.7\""), "got: {out}");++ assert!(out.contains("version=\"2.6.8\""), "got: {out}");+ }+ }++ /// The log FILE itself (audit finding #01).+ ///+ /// Nothing here writes a real log — installing a global subscriber inside a+ /// unit test would fight every other test in the binary for the process-wide+ /// slot. What these pin is the part a refactor silently breaks: that the file+ /// layer exists at all, that its guard is kept, and that the rotation cannot+ /// quietly become unbounded.+ #[cfg(test)]+ mod log_file_tests {+ const SRC: &str = include_str!("main.rs");++ fn init_tracing_body() -> &'static str {+ let s = &SRC[SRC.find("fn init_tracing()").expect("init_tracing exists")..];+ &s[..s.find("\n}\n").expect("the function ends")]+ }++ #[test]+ fn the_worker_guard_is_held_by_main_and_not_dropped_on_the_spot() {+ // THE tracing-appender trap. `let _ = init_tracing();` compiles, runs,+ // and produces an empty log file, because `_` drops the guard+ // immediately and the writer thread dies with it. A named binding in+ // `main` lives until the process ends.+ // Bounded to main's own body — the negative assertion below matches+ // its own source text otherwise, and the test would fail on itself.+ let main_fn = &SRC[SRC.find("\nfn main() {").expect("main exists")..];+ let main_fn = &main_fn[..main_fn.find("\n}\n").expect("main ends")];+ assert!(+ main_fn.contains("let _log_guard = init_tracing();"),+ "main must bind the WorkerGuard to a named local for the app's lifetime"+ );+ assert!(+ !main_fn.contains("let _ = init_tracing();"),+ "`let _ =` drops the guard at once and empties the log file"+ );+ }++ #[test]+ fn the_file_layer_is_added_to_both_log_modes_and_replaces_neither() {+ // "Additionally, not instead of": a developer running `cargo tauri dev`+ // must keep the console output they read while working.+ let init = init_tracing_body();+ assert_eq!(+ init.matches(".with(file_layer)").count(),+ 2,+ "text mode and json mode both need the file layer:\n{init}"+ );+ assert!(+ init.contains("fmt::layer().compact()"),+ "the stdout layer must survive alongside the file:\n{init}"+ );+ }++ #[test]+ fn rotation_is_bounded_in_both_directions() {+ // 0 would keep nothing (a log that prunes itself is no log), and a+ // large number turns "the app writes a log" into "the app fills the+ // disk of anyone who leaves it running for a year".+ assert!(+ (2..=31).contains(&super::LOG_FILES_KEPT),+ "kept log files out of range: {}",+ super::LOG_FILES_KEPT+ );+ let init = SRC+ .find("fn file_log_writer()")+ .map(|i| &SRC[i..i + 1200])+ .expect("file_log_writer exists");+ assert!(init.contains("max_log_files"), "the appender must prune:\n{init}");+ assert!(init.contains("Rotation::DAILY"), "rotation must be configured:\n{init}");+ }++ #[test]+ fn a_home_that_cannot_be_written_to_does_not_stop_the_app() {+ // Read-only profile / full disk: a missing log file is a degraded app,+ // an app that will not launch without one is a broken app. The helper+ // must therefore be fallible-but-soft, i.e. return an Option.+ let src = SRC+ .find("fn file_log_writer()")+ .map(|i| &SRC[i..i + 400])+ .expect("file_log_writer exists");+ assert!(src.contains("-> Option<"), "must degrade rather than panic:\n{src}");+ }++ #[test]+ fn the_log_lives_next_to_the_crash_log() {+ // One folder per support request. If these two drift apart, half the+ // evidence gets left behind on every report.+ let logs = crate::os_paths::log_dir();+ let crash = crate::crash_report::crash_log_path();+ assert_eq!(+ logs.parent(),+ crash.parent(),+ "the rolling log and crash.log must share one directory"+ );+ }++ #[test]+ fn the_appender_really_writes_the_file_name_settings_reports() {+ // The only test here that runs the real crate. Everything else about+ // the path is our own arithmetic; this pins it against+ // tracing-appender's actual behaviour, including the detail that the+ // date in the name is UTC and not the local day. A subscriber scoped+ // to this thread keeps it out of the global slot the other tests share.+ use tracing_subscriber::layer::SubscriberExt;+ let dir = tempfile::tempdir().expect("tempdir");+ let appender = tracing_appender::rolling::Builder::new()+ .rotation(tracing_appender::rolling::Rotation::DAILY)+ .filename_prefix(crate::commands::logging::LOG_FILE_PREFIX)+ .filename_suffix(crate::commands::logging::LOG_FILE_SUFFIX)+ .max_log_files(super::LOG_FILES_KEPT)+ .build(dir.path())+ .expect("the appender builds");+ let (writer, guard) = tracing_appender::non_blocking(appender);+ let subscriber = tracing_subscriber::registry().with(+ tracing_subscriber::fmt::layer().with_writer(writer).with_ansi(false),+ );+ tracing::subscriber::with_default(subscriber, || {+ tracing::warn!("a line that has to reach the disk");+ });+ // Dropping the guard shuts the writer thread down AND flushes it —+ // which is exactly why main must not drop it early.+ drop(guard);++ let expected = crate::commands::logging::log_file_name(+ &chrono::Utc::now().format("%Y-%m-%d").to_string(),+ );+ let written = std::fs::read_to_string(dir.path().join(&expected))+ .unwrap_or_else(|e| panic!("expected {expected} in the log dir: {e}"));+ assert!(+ written.contains("a line that has to reach the disk"),+ "the file exists but is empty — the guard was dropped too early: {written:?}"+ );+ }++ #[test]+ fn the_frontend_can_actually_reach_the_log_commands() {+ // The commands exist in logging.rs whether or not they are registered;+ // an unregistered command is an invoke that rejects at runtime with+ // "not allowed by scope" and no compile error anywhere.+ for cmd in [+ "commands::logging::log_write",+ "commands::logging::log_file_path",+ "commands::logging::log_reveal",+ ] {+ assert!(SRC.contains(cmd), "{cmd} is not in generate_handler!");+ }}}diff --cc src/App.tsxindex 2f4842e9,dbabc1eb..3b63660c--- a/src/App.tsx+++ b/src/App.tsx@@@ -11,34 -14,9 +14,28 @@@ function App()invoke('show_window').catch(() => {})})- // The keychain is the store of record for the HuggingFace token; Rust- // holds it in memory only, so every boot pushes it down again. Without- // this, only opening Settings would arm the token, and a model download- // started from Create or the Model Manager would still go out anonymous- // and throttled.- import('./api/mlx-image').then(async ({ isMlxImageHost, applyHfToken, HF_TOKEN_ACCOUNT }) => {- if (!isMlxImageHost()) return- const { secretGet } = await import('./api/backend')- const stored = await secretGet(HF_TOKEN_ACCOUNT).catch(() => null)- if (stored) await applyHfToken(stored).catch(() => {})- })- // HuggingFace token + persisted GPU selection → Rust. Shared with the- // onboarding window, which boots without App (lib/rust-boot-sync.ts).++ // HuggingFace token + persisted GPU selection nach Rust. Geteilt mit dem++ // Onboarding-Fenster, das ohne App bootet (lib/rust-boot-sync.ts). Der++ // Schluesselbund bleibt die fuehrende Kopie des Tokens, Rust haelt ihn++ // nur im Speicher, also drueckt ihn jeder Boot erneut hinunter.+ void pushPersistedChoicesToRust().catch(() => {})++ // Same store of record for the CivitAI key, on every platform that has a+ // vault. This also moves an existing plaintext key out of localStorage,+ // once, on the first boot after the update.+ import('./stores/workflowStore').then(({ hydrateCivitaiApiKey }) => {+ hydrateCivitaiApiKey().catch(() => {})+ })++ // Hand the user's own model folder to ComfyUI at boot. It used to happen+ // only while the AI Backends settings tab was mounted, so a user who set+ // the folder in an older build and never opened that tab again would have+ // started ComfyUI without it forever.+ void (async () => {+ const { syncCustomModelDir } = await import('./lib/custom-model-dir')+ const { useSettingsStore: store } = await import('./stores/settingsStore')+ await syncCustomModelDir(store.getState().settings.hfDownloadPathOverride)+ })()}// Probe local Whisper (STT) once at boot and push the result into the voicediff --cc src/api/discover.tsindex bcd35413,91a9031a..ca4f00c1--- a/src/api/discover.ts+++ b/src/api/discover.ts@@@ -1,103 -1,36 +1,75 @@@import { backendCall, fetchExternal } from "./backend"import { getCheckpoints, getDiffusionModels, getVAEModels, getCLIPModels, getGgufUnetModels, getAnimateDiffModels, getLoraModels, filterPartialFiles, refreshComfyModels } from "./comfyui"+ import { clearNodeCache } from "./comfyui-nodes"+ import { restartComfyForNewNodes } from "./comfy-restart"import type { ProviderId } from "./providers/types"import { log } from "../lib/logger"+import { useWorkflowStore } from "../stores/workflowStore"-- export interface DiscoverModel {- name: string- description: string- pulls: string- tags: string[]- updated: string- url?: string- // For direct download- downloadUrl?: string- filename?: string- subfolder?: string // ComfyUI models subfolder: checkpoints, diffusion_models, vae, text_encoders- sizeGB?: number- // Vision projector that belongs to `downloadUrl`. A text GGUF carries no- // image tower: llama.cpp keeps it in a separate mmproj file and only sees- // images when the server is started with `--mmproj`. When this is set the- // download writes BOTH files into the model folder and the built-in engine- // picks the projector up by name (see `mmprojFileName`). Ollama entries never- // need it, their tag already ships a projector layer.- mmprojUrl?: string- mmprojSizeGB?: number- // Discovery flags- hot?: boolean // Featured/trending model- agent?: boolean // Supports Agent Mode tool calling- released?: string // Release date YYYY-MM for sorting (newest first)- // F4 (juliandiggins-stack GH#21): explicit CPU-only / ≤8 GB RAM- // tag. Surfaces a green "CPU-friendly" badge in DiscoverModels and- // exposes the optional "Lightweight" filter. Set true for ≤4B- // unfiltered models we have personally test-loaded on a CPU-only- // 8 GB box.- lightweight?: boolean- // Multi-provider- provider?: ProviderId // Which provider this model belongs to- providerName?: string // Display name of the provider- canPull?: boolean // false = no download/pull capability (cloud/external)- ollamaModel?: string // Ollama model tag for `ollama pull` (e.g. 'qwen3.6')- // Model Hub grouping (2.5.8 redesign): entries that are the SAME model in a- // different quant share a `group` and render as ONE card with a size picker.- // Different parameter sizes stay separate cards on purpose.- group?: string- // Optional hand-written one-liner for the card. When absent the card derives- // a short line from `description` (text after the first "·", first sentence).- blurb?: string- }-- export interface DownloadProgress {- progress: number- total: number- speed: number- filename: string- status: 'connecting' | 'downloading' | 'pausing' | 'paused' | 'complete' | 'error'- error?: string- }+ import { waitForModelsVisible } from "../lib/bundle-install"+ import type { DownloadProgress } from "../types/downloads"+ import { asNumber, asRecordArray, asString, isRecord, prop, propPath } from "../types/json-guards"+ import type { DiscoverModel, ModelBundle } from "./model-bundles"+ import {+ CUSTOM_NODE_REGISTRY,+ getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles,+ } from "./model-bundles"++ // Katalog + Formen liegen in model-bundles.ts (siehe dort). Re-Export, damit+ // bestehende Importpfade unverändert bleiben.+ export type { DiscoverModel, ModelBundle, CustomNodeDef } from './model-bundles'+ export {+ CUSTOM_NODE_REGISTRY,+ getImageBundles, getImageModelsDiscover, getVideoBundles,+ getAudioBundles, getLipsyncBundles, getMotionBundles,+ } from './model-bundles'++ // Die Fortschrittsform lebt in types/downloads.ts, damit lib/bundle-install.ts+ // sie lesen kann, ohne dieses Modul zu importieren. Re-Export, damit bestehende+ // Importpfade unverändert bleiben.+ export type { DownloadProgress }// ─── Download API ───+/**+ * Is this URL served by CivitAI? Host comparison, never a substring of the+ * whole URL: `https://evil.test/?x=civitai.com` must not collect the user's+ * API key. Mirrors `is_civitai_host` in `src-tauri/src/commands/download.rs`,+ * which gates the same key a second time on its way onto the wire.+ */+const CIVITAI_HOSTS = ['civitai.com', 'civitai.red']++export function isCivitaiUrl(url: string): boolean {+ let host: string+ try {+ host = new URL(url).hostname.toLowerCase()+ } catch {+ return false+ }+ return CIVITAI_HOSTS.some((h) => host === h || host.endsWith(`.${h}`))+}++/**+ * The user's CivitAI API key, for a CivitAI URL and no other.+ *+ * goonerforporn (Discord #bug-reports, 2026-08-28): downloads from the CivitAI+ * search died in 400s because they went out anonymous. The key was in the store+ * and read by the search, and by nothing on the download path.+ */+export function civitaiAuthToken(url: string): string | null {+ if (!isCivitaiUrl(url)) return null+ const key = useWorkflowStore.getState().civitaiApiKey?.trim()+ return key ? key : null+}+- export async function startModelDownload(url: string, subfolder: string, filename: string, expectedBytes?: number): Promise<{ status: string; id: string; error?: string }> {+ export async function startModelDownload(url: string, subfolder: string, filename: string, expectedBytes?: number, sha256?: string): Promise<{ status: string; id: string; error?: string }> {- return backendCall("download_model", { url, subfolder, filename, expectedBytes: expectedBytes ?? null, expectedSha256: sha256 ?? null })+ return backendCall("download_model", {+ url,+ subfolder,+ filename,+ expectedBytes: expectedBytes ?? null,++ expectedSha256: sha256 ?? null,+ authToken: civitaiAuthToken(url),+ })}export async function getDownloadProgress(): Promise<Record<string, DownloadProgress>> {@@@ -116,8 -58,142 +97,149 @@@ export async function cancelDownload(idawait backendCall("cancel_download", { id })}- export async function resumeDownload(id: string, url: string, subfolder: string): Promise<void> {- await backendCall("resume_download", { id, url, subfolder, authToken: civitaiAuthToken(url) })+ /**+ * Drop a settled row (error / paused / complete) from the Rust progress map and+ * LEAVE THE PARTIAL FILE ALONE.+ *+ * Clearing the Rust side is not optional before a retry: `download_model`+ * short-circuits on a file that is already on disk without ever touching the+ * map, so the next poll would resurrect the error row the user just retried+ * (the_mr_pickles). That bookkeeping is all this does — it is not a decision+ * about the user's bytes.+ */+ export async function clearDownloadEntry(id: string): Promise<void> {+ await backendCall("clear_download_entry", { id })+ }++ /**+ * The four answers that mean the ADDRESS is dead rather than the connection:+ * gone (404/410) and gated-or-private (401/403). Everything else — a transport+ * error, a rate limit, a 5xx — is the host having a bad minute and stays+ * retryable.+ *+ * ONE list, read from two directions. `isPermanentDownloadError` reads it out+ * of the message a failed download carries back from Rust; `classifyAddressProbe`+ * (below, used by the catalog gate) reads it out of a bare HTTP status. Two+ * hand-written copies of "what counts as broken" would be two chances to+ * disagree, and the disagreement would be silent: the gate would pass an+ * address the download path calls permanently dead.+ */+ export const PERMANENT_HTTP_STATUSES: readonly number[] = [401, 403, 404, 410]++ const PERMANENT_HTTP = new RegExp(`\\(HTTP (${PERMANENT_HTTP_STATUSES.join('|')})\\)`)++ /**+ * Would pressing Retry on this error ever succeed?+ *+ * The catalog hard-codes its HuggingFace addresses (`catalogAddresses()` walks+ * every one of them). When one of those repos is renamed, gated or taken down,+ * every attempt answers the same 404/403 forever, and the old UI answered with+ * a bare "HTTP 404" and a Retry button — a loop with no exit. The status code+ * inside the message is the contract; it is put there by `http_error_message`+ * in src-tauri/src/commands/download.rs.+ *+ * A transport error, a rate limit and a 5xx are all temporary and stay+ * retryable: only an address that is gone is permanent.+ */+ export function isPermanentDownloadError(error?: string | null): boolean {+ return !!error && PERMANENT_HTTP.test(error)+ }++ export async function resumeDownload(id: string, url: string, subfolder: string, expectedBytes?: number, sha256?: string): Promise<void> {- await backendCall("resume_download", { id, url, subfolder, expectedBytes: expectedBytes ?? null, expectedSha256: sha256 ?? null })++ await backendCall("resume_download", {++ id,++ url,++ subfolder,++ expectedBytes: expectedBytes ?? null,++ expectedSha256: sha256 ?? null,++ authToken: civitaiAuthToken(url),++ })+ }++ /** A `.download` partial from an earlier run of the app, with no row watching it. */+ export interface OrphanDownload {+ /** Basename minus its extension — NOT the download id. See `orphanFilename`. */+ stem: string+ /** Absolute path of the partial. */+ path: string+ /** Directory it sits in; a GGUF outside the ComfyUI tree resumes into this. */+ dir: string+ bytes: number+ }++ /**+ * Partial downloads a previous run of the app left behind.+ *+ * Both halves of the download kept their state purely in RAM, so quitting+ * during a multi-gigabyte transfer left the `.download` file on disk with no+ * row, no button and no way to finish or delete it. `extraDirs` carries the+ * provider model folders only the frontend knows (LM Studio, a custom path),+ * taken from the download meta the store now persists.+ */+ export async function findOrphanDownloads(extraDirs: string[] = []): Promise<OrphanDownload[]> {+ try {+ return await backendCall("find_orphan_downloads", { extraDirs })+ } catch (err) {+ log.warn('[discover] orphan scan failed', { err })+ return []+ }+ }++ /** Delete one orphaned partial. Jailed to the model folders on the Rust side. */+ export async function deleteOrphanDownload(path: string, extraDirs: string[] = []): Promise<void> {+ await backendCall("delete_orphan_download", { path, extraDirs })+ }++ /**+ * Recover the download id (the real filename) for an orphaned partial.+ *+ * `Path::with_extension("download")` REPLACES the extension, so the partial for+ * `wan_2.1_vae.safetensors` is `wan_2.1_vae.download`: the original suffix is+ * not on disk any more. Everything that can name the file lives up here — the+ * persisted download meta first, because it also knows the destDir, then the+ * catalog. A stem nothing recognises stays unresolved; it can still be shown+ * and deleted, just not resumed.+ */+ export function orphanFilename(stem: string, knownFilenames: Iterable<string>): string | null {+ for (const name of knownFilenames) {+ if (name === stem || name.replace(/\.[^.]+$/, '') === stem) return name+ }+ return null+ }++ /** Verdict of the ONE space check a bundle gets before its first transfer. */+ export interface SpaceVerdict {+ fits: boolean+ requiredBytes: number+ reservedBytes: number+ availableBytes?: number | null+ message?: string+ }++ /**+ * Does `requiredBytes` still fit, counting what running transfers still owe?+ *+ * Asked once for a whole bundle. The per-file check in `do_download` answers+ * "does the rest of THIS file fit", which is the wrong question when four files+ * start at the same moment: all four passed against the same free bytes, all+ * four started, and the drive filled anyway — on Windows a full system+ * partition degrades the whole machine, not just the download.+ */+ export async function checkDownloadSpace(+ target: { subfolder?: string; destDir?: string },+ requiredBytes: number,+ ): Promise<SpaceVerdict | null> {+ try {+ return await backendCall("check_download_space", {+ subfolder: target.subfolder ?? null,+ destDir: target.destDir ?? null,+ requiredBytes: Math.max(0, Math.round(requiredBytes)),+ })+ } catch (err) {+ // A drive we cannot measure must never block a download.+ log.warn('[discover] space check unavailable', { err })+ return null+ }}// ─── Custom Node Installation ───@@@ -2451,22 -1805,28 +1851,31 @@@ export async function searchCivitaiMode// back near-empty for users who expected to find e.g. unfiltered SDXL forks.nsfw: 'true',})- // Adding the user's API key as a bearer token unlocks the full catalog and- // lifts the per-IP rate limit. Falls back to anon access if no key is set.- const url = `https://${host}/api/v1/models?${params}${apiKey ? `&token=${encodeURIComponent(apiKey)}` : ''}`- const text = await fetchExternal(url)+ // The user's API key unlocks the full catalog and lifts the per-IP rate+ // limit. It travels as an Authorization header, NOT as `&token=` in the+ // URL: the URL is what the error text and the log line quote, and the log+ // scrubber cannot see a secret that is just another substring of a URL.+ // No key set is still a valid, anonymous search.+ const url = `https://${host}/api/v1/models?${params}`+ const text = await fetchExternal(url, apiKey ?? null)- const data = JSON.parse(text)- const items: any[] = data.items ?? []+ const data: unknown = JSON.parse(text)+ // CivitAI's catalogue, not ours: `items` is walked with the boundary+ // guards, and a single malformed entry now yields a partly-empty CARD+ // instead of throwing out of the `.map` and losing all twenty results to+ // the catch below.+ const items = asRecordArray(prop(data, 'items'))return items.map((item) => {- const version = item.modelVersions?.[0]- const file = version?.files?.[0]- const thumb = version?.images?.[0]?.url- const downloadUrl = version?.downloadUrl ?? file?.downloadUrl- const sizeKB = file?.sizeKB ?? 0+ const version = asRecordArray(prop(item, 'modelVersions'))[0]+ const file = asRecordArray(prop(version, 'files'))[0]+ const thumb = asString(propPath(asRecordArray(prop(version, 'images'))[0], 'url'))+ const downloadUrl = asString(prop(version, 'downloadUrl')) ?? asString(prop(file, 'downloadUrl'))+ const sizeKB = asNumber(prop(file, 'sizeKB')) ?? 0+ const itemName = asString(prop(item, 'name'))+ const itemId = asNumber(prop(item, 'id')) ?? 0+ const stats = prop(item, 'stats')+ const downloadCount = asNumber(prop(stats, 'downloadCount'))+ const creator = asString(propPath(item, 'creator', 'username'))// Determine subfolder based on model typelet subfolder = 'checkpoints'diff --cc src/api/engine.tsindex ab5c2edb,c4a0668d..a3170914--- a/src/api/engine.ts+++ b/src/api/engine.ts@@@ -11,10 -11,9 +11,10 @@@* `backendCall` maps camelCase args → snake_case Rust params (Tauri).*/-import { backendCall } from './backend'+import { backendCall, isLinux } from './backend'+import { syncBuiltinEnginePort } from './builtin-ensure'import { trackEngineSwap } from './engine-swap-gate'- import { prefixModelName } from './providers'+ import { prefixModelName } from './providers/model-name'import { useProviderStore } from '../stores/providerStore'import { useSettingsStore } from '../stores/settingsStore'import type { CloudModel } from '../types/models'diff --cc src/api/providers/openai-provider.tsindex feadde35,444eb93e..1fab1945--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@@ -21,7 -23,10 +23,11 @@@ import { parseRetryAfter } from '../../import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost, backendCall } from '../backend'import { ensureBuiltinEngineAlive, explainDeadEngine, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'import { applyTemplateContract } from './normalize-system'+import { clampEffort, hasEffortLadder, DEFAULT_EFFORT } from '../../lib/effort'+ import {+ parseOpenAIStreamChunk, parseOpenAIChatResponse, keyForUnindexedBlock,+ isRecord, prop, asString, asNumber, asBoolean, asRecordArray,+ } from './wire'// Transport routing lives in the `useLocalProxy` getter (below) plus the shared// host helpers in backend.ts. A direct webview fetch only works for hosts the@@@ -31,41 -36,73 +37,74 @@@// probing), which must not follow the transport decision.// ── OpenAI API Types ───────────────────────────────────────────+ //+ // What comes BACK lives in ./wire, behind checked parsers. It used to be+ // declared here as two hand-rolled interfaces asserted onto `JSON.parse` and+ // `res.json()`, and both said things the code itself knew to be false: the+ // tool-call delta declared `index: number` as required while the accumulator+ // right below it falls back to `keyForUnindexedBlock` precisely because+ // servers omit it, and `choices` was typed as a one-element tuple.- interface OpenAIStreamChunk {- choices?: [{- delta?: {- content?: string- // Native reasoning channel — DeepInfra (LU Cloud) reasoning models- // stream thinking as `reasoning_content`, some as `reasoning`.- reasoning_content?: string- reasoning?: string- tool_calls?: {- index: number- id?: string- function?: { name?: string; arguments?: string }- }[]- }- finish_reason?: string | null- }]+ /**+ * What we SEND to `/v1/chat/completions`.+ *+ * A real shape, not a `Record<string, any>` bag: the ladder in `sendChat`+ * reads and deletes four of these fields by name, and under `any` a typo in+ * one of those names would have compiled into a request that silently kept+ * the parameter the server just refused.+ */+ export interface OpenAIContentPart {+ type: 'text' | 'image_url'+ text?: string+ image_url?: { url: string }}- interface OpenAIResponse {- choices?: [{- message?: {- content?: string- reasoning_content?: string- reasoning?: string- tool_calls?: {- id: string- type: 'function'- function: { name: string; arguments: string }- }[]- }- finish_reason?: string- }]+ export interface OpenAIRequestToolCall {+ id: string+ type: 'function'+ function: { name: string; arguments: string }+ }++ export interface OpenAIRequestMessage {+ role: ChatMessage['role']+ content: string | OpenAIContentPart[]+ tool_calls?: OpenAIRequestToolCall[]+ tool_call_id?: string+ }++ export interface OpenAIChatRequest {+ model: string+ messages: OpenAIRequestMessage[]+ stream: boolean+ temperature?: number+ top_p?: number+ max_tokens?: number+ tools?: ToolDefinition[]+ tool_choice?: 'auto' | 'none' | 'required'- /** 'high' | 'minimal' | 'none' — stepped down, then deleted, by sendChat. */++ /** One rung of the effort ladder ('none' and 'minimal' mean off). Stepped++ * down, then deleted, by sendChat. */+ reasoning_effort?: string+ chat_template_kwargs?: Record<string, unknown>+ stream_options?: { include_usage: boolean }}+ /**+ * The two transports this provider posts through: the browser `fetch` and+ * `localFetch`/`localFetchStream` (Rust proxy). Both satisfy this narrower+ * signature, which is what removes the `fetcher as any` casts that used to+ * bridge them — a cast that would equally have accepted a function taking no+ * arguments at all.+ */+ type ChatFetcher = (+ url: string,+ init: {+ method?: string+ headers?: Record<string, string>+ body?: string+ signal?: AbortSignal+ },+ ) => Promise<Response>+interface OpenAIModelEntry {id: stringobject: string@@@ -84,15 -121,34 +123,41 @@@// it → the mapping falls back to `true` (optimistic, corrected at runtime).supports_tools?: booleanthink?: 'toggle' | 'always' | 'never'+ // The reasoning rungs this model accepts, ascending, and the one it defaults+ // to. LU Cloud sends both for every model that reasons and neither for a+ // `think: 'never'` one. Absent everywhere else, and absent on an LU Cloud+ // deployment that predates 2.6.8, which is why every reader below treats a+ // missing ladder as "keep doing exactly what you did before".+ reasoning_effort_levels?: string[]+ reasoning_effort_default?: string}+ /**+ * Build a catalogue entry out of one `/v1/models` element, checking every+ * field on the way. `think` is validated against the three values the rest of+ * the app switches on — a server sending anything else must not smuggle a+ * fourth mode into the model picker.+ */+ function toModelEntry(m: Record<string, unknown>): OpenAIModelEntry {+ const think = asString(m.think)+ return {+ // A catalogue row with no string id is unusable downstream (it keys+ // KNOWN_CONTEXT and every heuristic); '' keeps the row and keeps+ // guessContextFromName from being handed a non-string.+ id: asString(m.id) ?? '',+ object: asString(m.object) ?? 'model',+ created: asNumber(m.created),+ owned_by: asString(m.owned_by),+ name: asString(m.name),+ context_length: asNumber(m.context_length),+ input_modalities: Array.isArray(m.input_modalities)+ ? m.input_modalities.filter((x): x is string => typeof x === 'string')+ : undefined,+ supports_tools: asBoolean(m.supports_tools),+ think: think === 'toggle' || think === 'always' || think === 'never' ? think : undefined,+ }+ }+// ── Known context lengths for popular models ───────────────────const KNOWN_CONTEXT: Record<string, number> = {@@@ -400,26 -446,28 +506,33 @@@ export class OpenAIProvider implements*/private async sendChat(model: string,- body: Record<string, any>,+ body: OpenAIChatRequest,signal: AbortSignal | undefined,- fetcher: (url: string, init: any) => Promise<Response>,+ fetcher: ChatFetcher,): Promise<Response> {- const post = () => fetcher(`${this.baseUrl}/chat/completions`, {- method: 'POST',- headers: this.headers,- body: JSON.stringify(body),- signal,- })+ // Sanierungspfad: a throttle or a gateway hiccup is not the request's+ // fault, and the user used to read the raw status line for it. The retry+ // sits HERE, around the request, so it can never replay a stream that has+ // already started — see providers/retry.ts for the rules.+ const post = () => sendWithTransientRetry(+ () => fetcher(`${this.baseUrl}/chat/completions`, {+ method: 'POST',+ headers: this.headers,+ body: JSON.stringify(body),+ signal,+ }),+ { signal },+ )const refused = (res: Response) => !res.ok && (res.status === 400 || res.status === 422)- const asked = body.reasoning_effort as string | undefined+ const asked = body.reasoning_effort+ // 'none' and 'minimal' are the two ways of saying off; every other rung is+ // the ON lane. Reading it off the value rather than off 'high' is what lets+ // 'low', 'medium' and 'max' keep their own memory instead of borrowing the+ // off switch's.const lane: 'on' | 'off' | undefined =- asked === undefined ? undefined : asked === 'high' ? 'on' : 'off'+ asked === undefined ? undefined : asked === 'none' || asked === 'minimal' ? 'off' : 'on'+ const memoryKey = lane === undefined ? '' : this.effortKey(model, lane, asked)// Stop ends the walk. The real fetch rejects on an aborted signal on its// own, but localFetchStream's proxy path used to fire the request anyway,@@@ -454,9 -502,9 +567,9 @@@}if (res.ok && lane) {- const survived = body.reasoning_effort as string | undefined+ const survived = body.reasoning_effort- if (survived === undefined) this.rememberEffort(model, lane, 'omit')- else if (survived !== asked) this.rememberEffort(model, lane, 'minimal')+ if (survived === undefined) this.rememberEffort(memoryKey, lane, 'omit')+ else if (survived !== asked) this.rememberEffort(memoryKey, lane, 'minimal')}return resdiff --cc src/api/rag.tsindex 28f64067,41ec595f..450930b8--- a/src/api/rag.ts+++ b/src/api/rag.ts@@@ -148,23 -211,26 +211,26 @@@ async function embedViaBuiltin(texts: sif (!res.ok) {let detail = ""try {- const body = await res.json()- detail = body?.error?.message || body?.error || ""+ const body: unknown = await res.json()+ // errorText covers both shapes this used to spell out by hand: a plain+ // string error and an `{ message }` object.+ detail = errorText(prop(body, "error"))} catch { /* ignore parse errors */ }throw new Error(- `Embedding failed (HTTP ${res.status}): ${detail || "the built-in embeddings server may still be loading"}`+ `Embedding failed (HTTP ${res.status}): ${detail || "the LU Engine embeddings server may still be loading"}`)}- const data = await res.json()+ const data: unknown = await res.json()// OpenAI shape: { data: [{ embedding: number[], index }] }. Sort by index so// the vectors line up with the input order even if the server reorders them.- if (!data?.data || !Array.isArray(data.data)) {+ const rows = prop(data, "data")+ if (!rows || !Array.isArray(rows)) {- throw new Error("Unexpected response from the built-in /v1/embeddings endpoint")+ throw new Error("Unexpected response from the LU Engine /v1/embeddings endpoint")}- return [...data.data]- .sort((a: any, b: any) => (a.index ?? 0) - (b.index ?? 0))- .map((d: any) => d.embedding as number[])+ return [...rows]+ .sort((a, b) => (asNumber(prop(a, "index")) ?? 0) - (asNumber(prop(b, "index")) ?? 0))+ .map((d) => asNumberArray(prop(d, "embedding")))}/** Ollama `/api/embed` — the legacy/Advanced path (unchanged). */diff --cc src/api/vram-handoff.tsindex ed4a1245,4414c27f..fe1b648e--- a/src/api/vram-handoff.ts+++ b/src/api/vram-handoff.ts@@@ -45,9 -45,10 +45,11 @@@*/import { backendCall, ollamaUrl, localFetch, isOllamaLocal, isWindows } from './backend'+ import type { ComfyApiGraph } from '../types/comfy-graph'+ import { asNumber, asRecordArray, asString, prop } from '../types/json-guards'import { listRunningModels, loadModel, unloadModel } from './ollama'import { startBundledEngine } from './engine'+import { getAmdGpuArch } from '../lib/hardware'import { useSettingsStore } from '../stores/settingsStore'import {getImageModels,@@@ -1484,21 -1591,30 +1592,37 @@@ async function pollAndExtract(promptId// Pull the richest detail ComfyUI gives us: an execution_error carries// node_type + exception_type + exception_message (the plain `message`// field is usually empty for node errors — David 2026-06-11, FramePack).- const errEntry = history.status.messages?.find((m: any) => m?.[0] === 'execution_error')?.[1]+ // ComfyHistoryEntry DECLARES `messages` as pairs; getHistory only+ // checked that the entry is an object, so the array-ness is tested+ // here rather than assumed by a `?.find` that would throw on a string.+ const messages = Array.isArray(history.status.messages) ? history.status.messages : []+ const errEntry = messages.find((m) => m?.[0] === 'execution_error')?.[1]const rawMsg = errEntry?.exception_message- || history.status.messages?.map((m: any) => m?.[1]?.message).filter(Boolean).join(' | ')- || history.status.messages?.[0]?.[1]?.message+ || messages.map((m) => m?.[1]?.message).filter(Boolean).join(' | ')+ || messages[0]?.[1]?.message|| 'Unknown ComfyUI error'- const hint = comfyErrorHint(errEntry?.node_type, errEntry?.exception_type, String(rawMsg))+ // The architecture only matters for the hipErrorInvalidValue branch, so+ // it is only fetched for that branch. detect_gpus shells out to several+ // vendor tools, each bounded at five seconds, and putting that in front+ // of EVERY ComfyUI failure would have delayed an out-of-memory message+ // or a missing-node message by seconds for nothing.+ const raw = String(rawMsg)+ const arch = /hiperrorinvalidvalue/i.test(raw) ? await getAmdGpuArch().catch(() => null) : null+ const hint = comfyErrorHint(errEntry?.node_type, errEntry?.exception_type, raw, arch)return `${kindLabel} generation failed: ${rawMsg}${hint ? `\n\n${hint}` : ''}`}+ const probeGap = comfyMisses > 0 ? COMFY_RECHECK_MS : COMFY_PROBE_EVERY_MS+ if (Date.now() - comfyProbedAt >= probeGap) {+ comfyProbedAt = Date.now()+ const alive = await raceCancel(checkComfyConnection())+ if (alive === CANCELLED) return `${kindLabel} generation cancelled.`+ comfyMisses = alive ? 0 : comfyMisses + 1+ if (comfyMisses >= 2) {+ const elapsedMs = Date.now() - startedAt+ log.warn('vram_handoff.comfy_died_mid_render', { promptId, elapsedMs })+ return `${kindLabel} generation failed: ComfyUI stopped responding after ${Math.round(elapsedMs / 1000)}s, so the render cannot finish. Start ComfyUI from the Create tab and try again.`+ }+ }const projected = pace.projectedTotalMs()if (overBudget(projected, timeoutMs)) {log.warn('vram_handoff.render_budget_abort', { promptId, projectedMs: Math.round(projected!), budgetMs: timeoutMs })diff --cc src/components/chat/ChatInput.tsxindex 1311a54d,ede1dab8..7e295815--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@@ -1,17 -1,16 +1,18 @@@import { useState, useRef, useEffect, useCallback, type ReactNode } from 'react'- import { motion } from 'framer-motion'-import { Send, Square, Paperclip, X, Brain, Terminal } from 'lucide-react'+import { Send, Square, Paperclip, X, Brain, Gauge, Terminal } from 'lucide-react'- import { matchAgentCommands, type AgentCommand } from '../../lib/agent-commands'+ import { matchAgentCommands, type AgentCommand, type CommandScope } from '../../lib/agent-commands'import { VoiceButton } from './VoiceButton'import { ApprovalDialog } from './ApprovalDialog'import { useVoiceStore } from '../../stores/voiceStore'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'+ import { useChatStore } from '../../stores/chatStore'import { isThinkingCompatible, isVisionCompatible, declaredVision } from '../../lib/model-compatibility'+import { clampEffort, effortChoices, effortLabel, nextEffort, DEFAULT_EFFORT } from '../../lib/effort'import type { AgentToolCall } from '../../types/agent-mode'import type { ImageAttachment } from '../../types/chat'+import { COMPOSER_MAX_W } from './composer-width'+ import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'interface Props {onSend: (content: string, images?: ImageAttachment[]) => void@@@ -21,21 -20,27 +22,23 @@@onApprove?: () => voidonReject?: () => voiddisabled?: boolean- /**- * Enable the "/command" typeahead. Only the Coding Agent (Code view) sets this- * — slash commands belong there, not in the normal chat (David 2026-06-12).- *//**- * Enable the "/command" typeahead. Only the Coding Agent (Code view) sets this- * — slash commands belong there, not in the normal chat (David 2026-06-12).+ * Which commands this composer offers. Was a boolean meaning+ * "Coding-Agent-only"; since 2.6.8 it is the SCOPE, because the answer+ * stopped being all-or-nothing: plain chat offers /compact and nothing else,+ * while Agent and Coding offer the whole set. Undefined = no menu at all.*/- slashCommands?: boolean+ slashCommands?: CommandScope/*** Open the Documents (RAG) panel. The clip button is images-only; this lets the* composer point a user who tried to attach a PDF/doc to the right place-- * (GH #69 — a PDF was silently dropped and the model hallucinated it couldn't++ * (GH #69: a PDF was silently dropped and the model hallucinated it couldn't* receive attachments).*/onAttachDocs?: () => void/*** The model picker, rendered on the right of the action bar (before Send).-- * The header no longer carries it — each surface passes an upward-opening++ * The header no longer carries it. Each surface passes an upward-opening* ModelSelector so the prompt window owns the model choice (web parity).*/composerModel?: ReactNode@@@ -48,6 -53,27 +51,27 @@@composerActions?: ReactNode}+ /** How long the synchronous double-fire guard below stays shut. */+ const SEND_LOCK_MS = 700++ /**+ * The double-fire guard's clock read, deliberately OUTSIDE the component.+ *+ * Reading `Date.now()` from a function declared in the component body puts an+ * impure call in the render path as far as React 19 is concerned (`purity`),+ * and the rule is right about where such a read belongs: not in a component,+ * not in a hook. Moving the whole check out here keeps it exactly as- * synchronous as it was — the point of the guard is that it decides inside the- * same tick as the second keydown — and makes it a thing that can be reasoned++ * synchronous as it was (the point of the guard is that it decides inside the++ * same tick as the second keydown) and makes it a thing that can be reasoned+ * about (and tested) on its own. Returns false when the send must be dropped.+ */+ function passSendLock(lock: { current: number }): boolean {+ const now = Date.now()+ if (now - lock.current < SEND_LOCK_MS) return false+ lock.current = now+ return true+ }+function fileToImageAttachment(file: File): Promise<ImageAttachment> {return new Promise((resolve, reject) => {const reader = new FileReader()@@@ -73,6 -99,79 +97,79 @@@ export function ChatInput({ onSend, onS// the matching agent commands; ↑/↓ to move, Enter/Tab to pick, Esc to dismiss.const [cmdMenu, setCmdMenu] = useState<AgentCommand[]>([])const [cmdIndex, setCmdIndex] = useState(0)+ /**+ * Ein Entwurf gehoert dem Gespraech, in dem er getippt wurde.+ *+ * Der Composer wird beim Wechsel nicht neu gebaut, also stand der halbe Satz- * aus dem alten Chat im neuen wieder im Feld — einmal beobachtet am++ * aus dem alten Chat im neuen wieder im Feld, einmal beobachtet am+ * 03.09.2026, mit dem naheliegenden Ausgang: der Satz geht an den falschen+ * Empfaenger. Ihn beim Wechsel einfach zu leeren waere die andere Haelfte+ * desselben Fehlers, nur teurer (Arbeit weg), darum wird er beiseitegelegt+ * und beim Zurueckkommen wieder hingelegt. Bilder reisen mit dem Text, sonst+ * hinge die Anlage am falschen Satz.+ *+ * WIE der Wechsel bemerkt wird, ist nicht Geschmack, sondern die Stelle, an+ * der dieser Block zweimal mit React aneinandergeriet. Er stand bis zum+ * 03.09.2026 als Effekt hier, mit zwei Refs davor, und war der einzige rote+ * Punkt von `npm run lint`. In Wahrheit zwei, denn eslint meldet pro+ * Komponente nur den ersten:+ *+ * 1. `react-hooks/refs`, "Cannot access refs during render". Der Stand des+ * Feldes wurde blank im Renderkoerper in ein Ref geschrieben+ * (`standRef.current = { input, images }`), damit der Effekt beim+ * Wechsel noch an die Werte VOR dem Wechsel kam.+ * 2. `react-hooks/set-state-in-effect`. Der Effekt rief `setInput` und+ * `setImages` direkt auf, also genau die Kaskade, vor der die Regel+ * warnt: erst ein Commit mit dem alten Entwurf, dann ein zweiter mit+ * dem neuen.+ *+ * Beide Regeln haben recht, und beide zeigen auf dieselbe Ursache: ein+ * Effekt ist der falsche Ort. React nennt den richtigen selbst ("You Might+ * Not Need an Effect" → Zustand anpassen, wenn sich etwas geaendert hat):+ * der Vergleich mit dem vorigen Wert steht IM Render, und die Anpassung+ * geschieht dort. React laeuft die Komponente sofort noch einmal, bevor es+ * ueberhaupt etwas uebergibt.+ *+ * Damit fallen beide Fehler zusammen mit ihrer Ursache weg. Das Ref fuer den+ * Stand braucht es nicht mehr: im Wechselrender fuehren `input` und `images`+ * noch den alten Entwurf, denn geleert wird erst hier, eine Zeile weiter+ * unten. Das ist derselbe Wert, den das Ref transportiert hat, nur ohne+ * Umweg. Und die Kaskade entfaellt, weil der Wechsel keinen eigenen Commit+ * mehr kostet: das Feld ist schon leer, wenn der neue Chat zum ersten Mal+ * zu sehen ist, statt fuer einen Frame den fremden Satz zu zeigen.+ *+ * Die beiden Refs sind deshalb Zustand geworden. Ein Ref darf im Render+ * nicht gelesen werden (Regel 1), und gelesen werden muessen hier beide.+ */+ const conversationId = useChatStore((s) => s.activeConversationId)+ const [entwuerfe, setEntwuerfe] = useState<Record<string, { text: string; bilder: ImageAttachment[] }>>({})+ const [letztesGespraech, setLetztesGespraech] = useState(conversationId)+ if (letztesGespraech !== conversationId) {+ const vorher = letztesGespraech+ setLetztesGespraech(conversationId)+ if (vorher) {+ const text = input+ const bilder = images+ // Der Aktualisierer laeuft unter StrictMode zweimal und muss deshalb+ // beim zweiten Mal dasselbe Ergebnis liefern wie beim ersten. Er+ // rechnet nur aus `bisher`, haengt also an nichts, was er selbst+ // veraendert.+ setEntwuerfe((bisher) => {+ if (text || bilder.length) return { ...bisher, [vorher]: { text, bilder } }+ if (!(vorher in bisher)) return bisher+ const ohne = { ...bisher }+ delete ohne[vorher]+ return ohne+ })+ }+ // Gelesen wird der Stand VOR dieser Anpassung, und das ist richtig:+ // geschrieben wurde gerade der Schluessel `vorher`, geholt wird+ // `conversationId`, und die beiden sind hier nie dasselbe.+ const zurueck = conversationId ? entwuerfe[conversationId] : undefined+ setInput(zurueck?.text ?? '')+ setImages(zurueck?.bilder ?? [])+ setCmdMenu([])+ }const textareaRef = useRef<HTMLTextAreaElement>(null)const fileInputRef = useRef<HTMLInputElement>(null)// Text already in the box when dictation started. Interim + final transcripts@@@ -122,7 -208,7 +219,7 @@@const addFiles = useCallback(async (files: FileList | File[]) => {const all = Array.from(files)const imageFiles = all.filter(f => f.type.startsWith('image/'))-- // A non-image file (PDF, Word, text, …) can't ride along as a chat image —++ // A non-image file (PDF, Word, text, …) can't ride along as a chat image,// it belongs in the Documents panel (RAG) so the model can actually read it.// Silently dropping it made a user think their PDF attached when it didn't,// and the model then hallucinated that it "couldn't receive attachments"@@@ -145,7 -231,7 +242,7 @@@}// Write a dictation transcript (interim or final) into the input as-- // base + transcript, then resize the textarea. NEVER sends — the user++ // base + transcript, then resize the textarea. NEVER sends, because the user// reviews and presses Send (David 2026-06-06).const applyDictation = (text: string) => {const base = dictationBaseRef.current@@@ -287,9 -373,9 +384,9 @@@onDragLeave={handleDragLeave}onDrop={handleDrop}>-- {/* Slash-command autocomplete — floats above the composer */}++ {/* Slash-command autocomplete, floats above the composer */}{cmdMenu.length > 0 && (- <div className="absolute bottom-full left-0 right-0 mb-1.5 z-50 max-h-64 overflow-y-auto scrollbar-thin rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-[#1f1f1f] shadow-xl py-1">+ <div className="absolute bottom-full left-0 right-0 mb-1.5 z-50 max-h-64 overflow-y-auto scrollbar-thin rounded-lg lu-elevated py-1"><div className="px-2.5 py-1 flex items-center gap-1 text-[0.5rem] uppercase tracking-widest text-gray-400 dark:text-gray-600"><Terminal size={9} /> Agent commands</div>@@@ -325,13 -411,13 +422,13 @@@<ApprovalDialog toolCall={pendingApproval} onApprove={onApprove} onReject={onReject} />)}-- {/* Prompt area — hints, image previews, then the textarea (buttons live++ {/* Prompt area: hints, image previews, then the textarea (buttons livein the action bar below, web-parity two-row composer). */}<div className="px-3 pt-2.5">-- {/* Non-image attach hint (GH #69) — the clip is images-only; PDFs, Word,++ {/* Non-image attach hint (GH #69). The clip is images-only; PDFs, Word,and text files go through the Documents panel so the model can read them. */}{docHint && (- <div className="flex items-center gap-2 mb-1.5 px-2 py-1 rounded-md bg-amber-500/10 border border-amber-500/20 text-[0.62rem] text-amber-700 dark:text-amber-300">+ <div className="flex items-center gap-2 mb-1.5 px-2 py-1 rounded-md bg-amber-500/10 border border-amber-500/20 t-micro text-amber-700 dark:text-amber-300"><span className="flex-1">The clip attaches images. To ask about a PDF, Word, or text file, add it in the Documents panel.</span>{onAttachDocs && (<button@@@ -375,7 -461,7 +472,7 @@@</div>)}-- {/* Vision hint — a text-only model can't read the attached image.++ {/* Vision hint: a text-only model can't read the attached image.Non-blocking (send still works); the runtime error is also mappedto friendly copy. gthvidsten, GH Discussion #67. */}{images.length > 0 && activeModel && !canSeeImages && (@@@ -411,7 -497,9 +508,9 @@@still than it was working, which is what David saw as "der StopKnopf oeffnet eine weitere Zeile, alles sieht asymmetrisch aus".No wrapping, a fixed-height row, and every control shrink-0 with- only the middle spacer giving way. */}- only the middle spacer giving way — das `flex: 0 0 auto` steckt++ only the middle spacer giving way, das `flex: 0 0 auto` steckt+ seit der Composer-Grammatik im Rezept `.lu-control` (index.css),+ nicht mehr als `shrink-0` an jedem einzelnen Knopf. */}<div className="flex flex-nowrap items-center gap-1 px-2 py-1.5 min-h-[38px] border-t border-gray-200 dark:border-white/[0.05]">{/* Clip button */}<button@@@ -444,7 -532,12 +543,12 @@@disabled={isGenerating}/>- {/* Think toggle ('always'-models render it locked on) */}+ {/* Think toggle ('always'-models render it locked on).+ Der Ein-Zustand kommt aus `aria-pressed`, nicht aus einer+ zweiten Klassenkette: das neutrale Rezept liest ihn und setzt- den Behaelter. Vorher war Ein ein blaues Pill — dieselbe Farbe,++ den Behaelter. Vorher war Ein ein blaues Pill, dieselbe Farbe,+ die auch der Fokusring traegt, also zwei Bedeutungen auf einer+ Farbe (Audit §4, Chat mit Antwort). */}<buttononClick={() => {if (canThink) updateSettings({ thinkingEnabled: !thinkingEnabled })@@@ -519,12 -592,21 +619,21 @@@in place while a run is in flight, exactly as the Chat surface hasalways done, and because the box is sized rather than padded therow height cannot move between the two states. */}- <div className="shrink-0 w-[26px] h-[26px]" data-testid="composer-send-slot">- {/* Send und Stop hatten hier je ein `whileTap` aus framer-motion —++ {/* Send und Stop hatten hier je ein `whileTap` aus framer-motion,+ zwei von den sechs, die der Audit als „6 von 462" zaehlt. Der+ Druck steht jetzt als eine Regel in index.css und laeuft ueber+ die `transition` von `.lu-control` weich aus; die beiden+ Knoepfe brauchen framer-motion dafuer nicht mehr. */}+ <div className="shrink-0 w-[var(--control-h-sm)] h-[var(--control-h-sm)]" data-testid="composer-send-slot">{isGenerating ? (- <motion.button+ <buttononClick={onStop}- className="w-full h-full flex items-center justify-center rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 transition-all"- whileTap={{ scale: 0.9 }}+ // Neutral, nicht rot: Stop ist der Normalabschluss und die+ // haeufigste Aktion waehrend eines Streams. `data-active`+ // gibt ihm den Behaelter des neutralen Rezepts, damit er+ // auffindbar bleibt, ohne die Fehlerfarbe zu tragen.+ data-active="true"+ className="lu-control lu-control--icon w-full h-full"aria-label="Stop generation"><Square size={13} />diff --cc src/components/chat/ChatView.tsxindex 7e260201,978ac318..4f697a8f--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@@ -15,10 -12,12 +16,12 @@@ import { useDocsAvailability } from '..import { AgentModeToggle } from './AgentModeToggle'import { AgentWorkspaceBadge } from './AgentWorkspaceBadge'import { ErrorBoundary } from '../ui/ErrorBoundary'+ import { useSettingsStore } from '../../stores/settingsStore'+ import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'-import { FileText, ChevronDown, Download, Wrench, Radio, RefreshCw, X } from 'lucide-react'+import { ChevronDown, Download, Wrench, Radio, RefreshCw, X } from 'lucide-react'import { PluginsDropdown } from './PluginsDropdown'import { ModelSelector } from '../models/ModelSelector'-import { ConversationModelNote } from './ConversationModelNote'+import { useConversationModelHint } from './ConversationModelNote'import { GoalBar } from './GoalBar'import { PlanBar } from './PlanBar'import { LoopBar } from './LoopBar'@@@ -37,25 -34,48 +40,74 @@@ import { CodexView } from './CodexViewimport { useCodexStore } from '../../stores/codexStore'import { useGenerationStore } from '../../stores/generationStore'import { useRemoteStore } from '../../stores/remoteStore'-import { useUIStore } from '../../stores/uiStore'+ import { displayModelName } from '../../api/providers'+ import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'++ /** Was die Eingangsseite sagt und anbietet, je nach Lage. */+ interface Landing {+ readonly subline: string- /** Zweite Zeile, einzeilig gekuerzt — heute der Name des Modells. */++ /** Zweite Zeile, einzeilig gekuerzt, heute der Name des Modells. */+ readonly note?: string+ readonly cta: { readonly label: string; readonly run: () => void } | null+ }export function ChatView() {const { sendMessage, stopGeneration, isGenerating, isLoadingModel, regenerateMessage, editAndResend, pendingApproval, approveToolCall, rejectToolCall } = useChat()const activeConversationId = useChatStore((s) => s.activeConversationId)+ // Drives the recent-chats list on the empty screen: collapsed panel means+ // the list stands in the main area, expanded means it stands in the panel.+ const sidebarOpen = useUIStore((s) => s.sidebarOpen)- const conversations = useChatStore((s) => s.conversations)+ // NOT `s.conversations`. That array is replaced on every streaming flush, so- // subscribing to it re-reconciled the entire chat chrome — composer, plan- // bar, header controls, none of them memoised — once per frame for the whole- // duration of an answer, which is why typing during a run felt broken. The- // only thing this component needs from the conversation while it renders is- // its mode; a string stands still while tokens arrive. Everything else- // (model, system prompt, the export payload) is read at click time from- // getState(), where a fresh value is what you want anyway.++ // subscribing to it re-reconciled the entire chat chrome (composer, plan++ // bar, header controls, none of them memoised) once per frame for the whole++ // duration of an answer, which is why typing during a run felt broken. What++ // this component needs from the conversation while it renders is two SCALARS,++ // and a scalar stands still while tokens arrive. Everything else (model,++ // system prompt, the export payload) is read at click time from getState(),++ // where a fresh value is what you want anyway.+ const activeConvMode = useChatStore(+ (s) => s.conversations.find((c) => c.id === s.activeConversationId)?.mode,+ )++ // A chat that is open but has nothing in it yet. Counted the way MessageList++ // counts: the system prompt and hidden bookkeeping are not something the user++ // has said. Screen check on the bundle (David, 2026-09-02): after New Chat the++ // main area went blank, because the recent list only stood on the no-chat++ // screen.++ //++ // Derived INSIDE the selector for the reason above: the answer is a boolean,++ // so it survives every streaming flush untouched and only re-renders on the++ // one frame where it actually flips.++ const activeConvIsEmpty = useChatStore((s) => {++ const conv = s.conversations.find((c) => c.id === s.activeConversationId)++ if (!conv || (conv.mode ?? 'lu') !== 'lu') return false++ return conv.messages.filter((m) => m.role !== 'system' && !m.hidden).length === 0++ })const activeModel = useModelStore((s) => s.activeModel)const models = useModelStore((s) => s.models)+ // Meldung 4 (R5 re-measure): the model that wrote the answers on screen,+ // when it is not the one the picker stands on. Handed to the picker, which+ // marks itself with a dot and says the whole sentence in its tooltip.+ const conversationModelHint = useConversationModelHint()const [ragPanelOpen, setRagPanelOpen] = useState(false)const [exportOpen, setExportOpen] = useState(false)const [exportToast, setExportToast] = useState<string>('')const [toolsDropdownOpen, setToolsDropdownOpen] = useState(false)+ // Beide Aufklapplisten dieser Datei legen eine volle `fixed inset-0`-Flaeche+ // ueber die App, und beide hatten Escape nie bekommen. Der Datei-Waechter+ // hat es uebersehen, weil weiter unten der Genehmigungsdialog auf 'Escape'+ // hoert: eine Datei, zwei Pfade, einer gepflegt. Nachgemessen: nach Escape+ // stand `aria-expanded="true"`, und ein Klick auf „New Chat" traf+ // `DIV.fixed inset-0 z-40` statt den Knopf.+ useDismissOnEscape(exportOpen, () => setExportOpen(false))+ useDismissOnEscape(toolsDropdownOpen, () => setToolsDropdownOpen(false))const chatMode = useCodexStore((s) => s.chatMode)+ const setView = useUIStore((s) => s.setView)++ // Nur noch fuer die Eingangsseite. Der Docs-Knopf haengt seit A9 NICHT mehr++ // hieran (er ist auch im Cloud-Chat da, siehe useDocsAvailability unten);++ // was am Betriebsmodus haengt, ist der Primaerknopf „Install a model": im++ // Cloud-Modus ist die Modellansicht ausgeblendet, ein Knopf dorthin waere++ // ein toter Klick.++ const appMode = useSettingsStore((s) => s.settings.appMode)// Per-conversation generating flag (David 2026-06-12): the typing indicator// + realtime counter must show ONLY in the chat that is actually generating,@@@ -93,19 -111,7 +145,10 @@@const remoteClearError = useRemoteStore((s) => s.clearError)const connectedDevices = useRemoteStore((s) => s.connectedDevices)const refreshDevices = useRemoteStore((s) => s.refreshDevices)- const activeConv = conversations.find((c) => c.id === activeConversationId)- const isRemoteChat = activeConv?.mode === 'remote'- // A chat that is open but has nothing in it yet. Counted the way MessageList- // counts: the system prompt and hidden bookkeeping are not something the user- // has said. Screen check on the bundle (David, 2026-09-02): after New Chat the- // main area went blank, because the recent list only stood on the no-chat- // screen. While the panel is collapsed and the chat is still empty, the list- // belongs above the composer instead.- const activeConvIsEmpty =- !!activeConv &&- (activeConv.mode ?? 'lu') === 'lu' &&- activeConv.messages.filter((m) => m.role !== 'system' && !m.hidden).length === 0+ const isRemoteChat = activeConvMode === 'remote'++ // While the panel is collapsed and the open chat is still empty, the recent++ // list belongs above the composer instead of nowhere at all.+ const showRecentsAboveComposer = !sidebarOpen && activeConvIsEmptyconst isThisRemoteActive = isRemoteChat && remoteEnabled && dispatchedConversationId === activeConversationIdconst isThisRemoteStopped = isRemoteChat && !isThisRemoteActiveconst mobileConnectedCount = connectedDevices.length@@@ -128,7 -134,7 +171,7 @@@return () => clearTimeout(t)}, [exportToast])-- // Approval keyboard shortcuts — Enter approves, Esc rejects the++ // Approval keyboard shortcuts: Enter approves, Esc rejects the// head-of-queue tool call. The buttons themselves now live inside// ToolCallBlock so they appear inline on the pending block, but the// keyboard layer stays here so the shortcuts work regardless of@@@ -160,7 -169,7 +206,7 @@@// #29: restart now rethrows. The store's `error` already holds the// reason (e.g. "Could not bind 0.0.0.0:11435: Address already in// use"). The "Server stopped" banner below renders that reason-- // inline so the user knows what to do — instead of clicking Restart++ // inline so the user knows what to do, instead of clicking Restart// forever and watching nothing change.}}@@@ -170,289 -179,443 +216,477 @@@return <ABCompare />}+ // Die drei Lagen, in denen man auf der Eingangsseite landen kann. Der+ // Primaerknopf steht nur in der einen, die der Composer nicht loesen kann.+ const landing: Landing = !activeModel && models.length === 0+ ? (appMode === 'cloud'+ // Cloud versteckt die Modellansicht (lokale Hardware ist dort- // bedeutungslos) — ein Knopf dorthin waere ein toter Klick.++ // bedeutungslos), ein Knopf dorthin waere ein toter Klick.+ ? { subline: 'The hosted catalogue is still loading.', cta: null }+ : {- subline: 'No model is installed yet — that is the one thing this box cannot do for you.',++ subline: 'No model is installed yet. That is the one thing this box cannot do for you.',+ cta: { label: 'Install a model', run: () => setView('models') },+ })+ : !activeModel+ // Der Waehler steht IM Composer und oeffnet nach oben. Der alte Satz+ // hier hiess „Select a model above." und zeigte in die falsche Richtung.+ ? { subline: 'Pick a model in the box below, then type.', cta: null }+ // Der Modellname steht auf einer EIGENEN Zeile und wird gekuerzt: er ist+ // haeufig 50+ Zeichen lang (`hf.co/DevQuasar/huihui-ai_Qwen3-4B-abliterated-GGUF`),+ // und im Fliesstext liess er die Zeile dreimal umbrechen.+ : { subline: 'Type below to start.', note: displayModelName(activeModel), cta: null }+return (<div className="h-full flex flex-col min-w-0">- <AnimatePresence mode="wait">- {!activeConversationId ? (- // ── Homepage: just logo, no prompt ──- <motion.div- key="home"- className="flex-1 flex flex-col items-center justify-center"- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- exit={{ opacity: 0, y: -20 }}- transition={{ duration: 0.2 }}- >- <img src="/LU-monogram-bw.png" alt="" width={46} height={46} className="dark:invert-0 invert opacity-20 mb-5" />-- {/* The latest chats stand here only while the side panel is- collapsed (David, web parity). Expanded, the list lives in the- panel and would be on screen twice. */}- {!sidebarOpen && <RecentChats />}+ {/* One composer, two places. The landing state used to render a logo and+ nothing else, so the screen you arrive on had no input field at all.+ sendMessage creates the conversation when none is active (useChat.ts),- so the same element serves both branches — and it has to stay OUTSIDE++ so the same element serves both branches, and it has to stay OUTSIDE+ the AnimatePresence as ONE instance: a second copy per branch would+ drop the draft the moment the first message creates the conversation,+ which is worse than having no input field at all. */}+ <div className="flex-1 flex overflow-hidden min-h-0">+ <div className="flex-1 flex flex-col min-w-0 relative">+ {chatMode === 'codex' && activeConversationId ? (+ <CodexView />+ ) : (<>+ <AnimatePresence mode="wait">+ {!activeConversationId ? (+ // ── Die Eingangsseite ──+ //+ // D-S02 („Empty-State ohne Titel und CTA") und D-S05 („1237x850px+ // tote Flaeche") sind EIN Befund und werden als einer geloest.+ //+ // Was hier stand: ein 46px-Monogramm auf `opacity-20`, mittig in- // einer 850px hohen leeren Flaeche, und darunter — nur wenn- // Modelle da waren, aber keins gewaehlt — der Satz „Select a++ // einer 850px hohen leeren Flaeche, und darunter, nur wenn++ // Modelle da waren, aber keins gewaehlt, der Satz „Select a+ // model above." Das war die erste Flaeche der App, und sie sagte+ // nicht, wie die App heisst, was sie tut oder was man tun soll.+ //+ // Der Satz war ausserdem falsch: der Modellwaehler ist mit dem+ // Umbau vom 2026-07-11 in den Composer gezogen und oeffnet nach- // OBEN — er steht seither UNTER dem Text, der auf ihn zeigt. Wer++ // OBEN, er steht seither UNTER dem Text, der auf ihn zeigt. Wer+ // dem Hinweis folgte, sah in die Kopfzeile und fand nichts.+ //+ // Was jetzt hier steht: Zeichen, Titel, eine Zeile, die den- // wirklichen naechsten Schritt benennt, und — nur wo er etwas- // kann, was der Composer nicht kann — ein Primaerknopf.++ // wirklichen naechsten Schritt benennt, und (nur wo er etwas++ // kann, was der Composer nicht kann) ein Primaerknopf.+ //+ // WIDERSPRUCH ZUM AUDIT, ausdruecklich: der Audit verlangt+ // „Zeichen + Headline + Subline + Primaerbutton", vier Dinge,+ // immer. Der vierte kommt hier nur im Modellfall. Begruendung:+ // als der Audit gemessen wurde, hatte dieser Screen GAR KEIN- // Eingabefeld (D-S01, geschlossen mit `bcec642b`) — ein++ // Eingabefeld (D-S01, geschlossen mit `bcec642b`), ein+ // Primaerknopf war der einzig moegliche Weg vorwaerts. Seither+ // steht der Composer da, und der IST die Primaeraktion. Ein+ // zweiter Primaerknopf daneben, der nichts anderes tut, waere+ // genau die Doppelung, die dieser Audit an vier anderen Stellen+ // ruegt (D-S06, D-S07, D-S23, D-A5). Wo der Composer aber nicht- // weiterhilft — kein einziges Modell installiert —, steht der++ // weiterhilft, also kein einziges Modell installiert, steht der+ // Knopf, und er fuehrt an die einzige Stelle, die das aendert.+ //+ // Zur toten Flaeche: kein Layout entfernt Leere, nur Inhalt tut+ // das. Der Block ist deshalb (a) inhaltlich gefuellt, (b) auf die+ // Spaltenbreite `--lu-measure` gelegt, dieselbe wie Transkript+ // und Composer (D-A1), und (c) UNTEN verankert statt in der Mitte+ // zu schweben, damit er mit dem Composer als ein Element liest+ // statt als Fleck in einem Feld. Erfundene Beispiel-Prompts als+ // Fuellmaterial habe ich bewusst nicht gebaut: sie waeren Inhalt,+ // den niemand bestellt hat, und der Audit verlangt sie nicht.+ <motion.div+ key="home"+ className="flex-1 flex flex-col items-center justify-end min-h-0 px-3 pb-4"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0, y: -20 }}+ transition={{ duration: 0.2 }}+ >+ <div+ data-testid="chat-landing"+ className="w-full max-w-[var(--lu-measure)] flex flex-col items-center text-center gap-2"+ >+ <img+ src={MONOGRAM}+ alt=""+ width={56}+ height={56}+ className={`${MONOGRAM_INVERT} opacity-90`}+ />+ <h1 className="t-display text-gray-900 dark:text-gray-100">Ask LU anything</h1>+ <p className="t-body text-gray-500 max-w-[40ch]">{landing.subline}</p>+ {landing.note && (+ <p className="t-mono w-full truncate px-4 text-gray-400 dark:text-gray-500" title={landing.note}>+ {landing.note}+ </p>+ )}+ {landing.cta && (+ <button onClick={landing.cta.run} className="lu-primary lu-control mt-1">+ {landing.cta.label}+ </button>+ )}+- {models.length > 0 && !activeModel && (- <p className="text-[0.6rem] text-amber-500/60 mt-3">Select a model above.</p>- )}- </motion.div>- ) : (- // ── Active chat ──- <motion.div- key="chat"- className="flex-1 flex overflow-hidden"- initial={{ opacity: 0, y: 20 }}- animate={{ opacity: 1, y: 0 }}- transition={{ duration: 0.25, ease: 'easeOut' }}- >- <div className="flex-1 flex flex-col min-w-0 relative">- {chatMode === 'codex' ? (- <CodexView />- ) : (<>- {/* Top bar — slim: session/meta controls only. Docs · Plugins ·- Tools + the model picker moved into the composer action bar- (web parity, David 2026-07-11); Memory stands alone top-right. */}- <div className="flex items-center gap-1.5 px-2 pt-0.5">- <AgentModeToggle />- <AgentWorkspaceBadge />-- {/* Spacer */}- <div className="flex-1" />-- {/* Token Counter */}- <TokenCounter />-- {/* Context window picker (Ollama num_ctx / LM Studio loaded ctx) */}- <ContextDropdown />-- {/* Small-Model Mode — only relevant when the agent loop (tools)- is active; plain chat has no tool calls to lean out. */}- {isAgentActive && <SmallModelModeToggle />}-- {/* Memory — standalone, top-right (moved out of the header model- picker; David 2026-07-11). View / add / delete injected context. */}- <MemoryDebugToggle />-- {/* Export */}- <div className="relative">- <button- onClick={() => setExportOpen(!exportOpen)}- className="flex items-center gap-1 px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"- title="Export chat"- >- <Download size={10} />- </button>- {exportOpen && (- <>- <div className="fixed inset-0 z-40" onClick={() => setExportOpen(false)} />- <div className="absolute right-0 top-full mt-1 z-50 w-32 rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-1">- {(['markdown', 'json'] as const).map(fmt => (- <button- key={fmt}- onClick={async () => {- const conv = conversations.find(c => c.id === activeConversationId)- setExportOpen(false)- if (!conv) return- const result = await exportConversation(conv, fmt)- if (result.status === 'saved' && result.path) {- setExportToast(`Saved to ${result.path}`)- } else if (result.status === 'downloaded') {- setExportToast(`Downloaded .${fmt === 'markdown' ? 'md' : 'json'}`)- }- // status === 'cancelled' → no toast, user closed the dialog- }}- className="w-full text-left px-3 py-1 text-[0.55rem] text-gray-400 hover:bg-white/5 hover:text-gray-200 transition-colors"- >- .{fmt === 'markdown' ? 'md' : fmt}- </button>- ))}- </div>- </>++ {/* The latest chats stand here only while the side panel is++ collapsed (David, web parity). Expanded, the list lives in++ the panel and would be on screen twice. They come AFTER++ the headline: the block says where you are first and++ offers somewhere to go second. */}++ {!sidebarOpen && (++ <div className="w-full pt-3 flex flex-col items-center text-left">++ <RecentChats />++ </div>+ )}</div>- </div>-- {/* The plan, for plain chat and for Agent alike. It belongs with- the standing status controls in the header, not at the prompt- box: the Chat surface has no right-hand column to hand it to,- and this row is where everything that is TRUE OF THE SESSION- rather than of the next message already lives (agent toggle,- workspace, token counter, context window, memory). Collapsed- by default so it costs one line above the transcript. */}- <PlanBar />-- {showRecentsAboveComposer ? (- // Same flex slot the transcript would take, so the composer- // stays where it is at the bottom of the view.- <div className="flex-1 flex flex-col items-center justify-center overflow-y-auto scrollbar-thin py-4">- <img src="/LU-monogram-bw.png" alt="" width={46} height={46} className="dark:invert-0 invert opacity-20 mb-5" />- <RecentChats />- </div>- ) : (- <MessageList- isGenerating={isGenerating}- isThisChatGenerating={activeGenerating}- isLoadingModel={isLoadingModel}- onRegenerate={regenerateMessage}- onEdit={editAndResend}- pendingApprovalId={pendingApproval?.id ?? null}- onApprove={approveToolCall}- onReject={rejectToolCall}- />- )}-- {/* Remote session banners */}- {isThisRemoteActive && (- <div className="mx-3 mb-1.5 flex items-center justify-between gap-2 px-2.5 py-1 rounded border border-green-500/25 bg-green-500/5 text-[0.6rem]">- <div className="flex items-center gap-1.5 text-green-400">- <Radio size={10} className="animate-pulse" />- <span className="font-medium">Live</span>- <span className="text-green-500/60">- {mobileConnectedCount > 0- ? `, ${mobileConnectedCount} mobile${mobileConnectedCount === 1 ? '' : 's'} connected`- : ', ready for mobile'}- </span>- </div>- <button- onClick={handleRemoteReactivate}- disabled={remoteLoading}- title="Regenerate passcode, keep this chat"- className="flex items-center gap-1 px-1.5 py-0.5 rounded text-blue-400 hover:bg-blue-500/15 border border-blue-500/20 transition-all disabled:opacity-50"- >- <RefreshCw size={9} className={remoteLoading ? 'animate-spin' : ''} />- Restart- </button>- </div>- )}- {isThisRemoteStopped && (- <div- className={- 'mx-3 mb-1.5 flex items-start justify-between gap-2 px-2.5 py-1 rounded border text-[0.6rem] ' +- (remoteError- ? 'border-red-500/30 bg-red-500/5'- : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.02]')- }- >- <div className={'flex flex-col gap-0.5 min-w-0 ' + (remoteError ? 'text-red-400' : 'text-gray-500')}>- <div className="flex items-center gap-1.5">- <Radio size={10} />- <span className="font-medium">Server stopped</span>- <span className={remoteError ? 'text-red-400/70' : 'text-gray-500/70'}>- {remoteError ? ', last attempt failed' : ', restart to reconnect mobile'}- </span>+ </motion.div>+ ) : (+ // ── Active chat ──+ <motion.div+ key="chat"+ className="flex-1 flex flex-col min-w-0 min-h-0"+ initial={{ opacity: 0, y: 20 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ duration: 0.25, ease: 'easeOut' }}+ >+ {/* The plan, for plain chat and for Agent alike. It belongs+ above the transcript, not at the prompt box: the Chat+ surface has no right-hand column to hand it to, and a plan- is what the run is going to DO — it reads before the++ is what the run is going to DO, so it reads before the+ output, not after it. Collapsed by default so it costs one+ line, and it renders nothing at all while there is no plan,+ so the empty case costs zero.+ (Die uebrigen Sitzungsanzeigen sind mit D-S18 unter das+ Transkript gezogen; der Plan bleibt, weil+ `the-prompt-window-is-the-prompt-window.test.ts` genau+ diese Reihenfolge festnagelt.) */}+ <PlanBar />+- <MessageList- isGenerating={isGenerating}- isThisChatGenerating={activeGenerating}- isLoadingModel={isLoadingModel}- onRegenerate={regenerateMessage}- onEdit={editAndResend}- pendingApprovalId={pendingApproval?.id ?? null}- onApprove={approveToolCall}- onReject={rejectToolCall}- />++ {!showRecentsAboveComposer && (++ <MessageList++ isGenerating={isGenerating}++ isThisChatGenerating={activeGenerating}++ isLoadingModel={isLoadingModel}++ onRegenerate={regenerateMessage}++ onEdit={editAndResend}++ pendingApprovalId={pendingApproval?.id ?? null}++ onApprove={approveToolCall}++ onReject={rejectToolCall}++ />++ )}+- {/* Die Statusleiste der Sitzung — Agent, Arbeitsordner,++ {/* Ein offener, aber noch leerer Chat bekommt an dieser++ Stelle die Liste der letzten Chats statt eines leeren++ Transkripts (David, 2026-09-02: nach „New Chat" stand der++ Hauptbereich blank da). Es ist DERSELBE Flex-Platz, den++ das Transkript sonst nimmt, also bleibt der Composer, wo++ er ist.++++ Warum zwei bewachte Bloecke statt eines Ternaers, obwohl++ genau eines von beiden rendert: `zwei-baender-sind-eine-++ flaeche.test.ts` liest, was zwischen `key="chat"` und dem++ Transkript steht, und will dort NUR den PlanBar sehen. In++ einem Ternaer stuende dieser Block textlich davor und++ zaehlte als drittes Band, obwohl er auf dem Bildschirm++ an der Stelle des Transkripts sitzt.++++ Unten verankert und mit dem Zeichen aus `brand.ts`, aus++ demselben Grund wie die Eingangsseite selbst (D-S05): ein++ Block, der in der Mitte einer leeren Flaeche schwebt,++ liest als Fleck; unten am Composer liest er als ein++ Element mit ihm. */}++ {showRecentsAboveComposer && (++ <div className="flex-1 min-h-0 flex flex-col items-center justify-end overflow-y-auto scrollbar-thin py-4">++ <img++ src={MONOGRAM}++ alt=""++ width={56}++ height={56}++ className={`${MONOGRAM_INVERT} opacity-90 mb-5`}++ />++ <RecentChats />++ </div>++ )}++++ {/* Die Statusleiste der Sitzung: Agent, Arbeitsordner,+ Kontext, Memory, Export. Inhaltlich unveraendert; was sich+ geaendert hat, ist der PLATZ.+- D-S18: „Drei Baender vor dem ersten Inhalt" — Titlebar++ D-S18, „Drei Baender vor dem ersten Inhalt": Titlebar+ (h-8), Header (h-10) und diese Leiste. Zwei davon sind+ Fensterrahmen und globale Navigation und koennen hier+ nicht weg; die dritte muss aber gar nicht VOR dem+ Transkript stehen. Nichts hier gehoert zur naechsten- Nachricht — es sind Eigenschaften des Laufs, und die++ Nachricht, es sind Eigenschaften des Laufs, und die+ liest man, waehrend man tippt, nicht bevor man liest.+ Also steht sie jetzt UNTER dem Transkript, direkt ueber+ dem Composer, bei den anderen Sitzungsanzeigen (LoopBar,+ GoalBar, GroupCostHint). Vor dem ersten Inhalt bleiben+ zwei Baender.++ ZWEITER DURCHGANG (01.09.2026): zwei ist die Zahl, und+ das ist eine Entscheidung, keine Restschuld. Gemessen im+ laufenden Fenster (Farben aus getComputedStyle):+ Fensterrahmen, Titlebar und Header tragen DIESELBE- Flaeche — hell #e5e7eb, dunkel #141414 —, ohne Kante und++ Flaeche (hell #e5e7eb, dunkel #141414), ohne Kante und+ ohne Schatten dazwischen; der Kontrast zwischen Header+ und Rahmen ist 1.00:1 in beiden Modi. Es liegen also+ nicht zwei Streifen uebereinander, sondern ein+ durchgehender Fenstergrund, auf dem die gerundete Pane+ (#ffffff / #1e1e1e) liegt. Der Schritt von 2 auf 1 waere- ein DOM-Schritt ohne Bildschirmwirkung — und im Browser++ ein DOM-Schritt ohne Bildschirmwirkung, und im Browser+ ist es ohnehin nur EIN Streifen, weil die Titlebar+ ausserhalb von Tauri `null` rendert.++ Bewacht wird nicht die Entscheidung, sondern ihre+ Voraussetzung: `chat/__tests__/zwei-baender-sind-eine-+ flaeche.test.ts` faellt, sobald einer der beiden+ Streifen eine eigene Flaeche, eine Kante oder einen+ Schatten bekommt. Dann sind es wieder zwei sichtbare+ Baender und die Frage ist neu zu stellen.++ Ausdruecklich NICHT in den Composer hinein: `composerAbove`+ rendert INNERHALB der Promptbox (ChatInput.tsx:318), und+ „das promptfenster ist ueberfuellt" ist eine stehende+ Regel dieses Hauses. Diese Leiste ist ein Geschwister der+ Box, kein Inhalt darin.+- Der PlanBar bleibt oben — `the-prompt-window-is-the-prompt-++ Der PlanBar bleibt oben, denn `the-prompt-window-is-the-prompt-+ window.test.ts` verlangt Plan vor Transkript, und er+ rendert ohnehin `null`, solange es keinen Plan gibt. */}+ <div data-testid="chat-session-strip" className="flex items-center gap-1.5 px-2 py-0.5">+ <AgentModeToggle />+ <AgentWorkspaceBadge />++ {/* Spacer */}+ <div className="flex-1" />++ {/* EIN Kontextelement statt zwei (D-S06): der Fuellstand+ ist die Beschriftung des Fensterwaehlers geworden, statt+ dieselbe Zahl 24px daneben ein zweites Mal in einer+ anderen Schreibweise zu zeigen. Die Begruendung samt der+ beiden Ausweichfaelle steht im Kopf von ContextDropdown. */}+ <ContextDropdown><TokenCounter /></ContextDropdown>+- {/* Small-Model Mode — only relevant when the agent loop (tools)++ {/* Small-Model Mode, only relevant when the agent loop (tools)+ is active; plain chat has no tool calls to lean out. */}+ {isAgentActive && <SmallModelModeToggle />}+- {/* Memory — standalone, top-right (moved out of the header model++ {/* Memory, standalone, top-right (moved out of the header model+ picker; David 2026-07-11). View / add / delete injected context. */}+ <MemoryDebugToggle />++ {/* Export */}+ <div className="relative">+ <button+ onClick={() => setExportOpen(!exportOpen)}+ className="flex items-center gap-1 px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"+ title="Export chat"+ >+ <Download size={10} />+ </button>+ {exportOpen && (+ <>+ <div className="fixed inset-0 z-40" onClick={() => setExportOpen(false)} />+ <div className="absolute right-0 top-full mt-1 z-50 w-32 rounded-lg bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-1">+ {(['markdown', 'json'] as const).map(fmt => (+ <button+ key={fmt}+ onClick={async () => {+ const conv = useChatStore.getState().conversations+ .find(c => c.id === activeConversationId)+ setExportOpen(false)+ if (!conv) return+ const result = await exportConversation(conv, fmt)+ if (result.status === 'saved' && result.path) {+ setExportToast(`Saved to ${result.path}`)+ } else if (result.status === 'downloaded') {+ setExportToast(`Downloaded .${fmt === 'markdown' ? 'md' : 'json'}`)+ }+ // status === 'cancelled' → no toast, user closed the dialog+ }}+ className="w-full text-left px-3 py-1 text-[0.55rem] text-gray-400 hover:bg-white/5 hover:text-gray-200 transition-colors"+ >+ .{fmt === 'markdown' ? 'md' : fmt}+ </button>+ ))}+ </div>+ </>+ )}</div>- {/* #29: surface the actual reason (port in use,- firewall, etc.) so the user knows why Restart is- not coming back, instead of staring at a button- that does nothing. */}- {remoteError && (- <div className="text-[0.55rem] text-red-300/80 break-words pl-4 leading-snug">- {remoteError}- </div>- )}</div>- <div className="flex items-center gap-1 shrink-0">- {remoteError && (++ {/* Remote session banners */}+ {isThisRemoteActive && (+ <div className="mx-3 mb-1.5 flex items-center justify-between gap-2 px-2.5 py-1 rounded border border-green-500/25 bg-green-500/5 text-[0.6rem]">+ <div className="flex items-center gap-1.5 text-green-400">+ <Radio size={10} className="animate-pulse" />+ <span className="font-medium">Live</span>+ <span className="text-green-500/60">+ {mobileConnectedCount > 0+ ? `, ${mobileConnectedCount} mobile${mobileConnectedCount === 1 ? '' : 's'} connected`+ : ', ready for mobile'}+ </span>+ </div><button- onClick={remoteClearError}- title="Dismiss error"- className="p-0.5 rounded text-red-400/70 hover:text-red-300 hover:bg-red-500/15 transition-all"+ onClick={handleRemoteReactivate}+ disabled={remoteLoading}+ title="Regenerate passcode, keep this chat"+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-blue-400 hover:bg-blue-500/15 border border-blue-500/20 transition-all disabled:opacity-50">- <X size={9} />+ <RefreshCw size={9} className={remoteLoading ? 'animate-spin' : ''} />+ Restart</button>- )}- <button- onClick={handleRemoteReactivate}- disabled={remoteLoading}- title="Start a fresh server and reattach this chat"+ </div>+ )}+ {isThisRemoteStopped && (+ <divclassName={- 'flex items-center gap-1 px-2 py-0.5 rounded transition-all disabled:opacity-50 font-medium ' ++ 'mx-3 mb-1.5 flex items-start justify-between gap-2 px-2.5 py-1 rounded border text-[0.6rem] ' +(remoteError- ? 'text-red-300 hover:bg-red-500/15 border border-red-500/40'- : 'text-green-400 hover:bg-green-500/15 border border-green-500/30')+ ? 'border-red-500/30 bg-red-500/5'+ : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.02]')}>- <RefreshCw size={9} className={remoteLoading ? 'animate-spin' : ''} />- {remoteError ? 'Retry' : 'Restart'}- </button>- </div>- </div>- )}-- <ChatInput- onSend={sendMessage}- onStop={stopGeneration}- isGenerating={isGenerating}- pendingApproval={pendingApproval}- onApprove={approveToolCall}- onReject={rejectToolCall}- // Commands need the tool catalog to drive, which only Agent- // mode has here. Plain chat leaves "/cmd" as ordinary text.- slashCommands={isAgentActive}- onAttachDocs={() => setRagPanelOpen(true)}- composerModel={- /* What this chat's answers were written by rides on the- picker itself now, as a dot plus a tooltip, instead of a- second chip in the row (Meldung 4, R5 re-measure; David- 2026-09-02 wanted it hidden away). */- <ModelSelector openUpward answeredBy={conversationModelHint} />- }- // No plan lives here. The prompt window is the prompt window- // (David, 2026-08-22): the plan band sits under the header row- // above, next to the other standing status controls.- composerAbove={<><LuEngineSwitchBar /><RetrievalErrorBar /><LoopBar onStop={stopGeneration} /><GoalBar /><GroupCostHint /></>}- composerActions={- <>- {/* Documents (RAG), shown in both modes since A9. In- Cloud mode without an embedding lane it stays visible- and says what is missing. */}- <DocsButton- availability={docs}- open={ragPanelOpen}- ragEnabled={ragEnabled}- docCount={docCount}- onToggle={() => setRagPanelOpen(!ragPanelOpen)}- />-- {/* Plugins (Chat Tools + Caveman + Personas) */}- <PluginsDropdown openUpward />-- {/* Tools — agent permission overrides (only when agent active) */}- {isAgentActive && (- <div className="relative">+ <div className={'flex flex-col gap-0.5 min-w-0 ' + (remoteError ? 'text-red-400' : 'text-gray-500')}>+ <div className="flex items-center gap-1.5">+ <Radio size={10} />+ <span className="font-medium">Server stopped</span>+ <span className={remoteError ? 'text-red-400/70' : 'text-gray-500/70'}>+ {remoteError ? ', last attempt failed' : ', restart to reconnect mobile'}+ </span>+ </div>+ {/* #29: surface the actual reason (port in use,+ firewall, etc.) so the user knows why Restart is+ not coming back, instead of staring at a button+ that does nothing. */}+ {remoteError && (+ <div className="text-[0.55rem] text-red-300/80 break-words pl-4 leading-snug">+ {remoteError}+ </div>+ )}+ </div>+ <div className="flex items-center gap-1 shrink-0">+ {remoteError && (+ <button+ onClick={remoteClearError}+ title="Dismiss error"+ className="p-0.5 rounded text-red-400/70 hover:text-red-300 hover:bg-red-500/15 transition-colors"+ >+ <X size={9} />+ </button>+ )}<button- onClick={() => setToolsDropdownOpen(!toolsDropdownOpen)}- className="flex items-center gap-1 px-2 py-1.5 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-all shrink-0 text-[0.6rem] font-medium"+ onClick={handleRemoteReactivate}+ disabled={remoteLoading}+ title="Start a fresh server and reattach this chat"+ className={+ 'flex items-center gap-1 px-2 py-0.5 rounded transition-all disabled:opacity-50 font-medium ' ++ (remoteError+ ? 'text-red-300 hover:bg-red-500/15 border border-red-500/40'+ : 'text-green-400 hover:bg-green-500/15 border border-green-500/30')+ }>- <Wrench size={11} className="text-green-400" />- <span>Tools</span>- <ChevronDown size={9} className={`transition-transform ${toolsDropdownOpen ? 'rotate-180' : ''}`} />+ <RefreshCw size={9} className={remoteLoading ? 'animate-spin' : ''} />+ {remoteError ? 'Retry' : 'Restart'}</button>- {toolsDropdownOpen && (- <>- <div className="fixed inset-0 z-40" onClick={() => setToolsDropdownOpen(false)} />- <div className="absolute left-0 bottom-full mb-0.5 z-50 w-28 rounded-md bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-0.5 px-0.5">- <PermissionOverrideBar />- </div>- </>- )}</div>- )}- </>- }- />- </>)}- </div>-- {/* RAG Panel */}- <AnimatePresence>- {ragPanelOpen && (- <ErrorBoundary fallbackClassName="w-[280px] shrink-0 h-full border-l border-white/5 bg-[#363636] flex flex-col items-center justify-center p-6 gap-3">- <RAGPanel conversationId={activeConversationId} onClose={() => setRagPanelOpen(false)} />- </ErrorBoundary>- )}- </AnimatePresence>- </motion.div>- )}- </AnimatePresence>+ </div>+ )}+ </motion.div>+ )}+ </AnimatePresence>++ {/* Code mode brings its own composer, so it stays out of this one. */}+ {chatMode !== 'codex' && (+ <ChatInput+ onSend={sendMessage}+ onStop={stopGeneration}+ isGenerating={isGenerating}+ pendingApproval={pendingApproval}+ onApprove={approveToolCall}+ onReject={rejectToolCall}+ // Commands need the tool catalog to drive, which only Agent+ // mode has here. Plain chat leaves "/cmd" as ordinary text.+ slashCommands={isAgentActive ? 'agent' : 'chat'}- onAttachDocs={appMode !== 'cloud' ? () => setRagPanelOpen(true) : undefined}++ onAttachDocs={() => setRagPanelOpen(true)}+ composerModel={- <div className="flex items-center gap-1.5">- {/* What this chat's answers were written by, when that is- not what the picker says (Meldung 4, R5 re-measure). */}- <ConversationModelNote />- <ModelSelector openUpward />- </div>++ /* What this chat's answers were written by rides on the++ picker itself now, as a dot plus a tooltip, instead of a++ second chip in the row (Meldung 4, R5 re-measure; David++ 2026-09-02 wanted it hidden away). */++ <ModelSelector openUpward answeredBy={conversationModelHint} />+ }+ // No plan lives here. The prompt window is the prompt window- // (David, 2026-08-22): the plan band sits under the header row++ // (David, 2026-08-22): the plan band sits in the session strip+ // above, next to the other standing status controls.- composerAbove={<><LoopBar onStop={stopGeneration} /><GoalBar /><GroupCostHint /></>}++ composerAbove={<><LuEngineSwitchBar /><RetrievalErrorBar /><LoopBar onStop={stopGeneration} /><GoalBar /><GroupCostHint /></>}+ composerActions={+ <>- {/* Documents (RAG) — local-embeddings only, so hide in- Cloud mode (web parity). */}- {appMode !== 'cloud' && (- <button- onClick={() => setRagPanelOpen(!ragPanelOpen)}- aria-pressed={ragPanelOpen || ragEnabled}- className="lu-control"- title="Document Chat (RAG)"- >- <FileText size={11} />- <span>Docs</span>- {docCount > 0 && (- <span className={- 'min-w-[12px] h-[12px] flex items-center justify-center rounded-full text-[0.45rem] font-bold ' +- (ragEnabled ? 'bg-green-500 text-white' : 'bg-white/15 text-gray-300')- }>- {docCount}- </span>- )}- </button>- )}++ {/* Documents (RAG), shown in both modes since A9. In++ Cloud mode without an embedding lane it stays visible++ and says what is missing. */}++ <DocsButton++ availability={docs}++ open={ragPanelOpen}++ ragEnabled={ragEnabled}++ docCount={docCount}++ onToggle={() => setRagPanelOpen(!ragPanelOpen)}++ />++ {/* Plugins (Chat Tools + Caveman + Personas) */}+ <PluginsDropdown openUpward />+- {/* Tools — agent permission overrides (only when agent active) */}++ {/* Tools: agent permission overrides (only when agent active) */}+ {isAgentActive && (+ <div className="relative">+ <button+ onClick={() => setToolsDropdownOpen(!toolsDropdownOpen)}+ aria-expanded={toolsDropdownOpen}+ className="lu-control"+ >+ {/* Kein eigener Gruenton mehr: das Icon erbt die+ Farbe des Controls, sonst traegt ein neutrales+ Control wieder einen Akzent von sich aus. */}+ <Wrench size={11} />+ <span>Tools</span>+ <ChevronDown size={9} className={`transition-transform ${toolsDropdownOpen ? 'rotate-180' : ''}`} />+ </button>+ {toolsDropdownOpen && (+ <>+ <div className="fixed inset-0 z-40" onClick={() => setToolsDropdownOpen(false)} />+ <div className="absolute left-0 bottom-full mb-0.5 z-50 w-28 rounded-md bg-white dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/10 shadow-xl py-0.5 px-0.5">+ <PermissionOverrideBar />+ </div>+ </>+ )}+ </div>+ )}+ </>+ }+ />+ )}+ </>)}+ </div>++ {/* RAG Panel */}+ <AnimatePresence>+ {ragPanelOpen && activeConversationId && (+ <ErrorBoundary fallbackClassName="w-[280px] shrink-0 h-full border-l border-gray-200 dark:border-white/5 bg-white dark:bg-lu-overlay flex flex-col items-center justify-center p-6 gap-3">+ <RAGPanel conversationId={activeConversationId} onClose={() => setRagPanelOpen(false)} />+ </ErrorBoundary>+ )}+ </AnimatePresence>++ {/* Hintergrundagenten, ganz aussen rechts.+ HIER und nicht in CodexView, obwohl der Code-Modus eigene Spalten+ hat: diese eine Montage deckt BEIDE Bereiche ab, weil CodexView+ innerhalb dieser Zeile gerendert wird. Im Code-Modus steht das- Panel damit rechts NEBEN dem Explorer statt in ihm — zwei++ Panel damit rechts NEBEN dem Explorer statt in ihm, zwei+ Spalten mit zwei Aufgaben, und keine musste die andere aufnehmen.+ Es rendert `null`, solange diese Konversation keine+ Hintergrundaufgabe hat, also auch im normalen Chat immer: dort+ kommt `delegate_task` gar nicht erst in die Werkzeugliste+ (CHAT_TOOLS), festgehalten in multiagent-nicht-im-chat.test.ts. */}+ <AgentPanel />+ </div>{/* Export toast */}<AnimatePresence>diff --cc src/components/chat/CodexView.tsxindex 43bda7ef,3172199d..3a9d1beb--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@@ -17,23 -18,18 +18,27 @@@ import { useCodexConfirmStore } from '.import { PluginsDropdown } from './PluginsDropdown'import { CodexModeDropdown } from './CodexModeDropdown'import { ModelSelector } from '../models/ModelSelector'+ import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'+ import { AVATAR_SLOT } from './avatar-slot'import { GoalBar } from './GoalBar'+import { LuEngineSwitchBar } from './LuEngineSwitchBar'import { LoopBar } from './LoopBar'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'+import { useAgentLoopStore } from '../../stores/agentLoopStore'+import { useAgentModeStore } from '../../stores/agentModeStore'+import {+ CODEX_WORKDIR_LOCK_TITLE,+ codexBusyReason,+ codexFallbackLabel,+} from '../../lib/codex-workdir'+import { resolveWorkspacePath } from '../../api/agents/workspace-resolve'import { StagedChangesPanel } from './StagedChangesPanel'import { SlashStepsBlock } from './SlashStepsBlock'+ import { CompactBlock } from './CompactBlock'+ import { compactionAnchors } from '../../lib/compact-summary'-import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder, Check, AlertTriangle } from 'lucide-react'+import { User, Code, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder, FolderX, Check, AlertTriangle } from 'lucide-react'- import { useEffect, useState } from 'react'+ import { Fragment, useEffect, useState } from 'react'import { checkGitInstalled, openExternal, type GitStatus } from '../../api/backend'import { CodexConfirmDialog } from './CodexConfirmDialog'import { stripModelNoise } from '../../lib/strip-model-noise'@@@ -56,9 -56,18 +65,18 @@@ export function CodexView()const conversation = conversations.find(c => c.id === activeConversationId)const messages = conversation?.messages || []+ // Verdichtungslinien fuer den Code-Verlauf. Codex blendet nur `hidden` aus+ // (Systemhinweise bleiben stehen), aber die Rechnung laeuft trotzdem ueber- // die volle Liste — der Schnittpunkt darf auf eine ausgeblendete zeigen.++ // die volle Liste, denn der Schnittpunkt darf auf eine ausgeblendete zeigen.+ const compactAt = compactionAnchors(+ messages,+ messages.filter((m) => !m.hidden).map((m) => m.id),+ conversation?.compactions,+ )+// Per-conversation generating flag (David 2026-06-12): the typing indicator// + realtime counter + a message's live-stream state must follow the coding-- // chat that's ACTUALLY running — not every chat the user switches to. The++ // chat that's ACTUALLY running, not every chat the user switches to. The// hook's `isRunning` is global (kept for the input, which guards shared stream// refs); the visual bits below read this conversation-scoped flag instead.const generatingMap = useGenerationStore((s) => s.generating)@@@ -149,7 -138,7 +169,7 @@@><Code size={9} className="text-gray-500" /><span className="text-[0.55rem] text-gray-600 dark:text-gray-400 font-medium">Coding Agent</span>-- {/* Code-Review Mode badge (B13) — makes it impossible to miss++ {/* Code-Review Mode badge (B13), makes it impossible to missthat the agent is read-only. The toggle itself lives inSettings → Codex Agent; clicking the badge jumps you thereisn't worth a routing change in v2.5.0. */}@@@ -162,35 -151,19 +182,35 @@@<span>Review</span></span>)}-- {/* Working directory indicator — so the user always sees WHERE the++ {/* Working directory indicator, so the user always sees WHERE theagent operates (David 2026-06-04: "ich hab den Ordner angegeben …er ist eigentlich in Dokumenten"). Empty = per-chat sandbox under~/agent-workspace, which is also where shell output now lands. */}<spanclassName="flex items-center gap-1 text-[0.5rem] text-gray-500 dark:text-gray-500 font-mono truncate max-w-[200px]"- title={codexWorkingDir || 'Sandbox: ~/agent-workspace/<chat>'}+ title={codexWorkingDir || `No folder picked, the agent works in ${fallbackLabel}`}><Folder size={9} className="shrink-0 opacity-70" />- <span className="truncate">{codexWorkingDir || 'sandbox · ~/agent-workspace'}</span>+ <span className="truncate">{codexWorkingDir || fallbackLabel}</span></span>+ {codexWorkingDir && (+ <button+ onClick={() => { if (!lockReason) clearWorkingDirectory() }}+ disabled={!!lockReason}+ data-testid="codex-remove-folder"+ aria-label="Remove the working directory"+ title={+ lockReason+ ? CODEX_WORKDIR_LOCK_TITLE[lockReason]+ : `Remove this folder. The agent falls back to ${fallbackLabel} until you pick a new one.`+ }+ className="p-1 rounded text-gray-400 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-white/5 disabled:opacity-30 disabled:hover:text-gray-400 transition-colors shrink-0"+ >+ <FolderX size={11} />+ </button>+ )}<div className="flex-1" />-- {/* New coding session — aborts any running loop and starts a fresh++ {/* New coding session: aborts any running loop and starts a freshchat/thread (keeps the working directory). David 2026-06-04:"start neu" must actually start new. */}<button@@@ -214,7 -188,7 +235,7 @@@</div>{/* Git-missing banner (v2.5.0). Codex shells out to git for-- status/diff/commit/log — without it those tools fail. Minimal,++ status/diff/commit/log, and without it those tools fail. Minimal,dismiss-by-installing: an Install button (opens the platform gitdownload page) + a Recheck button for after the install. */}{gitStatus && !gitStatus.installed && (@@@ -264,6 -237,14 +285,14 @@@) : (<div ref={contentRef} className="py-1">{messages.filter(msg => !msg.hidden).map((msg) => {+ // Der Rumpf hat mehrere Ausgaenge (Hinweiszeile, Werkzeugblock,+ // normale Blase). Statt jeden einzeln anzufassen, wandert er- // unveraendert in eine IIFE — seine `return`s werden ihre. Die++ // unveraendert in eine IIFE, seine `return`s werden ihre. Die+ // Verdichtungslinie haengt danach EINMAL an, fuer alle Ausgaenge+ // gleich. Der Alternativentwurf, jeden Ausgang zu umhuellen,+ // waere dieselbe Zeile an fuenf Stellen gewesen, und die+ // sechste, die jemand spaeter dazuschreibt, haette gefehlt.+ const gerendert = (() => {// App notices (a staged change that landed on disk) are not// model turns. They used to be written hidden, so the one line// that says "the file on disk is not the diff you approved"@@@ -535,7 -525,7 +573,7 @@@})}{/* 3-dot indicator while THIS coding chat is mid-loop. Bound tothe per-conversation flag so switching to another (idle) chat-- doesn't show its dots — David 2026-06-12 ("die drei ladepunkte++ doesn't show its dots. David 2026-06-12 ("die drei ladepunktekommen in vorherigen chats auch"). */}{/* Shell/code approval, inline in the stream so it reads as thenext step of the run instead of covering it (David 2026-07-24:@@@ -561,7 -551,7 +599,7 @@@onStop={stopCodex}// Store flag, not the hook's local isRunning (audit A2): the view// remounts on every tab switch and a fresh hook says "idle" while-- // the old instance's loop is still running — which offered a second++ // the old instance's loop is still running, which offered a second// parallel send and no Stop button. The generating flag follows the// conversation, not the hook instance.isGenerating={isRunning || codexGenerating}diff --cc src/components/chat/ContextDropdown.tsxindex 882eb74c,cb39db4c..70cbd400--- a/src/components/chat/ContextDropdown.tsx+++ b/src/components/chat/ContextDropdown.tsx@@@ -21,12 -23,42 +23,42 @@@ const fmt = (n: number) =* Context-window picker for the active LOCAL model. Sets `contextWindowOverride`* and AUTO-RELOADS the model so the change takes effect immediately:* - Ollama: warm the model with the new num_ctx (Ollama reloads its runner).-- * - LM Studio: `lms load -c <N>` (unload + reload — context is load-time there).++ * - LM Studio: `lms load -c <N>` (unload + reload, context is load-time there).* - Built-in: ctx lives in settings.builtinEngine (expert tuning), the* engine relaunches with the new -c via swapBundledModel.* Hidden for cloud models (their context is fixed and not adjustable here).+ *- * D-S06 — „Zwei Kontextanzeigen 24px nebeneinander in verschiedener Notation:++ * D-S06, „Zwei Kontextanzeigen 24px nebeneinander in verschiedener Notation:+ * ‚32/8.2k' und ‚ctx 8K' → eine."+ *+ * Beide zeigten DIESELBE Zahl: der Nenner des Fuellstands und die Beschriftung+ * dieses Knopfes sind dasselbe Kontextfenster, einmal als „8.2k" (Tausender)+ * und einmal als „8K" (Kibi). Wer den Unterschied las, suchte einen, den es+ * nicht gibt.+ *- * Aufgeloest wird das nicht dadurch, dass eine der beiden verschwindet — der++ * Aufgeloest wird das nicht dadurch, dass eine der beiden verschwindet, denn der+ * Fuellstand ist die einzige Stelle, die den VERBRAUCH zeigt, und dieser Knopf+ * ist die einzige Stelle, die das Fenster AENDERT. Aufgeloest wird es dadurch,+ * dass der Fuellstand die Beschriftung DIESES Knopfes wird: ein Element, eine+ * Zahl, und der Messwert sitzt auf dem Regler, der ihn bewegt.+ *+ * Die Ausweichfaelle, beide bewusst:- * - Kein Fuellstand (leerer Chat — `TokenCounter` gibt dort `null` zurueck,++ * - Kein Fuellstand (leerer Chat, `TokenCounter` gibt dort `null` zurueck,+ * und das ist in `token-usage.test.ts` festgenagelt): der Knopf traegt+ * wieder das Fenster allein. Beide Schreibweisen sind dann nie gleichzeitig+ * zu sehen, also gibt es auch nichts zu vergleichen.+ * - Nicht verstellbar (Cloud-Modelle): der Knopf verschwindet, aber der- * Fuellstand bleibt — er wird dann OHNE Rahmen ausgegeben. Ohne diesen++ * Fuellstand bleibt, er wird dann OHNE Rahmen ausgegeben. Ohne diesen+ * Zweig haette das Zusammenlegen den Fuellstand auf Cloud-Modellen mit+ * entfernt, wo er vorher stand.*/- export function ContextDropdown() {+ export function ContextDropdown({ children }: { children?: ReactNode }) {+ // `useId` und keine Modulkonstante: die Kopfzeile kann diesen Knopf mehr als+ // einmal rendern (Vergleichsmodus), und doppelte `id`s machen aus+ // `aria-labelledby` einen Zeiger auf den erstbesten Treffer im Dokument.+ const uid = useId()+ const labelId = `${uid}-ctx-label`+ const valueId = `${uid}-ctx-value`const activeModel = useModelStore((s) => s.activeModel)const override = useSettingsStore((s) => s.settings.contextWindowOverride)const updateSettings = useSettingsStore((s) => s.updateSettings)@@@ -66,7 -107,7 +107,7 @@@const status = await bundledEngineStatus()if (status?.running && status.model_path) await swapBundledModel(status.model_path)} catch (e) {-- // The setting is saved (the next start uses it) — but the immediate++ // The setting is saved (the next start uses it), but the immediate// relaunch failed and the engine is now stopped; say so.setApplyError(e instanceof Error ? e.message : String(e))} finally {@@@ -92,7 -133,7 +133,7 @@@await loadLmStudioModel(displayModelName(activeModel), value > 0 ? value : undefined)}} catch (e) {-- // Reload failed — the counter keeps its prior value; tell the user why.++ // Reload failed, the counter keeps its prior value; tell the user why.setApplyError(e instanceof Error ? e.message : String(e))} finally {setBusy(false)@@@ -114,12 -155,42 +155,42 @@@<buttononClick={() => setOpen((o) => !o)}disabled={busy}- title={`Context window: ${ctx.provider === 'lmstudio' ? "LM Studio's loaded context" : ctx.provider === 'builtin' ? "the built-in engine's loaded context" : 'Ollama num_ctx'}. Changing it reloads the model so it takes effect now.`}- /* KF-9 — der Knopf verdeckte seinen eigenen Messwert.+ title={`Context window: ${ctx.provider === 'lmstudio' ? "LM Studio's loaded context" : ctx.provider === 'builtin' ? "the LU Engine's loaded context" : 'Ollama num_ctx'}. Changing it reloads the model so it takes effect now.`}- className="flex items-center gap-1 px-1.5 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem] font-mono tabular-nums disabled:opacity-60"++ /* KF-9: der Knopf verdeckte seinen eigenen Messwert.+ *+ * Hier stand `aria-label="Context window"`. Ein `aria-label` ERSETZT+ * den Namen aus dem Inhalt; sichtbar steht im Knopf aber „117/16.4k".+ * Damit war der Name genau das, was WCAG 2.5.3 (Label in Name)+ * verbietet: er enthielt die sichtbare Beschriftung nicht. Und seit+ * D-S06 die zwei Anzeigen zusammengelegt hat, ist dieser Knopf die- * EINZIGE Stelle, an der die Zahl ueberhaupt noch steht — ein++ * EINZIGE Stelle, an der die Zahl ueberhaupt noch steht, ein+ * Screenreader-Nutzer bekam sie nirgends mehr.+ *+ * `aria-labelledby` statt eines zusammengebauten `aria-label`-Strings:+ * der Name zeigt damit auf den GERENDERTEN Knoten und kann nicht von+ * ihm abweichen. Ein `aria-label={`Context window ${…}`}` waere eine- * zweite Ableitung derselben Zahl — also genau der zweite Pflegeweg,++ * zweite Ableitung derselben Zahl, also genau der zweite Pflegeweg,+ * den D-S06 gerade weggenommen hat.+ *+ * Der Name lautet jetzt „Context window 117/16.4k" bzw. „Context+ * window ctx 8K": das unsichtbare Wort zuerst (es sagt, WAS der Knopf+ * ist), der sichtbare Text danach (er ist die Beschriftung). Der Name+ * bleibt damit ueber ein STABILES Praefix greifbar, obwohl er sich- * mitbewegt — siehe die Anpassung in e2e/builtin-ctx.spec.ts.++ * mitbewegt, siehe die Anpassung in e2e/builtin-ctx.spec.ts.+ */+ aria-labelledby={`${labelId} ${valueId}`}+ aria-expanded={open}+ aria-haspopup="menu"+ className="flex items-center gap-1 px-1.5 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem] lu-hud-num disabled:opacity-60">+ <span id={labelId} className="sr-only">Context window</span>{busy ? <Loader2 size={9} className="animate-spin" /> : null}{applyError && !busy ? <AlertTriangle size={9} className="text-red-400" /> : null}- <span>ctx {fmt(ctx.contextWindow)}</span>+ {/* Der Fuellstand IST die Beschriftung. Nur wenn es keinen gibt (leerer+ Chat), steht hier wieder das Fenster allein. */}+ <span id={valueId}>+ {hasFill ? children : <span>ctx {fmt(ctx.contextWindow)}</span>}+ </span><ChevronDown size={8} className={`transition-transform ${open ? 'rotate-180' : ''}`} /></button>{applyError && !open && (@@@ -131,7 -202,7 +202,7 @@@<div className="flex items-start gap-1.5 text-red-500 dark:text-red-300"><AlertTriangle size={10} className="mt-0.5 shrink-0" /><span className="text-[0.55rem] leading-snug break-words">-- Couldn't reload with the new context — {applyError}++ Couldn't reload with the new context: {applyError}</span></div></div>diff --cc src/components/chat/LoopBar.tsxindex c9563c1e,bbfc5af0..0320f7fb--- a/src/components/chat/LoopBar.tsx+++ b/src/components/chat/LoopBar.tsx@@@ -2,7 -2,7 +2,7 @@@//// A loop has no pass ceiling unless the user sets one, so it can genuinely run// all night. That is only honest if it is visible the whole time and one click--// from stopping — an endless job you cannot see is not a feature, it is a bill.++// from stopping. An endless job you cannot see is not a feature, it is a bill.import { useEffect, useState } from 'react'import { RefreshCw, Square } from 'lucide-react'diff --cc src/components/chat/RAGPanel.tsxindex abfb93f9,c2ebd089..6978be14--- a/src/components/chat/RAGPanel.tsx+++ b/src/components/chat/RAGPanel.tsx@@@ -20,10 -20,8 +20,11 @@@ importimport { useShallow } from 'zustand/react/shallow'import { useRAG } from '../../hooks/useRAG'import { useRAGStore } from '../../stores/ragStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useEmbedLane } from '../../hooks/useEmbedLane'+import { laneIsOnThisMachine } from '../../api/embed-availability'import { formatBytes } from '../../lib/formatters'+ import { MOTION_S } from '../ui/motion'interface Props {conversationId: string | nulldiff --cc src/components/create/experimental/CreateContext.tsxindex 71611cf4,1cc98991..5c384abe--- a/src/components/create/experimental/CreateContext.tsx+++ b/src/components/create/experimental/CreateContext.tsx@@@ -309,10 -302,13 +309,13 @@@ export function CreateExpProvider({ chi}// Timeout, or a state we already tried to fix once: report with the// real output instead of guessing.- const out = await backendCall<{ lines?: string[] }>('comfyui_last_output').catch(() => null)- throw new Error(comfyStartupError(out?.lines))+ const out = await backendCall<{ lines?: string[]; hint?: string }>('comfyui_last_output').catch(() => null)+ throw new Error(comfyStartupError(out?.lines, out?.hint))}- }, [checkConnection, repairComfyEnv, startAndAwait])+ // `checkConnection` stand hier, ohne im Rumpf vorzukommen: aufgerufen wird+ // es von `startAndAwait`, das selbst schon davon abhaengt. Der Eintrag war+ // damit reine Dopplung derselben Invalidierung.+ }, [repairComfyEnv, startAndAwait])// Install a capability in place — mirrors the VHS one-click flow (#72):// ensure ComfyUI runs, clone the custom node + pip install where one isdiff --cc src/components/layout/DownloadBadge.tsxindex 52cf9136,5f7f1778..4341a97d--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@@ -200,11 -208,18 +208,28 @@@ export function DownloadBadge()const bundleProg = totalBytes > 0 ? (doneBytes / totalBytes) * 100 : 0const bundleSpeed = files.reduce((s, f) => s + (f.d.status === 'downloading' ? (f.d.speed || 0) : 0), 0)const isBundle = files.length > 1- // The reason a download stopped, in words. A refused transfer- // used to show a Retry button and nothing else, so the CivitAI- // 400 that only ever needed an API key looked like a dead link- // (goonerforporn, Discord #bug-reports 2026-08-28).- const failure = files.find(f => f.d.status === 'error')?.d.error- // A renamed, gated or deleted repository answers the same way- // every time, so Retry is not a way out of it — offering the- // button anyway is a loop with no exit. Only the failures that- // could plausibly go differently get one; the rest get the- // reason, which says what to do instead.- const retryable = files.filter(f => f.d.status === 'error' && !isPermanentDownloadError(f.d.error))- const dead = files.filter(f => f.d.status === 'error' && isPermanentDownloadError(f.d.error))- // Bytes on disk waiting for the rest — a paused transfer, or a- // partial this session adopted from an earlier run. Without a- // Resume here those files had no way forward at all.++ const failed = files.filter(f => f.d.status === 'error')++ // Der Grund, aus dem ein Download stehen blieb, in Worten. Eine++ // abgelehnte Uebertragung zeigte frueher nur einen Retry-Knopf,++ // also sah die CivitAI-Absage, der bloss ein API-Key fehlte, wie++ // ein toter Link aus (goonerforporn, Discord #bug-reports,++ // 28.08.2026). Deshalb bekommt JEDE Absage mit Begruendung ihre++ // Zeile, nicht nur die endgueltige. Gleiche Begruendungen in++ // einem Bundle werden zu einer Zeile zusammengelegt.++ const reasons = Array.from(new Set(failed.map(f => f.d.error).filter((e): e is string => !!e)))++ // Ein umbenanntes, gesperrtes oder geloeschtes Repository++ // antwortet jedes Mal gleich, Retry ist da kein Ausweg, sondern++ // eine Schleife ohne Ausgang. Den Knopf bekommen nur die++ // Fehlschlaege, die beim naechsten Mal anders ausgehen koennen,++ // die uebrigen behalten die Begruendung, die sagt was stattdessen++ // zu tun ist.++ const retryable = failed.filter(f => !isPermanentDownloadError(f.d.error))++ // Bytes auf der Platte, die auf den Rest warten: eine pausierte++ // Uebertragung, oder ein Fragment, das diese Sitzung aus einem++ // frueheren Lauf uebernommen hat. Ohne ein Resume an dieser++ // Stelle kamen diese Dateien gar nicht mehr weiter.+ const resumable = files.filter(f => f.d.status === 'paused')+ const anyActive = files.some(f => f.d.status === 'downloading' || f.d.status === 'connecting' || f.d.status === 'pausing')return (<div key={bundleName} className="px-3 py-2 border-t border-gray-100 dark:border-white/[0.04] first:border-t-0">@@@ -246,11 -264,11 +274,16 @@@</button>)}</div>- {failure && (- <p className="mt-1 text-[0.55rem] text-red-400 leading-relaxed break-words whitespace-pre-line">- {failure}- {/* A dead address has no button, so it has to have the- reason: what happened and what to do instead. */}- {dead.map(f => (- <p key={f.id} className="mt-1 text-[0.55rem] text-red-400 break-words whitespace-pre-line">{f.d.error}</p>++ {/* Eine tote Adresse hat keinen Knopf, also muss sie die++ Begruendung haben: was passiert ist und was++ stattdessen zu tun ist. Eine Absage, die man wirklich++ beheben kann, bekommt sie ebenso, sonst steht neben++ dem Retry-Knopf wieder nur eine nackte Zahl. */}++ {reasons.map(reason => (++ <p key={reason} className="mt-1 text-[0.55rem] text-red-400 leading-relaxed break-words whitespace-pre-line">++ {reason}+ </p>- )}+ ))}{/* Individual file rows */}{isBundle && (<div className="mt-1.5 space-y-0.5">diff --cc src/components/layout/Sidebar.tsxindex 61bcf220,e5f1e0b7..b03b9311--- a/src/components/layout/Sidebar.tsx+++ b/src/components/layout/Sidebar.tsx@@@ -1,25 -1,34 +1,41 @@@- import { useState, useEffect } from 'react'+ import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'import { motion, AnimatePresence } from 'framer-motion'-import { Plus, Search, Trash2, Edit3, Check, X, MessageSquare, Code, Radio, Copy, RefreshCw, Square, Wifi, Globe, QrCode } from 'lucide-react'+import { Plus, Search, Trash2, Edit3, Check, X, MessageSquare, Code, Radio, Copy, RefreshCw, Square, Wifi, Globe, QrCode, PanelLeftOpen, PanelLeftClose } from 'lucide-react'import { useChatStore } from '../../stores/chatStore'import { useUIStore } from '../../stores/uiStore'+import { useCompareStore } from '../../stores/compareStore'import { useModelStore } from '../../stores/modelStore'import { useSettingsStore } from '../../stores/settingsStore'import { useCodexStore } from '../../stores/codexStore'import { useRemoteStore, REMOTE_DEV_MODE_ERROR } from '../../stores/remoteStore'import { backendCall, isTauri } from '../../api/backend'- import { formatDate, truncate } from '../../lib/formatters'+ import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'+ import {+ conversationMatches, sameSidebarRows, toSidebarRow, type SidebarRow,+ } from './sidebar-rows'export function Sidebar() {- const { conversations, activeConversationId, createConversation, deleteConversation, renameConversation, setActiveConversation } = useChatStore()- const { sidebarOpen, setView, setSidebarOpen, currentView } = useUIStore()- // Targeted selectors throughout. A whole-store subscription here re-rendered- // the entire sidebar once per animation frame for the full duration of every- // streamed answer — and it did so even while another view was on screen,- // because AppShell mounts the sidebar unconditionally.++ // Gezielte Selektoren, durchgehend. Ein Abo auf den ganzen Store hat die++ // Seitenleiste einmal pro Bild neu gezeichnet, solange eine Antwort lief,++ // und zwar auch dann, wenn eine andere Ansicht auf dem Schirm stand, weil++ // AppShell die Seitenleiste bedingungslos mountet.+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const createConversation = useChatStore((s) => s.createConversation)+ const deleteConversation = useChatStore((s) => s.deleteConversation)+ const renameConversation = useChatStore((s) => s.renameConversation)+ const setActiveConversation = useChatStore((s) => s.setActiveConversation)+ const sidebarOpen = useUIStore((s) => s.sidebarOpen)++ const setSidebarOpen = useUIStore((s) => s.setSidebarOpen)+ const sidebarWidth = useUIStore((s) => s.sidebarWidth)+ const setSidebarWidth = useUIStore((s) => s.setSidebarWidth)+ const setView = useUIStore((s) => s.setView)++ const currentView = useUIStore((s) => s.currentView)+ // A/B Compare takes the whole chat area, so neither rail nor panel belongs+ // on screen while it runs. AppShell already unmounts us there; this keeps+ // the rule readable in one place, the way apps/web does it.+ const isComparing = useCompareStore((s) => s.isComparing)- const { activeModel } = useModelStore()- const { getActivePersona } = useSettingsStore()+ const activeModel = useModelStore((s) => s.activeModel)+ const getActivePersona = useSettingsStore((s) => s.getActivePersona)const personasEnabled = useSettingsStore((s) => s.settings.personasEnabled)const chatMode = useCodexStore((s) => s.chatMode)const setChatMode = useCodexStore((s) => s.setChatMode)@@@ -231,111 -318,95 +325,188 @@@tick()const timer = setInterval(tick, 1000)return () => clearInterval(timer)- }, [passcodeExpiresAt, remoteEnabled])+ // `regenerateToken` ist eine Store-Action mit fester Referenz (wie das+ // `refreshDevices`/`hideQr` der Effekte darueber), der Countdown startet+ // also weiterhin nur bei neuem Ablaufzeitpunkt oder Remote-Umschaltung neu.+ }, [passcodeExpiresAt, regenerateToken, remoteEnabled])+ // Web parity (apps/web/components/layout/Sidebar.tsx:217): the conversation+ // list belongs to Chat and nowhere else. This used to be a side effect of+ // setView, which also tore the user's collapse open on every trip through+ // Models or Settings.+ const showSidebar = !isComparing && currentView === 'chat'++ /** One rail button, active or not. Same shape as the web rail. */+ const railBtn = (active: boolean) =>+ `flex items-center justify-center w-9 h-9 rounded-md transition-all ${+ active+ ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white'+ : 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5'+ }`+return (- <AnimatePresence>- {sidebarOpen && (+ <>+ <AnimatePresence mode="wait" initial={false}>+ {/* Collapsed: the slim icon rail. Chat/Code/Remote stay visible and+ clickable, the top button expands to the full conversation list.+ 56 px and w-9 buttons are the web numbers, unchanged. */}+ {showSidebar && !sidebarOpen && (+ <motion.aside+ key="rail"+ data-testid="sidebar-rail"+ className="h-full rounded-xl bg-gray-50 dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] flex flex-col items-center z-20 overflow-hidden shrink-0 py-2 gap-1"+ initial={{ width: 0, opacity: 0 }}+ animate={{ width: 56, opacity: 1 }}+ exit={{ width: 0, opacity: 0 }}+ transition={{ duration: 0.15 }}+ style={{ width: 56 }}+ >+ <button+ onClick={() => setSidebarOpen(true)}+ title="Expand sidebar"+ aria-label="Expand sidebar"+ data-testid="sidebar-toggle"+ className="flex items-center justify-center w-9 h-9 rounded-md text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-all"+ >+ <PanelLeftOpen size={16} />+ </button>+ <div className="w-6 h-px bg-gray-200 dark:bg-white/10 my-1" />+ <button+ onClick={() => { setChatMode('lu'); setActiveConversation(null); setView('chat'); setDispatchPicker(false) }}+ title="Chat"+ aria-label="Chat"+ className={railBtn(!isCodingMode && !isRemoteMode)}+ >+ <MessageSquare size={15} />+ </button>+ <button+ onClick={() => { setChatMode('codex'); setActiveConversation(null); setView('chat'); setDispatchPicker(false) }}+ title="Code"+ aria-label="Code"+ className={railBtn(isCodingMode)}+ >+ <Code size={15} />+ </button>+ <button+ onClick={() => { setChatMode('remote'); setActiveConversation(dispatchedConversationId); setView('chat') }}+ title="Remote"+ aria-label="Remote"+ className={railBtn(isRemoteMode)}+ >+ <Radio size={15} />+ </button>+ <div className="flex-1" />+ <button+ onClick={handleNewChat}+ title={activeModel ? 'New Chat' : 'Pick or install a model first'}+ aria-label="New Chat"+ className="flex items-center justify-center w-9 h-9 rounded-md text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-all"+ >+ <Plus size={17} />+ </button>+ </motion.aside>+ )}- {/* Expanded: the full conversation list. Width and zoom stay as they- were on the desktop (200 px at zoom 1.25 renders as 250, the web- panel is 258): this round ports the collapse, not a resize. */}++ {/* Expanded: the full conversation list. Die feste Breite von 200 px bei++ zoom 1.25 ist weg, die Spalte haengt jetzt am Ziehgriff weiter unten++ (sidebarWidth). `relative` traegt diesen Griff. */}+ {showSidebar && sidebarOpen && (<motion.aside+ key="full"+ data-testid="sidebar-panel"- className="w-[200px] h-full rounded-xl bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] flex flex-col z-20 overflow-hidden"- style={{ zoom: 1.25 }}+ className="relative h-full rounded-[10px] bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] flex flex-col z-20 overflow-hidden"initial={{ width: 0, opacity: 0 }}- animate={{ width: 200, opacity: 1 }}+ animate={{ width: sidebarWidth, opacity: 1 }}exit={{ width: 0, opacity: 0 }}- transition={{ duration: 0.15 }}+ transition={{ duration: ziehend ? 0 : 0.15 }}>+ {/* Ziehgriff — D1, zweite Haelfte (David, 02.09.2026: "bzw dynamisch+ mit vergroesserung anpassend").++ Die Spalte war auf 250 px festgenagelt, es gab also gar keine+ Vergroesserung, an die sich der Titel haette anpassen koennen.+ Erst zusammen mit dem CSS-Schnitt in der Zeile ergibt das etwas:+ waere dort noch `truncate(title, 30)`, endete der Name auch in+ einer 480-px-Spalte nach 30 Zeichen und liesse den Rest leer.++ `-mr-0.5` legt die 1-px-Flaeche halb ueber die Kante, damit sie+ greifbar ist, ohne dass die Spalte 1 px breiter aussieht — genau+ wie der Griff des Agenten-Panels, nur spiegelverkehrt: das steht+ rechts und wird durch Ziehen NACH LINKS breiter, diese Spalte+ steht links und wird durch Ziehen NACH RECHTS breiter. */}+ <div+ onPointerDown={(e) => {+ e.preventDefault()+ setZiehend(true)+ const startX = e.clientX+ const startWidth = sidebarWidth+ const onMove = (ev: PointerEvent) =>+ setSidebarWidth(startWidth + (ev.clientX - startX), window.innerWidth)+ const onUp = () => {+ setZiehend(false)+ window.removeEventListener('pointermove', onMove)+ window.removeEventListener('pointerup', onUp)+ }+ window.addEventListener('pointermove', onMove)+ window.addEventListener('pointerup', onUp)+ }}+ title="Drag to resize"+ data-testid="sidebar-resize-handle"+ className="absolute right-0 top-0 h-full w-1 -mr-0.5 z-10 cursor-col-resize hover:bg-blue-500/40 active:bg-blue-500/60 transition-colors"+ />{/* Mode Tabs (Chat | Code | Remote) — icon-only, like uselu.- Labels live in title/aria-label for accessibility. */}- <div className="flex items-center gap-0.5 px-2 pt-2 pb-1">+ Labels live in title/aria-label for accessibility.++ D-S17 — die Hoehen kommen jetzt aus der Leiter, nicht aus dem+ Padding. Der Befund sprach von vier Hoehen; nachgemessen sind es+ FUENF, und zwei davon standen nebeneinander in DIESER Zeile.+ Gemessen am Dev-Server (Chromium, 900x900, HEAD b3f0f786,+ `offsetHeight`, also CSS-px auf dem unskalierten Entwurfsraster):++ Reiter Chat 30 px+ Reiter Code 30 px+ Reiter Remote 26 px <- gleiche Zeile, 4 px kuerzer+ Suchfeld 31 px+ Chatzeile 36 px+ Dispatch / New Chat 36 px+ LAN / Internet 33 px++ Fuenf Stufen (26/30/31/33/36) auf 250 px Breite, keine davon+ benannt. Die App hat drei benannte: --control-h-sm 26,+ --control-h-md 32, --control-h-lg 40. Die Zuordnung ist nach+ BEDEUTUNG, nicht nach naechstem Zahlenwert:++ md = das Normalmass der Spalte — Reiter, Suchfeld, Chatzeile.+ lg = die EINE Primaeraktion am Fuss (New Chat bzw. Dispatch+ und sein Waehler). --control-h-lg traegt in index.css+ ausdruecklich den Kommentar „primary Create button";+ genau diese Rolle hat der Knopf hier.+ sm = kommt in dieser Spalte NICHT vor. 26 px ist das Mass der+ Composer-Leiste (`.lu-control`), also einer dichten+ Werkzeugzeile. Der Modusumschalter der Sidebar ist keine+ Werkzeugzeile, und dass der Remote-Reiter zufaellig schon+ auf 26 stand, ist kein Argument dafuer — er stand dort,+ weil ihm der Textspan fehlt, nicht weil es gemeint war.++ Keine fuenfte Stufe erfunden. Was das kostet, offen gesagt: die+ Reiter wachsen um 2 px (30->32) bzw. 6 px (26->32), die Chatzeile+ schrumpft um 4 px (36->32), der Fussknopf waechst um 4 px+ (36->40). Die 33 px des LAN/Internet-Waehlers gehen auf 40, weil- er im selben Slot steht wie die Aktion, die er ersetzt. */}++ er im selben Slot steht wie die Aktion, die er ersetzt.++++ Der Zuklapp-Knopf steht in derselben Zeile und haelt sich an++ dieselbe Leiter: md, quadratisch, damit er neben den Reitern++ keine sechste Hoehe aufmacht. */}+ <div className="flex items-center gap-[2.5px] px-2.5 pt-2.5 pb-1.25 text-[12px]">+ {/* Collapse back to the slim rail */}+ <button+ onClick={() => setSidebarOpen(false)}+ title="Collapse sidebar"+ aria-label="Collapse sidebar"+ data-testid="sidebar-toggle"- className="flex items-center justify-center w-6 h-6 rounded text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-all shrink-0"++ className="flex items-center justify-center w-[var(--control-h-md)] h-[var(--control-h-md)] rounded-[5px] text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-all shrink-0"+ >+ <PanelLeftClose size={13} />+ </button>{/* Chat tab */}<buttononClick={() => { setChatMode('lu'); setActiveConversation(null); setView('chat'); setDispatchPicker(false) }}diff --cc src/components/models/DiscoverModels.tsxindex a44916fe,cfa404f2..6c405ea2--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@@ -768,11 -911,15 +947,21 @@@ export function DiscoverModels({ catego</div>)}+ {/* A14: the pick took the chat backend with it, and says so. The same+ bar the composer shows, from the same store, so the sentence cannot+ drift into two versions of itself. */}+ <LuEngineSwitchBar />++ {/* D-S22 · die Legende zu den Faehigkeitszeichen auf den Kacheln.+ Steht einmal hier statt 53 Mal als Tooltip, den man erst findet,+ wenn man auf einem 12px-Glyph stehenbleibt. Sie rendert aus+ derselben `CAPABILITIES`-Tabelle wie die Kacheln (ModelTiles.tsx),- kann also nicht von ihnen abweichen. */}++ kann also nicht von ihnen abweichen. Sie steht unter der Leiste,++ also so nah wie moeglich an dem Raster, das sie erklaert. */}+ {isText && (uncensoredModels.length > 0 || mainstreamModels.length > 0) && (+ <CapLegend />+ )}+{/* Install error banner */}{installError && (<div className="flex items-center gap-2 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-sm">diff --cc src/components/models/ModelCard.tsxindex a188d6be,b93e6672..79130337--- a/src/components/models/ModelCard.tsx+++ b/src/components/models/ModelCard.tsx@@@ -1,6 -1,9 +1,9 @@@-import { Trash2, Info, MessageSquare, Image, Video } from 'lucide-react'+import { Trash2, Info, MessageSquare, Image, Video, Loader2 } from 'lucide-react'+ import { useState } from 'react'import { formatBytes } from '../../lib/formatters'import { BenchmarkButton } from './ModelBenchmark'+ import { ContextMenu } from '../ui/ContextMenu'+ import { buildModelCardMenu, type ModelMenuHandlers } from '../ui/menu-actions'import type { AIModel } from '../../types/models'interface Props {@@@ -33,13 -21,24 +36,24 @@@ const TYPE_CONFIG =video: { label: 'Video', icon: Video, color: 'text-green-400' },}-export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDelete = true }: Props) {+export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDelete = true, onUse, useBusy = false }: Props) {const typeInfo = TYPE_CONFIG[model.type] || TYPE_CONFIG.textconst TypeIcon = typeInfo.icon+ const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)++ // EIN Satz Aktionen fuer die Karte. Die sichtbaren Knoepfe unten lesen aus+ // diesem Objekt, das Kontextmenue bekommt dasselbe Objekt gereicht — es gibt+ // also keinen zweiten Aufrufweg, der irgendwann anders werden koennte.+ const actions: ModelMenuHandlers = { select: onSelect, info: onInfo, remove: onDelete }return (+ <><div- onClick={onSelect}+ onClick={actions.select}+ onContextMenu={(e) => {+ e.preventDefault()+ setMenu({ x: e.clientX, y: e.clientY })+ }}className={`flex items-center gap-2.5 px-3 py-1.5 rounded-lg border cursor-pointer transition-all group ${isActive? 'bg-blue-50 dark:bg-white/[0.05] border-blue-400/40 ring-1 ring-blue-400/40'diff --cc src/components/models/ModelManager.tsxindex 0cede15f,cc68d937..a580d456--- a/src/components/models/ModelManager.tsx+++ b/src/components/models/ModelManager.tsx@@@ -62,16 -57,16 +62,23 @@@ export function ModelManager()} = useModels()const { setView, openSettingsAt } = useUIStore()const ollamaEnabled = useProviderStore(s => s.providers.ollama.enabled)+ // A14: whether the LU Engine itself is serving the chat. Decides whether its+ // group needs a heading even when it is the only group (review 7).+ const luEngineHoldsChat = useProviderStore(s => s.providers.openai.enabled && s.providers.openai.managed === true)+ // A16 (A14-4a): which row's Use button is mid swap. The engine has to stop,+ // reload a GGUF that can be several gigabytes and come back healthy, and a+ // button that looks idle through all of that gets pressed again.+ const [usingModel, setUsingModel] = useState<string | null>(null)const [pullOpen, setPullOpen] = useState(false)const [infoOpen, setInfoOpen] = useState(false)- const [modelInfo, setModelInfo] = useState<any>(null)+ // Gesetzt wird das aus `{ name, ...await showModel(name) }` (unten in+ // `handleInfo`), und `showModel` gibt `Record<string, unknown>` zurueck+ // (api/ollama.ts:61) — es reicht die Antwort von Ollamas /api/show+ // unveraendert durch, deren Felder je nach Modell wechseln. Genau dafuer ist+ // der Typ hier gebaut: `name` kennen wir, weil wir es selbst danebenschreiben,+ // der Rest ist `unknown`. Gelesen wird ohnehin nur `name` (Modal-Titel) und+ // das Ganze als JSON.stringify.+ const [modelInfo, setModelInfo] = useState<({ name: string } & Record<string, unknown>) | null>(null)const [confirmDelete, setConfirmDelete] = useState<string | null>(null)// Open on Discover by default — most opens are to find and install// something new. Installed is one click away in the segment control.@@@ -474,13 -426,9 +481,13 @@@}/></motion.div>- ))}+ )+ })}+ </div>+ ))+ })()}{shown.length === 0 && (- <p className="text-center text-[0.65rem] text-gray-500 py-6">No installed {modeMeta.label.toLowerCase()} models match "{searchQuery}"</p>+ <p className="text-center t-micro text-gray-500 py-6">No installed {modeMeta.label.toLowerCase()} models match "{searchQuery}"</p>)}</div></section>diff --cc src/components/models/ModelSelector.tsxindex 90a06673,d1101f9c..0ca2b89c--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@@ -18,17 -20,9 +20,19 @@@ import { lmStudioSlotUpdate, adoptionReimport { nextProbeDelayMs } from '../../lib/probe-backoff'import { noChatBackendEnabled } from '../../lib/provider-visibility'import { cloudTeaserModels } from '../../lib/cloud-teaser-models'+import { splitLuEngineRows, needsLuEngineHeading, LU_ENGINE_GROUP } from '../../lib/lu-engine-rows'+import { isBuiltinEngineEntry, type InstalledModelLike } from '../../lib/lmstudio-match'+import {+ ensureLuEngineIsChatProvider, LU_ENGINE_SWITCH_NOTE, LU_ENGINE_SWAP_BUSY_NOTE,+ announceLuEngineSwapBusy, luEngineStartFailureNote,+ LM_STUDIO_LOAD_BUSY_NOTE, announceLmStudioLoadBusy,+ handBackChatProviderForRow, chatProviderSwitchNote,+} from '../../api/lu-engine-switch'+import { tryAcquireLuEngineSwap, releaseLuEngineSwap, luEngineSwapInFlight } from '../../api/lu-engine-swap-lock'+import { useLuEngineSwitchStore } from '../../stores/luEngineSwitchStore'+ import { ModelPickerSkeleton } from '../layout/ViewSkeletons'import type { AIModel } from '../../types/models'+ import { MOTION_S } from '../ui/motion'// ── Local-mode cloud discovery (2.5.8): an "LU Cloud" section at the list's// tail. Signed-in accounts show their real hosted chat models (the appMode@@@ -549,9 -526,18 +573,18 @@@ export interface ModelSelectorProps// `openUpward` flips the dropdown to open above the trigger, right-aligned —// used when the picker lives in the composer action bar (bottom of the screen)// instead of the header. Header usage keeps the default downward/centered menu.-export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSelectorProps = {}) {+export function ModelSelector({ openUpward = false, surface = 'chat', answeredBy = null }: ModelSelectorProps = {}) {const { models, activeModel, setActiveModel, fetchModels } = useModels()const isModelLoading = useModelStore((s) => s.isModelLoading)+ // Welle 3, Listen-Ladezustand 3 von 4 — und der einzige, den es vorher gar+ // nicht gab. `inventoryLoaded` ist die Frage „ist ueberhaupt schon einmal+ // eine Modellliste hier gelandet"; sie steht seit dem Zaehler-Nachschlag+ // (2026-08-29) im Store, aus genau demselben Grund: bis dahin darf man+ // keine Zahl und keine Leermeldung zeigen, sondern nur eine Ladeanzeige.+ // Ohne sie ging der Waehler direkt von leer auf Liste — und „leer" rendert+ // hier als „No models available", also als Aussage ueber die Maschine+ // statt ueber den Ladezustand.+ const inventoryLoaded = useModelStore((s) => s.inventoryLoaded)// G20: useModels hides every local model while the app is in Cloud mode.// Deliberate, but the picker never SAID so, and the silence reads as "my// local models are gone" (it cost a whole repro round on 2026-08-07).@@@ -957,21 -849,15 +995,19 @@@{/* ── Trigger Button ── */}<buttononClick={() => setOpen(!open)}- title={activeModel ? `Model: ${activeDisplayName}, click to switch` : 'Select a chat model'}+ title={+ answeredBy+ ? `The answers in this chat were written by ${answeredBy}. The next answer runs on the model picked here.`+ : activeModel ? `Model: ${activeDisplayName}, click to switch` : 'Select a chat model'+ }aria-label="Select chat model"- className={`- group flex items-center gap-1.5 h-[26px] px-2 rounded-md- bg-transparent border transition-all text-[0.7rem]- hover:bg-white/[0.04]- ${isModelLoading- ? 'border-blue-500/40 shadow-[0_0_6px_rgba(59,130,246,0.2)]'- : 'border-white/[0.06] hover:border-white/[0.1]'- }- `}+ aria-expanded={open}+ // Laedt gerade ein Modell: `aria-busy` statt eines eigenen blauen+ // Rezepts mit Leuchtschatten. Das Rezept faerbt die Kante mit dem+ // Akzent, die Aussage steht damit im selben Vokabular wie der Rest+ // der Leiste — und im Accessibility-Baum, wo sie hingehoert.+ aria-busy={isModelLoading}+ className="lu-control">{/* Type indicator dot */}<span className={`w-1.5 h-1.5 rounded-full ${@@@ -1044,12 -920,12 +1081,13 @@@</div>)}+{/* Scrollable model list */}<div className="py-1 max-h-[280px] overflow-y-auto scrollbar-thin">- {textModels.length === 0 && (+ {!inventoryLoaded && textModels.length === 0 && <ModelPickerSkeleton />}+ {inventoryLoaded && textModels.length === 0 && (<div className="px-2.5 py-3 text-center">- <p className="text-[0.65rem] text-gray-600">No models available</p>+ <p className="t-micro text-gray-600">No models available</p>{/* An empty picker after the user switched the last backendoff in Settings used to say only that, which reads like amachine with nothing installed (Nebenbefund 1, R9diff --cc src/components/models/ModelTiles.tsxindex 62787d54,e12e8f7b..ac95ad4c--- a/src/components/models/ModelTiles.tsx+++ b/src/components/models/ModelTiles.tsx@@@ -11,7 -12,7 +12,8 @@@ import type { LucideIcon } from 'lucideimport type { DiscoverModel, DownloadProgress, ModelBundle } from '../../api/discover'import { formatBytes } from '../../lib/formatters'import { bundleVramNeedGb } from '../../lib/hardware'+import { modelTileAction } from '../../lib/model-tile-action'+ import { ICON_SM } from '../ui/icon-size'// ─── Hardware fit ───────────────────────────────────────────────────@@@ -262,39 -423,28 +442,45 @@@ export function ModelTile({ variants, v)}<FitHint fit={fit} />- {sel.pulls && <span className="text-[0.55rem] text-gray-400 dark:text-gray-500 ml-auto mr-1">{sel.pulls}</span>}-- <div className={`flex items-center gap-1 shrink-0 ${sel.pulls ? '' : 'ml-auto'}`}>+ <div className="flex items-center gap-1.5 ml-auto shrink-0">+ {sel.hot && <HotMark />}+ {sel.pulls && <span className="text-[0.55rem] text-gray-400 dark:text-gray-500 mr-1">{sel.pulls}</span>}+- {externalOnly ? (++ {/* Ein Zustand, ein Ausgang: die Leiter kommt aus `modelTileAction`++ (GH #118), die Optik aus den Rezepten dieser Datei. `installed`,++ `downloading` und `externalOnly` stehen deshalb nicht mehr++ einzeln in dieser Kette, sie gehen oben in `action` ein. */}+ {action === 'view' ? (sel.url ? (<buttononClick={() => onOpenUrl(sel.url!)}- className="flex items-center gap-1 px-2 py-1 rounded-md bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-[0.62rem] font-medium text-gray-700 dark:text-gray-200 transition-colors"+ className="lu-control"title="View on HuggingFace"+ aria-label={`View ${groupTitle} on HuggingFace`}>- <ExternalLink size={11} /> View+ <ExternalLink size={ICON_SM} /> View</button>) : null- ) : installed ? (+ ) : action === 'use' ? (+ <button+ onClick={() => onUse!(sel)}- className="flex items-center gap-1 px-2 py-1 rounded-md bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-700 dark:text-gray-200 text-[0.62rem] font-medium transition-colors"++ className="lu-control"+ title="Installed. Load it in the chat and start the engine if it is not running."+ aria-label={`Use ${sel.name}`}+ >- <Check size={11} className="text-emerald-500/80" /> Use++ <Check size={ICON_SM} className="text-emerald-500/80" /> Use+ </button>+ ) : action === 'using' ? (- <span className="flex items-center gap-1.5 px-2 py-1 text-[0.62rem] text-gray-500 dark:text-gray-400">- <Loader2 size={11} className="animate-spin" /> Loading…++ <span className="flex items-center gap-1.5 h-[var(--control-h-sm)] px-2 t-micro text-gray-500 dark:text-gray-400">++ <Loader2 size={ICON_SM} className="animate-spin" /> Loading…+ </span>+ ) : action === 'installed' ? (- <span className="flex items-center gap-1 px-2 py-1 rounded-md bg-gray-100 dark:bg-white/[0.06] text-gray-600 dark:text-gray-300 text-[0.62rem] font-medium">- <Check size={11} className="text-emerald-500/80" /> Installed+ <span className={TILE_STATE}>+ <Check size={ICON_SM} className="text-emerald-500/80" /> Installed</span>- ) : downloading ? (+ ) : action === 'downloading' ? (- <span className="flex items-center gap-1.5 px-2 py-1 text-[0.62rem] text-gray-500 dark:text-gray-400">- <Loader2 size={11} className="animate-spin" /> Downloading…+ <span className="flex items-center gap-1.5 h-[var(--control-h-sm)] px-2 t-micro text-gray-500 dark:text-gray-400">+ <Loader2 size={ICON_SM} className="animate-spin" /> Downloading…</span>) : (<button@@@ -435,22 -589,13 +625,24 @@@ export function HardwareChip({ vramGb,if (!vramGb && !ramGb) return nullreturn (<span- className="inline-flex items-center gap-1.5 px-2 py-1 rounded-lg bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] text-[0.6rem] text-gray-600 dark:text-gray-300"+ className="inline-flex items-center gap-1.5 px-2 py-1 rounded-lg bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] t-micro text-gray-600 dark:text-gray-300"title="Detected hardware. Used for the 'runs on your PC' hints. Models are never hidden because of it.">- <HardDrive size={11} className="text-gray-400" />+ <HardDrive size={ICON_SM} className="text-gray-400" />- {vramGb ? <span className="tabular-nums">{Math.round(vramGb)} GB GPU</span> : null}- {vramGb && ramGb ? <span className="opacity-40">·</span> : null}- {ramGb ? <span className="tabular-nums">{Math.round(ramGb)} GB RAM</span> : null}+ {/* A side we could not measure says so. Zhorts (GH #123) read "62 GB GPU"+ off this chip on a 16 GB card, because the number behind it was his+ system RAM; the source of that is fixed in api/comfyui.ts, and this is+ the other half. Leaving the half out entirely reads as "no GPU", and- an unmeasured GPU is not the same thing as an absent one. */}++ an unmeasured GPU is not the same thing as an absent one. Beide++ Haelften stehen also immer, und der Trenner dazwischen braucht keine++ Bedingung mehr. */}+ {vramGb+ ? <span className="tabular-nums">{Math.round(vramGb)} GB GPU</span>+ : <span>GPU unknown</span>}+ <span className="opacity-40">·</span>+ {ramGb+ ? <span className="tabular-nums">{Math.round(ramGb)} GB RAM</span>+ : <span>RAM unknown</span>}</span>)}diff --cc src/components/models/__tests__/hints-name-real-controls.test.tsindex 2f2a50f4,c7dd622d..1c5cd9b4--- a/src/components/models/__tests__/hints-name-real-controls.test.ts+++ b/src/components/models/__tests__/hints-name-real-controls.test.ts@@@ -41,11 -41,11 +41,15 @@@ const modelManager = read('src/componenconst settingsPage = read('src/components/settings/SettingsPage.tsx')const hardware = read('src/components/settings/HardwareSettings.tsx')const modelSelector = read('src/components/models/ModelSelector.tsx')+const chatInput = read('src/components/chat/ChatInput.tsx')+/** The effort button's OWN tooltip, pulled out of the shipped markup. */+const effortTip =+ chatInput.match(/data-testid="effort-toggle"[\s\S]{0,600}?title=\{`([^`]*)`\}/)?.[1] ?? ''const remoteRs = read('src-tauri/src/commands/remote.rs')+ // 01.09.2026 (T-75): the mobile drawer moved out of the Rust string it used to+ // live in. The refusal text is still Rust; the controls it names are in the+ // client source now.+ const mobileClient = read('mobile-client/client.js')describe('THE FIX: the ComfyUI-is-down hint names the control that exists', () => {it('it sends the user to Settings, AI Backends, Start', () => {diff --cc src/components/onboarding/Onboarding.tsxindex 8475bba8,34bb546e..669f6464--- a/src/components/onboarding/Onboarding.tsx+++ b/src/components/onboarding/Onboarding.tsx@@@ -1,26 -1,73 +1,74 @@@- import { useState, useEffect } from 'react'- import { withInstallerOutput } from '../../lib/error-text'+ /**+ * Der Assistent beim ersten Start — die SCHALE.+ *+ * ── Warum diese Datei nur noch die Schale ist (W-T3) ──────────────────────+ *+ * Hier standen 1909 Zeilen: sechs Bildschirme, vier Installationsablaeufe,+ * drei Download-Wege und der Fensterrahmen, alles in einer Funktion. Die+ * Zerlegung folgt NICHT der Bildschirmfolge und nicht der Zeilenzahl, sondern+ * der Frage, welcher Zustand ueber einen Bildschirm hinaus gelesen wird:+ *+ * ./use-backend-scan.ts Der Scan und die gewaehlte Maschine. FUENF+ * Bildschirme lesen ihn, zwei schreiben ihn —+ * also gehoert er ueber die Schritte, nicht in+ * einen von ihnen.+ * ./use-installer-fleet.ts Die vier Installer und ihr EINER Takt. Sie+ * verteilen sich auf zwei Bildschirme, teilen+ * aber eine Uhr (AS-09); eine Zerlegung „pro+ * Schritt" haette daraus wieder zwei Uhren+ * gemacht.+ * ./onboarding-skin.ts Die zwei Knopf-Behandlungen und die zwei+ * Flaechen. Fuenf Dateien zeichnen sie; fuenf+ * Kopien waeren fuenf Rezepte (D-S36).+ * ./wait-for-download.ts Das Einzige, was sich Modell- und+ * Einbettungsschritt teilen: erst wenn die Datei+ * ganz da ist, darf ein Server darauf starten.+ * ./onboarding-host.ts Desktop-Fenster oder Browser-Vorschau. Drei+ * Dateien fragen; das Praedikat steht einmal.+ *+ * Was danach uebrig blieb, ist genau das, was ein Assistent ist: welcher+ * Bildschirm gerade dran ist, was der Nutzer bis hierher gewaehlt hat, der+ * Fensterrahmen, der Fortschrittsanzeiger — und die zwei Bildschirme, die+ * keinen eigenen Zustand haben (Willkommen, Fertig). Die vier+ * ARBEITSSCHRITTE liegen je in einer eigenen Datei:+ * ./BackendsStep.tsx · ./ComfyStep.tsx · ./ModelsStep.tsx ·+ * ./EmbeddingsStep.tsx.+ *+ * Die `motion.div` samt Schluessel und Ein-/Ausblendung bleibt hier, um jeden+ * Schritt herum: der UEBERGANG zwischen Bildschirmen gehoert dem Assistenten,+ * nicht dem Bildschirm. Die Schritte liefern ein Fragment — das DOM ist+ * dadurch dasselbe wie vorher, `space-y-*` der Karte greift unveraendert.+ *+ * ── Die zwei Weichen, die hier bleiben mussten ────────────────────────────+ *+ * `nextStepAfterBackends` und `selectBackendAndContinue` sehen aus wie+ * Backend-Schritt und sind es nicht: die erste entscheidet, welcher+ * Bildschirm als naechster kommt, die zweite schreibt den Provider-Store und+ * ruft dann die erste. Beides ist Routenwahl des Assistenten.+ */+ import { useState } from 'react'import { motion, AnimatePresence } from 'framer-motion'- import { Minus, Square, X as XIcon, ArrowRight, Download, Check, ChevronRight, Loader2, RefreshCw, ExternalLink, FolderOpen, Cpu } from 'lucide-react'+ import { Minus, Square, X as XIcon, ArrowRight } from 'lucide-react'import { useSettingsStore } from '../../stores/settingsStore'import { useProviderStore } from '../../stores/providerStore'- import { ONBOARDING_MODELS, ONBOARDING_EMBED_MODEL } from '../../lib/constants'import { PROVIDER_PRESETS } from '../../api/providers/types'- import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'- import { detectProviderModelPath, startModelDownloadToPath } from '../../api/discover'- import { useDownloadStore } from '../../stores/downloadStore'- import { ProgressBar } from '../ui/ProgressBar'- import { openExternal, isMacOS } from '../../api/backend'- import { formatBytes } from '../../lib/formatters'- import { backendCall } from '../../api/backend'- import { getSystemVRAM } from '../../api/comfyui'- import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'- import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'- import { startBundledEngine, startBundledEmbed } from '../../api/engine'- import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'+ import { ICON_SM } from '../ui/icon-size'+ import { isMacOS, backendCall } from '../../api/backend'+ import { BUILTIN_BACKEND_ID } from '../../lib/onboarding-backend'+import { LU_ENGINE_NAME } from '../../lib/engine-name'import { version as currentVersion } from '../../../package.json'import { useReleaseNotesStore } from '../../stores/releaseNotesStore'+ import { wizardProgress, workStepsFor, type Step } from './wizard-steps'+ import { onboardingSkin } from './onboarding-skin'+ import { useBackendScan } from './use-backend-scan'+ import { useInstallerFleet } from './use-installer-fleet'+ import { isTauri } from './onboarding-host'+ import { hostWindow } from '../../lib/host-window'+ import { BackendsStep } from './BackendsStep'+ import { ComfyStep } from './ComfyStep'+ import { ModelsStep } from './ModelsStep'+ import { EmbeddingsStep } from './EmbeddingsStep'+// Bug (h): the dedicated 'theme' onboarding step was removed because users// kept ending up on Light by accident, and the project standard is "darkdiff --cc src/components/settings/SettingsPage.tsxindex 977f6674,241e96a2..5bda5295--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@@ -1,8 -1,11 +1,13 @@@import { useState, useEffect, useRef, type ReactNode, type ChangeEvent } from 'react'- import { withInstallerOutput } from '../../lib/error-text'- import { ArrowLeft, RotateCcw, Sun, Moon, Volume2, Check, X, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User, Download, Mic } from 'lucide-react'-import { withInstallerOutput, withDetail } from '../../lib/error-text'-import type { InstallerStatusResponse } from '../onboarding/installer-state'-import { ArrowLeft, RotateCcw, Sun, Moon, Check, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User, Download, AlertTriangle } from 'lucide-react'++import { withDetail } from '../../lib/error-text'++// `X` steht hier weiterhin, obwohl der Sprachabschnitt mit seinen Symbolen++// nach ./SpeechSettings.tsx gezogen ist: der Dismiss-Knopf der ComfyUI-Notiz++// traegt ihn neben dem Wort.++import { ArrowLeft, RotateCcw, Sun, Moon, Check, X, Loader2, Shield, ChevronRight, GraduationCap, Lock, Sliders, Plug, Bot, Phone, User, Download, AlertTriangle } from 'lucide-react'import { motion, AnimatePresence } from 'framer-motion'import { SETTINGS_TAB_RESET_KEYS, type SettingsTab } from '../../lib/settings-reset'+ import { armedScopeFor, type ResetArm, type ResetArmScope } from '../../lib/reset-arming'+ import { sectionAnchorId, sectionsFor, type SettingsSectionFlags } from './settings-nav'import { useSettingsStore } from '../../stores/settingsStore'import { usePermissionStore } from '../../stores/permissionStore'import { useUIStore } from '../../stores/uiStore'@@@ -59,7 -39,8 +42,8 @@@ import { MCPServerSettings } from './MCimport { WorkflowList } from '../agents/WorkflowList'import { WorkflowBuilder } from '../agents/WorkflowBuilder'import { useUpdateStore, isNewerVersion } from '../../stores/updateStore'-import { backendCall, isTauri, openExternal } from '../../api/backend'+import { backendCall, isTauri, isMacOS, openExternal } from '../../api/backend'+ import { troubleshootHinweis, type TroubleshootHinweis } from './troubleshoot-message'import { isMlxImageHost } from '../../api/mlx-image'import { ArrowUpCircle, KeyRound, RefreshCw } from 'lucide-react'import { CLOUD_BASE } from '../../api/cloud/config'@@@ -262,140 -230,26 +242,149 @@@ function WorkflowSection())}-// ── Model Storage (HF GGUF download path override) ─────────────+// ── Model Storage (the user's own model folder) ─────────────────+//+// GH #122 (zrmdsxa) + Discord "Read me first" (ever.noob): this folder was a+// download TARGET and nothing else. Models already sitting in it were never+// looked at, and the copy above the field said nothing about that, so the+// Models tab stayed empty beside a folder full of models. It is read now+// (lib/custom-model-dir.ts), and the copy says what it does.-function HfDownloadPathSetting() {+export function HfDownloadPathSetting() {const override = useSettingsStore(s => s.settings.hfDownloadPathOverride)- const updateSettings = useSettingsStore(s => s.updateSettings)const [draft, setDraft] = useState(override)++ // Der Ordnerwaehler hat nicht aufgemacht: Stufe (c), der Klick sollte etwas++ // aendern und hat es nicht. Ein Abbruch im Dialog liefert null und ist kein++ // Fehler, hier landet also nur ein echter Fehlschlag.+ const [pickError, setPickError] = useState<string | null>(null)- useEffect(() => { setDraft(override) }, [override])+ const [comfy, setComfy] = useState<CustomModelDirResult | null>(null)+ const [scan, setScan] = useState<ScannedDir | null>(null)+ // The folder LU reads while the field is empty. Row 0 of the listing is the+ // app's own models dir, which is exactly the folder the LU Engine loads+ // from, so the empty field can name it instead of saying "(auto-detect)"+ // and leaving the user to guess.+ const [autoDir, setAutoDir] = useState('')+ /** Typed but not stored yet. Null means there is nothing owed. Declared+ * before the effect below because that effect asks it. */+ const pendingPath = useRef<string | null>(null)+ // The store value flows back into the box, EXCEPT while the user is in the+ // middle of typing one. A16 counter-check follow-up: with a half typed path+ // owed, a store write from anywhere would have pulled the box back to the+ // stored value under the cursor.+ useEffect(() => {+ if (pendingPath.current !== null) return+ setDraft(override)+ }, [override])++ // How the GGUF scan itself fared in that folder. A folder too big to finish+ // within the budget returns a real but partial list, and the only person who+ // can do anything about that is the one who chose the folder.+ //+ // Runs with and without an override since 2.6.8: without one there is no+ // scan verdict to show, but the listing is still the only place the app dir+ // is known, and the placeholder needs it.+ useEffect(() => {+ let alive = true+ void listBundledModels()+ .then(() => {+ if (!alive) return+ setScan(override ? lastCustomScanDir() : null)+ setAutoDir(lastScanDirs()[0]?.path ?? '')+ })+ .catch(() => { if (alive) { setScan(null); setAutoDir('') } })+ return () => { alive = false }+ }, [override])++ // Both directions of the folder: our own GGUF scan reads it on the next+ // model refresh, and the ComfyUI-shaped subfolders in it are handed to+ // ComfyUI. Runs on mount too, so a folder set by an older build reaches+ // ComfyUI without the user having to touch the field again.+ useEffect(() => {+ let alive = true+ void syncCustomModelDir(override).then((res) => { if (alive) setComfy(res) })+ return () => { alive = false }+ }, [override])++ // One line, and only when there is something to say.+ const scanNote = modelDirScanNote(scan?.status)+ // A folder that cannot be read at all has one problem, not two, so the+ // ComfyUI handoff note steps aside for those two verdicts: it would say the+ // same thing in different words. `truncated` is a different matter. The+ // folder IS readable, the walk simply ran out of budget, and what LU hands+ // to ComfyUI is unaffected by that, so both lines belong on screen.+ const scanHidesHandoff = scan?.status === 'unreachable' || scan?.status === 'unusable'++ // A16 (A14-2a), Windows counter-check 02.09.: the folder was stored on Enter+ // or on blur and on nothing else. Type a path, walk away to another tab or+ // close Settings, and the value stood in the box while+ // `hfDownloadPathOverride` stayed empty and Installed never changed. The+ // counter-check's first attempt concluded from that the folder was being+ // ignored, which is the reading anyone would reach.+ //+ // The first answer to that was a 600 ms debounce, and the follow-up+ // counter-check showed what it cost. The debounce wrote the TRIMMED value+ // into the store while the field was still being typed in, the effect above+ // pushed the store value straight back into the box, and a path with a space+ // in it lost that space mid word: "C:\Program " became "C:\Program", the+ // cursor jumped to the end, and the next keystrokes produced+ // "C:\ProgramFiles". A half typed path also reached the folder scan, which+ // then hung a red "unreachable" line under a field nobody had finished+ // filling in.+ //+ // So no timer writes anything any more. The field commits on blur, on Enter+ // and when it goes away, and the third of those is what the finding was+ // actually about: walking away from a settings field IS a blur or an+ // unmount, so nothing is lost without a clock having to guess when the user+ // is done.++ /** Store it. Everything that saves goes through here, so clearing the debt+ * cannot be forgotten on one path. */+ function commit(next: string) {+ pendingPath.current = null+ const store = useSettingsStore.getState()+ if (store.settings.hfDownloadPathOverride === next) return+ store.updateSettings({ hfDownloadPathOverride: next })+ // The Models tab is the surface this setting is about: refresh it now+ // instead of after the next navigation.+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ }++ function apply(next: string) {+ setDraft(next)+ commit(next)+ }++ /** One keystroke. Stored verbatim, trailing space and all: it is trimmed at+ * commit time and not before, so a path that is still being typed keeps the+ * space the next word needs. */+ function typePath(next: string) {+ setDraft(next)+ pendingPath.current = next+ }++ // Closing Settings or switching tabs unmounts this field. Whatever was owed+ // at that moment is stored, not thrown away.+ useEffect(() => () => {+ const owed = pendingPath.current+ pendingPath.current = null+ if (owed === null) return+ const store = useSettingsStore.getState()+ const trimmed = owed.trim()+ if (store.settings.hfDownloadPathOverride === trimmed) return+ store.updateSettings({ hfDownloadPathOverride: trimmed })+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ }, [])async function pickFolder() {+ setPickError(null)try {const chosen = await backendCall<string | null>('pick_folder')- if (chosen) { setDraft(chosen); updateSettings({ hfDownloadPathOverride: chosen }) }++ // Ueber `apply`, nicht am Feld vorbei: das ist der eine Weg, der die++ // offene Tippschuld loescht und die Modellliste anstoesst.+ if (chosen) apply(chosen)- } catch {}+ } catch (e) {- // Level (c): the click was meant to CHANGE the download path and did- // not. Cancelling the dialog returns null and is not an error, so- // anything landing here really failed to open the picker.+ setPickError(withDetail('The folder picker did not open. Type or paste the path into the field instead.', e))+ }}return (@@@ -430,23 -281,11 +419,28 @@@</button>)}</div>+ {/* A14: setting a folder under Desktop, Documents or Downloads makes+ macOS ask for access the first time LU walks it. That is the system+ asking on the user's behalf and nothing here prevents it; the panel+ only stops it from arriving as a surprise from an app that just+ started reading a folder. Shown for the path the user typed as well+ as for one he picked, and only on the Mac. */}+ {macOsWillAskForFolder(draft || override, isMacOS()) && (+ <div data-testid="macos-folder-access-note" className="text-[0.6rem] leading-relaxed text-gray-500">+ {MACOS_FOLDER_ACCESS_NOTE}+ </div>+ )}+ {override && scanNote && (+ <div data-testid="model-dir-scan-note" className="text-[0.6rem] leading-relaxed text-amber-600 dark:text-amber-400">+ {scanNote}+ </div>+ )}+ {override && comfy !== null && !scanHidesHandoff && <CustomModelDirNote result={comfy} />}+ {pickError && (+ <p role="alert" className="text-[0.55rem] text-red-500 dark:text-red-400 leading-snug whitespace-pre-line">+ {pickError}+ </p>+ )}</div>)}@@@ -649,8 -383,54 +648,51 @@@ export function ImportLocalModels()// ── ComfyUI Settings ────────────────────────────────────────────+ /**+ * Antwort von `comfyui_status` (`src-tauri/src/commands/process.rs:1989`).+ *+ * Der Typ stand als Ganzes schon da — als der inline notierte Zustandstyp von+ * `useState` eine Zeile weiter unten. Nur der Weg dorthin trug `any`, und der+ * hat zwei Abweichungen zugedeckt, die beide nachgemessen sind:+ *+ * 1. `path` ist auf der Rust-Seite `Option<String>`, kommt also als `null`+ * an — nicht als `undefined`. Der Zustandstyp sagte `path?: string`; ein+ * `null` haette dort nie hineingedurft, und `any` hat es hineingelassen.+ * Beide Lesestellen (`status?.path || ''`) vertragen `null` ohnehin.+ * 2. Der Dev-Server, den der Browser-Modus statt Tauri anspricht, sendet von+ * den zehn Schluesseln nur sechs (`dev-server/comfy.ts:461`): `stalled`,+ * `complete`, `port`, `host` und `isLocal` fehlen dort. Deshalb sind sie+ * hier optional — im Browser sind sie wirklich nicht da.+ */+ interface ComfyStatusResponse {+ running: boolean+ found: boolean+ /** Tauri sendet immer; der Dev-Server nur `running`/`starting`/`found`/`path`. */+ starting?: boolean+ stalled?: boolean+ complete?: boolean+ /** `null`, solange kein Pfad gespeichert ist — auch bei `found: true`. */+ path?: string | null+ port?: number+ host?: string+ isLocal?: boolean+ }+-/** Antwort von `comfyui_last_output` (`process.rs:1968`). Alle drei Schluessel++/** Antwort von `comfyui_last_output` (`process.rs`). Alle vier Schluessel+ * immer gesetzt; `lines` ist `[]` statt `null`, wenn nichts anliegt. Im+ * Browser-Modus existiert die Route nicht, der Aufruf wirft dann. */+ interface ComfyLastOutput {+ lines: string[]+ exited: boolean+ envBroken: boolean++ /** Der Befund des Installers zu genau diesem Absturz, leer wenn er keinen++ * hat (Ticket 007). Er sticht den allgemeinen Reparatursatz, siehe++ * `comfyCrashAdvice`. */++ hint: string+ }+-/** Antwort von `python_check` (`install.rs:3886`). Der Fehlerzweig schreibt- * `path: null` ausdruecklich hin, laesst den Schluessel also nicht weg. */-interface PythonCheckResponse {- available: boolean- path: string | null-}--function ComfyUISettings() {+export function ComfyUISettings() {- const [status, setStatus] = useState<{ running: boolean; found: boolean; complete?: boolean; path?: string; port?: number; host?: string; isLocal?: boolean; starting?: boolean; stalled?: boolean } | null>(null)+ const [status, setStatus] = useState<ComfyStatusResponse | null>(null)// Why the last start attempt did not stick. The button used to swallow this// whole (E16): on a box with no ComfyUI python environment, Start answered// "started", the panel went back to `Stopped`, and six minutes later there@@@ -720,14 -492,13 +769,14 @@@// does nothing". Look once, a few seconds in, and say what happened.setTimeout(async () => {try {- const out = await backendCall<{ exited?: boolean; lines?: string[]; envBroken?: boolean; hint?: string }>('comfyui_last_output')+ const out = await backendCall<ComfyLastOutput>('comfyui_last_output')if (out?.exited && Array.isArray(out?.lines) && out.lines.length > 1) {- const { comfyStartupError } = await import('../create/experimental/comfyError')- setStartError(- comfyStartupError(out.lines) +- (out.envBroken ? '\n\nThe Python environment looks broken. Repair environment below rebuilds it in place; models, outputs and custom nodes are left alone.' : ''),- )+ // Ticket 007: welcher Satz unter die Ausgabe gehoert, entscheidet+ // comfyCrashAdvice fuer beide Oberflaechen. Vorher stand der+ // allgemeine Satz hier fest verdrahtet, und der konkrete Hinweis+ // aus dem Einordner des Installers erreichte den Kunden nie.+ const { comfyStartupError, comfyCrashAdvice } = await import('../create/experimental/comfyError')+ setStartError(comfyStartupError(out.lines, comfyCrashAdvice(out)))}} catch { /* status polling keeps the panel honest */ }}, 6000)diff --cc src/hooks/useAgentChat.tsindex 96692a2b,15e3490a..0c3a1e6b--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@@ -433,19 -472,19 +473,20 @@@ export function useAgentChat()if (chunks.length > 0) {try {const { context: ragContext } = await retrieveContext(userContent, chunks, ragState.embeddingModel)- if (ragContext.chunks.length > 0) {- const contextBlock = ragContext.chunks- .map((c, i) => `[Source ${i + 1}]\n${c.content}`)- .join('\n\n')- // Retrieval is the most volatile thing in the whole prompt:- // every turn pulls different chunks. In front of the persona it- // put a fresh byte at offset 0 and made the upstream prefix cache- // miss the ENTIRE prompt on every RAG turn, so it rides at the end- // now, behind persona and memory (plan A5).- ragSuffix = `\n\nUse the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---`- }+ // Same builder plain chat uses (lib/rag-prompt.ts), so the two+ // surfaces cannot drift apart. It rides at the END of the prompt,+ // behind persona and memory, because retrieval changes every turn and+ // at offset 0 it cost the upstream prefix cache the whole prompt- // (plan A5).++ // (plan A5). Empty in, empty out: a turn without a hit spends no++ // tokens on an instruction pointing at no context.+ ragSuffix = buildRagSuffix(ragContext.chunks)+ ragState.setRetrievalError(null)} catch (err) {log.error('RAG retrieval failed', { err })+ // Same statement plain chat makes (review S4). An agent run that+ // quietly lost its documents is worse, not better: it goes on to act+ // on what it did not read.+ ragState.setRetrievalError(RETRIEVAL_FAILED_MESSAGE)}}}diff --cc src/hooks/useCodex.tsindex 06850911,81133213..9277aa28--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@@ -254,11 -248,14 +256,14 @@@ export function useCodex()const [isRunning, setIsRunning] = useState(false)const abortRef = useRef<AbortController | null>(null)const runningRef = useRef(false)- /** True once the user pressed stop, so the /loop driver does not start- * another pass on the run they just killed. Cleared when a new run starts. */- const userStoppedRef = useRef(false)+ // "The user pressed stop" lives in lib/run-stop, keyed by conversation, NOT+ // in a ref of this hook instance. The Code view unmounts on every tab switch,+ // and the /loop driver's finally runs in the closure of the instance that+ // started the pass — a stop pressed by the remounted instance set a ref that+ // closure never reads, so the finally re-armed the loop the user had just+ // killed. The loop is uncapped by design; that made it unstoppable.- const sendInstruction = useCallback(async (+ const runInstruction = useCallback(async (rawInstruction: string,opts?: {displayContent?: string@@@ -355,57 -360,48 +369,64 @@@defaultWorkspace: settings.defaultWorkspace,})- // Init codex thread if needed- if (!codexStore.getThread(convId)) {- codexStore.initThread(convId, codexStore.workingDirectory || '.')+ // Init codex thread if needed. Read LIVE, never from the `codexStore`+ // snapshot taken at the top of this function: `resolveChatWorkspaceSlug`+ // above is IPC, and a Remove pressed during it used to be undone here by+ // a thread born with the old path (A8 review, B1).+ if (!useCodexStore.getState().getThread(convId)) {+ useCodexStore.getState().initThread(convId, useCodexStore.getState().workingDirectory)}+ // Pull THIS conversation's thread onto the folder the picker shows now.+ // Only this one: another chat's thread may carry a deliberate per-chat+ // workspace, and rewriting all of them took that away (A8 review, S5).+ const liveWorkingDir = useCodexStore.getState().syncThreadWorkingDirectory(convId)- const thread = codexStore.getThread(convId)!+ const thread = useCodexStore.getState().getThread(convId)!- const workspacePath =- codexWorkspace && codexWorkspace.kind === 'folder' && codexWorkspace.path- ? codexWorkspace.path- : null- // Precedence lives in src/lib/codex-workdir.ts, with its cases tested.- const workDir = resolveCodexWorkDir({- threadDir: thread.workingDirectory,- workspacePath,- storeDir: liveWorkingDir,+ // Welcher Ordner: Rangfolge, Sperre und die Zusicherung, dass beide- // denselben Pfad nennen — hooks/codex/workspace-precedence.ts.++ // denselben Pfad nennen, stehen in hooks/codex/workspace-precedence.ts.++ // Dort ist auch belegt, warum die Sperre auf DENSELBEN Ordner zeigen muss,++ // den der Systemprompt nennt (Live-Fund 2026-07-11: sonst scheitert jedes++ // file_list/file_read des Arbeitsverzeichnisses an "path escapes the++ // allowed workspace").++ //++ // Beide Eingaben werden LIVE gelesen, nie aus dem codexStore-Abzug vom++ // Anfang dieser Funktion: dazwischen liegt IPC, und ein waehrenddessen++ // gedruecktes Entfernen wurde von einem Abzug wieder aufgehoben++ // (A8-Durchsicht, B1).+ const { workDir, runWorkspace } = resolveCodexWorkspace({+ threadWorkingDirectory: thread.workingDirectory,+ codexWorkspace,- storeWorkingDirectory: codexStore.workingDirectory,++ storeWorkingDirectory: liveWorkingDir,})- // Pin the tool-containment workspace to the SAME folder the model is told- // to use (workDir). resolveWorkspace() above only sees the agent-mode- // per-chat store + settings.defaultWorkspace — it MISSES the folder the- // Code tab's explorer picker sets (codexStore.workingDirectory), which is- // the primary way to pick a repo in the Code tab. Without this, containment- // stayed pinned to the per-chat sandbox while the model was told to work in- // a real folder, so every file_list/file_read of the working dir failed- // with "path escapes the allowed workspace" (live cloud find, 2026-07-11).- const runWorkspace =- workDir && workDir !== '.'- ? {- kind: 'folder' as const,- path: workDir,- extraPaths: codexWorkspace && codexWorkspace.kind === 'folder' ? codexWorkspace.extraPaths : undefined,- }- : codexWorkspace-// `/goal` is bookkeeping, not a prompt. Handle it here and show the result;// every LATER turn picks the goal up from the system prompt below.- if (slash?.command.handledLocally && slash.command.name === 'goal') {- const res = applyGoalCommand(convId, slash.args)+ // /compact — a round trip, unlike /goal, but the same kind of branch: the+ // hook does the work and nothing is sent to the model as an instruction.+ // See lib/run-compact-command.ts for why it is a record and not an edit.+ if (slash?.command.handledLocally && slash.command.name === 'compact') {+ // BEIDE Zeilen sind App-Hinweise, keine Modell-Turns. Bis 2.6.8 standen+ // sie als user/assistant im Verlauf, und die Nutzlast filtert nur+ // `role:'system'` — also fuhr ein erfundener Assistentenzug+ // („Summarised 12 earlier messages …") in jede spaetere Anfrage mit und+ // wurde bei der naechsten Verdichtung als Protokoll mitzusammengefasst.+ // In der Claude-Code-Desktop-App erreichen Schraegstrich-Befehle das+ // Modell nie. Der Mechanismus dafuer gab es hier schon: `notice`.useChatStore.getState().addMessage(convId, {- id: uuid(), role: 'user', content: rawInstruction, timestamp: Date.now(),+ id: uuid(), role: 'system', notice: 'info', content: rawInstruction, timestamp: Date.now(),})+ const noticeId = uuid()useChatStore.getState().addMessage(convId, {- id: uuid(), role: 'assistant', content: res.message, timestamp: Date.now(),+ id: noticeId, role: 'system', notice: 'info',+ content: 'Summarising the earlier turns…', timestamp: Date.now(),+ })+ const outcome = await runCompactForConversation({+ conversationId: convId,+ activeModel: activeModel || '',+ trigger: 'manual',+ focus: slash.args || undefined,})+ useChatStore.getState().updateMessageContent(convId, noticeId, compactOutcomeMessage(outcome))return}diff --cc src/lib/chat-tool-intent.tsindex ad5b0a6b,88b3f7b8..27fad20d--- a/src/lib/chat-tool-intent.ts+++ b/src/lib/chat-tool-intent.ts@@@ -29,17 -29,15 +29,19 @@@ export const CHAT_TOOLS =export type ChatToolCapability = 'image' | 'video' | 'web' | 'file'/**- * Umlaute und ß auf ihre Ersatzschreibung bringen, BEVOR irgendein Muster- * greift (Persona B3, 03.09.2026).+ * Umlaute und Eszett auf ihre Ersatzschreibung bringen, BEVOR irgendein Muster- * greift (Persona-Lauf 03.09.2026).++ * greift (Persona-Lauf B3, 03.09.2026).*- * Die Persona tippte „woertlich" und „Ueberschrift" — deutsches Tippen ohne- * Umlaute, auf einer Tastatur ohne sie oder aus Gewohnheit. Wer so tippt,- * tippt ueberall so. Ein Muster, das auf „öffne" oder „gemälde" besteht,- * verfehlt dann jede einzelne Stelle. Deshalb wird EINMAL zentral normalisiert- * und jedes Muster unten in der Ersatzschreibung geschrieben; „öffne" und- * „oeffne" laufen danach durch dieselbe Zeile.+ * Zwei Gruende. Erstens tippen viele Leute deutsch ohne Umlaute, aus Gewohnheit- * oder auf fremder Tastatur; ein Muster, das auf "oeffne" in Umlautschreibung- * besteht, verfehlt die dann jedes Mal. Zweitens, und schlimmer: eine- * Wortgrenze vor einem Umlaut greift in JavaScript nie, weil Umlaute keine- * Wortzeichen sind. Das alte Muster fuer "oeffne" stand mit Wortgrenze davor- * und war damit toter Buchstabe, auch bei korrekter Schreibung. Deshalb wird- * EINMAL zentral normalisiert und jedes Muster unten in der Ersatzschreibung- * gefuehrt.++ * oder auf einer Tastatur ohne sie; die Persona tippte "woertlich" und++ * "Ueberschrift", und wer so tippt, tippt ueberall so. Ein Muster, das auf++ * "oeffne" oder "gemaelde" in Umlautschreibung besteht, verfehlt dann jede++ * einzelne Stelle. Zweitens, und schlimmer: eine Wortgrenze vor einem Umlaut++ * greift in JavaScript nie, weil Umlaute keine Wortzeichen sind. Das alte++ * Muster fuer "oeffne" stand mit Wortgrenze davor und war damit toter++ * Buchstabe, auch bei korrekter Schreibung. Deshalb wird EINMAL zentral++ * normalisiert und jedes Muster unten in der Ersatzschreibung gefuehrt;++ * "oeffne" in beiden Schreibweisen laeuft danach durch dieselbe Zeile.*/export function entumlauten(s: string): string {return s@@@ -54,15 -52,15 +56,16 @@@ const lower = (s: string) => entumlaute// A bare URL or an explicit "open/read this page" → web_fetch territory.const URL_RE = /\bhttps?:\/\/\S+|\bwww\.\S+|\b[a-z0-9-]+\.(com|org|net|io|dev|ai|de|co|gov|edu|app|news)\b(\/\S*)?/i//-// Die deutsche Verbliste kannte lange nur oeffne/lies/fasse/ruf…auf. Eine-// Persona tippte am 03.09.2026 zweimal „Hol bitte die Seite …" und bekam-// beide Male gar kein `tools`-Feld im Payload, waehrend derselbe Satz auf-// Englisch sauber lief. Das Verb, das man am ehesten tippt, fehlte schlicht.-// Der Wortstamm steht deshalb jetzt an einer Stelle und wird unten zweimal-// verwendet — sonst waechst die eine Liste und die andere nicht mit.+// Die deutsche Verbliste kannte lange nur oeffne/lies/fasse/ruf...auf, und die+// URL-Regel darunter fuehrte eine zweite, kuerzere Kopie davon. Eine Persona+// tippte am 03.09.2026 zweimal "Hol bitte die Seite ..." und bekam beide Male+// gar kein tools-Feld im Payload, waehrend derselbe Satz auf Englisch sauber+// lief. Das Verb, das man am ehesten tippt, fehlte schlicht in beiden Listen.- // Der Wortstamm steht deshalb jetzt an genau einer Stelle.++// Der Wortstamm steht deshalb jetzt an genau einer Stelle und wird unten++// zweimal verwendet, sonst waechst die eine Liste und die andere nicht mit.const WEB_ZUGRIFF_VERBEN ='open|read|fetch|scrape|summari[sz]e|get|visit|check|' +- // Trennbare Verben: im Deutschen steht die Vorsilbe am Satzende („Ruf die+ // Trennbare Verben: im Deutschen steht die Vorsilbe am Satzende ("Ruf die// Webseite example.com AUF"), das alte Muster verlangte sie direkt hinter// dem Verb und traf damit nur unnatuerliche Saetze.'oeffne|lies|lese|fasse|zusammenfass\\w*|ruf(e|st|t)?|auf-?ruf\\w*|hol(e|st|t)?|abruf\\w*|' +@@@ -99,14 -97,14 +102,14 @@@ const LOOKUP_TOPIC_RE = /\b(weather|tem// Verbs that inherently mean "make an image" even without a media noun// ("draw a cat", "zeichne eine Blume").-// „mal" ohne Endung ist im Deutschen meistens gar kein Verb, sondern die-// Partikel: „erklaer mir mal", „sag mal", „schau mal". Als Malen-Befehl zaehlt-// es deshalb nur am SATZANFANG, wo es wirklich Befehlsform ist („Mal eine-// Blume"). Vorher hijackte jede beilaeufige deutsche Frage die Bildgenerierung-// — und ein Fehlalarm ist teuer: der Zug laeuft dann durch den+// "mal" ohne Endung ist im Deutschen meistens gar kein Verb, sondern die- // Partikel: "erklaer mir mal", "sag mal", "warte mal". Als Malen-Befehl zaehlt- // es deshalb nur am SATZANFANG, wo es wirklich Befehlsform ist ("Mal eine- // Blume"). Vorher kaperte jede beilaeufige deutsche Frage die Bildgenerierung,- // und ein Fehlalarm ist teuer: der Zug laeuft dann durch den++// Partikel: "erklaer mir mal", "sag mal", "schau mal", "warte mal". Als++// Malen-Befehl zaehlt es deshalb nur am SATZANFANG, wo es wirklich Befehlsform++// ist ("Mal eine Blume"). Vorher kaperte jede beilaeufige deutsche Frage die++// Bildgenerierung, und ein Fehlalarm ist teuer: der Zug laeuft dann durch den// Werkzeug-Ausfuehrer, woran sich kleine Modelle nachweislich verschlucken.-// „Mal mir ein Bild" bleibt auch mitten im Satz erkannt, das faengt die-// Verb+Substantiv-Regel darunter.+// "Mal mir ein Bild" bleibt auch mitten im Satz erkannt, das faengt die+// Verb-plus-Substantiv-Regel darunter.const INHERENT_IMAGE_VERB_RE = /\b(draw|sketch|paint|illustrate|mal(e|en)|zeichne(n|st)?|skizzier\w*)\b|^\s*mal\b/i// Image / video creation: a creation verb co-occurring with a media noun.diff --cc src/stores/__tests__/uiStore-explorer.test.tsindex 0411b446,4540c806..b5a2d1f5--- a/src/stores/__tests__/uiStore-explorer.test.ts+++ b/src/stores/__tests__/uiStore-explorer.test.ts@@@ -4,14 -4,8 +4,17 @@@* This store was NOT persisted before. It carries currentView and* cloudGateOpen, so a naive persist would change what the app does on start:* it would reopen on whatever tab was left behind, or come up with the cloud- * gate on screen. partialize therefore has to hold EXACTLY the two explorer- * fields, and this test is the guard on that word "exactly".+ * gate on screen. partialize therefore has to hold EXACTLY the fields that+ * are a stated preference, and this test is the guard on that word "exactly".+ *- * Widened in the web-parity round (2.6.8): sidebarOpen joined the written set.- * It is the user saying "rail" or "list", the same class of choice as- * explorerCollapsed, and forgetting it on every restart is the bug David- * reported. currentView / cloudGateOpen / cloudTeaser stay forbidden, because- * those steer where the app STARTS rather than how it looks.++ * Widened twice for 2.6.8. The web-parity round put sidebarOpen into the++ * written set: it is the user saying "rail" or "list", the same class of++ * choice as explorerCollapsed, and forgetting it on every restart is the bug++ * David reported. The design round added the agent panel's two geometry++ * fields and sidebarWidth, the dragged width of the left chat column (D1).++ * Six fields in total. currentView / cloudGateOpen / cloudTeaser stay++ * forbidden, because those steer where the app STARTS rather than how it++ * looks.** Run: npx vitest run src/stores/__tests__/uiStore-explorer.test.ts*/@@@ -48,11 -42,35 +51,34 @@@ import} from '../uiStore'describe('what the ui store writes to disk', () => {- it('persists exactly explorerWidth, explorerCollapsed and sidebarOpen', () => {- it('persistiert genau die fuenf Geometriefelder der drei Flaechen', () => {- // 2.6.8: das Agenten-Panel bringt seine zwei mit. Die Liste bleibt- // ausgeschrieben und wird nicht aus dem Zustand abgeleitet — sie ist eine- // ERLAUBNIS, keine Beschreibung. Jedes weitere Feld hier muss jemand- // hinschreiben und dabei begruenden, warum es einen Neustart ueberleben- // soll; das ist der ganze Zweck dieser Zeile.++ it('persists exactly the six preference fields of the three panels', () => {++ // Die Liste bleibt ausgeschrieben und wird nicht aus dem Zustand++ // abgeleitet, sie ist eine ERLAUBNIS und keine Beschreibung. Jedes weitere++ // Feld hier muss jemand hinschreiben und dabei begruenden, warum es einen++ // Neustart ueberleben soll; das ist der ganze Zweck dieser Zeile.+ //+ // Was ausdruecklich NICHT dazugehoert: die Aufgaben selbst. Die liegen in+ // agentTaskStore und werden gar nicht persistiert, weil eine+ // wiederhergestellte Zeile mit "laeuft" ueber den Zustand der Maschine- // luegen wuerde — samt einem Abbrechen-Knopf, der nichts mehr abbricht.++ // luegen wuerde, samt einem Abbrechen-Knopf, der nichts mehr abbricht.+ //- // 02.09.2026, das fuenfte Feld — und hier steht die Begruendung, die diese- // Liste verlangt: `sidebarWidth` ist die gezogene Breite der Chatspalte- // links (D1, David: "bzw dynamisch mit vergroesserung anpassend"). Sie- // gehoert in dieselbe Klasse wie die anderen vier: eine VORLIEBE ueber die- // Geometrie, die niemand nach jedem Start neu einstellen will. Sie steuert- // keinen Startzustand — die Spalte kommt so breit zurueck, wie der Mensch- // sie gezogen hat, und das ist das ganze Versprechen.++ // 2.6.8 bringt das Agenten-Panel seine zwei Felder mit, dazu kommt++ // `sidebarWidth`: die gezogene Breite der Chatspalte links (D1, David:++ // "bzw dynamisch mit vergroesserung anpassend"). Sie gehoert in dieselbe++ // Klasse wie die Geometrie der anderen Flaechen, eine VORLIEBE, die++ // niemand nach jedem Start neu einstellen will.+ //- // `sidebarOpen` steht dagegen weiter im Gegentest unten: OB die Spalte- // offen ist, entscheidet der Start, nicht das Gedaechtnis.++ // `sidebarOpen` steht seit der Web-Paritaetsrunde ebenfalls hier und nicht++ // mehr im Gegentest unten: OB die Spalte offen ist, ist "Schiene" oder++ // "Liste" und damit dieselbe Klasse Vorliebe wie explorerCollapsed. Das++ // Vergessen bei jedem Start war der Fehler, den David gemeldet hat.const partialize = useUIStore.persist.getOptions().partializeexpect(partialize).toBeTypeOf('function')const written = partialize!(useUIStore.getState()) as Record<string, unknown>- expect(Object.keys(written).sort()).toEqual(['explorerCollapsed', 'explorerWidth', 'sidebarOpen'])+ expect(Object.keys(written).sort()).toEqual([+ 'agentPanelCollapsed', 'agentPanelWidth', 'explorerCollapsed', 'explorerWidth',- 'sidebarWidth',++ 'sidebarOpen', 'sidebarWidth',+ ])})it('counter-test: nothing that steers the app start comes along', () => {@@@ -66,20 -83,36 +92,36 @@@expect(Object.values(written).every((v) => typeof v !== 'function')).toBe(true)})- it('keeps writing only those three after the state moved', () => {- useUIStore.setState({ currentView: 'settings', cloudGateOpen: true, explorerCollapsed: true, explorerWidth: 333, sidebarOpen: true })- it('schreibt auch nach einer Zustandsaenderung nur diese fuenf', () => {++ it('keeps writing only those six after the state moved', () => {+ useUIStore.setState({+ currentView: 'settings', cloudGateOpen: true,+ explorerCollapsed: true, explorerWidth: 333,+ agentPanelCollapsed: false, agentPanelWidth: 222,- sidebarWidth: 310,++ sidebarWidth: 310, sidebarOpen: true,+ })const written = useUIStore.persist.getOptions().partialize!(useUIStore.getState()) as Record<string, unknown>- expect(written).toEqual({ explorerWidth: 333, explorerCollapsed: true, sidebarOpen: true })+ expect(written).toEqual({+ explorerWidth: 333, explorerCollapsed: true,+ agentPanelWidth: 222, agentPanelCollapsed: false,- sidebarWidth: 310,++ sidebarWidth: 310, sidebarOpen: true,+ })})- it('und genau das landet auch wirklich im Speicher', () => {- useUIStore.setState({ currentView: 'benchmark', cloudGateOpen: true })+ it('and that is what actually lands in storage', () => {+ useUIStore.setState({ currentView: 'benchmark', cloudGateOpen: true, sidebarOpen: false })useUIStore.getState().setExplorerWidth(420, 1600)useUIStore.getState().setExplorerCollapsed(true)+ useUIStore.getState().setAgentPanelWidth(260, 1600)+ useUIStore.getState().setAgentPanelCollapsed(false)+ useUIStore.getState().setSidebarWidth(310, 1600)const raw = memory.getItem('locally-uncensored-ui')expect(raw).toBeTruthy()const parsed = JSON.parse(raw!)- expect(parsed.state).toEqual({ explorerWidth: 420, explorerCollapsed: true, sidebarOpen: false })+ expect(parsed.state).toEqual({+ explorerWidth: 420, explorerCollapsed: true,+ agentPanelWidth: 260, agentPanelCollapsed: false,- sidebarWidth: 310,++ sidebarWidth: 310, sidebarOpen: false,+ })})})diff --cc src/stores/modelStore.tsindex aa94cf56,b2c070ec..0afc00c1--- a/src/stores/modelStore.ts+++ b/src/stores/modelStore.ts@@@ -8,7 -9,16 +9,17 @@@ import { isLmStudioProvider } from '../import { isTauri, backendCall } from '../api/backend'import { useChatStore } from './chatStore'import { log } from '../lib/logger'+import { isLuEngineName } from '../lib/engine-name'+ // Which provider slot a model name routes to. There is exactly one answer to-// that question in this app and it lives in api/providers/registry — the same++// that question in this app and it lives in api/providers/registry, the same+ // function getProviderForModel uses to pick the client that actually sends the+ // turn. A second implementation here disagreed with it on real names+ // ('sdxl::x.safetensors' → null vs 'sdxl', 'a::b::c' → null vs 'ollama'), which+ // is the worst possible place for two answers: the guard below would decline to+ // clear a pick that the send path would then route to a dead backend.+ import { getProviderIdFromModel } from '../api/providers/model-name'+ import { onProviderSlotsDarkened } from '../lib/provider-slot-darkening'+ import type { ProviderId } from '../api/providers/types'export interface PullState {progress: PullProgress@@@ -165,15 -181,15 +183,22 @@@ export const useModelStore = create<Mod} else if (name) {// built-in → DIFFERENT built-in: llama-server serves exactly ONE// gguf and ignores the request's model field, and the send-path-- // self-heal only revives a DEAD server — so without a swap right++ // self-heal only revives a DEAD server, so without a swap right// here, a pick on the Models page would keep every chat silently// answering from the OLD model. The composer picker awaits this-- // same call itself before setting the store; Rust's argv-- // idempotence turns that double-swap into a no-op. (A cleared-- // selection, name = null, has nothing to swap to; nextIsBuiltin-- // is false then anyway, this branch just spells it out for tsc.)++ // same call itself before setting the store, so every activation++ // reaches the engine twice. Rust's argv idempotence swallows the++ // second call only for a model that LOADS: a GGUF that fails to++ // load leaves no running engine to compare argv against, and the++ // second command runs the whole try-and-retry routine again (four++ // llama-server spawns per click, measured 2026-09-03). The++ // coalescing that makes the double call harmless therefore lives++ // in api/engine.ts (activationsInFlight), at the one door both++ // callers come through. (A cleared selection, name = null, has++ // nothing to swap to; nextIsBuiltin is false then anyway, this++ // branch just spells it out for tsc.)activateBuiltinModel(name).catch((e) =>- log.warn('[modelStore] failed to swap built-in engine to the picked model', { model: name, err: e }),+ log.warn('[modelStore] failed to swap the LU Engine to the picked model', { model: name, err: e }),)}} else if (!prev.includes('::')) {@@@ -267,3 -295,13 +304,13 @@@}))+-// Audit W-T2: Der providerStore hat sich diesen Store früher selbst geholt++// Audit W-T2: Der providerStore hat sich diesen Store frueher selbst geholt+ // (`void import('./modelStore')`), um bei abgeschalteten Slots die Modellwahl-// zu räumen — ein dynamischer Import, der den Kreis providerStore ↔ modelStore-// nur verdeckt hat. Jetzt wird dort angesagt und hier zugehört; die Anmeldung-// passiert beim Laden dieses Moduls, wie registerBuiltinTools() sich beim-// Tool-Registry anmeldet.++// zu raeumen, ein dynamischer Import, der den Kreis providerStore zu++// modelStore und zurueck nur verdeckt hat. Jetzt wird dort angesagt und hier++// zugehoert; die Anmeldung passiert beim Laden dieses Moduls, wie++// registerBuiltinTools() sich beim Tool-Registry anmeldet.+ onProviderSlotsDarkened((darkened) => {+ for (const id of darkened) useModelStore.getState().dropActiveModelIfServedBy(id)+ })diff --cc src/stores/providerStore.tsindex a9816b80,6c577e42..80bce370--- a/src/stores/providerStore.ts+++ b/src/stores/providerStore.ts@@@ -7,10 -7,12 +7,13 @@@import { create } from 'zustand'import { persist } from 'zustand/middleware'+ import { keepPersistedState } from '../lib/persist-version'+ import { safeJSONStorage } from '../lib/storage-quota'import type { ProviderId, ProviderConfig } from '../api/providers/types'- import { clearProviderCache } from '../api/providers/registry'+ import { clearProviderCache } from '../api/providers/client-cache'import { onLocalSlotChanged } from '../lib/builtin-slot-eviction'+import { LU_ENGINE_NAME, renameLegacyEngine } from '../lib/engine-name'+ import { announceDarkenedSlots } from '../lib/provider-slot-darkening'import { secretGet, secretSet, secretDelete } from '../api/backend'import { CLOUD_BASE } from '../api/cloud/config'@@@ -100,6 -102,46 +103,46 @@@ const DEFAULT_PROVIDERS: Record<Provide},}+ /**+ * The model/provider invariant, asked on EVERY path that can switch a slot off.+ *+ * A slot going dark makes the picked model unservable, and nothing used to+ * notice: the pick is only re-validated against the next NON-EMPTY model list,+ * so until a refresh lands the composer offers a model whose backend is off and+ * every send fails with model-not-found.+ *+ * It hung off `setProviderConfig` alone, which is only the explicit toggle.+ * `resetProvidersToDefaults` ("Reset AI Backends", a button in Settings) writes- * DEFAULT_PROVIDERS over the whole map — Ollama and Anthropic default to- * `enabled: false` — so a user whose pick was an Ollama model reached exactly++ * DEFAULT_PROVIDERS over the whole map, where Ollama and Anthropic default to++ * `enabled: false`, so a user whose pick was an Ollama model reached exactly+ * the same broken state through a supported, one-click, non-exotic path.+ * `resetProvider` does the same for one slot.+ *- * Audit W-T2: hier stand `void import('./modelStore')` mit der Begründung++ * Audit W-T2: hier stand `void import('./modelStore')` mit der Begruendung+ * "modelStore reaches back here through chatStore/remoteStore, and a static- * edge would close that circle at module-init time". Die Begründung stimmte,- * die Auflösung nicht: der dynamische Import hat den Kreis nicht geöffnet,- * sondern nur unsichtbar gemacht (providerStore → modelStore → engine →- * providerStore, und providerStore → modelStore → chatStore → remoteStore →- * providerStore).++ * edge would close that circle at module-init time". Die Begruendung stimmte,++ * die Aufloesung nicht: der dynamische Import hat den Kreis nicht geoeffnet,++ * sondern nur unsichtbar gemacht (providerStore -> modelStore -> engine ->++ * providerStore, und providerStore -> modelStore -> chatStore -> remoteStore++ * -> providerStore).+ *- * Dieser Store hat kein Geschäft damit, den Modell-Store zu kennen. Er weiß- * nur, welche Slots gerade dunkel geworden sind — und sagt es an. Wer darauf++ * Dieser Store hat kein Geschaeft damit, den Modell-Store zu kennen. Er weiss++ * nur, welche Slots gerade dunkel geworden sind, und sagt es an. Wer darauf+ * reagieren will, meldet sich an; die Leitung dazwischen steht in- * lib/provider-slot-darkening.ts, gehört keinem der beiden Stores und schließt- * damit keinen Kreis.++ * lib/provider-slot-darkening.ts, gehoert keinem der beiden Stores und++ * schliesst damit keinen Kreis.+ */+ function dropPicksForDarkenedSlots(+ before: Partial<Record<ProviderId, ProviderConfig>>,+ after: Partial<Record<ProviderId, ProviderConfig>>,+ ): void {+ announceDarkenedSlots(+ (Object.keys(after) as ProviderId[]).filter(+ (id) => before[id]?.enabled === true && after[id]?.enabled === false,+ ),+ )+ }+// ── Store Interface ────────────────────────────────────────────interface ProviderState {diff --cc src/stores/ragStore.tsindex 69de901b,82a3c172..c09bb2b3--- a/src/stores/ragStore.ts+++ b/src/stores/ragStore.ts@@@ -43,9 -39,16 +44,17 @@@ interface RAGStatesetIndexing: (indexing: boolean) => voidsetIndexingProgress: (progress: { current: number; total: number } | null) => voidclearConversationDocs: (conversationId: string) => void+ /** Everything this conversation owns, gone: the document list, the RAG+ * toggle, the in-memory chunks and their 768-float vectors in IndexedDB.+ * clearConversationDocs empties the document array but LEAVES the two keys+ * behind, which is right while the chat still exists and wrong once it does+ * not — a deleted chat's entry would sit in `documents` forever and its+ * vectors would keep being exported to rag_chunks_backup.json every 30 s for+ * the lifetime of the installation. */+ removeConversation: (conversationId: string) => voidsetLastRetrievedChunks: (chunks: { chunk: TextChunk; score: number }[]) => voidsetContextWarning: (warning: string | null) => void+ setRetrievalError: (message: string | null) => voidsetPullingEmbeddingModel: (pulling: boolean) => voidsetEmbeddingPullProgress: (p: { completed: number; total: number; status: string } | null) => voidsetEmbeddingInstallPrompt: (prompt: boolean) => voiddiff --cc src/stores/settingsStore.tsindex ef62e3f0,13f966cb..38c60508--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@@ -1,8 -1,9 +1,10 @@@import { create } from 'zustand'import { persist } from 'zustand/middleware'+ import { safeJSONStorage } from '../lib/storage-quota'import type { Settings, Persona } from '../types/settings'import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'+import { isEffortLevel } from '../lib/effort'+ import { isRecord, asString } from '../types/json-guards'// v5 (Feature EE v2.5.0): added settings.exclusiveVramMode. The migrate below// already merges { ...DEFAULT_SETTINGS, ...persisted.settings }, so bumping the@@@ -159,30 -154,22 +161,40 @@@ export const useSettingsStore = create<}),{name: 'chat-settings',+ storage: safeJSONStorage(),version: STORE_VERSION,+ // The ONE guard for the rung, and it sits here rather than in migrate+ // above on purpose: migrate does not run for a blob that is already at+ // STORE_VERSION, where the persisted settings object is swapped in+ // wholesale. This runs on every rehydration, so it covers both, and a+ // second copy in migrate would be a guard no test can fail.+ //+ // reasoningEffort has a closed set of values. A profile written by a+ // build that spelled the rung differently, or edited by hand, would+ // otherwise travel through the whole app as an unknown word and the+ // composer would draw a rung the provider does not send. isEffortLevel is+ // the question, 'high' is the answer, and it is the answer a fresh+ // install gets.+ onRehydrateStorage: () => (state) => {+ if (!state?.settings) return+ if (!isEffortLevel(String(state.settings.reasoningEffort))) {+ state.settings.reasoningEffort = DEFAULT_SETTINGS.reasoningEffort+ }+ },- migrate: (persisted: any, version: number) => {+ migrate: (persisted: unknown, version: number): SettingsState => {- // Foreign at read time — an older build wrote this. A read that throws++ // Foreign at read time, an older build wrote this. A read that throws+ // in a migrate costs the whole store: zustand abandons hydration and+ // the next write persists the empty default over the blob, which here+ // would mean every setting AND every custom persona.+ const blob = isRecord(persisted) ? persisted : {}if (version < STORE_VERSION) {- const customPersonas = (persisted.personas || []).filter((p: Persona) => !p.isBuiltIn)+ const storedPersonas = Array.isArray(blob.personas) ? blob.personas : []+ const customPersonas = storedPersonas.filter(+ (p): p is Persona => isRecord(p) && p.isBuiltIn !== true,+ )// Merge new default settings into existing (fills missing fields like thinkingEnabled)- const mergedSettings = { ...DEFAULT_SETTINGS, ...(persisted.settings || {}) }+ const storedSettings = isRecord(blob.settings) ? blob.settings : {}+ const mergedSettings = { ...DEFAULT_SETTINGS, ...storedSettings }// v10: clear the saved model-picker preferences ONCE so the picker is// shown first again on image + video (David 2026-06-16). The additive// merge above would otherwise preserve a previously-saved pick.diff --cc src/stores/uiStore.tsindex a1239ca7,2347dba1..a1bfbf30--- a/src/stores/uiStore.ts+++ b/src/stores/uiStore.ts@@@ -45,6 -46,64 +46,64 @@@ export function clampExplorerWidth(widtreturn Math.round(Math.min(Math.max(width, EXPLORER_MIN_WIDTH), max))}+ /**+ * Geometrie des Agenten-Panels (2.6.8).+ *+ * Schmaler als der Explorer: dort steht ein verschachtelter Pfad, hier eine+ * Zielzeile und ein Zustand. 240 statt 280, Boden 180.+ *+ * Die Klemme ist bewusst DIESELBE Rechnung wie beim Explorer und keine+ * gemeinsame Funktion mit zwei Parametersaetzen: die beiden Panels teilen+ * heute die Regel "nie mehr als das halbe Fenster", aber nicht ihren Grund.+ * Ein Explorer darf breit werden, weil Pfade lang sind; dieses Panel soll es+ * gar nicht wollen. Eine geteilte Funktion haette die zweite Begruendung+ * unsichtbar gemacht.+ */+ export const AGENT_PANEL_DEFAULT_WIDTH = 240+ export const AGENT_PANEL_MIN_WIDTH = 180++ export function clampAgentPanelWidth(width: number, viewportWidth: number): number {+ if (!Number.isFinite(width)) return AGENT_PANEL_DEFAULT_WIDTH+ const half = Math.floor((Number.isFinite(viewportWidth) ? viewportWidth : 0) / 2)+ const max = Math.max(AGENT_PANEL_MIN_WIDTH, half)+ return Math.round(Math.min(Math.max(width, AGENT_PANEL_MIN_WIDTH), max))+ }++ /**+ * Geometrie der Chatspalte links (D1, 02.09.2026).+ *+ * David: "Der left Sidepanel bei Chat Agent und Code ist Textmaessig als+ * Sessionname und Datum nicht sauber bis zum Ende durchgezogen bzw dynamisch+ * mit vergroesserung anpassend." Die erste Haelfte war der harte+ * `truncate(title, 30)` in der Zeile, den der CSS-Schnitt ersetzt hat. Die+ * zweite konnte gar nicht erfuellt sein: die Spalte war auf 250 px+ * festgenagelt, es gab also keine Vergroesserung, an die sich etwas haette- * anpassen koennen. `--ui-scale` hilft nicht — `zoom` skaliert Kasten und Text- * gemeinsam und aendert das VERHAELTNIS nicht.++ * anpassen koennen. `--ui-scale` hilft nicht, denn `zoom` skaliert Kasten und++ * Text gemeinsam und aendert das VERHAELTNIS nicht.+ *+ * EIN DRITTEL statt der Haelfte, die Explorer und Agenten-Panel nehmen, und- * das ist keine Nachlaessigkeit: die beiden sind ARBEITSFLAECHEN — ein++ * das ist keine Nachlaessigkeit: die beiden sind ARBEITSFLAECHEN, ein+ * verschachtelter Pfad darf lang sein, eine Agentenzeile auch. Diese Spalte+ * ist NAVIGATION. Eine Navigation, die das halbe Fenster nimmt, hat den Zweck+ * verfehlt, fuer den man sie aufzieht.+ *+ * Dazu eine absolute Decke: ein Sitzungsname braucht nie mehr als 480 px, und- * auf einem 4K-Schirm waere ein Drittel sonst ueber 1200 px — eine Zahl, die++ * auf einem 4K-Schirm waere ein Drittel sonst ueber 1200 px, eine Zahl, die+ * nur entsteht, weil niemand sie aufgeschrieben hat.+ */+ export const SIDEBAR_DEFAULT_WIDTH = 250+ export const SIDEBAR_MIN_WIDTH = 200+ export const SIDEBAR_MAX_WIDTH = 480++ export function clampSidebarWidth(width: number, viewportWidth: number): number {+ if (!Number.isFinite(width)) return SIDEBAR_DEFAULT_WIDTH+ const third = Math.floor((Number.isFinite(viewportWidth) ? viewportWidth : 0) / 3)+ // Der Boden gewinnt gegen das Drittel: in einem sehr schmalen Fenster fiele+ // die Spalte sonst zusammen, und dann sind die Zeilen gar nicht mehr lesbar.+ const max = Math.max(SIDEBAR_MIN_WIDTH, Math.min(third, SIDEBAR_MAX_WIDTH))+ return Math.round(Math.min(Math.max(width, SIDEBAR_MIN_WIDTH), max))+ }+interface UIState {currentView: ViewsidebarOpen: boolean@@@ -118,17 -190,24 +197,29 @@@ export const useUIStore = create<UIStat}),{name: 'locally-uncensored-ui',- // The two explorer fields (plan C3 / R1) plus sidebarOpen. Persisting- // this store naively would carry currentView and cloudGateOpen across- // restarts: the app would reopen on whatever tab was left behind, or- // come up with the cloud gate on screen. Those stay out.- // sidebarOpen joined in the web-parity round: it is a stated preference- // ("I want the rail" / "I want the list"), not a leftover of one- // session, and the app would forget it on every restart otherwise.+ storage: safeJSONStorage(),- // EXACTLY the two explorer fields (plan C3 / R1). This store was not- // persisted at all before, and persisting it naively would carry- // currentView and cloudGateOpen across restarts: the app would reopen on- // whatever tab was left behind, or come up with the cloud gate on screen.++ // What survives a restart is a stated PREFERENCE, never a leftover of++ // one session. currentView and cloudGateOpen stay out: the app would++ // otherwise reopen on whatever tab was left behind, or come up with the++ // cloud gate on screen.partialize: (state) => ({++ // The two explorer fields (plan C3 / R1).explorerWidth: state.explorerWidth,explorerCollapsed: state.explorerCollapsed,++ // Joined in the web-parity round: the rail-or-list choice is a stated++ // preference ("I want the rail" / "I want the list"), and the app++ // would forget it on every restart otherwise.+ sidebarOpen: state.sidebarOpen,+ // 2.6.8: die zwei Felder des Agenten-Panels. Geometrie ist eine+ // Vorliebe und ueberlebt einen Neustart; die AUFGABEN selbst tun das- // ausdruecklich nicht (siehe agentTaskStore) — ein wiederhergestelltes++ // ausdruecklich nicht (siehe agentTaskStore), ein wiederhergestelltes+ // "laeuft" waere eine Luege ueber den Zustand der Maschine.+ agentPanelWidth: state.agentPanelWidth,+ agentPanelCollapsed: state.agentPanelCollapsed,+ // Dieselbe Begruendung: eine gezogene Spaltenbreite ist eine Vorliebe.+ // Ohne diese Zeile waere jede Ziehbewegung beim naechsten Start- // vergessen — der haeufigste Weg, so eine Funktion nutzlos zu machen.++ // vergessen, der haeufigste Weg, so eine Funktion nutzlos zu machen.+ sidebarWidth: state.sidebarWidth,}),},),diff --cc src/stores/workflowStore.tsindex 195541d3,ca5c9af1..9ccfd772--- a/src/stores/workflowStore.ts+++ b/src/stores/workflowStore.ts@@@ -511,15 -439,7 +512,16 @@@ export const useWorkflowStore = create<}),{name: 'workflow-store',+ storage: safeJSONStorage(),+ // The key is kept OUT of localStorage as soon as the OS vault has+ // proven itself and holds it. Until then, and on a host without one,+ // nothing changes: dropping it there would lose the key instead of+ // protecting it.+ partialize: (state) => {+ if (!civitaiVaultReady || civitaiVaultFailed) return state+ const { civitaiApiKey: _inTheVault, ...rest } = state+ return rest as WorkflowState+ },},),)