diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vue index 5daf723a4d..8fdba78999 100644 --- a/apps/desktop/src/components/editor/AiAssistant.vue +++ b/apps/desktop/src/components/editor/AiAssistant.vue @@ -160,6 +160,19 @@ const isGenerating = ref(false); const scrollRef = ref | null>(null); const activeAction = ref("general"); const assistantMode = ref("ask"); +// The selection is loaded asynchronously. Apply it once when this panel mounts, +// but do not let later setting changes alter an active conversation. +let defaultModeInitialized = false; +watch( + () => settings.isAiConfigLoaded, + (loaded) => { + if (loaded && !defaultModeInitialized) { + assistantMode.value = settings.defaultAiMode; + defaultModeInitialized = true; + } + }, + { immediate: true }, +); const currentSessionId = ref(""); const conversationId = ref(""); const conversations = ref([]); @@ -2030,9 +2043,10 @@ async function deleteConversation(id: string) { function startNewChat() { clearMessages(); showConversationList.value = false; - // A fresh conversation always starts from the safe, non-executing default. - assistantMode.value = "ask"; - activeAction.value = resolveDefaultAction("ask"); + // A fresh conversation starts from the configured default mode. + const mode = settings.defaultAiMode; + assistantMode.value = mode; + activeAction.value = resolveDefaultAction(mode); } onMounted(async () => { diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue index cda24bc377..b1a95cb2a1 100644 --- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue +++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue @@ -5549,6 +5549,30 @@ onUnmounted(() => { + +
+ +
+

+ {{ t("ai.defaultAiMode") }} +

+

+ {{ t("ai.defaultAiModeDescription") }} +

