Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(computer): run owner-chosen localmodels library actions
Dongdong Chen1f6eb0405aa8
diff --git a/Makefile b/Makefileindex 16dc6f47..6209d4ac 100644--- a/Makefile+++ b/Makefile@@ -127,7 +127,7 @@ check-desktop:check-computer-go:cd apps/computer/local-daemon && go test ./... -run '^$$'cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./internal/platform/...- cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./cmd/linger-computer-daemon ./cmd/linger-computer-launcher ./internal/computercli ./internal/computerconfig ./internal/daemon ./internal/linger/context ./internal/linger/assignment ./internal/linger/control ./internal/linger/registration ./internal/linger/localskills ./internal/linger/mcpproxy ./internal/linger/transport ./internal/linger/runtimehistory ./internal/linger/localtools ./internal/process ./internal/workspace ./internal/provider ./internal/provider/redact ./internal/permission+ cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./cmd/linger-computer-daemon ./cmd/linger-computer-launcher ./internal/computercli ./internal/computerconfig ./internal/daemon ./internal/linger/context ./internal/linger/assignment ./internal/linger/control ./internal/linger/registration ./internal/linger/localskills ./internal/linger/mcpproxy ./internal/linger/transport ./internal/linger/runtimehistory ./internal/linger/localtools ./internal/process ./internal/workspace ./internal/provider ./internal/provider/redact ./internal/permission ./internal/localmodelscd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./internal/provider/nativecheck-computer-release:diff --git a/apps/computer/AGENTS.md b/apps/computer/AGENTS.mdindex dc41599c..ca05a99c 100644--- a/apps/computer/AGENTS.md+++ b/apps/computer/AGENTS.md@@ -16,6 +16,11 @@- It consumes generated Runner Gateway contracts and shared Runtime packages.It must not import another `apps/*` source tree or own TeamHub records, Agentorchestration, model selection, or Room callback behavior.+- It executes the local-model library actions a Computer owner chose+ (download, cancel, load, unload, remove, refresh) through the installer's+ `localmodels` tool, but it never chooses a model: every action names the+ model the owner picked, and fit, placement and recommendation come from+ `localmodels`.## Structurediff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex aa7e3c56..207b0bac 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -100,6 +100,59 @@ structured call and one workspace call with the locally signed-in Codex (checkinthat it writes the file and cannot read files outside the working directory). Itspends model quota and is not part of the default tests.+## Local models++The Daemon runs the model library of the installer's `localmodels` tool for+the Local models page. The Computer config's `local_models` section names the+tool: `python`, `module_directory` (the sealed kit, used as `PYTHONPATH` and+working directory), `state_directory` (`LOCALMODELS_STATE`) and+`base_directory` (`--base-dir`). `packages/local-installation` writes it for+the CLI Computer and the Desktop app for its own; a Computer without it, or+whose interpreter is gone, reports `available: false` with+`TOOL_NOT_INSTALLED`. `internal/localmodels` owns the tool calls; the Daemon+only routes `execute` (kind `local_models`) to it and sends what it publishes.+The Daemon executes the actions the Computer owner chose; it never picks a+model.++- Answer. Every action is answered `accepted` or `refused` with a+ `LocalModelActionRefusal`. `localmodels` checks every precondition before+ it starts work, so a download or load runs as a child process whose first+ event line decides the answer: a progress or result line accepts it, and an+ error line before any progress refuses it with the tool's code and its+ `pool`, `need_bytes` and `free_bytes` (`have_bytes` for download+ refusals). A job that exits without an event is `TOOL_FAILED`. `unload`,+ `remove` and `cancel` are answered when the tool finishes; `refresh` after a+ status read. If the command's `expires_at` passes before the tool decides,+ the Daemon sends no answer (the Gateway, waiting for the same deadline,+ reports the action as unconfirmed) and the outcome reaches the owner only+ through snapshots: an accepted job publishes its progress, and a late+ refusal publishes a fresh status read. Command handling runs off the+ connection loop.+- Jobs. A download or load runs in its own process group and writes its event+ lines to a file under `state/local-models/jobs`, which the Daemon tails, so+ a Daemon restart neither signals the job nor breaks its output. `cancel` is+ `library cancel <model>`; the Daemon never signals a job. Calls that print+ one document also write to files and a timeout kills only the tool process:+ a call may start or restart the local model gateway, which must survive.+- Restart. `localmodels` keeps job records on disk, so a restarted Daemon+ trusts `library status` and rereads it every 2 seconds while a download or+ load it did not start is running. A failed status read (including the first+ one after connecting) is retried with backoff up to one minute until a read+ succeeds, so a transient failure never ends the watch.+- Snapshots. `runner.local_models` carries `library-status/v1` mapped to+ `LocalModelsSnapshot` (pools gain `kind` and `gpu_index`; a value outside+ the contract's closed sets makes the read `TOOL_FAILED`). It is sent after+ every welcome, after every action or job end, and at most every 2 seconds+ for progress. When a job enters a phase (download, verify, load, warm) the+ Daemon rereads the status, which carries what the phase reserved or freed+ (pool use, placement, models unloaded first), and applies the job's line on+ top; later lines of the phase update that snapshot without another read.+- Pi. When the loaded models change, the Daemon asks the Runtime monitor for a+ full discovery, so TeamHub sees Pi's new model list. Each model's+ `pi_model` (`<provider>/<id>`, as an Agent's `runtime_model` stores it) is+ passed through as `localmodels` reports it; the endpoint keeps only the+ loaded engine's `base_url`.+## Codex models cacheSigned in with ChatGPT, Codex blocks its first `thread/start` on a 4–5 sdiff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.goindex b12d484d..3ee8887a 100644--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go@@ -28,6 +28,7 @@ import ("github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/localtools""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/registration""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/localmodels""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs"localprocess "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/process"@@ -35,6 +36,7 @@ import ("github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider/redact""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/selfupdate"localworkspace "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/workspace"+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway")func main() {@@ -279,8 +281,33 @@ func run(args []string) (resultErr error) {computer: computer, rejected: provider.NewRejectedModels(runtimeCredentialFiles(providerEnvironment)),runtimes: runtimes, diagnostics: discovered.Diagnostics, revision: runtimeObservationRevision,}+ // A load or unload changes Pi's model list: the library asks for a+ // full Runtime discovery.+ runtimeRefresh := make(chan struct{}, 1)+ var localDaemon *daemon.Daemon+ var localModelsTool *localmodels.Tool+ if tool := computer.LocalModels; tool != nil {+ localModelsTool = &localmodels.Tool{+ Python: tool.Python, ModuleDirectory: tool.ModuleDirectory,+ StateDirectory: tool.StateDirectory, BaseDirectory: tool.BaseDirectory,+ }+ }+ localModels := localmodels.New(localmodels.Options{+ Tool: localModelsTool, Environment: providerEnvironment,+ JobDirectory: filepath.Join(computer.StateDirectory, "local-models", "jobs"),+ // The library publishes only from Act and Refresh, which the Daemon+ // calls once it runs.+ Publish: func(snapshot wire.LocalModelsSnapshot) { localDaemon.PublishLocalModels(snapshot) },+ RuntimeChanged: func() {+ select {+ case runtimeRefresh <- struct{}{}:+ default:+ }+ },+ })+ defer localModels.Close()codexModelSessions := &provider.CodexSessions{Root: filepath.Join(computer.StateDirectory, "model-invoke", "codex-sessions")}- localDaemon, err := daemon.New(daemon.Options{+ localDaemon, err = daemon.New(daemon.Options{ComputerID: computer.ComputerID, DisplayName: computer.DisplayName,Capacity: computer.MaxConcurrentOperations, Runtimes: runtimes,EnabledRuntimes: computer.EnabledRuntimes,@@ -302,6 +329,7 @@ func run(args []string) (resultErr error) {ComputerPermissions: localtools.NewComputerPermissions(permissionOptions),CLICredentials: cliCredentials,TeamHubCLIBin: teamhubBin,+ LocalModels: localModels,ModelInvoker: provider.ModelInvoker{TempBase: operationTempBase,ClaudeConfigRoot: filepath.Join(computer.StateDirectory, "model-invoke", "claude", ".claude"),@@ -383,6 +411,7 @@ func run(args []string) (resultErr error) {RuntimeBusy: func() bool {return localDaemon.ActiveOperationCount() > 0},+ Refresh: runtimeRefresh,OnChanged: func(next provider.DiscoveryResult) error {logRuntimeDiagnostics(next.Diagnostics)nextProviders, nextRuntimes := providerInstallations(next, providerEnvironment)diff --git a/apps/computer/local-daemon/internal/computercli/arguments.go b/apps/computer/local-daemon/internal/computercli/arguments.goindex 53442b2a..d297b1aa 100644--- a/apps/computer/local-daemon/internal/computercli/arguments.go+++ b/apps/computer/local-daemon/internal/computercli/arguments.go@@ -41,6 +41,7 @@ type command struct {maxRuns *intenabledRuntimes []stringtokenStdin bool+ localModels *stagedLocalModels// daemon service start|stopserviceName string@@ -320,6 +321,9 @@ func parseLogin(args []string, configPath string, options parseOptions) (commandif parsed.enabledRuntimes, err = removeEnabledRuntimes(&args); err != nil {return command{}, err}+ if parsed.localModels, err = removeLocalModelsTool(&args, options); err != nil {+ return command{}, err+ }if len(args) > 0 {return command{}, unknownCommand(append([]string{"login"}, args...), options.commandName)}@@ -343,6 +347,31 @@ func removeRuntimePaths(args *[]string, options parseOptions) (map[string]stringreturn values, nil}+// removeLocalModelsTool reads the four --localmodels-* options, which name+// the installer's localmodels tool together or not at all.+func removeLocalModelsTool(args *[]string, options parseOptions) (*stagedLocalModels, error) {+ names := []string{"--localmodels-python", "--localmodels-module-dir", "--localmodels-state", "--localmodels-base-dir"}+ values := make([]string, len(names))+ given := 0+ for index, name := range names {+ value, err := removeOption(args, name)+ if err != nil {+ return nil, err+ }+ if value != "" {+ values[index] = resolvePath(options.workingDirectory, value)+ given+++ }+ }+ if given == 0 {+ return nil, nil+ }+ if given != len(names) {+ return nil, newError(categoryUsage, "--localmodels-python, --localmodels-module-dir, --localmodels-state and --localmodels-base-dir go together")+ }+ return &stagedLocalModels{Python: values[0], ModuleDirectory: values[1], StateDirectory: values[2], BaseDirectory: values[3]}, nil+}+func removeEnabledRuntimes(args *[]string) ([]string, error) {var types []stringfor index := slices.Index(*args, "--enabled-runtime"); index != -1; index = slices.Index(*args, "--enabled-runtime") {diff --git a/apps/computer/local-daemon/internal/computercli/arguments_test.go b/apps/computer/local-daemon/internal/computercli/arguments_test.goindex bd5534de..90c57940 100644--- a/apps/computer/local-daemon/internal/computercli/arguments_test.go+++ b/apps/computer/local-daemon/internal/computercli/arguments_test.go@@ -75,6 +75,13 @@ Options:--max-concurrent-runs <n> Limit concurrent runs (1-100)--no-max-concurrent-runs Remove the concurrent run limit--codex-auth <path> Use this Codex auth.json+ --localmodels-python <path> Run the localmodels tool with this Python; give+ all four --localmodels-* options together+ --localmodels-module-dir <path>+ The localmodels tool directory+ --localmodels-state <path> The localmodels state directory+ --localmodels-base-dir <path>+ The localmodels model base directory--codex-path <path> Use this Codex executable--claude-path <path> Use this Claude Code executable--pi-path <path> Use this Pi executable@@ -130,6 +137,16 @@ func TestParsedCommandShapes(t *testing.T) {t.Fatalf("%v accepted", args)}}+ parsed, err = parseArguments([]string{"login", "--localmodels-python", "kit/python3", "--localmodels-module-dir", "/kit", "--localmodels-state", "/state", "--localmodels-base-dir", "/models"}, options)+ if err != nil || parsed.localModels == nil || *parsed.localModels != (stagedLocalModels{+ Python: filepath.Join(string(filepath.Separator), "work", "kit", "python3"), ModuleDirectory: filepath.Join(string(filepath.Separator), "kit"),+ StateDirectory: filepath.Join(string(filepath.Separator), "state"), BaseDirectory: filepath.Join(string(filepath.Separator), "models"),+ }) {+ t.Fatalf("login localmodels=%+v err=%v", parsed.localModels, err)+ }+ if _, err := parseArguments([]string{"login", "--localmodels-python", "/kit/python3"}, options); err == nil {+ t.Fatal("a partial localmodels tool location was accepted")+ }parsed, _ = parseArguments([]string{"runtime", "check", "claude-code", "--live", "--pi-path", "bin/pi"}, options)if parsed.name != "runtime-check" || parsed.runtime != "claude" || !parsed.live || parsed.runtimePaths["pi"] != filepath.Join(string(filepath.Separator), "work", "bin", "pi") {t.Fatalf("runtime check=%+v", parsed)diff --git a/apps/computer/local-daemon/internal/computercli/cli.go b/apps/computer/local-daemon/internal/computercli/cli.goindex 02f04800..587da448 100644--- a/apps/computer/local-daemon/internal/computercli/cli.go+++ b/apps/computer/local-daemon/internal/computercli/cli.go@@ -495,6 +495,7 @@ func (c *cli) executeLogin(ctx context.Context, parsed command) (int, error) {maxRunsSet: parsed.maxRunsSet, maxRuns: parsed.maxRuns,runtimePaths: runtimePaths, enabledRuntimes: parsed.enabledRuntimes,codexAuthFile: parsed.codexAuthFile, gatewayURL: parsed.gatewayURL, serverToken: token,+ localModels: parsed.localModels,})if err != nil {return 0, errdiff --git a/apps/computer/local-daemon/internal/computercli/help.go b/apps/computer/local-daemon/internal/computercli/help.goindex 33a70bb2..e68fc796 100644--- a/apps/computer/local-daemon/internal/computercli/help.go+++ b/apps/computer/local-daemon/internal/computercli/help.go@@ -24,6 +24,13 @@ Options:--max-concurrent-runs <n> Limit concurrent runs (1-100)--no-max-concurrent-runs Remove the concurrent run limit--codex-auth <path> Use this Codex auth.json+ --localmodels-python <path> Run the localmodels tool with this Python; give+ all four --localmodels-* options together+ --localmodels-module-dir <path>+ The localmodels tool directory+ --localmodels-state <path> The localmodels state directory+ --localmodels-base-dir <path>+ The localmodels model base directory` + runtimePathOptions + "\n" + configOption + "\n","auth": `Usage:linger-computer auth status [--json]diff --git a/apps/computer/local-daemon/internal/computercli/setup.go b/apps/computer/local-daemon/internal/computercli/setup.goindex 9d82c212..879bd859 100644--- a/apps/computer/local-daemon/internal/computercli/setup.go+++ b/apps/computer/local-daemon/internal/computercli/setup.go@@ -36,8 +36,10 @@ type setupOptions struct {serverToken stringruntimePaths map[string]stringenabledRuntimes []string- stateDirectory string- webURL string+ // localModels locates the installer's localmodels tool; nil for none.+ localModels *stagedLocalModels+ stateDirectory string+ webURL string}type setupResult struct {@@ -268,16 +270,26 @@ func persistPendingRenewal(path string, bundle credentialBundle) error {// stagedConfig is the config file setup writes, in its key order.type stagedConfig struct {// runner_id is the Computer ID key the Daemon config parser reads.- RunnerID string `json:"runner_id"`- CredentialExpiresAt string `json:"credential_expires_at"`- DisplayName string `json:"display_name"`- Gateway stagedGateway `json:"gateway"`- MaxConcurrentOperations *int `json:"max_concurrent_operations,omitempty"`- StateDirectory string `json:"state_directory"`- Codex *stagedCodex `json:"codex,omitempty"`- RuntimePaths map[string]string `json:"runtime_paths"`- EnabledRuntimes []string `json:"enabled_runtimes,omitempty"`- WorkspaceGrants []stagedGrant `json:"workspace_grants"`+ RunnerID string `json:"runner_id"`+ CredentialExpiresAt string `json:"credential_expires_at"`+ DisplayName string `json:"display_name"`+ Gateway stagedGateway `json:"gateway"`+ MaxConcurrentOperations *int `json:"max_concurrent_operations,omitempty"`+ StateDirectory string `json:"state_directory"`+ Codex *stagedCodex `json:"codex,omitempty"`+ RuntimePaths map[string]string `json:"runtime_paths"`+ EnabledRuntimes []string `json:"enabled_runtimes,omitempty"`+ WorkspaceGrants []stagedGrant `json:"workspace_grants"`+ LocalModels *stagedLocalModels `json:"local_models,omitempty"`+}++// stagedLocalModels is the config's local_models section+// (computerconfig.LocalModels).+type stagedLocalModels struct {+ Python string `json:"python"`+ ModuleDirectory string `json:"module_directory"`+ StateDirectory string `json:"state_directory"`+ BaseDirectory string `json:"base_directory"`}type stagedGateway struct {@@ -368,6 +380,7 @@ func stageSetup(normalized normalizedSetup, bundle credentialBundle) ([]byte, stif normalized.codexAuthFile != "" {config.Codex = &stagedCodex{AuthFile: normalized.codexAuthFile}}+ config.LocalModels = normalized.localModelsencoded := []byte(marshalReport(config))for _, file := range []struct {name string@@ -489,6 +502,13 @@ func normalizeSetupOptions(options setupOptions, deps setupDeps) (normalizedSetureturn normalizedSetup{}, newError(categoryConfiguration, "Runtime overrides must be absolute executable paths")}}+ if tool := normalized.localModels; tool != nil {+ for _, path := range []string{tool.Python, tool.ModuleDirectory, tool.StateDirectory, tool.BaseDirectory} {+ if !filepath.IsAbs(path) {+ return normalizedSetup{}, newError(categoryConfiguration, "localmodels tool paths must be absolute")+ }+ }+ }if options.gatewayURL != "" {if err := validateGatewayURL(options.gatewayURL); err != nil {return normalizedSetup{}, errdiff --git a/apps/computer/local-daemon/internal/computercli/setup_test.go b/apps/computer/local-daemon/internal/computercli/setup_test.goindex d7522f5b..5b7c1831 100644--- a/apps/computer/local-daemon/internal/computercli/setup_test.go+++ b/apps/computer/local-daemon/internal/computercli/setup_test.go@@ -247,6 +247,37 @@ func TestSetupPersistsRuntimeScopeAndRunLimitBeforeTheFirstStart(t *testing.T) {}}+func TestSetupWritesTheLocalModelsToolLocation(t *testing.T) {+ server := newExchangeServer(t, "runner-localmodels")+ f := newSetupFixture(t, server)+ root := t.TempDir()+ tool := stagedLocalModels{+ Python: filepath.Join(root, "kit", "python3"), ModuleDirectory: filepath.Join(root, "kit"),+ StateDirectory: filepath.Join(root, "state"), BaseDirectory: filepath.Join(root, "models"),+ }+ f.options.localModels = &tool+ f.deps.startDaemon = func(_ context.Context, configPath string) error {+ encoded, err := os.ReadFile(configPath)+ if err != nil {+ return err+ }+ var config struct {+ LocalModels *stagedLocalModels `json:"local_models"`+ }+ if err := json.Unmarshal(encoded, &config); err != nil || config.LocalModels == nil || *config.LocalModels != tool {+ return errors.New("local_models missing at start: " + string(encoded))+ }+ return nil+ }+ if _, err := runComputerSetup(context.Background(), f.options, f.deps); err != nil {+ t.Fatal(err)+ }+ f.options.localModels = &stagedLocalModels{Python: "python3", ModuleDirectory: tool.ModuleDirectory, StateDirectory: tool.StateDirectory, BaseDirectory: tool.BaseDirectory}+ if _, err := runComputerSetup(context.Background(), f.options, f.deps); err == nil {+ t.Fatal("relative localmodels Python was accepted")+ }+}+func TestSetupRenewsTheExistingComputerIdentity(t *testing.T) {server := newExchangeServer(t, "runner-existing")f := newSetupFixture(t, server)diff --git a/apps/computer/local-daemon/internal/computerconfig/config.go b/apps/computer/local-daemon/internal/computerconfig/config.goindex 21ac9163..f2153bf0 100644--- a/apps/computer/local-daemon/internal/computerconfig/config.go+++ b/apps/computer/local-daemon/internal/computerconfig/config.go@@ -34,6 +34,20 @@ type Config struct {Owners []Owner// Desktop is set when the Linger Desktop app runs this Daemon as its child.Desktop *Desktop+ // LocalModels locates the localmodels tool the installer prepared; nil+ // when this Computer has none.+ LocalModels *LocalModels+}++// LocalModels is where the installer put the localmodels tool and its state.+// The Daemon runs `python -P -s -m localmodels library ...` with PYTHONPATH+// and the working directory set to ModuleDirectory, LOCALMODELS_STATE set to+// StateDirectory and --base-dir set to BaseDirectory.+type LocalModels struct {+ Python string+ ModuleDirectory string+ StateDirectory string+ BaseDirectory string}// Desktop configures a Daemon owned by the Linger Desktop app. The app ships@@ -61,18 +75,26 @@ type WorkspaceGrant struct {}type encodedConfig struct {- RunnerID string `json:"runner_id"`- DisplayName string `json:"display_name"`- Gateway encodedGateway `json:"gateway"`- StateDirectory string `json:"state_directory"`- MaxConcurrentOperations *int `json:"max_concurrent_operations,omitempty"`- RuntimePaths map[string]string `json:"runtime_paths,omitempty"`- EnabledRuntimes json.RawMessage `json:"enabled_runtimes,omitempty"`- PreferredRuntime string `json:"preferred_runtime,omitempty"`- WorkspaceGrants []WorkspaceGrant `json:"workspace_grants"`- CredentialExpiresAt string `json:"credential_expires_at,omitempty"`- Codex *encodedCodex `json:"codex,omitempty"`- Desktop *encodedDesktop `json:"desktop,omitempty"`+ RunnerID string `json:"runner_id"`+ DisplayName string `json:"display_name"`+ Gateway encodedGateway `json:"gateway"`+ StateDirectory string `json:"state_directory"`+ MaxConcurrentOperations *int `json:"max_concurrent_operations,omitempty"`+ RuntimePaths map[string]string `json:"runtime_paths,omitempty"`+ EnabledRuntimes json.RawMessage `json:"enabled_runtimes,omitempty"`+ PreferredRuntime string `json:"preferred_runtime,omitempty"`+ WorkspaceGrants []WorkspaceGrant `json:"workspace_grants"`+ CredentialExpiresAt string `json:"credential_expires_at,omitempty"`+ Codex *encodedCodex `json:"codex,omitempty"`+ Desktop *encodedDesktop `json:"desktop,omitempty"`+ LocalModels *encodedLocalModels `json:"local_models,omitempty"`+}++type encodedLocalModels struct {+ Python string `json:"python"`+ ModuleDirectory string `json:"module_directory"`+ StateDirectory string `json:"state_directory"`+ BaseDirectory string `json:"base_directory"`}type encodedDesktop struct {@@ -121,6 +143,19 @@ func Load(path string, environment map[string]string) (Config, error) {}desktop = &Desktop{TeamHubCLIDirectory: value.Desktop.TeamHubCLIDirectory}}+ var localModels *LocalModels+ if value.LocalModels != nil {+ encoded := value.LocalModels+ for _, path := range []string{encoded.Python, encoded.ModuleDirectory, encoded.StateDirectory, encoded.BaseDirectory} {+ if !filepath.IsAbs(path) {+ return Config{}, errors.New("local_models paths must be absolute")+ }+ }+ localModels = &LocalModels{+ Python: encoded.Python, ModuleDirectory: encoded.ModuleDirectory,+ StateDirectory: encoded.StateDirectory, BaseDirectory: encoded.BaseDirectory,+ }+ }var token stringif value.Gateway.TokenFile != "" {if !filepath.IsAbs(value.Gateway.TokenFile) {@@ -185,7 +220,7 @@ func Load(path string, environment map[string]string) (Config, error) {GatewayURL: value.Gateway.URL, GatewayToken: token, CodexAuthFile: codexAuthFile(value.Codex), StateDirectory: value.StateDirectory,MaxConcurrentOperations: value.MaxConcurrentOperations, RuntimePaths: value.RuntimePaths,EnabledRuntimes: enabledRuntimes, PreferredRuntime: value.PreferredRuntime,- WorkspaceGrants: value.WorkspaceGrants, Owners: owners, Desktop: desktop,+ WorkspaceGrants: value.WorkspaceGrants, Owners: owners, Desktop: desktop, LocalModels: localModels,}, nil}diff --git a/apps/computer/local-daemon/internal/computerconfig/config_local_models_test.go b/apps/computer/local-daemon/internal/computerconfig/config_local_models_test.gonew file mode 100644index 00000000..f30b18f2--- /dev/null+++ b/apps/computer/local-daemon/internal/computerconfig/config_local_models_test.go@@ -0,0 +1,39 @@+package computerconfig++import "testing"++func TestLocalModelsConfigIsOptional(t *testing.T) {+ config, err := loadConfigFields(t, "")+ if err != nil {+ t.Fatal(err)+ }+ if config.LocalModels != nil {+ t.Fatalf("config without local_models has LocalModels = %+v", config.LocalModels)+ }+}++func TestLocalModelsConfigReadsToolLocation(t *testing.T) {+ config, err := loadConfigFields(t, `,"local_models":{"python":"/kit/python/bin/python3","module_directory":"/kit","state_directory":"/home/runtime/localmodels/state","base_directory":"/home/runtime/localmodels/models"}`)+ if err != nil {+ t.Fatal(err)+ }+ want := LocalModels{+ Python: "/kit/python/bin/python3", ModuleDirectory: "/kit",+ StateDirectory: "/home/runtime/localmodels/state", BaseDirectory: "/home/runtime/localmodels/models",+ }+ if config.LocalModels == nil || *config.LocalModels != want {+ t.Fatalf("LocalModels = %+v", config.LocalModels)+ }+}++func TestLocalModelsConfigRejectsRelativeOrMissingPaths(t *testing.T) {+ for _, field := range []string{+ `,"local_models":{"python":"python3","module_directory":"/kit","state_directory":"/s","base_directory":"/b"}`,+ `,"local_models":{"python":"/kit/python3","module_directory":"/kit","state_directory":"/s"}`,+ `,"local_models":{"python":"/kit/python3","module_directory":"/kit","state_directory":"/s","base_directory":"/b","extra":"/x"}`,+ } {+ if _, err := loadConfigFields(t, field); err == nil {+ t.Fatalf("invalid local_models accepted: %s", field)+ }+ }+}diff --git a/apps/computer/local-daemon/internal/daemon/connection.go b/apps/computer/local-daemon/internal/daemon/connection.goindex eef49a20..080190ac 100644--- a/apps/computer/local-daemon/internal/daemon/connection.go+++ b/apps/computer/local-daemon/internal/daemon/connection.go@@ -268,6 +268,17 @@ func (d *Daemon) handleConnectionCommand(ctx, connectionCtx context.Context, strslog.Warn("computer permission outcome was not sent", "error", err)}}()+ case protocol.CommandCapabilityLocalModels:+ if !d.welcomeSeen || command.ConnectionEpoch != d.connectionEpoch {+ return errors.New("Local models command uses a stale connection epoch")+ }+ // Downloads and loads wait for the tool's first answer; Operation+ // commands must not wait behind them.+ go func() {+ if err := d.handleLocalModelsCommand(connectionCtx, stream, command); err != nil {+ slog.Warn("local_models.outcome_not_sent", "error", err)+ }+ }()case protocol.CommandOperationCancel:if !dispatch.followOperation(command, func() error { return d.handleOperationCancel(command) }) {if err := d.handleOperationCancel(command); err != nil {@@ -309,6 +320,7 @@ func (d *Daemon) acceptRunnerWelcome(ctx, connectionCtx context.Context, streamreturn err}go d.heartbeatLoop(connectionCtx, stream, command.HeartbeatIntervalMs)+ d.refreshLocalModels(connectionCtx)return nil}diff --git a/apps/computer/local-daemon/internal/daemon/daemon.go b/apps/computer/local-daemon/internal/daemon/daemon.goindex 34ccb293..55fb3057 100644--- a/apps/computer/local-daemon/internal/daemon/daemon.go+++ b/apps/computer/local-daemon/internal/daemon/daemon.go@@ -64,6 +64,9 @@ type Options struct {OnModelUnavailable func(runtimeType, modelID string)// ModelInvoker runs model invocations; nil answers each with runtime_unavailable.ModelInvoker ModelInvoker+ // LocalModels runs owner-chosen localmodels library actions; nil+ // refuses each with TOOL_NOT_INSTALLED.+ LocalModels LocalModelLibrary}type OperationResolver interface {@@ -119,18 +122,22 @@ type Daemon struct {// what an accepted Operation may start with: Registration snapshots, Agent// Runner commands and Context commands. A start whose revision is unchanged// after its off-lock MCP preparation needs no second Resolve.- authorityRevision uint64- activeOperations map[string]*activeOperation- preparationMu sync.Mutex- preparedOperations map[string]*preparedOperation- providerPrepareMu sync.Mutex- providerPrepares map[string]*providerPrepare- sessionCompactMu sync.Mutex- sessionCompacts map[string]*sessionCompact- takeParkedSession func(runtimeType, contextKey string) parkedSession- modelInvoker ModelInvoker- modelInvokeMu sync.Mutex- modelInvokes map[string]*modelInvoke+ authorityRevision uint64+ activeOperations map[string]*activeOperation+ preparationMu sync.Mutex+ preparedOperations map[string]*preparedOperation+ providerPrepareMu sync.Mutex+ providerPrepares map[string]*providerPrepare+ sessionCompactMu sync.Mutex+ sessionCompacts map[string]*sessionCompact+ takeParkedSession func(runtimeType, contextKey string) parkedSession+ modelInvoker ModelInvoker+ modelInvokeMu sync.Mutex+ modelInvokes map[string]*modelInvoke+ localModels LocalModelLibrary+ // localModelsMu orders runner.local_models sends with their revision.+ localModelsMu sync.Mutex+ localModelsRevision uint64operationWG sync.WaitGroupinputWG sync.WaitGrouppreparationWG sync.WaitGroup@@ -220,6 +227,7 @@ func New(options Options) (*Daemon, error) {takeParkedSession: takeNativeParkedSession,modelInvoker: options.ModelInvoker,modelInvokes: make(map[string]*modelInvoke),+ localModels: options.LocalModels,contextDispatchLimit: defaultContextDispatchLimit,retryDelay: defaultRetryDelay(options.RetryDelay),stableConnection: stableGatewayConnection,diff --git a/apps/computer/local-daemon/internal/daemon/local_models.go b/apps/computer/local-daemon/internal/daemon/local_models.gonew file mode 100644index 00000000..1fe78f11--- /dev/null+++ b/apps/computer/local-daemon/internal/daemon/local_models.go@@ -0,0 +1,152 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/localmodels"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/protocol"+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"+)++// LocalModelLibrary runs the actions a Computer owner chooses on this+// Computer's localmodels library. The Daemon never picks a model itself.+type LocalModelLibrary interface {+ // Act answers once the tool accepted (nil) or refused the action;+ // answered is false when the deadline passed before the tool decided.+ Act(ctx context.Context, action localmodels.Action, deadline time.Time) (refusal *wire.LocalModelActionRefusal, answered bool)+ // Refresh reads the library and publishes the snapshot.+ Refresh(ctx context.Context) wire.LocalModelsSnapshot+}++// refreshLocalModels reports the library on a newly welcomed connection.+func (d *Daemon) refreshLocalModels(ctx context.Context) {+ if d.localModels == nil {+ return+ }+ // Reading the library runs the tool; the connection must not wait.+ go d.localModels.Refresh(ctx)+}++// PublishLocalModels sends one runner.local_models snapshot on the live+// connection. Without one it does nothing: every connection starts with a+// fresh read.+func (d *Daemon) PublishLocalModels(snapshot wire.LocalModelsSnapshot) {+ d.localModelsMu.Lock()+ defer d.localModelsMu.Unlock()+ d.connectionMu.Lock()+ stream := d.diagnosticsStream+ d.connectionMu.Unlock()+ if stream == nil {+ return+ }+ d.localModelsRevision+++ sentAt := time.Now().UTC()+ frame := wire.RunnerLocalModels{+ Type: wire.TypeRunnerLocalModels, ProtocolVersion: d.protocolVersion, RunnerID: d.computerID,+ SentAt: sentAt.Format(time.RFC3339Nano), Revision: d.localModelsRevision, LocalModels: snapshot,+ }+ payload, err := json.Marshal(frame)+ if err == nil {+ err = stream.Send(context.Background(), protocol.Event{+ Type: protocol.EventLocalModels, ProtocolVersion: d.protocolVersion, RunnerID: d.computerID,+ Revision: d.localModelsRevision, SentAt: sentAt, Payload: payload,+ })+ }+ if err != nil {+ slog.Warn("local_models.snapshot_not_sent", "revision", d.localModelsRevision, "error", err)+ }+}++func (d *Daemon) handleLocalModelsCommand(ctx context.Context, stream transport.Stream, command protocol.Command) error {+ var request wire.CapabilityLocalModelsExecute+ if err := json.Unmarshal(command.Payload, &request); err != nil {+ return errors.New("invalid local models command")+ }+ expiresAt, err := time.Parse(time.RFC3339Nano, request.ExpiresAt)+ if err != nil {+ return errors.New("invalid local models command expiry")+ }+ if !expiresAt.After(time.Now()) {+ // The Gateway no longer waits for an answer; starting the action+ // would act on a request nobody follows.+ slog.Info("local_models.command_expired", "action", request.Action, "model", request.ModelID)+ return nil+ }+ action := localmodels.Action{Name: request.Action, Model: request.ModelID, UnloadFirst: request.UnloadFirst}+ var refusal *wire.LocalModelActionRefusal+ switch {+ case request.RunnerID != d.computerID || !d.ownedBy(request.TenantID, request.OwnerActorID):+ // The Agent Service routes only the Computer's own owners here.+ slog.Warn("local_models.command_rejected", "reason", "owner", "action", request.Action)+ refusal = &wire.LocalModelActionRefusal{Code: localmodels.CodeToolFailed, Detail: "the command does not name this Computer's owner"}+ case !validLocalModelAction(action):+ slog.Warn("local_models.command_rejected", "reason", "shape", "action", request.Action)+ refusal = &wire.LocalModelActionRefusal{Code: "MODEL_UNKNOWN", Detail: "the command names no valid model action"}+ case d.localModels == nil:+ refusal = &wire.LocalModelActionRefusal{Code: localmodels.CodeToolNotInstalled}+ default:+ slog.Info("local_models.command_received", "action", action.Name, "model", action.Model, "unload_first", action.UnloadFirst)+ var answered bool+ refusal, answered = d.localModels.Act(ctx, action, expiresAt)+ if !answered {+ // The Gateway stopped waiting at the same deadline and reports the+ // action as unconfirmed; any answer now would be a guess.+ slog.Info("local_models.answer_missed_deadline", "action", action.Name, "model", action.Model)+ return nil+ }+ }+ route := protocol.EventCapabilityLocalModelsAccepted+ var frame any = wire.CapabilityLocalModelsAccepted{+ ProtocolVersion: request.ProtocolVersion, CommandID: request.CommandID, RunnerID: request.RunnerID,+ TenantID: request.TenantID, OwnerActorID: request.OwnerActorID, ConnectionEpoch: request.ConnectionEpoch,+ ExpiresAt: request.ExpiresAt, Type: wire.TypeExecuted, Kind: wire.KindLocalModels,+ Action: request.Action, ModelID: request.ModelID, Outcome: wire.OutcomeAccepted,+ }+ if refusal != nil {+ route = protocol.EventCapabilityLocalModelsRefused+ frame = wire.CapabilityLocalModelsRefused{+ ProtocolVersion: request.ProtocolVersion, CommandID: request.CommandID, RunnerID: request.RunnerID,+ TenantID: request.TenantID, OwnerActorID: request.OwnerActorID, ConnectionEpoch: request.ConnectionEpoch,+ ExpiresAt: request.ExpiresAt, Type: wire.TypeExecuted, Kind: wire.KindLocalModels,+ Action: request.Action, ModelID: request.ModelID, Refusal: *refusal, Outcome: wire.OutcomeRefused,+ }+ slog.Info("local_models.command_refused", "action", action.Name, "model", action.Model, "code", refusal.Code)+ }+ payload, err := json.Marshal(frame)+ if err != nil {+ return err+ }+ return stream.Send(ctx, protocol.Event{+ Type: route, ProtocolVersion: command.ProtocolVersion,+ CommandID: command.CommandID, RunnerID: command.RunnerID,+ TenantID: request.TenantID, OwnerActorID: request.OwnerActorID,+ ConnectionEpoch: command.ConnectionEpoch, SentAt: time.Now().UTC(), Payload: payload,+ })+}++// validLocalModelAction checks what the wire schema requires, so no value+// the tool would read as an option reaches its command line.+func validLocalModelAction(action localmodels.Action) bool {+ switch action.Name {+ case localmodels.ActionRefresh:+ return action.Model == "" && len(action.UnloadFirst) == 0+ case localmodels.ActionDownload, localmodels.ActionCancel, localmodels.ActionUnload, localmodels.ActionRemove:+ return localmodels.ValidModelID(action.Model) && len(action.UnloadFirst) == 0+ case localmodels.ActionLoad:+ if !localmodels.ValidModelID(action.Model) {+ return false+ }+ for _, other := range action.UnloadFirst {+ if !localmodels.ValidModelID(other) || other == action.Model {+ return false+ }+ }+ return true+ }+ return false+}diff --git a/apps/computer/local-daemon/internal/daemon/local_models_test.go b/apps/computer/local-daemon/internal/daemon/local_models_test.gonew file mode 100644index 00000000..23eb4ad4--- /dev/null+++ b/apps/computer/local-daemon/internal/daemon/local_models_test.go@@ -0,0 +1,173 @@+package daemon++import (+ "context"+ "encoding/json"+ "path/filepath"+ "sync"+ "testing"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/localmodels"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/protocol"+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"+)++type fakeLocalModels struct {+ mu sync.Mutex+ actions []localmodels.Action+ refusal *wire.LocalModelActionRefusal+ unanswered bool+}++func (f *fakeLocalModels) Act(_ context.Context, action localmodels.Action, _ time.Time) (*wire.LocalModelActionRefusal, bool) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.actions = append(f.actions, action)+ return f.refusal, !f.unanswered+}++func (f *fakeLocalModels) Refresh(context.Context) wire.LocalModelsSnapshot {+ return wire.LocalModelsSnapshot{}+}++func TestLocalModelsCommandAnswersAcceptedOrRefused(t *testing.T) {+ library := &fakeLocalModels{}+ d := &Daemon{computerID: "computer", localModels: library, owners: []ComputerOwner{{TenantID: "tenant", OwnerActorID: "owner"}}}+ expires := time.Now().Add(time.Minute).UTC().Format(time.RFC3339Nano)+ send := func(fields map[string]any) (protocol.Event, map[string]any) {+ t.Helper()+ request := map[string]any{+ "type": "execute", "kind": "local_models", "protocol_version": "2", "command_id": "command-1",+ "runner_id": "computer", "tenant_id": "tenant", "owner_actor_id": "owner", "connection_epoch": 7, "expires_at": expires,+ }+ for key, value := range fields {+ request[key] = value+ }+ payload, _ := json.Marshal(request)+ stream := &browserEventStream{}+ command := protocol.Command{Type: protocol.CommandCapabilityLocalModels, ProtocolVersion: "2", CommandID: "command-1", RunnerID: "computer", ConnectionEpoch: 7, Payload: payload}+ if err := d.handleLocalModelsCommand(t.Context(), stream, command); err != nil {+ t.Fatal(err)+ }+ if len(stream.events) != 1 {+ t.Fatalf("events = %+v", stream.events)+ }+ var frame map[string]any+ if err := json.Unmarshal(stream.events[0].Payload, &frame); err != nil {+ t.Fatal(err)+ }+ if frame["type"] != "executed" || frame["kind"] != "local_models" || frame["command_id"] != "command-1" ||+ frame["runner_id"] != "computer" || frame["tenant_id"] != "tenant" || frame["connection_epoch"] != float64(7) ||+ frame["expires_at"] != expires || frame["action"] != request["action"] {+ t.Fatalf("identity was not echoed: %v", frame)+ }+ return stream.events[0], frame+ }++ event, frame := send(map[string]any{"action": "load", "model_id": "qwen3-4b:Q4_K_M", "unload_first": []string{"gemma3-4b:Q4_K_M"}})+ if event.Type != protocol.EventCapabilityLocalModelsAccepted || frame["outcome"] != "accepted" || frame["model_id"] != "qwen3-4b:Q4_K_M" || frame["refusal"] != nil {+ t.Fatalf("accepted = %s %v", event.Type, frame)+ }+ if got := library.actions[0]; got.Name != "load" || got.Model != "qwen3-4b:Q4_K_M" || len(got.UnloadFirst) != 1 || got.UnloadFirst[0] != "gemma3-4b:Q4_K_M" {+ t.Fatalf("action = %+v", got)+ }++ need, free := uint64(8<<30), uint64(2<<30)+ library.refusal = &wire.LocalModelActionRefusal{Code: "LOAD_NO_ROOM", Pool: "gpu:0", NeedBytes: &need, FreeBytes: &free}+ event, frame = send(map[string]any{"action": "load", "model_id": "qwen3-4b:Q4_K_M"})+ refusal, _ := frame["refusal"].(map[string]any)+ if event.Type != protocol.EventCapabilityLocalModelsRefused || frame["outcome"] != "refused" ||+ refusal["code"] != "LOAD_NO_ROOM" || refusal["pool"] != "gpu:0" || refusal["need_bytes"] != float64(need) || refusal["free_bytes"] != float64(free) {+ t.Fatalf("refused = %s %v", event.Type, frame)+ }+ library.refusal = nil++ calls := len(library.actions)+ for _, invalid := range []map[string]any{+ {"action": "download", "model_id": "--base-dir=/tmp"},+ {"action": "refresh", "model_id": "qwen3-4b:Q4_K_M"},+ {"action": "unload", "model_id": "qwen3-4b:Q4_K_M", "unload_first": []string{"other:Q4"}},+ {"action": "format", "model_id": "qwen3-4b:Q4_K_M"},+ } {+ if _, frame := send(invalid); frame["outcome"] != "refused" || frame["refusal"].(map[string]any)["code"] != "MODEL_UNKNOWN" {+ t.Fatalf("%v answered %v", invalid, frame)+ }+ }+ if _, frame := send(map[string]any{"action": "refresh", "owner_actor_id": "intruder"}); frame["refusal"].(map[string]any)["code"] != "TOOL_FAILED" {+ t.Fatalf("another owner answered %v", frame)+ }+ if len(library.actions) != calls {+ t.Fatalf("rejected commands reached the library: %+v", library.actions[calls:])+ }++ d.localModels = nil+ if _, frame := send(map[string]any{"action": "refresh"}); frame["refusal"].(map[string]any)["code"] != "TOOL_NOT_INSTALLED" {+ t.Fatalf("no library answered %v", frame)+ }+}++func TestLocalModelsCommandTheToolDidNotDecideInTimeGetsNoAnswer(t *testing.T) {+ library := &fakeLocalModels{unanswered: true}+ d := &Daemon{computerID: "computer", localModels: library, owners: []ComputerOwner{{TenantID: "tenant", OwnerActorID: "owner"}}}+ payload, _ := json.Marshal(map[string]any{+ "runner_id": "computer", "tenant_id": "tenant", "owner_actor_id": "owner", "action": "load", "model_id": "qwen3-4b:Q4_K_M",+ "expires_at": time.Now().Add(time.Minute).UTC().Format(time.RFC3339Nano),+ })+ stream := &browserEventStream{}+ if err := d.handleLocalModelsCommand(t.Context(), stream, protocol.Command{Type: protocol.CommandCapabilityLocalModels, Payload: payload}); err != nil {+ t.Fatal(err)+ }+ // "accepted" would claim a decision the tool never made.+ if len(stream.events) != 0 || len(library.actions) != 1 {+ t.Fatalf("events = %+v, actions = %+v", stream.events, library.actions)+ }+}++func TestExpiredLocalModelsCommandIsNotStarted(t *testing.T) {+ library := &fakeLocalModels{}+ d := &Daemon{computerID: "computer", localModels: library, owners: []ComputerOwner{{TenantID: "tenant", OwnerActorID: "owner"}}}+ payload, _ := json.Marshal(map[string]any{+ "runner_id": "computer", "tenant_id": "tenant", "owner_actor_id": "owner", "action": "download", "model_id": "qwen3-4b:Q4_K_M",+ "expires_at": time.Now().Add(-time.Second).UTC().Format(time.RFC3339Nano),+ })+ stream := &browserEventStream{}+ if err := d.handleLocalModelsCommand(t.Context(), stream, protocol.Command{Type: protocol.CommandCapabilityLocalModels, Payload: payload}); err != nil {+ t.Fatal(err)+ }+ if len(stream.events) != 0 || len(library.actions) != 0 {+ t.Fatalf("expired command answered %+v and ran %+v", stream.events, library.actions)+ }+}++// A Computer without the tool reports available:false on connect through the+// real library.+func TestConnectedComputerWithoutTheToolReportsToolNotInstalled(t *testing.T) {+ stream := &browserEventStream{}+ d := &Daemon{computerID: "computer", protocolVersion: protocol.Version, diagnosticsStream: stream}+ library := localmodels.New(localmodels.Options{JobDirectory: filepath.Join(t.TempDir(), "jobs"), Publish: d.PublishLocalModels})+ defer library.Close()+ d.localModels = library+ library.Refresh(t.Context())+ library.Refresh(t.Context())+ if len(stream.events) != 2 {+ t.Fatalf("events = %+v", stream.events)+ }+ for index, event := range stream.events {+ var frame wire.RunnerLocalModels+ if err := json.Unmarshal(event.Payload, &frame); err != nil {+ t.Fatal(err)+ }+ if event.Type != protocol.EventLocalModels || frame.Type != "runner.local_models" || frame.ProtocolVersion != "2" ||+ frame.RunnerID != "computer" || frame.Revision != uint64(index+1) || frame.LocalModels.Available ||+ frame.LocalModels.Reason == nil || frame.LocalModels.Reason.Code != "TOOL_NOT_INSTALLED" {+ t.Fatalf("frame %d = %s %+v", index, event.Type, frame)+ }+ }++ d.diagnosticsStream = nil+ library.Refresh(t.Context())+ if len(stream.events) != 2 {+ t.Fatal("a snapshot was sent without a connection")+ }+}diff --git a/apps/computer/local-daemon/internal/localmodels/fake_tool_test.go b/apps/computer/local-daemon/internal/localmodels/fake_tool_test.gonew file mode 100644index 00000000..7ee9bb1d--- /dev/null+++ b/apps/computer/local-daemon/internal/localmodels/fake_tool_test.go@@ -0,0 +1,199 @@+package localmodels++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// The test binary doubles as a fake localmodels tool: a Library under test+// runs os.Args[0] as its "python" with LOCALMODELS_FAKE_TOOL=1. The fake+// reads its behavior from files in LOCALMODELS_STATE:+//+// - status.json is what `library status` prints; status-exit makes it+// fail with that exit code.+// - <verb>.json is a fakeScript for every other verb.+// - calls.log records each call's arguments and tool environment.+func TestMain(m *testing.M) {+ if os.Getenv("LOCALMODELS_FAKE_TOOL") == "1" {+ os.Exit(runFakeTool(os.Args[1:]))+ }+ os.Exit(m.Run())+}++type fakeScript struct {+ Lines []fakeLine `json:"lines"`+ Exit int `json:"exit"`+ // StatusAfter replaces status.json before the tool exits.+ StatusAfter json.RawMessage `json:"status_after,omitempty"`+ // MarkCancelled makes this call (a cancel) mark the download cancelled.+ MarkCancelled bool `json:"mark_cancelled,omitempty"`+}++type fakeLine struct {+ Line json.RawMessage `json:"line"`+ DelayMS int `json:"delay_ms,omitempty"`+ // CancelAware lines stop the call with CANCELLED once a cancel ran.+ CancelAware bool `json:"cancel_aware,omitempty"`+}++func runFakeTool(args []string) int {+ state := os.Getenv("LOCALMODELS_STATE")+ if len(args) < 6 || strings.Join(args[:5], " ") != "-P -s -m localmodels library" {+ fmt.Fprintln(os.Stderr, "unexpected invocation", args)+ return 3+ }+ verb := args[5]+ log, _ := os.OpenFile(filepath.Join(state, "calls.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)+ _, _ = fmt.Fprintf(log, "%s|PYTHONPATH=%s|cwd=%s\n", strings.Join(args[5:], " "), os.Getenv("PYTHONPATH"), workingDirectory())+ _ = log.Close()+ if verb == "status" {+ if code, err := os.ReadFile(filepath.Join(state, "status-exit")); err == nil {+ var exit int+ _, _ = fmt.Sscan(string(code), &exit)+ fmt.Fprintln(os.Stderr, "error: library status failed: /private/path")+ return exit+ }+ status, err := os.ReadFile(filepath.Join(state, "status.json"))+ if err != nil {+ return 1+ }+ _, _ = os.Stdout.Write(status)+ return 0+ }+ encoded, err := os.ReadFile(filepath.Join(state, verb+".json"))+ if err != nil {+ return 1+ }+ var script fakeScript+ if err := json.Unmarshal(encoded, &script); err != nil {+ return 1+ }+ if script.MarkCancelled {+ _ = os.WriteFile(filepath.Join(state, "cancelled"), nil, 0o600)+ }+ for _, line := range script.Lines {+ time.Sleep(time.Duration(line.DelayMS) * time.Millisecond)+ if _, err := os.Stat(filepath.Join(state, "cancelled")); line.CancelAware && err == nil {+ fmt.Printf(`{"schema":"localmodels.library-event/v1","event":"error","ok":false,"code":"CANCELLED","detail":"the download was cancelled","model":%q}`+"\n", args[6])+ return 130+ }+ fmt.Println(string(line.Line))+ }+ if script.StatusAfter != nil {+ _ = os.WriteFile(filepath.Join(state, "status.json"), script.StatusAfter, 0o600)+ }+ return script.Exit+}++func workingDirectory() string {+ directory, _ := os.Getwd()+ return directory+}++// fakeTool lays out a Tool that runs the fake.+type fakeTool struct {+ t *testing.T+ tool Tool+ state string+}++func newFakeTool(t *testing.T) *fakeTool {+ t.Helper()+ root := t.TempDir()+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ tool := Tool{+ Python: executable, ModuleDirectory: filepath.Join(root, "kit"),+ StateDirectory: filepath.Join(root, "state"), BaseDirectory: filepath.Join(root, "models"),+ }+ for _, directory := range []string{tool.ModuleDirectory, tool.StateDirectory, tool.BaseDirectory} {+ if err := os.MkdirAll(directory, 0o700); err != nil {+ t.Fatal(err)+ }+ }+ return &fakeTool{t: t, tool: tool, state: tool.StateDirectory}+}++func (f *fakeTool) write(name string, value any) {+ f.t.Helper()+ encoded, err := json.Marshal(value)+ if err != nil {+ f.t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(f.state, name), encoded, 0o600); err != nil {+ f.t.Fatal(err)+ }+}++func (f *fakeTool) script(verb string, script fakeScript) { f.write(verb+".json", script) }++func (f *fakeTool) calls() []string {+ encoded, _ := os.ReadFile(filepath.Join(f.state, "calls.log"))+ return strings.Split(strings.TrimSpace(string(encoded)), "\n")+}++// status is a library-status/v1 document with the given model states.+func status(models ...map[string]any) map[string]any {+ if models == nil {+ models = []map[string]any{}+ }+ return map[string]any{+ "schema": "localmodels.library-status/v1", "tool_version": "0.9.0", "observed_at": "2026-11-13T08:00:00+00:00",+ "host": map[string]any{+ "platform": "linux", "arch": "x86_64", "os_label": "Ubuntu 24.04", "engine_label": "llama.cpp b11370 · CUDA",+ "ram_total_bytes": 64 << 30, "disk_free_bytes": 500 << 30,+ "gpus": []any{map[string]any{"index": 0, "uuid": "GPU-1", "name": "RTX 4090", "total_bytes": 24 << 30, "free_bytes": 20 << 30}},+ "extra": "ignored",+ },+ "pools": []any{+ map[string]any{"id": "gpu:0", "total_bytes": 24 << 30, "used_bytes": 0, "holders": []any{}},+ map[string]any{"id": "system", "total_bytes": 51 << 30, "used_bytes": 1 << 30, "holders": []any{+ map[string]any{"kind": "component", "id": "embedding", "name": "Embedding", "bytes": 1 << 30},+ }},+ },+ "models": models,+ }+}++// testPiModel is the Pi key localmodels reports for testModel while it is on+// the Computer.+const testPiModel = "localmodels-library/localmodels-lib-qwen3-4b-q4-k-m/Qwen3-4B-Q4_K_M"++func model(id, state string) map[string]any {+ entry := map[string]any{+ "id": id, "name": "Qwen3 4B", "description": "A small model.", "quant": "Q4_K_M",+ "context_tokens": 32768, "vision": false, "download_bytes": 3 << 30, "memory_bytes": 4 << 30,+ "fit": "gpu", "recommended": false, "availability": map[string]any{"downloadable": true},+ "pool": "gpu:0", "state": state,+ }+ if state != "absent" && state != "downloading" {+ entry["pi_model"] = testPiModel+ }+ switch state {+ case "loaded":+ entry["endpoint"] = map[string]any{"base_url": "http://127.0.0.1:18100/v1", "gateway_model": "localmodels-library/" + id}+ entry["tokens_per_second"] = 41.5+ case "downloading":+ entry["download"] = map[string]any{"step": "download", "done_bytes": 1 << 30, "total_bytes": 3 << 30, "bytes_per_second": 1 << 20}+ }+ return entry+}++func progressLine(id, phase string, done, total int) json.RawMessage {+ return json.RawMessage(fmt.Sprintf(`{"schema":"localmodels.library-event/v1","event":"progress","model":%q,"phase":%q,"done":%d,"total":%d,"bytes_per_second":1048576}`, id, phase, done, total))+}++func resultLine(id string) json.RawMessage {+ return json.RawMessage(fmt.Sprintf(`{"schema":"localmodels.library-event/v1","event":"result","ok":true,"model":{"id":%q}}`, id))+}++func errorLine(id, code, extra string) json.RawMessage {+ return json.RawMessage(fmt.Sprintf(`{"schema":"localmodels.library-event/v1","event":"error","ok":false,"code":%q,"detail":"refused by the fake","model":%q%s}`, code, id, extra))+}diff --git a/apps/computer/local-daemon/internal/localmodels/library.go b/apps/computer/local-daemon/internal/localmodels/library.gonew file mode 100644index 00000000..58aee26a--- /dev/null+++ b/apps/computer/local-daemon/internal/localmodels/library.go@@ -0,0 +1,726 @@+package localmodels++import (+ "bufio"+ "bytes"+ "context"+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "sync/atomic"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/process"+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"+)++// Defaults for Options left zero.+const (+ defaultProgressInterval = 2 * time.Second+ defaultStatusTimeout = 2 * time.Minute+ defaultActionTimeout = 15 * time.Minute+ // maxRereadInterval bounds the backoff of status reads after failures.+ maxRereadInterval = time.Minute+ tailPollInterval = 100 * time.Millisecond+ maxEventLine = 1 << 20+)++// Options configures a Library.+type Options struct {+ // Tool is nil on a Computer the installer gave no localmodels tool.+ Tool *Tool+ // Environment is the base process environment of every tool call.+ Environment map[string]string+ // JobDirectory holds the output file of each running download or load.+ JobDirectory string+ // Publish receives every new snapshot, in order. It is called only from+ // Act and Refresh and the jobs they start.+ Publish func(wire.LocalModelsSnapshot)+ // RuntimeChanged is told that a model was loaded or unloaded, which+ // changes the model list Pi reports.+ RuntimeChanged func()+ // ProgressInterval bounds how often job progress is published.+ ProgressInterval time.Duration+ StatusTimeout time.Duration+ ActionTimeout time.Duration+}++// Library runs the localmodels tool for one Computer.+//+// Acknowledgement: an action is refused when the tool refuses it, and the+// tool validates every precondition before it starts work. A download or+// load therefore runs as a child process whose first event line decides the+// answer: a progress or result line means the tool passed validation and+// recorded its job (accepted); an error line before any progress is the+// refusal, with the tool's code and structured fields; an exit without any+// event is TOOL_FAILED. unload, remove and cancel are answered when the tool+// finishes. When the command's expiry passes before the tool decides, the+// Library gives no answer (the requester reports the action as unconfirmed)+// and the outcome reaches the owner only through snapshots.+//+// Jobs outlive the Daemon: the child runs in its own process group and+// writes to a file, not a pipe, so a Daemon restart neither signals it nor+// breaks its output. A restarted Daemon trusts `library status`, which+// reads the job records localmodels keeps on disk, and polls it while a job+// it did not start is running.+type Library struct {+ tool *Tool+ environment map[string]string+ jobDirectory string+ publish func(wire.LocalModelsSnapshot)+ runtimeChanged func()+ progressInterval time.Duration+ statusTimeout time.Duration+ actionTimeout time.Duration+ now func() time.Time+ ctx context.Context+ stop context.CancelFunc++ // refreshMu serializes status reads so an older read never replaces a+ // newer one.+ refreshMu sync.Mutex+ // publishMu orders updates of current with their Publish calls.+ publishMu sync.Mutex+ mu sync.Mutex+ current *wire.LocalModelsSnapshot+ // loaded identifies the loaded models of the last status read; nil+ // before the first one.+ loaded *string+ jobs map[string]*job+ lastProgress time.Time+ progressTimer *time.Timer+ // progressTimerID tells a timer callback that already fired whether it+ // is still the pending one.+ progressTimerID uint64+ polling bool+}++type job struct {+ action Action+}++// New returns a Library. Close stops its supervision; jobs keep running.+func New(options Options) *Library {+ ctx, stop := context.WithCancel(context.Background())+ library := &Library{+ tool: options.Tool, environment: options.Environment, jobDirectory: options.JobDirectory,+ publish: options.Publish, runtimeChanged: options.RuntimeChanged,+ progressInterval: options.ProgressInterval, statusTimeout: options.StatusTimeout, actionTimeout: options.ActionTimeout,+ now: time.Now, ctx: ctx, stop: stop, jobs: make(map[string]*job),+ }+ if library.progressInterval <= 0 {+ library.progressInterval = defaultProgressInterval+ }+ if library.statusTimeout <= 0 {+ library.statusTimeout = defaultStatusTimeout+ }+ if library.actionTimeout <= 0 {+ library.actionTimeout = defaultActionTimeout+ }+ if library.publish == nil {+ library.publish = func(wire.LocalModelsSnapshot) {}+ }+ if library.runtimeChanged == nil {+ library.runtimeChanged = func() {}+ }+ if library.jobDirectory != "" {+ // Output files of jobs a previous Daemon started are no longer read.+ _ = os.RemoveAll(library.jobDirectory)+ }+ return library+}++// Close stops reading job output and polling. Running jobs continue.+func (l *Library) Close() {+ l.stop()+ l.mu.Lock()+ if l.progressTimer != nil {+ l.progressTimer.Stop()+ }+ l.mu.Unlock()+}++// Refresh reads the library now, publishes the snapshot and returns it.+func (l *Library) Refresh(ctx context.Context) wire.LocalModelsSnapshot {+ l.refreshMu.Lock()+ defer l.refreshMu.Unlock()+ snapshot := l.read(ctx)+ if ctx.Err() != nil {+ // A read cut short by its caller says nothing about the library.+ return snapshot+ }+ changed := false+ l.mu.Lock()+ if snapshot.Available {+ key := loadedKey(snapshot)+ changed = l.loaded != nil && *l.loaded != key+ l.loaded = &key+ }+ l.mu.Unlock()+ l.commit(snapshot)+ // localmodels registers a loaded model with Pi and unregisters it on+ // unload; the Runtime diagnostics must be read again to list it.+ if changed {+ l.runtimeChanged()+ }+ l.reconcile(snapshot)+ return cloneSnapshot(snapshot)+}++func (l *Library) read(ctx context.Context) wire.LocalModelsSnapshot {+ if l.tool == nil || !l.tool.installed() {+ return unavailable(CodeToolNotInstalled, "", l.now())+ }+ ctx, cancel := context.WithTimeout(ctx, l.statusTimeout)+ defer cancel()+ stdout, exitCode, err := l.runOnce(ctx, Action{Name: ActionRefresh})+ if err != nil || exitCode != 0 {+ slog.Warn("local_models.status_failed", "exit_code", exitCode, "error", err)+ return unavailable(CodeToolFailed, "localmodels did not report its library status", l.now())+ }+ snapshot, err := mapStatus(stdout, l.now())+ if err != nil {+ slog.Warn("local_models.status_invalid", "error", err)+ return unavailable(CodeToolFailed, "localmodels reported a library status outside its contract", l.now())+ }+ return snapshot+}++// loadedKey names the loaded models; a change means Pi's model list changed.+func loadedKey(snapshot wire.LocalModelsSnapshot) string {+ var loaded []string+ for _, model := range snapshot.Models {+ if model.State == "loaded" {+ loaded = append(loaded, model.ID)+ }+ }+ sort.Strings(loaded)+ return strings.Join(loaded, "\x01")+}++func (l *Library) commit(snapshot wire.LocalModelsSnapshot) {+ l.publishMu.Lock()+ defer l.publishMu.Unlock()+ l.mu.Lock()+ l.current = &snapshot+ l.mu.Unlock()+ // Progress lines edit current in place; receivers get their own copy.+ l.publish(cloneSnapshot(snapshot))+}++// Act starts one action and returns the tool's answer: accepted (nil) or+// its refusal. deadline is when the requester stops waiting. When it passes+// before the tool has decided, answered is false: the Daemon does not guess+// an answer, the requester reports the action as unconfirmed, and the+// outcome reaches the owner through the snapshots published once the tool+// decides.+func (l *Library) Act(ctx context.Context, action Action, deadline time.Time) (refusal *wire.LocalModelActionRefusal, answered bool) {+ if l.tool == nil || !l.tool.installed() {+ if action.Name == ActionRefresh {+ l.Refresh(ctx)+ }+ return &wire.LocalModelActionRefusal{Code: CodeToolNotInstalled}, true+ }+ switch action.Name {+ case ActionRefresh:+ if snapshot := l.Refresh(ctx); !snapshot.Available {+ return &wire.LocalModelActionRefusal{Code: snapshot.Reason.Code, Detail: snapshot.Reason.Detail}, true+ }+ return nil, true+ case ActionDownload, ActionLoad:+ l.mu.Lock()+ known := l.current != nil+ l.mu.Unlock()+ if !known {+ // Progress lines update the last snapshot; read one first.+ l.Refresh(ctx)+ }+ return l.startJob(ctx, action, deadline)+ case ActionUnload, ActionRemove, ActionCancel:+ return l.runAction(ctx, action, deadline)+ }+ return &wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "unknown local model action"}, true+}++// runOnce runs a call that prints one JSON document and returns its stdout.+// Output goes to files and a timeout kills only the tool itself: a call may+// start or restart a long-lived server (the local model gateway) that+// inherits its output and process group, and that server must survive.+func (l *Library) runOnce(ctx context.Context, action Action) ([]byte, int, error) {+ stdout, err := l.jobOutput()+ if err != nil {+ return nil, -1, err+ }+ defer func() { _ = os.Remove(stdout.Name()) }()+ stderr, err := l.jobOutput()+ if err != nil {+ _ = stdout.Close()+ return nil, -1, err+ }+ defer func() { _ = os.Remove(stderr.Name()) }()+ cmd := l.tool.command(l.environment, action)+ cmd.Stdout, cmd.Stderr = stdout, stderr+ process.Prepare(cmd)+ err = cmd.Start()+ _ = stdout.Close()+ _ = stderr.Close()+ if err != nil {+ return nil, -1, err+ }+ exited := make(chan error, 1)+ go func() { exited <- cmd.Wait() }()+ select {+ case <-exited:+ case <-ctx.Done():+ _ = cmd.Process.Kill()+ <-exited+ return nil, -1, context.Cause(ctx)+ }+ exitCode := cmd.ProcessState.ExitCode()+ output, err := readBounded(stdout.Name(), maxEventLine)+ if exitCode != 0 {+ // Local diagnostics only: tool prose can name local paths.+ if diagnostic, readErr := readBounded(stderr.Name(), 4096); readErr == nil && len(diagnostic) > 0 {+ slog.Debug("local_models.tool_stderr", "action", action.Name, "stderr", string(diagnostic))+ }+ }+ return output, exitCode, err+}++func readBounded(path string, limit int64) ([]byte, error) {+ file, err := os.Open(path)+ if err != nil {+ return nil, err+ }+ defer file.Close()+ return io.ReadAll(io.LimitReader(file, limit))+}++// runAction answers unload, remove and cancel once the tool finishes.+func (l *Library) runAction(ctx context.Context, action Action, deadline time.Time) (*wire.LocalModelActionRefusal, bool) {+ answer := newPendingAnswer()+ go func() {+ runCtx, cancel := context.WithTimeout(l.ctx, l.actionTimeout)+ defer cancel()+ stdout, exitCode, err := l.runOnce(runCtx, action)+ refusal := documentRefusal(stdout, exitCode, err)+ answer.give(refusal)+ slog.Info("local_models.action_finished", "action", action.Name, "model", action.Model,+ "exit_code", exitCode, "refused", refusal != nil)+ switch {+ case refusal == nil:+ l.Refresh(l.ctx)+ if action.Name != ActionCancel {+ l.runtimeChanged()+ }+ case answer.missed():+ // Nobody heard the refusal; the snapshot is how the owner sees+ // that nothing changed.+ l.Refresh(l.ctx)+ }+ }()+ return answer.await(ctx, deadline)+}++// documentRefusal reads the one result or error document of a JSON call.+func documentRefusal(stdout []byte, exitCode int, err error) *wire.LocalModelActionRefusal {+ if err != nil {+ return &wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "localmodels did not finish"}+ }+ event, ok := parseEvent(bytes.TrimSpace(stdout))+ switch {+ case ok && event.Event == "result" && exitCode == 0:+ return nil+ case ok && event.Event == "error":+ return event.refusal()+ }+ return &wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "localmodels exited without a result"}+}++// pendingAnswer carries the tool's one answer to the requester, who waits+// until its deadline. Whether the answer missed it is recorded, so the side+// that produced the answer knows to make the outcome visible another way.+type pendingAnswer struct {+ answer chan *wire.LocalModelActionRefusal+ late atomic.Bool+}++func newPendingAnswer() *pendingAnswer {+ return &pendingAnswer{answer: make(chan *wire.LocalModelActionRefusal, 1)}+}++func (p *pendingAnswer) give(refusal *wire.LocalModelActionRefusal) { p.answer <- refusal }++// missed reports whether the requester stopped waiting before the answer.+func (p *pendingAnswer) missed() bool { return p.late.Load() }++func (p *pendingAnswer) await(ctx context.Context, deadline time.Time) (*wire.LocalModelActionRefusal, bool) {+ timer := time.NewTimer(time.Until(deadline))+ defer timer.Stop()+ select {+ case refusal := <-p.answer:+ return refusal, true+ case <-timer.C:+ case <-ctx.Done():+ }+ p.late.Store(true)+ // An answer given at the same moment still counts.+ select {+ case refusal := <-p.answer:+ return refusal, true+ default:+ return nil, false+ }+}++// startJob starts a download or load and answers from its first event.+func (l *Library) startJob(ctx context.Context, action Action, deadline time.Time) (*wire.LocalModelActionRefusal, bool) {+ output, err := l.jobOutput()+ if err != nil {+ slog.Warn("local_models.job_output_failed", "error", err)+ return &wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "the Computer could not start localmodels"}, true+ }+ cmd := l.tool.command(l.environment, action)+ cmd.Stdout, cmd.Stderr = output, output+ // Its own process group, outside any job object: the job must outlive+ // this Daemon.+ process.Prepare(cmd)+ if err := cmd.Start(); err != nil {+ _ = output.Close()+ _ = os.Remove(output.Name())+ slog.Warn("local_models.job_start_failed", "action", action.Name, "error", err)+ return &wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "the Computer could not start localmodels"}, true+ }+ _ = output.Close()+ slog.Info("local_models.job_started", "action", action.Name, "model", action.Model, "pid", cmd.Process.Pid)+ exited := make(chan int, 1)+ go func() {+ _ = cmd.Wait()+ exited <- cmd.ProcessState.ExitCode()+ }()+ events := make(chan libraryEvent, 64)+ ended := make(chan int, 1)+ go func() { ended <- l.tail(output.Name(), exited, events) }()+ answer := newPendingAnswer()+ go l.superviseJob(action, events, ended, answer)+ return answer.await(ctx, deadline)+}++func (l *Library) jobOutput() (*os.File, error) {+ if err := os.MkdirAll(l.jobDirectory, 0o700); err != nil {+ return nil, err+ }+ name := make([]byte, 12)+ if _, err := rand.Read(name); err != nil {+ return nil, err+ }+ return os.OpenFile(filepath.Join(l.jobDirectory, hex.EncodeToString(name)+".jsonl"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)+}++// tail reads event lines from the job's output file until the job exits,+// then returns its exit code. It closes events.+func (l *Library) tail(path string, exited <-chan int, events chan<- libraryEvent) int {+ defer close(events)+ defer func() { _ = os.Remove(path) }()+ file, err := os.Open(path)+ if err != nil {+ return <-exited+ }+ defer file.Close()+ reader := bufio.NewReader(file)+ var pending []byte+ drain := func() {+ for {+ chunk, err := reader.ReadBytes('\n')+ pending = append(pending, chunk...)+ if len(pending) > maxEventLine {+ pending = nil+ }+ if err != nil {+ return+ }+ if event, ok := parseEvent(bytes.TrimSpace(pending)); ok {+ events <- event+ }+ pending = nil+ }+ }+ ticker := time.NewTicker(tailPollInterval)+ defer ticker.Stop()+ for {+ drain()+ select {+ case code := <-exited:+ drain()+ if event, ok := parseEvent(bytes.TrimSpace(pending)); ok {+ events <- event+ }+ return code+ case <-l.ctx.Done():+ return -1+ case <-ticker.C:+ }+ }+}++// superviseJob answers the action from its first event, then follows the+// job to its end.+func (l *Library) superviseJob(action Action, events <-chan libraryEvent, ended <-chan int, answer *pendingAnswer) {+ answered := false+ accepted := false+ reply := func(refusal *wire.LocalModelActionRefusal) {+ if !answered {+ answered, accepted = true, refusal == nil+ answer.give(refusal)+ if accepted {+ l.mu.Lock()+ l.jobs[action.Model] = &job{action: action}+ l.mu.Unlock()+ }+ }+ }+ var final *libraryEvent+ phase := ""+ for event := range events {+ switch event.Event {+ case "progress":+ reply(nil)+ if event.Phase != phase {+ phase = event.Phase+ l.phaseStarted(event)+ } else {+ l.progress(event)+ }+ case "result":+ reply(nil)+ final = &event+ case "error":+ reply(event.refusal())+ final = &event+ }+ }+ exitCode := <-ended+ if l.ctx.Err() != nil {+ return+ }+ if !answered {+ slog.Warn("local_models.job_without_events", "action", action.Name, "model", action.Model, "exit_code", exitCode)+ reply(&wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "localmodels exited without a result"})+ }+ outcome := "failed"+ if final != nil && final.Event == "result" {+ outcome = "succeeded"+ } else if final != nil {+ outcome = final.Code+ }+ slog.Info("local_models.job_finished", "action", action.Name, "model", action.Model,+ "exit_code", exitCode, "outcome", outcome, "accepted", accepted)+ if !accepted {+ if answer.missed() {+ // Nobody heard the refusal; the snapshot is how the owner sees+ // that nothing changed.+ l.Refresh(l.ctx)+ }+ return+ }+ l.mu.Lock()+ delete(l.jobs, action.Model)+ l.mu.Unlock()+ l.Refresh(l.ctx)+ if action.Name == ActionLoad {+ l.runtimeChanged()+ }+}++// phaseStarted rereads the library when a supervised job enters a phase.+// localmodels records what a phase reserves or frees (pool use and holders,+// the placement, models unloaded first) only in its status, which progress+// lines do not carry; the job's own line is newer than that status, so it is+// applied on top. A failed read keeps the last library with only the line+// applied, and hands the failed observation to reconcile, which rereads+// with backoff until a read succeeds: the job may stay in this phase for+// minutes, so recovery must not wait for its next phase.+func (l *Library) phaseStarted(event libraryEvent) {+ l.refreshMu.Lock()+ snapshot := l.read(l.ctx)+ l.refreshMu.Unlock()+ if l.ctx.Err() != nil {+ return+ }+ if !snapshot.Available {+ l.progress(event)+ l.reconcile(snapshot)+ return+ }+ applyProgress(&snapshot, event)+ l.publishMu.Lock()+ l.mu.Lock()+ key := loadedKey(snapshot)+ changed := l.loaded != nil && *l.loaded != key+ l.loaded = &key+ l.current = &snapshot+ l.publishThrottledLocked()+ l.mu.Unlock()+ l.publishMu.Unlock()+ // A model unloaded first leaves Pi's catalog.+ if changed {+ l.runtimeChanged()+ }+}++// progress applies a progress line to the current snapshot and publishes+// it, at most once per progress interval; the last line of a burst is+// published when the interval ends.+func (l *Library) progress(event libraryEvent) {+ l.publishMu.Lock()+ defer l.publishMu.Unlock()+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.current == nil || !applyProgress(l.current, event) {+ return+ }+ l.publishThrottledLocked()+}++// publishThrottledLocked publishes current now, or when the progress+// interval since the last publish ends. It runs with publishMu and mu held.+func (l *Library) publishThrottledLocked() {+ wait := l.progressInterval - l.now().Sub(l.lastProgress)+ if wait <= 0 {+ l.publishProgressLocked()+ return+ }+ if l.progressTimer == nil {+ l.progressTimerID+++ id := l.progressTimerID+ l.progressTimer = time.AfterFunc(wait, func() { l.flushProgress(id) })+ }+}++func (l *Library) flushProgress(id uint64) {+ l.publishMu.Lock()+ defer l.publishMu.Unlock()+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.ctx.Err() != nil || l.current == nil || l.progressTimer == nil || l.progressTimerID != id {+ return+ }+ l.publishProgressLocked()+}++// publishProgressLocked runs with publishMu and mu held.+func (l *Library) publishProgressLocked() {+ if l.progressTimer != nil {+ l.progressTimer.Stop()+ l.progressTimer = nil+ }+ l.lastProgress = l.now()+ snapshot := cloneSnapshot(*l.current)+ l.publish(snapshot)+}++// applyProgress moves the progress line's model into downloading or+// loading. It reports whether the snapshot changed.+func applyProgress(snapshot *wire.LocalModelsSnapshot, event libraryEvent) bool {+ id := event.modelID()+ for index := range snapshot.Models {+ model := &snapshot.Models[index]+ if model.ID != id {+ continue+ }+ switch event.Phase {+ case "download", "verify":+ progress := &wire.LocalModelDownloadProgress{+ Step: event.Phase, DoneBytes: bytesValue(event.Done), TotalBytes: bytesValue(event.Total),+ }+ if event.Phase == "download" {+ rate := bytesValue(event.BytesPerSecond)+ progress.BytesPerSecond = &rate+ }+ model.State, model.Download, model.Endpoint, model.Error, model.Note = "downloading", progress, nil, nil, nil+ case "load", "warm":+ model.State, model.Download, model.Endpoint, model.Error, model.Note = "loading", nil, nil, nil, nil+ default:+ return false+ }+ return true+ }+ return false+}++func cloneSnapshot(snapshot wire.LocalModelsSnapshot) wire.LocalModelsSnapshot {+ encoded, err := json.Marshal(snapshot)+ if err != nil {+ return snapshot+ }+ var clone wire.LocalModelsSnapshot+ if json.Unmarshal(encoded, &clone) != nil {+ return snapshot+ }+ return clone+}++// reconcile rereads the library while the last read cannot be trusted to+// be followed by a report of its own: a download or load this Daemon is not+// supervising (one a previous Daemon started) runs, or the read failed. A+// failed read is retried with backoff instead of ending the watch; the loop+// ends only after a successful read with nothing to follow, or on Close.+func (l *Library) reconcile(snapshot wire.LocalModelsSnapshot) {+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.polling || !l.needsRereadLocked(snapshot) {+ return+ }+ l.polling = true+ go func() {+ delay := l.progressInterval+ for {+ select {+ case <-l.ctx.Done():+ return+ case <-time.After(delay):+ }+ next := l.Refresh(l.ctx)+ l.mu.Lock()+ if !l.needsRereadLocked(next) {+ l.polling = false+ l.mu.Unlock()+ return+ }+ l.mu.Unlock()+ if next.Available {+ delay = l.progressInterval+ } else {+ delay = min(2*delay, maxRereadInterval)+ }+ }+ }()+}++func (l *Library) needsRereadLocked(snapshot wire.LocalModelsSnapshot) bool {+ if !snapshot.Available {+ // A missing tool stays missing until the installer changes the+ // Computer config, which restarts the Daemon.+ return snapshot.Reason != nil && snapshot.Reason.Code == CodeToolFailed+ }+ return l.hasAdoptedJobLocked(snapshot)+}++func (l *Library) hasAdoptedJobLocked(snapshot wire.LocalModelsSnapshot) bool {+ for _, model := range snapshot.Models {+ if model.State != "downloading" && model.State != "loading" {+ continue+ }+ if _, supervised := l.jobs[model.ID]; !supervised {+ return true+ }+ }+ return false+}diff --git a/apps/computer/local-daemon/internal/localmodels/library_test.go b/apps/computer/local-daemon/internal/localmodels/library_test.gonew file mode 100644index 00000000..cd17df31--- /dev/null+++ b/apps/computer/local-daemon/internal/localmodels/library_test.go@@ -0,0 +1,579 @@+package localmodels++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "sync"+ "testing"+ "time"++ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"+)++const testModel = "qwen3-4b:Q4_K_M"++// recorder collects what a Library publishes and how often it asked for+// the Runtime diagnostics again.+type recorder struct {+ mu sync.Mutex+ snapshots []wire.LocalModelsSnapshot+ at []time.Time+ runtimeChanges int+}++func (r *recorder) publish(snapshot wire.LocalModelsSnapshot) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.snapshots = append(r.snapshots, snapshot)+ r.at = append(r.at, time.Now())+}++func (r *recorder) runtimeChanged() {+ r.mu.Lock()+ r.runtimeChanges+++ r.mu.Unlock()+}++func (r *recorder) last() wire.LocalModelsSnapshot {+ r.mu.Lock()+ defer r.mu.Unlock()+ return r.snapshots[len(r.snapshots)-1]+}++func (r *recorder) changes() int {+ r.mu.Lock()+ defer r.mu.Unlock()+ return r.runtimeChanges+}++// waitFor polls condition; the budget is a harness bound for loaded machines.+func waitFor(t *testing.T, what string, condition func() bool) {+ t.Helper()+ deadline := time.Now().Add(20 * time.Second)+ for !condition() {+ if time.Now().After(deadline) {+ t.Fatalf("timed out waiting for %s", what)+ }+ time.Sleep(10 * time.Millisecond)+ }+}++func newLibrary(t *testing.T, fake *fakeTool, record *recorder, interval time.Duration) *Library {+ t.Helper()+ var tool *Tool+ if fake != nil {+ tool = &fake.tool+ }+ library := New(Options{+ Tool: tool, Environment: map[string]string{"LOCALMODELS_FAKE_TOOL": "1", "PYTHONHOME": "/elsewhere", "PATH": os.Getenv("PATH")},+ JobDirectory: filepath.Join(t.TempDir(), "jobs"), Publish: record.publish, RuntimeChanged: record.runtimeChanged,+ ProgressInterval: interval,+ })+ t.Cleanup(library.Close)+ return library+}++func modelState(snapshot wire.LocalModelsSnapshot, id string) *wire.LocalModel {+ for index := range snapshot.Models {+ if snapshot.Models[index].ID == id {+ return &snapshot.Models[index]+ }+ }+ return nil+}++func soon() time.Time { return time.Now().Add(15 * time.Second) }++func TestRefreshMapsLibraryStatusToTheWireSnapshot(t *testing.T) {+ fake := newFakeTool(t)+ unfit := model("giant-405b:Q4_K_M", "absent")+ unfit["fit"], unfit["pool"] = "none", ""+ unfit["availability"] = map[string]any{"downloadable": false, "reason": map[string]any{"code": "MEMORY_INSUFFICIENT", "need_bytes": 200 << 30, "have_bytes": 24 << 30}}+ fake.write("status.json", status(model(testModel, "downloading"), unfit))+ record := &recorder{}+ snapshot := newLibrary(t, fake, record, time.Second).Refresh(context.Background())+ if !snapshot.Available || snapshot.ToolVersion != "0.9.0" || snapshot.ObservedAt != "2026-11-13T08:00:00Z" {+ t.Fatalf("snapshot = %+v", snapshot)+ }+ if len(snapshot.Pools) != 2 || snapshot.Pools[0].Kind != "gpu" || snapshot.Pools[0].GpuIndex == nil || *snapshot.Pools[0].GpuIndex != 0 ||+ snapshot.Pools[1].Kind != "system" || snapshot.Pools[1].GpuIndex != nil || snapshot.Pools[1].Holders[0].Kind != "component" {+ t.Fatalf("pools = %+v", snapshot.Pools)+ }+ downloading := modelState(snapshot, testModel)+ if downloading == nil || downloading.State != "downloading" || downloading.Download.DoneBytes != 1<<30 || *downloading.Download.BytesPerSecond != 1<<20 {+ t.Fatalf("model = %+v", downloading)+ }+ if giant := modelState(snapshot, "giant-405b:Q4_K_M"); giant == nil || giant.Pool != "" || giant.Availability.Reason.Code != "MEMORY_INSUFFICIENT" {+ t.Fatalf("model that fits nowhere = %+v", giant)+ }+ encoded, _ := json.Marshal(snapshot)+ if strings.Contains(string(encoded), `"pool":""`) {+ t.Fatalf("a model without a pool sent an empty pool: %s", encoded)+ }+ if len(record.snapshots) != 1 {+ t.Fatalf("published %d snapshots", len(record.snapshots))+ }+ call := fake.calls()[0]+ if !strings.HasPrefix(call, "status --base-dir "+fake.tool.BaseDirectory+" --json|PYTHONPATH="+fake.tool.ModuleDirectory+"|cwd="+fake.tool.ModuleDirectory) {+ t.Fatalf("status call = %q", call)+ }+}++func TestRefreshRejectsStatusOutsideTheContract(t *testing.T) {+ fake := newFakeTool(t)+ broken := model(testModel, "warming")+ // An Agent stores pi_model whole, so one longer than the contract is not cut.+ long := model("other:Q4_K_M", "idle")+ long["pi_model"] = "localmodels-library/" + strings.Repeat("x", 200)+ for _, entry := range []map[string]any{broken, long} {+ fake.write("status.json", status(entry))+ snapshot := newLibrary(t, fake, &recorder{}, time.Second).Refresh(context.Background())+ if snapshot.Available || snapshot.Reason.Code != CodeToolFailed || strings.Contains(snapshot.Reason.Detail, "warming") {+ t.Fatalf("snapshot = %+v", snapshot)+ }+ }+}++func TestFailedStatusReportsToolFailedWithoutLocalDetail(t *testing.T) {+ fake := newFakeTool(t)+ if err := os.WriteFile(filepath.Join(fake.state, "status-exit"), []byte("1"), 0o600); err != nil {+ t.Fatal(err)+ }+ library := newLibrary(t, fake, &recorder{}, time.Second)+ snapshot := library.Refresh(context.Background())+ if snapshot.Available || snapshot.Reason.Code != CodeToolFailed || strings.Contains(snapshot.Reason.Detail, "/private/path") {+ t.Fatalf("snapshot = %+v", snapshot)+ }+ refusal, _ := library.Act(context.Background(), Action{Name: ActionRefresh}, soon())+ if refusal == nil || refusal.Code != CodeToolFailed {+ t.Fatalf("refresh refusal = %+v", refusal)+ }+}++func TestComputerWithoutTheToolReportsToolNotInstalled(t *testing.T) {+ missing := newFakeTool(t)+ missing.tool.Python = filepath.Join(t.TempDir(), "python3")+ for name, fake := range map[string]*fakeTool{"no config": nil, "missing interpreter": missing} {+ t.Run(name, func(t *testing.T) {+ record := &recorder{}+ library := newLibrary(t, fake, record, time.Second)+ snapshot := library.Refresh(context.Background())+ if snapshot.Available || snapshot.Reason == nil || snapshot.Reason.Code != CodeToolNotInstalled ||+ snapshot.Pools == nil || snapshot.Models == nil {+ t.Fatalf("snapshot = %+v", snapshot)+ }+ for _, action := range []Action{{Name: ActionDownload, Model: testModel}, {Name: ActionRefresh}} {+ if refusal, _ := library.Act(context.Background(), action, soon()); refusal == nil || refusal.Code != CodeToolNotInstalled {+ t.Fatalf("%s refusal = %+v", action.Name, refusal)+ }+ }+ })+ }+}++func TestDownloadIsAcceptedAtItsFirstProgressAndThrottlesProgress(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "absent")))+ lines := []fakeLine{{Line: progressLine(testModel, "download", 0, 3000)}}+ for done := 100; done <= 3000; done += 100 {+ lines = append(lines, fakeLine{Line: progressLine(testModel, "download", done, 3000), DelayMS: 20})+ }+ lines = append(lines, fakeLine{Line: progressLine(testModel, "verify", 3000, 3000)}, fakeLine{Line: resultLine(testModel), DelayMS: 50})+ loaded := status(model(testModel, "loaded"))+ encodedLoaded, _ := json.Marshal(loaded)+ fake.script("download", fakeScript{Lines: lines, StatusAfter: encodedLoaded})+ record := &recorder{}+ interval := 200 * time.Millisecond+ library := newLibrary(t, fake, record, interval)+ library.Refresh(context.Background())++ started := time.Now()+ if refusal, _ := library.Act(context.Background(), Action{Name: ActionDownload, Model: testModel}, soon()); refusal != nil {+ t.Fatalf("download refused: %+v", refusal)+ }+ if elapsed := time.Since(started); elapsed > 500*time.Millisecond {+ t.Fatalf("the answer waited %s for the job instead of its first event", elapsed)+ }+ waitFor(t, "the loaded snapshot", func() bool {+ record.mu.Lock()+ defer record.mu.Unlock()+ last := record.snapshots[len(record.snapshots)-1]+ model := modelState(last, testModel)+ return model != nil && model.State == "loaded"+ })+ record.mu.Lock()+ defer record.mu.Unlock()+ var progressTimes []time.Time+ for index, snapshot := range record.snapshots {+ if model := modelState(snapshot, testModel); model != nil && model.State == "downloading" {+ progressTimes = append(progressTimes, record.at[index])+ }+ }+ // About 30 lines over 600 ms publish at most every 200 ms.+ if len(progressTimes) < 2 || len(progressTimes) > 6 {+ t.Fatalf("published %d progress snapshots", len(progressTimes))+ }+ for index := 1; index < len(progressTimes); index++ {+ if gap := progressTimes[index].Sub(progressTimes[index-1]); gap < interval-20*time.Millisecond {+ t.Fatalf("progress snapshots %s apart, interval %s", gap, interval)+ }+ }+ final := modelState(record.snapshots[len(record.snapshots)-1], testModel)+ if final.Endpoint == nil || final.Endpoint.BaseURL != "http://127.0.0.1:18100/v1" || final.PiModel != testPiModel {+ t.Fatalf("loaded model = %+v, endpoint %+v", final, final.Endpoint)+ }+}++func TestLoadRefusalBeforeWorkStartsIsTheAnswer(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "idle")))+ fake.script("load", fakeScript{+ Lines: []fakeLine{{Line: errorLine(testModel, "LOAD_NO_ROOM", `,"pool":"gpu:0","need_bytes":4294967296,"free_bytes":1073741824`)}},+ Exit: 2,+ })+ record := &recorder{}+ library := newLibrary(t, fake, record, time.Second)+ library.Refresh(context.Background())+ refusal, _ := library.Act(context.Background(), Action{Name: ActionLoad, Model: testModel, UnloadFirst: []string{"gemma3-4b:Q4_K_M"}}, soon())+ if refusal == nil || refusal.Code != "LOAD_NO_ROOM" || refusal.Pool != "gpu:0" ||+ refusal.NeedBytes == nil || *refusal.NeedBytes != 4<<30 || refusal.FreeBytes == nil || *refusal.FreeBytes != 1<<30 {+ t.Fatalf("refusal = %+v", refusal)+ }+ waitFor(t, "the load call", func() bool { return len(fake.calls()) == 2 })+ if call := fake.calls()[1]; !strings.HasPrefix(call, "load "+testModel+" --unload gemma3-4b:Q4_K_M --base-dir ") {+ t.Fatalf("load call = %q", call)+ }+ time.Sleep(100 * time.Millisecond)+ if len(record.snapshots) != 1 || record.changes() != 0 {+ t.Fatalf("a refused load published %d snapshots and %d runtime changes", len(record.snapshots), record.changes())+ }+}++func TestDownloadRefusalCarriesWhatTheDiskHas(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "absent")))+ fake.script("download", fakeScript{+ Lines: []fakeLine{{Line: errorLine(testModel, "DISK_INSUFFICIENT", `,"need_bytes":10,"have_bytes":4`)}}, Exit: 2,+ })+ refusal, _ := newLibrary(t, fake, &recorder{}, time.Second).Act(context.Background(), Action{Name: ActionDownload, Model: testModel}, soon())+ if refusal == nil || refusal.Code != "DISK_INSUFFICIENT" || *refusal.NeedBytes != 10 || *refusal.FreeBytes != 4 {+ t.Fatalf("refusal = %+v", refusal)+ }+}++func TestUnloadAndRemoveAnswerWhenTheToolFinishes(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "loaded")))+ idle, _ := json.Marshal(status(model(testModel, "idle")))+ fake.script("unload", fakeScript{Lines: []fakeLine{{Line: resultLine(testModel)}}, StatusAfter: idle})+ fake.script("remove", fakeScript{Lines: []fakeLine{{Line: errorLine(testModel, "INVALID_STATE", "")}}, Exit: 2})+ record := &recorder{}+ library := newLibrary(t, fake, record, time.Second)+ library.Refresh(context.Background())++ if refusal, _ := library.Act(context.Background(), Action{Name: ActionUnload, Model: testModel}, soon()); refusal != nil {+ t.Fatalf("unload refused: %+v", refusal)+ }+ waitFor(t, "the idle snapshot and a diagnostics re-run", func() bool {+ model := modelState(record.last(), testModel)+ return model.State == "idle" && model.Endpoint == nil && record.changes() > 0+ })+ refusal, _ := library.Act(context.Background(), Action{Name: ActionRemove, Model: testModel}, soon())+ if refusal == nil || refusal.Code != "INVALID_STATE" || refusal.Detail != "refused by the fake" {+ t.Fatalf("remove refusal = %+v", refusal)+ }+}++func TestCancelStopsARunningDownload(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "absent")))+ lines := []fakeLine{{Line: progressLine(testModel, "download", 0, 100)}}+ for range 200 {+ lines = append(lines, fakeLine{Line: progressLine(testModel, "download", 1, 100), DelayMS: 50, CancelAware: true})+ }+ fake.script("download", fakeScript{Lines: lines})+ fake.script("cancel", fakeScript{Lines: []fakeLine{{Line: resultLine(testModel)}}, MarkCancelled: true})+ record := &recorder{}+ library := newLibrary(t, fake, record, 50*time.Millisecond)+ library.Refresh(context.Background())+ if refusal, _ := library.Act(context.Background(), Action{Name: ActionDownload, Model: testModel}, soon()); refusal != nil {+ t.Fatalf("download refused: %+v", refusal)+ }+ waitFor(t, "a downloading snapshot", func() bool { return modelState(record.last(), testModel).State == "downloading" })+ if refusal, _ := library.Act(context.Background(), Action{Name: ActionCancel, Model: testModel}, soon()); refusal != nil {+ t.Fatalf("cancel refused: %+v", refusal)+ }+ waitFor(t, "the cancelled download to end", func() bool {+ library.mu.Lock()+ defer library.mu.Unlock()+ return len(library.jobs) == 0 && modelState(*library.current, testModel).State == "absent"+ })+ if !slices.ContainsFunc(fake.calls(), func(call string) bool { return strings.HasPrefix(call, "cancel "+testModel+" --base-dir ") }) {+ t.Fatalf("calls = %q", fake.calls())+ }+}++func TestJobThatExitsWithoutEventsIsRefusedAndOneThatCrashesIsReread(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "absent")))+ fake.script("download", fakeScript{Exit: 1})+ record := &recorder{}+ library := newLibrary(t, fake, record, time.Second)+ library.Refresh(context.Background())+ if refusal, _ := library.Act(context.Background(), Action{Name: ActionDownload, Model: testModel}, soon()); refusal == nil || refusal.Code != CodeToolFailed {+ t.Fatalf("silent exit answer = %+v", refusal)+ }++ failed := model(testModel, "failed")+ failed["error"] = map[string]any{"code": "DOWNLOAD_FAILED", "detail": "stale job"}+ encodedFailed, _ := json.Marshal(status(failed))+ fake.script("download", fakeScript{Lines: []fakeLine{{Line: progressLine(testModel, "download", 0, 100)}}, Exit: 1, StatusAfter: encodedFailed})+ if refusal, _ := library.Act(context.Background(), Action{Name: ActionDownload, Model: testModel}, soon()); refusal != nil {+ t.Fatalf("download refused: %+v", refusal)+ }+ waitFor(t, "the failed state from status", func() bool {+ model := modelState(record.last(), testModel)+ return model.State == "failed" && model.Error != nil && model.Error.Code == "DOWNLOAD_FAILED"+ })+}++func TestAnswerAfterTheDeadlineIsNotAGuessAndShowsInASnapshot(t *testing.T) {+ for _, scenario := range []struct {+ name string+ action Action+ script fakeScript+ }{+ {"load refused late", Action{Name: ActionLoad, Model: testModel},+ fakeScript{Lines: []fakeLine{{Line: errorLine(testModel, "LOAD_NO_ROOM", ""), DelayMS: 250}}, Exit: 2}},+ {"unload refused late", Action{Name: ActionUnload, Model: testModel},+ fakeScript{Lines: []fakeLine{{Line: errorLine(testModel, "INVALID_STATE", ""), DelayMS: 250}}, Exit: 2}},+ } {+ t.Run(scenario.name, func(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "idle")))+ fake.script(scenario.action.Name, scenario.script)+ record := &recorder{}+ library := newLibrary(t, fake, record, 20*time.Millisecond)+ library.Refresh(context.Background())+ started := time.Now()+ refusal, answered := library.Act(context.Background(), scenario.action, started.Add(50*time.Millisecond))+ if answered || refusal != nil {+ t.Fatalf("the deadline passed before the tool decided, yet the answer is %+v (answered %v)", refusal, answered)+ }+ if elapsed := time.Since(started); elapsed > 200*time.Millisecond {+ t.Fatalf("the answer waited %s past the deadline", elapsed)+ }+ // The late refusal changes nothing, and a fresh snapshot shows it.+ waitFor(t, "the snapshot after the late refusal", func() bool {+ record.mu.Lock()+ defer record.mu.Unlock()+ return len(record.snapshots) == 2+ })+ if got := modelState(record.last(), testModel); got.State != "idle" {+ t.Fatalf("model = %+v", got)+ }+ })+ }+}++func TestFollowingAJobSurvivesAFailedStatusRead(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "downloading")))+ record := &recorder{}+ library := newLibrary(t, fake, record, 20*time.Millisecond)+ library.Refresh(context.Background())+ failStatus(t, fake, true)+ waitFor(t, "the failed read", func() bool { return !record.last().Available })+ // The tool recovers and the job it was following has finished meanwhile.+ failStatus(t, fake, false)+ fake.write("status.json", status(model(testModel, "loaded")))+ waitFor(t, "the read after recovery", func() bool {+ model := modelState(record.last(), testModel)+ return model != nil && model.State == "loaded"+ })+ waitFor(t, "the Pi diagnostics for the new model", func() bool { return record.changes() == 1 })+}++func TestAFailedFirstReadIsRetried(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "idle")))+ failStatus(t, fake, true)+ record := &recorder{}+ library := newLibrary(t, fake, record, 20*time.Millisecond)+ if library.Refresh(context.Background()).Available {+ t.Fatal("the failing read reported a library")+ }+ failStatus(t, fake, false)+ waitFor(t, "a retried read", func() bool { return record.last().Available })+ calls := len(fake.calls())+ time.Sleep(200 * time.Millisecond)+ if len(fake.calls()) != calls {+ t.Fatal("reads continued after a library with nothing to follow")+ }+}++// failStatus makes `library status` exit 1 until it is called with false.+func failStatus(t *testing.T, fake *fakeTool, fail bool) {+ t.Helper()+ path := filepath.Join(fake.state, "status-exit")+ if !fail {+ if err := os.Remove(path); err != nil {+ t.Fatal(err)+ }+ return+ }+ if err := os.WriteFile(path, []byte("1"), 0o600); err != nil {+ t.Fatal(err)+ }+}++func TestALoadingSnapshotShowsWhatTheLoadReservedAndFreed(t *testing.T) {+ fake := newFakeTool(t)+ other := model("gemma3-4b:Q4_K_M", "loaded")+ fake.write("status.json", status(model(testModel, "idle"), other))+ lines := []fakeLine{{Line: progressLine(testModel, "load", 0, 3), DelayMS: 100}}+ for range 200 {+ lines = append(lines, fakeLine{Line: progressLine(testModel, "load", 1, 3), DelayMS: 50, CancelAware: true})+ }+ fake.script("load", fakeScript{Lines: lines})+ record := &recorder{}+ library := newLibrary(t, fake, record, 20*time.Millisecond)+ library.Refresh(context.Background())+ t.Cleanup(func() {+ _ = os.WriteFile(filepath.Join(fake.state, "cancelled"), nil, 0o600)+ waitFor(t, "the job to end", func() bool { library.mu.Lock(); defer library.mu.Unlock(); return len(library.jobs) == 0 })+ })+ // What localmodels records before its first load line: the model it+ // unloads first is idle and the load's memory is reserved.+ reserved := status(model(testModel, "loading"), model("gemma3-4b:Q4_K_M", "idle"))+ pool := reserved["pools"].([]any)[0].(map[string]any)+ pool["used_bytes"] = 4 << 30+ pool["holders"] = []any{map[string]any{"kind": "model", "id": testModel, "name": "Qwen3 4B", "bytes": 4 << 30}}+ fake.write("status.json", reserved)+ if refusal, _ := library.Act(context.Background(), Action{Name: ActionLoad, Model: testModel, UnloadFirst: []string{"gemma3-4b:Q4_K_M"}}, soon()); refusal != nil {+ t.Fatal(refusal)+ }+ waitFor(t, "the loading snapshot", func() bool { return modelState(record.last(), testModel).State == "loading" })+ record.mu.Lock()+ defer record.mu.Unlock()+ for _, snapshot := range record.snapshots {+ if modelState(snapshot, testModel).State != "loading" {+ continue+ }+ if snapshot.Pools[0].UsedBytes != 4<<30 || len(snapshot.Pools[0].Holders) != 1 {+ t.Fatalf("a loading snapshot shows the pool before its reservation: %+v", snapshot.Pools[0])+ }+ if freed := modelState(snapshot, "gemma3-4b:Q4_K_M"); freed.State != "idle" || freed.Endpoint != nil {+ t.Fatalf("the model unloaded first still shows %+v", freed)+ }+ }+}++func TestAFailedPhaseReadIsRetriedWithinThePhase(t *testing.T) {+ fake := newFakeTool(t)+ other := "gemma3-4b:Q4_K_M"+ fake.write("status.json", status(model(testModel, "idle"), model(other, "loaded")))+ lines := []fakeLine{{Line: progressLine(testModel, "load", 0, 3)}}+ for range 2000 {+ lines = append(lines, fakeLine{Line: progressLine(testModel, "load", 1, 3), DelayMS: 50, CancelAware: true})+ }+ fake.script("load", fakeScript{Lines: lines})+ record := &recorder{}+ library := newLibrary(t, fake, record, 20*time.Millisecond)+ library.Refresh(context.Background())+ t.Cleanup(func() {+ _ = os.WriteFile(filepath.Join(fake.state, "cancelled"), nil, 0o600)+ waitFor(t, "the job to end", func() bool { library.mu.Lock(); defer library.mu.Unlock(); return len(library.jobs) == 0 })+ })+ // The read at the start of the load phase fails.+ failStatus(t, fake, true)+ if refusal, answered := library.Act(context.Background(), Action{Name: ActionLoad, Model: testModel, UnloadFirst: []string{other}}, soon()); refusal != nil || !answered {+ t.Fatalf("refusal = %+v, answered = %v", refusal, answered)+ }+ waitFor(t, "the loading snapshot", func() bool {+ model := modelState(record.last(), testModel)+ return model != nil && model.State == "loading"+ })+ // The tool recovers while the job stays in the same phase: what the load+ // reserved and freed must still reach the page.+ reserved := status(model(testModel, "loading"), model(other, "idle"))+ pool := reserved["pools"].([]any)[0].(map[string]any)+ pool["used_bytes"] = 4 << 30+ pool["holders"] = []any{map[string]any{"kind": "model", "id": testModel, "name": "Qwen3 4B", "bytes": 4 << 30}}+ fake.write("status.json", reserved)+ failStatus(t, fake, false)+ waitFor(t, "the reread after the failed phase read", func() bool {+ last := record.last()+ if !last.Available || len(last.Pools) == 0 {+ return false+ }+ freed := modelState(last, other)+ return last.Pools[0].UsedBytes == 4<<30 && freed != nil && freed.State == "idle" && freed.Endpoint == nil+ })+}++func TestRestartedLibraryFollowsAJobFromStatus(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "downloading")))+ record := &recorder{}+ library := newLibrary(t, fake, record, 50*time.Millisecond)+ library.Refresh(context.Background())+ waitFor(t, "a status poll", func() bool { return len(fake.calls()) >= 3 })+ fake.write("status.json", status(model(testModel, "idle")))+ waitFor(t, "the finished job", func() bool { return modelState(record.last(), testModel).State == "idle" })+ time.Sleep(200 * time.Millisecond)+ calls := len(fake.calls())+ time.Sleep(200 * time.Millisecond)+ if len(fake.calls()) != calls {+ t.Fatal("polling continued after the job ended")+ }+}++func TestPiModelPassesThroughAndTheEndpointKeepsOnlyItsURL(t *testing.T) {+ fake := newFakeTool(t)+ idle := model(testModel, "idle")+ // An endpoint outside the loaded state is not the contract's.+ idle["endpoint"] = map[string]any{"base_url": "http://127.0.0.1:18100/v1"}+ fake.write("status.json", status(idle))+ record := &recorder{}+ library := newLibrary(t, fake, record, time.Second)+ if got := modelState(library.Refresh(context.Background()), testModel); got.PiModel != testPiModel || got.Endpoint != nil {+ t.Fatalf("idle model = %+v", got)+ }+ fake.write("status.json", status(model(testModel, "loaded")))+ loaded := library.Refresh(context.Background())+ got := modelState(loaded, testModel)+ if got.PiModel != testPiModel || got.Endpoint == nil || got.Endpoint.BaseURL != "http://127.0.0.1:18100/v1" {+ t.Fatalf("loaded model = %+v", got)+ }+ // The gateway's own model id is not an Agent's runtime_model.+ if encoded, _ := json.Marshal(loaded); strings.Contains(string(encoded), "gateway_model") {+ t.Fatalf("snapshot carries the gateway's model id: %s", encoded)+ }+}++func TestChangeOfTheLoadedModelsAsksForRuntimeDiagnostics(t *testing.T) {+ fake := newFakeTool(t)+ fake.write("status.json", status(model(testModel, "idle")))+ record := &recorder{}+ library := newLibrary(t, fake, record, time.Second)+ library.Refresh(context.Background())+ if record.changes() != 0 {+ t.Fatalf("the first read asked for %d diagnostics", record.changes())+ }+ fake.write("status.json", status(model(testModel, "loaded")))+ library.Refresh(context.Background())+ library.Refresh(context.Background())+ if record.changes() != 1 {+ t.Fatalf("a load asked for %d diagnostics, want 1", record.changes())+ }+ fake.write("status.json", status(model(testModel, "idle")))+ library.Refresh(context.Background())+ if record.changes() != 2 {+ t.Fatalf("an unload asked for %d diagnostics in all, want 2", record.changes())+ }+}diff --git a/apps/computer/local-daemon/internal/localmodels/status.go b/apps/computer/local-daemon/internal/localmodels/status.gonew file mode 100644index 00000000..c4492e53--- /dev/null+++ b/apps/computer/local-daemon/internal/localmodels/status.go@@ -0,0 +1,281 @@+package localmodels++import (+ "encoding/json"+ "errors"+ "fmt"+ "math"+ "regexp"+ "slices"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"+)++const (+ statusSchema = "localmodels.library-status/v1"+ eventSchema = "localmodels.library-event/v1"+)++// Unavailable reason codes of a LocalModelsSnapshot, and the refusal codes+// the Daemon adds to the tool's own.+const (+ CodeToolNotInstalled = "TOOL_NOT_INSTALLED"+ CodeToolFailed = "TOOL_FAILED"+)++// errorCodes is the tool's closed error set (LocalModelErrorCode).+var errorCodes = []string{+ "MODEL_UNKNOWN", "INVALID_STATE", "JOB_RUNNING", "MEMORY_INSUFFICIENT", "DISK_INSUFFICIENT",+ "PLATFORM_UNSUPPORTED", "LOAD_NO_ROOM", "DOWNLOAD_FAILED", "CHECKSUM_MISMATCH", "NETWORK_UNAVAILABLE",+ "ENGINE_START_FAILED", "HEALTH_CHECK_FAILED", "OUT_OF_MEMORY", "MODEL_FILES_MISSING",+ "GATEWAY_REGISTRATION_FAILED", "CANCELLED",+}++var modelIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$`)++// ValidModelID reports whether id is a LocalModelId the tool may be given as+// an argument.+func ValidModelID(id string) bool { return modelIDPattern.MatchString(id) }++// unavailable is the snapshot of a Computer whose library cannot be read.+func unavailable(code, detail string, now time.Time) wire.LocalModelsSnapshot {+ return wire.LocalModelsSnapshot{+ Available: false,+ Reason: &wire.LocalModelsUnavailableReason{Code: code, Detail: clip(detail, 4000)},+ ObservedAt: now.UTC().Format(time.RFC3339),+ Pools: []wire.LocalModelPool{}, Models: []wire.LocalModel{},+ }+}++// libraryStatus is localmodels.library-status/v1. Its host and model entries+// already use the wire field names; pools gain kind and gpu_index here.+type libraryStatus struct {+ Schema string `json:"schema"`+ ToolVersion string `json:"tool_version"`+ ObservedAt string `json:"observed_at"`+ Host *wire.LocalModelHost `json:"host"`+ Pools []struct {+ ID string `json:"id"`+ TotalBytes uint64 `json:"total_bytes"`+ UsedBytes uint64 `json:"used_bytes"`+ Holders []wire.LocalModelPoolHolder `json:"holders"`+ } `json:"pools"`+ Models []wire.LocalModel `json:"models"`+}++// mapStatus turns one library-status/v1 document into the wire snapshot. A+// value outside the contract's closed sets makes the whole document invalid:+// the reader would otherwise show a state nobody defined.+func mapStatus(encoded []byte, now time.Time) (wire.LocalModelsSnapshot, error) {+ var status libraryStatus+ if err := json.Unmarshal(encoded, &status); err != nil {+ return wire.LocalModelsSnapshot{}, fmt.Errorf("decode library status: %w", err)+ }+ if status.Schema != statusSchema {+ return wire.LocalModelsSnapshot{}, fmt.Errorf("library status schema is %q", status.Schema)+ }+ if status.Host == nil {+ return wire.LocalModelsSnapshot{}, errors.New("library status has no host")+ }+ host := *status.Host+ // The tool reports the machine's own architecture name; the wire knows two.+ switch host.Arch {+ case "amd64":+ host.Arch = "x86_64"+ case "aarch64":+ host.Arch = "arm64"+ }+ if !slices.Contains([]string{"linux", "darwin", "windows"}, host.Platform) || (host.Arch != "x86_64" && host.Arch != "arm64") {+ return wire.LocalModelsSnapshot{}, fmt.Errorf("library status host %s/%s is outside the contract", status.Host.Platform, status.Host.Arch)+ }+ host.OsLabel, host.EngineLabel = clip(host.OsLabel, 200), clip(host.EngineLabel, 200)+ if host.Gpus == nil {+ host.Gpus = []wire.LocalModelGpu{}+ }+ observedAt := now.UTC().Format(time.RFC3339)+ if parsed, err := time.Parse(time.RFC3339, status.ObservedAt); err == nil {+ observedAt = parsed.UTC().Format(time.RFC3339)+ }+ snapshot := wire.LocalModelsSnapshot{+ Available: true, ObservedAt: observedAt, ToolVersion: clip(status.ToolVersion, 64), Host: &host,+ Pools: make([]wire.LocalModelPool, 0, len(status.Pools)), Models: make([]wire.LocalModel, 0, len(status.Models)),+ }+ for _, pool := range status.Pools {+ kind, index, err := poolKind(pool.ID)+ if err != nil {+ return wire.LocalModelsSnapshot{}, err+ }+ holders := pool.Holders+ if holders == nil {+ holders = []wire.LocalModelPoolHolder{}+ }+ for _, holder := range holders {+ if holder.Kind != "model" && holder.Kind != "component" {+ return wire.LocalModelsSnapshot{}, fmt.Errorf("pool holder kind %q is outside the contract", holder.Kind)+ }+ }+ snapshot.Pools = append(snapshot.Pools, wire.LocalModelPool{+ ID: pool.ID, Kind: kind, GpuIndex: index, TotalBytes: pool.TotalBytes, UsedBytes: pool.UsedBytes, Holders: holders,+ })+ }+ for _, model := range status.Models {+ if err := checkModel(model); err != nil {+ return wire.LocalModelsSnapshot{}, err+ }+ model.Description = clip(model.Description, 2000)+ // Only a loaded model answers at an endpoint; Agents reach it through+ // Pi by pi_model.+ if model.State != "loaded" {+ model.Endpoint = nil+ }+ if model.Error != nil {+ model.Error.Detail = clip(model.Error.Detail, 4000)+ }+ snapshot.Models = append(snapshot.Models, model)+ }+ return snapshot, nil+}++// poolKind splits a pool id so no reader parses "gpu:1".+func poolKind(id string) (string, *uint64, error) {+ switch {+ case id == "system" || id == "unified":+ return id, nil, nil+ case strings.HasPrefix(id, "gpu:"):+ index, err := strconv.ParseUint(strings.TrimPrefix(id, "gpu:"), 10, 16)+ if err == nil && index < 1000 && strconv.FormatUint(index, 10) == strings.TrimPrefix(id, "gpu:") {+ return "gpu", &index, nil+ }+ }+ return "", nil, fmt.Errorf("pool id %q is outside the contract", id)+}++func checkModel(model wire.LocalModel) error {+ invalid := func(field, value string) error {+ return fmt.Errorf("model %s %s %q is outside the contract", model.ID, field, value)+ }+ if !ValidModelID(model.ID) {+ return invalid("id", model.ID)+ }+ if !slices.Contains([]string{"gpu", "unified", "system", "none"}, model.Fit) {+ return invalid("fit", model.Fit)+ }+ if !slices.Contains([]string{"absent", "downloading", "idle", "loading", "loaded", "failed"}, model.State) {+ return invalid("state", model.State)+ }+ // A model that fits nowhere has no pool.+ if _, _, err := poolKind(model.Pool); err != nil && (model.Pool != "" || model.Fit != "none") {+ return invalid("pool", model.Pool)+ }+ if reason := model.Availability.Reason; reason != nil &&+ !slices.Contains([]string{"MEMORY_INSUFFICIENT", "DISK_INSUFFICIENT", "PLATFORM_UNSUPPORTED"}, reason.Code) {+ return invalid("availability reason", reason.Code)+ }+ if model.Download != nil && model.Download.Step != "download" && model.Download.Step != "verify" {+ return invalid("download step", model.Download.Step)+ }+ if model.Error != nil && !slices.Contains(errorCodes, model.Error.Code) {+ return invalid("error code", model.Error.Code)+ }+ if model.Note != nil && model.Note.Code != "NO_ROOM_TO_LOAD" {+ return invalid("note", model.Note.Code)+ }+ // An Agent stores pi_model as its runtime_model, so it is never cut.+ if len(model.PiModel) > 200 {+ return invalid("pi_model", model.PiModel)+ }+ if model.TokensPerSecond != nil && (math.IsNaN(*model.TokensPerSecond) || *model.TokensPerSecond < 0) {+ return errors.New("model tokens_per_second is outside the contract")+ }+ return nil+}++// libraryEvent is one localmodels.library-event/v1 line, or the one document+// a JSON command prints. Counters are read as numbers and clamped, since the+// reader only displays them.+type libraryEvent struct {+ Schema string `json:"schema"`+ Event string `json:"event"`+ Model json.RawMessage `json:"model"`+ Phase string `json:"phase"`+ Done float64 `json:"done"`+ Total float64 `json:"total"`+ BytesPerSecond float64 `json:"bytes_per_second"`+ OK bool `json:"ok"`+ Code string `json:"code"`+ Detail string `json:"detail"`+ Pool string `json:"pool"`+ NeedBytes *float64 `json:"need_bytes"`+ FreeBytes *float64 `json:"free_bytes"`+ HaveBytes *float64 `json:"have_bytes"`+}++func parseEvent(line []byte) (libraryEvent, bool) {+ var event libraryEvent+ if err := json.Unmarshal(line, &event); err != nil || event.Schema != eventSchema {+ return libraryEvent{}, false+ }+ switch event.Event {+ case "progress", "result", "error":+ return event, true+ }+ return libraryEvent{}, false+}++// modelID is the progress line's model, which is the id string.+func (e libraryEvent) modelID() string {+ var id string+ if json.Unmarshal(e.Model, &id) == nil {+ return id+ }+ return ""+}++// refusal turns the tool's error into the wire refusal. A code outside the+// closed set means the tool broke its contract.+func (e libraryEvent) refusal() *wire.LocalModelActionRefusal {+ if !slices.Contains(errorCodes, e.Code) {+ return &wire.LocalModelActionRefusal{Code: CodeToolFailed, Detail: "localmodels reported an error outside its contract"}+ }+ refusal := &wire.LocalModelActionRefusal{Code: e.Code, Detail: clip(e.Detail, 4000)}+ if _, _, err := poolKind(e.Pool); err == nil {+ refusal.Pool = e.Pool+ }+ refusal.NeedBytes = counter(e.NeedBytes)+ refusal.FreeBytes = counter(e.FreeBytes)+ if refusal.FreeBytes == nil {+ // Download refusals name what the disk or memory has as have_bytes.+ refusal.FreeBytes = counter(e.HaveBytes)+ }+ return refusal+}++func counter(value *float64) *uint64 {+ if value == nil {+ return nil+ }+ result := bytesValue(*value)+ return &result+}++func bytesValue(value float64) uint64 {+ if math.IsNaN(value) || value <= 0 {+ return 0+ }+ if value >= 1<<53 {+ return 1 << 53+ }+ return uint64(value)+}++// clip bounds display text to the schema's length in characters.+func clip(text string, limit int) string {+ if utf8.RuneCountInString(text) <= limit {+ return text+ }+ return string([]rune(text)[:limit])+}diff --git a/apps/computer/local-daemon/internal/localmodels/tool.go b/apps/computer/local-daemon/internal/localmodels/tool.gonew file mode 100644index 00000000..3f938d9b--- /dev/null+++ b/apps/computer/local-daemon/internal/localmodels/tool.go@@ -0,0 +1,90 @@+// Package localmodels runs the installer's localmodels tool for the Daemon.+// It reads `library status`, starts the library actions a Computer owner+// chose, supervises the long ones (download, load), and maps the tool's+// localmodels.library-status/v1 into the Runner Gateway LocalModelsSnapshot.+// It never chooses a model: every action names the model the owner picked.+package localmodels++import (+ "os"+ "os/exec"+ "strings"+)++// Tool is where the installer put the localmodels tool and its state, as+// the Computer config records it.+type Tool struct {+ Python string+ ModuleDirectory string+ StateDirectory string+ BaseDirectory string+}++// Action is one owner-chosen library action. Model is empty only for+// refresh; UnloadFirst is only for load.+type Action struct {+ Name string+ Model string+ UnloadFirst []string+}++// Action names, as the Runner Gateway sends them.+const (+ ActionDownload = "download"+ ActionCancel = "cancel"+ ActionLoad = "load"+ ActionUnload = "unload"+ ActionRemove = "remove"+ ActionRefresh = "refresh"+)++// arguments are the `library` arguments of one call. Model ids are validated+// by the caller, so none starts with "-".+func (t Tool) arguments(action Action) []string {+ args := []string{"-P", "-s", "-m", "localmodels", "library"}+ switch action.Name {+ case ActionRefresh:+ return append(args, "status", "--base-dir", t.BaseDirectory, "--json")+ case ActionDownload:+ return append(args, "download", action.Model, "--base-dir", t.BaseDirectory, "--jsonl")+ case ActionLoad:+ args = append(args, "load", action.Model)+ for _, other := range action.UnloadFirst {+ args = append(args, "--unload", other)+ }+ return append(args, "--base-dir", t.BaseDirectory, "--jsonl")+ default:+ return append(args, action.Name, action.Model, "--base-dir", t.BaseDirectory, "--json")+ }+}++// command builds one tool invocation the way the installer runs it: the+// sealed kit on PYTHONPATH and as the working directory, no user site+// packages, no bytecode writes into the sealed kit.+func (t Tool) command(environment map[string]string, action Action) *exec.Cmd {+ cmd := exec.Command(t.Python, t.arguments(action)...)+ cmd.Dir = t.ModuleDirectory+ values := make(map[string]string, len(environment)+4)+ for key, value := range environment {+ switch strings.ToUpper(key) {+ case "PYTHONHOME", "PYTHONSTARTUP", "PYTHONINSPECT", "PYTHONPATH", "LOCALMODELS_STATE":+ continue+ }+ values[key] = value+ }+ values["PYTHONPATH"] = t.ModuleDirectory+ values["LOCALMODELS_STATE"] = t.StateDirectory+ values["PYTHONNOUSERSITE"] = "1"+ values["PYTHONDONTWRITEBYTECODE"] = "1"+ cmd.Env = make([]string, 0, len(values))+ for key, value := range values {+ cmd.Env = append(cmd.Env, key+"="+value)+ }+ return cmd+}++// installed reports whether the configured interpreter still exists.+func (t Tool) installed() bool {+ info, err := os.Stat(t.Python)+ return err == nil && info.Mode().IsRegular()+}diff --git a/apps/computer/local-daemon/internal/provider/runtime_monitor.go b/apps/computer/local-daemon/internal/provider/runtime_monitor.goindex 56e52ad1..5ca6f51f 100644--- a/apps/computer/local-daemon/internal/provider/runtime_monitor.go+++ b/apps/computer/local-daemon/internal/provider/runtime_monitor.go@@ -22,6 +22,10 @@ type RuntimeMonitorOptions struct {// RuntimeBusy reports an active operation. A running operation proves its// Runtime works, so an inconclusive auth probe then keeps the ready state.RuntimeBusy func() bool+ // Refresh asks for a full discovery before the next scheduled one, for+ // example after a local model load changed Pi's model list. The request+ // waits while FullRefreshAllowed is false.+ Refresh <-chan struct{}}const transientRuntimeFailureThreshold = 2@@ -39,18 +43,23 @@ func MonitorRuntimeDiagnostics(ctx context.Context, options RuntimeMonitorOption}ticker := time.NewTicker(options.RefreshInterval)defer ticker.Stop()- for tick := 1; ; tick++ {+ requested := false+ for tick := 0; ; {select {case <-ctx.Done():return context.Cause(ctx)case <-ticker.C:+ tick+++ case <-options.Refresh:+ requested = true}var next DiscoveryResultvar err error- if (tick%options.FullRefreshEveryTicks == 0 || runtimeExecutablesChanged(current.Diagnostics)) &&+ if (requested || tick%options.FullRefreshEveryTicks == 0 || runtimeExecutablesChanged(current.Diagnostics)) &&(options.FullRefreshAllowed == nil || options.FullRefreshAllowed()) {next, err = discover(ctx, options.Discovery)if err == nil {+ requested = falsefor _, diagnostic := range next.Diagnostics {if diagnostic.Status == "ready" {delete(authenticationFailures, diagnostic.Type)diff --git a/apps/computer/local-daemon/internal/provider/runtime_monitor_test.go b/apps/computer/local-daemon/internal/provider/runtime_monitor_test.goindex a78e84ac..3ae46a77 100644--- a/apps/computer/local-daemon/internal/provider/runtime_monitor_test.go+++ b/apps/computer/local-daemon/internal/provider/runtime_monitor_test.go@@ -288,3 +288,32 @@ func primeTestExecutable(t *testing.T, path string, env ...string) {command.Env = env_ = command.Run()}++func TestRuntimeMonitorRunsARequestedFullRefreshBeforeItsSchedule(t *testing.T) {+ initial := DiscoveryResult{Diagnostics: []RuntimeDiagnostic{{+ Type: "pi", Status: "ready", Protocol: "rpc", Version: "pi-test", Models: []RuntimeModel{},+ }}}+ loaded := DiscoveryResult{Diagnostics: []RuntimeDiagnostic{{+ Type: "pi", Status: "ready", Protocol: "rpc", Version: "pi-test", Models: []RuntimeModel{{ID: "local/qwen3-4b"}},+ }}}+ refresh := make(chan struct{}, 1)+ refresh <- struct{}{}+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ var published []DiscoveryResult+ err := MonitorRuntimeDiagnostics(ctx, RuntimeMonitorOptions{+ Initial: initial, RefreshInterval: time.Hour, FullRefreshEveryTicks: 4, Refresh: refresh,+ Discover: func(context.Context, DiscoveryOptions) (DiscoveryResult, error) { return loaded, nil },+ OnChanged: func(next DiscoveryResult) error {+ published = append(published, next)+ cancel()+ return nil+ },+ })+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("monitor ended with %v before the requested refresh", err)+ }+ if len(published) != 1 || len(published[0].Diagnostics[0].Models) != 1 {+ t.Fatalf("published = %+v, want the refreshed Pi model list", published)+ }+}