fix(ai): preserve Dameng database and schema scopes
This commit is contained in:
16 files changed
+634
-76
No files matched your search
+77
-2
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildAiContext } from "@/lib/ai/ai";
|
||||
import { buildAiContext, resolveAiDatabaseTarget, resolveAiNamespaceSelection, resolveDefaultAiSchema, runAgentStream } from "@/lib/ai/ai";
|
||||
import type { AiConfig } from "@/types/ai";
|
||||
import type { ConnectionConfig, QueryTab } from "@/types/database";
|
||||
|
||||
const apiMock = vi.hoisted(() => ({
|
||||
@@ -7,6 +8,7 @@ const apiMock = vi.hoisted(() => ({
|
||||
getColumns: vi.fn(),
|
||||
listIndexes: vi.fn(),
|
||||
listForeignKeys: vi.fn(),
|
||||
aiAgentStream: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => apiMock);
|
||||
@@ -24,12 +26,13 @@ function sqliteConnection(database?: string): ConnectionConfig {
|
||||
};
|
||||
}
|
||||
|
||||
function queryTab(database: string): QueryTab {
|
||||
function queryTab(database: string, schema?: string): QueryTab {
|
||||
return {
|
||||
id: "tab-1",
|
||||
title: "Query",
|
||||
connectionId: "sqlite-1",
|
||||
database,
|
||||
schema,
|
||||
sql: "",
|
||||
isExecuting: false,
|
||||
isCancelling: false,
|
||||
@@ -38,6 +41,30 @@ function queryTab(database: string): QueryTab {
|
||||
};
|
||||
}
|
||||
|
||||
function damengConnection(database = "APPDB"): ConnectionConfig {
|
||||
return {
|
||||
id: "dameng-1",
|
||||
name: "Dameng",
|
||||
db_type: "dameng",
|
||||
host: "127.0.0.1",
|
||||
port: 5236,
|
||||
username: "APP_USER",
|
||||
password: "",
|
||||
database,
|
||||
};
|
||||
}
|
||||
|
||||
function aiConfig(): AiConfig {
|
||||
return {
|
||||
provider: "openai",
|
||||
apiKey: "",
|
||||
authMethod: "api-key",
|
||||
endpoint: "",
|
||||
model: "test-model",
|
||||
apiStyle: "responses",
|
||||
};
|
||||
}
|
||||
|
||||
describe("SQLite AI context routing", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -61,3 +88,51 @@ describe("SQLite AI context routing", () => {
|
||||
expect(apiMock.listTables).toHaveBeenCalledWith("sqlite-1", "analytics", "analytics");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Dameng AI context routing", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMock.listTables.mockResolvedValue([]);
|
||||
apiMock.getColumns.mockResolvedValue([]);
|
||||
apiMock.listIndexes.mockResolvedValue([]);
|
||||
apiMock.listForeignKeys.mockResolvedValue([]);
|
||||
apiMock.aiAgentStream.mockResolvedValue("done");
|
||||
});
|
||||
|
||||
it("keeps the connection database while routing metadata through the selected schema", async () => {
|
||||
const tab = { ...queryTab("APPDB", "REPORTING"), connectionId: "dameng-1" };
|
||||
const context = await buildAiContext(tab, damengConnection());
|
||||
|
||||
expect(context.database).toBe("APPDB");
|
||||
expect(context.schema).toBe("REPORTING");
|
||||
expect(apiMock.listTables).toHaveBeenCalledWith("dameng-1", "APPDB", "REPORTING");
|
||||
|
||||
await runAgentStream(
|
||||
{
|
||||
config: aiConfig(),
|
||||
action: "general",
|
||||
mode: "agent",
|
||||
instruction: "inspect orders",
|
||||
context,
|
||||
},
|
||||
[],
|
||||
vi.fn(),
|
||||
"session-1",
|
||||
);
|
||||
expect(apiMock.aiAgentStream).toHaveBeenCalledWith("session-1", expect.any(Object), "dameng-1", "APPDB", "REPORTING", "dameng", expect.any(Function), "agent", false, undefined, undefined, undefined, undefined);
|
||||
});
|
||||
|
||||
it("models the AI selector as a schema and chooses the connected user by default", () => {
|
||||
const connection = damengConnection();
|
||||
expect(resolveAiNamespaceSelection(queryTab("APPDB", "REPORTING"), connection)).toEqual({
|
||||
kind: "schema",
|
||||
value: "REPORTING",
|
||||
});
|
||||
expect(resolveDefaultAiSchema(connection, ["ARCHIVE", "APP_USER", "REPORTING"])).toBe("APP_USER");
|
||||
expect(resolveDefaultAiSchema(connection, ["REPORTING", "ARCHIVE"])).toBe("REPORTING");
|
||||
});
|
||||
|
||||
it("does not change non-Dameng namespace behavior", () => {
|
||||
expect(resolveAiDatabaseTarget(queryTab("analytics"), sqliteConnection())).toEqual({ database: "analytics" });
|
||||
});
|
||||
});
|
||||
@@ -80,6 +80,8 @@ export interface AiContext {
|
||||
connectionName: string;
|
||||
databaseType: DatabaseType;
|
||||
database: string;
|
||||
/** Selected schema when it is distinct from the connection database (for example Dameng). */
|
||||
schema?: string;
|
||||
currentSql: string;
|
||||
lastError?: string;
|
||||
lastResultPreview?: string;
|
||||
@@ -98,9 +100,15 @@ export interface AiRequestInput {
|
||||
allowWriteSql?: boolean;
|
||||
/** When allowWriteSql is true, the specific write SQL the user confirmed. */
|
||||
confirmedWriteSql?: string;
|
||||
/** Connection/database snapshot at confirmation time; verified at backend. */
|
||||
/** Connection/database/schema snapshot at confirmation time; verified at backend. */
|
||||
confirmedConnectionId?: string;
|
||||
confirmedDatabase?: string;
|
||||
confirmedSchema?: string;
|
||||
}
|
||||
|
||||
export interface AiNamespaceSelection {
|
||||
kind: "database" | "schema";
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface CustomPromptContext {
|
||||
@@ -189,6 +197,7 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessa
|
||||
},
|
||||
input.context.connectionId,
|
||||
input.context.database,
|
||||
input.context.schema,
|
||||
input.context.databaseType,
|
||||
onEvent,
|
||||
input.mode || "ask",
|
||||
@@ -196,6 +205,7 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessa
|
||||
input.confirmedWriteSql,
|
||||
input.confirmedConnectionId,
|
||||
input.confirmedDatabase,
|
||||
input.confirmedSchema,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -264,6 +274,7 @@ export function buildSystemPrompt(action: AiAction, context: AiContext, mode: Ai
|
||||
`Database type: ${context.databaseType}`,
|
||||
`Connection: ${context.connectionName}`,
|
||||
`Database: ${context.database}`,
|
||||
context.schema ? `Selected schema: ${context.schema}` : "",
|
||||
schemaCoverageLine(context, isZh),
|
||||
"",
|
||||
`Current SQL:\n${context.currentSql.trim() || "(empty)"}`,
|
||||
@@ -435,7 +446,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
|
||||
const maxIndexesPerTable = options.maxIndexesPerTable ?? 10;
|
||||
const maxFksPerTable = options.maxFksPerTable ?? 10;
|
||||
const databaseType = aiDatabaseTypeForConnection(connection);
|
||||
const database = aiDatabaseNamespace(tab, connection);
|
||||
const { database, schema } = resolveAiDatabaseTarget(tab, connection);
|
||||
const tables: AiSchemaTable[] = [];
|
||||
const tableKeys = new Set<string>();
|
||||
let truncated = false;
|
||||
@@ -551,6 +562,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
|
||||
connectionName: connection.name,
|
||||
databaseType,
|
||||
database,
|
||||
schema,
|
||||
currentSql: currentCollectionName ?? tab.sql,
|
||||
lastError: extractLastError(tab.result),
|
||||
lastResultPreview: formatResultPreview(tab.result),
|
||||
@@ -604,7 +616,8 @@ async function resolveMentionedTableSchema(tab: QueryTab, connection: Connection
|
||||
}
|
||||
|
||||
async function loadCandidateSchemas(tab: QueryTab, connection: ConnectionConfig): Promise<string[]> {
|
||||
const database = aiDatabaseNamespace(tab, connection);
|
||||
const { database, schema } = resolveAiDatabaseTarget(tab, connection);
|
||||
if (schema) return [schema];
|
||||
if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {
|
||||
const schemas = await api.listSchemas(tab.connectionId, database);
|
||||
return prioritizeSchemas(schemas);
|
||||
@@ -617,8 +630,37 @@ function aiDatabaseTypeForConnection(connection: ConnectionConfig): DatabaseType
|
||||
}
|
||||
|
||||
function aiDatabaseNamespace(tab: QueryTab, connection: ConnectionConfig): string {
|
||||
return resolveAiDatabaseTarget(tab, connection).database;
|
||||
}
|
||||
|
||||
export function resolveAiNamespaceSelection(tab: QueryTab, connection: ConnectionConfig): AiNamespaceSelection {
|
||||
if (connection.db_type === "dameng") {
|
||||
return { kind: "schema", value: tab.schema?.trim() || "" };
|
||||
}
|
||||
return { kind: "database", value: tab.database || "" };
|
||||
}
|
||||
|
||||
export function resolveDefaultAiSchema(connection: ConnectionConfig, schemaOptions: string[]): string | undefined {
|
||||
if (connection.db_type !== "dameng") return undefined;
|
||||
const username = connection.username.trim().toLowerCase();
|
||||
return schemaOptions.find((schema) => schema.trim().toLowerCase() === username) ?? schemaOptions[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the namespace used by an AI request without treating a Dameng schema
|
||||
* selection as a connection database override. Dameng connections stay bound to
|
||||
* their configured database while the query tab's selection scopes metadata and
|
||||
* SQL execution through the schema parameter.
|
||||
*/
|
||||
export function resolveAiDatabaseTarget(tab: QueryTab, connection: ConnectionConfig): { database: string; schema?: string } {
|
||||
const database = tab.database || connection.database || "main";
|
||||
return connection.db_type === "sqlite" ? normalizeSqliteNamespace(database, connection) : database;
|
||||
if (connection.db_type === "dameng") {
|
||||
return {
|
||||
database,
|
||||
schema: resolveAiNamespaceSelection(tab, connection).value || undefined,
|
||||
};
|
||||
}
|
||||
return { database: connection.db_type === "sqlite" ? normalizeSqliteNamespace(database, connection) : database };
|
||||
}
|
||||
|
||||
function prioritizeSchemas(schemas: string[]): string[] {
|
||||
|
||||
@@ -1336,6 +1336,7 @@ export async function aiAgentStream(
|
||||
request: AiCompletionRequest,
|
||||
connectionId: string,
|
||||
database: string,
|
||||
schema: string | undefined,
|
||||
dbType: string,
|
||||
onEvent: (event: import("@/lib/backend/tauri").AgentEvent) => void,
|
||||
mode?: string,
|
||||
@@ -1343,6 +1344,7 @@ export async function aiAgentStream(
|
||||
confirmedWriteSql?: string,
|
||||
confirmedConnectionId?: string,
|
||||
confirmedDatabase?: string,
|
||||
confirmedSchema?: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const res = await fetch(apiUrl("/api/ai/agent-stream"), {
|
||||
@@ -1353,12 +1355,14 @@ export async function aiAgentStream(
|
||||
request,
|
||||
connectionId,
|
||||
database,
|
||||
schema,
|
||||
dbType,
|
||||
mode: mode || "ask",
|
||||
allowWriteSql,
|
||||
confirmedWriteSql,
|
||||
confirmedConnectionId,
|
||||
confirmedDatabase,
|
||||
confirmedSchema,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
@@ -431,6 +431,7 @@ export async function aiAgentStream(
|
||||
request: AiCompletionRequest,
|
||||
connectionId: string,
|
||||
database: string,
|
||||
schema: string | undefined,
|
||||
dbType: string,
|
||||
onEvent: (event: AgentEvent) => void,
|
||||
mode?: string,
|
||||
@@ -438,6 +439,7 @@ export async function aiAgentStream(
|
||||
confirmedWriteSql?: string,
|
||||
confirmedConnectionId?: string,
|
||||
confirmedDatabase?: string,
|
||||
confirmedSchema?: string,
|
||||
_signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
const unlisten: UnlistenFn = await listen<AgentEvent>("ai-agent-event", (event) => {
|
||||
@@ -452,12 +454,14 @@ export async function aiAgentStream(
|
||||
request,
|
||||
connectionId,
|
||||
database,
|
||||
schema,
|
||||
dbType,
|
||||
mode,
|
||||
allowWriteSql,
|
||||
confirmedWriteSql,
|
||||
confirmedConnectionId,
|
||||
confirmedDatabase,
|
||||
confirmedSchema,
|
||||
});
|
||||
} catch (e) {
|
||||
unlisten();
|
||||
|
||||
Reference in new issue
Block a user