Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(skills): remove imported skills from one bot and clear stale imports
erywimc3227876e2e4
diff --git a/server/imported-skills.test.ts b/server/imported-skills.test.tsindex 9fd9a556f2..ed1c135949 100644--- a/server/imported-skills.test.ts+++ b/server/imported-skills.test.ts@@ -1,5 +1,5 @@import { createHash, randomUUID } from "node:crypto";-import { chmodSync, existsSync, lstatSync, mkdirSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";@@ -8,7 +8,8 @@ import { DATA_DIR, type AppConfig } from "./config.ts";import { createSkillsLibraryHost } from "./host/skills-library.ts";import {FIT_MAX_SKILLS, IMPORTED_CHANGED_WARNING, IMPORTED_SKILLS_DIR, importedSkillListings, importedSkillsFor, importedSkillsPrompt,- listedImportedSkills, nativeSkillFolders, readImportedSkillFile, setImportedSkillEnabled, storeImportedSkills, syncImportedSkillLinks, type ImportedSkillInput,+ listedImportedSkills, nativeSkillFolders, purgeImportedSkill, readImportedSkillFile, readImportedSkills, removeImportedSkillForBot,+ setImportedSkillEnabled, storeImportedSkills, syncImportedSkillLinks, type ImportedSkillInput,} from "./imported-skills.ts";import { skillCommandTurnText } from "../shared/skill-command.ts";import { ensureTaskWorkspaceWithSkills } from "./skill-task-links.ts";@@ -258,3 +259,60 @@ describe("skills brought in from this computer", () => {expect(listedImportedSkills(older, importedSkillsFor(older, new Set()), "sales")).toHaveLength(19);});});++describe("removing a skill brought in from this computer", () => {+ const sourceFolder = (name: string) => join(HOME, ".claude", "skills", name);+ const writeSource = (name: string) => {+ mkdirSync(sourceFolder(name), { recursive: true });+ writeFileSync(join(sourceFolder(name), "SKILL.md"), skillMd(name));+ };++ it("takes it out of one bot, leaving the shared copy, the source and every other bot alone", () => {+ const [first, second] = [newBot(), newBot()];+ store([input("pdf")]);+ writeSource("pdf");+ expect(importedSkillListings(first, new Set())[0]).toMatchObject({ name: "pdf", sourceGone: false });++ expect(removeImportedSkillForBot(first, "pdf")).toEqual({ removed: true });+ expect(names(importedSkillListings(first, new Set()))).not.toContain("pdf");+ expect(names(importedSkillsFor(first, new Set()))).not.toContain("pdf");+ expect(names(importedSkillListings(second, new Set()))).toContain("pdf");+ expect(names(importedSkillsFor(second, new Set()))).toContain("pdf");+ expect(readImportedSkillFile("pdf")).toBe(skillMd("pdf"));+ expect(readFileSync(join(IMPORTED_SKILLS_DIR, "pdf", "SKILL.md"), "utf8")).toBe(skillMd("pdf"));+ expect(readFileSync(join(sourceFolder("pdf"), "SKILL.md"), "utf8")).toBe(skillMd("pdf"));++ // The switch still works for another bot.+ expect(setImportedSkillEnabled(second, "pdf", false)).toMatchObject({ name: "pdf", enabled: false });+ expect(names(importedSkillsFor(second, new Set()))).not.toContain("pdf");+ expect(setImportedSkillEnabled(second, "pdf", true)).toMatchObject({ name: "pdf", enabled: true });+ expect(names(importedSkillsFor(second, new Set()))).toContain("pdf");++ // A copy brought in again stays out of the bot it was removed from until it is switched on there.+ store([input("pdf")]);+ expect(names(importedSkillListings(first, new Set()))).not.toContain("pdf");+ expect(setImportedSkillEnabled(first, "pdf", true)).toMatchObject({ name: "pdf", enabled: true });+ expect(names(importedSkillListings(first, new Set()))).toContain("pdf");+ expect(removeImportedSkillForBot(first, "not a name")).toHaveProperty("error");+ });++ it("clears a stale entry only when its source folder no longer holds a skill", () => {+ store([input("pdf")]);+ writeSource("pdf");+ expect(purgeImportedSkill("pdf")).toHaveProperty("error");+ expect(readImportedSkills()["pdf"]).toBeDefined();+ expect(existsSync(join(IMPORTED_SKILLS_DIR, "pdf"))).toBe(true);++ rmSync(sourceFolder("pdf"), { recursive: true });+ expect(importedSkillListings(newBot(), new Set())[0]).toMatchObject({ name: "pdf", sourceGone: true });+ const bot = newBot();+ expect(removeImportedSkillForBot(bot, "pdf")).toEqual({ removed: true });+ expect(names(importedSkillListings(bot, new Set()))).not.toContain("pdf");+ expect(names(importedSkillListings(newBot(), new Set()))).toContain("pdf");+ expect(purgeImportedSkill("pdf")).toEqual({ removed: true });+ expect(readImportedSkills()["pdf"]).toBeUndefined();+ expect(existsSync(join(IMPORTED_SKILLS_DIR, "pdf"))).toBe(false);+ expect(importedSkillListings(newBot(), new Set())).toEqual([]);+ expect(purgeImportedSkill("pdf")).toHaveProperty("error");+ });+});diff --git a/server/imported-skills.ts b/server/imported-skills.tsindex 4c4c2f55a8..6165bcb1e1 100644--- a/server/imported-skills.ts+++ b/server/imported-skills.ts@@ -28,6 +28,8 @@ export const IMPORTED_SKILLS_DIR = join(DATA_DIR, "imported-skills");/** Beside each bot's own skill state, outside every folder a bot works in. */const INDEX_PATH = join(DATA_DIR, "skill-state", "imported-skills.json");const choicesPath = (botId: string) => join(DATA_DIR, "skill-state", botId, "imported-skills.json");+/** In its own file so a version that does not know it never rewrites the removal away. */+const removedPath = (botId: string) => join(DATA_DIR, "skill-state", botId, "imported-skills-removed.json");const sha256Hex = z.string().regex(/^[a-f0-9]{64}$/);const entrySchema = z.object({@@ -56,6 +58,7 @@ const choicesSchema = z.object({listed: z.array(z.string()).optional(),});type Choices = z.infer<typeof choicesSchema>;+const removedSchema = z.object({ removed: z.array(z.string()).default([]) });/** Every imported skill by name; empty when there are none or the index cannot be trusted. */export function readImportedSkills(): Record<string, ImportedSkillEntry> {@@ -81,6 +84,43 @@ function readChoices(botId: string): Choices {return { off: [], on: {}, listed: [] };}+function writeChoices(botId: string, choices: Choices): void {+ mkdirSync(dirname(choicesPath(botId)), { recursive: true, mode: 0o700 });+ writeFileAtomic(choicesPath(botId), `${JSON.stringify(choices, null, 2)}\n`, { mode: 0o600 });+}++/** The imported skills a person took out of one bot's Skills settings. */+function readRemoved(botId: string): string[] {+ try {+ const parsed = removedSchema.safeParse(JSON.parse(readFileSync(removedPath(botId), "utf8")));+ if (parsed.success) return parsed.data.removed.filter(isSkillName);+ } catch {}+ return [];+}++function writeRemoved(botId: string, removed: readonly string[]): void {+ mkdirSync(dirname(removedPath(botId)), { recursive: true, mode: 0o700 });+ writeFileAtomic(removedPath(botId), `${JSON.stringify({ removed: [...new Set(removed)].sort() }, null, 2)}\n`, { mode: 0o600 });+}++/** Whether the folder a skill was brought in from no longer holds a SKILL.md: the copy here is all that is left. The+ * source is only asked whether its SKILL.md is a file; it is never read. */+function sourceFolderGone(entry: ImportedSkillEntry): boolean {+ if (!entry.origin) return true;+ try {+ return !statSync(join(entry.origin, "SKILL.md")).isFile();+ } catch (error) {+ // A missing path is gone; a permission or I/O error does not prove it, so it must not allow the shared copy's removal.+ const code = (error as NodeJS.ErrnoException).code;+ return code === "ENOENT" || code === "ENOTDIR";+ }+}++/** Imported skills this bot removed: a native copy of the same name stays off with them. */+export function removedImportedSkills(botId: string): string[] {+ return readRemoved(botId);+}+/** More than this many and a bot's prompt lists only the ones that fit it. */export const FIT_MAX_SKILLS = 15;@@ -328,7 +368,8 @@ function loadedInPlace(entry: ImportedSkillEntry, native: readonly string[]): bo* the ones listedImportedSkills picks. */export function importedSkillsFor(botId: string, shadowed: ReadonlySet<string>, native: readonly string[] = []): ImportedSkillView[] {const index = readImportedSkills();- const names = Object.keys(index).filter((name) => !shadowed.has(name)).sort();+ const removed = new Set(readRemoved(botId));+ const names = Object.keys(index).filter((name) => !shadowed.has(name) && !removed.has(name)).sort();if (!names.length) return [];const choices = readChoices(botId);return names.flatMap((name) => {@@ -341,14 +382,16 @@ export function importedSkillsFor(botId: string, shadowed: ReadonlySet<string>,export const IMPORTED_CHANGED_WARNING = "its files changed after it was brought in — bring it in again from Settings → Import & export → Bring things in → From your AI apps";-export type ImportedSkillListing = SkillListing & { origin: "imported"; listed: boolean; file?: string };+export type ImportedSkillListing = SkillListing & { origin: "imported"; listed: boolean; file?: string; sourceGone: boolean };-/** Bot Settings → Skills: every imported skill not shadowed by one of the bot's own, with its switch for this bot,- * the ones in its list (`about` is what the bot is for) first. An enabled one names its SKILL.md, so a search finds it. */+/** Bot Settings → Skills: every imported skill not shadowed by one of the bot's own or removed from it, with its switch+ * for this bot, the ones in its list (`about` is what the bot is for) first. An enabled one names its SKILL.md, so a+ * search finds it. */export function importedSkillListings(botId: string, shadowed: ReadonlySet<string>, about = ""): ImportedSkillListing[] {const index = readImportedSkills();const choices = readChoices(botId);- const listings = Object.keys(index).filter((name) => !shadowed.has(name)).sort().map((name): ImportedSkillListing => {+ const removed = new Set(readRemoved(botId));+ const listings = Object.keys(index).filter((name) => !shadowed.has(name) && !removed.has(name)).sort().map((name): ImportedSkillListing => {const entry = index[name]!;const intact = importedSkillIntact(name, entry);const enabled = intact && enabledFor(name, entry, choices);@@ -357,6 +400,7 @@ export function importedSkillListings(botId: string, shadowed: ReadonlySet<strindescription: entry.description,enabled,listed: false,+ sourceGone: sourceFolderGone(entry),...(enabled ? { file: join(IMPORTED_SKILLS_DIR, name, "SKILL.md") } : {}),editable: false,source: entry.label,@@ -396,8 +440,11 @@ export function setImportedSkillEnabled(botId: string, name: string, enabled: boconst next: Choices = enabled? { off, on: entry.warnings.length ? { ...on, [name]: entry.filesSha256 } : on, ...(listed ? { listed: [...listed, name].sort() } : {}) }: { off: [...off, name].sort(), on, ...(listed ? { listed } : {}) };- mkdirSync(dirname(choicesPath(botId)), { recursive: true, mode: 0o700 });- writeFileAtomic(choicesPath(botId), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ writeChoices(botId, next);+ if (enabled) {+ const removed = readRemoved(botId);+ if (removed.includes(name)) writeRemoved(botId, removed.filter((other) => other !== name));+ }return importedSkillListings(botId, new Set()).find((skill) => skill.name === name)!;}@@ -410,9 +457,39 @@ export function importedSkillsSwitchedOff(botId: string): string[] {export function switchImportedSkillBackOn(botId: string, name: string): void {const choices = readChoices(botId);if (!choices.off.includes(name)) return;- const next: Choices = { ...choices, off: choices.off.filter((other) => other !== name) };- mkdirSync(dirname(choicesPath(botId)), { recursive: true, mode: 0o700 });- writeFileAtomic(choicesPath(botId), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });+ writeChoices(botId, { ...choices, off: choices.off.filter((other) => other !== name) });+}++/** Takes an imported skill out of one bot's Skills settings and its turn: every other bot, OpenMausBot's copy and the+ * folder it came from keep it. Bringing the same copy in again leaves it out until it is switched on for this bot. */+export function removeImportedSkillForBot(botId: string, name: string): { removed: true } | { error: string } {+ if (!isSkillName(name)) return { error: `invalid skill name "${name}"` };+ writeRemoved(botId, [...readRemoved(botId), name]);+ return { removed: true };+}++/** Deletes OpenMausBot's copy and index entry, only once the folder it was brought in from no longer holds a SKILL.md:+ * every bot loses the skill, and the files on disk are never touched. */+export function purgeImportedSkill(name: string): { removed: true } | { error: string } {+ if (!isSkillName(name)) return { error: `invalid skill name "${name}"` };+ const index = readImportedSkills();+ const entry = index[name];+ if (!entry) return { error: `no skill named "${name}" was brought in from this computer` };+ if (!sourceFolderGone(entry)) return { error: `"${name}" still has its source folder; remove it from this bot instead` };+ if (directoryEntryState(IMPORTED_SKILLS_DIR) === "unsafe") {+ return { error: "the imported skills folder is a symlink or file; refusing to remove through it" };+ }+ const target = join(IMPORTED_SKILLS_DIR, name);+ try {+ if (directoryEntryState(target) === "directory") rmSync(target, { recursive: true, force: true });+ else if (entryExistsWithoutFollowing(target)) unlinkSync(target);+ } catch (error) {+ return { error: `could not remove the copy of "${name}": ${error instanceof Error ? error.message : String(error)}` };+ }+ digests.delete(target);+ delete index[name];+ writeIndex(index);+ return { removed: true };}/** The engine of one turn, as far as which skill folders it loads by itself. */diff --git a/server/native-skill-choices.test.ts b/server/native-skill-choices.test.tsindex a696c93d0e..e837ba67f0 100644--- a/server/native-skill-choices.test.ts+++ b/server/native-skill-choices.test.ts@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";import { DATA_DIR } from "./config.ts";import { claudeDisabledNativeSkillRules } from "./drivers/claude-unusable-tools.ts";import { codexDisabledNativeSkillArgs, codexTurnConfigArgs, GUEST_CONFINED_CODEX_ARGS } from "./drivers/codex-guest.ts";-import { setImportedSkillEnabled, storeImportedSkills } from "./imported-skills.ts";+import { removeImportedSkillForBot, setImportedSkillEnabled, storeImportedSkills } from "./imported-skills.ts";import { deniedNativeSkills, isNativeSkillEnabled, setNativeSkillEnabled } from "./native-skill-choices.ts";// HOME and the data folder are this test file's own temporary ones (server/testing/setup.ts).@@ -102,4 +102,26 @@ describe("Codex skills.config overrides for a bot's switched-off skills", () =>expect(isNativeSkillEnabled("bot-a", "rex")).toBe(true);expect(paths(codexDisabledNativeSkillArgs("bot-a", env))).toEqual([]);});++ it("keeps a removed imported skill's native copy off for that bot, and restores it when the skill is switched back on", () => {+ plant(join(HOME, "brought"), "renamed-folder");+ storeImportedSkills([{+ name: "rex",+ entry: {+ description: "Works with rex.", source: "codex", root: join(HOME, "brought"), origin: join(HOME, "brought", "renamed-folder"),+ label: "rex", sha256: createHash("sha256").update(skillMd("rex")).digest("hex"), warnings: [],+ },+ skillMd: skillMd("rex"),+ files: [],+ }]);+ expect(removeImportedSkillForBot("bot-a", "rex")).toEqual({ removed: true });+ expect(isNativeSkillEnabled("bot-a", "rex")).toBe(false);+ // The same removal for a bot whose native switch was already off: switching the import back on does not override it.+ expect(removeImportedSkillForBot("bot-b", "rex")).toEqual({ removed: true });+ setNativeSkillEnabled("bot-b", "rex", false);+ expect(setImportedSkillEnabled("bot-a", "rex", true)).not.toHaveProperty("error");+ expect(isNativeSkillEnabled("bot-a", "rex")).toBe(true);+ expect(setImportedSkillEnabled("bot-b", "rex", true)).not.toHaveProperty("error");+ expect(isNativeSkillEnabled("bot-b", "rex")).toBe(false);+ });});diff --git a/server/native-skill-choices.ts b/server/native-skill-choices.tsindex 78eebfd574..54bac82f17 100644--- a/server/native-skill-choices.ts+++ b/server/native-skill-choices.ts@@ -6,7 +6,7 @@ import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";import { DATA_DIR } from "./config.ts";-import { importedSkillsSwitchedOff, readImportedSkills, switchImportedSkillBackOn } from "./imported-skills.ts";+import { importedSkillsSwitchedOff, readImportedSkills, removedImportedSkills, switchImportedSkillBackOn } from "./imported-skills.ts";import { isSkillName } from "../shared/skill-md.ts";const choicesPath = (botId: string) => join(DATA_DIR, "skill-state", botId, "native-skills.json");@@ -33,11 +33,11 @@ function readChoices(botId: string): string[] {return [];}-/** Native skills this bot has off: its own switches, plus each skill from this computer it switched off, with the- * SKILL.md it was brought in from, which an engine loading that folder would still read. */+/** Native skills this bot has off: its own switches, plus each skill from this computer it switched off or removed, with+ * the SKILL.md it was brought in from, which an engine loading that folder would still read. */export function deniedNativeSkills(botId: string): { names: string[]; origins: string[] } {const own = readChoices(botId);- const imported = importedSkillsSwitchedOff(botId);+ const imported = [...new Set([...importedSkillsSwitchedOff(botId), ...removedImportedSkills(botId)])];const index = readImportedSkills();const origins = imported.flatMap((name) => (index[name] ? [join(index[name].origin, "SKILL.md")] : []));return { names: [...new Set([...own, ...imported])].sort(), origins };diff --git a/server/routes/bot-skills.test.ts b/server/routes/bot-skills.test.tsindex f837cd820b..157ff8652f 100644--- a/server/routes/bot-skills.test.ts+++ b/server/routes/bot-skills.test.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, symlinkSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";@@ -7,6 +8,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { DATA_DIR, type AppConfig } from "../config.ts";import { provideGithubSignIn } from "../github/token.ts";import { json, readBody } from "../harness/http.ts";+import { IMPORTED_SKILLS_DIR, importedSkillListings, importedSkillsFor, readImportedSkillFile, readImportedSkills, storeImportedSkills } from "../imported-skills.ts";import { personKey } from "../person-key.ts";import type { RequestAuth } from "../request-auth.ts";import type { SessionRecord } from "../sessions.ts";@@ -243,11 +245,36 @@ describe("whose GitHub sign-in a bot import uses", () => {const learned = (name: string) => `---\nname: ${name}\ndescription: A skill.\n---\n\n# ${name}\n\nSteps.\n`;+/** One skill from this computer, kept in the real imported store; its source folder is made unless `withSource` is false. */+function storeImported(name: string, sourceFolder: string, withSource = true): string {+ const text = learned(name);+ if (withSource) {+ mkdirSync(sourceFolder, { recursive: true });+ writeFileSync(join(sourceFolder, "SKILL.md"), text);+ }+ expect(storeImportedSkills([{+ name,+ skillMd: text,+ files: [],+ entry: {+ description: "A skill.",+ source: "claudeCode",+ root: dirname(sourceFolder),+ origin: sourceFolder,+ label: sourceFolder,+ sha256: createHash("sha256").update(text).digest("hex"),+ warnings: [],+ },+ }])).toMatchObject([{ name, stored: true }]);+ return text;+}+describe("removing a skill from one bot", () => {- it("deletes a bot-owned skill, unassigns a shared one from that bot only, and refuses an imported one", async () => {+ it("deletes a bot-owned skill, unassigns a shared one from that bot only, removes an imported one for that bot, and clears a stale import", async () => {const owned = `owned-${Math.random().toString(36).slice(2, 8)}`;const shared = `shared-${Math.random().toString(36).slice(2, 8)}`;const brought = `brought-${Math.random().toString(36).slice(2, 8)}`;+ const stale = `stale-${Math.random().toString(36).slice(2, 8)}`;const first = `bot-${Math.random().toString(36).slice(2, 8)}`;const second = `bot-${Math.random().toString(36).slice(2, 8)}`;const third = `bot-${Math.random().toString(36).slice(2, 8)}`;@@ -260,6 +287,9 @@ describe("removing a skill from one bot", () => {expect(installSkill(first, "private:test", [{ path: "SKILL.md", content: learned(owned) }])).toMatchObject({ name: owned });expect(installLibrarySkill({ name: shared, instructions: text, source: "lib", reviewState: "approved" })).toMatchObject({ name: shared });expect(setLibrarySkillEveryBot(shared, true)).toMatchObject({ everyBot: true });+ const broughtSource = join(DATA_DIR, "test-source-skills", brought);+ const broughtText = storeImported(brought, broughtSource);+ storeImported(stale, join(DATA_DIR, "test-source-skills", stale), false);const store = {bot: (id: string) => bots.get(id),get bots() { return [...bots.values()]; },@@ -273,8 +303,8 @@ describe("removing a skill from one bot", () => {const routes = [createBotSkillsRoutes({store,cfg: { features: { skillsLibrary: true } } as AppConfig,- listBotSkills: () => [- { name: brought, origin: "imported" },+ listBotSkills: (bot) => [+ ...importedSkillListings(bot.id, new Set()),{ name: "engine-notes", origin: "native" },] as never,readBotSkillFile: () => null,@@ -293,6 +323,14 @@ describe("removing a skill from one bot", () => {const response = await fetch(`${base}${path}`, { method });return { status: response.status, body: await response.json() as { error?: string; skills?: Array<{ name: string }> } };};+ const patch = async (botId: string, name: string, enabled: boolean) => {+ const response = await fetch(`${base}/api/bots/${botId}/skills/${name}`, {+ method: "PATCH",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ enabled }),+ });+ return { status: response.status, body: await response.json() as { skill?: { name: string; enabled: boolean } } };+ };expect((await call("DELETE", `/api/bots/${first}/skills/${owned}`)).status).toBe(200);expect(listSkills(first).map((skill) => skill.name)).not.toContain(owned);@@ -306,9 +344,37 @@ describe("removing a skill from one bot", () => {expect(resolveBotSkills(third, []).map((skill) => skill.name)).toContain(shared);expect((await call("GET", `/api/bots/${first}/skills`)).body.skills?.map((skill) => skill.name)).not.toContain(shared);- const refused = await call("DELETE", `/api/bots/${first}/skills/${brought}`);- expect(refused.status).toBe(404);- expect(refused.body.error).toMatch(/can't be removed from one bot/);+ const removed = await call("DELETE", `/api/bots/${first}/skills/${brought}`);+ expect(removed.status).toBe(200);+ expect(removed.body).toEqual({ ok: true, scope: "bot", sourceFilesTouched: false });+ expect(importedSkillListings(first, new Set()).map((skill) => skill.name)).not.toContain(brought);+ expect((await call("GET", `/api/bots/${first}/skills`)).body.skills?.map((skill) => skill.name)).not.toContain(brought);+ expect(importedSkillListings(second, new Set()).map((skill) => skill.name)).toContain(brought);+ expect(importedSkillsFor(second, new Set()).map((skill) => skill.name)).toContain(brought);+ expect(readImportedSkillFile(brought)).toBe(broughtText);+ expect(readFileSync(join(broughtSource, "SKILL.md"), "utf8")).toBe(broughtText);+ expect(readImportedSkills()[brought]).toBeDefined();+ // The one copy every bot shares is only cleared when its source folder is gone.+ const kept = await call("DELETE", `/api/bots/${second}/skills/${brought}?scope=all-bots`);+ expect(kept.status).toBe(409);+ expect(kept.body.error).toMatch(/still has its source folder/);+ expect(readImportedSkills()[brought]).toBeDefined();++ const cleared = await call("DELETE", `/api/bots/${first}/skills/${stale}?scope=all-bots`);+ expect(cleared.status).toBe(200);+ expect(cleared.body).toEqual({ ok: true, scope: "all-bots", sourceFilesTouched: false });+ expect(readImportedSkills()[stale]).toBeUndefined();+ expect(existsSync(join(IMPORTED_SKILLS_DIR, stale))).toBe(false);+ expect((await call("GET", `/api/bots/${second}/skills`)).body.skills?.map((skill) => skill.name)).not.toContain(stale);++ // The switch still works for an imported skill another bot keeps, and brings one back to the bot it was removed from.+ expect(await patch(second, brought, false)).toMatchObject({ status: 200, body: { skill: { name: brought, enabled: false } } });+ expect(importedSkillsFor(second, new Set()).map((skill) => skill.name)).not.toContain(brought);+ expect(await patch(second, brought, true)).toMatchObject({ status: 200, body: { skill: { name: brought, enabled: true } } });+ expect(importedSkillsFor(second, new Set()).map((skill) => skill.name)).toContain(brought);+ expect(await patch(first, brought, true)).toMatchObject({ status: 200, body: { skill: { name: brought, enabled: true } } });+ expect(importedSkillListings(first, new Set()).map((skill) => skill.name)).toContain(brought);+const native = await call("DELETE", `/api/bots/${first}/skills/engine-notes`);expect(native.status).toBe(404);expect(native.body.error).toMatch(/can't be removed here/);@@ -320,12 +386,12 @@ describe("removing a skill from one bot", () => {body: JSON.stringify({ skills: [shared] }),});expect(put.status).toBe(200);- const cleared = await fetch(`${base}/api/bots/${first}/skills-library`, {+ const clearedAssignments = await fetch(`${base}/api/bots/${first}/skills-library`, {method: "PUT",headers: { "content-type": "application/json" },body: JSON.stringify({ skills: [] }),});- expect(cleared.status).toBe(200);+ expect(clearedAssignments.status).toBe(200);expect(resolveBotSkills(first, []).map((skill) => skill.name)).toContain(shared);});diff --git a/server/routes/bot-skills.ts b/server/routes/bot-skills.tsindex 8a496920ff..d938c8cece 100644--- a/server/routes/bot-skills.ts+++ b/server/routes/bot-skills.ts@@ -2,7 +2,7 @@ import { z } from "zod";import type { SkillsLibrarySkillWire } from "../../shared/wire.ts";import type { AppConfig } from "../config.ts";-import { setImportedSkillEnabled } from "../imported-skills.ts";+import { purgeImportedSkill, readImportedSkills, removeImportedSkillForBot, setImportedSkillEnabled } from "../imported-skills.ts";import { setNativeSkillEnabled } from "../native-skill-choices.ts";import { botSkillTemplateSchema } from "../new-bot-defaults.ts";import { fetchSkillFromSource, skillImportToken } from "../skill-fetch.ts";@@ -93,8 +93,9 @@ export function createBotSkillsRoutes(deps: BotSkillsRouteDeps): RouteHandler {const parsed = z.object({ enabled: z.boolean() }).safeParse(await readBody(req));if (!parsed.success) return json(res, 400, { error: "enabled must be true or false" });const bot = store.bot(m[1]);- // A skill from this computer that none of the bot's own or library skills shadows: this bot's switch for it.- if (bot && listBotSkills(bot).some((skill) => skill.name === m![2] && (skill as { origin?: string }).origin === "imported")) {+ const shown = bot ? listBotSkills(bot).find((skill) => skill.name === m![2]) : undefined;+ // A skill from this computer, listed or removed from this bot, that none of its own or library skills shadows.+ if (bot && (shown ? (shown as { origin?: string }).origin === "imported" : Boolean(readImportedSkills()[m![2]!]))) {const result = setImportedSkillEnabled(bot.id, m[2]!, parsed.data.enabled);if ("error" in result) return json(res, 409, { error: result.error });return json(res, 200, { skill: result });@@ -125,7 +126,19 @@ export function createBotSkillsRoutes(deps: BotSkillsRouteDeps): RouteHandler {}}const origin = (listBotSkills(bot).find((skill) => skill.name === name) as { origin?: string } | undefined)?.origin;- if (origin === "imported") return json(res, 404, { error: `"${name}" comes from this computer and can't be removed from one bot. Turn it off instead.` });+ if (origin === "imported") {+ const scope = url.searchParams.get("scope");+ if (scope !== null && scope !== "bot" && scope !== "all-bots") return json(res, 400, { error: "scope must be bot or all-bots" });+ if (scope === "all-bots") {+ const purged = purgeImportedSkill(name);+ if ("error" in purged) return json(res, 409, { error: purged.error });+ removeImportedSkillForBot(bot.id, name);+ return json(res, 200, { ok: true, scope: "all-bots", sourceFilesTouched: false });+ }+ const removedForBot = removeImportedSkillForBot(bot.id, name);+ if ("error" in removedForBot) return json(res, 404, { error: removedForBot.error });+ return json(res, 200, { ok: true, scope: "bot", sourceFilesTouched: false });+ }if (origin === "native") return json(res, 404, { error: `"${name}" comes from this bot's engine and can't be removed here.` });return json(res, 404, { error: removed.error });}diff --git a/server/setup-import.e2e.test.ts b/server/setup-import.e2e.test.tsindex 3c73e8e778..cd3833df28 100644--- a/server/setup-import.e2e.test.ts+++ b/server/setup-import.e2e.test.ts@@ -159,8 +159,11 @@ describe("bringing in another AI tool's setup through the desktop app's own servconst told = await turn(later, "Review it");expect(told.system).not.toContain("review-pr");expect(told.linked(".agents", "review-pr")).toBeNull();- // There is one copy for all bots: nothing here deletes it.- expect((await api("DELETE", `/api/bots/${later.id}/skills/review-pr`)).status).toBe(404);+ // Removing it here leaves the one shared copy, and every other bot, alone; switching it on here brings it back.+ const removed = await api("DELETE", `/api/bots/${later.id}/skills/review-pr`);+ expect(removed.status).toBe(200);+ expect(JSON.parse(removed.text)).toEqual({ ok: true, scope: "bot", sourceFilesTouched: false });+ expect(await enabled(later.id)).toEqual({ "release-notes": true });expect((await api("PATCH", "/api/config", { features: { skillsLibrary: true } })).status).toBe(200);expect(await enabled(starter.id)).toEqual({ "release-notes": true, "review-pr": true });expect((await api("PATCH", `/api/bots/${later.id}/skills/review-pr`, { enabled: true })).status).toBe(200);diff --git a/server/skill-switch.ts b/server/skill-switch.tsindex 96958e32ae..4a03b1216a 100644--- a/server/skill-switch.ts+++ b/server/skill-switch.ts@@ -40,7 +40,7 @@ export function skillSwitchTarget(return { error: `skill "${name}" is shared with this bot, not its own; only the person can change it, in the bot's Skills settings` };}if (action === "delete" && skill.kind === "imported") {- return { error: `skill "${name}" comes from this computer and can't be deleted from one bot; turn it off instead (action "disable")` };+ return { error: `skill "${name}" comes from this computer and can't be deleted from one bot; turn it off instead (action "disable"), or the person can remove it in the bot's Skills settings` };}// Its scan warnings and helper files are reviewed in Settings, not on this card.if (action === "enable" && skill.kind === "imported") {diff --git a/src/components/SkillsSection.behavior.test.ts b/src/components/SkillsSection.behavior.test.tsindex e40298cb79..651297b67f 100644--- a/src/components/SkillsSection.behavior.test.ts+++ b/src/components/SkillsSection.behavior.test.ts@@ -125,16 +125,37 @@ describe("Skills library review and assignment controls", () => {expect(fixture.request).toHaveBeenCalledWith("/api/skills-library/order-audit", expect.objectContaining({ method: "PATCH", body: '{"enabled":true}' }));});- it("shows a skill from this computer with this bot's switch, and no way to delete the one copy every bot shares", async () => {- const imported = { name: "pdf", description: "Works with PDFs", enabled: true, source: "~/.claude/skills/pdf", warnings: [], origin: "imported" };+ it("shows a skill from this computer with this bot's switch, and removes it from this bot after saying what stays", async () => {+ const imported = { name: "pdf", description: "Works with PDFs", enabled: true, source: "~/.claude/skills/pdf", warnings: [], origin: "imported", sourceGone: false };fixture.values = [[imported], [], [], "", [], false, "", "", null, { current: false }, "", null, "", false, ""];- fixture.request.mockImplementation(async (_url, options) => options?.method ? {} : { text: source });+ fixture.request.mockImplementation(async (url: string, options?: RequestInit) => options?.method ? {} : url.endsWith("/skills") ? { skills: [imported] } : { text: source });const tree = render(true);- expect(tree.find((node) => node.props["aria-label"] === "Remove pdf")).toBeUndefined();expect(tree.some((node) => node.props.children === "this computer")).toBe(true);named(tree, "Disable pdf").props.onClick!();await flush();expect(fixture.request).toHaveBeenCalledWith("/api/bots/bot/skills/pdf", expect.objectContaining({ method: "PATCH", body: '{"enabled":false}' }));+ const confirm = vi.fn(() => false);+ vi.stubGlobal("window", { confirm });+ named(render(true), "Remove pdf").props.onClick!();+ expect(confirm).toHaveBeenCalledWith("Remove “pdf” from this bot? OpenMausBot's imported copy stays for your other bots, and the files on your computer are not touched.");+ expect(fixture.request).not.toHaveBeenCalledWith("/api/bots/bot/skills/pdf", { method: "DELETE" });+ vi.stubGlobal("window", { confirm: vi.fn(() => true) });+ named(render(true), "Remove pdf").props.onClick!();+ await flush();+ expect(fixture.request).toHaveBeenCalledWith("/api/bots/bot/skills/pdf", { method: "DELETE" });+ vi.unstubAllGlobals();+ });+ it("clears a skill from this computer whose source folder is gone, for every bot", async () => {+ const stale = { name: "pdf", description: "Works with PDFs", enabled: true, source: "~/.claude/skills/pdf", warnings: [], origin: "imported", sourceGone: true };+ fixture.values = [[stale], [], [], "", [], false, "", "", null, { current: false }, "", null, "", false, ""];+ fixture.request.mockImplementation(async (url: string, options?: RequestInit) => options?.method ? {} : url.endsWith("/skills") ? { skills: [stale] } : { text: source });+ const confirm = vi.fn(() => true);+ vi.stubGlobal("window", { confirm });+ named(render(true), "Remove pdf").props.onClick!();+ expect(confirm).toHaveBeenCalledWith("Remove “pdf” from OpenMausBot? Its source folder is gone, so OpenMausBot's imported copy is removed for every bot. No files on your computer are touched.");+ await flush();+ expect(fixture.request).toHaveBeenCalledWith("/api/bots/bot/skills/pdf?scope=all-bots", { method: "DELETE" });+ vi.unstubAllGlobals();});it("puts one of the bot's own skills on all bots, and marks one already there with this bot's own switch", async () => {const own = { name: "invoice-check", description: "Checks invoices", enabled: true, source: "learned:conversation", warnings: [], canUseOnAllBots: true };diff --git a/src/components/bot-settings/SkillsSection.tsx b/src/components/bot-settings/SkillsSection.tsxindex 4062e859c3..3d96e822c2 100644--- a/src/components/bot-settings/SkillsSection.tsx+++ b/src/components/bot-settings/SkillsSection.tsx@@ -20,7 +20,7 @@ export interface ManagedSkill {enabled: boolean;source: string;warnings: string[];- /** "imported": one copy brought in from this computer for every bot, switched per bot and never removed from one.+ /** "imported": one copy brought in from this computer for every bot, switched per bot and removable from one bot.* "native": loaded by the bot's engine from a skills folder of its own; changed only there.* "project": shipped in the folder the bot works in; used while the owner trusts project skills, changed only there. */origin?: "private" | "library" | "all-bots" | "imported" | "native" | "project";@@ -29,6 +29,8 @@ export interface ManagedSkill {canUseOnAllBots?: boolean;/** An imported skill that is on but not in this bot's list: the bot finds it when a task needs it. */listed?: boolean;+ /** An imported copy whose source folder is gone: removing it clears OpenMausBot's copy for every bot. */+ sourceGone?: boolean;}/** On all of the person's bots, with this bot's own switch. */@@ -367,6 +369,21 @@ export function SkillsSection({ bot }: { bot: Bot }) {}, [bot.id]);const remove = async (skill: ManagedSkill) => {+ if (skill.origin === "imported") {+ const stale = skill.sourceGone === true;+ if (!window.confirm(t(stale ? "skills.imported.removeStaleConfirm" : "skills.imported.removeConfirm", { name: skill.name }))) return;+ setWorking(skill.name);+ setError("");+ try {+ await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}${stale ? "?scope=all-bots" : ""}`, { method: "DELETE" });+ await refresh();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : t("skills.error.remove"));+ } finally {+ setWorking("");+ }+ return;+ }if (skill.origin === "library") {if (assignmentBusy.current) return;if (!window.confirm(t("skills.unassignConfirm", { name: skill.name }))) return;@@ -544,7 +561,7 @@ export function SkillsSection({ bot }: { bot: Bot }) {<Users size={15} /></button>)}- {skill.origin !== "imported" && !inFolder(skill) && (+ {!inFolder(skill) && (<buttonaria-label={t("skills.removeName", { name: skill.name })}title={t("skills.remove")}@@ -557,6 +574,7 @@ export function SkillsSection({ bot }: { bot: Bot }) {)}</div><div className="mt-1 truncate text-[11px] text-ink-secondary" title={skill.source}>{t("skills.source", { source: skill.source })}</div>+ {skill.sourceGone && <div className="mt-1 text-[11px] text-ink-secondary">{t("skills.imported.sourceGone")}</div>}{skill.warnings.length > 0 && (<div className="mt-1 text-[11px] text-warning">{skill.warnings.join(" · ")}</div>)}diff --git a/src/locales/en.json b/src/locales/en.jsonindex dc7c8054f3..65d2b1519d 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6530,6 +6530,9 @@"skills.learned.hintOff": "Skill authoring is off, but skills you already enabled stay under your control here.","skills.origin.imported": "this computer","skills.origin.importedHint": "Brought in from this computer. Each bot lists the ones that fit its role and finds the rest when a task needs them. Switch it on to list it for this bot, or off to keep it from this bot.",+ "skills.imported.sourceGone": "Its source folder no longer exists. OpenMausBot's copy still works.",+ "skills.imported.removeConfirm": "Remove “{name}” from this bot? OpenMausBot's imported copy stays for your other bots, and the files on your computer are not touched.",+ "skills.imported.removeStaleConfirm": "Remove “{name}” from OpenMausBot? Its source folder is gone, so OpenMausBot's imported copy is removed for every bot. No files on your computer are touched.","skills.origin.native": "AI","skills.origin.nativeHint": "The bot's AI loads this from the folder under Source. Turn it off here for this bot only; the files stay where they are.","skills.origin.project": "project",