Skip to content

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

Go

fix(agent): MUL-6606 surface hermes model-discovery failures instead of a silent empty catalog (#7464)

Bohan Jiang25afaaf153a5
diff --git a/packages/core/runtimes/models.test.ts b/packages/core/runtimes/models.test.ts
index ab52fa04dc..9f56f14a26 100644
--- a/packages/core/runtimes/models.test.ts
+++ b/packages/core/runtimes/models.test.ts
@@ -99,6 +99,72 @@ describe("resolveRuntimeModels", () => {
expect(getListModelsResult).toHaveBeenLastCalledWith("rt-1", "req-1");
});
+ // MUL-6606 review: the client budget has to cover the server's pending AND
+ // running windows, which are sequential. A request the daemon claims at ~29s
+ // (still inside modelListPendingTimeout) and then spends hermes' ~40s
+ // discovery on reports at ~69s — while the server still holds the record
+ // open. A 60s client budget gave up first and replaced the daemon's reason
+ // with a generic "model discovery timed out", which is precisely the message
+ // this issue exists to stop showing.
+ it("waits out a claim near the pending limit plus a full discovery", async () => {
+ vi.useFakeTimers();
+ try {
+ const start = Date.now();
+ initiateListModels.mockResolvedValue(request({ status: "pending" }));
+ getListModelsResult.mockImplementation(async () =>
+ Date.now() - start >= 69_000
+ ? request({ status: "completed", models: catalog })
+ : request({ status: "running" }),
+ );
+
+ const pending = resolveRuntimeModels("rt-1");
+ // Surface a rejection as the test failure instead of an unhandled one.
+ const settled = pending.then(
+ (value) => ({ ok: true as const, value }),
+ (error: Error) => ({ ok: false as const, error }),
+ );
+
+ await vi.advanceTimersByTimeAsync(75_000);
+
+ const outcome = await settled;
+ if (!outcome.ok) {
+ throw new Error(
+ `client gave up while the server still held the request: ${outcome.error.message}`,
+ );
+ }
+ expect(outcome.value.models).toEqual(catalog);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ // The budget is not unbounded: once BOTH server windows have elapsed the
+ // record is terminal, so continuing to poll would spin forever against a
+ // server that will never answer again.
+ it("does eventually give up once the server's own windows have closed", async () => {
+ vi.useFakeTimers();
+ try {
+ initiateListModels.mockResolvedValue(request({ status: "pending" }));
+ getListModelsResult.mockResolvedValue(request({ status: "running" }));
+
+ const pending = resolveRuntimeModels("rt-1");
+ const settled = pending.then(
+ () => ({ ok: true as const }),
+ (error: Error) => ({ ok: false as const, error }),
+ );
+
+ await vi.advanceTimersByTimeAsync(200_000);
+
+ const outcome = await settled;
+ expect(outcome.ok).toBe(false);
+ if (!outcome.ok) {
+ expect(outcome.error.message).toContain("timed out");
+ }
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("surfaces a failed discovery as an error", async () => {
initiateListModels.mockResolvedValue(
request({ status: "failed", error: "claude not installed" }),
diff --git a/packages/core/runtimes/models.ts b/packages/core/runtimes/models.ts
index e3881f102e..4c166f2d3c 100644
--- a/packages/core/runtimes/models.ts
+++ b/packages/core/runtimes/models.ts
@@ -9,7 +9,37 @@ export const runtimeModelsKeys = {
};
const POLL_INTERVAL_MS = 500;
-const POLL_TIMEOUT_MS = 30_000;
+
+// The client must not give up on a request the server still considers live.
+// Those two windows are sequential, not overlapping (server/internal/handler/
+// runtime_models.go):
+//
+// - pending: measured from CreatedAt, so the daemon has up to 30s to CLAIM
+// the request off a heartbeat.
+// - running: measured from RunStartedAt, which PopPending sets at claim
+// time. Heartbeat pickup happens before the claim and is bounded by the
+// pending window, so it does not eat into this 60s.
+//
+// A request claimed at 29s that then runs hermes' ~25-40s discovery reports at
+// ~69s — past a 60s client budget, while the server is still holding the record
+// open. The user would be shown a generic client-side "timed out" instead of the
+// reason the daemon was about to deliver, which for hermes names the exact
+// command to run (MUL-6606). Budgeting for the sum removes that whole class of
+// premature give-up, and lets the server's own timeout text ("daemon did not
+// respond within 30 seconds") win instead of ours — it is the more specific of
+// the two.
+//
+// Waiting longer costs the user nothing here: the picker's manual-entry input
+// stays live for the whole poll, so a model ID can be typed and saved without
+// waiting for discovery at all.
+const SERVER_PENDING_TIMEOUT_MS = 30_000;
+const SERVER_RUNNING_TIMEOUT_MS = 60_000;
+// Slack for the poll interval, the store's own sweep granularity, and network
+// latency on the final GET — without it the client can still expire in the same
+// tick the server transitions the record.
+const POLL_SLACK_MS = 10_000;
+const POLL_TIMEOUT_MS =
+ SERVER_PENDING_TIMEOUT_MS + SERVER_RUNNING_TIMEOUT_MS + POLL_SLACK_MS;
// How long a LIVE discovery result (one the daemon just produced) is trusted
// without re-asking. Discovery is a round trip to the user's machine, and a
@@ -26,8 +56,9 @@ export const MODELS_GC_TIME_MS = 30 * 60_000;
// (via heartbeat piggyback) and polls until the daemon reports back or
// the request times out. Returns both the models list and a
// `supported` flag: `supported=false` means the provider ignores
-// per-agent model selection entirely (hermes today) — the UI uses
-// this to disable its dropdown instead of accepting a value that
+// per-agent model selection entirely (qwenpaw and mcode — hermes is NOT
+// one of them; it applies opts.Model via ACP session/set_model) — the UI
+// uses this to disable its dropdown instead of accepting a value that
// wouldn't be honoured at runtime.
//
// `cached` reports that the server answered from its catalog cache rather than
diff --git a/packages/views/agents/components/model-dropdown.test.tsx b/packages/views/agents/components/model-dropdown.test.tsx
index a890027348..82532f6616 100644
--- a/packages/views/agents/components/model-dropdown.test.tsx
+++ b/packages/views/agents/components/model-dropdown.test.tsx
@@ -28,14 +28,21 @@ const CODEX_MODELS: RuntimeModelsResult = {
supported: true,
};
+// Discovery outcome for the next render. resolveRuntimeModels rejects with the
+// daemon's reported error text, so a failure is modelled as a throwing queryFn.
+let discovery: () => Promise<RuntimeModelsResult> = async () => CODEX_MODELS;
+
vi.mock("@multica/core/runtimes", () => ({
runtimeModelsOptions: (runtimeId: string | null) => ({
enabled: Boolean(runtimeId),
- queryKey: ["runtime-models", runtimeId],
- queryFn: async () => CODEX_MODELS,
+ queryKey: ["runtime-models", runtimeId, discoveryKey],
+ queryFn: () => discovery(),
}),
}));
+// Bumped per test so React Query cannot serve a previous case's cached result.
+let discoveryKey = 0;
+
function renderDropdown() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -65,7 +72,11 @@ function openDropdown(container: HTMLElement) {
}
describe("ModelDropdown", () => {
- afterEach(() => cleanup());
+ afterEach(() => {
+ cleanup();
+ discovery = async () => CODEX_MODELS;
+ discoveryKey += 1;
+ });
it("offers the gpt-5.6 Codex models and submits their canonical IDs", async () => {
const { container, onChange } = renderDropdown();
@@ -81,4 +92,48 @@ describe("ModelDropdown", () => {
fireEvent.click(screen.getByText("GPT-5.6 Terra"));
expect(onChange).toHaveBeenCalledWith("gpt-5.6-terra");
});
+
+ // MUL-6606: a runtime that could not enumerate its models used to report an
+ // empty catalog with no error, which rendered as an authoritative empty
+ // dropdown. The reason has to reach the user, because for hermes it names the
+ // exact command that fixes the problem.
+ it("shows the runtime's own reason when discovery fails", async () => {
+ const reason =
+ "ACP model discovery session/new failed: No LLM provider configured. " +
+ "Run `hermes model` to select a provider.";
+ discovery = async () => {
+ throw new Error(reason);
+ };
+
+ const { container } = renderDropdown();
+ openDropdown(container);
+
+ expect(await screen.findByText(reason)).toBeTruthy();
+ // And the picker says so up front, rather than looking like an empty catalog.
+ expect(screen.getByText(enAgents.model_dropdown.discovery_failed)).toBeTruthy();
+ expect(
+ screen.queryByText(enAgents.pickers.model_empty_with_dot),
+ ).toBeNull();
+ });
+
+ // A reason with no way forward is a dead end: manual entry is the documented
+ // fallback for a failed discovery, so it must survive one.
+ it("still accepts a manually typed model ID after a failed discovery", async () => {
+ discovery = async () => {
+ throw new Error("discovery blew up");
+ };
+
+ const { container, onChange } = renderDropdown();
+ openDropdown(container);
+
+ await screen.findByText("discovery blew up");
+ // The popover renders through a portal, so reach it via screen, not container.
+ const input = screen.getByPlaceholderText(
+ enAgents.pickers.model_search_placeholder,
+ );
+ fireEvent.change(input, { target: { value: "vertex/gemini-3.1-pro" } });
+
+ fireEvent.click(await screen.findByText(/vertex\/gemini-3\.1-pro/));
+ expect(onChange).toHaveBeenCalledWith("vertex/gemini-3.1-pro");
+ });
});
diff --git a/packages/views/agents/components/model-dropdown.tsx b/packages/views/agents/components/model-dropdown.tsx
index 9a5bcb4446..37a83872e4 100644
--- a/packages/views/agents/components/model-dropdown.tsx
+++ b/packages/views/agents/components/model-dropdown.tsx
@@ -19,9 +19,15 @@ import { useT } from "../../i18n";
// daemon enumerates models on demand via heartbeat piggyback. Providers
// whose runtime ignores per-agent model selection return supported=false,
// and the dropdown renders disabled with an explanation instead of silently
-// accepting a value the backend would ignore. No built-in provider does so
-// today — Antigravity gained `--model` in agy 1.0.6 — but the path stays for
-// any future model-less runtime.
+// accepting a value the backend would ignore. Today that is qwenpaw and mcode
+// (agent.ModelSelectionSupported is the single source of truth for the set);
+// Antigravity left it when agy 1.0.6 added `--model`.
+//
+// supported=false is a different state from discovery failing, and the two must
+// not be conflated. A failed discovery throws out of resolveRuntimeModels, so
+// modelsQuery.isError renders the discovery-failed notice and keeps the
+// creatable manual-entry input below — which is exactly the fallback a user
+// needs when their runtime could not enumerate anything (MUL-6606).
export function ModelDropdown({
runtimeId,
runtimeOnline,
@@ -51,6 +57,13 @@ export function ModelDropdown({
[modelsQuery.data],
);
const grouped = useMemo(() => groupByProvider(models), [models]);
+ // resolveRuntimeModels throws the daemon's reported error text, so this is
+ // the runtime's own message (plus any hint the daemon appended). It is only
+ // ever read while isError is true.
+ const discoveryError =
+ modelsQuery.error instanceof Error
+ ? modelsQuery.error.message.trim() || null
+ : null;
// When the selected runtime reports it doesn't support per-agent
// model selection, clear any previously-saved value so we don't
@@ -120,7 +133,12 @@ export function ModelDropdown({
<div className="flex h-6 items-center justify-between">
<Label className="text-caption text-muted-foreground">{t(($) => $.model_dropdown.label)}</Label>
{modelsQuery.isError && (
- <span className="text-caption text-muted-foreground">{t(($) => $.model_dropdown.discovery_failed)}</span>
+ <span
+ className="text-caption text-muted-foreground"
+ title={discoveryError ?? undefined}
+ >
+ {t(($) => $.model_dropdown.discovery_failed)}
+ </span>
)}
</div>
<Popover open={open} onOpenChange={setOpen}>
@@ -200,7 +218,35 @@ export function ModelDropdown({
</div>
))}
+ {/* A failed discovery reports WHY here rather than in the label
+ row's caption, which has no room for a sentence. The runtime's
+ own words are the actionable part — hermes, for one, names the
+ exact command to run — so they are rendered verbatim and left
+ selectable. Paired with the manual-entry prompt, because a
+ reason with no way forward is just a nicer dead end. */}
+ {!modelsQuery.isLoading && modelsQuery.isError && (
+ <div className="px-3 py-4 text-body text-muted-foreground">
+ <div className="flex items-start gap-2">
+ <Info className="mt-0.5 h-4 w-4 shrink-0" />
+ <div className="min-w-0">
+ <div className="font-medium text-foreground">
+ {t(($) => $.pickers.model_discovery_failed_title)}
+ </div>
+ {discoveryError && (
+ <div className="mt-1 whitespace-pre-wrap break-words text-caption select-text">
+ {discoveryError}
+ </div>
+ )}
+ <div className="mt-1.5 text-caption">
+ {t(($) => $.pickers.model_discovery_failed_hint)}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
{!modelsQuery.isLoading &&
+ !modelsQuery.isError &&
Object.keys(filtered).length === 0 &&
!canCreate && (
<div className="px-3 py-6 text-center text-body text-muted-foreground">
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index b0ae090257..cc42ca6c5d 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -227,6 +227,8 @@
"model_managed_by_runtime": "Managed by runtime",
"model_search_placeholder": "Search or type a model ID",
"model_discovering": "Discovering models…",
+ "model_discovery_failed_title": "Could not list this runtime's models.",
+ "model_discovery_failed_hint": "Type a model ID above to enter one manually.",
"model_empty": "No models available",
"model_empty_with_dot": "No models available.",
"model_custom_tooltip": "Use \"{{value}}\" as a custom model id",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 6457a13f98..8b48db79a9 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -210,6 +210,8 @@
"model_managed_by_runtime": "ランタイムで管理",
"model_search_placeholder": "モデル ID を検索または入力",
"model_discovering": "モデルを検出中...",
+ "model_discovery_failed_title": "このランタイムのモデルを取得できませんでした。",
+ "model_discovery_failed_hint": "上の入力欄にモデル ID を直接入力して手動で指定できます。",
"model_empty": "利用可能なモデルがありません",
"model_empty_with_dot": "利用可能なモデルがありません。",
"model_custom_tooltip": "\"{{value}}\" をカスタムモデル ID として使用",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 5f0d67b6a9..9f82acee5c 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -218,6 +218,8 @@
"model_managed_by_runtime": "런타임에서 관리",
"model_search_placeholder": "모델 ID 검색 또는 입력",
"model_discovering": "모델 찾는 중...",
+ "model_discovery_failed_title": "이 런타임의 모델을 가져오지 못했습니다.",
+ "model_discovery_failed_hint": "위 입력란에 모델 ID를 직접 입력해 수동으로 지정할 수 있습니다.",
"model_empty": "사용 가능한 모델이 없습니다",
"model_empty_with_dot": "사용 가능한 모델이 없습니다.",
"model_custom_tooltip": "\"{{value}}\"을(를) 사용자 지정 모델 ID로 사용",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 2344e4064f..bf24ce5981 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -218,6 +218,8 @@
"model_managed_by_runtime": "由运行时管理",
"model_search_placeholder": "搜索或输入模型 ID",
"model_discovering": "正在发现模型...",
+ "model_discovery_failed_title": "无法列出该运行时的模型。",
+ "model_discovery_failed_hint": "可在上方输入框直接键入模型 ID 手动指定。",
"model_empty": "暂无可用模型",
"model_empty_with_dot": "暂无可用模型。",
"model_custom_tooltip": "使用\"{{value}}\"作为自定义模型 ID",
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a7fb6ac927..e4f7cc4904 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4026,8 +4026,9 @@ func (d *Daemon) handlePendingWorkHint(runtimeID, kind string) {
}()
// Root context: handleHeartbeatActions hands this ctx to the actual work
- // (model discovery shells out to a CLI for up to ~15s), so it must outlive
- // this function. Only the heartbeat request itself is time-bounded.
+ // (model discovery shells out to a CLI, for up to ~40s on the slowest
+ // provider — see agent.hermesDiscoveryTimeout), so it must outlive this
+ // function. Only the heartbeat request itself is time-bounded.
ctx := d.recoveryContext()
if ctx.Err() != nil {
return
@@ -4056,9 +4057,14 @@ func (d *Daemon) handlePendingWorkHint(runtimeID, kind string) {
// handleModelList resolves the provider's supported models (via static
// catalog or by shelling out to the agent CLI) and reports the result
-// back to the server. Model discovery failures are reported as empty
-// lists rather than errors so the UI can still render a creatable
-// dropdown.
+// back to the server.
+//
+// How a discovery failure is reported is the provider's decision, not this
+// function's. Providers with a safe static catalog swallow the error and return
+// the stand-in (marked Fallback); providers without one — hermes — return the
+// error, and it is forwarded as status=failed so the picker can show the reason
+// and keep manual entry (MUL-6606). Both outcomes leave the creatable dropdown
+// usable; only the second one tells the user why it is empty.
func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID string) {
d.logger.Info("model list requested", "runtime_id", rt.ID, "request_id", requestID, "provider", rt.Provider)
@@ -4232,9 +4238,9 @@ func (d *Daemon) handleLocalSkillImport(ctx context.Context, rt Runtime, pending
// runtimeReportBackoffs defines the retry schedule for delivering any
// daemon→server async result (model list, local-skill list, local-skill
// import). First attempt runs immediately, then we back off. The sum
-// (≈6.5s) stays well under the server-side running timeout (60s) so a
-// report that eventually lands still updates the request instead of
-// racing a timeout transition.
+// (≈6.5s) leaves most of the server-side running timeout (60s) available for
+// discovery and report attempts. Each HTTP attempt has its own client timeout,
+// so this schedule alone is not an end-to-end delivery deadline.
//
// Overridable for tests to avoid real sleeps.
var runtimeReportBackoffs = []time.Duration{0, 500 * time.Millisecond, 2 * time.Second, 4 * time.Second}
diff --git a/server/internal/handler/runtime_models.go b/server/internal/handler/runtime_models.go
index 88a7e2c534..d4a0d3b1a9 100644
--- a/server/internal/handler/runtime_models.go
+++ b/server/internal/handler/runtime_models.go
@@ -44,9 +44,13 @@ const (
// ModelListRequest represents a pending or completed model list request.
// Supported is false when the provider ignores per-agent model
-// selection entirely (currently: hermes). The UI uses this to
-// disable its dropdown rather than silently accepting a value the
-// backend will drop.
+// selection entirely — agent.ModelSelectionSupported is the single
+// source of truth, and it names qwenpaw and mcode. Hermes is NOT in
+// that set: it honours opts.Model through the ACP `session/set_model`
+// RPC, so do not "align" this list by adding it (MUL-6606 — an earlier
+// version of this comment said hermes, which would have cost Hermes its
+// model picker outright). The UI uses this to disable its dropdown
+// rather than silently accepting a value the backend will drop.
//
// RunStartedAt is set when PopPending claims the request. It is
// `json:"-"` because it's a server-side bookkeeping field — the UI only
diff --git a/server/pkg/agent/hermes_model_discovery_test.go b/server/pkg/agent/hermes_model_discovery_test.go
new file mode 100644
index 0000000000..37f59f3aa8
--- /dev/null
+++ b/server/pkg/agent/hermes_model_discovery_test.go
@@ -0,0 +1,146 @@
+package agent
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// hermesProviderUnconfiguredACPError is the failure exactly as discoverACPModels
+// renders it when hermes resolves no provider — verified against hermes 0.20.0
+// by pointing it at a HERMES_HOME whose configured provider cannot be resolved.
+// The error frame carries its message in a `data` OBJECT rather than a string,
+// which is why the transport renders it as raw JSON and why ProviderUnconfigured
+// matches on a substring instead of equality.
+//
+// The end-to-end path that produces this string is covered in
+// hermes_model_discovery_unix_test.go; keeping a literal here lets the wording
+// assertions below run on every platform, including the one that cannot execute
+// a shell fixture.
+var hermesProviderUnconfiguredACPError = fmt.Sprintf(
+ "ACP model discovery session/new failed: session/new: Internal error (code=-32603, data={%q:%q})",
+ "details",
+ "No LLM provider configured. Run `hermes model` to select a provider, "+
+ "or run `hermes setup` for first-time configuration.",
+)
+
+// TestHermesDiscoveryUnconfiguredHintPointsAtTheDaemonEnvironment pins the
+// content of the hint, not just its presence. Discovery builds no per-task
+// HERMES_HOME overlay and never reads an agent's custom_env, so the task path's
+// advice (annotateHermesProviderUnconfigured in internal/daemon) is not merely
+// unhelpful here — following it cannot put a single model in the picker. The
+// hint has to send the reader at the daemon's own environment instead.
+func TestHermesDiscoveryUnconfiguredHintPointsAtTheDaemonEnvironment(t *testing.T) {
+ t.Parallel()
+
+ err := annotateHermesDiscoveryUnconfigured(errString(hermesProviderUnconfiguredACPError))
+ if err == nil {
+ t.Fatal("expected the unconfigured-provider failure to be annotated")
+ }
+ msg := err.Error()
+
+ // Hermes' own message survives: it is what the runtime actually said.
+ if !strings.Contains(msg, "No LLM provider configured") {
+ t.Errorf("the runtime's own message must be preserved, got: %s", msg)
+ }
+ // And the hint carries what hermes could not know — that it was answering
+ // the daemon, not the user's shell — plus a check the user can run.
+ for _, want := range []string{"daemon", "login shell", "env -i"} {
+ if !strings.Contains(msg, want) {
+ t.Errorf("hint must mention %q, got: %s", want, msg)
+ }
+ }
+ // The task path's remedy must not leak in: it would send the reader to
+ // edit config that discovery provably never reads.
+ if !strings.Contains(hermesDiscoveryUnconfiguredHint, "will not populate this picker") {
+ t.Error("hint must say outright that HERMES_HOME / custom_env cannot fix the picker")
+ }
+}
+
+// TestAnnotateHermesDiscoveryUnconfiguredLeavesOtherFailuresAlone proves the
+// predicate, not the transport, is the gate — including for stages a fake ACP
+// binary cannot reach, since a missing binary never speaks the protocol at all.
+func TestAnnotateHermesDiscoveryUnconfiguredLeavesOtherFailuresAlone(t *testing.T) {
+ t.Parallel()
+
+ if got := annotateHermesDiscoveryUnconfigured(nil); got != nil {
+ t.Errorf("nil error must stay nil, got: %v", got)
+ }
+ for _, msg := range []string{
+ `ACP model discovery executable lookup failed: exec: "hermes": executable file not found in $PATH`,
+ "ACP model discovery initialize failed: unexpected EOF",
+ "ACP model discovery session/new failed: session/new: Internal error (code=-32603, data=401 invalid api key)",
+ "ACP model discovery completion failed: context deadline exceeded",
+ } {
+ in := errString(msg)
+ if got := annotateHermesDiscoveryUnconfigured(in); got.Error() != msg {
+ t.Errorf("error text must be untouched\n got: %s\nwant: %s", got.Error(), msg)
+ }
+ }
+}
+
+// TestHermesDiscoveryHintDoesNotReclassifyTheFailure keeps the hint inert. The
+// same predicate that gates it (taskfailure.ProviderUnconfigured) also feeds
+// Classify, and this text is appended to an error string other code reads —
+// so it must not change what that error is understood to be.
+func TestHermesDiscoveryHintDoesNotReclassifyTheFailure(t *testing.T) {
+ t.Parallel()
+
+ for _, msg := range []string{
+ hermesProviderUnconfiguredACPError,
+ "ACP model discovery initialize failed: unexpected EOF",
+ "API Error: prompt is too long: 250000 tokens > 200000 maximum",
+ } {
+ annotated := msg + hermesDiscoveryUnconfiguredHint
+ if got, want := taskfailure.Classify(annotated), taskfailure.Classify(msg); got != want {
+ t.Errorf("hint moved the failure reason for %q: %q -> %q", msg, want, got)
+ }
+ }
+}
+
+// TestHermesDiscoveryTimeoutLeavesRoomForReportRetryBackoffs is the reason the
+// per-provider knob exists, and pins both ends of it.
+//
+// Lower bound: measured against hermes 0.20.0, a healthy session/new returns in
+// ~2s but a hermes whose configured provider cannot be resolved spends ~25s
+// before reporting "No LLM provider configured" — the exact case MUL-6606 is
+// about. Under the shared 15s default that diagnosis was replaced by "context
+// deadline exceeded", so the budget must clear ~25s with margin.
+//
+// Upper bound: the server closes a CLAIMED request after
+// handler.modelListRunningTimeout (60s), measured from RunStartedAt — which
+// PopPending sets at claim time. Heartbeat pickup happens BEFORE the claim and
+// is bounded separately by modelListPendingTimeout, so it does not eat into this
+// 60s; what does share it is the daemon's report-retry backoff schedule
+// (runtimeReportBackoffs, ≈6.5s). Discovery plus those scheduled sleeps must
+// leave room inside 60s for report attempts. This test deliberately does not
+// model the HTTP attempts themselves; those have a separate client timeout.
+func TestHermesDiscoveryTimeoutLeavesRoomForReportRetryBackoffs(t *testing.T) {
+ t.Parallel()
+
+ // Mirrors internal/handler.modelListRunningTimeout and
+ // internal/daemon.runtimeReportBackoffs. Duplicated rather than imported
+ // because pkg/agent must not depend on either package; the comment above is
+ // the contract, and this test is what notices when it drifts.
+ const serverRunningWindow = 60 * time.Second
+ const reportRetryBackoffBudget = 6500 * time.Millisecond
+
+ if hermesDiscoveryTimeout <= acpDiscoveryDefaultTimeout {
+ t.Fatalf("hermes budget %s must exceed the shared default %s; its failure path needs ~25s",
+ hermesDiscoveryTimeout, acpDiscoveryDefaultTimeout)
+ }
+ if hermesDiscoveryTimeout < 30*time.Second {
+ t.Errorf("hermes budget %s leaves no margin over the ~25s failure path", hermesDiscoveryTimeout)
+ }
+ if got := hermesDiscoveryTimeout + reportRetryBackoffBudget; got > serverRunningWindow {
+ t.Errorf("discovery (%s) plus report retry backoffs (%s) = %s, which outlives the server's %s claimed-request window",
+ hermesDiscoveryTimeout, reportRetryBackoffBudget, got, serverRunningWindow)
+ }
+}
+
+type errString string
+
+func (e errString) Error() string { return string(e) }
diff --git a/server/pkg/agent/hermes_model_discovery_unix_test.go b/server/pkg/agent/hermes_model_discovery_unix_test.go
new file mode 100644
index 0000000000..5b202bf8ed
--- /dev/null
+++ b/server/pkg/agent/hermes_model_discovery_unix_test.go
@@ -0,0 +1,185 @@
+//go:build !windows
+
+// Process-based coverage for hermes model discovery. Split from the
+// cross-platform half because every test here writes a `#!/bin/sh` fixture and
+// executes it: on Windows, writeTestExecutable can only drop the bytes on disk
+// (there is no shebang to honour and no .exe extension), so `go test
+// ./pkg/agent` would fail to run rather than fail to build. Same posture as
+// codebuddy_discovery_fallback_test.go, which fakes the same handshake.
+//
+// The assertions that need no subprocess — hint wording, classification
+// inertness, the timeout invariant — live in hermes_model_discovery_test.go and
+// run everywhere.
+
+package agent
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// hermesACPProviderUnconfiguredScript is a `hermes acp` stand-in that completes
+// initialize and then rejects session/new exactly as hermes 0.20.0 does when it
+// resolves no LLM provider — verified against the real binary by pointing it at
+// an empty HERMES_HOME. The error frame carries its message in a `data` OBJECT,
+// not a string, which is why the transport renders it as raw JSON and why
+// ProviderUnconfigured matches on a substring.
+func hermesACPProviderUnconfiguredScript() string {
+ // hermes' message quotes its own commands in backticks, which cannot
+ // appear inside a Go raw string literal — hence the concatenation. Inside
+ // the shell script they sit in single quotes, so sh treats them as text
+ // rather than command substitution.
+ bt := "`"
+ details := "No LLM provider configured. Run " + bt + "hermes model" + bt +
+ " to select a provider, or run " + bt + "hermes setup" + bt +
+ " for first-time configuration."
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"hermes-agent","version":"0.20.0"}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":{"details":"` + details + `"}}}\n' "$id"
+ ;;
+ esac
+done
+`
+}
+
+// hermesACPHandshakeErrorScript fails session/new for a reason that has nothing
+// to do with configuration.
+func hermesACPHandshakeErrorScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Internal error","data":{"details":"401 invalid api key"}}}\n' "$id"
+ ;;
+ esac
+done
+`
+}
+
+func hermesACPCatalogScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_ok","models":{"currentModelId":"openai-codex:gpt-5.6-terra","availableModels":[{"modelId":"openai-codex:gpt-5.6-terra","name":"OpenAI Codex · gpt-5.6-terra"},{"modelId":"openai-codex:gpt-5.5","name":"OpenAI Codex · gpt-5.5"}]}}}\n' "$id"
+ ;;
+ esac
+done
+`
+}
+
+// TestDiscoverHermesModelsSurfacesSessionNewFailure is the regression this file
+// exists for (MUL-6606). Hermes ships no static catalog, so swallowing a
+// session/new failure into an empty list reports "discovery succeeded and found
+// nothing" — which the picker renders as an authoritative empty dropdown with
+// no error, no reason, and no prompt to type a model in by hand. The failure
+// must reach the caller so the daemon reports status=failed.
+func TestDiscoverHermesModelsSurfacesSessionNewFailure(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ script string
+ // wantHint is true only for the provider-unconfigured failure; every
+ // other failure must pass through with its own text and nothing added.
+ wantHint bool
+ }{
+ {name: "provider unconfigured", script: hermesACPProviderUnconfiguredScript(), wantHint: true},
+ {name: "rejected credential", script: hermesACPHandshakeErrorScript(), wantHint: false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(tc.script))
+
+ models, err := discoverHermesModels(context.Background(), Command{Path: fakePath})
+ if err == nil {
+ t.Fatalf("session/new failed but discovery reported success with %d models", len(models))
+ }
+ if len(models) != 0 {
+ t.Errorf("a failed discovery must return no models, got %+v", models)
+ }
+ // The runtime's own words are the actionable part of the message;
+ // the wrapper must not replace them.
+ if !strings.Contains(err.Error(), "session/new") {
+ t.Errorf("error must name the stage that failed, got: %v", err)
+ }
+ if got := strings.Contains(err.Error(), hermesDiscoveryUnconfiguredHint); got != tc.wantHint {
+ t.Errorf("hint present=%v, want %v; error: %v", got, tc.wantHint, err)
+ }
+ })
+ }
+}
+
+// TestDiscoverHermesModelsStillReturnsACatalogOnSuccess guards the other half:
+// strictErrors must not have turned a working hermes into a failing one.
+func TestDiscoverHermesModelsStillReturnsACatalogOnSuccess(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(hermesACPCatalogScript()))
+
+ models, err := discoverHermesModels(context.Background(), Command{Path: fakePath})
+ if err != nil {
+ t.Fatalf("discover hermes models: %v", err)
+ }
+ if len(models) != 2 || models[0].ID != "openai-codex:gpt-5.6-terra" {
+ t.Fatalf("unexpected models: %+v", models)
+ }
+ if !models[0].Default {
+ t.Error("currentModelId must still be badged as the default pick")
+ }
+}
+
+// TestACPDiscoveryTimeoutIsPerProvider covers the knob hermes needs: a provider
+// that sets no timeout keeps the shared default, and one that sets a short
+// timeout is actually cut off by it.
+func TestACPDiscoveryTimeoutIsPerProvider(t *testing.T) {
+ t.Parallel()
+
+ // A binary that consumes initialize but never answers it. Keep the stall in
+ // the shell's built-in read: spawning sleep here would leave a descendant
+ // holding stdout open after CommandContext kills the shell, so Scanner would
+ // wait for the descendant instead of measuring the provider deadline.
+ stalled := `#!/bin/sh
+while IFS= read -r _; do
+ :
+done
+`
+ fakePath := filepath.Join(t.TempDir(), "stalled")
+ writeTestExecutable(t, fakePath, []byte(stalled))
+
+ start := time.Now()
+ _, err := discoverACPModels(context.Background(), Command{Path: fakePath}, acpDiscoveryProvider{
+ defaultBin: "stalled",
+ clientName: "multica-model-discovery",
+ tmpdirPrefix: "multica-timeout-test-",
+ strictErrors: true,
+ timeout: 300 * time.Millisecond,
+ })
+ if err == nil {
+ t.Fatal("expected the per-provider deadline to abort the handshake")
+ }
+ // The override has to be what fired, not the 15s default.
+ if elapsed := time.Since(start); elapsed > 5*time.Second {
+ t.Errorf("provider timeout was ignored; handshake ran for %s", elapsed)
+ }
+}
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 91f8ab0528..243671fd89 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -15,6 +15,8 @@ import (
"strings"
"sync"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// Model describes a single LLM model exposed by an agent provider.
@@ -1363,15 +1365,26 @@ func parseOmpModels(data []byte) ([]Model, error) {
// `_build_model_state` so whatever ~/.hermes/config.yaml resolves
// to at runtime is exactly what the UI shows.
//
-// Failure modes (hermes missing, no credentials, config resolution
-// error) all return an empty list so the UI falls back to the
-// creatable manual-entry input instead of blocking the form.
+// Failures propagate. Hermes has no static catalog to degrade to, so the
+// empty-list behaviour the other legacy providers keep would report a
+// successful discovery that found nothing — and the picker renders that as an
+// authoritative empty dropdown with no error and no hint, which is the one
+// outcome packages/core/runtimes/models.ts explicitly refuses to produce
+// (MUL-6606). An error instead puts the picker in its discovery-failed state,
+// which still offers the creatable manual-entry input, and carries the reason
+// Hermes gave for why it found nothing.
+//
+// Contrast grok (strictErrors with a static fallback) and codebuddy: those
+// substitute a baked-in list and only slog.Debug the reason, because a
+// stand-in catalog is better than nothing there. Here there is no stand-in.
func discoverHermesModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {
- return discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{
+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{
defaultBin: "hermes",
clientName: "multica-model-discovery",
extraEnv: []string{"HERMES_YOLO_MODE=1"},
tmpdirPrefix: "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
@@ -1379,6 +1392,53 @@ func discoverHermesModels(ctx context.Context, runtimeCmd Command) ([]Model, err
// annotateACPThinkingForSessionModel.
annotate: annotateACPThinkingForSessionModel,
})
+ if err != nil {
+ return nil, annotateHermesDiscoveryUnconfigured(err)
+ }
+ return models, nil
+}
+
+// hermesDiscoveryUnconfiguredHint explains a "no LLM provider configured"
+// failure raised by MODEL DISCOVERY, which is a different story from the same
+// message raised by a task.
+//
+// Hermes' own remedy ("run `hermes model`") assumes the shell the user is
+// standing in. Discovery does not run there: it is a `hermes acp` child of the
+// daemon, and the daemon is frequently GUI-launched, in which case its
+// environment never saw the user's shell rc. agents_probe.go's login-shell
+// fallback does not close that gap — it resolves the binary's PATH and nothing
+// else — so a provider whose credentials live in an exported variable or in
+// gcloud/ADC state (GH: Vertex AI) resolves for the user and not for the
+// daemon.
+//
+// Deliberately NOT the task path's hint (annotateHermesProviderUnconfigured in
+// the daemon): that one is about a per-task HERMES_HOME overlay, and discovery
+// builds no overlay. Sending someone to set HERMES_HOME in an agent's
+// custom_env would be actively wrong here — discovery is per-runtime and never
+// reads any agent's custom_env, so that edit cannot put a single model in this
+// picker.
+//
+// Fixed prose, no interpolation, for the same reason the task hint is: this
+// text is error copy, and nothing user-controlled belongs in a string other
+// code may match on.
+const hermesDiscoveryUnconfiguredHint = " [multica] this is what hermes reported to the daemon, " +
+ "which runs `hermes acp` with its OWN environment — not your login shell. " +
+ "Credentials exported only from a shell rc file are invisible to it. " +
+ "Reproduce with `env -i HOME=\"$HOME\" PATH=\"$PATH\" hermes model`: if that fails while a plain " +
+ "`hermes model` succeeds, restart the daemon from a shell that already has those variables. " +
+ "Setting HERMES_HOME or custom_env on an agent will not populate this picker — " +
+ "model discovery is per-runtime and reads neither."
+
+// annotateHermesDiscoveryUnconfigured appends the hint above when, and only
+// when, the discovery failure is Hermes resolving no provider at all. Every
+// other failure (binary missing, handshake timeout, a rejected credential)
+// passes through untouched — the environment story would misdirect there, and
+// a rejected credential in particular means the config WAS found.
+func annotateHermesDiscoveryUnconfigured(err error) error {
+ if err == nil || !taskfailure.ProviderUnconfigured(err.Error()) {
+ return err
+ }
+ return fmt.Errorf("%w%s", err, hermesDiscoveryUnconfiguredHint)
}
// discoverKimiModels combines Kimi's ACP model catalog with the structured
@@ -1721,6 +1781,23 @@ func discoverQoderModels(ctx context.Context, runtimeCmd Command, defaultBin str
})
}
+// acpDiscoveryDefaultTimeout bounds an ACP discovery handshake unless the
+// provider overrides it. Discovery is a foreground UI request, so the ceiling
+// is what a user will wait for a picker to populate, not what a CLI might
+// eventually manage.
+const acpDiscoveryDefaultTimeout = 15 * time.Second
+
+// hermesDiscoveryTimeout is sized to hermes' failure path, not its success
+// path. See acpDiscoveryProvider.timeout: a configured hermes returns its
+// catalog in ~2s, but one that cannot resolve its provider — the case that
+// actually needs to be reported — spends ~25s getting there. At the default 15s
+// the user would be told "context deadline exceeded" instead of the exact
+// command hermes wants them to run.
+//
+// Kept well below the server's 60s modelListRunningTimeout so discovery leaves
+// time for report delivery and retry backoffs before the request closes.
+const hermesDiscoveryTimeout = 40 * time.Second
+
// acpDiscoveryProvider configures how discoverACPModels launches an
// ACP-speaking agent CLI. The shared helper drives every CLI in
// the same way (initialize → optional authenticate → session/new → parse
@@ -1752,6 +1829,17 @@ type acpDiscoveryProvider struct {
// ignores. CodeBuddy uses it to read its effort catalog out of the same
// handshake, which is why it needs no separate discovery call at all.
annotate func([]Model, json.RawMessage)
+ // timeout bounds the whole handshake — spawn, initialize, session/new.
+ // Zero means acpDiscoveryDefaultTimeout.
+ //
+ // It is per-provider because a CLI's UNHAPPY path is what has to fit, and
+ // that is the path with no shared shape: hermes answers a healthy
+ // session/new in ~2s but takes ~25s to conclude it cannot resolve a
+ // provider, because it re-probes before giving up (measured against hermes
+ // 0.20.0 — MUL-6606). A budget sized for the happy path turns every such
+ // diagnosis into "context deadline exceeded", which is the one failure text
+ // that tells the user nothing.
+ timeout time.Duration
// inspectInit receives the raw initialize result before any session is
// created. It is for reading capability facts the handshake already
// carries — Kimi reads `agentInfo.version` to gate a feature on the CLI
@@ -1780,7 +1868,11 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPr
if _, err := exec.LookPath(runtimeCmd.Path); err != nil {
return fail("executable lookup", err)
}
- runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
+ timeout := p.timeout
+ if timeout <= 0 {
+ timeout = acpDiscoveryDefaultTimeout
+ }
+ runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var isolatedStateDir string
if p.isolatedStateEnv != "" {
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index 389853418d..74f98c0ff4 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -785,10 +785,17 @@ func TestCopilotStaticModelsExposesFullCatalog(t *testing.T) {
}
func TestListModelsHermesWithoutBinary(t *testing.T) {
- // With no `hermes` binary on PATH the discovery fast-paths to
- // an empty list (the UI then falls back to creatable manual
- // entry). This test only verifies the fast-path; an actual
- // ACP session is exercised in integration.
+ // Hermes reports discovery failures instead of swallowing them into an
+ // empty list, unlike the kiro / qoder cases below (MUL-6606). Those two
+ // have a caller that substitutes something; hermes has no static catalog,
+ // so an empty list here would be indistinguishable from "this runtime
+ // genuinely has no models" and the picker would render it as an
+ // authoritative empty dropdown. The error keeps the picker in its
+ // discovery-failed state, which still offers manual entry — the same
+ // fallback, minus the false confidence.
+ //
+ // This test only verifies the executable-lookup fast path; an actual ACP
+ // session is exercised in hermes_model_discovery_test.go.
ctx := context.Background()
// Prime the cache miss so we hit the live discovery function.
modelCacheMu.Lock()
@@ -796,11 +803,16 @@ func TestListModelsHermesWithoutBinary(t *testing.T) {
modelCacheMu.Unlock()
got, err := ListModels(ctx, "hermes", Command{Path: missingAgentExecutable(t, "hermes")})
- if err != nil {
- t.Fatalf("ListModels(hermes) error: %v", err)
+ if err == nil {
+ t.Fatalf("expected a missing binary to be reported, got catalog %+v", got.Models)
}
- if got.Models == nil {
- t.Error("expected non-nil slice even when binary is missing")
+ if len(got.Models) != 0 {
+ t.Errorf("a failed discovery must carry no models, got %+v", got.Models)
+ }
+ // The reason has to name what actually went wrong: this text is what the
+ // daemon forwards as the request's error and what the picker displays.
+ if !strings.Contains(err.Error(), "executable lookup") {
+ t.Errorf("error should name the failing stage, got: %v", err)
}
}