The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Desktop install card: parallel installs succeed, Try again enables a plugin on disk, a failed row stops blocking the turn (#129650)
Siddharth Balyan2c018e820027
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-connection.ts b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-connection.tsindex c0bb443a6dc..231558c5d68 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-connection.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-connection.ts@@ -2,6 +2,7 @@ import { type ChatMessage, type GatewayEventPayload, restorePendingBlockingToolCimport {$connectionRequests,clearConnectionRequest,+ CONNECTION_OP_ARG,type ConnectionRequest,isCatalogRequest,normalizeConnectionRequest,@@ -56,11 +57,16 @@ export function restorePendingConnectionFromSnapshot(return { authoritativeAbsent: false, cleared: null, request }}-/** Tool row for a pending operation whose `tool.start` event was missed. */+/** Tool row for a pending operation (upserted onto the `tool.start` row when that arrived). The row keeps+ * the op id, so its card stays this operation's after a later call reuses the call id. */export function connectionRequestToolPayload(request: ConnectionRequest): GatewayEventPayload & { name: string } {if (isCatalogRequest(request)) {return {- args: { action: 'install', items: request.targets.map(target => ({ id: target.name, kind: target.kind })) },+ args: {+ action: 'install',+ items: request.targets.map(target => ({ id: target.name, kind: target.kind })),+ [CONNECTION_OP_ARG]: request.opId+ },name: 'manage_catalog',tool_id: request.toolCallId}@@ -69,7 +75,8 @@ export function connectionRequestToolPayload(request: ConnectionRequest): Gatewareturn {args: {action: request.targets[0]?.action ?? (request.targets[0]?.kind === 'connector' ? 'connect' : 'install'),- connectors: request.targets.map(target => ({ mcp: target.kind === 'mcp', name: target.name }))+ connectors: request.targets.map(target => ({ mcp: target.kind === 'mcp', name: target.name })),+ [CONNECTION_OP_ARG]: request.opId},name: 'manage_connections',tool_id: request.toolCallIddiff --git a/apps/desktop/src/components/assistant-ui/catalog-install-tool.tsx b/apps/desktop/src/components/assistant-ui/catalog-install-tool.tsxindex 4f8f34c378e..a12711b247f 100644--- a/apps/desktop/src/components/assistant-ui/catalog-install-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/catalog-install-tool.tsx@@ -4,11 +4,7 @@ import { useMemo, useRef, useState } from 'react'import { useSessionView } from '@/app/chat/session-view'import { CatalogAdvancedDialog } from '@/components/assistant-ui/catalog-advanced-dialog'-import {- connectionRequestOwnsPart,- CONNECTOR_CARD_PHASES,- useConnectorFocusHandoff-} from '@/components/assistant-ui/connector-tool'+import { connectionRequestOwnsPart, useConnectorFocusHandoff } from '@/components/assistant-ui/connector-tool'import { ToolFallback } from '@/components/assistant-ui/tool/fallback'import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'import { Button } from '@/components/ui/button'@@ -16,14 +12,19 @@ import { Progress } from '@/components/ui/progress'import { useI18n } from '@/i18n'import { Book, Loader2, Plug } from '@/lib/icons'import { cn } from '@/lib/utils'+import { installAgentPlugin } from '@/store/agent-plugins'import {type CatalogEntry,+ catalogRowResolved,+ connectionOpOf,+ connectionOwnerFor,type ConnectionRequest,type ConnectionTarget,continueConnectionRequest,respondToConnectionRequest,toolConnectionRequest} from '@/store/connection-request'+import { requestGatewayForAgent } from '@/store/gateway'import { notifyError } from '@/store/notifications'import { profileLabel } from '@/store/profile'@@ -62,7 +63,14 @@ export function CatalogInstallTool(props: ToolCallMessagePartProps) {const { t } = useI18n()const view = useSessionView()const runtimeId = useStore(view.$runtimeId)- const $request = useMemo(() => toolConnectionRequest(runtimeId, props.toolCallId), [props.toolCallId, runtimeId])+ const opId = connectionOpOf(props.args)+ const running = props.result === undefined++ const $request = useMemo(+ () => toolConnectionRequest(runtimeId, props.toolCallId, opId, running),+ [opId, props.toolCallId, running, runtimeId]+ )+const request = useStore($request)if (request && connectionRequestOwnsPart(props, request)) {@@ -86,7 +94,7 @@ export function CatalogInstallCard({ request }: { request: ConnectionRequest })const { t } = useI18n()const cardRef = useRef<HTMLDivElement | null>(null)const rows = request.targets.filter(isCatalogTarget)- const unresolved = rows.some(target => !CONNECTOR_CARD_PHASES[target.state].resolved)+ const unresolved = rows.some(target => !catalogRowResolved(target.state))const profile = rows[0]?.catalog.targetProfile ?? 'default'useConnectorFocusHandoff(request.targets, cardRef)@@ -121,27 +129,63 @@ export function CatalogRow({ request, target }: CatalogRowProps) {const copy = t.assistant.catalogInstallconst { catalog } = targetconst [advancedOpen, setAdvancedOpen] = useState(false)- // The operation's seq when an answer was sent; the verbs stay held until a newer frame answers it,- // so a second click cannot send the answer twice.- const [sentAtSeq, setSentAtSeq] = useState<null | number>(null)- const sending = sentAtSeq !== null && request.seq <= sentAtSeq+ // The operation and seq an answer was sent at; the verbs stay held until a newer frame of that+ // operation answers it, so a second click cannot send the answer twice. Keyed by op so a seq from+ // another operation can never hold this row.+ const [sentAt, setSentAt] = useState<null | { opId: string; seq: number }>(null)+ // Try again on a failed plugin row after the operation settled: a fresh host install (which enables a+ // plugin already on disk). The settled operation is frozen, so the row shows this outcome over it.+ const [retry, setRetry] = useState<null | { detail: string; status: 'failed' | 'installed' | 'running' }>(null)+ const sending = (sentAt?.opId === request.opId && request.seq <= sentAt.seq) || retry?.status === 'running'const Glyph = KIND_GLYPH[target.kind]const answer = async (status: 'approved' | 'skipped', env: Record<string, string> | null = null) => {- setSentAtSeq(request.seq)+ setSentAt({ opId: request.opId, seq: request.seq })try {const sent = await respondToConnectionRequest(request, { targets: [{ env, name: target.name, status }] })if (!sent) {- setSentAtSeq(null)+ setSentAt(null)}} catch (error) {notifyError(error, copy.sendFailed)- setSentAtSeq(null)+ setSentAt(null)}}+ const retrySettled = async () => {+ setRetry({ detail: '', status: 'running' })+ const owner = request.sessionId ? await connectionOwnerFor(request.sessionId, 'plugins.manage') : null++ const result = await installAgentPlugin(+ (method, params, timeoutMs) =>+ requestGatewayForAgent(+ owner?.connectionId ?? null,+ owner?.profile ?? catalog.targetProfile,+ method,+ params,+ timeoutMs+ ),+ { catalogName: target.name, identifier: '', profile: catalog.targetProfile }+ )++ setRetry(result.ok ? { detail: '', status: 'installed' } : { detail: result.error ?? '', status: 'failed' })+ }++ const shown: CatalogTarget =+ retry?.status === 'installed'+ ? { ...target, detail: '', state: 'connected' }+ : retry?.status === 'failed'+ ? { ...target, detail: retry.detail || target.detail }+ : target++ const onRetry = !request.settled+ ? () => void answer('approved')+ : target.kind === 'plugin'+ ? () => void retrySettled()+ : undefined+return (<div className={cn(SHELL_CLASS, 'grid min-w-0 gap-1.5')} data-connector-row={target.name} tabIndex={-1}><div className="flex min-w-0 items-start gap-3">@@ -177,12 +221,13 @@ export function CatalogRow({ request, target }: CatalogRowProps) {copy={copy}onAdvanced={() => setAdvancedOpen(true)}onInstall={() => void answer('approved')}+ onRetry={onRetry}onSkip={() => void answer('skipped')}retryLabel={t.connectors.retry}sending={sending}settled={request.settled}skippedLabel={t.connectors.skipped}- target={target}+ target={shown}toolCount={t.assistant.mcpSetup.toolCount}/></div>@@ -206,6 +251,8 @@ interface RowOutcomeProps {copy: CatalogCopyonAdvanced: () => voidonInstall: () => void+ /** Try again on a failed row; absent when nothing can run it again. */+ onRetry?: () => voidonSkip: () => voidretryLabel: stringsending: boolean@@ -220,6 +267,7 @@ function RowOutcome({copy,onAdvanced,onInstall,+ onRetry,onSkip,retryLabel,sending,@@ -276,18 +324,18 @@ function RowOutcome({<p className={cn(CAPTION, 'min-w-0 text-destructive wrap-anywhere')} role="status">{target.detail ? `${copy.failed} · ${target.detail}` : copy.failed}</p>- {settled ? null : (+ {onRetry ? (<ButtonclassName="h-6 px-1.5 text-(--ui-text-tertiary)"disabled={sending}loading={sending}- onClick={onInstall}+ onClick={onRetry}size="xs"variant="ghost">{retryLabel}</Button>- )}+ ) : null}</div>)}diff --git a/apps/desktop/src/components/assistant-ui/connector-tool.tsx b/apps/desktop/src/components/assistant-ui/connector-tool.tsxindex b347beb539d..d174ab2364a 100644--- a/apps/desktop/src/components/assistant-ui/connector-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/connector-tool.tsx@@ -20,6 +20,7 @@ import {} from '@/lib/connector-tools'import {$connectionRequests,+ connectionOpOf,type ConnectionOwner,connectionOwnerFor,type ConnectionRequest,@@ -148,7 +149,14 @@ export function ConnectorTool(props: ToolCallMessagePartProps) {const view = useSessionView()const runtimeId = useStore(view.$runtimeId)const storedId = useStore(view.$storedId)- const $request = useMemo(() => toolConnectionRequest(runtimeId, props.toolCallId), [props.toolCallId, runtimeId])+ const opId = connectionOpOf(props.args)+ const running = props.result === undefined++ const $request = useMemo(+ () => toolConnectionRequest(runtimeId, props.toolCallId, opId, running),+ [opId, props.toolCallId, running, runtimeId]+ )+const request = useStore($request)const targetNames = requestedConnectorNames(props.args)diff --git a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsxindex e3d2875d852..10beb6ae512 100644--- a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx@@ -24,6 +24,7 @@ import { Loader2 } from '@/lib/icons'import { prettyName } from '@/lib/text'import { cn } from '@/lib/utils'import {+ connectionOpOf,type ConnectionOwner,type ConnectionRequest,type ConnectionTarget,@@ -189,7 +190,14 @@ export function McpSetupPending(props: ToolCallMessagePartProps) {const sessionId = useStore(view.$runtimeId)// Owner routes and hints are keyed by the stored id, not the runtime id the events carry.const storedId = useStore(view.$storedId)- const $request = useMemo(() => toolConnectionRequest(sessionId, props.toolCallId), [props.toolCallId, sessionId])+ const opId = connectionOpOf(props.args)+ const running = props.result === undefined++ const $request = useMemo(+ () => toolConnectionRequest(sessionId, props.toolCallId, opId, running),+ [opId, props.toolCallId, running, sessionId]+ )+const request = useStore($request)const action = useMemo(() => readSetupAction(props.args), [props.args])// The session's operation belongs to one tool call; another call's request never paints here.diff --git a/apps/desktop/src/store/connection-request.ts b/apps/desktop/src/store/connection-request.tsindex 7210effde0d..3c3bd3dc82f 100644--- a/apps/desktop/src/store/connection-request.ts+++ b/apps/desktop/src/store/connection-request.ts@@ -17,6 +17,7 @@ import { atom, computed } from 'nanostores'import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'import type { SetupField } from '@/components/ui/setup-field-list'+import { recordOf } from '@/lib/connector-tools'import { $gateway, requestGatewayForAgent } from './gateway'import { $activeGatewayProfile } from './profile'@@ -90,7 +91,8 @@ export interface ConnectionOwner {}export interface ConnectionRequest {- /** The model's tool call that opened the operation. The card lives on that row and no other. */+ /** The model's tool call that opened the operation. Call ids repeat across turns, so the row names its+ * card by op id (`CONNECTION_OP_ARG`); the call id is only the fallback for a row without one. */toolCallId: stringopId: string/** The sequence of the newest frame this cache holds; an older frame for the same op is dropped. */@@ -109,18 +111,47 @@ const keyFor = (sessionId: string | null | undefined): string => sessionId ?? ''export const $connectionRequests = atom<Record<string, ConnectionRequest>>({})-/** The settled operation of the other card kind that the session's current operation replaced. One turn- * can ask twice (an install card and a connect card, either order) and both cards stay drawn; a later- * operation of the same kind still replaces its card, so consecutive connect calls show one card. */-const $replacedConnectionRequests = atom<Record<string, ConnectionRequest>>({})+/** Settled operations the session's current one replaced, oldest first. Their cards stay drawn on the+ * rows that opened them: every settled install card, and the last settled connect card when the current+ * operation is an install one. A later connect operation still replaces the connect card, so consecutive+ * connect calls show one card. */+const $keptConnectionRequests = atom<Record<string, ConnectionRequest[]>>({})-/** The operation a tool row draws: the session's current one when this row opened it, else the replaced- * one when this row opened that. */-export const toolConnectionRequest = (sessionId: string | null, toolCallId: string) =>- computed([$connectionRequests, $replacedConnectionRequests], (requests, replaced) => {+/** The key a tool row's args carry its operation id under, written when `connection.request` arrives.+ * Models reuse call ids (`call_0` on every turn), so the op id, not the call id, names a row's card. */+export const CONNECTION_OP_ARG = 'hermes_connection_op'++export const connectionOpOf = (args: unknown): null | string => {+ const value = recordOf(args as never)[CONNECTION_OP_ARG]++ return typeof value === 'string' && value ? value : null+}++/** The operation a tool row draws. A row that carries an op id draws that operation and no other. A row+ * without one (history loaded from disk, or a call whose request has not arrived yet) falls back to its+ * call id, but only when a single known operation has that id, and a running row never takes a settled+ * one: that is an earlier call's card. */+export const toolConnectionRequest = (+ sessionId: string | null,+ toolCallId: string,+ opId: null | string,+ running: boolean+) =>+ computed([$connectionRequests, $keptConnectionRequests], (requests, kept) => {const key = keyFor(sessionId)- return [requests[key], replaced[key]].find(request => request?.toolCallId === toolCallId) ?? null+ const known = [requests[key], ...(kept[key] ?? [])].filter((request): request is ConnectionRequest =>+ Boolean(request)+ )++ if (opId) {+ return known.find(request => request.opId === opId) ?? null+ }++ const matches = known.filter(request => request.toolCallId === toolCallId)+ const only = matches.length === 1 ? matches[0] : null++ return only && !(running && only.settled) ? only : null})const TARGET_STATES: readonly ConnectionTargetState[] = [@@ -151,6 +182,11 @@ const settleReason = oneOf(SETTLE_REASONS)export const isCatalogKind = (kind: ConnectionTargetKind): kind is 'plugin' | 'skill' =>kind === 'plugin' || kind === 'skill'+/** A catalog row is done once it installed, was skipped or failed: the backend settles the operation+ * then, so a failed row never holds the turn (`tools/connectors/contract.py::resolves`). */+export const catalogRowResolved = (state: ConnectionTargetState): boolean =>+ state === 'connected' || state === 'skipped' || state === 'failed'+/** A `manage_catalog` install operation, as opposed to a `manage_connections` one. */export const isCatalogRequest = (request: ConnectionRequest): boolean =>request.targets.some(target => isCatalogKind(target.kind))@@ -323,11 +359,15 @@ export function setConnectionRequest(request: ConnectionRequest): void {const requests = $connectionRequests.get()const previous = requests[key]- if (previous && previous.opId !== request.opId && isCatalogRequest(previous) !== isCatalogRequest(request)) {- const replaced = { ...$replacedConnectionRequests.get() }- delete replaced[key]+ if (previous && previous.opId !== request.opId) {+ const catalog = isCatalogRequest(request)+ const stays = (entry: ConnectionRequest) => isCatalogRequest(entry) || isCatalogRequest(entry) !== catalog+ const kept = ($keptConnectionRequests.get()[key] ?? []).filter(entry => entry.opId !== request.opId && stays(entry))- $replacedConnectionRequests.set(previous.settled ? { ...replaced, [key]: previous } : replaced)+ $keptConnectionRequests.set({+ ...$keptConnectionRequests.get(),+ [key]: previous.settled && stays(previous) ? [...kept, previous] : kept+ })}$connectionRequests.set({ ...requests, [key]: request })@@ -353,13 +393,21 @@ export function clearConnectionRequest(opId?: string, sessionId?: string | null)const cleared = ([key, value]: [string, ConnectionRequest]) =>(sessionId === undefined || key === keyFor(sessionId)) && (!opId || value.opId === opId)- for (const store of [$connectionRequests, $replacedConnectionRequests]) {- const entries = Object.entries(store.get())- const kept = entries.filter(entry => !cleared(entry))+ const entries = Object.entries($connectionRequests.get())+ const current = entries.filter(entry => !cleared(entry))- if (kept.length !== entries.length) {- store.set(Object.fromEntries(kept))- }+ if (current.length !== entries.length) {+ $connectionRequests.set(Object.fromEntries(current))+ }++ const keptBefore = $keptConnectionRequests.get()++ const keptAfter = Object.fromEntries(+ Object.entries(keptBefore).map(([key, list]) => [key, list.filter(request => !cleared([key, request]))])+ )++ if (Object.keys(keptBefore).some(key => keptAfter[key].length !== keptBefore[key].length)) {+ $keptConnectionRequests.set(keptAfter)}}diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex a517e1c55f2..66099853b33 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -11,10 +11,11 @@ import loggingimport osimport shutilimport sys+import threadingfrom pathlib import Pathfrom typing import Any, NoReturn, Optional-from hermes_constants import get_hermes_home+from hermes_constants import get_hermes_home, hermes_home_keyfrom hermes_cli.config import cfg_getfrom hermes_cli.plugin_capabilities import _child_dict# Tests patch these two on the facade; the install/remove siblings read them through it.@@ -585,19 +586,32 @@ def _forget_plugin_config(aliases: set) -> dict[str, Any]:return result+# One lock per Hermes home. The Desktop install card enables several plugins at once, each on its own+# thread; without it every thread read the same config version and all but the first commit were+# refused as stale. The version check in PM stays: it still catches an edit from another process.+_SELECTION_LOCKS: dict[str, threading.Lock] = {}+_SELECTION_LOCKS_GUARD = threading.Lock()+++def _selection_lock() -> threading.Lock:+ with _SELECTION_LOCKS_GUARD:+ return _SELECTION_LOCKS.setdefault(hermes_home_key(), threading.Lock())++def _set_plugin_enabled(name: str, *, enable: bool, aliases=(), console=None) -> None:"""Submit the command's delta with the version of the selection it read."""from pm.plugins_state import read_home_selection- expected_config = _plugin_selection_version()- config = read_home_selection(get_hermes_home()) or {}- plugins = config.get("plugins") or {}- enabled = set(plugins.get("enabled") or ())- disabled = set(plugins.get("disabled") or ())- _apply_activation(enabled, disabled, name, aliases, enable=enable)- _admit_and_save_plugin_sets(enabled, disabled, console=console,- action=f"{'Enable' if enable else 'Disable'} '{name}'",- expected_config=expected_config, plugin=name if enable else None)+ with _selection_lock():+ expected_config = _plugin_selection_version()+ config = read_home_selection(get_hermes_home()) or {}+ plugins = config.get("plugins") or {}+ enabled = set(plugins.get("enabled") or ())+ disabled = set(plugins.get("disabled") or ())+ _apply_activation(enabled, disabled, name, aliases, enable=enable)+ _admit_and_save_plugin_sets(enabled, disabled, console=console,+ action=f"{'Enable' if enable else 'Disable'} '{name}'",+ expected_config=expected_config, plugin=name if enable else None)def _apply_activation(enabled: set, disabled: set, key: str, aliases, *, enable: bool) -> None:diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.pyindex 6c196487276..800b4d11d47 100644--- a/hermes_cli/plugins_cmd_install.py+++ b/hermes_cli/plugins_cmd_install.py@@ -560,6 +560,23 @@ def cmd_install(console.print()+def _catalog_install_on_disk(catalog_name: str) -> Optional[tuple]:+ """``(target, manifest, installed_name)`` of the installed, not enabled tree whose install record+ names catalog entry *catalog_name*, else None. A refused enable leaves the published clone in+ place (there is no rollback), so the card's Try again, or the model asking again, stopped at+ "already exists" on a second clone and the plugin could never be turned on from the card."""+ enabled = _pc()._get_enabled_set()+ for key, record in _pc()._read_install_metadata().items():+ block = record.get("catalog") if isinstance(record, dict) else None+ target = _pc()._plugins_dir() / key+ if not (isinstance(block, dict) and block.get("name") == catalog_name and target.is_dir()):+ continue+ manifest = _pc()._read_manifest(target)+ installed_name = manifest.get("name") or target.name+ return None if {installed_name, target.name} & enabled else (target, manifest, installed_name)+ return None++def dashboard_install_plugin(identifier: str, *, force: bool, enable: bool, catalog_name: Optional[str] = None,ref: Optional[str] = None, on_step: Optional[Callable[[str], None]] = None,@@ -594,10 +611,15 @@ def dashboard_install_plugin(return catalog.install_catalog_entry(entry, force=force, allow_removed=False)return _pc()._install_plugin_core(identifier, force=force, ref=(ref or "").strip() or None)- step("Downloading…")try:- target, installed_manifest, installed_name = recorded_install(- _install, catalog_name=entry.name if entry is not None else None, identifier=identifier)+ on_disk = _catalog_install_on_disk(entry.name) if entry is not None and not force else None+ if on_disk is not None:+ # An earlier enable was refused after the clone landed: enable the tree that is there.+ target, installed_manifest, installed_name = on_disk+ else:+ step("Downloading…")+ target, installed_manifest, installed_name = recorded_install(+ _install, catalog_name=entry.name if entry is not None else None, identifier=identifier)except _pc().PluginScanBlocked as exc:fields = ("pattern_id", "severity", "category", "file", "line", "description")return {diff --git a/tests/tools/test_connectors_catalog.py b/tests/tools/test_connectors_catalog.pyindex d94b98ae50c..c94d6faef12 100644--- a/tests/tools/test_connectors_catalog.py+++ b/tests/tools/test_connectors_catalog.py@@ -122,15 +122,15 @@ def test_off_the_desktop_the_result_points_at_the_cli_and_opens_no_card():assert not card.seen and not installer.installs and live.current("s1") is None-def test_unknown_and_unsupported_ids_are_drawn_failed_and_never_installed():+def test_unknown_and_unsupported_ids_fail_at_once_with_the_reason_and_are_never_installed():installer = FakeInstaller([_entry("nvidia-app", platforms=["windows"])],refuse={"nvidia-app": "Plugin 'nvidia-app' is unavailable on darwin; ""supported platforms: windows."})card = _card(lambda payload: {"settled_by": "continue"})out = _install([{"kind": "plugin", "id": "nope"}, {"kind": "plugin", "id": "nvidia-app"}], installer, card)- drawn = {t["name"]: t for t in card.seen[0]["targets"]}- assert {t["state"] for t in drawn.values()} == {TargetState.failed.value} # drawn with the reason+ assert not card.seen # every row is already done: the model reads the reasons, no card waitsrows = {t["name"]: t for t in out["targets"]}+ assert {t["state"] for t in rows.values()} == {TargetState.failed.value}assert "catalog" in rows["nope"]["detail"]assert "unavailable on darwin" in rows["nvidia-app"]["detail"]assert rows["nvidia-app"]["display"] == "Nvidia App" and rows["nvidia-app"]["platforms"] == ["windows"]@@ -173,30 +173,39 @@ def test_advanced_values_pick_the_profile_force_and_pin(tmp_path):assert "not enabled" in row["detail"]-def test_a_failed_install_stays_failed_until_the_user_tries_again():- installer = FakeInstaller([_entry("blender")], install_error="clone failed: network down")- attempts = []+def test_a_failed_row_keeps_its_reason_and_try_again_works_while_the_card_is_open():+ installer = FakeInstaller([_entry("blender"), _entry("krita")], install_error="clone failed: network down")+ card = _card(lambda payload: {"targets": [{"name": "blender", "status": "approved", "env": None}]})- def answer(payload):- (target,) = payload["targets"]- attempts.append(target["state"])- return {"targets": [{"name": "blender", "status": "approved", "env": None}]}+ def wait_for(state):+ for _ in range(200):+ operation = live.current("s1")+ if operation is not None and operation.targets[0].state == state:+ return operation+ threading.Event().wait(0.01)+ raise AssertionError(f"blender never reached {state}")- card = _card(answer)with patch("tools.connectors.run.WATCH_INTERVAL_SECONDS", 0.01):result = {}thread = threading.Thread(target=lambda: result.setdefault("out", json.loads(manage_catalog(- {"action": "install", "items": [{"kind": "plugin", "id": "blender"}]}, session_id="s1",- connection_callback=card, card_surface=True, installer=installer))))+ {"action": "install", "items": [{"kind": "plugin", "id": "blender"}, {"kind": "plugin", "id": "krita"}]},+ session_id="s1", connection_callback=card, card_surface=True, installer=installer))))thread.start()- for _ in range(200):- operation = live.current("s1")- if operation is not None and operation.targets[0].state == TargetState.failed:- break- threading.Event().wait(0.01)+ operation = wait_for(TargetState.failed)assert operation.targets[0].detail == "clone failed: network down"+ assert not operation.settled # krita still waits on the userinstaller.install_error = ""apply_answer(operation, json.dumps({"targets": [{"name": "blender", "status": "approved"}]}))+ wait_for(TargetState.connected)+ apply_answer(operation, json.dumps({"targets": [{"name": "krita", "status": "skipped"}]}))thread.join(5)assert result["out"]["targets"][0]["state"] == TargetState.connected.valueassert len(installer.installs) == 2++ # A failed row does not hold the turn to the deadline: once it is the last open row, the+ # operation settles and the row keeps its state and reason.+ installer.install_error = "clone failed: network down"+ out = _install([{"kind": "plugin", "id": "blender"}], installer, _card(_approve()))+ (row,) = out["targets"]+ assert out["settled_by"] == "all_resolved"+ assert (row["state"], row["detail"]) == (TargetState.failed.value, "clone failed: network down")diff --git a/tools/connectors/catalog_tool.py b/tools/connectors/catalog_tool.pyindex a333e5e3639..4765db246cc 100644--- a/tools/connectors/catalog_tool.py+++ b/tools/connectors/catalog_tool.py@@ -38,9 +38,10 @@ MANAGE_CATALOG_SCHEMA = {"description": ("Find and install Hermes catalog plugins and hub skills for the user. 'search' lists matches ""(id, kind, display, tier, platforms, installed) and changes nothing. 'install' shows the user "- "one approval card with a row per item and blocks until every row is installed, skipped, or "- "the card is closed; the host installs each approved row into this chat's profile at "- "the catalog's reviewed version. Pass only catalog ids exactly as 'search' returns them; the "+ "one approval card with a row per item and blocks until every row is installed, skipped or "+ "failed, or the card is closed; the host installs each approved row into this chat's profile at "+ "the catalog's reviewed version, and turns on a catalog plugin that is installed but not "+ "enabled. Pass only catalog ids exactly as 'search' returns them; the ""host decides the source, version, profile and settings, and the user can change them on the ""card. Offer an install only for something the user asked for or agreed to."),diff --git a/tools/connectors/contract.py b/tools/connectors/contract.pyindex cc45e12ece0..442abc335ca 100644--- a/tools/connectors/contract.py+++ b/tools/connectors/contract.py@@ -36,6 +36,15 @@ class SettleReason(str, Enum):KINDS: Tuple[str, ...] = ("connector", "mcp", "plugin", "skill")RESOLVED_STATES = frozenset({TargetState.connected, TargetState.skipped})+# A failed catalog row is done as well: the host already ran the install and the row carries the+# reason. Counting it as open held the model's turn until the deadline while nobody clicked. Try+# again still works while another row keeps the operation open, and the failed row keeps its state+# and reason when the operation settles.+_RESOLVED_BY_KIND = {kind: RESOLVED_STATES | {TargetState.failed} for kind in ("plugin", "skill")}+++def resolves(kind: str, state: TargetState) -> bool:+ return state in _RESOLVED_BY_KIND.get(kind, RESOLVED_STATES)_S, _A = TargetState, Actordiff --git a/tools/connectors/operation.py b/tools/connectors/operation.pyindex f908da5d367..2e8d3ebfd20 100644--- a/tools/connectors/operation.py+++ b/tools/connectors/operation.py@@ -8,7 +8,7 @@ import uuidfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, ClassVar, Dict, List, Optional-from tools.connectors.contract import RESOLVED_STATES, Actor, SettleReason, TargetState, allowed+from tools.connectors.contract import Actor, SettleReason, TargetState, allowed, resolves# Not a config key: a user-tunable wait with clamp rails was a foot-gun (PR1 shipped one, unmerged).OPERATION_DEADLINE_SECONDS = 300.0@@ -42,7 +42,7 @@ class Target:@propertydef resolved(self) -> bool:- return self.state in RESOLVED_STATES+ return resolves(self.kind, self.state)def snapshot(self, *, with_url: bool = True) -> Dict[str, Any]:out: Dict[str, Any] = {"name": self.name, "kind": self.kind, "action": self.action, "state": self.state.value}