feat(ai): add read-only user skill loader for SKILL.md

Refs: #9363
This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-09-22 02:24:23 +08:00
1 parent 6af337e67c
commit 34d8811cd3
36 files changed
+1765 -26

No files matched your search

@@ -0,0 +1,77 @@
import { beforeAll, describe, expect, it } from "vitest";
import { buildSystemPrompt, type AiContext, type CustomPromptContext } from "@/lib/ai/ai";
import { setLocale } from "@/i18n";
import type { ReadUserSkill } from "@/types/userSkills";
function context(overrides: Partial<AiContext> = {}): AiContext {
return {
connectionId: "conn-1",
connectionName: "Postgres",
databaseType: "postgres",
database: "app",
currentSql: "",
tables: [],
sqlFiles: [],
csvFiles: [],
truncated: false,
...overrides,
};
}
const skill: ReadUserSkill = {
id: "d-abc123",
name: "SQL Review",
description: "Team SQL review rules",
content: "Always prefix reviews with EXPLAIN checks.",
};
// buildSystemPrompt picks zh/en copy via currentLocale(); pin to en so the
// English-string assertions are deterministic regardless of the host OS locale.
beforeAll(async () => {
await setLocale("en");
});
describe("selected skills prompt injection", () => {
it("injects selected skills into the SQL, Redis, and vector branches", () => {
for (const ctx of [context(), context({ databaseType: "redis", connectionName: "Redis", database: "8" }), context({ databaseType: "qdrant", connectionName: "Qdrant", database: "vec" })]) {
const prompt = buildSystemPrompt("general", ctx, "ask", { selectedSkills: [skill] });
expect(prompt).toContain("## Selected Skills (supplementary)");
expect(prompt).toContain("### Skill: SQL Review");
expect(prompt).toContain('<ai-skill id="d-abc123">');
expect(prompt).toContain("Always prefix reviews with EXPLAIN checks.");
expect(prompt).toContain("</ai-skill>");
}
});
it("injects the zh header for zh locale", async () => {
await setLocale("zh-CN");
try {
const prompt = buildSystemPrompt("general", context(), "ask", { selectedSkills: [skill] });
expect(prompt).toContain("## 用户选择的 Skills(补充性)");
expect(prompt).toContain("按原样注入");
} finally {
await setLocale("en");
}
});
it("leaves prompts byte-for-byte unchanged when no skills are selected", () => {
// AC: with no selected skills, every prompt branch is byte-identical to the
// pre-feature baseline. Absent field, empty array, and undefined custom all
// must agree exactly.
const baseline = buildSystemPrompt("general", context(), "ask");
const withGlobals: CustomPromptContext = { globalInstructions: "Global rule." };
const withEmptySkills: CustomPromptContext = { globalInstructions: "Global rule.", selectedSkills: [] };
for (const ctx of [context(), context({ databaseType: "redis", connectionName: "Redis", database: "8" }), context({ databaseType: "milvus", connectionName: "Milvus", database: "vec" })]) {
expect(buildSystemPrompt("general", ctx, "ask")).toBe(buildSystemPrompt("general", ctx, "ask", undefined));
expect(buildSystemPrompt("general", ctx, "ask", withEmptySkills)).toBe(buildSystemPrompt("general", ctx, "ask", withGlobals));
expect(buildSystemPrompt("general", ctx, "ask", withEmptySkills)).not.toBe(baseline); // globals still apply
}
});
it("treats blank-content skills as absent", () => {
const blank: ReadUserSkill = { ...skill, content: " " };
const withBlank = buildSystemPrompt("general", context(), "ask", { selectedSkills: [blank] });
expect(withBlank).toBe(buildSystemPrompt("general", context(), "ask"));
expect(withBlank).not.toContain("ai-skill");
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import { buildSelectedSkillChips, capSkillsToCharLimit, removeSkillIds, userSkillSourceOfId } from "@/lib/ai/userSkillSelection";
import { ACTIVE_SKILLS_TOTAL_MAX, type ReadUserSkill, type UserSkillMeta } from "@/types/userSkills";
const catalog: Record<string, UserSkillMeta> = {
"d-aaa": { id: "d-aaa", name: "SQL Review", description: "review rules" },
"c-bbb": { id: "c-bbb", name: "Team Rules", description: "team rules" },
};
const lookup = (id: string): UserSkillMeta | undefined => catalog[id];
function skill(id: string, content: string): ReadUserSkill {
return { id, name: id, description: "", content };
}
describe("selected skill chips", () => {
it("keeps a chip for every selected id, including vanished ones", () => {
// Regression anchor for "unavailable skills have a visible recovery action":
// `d-gone` is absent from the catalog (deleted after selection + refresh) and
// must still render a removable chip rather than silently disappearing.
const chips = buildSelectedSkillChips(["d-aaa", "d-gone", "c-bbb"], lookup);
expect(chips.map((chip) => chip.id)).toEqual(["d-aaa", "d-gone", "c-bbb"]);
expect(chips[1]).toEqual({ id: "d-gone", name: "d-gone", description: "", source: "default", unavailable: true });
expect(chips[0].unavailable).toBe(false);
expect(chips[0].name).toBe("SQL Review");
});
it("labels the source from the id prefix so a vanished skill keeps its origin", () => {
expect(userSkillSourceOfId("c-bbb")).toBe("custom");
expect(userSkillSourceOfId("d-aaa")).toBe("default");
const chips = buildSelectedSkillChips(["c-gone"], lookup);
expect(chips[0].source).toBe("custom");
expect(chips[0].unavailable).toBe(true);
});
it("handles an empty selection", () => {
expect(buildSelectedSkillChips([], lookup)).toEqual([]);
});
});
describe("removeSkillIds", () => {
it("drops the given ids and preserves the remaining order", () => {
expect(removeSkillIds(["a", "b", "c"], ["b"])).toEqual(["a", "c"]);
expect(removeSkillIds(["a", "b", "c"], ["a", "c"])).toEqual(["b"]);
});
it("is a no-op for unknown ids and empty removals", () => {
const ids = ["a", "b"];
expect(removeSkillIds(ids, [])).toEqual(ids);
expect(removeSkillIds(ids, ["zzz"])).toEqual(ids);
expect(removeSkillIds(ids, ["a", "a"])).toEqual(["b"]);
});
});
describe("capSkillsToCharLimit", () => {
it("keeps leading skills that fit the combined budget and skips overflowing ones", () => {
// Regression anchor for "selected skills cannot grow the system prompt
// without bound": the first skill fills the budget, the oversized second
// is skipped, and the smaller third still fits.
const big = "x".repeat(60);
const capped = capSkillsToCharLimit([skill("d-1", "a".repeat(30)), skill("d-2", big), skill("d-3", "b".repeat(10))], 50);
expect(capped.map((s) => s.id)).toEqual(["d-1", "d-3"]);
});
it("drops a single skill whose content alone exceeds the budget", () => {
expect(capSkillsToCharLimit([skill("d-1", "x".repeat(ACTIVE_SKILLS_TOTAL_MAX + 1))], ACTIVE_SKILLS_TOTAL_MAX)).toEqual([]);
expect(capSkillsToCharLimit([skill("d-1", "x".repeat(ACTIVE_SKILLS_TOTAL_MAX))], ACTIVE_SKILLS_TOTAL_MAX).map((s) => s.id)).toEqual(["d-1"]);
});
it("preserves selection order and dedupes repeated ids", () => {
const capped = capSkillsToCharLimit([skill("d-1", "a"), skill("d-2", "b"), skill("d-1", "a")], 10);
expect(capped.map((s) => s.id)).toEqual(["d-1", "d-2"]);
});
it("keeps everything under the real budget for realistic sizes", () => {
const skills = Array.from({ length: 8 }, (_, i) => skill(`d-${i}`, "y".repeat(2000)));
expect(capSkillsToCharLimit(skills, ACTIVE_SKILLS_TOTAL_MAX).length).toBe(8);
});
});
+13 -1
View File
@@ -3,6 +3,7 @@ import type { AiAssistantMode } from "@/types/ai";
import { uuid } from "@/lib/common/utils";
import type { ColumnInfo, ConnectionConfig, DatabaseType, ForeignKeyInfo, IndexInfo, QueryResult, QueryTab } from "@/types/database";
import type { PromptTemplate } from "@/types/promptTemplate";
import type { ReadUserSkill } from "@/types/userSkills";
import * as api from "@/lib/backend/api";
import { currentLocale, type Locale } from "@/i18n";
import { aiTableMentionKey, type AiTableMention } from "@/lib/ai/aiTableMentions";
@@ -161,16 +162,27 @@ export interface AiNamespaceSelection {
export interface CustomPromptContext {
globalInstructions?: string;
activeTemplates?: PromptTemplate[];
/** Selected read-only SKILL.md snapshots resolved at send time (09-21-public-skill-loader). */
selectedSkills?: ReadUserSkill[];
}
function buildCustomInstructionLines(custom: CustomPromptContext | undefined, isZh: boolean): string[] {
const global = custom?.globalInstructions?.trim() ?? "";
const templates = (custom?.activeTemplates ?? []).filter((t) => t.content.trim());
if (!global && templates.length === 0) return [];
const skills = (custom?.selectedSkills ?? []).filter((skill) => skill.content.trim());
if (!global && templates.length === 0 && skills.length === 0) return [];
const parts: string[] = [];
if (global) parts.push(global);
parts.push(...templates.map((t) => `### ${t.name}\n${t.content}`));
if (skills.length > 0) {
parts.push(
isZh
? "## 用户选择的 Skills(补充性)\n以下为用户显式选择的外部 SKILL.md 规则文件,按原样注入;上方核心安全及方言规则优先级更高。"
: "## Selected Skills (supplementary)\nThe following external SKILL.md rule files were explicitly selected by the user and are injected as-is. Core safety and dialect rules above take precedence.",
);
parts.push(...skills.map((skill) => `### Skill: ${skill.name}\n<ai-skill id="${skill.id}">\n${skill.content}\n</ai-skill>`));
}
return [
isZh
@@ -0,0 +1,67 @@
import type { ReadUserSkill, UserSkillMeta } from "@/types/userSkills";
import { promptTemplateCharacterCount } from "@/types/promptTemplate";
/** A selected skill rendered as a chip, whether or not it is still discoverable. */
export interface SelectedSkillChip {
id: string;
name: string;
description: string;
source: "custom" | "default";
/** True when the catalog no longer lists this id (deleted, or its root went away). */
unavailable: boolean;
}
/**
* The backend mints ids as `<root>-<digest>` (`c-` custom root, `d-` default
* root). Deriving the source from that prefix instead of from the catalog keeps
* a selected skill labeled and removable after it disappears from discovery.
*/
export function userSkillSourceOfId(id: string): "custom" | "default" {
return id.startsWith("c-") ? "custom" : "default";
}
/**
* Every selected id keeps a chip: a skill that vanished from discovery would
* otherwise lose its only remove affordance and block every later send. The
* fallback label is the opaque id, paired with `unavailable` for styling.
*/
export function buildSelectedSkillChips(ids: readonly string[], lookup: (id: string) => UserSkillMeta | undefined): SelectedSkillChip[] {
return ids.map((id) => {
const meta = lookup(id);
return {
id,
name: meta?.name ?? id,
description: meta?.description ?? "",
source: userSkillSourceOfId(id),
unavailable: !meta,
};
});
}
/** Order-preserving removal, shared by the chip close button and the failure banner. */
export function removeSkillIds(ids: readonly string[], removed: Iterable<string>): string[] {
const dropped = new Set(removed);
return ids.filter((id) => !dropped.has(id));
}
/**
* Keep the leading skills that fit the combined character budget for one
* request. A skill whose content would push the total past maxTotal is
* skipped, but a later smaller skill still fits (same budget semantics as
* capTemplateIdsToCharLimit for templates). Selection order is preserved so
* the injected set matches the chips top to bottom.
*/
export function capSkillsToCharLimit(skills: readonly ReadUserSkill[], maxTotal: number): ReadUserSkill[] {
const kept: ReadUserSkill[] = [];
const seen = new Set<string>();
let total = 0;
for (const skill of skills) {
if (seen.has(skill.id)) continue;
seen.add(skill.id);
const size = promptTemplateCharacterCount(skill.content);
if (total + size > maxTotal) continue;
total += size;
kept.push(skill);
}
return kept;
}
@@ -0,0 +1,47 @@
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 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");
const commandModuleSource = readFileSync(new URL("../../../../../../src-tauri/src/commands/user_skills.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);
}
describe("user skills transport contract", () => {
it("routes list/read through the desktop Tauri backend", () => {
expect(functionBody(tauri, "listUserSkills")).toContain('invoke("list_user_skills"');
expect(functionBody(tauri, "readUserSkills")).toContain('invoke("read_user_skills"');
expect(tauriRegistry).toContain("commands::user_skills::list_user_skills,");
expect(tauriRegistry).toContain("commands::user_skills::read_user_skills,");
expect(api).toContain('listUserSkills = forward("listUserSkills")');
expect(api).toContain('readUserSkills = forward("readUserSkills")');
});
it("keeps the skill service strictly read-only outside its tests", () => {
const production = commandModuleSource.slice(0, commandModuleSource.indexOf("#[cfg(test)]"));
expect(production).not.toContain("fs::write");
expect(production).not.toContain("fs::remove");
expect(production).not.toContain("fs::create_dir");
expect(production).not.toContain("OpenOptions");
});
it("keeps the Web transport explicitly unsupported without adding HTTP routes", () => {
for (const operation of ["listUserSkills", "readUserSkills"]) {
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("user_skills");
expect(webRegistry).not.toContain("list_user_skills");
expect(webRegistry).not.toContain("read_user_skills");
});
});
+4
View File
@@ -415,6 +415,10 @@ export const deletePromptTemplate = forward("deletePromptTemplate");
export const getAiGlobalCustomInstructions = forward("getAiGlobalCustomInstructions");
export const setAiGlobalCustomInstructions = forward("setAiGlobalCustomInstructions");
// User Skills (read-only Codex-compatible SKILL.md library)
export const listUserSkills = forward("listUserSkills");
export const readUserSkills = forward("readUserSkills");
// System
export const listSystemFonts = forward("listSystemFonts");
export const listSshConfigHosts = forward("listSshConfigHosts");
+11
View File
@@ -1,5 +1,6 @@
import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRestoreSourcePreview, MongoDatabaseDumpRequest, MongoDatabaseRestoreRequest, MongoDatabaseDumpProgress } from "./mongodbDumpTypes";
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
import type {
ConnectionConfig,
ConnectionTestResult,
@@ -303,6 +304,8 @@ const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
driver_store_dir: null,
plugin_store_dir: null,
agent_store_dir: null,
custom_ai_skill_root_enabled: false,
custom_ai_skill_root: null,
sidebar_table_page_size: 1000,
};
@@ -894,6 +897,14 @@ export async function exportAgentsOffline(_path: string, _driverKeys: string[]):
throw new Error("Offline Agent package export is only available in the desktop app.");
}
export async function listUserSkills(_settings: UserSkillRootSettings): Promise<UserSkillsListResult> {
throw new Error("AI skills are only available in the desktop app.");
}
export async function readUserSkills(_ids: string[], _settings: UserSkillRootSettings): Promise<UserSkillsReadResult> {
throw new Error("AI skills are only available in the desktop app.");
}
export async function importAgentDriver(dbType: string, pathOrFile: string | File): Promise<void> {
let blob: Blob;
let fileName: string;
+11
View File
@@ -1,6 +1,7 @@
import { invoke as tauriInvoke } from "@tauri-apps/api/core";
import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRestoreSourcePreview, MongoDatabaseDumpRequest, MongoDatabaseRestoreRequest, MongoDatabaseDumpProgress } from "./mongodbDumpTypes";
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";
import { assertUpdateAllowsCommand } from "@/lib/app/updatePreparation";
import { collectBrowserSupportInfo } from "@/lib/app/supportInfo";
// Re-exported below so the HTTP transport shares one definition; imported here
@@ -290,6 +291,8 @@ export interface DesktopSettings {
driver_store_dir?: string | null;
plugin_store_dir?: string | null;
agent_store_dir?: string | null;
custom_ai_skill_root_enabled?: boolean | null;
custom_ai_skill_root?: string | null;
sidebar_table_page_size?: number | null;
}
@@ -1246,6 +1249,14 @@ export async function setAiGlobalCustomInstructions(content: string): Promise<vo
return invoke("set_ai_global_custom_instructions", { content });
}
export async function listUserSkills(settings: UserSkillRootSettings): Promise<UserSkillsListResult> {
return invoke("list_user_skills", { customRootEnabled: settings.customRootEnabled, customRoot: settings.customRoot });
}
export async function readUserSkills(ids: string[], settings: UserSkillRootSettings): Promise<UserSkillsReadResult> {
return invoke("read_user_skills", { ids, customRootEnabled: settings.customRootEnabled, customRoot: settings.customRoot });
}
export async function testConnection(config: ConnectionConfig): Promise<string> {
return invokeBackend("test_connection", { config });
}
@@ -267,6 +267,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "ai-agent-turn-limit", category: "ai", titleKey: "ai.maxAgentTurns", descriptionKey: "ai.maxAgentTurnsDescription", targetId: "ai" },
{ id: "ai-global-retries", category: "ai", titleKey: "ai.maxRetriesGlobal", descriptionKey: "ai.maxRetriesGlobalDescription", targetId: "ai" },
{ id: "ai-global-instructions", category: "ai", titleKey: "ai.globalInstructions", descriptionKey: "ai.globalInstructionsDescription", targetId: "ai" },
{ id: "ai-custom-skill-root", category: "ai", titleKey: "settings.aiSkillRoot", descriptionKey: "settings.aiSkillRootDesc", targetId: "ai", visible: desktopOnly },
{ id: "mcp", category: "mcp", titleKey: "settings.mcpTitle", descriptionKey: "settings.mcpDescription", targetId: "mcp" },
{ id: "mcp-bin-path", category: "mcp", titleKey: "settings.mcpBinPath", targetId: "mcp" },
{ id: "mcp-permissions", category: "mcp", titleKey: "settings.mcpExecutionMode", descriptionKey: "settings.mcpExecutionModeDescription", targetId: "mcp" },