Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9141 fix(hermes): preserve model discovery through confirmations (#10478)
Bohan Jiang5b8a150820cb
diff --git a/packages/views/agents/components/inspector/model-picker.test.tsx b/packages/views/agents/components/inspector/model-picker.test.tsxindex f8ec2d153a..037b608920 100644--- a/packages/views/agents/components/inspector/model-picker.test.tsx+++ b/packages/views/agents/components/inspector/model-picker.test.tsx@@ -87,6 +87,25 @@ describe("ModelPicker (inspector)", () => {expect(onChange).toHaveBeenCalledWith("claude-fable-5");});+ it("shows the discovery failure and keeps manual model selection available", async () => {+ const reason = "ACP model discovery session/new failed: provider unavailable";+ discovery = async () => {+ throw new Error(reason);+ };+ const { container, onChange } = renderPicker();+ openPicker(container);++ await screen.findByText(enAgents.pickers.model_discovery_failed_title);+ expect(screen.getByText(reason)).toBeTruthy();+ expect(screen.queryByText(enAgents.pickers.model_empty)).toBeNull();++ fireEvent.change(screen.getByRole("textbox"), {+ target: { value: "openrouter:known-model" },+ });+ fireEvent.click(screen.getByText('Use "openrouter:known-model"'));+ expect(onChange).toHaveBeenCalledWith("openrouter:known-model");+ });+it("shows an unavailable model with its reason and no way to select it", async () => {const { container, onChange } = renderPicker();openPicker(container);diff --git a/packages/views/agents/components/inspector/model-picker.tsx b/packages/views/agents/components/inspector/model-picker.tsxindex ca4304d94e..ee4bd513bd 100644--- a/packages/views/agents/components/inspector/model-picker.tsx+++ b/packages/views/agents/components/inspector/model-picker.tsx@@ -58,6 +58,10 @@ export function ModelPicker({runtimeModelsOptions(runtimeOnline ? runtimeId : null),);const supported = modelsQuery.data?.supported ?? true;+ const discoveryError =+ modelsQuery.error instanceof Error+ ? modelsQuery.error.message.trim() || null+ : null;// Memoise the model list so every downstream useMemo gets a stable// reference; `?? []` would mint a fresh array on every render and// invalidate filters needlessly.@@ -253,12 +257,31 @@ export function ModelPicker({</PickerItem>))}- {!modelsQuery.isLoading && filtered.length === 0 && !canCreate && (- <p className="px-3 py-3 text-center text-caption text-muted-foreground">- {t(($) => $.pickers.model_empty)}- </p>+ {!modelsQuery.isLoading && modelsQuery.isError && (+ <div role="alert" className="px-3 py-3 text-caption text-muted-foreground">+ <p className="font-medium text-foreground">+ {t(($) => $.pickers.model_discovery_failed_title)}+ </p>+ {discoveryError && (+ <p className="mt-1 whitespace-pre-wrap break-words select-text">+ {discoveryError}+ </p>+ )}+ <p className="mt-1.5">+ {t(($) => $.pickers.model_discovery_failed_hint)}+ </p>+ </div>)}+ {!modelsQuery.isLoading &&+ !modelsQuery.isError &&+ filtered.length === 0 &&+ !canCreate && (+ <p className="px-3 py-3 text-center text-caption text-muted-foreground">+ {t(($) => $.pickers.model_empty)}+ </p>+ )}+{!modelsQuery.isLoading && (<UnavailableModelsNotemodels={unavailableModels}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 6ecdd293f3..104e7bf96c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -4781,7 +4781,7 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri}models := catalog.Modelsif catalog.Fallback {- d.logger.Warn("model discovery fell back to a static catalog; reporting it as non-authoritative",+ d.logger.Warn("model discovery incomplete; reporting the catalog as non-authoritative","runtime_id", rt.ID, "provider", rt.Provider, "path", execPath, "count", len(models))}if rt.Provider == "codearts" && len(models) == 0 {diff --git a/server/pkg/agent/acp_discovery_unix_test.go b/server/pkg/agent/acp_discovery_unix_test.gonew file mode 100644index 0000000000..01e94bd293--- /dev/null+++ b/server/pkg/agent/acp_discovery_unix_test.go@@ -0,0 +1,154 @@+//go:build !windows++package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "testing"+ "time"+)++func TestACPDiscoveryRejectsAgentRequests(t *testing.T) {+ for _, tc := range []struct {+ name, requestID, method, params string+ wantDenial bool+ }{+ {"permission", `0`, "session/request_permission", `{"options":[{"optionId":"approve","kind":"allow_once"},{"optionId":"deny","kind":"reject_once"}]}`, true},+ {"colliding request ID", `3`, "session/request_permission", `{"options":[{"optionId":"deny","kind":"reject_once"}]}`, true},+ {"string request ID", `"ask-1"`, "session/request_permission", `{"options":[{"optionId":"deny","kind":"reject_once"}]}`, true},+ {"grant only", `0`, "session/request_permission", `{"options":[{"optionId":"approve","kind":"allow_once"}]}`, false},+ {"unsupported filesystem request", `0`, "fs/read_text_file", `{"path":"/private/file"}`, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ record := filepath.Join(t.TempDir(), "response.json")+ bin := filepath.Join(t.TempDir(), "hermes")+ script := fmt.Sprintf(`#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%%s,"result":{"sessionId":"s","models":{"currentModelId":"a","availableModels":[{"modelId":"a"},{"modelId":"b"}]},"configOptions":[{"id":"model","currentValue":"a","options":[{"value":"a"},{"value":"b"}]}]}}\n' "$id" ;;+ *'"method":"session/set_model"'*)+ printf '%%s\n' '{"jsonrpc":"2.0","id":%s,"method":"%s","params":%s}'+ IFS= read -r response || exit+ printf '%%s\n' "$response" > '%s'+ printf '{"jsonrpc":"2.0","id":%%s,"error":{"code":-32000,"message":"model_switch_cancelled"}}\n' "$id" ;;+ *) printf '{"jsonrpc":"2.0","id":%%s,"result":{}}\n' "$id" ;;+ esac+done+`, tc.requestID, tc.method, tc.params, record)+ writeTestExecutable(t, bin, []byte(script))+ catalog, err := discovered(discoverACPModels(context.Background(), Command{Path: bin}, acpDiscoveryProvider{+ strictErrors: true, probeModelEffort: true, timeout: 5 * time.Second,+ }))+ if err != nil || len(catalog.Models) != 2 {+ t.Fatalf("agent request lost the catalog: models=%+v, err=%v", catalog.Models, err)+ }+ if !catalog.Fallback || catalog.Verified() {+ t.Fatal("a rejected model switch must not claim its effort capabilities are verified")+ }+ raw, err := os.ReadFile(record)+ if err != nil {+ t.Fatalf("agent never received a response: %v", err)+ }+ var response struct {+ ID json.RawMessage `json:"id"`+ Result struct {+ Outcome struct {+ Outcome string `json:"outcome"`+ OptionID string `json:"optionId"`+ } `json:"outcome"`+ } `json:"result"`+ Error *struct {+ Code int `json:"code"`+ } `json:"error"`+ }+ if err := json.Unmarshal(raw, &response); err != nil {+ t.Fatal(err)+ }+ if string(response.ID) != tc.requestID {+ t.Fatalf("response ID=%s, want %s", response.ID, tc.requestID)+ }+ if tc.wantDenial {+ if response.Error != nil || response.Result.Outcome.Outcome != "selected" || response.Result.Outcome.OptionID != "deny" {+ t.Fatalf("discovery must select the offered rejection: %s", raw)+ }+ } else if response.Error == nil || response.Error.Code != -32601 {+ t.Fatalf("discovery must refuse unsupported actions without granting permission: %s", raw)+ }+ })+ }+}++func TestACPDiscoveryKeepsCatalogAfterEffortTimeout(t *testing.T) {+ for _, callerCancels := range []bool{false, true} {+ t.Run(fmt.Sprintf("caller_cancels=%t", callerCancels), func(t *testing.T) {+ bin := filepath.Join(t.TempDir(), "hermes")+ probing := filepath.Join(t.TempDir(), "probing")+ writeTestExecutable(t, bin, []byte(fmt.Sprintf(`#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/new"'*) printf '{"jsonrpc":"2.0","id":%%s,"result":{"sessionId":"s","models":{"currentModelId":"a","availableModels":[{"modelId":"a"},{"modelId":"b"},{"modelId":"c"}]},"configOptions":[{"id":"effort","currentValue":"low","options":[{"value":"low"}]}]}}\n' "$id" ;;+ *'"modelId":"b"'*) printf '{"jsonrpc":"2.0","id":%%s,"result":{"configOptions":[{"id":"effort","currentValue":"high","options":[{"value":"high"}]}]}}\n' "$id" ;;+ *'"modelId":"c"'*) : > '%s'; while IFS= read -r _; do :; done ;;+ *) printf '{"jsonrpc":"2.0","id":%%s,"result":{}}\n' "$id" ;;+ esac+done+`, probing)))+ ctx := context.Background()+ timeout := 3 * time.Second+ if callerCancels {+ cancelCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ ctx = cancelCtx+ done := make(chan struct{})+ go func() {+ defer close(done)+ ticker := time.NewTicker(5 * time.Millisecond)+ defer ticker.Stop()+ for {+ select {+ case <-cancelCtx.Done():+ return+ case <-ticker.C:+ if _, err := os.Stat(probing); err == nil {+ cancel()+ return+ }+ }+ }+ }()+ defer func() { cancel(); <-done }()+ timeout = 15 * time.Second+ }+ catalog, err := discovered(discoverACPModels(ctx, Command{Path: bin}, acpDiscoveryProvider{+ strictErrors: true, probeModelEffort: true, timeout: timeout,+ annotate: annotateACPThinkingForSessionModel,+ }))+ if _, err := os.Stat(probing); err != nil {+ t.Fatalf("discovery did not reach the hanging model probe: %v", err)+ }+ models := catalog.Models+ if callerCancels {+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("caller cancellation must still fail discovery: models=%+v, err=%v", models, err)+ }+ return+ }+ if err != nil || len(models) != 3 {+ t.Fatalf("optional effort timeout lost the catalog: models=%+v, err=%v", models, err)+ }+ if !catalog.Fallback || catalog.Verified() {+ t.Fatal("incomplete capability discovery must not reject saved settings or enter the catalog cache")+ }+ if models[0].Thinking == nil || models[0].Thinking.DefaultLevel != "low" || models[1].Thinking == nil || models[1].Thinking.DefaultLevel != "high" || models[2].Thinking != nil {+ t.Fatalf("only confirmed effort metadata should survive: %+v", models)+ }+ })+ }+}diff --git a/server/pkg/agent/acp_effort.go b/server/pkg/agent/acp_effort.goindex 34f84ffb83..91a04b3f6b 100644--- a/server/pkg/agent/acp_effort.go+++ b/server/pkg/agent/acp_effort.go@@ -230,7 +230,7 @@ func acpOptionsAfterModelSwitch(ctx context.Context, request acpRequestFn, sessi// each and reading the options it advertises there — the per-model read that// annotateACPThinkingForSessionModel cannot do from a single response. A model// whose switch yields no options keeps a nil Thinking rather than borrowing a-// sibling's levels. A session with no configOptions at all (Hermes Agent) is+// sibling's levels. A session with no configOptions at all is// skipped outright: switching models there cannot surface a catalog.func probeACPModelEffort(ctx context.Context, request acpRequestFn, sessionResult json.RawMessage, models []Model) {sessionID := extractACPSessionID(sessionResult)diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex 8f3ebe2de6..b2a66bbd08 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -5,6 +5,7 @@ import ("bytes""context""encoding/json"+ "errors""fmt""io""log/slog"@@ -113,8 +114,8 @@ type Catalog struct {// walks Models, so keeping these out is what makes an unrunnable model fail// closed everywhere without each lookup having to remember a flag.Unavailable []UnavailableModel- // Fallback reports that discovery did not succeed and Models is a static- // stand-in rather than the runtime's real catalog.+ // Fallback reports that discovery is incomplete. Models may be a static+ // stand-in or a live catalog whose capability probes did not finish.//// Several providers (codebuddy, copilot, cursor, grok) answer a failed// discovery with a baked-in list so the picker still has something to@@ -141,10 +142,9 @@ type Catalog struct {// be used to reject, rewrite, or drop a saved model, thinking level, or// service tier.//-// A fallback is a static stand-in for a discovery that failed, and an empty-// catalog is what the providers without one return in the same situation.-// Both mean "unknown", not "unsupported": the saved value goes to the CLI-// as-is and the CLI is the judge (MUL-7691).+// Static stand-ins, incomplete capability probes, and empty catalogs mean+// "unknown", not "unsupported": the saved value goes to the CLI as-is and+// the CLI is the judge (MUL-7691).func (c Catalog) Verified() bool {return !c.Fallback && len(c.Models) > 0}@@ -158,9 +158,16 @@ func (c Catalog) Verified() bool {// report leaves the cache alone; flagging it here would change that. The// capability checks read emptiness themselves (Catalog.Verified).func discovered(models []Model, err error) (Catalog, error) {+ if errors.Is(err, errACPEffortDiscoveryIncomplete) {+ // The model IDs are real, but missing effort metadata must not be used+ // to reject saved settings or cached as a complete discovery.+ return Catalog{Models: models, Fallback: true}, nil+ }return Catalog{Models: models}, err}+var errACPEffortDiscoveryIncomplete = errors.New("ACP per-model effort discovery incomplete")+// modelCache memoizes dynamic discovery calls so repeated UI loads// don't re-shell the agent CLI. Entries expire after cacheTTL.type modelCacheEntry struct {@@ -1641,17 +1648,13 @@ func discoverHermesModels(ctx context.Context, runtimeCmd Command) ([]Model, errtmpdirPrefix: "multica-hermes-discovery-",strictErrors: true,timeout: hermesDiscoveryTimeout,- // The same handshake carries an effort selector on jcode and carries- // none on Hermes Agent, so annotate is what tells the two apart —- // Hermes Agent models come back with a nil Thinking and show no- // picker. annotate covers the session's current model; the probe- // switches the discovery session onto each remaining model for its- // own catalog. See probeACPModelEffort.+ // Session options describe only the current model; probe other models+ // individually rather than sharing an effort catalog across providers.annotate: annotateACPThinkingForSessionModel,probeModelEffort: true,})if err != nil {- return nil, annotateHermesDiscoveryUnconfigured(err)+ return models, annotateHermesDiscoveryUnconfigured(err)}return models, nil}@@ -2190,6 +2193,14 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPrscanner := bufio.NewScanner(stdout)scanner.Buffer(make([]byte, 0, 1024*1024), 4*1024*1024)+ writeACP := func(msg any) error {+ data, err := json.Marshal(msg)+ if err != nil {+ return err+ }+ _, err = stdin.Write(append(data, '\n'))+ return err+ }nextID := 1requestACP := func(method string, params any) (json.RawMessage, error) {id := nextID@@ -2200,12 +2211,7 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPr"method": method,"params": params,}- data, err := json.Marshal(msg)- if err != nil {- return nil, err- }- data = append(data, '\n')- if _, err = stdin.Write(data); err != nil {+ if err := writeACP(msg); err != nil {return nil, err}@@ -2216,10 +2222,23 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPr}var env struct {ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params"`Result json.RawMessage `json:"result"`Error json.RawMessage `json:"error"`}- if err := json.Unmarshal([]byte(line), &env); err != nil || string(env.ID) != fmt.Sprint(id) {+ if err := json.Unmarshal([]byte(line), &env); err != nil {+ continue+ }+ // Agent requests have their own ID namespace. Answer before matching+ // responses, including when the agent's ID equals our pending ID.+ if env.Method != "" && len(env.ID) > 0 && string(env.ID) != "null" {+ if err := writeACP(rejectACPDiscoveryRequest(env.ID, env.Method, env.Params)); err != nil {+ return nil, err+ }+ continue+ }+ if string(env.ID) != fmt.Sprint(id) {continue}if len(env.Error) > 0 && string(env.Error) != "null" {@@ -2332,16 +2351,51 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPr}, models, sessionResult)}if p.probeModelEffort {+ probeIncomplete := falseprobeACPModelEffort(runCtx, func(_ context.Context, method string, params any) (json.RawMessage, error) {- return requestACP(method, params)+ result, err := requestACP(method, params)+ if err != nil {+ probeIncomplete = true+ }+ return result, err}, sessionResult, models)- if err := runCtx.Err(); err != nil {+ if err := ctx.Err(); err != nil {return fail("per-model effort discovery", err)}+ // Effort metadata is optional: a rejected or slow model switch must+ // not discard the catalog or claim unknown capabilities are absent.+ // Unprobed models keep nil Thinking; confirmed metadata survives.+ if probeIncomplete || runCtx.Err() != nil {+ return models, errACPEffortDiscoveryIncomplete+ }}return models, nil}+// Discovery has no human to approve actions. Select an offered single-use+// rejection, or refuse the client method without granting any permission.+func rejectACPDiscoveryRequest(id json.RawMessage, method string, params json.RawMessage) map[string]any {+ if method == "session/request_permission" {+ var p struct {+ Options []acpPermissionOption `json:"options"`+ }+ if json.Unmarshal(params, &p) == nil {+ for _, option := range p.Options {+ if option.OptionID != "" && strings.EqualFold(strings.TrimSpace(option.Kind), acpKindRejectOnce) {+ return map[string]any{+ "jsonrpc": "2.0", "id": id,+ "result": map[string]any{"outcome": map[string]any{"outcome": "selected", "optionId": option.OptionID}},+ }+ }+ }+ }+ }+ return map[string]any{+ "jsonrpc": "2.0", "id": id,+ "error": map[string]any{"code": -32601, "message": "Client actions are unavailable during model discovery"},+ }+}+func replaceEnvValue(env []string, key, value string) []string {out := make([]string, 0, len(env)+1)for _, entry := range env {