25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(agent): export managed drivers for offline use
Guoyu Su82e5756325cf
diff --git a/apps/desktop/src/components/config/AgentOfflineExportDialog.vue b/apps/desktop/src/components/config/AgentOfflineExportDialog.vuenew file mode 100644index 0000000000..c0a1c098e7--- /dev/null+++ b/apps/desktop/src/components/config/AgentOfflineExportDialog.vue@@ -0,0 +1,190 @@+<script setup lang="ts">+import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { FileArchive, Loader2, ShieldCheck } from "@lucide/vue";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { ScrollArea } from "@/components/ui/scroll-area";+import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";+import type { AgentOfflineExportCandidate, AgentOfflineExportPreview, AgentOfflineExportUnavailableReason } from "@/lib/backend/api";++const props = defineProps<{+ open: boolean;+ preview: AgentOfflineExportPreview | null;+ loading?: boolean;+ exporting?: boolean;+ error?: string;+}>();++const emit = defineEmits<{+ "update:open": [value: boolean];+ confirm: [driverKeys: string[]];+}>();++const { t } = useI18n();+const selectedDriverKeys = ref<string[]>([]);++const dialogOpen = computed({+ get: () => props.open,+ set: (value) => {+ if (props.exporting && !value) return;+ emit("update:open", value);+ },+});++const candidates = computed(() => props.preview?.candidates ?? []);+const eligibleCandidates = computed(() => candidates.value.filter((candidate) => candidate.eligible));+const selectedCandidates = computed(() => eligibleCandidates.value.filter((candidate) => selectedDriverKeys.value.includes(candidate.dbType)));+const selectedJres = computed(() => new Set(selectedCandidates.value.map((candidate) => candidate.requiredJre).filter((jre): jre is string => Boolean(jre))));+const selectedCount = computed(() => selectedDriverKeys.value.length);+const canConfirm = computed(() => selectedCount.value > 0 && !props.loading && !props.exporting && !props.error);++watch(+ () => [props.open, props.preview] as const,+ ([open]) => {+ if (open && props.preview) {+ selectedDriverKeys.value = eligibleCandidates.value.map((candidate) => candidate.dbType);+ }+ },+ { immediate: true },+);++function isSelected(dbType: string) {+ return selectedDriverKeys.value.includes(dbType);+}++function toggle(dbType: string, checked: boolean) {+ if (checked) {+ if (!selectedDriverKeys.value.includes(dbType)) {+ selectedDriverKeys.value = [...selectedDriverKeys.value, dbType];+ }+ return;+ }+ selectedDriverKeys.value = selectedDriverKeys.value.filter((selected) => selected !== dbType);+}++function selectAll() {+ selectedDriverKeys.value = eligibleCandidates.value.map((candidate) => candidate.dbType);+}++function clearSelection() {+ selectedDriverKeys.value = [];+}++function confirm() {+ if (!canConfirm.value) return;+ emit("confirm", [...selectedDriverKeys.value]);+}++function formatSize(bytes: number) {+ if (!bytes) return "";+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+}++function artifactLabel(candidate: AgentOfflineExportCandidate) {+ if (candidate.artifactKind === "jar") return t("driverStore.offlineExportArtifactJar");+ if (candidate.artifactKind === "native") return t("driverStore.offlineExportArtifactNative");+ return t("driverStore.offlineExportArtifactUnknown");+}++function unavailableReason(reason: AgentOfflineExportUnavailableReason | null) {+ return reason ? t(`driverStore.offlineExportUnavailable_${reason}`) : "";+}+</script>++<template>+ <Dialog v-model:open="dialogOpen">+ <DialogContent class="sm:max-w-[640px]">+ <DialogHeader>+ <DialogTitle class="flex items-center gap-2">+ <FileArchive class="h-5 w-5" />+ {{ t("driverStore.offlineExportTitle") }}+ </DialogTitle>+ </DialogHeader>++ <div class="grid gap-3 py-2" :aria-busy="loading || exporting">+ <p class="text-sm text-muted-foreground">{{ t("driverStore.offlineExportDescription") }}</p>++ <div v-if="preview" class="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-3 py-2 text-xs">+ <span>+ {{ t("driverStore.offlineExportPlatform") }}+ <Badge variant="outline" class="ml-1 font-mono">{{ preview.platform }}</Badge>+ </span>+ <span class="text-muted-foreground">+ {{ t("driverStore.offlineExportSelectedCount", { selected: selectedCount, total: eligibleCandidates.length }) }}+ </span>+ </div>++ <div v-if="loading" role="status" aria-live="polite" class="flex h-64 items-center justify-center gap-2 text-sm text-muted-foreground">+ <Loader2 class="h-4 w-4 animate-spin" />+ {{ t("driverStore.offlineExportPreparing") }}+ </div>+ <div v-else-if="error" role="alert" class="flex h-48 items-center justify-center rounded-md border border-destructive/30 bg-destructive/5 px-6 text-center text-sm text-destructive">+ {{ error }}+ </div>+ <template v-else>+ <div class="flex items-center gap-2">+ <Button type="button" variant="outline" size="sm" :disabled="exporting || eligibleCandidates.length === 0" @click="selectAll">+ {{ t("driverStore.offlineExportSelectAll") }}+ </Button>+ <Button type="button" variant="outline" size="sm" :disabled="exporting || selectedCount === 0" @click="clearSelection">+ {{ t("driverStore.offlineExportClear") }}+ </Button>+ </div>++ <ScrollArea class="h-72 rounded-md border">+ <div v-if="candidates.length === 0" class="px-4 py-12 text-center text-sm text-muted-foreground">+ {{ t("driverStore.offlineExportNoDrivers") }}+ </div>+ <label v-for="candidate in candidates" :key="candidate.dbType" class="flex items-start gap-3 border-b px-3 py-2.5 last:border-b-0" :class="candidate.eligible ? 'cursor-pointer hover:bg-muted/50' : 'cursor-not-allowed bg-muted/20 opacity-70'">+ <input+ type="checkbox"+ class="mt-1 h-3.5 w-3.5 shrink-0 accent-primary"+ :checked="isSelected(candidate.dbType)"+ :disabled="!candidate.eligible || exporting"+ :aria-label="candidate.label"+ :aria-describedby="!candidate.eligible ? `offline-export-reason-${candidate.dbType}` : undefined"+ @change="toggle(candidate.dbType, ($event.target as HTMLInputElement).checked)"+ />+ <DatabaseIcon :db-type="candidate.dbType" class="mt-0.5 h-4 w-4 shrink-0" />+ <span class="min-w-0 flex-1">+ <span class="flex min-w-0 flex-wrap items-center gap-1.5">+ <span class="truncate text-sm font-medium">{{ candidate.label }}</span>+ <Badge variant="outline" class="h-5 rounded-full px-2 text-[10px]">v{{ candidate.version }}</Badge>+ <Badge v-if="candidate.artifactKind" variant="secondary" class="h-5 rounded-full px-2 text-[10px]">{{ artifactLabel(candidate) }}</Badge>+ <Badge v-if="candidate.requiredJre" variant="secondary" class="h-5 rounded-full px-2 text-[10px]">JRE {{ candidate.requiredJre }}</Badge>+ <span v-if="candidate.size" class="text-[11px] text-muted-foreground">{{ formatSize(candidate.size) }}</span>+ </span>+ <span v-if="!candidate.eligible" :id="`offline-export-reason-${candidate.dbType}`" class="mt-0.5 block text-xs text-muted-foreground">+ {{ unavailableReason(candidate.unavailableReason) }}+ </span>+ </span>+ </label>+ </ScrollArea>++ <div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ {{ t("driverStore.offlineExportJreSummary", { count: selectedJres.size }) }}+ </div>++ <div class="flex items-start gap-2 rounded-md border border-green-500/20 bg-green-500/5 px-3 py-2 text-xs text-muted-foreground">+ <ShieldCheck class="mt-0.5 h-4 w-4 shrink-0 text-green-600" />+ <span>{{ t("driverStore.offlineExportSecurityHint") }}</span>+ </div>+ </template>+ </div>++ <DialogFooter>+ <Button type="button" variant="outline" :disabled="exporting" @click="dialogOpen = false">+ {{ t("common.cancel") }}+ </Button>+ <Button type="button" :disabled="!canConfirm" @click="confirm">+ <Loader2 v-if="exporting" class="mr-1.5 h-4 w-4 animate-spin" />+ {{ exporting ? t("driverStore.offlineExporting") : t("driverStore.offlineExportStart", { count: selectedCount }) }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/config/DriverStoreDialog.vue b/apps/desktop/src/components/config/DriverStoreDialog.vueindex ff23745f35..47f9133899 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, X } from "@lucide/vue";+import { Activity, ExternalLink, Cpu, FolderOpen, FolderSync, MemoryStick, Search, Square, Trash2, Download, RotateCcw, Loader2, RefreshCw, Check, Clock3, FileArchive, FileUp, X } from "@lucide/vue";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -10,6 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import DriverInstallProgressCircle from "@/components/config/DriverInstallProgressCircle.vue";+import AgentOfflineExportDialog from "@/components/config/AgentOfflineExportDialog.vue";import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";import { useToast } from "@/composables/useToast";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";@@ -17,7 +18,7 @@ import { uuid } from "@/lib/common/utils";import { countAvailableDriverUpdates } from "@/lib/connection/agentDriverUpdateBadge";import type { JdbcDriverInfo, JdbcLocalBundleInfo, JdbcMavenBundleInfo, JdbcPluginStatus } from "@/types/database";import * as api from "@/lib/backend/api";-import type { AgentDriverInfo, DriverRuntimeInfo, DriverRuntimeSummary, DriverStoreUsage, JavaRuntimeConfig } from "@/lib/backend/api";+import type { AgentDriverInfo, AgentOfflineExportPreview, DriverRuntimeInfo, DriverRuntimeSummary, DriverStoreUsage, JavaRuntimeConfig } from "@/lib/backend/api";import { formatRuntimeBytes, formatRuntimeCpu, formatRuntimeUptime, runtimeHealthClass, runtimeStatusClass, runtimeStatusDotClass } from "@/lib/connection/driverRuntimePresentation";import {addDriverInstallQueue,@@ -36,6 +37,7 @@ import { installRegisteredManagedJdbcDriver, isManagedJdbcDriver, managedJdbcDriimport type { DriverStoreFocus } from "@/lib/connection/agentDriverInstallHint";import { isOfflineDriverPackage, webDriverImportAccept } from "@/lib/driverStore/driverImportSelection";import { translateBackendError } from "@/i18n/backend-errors";+import { runAgentOfflineExportAction } from "@/lib/driverStore/agentOfflineExportFlow";import { DRIVER_CATEGORIES, getCategoryForAgentDriver, assertAgentDriverCategoriesComplete } from "@/lib/connection/driver-category-definitions";import { selectUpdatableDrivers, selectStableDrivers, hasAnyUpdatableDriverMatching } from "@/lib/connection/driverListFilter";@@ -205,6 +207,13 @@ const customJavaPath = ref("");const savingJavaRuntime = ref(false);const driverStoreUsage = ref<DriverStoreUsage | null>(null);const clearingDownloadCache = ref(false);+const offlineExportDialogOpen = ref(false);+const offlineExportPreview = ref<AgentOfflineExportPreview | null>(null);+const offlineExportLoading = ref(false);+const offlineExporting = ref(false);+const offlineExportError = ref("");+const uninstallingDriver = ref<string | null>(null);+const uninstallingJre = ref<string | null>(null);const runtimeSummary = ref<DriverRuntimeSummary | null>(null);const runtimeLoading = ref(false);const runtimeError = ref("");@@ -468,6 +477,7 @@ async function chooseCustomJavaPath() {}async function installDriver(dbType: string) {+ if (agentPackageBusy.value) return;if (installing.value !== null || preparingUpgradeAll.value || upgradingAll.value) {queueDriverInstall(dbType);return;@@ -519,7 +529,7 @@ async function runDriverInstall(dbType: string) {}async function runQueuedDriverInstalls() {- if (installing.value !== null || preparingUpgradeAll.value || upgradingAll.value) return;+ if (agentPackageBusy.value || installing.value !== null || preparingUpgradeAll.value || upgradingAll.value) return;const result = takeNextDriverInstallQueue(queuedDriverInstalls.value, canInstallOrUpdateDriver);queuedDriverInstalls.value = result.queue;@@ -530,7 +540,7 @@ async function runQueuedDriverInstalls() {}async function upgradeAll() {- if (preparingUpgradeAll.value || upgradingAll.value) return;+ if (agentPackageBusy.value || preparingUpgradeAll.value || upgradingAll.value) return;preparingUpgradeAll.value = true;try {const updatableDbTypes = drivers.value.filter((driver) => driver.update_available).map((driver) => driver.db_type);@@ -595,7 +605,9 @@ async function cancelUpgradeAll() {}async function uninstallDriver(dbType: string) {+ if (agentPackageBusy.value) return;const label = driverLabel(dbType);+ uninstallingDriver.value = dbType;try {const managedResult = await uninstallRegisteredManagedJdbcDriver(dbType, jdbcMavenBundles.value, api);if (managedResult) {@@ -615,12 +627,65 @@ async function uninstallDriver(dbType: string) {toast(t("driverStore.driverUninstallSuccess", { label }));} catch (e: any) {toast(t("driverStore.driverUninstallFailed", { label, error: backendError(e) }));+ } finally {+ uninstallingDriver.value = null;}}const importingZip = ref(false);const importingDriver = ref<string | null>(null);const agentImportBusy = computed(() => importingZip.value || importingDriver.value !== null);+const agentPackageBusy = computed(() => agentImportBusy.value || offlineExportLoading.value || offlineExporting.value || uninstallingDriver.value !== null || uninstallingJre.value !== null);+const agentExportImportBlocked = computed(() => agentPackageBusy.value || installing.value !== null || preparingUpgradeAll.value || upgradingAll.value || reinstallingJre.value !== null || queuedDriverInstalls.value.length > 0);++async function openOfflineExportDialog() {+ if (isWeb || agentExportImportBlocked.value) return;+ offlineExportDialogOpen.value = true;+ offlineExportLoading.value = true;+ offlineExportPreview.value = null;+ offlineExportError.value = "";+ try {+ offlineExportPreview.value = await api.previewAgentOfflineExport();+ } catch (error) {+ offlineExportError.value = t("driverStore.offlineExportPreviewFailed", { error: backendError(error) });+ } finally {+ offlineExportLoading.value = false;+ }+}++async function exportOfflinePackage(driverKeys: string[]) {+ if (isWeb || agentExportImportBlocked.value || driverKeys.length === 0) return;+ const platform = offlineExportPreview.value?.platform ?? "current-platform";+ await runAgentOfflineExportAction({+ driverKeys,+ setBusy: (busy) => {+ offlineExporting.value = busy;+ },+ chooseDestination: async () => {+ const { save } = await import("@tauri-apps/plugin-dialog");+ return save({+ title: t("driverStore.offlineExportChooseDestination"),+ defaultPath: `dbx-agents-offline-${platform}.zip`,+ filters: [{ name: "ZIP", extensions: ["zip"] }],+ });+ },+ exportPackage: api.exportAgentsOffline,+ onSuccess: ({ destination, result }) => {+ offlineExportDialogOpen.value = false;+ toast(+ t("driverStore.offlineExportSuccess", {+ drivers: result.driverCount,+ jres: result.jreCount,+ size: formatBytes(result.bytes),+ file: destination.split(/[/\\]/).pop() || destination,+ }),+ );+ },+ onError: (error) => {+ toast(t("driverStore.offlineExportFailed", { error: backendError(error) }), 8000);+ },+ });+}function chooseWebOfflineZip(): Promise<File | null> {return new Promise((resolve) => {@@ -661,7 +726,7 @@ function chooseWebFile(accept: string): Promise<File | null> {}async function importOfflineZip() {- if (agentImportBusy.value) return;+ if (agentExportImportBlocked.value) return;let selected: string | File | null = null;if (isWeb) {selected = await chooseWebOfflineZip();@@ -692,7 +757,7 @@ async function importOfflineZip() {}async function importDriverFile(driver: AgentDriverInfo) {- if (agentImportBusy.value) return;+ if (agentPackageBusy.value) return;const dbType = driver.db_type;if (isManagedJdbcBuiltinDriver(dbType)) {await importJdbcDrivers();@@ -753,6 +818,7 @@ async function importDriverFile(driver: AgentDriverInfo) {}async function reinstallJre(jreKey: string) {+ if (agentPackageBusy.value) return;reinstallingJre.value = jreKey;activeAgentOperationId.value = uuid();resetAgentInstallProgress();@@ -770,12 +836,16 @@ async function reinstallJre(jreKey: string) {}async function uninstallJre(jreKey: string) {+ if (agentPackageBusy.value) return;+ uninstallingJre.value = jreKey;try {await api.uninstallJre(jreKey);await refreshAgents();toast(t("driverStore.jreUninstallSuccess", { jre: jreKey }));} catch (e: any) {toast(String(e));+ } finally {+ uninstallingJre.value = null;}}@@ -1400,7 +1470,12 @@ watch(driverStoreTab, (tab) => {</SelectContent></Select></div>- <Button v-if="driverStoreTab === 'agent'" variant="ghost" size="sm" class="h-7 rounded-md text-xs gap-1 text-muted-foreground" :disabled="agentImportBusy || installing !== null || upgradingAll || reinstallingJre !== null || queuedDriverInstalls.length > 0" @click="importOfflineZip">+ <Button v-if="driverStoreTab === 'agent' && !isWeb" data-testid="agent-offline-export-button" variant="ghost" size="sm" class="h-7 rounded-md text-xs gap-1 text-muted-foreground" :disabled="agentExportImportBlocked" @click="openOfflineExportDialog">+ <Loader2 v-if="offlineExportLoading || offlineExporting" class="h-3.5 w-3.5 animate-spin" />+ <FileArchive v-else class="h-3.5 w-3.5" />+ {{ offlineExporting ? t("driverStore.offlineExporting") : t("driverStore.offlineExport") }}+ </Button>+ <Button v-if="driverStoreTab === 'agent'" data-testid="agent-offline-import-button" variant="ghost" size="sm" class="h-7 rounded-md text-xs gap-1 text-muted-foreground" :disabled="agentExportImportBlocked" @click="importOfflineZip"><Loader2 v-if="agentImportBusy" class="h-3.5 w-3.5 animate-spin" /><FileUp v-else class="h-3.5 w-3.5" />{{ agentImportBusy ? t("driverStore.importing") : t("driverStore.importOfflinePackage") }}@@ -1453,15 +1528,15 @@ watch(driverStoreTab, (tab) => {<Check v-if="jre.installed" class="h-4 w-4 text-green-600" /><span v-else class="text-xs text-muted-foreground">{{ t("driverStore.notInstalled") }}</span><DriverInstallProgressCircle v-if="reinstallingJre === jre.key" :percent="getJreReinstallPercent()" :title="getJreReinstallTitle(jre.installed ? t('driverStore.reinstalling') : t('driverStore.installing'))" />- <Button v-else-if="!jre.installed" type="button" variant="default" size="sm" class="h-8 rounded-md text-xs" :disabled="reinstallingJre !== null || installing !== null || agentImportBusy" @click="reinstallJre(jre.key)">+ <Button v-else-if="!jre.installed" type="button" variant="default" size="sm" class="h-8 rounded-md text-xs" :disabled="reinstallingJre !== null || installing !== null || agentPackageBusy" @click="reinstallJre(jre.key)"><Download class="h-3.5 w-3.5 mr-1" />{{ t("driverStore.install") }}</Button>- <Button v-else-if="jre.installed" type="button" variant="outline" size="sm" class="h-8 rounded-md text-xs" :disabled="reinstallingJre !== null || installing !== null || agentImportBusy" @click="reinstallJre(jre.key)">+ <Button v-else-if="jre.installed" type="button" variant="outline" size="sm" class="h-8 rounded-md text-xs" :disabled="reinstallingJre !== null || installing !== null || agentPackageBusy" @click="reinstallJre(jre.key)"><RotateCcw class="h-3.5 w-3.5 mr-1" />{{ t("driverStore.reinstall") }}</Button>- <Button v-if="jre.installed" type="button" variant="ghost" size="sm" class="h-8 rounded-md text-xs text-muted-foreground hover:text-destructive" :disabled="reinstallingJre !== null || installing !== null || agentImportBusy" @click="uninstallJre(jre.key)">+ <Button v-if="jre.installed" type="button" variant="ghost" size="sm" class="h-8 rounded-md text-xs text-muted-foreground hover:text-destructive" :disabled="reinstallingJre !== null || installing !== null || agentPackageBusy" @click="uninstallJre(jre.key)">{{ t("driverStore.uninstall") }}</Button></div>@@ -1482,7 +1557,7 @@ watch(driverStoreTab, (tab) => {<p class="text-xs text-muted-foreground">{{ t("driverStore.updatesAvailableDescription") }}</p></div><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">+ <Button size="sm" class="h-7 rounded-md text-xs shrink-0 ml-3" :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentPackageBusy" @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") }}@@ -1518,7 +1593,7 @@ 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="preparingUpgradeAll || upgradingAll || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy"@click="removeQueuedDriverInstall(driver.db_type)"><Clock3 class="h-3 w-3 mr-1" />@@ -1535,7 +1610,7 @@ watch(driverStoreTab, (tab) => {@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)">+ <Button v-else-if="!driver.installed && !isDriverProgressActive(driver.db_type)" size="sm" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy" @click="installDriver(driver.db_type)"><Download class="h-3 w-3 mr-1" />{{ t("driverStore.install") }}</Button>@@ -1545,7 +1620,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="preparingUpgradeAll || upgradingAll || installing !== null || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || installing !== null || agentPackageBusy"@click="importDriverFile(driver)"><Loader2 v-if="importingDriver === driver.db_type" class="h-3.5 w-3.5 animate-spin" />@@ -1557,7 +1632,7 @@ 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="preparingUpgradeAll || upgradingAll || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy"@click="removeQueuedDriverInstall(driver.db_type)"><Clock3 class="h-3 w-3 mr-1" />@@ -1574,7 +1649,7 @@ watch(driverStoreTab, (tab) => {@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)">+ <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 || agentPackageBusy" @click="installDriver(driver.db_type)">{{ t("driverStore.update") }}</Button><Button@@ -1582,7 +1657,7 @@ watch(driverStoreTab, (tab) => {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)"+ :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentPackageBusy || isDriverQueued(driver.db_type)"@click="uninstallDriver(driver.db_type)">{{ t("driverStore.uninstall") }}@@ -1663,7 +1738,7 @@ 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="preparingUpgradeAll || upgradingAll || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy"@click="removeQueuedDriverInstall(driver.db_type)"><Clock3 class="h-3 w-3 mr-1" />@@ -1680,7 +1755,7 @@ watch(driverStoreTab, (tab) => {@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)">+ <Button v-else-if="!driver.installed && !isDriverProgressActive(driver.db_type)" size="sm" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy" @click="installDriver(driver.db_type)"><Download class="h-3 w-3 mr-1" />{{ t("driverStore.install") }}</Button>@@ -1690,7 +1765,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="preparingUpgradeAll || upgradingAll || installing !== null || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || installing !== null || agentPackageBusy"@click="importDriverFile(driver)"><Loader2 v-if="importingDriver === driver.db_type" class="h-3.5 w-3.5 animate-spin" />@@ -1702,7 +1777,7 @@ 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="preparingUpgradeAll || upgradingAll || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy"@click="removeQueuedDriverInstall(driver.db_type)"><Clock3 class="h-3 w-3 mr-1" />@@ -1719,7 +1794,7 @@ watch(driverStoreTab, (tab) => {@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)">+ <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 || agentPackageBusy" @click="installDriver(driver.db_type)">{{ t("driverStore.update") }}</Button><Button@@ -1727,7 +1802,7 @@ watch(driverStoreTab, (tab) => {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)"+ :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentPackageBusy || isDriverQueued(driver.db_type)"@click="uninstallDriver(driver.db_type)">{{ t("driverStore.uninstall") }}@@ -1767,7 +1842,7 @@ 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="preparingUpgradeAll || upgradingAll || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy"@click="removeQueuedDriverInstall(driver.db_type)"><Clock3 class="h-3 w-3 mr-1" />@@ -1784,7 +1859,7 @@ watch(driverStoreTab, (tab) => {@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)">+ <Button v-else-if="!driver.installed && !isDriverProgressActive(driver.db_type)" size="sm" class="h-7 rounded-md text-xs" :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy" @click="installDriver(driver.db_type)"><Download class="h-3 w-3 mr-1" />{{ t("driverStore.install") }}</Button>@@ -1794,7 +1869,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="preparingUpgradeAll || upgradingAll || installing !== null || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || installing !== null || agentPackageBusy"@click="importDriverFile(driver)"><Loader2 v-if="importingDriver === driver.db_type" class="h-3.5 w-3.5 animate-spin" />@@ -1806,7 +1881,7 @@ 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="preparingUpgradeAll || upgradingAll || agentImportBusy"+ :disabled="preparingUpgradeAll || upgradingAll || agentPackageBusy"@click="removeQueuedDriverInstall(driver.db_type)"><Clock3 class="h-3 w-3 mr-1" />@@ -1823,7 +1898,7 @@ watch(driverStoreTab, (tab) => {@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)">+ <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 || agentPackageBusy" @click="installDriver(driver.db_type)">{{ t("driverStore.update") }}</Button><Button@@ -1831,7 +1906,7 @@ watch(driverStoreTab, (tab) => {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)"+ :disabled="installing !== null || preparingUpgradeAll || upgradingAll || agentPackageBusy || isDriverQueued(driver.db_type)"@click="uninstallDriver(driver.db_type)">{{ t("driverStore.uninstall") }}@@ -2150,6 +2225,7 @@ watch(driverStoreTab, (tab) => {</div></div></div>+ <AgentOfflineExportDialog v-model:open="offlineExportDialogOpen" :preview="offlineExportPreview" :loading="offlineExportLoading" :exporting="offlineExporting" :error="offlineExportError" @confirm="exportOfflinePackage" /></template><style>diff --git a/apps/desktop/src/components/config/__tests__/AgentOfflineExportDialog.spec.ts b/apps/desktop/src/components/config/__tests__/AgentOfflineExportDialog.spec.tsnew file mode 100644index 0000000000..b72aaa0338--- /dev/null+++ b/apps/desktop/src/components/config/__tests__/AgentOfflineExportDialog.spec.ts@@ -0,0 +1,183 @@+// @vitest-environment happy-dom++import { createApp, defineComponent, h, nextTick, type App } from "vue";+import { afterEach, describe, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import type { AgentOfflineExportPreview } from "@/lib/backend/api";++vi.mock("@/components/ui/dialog", async () => {+ const { defineComponent, h } = await import("vue");+ const passthrough = defineComponent({+ setup(_props, { slots }) {+ return () => h("div", slots.default?.());+ },+ });+ return { Dialog: passthrough, DialogContent: passthrough, DialogHeader: passthrough, DialogTitle: passthrough, DialogFooter: passthrough };+});++vi.mock("@/components/ui/button", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ Button: defineComponent({+ props: { disabled: Boolean },+ setup(props, { slots, emit }) {+ return () => h("button", { disabled: props.disabled, onClick: () => emit("click") }, slots.default?.());+ },+ }),+ };+});++vi.mock("@/components/ui/badge", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ Badge: defineComponent({+ setup(_props, { slots }) {+ return () => h("span", slots.default?.());+ },+ }),+ };+});++vi.mock("@/components/ui/scroll-area", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ ScrollArea: defineComponent({+ setup(_props, { slots }) {+ return () => h("div", slots.default?.());+ },+ }),+ };+});++vi.mock("@/components/icons/DatabaseIcon.vue", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ default: defineComponent({+ setup() {+ return () => h("span");+ },+ }),+ };+});++import AgentOfflineExportDialog from "@/components/config/AgentOfflineExportDialog.vue";++const mountedApps: App[] = [];++const preview: AgentOfflineExportPreview = {+ platform: "macos-aarch64",+ candidates: [+ {+ dbType: "duckdb",+ label: "DuckDB",+ version: "1.2.3",+ size: 1024,+ artifactKind: "jar",+ requiredJre: "21",+ eligible: true,+ unavailableReason: null,+ },+ {+ dbType: "kafka",+ label: "Apache Kafka",+ version: "4.0.0",+ size: 2048,+ artifactKind: "jar",+ requiredJre: "21",+ eligible: false,+ unavailableReason: "localInstall",+ },+ {+ dbType: "redis",+ label: "Redis",+ version: "8.0.0",+ size: 4096,+ artifactKind: "native",+ requiredJre: null,+ eligible: true,+ unavailableReason: null,+ },+ ],+};++afterEach(() => {+ for (const app of mountedApps.splice(0)) app.unmount();+ while (document.body.firstChild) document.body.removeChild(document.body.firstChild);+});++async function mountDialog(props: Record<string, unknown>, onConfirm = vi.fn()) {+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp(+ defineComponent({+ setup() {+ return () => h(AgentOfflineExportDialog, { ...props, onConfirm });+ },+ }),+ );+ mountedApps.push(app);+ app.use(i18n);+ app.mount(container);+ await nextTick();+ return { onConfirm };+}++function buttonContaining(text: string) {+ return [...document.body.querySelectorAll("button")].find((button) => button.textContent?.includes(text));+}++describe("AgentOfflineExportDialog", () => {+ it("selects eligible drivers by default and explains excluded candidates", async () => {+ i18n.global.locale.value = "en";+ const { onConfirm } = await mountDialog({ open: true, preview });++ expect(document.body.textContent).toContain("2 of 2 selected");+ expect(document.body.textContent).toContain("1 managed JRE(s) will be included automatically.");+ expect(document.body.textContent).toContain("Locally imported Agent builds are not included.");++ const inputs = [...document.body.querySelectorAll<HTMLInputElement>("input[type='checkbox']")];+ expect(inputs).toHaveLength(3);+ expect(inputs.map((input) => input.checked)).toEqual([true, false, true]);+ expect(inputs.map((input) => input.disabled)).toEqual([false, true, false]);+ expect(inputs[1]?.getAttribute("aria-describedby")).toBe("offline-export-reason-kafka");+ expect(document.getElementById("offline-export-reason-kafka")?.textContent).toContain("Locally imported");++ buttonContaining("Export 2 driver(s)")?.click();+ expect(onConfirm).toHaveBeenCalledWith(["duckdb", "redis"]);+ });++ it("disables export after clearing the selection", async () => {+ i18n.global.locale.value = "en";+ const { onConfirm } = await mountDialog({ open: true, preview });++ buttonContaining("Clear")?.click();+ await nextTick();++ expect(document.body.textContent).toContain("0 of 2 selected");+ const confirm = buttonContaining("Export 0 driver(s)");+ expect(confirm?.disabled).toBe(true);+ confirm?.click();+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it("locks controls while an export is running", async () => {+ i18n.global.locale.value = "en";+ const { onConfirm } = await mountDialog({ open: true, preview, exporting: true });++ expect(buttonContaining("Select all")?.disabled).toBe(true);+ expect(buttonContaining("Clear")?.disabled).toBe(true);+ expect(buttonContaining("Cancel")?.disabled).toBe(true);+ expect(buttonContaining("Exporting")?.disabled).toBe(true);+ expect([...document.body.querySelectorAll<HTMLInputElement>("input[type='checkbox']")].every((input) => input.disabled)).toBe(true);+ buttonContaining("Exporting")?.click();+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it("shows the empty state when no managed drivers are available", async () => {+ i18n.global.locale.value = "en";+ await mountDialog({ open: true, preview: { platform: "linux-x64", candidates: [] } satisfies AgentOfflineExportPreview });++ expect(document.body.textContent).toContain("No eligible DBX-managed Agent drivers are installed.");+ expect(buttonContaining("Export 0 driver(s)")?.disabled).toBe(true);+ });+});diff --git a/apps/desktop/src/i18n/__tests__/agentOfflineExportParity.spec.ts b/apps/desktop/src/i18n/__tests__/agentOfflineExportParity.spec.tsnew file mode 100644index 0000000000..8a0ca1a9a7--- /dev/null+++ b/apps/desktop/src/i18n/__tests__/agentOfflineExportParity.spec.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import en from "../locales/en";+import es from "../locales/es";+import itLocale from "../locales/it";+import ja from "../locales/ja";+import ko from "../locales/ko";+import ptBR from "../locales/pt-BR";+import zhCN from "../locales/zh-CN";+import zhTW from "../locales/zh-TW";++type Messages = Record<string, unknown>;++const locales: Array<[string, Messages]> = [+ ["es", es],+ ["it", itLocale],+ ["ja", ja],+ ["ko", ko],+ ["pt-BR", ptBR],+ ["zh-CN", zhCN],+ ["zh-TW", zhTW],+];++function offlineExportEntries(locale: Messages): Map<string, string> {+ const driverStore = locale.driverStore as Record<string, unknown>;+ return new Map(+ Object.entries(driverStore)+ .filter(([key, value]) => key.startsWith("offlineExport") && typeof value === "string")+ .map(([key, value]) => [key, value as string]),+ );+}++function placeholders(message: string): string[] {+ return [...new Set([...message.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]))].sort();+}++describe("offline Agent export i18n parity", () => {+ const englishEntries = offlineExportEntries(en);++ it("declares the complete English message set", () => {+ expect(englishEntries.size).toBe(29);+ });++ it.each(locales)("%s declares matching keys and placeholders", (_name, locale) => {+ const localeEntries = offlineExportEntries(locale);+ expect([...localeEntries.keys()].sort()).toEqual([...englishEntries.keys()].sort());++ for (const [key, englishMessage] of englishEntries) {+ expect(placeholders(localeEntries.get(key) ?? ""), key).toEqual(placeholders(englishMessage));+ }+ });+});diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 91d17a068b..7c12387526 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -6696,6 +6696,35 @@ export default {jdbcDrivers: "JDBC Drivers",importing: "Importing...",importOfflinePackage: "Import offline package",+ offlineExport: "Export offline package",+ offlineExportTitle: "Export offline Agent package",+ offlineExportDescription: "Select the DBX-managed Agent drivers to include. The package is compatible with the current platform only.",+ offlineExportPlatform: "Platform",+ offlineExportSelectedCount: "{selected} of {total} selected",+ offlineExportSelectAll: "Select all",+ offlineExportClear: "Clear",+ offlineExportNoDrivers: "No eligible DBX-managed Agent drivers are installed.",+ offlineExportArtifactJar: "Java JAR",+ offlineExportArtifactNative: "Native",+ offlineExportArtifactUnknown: "Unknown",+ offlineExportPreparing: "Preparing export preview...",+ offlineExportJreSummary: "{count} managed JRE(s) will be included automatically.",+ offlineExportSecurityHint: "Only DBX-managed artifacts and required managed JREs are included. Local paths, settings, and external drivers are excluded.",+ offlineExportStart: "Export {count} driver(s)",+ offlineExporting: "Exporting...",+ offlineExportPreviewFailed: "Unable to prepare the export: {error}",+ offlineExportChooseDestination: "Save offline Agent package",+ offlineExportSuccess: "Exported {file}: {drivers} driver(s), {jres} JRE(s), {size}.",+ offlineExportFailed: "Offline package export failed: {error}",+ offlineExportUnavailable_unmanagedInstall: "This artifact is not tracked as a DBX-managed installation.",+ offlineExportUnavailable_localInstall: "Locally imported Agent builds are not included.",+ offlineExportUnavailable_launchConfig: "Custom launch configurations are machine-specific.",+ offlineExportUnavailable_missingArtifact: "The installed Agent artifact is missing.",+ offlineExportUnavailable_invalidArtifact: "The installed Agent artifact is invalid or corrupt.",+ offlineExportUnavailable_unsafeSource: "The artifact is outside the managed store or uses a symbolic link.",+ offlineExportUnavailable_externalDriverRequired: "This Agent requires a user-provided external driver.",+ offlineExportUnavailable_missingManagedJre: "The required DBX-managed JRE is not installed.",+ offlineExportUnavailable_invalidManagedJre: "The required DBX-managed JRE is invalid or unsafe.",refresh: "Refresh",javaRuntime: "Java Runtime",javaRuntimeManaged: "DBX managed JRE",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex a267d254f0..fa77333412 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -6407,6 +6407,35 @@ export default withEnglishFallback({jdbcDrivers: "Drivers JDBC",importing: "Importando...",importOfflinePackage: "Importar paquete offline",+ offlineExport: "Exportar paquete offline",+ offlineExportTitle: "Exportar paquete de Agent offline",+ offlineExportDescription: "Selecciona los drivers Agent administrados por DBX que se incluirán. El paquete solo es compatible con la plataforma actual.",+ offlineExportPlatform: "Plataforma",+ offlineExportSelectedCount: "{selected} de {total} seleccionados",+ offlineExportSelectAll: "Seleccionar todo",+ offlineExportClear: "Limpiar",+ offlineExportNoDrivers: "No hay drivers Agent administrados por DBX que se puedan exportar.",+ offlineExportArtifactJar: "JAR de Java",+ offlineExportArtifactNative: "Nativo",+ offlineExportArtifactUnknown: "Desconocido",+ offlineExportPreparing: "Preparando la vista previa...",+ offlineExportJreSummary: "Se incluirán automáticamente {count} JRE administrados.",+ offlineExportSecurityHint: "Solo se incluyen artefactos administrados por DBX y los JRE necesarios. Se excluyen rutas locales, configuraciones y drivers externos.",+ offlineExportStart: "Exportar {count} driver(s)",+ offlineExporting: "Exportando...",+ offlineExportPreviewFailed: "No se pudo preparar la exportación: {error}",+ offlineExportChooseDestination: "Guardar paquete de Agent offline",+ offlineExportSuccess: "Se exportó {file}: {drivers} driver(s), {jres} JRE, {size}.",+ offlineExportFailed: "Error al exportar el paquete offline: {error}",+ offlineExportUnavailable_unmanagedInstall: "El artefacto no está registrado como una instalación administrada por DBX.",+ offlineExportUnavailable_localInstall: "Las compilaciones Agent importadas localmente no se incluyen.",+ offlineExportUnavailable_launchConfig: "Las configuraciones de inicio personalizadas son específicas de este equipo.",+ offlineExportUnavailable_missingArtifact: "Falta el artefacto Agent instalado.",+ offlineExportUnavailable_invalidArtifact: "El artefacto Agent instalado no es válido o está dañado.",+ offlineExportUnavailable_unsafeSource: "El artefacto está fuera del almacén administrado o usa un enlace simbólico.",+ offlineExportUnavailable_externalDriverRequired: "Este Agent requiere un driver externo proporcionado por el usuario.",+ offlineExportUnavailable_missingManagedJre: "El JRE administrado por DBX requerido no está instalado.",+ offlineExportUnavailable_invalidManagedJre: "El JRE administrado por DBX requerido no es válido o no es seguro.",refresh: "Actualizar",javaRuntime: "Runtime Java",javaRuntimeManaged: "JRE administrado por DBX",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex b044b6a62b..69677f48f4 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -6407,6 +6407,35 @@ export default withEnglishFallback({jdbcDrivers: "Driver JDBC",importing: "Importazione in corso...",importOfflinePackage: "Importa pacchetto offline",+ offlineExport: "Esporta pacchetto offline",+ offlineExportTitle: "Esporta pacchetto Agent offline",+ offlineExportDescription: "Seleziona i driver Agent gestiti da DBX da includere. Il pacchetto è compatibile solo con la piattaforma corrente.",+ offlineExportPlatform: "Piattaforma",+ offlineExportSelectedCount: "{selected} di {total} selezionati",+ offlineExportSelectAll: "Seleziona tutto",+ offlineExportClear: "Deseleziona",+ offlineExportNoDrivers: "Non sono installati driver Agent gestiti da DBX idonei all'esportazione.",+ offlineExportArtifactJar: "JAR Java",+ offlineExportArtifactNative: "Nativo",+ offlineExportArtifactUnknown: "Sconosciuto",+ offlineExportPreparing: "Preparazione dell'anteprima...",+ offlineExportJreSummary: "Verranno inclusi automaticamente {count} JRE gestiti.",+ offlineExportSecurityHint: "Sono inclusi solo gli artefatti gestiti da DBX e i JRE necessari. Percorsi locali, impostazioni e driver esterni sono esclusi.",+ offlineExportStart: "Esporta {count} driver",+ offlineExporting: "Esportazione in corso...",+ offlineExportPreviewFailed: "Impossibile preparare l'esportazione: {error}",+ offlineExportChooseDestination: "Salva pacchetto Agent offline",+ offlineExportSuccess: "Esportato {file}: {drivers} driver, {jres} JRE, {size}.",+ offlineExportFailed: "Esportazione del pacchetto offline non riuscita: {error}",+ offlineExportUnavailable_unmanagedInstall: "L'artefatto non è registrato come installazione gestita da DBX.",+ offlineExportUnavailable_localInstall: "Le build Agent importate localmente non sono incluse.",+ offlineExportUnavailable_launchConfig: "Le configurazioni di avvio personalizzate sono specifiche del computer.",+ offlineExportUnavailable_missingArtifact: "L'artefatto Agent installato è mancante.",+ offlineExportUnavailable_invalidArtifact: "L'artefatto Agent installato non è valido o è danneggiato.",+ offlineExportUnavailable_unsafeSource: "L'artefatto è fuori dall'archivio gestito o usa un collegamento simbolico.",+ offlineExportUnavailable_externalDriverRequired: "Questo Agent richiede un driver esterno fornito dall'utente.",+ offlineExportUnavailable_missingManagedJre: "Il JRE gestito da DBX richiesto non è installato.",+ offlineExportUnavailable_invalidManagedJre: "Il JRE gestito da DBX richiesto non è valido o sicuro.",refresh: "Aggiorna",javaRuntime: "Java Runtime",javaRuntimeManaged: "JRE gestito da DBX",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 3cc1274e50..06be0fdffd 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -6460,6 +6460,35 @@ export default withEnglishFallback({jdbcDrivers: "JDBCドライバー",importing: "インポート中...",importOfflinePackage: "オフラインパッケージをインポート",+ offlineExport: "オフラインパッケージをエクスポート",+ offlineExportTitle: "Agentオフラインパッケージをエクスポート",+ offlineExportDescription: "含めるDBX管理のAgentドライバーを選択します。パッケージは現在のプラットフォームでのみ使用できます。",+ offlineExportPlatform: "対応プラットフォーム",+ offlineExportSelectedCount: "{total}件中{selected}件を選択",+ offlineExportSelectAll: "すべて選択",+ offlineExportClear: "選択を解除",+ offlineExportNoDrivers: "エクスポート可能なDBX管理のAgentドライバーがインストールされていません。",+ offlineExportArtifactJar: "Java JAR",+ offlineExportArtifactNative: "ネイティブ",+ offlineExportArtifactUnknown: "不明",+ offlineExportPreparing: "エクスポート内容を準備中...",+ offlineExportJreSummary: "必要な管理対象JREを{count}件、自動的に含めます。",+ offlineExportSecurityHint: "DBX管理の成果物と必要なJREのみを含めます。ローカルパス、設定、外部ドライバーは除外されます。",+ offlineExportStart: "{count}件のドライバーをエクスポート",+ offlineExporting: "エクスポート中...",+ offlineExportPreviewFailed: "エクスポートを準備できませんでした: {error}",+ offlineExportChooseDestination: "Agentオフラインパッケージを保存",+ offlineExportSuccess: "{file} をエクスポートしました: ドライバー{drivers}件、JRE {jres}件、{size}。",+ offlineExportFailed: "オフラインパッケージのエクスポートに失敗しました: {error}",+ offlineExportUnavailable_unmanagedInstall: "この成果物はDBX管理のインストールとして記録されていません。",+ offlineExportUnavailable_localInstall: "ローカルでインポートしたAgentビルドは含まれません。",+ offlineExportUnavailable_launchConfig: "カスタム起動設定はこのマシン固有です。",+ offlineExportUnavailable_missingArtifact: "インストール済みのAgent成果物が見つかりません。",+ offlineExportUnavailable_invalidArtifact: "インストール済みのAgent成果物が無効または破損しています。",+ offlineExportUnavailable_unsafeSource: "成果物が管理対象ストア外にあるか、シンボリックリンクを使用しています。",+ offlineExportUnavailable_externalDriverRequired: "このAgentにはユーザー提供の外部ドライバーが必要です。",+ offlineExportUnavailable_missingManagedJre: "必要なDBX管理JREがインストールされていません。",+ offlineExportUnavailable_invalidManagedJre: "必要なDBX管理JREが無効または安全ではありません。",refresh: "更新",javaRuntime: "Javaランタイム",javaRuntimeManaged: "DBX管理JRE",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex f7bfffedf9..67ba423bda 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -6099,6 +6099,35 @@ export default withEnglishFallback({jdbcDrivers: "JDBC 드라이버",importing: "가져오는 중...",importOfflinePackage: "오프라인 패키지 가져오기",+ offlineExport: "오프라인 패키지 내보내기",+ offlineExportTitle: "Agent 오프라인 패키지 내보내기",+ offlineExportDescription: "포함할 DBX 관리 Agent 드라이버를 선택하세요. 패키지는 현재 플랫폼에서만 사용할 수 있습니다.",+ offlineExportPlatform: "대상 플랫폼",+ offlineExportSelectedCount: "{total}개 중 {selected}개 선택",+ offlineExportSelectAll: "모두 선택",+ offlineExportClear: "선택 해제",+ offlineExportNoDrivers: "내보낼 수 있는 DBX 관리 Agent 드라이버가 설치되어 있지 않습니다.",+ offlineExportArtifactJar: "Java JAR",+ offlineExportArtifactNative: "네이티브",+ offlineExportArtifactUnknown: "알 수 없음",+ offlineExportPreparing: "내보내기 미리보기를 준비하는 중...",+ offlineExportJreSummary: "필요한 관리 JRE {count}개가 자동으로 포함됩니다.",+ offlineExportSecurityHint: "DBX 관리 아티팩트와 필요한 JRE만 포함됩니다. 로컬 경로, 설정 및 외부 드라이버는 제외됩니다.",+ offlineExportStart: "드라이버 {count}개 내보내기",+ offlineExporting: "내보내는 중...",+ offlineExportPreviewFailed: "내보내기를 준비할 수 없습니다: {error}",+ offlineExportChooseDestination: "Agent 오프라인 패키지 저장",+ offlineExportSuccess: "{file} 내보내기 완료: 드라이버 {drivers}개, JRE {jres}개, {size}.",+ offlineExportFailed: "오프라인 패키지 내보내기 실패: {error}",+ offlineExportUnavailable_unmanagedInstall: "이 아티팩트는 DBX 관리 설치로 기록되어 있지 않습니다.",+ offlineExportUnavailable_localInstall: "로컬에서 가져온 Agent 빌드는 포함되지 않습니다.",+ offlineExportUnavailable_launchConfig: "사용자 지정 실행 설정은 이 컴퓨터에만 적용됩니다.",+ offlineExportUnavailable_missingArtifact: "설치된 Agent 아티팩트가 없습니다.",+ offlineExportUnavailable_invalidArtifact: "설치된 Agent 아티팩트가 유효하지 않거나 손상되었습니다.",+ offlineExportUnavailable_unsafeSource: "아티팩트가 관리 저장소 밖에 있거나 심볼릭 링크를 사용합니다.",+ offlineExportUnavailable_externalDriverRequired: "이 Agent에는 사용자가 제공하는 외부 드라이버가 필요합니다.",+ offlineExportUnavailable_missingManagedJre: "필요한 DBX 관리 JRE가 설치되어 있지 않습니다.",+ offlineExportUnavailable_invalidManagedJre: "필요한 DBX 관리 JRE가 유효하지 않거나 안전하지 않습니다.",refresh: "새로고침",javaRuntime: "Java 런타임",javaRuntimeManaged: "DBX 관리 JRE",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex beab55fa8a..1716d3da35 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -6409,6 +6409,35 @@ export default withEnglishFallback({jdbcDrivers: "Drivers JDBC",importing: "Importando...",importOfflinePackage: "Importar pacote offline",+ offlineExport: "Exportar pacote offline",+ offlineExportTitle: "Exportar pacote offline do Agent",+ offlineExportDescription: "Selecione os drivers Agent gerenciados pelo DBX que serão incluídos. O pacote é compatível apenas com a plataforma atual.",+ offlineExportPlatform: "Plataforma",+ offlineExportSelectedCount: "{selected} de {total} selecionados",+ offlineExportSelectAll: "Selecionar tudo",+ offlineExportClear: "Limpar",+ offlineExportNoDrivers: "Nenhum driver Agent gerenciado pelo DBX elegível está instalado.",+ offlineExportArtifactJar: "JAR Java",+ offlineExportArtifactNative: "Nativo",+ offlineExportArtifactUnknown: "Desconhecido",+ offlineExportPreparing: "Preparando a visualização...",+ offlineExportJreSummary: "{count} JRE gerenciada(s) serão incluídas automaticamente.",+ offlineExportSecurityHint: "Somente artefatos gerenciados pelo DBX e as JRE necessárias são incluídos. Caminhos locais, configurações e drivers externos são excluídos.",+ offlineExportStart: "Exportar {count} driver(s)",+ offlineExporting: "Exportando...",+ offlineExportPreviewFailed: "Não foi possível preparar a exportação: {error}",+ offlineExportChooseDestination: "Salvar pacote offline do Agent",+ offlineExportSuccess: "{file} exportado: {drivers} driver(s), {jres} JRE, {size}.",+ offlineExportFailed: "Falha ao exportar o pacote offline: {error}",+ offlineExportUnavailable_unmanagedInstall: "O artefato não está registrado como uma instalação gerenciada pelo DBX.",+ offlineExportUnavailable_localInstall: "Builds Agent importadas localmente não são incluídas.",+ offlineExportUnavailable_launchConfig: "Configurações de inicialização personalizadas são específicas desta máquina.",+ offlineExportUnavailable_missingArtifact: "O artefato Agent instalado está ausente.",+ offlineExportUnavailable_invalidArtifact: "O artefato Agent instalado é inválido ou está corrompido.",+ offlineExportUnavailable_unsafeSource: "O artefato está fora do armazenamento gerenciado ou usa um link simbólico.",+ offlineExportUnavailable_externalDriverRequired: "Este Agent exige um driver externo fornecido pelo usuário.",+ offlineExportUnavailable_missingManagedJre: "A JRE gerenciada pelo DBX necessária não está instalada.",+ offlineExportUnavailable_invalidManagedJre: "A JRE gerenciada pelo DBX necessária é inválida ou insegura.",refresh: "Atualizar",javaRuntime: "Runtime do Java",javaRuntimeManaged: "JRE gerenciada pelo DBX",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 5b4f535dfa..0f95a3ba8e 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -6681,6 +6681,35 @@ export default withEnglishFallback({jdbcDrivers: "JDBC 驱动",importing: "导入中...",importOfflinePackage: "导入离线包",+ offlineExport: "导出离线包",+ offlineExportTitle: "导出 Agent 离线包",+ offlineExportDescription: "选择要包含的 DBX 托管 Agent 驱动。离线包仅适用于当前平台。",+ offlineExportPlatform: "适用平台",+ offlineExportSelectedCount: "已选择 {selected}/{total}",+ offlineExportSelectAll: "全选",+ offlineExportClear: "清空",+ offlineExportNoDrivers: "当前没有可导出的 DBX 托管 Agent 驱动。",+ offlineExportArtifactJar: "Java JAR",+ offlineExportArtifactNative: "原生程序",+ offlineExportArtifactUnknown: "未知",+ offlineExportPreparing: "正在准备导出预览...",+ offlineExportJreSummary: "将自动包含 {count} 个所需的托管 JRE。",+ offlineExportSecurityHint: "仅包含 DBX 托管的驱动产物及所需 JRE;本地路径、配置和外部驱动不会被导出。",+ offlineExportStart: "导出 {count} 个驱动",+ offlineExporting: "导出中...",+ offlineExportPreviewFailed: "无法准备导出:{error}",+ offlineExportChooseDestination: "保存 Agent 离线包",+ offlineExportSuccess: "已导出 {file}:{drivers} 个驱动、{jres} 个 JRE,共 {size}。",+ offlineExportFailed: "离线包导出失败:{error}",+ offlineExportUnavailable_unmanagedInstall: "该产物未被记录为 DBX 托管安装。",+ offlineExportUnavailable_localInstall: "本地导入的 Agent 构建不会被打包。",+ offlineExportUnavailable_launchConfig: "自定义启动配置仅适用于当前机器。",+ offlineExportUnavailable_missingArtifact: "已安装的 Agent 产物不存在。",+ offlineExportUnavailable_invalidArtifact: "已安装的 Agent 产物无效或已损坏。",+ offlineExportUnavailable_unsafeSource: "产物不在托管目录内,或使用了符号链接。",+ offlineExportUnavailable_externalDriverRequired: "该 Agent 依赖用户自行提供的外部驱动。",+ offlineExportUnavailable_missingManagedJre: "尚未安装所需的 DBX 托管 JRE。",+ offlineExportUnavailable_invalidManagedJre: "所需的 DBX 托管 JRE 无效或不安全。",refresh: "刷新",javaRuntime: "Java 运行时",javaRuntimeManaged: "DBX 托管 JRE",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 698935ab41..a932bf1c67 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -5717,6 +5717,35 @@ export default withEnglishFallback({jdbcDrivers: "JDBC 驅動程式",importing: "匯入中……",importOfflinePackage: "匯入離線包",+ offlineExport: "匯出離線包",+ offlineExportTitle: "匯出 Agent 離線包",+ offlineExportDescription: "選擇要包含的 DBX 託管 Agent 驅動程式。離線包僅適用於目前平台。",+ offlineExportPlatform: "適用平台",+ offlineExportSelectedCount: "已選擇 {selected}/{total}",+ offlineExportSelectAll: "全選",+ offlineExportClear: "清除",+ offlineExportNoDrivers: "目前沒有可匯出的 DBX 託管 Agent 驅動程式。",+ offlineExportArtifactJar: "Java JAR",+ offlineExportArtifactNative: "原生程式",+ offlineExportArtifactUnknown: "未知",+ offlineExportPreparing: "正在準備匯出預覽……",+ offlineExportJreSummary: "將自動包含 {count} 個所需的託管 JRE。",+ offlineExportSecurityHint: "僅包含 DBX 託管的驅動程式產物及所需 JRE;本機路徑、設定和外部驅動程式不會被匯出。",+ offlineExportStart: "匯出 {count} 個驅動程式",+ offlineExporting: "匯出中……",+ offlineExportPreviewFailed: "無法準備匯出:{error}",+ offlineExportChooseDestination: "儲存 Agent 離線包",+ offlineExportSuccess: "已匯出 {file}:{drivers} 個驅動程式、{jres} 個 JRE,共 {size}。",+ offlineExportFailed: "離線包匯出失敗:{error}",+ offlineExportUnavailable_unmanagedInstall: "此產物未被記錄為 DBX 託管安裝。",+ offlineExportUnavailable_localInstall: "本機匯入的 Agent 建置不會被打包。",+ offlineExportUnavailable_launchConfig: "自訂啟動設定僅適用於目前機器。",+ offlineExportUnavailable_missingArtifact: "已安裝的 Agent 產物不存在。",+ offlineExportUnavailable_invalidArtifact: "已安裝的 Agent 產物無效或已損毀。",+ offlineExportUnavailable_unsafeSource: "產物不在託管目錄內,或使用了符號連結。",+ offlineExportUnavailable_externalDriverRequired: "此 Agent 依賴使用者自行提供的外部驅動程式。",+ offlineExportUnavailable_missingManagedJre: "尚未安裝所需的 DBX 託管 JRE。",+ offlineExportUnavailable_invalidManagedJre: "所需的 DBX 託管 JRE 無效或不安全。",refresh: "重新整理",javaRuntime: "Java 執行環境",javaRuntimeManaged: "DBX 託管 JRE",diff --git a/apps/desktop/src/lib/backend/__tests__/agentOfflineExportContract.spec.ts b/apps/desktop/src/lib/backend/__tests__/agentOfflineExportContract.spec.tsnew file mode 100644index 0000000000..52fd4ed93b--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/agentOfflineExportContract.spec.ts@@ -0,0 +1,126 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++const tauri = readFileSync(new URL("../tauri.ts", import.meta.url), "utf8");+const http = readFileSync(new URL("../http.ts", import.meta.url), "utf8");+const api = readFileSync(new URL("../api.ts", import.meta.url), "utf8");+const driverStore = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");+const tauriRegistry = readFileSync(new URL("../../../../../../src-tauri/src/lib.rs", import.meta.url), "utf8");+const webRegistry = readFileSync(new URL("../../../../../../crates/dbx-web/src/main.rs", import.meta.url), "utf8");++function functionBody(source: string, operation: string): string {+ const start = source.indexOf(`export async function ${operation}(`);+ expect(start, `${operation} transport function`).toBeGreaterThanOrEqual(0);+ const end = source.indexOf("\nexport async function ", start + 1);+ return source.slice(start, end === -1 ? source.length : end);+}++function sourceSection(source: string, startMarker: string, endMarker: string): string {+ const start = source.indexOf(startMarker);+ expect(start, `source marker ${startMarker}`).toBeGreaterThanOrEqual(0);+ const end = source.indexOf(endMarker, start + startMarker.length);+ expect(end, `source marker ${endMarker}`).toBeGreaterThan(start);+ return source.slice(start, end);+}++function buttonTagByTestId(testId: string): string {+ const marker = `data-testid="${testId}"`;+ const markerIndex = driverStore.indexOf(marker);+ expect(markerIndex, marker).toBeGreaterThanOrEqual(0);+ const start = driverStore.lastIndexOf("<Button", markerIndex);+ const end = driverStore.indexOf(">", markerIndex);+ expect(start, `${testId} button start`).toBeGreaterThanOrEqual(0);+ expect(end, `${testId} button end`).toBeGreaterThan(markerIndex);+ return driverStore.slice(start, end + 1);+}++function buttonTagsForClick(handler: string): string[] {+ const marker = `@click="${handler}"`;+ const tags: string[] = [];+ let offset = 0;+ while (true) {+ const markerIndex = driverStore.indexOf(marker, offset);+ if (markerIndex === -1) break;+ const start = driverStore.lastIndexOf("<Button", markerIndex);+ const end = driverStore.indexOf(">", markerIndex);+ expect(start, `${handler} button start`).toBeGreaterThanOrEqual(0);+ expect(end, `${handler} button end`).toBeGreaterThan(markerIndex);+ tags.push(driverStore.slice(start, end + 1));+ offset = end + 1;+ }+ expect(tags.length, `${handler} button count`).toBeGreaterThan(0);+ return tags;+}++describe("offline Agent export transport contract", () => {+ it("routes preview and export through the Tauri desktop backend", () => {+ expect(functionBody(tauri, "previewAgentOfflineExport")).toContain('invoke("preview_agent_offline_export")');+ expect(functionBody(tauri, "exportAgentsOffline")).toContain('invoke("export_agents_offline", { path, driverKeys })');+ expect(tauriRegistry).toContain("commands::agents::preview_agent_offline_export,");+ expect(tauriRegistry).toContain("commands::agents::export_agents_offline,");+ expect(api).toContain('previewAgentOfflineExport = forward("previewAgentOfflineExport")');+ expect(api).toContain('exportAgentsOffline = forward("exportAgentsOffline")');+ });++ it("keeps the Web transport explicitly unsupported without adding HTTP routes", () => {+ for (const operation of ["previewAgentOfflineExport", "exportAgentsOffline"]) {+ const body = functionBody(http, operation);+ expect(body).toContain("only available in the desktop app");+ expect(body).not.toContain("post(");+ expect(body).not.toContain("fetch(");+ }+ expect(webRegistry).not.toContain("agent-offline-export");+ expect(webRegistry).not.toContain("preview_agent_offline_export");+ expect(webRegistry).not.toContain("export_agents_offline");+ });++ it("shows export only on Desktop while preserving offline import on Desktop and Web", () => {+ const exportButton = buttonTagByTestId("agent-offline-export-button");+ const importButton = buttonTagByTestId("agent-offline-import-button");+ expect(exportButton).toContain(`v-if="driverStoreTab === 'agent' && !isWeb"`);+ expect(importButton).toContain(`v-if="driverStoreTab === 'agent'"`);+ expect(importButton).not.toContain("!isWeb");+ expect(exportButton).toContain(':disabled="agentExportImportBlocked"');+ expect(importButton).toContain(':disabled="agentExportImportBlocked"');+ expect(driverStore.indexOf(exportButton)).toBeLessThan(driverStore.indexOf(importButton));+ });++ it("shares one busy contract across export, import, driver, and JRE package actions", () => {+ const busyContract = sourceSection(driverStore, "const agentPackageBusy", "\n\nasync function openOfflineExportDialog");+ for (const dependency of ["agentImportBusy.value", "offlineExportLoading.value", "offlineExporting.value", "uninstallingDriver.value", "uninstallingJre.value", "installing.value", "preparingUpgradeAll.value", "upgradingAll.value", "reinstallingJre.value", "queuedDriverInstalls.value"]) {+ expect(busyContract).toContain(dependency);+ }++ for (const handler of ["upgradeAll", "installDriver(driver.db_type)", "importDriverFile(driver)", "uninstallDriver(driver.db_type)", "reinstallJre(jre.key)", "uninstallJre(jre.key)"]) {+ for (const button of buttonTagsForClick(handler)) expect(button).toContain("agentPackageBusy");+ }++ expect(sourceSection(driverStore, "async function importOfflineZip", "\n\nasync function importDriverFile")).toContain("if (agentExportImportBlocked.value) return;");+ });++ it("uses the platform-specific ZIP save contract and keeps failed exports retryable", () => {+ const openDialog = sourceSection(driverStore, "async function openOfflineExportDialog", "\n\nasync function exportOfflinePackage");+ expect(openDialog).toContain("if (isWeb || agentExportImportBlocked.value) return;");+ expect(openDialog).toContain("offlineExportDialogOpen.value = true;");+ expect(openDialog.indexOf('offlineExportError.value = "";')).toBeLessThan(openDialog.indexOf("await api.previewAgentOfflineExport()"));++ const exportPackage = sourceSection(driverStore, "async function exportOfflinePackage", "\n\nfunction chooseWebOfflineZip");+ expect(exportPackage).toContain("runAgentOfflineExportAction({");+ expect(exportPackage).toContain("defaultPath: `dbx-agents-offline-${platform}.zip`");+ expect(exportPackage).toContain('filters: [{ name: "ZIP", extensions: ["zip"] }]');++ const success = sourceSection(exportPackage, "onSuccess:", "\n onError:");+ const failure = exportPackage.slice(exportPackage.indexOf("onError:"));+ expect(success).toContain("offlineExportDialogOpen.value = false;");+ expect(failure).toContain('t("driverStore.offlineExportFailed"');+ expect(failure).not.toContain("offlineExportDialogOpen.value = false;");++ const dialog = sourceSection(driverStore, "<AgentOfflineExportDialog", " />");+ expect(dialog).toContain('v-model:open="offlineExportDialogOpen"');+ expect(dialog).toContain(':preview="offlineExportPreview"');+ expect(dialog).toContain(':loading="offlineExportLoading"');+ expect(dialog).toContain(':exporting="offlineExporting"');+ expect(dialog).toContain(':error="offlineExportError"');+ expect(dialog).toContain('@confirm="exportOfflinePackage"');+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex 70f6f0e1b4..d98a70b16b 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -118,6 +118,8 @@ export async function importAgentsFromZip(fileOrPath: string | File, operationIdconst backend = await getBackend();return backend.importAgentsFromZip(fileOrPath, operationId);}+export const previewAgentOfflineExport = forward("previewAgentOfflineExport");+export const exportAgentsOffline = forward("exportAgentsOffline");export const importAgentDriver = forward("importAgentDriver");export const importAgentJar = importAgentDriver;export async function reinstallJre(jreKey?: string, operationId?: string) {@@ -801,6 +803,11 @@ export type {AiConversation,PromptTemplate,AgentDriverInfo,+ AgentOfflineArtifactKind,+ AgentOfflineExportUnavailableReason,+ AgentOfflineExportCandidate,+ AgentOfflineExportPreview,+ AgentOfflineExportResult,DriverStoreUsage,DriverStoreUsageItem,DriverRuntimeHealth,diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex a2d71d25ed..8e3a548665 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -63,6 +63,8 @@ import type {DriverRuntimeSummary,UpgradeAllAgentDriversResult,AgentUpdateBlocker,+ AgentOfflineExportPreview,+ AgentOfflineExportResult,DesktopSettings,McpGlobalPolicy,SavedSqlSyncRequest,@@ -645,6 +647,14 @@ export async function importAgentsFromZip(fileOrPath: string | File, operationIdreturn result.count;}+export async function previewAgentOfflineExport(): Promise<AgentOfflineExportPreview> {+ throw new Error("Offline Agent package export is only available in the desktop app.");+}++export async function exportAgentsOffline(_path: string, _driverKeys: string[]): Promise<AgentOfflineExportResult> {+ throw new Error("Offline Agent package export is only available in the desktop app.");+}+export async function importAgentDriver(dbType: string, pathOrFile: string | File): Promise<void> {let blob: Blob;let fileName: string;diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 2339ce9936..e276d722f4 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -141,6 +141,33 @@ export interface AgentUpdateBlocker {label: string;}+export type AgentOfflineArtifactKind = "jar" | "native";++export type AgentOfflineExportUnavailableReason = "unmanagedInstall" | "localInstall" | "launchConfig" | "missingArtifact" | "invalidArtifact" | "unsafeSource" | "externalDriverRequired" | "missingManagedJre" | "invalidManagedJre";++export interface AgentOfflineExportCandidate {+ dbType: string;+ label: string;+ version: string;+ size: number;+ artifactKind: AgentOfflineArtifactKind | null;+ requiredJre: string | null;+ eligible: boolean;+ unavailableReason: AgentOfflineExportUnavailableReason | null;+}++export interface AgentOfflineExportPreview {+ platform: string;+ candidates: AgentOfflineExportCandidate[];+}++export interface AgentOfflineExportResult {+ platform: string;+ driverCount: number;+ jreCount: number;+ bytes: number;+}+export type JavaRuntimeMode = "managed" | "system" | "custom";export interface JavaRuntimeConfig {@@ -2028,6 +2055,14 @@ export async function importAgentsFromZip(path: string | File, operationId?: strreturn invoke("import_agents_from_zip", { path, operationId });}+export async function previewAgentOfflineExport(): Promise<AgentOfflineExportPreview> {+ return invoke("preview_agent_offline_export");+}++export async function exportAgentsOffline(path: string, driverKeys: string[]): Promise<AgentOfflineExportResult> {+ return invoke("export_agents_offline", { path, driverKeys });+}+export async function importAgentDriver(dbType: string, path: string | File): Promise<void> {if (typeof path !== "string") {throw new Error("Desktop driver import requires a local file path");diff --git a/apps/desktop/src/lib/driverStore/__tests__/agentOfflineExportFlow.spec.ts b/apps/desktop/src/lib/driverStore/__tests__/agentOfflineExportFlow.spec.tsnew file mode 100644index 0000000000..65a1a498df--- /dev/null+++ b/apps/desktop/src/lib/driverStore/__tests__/agentOfflineExportFlow.spec.ts@@ -0,0 +1,127 @@+import { describe, expect, it, vi } from "vitest";+import { runAgentOfflineExportAction, runAgentOfflineExportFlow } from "@/lib/driverStore/agentOfflineExportFlow";++describe("runAgentOfflineExportFlow", () => {+ it("stops silently when destination selection is cancelled", async () => {+ const exportPackage = vi.fn();++ await expect(+ runAgentOfflineExportFlow({+ driverKeys: ["duckdb"],+ chooseDestination: vi.fn().mockResolvedValue(null),+ exportPackage,+ }),+ ).resolves.toBeNull();+ expect(exportPackage).not.toHaveBeenCalled();+ });++ it("exports the selected drivers to the chosen destination", async () => {+ const driverKeys = ["duckdb", "redis"];+ const exportPackage = vi.fn().mockResolvedValue({ driverCount: 2 });++ await expect(+ runAgentOfflineExportFlow({+ driverKeys,+ chooseDestination: vi.fn().mockResolvedValue("/tmp/dbx-agents.zip"),+ exportPackage,+ }),+ ).resolves.toEqual({+ destination: "/tmp/dbx-agents.zip",+ result: { driverCount: 2 },+ });+ expect(exportPackage).toHaveBeenCalledWith("/tmp/dbx-agents.zip", ["duckdb", "redis"]);++ driverKeys.push("kafka");+ expect(exportPackage.mock.calls[0]?.[1]).toEqual(["duckdb", "redis"]);+ });++ it("does not open the save dialog for an empty selection", async () => {+ const chooseDestination = vi.fn();+ const exportPackage = vi.fn();++ await expect(runAgentOfflineExportFlow({ driverKeys: [], chooseDestination, exportPackage })).resolves.toBeNull();+ expect(chooseDestination).not.toHaveBeenCalled();+ expect(exportPackage).not.toHaveBeenCalled();+ });++ it.each([+ ["destination selection", vi.fn().mockRejectedValue(new Error("save failed"))],+ ["package creation", vi.fn().mockResolvedValue("/tmp/dbx-agents.zip")],+ ])("propagates %s failures to the caller", async (stage, chooseDestination) => {+ const exportPackage = stage === "package creation" ? vi.fn().mockRejectedValue(new Error("export failed")) : vi.fn();++ await expect(+ runAgentOfflineExportFlow({+ driverKeys: ["duckdb"],+ chooseDestination,+ exportPackage,+ }),+ ).rejects.toThrow(stage === "destination selection" ? "save failed" : "export failed");+ });+});++describe("runAgentOfflineExportAction", () => {+ function createOptions(overrides: Partial<Parameters<typeof runAgentOfflineExportAction<{ driverCount: number }>>[0]> = {}) {+ return {+ driverKeys: ["duckdb"],+ chooseDestination: vi.fn().mockResolvedValue("/tmp/dbx-agents.zip"),+ exportPackage: vi.fn().mockResolvedValue({ driverCount: 1 }),+ setBusy: vi.fn(),+ onSuccess: vi.fn(),+ onError: vi.fn(),+ ...overrides,+ };+ }++ it("holds the busy state across destination selection and package creation", async () => {+ const events: string[] = [];+ const options = createOptions({+ setBusy: vi.fn((busy: boolean) => events.push(`busy:${busy}`)),+ chooseDestination: vi.fn(async () => {+ events.push("choose");+ return "/tmp/dbx-agents.zip";+ }),+ exportPackage: vi.fn(async () => {+ events.push("export");+ return { driverCount: 1 };+ }),+ onSuccess: vi.fn(() => events.push("success")),+ });++ await expect(runAgentOfflineExportAction(options)).resolves.toBe("exported");+ expect(events).toEqual(["busy:true", "choose", "export", "success", "busy:false"]);+ expect(options.onError).not.toHaveBeenCalled();+ });++ it("keeps cancellation silent and always releases the busy state", async () => {+ const options = createOptions({ chooseDestination: vi.fn().mockResolvedValue(null) });++ await expect(runAgentOfflineExportAction(options)).resolves.toBe("cancelled");+ expect(options.setBusy).toHaveBeenNthCalledWith(1, true);+ expect(options.setBusy).toHaveBeenLastCalledWith(false);+ expect(options.exportPackage).not.toHaveBeenCalled();+ expect(options.onSuccess).not.toHaveBeenCalled();+ expect(options.onError).not.toHaveBeenCalled();+ });++ it.each([+ ["destination selection", { chooseDestination: vi.fn().mockRejectedValue(new Error("save failed")) }],+ ["package creation", { exportPackage: vi.fn().mockRejectedValue(new Error("export failed")) }],+ ])("reports %s failures and releases the busy state", async (_stage, overrides) => {+ const options = createOptions(overrides);++ await expect(runAgentOfflineExportAction(options)).resolves.toBe("failed");+ expect(options.setBusy).toHaveBeenNthCalledWith(1, true);+ expect(options.setBusy).toHaveBeenLastCalledWith(false);+ expect(options.onSuccess).not.toHaveBeenCalled();+ expect(options.onError).toHaveBeenCalledOnce();+ });++ it("does not enter the busy state for an empty selection", async () => {+ const options = createOptions({ driverKeys: [] });++ await expect(runAgentOfflineExportAction(options)).resolves.toBe("empty");+ expect(options.setBusy).not.toHaveBeenCalled();+ expect(options.chooseDestination).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/driverStore/agentOfflineExportFlow.ts b/apps/desktop/src/lib/driverStore/agentOfflineExportFlow.tsnew file mode 100644index 0000000000..72accf78bd--- /dev/null+++ b/apps/desktop/src/lib/driverStore/agentOfflineExportFlow.ts@@ -0,0 +1,57 @@+export interface AgentOfflineExportFlowOptions<TResult> {+ driverKeys: string[];+ chooseDestination: () => Promise<string | null>;+ exportPackage: (destination: string, driverKeys: string[]) => Promise<TResult>;+}++export interface AgentOfflineExportFlowResult<TResult> {+ destination: string;+ result: TResult;+}++export interface AgentOfflineExportActionOptions<TResult> extends AgentOfflineExportFlowOptions<TResult> {+ setBusy: (busy: boolean) => void;+ onSuccess: (exported: AgentOfflineExportFlowResult<TResult>) => void | Promise<void>;+ onError: (error: unknown) => void | Promise<void>;+}++export type AgentOfflineExportActionResult = "empty" | "cancelled" | "exported" | "failed";++/**+ * Keep destination selection and package creation in one testable workflow.+ * The caller owns the busy state so it can cover the native save dialog too.+ */+export async function runAgentOfflineExportFlow<TResult>({ driverKeys, chooseDestination, exportPackage }: AgentOfflineExportFlowOptions<TResult>): Promise<AgentOfflineExportFlowResult<TResult> | null> {+ if (driverKeys.length === 0) return null;++ const destination = await chooseDestination();+ if (!destination) return null;++ return {+ destination,+ result: await exportPackage(destination, [...driverKeys]),+ };+}++/**+ * Own the complete UI action lifecycle, including the native save dialog.+ * This keeps busy-state release and success/error side effects testable as one+ * contract instead of splitting them between the component and export helper.+ */+export async function runAgentOfflineExportAction<TResult>({ driverKeys, chooseDestination, exportPackage, setBusy, onSuccess, onError }: AgentOfflineExportActionOptions<TResult>): Promise<AgentOfflineExportActionResult> {+ if (driverKeys.length === 0) return "empty";++ setBusy(true);+ try {+ const exported = await runAgentOfflineExportFlow({ driverKeys, chooseDestination, exportPackage });+ if (!exported) return "cancelled";++ await onSuccess(exported);+ return "exported";+ } catch (error) {+ await onError(error);+ return "failed";+ } finally {+ setBusy(false);+ }+}diff --git a/crates/dbx-core/src/agent_offline_export.rs b/crates/dbx-core/src/agent_offline_export.rsnew file mode 100644index 0000000000..9538dc1e3e--- /dev/null+++ b/crates/dbx-core/src/agent_offline_export.rs@@ -0,0 +1,1811 @@+use std::collections::{BTreeMap, BTreeSet, HashMap};+use std::fs::{self, File, Metadata};+use std::io::{Read, Write};+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use zip::write::SimpleFileOptions;++use crate::agent_catalog;+use crate::agent_manager::{AgentManager, AgentState, ArtifactFormat, ArtifactInfo, DriverInfo, JreInfo};+use crate::agent_service::{inspect_offline_package, replace_download, validate_native_agent_binary};++const LOCAL_DRIVER_VERSIONS: &[&str] = &["local", "0.1.0-local"];+const MAX_AGENT_MANIFEST_BYTES: u64 = 1024 * 1024;+const MAX_EXPORT_ARTIFACT_BYTES: u64 = 8 * 1024 * 1024 * 1024;+const MAX_JRE_ENTRY_COUNT: usize = 100_000;+const MAX_JRE_DEPTH: usize = 64;+const MAX_JRE_UNCOMPRESSED_BYTES: u64 = 8 * 1024 * 1024 * 1024;++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum AgentOfflineArtifactKind {+ Jar,+ Native,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum AgentOfflineExportUnavailableReason {+ UnmanagedInstall,+ LocalInstall,+ LaunchConfig,+ MissingArtifact,+ InvalidArtifact,+ UnsafeSource,+ ExternalDriverRequired,+ MissingManagedJre,+ InvalidManagedJre,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct AgentOfflineExportCandidate {+ pub db_type: String,+ pub label: String,+ pub version: String,+ pub size: u64,+ pub artifact_kind: Option<AgentOfflineArtifactKind>,+ pub required_jre: Option<String>,+ pub eligible: bool,+ pub unavailable_reason: Option<AgentOfflineExportUnavailableReason>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct AgentOfflineExportPreview {+ pub platform: String,+ pub candidates: Vec<AgentOfflineExportCandidate>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct AgentOfflineExportResult {+ pub platform: String,+ pub driver_count: usize,+ pub jre_count: usize,+ pub bytes: u64,+}++#[derive(Debug)]+struct PreparedDriver {+ db_type: String,+ label: String,+ version: String,+ jre: String,+ kind: AgentOfflineArtifactKind,+ source: PathBuf,+ filename: String,+ size: u64,+ sha256: String,+}++#[derive(Debug)]+struct PreparedJre {+ key: String,+ version: String,+ archive: PathBuf,+ filename: String,+ size: u64,+ sha256: String,+}++#[derive(Serialize)]+struct ExportRegistry {+ #[serde(skip_serializing_if = "Option::is_none")]+ jre: Option<JreInfo>,+ jres: BTreeMap<String, JreInfo>,+ drivers: BTreeMap<String, DriverInfo>,+}++pub fn preview_agent_offline_export(am: &AgentManager) -> AgentOfflineExportPreview {+ let _installation_guard = am.installation_operation_lock.blocking_read();+ preview_agent_offline_export_unlocked(am)+}++pub fn export_agents_offline(+ am: &AgentManager,+ destination: &Path,+ selected_driver_keys: &[String],+) -> Result<AgentOfflineExportResult, String> {+ // Driver install/uninstall operations intentionally share the read side of+ // this lock so different drivers can be managed concurrently. Export must+ // take the write side because it reads an arbitrary set of drivers and JREs+ // as one consistent snapshot.+ let _installation_guard = am.installation_operation_lock.blocking_write();+ export_agents_offline_unlocked(am, destination, selected_driver_keys)+}++fn preview_agent_offline_export_unlocked(am: &AgentManager) -> AgentOfflineExportPreview {+ let state = am.load_state();+ let mut jre_validity = HashMap::<String, Result<(), AgentOfflineExportUnavailableReason>>::new();+ let mut candidates = Vec::new();++ for (db_type, label) in agent_catalog::driver_store_entries() {+ let has_artifact = am.driver_launch_config_path(db_type).exists()+ || am.driver_native_path(db_type).exists()+ || am.driver_jar_path(db_type).exists();+ let installed = state.installed_drivers.get(db_type);+ if installed.is_none() && !has_artifact {+ continue;+ }++ candidates.push(classify_candidate(am, &state, db_type, label, &mut jre_validity));+ }++ candidates.sort_by(|left, right| left.label.cmp(&right.label).then(left.db_type.cmp(&right.db_type)));+ AgentOfflineExportPreview { platform: AgentManager::current_platform().to_string(), candidates }+}++fn classify_candidate(+ am: &AgentManager,+ state: &AgentState,+ db_type: &str,+ label: &str,+ jre_validity: &mut HashMap<String, Result<(), AgentOfflineExportUnavailableReason>>,+) -> AgentOfflineExportCandidate {+ let installed = state.installed_drivers.get(db_type);+ let version = installed.map(|driver| driver.version.clone()).unwrap_or_else(|| "unknown".to_string());+ let native_path = am.driver_native_path(db_type);+ let jar_path = am.driver_jar_path(db_type);+ let launch_config_path = am.driver_launch_config_path(db_type);+ let artifact_kind = if native_path.exists() {+ Some(AgentOfflineArtifactKind::Native)+ } else if jar_path.exists() {+ Some(AgentOfflineArtifactKind::Jar)+ } else {+ None+ };+ let required_jre = matches!(artifact_kind, Some(AgentOfflineArtifactKind::Jar))+ .then(|| installed.map(|driver| driver.jre.clone()))+ .flatten();++ let unavailable_reason = if installed.is_none() {+ Some(AgentOfflineExportUnavailableReason::UnmanagedInstall)+ } else if LOCAL_DRIVER_VERSIONS.iter().any(|local| version.eq_ignore_ascii_case(local)) {+ Some(AgentOfflineExportUnavailableReason::LocalInstall)+ } else if launch_config_path.exists() {+ Some(AgentOfflineExportUnavailableReason::LaunchConfig)+ } else {+ match artifact_kind {+ Some(AgentOfflineArtifactKind::Native) => classify_native_source(am, &native_path).err(),+ Some(AgentOfflineArtifactKind::Jar) => {+ let jar_reason = classify_jar_source(am, &jar_path).err();+ if jar_reason.is_some() {+ jar_reason+ } else if let Some(jre_key) = required_jre.as_deref().filter(|key| !key.is_empty()) {+ jre_validity+ .entry(jre_key.to_string())+ .or_insert_with(|| classify_managed_jre(am, jre_key))+ .as_ref()+ .err()+ .copied()+ } else {+ Some(AgentOfflineExportUnavailableReason::MissingManagedJre)+ }+ }+ None => Some(AgentOfflineExportUnavailableReason::MissingArtifact),+ }+ };++ let source = match artifact_kind {+ Some(AgentOfflineArtifactKind::Native) => Some(native_path),+ Some(AgentOfflineArtifactKind::Jar) => Some(jar_path),+ None => None,+ };+ let size = source+ .and_then(|path| fs::symlink_metadata(path).ok())+ .filter(|metadata| metadata.is_file())+ .map(|metadata| metadata.len())+ .unwrap_or(0);++ AgentOfflineExportCandidate {+ db_type: db_type.to_string(),+ label: label.to_string(),+ version,+ size,+ artifact_kind,+ required_jre,+ eligible: unavailable_reason.is_none(),+ unavailable_reason,+ }+}++fn classify_native_source(am: &AgentManager, path: &Path) -> Result<(), AgentOfflineExportUnavailableReason> {+ validate_managed_regular_file(am, path)?;+ validate_native_agent_binary(path).map_err(|_| AgentOfflineExportUnavailableReason::InvalidArtifact)+}++fn classify_jar_source(am: &AgentManager, path: &Path) -> Result<(), AgentOfflineExportUnavailableReason> {+ validate_managed_regular_file(am, path)?;+ match inspect_agent_jar_manifest(path) {+ Ok(true) => Err(AgentOfflineExportUnavailableReason::ExternalDriverRequired),+ Ok(false) => Ok(()),+ Err(_) => Err(AgentOfflineExportUnavailableReason::InvalidArtifact),+ }+}++fn classify_managed_jre(am: &AgentManager, jre_key: &str) -> Result<(), AgentOfflineExportUnavailableReason> {+ let state = am.load_state();+ if !state.jre_versions.contains_key(jre_key) || !am.is_jre_installed(jre_key) {+ return Err(AgentOfflineExportUnavailableReason::MissingManagedJre);+ }+ validate_managed_jre_tree(am, jre_key)+ .map(|_| ())+ .map_err(|_| AgentOfflineExportUnavailableReason::InvalidManagedJre)+}++fn validate_managed_regular_file(+ am: &AgentManager,+ path: &Path,+) -> Result<Metadata, AgentOfflineExportUnavailableReason> {+ let metadata = fs::symlink_metadata(path).map_err(|_| AgentOfflineExportUnavailableReason::MissingArtifact)?;+ if metadata.file_type().is_symlink() {+ return Err(AgentOfflineExportUnavailableReason::UnsafeSource);+ }+ if !metadata.is_file() || metadata.len() == 0 || metadata.len() > MAX_EXPORT_ARTIFACT_BYTES {+ return Err(AgentOfflineExportUnavailableReason::InvalidArtifact);+ }+ ensure_path_within_base(am, path).map_err(|_| AgentOfflineExportUnavailableReason::UnsafeSource)?;+ Ok(metadata)+}++fn ensure_path_within_base(am: &AgentManager, path: &Path) -> Result<(), String> {+ let base = am.base_dir().canonicalize().map_err(|error| format!("Failed to resolve Agent store path: {error}"))?;+ let resolved = path.canonicalize().map_err(|error| format!("Failed to resolve export source: {error}"))?;+ if !resolved.starts_with(&base) {+ return Err("Agent export source is outside the managed Agent store".to_string());+ }+ Ok(())+}++fn inspect_agent_jar_manifest(path: &Path) -> Result<bool, String> {+ let file = File::open(path).map_err(|error| format!("Failed to read Agent JAR: {error}"))?;+ let mut archive = zip::ZipArchive::new(file).map_err(|error| format!("Invalid Agent JAR: {error}"))?;+ let manifest = archive.by_name("META-INF/MANIFEST.MF").map_err(|_| "Agent JAR manifest is missing".to_string())?;+ if manifest.size() > MAX_AGENT_MANIFEST_BYTES {+ return Err(format!("Agent JAR manifest exceeds the {MAX_AGENT_MANIFEST_BYTES}-byte safety limit"));+ }+ let mut text = String::new();+ manifest+ .take(MAX_AGENT_MANIFEST_BYTES + 1)+ .read_to_string(&mut text)+ .map_err(|error| format!("Failed to read Agent JAR manifest: {error}"))?;+ if text.len() as u64 > MAX_AGENT_MANIFEST_BYTES {+ return Err(format!("Agent JAR manifest exceeds the {MAX_AGENT_MANIFEST_BYTES}-byte safety limit"));+ }+ let logical_lines = unfold_manifest_lines(&text)?;+ let has_main_class = logical_lines.iter().any(|line| {+ line.split_once(':')+ .is_some_and(|(name, value)| name.trim().eq_ignore_ascii_case("Main-Class") && !value.trim().is_empty())+ });+ if !has_main_class {+ return Err("Agent JAR manifest does not declare Main-Class".to_string());+ }+ Ok(logical_lines.iter().any(|line| {+ line.split_once(':').is_some_and(|(name, value)| {+ name.trim().eq_ignore_ascii_case("Agent-External-Driver") && value.trim().eq_ignore_ascii_case("true")+ })+ }))+}++fn unfold_manifest_lines(manifest: &str) -> Result<Vec<String>, String> {+ let mut logical_lines = Vec::<String>::new();+ for physical_line in manifest.split('\n') {+ let line = physical_line.strip_suffix('\r').unwrap_or(physical_line);+ if let Some(continuation) = line.strip_prefix(' ') {+ let previous = logical_lines+ .last_mut()+ .ok_or_else(|| "Agent JAR manifest starts with an invalid continuation line".to_string())?;+ previous.push_str(continuation);+ } else {+ logical_lines.push(line.to_string());+ }+ }+ Ok(logical_lines)+}++fn export_agents_offline_unlocked(+ am: &AgentManager,+ destination: &Path,+ selected_driver_keys: &[String],+) -> Result<AgentOfflineExportResult, String> {+ let selected = selected_driver_keys.iter().map(String::as_str).collect::<BTreeSet<_>>();+ if selected.is_empty() {+ return Err("Select at least one eligible Agent driver to export.".to_string());+ }++ let preview = preview_agent_offline_export_unlocked(am);+ let candidate_by_key =+ preview.candidates.iter().map(|candidate| (candidate.db_type.as_str(), candidate)).collect::<HashMap<_, _>>();+ let state = am.load_state();+ let mut drivers = Vec::with_capacity(selected.len());+ let mut required_jres = BTreeSet::new();++ for db_type in selected {+ let candidate = candidate_by_key+ .get(db_type)+ .ok_or_else(|| format!("Agent driver is not installed or cannot be exported: {db_type}"))?;+ if !candidate.eligible {+ let reason = candidate.unavailable_reason.map(unavailable_reason_label).unwrap_or("unknown reason");+ return Err(format!("{} cannot be exported: {reason}", candidate.label));+ }+ let installed = state+ .installed_drivers+ .get(db_type)+ .ok_or_else(|| format!("Agent driver installation state is missing: {db_type}"))?;+ let kind = candidate.artifact_kind.ok_or_else(|| format!("Agent artifact is missing: {db_type}"))?;+ let source = match kind {+ AgentOfflineArtifactKind::Jar => am.driver_jar_path(db_type),+ AgentOfflineArtifactKind::Native => am.driver_native_path(db_type),+ };+ let filename = match kind {+ AgentOfflineArtifactKind::Jar => format!("dbx-agent-{db_type}.jar"),+ AgentOfflineArtifactKind::Native => {+ let suffix = if cfg!(windows) { ".exe" } else { "" };+ format!("dbx-agent-{db_type}-{}{suffix}", AgentManager::current_platform())+ }+ };+ if kind == AgentOfflineArtifactKind::Jar {+ required_jres.insert(installed.jre.clone());+ }+ drivers.push(PreparedDriver {+ db_type: db_type.to_string(),+ label: candidate.label.clone(),+ version: installed.version.clone(),+ jre: installed.jre.clone(),+ kind,+ source,+ filename,+ size: 0,+ sha256: String::new(),+ });+ }++ validate_export_destination_name(destination)?;+ let destination_parent = normalized_parent(destination)?;+ fs::create_dir_all(&destination_parent)+ .map_err(|error| format!("Failed to create export destination directory: {error}"))?;+ validate_export_destination(am, destination, &destination_parent)?;+ let staging_dir = tempfile::Builder::new()+ .prefix(".dbx-agent-export-")+ .tempdir_in(&destination_parent)+ .map_err(|error| format!("Failed to create export staging directory: {error}"))?;++ let driver_snapshot_dir = staging_dir.path().join("driver-snapshots");+ fs::create_dir(&driver_snapshot_dir)+ .map_err(|error| format!("Failed to create driver snapshot directory: {error}"))?;+ for driver in &mut drivers {+ let snapshot = driver_snapshot_dir.join(&driver.filename);+ let (size, sha256) = snapshot_driver_source(am, &driver.source, &snapshot, driver.kind)+ .map_err(|error| format!("Failed to snapshot {} Agent artifact: {error}", driver.label))?;+ driver.source = snapshot;+ driver.size = size;+ driver.sha256 = sha256;+ }++ let mut jres = Vec::with_capacity(required_jres.len());+ for key in required_jres {+ validate_offline_identifier(&key, "JRE")?;+ let version = state+ .jre_versions+ .get(&key)+ .cloned()+ .ok_or_else(|| format!("Managed JRE {key} installation state is missing"))?;+ validate_managed_jre_tree(am, &key)?;+ let filename =+ format!("dbx-jre-{}-{}-{}.tar.zst", key, safe_filename_token(&version), AgentManager::current_platform());+ let archive = staging_dir.path().join(&filename);+ archive_managed_jre(am, &key, &archive)?;+ let size =+ fs::metadata(&archive).map_err(|error| format!("Failed to inspect archived JRE {key}: {error}"))?.len();+ let sha256 = sha256_file(&archive)?;+ jres.push(PreparedJre { key, version, archive, filename, size, sha256 });+ }++ let registry = build_export_registry(am, &drivers, &jres);+ let registry_json = serde_json::to_vec_pretty(®istry)+ .map_err(|error| format!("Failed to serialize offline Agent registry: {error}"))?;+ let destination_name = destination.file_name().and_then(|name| name.to_str()).unwrap_or("agents-offline.zip");+ let temporary_path = destination_parent.join(format!(".{destination_name}.partial-{}", uuid::Uuid::new_v4()));++ write_and_finalize_export_zip(&temporary_path, destination, ®istry_json, &drivers, &jres, |package| {+ let plan = inspect_offline_package(package)?;+ let expected = drivers.iter().map(|driver| driver.db_type.clone()).collect::<BTreeSet<_>>();+ let actual = plan.driver_keys.into_iter().collect::<BTreeSet<_>>();+ if expected != actual || plan.includes_jre != !jres.is_empty() {+ return Err("Generated offline Agent package failed compatibility validation".to_string());+ }+ Ok(())+ })?;++ let bytes =+ fs::metadata(destination).map_err(|error| format!("Failed to inspect exported package: {error}"))?.len();+ Ok(AgentOfflineExportResult {+ platform: AgentManager::current_platform().to_string(),+ driver_count: drivers.len(),+ jre_count: jres.len(),+ bytes,+ })+}++fn build_export_registry(am: &AgentManager, drivers: &[PreparedDriver], jres: &[PreparedJre]) -> ExportRegistry {+ let platform = AgentManager::current_platform().to_string();+ let mut registry_drivers = BTreeMap::new();+ for driver in drivers {+ let artifact = ArtifactInfo {+ url: format!("offline://{}", driver.filename),+ sha256: Some(driver.sha256.clone()),+ size: driver.size,+ format: None,+ };+ let (jar, native) = match driver.kind {+ AgentOfflineArtifactKind::Jar => (Some(artifact), HashMap::new()),+ AgentOfflineArtifactKind::Native => (None, HashMap::from([(platform.clone(), artifact)])),+ };+ registry_drivers.insert(+ driver.db_type.clone(),+ DriverInfo {+ version: driver.version.clone(),+ label: driver.label.clone(),+ min_app_version: am.agent_app_version().to_string(),+ jar,+ native,+ jre: driver.jre.clone(),+ },+ );+ }++ let mut registry_jres = BTreeMap::new();+ for jre in jres {+ registry_jres.insert(+ jre.key.clone(),+ JreInfo {+ version: jre.version.clone(),+ platforms: HashMap::from([(+ platform.clone(),+ ArtifactInfo {+ url: format!("offline://{}", jre.filename),+ sha256: Some(jre.sha256.clone()),+ size: jre.size,+ format: Some(ArtifactFormat::TarZstd),+ },+ )]),+ },+ );+ }++ ExportRegistry { jre: None, jres: registry_jres, drivers: registry_drivers }+}++fn write_export_zip(+ path: &Path,+ registry_json: &[u8],+ drivers: &[PreparedDriver],+ jres: &[PreparedJre],+) -> Result<(), String> {+ let file = File::create(path).map_err(|error| format!("Failed to create offline Agent package: {error}"))?;+ let mut archive = zip::ZipWriter::new(file);+ let options =+ SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o644);++ archive+ .start_file("agent-registry.json", options)+ .map_err(|error| format!("Failed to write offline Agent registry: {error}"))?;+ archive.write_all(registry_json).map_err(|error| format!("Failed to write offline Agent registry: {error}"))?;+ for driver in drivers {+ write_zip_file(+ &mut archive,+ &format!("drivers/{}", driver.filename),+ &driver.source,+ driver.size,+ &driver.sha256,+ options,+ )?;+ }+ for jre in jres {+ write_zip_file(&mut archive, &format!("jre/{}", jre.filename), &jre.archive, jre.size, &jre.sha256, options)?;+ }+ let mut file = archive.finish().map_err(|error| format!("Failed to finalize offline Agent package: {error}"))?;+ file.flush().map_err(|error| format!("Failed to flush offline Agent package: {error}"))?;+ file.sync_all().map_err(|error| format!("Failed to sync offline Agent package: {error}"))+}++fn write_and_finalize_export_zip<F>(+ temporary_path: &Path,+ destination: &Path,+ registry_json: &[u8],+ drivers: &[PreparedDriver],+ jres: &[PreparedJre],+ validate: F,+) -> Result<(), String>+where+ F: FnOnce(&Path) -> Result<(), String>,+{+ let result = write_export_zip(temporary_path, registry_json, drivers, jres)+ .and_then(|_| validate(temporary_path))+ .and_then(|_| replace_download(temporary_path, destination));+ if let Err(error) = result {+ fs::remove_file(temporary_path).ok();+ return Err(error);+ }+ Ok(())+}++fn write_zip_file(+ archive: &mut zip::ZipWriter<File>,+ entry_name: &str,+ source: &Path,+ expected_size: u64,+ expected_sha256: &str,+ options: SimpleFileOptions,+) -> Result<(), String> {+ archive+ .start_file(entry_name, options)+ .map_err(|error| format!("Failed to add {entry_name} to offline package: {error}"))?;+ let mut source_file =+ File::open(source).map_err(|error| format!("Failed to open {}: {error}", source.display()))?;+ let mut digest = Sha256::new();+ let mut size = 0u64;+ let mut buffer = [0u8; 64 * 1024];+ loop {+ let read =+ source_file.read(&mut buffer).map_err(|error| format!("Failed to read {}: {error}", source.display()))?;+ if read == 0 {+ break;+ }+ size = size.checked_add(read as u64).ok_or_else(|| format!("{entry_name} size overflow"))?;+ digest.update(&buffer[..read]);+ archive+ .write_all(&buffer[..read])+ .map_err(|error| format!("Failed to add {entry_name} to offline package: {error}"))?;+ }+ let sha256 = format!("{:x}", digest.finalize());+ if size != expected_size || !sha256.eq_ignore_ascii_case(expected_sha256) {+ return Err(format!("Offline export source changed while archiving {entry_name}"));+ }+ Ok(())+}++fn snapshot_driver_source(+ am: &AgentManager,+ source: &Path,+ snapshot: &Path,+ kind: AgentOfflineArtifactKind,+) -> Result<(u64, String), String> {+ let before =+ validate_managed_regular_file(am, source).map_err(|reason| unavailable_reason_label(reason).to_string())?;+ let mut source_file = File::open(source).map_err(|error| format!("Failed to open source: {error}"))?;+ let opened = source_file.metadata().map_err(|error| format!("Failed to inspect opened source: {error}"))?;+ if !opened.is_file() || opened.len() == 0 || opened.len() > MAX_EXPORT_ARTIFACT_BYTES {+ return Err("the opened Agent artifact is invalid".to_string());+ }+ ensure_path_within_base(am, source)?;+ let after = fs::symlink_metadata(source).map_err(|error| format!("Failed to re-inspect source: {error}"))?;+ if after.file_type().is_symlink() || !after.is_file() || !same_opened_file(&opened, &after) {+ return Err("the Agent artifact changed while it was being opened".to_string());+ }+ if !same_opened_file(&before, &opened) {+ return Err("the Agent artifact changed before it could be snapshotted".to_string());+ }++ let mut snapshot_file = fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(snapshot)+ .map_err(|error| format!("Failed to create snapshot: {error}"))?;+ let mut digest = Sha256::new();+ let mut size = 0u64;+ let mut buffer = [0u8; 64 * 1024];+ loop {+ let read = source_file.read(&mut buffer).map_err(|error| format!("Failed to read source: {error}"))?;+ if read == 0 {+ break;+ }+ size = size.checked_add(read as u64).ok_or_else(|| "Agent artifact size overflow".to_string())?;+ if size > MAX_EXPORT_ARTIFACT_BYTES {+ return Err(format!("Agent artifact exceeds the {MAX_EXPORT_ARTIFACT_BYTES}-byte safety limit"));+ }+ digest.update(&buffer[..read]);+ snapshot_file.write_all(&buffer[..read]).map_err(|error| format!("Failed to write snapshot: {error}"))?;+ }+ if size != opened.len() {+ return Err("the Agent artifact changed while it was being snapshotted".to_string());+ }+ let opened_after =+ source_file.metadata().map_err(|error| format!("Failed to re-inspect opened source: {error}"))?;+ let path_after = fs::symlink_metadata(source).map_err(|error| format!("Failed to re-inspect source: {error}"))?;+ ensure_path_within_base(am, source)?;+ if path_after.file_type().is_symlink()+ || !path_after.is_file()+ || !same_opened_entry(&opened, &opened_after)+ || !same_opened_entry(&opened_after, &path_after)+ {+ return Err("the Agent artifact changed while it was being snapshotted".to_string());+ }+ snapshot_file.flush().map_err(|error| format!("Failed to flush snapshot: {error}"))?;+ snapshot_file.sync_all().map_err(|error| format!("Failed to sync snapshot: {error}"))?;+ drop(snapshot_file);++ match kind {+ AgentOfflineArtifactKind::Jar => match inspect_agent_jar_manifest(snapshot) {+ Ok(false) => {}+ Ok(true) => {+ return Err(+ unavailable_reason_label(AgentOfflineExportUnavailableReason::ExternalDriverRequired).to_string()+ )+ }+ Err(error) => return Err(format!("invalid Agent JAR: {error}")),+ },+ AgentOfflineArtifactKind::Native => validate_native_agent_binary(snapshot)?,+ }+ Ok((size, format!("{:x}", digest.finalize())))+}++#[cfg(unix)]+fn same_opened_file(left: &Metadata, right: &Metadata) -> bool {+ use std::os::unix::fs::MetadataExt;++ left.dev() == right.dev() && left.ino() == right.ino() && left.len() == right.len()+}++#[cfg(not(unix))]+fn same_opened_file(left: &Metadata, right: &Metadata) -> bool {+ left.len() == right.len()+}++fn archive_managed_jre(am: &AgentManager, key: &str, destination: &Path) -> Result<(), String> {+ let source = am.jre_dir(key);+ validate_managed_jre_tree(am, key)?;+ let file = File::create(destination).map_err(|error| format!("Failed to create JRE archive: {error}"))?;+ let encoder = zstd::stream::write::Encoder::new(file, 6)+ .map_err(|error| format!("Failed to initialize JRE compression: {error}"))?;+ let mut archive = tar::Builder::new(encoder);+ let root_name = PathBuf::from(format!("dbx-jre-{key}"));+ append_jre_tree(&mut archive, &source, &root_name)?;+ let encoder = archive.into_inner().map_err(|error| format!("Failed to finalize JRE archive: {error}"))?;+ let mut file = encoder.finish().map_err(|error| format!("Failed to finish JRE compression: {error}"))?;+ file.flush().map_err(|error| format!("Failed to flush JRE archive: {error}"))?;+ file.sync_all().map_err(|error| format!("Failed to sync JRE archive: {error}"))+}++fn append_jre_tree<W: Write>(+ archive: &mut tar::Builder<W>,+ source_root: &Path,+ archive_root: &Path,+) -> Result<(), String> {+ append_jre_tree_with_limits(+ archive,+ source_root,+ archive_root,+ MAX_JRE_ENTRY_COUNT,+ MAX_JRE_DEPTH,+ MAX_JRE_UNCOMPRESSED_BYTES,+ )+}++fn append_jre_tree_with_limits<W: Write>(+ archive: &mut tar::Builder<W>,+ source_root: &Path,+ archive_root: &Path,+ max_entry_count: usize,+ max_depth: usize,+ max_uncompressed_bytes: u64,+) -> Result<(), String> {+ let canonical_root = source_root+ .canonicalize()+ .map_err(|error| format!("Failed to resolve managed JRE root {}: {error}", source_root.display()))?;+ let mut stack = vec![(source_root.to_path_buf(), archive_root.to_path_buf(), 0usize)];+ let mut entry_count = 1usize;+ let mut total_bytes = 0u64;+ while let Some((source, archive_path, depth)) = stack.pop() {+ if depth > max_depth {+ return Err(format!("Managed JRE exceeds the export depth limit of {max_depth}"));+ }+ let canonical_source = source+ .canonicalize()+ .map_err(|error| format!("Failed to resolve managed JRE entry {}: {error}", source.display()))?;+ if !canonical_source.starts_with(&canonical_root) {+ return Err(format!("Managed JRE entry resolves outside the managed JRE root: {}", source.display()));+ }+ let metadata = fs::symlink_metadata(&source)+ .map_err(|error| format!("Failed to inspect managed JRE entry {}: {error}", source.display()))?;+ if metadata.file_type().is_symlink() {+ // Official JRE archives can contain relative links for duplicated+ // license files. Preserve the package's no-symlink extraction+ // contract by copying safe in-tree file targets as regular files.+ let (link_target, resolved_target, target_metadata) =+ resolve_managed_jre_file_symlink(&source, &canonical_root)?;+ if resolved_target != canonical_source {+ return Err(format!(+ "Managed JRE symbolic link changed while it was being archived: {}",+ source.display()+ ));+ }+ let file = File::open(&source)+ .map_err(|error| format!("Failed to open managed JRE symbolic link {}: {error}", source.display()))?;+ let opened = file.metadata().map_err(|error| {+ format!("Failed to inspect managed JRE symbolic link target {}: {error}", source.display())+ })?;+ if !opened.is_file() || !same_opened_entry(&target_metadata, &opened) {+ return Err(format!(+ "Managed JRE symbolic link target changed while it was being opened: {}",+ source.display()+ ));+ }+ total_bytes = total_bytes+ .checked_add(opened.len())+ .ok_or_else(|| "Managed JRE size overflow during export".to_string())?;+ if total_bytes > max_uncompressed_bytes {+ return Err(format!("Managed JRE exceeds the export size limit of {max_uncompressed_bytes} bytes"));+ }+ let mut header = tar::Header::new_gnu();+ header.set_mtime(0);+ header.set_uid(0);+ header.set_gid(0);+ header.set_entry_type(tar::EntryType::Regular);+ header.set_mode(metadata_mode(&opened));+ header.set_size(opened.len());+ header.set_cksum();+ let mut file = file;+ archive.append_data(&mut header, &archive_path, &mut file).map_err(|error| {+ format!("Failed to archive managed JRE symbolic link {}: {error}", source.display())+ })?;++ let link_metadata_after = fs::symlink_metadata(&source).map_err(|error| {+ format!("Failed to re-inspect managed JRE symbolic link {}: {error}", source.display())+ })?;+ let link_target_after = fs::read_link(&source).map_err(|error| {+ format!("Failed to re-read managed JRE symbolic link {}: {error}", source.display())+ })?;+ let canonical_after = source.canonicalize().map_err(|error| {+ format!("Failed to re-resolve managed JRE symbolic link {}: {error}", source.display())+ })?;+ let opened_after = file.metadata().map_err(|error| {+ format!("Failed to re-inspect managed JRE symbolic link target {}: {error}", source.display())+ })?;+ let target_after = fs::metadata(&source).map_err(|error| {+ format!("Failed to re-inspect managed JRE symbolic link target {}: {error}", source.display())+ })?;+ if !link_metadata_after.file_type().is_symlink()+ || link_target_after != link_target+ || canonical_after != canonical_source+ || !canonical_after.starts_with(&canonical_root)+ || !same_opened_entry(&metadata, &link_metadata_after)+ || !same_opened_entry(&opened, &opened_after)+ || !same_opened_entry(&opened_after, &target_after)+ {+ return Err(format!(+ "Managed JRE symbolic link changed while it was being archived: {}",+ source.display()+ ));+ }+ continue;+ }+ let mut header = tar::Header::new_gnu();+ header.set_mtime(0);+ header.set_uid(0);+ header.set_gid(0);+ header.set_mode(metadata_mode(&metadata));+ if metadata.is_dir() {+ header.set_entry_type(tar::EntryType::Directory);+ header.set_size(0);+ header.set_cksum();+ archive+ .append_data(&mut header, &archive_path, std::io::empty())+ .map_err(|error| format!("Failed to archive managed JRE directory: {error}"))?;+ let mut children = Vec::new();+ for child in fs::read_dir(&source)+ .map_err(|error| format!("Failed to read managed JRE directory {}: {error}", source.display()))?+ {+ let child = child+ .map_err(|error| format!("Failed to read managed JRE directory {}: {error}", source.display()))?;+ entry_count = entry_count+ .checked_add(1)+ .ok_or_else(|| "Managed JRE entry count overflow during export".to_string())?;+ if entry_count > max_entry_count {+ return Err(format!("Managed JRE exceeds the export entry limit of {max_entry_count}"));+ }+ if depth + 1 > max_depth {+ return Err(format!("Managed JRE exceeds the export depth limit of {max_depth}"));+ }+ children.push(child);+ }+ let after = fs::symlink_metadata(&source)+ .map_err(|error| format!("Failed to re-inspect managed JRE directory {}: {error}", source.display()))?;+ if after.file_type().is_symlink() || !after.is_dir() || !same_opened_entry(&metadata, &after) {+ return Err(format!("Managed JRE directory changed while it was being archived: {}", source.display()));+ }+ let canonical_after = source+ .canonicalize()+ .map_err(|error| format!("Failed to re-resolve managed JRE directory {}: {error}", source.display()))?;+ if canonical_after != canonical_source || !canonical_after.starts_with(&canonical_root) {+ return Err(format!("Managed JRE directory changed while it was being archived: {}", source.display()));+ }+ children.sort_by_key(|entry| entry.file_name());+ for child in children.into_iter().rev() {+ stack.push((child.path(), archive_path.join(child.file_name()), depth + 1));+ }+ } else if metadata.is_file() {+ let file = File::open(&source)+ .map_err(|error| format!("Failed to open managed JRE entry {}: {error}", source.display()))?;+ let opened = file+ .metadata()+ .map_err(|error| format!("Failed to inspect opened managed JRE entry {}: {error}", source.display()))?;+ let after = fs::symlink_metadata(&source)+ .map_err(|error| format!("Failed to re-inspect managed JRE entry {}: {error}", source.display()))?;+ if !opened.is_file()+ || after.file_type().is_symlink()+ || !after.is_file()+ || !same_opened_entry(&metadata, &opened)+ || !same_opened_entry(&opened, &after)+ {+ return Err(format!("Managed JRE entry changed while it was being opened: {}", source.display()));+ }+ total_bytes = total_bytes+ .checked_add(opened.len())+ .ok_or_else(|| "Managed JRE size overflow during export".to_string())?;+ if total_bytes > max_uncompressed_bytes {+ return Err(format!("Managed JRE exceeds the export size limit of {max_uncompressed_bytes} bytes"));+ }+ header.set_entry_type(tar::EntryType::Regular);+ header.set_mode(metadata_mode(&opened));+ header.set_size(opened.len());+ header.set_cksum();+ let mut file = file;+ archive+ .append_data(&mut header, &archive_path, &mut file)+ .map_err(|error| format!("Failed to archive managed JRE entry {}: {error}", source.display()))?;+ let opened_after = file.metadata().map_err(|error| {+ format!("Failed to re-inspect opened managed JRE entry {}: {error}", source.display())+ })?;+ let path_after = fs::symlink_metadata(&source)+ .map_err(|error| format!("Failed to re-inspect managed JRE entry {}: {error}", source.display()))?;+ let canonical_after = source+ .canonicalize()+ .map_err(|error| format!("Failed to re-resolve managed JRE entry {}: {error}", source.display()))?;+ if path_after.file_type().is_symlink()+ || !path_after.is_file()+ || canonical_after != canonical_source+ || !canonical_after.starts_with(&canonical_root)+ || !same_opened_entry(&opened, &opened_after)+ || !same_opened_entry(&opened_after, &path_after)+ {+ return Err(format!("Managed JRE entry changed while it was being archived: {}", source.display()));+ }+ } else {+ return Err(format!("Managed JRE contains a special file: {}", source.display()));+ }+ }+ Ok(())+}++fn same_opened_entry(left: &Metadata, right: &Metadata) -> bool {+ same_opened_file(left, right)+ && match (left.modified(), right.modified()) {+ (Ok(left_modified), Ok(right_modified)) => left_modified == right_modified,+ _ => true,+ }+}++fn resolve_managed_jre_file_symlink(+ source: &Path,+ canonical_root: &Path,+) -> Result<(PathBuf, PathBuf, Metadata), String> {+ let link_target = fs::read_link(source)+ .map_err(|error| format!("Failed to read managed JRE symbolic link {}: {error}", source.display()))?;+ if link_target.is_absolute() {+ return Err(format!("Managed JRE contains an absolute symbolic link: {}", source.display()));+ }+ let parent = source+ .parent()+ .ok_or_else(|| format!("Managed JRE symbolic link has no parent directory: {}", source.display()))?;+ let resolved_target = parent+ .join(&link_target)+ .canonicalize()+ .map_err(|error| format!("Failed to resolve managed JRE symbolic link {}: {error}", source.display()))?;+ if !resolved_target.starts_with(canonical_root) {+ return Err(format!("Managed JRE symbolic link resolves outside the managed JRE root: {}", source.display()));+ }+ let target_metadata = fs::metadata(source)+ .map_err(|error| format!("Failed to inspect managed JRE symbolic link target {}: {error}", source.display()))?;+ if !target_metadata.is_file() {+ return Err(format!("Managed JRE symbolic link does not resolve to a regular file: {}", source.display()));+ }+ Ok((link_target, resolved_target, target_metadata))+}++fn validate_managed_jre_tree(am: &AgentManager, key: &str) -> Result<(usize, u64), String> {+ validate_offline_identifier(key, "JRE")?;+ let root = am.jre_dir(key);+ let root_metadata = fs::symlink_metadata(&root).map_err(|_| format!("Managed JRE {key} is not installed"))?;+ if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() {+ return Err(format!("Managed JRE {key} directory is not a regular managed directory"));+ }+ ensure_path_within_base(am, &root)?;+ let canonical_root =+ root.canonicalize().map_err(|error| format!("Failed to resolve managed JRE {key} directory: {error}"))?;++ let mut stack = vec![(root.clone(), 0usize)];+ let mut entry_count = 1usize;+ let mut total_bytes = 0u64;+ while let Some((path, depth)) = stack.pop() {+ if depth > MAX_JRE_DEPTH {+ return Err(format!("Managed JRE {key} exceeds the export depth limit"));+ }+ let metadata =+ fs::symlink_metadata(&path).map_err(|error| format!("Failed to inspect managed JRE {key}: {error}"))?;+ if metadata.file_type().is_symlink() {+ let (_, _, target_metadata) = resolve_managed_jre_file_symlink(&path, &canonical_root)?;+ total_bytes = total_bytes+ .checked_add(target_metadata.len())+ .ok_or_else(|| format!("Managed JRE {key} size overflow"))?;+ if total_bytes > MAX_JRE_UNCOMPRESSED_BYTES {+ return Err(format!("Managed JRE {key} exceeds the export size limit"));+ }+ continue;+ }+ if metadata.is_dir() {+ for child in fs::read_dir(&path).map_err(|error| format!("Failed to inspect managed JRE {key}: {error}"))? {+ let child = child.map_err(|error| format!("Failed to inspect managed JRE {key}: {error}"))?;+ entry_count =+ entry_count.checked_add(1).ok_or_else(|| format!("Managed JRE {key} entry count overflow"))?;+ if entry_count > MAX_JRE_ENTRY_COUNT {+ return Err(format!("Managed JRE {key} exceeds the export entry limit"));+ }+ if depth + 1 > MAX_JRE_DEPTH {+ return Err(format!("Managed JRE {key} exceeds the export depth limit"));+ }+ stack.push((child.path(), depth + 1));+ }+ } else if metadata.is_file() {+ total_bytes =+ total_bytes.checked_add(metadata.len()).ok_or_else(|| format!("Managed JRE {key} size overflow"))?;+ if total_bytes > MAX_JRE_UNCOMPRESSED_BYTES {+ return Err(format!("Managed JRE {key} exceeds the export size limit"));+ }+ } else {+ return Err(format!("Managed JRE {key} contains a special file"));+ }+ }+ let java_path = am.jre_java_path(key);+ let java_metadata = fs::symlink_metadata(&java_path)+ .map_err(|_| format!("Managed JRE {key} does not contain a Java executable"))?;+ if java_metadata.file_type().is_symlink() || !java_metadata.is_file() || java_metadata.len() == 0 {+ return Err(format!("Managed JRE {key} Java executable is invalid"));+ }+ Ok((entry_count, total_bytes))+}++#[cfg(unix)]+fn metadata_mode(metadata: &Metadata) -> u32 {+ use std::os::unix::fs::PermissionsExt;+ metadata.permissions().mode() & 0o7777+}++#[cfg(not(unix))]+fn metadata_mode(metadata: &Metadata) -> u32 {+ if metadata.is_dir() {+ 0o755+ } else {+ 0o644+ }+}++fn sha256_file(path: &Path) -> Result<String, String> {+ let mut file = File::open(path).map_err(|error| format!("Failed to hash {}: {error}", path.display()))?;+ let mut digest = Sha256::new();+ let mut buffer = [0u8; 64 * 1024];+ loop {+ let read = file.read(&mut buffer).map_err(|error| format!("Failed to hash {}: {error}", path.display()))?;+ if read == 0 {+ break;+ }+ digest.update(&buffer[..read]);+ }+ Ok(format!("{:x}", digest.finalize()))+}++fn unavailable_reason_label(reason: AgentOfflineExportUnavailableReason) -> &'static str {+ match reason {+ AgentOfflineExportUnavailableReason::UnmanagedInstall => "the artifact is not tracked as a DBX-managed install",+ AgentOfflineExportUnavailableReason::LocalInstall => "locally imported Agent builds are not redistributable",+ AgentOfflineExportUnavailableReason::LaunchConfig => "custom launch configurations are machine-local",+ AgentOfflineExportUnavailableReason::MissingArtifact => "the installed Agent artifact is missing",+ AgentOfflineExportUnavailableReason::InvalidArtifact => "the installed Agent artifact is invalid or corrupt",+ AgentOfflineExportUnavailableReason::UnsafeSource => {+ "the Agent artifact is outside the managed store or is a symbolic link"+ }+ AgentOfflineExportUnavailableReason::ExternalDriverRequired => {+ "the Agent requires an external user-provided driver and is excluded from offline export"+ }+ AgentOfflineExportUnavailableReason::MissingManagedJre => "the required DBX-managed JRE is not installed",+ AgentOfflineExportUnavailableReason::InvalidManagedJre => "the required DBX-managed JRE is invalid or unsafe",+ }+}++fn normalized_parent(path: &Path) -> Result<PathBuf, String> {+ let parent = path.parent().ok_or_else(|| "Export destination has no parent directory".to_string())?;+ if parent.as_os_str().is_empty() {+ Ok(PathBuf::from("."))+ } else {+ Ok(parent.to_path_buf())+ }+}++fn validate_export_destination(am: &AgentManager, destination: &Path, parent: &Path) -> Result<(), String> {+ validate_export_destination_name(destination)?;++ let managed_base =+ am.base_dir().canonicalize().map_err(|error| format!("Failed to resolve Agent store path: {error}"))?;+ let resolved_parent =+ parent.canonicalize().map_err(|error| format!("Failed to resolve export destination directory: {error}"))?;+ if resolved_parent.starts_with(&managed_base) {+ return Err("Offline Agent packages cannot be written inside the managed Agent store".to_string());+ }+ match fs::symlink_metadata(destination) {+ Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {+ return Err("Existing export destination must be a regular non-symbolic-link file".to_string());+ }+ Ok(_) => {+ let resolved_destination =+ destination.canonicalize().map_err(|error| format!("Failed to resolve export destination: {error}"))?;+ if resolved_destination.starts_with(&managed_base) {+ return Err("Offline Agent packages cannot replace files in the managed Agent store".to_string());+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(format!("Failed to inspect export destination: {error}")),+ }+ Ok(())+}++fn validate_export_destination_name(destination: &Path) -> Result<(), String> {+ let file_name = destination+ .file_name()+ .filter(|name| !name.is_empty())+ .ok_or_else(|| "Export destination must name a ZIP file".to_string())?;+ if file_name == "." || file_name == ".." {+ return Err("Export destination must name a ZIP file".to_string());+ }+ if !destination+ .extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| extension.eq_ignore_ascii_case("zip"))+ {+ return Err("Export destination must use the .zip extension".to_string());+ }+ Ok(())+}++fn safe_filename_token(value: &str) -> String {+ let token =+ value+ .chars()+ .map(|character| {+ if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {+ character+ } else {+ '_'+ }+ })+ .collect::<String>();+ if token.is_empty() {+ "unknown".to_string()+ } else {+ token+ }+}++fn validate_offline_identifier(value: &str, kind: &str) -> Result<(), String> {+ if value.is_empty()+ || matches!(value, "." | "..")+ || !value.chars().all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_'))+ {+ return Err(format!("Invalid {kind} identifier for offline export: {value}"));+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Cursor;++ use crate::agent_manager::{AgentRegistry, InstalledDriver};+ use crate::agent_service::import_agents_from_package;++ fn manager(root: &Path) -> AgentManager {+ AgentManager::new_with_base_dir_and_app_version(root.to_path_buf(), "9.9.9")+ }++ fn write_agent_jar(path: &Path, external_driver: bool) -> Vec<u8> {+ write_agent_jar_manifest(+ path,+ &format!(+ "Manifest-Version: 1.0\nMain-Class: com.example.Agent\n{}",+ if external_driver { "Agent-External-Driver: true\n" } else { "" }+ ),+ )+ }++ fn write_agent_jar_manifest(path: &Path, manifest: &str) -> Vec<u8> {+ let mut bytes = Cursor::new(Vec::new());+ {+ let mut archive = zip::ZipWriter::new(&mut bytes);+ archive.start_file("META-INF/MANIFEST.MF", SimpleFileOptions::default()).unwrap();+ archive.write_all(manifest.as_bytes()).unwrap();+ archive.finish().unwrap();+ }+ let bytes = bytes.into_inner();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, &bytes).unwrap();+ bytes+ }++ fn install_managed_jar(am: &AgentManager, db_type: &str, version: &str, jre_key: &str, external: bool) {+ write_agent_jar(&am.driver_jar_path(db_type), external);+ am.mutate_state(|state| {+ state.installed_drivers.insert(+ db_type.to_string(),+ InstalledDriver {+ version: version.to_string(),+ installed_at: "ignored".to_string(),+ jre: jre_key.to_string(),+ },+ );+ })+ .unwrap();+ }++ fn install_managed_jre(am: &AgentManager, key: &str, version: &str) {+ let java = am.jre_java_path(key);+ fs::create_dir_all(java.parent().unwrap()).unwrap();+ fs::write(&java, b"managed-java").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(&java, fs::Permissions::from_mode(0o755)).unwrap();+ }+ am.mutate_state(|state| {+ state.jre_versions.insert(key.to_string(), version.to_string());+ })+ .unwrap();+ }++ fn current_platform_native_binary() -> Vec<u8> {+ if cfg!(windows) {+ let mut bytes = vec![0_u8; 0x48];+ bytes[..2].copy_from_slice(b"MZ");+ bytes[0x3c..0x40].copy_from_slice(&(0x40_u32).to_le_bytes());+ bytes[0x40..0x44].copy_from_slice(b"PE\0\0");+ let machine = if cfg!(target_arch = "aarch64") { 0xaa64_u16 } else { 0x8664_u16 };+ bytes[0x44..0x46].copy_from_slice(&machine.to_le_bytes());+ bytes+ } else if cfg!(target_os = "linux") {+ let mut bytes = vec![0_u8; 20];+ bytes[..4].copy_from_slice(b"\x7fELF");+ bytes[4] = 2;+ bytes[5] = 1;+ let machine = if cfg!(target_arch = "aarch64") { 183_u16 } else { 62_u16 };+ bytes[18..20].copy_from_slice(&machine.to_le_bytes());+ bytes+ } else if cfg!(target_os = "macos") {+ let mut bytes = vec![0xcf, 0xfa, 0xed, 0xfe];+ let cpu_type = if cfg!(target_arch = "aarch64") { 0x0100_000c_u32 } else { 0x0100_0007_u32 };+ bytes.extend_from_slice(&cpu_type.to_le_bytes());+ bytes+ } else {+ Vec::new()+ }+ }++ fn install_managed_native(am: &AgentManager, db_type: &str, version: &str) -> Vec<u8> {+ let bytes = current_platform_native_binary();+ let path = am.driver_native_path(db_type);+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(&path, &bytes).unwrap();+ am.mutate_state(|state| {+ state.installed_drivers.insert(+ db_type.to_string(),+ InstalledDriver {+ version: version.to_string(),+ installed_at: "ignored".to_string(),+ jre: "21".to_string(),+ },+ );+ })+ .unwrap();+ bytes+ }++ fn candidate<'a>(preview: &'a AgentOfflineExportPreview, db_type: &str) -> &'a AgentOfflineExportCandidate {+ preview.candidates.iter().find(|candidate| candidate.db_type == db_type).unwrap()+ }++ #[test]+ fn preview_distinguishes_managed_local_external_and_launch_config_drivers() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(temp.path());+ install_managed_jre(&am, "21", "21.0.7");+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);+ install_managed_jar(&am, "kafka", "0.1.0-local", "21", false);+ install_managed_jar(&am, "rocketmq", "1.2.3", "21", true);+ fs::create_dir_all(am.driver_dir("rabbitmq")).unwrap();+ fs::write(am.driver_launch_config_path("rabbitmq"), b"{}").unwrap();+ am.mutate_state(|state| {+ state.installed_drivers.insert(+ "rabbitmq".to_string(),+ InstalledDriver {+ version: "1.2.3".to_string(),+ installed_at: "ignored".to_string(),+ jre: "21".to_string(),+ },+ );+ })+ .unwrap();++ let preview = preview_agent_offline_export(&am);+ assert!(candidate(&preview, "duckdb").eligible);+ assert_eq!(+ candidate(&preview, "kafka").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::LocalInstall)+ );+ assert_eq!(+ candidate(&preview, "rocketmq").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::ExternalDriverRequired)+ );+ assert_eq!(+ candidate(&preview, "rabbitmq").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::LaunchConfig)+ );+ }++ #[test]+ fn preview_requires_a_valid_managed_jre_for_java_agents() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(temp.path());+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);++ let preview = preview_agent_offline_export(&am);+ assert_eq!(+ candidate(&preview, "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::MissingManagedJre)+ );+ }++ #[test]+ fn preview_treats_an_empty_jre_key_as_missing_instead_of_panicking() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(temp.path());+ install_managed_jar(&am, "duckdb", "1.2.3", "", false);++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::MissingManagedJre)+ );+ }++ #[test]+ fn preview_detects_folded_external_driver_manifest_values() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(temp.path());+ install_managed_jre(&am, "21", "21.0.7");+ let path = am.driver_jar_path("duckdb");+ write_agent_jar_manifest(+ &path,+ "Manifest-Version: 1.0\r\nMain-Class: com.example.Agent\r\nAgent-External-Driver: tr\r\n ue\r\n",+ );+ am.mutate_state(|state| {+ state.installed_drivers.insert(+ "duckdb".to_string(),+ InstalledDriver {+ version: "1.2.3".to_string(),+ installed_at: "ignored".to_string(),+ jre: "21".to_string(),+ },+ );+ })+ .unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::ExternalDriverRequired)+ );+ }++ #[test]+ fn preview_rejects_a_jar_without_a_main_class_using_the_bounded_manifest_reader() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(temp.path());+ install_managed_jre(&am, "21", "21.0.7");+ let path = am.driver_jar_path("duckdb");+ write_agent_jar_manifest(&path, "Manifest-Version: 1.0\nImplementation-Title: Invalid Agent\n");+ am.mutate_state(|state| {+ state.installed_drivers.insert(+ "duckdb".to_string(),+ InstalledDriver {+ version: "1.2.3".to_string(),+ installed_at: "ignored".to_string(),+ jre: "21".to_string(),+ },+ );+ })+ .unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::InvalidArtifact)+ );+ }++ #[test]+ fn preview_prefers_the_current_platform_native_artifact_over_a_jar() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(temp.path());+ install_managed_jre(&am, "21", "21.0.7");+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);+ install_managed_native(&am, "duckdb", "1.2.3");++ let duckdb = candidate(&preview_agent_offline_export(&am), "duckdb").clone();+ assert!(duckdb.eligible);+ assert_eq!(duckdb.artifact_kind, Some(AgentOfflineArtifactKind::Native));+ assert_eq!(duckdb.required_jre, None);+ }++ #[cfg(unix)]+ #[test]+ fn preview_rejects_symlinked_managed_artifacts() {+ use std::os::unix::fs::symlink;++ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_jre(&am, "21", "21.0.7");+ let real = temp.path().join("outside.jar");+ write_agent_jar(&real, false);+ fs::create_dir_all(am.driver_dir("duckdb")).unwrap();+ symlink(&real, am.driver_jar_path("duckdb")).unwrap();+ am.mutate_state(|state| {+ state.installed_drivers.insert(+ "duckdb".to_string(),+ InstalledDriver {+ version: "1.2.3".to_string(),+ installed_at: "ignored".to_string(),+ jre: "21".to_string(),+ },+ );+ })+ .unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::UnsafeSource)+ );+ }++ #[tokio::test]+ async fn exported_package_round_trips_through_existing_importer_and_deduplicates_jre() {+ let temp = tempfile::tempdir().unwrap();+ let source = manager(&temp.path().join("source"));+ install_managed_jre(&source, "21", "21.0.7");+ let duckdb_bytes = write_agent_jar(&source.driver_jar_path("duckdb"), false);+ let kafka_bytes = write_agent_jar(&source.driver_jar_path("kafka"), false);+ source+ .mutate_state(|state| {+ state.jre_versions.insert("21".to_string(), "21.0.7".to_string());+ for db_type in ["duckdb", "kafka"] {+ state.installed_drivers.insert(+ db_type.to_string(),+ InstalledDriver {+ version: "1.2.3".to_string(),+ installed_at: "ignored".to_string(),+ jre: "21".to_string(),+ },+ );+ }+ })+ .unwrap();+ let package = temp.path().join("agents.zip");++ let result =+ export_agents_offline_unlocked(&source, &package, &["kafka".to_string(), "duckdb".to_string()]).unwrap();+ assert_eq!(result.driver_count, 2);+ assert_eq!(result.jre_count, 1);+ let plan = inspect_offline_package(&package).unwrap();+ assert_eq!(+ plan.driver_keys.into_iter().collect::<BTreeSet<_>>(),+ BTreeSet::from(["duckdb".to_string(), "kafka".to_string(),])+ );+ assert!(plan.includes_jre);++ let registry = {+ let file = File::open(&package).unwrap();+ let mut archive = zip::ZipArchive::new(file).unwrap();+ let mut entry = archive.by_name("agent-registry.json").unwrap();+ let mut bytes = Vec::new();+ entry.read_to_end(&mut bytes).unwrap();+ serde_json::from_slice::<AgentRegistry>(&bytes).unwrap()+ };+ assert!(registry.jre.is_none());+ assert_eq!(registry.jres.keys().cloned().collect::<BTreeSet<_>>(), BTreeSet::from(["21".to_string()]));+ assert_eq!(+ registry.drivers.keys().cloned().collect::<BTreeSet<_>>(),+ BTreeSet::from(["duckdb".to_string(), "kafka".to_string()])+ );+ let duckdb_artifact = registry.drivers["duckdb"].jar.as_ref().unwrap();+ assert_eq!(duckdb_artifact.url, "offline://dbx-agent-duckdb.jar");+ assert_eq!(duckdb_artifact.size, duckdb_bytes.len() as u64);+ assert_eq!(+ duckdb_artifact.sha256.as_deref(),+ Some(sha256_file(&source.driver_jar_path("duckdb")).unwrap().as_str())+ );+ let jre_artifact = ®istry.jres["21"].platforms[AgentManager::current_platform()];+ assert!(jre_artifact.url.starts_with("offline://dbx-jre-21-21.0.7-"));+ assert_eq!(jre_artifact.format, Some(ArtifactFormat::TarZstd));+ assert!(jre_artifact.size > 0);+ assert!(jre_artifact.sha256.as_ref().is_some_and(|sha| sha.len() == 64));++ let target = manager(&temp.path().join("target"));+ let imported = import_agents_from_package(&target, &package, |_| {}).await.unwrap();+ assert_eq!(+ imported.drivers_installed.into_iter().collect::<BTreeSet<_>>(),+ BTreeSet::from(["duckdb".to_string(), "kafka".to_string(),])+ );+ assert_eq!(fs::read(target.driver_jar_path("duckdb")).unwrap(), duckdb_bytes);+ assert_eq!(fs::read(target.driver_jar_path("kafka")).unwrap(), kafka_bytes);+ assert_eq!(fs::read(target.jre_java_path("21")).unwrap(), b"managed-java");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;++ assert_ne!(fs::metadata(target.jre_java_path("21")).unwrap().permissions().mode() & 0o111, 0);+ }++ let file = File::open(&package).unwrap();+ let mut archive = zip::ZipArchive::new(file).unwrap();+ let names =+ (0..archive.len()).map(|index| archive.by_index(index).unwrap().name().to_string()).collect::<Vec<_>>();+ assert_eq!(names.iter().filter(|name| name.starts_with("jre/")).count(), 1);+ assert!(!names.iter().any(|name| name.contains("state.json") || name.contains("agent-launch.json")));+ }++ #[tokio::test]+ async fn exported_native_package_round_trips_without_a_jre() {+ let temp = tempfile::tempdir().unwrap();+ let source = manager(&temp.path().join("source"));+ let native_bytes = install_managed_native(&source, "duckdb", "1.2.3");+ let package = temp.path().join("native-agents.zip");++ let result = export_agents_offline_unlocked(&source, &package, &["duckdb".to_string()]).unwrap();+ assert_eq!(result.driver_count, 1);+ assert_eq!(result.jre_count, 0);+ let plan = inspect_offline_package(&package).unwrap();+ assert_eq!(plan.driver_keys, vec!["duckdb"]);+ assert!(!plan.includes_jre);++ let target = manager(&temp.path().join("target"));+ let imported = import_agents_from_package(&target, &package, |_| {}).await.unwrap();+ assert_eq!(imported.drivers_installed, vec!["duckdb"]);+ assert_eq!(fs::read(target.driver_native_path("duckdb")).unwrap(), native_bytes);+ assert!(!target.driver_jar_path("duckdb").exists());+ }++ #[cfg(unix)]+ #[test]+ fn preview_rejects_a_managed_jre_symbolic_link_that_escapes_the_managed_root() {+ use std::os::unix::fs::symlink;++ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_jre(&am, "21", "21.0.7");+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);+ let outside = temp.path().join("outside.txt");+ fs::write(&outside, b"must-not-export").unwrap();+ symlink(&outside, am.jre_dir("21").join("unsafe-link")).unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::InvalidManagedJre)+ );+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn export_dereferences_safe_internal_jre_file_symlinks() {+ use std::os::unix::fs::symlink;++ let temp = tempfile::tempdir().unwrap();+ let source = manager(&temp.path().join("source"));+ install_managed_jre(&source, "21", "21.0.7");+ install_managed_jar(&source, "h2", "1.2.3", "21", false);+ let license = source.jre_dir("21").join("licenses/LICENSE");+ fs::create_dir_all(license.parent().unwrap()).unwrap();+ fs::write(&license, b"managed-license").unwrap();+ let linked_license = source.jre_dir("21").join("legal/LICENSE");+ fs::create_dir_all(linked_license.parent().unwrap()).unwrap();+ symlink("../licenses/LICENSE", &linked_license).unwrap();++ assert!(candidate(&preview_agent_offline_export_unlocked(&source), "h2").eligible);+ let package = temp.path().join("agents.zip");+ let result = export_agents_offline_unlocked(&source, &package, &["h2".to_string()]).unwrap();+ assert_eq!(result.driver_count, 1);+ assert_eq!(result.jre_count, 1);++ let target = manager(&temp.path().join("target"));+ import_agents_from_package(&target, &package, |_| {}).await.unwrap();+ let imported_license = target.jre_dir("21").join("legal/LICENSE");+ assert_eq!(fs::read(&imported_license).unwrap(), b"managed-license");+ assert!(!fs::symlink_metadata(imported_license).unwrap().file_type().is_symlink());+ }++ #[cfg(unix)]+ #[test]+ fn preview_rejects_a_managed_jre_containing_a_special_file() {+ use std::os::unix::net::UnixListener;++ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_jre(&am, "21", "21.0.7");+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);+ let _socket = UnixListener::bind(am.jre_dir("21").join("unsafe.sock")).unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::InvalidManagedJre)+ );+ }++ #[test]+ fn preview_rejects_a_managed_jre_exceeding_the_depth_limit() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_jre(&am, "21", "21.0.7");+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);+ let mut nested = am.jre_dir("21");+ for _ in 0..=MAX_JRE_DEPTH {+ nested.push("nested");+ }+ fs::create_dir_all(nested).unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::InvalidManagedJre)+ );+ }++ #[test]+ fn preview_rejects_a_managed_jre_exceeding_the_size_limit() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_jre(&am, "21", "21.0.7");+ install_managed_jar(&am, "duckdb", "1.2.3", "21", false);+ let oversized = File::create(am.jre_dir("21").join("oversized.bin")).unwrap();+ oversized.set_len(MAX_JRE_UNCOMPRESSED_BYTES + 1).unwrap();++ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::InvalidManagedJre)+ );+ }++ #[test]+ fn jre_archive_enforces_the_entry_count_limit() {+ let temp = tempfile::tempdir().unwrap();+ let source = temp.path().join("jre");+ fs::create_dir(&source).unwrap();+ fs::write(source.join("first"), b"first").unwrap();+ fs::write(source.join("second"), b"second").unwrap();+ let mut bytes = Vec::new();+ let mut archive = tar::Builder::new(&mut bytes);++ let error = append_jre_tree_with_limits(+ &mut archive,+ &source,+ Path::new("dbx-jre-test"),+ 2,+ MAX_JRE_DEPTH,+ MAX_JRE_UNCOMPRESSED_BYTES,+ )+ .unwrap_err();++ assert!(error.contains("entry limit of 2"), "unexpected error: {error}");+ }++ #[test]+ fn stale_preview_is_revalidated_before_export_without_leaving_partial_files() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_native(&am, "duckdb", "1.2.3");+ assert!(candidate(&preview_agent_offline_export(&am), "duckdb").eligible);+ fs::remove_file(am.driver_native_path("duckdb")).unwrap();+ assert_eq!(+ candidate(&preview_agent_offline_export(&am), "duckdb").unavailable_reason,+ Some(AgentOfflineExportUnavailableReason::MissingArtifact)+ );+ let destination = temp.path().join("stale.zip");++ let error = export_agents_offline_unlocked(&am, &destination, &["duckdb".to_string()]).unwrap_err();+ assert!(error.contains("cannot be exported"), "unexpected error: {error}");+ assert!(!destination.exists());+ assert!(!fs::read_dir(temp.path())+ .unwrap()+ .filter_map(Result::ok)+ .any(|entry| entry.file_name().to_string_lossy().contains(".partial-")));+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn export_waits_for_an_in_flight_installation_operation() {+ let temp = tempfile::tempdir().unwrap();+ let am = std::sync::Arc::new(manager(&temp.path().join("agents")));+ install_managed_native(&am, "duckdb", "1.2.3");+ let install_guard = am.installation_operation_lock.read().await;+ let export_manager = std::sync::Arc::clone(&am);+ let destination = temp.path().join("waited.zip");+ let mut export = tokio::task::spawn_blocking(move || {+ export_agents_offline(&export_manager, &destination, &["duckdb".to_string()])+ });++ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(50), &mut export).await.is_err(),+ "export entered while another installation operation held the snapshot lock"+ );+ drop(install_guard);++ let result = tokio::time::timeout(std::time::Duration::from_secs(2), export)+ .await+ .expect("export did not resume after the installation operation finished")+ .expect("export worker panicked")+ .expect("export failed after the installation operation finished");+ assert_eq!(result.driver_count, 1);+ }++ #[test]+ fn failed_export_preserves_existing_destination() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ let destination = temp.path().join("existing.zip");+ fs::write(&destination, b"keep-me").unwrap();++ let error = export_agents_offline_unlocked(&am, &destination, &["missing".to_string()]).unwrap_err();+ assert!(error.contains("not installed"));+ assert_eq!(fs::read(destination).unwrap(), b"keep-me");+ }++ #[test]+ fn late_validation_failure_removes_partial_file_and_preserves_destination() {+ let temp = tempfile::tempdir().unwrap();+ let destination = temp.path().join("existing.zip");+ fs::write(&destination, b"keep-me").unwrap();+ let partial = temp.path().join(".existing.zip.partial-test");++ let error = write_and_finalize_export_zip(&partial, &destination, br#"{"drivers":{}}"#, &[], &[], |_| {+ Err("forced compatibility failure".to_string())+ })+ .unwrap_err();++ assert_eq!(error, "forced compatibility failure");+ assert!(!partial.exists());+ assert_eq!(fs::read(destination).unwrap(), b"keep-me");+ }++ #[test]+ fn successful_export_replaces_an_existing_destination() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_native(&am, "duckdb", "1.2.3");+ let destination = temp.path().join("existing.zip");+ fs::write(&destination, b"replace-me").unwrap();++ let result = export_agents_offline_unlocked(&am, &destination, &["duckdb".to_string()]).unwrap();+ assert_eq!(result.driver_count, 1);+ assert_ne!(fs::read(&destination).unwrap(), b"replace-me");+ assert_eq!(inspect_offline_package(&destination).unwrap().driver_keys, vec!["duckdb"]);+ }++ #[test]+ fn export_rejects_a_non_zip_destination_before_creating_its_parent() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_native(&am, "duckdb", "1.2.3");+ let parent = temp.path().join("new-directory");+ let destination = parent.join("agents.tar.zst");++ let error = export_agents_offline_unlocked(&am, &destination, &["duckdb".to_string()]).unwrap_err();+ assert!(error.contains(".zip extension"), "unexpected error: {error}");+ assert!(!parent.exists());+ }++ #[test]+ fn export_rejects_an_existing_directory_without_moving_it() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_native(&am, "duckdb", "1.2.3");+ let destination = temp.path().join("existing.zip");+ fs::create_dir(&destination).unwrap();+ fs::write(destination.join("sentinel"), b"keep-me").unwrap();++ let error = export_agents_offline_unlocked(&am, &destination, &["duckdb".to_string()]).unwrap_err();+ assert!(error.contains("regular non-symbolic-link file"), "unexpected error: {error}");+ assert_eq!(fs::read(destination.join("sentinel")).unwrap(), b"keep-me");+ }++ #[cfg(unix)]+ #[test]+ fn export_rejects_an_existing_symlink_without_changing_its_target() {+ use std::os::unix::fs::symlink;++ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_native(&am, "duckdb", "1.2.3");+ let target = temp.path().join("target.zip");+ fs::write(&target, b"keep-me").unwrap();+ let destination = temp.path().join("existing.zip");+ symlink(&target, &destination).unwrap();++ let error = export_agents_offline_unlocked(&am, &destination, &["duckdb".to_string()]).unwrap_err();+ assert!(error.contains("regular non-symbolic-link file"), "unexpected error: {error}");+ assert_eq!(fs::read(&target).unwrap(), b"keep-me");+ assert!(fs::symlink_metadata(&destination).unwrap().file_type().is_symlink());+ }++ #[test]+ fn export_rejects_an_empty_selection_without_creating_a_destination() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ let destination = temp.path().join("empty.zip");++ let error = export_agents_offline_unlocked(&am, &destination, &[]).unwrap_err();+ assert!(error.contains("Select at least one"));+ assert!(!destination.exists());+ }++ #[test]+ fn export_rejects_a_destination_inside_the_managed_agent_store() {+ let temp = tempfile::tempdir().unwrap();+ let am = manager(&temp.path().join("agents"));+ install_managed_native(&am, "duckdb", "1.2.3");+ let destination = am.base_dir().join("must-not-overwrite.zip");++ let error = export_agents_offline_unlocked(&am, &destination, &["duckdb".to_string()]).unwrap_err();+ assert!(error.contains("managed Agent store"), "unexpected error: {error}");+ assert!(!destination.exists());+ }++ #[test]+ fn preview_contract_uses_camel_case_values() {+ let value = serde_json::to_value(AgentOfflineExportCandidate {+ db_type: "duckdb".to_string(),+ label: "DuckDB".to_string(),+ version: "1".to_string(),+ size: 1,+ artifact_kind: Some(AgentOfflineArtifactKind::Jar),+ required_jre: Some("21".to_string()),+ eligible: false,+ unavailable_reason: Some(AgentOfflineExportUnavailableReason::ExternalDriverRequired),+ })+ .unwrap();+ assert_eq!(value["dbType"], "duckdb");+ assert_eq!(value["artifactKind"], "jar");+ assert_eq!(value["unavailableReason"], "externalDriverRequired");++ let preview = serde_json::to_value(AgentOfflineExportPreview {+ platform: "linux-x64".to_string(),+ candidates: Vec::new(),+ })+ .unwrap();+ assert_eq!(preview["platform"], "linux-x64");+ assert!(preview["candidates"].as_array().unwrap().is_empty());++ let result = serde_json::to_value(AgentOfflineExportResult {+ platform: "linux-x64".to_string(),+ driver_count: 2,+ jre_count: 1,+ bytes: 42,+ })+ .unwrap();+ assert_eq!(result["driverCount"], 2);+ assert_eq!(result["jreCount"], 1);+ assert_eq!(result["bytes"], 42);+ }+}diff --git a/crates/dbx-core/src/agent_service.rs b/crates/dbx-core/src/agent_service.rsindex 7f3d9172a4..30bda3ad7d 100644--- a/crates/dbx-core/src/agent_service.rs+++ b/crates/dbx-core/src/agent_service.rs@@ -9,8 +9,8 @@ use sha2::{Digest, Sha256};use crate::agent_catalog;use crate::agent_manager::{- AgentDriverInfo, AgentInstallCancellation, AgentManager, AgentRegistry, ArtifactFormat, InstalledDriver,- JavaRuntimeMode, OperationLockHandle, DEFAULT_JRE_KEY,+ AgentDriverInfo, AgentInstallCancellation, AgentManager, AgentRegistry, ArtifactFormat, ArtifactInfo,+ InstalledDriver, JavaRuntimeMode, OperationLockHandle, DEFAULT_JRE_KEY,};use crate::DownloadSource;@@ -2431,6 +2431,7 @@ pub fn inspect_offline_zip(zip_path: &Path) -> Result<OfflineImportPlan, String>let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP file: {e}"))?;let registry = read_registry_from_zip(&mut archive)?;let (jre_entries, driver_entries) = collect_offline_entries(&mut archive, ®istry)?;+ validate_offline_zip_preflight(&mut archive, ®istry, &jre_entries, &driver_entries)?;Ok(OfflineImportPlan {driver_keys: driver_entries.into_iter().map(|(db_type, _, _)| db_type).collect(),includes_jre: !jre_entries.is_empty(),@@ -2453,18 +2454,18 @@ pub async fn import_offline_zip(let registry = read_registry_from_zip(&mut archive)?;let platform = AgentManager::current_platform();- std::fs::create_dir_all(am.base_dir()).map_err(|e| format!("Failed to create agent directory: {e}"))?;- let mut local_state = am.load_state();- let mut result =- OfflineImportResult { jre_installed: Vec::new(), drivers_installed: Vec::new(), drivers_skipped: Vec::new() };-let (jre_entries, driver_entries) = collect_offline_entries(&mut archive, ®istry)?;let total = (jre_entries.len() + driver_entries.len()) as u32;if total == 0 {return Err(format!("Offline package contains no drivers compatible with platform: {platform}"));}+ validate_offline_zip_preflight(&mut archive, ®istry, &jre_entries, &driver_entries)?;+ std::fs::create_dir_all(am.base_dir()).map_err(|e| format!("Failed to create agent directory: {e}"))?;validate_offline_driver_entries(am, &mut archive, &driver_entries)?;+ let mut local_state = am.load_state();+ let mut result =+ OfflineImportResult { jre_installed: Vec::new(), drivers_installed: Vec::new(), drivers_skipped: Vec::new() };let mut current: u32 = 0;for (jre_key, entry_name, format) in &jre_entries {@@ -2614,7 +2615,7 @@ fn collect_offline_entries(return Err(format!("Offline package contains an unsafe path: {}", entry.name()));};let name = path.to_string_lossy().replace('\\', "/");- if name.starts_with("jre/") && name.contains(platform) {+ if name.starts_with("jre/") {let jre_format = if name.ends_with(".tar.zst") {Some(ArtifactFormat::TarZstd)} else if name.ends_with(".tar.gz") {@@ -2622,8 +2623,11 @@ fn collect_offline_entries(} else {continue;};- let jre_key = extract_jre_key_from_filename(&name)- .ok_or_else(|| format!("Invalid JRE filename in offline package: {name}"))?;+ let Some(jre_key) = jre_key_for_offline_entry(registry, platform, &name)+ .or_else(|| name.contains(platform).then(|| extract_jre_key_from_filename(&name)).flatten())+ else {+ continue;+ };validate_offline_identifier(&jre_key, "JRE")?;let replace = !jres.contains_key(&jre_key) || jre_format == Some(ArtifactFormat::TarZstd);if replace {@@ -2651,6 +2655,105 @@ fn collect_offline_entries())}+fn validate_offline_zip_preflight(+ archive: &mut zip::ZipArchive<std::fs::File>,+ registry: &AgentRegistry,+ jre_entries: &[OfflineJreEntry],+ driver_entries: &[OfflineDriverEntry],+) -> Result<(), String> {+ let platform = AgentManager::current_platform();+ let has_jre_artifact_metadata =+ registry.jre.iter().chain(registry.jres.values()).any(|jre| !jre.platforms.is_empty());+ let packaged_jres = jre_entries.iter().map(|(key, _, _)| key.as_str()).collect::<std::collections::BTreeSet<_>>();++ for (jre_key, entry_name, format) in jre_entries {+ if let Some(artifact) = registry.resolve_jre(jre_key).and_then(|jre| jre.platforms.get(platform)) {+ if artifact.format != *format {+ return Err(format!("Offline JRE {jre_key} archive format does not match its registry metadata"));+ }+ validate_offline_zip_artifact(archive, entry_name, artifact, &format!("JRE {jre_key}"))?;+ }+ }++ for (db_type, entry_name, is_native) in driver_entries {+ let Some(driver) = registry.drivers.get(db_type) else {+ // Older locally assembled ZIPs can identify a JAR solely from its+ // canonical filename. Preserve that import path when no registry+ // artifact metadata exists to validate.+ continue;+ };+ let artifact = if *is_native {+ driver.native.get(platform)+ } else {+ let jre_key = driver.jre.trim();+ if !jre_key.is_empty() {+ if let Some(jre) = registry.resolve_jre(jre_key) {+ if !jre.platforms.is_empty() && !jre.platforms.contains_key(platform) {+ return Err(format!(+ "Offline Java driver {db_type} requires JRE {jre_key}, which does not support the current platform: {platform}"+ ));+ }+ if !jre.platforms.is_empty() && !packaged_jres.contains(jre_key) {+ return Err(format!(+ "Offline Java driver {db_type} requires JRE {jre_key}, but the current-platform JRE artifact is missing"+ ));+ }+ } else if has_jre_artifact_metadata {+ return Err(format!(+ "Offline Java driver {db_type} requires JRE {jre_key}, but that JRE is missing from the package registry"+ ));+ }+ }+ driver.jar.as_ref()+ };+ if let Some(artifact) = artifact {+ validate_offline_zip_artifact(archive, entry_name, artifact, &format!("driver {db_type}"))?;+ }+ }+ Ok(())+}++fn validate_offline_zip_artifact(+ archive: &mut zip::ZipArchive<std::fs::File>,+ entry_name: &str,+ artifact: &ArtifactInfo,+ label: &str,+) -> Result<(), String> {+ let mut entry = archive+ .by_name(entry_name)+ .map_err(|error| format!("Failed to read offline {label} artifact {entry_name}: {error}"))?;+ if !entry.is_file() {+ return Err(format!("Offline {label} artifact is not a regular file: {entry_name}"));+ }+ if artifact.size > 0 && entry.size() != artifact.size {+ return Err(format!(+ "Offline {label} artifact size mismatch: expected {} bytes, got {} bytes",+ artifact.size,+ entry.size()+ ));+ }+ let Some(expected_sha256) = normalized_sha256(artifact.sha256.as_deref())? else {+ return Ok(());+ };+ let mut digest = Sha256::new();+ let mut buffer = [0u8; 64 * 1024];+ loop {+ let read = entry+ .read(&mut buffer)+ .map_err(|error| format!("Failed to hash offline {label} artifact {entry_name}: {error}"))?;+ if read == 0 {+ break;+ }+ digest.update(&buffer[..read]);+ }+ let actual_sha256 = format!("{:x}", digest.finalize());+ if actual_sha256.eq_ignore_ascii_case(expected_sha256) {+ Ok(())+ } else {+ Err(format!("Offline {label} artifact SHA-256 mismatch: expected {expected_sha256}, got {actual_sha256}"))+ }+}+fn validate_offline_driver_entries(am: &AgentManager,archive: &mut zip::ZipArchive<std::fs::File>,@@ -2714,6 +2817,24 @@ fn extract_jre_key_from_filename(name: &str) -> Option<String> {Some(key.to_string())}+fn jre_key_for_offline_entry(registry: &AgentRegistry, platform: &str, name: &str) -> Option<String> {+ let filename = name.rsplit('/').next()?;+ let registry_match = registry.jres.iter().find_map(|(key, jre)| {+ let artifact = jre.platforms.get(platform)?;+ (artifact.url.rsplit('/').next()? == filename).then(|| key.clone())+ });+ if registry_match.is_some() {+ return registry_match;+ }+ if registry.jres.is_empty() {+ let artifact = registry.jre.as_ref()?.platforms.get(platform)?;+ if artifact.url.rsplit('/').next()? == filename {+ return Some(DEFAULT_JRE_KEY.to_string());+ }+ }+ None+}+fn extract_db_type_from_filename(name: &str) -> Option<String> {let filename = name.rsplit('/').next()?;let rest = filename.strip_prefix("dbx-agent-")?;@@ -2967,7 +3088,7 @@ fn jre_dir_contains_java(path: &Path) -> bool {|| path.join("Contents").join("Home").join("bin").join(java_name).is_file()}-fn validate_native_agent_binary(path: &Path) -> Result<(), String> {+pub(crate) fn validate_native_agent_binary(path: &Path) -> Result<(), String> {let mut file = std::fs::File::open(path).map_err(|e| format!("Failed to read native agent: {e}"))?;let mut magic = [0_u8; 4];file.read_exact(&mut magic).map_err(|e| format!("Failed to read native agent header: {e}"))?;@@ -3298,6 +3419,28 @@ mod agent_registry_install_tests {bytes.into_inner()}+ fn sha256_bytes(bytes: &[u8]) -> String {+ format!("{:x}", Sha256::digest(bytes))+ }++ fn write_offline_zip(registry: &AgentRegistry, entries: &[(String, Vec<u8>)]) -> (tempfile::TempDir, PathBuf) {+ use std::io::Write;++ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("agents.zip");+ let file = std::fs::File::create(&path).unwrap();+ let mut archive = zip::ZipWriter::new(file);+ let options = zip::write::SimpleFileOptions::default();+ archive.start_file("agent-registry.json", options).unwrap();+ archive.write_all(&serde_json::to_vec(registry).unwrap()).unwrap();+ for (name, bytes) in entries {+ archive.start_file(name, options).unwrap();+ archive.write_all(bytes).unwrap();+ }+ archive.finish().unwrap();+ (temp, path)+ }+fn build_tar_zstd_driver_package(db_type: &str,version: &str,@@ -4883,6 +5026,266 @@ mod agent_registry_install_tests {assert!(!manager.load_state().installed_drivers.contains_key(db_type));}+ #[tokio::test]+ async fn offline_zip_rejects_a_cross_platform_java_dependency_before_install_changes() {+ let platform = AgentManager::current_platform();+ let foreign_platform = if platform == "linux-x64" { "macos-x64" } else { "linux-x64" };+ let jre_key = "temurin-21";+ let jar_name = "dbx-agent-h2.jar";+ let jre_name = format!("dbx-jre-{jre_key}-{foreign_platform}.tar.gz");+ let jar_bytes = test_agent_jar();+ let jre_bytes = b"foreign-jre".to_vec();+ let registry = AgentRegistry {+ jre: None,+ jres: [(+ jre_key.to_string(),+ JreInfo {+ version: "21.0.7".to_string(),+ platforms: [(+ foreign_platform.to_string(),+ ArtifactInfo {+ url: format!("offline://{jre_name}"),+ sha256: Some(sha256_bytes(&jre_bytes)),+ size: jre_bytes.len() as u64,+ format: None,+ },+ )]+ .into_iter()+ .collect(),+ },+ )]+ .into_iter()+ .collect(),+ drivers: [(+ "h2".to_string(),+ DriverInfo {+ version: "1.0.0".to_string(),+ label: "H2".to_string(),+ min_app_version: "0.1.0".to_string(),+ jar: Some(ArtifactInfo {+ url: format!("offline://{jar_name}"),+ sha256: Some(sha256_bytes(&jar_bytes)),+ size: jar_bytes.len() as u64,+ format: None,+ }),+ native: std::collections::HashMap::new(),+ jre: jre_key.to_string(),+ },+ )]+ .into_iter()+ .collect(),+ };+ let (_package_dir, package) = write_offline_zip(+ ®istry,+ &[(format!("drivers/{jar_name}"), jar_bytes), (format!("jre/{jre_name}"), jre_bytes)],+ );++ let inspect_error = inspect_offline_zip(&package).unwrap_err();+ assert!(inspect_error.contains("does not support the current platform"), "unexpected error: {inspect_error}");++ let manager = test_manager("offline-cross-platform-java");+ let existing_jar = manager.driver_jar_path("h2");+ std::fs::create_dir_all(existing_jar.parent().unwrap()).unwrap();+ std::fs::write(&existing_jar, b"existing-driver").unwrap();+ manager+ .mutate_state(|state| {+ state.installed_drivers.insert(+ "h2".to_string(),+ InstalledDriver {+ version: "9.9.9".to_string(),+ installed_at: "before".to_string(),+ jre: jre_key.to_string(),+ },+ );+ })+ .unwrap();++ let import_error = import_offline_zip(&manager, &package, |_| {}).await.unwrap_err();+ assert!(import_error.contains("does not support the current platform"), "unexpected error: {import_error}");+ assert_eq!(std::fs::read(existing_jar).unwrap(), b"existing-driver");+ assert_eq!(manager.load_state().installed_drivers["h2"].version, "9.9.9");+ assert!(!manager.jre_dir(jre_key).exists());+ }++ #[test]+ fn offline_zip_rejects_a_java_dependency_missing_from_a_registry_with_jre_metadata() {+ let platform = AgentManager::current_platform();+ let jar_name = "dbx-agent-h2.jar";+ let jar_bytes = test_agent_jar();+ let unrelated_jre_name = format!("dbx-jre-temurin-17-{platform}.tar.gz");+ let unrelated_jre_bytes = b"unrelated-jre".to_vec();+ let registry = AgentRegistry {+ jre: None,+ jres: [(+ "temurin-17".to_string(),+ JreInfo {+ version: "17.0.15".to_string(),+ platforms: [(+ platform.to_string(),+ ArtifactInfo {+ url: format!("offline://{unrelated_jre_name}"),+ sha256: Some(sha256_bytes(&unrelated_jre_bytes)),+ size: unrelated_jre_bytes.len() as u64,+ format: None,+ },+ )]+ .into_iter()+ .collect(),+ },+ )]+ .into_iter()+ .collect(),+ drivers: [(+ "h2".to_string(),+ DriverInfo {+ version: "1.0.0".to_string(),+ label: "H2".to_string(),+ min_app_version: "0.1.0".to_string(),+ jar: Some(ArtifactInfo {+ url: format!("offline://{jar_name}"),+ sha256: Some(sha256_bytes(&jar_bytes)),+ size: jar_bytes.len() as u64,+ format: None,+ }),+ native: std::collections::HashMap::new(),+ jre: "temurin-21".to_string(),+ },+ )]+ .into_iter()+ .collect(),+ };+ let (_package_dir, package) = write_offline_zip(+ ®istry,+ &[(format!("drivers/{jar_name}"), jar_bytes), (format!("jre/{unrelated_jre_name}"), unrelated_jre_bytes)],+ );++ let error = inspect_offline_zip(&package).unwrap_err();+ assert!(error.contains("missing from the package registry"), "unexpected error: {error}");+ }++ #[test]+ fn offline_zip_rejects_registry_size_and_sha256_tampering() {+ let platform = AgentManager::current_platform();+ let entry_name = format!("dbx-agent-h2-{platform}");+ let original = b"native-bytes".to_vec();+ let tampered = b"native-byteS".to_vec();+ assert_eq!(original.len(), tampered.len());++ let registry_with = |size, sha256: String| AgentRegistry {+ jre: None,+ jres: std::collections::HashMap::new(),+ drivers: [(+ "h2".to_string(),+ DriverInfo {+ version: "1.0.0".to_string(),+ label: "H2".to_string(),+ min_app_version: "0.1.0".to_string(),+ jar: None,+ native: [(+ platform.to_string(),+ ArtifactInfo {+ url: format!("offline://{entry_name}"),+ sha256: Some(sha256),+ size,+ format: None,+ },+ )]+ .into_iter()+ .collect(),+ jre: DEFAULT_JRE_KEY.to_string(),+ },+ )]+ .into_iter()+ .collect(),+ };++ let size_registry = registry_with((original.len() + 1) as u64, sha256_bytes(&original));+ let (_size_dir, size_package) =+ write_offline_zip(&size_registry, &[(format!("drivers/{entry_name}"), original.clone())]);+ let size_error = inspect_offline_zip(&size_package).unwrap_err();+ assert!(size_error.contains("size mismatch"), "unexpected error: {size_error}");++ let sha_registry = registry_with(original.len() as u64, sha256_bytes(&original));+ let (_sha_dir, sha_package) = write_offline_zip(&sha_registry, &[(format!("drivers/{entry_name}"), tampered)]);+ let sha_error = inspect_offline_zip(&sha_package).unwrap_err();+ assert!(sha_error.contains("SHA-256 mismatch"), "unexpected error: {sha_error}");+ }++ #[test]+ fn offline_zip_resolves_a_hyphenated_jre_key_from_the_registry_basename() {+ let platform = AgentManager::current_platform();+ let jre_key = "temurin-21";+ let jar_name = "dbx-agent-h2.jar";+ let jre_name = format!("dbx-jre-{jre_key}-21.0.7-{platform}.tar.gz");+ let jar_bytes = test_agent_jar();+ let jre_bytes = b"current-jre".to_vec();+ let registry = AgentRegistry {+ jre: None,+ jres: [(+ jre_key.to_string(),+ JreInfo {+ version: "21.0.7".to_string(),+ platforms: [(+ platform.to_string(),+ ArtifactInfo {+ url: format!("offline://{jre_name}"),+ sha256: Some(sha256_bytes(&jre_bytes)),+ size: jre_bytes.len() as u64,+ format: None,+ },+ )]+ .into_iter()+ .collect(),+ },+ )]+ .into_iter()+ .collect(),+ drivers: [(+ "h2".to_string(),+ DriverInfo {+ version: "1.0.0".to_string(),+ label: "H2".to_string(),+ min_app_version: "0.1.0".to_string(),+ jar: Some(ArtifactInfo {+ url: format!("offline://{jar_name}"),+ sha256: Some(sha256_bytes(&jar_bytes)),+ size: jar_bytes.len() as u64,+ format: None,+ }),+ native: std::collections::HashMap::new(),+ jre: jre_key.to_string(),+ },+ )]+ .into_iter()+ .collect(),+ };+ let (_package_dir, package) = write_offline_zip(+ ®istry,+ &[(format!("drivers/{jar_name}"), jar_bytes), (format!("jre/{jre_name}"), jre_bytes)],+ );++ let plan = inspect_offline_zip(&package).unwrap();+ assert_eq!(plan.driver_keys, vec!["h2"]);+ assert!(plan.includes_jre);+ }++ #[test]+ fn offline_zip_keeps_legacy_jar_and_jre_entries_compatible_without_integrity_metadata() {+ let platform = AgentManager::current_platform();+ let jar_name = "dbx-agent-h2.jar";+ let jre_name = format!("jre-21-{platform}.tar.gz");+ let jar_bytes = test_agent_jar();+ let registry = registry_with_jar("h2", "1.0.0", &format!("offline://{jar_name}"), jar_bytes.len() as u64);+ let (_package_dir, package) = write_offline_zip(+ ®istry,+ &[(format!("drivers/{jar_name}"), jar_bytes), (format!("jre/{jre_name}"), b"legacy-jre".to_vec())],+ );++ let plan = inspect_offline_zip(&package).unwrap();+ assert_eq!(plan.driver_keys, vec!["h2"]);+ assert!(plan.includes_jre);+ }+#[tokio::test]async fn offline_import_exclusive_lock_waits_for_in_flight_driver_operation() {let manager = test_manager("offline-import-lock");diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex 517b402579..851bd96e8e 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -7,6 +7,7 @@ pub mod agent_explain;pub mod agent_kv;pub mod agent_loop;pub mod agent_manager;+pub mod agent_offline_export;pub mod agent_recovery;pub mod agent_runtime;pub mod agent_service;diff --git a/src-tauri/src/commands/agents.rs b/src-tauri/src/commands/agents.rsindex ac322e778a..65240f735a 100644--- a/src-tauri/src/commands/agents.rs+++ b/src-tauri/src/commands/agents.rs@@ -3,6 +3,11 @@ use std::sync::Arc;use tauri::{Emitter, State};use dbx_core::agent_manager::{AgentDriverInfo, DriverStoreUsage, JavaRuntimeConfig, JavaRuntimeMode, DEFAULT_JRE_KEY};+use dbx_core::agent_offline_export::{+ export_agents_offline as export_agents_offline_core,+ preview_agent_offline_export as preview_agent_offline_export_core, AgentOfflineExportPreview,+ AgentOfflineExportResult,+};use dbx_core::agent_service::{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,@@ -231,6 +236,38 @@ pub async fn import_agents_from_zip(Ok(count)}+#[tauri::command]+pub async fn preview_agent_offline_export(+ state: State<'_, Arc<AppState>>,+) -> Result<AgentOfflineExportPreview, String> {+ let state = Arc::clone(state.inner());+ run_blocking_agent_task("Failed to prepare the offline Agent export preview", move || {+ Ok(preview_agent_offline_export_core(&state.agent_manager))+ })+ .await+}++#[tauri::command]+pub async fn export_agents_offline(+ state: State<'_, Arc<AppState>>,+ path: String,+ driver_keys: Vec<String>,+) -> Result<AgentOfflineExportResult, String> {+ let state = Arc::clone(state.inner());+ run_blocking_agent_task("Failed to run the offline Agent export task", move || {+ export_agents_offline_core(&state.agent_manager, std::path::Path::new(&path), &driver_keys)+ })+ .await+}++async fn run_blocking_agent_task<T, F>(context: &'static str, task: F) -> Result<T, String>+where+ T: Send + 'static,+ F: FnOnce() -> Result<T, String> + Send + 'static,+{+ tauri::async_runtime::spawn_blocking(task).await.map_err(|error| format!("{context}: {error}"))?+}+#[tauri::command]pub async fn import_agent_driver_cmd(state: State<'_, Arc<AppState>>,@@ -317,3 +354,34 @@ fn update_blockers_from_keys(blockers.sort_by(|left, right| left.label.cmp(&right.label));blockers}++#[cfg(test)]+mod tests {+ use super::run_blocking_agent_task;++ #[tokio::test]+ async fn blocking_agent_task_returns_successful_value() {+ let result = run_blocking_agent_task("agent task failed", || Ok::<_, String>(42)).await;++ assert_eq!(result.unwrap(), 42);+ }++ #[tokio::test]+ async fn blocking_agent_task_preserves_core_error() {+ let result = run_blocking_agent_task("agent task failed", || Err::<(), _>("core failure".to_string())).await;++ assert_eq!(result.unwrap_err(), "core failure");+ }++ #[tokio::test]+ async fn blocking_agent_task_maps_join_error_with_context() {+ let result = run_blocking_agent_task("agent task failed", || -> Result<(), String> {+ panic!("worker panic");+ })+ .await;++ let error = result.unwrap_err();+ assert!(error.starts_with("agent task failed:"), "unexpected error: {error}");+ assert!(error.contains("panicked"), "unexpected error: {error}");+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 44aebaa8d8..b1ca3451df 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -2306,6 +2306,8 @@ pub fn run() {commands::agents::reinstall_jre,commands::agents::invalidate_agent_registry_cache,commands::agents::import_agents_from_zip,+ commands::agents::preview_agent_offline_export,+ commands::agents::export_agents_offline,commands::agents::import_agent_driver_cmd,commands::agents::import_agent_jar_cmd,commands::system_fonts::list_system_fonts,