fix(ai): retain configured default agent during failed discovery

This commit is contained in:
陈大猫 committed 2026-11-21 17:38:41 +08:00
1 parent f987341bf2
commit b864bf55b6
9 files changed
+100 -9

No files matched your search

+1
View File
@@ -333,6 +333,7 @@ export const enAiMessages: Messages = {
'ai.defaultAgent': 'Default Agent',
'ai.defaultAgent.description': 'Agent to use when starting a new AI session',
'ai.defaultAgent.catty': 'Catty (Built-in)',
'ai.defaultAgent.unavailable': 'Unavailable',
'ai.toolAccess.title': 'Tool Access',
'ai.toolAccess.mode': 'Netcatty Access Mode',
'ai.toolAccess.description': 'Choose how external agents access Netcatty sessions. MCP exposes the built-in server, while Skills + CLI points agents to the local Netcatty skill and CLI commands.',
+1
View File
@@ -333,6 +333,7 @@ export const esAiMessages: Messages = {
'ai.defaultAgent': 'Agente predeterminado',
'ai.defaultAgent.description': 'Agente que se usará al iniciar una nueva sesión de IA',
'ai.defaultAgent.catty': 'Catty (Integrado)',
'ai.defaultAgent.unavailable': 'No disponible',
'ai.toolAccess.title': 'Acceso a herramientas',
'ai.toolAccess.mode': 'Modo de acceso de Netcatty',
'ai.toolAccess.description': 'Elige cómo acceden los agentes externos a las sesiones de Netcatty. MCP expone el servidor integrado, mientras que Habilidades + CLI apunta a los agentes hacia las habilidades locales de Netcatty y los comandos de CLI.',
+1
View File
@@ -273,6 +273,7 @@ export const ruAiMessages: Messages = {
'ai.defaultAgent': 'Агент по умолчанию',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
'ai.defaultAgent.catty': 'Catty (встроенный)',
'ai.defaultAgent.unavailable': 'Недоступен',
'ai.toolAccess.title': 'Доступ к инструментам',
'ai.toolAccess.mode': 'Режим доступа Netcatty',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
+1
View File
@@ -333,6 +333,7 @@ export const zhCNAiMessages: Messages = {
'ai.defaultAgent': '默认 Agent',
'ai.defaultAgent.description': '创建新 AI 会话时使用的 Agent',
'ai.defaultAgent.catty': 'Catty(内置)',
'ai.defaultAgent.unavailable': '暂不可用',
'ai.toolAccess.title': '工具接入',
'ai.toolAccess.mode': 'Netcatty 接入模式',
'ai.toolAccess.description': '选择外部 Agent 访问 Netcatty 会话的方式。MCP 会暴露内置服务器,Skills + CLI 会引导 Agent 读取本地 Skill 并调用 Netcatty CLI。',
+1
View File
@@ -333,6 +333,7 @@ export const zhTWAiMessages: Messages = {
'ai.defaultAgent': '預設 Agent',
'ai.defaultAgent.description': '建立新 AI 工作階段時使用的 Agent',
'ai.defaultAgent.catty': 'Catty(內建)',
'ai.defaultAgent.unavailable': '暫時無法使用',
'ai.toolAccess.title': '工具介接',
'ai.toolAccess.mode': 'Netcatty 介接模式',
'ai.toolAccess.description': '選擇外部 Agent 存取 Netcatty 工作階段的方式。MCP 會公開內建伺服器,Skills + CLI 會引導 Agent 讀取本機 Skill 並呼叫 Netcatty CLI。',
+2 -1
View File
@@ -36,7 +36,7 @@ export const Toggle: React.FC<ToggleProps> = ({ checked, onChange, disabled, ari
interface SelectProps {
value: string;
options: { value: string; label: string; icon?: React.ReactNode }[];
options: { value: string; label: string; icon?: React.ReactNode; disabled?: boolean }[];
onChange: (value: string) => void;
className?: string;
disabled?: boolean;
@@ -87,6 +87,7 @@ export const Select: React.FC<SelectProps> = ({
<SelectPrimitive.Item
key={opt.value}
value={opt.value}
disabled={opt.disabled}
className="relative flex w-full min-w-0 cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
import React, { useCallback, useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import TestRenderer, { act } from "react-test-renderer";
import ts from "typescript";
import { canSendWithAgent } from "../../ai/agentSendEligibility";
import { buildManagedAgentState, getUnavailablePreferredHarness } from "./ai/managedAgentState";
import type { ExternalAgentConfig } from "../../../infrastructure/ai/types";
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -94,3 +97,61 @@ test("an older AI detection result cannot replace or finish the newer request",
assert.equal(h.state.busy, false);
} finally { await act(async () => h.root.unmount()); }
});
// Mount the same option computation and normalization effect that the
// Settings tab runs after a probe has updated the actual saved agent state.
const pickerStart = source.indexOf(" // Agent options for default agent");
const pickerEnd = source.indexOf("\n useEffect(() => {\n const bridge", pickerStart);
assert.ok(pickerStart >= 0 && pickerEnd > pickerStart);
const runDefaultPicker = vm.runInNewContext(ts.transpile(`(function(ctx) {
const { useMemo, useEffect, externalAgents, defaultAgentId, setDefaultAgentId, t,
canSendWithAgent, getUnavailablePreferredHarness, React, AgentIconBadge } = ctx;
${source.slice(pickerStart, pickerEnd)}
return agentOptions;
})`, { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }), { console }) as
(ctx: Record<string, unknown>) => { value: string; disabled?: boolean }[];
test("Settings retains the unavailable saved default, blocks sends and restores the same choice", async () => {
const agent: ExternalAgentConfig = {
id: "discovered_copilot",
name: "GitHub Copilot CLI",
command: "/fixture/copilot",
commandSource: "manual",
sdkBackend: "copilot",
enabled: true,
available: true,
};
let options: ReturnType<typeof runDefaultPicker> = [];
let choice = "";
function Harness({ agents }: { agents: ExternalAgentConfig[] }) {
const [defaultAgentId, setDefaultAgentId] = useState(agent.id);
options = runDefaultPicker({
useMemo, useEffect, externalAgents: agents, defaultAgentId, setDefaultAgentId,
t: (key: string) => key, canSendWithAgent, getUnavailablePreferredHarness, React,
AgentIconBadge: () => null,
});
choice = defaultAgentId;
return null;
}
const failed = buildManagedAgentState([agent], agent.id, "copilot", null, "manual");
const recovered = buildManagedAgentState(failed.agents, agent.id, "copilot", {
path: agent.command, available: true, version: "1.0.106",
}, "manual");
let root!: TestRenderer.ReactTestRenderer;
const render = (agents: ExternalAgentConfig[]) => React.createElement(Harness, { agents });
try {
await act(async () => { root = TestRenderer.create(render([agent])); });
await act(async () => { root.update(render(failed.agents)); });
assert.equal(choice, agent.id);
assert.equal(options.find(option => option.value === agent.id)?.disabled, true);
assert.equal(canSendWithAgent(choice, failed.agents), false);
await act(async () => { root.update(render(recovered.agents)); });
assert.equal(choice, agent.id);
assert.equal(options.find(option => option.value === agent.id)?.disabled, undefined);
assert.equal(canSendWithAgent(choice, recovered.agents), true);
const reset = buildManagedAgentState(recovered.agents, agent.id, "copilot", null, "auto");
await act(async () => { root.update(render(reset.agents)); });
assert.equal(choice, "catty");
} finally { await act(async () => root.unmount()); }
});
+17 -7
View File
@@ -68,6 +68,7 @@ import {
areExternalAgentListsEqual,
buildManagedAgentState,
getInitialManagedAgentPaths,
getUnavailablePreferredHarness,
updateCodebuddyManagedEnv,
updateCodebuddyManagedOptions,
} from "./ai/managedAgentState";
@@ -655,13 +656,22 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
[removeProvider, editingProviderId, removeProviderConfirm],
);
// Agent options for default agent
const agentOptions = useMemo(() => [
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
...externalAgents
.filter((a) => canSendWithAgent(a.id, externalAgents))
.map((a) => ({ value: a.id, label: a.name, icon: <AgentIconBadge agent={a} size="xs" variant="plain" /> })),
], [externalAgents, t]);
// Agent options for default agent. Include a saved default that is temporarily offline as a disabled option.
// This preserves the setting without offering that harness for new selections.
const agentOptions = useMemo(() => {
const unavailable = getUnavailablePreferredHarness(externalAgents, defaultAgentId);
return [
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
...externalAgents
.filter((a) => a === unavailable || canSendWithAgent(a.id, externalAgents))
.map((a) => ({
value: a.id,
label: a === unavailable ? `${a.name} (${t('ai.defaultAgent.unavailable')})` : a.name,
icon: <AgentIconBadge agent={a} size="xs" variant="plain" />,
disabled: a === unavailable ? true : undefined,
})),
];
}, [externalAgents, defaultAgentId, t]);
useEffect(() => {
if (!agentOptions.some((option) => option.value === defaultAgentId)) {
@@ -1,12 +1,26 @@
import type { ExternalAgentConfig } from "../../../../infrastructure/ai/types";
import {
type ManagedAgentKey,
getExternalAgentSdkBackend,
isPathLikeCommand,
} from "../../../../infrastructure/ai/managedAgents";
import type { AgentPathInfo } from "./types";
import { AGENT_DEFAULTS, isCursorAvailableForMode } from "./types";
import { buildCodebuddyEnv } from "./codebuddyConfigEnv";
/** A saved, enabled harness can remain preferred while its version probe fails. */
export function getUnavailablePreferredHarness(
agents: ExternalAgentConfig[],
defaultAgentId: string,
): ExternalAgentConfig | undefined {
return agents.find((agent) =>
agent.id === defaultAgentId &&
Object.keys(AGENT_DEFAULTS).some((key) => agent.id === `discovered_${key}`) &&
agent.enabled && agent.available === false &&
agent.commandSource !== "auto" && isPathLikeCommand(agent.command) &&
Boolean(getExternalAgentSdkBackend(agent)));
}
function getAutoManagedAgentStoredPath(
agents: ExternalAgentConfig[],
agentKey: ManagedAgentKey,