From eb3c7be2eb019ce7f9cf1fa916696f8349073af0 Mon Sep 17 00:00:00 2001 From: shoudi zheng <434782114@qq.com> Date: Thu, 26 Nov 2026 21:04:21 +0800 Subject: [PATCH] fix(computer): run Antigravity probes in private state temp dir --- .github/workflows/ci.yml | 1 + apps/computer/local-daemon/README.md | 13 +- .../local-daemon/internal/computercli/cli.go | 9 +- .../internal/computercli/cli_test.go | 122 ++++++- .../internal/computercli/doctor.go | 13 +- .../internal/computercli/fixture_test.go | 6 +- .../internal/computercli/runtime_login.go | 4 +- .../internal/computercli/runtimes.go | 19 +- .../internal/computercli/runtimes_test.go | 11 +- .../computerconfig/runtime_discovery.go | 10 + .../computerconfig/runtime_discovery_test.go | 18 ++ .../internal/provider/antigravity_probe.go | 15 +- .../provider/antigravity_probe_test.go | 306 ++++++++++++++++++ .../internal/provider/discovery.go | 20 +- .../provider/native/antigravity_catalog.go | 55 ++-- .../native/antigravity_runtime_test.go | 138 +++++++- .../internal/provider/native/catalog.go | 2 - .../internal/provider/protocol_probe.go | 30 +- .../internal/provider/protocol_probe_test.go | 269 ++++++++++++++- .../provider/protocol_probe_unix_test.go | 15 +- .../provider/protocol_probe_windows_test.go | 115 +++++++ .../internal/provider/runtime_monitor.go | 2 +- .../internal/workspace/operation_temp.go | 2 + .../internal/workspace/operation_temp_test.go | 42 +++ 24 files changed, 1141 insertions(+), 96 deletions(-) create mode 100644 apps/computer/local-daemon/internal/provider/antigravity_probe_test.go create mode 100644 apps/computer/local-daemon/internal/provider/protocol_probe_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 852ba045c..fa2abbfa1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -323,6 +323,7 @@ jobs: # hold the Windows launcher, process Job, CLI and overlay path code. - run: go test -run '^$' ./... - run: go test ./cmd/linger-computer-launcher ./cmd/linger-pi-launcher ./cmd/linger-teamhub-launcher ./internal/computercli ./internal/computerconfig ./internal/localmodels ./internal/process + - run: go test -v ./internal/provider -run '^TestWindowsAntigravityProbeUsesPrivateTempBase$' # A failed run saves unpruned; the next successful push prunes. - if: success() && github.event_name == 'push' run: | diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md index 1a2857348..6479043cc 100644 --- a/apps/computer/local-daemon/README.md +++ b/apps/computer/local-daemon/README.md @@ -594,9 +594,16 @@ for a browser sign-in when signed out. - Discovery runs `agy --version`, then an ACP `initialize`, then an empty `session/new` in an isolated temporary directory seeded with the user's - `antigravity-oauth-token` and `settings.json`. ACP's authentication-required - error (`-32000`) on `session/new` means signed out. No prompt is sent, so a - probe stores no conversation. + `antigravity-oauth-token` and `settings.json`. The resident Daemon (and the + control CLI when a validated private state directory exists) allocates each + probe directory under `/operation-tmp` (falling back to the OS + temporary directory when no private temp base is configured), and reports + local probe environment preparation failures as `RUNTIME_DIAGNOSTIC_FAILED` + (logging `runner.runtime_probe.prepare_failed`, + `runner.runtime_auth.prepare_failed`, or + `runner.runtime_models.prepare_failed`) rather than `RUNTIME_INCOMPATIBLE`. + ACP's authentication-required error (`-32000`) on `session/new` means signed + out. No prompt is sent, so a probe stores no conversation. - When `session/new` needs authentication and the environment carries `GEMINI_API_KEY` or `GOOGLE_API_KEY`, the adapter selects the `gemini-api-key` method once and retries. A Google sign-in is never diff --git a/apps/computer/local-daemon/internal/computercli/cli.go b/apps/computer/local-daemon/internal/computercli/cli.go index f32540486..b4edf4819 100644 --- a/apps/computer/local-daemon/internal/computercli/cli.go +++ b/apps/computer/local-daemon/internal/computercli/cli.go @@ -42,7 +42,7 @@ type deps struct { // interruptible derives a context that an interrupt arriving after the // call cancels. interruptible func(ctx context.Context) (context.Context, context.CancelFunc) - diagnoseRuntimes func(ctx context.Context, configuredPaths, environment map[string]string, enabled []string) ([]runtimeDiagnostic, error) + diagnoseRuntimes func(ctx context.Context, request runtimeRequest, enabled []string) ([]runtimeDiagnostic, error) newClient func(stateDirectory string) controlClient inspectDaemon func(ctx context.Context, stateDirectory string) doctorCheck probeGateway func(ctx context.Context, gatewayURL string) doctorCheck @@ -472,7 +472,12 @@ func (c *cli) executeLogin(ctx context.Context, parsed command) (int, error) { if parsed.codexAuthFile != "" { environment = withVariable(environment, "CODEX_HOME", filepath.Dir(parsed.codexAuthFile)) } - diagnostics, err := c.deps.diagnoseRuntimes(ctx, requested, environment, parsed.enabledRuntimes) + tempBase := validatedProbeTempBase(filepath.Join(filepath.Dir(parsed.configPath), "state")) + diagnostics, err := c.deps.diagnoseRuntimes(ctx, runtimeRequest{ + configuredPaths: requested, + environment: environment, + tempBase: tempBase, + }, parsed.enabledRuntimes) if err != nil { return 0, wrapError(categoryCapabilityProbe, "Runtime capability probing failed: "+err.Error(), err) } diff --git a/apps/computer/local-daemon/internal/computercli/cli_test.go b/apps/computer/local-daemon/internal/computercli/cli_test.go index c46596f04..7cda0c748 100644 --- a/apps/computer/local-daemon/internal/computercli/cli_test.go +++ b/apps/computer/local-daemon/internal/computercli/cli_test.go @@ -8,11 +8,13 @@ import ( "os" "path/filepath" "reflect" + "runtime" "strings" "testing" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/control" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport" + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider" ) @@ -47,7 +49,7 @@ func TestLoginAcceptsRetiredConcurrencyFlags(t *testing.T) { func TestLoginLimitsDiagnosticsAndSetupToTheEnabledRuntime(t *testing.T) { f := newFixture(t) var requested []string - f.deps.diagnoseRuntimes = func(_ context.Context, _, _ map[string]string, enabled []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(_ context.Context, _ runtimeRequest, enabled []string) ([]runtimeDiagnostic, error) { requested = enabled return onlyRuntime("codex"), nil } @@ -61,7 +63,7 @@ func TestLoginLimitsDiagnosticsAndSetupToTheEnabledRuntime(t *testing.T) { func TestLoginConnectsWithOnlySelectedPiAbsent(t *testing.T) { f := newFixture(t) - f.deps.diagnoseRuntimes = func(context.Context, map[string]string, map[string]string, []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(context.Context, runtimeRequest, []string) ([]runtimeDiagnostic, error) { return onlyRuntime("pi"), nil } if code := f.run("login", "--enabled-runtime", "pi"); code != 0 { @@ -74,7 +76,7 @@ func TestLoginConnectsWithOnlySelectedPiAbsent(t *testing.T) { func TestLoginPreservesAnUnselectedExecutableOverride(t *testing.T) { f := newFixture(t) - f.deps.diagnoseRuntimes = func(context.Context, map[string]string, map[string]string, []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(context.Context, runtimeRequest, []string) ([]runtimeDiagnostic, error) { return onlyRuntime("codex"), nil } selected, other := filepath.Join(f.root, "selected-codex"), filepath.Join(f.root, "unselected-claude") @@ -88,13 +90,13 @@ func TestLoginPreservesAnUnselectedExecutableOverride(t *testing.T) { func TestLoginRejectsMissingSelectedExecutableAndEmptyDiscovery(t *testing.T) { f := newFixture(t) - f.deps.diagnoseRuntimes = func(context.Context, map[string]string, map[string]string, []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(context.Context, runtimeRequest, []string) ([]runtimeDiagnostic, error) { return onlyRuntime("pi"), nil } if code := f.run("login", "--enabled-runtime", "pi", "--pi-path", filepath.Join(f.root, "missing-pi")); code != 14 { t.Fatalf("explicit missing executable exit=%d", code) } - f.deps.diagnoseRuntimes = func(context.Context, map[string]string, map[string]string, []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(context.Context, runtimeRequest, []string) ([]runtimeDiagnostic, error) { return nil, nil } if code := f.run("login", "--enabled-runtime", "pi"); code != 13 { @@ -107,7 +109,7 @@ func TestLoginRejectsMissingSelectedExecutableAndEmptyDiscovery(t *testing.T) { func TestLoginConnectsBeforeRuntimeInstallation(t *testing.T) { f := newFixture(t) - f.deps.diagnoseRuntimes = func(context.Context, map[string]string, map[string]string, []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(context.Context, runtimeRequest, []string) ([]runtimeDiagnostic, error) { var absent []runtimeDiagnostic for _, runtimeType := range runtimeTypes { absent = append(absent, runtimeDiagnostic{Type: runtimeType, Status: "not_installed", ErrorMessage: "Runtime executable not found"}) @@ -566,6 +568,108 @@ func TestRuntimeCheckUsesConfiguredPathsAndCodexHome(t *testing.T) { } } +func TestDoctorAndRuntimeCheckForwardValidatedStateTempBase(t *testing.T) { + t.Run("valid_private_state_directory", func(t *testing.T) { + f := newFixture(t) + stateDir := filepath.Join(f.root, "state") + if err := privatefs.EnsureDir(stateDir); err != nil { + t.Fatal(err) + } + wantTempBase := filepath.Join(stateDir, "operation-tmp") + + var doctorReq runtimeRequest + f.deps.diagnoseRuntimes = func(_ context.Context, request runtimeRequest, _ []string) ([]runtimeDiagnostic, error) { + doctorReq = request + return runtimeFixtures(request.configuredPaths), nil + } + if code := f.run("doctor", "--json", "--config", f.configPath); code != 0 { + t.Fatalf("doctor exit=%d stdout=%s stderr=%s", code, f.stdout.String(), f.stderr.String()) + } + if doctorReq.tempBase != wantTempBase { + t.Fatalf("doctor tempBase = %q, want %q", doctorReq.tempBase, wantTempBase) + } + + var checkReq runtimeRequest + f.deps.checkRuntime = func(_ context.Context, runtimeType string, request runtimeRequest) (runtimeCheck, error) { + checkReq = request + return runtimeCheck{diagnostic: onlyRuntime(runtimeType)[0]}, nil + } + f.clear() + if code := f.run("runtime", "check", "codex", "--config", f.configPath); code != 0 { + t.Fatalf("runtime check exit=%d stdout=%s stderr=%s", code, f.stdout.String(), f.stderr.String()) + } + if checkReq.tempBase != wantTempBase { + t.Fatalf("runtime check tempBase = %q, want %q", checkReq.tempBase, wantTempBase) + } + }) + + t.Run("missing_state_directory_omits_temp_base", func(t *testing.T) { + f := newFixture(t) + if err := os.RemoveAll(filepath.Join(f.root, "state")); err != nil { + t.Fatal(err) + } + doctorReq := runtimeRequest{tempBase: "sentinel"} + f.deps.diagnoseRuntimes = func(_ context.Context, request runtimeRequest, _ []string) ([]runtimeDiagnostic, error) { + doctorReq = request + return runtimeFixtures(request.configuredPaths), nil + } + _ = f.run("doctor", "--json", "--config", f.configPath) + if doctorReq.tempBase != "" { + t.Fatalf("doctor tempBase = %q, want empty when state directory is missing", doctorReq.tempBase) + } + + checkReq := runtimeRequest{tempBase: "sentinel"} + f.deps.checkRuntime = func(_ context.Context, runtimeType string, request runtimeRequest) (runtimeCheck, error) { + checkReq = request + return runtimeCheck{diagnostic: onlyRuntime(runtimeType)[0]}, nil + } + f.clear() + _ = f.run("runtime", "check", "codex", "--config", f.configPath) + if checkReq.tempBase != "" { + t.Fatalf("runtime check tempBase = %q, want empty when state directory is missing", checkReq.tempBase) + } + }) + + t.Run("unsafe_state_directory_omits_temp_base", func(t *testing.T) { + f := newFixture(t) + stateDir := filepath.Join(f.root, "state") + if runtime.GOOS == "windows" { + // Replace the directory with a regular file so privatefs.CheckPath + // rejects it deterministically on Windows without touching ACLs. + if err := os.RemoveAll(stateDir); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(stateDir, []byte("not-a-dir"), 0o600); err != nil { + t.Fatal(err) + } + } else { + if err := os.Chmod(stateDir, 0o755); err != nil { + t.Fatal(err) + } + } + doctorReq := runtimeRequest{tempBase: "sentinel"} + f.deps.diagnoseRuntimes = func(_ context.Context, request runtimeRequest, _ []string) ([]runtimeDiagnostic, error) { + doctorReq = request + return runtimeFixtures(request.configuredPaths), nil + } + _ = f.run("doctor", "--json", "--config", f.configPath) + if doctorReq.tempBase != "" { + t.Fatalf("doctor tempBase = %q, want empty when state directory fails privatefs check", doctorReq.tempBase) + } + + checkReq := runtimeRequest{tempBase: "sentinel"} + f.deps.checkRuntime = func(_ context.Context, runtimeType string, request runtimeRequest) (runtimeCheck, error) { + checkReq = request + return runtimeCheck{diagnostic: onlyRuntime(runtimeType)[0]}, nil + } + f.clear() + _ = f.run("runtime", "check", "codex", "--config", f.configPath) + if checkReq.tempBase != "" { + t.Fatalf("runtime check tempBase = %q, want empty when state directory fails privatefs check", checkReq.tempBase) + } + }) +} + func TestAuthStatusShowsTheSavedAuthorization(t *testing.T) { f := newFixture(t) f.deps.environment["LINGER_WEB_URL"] = "https://app.example.test" @@ -644,7 +748,7 @@ func TestDoctorFailures(t *testing.T) { f = newFixture(t) f.writeConfig(map[string]any{"enabled_runtimes": []any{}}) probed := false - f.deps.diagnoseRuntimes = func(context.Context, map[string]string, map[string]string, []string) ([]runtimeDiagnostic, error) { + f.deps.diagnoseRuntimes = func(context.Context, runtimeRequest, []string) ([]runtimeDiagnostic, error) { probed = true return nil, nil } @@ -656,8 +760,8 @@ func TestDoctorFailures(t *testing.T) { codexHome := filepath.Join(f.root, "custom-codex") f.writeConfig(map[string]any{"codex": map[string]any{"auth_file": filepath.Join(codexHome, "auth.json")}, "credential_expires_at": "2026-01-01T00:00:00.000Z"}) var environment map[string]string - f.deps.diagnoseRuntimes = func(_ context.Context, _ map[string]string, probeEnvironment map[string]string, _ []string) ([]runtimeDiagnostic, error) { - environment = probeEnvironment + f.deps.diagnoseRuntimes = func(_ context.Context, request runtimeRequest, _ []string) ([]runtimeDiagnostic, error) { + environment = request.environment diagnostics := runtimeFixtures(nil) diagnostics[0].Status, diagnostics[0].ErrorMessage = "authentication_required", "Codex authentication is required" return diagnostics, nil diff --git a/apps/computer/local-daemon/internal/computercli/doctor.go b/apps/computer/local-daemon/internal/computercli/doctor.go index 042e6bc79..c2547aae4 100644 --- a/apps/computer/local-daemon/internal/computercli/doctor.go +++ b/apps/computer/local-daemon/internal/computercli/doctor.go @@ -43,7 +43,8 @@ func (c *cli) runDoctor(ctx context.Context, parsed command) (doctorReport, erro if config.configCheck.Status == "fail" { return doctorReport{Version: 1, OK: false, Checks: checks}, nil } - checks = append(checks, inspectStateDirectory(config.stateDirectory)) + stateCheck := inspectStateDirectory(config.stateDirectory) + checks = append(checks, stateCheck) checks = append(checks, c.deps.probeGateway(ctx, config.gatewayURL)) checks = append(checks, c.deps.inspectDaemon(ctx, config.stateDirectory)) configuredPaths := parsed.runtimePaths @@ -54,7 +55,15 @@ func (c *cli) runDoctor(ctx context.Context, parsed command) (doctorReport, erro if config.codexHome != "" { environment = withVariable(environment, "CODEX_HOME", config.codexHome) } - diagnostics, err := c.deps.diagnoseRuntimes(ctx, configuredPaths, environment, config.enabledRuntimes) + tempBase := "" + if stateCheck.Status == "pass" { + tempBase = filepath.Join(config.stateDirectory, "operation-tmp") + } + diagnostics, err := c.deps.diagnoseRuntimes(ctx, runtimeRequest{ + configuredPaths: configuredPaths, + environment: environment, + tempBase: tempBase, + }, config.enabledRuntimes) if err != nil { return doctorReport{}, err } diff --git a/apps/computer/local-daemon/internal/computercli/fixture_test.go b/apps/computer/local-daemon/internal/computercli/fixture_test.go index 4ff23b77f..0aec4f06c 100644 --- a/apps/computer/local-daemon/internal/computercli/fixture_test.go +++ b/apps/computer/local-daemon/internal/computercli/fixture_test.go @@ -140,9 +140,9 @@ func newFixture(t *testing.T) *fixture { } return runtimeCheck{}, errors.New("missing fixture") }, - diagnoseRuntimes: func(_ context.Context, configuredPaths, _ map[string]string, _ []string) ([]runtimeDiagnostic, error) { - f.diagnoseInputs = append(f.diagnoseInputs, configuredPaths) - return runtimeFixtures(configuredPaths), nil + diagnoseRuntimes: func(_ context.Context, request runtimeRequest, _ []string) ([]runtimeDiagnostic, error) { + f.diagnoseInputs = append(f.diagnoseInputs, request.configuredPaths) + return runtimeFixtures(request.configuredPaths), nil }, newClient: func(string) controlClient { return fakeClient{f: f} }, inspectDaemon: func(context.Context, string) doctorCheck { diff --git a/apps/computer/local-daemon/internal/computercli/runtime_login.go b/apps/computer/local-daemon/internal/computercli/runtime_login.go index 06a817573..c0dc13602 100644 --- a/apps/computer/local-daemon/internal/computercli/runtime_login.go +++ b/apps/computer/local-daemon/internal/computercli/runtime_login.go @@ -82,6 +82,7 @@ func (c *cli) runtimeRequest(parsed command) (runtimeRequest, error) { } configuredPaths := parsed.runtimePaths environment := c.deps.environment + var tempBase string if configured { config := inspectComputerConfig(parsed.configPath, c.deps.environment, c.command) if configuredPaths == nil { @@ -90,8 +91,9 @@ func (c *cli) runtimeRequest(parsed command) (runtimeRequest, error) { if config.codexHome != "" { environment = withVariable(environment, "CODEX_HOME", config.codexHome) } + tempBase = validatedProbeTempBase(config.stateDirectory) } - return runtimeRequest{configuredPaths: configuredPaths, environment: environment}, nil + return runtimeRequest{configuredPaths: configuredPaths, environment: environment, tempBase: tempBase}, nil } // environmentList renders a Runtime environment for exec.Cmd, sorted so a diff --git a/apps/computer/local-daemon/internal/computercli/runtimes.go b/apps/computer/local-daemon/internal/computercli/runtimes.go index 0bf3cfd2d..9719d4d0b 100644 --- a/apps/computer/local-daemon/internal/computercli/runtimes.go +++ b/apps/computer/local-daemon/internal/computercli/runtimes.go @@ -10,6 +10,7 @@ import ( "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/computerconfig" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/localtools" + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider" ) @@ -53,16 +54,29 @@ type runtimeCheck struct { type runtimeRequest struct { configuredPaths map[string]string environment map[string]string + tempBase string live bool } +// validatedProbeTempBase returns /operation-tmp only when +// stateDirectory exists as a validated owner-only private directory. +func validatedProbeTempBase(stateDirectory string) string { + if stateDirectory == "" { + return "" + } + if err := privatefs.CheckPath(stateDirectory, "directory", true); err != nil { + return "" + } + return filepath.Join(stateDirectory, "operation-tmp") +} + // diagnoseRuntimes discovers the enabled Runtimes with the same discovery the // Daemon uses. -func diagnoseRuntimes(ctx context.Context, configuredPaths, environment map[string]string, enabled []string) ([]runtimeDiagnostic, error) { +func diagnoseRuntimes(ctx context.Context, request runtimeRequest, enabled []string) ([]runtimeDiagnostic, error) { if enabled == nil { enabled = runtimeTypes } - checks, err := requestRuntimeChecks(ctx, enabled, runtimeRequest{configuredPaths: configuredPaths, environment: environment}) + checks, err := requestRuntimeChecks(ctx, enabled, request) diagnostics := make([]runtimeDiagnostic, 0, len(checks)) for _, check := range checks { diagnostics = append(diagnostics, check.diagnostic) @@ -90,6 +104,7 @@ func requestRuntimeChecks(ctx context.Context, types []string, request runtimeRe BundledPaths: resolveBundledRuntimePaths(), Environment: request.environment, Runtimes: selectedRuntimes, + TempBase: request.tempBase, }) if err != nil { return nil, err diff --git a/apps/computer/local-daemon/internal/computercli/runtimes_test.go b/apps/computer/local-daemon/internal/computercli/runtimes_test.go index 53661319b..06e74c981 100644 --- a/apps/computer/local-daemon/internal/computercli/runtimes_test.go +++ b/apps/computer/local-daemon/internal/computercli/runtimes_test.go @@ -110,11 +110,12 @@ done diagnostics, err := diagnoseRuntimes( context.Background(), - nil, - map[string]string{ - "PATH": emptyPath, - "HOME": home, - "SHELL": filepath.Join(root, "no-shell"), + runtimeRequest{ + environment: map[string]string{ + "PATH": emptyPath, + "HOME": home, + "SHELL": filepath.Join(root, "no-shell"), + }, }, []string{"pi"}, ) diff --git a/apps/computer/local-daemon/internal/computerconfig/runtime_discovery.go b/apps/computer/local-daemon/internal/computerconfig/runtime_discovery.go index dc75f8994..42c723fe9 100644 --- a/apps/computer/local-daemon/internal/computerconfig/runtime_discovery.go +++ b/apps/computer/local-daemon/internal/computerconfig/runtime_discovery.go @@ -1,6 +1,7 @@ package computerconfig import ( + "errors" "fmt" "path/filepath" "strings" @@ -36,6 +37,10 @@ type RuntimeDiscoveryRequest struct { Runtimes []string SkipModelCatalog bool Timeout time.Duration + // TempBase holds per-probe temporary directories inside a private state + // directory; when non-empty it must be absolute, and empty falls back to + // the OS temporary directory. + TempBase string // RequireAbsolutePaths rejects relative paths in ConfiguredPaths and ignores // relative LINGER__PATH values. RequireAbsolutePaths bool @@ -50,6 +55,10 @@ func RuntimeDiscoveryOptions(request RuntimeDiscoveryRequest) (provider.Discover return provider.DiscoveryOptions{}, err } } + tempBase := strings.TrimSpace(request.TempBase) + if tempBase != "" && !filepath.IsAbs(tempBase) { + return provider.DiscoveryOptions{}, errors.New("TempBase must be absolute") + } selected := map[string]string{} for _, runtimeType := range allRuntimeTypes { explicit := strings.TrimSpace(request.ConfiguredPaths[runtimeType]) @@ -73,5 +82,6 @@ func RuntimeDiscoveryOptions(request RuntimeDiscoveryRequest) (provider.Discover Runtimes: request.Runtimes, SkipModelCatalog: request.SkipModelCatalog, Timeout: request.Timeout, + TempBase: tempBase, }, nil } diff --git a/apps/computer/local-daemon/internal/computerconfig/runtime_discovery_test.go b/apps/computer/local-daemon/internal/computerconfig/runtime_discovery_test.go index fdeb4c066..0daf913ce 100644 --- a/apps/computer/local-daemon/internal/computerconfig/runtime_discovery_test.go +++ b/apps/computer/local-daemon/internal/computerconfig/runtime_discovery_test.go @@ -70,6 +70,24 @@ func TestRuntimeDiscoveryOptionsRejectsInvalidInputs(t *testing.T) { }); err == nil { t.Fatal("expected error for relative configured path when RequireAbsolutePaths is true") } + if _, err := RuntimeDiscoveryOptions(RuntimeDiscoveryRequest{ + TempBase: "relative/tmp", + }); err == nil { + t.Fatal("expected error for relative TempBase") + } +} + +func TestRuntimeDiscoveryOptionsForwardsTempBase(t *testing.T) { + tempBase := filepath.Join(t.TempDir(), "operation-tmp") + options, err := RuntimeDiscoveryOptions(RuntimeDiscoveryRequest{ + TempBase: tempBase, + }) + if err != nil { + t.Fatalf("RuntimeDiscoveryOptions failed: %v", err) + } + if options.TempBase != tempBase { + t.Fatalf("TempBase = %q, want %q", options.TempBase, tempBase) + } } func TestRuntimeDiscoveryOptionsForwardsBundledPaths(t *testing.T) { diff --git a/apps/computer/local-daemon/internal/provider/antigravity_probe.go b/apps/computer/local-daemon/internal/provider/antigravity_probe.go index d0aeaa9bb..55ee1e7b9 100644 --- a/apps/computer/local-daemon/internal/provider/antigravity_probe.go +++ b/apps/computer/local-daemon/internal/provider/antigravity_probe.go @@ -3,19 +3,30 @@ package provider import ( "context" "errors" + "log/slog" "time" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider/native" + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider/redact" ) // probeAntigravityAuthentication opens an empty ACP session: Antigravity // answers session/new with ACP's authentication-required error when neither // a Google sign-in nor a Gemini API key is available. -func probeAntigravityAuthentication(ctx context.Context, executable string, environment map[string]string, timeout time.Duration, _ string) runtimeProbeOutcome { +func probeAntigravityAuthentication(ctx context.Context, executable string, environment map[string]string, timeout time.Duration, tempBase string) runtimeProbeOutcome { ctx, cancel := context.WithTimeout(ctx, boundedAuthTimeout(timeout)) defer cancel() - probe, err := native.ProbeAntigravity(ctx, native.NewInvocation(executable, nil).WithEnvironment(environment)) + probe, err := native.ProbeAntigravity(ctx, native.NewInvocation(executable, nil).WithEnvironment(environment), tempBase) if err != nil { + if errors.Is(err, native.ErrAntigravityProbePrepare) { + slog.Warn("runner.runtime_auth.prepare_failed", "runtime_type", "antigravity", "error", redact.Text(err.Error())) + return runtimeProbeOutcome{ + Status: "error", + Code: "RUNTIME_DIAGNOSTIC_FAILED", + Message: "Antigravity diagnostic environment could not be prepared", + } + } + slog.Warn("runner.runtime_auth.probe_failed", "runtime_type", "antigravity", "error", redact.Text(err.Error())) message := "Antigravity authentication could not be verified" if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) { message = "Antigravity authentication check timed out" diff --git a/apps/computer/local-daemon/internal/provider/antigravity_probe_test.go b/apps/computer/local-daemon/internal/provider/antigravity_probe_test.go new file mode 100644 index 000000000..4c8c1a58d --- /dev/null +++ b/apps/computer/local-daemon/internal/provider/antigravity_probe_test.go @@ -0,0 +1,306 @@ +package provider + +import ( + "bufio" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +type agyProbeTraceEntry struct { + GeminiDir string `json:"geminiDir"` + LogFile string `json:"logFile"` + Cwd string `json:"cwd"` + PrivateCheckOK bool `json:"privateCheckOK"` +} + +func readAgyProbeTrace(t *testing.T, path string) []agyProbeTraceEntry { + t.Helper() + file, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer file.Close() + var entries []agyProbeTraceEntry + scanner := bufio.NewScanner(file) + for scanner.Scan() { + var entry agyProbeTraceEntry + if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil { + t.Fatalf("decode trace line %q: %v", scanner.Text(), err) + } + entries = append(entries, entry) + } + if err := scanner.Err(); err != nil { + t.Fatal(err) + } + return entries +} + +func TestDiscoverAntigravityUsesTempBaseForProtocolAuthAndCatalog(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + home := filepath.Join(root, "home") + tempBase := filepath.Join(root, "state", "operation-tmp") + metaFile := filepath.Join(root, "meta.json") + traceFile := filepath.Join(root, "trace.jsonl") + badTemp := filepath.Join(root, "not-a-dir") + if err := os.MkdirAll(home, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(badTemp, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + // Poison every OS temporary directory variable so any accidental fallback + // to os.TempDir() fails immediately. + t.Setenv("TMPDIR", badTemp) + t.Setenv("TEMP", badTemp) + t.Setenv("TMP", badTemp) + + env := map[string]string{ + "HOME": home, + "PATH": filepath.Dir(executable), + testAgyProtocolHelperEnv: metaFile, + testAgyProtocolTraceEnv: traceFile, + } + result, err := Discover(context.Background(), DiscoveryOptions{ + ConfiguredPaths: map[string]string{"antigravity": executable}, + Runtimes: []string{"antigravity"}, + TempBase: tempBase, + Environment: env, + Timeout: 5 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + if len(result.Diagnostics) != 1 { + t.Fatalf("diagnostics = %+v, want 1 entry", result.Diagnostics) + } + diagnostic := result.Diagnostics[0] + if diagnostic.Type != "antigravity" || diagnostic.Status != "ready" || diagnostic.Error != nil { + t.Fatalf("antigravity diagnostic = %+v, want ready", diagnostic) + } + if len(diagnostic.Models) != 1 || diagnostic.Models[0].ID != "gemini-pro" { + t.Fatalf("antigravity models = %+v, want gemini-pro", diagnostic.Models) + } + + trace := readAgyProbeTrace(t, traceFile) + if len(trace) != 2 { + t.Fatalf("expected 2 antigravity probe invocations (protocol + auth/catalog), got %d: %+v", len(trace), trace) + } + for i, entry := range trace { + if !isPathWithin(tempBase, entry.GeminiDir) || !isPathWithin(tempBase, entry.LogFile) || !entry.PrivateCheckOK { + t.Fatalf("trace[%d] did not run privately inside tempBase %q: %+v", i, tempBase, entry) + } + } + if entries, err := os.ReadDir(tempBase); err != nil || len(entries) != 0 { + t.Fatalf("tempBase was not cleaned up after Discover: entries=%v err=%v", entries, err) + } + + // Verify the uncached model-discovery fallback path also uses TempBase. + models, modelErr := discoverRuntimeModels(context.Background(), "antigravity", executable, env, tempBase) + if modelErr != "" || len(models) != 1 || models[0].ID != "gemini-pro" { + t.Fatalf("discoverRuntimeModels() = %+v, err=%q; want gemini-pro", models, modelErr) + } + if entries, err := os.ReadDir(tempBase); err != nil || len(entries) != 0 { + t.Fatalf("tempBase was not cleaned up after discoverRuntimeModels: entries=%v err=%v", entries, err) + } +} + +func TestRefreshRuntimeAuthenticationAntigravityUsesTempBase(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + canonical, err := canonicalExecutable(executable) + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + home := filepath.Join(root, "home") + tempBase := filepath.Join(root, "state", "operation-tmp") + metaFile := filepath.Join(root, "meta.json") + traceFile := filepath.Join(root, "trace.jsonl") + badTemp := filepath.Join(root, "not-a-dir") + if err := os.MkdirAll(home, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(badTemp, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("TMPDIR", badTemp) + t.Setenv("TEMP", badTemp) + t.Setenv("TMP", badTemp) + + current := DiscoveryResult{ + Diagnostics: []RuntimeDiagnostic{ + { + Type: "antigravity", + Status: "ready", + Version: "1.5.12", + ExecutablePath: canonical, + EntryPath: executable, + }, + }, + } + options := DiscoveryOptions{ + TempBase: tempBase, + Timeout: 5 * time.Second, + Environment: map[string]string{ + "HOME": home, + testAgyProtocolHelperEnv: metaFile, + testAgyProtocolTraceEnv: traceFile, + }, + } + refreshed, err := RefreshRuntimeAuthentication(context.Background(), current, options) + if err != nil { + t.Fatal(err) + } + if len(refreshed.Diagnostics) != 1 || refreshed.Diagnostics[0].Status != "ready" || len(refreshed.Diagnostics[0].Models) != 1 { + t.Fatalf("refreshed = %+v, want ready with 1 model", refreshed.Diagnostics) + } + trace := readAgyProbeTrace(t, traceFile) + if len(trace) != 1 || !isPathWithin(tempBase, trace[0].GeminiDir) || !isPathWithin(tempBase, trace[0].LogFile) || !trace[0].PrivateCheckOK { + t.Fatalf("auth refresh trace = %+v, want single private probe under %q", trace, tempBase) + } + if entries, err := os.ReadDir(tempBase); err != nil || len(entries) != 0 { + t.Fatalf("tempBase was not cleaned up after RefreshRuntimeAuthentication: entries=%v err=%v", entries, err) + } +} + +func TestProbeAntigravityAuthenticationLogsAndCategorizesFailures(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + + t.Run("prepare_failed", func(t *testing.T) { + root := t.TempDir() + fileBase := filepath.Join(root, "blocked-temp-base") + if err := os.WriteFile(fileBase, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + logged := captureProbeLog(t) + outcome := probeAntigravityAuthentication( + context.Background(), + executable, + map[string]string{"HOME": root, testAgyProtocolHelperEnv: filepath.Join(root, "meta.json")}, + 5*time.Second, + fileBase, + ) + if outcome.Status != "error" || outcome.Code != "RUNTIME_DIAGNOSTIC_FAILED" || outcome.Message != "Antigravity diagnostic environment could not be prepared" { + t.Fatalf("outcome = %+v, want prepare failure RUNTIME_DIAGNOSTIC_FAILED", outcome) + } + if strings.Contains(outcome.Message, fileBase) { + t.Fatalf("outcome.Message leaked local path: %q", outcome.Message) + } + logOutput := logged.String() + for _, want := range []string{"runner.runtime_auth.prepare_failed", "runtime_type=antigravity"} { + if !strings.Contains(logOutput, want) { + t.Fatalf("log lacks %q: %s", want, logOutput) + } + } + }) + + t.Run("probe_failed", func(t *testing.T) { + root := t.TempDir() + tempBase := filepath.Join(root, "state", "operation-tmp") + logged := captureProbeLog(t) + outcome := probeAntigravityAuthentication( + context.Background(), + executable, + map[string]string{ + "HOME": root, + testAgyProtocolHelperEnv: filepath.Join(root, "meta.json"), + testAgyProtocolModeEnv: "auth-error", + }, + 5*time.Second, + tempBase, + ) + if outcome.Status != "error" || outcome.Code != "RUNTIME_DIAGNOSTIC_FAILED" || outcome.Message != "Antigravity authentication could not be verified" { + t.Fatalf("outcome = %+v, want probe failure RUNTIME_DIAGNOSTIC_FAILED", outcome) + } + logOutput := logged.String() + for _, want := range []string{"runner.runtime_auth.probe_failed", "runtime_type=antigravity"} { + if !strings.Contains(logOutput, want) { + t.Fatalf("log lacks %q: %s", want, logOutput) + } + } + if entries, err := os.ReadDir(tempBase); err != nil || len(entries) != 0 { + t.Fatalf("tempBase leaked entries after failed auth probe: entries=%v err=%v", entries, err) + } + }) + + t.Run("os_temp_fallback_prepare_failed", func(t *testing.T) { + root := t.TempDir() + badTemp := filepath.Join(root, "not-a-dir") + if err := os.WriteFile(badTemp, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("TMPDIR", badTemp) + t.Setenv("TEMP", badTemp) + t.Setenv("TMP", badTemp) + logged := captureProbeLog(t) + outcome := probeAntigravityAuthentication( + context.Background(), + executable, + map[string]string{"HOME": root, testAgyProtocolHelperEnv: filepath.Join(root, "meta.json")}, + 5*time.Second, + "", + ) + if outcome.Status != "error" || outcome.Code != "RUNTIME_DIAGNOSTIC_FAILED" || outcome.Message != "Antigravity diagnostic environment could not be prepared" { + t.Fatalf("outcome = %+v, want prepare failure RUNTIME_DIAGNOSTIC_FAILED", outcome) + } + if strings.Contains(outcome.Message, badTemp) { + t.Fatalf("outcome.Message leaked local path %q: %q", badTemp, outcome.Message) + } + logOutput := logged.String() + for _, want := range []string{"runner.runtime_auth.prepare_failed", "runtime_type=antigravity"} { + if !strings.Contains(logOutput, want) { + t.Fatalf("log lacks %q: %s", want, logOutput) + } + } + }) +} + +func TestDiscoverRuntimeModelsAntigravityPrepareFailureIsCategorical(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + badTemp := filepath.Join(root, "not-a-dir") + if err := os.WriteFile(badTemp, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("TMPDIR", badTemp) + t.Setenv("TEMP", badTemp) + t.Setenv("TMP", badTemp) + + logged := captureProbeLog(t) + models, modelErr := discoverRuntimeModels( + context.Background(), + "antigravity", + executable, + map[string]string{"HOME": root, testAgyProtocolHelperEnv: filepath.Join(root, "meta.json")}, + "", + ) + if len(models) != 0 || modelErr != "Antigravity diagnostic environment could not be prepared" { + t.Fatalf("discoverRuntimeModels() = %+v, err=%q; want empty models and categorical prepare error", models, modelErr) + } + if strings.Contains(modelErr, badTemp) { + t.Fatalf("modelErr leaked local path %q: %q", badTemp, modelErr) + } + logOutput := logged.String() + for _, want := range []string{"runner.runtime_models.prepare_failed", "runtime_type=antigravity"} { + if !strings.Contains(logOutput, want) { + t.Fatalf("log lacks %q: %s", want, logOutput) + } + } +} diff --git a/apps/computer/local-daemon/internal/provider/discovery.go b/apps/computer/local-daemon/internal/provider/discovery.go index f0fa5d8f4..ef80231ef 100644 --- a/apps/computer/local-daemon/internal/provider/discovery.go +++ b/apps/computer/local-daemon/internal/provider/discovery.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "log/slog" "os" "path/filepath" "runtime" @@ -273,7 +274,7 @@ func diagnose(ctx context.Context, kind, executable, protocol string, options Di catalogAllowed := !options.SkipModelCatalog && (outcome.Status == "ready" || ((kind == "codex" || kind == "pi") && outcome.Status == "authentication_required")) if catalogAllowed { catalogCtx, stop := context.WithTimeout(ctx, budget) - observation.Models, observation.ModelCatalogError = probedRuntimeModels(catalogCtx, kind, canonical, environment, outcome) + observation.Models, observation.ModelCatalogError = probedRuntimeModels(catalogCtx, kind, canonical, environment, outcome, options.TempBase) if observation.ModelCatalogError == "" { getModelLink := newGetModelLink(catalogCtx, kind, environment) for i := range observation.Models { @@ -320,15 +321,24 @@ func versionProbeTimedOut(err error) bool { // probedRuntimeModels uses the catalog the probe already read, or discovers // it. -func probedRuntimeModels(ctx context.Context, kind, executable string, environment map[string]string, outcome runtimeProbeOutcome) ([]RuntimeModel, string) { +func probedRuntimeModels(ctx context.Context, kind, executable string, environment map[string]string, outcome runtimeProbeOutcome, tempBase string) ([]RuntimeModel, string) { if outcome.catalog != nil { return catalogModels(*outcome.catalog, nil) } - return discoverRuntimeModels(ctx, kind, executable, environment) + return discoverRuntimeModels(ctx, kind, executable, environment, tempBase) } -func discoverRuntimeModels(ctx context.Context, kind, executable string, environment map[string]string) ([]RuntimeModel, string) { - return catalogModels(native.DiscoverModels(ctx, kind, native.NewInvocation(executable, nil).WithEnvironment(environment))) +func discoverRuntimeModels(ctx context.Context, kind, executable string, environment map[string]string, tempBase string) ([]RuntimeModel, string) { + inv := native.NewInvocation(executable, nil).WithEnvironment(environment) + if kind == "antigravity" { + catalog, err := native.DiscoverAntigravityModels(ctx, inv, tempBase) + if errors.Is(err, native.ErrAntigravityProbePrepare) { + slog.Warn("runner.runtime_models.prepare_failed", "runtime_type", kind, "error", redact.Text(err.Error())) + return []RuntimeModel{}, "Antigravity diagnostic environment could not be prepared" + } + return catalogModels(catalog, err) + } + return catalogModels(native.DiscoverModels(ctx, kind, inv)) } func catalogModels(catalog native.ModelList, err error) ([]RuntimeModel, string) { diff --git a/apps/computer/local-daemon/internal/provider/native/antigravity_catalog.go b/apps/computer/local-daemon/internal/provider/native/antigravity_catalog.go index b198a4ad8..3cefcd065 100644 --- a/apps/computer/local-daemon/internal/provider/native/antigravity_catalog.go +++ b/apps/computer/local-daemon/internal/provider/native/antigravity_catalog.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" "path/filepath" "slices" @@ -23,6 +24,14 @@ var ( antigravityProbeUsageSettle = 40 * time.Millisecond ) +// ErrAntigravityProbePrepare marks failures preparing the isolated local +// temporary environment for an Antigravity probe before launching `agy acp`. +var ErrAntigravityProbePrepare = errors.New("Antigravity diagnostic environment could not be prepared") + +func wrapAntigravityProbePrepareError(err error) error { + return fmt.Errorf("%w: %w", ErrAntigravityProbePrepare, err) +} + // AntigravityProbe is what one ACP session/new tells about the signed-in // account: whether a session opens and which models it offers. type AntigravityProbe struct { @@ -30,11 +39,14 @@ type AntigravityProbe struct { Models ModelList } -// PrepareAntigravityProtocolProbe creates an empty isolated temporary Gemini -// directory and ACP log path for `agy acp` protocol handshakes without copying -// any user credentials or settings. -func PrepareAntigravityProtocolProbe() ([]string, func(), error) { - args, _, release, err := prepareAntigravityProbe(nil, false) +// PrepareAntigravityProtocolProbe creates an empty isolated Gemini directory +// and ACP log path for `agy acp` protocol handshakes without copying any user +// credentials or settings. When tempBase is non-empty, it allocates a +// lock-tracked private directory via localworkspace.PrivateTempRoot under +// tempBase; when empty, it falls back to the hardened OS temporary directory. +// Preparation failures wrap ErrAntigravityProbePrepare. +func PrepareAntigravityProtocolProbe(tempBase string) ([]string, func(), error) { + args, _, release, err := prepareAntigravityProbe(tempBase, nil, false) return args, release, err } @@ -54,21 +66,21 @@ func prepareAntigravityIsolatedDir(baseDir string, env map[string]string, seedCr return geminiDir, localworkspace.AntigravityACPLogPath(baseDir), nil } -func prepareAntigravityProbe(env map[string]string, seedCredentials bool) ([]string, string, func(), error) { - root, removeRoot, err := localworkspace.PrivateTempRoot("", "linger-antigravity-probe-") +func prepareAntigravityProbe(tempBase string, env map[string]string, seedCredentials bool) ([]string, string, func(), error) { + root, removeRoot, err := localworkspace.PrivateTempRoot(tempBase, "linger-antigravity-probe-") if err != nil { - return nil, "", nil, err + return nil, "", nil, wrapAntigravityProbePrepareError(err) } release := func() { _ = removeRoot() } geminiDir, logFile, err := prepareAntigravityIsolatedDir(root, env, seedCredentials) if err != nil { release() - return nil, "", nil, err + return nil, "", nil, wrapAntigravityProbePrepareError(err) } workDir := filepath.Join(root, "workspace") if err := privatefs.EnsureDir(workDir); err != nil { release() - return nil, "", nil, err + return nil, "", nil, wrapAntigravityProbePrepareError(err) } args := []string{"--gemini-dir", geminiDir, "--log-file", logFile} return args, workDir, release, nil @@ -77,15 +89,18 @@ func prepareAntigravityProbe(env map[string]string, seedCredentials bool) ([]str // ProbeAntigravity opens an empty ACP session inside a temporary isolated // Gemini directory and removes that directory after `agy acp` exits, so // probing never persists 0-step conversations or ACP logs under the user's -// ~/.gemini/antigravity-cli store. HOME/USERPROFILE stays unchanged so OS -// keyring auth and GEMINI_API_KEY continue working alongside the copied -// file-based OAuth token and settings. -func ProbeAntigravity(ctx context.Context, inv Invocation) (AntigravityProbe, error) { +// ~/.gemini/antigravity-cli store. When tempBase is non-empty, it allocates a +// lock-tracked private directory via localworkspace.PrivateTempRoot under +// tempBase; when empty, it falls back to the hardened OS temporary directory. +// Preparation failures wrap ErrAntigravityProbePrepare. HOME/USERPROFILE stays +// unchanged so OS keyring auth and GEMINI_API_KEY continue working alongside +// the copied file-based OAuth token and settings. +func ProbeAntigravity(ctx context.Context, inv Invocation, tempBase string) (AntigravityProbe, error) { env := invocationEnvironment(inv) if localworkspace.AntigravityUserAppDataDir(env) == "" { return AntigravityProbe{}, errors.New("Antigravity probe requires HOME") } - probeArgs, workDir, release, err := prepareAntigravityProbe(env, true) + probeArgs, workDir, release, err := prepareAntigravityProbe(tempBase, env, true) if err != nil { return AntigravityProbe{}, err } @@ -117,9 +132,13 @@ func ProbeAntigravity(ctx context.Context, inv Invocation) (AntigravityProbe, er return result, err } -// DiscoverAntigravityModels lists the models of the signed-in account. -func DiscoverAntigravityModels(ctx context.Context, inv Invocation) (ModelList, error) { - probe, err := ProbeAntigravity(ctx, inv) +// DiscoverAntigravityModels lists the models of the signed-in account. When +// tempBase is non-empty, it allocates a lock-tracked private directory via +// localworkspace.PrivateTempRoot under tempBase; when empty, it falls back to +// the hardened OS temporary directory. Preparation failures wrap +// ErrAntigravityProbePrepare. +func DiscoverAntigravityModels(ctx context.Context, inv Invocation, tempBase string) (ModelList, error) { + probe, err := ProbeAntigravity(ctx, inv, tempBase) if err != nil { return ModelList{}, err } diff --git a/apps/computer/local-daemon/internal/provider/native/antigravity_runtime_test.go b/apps/computer/local-daemon/internal/provider/native/antigravity_runtime_test.go index 8dc113bed..05190691d 100644 --- a/apps/computer/local-daemon/internal/provider/native/antigravity_runtime_test.go +++ b/apps/computer/local-daemon/internal/provider/native/antigravity_runtime_test.go @@ -15,6 +15,8 @@ import ( "time" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission" + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs" + localworkspace "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/workspace" ) type agyHarness struct { @@ -327,7 +329,7 @@ func TestAntigravityTimeoutStopsTheProcess(t *testing.T) { func TestAntigravityProbeListsModelFamiliesWithTheirLevels(t *testing.T) { h := newAgyHarness(t, "turn", nil) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -346,7 +348,7 @@ func TestAntigravityProbeListsModelFamiliesWithTheirLevels(t *testing.T) { } signedOut := newAgyHarness(t, "signed-out", nil) - if probe, err := ProbeAntigravity(t.Context(), signedOut.inv); err != nil || !probe.AuthenticationRequired { + if probe, err := ProbeAntigravity(t.Context(), signedOut.inv, ""); err != nil || !probe.AuthenticationRequired { t.Fatalf("signed out probe=%+v err=%v", probe, err) } } @@ -369,7 +371,7 @@ func TestAntigravityProbeIsolatesStateAndSeedsCredentials(t *testing.T) { t.Fatal(err) } - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -426,7 +428,7 @@ func TestAntigravityProbeIsolatesStateAndSeedsCredentials(t *testing.T) { func TestAntigravityProbeHandlesMissingUserGeminiDir(t *testing.T) { h := newAgyHarness(t, "token-file", nil) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -438,6 +440,114 @@ func TestAntigravityProbeHandlesMissingUserGeminiDir(t *testing.T) { } } +func TestAntigravityProbeUsesTempBaseAndCleansUp(t *testing.T) { + if _, _, err := PrepareAntigravityProtocolProbe("relative-temp-base"); !errors.Is(err, ErrAntigravityProbePrepare) { + t.Fatalf("PrepareAntigravityProtocolProbe(relative) err = %v, want ErrAntigravityProbePrepare", err) + } + + tempBase := t.TempDir() + unrelatedFile := filepath.Join(tempBase, "keep-me") + if err := os.WriteFile(unrelatedFile, []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + + args1, release1, err := PrepareAntigravityProtocolProbe(tempBase) + if err != nil { + t.Fatalf("PrepareAntigravityProtocolProbe(%q) #1: %v", tempBase, err) + } + args2, release2, err := PrepareAntigravityProtocolProbe(tempBase) + if err != nil { + release1() + t.Fatalf("PrepareAntigravityProtocolProbe(%q) #2: %v", tempBase, err) + } + if len(args1) != 4 || args1[0] != "--gemini-dir" || args1[2] != "--log-file" { + release1() + release2() + t.Fatalf("unexpected args1 = %v", args1) + } + if len(args2) != 4 || args2[0] != "--gemini-dir" || args2[2] != "--log-file" { + release1() + release2() + t.Fatalf("unexpected args2 = %v", args2) + } + probeDir1 := filepath.Dir(args1[1]) + probeDir2 := filepath.Dir(args2[1]) + if probeDir1 == probeDir2 { + release1() + release2() + t.Fatalf("concurrent probes in the same tempBase collided on %q", probeDir1) + } + for _, probeDir := range []string{probeDir1, probeDir2} { + if filepath.Dir(probeDir) != tempBase || !strings.HasPrefix(filepath.Base(probeDir), localworkspace.TaskTempDirPrefix) { + release1() + release2() + t.Fatalf("probeDir = %q, want unique %s* child under %q", probeDir, localworkspace.TaskTempDirPrefix, tempBase) + } + for _, dir := range []string{tempBase, probeDir, filepath.Join(probeDir, "gemini"), filepath.Join(probeDir, "workspace")} { + if err := privatefs.CheckPath(dir, "directory", true); err != nil { + release1() + release2() + t.Fatalf("privatefs check failed for %q: %v", dir, err) + } + } + } + if args1[3] != filepath.Join(probeDir1, "acp.log") || args2[3] != filepath.Join(probeDir2, "acp.log") { + release1() + release2() + t.Fatalf("unexpected log files: args1=%v args2=%v", args1, args2) + } + + release1() + release1() // idempotent + if _, err := os.Stat(probeDir1); !os.IsNotExist(err) { + release2() + t.Fatalf("probeDir1 survived release: %v", err) + } + if _, err := os.Stat(probeDir2); err != nil { + release2() + t.Fatalf("releasing probeDir1 disturbed active probeDir2: %v", err) + } + release2() + if _, err := os.Stat(probeDir2); !os.IsNotExist(err) { + t.Fatalf("probeDir2 survived release: %v", err) + } + if _, err := os.Stat(unrelatedFile); err != nil { + t.Fatalf("release removed unrelated file %q in tempBase: %v", unrelatedFile, err) + } + + metaFile := filepath.Join(t.TempDir(), "probe-in-meta.json") + h := newAgyHarness(t, "turn", map[string]string{agyFakeMetaEnv: metaFile}) + models, err := DiscoverAntigravityModels(t.Context(), h.inv, tempBase) + if err != nil { + t.Fatalf("DiscoverAntigravityModels: %v", err) + } + if len(models.Models) != 2 { + t.Fatalf("models = %+v, want 2 models", models) + } + rawMeta, err := os.ReadFile(metaFile) + if err != nil { + t.Fatal(err) + } + var meta struct { + GeminiDir string `json:"geminiDir"` + LogFile string `json:"logFile"` + } + if err := json.Unmarshal(rawMeta, &meta); err != nil { + t.Fatal(err) + } + usedProbeDir := filepath.Dir(meta.GeminiDir) + if filepath.Dir(usedProbeDir) != tempBase || !strings.HasPrefix(filepath.Base(usedProbeDir), localworkspace.TaskTempDirPrefix) || + meta.GeminiDir != filepath.Join(usedProbeDir, "gemini") || meta.LogFile != filepath.Join(usedProbeDir, "acp.log") { + t.Fatalf("probe paths = %+v, want unique %s* subdir under %q", meta, localworkspace.TaskTempDirPrefix, tempBase) + } + if _, err := os.Stat(usedProbeDir); !os.IsNotExist(err) { + t.Fatalf("probe subdir survived DiscoverAntigravityModels: %v", err) + } + if _, err := os.Stat(unrelatedFile); err != nil { + t.Fatalf("DiscoverAntigravityModels removed unrelated file %q in tempBase: %v", unrelatedFile, err) + } +} + func TestAntigravityTurnKeepsDefaultGeminiDir(t *testing.T) { metaFile := filepath.Join(t.TempDir(), "turn-meta.json") h := newAgyHarness(t, "turn", map[string]string{agyFakeMetaEnv: metaFile}) @@ -1177,7 +1287,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-small": 128000 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1212,7 +1322,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { h := newAgyHarness(t, "turn", map[string]string{ agyFakeUsageWindowsEnv: `{"gemini-pro": ` + rawSize + `}`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1230,7 +1340,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { t.Run("no_usage_update_skips_model_switching", func(t *testing.T) { h := newAgyHarness(t, "turn", nil) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1254,7 +1364,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-small": 128000 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1290,7 +1400,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-valid": 128000 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1324,7 +1434,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-small": 128000 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1357,7 +1467,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-flash": 200000 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1388,7 +1498,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-same-as-pro": 1048576 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1420,7 +1530,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-same-as-pro": 1048576 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } @@ -1447,7 +1557,7 @@ func TestAntigravityProbeContextWindowsFromUsageUpdates(t *testing.T) { "gemini-flash": 1048576 }`, }) - probe, err := ProbeAntigravity(t.Context(), h.inv) + probe, err := ProbeAntigravity(t.Context(), h.inv, "") if err != nil { t.Fatal(err) } diff --git a/apps/computer/local-daemon/internal/provider/native/catalog.go b/apps/computer/local-daemon/internal/provider/native/catalog.go index a4b90e5bc..018244ee2 100644 --- a/apps/computer/local-daemon/internal/provider/native/catalog.go +++ b/apps/computer/local-daemon/internal/provider/native/catalog.go @@ -47,8 +47,6 @@ func DiscoverModels(ctx context.Context, kind string, inv Invocation) (ModelList return codexCatalog(ctx, inv) case "pi": return DiscoverPiModels(ctx, inv) - case "antigravity": - return DiscoverAntigravityModels(ctx, inv) } return ModelList{}, fmt.Errorf("model discovery is unsupported for Runtime %q", kind) } diff --git a/apps/computer/local-daemon/internal/provider/protocol_probe.go b/apps/computer/local-daemon/internal/provider/protocol_probe.go index 5a9594d09..25f867d2c 100644 --- a/apps/computer/local-daemon/internal/provider/protocol_probe.go +++ b/apps/computer/local-daemon/internal/provider/protocol_probe.go @@ -41,6 +41,21 @@ type probeOptions struct { tempBase string } +type probePreparationError struct { + err error +} + +func (e *probePreparationError) Error() string { + if e.err == nil { + return "Antigravity diagnostic environment could not be prepared" + } + return e.err.Error() +} + +func (e *probePreparationError) Unwrap() error { + return e.err +} + func probeRuntime(ctx context.Context, runtimeType, executable string, environment map[string]string, timeout time.Duration, options probeOptions) runtimeProbeOutcome { if runtimeType == "pi" { return probePiRuntime(ctx, executable, environment, timeout) @@ -53,10 +68,14 @@ func probeRuntime(ctx context.Context, runtimeType, executable string, environme return authentication } } - if err := probeRuntimeProtocol(ctx, runtimeType, executable, environment, timeout); err != nil { + if err := probeRuntimeProtocol(ctx, runtimeType, executable, environment, timeout, options.tempBase); err != nil { if ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { return runtimeProbeOutcome{Status: "error", Code: "RUNTIME_DIAGNOSTIC_FAILED", Message: "Runtime protocol handshake could not be completed within its deadline"} } + var prepErr *probePreparationError + if errors.As(err, &prepErr) { + return runtimeProbeOutcome{Status: "error", Code: "RUNTIME_DIAGNOSTIC_FAILED", Message: "Antigravity diagnostic environment could not be prepared"} + } return runtimeProbeOutcome{Status: "incompatible", Code: "RUNTIME_INCOMPATIBLE", Message: "Runtime protocol handshake failed"} } if !policy.authenticationBeforeProtocol && policy.authenticationProbe != nil { @@ -74,7 +93,7 @@ func codexProbeArgs() []string { return native.CodexAppServerArgs() } -func probeRuntimeProtocol(ctx context.Context, runtimeType, executable string, environment map[string]string, timeout time.Duration) error { +func probeRuntimeProtocol(ctx context.Context, runtimeType, executable string, environment map[string]string, timeout time.Duration, tempBase string) error { var args []string var payload string switch runtimeType { @@ -86,11 +105,12 @@ func probeRuntimeProtocol(ctx context.Context, runtimeType, executable string, e payload = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"linger-computer-doctor","title":"Linger Computer Doctor","version":"1.0.0"},"capabilities":null}}` + "\n" case "antigravity": - probeArgs, release, err := native.PrepareAntigravityProtocolProbe() + probeArgs, releaseProbe, err := native.PrepareAntigravityProtocolProbe(tempBase) if err != nil { - return err + slog.Warn("runner.runtime_probe.prepare_failed", "runtime_type", runtimeType, "error", redact.Text(err.Error())) + return &probePreparationError{err: err} } - defer release() + defer releaseProbe() args = append([]string{"acp"}, probeArgs...) payload = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}` + "\n" case "claude": diff --git a/apps/computer/local-daemon/internal/provider/protocol_probe_test.go b/apps/computer/local-daemon/internal/provider/protocol_probe_test.go index fb38050e2..0b00be519 100644 --- a/apps/computer/local-daemon/internal/provider/protocol_probe_test.go +++ b/apps/computer/local-daemon/internal/provider/protocol_probe_test.go @@ -1,11 +1,13 @@ package provider import ( + "bytes" "context" "encoding/json" "errors" "fmt" "io" + "log/slog" "os" "path/filepath" "runtime" @@ -13,10 +15,17 @@ import ( "testing" "time" + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs" "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider/native" + localworkspace "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/workspace" ) -const testAgyProtocolHelperEnv = "LINGER_TEST_AGY_PROTOCOL_HELPER" +const ( + testAgyProtocolHelperEnv = "LINGER_TEST_AGY_PROTOCOL_HELPER" + testAgyProtocolModeEnv = "LINGER_TEST_AGY_PROTOCOL_MODE" + testAgyProtocolTraceEnv = "LINGER_TEST_AGY_PROTOCOL_TRACE" + testAgyPruneBaseEnv = "LINGER_TEST_AGY_PRUNE_BASE" +) func init() { metaPath := os.Getenv(testAgyProtocolHelperEnv) @@ -26,7 +35,20 @@ func init() { os.Exit(runAgyProtocolHelper(metaPath, os.Args[1:])) } +func captureProbeLog(t *testing.T) *bytes.Buffer { + t.Helper() + var output bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&output, nil))) + t.Cleanup(func() { slog.SetDefault(previous) }) + return &output +} + func runAgyProtocolHelper(metaPath string, args []string) int { + if len(args) == 1 && args[0] == "--version" { + fmt.Println("agy 1.5.12") + return 0 + } if len(args) == 0 || args[0] != "acp" { return 2 } @@ -54,19 +76,115 @@ func runAgyProtocolHelper(metaPath string, args []string) int { appDataEntries = append(appDataEntries, entry.Name()) } } + cwd, _ := os.Getwd() + privateOK := privatefs.CheckPath(geminiDir, "directory", true) == nil + pruneRemoved := 0 + pruneErrText := "" + if pruneBase := os.Getenv(testAgyPruneBaseEnv); pruneBase != "" { + removed, _, err := localworkspace.PruneOperationTemps(pruneBase, nil) + pruneRemoved = removed + if err != nil { + pruneErrText = err.Error() + } + } meta, _ := json.Marshal(map[string]any{ "geminiDir": geminiDir, "logFile": logFile, + "cwd": cwd, "appDataEntries": appDataEntries, + "privateCheckOK": privateOK, + "pruneRemoved": pruneRemoved, + "pruneError": pruneErrText, }) _ = os.WriteFile(metaPath, meta, 0o600) + if tracePath := os.Getenv(testAgyProtocolTraceEnv); tracePath != "" { + if file, err := os.OpenFile(tracePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); err == nil { + _, _ = file.Write(append(meta, '\n')) + _ = file.Close() + } + } + mode := os.Getenv(testAgyProtocolModeEnv) + if mode == "exit-error" { + fmt.Fprintln(os.Stderr, "simulated protocol handshake exit failure") + return 2 + } decoder := json.NewDecoder(os.Stdin) - var request map[string]any - if decoder.Decode(&request) != nil { - return 4 + handled := 0 + for { + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + } + err := decoder.Decode(&request) + if errors.Is(err, io.EOF) { + if handled == 0 { + return 4 + } + return 0 + } + if err != nil { + return 4 + } + handled++ + switch request.Method { + case "initialize": + protocolVersion := 1 + if mode == "wrong-version" { + protocolVersion = 99 + } + response, _ := json.Marshal(map[string]any{ + "jsonrpc": "2.0", + "id": request.ID, + "result": map[string]any{"protocolVersion": protocolVersion}, + }) + fmt.Println(string(response)) + case "session/new": + if mode == "auth-error" { + fmt.Fprintln(os.Stderr, "simulated session/new error") + return 5 + } + if mode == "auth-required" { + response, _ := json.Marshal(map[string]any{ + "jsonrpc": "2.0", + "id": request.ID, + "error": map[string]any{"code": -32000, "message": "Authentication required"}, + }) + fmt.Println(string(response)) + continue + } + response, _ := json.Marshal(map[string]any{ + "jsonrpc": "2.0", + "id": request.ID, + "result": map[string]any{ + "sessionId": "probe-session", + "models": map[string]any{ + "availableModels": []any{ + map[string]any{"modelId": "gemini-pro-low", "name": "Gemini Pro (Low)"}, + }, + "currentModelId": "gemini-pro-low", + }, + "configOptions": []any{ + map[string]any{ + "id": "model", + "category": "model", + "currentValue": "gemini-pro", + "options": []any{ + map[string]any{"value": "gemini-pro", "name": "Gemini Pro"}, + }, + }, + }, + }, + }) + fmt.Println(string(response)) + default: + response, _ := json.Marshal(map[string]any{ + "jsonrpc": "2.0", + "id": request.ID, + "error": map[string]any{"code": -32601, "message": "method not found"}, + }) + fmt.Println(string(response)) + } } - fmt.Println(`{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1}}`) - return 0 } func TestAntigravityProtocolProbeIsolatesGeminiDirAndLogFile(t *testing.T) { @@ -87,7 +205,7 @@ func TestAntigravityProtocolProbeIsolatesGeminiDirAndLogFile(t *testing.T) { "HOME": home, testAgyProtocolHelperEnv: metaFile, } - if err := probeRuntimeProtocol(context.Background(), "antigravity", executable, env, 5*time.Second); err != nil { + if err := probeRuntimeProtocol(context.Background(), "antigravity", executable, env, 5*time.Second, ""); err != nil { t.Fatalf("antigravity protocol probe failed: %v", err) } rawMeta, err := os.ReadFile(metaFile) @@ -116,6 +234,139 @@ func TestAntigravityProtocolProbeIsolatesGeminiDirAndLogFile(t *testing.T) { } } +func isPathWithin(base, target string) bool { + rel, err := filepath.Rel(base, target) + return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) +} + +func TestAntigravityProtocolProbeUsesTempBaseAndProtectsActiveDir(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + home := filepath.Join(root, "home") + tempBase := filepath.Join(root, "state", "operation-tmp") + metaFile := filepath.Join(root, "protocol-meta.json") + badTemp := filepath.Join(root, "not-a-dir") + if err := os.MkdirAll(home, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(badTemp, []byte("not a directory"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("TMPDIR", badTemp) + t.Setenv("TEMP", badTemp) + t.Setenv("TMP", badTemp) + + env := map[string]string{ + "HOME": home, + testAgyProtocolHelperEnv: metaFile, + testAgyPruneBaseEnv: tempBase, + } + if err := probeRuntimeProtocol(context.Background(), "antigravity", executable, env, 5*time.Second, tempBase); err != nil { + t.Fatalf("antigravity protocol probe in tempBase failed: %v", err) + } + rawMeta, err := os.ReadFile(metaFile) + if err != nil { + t.Fatal(err) + } + var meta struct { + GeminiDir string `json:"geminiDir"` + LogFile string `json:"logFile"` + PrivateCheckOK bool `json:"privateCheckOK"` + PruneRemoved int `json:"pruneRemoved"` + PruneError string `json:"pruneError"` + } + if err := json.Unmarshal(rawMeta, &meta); err != nil { + t.Fatal(err) + } + if !isPathWithin(tempBase, meta.GeminiDir) || !isPathWithin(tempBase, meta.LogFile) { + t.Fatalf("expected probe paths inside tempBase %q, got %+v", tempBase, meta) + } + if !meta.PrivateCheckOK { + t.Fatalf("active probe gemini dir failed privatefs.CheckPath: %+v", meta) + } + if meta.PruneRemoved != 0 || meta.PruneError != "" { + t.Fatalf("concurrent PruneOperationTemps touched active probe dir: %+v", meta) + } + entries, err := os.ReadDir(tempBase) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("tempBase was not cleaned up after probe: %v", entries) + } +} + +func TestAntigravityProtocolProbePreparationFailureReportsDiagnosticFailed(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + fileBase := filepath.Join(root, "blocked-temp-base") + if err := os.WriteFile(fileBase, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + logged := captureProbeLog(t) + outcome := probeRuntime( + context.Background(), + "antigravity", + executable, + map[string]string{"HOME": root, testAgyProtocolHelperEnv: filepath.Join(root, "meta.json")}, + 5*time.Second, + probeOptions{tempBase: fileBase}, + ) + if outcome.Status != "error" || outcome.Code != "RUNTIME_DIAGNOSTIC_FAILED" { + t.Fatalf("outcome = %+v, want error RUNTIME_DIAGNOSTIC_FAILED (not RUNTIME_INCOMPATIBLE)", outcome) + } + if strings.Contains(outcome.Message, fileBase) { + t.Fatalf("outcome.Message leaked local path %q: %q", fileBase, outcome.Message) + } + logOutput := logged.String() + for _, want := range []string{"runner.runtime_probe.prepare_failed", "runtime_type=antigravity"} { + if !strings.Contains(logOutput, want) { + t.Fatalf("log lacks %q: %s", want, logOutput) + } + } +} + +func TestAntigravityProtocolHandshakeMismatchStillReportsIncompatible(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + for _, mode := range []string{"exit-error", "wrong-version"} { + t.Run(mode, func(t *testing.T) { + root := t.TempDir() + tempBase := filepath.Join(root, "state", "operation-tmp") + outcome := probeRuntime( + context.Background(), + "antigravity", + executable, + map[string]string{ + "HOME": root, + testAgyProtocolHelperEnv: filepath.Join(root, "meta.json"), + testAgyProtocolModeEnv: mode, + }, + 5*time.Second, + probeOptions{tempBase: tempBase}, + ) + if outcome.Status != "incompatible" || outcome.Code != "RUNTIME_INCOMPATIBLE" || outcome.Message != "Runtime protocol handshake failed" { + t.Fatalf("mode %q outcome = %+v, want incompatible RUNTIME_INCOMPATIBLE", mode, outcome) + } + entries, err := os.ReadDir(tempBase) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("tempBase leaked entries after failed handshake: %v", entries) + } + }) + } +} + func TestProtocolProbeWaitsForInitializeBeforeClosingInput(t *testing.T) { executable, err := os.Executable() if err != nil { @@ -226,7 +477,7 @@ exit 0 if _, mutated := callerEnv["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"]; mutated { t.Fatal("probeClaudeAuthStatus mutated caller environment map") } - if err := probeRuntimeProtocol(context.Background(), "claude", claude, callerEnv, 5*time.Second); err != nil { + if err := probeRuntimeProtocol(context.Background(), "claude", claude, callerEnv, 5*time.Second, ""); err != nil { t.Fatalf("probeRuntimeProtocol(claude) = %v, want nil", err) } if _, mutated := callerEnv["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"]; mutated { @@ -241,7 +492,7 @@ exit 0 if outcome := probeClaudeAuthStatus(context.Background(), claude, overrideEnv, 5*time.Second); outcome.Status != "ready" { t.Fatalf("probeClaudeAuthStatus(override) = %+v, want ready", outcome) } - if err := probeRuntimeProtocol(context.Background(), "claude", claude, overrideEnv, 5*time.Second); err != nil { + if err := probeRuntimeProtocol(context.Background(), "claude", claude, overrideEnv, 5*time.Second, ""); err != nil { t.Fatalf("probeRuntimeProtocol(claude, override) = %v, want nil", err) } } diff --git a/apps/computer/local-daemon/internal/provider/protocol_probe_unix_test.go b/apps/computer/local-daemon/internal/provider/protocol_probe_unix_test.go index 7a36fb3d5..dfb488c3a 100644 --- a/apps/computer/local-daemon/internal/provider/protocol_probe_unix_test.go +++ b/apps/computer/local-daemon/internal/provider/protocol_probe_unix_test.go @@ -3,10 +3,8 @@ package provider import ( - "bytes" "context" "errors" - "log/slog" "os" "path/filepath" "strings" @@ -23,15 +21,6 @@ func writeProbeScript(t *testing.T, body string) string { return path } -func captureProbeLog(t *testing.T) *bytes.Buffer { - t.Helper() - var output bytes.Buffer - previous := slog.Default() - slog.SetDefault(slog.New(slog.NewTextHandler(&output, nil))) - t.Cleanup(func() { slog.SetDefault(previous) }) - return &output -} - func TestProtocolProbeAcceptsAnAnswerFollowedByAFailedExit(t *testing.T) { logged := captureProbeLog(t) script := writeProbeScript(t, `read request @@ -41,7 +30,7 @@ echo 'shutting down after input closed' >&2 exit 1 `) environment := map[string]string{"PATH": "/usr/bin:/bin", "HOME": t.TempDir()} - if err := probeRuntimeProtocol(context.Background(), "codex", script, environment, 5*time.Second); err != nil { + if err := probeRuntimeProtocol(context.Background(), "codex", script, environment, 5*time.Second, ""); err != nil { t.Fatalf("an answered handshake failed: %v", err) } if !strings.Contains(logged.String(), "runner.runtime_probe.exit_after_handshake") || !strings.Contains(logged.String(), "exit_code=1") { @@ -55,7 +44,7 @@ func TestProtocolProbeLogsWhyAnUnansweredHandshakeFailed(t *testing.T) { exit 2 `) environment := map[string]string{"PATH": "/usr/bin:/bin", "HOME": t.TempDir()} - if err := probeRuntimeProtocol(context.Background(), "codex", script, environment, 5*time.Second); err == nil { + if err := probeRuntimeProtocol(context.Background(), "codex", script, environment, 5*time.Second, ""); err == nil { t.Fatal("an unanswered handshake passed") } output := logged.String() diff --git a/apps/computer/local-daemon/internal/provider/protocol_probe_windows_test.go b/apps/computer/local-daemon/internal/provider/protocol_probe_windows_test.go new file mode 100644 index 000000000..6c2c8fd00 --- /dev/null +++ b/apps/computer/local-daemon/internal/provider/protocol_probe_windows_test.go @@ -0,0 +1,115 @@ +//go:build windows + +package provider + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/sys/windows" + + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs" +) + +func TestWindowsAntigravityProbeUsesPrivateTempBase(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + sid, err := privatefs.CurrentSID() + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + home := filepath.Join(root, "home") + badTemp := filepath.Join(root, "bad-temp") + blockedTemp := filepath.Join(root, "blocked-temp") + privateBase := filepath.Join(root, "state", "operation-tmp") + metaFile := filepath.Join(root, "meta.json") + for _, dir := range []string{home, badTemp} { + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(blockedTemp, []byte("not-a-directory"), 0o600); err != nil { + t.Fatal(err) + } + + // Grant LOCAL SERVICE (S-1-5-19) full access so badTemp is broadly + // accessible and fails target-level owner-only checks. + const localServiceSID = "S-1-5-19" + sd, err := windows.SecurityDescriptorFromString("O:" + sid.String() + "D:P(A;OICI;FA;;;" + sid.String() + ")(A;OICI;FA;;;SY)(A;OICI;FA;;;" + localServiceSID + ")") + if err != nil { + t.Fatal(err) + } + acl, _, err := sd.DACL() + if err != nil { + t.Fatal(err) + } + if err := windows.SetNamedSecurityInfo(badTemp, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil); err != nil { + t.Fatal(err) + } + if err := privatefs.CheckPath(badTemp, "directory", true); err == nil || !strings.Contains(err.Error(), localServiceSID) { + t.Fatalf("expected target-level private check to reject %s on badTemp, got %v", localServiceSID, err) + } + + env := map[string]string{ + "HOME": home, + "USERPROFILE": home, + testAgyProtocolHelperEnv: metaFile, + } + if systemRoot := os.Getenv("SystemRoot"); systemRoot != "" { + env["SystemRoot"] = systemRoot + } + + // Empty TempBase falls back to %TEMP%; a local preparation failure must + // report RUNTIME_DIAGNOSTIC_FAILED rather than RUNTIME_INCOMPATIBLE. + t.Setenv("TEMP", blockedTemp) + t.Setenv("TMP", blockedTemp) + logged := captureProbeLog(t) + fallbackOutcome := probeRuntime(context.Background(), "antigravity", executable, env, 5*time.Second, probeOptions{}) + if fallbackOutcome.Status != "error" || fallbackOutcome.Code != "RUNTIME_DIAGNOSTIC_FAILED" { + t.Fatalf("fallback outcome = %+v, want error RUNTIME_DIAGNOSTIC_FAILED (not RUNTIME_INCOMPATIBLE)", fallbackOutcome) + } + if strings.Contains(fallbackOutcome.Message, blockedTemp) { + t.Fatalf("fallback outcome.Message leaked local path: %q", fallbackOutcome.Message) + } + if !strings.Contains(logged.String(), "runner.runtime_probe.prepare_failed") { + t.Fatalf("expected runner.runtime_probe.prepare_failed in log, got: %s", logged.String()) + } + + // With a clean private TempBase, the probe succeeds and never touches a + // broadly accessible %TEMP%. + t.Setenv("TEMP", badTemp) + t.Setenv("TMP", badTemp) + privateOutcome := probeRuntime(context.Background(), "antigravity", executable, env, 5*time.Second, probeOptions{tempBase: privateBase}) + if privateOutcome.Status != "ready" { + t.Fatalf("private TempBase outcome = %+v, want ready", privateOutcome) + } + rawMeta, err := os.ReadFile(metaFile) + if err != nil { + t.Fatal(err) + } + var meta struct { + GeminiDir string `json:"geminiDir"` + LogFile string `json:"logFile"` + PrivateCheckOK bool `json:"privateCheckOK"` + } + if err := json.Unmarshal(rawMeta, &meta); err != nil { + t.Fatal(err) + } + if !isPathWithin(privateBase, meta.GeminiDir) || !isPathWithin(privateBase, meta.LogFile) || !meta.PrivateCheckOK { + t.Fatalf("probe paths = %+v, want private paths under %q", meta, privateBase) + } + if entries, err := os.ReadDir(privateBase); err != nil || len(entries) != 0 { + t.Fatalf("privateBase was not cleaned up: entries=%v err=%v", entries, err) + } + if entries, err := os.ReadDir(badTemp); err != nil || len(entries) != 0 { + t.Fatalf("badTemp was touched during private TempBase probe: entries=%v err=%v", entries, err) + } +} diff --git a/apps/computer/local-daemon/internal/provider/runtime_monitor.go b/apps/computer/local-daemon/internal/provider/runtime_monitor.go index 7b104275c..36f70dc65 100644 --- a/apps/computer/local-daemon/internal/provider/runtime_monitor.go +++ b/apps/computer/local-daemon/internal/provider/runtime_monitor.go @@ -351,7 +351,7 @@ func refreshRuntimeAuthentication(ctx context.Context, current DiscoveryResult, if (diagnostic.Type == "pi" || diagnostic.Type == "antigravity") && diagnostic.Status == "ready" { previousModels := diagnostic.Models catalogCtx, cancel := context.WithTimeout(ctx, boundedAuthTimeout(options.Timeout)) - diagnostic.Models, diagnostic.ModelCatalogError = probedRuntimeModels(catalogCtx, diagnostic.Type, diagnostic.ExecutablePath, environment, outcome) + diagnostic.Models, diagnostic.ModelCatalogError = probedRuntimeModels(catalogCtx, diagnostic.Type, diagnostic.ExecutablePath, environment, outcome, options.TempBase) if diagnostic.ModelCatalogError == "" { carryOrResolveModelLinks(catalogCtx, diagnostic.Type, environment, previousModels, diagnostic.Models) } diff --git a/apps/computer/local-daemon/internal/workspace/operation_temp.go b/apps/computer/local-daemon/internal/workspace/operation_temp.go index 16be38da1..ed581061a 100644 --- a/apps/computer/local-daemon/internal/workspace/operation_temp.go +++ b/apps/computer/local-daemon/internal/workspace/operation_temp.go @@ -27,6 +27,8 @@ func PruneOperationTemps(base string, logger *slog.Logger) (int, int64, error) { return removed, bytesFreed, nil } +// PrepareOperationTemp allocates a lock-tracked, owner-only temporary directory +// under base. func PrepareOperationTemp(base string) (*OperationTemp, error) { if !filepath.IsAbs(base) { return nil, fmt.Errorf("Operation temp base must be absolute") diff --git a/apps/computer/local-daemon/internal/workspace/operation_temp_test.go b/apps/computer/local-daemon/internal/workspace/operation_temp_test.go index b0af07a57..39521388c 100644 --- a/apps/computer/local-daemon/internal/workspace/operation_temp_test.go +++ b/apps/computer/local-daemon/internal/workspace/operation_temp_test.go @@ -2,7 +2,11 @@ package workspace import ( "os" + "path/filepath" + "runtime" "testing" + + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/platform/privatefs" ) func TestOperationTempLeasesKeepSweepLockUntilLastRelease(t *testing.T) { @@ -43,3 +47,41 @@ func TestOperationTempLeasesKeepSweepLockUntilLastRelease(t *testing.T) { t.Fatal("a released directory acquired a new lease") } } + +func TestPrepareOperationTempProtectsBaseAndDirectoryWithPrivateFS(t *testing.T) { + root := t.TempDir() + base := filepath.Join(root, "operation-tmp") + if err := os.MkdirAll(base, 0o755); err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" { + if err := os.Chmod(base, 0o755); err != nil { + t.Fatal(err) + } + } + + temp, err := PrepareOperationTemp(base) + if err != nil { + t.Fatalf("PrepareOperationTemp(%q): %v", base, err) + } + defer func() { + if err := temp.Close(); err != nil { + t.Fatalf("Close(): %v", err) + } + }() + + if err := privatefs.CheckPath(base, "directory", true); err != nil { + t.Fatalf("base failed privatefs check: %v", err) + } + if err := privatefs.CheckPath(temp.Path, "directory", true); err != nil { + t.Fatalf("operation temp dir failed privatefs check: %v", err) + } + + fileBase := filepath.Join(root, "not-a-directory") + if err := os.WriteFile(fileBase, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := PrepareOperationTemp(fileBase); err == nil { + t.Fatal("PrepareOperationTemp succeeded on a regular file base") + } +}