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(agent): support cancelling installs and upgrades

Abeautifulsnowc712be3e0239
diff --git a/apps/desktop/src/components/config/DriverStoreDialog.vue b/apps/desktop/src/components/config/DriverStoreDialog.vue
index 7811aa4ef0..cc5595c768 100644
--- a/apps/desktop/src/components/config/DriverStoreDialog.vue
+++ b/apps/desktop/src/components/config/DriverStoreDialog.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from "vue";
import { useI18n } from "vue-i18n";
-import { Activity, ExternalLink, Cpu, FolderOpen, FolderSync, MemoryStick, Search, Square, Trash2, Download, RotateCcw, Loader2, RefreshCw, Check, Clock3, FileUp } from "@lucide/vue";
+import { Activity, ExternalLink, Cpu, FolderOpen, FolderSync, MemoryStick, Search, Square, Trash2, Download, RotateCcw, Loader2, RefreshCw, Check, Clock3, FileUp, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -23,6 +23,8 @@ import {
addDriverInstallQueue,
driverInstallProgressChannel,
driverInstallProgressPercent,
+ isDriverInstallCanceledError,
+ isDriverInstallCancellationTarget,
isDriverInstallProgressForOperation,
isDriverInstallProgressTarget,
removeDriverInstallQueue,
@@ -188,11 +190,13 @@ const agentDriverSearch = ref("");
const selectedDriverCategory = ref<string>("all");
const installing = ref<string | null>(null);
const upgradingAll = ref(false);
+const preparingUpgradeAll = ref(false);
const upgradingCompletedCount = ref(0);
const upgradingTotal = ref(0);
const queuedDriverInstalls = ref<string[]>([]);
const reinstallingJre = ref<string | null>(null);
const activeAgentOperationId = ref<string | null>(null);
+const cancellableAgentInstallDbType = ref<string | null>(null);
const refreshing = ref(false);
const agentProgressByDbType = reactive<Record<string, DriverInstallProgress | null | undefined>>({});
const jdbcPluginProgress = ref<DriverInstallProgress | null>(null);
@@ -329,6 +333,15 @@ function isDriverProgressActive(dbType: string): boolean {
});
}
+function isDriverInstallCancellable(dbType: string): boolean {
+ return isDriverInstallCancellationTarget(dbType, {
+ activeOperationId: activeAgentOperationId.value,
+ cancellableDbType: cancellableAgentInstallDbType.value,
+ upgradingAll: upgradingAll.value,
+ progressMap: agentProgressByDbType,
+ });
+}
+
function driverRequiresJavaRuntime(driver: AgentDriverInfo): boolean {
return driver.requires_java_runtime ?? Boolean(driver.jre);
}
@@ -455,7 +468,7 @@ async function chooseCustomJavaPath() {
}
async function installDriver(dbType: string) {
- if (installing.value !== null || upgradingAll.value) {
+ if (installing.value !== null || preparingUpgradeAll.value || upgradingAll.value) {
queueDriverInstall(dbType);
return;
}
@@ -466,7 +479,6 @@ async function installDriver(dbType: string) {
async function runDriverInstall(dbType: string) {
const label = driverLabel(dbType);
installing.value = dbType;
- activeAgentOperationId.value = uuid();
resetAgentInstallProgress();
try {
const managedResult = await installRegisteredManagedJdbcDriver(dbType, jdbcMavenBundles.value, jdbcPluginStatus.value, api);
@@ -486,20 +498,28 @@ async function runDriverInstall(dbType: string) {
toast(t("driverStore.driverUpdateBlocked", { labels: blockers.map((blocker) => blocker.label).join(", ") }));
return;
}
- await api.installAgent(dbType, activeAgentOperationId.value);
+ const operationId = uuid();
+ activeAgentOperationId.value = operationId;
+ cancellableAgentInstallDbType.value = dbType;
+ await api.installAgent(dbType, operationId);
await refreshAgents();
toast(t("driverStore.driverInstallSuccess", { label }));
} catch (e: any) {
+ if (isDriverInstallCanceledError(e)) {
+ toast(t("driverStore.driverInstallCancelled", { label }));
+ return;
+ }
toast(t("driverStore.driverInstallFailed", { label, error: backendError(e) }));
} finally {
installing.value = null;
activeAgentOperationId.value = null;
+ cancellableAgentInstallDbType.value = null;
resetAgentInstallProgress();
}
}
async function runQueuedDriverInstalls() {
- if (installing.value !== null || upgradingAll.value) return;
+ if (installing.value !== null || preparingUpgradeAll.value || upgradingAll.value) return;
const result = takeNextDriverInstallQueue(queuedDriverInstalls.value, canInstallOrUpdateDriver);
queuedDriverInstalls.value = result.queue;
@@ -510,21 +530,29 @@ async function runQueuedDriverInstalls() {
}
async function upgradeAll() {
- upgradingAll.value = true;
- activeAgentOperationId.value = uuid();
- upgradingCompletedCount.value = 0;
- queuedDriverInstalls.value = [];
- resetAgentInstallProgress();
+ if (preparingUpgradeAll.value || upgradingAll.value) return;
+ preparingUpgradeAll.value = true;
try {
const updatableDbTypes = drivers.value.filter((driver) => driver.update_available).map((driver) => driver.db_type);
- upgradingTotal.value = updatableDbTypes.length;
const blockers = await api.checkAgentUpdateBlockers(updatableDbTypes);
if (blockers.length > 0) {
toast(t("driverStore.driverUpdateBlocked", { labels: blockers.map((blocker) => blocker.label).join(", ") }));
return;
}
+ // Do not expose Cancel until the backend operation has registered its token.
+ // Otherwise a cancel during this client-side blocker check is silently lost.
+ upgradingAll.value = true;
+ activeAgentOperationId.value = uuid();
+ upgradingCompletedCount.value = 0;
+ upgradingTotal.value = updatableDbTypes.length;
+ queuedDriverInstalls.value = [];
+ resetAgentInstallProgress();
const result = await api.upgradeAllAgents(activeAgentOperationId.value);
await refreshAgents();
+ if (result.cancelled > 0 && result.failed.length === 0) {
+ toast(t("driverStore.upgradeAllCancelled", { count: result.cancelled }));
+ return;
+ }
if (result.failed.length > 0) {
const failedLabels = result.failed.map((item) => drivers.value.find((driver) => driver.db_type === item.db_type)?.label ?? item.db_type).join(", ");
toast(t("driverStore.upgradeAllPartial", { count: result.upgraded, failed: failedLabels }));
@@ -532,8 +560,13 @@ async function upgradeAll() {
toast(t("driverStore.upgradeAllSuccess", { count: result.upgraded }));
}
} catch (e: any) {
+ if (isDriverInstallCanceledError(e)) {
+ toast(t("driverStore.upgradeAllCancelled", { count: 0 }));
+ return;
+ }
toast(t("driverStore.upgradeAllFailed", { error: backendError(e) }));
} finally {
+ preparingUpgradeAll.value = false;
upgradingAll.value = false;
activeAgentOperationId.value = null;
upgradingCompletedCount.value = 0;
@@ -542,6 +575,25 @@ async function upgradeAll() {
}
}
+/** Abort a single driver's install, whether started alone or inside a batch. */
+async function cancelDriverInstall(dbType: string) {
+ if (!isDriverInstallCancellable(dbType) || !activeAgentOperationId.value) return;
+ try {
+ await api.cancelAgentInstall(dbType, activeAgentOperationId.value);
+ } catch {
+ // A cancel that arrives after the download finished is a no-op.
+ }
+}
+
+/** Abort the whole batch upgrade: in-flight downloads stop, queued ones never start. */
+async function cancelUpgradeAll() {
+ try {
+ await api.cancelAgentUpgradeAll(activeAgentOperationId.value ?? undefined);
+ } catch {
+ // The batch may have just finished; treat a failed cancel as a no-op.
+ }
+}
+
async function uninstallDriver(dbType: string) {
const label = driverLabel(dbType);
try {
@@ -1429,11 +1481,16 @@ watch(driverStoreTab, (tab) => {
<div class="text-sm font-semibold">{{ t("driverStore.updatesAvailableTitle") }} ({{ globalUpdatableDrivers.length }})</div>
<p class="text-xs text-muted-foreground">{{ t("driverStore.updatesAvailableDescription") }}</p>
</div>
- <Button size="sm" class="h-7 rounded-md text-xs shrink-0 ml-3" :disabled="installing !== null || upgradingAll || agentImportBusy" @click="upgradeAll">
- <Loader2 v-if="upgradingAll" class="h-3 w-3 animate-spin mr-1" />
- <Download v-else class="h-3 w-3 mr-1" />
- {{ upgradingAll ? t("driverStore.upgradingProgress", { current: upgradingCompletedCount, total: upgradingTotal }) : t("driverStore.upgradeAll") }}
- </Button>
+ <div class="flex shrink-0 items-center gap-2">
+ <Button size="sm" class="h-7 rounded-md text-xs shrink-0 ml-3" :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentImportBusy" @click="upgradeAll">
+ <Loader2 v-if="upgradingAll" class="h-3 w-3 animate-spin mr-1" />
+ <Download v-else class="h-3 w-3 mr-1" />
+ {{ upgradingAll ? t("driverStore.upgradingProgress", { current: upgradingCompletedCount, total: upgradingTotal }) : t("driverStore.upgradeAll") }}
+ </Button>
+ <Button v-if="upgradingAll" type="button" variant="outline" size="icon-sm" class="h-7 w-7 rounded-md shrink-0 text-muted-foreground hover:text-destructive" :title="t('driverStore.cancelUpgradeAll')" :aria-label="t('driverStore.cancelUpgradeAll')" @click="cancelUpgradeAll">
+ <X class="h-3.5 w-3.5" />
+ </Button>
+ </div>
</div>
<div
v-for="driver in globalUpdatableDrivers"
@@ -1461,14 +1518,24 @@ watch(driverStoreTab, (tab) => {
size="sm"
variant="outline"
class="h-7 rounded-md border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy"
@click="removeQueuedDriverInstall(driver.db_type)"
>
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.installing'))" />
- <Button v-else-if="!driver.installed" size="sm" class="h-7 rounded-md text-xs" :disabled="upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
+ <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.installing'))" /><Button
+ v-if="!driver.installed && isDriverProgressActive(driver.db_type) && isDriverInstallCancellable(driver.db_type)"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="h-7 w-7 rounded-md text-muted-foreground hover:text-destructive"
+ :title="t('driverStore.cancelInstall')"
+ :aria-label="t('driverStore.cancelInstall')"
+ @click="cancelDriverInstall(driver.db_type)"
+ ><X class="h-3.5 w-3.5"
+ /></Button>
+ <Button v-else-if="!driver.installed && !isDriverProgressActive(driver.db_type)" size="sm" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
<Download class="h-3 w-3 mr-1" />
{{ t("driverStore.install") }}
</Button>
@@ -1478,7 +1545,7 @@ watch(driverStoreTab, (tab) => {
variant="ghost"
class="driver-store-local-import-button h-7 w-7 rounded-md text-xs text-muted-foreground"
:title="importingDriver === driver.db_type ? t('driverStore.importing') : t('driverStore.importLocalJar')"
- :disabled="upgradingAll || installing !== null || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || installing !== null || agentImportBusy"
@click="importDriverFile(driver)"
>
<Loader2 v-if="importingDriver === driver.db_type" class="h-3.5 w-3.5 animate-spin" />
@@ -1490,17 +1557,34 @@ watch(driverStoreTab, (tab) => {
size="sm"
variant="outline"
class="h-7 rounded-md border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy"
@click="removeQueuedDriverInstall(driver.db_type)"
>
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle v-else-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.updating'))" />
- <Button v-else-if="driver.installed && driver.update_available" size="sm" variant="outline" class="h-7 rounded-md text-xs" :disabled="upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
+ <DriverInstallProgressCircle v-else-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.updating'))" /><Button
+ v-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type) && isDriverInstallCancellable(driver.db_type)"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="h-7 w-7 rounded-md text-muted-foreground hover:text-destructive"
+ :title="t('driverStore.cancelInstall')"
+ :aria-label="t('driverStore.cancelInstall')"
+ @click="cancelDriverInstall(driver.db_type)"
+ ><X class="h-3.5 w-3.5"
+ /></Button>
+ <Button v-else-if="driver.installed && driver.update_available && !isDriverProgressActive(driver.db_type)" size="sm" variant="outline" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
{{ t("driverStore.update") }}
</Button>
- <Button v-if="driver.installed" variant="ghost" size="sm" class="h-7 rounded-md text-xs text-muted-foreground hover:text-destructive" :disabled="installing !== null || upgradingAll || agentImportBusy || isDriverQueued(driver.db_type)" @click="uninstallDriver(driver.db_type)">
+ <Button
+ v-if="driver.installed"
+ variant="ghost"
+ size="sm"
+ class="h-7 rounded-md text-xs text-muted-foreground hover:text-destructive"
+ :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentImportBusy || isDriverQueued(driver.db_type)"
+ @click="uninstallDriver(driver.db_type)"
+ >
{{ t("driverStore.uninstall") }}
</Button>
</div>
@@ -1579,14 +1663,24 @@ watch(driverStoreTab, (tab) => {
size="sm"
variant="outline"
class="h-7 rounded-md border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy"
@click="removeQueuedDriverInstall(driver.db_type)"
>
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.installing'))" />
- <Button v-else-if="!driver.installed" size="sm" class="h-7 rounded-md text-xs" :disabled="upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
+ <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.installing'))" /><Button
+ v-if="!driver.installed && isDriverProgressActive(driver.db_type) && isDriverInstallCancellable(driver.db_type)"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="h-7 w-7 rounded-md text-muted-foreground hover:text-destructive"
+ :title="t('driverStore.cancelInstall')"
+ :aria-label="t('driverStore.cancelInstall')"
+ @click="cancelDriverInstall(driver.db_type)"
+ ><X class="h-3.5 w-3.5"
+ /></Button>
+ <Button v-else-if="!driver.installed && !isDriverProgressActive(driver.db_type)" size="sm" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
<Download class="h-3 w-3 mr-1" />
{{ t("driverStore.install") }}
</Button>
@@ -1596,7 +1690,7 @@ watch(driverStoreTab, (tab) => {
variant="ghost"
class="driver-store-local-import-button h-7 w-7 rounded-md text-xs text-muted-foreground"
:title="importingDriver === driver.db_type ? t('driverStore.importing') : t('driverStore.importLocalJar')"
- :disabled="upgradingAll || installing !== null || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || installing !== null || agentImportBusy"
@click="importDriverFile(driver)"
>
<Loader2 v-if="importingDriver === driver.db_type" class="h-3.5 w-3.5 animate-spin" />
@@ -1608,14 +1702,24 @@ watch(driverStoreTab, (tab) => {
size="sm"
variant="outline"
class="h-7 rounded-md border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy"
@click="removeQueuedDriverInstall(driver.db_type)"
>
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle v-else-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.updating'))" />
- <Button v-else-if="driver.installed && driver.update_available" size="sm" variant="outline" class="h-7 rounded-md text-xs" :disabled="upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
+ <DriverInstallProgressCircle v-else-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.updating'))" /><Button
+ v-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type) && isDriverInstallCancellable(driver.db_type)"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="h-7 w-7 rounded-md text-muted-foreground hover:text-destructive"
+ :title="t('driverStore.cancelInstall')"
+ :aria-label="t('driverStore.cancelInstall')"
+ @click="cancelDriverInstall(driver.db_type)"
+ ><X class="h-3.5 w-3.5"
+ /></Button>
+ <Button v-else-if="driver.installed && driver.update_available && !isDriverProgressActive(driver.db_type)" size="sm" variant="outline" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
{{ t("driverStore.update") }}
</Button>
<Button
@@ -1623,7 +1727,7 @@ watch(driverStoreTab, (tab) => {
variant="ghost"
size="sm"
class="h-7 rounded-md text-xs text-muted-foreground hover:text-destructive"
- :disabled="installing !== null || upgradingAll || agentImportBusy || isDriverQueued(driver.db_type)"
+ :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentImportBusy || isDriverQueued(driver.db_type)"
@click="uninstallDriver(driver.db_type)"
>
{{ t("driverStore.uninstall") }}
@@ -1663,14 +1767,24 @@ watch(driverStoreTab, (tab) => {
size="sm"
variant="outline"
class="h-7 rounded-md border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy"
@click="removeQueuedDriverInstall(driver.db_type)"
>
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.installing'))" />
- <Button v-else-if="!driver.installed" size="sm" class="h-7 rounded-md text-xs" :disabled="upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
+ <DriverInstallProgressCircle v-else-if="!driver.installed && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.installing'))" /><Button
+ v-if="!driver.installed && isDriverProgressActive(driver.db_type) && isDriverInstallCancellable(driver.db_type)"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="h-7 w-7 rounded-md text-muted-foreground hover:text-destructive"
+ :title="t('driverStore.cancelInstall')"
+ :aria-label="t('driverStore.cancelInstall')"
+ @click="cancelDriverInstall(driver.db_type)"
+ ><X class="h-3.5 w-3.5"
+ /></Button>
+ <Button v-else-if="!driver.installed && !isDriverProgressActive(driver.db_type)" size="sm" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
<Download class="h-3 w-3 mr-1" />
{{ t("driverStore.install") }}
</Button>
@@ -1680,7 +1794,7 @@ watch(driverStoreTab, (tab) => {
variant="ghost"
class="driver-store-local-import-button h-7 w-7 rounded-md text-xs text-muted-foreground"
:title="importingDriver === driver.db_type ? t('driverStore.importing') : t('driverStore.importLocalJar')"
- :disabled="upgradingAll || installing !== null || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || installing !== null || agentImportBusy"
@click="importDriverFile(driver)"
>
<Loader2 v-if="importingDriver === driver.db_type" class="h-3.5 w-3.5 animate-spin" />
@@ -1692,17 +1806,34 @@ watch(driverStoreTab, (tab) => {
size="sm"
variant="outline"
class="h-7 rounded-md border-green-500/30 bg-green-500/10 text-xs text-green-700 hover:bg-green-500/15"
- :disabled="upgradingAll || agentImportBusy"
+ :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy"
@click="removeQueuedDriverInstall(driver.db_type)"
>
<Clock3 class="h-3 w-3 mr-1" />
{{ t("driverStore.queued") }}
</Button>
- <DriverInstallProgressCircle v-else-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.updating'))" />
- <Button v-else-if="driver.installed && driver.update_available" size="sm" variant="outline" class="h-7 rounded-md text-xs" :disabled="upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
+ <DriverInstallProgressCircle v-else-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type)" :percent="getAgentProgressPercent(driver.db_type)" :title="getAgentProgressTitle(driver.db_type, t('driverStore.updating'))" /><Button
+ v-if="driver.installed && driver.update_available && isDriverProgressActive(driver.db_type) && isDriverInstallCancellable(driver.db_type)"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="h-7 w-7 rounded-md text-muted-foreground hover:text-destructive"
+ :title="t('driverStore.cancelInstall')"
+ :aria-label="t('driverStore.cancelInstall')"
+ @click="cancelDriverInstall(driver.db_type)"
+ ><X class="h-3.5 w-3.5"
+ /></Button>
+ <Button v-else-if="driver.installed && driver.update_available && !isDriverProgressActive(driver.db_type)" size="sm" variant="outline" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentImportBusy" @click="installDriver(driver.db_type)">
{{ t("driverStore.update") }}
</Button>
- <Button v-if="driver.installed" variant="ghost" size="sm" class="h-7 rounded-md text-xs text-muted-foreground hover:text-destructive" :disabled="installing !== null || upgradingAll || agentImportBusy || isDriverQueued(driver.db_type)" @click="uninstallDriver(driver.db_type)">
+ <Button
+ v-if="driver.installed"
+ variant="ghost"
+ size="sm"
+ class="h-7 rounded-md text-xs text-muted-foreground hover:text-destructive"
+ :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentImportBusy || isDriverQueued(driver.db_type)"
+ @click="uninstallDriver(driver.db_type)"
+ >
{{ t("driverStore.uninstall") }}
</Button>
</div>
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index eba7066173..739616e48b 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -67,7 +67,7 @@ import { loadConnectionPickerView, saveConnectionPickerView, type DbPickerView }
import { normalizeRocketmqNamesrvAddr } from "@/lib/connection/rocketmqNamesrv";
import { normalizeRabbitmqAddresses } from "@/lib/connection/rabbitmqAddresses";
import { detectMqUiAuthKind, isMqAuthKindAllowedForSystem, type MqUiAuthKind } from "@/lib/connection/mqAuth";
-import { driverInstallProgressChannel, driverInstallProgressPercent, isDriverInstallProgressForOperation, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";
+import { driverInstallProgressChannel, driverInstallProgressPercent, isDriverInstallProgressForOperation, requestAgentInstallCancellation, resolveAgentInstallOutcome, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";
import { requiresSqlServerLegacyCompatibilityComponent, setSqlServerLegacyCompatibilityConfig, sqlServerUsesLegacyCompatibility, SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY } from "@/lib/connection/sqlServerLegacyCompatibility";
import { normalizeNacosEndpoint, normalizeNacosMetricsUrl, parseNacosManagedNamespaces } from "@/lib/nacos/nacosAdmin";
import { loadReadableNacosNamespaces, nacosNamespaceIdentity, normalizeNacosNamespaceSelection } from "@/lib/nacos/nacosNamespaceVisibility";
@@ -259,6 +259,11 @@ const agentInstallDriverKey = ref("");
const agentInstallLabel = ref("");
const agentInstallProgress = ref<DriverInstallProgress | null>(null);
const agentInstallError = ref("");
+const agentInstallCancelError = ref("");
+const agentInstallCancelling = ref(false);
+/** Set when the user cancels from the modal, so the pending promise's
+ * "canceled by user" error is treated as a non-failure by its caller. */
+const agentInstallCancelRequested = ref(false);
const showConnectionErrorDialog = ref(false);
const connectionErrorRawDetail = ref("");
const connectionErrorDetail = ref("");
@@ -1890,31 +1895,67 @@ async function refreshLocalAgentDrivers(): Promise<AgentDriverInstallState[]> {
return drivers;
}
-function beginAgentDriverInstall(driverKey: string, label: string) {
+function beginAgentDriverInstall(driverKey: string, label: string): string {
agentInstallOperationId.value = uuid();
agentInstallDriverKey.value = driverKey;
agentInstallLabel.value = label;
agentInstallProgress.value = null;
agentInstallError.value = "";
+ agentInstallCancelError.value = "";
+ agentInstallCancelling.value = false;
+ agentInstallCancelRequested.value = false;
agentInstallRunning.value = true;
showAgentInstallDialog.value = true;
+ return agentInstallOperationId.value;
}
-function finishAgentDriverInstall() {
+/**
+ * Clear the install dialog, unless a newer operation now owns it. Stale
+ * operation promises (cancelled, then retried before settling) must not
+ * finish/reset the retry's dialog state.
+ */
+function finishAgentDriverInstall(operationId?: string | null) {
+ if (operationId !== undefined && operationId !== null && agentInstallOperationId.value !== operationId) return;
agentInstallOperationId.value = null;
agentInstallRunning.value = false;
agentInstallProgress.value = null;
agentInstallError.value = "";
+ agentInstallCancelError.value = "";
+ agentInstallCancelling.value = false;
showAgentInstallDialog.value = false;
}
-function failAgentDriverInstall(error: unknown) {
+function failAgentDriverInstall(operationId: string | null | undefined, error: unknown) {
+ if (operationId !== undefined && operationId !== null && agentInstallOperationId.value !== operationId) return;
agentInstallOperationId.value = null;
agentInstallRunning.value = false;
+ agentInstallCancelError.value = "";
+ agentInstallCancelling.value = false;
agentInstallError.value = translateBackendError(t, error);
showAgentInstallDialog.value = true;
}
+/**
+ * Abort an in-flight agent driver install from the modal's Cancel button.
+ * The backend stops the download; the pending `installAgent` promise resolves
+ * with a "canceled by user" error, which callers treat as a non-failure.
+ */
+async function cancelActiveAgentInstall() {
+ const operationId = agentInstallOperationId.value;
+ if (!agentInstallDriverKey.value || !operationId || agentInstallCancelling.value) return;
+ agentInstallCancelling.value = true;
+ agentInstallCancelError.value = "";
+ const result = await requestAgentInstallCancellation(() => api.cancelAgentInstall(agentInstallDriverKey.value, operationId));
+ if (agentInstallOperationId.value !== operationId) return;
+ agentInstallCancelling.value = false;
+ if (!result.ok) {
+ agentInstallCancelError.value = translateBackendError(t, result.error);
+ return;
+ }
+ agentInstallCancelRequested.value = true;
+ finishAgentDriverInstall(operationId);
+}
+
function showConnectionError(message: string) {
connectionErrorRawDetail.value = message;
connectionErrorDetail.value = translateBackendError(t, message);
@@ -1964,14 +2005,35 @@ async function ensureRequiredAgentDriverInstalled(config: ConnectionConfig): Pro
const label = config.driver_label || driverKey;
testResult.value = { ok: true, message: `Installing ${label} driver...` };
- beginAgentDriverInstall(driverKey, label);
+ const operationId = beginAgentDriverInstall(driverKey, label);
try {
- await api.installAgent(driverKey, agentInstallOperationId.value ?? undefined);
+ await api.installAgent(driverKey, operationId);
await refreshLocalAgentDrivers();
- finishAgentDriverInstall();
+ // A stale promise (cancelled then retried) must not close the retry's dialog.
+ if (agentInstallOperationId.value === operationId) finishAgentDriverInstall(operationId);
} catch (error) {
+ const outcome = resolveAgentInstallOutcome(
+ { ok: false, error },
+ {
+ operationId,
+ currentOperationId: agentInstallOperationId.value,
+ cancelRequested: agentInstallCancelRequested.value,
+ },
+ );
+ if (outcome.kind === "cancelled") {
+ // User cancelled: close silently, do not surface a failure.
+ if (outcome.ownsState) {
+ testResult.value = null;
+ finishAgentDriverInstall(operationId);
+ }
+ return;
+ }
+ if (!outcome.ownsState) {
+ // A newer operation owns the dialog; leave its state untouched.
+ return;
+ }
testResult.value = { ok: false, message: translateBackendError(t, error) };
- failAgentDriverInstall(error);
+ failAgentDriverInstall(operationId, error);
throw error;
}
}
@@ -2019,14 +2081,32 @@ async function installSqlServerLegacyCompatibilityComponentIfNeeded(): Promise<b
if (await api.isAgentInstalled(SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY)) return true;
const label = t("connection.sqlServerLegacyCompatibilityComponent");
- beginAgentDriverInstall(SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY, label);
+ const operationId = beginAgentDriverInstall(SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY, label);
try {
- await api.installAgent(SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY, agentInstallOperationId.value ?? undefined);
+ await api.installAgent(SQLSERVER_LEGACY_COMPATIBILITY_DRIVER_KEY, operationId);
await refreshLocalAgentDrivers();
- finishAgentDriverInstall();
+ // A stale promise (cancelled then retried) must not close the retry's dialog.
+ if (agentInstallOperationId.value === operationId) finishAgentDriverInstall(operationId);
} catch (error) {
+ const outcome = resolveAgentInstallOutcome(
+ { ok: false, error },
+ {
+ operationId,
+ currentOperationId: agentInstallOperationId.value,
+ cancelRequested: agentInstallCancelRequested.value,
+ },
+ );
+ if (outcome.kind === "cancelled") {
+ // User cancelled the download: the toggle's caller falls back to `auto`.
+ if (outcome.ownsState) finishAgentDriverInstall(operationId);
+ return false;
+ }
+ if (!outcome.ownsState) {
+ // A newer operation owns the dialog; leave its state untouched.
+ return false;
+ }
testResult.value = { ok: false, message: translateBackendError(t, error) };
- failAgentDriverInstall(error);
+ failAgentDriverInstall(operationId, error);
throw error;
}
return true;
@@ -2042,7 +2122,13 @@ async function setSqlServerDriverMode(mode: "auto" | "legacy") {
}
try {
- await installSqlServerLegacyCompatibilityComponentIfNeeded();
+ const installed = await installSqlServerLegacyCompatibilityComponentIfNeeded();
+ if (!installed) {
+ // User cancelled the download: never leave the form in legacy mode
+ // without the component installed.
+ setSqlServerLegacyCompatibilityConfig(form.value, false);
+ return;
+ }
setSqlServerLegacyCompatibilityConfig(form.value, true);
testResult.value = null;
} catch {
@@ -8535,6 +8621,9 @@ function openExternalUrl(url: string) {
<div class="text-sm font-medium text-destructive">{{ t("connection.driverInstall.fullError") }}</div>
<pre class="max-h-56 min-w-0 max-w-full overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-all [overflow-wrap:anywhere] rounded-md border bg-muted/30 p-3 text-xs leading-5 text-destructive">{{ agentInstallError }}</pre>
</div>
+ <div v-else-if="agentInstallCancelError" class="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
+ {{ agentInstallCancelError }}
+ </div>
</div>
<DialogFooter class="gap-2">
@@ -8542,6 +8631,9 @@ function openExternalUrl(url: string) {
<Copy class="mr-1.5 h-3.5 w-3.5" />
{{ t("connection.copyError") }}
</Button>
+ <Button v-if="agentInstallRunning && !agentInstallError" variant="outline" :disabled="agentInstallCancelling" @click="cancelActiveAgentInstall">
+ {{ t("common.cancel") }}
+ </Button>
<Button :disabled="!canCloseAgentInstallDialog" @click="showAgentInstallDialog = false">
{{ agentInstallError ? t("common.close") : t("connection.driverInstall.installingButton") }}
</Button>
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index bad29f288f..5b6b2c0edf 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -6445,10 +6445,14 @@ export default {
chooseJavaExecutable: "Choose Java executable",
driverInstallSuccess: "{label} driver installed",
driverInstallFailed: "Failed to install {label} driver: {error}",
+ driverInstallCancelled: "{label} driver install cancelled",
driverUpdateBlocked: "Close these database connections before updating drivers: {labels}",
upgradeAllSuccess: "{count} driver(s) upgraded",
upgradeAllPartial: "{count} driver(s) upgraded. Skipped: {failed}",
upgradeAllFailed: "Batch upgrade failed: {error}",
+ upgradeAllCancelled: "Upgrade cancelled ({count} driver(s) aborted)",
+ cancelInstall: "Cancel install",
+ cancelUpgradeAll: "Cancel batch upgrade",
driverUninstallSuccess: "{label} driver uninstalled",
driverUninstallFailed: "Failed to uninstall {label} driver: {error}",
chooseOfflineDriverPackage: "Choose offline driver package",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index dcce2ec6cb..8c20f28799 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -6267,6 +6267,10 @@ export default withEnglishFallback({
driverStoreDirMigrationFailed: "Error en la migración de controladores: {error}",
driverStoreDirDialogTitle: "Seleccionar {target}",
driverStoreDirSuccess: "{target} cambiado, reiniciando…",
+ driverInstallCancelled: "Instalación del controlador {label} cancelada",
+ upgradeAllCancelled: "Actualización masiva cancelada ({count} controladores interrumpidos)",
+ cancelInstall: "Cancelar instalación",
+ cancelUpgradeAll: "Cancelar actualización masiva",
},
databaseExport: {
title: "Exportar base de datos",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index a2801e6b8c..9b8aaa912e 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -6267,6 +6267,10 @@ export default withEnglishFallback({
driverStoreDirMigrationFailed: "Migrazione driver fallita: {error}",
driverStoreDirDialogTitle: "Seleziona {target}",
driverStoreDirSuccess: "{target} cambiato, riavvio in corso…",
+ driverInstallCancelled: "{label} installazione del driver annullata",
+ upgradeAllCancelled: "Aggiornamento batch annullato ({count} driver interrotti)",
+ cancelInstall: "Annulla installazione",
+ cancelUpgradeAll: "Annulla aggiornamento batch",
},
databaseExport: {
title: "Esporta Database",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index ae30558985..14050b1dc2 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -6320,6 +6320,10 @@ export default withEnglishFallback({
driverStoreDirMigrationFailed: "ドライバーストアの移行に失敗しました: {error}",
driverStoreDirDialogTitle: "{target}を選択",
driverStoreDirSuccess: "{target}を変更しました。再起動中…",
+ driverInstallCancelled: "{label} ドライバーのインストールはキャンセルされました",
+ upgradeAllCancelled: "一括アップグレードはキャンセルされました({count} 個のドライバーが中止されました)",
+ cancelInstall: "インストールをキャンセル",
+ cancelUpgradeAll: "一括アップグレードをキャンセル",
},
databaseExport: {
runInBackground: "バックグラウンドで実行",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 05ac294343..6f4247b84d 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -6269,6 +6269,10 @@ export default withEnglishFallback({
driverStoreDirMigrationFailed: "Falha na migração de drivers: {error}",
driverStoreDirDialogTitle: "Selecionar {target}",
driverStoreDirSuccess: "{target} alterado, reiniciando…",
+ driverInstallCancelled: "{label} instalação do driver cancelada",
+ upgradeAllCancelled: "Atualização em lote cancelada ({count} drivers interrompidos)",
+ cancelInstall: "Cancelar instalação",
+ cancelUpgradeAll: "Cancelar atualização em lote",
},
databaseExport: {
title: "Exportar banco de dados",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 0350b125cb..93266bed7b 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -6430,10 +6430,14 @@ export default withEnglishFallback({
chooseJavaExecutable: "选择 Java 可执行文件",
driverInstallSuccess: "{label} 驱动安装成功",
driverInstallFailed: "{label} 驱动安装失败: {error}",
+ driverInstallCancelled: "{label} 驱动安装已取消",
driverUpdateBlocked: "请先关闭以下数据库连接后再更新驱动: {labels}",
upgradeAllSuccess: "{count} 个驱动升级完成",
upgradeAllPartial: "{count} 个驱动升级完成,以下驱动已跳过: {failed}",
upgradeAllFailed: "批量升级失败: {error}",
+ upgradeAllCancelled: "批量升级已取消({count} 个驱动中止)",
+ cancelInstall: "取消安装",
+ cancelUpgradeAll: "取消批量升级",
driverUninstallSuccess: "{label} 驱动已卸载",
driverUninstallFailed: "{label} 驱动卸载失败: {error}",
chooseOfflineDriverPackage: "选择离线驱动包",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 4d2f818002..c65acf1228 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -5591,6 +5591,10 @@ export default withEnglishFallback({
jdbcSourceMaven: "Maven",
jdbcSourceManual: "手動",
noMatchingDrivers: "沒有相符的驅動程式。",
+ driverInstallCancelled: "{label} 驅動安裝已取消",
+ upgradeAllCancelled: "批次升級已取消({count} 個驅動中止)",
+ cancelInstall: "取消安裝",
+ cancelUpgradeAll: "取消批次升級",
},
databaseExport: {
title: "匯出資料庫",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index b067cc4f26..a9613bf4f5 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -106,6 +106,8 @@ export async function upgradeAllAgents(operationId?: string) {
const backend = await getBackend();
return backend.upgradeAllAgents(useSettingsStore().editorSettings.updateDownloadSource, operationId);
}
+export const cancelAgentInstall = forward("cancelAgentInstall");
+export const cancelAgentUpgradeAll = forward("cancelAgentUpgradeAll");
export const checkAgentUpdateBlockers = forward("checkAgentUpdateBlockers");
export const uninstallAgent = forward("uninstallAgent");
export const getAgentJavaRuntimeConfig = forward("getAgentJavaRuntimeConfig");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 51ea0708c1..a72e2ff87a 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -582,6 +582,14 @@ export async function upgradeAllAgents(_source?: UpdateDownloadSource, operation
return post("/api/agents/upgrade-all", { operationId });
}
+export async function cancelAgentInstall(dbType: string, operationId?: string): Promise<void> {
+ await post("/api/agents/cancel-install", { dbType, operationId });
+}
+
+export async function cancelAgentUpgradeAll(operationId?: string): Promise<void> {
+ await post("/api/agents/cancel-upgrade-all", { operationId });
+}
+
export async function checkAgentUpdateBlockers(dbTypes: string[]): Promise<AgentUpdateBlocker[]> {
return post("/api/agents/update-blockers", { dbTypes });
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 5e3594c777..1bf094315e 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -118,6 +118,8 @@ export interface AgentDriverUpdateIssue {
export interface UpgradeAllAgentDriversResult {
upgraded: number;
+ /** Drivers whose install was aborted by a user cancel (single-driver or batch). */
+ cancelled: number;
failed: AgentDriverUpdateIssue[];
}
@@ -1915,6 +1917,14 @@ export async function upgradeAllAgents(source?: UpdateDownloadSource, operationI
return invoke("upgrade_all_agents", { source, operationId });
}
+export async function cancelAgentInstall(dbType: string, operationId?: string): Promise<void> {
+ return invoke("cancel_agent_install", { dbType, operationId });
+}
+
+export async function cancelAgentUpgradeAll(operationId?: string): Promise<void> {
+ return invoke("cancel_agent_upgrade_all", { operationId });
+}
+
export async function checkAgentUpdateBlockers(dbTypes: string[]): Promise<AgentUpdateBlocker[]> {
return invoke("check_agent_update_blockers", { dbTypes });
}
diff --git a/apps/desktop/src/lib/connection/driverInstallProgressUi.ts b/apps/desktop/src/lib/connection/driverInstallProgressUi.ts
index 0890487169..15ee484926 100644
--- a/apps/desktop/src/lib/connection/driverInstallProgressUi.ts
+++ b/apps/desktop/src/lib/connection/driverInstallProgressUi.ts
@@ -16,16 +16,74 @@ export interface DriverInstallProgressTargetState {
progressMap: Record<string, DriverInstallProgress | null | undefined>;
}
+export interface DriverInstallCancellationTargetState {
+ activeOperationId: string | null;
+ cancellableDbType: string | null;
+ upgradingAll: boolean;
+ progressMap: Record<string, DriverInstallProgress | null | undefined>;
+}
+
export type DriverInstallProgressChannel = "agent" | "jdbc-plugin";
const AGENT_PROGRESS_STEPS = new Set(["driver", "jre", "jre-extract", "all-done"]);
+/** Substring the backend uses for a user-cancelled driver install/upgrade. */
+const AGENT_DOWNLOAD_CANCELED_ERROR = "Agent download canceled by user.";
+
+/**
+ * True when a driver-install error is a user cancel rather than a genuine
+ * failure. Callers use this to close install modals silently and to avoid
+ * reporting a cancelled driver/upgrade as failed.
+ */
+export function isDriverInstallCanceledError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String((error as { message?: string } | null)?.message ?? error ?? "");
+ return message.includes(AGENT_DOWNLOAD_CANCELED_ERROR);
+}
+
export function isDriverInstallProgressForOperation(progress: DriverInstallProgress, operationId: string | null): boolean {
// Keep accepting legacy unscoped events, while preventing another active
// install's terminal/progress event from mutating this dialog.
return !progress.operation_id || progress.operation_id === operationId;
}
+/** How an agent install promise settled relative to the dialog's state. */
+export interface AgentInstallOperationContext {
+ /** Operation id captured when the install promise was created. */
+ operationId: string;
+ /** Operation id the dialog is currently tracking (null once finished). */
+ currentOperationId: string | null;
+ /** Whether the user pressed Cancel on the dialog's tracked operation. */
+ cancelRequested: boolean;
+}
+
+export type AgentInstallOutcome = { kind: "succeeded"; ownsState: boolean } | { kind: "cancelled"; ownsState: boolean } | { kind: "failed"; ownsState: boolean };
+
+export type AgentInstallCancelRequestResult = { ok: true } | { ok: false; error: unknown };
+
+/**
+ * Classify the settlement of an agent install operation promise. When the
+ * dialog no longer tracks the promise's operation id (the user cancelled and
+ * immediately retried, so a newer operation owns the state), `ownsState` is
+ * false and the stale promise must not finish/fail the new operation's UI.
+ */
+export function resolveAgentInstallOutcome(result: { ok: true } | { ok: false; error: unknown }, context: AgentInstallOperationContext): AgentInstallOutcome {
+ const ownsState = context.currentOperationId === context.operationId;
+ if (result.ok) return { kind: "succeeded", ownsState };
+ if (isDriverInstallCanceledError(result.error) || context.cancelRequested) {
+ return { kind: "cancelled", ownsState };
+ }
+ return { kind: "failed", ownsState };
+}
+
+export async function requestAgentInstallCancellation(request: () => Promise<void>): Promise<AgentInstallCancelRequestResult> {
+ try {
+ await request();
+ return { ok: true };
+ } catch (error) {
+ return { ok: false, error };
+ }
+}
+
export function driverInstallProgressChannel(progress: DriverInstallProgress): DriverInstallProgressChannel | null {
if (progress.step === "jdbc-plugin" || progress.step === "jdbc-plugin-extract") return "jdbc-plugin";
if (progress.db_type || AGENT_PROGRESS_STEPS.has(progress.step)) return "agent";
@@ -73,6 +131,13 @@ export function isDriverInstallProgressTarget(dbType: string, state: DriverInsta
return progress !== null && progress !== undefined;
}
+export function isDriverInstallCancellationTarget(dbType: string, state: DriverInstallCancellationTargetState): boolean {
+ if (!state.activeOperationId) return false;
+ if (!state.upgradingAll) return state.cancellableDbType === dbType;
+ const progress = state.progressMap[dbType];
+ return progress !== null && progress !== undefined;
+}
+
export function addDriverInstallQueue(queue: string[], dbType: string, activeDbType: string | null): string[] {
if (activeDbType === dbType || queue.includes(dbType)) return queue;
return [...queue, dbType];
diff --git a/crates/dbx-core/src/agent_manager.rs b/crates/dbx-core/src/agent_manager.rs
index ccd20aee58..f2456e0682 100644
--- a/crates/dbx-core/src/agent_manager.rs
+++ b/crates/dbx-core/src/agent_manager.rs
@@ -16,6 +16,43 @@ pub const DEFAULT_JRE_KEY: &str = "21";
pub const DOWNLOAD_CACHE_DIR_NAME: &str = "download-cache";
pub const DOWNLOAD_CACHE_MAX_AGE_DAYS: u64 = 7;
+/// Cooperative cancellation token for an agent driver install/upgrade.
+///
+/// Mirrors the updater's `DownloadCancellation` (src-tauri/src/commands/update.rs)
+/// so the same `watch<bool>` pattern can abort an in-flight JRE/driver download.
+#[derive(Debug)]
+pub struct AgentInstallCancellation {
+ canceled: tokio::sync::watch::Sender<bool>,
+}
+
+impl AgentInstallCancellation {
+ fn new() -> Self {
+ let (canceled, _) = tokio::sync::watch::channel(false);
+ Self { canceled }
+ }
+
+ pub fn cancel(&self) {
+ let _ = self.canceled.send_replace(true);
+ }
+
+ pub fn is_cancelled(&self) -> bool {
+ *self.canceled.borrow()
+ }
+
+ /// Completes once cancellation is requested (immediately if already cancelled).
+ pub async fn cancelled(&self) {
+ let mut receiver = self.canceled.subscribe();
+ if *receiver.borrow_and_update() {
+ return;
+ }
+ while receiver.changed().await.is_ok() {
+ if *receiver.borrow_and_update() {
+ return;
+ }
+ }
+ }
+}
+
fn default_jre_key() -> String {
DEFAULT_JRE_KEY.to_string()
}
@@ -511,6 +548,11 @@ pub struct AgentManager {
/// Driver operations may run concurrently, but JRE replacement/removal
/// must exclude them until their dependent driver state is persisted.
pub(crate) installation_operation_lock: tokio::sync::RwLock<()>,
+ /// Per-operation cancellation tokens keyed by operation id (single installs
+ /// use `install:<op>`, batches `batch:<op>` and `batch:<op>:<db>`). Downloads
+ /// observe the exact token threaded to them to abort promptly.
+ pub(crate) install_cancellations:
+ tokio::sync::Mutex<std::collections::HashMap<String, Arc<AgentInstallCancellation>>>,
}
impl Default for AgentManager {
@@ -540,6 +582,7 @@ impl AgentManager {
jre_install_locks: Mutex::new(std::collections::HashMap::new()),
driver_operation_locks: Mutex::new(std::collections::HashMap::new()),
installation_operation_lock: tokio::sync::RwLock::new(()),
+ install_cancellations: Mutex::new(std::collections::HashMap::new()),
};
mgr.migrate_legacy_jre();
mgr.cleanup_pending_jre_dirs();
@@ -560,6 +603,39 @@ impl AgentManager {
Ok(result)
}
+ /// Register a fresh cancellation token for an operation keyed by `key` (an
+ /// operation-scoped key; see the `agent_service` key helpers). Any existing
+ /// token for the same key is replaced; each install registers under a unique
+ /// operation id, so a stale cancelled token cannot leak into another
+ /// operation, and concurrent same-driver installs stay isolated.
+ pub async fn begin_install_cancellation(&self, key: &str) -> Arc<AgentInstallCancellation> {
+ let token = Arc::new(AgentInstallCancellation::new());
+ self.install_cancellations.lock().await.insert(key.to_string(), Arc::clone(&token));
+ token
+ }
+
+ /// Remove the token for `key` only if it is still `token` (guarded by
+ /// `Arc::ptr_eq`) so a concurrently registered fresh token is not removed.
+ pub async fn finish_install_cancellation(&self, key: &str, token: &Arc<AgentInstallCancellation>) {
+ let mut cancellations = self.install_cancellations.lock().await;
+ if cancellations.get(key).is_some_and(|current| Arc::ptr_eq(current, token)) {
+ cancellations.remove(key);
+ }
+ }
+
+ /// Request cancellation for the operation registered under `key`.
+ pub async fn cancel_install(&self, key: &str) {
+ if let Some(token) = self.install_cancellations.lock().await.get(key).cloned() {
+ token.cancel();
+ }
+ }
+
+ /// Whether the operation registered under `key` (an operation-scoped key,
+ /// see `agent_service` key helpers) has been cancelled.
+ pub async fn is_install_cancelled(&self, key: &str) -> bool {
+ self.install_cancellations.lock().await.get(key).is_some_and(|token| token.is_cancelled())
+ }
+
fn migrate_legacy_jre(&self) {
let legacy = self.base_dir.join("jre");
let versioned = self.jre_dir(DEFAULT_JRE_KEY);
diff --git a/crates/dbx-core/src/agent_service.rs b/crates/dbx-core/src/agent_service.rs
index 4427a08b6e..c1f6d6fb49 100644
--- a/crates/dbx-core/src/agent_service.rs
+++ b/crates/dbx-core/src/agent_service.rs
@@ -9,10 +9,16 @@ use sha2::{Digest, Sha256};
use crate::agent_catalog;
use crate::agent_manager::{
- AgentDriverInfo, AgentManager, AgentRegistry, ArtifactFormat, InstalledDriver, JavaRuntimeMode, DEFAULT_JRE_KEY,
+ AgentDriverInfo, AgentInstallCancellation, AgentManager, AgentRegistry, ArtifactFormat, InstalledDriver,
+ JavaRuntimeMode, DEFAULT_JRE_KEY,
};
use crate::DownloadSource;
+/// Error returned when a user cancels an agent driver install/upgrade. The
+/// frontend recognizes this substring to treat the outcome as "cancelled"
+/// rather than a genuine failure.
+pub const AGENT_DOWNLOAD_CANCELED_ERROR: &str = "Agent download canceled by user.";
+
/// Number of attempts to delete a JRE directory before giving up (Windows
/// experiences transient `ERROR_ACCESS_DENIED` when java.exe is still mapped
/// or anti-virus is scanning the archive). POSIX returns 1 — `unlink` of an
@@ -164,6 +170,10 @@ pub struct AgentDriverUpdateIssue {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Default)]
pub struct UpgradeAllAgentDriversResult {
pub upgraded: u32,
+ /// Drivers whose install was aborted by a user cancel (either individually
+ /// or via the batch-level cancel). These are reported separately from
+ /// `failed` so the UI can show "cancelled" rather than "failed".
+ pub cancelled: u32,
pub failed: Vec<AgentDriverUpdateIssue>,
}
@@ -367,6 +377,34 @@ pub async fn fetch_registry() -> Result<AgentRegistry, String> {
}
pub async fn fetch_registry_from(source: DownloadSource) -> Result<AgentRegistry, String> {
+ fetch_registry_from_claimed(source, &[]).await
+}
+
+/// Like `fetch_registry_from`, but the registry HTTP request AND the
+/// response-body JSON parse are raced against the given cancellation tokens, so
+/// a cancel fired during install/batch setup aborts promptly instead of waiting
+/// for the 10s client timeout. Pass an empty slice to keep the non-cancellable
+/// behavior.
+pub async fn fetch_registry_from_claimed(
+ source: DownloadSource,
+ cancellations: &[&AgentInstallCancellation],
+) -> Result<AgentRegistry, String> {
+ let urls = source.download_candidate_urls(REGISTRY_PATH, REGISTRY_R2_PATH)?;
+ fetch_registry_from_urls(source, &urls, cancellations).await
+}
+
+/// Core registry fetch over explicit candidate URLs (the URL seam lets tests
+/// point at a localhost server). With a non-empty `cancellations` slice both the
+/// HTTP request and the body parse are raced against cancellation.
+async fn fetch_registry_from_urls(
+ source: DownloadSource,
+ urls: &[String],
+ cancellations: &[&AgentInstallCancellation],
+) -> Result<AgentRegistry, String> {
+ // A pre-cancelled token must abort before any network attempt.
+ if !cancellations.is_empty() && cancellations.iter().any(|token| token.is_cancelled()) {
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
{
let cache = REGISTRY_CACHE.lock().await;
if let Some((ts, registry)) = cache.get(&source) {
@@ -379,32 +417,60 @@ pub async fn fetch_registry_from(source: DownloadSource) -> Result<AgentRegistry
.timeout(std::time::Duration::from_secs(10))
.build()
.map_err(|err| format!("Failed to create HTTP client: {err}"))?;
- let resp = open_download_response(&client, source, REGISTRY_PATH, REGISTRY_R2_PATH, "dbx-agent-manager")
+ let resp = open_download_response(&client, urls, "dbx-agent-manager", cancellations)
.await
.map_err(|err| format!("Failed to fetch agent registry: {err}"))?;
- let registry: AgentRegistry = resp.json().await.map_err(|err| format!("Failed to parse registry: {err}"))?;
+ // Race the body parse too: a stalled/partial body must not hold the
+ // registry fetch hostage until the 10s client timeout.
+ let registry: AgentRegistry = if cancellations.is_empty() {
+ resp.json().await.map_err(|err| format!("Failed to parse registry: {err}"))?
+ } else {
+ tokio::select! {
+ result = resp.json() => result.map_err(|err| format!("Failed to parse registry: {err}"))?,
+ _ = first_cancellation(cancellations) => return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string()),
+ }
+ };
REGISTRY_CACHE.lock().await.insert(source, (std::time::Instant::now(), registry.clone()));
Ok(registry)
}
async fn open_download_response(
client: &reqwest::Client,
- source: DownloadSource,
- github_url: &str,
- r2_path: &str,
+ urls: &[String],
user_agent: &str,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<reqwest::Response, String> {
let mut errors = Vec::new();
- for url in source.download_candidate_urls(github_url, r2_path)? {
- match client
- .get(&url)
+ for url in urls {
+ let request = client
+ .get(url)
.header(reqwest::header::USER_AGENT, user_agent)
- .header(reqwest::header::ACCEPT_ENCODING, "identity")
- .send()
- .await
- .and_then(|response| response.error_for_status())
- {
- Ok(response) => return Ok(response),
+ .header(reqwest::header::ACCEPT_ENCODING, "identity");
+ // Race the request with cancellation: a stalled mirror that never
+ // returns response headers must not hold the registry fetch hostage
+ // until the 10s client timeout. Dropping the send future aborts it.
+ let resp = if cancellations.is_empty() {
+ match request.send().await {
+ Ok(resp) => resp,
+ Err(error) => {
+ errors.push(format!("{url}: {error}"));
+ continue;
+ }
+ }
+ } else {
+ tokio::select! {
+ result = request.send() => match result {
+ Ok(resp) => resp,
+ Err(error) => {
+ errors.push(format!("{url}: {error}"));
+ continue;
+ }
+ },
+ _ = first_cancellation(cancellations) => return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string()),
+ }
+ };
+ match resp.error_for_status() {
+ Ok(resp) => return Ok(resp),
Err(error) => errors.push(format!("{url}: {error}")),
}
}
@@ -423,13 +489,79 @@ pub async fn install_agent_driver(
install_agent_driver_from(am, db_type, DownloadSource::Official, progress).await
}
+/// Like `install_agent_driver`, but using a command-scoped cancellation token
+/// that was registered before any awaitable setup (blocker check, lock wait,
+/// registry fetch) so a cancel fired during that window is observed.
+pub async fn install_agent_driver_claimed(
+ am: &AgentManager,
+ db_type: &str,
+ progress: impl Fn(AgentProgressEvent),
+ cancellation: &Arc<AgentInstallCancellation>,
+) -> Result<(), String> {
+ install_agent_driver_from_claimed(am, db_type, DownloadSource::Official, progress, cancellation).await
+}
+
pub async fn install_agent_driver_from(
am: &AgentManager,
db_type: &str,
source: DownloadSource,
progress: impl Fn(AgentProgressEvent),
) -> Result<(), String> {
- install_agent_driver_with_batch(am, db_type, source, &progress, None, None).await
+ install_agent_driver_with_batch(am, db_type, source, &progress, None, None, None).await
+}
+
+/// Like `install_agent_driver_from`, but using a command-scoped cancellation
+/// token registered before any awaitable setup. A cancel fired while waiting
+/// on locks, blockers, or the registry fetch is observed instead of lost.
+pub async fn install_agent_driver_from_claimed(
+ am: &AgentManager,
+ db_type: &str,
+ source: DownloadSource,
+ progress: impl Fn(AgentProgressEvent),
+ cancellation: &Arc<AgentInstallCancellation>,
+) -> Result<(), String> {
+ install_agent_driver_with_batch(am, db_type, source, &progress, None, None, Some(cancellation)).await
+}
+
+/// Cancel an in-flight single driver install/update. `operation_id` targets the
+/// exact install (a second same-db_type install registered under a different
+/// operation id is unaffected). Also covers a driver inside a batch upgrade
+/// when the batch's operation id is supplied. Missing keys are a no-op.
+pub async fn cancel_agent_driver_install(
+ am: &AgentManager,
+ db_type: &str,
+ operation_id: Option<&str>,
+) -> Result<(), String> {
+ if let Some(operation_id) = operation_id {
+ am.cancel_install(&install_cancellation_key(operation_id)).await;
+ am.cancel_install(&batch_driver_cancellation_key(operation_id, db_type)).await;
+ }
+ Ok(())
+}
+
+/// Cancel an in-flight batch upgrade, targeting the exact batch by its
+/// operation id. Aborts every driver still downloading and stops scheduling
+/// drivers that have not started yet.
+pub async fn cancel_agent_batch_upgrade(am: &AgentManager, operation_id: Option<&str>) -> Result<(), String> {
+ if let Some(operation_id) = operation_id {
+ am.cancel_install(&batch_cancellation_key(operation_id)).await;
+ }
+ Ok(())
+}
+
+/// Cancellation-map key for a single install operation.
+pub fn install_cancellation_key(operation_id: &str) -> String {
+ format!("install:{operation_id}")
+}
+
+/// Cancellation-map key for a whole-batch upgrade operation.
+pub fn batch_cancellation_key(operation_id: &str) -> String {
+ format!("batch:{operation_id}")
+}
+
+/// Cancellation-map key for one driver inside a batch upgrade operation.
+pub fn batch_driver_cancellation_key(operation_id: &str, db_type: &str) -> String {
+ format!("batch:{operation_id}:{db_type}")
}
/// Ensure an already-selected fallback Agent can be launched, installing only
@@ -460,7 +592,7 @@ async fn ensure_agent_driver_ready_from(
let registry = fetch_registry_from(source).await?;
let progress = |_| {};
if !am.is_driver_installed(db_type) {
- install_agent_driver_from_registry(am, &registry, source, db_type, &progress, None, None).await?;
+ install_agent_driver_from_registry(am, &registry, source, db_type, &progress, None, None, &[]).await?;
} else if am.driver_requires_java_runtime(db_type) {
let state = am.load_state();
let jre_key = state
@@ -469,7 +601,7 @@ async fn ensure_agent_driver_ready_from(
.map(|driver| driver.jre.as_str())
.or_else(|| agent_registry_driver(&registry, db_type).map(|driver| driver.jre.as_str()))
.unwrap_or(DEFAULT_JRE_KEY);
- ensure_jre_from_registry(am, &registry, source, jre_key, db_type, &progress, None, None).await?;
+ ensure_jre_from_registry(am, &registry, source, jre_key, db_type, &progress, None, None, &[]).await?;
}
agent_driver_runtime_readiness(am, db_type)
@@ -494,7 +626,41 @@ pub async fn upgrade_all_agent_drivers_from(
progress: impl Fn(AgentProgressEvent),
) -> Result<UpgradeAllAgentDriversResult, String> {
let registry = fetch_registry_from(source).await?;
- upgrade_all_agent_drivers_with_registry(am, &registry, source, &progress).await
+ upgrade_all_agent_drivers_with_registry(am, &registry, source, &progress, None, None).await
+}
+
+/// Like `upgrade_all_agent_drivers`, but using a command-scoped batch
+/// cancellation token registered before the registry fetch + blocker check so a
+/// cancel fired during that setup aborts the whole batch instead of being lost.
+/// `operation_id` names the batch so per-driver cancellation targets the right
+/// operation even when the same driver is installed concurrently elsewhere.
+pub async fn upgrade_all_agent_drivers_claimed(
+ am: &AgentManager,
+ progress: impl Fn(AgentProgressEvent),
+ batch_cancellation: &Arc<AgentInstallCancellation>,
+ operation_id: &str,
+) -> Result<UpgradeAllAgentDriversResult, String> {
+ upgrade_all_agent_drivers_from_claimed(am, DownloadSource::Official, progress, batch_cancellation, operation_id)
+ .await
+}
+
+pub async fn upgrade_all_agent_drivers_from_claimed(
+ am: &AgentManager,
+ source: DownloadSource,
+ progress: impl Fn(AgentProgressEvent),
+ batch_cancellation: &Arc<AgentInstallCancellation>,
+ operation_id: &str,
+) -> Result<UpgradeAllAgentDriversResult, String> {
+ let registry = fetch_registry_from_claimed(source, &[batch_cancellation.as_ref()]).await?;
+ upgrade_all_agent_drivers_with_registry(
+ am,
+ &registry,
+ source,
+ &progress,
+ Some(batch_cancellation),
+ Some(operation_id),
+ )
+ .await
}
async fn upgrade_all_agent_drivers_with_registry(
@@ -502,37 +668,97 @@ async fn upgrade_all_agent_drivers_with_registry(
registry: &AgentRegistry,
source: DownloadSource,
progress: &impl Fn(AgentProgressEvent),
+ batch_cancellation: Option<&Arc<AgentInstallCancellation>>,
+ operation_id: Option<&str>,
) -> Result<UpgradeAllAgentDriversResult, String> {
let agents = build_agent_list(am, Some(registry));
let updatable: Vec<String> =
agents.iter().filter(|agent| agent.update_available).map(|agent| agent.db_type.clone()).collect();
let total = updatable.len() as u32;
+ // Use the command-scoped batch token when one was registered before the
+ // registry fetch + blocker check, so a cancel fired during that setup is
+ // observed. Otherwise register a token owned by this call keyed by a fresh
+ // operation id so it cannot collide with another in-flight operation.
+ let owned_operation_id: Option<String> =
+ if operation_id.is_some() { None } else { Some(uuid::Uuid::new_v4().to_string()) };
+ let effective_operation_id: &str = owned_operation_id.as_deref().or(operation_id).unwrap_or_default();
+ let owned_batch: Option<Arc<AgentInstallCancellation>> = if batch_cancellation.is_some() {
+ None
+ } else {
+ Some(am.begin_install_cancellation(&batch_cancellation_key(effective_operation_id)).await)
+ };
+ let active_batch_arc: Arc<AgentInstallCancellation> = owned_batch
+ .clone()
+ .or_else(|| batch_cancellation.cloned())
+ .expect("a batch cancellation token is always available");
+ let active_batch: &AgentInstallCancellation = active_batch_arc.as_ref();
+ if active_batch.is_cancelled() {
+ if let Some(token) = owned_batch {
+ am.finish_install_cancellation(&batch_cancellation_key(effective_operation_id), &token).await;
+ }
+ return Ok(UpgradeAllAgentDriversResult { cancelled: total, ..Default::default() });
+ }
+
+ // Register a per-driver token for every driver in the batch, keyed by the
+ // batch operation id so per-driver cancels target this batch's driver even
+ // when the same db_type is being installed concurrently elsewhere. The
+ // batch token lets one click abort the whole upgrade; each driver token
+ // lets the user cancel a single driver while the rest continue.
+ let mut driver_cancellations = std::collections::HashMap::new();
+ for db_type in &updatable {
+ let key = batch_driver_cancellation_key(effective_operation_id, db_type);
+ let token = am.begin_install_cancellation(&key).await;
+ driver_cancellations.insert(db_type.clone(), token);
+ }
+
// Run independent driver installs concurrently, with a fixed upper bound
// so a large registry cannot saturate download and file-system resources.
- let installs = updatable.into_iter().enumerate().map(|(index, db_type)| async move {
- let result = install_agent_driver_from_registry_locked(
- am,
- registry,
- source,
- &db_type,
- progress,
- Some((index + 1) as u32),
- Some(total),
- )
- .await;
- (db_type, result)
+ let installs = updatable.into_iter().enumerate().map(|(index, db_type)| {
+ let key = batch_driver_cancellation_key(effective_operation_id, &db_type);
+ let token = driver_cancellations.remove(&db_type).expect("driver token registered");
+ let batch_token = Arc::clone(&active_batch_arc);
+ async move {
+ let result = if batch_token.is_cancelled() {
+ Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string())
+ } else {
+ install_agent_driver_from_registry_locked(
+ am,
+ registry,
+ source,
+ &db_type,
+ progress,
+ Some((index + 1) as u32),
+ Some(total),
+ // Observe BOTH the row token (per-driver cancel) and the
+ // batch token (cancel-all): a batch cancel must interrupt a
+ // driver whose download already started, not just one that
+ // is still waiting to begin.
+ &[&token, &batch_token],
+ )
+ .await
+ };
+ am.finish_install_cancellation(&key, &token).await;
+ (db_type, result)
+ }
});
let outcomes = stream::iter(installs).buffer_unordered(MAX_CONCURRENT_AGENT_UPDATES).collect::<Vec<_>>().await;
+ if let Some(token) = owned_batch {
+ am.finish_install_cancellation(&batch_cancellation_key(effective_operation_id), &token).await;
+ }
let mut result = UpgradeAllAgentDriversResult::default();
for (db_type, outcome) in outcomes {
match outcome {
Ok(()) => result.upgraded += 1,
Err(error) => {
- log::warn!("Failed to update {} agent driver: {}", db_type, error);
- result.failed.push(AgentDriverUpdateIssue { db_type, error });
+ if is_cancelled_error(&error) {
+ result.cancelled += 1;
+ } else {
+ log::warn!("Failed to update {} agent driver: {}", db_type, error);
+ result.failed.push(AgentDriverUpdateIssue { db_type, error });
+ }
}
}
}
@@ -541,6 +767,18 @@ async fn upgrade_all_agent_drivers_with_registry(
Ok(result)
}
+fn is_cancelled_error(error: &str) -> bool {
+ error.contains(AGENT_DOWNLOAD_CANCELED_ERROR)
+}
+
+async fn can_fallback_to_local_agent(
+ _am: &AgentManager,
+ _db_type: &str,
+ cancellations: &[&AgentInstallCancellation],
+) -> bool {
+ !cancellations.iter().any(|token| token.is_cancelled())
+}
+
async fn driver_operation_lock(am: &AgentManager, db_type: &str) -> Arc<tokio::sync::Mutex<()>> {
let mut locks = am.driver_operation_locks.lock().await;
locks.entry(db_type.to_string()).or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))).clone()
@@ -551,6 +789,33 @@ async fn jre_operation_lock(am: &AgentManager, jre_key: &str) -> Arc<tokio::sync
locks.entry(jre_key.to_string()).or_insert_with(|| Arc::new(tokio::sync::Mutex::new(()))).clone()
}
+/// Future that resolves as soon as any cancellation token fires.
+fn first_cancellation<'a>(
+ cancellations: &'a [&'a AgentInstallCancellation],
+) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
+ Box::pin(async move {
+ let ((), _index, _rest) =
+ futures::future::select_all(cancellations.iter().map(|token| Box::pin(token.cancelled()))).await;
+ })
+}
+
+/// Acquire a per-driver/JRE operation lock, aborting promptly if any
+/// cancellation token fires while the lock is held elsewhere. Without this
+/// race a cancelled install would wait for the current lock holder to finish
+/// before it could observe its token.
+async fn lock_or_cancel<'a>(
+ lock: &'a tokio::sync::Mutex<()>,
+ cancellations: &'a [&'a AgentInstallCancellation],
+) -> Result<tokio::sync::MutexGuard<'a, ()>, String> {
+ if cancellations.is_empty() {
+ return Ok(lock.lock().await);
+ }
+ tokio::select! {
+ guard = lock.lock() => Ok(guard),
+ _ = first_cancellation(cancellations) => Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string()),
+ }
+}
+
pub async fn uninstall_agent_driver(am: &AgentManager, db_type: &str) -> Result<(), String> {
let _installation_guard = am.installation_operation_lock.read().await;
let driver_lock = driver_operation_lock(am, db_type).await;
@@ -642,6 +907,7 @@ pub async fn reinstall_agent_jre_from(
None,
None,
None,
+ &[],
)
.await?;
let jre_dir = am.jre_dir(jre_key);
@@ -720,11 +986,58 @@ async fn install_agent_driver_with_batch(
progress: &impl Fn(AgentProgressEvent),
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellation: Option<&Arc<AgentInstallCancellation>>,
) -> Result<(), String> {
let _installation_guard = am.installation_operation_lock.read().await;
let driver_lock = driver_operation_lock(am, db_type).await;
- let _driver_guard = driver_lock.lock().await;
- install_agent_driver_with_batch_unlocked(am, db_type, source, progress, current, total_drivers).await
+ // A cancel that fires while the driver lock is held elsewhere must abort
+ // promptly instead of waiting for the lock holder to finish.
+ let owned_tokens;
+ let command_tokens: &[&AgentInstallCancellation] = match cancellation {
+ Some(token) => {
+ owned_tokens = [token.as_ref()];
+ &owned_tokens
+ }
+ None => &[],
+ };
+ let _driver_guard = lock_or_cancel(&driver_lock, command_tokens).await?;
+ // Use the command-scoped token when one was registered before any awaitable
+ // setup (blocker check, lock wait, registry fetch) so a cancel fired during
+ // that window is observed here instead of being lost. Otherwise register a
+ // token owned by this call keyed by a fresh operation id so two concurrent
+ // installs of the same driver cannot replace each other's token.
+ let owned_operation_id: Option<String> =
+ if cancellation.is_some() { None } else { Some(uuid::Uuid::new_v4().to_string()) };
+ let owned_cancellation: Option<Arc<AgentInstallCancellation>> = match owned_operation_id.as_deref() {
+ Some(operation_id) => Some(am.begin_install_cancellation(&install_cancellation_key(operation_id)).await),
+ None => None,
+ };
+ let active_cancellation: &AgentInstallCancellation = owned_cancellation
+ .as_deref()
+ .or_else(|| cancellation.map(|token| token.as_ref()))
+ .expect("a cancellation token is always available");
+ if active_cancellation.is_cancelled() {
+ if let (Some(operation_id), Some(token)) = (owned_operation_id.as_deref(), owned_cancellation.as_ref()) {
+ am.finish_install_cancellation(&install_cancellation_key(operation_id), token).await;
+ }
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+
+ let result = install_agent_driver_with_batch_unlocked(
+ am,
+ db_type,
+ source,
+ progress,
+ current,
+ total_drivers,
+ &[active_cancellation],
+ )
+ .await;
+
+ if let (Some(operation_id), Some(token)) = (owned_operation_id.as_deref(), owned_cancellation.as_ref()) {
+ am.finish_install_cancellation(&install_cancellation_key(operation_id), token).await;
+ }
+ result
}
async fn install_agent_driver_from_registry_locked(
@@ -735,11 +1048,16 @@ async fn install_agent_driver_from_registry_locked(
progress: &impl Fn(AgentProgressEvent),
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(), String> {
let _installation_guard = am.installation_operation_lock.read().await;
let driver_lock = driver_operation_lock(am, db_type).await;
- let _driver_guard = driver_lock.lock().await;
- install_agent_driver_from_registry(am, registry, source, db_type, progress, current, total_drivers).await
+ assert!(!cancellations.is_empty(), "batch driver cancellation token is always registered");
+ // A cancelled batch row must not wait for the current lock holder to
+ // finish before observing its cancellation tokens.
+ let _driver_guard = lock_or_cancel(&driver_lock, cancellations).await?;
+ install_agent_driver_from_registry(am, registry, source, db_type, progress, current, total_drivers, cancellations)
+ .await
}
async fn install_agent_driver_with_batch_unlocked(
@@ -749,38 +1067,59 @@ async fn install_agent_driver_with_batch_unlocked(
progress: &impl Fn(AgentProgressEvent),
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(), String> {
- match fetch_registry_from(source).await {
+ match fetch_registry_from_claimed(source, cancellations).await {
Ok(registry) => {
- match install_agent_driver_from_registry(am, &registry, source, db_type, progress, current, total_drivers)
- .await
+ match install_agent_driver_from_registry(
+ am,
+ &registry,
+ source,
+ db_type,
+ progress,
+ current,
+ total_drivers,
+ cancellations,
+ )
+ .await
{
Ok(()) => Ok(()),
Err(registry_err) => {
- if let Some(local_jar) = find_local_agent_jar(db_type) {
- install_local_agent_with_registry_jre(
- am,
- &registry,
- source,
- db_type,
- local_jar,
- progress,
- current,
- total_drivers,
- )
- .await?;
- return Ok(());
+ // Cancellation is terminal, not a registry failure. Falling
+ // back here would install a bundled JAR after the user
+ // explicitly aborted the download.
+ if can_fallback_to_local_agent(am, db_type, cancellations).await {
+ if let Some(local_jar) = find_local_agent_jar(db_type) {
+ install_local_agent_with_registry_jre(
+ am,
+ &registry,
+ source,
+ db_type,
+ local_jar,
+ progress,
+ current,
+ total_drivers,
+ cancellations,
+ )
+ .await?;
+ return Ok(());
+ }
}
Err(registry_err)
}
}
}
Err(registry_err) => {
- if let Some(local_jar) = find_local_agent_jar(db_type) {
- install_local_agent(am, db_type, local_jar)?;
- am.stop_daemon_by_key(db_type).await;
- progress(AgentProgressEvent::step("done").with_batch(Some(db_type), current, total_drivers));
- return Ok(());
+ // The registry fetch observes cancellation, so the cancel error
+ // must not start the local fallback (the fallback guard refuses it
+ // anyway because the same tokens are cancelled).
+ if can_fallback_to_local_agent(am, db_type, cancellations).await {
+ if let Some(local_jar) = find_local_agent_jar(db_type) {
+ install_local_agent(am, db_type, local_jar)?;
+ am.stop_daemon_by_key(db_type).await;
+ progress(AgentProgressEvent::step("done").with_batch(Some(db_type), current, total_drivers));
+ return Ok(());
+ }
}
Err(registry_err)
}
@@ -796,6 +1135,7 @@ async fn ensure_jre_from_registry(
progress: &impl Fn(AgentProgressEvent),
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(), String> {
// Fast path: already installed — return immediately without acquiring the
// per-JRE lock. The lock is only needed when a download + extract may be
@@ -807,7 +1147,9 @@ async fn ensure_jre_from_registry(
// Acquire (or create) the per-JRE-key mutex so that concurrent driver
// installs sharing the same JRE download it exactly once.
let lock = jre_operation_lock(am, jre_key).await;
- let _jre_guard = lock.lock().await;
+ // A cancel that fires while another install holds the JRE lock must abort
+ // promptly instead of waiting for the lock holder to finish.
+ let _jre_guard = lock_or_cancel(&lock, cancellations).await?;
// Double-check: the previous lock holder may have already installed.
if !jre_needs_install(am, registry, jre_key) {
@@ -840,8 +1182,15 @@ async fn ensure_jre_from_registry(
Some(db_type),
current,
total_drivers,
+ cancellations,
)
.await?;
+ // A cancel may have fired right after the download completed but before we
+ // replace the JRE directory — don't leave a half-extracted runtime.
+ if cancellations.iter().any(|token| token.is_cancelled()) {
+ std::fs::remove_file(&jre_archive).ok();
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
progress(AgentProgressEvent::transfer("jre-extract", 0, 0).with_batch(Some(db_type), current, total_drivers));
let jre_dir = am.jre_dir(jre_key);
// Stop only daemons that use this JRE before replacing its directory
@@ -909,6 +1258,24 @@ async fn persist_local_agent_install_state(
})
}
+fn ensure_local_agent_commit_allowed(cancellations: &[&AgentInstallCancellation]) -> Result<(), String> {
+ if cancellations.iter().any(|token| token.is_cancelled()) {
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+ Ok(())
+}
+
+async fn commit_local_agent_install(
+ am: &AgentManager,
+ db_type: &str,
+ local_jar: &Path,
+ jre_key: &str,
+ jre_version: Option<&str>,
+) -> Result<(), String> {
+ install_local_agent_file(am, db_type, local_jar)?;
+ persist_local_agent_install_state(am, db_type, jre_key, jre_version).await
+}
+
async fn install_local_agent_with_registry_jre(
am: &AgentManager,
registry: &AgentRegistry,
@@ -918,17 +1285,28 @@ async fn install_local_agent_with_registry_jre(
progress: &impl Fn(AgentProgressEvent),
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(), String> {
let jre_key = DEFAULT_JRE_KEY;
if jre_needs_install(am, registry, jre_key) {
- ensure_jre_from_registry(am, registry, source, jre_key, db_type, progress, current, total_drivers).await?;
+ ensure_jre_from_registry(
+ am,
+ registry,
+ source,
+ jre_key,
+ db_type,
+ progress,
+ current,
+ total_drivers,
+ cancellations,
+ )
+ .await?;
}
- install_local_agent_file(am, db_type, &local_jar)?;
- // This fallback can run for several drivers during upgrade-all. Keep its
- // driver and JRE updates in one state_lock-protected transaction.
- persist_local_agent_install_state(
+ ensure_local_agent_commit_allowed(cancellations)?;
+ commit_local_agent_install(
am,
db_type,
+ &local_jar,
jre_key,
registry.resolve_jre(jre_key).map(|jre| jre.version.as_str()),
)
@@ -946,6 +1324,7 @@ async fn install_agent_driver_from_registry(
progress: &impl Fn(AgentProgressEvent),
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(), String> {
let Some(driver) = agent_registry_driver(registry, db_type) else {
if let Some(local_jar) = find_local_agent_jar(db_type) {
@@ -958,6 +1337,7 @@ async fn install_agent_driver_from_registry(
progress,
current,
total_drivers,
+ cancellations,
)
.await?;
return Ok(());
@@ -971,7 +1351,18 @@ async fn install_agent_driver_from_registry(
let needs_jre = requires_java_runtime && jre_needs_install(am, registry, jre_key);
if needs_jre {
- ensure_jre_from_registry(am, registry, source, jre_key, db_type, progress, current, total_drivers).await?;
+ ensure_jre_from_registry(
+ am,
+ registry,
+ source,
+ jre_key,
+ db_type,
+ progress,
+ current,
+ total_drivers,
+ cancellations,
+ )
+ .await?;
}
let (artifact, target_path, is_native_artifact) = if let Some(native) = native_artifact {
@@ -1005,8 +1396,15 @@ async fn install_agent_driver_from_registry(
Some(db_type),
current,
total_drivers,
+ cancellations,
)
.await?;
+ // A cancel may have fired after the download completed but before the
+ // artifact is moved into place — drop the partial artifact and bail.
+ if cancellations.iter().any(|token| token.is_cancelled()) {
+ std::fs::remove_file(&download_path).ok();
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
install_downloaded_driver_artifact(
&download_path,
&target_path,
@@ -1028,6 +1426,10 @@ async fn install_agent_driver_from_registry(
std::fs::remove_file(am.driver_native_path(db_type)).ok();
}
+ // The cancellation boundary is immediately before the staged artifact is
+ // committed above. After that atomic replacement, treating a newly arrived
+ // cancel as a rollback would delete a working driver and lose the prior
+ // installation, so this completed install must persist normally.
am.mutate_state(|state| {
if requires_java_runtime {
if let Some(jre_info) = registry.resolve_jre(jre_key) {
@@ -1050,12 +1452,14 @@ async fn install_agent_driver_from_registry(
}
fn driver_artifact_download_path(target_path: &Path, format: Option<ArtifactFormat>) -> PathBuf {
+ let parent = target_path.parent().unwrap_or_else(|| Path::new("."));
+ let file_name = target_path.file_name().and_then(|name| name.to_str()).unwrap_or("agent");
match format {
- Some(ArtifactFormat::TarZstd) => {
- let file_name = target_path.file_name().and_then(|name| name.to_str()).unwrap_or("agent");
- target_path.with_file_name(format!(".{file_name}.tar.zst"))
- }
- None => target_path.to_path_buf(),
+ Some(ArtifactFormat::TarZstd) => parent.join(format!(".{file_name}.tar.zst")),
+ // Keep raw artifacts out of the live driver path until the caller has
+ // made its final cancellation check. The filename stays stable so an
+ // existing download-cache entry remains reusable.
+ None => parent.join(".staging").join(file_name),
}
}
@@ -1067,11 +1471,9 @@ fn install_downloaded_driver_artifact(
db_type: &str,
expected_version: &str,
) -> Result<(), String> {
- let Some(format) = format else {
- return Ok(());
- };
let result = match format {
- ArtifactFormat::TarZstd => {
+ None => replace_download(download_path, target_path),
+ Some(ArtifactFormat::TarZstd) => {
install_driver_from_tar_zstd_package(download_path, target_path, artifact_kind, db_type, expected_version)
}
};
@@ -1234,9 +1636,19 @@ async fn download_with_progress(
db_type: Option<&str>,
current: Option<u32>,
total_drivers: Option<u32>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(), String> {
const DOWNLOAD_ATTEMPTS: usize = 4;
let expected_sha256 = normalized_sha256(expected_sha256)?;
+ // Observe the exact operation tokens threaded from the command layer: a
+ // single install passes its own token; a batch passes BOTH the row token
+ // and the batch token so a batch cancel-all interrupts a driver whose
+ // download already started. An empty slice means "no cancellation" for the
+ // offline/auto paths.
+ let any_cancelled = || cancellations.iter().any(|token| token.is_cancelled());
+ if any_cancelled() {
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|err| err.to_string())?;
@@ -1246,6 +1658,9 @@ async fn download_with_progress(
let cache_path = cached_download_path(am, url, total_size, expected_sha256, cache_identity, dest);
prune_download_cache(am).ok();
if cached_download_is_valid(am, &cache_path, total_size, expected_sha256) {
+ if any_cancelled() {
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
std::fs::copy(&cache_path, &tmp).map_err(|err| format!("Failed to copy cached download: {err}"))?;
progress(AgentProgressEvent::transfer(step, total_size, total_size).with_batch(
db_type,
@@ -1263,6 +1678,11 @@ async fn download_with_progress(
let mut completed = false;
let mut rejected_sources = std::collections::HashSet::new();
for attempt in 1..=DOWNLOAD_ATTEMPTS {
+ if any_cancelled() {
+ std::fs::remove_file(&tmp).ok();
+ std::fs::remove_file(&tmp_source).ok();
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
let mut resume_from = std::fs::metadata(&tmp).map(|meta| meta.len()).unwrap_or(0);
let resume_source = std::fs::read_to_string(&tmp_source).ok().map(|value| value.trim().to_string());
if resume_from > 0 && resume_source.is_none() {
@@ -1307,6 +1727,7 @@ async fn download_with_progress(
total_size,
resume_source.as_deref(),
&rejected_sources,
+ cancellations,
)
.await
{
@@ -1333,14 +1754,41 @@ async fn download_with_progress(
std::fs::write(&tmp_source, &source_url).map_err(|err| format!("Failed to write download source: {err}"))?;
let mut downloaded = starting_size;
let transfer_result = async {
- while let Some(chunk) = resp.chunk().await.map_err(|err| format!("Download stream error: {err}"))? {
- std::io::Write::write_all(&mut file, &chunk).map_err(|err| format!("Failed to write chunk: {err}"))?;
- downloaded += chunk.len() as u64;
- progress(AgentProgressEvent::transfer(step, downloaded, content_length).with_batch(
- db_type,
- current,
- total_drivers,
- ));
+ if cancellations.is_empty() {
+ while let Some(chunk) = resp.chunk().await.map_err(|err| format!("Download stream error: {err}"))? {
+ std::io::Write::write_all(&mut file, &chunk)
+ .map_err(|err| format!("Failed to write chunk: {err}"))?;
+ downloaded += chunk.len() as u64;
+ progress(AgentProgressEvent::transfer(step, downloaded, content_length).with_batch(
+ db_type,
+ current,
+ total_drivers,
+ ));
+ }
+ return std::io::Write::flush(&mut file).map_err(|err| format!("Failed to flush temp file: {err}"));
+ }
+ // Cancellation tokens are registered: await the stream and every
+ // cancel signal concurrently so any token (row-level or batch-level)
+ // aborts mid-stream.
+ loop {
+ tokio::select! {
+ chunk = resp.chunk() => {
+ let chunk = chunk.map_err(|err| format!("Download stream error: {err}"))?;
+ match chunk {
+ Some(chunk) => {
+ std::io::Write::write_all(&mut file, &chunk)
+ .map_err(|err| format!("Failed to write chunk: {err}"))?;
+ downloaded += chunk.len() as u64;
+ progress(AgentProgressEvent::transfer(step, downloaded, content_length)
+ .with_batch(db_type, current, total_drivers));
+ }
+ None => break,
+ }
+ }
+ _ = first_cancellation(cancellations) => {
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
+ }
}
std::io::Write::flush(&mut file).map_err(|err| format!("Failed to flush temp file: {err}"))
}
@@ -1348,6 +1796,11 @@ async fn download_with_progress(
drop(file);
if let Err(err) = transfer_result {
+ if any_cancelled() {
+ std::fs::remove_file(&tmp).ok();
+ std::fs::remove_file(&tmp_source).ok();
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
last_err = Some(format!("{err} (attempt {attempt}/{DOWNLOAD_ATTEMPTS}, source {source_url})"));
continue;
}
@@ -1377,6 +1830,11 @@ async fn download_with_progress(
));
}
if !completed {
+ if any_cancelled() {
+ std::fs::remove_file(&tmp).ok();
+ std::fs::remove_file(&tmp_source).ok();
+ return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string());
+ }
let actual_size = std::fs::metadata(&tmp).map(|meta| meta.len()).unwrap_or(0);
return Err(last_err.unwrap_or_else(|| {
format!("Downloaded {step} is incomplete: expected {total_size} bytes, got {actual_size} bytes")
@@ -1403,6 +1861,7 @@ async fn open_agent_download_response(
expected_size: u64,
resume_source: Option<&str>,
rejected_sources: &std::collections::HashSet<String>,
+ cancellations: &[&AgentInstallCancellation],
) -> Result<(reqwest::Response, bool, String), String> {
let mut errors = Vec::new();
for candidate_url in source.download_candidate_urls(github_url, r2_path)? {
@@ -1420,11 +1879,27 @@ async fn open_agent_download_response(
if resume_from > 0 {
request = request.header(reqwest::header::RANGE, format!("bytes={resume_from}-"));
}
- let resp = match request.send().await {
- Ok(resp) => resp,
- Err(err) => {
- errors.push(format!("{candidate_url}: {err}"));
- continue;
+ // Race the request with cancellation: a stalled mirror that never
+ // returns response headers must not hold the install hostage until
+ // the 300s client timeout. Dropping the send future aborts it.
+ let resp = if cancellations.is_empty() {
+ match request.send().await {
+ Ok(resp) => resp,
+ Err(err) => {
+ errors.push(format!("{candidate_url}: {err}"));
+ continue;
+ }
+ }
+ } else {
+ tokio::select! {
+ result = request.send() => match result {
+ Ok(resp) => resp,
+ Err(err) => {
+ errors.push(format!("{candidate_url}: {err}"));
+ continue;
+ }
+ },
+ _ = first_cancellation(cancellations) => return Err(AGENT_DOWNLOAD_CANCELED_ERROR.to_string()),
}
};
let status = resp.status();
@@ -3256,6 +3731,7 @@ mod agent_registry_install_tests {
&progress,
None,
None,
+ &[],
)
.await
.unwrap();
@@ -3271,6 +3747,51 @@ mod agent_registry_install_tests {
.any(|event| event.step == "done" && event.db_type.as_deref() == Some(db_type)));
}
+ #[tokio::test]
+ async fn registry_install_cancel_after_cached_download_preserves_existing_driver() {
+ let manager = test_manager("cancel-after-cached-driver-download");
+ let db_type = "mongodb";
+ let old_version = "1.0.0";
+ let new_version = "2.0.0";
+ let url = "https://example.com/dbx-agent-mongodb.jar";
+ // The old driver only needs to exist for this regression: use distinct
+ // bytes so the assertion proves cancellation did not replace it.
+ let old_bytes = b"previously-installed-driver".to_vec();
+ let new_bytes = test_agent_jar();
+ let target_path = manager.driver_jar_path(db_type);
+ std::fs::create_dir_all(target_path.parent().unwrap()).unwrap();
+ std::fs::write(&target_path, &old_bytes).unwrap();
+ install_jre(&manager);
+ record_driver(&manager, db_type);
+ write_cached_driver_download(&manager, db_type, new_version, url, &target_path, &new_bytes);
+ let registry = registry_with_jar(db_type, new_version, url, new_bytes.len() as u64);
+ let cancellation = manager.begin_install_cancellation("cancel-after-cached-download").await;
+ let progress_cancellation = Arc::clone(&cancellation);
+ let progress = move |event: AgentProgressEvent| {
+ if event.step == "driver" && event.downloaded == Some(new_bytes.len() as u64) {
+ progress_cancellation.cancel();
+ }
+ };
+
+ let error = install_agent_driver_from_registry(
+ &manager,
+ &registry,
+ DownloadSource::Official,
+ db_type,
+ &progress,
+ None,
+ None,
+ &[&cancellation],
+ )
+ .await
+ .expect_err("cancellation after download completion must abort installation");
+
+ assert!(error.contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ assert_eq!(std::fs::read(&target_path).unwrap(), old_bytes);
+ assert_eq!(manager.load_state().installed_drivers[db_type].version, old_version);
+ assert!(!driver_artifact_download_path(&target_path, None).exists());
+ }
+
#[tokio::test]
async fn registry_install_extracts_tar_zstd_native_driver_package() {
let manager = test_manager("tar-zstd-native-package");
@@ -3297,6 +3818,7 @@ mod agent_registry_install_tests {
&progress,
None,
None,
+ &[],
)
.await
.unwrap();
@@ -3336,6 +3858,7 @@ mod agent_registry_install_tests {
&progress,
None,
None,
+ &[],
)
.await
.unwrap();
@@ -3404,9 +3927,16 @@ mod agent_registry_install_tests {
let events = std::sync::Mutex::new(Vec::new());
let progress = |event| events.lock().unwrap().push(event);
- let result = upgrade_all_agent_drivers_with_registry(&manager, &registry, DownloadSource::Official, &progress)
- .await
- .unwrap();
+ let result = upgrade_all_agent_drivers_with_registry(
+ &manager,
+ &registry,
+ DownloadSource::Official,
+ &progress,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
assert_eq!(result.upgraded, 2);
assert_eq!(result.failed.len(), 1);
@@ -3418,6 +3948,122 @@ mod agent_registry_install_tests {
assert_eq!(events.lock().unwrap().iter().filter(|event| event.step == "done").count(), 2);
}
+ #[tokio::test]
+ async fn batch_cancel_all_aborts_in_flight_downloads_without_persisting() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
+ let manager = std::sync::Arc::new(test_manager("batch-cancel-in-flight"));
+ let db_type = "oracle";
+ let version = "2.0.0";
+ // Pad the native binary to a sizeable payload so the server can stream
+ // it slowly and the download stays in-flight when cancel-all fires.
+ let body_size = 256 * 1024usize;
+ let mut native_bytes = current_platform_native_binary();
+ native_bytes.resize(body_size, 0xAA);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let native_url = format!("http://{addr}/dbx-agent-oracle");
+ let registry = registry_with_native_and_legacy_jar(db_type, version, &native_url, native_bytes.len() as u64);
+
+ // Mark the driver installed at an older version so the batch considers
+ // it updatable.
+ let mut state = manager.load_state();
+ state.java_runtime = JavaRuntimeConfig { mode: JavaRuntimeMode::System, custom_java_path: None };
+ state.installed_drivers.insert(
+ db_type.to_string(),
+ InstalledDriver {
+ version: "1.0.0".to_string(),
+ installed_at: "2026-01-01T00:00:00Z".to_string(),
+ jre: DEFAULT_JRE_KEY.to_string(),
+ },
+ );
+ manager.save_state(&state).unwrap();
+
+ // Slow server: serve the exact payload size slowly so the download is
+ // still transferring when the batch cancel-all fires.
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+ let mut buf = [0u8; 1024];
+ let _ = socket.read(&mut buf).await;
+ let header = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {body_size}\r\nContent-Type: application/octet-stream\r\nConnection: close\r\n\r\n"
+ );
+ socket.write_all(header.as_bytes()).await.expect("write header");
+ let chunk = vec![0xAAu8; 4096];
+ for _ in 0..(body_size / 4096) {
+ socket.write_all(&chunk).await.expect("write chunk");
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ });
+
+ // Register the batch operation + shared batch token (as the command
+ // layer does) and start the upgrade.
+ let operation_id = "batch-op";
+ let batch_token = manager.begin_install_cancellation(&batch_cancellation_key(operation_id)).await;
+ let batch_token_task = Arc::clone(&batch_token);
+ let started = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let started_progress = started.clone();
+ let task_manager = Arc::clone(&manager);
+ let mut batch_task = tokio::spawn(async move {
+ upgrade_all_agent_drivers_with_registry(
+ &task_manager,
+ &registry,
+ DownloadSource::Official,
+ &|event| {
+ if event.step == "driver" && event.downloaded.unwrap_or(0) > 0 {
+ started_progress.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ },
+ Some(&batch_token_task),
+ Some(operation_id),
+ )
+ .await
+ });
+
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
+ while !started.load(std::sync::atomic::Ordering::SeqCst) {
+ if tokio::time::Instant::now() >= deadline {
+ server.abort();
+ if let Ok(joined) = tokio::time::timeout(std::time::Duration::from_secs(1), &mut batch_task).await {
+ panic!("batch download never started; batch finished with: {joined:?}");
+ }
+ batch_task.abort();
+ panic!("batch download never started");
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+
+ // Cancel-all must abort the already-transferring driver.
+ cancel_agent_batch_upgrade(&manager, Some(operation_id)).await.unwrap();
+
+ let result = tokio::time::timeout(std::time::Duration::from_secs(30), batch_task)
+ .await
+ .expect("batch did not finish after cancel-all")
+ .expect("batch panicked")
+ .expect("batch returned an unexpected error");
+ server.abort();
+ manager.finish_install_cancellation(&batch_cancellation_key(operation_id), &batch_token).await;
+
+ assert_eq!(result.upgraded, 0);
+ assert!(result.failed.is_empty(), "cancelled drivers must not be reported as failed: {:?}", result.failed);
+ assert!(result.cancelled >= 1, "the in-flight driver must be reported cancelled, got {result:?}");
+ // The pre-existing install is untouched: cancel-all must not persist the
+ // new (in-flight) download as the installed version.
+ assert_eq!(
+ manager.load_state().installed_drivers.get(db_type).map(|driver| driver.version.as_str()),
+ Some("1.0.0"),
+ "batch cancel-all must not persist the cancelled download as installed"
+ );
+ assert!(
+ !manager.driver_native_path(db_type).exists(),
+ "cancelled download must not leave the driver artifact behind"
+ );
+ assert!(
+ !download_temp_path(&manager.driver_native_path(db_type)).exists(),
+ "cancelled download must clean up its temp file"
+ );
+ }
+
#[tokio::test]
async fn shared_jre_is_not_downloaded_again_after_the_first_install_persists_its_version() {
let manager = test_manager("shared-jre-deduplication");
@@ -3439,6 +4085,7 @@ mod agent_registry_install_tests {
&progress,
Some(1),
Some(2),
+ &[],
)
.await
.unwrap();
@@ -3455,6 +4102,7 @@ mod agent_registry_install_tests {
&progress,
Some(2),
Some(2),
+ &[],
)
.await
.unwrap();
@@ -3495,9 +4143,19 @@ mod agent_registry_install_tests {
&archive,
);
- ensure_jre_from_registry(&manager, &registry, DownloadSource::Official, jre_key, "dameng", &|_| {}, None, None)
- .await
- .unwrap();
+ ensure_jre_from_registry(
+ &manager,
+ &registry,
+ DownloadSource::Official,
+ jre_key,
+ "dameng",
+ &|_| {},
+ None,
+ None,
+ &[],
+ )
+ .await
+ .unwrap();
assert!(manager.is_jre_installed(jre_key));
assert_eq!(manager.load_state().jre_versions[jre_key], version);
@@ -3513,6 +4171,47 @@ mod agent_registry_install_tests {
assert_eq!(manager.load_state().pending_jre_cleanup, vec![stash]);
}
+ #[tokio::test]
+ async fn local_fallback_cancel_before_commit_preserves_existing_driver() {
+ let manager = test_manager("local-cancel-before-commit");
+ let db_type = "oracle";
+ let jar_path = manager.driver_jar_path(db_type);
+ std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
+ std::fs::write(&jar_path, b"existing-driver").unwrap();
+ manager.mutate_state(|state| record_local_agent_install(state, db_type, DEFAULT_JRE_KEY)).unwrap();
+ let token = manager.begin_install_cancellation("local-cancel-before-commit").await;
+ token.cancel();
+
+ let error = ensure_local_agent_commit_allowed(&[&token]).expect_err("a pre-commit cancel must abort");
+
+ assert!(error.contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ assert_eq!(std::fs::read(&jar_path).unwrap(), b"existing-driver");
+ assert!(manager.load_state().installed_drivers.contains_key(db_type));
+ }
+
+ #[tokio::test]
+ async fn local_fallback_cancel_after_commit_boundary_persists_replacement() {
+ let manager = test_manager("local-cancel-after-boundary");
+ let db_type = "oracle";
+ let jar_path = manager.driver_jar_path(db_type);
+ std::fs::create_dir_all(jar_path.parent().unwrap()).unwrap();
+ std::fs::write(&jar_path, b"existing-driver").unwrap();
+ manager.mutate_state(|state| record_local_agent_install(state, db_type, DEFAULT_JRE_KEY)).unwrap();
+ let source = manager.base_dir().join("replacement.jar");
+ write_test_agent_jar(&source);
+ let expected = std::fs::read(&source).unwrap();
+ let token = manager.begin_install_cancellation("local-cancel-after-boundary").await;
+
+ ensure_local_agent_commit_allowed(&[&token]).unwrap();
+ token.cancel();
+ commit_local_agent_install(&manager, db_type, &source, DEFAULT_JRE_KEY, Some("21.0.12")).await.unwrap();
+
+ assert_eq!(std::fs::read(&jar_path).unwrap(), expected);
+ let state = manager.load_state();
+ assert_eq!(state.installed_drivers[db_type].version, "0.1.0-local");
+ assert_eq!(state.jre_versions[DEFAULT_JRE_KEY], "21.0.12");
+ }
+
#[test]
fn concurrent_local_agent_state_updates_preserve_each_driver() {
let manager = test_manager("concurrent-local-agent-state");
@@ -3558,6 +4257,7 @@ mod agent_registry_install_tests {
);
let first_lock = driver_operation_lock(&manager, "oracle").await;
let first_guard = first_lock.lock().await;
+ let token = manager.begin_install_cancellation(&install_cancellation_key("batch-test")).await;
let progress = |_| {};
let blocked = tokio::time::timeout(std::time::Duration::from_millis(50), async {
@@ -3569,6 +4269,7 @@ mod agent_registry_install_tests {
&progress,
Some(1),
Some(1),
+ &[&token],
)
.await
})
@@ -3586,6 +4287,7 @@ mod agent_registry_install_tests {
&progress,
Some(1),
Some(1),
+ &[&token],
),
)
.await
@@ -3634,6 +4336,481 @@ mod agent_registry_install_tests {
.expect("JRE replacement did not resume after driver operations completed");
}
+ #[tokio::test]
+ async fn cancellation_token_lifecycle_is_scoped_and_removable() {
+ let manager = test_manager("cancel-token-lifecycle");
+ let token = manager.begin_install_cancellation("oracle").await;
+ assert!(!token.is_cancelled());
+ assert!(!manager.is_install_cancelled("oracle").await);
+
+ manager.cancel_install("oracle").await;
+ assert!(token.is_cancelled());
+ assert!(manager.is_install_cancelled("oracle").await);
+
+ manager.finish_install_cancellation("oracle", &token).await;
+ assert!(!manager.is_install_cancelled("oracle").await);
+ }
+
+ #[tokio::test]
+ async fn cancelled_install_never_enters_local_fallback() {
+ let manager = test_manager("cancel-local-fallback");
+ let token = manager.begin_install_cancellation("oracle").await;
+ assert!(can_fallback_to_local_agent(&manager, "oracle", &[&token]).await);
+
+ token.cancel();
+
+ assert!(!can_fallback_to_local_agent(&manager, "oracle", &[&token]).await);
+ }
+
+ #[tokio::test]
+ async fn finish_install_cancellation_keeps_a_fresh_token() {
+ let manager = test_manager("cancel-token-fresh");
+ let old_token = manager.begin_install_cancellation("oracle").await;
+ old_token.cancel();
+ // A new install replaces the cancelled token; finishing the OLD token
+ // must not remove the fresh one (Arc::ptr_eq guard).
+ let new_token = manager.begin_install_cancellation("oracle").await;
+ assert!(!new_token.is_cancelled());
+ manager.finish_install_cancellation("oracle", &old_token).await;
+ assert!(!manager.is_install_cancelled("oracle").await);
+
+ manager.cancel_install("oracle").await;
+ assert!(new_token.is_cancelled());
+ manager.finish_install_cancellation("oracle", &new_token).await;
+ assert!(!manager.is_install_cancelled("oracle").await);
+ }
+
+ #[tokio::test]
+ async fn download_with_progress_returns_cancelled_when_token_prefired() {
+ let manager = test_manager("cancel-download-entry");
+ let db_type = "oracle";
+ let token = manager.begin_install_cancellation(db_type).await;
+ token.cancel();
+ let dest = manager.base_dir().join("downloads").join("oracle-agent");
+ let error = download_with_progress(
+ &manager,
+ &|_| {},
+ "driver",
+ DownloadSource::Official,
+ "https://example.com/dbx-agent-oracle",
+ "agents/drivers/dbx-agent-oracle",
+ &dest,
+ 100,
+ None,
+ None,
+ Some(db_type),
+ None,
+ None,
+ &[&token],
+ )
+ .await
+ .expect_err("a pre-cancelled token must abort the download before any transfer");
+ assert!(error.contains(AGENT_DOWNLOAD_CANCELED_ERROR), "unexpected error: {error}");
+ assert!(!download_temp_path(&dest).exists());
+ assert!(!dest.exists());
+ }
+
+ #[tokio::test]
+ async fn download_with_progress_aborts_mid_stream_when_cancelled() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let manager = test_manager("cancel-mid-stream");
+ let db_type = "oracle";
+ let token = manager.begin_install_cancellation(db_type).await;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let url = format!("http://{addr}/slow-agent");
+
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+ let mut buf = [0u8; 1024];
+ let _ = socket.read(&mut buf).await;
+ let body_size = 256 * 1024usize;
+ let header = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {body_size}\r\nContent-Type: application/octet-stream\r\nConnection: close\r\n\r\n"
+ );
+ socket.write_all(header.as_bytes()).await.expect("write header");
+ let chunk = vec![0xAAu8; 4096];
+ for _ in 0..64 {
+ socket.write_all(&chunk).await.expect("write chunk");
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ });
+
+ let dest = manager.base_dir().join("downloads").join("oracle-agent");
+ let dest_assert = dest.clone();
+ let started = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let started_progress = started.clone();
+ let token_for_task = Arc::clone(&token);
+ let task = tokio::spawn(async move {
+ download_with_progress(
+ &manager,
+ &|event| {
+ if event.step == "driver" && event.downloaded.unwrap_or(0) > 0 {
+ started_progress.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ },
+ "driver",
+ DownloadSource::Official,
+ &url,
+ "agents/drivers/dbx-agent-oracle",
+ &dest,
+ 256 * 1024,
+ None,
+ None,
+ Some(db_type),
+ None,
+ None,
+ &[&token_for_task],
+ )
+ .await
+ });
+
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(15);
+ while !started.load(std::sync::atomic::Ordering::SeqCst) {
+ if tokio::time::Instant::now() >= deadline {
+ server.abort();
+ panic!("download never started (external mirror probe may have stalled)");
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ token.cancel();
+
+ let result = tokio::time::timeout(std::time::Duration::from_secs(15), task)
+ .await
+ .expect("download task did not finish after cancel")
+ .expect("download task panicked");
+ server.abort();
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ assert!(!download_temp_path(&dest_assert).exists());
+ assert!(!dest_assert.exists());
+ }
+
+ #[test]
+ fn cancelled_error_classification_distinguishes_user_cancel() {
+ assert!(is_cancelled_error(AGENT_DOWNLOAD_CANCELED_ERROR));
+ assert!(is_cancelled_error(&format!("prefix {AGENT_DOWNLOAD_CANCELED_ERROR} suffix")));
+ assert!(!is_cancelled_error("Download failed: 404 Not Found"));
+ }
+
+ #[tokio::test]
+ async fn cancel_during_driver_lock_wait_aborts_install_before_persist() {
+ let manager = std::sync::Arc::new(test_manager("cancel-lock-wait"));
+ let db_type = "oracle";
+ // Command scope: the token is registered before any awaitable setup.
+ let cancellation = manager.begin_install_cancellation(db_type).await;
+ let cancel_handle = Arc::clone(&cancellation);
+ // Hold the driver lock so the install blocks on it.
+ let lock = driver_operation_lock(&manager, db_type).await;
+ let _guard = lock.lock().await;
+
+ let install_manager = Arc::clone(&manager);
+ let install = tokio::spawn(async move {
+ install_agent_driver_from_claimed(
+ &install_manager,
+ db_type,
+ DownloadSource::Official,
+ |_| {},
+ &cancellation,
+ )
+ .await
+ });
+ // Let the install reach the lock wait, then cancel.
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ cancel_handle.cancel();
+
+ // The guard is still held: the install must observe its token and
+ // return promptly instead of waiting for the lock holder to finish.
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), install)
+ .await
+ .expect("install task did not finish after cancel while the driver lock was still held")
+ .expect("install task panicked");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ // Cancellation observed while waiting on the lock must never persist state.
+ assert!(!manager.load_state().installed_drivers.contains_key(db_type));
+ drop(_guard);
+ manager.finish_install_cancellation(db_type, &cancel_handle).await;
+ }
+
+ #[tokio::test]
+ async fn cancelled_install_aborts_while_waiting_for_jre_lock() {
+ let manager = std::sync::Arc::new(test_manager("cancel-jre-lock-wait"));
+ let db_type = "oracle";
+ let registry = registry_with_jre_version("21.0.12");
+ let cancellation = manager.begin_install_cancellation(&install_cancellation_key("jre-lock-wait")).await;
+ let cancel_handle = Arc::clone(&cancellation);
+ // Hold the JRE lock so the install blocks on it before downloading.
+ let lock = jre_operation_lock(&manager, DEFAULT_JRE_KEY).await;
+ let _guard = lock.lock().await;
+
+ let install_manager = Arc::clone(&manager);
+ let install = tokio::spawn(async move {
+ ensure_jre_from_registry(
+ &install_manager,
+ &registry,
+ DownloadSource::Official,
+ DEFAULT_JRE_KEY,
+ db_type,
+ &|_| {},
+ None,
+ None,
+ &[&cancellation],
+ )
+ .await
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ cancel_handle.cancel();
+
+ // The guard is still held: the JRE wait must abort on the token
+ // instead of waiting for the lock holder to finish.
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), install)
+ .await
+ .expect("JRE wait did not finish after cancel while the JRE lock was still held")
+ .expect("JRE wait panicked");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ // Nothing must have been downloaded or persisted.
+ assert!(!manager.jre_dir(DEFAULT_JRE_KEY).exists());
+ assert!(manager.load_state().jre_versions.is_empty());
+ drop(_guard);
+ manager.finish_install_cancellation(&install_cancellation_key("jre-lock-wait"), &cancel_handle).await;
+ }
+
+ #[tokio::test]
+ async fn download_with_progress_aborts_before_response_headers_when_cancelled() {
+ use tokio::io::AsyncReadExt;
+ let manager = test_manager("cancel-stalled-headers");
+ let db_type = "oracle";
+ let token = manager.begin_install_cancellation(db_type).await;
+ // A mirror that accepts connections but never sends response headers -
+ // without racing `request.send()` against cancellation the install
+ // would hang here until the 300s client timeout.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let url = format!("http://{addr}/stalled-agent");
+ let server = tokio::spawn(async move {
+ loop {
+ let Ok((mut socket, _)) = listener.accept().await else { break };
+ // Read the request, then never respond.
+ let mut buf = [0u8; 1024];
+ let _ = socket.read(&mut buf).await;
+ let _ = socket.read(&mut buf).await;
+ }
+ });
+
+ let dest = manager.base_dir().join("downloads").join("oracle-agent");
+ let dest_assert = dest.clone();
+ let token_for_task = Arc::clone(&token);
+ let task = tokio::spawn(async move {
+ download_with_progress(
+ &manager,
+ &|_| {},
+ "driver",
+ DownloadSource::Official,
+ &url,
+ "agents/drivers/dbx-agent-oracle",
+ &dest,
+ 256 * 1024,
+ None,
+ None,
+ Some(db_type),
+ None,
+ None,
+ &[&token_for_task],
+ )
+ .await
+ });
+ // The request is now pending on the stalled mirror; cancel must abort
+ // it long before the 300s timeout.
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ token.cancel();
+
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), task)
+ .await
+ .expect("download did not abort after cancel while response headers were stalled")
+ .expect("download task panicked");
+ server.abort();
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ assert!(!download_temp_path(&dest_assert).exists());
+ assert!(!dest_assert.exists());
+ }
+
+ #[tokio::test]
+ async fn fetch_registry_aborts_when_cancelled_while_request_stalled() {
+ use tokio::io::AsyncReadExt;
+ let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
+ invalidate_registry_cache().await;
+ let manager = test_manager("cancel-registry-stalled-headers");
+ let token = manager.begin_install_cancellation("registry-fetch").await;
+ // A registry mirror that accepts connections but never sends response
+ // headers - without racing `request.send()` against cancellation the
+ // registry fetch would hang until the 10s client timeout.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let url = format!("http://{addr}/stalled-registry.json");
+ let server = tokio::spawn(async move {
+ let Ok((mut socket, _)) = listener.accept().await else { return };
+ // Read the request, then never respond.
+ let mut buf = [0u8; 1024];
+ let _ = socket.read(&mut buf).await;
+ let _ = socket.read(&mut buf).await;
+ });
+
+ let token_for_task = Arc::clone(&token);
+ let task = tokio::spawn(async move {
+ let urls = vec![url];
+ fetch_registry_from_urls(DownloadSource::Official, &urls, &[token_for_task.as_ref()]).await
+ });
+ // The request is now pending on the stalled mirror; cancel must abort
+ // it long before the 10s client timeout.
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ token.cancel();
+
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), task)
+ .await
+ .expect("registry fetch did not abort after cancel while response headers were stalled")
+ .expect("registry fetch task panicked");
+ server.abort();
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ }
+
+ #[tokio::test]
+ async fn fetch_registry_aborts_when_cancelled_while_body_stalled() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
+ invalidate_registry_cache().await;
+ let manager = test_manager("cancel-registry-stalled-body");
+ let token = manager.begin_install_cancellation("registry-fetch").await;
+ // A registry mirror that sends response headers plus a small partial
+ // body, then stalls before satisfying Content-Length - without racing
+ // `resp.json()` against cancellation the registry fetch would hang
+ // until the 10s client timeout.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let url = format!("http://{addr}/partial-registry.json");
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+ let mut buf = [0u8; 1024];
+ let _ = socket.read(&mut buf).await;
+ let header = "HTTP/1.1 200 OK\r\nContent-Length: 65536\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n";
+ socket.write_all(header.as_bytes()).await.expect("write header");
+ // A truncated JSON body: the client keeps waiting for the remaining
+ // bytes to satisfy Content-Length.
+ socket.write_all(b"{\"drivers\": {}}").await.expect("write partial body");
+ let mut drain = [0u8; 1024];
+ let _ = socket.read(&mut drain).await;
+ });
+
+ let token_for_task = Arc::clone(&token);
+ let task = tokio::spawn(async move {
+ let urls = vec![url];
+ fetch_registry_from_urls(DownloadSource::Official, &urls, &[token_for_task.as_ref()]).await
+ });
+ // The body parse is now waiting on the stalled mirror; cancel must
+ // abort it during parsing, not after the 10s client timeout.
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ token.cancel();
+
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), task)
+ .await
+ .expect("registry fetch did not abort after cancel while the response body was stalled")
+ .expect("registry fetch task panicked");
+ server.abort();
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ }
+
+ #[tokio::test]
+ async fn fetch_registry_precancelled_token_aborts_before_any_network_attempt() {
+ let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
+ invalidate_registry_cache().await;
+ let manager = test_manager("cancel-registry-prefired");
+ let token = manager.begin_install_cancellation("registry-fetch").await;
+ token.cancel();
+
+ // Point at a port that would refuse/never answer: the entry check must
+ // abort before any network attempt, so the result is the cancel error,
+ // not a connection/timeout error.
+ let urls = vec!["http://127.0.0.1:1/stalled-registry.json".to_string()];
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ fetch_registry_from_urls(DownloadSource::Official, &urls, &[token.as_ref()]),
+ )
+ .await
+ .expect("pre-cancelled registry fetch must return immediately")
+ .expect_err("pre-cancelled token must abort the registry fetch");
+ assert!(result.contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+ }
+
+ #[tokio::test]
+ async fn concurrent_same_driver_installs_cancel_only_the_targeted_operation() {
+ let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
+ let manager = std::sync::Arc::new(test_manager("concurrent-same-driver-cancel"));
+ let db_type = "oracle";
+ let version = "0.1.31";
+ let native_url = "https://example.com/dbx-agent-oracle";
+ let native_bytes = b"native-agent";
+ let registry = registry_with_native_and_legacy_jar(db_type, version, native_url, native_bytes.len() as u64);
+ write_cached_driver_download(
+ &manager,
+ db_type,
+ version,
+ native_url,
+ &manager.driver_native_path(db_type),
+ native_bytes,
+ );
+ cache_test_registry(registry).await;
+
+ // Two independent operations for the SAME driver, each with its own
+ // operation id and therefore its own cancellation token.
+ let op_a = "operation-a";
+ let op_b = "operation-b";
+ let token_a = manager.begin_install_cancellation(&install_cancellation_key(op_a)).await;
+ let token_b = manager.begin_install_cancellation(&install_cancellation_key(op_b)).await;
+
+ // Hold the driver lock so both installs block on it.
+ let lock = driver_operation_lock(&manager, db_type).await;
+ let _guard = lock.lock().await;
+
+ let manager_a = Arc::clone(&manager);
+ let manager_b = Arc::clone(&manager);
+ let token_a_task = Arc::clone(&token_a);
+ let token_b_task = Arc::clone(&token_b);
+ let install_a = tokio::spawn(async move {
+ install_agent_driver_from_claimed(&manager_a, db_type, DownloadSource::Cnb, |_| {}, &token_a_task).await
+ });
+ let install_b = tokio::spawn(async move {
+ install_agent_driver_from_claimed(&manager_b, db_type, DownloadSource::Cnb, |_| {}, &token_b_task).await
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+
+ // Cancel operation A only; operation B must be unaffected.
+ cancel_agent_driver_install(&manager, db_type, Some(op_a)).await.unwrap();
+ assert!(!token_b.is_cancelled(), "cancelling operation A must not cancel operation B");
+ drop(_guard);
+
+ let result_a = tokio::time::timeout(std::time::Duration::from_secs(5), install_a)
+ .await
+ .expect("install A did not finish after cancel")
+ .expect("install A panicked");
+ assert!(result_a.is_err());
+ assert!(result_a.unwrap_err().contains(AGENT_DOWNLOAD_CANCELED_ERROR));
+
+ let result_b = tokio::time::timeout(std::time::Duration::from_secs(5), install_b)
+ .await
+ .expect("install B did not finish")
+ .expect("install B panicked");
+ assert!(result_b.is_ok(), "operation A's cancel must not abort operation B: {:?}", result_b.err());
+
+ // Only the completed operation B persists installed state.
+ assert_eq!(manager.load_state().installed_drivers[db_type].version, version);
+ manager.finish_install_cancellation(&install_cancellation_key(op_a), &token_a).await;
+ manager.finish_install_cancellation(&install_cancellation_key(op_b), &token_b).await;
+ }
+
#[tokio::test]
async fn registry_install_rejects_corrupt_downloaded_jar() {
let manager = test_manager("corrupt-jar");
@@ -3660,6 +4837,7 @@ mod agent_registry_install_tests {
&progress,
None,
None,
+ &[],
)
.await
.unwrap_err();
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 59c253a04f..e363e75953 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -378,7 +378,9 @@ async fn main() {
.route("/agents/runtime/stop", post(routes::agents::stop_driver_runtime))
.route("/agents/runtime/restart", post(routes::agents::restart_driver_runtime))
.route("/agents/install", post(routes::agents::install_agent))
+ .route("/agents/cancel-install", post(routes::agents::cancel_install))
.route("/agents/upgrade-all", post(routes::agents::upgrade_all_agents))
+ .route("/agents/cancel-upgrade-all", post(routes::agents::cancel_upgrade_all))
.route("/agents/update-blockers", post(routes::agents::check_agent_update_blockers))
.route("/agents/uninstall", post(routes::agents::uninstall_agent))
.route("/agents/import-offline", post(routes::agents::import_agents_from_zip))
diff --git a/crates/dbx-web/src/routes/agents.rs b/crates/dbx-web/src/routes/agents.rs
index 1a833cc2a8..3fce5f406a 100644
--- a/crates/dbx-web/src/routes/agents.rs
+++ b/crates/dbx-web/src/routes/agents.rs
@@ -7,10 +7,12 @@ use dbx_core::agent_manager::{
AgentDriverInfo, AgentState, DriverStoreUsage, JavaRuntimeConfig, JavaRuntimeMode, DEFAULT_JRE_KEY,
};
use dbx_core::agent_service::{
- build_agent_list, clear_agent_download_cache, fetch_registry, import_agent_driver,
- import_agents_from_package as import_agents_from_package_core, inspect_offline_package, install_agent_driver,
- invalidate_registry_cache, reinstall_agent_jre, uninstall_agent_driver, uninstall_agent_jre,
- upgrade_all_agent_drivers, AgentProgressEvent, OfflineImportPlan,
+ batch_cancellation_key, build_agent_list, cancel_agent_batch_upgrade, cancel_agent_driver_install,
+ clear_agent_download_cache, fetch_registry, fetch_registry_from_claimed, import_agent_driver,
+ import_agents_from_package as import_agents_from_package_core, inspect_offline_package,
+ install_agent_driver_claimed, install_cancellation_key, invalidate_registry_cache, reinstall_agent_jre,
+ uninstall_agent_driver, uninstall_agent_jre, upgrade_all_agent_drivers_claimed, AgentProgressEvent,
+ OfflineImportPlan,
};
use dbx_core::driver_runtime::DriverRuntimeSummary;
use futures::Stream;
@@ -120,34 +122,86 @@ pub async fn install_agent(
State(state): State<Arc<WebState>>,
Json(req): Json<AgentTypeRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- ensure_no_agent_update_blockers(&state.app, std::slice::from_ref(&req.db_type)).await.map_err(AppError::from)?;
- let operation_id = req.operation_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
- let tx = progress_sender(&state, "global").await;
- install_agent_driver(&state.app.agent_manager, &req.db_type, |event| {
- send_progress_event(&tx, event.with_operation_id(&operation_id))
- })
- .await
- .map_err(AppError::from)?;
- Ok(Json(serde_json::json!({ "ok": true })))
+ // Resolve the operation id first, then register the cancellation token under
+ // it BEFORE any awaitable setup (blocker check, lock wait, registry fetch)
+ // so a cancel fired while the modal is showing is observed by this exact
+ // install instead of being silently lost or crossing into a second
+ // same-driver install.
+ let operation_id = req.operation_id.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
+ let cancellation =
+ state.app.agent_manager.begin_install_cancellation(&install_cancellation_key(&operation_id)).await;
+ let result = async {
+ ensure_no_agent_update_blockers(&state.app, std::slice::from_ref(&req.db_type))
+ .await
+ .map_err(AppError::from)?;
+ let tx = progress_sender(&state, "global").await;
+ install_agent_driver_claimed(
+ &state.app.agent_manager,
+ &req.db_type,
+ |event| send_progress_event(&tx, event.with_operation_id(&operation_id)),
+ &cancellation,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(serde_json::json!({ "ok": true })))
+ }
+ .await;
+ state.app.agent_manager.finish_install_cancellation(&install_cancellation_key(&operation_id), &cancellation).await;
+ result
}
pub async fn upgrade_all_agents(
State(state): State<Arc<WebState>>,
Json(req): Json<AgentOperationRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
- let registry = fetch_registry().await.map_err(AppError::from)?;
- let agents = build_agent_list(&state.app.agent_manager, Some(&registry));
- let updatable: Vec<String> =
- agents.iter().filter(|agent| agent.update_available).map(|agent| agent.db_type.clone()).collect();
- ensure_no_agent_update_blockers(&state.app, &updatable).await.map_err(AppError::from)?;
- let operation_id = req.operation_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
- let tx = progress_sender(&state, "global").await;
- let result = upgrade_all_agent_drivers(&state.app.agent_manager, |event| {
- send_progress_event(&tx, event.with_operation_id(&operation_id))
- })
- .await
- .map_err(AppError::from)?;
- Ok(Json(serde_json::to_value(result).map_err(|err| AppError::from(err.to_string()))?))
+ // Resolve the batch operation id first, then register the batch token under
+ // it BEFORE the registry fetch + blocker check so a cancel fired while the
+ // batch is still setting up aborts it.
+ let operation_id = req.operation_id.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
+ let cancellation = state.app.agent_manager.begin_install_cancellation(&batch_cancellation_key(&operation_id)).await;
+ let result = async {
+ // The batch token is registered above; race the pre-blocker registry
+ // fetch against it so a cancel fired during batch setup aborts promptly
+ // instead of waiting out the 10s client timeout.
+ let registry = fetch_registry_from_claimed(dbx_core::DownloadSource::Official, &[cancellation.as_ref()])
+ .await
+ .map_err(AppError::from)?;
+ let agents = build_agent_list(&state.app.agent_manager, Some(&registry));
+ let updatable: Vec<String> =
+ agents.iter().filter(|agent| agent.update_available).map(|agent| agent.db_type.clone()).collect();
+ ensure_no_agent_update_blockers(&state.app, &updatable).await.map_err(AppError::from)?;
+ let tx = progress_sender(&state, "global").await;
+ let result = upgrade_all_agent_drivers_claimed(
+ &state.app.agent_manager,
+ |event| send_progress_event(&tx, event.with_operation_id(&operation_id)),
+ &cancellation,
+ &operation_id,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(serde_json::to_value(result).map_err(|err| AppError::from(err.to_string()))?))
+ }
+ .await;
+ state.app.agent_manager.finish_install_cancellation(&batch_cancellation_key(&operation_id), &cancellation).await;
+ result
+}
+
+pub async fn cancel_install(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<AgentTypeRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ cancel_agent_driver_install(&state.app.agent_manager, &req.db_type, req.operation_id.as_deref())
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
+
+pub async fn cancel_upgrade_all(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<AgentOperationRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ cancel_agent_batch_upgrade(&state.app.agent_manager, req.operation_id.as_deref()).await.map_err(AppError::from)?;
+ Ok(Json(serde_json::json!({ "ok": true })))
}
pub async fn check_agent_update_blockers(
diff --git a/packages/app-tests/driverInstallProgressUi.test.ts b/packages/app-tests/driverInstallProgressUi.test.ts
index 8bdc7b9515..cc1a2603a5 100644
--- a/packages/app-tests/driverInstallProgressUi.test.ts
+++ b/packages/app-tests/driverInstallProgressUi.test.ts
@@ -1,7 +1,17 @@
import assert from "node:assert/strict";
import { test } from "vitest";
-import { addDriverInstallQueue, driverInstallProgressPercent, isDriverInstallProgressTarget, removeDriverInstallQueue, takeNextDriverInstallQueue } from "../../apps/desktop/src/lib/connection/driverInstallProgressUi.ts";
+import {
+ addDriverInstallQueue,
+ driverInstallProgressPercent,
+ isDriverInstallCanceledError,
+ isDriverInstallCancellationTarget,
+ isDriverInstallProgressTarget,
+ removeDriverInstallQueue,
+ requestAgentInstallCancellation,
+ resolveAgentInstallOutcome,
+ takeNextDriverInstallQueue,
+} from "../../apps/desktop/src/lib/connection/driverInstallProgressUi.ts";
test("formats driver install progress as a bounded whole percent", () => {
assert.equal(driverInstallProgressPercent({ step: "driver", downloaded: 3_900_000, total: 10_500_000 }), 37);
@@ -28,6 +38,57 @@ test("targets only the row currently installing or upgrading", () => {
);
});
+test("shows single-driver cancel only after the cancellable agent operation starts", () => {
+ assert.equal(
+ isDriverInstallCancellationTarget("mysql", {
+ activeOperationId: null,
+ cancellableDbType: null,
+ upgradingAll: false,
+ progressMap: {},
+ }),
+ false,
+ );
+ assert.equal(
+ isDriverInstallCancellationTarget("mysql", {
+ activeOperationId: "operation-a",
+ cancellableDbType: "mysql",
+ upgradingAll: false,
+ progressMap: {},
+ }),
+ true,
+ );
+ assert.equal(
+ isDriverInstallCancellationTarget("postgres", {
+ activeOperationId: "operation-a",
+ cancellableDbType: "mysql",
+ upgradingAll: false,
+ progressMap: {},
+ }),
+ false,
+ );
+});
+
+test("keeps batch row cancellation scoped to registered progress entries", () => {
+ assert.equal(
+ isDriverInstallCancellationTarget("postgres", {
+ activeOperationId: "batch-a",
+ cancellableDbType: null,
+ upgradingAll: true,
+ progressMap: { postgres: { step: "driver", db_type: "postgres" } },
+ }),
+ true,
+ );
+ assert.equal(
+ isDriverInstallCancellationTarget("mysql", {
+ activeOperationId: "batch-a",
+ cancellableDbType: null,
+ upgradingAll: true,
+ progressMap: { postgres: { step: "driver", db_type: "postgres" } },
+ }),
+ false,
+ );
+});
+
test("adds queued driver installs without duplicating the active or queued driver", () => {
assert.deepEqual(addDriverInstallQueue(["postgres"], "mysql", "sqlite"), ["postgres", "mysql"]);
assert.deepEqual(addDriverInstallQueue(["postgres"], "postgres", "sqlite"), ["postgres"]);
@@ -44,3 +105,82 @@ test("takes the next installable queued driver and drops stale queued drivers",
assert.equal(result.next, "mysql");
assert.deepEqual(result.queue, ["sqlite"]);
});
+
+test("recognizes a user-cancelled driver install error", () => {
+ assert.equal(isDriverInstallCanceledError(new Error("Agent download canceled by user.")), true);
+ assert.equal(isDriverInstallCanceledError("prefix Agent download canceled by user. suffix"), true);
+ assert.equal(isDriverInstallCanceledError({ message: "Agent download canceled by user." }), true);
+ assert.equal(isDriverInstallCanceledError("Failed to install driver: 404"), false);
+ assert.equal(isDriverInstallCanceledError(null), false);
+ assert.equal(isDriverInstallCanceledError(undefined), false);
+});
+
+test("a failed cancel request keeps the install outcome as a real failure", async () => {
+ const result = await requestAgentInstallCancellation(async () => {
+ throw new Error("cancel transport failed");
+ });
+
+ assert.equal(result.ok, false);
+ if (result.ok) assert.fail("cancel request must fail");
+ assert.match(String(result.error), /cancel transport failed/);
+ assert.deepEqual(
+ resolveAgentInstallOutcome(
+ { ok: false, error: new Error("download failed") },
+ {
+ operationId: "operation-a",
+ currentOperationId: "operation-a",
+ cancelRequested: result.ok,
+ },
+ ),
+ { kind: "failed", ownsState: true },
+ );
+});
+
+test("cancel then immediate retry: the stale operation never owns the dialog state", () => {
+ // The dialog flow: operation A begins, the user cancels (the cancel handler
+ // finishes the dialog, clearing the tracked id), then retries - operation B
+ // begins - before A's install promise settles.
+ const staleContext = {
+ operationId: "operation-a",
+ currentOperationId: "operation-b",
+ cancelRequested: false,
+ };
+
+ const cancelled = resolveAgentInstallOutcome({ ok: false, error: new Error("Agent download canceled by user.") }, staleContext);
+ assert.equal(cancelled.kind, "cancelled");
+ assert.equal(cancelled.ownsState, false);
+
+ const succeeded = resolveAgentInstallOutcome({ ok: true }, staleContext);
+ assert.equal(succeeded.kind, "succeeded");
+ assert.equal(succeeded.ownsState, false);
+
+ const failed = resolveAgentInstallOutcome({ ok: false, error: new Error("Download failed: 404") }, staleContext);
+ assert.equal(failed.kind, "failed");
+ assert.equal(failed.ownsState, false);
+});
+
+test("cancel without retry: the cleared dialog is not re-failed by the old promise", () => {
+ // After the cancel handler ran, no operation is tracked, so the old
+ // promise's settlement must not own state either.
+ const clearedContext = {
+ operationId: "operation-a",
+ currentOperationId: null,
+ cancelRequested: true,
+ };
+
+ const cancelled = resolveAgentInstallOutcome({ ok: false, error: new Error("Download failed: 404") }, clearedContext);
+ assert.equal(cancelled.kind, "cancelled");
+ assert.equal(cancelled.ownsState, false);
+});
+
+test("the active operation owns the dialog state on every outcome", () => {
+ const context = {
+ operationId: "operation-a",
+ currentOperationId: "operation-a",
+ cancelRequested: false,
+ };
+
+ assert.deepEqual(resolveAgentInstallOutcome({ ok: true }, context), { kind: "succeeded", ownsState: true });
+ assert.deepEqual(resolveAgentInstallOutcome({ ok: false, error: new Error("Agent download canceled by user.") }, context), { kind: "cancelled", ownsState: true });
+ assert.deepEqual(resolveAgentInstallOutcome({ ok: false, error: new Error("Download failed: 404") }, context), { kind: "failed", ownsState: true });
+});
diff --git a/src-tauri/src/commands/agents.rs b/src-tauri/src/commands/agents.rs
index b3e774c4fe..ac322e778a 100644
--- a/src-tauri/src/commands/agents.rs
+++ b/src-tauri/src/commands/agents.rs
@@ -4,10 +4,12 @@ use tauri::{Emitter, State};
use dbx_core::agent_manager::{AgentDriverInfo, DriverStoreUsage, JavaRuntimeConfig, JavaRuntimeMode, DEFAULT_JRE_KEY};
use dbx_core::agent_service::{
- build_agent_list, clear_agent_download_cache, fetch_registry_from, import_agent_driver,
- import_agents_from_package as import_agents_from_package_core, inspect_offline_package, install_agent_driver_from,
- invalidate_registry_cache, reinstall_agent_jre_from, uninstall_agent_driver, uninstall_agent_jre,
- upgrade_all_agent_drivers_from, AgentProgressEvent, OfflineImportPlan, UpgradeAllAgentDriversResult,
+ batch_cancellation_key, build_agent_list, cancel_agent_batch_upgrade, cancel_agent_driver_install,
+ clear_agent_download_cache, fetch_registry_from, fetch_registry_from_claimed, import_agent_driver,
+ import_agents_from_package as import_agents_from_package_core, inspect_offline_package,
+ install_agent_driver_from_claimed, install_cancellation_key, invalidate_registry_cache, reinstall_agent_jre_from,
+ uninstall_agent_driver, uninstall_agent_jre, upgrade_all_agent_drivers_from_claimed, AgentProgressEvent,
+ OfflineImportPlan, UpgradeAllAgentDriversResult,
};
use dbx_core::connection::AppState;
use dbx_core::driver_runtime::DriverRuntimeSummary;
@@ -71,13 +73,29 @@ pub async fn install_agent(
source: Option<DownloadSource>,
operation_id: Option<String>,
) -> Result<(), String> {
- ensure_no_agent_update_blockers(state.inner().as_ref(), std::slice::from_ref(&db_type)).await?;
- let app_handle = app.clone();
+ // Resolve the operation id first, then register the cancellation token
+ // under it BEFORE any awaitable setup (blocker check, lock wait, registry
+ // fetch) so a cancel fired while the UI shows the modal is observed by this
+ // exact install instead of being silently lost or crossing into a second
+ // same-driver install.
let operation_id = operation_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
- install_agent_driver_from(&state.agent_manager, &db_type, source.unwrap_or_default(), move |event| {
- emit_agent_progress(&app_handle, &operation_id, event)
- })
- .await
+ let cancellation = state.agent_manager.begin_install_cancellation(&install_cancellation_key(&operation_id)).await;
+ let result = async {
+ ensure_no_agent_update_blockers(state.inner().as_ref(), std::slice::from_ref(&db_type)).await?;
+ let app_handle = app.clone();
+ let progress_operation_id = operation_id.clone();
+ install_agent_driver_from_claimed(
+ &state.agent_manager,
+ &db_type,
+ source.unwrap_or_default(),
+ move |event| emit_agent_progress(&app_handle, &progress_operation_id, event),
+ &cancellation,
+ )
+ .await
+ }
+ .await;
+ state.agent_manager.finish_install_cancellation(&install_cancellation_key(&operation_id), &cancellation).await;
+ result
}
#[tauri::command]
@@ -88,17 +106,48 @@ pub async fn upgrade_all_agents(
operation_id: Option<String>,
) -> Result<UpgradeAllAgentDriversResult, String> {
let source = source.unwrap_or_default();
- let registry = fetch_registry_from(source).await?;
- let agents = build_agent_list(&state.agent_manager, Some(&registry));
- let updatable: Vec<String> =
- agents.iter().filter(|agent| agent.update_available).map(|agent| agent.db_type.clone()).collect();
- ensure_no_agent_update_blockers(state.inner().as_ref(), &updatable).await?;
- let app_handle = app.clone();
+ // Resolve the batch operation id first, then register the batch token under
+ // it BEFORE the registry fetch + blocker check so a cancel fired while the
+ // batch is still setting up aborts it instead of being lost.
let operation_id = operation_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
- upgrade_all_agent_drivers_from(&state.agent_manager, source, move |event| {
- emit_agent_progress(&app_handle, &operation_id, event)
- })
- .await
+ let cancellation = state.agent_manager.begin_install_cancellation(&batch_cancellation_key(&operation_id)).await;
+ let result = async {
+ let registry = fetch_registry_from_claimed(source, &[cancellation.as_ref()]).await?;
+ let agents = build_agent_list(&state.agent_manager, Some(&registry));
+ let updatable: Vec<String> =
+ agents.iter().filter(|agent| agent.update_available).map(|agent| agent.db_type.clone()).collect();
+ ensure_no_agent_update_blockers(state.inner().as_ref(), &updatable).await?;
+ let app_handle = app.clone();
+ let progress_operation_id = operation_id.clone();
+ upgrade_all_agent_drivers_from_claimed(
+ &state.agent_manager,
+ source,
+ move |event| emit_agent_progress(&app_handle, &progress_operation_id, event),
+ &cancellation,
+ &operation_id,
+ )
+ .await
+ }
+ .await;
+ state.agent_manager.finish_install_cancellation(&batch_cancellation_key(&operation_id), &cancellation).await;
+ result
+}
+
+#[tauri::command]
+pub async fn cancel_agent_install(
+ state: State<'_, Arc<AppState>>,
+ db_type: String,
+ operation_id: Option<String>,
+) -> Result<(), String> {
+ cancel_agent_driver_install(&state.agent_manager, &db_type, operation_id.as_deref()).await
+}
+
+#[tauri::command]
+pub async fn cancel_agent_upgrade_all(
+ state: State<'_, Arc<AppState>>,
+ operation_id: Option<String>,
+) -> Result<(), String> {
+ cancel_agent_batch_upgrade(&state.agent_manager, operation_id.as_deref()).await
}
#[tauri::command]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index b171728b4d..c331051f1c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2256,7 +2256,9 @@ pub fn run() {
commands::agents::stop_driver_runtime,
commands::agents::restart_driver_runtime,
commands::agents::install_agent,
+ commands::agents::cancel_agent_install,
commands::agents::upgrade_all_agents,
+ commands::agents::cancel_agent_upgrade_all,
commands::agents::check_agent_update_blockers,
commands::agents::uninstall_agent,
commands::agents::check_jre_installed,