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。

feat(ai): run agent sessions as background tasks

Abeautifulsnoweeeb4e5011ac
diff --git a/.github/scripts/i18n-autofill.mjs b/.github/scripts/i18n-autofill.mjs
index 50c4d202a1..9bb67d313c 100644
--- a/.github/scripts/i18n-autofill.mjs
+++ b/.github/scripts/i18n-autofill.mjs
@@ -6,12 +6,16 @@ import { dirname, join, resolve } from "node:path";
const LOCALES_DIR = "apps/desktop/src/i18n/locales";
const SOURCE_LOCALE = "zh-CN";
-const TARGET_LOCALES = ["en", "es", "it", "ja", "pt-BR", "zh-TW"];
+const TARGET_LOCALES = ["en", "es", "it", "ja", "ko", "pt-BR", "zh-TW"];
+// `git show <ref>:<path>` needs forward slashes even on Windows, where
+// `path.join()` yields backslashes. Allow an override (CI keeps the default).
+const refPath = (path) => path.replaceAll("\\", "/");
const TARGET_LABELS = {
en: "English",
es: "Spanish",
it: "Italian",
ja: "Japanese",
+ ko: "Korean",
"pt-BR": "Brazilian Portuguese",
"zh-TW": "Traditional Chinese used in Taiwan",
};
@@ -106,7 +110,7 @@ function localePath(locale) {
function readBaseFile(path) {
try {
- return execFileSync("git", ["show", `${baseRef}:${path}`], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
+ return execFileSync("git", ["show", `${baseRef}:${refPath(path)}`], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
} catch (error) {
throw new Error(`Unable to read ${path} from ${baseRef}: ${error.message}`);
}
diff --git a/.gitignore b/.gitignore
index 8c95ed02c4..1a715f8baf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -62,6 +62,11 @@ Thumbs.db
# Temp
tmp/
+# AI background-run dev artifacts (never commit)
+.dlp-quarantine/
+outputs/
+target-ai-write-confirmation/
+
# Code review tool artifacts
review_diff.json
review_classified.json
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index ba0401009c..58ad44a429 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -66,6 +66,7 @@ import { externalSqlFileOpenErrorMessage, readBrowserSqlFile, sqlFileTitleFromPa
import type { ConnectionConfig, DatabaseType, ObjectSourceKind, QueryTab, TreeNode } from "@/types/database";
import { parseConnectionDeepLink, type ConnectionDeepLinkDraft } from "@/lib/connection/connectionDeepLink";
import { parseAiConfigDeepLink, type AiConfigDeepLinkDraft } from "@/lib/ai/aiConfigDeepLink";
+import { activeDesktopAiRuns, blockingDesktopAiRunsForQuit } from "@/lib/ai/desktopAiRunRegistry";
import {
isBrowserReloadShortcut,
isCloseOtherTabsShortcut,
@@ -143,6 +144,7 @@ const DriverStorePage = defineAsyncComponent(() => import("@/components/config/D
const EditorSettingsPage = defineAsyncComponent(() => import("@/components/editor/EditorSettingsDialog.vue"));
const UpdateDialog = defineAsyncComponent(() => import("@/components/layout/UpdateDialog.vue"));
const CloseActionPromptDialog = defineAsyncComponent(() => import("@/components/layout/CloseActionPromptDialog.vue"));
+const AiRunsClosePromptDialog = defineAsyncComponent(() => import("@/components/layout/AiRunsClosePromptDialog.vue"));
const LoginPage = defineAsyncComponent(() => import("@/components/auth/LoginPage.vue"));
const QuickOpenDialog = defineAsyncComponent(() => import("@/components/quick-open/QuickOpenDialog.vue"));
const TabSwitcherDialog = defineAsyncComponent(() => import("@/components/tabs/TabSwitcherDialog.vue"));
@@ -154,6 +156,8 @@ type AiAssistantHandle = {
setPrompt: (text: string) => void;
addTableMention: (target: { schema?: string; table: string }) => void;
clearContextReferences: () => void;
+ /** Opens a conversation by id (used by the background-run toast, §9). */
+ selectConversationById: (conversationId: string) => void;
};
const { t } = useI18n();
@@ -180,7 +184,7 @@ connectionStore.setBeforeConnectHandler(async (config) => {
await connectionStore.updateConnection(config);
}
});
-const { message: toastMessage, visible: toastVisible, toast } = useToast();
+const { message: toastMessage, visible: toastVisible, action: toastAction, toast } = useToast();
const { isDark, themeMode, applyTheme, setThemeMode } = useTheme();
const { activeCount: activeBackgroundTaskCount } = useExportTracker();
const trackedUpdateTaskCount = computed(() => countActiveUpdateBlockingTasks(activeBackgroundTaskCount.value, queryStore.tabs));
@@ -211,6 +215,10 @@ const {
const { setupFileDrop } = useFileDrop();
const isDesktop = isTauriRuntime();
+const activeAiRunCount = computed(() => (isDesktop ? activeDesktopAiRuns().length : 0));
+/** Runs waiting for a write confirmation — the panel-entry badge shows these
+ * with a higher-priority indicator (parent PRD §4 line 71 / §9). */
+const awaitingAiRunCount = computed(() => (isDesktop ? activeDesktopAiRuns().filter((run) => run.status === "awaiting_write_confirmation").length : 0));
const { mcpUpdateAvailable, refreshMcpUpdateStatus, handleMcpStatusChanged } = useMcpUpdateBadge({
isDesktop,
updateNotificationsEnabled: () => settingsStore.editorSettings.updateNotificationsEnabled,
@@ -307,6 +315,9 @@ const pendingPrevActiveTabId = ref<string | null>(null);
const pendingSaveShouldCloseTab = ref(true);
const pendingAppCloseAction = ref<AppCloseAction | null>(null);
const pendingCloseActionChoice = ref(false);
+const showAiRunsClosePrompt = ref(false);
+const blockingAiRunCount = computed(() => (isDesktop ? blockingDesktopAiRunsForQuit().length : 0));
+let aiRunsQuitConfirmed = false;
const activeTab = computed(() => queryStore.tabs.find((t) => t.id === queryStore.activeTabId));
const tabNavigationHistory = ref(createTabNavigationHistory());
@@ -953,6 +964,16 @@ function openAiPanel() {
openRightSidebarPanel("ai");
}
+/** A background AI run reached a terminal/confirmation state while the panel
+ * was closed. Opens the panel and selects the run's conversation (parent PRD
+ * §4 line 71 / §9 clickable toast). */
+function handleAiRunNotify(event: Event) {
+ const conversationId = (event as CustomEvent).detail?.conversationId as string | undefined;
+ if (!conversationId) return;
+ openRightSidebarPanel("ai");
+ invokeWhenAiReady((handle) => handle.selectConversationById(conversationId));
+}
+
function analyzeHistoryWithAi(entry: HistoryEntry) {
const connectionId = entry.connection_id || activeTab.value?.connectionId;
if (!connectionId) {
@@ -1088,10 +1109,18 @@ function cancelPendingSaveAndClose() {
function cancelPendingAppClose() {
pendingAppCloseAction.value = null;
pendingCloseActionChoice.value = false;
+ showAiRunsClosePrompt.value = false;
+ aiRunsQuitConfirmed = false;
pendingSaveShouldCloseTab.value = true;
}
async function finishPendingAppClose(action: AppCloseAction) {
+ if (action === "quit" && !aiRunsQuitConfirmed && blockingAiRunCount.value > 0) {
+ pendingAppCloseAction.value = action;
+ showAiRunsClosePrompt.value = true;
+ return;
+ }
+ aiRunsQuitConfirmed = false;
if (pendingCloseActionChoice.value) {
pendingCloseActionChoice.value = false;
showCloseActionPrompt.value = true;
@@ -1120,6 +1149,13 @@ async function finishPendingAppClose(action: AppCloseAction) {
await performCloseAction(action);
}
+function confirmQuitWithActiveAiRuns() {
+ const action = pendingAppCloseAction.value ?? "quit";
+ showAiRunsClosePrompt.value = false;
+ aiRunsQuitConfirmed = true;
+ void finishPendingAppClose(action);
+}
+
function continuePendingAppCloseAfterSave() {
const action = pendingAppCloseAction.value;
if (!action) return;
@@ -2811,6 +2847,7 @@ onMounted(async () => {
window.addEventListener("dbx-open-driver-store", openDriverStoreFromEvent);
window.addEventListener("dbx:activate-query-surface", activateQuerySurface);
window.addEventListener("dbx-mcp-status-changed", handleMcpStatusChanged);
+ window.addEventListener("dbx:ai-run-notify", handleAiRunNotify);
if (isDesktop) {
document.addEventListener("contextmenu", handleContextMenu);
}
@@ -2886,6 +2923,7 @@ onUnmounted(() => {
window.removeEventListener("dbx-open-driver-store", openDriverStoreFromEvent);
window.removeEventListener("dbx:activate-query-surface", activateQuerySurface);
window.removeEventListener("dbx-mcp-status-changed", handleMcpStatusChanged);
+ window.removeEventListener("dbx:ai-run-notify", handleAiRunNotify);
document.removeEventListener("contextmenu", handleContextMenu);
window.clearTimeout(sqlLibraryFlyAnimationTimer);
});
@@ -2900,6 +2938,8 @@ onUnmounted(() => {
:is-dark="isDark"
:theme-mode="themeMode"
:show-ai-panel="showAiPanel"
+ :active-ai-run-count="activeAiRunCount"
+ :awaiting-ai-run-count="awaitingAiRunCount"
:show-history="showHistory"
:show-sql-library="showSqlLibraryPanel"
:sql-library-save-feedback-id="sqlLibrarySaveFeedbackId"
@@ -3241,6 +3281,7 @@ onUnmounted(() => {
/>
<ExternalSqlFileChangeDialog :prompt="externalSqlFilePrompt" @decide="externalSqlFileChanges.resolvePrompt" />
<CloseActionPromptDialog v-if="isDesktop && showCloseActionPrompt" :open="showCloseActionPrompt" @update:open="handleCloseActionPromptOpenChange" @quit="chooseQuit" @minimize="chooseMinimize" />
+ <AiRunsClosePromptDialog v-if="isDesktop && showAiRunsClosePrompt" v-model:open="showAiRunsClosePrompt" :count="blockingAiRunCount" @cancel="cancelPendingAppClose" @quit="confirmQuitWithActiveAiRuns" />
<QuickOpenDialog :open="showQuickOpen" @update:open="showQuickOpen = $event" @select="handleQuickOpenSelect" />
<TabSwitcherDialog :open="showTabSwitcher" :tabs="tabSwitcherTabs" :selected-index="tabSwitcherIndex" :shortcut-hint="tabSwitcherShortcutHint" @update:open="handleTabSwitcherOpenChange" @update:selected-index="tabSwitcherIndex = $event" @select="handleTabSwitcherSelect" />
</div>
@@ -3259,8 +3300,11 @@ onUnmounted(() => {
@animationend="finishSqlLibraryFlyAnimation(sqlLibraryFlyAnimation.id)"
/>
<Transition name="toast">
- <div v-if="toastVisible" class="fixed bottom-6 inset-x-0 w-max max-w-[90vw] sm:max-w-3xl mx-auto z-99999 px-4 py-2 rounded-lg bg-foreground text-background text-sm shadow-lg select-text whitespace-pre-wrap break-words">
- {{ toastMessage }}
+ <div v-if="toastVisible" class="fixed bottom-6 inset-x-0 mx-auto z-99999 w-max max-w-[90vw] sm:max-w-3xl px-4 py-2 rounded-lg bg-foreground text-background text-sm shadow-lg select-text whitespace-pre-wrap break-words">
+ <span>{{ toastMessage }}</span>
+ <button v-if="toastAction" type="button" class="ml-3 shrink-0 rounded border border-background/40 bg-background/10 px-2 py-0.5 text-xs font-medium hover:bg-background/20" @click="toastAction.onClick()">
+ {{ toastAction.label }}
+ </button>
</div>
</Transition>
</Teleport>
diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vue
index 894d0f5e0f..e0553137f6 100644
--- a/apps/desktop/src/components/editor/AiAssistant.vue
+++ b/apps/desktop/src/components/editor/AiAssistant.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, nextTick, onMounted, onUnmounted, ref, toRaw, watch, type Component } from "vue";
+import { computed, nextTick, onMounted, onUnmounted, reactive, ref, toRaw, watch, type Component } from "vue";
import { uuid } from "@/lib/common/utils";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
@@ -30,6 +30,7 @@ import {
Minimize2,
Pencil,
Plus,
+ RefreshCw,
Replace,
Server,
ShieldCheck,
@@ -50,7 +51,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useTheme } from "@/composables/useTheme";
import CodeSnapshotDialog from "@/components/codeSnapshot/CodeSnapshotDialog.vue";
import type { CodeSnapshotSource } from "@/lib/codeSnapshot/codeSnapshot";
@@ -107,6 +108,24 @@ import { isAiConfigModelCandidate } from "@/lib/ai/aiConfigCandidates";
import { deleteConversationWithCancellation, stopAiGenerationWithFallback } from "@/lib/ai/aiConversationLifecycle";
import { AiGenerationGuard } from "@/lib/ai/aiGenerationGuard";
import { applyStatusEvent, createGenerationStatus, createStatusTicker, liveAnnouncementText, markCancelling, shouldShowLongRunningHint, statusText, toolLabel, STATUS_IDLE_THRESHOLD_MS, type AiGenerationStatus } from "@/lib/ai/aiGenerationStatus";
+import { supportsBackgroundAiRuns } from "@/lib/ai/aiRuntimeStrategy";
+import {
+ acquireDesktopAiRunSlot,
+ activeDesktopAiRuns,
+ bumpDesktopAiRunSeq,
+ cancelQueuedDesktopAiRun,
+ desktopAiRun,
+ finishDesktopAiRun,
+ isTerminalDesktopAiRunStatus,
+ registerDesktopAiRun,
+ releaseDesktopAiRunSlot,
+ removeDesktopAiRun,
+ retireDesktopAiRun,
+ updateDesktopAiRun,
+ type DesktopAiRunRuntime,
+ type DesktopAiRunStatus,
+} from "@/lib/ai/desktopAiRunRegistry";
+import { createDesktopAiRunSnapshotScheduler } from "@/lib/ai/desktopAiRunSnapshotScheduler";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { addConfiguredAiModel, aiModelOptions } from "@/lib/ai/aiConfigList";
import { orderAiConfigsForDisplay } from "@/lib/ai/aiConfigOrdering";
@@ -123,7 +142,7 @@ import { buildAiAgentStepItems, formatToolDurationMs, toolCallStepKey, upsertAge
import { createAiShikiCodeHighlighter, type AiCodeHighlighter } from "@/lib/ai/aiCodeHighlighter";
import { createAiMessageRenderer } from "@/lib/ai/aiMessageRender";
import { formatAiInlineMarkdown, handleAiMarkdownLinkClick } from "@/lib/ai/aiMarkdown";
-import { aiCancelStream, saveAiConversation, loadAiConversations, deleteAiConversation, listSchemas, listTables, type AiConversation } from "@/lib/backend/api";
+import { aiCancelStream, saveAiConversation, saveAiRun, saveAiRunState, loadAiConversations, loadAiRuns, deleteAiConversation, listSchemas, listTables, type AiConversation, type AiRun, type AiRunStatus } from "@/lib/backend/api";
import type { AiMessage } from "@/lib/backend/api";
import type { AiConfigItem, AiEffortCapability, AiEffortOption, AiEffortSelection } from "@/types/ai";
import type { ConnectionConfig, QueryTab, SavedSqlFile, TableInfo } from "@/types/database";
@@ -162,6 +181,7 @@ const { openTableTarget } = useNavigationTargets({
const { toast } = useToast();
const { isDark } = useTheme();
const supportsCliProviders = isTauriRuntime();
+const backgroundAiRunsEnabled = supportsBackgroundAiRuns();
type AiMessageMention =
| {
@@ -262,6 +282,143 @@ const filteredConversations = computed(() => filterAiConversationSearchIndex(con
const showConversationList = ref(false);
const showTemplateSelector = ref(false);
const modeActionOpen = ref(false);
+let assistantViewMounted = false;
+// A normal-send FIFO run recovered at startup as an editable pending draft.
+// When the user opens that conversation, the draft is loaded into the input
+// box and this banner explains it is an unsent, resendable request.
+const recoveredDraftActive = ref(false);
+const recoveredDraftLoadedFor = new Set<string>();
+// Per-conversation run status for the history rows. Active registry runs take
+// precedence; terminal statuses from persisted runs (e.g. `interrupted` after a
+// restart) are tracked here. Unread marks conversations that reached a terminal
+// or awaiting-confirmation state while the user was looking elsewhere.
+const conversationRunStatus = reactive(new Map<string, AiRunStatus>());
+const unreadConversations = reactive(new Set<string>());
+
+// --- Phase 2: queue-send, auto-send, seq baseline, away-updates (parent PRD §5/§8) ---
+
+/** One editable "send later" input per conversation, saved while an active run
+ * occupies it. Persisted via `AiConversation.queuedInput` and restored after a
+ * restart. The mode/action are in-memory only (they default to the current
+ * view after a restart). */
+type QueuedConversationInput = { text: string; mode: AiAssistantMode; action: AiAction };
+const queuedInputs = reactive(new Map<string, QueuedConversationInput>());
+
+/** Auto-send/retry work waiting to enter the normal send pipeline. More than
+ * one background run can settle in the same event turn; this must be FIFO, not
+ * a single "next send" slot, or the later completion silently drops the first
+ * conversation's queued input. */
+type PendingAutoSend = { conversationId: string; text: string; messages: ChatMessage[]; mode: AiAssistantMode; action: AiAction };
+const pendingAutoSends: PendingAutoSend[] = [];
+
+/** Highest event `seq` the user has read per conversation (parent PRD §8). Set
+ * when the conversation is opened; unread is driven by new events exceeding it.
+ * In-memory only — a fresh session starts with an empty baseline, which is the
+ * correct "everything since the last restart is new" default for a recovered
+ * run that resumed in the background. */
+const conversationReadSeq = reactive(new Map<string, number>());
+
+/** Number of messages visible when the user last left the conversation. Used to
+ * anchor the "updates while you were away" separator when the conversation
+ * gained content during the departure. */
+const conversationReadMessageCount = reactive(new Map<string, number>());
+const conversationHasAwayUpdates = reactive(new Map<string, boolean>());
+
+interface ConversationRowDetail {
+ status?: AiRunStatus;
+ unread: boolean;
+ /** Live elapsed seconds for preparing/running rows, from run start. */
+ elapsedSeconds: number | null;
+ /** Dynamic phase text for preparing/running rows (e.g. "正在执行 xxx"). */
+ phaseText: string | null;
+ /** Truncated one-line summary of the run's last assistant output. */
+ summary: string | null;
+ /** Readable reason for failed/interrupted rows. */
+ reason: string | null;
+ canRetry: boolean;
+ hasQueuedInput: boolean;
+}
+
+function runPhaseText(run: DesktopAiRunRuntime<ChatMessage>, t: (key: string, params?: Record<string, unknown>) => string): string {
+ const lastAssistant = run.messages[run.assistantMessageIndex];
+ const steps: AiAgentStepItem[] | undefined = lastAssistant?.agentSteps;
+ if (steps && steps.length) {
+ for (let i = steps.length - 1; i >= 0; i--) {
+ const step = steps[i];
+ if (step.tone === "active" && step.toolName) {
+ return t("ai.runRowPhaseTool", { tool: toolLabel(step.toolName, t) });
+ }
+ }
+ }
+ return t("ai.runRowPhaseThinking");
+}
+
+function truncateToOneLine(content: string, maxChars: number): string {
+ const normalized = content.replace(/\s+/g, " ").trim();
+ return normalized.length > maxChars ? `${normalized.slice(0, maxChars)}…` : normalized;
+}
+
+/** Formats a run's elapsed seconds for the history row ("42s", "2m 3s").
+ * Returns "" for a run without a live elapsed value. */
+function formatRunElapsed(seconds: number | null): string {
+ if (seconds === null || seconds < 0) return "";
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ const remaining = seconds % 60;
+ return remaining > 0 ? `${minutes}m ${remaining}s` : `${minutes}m`;
+}
+
+function conversationRowDetail(conv: AiConversation): ConversationRowDetail {
+ const run = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(conv.id) : undefined;
+ const status = run?.status ?? conversationRunStatus.get(conv.id);
+ const messages = run?.messages ?? chatMessagesFromConversation(conv);
+ const lastAssistant = [...messages].reverse().find((m) => m.role === "assistant" && m.content);
+ const summary = lastAssistant ? truncateToOneLine(lastAssistant.content, 48) : null;
+ const reason = status === "failed" || status === "interrupted" ? (lastAssistant ? truncateToOneLine(lastAssistant.content, 64) : t("ai.runStatusInterrupted")) : null;
+ let elapsedSeconds: number | null = null;
+ let phaseText: string | null = null;
+ if (run && (status === "running" || status === "preparing")) {
+ elapsedSeconds = Math.max(0, Math.floor((statusNow.value - new Date(run.createdAt).getTime()) / 1000));
+ phaseText = runPhaseText(run, t);
+ }
+ return {
+ status,
+ unread: unreadConversations.has(conv.id),
+ elapsedSeconds,
+ phaseText,
+ summary,
+ reason,
+ canRetry: status === "failed" || status === "interrupted",
+ hasQueuedInput: queuedInputs.has(conv.id),
+ };
+}
+
+/** Keep the elapsed-time ticker alive whenever any desktop run is live, so the
+ * history rows show a moving elapsed counter even when the visible conversation
+ * has no active run (parent PRD §7). */
+const hasLiveDesktopRuns = computed(() => backgroundAiRunsEnabled && activeDesktopAiRuns().length > 0);
+watch(hasLiveDesktopRuns, (live) => {
+ if (live) startStatusTimer();
+ else if (!isGenerating.value) stopStatusTimer();
+});
+
+/** The currently-viewed conversation's row detail, for the queue-send affordance. */
+const currentQueuedInput = computed(() => (conversationId.value ? (queuedInputs.get(conversationId.value) ?? null) : null));
+/** Whether the visible conversation is busy with a run the user cannot send
+ * through (parent PRD §5): the send button becomes "queue send". A recovered
+ * `pending_recoverable` draft is intentionally NOT busy — §2 recovery lets the
+ * user edit and re-send it, which discards the stale run. */
+const hasActiveRunForCurrentConversation = computed(() => {
+ if (!backgroundAiRunsEnabled || !conversationId.value) return isGenerating.value;
+ const run = desktopAiRun<ChatMessage>(conversationId.value);
+ if (!run) return false;
+ return run.status === "preparing" || run.status === "queued" || run.status === "running" || run.status === "awaiting_write_confirmation";
+});
+const awayUpdatesBaselineIndex = computed(() => {
+ const convId = conversationId.value;
+ if (!convId || !conversationHasAwayUpdates.get(convId)) return -1;
+ return conversationReadMessageCount.get(convId) ?? -1;
+});
// Prompt template selection (panel-session scope)
const activeTemplateIds = ref<string[]>([]);
@@ -357,6 +514,13 @@ const STREAM_RENDER_INTERVAL_MS = 33;
// uses. See cancelStream() for why the backend RPC alone can't be trusted to
// unstick a genuinely hung tool call.
const STOP_FORCE_ABANDON_MS = 5000;
+// Spacing between incremental run-snapshot saves while a detached run streams.
+// Bounds how much streamed output a crash/quit can lose relative to the last
+// durable snapshot - without this, deltas lived only in memory.
+const RUN_SNAPSHOT_PERSIST_INTERVAL_MS = 2000;
+// Retry cadence for a backend cancel RPC that has not been acknowledged yet
+// (the session registers with the backend only once runAgentStream() starts).
+const DESKTOP_CANCEL_ACK_RETRY_MS = 500;
let assistantDeltaFrame: number | null = null;
let lastAssistantFlushAt = 0;
let pendingAssistantDelta = "";
@@ -1040,6 +1204,13 @@ function sendProposalReply(positive: boolean) {
// Write confirmations carry the exact-SQL reply; other action proposals keep
// the generic wording so the model does not receive SQL-specific instructions.
prompt.value = positive ? (isWriteConfirmation ? t("ai.writeSqlConfirmationReplyYes") : t("ai.proposalConfirmReplyYes")) : isWriteConfirmation ? t("ai.writeSqlConfirmationReplyNo") : t("ai.proposalConfirmReplyNo");
+ // A rejected write confirmation must not auto-send the conversation's queued
+ // input when this run ends (parent PRD §5): tag the run so the finally block
+ // can suppress the auto-send and leave the "send queued message" button.
+ if (!positive && isWriteConfirmation && backgroundAiRunsEnabled) {
+ const run = desktopAiRun<ChatMessage>(conversationId.value);
+ if (run) run.pendingConfirmationRejected = true;
+ }
if (positive && assistantMode.value === "agent" && isWriteConfirmation) {
confirmedWriteSqlText = extractSingleSqlCodeBlock(target.content);
if (confirmedWriteSqlText) {
@@ -1261,6 +1432,74 @@ function appendAssistantReasoning(assistantIdx: number, delta: string) {
scheduleAssistantDeltaFlush(assistantIdx);
}
+function createDetachedAssistantDeltaBuffer(targetMessages: ChatMessage[], onFlush: () => void) {
+ let frame: number | null = null;
+ let lastFlushAt = 0;
+ let pendingDelta = "";
+ let pendingReasoning = "";
+ let pendingIndex = -1;
+
+ const flush = () => {
+ frame = null;
+ lastFlushAt = performance.now();
+ const msg = targetMessages[pendingIndex];
+ if (!msg) return;
+ if (pendingReasoning) {
+ msg.reasoning = (msg.reasoning || "") + pendingReasoning;
+ msg.isThinking = true;
+ }
+ if (pendingDelta) {
+ msg.isThinking = false;
+ msg.content += pendingDelta;
+ }
+ pendingDelta = "";
+ pendingReasoning = "";
+ onFlush();
+ };
+
+ const runFrame = () => {
+ if (performance.now() - lastFlushAt < STREAM_RENDER_INTERVAL_MS) {
+ frame = requestAnimationFrame(runFrame);
+ return;
+ }
+ flush();
+ };
+
+ const schedule = (assistantIdx: number) => {
+ pendingIndex = assistantIdx;
+ if (frame === null) frame = requestAnimationFrame(runFrame);
+ };
+
+ return {
+ appendText(assistantIdx: number, delta: string) {
+ const msg = targetMessages[assistantIdx];
+ if (msg?.isThinking) msg.isThinking = false;
+ pendingDelta += delta;
+ schedule(assistantIdx);
+ },
+ appendReasoning(assistantIdx: number, delta: string) {
+ pendingReasoning += delta;
+ schedule(assistantIdx);
+ },
+ replaceText(assistantIdx: number, content: string) {
+ if (frame !== null) cancelAnimationFrame(frame);
+ frame = null;
+ pendingDelta = "";
+ pendingReasoning = "";
+ pendingIndex = -1;
+ const msg = targetMessages[assistantIdx];
+ if (!msg) return;
+ msg.content = content;
+ msg.reasoning = undefined;
+ msg.isThinking = false;
+ },
+ flush() {
+ if (frame !== null) cancelAnimationFrame(frame);
+ flush();
+ },
+ };
+}
+
const reasoningExpanded = ref(false);
const expandedSteps = ref<Set<string>>(new Set());
@@ -2390,8 +2629,20 @@ function onTableReferenceDropEvent(event: Event) {
}
async function send() {
- const text = prompt.value.trim();
- if ((!text && !selectedMentions.value.length && !selectedSqlFileMentions.value.length && !selectedCsvAttachments.value.length && !selectedImageAttachments.value.length) || isGenerating.value) return;
+ // Auto-send (queued input / retry) overrides the view: the send runs against
+ // the target conversation's own history instead of the visible chat. Consumed
+ // once so a second unrelated send() cannot inherit a stale target.
+ const auto = pendingAutoSends.shift() ?? null;
+ const text = auto ? auto.text : prompt.value.trim();
+ // A background auto-send must not flip the visible conversation's send button
+ // into "stop": only the run actually shown here owns `isGenerating`.
+ const autoSendVisible = auto ? assistantViewMounted && conversationId.value === auto.conversationId : true;
+ if (auto) {
+ // A background auto-send must not be blocked by a concurrent visible run's
+ // `isGenerating` (slots arbitrate concurrency); only block when it would
+ // stream into the visible conversation that is busy.
+ if (autoSendVisible && isGenerating.value) return;
+ } else if ((!text && !selectedMentions.value.length && !selectedSqlFileMentions.value.length && !selectedCsvAttachments.value.length && !selectedImageAttachments.value.length) || isGenerating.value) return;
if (isAttachmentProcessing.value) return;
// Snapshot the target connection/database before any async work so that
@@ -2408,14 +2659,15 @@ async function send() {
toast(t("ai.noConfig"));
return;
}
- const imageError = imageAttachmentSupportError(
- activeConfig.provider,
- selectedImageAttachments.value.map((attachment) => attachment.mediaType),
- );
+ const imageError = imageAttachmentSupportError(activeConfig.provider, auto ? [] : selectedImageAttachments.value.map((attachment) => attachment.mediaType));
if (imageError) {
toast(imageAttachmentSupportErrorMessage(imageError), 5000);
return;
}
+ // The queued input is consumed only now that the send is actually proceeding
+ // (config + connection valid). Consuming it here also guarantees a terminal
+ // run can never chain into an infinite auto-send loop.
+ if (auto) queuedInputs.delete(auto.conversationId);
// Acquire the send guard before the first async operation so two rapid
// submissions cannot both pass the initial isGenerating check and then
// resume into concurrent agent runs. `myGeneration` is this call's identity:
@@ -2423,18 +2675,88 @@ async function send() {
// resumed at least once, must check `aiGenerationGuard.isCurrent(myGeneration)`
// first, since clearMessages()/selectConversation() can invalidate it out from
// under an in-flight send().
- isGenerating.value = true;
- generationStatus.value = createGenerationStatus(Date.now());
- startStatusTimer();
+ if (autoSendVisible) {
+ isGenerating.value = true;
+ generationStatus.value = createGenerationStatus(Date.now());
+ startStatusTimer();
+ }
const myGeneration = aiGenerationGuard.begin();
+ if (!auto && !conversationId.value) conversationId.value = uuid();
+ const runConversationId = auto ? auto.conversationId : conversationId.value;
+ const runMessages = auto ? auto.messages : messages.value;
+ const runCreatedAt = new Date().toISOString();
+ let detachedRun: DesktopAiRunRuntime<ChatMessage> | undefined;
+ // Resolves detachedRun.settled below; declared here so every exit path of
+ // send() (the pre-stream early returns and the finally) can wake a stop
+ // request waiting for this pipeline's real terminal state.
+ let resolveDetachedRunSettled: () => void = () => {};
+ let desktopSlotAcquired = false;
+ let resumingConfirmedWrite = false;
+ if (backgroundAiRunsEnabled) {
+ const resumableRun = desktopAiRun<ChatMessage>(runConversationId);
+ resumingConfirmedWrite = resumableRun?.status === "awaiting_write_confirmation";
+ // A recovered pending-input run is not resumable: the user just re-sent
+ // the draft (possibly edited). Discard it so it can never be persisted
+ // alongside the fresh run — one conversation, one active AiRun.
+ if (resumableRun?.status === "pending_recoverable") {
+ resumableRun.discardOnFinish = true;
+ finishDesktopAiRun(resumableRun, "cancelled");
+ removeDesktopAiRun(resumableRun.conversationId);
+ recoveredDraftActive.value = false;
+ }
+ detachedRun = registerDesktopAiRun({
+ // A confirmed write starts a new backend session, but remains a segment
+ // of the same logical run. Session ids are append-only and never rebound.
+ runId: resumingConfirmedWrite ? resumableRun!.runId : uuid(),
+ conversationId: runConversationId,
+ sessionIds: resumingConfirmedWrite ? [...resumableRun!.sessionIds] : [],
+ currentSessionId: "",
+ status: "preparing",
+ messages: runMessages,
+ assistantMessageIndex: -1,
+ connectionId: connection.id,
+ connectionName: connection.name,
+ database: tab.database || "",
+ schema: resolveAiDatabaseTarget(tab, connection).schema,
+ createdAt: resumingConfirmedWrite ? resumableRun!.createdAt : runCreatedAt,
+ updatedAt: runCreatedAt,
+ // Carry the proposal snapshot across a confirmed-write resume so a queued
+ // resume that is persisted and restarted can fall back to the original
+ // confirmation card (the grant itself is never serialized).
+ pendingConfirmation: resumingConfirmedWrite ? resumableRun!.pendingConfirmation : undefined,
+ // A rejection initiated on the awaiting run belongs to the same logical
+ // run; carry it so the resume segment can suppress the queued-input
+ // auto-send when the agent ends the run cancelled (parent PRD §5).
+ pendingConfirmationRejected: resumingConfirmedWrite ? resumableRun!.pendingConfirmationRejected : undefined,
+ cancelRequested: false,
+ });
+ // Terminal-event signal for stop requests: resolved once this send()
+ // pipeline has fully settled (its finally, or a pre-stream early exit).
+ // A stop waits on it instead of finalizing the run itself, so a hung or
+ // merely cancellation-pending stream cannot go invisible while it still
+ // occupies a concurrency slot (mirrors the foreground
+ // stopAiGenerationWithFallback() contract from issue #5941).
+ detachedRun.settled = new Promise<void>((resolve) => {
+ resolveDetachedRunSettled = resolve;
+ });
+ }
+ const generationCanContinue = () => (detachedRun ? !detachedRun.cancelRequested : aiGenerationGuard.isCurrent(myGeneration));
+ const runIsVisible = () => !detachedRun || (assistantViewMounted && conversationId.value === runConversationId);
if (!(await promptTemplateStore.ensureLoaded())) {
clearPendingWriteGrant();
- if (aiGenerationGuard.isCurrent(myGeneration)) {
- isGenerating.value = false;
- stopStatusTimer();
- generationStatus.value = createGenerationStatus(Date.now());
+ if (generationCanContinue()) {
+ if (detachedRun) finishDesktopAiRun(detachedRun, "failed");
+ if (runIsVisible()) {
+ isGenerating.value = false;
+ stopStatusTimer();
+ generationStatus.value = createGenerationStatus(Date.now());
+ }
toast(t("ai.customInstructionsLoadFailed"), 5000);
}
+ // This pipeline is done - wake any stop request waiting on it (the run may
+ // have been left non-terminal above when the stop pre-empted this path; the
+ // waiting stop-side force-abandon finalizes it).
+ resolveDetachedRunSettled();
return;
}
// Superseded (chat cleared/switched, or a newer send() started) while awaiting
@@ -2444,8 +2766,13 @@ async function send() {
// runAgentStream()), so a bare return here would leave a previously-confirmed
// write grant sitting in the module-scope vars, live to be replayed against
// whatever unrelated send() the next conversation issues.
- if (!aiGenerationGuard.isCurrent(myGeneration)) {
+ if (!generationCanContinue()) {
clearPendingWriteGrant();
+ // A stop fired while the templates loaded; this pipeline is done. Resolve
+ // settled so the waiting stop-side force-abandon (which owns the finalize
+ // for a run this early exit leaves non-terminal) runs without the full
+ // STOP_FORCE_ABANDON_MS wait.
+ resolveDetachedRunSettled();
return;
}
// Snapshot the selected custom prompts at send time so later async context loading
@@ -2455,10 +2782,10 @@ async function send() {
activeTemplates: [...activeTemplates.value],
};
- const selectedTableMentions = [...selectedMentions.value];
- const selectedSqlFiles = [...selectedSqlFileMentions.value];
- const csvAttachments = [...selectedCsvAttachments.value];
- const imageAttachments = [...selectedImageAttachments.value];
+ const selectedTableMentions = auto ? [] : [...selectedMentions.value];
+ const selectedSqlFiles = auto ? [] : [...selectedSqlFileMentions.value];
+ const csvAttachments = auto ? [] : [...selectedCsvAttachments.value];
+ const imageAttachments = auto ? [] : [...selectedImageAttachments.value];
const mentionedTables = [...selectedTableMentions, ...parseAiTableMentions(text)];
const modelInstruction = buildAiModelInstruction({
tableMentionRaws: selectedTableMentions.map((mention) => mention.raw),
@@ -2466,23 +2793,25 @@ async function send() {
userText: text,
});
- messages.value.push({ role: "user", content: text, mentions: selectedMessageMentions(selectedTableMentions, selectedSqlFiles, csvAttachments, imageAttachments), csvAttachments, imageAttachments });
- // Save to prompt history (deduplicate consecutive duplicates)
- if (text && promptHistory.value[0] !== text) {
- promptHistory.value.unshift(text);
- if (promptHistory.value.length > 100) promptHistory.value.length = 100;
+ runMessages.push({ role: "user", content: text, mentions: selectedMessageMentions(selectedTableMentions, selectedSqlFiles, csvAttachments, imageAttachments), csvAttachments, imageAttachments });
+ if (!auto) {
+ // Save to prompt history (deduplicate consecutive duplicates)
+ if (text && promptHistory.value[0] !== text) {
+ promptHistory.value.unshift(text);
+ if (promptHistory.value.length > 100) promptHistory.value.length = 100;
+ }
+ historyIndex.value = -1;
+ draftBeforeHistory.value = "";
+ prompt.value = "";
+ selectedMentions.value = [];
+ selectedSqlFileMentions.value = [];
+ selectedCsvAttachments.value = [];
+ selectedImageAttachments.value = [];
}
- historyIndex.value = -1;
- draftBeforeHistory.value = "";
- prompt.value = "";
- selectedMentions.value = [];
- selectedSqlFileMentions.value = [];
- selectedCsvAttachments.value = [];
- selectedImageAttachments.value = [];
- scrollToBottom({ force: true });
+ if (autoSendVisible) scrollToBottom({ force: true });
- const requestedAction = activeAction.value;
- const requestedMode = assistantMode.value;
+ const requestedAction = auto ? auto.action : activeAction.value;
+ const requestedMode = auto ? auto.mode : assistantMode.value;
// Detect user-typed short confirmation (e.g. "可以"/"go ahead") as an alternative
// path to the proposal ✅ button. Delegates to the shared pure function so the
// component and its unit tests share the same gating logic.
@@ -2493,14 +2822,14 @@ async function send() {
isProduction: productionContext.value.active,
userText: text,
// Pass the history BEFORE the just-pushed user message so the function skips it.
- messages: messages.value.slice(0, -1),
+ messages: runMessages.slice(0, -1),
});
if (allowWriteSqlForNextRun) {
// Extract the confirmed SQL from the assistant's proposal message.
// If no SQL code block is found, treat the confirmation as rejected —
// we cannot bind the agent to a specific SQL statement.
- for (let i = messages.value.length - 2; i >= 0; i--) {
- const msg = messages.value[i];
+ for (let i = runMessages.length - 2; i >= 0; i--) {
+ const msg = runMessages[i];
if (msg.kind === "contextSummary") continue;
if (msg.role === "assistant" && msg.content) {
confirmedWriteSqlText = extractSingleSqlCodeBlock(msg.content);
@@ -2540,18 +2869,76 @@ async function send() {
confirmedConnectionId = undefined;
confirmedDatabase = undefined;
confirmedSchema = undefined;
- messages.value.push({ role: "assistant", content: "", sourceConnectionName: connection.name });
- const assistantIdx = messages.value.length - 1;
- currentAssistantMessageIndex = assistantIdx;
+ if (detachedRun) {
+ const admission = acquireDesktopAiRunSlot(detachedRun);
+ if (detachedRun.status === "queued") {
+ // Tag how this run occupies the global FIFO so restart recovery knows
+ // whether to recover a pending input (normal send) or fall back to the
+ // confirmation card (accepted write-confirmation resume, PRD §3).
+ updateDesktopAiRun(detachedRun, {
+ fifoCategory: resumingConfirmedWrite ? "write_confirmation_resume" : "normal_send",
+ pendingInput: resumingConfirmedWrite ? detachedRun.pendingInput : text,
+ });
+ // Never re-persist a run the user has already deleted from under the
+ // queue: deleteConversation() committed the DELETE first, so this would
+ // resurrect the conversation via INSERT OR REPLACE.
+ if (!detachedRun.discardOnFinish) void runSnapshotScheduler.save(detachedRun);
+ }
+ desktopSlotAcquired = await admission;
+ if (!desktopSlotAcquired) {
+ if (runIsVisible()) {
+ isGenerating.value = false;
+ stopStatusTimer();
+ generationStatus.value = createGenerationStatus(Date.now());
+ }
+ if (!detachedRun.discardOnFinish) void runSnapshotScheduler.save(detachedRun);
+ // A queued run cancelled out of the admission queue resolves this early;
+ // settle any stop request that raced into the preparing->queued window.
+ resolveDetachedRunSettled();
+ return;
+ }
+ }
+ runMessages.push({ role: "assistant", content: "", sourceConnectionName: connection.name });
+ const assistantIdx = runMessages.length - 1;
const sessionId = uuid();
- currentSessionId.value = sessionId;
+ if (runIsVisible()) {
+ currentAssistantMessageIndex = assistantIdx;
+ currentSessionId.value = sessionId;
+ }
+ if (detachedRun) {
+ updateDesktopAiRun(detachedRun, {
+ status: "running",
+ sessionIds: [...detachedRun.sessionIds, sessionId],
+ currentSessionId: sessionId,
+ assistantMessageIndex: assistantIdx,
+ });
+ }
+ const detachedDeltaBuffer = detachedRun
+ ? createDetachedAssistantDeltaBuffer(runMessages, () => {
+ if (runIsVisible()) scrollToBottom();
+ // Persist streamed output incrementally (throttled + serialized by
+ // runSnapshotScheduler): without this, a crash/quit mid-response lost
+ // everything after the pre-stream snapshot.
+ if (detachedRun) runSnapshotScheduler.schedule(detachedRun);
+ })
+ : undefined;
+ if (detachedRun) detachedRun.flushPending = detachedDeltaBuffer?.flush;
const agentEvents: AgentEvent[] = [];
+ let detachedCompaction: { summary: string; compactedMessages: number } | null = null;
+ let writeConfirmationRequired = false;
+ if (detachedRun) {
+ // Same delete-resurrection guard as the queued sites: a concurrent delete
+ // must not be undone by this snapshot either.
+ if (!detachedRun.discardOnFinish) void runSnapshotScheduler.save(detachedRun);
+ } else {
+ void persistConversationSnapshot(runConversationId, runMessages, connection.name, tab.database || "", runCreatedAt);
+ }
try {
const sqlFiles = await loadReferencedSqlFiles(selectedSqlFiles);
// Superseded while awaiting loadReferencedSqlFiles() above — bail before
// paying for buildAiContext() too; it can do real backend/schema work that
// would be entirely wasted on an already-abandoned request.
- if (!aiGenerationGuard.isCurrent(myGeneration)) return;
+ if (!generationCanContinue()) return;
const context = await buildAiContext(tab, connection, {
mentionedTables,
sqlFiles,
@@ -2565,12 +2952,12 @@ async function send() {
// fired by abandonInFlightRequest() is a no-op here since no session has
// been registered with the backend yet (registration happens inside
// runAgentStream() itself).
- if (!aiGenerationGuard.isCurrent(myGeneration)) return;
+ if (!generationCanContinue()) return;
// The stream is about to reach the backend — transition the status line from
// `preparing` to `waiting_model` so it reads "等待模型响应" while no events have
// arrived yet (slow CLI first token included).
- generationStatus.value = { ...generationStatus.value, phase: "waiting_model" };
- const history: AiMessage[] = messagesForAgentHistory(messages.value.slice(0, -2));
+ if (runIsVisible()) generationStatus.value = { ...generationStatus.value, phase: "waiting_model" };
+ const history: AiMessage[] = messagesForAgentHistory(runMessages.slice(0, -2));
await runAgentStream(
{
config: activeConfig,
@@ -2591,64 +2978,89 @@ async function send() {
// Superseded by a clear/switch/new-chat (or a newer send()) — the backend
// stream may still be running, but this generation no longer owns any
// shared state to write into.
- if (!aiGenerationGuard.isCurrent(myGeneration)) return;
+ if (!generationCanContinue()) return;
agentEvents.push(event);
+ // Every desktop agent event takes the next seq for its run (parent PRD
+ // §8: strictly increasing from 1, across all sessions). Mark the
+ // conversation unread when a new event arrives beyond the user's read
+ // baseline while they are looking elsewhere.
+ if (detachedRun) {
+ const seq = bumpDesktopAiRunSeq(detachedRun);
+ if (!runIsVisible() && seq > (conversationReadSeq.get(runConversationId) ?? 0)) unreadConversations.add(runConversationId);
+ }
// Feed every agent event into the generation-status state machine (Issue
// #6743 feature 1). `applyStatusEvent` refreshes lastEventAt, tracks the
// active tool / turn, and derives the phase purely from the event stream.
- generationStatus.value = applyStatusEvent(generationStatus.value, event, Date.now());
+ if (runIsVisible()) generationStatus.value = applyStatusEvent(generationStatus.value, event, Date.now());
// Terminal event (agent_end / error) hides the status line immediately —
// the backend promise may still be settling (CLI teardown / SSE close), so
// stop the ticker now instead of letting it idle through that gap. The
// non-terminal `response_complete` (phase=finalizing) hides the line the
// same way, but the listener stays alive for the real agent_end/error.
- if (generationStatus.value.phase === "finished" || generationStatus.value.phase === "finalizing") {
+ if (runIsVisible() && (generationStatus.value.phase === "finished" || generationStatus.value.phase === "finalizing")) {
stopStatusTimer();
}
if (event.type === "text_delta" && event.delta) {
- appendAssistantDelta(assistantIdx, event.delta);
+ if (detachedDeltaBuffer) detachedDeltaBuffer.appendText(assistantIdx, event.delta);
+ else appendAssistantDelta(assistantIdx, event.delta);
}
if (event.type === "write_sql_confirmation_required") {
- replaceAssistantText(assistantIdx, writeSqlConfirmationText(event.sql));
- const msg = messages.value[assistantIdx];
+ writeConfirmationRequired = true;
+ if (detachedRun) {
+ updateDesktopAiRun(detachedRun, {
+ pendingConfirmation: {
+ sql: event.sql,
+ connectionId: detachedRun.connectionId,
+ database: detachedRun.database,
+ schema: detachedRun.schema,
+ },
+ });
+ }
+ if (detachedDeltaBuffer) detachedDeltaBuffer.replaceText(assistantIdx, writeSqlConfirmationText(event.sql));
+ else replaceAssistantText(assistantIdx, writeSqlConfirmationText(event.sql));
+ const msg = runMessages[assistantIdx];
if (msg) msg.kind = "writeSqlConfirmation";
}
if (event.type === "production_write_blocked") {
- replaceAssistantText(assistantIdx, productionWriteBlockedText(event.sql));
- const msg = messages.value[assistantIdx];
+ if (detachedDeltaBuffer) detachedDeltaBuffer.replaceText(assistantIdx, productionWriteBlockedText(event.sql));
+ else replaceAssistantText(assistantIdx, productionWriteBlockedText(event.sql));
+ const msg = runMessages[assistantIdx];
if (msg) msg.kind = "productionWriteBlocked";
}
if (event.type === "reasoning_delta" && event.delta) {
- appendAssistantReasoning(assistantIdx, event.delta);
+ if (detachedDeltaBuffer) detachedDeltaBuffer.appendReasoning(assistantIdx, event.delta);
+ else appendAssistantReasoning(assistantIdx, event.delta);
}
if (event.type === "agent_end") {
// End the card's "思考过程" spinner at the terminal event rather than
// waiting for send()'s finally (which can lag behind CLI teardown).
- const msg = messages.value[assistantIdx];
+ const msg = runMessages[assistantIdx];
if (msg) msg.isThinking = false;
if (event.input_tokens || event.output_tokens) {
if (msg) msg.tokens = { input: event.input_tokens ?? 0, output: event.output_tokens ?? 0 };
}
}
if (event.type === "context_compacted") {
- const msg = messages.value[assistantIdx];
+ const msg = runMessages[assistantIdx];
if (msg) {
if (!msg.agentSteps) msg.agentSteps = [];
const step = agentEventToStep(event, agentEvents.length - 1, Date.now());
if (step) upsertAgentStep(msg.agentSteps, step);
}
- pendingCompaction.value = { summary: event.summary, compactedMessages: event.compacted_messages };
+ const compaction = { summary: event.summary, compactedMessages: event.compacted_messages };
+ if (detachedRun) detachedCompaction = compaction;
+ else pendingCompaction.value = compaction;
}
// Real-time agent step rendering
if (event.type === "tool_call_start" || event.type === "tool_call_end") {
- const msg = messages.value[assistantIdx];
+ const msg = runMessages[assistantIdx];
if (msg) {
if (!msg.agentSteps) msg.agentSteps = [];
const step = agentEventToStep(event, agentEvents.length - 1, Date.now());
if (step) upsertAgentStep(msg.agentSteps, step);
}
}
- scrollToBottom();
+ if (runIsVisible()) scrollToBottom();
},
sessionId,
customPromptContext,
@@ -2658,10 +3070,11 @@ async function send() {
// abandonInFlightRequest()-triggered cancellation) must not overwrite a
// message that now belongs to a different conversation, or one that no
// longer exists in `messages.value`.
- if (aiGenerationGuard.isCurrent(myGeneration)) {
+ if (generationCanContinue()) {
const message = e instanceof Error ? e.message : String(e);
- const msg = messages.value[assistantIdx];
+ const msg = runMessages[assistantIdx];
if (msg) msg.content = `${t("ai.requestFailed")}\n\n${translateBackendError(t, message)}`;
+ if (detachedRun) finishDesktopAiRun(detachedRun, "failed");
}
} finally {
// Everything below mutates state (messages, isGenerating, currentSessionId,
@@ -2675,17 +3088,22 @@ async function send() {
// resetPendingRequestState() below for the abandon-path equivalent that
// discards it instead. If you add a new piece of per-request transient
// state, it must be handled on both paths.
- if (aiGenerationGuard.isCurrent(myGeneration)) {
- if (assistantDeltaFrame !== null) cancelAnimationFrame(assistantDeltaFrame);
- flushAssistantDeltas();
- const msg = messages.value[assistantIdx];
+ if (detachedRun || aiGenerationGuard.isCurrent(myGeneration)) {
+ if (detachedDeltaBuffer) detachedDeltaBuffer.flush();
+ else {
+ if (assistantDeltaFrame !== null) cancelAnimationFrame(assistantDeltaFrame);
+ flushAssistantDeltas();
+ }
+ const msg = runMessages[assistantIdx];
if (msg) msg.isThinking = false;
- isGenerating.value = false;
+ if (runIsVisible()) isGenerating.value = false;
// Normal-path generation-status cleanup (dual-path reset — see
// resetPendingRequestState() below for the abandon-path equivalent).
- stopStatusTimer();
- generationStatus.value = createGenerationStatus(Date.now());
- statusNow.value = Date.now();
+ if (runIsVisible()) {
+ stopStatusTimer();
+ generationStatus.value = createGenerationStatus(Date.now());
+ statusNow.value = Date.now();
+ }
// Render agent tool call steps from agent events (fallback when no real-time steps)
if (msg && agentEvents.length > 0 && !msg.agentSteps?.length) {
const steps: AiAgentStepItem[] = [];
@@ -2708,28 +3126,113 @@ async function send() {
if (msg && requestedMode === "agent") msg.agentSteps = buildAiAgentStepItems(agentPlan);
if (agentPlan.handoffSql) emit("requestAutoExecuteSql", agentPlan.handoffSql);
}
- currentSessionId.value = "";
- currentAssistantMessageIndex = -1;
+ if (runIsVisible()) {
+ currentSessionId.value = "";
+ currentAssistantMessageIndex = -1;
+ }
// Apply deferred context compaction after streaming so assistantIdx stays stable.
// Visible chat history is kept for the user; future LLM history starts from this hidden summary.
- if (pendingCompaction.value) {
- const { summary, compactedMessages } = pendingCompaction.value;
- pendingCompaction.value = null;
- const insertAt = Math.min(1 + compactedMessages, messages.value.length - 1);
+ const compaction = detachedRun ? detachedCompaction : pendingCompaction.value;
+ if (compaction) {
+ const { summary, compactedMessages } = compaction;
+ if (!detachedRun) pendingCompaction.value = null;
+ const insertAt = Math.min(1 + compactedMessages, runMessages.length - 1);
if (summary) {
- messages.value.splice(insertAt, 0, {
+ runMessages.splice(insertAt, 0, {
role: "user",
content: summary,
kind: "contextSummary",
});
}
}
- persistConversation();
- scrollToBottom();
+ // A stop-side force-abandon (STOP_FORCE_ABANDON_MS), a conversation
+ // delete, or a replacement send may have finalized and removed this run
+ // from the registry already. Re-running the finish chain would resurrect
+ // it over whatever now owns the conversation's registry slot
+ // (updateDesktopAiRun() re-inserts unconditionally).
+ const runStillOwned = detachedRun ? desktopAiRun(detachedRun.conversationId) === detachedRun : false;
+ if (detachedRun && runStillOwned) {
+ if (detachedRun.cancelRequested) finishDesktopAiRun(detachedRun, "cancelled");
+ else if (detachedRun.status !== "failed") {
+ if (writeConfirmationRequired) updateDesktopAiRun(detachedRun, { status: "awaiting_write_confirmation", currentSessionId: "", flushPending: undefined });
+ else finishDesktopAiRun(detachedRun, "completed");
+ }
+ // Read the run's settled status once, after the finish/update chain above,
+ // so the checks below see the terminal/awaiting value without TypeScript
+ // narrowing the property from the earlier `!== "failed"` branch.
+ const runSettledStatus = detachedRun.status;
+ // Reflect the terminal/confirmation state in the history row, and mark
+ // the conversation unread if the user was looking elsewhere (seq
+ // baseline: only events beyond the user's read position count).
+ if (runSettledStatus === "completed" || runSettledStatus === "failed" || runSettledStatus === "cancelled" || runSettledStatus === "awaiting_write_confirmation") {
+ conversationRunStatus.set(runConversationId, runSettledStatus);
+ const seenSeq = conversationReadSeq.get(runConversationId) ?? 0;
+ if (!runIsVisible() && (detachedRun.maxSeq ?? 0) > seenSeq) unreadConversations.add(runConversationId);
+ }
+ if (!runIsVisible() && !detachedRun.cancelRequested) {
+ toast(t(writeConfirmationRequired ? "ai.backgroundRunNeedsConfirmation" : "ai.backgroundRunCompleted"), 5000, {
+ label: t("ai.openPanel"),
+ onClick: () => window.dispatchEvent(new CustomEvent("dbx:ai-run-notify", { detail: { conversationId: runConversationId, status: runSettledStatus } })),
+ });
+ }
+ // Auto-send the conversation's queued input once this run reaches a
+ // terminal state (parent PRD §5). Exceptions: awaiting confirmation is
+ // not terminal, and a run cancelled because the user rejected the write
+ // confirmation must NOT auto-send — the queued input waits for an
+ // explicit "send queued message" click instead. In-memory terminal
+ // statuses are completed/failed/cancelled; `interrupted` only ever
+ // appears as a persisted row status after a restart.
+ if (!detachedRun.discardOnFinish && (runSettledStatus === "completed" || runSettledStatus === "failed" || runSettledStatus === "cancelled")) {
+ const queued = queuedInputs.get(runConversationId);
+ if (queued && !(detachedRun.pendingConfirmationRejected && runSettledStatus === "cancelled")) {
+ scheduleAutoSend(runConversationId, queued, runMessages);
+ }
+ }
+ }
+ if (desktopSlotAcquired && detachedRun) releaseDesktopAiRunSlot(detachedRun.runId);
+ if (detachedRun && runStillOwned) {
+ // A run the user deleted (discardOnFinish) must never be written back:
+ // the DELETE already committed, and INSERT OR REPLACE would resurrect it.
+ if (!detachedRun.discardOnFinish) {
+ // Drop the pending throttled save: this ordered final save is
+ // authoritative.
+ runSnapshotScheduler.cancel(detachedRun.runId);
+ void runSnapshotScheduler.save(detachedRun).finally(() => {
+ if (detachedRun?.status === "completed" || detachedRun?.status === "failed" || detachedRun?.status === "cancelled") {
+ retireDesktopAiRun(detachedRun);
+ }
+ });
+ }
+ } else if (!detachedRun) {
+ void persistConversationSnapshot(runConversationId, runMessages, connection.name, tab.database || "", runCreatedAt);
+ }
+ if (runIsVisible()) scrollToBottom();
+ // Wake any stop request waiting for this pipeline's real terminal state.
+ resolveDetachedRunSettled();
}
}
}
+/** Sends the conversation's queued input as a fresh run (parent PRD §5). Runs
+ * in the background when the conversation is not the visible one. The queued
+ * input is consumed by the send pipeline once it actually starts, so a failed
+ * early bail (no config, superseded) does not silently drop it. */
+function scheduleAutoSend(convId: string, queued: QueuedConversationInput, messages: ChatMessage[]) {
+ pendingAutoSends.push({ conversationId: convId, text: queued.text, messages, mode: queued.mode, action: queued.action });
+ void send();
+}
+
+/** Manual trigger for a queued input that must wait (e.g. the previous run was
+ * cancelled by a rejected write confirmation). Reuses the same background path
+ * as auto-send. */
+function sendQueuedInputNow() {
+ const convId = conversationId.value;
+ const queued = convId ? queuedInputs.get(convId) : undefined;
+ if (!queued) return;
+ const run = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(convId) : undefined;
+ scheduleAutoSend(convId, queued, run?.messages ?? messages.value);
+}
+
// Resolves once `isGenerating` goes false, or after `timeoutMs` — whichever
// comes first. Used by cancelStream() to bound how long it waits for the
// backend to actually acknowledge a cancellation before forcing it.
@@ -2752,6 +3255,136 @@ function waitForGenerationToClear(timeoutMs: number): Promise<void> {
});
}
+/** Waits for a detached run's owning send() pipeline to reach its terminal
+ * state. Resolves false when STOP_FORCE_ABANDON_MS elapses first - the caller
+ * must then force-abandon the run so a hung backend stream cannot wedge its
+ * concurrency slot forever. */
+function waitForDesktopRunSettled(run: DesktopAiRunRuntime<ChatMessage>): Promise<boolean> {
+ if (!run.settled) return Promise.resolve(false);
+ return Promise.race([run.settled.then(() => true), new Promise<false>((resolve) => setTimeout(() => resolve(false), STOP_FORCE_ABANDON_MS))]);
+}
+
+/** Fires the backend cancel RPC for the run's current session until it is
+ * acknowledged or `deadlineAt` passes. aiCancelStream() resolves true only
+ * when the session id is already registered with the backend; a stop during
+ * context preparation RPCs before runAgentStream() has registered the
+ * session, so a single fire-and-forget call would silently miss the
+ * cancellation. When the session is not registered yet, the loop waits for it
+ * to appear and retries. `requireRegistryOwnership` is false for the delete
+ * path, which removes the run from the registry before this loop runs. */
+async function requestDesktopRunCancellation(run: DesktopAiRunRuntime<ChatMessage>, deadlineAt: number, requireRegistryOwnership = true) {
+ for (;;) {
+ // The run settled (or was replaced) while retrying - nothing left to cancel.
+ if (isTerminalDesktopAiRunStatus(run.status)) return;
+ if (requireRegistryOwnership && desktopAiRun(run.conversationId) !== run) return;
+ if (run.currentSessionId) {
+ const acknowledged = await aiCancelStream(run.currentSessionId).catch(() => false);
+ if (acknowledged) return;
+ }
+ if (Date.now() + DESKTOP_CANCEL_ACK_RETRY_MS > deadlineAt) return;
+ await new Promise((resolve) => setTimeout(resolve, DESKTOP_CANCEL_ACK_RETRY_MS));
+ }
+}
+
+/** Clears the visible generation state once a run the user stopped has fully
+ * settled (or been force-abandoned). Only safe to call while the stopped
+ * conversation is still the visible one. */
+function clearVisibleGenerationState() {
+ isGenerating.value = false;
+ currentSessionId.value = "";
+ currentAssistantMessageIndex = -1;
+ stopStatusTimer();
+ generationStatus.value = createGenerationStatus(Date.now());
+ statusNow.value = Date.now();
+}
+
+/** Terminal cleanup for a run whose send() pipeline never settled (hung
+ * backend stream) or settled through a pre-stream early return that left it
+ * non-terminal. Mirrors what send()'s finally does on the normal path, plus
+ * the slot release the old stop path used to skip entirely. */
+async function forceAbandonDesktopAiRun(run: DesktopAiRunRuntime<ChatMessage>) {
+ if (conversationId.value === run.conversationId) clearVisibleGenerationState();
+ finishDesktopAiRun(run, "cancelled");
+ releaseDesktopAiRunSlot(run.runId);
+ conversationRunStatus.set(run.conversationId, "cancelled");
+ if (!run.discardOnFinish) {
+ runSnapshotScheduler.cancel(run.runId);
+ await runSnapshotScheduler.save(run);
+ }
+ retireDesktopAiRun(run);
+}
+
+/** Releases a deleted run's concurrency slot once its owning pipeline settles,
+ * or after the force-abandon deadline if the backend stream never settles,
+ * while retrying the backend cancel until the session registers.
+ * discardOnFinish guarantees nothing is ever persisted. Runs in the
+ * background so the delete is not blocked by a possibly-hung stream; without
+ * it, a few deleted-but-hung runs would permanently wedge the global queue
+ * (admittedRunIds never shrinks). */
+function releaseDeletedRunSlot(run: DesktopAiRunRuntime<ChatMessage>) {
+ // Recovered runs (awaiting_write_confirmation / pending_recoverable) have no
+ // pipeline and hold no slot; only send()-created runs do.
+ if (!run.settled) return;
+ const deadlineAt = Date.now() + STOP_FORCE_ABANDON_MS;
+ void requestDesktopRunCancellation(run, deadlineAt, false);
+ void waitForDesktopRunSettled(run).then(() => releaseDesktopAiRunSlot(run.runId));
+}
+
+/** Stops a background run without lying about its state: the stop path used to
+ * finish+retire the run before the backend settled, so a hung or merely
+ * cancellation-pending stream went invisible while still occupying its
+ * concurrency slot, with no way to see or retry the stop. Mirrors the
+ * foreground stopAiGenerationWithFallback() contract: reflect the request
+ * immediately, then wait for the owning send() pipeline's real terminal
+ * event - bounded by STOP_FORCE_ABANDON_MS, after which the run is
+ * force-finalized so the queue can never wedge. */
+async function stopDesktopAiRun(run: DesktopAiRunRuntime<ChatMessage>) {
+ run.cancelRequested = true;
+ if (run.status === "queued") {
+ // Never admitted: no backend session and no slot - finalize immediately.
+ cancelQueuedDesktopAiRun(run);
+ if (conversationId.value === run.conversationId) clearVisibleGenerationState();
+ conversationRunStatus.set(run.conversationId, "cancelled");
+ if (!run.discardOnFinish) await runSnapshotScheduler.save(run);
+ retireDesktopAiRun(run);
+ return;
+ }
+ // Show what streamed so far (plus the cancelled placeholder when empty) and
+ // reflect the stop in the status line while the backend settles.
+ run.flushPending?.();
+ const msg = run.messages[run.assistantMessageIndex];
+ if (msg) {
+ msg.isThinking = false;
+ if (!msg.content) msg.content = t("ai.requestCancelled");
+ }
+ if (conversationId.value === run.conversationId && isGenerating.value) {
+ generationStatus.value = markCancelling(generationStatus.value, Date.now());
+ statusNow.value = Date.now();
+ }
+ const deadlineAt = Date.now() + STOP_FORCE_ABANDON_MS;
+ const settled = waitForDesktopRunSettled(run);
+ // Fire-and-forget the backend-cancel retry: it must never gate the bounded
+ // force-abandon below. If the IPC itself hangs, awaiting it here would leave
+ // the stop stuck forever — the STOP_FORCE_ABANDON_MS race would never be
+ // read. The loop is internally bounded by deadlineAt and bails once the run
+ // is retired.
+ void requestDesktopRunCancellation(run, deadlineAt);
+ if (await settled) {
+ // The pipeline settled. Its finally has normally finalized the run
+ // already; a pre-stream early return can leave it a zombie instead - the
+ // conversation would stay busy forever with no stream behind it.
+ if (desktopAiRun(run.conversationId) === run && !isTerminalDesktopAiRunStatus(run.status)) {
+ await forceAbandonDesktopAiRun(run);
+ }
+ return;
+ }
+ // The backend never settled within the timeout - force-finalize so the run
+ // stops occupying its slot and the conversation becomes usable again. If it
+ // was deleted or replaced meanwhile, whoever retired it already owns the
+ // cleanup.
+ if (desktopAiRun(run.conversationId) === run) await forceAbandonDesktopAiRun(run);
+}
+
async function cancelStream() {
// User explicitly requested stop — reflect it in the status line (phase=cancelling)
// so it reads "正在取消…" while the backend cancellation is still settling.
@@ -2759,6 +3392,12 @@ async function cancelStream() {
generationStatus.value = markCancelling(generationStatus.value, Date.now());
statusNow.value = Date.now();
}
+ if (backgroundAiRunsEnabled) {
+ const run = desktopAiRun<ChatMessage>(conversationId.value);
+ if (!run || (run.status !== "preparing" && run.status !== "queued" && run.status !== "running")) return;
+ await stopDesktopAiRun(run);
+ return;
+ }
await stopAiGenerationWithFallback({
isGenerating: () => isGenerating.value,
currentGeneration: () => aiGenerationGuard.peek(),
@@ -2920,13 +3559,26 @@ function clearMessages() {
// session id yet — otherwise isGenerating would never reset (nothing but
// send()'s own finally clears it) and the send box would stay stuck disabled
// indefinitely.
- if (isGenerating.value) abandonInFlightRequest();
+ if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();
+ // Desktop detaches the view from the running conversation. Its message array
+ // remains owned by the run registry and will be persisted by send() when the
+ // stream reaches a terminal/confirmation state.
+ if (isGenerating.value && backgroundAiRunsEnabled) void persistConversation();
+ // Anchor the away-updates separator at the last-read position before wiping
+ // the transcript, so returning to this conversation shows what changed.
+ if (conversationId.value) conversationReadMessageCount.set(conversationId.value, visibleMessages.value.length);
messages.value = [];
cancelEdit();
clearAttachmentDraftState();
conversationId.value = "";
+ isGenerating.value = false;
+ currentSessionId.value = "";
+ currentAssistantMessageIndex = -1;
+ stopStatusTimer();
+ generationStatus.value = createGenerationStatus(Date.now());
historyIndex.value = -1;
draftBeforeHistory.value = "";
+ recoveredDraftActive.value = false;
messageRenderer.value.clear();
}
@@ -2941,25 +3593,148 @@ function clearAttachmentDraftState() {
browserAttachmentDragDepth = 0;
}
-async function persistConversation() {
- if (!messages.value.length || !props.connection) return;
- if (!conversationId.value) conversationId.value = uuid();
- const first = messages.value.find((m) => m.role === "user" && m.kind !== "contextSummary");
- await saveAiConversation({
- id: conversationId.value,
+function buildConversationSnapshot(targetConversationId: string, targetMessages: ChatMessage[], connectionName: string, database: string, createdAt = new Date().toISOString()): AiConversation | null {
+ if (!targetConversationId || !targetMessages.length) return null;
+ const first = targetMessages.find((m) => m.role === "user" && m.kind !== "contextSummary");
+ return {
+ id: targetConversationId,
title: first ? messageTitle(first).slice(0, 50) : "Untitled",
- connectionName: props.connection.name,
- database: props.tab?.database || "",
- messages: messages.value.map((m) => ({
+ connectionName,
+ database,
+ messages: targetMessages.map((m) => ({
role: m.role,
content: m.content,
...(m.mentions?.length ? { mentions: m.mentions } : {}),
...(m.reasoning ? { reasoning: m.reasoning } : {}),
...(m.kind ? { kind: m.kind } : {}),
})),
- createdAt: new Date().toISOString(),
+ // The conversation's single queued "send later" input, persisted so it
+ // survives a restart (parent PRD §5).
+ queuedInput: queuedInputs.get(targetConversationId)?.text,
+ createdAt,
updatedAt: new Date().toISOString(),
- }).catch(() => {});
+ };
+}
+
+async function persistConversationSnapshot(targetConversationId: string, targetMessages: ChatMessage[], connectionName: string, database: string, createdAt = new Date().toISOString()) {
+ const conversation = buildConversationSnapshot(targetConversationId, targetMessages, connectionName, database, createdAt);
+ if (!conversation) return;
+ await saveAiConversation(conversation)
+ .then(() => syncPersistedConversation(conversation))
+ .catch(() => {});
+}
+
+async function persistDesktopRunSnapshot(run: DesktopAiRunRuntime<ChatMessage>) {
+ const conversation = buildConversationSnapshot(run.conversationId, run.messages, run.connectionName, run.database, run.createdAt);
+ if (!conversation) return;
+ await saveAiRunState(conversation, {
+ runId: run.runId,
+ conversationId: run.conversationId,
+ sessionIds: run.sessionIds,
+ status: run.status,
+ connectionId: run.connectionId,
+ database: run.database,
+ schema: run.schema,
+ pendingConfirmation: run.pendingConfirmation,
+ fifoCategory: run.fifoCategory,
+ pendingInput: run.pendingInput,
+ maxSeq: run.maxSeq,
+ createdAt: run.createdAt,
+ updatedAt: run.updatedAt,
+ })
+ // A newly-created conversation is not in `conversations` until the next
+ // list reload unless we mirror the successful durable snapshot here. The
+ // background-complete toast relies on that list to navigate back to it.
+ .then(() => syncPersistedConversation(conversation))
+ .catch(() => {});
+}
+
+/** Throttled, serialized snapshot persistence for streaming runs: detached
+ * deltas used to live only in memory, so a crash or quit mid-response lost
+ * everything after the last pre-stream snapshot. Saves are chained per run so
+ * a slow write can never let an older snapshot overwrite a newer one. */
+const runSnapshotScheduler = createDesktopAiRunSnapshotScheduler<ChatMessage>({
+ persist: (run) => persistDesktopRunSnapshot(run),
+ intervalMs: RUN_SNAPSHOT_PERSIST_INTERVAL_MS,
+});
+
+function syncPersistedConversation(conversation: AiConversation) {
+ const index = conversations.value.findIndex((item) => item.id === conversation.id);
+ if (index >= 0) conversations.value.splice(index, 1, conversation);
+ else conversations.value.unshift(conversation);
+ conversations.value.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
+}
+
+/** Re-registers a persisted run at startup. `extra` overrides the transcript
+ * (e.g. a recovered pending-input run whose message was stripped) and other
+ * fields for the specific recovery path. */
+function registerPersistedAiRun(conversation: AiConversation, persistedRun: AiRun, status: DesktopAiRunStatus, updatedAt: string, extra?: Partial<DesktopAiRunRuntime<ChatMessage>>) {
+ registerDesktopAiRun({
+ runId: persistedRun.runId,
+ conversationId: persistedRun.conversationId,
+ sessionIds: [...persistedRun.sessionIds],
+ currentSessionId: "",
+ status,
+ messages: chatMessagesFromConversation(conversation),
+ assistantMessageIndex: -1,
+ connectionId: persistedRun.connectionId,
+ connectionName: conversation.connectionName,
+ database: persistedRun.database,
+ schema: persistedRun.schema,
+ pendingConfirmation: persistedRun.pendingConfirmation,
+ maxSeq: persistedRun.maxSeq,
+ createdAt: persistedRun.createdAt,
+ updatedAt,
+ cancelRequested: false,
+ ...extra,
+ });
+}
+
+/** The last user message in a transcript, treated as the queued-but-unsent
+ * input of a normal-send FIFO run. Returns the draft text plus the transcript
+ * WITHOUT that message (the input was never submitted, so it must not stay in
+ * the history). Returns null when the tail is an assistant message or empty. */
+function extractRecoverableDraft(messages: ChatMessage[]): { draft: string; messages: ChatMessage[] } | null {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg.kind === "contextSummary") continue;
+ if (msg.role === "user") {
+ if (!msg.content.trim()) return null;
+ return { draft: msg.content, messages: messages.slice(0, i) };
+ }
+ return null;
+ }
+ return null;
+}
+
+/** Persists a normal-send FIFO run recovered as an editable pending draft:
+ * status `pending_recoverable` (protected, never a failure), the draft text on
+ * the run, and the conversation transcript without the unsent user message. */
+async function persistPendingInputRecovery(conversation: AiConversation, messages: ChatMessage[], run: AiRun, updatedAt: string) {
+ const first = messages.find((m) => m.role === "user" && m.kind !== "contextSummary");
+ const snapshot: AiConversation = {
+ id: conversation.id,
+ title: first ? messageTitle(first).slice(0, 50) : conversation.title || "Untitled",
+ connectionName: conversation.connectionName,
+ database: conversation.database,
+ messages: messages.map((m) => ({
+ role: m.role,
+ content: m.content,
+ ...(m.mentions?.length ? { mentions: m.mentions } : {}),
+ ...(m.reasoning ? { reasoning: m.reasoning } : {}),
+ ...(m.kind ? { kind: m.kind } : {}),
+ })),
+ queuedInput: conversation.queuedInput,
+ createdAt: conversation.createdAt,
+ updatedAt,
+ };
+ await saveAiRunState(snapshot, run).catch(() => {});
+}
+
+async function persistConversation() {
+ if (!messages.value.length || !props.connection) return;
+ if (!conversationId.value) conversationId.value = uuid();
+ await persistConversationSnapshot(conversationId.value, messages.value, props.connection.name, props.tab?.database || "");
}
async function setConversationListOpen(open: boolean) {
@@ -2972,35 +3747,146 @@ async function setConversationListOpen(open: boolean) {
}
}
+function chatMessagesFromConversation(conv: AiConversation): ChatMessage[] {
+ return conv.messages.map((m) => ({
+ role: m.role as "user" | "assistant",
+ content: m.content,
+ sourceConnectionName: m.role === "assistant" ? conv.connectionName : undefined,
+ mentions: Array.isArray(m.mentions) ? (m.mentions as AiMessageMention[]) : undefined,
+ reasoning: m.reasoning,
+ kind: m.kind,
+ }));
+}
+
function selectConversation(conv: AiConversation) {
// Same guard as clearMessages(): switching away from an in-flight request must
// abandon it first — abandonInFlightRequest() invalidates the generation so
// the old send() can't write its deltas/result into this (different)
// conversation's messages array once it's assigned below.
- if (isGenerating.value) abandonInFlightRequest();
+ if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();
+ if (isGenerating.value && backgroundAiRunsEnabled) void persistConversation();
+ // Anchor the "updates while you were away" separator at the message count the
+ // 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);
conversationId.value = conv.id;
cancelEdit();
clearAttachmentDraftState();
// Drop the previous conversation's rendered Markdown instead of keeping it until the LRU evicts it.
messageRenderer.value.clear();
- messages.value = conv.messages.map((m) => ({
- role: m.role as "user" | "assistant",
- content: m.content,
- sourceConnectionName: m.role === "assistant" ? conv.connectionName : undefined,
- mentions: Array.isArray(m.mentions) ? (m.mentions as AiMessageMention[]) : undefined,
- reasoning: m.reasoning,
- kind: m.kind,
- }));
+ const activeRun = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(conv.id) : undefined;
+ messages.value = activeRun?.messages ?? chatMessagesFromConversation(conv);
+ unreadConversations.delete(conv.id);
+ isGenerating.value = activeRun?.status === "preparing" || activeRun?.status === "queued" || activeRun?.status === "running";
+ currentSessionId.value = activeRun?.currentSessionId ?? "";
+ currentAssistantMessageIndex = activeRun?.assistantMessageIndex ?? -1;
+ // Reset the seq read baseline to the run's current position: anything beyond
+ // this that arrives while the user is away is "new" again (parent PRD §8).
+ conversationReadSeq.set(conv.id, activeRun?.maxSeq ?? 0);
+ // A recovered pending-input run restores its draft into the input box exactly
+ // once per mount; re-selecting the same conversation later must not clobber
+ // whatever the user has since typed or cleared.
+ if (activeRun?.status === "pending_recoverable" && !recoveredDraftLoadedFor.has(conv.id)) {
+ recoveredDraftLoadedFor.add(conv.id);
+ prompt.value = activeRun.pendingInput ?? "";
+ recoveredDraftActive.value = true;
+ } else {
+ recoveredDraftActive.value = activeRun?.status === "pending_recoverable";
+ }
+ // If the conversation gained content since the user left, show the separator
+ // before the first "new" message plus a jump-to-latest affordance.
+ const awayBaseline = conversationReadMessageCount.get(conv.id);
+ if (awayBaseline !== undefined && visibleMessages.value.length > awayBaseline) {
+ conversationHasAwayUpdates.set(conv.id, true);
+ } else {
+ conversationHasAwayUpdates.delete(conv.id);
+ }
+ if (isGenerating.value) {
+ generationStatus.value = createGenerationStatus(new Date(activeRun?.createdAt ?? Date.now()).getTime());
+ startStatusTimer();
+ } else {
+ stopStatusTimer();
+ generationStatus.value = createGenerationStatus(Date.now());
+ }
pendingCompaction.value = null;
showConversationList.value = false;
scrollToBottom({ force: true });
}
+/** Opens a conversation by id from outside the panel (e.g. a background-run
+ * toast click). No-op when the conversation is unknown; retries briefly in
+ * case the panel is still loading its conversation list on first mount. */
+function selectConversationById(convId: string) {
+ const open = (list: AiConversation[]): boolean => {
+ const conv = list.find((c) => c.id === convId);
+ if (conv) {
+ selectConversation(conv);
+ return true;
+ }
+ return false;
+ };
+ if (open(conversations.value)) return;
+ let timer = 0;
+ const stop = watch(
+ () => conversations.value,
+ (list) => {
+ if (open(list)) {
+ clearTimeout(timer);
+ stop();
+ }
+ },
+ );
+ timer = window.setTimeout(() => stop(), 5000);
+}
+
+/** Conversation id awaiting a destructive delete confirmation (parent PRD §4:
+ * deleting a conversation that owns an active task must ask first). */
+const deleteConfirmConversationId = ref<string | null>(null);
+
+function conversationHasActiveTask(id: string): boolean {
+ const status = (backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(id)?.status : undefined) ?? conversationRunStatus.get(id);
+ return status === "preparing" || status === "queued" || status === "running" || status === "awaiting_write_confirmation" || status === "pending_recoverable";
+}
+
async function deleteConversation(id: string) {
+ if (backgroundAiRunsEnabled && conversationHasActiveTask(id)) {
+ deleteConfirmConversationId.value = id;
+ return;
+ }
+ await performDeleteConversation(id);
+}
+
+function cancelDeleteConversation() {
+ deleteConfirmConversationId.value = null;
+}
+
+async function confirmDeleteConversation() {
+ const id = deleteConfirmConversationId.value;
+ deleteConfirmConversationId.value = null;
+ if (id) await performDeleteConversation(id);
+}
+
+async function performDeleteConversation(id: string) {
+ if (backgroundAiRunsEnabled) {
+ const run = desktopAiRun<ChatMessage>(id);
+ if (run && (run.status === "preparing" || run.status === "queued" || run.status === "running" || run.status === "awaiting_write_confirmation" || run.status === "pending_recoverable")) {
+ run.discardOnFinish = true;
+ run.cancelRequested = true;
+ if (run.status === "queued") cancelQueuedDesktopAiRun(run);
+ // Bound the backend cancel and guarantee the concurrency slot is freed
+ // when the pipeline settles (or after the force-abandon deadline if the
+ // stream is hung). The old path removed the run immediately without ever
+ // releasing the slot, so a few deleted-but-hung runs wedged the queue
+ // permanently. Never blocks the delete itself.
+ releaseDeletedRunSlot(run);
+ }
+ removeDesktopAiRun(id);
+ }
+ queuedInputs.delete(id);
await deleteConversationWithCancellation({
id,
currentConversationId: () => conversationId.value,
- isGenerating: () => isGenerating.value,
+ isGenerating: () => !backgroundAiRunsEnabled && isGenerating.value,
abandon: () => abandonInFlightRequest(),
deletePersisted: () => deleteAiConversation(id).catch(() => {}),
afterDelete: () => {
@@ -3010,6 +3896,21 @@ async function deleteConversation(id: string) {
});
}
+/** Removes a recovered pending-input draft and the `pending_recoverable` run
+ * that carries it. The draft was never sent, so nothing needs a backend
+ * cancel — just finish the run terminal and drop it from the registry. */
+function discardRecoveredDraft() {
+ const run = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(conversationId.value) : undefined;
+ if (run?.status === "pending_recoverable") {
+ run.discardOnFinish = true;
+ run.cancelRequested = true;
+ finishDesktopAiRun(run, "cancelled");
+ removeDesktopAiRun(run.conversationId);
+ }
+ prompt.value = "";
+ recoveredDraftActive.value = false;
+}
+
function startNewChat() {
clearMessages();
showConversationList.value = false;
@@ -3019,7 +3920,96 @@ function startNewChat() {
activeAction.value = resolveDefaultAction(mode);
}
+/** Send-button dispatcher: with an active run on the visible conversation the
+ * button becomes "queue send" (parent PRD §5) and stores the input instead of
+ * creating a second run. */
+function onSendClick() {
+ if (hasActiveRunForCurrentConversation.value) queueInput();
+ else void send();
+}
+
+/** Saves the input as the conversation's single queued "send later" message.
+ * Does not create an AiRun; persisted via the conversation and auto-sent when
+ * the active run reaches a terminal state. */
+function queueInput() {
+ const text = prompt.value.trim();
+ if (!text) return;
+ if (!conversationId.value) conversationId.value = uuid();
+ queuedInputs.set(conversationId.value, { text, mode: assistantMode.value, action: activeAction.value });
+ prompt.value = "";
+ selectedMentions.value = [];
+ selectedSqlFileMentions.value = [];
+ selectedCsvAttachments.value = [];
+ selectedImageAttachments.value = [];
+ void persistConversation();
+ toast(t("ai.inputQueued"), 2500);
+}
+
+function removeQueuedInput() {
+ if (!conversationId.value) return;
+ queuedInputs.delete(conversationId.value);
+ void persistConversation();
+}
+
+/** Pulls the queued input back into the input box for editing; the queued slot
+ * is cleared so the user owns the draft again. */
+function editQueuedInput() {
+ const queued = currentQueuedInput.value;
+ if (!queued || !conversationId.value) return;
+ prompt.value = queued.text;
+ queuedInputs.delete(conversationId.value);
+ recoveredDraftActive.value = false;
+ nextTick(() => promptTextareaRef.value?.focus());
+}
+
+/** Stops a specific conversation's run from its history row. Mirrors the
+ * desktop branch of cancelStream() so the row and the input area stop the
+ * exact same AiRun (parent PRD §7). */
+async function stopConversationRun(convId: string) {
+ const run = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(convId) : undefined;
+ if (!run || (run.status !== "preparing" && run.status !== "queued" && run.status !== "running")) return;
+ await stopDesktopAiRun(run);
+}
+
+/** "Retry this round" for a failed/interrupted row: sends a fresh run whose
+ * history ends before the failed round's user message, excluding any partial
+ * assistant text/reasoning/tool results it produced (parent PRD §7). */
+function retryConversationRun(convId: string) {
+ const run = backgroundAiRunsEnabled ? desktopAiRun<ChatMessage>(convId) : undefined;
+ const history = run?.messages ?? chatMessagesFromConversation(conversations.value.find((c) => c.id === convId) ?? conversations.value[0]);
+ let lastUserIdx = -1;
+ for (let i = history.length - 1; i >= 0; i--) {
+ const m = history[i];
+ if (m.kind === "contextSummary") continue;
+ if (m.role === "user") {
+ lastUserIdx = i;
+ break;
+ }
+ }
+ if (lastUserIdx < 0) return;
+ const text = history[lastUserIdx].content;
+ if (!text.trim()) return;
+ // A fresh run — never reuse the failed run's id/session. (`interrupted` is a
+ // persisted row status only; a live registry run can never be interrupted.)
+ if (run && run.status === "failed") {
+ run.discardOnFinish = true;
+ run.cancelRequested = true;
+ finishDesktopAiRun(run, "cancelled");
+ }
+ scheduleAutoSend(convId, { text, mode: assistantMode.value, action: activeAction.value }, history.slice(0, lastUserIdx));
+}
+
+/** Dismisses the "updates while you were away" separator and jumps to the end. */
+function dismissAwayUpdates() {
+ const convId = conversationId.value;
+ if (!convId) return;
+ conversationHasAwayUpdates.delete(convId);
+ conversationReadMessageCount.set(convId, visibleMessages.value.length);
+ scrollToBottom({ force: true });
+}
+
onMounted(async () => {
+ assistantViewMounted = true;
const savedHeight = localStorage.getItem(AI_TEXTAREA_HEIGHT_STORAGE_KEY);
if (savedHeight) {
const height = parseInt(savedHeight, 10);
@@ -3029,6 +4019,94 @@ 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.
+ for (const conversation of conversations.value) {
+ if (conversation.queuedInput) {
+ queuedInputs.set(conversation.id, { text: conversation.queuedInput, mode: assistantMode.value, action: activeAction.value });
+ }
+ }
+ if (backgroundAiRunsEnabled) {
+ const persistedRuns = await loadAiRuns().catch(() => []);
+ const conversationsById = new Map(conversations.value.map((conversation) => [conversation.id, conversation]));
+ const recoveredConversations = new Set<string>();
+ for (const persistedRun of persistedRuns) {
+ const conversation = conversationsById.get(persistedRun.conversationId);
+ if (!conversation) continue;
+ // The panel can be closed and reopened while the original component's
+ // detached stream is still alive. Its run object is the authoritative
+ // live owner of incoming deltas; never replace it with an older durable
+ // snapshot during the new component's startup recovery.
+ const liveRun = desktopAiRun<ChatMessage>(persistedRun.conversationId);
+ if (liveRun) {
+ conversationRunStatus.set(persistedRun.conversationId, liveRun.status);
+ conversationReadSeq.set(persistedRun.conversationId, liveRun.maxSeq ?? 0);
+ recoveredConversations.add(persistedRun.conversationId);
+ continue;
+ }
+ // Multiple runs can exist per conversation across separate sends; the
+ // newest run (first in the updated_at DESC list) defines the row state.
+ if (recoveredConversations.has(persistedRun.conversationId)) continue;
+ recoveredConversations.add(persistedRun.conversationId);
+ // The read baseline for a recovered run starts at its persisted max seq:
+ // anything the run later produces while the user is away is "new".
+ conversationReadSeq.set(persistedRun.conversationId, persistedRun.maxSeq ?? 0);
+ const now = new Date().toISOString();
+ if (persistedRun.status === "awaiting_write_confirmation") {
+ conversationRunStatus.set(persistedRun.conversationId, "awaiting_write_confirmation");
+ registerPersistedAiRun(conversation, persistedRun, "awaiting_write_confirmation", now);
+ } else if (persistedRun.status === "queued") {
+ if (persistedRun.fifoCategory === "write_confirmation_resume") {
+ // The accepted write confirmation never survives a restart: the grant
+ // is intentionally not serialized (PRD §7). Fall back to the original
+ // confirmation card; the user must confirm again before the resume
+ // segment may re-enter the FIFO.
+ void saveAiRun({ ...persistedRun, status: "awaiting_write_confirmation", fifoCategory: undefined, pendingInput: undefined, updatedAt: now }).catch(() => {});
+ conversationRunStatus.set(persistedRun.conversationId, "awaiting_write_confirmation");
+ registerPersistedAiRun(conversation, persistedRun, "awaiting_write_confirmation", now);
+ } else {
+ // A normal-send FIFO item becomes an editable, UNSENT pending draft
+ // (PRD §7 line 93, AC 123) — never a failed/interrupted task. Pull the
+ // user's input out of the transcript and surface it as the draft.
+ const messages = chatMessagesFromConversation(conversation);
+ const recovered = extractRecoverableDraft(messages);
+ const draft = persistedRun.pendingInput ?? recovered?.draft;
+ if (draft && recovered) {
+ await persistPendingInputRecovery(conversation, recovered.messages, { ...persistedRun, status: "pending_recoverable", fifoCategory: undefined, pendingInput: draft, updatedAt: now }, now);
+ conversationRunStatus.set(persistedRun.conversationId, "pending_recoverable");
+ registerPersistedAiRun(conversation, persistedRun, "pending_recoverable", now, {
+ messages: recovered.messages,
+ pendingInput: draft,
+ });
+ } else if (draft) {
+ // Draft recovered without a transcript message to strip (e.g. the
+ // conversation was pruned mid-restart) — keep the transcript intact.
+ await persistPendingInputRecovery(conversation, messages, { ...persistedRun, status: "pending_recoverable", fifoCategory: undefined, pendingInput: draft, updatedAt: now }, now);
+ conversationRunStatus.set(persistedRun.conversationId, "pending_recoverable");
+ registerPersistedAiRun(conversation, persistedRun, "pending_recoverable", now, { pendingInput: draft });
+ } else {
+ // No input to recover; do not fake an interruption for a task that
+ // never started. Simply mark it terminal so it leaves the queue.
+ void saveAiRun({ ...persistedRun, status: "cancelled", updatedAt: now }).catch(() => {});
+ conversationRunStatus.set(persistedRun.conversationId, "cancelled");
+ }
+ }
+ } else if (persistedRun.status === "pending_recoverable") {
+ // A draft recovered in an earlier session that was still pending when the
+ // app closed again — keep it recoverable, do not fake a failure.
+ conversationRunStatus.set(persistedRun.conversationId, "pending_recoverable");
+ registerPersistedAiRun(conversation, persistedRun, "pending_recoverable", now, { pendingInput: persistedRun.pendingInput });
+ } else if (persistedRun.status === "preparing" || persistedRun.status === "running") {
+ // A process restart cannot truthfully resume a Tauri producer. Preserve
+ // the transcript, but make the terminal state explicit instead of
+ // pretending the old stream is still alive.
+ void saveAiRun({ ...persistedRun, status: "interrupted", updatedAt: now }).catch(() => {});
+ conversationRunStatus.set(persistedRun.conversationId, "interrupted");
+ } else {
+ conversationRunStatus.set(persistedRun.conversationId, persistedRun.status);
+ }
+ }
+ }
shikiCodeHighlighter.value = await createAiShikiCodeHighlighter({
appearance: () => aiCodeAppearance.value,
}).catch(() => undefined);
@@ -3093,6 +4171,7 @@ function stopResize() {
}
onUnmounted(() => {
+ assistantViewMounted = false;
// Ignore any FileReader/Tauri filesystem work that finishes after this panel is gone.
attachmentDraftEpoch += 1;
if (assistantDeltaFrame !== null) cancelAnimationFrame(assistantDeltaFrame);
@@ -3105,7 +4184,7 @@ onUnmounted(() => {
// yet) when this component unmounts, cancelStream() alone leaves the generation
// current, so the request still starts and its event callback/catch/finally keep
// writing into refs this now-unmounted instance's closures still hold.
- if (isGenerating.value) abandonInFlightRequest();
+ if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();
detachMessageScrollListener();
// 清理拖拽事件监听,防止内存泄漏
document.removeEventListener("mousemove", handleResize);
@@ -3155,7 +4234,7 @@ function clearContextReferences() {
mentionError.value = "";
}
-defineExpose({ triggerAction, setPrompt, addTableMention, clearContextReferences });
+defineExpose({ triggerAction, setPrompt, addTableMention, clearContextReferences, selectConversationById });
const messageRenderer = computed(() => {
const appearance = aiCodeAppearance.value;
@@ -3234,8 +4313,47 @@ async function openExternalUrl(url: string) {
</div>
<div v-else class="max-h-64 overflow-auto p-1">
<div v-for="conv in filteredConversations" :key="conv.id" class="flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-muted" :class="{ 'bg-muted': conv.id === conversationId }" @click="selectConversation(conv)">
- <span class="min-w-0 flex-1 truncate">{{ conv.title }}</span>
- <button class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-background hover:text-destructive" @click.stop="deleteConversation(conv.id)">
+ <span class="min-w-0 flex-1 truncate" :title="conv.title">{{ conv.title }}</span>
+ <span v-if="conversationRowDetail(conv).hasQueuedInput" class="shrink-0 rounded border border-primary/40 bg-primary/10 px-1 py-px text-[10px] text-primary" :aria-label="t('ai.rowQueuedInput')" :title="t('ai.rowQueuedInput')">{{ t("ai.rowQueuedInput") }}</span>
+ <span v-if="conversationRowDetail(conv).status === 'preparing' || conversationRowDetail(conv).status === 'running'" class="flex min-w-0 shrink-0 items-center gap-1 text-muted-foreground" :aria-label="t('ai.runStatusRunning')" :title="t('ai.runStatusRunning')">
+ <Loader2 class="h-3 w-3 shrink-0 animate-spin" />
+ <span class="hidden truncate min-[430px]:inline">{{ conversationRowDetail(conv).phaseText ?? t("ai.runStatusRunning") }}</span>
+ <span v-if="conversationRowDetail(conv).elapsedSeconds !== null" class="shrink-0 tabular-nums text-muted-foreground/70">{{ formatRunElapsed(conversationRowDetail(conv).elapsedSeconds) }}</span>
+ <button class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-destructive" :title="t('ai.stopGenerating')" :aria-label="t('ai.stopGenerating')" @click.stop="stopConversationRun(conv.id)">
+ <Square class="h-3 w-3" />
+ </button>
+ </span>
+ <span v-else-if="conversationRowDetail(conv).status === 'queued'" class="flex shrink-0 items-center gap-1 text-muted-foreground" :aria-label="t('ai.runStatusWaitingToStart')">
+ <Hourglass class="h-3 w-3" />
+ <span>{{ t("ai.runStatusWaitingToStart") }}</span>
+ </span>
+ <span v-else-if="conversationRowDetail(conv).status === 'awaiting_write_confirmation'" class="flex shrink-0 items-center gap-1 font-medium text-amber-600 dark:text-amber-400" :aria-label="t('ai.runStatusAwaitingConfirmation')">
+ <AlertTriangle class="h-3 w-3" />
+ <span>{{ t("ai.runStatusAwaitingConfirmation") }}</span>
+ </span>
+ <span v-else-if="conversationRowDetail(conv).status === 'pending_recoverable'" class="flex shrink-0 items-center gap-1 text-muted-foreground" :aria-label="t('ai.runStatusPendingDraft')">
+ <Clock class="h-3 w-3" />
+ <span>{{ t("ai.runStatusPendingDraft") }}</span>
+ </span>
+ <span v-else-if="conversationRowDetail(conv).status === 'completed'" class="flex min-w-0 shrink-0 items-center gap-1" :aria-label="t('ai.runStatusCompleted')" :title="conversationRowDetail(conv).summary ?? t('ai.runStatusCompleted')">
+ <Check class="h-3 w-3 shrink-0 text-green-500" />
+ </span>
+ <span
+ v-else-if="conversationRowDetail(conv).status === 'failed' || conversationRowDetail(conv).status === 'interrupted'"
+ class="flex min-w-0 shrink-0 items-center gap-1"
+ :aria-label="t(conversationRowDetail(conv).status === 'interrupted' ? 'ai.runStatusInterrupted' : 'ai.runStatusFailed')"
+ :title="conversationRowDetail(conv).reason ?? t(conversationRowDetail(conv).status === 'interrupted' ? 'ai.runStatusInterrupted' : 'ai.runStatusFailed')"
+ >
+ <AlertTriangle class="h-3 w-3 shrink-0 text-destructive" />
+ <button class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground" :title="t('ai.retryRound')" :aria-label="t('ai.retryRound')" @click.stop="retryConversationRun(conv.id)">
+ <RefreshCw class="h-3 w-3" />
+ </button>
+ </span>
+ <span v-else-if="conversationRowDetail(conv).status === 'cancelled'" class="flex shrink-0 items-center" :aria-label="t('ai.runStatusCancelled')" :title="t('ai.runStatusCancelled')">
+ <CircleSlash class="h-3 w-3 text-muted-foreground" />
+ </span>
+ <span v-if="conversationRowDetail(conv).unread" class="h-1.5 w-1.5 shrink-0 rounded-full bg-primary" :aria-label="t('ai.runUnread')" :title="t('ai.runUnread')" />
+ <button class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-background hover:text-destructive" :title="t('ai.deleteConversation')" :aria-label="t('ai.deleteConversation')" @click.stop="deleteConversation(conv.id)">
<X class="h-3 w-3" />
</button>
</div>
@@ -3262,6 +4380,15 @@ async function openExternalUrl(url: string) {
<ScrollArea ref="scrollRef" class="ai-message-scroll h-full overflow-hidden">
<div class="flex flex-col gap-3 p-3">
<template v-for="(msg, i) in visibleMessages" :key="i">
+ <div v-if="awayUpdatesBaselineIndex >= 0 && i === awayUpdatesBaselineIndex" class="mb-1 flex items-center gap-2 py-0.5" role="separator" :aria-label="t('ai.awayUpdatesDivider')">
+ <span class="h-px flex-1 bg-primary/25" />
+ <span class="shrink-0 text-[10px] uppercase tracking-wide text-primary/80">{{ t("ai.awayUpdatesDivider") }}</span>
+ <button type="button" class="shrink-0 rounded border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary hover:bg-primary/20" :title="t('ai.jumpToLatest')" :aria-label="t('ai.jumpToLatest')" @click="dismissAwayUpdates">
+ <ArrowDown class="mr-0.5 inline h-2.5 w-2.5" />
+ {{ t("ai.jumpToLatest") }}
+ </button>
+ <span class="h-px flex-1 bg-primary/25" />
+ </div>
<div v-if="msg.role === 'user'" class="group flex justify-end">
<div class="relative min-w-0 max-w-[85%]" :class="{ 'w-[85%]': editingMessageIndex === i }">
<template v-if="editingMessageIndex === i">
@@ -3761,6 +4888,35 @@ async function openExternalUrl(url: string) {
@remove="removeImageAttachment(index)"
/>
</div>
+ <div v-if="recoveredDraftActive" class="mb-1.5 flex items-center gap-1.5 rounded-[7px] border border-primary/30 bg-primary/10 px-[9px] py-[5px] text-[11px] text-primary" role="status">
+ <Clock class="h-3.5 w-3.5 shrink-0" />
+ <span class="min-w-0 flex-1 truncate"> {{ t("ai.recoveredDraftBanner") }} — {{ t("ai.recoveredDraftHint") }} </span>
+ <button type="button" class="shrink-0 rounded p-0.5 text-muted-foreground hover:text-destructive" :title="t('ai.discardDraft')" :aria-label="t('ai.discardDraft')" @click="discardRecoveredDraft">
+ <X class="h-3 w-3" />
+ </button>
+ </div>
+ <div v-if="currentQueuedInput" class="mb-1.5 flex items-center gap-1.5 rounded-[7px] border border-primary/30 bg-primary/10 px-[9px] py-[5px] text-[11px] text-primary" role="status">
+ <Hourglass class="h-3.5 w-3.5 shrink-0" />
+ <span class="min-w-0 flex-1 truncate" :title="currentQueuedInput.text">
+ {{ hasActiveRunForCurrentConversation ? t("ai.queuedInputWaiting", { text: currentQueuedInput.text }) : t("ai.queuedInputPending", { text: currentQueuedInput.text }) }}
+ </span>
+ <button
+ v-if="!hasActiveRunForCurrentConversation"
+ type="button"
+ class="shrink-0 rounded border border-primary/40 bg-primary px-1.5 py-0.5 text-[10px] font-medium text-primary-foreground hover:bg-primary/90"
+ :title="t('ai.sendQueuedInput')"
+ :aria-label="t('ai.sendQueuedInput')"
+ @click="sendQueuedInputNow"
+ >
+ {{ t("ai.sendQueuedInput") }}
+ </button>
+ <button type="button" class="shrink-0 rounded p-0.5 text-muted-foreground hover:text-primary" :title="t('ai.queuedInputEdit')" :aria-label="t('ai.queuedInputEdit')" @click="editQueuedInput">
+ <Pencil class="h-3 w-3" />
+ </button>
+ <button type="button" class="shrink-0 rounded p-0.5 text-muted-foreground hover:text-destructive" :title="t('ai.queuedInputRemove')" :aria-label="t('ai.queuedInputRemove')" @click="removeQueuedInput">
+ <X class="h-3 w-3" />
+ </button>
+ </div>
<textarea
ref="promptTextareaRef"
v-model="prompt"
@@ -4037,6 +5193,10 @@ async function openExternalUrl(url: string) {
<button v-if="isGenerating" class="h-7 w-7 shrink-0 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center" :title="t('ai.stopGenerating')" @click="cancelStream">
<Square class="h-3.5 w-3.5" />
</button>
+ <button v-else-if="hasActiveRunForCurrentConversation" class="h-7 shrink-0 items-center gap-1 rounded-full bg-foreground px-2.5 text-[11px] font-medium text-background disabled:opacity-30 flex" :disabled="!canSubmitPrompt" :title="t('ai.queueSendHint')" @click="onSendClick">
+ <Hourglass class="h-3.5 w-3.5" />
+ <span>{{ t("ai.queueSend") }}</span>
+ </button>
<button v-else class="h-7 w-7 shrink-0 rounded-full bg-foreground text-background flex items-center justify-center disabled:opacity-30" :disabled="!canSubmitPrompt" @click="send">
<ArrowUp class="h-4 w-4" />
</button>
@@ -4064,6 +5224,26 @@ async function openExternalUrl(url: string) {
</div>
</DialogContent>
</Dialog>
+
+ <Dialog
+ :open="deleteConfirmConversationId !== null"
+ @update:open="
+ (open: boolean) => {
+ if (!open) deleteConfirmConversationId = null;
+ }
+ "
+ >
+ <DialogContent class="sm:max-w-[440px]" @interact-outside.prevent>
+ <DialogHeader>
+ <DialogTitle>{{ t("ai.deleteActiveConversationTitle") }}</DialogTitle>
+ <DialogDescription>{{ t("ai.deleteActiveConversationDescription") }}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter class="gap-2 sm:gap-2">
+ <Button type="button" variant="outline" @click="cancelDeleteConversation">{{ t("ai.keepConversation") }}</Button>
+ <Button type="button" variant="destructive" @click="confirmDeleteConversation">{{ t("ai.cancelTaskAndDelete") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</template>
<style scoped>
diff --git a/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts b/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts
index 1b5c5f8603..90bf8fe32b 100644
--- a/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/AiAssistant.clearAndCancel.spec.ts
@@ -33,7 +33,7 @@ function bodyOf(fnSignature: string): string {
throw new Error(`unbalanced braces reading body of "${fnSignature}"`);
}
-describe("AI assistant clear/switch cancels an in-flight request (issue #5941, PR #6332)", () => {
+describe("AI assistant uses platform-specific conversation lifecycle", () => {
it("abandonInFlightRequest() invalidates the generation guard before/regardless of the backend RPC", () => {
const body = bodyOf("function abandonInFlightRequest(alreadyCancelledSessionId?: string)");
expect(body).toContain("aiGenerationGuard.invalidate();");
@@ -45,17 +45,19 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
expect(body.indexOf("aiGenerationGuard.invalidate();")).toBeLessThan(body.indexOf("if (sessionId && sessionId !== alreadyCancelledSessionId) {"));
});
- it("clearMessages() abandons a stuck stream before wiping history", () => {
+ it("clearMessages() keeps Web cancellation while Desktop detaches the view", () => {
const body = bodyOf("function clearMessages()");
- expect(body).toContain("if (isGenerating.value) abandonInFlightRequest();");
+ expect(body).toContain("if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();");
+ expect(body).toContain("if (isGenerating.value && backgroundAiRunsEnabled) void persistConversation();");
// The abandon guard must run before the history is actually wiped, not after.
- expect(body.indexOf("if (isGenerating.value) abandonInFlightRequest();")).toBeLessThan(body.indexOf("messages.value = []"));
+ expect(body.indexOf("!backgroundAiRunsEnabled) abandonInFlightRequest();")).toBeLessThan(body.indexOf("messages.value = []"));
});
- it("selectConversation() abandons a stuck stream before switching conversations", () => {
+ it("selectConversation() cancels on Web and reattaches to a Desktop run", () => {
const body = bodyOf("function selectConversation(conv: AiConversation)");
- expect(body).toContain("if (isGenerating.value) abandonInFlightRequest();");
- expect(body.indexOf("if (isGenerating.value) abandonInFlightRequest();")).toBeLessThan(body.indexOf("conversationId.value = conv.id;"));
+ expect(body).toContain("if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();");
+ expect(body).toContain("desktopAiRun<ChatMessage>(conv.id)");
+ expect(body.indexOf("!backgroundAiRunsEnabled) abandonInFlightRequest();")).toBeLessThan(body.indexOf("conversationId.value = conv.id;"));
});
it("cancelStream() delegates live state readers to the tested stop lifecycle", () => {
@@ -67,15 +69,97 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
expect(body).toContain("persistConversation,");
});
- it("startNewChat() clears through the guarded path and deleteConversation() uses the tested delete lifecycle", () => {
+ it("startNewChat() clears through the guarded path and performDeleteConversation() uses the tested delete lifecycle", () => {
expect(bodyOf("function startNewChat()")).toContain("clearMessages();");
- const deleteBody = bodyOf("async function deleteConversation(id: string)");
+ const deleteBody = bodyOf("async function performDeleteConversation(id: string)");
expect(deleteBody).toContain("await deleteConversationWithCancellation({");
expect(deleteBody).toContain("abandon: () => abandonInFlightRequest()");
expect(deleteBody).toContain("deletePersisted: () => deleteAiConversation(id).catch(() => {})");
expect(deleteBody).toContain("if (conversationId.value === id) clearMessages();");
});
+ it("deleteConversation() asks for confirmation only when the conversation owns an active task", () => {
+ // Parent PRD §4 line 70: deleting a conversation with a running/queued/
+ // awaiting task must first ask; a conversation without an active task still
+ // deletes directly.
+ const deleteBody = bodyOf("async function deleteConversation(id: string)");
+ expect(deleteBody).toContain("if (backgroundAiRunsEnabled && conversationHasActiveTask(id)) {");
+ expect(deleteBody).toContain("deleteConfirmConversationId.value = id;");
+ expect(deleteBody).toContain("await performDeleteConversation(id);");
+ const taskBody = bodyOf("function conversationHasActiveTask(id: string)");
+ expect(taskBody).toContain('status === "awaiting_write_confirmation"');
+ expect(taskBody).toContain('status === "pending_recoverable"');
+ });
+
+ it("performDeleteConversation() marks desktop runs discardOnFinish so no async write can resurrect them", () => {
+ // Reviewed finding (delete-resurrection, HIGH): a queued/running background
+ // run's snapshot persists fired AFTER deleteAiConversation committed, so the
+ // INSERT OR REPLACE recreated the just-deleted conversation. The delete path
+ // must flag the run so every persist site skips it.
+ const body = bodyOf("async function performDeleteConversation(id: string)");
+ expect(body).toContain("run.discardOnFinish = true;");
+ expect(body).toContain('if (run.status === "queued") cancelQueuedDesktopAiRun(run);');
+ // The run is never finished here: the delete removes it from the registry
+ // immediately and the bounded background cleanup owns finalization, so a
+ // finished-but-still-slot-holding run can't wedge the queue.
+ expect(body).not.toContain('finishDesktopAiRun(run, "cancelled");');
+ expect(body).toContain("releaseDeletedRunSlot(run);");
+ // The confirm path must cancel runs in ALL active statuses, including a
+ // pending write confirmation and a recovered draft.
+ expect(body).toContain('run.status === "awaiting_write_confirmation"');
+ expect(body).toContain('run.status === "pending_recoverable"');
+ });
+
+ it("performDeleteConversation() launches bounded slot release so a deleted-but-hung run cannot wedge the queue", () => {
+ // Reviewed finding (slot leak, HIGH): the delete path removed the run from
+ // the registry immediately but never released its admittedRunIds slot when
+ // the backend stream was hung — after DESKTOP_AI_CONCURRENCY_LIMIT such
+ // deletes the global queue wedges permanently. The bounded release waits
+ // for the pipeline's settled signal (or the force-abandon deadline) and
+ // frees the slot; it also must not block the delete on the cancel RPC.
+ const releaseBody = bodyOf("function releaseDeletedRunSlot(run: DesktopAiRunRuntime<ChatMessage>)");
+ expect(releaseBody).toContain("if (!run.settled) return;");
+ expect(releaseBody).toContain("waitForDesktopRunSettled(run)");
+ expect(releaseBody).toContain("releaseDesktopAiRunSlot(run.runId)");
+ expect(releaseBody).toContain("requestDesktopRunCancellation(run, deadlineAt, false)");
+ const deleteBody = bodyOf("async function performDeleteConversation(id: string)");
+ expect(deleteBody).not.toContain("await aiCancelStream(");
+ });
+
+ it("send() guards every snapshot persist behind discardOnFinish so a deleted conversation can't be resurrected", () => {
+ const sendBody = bodyOf("async function send()");
+ // All three send()-internal persist sites (queued persist, unslotted
+ // early-return, and the pre-stream snapshot) must be guarded — previously
+ // some persisted unconditionally.
+ const guardedSites = sendBody.match(/if \(!detachedRun\.discardOnFinish\) void runSnapshotScheduler\.save\(detachedRun\);/g) ?? [];
+ expect(guardedSites.length).toBe(3);
+ // The finally must skip the run snapshot when the run was deleted, and the
+ // Web-only conversation fallback must not fire for a deleted Desktop run.
+ const finallyIdx = sendBody.indexOf("} finally {");
+ const finallyBody = sendBody.slice(finallyIdx);
+ expect(finallyBody).toContain("if (!detachedRun.discardOnFinish) {");
+ expect(finallyBody).not.toContain("else void persistConversationSnapshot(");
+ });
+
+ it("send() tags a queued run's FIFO category so restart recovery can classify it", () => {
+ const sendBody = bodyOf("async function send()");
+ const queueIdx = sendBody.indexOf('if (detachedRun.status === "queued")');
+ expect(queueIdx).toBeGreaterThanOrEqual(0);
+ const queuedBlock = sendBody.slice(queueIdx);
+ expect(queuedBlock).toContain('fifoCategory: resumingConfirmedWrite ? "write_confirmation_resume" : "normal_send"');
+ expect(queuedBlock).toContain("pendingInput: resumingConfirmedWrite ? detachedRun.pendingInput : text");
+ });
+
+ it("send() discards a recovered pending-input run before starting a fresh one", () => {
+ const sendBody = bodyOf("async function send()");
+ const registerIdx = sendBody.indexOf("const resumableRun = desktopAiRun<ChatMessage>(runConversationId);");
+ expect(registerIdx).toBeGreaterThanOrEqual(0);
+ const registerBlock = sendBody.slice(registerIdx);
+ expect(registerBlock).toContain('resumableRun?.status === "pending_recoverable"');
+ expect(registerBlock).toContain("resumableRun.discardOnFinish = true;");
+ expect(registerBlock).toContain("removeDesktopAiRun(resumableRun.conversationId);");
+ });
+
it("send() claims a generation id right after setting isGenerating and re-checks it after the first await", () => {
const sendBody = bodyOf("async function send()");
const claimIdx = sendBody.indexOf("const myGeneration = aiGenerationGuard.begin();");
@@ -85,7 +169,7 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
// anything that touches messages/mentions belonging to whatever conversation
// is current by the time it resolves.
const ensureLoadedAwaitIdx = sendBody.indexOf("await promptTemplateStore.ensureLoaded()");
- const recheckIdx = sendBody.indexOf("if (!aiGenerationGuard.isCurrent(myGeneration))", ensureLoadedAwaitIdx);
+ const recheckIdx = sendBody.indexOf("if (!generationCanContinue())", ensureLoadedAwaitIdx);
expect(ensureLoadedAwaitIdx).toBeGreaterThan(claimIdx);
expect(recheckIdx).toBeGreaterThan(ensureLoadedAwaitIdx);
});
@@ -100,7 +184,7 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
const sendBody = bodyOf("async function send()");
const ensureLoadedAwaitIdx = sendBody.indexOf("await promptTemplateStore.ensureLoaded()");
const grantConsumedIdx = sendBody.indexOf("const allowWriteSql = requestedMode", ensureLoadedAwaitIdx);
- const recheckIdx = sendBody.indexOf("if (!aiGenerationGuard.isCurrent(myGeneration)) {", ensureLoadedAwaitIdx);
+ const recheckIdx = sendBody.indexOf("if (!generationCanContinue()) {", ensureLoadedAwaitIdx);
expect(recheckIdx).toBeGreaterThan(ensureLoadedAwaitIdx);
expect(recheckIdx).toBeLessThan(grantConsumedIdx);
const recheckEnd = sendBody.indexOf("}", recheckIdx);
@@ -113,7 +197,7 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
const sendBody = bodyOf("async function send()");
const callbackStart = sendBody.indexOf("(event: AgentEvent) => {");
expect(callbackStart).toBeGreaterThanOrEqual(0);
- const guardIdx = sendBody.indexOf("if (!aiGenerationGuard.isCurrent(myGeneration)) return;", callbackStart);
+ const guardIdx = sendBody.indexOf("if (!generationCanContinue()) return;", callbackStart);
const pushIdx = sendBody.indexOf("agentEvents.push(event);", callbackStart);
expect(guardIdx).toBeGreaterThan(callbackStart);
expect(guardIdx).toBeLessThan(pushIdx);
@@ -131,8 +215,8 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
// either throw (silently eating the real error) or corrupt a different
// conversation's transcript.
expect(catchBody).not.toContain("messages.value[assistantIdx].content =");
- expect(catchBody).toContain("aiGenerationGuard.isCurrent(myGeneration)");
- expect(catchBody).toContain("const msg = messages.value[assistantIdx];");
+ expect(catchBody).toContain("generationCanContinue()");
+ expect(catchBody).toContain("const msg = runMessages[assistantIdx];");
expect(catchBody).toContain("if (msg) msg.content =");
});
@@ -141,7 +225,7 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
const start = sendBody.indexOf("} finally {");
expect(start).toBeGreaterThanOrEqual(0);
const finallyBody = sendBody.slice(start);
- const guardIdx = finallyBody.indexOf("if (aiGenerationGuard.isCurrent(myGeneration)) {");
+ const guardIdx = finallyBody.indexOf("if (detachedRun || aiGenerationGuard.isCurrent(myGeneration)) {");
expect(guardIdx).toBeGreaterThanOrEqual(0);
const isGeneratingIdx = finallyBody.indexOf("isGenerating.value = false;");
const sessionResetIdx = finallyBody.indexOf('currentSessionId.value = "";');
@@ -199,9 +283,9 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
it("send() rechecks the generation after EACH context-preparation await, before ever starting the stream", () => {
const sendBody = bodyOf("async function send()");
const sqlFilesIdx = sendBody.indexOf("await loadReferencedSqlFiles(");
- const firstRecheckIdx = sendBody.indexOf("if (!aiGenerationGuard.isCurrent(myGeneration)) return;", sqlFilesIdx);
+ const firstRecheckIdx = sendBody.indexOf("if (!generationCanContinue()) return;", sqlFilesIdx);
const contextIdx = sendBody.indexOf("const context = await buildAiContext(");
- const secondRecheckIdx = sendBody.indexOf("if (!aiGenerationGuard.isCurrent(myGeneration)) return;", contextIdx);
+ const secondRecheckIdx = sendBody.indexOf("if (!generationCanContinue()) return;", contextIdx);
const runIdx = sendBody.indexOf("await runAgentStream(", contextIdx);
// A clear/switch/unmount firing during EITHER await invalidates the generation
// but doesn't touch the backend (no session registered yet) — without a
@@ -221,8 +305,8 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
// "finalizes the stuck placeholder message" test above). Must be set at the
// same point currentSessionId is, and cleared alongside it too.
const sendBody = bodyOf("async function send()");
- const pushIdx = sendBody.indexOf('messages.value.push({ role: "assistant"');
- const assistantIdxIdx = sendBody.indexOf("const assistantIdx = messages.value.length - 1;", pushIdx);
+ const pushIdx = sendBody.indexOf('runMessages.push({ role: "assistant"');
+ const assistantIdxIdx = sendBody.indexOf("const assistantIdx = runMessages.length - 1;", pushIdx);
const trackIdx = sendBody.indexOf("currentAssistantMessageIndex = assistantIdx;", assistantIdxIdx);
const sessionSetIdx = sendBody.indexOf("currentSessionId.value = sessionId;", trackIdx);
expect(pushIdx).toBeGreaterThanOrEqual(0);
@@ -286,10 +370,35 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
// callback/catch/finally would keep writing into refs this now-unmounted
// instance's closures still hold. Must go through the same invalidating path as
// clearMessages()/selectConversation().
- expect(body).toContain("if (isGenerating.value) abandonInFlightRequest();");
+ expect(body).toContain("if (isGenerating.value && !backgroundAiRunsEnabled) abandonInFlightRequest();");
expect(body).not.toContain("cancelStream();");
});
+ it("queues simultaneous background auto-sends instead of overwriting a single pending target", () => {
+ // Several detached runs can settle in the same turn. A single mutable
+ // `pendingAutoSend` slot lost whichever queued input was scheduled first.
+ expect(source).toContain("const pendingAutoSends: PendingAutoSend[] = [];");
+ const sendBody = bodyOf("async function send()");
+ expect(sendBody).toContain("const auto = pendingAutoSends.shift() ?? null;");
+ const scheduleBody = bodyOf("function scheduleAutoSend(");
+ expect(scheduleBody).toContain("pendingAutoSends.push(");
+ });
+
+ it("makes successfully persisted background conversations navigable without reopening the list", () => {
+ const snapshotBody = bodyOf("async function persistDesktopRunSnapshot(");
+ expect(snapshotBody).toContain(".then(() => syncPersistedConversation(conversation))");
+ const syncBody = bodyOf("function syncPersistedConversation(conversation: AiConversation)");
+ expect(syncBody).toContain("conversations.value.unshift(conversation);");
+ expect(syncBody).toContain("conversations.value.sort(");
+ });
+
+ it("does not replace an in-memory desktop run when the AI panel remounts", () => {
+ const mountedBody = bodyOf("onMounted(async () => {");
+ expect(mountedBody).toContain("const liveRun = desktopAiRun<ChatMessage>(persistedRun.conversationId);");
+ expect(mountedBody).toContain("if (liveRun) {");
+ expect(mountedBody).toContain("continue;");
+ });
+
it("agent step cards render a running-tool tail and a computed duration tail", () => {
// Issue #6743 (feature-1 gap): per-tool execution time in the agent step cards —
// mockup shows a spinner + "执行中…" tail on running steps and `0.8s`/`1.2s` on
@@ -314,4 +423,115 @@ describe("AI assistant clear/switch cancels an in-flight request (issue #5941, P
const statusBlock = source.slice(statusLineIdx);
expect(statusBlock).toContain("<Hourglass v-else");
});
+
+ // --- Review findings on background AI session tasks (see the two findings
+ // evaluated in this session) ---
+
+ it("persists detached streaming snapshots incrementally from the delta flush path", () => {
+ // Finding 1: detached deltas were flushed only into memory (plus a scroll
+ // callback), so a crash/quit mid-response lost everything after the
+ // pre-stream snapshot. The flush path must now schedule throttled,
+ // serialized snapshot persistence.
+ const sendBody = bodyOf("async function send()");
+ const bufferIdx = sendBody.indexOf("createDetachedAssistantDeltaBuffer(runMessages, () => {");
+ expect(bufferIdx).toBeGreaterThanOrEqual(0);
+ const flushBlock = sendBody.slice(bufferIdx, sendBody.indexOf(": undefined", bufferIdx));
+ expect(flushBlock).toContain("runSnapshotScheduler.schedule(detachedRun);");
+ // The pre-stream snapshot and the finally go through the same serialized
+ // scheduler so a slow write can never reorder around them.
+ expect(sendBody).toContain("void runSnapshotScheduler.save(detachedRun)");
+ // The scheduler itself lives at module scope (the flush callback and the
+ // stop path both use it), configured with the streaming interval.
+ expect(source).toContain("const runSnapshotScheduler = createDesktopAiRunSnapshotScheduler<ChatMessage>({");
+ expect(source).toContain("intervalMs: RUN_SNAPSHOT_PERSIST_INTERVAL_MS");
+ });
+
+ it("send() resolves the run's settled signal on every exit path so a stop can wait for the real terminal event", () => {
+ // Finding 2: the stop path must not finalize the run itself; it waits for
+ // the pipeline's terminal event via the run's `settled` promise. Every
+ // exit path of send() must resolve it (finally + three pre-stream early
+ // returns), or a stop fired there would sit out the full timeout.
+ const sendBody = bodyOf("async function send()");
+ expect(sendBody).toContain("detachedRun.settled = new Promise<void>((resolve) => {");
+ const finallyIdx = sendBody.indexOf("} finally {");
+ const finallyBody = sendBody.slice(finallyIdx);
+ expect(finallyBody).toContain("resolveDetachedRunSettled();");
+ const settledCalls = sendBody.match(/resolveDetachedRunSettled\(\);/g) ?? [];
+ expect(settledCalls.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it("the finally skips finalization for a run that no longer owns its registry slot", () => {
+ // Finding 2: after a stop-side force-abandon (or a delete/replacement send)
+ // retires the run, the old pipeline's finally must not re-run the finish
+ // chain - updateDesktopAiRun() re-inserts unconditionally, which would
+ // resurrect the retired run over whatever now owns the conversation.
+ const sendBody = bodyOf("async function send()");
+ const finallyIdx = sendBody.indexOf("} finally {");
+ const finallyBody = sendBody.slice(finallyIdx);
+ expect(finallyBody).toContain("const runStillOwned = detachedRun ? desktopAiRun(detachedRun.conversationId) === detachedRun : false;");
+ expect(finallyBody).toContain("if (detachedRun && runStillOwned) {");
+ expect(finallyBody).toContain("runSnapshotScheduler.cancel(detachedRun.runId);");
+ expect(finallyBody).toContain("void runSnapshotScheduler.save(detachedRun).finally(");
+ expect(finallyBody).toContain("} else if (!detachedRun) {");
+ });
+
+ it("stopDesktopAiRun keeps a background run active until the pipeline settles, force-abandoning after the timeout", () => {
+ // Finding 2: the old stop path finished+retired immediately, so a hung or
+ // cancellation-pending stream went invisible while still occupying its slot.
+ // The shared helper must reflect the request but defer finalization to the
+ // pipeline's finally or the bounded force-abandon.
+ const body = bodyOf("async function stopDesktopAiRun(");
+ expect(body).toContain("run.cancelRequested = true;");
+ expect(body).toContain("waitForDesktopRunSettled(run)");
+ expect(body).toContain("requestDesktopRunCancellation(run, deadlineAt)");
+ expect(body).toContain("await forceAbandonDesktopAiRun(run);");
+ // Only the never-admitted queued branch finalizes immediately.
+ expect(body).toContain('if (run.status === "queued")');
+ expect(body).toContain("cancelQueuedDesktopAiRun(run);");
+ });
+
+ it("the stop path consumes the aiCancelStream acknowledgement and retries while unacknowledged", () => {
+ // Finding 2: aiCancelStream() returns a boolean (true only when the session
+ // id is registered with the backend) that was discarded. The retry loop
+ // lands the cancellation once the session registers during context
+ // preparation.
+ const body = bodyOf("async function requestDesktopRunCancellation(");
+ expect(body).toContain("const acknowledged = await aiCancelStream(run.currentSessionId).catch(() => false);");
+ expect(body).toContain("if (acknowledged) return;");
+ expect(body).toContain("DESKTOP_CANCEL_ACK_RETRY_MS");
+ });
+
+ it("stopDesktopAiRun fire-and-forgets the cancel retry so a hung IPC cannot block the bounded force-abandon", () => {
+ // Reviewed finding (deadlock, HIGH): stopDesktopAiRun() awaited
+ // requestDesktopRunCancellation(), which awaits aiCancelStream() directly.
+ // If the IPC never returned, the STOP_FORCE_ABANDON_MS race was never read
+ // and the stop never force-abandoned — a hung cancel RPC stranded the run
+ // exactly like the hung stream it was meant to recover from.
+ const body = bodyOf("async function stopDesktopAiRun(");
+ expect(body).toContain("void requestDesktopRunCancellation(run, deadlineAt);");
+ expect(body).not.toContain("await requestDesktopRunCancellation(run, deadlineAt);");
+ // The bounded settle race drives the force-abandon, not the cancel RPC.
+ expect(body).toContain("if (await settled) {");
+ });
+
+ it("both stop entry points delegate to the shared stopDesktopAiRun helper", () => {
+ const cancelBody = bodyOf("async function cancelStream()");
+ expect(cancelBody).toContain("await stopDesktopAiRun(run);");
+ expect(cancelBody).not.toContain('finishDesktopAiRun(run, "cancelled")');
+ const rowBody = bodyOf("async function stopConversationRun(");
+ expect(rowBody).toContain("await stopDesktopAiRun(run);");
+ });
+
+ it("keeps long task summaries out of the fixed-width history popover", () => {
+ // The history popover is always w-72, but min-[430px] responds to viewport
+ // width. On desktop it displayed long summaries inside the compact row,
+ // squeezing the conversation title and forcing horizontal scrolling. The
+ // status icon still exposes the full text through its title/ARIA metadata.
+ const historyStart = source.indexOf('<PopoverContent align="end" class="w-72 gap-0 p-0"');
+ const history = source.slice(historyStart);
+ expect(history).toContain(":title=\"conversationRowDetail(conv).summary ?? t('ai.runStatusCompleted')\"");
+ expect(history).toContain(":title=\"conversationRowDetail(conv).reason ?? t(conversationRowDetail(conv).status === 'interrupted' ? 'ai.runStatusInterrupted' : 'ai.runStatusFailed')\"");
+ expect(history).not.toContain("conversationRowDetail(conv).summary }}</span>");
+ expect(history).not.toContain("conversationRowDetail(conv).reason }}</span>");
+ });
});
diff --git a/apps/desktop/src/components/layout/AiRunsClosePromptDialog.vue b/apps/desktop/src/components/layout/AiRunsClosePromptDialog.vue
new file mode 100644
index 0000000000..2546e1e22f
--- /dev/null
+++ b/apps/desktop/src/components/layout/AiRunsClosePromptDialog.vue
@@ -0,0 +1,25 @@
+<script setup lang="ts">
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+
+defineProps<{ count: number }>();
+const open = defineModel<boolean>("open", { required: true });
+const emit = defineEmits<{ cancel: []; quit: [] }>();
+const { t } = useI18n();
+</script>
+
+<template>
+ <Dialog v-model:open="open">
+ <DialogContent class="sm:max-w-[440px]" @interact-outside.prevent>
+ <DialogHeader>
+ <DialogTitle>{{ t("ai.closeWithRunsTitle") }}</DialogTitle>
+ <DialogDescription>{{ t("ai.closeWithRunsDescription", { count }) }}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter class="gap-2 sm:gap-2">
+ <Button type="button" variant="outline" @click="emit('cancel')">{{ t("common.cancel") }}</Button>
+ <Button type="button" variant="destructive" @click="emit('quit')">{{ t("ai.closeWithRunsQuit") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+</template>
diff --git a/apps/desktop/src/components/layout/AppToolbar.vue b/apps/desktop/src/components/layout/AppToolbar.vue
index 8e155b67e3..95a57ad729 100644
--- a/apps/desktop/src/components/layout/AppToolbar.vue
+++ b/apps/desktop/src/components/layout/AppToolbar.vue
@@ -27,6 +27,10 @@ const props = defineProps<{
isDark: boolean;
themeMode: AppThemeMode;
showAiPanel: boolean;
+ activeAiRunCount: number;
+ /** Runs awaiting a write confirmation; the badge turns amber to outrank the
+ * plain active count (parent PRD §4 line 71). */
+ awaitingAiRunCount: number;
showHistory: boolean;
showSqlLibrary: boolean;
sqlLibrarySaveFeedbackId: number;
@@ -642,8 +646,19 @@ const toolbarStyle = computed(() => {
<Tooltip v-if="toolbarItems.ai">
<TooltipTrigger as-child>
- <Button v-show="isRightItemVisible('ai')" variant="ghost" size="icon" class="h-8 w-8 shrink-0" :class="{ 'bg-accent': showAiPanel }" @click="emit('toggle-ai')">
+ <Button v-show="isRightItemVisible('ai')" variant="ghost" size="icon" class="relative h-8 w-8 shrink-0" :class="{ 'bg-accent': showAiPanel }" @click="emit('toggle-ai')">
<Bot class="h-4 w-4" />
+ <span
+ v-if="awaitingAiRunCount > 0"
+ class="absolute right-0.5 top-0.5 flex h-3 min-w-3 items-center justify-center rounded-full bg-amber-500 px-0.5 text-[8px] font-semibold leading-none text-white"
+ :aria-label="t('ai.toolbarAwaitingConfirmation', { count: awaitingAiRunCount })"
+ :title="t('ai.toolbarAwaitingConfirmation', { count: awaitingAiRunCount })"
+ >
+ {{ awaitingAiRunCount > 9 ? "9+" : awaitingAiRunCount }}
+ </span>
+ <span v-else-if="activeAiRunCount > 0" class="absolute right-0.5 top-0.5 flex h-3 min-w-3 items-center justify-center rounded-full bg-primary px-0.5 text-[8px] font-semibold leading-none text-primary-foreground">
+ {{ activeAiRunCount > 9 ? "9+" : activeAiRunCount }}
+ </span>
</Button>
</TooltipTrigger>
<TooltipContent>AI</TooltipContent>
diff --git a/apps/desktop/src/composables/useToast.ts b/apps/desktop/src/composables/useToast.ts
index c30eef271f..cca7b3cafb 100644
--- a/apps/desktop/src/composables/useToast.ts
+++ b/apps/desktop/src/composables/useToast.ts
@@ -1,9 +1,12 @@
import { ref, type Ref } from "vue";
+export type ToastAction = { label: string; onClick: () => void };
+
type ToastState = {
message: Ref<string>;
visible: Ref<boolean>;
timer: number;
+ action: Ref<ToastAction | undefined>;
};
declare global {
@@ -16,17 +19,25 @@ const toastState =
message: ref(""),
visible: ref(false),
timer: 0,
+ action: ref<ToastAction | undefined>(undefined),
});
export function useToast() {
- function toast(msg: string, duration = 2000) {
+ function toast(msg: string, duration = 2000, action?: ToastAction) {
toastState.message.value = msg;
+ toastState.action.value = action;
toastState.visible.value = true;
clearTimeout(toastState.timer);
toastState.timer = window.setTimeout(() => {
toastState.visible.value = false;
+ toastState.action.value = undefined;
}, duration);
}
- return { message: toastState.message, visible: toastState.visible, toast };
+ function dismissToast() {
+ toastState.visible.value = false;
+ toastState.action.value = undefined;
+ }
+
+ return { message: toastState.message, visible: toastState.visible, action: toastState.action, toast, dismissToast };
}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b0d975804d..cd8db95ec0 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -2514,6 +2514,44 @@ export default {
welcome: "Tell me what you'd like to query, and I'll write the SQL",
requestFailed: "AI request failed",
requestCancelled: "Request cancelled",
+ backgroundRunCompleted: "AI response completed in the background",
+ backgroundRunNeedsConfirmation: "AI needs your confirmation to continue",
+ recoveredDraftBanner: "A request that was queued before restart was recovered",
+ recoveredDraftHint: "Edit and resend, or remove it.",
+ discardDraft: "Remove draft",
+ runStatusRunning: "Running",
+ runStatusWaitingToStart: "Waiting to start",
+ runStatusAwaitingConfirmation: "Awaiting confirmation",
+ runStatusPendingDraft: "Pending input",
+ runStatusCompleted: "Completed",
+ runStatusFailed: "Failed",
+ runStatusInterrupted: "Interrupted",
+ runStatusCancelled: "Cancelled",
+ runUnread: "New updates in this conversation",
+ closeWithRunsTitle: "AI tasks are still running",
+ closeWithRunsDescription: "Quitting DBX will interrupt {count} running or queued AI task(s). You can close this dialog and let them finish instead.",
+ closeWithRunsQuit: "Quit and interrupt",
+ queueSend: "Queue send",
+ queueSendHint: "A task is still running for this conversation; the message will be sent when it finishes",
+ inputQueued: "Message queued to send after the current task",
+ queuedInputWaiting: "Waiting — {text}",
+ queuedInputPending: "Queued to send — {text}",
+ sendQueuedInput: "Send queued message",
+ queuedInputEdit: "Edit queued message",
+ queuedInputRemove: "Remove queued message",
+ rowQueuedInput: "Queued input",
+ retryRound: "Retry this round",
+ deleteConversation: "Delete conversation",
+ deleteActiveConversationTitle: "Conversation has an active task",
+ deleteActiveConversationDescription: "This conversation still has a task running or waiting. Cancel the task and delete the conversation, or keep it?",
+ cancelTaskAndDelete: "Cancel task and delete conversation",
+ keepConversation: "Keep conversation",
+ awayUpdatesDivider: "Updates while you were away",
+ jumpToLatest: "Jump to latest",
+ openPanel: "Open panel",
+ runRowPhaseTool: "Running {tool}",
+ runRowPhaseThinking: "Analyzing…",
+ toolbarAwaitingConfirmation: "{count} AI task(s) awaiting your confirmation",
newChat: "New Chat",
thinking: "Thinking...",
reasoningProcess: "Thinking process",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index d5c28e91f3..7011e0f000 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -2548,6 +2548,44 @@ export default withEnglishFallback({
welcome: "Dime qué quieres consultar y escribiré el SQL",
requestFailed: "La solicitud de AI falló",
requestCancelled: "Solicitud de AI cancelada",
+ backgroundRunCompleted: "La respuesta de AI se completó en segundo plano",
+ backgroundRunNeedsConfirmation: "AI necesita tu confirmación para continuar",
+ recoveredDraftBanner: "Se recuperó una solicitud que estaba en cola antes del reinicio",
+ recoveredDraftHint: "Puedes editarla y reenviarla, o eliminarla.",
+ discardDraft: "Eliminar borrador",
+ runStatusRunning: "En ejecución",
+ runStatusWaitingToStart: "Esperando para comenzar",
+ runStatusAwaitingConfirmation: "Esperando confirmación",
+ runStatusPendingDraft: "Entrada pendiente",
+ runStatusCompleted: "Completado",
+ runStatusFailed: "Falló",
+ runStatusInterrupted: "Interrumpido",
+ runStatusCancelled: "Cancelado",
+ runUnread: "Hay novedades en esta conversación",
+ closeWithRunsTitle: "Las tareas de AI siguen en ejecución",
+ closeWithRunsDescription: "Salir de DBX interrumpirá {count} tarea(s) de AI en ejecución o en cola. También puedes cerrar este diálogo y dejar que terminen.",
+ closeWithRunsQuit: "Salir e interrumpir",
+ queueSend: "Encolar envío",
+ queueSendHint: "Esta conversación aún tiene una tarea en ejecución; el mensaje se enviará cuando termine",
+ inputQueued: "Mensaje en cola para enviarse después de la tarea actual",
+ queuedInputWaiting: "Esperando — {text}",
+ queuedInputPending: "En cola para enviar — {text}",
+ sendQueuedInput: "Enviar mensaje en cola",
+ queuedInputEdit: "Editar mensaje en cola",
+ queuedInputRemove: "Quitar mensaje en cola",
+ rowQueuedInput: "Entrada en cola",
+ retryRound: "Reintentar esta ronda",
+ deleteConversation: "Eliminar conversación",
+ deleteActiveConversationTitle: "La conversación tiene una tarea activa",
+ deleteActiveConversationDescription: "Esta conversación aún tiene una tarea en ejecución o en espera. ¿Cancelar la tarea y eliminar la conversación, o conservarla?",
+ cancelTaskAndDelete: "Cancelar tarea y eliminar conversación",
+ keepConversation: "Conservar conversación",
+ awayUpdatesDivider: "Novedades mientras no estabas",
+ jumpToLatest: "Ir a lo más reciente",
+ openPanel: "Abrir panel",
+ runRowPhaseTool: "Ejecutando {tool}",
+ runRowPhaseThinking: "Analizando…",
+ toolbarAwaitingConfirmation: "{count} tarea(s) de AI esperando tu confirmación",
newChat: "Nuevo chat",
thinking: "Procesando...",
reasoningProcess: "Proceso de razonamiento",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index cb79d6f676..bf7953ad2a 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -2442,6 +2442,44 @@ export default withEnglishFallback({
welcome: "Dimmi cosa vorresti interrogare e io scriverò il codice SQL",
requestFailed: "Richiesta AI non riuscita",
requestCancelled: "Richiesta AI annullata",
+ backgroundRunCompleted: "La risposta di AI è stata completata in background",
+ backgroundRunNeedsConfirmation: "AI ha bisogno della tua conferma per continuare",
+ recoveredDraftBanner: "È stata recuperata una richiesta in coda prima del riavvio",
+ recoveredDraftHint: "Puoi modificarla e inviarla di nuovo, oppure rimuoverla.",
+ discardDraft: "Rimuovi bozza",
+ runStatusRunning: "In esecuzione",
+ runStatusWaitingToStart: "In attesa di avvio",
+ runStatusAwaitingConfirmation: "In attesa di conferma",
+ runStatusPendingDraft: "Input in attesa",
+ runStatusCompleted: "Completato",
+ runStatusFailed: "Non riuscito",
+ runStatusInterrupted: "Interrotto",
+ runStatusCancelled: "Annullato",
+ runUnread: "Ci sono nuovi aggiornamenti in questa conversazione",
+ closeWithRunsTitle: "Le attività di AI sono ancora in esecuzione",
+ closeWithRunsDescription: "Uscire da DBX interromperà {count} attività di AI in esecuzione o in coda. Puoi anche chiudere questa finestra e lasciarle terminare.",
+ closeWithRunsQuit: "Esci e interrompi",
+ queueSend: "Accoda l'invio",
+ queueSendHint: "Questa conversazione ha ancora un'attività in esecuzione; il messaggio verrà inviato al termine",
+ inputQueued: "Messaggio in coda per l'invio dopo l'attività corrente",
+ queuedInputWaiting: "In attesa — {text}",
+ queuedInputPending: "In coda per l'invio — {text}",
+ sendQueuedInput: "Invia messaggio in coda",
+ queuedInputEdit: "Modifica messaggio in coda",
+ queuedInputRemove: "Rimuovi messaggio in coda",
+ rowQueuedInput: "Input in coda",
+ retryRound: "Riprova questo turno",
+ deleteConversation: "Elimina conversazione",
+ deleteActiveConversationTitle: "La conversazione ha un'attività attiva",
+ deleteActiveConversationDescription: "Questa conversazione ha ancora un'attività in esecuzione o in attesa. Annullare l'attività ed eliminare la conversazione, oppure conservarla?",
+ cancelTaskAndDelete: "Annulla attività ed elimina conversazione",
+ keepConversation: "Conserva conversazione",
+ awayUpdatesDivider: "Aggiornamenti mentre eri via",
+ jumpToLatest: "Vai all'ultimo",
+ openPanel: "Apri pannello",
+ runRowPhaseTool: "Esecuzione di {tool}",
+ runRowPhaseThinking: "Analisi in corso…",
+ toolbarAwaitingConfirmation: "{count} attività di AI in attesa della tua conferma",
newChat: "Nuova Chat",
thinking: "Riflessione...",
reasoningProcess: "Processo di riflessione",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 9b6350b192..eeb10788e7 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -2581,6 +2581,44 @@ export default withEnglishFallback({
welcome: "クエリしたい内容を教えてください。SQLを作成します",
requestFailed: "AIリクエストに失敗しました",
requestCancelled: "AIリクエストがキャンセルされました",
+ backgroundRunCompleted: "AIの応答はバックグラウンドで完了しました",
+ backgroundRunNeedsConfirmation: "続行するにはAIの確認が必要です",
+ recoveredDraftBanner: "再起動前にキューに入っていたリクエストを復元しました",
+ recoveredDraftHint: "編集して再送するか、削除できます。",
+ discardDraft: "下書きを削除",
+ runStatusRunning: "実行中",
+ runStatusWaitingToStart: "開始待ち",
+ runStatusAwaitingConfirmation: "確認待ち",
+ runStatusPendingDraft: "送信待ちの入力",
+ runStatusCompleted: "完了",
+ runStatusFailed: "失敗",
+ runStatusInterrupted: "中断",
+ runStatusCancelled: "キャンセル済み",
+ runUnread: "この会話に新しい更新があります",
+ closeWithRunsTitle: "AIタスクはまだ実行中です",
+ closeWithRunsDescription: "DBXを終了すると、実行中またはキューに入っている{count}件のAIタスクが中断されます。このダイアログを閉じて完了を待つこともできます。",
+ closeWithRunsQuit: "終了して中断",
+ queueSend: "送信をキューに入れる",
+ queueSendHint: "この会話ではまだタスクが実行中のため、完了後にメッセージが送信されます",
+ inputQueued: "現在のタスク完了後に送信されるようキューに入れました",
+ queuedInputWaiting: "待機中 — {text}",
+ queuedInputPending: "送信待ち — {text}",
+ sendQueuedInput: "キュー済みメッセージを送信",
+ queuedInputEdit: "キュー済みメッセージを編集",
+ queuedInputRemove: "キュー済みメッセージを削除",
+ rowQueuedInput: "キュー済みの入力",
+ retryRound: "このラウンドを再試行",
+ deleteConversation: "会話を削除",
+ deleteActiveConversationTitle: "会話にアクティブなタスクがあります",
+ deleteActiveConversationDescription: "この会話には実行中または待機中のタスクがあります。タスクをキャンセルして会話を削除しますか、それとも保持しますか?",
+ cancelTaskAndDelete: "タスクをキャンセルして会話を削除",
+ keepConversation: "会話を保持",
+ awayUpdatesDivider: "離れていた間の更新",
+ jumpToLatest: "最新へ移動",
+ openPanel: "パネルを開く",
+ runRowPhaseTool: "{tool}を実行中",
+ runRowPhaseThinking: "分析中…",
+ toolbarAwaitingConfirmation: "{count}件のAIタスクが確認を待っています",
newChat: "新しいチャット",
thinking: "思考中...",
reasoningProcess: "思考プロセス",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index c5a4cd3241..3b65592839 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -2339,6 +2339,44 @@ export default withEnglishFallback({
welcome: "쿼리할 내용을 말씀해 주세요. SQL을 작성해 드릴게요",
requestFailed: "AI 요청 실패",
requestCancelled: "AI 요청이 취소되었습니다",
+ backgroundRunCompleted: "AI 응답이 백그라운드에서 완료되었습니다",
+ backgroundRunNeedsConfirmation: "계속하려면 AI 확인이 필요합니다",
+ recoveredDraftBanner: "재시작 전에 대기열에 있던 요청이 복구되었습니다",
+ recoveredDraftHint: "편집 후 다시 보내거나 삭제할 수 있습니다.",
+ discardDraft: "초안 삭제",
+ runStatusRunning: "실행 중",
+ runStatusWaitingToStart: "시작 대기 중",
+ runStatusAwaitingConfirmation: "확인 대기 중",
+ runStatusPendingDraft: "전송 대기 입력",
+ runStatusCompleted: "완료",
+ runStatusFailed: "실패",
+ runStatusInterrupted: "중단됨",
+ runStatusCancelled: "취소됨",
+ runUnread: "이 대화에 새 업데이트가 있습니다",
+ closeWithRunsTitle: "AI 작업이 아직 실행 중입니다",
+ closeWithRunsDescription: "DBX를 종료하면 실행 중이거나 대기 중인 AI 작업 {count}개가 중단됩니다. 이 대화 상자를 닫고 완료될 때까지 기다릴 수도 있습니다.",
+ closeWithRunsQuit: "종료하고 중단",
+ queueSend: "보내기 대기열에 추가",
+ queueSendHint: "이 대화에는 아직 실행 중인 작업이 있어 메시지가 완료 후 전송됩니다",
+ inputQueued: "현재 작업 완료 후 보내도록 메시지가 대기열에 추가되었습니다",
+ queuedInputWaiting: "대기 중 — {text}",
+ queuedInputPending: "전송 대기 중 — {text}",
+ sendQueuedInput: "대기 메시지 보내기",
+ queuedInputEdit: "대기 메시지 편집",
+ queuedInputRemove: "대기 메시지 제거",
+ rowQueuedInput: "대기 중인 입력",
+ retryRound: "이번 라운드 다시 시도",
+ deleteConversation: "대화 삭제",
+ deleteActiveConversationTitle: "대화에 활성 작업이 있습니다",
+ deleteActiveConversationDescription: "이 대화에는 아직 실행 중이거나 대기 중인 작업이 있습니다. 작업을 취소하고 대화를 삭제할까요, 아니면 유지할까요?",
+ cancelTaskAndDelete: "작업 취소하고 대화 삭제",
+ keepConversation: "대화 유지",
+ awayUpdatesDivider: "자리를 비운 동안의 업데이트",
+ jumpToLatest: "최신으로 이동",
+ openPanel: "패널 열기",
+ runRowPhaseTool: "{tool} 실행 중",
+ runRowPhaseThinking: "분석 중…",
+ toolbarAwaitingConfirmation: "확인을 기다리는 AI 작업 {count}개",
newChat: "새 채팅",
thinking: "생각하는 중...",
reasoningProcess: "사고 과정",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 7255a3d39b..9c0c6fb9f0 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -2550,6 +2550,44 @@ export default withEnglishFallback({
welcome: "Diga o que você gostaria de consultar e eu escreverei o SQL",
requestFailed: "Falha na solicitação de AI",
requestCancelled: "Solicitação de AI cancelada",
+ backgroundRunCompleted: "A resposta de AI foi concluída em segundo plano",
+ backgroundRunNeedsConfirmation: "A AI precisa da sua confirmação para continuar",
+ recoveredDraftBanner: "Foi recuperada uma solicitação que estava na fila antes da reinicialização",
+ recoveredDraftHint: "Você pode editá-la e reenviá-la, ou removê-la.",
+ discardDraft: "Remover rascunho",
+ runStatusRunning: "Em execução",
+ runStatusWaitingToStart: "Aguardando para começar",
+ runStatusAwaitingConfirmation: "Aguardando confirmação",
+ runStatusPendingDraft: "Entrada pendente",
+ runStatusCompleted: "Concluído",
+ runStatusFailed: "Falhou",
+ runStatusInterrupted: "Interrompido",
+ runStatusCancelled: "Cancelado",
+ runUnread: "Há novas atualizações nesta conversa",
+ closeWithRunsTitle: "As tarefas de AI ainda estão em execução",
+ closeWithRunsDescription: "Sair do DBX interromperá {count} tarefa(s) de AI em execução ou na fila. Você também pode fechar esta caixa de diálogo e deixá-las terminar.",
+ closeWithRunsQuit: "Sair e interromper",
+ queueSend: "Enfileirar envio",
+ queueSendHint: "Esta conversa ainda tem uma tarefa em execução; a mensagem será enviada quando ela terminar",
+ inputQueued: "Mensagem enfileirada para enviar após a tarefa atual",
+ queuedInputWaiting: "Aguardando — {text}",
+ queuedInputPending: "Na fila para enviar — {text}",
+ sendQueuedInput: "Enviar mensagem na fila",
+ queuedInputEdit: "Editar mensagem na fila",
+ queuedInputRemove: "Remover mensagem na fila",
+ rowQueuedInput: "Entrada na fila",
+ retryRound: "Repetir esta rodada",
+ deleteConversation: "Excluir conversa",
+ deleteActiveConversationTitle: "A conversa tem uma tarefa ativa",
+ deleteActiveConversationDescription: "Esta conversa ainda tem uma tarefa em execução ou aguardando. Cancelar a tarefa e excluir a conversa, ou mantê-la?",
+ cancelTaskAndDelete: "Cancelar tarefa e excluir conversa",
+ keepConversation: "Manter conversa",
+ awayUpdatesDivider: "Atualizações enquanto você esteve fora",
+ jumpToLatest: "Ir para o mais recente",
+ openPanel: "Abrir painel",
+ runRowPhaseTool: "Executando {tool}",
+ runRowPhaseThinking: "Analisando…",
+ toolbarAwaitingConfirmation: "{count} tarefa(s) de AI aguardando sua confirmação",
newChat: "Nova Conversa",
thinking: "Pensando...",
reasoningProcess: "Processo de raciocínio",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index e36581f9d7..682e4ff055 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -2438,6 +2438,44 @@ export default withEnglishFallback({
welcome: "聊聊你想查什么,我来写 SQL",
requestFailed: "AI 请求失败",
requestCancelled: "请求已取消",
+ backgroundRunCompleted: "AI 已在后台完成回复",
+ backgroundRunNeedsConfirmation: "AI 需要你的确认才能继续",
+ recoveredDraftBanner: "已恢复上次排队发送的请求",
+ recoveredDraftHint: "可编辑后重新发送,或删除移除。",
+ discardDraft: "删除草稿",
+ runStatusRunning: "运行中",
+ runStatusWaitingToStart: "等待开始",
+ runStatusAwaitingConfirmation: "等待写入确认",
+ runStatusPendingDraft: "待发输入",
+ runStatusCompleted: "已完成",
+ runStatusFailed: "失败",
+ runStatusInterrupted: "已中断",
+ runStatusCancelled: "已取消",
+ runUnread: "此会话有新的更新",
+ closeWithRunsTitle: "AI 任务仍在运行",
+ closeWithRunsDescription: "退出 DBX 会中断 {count} 个正在运行或排队的 AI 任务。你也可以取消退出并等待任务完成。",
+ closeWithRunsQuit: "退出并中断任务",
+ queueSend: "排队发送",
+ queueSendHint: "当前会话还有任务在运行,发送的消息将在任务完成后自动发出",
+ inputQueued: "已排队,当前任务完成后自动发送",
+ queuedInputWaiting: "等待中 — {text}",
+ queuedInputPending: "已排队待发送 — {text}",
+ sendQueuedInput: "发送排队消息",
+ queuedInputEdit: "编辑排队消息",
+ queuedInputRemove: "移除排队消息",
+ rowQueuedInput: "有排队输入",
+ retryRound: "重试本轮",
+ deleteConversation: "删除会话",
+ deleteActiveConversationTitle: "会话中还有活动任务",
+ deleteActiveConversationDescription: "该会话仍有任务在运行或等待。是取消任务并删除会话,还是保留会话?",
+ cancelTaskAndDelete: "取消任务并删除会话",
+ keepConversation: "保留会话",
+ awayUpdatesDivider: "离开期间的更新",
+ jumpToLatest: "跳到最新",
+ openPanel: "打开面板",
+ runRowPhaseTool: "正在执行 {tool}",
+ runRowPhaseThinking: "正在分析…",
+ toolbarAwaitingConfirmation: "{count} 个 AI 任务等待你的确认",
newChat: "新对话",
thinking: "思考中...",
reasoningProcess: "思考过程",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 9fcdd13fd6..4ea4bf5f21 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -2442,6 +2442,44 @@ export default withEnglishFallback({
welcome: "告訴我你想查詢什麼,我會寫出 SQL",
requestFailed: "AI 請求失敗",
requestCancelled: "AI 請求已取消",
+ backgroundRunCompleted: "AI 已在背景完成回覆",
+ backgroundRunNeedsConfirmation: "AI 需要你的確認才能繼續",
+ recoveredDraftBanner: "已還原上次排隊傳送的請求",
+ recoveredDraftHint: "可編輯後重新傳送,或刪除移除。",
+ discardDraft: "刪除草稿",
+ runStatusRunning: "執行中",
+ runStatusWaitingToStart: "等待開始",
+ runStatusAwaitingConfirmation: "等待寫入確認",
+ runStatusPendingDraft: "待傳輸輸入",
+ runStatusCompleted: "已完成",
+ runStatusFailed: "失敗",
+ runStatusInterrupted: "已中斷",
+ runStatusCancelled: "已取消",
+ runUnread: "此會話有新的更新",
+ closeWithRunsTitle: "AI 任務仍在執行",
+ closeWithRunsDescription: "結束 DBX 會中斷 {count} 個正在執行或排隊的 AI 任務。你也可以取消結束並等待任務完成。",
+ closeWithRunsQuit: "結束並中斷任務",
+ queueSend: "排隊發送",
+ queueSendHint: "目前會話仍有任務在執行,發送的訊息將在任務完成後自動送出",
+ inputQueued: "已排隊,目前任務完成後自動發送",
+ queuedInputWaiting: "等待中 — {text}",
+ queuedInputPending: "已排隊待發送 — {text}",
+ sendQueuedInput: "發送排隊訊息",
+ queuedInputEdit: "編輯排隊訊息",
+ queuedInputRemove: "移除排隊訊息",
+ rowQueuedInput: "有排隊輸入",
+ retryRound: "重試本輪",
+ deleteConversation: "刪除會話",
+ deleteActiveConversationTitle: "會話中還有執行中任務",
+ deleteActiveConversationDescription: "此會話仍有任務在執行或等待。要取消任務並刪除會話,還是保留會話?",
+ cancelTaskAndDelete: "取消任務並刪除會話",
+ keepConversation: "保留會話",
+ awayUpdatesDivider: "離開期間的更新",
+ jumpToLatest: "跳到最新",
+ openPanel: "開啟面板",
+ runRowPhaseTool: "正在執行 {tool}",
+ runRowPhaseThinking: "正在分析…",
+ toolbarAwaitingConfirmation: "{count} 個 AI 任務等待你的確認",
newChat: "新對話",
thinking: "思考中……",
reasoningProcess: "思考過程",
diff --git a/apps/desktop/src/lib/__tests__/windowsInstallerTemplate.spec.ts b/apps/desktop/src/lib/__tests__/windowsInstallerTemplate.spec.ts
index 605b96b207..4ee5752f00 100644
--- a/apps/desktop/src/lib/__tests__/windowsInstallerTemplate.spec.ts
+++ b/apps/desktop/src/lib/__tests__/windowsInstallerTemplate.spec.ts
@@ -119,8 +119,10 @@ describe("Windows 7 fixed WebView2 runtime bundle", () => {
it("passes the configured fixed-runtime folder to WebView2 discovery and creation", () => {
expect(workspaceCargoToml).toContain('wry = { path = "vendor/wry" }');
expect(wryWebView2Source).toContain('std::env::var_os("WEBVIEW2_BROWSER_EXECUTABLE_FOLDER")');
- expect(wryWebView2Source).toContain(`CreateCoreWebView2EnvironmentWithOptions(
- browser_executable_folder_ptr,`);
+ // The webview2_com crate indents this with 8 spaces; assert on the two
+ // adjacent lines loosely so a formatter's re-indent doesn't break the test.
+ expect(wryWebView2Source).toContain("CreateCoreWebView2EnvironmentWithOptions(");
+ expect(wryWebView2Source).toContain("browser_executable_folder_ptr,");
expect(wryWebView2Source).toContain("GetAvailableCoreWebView2BrowserVersionString(browser_executable_folder_ptr, &mut versioninfo)");
});
diff --git a/apps/desktop/src/lib/ai/__tests__/aiRuntimeStrategy.spec.ts b/apps/desktop/src/lib/ai/__tests__/aiRuntimeStrategy.spec.ts
new file mode 100644
index 0000000000..aa071c408d
--- /dev/null
+++ b/apps/desktop/src/lib/ai/__tests__/aiRuntimeStrategy.spec.ts
@@ -0,0 +1,206 @@
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ acquireDesktopAiRunSlot,
+ activeDesktopAiRuns,
+ blockingDesktopAiRunsForQuit,
+ bumpDesktopAiRunSeq,
+ cancelQueuedDesktopAiRun,
+ desktopAiRun,
+ finishDesktopAiRun,
+ hasActiveDesktopAiRun,
+ isTerminalDesktopAiRunStatus,
+ registerDesktopAiRun,
+ releaseDesktopAiRunSlot,
+ resetDesktopAiRunRegistryForTests,
+} from "@/lib/ai/desktopAiRunRegistry";
+import { resolveAiRuntimeStrategy, supportsBackgroundAiRuns } from "@/lib/ai/aiRuntimeStrategy";
+
+describe("AI runtime platform strategy", () => {
+ afterEach(() => resetDesktopAiRunRegistryForTests());
+
+ it("enables detached runs only for the Tauri desktop runtime", () => {
+ expect(resolveAiRuntimeStrategy(true)).toBe("desktop-background");
+ expect(supportsBackgroundAiRuns("desktop-background")).toBe(true);
+ expect(resolveAiRuntimeStrategy(false)).toBe("web-cancel-on-navigation");
+ expect(supportsBackgroundAiRuns("web-cancel-on-navigation")).toBe(false);
+ });
+
+ it("keeps a desktop run addressable by conversation until terminal", () => {
+ const run = registerDesktopAiRun({
+ runId: "run-1",
+ conversationId: "conversation-1",
+ sessionIds: ["session-1"],
+ currentSessionId: "session-1",
+ status: "running",
+ messages: [{ content: "partial" }],
+ assistantMessageIndex: 0,
+ connectionId: "connection-1",
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+
+ expect(desktopAiRun("conversation-1")).toBe(run);
+ expect(activeDesktopAiRuns()).toEqual([run]);
+
+ finishDesktopAiRun(run, "completed");
+ expect(desktopAiRun("conversation-1")?.status).toBe("completed");
+ expect(activeDesktopAiRuns()).toEqual([]);
+ });
+
+ it("admits at most three runs and lets a queued run be cancelled", async () => {
+ const makeRun = (index: number) =>
+ registerDesktopAiRun({
+ runId: `run-${index}`,
+ conversationId: `conversation-${index}`,
+ sessionIds: [],
+ currentSessionId: "",
+ status: "preparing" as const,
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: `connection-${index}`,
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+
+ const runs = [1, 2, 3, 4].map(makeRun);
+ await Promise.all(runs.slice(0, 3).map(acquireDesktopAiRunSlot));
+ const fourthAdmission = acquireDesktopAiRunSlot(runs[3]);
+ expect(runs[3].status).toBe("queued");
+ expect(cancelQueuedDesktopAiRun(runs[3])).toBe(true);
+ await expect(fourthAdmission).resolves.toBe(false);
+
+ runs.slice(0, 3).forEach((run) => releaseDesktopAiRunSlot(run.runId));
+ });
+
+ it("keeps a recovered pending-input run addressable without consuming a slot or blocking quit", async () => {
+ const run = registerDesktopAiRun({
+ runId: "run-recovered",
+ conversationId: "conversation-1",
+ sessionIds: [],
+ currentSessionId: "",
+ status: "pending_recoverable",
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: "connection-1",
+ connectionName: "local",
+ database: "db",
+ pendingInput: "select * from orders",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+
+ // Addressable (so the row can render "pending input"), but neither an
+ // active run nor a quit-blocking one.
+ expect(desktopAiRun("conversation-1")).toBe(run);
+ expect(activeDesktopAiRuns()).toEqual([]);
+ expect(blockingDesktopAiRunsForQuit()).toEqual([]);
+
+ // It also does not consume a global concurrency slot: a fresh preparing run
+ // is admitted immediately even though the recovered run is registered.
+ const fresh = registerDesktopAiRun({
+ runId: "run-fresh",
+ conversationId: "conversation-2",
+ sessionIds: [],
+ currentSessionId: "",
+ status: "preparing",
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: "connection-2",
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+ const admission = acquireDesktopAiRunSlot(fresh);
+ expect(fresh.status).toBe("preparing");
+ await expect(admission).resolves.toBe(true);
+ releaseDesktopAiRunSlot(fresh.runId);
+ });
+
+ it("assigns strictly increasing event seqs that persist on the run", () => {
+ const run = registerDesktopAiRun({
+ runId: "run-seq",
+ conversationId: "conversation-1",
+ sessionIds: ["session-1", "session-2"],
+ currentSessionId: "session-2",
+ status: "running",
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: "connection-1",
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+
+ // Parent PRD §8: seq starts at 1 and strictly increases across sessions.
+ expect(bumpDesktopAiRunSeq(run)).toBe(1);
+ expect(bumpDesktopAiRunSeq(run)).toBe(2);
+ expect(run.maxSeq).toBe(2);
+
+ // A recovered run with a persisted maxSeq continues from there.
+ run.maxSeq = 40;
+ expect(bumpDesktopAiRunSeq(run)).toBe(41);
+ expect(desktopAiRun("conversation-1")?.maxSeq).toBe(41);
+ });
+
+ it("treats every non-terminal status as active for queue-send, including pending_recoverable", () => {
+ const statuses = ["preparing", "queued", "running", "awaiting_write_confirmation", "pending_recoverable"] as const;
+ for (const status of statuses) {
+ registerDesktopAiRun({
+ runId: `run-${status}`,
+ conversationId: `conversation-${status}`,
+ sessionIds: [],
+ currentSessionId: "",
+ status,
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: "connection-1",
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+ expect(hasActiveDesktopAiRun(`conversation-${status}`)).toBe(true);
+ }
+ for (const status of ["completed", "failed", "cancelled", "interrupted"] as const) {
+ const run = registerDesktopAiRun({
+ runId: `run-${status}`,
+ conversationId: `conversation-${status}`,
+ sessionIds: [],
+ currentSessionId: "",
+ status,
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: "connection-1",
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ });
+ expect(hasActiveDesktopAiRun(`conversation-${status}`)).toBe(false);
+ finishDesktopAiRun(run, "completed");
+ }
+ });
+
+ it("classifies terminal statuses for the stop-wait logic (isTerminalDesktopAiRunStatus)", () => {
+ for (const status of ["completed", "failed", "cancelled"] as const) {
+ expect(isTerminalDesktopAiRunStatus(status)).toBe(true);
+ }
+ // `interrupted` is a persisted-row-only pseudo status, never a runtime one.
+ for (const status of ["preparing", "queued", "running", "awaiting_write_confirmation", "pending_recoverable"] as const) {
+ expect(isTerminalDesktopAiRunStatus(status)).toBe(false);
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/ai/__tests__/desktopAiRunSnapshotScheduler.spec.ts b/apps/desktop/src/lib/ai/__tests__/desktopAiRunSnapshotScheduler.spec.ts
new file mode 100644
index 0000000000..07407eacf4
--- /dev/null
+++ b/apps/desktop/src/lib/ai/__tests__/desktopAiRunSnapshotScheduler.spec.ts
@@ -0,0 +1,171 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createDesktopAiRunSnapshotScheduler } from "@/lib/ai/desktopAiRunSnapshotScheduler";
+import type { DesktopAiRunRuntime } from "@/lib/ai/desktopAiRunRegistry";
+
+function makeRun(overrides: Partial<DesktopAiRunRuntime> = {}): DesktopAiRunRuntime {
+ return {
+ runId: "run-1",
+ conversationId: "conversation-1",
+ sessionIds: [],
+ currentSessionId: "",
+ status: "running",
+ messages: [],
+ assistantMessageIndex: -1,
+ connectionId: "connection-1",
+ connectionName: "local",
+ database: "db",
+ createdAt: "2026-08-25T00:00:00.000Z",
+ updatedAt: "2026-08-25T00:00:00.000Z",
+ cancelRequested: false,
+ ...overrides,
+ };
+}
+
+// Finding 1 regression coverage: detached streaming deltas used to live only
+// in memory (a crash/quit mid-response lost everything after the last
+// pre-stream snapshot). The scheduler persists snapshots incrementally from
+// the delta flush path - throttled to keep writes cheap, serialized per run so
+// a slow write can never let an older snapshot overwrite a newer one.
+describe("desktop AI run snapshot scheduler", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("throttles streaming flushes to one durable save per interval, capturing state at fire time", async () => {
+ const persistedContentLengths: number[] = [];
+ const run = makeRun();
+ const scheduler = createDesktopAiRunSnapshotScheduler({
+ persist: async () => {
+ persistedContentLengths.push(run.messages.length);
+ },
+ intervalMs: 2000,
+ });
+
+ run.messages.push({ content: "a" });
+ scheduler.schedule(run);
+ // Further flushes inside the window must not stack extra timers.
+ run.messages.push({ content: "b" });
+ scheduler.schedule(run);
+ run.messages.push({ content: "c" });
+ scheduler.schedule(run);
+
+ await vi.advanceTimersByTimeAsync(1999);
+ expect(persistedContentLengths).toEqual([]);
+ await vi.advanceTimersByTimeAsync(1);
+ // The save reads the run's state when the timer fires (3 messages), not at
+ // schedule time - so a crash after the first flush still persists the tail.
+ expect(persistedContentLengths).toEqual([3]);
+ });
+
+ it("re-arms after each save so a long stream keeps snapshotting", async () => {
+ const persisted: number[] = [];
+ const run = makeRun();
+ const scheduler = createDesktopAiRunSnapshotScheduler({
+ persist: async () => {
+ persisted.push(run.messages.length);
+ },
+ intervalMs: 2000,
+ });
+
+ scheduler.schedule(run);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(persisted).toEqual([0]);
+ run.messages.push({ content: "late" });
+ scheduler.schedule(run);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(persisted).toEqual([0, 1]);
+ });
+
+ it("serializes saves so an older in-flight snapshot can never overwrite a newer one", async () => {
+ const callOrder: number[] = [];
+ let resolveFirst!: () => void;
+ const persist = vi
+ .fn()
+ .mockImplementationOnce(() => {
+ callOrder.push(1);
+ return new Promise<void>((resolve) => {
+ resolveFirst = resolve;
+ });
+ })
+ .mockImplementationOnce(() => {
+ callOrder.push(2);
+ return Promise.resolve();
+ });
+ const scheduler = createDesktopAiRunSnapshotScheduler({ persist, intervalMs: 2000 });
+ const run = makeRun();
+
+ const first = scheduler.save(run);
+ run.status = "completed";
+ const second = scheduler.save(run);
+
+ // The newer save must not start (let alone finish) before the older one
+ // resolves - saves are INSERT OR REPLACEs keyed by the same run row.
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(persist).toHaveBeenCalledTimes(1);
+ resolveFirst();
+ await Promise.all([first, second]);
+ expect(callOrder).toEqual([1, 2]);
+ });
+
+ it("skips a queued save if the run is deleted while a prior write is still in flight", async () => {
+ // Reviewed finding (delete-resurrection race): a save() that was enqueued
+ // behind a slow in-flight write was NOT re-checked for discardOnFinish at
+ // execution time. The delete path commits its DELETE first, so the queued
+ // save firing afterwards recreated the just-deleted conversation via
+ // INSERT OR REPLACE. The discard marker must be checked at the actual
+ // execution point, not just at enqueue time.
+ const persist = vi.fn(async () => {});
+ let resolveFirst!: () => void;
+ persist.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveFirst = resolve;
+ }),
+ );
+ const scheduler = createDesktopAiRunSnapshotScheduler({ persist, intervalMs: 2000 });
+ const run = makeRun();
+
+ // First save: flush the microtask so the write actually starts (and blocks
+ // on the pending mock) BEFORE the second is enqueued behind it.
+ const first = scheduler.save(run);
+ await Promise.resolve();
+ const second = scheduler.save(run);
+ // The user deletes the conversation while the first write is still running.
+ run.discardOnFinish = true;
+ resolveFirst();
+
+ await Promise.all([first, second]);
+ // Only the already-executing first write persisted; the queued one skipped.
+ expect(persist).toHaveBeenCalledTimes(1);
+ });
+
+ it("never persists a run the user deleted (discardOnFinish), even through the ordered path", async () => {
+ const persist = vi.fn(async () => {});
+ const scheduler = createDesktopAiRunSnapshotScheduler({ persist, intervalMs: 2000 });
+
+ scheduler.schedule(makeRun({ discardOnFinish: true }));
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(persist).not.toHaveBeenCalled();
+
+ // A run deleted after scheduling must be skipped when the timer fires.
+ const run = makeRun();
+ scheduler.schedule(run);
+ run.discardOnFinish = true;
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(persist).not.toHaveBeenCalled();
+
+ // save() on a discarded run is also a no-op (delete-resurrection guard).
+ await scheduler.save(makeRun({ discardOnFinish: true }));
+ expect(persist).not.toHaveBeenCalled();
+ });
+
+ it("cancel() drops a pending throttled save so a late fire cannot write stale state", async () => {
+ const persist = vi.fn(async () => {});
+ const scheduler = createDesktopAiRunSnapshotScheduler({ persist, intervalMs: 2000 });
+
+ const run = makeRun();
+ scheduler.schedule(run);
+ scheduler.cancel(run.runId);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(persist).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/lib/ai/aiRuntimeStrategy.ts b/apps/desktop/src/lib/ai/aiRuntimeStrategy.ts
new file mode 100644
index 0000000000..475ef11a38
--- /dev/null
+++ b/apps/desktop/src/lib/ai/aiRuntimeStrategy.ts
@@ -0,0 +1,15 @@
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+
+export type AiRuntimeStrategy = "desktop-background" | "web-cancel-on-navigation";
+
+/**
+ * Keep the platform boundary in one place. Desktop owns a process-wide Tauri
+ * event stream, while Web's POST/SSE response is still tied to the page request.
+ */
+export function resolveAiRuntimeStrategy(tauriRuntime = isTauriRuntime()): AiRuntimeStrategy {
+ return tauriRuntime ? "desktop-background" : "web-cancel-on-navigation";
+}
+
+export function supportsBackgroundAiRuns(strategy = resolveAiRuntimeStrategy()): boolean {
+ return strategy === "desktop-background";
+}
diff --git a/apps/desktop/src/lib/ai/desktopAiRunRegistry.ts b/apps/desktop/src/lib/ai/desktopAiRunRegistry.ts
new file mode 100644
index 0000000000..c02036ec03
--- /dev/null
+++ b/apps/desktop/src/lib/ai/desktopAiRunRegistry.ts
@@ -0,0 +1,159 @@
+import { shallowReactive } from "vue";
+
+export type DesktopAiRunStatus = "preparing" | "queued" | "running" | "awaiting_write_confirmation" | "completed" | "failed" | "cancelled" | "pending_recoverable";
+
+export type DesktopAiRunFifoCategory = "normal_send" | "write_confirmation_resume";
+
+const DESKTOP_AI_CONCURRENCY_LIMIT = 3;
+
+export interface DesktopAiRunRuntime<TMessage = unknown> {
+ runId: string;
+ conversationId: string;
+ sessionIds: string[];
+ currentSessionId: string;
+ status: DesktopAiRunStatus;
+ messages: TMessage[];
+ assistantMessageIndex: number;
+ connectionId: string;
+ connectionName: string;
+ database: string;
+ schema?: string;
+ pendingConfirmation?: unknown;
+ /** Queue category of a global-FIFO item, persisted so restart recovery can
+ * tell a normal send (→ editable pending input) from an accepted
+ * write-confirmation resume (→ back to awaiting confirmation). */
+ fifoCategory?: DesktopAiRunFifoCategory;
+ /** User input text carried by a normal-send FIFO item, recovered after
+ * restart as an editable, unsent pending draft. */
+ pendingInput?: string;
+ /** Highest event `seq` assigned to this run, across all its sessions (parent
+ * PRD §8). Strictly increasing from 1; persisted with the run. */
+ maxSeq?: number;
+ /** True when the user rejected the write-confirmation card for this run. A
+ * run cancelled on this path must NOT auto-send the conversation's queued
+ * input (parent PRD §5). In-memory only — never serialized. */
+ pendingConfirmationRejected?: boolean;
+ createdAt: string;
+ updatedAt: string;
+ cancelRequested: boolean;
+ discardOnFinish?: boolean;
+ flushPending?: () => void;
+ /** Resolved by the owning send() pipeline once it has fully settled (its
+ * finally block, or a pre-stream early return). A stop request waits on this
+ * signal rather than finalizing the run itself, so a cancellation-pending
+ * run stays visible - and keeps owning its concurrency slot - until the
+ * real terminal event (or a bounded force-abandon). Runtime-only - never
+ * serialized. */
+ settled?: Promise<void>;
+}
+
+// This registry deliberately lives outside AiAssistant.vue. Closing the panel
+// unmounts its view in some layouts, but a Desktop run remains addressable until
+// it reaches a terminal state. Web never registers runs here.
+const runsByConversation = shallowReactive(new Map<string, DesktopAiRunRuntime>());
+const admittedRunIds = new Set<string>();
+const admissionQueue: Array<{ run: DesktopAiRunRuntime; resolve: (admitted: boolean) => void }> = [];
+
+export function registerDesktopAiRun<TMessage>(run: DesktopAiRunRuntime<TMessage>): DesktopAiRunRuntime<TMessage> {
+ runsByConversation.set(run.conversationId, run as DesktopAiRunRuntime);
+ return run;
+}
+
+export function desktopAiRun<TMessage = unknown>(conversationId: string): DesktopAiRunRuntime<TMessage> | undefined {
+ return runsByConversation.get(conversationId) as DesktopAiRunRuntime<TMessage> | undefined;
+}
+
+export function updateDesktopAiRun(run: DesktopAiRunRuntime, patch: Partial<DesktopAiRunRuntime>): void {
+ Object.assign(run, patch, { updatedAt: new Date().toISOString() });
+ // Values are intentionally shallow (message arrays can be large). Re-setting
+ // the entry invalidates count/badge computations when status changes.
+ runsByConversation.set(run.conversationId, run);
+}
+
+export function finishDesktopAiRun(run: DesktopAiRunRuntime, status: Extract<DesktopAiRunStatus, "completed" | "failed" | "cancelled">): void {
+ updateDesktopAiRun(run, { status, currentSessionId: "", flushPending: undefined, pendingConfirmation: undefined });
+}
+
+export function acquireDesktopAiRunSlot(run: DesktopAiRunRuntime): Promise<boolean> {
+ if (admittedRunIds.has(run.runId)) return Promise.resolve(true);
+ if (admittedRunIds.size < DESKTOP_AI_CONCURRENCY_LIMIT) {
+ admittedRunIds.add(run.runId);
+ return Promise.resolve(true);
+ }
+ updateDesktopAiRun(run, { status: "queued" });
+ return new Promise((resolve) => admissionQueue.push({ run, resolve }));
+}
+
+export function releaseDesktopAiRunSlot(runId: string): void {
+ if (!admittedRunIds.delete(runId)) return;
+ while (admissionQueue.length > 0 && admittedRunIds.size < DESKTOP_AI_CONCURRENCY_LIMIT) {
+ const next = admissionQueue.shift()!;
+ if (next.run.cancelRequested || next.run.status === "cancelled") {
+ next.resolve(false);
+ continue;
+ }
+ admittedRunIds.add(next.run.runId);
+ updateDesktopAiRun(next.run, { status: "preparing" });
+ next.resolve(true);
+ }
+}
+
+export function cancelQueuedDesktopAiRun(run: DesktopAiRunRuntime): boolean {
+ const index = admissionQueue.findIndex((entry) => entry.run === run);
+ if (index < 0) return false;
+ const [entry] = admissionQueue.splice(index, 1);
+ run.cancelRequested = true;
+ finishDesktopAiRun(run, "cancelled");
+ entry.resolve(false);
+ return true;
+}
+
+export function activeDesktopAiRuns(): DesktopAiRunRuntime[] {
+ return [...runsByConversation.values()].filter((run) => run.status === "preparing" || run.status === "queued" || run.status === "running" || run.status === "awaiting_write_confirmation");
+}
+
+/** Terminal statuses: the run has fully settled and no longer blocks the
+ * conversation, the quit prompt, or a concurrency slot. `interrupted` is a
+ * persisted-row-only pseudo status (never a runtime status) and is excluded
+ * here for that reason. */
+export function isTerminalDesktopAiRunStatus(status: DesktopAiRunStatus): boolean {
+ return status === "completed" || status === "failed" || status === "cancelled";
+}
+
+/** Statuses that block queue-send/auto-send: the conversation already owns a
+ * run the queued input must wait behind (parent PRD §5). */
+export function hasActiveDesktopAiRun(conversationId: string): boolean {
+ const run = runsByConversation.get(conversationId);
+ if (!run) return false;
+ return run.status === "preparing" || run.status === "queued" || run.status === "running" || run.status === "awaiting_write_confirmation" || run.status === "pending_recoverable";
+}
+
+export function blockingDesktopAiRunsForQuit(): DesktopAiRunRuntime[] {
+ return [...runsByConversation.values()].filter((run) => run.status === "preparing" || run.status === "queued" || run.status === "running");
+}
+
+/**
+ * Advances a run's event `seq` (parent PRD §8). Every agent event for the run —
+ * across all its sessions — takes the next integer, strictly increasing from 1.
+ * Returns the new seq so the caller can record it as the last-processed anchor.
+ */
+export function bumpDesktopAiRunSeq(run: DesktopAiRunRuntime): number {
+ const next = (run.maxSeq ?? 0) + 1;
+ run.maxSeq = next;
+ runsByConversation.set(run.conversationId, run);
+ return next;
+}
+
+export function removeDesktopAiRun(conversationId: string): void {
+ runsByConversation.delete(conversationId);
+}
+
+export function retireDesktopAiRun(run: DesktopAiRunRuntime): void {
+ if (runsByConversation.get(run.conversationId) === run) runsByConversation.delete(run.conversationId);
+}
+
+export function resetDesktopAiRunRegistryForTests(): void {
+ runsByConversation.clear();
+ admittedRunIds.clear();
+ while (admissionQueue.length) admissionQueue.shift()!.resolve(false);
+}
diff --git a/apps/desktop/src/lib/ai/desktopAiRunSnapshotScheduler.ts b/apps/desktop/src/lib/ai/desktopAiRunSnapshotScheduler.ts
new file mode 100644
index 0000000000..a98bf788b2
--- /dev/null
+++ b/apps/desktop/src/lib/ai/desktopAiRunSnapshotScheduler.ts
@@ -0,0 +1,83 @@
+import type { DesktopAiRunRuntime } from "@/lib/ai/desktopAiRunRegistry";
+
+export interface DesktopAiRunSnapshotSchedulerOptions<TMessage> {
+ /** Durable save for one run. Runs while the previous save for the same run
+ * is still in flight are deferred, so call order equals write order.
+ * Rejections are swallowed by the scheduler - a failed save must never
+ * break the chain for the saves behind it. */
+ persist: (run: DesktopAiRunRuntime<TMessage>) => Promise<void>;
+ /** Minimum spacing between throttled saves for one run. Bounds how much
+ * streamed output a crash/quit can lose relative to the last durable
+ * snapshot. */
+ intervalMs: number;
+}
+
+export interface DesktopAiRunSnapshotScheduler<TMessage = unknown> {
+ /** Schedules a throttled save for a streaming run: at most one save per
+ * intervalMs, capturing whatever the run's state is when the timer fires
+ * (not when the flush that scheduled it happened). */
+ schedule(run: DesktopAiRunRuntime<TMessage>): void;
+ /** Saves immediately, strictly ordered after any save already queued or in
+ * flight for the run, so an older snapshot can never overwrite a newer
+ * one (saves are INSERT OR REPLACEs keyed by the same row). */
+ save(run: DesktopAiRunRuntime<TMessage>): Promise<void>;
+ /** Drops a pending throttled save - call when the run settles or is deleted,
+ * so a late fire cannot write stale state over the authoritative final
+ * save (or resurrect a deleted conversation). */
+ cancel(runId: string): void;
+}
+
+// Streaming deltas used to live only in memory: a crash or quit mid-response
+// lost everything after the last pre-stream snapshot. The scheduler persists
+// snapshots incrementally from the delta flush path while keeping the writes
+// cheap (throttled) and ordered (serialized per run).
+export function createDesktopAiRunSnapshotScheduler<TMessage>(options: DesktopAiRunSnapshotSchedulerOptions<TMessage>): DesktopAiRunSnapshotScheduler<TMessage> {
+ const pendingTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ const chains = new Map<string, Promise<void>>();
+
+ const enqueue = (run: DesktopAiRunRuntime<TMessage>): Promise<void> => {
+ const chain = (chains.get(run.runId) ?? Promise.resolve())
+ .then(() => {
+ // Re-check discard at the actual execution point, not just at enqueue
+ // time: the run may have been deleted while an earlier write in this
+ // chain was still in flight. Without this re-check the queued save
+ // would persist anyway and resurrect the deleted conversation via
+ // INSERT OR REPLACE.
+ if (run.discardOnFinish) return;
+ return options.persist(run);
+ })
+ .catch(() => {})
+ .finally(() => {
+ if (chains.get(run.runId) === chain) chains.delete(run.runId);
+ });
+ chains.set(run.runId, chain);
+ return chain;
+ };
+
+ return {
+ schedule(run) {
+ // A run the user deleted must never be written back - INSERT OR REPLACE
+ // would resurrect the just-deleted conversation.
+ if (run.discardOnFinish) return;
+ if (pendingTimers.has(run.runId)) return;
+ const timer = setTimeout(() => {
+ pendingTimers.delete(run.runId);
+ if (run.discardOnFinish) return;
+ void enqueue(run);
+ }, options.intervalMs);
+ pendingTimers.set(run.runId, timer);
+ },
+ save(run) {
+ // Same delete-resurrection guard as schedule(): no caller may persist a
+ // discarded run, not even through the ordered path.
+ if (run.discardOnFinish) return Promise.resolve();
+ return enqueue(run);
+ },
+ cancel(runId) {
+ const timer = pendingTimers.get(runId);
+ if (timer === undefined) return;
+ clearTimeout(timer);
+ pendingTimers.delete(runId);
+ },
+ };
+}
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index d0966feeb5..38f00c76dc 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -345,6 +345,9 @@ export const snippetSyncDownload = forward("snippetSyncDownload");
export const saveAiConversation = forward("saveAiConversation");
export const loadAiConversations = forward("loadAiConversations");
export const deleteAiConversation = forward("deleteAiConversation");
+export const saveAiRun = forward("saveAiRun");
+export const saveAiRunState = forward("saveAiRunState");
+export const loadAiRuns = forward("loadAiRuns");
// Prompt Templates
export const loadPromptTemplates = forward("loadPromptTemplates");
@@ -821,6 +824,8 @@ export type {
AiModelInfo,
AiChatMessage,
AiConversation,
+ AiRun,
+ AiRunStatus,
PromptTemplate,
AgentDriverInfo,
AgentOfflineArtifactKind,
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index a7ed8f6012..c34551fad0 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -60,6 +60,7 @@ import type {
AiCompletionRequest,
AiStreamChunk,
AiConversation,
+ AiRun,
AiModelInfo,
DriverStoreUsage,
DriverRuntimeSummary,
@@ -1590,13 +1591,16 @@ export async function aiStream(sessionId: string, request: AiCompletionRequest,
if (line.startsWith("data:")) {
const data = line.slice(5).trim();
if (data && data !== "[DONE]") {
+ let chunk: AiStreamChunk;
try {
- const chunk: AiStreamChunk = JSON.parse(data);
- onChunk(chunk);
- if (chunk.done) return;
+ chunk = JSON.parse(data);
} catch {
// skip malformed JSON
+ continue;
}
+ if (chunk.error) throw new Error(chunk.error);
+ onChunk(chunk);
+ if (chunk.done) return;
}
}
}
@@ -1687,18 +1691,23 @@ export async function aiAgentStream(
if (line.startsWith("data:")) {
const data = line.slice(5).trim();
if (data && data !== "[DONE]") {
+ let parsed: unknown;
try {
- const parsed = JSON.parse(data);
- if (!isAgentEvent(parsed)) {
- console.warn("[aiAgentStream] Skipping invalid agent event:", data);
- continue;
- }
- onEvent(parsed);
- if (parsed.type === "agent_end" || parsed.type === "error") {
- result = data;
- }
+ parsed = JSON.parse(data);
} catch {
// skip malformed JSON
+ continue;
+ }
+ if (!isAgentEvent(parsed)) {
+ console.warn("[aiAgentStream] Skipping invalid agent event:", data);
+ continue;
+ }
+ onEvent(parsed);
+ if (parsed.type === "error") {
+ throw new Error(parsed.message);
+ }
+ if (parsed.type === "agent_end") {
+ result = data;
}
}
}
@@ -2067,6 +2076,21 @@ export async function deleteAiConversation(id: string): Promise<void> {
return del(`/api/ai/conversation/${id}`);
}
+// Background AI runs are a Desktop-only capability in this release. Keep the
+// symbols for backend-module parity without changing Web's request-bound SSE
+// lifecycle or adding a partially functional persistence API.
+export async function saveAiRun(_run: AiRun): Promise<void> {
+ throw new Error("Background AI runs are only available in DBX Desktop");
+}
+
+export async function saveAiRunState(_conversation: AiConversation, _run: AiRun): Promise<void> {
+ throw new Error("Background AI runs are only available in DBX Desktop");
+}
+
+export async function loadAiRuns(): Promise<AiRun[]> {
+ return [];
+}
+
// ---------------------------------------------------------------------------
// Prompt Templates
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 54bcb52e76..4a0e56c987 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -447,6 +447,8 @@ export interface AiStreamChunk {
delta: string;
reasoning_delta?: string;
done: boolean;
+ /** Web-only explicit terminal error; Tauri reports invoke failures directly. */
+ error?: string;
}
export async function aiStream(sessionId: string, request: AiCompletionRequest, onChunk: (chunk: AiStreamChunk) => void): Promise<void> {
@@ -904,6 +906,32 @@ export interface AiConversation {
connectionName: string;
database: string;
messages: AiChatMessage[];
+ /** One editable "send later" input saved while an active run occupies the
+ * conversation (parent PRD §5). Persisted with the conversation. */
+ queuedInput?: string;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export type AiRunStatus = "preparing" | "queued" | "running" | "awaiting_write_confirmation" | "completed" | "failed" | "cancelled" | "interrupted" | "pending_recoverable";
+
+export type AiRunFifoCategory = "normal_send" | "write_confirmation_resume";
+
+export interface AiRun {
+ runId: string;
+ conversationId: string;
+ sessionIds: string[];
+ status: AiRunStatus;
+ connectionId: string;
+ database: string;
+ schema?: string;
+ pendingConfirmation?: unknown;
+ fifoCategory?: AiRunFifoCategory;
+ pendingInput?: string;
+ /** Highest event seq assigned to this run across all its sessions (parent
+ * PRD §8). Drives the unread baseline and the "updates while you were away"
+ * separator anchor. */
+ maxSeq?: number;
createdAt: string;
updatedAt: string;
}
@@ -920,6 +948,18 @@ export async function deleteAiConversation(id: string): Promise<void> {
return invoke("delete_ai_conversation", { id });
}
+export async function saveAiRun(run: AiRun): Promise<void> {
+ return invoke("save_ai_run", { run });
+}
+
+export async function saveAiRunState(conversation: AiConversation, run: AiRun): Promise<void> {
+ return invoke("save_ai_run_state", { conversation, run });
+}
+
+export async function loadAiRuns(): Promise<AiRun[]> {
+ return invoke("load_ai_runs");
+}
+
// --- Prompt Templates ---
export interface PromptTemplate {
diff --git a/crates/dbx-core/src/agent_tools.rs b/crates/dbx-core/src/agent_tools.rs
index 012c81e82e..a375ca19c8 100644
--- a/crates/dbx-core/src/agent_tools.rs
+++ b/crates/dbx-core/src/agent_tools.rs
@@ -1,4 +1,5 @@
-use std::sync::Arc;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak};
use serde_json::json;
@@ -36,6 +37,32 @@ const MAX_QUERY_CELL_CHAR_LIMIT: usize = 4_000;
/// Bounds explicit sliding-window scans without changing the underlying database request.
const MAX_QUERY_CELL_CHAR_OFFSET: usize = 1_000_000;
+fn connection_tool_lock(connection_id: &str) -> Arc<tokio::sync::Mutex<()>> {
+ static LOCKS: OnceLock<StdMutex<HashMap<String, Weak<tokio::sync::Mutex<()>>>>> = OnceLock::new();
+ let locks = LOCKS.get_or_init(|| StdMutex::new(HashMap::new()));
+ let mut registry = locks.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ registry.retain(|_, lock| lock.strong_count() > 0);
+ if let Some(lock) = registry.get(connection_id).and_then(Weak::upgrade) {
+ return lock;
+ }
+ let lock = Arc::new(tokio::sync::Mutex::new(()));
+ registry.insert(connection_id.to_string(), Arc::downgrade(&lock));
+ lock
+}
+
+fn tool_uses_database(tool_name: &str) -> bool {
+ matches!(
+ tool_name,
+ "list_tables"
+ | "get_columns"
+ | "execute_query"
+ | "get_sample_data"
+ | "list_collections"
+ | "browse_collection"
+ | "explain_query"
+ )
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryCellWindow {
offset: usize,
@@ -506,6 +533,15 @@ pub async fn execute_tool(
db_type: &DatabaseType,
sql_permissions: AgentSqlPermissions,
) -> ToolResult {
+ // Agent loops for different conversations may share a physical connection.
+ // Lock only the database tool future; model generation and non-DB tools stay
+ // concurrent. Dropping a cancelled future releases either the waiter or the
+ // acquired guard automatically.
+ let _connection_guard = if tool_uses_database(&tool_call.name) {
+ Some(connection_tool_lock(connection_id).lock_owned().await)
+ } else {
+ None
+ };
let result = match tool_call.name.as_str() {
"list_tables" => execute_list_tables(tool_call, state, connection_id, database, default_schema, db_type).await,
"get_columns" => execute_get_columns(tool_call, state, connection_id, database, default_schema, db_type).await,
@@ -1243,6 +1279,24 @@ async fn resolve_chroma_collection_uuid(
#[cfg(test)]
mod tests {
use super::*;
+
+ #[tokio::test]
+ async fn database_tool_locks_are_connection_scoped_and_cancel_safe() {
+ let first = connection_tool_lock("agent-tool-lock-a").lock_owned().await;
+ let same_connection = connection_tool_lock("agent-tool-lock-a");
+ let other_connection = connection_tool_lock("agent-tool-lock-b");
+
+ assert!(same_connection.try_lock().is_err(), "same connection must serialize tool calls");
+ assert!(other_connection.try_lock().is_ok(), "different connections must remain concurrent");
+
+ let waiter = tokio::spawn(async move { same_connection.lock_owned().await });
+ tokio::task::yield_now().await;
+ waiter.abort();
+ let _ = waiter.await;
+ drop(first);
+
+ assert!(connection_tool_lock("agent-tool-lock-a").try_lock().is_ok());
+ }
#[cfg(unix)]
use crate::connection::PoolKind;
#[cfg(unix)]
diff --git a/crates/dbx-core/src/ai.rs b/crates/dbx-core/src/ai.rs
index 4a6d32c07e..4198d78922 100644
--- a/crates/dbx-core/src/ai.rs
+++ b/crates/dbx-core/src/ai.rs
@@ -558,6 +558,131 @@ pub struct AiConversation {
pub connection_name: String,
pub database: String,
pub messages: Vec<AiChatMessage>,
+ /// One editable "send later" input saved while an active run occupies the
+ /// conversation (parent PRD §5). Persisted with the conversation so it
+ /// survives a restart and is restored when the conversation reopens.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub queued_input: Option<String>,
+ pub created_at: String,
+ pub updated_at: String,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AiRunStatus {
+ Preparing,
+ Queued,
+ Running,
+ AwaitingWriteConfirmation,
+ Completed,
+ Failed,
+ Cancelled,
+ Interrupted,
+ /// A normal-send FIFO item recovered after a process restart. The user's
+ /// input was never actually submitted, so the run is surfaced as an
+ /// editable, unsent pending draft — never as a failure/interruption.
+ /// (Parent PRD §7: "恢复为其会话中可编辑、未发送的待发输入".)
+ PendingRecoverable,
+}
+
+impl AiRunStatus {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Preparing => "preparing",
+ Self::Queued => "queued",
+ Self::Running => "running",
+ Self::AwaitingWriteConfirmation => "awaiting_write_confirmation",
+ Self::Completed => "completed",
+ Self::Failed => "failed",
+ Self::Cancelled => "cancelled",
+ Self::Interrupted => "interrupted",
+ Self::PendingRecoverable => "pending_recoverable",
+ }
+ }
+
+ pub fn parse(value: &str) -> Result<Self, String> {
+ match value {
+ "preparing" => Ok(Self::Preparing),
+ "queued" => Ok(Self::Queued),
+ "running" => Ok(Self::Running),
+ "awaiting_write_confirmation" => Ok(Self::AwaitingWriteConfirmation),
+ "completed" => Ok(Self::Completed),
+ "failed" => Ok(Self::Failed),
+ "cancelled" => Ok(Self::Cancelled),
+ "interrupted" => Ok(Self::Interrupted),
+ "pending_recoverable" => Ok(Self::PendingRecoverable),
+ other => Err(format!("Unknown AI run status: {other}")),
+ }
+ }
+
+ pub fn protects_conversation(self) -> bool {
+ matches!(
+ self,
+ Self::Preparing | Self::Queued | Self::Running | Self::AwaitingWriteConfirmation | Self::PendingRecoverable
+ )
+ }
+}
+
+/// Why a run occupies the global FIFO queue. Normal sends and accepted
+/// write-confirmation resumes recover differently after a restart (parent
+/// PRD §3 line 58), so the category must be persisted.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AiRunFifoCategory {
+ /// A user-sent message waiting for a global concurrency slot.
+ NormalSend,
+ /// An accepted write confirmation whose resume segment is queued.
+ WriteConfirmationResume,
+}
+
+impl AiRunFifoCategory {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::NormalSend => "normal_send",
+ Self::WriteConfirmationResume => "write_confirmation_resume",
+ }
+ }
+
+ pub fn parse(value: &str) -> Result<Self, String> {
+ match value {
+ "normal_send" => Ok(Self::NormalSend),
+ "write_confirmation_resume" => Ok(Self::WriteConfirmationResume),
+ other => Err(format!("Unknown AI run FIFO category: {other}")),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AiRun {
+ pub run_id: String,
+ pub conversation_id: String,
+ #[serde(default)]
+ pub session_ids: Vec<String>,
+ pub status: AiRunStatus,
+ #[serde(default)]
+ pub connection_id: String,
+ #[serde(default)]
+ pub database: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub schema: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pending_confirmation: Option<serde_json::Value>,
+ /// Which queue category this run occupied. Persisted so restart recovery
+ /// can distinguish a normal send (→ editable pending input) from an
+ /// accepted write-confirmation resume (→ back to awaiting confirmation).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fifo_category: Option<AiRunFifoCategory>,
+ /// The user's input text for a normal-send FIFO item, recovered after
+ /// restart as an editable, unsent pending draft.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pending_input: Option<String>,
+ /// Highest event `seq` ever assigned to this run, across all its sessions
+ /// (parent PRD §8). Strictly increasing from 1; the run manager persists it
+ /// to drive event dedup, the unread baseline, and the "updates while you
+ /// were away" separator anchor.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_seq: Option<u64>,
pub created_at: String,
pub updated_at: String,
}
diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs
index d173a25006..35a4555639 100644
--- a/crates/dbx-core/src/storage.rs
+++ b/crates/dbx-core/src/storage.rs
@@ -4,13 +4,16 @@ use std::time::{SystemTime, UNIX_EPOCH};
use log::warn;
use rusqlite::{
- params, params_from_iter, types::Value, Connection, DatabaseName, OpenFlags, OptionalExtension, ToSql,
+ params, params_from_iter, types::Value, Connection, DatabaseName, OpenFlags, OptionalExtension, ToSql, Transaction,
TransactionBehavior,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-use crate::ai::{AiChatMessage, AiChatSelectionState, AiConfig, AiConfigItem, AiConversation, AiProvider};
+use crate::ai::{
+ AiChatMessage, AiChatSelectionState, AiConfig, AiConfigItem, AiConversation, AiProvider, AiRun, AiRunFifoCategory,
+ AiRunStatus,
+};
use crate::connection_secrets::{
MQ_AUTH_API_KEY_VALUE_KEY, MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_SECRET_PREFIX,
MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY, MQ_TOKEN_SIGNING_SECRET_PREFIX, NACOS_AUTH_PASSWORD_KEY,
@@ -43,6 +46,7 @@ const USER_DATA_TABLES: &[&str] = &[
"connection_secrets",
"history",
"ai_conversations",
+ "ai_runs",
"mq_token_records",
"saved_sql_folders",
"saved_sql_files",
@@ -364,9 +368,27 @@ const SCHEMA_STATEMENTS: &[&str] = &[
connection_name TEXT NOT NULL DEFAULT '',
database TEXT NOT NULL DEFAULT '',
messages_json TEXT NOT NULL DEFAULT '[]',
+ queued_input TEXT,
created_at TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT ''
)",
+ "CREATE TABLE IF NOT EXISTS ai_runs (
+ run_id TEXT PRIMARY KEY,
+ conversation_id TEXT NOT NULL,
+ session_ids_json TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL,
+ connection_id TEXT NOT NULL DEFAULT '',
+ database TEXT NOT NULL DEFAULT '',
+ schema_name TEXT,
+ pending_confirmation_json TEXT,
+ fifo_category TEXT,
+ pending_input TEXT,
+ max_seq INTEGER,
+ created_at TEXT NOT NULL DEFAULT '',
+ updated_at TEXT NOT NULL DEFAULT '',
+ FOREIGN KEY (conversation_id) REFERENCES ai_conversations(id) ON DELETE CASCADE
+ )",
+ "CREATE INDEX IF NOT EXISTS idx_ai_runs_conversation_status ON ai_runs(conversation_id, status)",
"CREATE TABLE IF NOT EXISTS sidebar_layout (
id INTEGER PRIMARY KEY CHECK (id = 1),
layout_json TEXT NOT NULL
@@ -532,6 +554,8 @@ impl Storage {
ensure_schema_cache_columns_sync(conn)?;
ensure_ai_configs_columns_sync(conn)?;
ensure_state_store_columns_sync(conn)?;
+ ensure_ai_conversations_columns_sync(conn)?;
+ ensure_ai_runs_columns_sync(conn)?;
Ok(())
})
}
@@ -730,6 +754,24 @@ fn ensure_ai_configs_columns_sync(conn: &Connection) -> Result<(), String> {
Ok(())
}
+
+/// Adds the queued-input column to `ai_conversations` for databases created
+/// by earlier iterations of the uncommitted WIP, where the table predates it.
+fn ensure_ai_conversations_columns_sync(conn: &Connection) -> Result<(), String> {
+ const COLUMNS: &[(&str, &str)] = &[("queued_input", "TEXT")];
+
+ ensure_table_columns(conn, "ai_conversations", COLUMNS)
+}
+
+/// Adds the background-run recovery columns (`fifo_category`, `pending_input`,
+/// `max_seq`) to databases created by earlier iterations of the uncommitted
+/// WIP, where the `ai_runs` table predates these fields.
+fn ensure_ai_runs_columns_sync(conn: &Connection) -> Result<(), String> {
+ const COLUMNS: &[(&str, &str)] = &[("fifo_category", "TEXT"), ("pending_input", "TEXT"), ("max_seq", "INTEGER")];
+
+ ensure_table_columns(conn, "ai_runs", COLUMNS)
+}
+
fn ensure_table_columns(conn: &Connection, table_name: &str, columns: &[(&str, &str)]) -> Result<(), String> {
let mut stmt =
conn.prepare(&format!("SELECT name FROM pragma_table_info('{table_name}')")).map_err(|e| e.to_string())?;
@@ -2136,34 +2178,109 @@ impl Storage {
// AI Conversations
+// Terminal runs beyond this many per conversation are pruned on every AI save.
+// Only the newest terminal run per conversation is ever read at recovery (it
+// drives the history row's status badge after a restart); the older ones are
+// pure, unbounded storage + startup-load growth.
+const KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION: i64 = 2;
+
+/// Caps each conversation's terminal run history. `save_ai_run` /
+/// `save_ai_run_state` persist every run unconditionally and `load_ai_runs`
+/// loads the whole table at startup, so without this cap repeated completed/
+/// failed/cancelled runs grow SQLite storage and recovery work forever. The
+/// frontend recovery loop dedups to the newest run per conversation, so keeping
+/// the newest few terminal runs preserves the row status badge exactly while
+/// bounding the table. Non-terminal statuses (preparing/queued/running/
+/// awaiting_write_confirmation/pending_recoverable) are never touched - they
+/// are the recovery payload.
+fn prune_terminal_ai_runs(tx: &Transaction<'_>) -> Result<(), String> {
+ tx.execute(
+ "DELETE FROM ai_runs
+ WHERE status IN ('completed', 'failed', 'cancelled', 'interrupted')
+ AND run_id NOT IN (
+ SELECT run_id FROM (
+ SELECT run_id,
+ ROW_NUMBER() OVER (
+ PARTITION BY conversation_id
+ ORDER BY updated_at DESC, run_id DESC
+ ) AS rn
+ FROM ai_runs
+ WHERE status IN ('completed', 'failed', 'cancelled', 'interrupted')
+ ) WHERE rn <= ?1
+ )",
+ params![KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION],
+ )
+ .map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+fn prune_ai_conversations(tx: &Transaction<'_>) -> Result<(), String> {
+ // The 50-row limit is a soft cap: conversations with active or actionable
+ // runs remain reachable even when they exceed the cap. Only terminal,
+ // unprotected conversations compete for the remaining budget.
+ tx.execute(
+ "WITH protected AS (
+ SELECT DISTINCT conversation_id FROM ai_runs
+ WHERE status IN ('preparing', 'queued', 'running', 'awaiting_write_confirmation', 'pending_recoverable')
+ ), budget AS (
+ SELECT MAX(0, 50 - COUNT(*)) AS value FROM protected
+ ), keepers AS (
+ SELECT conversation_id AS id FROM protected
+ UNION
+ SELECT id FROM (
+ SELECT id FROM ai_conversations
+ WHERE id NOT IN (SELECT conversation_id FROM protected)
+ ORDER BY updated_at DESC
+ LIMIT (SELECT value FROM budget)
+ )
+ )
+ DELETE FROM ai_conversations WHERE id NOT IN (SELECT id FROM keepers)",
+ [],
+ )
+ .map_err(|e| e.to_string())?;
+ // Do not depend on a connection-wide foreign_keys pragma for cleanup.
+ tx.execute("DELETE FROM ai_runs WHERE conversation_id NOT IN (SELECT id FROM ai_conversations)", [])
+ .map_err(|e| e.to_string())?;
+ // Cap terminal run history for the conversations that survive the cap
+ // above (they are deliberately retained), so normal use cannot grow the
+ // ai_runs table without bound.
+ prune_terminal_ai_runs(tx)?;
+ Ok(())
+}
+
impl Storage {
pub async fn save_ai_conversation(&self, conv: &AiConversation) -> Result<(), String> {
let conv = conv.clone();
let messages_json = serde_json::to_string(&conv.messages).map_err(|e| e.to_string())?;
self.with_conn(move |conn| {
- conn.execute(
- "INSERT OR REPLACE INTO ai_conversations \
- (id, title, connection_name, database, messages_json, created_at, updated_at) \
- VALUES (?, ?, ?, ?, ?, ?, ?)",
+ let tx = conn.transaction().map_err(|e| e.to_string())?;
+ tx.execute(
+ "INSERT INTO ai_conversations \
+ (id, title, connection_name, database, messages_json, queued_input, created_at, updated_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
+ ON CONFLICT(id) DO UPDATE SET \
+ title = excluded.title, \
+ connection_name = excluded.connection_name, \
+ database = excluded.database, \
+ messages_json = excluded.messages_json, \
+ queued_input = excluded.queued_input, \
+ created_at = excluded.created_at, \
+ updated_at = excluded.updated_at",
params![
conv.id,
conv.title,
conv.connection_name,
conv.database,
messages_json,
+ conv.queued_input,
conv.created_at,
conv.updated_at
],
)
.map_err(|e| e.to_string())?;
- conn.execute(
- "DELETE FROM ai_conversations WHERE id NOT IN \
- (SELECT id FROM ai_conversations ORDER BY updated_at DESC LIMIT 50)",
- [],
- )
- .map_err(|e| e.to_string())?;
- Ok(())
+ prune_ai_conversations(&tx)?;
+ tx.commit().map_err(|e| e.to_string())
})
.await
}
@@ -2172,7 +2289,7 @@ impl Storage {
self.with_conn(|conn| {
let mut stmt = conn
.prepare(
- "SELECT id, title, connection_name, database, messages_json, created_at, updated_at \
+ "SELECT id, title, connection_name, database, messages_json, queued_input, created_at, updated_at \
FROM ai_conversations ORDER BY updated_at DESC",
)
.map_err(|e| e.to_string())?;
@@ -2187,8 +2304,9 @@ impl Storage {
connection_name: row.get(2)?,
database: row.get(3)?,
messages,
- created_at: row.get(5)?,
- updated_at: row.get(6)?,
+ queued_input: row.get(5)?,
+ created_at: row.get(6)?,
+ updated_at: row.get(7)?,
})
})
.map_err(|e| e.to_string())?;
@@ -2200,7 +2318,179 @@ impl Storage {
pub async fn delete_ai_conversation(&self, id: &str) -> Result<(), String> {
let id = id.to_string();
self.with_conn(move |conn| {
- conn.execute("DELETE FROM ai_conversations WHERE id = ?1", [id]).map(|_| ()).map_err(|e| e.to_string())
+ let tx = conn.transaction().map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_runs WHERE conversation_id = ?1", [&id]).map_err(|e| e.to_string())?;
+ tx.execute("DELETE FROM ai_conversations WHERE id = ?1", [&id]).map_err(|e| e.to_string())?;
+ prune_ai_conversations(&tx)?;
+ tx.commit().map_err(|e| e.to_string())
+ })
+ .await
+ }
+
+ pub async fn save_ai_run(&self, run: &AiRun) -> Result<(), String> {
+ let run = run.clone();
+ let session_ids_json = serde_json::to_string(&run.session_ids).map_err(|e| e.to_string())?;
+ let pending_confirmation_json = run.pending_confirmation.map(|value| value.to_string());
+ let fifo_category = run.fifo_category.map(|c| c.as_str().to_string());
+ self.with_conn(move |conn| {
+ let tx = conn.transaction().map_err(|e| e.to_string())?;
+ tx.execute(
+ "INSERT OR REPLACE INTO ai_runs
+ (run_id, conversation_id, session_ids_json, status, connection_id, database, schema_name,
+ pending_confirmation_json, fifo_category, pending_input, max_seq, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ params![
+ run.run_id,
+ run.conversation_id,
+ session_ids_json,
+ run.status.as_str(),
+ run.connection_id,
+ run.database,
+ run.schema,
+ pending_confirmation_json,
+ fifo_category,
+ run.pending_input,
+ run.max_seq,
+ run.created_at,
+ run.updated_at,
+ ],
+ )
+ .map_err(|e| e.to_string())?;
+ prune_ai_conversations(&tx)?;
+ tx.commit().map_err(|e| e.to_string())
+ })
+ .await
+ }
+
+ pub async fn save_ai_run_state(&self, conv: &AiConversation, run: &AiRun) -> Result<(), String> {
+ let conv = conv.clone();
+ let run = run.clone();
+ let messages_json = serde_json::to_string(&conv.messages).map_err(|e| e.to_string())?;
+ let session_ids_json = serde_json::to_string(&run.session_ids).map_err(|e| e.to_string())?;
+ let pending_confirmation_json = run.pending_confirmation.map(|value| value.to_string());
+ let fifo_category = run.fifo_category.map(|c| c.as_str().to_string());
+ self.with_conn(move |conn| {
+ let tx = conn.transaction().map_err(|e| e.to_string())?;
+ tx.execute(
+ "INSERT INTO ai_conversations
+ (id, title, connection_name, database, messages_json, queued_input, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ title = excluded.title,
+ connection_name = excluded.connection_name,
+ database = excluded.database,
+ messages_json = excluded.messages_json,
+ queued_input = excluded.queued_input,
+ created_at = excluded.created_at,
+ updated_at = excluded.updated_at",
+ params![
+ conv.id,
+ conv.title,
+ conv.connection_name,
+ conv.database,
+ messages_json,
+ conv.queued_input,
+ conv.created_at,
+ conv.updated_at
+ ],
+ )
+ .map_err(|e| e.to_string())?;
+ tx.execute(
+ "INSERT OR REPLACE INTO ai_runs
+ (run_id, conversation_id, session_ids_json, status, connection_id, database, schema_name,
+ pending_confirmation_json, fifo_category, pending_input, max_seq, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ params![
+ run.run_id,
+ run.conversation_id,
+ session_ids_json,
+ run.status.as_str(),
+ run.connection_id,
+ run.database,
+ run.schema,
+ pending_confirmation_json,
+ fifo_category,
+ run.pending_input,
+ run.max_seq,
+ run.created_at,
+ run.updated_at,
+ ],
+ )
+ .map_err(|e| e.to_string())?;
+ prune_ai_conversations(&tx)?;
+ tx.commit().map_err(|e| e.to_string())
+ })
+ .await
+ }
+
+ pub async fn load_ai_runs(&self) -> Result<Vec<AiRun>, String> {
+ self.with_conn(|conn| {
+ let mut stmt = conn
+ .prepare(
+ "SELECT run_id, conversation_id, session_ids_json, status, connection_id, database,
+ schema_name, pending_confirmation_json, fifo_category, pending_input, max_seq, created_at, updated_at
+ FROM ai_runs ORDER BY updated_at DESC",
+ )
+ .map_err(|e| e.to_string())?;
+ let rows = stmt
+ .query_map([], |row| {
+ let session_ids_json: String = row.get(2)?;
+ let status: String = row.get(3)?;
+ let pending_confirmation_json: Option<String> = row.get(7)?;
+ let fifo_category: Option<String> = row.get(8)?;
+ let pending_input: Option<String> = row.get(9)?;
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ session_ids_json,
+ status,
+ row.get::<_, String>(4)?,
+ row.get::<_, String>(5)?,
+ row.get::<_, Option<String>>(6)?,
+ pending_confirmation_json,
+ fifo_category,
+ pending_input,
+ row.get::<_, Option<u64>>(10)?,
+ row.get::<_, String>(11)?,
+ row.get::<_, String>(12)?,
+ ))
+ })
+ .map_err(|e| e.to_string())?;
+ rows.map(|row| {
+ let (
+ run_id,
+ conversation_id,
+ session_ids_json,
+ status,
+ connection_id,
+ database,
+ schema,
+ pending_confirmation_json,
+ fifo_category,
+ pending_input,
+ max_seq,
+ created_at,
+ updated_at,
+ ) = row.map_err(|e| e.to_string())?;
+ Ok(AiRun {
+ run_id,
+ conversation_id,
+ session_ids: serde_json::from_str(&session_ids_json).map_err(|e| e.to_string())?,
+ status: AiRunStatus::parse(&status)?,
+ connection_id,
+ database,
+ schema,
+ pending_confirmation: pending_confirmation_json
+ .map(|json| serde_json::from_str(&json).map_err(|e| e.to_string()))
+ .transpose()?,
+ fifo_category: fifo_category.map(|value| AiRunFifoCategory::parse(&value)).transpose()?,
+ pending_input,
+ max_seq,
+ created_at,
+ updated_at,
+ })
+ })
+ .collect::<Result<Vec<_>, String>>()
})
.await
}
@@ -4385,10 +4675,11 @@ fn map_from_sql_err(err: serde_json::Error) -> rusqlite::Error {
mod tests {
use super::{
maybe_import_user_data_db, DataDbImportResult, DesktopIconTheme, DesktopSettings, McpGlobalPolicy,
- McpGlobalPolicyState, Storage, MCP_GLOBAL_POLICY_KEY,
+ McpGlobalPolicyState, Storage, KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION, MCP_GLOBAL_POLICY_KEY,
};
use crate::ai::{
- AiActiveModelSelection, AiAssistantMode, AiChatSelectionState, AiEffortSelection, AiModelEffortPreference,
+ AiActiveModelSelection, AiAssistantMode, AiChatMessage, AiChatSelectionState, AiConversation,
+ AiEffortSelection, AiModelEffortPreference, AiRun, AiRunFifoCategory, AiRunStatus,
};
use crate::connection_secrets::NACOS_RNACOS_CONSOLE_PASSWORD_KEY;
use crate::connection_secrets::{
@@ -4440,6 +4731,239 @@ mod tests {
}
}
+ fn ai_conversation(id: &str, updated_at: &str) -> AiConversation {
+ AiConversation {
+ id: id.to_string(),
+ title: id.to_string(),
+ connection_name: "local".to_string(),
+ database: "db".to_string(),
+ messages: vec![AiChatMessage {
+ role: "user".to_string(),
+ content: id.to_string(),
+ mentions: None,
+ reasoning: None,
+ kind: None,
+ covered_messages: None,
+ }],
+ queued_input: None,
+ created_at: updated_at.to_string(),
+ updated_at: updated_at.to_string(),
+ }
+ }
+
+ fn ai_run(id: &str, conversation_id: &str, status: AiRunStatus, updated_at: &str) -> AiRun {
+ AiRun {
+ run_id: id.to_string(),
+ conversation_id: conversation_id.to_string(),
+ session_ids: vec![],
+ status,
+ connection_id: "connection".to_string(),
+ database: "db".to_string(),
+ schema: None,
+ pending_confirmation: None,
+ fifo_category: None,
+ pending_input: None,
+ max_seq: None,
+ created_at: updated_at.to_string(),
+ updated_at: updated_at.to_string(),
+ }
+ }
+
+ #[tokio::test]
+ async fn ai_conversation_soft_cap_never_evicts_protected_runs() {
+ let path = temp_db_path("ai-conversation-soft-cap");
+ let storage = Storage::open(&path).await.unwrap();
+
+ let protected = ai_conversation("protected", "0000");
+ let protected_run = ai_run("protected-run", "protected", AiRunStatus::Running, "0000");
+ storage.save_ai_run_state(&protected, &protected_run).await.unwrap();
+ for index in 0..55 {
+ let timestamp = format!("{index:04}");
+ storage.save_ai_conversation(&ai_conversation(&format!("terminal-{index}"), &timestamp)).await.unwrap();
+ }
+
+ let conversations = storage.load_ai_conversations().await.unwrap();
+ assert_eq!(conversations.len(), 50);
+ assert!(conversations.iter().any(|conversation| conversation.id == "protected"));
+ assert!(!conversations.iter().any(|conversation| conversation.id == "terminal-0"));
+ assert!(conversations.iter().any(|conversation| conversation.id == "terminal-54"));
+
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn ai_conversation_soft_cap_allows_more_than_fifty_protected_runs() {
+ let path = temp_db_path("ai-conversation-protected-overflow");
+ let storage = Storage::open(&path).await.unwrap();
+
+ for index in 0..51 {
+ let id = format!("protected-{index}");
+ let timestamp = format!("{index:04}");
+ storage
+ .save_ai_run_state(
+ &ai_conversation(&id, &timestamp),
+ &ai_run(&format!("run-{index}"), &id, AiRunStatus::AwaitingWriteConfirmation, &timestamp),
+ )
+ .await
+ .unwrap();
+ }
+ storage.save_ai_conversation(&ai_conversation("terminal-extra", "9999")).await.unwrap();
+
+ let conversations = storage.load_ai_conversations().await.unwrap();
+ assert_eq!(conversations.len(), 51);
+ assert!(conversations.iter().all(|conversation| conversation.id.starts_with("protected-")));
+
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn ai_conversation_soft_cap_protects_pending_recoverable_runs() {
+ let path = temp_db_path("ai-conversation-pending-recoverable-protection");
+ let storage = Storage::open(&path).await.unwrap();
+
+ // A recovered pending-input run (PRD §7 line 93) must be protected like
+ // any other non-terminal run: its draft is not lost to pruning.
+ let protected = ai_conversation("recoverable", "0000");
+ let mut protected_run = ai_run("recoverable-run", "recoverable", AiRunStatus::PendingRecoverable, "0000");
+ protected_run.pending_input = Some("recover me".to_string());
+ storage.save_ai_run_state(&protected, &protected_run).await.unwrap();
+ for index in 0..55 {
+ let timestamp = format!("{index:04}");
+ storage.save_ai_conversation(&ai_conversation(&format!("terminal-{index}"), &timestamp)).await.unwrap();
+ }
+
+ let conversations = storage.load_ai_conversations().await.unwrap();
+ assert_eq!(conversations.len(), 50);
+ assert!(conversations.iter().any(|conversation| conversation.id == "recoverable"));
+ assert!(!conversations.iter().any(|conversation| conversation.id == "terminal-0"));
+
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn ai_run_roundtrips_fifo_category_and_pending_input() {
+ let path = temp_db_path("ai-run-fifo-category-roundtrip");
+ let storage = Storage::open(&path).await.unwrap();
+
+ let conversation = ai_conversation("fifo-conv", "0000");
+ let mut run = ai_run("fifo-run", "fifo-conv", AiRunStatus::Queued, "0000");
+ run.fifo_category = Some(AiRunFifoCategory::NormalSend);
+ run.pending_input = Some("select * from orders limit 5".to_string());
+ run.max_seq = Some(42);
+ storage.save_ai_run_state(&conversation, &run).await.unwrap();
+
+ let loaded = storage.load_ai_runs().await.unwrap();
+ assert_eq!(loaded.len(), 1);
+ assert_eq!(loaded[0].run_id, "fifo-run");
+ assert_eq!(loaded[0].status, AiRunStatus::Queued);
+ assert_eq!(loaded[0].fifo_category, Some(AiRunFifoCategory::NormalSend));
+ assert_eq!(loaded[0].pending_input.as_deref(), Some("select * from orders limit 5"));
+ assert_eq!(loaded[0].max_seq, Some(42));
+
+ // The write_confirmation_resume category survives too.
+ let mut resume = ai_run("resume-run", "fifo-conv", AiRunStatus::Queued, "0001");
+ resume.fifo_category = Some(AiRunFifoCategory::WriteConfirmationResume);
+ storage.save_ai_run(&resume).await.unwrap();
+ let loaded = storage.load_ai_runs().await.unwrap();
+ let resume = loaded.iter().find(|run| run.run_id == "resume-run").unwrap();
+ assert_eq!(resume.fifo_category, Some(AiRunFifoCategory::WriteConfirmationResume));
+ assert!(resume.pending_input.is_none());
+
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn saving_a_conversation_keeps_its_background_runs() {
+ let path = temp_db_path("ai-conversation-upsert-keeps-runs");
+ let storage = Storage::open(&path).await.unwrap();
+ // `ai_runs` declares an ON DELETE CASCADE relationship. Exercise the
+ // snapshot path with enforcement enabled so an accidental REPLACE
+ // (delete + insert) cannot silently erase an active run on restart.
+ storage
+ .with_conn(|conn| conn.execute_batch("PRAGMA foreign_keys = ON").map_err(|e| e.to_string()))
+ .await
+ .unwrap();
+
+ let mut conversation = ai_conversation("upsert-conv", "0000");
+ let run = ai_run("upsert-run", "upsert-conv", AiRunStatus::Running, "0000");
+ storage.save_ai_run_state(&conversation, &run).await.unwrap();
+
+ conversation.updated_at = "0001".to_string();
+ conversation.queued_input = Some("send later".to_string());
+ storage.save_ai_conversation(&conversation).await.unwrap();
+
+ let runs = storage.load_ai_runs().await.unwrap();
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].run_id, "upsert-run");
+
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn terminal_ai_runs_are_capped_per_conversation_while_nonterminal_survive() {
+ // Reviewed finding (unbounded terminal run growth): save_ai_run /
+ // save_ai_run_state persist every terminal run and load_ai_runs loads
+ // the whole table at startup, but prune_ai_conversations only caps
+ // conversations and deliberately retains runs for the survivors - so
+ // repeated completed runs grew SQLite storage and recovery work
+ // forever. The storage layer now caps terminal history per
+ // conversation (keeping the newest few, which drive the row status
+ // badge after restart) and never touches recovery-relevant runs.
+ let path = temp_db_path("ai-terminal-runs-capped");
+ let storage = Storage::open(&path).await.unwrap();
+
+ // A non-terminal run must always survive - it is the recovery payload.
+ let conversation = ai_conversation("cap-conv", "0000");
+ storage
+ .save_ai_run_state(&conversation, &ai_run("active-run", "cap-conv", AiRunStatus::Running, "0000"))
+ .await
+ .unwrap();
+ // Repeated completed runs (normal use): older ones must be pruned.
+ for index in 0..5 {
+ let timestamp = format!("{index:04}");
+ storage
+ .save_ai_run(&ai_run(&format!("terminal-{index}"), "cap-conv", AiRunStatus::Completed, &timestamp))
+ .await
+ .unwrap();
+ }
+
+ let runs = storage.load_ai_runs().await.unwrap();
+ assert!(runs.iter().any(|run| run.run_id == "active-run"), "recovery-relevant run must survive");
+ let terminal: Vec<_> = runs.iter().filter(|run| run.status == AiRunStatus::Completed).collect();
+ assert_eq!(
+ terminal.len(),
+ KEEP_TERMINAL_AI_RUNS_PER_CONVERSATION as usize,
+ "only the newest terminal runs per conversation survive"
+ );
+ assert!(terminal.iter().any(|run| run.run_id == "terminal-4"), "the newest terminal run is retained");
+ assert!(!runs.iter().any(|run| run.run_id == "terminal-0"), "the oldest terminal runs are pruned");
+
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[tokio::test]
+ async fn ai_conversation_roundtrips_queued_input() {
+ let path = temp_db_path("ai-conversation-queued-input-roundtrip");
+ let storage = Storage::open(&path).await.unwrap();
+
+ let mut conversation = ai_conversation("queued-conv", "0000");
+ conversation.queued_input = Some("run this after the current task".to_string());
+ storage.save_ai_conversation(&conversation).await.unwrap();
+
+ let loaded = storage.load_ai_conversations().await.unwrap();
+ assert_eq!(loaded.len(), 1);
+ assert_eq!(loaded[0].id, "queued-conv");
+ assert_eq!(loaded[0].queued_input.as_deref(), Some("run this after the current task"));
+
+ // Overwriting clears a stale queued input.
+ conversation.queued_input = None;
+ storage.save_ai_conversation(&conversation).await.unwrap();
+ let loaded = storage.load_ai_conversations().await.unwrap();
+ assert!(loaded[0].queued_input.is_none());
+
+ let _ = std::fs::remove_file(path);
+ }
+
#[tokio::test]
async fn history_search_filters_connection_database_and_legacy_entries() {
let path = temp_db_path("history-search-scope");
diff --git a/crates/dbx-web/src/routes/ai.rs b/crates/dbx-web/src/routes/ai.rs
index 4f400354ca..3e72c4f69a 100644
--- a/crates/dbx-web/src/routes/ai.rs
+++ b/crates/dbx-web/src/routes/ai.rs
@@ -369,10 +369,17 @@ pub async fn ai_stream(
})
.await;
- if let Err(_e) = result {
- let error_chunk =
- AiStreamChunk { session_id: sid.clone(), delta: String::new(), reasoning_delta: None, done: true };
- let _ = tx.send(serde_json::to_string(&error_chunk).unwrap_or_default());
+ if let Err(error) = result {
+ // Preserve the existing POST/SSE lifecycle, but make failure an
+ // explicit terminal payload so Web cannot mistake it for a
+ // successful empty response.
+ let error_chunk = serde_json::json!({
+ "session_id": sid.clone(),
+ "delta": "",
+ "done": true,
+ "error": error,
+ });
+ let _ = tx.send(error_chunk.to_string());
}
dbx_core::ai::unregister_stream(&sid).await;
diff --git a/packages/app-tests/aiAssistantSendGuard.test.ts b/packages/app-tests/aiAssistantSendGuard.test.ts
index c65d4ebe47..ed73048ce9 100644
--- a/packages/app-tests/aiAssistantSendGuard.test.ts
+++ b/packages/app-tests/aiAssistantSendGuard.test.ts
@@ -57,7 +57,10 @@ test("send() acquires the guard synchronously before the first await", () => {
const entryCheck = body.search(/\|\|\s*isGenerating\.value\)\s*return/);
const guardSet = body.indexOf("isGenerating.value = true");
- const firstAwait = body.indexOf("await");
+ // `await` as a whole word (not the substring inside e.g. the
+ // `awaiting_write_confirmation` run status), so the first suspension point is
+ // genuinely the first await statement.
+ const firstAwait = body.search(/\bawait\b/);
assert.notEqual(entryCheck, -1, "send() should early-return when isGenerating is already set");
assert.notEqual(guardSet, -1, "send() should set the isGenerating guard");
diff --git a/packages/app-tests/aiMessageLayout.test.ts b/packages/app-tests/aiMessageLayout.test.ts
index 2a4bc9d6bd..6c823af302 100644
--- a/packages/app-tests/aiMessageLayout.test.ts
+++ b/packages/app-tests/aiMessageLayout.test.ts
@@ -61,15 +61,17 @@ test("assistant messages keep metadata aligned with the bubble and wrap long tex
test("AI request failures use localized backend diagnostics", () => {
// The lookup is guarded (matching the `finally` block right below it) so that if
- // clearMessages()/selectConversation() already replaced messages.value while this
+ // clearMessages()/selectConversation() already replaced the transcript while this
// request was still in flight, writing the failure text doesn't throw and silently
- // swallow the real error. See issue #5941.
- assert.match(source, /const msg = messages\.value\[assistantIdx\];\s*\n\s*if \(msg\) msg\.content = `\$\{t\("ai\.requestFailed"\)\}\\n\\n\$\{translateBackendError\(t, message\)\}`;/);
+ // swallow the real error. See issue #5941. (`runMessages` is the send pipeline's
+ // array — `messages.value` for a visible conversation, the run's own array for a
+ // detached/background run.)
+ assert.match(source, /const msg = runMessages\[assistantIdx\];\s*\n\s*if \(msg\) msg\.content = `\$\{t\("ai\.requestFailed"\)\}\\n\\n\$\{translateBackendError\(t, message\)\}`;/);
});
test("AI analysis export keeps the connection that produced each assistant response", () => {
assert.match(source, /sourceConnectionName\?: string/);
- assert.match(source, /messages\.value\.push\(\{ role: "assistant", content: "", sourceConnectionName: connection\.name \}\)/);
+ assert.match(source, /runMessages\.push\(\{ role: "assistant", content: "", sourceConnectionName: connection\.name \}\)/);
assert.match(source, /connectionName: msg\.sourceConnectionName \?\? props\.connection\?\.name/);
assert.match(source, /sourceConnectionName: m\.role === "assistant" \? conv\.connectionName : undefined/);
});
diff --git a/packages/app-tests/i18nAutofillParser.test.ts b/packages/app-tests/i18nAutofillParser.test.ts
index 398028a9e3..461aeed134 100644
--- a/packages/app-tests/i18nAutofillParser.test.ts
+++ b/packages/app-tests/i18nAutofillParser.test.ts
@@ -3,11 +3,17 @@ import { execFileSync } from "node:child_process";
import { test } from "vitest";
test("i18n autofill parses locale roots with imported shorthand sections", () => {
- const output = execFileSync(process.execPath, [".github/scripts/i18n-autofill.mjs", "--dry-run", "--base-ref", "HEAD"], {
- encoding: "utf8",
- });
+ // `--mock-translations`: the script's DeepSeek-backed translation step only
+ // runs when a PR adds NEW zh-CN keys (here: the current branch's 38). CI
+ // has no DEEPSEEK_API_KEY, so this test asserts the parser/dry-run pipeline
+ // works with the deterministic mock instead of depending on a live API key.
+ const output = execFileSync(
+ process.execPath,
+ [".github/scripts/i18n-autofill.mjs", "--dry-run", "--base-ref", "HEAD", "--mock-translations"],
+ { encoding: "utf8" },
+ );
// Accept every "no new keys / no changes needed" wording used across
// recent PRs (e.g. mongo-clone, consul) plus the "found N new keys" path.
- assert.match(output, /(?:No new zh-CN i18n keys compared with HEAD|Found \d+ new zh-CN i18n key\(s\):|No locale files needed changes)/);
+ assert.match(output, /(?:No new zh-CN i18n keys compared with HEAD|Found \d+ new zh-CN i18n key\(s\):|No locale files needed changes|Dry run completed)/);
});
diff --git a/src-tauri/src/commands/ai.rs b/src-tauri/src/commands/ai.rs
index 84d617937b..f0dea97360 100644
--- a/src-tauri/src/commands/ai.rs
+++ b/src-tauri/src/commands/ai.rs
@@ -286,6 +286,25 @@ pub async fn delete_ai_conversation(state: State<'_, Arc<AppState>>, id: String)
state.storage.delete_ai_conversation(&id).await
}
+#[tauri::command]
+pub async fn save_ai_run(state: State<'_, Arc<AppState>>, run: AiRun) -> Result<(), String> {
+ state.storage.save_ai_run(&run).await
+}
+
+#[tauri::command]
+pub async fn save_ai_run_state(
+ state: State<'_, Arc<AppState>>,
+ conversation: AiConversation,
+ run: AiRun,
+) -> Result<(), String> {
+ state.storage.save_ai_run_state(&conversation, &run).await
+}
+
+#[tauri::command]
+pub async fn load_ai_runs(state: State<'_, Arc<AppState>>) -> Result<Vec<AiRun>, String> {
+ state.storage.load_ai_runs().await
+}
+
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU32, Ordering};
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 871bae4387..88846c3981 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1804,6 +1804,9 @@ pub fn run() {
commands::ai::save_ai_conversation,
commands::ai::load_ai_conversations,
commands::ai::delete_ai_conversation,
+ commands::ai::save_ai_run,
+ commands::ai::save_ai_run_state,
+ commands::ai::load_ai_runs,
commands::ai_multi_config::save_ai_configs,
commands::ai_multi_config::load_ai_configs,
commands::ai_multi_config::set_default_ai_config,