feat(agent): export managed drivers for offline use
This commit is contained in:
1 parent
6eb8b43701
commit
82e5756325
23 files changed
+3419
-40
No files matched your search
@@ -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"');
|
||||
});
|
||||
});
|
||||
@@ -118,6 +118,8 @@ export async function importAgentsFromZip(fileOrPath: string | File, operationId
|
||||
const 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,
|
||||
|
||||
@@ -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, operationId
|
||||
return 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;
|
||||
|
||||
@@ -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?: str
|
||||
return 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");
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user