From d71eb8253c3f3077146a15019e9fc3b8274642e5 Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 02:53:02 +0800 Subject: [PATCH 1/9] fix(desktop): update localmodels to 0.1.0.dev40 0.1.0.dev40 replaces a Pi that cannot load extensions when the stack is applied again, reports it in setup binding as pi-extensions-unavailable, fails harness apply with RUNTIME_ACTION_FAILED or RUNTIME_EXTENSIONS_FAILED instead of exiting 0 after an incomplete install, refuses an unusable SIMPLEX_PI_PATH and a too-long Windows runtime root at plan time, reports GPU and free-memory shortfalls with byte figures, and stops the library Bifrost on stack down. - Pin 0.1.0.dev40 in the three desktop distributions and in scripts/installs/stack.sh and stack.ps1, copied from the published launchers; the three tool archives and both launchers were checked against the release's SHA256 and size. - Point the run-without-cloning URLs in scripts/installs/README.md at the pinned version, and sync the stack pins in scripts/install with scripts/sync-install-stack-pin.mjs. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/distribution/darwin-arm64.json | 10 ++-- apps/desktop/distribution/linux-x64.json | 10 ++-- apps/desktop/distribution/win32-x64.json | 10 ++-- scripts/install/install.ps1 | 4 +- scripts/install/install.sh | 4 +- scripts/installs/README.md | 8 +-- scripts/installs/stack.ps1 | 66 ++++++++++----------- scripts/installs/stack.sh | 22 +++---- 8 files changed, 67 insertions(+), 67 deletions(-) diff --git a/apps/desktop/distribution/darwin-arm64.json b/apps/desktop/distribution/darwin-arm64.json index d6c637ad..391fb54b 100644 --- a/apps/desktop/distribution/darwin-arm64.json +++ b/apps/desktop/distribution/darwin-arm64.json @@ -2,11 +2,11 @@ "platform": "darwin", "arch": "arm64", "localmodelsTool": { - "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev39/darwin-arm64.tgz", - "sha256": "e15c1d96c4db70cc834b42693228c6b6bbe7eb575e79d19e8aff2f0bf8ba6e48", - "bytes": 14937177, - "sourceCommit": "9a72159a9c114e323de703fcbf6e030fbf7d480a", - "manifestSha256": "b9f750c55834913394ebc459395f5331915d02d98ebeecee3586fb1721a7bc41" + "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev40/darwin-arm64.tgz", + "sha256": "648e8909915d8da2b87ae4f4797cd22f2d46d8a7cd025287ab9e6b5436119687", + "bytes": 14953559, + "sourceCommit": "a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d", + "manifestSha256": "15f7138847ef4d13f9c2df455ec04423dc35d30d759d5f952dcb0b69d81db13b" }, "nativeSources": [ { diff --git a/apps/desktop/distribution/linux-x64.json b/apps/desktop/distribution/linux-x64.json index a425f170..ad7b3ee7 100644 --- a/apps/desktop/distribution/linux-x64.json +++ b/apps/desktop/distribution/linux-x64.json @@ -2,11 +2,11 @@ "platform": "linux", "arch": "x64", "localmodelsTool": { - "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev39/linux-x64.tgz", - "sha256": "f58f55f94e3559ffd959af9e9f44663a41ec34aef53a1c2d1ff7279ec207af3a", - "bytes": 20776267, - "sourceCommit": "9a72159a9c114e323de703fcbf6e030fbf7d480a", - "manifestSha256": "60664ab53e44b9967bf21e54a2e2fb263862296537ebd24691ab96e7ed268336" + "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev40/linux-x64.tgz", + "sha256": "a8e176fa426360f489bf9c552064faf7e1dd88072b463a13185ff1193a223683", + "bytes": 20790291, + "sourceCommit": "a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d", + "manifestSha256": "d36a909ddad7be0de0642766102a5478efd22d7d437c86d8b63ac7bddc24e082" }, "nativeSources": [ { diff --git a/apps/desktop/distribution/win32-x64.json b/apps/desktop/distribution/win32-x64.json index f20abd5f..26966b59 100644 --- a/apps/desktop/distribution/win32-x64.json +++ b/apps/desktop/distribution/win32-x64.json @@ -2,11 +2,11 @@ "platform": "win32", "arch": "x64", "localmodelsTool": { - "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev39/win32-x64.tgz", - "sha256": "492ed40845a7d732f077b575c7ef4d75f06965c991e5e2c4c0e9f356ed0da37f", - "bytes": 23174114, - "sourceCommit": "9a72159a9c114e323de703fcbf6e030fbf7d480a", - "manifestSha256": "f17122b311b71a3b37e3207a2c0cdce6f84b3a14e09ef0bceed81be74e90e161" + "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/0.1.0.dev40/win32-x64.tgz", + "sha256": "de07306075b5efbf2158c41a7c87fe4939bac45b9b6f953270ed00017a6540be", + "bytes": 23191788, + "sourceCommit": "a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d", + "manifestSha256": "c7e2fab80d7aa2bdf52975a0b6e180611830a5d3c013bb302d16ff5c3c0d42dd" }, "nativeSources": [ { diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1 index 0d46b2e9..98a48d67 100644 --- a/scripts/install/install.ps1 +++ b/scripts/install/install.ps1 @@ -167,8 +167,8 @@ $script:PowerShellExe = (Get-Process -Id $PID).Path $script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false) $script:TempDirsToClean = New-Object System.Collections.Generic.List[string] # >>> stack release pin -$script:StackPinNpmVersion = '0.1.0-dev.39' -$script:StackPinSha256 = '089102538c287af8bc156a5b3c9b90815b39392b86e1ac0deb2bae2a6f9ff80c' +$script:StackPinNpmVersion = '0.1.0-dev.40' +$script:StackPinSha256 = '04fff205b3ac826caacb8df2e20c7f11f4a10a0fbdd81e4d254d9e3d136b503a' # <<< stack release pin $script:StackScriptPath = '' $script:KitHome = '' diff --git a/scripts/install/install.sh b/scripts/install/install.sh index f1e15011..270f08b3 100755 --- a/scripts/install/install.sh +++ b/scripts/install/install.sh @@ -42,8 +42,8 @@ KIT_PYTHON="" PROMPT_VALUE="" # >>> stack release pin -STACK_PIN_NPM_VERSION='0.1.0-dev.39' -STACK_PIN_SHA256='49280238b7e92972addad17436f81890ce4d19f78d3d0652b73c1e1c745a3e55' +STACK_PIN_NPM_VERSION='0.1.0-dev.40' +STACK_PIN_SHA256='f4bc079520e73fdde9f15fe050397a46cde27fcc1941702b70dd8c287b1b57ee' # <<< stack release pin usage() { diff --git a/scripts/installs/README.md b/scripts/installs/README.md index a4a0f660..496315ae 100644 --- a/scripts/installs/README.md +++ b/scripts/installs/README.md @@ -89,15 +89,15 @@ Run the pinned script without cloning the repository: ```sh # global -curl -fsSL https://cdn.jsdelivr.net/npm/@simplexai/localmodels@0.1.0-dev.39/stack.sh | sh -s -- --region global --help +curl -fsSL https://cdn.jsdelivr.net/npm/@simplexai/localmodels@0.1.0-dev.40/stack.sh | sh -s -- --region global --help # cn -curl -fsSL https://registry.npmmirror.com/@simplexai/localmodels/0.1.0-dev.39/files/stack.sh | sh -s -- --region cn --help +curl -fsSL https://registry.npmmirror.com/@simplexai/localmodels/0.1.0-dev.40/files/stack.sh | sh -s -- --region cn --help ``` ```powershell -irm https://cdn.jsdelivr.net/npm/@simplexai/localmodels@0.1.0-dev.39/stack.ps1 -OutFile stack.ps1 +irm https://cdn.jsdelivr.net/npm/@simplexai/localmodels@0.1.0-dev.40/stack.ps1 -OutFile stack.ps1 powershell -ExecutionPolicy Bypass -File .\stack.ps1 -Region global --help -# cn script URL: https://registry.npmmirror.com/@simplexai/localmodels/0.1.0-dev.39/files/stack.ps1 +# cn script URL: https://registry.npmmirror.com/@simplexai/localmodels/0.1.0-dev.40/files/stack.ps1 ``` The localmodels release process publishes each version's platform kits, its patched Bifrost packages and the diff --git a/scripts/installs/stack.ps1 b/scripts/installs/stack.ps1 index 3492c67e..2d7422e3 100644 --- a/scripts/installs/stack.ps1 +++ b/scripts/installs/stack.ps1 @@ -3,59 +3,59 @@ $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' # >>> release pin -$StackVersion = '0.1.0.dev39' -$StackSourceCommit = '9a72159a9c114e323de703fcbf6e030fbf7d480a' -$StackNpmVersion = '0.1.0-dev.39' +$StackVersion = '0.1.0.dev40' +$StackSourceCommit = 'a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d' +$StackNpmVersion = '0.1.0-dev.40' $StackKits = @{ - 'darwin-arm64' = 'e15c1d96c4db70cc834b42693228c6b6bbe7eb575e79d19e8aff2f0bf8ba6e48' - 'darwin-x64' = 'fc534f42b813cf5bf391ee007fe860ac76063e06af3bfc18d5d6256479137cf5' - 'linux-arm64' = '37ab1c50f7269c65c70e5956b7e1b7a2ec9ce8286bb55046de1b15a6b3c9907a' - 'linux-x64' = 'f58f55f94e3559ffd959af9e9f44663a41ec34aef53a1c2d1ff7279ec207af3a' - 'win32-x64' = '492ed40845a7d732f077b575c7ef4d75f06965c991e5e2c4c0e9f356ed0da37f' + 'darwin-arm64' = '648e8909915d8da2b87ae4f4797cd22f2d46d8a7cd025287ab9e6b5436119687' + 'darwin-x64' = 'eac7027d9746eaa61b1d4309e934ef437a01a79e915171704f04539c6275f3f0' + 'linux-arm64' = '4963f4c71dcf05bb8d55e19dd6f1441c5cd5b099e62b30b9b2fbba80cdddaa3c' + 'linux-x64' = 'a8e176fa426360f489bf9c552064faf7e1dd88072b463a13185ff1193a223683' + 'win32-x64' = 'de07306075b5efbf2158c41a7c87fe4939bac45b9b6f953270ed00017a6540be' } $StackBootstrap = @{ 'darwin-arm64' = @{ - manifest = 'b9f750c55834913394ebc459395f5331915d02d98ebeecee3586fb1721a7bc41' - inventory = '3076b6da1fec8727cef3de7187d0ab2818a768e77131952577ebb484d5abd2bc' - bytes = '14937177' - files = '1368' - entries = '1508' + manifest = '15f7138847ef4d13f9c2df455ec04423dc35d30d759d5f952dcb0b69d81db13b' + inventory = 'ecd1dc2a81dbf53803af4669ffb00d31476dced14049e9889beaf4967b7f1dfb' + bytes = '14953559' + files = '1370' + entries = '1510' python = 'python/bin/python3.12' modules = 'modules' } 'darwin-x64' = @{ - manifest = 'c147e254cdf01e8666c69c9e95d6983ea9bbc9c1124f2ad12b3495a4ddc3bd7f' - inventory = '0271d1b25459a9e82ecc6ba99987783650a206ec5280e5818245d47912c03c99' - bytes = '14770496' - files = '1365' - entries = '1504' + manifest = '86fd2f7ad8133e40d507d0a0e09fc860a22108c9d5a6a23d7edd2cdad64318a7' + inventory = '67a3967cf2fb0b062ab0f97b8e7356b85ac28e278fa4d8edd4ef32183d76e1a9' + bytes = '14787792' + files = '1367' + entries = '1506' python = 'python/bin/python3.12' modules = 'modules' } 'linux-arm64' = @{ - manifest = '56ffd15353a55ca0bd9fb847924feada7b9dbd13516ace7f33c6da88a710ad61' - inventory = '8635d2b5765f4bc77582df25099623e9b0cbbe85ae0171f25a395bda6e263dc6' - bytes = '17446785' - files = '4239' - entries = '4423' + manifest = 'e47a45bb030e4d427fcb750df08daa9ccf5f8af6ea67bee395af85ebdf35f455' + inventory = 'e9ed54c5e579d05096f8d8943bcede0488701e5497d468b42e1cc2dd4580a446' + bytes = '17460592' + files = '4241' + entries = '4425' python = 'python/bin/python3.12' modules = 'modules' } 'linux-x64' = @{ - manifest = '60664ab53e44b9967bf21e54a2e2fb263862296537ebd24691ab96e7ed268336' - inventory = '8157380689477b6835695adb0f3bb9e0d0fed5f9bf29586496b8b123088bbed0' - bytes = '20776267' - files = '4239' - entries = '4423' + manifest = 'd36a909ddad7be0de0642766102a5478efd22d7d437c86d8b63ac7bddc24e082' + inventory = '435ed71955a8dc0415cd35579637a35772f44e753e814e34818b38ba60516211' + bytes = '20790291' + files = '4241' + entries = '4425' python = 'python/bin/python3.12' modules = 'modules' } 'win32-x64' = @{ - manifest = 'f17122b311b71a3b37e3207a2c0cdce6f84b3a14e09ef0bceed81be74e90e161' - inventory = 'ce4acb03a685e8e2756656d6d50e491d168c3659ce89882e8f83aff0df2cbc7e' - bytes = '23174114' - files = '3409' - entries = '3676' + manifest = 'c7e2fab80d7aa2bdf52975a0b6e180611830a5d3c013bb302d16ff5c3c0d42dd' + inventory = 'd079da0a54acd521f1b4ace18cea5d4d2a078ff50637266a3982ad43cda0273a' + bytes = '23191788' + files = '3411' + entries = '3678' python = 'python/python.exe' modules = 'modules' } diff --git a/scripts/installs/stack.sh b/scripts/installs/stack.sh index 196ed7e3..f9947752 100755 --- a/scripts/installs/stack.sh +++ b/scripts/installs/stack.sh @@ -2,13 +2,13 @@ set -eu # >>> release pin -STACK_VERSION='0.1.0.dev39' -STACK_SOURCE_COMMIT='9a72159a9c114e323de703fcbf6e030fbf7d480a' -STACK_NPM_VERSION='0.1.0-dev.39' -STACK_KIT_darwin_arm64='e15c1d96c4db70cc834b42693228c6b6bbe7eb575e79d19e8aff2f0bf8ba6e48' -STACK_KIT_darwin_x64='fc534f42b813cf5bf391ee007fe860ac76063e06af3bfc18d5d6256479137cf5' -STACK_KIT_linux_arm64='37ab1c50f7269c65c70e5956b7e1b7a2ec9ce8286bb55046de1b15a6b3c9907a' -STACK_KIT_linux_x64='f58f55f94e3559ffd959af9e9f44663a41ec34aef53a1c2d1ff7279ec207af3a' +STACK_VERSION='0.1.0.dev40' +STACK_SOURCE_COMMIT='a4de3e359d2a4f9b654f9ae7bdf6887c55896b7d' +STACK_NPM_VERSION='0.1.0-dev.40' +STACK_KIT_darwin_arm64='648e8909915d8da2b87ae4f4797cd22f2d46d8a7cd025287ab9e6b5436119687' +STACK_KIT_darwin_x64='eac7027d9746eaa61b1d4309e934ef437a01a79e915171704f04539c6275f3f0' +STACK_KIT_linux_arm64='4963f4c71dcf05bb8d55e19dd6f1441c5cd5b099e62b30b9b2fbba80cdddaa3c' +STACK_KIT_linux_x64='a8e176fa426360f489bf9c552064faf7e1dd88072b463a13185ff1193a223683' # <<< release pin die() { @@ -46,10 +46,10 @@ esac manifest='' inventory='' bytes='' files='' entries='' python='' modules='' # >>> bootstrap targets case "$target" in - darwin-arm64) manifest='b9f750c55834913394ebc459395f5331915d02d98ebeecee3586fb1721a7bc41'; inventory='3076b6da1fec8727cef3de7187d0ab2818a768e77131952577ebb484d5abd2bc'; bytes='14937177'; files='1368'; entries='1508'; python='python/bin/python3.12'; modules='modules' ;; - darwin-x64) manifest='c147e254cdf01e8666c69c9e95d6983ea9bbc9c1124f2ad12b3495a4ddc3bd7f'; inventory='0271d1b25459a9e82ecc6ba99987783650a206ec5280e5818245d47912c03c99'; bytes='14770496'; files='1365'; entries='1504'; python='python/bin/python3.12'; modules='modules' ;; - linux-arm64) manifest='56ffd15353a55ca0bd9fb847924feada7b9dbd13516ace7f33c6da88a710ad61'; inventory='8635d2b5765f4bc77582df25099623e9b0cbbe85ae0171f25a395bda6e263dc6'; bytes='17446785'; files='4239'; entries='4423'; python='python/bin/python3.12'; modules='modules' ;; - linux-x64) manifest='60664ab53e44b9967bf21e54a2e2fb263862296537ebd24691ab96e7ed268336'; inventory='8157380689477b6835695adb0f3bb9e0d0fed5f9bf29586496b8b123088bbed0'; bytes='20776267'; files='4239'; entries='4423'; python='python/bin/python3.12'; modules='modules' ;; + darwin-arm64) manifest='15f7138847ef4d13f9c2df455ec04423dc35d30d759d5f952dcb0b69d81db13b'; inventory='ecd1dc2a81dbf53803af4669ffb00d31476dced14049e9889beaf4967b7f1dfb'; bytes='14953559'; files='1370'; entries='1510'; python='python/bin/python3.12'; modules='modules' ;; + darwin-x64) manifest='86fd2f7ad8133e40d507d0a0e09fc860a22108c9d5a6a23d7edd2cdad64318a7'; inventory='67a3967cf2fb0b062ab0f97b8e7356b85ac28e278fa4d8edd4ef32183d76e1a9'; bytes='14787792'; files='1367'; entries='1506'; python='python/bin/python3.12'; modules='modules' ;; + linux-arm64) manifest='e47a45bb030e4d427fcb750df08daa9ccf5f8af6ea67bee395af85ebdf35f455'; inventory='e9ed54c5e579d05096f8d8943bcede0488701e5497d468b42e1cc2dd4580a446'; bytes='17460592'; files='4241'; entries='4425'; python='python/bin/python3.12'; modules='modules' ;; + linux-x64) manifest='d36a909ddad7be0de0642766102a5478efd22d7d437c86d8b63ac7bddc24e082'; inventory='435ed71955a8dc0415cd35579637a35772f44e753e814e34818b38ba60516211'; bytes='20790291'; files='4241'; entries='4425'; python='python/bin/python3.12'; modules='modules' ;; *) die 'release lacks bootstrap pins' ;; esac # <<< bootstrap targets From 03945dbff437e390e3c03fcfeca53cca5fd20b77 Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:27:24 +0800 Subject: [PATCH 2/9] fix(local-installation): end the services a failed install attempt leaves behind A start whose lease identity could not be proved left its supervisor and service running with no record, so PostgreSQL kept postmaster.pid and every Try Again failed until the processes were killed by hand. - When a start fails before its record is kept and the lease cannot be proved, end the process group of the supervisor it spawned and has not reaped yet; that PID cannot belong to another program. - On macOS and Linux, reclaimNativeOrphans now also ends a supervisor whose command line names a job file in the instance's process directory under a lease no record holds, once its environment proves the lease; the services step runs it before PostgreSQL starts, so a state an earlier release left heals on the next attempt. - Split the POSIX stop of one lease out of stopNativeProcess to share it. Co-Authored-By: Claude Opus 5.5 --- packages/local-installation/AGENTS.md | 10 +- .../src/native-process-unverified.test.ts | 71 +++++++++++ .../src/native-process.test.ts | 34 +++++ .../local-installation/src/native-process.ts | 119 ++++++++++++++++-- .../local-installation/src/native-source.ts | 7 +- .../local-installation/src/source-checkout.ts | 2 +- 6 files changed, 229 insertions(+), 14 deletions(-) create mode 100644 packages/local-installation/src/native-process-unverified.test.ts diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md index 03e51376..1935e102 100644 --- a/packages/local-installation/AGENTS.md +++ b/packages/local-installation/AGENTS.md @@ -137,7 +137,15 @@ program fails the start after 15 seconds instead of at the deadline. On POSIX, a start that finds the recorded supervisor gone but processes still carrying its lease (the app was killed with it) ends them as a stop does and starts the service again. A live recorded PID or process group -without the lease proves nothing and is refused, never signalled. +without the lease proves nothing and is refused, never signalled. A start +that fails before its record is kept ends what it launched: by the lease, +or, when the lease cannot be proved, by the group of the supervisor it has +not reaped yet, whose PID cannot belong to another program. Before the +services start, `reclaimNativeOrphans` also ends, on POSIX, a supervisor +whose command line names a job file in this instance's process directory +under a lease no record holds, once its environment proves that lease; an +attempt that failed or was killed before keeping a record would otherwise +leave PostgreSQL holding `postmaster.pid` against every retry. Move a freshly downloaded or unpacked file or folder into place with `renameRetrying` from `fs-retry.ts`: on Windows antivirus and indexing hold diff --git a/packages/local-installation/src/native-process-unverified.test.ts b/packages/local-installation/src/native-process-unverified.test.ts new file mode 100644 index 00000000..a5da2d35 --- /dev/null +++ b/packages/local-installation/src/native-process-unverified.test.ts @@ -0,0 +1,71 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { expect, onTestFinished, test, vi } from "vitest"; + +// Every identity check fails, as a localized `ps` once made them on macOS: +// neither the supervisor nor what it started can be proved by its lease. +vi.mock("./native-process-identity.js", async (original) => ({ + ...(await original()), + nativeProcessIdentity: async () => undefined, + nativeLeaseProcesses: async () => [], +})); +const { startNativeProcess } = await import("./native-process.js"); + +vi.setConfig({ testTimeout: 30_000, expect: { poll: { timeout: 15_000 } } }); + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + if (process.platform === "linux") + return !execFileSync("cat", [`/proc/${pid}/stat`], { encoding: "utf8" }) + .replace(/^.*\) /s, "") + .startsWith("Z"); + return true; + } catch { + return false; + } +} + +(process.platform === "win32" ? test.skip : test)( + "ends the launched supervisor and its service when their identity cannot be verified", + async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-unverified-")); + onTestFinished(async () => { + try { + execFileSync("pkill", ["-KILL", "-f", root]); + } catch { + // pkill exits 1 when nothing matched. + } + await rm(root, { recursive: true, force: true }); + }); + await expect( + startNativeProcess({ + root, + name: "postgres", + executable: process.execPath, + args: [ + "-e", + "require('node:fs').writeFileSync('service.pid',String(process.pid));setInterval(()=>{},1000)", + // Names the root on its command line, so the check below finds it. + root, + ], + cwd: root, + env: process.env, + }), + ).rejects.toThrow("Native postgres identity could not be verified."); + const service = Number( + await readFile(path.join(root, "service.pid"), "utf8").catch(() => "0"), + ); + // A service left running here held postmaster.pid against every retry. + if (service) await expect.poll(() => alive(service)).toBe(false); + await expect + .poll(() => + execFileSync("ps", ["-axo", "stat=,command="], { encoding: "utf8" }) + .split("\n") + .filter((line) => line.includes(root) && !/^\s*Z/.test(line)), + ) + .toEqual([]); + }, +); diff --git a/packages/local-installation/src/native-process.test.ts b/packages/local-installation/src/native-process.test.ts index 6a46b42b..4f22b8e9 100644 --- a/packages/local-installation/src/native-process.test.ts +++ b/packages/local-installation/src/native-process.test.ts @@ -24,6 +24,7 @@ import { nativeConfigurationChanged, startNativeProcess, inspectNativeProcess, + reclaimNativeOrphans, stopNativeProcess, } from "./native-process.js"; @@ -245,6 +246,39 @@ test("stops descendants that ignore SIGINT after the service leader exits", asyn }, ); +(process.platform === "win32" ? test.skip : test)( + "reclaims a service an earlier attempt left under a lease no record holds", + async (context) => { + const { expect } = context; + const root = await fixture(context); + const service = (name: "web" | "teamhub") => ({ + root, + name, + executable: process.execPath, + args: [ + "-e", + `require('node:fs').writeFileSync('${name}.pid',String(process.pid));setInterval(()=>{},1000)`, + ], + cwd: root, + env: process.env, + }); + const lost = await startNativeProcess(service("web")); + const kept = await startNativeProcess(service("teamhub")); + const pid = async (name: string) => + Number(await readFile(path.join(root, `${name}.pid`), "utf8")); + await expect.poll(() => pid("web").catch(() => 0)).not.toBe(0); + await expect.poll(() => pid("teamhub").catch(() => 0)).not.toBe(0); + // The attempt that started it failed before its record was kept. + await rm(path.join(root, "native/processes/web.json")); + const ended = await reclaimNativeOrphans(root, { ports: [], paths: [] }); + expect(ended).toContain(lost.pid); + await expect.poll(async () => exited(await pid("web"))).toBe(true); + expect(exited(lost.pid!)).toBe(true); + expect(exited(kept.pid!)).toBe(false); + expect(exited(await pid("teamhub"))).toBe(false); + }, +); + test("cleans the launched owned group when identity persistence fails", async (context) => { const { expect } = context; const root = await fixture(context); diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.ts index 46e5ac23..489afffd 100644 --- a/packages/local-installation/src/native-process.ts +++ b/packages/local-installation/src/native-process.ts @@ -1,4 +1,4 @@ -import { spawn } from "node:child_process"; +import { spawn, type ChildProcess } from "node:child_process"; import { existsSync } from "node:fs"; import { readFile, rm } from "node:fs/promises"; import { createHash, randomBytes } from "node:crypto"; @@ -396,6 +396,11 @@ export async function startNativeProcess(options: { { cause: error }, ); } + // When the lease could not be proved, the supervisor this call spawned + // and has not reaped is still provably its own, and so is the group it + // leads: end them, or the service keeps its files (postmaster.pid) and + // ports against every retry. + await endUnreapedGroup(child); if (child.connected) child.disconnect(); child.unref(); throw error; @@ -404,6 +409,33 @@ export async function startNativeProcess(options: { } } +/** + * Ends the process group a detached child leads while the child is not yet + * reaped: until then its PID, and so its group, cannot belong to another + * program. + */ +async function endUnreapedGroup(child: ChildProcess): Promise { + if (child.pid === undefined) return; + const exited = new Promise((resolve) => child.once("exit", resolve)); + if (child.exitCode === null && child.signalCode === null) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } + await Promise.race([exited, delay(5_000)]); + } + // The leader's exit does not wait for the rest of its group. + for (let count = 0; count < 50 && (await groupLive(child.pid)); count++) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } + await delay(100); + } +} + /** * Marks a stop refused because the recorded PID now belongs to another * program: none of the service's own processes are left. @@ -417,11 +449,20 @@ export async function stopNativeProcess( ): Promise { const record = await stored(root, name); if (!record) return; - if (process.platform === "win32") { + if (process.platform === "win32") await stopWindowsTree(name, record.lease, record); - await rm(paths(root, name).record, { force: true }); - return; - } + else await stopLease(name, record, interruptMs); + await rm(paths(root, name).record, { force: true }); +} +/** + * macOS and Linux: ends the supervisor holding the lease and everything + * under it, SIGINT first and SIGKILL for what outlives `interruptMs`. + */ +async function stopLease( + name: NativeService, + record: Pick, + interruptMs: number, +): Promise { const current = await observed(record.pid, record.lease); let owned = await nativeLeaseProcesses(record.lease); if (current !== record.birth && !owned.length) { @@ -432,7 +473,6 @@ export async function stopNativeProcess( ), { code: NATIVE_PROCESS_REPLACED }, ); - await rm(paths(root, name).record, { force: true }); return; } const signalOwned = async ( @@ -496,7 +536,6 @@ export async function stopNativeProcess( (await nativeLeaseProcesses(record.lease)).length ) throw new Error(`Native ${name} did not stop; identity record retained.`); - await rm(paths(root, name).record, { force: true }); } function terminate(pid: number) { @@ -664,14 +703,14 @@ export function windowsOrphans( return order; } /** - * Ends what `windowsOrphans` finds for this instance; nothing elsewhere. + * Ends what `windowsOrphans` finds for this instance on Windows, and what + * `reclaimUnrecordedLeases` finds on macOS and Linux; nothing elsewhere. * Returns the PIDs it ended. */ export async function reclaimNativeOrphans( root: string, options: { ports: number[]; paths: string[] }, ): Promise { - if (process.platform !== "win32") return []; const records: Lease[] = []; for (const name of services) try { @@ -680,6 +719,8 @@ export async function reclaimNativeOrphans( } catch { // A damaged record proves nothing; its supervisor counts as unrecorded. } + if (process.platform !== "win32") + return reclaimUnrecordedLeases(root, records); const ended: number[] = []; const deadline = Date.now() + 12_000; for (;;) { @@ -709,3 +750,63 @@ export async function reclaimNativeOrphans( await delay(100); } } + +/** Each process of this user with its command line (macOS and Linux). */ +async function ownCommands(): Promise> { + if (process.platform === "linux") { + const listed = await Promise.all( + (await linuxProcessStates(true)).map(async ({ pid, state }) => { + if (state === "Z") return undefined; + const command = await readFile(`/proc/${pid}/cmdline`, "utf8").catch( + () => "", + ); + return { pid, command: command.split("\0").join(" ") }; + }), + ); + return listed.filter((entry) => entry !== undefined); + } + const result = await runProcess("/bin/ps", ["-axo", "pid=,uid=,command="], { + timeoutMs: 5_000, + }); + if (result.code !== 0) + throw new Error("Native processes could not be enumerated."); + return result.stdout.split("\n").flatMap((line) => { + const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line); + return match && Number(match[2]) === process.getuid?.() + ? [{ pid: Number(match[1]), command: match[3]! }] + : []; + }); +} +/** + * macOS and Linux: ends the services an earlier attempt started and kept no + * record of (it failed or was killed before writing one), which otherwise + * keep their files and ports, such as PostgreSQL's postmaster.pid, against + * every retry. A supervisor is this instance's own when its command line + * names a job file in this instance's process directory and its environment + * carries that job's unguessable lease. Returns the supervisors it ended. + */ +async function reclaimUnrecordedLeases( + root: string, + records: Array>, +): Promise { + const recorded = new Set(records.map((record) => record.lease)); + const jobs = path.join(root, "native", "processes") + path.sep; + const ended: number[] = []; + for (const { pid, command } of await ownCommands()) { + if (!command.includes(SUPERVISOR)) continue; + const at = command.indexOf(jobs); + const job = + at < 0 + ? undefined + : /^([a-z-]+)\.([a-f0-9]{64})\.job(?:\s|$)/.exec( + command.slice(at + jobs.length), + ); + if (!job || !services.has(job[1]!) || recorded.has(job[2]!)) continue; + const [, name, lease] = job as unknown as [string, NativeService, string]; + const birth = await observed(pid, lease); + if (!birth) continue; + await stopLease(name, { pid, birth, lease }, 12_000); + ended.push(pid); + } + return ended; +} diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts index 885f727a..72f058db 100644 --- a/packages/local-installation/src/native-source.ts +++ b/packages/local-installation/src/native-source.ts @@ -1121,9 +1121,10 @@ async function runNativeSource( } } /** - * Windows: ends the processes of this instance an earlier run lost track of - * (an earlier release's stop left them, or their supervisor died), so they - * neither hold the ports nor answer health checks for the new services. + * Ends the processes of this instance an earlier run lost track of (an + * earlier release's stop left them, their supervisor died, or a failed + * attempt kept no record of them), so they neither hold the ports and data + * files nor answer health checks for the new services. */ async function reclaimEarlierProcesses( instance: Instance, diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.ts index 0bf68db6..6f3f7081 100644 --- a/packages/local-installation/src/source-checkout.ts +++ b/packages/local-installation/src/source-checkout.ts @@ -228,7 +228,7 @@ export async function prepareSourceConfiguration( (await portFree(port)) ) continue; - // On Windows the program may be one an earlier run left behind. + // The program may be one an earlier run left behind. await reclaimNativeOrphans(instance.root, { ports: [port], paths: [path.resolve(instance.root, "../.."), instance.root, repo], From 7ffa735cda4164ba1dd40851736ed1369629a94f Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:27:38 +0800 Subject: [PATCH 3/9] fix(local-installation): apply the approved local model plan again when the stack is not ready A launch that found the local model stack not ready failed with LOCAL_MODELS_RECOVERY_REQUIRED and asked to review an updated plan, which the start failure page cannot do; Try Again failed the same way and Set Up Again was the only way out. A 0.1.3 Pi installed without extension support reports pi-extensions-unavailable from localmodels 0.1.0.dev40 the same way. - When the saved binding for the approved plan is not ready and the saved plan inputs still match, apply that plan again and bind once it verifies; changed inputs still need a new review. The binding's reason codes go out in details.reasons and to the installer log. - The desktop's start failure words the first known reason code and names the action that works for LOCAL_MODELS_RECOVERY_REQUIRED (Try Again) and LOCAL_MODELS_APPROVAL_REQUIRED (Set Up Again). - Map localmodels harness errors to structured failures: a refused harness plan (unusable SIMPLEX_PI_PATH, a Windows runtime root too long for Pi without long paths) is RUNTIME_PLAN_REFUSED, and RUNTIME_ACTION_FAILED and RUNTIME_EXTENSIONS_FAILED keep their codes through dependency preparation and into the failed job's errorCode. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/AGENTS.md | 7 +- apps/desktop/src/main/local-server.test.ts | 59 ++++++++- apps/desktop/src/main/local-server.ts | 54 ++++++++- apps/linger-installer/AGENTS.md | 13 +- apps/linger-installer/src/server/jobs.test.ts | 20 ++++ apps/linger-installer/src/server/jobs.ts | 9 +- .../src/dependencies.test.ts | 39 +++++- .../local-installation/src/dependencies.ts | 10 +- .../src/local-models.test.ts | 112 +++++++++++++++++- .../local-installation/src/local-models.ts | 110 +++++++++++------ .../src/managed-runtimes.test.ts | 61 ++++++++++ .../src/managed-runtimes.ts | 49 ++++++-- 12 files changed, 479 insertions(+), 64 deletions(-) diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index b82fc3cf..5d73b0b4 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -185,7 +185,12 @@ Gateway and runs Agents. The daemon exits with the app. from their folder, the record keeps naming it, and the start failure page's Retry moves them again. An app older than the recorded version (a downgrade) leaves the services on their newer source and logs - `local_server.source_newer_than_app`. A Quick Install that stopped + `local_server.source_newer_than_app`. When the local model stops a resume, + the start failure names the stack's first known binding reason code + (`details.reasons`, such as `pi-extensions-unavailable`) in its own words + and, by `details.code`, the action that works: Try Again for + `LOCAL_MODELS_RECOVERY_REQUIRED` (the resume applies the approved plan + again), Set Up Again to review a new plan or choose another runtime. A Quick Install that stopped before the computer enrolled is not resumed: setup shows again and Install finishes it, reusing a finished job only while its origin answers (a stopped server gets a new job, which starts the services again). The start failure diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts index 65b421c0..7e8cf16d 100644 --- a/apps/desktop/src/main/local-server.test.ts +++ b/apps/desktop/src/main/local-server.test.ts @@ -134,7 +134,10 @@ if (args.includes("--resume")) { const repo = args[args.indexOf("--source-repo") + 1]; const servingFile = path.join(home, "resume-serving"); const source = fs.existsSync(servingFile) ? fs.readFileSync(servingFile, "utf8") : fs.existsSync(repo) ? fs.realpathSync(repo) : repo; - process.stdout.write("noise\n" + JSON.stringify({ code, message: code ? "Native teamhub stopped" : "ok", details: { source }, ...(runtime ? { runtime } : {}) }) + "\n"); + // resume-fails may hold the failed outcome's message and details. + const failure = code ? fs.readFileSync(path.join(home, "resume-fails"), "utf8").trim() : ""; + const outcome = failure ? JSON.parse(failure) : { message: code ? "Native teamhub stopped" : "ok", details: { source } }; + process.stdout.write("noise\n" + JSON.stringify({ code, ...outcome, ...(runtime ? { runtime } : {}) }) + "\n"); process.exit(code); } const origin = "http://127.0.0.1:4321"; @@ -2659,6 +2662,60 @@ describe("LocalServerModule after a restart", () => { await f.host.stop("quit"); }); + it.each([ + [ + "LOCAL_MODELS_RECOVERY_REQUIRED", + "Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.", + ], + [ + "LOCAL_MODELS_APPROVAL_REQUIRED", + "Set Up Again to review the local model plan or choose another AI runtime.", + ], + ])( + "names the action that works when the local model stops a restart (%s)", + async (code, action) => { + const f = fixture({}, enrolled, (home) => { + record(home); + writeFileSync( + path.join(home, "resume-fails"), + JSON.stringify({ + message: "The local model stack is not ready.", + details: { code }, + }), + ); + }); + await f.host.start(); + await vi.waitFor(() => expect(f.module.status().phase).toBe("failed")); + expect(f.showStartFailed).toHaveBeenCalledWith( + `The local model stack is not ready. ${action}`, + ); + await f.host.stop("quit"); + }, + ); + + it("says why the local model stack is not ready, from its reason code", async () => { + const f = fixture({}, enrolled, (home) => { + record(home); + writeFileSync( + path.join(home, "resume-fails"), + JSON.stringify({ + message: + "The upstream tool could not verify the local stack binding.", + details: { + code: "LOCAL_MODELS_RECOVERY_REQUIRED", + reasons: ["pi-extensions-unavailable", "gateway-unavailable"], + }, + }), + ); + }); + await f.host.start(); + await vi.waitFor(() => expect(f.module.status().phase).toBe("failed")); + expect(f.showStartFailed).toHaveBeenCalledWith( + "The local model's Pi can't load extensions, which every Linger run needs. The upstream tool could not verify the local stack binding. Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.", + ); + await f.host.stop("quit"); + }); + it("starts the services again when the person tries again", async () => { const f = fixture({}, enrolled, (home) => { record(home); diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts index d69e59d1..fe3c4b11 100644 --- a/apps/desktop/src/main/local-server.ts +++ b/apps/desktop/src/main/local-server.ts @@ -2326,7 +2326,7 @@ export class LocalServerModule implements Module { const outcome = await new Promise<{ code: number; message: string; - details?: { source?: unknown }; + details?: { source?: unknown; code?: unknown; reasons?: unknown }; runtime?: InstanceRuntime; }>((resolve, reject) => { const child = spawn( @@ -2363,7 +2363,7 @@ export class LocalServerModule implements Module { JSON.parse(last) as { code: number; message: string; - details?: { source?: unknown }; + details?: { source?: unknown; code?: unknown; reasons?: unknown }; runtime?: InstanceRuntime; }, ); @@ -2372,8 +2372,29 @@ export class LocalServerModule implements Module { } }); }); - if (outcome.code !== 0) - throw new Error(outcome.message || "The installation stopped"); + if (outcome.code !== 0) { + const { code, reasons } = outcome.details ?? {}; + const action = + typeof code === "string" && Object.hasOwn(RESUME_ACTIONS, code) + ? RESUME_ACTIONS[code] + : undefined; + const reason = Array.isArray(reasons) + ? reasons.find( + (item): item is string => + typeof item === "string" && + Object.hasOwn(LOCAL_MODEL_NOT_READY, item), + ) + : undefined; + throw new Error( + [ + reason && LOCAL_MODEL_NOT_READY[reason], + outcome.message || "The installation stopped", + action, + ] + .filter(Boolean) + .join(" "), + ); + } this.#adoptRuntime(outcome.runtime); const source = outcome.details?.source; return typeof source === "string" ? source : undefined; @@ -2667,6 +2688,31 @@ const LOCAL_MODEL_FAILURES = new Set([ "GPU_SHARING_REVOCATION_FAILED", ]); +// What works from the start-failure page when the local model stops a +// restart: a restart applies the approved plan again, but only setup can +// approve a new one or switch the runtime. +const RESUME_ACTIONS: Record = { + LOCAL_MODELS_RECOVERY_REQUIRED: + "Try Again to apply the approved local model plan again, or Set Up Again to review a new plan or choose another AI runtime.", + LOCAL_MODELS_APPROVAL_REQUIRED: + "Set Up Again to review the local model plan or choose another AI runtime.", +}; + +// Why the local model stack was not ready, by the reason code localmodels' +// setup binding gives. +const LOCAL_MODEL_NOT_READY: Record = { + "pi-extensions-unavailable": + "The local model's Pi can't load extensions, which every Linger run needs.", + "deployment-unavailable": "The local model service isn't running.", + "acceptance-unavailable": "The local model stack hasn't passed its checks.", + "gateway-ownership": "The local model gateway isn't running.", + "gateway-unavailable": "The local model gateway isn't running.", + "pi-model-unavailable": "Pi can't reach the local model.", + "pi-config-changed": "Pi's settings changed while they were checked.", + "plan-invalid": "The approved local model plan can't be read.", + "binding-unavailable": "The local model stack couldn't be checked.", +}; + export interface Reconnect { readonly windowMs: number; readonly maxBackoffMs: number; diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md index 21e94437..61146daa 100644 --- a/apps/linger-installer/AGENTS.md +++ b/apps/linger-installer/AGENTS.md @@ -28,7 +28,18 @@ once its services are ready on it: until then `instance.json` keeps naming the checkout they run from, the new checkout's migrations run only after the runtime (the local model, for one) is ready, and a run that stops earlier leaves the running services and their schema as they were. A successful -outcome's `details.source` names the checkout the services serve from. With +outcome's `details.source` names the checkout the services serve from. A +local model stack whose saved binding is no longer ready (any setup binding +reason, `pi-extensions-unavailable` from a Pi an earlier localmodels +installed without extension support included) gets its approved plan applied +again when the saved plan inputs still match the current choices; only a +plan the person approved is ever applied, and a stack still not ready ends +`LOCAL_MODELS_RECOVERY_REQUIRED` with the binding's reason codes in +`details.reasons`. A failed job's `errorCode` is the runtime's cause when it +has one (`RUNTIME_PLAN_REFUSED`, a harness plan refused before anything +changed, such as an unusable `SIMPLEX_PI_PATH` or a Windows runtime root too +long for Pi without long paths; `RUNTIME_ACTION_FAILED`; +`RUNTIME_EXTENSIONS_FAILED`), otherwise `INSTALL_FAILED`. With `--external-computer`, a successful outcome carries `runtime`, the same instance runtime as `GET /api/instances/{name}/runtime` (runtime and localmodels tool paths), so the desktop's Computer follows them. diff --git a/apps/linger-installer/src/server/jobs.test.ts b/apps/linger-installer/src/server/jobs.test.ts index 4ce9094f..0b263b9f 100644 --- a/apps/linger-installer/src/server/jobs.test.ts +++ b/apps/linger-installer/src/server/jobs.test.ts @@ -257,6 +257,26 @@ test.each([ }, ); +test.each([ + ["RUNTIME_PLAN_REFUSED", "RUNTIME_PLAN_REFUSED"], + ["RUNTIME_ACTION_FAILED", "RUNTIME_ACTION_FAILED"], + ["RUNTIME_EXTENSIONS_FAILED", "RUNTIME_EXTENSIONS_FAILED"], + ["NATIVE_SOURCE_INSTALLATION_FAILED", "INSTALL_FAILED"], +])( + "a failed installation with runtime cause %s reports it as %s", + async (code, errorCode) => { + const { jobs } = await setup(async () => ({ + code: 5, + state: "failed", + message: "The runtime could not be installed.", + details: { code, stage: "runtime" }, + })); + const job = await jobs.start({ instance: "default" }); + await jobs.wait(job.id); + expect(jobs.get(job.id)).toMatchObject({ state: "failed", errorCode }); + }, +); + const localPlan = { planId: "a".repeat(64), gpuIndex: 1, diff --git a/apps/linger-installer/src/server/jobs.ts b/apps/linger-installer/src/server/jobs.ts index 84165a33..84972d2d 100644 --- a/apps/linger-installer/src/server/jobs.ts +++ b/apps/linger-installer/src/server/jobs.ts @@ -417,7 +417,14 @@ export class JobManager { "LOCAL_MODELS_UNAVAILABLE", "LOCAL_MODELS_APPROVAL_REQUIRED", "LOCAL_MODELS_RECOVERY_REQUIRED", - ].includes(String(details.code)) + ].includes(String(details.code)) || + // Why the runtime could not be installed, in place of INSTALL_FAILED. + (record.job.state === "failed" && + [ + "RUNTIME_PLAN_REFUSED", + "RUNTIME_ACTION_FAILED", + "RUNTIME_EXTENSIONS_FAILED", + ].includes(String(details.code))) ) { record.job.errorCode = String(details.code); if (details.code === "LOCAL_MODELS_APPROVAL_REQUIRED") { diff --git a/packages/local-installation/src/dependencies.test.ts b/packages/local-installation/src/dependencies.test.ts index 26a9d0be..18ac3817 100644 --- a/packages/local-installation/src/dependencies.test.ts +++ b/packages/local-installation/src/dependencies.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, it, vi } from "vitest"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { prepareDependencies } from "./dependencies.js"; @@ -66,3 +66,40 @@ it("returns Runtime timeout category and stage through dependency preparation", details: { code: "COMMAND_TIMEOUT", stage: "runtime" }, }); }); +it.each([ + ["plan", "RUNTIME_ACTION_FAILED", "RUNTIME_PLAN_REFUSED"], + ["apply", "RUNTIME_ACTION_FAILED", "RUNTIME_ACTION_FAILED"], + ["apply", "RUNTIME_EXTENSIONS_FAILED", "RUNTIME_EXTENSIONS_FAILED"], +])( + "returns the harness %s failure %s as %s through dependency preparation", + async (step, upstream, code) => { + const options = { ...(await fixture()), dependency: "pi" as const }; + const localmodels = vi.fn(async (_home: string, args: string[]) => { + if (args[1] === "plan" && step !== "plan") + await writeFile( + args[args.indexOf("--out") + 1]!, + JSON.stringify({ + schema: "localmodels.harness-plan/v1", + id: "a".repeat(64), + runtime: "pi", + }), + ); + const failed = args[1] === step; + return { + code: failed ? 1 : 0, + stdout: failed + ? JSON.stringify({ + schema: "localmodels.harness-error/v1", + code: upstream, + message: "Runtime action failed: upstream cause.", + }) + : "", + stderr: "", + }; + }); + expect(await prepareDependencies(options, { localmodels })).toMatchObject({ + state: "failed", + details: { code, stage: "runtime" }, + }); + }, +); diff --git a/packages/local-installation/src/dependencies.ts b/packages/local-installation/src/dependencies.ts index de9a226a..6ef89773 100644 --- a/packages/local-installation/src/dependencies.ts +++ b/packages/local-installation/src/dependencies.ts @@ -5,6 +5,7 @@ import { privateDirectory } from "./instance.js"; import type { InstallOutcome, InstallerEvent } from "./events.js"; import { installNativeRuntime, + runtimeFailureCode, runtimeVersionFailure, type RuntimeDependencies, } from "./managed-runtimes.js"; @@ -61,12 +62,9 @@ export async function prepareDependencies( emit("failed", message); const code = versionFailure?.code ?? - (error && - typeof error === "object" && - "code" in error && - (error.code === "LOCALMODELS_RUNTIME_UNAVAILABLE" || - error.code === "COMMAND_TIMEOUT") - ? error.code + runtimeFailureCode(error) ?? + ((error as { code?: unknown } | null)?.code === "COMMAND_TIMEOUT" + ? "COMMAND_TIMEOUT" : undefined); return { code: 5, diff --git a/packages/local-installation/src/local-models.test.ts b/packages/local-installation/src/local-models.test.ts index 98dbf118..8a23f16b 100644 --- a/packages/local-installation/src/local-models.test.ts +++ b/packages/local-installation/src/local-models.test.ts @@ -279,7 +279,8 @@ test("replanning requires a separate review and never silently approves", async ).toMatchObject({ details: { code: "LOCAL_MODELS_APPROVAL_REQUIRED" } }); expect(f.call.mock.calls.some((c) => c[1][1] === "apply")).toBe(false); }); -test("saved binding needs fresh upstream health before reuse", async () => { +// A deployed stack whose binding is ready, then observed not ready once. +async function deployedThenNotReady(reason: string) { const f = await fixture(); await prepareLocalModels(f.instance, f.options, { localmodels: f.call }); await prepareLocalModels( @@ -287,11 +288,118 @@ test("saved binding needs fresh upstream health before reuse", async () => { { ...f.options, localModelsApproval: f.id }, { localmodels: f.call }, ); + const ready = structuredClone(f.binding); f.binding.ready = false; f.binding.pi = null as never; + f.binding.reasons = [{ code: reason, message: "upstream text" }] as never; + f.call.mockClear(); + return { ...f, ready }; +} +test.each(["deployment-unavailable", "pi-extensions-unavailable"])( + "a saved binding observed not ready (%s) applies the approved plan again", + async (reason) => { + const f = await deployedThenNotReady(reason); + const original = f.call.getMockImplementation()!; + f.call.mockImplementation(async (...a) => { + // stack apply brings the stack and its Pi back. + if (a[1][1] === "apply") Object.assign(f.binding, f.ready); + return original(...a); + }); + expect( + await prepareLocalModels(f.instance, f.options, { localmodels: f.call }), + ).toBeUndefined(); + const stack = f.call.mock.calls + .map(([, args]) => args) + .filter((args) => args[0] === "stack"); + expect(stack).toEqual([ + [ + "stack", + "apply", + path.join(f.home, "runtime/localmodels/plan.json"), + "--approve", + f.id, + "--jsonl", + ], + ]); + expect( + JSON.parse( + await readFile( + path.join(f.home, "runtime/localmodels/binding.json"), + "utf8", + ), + ), + ).toEqual(f.ready); + expect(f.options.onEvent).toHaveBeenCalledWith( + expect.objectContaining({ + kind: "log", + stage: "runtime", + message: expect.stringContaining(reason), + }), + ); + }, +); +test("a stack still not ready after applying the approved plan again asks for recovery", async () => { + const f = await deployedThenNotReady("gateway-unavailable"); + const result = await prepareLocalModels(f.instance, f.options, { + localmodels: f.call, + }); + expect(result).toMatchObject({ + state: "action_required", + details: { + code: "LOCAL_MODELS_RECOVERY_REQUIRED", + reasons: ["gateway-unavailable"], + }, + }); + expect( + f.call.mock.calls.filter(([, args]) => args[1] === "apply"), + ).toHaveLength(1); + // The earlier ready binding is never replaced by one not verified. + expect( + JSON.parse( + await readFile( + path.join(f.home, "runtime/localmodels/binding.json"), + "utf8", + ), + ), + ).toEqual(f.ready); +}); +test("a failed re-apply of the approved plan reports the upstream cause", async () => { + const f = await deployedThenNotReady("deployment-unavailable"); + const original = f.call.getMockImplementation()!; + f.call.mockImplementation(async (...a) => { + if (a[1][1] !== "apply") return original(...a); + a[2]!.onOutput!("stack: port 8080 is held by another program\n"); + return { code: 1, stdout: "", stderr: "" }; + }); expect( await prepareLocalModels(f.instance, f.options, { localmodels: f.call }), - ).toMatchObject({ details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" } }); + ).toMatchObject({ + state: "action_required", + // What made it apply the plan again. + details: { + code: "LOCAL_MODELS_RECOVERY_REQUIRED", + reasons: ["deployment-unavailable"], + }, + message: expect.stringContaining( + "stack: port 8080 is held by another program", + ), + }); +}); +test("a not-ready binding is never re-applied once resource choices changed", async () => { + const f = await deployedThenNotReady("deployment-unavailable"); + const result = await prepareLocalModels( + f.instance, + { ...f.options, shareGpu: false }, + { localmodels: f.call }, + ); + expect(result).toMatchObject({ + details: { code: "LOCAL_MODELS_RECOVERY_REQUIRED" }, + }); + expect( + f.call.mock.calls.some( + ([, args]) => args[0] === "stack" && ["plan", "apply"].includes(args[1]!), + ), + ).toBe(false); }); test("cancellation propagates without pretending to finish", async () => { const f = await fixture(); diff --git a/packages/local-installation/src/local-models.ts b/packages/local-installation/src/local-models.ts index cabc2020..c1fac212 100644 --- a/packages/local-installation/src/local-models.ts +++ b/packages/local-installation/src/local-models.ts @@ -39,6 +39,8 @@ interface Binding { environment: Record; configFingerprint: string; } | null; + // Why the stack is not ready, such as pi-extensions-unavailable. + reasons?: { code?: unknown; message?: unknown }[]; } interface Options { shareGpu?: boolean; @@ -182,6 +184,22 @@ function binding(value: unknown, id?: string): Binding { throw new Error("Invalid upstream Pi binding."); return b; } +// The binding's reason codes, such as pi-extensions-unavailable. +function reasonCodes(observed: Binding | null): string[] { + return (observed?.reasons ?? []).flatMap((reason) => + typeof reason?.code === "string" && + /^[a-z][a-z0-9-]{0,63}$/.test(reason.code) + ? [reason.code] + : [], + ); +} +// The first reason's upstream message, for display only. +function reasonText(observed: Binding | null): string { + const message = observed?.reasons?.[0]?.message; + return typeof message === "string" && message.trim() + ? `: ${message.trim().replace(/\s+/g, " ").slice(0, 300)}` + : ""; +} export async function localModelsEnvironment( instance: Instance, ): Promise { @@ -235,6 +253,8 @@ export async function prepareLocalModels( dependencies: Dependencies = {}, ): Promise { options.signal.throwIfAborted(); + // Why the binding was not ready, for the client to word; set once observed. + let reasons: string[] = []; const action = ( code: string, message: string, @@ -243,7 +263,11 @@ export async function prepareLocalModels( code: 4, state: "action_required", message, - details: { code, ...(summary ? { localModelsPlan: summary } : {}) }, + details: { + code, + ...(summary ? { localModelsPlan: summary } : {}), + ...(reasons.length ? { reasons } : {}), + }, }); if (options.localModelsReplan && options.localModelsApproval) return action( @@ -399,23 +423,10 @@ export async function prepareLocalModels( "--json", ]); if (result.code !== 0) return null; - return binding(JSON.parse(result.stdout), summary.planId); + const observed = binding(JSON.parse(result.stdout), summary.planId); + reasons = observed.ready ? [] : reasonCodes(observed); + return observed; }; - if ( - previous && - !options.localModelsReplan && - binding(JSON.parse(previous)).planId === summary.planId - ) { - const observed = await observe(); - if (observed?.ready) { - await atomicPrivate(bindFile, JSON.stringify(observed)); - return; - } - return action( - "LOCAL_MODELS_RECOVERY_REQUIRED", - "The upstream stack is not ready. Review an updated plan; existing resources were preserved.", - ); - } let inputs: | { planId?: unknown; shareGpu?: unknown; decision?: unknown } | undefined; @@ -425,24 +436,51 @@ export async function prepareLocalModels( } catch { // A damaged or incomplete approval binding cannot authorize deployment. } - if ( - inputs?.planId !== summary.planId || - inputs?.shareGpu !== shareGpu || - inputs?.decision !== false - ) - return action( - "LOCAL_MODELS_RECOVERY_REQUIRED", - "Local model resource choices changed or their approval binding is unavailable. Review a new plan; existing resources were preserved.", - ); - if ( - options.localModelsApproval !== summary.planId || - options.localModelsReplan - ) - return action( - "LOCAL_MODELS_APPROVAL_REQUIRED", - "Review the upstream local model plan before installing.", - summary, - ); + const approvedInputs = + inputs?.planId === summary.planId && + inputs?.shareGpu === shareGpu && + inputs?.decision === false; + // A binding saved for this plan means it was approved and deployed once. + const deployed = + !!previous && + !options.localModelsReplan && + binding(JSON.parse(previous)).planId === summary.planId; + if (deployed) { + const observed = await observe(); + if (observed?.ready) { + await atomicPrivate(bindFile, JSON.stringify(observed)); + return; + } + if (!approvedInputs) + return action( + "LOCAL_MODELS_RECOVERY_REQUIRED", + "The local model stack is not ready, and its resource choices changed since its plan was approved. Review a new plan; existing resources were preserved.", + ); + // Whatever stopped the approved stack (a stopped or adopted + // deployment, a Pi without extension support from an earlier + // localmodels), applying the same plan again restores it; the + // approval it was deployed under still holds. + options.onEvent({ + kind: "log", + stage: "runtime", + message: `The local model stack is not ready (${reasons.join(", ") || "unknown"}); applying its approved plan again.\n`, + }); + } else { + if (!approvedInputs) + return action( + "LOCAL_MODELS_RECOVERY_REQUIRED", + "Local model resource choices changed or their approval binding is unavailable. Review a new plan; existing resources were preserved.", + ); + if ( + options.localModelsApproval !== summary.planId || + options.localModelsReplan + ) + return action( + "LOCAL_MODELS_APPROVAL_REQUIRED", + "Review the upstream local model plan before installing.", + summary, + ); + } const applied = await command([ "stack", "apply", @@ -462,7 +500,7 @@ export async function prepareLocalModels( if (!observed?.ready) return action( "LOCAL_MODELS_RECOVERY_REQUIRED", - "The upstream tool could not verify the local stack binding. Existing resources were preserved.", + `The upstream tool could not verify the local stack binding${reasonText(observed)}. Existing resources were preserved.`, ); await atomicPrivate(bindFile, JSON.stringify(observed)); options.onEvent({ diff --git a/packages/local-installation/src/managed-runtimes.test.ts b/packages/local-installation/src/managed-runtimes.test.ts index 0423a51e..6a2c6653 100644 --- a/packages/local-installation/src/managed-runtimes.test.ts +++ b/packages/local-installation/src/managed-runtimes.test.ts @@ -371,3 +371,64 @@ it("does not retry once the install is cancelled during the wait", async () => { ).rejects.toThrow(); expect(applies(localmodels)).toHaveLength(1); }); + +// A harness command that fails at `step` with one harness-error/v1 line. +function harnessFailing(step: "plan" | "apply", code: string, message = "") { + return vi.fn(async (_home: string, args: string[]) => { + if (args[1] === "plan" && step !== "plan") + await writeFile( + args[args.indexOf("--out") + 1]!, + JSON.stringify({ + schema: "localmodels.harness-plan/v1", + id: "a".repeat(64), + runtime: "pi", + }), + ); + const failed = args[1] === step; + return { + code: failed ? 1 : 0, + stdout: failed + ? JSON.stringify({ + schema: "localmodels.harness-error/v1", + code, + message, + }) + : "", + stderr: "", + }; + }); +} + +it("reports a plan the harness refused, such as a Windows runtime root too long for Pi", async () => { + const options = await fixture(); + const localmodels = harnessFailing( + "plan", + "RUNTIME_ACTION_FAILED", + "Runtime action failed: The runtime root is 120 characters; Pi's dependency tree fits below a root of at most 90 on Windows unless long paths are enabled. Inspect the plan and retry.", + ); + const failure = await installNativeRuntime("pi", options, { + localmodels, + }).catch((error: Error & { code: string }) => error); + expect(failure).toMatchObject({ code: "RUNTIME_PLAN_REFUSED" }); + expect((failure as Error).message).toContain( + "The runtime root is 120 characters", + ); + expect(localmodels.mock.calls.some(([, args]) => args[1] === "apply")).toBe( + false, + ); +}); + +it.each(["RUNTIME_ACTION_FAILED", "RUNTIME_EXTENSIONS_FAILED"])( + "keeps the harness apply failure %s as its code", + async (code) => { + const options = await fixture(); + const failure = await installNativeRuntime("pi", options, { + localmodels: harnessFailing( + "apply", + code, + "Runtime action failed: pi is still not usable after apply. Inspect the plan and retry.", + ), + }).catch((error: Error & { code: string }) => error); + expect(failure).toMatchObject({ code }); + }, +); diff --git a/packages/local-installation/src/managed-runtimes.ts b/packages/local-installation/src/managed-runtimes.ts index 634c5fa1..54733872 100644 --- a/packages/local-installation/src/managed-runtimes.ts +++ b/packages/local-installation/src/managed-runtimes.ts @@ -53,6 +53,25 @@ export function runtimeVersionFailure( ? { code, message: versionFailures[code]! } : undefined; } +/** + * The failures this module reports with their own code: a harness plan + * refused before anything changed (an unusable SIMPLEX_PI_PATH, a Windows + * runtime root too long for Pi without long paths), an apply that left the + * runtime unusable, a Pi that cannot load extensions, and any other + * localmodels failure. + */ +const runtimeFailures = new Set([ + "RUNTIME_PLAN_REFUSED", + "RUNTIME_ACTION_FAILED", + "RUNTIME_EXTENSIONS_FAILED", + "LOCALMODELS_RUNTIME_UNAVAILABLE", +]); +export function runtimeFailureCode(error: unknown): string | undefined { + const code = (error as { code?: unknown } | null)?.code; + return typeof code === "string" && runtimeFailures.has(code) + ? code + : undefined; +} type LocalmodelsResult = Awaited>; function unavailable(failed?: { args: string[]; @@ -75,9 +94,25 @@ function unavailable(failed?: { } catch { /* Non-JSON output is read below as redacted diagnostics. */ } - const { cause, log } = localmodelsFailure(failed.args, failed.result); + const { code, cause, log } = localmodelsFailure(failed.args, failed.result); for (const message of log) failed.onEvent?.({ kind: "log", stage: "runtime", message }); + if (code === "RUNTIME_EXTENSIONS_FAILED") + return Object.assign( + new Error( + "Pi cannot load extensions, which Linger needs on every run. If you installed Pi yourself, update or remove it, then try again.", + ), + { code }, + ); + if (code === "RUNTIME_ACTION_FAILED") { + const planned = failed.args[1] === "plan"; + return Object.assign( + new Error( + `The localmodels Runtime ${planned ? "plan was refused" : "operation failed"}${cause ? `: ${cause}` : "."}`, + ), + { code: planned ? "RUNTIME_PLAN_REFUSED" : code }, + ); + } if (cause) return Object.assign( new Error(`The localmodels Runtime operation failed: ${cause}`), @@ -141,11 +176,7 @@ export async function inspectRuntimeDescriptors( const failure = runtimeVersionFailure(error); if (failure) throw Object.assign(new Error(failure.message), { code: failure.code }); - if ( - error instanceof Error && - (error as { code?: string }).code === "LOCALMODELS_RUNTIME_UNAVAILABLE" - ) - throw error; + if (error instanceof Error && runtimeFailureCode(error)) throw error; throw unavailable(); } } @@ -296,11 +327,7 @@ export async function installNativeRuntime( const failure = runtimeVersionFailure(error); if (failure) throw Object.assign(new Error(failure.message), { code: failure.code }); - if ( - error instanceof Error && - (error as { code?: string }).code === "LOCALMODELS_RUNTIME_UNAVAILABLE" - ) - throw error; + if (error instanceof Error && runtimeFailureCode(error)) throw error; throw unavailable(); } finally { await rm(temporary, { recursive: true, force: true }); From b031bfc17bc905ffc1ccf42093103aa72643598c Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:44:20 +0800 Subject: [PATCH 4/9] fix(desktop): stop the local models and their gateway on quit, uninstall and setup A Bifrost gateway the localmodels model library started, and the engines of the models it loaded, survived a quit, an uninstall and a cleanup of the Linger folders: the stop the uninstaller runs asked only for `foundations stop` and `stack down`, which leaves library-loaded models running, and a quit stopped nothing. - stopLocalmodels first unloads every model `library status` reports loaded (`library unload --base-dir `), then stops the controller and runs `stack down`, which with localmodels 0.1.0.dev40 also stops the library's Bifrost. Every step runs even when an earlier one fails; the error names each failed step by the library's error code. - The installer's new `--stop-local-models` mode does the same in every installation home for a quit, keeping the model controller that the still-running services use. - On a quit the person chose, LocalServer starts that mode detached under ELECTRON_RUN_AS_NODE with its output in /installer/ local-models-stop.log and does not wait. Updates, relaunches and the `--quit` of setup or the uninstaller skip it: they stop the models themselves right after, and a second `stack down` would race theirs for the stack lock. The next launch's resume applies the approved plan again. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/AGENTS.md | 21 +++- apps/desktop/src/main/index.ts | 20 +++- apps/desktop/src/main/local-server.test.ts | 40 +++++++ apps/desktop/src/main/local-server.ts | 70 +++++++++++- apps/linger-installer/AGENTS.md | 11 +- apps/linger-installer/src/main.ts | 36 +++++- apps/linger-installer/src/server/stop.test.ts | 42 ++++++- apps/linger-installer/src/server/stop.ts | 55 +++++++-- .../src/localmodels-tool.test.ts | 97 +++++++++++++++- .../src/localmodels-tool.ts | 108 ++++++++++++++---- 10 files changed, 441 insertions(+), 59 deletions(-) diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 5d73b0b4..78e6c21a 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -331,12 +331,25 @@ Gateway and runs Agents. The daemon exits with the app. on `--quit`, so setup skips `--quit` for it (CloseLinger asks the person to quit a running app). Retry in that prompt runs the stop again. Nothing running: the stop finds nothing and setup goes on. The stop also asks the pinned localmodels kit, when that kit is installed in the - home, to end its foundations controller under `runtime/model-services` - (`foundations stop`) and the stack's processes (`stack down`); it downloads - nothing, and Linger does not end the tool's processes itself. + home, to unload every model its model library loaded (`library status`, + then `library unload` for each `loaded` model), to end its foundations + controller under `runtime/model-services` (`foundations stop`), and to stop + the stack's processes and the gateway the tool started, the library's + Bifrost included (`stack down`); it downloads nothing, and Linger does not + end the tool's processes itself. Every step runs even when an earlier one + fails. On Windows the tool cannot prove and end a controller from a kit that has no stop command. - The tool refuses the chat stack on Windows, so no engine runs there. + A quit the person chose (the tray, the app menu, the Dock) does the same + for the local models, except the controller, which serves the services + that keep running: `LocalServer` starts `installer.js --home --stop-local-models` under `ELECTRON_RUN_AS_NODE`, detached, with + its output in `/installer/local-models-stop.log`, and does not wait + for it. It runs only when `desktop/local-server.json` names an + installation. The Computer exits with the app, so nothing uses the models + until the next launch, whose resume applies the approved plan again. A + quit for an update or a relaunch, and the `--quit` of setup or the + uninstaller (which stop the models themselves right after), leave them. - `src/main/legacy-migration.ts`: on start, stops a bridge an older version left running and moves its credential and the Desktop 0.16 daemon identity into the daemon layout, so the computer keeps its id. diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 837acaf8..b1220d56 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -326,10 +326,14 @@ async function main(): Promise { const host = new ModuleHost(modules, { config, log, bus: new EventBus() }); const showApp = (): void => setup.showApp(); + // The uninstaller, or setup replacing this release, asked to quit. + let replacing = false; app.on("second-instance", (_event, argv) => { // Without asking: the uninstaller is removing the app. - if (quitRequested(argv)) app.quit(); - else showApp(); + if (quitRequested(argv)) { + replacing = true; + app.quit(); + } else showApp(); }); app.on("activate", showApp); // Closing the window only hides it; the tray keeps the app running. @@ -340,10 +344,14 @@ async function main(): Promise { if (quitting) return; quitting = true; event.preventDefault(); - void host.stop(relaunch || updating ? "update" : "quit").finally(() => { - if (relaunch) app.relaunch(); - app.exit(0); - }); + // Setup and the uninstaller stop the services and the local models + // themselves right after --quit; a stop from here would race theirs. + void host + .stop(relaunch || updating || replacing ? "update" : "quit") + .finally(() => { + if (relaunch) app.relaunch(); + app.exit(0); + }); }); // Tasks run in the app, so quitting takes the computer offline; ask first diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts index 7e8cf16d..362c8eb0 100644 --- a/apps/desktop/src/main/local-server.test.ts +++ b/apps/desktop/src/main/local-server.test.ts @@ -76,6 +76,12 @@ if (args.includes("--user-keys")) { process.stdout.write(JSON.stringify({ saved: names }) + "\n"); process.exit(0); } +if (args.includes("--stop-local-models")) { + // The quit's stop of the local models; its output goes to a log file. + fs.writeFileSync(path.join(home, "stop-local-models.json"), JSON.stringify({ args, runAsNode: process.env.ELECTRON_RUN_AS_NODE })); + process.stdout.write(JSON.stringify({ failed: [] }) + "\n"); + process.exit(0); +} if (args.includes("--migrate")) { // Converts every legacy instance record, except a "desktop" that // migrate-skips holds back. @@ -2321,6 +2327,40 @@ describe("LocalServerModule after a restart", () => { await f.host.stop("quit"); }); + it("stops the local models when the person quits, without waiting for them", async () => { + const stopped = (home: string) => path.join(home, "stop-local-models.json"); + const f = fixture({}, enrolled, record); + await f.host.start(); + await vi.waitFor(() => expect(f.module.status().phase).toBe("ready")); + await f.host.stop("quit"); + // It runs on after the app is gone; its outcome goes to the log. + await vi.waitFor(() => + expect( + readFileSync( + path.join(f.home, "installer", "local-models-stop.log"), + "utf8", + ), + ).toBe('{"failed":[]}\n'), + ); + expect(JSON.parse(readFileSync(stopped(f.home), "utf8"))).toEqual({ + args: ["--home", f.home, "--stop-local-models"], + runAsNode: "1", + }); + }); + + it("leaves the local models running for an update, and stops none without an installation", async () => { + const update = fixture({}, enrolled, record); + await update.host.start(); + await vi.waitFor(() => expect(update.module.status().phase).toBe("ready")); + await update.host.stop("update"); + const none = fixture(); + await none.host.start(); + await none.host.stop("quit"); + await delay(300); + for (const home of [update.home, none.home]) + expect(existsSync(path.join(home, "stop-local-models.json"))).toBe(false); + }); + it("moves the keys of the unpacked source's .env into the instance's user.env once", async () => { const f = fixture({}, enrolled, (home) => { const source = path.join(home, "desktop", "source", "previous"); diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts index fe3c4b11..b5d71e4e 100644 --- a/apps/desktop/src/main/local-server.ts +++ b/apps/desktop/src/main/local-server.ts @@ -1,6 +1,12 @@ import { spawn } from "node:child_process"; import { createHash, randomBytes, randomUUID } from "node:crypto"; -import { createReadStream, existsSync, readFileSync } from "node:fs"; +import { + closeSync, + createReadStream, + existsSync, + openSync, + readFileSync, +} from "node:fs"; import { constants as fsConstants, cp, @@ -59,7 +65,7 @@ import { nodeRuntimeDownloadUrls, } from "../../../../scripts/local-computer-node-distributions.mjs"; import type { Logger } from "./log.js"; -import type { Module, ModuleContext } from "./modules.js"; +import type { Module, ModuleContext, StopReason } from "./modules.js"; import { sameOrigin } from "./navigation.js"; import { humanTenant, type EnrollmentModule } from "./enrollment.js"; import { compareVersions } from "./update-manifest.js"; @@ -502,7 +508,7 @@ export class LocalServerModule implements Module { }); } - async stop(): Promise { + async stop(reason: StopReason): Promise { this.#offRetry?.(); this.#offReset?.(); this.#offDaemon?.(); @@ -511,6 +517,64 @@ export class LocalServerModule implements Module { // The installer manager keeps running a started installation; it exits // by itself once idle. this.#abort.abort(); + if (reason === "quit") await this.#stopLocalModels(); + } + + // The Computer exits with the app, so after a quit nothing uses the local + // models: the bundled installer unloads the model library's models and + // stops the stack with the gateway the localmodels tool started, which + // would otherwise keep their memory and ports until the next reboot. The + // services and the model controller keep running, as after every quit; + // the next launch brings the approved stack up again. The stop runs on + // after the app is gone, its output in the installer's folder. An update + // or an uninstall stops the models with the services instead. + async #stopLocalModels(): Promise { + if (!(await this.#readRecord()) || !existsSync(this.#installerScript())) + return; + const directory = path.join(this.#options.home, "installer"); + let output: number; + try { + await mkdir(directory, { recursive: true, mode: 0o700 }); + output = openSync( + path.join(directory, "local-models-stop.log"), + "w", + 0o600, + ); + } catch (error) { + this.#ctx?.log.warn("local_server.local_models_stop_failed", { + error: String(error), + }); + return; + } + try { + const child = spawn( + process.execPath, + [ + this.#installerScript(), + "--home", + this.#options.home, + "--stop-local-models", + ], + { + detached: true, + // A detached Windows process otherwise opens its own console window. + windowsHide: true, + stdio: ["ignore", output, output], + env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }, + }, + ); + child.once("error", (error) => + this.#ctx?.log.warn("local_server.local_models_stop_failed", { + error: String(error), + }), + ); + child.unref(); + this.#ctx?.log.info("local_server.local_models_stopping", { + home: this.#options.home, + }); + } finally { + closeSync(output); + } } status(): LocalServerStatus { diff --git a/apps/linger-installer/AGENTS.md b/apps/linger-installer/AGENTS.md index 61146daa..4be37c4f 100644 --- a/apps/linger-installer/AGENTS.md +++ b/apps/linger-installer/AGENTS.md @@ -48,7 +48,16 @@ the desktop's Computer follows them. manager the desktop started for that instance (its `/api/stop` cancels a running job) and the instance's services, deletes nothing, and prints one JSON line with what failed. It needs nothing beside `installer.js`, so -setup can run it from a copy on an earlier release's `Linger.exe`. +setup can run it from a copy on an earlier release's `Linger.exe`. It also +stops what the pinned localmodels kit runs for each home: the model +library's loaded models, the model controller, and the stack with its +gateway (`stopLocalmodels`). + +`--stop-local-models` is the desktop's quit: in the default home and the +location `desktop/local-server.json` names, it unloads the model library's +loaded models and stops the stack with the gateway the localmodels tool +started, and keeps the services and the model controller running. It +prints one JSON line with what failed. Every other mode first converts an install from before the rename to Linger (`migrateLegacyInstallation`); `--migrate` does only that and exits, for the diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts index b99d8abd..cdf294a3 100644 --- a/apps/linger-installer/src/main.ts +++ b/apps/linger-installer/src/main.ts @@ -19,6 +19,7 @@ export function parseInstallerArguments(args: string[]) { userKeys?: boolean; migrate?: boolean; stop?: boolean; + stopLocalModels?: boolean; } = { home: lingerHome(), }; @@ -48,6 +49,10 @@ export function parseInstallerArguments(args: string[]) { options.stop = true; continue; } + if (flag === "--stop-local-models") { + options.stopLocalModels = true; + continue; + } if (flag === "--user-keys") { options.userKeys = true; continue; @@ -82,7 +87,8 @@ export function parseInstallerArguments(args: string[]) { !options.checkByok && !options.userKeys && !options.migrate && - !options.stop + !options.stop && + !options.stopLocalModels ) throw new Error("The installer needs a source checkout (--source-repo)."); if (options.resume && !options.instanceName) @@ -273,6 +279,29 @@ async function stopInstallation( process.exit(outcome.failed.length ? 1 : 0), ); } +// Headless stop of the local models for the desktop's quit: the outcome as +// one JSON line on stdout. The desktop does not wait for it to finish. +async function stopLocalModels( + options: ReturnType, +) { + const { stopDesktopLocalModels } = await import("./server/stop.js"); + setTimeout(() => process.exit(1), 150_000).unref(); + const outcome = await stopDesktopLocalModels({ + home: options.home, + signal: AbortSignal.timeout(120_000), + log: (message) => process.stderr.write(message.replace(/\n?$/, "\n")), + }).catch((error: unknown) => ({ + failed: [ + { + home: options.home, + message: error instanceof Error ? error.message : String(error), + }, + ], + })); + process.stdout.write(`${JSON.stringify(outcome)}\n`, () => + process.exit(outcome.failed.length ? 1 : 0), + ); +} async function serve(options: ReturnType) { const server = await launchInstaller({ ...options, @@ -327,13 +356,13 @@ if ( } // Installs from before the rename move to the Linger home once, before // any mode opens it; --migrate does only that, for the desktop client. - // Stopping for an uninstall changes nothing. + // Stopping for an uninstall or a quit changes nothing. // Only --migrate reports the instances it skipped, as warnings and as one // JSON line on stdout: the desktop runs it first, and in the other modes a // warning on stderr would read as the reason a start failed. A skipped // instance is refused with its own error when a mode opens it. let skipped: LegacyInstanceSkipped[] = []; - if (options && !options.stop) + if (options && !options.stop && !options.stopLocalModels) await import("@linger/local-installation/legacy-migration") .then(async ({ migrateLegacyInstallation }) => { skipped = await migrateLegacyInstallation({ home: options!.home }); @@ -346,6 +375,7 @@ if ( options = undefined; }); if (options?.stop) await stopInstallation(options); + else if (options?.stopLocalModels) await stopLocalModels(options); else if (options?.migrate) process.stdout.write(`${JSON.stringify({ skipped })}\n`, () => process.exit(0), diff --git a/apps/linger-installer/src/server/stop.test.ts b/apps/linger-installer/src/server/stop.test.ts index 9f108bad..49c274d2 100644 --- a/apps/linger-installer/src/server/stop.test.ts +++ b/apps/linger-installer/src/server/stop.test.ts @@ -6,7 +6,11 @@ import { tmpdir } from "node:os"; import { parseInstallerArguments } from "../main.js"; import { launchInstaller } from "./launch.js"; import { privateDirectory, privateWrite } from "./storage.js"; -import { stopDesktopInstallation, type StopDependencies } from "./stop.js"; +import { + stopDesktopInstallation, + stopDesktopLocalModels, + type StopDependencies, +} from "./stop.js"; const clean: Array<() => Promise> = []; afterEach(async () => { @@ -41,6 +45,12 @@ test("the uninstall stop needs only the instance", () => { expect(() => parseInstallerArguments(["--stop"])).toThrow(/instance/); }); +test("the quit's local model stop needs no instance or source", () => { + expect(parseInstallerArguments(["--stop-local-models"])).toMatchObject({ + stopLocalModels: true, + }); +}); + test("stops the desktop's manager while a job runs, then the instance's services", async () => { const value = await home(); let cancelled = false; @@ -228,3 +238,33 @@ test("stops the local models in every home, even where the services did not stop { home: custom, message: "localmodels stack down: gateway still running" }, ]); }); + +test("a quit stops only the local models, in every home, and keeps their controller", async () => { + const value = await home(); + const custom = await home(); + await mkdir(path.join(value, "desktop"), { recursive: true }); + await writeFile( + path.join(value, "desktop/local-server.json"), + JSON.stringify({ home: custom }), + ); + const models: { home: string; keepController?: boolean }[] = []; + const outcome = await stopDesktopLocalModels(options(value), { + stopModels: async (at, { keepController }) => { + models.push({ home: at, keepController }); + if (at === value) + throw new Error( + "localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING", + ); + }, + }); + expect(models).toEqual([ + { home: value, keepController: true }, + { home: custom, keepController: true }, + ]); + expect(outcome.failed).toEqual([ + { + home: value, + message: "localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING", + }, + ]); +}); diff --git a/apps/linger-installer/src/server/stop.ts b/apps/linger-installer/src/server/stop.ts index 4ea0753f..63b35790 100644 --- a/apps/linger-installer/src/server/stop.ts +++ b/apps/linger-installer/src/server/stop.ts @@ -26,7 +26,11 @@ export interface StopDependencies { stopInstance?: (instance: Instance, signal: AbortSignal) => Promise; stopModels?: ( home: string, - options: { signal: AbortSignal; log: (message: string) => void }, + options: { + signal: AbortSignal; + log: (message: string) => void; + keepController?: boolean; + }, ) => Promise; fetch?: typeof fetch; } @@ -47,16 +51,7 @@ export async function stopDesktopInstallation( fetch: fetcher = fetch, }: StopDependencies = {}, ): Promise { - const failed: StopOutcome["failed"] = []; - const attempt = async (home: string, step: () => Promise) => { - try { - await step(); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - options.log(`Could not stop the installation in ${home}: ${message}`); - failed.push({ home, message }); - } - }; + const { failed, attempt } = attempts(options.log); for (const home of await installationHomes(options.home)) { // The services stop even when the manager could not: an earlier release's // manager has no /api/stop, and a stale session may name another server. @@ -74,6 +69,44 @@ export async function stopDesktopInstallation( return { failed }; } +/** + * Stops the local models a quit leaves nothing to use: the model library's + * loaded models and the stack with the gateway the localmodels tool started, + * in every home the desktop installed to. The services and the model + * controller keep running, as the services do after a quit; the next launch + * brings the approved stack up again. + */ +export async function stopDesktopLocalModels( + options: Pick, + { stopModels = stopLocalmodels }: Pick = {}, +): Promise { + const { failed, attempt } = attempts(options.log); + for (const home of await installationHomes(options.home)) + await attempt(home, () => + stopModels(home, { + signal: options.signal, + log: options.log, + keepController: true, + }), + ); + return { failed }; +} + +// Runs each step and records the ones that failed, so every home is tried. +function attempts(log: (message: string) => void) { + const failed: StopOutcome["failed"] = []; + const attempt = async (home: string, step: () => Promise) => { + try { + await step(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + log(`Could not stop the installation in ${home}: ${message}`); + failed.push({ home, message }); + } + }; + return { failed, attempt }; +} + // The default home and the install location the desktop chose under // Customize (desktop/local-server.json). async function installationHomes(home: string): Promise { diff --git a/packages/local-installation/src/localmodels-tool.test.ts b/packages/local-installation/src/localmodels-tool.test.ts index 7c3df438..c4c47454 100644 --- a/packages/local-installation/src/localmodels-tool.test.ts +++ b/packages/local-installation/src/localmodels-tool.test.ts @@ -354,16 +354,36 @@ test("invokes the verified upstream module with isolated module and state paths" "sourceCommit", ); }); -test("stops the controller and the stack through the installed pinned kit", async () => { +// What `library status` prints, cut to the fields the stop reads. +const libraryStatus = (models: { id: string; state: string }[]) => ({ + code: 0, + stdout: JSON.stringify({ schema: "localmodels.library-status/v1", models }), + stderr: "", +}); +test("unloads the library's models, then stops the controller and the stack through the installed pinned kit", async () => { const f = await fixture(); vi.stubEnv("LINGER_LOCALMODELS_TOOL_JSON", JSON.stringify(f.source)); - const run = vi.fn(async () => ({ - code: 0, - stdout: "{}", - stderr: "", - })); + const base = path.join(f.home, "runtime/localmodels/models"); + const run = vi.fn(async (_home, args) => + args[1] === "status" + ? libraryStatus([ + { id: "qwen3-8b:Q4_K_M", state: "loaded" }, + { id: "lfm3-1.7b:Q8_0", state: "idle" }, + { id: "gemma4-4b:Q4_K_M", state: "loaded" }, + ]) + : { code: 0, stdout: "{}", stderr: "" }, + ); await stopLocalmodels(f.home, { signal: AbortSignal.timeout(5000) }, { run }); expect(run.mock.calls.map(([home, args]) => [home, args])).toEqual([ + [f.home, ["library", "status", "--base-dir", base, "--json"]], + [ + f.home, + ["library", "unload", "qwen3-8b:Q4_K_M", "--base-dir", base, "--json"], + ], + [ + f.home, + ["library", "unload", "gemma4-4b:Q4_K_M", "--base-dir", base, "--json"], + ], [ f.home, [ @@ -377,6 +397,70 @@ test("stops the controller and the stack through the installed pinned kit", asyn [f.home, ["stack", "down", "--json"]], ]); }); +test("a quit keeps the controller and stops only the library's models and the stack", async () => { + const run = vi.fn(async (_home, args) => + args[1] === "status" + ? libraryStatus([{ id: "qwen3-8b:Q4_K_M", state: "loaded" }]) + : { code: 0, stdout: "{}", stderr: "" }, + ); + await stopLocalmodels( + "/home", + { signal: AbortSignal.timeout(5000), keepController: true }, + { run, installed: async () => true }, + ); + expect(run.mock.calls.map(([, args]) => args.slice(0, 2))).toEqual([ + ["library", "status"], + ["library", "unload"], + ["stack", "down"], + ]); +}); +test("stops the stack even when the library could not be read or a model did not unload, and names each failure", async () => { + const unloadFailed = vi.fn(async (_home, args) => + args[1] === "status" + ? libraryStatus([{ id: "qwen3-8b:Q4_K_M", state: "loaded" }]) + : args[1] === "unload" + ? { + code: 1, + stdout: JSON.stringify({ + schema: "localmodels.library-event/v1", + event: "error", + ok: false, + code: "JOB_RUNNING", + detail: "a download is running", + }), + stderr: "", + } + : { code: 0, stdout: "{}", stderr: "" }, + ); + await expect( + stopLocalmodels( + "/home", + { signal: AbortSignal.timeout(5000), keepController: true }, + { run: unloadFailed, installed: async () => true }, + ), + ).rejects.toThrow("localmodels library unload qwen3-8b:Q4_K_M: JOB_RUNNING"); + expect(unloadFailed.mock.calls.at(-1)?.[1]).toEqual([ + "stack", + "down", + "--json", + ]); + const statusFailed = vi.fn(async (_home, args) => + args[1] === "status" + ? { code: 1, stdout: "", stderr: "error: library status failed" } + : { code: 0, stdout: "{}", stderr: "" }, + ); + await expect( + stopLocalmodels( + "/home", + { signal: AbortSignal.timeout(5000), keepController: true }, + { run: statusFailed, installed: async () => true }, + ), + ).rejects.toThrow("localmodels library status: exit 1"); + expect(statusFailed.mock.calls.map(([, args]) => args[1])).toEqual([ + "status", + "down", + ]); +}); test("a home without the pinned kit has nothing to stop and downloads nothing", async () => { const f = await fixture(); vi.stubEnv( @@ -413,6 +497,7 @@ test("stops the stack even when the controller did not stop, and names the failu ), ).rejects.toThrow("localmodels foundations stop: controller still running"); expect(run.mock.calls.map(([, args]) => args[0])).toEqual([ + "library", "foundations", "stack", ]); diff --git a/packages/local-installation/src/localmodels-tool.ts b/packages/local-installation/src/localmodels-tool.ts index 61cf743a..5ef8ab31 100644 --- a/packages/local-installation/src/localmodels-tool.ts +++ b/packages/local-installation/src/localmodels-tool.ts @@ -517,50 +517,110 @@ export async function runLocalmodels( return result; } /** - * For an uninstall, or an install over this release: stops the model - * controller under /runtime/model-services and the processes the stack - * started, through the pinned kit. Nothing is downloaded: a home without that - * kit has nothing it started. Both requests are made even when one fails; the - * error names each that did not stop. + * Stops what the pinned kit runs for a home, through that kit: first every + * model the model library loaded (`library unload`), whose engines `stack + * down` leaves running, then, unless `keepController`, the model controller + * under /runtime/model-services, and last the stack's processes and + * the gateway the tool started (`stack down`), the library's Bifrost + * included. An uninstall or an install over this release stops all of it; a + * quit keeps the controller, which belongs to the services that keep + * running. Nothing is downloaded: a home without that kit has nothing it + * started. Every step runs even when an earlier one fails; the error names + * each that did not stop. */ export async function stopLocalmodels( home: string, - options: { signal: AbortSignal; log?: (message: string) => void }, + options: { + signal: AbortSignal; + log?: (message: string) => void; + keepController?: boolean; + }, dependencies: { run?: typeof runLocalmodels; installed?: (home: string) => Promise; } = {}, ): Promise { if (!(await (dependencies.installed ?? hasPinnedTool)(home))) return; - const root = modelServicesRoot(home); + const run = dependencies.run ?? runLocalmodels; + const base = localmodelsBaseDirectory(home); const failed: string[] = []; - for (const args of [ - ["foundations", "stop", "--root", root, "--json"], - ["stack", "down", "--json"], - ]) { + const step = async (args: string[], name = args.slice(0, 2).join(" ")) => { options.signal.throwIfAborted(); - options.log?.( - `Stopping the local models (localmodels ${args[0]} ${args[1]}).`, - ); - const result = await (dependencies.run ?? runLocalmodels)(home, args, { + options.log?.(`Stopping the local models (localmodels ${name}).`); + const result = await run(home, args, { signal: options.signal, timeoutMs: 30_000, }).catch((error: unknown) => { options.signal.throwIfAborted(); return { code: 1, stdout: "", stderr: String(error) }; }); - if (result.code === 0) continue; - let reason = `exit ${result.code}`; - try { - const error = (JSON.parse(result.stdout) as { error?: unknown }).error; - if (typeof error === "string" && error) reason = error; - } catch { - // No report: the exit status is all there is. - } - failed.push(`localmodels ${args[0]} ${args[1]}: ${reason}`); + if (result.code !== 0) + failed.push(`localmodels ${name}: ${stopFailure(result)}`); + return result; + }; + const status = await step([ + "library", + "status", + "--base-dir", + base, + "--json", + ]); + if (status.code === 0) { + const loaded = loadedLibraryModels(status.stdout); + if (!loaded) failed.push("localmodels library status: no model list"); + for (const model of loaded ?? []) + await step( + ["library", "unload", model, "--base-dir", base, "--json"], + `library unload ${model}`, + ); } + if (!options.keepController) + await step([ + "foundations", + "stop", + "--root", + modelServicesRoot(home), + "--json", + ]); + await step(["stack", "down", "--json"]); if (failed.length) throw new Error(failed.join("; ")); } +// The ids of the models `library status` reports loaded, or undefined when +// its output is not a status report. +function loadedLibraryModels(stdout: string): string[] | undefined { + try { + const models = (JSON.parse(stdout) as { models?: unknown }).models; + if (!Array.isArray(models)) return undefined; + return models.flatMap((model: { id?: unknown; state?: unknown }) => + model?.state === "loaded" && + typeof model.id === "string" && + /^[a-z0-9][a-z0-9._-]*:[A-Za-z0-9._-]+$/.test(model.id) + ? [model.id] + : [], + ); + } catch { + return undefined; + } +} +// A failed step's structured cause: the library's error code, the tool's +// error, or its exit status. +function stopFailure(result: { code: number; stdout: string }): string { + try { + const report = JSON.parse(result.stdout) as { + code?: unknown; + error?: unknown; + }; + if ( + typeof report.code === "string" && + /^[A-Z][A-Z_]{0,63}$/.test(report.code) + ) + return report.code; + if (typeof report.error === "string" && report.error) return report.error; + } catch { + // No report: the exit status is all there is. + } + return `exit ${result.code}`; +} async function hasPinnedTool(home: string): Promise { if (configuredDevTool()) return true; const source = pinnedToolSource(); From da8afd73a07fd24b865161160fcb36104256c49d Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:45:36 +0800 Subject: [PATCH 5/9] fix(desktop): never report a daemon log record as the Computer's exit reason computer_daemon.exited kept the daemon's last stderr line as its reason, and the start failure showed it. After a kill or a crash that was usually a log record from minutes earlier ("2026/11/17 20:29:38 INFO runtime.diagnostic ...") or the last frame of a Go stack trace. The reason is now the last line outside the daemon's log records, which carry Go's log prefix and a level, and a Go runtime crash keeps its panic or fatal error line. A daemon that printed nothing else has no reason, and the failure falls back to its exit code. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/AGENTS.md | 5 +- apps/desktop/src/main/computer-daemon.test.ts | 53 +++++++++++++++++++ apps/desktop/src/main/computer-daemon.ts | 14 ++++- 3 files changed, 70 insertions(+), 2 deletions(-) diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 78e6c21a..9927db68 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -275,7 +275,10 @@ Gateway and runs Agents. The daemon exits with the app. `desktop` section puts the daemon in Desktop mode: no self-update, it exits when its stdin closes, and it reports `{"type":"status",...}` lines on stdout, which drive the tray and the SPA status. Its log goes to - `/logs/computer-daemon.log`. Crashes restart with backoff; new + `/logs/computer-daemon.log`. Crashes restart with backoff; the + exit reason, logged with `computer_daemon.exited` and shown once starts + keep failing, is the last stderr line outside the daemon's log records (a + Go crash: its `panic:` line), or none; new folders or a new name restart it once tasks finish. On macOS it writes `{"type":"hello","features":["permissions.v1"]}` to the daemon's stdin after spawn and answers `permission.request` lines with diff --git a/apps/desktop/src/main/computer-daemon.test.ts b/apps/desktop/src/main/computer-daemon.test.ts index b7c7ff27..8a7d0518 100644 --- a/apps/desktop/src/main/computer-daemon.test.ts +++ b/apps/desktop/src/main/computer-daemon.test.ts @@ -630,4 +630,57 @@ describe.skipIf(process.platform === "win32")("spawnDaemon", () => { expect(reason).toBe("read Computer config: denied"); expect(readFileSync(log, "utf8")).toContain("starting\n"); }); + + const exitOf = async (script: string) => { + const directory = mkdtempSync(path.join(os.tmpdir(), "spawn-daemon-")); + const executable = path.join(directory, "daemon"); + writeFileSync(executable, `#!/bin/sh\n${script}`); + chmodSync(executable, 0o755); + const log = path.join(directory, "logs", "computer-daemon.log"); + const child = spawnDaemon(executable, log)("config.json", {}); + return new Promise<[number | null, string?]>((resolve) => + child.onExit((...exit) => resolve(exit)), + ); + }; + + it("never takes a log record for the exit reason", async () => { + const [code, reason] = await exitOf( + [ + 'echo "2026/11/17 20:26:26 INFO local_models.job_finished action=download exit_code=0" >&2', + 'echo "2026/11/17 20:29:38 WARN runtime.diagnostic type=pi status=ready" >&2', + "kill -9 $$", + ].join("\n"), + ); + expect(code).toBeNull(); + expect(reason).toBeUndefined(); + }); + + it("keeps the error the daemon printed when log records follow it", async () => { + const [, reason] = await exitOf( + [ + 'echo "2026/11/17 20:26:26 INFO daemon.started" >&2', + 'echo "read Computer config: private path is not owned by the current user" >&2', + 'echo "2026/11/17 20:26:27 INFO runner.shutdown phase=completed" >&2', + "exit 1", + ].join("\n"), + ); + expect(reason).toBe( + "read Computer config: private path is not owned by the current user", + ); + }); + + it("reports a Go panic by its panic line, not its stack trace", async () => { + const [code, reason] = await exitOf( + [ + 'echo "panic: assignment to entry in nil map" >&2', + "echo >&2", + 'echo "goroutine 1 [running]:" >&2', + 'echo "main.main()" >&2', + 'echo "\t/src/main.go:10 +0x1d" >&2', + "exit 2", + ].join("\n"), + ); + expect(code).toBe(2); + expect(reason).toBe("panic: assignment to entry in nil map"); + }); }); diff --git a/apps/desktop/src/main/computer-daemon.ts b/apps/desktop/src/main/computer-daemon.ts index 5fd584d8..dceacb73 100644 --- a/apps/desktop/src/main/computer-daemon.ts +++ b/apps/desktop/src/main/computer-daemon.ts @@ -545,6 +545,12 @@ export class ComputerDaemonModule implements Module { // Starts the daemon executable with only the given environment. Its stderr // (the daemon log) and any stdout that is not a status line go to logFile. +// A record of the daemon's log: Go's log package prefix, then the level. +const LOG_RECORD = + /^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? (?:DEBUG|INFO|WARN|ERROR)\b/; +// The first line of a Go runtime crash. +const GO_CRASH = /^(?:panic|fatal error): /; + export const spawnDaemon = (executable: string, logFile: string): SpawnDaemon => (configFile, env) => { @@ -576,9 +582,15 @@ export const spawnDaemon = }); }; child.stderr.pipe(log, { end: false }); + // The daemon prints why it stopped as its last line outside its log; + // its log records (a timestamp, then the level) may come from any time + // before. A Go runtime crash leads with its panic line, then a trace. + let crashed = false; createInterface({ input: child.stderr }).on("line", (line) => { const text = line.trim(); - if (text) reason = text.slice(0, 500); + if (!text || crashed || LOG_RECORD.test(text)) return; + crashed = GO_CRASH.test(text); + reason = text.slice(0, 500); }); createInterface({ input: child.stdout }).on("line", (line) => { if (line.startsWith("{")) for (const listener of lines) listener(line); From 90357d10cc7ca7f2c78ea01db7efcc2ed99037f6 Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:47:15 +0800 Subject: [PATCH 6/9] fix(local-installation): name the path and the reason when a Windows private path check fails After Linger ran elevated once, files it wrote there (config.json, native.env.*.tmp) belong to Administrators, and the next normal start failed with "Windows private path validation failed" without naming the file or the cause. The ACL program now throws fixed UPPER_SNAKE reason codes and prints only such a code when it fails, never a system message. The error names the resolved path and words the reason, and carries code WINDOWS_PRIVATE_PATH_UNSAFE with reason and path; an output that is not one of the codes is UNCHECKED. The Windows-only native tests now assert the reason for a junction, a junction ancestor and shared access. Co-Authored-By: Claude Opus 5.5 --- .../src/windows-private.native.test.ts | 27 ++++----- .../src/windows-private.test.ts | 50 +++++++++++++++-- .../local-installation/src/windows-private.ts | 56 +++++++++++++++---- 3 files changed, 104 insertions(+), 29 deletions(-) diff --git a/packages/local-installation/src/windows-private.native.test.ts b/packages/local-installation/src/windows-private.native.test.ts index 6d7b3fc4..cf8bfe71 100644 --- a/packages/local-installation/src/windows-private.native.test.ts +++ b/packages/local-installation/src/windows-private.native.test.ts @@ -34,12 +34,12 @@ it.skipIf(process.platform !== "win32")( const junction = path.join(root, "link"); await symlink(root, junction, "junction"); await writeFile(path.join(root, "settings.json"), "{}"); - await expect(windowsPrivatePath(junction, "directory")).rejects.toThrow( - /validation failed/, - ); + await expect( + windowsPrivatePath(junction, "directory"), + ).rejects.toMatchObject({ reason: "UNSAFE_TYPE", path: junction }); await expect( windowsPrivatePath(path.join(junction, "settings.json"), "file"), - ).rejects.toThrow(/validation failed/); + ).rejects.toMatchObject({ reason: "UNSAFE_PARENT_LINK" }); }, ); it.skipIf(process.platform !== "win32")( @@ -67,9 +67,10 @@ it.skipIf(process.platform !== "win32")( { input: file, timeoutMs: 30000 }, ); expect(changed.code).toBe(0); - await expect(windowsPrivatePath(file, "file")).rejects.toThrow( - /validation failed/, - ); + await expect(windowsPrivatePath(file, "file")).rejects.toMatchObject({ + reason: "SHARED_ACCESS", + path: file, + }); }, ); it.skipIf(process.platform !== "win32")( @@ -106,12 +107,12 @@ it.skipIf(process.platform !== "win32")( ).resolves.toBeUndefined(); // A private target also owns future descendants, so broad inheritance on // the target remains forbidden even when it is inherit-only. - await expect(windowsPrivatePath(root, "directory")).rejects.toThrow( - /validation failed/, - ); + await expect(windowsPrivatePath(root, "directory")).rejects.toMatchObject({ + reason: "SHARED_ACCESS", + }); await mutate("None"); - await expect(windowsPrivatePath(child, "directory")).rejects.toThrow( - /validation failed/, - ); + await expect(windowsPrivatePath(child, "directory")).rejects.toMatchObject({ + reason: "UNSAFE_PARENT_ACCESS", + }); }, ); diff --git a/packages/local-installation/src/windows-private.test.ts b/packages/local-installation/src/windows-private.test.ts index 33011f08..b7b3f9fe 100644 --- a/packages/local-installation/src/windows-private.test.ts +++ b/packages/local-installation/src/windows-private.test.ts @@ -1,3 +1,4 @@ +import path from "node:path"; import { expect, it, vi } from "vitest"; import { windowsPrivatePath, @@ -19,10 +20,51 @@ it("sends paths through stdin and runs a fixed encoded ACL program", async () => expect(WINDOWS_PRIVATE_SCRIPT).toContain("AccessControlSections]::Access"); }); it("fails closed without disclosing command diagnostics", async () => { - const run = vi.fn().mockResolvedValue({ code: 1, stderr: "sensitive path" }); + const run = vi + .fn() + .mockResolvedValue({ code: 1, stdout: "", stderr: "sensitive path" }); + const error = await windowsPrivatePath("private", "file", false, run).catch( + (failure: unknown) => failure as Error, + ); + expect(error?.message).toMatch(/^Windows private path validation failed/); + expect(error?.message).not.toContain("sensitive"); + expect(error).toMatchObject({ + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNCHECKED", + }); +}); +it("names the path and why it is not private", async () => { + const file = + "C:\\Users\\person\\.simplexai\\instances\\desktop\\native.env.1.tmp"; + const owned = vi + .fn() + .mockResolvedValue({ code: 1, stdout: "UNSAFE_OWNER", stderr: "" }); + const error = await windowsPrivatePath(file, "file", false, owned).catch( + (failure: unknown) => failure as Error, + ); + expect(error).toMatchObject({ + code: "WINDOWS_PRIVATE_PATH_UNSAFE", + reason: "UNSAFE_OWNER", + path: path.resolve(file), + }); + expect(error?.message).toContain(path.resolve(file)); + expect(error?.message).toContain("owned by another account"); + // Only the script's fixed codes pass; anything else is unchecked. + const other = vi.fn().mockResolvedValue({ + code: 1, + stdout: "Access denied to C:\\x", + stderr: "", + }); await expect( - windowsPrivatePath("private", "file", false, run), - ).rejects.toThrow("Windows private path validation failed"); + windowsPrivatePath(file, "file", false, other), + ).rejects.toMatchObject({ reason: "UNCHECKED" }); +}); +it("gives every failure in the ACL program a fixed reason code", () => { + const thrown = [...WINDOWS_PRIVATE_SCRIPT.matchAll(/throw '([^']*)'/g)].map( + (match) => match[1], + ); + expect(thrown.length).toBeGreaterThan(5); + for (const code of thrown) expect(code).toMatch(/^[A-Z][A-Z_]+$/); }); it("ignores inherit-only ACEs only for effective ancestor permissions", () => { const ancestors = WINDOWS_PRIVATE_SCRIPT.slice( @@ -36,5 +78,5 @@ it("ignores inherit-only ACEs only for effective ancestor permissions", () => { "$rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly", ); expect(target).not.toContain("PropagationFlags"); - expect(target).toContain("Non-private permissions"); + expect(target).toContain("SHARED_ACCESS"); }); diff --git a/packages/local-installation/src/windows-private.ts b/packages/local-installation/src/windows-private.ts index c5580877..e1374ccf 100644 --- a/packages/local-installation/src/windows-private.ts +++ b/packages/local-installation/src/windows-private.ts @@ -11,22 +11,22 @@ try { $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User $system = 'S-1-5-18'; $admins = 'S-1-5-32-544' $item = Get-Item -LiteralPath $request.path -Force - if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item.PSIsContainer -ne ($request.kind -eq 'directory'))) { throw 'Unsafe type' } + if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($item.PSIsContainer -ne ($request.kind -eq 'directory'))) { throw 'UNSAFE_TYPE' } $acl = Get-Acl -LiteralPath $item.FullName - if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'Unsafe owner' } + if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'UNSAFE_OWNER' } $parent = $item.Directory if ($item.PSIsContainer) { $parent = $item.Parent } while ($parent) { - if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unsafe parent link' } + if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'UNSAFE_PARENT_LINK' } $parentAcl = Get-Acl -LiteralPath $parent.FullName $owner = $parentAcl.GetOwner([Security.Principal.SecurityIdentifier]).Value - if ($owner -notin @($sid.Value, $system, $admins, 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')) { throw 'Unsafe parent owner' } + if ($owner -notin @($sid.Value, $system, $admins, 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464')) { throw 'UNSAFE_PARENT_OWNER' } foreach ($rule in $parentAcl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { # InheritOnly ACEs do not authorize mutation of this ancestor. They are # still checked below when present on the private target itself. if ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) { continue } if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($sid.Value, $system, $admins, 'S-1-3-0', 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464') -and - ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]'Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership')) { throw 'Unsafe parent permissions' } + ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]'Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership')) { throw 'UNSAFE_PARENT_ACCESS' } } $parent = $parent.Parent } @@ -44,17 +44,22 @@ try { if ($PSVersionTable.PSEdition -eq 'Core') { [IO.FileSystemAclExtensions]::SetAccessControl($item, $acl) } else { $item.SetAccessControl($acl) } $acl = Get-Acl -LiteralPath $item.FullName } - if ($request.kind -eq 'directory' -and !$acl.AreAccessRulesProtected) { throw 'Inherited private permissions' } + if ($request.kind -eq 'directory' -and !$acl.AreAccessRulesProtected) { throw 'INHERITED_ACCESS' } $currentAllowed = $false foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { if ($rule.AccessControlType -eq 'Allow') { - if ($rule.IdentityReference.Value -notin @($sid.Value, $system)) { throw 'Non-private permissions' } + if ($rule.IdentityReference.Value -notin @($sid.Value, $system)) { throw 'SHARED_ACCESS' } if ($rule.IdentityReference.Value -eq $sid.Value) { $currentAllowed = $true } } } - if (!$currentAllowed) { throw 'Missing owner access' } + if (!$currentAllowed) { throw 'MISSING_OWNER_ACCESS' } exit 0 -} catch { exit 1 } +} catch { + # Only this program's own reason codes leave it; never a system message. + $code = [string]$_.Exception.Message + if ($code -cmatch '^[A-Z][A-Z_]+$') { [Console]::Out.Write($code) } + exit 1 +} `; export async function windowsPrivatePath( file: string, @@ -82,8 +87,35 @@ export async function windowsPrivatePath( timeoutMs: 30000, }, ); - if (result.code !== 0) - throw new Error( - "Windows private path validation failed; use a current-user owned local directory without links or shared access.", + if (result.code !== 0) { + const reason: WindowsPrivateReason = Object.hasOwn( + WINDOWS_PRIVATE_REASONS, + result.stdout.trim(), + ) + ? (result.stdout.trim() as WindowsPrivateReason) + : "UNCHECKED"; + const target = path.resolve(file); + throw Object.assign( + new Error( + `Windows private path validation failed: ${target} ${WINDOWS_PRIVATE_REASONS[reason]}. Use a current-user owned local directory without links or shared access.`, + ), + { code: WINDOWS_PRIVATE_PATH_UNSAFE, reason, path: target }, ); + } } +/** The code of an error from windowsPrivatePath; its reason says why. */ +export const WINDOWS_PRIVATE_PATH_UNSAFE = "WINDOWS_PRIVATE_PATH_UNSAFE"; +// The ACL program's reason codes, worded for the error message. +const WINDOWS_PRIVATE_REASONS = { + UNSAFE_TYPE: "is a link, or not the expected file or folder", + UNSAFE_OWNER: + "is owned by another account, such as Administrators after Linger ran as administrator", + UNSAFE_PARENT_LINK: "is inside a linked folder", + UNSAFE_PARENT_OWNER: "is inside a folder another account owns", + UNSAFE_PARENT_ACCESS: "is inside a folder other accounts may change", + INHERITED_ACCESS: "takes its permissions from its parent folder", + SHARED_ACCESS: "is shared with other accounts", + MISSING_OWNER_ACCESS: "does not give your account access", + UNCHECKED: "could not be checked", +} as const; +export type WindowsPrivateReason = keyof typeof WINDOWS_PRIVATE_REASONS; From e8734a6a1df1af565cb441c56cca6f75b3e3dac3 Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:48:10 +0800 Subject: [PATCH 7/9] fix(desktop): unpack this app's source package again when its folder is damaged Resume unpacks the source package when the recorded folder is not one the installer accepts, but a folder with this package's hash and its marker file counted as already unpacked even with package.json or other files gone. Every start then failed with "Source checkout must be a Linger checkout with scripts/source-native.mjs." and Try Again did the same. The folder now counts as unpacked only when the installer's own check accepts it; otherwise it is removed and the package unpacked again in its place, logged as local_server.source_damaged. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/AGENTS.md | 5 +-- apps/desktop/src/main/local-server.test.ts | 39 ++++++++++++++++++++++ apps/desktop/src/main/local-server.ts | 28 ++++++++++++---- 3 files changed, 63 insertions(+), 9 deletions(-) diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 9927db68..2b133f8e 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -174,8 +174,9 @@ Gateway and runs Agents. The daemon exits with the app. services on launch with `installer.js --resume`, which also restarts them when the instance's `user.env` changed. A source folder removed since, or one the installer no longer accepts as a Linger checkout (such as one the - earlier Simplex app unpacked), is unpacked again from the app's package - first and replaces the recorded one. The record also names the app + earlier Simplex app unpacked, or this package's own folder with files + missing since), is unpacked again from the app's package first and + replaces the recorded one. The record also names the app version that unpacked the source; when this app brings another source package (it was installed over an older one), that launch unpacks it and resumes on it, with the "Updating Linger" page instead of the older diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts index 362c8eb0..64059d1b 100644 --- a/apps/desktop/src/main/local-server.test.ts +++ b/apps/desktop/src/main/local-server.test.ts @@ -2853,6 +2853,45 @@ describe("LocalServerModule after a restart", () => { await f.host.stop("quit"); }); + it("unpacks the source package again when its folder is damaged", async () => { + const root = tempDirectory(); + const archive = sourceArchive(root); + const repo = (home: string) => + path.join(home, "desktop", "source", archive.sha256.slice(0, 16)); + const f = fixture( + { + sourceArchive: { + url: "https://cdn.example/linger.tar.gz", + sha256: archive.sha256, + }, + fetch: (async () => new Response(archive.bytes)) as typeof fetch, + }, + enrolled, + (home) => { + // This app's own folder: the marker is there, package.json is gone. + mkdirSync(path.join(repo(home), "scripts"), { recursive: true }); + writeFileSync(path.join(repo(home), "scripts/source-native.mjs"), ""); + writeFileSync( + path.join(home, "desktop", "local-server.json"), + JSON.stringify({ + home, + repo: repo(home), + origin: "http://localhost:3000", + version: APP_VERSION, + }), + ); + }, + ); + await f.host.start(); + await vi.waitFor(() => expect(f.module.status().phase).toBe("ready")); + const args = installerArgs(f.home); + expect(args[args.indexOf("--source-repo") + 1]).toBe(repo(f.home)); + expect( + JSON.parse(readFileSync(path.join(repo(f.home), "package.json"), "utf8")), + ).toEqual({ name: "linger" }); + await f.host.stop("quit"); + }); + it("moves to the source package when the earlier Simplex app unpacked the one in use", async () => { const root = tempDirectory(); const archive = sourceArchive(root); diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts index b5d71e4e..c25f30e6 100644 --- a/apps/desktop/src/main/local-server.ts +++ b/apps/desktop/src/main/local-server.ts @@ -1590,13 +1590,27 @@ export class LocalServerModule implements Module { archive.sha256.slice(0, 16), ); if (await isFile(path.join(directory, SOURCE_MARKER))) { - await this.#timed("teamhub_binaries", () => - this.#ensureTeamhubBinaries(directory, archive.sha256, signal), - ); - await this.#timed("native_runtime", () => - this.#ensureNativeRuntime(directory, archive.sha256, signal), - ); - return directory; + if ( + await validateSourceRepository(directory).then( + () => true, + () => false, + ) + ) { + await this.#timed("teamhub_binaries", () => + this.#ensureTeamhubBinaries(directory, archive.sha256, signal), + ); + await this.#timed("native_runtime", () => + this.#ensureNativeRuntime(directory, archive.sha256, signal), + ); + return directory; + } + // This package's own folder, damaged since it was unpacked (files + // removed by hand or by a cleanup): the installer would refuse it, so + // it is unpacked again in its place. + this.#ctx?.log.warn("local_server.source_damaged", { + source: path.basename(directory), + }); + await removeRetrying(directory); } if ("file" in archive) await this.#extract(archive, directory, SOURCE_MARKER, signal); From f3e34c0d522ab1682ecc003b9dc050c8af6e05ba Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:51:11 +0800 Subject: [PATCH 8/9] fix(local-installation): adopt macOS services 0.1.2 recorded with a localized start time Linger 0.1.2 recorded each macOS service's birth from ps lstart in the locale it ran in. Since 0.1.3 every check reads lstart in the C locale, so on a Mac with, for example, a German region format the services 0.1.2 left running never matched their records again, and the upgraded app reported their identity as unverifiable until they ended. A darwin record whose birth is not in the C-locale shape is now checked once more with ps in the installer's own locale. When that prints the recorded birth for the live group leader holding the record's lease, the record takes the C-locale birth, once; otherwise it is left as it is and proves nothing, as before. Co-Authored-By: Claude Opus 5.5 --- packages/local-installation/AGENTS.md | 7 +- .../src/native-process-darwin-legacy.test.ts | 90 +++++++++++++++++++ .../src/native-process-identity.ts | 28 +++++- .../local-installation/src/native-process.ts | 27 ++++++ 4 files changed, 148 insertions(+), 4 deletions(-) create mode 100644 packages/local-installation/src/native-process-darwin-legacy.test.ts diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md index 1935e102..6e3c2bde 100644 --- a/packages/local-installation/AGENTS.md +++ b/packages/local-installation/AGENTS.md @@ -137,7 +137,12 @@ program fails the start after 15 seconds instead of at the deadline. On POSIX, a start that finds the recorded supervisor gone but processes still carrying its lease (the app was killed with it) ends them as a stop does and starts the service again. A live recorded PID or process group -without the lease proves nothing and is refused, never signalled. A start +without the lease proves nothing and is refused, never signalled. +On macOS every identity check reads `ps` start times in the C locale. +Linger 0.1.2 recorded them in the locale it ran in; such a record is +converted once to the C-locale birth when `ps` in the installer's own +locale still prints the recorded birth for the live leader holding the +lease, and is otherwise left as it is. A start that fails before its record is kept ends what it launched: by the lease, or, when the lease cannot be proved, by the group of the supervisor it has not reaped yet, whose PID cannot belong to another program. Before the diff --git a/packages/local-installation/src/native-process-darwin-legacy.test.ts b/packages/local-installation/src/native-process-darwin-legacy.test.ts new file mode 100644 index 00000000..2b1f805c --- /dev/null +++ b/packages/local-installation/src/native-process-darwin-legacy.test.ts @@ -0,0 +1,90 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +// ps as a Mac in a German region format prints it: lstart in the caller's +// locale, C only when the inspector asks for it. +const ps = vi.hoisted(() => { + const uid = process.getuid!(); + return { + uid, + c: `Wed Nov 18 06:04:14 2026 ${uid} 73285 Ss\n`, + localized: `Mi 18 Nov 06:04:14 2026 ${uid} 73285 Ss\n`, + environment: "", + }; +}); +vi.mock("node:child_process", async (original) => ({ + ...(await original()), + execFile: ( + _executable: string, + args: string[], + options: { env: NodeJS.ProcessEnv }, + callback: (error: null, stdout: string) => void, + ) => { + if (args[0] === "eww") callback(null, ps.environment); + else callback(null, options.env.LC_ALL === "C" ? ps.c : ps.localized); + }, +})); + +const { atomicPrivate, privateDirectory } = await import("./instance.js"); +const { inspectNativeProcess } = await import("./native-process.js"); + +const lease = "a".repeat(64); +// What Linger 0.1.2 recorded for that process: the localized start time. +const legacyBirth = `darwin:Mi:18:Nov:06:04:14:2026:${ps.uid}:73285`; +const platform = process.platform; +let root: string; +const recordFile = () => + path.join(root, "native", "processes", "postgres.json"); +const birth = async () => + (JSON.parse(await readFile(recordFile(), "utf8")) as { birth: string }).birth; + +beforeEach(async () => { + root = await mkdtemp(path.join(tmpdir(), "linger-darwin-legacy-")); + await privateDirectory(path.join(root, "native", "processes")); + await atomicPrivate( + recordFile(), + JSON.stringify({ + schemaVersion: 1, + name: "postgres", + pid: 73285, + birth: legacyBirth, + lease, + configuration: "b".repeat(64), + }), + ); + Object.defineProperty(process, "platform", { value: "darwin" }); + vi.stubEnv("LANG", "de_DE.UTF-8"); + ps.localized = `Mi 18 Nov 06:04:14 2026 ${ps.uid} 73285 Ss\n`; + ps.environment = `node worker.mjs LINGER_NATIVE_PROCESS_LEASE=${lease}\n`; +}); +afterEach(async () => { + Object.defineProperty(process, "platform", { value: platform }); + vi.unstubAllEnvs(); + await rm(root, { recursive: true, force: true }); +}); + +it("adopts a service 0.1.2 recorded with a localized start time, once", async () => { + await expect(inspectNativeProcess(root, "postgres")).resolves.toEqual({ + running: true, + pid: 73285, + }); + expect(await birth()).toBe(`darwin:Wed:Nov:18:06:04:14:2026:${ps.uid}:73285`); +}); + +it("keeps the record when the localized start time names another process", async () => { + ps.localized = `Mi 18 Nov 07:00:00 2026 ${ps.uid} 73285 Ss\n`; + await expect(inspectNativeProcess(root, "postgres")).resolves.toMatchObject({ + running: false, + }); + expect(await birth()).toBe(legacyBirth); +}); + +it("keeps the record of a process without the lease", async () => { + ps.environment = "node worker.mjs\n"; + await expect(inspectNativeProcess(root, "postgres")).resolves.toMatchObject({ + running: false, + }); + expect(await birth()).toBe(legacyBirth); +}); diff --git a/packages/local-installation/src/native-process-identity.ts b/packages/local-installation/src/native-process-identity.ts index d5c62344..8adfff99 100644 --- a/packages/local-installation/src/native-process-identity.ts +++ b/packages/local-installation/src/native-process-identity.ts @@ -5,13 +5,16 @@ const leaseKey = "LINGER_NATIVE_PROCESS_LEASE"; function runProcess( executable: string, args: string[], - options: { timeoutMs: number }, + options: { timeoutMs: number; locale?: "c" | "inherited" }, ) { // Inspectors must not inherit the lease and appear among the owned processes. // ps prints lstart in the caller's locale (a zh-CN Mac prints a different // number of fields), and a recorded birth must read the same from every // process that checks it, so inspectors run in the C locale. - const env: NodeJS.ProcessEnv = { ...process.env, LC_ALL: "C", LANG: "C" }; + const env: NodeJS.ProcessEnv = + options.locale === "inherited" + ? { ...process.env } + : { ...process.env, LC_ALL: "C", LANG: "C" }; delete env[leaseKey]; return new Promise<{ code: number; stdout: string }>((resolve, reject) => { execFile( @@ -183,10 +186,29 @@ export function darwinProcessIdentity( state, }; } +/** + * The birth of a macOS process as Linger 0.1.2 recorded it: lstart in the + * locale the installer ran in, not the C locale every check now uses. Only + * for converting such a record; undefined elsewhere. + */ +export function legacyDarwinIdentity( + pid: number, + lease: string, +): Promise { + if (process.platform !== "darwin") return Promise.resolve(undefined); + return nativeProcessIdentity(pid, lease, true, "inherited"); +} +/** Whether a recorded macOS birth reads lstart in the C locale. */ +export function darwinBirthInCLocale(birth: string): boolean { + return /^darwin:(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat):(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec):\d{1,2}:\d{2}:\d{2}:\d{2}:\d{4}:\d+:\d+$/.test( + birth, + ); +} export async function nativeProcessIdentity( pid: number, lease: string, requireLeader = true, + locale: "c" | "inherited" = "c", ): Promise { try { if (process.platform === "win32") { @@ -214,7 +236,7 @@ export async function nativeProcessIdentity( runProcess( "/bin/ps", ["-p", String(pid), "-o", "lstart=,uid=,pgid=,stat="], - { timeoutMs: 5_000 }, + { timeoutMs: 5_000, locale }, ), // Read only this candidate. Never print the output: it contains // environment values. The unguessable launch lease survives execve. diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.ts index 489afffd..c68507e1 100644 --- a/packages/local-installation/src/native-process.ts +++ b/packages/local-installation/src/native-process.ts @@ -8,6 +8,8 @@ import { setTimeout as delay } from "node:timers/promises"; import { atomicPrivate, privateDirectory, readPrivate } from "./instance.js"; import { runProcess, windowsTreeTermination } from "./process.js"; import { + darwinBirthInCLocale, + legacyDarwinIdentity, linuxProcessStates, nativeProcessIdentity as observed, nativeLeaseProcesses, @@ -68,8 +70,33 @@ async function stored( !/^[a-f0-9]{64}$/.test(record.configuration) ) throw new Error("Invalid native process identity record"); + if (process.platform === "darwin" && !darwinBirthInCLocale(record.birth)) + return adoptLegacyDarwinBirth(root, name, record); return record; } +/** + * Linger 0.1.2 recorded a macOS birth with lstart in the locale it ran in; + * every check now reads it in the C locale, so a service it started in, for + * example, a German region format never matched again. When ps in this + * process's own locale still prints the recorded birth for the live leader + * holding the lease, it is that service: its record takes the C-locale birth, + * once. Otherwise the record stays as it is and proves nothing. + */ +async function adoptLegacyDarwinBirth( + root: string, + name: NativeService, + record: Lease, +): Promise { + const current = await observed(record.pid, record.lease); + if ( + !current || + (await legacyDarwinIdentity(record.pid, record.lease)) !== record.birth + ) + return record; + const converted = { ...record, birth: current }; + await atomicPrivate(paths(root, name).record, JSON.stringify(converted)); + return converted; +} async function stillLive(pid: number): Promise { try { if (process.platform === "win32") { From 8bb56061a706b1dc436dfa58ac015d43f10ba704 Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 19 Nov 2026 03:20:21 +0800 Subject: [PATCH 9/9] fix(desktop): word localmodels setup reasons by code in the setup window The setup window printed the localmodels tool's reason message verbatim and hid the Local model card when no model was offered. The installer's setup report now carries each reason as {code, message, gpuIndex?, freeBytes?, requiredBytes?}; the desktop passes the code and counts to the page and keeps the tool's words in its log. The page words every code (gpu-memory-required and free-memory-required with free against needed memory, gpu-sharing-required, plan-unavailable, facts-unavailable, unsupported-platform, and dev39's gpu-ownership-unknown), keeps the card visible and disabled with the reason, names the system tray off macOS and labels the card's memory as the whole stack's. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/AGENTS.md | 19 +- apps/desktop/src/main/local-server.test.ts | 19 +- apps/desktop/src/main/local-server.ts | 61 +++--- apps/desktop/src/shared/setup.ts | 22 ++- apps/desktop/src/shell/setup-page.test.ts | 171 ++++++++++++---- apps/desktop/src/shell/setup.html | 186 ++++++++++++------ apps/linger-installer/src/server/api.test.ts | 2 +- apps/linger-installer/src/web/App.test.tsx | 5 +- .../src/generated/linger-installer/types.ts | 14 +- .../openapi/linger-installer/openapi.yaml | 26 ++- .../local-installation/src/setup-plan.test.ts | 68 +++++-- packages/local-installation/src/setup-plan.ts | 43 ++-- 12 files changed, 457 insertions(+), 179 deletions(-) diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 2b133f8e..0fb07a66 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -138,8 +138,14 @@ Gateway and runs Agents. The daemon exits with the app. Quick Install installs the `recommendation` of the localmodels setup report (`installer.js --inspect`, run once as the setup window opens): `local-models` is the planned model served by Pi, shown with the model, - GPU, memory and download, plus the tool's caveat when it has one; - otherwise the named runtime, with the tool's reason for no local model. + GPU, memory and download (the card's memory is the whole stack's, so + "with its services"); otherwise the named runtime, with why there is no + local model. The page words each reason by its code and the counts it + carries (`gpuIndex`, `freeBytes`, `requiredBytes`); the tool's message + goes only to the main process log (`local_server.inspected`), never to + the page. Under Customize the Local model card stays visible once the + check ends: disabled, "Not available on this computer", with that reason. + Off macOS the page names the system tray, not the menu bar. Under Customize the local model runs only behind Pi: with another runtime it is greyed (`aria-disabled`, still focusable), does not toggle, and says "Local models are only available with the Pi runtime."; choosing another @@ -149,10 +155,11 @@ Gateway and runs Agents. The daemon exits with the app. memory it needs now; a tool before that field marks it by `basis: "capacity"` or reason `free-memory-required`, either one), the install would plan again against the memory free then and stop, so the local model - shows on hold and is not offered. With the tool's `stack.memory` the page - says "quit other programs first; it needs X of memory, Y is free" (and the - graphics memory on a discrete GPU), adding the tool's words for any other - reason code; without it, the tool's reason. Quick Install installs the + shows on hold and is not offered. `gpu-memory-required` names the GPU and + its free against needed memory and says to close programs that use the + GPU; `free-memory-required` gives the RAM counts (from the reason, or the + tool's `stack.memory` when the reason has none). The page still words + `gpu-ownership-unknown`, which localmodels 0.1.0.dev39 reports. Quick Install installs the runtime the installer recommends instead, and Check again (`local.recheck`) runs the check again. A tool before `stack.state` still recommends `local-models` there, so the installer's setup adapter diff --git a/apps/desktop/src/main/local-server.test.ts b/apps/desktop/src/main/local-server.test.ts index 64059d1b..3c525fad 100644 --- a/apps/desktop/src/main/local-server.test.ts +++ b/apps/desktop/src/main/local-server.test.ts @@ -119,8 +119,11 @@ if (args.includes("--inspect")) { } process.stderr.write("Checked this computer in 1.5s.\n"); const lowMemory = eligible && fs.existsSync(path.join(home, "low-memory")); - const reasons = eligible ? (lowMemory ? ["free-memory-required"] : []) : ["facts-unavailable"]; - const reasonMessages = eligible ? (lowMemory ? ["Close other programs before installing."] : []) : ["nvidia-smi was not found"]; + const reasons = eligible + ? lowMemory + ? [{ code: "free-memory-required", message: "Close other programs before installing.", freeBytes: 2899102924, requiredBytes: 13689304433 }] + : [] + : [{ code: "facts-unavailable", message: "nvidia-smi was not found" }]; // With the plan priced on capacity, the installer recommends a runtime. const recommendation = eligible && !lowMemory ? "local-models" : "codex"; const local = { @@ -128,7 +131,7 @@ if (args.includes("--inspect")) { state: lowMemory ? "blocked-now" : eligible ? "ready" : "unavailable", ...(lowMemory ? { basis: "capacity", memory: { ramAvailableBytes: 2899102924, ramRequiredBytes: 13689304433 } } : {}), }; - process.stdout.write(JSON.stringify({ hardware, localModels: { ...local, reasons, reasonMessages, estimate }, recommendation }) + "\n"); + process.stdout.write(JSON.stringify({ hardware, localModels: { ...local, reasons, estimate }, recommendation }) + "\n"); process.exit(0); } if (args.includes("--resume")) { @@ -1621,14 +1624,13 @@ describe("LocalServerModule", () => { expect(f.module.status().localModels).toMatchObject({ state: "checked", eligible: false, - reasons: [ - { code: "facts-unavailable", message: "nvidia-smi was not found" }, - ], + reasons: [{ code: "facts-unavailable" }], recommendation: "codex", }), ); expect(f.module.status().localModels).not.toHaveProperty("model"); - // The log says why, as the localmodels tool did. + // The page gets the code only; the tool's words go to the log. + expect(JSON.stringify(f.module.status())).not.toContain("nvidia-smi"); expect(info).toHaveBeenCalledWith( "local_server.inspected", expect.objectContaining({ @@ -1660,7 +1662,8 @@ describe("LocalServerModule", () => { reasons: [ { code: "free-memory-required", - message: "Close other programs before installing.", + freeBytes: 2899102924, + requiredBytes: 13689304433, }, ], recommendation: "codex", diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts index c25f30e6..da6cf2b3 100644 --- a/apps/desktop/src/main/local-server.ts +++ b/apps/desktop/src/main/local-server.ts @@ -75,7 +75,11 @@ import { savedProviderKeys, type ProviderKeyChanges, } from "./provider-keys.js"; -import type { SetupByokCheck, SetupByokConfig } from "../shared/setup.js"; +import type { + SetupByokCheck, + SetupByokConfig, + SetupReason, +} from "../shared/setup.js"; // The pinned linger source this build installs, written by the release build: // downloaded from `url` (or a mirror of it), or bundled in the app at `file`. @@ -129,19 +133,14 @@ export type LocalModelsCheck = readonly gpu?: string; // Present when eligible or when it needs free memory. readonly model?: LocalModel; - // The localmodels tool's code and words for why not, or, when - // eligible, for what could still stop the install. + // The localmodels tool's code for why not, or, when eligible, for + // what could still stop the install, with the counts it carries. readonly reasons?: readonly SetupReason[]; // The localmodels tool's pick for this computer, which Quick Install // installs; the page adds no rule of its own. readonly recommendation?: SetupChoice; }; -export interface SetupReason { - readonly code: string; - readonly message?: string; -} - // A download under way: its bytes so far and in all, and the rate when the // source reports one. partial: the counts cover only the file downloading // now, so nothing says what remains. @@ -664,7 +663,7 @@ export class LocalServerModule implements Module { this.#ctx?.bus.emit("local-server.changed"); }) .then( - (check) => { + ({ check, reasonLog }) => { this.#ctx?.log.info("local_server.inspected", { ms: Date.now() - started, eligible: check.state === "checked" && check.eligible, @@ -674,13 +673,7 @@ export class LocalServerModule implements Module { ...(check.state === "checked" && check.recommendation ? { recommendation: check.recommendation } : {}), - ...(check.state === "checked" && check.reasons - ? { - reasons: check.reasons.map(({ code, message }) => - message ? `${code}: ${message}` : code, - ), - } - : {}), + ...(reasonLog.length ? { reasons: reasonLog } : {}), }); this.#check = check; }, @@ -782,7 +775,11 @@ export class LocalServerModule implements Module { async #inspect( signal: AbortSignal, onDownload: (download: Transfer) => void, - ): Promise { + ): Promise<{ + check: LocalModelsCheck; + // The tool's codes with its words, for the log only. + reasonLog: string[]; + }> { // The app's own Node runs the check, so it needs no download of its own; // installing still uses the pinned Node runtime. const output = await new Promise((resolve, reject) => { @@ -840,7 +837,6 @@ export class LocalServerModule implements Module { state?: unknown; memory?: Record; reasons?: unknown; - reasonMessages?: unknown; estimate?: { model?: unknown; downloadBytes?: unknown; @@ -889,12 +885,26 @@ export class LocalServerModule implements Module { : {}), } : undefined; - const strings = (value: unknown) => - Array.isArray(value) ? value.map(String) : []; - const messages = strings(report.localModels.reasonMessages); - const reasons = strings(report.localModels.reasons).map( - (code, index): SetupReason => - messages[index] ? { code, message: messages[index] } : { code }, + const listed = Array.isArray(report.localModels.reasons) + ? (report.localModels.reasons as Record[]).filter( + (reason) => typeof reason?.code === "string", + ) + : []; + // The page words each reason by its code and counts, never the tool's. + const reasons = listed.map((reason): SetupReason => { + const counted = (key: "gpuIndex" | "freeBytes" | "requiredBytes") => + bytes(reason[key]) !== null ? { [key]: reason[key] as number } : {}; + return { + code: reason.code as string, + ...counted("gpuIndex"), + ...counted("freeBytes"), + ...counted("requiredBytes"), + }; + }); + const reasonLog = listed.map(({ code, message }) => + typeof message === "string" && message + ? `${code}: ${message}` + : `${code}`, ); const pick = report.recommendation; // The local model is recommended only with a model the page can show. @@ -904,7 +914,7 @@ export class LocalServerModule implements Module { (pick !== "local-models" || eligible) ? (pick as SetupChoice) : undefined; - return { + const check: LocalModelsCheck = { state: "checked", eligible, memoryBytes: hardware.totalMemoryBytes, @@ -928,6 +938,7 @@ export class LocalServerModule implements Module { ...(reasons.length ? { reasons } : {}), ...(recommendation ? { recommendation } : {}), }; + return { check, reasonLog }; } // Logs how long one part of setup took, so a slow setup says which part. diff --git a/apps/desktop/src/shared/setup.ts b/apps/desktop/src/shared/setup.ts index ef61ef8d..3ec2ccd4 100644 --- a/apps/desktop/src/shared/setup.ts +++ b/apps/desktop/src/shared/setup.ts @@ -123,6 +123,18 @@ export interface SetupTransfer { readonly partial?: boolean; } +// The localmodels tool's reason code with the counts it carries. Its words +// stay in the main process log; the page has its own copy per code. +export interface SetupReason { + readonly code: string; + // On gpu-memory-required: the card other programs hold memory on. + readonly gpuIndex?: number; + // The memory free now and what the install needs free: that card's VRAM, + // or RAM on free-memory-required. + readonly freeBytes?: number; + readonly requiredBytes?: number; +} + export type SetupLocalModelsCheck = | { readonly state: "unchecked" | "unavailable" } // While the check first downloads the localmodels tool: its bytes. @@ -147,12 +159,10 @@ export type SetupLocalModelsCheck = readonly diskBytes: number | null; readonly memoryBytes: number | null; }; - // The localmodels tool's code and words for why not, or, when - // eligible, for what could still stop the install. - readonly reasons?: readonly { - readonly code: string; - readonly message?: string; - }[]; + // The localmodels tool's code for why not, or, when eligible, for + // what could still stop the install, with the counts it carries. The + // page words each code itself. + readonly reasons?: readonly SetupReason[]; // The localmodels tool's pick, which Quick Install installs: // "local-models" is the model above served by Pi. readonly recommendation?: SetupChoice; diff --git a/apps/desktop/src/shell/setup-page.test.ts b/apps/desktop/src/shell/setup-page.test.ts index a837c6bc..fa4b1e35 100644 --- a/apps/desktop/src/shell/setup-page.test.ts +++ b/apps/desktop/src/shell/setup-page.test.ts @@ -9,6 +9,7 @@ import type { SetupCommand, SetupLocalAccount, SetupLocalModelsCheck, + SetupReason, SetupState, } from "../shared/setup.js"; @@ -203,12 +204,13 @@ const small: SetupLocalModelsCheck = { eligible: false, memoryBytes: 8 * GB, diskFreeBytes: 100 * GB, - // A code the page never parses: it shows only the message. - reasons: [ - { code: "upstream_policy", message: "No model fits this computer." }, - ], + reasons: [{ code: "plan-unavailable" }], recommendation: "codex", }; +// The tool's own words, which the page must never show. +const TOOL_WORDS = "GPU service owners unknown; explicit sharing"; +const reason = (fields: SetupReason): SetupReason => + ({ ...fields, message: TOOL_WORDS }) as SetupReason; // The model fits the hardware, but other programs hold its memory now. const held: SetupLocalModelsCheck = { state: "checked", @@ -222,13 +224,7 @@ const held: SetupLocalModelsCheck = { diskBytes: 8 * GB, memoryBytes: 12 * GB, }, - reasons: [ - { - code: "free-memory-required", - message: - "Other programs are using memory it needs (now 2.7 GB of RAM is available).", - }, - ], + reasons: [reason({ code: "free-memory-required" })], recommendation: "codex", }; const welcome = (localModels: SetupLocalModelsCheck): SetupState => { @@ -263,7 +259,7 @@ describe("setup page Quick Install recommendation", () => { "Recommended for this computer: Codex", ); expect($("plan-why").textContent).toBe( - "No local model: No model fits this computer.", + "No local model fits this computer.", ); expect($("local-row").hidden).toBe(true); $("local-install").click(); @@ -278,7 +274,7 @@ describe("setup page Quick Install recommendation", () => { "Recommended for this computer: Codex", ); expect($("plan-why").textContent).toBe( - "Local model on hold: Other programs are using memory it needs (now 2.7 GB of RAM is available). Quick Install sets up Codex now, or choose Check again once memory is free.", + "Local model on hold. Other programs are using the memory it needs. Close other programs. Quick Install sets up Codex now, or choose Check again once memory is free.", ); expect($("local-recheck").hidden).toBe(false); $("local-customize").click(); @@ -313,25 +309,40 @@ describe("setup page Quick Install recommendation", () => { }); it("says how much memory a held local model needs and how much is free", async () => { - const counted = ( - code: string, - message: string, - vram = false, - ): SetupLocalModelsCheck => ({ + const withCounts = (reasons: SetupReason[]): SetupLocalModelsCheck => ({ ...held, freeMemory: { ramAvailableBytes: 2899102924, ramRequiredBytes: 13689304433, - ...(vram ? { vramFreeBytes: 3 * GB, vramRequiredBytes: 9 * GB } : {}), + vramFreeBytes: 3 * GB, + vramRequiredBytes: 9 * GB, }, - reasons: [{ code, message }], + reasons, }); + const customizeLocal = () => { + $("local-customize").click(); + document + .querySelector( + '[data-plan="source"] [data-value="local"]', + )! + .click(); + }; + // The GPU and the RAM each name what is free and what the install needs. await openPage( welcome( - counted( - "free-memory-required", - "Other programs are using memory it needs.", - ), + withCounts([ + reason({ + code: "gpu-memory-required", + gpuIndex: 1, + freeBytes: 3 * GB, + requiredBytes: 9 * GB, + }), + reason({ + code: "free-memory-required", + freeBytes: 2899102924, + requiredBytes: 13689304433, + }), + ]), ), "welcome", ); @@ -339,31 +350,95 @@ describe("setup page Quick Install recommendation", () => { "Recommended for this computer: Codex", ); expect($("plan-why").textContent).toBe( - "Local model on hold: quit other programs first; it needs 12.7 GB of memory, 2.7 GB is free. Quick Install sets up Codex now, or choose Check again once memory is free.", + "Local model on hold. Other programs are using GPU 1's memory (3.0 GB free, 9.0 GB needed). Close programs that use the GPU, such as games, video or other AI apps. Other programs are using the memory it needs (2.7 GB free, 12.7 GB needed). Close other programs. Quick Install sets up Codex now, or choose Check again once memory is free.", ); expect($("local-recheck").hidden).toBe(false); + customizeLocal(); + expect($("local-sub").textContent).toBe( + "On hold: GPU 1 has 3.0 GB free, needs 9.0 GB", + ); + expect(document.body.textContent).not.toContain(TOOL_WORDS); + // A tool that counts only the plan's memory: the RAM counts from it. + await openPage( + welcome(withCounts([reason({ code: "free-memory-required" })])), + "welcome", + ); + expect($("plan-why").textContent).toBe( + "Local model on hold. Other programs are using the memory it needs (2.7 GB free, 12.7 GB needed). Close other programs. Quick Install sets up Codex now, or choose Check again once memory is free.", + ); + customizeLocal(); + expect($("local-sub").textContent).toBe( + "On hold: 2.7 GB of memory free, needs 12.7 GB", + ); + }); + + it("words every localmodels reason by its code, never the tool's message", async () => { + const cases: [SetupLocalModelsCheck, string][] = [ + [ + { ...held, reasons: [reason({ code: "gpu-sharing-required" })] }, + "Local model on hold. Other work is running on the GPU. Close it.", + ], + [ + { ...held, reasons: [reason({ code: "plan-unavailable" })] }, + "Local model on hold. Another app is holding the memory it needs, such as another AI app. Quit it.", + ], + [ + { ...small, reasons: [reason({ code: "gpu-ownership-unknown" })] }, + "Linger couldn't tell which programs are using the GPU, so it can't share it. Close programs that use the GPU.", + ], + [ + { ...small, reasons: [reason({ code: "facts-unavailable" })] }, + "Linger couldn't read this computer's memory, disk or GPU.", + ], + [ + { ...small, reasons: [reason({ code: "unsupported-platform" })] }, + "Local models don't run on this system.", + ], + [ + { ...small, reasons: [reason({ code: "a-new-code" })] }, + "This computer can't run a local model now.", + ], + ]; + for (const [check, words] of cases) { + await openPage(welcome(check), "welcome"); + expect($("plan-why").textContent).toContain(words); + expect(document.body.textContent).not.toContain(TOOL_WORDS); + } + }); + + it("shows the Local model card disabled with the reason when none can run", async () => { + await openPage( + welcome({ + ...small, + reasons: [reason({ code: "gpu-ownership-unknown" })], + }), + "welcome", + ); $("local-customize").click(); document .querySelector( '[data-plan="source"] [data-value="local"]', )! .click(); - expect($("local-sub").textContent).toBe( - "On hold: 12.7 GB memory needed, 2.7 GB free", + expect($("local-row").hidden).toBe(false); + expect($("local-model").hidden).toBe(false); + expect(($("local-model") as HTMLButtonElement).disabled).toBe(true); + expect($("local-model").getAttribute("aria-checked")).toBe("false"); + expect($("local-model-name").textContent).toBe( + "Not available on this computer", ); - // Another code names what holds the memory, so its words stay. - await openPage( - welcome( - counted( - "plan-unavailable", - "Another inference app holds this Mac's memory; quit it and check again.", - true, - ), - ), - "welcome", + expect($("local-model-needs").textContent).toBe( + "Linger couldn't tell which programs are using the GPU, so it can't share it. Close programs that use the GPU.", ); - expect($("plan-why").textContent).toBe( - "Local model on hold: quit other programs first; it needs 12.7 GB of memory, 2.7 GB is free; graphics memory needs 9.0 GB, 3.0 GB is free. Another inference app holds this Mac's memory; quit it and check again. Quick Install sets up Codex now, or choose Check again once memory is free.", + expect(($("local-install") as HTMLButtonElement).disabled).toBe(true); + expect(document.body.textContent).not.toContain(TOOL_WORDS); + }); + + it("says the stack's memory covers the model and its services", async () => { + await openPage(welcome(capable), "welcome"); + $("local-customize").click(); + expect($("local-model-needs").textContent).toBe( + "6 GB download · 8 GB disk · 12 GB memory with its services", ); }); @@ -605,6 +680,24 @@ describe("setup page Quick Install recommendation", () => { }); }); +describe("setup page permissions", () => { + it("names the menu bar on macOS and the system tray elsewhere", async () => { + const permissions = () => + document.querySelector('[data-step="permissions"]')!.textContent!; + for (const [platform, place] of [ + ["darwin", "menu bar"], + ["win32", "system tray"], + ["linux", "system tray"], + ] as const) { + await openPage({ ...welcome(capable), platform }, "welcome"); + const words = permissions().replace(/\s+/g, " "); + expect(words).toContain(`Change these later from the ${place} or`); + expect(words).toContain(`Start in the ${place} when you log in.`); + if (platform !== "darwin") expect(words).not.toContain("menu bar"); + } + }); +}); + describe("setup page download progress", () => { const installing = (transfer?: SetupState["localServer"]["transfer"]) => { const base = state("installing"); diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.html index dd13c3f1..109de925 100644 --- a/apps/desktop/src/shell/setup.html +++ b/apps/desktop/src/shell/setup.html @@ -2057,7 +2057,8 @@

Connect this computer

A few permissions

- Change these later from the menu bar or in your system settings. + Change these later from the menu bar or in your + system settings.

@@ -2162,7 +2163,10 @@

A few permissions

>
Open at loginStart in the menu bar when you log in. + >Start in the menu bar when you log + in.