Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(ai): persist conversation mode per conversation

Abeautifulsnow62c872031607
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vue
index 9936298267..efdf9ddd39 100644
--- a/apps/desktop/src/components/editor/AiAssistant.vue
+++ b/apps/desktop/src/components/editor/AiAssistant.vue
@@ -131,7 +131,6 @@ import {
isVectorDbType,
isValidActionForMode,
isAutoActionSelection,
- defaultActionForMode,
type AiAction,
type AiActionSelection,
type AiAssistantMode,
@@ -248,6 +247,8 @@ import { saveTextFile } from "@/lib/export/saveTextFile";
import { buildAiAnalysisExport } from "@/lib/export/aiAnalysisExport";
import { buildAiConversationExport, type AiConversationExportFormat } from "@/lib/export/aiConversationExport";
import { buildAiConversationSearchIndex, filterAiConversationSearchIndex } from "@/lib/ai/aiConversationSearch";
+import { applyCapabilities, resolveConversationPicker, resolveDefaultPickerAction, type AiPickerAmbient, type AiPickerConversationRecord, type AiPickerSelection } from "@/lib/ai/aiConversationPicker";
+import { createAiConversationPickerController } from "@/lib/ai/aiConversationPickerState";
import AiAttachmentCard from "@/components/editor/AiAttachmentCard.vue";
import AiToolApprovalCard from "@/components/editor/AiToolApprovalCard.vue";
import { resolveAiMessageCopyText } from "@/lib/ai/aiMessageCopy";
@@ -410,13 +411,13 @@ const draftPluginContext = ref<AiPluginContext>();
const pluginContext = computed(() => pluginContextFromMessages(messages.value) ?? draftPluginContext.value);
const isGenerating = ref(false);
const scrollRef = ref<InstanceType<typeof ScrollArea> | null>(null);
-// Stays a concrete action until the AI config loads: whether new conversations
-// land on the `auto` entry is decided by the Settings > AI toggle (see
-// `resolveDefaultActionSelection`).
-const activeAction = ref<AiActionSelection>("general");
/** True while the Auto slow path (intent classifier) is in flight for the visible conversation. */
const routingInFlight = ref(false);
-const assistantMode = ref<AiAssistantMode>("ask");
+// The Ask/Agent mode + action picker is created further down, once the binding
+// and plugin computeds it reads exist — reading `boundConnection` during setup
+// would throw a TDZ ReferenceError. It exposes the `assistantMode` /
+// `activeAction` refs this file has always used.
+//
// 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;
@@ -464,27 +465,189 @@ function canUsePluginAgentMode(context = pluginContext.value, connection = bound
return !context || !!connection;
}
-watch(
- [pluginContext, boundConnection],
- ([context, connection]) => {
- if (context && !connection && assistantMode.value === "agent") assistantMode.value = "ask";
+/**
+ * Ambient capabilities the mode/action selection has to be legal in, read lazily
+ * so a connection change, a settings toggle or a plugin context refresh applies
+ * on the next resolution without rebuilding the picker (R5/R10).
+ */
+function pickerAmbientFor(connection: ConnectionConfig | undefined, isPluginConversation: boolean): AiPickerAmbient {
+ return {
+ defaultMode: settings.defaultAiMode,
+ defaultAutoRouting: settings.defaultAutoRouting,
+ // Ongoing permission rather than a snapshot: the choice survives, the UI just
+ // cannot offer it. `pluginSession` mirrors `showActionButtons`'s first branch.
+ vectorDb: !!connection && isVectorDbType(connection.db_type),
+ pluginSession: isPluginConversation,
+ pluginWithoutConnection: isPluginConversation && !connection,
+ };
+}
+
+/** Ambient for the conversation on screen. */
+function pickerAmbient(): AiPickerAmbient {
+ return pickerAmbientFor(boundConnection.value, !!pluginContext.value);
+}
+
+/**
+ * The Ask/Agent mode + action picker (#12075). It owns both values as a pair, so
+ * restoring a conversation's own selection cannot be undone by the mode reset —
+ * see `aiConversationPickerState.ts` for why that used to happen and how the
+ * reset is kept for a genuine mode switch.
+ *
+ * `raw` belongs to the conversation: `onUserSelection` records a real picker
+ * operation (or an entry point that explicitly asks for a mode/action) while a
+ * restore and a capability limit only move the shown values (R9).
+ */
+const picker = createAiConversationPickerController({
+ ambient: pickerAmbient,
+ onUserSelection: (selection) => {
+ conversationPickerSelections.set(pickerSelectionKey(), selection);
+ // A pick has to reach disk right away, not at the next send: switching to
+ // another conversation and closing the panel both unmount/leave this chat
+ // without a save, so a choice held only in memory is exactly the "my
+ // selection was forgotten" symptom (#12075). `persistConversation` writes the
+ // live transcript, so the save cannot clobber a newer run snapshot with the
+ // stale list copy. A draft with no messages yet saves nothing — its pick
+ // rides the first snapshot that creates the record (R4).
+ if (conversationId.value) void persistConversation();
},
- { immediate: true },
-);
+});
+/** The shown mode; the next send uses it. */
+const assistantMode = picker.mode;
+/** The shown action entry (`auto` included); the next send resolves it (#9118). */
+const activeAction = picker.action;
+
+/**
+ * Which picker selection each conversation recorded, `raw` only — a capability
+ * limit never lands here (R9). Keyed by `skillStateKey`'s convention: a persisted
+ * conversation's id, or the single unsaved-chat slot, which `clearMessages()`
+ * rotates so two unsaved drafts can never trade values (R4). In-memory on
+ * purpose: the values are persisted onto the conversation record (see
+ * `pickerSnapshotFor`), and this map is what lets a chat with no record yet keep
+ * its choice until the first snapshot writes it.
+ */
+const conversationPickerSelections = createReactiveMap(new Map<string, AiPickerSelection>());
+
+/** Key the shown conversation's selection is filed under. */
+function pickerSelectionKey(): string {
+ return conversationId.value || unsavedConversationKey.value;
+}
+
+/** The reported `raw` values for one conversation record, if it has any. */
+function pickerRecordFor(conversation: AiConversation | undefined): AiPickerConversationRecord {
+ if (!conversation) return {};
+ return {
+ assistantMode: conversation.assistantMode,
+ assistantAction: conversation.assistantAction,
+ // R10 read priority: the legacy plugin field is only a fallback source, and
+ // the persisted plugin context lives on the RECORD (`plugin_context_json`).
+ // `AiChatMessage` never carried it — the panel rebuilds the message-level
+ // context from this field when it loads a transcript.
+ pluginContextMode: conversation.pluginContext?.mode,
+ };
+}
+
+/**
+ * The picker selection another conversation owns — its recorded values resolved
+ * through the R9 table, or an in-memory pick that has not been persisted yet.
+ *
+ * Capabilities are derived from THAT conversation's binding, not the visible
+ * one: a background retry of a vector-DB chat must be locked to `generate` even
+ * while a SQL editor is on screen (R7).
+ */
+function conversationPickerSelectionFor(convId: string): AiPickerSelection {
+ const conversation = conversations.value.find((item) => item.id === convId);
+ const connection = conversation?.connectionId ? connectionStore.getConfig(conversation.connectionId) : undefined;
+ const ambient = pickerAmbientFor(connection, !!pickerRecordFor(conversation).pluginContextMode || !!conversation?.pluginContext);
+ const pending = conversationPickerSelections.get(convId);
+ if (pending) return applyCapabilities(pending, ambient);
+ return resolveConversationPicker(pickerRecordFor(conversation), ambient).effective;
+}
+
+/**
+ * The picker values to persist with `targetConversationId`.
+ *
+ * Only a real picker operation is stored: the in-memory map first (a chat whose
+ * record does not exist yet, or one just picked), then the conversation's own
+ * recorded values — never `effective`. A vector DB or a disconnected plugin chat
+ * shows a degraded combination, and writing that back would silently replace the
+ * user's own choice (R9/R10).
+ */
+function pickerSnapshotFor(targetConversationId: string): { assistantMode?: string; assistantAction?: string } {
+ const selection = conversationPickerSelections.get(targetConversationId);
+ if (selection) return { assistantMode: selection.mode, assistantAction: selection.action };
+ const existing = conversations.value.find((conversation) => conversation.id === targetConversationId);
+ return { assistantMode: existing?.assistantMode, assistantAction: existing?.assistantAction };
+}
+
+/**
+ * Restores the shown conversation's own picker selection (R2), with the R9
+ * capability replay and the R10 read priority.
+ *
+ * `selectConversation` calls this after `conversationId` has moved, so both the
+ * record read and any in-memory pick belong to the arriving conversation. A
+ * read never records anything: an old record's fallback (settings default, or
+ * `pluginContext.mode` for a plugin chat) stays implicit instead of being
+ * promoted into the new columns (R10's "no double write").
+ */
+function restoreConversationPicker(conv: AiConversation) {
+ const resolution = resolveConversationPicker(pickerRecordFor(conv), pickerAmbient());
+ const pending = conversationPickerSelections.get(conv.id);
+ picker.restore(pending ? applyCapabilities(pending, pickerAmbient()) : resolution.effective);
+}
+
+/**
+ * Re-derives the shown pair after a capability changed — a plugin conversation's
+ * connection appearing or going away, a rebind to or from a vector DB.
+ *
+ * A capability limit belongs to `effective` alone, so when the environment
+ * changes the shown pair has to be recomputed from the conversation's own
+ * recording. A one-way degradation would strand the panel on the degraded value:
+ * `send()` reads the shown mode, so a connection that merely blipped would keep
+ * an Agent conversation in Ask for the rest of the session. `raw` is never
+ * touched, so the user's own choice is what comes back (R5/R9).
+ */
+function reapplyPickerCapabilities() {
+ const pending = conversationPickerSelections.get(pickerSelectionKey());
+ if (pending) {
+ picker.restore(applyCapabilities(pending, pickerAmbient()));
+ return;
+ }
+ const conversation = activeConversation.value;
+ if (conversation) {
+ picker.restore(resolveConversationPicker(pickerRecordFor(conversation), pickerAmbient()).effective);
+ return;
+ }
+ // A draft with no pick of its own keeps the new-chat default it already shows,
+ // constrained by the new capability (a vector DB still forces `generate`).
+ picker.restore(applyCapabilities({ mode: assistantMode.value, action: activeAction.value }, pickerAmbient()));
+}
+
+/**
+ * Moves the unsaved chat's picker selection onto the id it just adopted, exactly
+ * like `migrateUnsavedSkillState` does for skills: `send()` mints the id and
+ * reads the selection in the same tick, while the id watcher flushes later (R4).
+ */
+function migrateUnsavedPickerSelection(id: string) {
+ const unsavedKey = unsavedConversationKey.value;
+ if (!id || !unsavedKey || unsavedKey === id) return;
+ const selection = conversationPickerSelections.get(unsavedKey);
+ if (!selection) return;
+ conversationPickerSelections.delete(unsavedKey);
+ conversationPickerSelections.set(id, selection);
+}
// `immediate` runs this during setup whenever the AI config finished loading
// before the panel mounted (the usual case: the app loads it at startup), and
-// `resolveDefaultActionSelection` reads `boundConnection`. It must therefore
-// stay below the binding computeds, or setup throws a TDZ ReferenceError and
-// the panel never mounts.
+// the ambient it reads uses `boundConnection`. It must therefore stay below the
+// binding computeds, or setup throws a TDZ ReferenceError and the panel never
+// mounts.
watch(
() => settings.isAiConfigLoaded,
(loaded) => {
if (loaded && !defaultModeInitialized) {
- assistantMode.value = settings.defaultAiMode;
- // Same apply-once rule as the mode: later setting changes must not
- // disturb an active conversation.
- activeAction.value = resolveDefaultActionSelection(settings.defaultAiMode);
+ // The picker's mode watch lands the action on the same default entry this
+ // always used (`auto` when Settings > AI says so, #9118) — R3 unchanged.
+ picker.restoreDefault();
defaultModeInitialized = true;
}
},
@@ -764,6 +927,18 @@ function loadedSkillIdFromToolResult(result: unknown): string | undefined {
const unsavedConversationKey = ref(`unsaved:${uuid()}`);
const skillStateKey = computed(() => conversationId.value || unsavedConversationKey.value);
+// A capability can come AND go while a conversation is on screen: the app's
+// connections load after the panel opens, a plugin conversation's connection is
+// added or removed, the user rebinds, or the selected conversation moves between
+// a vector DB and a relational one. Each of those re-derives the shown pair from
+// the conversation's own recording, which is what keeps `effective` equal to
+// capabilities(`raw`) at all times — the mode/action refs have no other writer.
+//
+// `immediate` runs this during setup, so it must stay below everything
+// `reapplyPickerCapabilities` reads — `unsavedConversationKey` included, exactly
+// like the panel-mount default watch further down.
+watch([pluginContext, boundConnection], () => reapplyPickerCapabilities(), { immediate: true });
+
/**
* Loaded = this conversation's recorded facts (a model-initiated `use_skill` in
* one of its runs, a forced load, or the ids restored from its own transcript).
@@ -779,6 +954,25 @@ function recordConversationSkillLoad(key: string, id: string) {
conversationLoadedSkillIds.set(key, [...loaded, id]);
}
+/**
+ * Drops everything filed under the unsaved chat's slot and moves to a fresh one.
+ *
+ * A draft can never be reopened, so none of its state may outlive it: leaving it
+ * for an existing conversation would otherwise let the abandoned draft's loaded
+ * skills and its recorded mode/action ride into whichever conversation is opened
+ * next (#12075 review — the picker values are persisted, so the leak showed up as
+ * that conversation being re-opened with the draft's selection).
+ */
+function discardUnsavedDraftState() {
+ const unsavedKey = unsavedConversationKey.value;
+ skillHintLatch.value = null;
+ conversationSkillHintSeen.delete(unsavedKey);
+ conversationLoadedSkillIds.delete(unsavedKey);
+ conversationLoadedSkillBodies.delete(unsavedKey);
+ conversationPickerSelections.delete(unsavedKey);
+ unsavedConversationKey.value = `unsaved:${uuid()}`;
+}
+
/**
* Moves the unsaved chat's skill state onto the id it just adopted. The id
* watcher covers this for the UI, but watchers flush later: `send()` mints the id
@@ -852,13 +1046,23 @@ watch([skillStateKey, () => selectedSkillChips.value.map((chip) => chip.id).join
// conversation switch: move the unsaved chat's skill state onto the id it just
// adopted, or the brand-new id would read as a fresh conversation (Req 14) and
// would lose the bodies a forced load already put in this run's state (Req 13).
+//
+// `previous === ""` alone cannot tell the two apart: opening a conversation from
+// the list also moves the id from `""` to a value. A switch discards the draft
+// instead (`selectConversation`), and this guard keeps the adoption rule honest
+// even if some other path moves the id onto a record that already exists.
watch(conversationId, (id, previous) => {
if (previous !== "" || !id) return;
+ if (conversations.value.some((conversation) => conversation.id === id)) return;
const unsavedKey = unsavedConversationKey.value;
if (conversationSkillHintSeen.delete(unsavedKey)) conversationSkillHintSeen.add(id);
const latch = skillHintLatch.value;
if (latch && latch.key === unsavedKey) skillHintLatch.value = { ...latch, key: id };
migrateUnsavedSkillState(id);
+ // The picker selection of the unsaved chat moves with it for the same reason:
+ // the new id must not read as a fresh conversation whose selection is unset,
+ // or the first snapshot would persist nothing (#12075 R4).
+ migrateUnsavedPickerSelection(id);
});
// The selector's capability state (predicate, gated open state, trigger label)
// lives below `activeFullConfig`, next to the config it reads.
@@ -1799,50 +2003,27 @@ const isRedisConnection = computed(() => boundConnection.value?.db_type === "red
// Vector DBs hide the action menu and only expose collection tools.
// Keep their action at `generate` so the task contract doesn't tell the LLM to call execute_query.
+// The same rule as `resolveDefaultPickerAction`'s vector branch: `mode` is
+// accepted for the call sites that have one at hand, but the capability decides.
+// The rebind itself is handled by `reapplyPickerCapabilities`, whose ambient
+// carries the vector-DB flag — including on the way back out, which the old
+// one-way force did not do.
function resolveDefaultAction(mode: AiAssistantMode): AiAction {
- if (boundConnection.value && isVectorDbType(boundConnection.value.db_type)) return "generate";
- return defaultActionForMode(mode);
+ return resolveDefaultPickerAction(mode, pickerAmbient());
}
-// The Settings > AI toggle lets new conversations land on the `auto` picker
-// entry (#9118); routing still resolves to a concrete action before any
-// request. Vector DBs keep the concrete `generate` action because their action
-// menu is hidden entirely.
-function resolveDefaultActionSelection(mode: AiAssistantMode): AiActionSelection {
- if (settings.defaultAutoRouting && !(boundConnection.value && isVectorDbType(boundConnection.value.db_type))) return "auto";
- return resolveDefaultAction(mode);
-}
-
-// Switching mode is a deliberate context change: land on that mode's default action so the
-// menu and behavior match the new intent. That default is the mode's concrete action, or
-// `auto` when Settings > AI enables it (#9118).
-//
-// `triggerAction` may set the action itself after programmatically switching mode (e.g. "Fix
-// with AI" invoked from Agent mode); `suppressModeActionReset` tells this watch to skip the
-// default reset so the menu keeps reflecting the action actually being run.
-let suppressModeActionReset = false;
-watch(assistantMode, (mode) => {
- if (suppressModeActionReset) {
- suppressModeActionReset = false;
- return;
- }
- activeAction.value = resolveDefaultActionSelection(mode);
-});
-
-watch(
- () => boundConnection.value?.db_type,
- () => {
- // Vector DBs hide the action picker, so keep the hidden action aligned with
- // the collection-oriented prompt contract on initial render and connection changes.
- if (boundConnection.value && isVectorDbType(boundConnection.value.db_type)) {
- activeAction.value = "generate";
- }
- },
- { immediate: true },
-);
+// Switching mode is a deliberate context change: the picker lands the action on
+// that mode's default entry (or `auto`, #9118). That reset lives in the picker
+// controller's own mode watch — the single writer of the pair — so a restore can
+// no longer be undone by it. Capability-driven changes go through
+// `reapplyPickerCapabilities` above; nothing writes the refs from here.
function selectAction(action: AiActionSelection) {
- activeAction.value = action;
+ // A genuine picker operation: the picker records it as the conversation's own
+ // `raw` value (and applies the capability limit to what is shown). The
+ // controller's mode watch would land on the mode default, so the action is set
+ // through the picker rather than the bare ref.
+ picker.selectAction(action);
if (action === "fix" && aiContextTarget.value.result) {
if (isQueryExecutionErrorResult(aiContextTarget.value.result)) {
const errVal = aiContextTarget.value.result.rows[0]?.[0];
@@ -1864,19 +2045,15 @@ function routedActionOf(message: ChatMessage): AiAction | null {
}
/**
- * The "Auto · <action>" chip switches the picker to the action that was routed
- * for that message, so the user can keep iterating explicitly. The routed action
- * is always valid in the mode it was routed in; when the panel now stands in the
- * other mode, switch there first (the `suppressModeActionReset` handshake keeps
- * the mode-switch watch from overwriting the action we just set).
+ * The "Auto · <action>" chip switches the picker onto the action the router
+ * resolved for that message, so the user can keep iterating explicitly. The
+ * routed action is always valid in the mode it was routed in; when the panel now
+ * stands in the other mode the pair moves together — the picker owns both refs,
+ * so there is no mode-switch reset to work around.
*/
function switchToRoutedAction(action: AiAction | null | undefined) {
if (!action) return;
- if (!isValidActionForMode(action, assistantMode.value)) {
- suppressModeActionReset = true;
- assistantMode.value = isValidActionForMode(action, "ask") ? "ask" : "agent";
- }
- activeAction.value = action;
+ picker.select({ mode: isValidActionForMode(action, assistantMode.value) ? assistantMode.value : isValidActionForMode(action, "ask") ? "ask" : "agent", action });
}
/** Mirrors `buildAiContext`'s `lastError`: only a real failed execution counts. */
@@ -2162,11 +2339,10 @@ const modeActionTriggerLabel = computed(() => {
function switchModeActionTab(mode: "ask" | "agent") {
if (mode === "agent" && !canUsePluginAgentMode()) return;
- activeAction.value = resolveDefaultActionSelection(mode);
- if (assistantMode.value !== mode) {
- // Set the mode after the action so the tab label and picker stay aligned.
- assistantMode.value = mode;
- }
+ // Tab switch = a deliberate context change: the pair moves together (the
+ // picker lands on the new mode's default entry) and is recorded as this
+ // conversation's own selection (#12075).
+ picker.selectMode(mode);
}
function selectModeActionItem(action: AiActionSelection) {
@@ -3352,7 +3528,7 @@ function selectCommand(command: AiSlashEntry) {
// textarea already keeps focus; nothing needs to be restored.
return;
}
- activeAction.value = command.button.action;
+ picker.selectAction(command.button.action);
nextTick(() => {
const textarea = promptTextareaRef.value;
if (textarea) {
@@ -3875,10 +4051,20 @@ async function send() {
startStatusTimer();
}
const myGeneration = aiGenerationGuard.begin();
- if (!auto && !conversationId.value) conversationId.value = uuid();
+ const mintedConversationId = !auto && !conversationId.value;
+ if (mintedConversationId) conversationId.value = uuid();
// The id was minted a line ago and the watcher has not flushed yet: this send
// must already read the skill state of the conversation it is now running for.
- if (!auto) migrateUnsavedSkillState(conversationId.value);
+ // Only on a mint — a send on an id that already has a record must not pull the
+ // (now discarded) draft slot into it.
+ if (mintedConversationId) {
+ migrateUnsavedSkillState(conversationId.value);
+ // Same tick, same reason: this send is already running for the id minted a
+ // line above, so its picker selection has to follow now (the id watcher flushes
+ // later). Without this the first snapshot of a picker-touched new chat would
+ // persist no selection at all (#12075 R4).
+ migrateUnsavedPickerSelection(conversationId.value);
+ }
const runConversationId = auto ? auto.conversationId : conversationId.value;
const runMessages = auto ? auto.messages : messages.value;
const runCreatedAt = new Date().toISOString();
@@ -5146,13 +5332,9 @@ function clearMessages() {
draftBeforeHistory.value = "";
recoveredDraftActive.value = false;
// A new chat is a new conversation, so it gets its own hint identity and a
- // first hint of its own (Req 14). Its predecessor's skill state is dropped with
- // it — that chat's id can never come back.
- skillHintLatch.value = null;
- conversationSkillHintSeen.delete(unsavedConversationKey.value);
- conversationLoadedSkillIds.delete(unsavedConversationKey.value);
- conversationLoadedSkillBodies.delete(unsavedConversationKey.value);
- unsavedConversationKey.value = `unsaved:${uuid()}`;
+ // first hint of its own (Req 14). Its predecessor's state is dropped with it —
+ // that chat's id can never come back.
+ discardUnsavedDraftState();
messageRenderer.value.clear();
}
@@ -5226,6 +5408,11 @@ function buildConversationSnapshot(targetConversationId: string, targetMessages:
// The conversation's single queued "send later" input, persisted so it
// survives a restart (parent PRD §5).
queuedInput: queuedInputs.get(targetConversationId)?.text,
+ // The conversation's own mode + action selection (#12075). `pickerSnapshotFor`
+ // returns the RECORDED values only — never the constrained `effective` pair —
+ // so a vector-DB or disconnected-plugin chat cannot have its degraded
+ // combination written back over the user's own choice (R9).
+ ...pickerSnapshotFor(targetConversationId),
createdAt,
updatedAt: new Date().toISOString(),
};
@@ -5358,6 +5545,10 @@ async function persistPendingInputRecovery(conversation: AiConversation, message
...(m.loadedSkillIds?.length ? { loadedSkillIds: [...m.loadedSkillIds] } : {}),
})),
queuedInput: conversation.queuedInput,
+ // Recovery must not drop the conversation's own picker selection either
+ // (#12075): this path rewrites the whole record, so the values come from the
+ // same raw source as `buildConversationSnapshot` (never `effective`).
+ ...pickerSnapshotFor(conversation.id),
createdAt: conversation.createdAt,
updatedAt,
};
@@ -5455,6 +5646,11 @@ function selectConversation(conv: AiConversation) {
// user is leaving behind (parent PRD §8). Uses the VISIBLE count (context
// summaries are filtered out of rendering) so the anchor matches row indices.
if (conversationId.value) conversationReadMessageCount.set(conversationId.value, visibleMessages.value.length);
+ // Leaving a draft abandons it — a draft can never be reopened, so its state
+ // must not stay filed under a key a later conversation could read. Dropping it
+ // here keeps an abandoned draft's picker selection and loaded skill ids out of
+ // the conversation being opened (#12075 review).
+ if (!conversationId.value) discardUnsavedDraftState();
conversationId.value = conv.id;
// The chosen conversation owns its connection from here on (#9902); any
// binding staged for the unsaved chat we are leaving is now irrelevant.
@@ -5475,10 +5671,11 @@ function selectConversation(conv: AiConversation) {
// loaded, so the chips can light up before anything is read again. The bodies
// come back when a request actually needs them (`rehydrateLoadedSkillBodies`).
seedLoadedSkillsFromTranscript(conv.id, messages.value);
- if (pluginContext.value) {
- assistantMode.value = pluginContext.value.mode === "agent" && !boundConnection.value ? "ask" : (pluginContext.value.mode ?? "ask");
- activeAction.value = "general";
- }
+ // The arriving conversation owns its own mode + action selection (#12075):
+ // restore it here rather than leaving the previous chat's picker on screen.
+ // This replaced a plugin-only branch that always forced `general`; the plugin
+ // case is one of the rules `resolveConversationPicker` replays (R9/R10).
+ restoreConversationPicker(conv);
unreadConversations.delete(conv.id);
isGenerating.value = activeRun?.status === "preparing" || activeRun?.status === "queued" || activeRun?.status === "running";
currentSessionId.value = activeRun?.currentSessionId ?? "";
@@ -5590,6 +5787,8 @@ async function performDeleteConversation(id: string) {
conversationLoadedSkillIds.delete(id);
conversationLoadedSkillBodies.delete(id);
conversationSkillHintSeen.delete(id);
+ // Its picker selection goes with it too (#12075): the id can never come back.
+ conversationPickerSelections.delete(id);
await deleteConversationWithCancellation({
id,
currentConversationId: () => conversationId.value,
@@ -5622,10 +5821,10 @@ function startNewChat() {
clearMessages();
showConversationList.value = false;
// A fresh conversation starts from the configured default mode and, when the
- // Settings > AI toggle says so, from the `auto` picker entry (#9118).
- const mode = settings.defaultAiMode;
- assistantMode.value = mode;
- activeAction.value = resolveDefaultActionSelection(mode);
+ // Settings > AI toggle says so, from the `auto` picker entry (#9118). This is
+ // unchanged by #12075: the picker takes over once the user picks, or once the
+ // conversation is reopened with its own recorded selection.
+ picker.restoreDefault();
}
/** Send-button dispatcher: with an active run on the visible conversation the
@@ -5642,7 +5841,14 @@ function onSendClick() {
function queueInput() {
const text = prompt.value.trim();
if (!text) return;
- if (!conversationId.value) conversationId.value = uuid();
+ if (!conversationId.value) {
+ conversationId.value = uuid();
+ // Minted a line above and the id watcher has not flushed yet, so the draft's
+ // selection has to follow now or this snapshot would persist none (same
+ // reason as `send()`, #12075 R4). Only on a mint: moving it for an id that
+ // already has a record is exactly what must not happen.
+ migrateUnsavedPickerSelection(conversationId.value);
+ }
queuedInputs.set(conversationId.value, { text, mode: assistantMode.value, action: activeAction.value });
prompt.value = "";
selectedMentions.value = [];
@@ -5709,7 +5915,11 @@ function retryConversationRun(convId: string) {
run.cancelRequested = true;
finishDesktopAiRun(run, "cancelled");
}
- scheduleAutoSend(convId, { text, mode: assistantMode.value, action: activeAction.value }, history.slice(0, lastUserIdx), pluginContextFromMessages(history));
+ // The retry belongs to `convId`, not to whatever chat is on screen, so it runs
+ // on THAT conversation's own mode/action (#12075 R7). It is a continuation of
+ // the same request, not a fresh picker operation, so nothing is recorded.
+ const retrySelection = conversationPickerSelectionFor(convId);
+ scheduleAutoSend(convId, { text, mode: retrySelection.mode, action: retrySelection.action }, history.slice(0, lastUserIdx), pluginContextFromMessages(history));
}
/** Dismisses the "updates while you were away" separator and jumps to the end. */
@@ -5749,9 +5959,13 @@ onMounted(async () => {
conversations.value = await loadAiConversations().catch(() => []);
// Restore per-conversation queued "send later" inputs (parent PRD §5) — they
// are persisted with the conversation and must surface again after a restart.
+ // The queued mode/action belong to the conversation that queued them, not to
+ // whichever chat the panel restores into (#12075 R7); the queued payload is
+ // resolved exactly like a retry would be.
for (const conversation of conversations.value) {
if (conversation.queuedInput) {
- queuedInputs.set(conversation.id, { text: conversation.queuedInput, mode: assistantMode.value, action: activeAction.value });
+ const queuedSelection = conversationPickerSelectionFor(conversation.id);
+ queuedInputs.set(conversation.id, { text: conversation.queuedInput, mode: queuedSelection.mode, action: queuedSelection.action });
}
}
if (backgroundAiRunsEnabled) {
@@ -6085,14 +6299,9 @@ function triggerAction(action: AiAction, instruction?: string) {
if (pluginContext.value) startNewChat();
// External Ask-style entry points (Fix with AI, Explain history) produce/analyze SQL text.
// If the assistant is currently in Agent mode where those actions aren't offered, switch to
- // Ask mode so the action is valid and the menu reflects what actually runs.
- if (!isValidActionForMode(action, assistantMode.value)) {
- // Suppress the mode-switch watch so it doesn't overwrite `action` (set below) with the
- // Ask default — the menu must reflect the action actually being run.
- suppressModeActionReset = true;
- assistantMode.value = "ask";
- }
- activeAction.value = action;
+ // Ask mode so the action is valid and the menu reflects what actually runs. The picker moves
+ // both values at once, so the mode no longer resets the action we are about to set.
+ picker.select({ mode: isValidActionForMode(action, assistantMode.value) ? assistantMode.value : "ask", action });
if (instruction) prompt.value = instruction;
send();
}
@@ -6105,8 +6314,12 @@ function openPluginConversation(request: AiPluginConversationRequest) {
const pluginConnectionId = pluginContextConnectionId(request.context);
const pluginConnection = pluginConnectionId ? connectionStore.getConfig(pluginConnectionId) : undefined;
draftBinding.value = pluginConnection ? { connectionId: pluginConnection.id, connectionName: pluginConnection.name, database: "", schema: undefined } : null;
- assistantMode.value = request.mode === "agent" && !pluginConnection ? "ask" : (request.mode ?? request.context.mode ?? "ask");
- activeAction.value = "general";
+ // The plugin request names a mode explicitly, so this is a user-level choice
+ // and is recorded as this conversation's own selection. The recorded value is
+ // what the plugin ASKED for, not the constrained one: a plugin chat with no
+ // connection degrades to `ask` / `general` in `effective` only, so connecting
+ // later brings the requested Agent mode back (R9/AC6).
+ picker.select({ mode: request.mode ?? request.context.mode ?? "ask", action: "general" });
setPrompt(request.prompt, true);
if (request.send) void send();
}
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts
index 61e0cc0de6..2ae1fda1ed 100644
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationBinding.spec.ts
@@ -56,7 +56,12 @@ describe("AI conversation owns its connection binding (#9902)", () => {
it("does not expose Agent mode for a plugin conversation without a connection", () => {
expect(source).toContain("function canUsePluginAgentMode");
expect(source).toContain('if (mode === "agent" && !canUsePluginAgentMode()) return;');
- expect(source).toContain('request.mode === "agent" && !pluginConnection ? "ask"');
+ // #12075 moved the downgrade out of this function: the request now records
+ // the mode it ASKED for and the picker's capability replay degrades what is
+ // shown, so connecting later brings Agent mode back. The rule itself is
+ // covered in `lib/ai/__tests__/aiConversationPicker.spec.ts`
+ // ("degrades a plugin conversation without a connection…").
+ expect(bodyOf("function openPluginConversation(request: AiPluginConversationRequest)")).toContain('picker.select({ mode: request.mode ?? request.context.mode ?? "ask", action: "general" })');
});
it("rebinding the conversation never rewrites the editor tab or the global active connection", () => {
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationPicker.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationPicker.spec.ts
new file mode 100644
index 0000000000..a4084dd3f3
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.conversationPicker.spec.ts
@@ -0,0 +1,171 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+// Regression coverage for https://github.com/t8y2/dbx/issues/12075:
+//
+// The Ask/Agent mode + action picker used to be two panel-level refs with no
+// per-conversation owner and no persistence, so switching conversations carried
+// one chat's choice into another, closing the AI panel reset it to the settings
+// default ("Ask · 通用问答"), and no conversation ever reopened with its own
+// choice.
+//
+// AiAssistant.vue is a ~6000-line SFC the suite never mounts, so the wiring that
+// gives each conversation its own selection is pinned as text, matching the
+// #9902 pattern in `AiAssistant.conversationBinding.spec.ts`. The rules
+// themselves are unit-tested in `lib/ai/__tests__/aiConversationPicker.spec.ts`,
+// and the restore/record order in
+// `lib/ai/__tests__/aiConversationPickerState.spec.ts`.
+const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
+const rules = readFileSync(new URL("../../../lib/ai/aiConversationPicker.ts", import.meta.url), "utf8");
+const controllerSource = readFileSync(new URL("../../../lib/ai/aiConversationPickerState.ts", import.meta.url), "utf8");
+
+/**
+ * The `{ … }` block that opens on `signature`'s own line. Every pinned signature
+ * below keeps its opening brace as the last one on that line — which is also how
+ * a return type such as `): { mode: string } {` stays unambiguous.
+ */
+function bodyAt(signature: string): string {
+ const start = source.indexOf(signature);
+ expect(start, `expected to find "${signature}" in AiAssistant.vue`).toBeGreaterThanOrEqual(0);
+ const braceStart = source.lastIndexOf("{", source.indexOf("\n", start));
+ expect(source.slice(braceStart, braceStart + 1), `expected "${signature}" to open a block on its line`).toBe("{");
+ let depth = 0;
+ for (let i = braceStart; i < source.length; i++) {
+ if (source[i] === "{") depth++;
+ else if (source[i] === "}") {
+ depth--;
+ if (depth === 0) return source.slice(braceStart, i + 1);
+ }
+ }
+ throw new Error(`unbalanced braces reading body of "${signature}"`);
+}
+
+describe("AI conversation owns its mode + action selection (#12075)", () => {
+ it("keeps the picker selection per conversation, keyed like the skill state", () => {
+ expect(source).toContain("const conversationPickerSelections = createReactiveMap(new Map<string, AiPickerSelection>());");
+ // The unsaved chat is a single slot, so two drafts can never trade values (R4).
+ expect(bodyAt("function pickerSelectionKey()")).toContain("conversationId.value || unsavedConversationKey.value");
+ });
+
+ it("restores the arriving conversation's own selection instead of leaving the previous one", () => {
+ const body = bodyAt("function selectConversation(conv: AiConversation)");
+ expect(body).toContain("restoreConversationPicker(conv)");
+ // The plugin-only branch that always forced `general` was replaced: the
+ // plugin rules are one of the cases `resolveConversationPicker` replays.
+ expect(body).not.toContain('activeAction.value = "general"');
+ expect(bodyAt("function restoreConversationPicker(conv: AiConversation)")).toContain("resolveConversationPicker(pickerRecordFor(conv), pickerAmbient())");
+ });
+
+ it("leaves the new-chat starting point exactly as it was (R3)", () => {
+ const body = bodyAt("function startNewChat()");
+ expect(body).toContain("picker.restoreDefault()");
+ // The settings semantics must survive: `restoreDefault` lands on the
+ // settings default mode and, with the Settings > AI toggle on, on `auto`.
+ expect(body).not.toContain("assistantMode.value =");
+ expect(body).not.toContain("activeAction.value =");
+ expect(controllerSource).toContain("const next = { mode: ambient().defaultMode, action: resolveDefaultPickerSelection(ambient().defaultMode, ambient()) };");
+ expect(rules).toContain('return ambient.defaultAutoRouting ? "auto" : defaultActionForMode(mode);');
+ });
+
+ it("runs another conversation's retry and queued input on that conversation's own values (R7)", () => {
+ const retry = bodyAt("function retryConversationRun(");
+ expect(retry).toContain("const retrySelection = conversationPickerSelectionFor(convId);");
+ expect(retry).toContain("mode: retrySelection.mode, action: retrySelection.action");
+ // Never the visible chat's picker refs.
+ expect(retry).not.toContain("mode: assistantMode.value");
+
+ // The startup restore of persisted "send later" inputs does the same.
+ expect(source).toContain("const queuedSelection = conversationPickerSelectionFor(conversation.id);");
+ expect(source).not.toContain("queuedInputs.set(conversation.id, { text: conversation.queuedInput, mode: assistantMode.value, action: activeAction.value });");
+ });
+
+ it("records only a real picker operation, never a restore or a capability limit", () => {
+ const controller = bodyAt("const picker = createAiConversationPickerController({");
+ expect(controller).toContain("onUserSelection: (selection) => {");
+ expect(controller).toContain("conversationPickerSelections.set(pickerSelectionKey(), selection);");
+ // A pick on an existing conversation must reach disk immediately: closing the
+ // panel unmounts the component and drops the in-memory map.
+ expect(controller).toContain("if (conversationId.value) void persistConversation();");
+
+ // Capability limits go through `applyCapabilities`, which only shapes what is
+ // shown; `restore` never calls the recording hook.
+ expect(bodyAt("function restoreConversationPicker(conv: AiConversation)")).toContain("applyCapabilities(pending, pickerAmbient())");
+ expect(rules).toContain('if (ambient.vectorDb) action = "generate";');
+ expect(controllerSource).toContain("function setPair(desired: AiPickerSelection, recorded?: AiPickerSelection) {");
+ expect(controllerSource).toContain("if (recorded) options.onUserSelection?.(recorded);");
+ });
+
+ it("persists the RECORDED pair with the conversation, not the constrained one", () => {
+ const snapshot = bodyAt("function pickerSnapshotFor(");
+ expect(snapshot).toContain("conversationPickerSelections.get(targetConversationId)");
+ expect(snapshot).toContain("return { assistantMode: existing?.assistantMode, assistantAction: existing?.assistantAction };");
+ // The raw source, reused by every path that rewrites a whole record.
+ expect(bodyAt("function buildConversationSnapshot(")).toContain("...pickerSnapshotFor(targetConversationId),");
+ expect(bodyAt("async function persistPendingInputRecovery(")).toContain("...pickerSnapshotFor(conversation.id),");
+ });
+
+ it("moves an unsaved chat's selection onto the id it adopts, in the same tick as send (R4)", () => {
+ const migrate = bodyAt("function migrateUnsavedPickerSelection(id: string)");
+ expect(migrate).toContain("conversationPickerSelections.delete(unsavedKey);");
+ expect(migrate).toContain("conversationPickerSelections.set(id, selection);");
+ const watcher = bodyAt("watch(conversationId, (id, previous) => {");
+ expect(watcher).toContain("migrateUnsavedPickerSelection(id);");
+ // A draft can never be reopened, so its state moves only onto an id this panel
+ // minted — never onto a record that already exists, which is what a switch to
+ // a conversation from the history list looks like (#12075 review).
+ expect(watcher).toContain("if (conversations.value.some((conversation) => conversation.id === id)) return;");
+ // `send()` mints the id and reads the selection before the watcher flushes,
+ // and it only does so on a mint — never for an id that already has a record.
+ const send = bodyAt("async function send()");
+ expect(send).toContain("const mintedConversationId = !auto && !conversationId.value;");
+ expect(send).toContain("if (mintedConversationId) {");
+ expect(send).toContain("migrateUnsavedPickerSelection(conversationId.value);");
+ // Queued input takes the same route when it mints the id itself.
+ expect(bodyAt("function queueInput()")).toContain("migrateUnsavedPickerSelection(conversationId.value);");
+ });
+
+ it("abandons a draft's state instead of carrying it into the next conversation", () => {
+ const discard = bodyAt("function discardUnsavedDraftState()");
+ expect(discard).toContain("conversationPickerSelections.delete(unsavedKey);");
+ expect(discard).toContain("conversationLoadedSkillIds.delete(unsavedKey);");
+ expect(discard).toContain("unsavedConversationKey.value = `unsaved:${uuid()}`;");
+ // A replaced draft (new chat) and an abandoned one (opening a stored
+ // conversation) both go through the same drop, so the two cannot drift.
+ expect(bodyAt("function clearMessages()")).toContain("discardUnsavedDraftState();");
+ expect(bodyAt("function selectConversation(conv: AiConversation)")).toContain("if (!conversationId.value) discardUnsavedDraftState();");
+ });
+
+ it("drops a deleted conversation's selection with the rest of its state", () => {
+ expect(bodyAt("async function performDeleteConversation(id: string)")).toContain("conversationPickerSelections.delete(id);");
+ });
+
+ it("routes every picker entry point through the controller", () => {
+ // Mode tab, action item, slash command, the "Auto · <action>" chip, the
+ // "Fix with AI" trigger and the plugin request all move the pair together.
+ expect(bodyAt('function switchModeActionTab(mode: "ask" | "agent")')).toContain("picker.selectMode(mode);");
+ expect(bodyAt("function selectAction(action: AiActionSelection)")).toContain("picker.selectAction(action);");
+ expect(bodyAt("function switchToRoutedAction(action: AiAction | null | undefined)")).toContain("picker.select({");
+ expect(bodyAt("function triggerAction(action: AiAction, instruction?: string)")).toContain("picker.select({");
+ expect(bodyAt("function openPluginConversation(request: AiPluginConversationRequest)")).toContain("picker.select({");
+ // The bare refs are no longer written outside the controller, and the
+ // hand-rolled reset handshake is gone with them.
+ expect(source).not.toContain("activeAction.value = resolveDefaultActionSelection");
+ expect(source).not.toContain("suppressModeActionReset");
+ });
+
+ it("re-derives the shown pair when a capability comes or goes, instead of degrading one way", () => {
+ // A capability limit belongs to `effective`, so it has to be recomputed from
+ // the conversation's recording when the environment changes. The one-way
+ // downgrades that used to live here stranded the panel on the degraded value:
+ // `send()` reads the shown mode, so a connection that merely blipped kept an
+ // Agent conversation sending as Ask.
+ expect(bodyAt("function reapplyPickerCapabilities()")).toContain("resolveConversationPicker(pickerRecordFor(conversation), pickerAmbient()).effective");
+ expect(bodyAt("function reapplyPickerCapabilities()")).toContain("applyCapabilities(pending, pickerAmbient())");
+ // The capability watch is `immediate`, so it is declared below the
+ // per-conversation key maps it reads (a TDZ otherwise).
+ expect(source).toContain("watch([pluginContext, boundConnection], () => reapplyPickerCapabilities(), { immediate: true });");
+ // Nothing writes the pair outside the controller — not even a capability.
+ expect(source).not.toMatch(/\bassistantMode\.value = /);
+ expect(source).not.toMatch(/\bactiveAction\.value = /);
+ });
+});
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts
index 7ab23012a8..50694e5f07 100644
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.mount.spec.ts
@@ -250,7 +250,7 @@ function stubResizeObserver(): Array<{ callback: ResizeObserverCallback; targets
async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig, configureSettings?: (settings: ReturnType<typeof useSettingsStore>) => void, pluginRecommendations?: PluginAiRecommendationHostUpdate, extraConnections: ConnectionConfig[] = []) {
const pinia = createPinia();
const errors: unknown[] = [];
- const panelRef = ref<{ openExternalContext: (request: AiExternalContextRequest) => void } | null>(null);
+ const panelRef = ref<{ openExternalContext: (request: AiExternalContextRequest) => void; selectConversationById: (convId: string) => void } | null>(null);
const app = createApp({ render: () => h(TooltipProvider, () => h(AiAssistant, { ref: panelRef, connection, pluginRecommendations })) });
app.use(pinia);
app.use(i18n);
@@ -269,7 +269,7 @@ async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig
});
// Let mount-time loads settle so their failures surface here too.
await new Promise((resolve) => setTimeout(resolve, 20));
- return { errors, container, panelRef };
+ return { errors, container, panelRef, pinia };
}
describe("AiAssistant mount", () => {
@@ -864,6 +864,81 @@ describe("AiAssistant mount", () => {
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
+ // #12075 review: a draft can never be reopened, so its picker selection must not
+ // travel into a conversation opened from the list. The leak only surfaced one
+ // step later — reopening that conversation showed the abandoned draft's pick
+ // instead of the value it had recorded.
+ it("does not hand an abandoned draft's picker selection to a conversation opened from the list", async () => {
+ aiAssistantMountApi.conversations = [storedConversation({ id: "conv-b", connectionId: "", database: "", connectionName: "", assistantMode: "ask", assistantAction: "optimize" }), storedConversation({ id: "conv-c", connectionId: "", database: "", connectionName: "" })];
+ const { errors, container, panelRef } = await mountPanel(true, undefined, (settings) => {
+ configureAiPanel(settings);
+ // Nothing is restored, so the panel opens on a draft (conversationId "").
+ settings.restoreLastConversation = false;
+ });
+ expect(errors.map(String)).toEqual([]);
+
+ const modeTrigger = () => container.querySelector<HTMLButtonElement>(".ai-mode-action-trigger")!;
+ // Pick Agent on the draft. It has no id yet, so nothing may be persisted.
+ modeTrigger().click();
+ await settle();
+ Array.from(document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button'))
+ .find((button) => button.textContent?.trim() === i18n.global.t("ai.modes.agent"))!
+ .click();
+ await settle();
+ expect(modeTrigger().textContent).toContain(i18n.global.t("ai.modes.agent"));
+ expect(aiAssistantMountApi.savedConversations).toEqual([]);
+
+ // Open a stored conversation, leave it, and come back to it.
+ panelRef.value!.selectConversationById("conv-b");
+ await settle();
+ expect(modeTrigger().textContent).toContain(i18n.global.t("ai.actions.optimize"));
+ panelRef.value!.selectConversationById("conv-c");
+ await settle();
+ panelRef.value!.selectConversationById("conv-b");
+ await settle();
+
+ // B still shows what B recorded: the abandoned draft's Agent pick is gone.
+ expect(modeTrigger().textContent).toContain(i18n.global.t("ai.actions.optimize"));
+ expect(modeTrigger().textContent).not.toContain(i18n.global.t("ai.modes.agent"));
+ expect(aiAssistantMountApi.savedConversations).toEqual([]);
+ expect(errors.map(String)).toEqual([]);
+ });
+
+ // #12075: a capability that comes back must restore the conversation's own
+ // recording. The app's connections load after the panel opens, so a plugin
+ // conversation can legitimately be on screen with no resolvable connection and
+ // has to recover Agent mode once the connection is there. A one-way downgrade
+ // stranded it on Ask, and `send()` reads the shown mode — so an Agent
+ // conversation would keep sending as Ask for the rest of the session.
+ it("restores a plugin conversation's recorded Agent mode when its connection becomes available", async () => {
+ aiAssistantMountApi.conversations = [
+ storedConversation({
+ id: "conv-plugin",
+ connectionId: "postgres",
+ connectionName: "PostgreSQL",
+ assistantMode: "agent",
+ assistantAction: "general",
+ pluginContext: { pluginId: "sample.plugin", pluginName: "Sample", title: "Cluster", capturedAt: "2026-09-27T00:00:00.000Z", data: { connectionId: "postgres" } },
+ }),
+ ];
+ // No connection registered yet: the panel opens before the connections load.
+ const { errors, container, pinia } = await mountPanel(true, undefined, (settings) => {
+ configureAiPanel(settings);
+ settings.restoreLastConversation = true;
+ });
+ await settle();
+ const modeTrigger = () => container.querySelector<HTMLButtonElement>(".ai-mode-action-trigger")!;
+ // Degraded: without a connection this plugin conversation cannot offer Agent.
+ expect(modeTrigger().textContent).toContain(i18n.global.t("ai.modes.ask"));
+
+ useConnectionStore(pinia).connections = [POSTGRES];
+ await settle();
+
+ // The connection arrived: the recorded Agent mode comes back on its own.
+ expect(modeTrigger().textContent).toContain(i18n.global.t("ai.modes.agent"));
+ expect(errors.map(String)).toEqual([]);
+ });
+
it("reuses the chat already on the selection's namespace and attaches the chip there", async () => {
aiAssistantMountApi.conversations = [storedConversation({ id: "conv-b", connectionId: "postgres", database: "app", connectionName: "PostgreSQL" })];
const { errors, container, panelRef } = await mountPanel(true, POSTGRES, (settings) => {
diff --git a/apps/desktop/src/lib/ai/__tests__/aiConversationPicker.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiConversationPicker.spec.ts
new file mode 100644
index 0000000000..b17a4e4c54
--- /dev/null
+++ b/apps/desktop/src/lib/ai/__tests__/aiConversationPicker.spec.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from "vitest";
+import { applyCapabilities, isPickerSelectionValidForMode, resolveConversationPicker, resolveDefaultPickerAction, resolveDefaultPickerSelection, type AiPickerAmbient } from "@/lib/ai/aiConversationPicker";
+
+/**
+ * #12075 / #12076 — a conversation owns its Ask/Agent mode and action selection.
+ *
+ * These are the R9 decision table and the R10 read priority as pure rules. The
+ * component wiring is pinned separately in
+ * `components/editor/__tests__/AiAssistant.conversationPicker.spec.ts`, but the
+ * fallback / write-back semantics live here because a text assertion cannot show
+ * whether a capability limit leaked into the recorded value.
+ */
+
+function ambient(overrides: Partial<AiPickerAmbient> = {}): AiPickerAmbient {
+ return { defaultMode: "ask", defaultAutoRouting: false, ...overrides };
+}
+
+describe("resolveConversationPicker", () => {
+ it("restores a conversation's own recorded selection in both layers", () => {
+ const resolution = resolveConversationPicker({ assistantMode: "agent", assistantAction: "query" }, ambient());
+ expect(resolution.raw).toEqual({ mode: "agent", action: "query" });
+ expect(resolution.effective).toEqual({ mode: "agent", action: "query" });
+ });
+
+ it("keeps `auto` as a first-class recorded value, not a routed concrete action", () => {
+ // R8: the picker restores the entry the user chose; routing happens at send.
+ for (const mode of ["ask", "agent"] as const) {
+ const resolution = resolveConversationPicker({ assistantMode: mode, assistantAction: "auto" }, ambient({ defaultAutoRouting: false }));
+ expect(resolution.raw.action).toBe("auto");
+ expect(resolution.effective.action).toBe("auto");
+ }
+ });
+
+ it("falls back on an unknown mode without writing it back", () => {
+ for (const stored of [undefined, "", "AGENT", "expert"]) {
+ const resolution = resolveConversationPicker({ assistantMode: stored, assistantAction: "optimize" }, ambient({ defaultMode: "agent" }));
+ // `optimize` is an Ask action, so the Agent default mode makes it
+ // incompatible — the mode's own default is used instead (next case).
+ expect(resolution.raw.mode).toBeUndefined();
+ expect(resolution.effective.mode).toBe("agent");
+ expect(resolution.effective.action).toBe("general");
+ expect(resolution.raw.action).toBe("optimize");
+ }
+ });
+
+ it("falls back on an unknown mode to a compatible default action", () => {
+ const resolution = resolveConversationPicker({ assistantMode: undefined, assistantAction: "optimize" }, ambient({ defaultMode: "ask" }));
+ expect(resolution.effective).toEqual({ mode: "ask", action: "optimize" });
+ // The action was known and valid, so it is still the recorded value.
+ expect(resolution.raw.action).toBe("optimize");
+ });
+
+ it("falls back on an unknown action through the default-selection chain", () => {
+ const off = resolveConversationPicker({ assistantMode: "agent", assistantAction: "summarize" }, ambient({ defaultAutoRouting: false }));
+ expect(off.effective).toEqual({ mode: "agent", action: "general" });
+ expect(off.raw).toEqual({ mode: "agent", action: undefined });
+
+ // R9 blurbs "the fallback is re-validated by the same chain": the Auto
+ // toggle makes the fallback the Auto entry, exactly like a new chat.
+ const on = resolveConversationPicker({ assistantMode: "agent" }, ambient({ defaultAutoRouting: true }));
+ expect(on.effective).toEqual({ mode: "agent", action: "auto" });
+ });
+
+ it("lands a known-but-incompatible action on the mode's own default, never migrating the mode", () => {
+ const resolution = resolveConversationPicker({ assistantMode: "ask", assistantAction: "executeAndExplain" }, ambient({ defaultMode: "agent" }));
+ expect(resolution.effective).toEqual({ mode: "ask", action: "general" });
+ expect(resolution.raw).toEqual({ mode: "ask", action: "executeAndExplain" });
+ });
+
+ it("treats `auto` as legal in every mode while a concrete action is mode-bound", () => {
+ expect(isPickerSelectionValidForMode("auto", "ask")).toBe(true);
+ expect(isPickerSelectionValidForMode("auto", "agent")).toBe(true);
+ expect(isPickerSelectionValidForMode("query", "agent")).toBe(true);
+ expect(isPickerSelectionValidForMode("query", "ask")).toBe(false);
+ });
+
+ it("reads assistant_mode before pluginContext.mode and the settings default (R10)", () => {
+ // Both present: the column wins.
+ expect(resolveConversationPicker({ assistantMode: "agent", assistantAction: "query", pluginContextMode: "ask" }, ambient()).effective).toEqual({ mode: "agent", action: "query" });
+ // Only the legacy plugin field: it is still honoured.
+ expect(resolveConversationPicker({ pluginContextMode: "agent", assistantAction: "query" }, ambient()).effective).toEqual({ mode: "agent", action: "query" });
+ // Neither: the settings default.
+ expect(resolveConversationPicker({}, ambient({ defaultMode: "agent" })).effective.mode).toBe("agent");
+ // An unknown pluginContext value falls through to the default too.
+ expect(resolveConversationPicker({ pluginContextMode: "hybrid" }, ambient({ defaultMode: "agent" })).effective.mode).toBe("agent");
+ });
+
+ it("does not write the plugin fallback back into raw", () => {
+ const resolution = resolveConversationPicker({ pluginContextMode: "agent" }, ambient({ defaultMode: "ask" }));
+ expect(resolution.effective.mode).toBe("agent");
+ // `pluginContext.mode` stays the single fallback source; nothing is promoted
+ // into the new column (R10 "no double write").
+ expect(resolution.raw.mode).toBeUndefined();
+ });
+
+ it("limits a vector-DB conversation to `generate` without overwriting the record", () => {
+ const resolution = resolveConversationPicker({ assistantMode: "agent", assistantAction: "query" }, ambient({ vectorDb: true }));
+ expect(resolution.effective).toEqual({ mode: "agent", action: "generate" });
+ expect(resolution.raw).toEqual({ mode: "agent", action: "query" });
+
+ // Same conversation on a relational connection restores the original pick.
+ expect(resolveConversationPicker({ assistantMode: "agent", assistantAction: "query" }, ambient()).effective).toEqual({ mode: "agent", action: "query" });
+ });
+
+ it("degrades a plugin conversation without a connection but keeps the recorded Agent", () => {
+ const record = { assistantMode: "agent", assistantAction: "query" };
+ const degraded = resolveConversationPicker(record, ambient({ pluginSession: true, pluginWithoutConnection: true }));
+ expect(degraded.effective).toEqual({ mode: "ask", action: "general" });
+ expect(degraded.raw).toEqual({ mode: "agent", action: "query" });
+
+ // Once a connection exists the original Agent + action come back.
+ const connected = resolveConversationPicker(record, ambient({ pluginSession: true }));
+ expect(connected.effective).toEqual({ mode: "agent", action: "general" });
+ expect(connected.raw).toEqual({ mode: "agent", action: "query" });
+ });
+
+ it("keeps a plugin conversation on `general` because the plugin lane always sends it", () => {
+ const resolution = resolveConversationPicker({ assistantMode: "agent", assistantAction: "auto" }, ambient({ pluginSession: true }));
+ expect(resolution.effective.action).toBe("general");
+ expect(resolution.raw.action).toBe("auto");
+ });
+});
+
+describe("default selection helpers", () => {
+ it("returns the Auto entry only when the Settings toggle says so (#9118)", () => {
+ expect(resolveDefaultPickerSelection("ask", ambient({ defaultAutoRouting: false }))).toBe("general");
+ expect(resolveDefaultPickerSelection("agent", ambient({ defaultAutoRouting: false }))).toBe("general");
+ expect(resolveDefaultPickerSelection("agent", ambient({ defaultAutoRouting: true }))).toBe("auto");
+ });
+
+ it("never returns the Auto sentinel from the concrete default", () => {
+ expect(resolveDefaultPickerAction("agent", ambient({ defaultAutoRouting: true }))).toBe("general");
+ expect(resolveDefaultPickerAction("ask", ambient())).toBe("general");
+ });
+
+ it("forces `generate` for vector DBs and `general` for plugin lanes", () => {
+ expect(resolveDefaultPickerSelection("ask", ambient({ vectorDb: true, defaultAutoRouting: true }))).toBe("generate");
+ expect(resolveDefaultPickerAction("agent", ambient({ vectorDb: true }))).toBe("generate");
+ expect(resolveDefaultPickerSelection("agent", ambient({ pluginSession: true }))).toBe("general");
+ expect(resolveDefaultPickerAction("agent", ambient({ pluginSession: true }))).toBe("general");
+ });
+});
+
+describe("applyCapabilities", () => {
+ it("is the only place a limit is applied, leaving raw untouched upstream", () => {
+ expect(applyCapabilities({ mode: "agent", action: "query" }, ambient())).toEqual({ mode: "agent", action: "query" });
+ expect(applyCapabilities({ mode: "agent", action: "query" }, ambient({ vectorDb: true }))).toEqual({ mode: "agent", action: "generate" });
+ expect(applyCapabilities({ mode: "agent", action: "exploreSchema" }, ambient({ pluginSession: true, pluginWithoutConnection: true }))).toEqual({ mode: "ask", action: "general" });
+ });
+});
diff --git a/apps/desktop/src/lib/ai/__tests__/aiConversationPickerState.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiConversationPickerState.spec.ts
new file mode 100644
index 0000000000..18f3c299bc
--- /dev/null
+++ b/apps/desktop/src/lib/ai/__tests__/aiConversationPickerState.spec.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it, vi } from "vitest";
+import { createAiConversationPickerController } from "@/lib/ai/aiConversationPickerState";
+import type { AiPickerAmbient } from "@/lib/ai/aiConversationPicker";
+import type { AiAssistantMode } from "@/types/ai";
+
+/**
+ * AC15 — the wiring order, not the rule table.
+ *
+ * A text assertion cannot show that restoring a conversation's mode leaves its
+ * action alone; the pre-#12075 panel had two refs and a `watch(mode)` that reset
+ * the action, which is exactly how "restore" silently turned into "the mode
+ * default". These cases drive the real controller with a reactive ambient.
+ */
+
+function ambient(overrides: Partial<AiPickerAmbient> = {}): AiPickerAmbient {
+ return { defaultMode: "ask", defaultAutoRouting: false, ...overrides };
+}
+
+function controller(overrides: Partial<AiPickerAmbient> = {}) {
+ const onUserSelection = vi.fn();
+ const state = { ...ambient(overrides) };
+ const picker = createAiConversationPickerController({ ambient: () => state, onUserSelection });
+ return { picker, onUserSelection, state };
+}
+
+describe("createAiConversationPickerController", () => {
+ it("restores a conversation's own pair without resetting the action through the mode watcher", async () => {
+ const { picker, onUserSelection } = controller();
+ picker.restore({ mode: "agent", action: "exploreSchema" });
+
+ // Mode first, action second is the historical restore order — and it used to
+ // be undone by the mode watcher on the next flush.
+ expect(picker.mode.value).toBe("agent");
+ expect(picker.action.value).toBe("exploreSchema");
+ await Promise.resolve();
+ expect(picker.mode.value).toBe("agent");
+ expect(picker.action.value).toBe("exploreSchema");
+ // A restore is not a user operation, so nothing is written back.
+ expect(onUserSelection).not.toHaveBeenCalled();
+ });
+
+ it("keeps a later mode change resetting the action (pre-existing behavior, #9118)", () => {
+ const { picker } = controller();
+ picker.restore({ mode: "agent", action: "exploreSchema" });
+ picker.selectMode("ask");
+ // The mode's own default, not the Agent action it was standing on.
+ expect(picker.action.value).toBe("general");
+ });
+
+ it("lets a mode change land on the Auto entry only when the settings toggle says so", () => {
+ const { picker } = controller({ defaultAutoRouting: true });
+ picker.selectMode("agent");
+ expect(picker.action.value).toBe("auto");
+ picker.selectMode("ask");
+ expect(picker.action.value).toBe("auto");
+ });
+
+ it("does not let an earlier pair write poison the next user mode change", () => {
+ // The ownership handshake is consumed synchronously by the assignment that
+ // changes the mode; a leftover flag would swallow the next reset.
+ for (const sameMode of [false, true]) {
+ const { picker } = controller();
+ // A pair write that moves the mode (false) and one that does not (true).
+ picker.restore({ mode: sameMode ? "ask" : "agent", action: "query" });
+ picker.restore({ mode: "agent", action: "exploreSchema" });
+ picker.selectMode("agent");
+ expect(picker.action.value).toBe("general");
+ picker.selectMode("ask");
+ expect(picker.action.value).toBe("general");
+ }
+ });
+
+ it("records a user picker operation with the chosen entry, not the routed action", () => {
+ const { picker, onUserSelection } = controller();
+ picker.selectAction("auto");
+ expect(onUserSelection).toHaveBeenLastCalledWith({ mode: "ask", action: "auto" });
+ picker.selectMode("agent");
+ expect(onUserSelection).toHaveBeenLastCalledWith({ mode: "agent", action: "general" });
+ });
+
+ it("records the user's own value even when a capability limits what is shown (R9)", () => {
+ const { picker, onUserSelection, state } = controller();
+ picker.selectMode("agent");
+ picker.selectAction("query");
+ expect(picker.action.value).toBe("query");
+
+ // The connection turns into a vector DB mid-session: the picker is hidden and
+ // forced onto `generate`, but the recorded value stays `query`.
+ state.vectorDb = true;
+ picker.restore({ mode: "agent", action: "query" });
+ expect(picker.action.value).toBe("generate");
+ expect(onUserSelection).toHaveBeenLastCalledWith({ mode: "agent", action: "query" });
+ expect(onUserSelection).toHaveBeenCalledTimes(2);
+
+ // Back on a relational connection, the original pick returns.
+ state.vectorDb = false;
+ picker.restore({ mode: "agent", action: "query" });
+ expect(picker.action.value).toBe("query");
+ });
+
+ it("degrades a plugin conversation without a connection but restores it with one", () => {
+ const { picker, state } = controller();
+ state.pluginSession = true;
+ state.pluginWithoutConnection = true;
+ picker.restore({ mode: "agent", action: "query" });
+ expect(picker.mode.value).toBe("ask");
+ expect(picker.action.value).toBe("general");
+
+ state.pluginWithoutConnection = false;
+ picker.restore({ mode: "agent", action: "query" });
+ expect(picker.mode.value).toBe("agent");
+ expect(picker.action.value).toBe("general");
+ });
+
+ it("starts a new chat from the settings default in every toggle state (R3)", () => {
+ const cases: Array<{ mode: AiAssistantMode; auto: boolean; expected: { mode: AiAssistantMode; action: string } }> = [
+ { mode: "ask", auto: false, expected: { mode: "ask", action: "general" } },
+ { mode: "agent", auto: false, expected: { mode: "agent", action: "general" } },
+ { mode: "agent", auto: true, expected: { mode: "agent", action: "auto" } },
+ ];
+ for (const item of cases) {
+ const { picker } = controller({ defaultMode: item.mode, defaultAutoRouting: item.auto });
+ // Start from a different pair: a new chat must not inherit it.
+ picker.restore({ mode: "agent", action: "exploreSchema" });
+ picker.restoreDefault();
+ expect(picker.mode.value).toBe(item.expected.mode);
+ expect(picker.action.value).toBe(item.expected.action);
+ }
+ });
+
+ it("forces vector DBs onto `generate` even for a new chat, where Auto is never offered", () => {
+ const { picker } = controller({ defaultMode: "agent", defaultAutoRouting: true, vectorDb: true });
+ picker.restoreDefault();
+ expect(picker.action.value).toBe("generate");
+ });
+});
diff --git a/apps/desktop/src/lib/ai/aiConversationPicker.ts b/apps/desktop/src/lib/ai/aiConversationPicker.ts
new file mode 100644
index 0000000000..9065bcf54d
--- /dev/null
+++ b/apps/desktop/src/lib/ai/aiConversationPicker.ts
@@ -0,0 +1,181 @@
+import { AGENT_ACTIONS, ASK_ACTIONS, defaultActionForMode, isValidActionForMode, type AiAction, type AiActionSelection } from "@/lib/ai/ai";
+import type { AiAssistantMode } from "@/types/ai";
+
+/**
+ * Per-conversation picker selection (Ask/Agent mode + action) — issue #12075.
+ *
+ * The picker used to be panel-level Vue refs only, so switching conversations
+ * carried one chat's choice into another, and reopening a conversation always
+ * fell back to the settings default. This module owns the whole rule set for
+ *
+ * (persisted conversation record | unsaved-chat key, ambient capabilities)
+ * → { raw, effective }
+ *
+ * and is deliberately free of Vue, stores and DOM so the rules are unit-tested
+ * directly (`__tests__/aiConversationPicker.spec.ts`), matching the #9902
+ * pattern of `aiConversationBinding.ts`.
+ *
+ * Two layers, never merged (R9):
+ *
+ * - `raw` — the persisted original selection. Written ONLY when the user
+ * operates the picker (or an entry point that explicitly asks for a mode /
+ * action). A capability limit, a degradation and a fallback NEVER write back.
+ * - `effective` — what is displayed and used for the next send. Always a legal
+ * combination.
+ */
+
+/**
+ * The loose persisted shape. The columns are plain strings on purpose: a future
+ * mode or action must not need a migration, so unknown values are validated
+ * here instead of being rejected at the storage boundary.
+ */
+export interface AiPickerConversationRecord {
+ /** `AiConversation.assistantMode` (columns added for #12075). */
+ assistantMode?: string;
+ /** `AiConversation.assistantAction`. */
+ assistantAction?: string;
+ /** Legacy fallback source for plugin conversations (R10 read priority). */
+ pluginContextMode?: string;
+}
+
+/** The environment the selection has to be legal in. */
+export interface AiPickerAmbient {
+ /** `settings.defaultAiMode` — also the new-chat start mode. */
+ defaultMode: AiAssistantMode;
+ /** `settings.defaultAutoRouting` — the Settings > AI "Auto" toggle (#9118). */
+ defaultAutoRouting: boolean;
+ /** Vector-DB connection: the action menu is hidden and `generate` is forced. */
+ vectorDb?: boolean;
+ /**
+ * A plugin conversation: the action menu is hidden and the action is locked to
+ * `general` (the plugin lane always sends `general`). Set only on the restore /
+ * background paths — the existing "pick a mode default" call sites
+ * (mode switch, panel mount, new chat) must keep returning the Auto entry when
+ * the toggle says so.
+ */
+ pluginSession?: boolean;
+ /** A plugin conversation with no resolvable connection: mode degrades to `ask`. */
+ pluginWithoutConnection?: boolean;
+}
+
+/** Persisted original selection; each field is absent until the user picks it. */
+export interface AiPickerRaw {
+ mode?: AiAssistantMode;
+ action?: AiActionSelection;
+}
+
+/** Displayed / next-send selection. Always legal. */
+export interface AiPickerSelection {
+ mode: AiAssistantMode;
+ action: AiActionSelection;
+}
+
+export interface AiPickerResolution {
+ raw: AiPickerRaw;
+ effective: AiPickerSelection;
+}
+
+/**
+ * Every selectable picker entry. Derived from the mode tables so a new action
+ * joins the known set automatically, and `auto` is added explicitly: it is a
+ * valid picker entry in *every* mode and `isValidActionForMode` deliberately
+ * does not know it (it must never reach the send path, #9118).
+ */
+const KNOWN_SELECTIONS: readonly string[] = [...ASK_ACTIONS, ...AGENT_ACTIONS, "auto"];
+
+function knownMode(value: string | undefined | null): AiAssistantMode | undefined {
+ return value === "ask" || value === "agent" ? value : undefined;
+}
+
+function knownSelection(value: string | undefined | null): AiActionSelection | undefined {
+ return value && KNOWN_SELECTIONS.includes(value) ? (value as AiActionSelection) : undefined;
+}
+
+/**
+ * Whether `selection` may be used in `mode`. `auto` is legal everywhere and is
+ * checked first: `isValidActionForMode` only knows concrete actions.
+ */
+export function isPickerSelectionValidForMode(selection: AiActionSelection, mode: AiAssistantMode): boolean {
+ if (selection === "auto") return true;
+ return isValidActionForMode(selection, mode);
+}
+
+/**
+ * The "land on the default" selection for `mode`: the mode's concrete action, or
+ * the `auto` entry when the Settings > AI toggle asks for it.
+ *
+ * Used by every site that starts from a default — a new chat, a mode switch, the
+ * panel-mount init (#9118) — and by R9's "unknown action" fallback.
+ */
+export function resolveDefaultPickerSelection(mode: AiAssistantMode, ambient: AiPickerAmbient): AiActionSelection {
+ if (ambient.pluginSession) return "general";
+ if (ambient.vectorDb) return "generate";
+ return ambient.defaultAutoRouting ? "auto" : defaultActionForMode(mode);
+}
+
+/**
+ * The concrete default action for `mode` — never `auto`, because the callers
+ * (confirmed-write continuations, request assembly) must not hand a sentinel to
+ * the transport. Also R9's "known but incompatible action" fallback: an action
+ * that does not exist in the current mode lands on that mode's own default
+ * instead of dragging the mode along.
+ */
+export function resolveDefaultPickerAction(mode: AiAssistantMode, ambient: AiPickerAmbient): AiAction {
+ if (ambient.pluginSession) return "general";
+ if (ambient.vectorDb) return "generate";
+ return defaultActionForMode(mode);
+}
+
+/**
+ * Replay a conversation's own picker state, with the R9 decision table applied:
+ *
+ * | case | effective | written back to raw |
+ * |---|---|---|
+ * | valid value | equals raw | — |
+ * | unknown mode (absent, or an old record) | `ambient.defaultMode` | no |
+ * | unknown action (absent, or an old record) | `resolveDefaultPickerSelection` | no |
+ * | known action, incompatible with the mode | the mode's own default | no |
+ * | capability limit (vector DB / plugin session) | the constrained value | no |
+ *
+ * Reading priority is R10's: `assistant_mode` → `pluginContext.mode` →
+ * `settings.defaultAiMode`. A capability limit is applied last and touches
+ * `effective` only, so a conversation keeps the user's original pick and gets it
+ * back once the restriction is lifted (relational connection, connected plugin).
+ */
+export function resolveConversationPicker(record: AiPickerConversationRecord, ambient: AiPickerAmbient): AiPickerResolution {
+ const rawMode = knownMode(record.assistantMode);
+ const rawAction = knownSelection(record.assistantAction);
+ const mode = rawMode ?? knownMode(record.pluginContextMode) ?? ambient.defaultMode;
+
+ // Both fallbacks are guaranteed legal by construction, so the chain needs no
+ // second validation pass (R9): the default selection is either `auto`, which
+ // every mode accepts, or the mode's own default action.
+ const action: AiActionSelection = rawAction ? (isPickerSelectionValidForMode(rawAction, mode) ? rawAction : resolveDefaultPickerAction(mode, ambient)) : resolveDefaultPickerSelection(mode, ambient);
+
+ return {
+ raw: { mode: rawMode, action: rawAction },
+ effective: applyCapabilities({ mode, action }, ambient),
+ };
+}
+
+/**
+ * The capability limits of R5, applied to `effective` only.
+ *
+ * - Vector DB: the action picker is hidden, so the action stays `generate`.
+ * - Plugin conversation: the composer hides the action menu and the plugin lane
+ * always sends `general`; with no resolvable connection Agent is unreachable,
+ * so the mode degrades to `ask`.
+ *
+ * `raw` is untouched by design: both restrictions are environmental, and the
+ * user's own choice must come back when the environment changes.
+ */
+export function applyCapabilities(selection: AiPickerSelection, ambient: AiPickerAmbient): AiPickerSelection {
+ let mode = selection.mode;
+ let action = selection.action;
+ if (ambient.vectorDb) action = "generate";
+ if (ambient.pluginSession) {
+ action = "general";
+ if (ambient.pluginWithoutConnection) mode = "ask";
+ }
+ return { mode, action };
+}
diff --git a/apps/desktop/src/lib/ai/aiConversationPickerState.ts b/apps/desktop/src/lib/ai/aiConversationPickerState.ts
new file mode 100644
index 0000000000..ac7649c7bd
--- /dev/null
+++ b/apps/desktop/src/lib/ai/aiConversationPickerState.ts
@@ -0,0 +1,114 @@
+import { ref, watch, type Ref } from "vue";
+import type { AiAssistantMode } from "@/types/ai";
+import type { AiActionSelection } from "@/lib/ai/ai";
+import { applyCapabilities, resolveDefaultPickerSelection, type AiPickerAmbient, type AiPickerSelection } from "@/lib/ai/aiConversationPicker";
+
+/**
+ * The AI panel's Ask/Agent mode + action picker, owned as a pair (#12075).
+ *
+ * Before this existed the two values were independent panel-level refs and a
+ * `watch(mode)` reset the action, so restoring a conversation's own selection
+ * raced the reset: `assistantMode.value = stored; activeAction.value = stored`
+ * looked right until the watcher flushed and overwrote the action with the mode
+ * default. That is why the reset lives *inside* this controller now — a single
+ * writer of the pair, which makes the restore order structurally correct instead
+ * of relying on a flag each call site has to remember.
+ *
+ * Nothing here is persisted; `raw` belongs to the conversation record
+ * (`AiConversation.assistantMode` / `assistantAction`) and is only written by
+ * `onUserSelection`, which callers use to store a genuine picker operation (R9).
+ */
+export interface AiConversationPickerControllerOptions {
+ /** Ambient capabilities, read lazily so a settings/connection change is picked
+ * up without rebuilding the controller. */
+ ambient: () => AiPickerAmbient;
+ /**
+ * Called ONLY for a user picker operation, with the pair the user actually
+ * chose (before capability limits). The caller records it as the
+ * conversation's own `raw` selection; a restore, a capability limit and a
+ * routed/external set never reach this hook (R9's "no write-back" rule).
+ */
+ onUserSelection?: (selection: AiPickerSelection) => void;
+}
+
+export interface AiConversationPickerController {
+ /** Effective mode — what the picker shows and the next send uses. */
+ mode: Ref<AiAssistantMode>;
+ /** Effective action; always a legal entry for `mode` (incl. `auto`). */
+ action: Ref<AiActionSelection>;
+ /** Restore a conversation's own effective pair (R2), capabilities included. */
+ restore(selection: AiPickerSelection): void;
+ /** New chat / panel mount: the settings default mode and its default entry.
+ * Unchanged by #12075 (R3) — `defaultAutoRouting` still decides the entry. */
+ restoreDefault(): AiPickerSelection;
+ /** User picked a mode tab: lands on that mode's default entry and records it. */
+ selectMode(mode: AiAssistantMode): AiPickerSelection;
+ /** User picked an action entry (incl. `auto`) — recorded (R8/R9). */
+ selectAction(action: AiActionSelection): AiPickerSelection;
+ /** User picked an explicit mode+action pair (the "Auto · <action>" chip, which
+ * switches the picker onto the action that ran; the plugin request) — recorded. */
+ select(selection: AiPickerSelection): AiPickerSelection;
+}
+
+export function createAiConversationPickerController(options: AiConversationPickerControllerOptions): AiConversationPickerController {
+ const ambient = options.ambient;
+ const mode = ref<AiAssistantMode>(ambient().defaultMode);
+ const action = ref<AiActionSelection>("general");
+
+ // Ownership handshake. `sync` flush is deliberate: the flag is consumed by the
+ // very assignment that changes the mode, so a pair write can never poison a
+ // later, unrelated mode change (the failure mode a pre-flush flag has — the
+ // watcher has not run yet when the next writer looks at it).
+ let ownedModeChange = false;
+ watch(
+ mode,
+ (next) => {
+ if (ownedModeChange) {
+ ownedModeChange = false;
+ return;
+ }
+ action.value = resolveDefaultPickerSelection(next, ambient());
+ },
+ { flush: "sync" },
+ );
+
+ /**
+ * The only writer of the pair. `recorded` is the pair the user chose, before
+ * capability limits: `effective` may be constrained (a vector DB must stay on
+ * `generate`), while the recorded value stays the user's own (R9/R10).
+ */
+ function setPair(desired: AiPickerSelection, recorded?: AiPickerSelection) {
+ const effective = applyCapabilities(desired, ambient());
+ if (mode.value !== effective.mode) ownedModeChange = true;
+ mode.value = effective.mode;
+ action.value = effective.action;
+ if (recorded) options.onUserSelection?.(recorded);
+ }
+
+ return {
+ mode,
+ action,
+ restore(selection) {
+ setPair(selection);
+ },
+ restoreDefault() {
+ const next = { mode: ambient().defaultMode, action: resolveDefaultPickerSelection(ambient().defaultMode, ambient()) };
+ setPair(next);
+ return next;
+ },
+ selectMode(nextMode) {
+ const desired = { mode: nextMode, action: resolveDefaultPickerSelection(nextMode, ambient()) };
+ setPair(desired, desired);
+ return desired;
+ },
+ selectAction(nextAction) {
+ const desired = { mode: mode.value, action: nextAction };
+ setPair(desired, desired);
+ return desired;
+ },
+ select(selection) {
+ setPair(selection, selection);
+ return selection;
+ },
+ };
+}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index f5af507749..bd75c4b52f 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1442,6 +1442,17 @@ export interface AiConversation {
/** One editable "send later" input saved while an active run occupies the
* conversation (parent PRD §5). Persisted with the conversation. */
queuedInput?: string;
+ /** Ask/Agent mode the user picked for THIS conversation (#12075). Written
+ * only by a picker operation, so a capability limit (vector DB, plugin
+ * without a connection) never replaces it. Absent means "never picked": the
+ * panel then falls back to the plugin context's mode and the settings
+ * default. Plain string on purpose — a future mode must not need a schema
+ * migration, so unknown values are validated in the frontend instead. */
+ assistantMode?: string;
+ /** Picker action entry for this conversation, `auto` included (#9118 / R8):
+ * the record keeps the ENTRY the user chose, not the action a send routed
+ * to. Same semantics as `assistantMode`. */
+ assistantAction?: string;
createdAt: string;
updatedAt: string;
}
diff --git a/crates/dbx-ai-provider/src/ai.rs b/crates/dbx-ai-provider/src/ai.rs
index 2115e1d362..c12b72373b 100644
--- a/crates/dbx-ai-provider/src/ai.rs
+++ b/crates/dbx-ai-provider/src/ai.rs
@@ -694,6 +694,24 @@ pub struct AiConversation {
/// survives a restart and is restored when the conversation reopens.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub queued_input: Option<String>,
+ /// Ask/Agent mode the user picked for THIS conversation (#12075), written
+ /// only when the user operates the picker.
+ ///
+ /// Plain string, not an enum, and deliberately so: a future mode must not
+ /// need a schema migration, and the frontend validates unknown values back
+ /// down to `settings.defaultAiMode` (R9's fail-open, mirroring DBeaver's
+ /// unknown-`promptGeneratorId` fallback). `None` means "the user never
+ /// picked", which the frontend resolves through `pluginContext.mode` and then
+ /// the settings default — the capability limits (vector DB, plugin without a
+ /// connection) never write back here, so the user's own choice survives.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub assistant_mode: Option<String>,
+ /// Picker action for this conversation, including the UI-only `auto` entry
+ /// (#9118 / R8): the record stores the ENTRY the user chose, not the action a
+ /// send happened to route to. Same string/`None` semantics as
+ /// [`AiConversation::assistant_mode`].
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub assistant_action: Option<String>,
pub created_at: String,
pub updated_at: String,
}
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index b09bec901a..38c87f9aab 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -1161,6 +1161,8 @@ const SCHEMA_STATEMENTS: &[&str] = &[
messages_json TEXT NOT NULL DEFAULT '[]',
queued_input TEXT,
plugin_context_json TEXT,
+ assistant_mode TEXT,
+ assistant_action TEXT,
created_at TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT ''
)",
@@ -3243,6 +3245,12 @@ fn ensure_ai_conversations_columns_sync(conn: &Connection) -> Result<(), String>
// [`backfill_ai_conversation_connections`].
("connection_id", "TEXT NOT NULL DEFAULT ''"),
("schema_name", "TEXT"),
+ // Per-conversation picker selection (#12075). Plain TEXT and nullable:
+ // a legacy row keeps NULL, which the frontend reads as "no recorded
+ // choice" and resolves through the plugin context and then the settings
+ // default.
+ ("assistant_mode", "TEXT"),
+ ("assistant_action", "TEXT"),
];
ensure_table_columns(conn, "ai_conversations", COLUMNS)
@@ -6134,8 +6142,8 @@ impl Storage {
let tx = conn.transaction().map_err(|e| e.to_string())?;
tx.execute(
"INSERT INTO ai_conversations \
- (id, title, connection_name, connection_id, database, schema_name, messages_json, queued_input, created_at, updated_at, plugin_context_json) \
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) \
+ (id, title, connection_name, connection_id, database, schema_name, messages_json, queued_input, created_at, updated_at, plugin_context_json, assistant_mode, assistant_action) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) \
ON CONFLICT(id) DO UPDATE SET \
title = excluded.title, \
connection_name = excluded.connection_name, \
@@ -6145,7 +6153,8 @@ impl Storage {
messages_json = excluded.messages_json, \
queued_input = excluded.queued_input, \
created_at = excluded.created_at, \
- updated_at = excluded.updated_at, plugin_context_json = excluded.plugin_context_json",
+ updated_at = excluded.updated_at, plugin_context_json = excluded.plugin_context_json, \
+ assistant_mode = excluded.assistant_mode, assistant_action = excluded.assistant_action",
params![
conv.id,
conv.title,
@@ -6157,7 +6166,9 @@ impl Storage {
conv.queued_input,
conv.created_at,
conv.updated_at,
- conv.plugin_context.map(|value| value.to_string())
+ conv.plugin_context.map(|value| value.to_string()),
+ conv.assistant_mode,
+ conv.assistant_action
],
)
.map_err(|e| e.to_string())?;
@@ -6172,7 +6183,7 @@ impl Storage {
self.with_conn(|conn| {
let mut stmt = conn
.prepare(
- "SELECT id, title, connection_name, database, messages_json, queued_input, created_at, updated_at, plugin_context_json, connection_id, schema_name \
+ "SELECT id, title, connection_name, database, messages_json, queued_input, created_at, updated_at, plugin_context_json, connection_id, schema_name, assistant_mode, assistant_action \
FROM ai_conversations ORDER BY updated_at DESC",
)
.map_err(|e| e.to_string())?;
@@ -6193,6 +6204,8 @@ impl Storage {
plugin_context: row.get::<_, Option<String>>(8)?.map(|json| serde_json::from_str(&json)).transpose().map_err(map_from_sql_err)?,
connection_id: row.get(9)?,
schema: row.get(10)?,
+ assistant_mode: row.get(11)?,
+ assistant_action: row.get(12)?,
})
})
.map_err(|e| e.to_string())?;
@@ -6259,8 +6272,8 @@ impl Storage {
let tx = conn.transaction().map_err(|e| e.to_string())?;
tx.execute(
"INSERT INTO ai_conversations
- (id, title, connection_name, connection_id, database, schema_name, messages_json, queued_input, created_at, updated_at, plugin_context_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ (id, title, connection_name, connection_id, database, schema_name, messages_json, queued_input, created_at, updated_at, plugin_context_json, assistant_mode, assistant_action)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
title = excluded.title,
connection_name = excluded.connection_name,
@@ -6270,7 +6283,8 @@ impl Storage {
messages_json = excluded.messages_json,
queued_input = excluded.queued_input,
created_at = excluded.created_at,
- updated_at = excluded.updated_at, plugin_context_json = excluded.plugin_context_json",
+ updated_at = excluded.updated_at, plugin_context_json = excluded.plugin_context_json,
+ assistant_mode = excluded.assistant_mode, assistant_action = excluded.assistant_action",
params![
conv.id,
conv.title,
@@ -6282,7 +6296,9 @@ impl Storage {
conv.queued_input,
conv.created_at,
conv.updated_at,
- conv.plugin_context.map(|value| value.to_string())
+ conv.plugin_context.map(|value| value.to_string()),
+ conv.assistant_mode,
+ conv.assistant_action
],
)
.map_err(|e| e.to_string())?;
@@ -10687,6 +10703,8 @@ mod tests {
loaded_skill_ids: None,
}],
queued_input: None,
+ assistant_mode: None,
+ assistant_action: None,
created_at: updated_at.to_string(),
updated_at: updated_at.to_string(),
}
@@ -11005,6 +11023,84 @@ mod tests {
let _ = std::fs::remove_file(path);
}
+ /// #12075 / AC14 — a database created before the picker columns existed must
+ /// upgrade in place, and both conversation upsert paths must carry the new
+ /// values. Tests the real migration (`ensure_ai_conversations_columns_sync`),
+ /// not just serde: the columns have to exist before the INSERT can name them.
+ #[tokio::test]
+ async fn ai_conversation_upgrades_legacy_schema_and_roundtrips_picker_selection() {
+ let path = temp_db_path("ai-conversation-picker-selection");
+ // Pre-#12075 schema: none of the later columns exist yet.
+ let conn = Connection::open(&path).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE ai_conversations (
+ id TEXT PRIMARY KEY, title TEXT NOT NULL DEFAULT '', connection_name TEXT NOT NULL DEFAULT '',
+ database TEXT NOT NULL DEFAULT '', messages_json TEXT NOT NULL DEFAULT '[]',
+ created_at TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT ''
+ ); INSERT INTO ai_conversations (id, title) VALUES ('legacy', 'SQL conversation');",
+ )
+ .unwrap();
+ drop(conn);
+
+ let storage = crate::persistence::test_storage::open(&path).await.unwrap();
+ // The legacy row loads with no recorded picker selection — the frontend's
+ // R9 fallback (settings default + default action) is what fills the UI.
+ let legacy = storage.load_ai_conversations().await.unwrap();
+ assert_eq!(legacy[0].title, "SQL conversation");
+ assert!(legacy[0].assistant_mode.is_none());
+ assert!(legacy[0].assistant_action.is_none());
+
+ // Path 1: the plain conversation upsert.
+ let mut conversation = ai_conversation("picker-conv", "0001");
+ conversation.assistant_mode = Some("agent".to_string());
+ conversation.assistant_action = Some("auto".to_string());
+ storage.save_ai_conversation(&conversation).await.unwrap();
+
+ let loaded = storage.load_ai_conversations().await.unwrap();
+ let saved = loaded.iter().find(|item| item.id == "picker-conv").unwrap();
+ assert_eq!(saved.assistant_mode.as_deref(), Some("agent"));
+ // `auto` is the recorded picker entry, not a routed concrete action (R8).
+ assert_eq!(saved.assistant_action.as_deref(), Some("auto"));
+
+ // Path 2: the conversation+run upsert used by background runs.
+ let mut run_conversation = ai_conversation("run-conv", "0002");
+ run_conversation.assistant_mode = Some("ask".to_string());
+ run_conversation.assistant_action = Some("optimize".to_string());
+ let run = ai_run("run-1", "run-conv", AiRunStatus::Running, "0002");
+ storage.save_ai_run_state(&run_conversation, &run).await.unwrap();
+
+ let loaded = storage.load_ai_conversations().await.unwrap();
+ let saved = loaded.iter().find(|item| item.id == "run-conv").unwrap();
+ assert_eq!(saved.assistant_mode.as_deref(), Some("ask"));
+ assert_eq!(saved.assistant_action.as_deref(), Some("optimize"));
+ // The legacy row is still there, still without a recorded selection.
+ let legacy = loaded.iter().find(|item| item.id == "legacy").unwrap();
+ assert!(legacy.assistant_mode.is_none());
+ assert!(legacy.assistant_action.is_none());
+
+ // Clearing the picker selection (a future "forget the choice" path) writes
+ // NULL rather than a stale value.
+ conversation.assistant_mode = None;
+ conversation.assistant_action = None;
+ storage.save_ai_conversation(&conversation).await.unwrap();
+ let loaded = storage.load_ai_conversations().await.unwrap();
+ let saved = loaded.iter().find(|item| item.id == "picker-conv").unwrap();
+ assert!(saved.assistant_mode.is_none());
+ assert!(saved.assistant_action.is_none());
+
+ // A record written before the fields existed still deserializes; the JSON
+ // boundary is what the cloud-sync / web transports carry.
+ let legacy_json: AiConversation = serde_json::from_str(r#"{"id":"old","title":"Old","connectionName":"","connectionId":"","database":"","messages":[],"createdAt":"0000","updatedAt":"0000"}"#).unwrap();
+ assert!(legacy_json.assistant_mode.is_none());
+ assert!(legacy_json.assistant_action.is_none());
+ // `None` is skipped entirely, so an old reader sees the record it always saw.
+ let serialized = serde_json::to_value(&legacy_json).unwrap();
+ assert!(serialized.get("assistantMode").is_none());
+ assert!(serialized.get("assistantAction").is_none());
+
+ let _ = std::fs::remove_file(path);
+ }
+
// #10058: a turn that carried a context selection keeps only a footprint in
// storage — the selection text is session-only. The record must round-trip
// that boolean, and a record written before the field existed must load.