+
+
+
+ + +
+
+
+
+
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index e41e1ec46c..999ce81f76 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -2295,6 +2295,8 @@ export default { maxAgentTurnsDescription: "Maximum tool-call turns per API agent run before it pauses and asks you to continue. CLI providers use their own run limits.", maxAgentTurnsRange: "{min}–{max}, default {default}", maxAgentTurnsSaved: "Agent turn limit saved", + defaultAiMode: "Default AI Mode", + defaultAiModeDescription: "Mode used when starting a new AI conversation. Switching mode in the current conversation does not change this setting.", promptTemplates: "Scenario Prompt Templates", promptTemplatesDescription: "Select one or more templates in the AI assistant to inject scenario-specific conventions.", promptTemplateNew: "New Template", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index f3f6b59880..5a7f6de1e4 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -2161,6 +2161,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "Máximo de turnos de llamadas a herramientas por ejecución del agente API antes de pausar y pedir continuar. Los proveedores CLI usan sus propios límites.", maxAgentTurnsRange: "{min}–{max}, predeterminado {default}", maxAgentTurnsSaved: "Límite de turnos del agente guardado", + defaultAiMode: "Modo de IA predeterminado", + defaultAiModeDescription: "Modo usado al iniciar una nueva conversación de IA. Cambiar de modo en la conversación actual no modifica esta configuración.", promptTemplates: "Plantillas de prompt por escenario", promptTemplatesDescription: "Selecciona una o más plantillas en el asistente de IA para inyectar convenciones específicas del escenario.", promptTemplateNew: "Nueva plantilla", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index d578052630..2d4055f1b2 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -2083,6 +2083,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "Numero massimo di turni di chiamate agli strumenti per esecuzione dell'agente API prima di mettere in pausa e chiedere di continuare. I provider CLI usano limiti propri.", maxAgentTurnsRange: "{min}–{max}, predefinito {default}", maxAgentTurnsSaved: "Limite di turni dell'agente salvato", + defaultAiMode: "Modalità IA predefinita", + defaultAiModeDescription: "Modalità usata all'avvio di una nuova conversazione IA. Cambiare modalità nella conversazione corrente non modifica questa impostazione.", promptTemplates: "Modelli di prompt per scenario", promptTemplatesDescription: "Seleziona uno o più modelli nell'assistente AI per inserire convenzioni specifiche dello scenario.", promptTemplateNew: "Nuovo modello", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 27201d5397..4fa58e6701 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -2195,6 +2195,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "1回のAPIエージェント実行あたりの最大ツール呼び出しターン数。超過すると一時停止し、続行を求めます。CLIプロバイダーは独自の実行制限を使用します。", maxAgentTurnsRange: "{min}–{max}、デフォルト {default}", maxAgentTurnsSaved: "エージェントターン上限を保存しました", + defaultAiMode: "既定の AI モード", + defaultAiModeDescription: "新しい AI 会話を開始するときに使用されるモードです。現在の会話でモードを切り替えてもこの設定は変更されません。", promptTemplates: "シナリオプロンプトテンプレート", promptTemplatesDescription: "AIアシスタントで1つ以上のテンプレートを選択し、シナリオ固有の規約を注入します。", promptTemplateNew: "新規テンプレート", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index 22fc66175c..19c5d6475f 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -2152,6 +2152,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "API 에이전트 실행 중 일시 중지하고 계속할지 묻기 전의 최대 도구 호출 턴 수입니다. CLI 공급자는 자체 실행 제한을 사용합니다.", maxAgentTurnsRange: "{min}–{max}, 기본 {default}", maxAgentTurnsSaved: "에이전트 턴 제한을 저장했습니다", + defaultAiMode: "기본 AI 모드", + defaultAiModeDescription: "새 AI 대화를 시작할 때 사용되는 모드입니다. 현재 대화에서 모드를 전환해도 이 설정은 변경되지 않습니다.", promptTemplates: "시나리오 프롬프트 템플릿", promptTemplatesDescription: "AI 어시스턴트에서 하나 이상의 템플릿을 선택하여 시나리오별 규칙을 주입합니다.", promptTemplateNew: "새 템플릿", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 27d93eebf7..c56c5fb940 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -2163,6 +2163,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "Máximo de turnos de ferramentas por execução do agente de API antes de pausar e pedir para continuar. Provedores CLI usam seus próprios limites.", maxAgentTurnsRange: "{min}–{max}, padrão {default}", maxAgentTurnsSaved: "Limite de turnos do agente salvo", + defaultAiMode: "Modo de IA padrão", + defaultAiModeDescription: "Modo usado ao iniciar uma nova conversa de IA. Alterar o modo na conversa atual não altera esta configuração.", promptTemplates: "Modelos de prompt por cenário", promptTemplatesDescription: "Selecione um ou mais modelos no assistente de IA para injetar convenções específicas do cenário.", promptTemplateNew: "Novo modelo", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index d31bb8c741..5dce452c0f 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -2295,6 +2295,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "单次 API Agent 运行的最大工具调用回合数,超过后会暂停并提示继续。CLI 供应商使用各自的运行限制。", maxAgentTurnsRange: "{min}–{max},默认 {default}", maxAgentTurnsSaved: "Agent 回合上限已保存", + defaultAiMode: "默认 AI 模式", + defaultAiModeDescription: "新建 AI 对话时使用的模式。切换当前对话的模式不会修改此设置。", promptTemplates: "场景 Prompt 模板", promptTemplatesDescription: "在 AI 助手中选择一个或多个模板,注入场景化的约定规范。", promptTemplateNew: "新建模板", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index 5d7673528c..b58c36e812 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -2084,6 +2084,8 @@ export default withEnglishFallback({ maxAgentTurnsDescription: "單次 API Agent 執行的最大工具呼叫回合數,超過後會暫停並提示繼續。CLI 供應商使用各自的執行限制。", maxAgentTurnsRange: "{min}–{max},預設 {default}", maxAgentTurnsSaved: "Agent 回合上限已儲存", + defaultAiMode: "預設 AI 模式", + defaultAiModeDescription: "建立新 AI 對話時使用的模式。切換目前對話的模式不會變更此設定。", promptTemplates: "場景 Prompt 範本", promptTemplatesDescription: "在 AI 助手中選擇一或多個範本,注入場景化的約定規範。", promptTemplateNew: "新增範本", diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.ts index 2da72ee973..08e5973a64 100644 --- a/apps/desktop/src/lib/ai/ai.ts +++ b/apps/desktop/src/lib/ai/ai.ts @@ -1,4 +1,5 @@ import type { AiConfig } from "@/stores/settingsStore"; +import type { AiAssistantMode } from "@/types/ai"; import { uuid } from "@/lib/common/utils"; import type { ColumnInfo, ConnectionConfig, DatabaseType, ForeignKeyInfo, IndexInfo, QueryResult, QueryTab } from "@/types/database"; import type { PromptTemplate } from "@/types/promptTemplate"; @@ -36,7 +37,7 @@ function dbLabel(dbType: DatabaseType): string { } export type AiAction = "general" | "generate" | "explain" | "optimize" | "fix" | "convert" | "sampleData" | "query" | "exploreSchema" | "executeAndExplain"; -export type AiAssistantMode = "ask" | "agent"; +export type { AiAssistantMode } from "@/types/ai"; /** Actions shown in the Ask mode menu: SQL-producing, never auto-run. */ export const ASK_ACTIONS: AiAction[] = ["general", "generate", "explain", "optimize", "fix", "convert", "sampleData"]; diff --git a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts index 9fb96a0829..04a5dc829e 100644 --- a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts +++ b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts @@ -163,6 +163,7 @@ describe("settings search", () => { { titleKey: "settings.exportRowLimitEnabled", category: "data", targetId: "data" }, { titleKey: "settings.exportRowLimit", category: "data", targetId: "data" }, { titleKey: "settings.queryExportKeysetOptimizationEnabled", category: "data", targetId: "data" }, + { titleKey: "ai.defaultAiMode", category: "ai", targetId: "ai" }, { titleKey: "ai.maxAgentTurns", category: "ai", targetId: "ai" }, { titleKey: "ai.maxRetriesGlobal", category: "ai", targetId: "ai" }, { titleKey: "ai.globalInstructions", category: "ai", targetId: "ai" }, diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts index 2f5cb0828b..9e5dc635d3 100644 --- a/apps/desktop/src/lib/settings/settingsSearch.ts +++ b/apps/desktop/src/lib/settings/settingsSearch.ts @@ -211,6 +211,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] = { id: "sync-secrets-passphrase", category: "sync", titleKey: "settings.syncSecretsPassphrase", targetId: "sync", visible: desktopOnly }, { id: "ai-config", category: "ai", titleKey: "ai.configList", targetId: "ai" }, { id: "ai-prompts", category: "ai", titleKey: "ai.promptTemplates", descriptionKey: "ai.promptTemplatesDescription", targetId: "ai" }, + { id: "ai-default-mode", category: "ai", titleKey: "ai.defaultAiMode", descriptionKey: "ai.defaultAiModeDescription", targetId: "ai" }, { id: "ai-agent-turn-limit", category: "ai", titleKey: "ai.maxAgentTurns", descriptionKey: "ai.maxAgentTurnsDescription", targetId: "ai" }, { id: "ai-global-retries", category: "ai", titleKey: "ai.maxRetriesGlobal", descriptionKey: "ai.maxRetriesGlobalDescription", targetId: "ai" }, { id: "ai-global-instructions", category: "ai", titleKey: "ai.globalInstructions", descriptionKey: "ai.globalInstructionsDescription", targetId: "ai" }, diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts index b31296e868..717286a4f1 100644 --- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts +++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts @@ -770,6 +770,7 @@ describe("settingsStore activeModel lifecycle", () => { version: 1, active: undefined, effortPreferences: [], + defaultMode: "ask", }), ); @@ -838,6 +839,7 @@ describe("settingsStore activeModel lifecycle", () => { selection: { kind: "enum", value: "high" }, }, ], + defaultMode: "ask", }); }); @@ -862,3 +864,67 @@ describe("settingsStore activeModel lifecycle", () => { expect(store.activeModel).toBeNull(); }); }); + +// --- defaultAiMode lifecycle tests --- + +describe("settingsStore defaultAiMode lifecycle", () => { + beforeEach(() => { + vi.resetModules(); + setActivePinia(createPinia()); + }); + + it("falls back to Ask when the saved chat selection has no defaultMode", async () => { + vi.doMock("@/lib/backend/api", () => ({ + loadAiConfigs: vi.fn().mockResolvedValue([]), + loadAiConfig: vi.fn().mockResolvedValue(null), + loadAiProviderConfigs: vi.fn().mockResolvedValue(null), + loadAiChatSelection: vi.fn().mockResolvedValue(null), + saveAiChatSelection: vi.fn().mockResolvedValue(undefined), + })); + + const { useSettingsStore } = await import("@/stores/settingsStore"); + const store = useSettingsStore(); + + await store.initAiConfigs(); + + expect(store.defaultAiMode).toBe("ask"); + }); + + it("restores Agent from the saved chat selection", async () => { + vi.doMock("@/lib/backend/api", () => ({ + loadAiConfigs: vi.fn().mockResolvedValue([]), + loadAiConfig: vi.fn().mockResolvedValue(null), + loadAiProviderConfigs: vi.fn().mockResolvedValue(null), + loadAiChatSelection: vi.fn().mockResolvedValue({ version: 1, effortPreferences: [], defaultMode: "agent" }), + saveAiChatSelection: vi.fn().mockResolvedValue(undefined), + })); + + const { useSettingsStore } = await import("@/stores/settingsStore"); + const store = useSettingsStore(); + + await store.initAiConfigs(); + + expect(store.defaultAiMode).toBe("agent"); + }); + + it("setDefaultAiMode updates state and persists the mode", async () => { + const saveAiChatSelection = vi.fn().mockResolvedValue(undefined); + vi.doMock("@/lib/backend/api", () => ({ + loadAiConfigs: vi.fn().mockResolvedValue([]), + loadAiConfig: vi.fn().mockResolvedValue(null), + loadAiProviderConfigs: vi.fn().mockResolvedValue(null), + loadAiChatSelection: vi.fn().mockResolvedValue(null), + saveAiChatSelection, + })); + + const { useSettingsStore } = await import("@/stores/settingsStore"); + const store = useSettingsStore(); + store.isAiConfigLoaded = true; + + store.setDefaultAiMode("agent"); + expect(store.defaultAiMode).toBe("agent"); + + await vi.waitFor(() => expect(saveAiChatSelection).toHaveBeenCalled()); + expect(saveAiChatSelection.mock.calls[0][0]).toMatchObject({ defaultMode: "agent" }); + }); +}); diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts index c154ab03c2..207dfd93c9 100644 --- a/apps/desktop/src/stores/settingsStore.ts +++ b/apps/desktop/src/stores/settingsStore.ts @@ -19,7 +19,7 @@ import { normalizeSqlVariableSyntaxOverrides, type SqlVariableSyntaxOverrides } import { DEFAULT_TABLE_COLUMN_TEMPLATE_FIELDS, normalizeTableColumnTemplateFields } from "@/lib/table/tableColumnTemplates"; import { type DataTabReuseMode, DEFAULT_DATA_TAB_REUSE_MODE, normalizeDataTabReuseMode } from "@/lib/tabs/dataTabReuseMode"; import { normalizeCompletionTriggerMode, type SqlCompletionTriggerMode } from "@/lib/sql/sqlCompletionTriggerPolicy"; -import type { AiApiStyle, AiAuthMethod, AiChatSelectionState, AiConfig, AiConfigItem, AiConfiguredModel, AiEffortLevel, AiEffortSelection, AiModelEffortPreference, AiProvider, AiReasoningLevel, AiTestConnectionResult } from "@/types/ai"; +import type { AiApiStyle, AiAssistantMode, AiAuthMethod, AiChatSelectionState, AiConfig, AiConfigItem, AiConfiguredModel, AiEffortLevel, AiEffortSelection, AiModelEffortPreference, AiProvider, AiReasoningLevel, AiTestConnectionResult } from "@/types/ai"; import type { SqlSnippet, TableInfoTab } from "@/types/database"; export type { AiApiStyle, AiAuthMethod, AiChatSelectionState, AiConfig, AiConfigItem, AiConfiguredModel, AiEffortLevel, AiEffortSelection, AiProvider, AiReasoningLevel, AiTestConnectionResult, DataTabReuseMode, SavedSqlOpenTargetMode, SqlCompletionTriggerMode }; @@ -1162,6 +1162,7 @@ export const useSettingsStore = defineStore("settings", () => { const settingsNavigationRequest = ref(null); const activeModel = ref<{ configId: string; modelId: string } | null>(null); const effortPreferences = ref([]); + const defaultAiMode = ref("ask"); const isAiConfigLoaded = ref(false); const aiConfigs = ref([]); const desktopSettings = ref({ ...DEFAULT_DESKTOP_SETTINGS }); @@ -1286,6 +1287,7 @@ export const useSettingsStore = defineStore("settings", () => { const savedSelection = await api.loadAiChatSelection().catch(() => null); effortPreferences.value = (savedSelection?.effortPreferences ?? []).filter((preference) => aiConfigs.value.some((config) => config.id === preference.configId)); + defaultAiMode.value = savedSelection?.defaultMode ?? "ask"; const savedActive = savedSelection?.active; const savedConfig = savedActive ? aiConfigs.value.find((config) => config.id === savedActive.configId) : undefined; @@ -1418,6 +1420,12 @@ export const useSettingsStore = defineStore("settings", () => { persistAiChatSelection(); } + function setDefaultAiMode(mode: AiAssistantMode) { + if (mode === defaultAiMode.value) return; + defaultAiMode.value = mode; + persistAiChatSelection(); + } + function persistAiChatSelection() { pendingAiChatSelection = { version: 1, @@ -1426,6 +1434,7 @@ export const useSettingsStore = defineStore("settings", () => { ...preference, selection: { ...preference.selection }, })), + defaultMode: defaultAiMode.value, }; if (!aiChatSelectionSaveRunning) void flushAiChatSelection(); } @@ -1631,6 +1640,8 @@ export const useSettingsStore = defineStore("settings", () => { clearSettingsNavigationRequest, activeModel, activeEffort, + defaultAiMode, + setDefaultAiMode, isAiConfigLoaded, aiConfigs, initAiConfigs, diff --git a/apps/desktop/src/types/ai.ts b/apps/desktop/src/types/ai.ts index 1db0fa6b12..9a017f2d1c 100644 --- a/apps/desktop/src/types/ai.ts +++ b/apps/desktop/src/types/ai.ts @@ -4,6 +4,7 @@ export type AiAuthMethod = "api-key" | "bearer"; export type AiEffortLevel = "low" | "medium" | "high" | "xhigh" | "max"; export type AiReasoningLevel = "default" | "minimal" | AiEffortLevel; export type AiCapabilitySource = "providerApi" | "localCli" | "officialRegistry" | "custom"; +export type AiAssistantMode = "ask" | "agent"; export type AiEffortSelection = { kind: "providerDefault" } | { kind: "disabled" } | { kind: "enum"; value: string } | { kind: "integer"; value: number } | { kind: "boolean"; value: boolean } | { kind: "text"; value: string }; @@ -82,4 +83,5 @@ export interface AiChatSelectionState { version: number; active?: AiActiveModelSelection; effortPreferences: AiModelEffortPreference[]; + defaultMode?: AiAssistantMode; } diff --git a/crates/dbx-core/src/ai.rs b/crates/dbx-core/src/ai.rs index 616d2f6760..d6de786968 100644 --- a/crates/dbx-core/src/ai.rs +++ b/crates/dbx-core/src/ai.rs @@ -284,6 +284,13 @@ pub struct AiModelEffortPreference { pub selection: AiEffortSelection, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AiAssistantMode { + Ask, + Agent, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct AiChatSelectionState { @@ -293,11 +300,18 @@ pub struct AiChatSelectionState { pub active: Option, #[serde(default)] pub effort_preferences: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_mode: Option, } impl Default for AiChatSelectionState { fn default() -> Self { - Self { version: default_ai_chat_selection_version(), active: None, effort_preferences: Vec::new() } + Self { + version: default_ai_chat_selection_version(), + active: None, + effort_preferences: Vec::new(), + default_mode: None, + } } } @@ -3910,12 +3924,30 @@ mod tests { responses_text, responses_token_usage, retain_ollama_completion_models, retry_after_secs, set_chat_completion_token_limit, stream, stream_claude, stream_claude_with_tools, stream_data_payload, stream_error, stream_openai_with_tools, stream_with_tools, test_connection_core, uses_anthropic_messages_api, - validate_config, validate_model_list_config, with_retry, with_stream_retry, AiApiStyle, AiAuthMethod, - AiCapabilitySource, AiCompletionRequest, AiConfig, AiEffortCapability, AiEffortOption, AiEffortSelection, - AiMessage, AiModelInfo, AiProvider, AiReasoningLevel, StreamToolEvent, StreamingToolCallAccumulator, - ToolCallRef, AUTHORIZATION, CLAUDE_DEFAULT_SYSTEM, TEST_PROMPT, + validate_config, validate_model_list_config, with_retry, with_stream_retry, AiApiStyle, AiAssistantMode, + AiAuthMethod, AiCapabilitySource, AiChatSelectionState, AiCompletionRequest, AiConfig, AiEffortCapability, + AiEffortOption, AiEffortSelection, AiMessage, AiModelInfo, AiProvider, AiReasoningLevel, StreamToolEvent, + StreamingToolCallAccumulator, ToolCallRef, AUTHORIZATION, CLAUDE_DEFAULT_SYSTEM, TEST_PROMPT, }; + #[test] + fn ai_chat_selection_default_mode_serde() { + // Old blobs without a defaultMode field load as None (no migration needed). + let legacy: AiChatSelectionState = + serde_json::from_str(r#"{"version":1,"active":null,"effortPreferences":[]}"#).unwrap(); + assert_eq!(legacy.default_mode, None); + + let agent: AiChatSelectionState = serde_json::from_str(r#"{"version":1,"defaultMode":"agent"}"#).unwrap(); + assert_eq!(agent.default_mode, Some(AiAssistantMode::Agent)); + + let ask: AiChatSelectionState = serde_json::from_str(r#"{"version":1,"defaultMode":"ask"}"#).unwrap(); + assert_eq!(ask.default_mode, Some(AiAssistantMode::Ask)); + + // camelCase key + lowercase value round-trip. + let serialized = serde_json::to_value(agent).unwrap(); + assert_eq!(serialized["defaultMode"], serde_json::json!("agent")); + } + struct CapturedJsonRequest { headers: String, body: serde_json::Value, diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs index ae7d45679e..132cd40a5e 100644 --- a/crates/dbx-core/src/storage.rs +++ b/crates/dbx-core/src/storage.rs @@ -3907,7 +3907,9 @@ mod tests { maybe_import_user_data_db, DataDbImportResult, DesktopIconTheme, DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, Storage, MCP_GLOBAL_POLICY_KEY, }; - use crate::ai::{AiActiveModelSelection, AiChatSelectionState, AiEffortSelection, AiModelEffortPreference}; + use crate::ai::{ + AiActiveModelSelection, AiAssistantMode, AiChatSelectionState, AiEffortSelection, AiModelEffortPreference, + }; use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY; use crate::connection_secrets::{ MQ_AUTH_PASSWORD_KEY, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, NACOS_AUTH_PASSWORD_KEY, @@ -5268,6 +5270,7 @@ mod tests { model_id: "model-1".to_string(), selection: AiEffortSelection::Enum("high".to_string()), }], + default_mode: Some(AiAssistantMode::Agent), }; storage.save_ai_chat_selection(&selection).await.unwrap(); diff --git a/packages/app-tests/aiAssistantModePersistence.test.ts b/packages/app-tests/aiAssistantModePersistence.test.ts index c1bdd16c20..753bd5c38a 100644 --- a/packages/app-tests/aiAssistantModePersistence.test.ts +++ b/packages/app-tests/aiAssistantModePersistence.test.ts @@ -6,24 +6,40 @@ import { test } from "vitest"; const aiAssistantPath = fileURLToPath(new URL("../../apps/desktop/src/components/editor/AiAssistant.vue", import.meta.url)); const aiAssistantSource = readFileSync(aiAssistantPath, "utf8"); -test("AI mode resets to Ask for a new conversation and panel remount", () => { +test("AI mode initializes from the persisted default mode", () => { + // The fallback value is still Ask, but the panel syncs from the configured default. assert.match(aiAssistantSource, /const assistantMode = ref\("ask"\)/); + assert.match(aiAssistantSource, /settings\.defaultAiMode/); assert.doesNotMatch(aiAssistantSource, /"update:mode"/); + // The persisted setting is applied once after the asynchronous config load; + // later setting changes must not alter an active conversation. + assert.match(aiAssistantSource, /watch\([\s\S]*?settings\.isAiConfigLoaded[\s\S]*?defaultModeInitialized/); + assert.match(aiAssistantSource, /assistantMode\.value = settings\.defaultAiMode/); +}); + +test("startNewChat uses the configured default mode instead of a hardcoded Ask reset", () => { const start = aiAssistantSource.indexOf("function startNewChat()"); const end = aiAssistantSource.indexOf("\nonMounted", start); const startNewChat = aiAssistantSource.slice(start, end); - assert.match(startNewChat, /assistantMode\.value = "ask"/); - assert.match(startNewChat, /activeAction\.value = resolveDefaultAction\("ask"\)/); + + assert.notEqual(start, -1, "startNewChat should exist"); + assert.match(startNewChat, /const mode = settings\.defaultAiMode/); + assert.match(startNewChat, /assistantMode\.value = mode/); + assert.match(startNewChat, /activeAction\.value = resolveDefaultAction\(mode\)/); + // The old hardcoded Ask reset must be gone. + assert.doesNotMatch(startNewChat, /assistantMode\.value = "ask"/); }); -test("AI mode tab click resets the active action even when mode is unchanged", () => { +test("switching mode in a session never touches the global default setting", () => { const start = aiAssistantSource.indexOf('function switchModeActionTab(mode: "ask" | "agent")'); const end = aiAssistantSource.indexOf("\nfunction selectModeActionItem", start); const switchModeActionTab = aiAssistantSource.slice(start, end); assert.notEqual(start, -1, "switchModeActionTab should exist"); assert.notEqual(end, -1, "selectModeActionItem should follow switchModeActionTab"); + // Session switch updates local state only — no store write. + assert.doesNotMatch(switchModeActionTab, /setDefaultAiMode|setAiAssistantDefaultMode/); assert.doesNotMatch(switchModeActionTab, /if\s*\(\s*assistantMode\.value\s*===\s*mode\s*\)\s*(?:\{\s*)?return/); const defaultActionReset = switchModeActionTab.indexOf("activeAction.value = resolveDefaultAction(mode)");