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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(result-tabs): support pinned tabs and batch closing
二丫讲梵93dc455c7297
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex f4bf2ec526..19ea6c9ec8 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -49,6 +49,7 @@ import "splitpanes/dist/splitpanes.css";import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent, DropdownMenuPortal } from "@/components/ui/dropdown-menu";+import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";import { Switch } from "@/components/ui/switch";import LightTooltip from "@/components/ui/LightTooltip.vue";import QueryEditor from "@/components/editor/QueryEditor.vue";@@ -255,6 +256,7 @@ onMounted(() => {window.addEventListener("resize", updateStandaloneResultToolbarDimensions);window.visualViewport?.addEventListener("resize", updateStandaloneResultToolbarDimensions);window.addEventListener("dbx:ui-scale-applied", updateStandaloneResultToolbarDimensions);+ revealActiveResultRunAfterRender();});watch(@@ -474,13 +476,43 @@ const activeResultRunItem = computed(() => resultRuns.value.find((run) => run.acconst showResultRunTabs = computed(() => resultRuns.value.length > 0 && resultRunDisplayMode.value === "tabs");const showResultRunSelector = computed(() => resultRuns.value.length > 0 && resultRunDisplayMode.value === "list");const canCloseQueryResult = computed(() => props.activeTab.mode === "query" && !props.activeTab.isExecuting && !props.activeTab.activeResultRunId && (!!props.activeTab.result || !!props.activeTab.results?.length || props.activeTab.resultEvicted === true));++function updateResultTabsAfterRender() {+ nextTick(() => updateResultTabsScrollbar());+}++function revealActiveResultRunAfterRender() {+ nextTick(() => {+ if (!showResultRunTabs.value) return;+ updateResultTabsScrollbar();+ resultTabsScrollerRef.value?.querySelector<HTMLElement>('[data-active-result-run="true"]')?.scrollIntoView({ block: "nearest", inline: "nearest" });+ });+}++function resultRunIdsWereAppended(previous: string[], current: string[]) {+ return current.length > previous.length && previous.every((id, index) => current[index] === id);+}+watch(- () => `${resultRunDisplayMode.value}:${resultRuns.value.map((run) => run.id).join(",")}:${props.activeTab.activeResultRunId ?? ""}`,- () => {- nextTick(() => {- updateResultTabsScrollbar();- resultTabsScrollerRef.value?.querySelector<HTMLElement>('[data-active-result-run="true"]')?.scrollIntoView({ block: "nearest", inline: "nearest" });- });+ () => ({+ tabId: props.activeTab.id,+ displayMode: resultRunDisplayMode.value,+ runIds: resultRuns.value.map((run) => run.id),+ activeRunId: props.activeTab.activeResultRunId,+ }),+ (current, previous) => {+ const switchedTab = current.tabId !== previous.tabId;+ const switchedDisplayMode = current.displayMode !== previous.displayMode;+ const activeRunChanged = current.activeRunId !== previous.activeRunId;++ // Appending a fresh result must keep the user's horizontal position stable.+ // Reused result slots, tab/display-mode changes, and keyboard/close flows+ // still reveal the active run when it may be outside the visible strip.+ if (switchedTab || switchedDisplayMode || (activeRunChanged && !resultRunIdsWereAppended(previous.runIds, current.runIds))) {+ revealActiveResultRunAfterRender();+ return;+ }+ updateResultTabsAfterRender();},);const summaryItems = computed(() => executionSummaryItems(props.activeTab));@@ -911,6 +943,61 @@ async function removeResultRun(runId: string) {activeRunTab?.scrollIntoView({ block: "nearest", inline: "nearest" });}+function toggleResultRunPinned(runId: string) {+ queryStore.toggleResultRunPinned(props.activeTab.id, runId);+}++async function closeOtherResultRuns(runId: string) {+ if (!(await queryStore.closeOtherResultRuns(props.activeTab.id, runId))) return;+ await selectResultRun(runId);+}++async function closeResultRunsToLeft(runId: string) {+ if (!(await queryStore.closeResultRunsToLeft(props.activeTab.id, runId))) return;+ await selectResultRun(runId);+}++async function closeResultRunsToRight(runId: string) {+ if (!(await queryStore.closeResultRunsToRight(props.activeTab.id, runId))) return;+ await selectResultRun(runId);+}++function resultRunContextMenuItems(run: (typeof resultRuns.value)[number]): ContextMenuItem[] {+ return [+ {+ label: t(run.pinned ? "tabs.unpinResultRun" : "tabs.pinResultRun"),+ action: () => toggleResultRunPinned(run.id),+ icon: Pin,+ iconClass: run.pinned ? "fill-current" : "",+ },+ {+ label: t("tabs.unpinAllResultRuns"),+ action: () => queryStore.unpinAllResultRuns(props.activeTab.id),+ disabled: !resultRuns.value.some((item) => item.pinned),+ icon: Pin,+ },+ { label: "", separator: true },+ {+ label: t("tabs.closeOtherResultRuns"),+ action: () => void closeOtherResultRuns(run.id),+ disabled: resultRuns.value.length <= 1,+ icon: X,+ },+ {+ label: t("tabs.closeResultRunsToLeft"),+ action: () => void closeResultRunsToLeft(run.id),+ disabled: resultRuns.value.findIndex((item) => item.id === run.id) <= 0,+ icon: X,+ },+ {+ label: t("tabs.closeResultRunsToRight"),+ action: () => void closeResultRunsToRight(run.id),+ disabled: resultRuns.value.findIndex((item) => item.id === run.id) >= resultRuns.value.length - 1,+ icon: X,+ },+ ];+}+async function closeCurrentQueryResult() {if (!(await queryStore.closeQueryResult(props.activeTab.id))) return;emit("update:activeOutputView", "result");@@ -1163,36 +1250,38 @@ defineExpose({</div><div ref="resultTabsScrollerRef" class="result-tab-scroll flex h-full items-center gap-1 overflow-x-auto overflow-y-hidden px-1" :style="resultTabsScrollerStyle" @scroll="updateResultTabsScrollbar" @wheel="onResultTabsWheel"><div role="tablist" :aria-label="t('tabs.resultRuns')" class="flex h-full shrink-0 items-center gap-1">- <div- v-for="(run, runIndex) in resultRuns"- :key="run.id"- role="presentation"- class="group/result-run inline-flex h-7 shrink-0 items-center overflow-hidden rounded-md border transition-colors"- :class="run.active ? 'border-border bg-background text-foreground shadow-sm' : 'border-transparent text-muted-foreground hover:border-border/70 hover:bg-background/70 hover:text-foreground'"- >- <button- type="button"- role="tab"- data-result-run-tab- :tabindex="run.active ? 0 : -1"- :aria-selected="run.active"- :data-active-result-run="run.active ? 'true' : undefined"- class="h-full whitespace-nowrap pl-2.5 pr-1 text-xs font-medium outline-none focus-visible:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"- @click="selectResultRun(run.id)"- @keydown="onResultRunTabKeydown($event, runIndex)"+ <CustomContextMenu v-for="(run, runIndex) in resultRuns" :key="run.id" :items="() => resultRunContextMenuItems(run)" v-slot="{ onContextMenu }">+ <div+ role="presentation"+ class="group/result-run inline-flex h-7 shrink-0 select-none items-center overflow-hidden rounded-md border transition-colors"+ :class="run.active ? 'border-border bg-background text-foreground shadow-sm' : 'border-transparent text-muted-foreground hover:border-border/70 hover:bg-background/70 hover:text-foreground'"+ @contextmenu="onContextMenu">- {{ run.title || t("tabs.runN", { n: run.sequence }) }}- </button>- <button- type="button"- class="mr-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground/70 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"- :title="t('tabs.removeRun', { n: run.sequence })"- :aria-label="t('tabs.removeRun', { n: run.sequence })"- @click.stop.prevent="removeResultRun(run.id)"- >- <X class="h-3 w-3" />- </button>- </div>+ <button+ type="button"+ role="tab"+ data-result-run-tab+ :tabindex="run.active ? 0 : -1"+ :aria-selected="run.active"+ :data-active-result-run="run.active ? 'true' : undefined"+ class="flex h-full select-none items-center gap-1 whitespace-nowrap pl-2.5 pr-1 text-xs font-medium outline-none focus-visible:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"+ @click="selectResultRun(run.id)"+ @keydown="onResultRunTabKeydown($event, runIndex)"+ >+ <Pin v-if="run.pinned" class="h-3 w-3 shrink-0 fill-current text-primary" />+ {{ run.title || t("tabs.runN", { n: run.sequence }) }}+ </button>+ <button+ type="button"+ class="mr-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground/70 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"+ :title="t('tabs.removeRun', { n: run.sequence })"+ :aria-label="t('tabs.removeRun', { n: run.sequence })"+ @click.stop.prevent="removeResultRun(run.id)"+ >+ <X class="h-3 w-3" />+ </button>+ </div>+ </CustomContextMenu></div></div></div>@@ -1205,20 +1294,23 @@ defineExpose({</Button></DropdownMenuTrigger><DropdownMenuContent align="start" class="w-48">- <DropdownMenuItem v-for="run in resultRuns" :key="run.id" class="flex items-center gap-2 pr-1" @select="selectResultRun(run.id)">- <Check v-if="run.active" class="h-3.5 w-3.5 shrink-0" />- <span v-else class="h-3.5 w-3.5 shrink-0" />- <span class="min-w-0 flex-1 truncate">{{ run.title || t("tabs.runN", { n: run.sequence }) }}</span>- <button- type="button"- class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"- :title="t('tabs.removeRun', { n: run.sequence })"- :aria-label="t('tabs.removeRun', { n: run.sequence })"- @click.stop.prevent="removeResultRun(run.id)"- >- <X class="h-3 w-3" />- </button>- </DropdownMenuItem>+ <CustomContextMenu v-for="run in resultRuns" :key="run.id" :items="() => resultRunContextMenuItems(run)" v-slot="{ onContextMenu }">+ <DropdownMenuItem class="flex items-center gap-2 pr-1" @select="selectResultRun(run.id)" @contextmenu="onContextMenu">+ <Check v-if="run.active" class="h-3.5 w-3.5 shrink-0" />+ <span v-else class="h-3.5 w-3.5 shrink-0" />+ <Pin v-if="run.pinned" class="h-3 w-3 shrink-0 fill-current text-primary" />+ <span class="min-w-0 flex-1 truncate">{{ run.title || t("tabs.runN", { n: run.sequence }) }}</span>+ <button+ type="button"+ class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"+ :title="t('tabs.removeRun', { n: run.sequence })"+ :aria-label="t('tabs.removeRun', { n: run.sequence })"+ @click.stop.prevent="removeResultRun(run.id)"+ >+ <X class="h-3 w-3" />+ </button>+ </DropdownMenuItem>+ </CustomContextMenu></DropdownMenuContent></DropdownMenu></div>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 53675ad4cc..4e07010d64 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1395,6 +1395,12 @@ export default {resultRuns: "Result runs",resultSets: "Result sets",removeRun: "Remove run {n}",+ pinResultRun: "Pin result tab",+ unpinResultRun: "Unpin result tab",+ unpinAllResultRuns: "Unpin all result tabs",+ closeOtherResultRuns: "Close other result tabs",+ closeResultRunsToLeft: "Close result tabs to the left",+ closeResultRunsToRight: "Close result tabs to the right",closeResult: "Close result",autoKeepResults: "Auto-keep query results",autoKeepResultsEnabled: "Auto-keep results enabled",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 5584f8d7d3..8b426e12a4 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1372,6 +1372,12 @@ export default withEnglishFallback({resultRuns: "Ejecuciones de resultado",resultSets: "Conjuntos de resultados",removeRun: "Eliminar ejecución {n}",+ pinResultRun: "Fijar pestaña de resultado",+ unpinResultRun: "Desfijar pestaña de resultado",+ unpinAllResultRuns: "Desfijar todas las pestañas de resultado",+ closeOtherResultRuns: "Cerrar otras pestañas de resultado",+ closeResultRunsToLeft: "Cerrar pestañas de resultado a la izquierda",+ closeResultRunsToRight: "Cerrar pestañas de resultado a la derecha",closeResult: "Cerrar resultado",autoKeepResults: "Conservar resultados automáticamente",autoKeepResultsEnabled: "Conservación automática activada",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex a98f73668b..be6c1a96d4 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1370,6 +1370,12 @@ export default withEnglishFallback({resultRuns: "Esecuzioni risultati",resultSets: "Set di risultati",removeRun: "Rimuovi esecuzione {n}",+ pinResultRun: "Fissa scheda risultato",+ unpinResultRun: "Sblocca scheda risultato",+ unpinAllResultRuns: "Sblocca tutte le schede risultato",+ closeOtherResultRuns: "Chiudi le altre schede risultato",+ closeResultRunsToLeft: "Chiudi le schede risultato a sinistra",+ closeResultRunsToRight: "Chiudi le schede risultato a destra",closeResult: "Chiudi risultato",autoKeepResults: "Mantieni automaticamente i risultati",autoKeepResultsEnabled: "Mantieni risultati abilitato",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 2dbda5f705..7b49a93371 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1389,6 +1389,12 @@ export default withEnglishFallback({resultRuns: "実行履歴",resultSets: "結果セット",removeRun: "実行 {n} を削除",+ pinResultRun: "結果タブを固定",+ unpinResultRun: "結果タブの固定を解除",+ unpinAllResultRuns: "すべての結果タブの固定を解除",+ closeOtherResultRuns: "他の結果タブを閉じる",+ closeResultRunsToLeft: "左側の結果タブを閉じる",+ closeResultRunsToRight: "右側の結果タブを閉じる",closeResult: "結果を閉じる",autoKeepResults: "クエリ結果を自動保持",autoKeepResultsEnabled: "結果の自動保持をオンにしました",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 8a40c79e6d..acde7e3552 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1276,6 +1276,12 @@ export default withEnglishFallback({resultRuns: "결과 실행",resultSets: "결과 집합",removeRun: "실행 {n} 제거",+ pinResultRun: "결과 탭 고정",+ unpinResultRun: "결과 탭 고정 해제",+ unpinAllResultRuns: "모든 결과 탭 고정 해제",+ closeOtherResultRuns: "다른 결과 탭 닫기",+ closeResultRunsToLeft: "왼쪽 결과 탭 닫기",+ closeResultRunsToRight: "오른쪽 결과 탭 닫기",closeResult: "결과 닫기",autoKeepResults: "쿼리 결과 자동 보관",autoKeepResultsEnabled: "결과 자동 보관 활성화됨",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 7c95f8735a..3cc0020345 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1372,6 +1372,12 @@ export default withEnglishFallback({resultRuns: "Execuções de resultado",resultSets: "Conjuntos de resultados",removeRun: "Remover execução {n}",+ pinResultRun: "Fixar aba de resultado",+ unpinResultRun: "Desafixar aba de resultado",+ unpinAllResultRuns: "Desafixar todas as abas de resultado",+ closeOtherResultRuns: "Fechar outras abas de resultado",+ closeResultRunsToLeft: "Fechar abas de resultado à esquerda",+ closeResultRunsToRight: "Fechar abas de resultado à direita",closeResult: "Fechar resultado",autoKeepResults: "Manter resultados automaticamente",autoKeepResultsEnabled: "Manutenção automática de resultados ativada",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex c073f15094..eb2f1f2b12 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1319,6 +1319,12 @@ export default withEnglishFallback({resultRuns: "执行结果",resultSets: "语句结果",removeRun: "删除执行 {n}",+ pinResultRun: "固定结果标签",+ unpinResultRun: "取消固定结果标签",+ unpinAllResultRuns: "取消固定所有结果标签",+ closeOtherResultRuns: "关闭其他结果标签",+ closeResultRunsToLeft: "关闭左侧结果标签",+ closeResultRunsToRight: "关闭右侧结果标签",closeResult: "关闭结果",autoKeepResults: "自动保留查询结果",autoKeepResultsEnabled: "已开启自动保留结果",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex bf6c922a0c..6e6499c709 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1371,6 +1371,12 @@ export default withEnglishFallback({resultRuns: "執行結果",resultSets: "語句結果",removeRun: "移除執行 {n}",+ pinResultRun: "釘選結果分頁",+ unpinResultRun: "取消釘選結果分頁",+ unpinAllResultRuns: "取消釘選所有結果分頁",+ closeOtherResultRuns: "關閉其他結果分頁",+ closeResultRunsToLeft: "關閉左側結果分頁",+ closeResultRunsToRight: "關閉右側結果分頁",closeResult: "關閉結果",autoKeepResults: "自動保留查詢結果",autoKeepResultsEnabled: "自動保留結果已啟用",diff --git a/apps/desktop/src/lib/app/openTabsPersistence.ts b/apps/desktop/src/lib/app/openTabsPersistence.tsindex 4a32024dd0..c93bd6827f 100644--- a/apps/desktop/src/lib/app/openTabsPersistence.ts+++ b/apps/desktop/src/lib/app/openTabsPersistence.ts@@ -9,6 +9,7 @@ export interface SavedQueryResultRun {sequence: number;sql: string;createdAt: number;+ pinned?: boolean;activeResultIndex?: number;resultCacheKey?: string;resultEvicted?: boolean;@@ -138,6 +139,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {sequence: run.sequence,sql: run.sql,createdAt: run.createdAt,+ ...(run.pinned ? { pinned: true } : {}),activeResultIndex: run.activeResultIndex,...(run.resultCacheKey !== undefined ? { resultCacheKey: run.resultCacheKey } : {}),...(run.resultEvicted ? { resultEvicted: true } : {}),diff --git a/apps/desktop/src/lib/tabs/tabPresentation.ts b/apps/desktop/src/lib/tabs/tabPresentation.tsindex 52191bcdab..e5397c70e1 100644--- a/apps/desktop/src/lib/tabs/tabPresentation.ts+++ b/apps/desktop/src/lib/tabs/tabPresentation.ts@@ -344,12 +344,13 @@ export function activeResultRun(tab: Pick<QueryTab, "resultRuns" | "activeResultreturn tab.resultRuns?.find((run) => run.id === tab.activeResultRunId);}-export function resultRunItems(tab: Pick<QueryTab, "resultRuns" | "activeResultRunId">): { id: string; title: string; sequence: number; active: boolean }[] {+export function resultRunItems(tab: Pick<QueryTab, "resultRuns" | "activeResultRunId">): { id: string; title: string; sequence: number; active: boolean; pinned: boolean }[] {return (tab.resultRuns ?? []).map((run) => ({id: run.id,title: run.title,sequence: run.sequence,active: run.id === tab.activeResultRunId,+ pinned: run.pinned === true,}));}diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 4de924e0ad..9b8a3ebcc4 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -1117,9 +1117,18 @@ export const useQueryStore = defineStore("query", () => {{...run,...snapshotRun,+ id: run.id,+ title: run.title,+ sequence: run.sequence,+ sql: run.sql,+ createdAt: run.createdAt,+ pinned: run.pinned,+ activeResultIndex: run.activeResultIndex,+ resultCacheKey: run.resultCacheKey ?? snapshotRun.resultCacheKey,result: snapshotRun.result ? markQueryResultRowsRaw(snapshotRun.result) : undefined,results: snapshotRun.results ? markQueryResultsRowsRaw(snapshotRun.results) : undefined,resultCacheState: "memory" as const,+ resultEvicted: undefined,// 快照编解码会重建负载(如省略 session_id),落盘前的估算值不再对应// 恢复后的对象,置空以便 projectResultRun 按当前负载重算resultEstimatedBytes: undefined,@@ -1129,14 +1138,79 @@ export const useQueryStore = defineStore("query", () => {return restoredRun;}- async function setActiveResultRun(id: string, runId: string) {+ async function setActiveResultRun(id: string, runId: string, options: { evictInactive?: boolean } = {}) {const tab = findExecutionTab(id);if (!tab) return false;const existingRun = tab.resultRuns?.find((item) => item.id === runId);const run = existingRun && resultRunHasPayload(existingRun) ? existingRun : await restoreResultRunPayload(tab, runId);if (!run?.result && !run?.results?.length) return false;projectResultRun(tab, run);- evictInactiveResultRunPayloads(tab);+ if (options.evictInactive !== false) evictInactiveResultRunPayloads(tab);+ return true;+ }++ function toggleResultRunPinned(id: string, runId: string): boolean | undefined {+ const tab = tabs.value.find((item) => item.id === id);+ const runIndex = tab?.resultRuns?.findIndex((run) => run.id === runId) ?? -1;+ if (!tab?.resultRuns || runIndex < 0) return undefined;++ const run = { ...tab.resultRuns[runIndex]!, pinned: tab.resultRuns[runIndex]!.pinned ? undefined : true };+ tab.resultRuns[runIndex] = run;+ void persistResultRun(tab, run);+ return run.pinned === true;+ }++ function unpinAllResultRuns(id: string): number {+ const tab = tabs.value.find((item) => item.id === id);+ if (!tab?.resultRuns?.length) return 0;++ let changed = 0;+ tab.resultRuns = tab.resultRuns.map((run) => {+ if (!run.pinned) return run;+ changed += 1;+ const updated = { ...run, pinned: undefined };+ void persistResultRun(tab, updated);+ return updated;+ });+ return changed;+ }++ async function closeOtherResultRuns(id: string, keepRunId: string): Promise<boolean> {+ const tab = tabs.value.find((item) => item.id === id);+ if (!tab?.resultRuns?.some((run) => run.id === keepRunId)) return false;++ const runIds = tab.resultRuns.filter((run) => run.id !== keepRunId).map((run) => run.id);+ if (runIds.length === 0) return false;+ // Do not delete otherwise usable runs until the run the user chose to keep+ // has been restored successfully. Disk-backed snapshots can be unavailable.+ if (!(await setActiveResultRun(id, keepRunId, { evictInactive: false }))) return false;+ for (const runId of runIds) {+ await removeResultRun(id, runId);+ }+ return true;+ }++ async function closeResultRunsToLeft(id: string, runId: string): Promise<boolean> {+ const tab = tabs.value.find((item) => item.id === id);+ const runIndex = tab?.resultRuns?.findIndex((run) => run.id === runId) ?? -1;+ if (!tab?.resultRuns || runIndex <= 0) return false;++ if (!(await setActiveResultRun(id, runId, { evictInactive: false }))) return false;+ for (const run of tab.resultRuns.slice(0, runIndex)) {+ await removeResultRun(id, run.id);+ }+ return true;+ }++ async function closeResultRunsToRight(id: string, runId: string): Promise<boolean> {+ const tab = tabs.value.find((item) => item.id === id);+ const runIndex = tab?.resultRuns?.findIndex((run) => run.id === runId) ?? -1;+ if (!tab?.resultRuns || runIndex < 0 || runIndex >= tab.resultRuns.length - 1) return false;++ if (!(await setActiveResultRun(id, runId, { evictInactive: false }))) return false;+ for (const run of tab.resultRuns.slice(runIndex + 1)) {+ await removeResultRun(id, run.id);+ }return true;}@@ -1230,6 +1304,9 @@ export const useQueryStore = defineStore("query", () => {}function persistResultRun(tab: QueryTab, run: NonNullable<QueryTab["resultRuns"]>[number]): Promise<boolean> {+ // An evicted run only has metadata in memory. Writing it back here would+ // replace its valid disk snapshot with an empty payload.+ if (!resultRunHasPayload(run)) return Promise.resolve(false);const key = run.resultCacheKey ?? resultRunCacheKey(tab.id, run.id);run.resultCacheKey = key;run.resultCacheState = "memory";@@ -1616,6 +1693,20 @@ export const useQueryStore = defineStore("query", () => {mongoEditTarget: t.mongoEditTarget,resultEvicted: t.resultEvicted,resultCacheKey: t.resultCacheKey,+ // Keep the watch dependency limited to the metadata that is serialized+ // for each result run, without tracking the potentially large payload.+ resultRuns: t.resultRuns?.map((run) => ({+ id: run.id,+ title: run.title,+ sequence: run.sequence,+ sql: run.sql,+ createdAt: run.createdAt,+ pinned: run.pinned,+ activeResultIndex: run.activeResultIndex,+ resultCacheKey: run.resultCacheKey,+ resultEvicted: run.resultEvicted,+ })),+ activeResultRunId: t.activeResultRunId,})),);@@ -4238,7 +4329,26 @@ export const useQueryStore = defineStore("query", () => {if (!tab || !sql.trim()) return;const openInNewResultTab = tab.mode === "query" && options?.openInNewResultTab === true;- const captureResultRun = openInNewResultTab;+ // Auto-saved results need two independent decisions: keep the currently+ // displayed run visible while the request is pending, then capture the new+ // response as another run. Previously `resultAutoSave` only made the latter+ // decision after clearing the displayed payload, which caused the result+ // toolbar and grid to briefly disappear before the next Run was added.+ const captureAutoSavedResultRun = tab.mode === "query" && tab.resultAutoSave === true && !!tab.activeResultRunId && !!tab.result;+ let captureResultRun = openInNewResultTab || captureAutoSavedResultRun;+ if (!captureResultRun && tab.mode === "query" && !tab.resultAutoSave && tab.activeResultRunId) {+ const activeRun = tab.resultRuns?.find((run) => run.id === tab.activeResultRunId);+ if (activeRun?.pinned) {+ const reusableRun = tab.resultRuns?.find((run) => !run.pinned);+ if (reusableRun) {+ // A stale disk snapshot must not make us fall back to overwriting+ // the pinned active run. Capture a fresh run instead.+ captureResultRun = !(await setActiveResultRun(id, reusableRun.id));+ } else {+ captureResultRun = true;+ }+ }+ }if (captureResultRun && tab.activeResultRunId && !tab.result) {await setActiveResultRun(id, tab.activeResultRunId);if (findExecutionTab(id) !== tab) return false;@@ -4278,7 +4388,7 @@ export const useQueryStore = defineStore("query", () => {tab.batchSqlExecution = undefined;liveBatchSqlExecutions.delete(tab);}- const preserveResultDuringExecution = batchResume !== undefined || options?.preserveResultDuringExecution === true || (tab.mode === "query" && !!tab.activeResultRunId && !tab.resultAutoSave && !captureResultRun);+ const preserveResultDuringExecution = batchResume !== undefined || options?.preserveResultDuringExecution === true || captureAutoSavedResultRun || (tab.mode === "query" && !!tab.activeResultRunId && !tab.resultAutoSave && !captureResultRun);const updateActiveResultRun = !!tab.activeResultRunId && preserveResultDuringExecution;if (!updateActiveResultRun) {tab.activeResultRunId = undefined;@@ -5299,7 +5409,9 @@ export const useQueryStore = defineStore("query", () => {current.resultTotalRowCountLoading = false;touchResult(current);producedResult = true;- syncDisplayedResultRun(current, queryBaseSql, openInNewResultTab);+ // When a pinned result requires a new run, errors must use that same+ // run instead of being replaced by the retained pinned result below.+ syncDisplayedResultRun(current, queryBaseSql, captureResultRun);}} finally {if (tableDataNativeSelectionBlockOwner) finishDataGridNativeSelectionBlock(tableDataNativeSelectionBlockOwner);@@ -6469,6 +6581,11 @@ export const useQueryStore = defineStore("query", () => {invalidateResultEstimateForPayload,toggleResultAutoSave,setActiveResultRun,+ toggleResultRunPinned,+ unpinAllResultRuns,+ closeOtherResultRuns,+ closeResultRunsToLeft,+ closeResultRunsToRight,removeResultRun,closeQueryResult,clearQueryResults,diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex bc2e39fefc..9703697af3 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -793,6 +793,8 @@ export interface QueryResultRun {sequence: number;sql: string;createdAt: number;+ /** Keeps this result from being replaced by an ordinary query execution. */+ pinned?: boolean;/** Distinguishes successive result payloads that reuse the same run slot. */resultGridRevision?: string;result?: QueryResult;diff --git a/packages/app-tests/openTabsPersistence.test.ts b/packages/app-tests/openTabsPersistence.test.tsindex 8f51e24304..e71676ba0f 100644--- a/packages/app-tests/openTabsPersistence.test.ts+++ b/packages/app-tests/openTabsPersistence.test.ts@@ -179,6 +179,7 @@ test("serializes query result run metadata without row payloads", () => {sequence: 1,sql: "select 1",createdAt: 100,+ pinned: true,result: {columns: ["id"],rows: [[1]],@@ -200,6 +201,7 @@ test("serializes query result run metadata without row payloads", () => {sequence: 1,sql: "select 1",createdAt: 100,+ pinned: true,activeResultIndex: undefined,resultCacheKey: "tab:tab-1:run:run-1",resultEvicted: true,@@ -221,6 +223,7 @@ test("restores query result run metadata as disk-backed runtime state", () => {sequence: 1,sql: "select 1",createdAt: 100,+ pinned: true,resultCacheKey: "tab:tab-1:run:run-1",resultEvicted: true,},@@ -234,6 +237,7 @@ test("restores query result run metadata as disk-backed runtime state", () => {assert.equal(restored.tabs[0]?.resultRuns?.[0]?.id, "run-1");assert.equal(restored.tabs[0]?.resultRuns?.[0]?.resultCacheState, "disk");assert.equal(restored.tabs[0]?.resultRuns?.[0]?.result, undefined);+ assert.equal(restored.tabs[0]?.resultRuns?.[0]?.pinned, true);});test("ignores legacy table data result cache handles on restore", () => {diff --git a/packages/app-tests/queryResultToolbar.test.ts b/packages/app-tests/queryResultToolbar.test.tsindex 8da9b7f234..16b0df5df4 100644--- a/packages/app-tests/queryResultToolbar.test.ts+++ b/packages/app-tests/queryResultToolbar.test.ts@@ -80,6 +80,22 @@ test("ContentArea exposes retained result runs as switchable tabs or a compact lassert.equal((contentArea.match(/<QueryResultToolbarActions\b/g) ?? []).length, 2);});+test("appending a result run preserves the tab-strip scroll position", () => {+ const contentArea = source(contentAreaPath);+ const resultRunWatcherStart = contentArea.indexOf("function resultRunIdsWereAppended");+ const resultRunWatcherEnd = contentArea.indexOf("const summaryItems", resultRunWatcherStart);+ const resultRunWatcher = contentArea.slice(resultRunWatcherStart, resultRunWatcherEnd);++ assert.ok(resultRunWatcherStart >= 0);+ assert.match(resultRunWatcher, /current\.length > previous\.length/);+ assert.match(resultRunWatcher, /activeRunId: props\.activeTab\.activeResultRunId/);+ assert.match(resultRunWatcher, /activeRunChanged && !resultRunIdsWereAppended\(previous\.runIds, current\.runIds\)/);+ assert.match(resultRunWatcher, /updateResultTabsAfterRender/);+ assert.match(resultRunWatcher, /revealActiveResultRunAfterRender/);+ assert.match(contentArea, /function focusResultRunByIndex[\s\S]*scrollIntoView/);+ assert.match(contentArea, /async function removeResultRun[\s\S]*scrollIntoView/);+});+test("the close-tab shortcut clears query results before closing the tab", () => {const app = source(appPath);const closeShortcutStart = app.indexOf("if (isCloseTabShortcut(e, shortcuts))");diff --git a/packages/app-tests/queryStore.test.ts b/packages/app-tests/queryStore.test.tsindex 637959c4a0..0d3e2e01d6 100644--- a/packages/app-tests/queryStore.test.ts+++ b/packages/app-tests/queryStore.test.ts@@ -1418,6 +1418,239 @@ test("removing the active result run selects an adjacent run", async () => {assert.deepEqual(tab.result?.columns, ["one"]);});+test("pins result runs independently and can unpin all runs", () => {+ setActivePinia(createPinia());+ const store = useQueryStore();+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);++ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1 },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, pinned: true },+ ];++ assert.equal(store.toggleResultRunPinned(tabId, "run-1"), true);+ assert.equal(tab.resultRuns?.[0]?.pinned, true);+ assert.equal(store.unpinAllResultRuns(tabId), 2);+ assert.deepEqual(+ tab.resultRuns?.map((run) => run.pinned),+ [undefined, undefined],+ );+});++test("changing the pin state preserves an evicted result cache", () => {+ setActivePinia(createPinia());+ const store = useQueryStore();+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);++ tab.resultRuns = [+ {+ id: "run-1",+ title: "Run 1",+ sequence: 1,+ sql: "select 1",+ createdAt: 1,+ resultCacheKey: "tab:tab-1:run:run-1",+ resultCacheState: "disk",+ resultEvicted: true,+ },+ ];++ assert.equal(store.toggleResultRunPinned(tabId, "run-1"), true);+ assert.equal(tab.resultRuns?.[0]?.pinned, true);+ assert.equal(tab.resultRuns?.[0]?.resultCacheKey, "tab:tab-1:run:run-1");+ assert.equal(tab.resultRuns?.[0]?.resultCacheState, "disk");+ assert.equal(tab.resultRuns?.[0]?.resultEvicted, true);+ assert.equal(store.toggleResultRunPinned(tabId, "run-1"), false);+ assert.equal(tab.resultRuns?.[0]?.pinned, undefined);+ assert.equal(tab.resultRuns?.[0]?.resultCacheKey, "tab:tab-1:run:run-1");+ assert.equal(tab.resultRuns?.[0]?.resultCacheState, "disk");+ assert.equal(tab.resultRuns?.[0]?.resultEvicted, true);+});++test("result run pin and close state persist across a restart", async () => {+ const restoreStorage = installMemoryStorage();+ try {+ setActivePinia(createPinia());+ let store = useQueryStore();+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);+ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1, result: { columns: ["one"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, result: { columns: ["two"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 } },+ ];+ await store.setActiveResultRun(tabId, "run-1");+ await store.flushPendingPersist();++ assert.equal(store.toggleResultRunPinned(tabId, "run-1"), true);+ await waitFor(() => {+ const saved = JSON.parse(localStorage.getItem("dbx-app-state:open_tabs") ?? "null");+ return saved?.tabs?.[0]?.resultRuns?.[0]?.pinned === true;+ });+ assert.equal(await store.closeOtherResultRuns(tabId, "run-1"), true);+ await waitFor(() => {+ const saved = JSON.parse(localStorage.getItem("dbx-app-state:open_tabs") ?? "null");+ return saved?.tabs?.[0]?.resultRuns?.length === 1;+ });++ setActivePinia(createPinia());+ store = useQueryStore();+ await store.initOpenTabs();+ const restored = store.tabs.find((item) => item.id === tabId);+ assert.deepEqual(restored?.resultRuns?.map((run) => run.id), ["run-1"]);+ assert.equal(restored?.resultRuns?.[0]?.pinned, true);+ } finally {+ restoreStorage();+ }+});++test("closing other result runs preserves the selected run", async () => {+ setActivePinia(createPinia());+ const store = useQueryStore();+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);++ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1, result: { columns: ["one"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, pinned: true, result: { columns: ["two"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-3", title: "Run 3", sequence: 3, sql: "select 3", createdAt: 3, result: { columns: ["three"], rows: [[3]], affected_rows: 0, execution_time_ms: 1 } },+ ];+ await store.setActiveResultRun(tabId, "run-1");++ assert.equal(await store.closeOtherResultRuns(tabId, "run-2"), true);+ assert.deepEqual(+ tab.resultRuns?.map((run) => run.id),+ ["run-2"],+ );+ assert.equal(tab.activeResultRunId, "run-2");+ assert.deepEqual(tab.result?.rows, [[2]]);+});++test("bulk result-run close leaves all runs untouched when the selected run is unavailable", async () => {+ setActivePinia(createPinia());+ const store = useQueryStore();+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);+ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1, result: { columns: ["one"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, resultCacheKey: `missing-result-run-${Date.now()}`, resultCacheState: "disk", resultEvicted: true },+ { id: "run-3", title: "Run 3", sequence: 3, sql: "select 3", createdAt: 3, result: { columns: ["three"], rows: [[3]], affected_rows: 0, execution_time_ms: 1 } },+ ];+ await store.setActiveResultRun(tabId, "run-1");++ assert.equal(await store.closeOtherResultRuns(tabId, "run-2"), false);+ assert.equal(await store.closeResultRunsToLeft(tabId, "run-2"), false);+ assert.equal(await store.closeResultRunsToRight(tabId, "run-2"), false);+ assert.deepEqual(tab.resultRuns?.map((run) => run.id), ["run-1", "run-2", "run-3"]);+ assert.equal(tab.activeResultRunId, "run-1");+ assert.deepEqual(tab.result?.rows, [[1]]);+});++test("bulk result-run close does not rewrite a deleted session-backed snapshot", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;+ let releaseSessionClose: (() => void) | undefined;+ const sessionCloseGate = new Promise<void>((resolve) => {+ releaseSessionClose = resolve;+ });+ let sessionCloseRequests = 0;+ let cacheWrites = 0;+ const deletedCacheKeys: string[] = [];++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/close-session") {+ sessionCloseRequests += 1;+ await sessionCloseGate;+ return new Response(JSON.stringify(true), { status: 200, headers: { "Content-Type": "application/json" } });+ }+ if (url === "/api/tab-runtime-cache" && init?.method === "POST") {+ cacheWrites += 1;+ return new Response(JSON.stringify(true), { status: 200, headers: { "Content-Type": "application/json" } });+ }+ if (url.startsWith("/api/tab-runtime-cache?")) {+ if (init?.method === "DELETE") {+ deletedCacheKeys.push(new URL(url, "http://localhost").searchParams.get("key") ?? "");+ return new Response(JSON.stringify(true), { status: 200, headers: { "Content-Type": "application/json" } });+ }+ return new Response("null", { status: 200, headers: { "Content-Type": "application/json" } });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);+ const removedRun = {+ id: "run-1",+ title: "Run 1",+ sequence: 1,+ sql: "select 1",+ createdAt: 1,+ result: { columns: ["one"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 },+ resultSessionId: "session-1",+ resultCacheKey: "tab:tab-1:run:run-1",+ };+ tab.resultRuns = [+ removedRun,+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, result: { columns: ["two"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 } },+ ];+ tab.activeResultRunId = removedRun.id;+ tab.result = removedRun.result;+ tab.resultSessionId = removedRun.resultSessionId;+ tab.resultCacheKey = removedRun.resultCacheKey;++ assert.equal(await store.closeOtherResultRuns(tabId, "run-2"), true);+ await waitFor(() => sessionCloseRequests === 1);+ assert.deepEqual(deletedCacheKeys, ["tab:tab-1:run:run-1"]);++ releaseSessionClose?.();+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(cacheWrites, 0);+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("closes only result runs to the requested side", async () => {+ setActivePinia(createPinia());+ const store = useQueryStore();+ const tabId = store.createTab("conn-1", "db");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);++ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1, result: { columns: ["one"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, result: { columns: ["two"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-3", title: "Run 3", sequence: 3, sql: "select 3", createdAt: 3, result: { columns: ["three"], rows: [[3]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-4", title: "Run 4", sequence: 4, sql: "select 4", createdAt: 4, result: { columns: ["four"], rows: [[4]], affected_rows: 0, execution_time_ms: 1 } },+ ];+ await store.setActiveResultRun(tabId, "run-1");++ assert.equal(await store.closeResultRunsToLeft(tabId, "run-3"), true);+ assert.deepEqual(+ tab.resultRuns?.map((run) => run.id),+ ["run-3", "run-4"],+ );+ assert.equal(await store.closeResultRunsToRight(tabId, "run-3"), true);+ assert.deepEqual(+ tab.resultRuns?.map((run) => run.id),+ ["run-3"],+ );+});+test("closing an ordinary query result preserves the query tab", async () => {setActivePinia(createPinia());const store = useQueryStore();@@ -1661,6 +1894,316 @@ test("completed query executions append result runs and select the latest run",}});+test("auto-saved result stays visible until the next run is ready", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;+ let executeCount = 0;+ let resolveSecondExecution: ((response: Response) => void) | undefined;+ let secondExecutionStarted: (() => void) | undefined;+ const secondExecutionStartedPromise = new Promise<void>((resolve) => {+ secondExecutionStarted = resolve;+ });++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(JSON.stringify({ sqlToExecute: body.options.sql, useAgentResultSession: false }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/execute-multi") {+ executeCount++;+ if (executeCount === 2) {+ secondExecutionStarted?.();+ return await new Promise<Response>((resolve) => {+ resolveSecondExecution = resolve;+ });+ }+ return new Response(JSON.stringify([{ columns: ["run_1"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/analyze-editability") {+ return new Response(JSON.stringify({ editable: false, reason: "complex-source" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "db", "Query");+ store.toggleResultAutoSave(tabId);+ await store.executeTabSql(tabId, "select 1");++ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab?.resultRuns?.[0]);+ const firstRunId = tab.resultRuns[0].id;+ const execution = store.executeTabSql(tabId, "select 2");+ await secondExecutionStartedPromise;++ assert.equal(tab.activeResultRunId, firstRunId);+ assert.equal(tab.resultRuns?.length, 1);+ assert.deepEqual(tab.result?.columns, ["run_1"]);+ assert.deepEqual(tab.resultRuns?.[0]?.result?.rows, [[1]]);++ resolveSecondExecution?.(new Response(JSON.stringify([{ columns: ["run_2"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 }]), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }));+ await execution;++ assert.equal(tab.resultRuns?.length, 2);+ assert.deepEqual(tab.resultRuns?.[0]?.result?.columns, ["run_1"]);+ assert.deepEqual(tab.result?.columns, ["run_2"]);+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("canceling an auto-saved execution restores the displayed run", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;+ let executeCount = 0;+ let rejectSecondExecution: ((error: Error) => void) | undefined;+ let secondExecutionStarted: (() => void) | undefined;+ const secondExecutionStartedPromise = new Promise<void>((resolve) => {+ secondExecutionStarted = resolve;+ });++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(JSON.stringify({ sqlToExecute: body.options.sql, useAgentResultSession: false }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/execute-multi") {+ executeCount++;+ if (executeCount === 2) {+ secondExecutionStarted?.();+ return await new Promise<Response>((_resolve, reject) => {+ rejectSecondExecution = reject;+ });+ }+ return new Response(JSON.stringify([{ columns: ["run_1"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/cancel") {+ rejectSecondExecution?.(new Error("Query canceled"));+ return new Response(JSON.stringify(true), { status: 200, headers: { "Content-Type": "application/json" } });+ }+ if (url === "/api/query/analyze-editability") {+ return new Response(JSON.stringify({ editable: false, reason: "complex-source" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "db", "Query");+ store.toggleResultAutoSave(tabId);+ await store.executeTabSql(tabId, "select 1");++ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab?.resultRuns?.[0]);+ const firstRunId = tab.resultRuns[0].id;+ const execution = store.executeTabSql(tabId, "select 2");+ await secondExecutionStartedPromise;+ assert.equal(await store.cancelTabExecution(tabId), true);+ await execution;++ assert.equal(tab.activeResultRunId, firstRunId);+ assert.equal(tab.resultRuns?.length, 1);+ assert.deepEqual(tab.result?.columns, ["run_1"]);+ assert.deepEqual(tab.resultRuns?.[0]?.result?.rows, [[1]]);+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("a failed auto-saved execution keeps the prior run and adds an error run", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;+ let executeCount = 0;++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(JSON.stringify({ sqlToExecute: body.options.sql, useAgentResultSession: false }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/execute-multi") {+ executeCount++;+ if (executeCount === 2) return new Response("backend exploded", { status: 500 });+ return new Response(JSON.stringify([{ columns: ["run_1"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/analyze-editability") {+ return new Response(JSON.stringify({ editable: false, reason: "complex-source" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "db", "Query");+ store.toggleResultAutoSave(tabId);+ await store.executeTabSql(tabId, "select 1");+ await store.executeTabSql(tabId, "select broken");++ const tab = store.tabs.find((item) => item.id === tabId);+ assert.equal(tab?.resultRuns?.length, 2);+ assert.deepEqual(tab?.resultRuns?.[0]?.result?.columns, ["run_1"]);+ assert.deepEqual(tab?.result?.columns, ["Error"]);+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("an unavailable reusable result run does not overwrite the pinned active result", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(JSON.stringify({ sqlToExecute: body.options.sql, useAgentResultSession: false }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/execute-multi") {+ return new Response(JSON.stringify([{ columns: ["fresh"], rows: [[3]], affected_rows: 0, execution_time_ms: 1 }]), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/analyze-editability") {+ return new Response(JSON.stringify({ editable: false, reason: "complex-source" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url.startsWith("/api/tab-runtime-cache?")) {+ return new Response("null", { status: 200, headers: { "Content-Type": "application/json" } });+ }+ if (url === "/api/tab-runtime-cache" && init?.method === "POST") {+ return new Response(JSON.stringify(true), { status: 200, headers: { "Content-Type": "application/json" } });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "db", "Query");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);+ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1, pinned: true, result: { columns: ["pinned"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, resultCacheKey: "missing-result-run", resultCacheState: "disk", resultEvicted: true },+ ];+ await store.setActiveResultRun(tabId, "run-1");++ await store.executeTabSql(tabId, "select 3");++ assert.equal(tab.resultRuns?.length, 3);+ assert.deepEqual(tab.resultRuns?.[0]?.result?.rows, [[1]]);+ assert.notEqual(tab.activeResultRunId, "run-1");+ assert.deepEqual(tab.result?.columns, ["fresh"]);+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("a failed execution keeps the pinned result and captures its error separately", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(JSON.stringify({ sqlToExecute: body.options.sql, useAgentResultSession: false }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/execute-multi") {+ return new Response("backend exploded", { status: 500 });+ }+ if (url.startsWith("/api/tab-runtime-cache?")) {+ return new Response("null", { status: 200, headers: { "Content-Type": "application/json" } });+ }+ if (url === "/api/tab-runtime-cache" && init?.method === "POST") {+ return new Response(JSON.stringify(true), { status: 200, headers: { "Content-Type": "application/json" } });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "db", "Query");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);+ tab.resultRuns = [+ { id: "run-1", title: "Run 1", sequence: 1, sql: "select 1", createdAt: 1, pinned: true, result: { columns: ["pinned"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } },+ { id: "run-2", title: "Run 2", sequence: 2, sql: "select 2", createdAt: 2, resultCacheKey: "missing-result-run", resultCacheState: "disk", resultEvicted: true },+ ];+ await store.setActiveResultRun(tabId, "run-1");++ await store.executeTabSql(tabId, "select broken");++ assert.equal(tab.resultRuns?.length, 3);+ assert.deepEqual(tab.resultRuns?.[0]?.result?.rows, [[1]]);+ assert.notEqual(tab.activeResultRunId, "run-1");+ assert.deepEqual(tab.result?.columns, ["Error"]);+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});+test("kept result runs evict inactive payloads without losing switch or archive data", async () => {const restoreStorage = installMemoryStorage();setActivePinia(createPinia());diff --git a/packages/app-tests/tabPresentation.test.ts b/packages/app-tests/tabPresentation.test.tsindex 84578858db..c00988b839 100644--- a/packages/app-tests/tabPresentation.test.ts+++ b/packages/app-tests/tabPresentation.test.ts@@ -324,6 +324,7 @@ test("result run items expose ordered labels and active state", () => {sequence: 1,sql: "select 1",createdAt: 10,+ pinned: true,result: result(["one"]),},{@@ -338,8 +339,8 @@ test("result run items expose ordered labels and active state", () => {});assert.deepEqual(resultRunItems(tab), [- { id: "run-1", title: "Run 1", sequence: 1, active: false },- { id: "run-2", title: "Run 2", sequence: 2, active: true },+ { id: "run-1", title: "Run 1", sequence: 1, active: false, pinned: true },+ { id: "run-2", title: "Run 2", sequence: 2, active: true, pinned: false },]);assert.equal(activeResultRun(tab)?.id, "run-2");assert.deepEqual(