Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(opencode): let model listing fall back after a timeout (#11088)

Danila Katalshov674f912a6865
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index a72e12bcc0..a9260f7dc5 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -276,7 +276,7 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C
})
case "opencode":
return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {
- return discovered(discoverOpenCodeModels(ctx, runtimeCmd))
+ return discoverOpenCodeModels(ctx, runtimeCmd)
})
case "codearts":
return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {
@@ -816,20 +816,23 @@ func isOpenAIReasoningSeriesID(id string) bool {
// discoverOpenCodeModels reads model metadata using the installed CLI's contract:
// the model API on 2.x, and verbose model rows on 1.x. Plain IDs remain a
// fallback when metadata discovery fails; no reasoning levels are invented.
-func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {
+func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {
+ // Newer opencode (1.15+) syncs its hosted free-model catalog over the
+ // network on `opencode models`, which can take ~6s; the previous 5s cap
+ // timed out and returned an empty list, so the runtime showed online but
+ // the model picker was empty. See multica-ai/multica#3627.
+ return discoverOpenCodeModelsWithin(ctx, runtimeCmd, 15*time.Second)
+}
+
+func discoverOpenCodeModelsWithin(ctx context.Context, runtimeCmd Command, attemptTimeout time.Duration) (Catalog, error) {
if runtimeCmd.Path == "" {
runtimeCmd.Path = "opencode"
}
if _, err := exec.LookPath(runtimeCmd.Path); err != nil {
- return []Model{}, nil
+ return Catalog{Models: []Model{}}, nil
}
- // Newer opencode (1.15+) syncs its hosted free-model catalog over the
- // network on `opencode models`, which can take ~6s; the previous 5s cap
- // timed out and returned an empty list, so the runtime showed online but
- // the model picker was empty. See multica-ai/multica#3627.
- runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
- defer cancel()
- version, _ := detectCLIVersion(runCtx, runtimeCmd)
+ metadataCtx, cancelMetadata := context.WithTimeout(ctx, attemptTimeout)
+ version, _ := detectCLIVersion(metadataCtx, runtimeCmd)
parsed, versionErr := parseSemver(version)
var models []Model
if versionErr == nil && parsed.Major >= 2 {
@@ -843,29 +846,38 @@ func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, e
if server == "" && !standalone {
args = append(args, "--standalone")
}
- cmd := runtimeCmd.exec(runCtx, args...)
+ cmd := runtimeCmd.exec(metadataCtx, args...)
hideAgentWindow(cmd)
if out, err := outputOwned(cmd, runtimeCmd.logger); err == nil {
models = parseOpenCodeV2Models(out)
}
}
} else {
- cmd := runtimeCmd.exec(runCtx, "models", "--verbose")
+ cmd := runtimeCmd.exec(metadataCtx, "models", "--verbose")
hideAgentWindow(cmd)
// A stale config can produce a non-zero exit with a usable catalog.
out, _ := outputOwned(cmd, runtimeCmd.logger)
models = parseOpenCodeModels(string(out))
}
- if len(models) == 0 {
- cmd := runtimeCmd.exec(runCtx, "models")
- hideAgentWindow(cmd)
- out, _ := outputOwned(cmd, runtimeCmd.logger)
- models = parseOpenCodeModels(string(out))
+ metadataTimedOut := metadataCtx.Err() == context.DeadlineExceeded
+ cancelMetadata()
+ if len(models) > 0 {
+ return Catalog{Models: models}, nil
}
+
+ // A timed-out metadata probe must not expire the plain listing.
+ fallbackCtx, cancelFallback := context.WithTimeout(ctx, attemptTimeout)
+ defer cancelFallback()
+ cmd := runtimeCmd.exec(fallbackCtx, "models")
+ hideAgentWindow(cmd)
+ out, _ := outputOwned(cmd, runtimeCmd.logger)
+ models = parseOpenCodeModels(string(out))
if len(models) == 0 {
- return []Model{}, nil
+ return Catalog{Models: []Model{}}, nil
}
- return models, nil
+ // After a timeout, the plain IDs can populate the picker but cannot
+ // validate saved variants or replace an existing complete catalog.
+ return Catalog{Models: models, Fallback: metadataTimedOut}, nil
}
// OpenCode 2.x GET /api/model returns Location.response(Model.Info[]): an
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index 1344764722..23fcd76594 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -2,7 +2,9 @@ package agent
import (
"context"
+ "errors"
"fmt"
+ "os"
"path/filepath"
"reflect"
"runtime"
@@ -820,9 +822,13 @@ exit 1
`
writeTestExecutable(t, fake, []byte(script))
- models, err := discoverOpenCodeModels(context.Background(), Command{Path: fake})
+ catalog, err := ListModels(t.Context(), "opencode", Command{Path: fake})
if err != nil {
- t.Fatalf("discoverOpenCodeModels: %v", err)
+ t.Fatalf("ListModels: %v", err)
+ }
+ models := catalog.Models
+ if !catalog.Verified() {
+ t.Fatalf("plain listing after a non-timeout verbose failure should remain verified: %+v", catalog)
}
if len(models) != 1 {
t.Fatalf("expected fallback non-verbose model, got %d: %+v", len(models), models)
@@ -832,6 +838,54 @@ exit 1
}
}
+func TestDiscoverOpenCodeModelsFallsBackAfterMetadataTimeout(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fake binary requires a POSIX shell")
+ }
+
+ for _, tc := range []struct {
+ version string
+ probe string
+ }{
+ {version: "1.18.31", probe: "models --verbose"},
+ {version: "2.0.26", probe: "api GET"},
+ } {
+ t.Run(tc.version, func(t *testing.T) {
+ dir := t.TempDir()
+ marker := filepath.Join(dir, "metadata-called")
+ t.Setenv("MULTICA_TEST_OPENCODE_METADATA_MARKER", marker)
+ fake := filepath.Join(dir, "opencode")
+ writeTestExecutable(t, fake, []byte(fmt.Sprintf(`#!/bin/sh
+case "$1 ${2:-}" in
+ '--version ') echo '%s' ;;
+ '%s') : > "$MULTICA_TEST_OPENCODE_METADATA_MARKER"; exec sleep 60 ;;
+ 'models ') echo 'openai/gpt-4o' ;;
+ *) exit 2 ;;
+esac
+`, tc.version, tc.probe)))
+ catalog, err := discoverOpenCodeModelsWithin(t.Context(), Command{Path: fake}, 2*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(marker); err != nil {
+ t.Fatalf("metadata probe was not invoked: %v", err)
+ }
+ if models := catalog.Models; len(models) != 1 || models[0].ID != "openai/gpt-4o" || models[0].Thinking != nil {
+ t.Fatalf("plain fallback after a timed-out metadata probe: got %+v", models)
+ }
+ if !catalog.Fallback {
+ t.Fatalf("catalog without capability metadata must be a fallback: %+v", catalog)
+ }
+ check, err := CheckThinkingLevelWith(func() (Catalog, error) {
+ return catalog, nil
+ }, "opencode", "openai/gpt-4o", "high")
+ if !errors.Is(err, errUnverifiedCatalog) {
+ t.Fatalf("saved variant should be left for the CLI to validate: check=%+v, err=%v", check, err)
+ }
+ })
+ }
+}
+
// TestCachedDiscoveryDoesNotCacheEmpty verifies that an empty discovery result
// is not cached, so a transient failure (e.g. a `pi --list-models` timeout)
// doesn't keep the model picker blank for the full TTL. A non-empty result is
@@ -1225,10 +1279,11 @@ func TestDiscoverOpenCodeModelsFallsBackOnVerboseNoise(t *testing.T) {
fakePath := filepath.Join(t.TempDir(), "opencode")
writeTestExecutable(t, fakePath, []byte(script))
- models, err := discoverOpenCodeModels(context.Background(), Command{Path: fakePath})
+ catalog, err := ListModels(t.Context(), "opencode", Command{Path: fakePath})
if err != nil {
- t.Fatalf("discoverOpenCodeModels: %v", err)
+ t.Fatalf("ListModels: %v", err)
}
+ models := catalog.Models
if len(models) != 1 || models[0].ID != "openai/gpt-4o" {
t.Fatalf("expected fallback to plain `opencode models` to yield [openai/gpt-4o], got %+v", models)
}
diff --git a/server/pkg/agent/opencode_models_test.go b/server/pkg/agent/opencode_models_test.go
index b8c1505aac..2aa3837f01 100644
--- a/server/pkg/agent/opencode_models_test.go
+++ b/server/pkg/agent/opencode_models_test.go
@@ -42,10 +42,11 @@ JSON
*) exit 1 ;;
esac
`, fixture)))
- models, err := discoverOpenCodeModels(context.Background(), Command{Path: fake})
+ catalog, err := ListModels(t.Context(), "opencode", Command{Path: fake})
if err != nil {
t.Fatal(err)
}
+ models := catalog.Models
if len(models) != 2 {
t.Fatalf("models = %+v", models)
}
@@ -176,7 +177,8 @@ case "$1" in
*) exit 1 ;;
esac
`, tc.version, tc.api, tc.apiExit, tc.verbose, tc.verbose)))
- models, err := discoverOpenCodeModels(context.Background(), Command{Path: fake})
+ catalog, err := ListModels(t.Context(), "opencode", Command{Path: fake})
+ models := catalog.Models
if err != nil || len(models) != 1 || models[0].ID != "p/m" ||
(models[0].Thinking != nil) != tc.wantThinking {
t.Fatalf("models = %+v, err = %v", models, err)
@@ -214,7 +216,8 @@ printf '%s\n' "$@" > "$OPENCODE_TEST_TRACE"
echo '{"location":{"directory":"/unused"},"data":[{"providerID":"p","id":"m","variants":[{"id":"high"}]}]}'
`))
prefix := append([]string{"profile", "test"}, connection...)
- models, err := discoverOpenCodeModels(context.Background(), NewCommand(fake, prefix))
+ catalog, err := ListModels(t.Context(), "opencode", NewCommand(fake, prefix))
+ models := catalog.Models
if err != nil || len(models) != 1 || models[0].Thinking == nil {
t.Fatalf("profile discovery = %+v, %v", models, err)
}
@@ -259,9 +262,9 @@ exec sleep 30
ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
defer cancel()
start := time.Now()
- models, err := discoverOpenCodeModels(ctx, Command{Path: fake})
- if err != nil || len(models) != 0 {
- t.Fatalf("timed-out discovery = %+v, %v", models, err)
+ catalog, err := ListModels(ctx, "opencode", Command{Path: fake})
+ if err != nil || len(catalog.Models) != 0 {
+ t.Fatalf("timed-out discovery = %+v, %v", catalog, err)
}
if elapsed := time.Since(start); elapsed > 3*time.Second {
t.Fatalf("discovery exceeded caller deadline: %v", elapsed)
@@ -269,3 +272,27 @@ exec sleep 30
})
}
}
+
+func TestDiscoverOpenCodeModelsWithCanceledContext(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("POSIX shell fixture")
+ }
+ dir := t.TempDir()
+ marker := filepath.Join(dir, "started")
+ t.Setenv("OPENCODE_TEST_TRACE", marker)
+ fake := filepath.Join(dir, "opencode")
+ writeTestExecutable(t, fake, []byte(`#!/bin/sh
+: > "$OPENCODE_TEST_TRACE"
+echo 'p/m'
+`))
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+
+ catalog, err := ListModels(ctx, "opencode", Command{Path: fake})
+ if err != nil || len(catalog.Models) != 0 {
+ t.Fatalf("canceled discovery = %+v, %v", catalog, err)
+ }
+ if _, err := os.Stat(marker); !os.IsNotExist(err) {
+ t.Fatalf("canceled discovery started a subprocess or marker check failed: %v", err)
+ }
+}