diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index b0d7ec6d3ba64..5ee3608c17a94 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -56,6 +56,7 @@ import { normalizeCommandPath, resolveProviderMaintenanceCapabilitiesEffect, } from "../providerMaintenance.ts"; +import type { ServerProviderDraft } from "../providerSnapshot.ts"; import { haveProviderSnapshotSettingsChanged, makeProviderSnapshotSettingsSource, @@ -153,13 +154,16 @@ export const ClaudeDriver: ProviderDriver = { ? configDir : undefined, ); - const stampIdentity = withInstanceIdentity({ + const stampInstance = withInstanceIdentity({ instanceId, driverKind: DRIVER_KIND, displayName, accentColor, continuationGroupKey, }); + // The resolved config dir tells the Skills catalog where this instance's personal skills live. + const stampIdentity = (draft: ServerProviderDraft) => + stampInstance({ ...draft, runtimePaths: { homePath: configDir, shadowHomePath: null } }); // One per instance: the status probe writes the model-scoped bucket // names it saw, the adapter reads them to place turn-driven events. diff --git a/apps/server/src/workspace/SkillFiles.test.ts b/apps/server/src/workspace/SkillFiles.test.ts index 7c75b22103b28..372ca66dc0f11 100644 --- a/apps/server/src/workspace/SkillFiles.test.ts +++ b/apps/server/src/workspace/SkillFiles.test.ts @@ -188,6 +188,76 @@ describe("file skills catalog", () => { expect(result.skills).toEqual([]); }); + it("skips deleted skills a provider keeps in a hidden trash folder", async () => { + const trashed = NodePath.join(home, ".claude", "skills", ".trash", "1790310884383", "review"); + await NodeFSP.mkdir(trashed, { recursive: true }); + const file = NodePath.join(trashed, "SKILL.md"); + await NodeFSP.writeFile(file, "---\nname: review\n---\n"); + const result = await listSkillFiles( + { workspaceRoots: [] }, + [provider([{ name: "review", path: file, scope: "user", enabled: true }])], + home, + ); + expect(result.skills).toEqual([]); + }); + + it("labels a provider-reported skill by the folder it lives in", async () => { + const synced = NodePath.join(home, ".claude", "skills", "synced", "account-id", "docs"); + await NodeFSP.mkdir(synced, { recursive: true }); + const file = NodePath.join(synced, "SKILL.md"); + await NodeFSP.writeFile(file, "---\nname: docs\n---\n"); + const opencode = { + ...provider([{ name: "docs", path: file, scope: "user", enabled: true }]), + driver: ProviderDriverKind.make("opencode"), + }; + const result = await listSkillFiles({ workspaceRoots: [] }, [opencode], home); + expect(result.skills.map(({ name, source }) => [name, source])).toEqual([["docs", "claude"]]); + }); + + it("keeps personal skills from a provider's custom home", async () => { + const customHome = NodePath.join(home, ".codex-work"); + const file = NodePath.join(customHome, "skills", "review", "SKILL.md"); + await NodeFSP.mkdir(NodePath.dirname(file), { recursive: true }); + await NodeFSP.writeFile(file, "---\nname: review\n---\n"); + const codex = { + ...provider([{ name: "review", path: file, scope: "user", enabled: true }]), + runtimePaths: { homePath: customHome, shadowHomePath: null }, + }; + const result = await listSkillFiles({ workspaceRoots: [] }, [codex], home); + expect(result.skills.map(({ name, scope, source }) => [name, scope, source])).toEqual([ + ["review", "personal", "codex"], + ]); + }); + + it("ignores skills providers report from worktrees, other checkouts, and plugin caches", async () => { + const worktree = NodePath.join(home, ".t3", "worktrees", "app", "feature-1"); + const otherCheckout = NodePath.join(home, "Git", "other-repo"); + const pluginCache = NodePath.join(home, ".codex", "plugins", "cache", "vendor", "tool"); + const reported = await Promise.all([ + writeSkill(worktree, "from-worktree"), + writeSkill(otherCheckout, "from-other-repo"), + writeSkill(pluginCache, "from-plugin-cache"), + writeSkill(project, "from-selected-project"), + ]); + const result = await listSkillFiles( + { workspaceRoots: [project] }, + [ + provider( + reported.map((path) => ({ + name: NodePath.basename(NodePath.dirname(path)), + path, + scope: "user", + enabled: true, + })), + ), + ], + home, + ); + expect(result.skills.map(({ name, scope }) => [name, scope])).toEqual([ + ["from-selected-project", "project"], + ]); + }); + it("reports malformed or oversized frontmatter instead of silently showing a complete catalog", async () => { await writeSkill(project, "bad", "---\nname: [invalid\n---\n"); await writeSkill(project, "huge", "---\ndescription: " + "x".repeat(20_000) + "\n---\n"); diff --git a/apps/server/src/workspace/SkillFiles.ts b/apps/server/src/workspace/SkillFiles.ts index 899f06ade9c7d..dab51f23da060 100644 --- a/apps/server/src/workspace/SkillFiles.ts +++ b/apps/server/src/workspace/SkillFiles.ts @@ -62,8 +62,31 @@ function within(file: string, root: string) { !NodePath.isAbsolute(relative)) ); } -function builtin(file: string) { - return file.replaceAll("\\", "/").includes("/skills/.system/"); +/** + * Skills inside a hidden folder of a skills directory are not installed skills: `.system` holds + * provider built-ins and `.trash` holds deleted skills a provider keeps around. + */ +function hiddenSkillFile(file: string) { + const segments = file.replaceAll("\\", "/").split("/"); + const skillsIndex = segments.lastIndexOf("skills"); + return ( + skillsIndex >= 0 && segments.slice(skillsIndex + 1).some((segment) => segment.startsWith(".")) + ); +} + +/** + * The folder family a skill file lives in, such as `claude` for anything under `.claude/skills`. + * Providers also report skills from other tools' folders (OpenCode reads `~/.claude/skills`), so + * the folder, not the reporting provider, says where a skill comes from. + */ +function folderSource(file: string): string | null { + const normalized = file.replaceAll("\\", "/"); + let match: { readonly index: number; readonly source: string } | null = null; + for (const [folder, source] of PERSONAL_SKILL_FOLDERS) { + const index = normalized.lastIndexOf(`/${folder}/`); + if (index >= 0 && (match === null || index > match.index)) match = { index, source }; + } + return match?.source ?? null; } /** Limit open handles, not catalog size. Cancellation stops scheduling further disk reads. */ @@ -108,14 +131,22 @@ export async function listSkillFiles( })), ), ]; - const personalRoots = PERSONAL_SKILL_FOLDERS.map(([folder]) => NodePath.join(home, folder)); + // Providers can run from a custom home, such as `~/.codex-work`, whose skills folder is personal. + const personalRoots = [ + ...PERSONAL_SKILL_FOLDERS.map(([folder]) => NodePath.join(home, folder)), + ...providers.flatMap(({ runtimePaths }) => + [runtimePaths?.homePath, runtimePaths?.shadowHomePath].flatMap((providerHome) => + providerHome ? [NodePath.join(NodePath.resolve(providerHome), "skills")] : [], + ), + ), + ]; const addCandidate = (file: string, scope: FileSkill["scope"], source: string) => { - if (builtin(file)) return; + if (hiddenSkillFile(file)) return; const personal = personalRoots.some((root) => within(file, root)); const previous = candidates.get(file); candidates.set(file, { scope: personal || previous?.scope === "personal" ? "personal" : scope, - source: previous?.source ?? source, + source: previous?.source ?? folderSource(file) ?? source, }); }; await forEachConcurrent( @@ -151,17 +182,13 @@ export async function listSkillFiles( } if (!provider.enabled || !provider.installed) continue; providerPaths.add(file); - const homeSkill = - within(file, home) && !roots.some((root) => root !== home && within(file, root)); - if ( - homeSkill && - !["project", "repo", "workspace", "local"].includes(skill.scope?.toLowerCase() ?? "") - ) { + // Providers report every skill they can see from wherever they run, including worktrees, + // other checkouts, and plugin caches under home. Only personal skill folders and the + // selected projects belong in this catalog. + if (personalRoots.some((root) => within(file, root))) { addCandidate(file, "personal", provider.driver); - } else if (roots.some((root) => within(file, root))) { + } else if (roots.some((root) => root !== home && within(file, root))) { addCandidate(file, "project", provider.driver); - } else if (["user", "personal"].includes(skill.scope?.toLowerCase() ?? "")) { - addCandidate(file, "personal", provider.driver); } } } @@ -182,7 +209,8 @@ export async function listSkillFiles( async ([file, location]) => { try { const canonical = await NodeFSP.realpath(file); - if (builtin(canonical) || excludedPaths.has(file) || excludedPaths.has(canonical)) return; + if (hiddenSkillFile(canonical) || excludedPaths.has(file) || excludedPaths.has(canonical)) + return; if (!(await NodeFSP.stat(file)).isFile()) return; const handle = await NodeFSP.open(file, "r"); let contents: string; diff --git a/apps/web/src/components/settings/SkillsSettings.tsx b/apps/web/src/components/settings/SkillsSettings.tsx index 65efcef891c7a..784fbe9edf2e9 100644 --- a/apps/web/src/components/settings/SkillsSettings.tsx +++ b/apps/web/src/components/settings/SkillsSettings.tsx @@ -1,17 +1,29 @@ import { normalizeSkillVisibilityPath } from "@t3tools/client-runtime/providerSkills"; import { CopyIcon, - EyeIcon, + FolderGit2Icon, FolderOpenIcon, PlusIcon, SearchIcon, + SparklesIcon, TriangleAlertIcon, + UserRoundIcon, } from "lucide-react"; -import { useEffect, useState } from "react"; +import { type CSSProperties, useEffect, useState } from "react"; import { useProjectFileQuery } from "../files/projectFilesQueryState"; import { writeTextToClipboard } from "../../hooks/useCopyToClipboard"; import { useSkillVisibility } from "../../hooks/useSkillVisibility"; +import { cn } from "../../lib/utils"; +import { + AntigravityIcon, + ClaudeAI, + CursorIcon, + GrokIcon, + type Icon, + OpenAI, + OpenCodeIcon, +} from "../Icons"; import { Switch } from "../ui/switch"; import { AddSkillDialog } from "./AddSkillDialog"; import { shellEnvironment } from "../../state/shell"; @@ -30,6 +42,179 @@ import { type SettingsSkill, type SkillEnvironmentTarget, } from "./projectSkillFiles"; +import { + groupSkills, + skillSourceKey, + type SkillGroup, + type SkillSourceKey, +} from "./skillPresentation"; + +// Each source gets its brand mark on a tile tinted with its own color, so a long list scans by +// where a skill comes from. Shared ~/.agents skills use the product accent. +const SOURCE_PRESENTATION: Readonly< + Record< + SkillSourceKey, + { readonly label: string; readonly tint: string; readonly icon: Icon | null } + > +> = { + agents: { label: "Shared", tint: "var(--color-primary)", icon: null }, + claude: { label: "Claude Code", tint: "#D97757", icon: ClaudeAI }, + codex: { label: "Codex", tint: "#10A37F", icon: OpenAI }, + cursor: { label: "Cursor", tint: "#8B93A7", icon: CursorIcon }, + opencode: { label: "OpenCode", tint: "#E0A030", icon: OpenCodeIcon }, + grok: { label: "Grok", tint: "#8B93A7", icon: GrokIcon }, + antigravity: { label: "Antigravity", tint: "#4285F4", icon: AntigravityIcon }, + other: { label: "Other", tint: "var(--color-muted-foreground)", icon: null }, +}; + +function SkillSourceTile({ source }: { readonly source: string }) { + const presentation = SOURCE_PRESENTATION[skillSourceKey(source)]; + const SourceIcon = presentation.icon ?? SparklesIcon; + return ( + + + + ); +} + +function SkillSourceLabel({ source }: { readonly source: string }) { + const key = skillSourceKey(source); + const presentation = SOURCE_PRESENTATION[key]; + return ( + + {key === "other" ? source : presentation.label} + + ); +} + +function SkillGroupHeader({ group }: { readonly group: SkillGroup }) { + const GroupIcon = group.kind === "personal" ? UserRoundIcon : FolderGit2Icon; + return ( +
+ + {group.label} + {group.environmentLabel ? · {group.environmentLabel} : null} + {group.skills.length} +
+ ); +} + +function SkillRow({ + skill, + visible, + canReveal, + onPreview, + onVisibleChange, + onCopyPath, + onReveal, +}: { + readonly skill: SkillGroup["skills"][number]; + readonly visible: boolean; + readonly canReveal: boolean; + readonly onPreview: () => void; + readonly onVisibleChange: (visible: boolean) => void; + readonly onCopyPath: () => void; + readonly onReveal: () => void; +}) { + return ( +
+ +
+
+ + + + + } + /> + Copy path + + {canReveal ? ( + + + + + } + /> + Reveal in file manager + + ) : null} +
+ + + } + /> + + {visible ? "Shown in skill pickers" : "Hidden from skill pickers"} + + +
+
+ ); +} function SkillPreview({ skill, cwd }: { skill: SettingsSkill; cwd: string }) { const file = useProjectFileQuery(skill.environmentId, cwd, skill.path); @@ -104,7 +289,7 @@ export function SkillsSettings() { (value) => value.toLowerCase().includes(normalizedQuery), ), ); - const multipleEnvironments = targets.length > 1; + const groups = groupSkills(filtered, targets); const revealableEnvironments = new Set( connectedEnvironments .filter((environment) => environment.serverConfig?.shellRevealInFileManager === true) @@ -197,107 +382,49 @@ export function SkillsSettings() { : "No skills in your home folders or selected projects"}

) : ( - filtered.map((skill) => { - const visible = !skill.aliases.some((alias) => - (hiddenByEnvironment[skill.environmentId] ?? []).some( - (hidden) => - normalizeSkillVisibilityPath(hidden) === normalizeSkillVisibilityPath(alias), - ), - ); - return ( -
-
- - - {skill.scope === "project" ? "Project" : "Personal"} - - - {skill.source} - - - - setVisible(skill.environmentId, skill.aliases, checked) - } - /> - } - /> - - {visible ? "Shown in skill pickers" : "Hidden from skill pickers"} - - -
- {skill.description ? ( -

{skill.description}

- ) : null} -
-

- {skill.path} -

- {multipleEnvironments ? ( - - {skill.environmentLabel} - - ) : null} - - - {revealableEnvironments.has(skill.environmentId) ? ( - - ) : null} -
-
- ); - }) + onReveal={() => { + void openInEditor({ + environmentId: skill.environmentId, + input: { cwd: skill.path, editor: "file-manager", reveal: true }, + }).then((result) => { + if (result._tag === "Failure") + toastManager.add({ type: "error", title: "Could not reveal skill" }); + }); + }} + /> + ); + })} + + )) )} {adding && ( diff --git a/apps/web/src/components/settings/skillPresentation.test.ts b/apps/web/src/components/settings/skillPresentation.test.ts new file mode 100644 index 0000000000000..02ac46d327fcb --- /dev/null +++ b/apps/web/src/components/settings/skillPresentation.test.ts @@ -0,0 +1,113 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { SettingsSkill } from "./projectSkillFiles"; +import { groupSkills, skillDisplayPath, skillSourceKey } from "./skillPresentation"; + +const local = EnvironmentId.make("local"); +const remote = EnvironmentId.make("remote"); + +function skill(overrides: Partial & Pick) { + return { + description: "", + aliases: [overrides.path], + source: "agents", + scope: "personal", + environmentId: local, + environmentLabel: "This Mac", + ...overrides, + } satisfies SettingsSkill; +} + +describe("skill presentation", () => { + it("shortens personal skill paths to the home dot-folder and drops SKILL.md", () => { + expect(skillDisplayPath({ path: "/Users/dev/.agents/skills/animate/SKILL.md" }, null)).toBe( + "~/.agents/skills/animate", + ); + }); + + it("collapses generated folder names such as synced account IDs", () => { + expect( + skillDisplayPath( + { + path: "/Users/dev/.claude/skills/synced/9ee4f194-76ea-4cf9-b250-c1a540fcd1b3_0216b96c-134a-45c0-af50-4c78f19e6d11/docs/SKILL.md", + }, + null, + ), + ).toBe("~/.claude/skills/synced/…/docs"); + }); + + it("shows project skill paths from the project folder", () => { + expect( + skillDisplayPath( + { path: "/Users/dev/Git/t3code/.claude/skills/review/SKILL.md" }, + { root: "/Users/dev/Git/t3code", label: "t3code" }, + ), + ).toBe("t3code/.claude/skills/review"); + }); + + it("tells apart selected projects that share a folder name", () => { + const groups = groupSkills( + [ + skill({ + name: "one", + path: "/src/one/app/.agents/skills/review/SKILL.md", + scope: "project", + }), + skill({ + name: "two", + path: "/src/two/app/.agents/skills/review/SKILL.md", + scope: "project", + }), + ], + [ + { + environmentId: local, + environmentLabel: "This Mac", + workspaceRoots: ["/src/one/app", "/src/two/app", "/src/solo"], + }, + ], + ); + + expect(groups.map((group) => [group.label, group.skills[0]?.displayPath])).toEqual([ + ["one/app", "one/app/.agents/skills/review"], + ["two/app", "two/app/.agents/skills/review"], + ]); + }); + + it("puts personal skills first, then one group per project and environment", () => { + const targets = [ + { environmentId: local, environmentLabel: "This Mac", workspaceRoots: ["/repo/app"] }, + { environmentId: remote, environmentLabel: "Devbox", workspaceRoots: ["/srv/app"] }, + ]; + const groups = groupSkills( + [ + skill({ name: "ship", path: "/repo/app/.agents/skills/ship/SKILL.md", scope: "project" }), + skill({ name: "animate", path: "/Users/dev/.agents/skills/animate/SKILL.md" }), + skill({ + name: "deploy", + path: "/srv/app/.codex/skills/deploy/SKILL.md", + scope: "project", + source: "codex", + environmentId: remote, + environmentLabel: "Devbox", + }), + ], + targets, + ); + + expect( + groups.map((group) => [group.label, group.environmentLabel, group.skills.map((s) => s.name)]), + ).toEqual([ + ["Personal", "This Mac", ["animate"]], + ["app", "Devbox", ["deploy"]], + ["app", "This Mac", ["ship"]], + ]); + }); + + it("maps folder families and provider drivers to one source presentation", () => { + expect(skillSourceKey("claude")).toBe("claude"); + expect(skillSourceKey("claudeAgent")).toBe("claude"); + expect(skillSourceKey("hermes")).toBe("other"); + }); +}); diff --git a/apps/web/src/components/settings/skillPresentation.ts b/apps/web/src/components/settings/skillPresentation.ts new file mode 100644 index 0000000000000..ea1554f986e41 --- /dev/null +++ b/apps/web/src/components/settings/skillPresentation.ts @@ -0,0 +1,156 @@ +import type { SettingsSkill, SkillEnvironmentTarget } from "./projectSkillFiles"; + +export type SkillSourceKey = + | "agents" + | "claude" + | "codex" + | "cursor" + | "opencode" + | "grok" + | "antigravity" + | "other"; + +/** Folder families and provider drivers that report skills, keyed to one presentation. */ +const SOURCE_KEYS: Readonly> = { + agents: "agents", + claude: "claude", + claudeAgent: "claude", + codex: "codex", + cursor: "cursor", + opencode: "opencode", + grok: "grok", + antigravity: "antigravity", +}; + +export function skillSourceKey(source: string): SkillSourceKey { + return SOURCE_KEYS[source] ?? "other"; +} + +function normalize(path: string) { + return path.replaceAll("\\", "/").replace(/\/+$/u, ""); +} + +/** + * The shortest trailing part of a project root that no other selected root in its environment + * ends with, so `~/Git/app` and `~/work/app` read as `Git/app` and `work/app`. + */ +function projectLabel(root: string, roots: ReadonlyArray) { + const segments = normalize(root).split("/"); + const others = roots.map(normalize).filter((other) => other !== normalize(root)); + for (let count = 1; count < segments.length; count++) { + const suffix = segments.slice(-count).join("/"); + if (!others.some((other) => other === suffix || other.endsWith(`/${suffix}`))) return suffix; + } + return normalize(root); +} + +/** The project root that holds a project skill, or null for personal skills and strays. */ +function skillProjectRoot( + skill: Pick, + targets: ReadonlyArray>, +): string | null { + if (skill.scope !== "project") return null; + const path = normalize(skill.path); + const roots = targets + .filter((target) => target.environmentId === skill.environmentId) + .flatMap((target) => target.workspaceRoots) + .filter((root) => path.startsWith(`${normalize(root)}/`)); + // The deepest root wins when projects nest. + return roots.toSorted((left, right) => right.length - left.length)[0] ?? null; +} + +// Generated folder names, like the account IDs Claude uses for skills it syncs from claude.ai. +const GENERATED_SEGMENT = /^[\da-f]{8}-[\da-f-]{20,}$/iu; + +function collapseGeneratedSegments(path: string) { + return path + .split("/") + .map((segment) => (GENERATED_SEGMENT.test(segment.split("_")[0] ?? "") ? "…" : segment)) + .join("/"); +} + +/** + * A short location for a row: `~/.agents/skills/review` for personal skills and + * `project/.claude/skills/review` for project skills. The file name is implied. + */ +export function skillDisplayPath( + skill: Pick, + project: { readonly root: string; readonly label: string } | null, +) { + const path = normalize(skill.path).replace(/\/SKILL\.md$/iu, ""); + if (project !== null) { + return collapseGeneratedSegments( + `${project.label}/${path.slice(normalize(project.root).length + 1)}`, + ); + } + // Personal skills live in a dot-folder of the server's home, which this client does not know. + const segments = path.split("/"); + const dotFolder = segments.findIndex((segment) => segment.startsWith(".")); + return collapseGeneratedSegments( + dotFolder > 0 ? `~/${segments.slice(dotFolder).join("/")}` : path, + ); +} + +export interface SkillGroup { + readonly key: string; + readonly label: string; + readonly kind: "personal" | "project"; + readonly environmentLabel: string | null; + readonly skills: ReadonlyArray; +} + +/** + * Personal skills first, then one group per project, each per environment when more than one + * environment is in scope. Projects that share a folder name are labeled by enough of their + * path to tell them apart. Skills keep their incoming order within a group. + */ +export function groupSkills( + skills: ReadonlyArray, + targets: ReadonlyArray< + Pick + >, +): SkillGroup[] { + const multipleEnvironments = targets.length > 1; + const groups = new Map< + string, + { + key: string; + label: string; + kind: "personal" | "project"; + environmentLabel: string | null; + skills: Array; + } + >(); + for (const skill of skills) { + const projectRoot = skillProjectRoot(skill, targets); + const project = + projectRoot === null + ? null + : { + root: projectRoot, + label: projectLabel( + projectRoot, + targets + .filter((target) => target.environmentId === skill.environmentId) + .flatMap((target) => target.workspaceRoots), + ), + }; + const kind = project === null ? "personal" : "project"; + const key = JSON.stringify([skill.environmentId, projectRoot]); + const group = groups.get(key) ?? { + key, + label: project?.label ?? "Personal", + kind, + environmentLabel: multipleEnvironments ? skill.environmentLabel : null, + skills: [], + }; + group.skills.push({ ...skill, displayPath: skillDisplayPath(skill, project) }); + groups.set(key, group); + } + return [...groups.values()].toSorted( + (left, right) => + Number(left.kind === "project") - Number(right.kind === "project") || + (left.environmentLabel ?? "").localeCompare(right.environmentLabel ?? "") || + left.label.localeCompare(right.label), + ); +}