Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(opencode): discover v2 model thinking variants (ZIC-351) (#9365)
ZIce4152fed89fc0
diff --git a/packages/views/agents/components/inspector/thinking-prop-row.test.tsx b/packages/views/agents/components/inspector/thinking-prop-row.test.tsxindex ce27003176..7f249386f5 100644--- a/packages/views/agents/components/inspector/thinking-prop-row.test.tsx+++ b/packages/views/agents/components/inspector/thinking-prop-row.test.tsx@@ -152,6 +152,30 @@ describe("ThinkingPropRow", () => {cleanup();});+ it("offers discovered OpenCode variants and emits the native token for saving", async () => {+ mockInitiateListModels.mockResolvedValue(listResult([{+ id: "opencode-go/deepseek-v4.1-flash",+ label: "opencode-go/deepseek-v4.1-flash",+ provider: "opencode-go",+ thinking: {+ supported_levels: [+ { value: "low", label: "Low" },+ { value: "high", label: "High" },+ { value: "fast-mode", label: "Fast Mode" },+ ],+ },+ }]));+ const { onChange } = renderRow({+ provider: "opencode",+ model: "opencode-go/deepseek-v4.1-flash",+ });++ await screen.findByText("Thinking");+ fireEvent.click(screen.getByRole("button"));+ fireEvent.click(await screen.findByText("Fast Mode"));+ expect(onChange).toHaveBeenCalledWith("fast-mode");+ });+it("hides the row when the active model has no thinking levels and nothing is persisted", async () => {mockInitiateListModels.mockResolvedValue(listResult([NO_THINKING_MODEL]));renderRow({ model: "gemini-2.5-pro", value: "" });diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex d058d5ffcc..c3246b3494 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -8,6 +8,7 @@ import ("fmt""io""log/slog"+ "net/url""os""os/exec""regexp"@@ -768,14 +769,9 @@ func isOpenAIReasoningSeriesID(id string) bool {// ── Dynamic discovery ──-// discoverOpenCodeModels runs `opencode models --verbose` and parses its-// output. The CLI prints `provider/model` rows, followed by JSON metadata-// when verbose mode is enabled; we emit IDs verbatim so what the user sees-// matches what `--model` accepts, and project any model `variants` into the-// thinking-level picker because OpenCode's `run --variant` flag is its-// provider-specific reasoning-effort surface.-// On any failure (CLI missing, parse error, timeout) we fall back to-// an empty list so the creatable UI still works.+// 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) {if runtimeCmd.Path == "" {runtimeCmd.Path = "opencode"@@ -789,20 +785,37 @@ func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, e// the model picker was empty. See multica-ai/multica#3627.runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := runtimeCmd.exec(runCtx, "models", "--verbose")- hideAgentWindow(cmd)- // Parse whatever the verbose command printed, even on a non-zero exit — a- // stale config entry can make `opencode models` exit non-zero while still- // listing the resolvable catalog (mirrors the pi path; see #3729/#3627).- out, _ := outputOwned(cmd, runtimeCmd.logger)- models := parseOpenCodeModels(string(out))+ version, _ := detectCLIVersion(runCtx, runtimeCmd)+ parsed, versionErr := parseSemver(version)+ var models []Model+ if versionErr == nil && parsed.Major >= 2 {+ // Use a private server so profile environment and cwd are inherited and+ // discovery does not start a resident service. An explicitly selected+ // server in the runtime prefix must still win.+ if directory, err := os.Getwd(); err == nil {+ query := url.Values{"location[directory]": {directory}}+ args := []string{"api", "GET", "/api/model?" + query.Encode()}+ server, standalone := opencodeConnectionFromArgs(runtimeCmd.Prefix)+ if server == "" && !standalone {+ args = append(args, "--standalone")+ }+ cmd := runtimeCmd.exec(runCtx, args...)+ hideAgentWindow(cmd)+ if out, err := outputOwned(cmd, runtimeCmd.logger); err == nil {+ models = parseOpenCodeV2Models(out)+ }+ }+ } else {+ cmd := runtimeCmd.exec(runCtx, "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 {- // Verbose yielded nothing usable (unsupported flag, error text, or an- // empty list). Retry the plain command, which omits the per-model JSON- // but still prints the IDs.- cmd = runtimeCmd.exec(runCtx, "models")+ cmd := runtimeCmd.exec(runCtx, "models")hideAgentWindow(cmd)- out, _ = outputOwned(cmd, runtimeCmd.logger)+ out, _ := outputOwned(cmd, runtimeCmd.logger)models = parseOpenCodeModels(string(out))}if len(models) == 0 {@@ -811,6 +824,46 @@ func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, ereturn models, nil}+// OpenCode 2.x GET /api/model returns Location.response(Model.Info[]): an+// envelope, with variants represented as an array of {id, settings, body, ...}.+// Unlike 1.x, there is no reasoning boolean or advertised default variant.+func parseOpenCodeV2Models(output []byte) []Model {+ var response struct {+ Data []struct {+ ID string `json:"id"`+ ProviderID string `json:"providerID"`+ Variants []struct {+ ID string `json:"id"`+ } `json:"variants"`+ } `json:"data"`+ }+ if err := json.Unmarshal(output, &response); err != nil {+ return nil+ }+ var models []Model+ seen := make(map[string]bool)+ for _, entry := range response.Data {+ if entry.ID == "" || entry.ProviderID == "" {+ continue+ }+ id := entry.ProviderID + "/" + entry.ID+ if seen[id] {+ continue+ }+ seen[id] = true+ model := Model{ID: id, Label: id, Provider: entry.ProviderID}+ variants := make(map[string]opencodeModelVariant, len(entry.Variants))+ for _, variant := range entry.Variants {+ variants[variant.ID] = opencodeModelVariant{}+ }+ if levels := openCodeThinkingLevelsFromVariants(variants); len(levels) > 0 {+ model.Thinking = &ModelThinking{SupportedLevels: levels}+ }+ models = append(models, model)+ }+ return models+}+// parseOpenCodeModels accepts the `opencode models` text output and// extracts IDs. Non-verbose output is one `provider/model` row per line.// Verbose output appends a pretty-printed JSON object after each ID; whendiff --git a/server/pkg/agent/opencode_models_test.go b/server/pkg/agent/opencode_models_test.gonew file mode 100644index 0000000000..b8c1505aac--- /dev/null+++ b/server/pkg/agent/opencode_models_test.go@@ -0,0 +1,271 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"+ "net/url"+ "os"+ "path/filepath"+ "reflect"+ "runtime"+ "strings"+ "testing"+ "time"+)++func TestDiscoverOpenCodeV2Models(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX shell fixture")+ }+ // Schema-shaped fixture for OpenCode 2.0.32 (843a6c514e60):+ // packages/schema/src/model.ts and Location.response in location.ts.+ fixture, err := os.ReadFile("testdata/opencode_v2_models.json")+ if err != nil {+ t.Fatal(err)+ }+ fake := filepath.Join(t.TempDir(), "opencode")+ writeTestExecutable(t, fake, []byte(fmt.Sprintf(`#!/bin/sh+case "$1" in+ --version) echo 'opencode v2.0.32' ;;+ api) cat <<'JSON'+%s+JSON+ ;;+ models)+ if [ "$2" = "--verbose" ]; then+ echo 'Unrecognized flag: --verbose in command opencode models' >&2+ exit 1+ fi+ printf 'opencode-go/deepseek-v4.1-flash\nopencode-go/plain\n'+ ;;+ *) exit 1 ;;+esac+`, fixture)))+ models, err := discoverOpenCodeModels(context.Background(), Command{Path: fake})+ if err != nil {+ t.Fatal(err)+ }+ if len(models) != 2 {+ t.Fatalf("models = %+v", models)+ }+ if models[0].Thinking == nil {+ t.Fatal("structured discovery lost reasoning variants")+ }+ if models[1].Thinking != nil {+ t.Fatalf("plain model acquired thinking: %+v", models[1])+ }+}++func TestParseOpenCodeV2Models(t *testing.T) {+ fixture, err := os.ReadFile("testdata/opencode_v2_models.json")+ if err != nil {+ t.Fatal(err)+ }+ models := parseOpenCodeV2Models(fixture)+ want := []Model{+ {ID: "opencode-go/deepseek-v4.1-flash", Label: "opencode-go/deepseek-v4.1-flash", Provider: "opencode-go",+ Thinking: &ModelThinking{SupportedLevels: []ThinkingLevel{+ {Value: "low", Label: "Low"}, {Value: "high", Label: "High"}, {Value: "fast-mode", Label: "Fast Mode"},+ }}},+ {ID: "opencode-go/plain", Label: "opencode-go/plain", Provider: "opencode-go"},+ }+ if !reflect.DeepEqual(models, want) {+ t.Fatalf("models = %#v, want %#v", models, want)+ }+ // No default is advertised by the API. Preserve runtime-native variant IDs+ // through the daemon/UI wire format and the existing v2 argument helper.+ raw, err := json.Marshal(models)+ if err != nil {+ t.Fatal(err)+ }+ var roundTrip []Model+ if err := json.Unmarshal(raw, &roundTrip); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(roundTrip, want) {+ t.Fatalf("catalog wire round trip = %+v", roundTrip)+ }+ for _, level := range roundTrip[0].Thinking.SupportedLevels {+ if !IsKnownThinkingValue("opencode", level.Value) {+ t.Fatalf("API would reject variant %q for persistence", level.Value)+ }+ valid, err := ValidateThinkingLevelWith(func() (Catalog, error) {+ return Catalog{Models: roundTrip}, nil+ }, "opencode", roundTrip[0].ID, level.Value)+ if err != nil || !valid {+ t.Fatalf("execution guard dropped variant %q: valid=%v, err=%v", level.Value, valid, err)+ }+ arg, ok := opencodeModelArg(roundTrip[0].ID, level.Value)+ if !ok || arg != roundTrip[0].ID+"#"+level.Value {+ t.Fatalf("variant %q did not reach model argument: %q", level.Value, arg)+ }+ }+}++func TestParseOpenCodeV2ModelsInvalidAndEmpty(t *testing.T) {+ for _, input := range []string{+ ``, `not json`, `{"data":`, `[]`, `{}`, `null`,+ `{"data":null}`, `{"data":[]}`, `{"error":"unavailable"}`,+ `{"data":[{"id":"missing-provider"},{"providerID":"missing-model"}]}`,+ `{"data":[{"id":"m","providerID":"p","variants":{"high":{}}}]}`,+ } {+ t.Run(input, func(t *testing.T) {+ if got := parseOpenCodeV2Models([]byte(input)); len(got) != 0 {+ t.Fatalf("invalid/empty response produced models: %+v", got)+ }+ })+ }+ models := parseOpenCodeV2Models([]byte(`{"data":[+ {"providerID":"p","id":"m","variants":[{"id":""},{"id":"custom"},{"id":"custom"}]},+ {"providerID":"p","id":"m","variants":[]},+ {"providerID":"p","id":"plain","variants":[{"id":""}]}+ ]}`))+ if len(models) != 2 || models[0].Thinking == nil ||+ !reflect.DeepEqual(models[0].Thinking.SupportedLevels, []ThinkingLevel{{Value: "custom", Label: "Custom"}}) ||+ models[1].Thinking != nil {+ t.Fatalf("duplicate/empty variants: %+v", models)+ }+}++func TestDiscoverOpenCodeModelContractsAndFallback(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX shell fixture")+ }+ for _, tc := range []struct {+ name, version, api, apiExit, verbose, wantCalls string+ wantThinking bool+ }{+ {"v1 metadata", "1.18.31", "", "1", "valid", "--version\nmodels --verbose\n", true},+ {"unknown version keeps v1", "nightly", "", "1", "valid", "--version\nmodels --verbose\n", true},+ {"version probe fails keeps v1", "", "", "1", "valid", "--version\nmodels --verbose\n", true},+ {"v1 partial output", "1.18.31", "", "1", "partial", "--version\nmodels --verbose\n", true},+ {"v2 malformed", "opencode v2.0.32", "{broken", "0", "", "--version\napi\nmodels\n", false},+ {"v2 empty", "opencode v2.0.32", `{"location":{"directory":"/tmp"},"data":[]}`, "0", "", "--version\napi\nmodels\n", false},+ {"v2 failure", "opencode v2.0.32", `{"data":[{"providerID":"p","id":"m","variants":[{"id":"high"}]}]}`, "1", "", "--version\napi\nmodels\n", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ dir := t.TempDir()+ trace := filepath.Join(dir, "trace")+ t.Setenv("OPENCODE_TEST_TRACE", trace)+ fake := filepath.Join(dir, "opencode")+ writeTestExecutable(t, fake, []byte(fmt.Sprintf(`#!/bin/sh+case "$1" in+ --version)+ echo '--version' >> "$OPENCODE_TEST_TRACE"+ version='%s'+ [ -n "$version" ] || exit 1+ echo "$version"+ ;;+ api)+ echo api >> "$OPENCODE_TEST_TRACE"+ echo '%s'+ exit %s+ ;;+ models)+ echo "$*" >> "$OPENCODE_TEST_TRACE"+ if [ "$2" = "--verbose" ]; then+ [ '%s' = '' ] && exit 1+ printf 'p/m\n{"reasoning":true,"variants":{"high":{}}}\n'+ [ '%s' = partial ] && exit 1+ else+ echo p/m+ fi+ exit 0+ ;;+ *) exit 1 ;;+esac+`, tc.version, tc.api, tc.apiExit, tc.verbose, tc.verbose)))+ models, err := discoverOpenCodeModels(context.Background(), Command{Path: fake})+ 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)+ }+ raw, err := os.ReadFile(trace)+ if err != nil || string(raw) != tc.wantCalls {+ t.Fatalf("calls = %q, want %q (err=%v)", raw, tc.wantCalls, err)+ }+ })+ }+}++func TestDiscoverOpenCodeV2ModelsPreservesProfileAndLocation(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX shell fixture")+ }+ for _, connection := range [][]string{nil, {"--server", "http://localhost:4567"}, {"--server=http://localhost:4567"}, {"--standalone"}} {+ t.Run(strings.Join(connection, " "), func(t *testing.T) {+ dir := t.TempDir()+ trace := filepath.Join(dir, "trace")+ t.Setenv("OPENCODE_TEST_TRACE", trace)+ t.Setenv("OPENCODE_TEST_PROFILE", "profile-environment")+ fake := filepath.Join(dir, "wrapper")+ writeTestExecutable(t, fake, []byte(`#!/bin/sh+[ "$1" = profile ] && [ "$2" = test ] || exit 1+shift 2+case "$1" in+ --server) shift 2 ;;+ --server=*|--standalone) shift ;;+esac+[ "$OPENCODE_TEST_PROFILE" = profile-environment ] || exit 1+if [ "$1" = "--version" ]; then echo 'opencode v2.0.32'; exit 0; fi+[ "$1" = api ] || exit 1+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))+ if err != nil || len(models) != 1 || models[0].Thinking == nil {+ t.Fatalf("profile discovery = %+v, %v", models, err)+ }+ raw, err := os.ReadFile(trace)+ if err != nil {+ t.Fatal(err)+ }+ args := strings.Split(strings.TrimSpace(string(raw)), "\n")+ cwd, err := os.Getwd()+ if err != nil {+ t.Fatal(err)+ }+ want := []string{"api", "GET", "/api/model?" + url.Values{"location[directory]": {cwd}}.Encode()}+ if len(connection) == 0 {+ want = append(want, "--standalone")+ }+ if !reflect.DeepEqual(args, want) {+ t.Fatalf("API args = %q, want %q", args, want)+ }+ if !reflect.DeepEqual(prefix, append([]string{"profile", "test"}, connection...)) {+ t.Fatal("discovery mutated runtime prefix")+ }+ })+ }+}++func TestDiscoverOpenCodeV2ModelsDeadline(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX shell fixture")+ }+ for _, hangAt := range []string{"version", "api"} {+ t.Run(hangAt, func(t *testing.T) {+ fake := filepath.Join(t.TempDir(), "opencode")+ writeTestExecutable(t, fake, []byte(fmt.Sprintf(`#!/bin/sh+if [ "$1" = "--version" ]; then+ [ '%s' = version ] && exec sleep 30+ echo 'opencode v2.0.32'+ exit 0+fi+exec sleep 30+`, hangAt)))+ 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)+ }+ if elapsed := time.Since(start); elapsed > 3*time.Second {+ t.Fatalf("discovery exceeded caller deadline: %v", elapsed)+ }+ })+ }+}diff --git a/server/pkg/agent/testdata/opencode_v2_models.json b/server/pkg/agent/testdata/opencode_v2_models.jsonnew file mode 100644index 0000000000..f1e7206bba--- /dev/null+++ b/server/pkg/agent/testdata/opencode_v2_models.json@@ -0,0 +1,78 @@+{+ "location": {+ "directory": "/workspace/project"+ },+ "data": [+ {+ "id": "deepseek-v4.1-flash",+ "modelID": "deepseek-v4.1-flash",+ "providerID": "opencode-go",+ "name": "deepseek-v4.1-flash",+ "capabilities": {+ "tools": true,+ "input": [+ "text"+ ],+ "output": [+ "text"+ ]+ },+ "variants": [+ {+ "id": "high",+ "body": {+ "reasoning_effort": "high"+ }+ },+ {+ "id": "low",+ "body": {+ "reasoning_effort": "low"+ }+ },+ {+ "id": "fast-mode",+ "settings": {+ "reasoningEffort": "low"+ }+ }+ ],+ "time": {+ "released": 0+ },+ "cost": [],+ "status": "active",+ "enabled": true,+ "limit": {+ "context": 200000,+ "output": 32000+ }+ },+ {+ "id": "plain",+ "modelID": "plain",+ "providerID": "opencode-go",+ "name": "plain",+ "capabilities": {+ "tools": true,+ "input": [+ "text"+ ],+ "output": [+ "text"+ ]+ },+ "variants": [],+ "time": {+ "released": 0+ },+ "cost": [],+ "status": "active",+ "enabled": true,+ "limit": {+ "context": 200000,+ "output": 32000+ }+ }+ ]+}