feat(agents): native GitHub skill browser, preview, static scan, and installer (#5157)

Settings › Agents › Skills gets Install Skill…: enter a GitHub source in the forms `npx skills add` accepts (`owner/repo`, `owner/repo@skill`, `owner/repo#ref`, `owner/repo/path[@ref]`, GitHub tree URLs, pasted skills.sh links), pick one of the skills found, preview its `SKILL.md` and file list, and install it into `~/.agents/skills` (default) or the workspace `.agents/skills` (trusted projects only). Sources resolve through GitHub's Git Trees and Blobs APIs over the existing `ide-tools` HTTP client, with no curated repository list and no Node or git dependency, retrying unauthenticated when an ambient GitHub token gets HTTP 401 on a public repository. Only the selected skill's subtree is downloaded (capped at 2 MiB / 256 files) and installed atomically through a staging folder. A static scan flags hidden or bidirectional Unicode, out-of-root symlinks (omitted on disk), executable scripts and `allowed-tools` shell grants; the user must confirm the warnings, and the backend checks that confirmation again before writing.

Part of #5115

Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com>
This commit is contained in:
Deng Liu
2026-11-22 15:09:01 +08:00
committed by GitHub
co-authored by dengliu
parent b7ac5f1bbb
commit 0800e8445f
16 changed files with 2504 additions and 5 deletions
Generated
+1
View File
@@ -4146,6 +4146,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
name = "ide-agent"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"encoding_rs",
+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
encoding_rs.workspace = true
base64.workspace = true
blake3.workspace = true
ide-vfs.workspace = true
ide-core.workspace = true
+5
View File
@@ -23,6 +23,7 @@ mod provider;
pub mod registry;
pub mod security;
mod shell;
pub mod skill_installer;
pub mod skills;
mod timeline;
mod worktree;
@@ -31,6 +32,10 @@ pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
pub use model::*;
pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
};
use conversation::{Conversation, SavedSubagent, Session};
use ide_core::{IdeError, IdeResult, IpcPath};
File diff suppressed because it is too large Load Diff
+114 -2
View File
@@ -8,8 +8,9 @@ use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1116,6 +1117,114 @@ pub fn agent_skills_set_mode(
))
}
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
#[command(trust = always)]
pub async fn agent_skills_browse(
host: &Host,
source: String,
request: RequestId,
) -> IdeResult<RemoteSkillBrowseResult> {
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel)
})
.await
.map_err(join_err);
host.end_request(request);
res?
}
/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation.
#[command(trust = always)]
pub async fn agent_skills_preview(
host: &Host,
window: &str,
owner: String,
repo: String,
git_ref: String,
subpath: String,
request: RequestId,
) -> IdeResult<RemoteSkillPreview> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
let search_path = ide_core::tool_path::search_path();
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::preview_skill(
&fetcher,
ide_agent::skill_installer::RepoRef { owner: &owner, repo: &repo, git_ref: &git_ref },
&subpath,
home.as_deref(),
ws_root.as_deref(),
&cancel,
)
})
.await
.map_err(join_err);
host.end_request(request);
res?
}
/// Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace).
#[command(trust = always)]
pub async fn agent_skills_install(
host: &Host,
window: &str,
input: InstallRemoteSkillRequest,
request: RequestId,
) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = dirs::home_dir();
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let install_home = home.clone();
let install_ws = ws_root.clone();
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::install_skill(
&fetcher,
&input,
install_home.as_deref(),
install_ws.as_deref(),
&cancel,
)
})
.await
.map_err(join_err);
host.end_request(request);
res??;
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
let policy = host_skills_policy(host, project.as_deref());
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.map_err(join_err)?
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
fn skills_maps(
host: &Host,
@@ -1364,7 +1473,10 @@ ide_command::domain!(
agent_set_env,
agent_set_mcp_overrides,
agent_set_skill_overrides,
agent_skills_browse,
agent_skills_install,
agent_skills_list,
agent_skills_preview,
agent_skills_set_mode,
agent_stop_background,
agent_subscribe,
+7
View File
@@ -405,6 +405,13 @@ impl Http {
self
}
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
pub fn without_github_auth(mut self) -> Self {
self.gh = None;
self.explicit_github_token = None;
self
}
fn base(&self, url: &str, cancel: &CancellationToken) -> IdeResult<(Command, Option<String>)> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
+111
View File
@@ -206,6 +206,90 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
);
return skills;
};
handlers.agent_skills_browse = () => ({
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
truncated: false,
skills: [
{ folderName: "find-skills", subpath: "skills/find-skills", fileCount: 2, totalBytes: 1420 },
{ folderName: "web-design-audit", subpath: "skills/web-design-audit", fileCount: 1, totalBytes: 860 },
],
});
handlers.agent_skills_preview = ({ subpath }) =>
subpath === "skills/web-design-audit"
? {
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
subpath: "skills/web-design-audit",
skillName: "web-design-audit",
description: "Audit responsive layout and contrast tokens",
skillMarkdown:
"---\nname: web-design-audit\ndescription: Audit responsive layout and contrast tokens\n---\n\nCheck spacing and contrast tokens.\n",
files: [{ path: "SKILL.md", size: 860, executable: false, symlink: false }],
scanWarnings: [],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
}
: {
owner: "vercel-labs",
repo: "agent-skills",
gitRef: "main",
treeSha: "9f8e7d6c",
subpath: "skills/find-skills",
skillName: "find-skills",
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
skillMarkdown:
"---\nname: find-skills\ndescription: Discover reusable SKILL.md workflows and inspect bundled scripts\nallowed-tools:\n - Bash(gh:*)\n---\n\nInspect candidate SKILL.md files before installing.\n",
files: [
{ path: "SKILL.md", size: 980, executable: false, symlink: false },
{ path: "scripts/inspect.sh", size: 440, executable: true, symlink: false },
],
scanWarnings: [
{
kind: "executableScript",
file: "scripts/inspect.sh",
message: "Contains executable file mode (100755)",
},
{
kind: "allowedToolsShell",
file: "SKILL.md",
message: "`allowed-tools` grants shell/command execution (`Bash(gh:*)`)",
},
],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
};
handlers.agent_skills_install = ({ input }) => {
const req = input as { subpath: string; scope: "user" | "workspace" };
const installedName = req.subpath.endsWith("web-design-audit") ? "web-design-audit" : "find-skills";
skills = [
...skills,
{
skill: {
name: installedName,
description: "Discover reusable SKILL.md workflows and inspect bundled scripts",
hint: null,
path:
req.scope === "workspace"
? `/dev/openidea/.agents/skills/${installedName}`
: `/Users/dev/.agents/skills/${installedName}`,
source: req.scope === "workspace" ? "workspace" : "user",
alsoIn: [],
userInvocable: true,
disableModelInvocation: false,
valid: true,
warnings: [],
},
mode: "auto",
origin: "none",
},
];
return skills;
};
handlers.agent_set_skill_overrides = ({ overrides }) => {
currentTask = { ...currentTask, skillOverrides: overrides as Record<string, AgentSkillMode> };
return currentTask;
@@ -282,4 +366,31 @@ test("manages multi-level skills in Settings and per-session overrides via Compo
await settingsDialog.getByRole("tab", { name: /All Sources/ }).click();
await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills.png` });
}
// Open Install Skill… dialog, fetch repository, verify static scan warning gate, confirm, and install.
await settingsDialog.getByRole("button", { name: "Install Skill…" }).click();
const installDialog = page.getByRole("dialog", { name: "Install Agent Skill" });
await expect(installDialog).toBeVisible();
await installDialog.getByLabel("Skill repository").fill("vercel-labs/agent-skills");
await installDialog.getByRole("button", { name: "Fetch" }).click();
await expect(installDialog.getByText("Static security scan found 2 warnings")).toBeVisible();
const installBtn = installDialog.getByRole("button", { name: "Install", exact: true });
await expect(installBtn).toBeDisabled();
if (screenshotDir) {
await installDialog.screenshot({ path: `${screenshotDir}/after-install-skill-dialog.png` });
}
await installDialog.getByLabel("I reviewed these warnings and want to install this skill").click();
await expect(installBtn).toBeEnabled();
await installBtn.click();
await expect(installDialog).toHaveCount(0);
await settingsDialog.getByRole("tab", { name: /^User/ }).click();
await expect(settingsDialog.getByText("find-skills")).toBeVisible();
if (screenshotDir) {
await settingsDialog.screenshot({ path: `${screenshotDir}/after-settings-skills-installed.png` });
}
});
+3
View File
@@ -48,7 +48,10 @@ agent_set_env trusted project_host bin
agent_set_mcp_overrides always project_host bindings sync
agent_set_skill_overrides always project_host bindings sync
agent_shell trusted project_host bindings async
agent_skills_browse always project_host bindings async
agent_skills_install always project_host bindings async
agent_skills_list always project_host bindings async
agent_skills_preview always project_host bindings async
agent_skills_set_mode always project_host bindings sync
agent_stop_background always project_host bindings async
agent_subscribe always project_host bindings sync
+67
View File
@@ -150,11 +150,17 @@ export const commands = {
* starting a turn; its output goes to the agent with the next message.
*/
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
/** Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it. */
agentSkillsBrowse: (source: string, request: RequestId) => typedError<RemoteSkillBrowseResult, IdeError>(__TAURI_INVOKE("agent_skills_browse", { source, request })),
/** Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace). */
agentSkillsInstall: (input: InstallRemoteSkillRequest, request: RequestId) => typedError<AgentSkillState_Serialize[], IdeError>(__TAURI_INVOKE("agent_skills_install", { input, request })),
/**
* Every skill discovered in the project, the user's folders and enabled plugins, with
* the mode a session runs it with (without any session's own overrides).
*/
agentSkillsList: () => typedError<AgentSkillState_Serialize[], IdeError>(__TAURI_INVOKE("agent_skills_list")),
/** Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation. */
agentSkillsPreview: (owner: string, repo: string, gitRef: string, subpath: string, request: RequestId) => typedError<RemoteSkillPreview, IdeError>(__TAURI_INVOKE("agent_skills_preview", { owner, repo, gitRef, subpath, request })),
/**
* Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
* updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
@@ -7791,6 +7797,18 @@ export type InstallPreview = {
needsConsent: boolean,
};
export type InstallRemoteSkillRequest = {
owner: string,
repo: string,
gitRef: string,
subpath: string,
scope: McpScope,
/** Must be `true` when the static security scan produces any warnings. */
confirmWarnings?: boolean,
/** Must be `true` to replace an existing folder of the same name in `scope`. */
overwrite?: boolean,
};
/** The settings folder of a JetBrains IDE (or Android Studio) of this user. */
export type InstalledIdeSettings = {
/** The IDE and its version: `IntelliJ IDEA 2025.2`. */
@@ -10939,6 +10957,47 @@ export type RemoteSession = {
commands: string[],
};
export type RemoteSkillBrowseResult = {
owner: string,
repo: string,
gitRef: string,
treeSha: string,
truncated: boolean,
skills: RemoteSkillCandidate[],
};
export type RemoteSkillCandidate = {
/** Target folder name (`<name>` under `.agents/skills/<name>`). */
folderName: string,
/** Repository-relative directory holding `SKILL.md` (`""` when at repository root). */
subpath: string,
fileCount: number,
totalBytes: number,
};
export type RemoteSkillFile = {
/** Path relative to the skill folder (e.g. `"SKILL.md"`, `"scripts/check.sh"`). */
path: string,
size: number,
executable: boolean,
symlink: boolean,
};
export type RemoteSkillPreview = {
owner: string,
repo: string,
gitRef: string,
treeSha: string,
subpath: string,
skillName: string,
description: string,
skillMarkdown: string,
files: RemoteSkillFile[],
scanWarnings: SkillScanWarning[],
alreadyInstalledUser: boolean,
alreadyInstalledWorkspace: boolean,
};
/** Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload). */
export type RemoteStage = "connecting" |
/** `devcontainer up`: building or starting the container. */
@@ -11819,6 +11878,14 @@ export type SizeSource =
*/
"addressGaps" | "layout";
export type SkillScanWarning = {
kind: SkillScanWarningKind,
file: string,
message: string,
};
export type SkillScanWarningKind = "hiddenUnicode" | "outOfRootSymlink" | "executableScript" | "allowedToolsShell";
export type SkipReason =
/** A configuration with this name already exists. */
{ kind: "nameTaken" } |
+392
View File
@@ -0,0 +1,392 @@
import clsx from "clsx";
import { useCallback, useEffect, useRef, useState } from "react";
import type {
AgentSkillState,
McpScope,
RemoteSkillBrowseResult,
RemoteSkillCandidate,
RemoteSkillPreview,
RequestId,
SkillScanWarningKind,
} from "@/bindings";
import { formatMessage, useTx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { Button, Checkbox, Dialog, Icon, Input, Select, Tabs, T, selectableText } from "@/ui";
import type { SkillsBackend } from "./skillsModel";
import page from "./SettingsPage.module.css";
import styles from "./SkillsPage.module.css";
type PreviewTab = "markdown" | "files";
function formatBytes(bytes: number): string {
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
return `${bytes} B`;
}
const WARNING_KIND_LABELS: Record<SkillScanWarningKind, string> = {
hiddenUnicode: "Hidden Unicode",
outOfRootSymlink: "Out-of-root symlink",
executableScript: "Executable script",
allowedToolsShell: "Shell tool grant",
};
export function InstallSkillDialog({
backend,
hasTrustedProject,
onInstalled,
onClose,
}: {
backend: SkillsBackend;
hasTrustedProject: boolean;
onInstalled: (next: AgentSkillState[]) => void;
onClose: () => void;
}) {
const tx = useTx();
const [source, setSource] = useState("");
const [scope, setScope] = useState<McpScope>("user");
const [browseResult, setBrowseResult] = useState<RemoteSkillBrowseResult | null>(null);
const [selectedSubpath, setSelectedSubpath] = useState<string | null>(null);
const [preview, setPreview] = useState<RemoteSkillPreview | null>(null);
const [previewTab, setPreviewTab] = useState<PreviewTab>("markdown");
const [confirmedWarnings, setConfirmedWarnings] = useState(false);
const [overwrite, setOverwrite] = useState(false);
const [loading, setLoading] = useState(false);
const [installing, setInstalling] = useState(false);
const [error, setError] = useState<string | null>(null);
const activeReq = useRef<RequestId | null>(null);
const cancelInFlight = useCallback(() => {
if (activeReq.current != null) {
void commands.cancelRequest?.(activeReq.current);
activeReq.current = null;
}
}, []);
useEffect(() => () => cancelInFlight(), [cancelInFlight]);
const loadPreview = useCallback(
async (res: RemoteSkillBrowseResult, candidate: RemoteSkillCandidate) => {
if (!backend.preview) return;
cancelInFlight();
const req = nextRequestId();
activeReq.current = req;
setSelectedSubpath(candidate.subpath);
setPreview(null);
setConfirmedWarnings(false);
setOverwrite(false);
setError(null);
setLoading(true);
try {
const loaded = await backend.preview(res.owner, res.repo, res.gitRef, candidate.subpath, req);
if (activeReq.current === req) {
setPreview(loaded);
activeReq.current = null;
}
} catch (e: unknown) {
if (!isCancelled(e)) {
setError(e instanceof Error ? e.message : String(e));
}
} finally {
if (activeReq.current === req || activeReq.current == null) {
setLoading(false);
}
}
},
[backend, cancelInFlight],
);
const fetchRepository = useCallback(async () => {
const trimmed = source.trim();
if (!trimmed || !backend.browse) return;
cancelInFlight();
const req = nextRequestId();
activeReq.current = req;
setLoading(true);
setError(null);
setBrowseResult(null);
setPreview(null);
setSelectedSubpath(null);
setConfirmedWarnings(false);
setOverwrite(false);
try {
const res = await backend.browse(trimmed, req);
if (activeReq.current !== req) return;
activeReq.current = null;
setBrowseResult(res);
const first = res.skills[0];
if (first) {
await loadPreview(res, first);
} else {
setLoading(false);
}
} catch (e: unknown) {
if (!isCancelled(e)) {
setError(e instanceof Error ? e.message : String(e));
}
setLoading(false);
}
}, [backend, cancelInFlight, loadPreview, source]);
const alreadyExists =
preview != null && (scope === "workspace" ? preview.alreadyInstalledWorkspace : preview.alreadyInstalledUser);
const needsWarningConfirm = (preview?.scanWarnings.length ?? 0) > 0;
const canInstall =
!!preview &&
!loading &&
!installing &&
(!needsWarningConfirm || confirmedWarnings) &&
(!alreadyExists || overwrite);
const handleInstall = async () => {
if (!preview || !backend.install || !canInstall) return;
cancelInFlight();
const req = nextRequestId();
activeReq.current = req;
setInstalling(true);
setError(null);
try {
const next = await backend.install(
{
owner: preview.owner,
repo: preview.repo,
gitRef: preview.gitRef,
subpath: preview.subpath,
scope,
confirmWarnings: confirmedWarnings,
overwrite,
},
req,
);
activeReq.current = null;
onInstalled(next);
} catch (e: unknown) {
if (!isCancelled(e)) {
setError(e instanceof Error ? e.message : String(e));
}
} finally {
setInstalling(false);
}
};
const handleClose = () => {
cancelInFlight();
onClose();
};
return (
<Dialog
open
onClose={handleClose}
title={tx("Install Agent Skill")}
width={680}
buttons={[
{
label: installing ? "Installing…" : "Install",
role: "default",
disabled: !canInstall,
onClick: () => void handleInstall(),
},
{ label: "Cancel", role: "cancel", onClick: handleClose },
]}
>
<div className={styles.installBody}>
<p className={styles.hint}>
<T>
Enter a GitHub repository (owner/repo, owner/repo@skill, owner/repo/path@ref, or a GitHub URL). Only the
chosen skill folder is downloaded after preview and static scan.
</T>
</p>
<div className={styles.installSourceRow}>
<Input
className={styles.installSourceInput}
value={source}
onChange={(e) => setSource(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
void fetchRepository();
}
}}
placeholder={tx("owner/repo, owner/repo@skill, or GitHub URL")}
aria-label={tx("Skill repository")}
autoFocus
/>
<Button
variant="secondary"
disabled={!source.trim() || loading || installing}
onClick={() => void fetchRepository()}
>
{loading && !browseResult ? <T>Fetching…</T> : <T>Fetch</T>}
</Button>
</div>
<div className={styles.installScopeRow}>
<span>
<T>Install location</T>
</span>
<Select
className={styles.installScopeSelect}
variant="framed"
aria-label={tx("Install location")}
value={scope}
disabled={installing}
options={[
{ value: "user" as McpScope, label: tx("User (~/.agents/skills)") },
...(hasTrustedProject
? [{ value: "workspace" as McpScope, label: tx("Workspace (.agents/skills)") }]
: []),
]}
onChange={setScope}
/>
</div>
{error && (
<div className={page.error} role="alert">
<Icon name="error" size={14} />
<span>{error}</span>
</div>
)}
{browseResult && (
<div className={styles.candidateSection}>
<div className={styles.candidateHeader}>
<span>
{browseResult.owner}/{browseResult.repo}@{browseResult.gitRef}
</span>
<span>{formatMessage(tx("{count} skills found"), { count: browseResult.skills.length })}</span>
</div>
{browseResult.skills.length > 1 && (
<div className={styles.candidateList} role="listbox" aria-label={tx("Available skills")}>
{browseResult.skills.map((candidate) => {
const active = selectedSubpath === candidate.subpath;
return (
<button
key={candidate.subpath || candidate.folderName}
type="button"
role="option"
aria-selected={active}
className={clsx(styles.candidateBtn, active && styles.candidateBtnActive)}
onClick={() => void loadPreview(browseResult, candidate)}
>
<span>{candidate.folderName}</span>
<span className={styles.candidateMeta}>{formatBytes(candidate.totalBytes)}</span>
</button>
);
})}
</div>
)}
</div>
)}
{loading && browseResult && !preview && (
<div className={styles.hint}>
<T>Scanning SKILL.md and bundled files…</T>
</div>
)}
{preview && (
<>
{preview.scanWarnings.length === 0 ? (
<div className={styles.scanClean} role="status">
<Icon name="check" size={14} className={styles.scanCleanIcon} />
<span>
<T>
Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable
scripts detected.
</T>
</span>
</div>
) : (
<div className={styles.scanWarnBox} role="region" aria-label={tx("Static security scan warnings")}>
<div className={styles.scanWarnTitle}>
<Icon name="warning" size={14} />
<span>
{formatMessage(tx("Static security scan found {count} warnings"), {
count: preview.scanWarnings.length,
})}
</span>
</div>
<ul className={styles.scanWarnList}>
{preview.scanWarnings.map((w, idx) => (
<li key={`${w.kind}:${w.file}:${idx}`}>
<strong>{tx(WARNING_KIND_LABELS[w.kind])}:</strong>{" "}
<span className={styles.scanWarnCode}>{w.file}</span> — {w.message}
</li>
))}
</ul>
<Checkbox
checked={confirmedWarnings}
onChange={setConfirmedWarnings}
label={tx("I reviewed these warnings and want to install this skill")}
/>
</div>
)}
{alreadyExists && (
<Checkbox
checked={overwrite}
onChange={setOverwrite}
label={formatMessage(tx("Replace existing {name} folder in the selected location"), {
name: preview.skillName,
})}
/>
)}
<div className={clsx(styles.previewBox, selectableText)}>
<div className={styles.previewMeta}>
<div className={page.cardTitleRow}>
<span className={styles.skillName}>{preview.skillName}</span>
{preview.subpath && <span className={page.tag}>{preview.subpath}</span>}
</div>
{preview.description && <span className={styles.subtitle}>{preview.description}</span>}
</div>
<Tabs
variant="compact"
aria-label={tx("Skill preview")}
activeId={previewTab}
onSelect={(id) => setPreviewTab(id as PreviewTab)}
items={[
{ id: "markdown", label: "SKILL.md", text: "SKILL.md" },
{
id: "files",
label: formatMessage(tx("Files ({count})"), { count: preview.files.length }),
text: tx("Files"),
},
]}
/>
{previewTab === "markdown" ? (
<pre className={styles.previewMarkdown}>{preview.skillMarkdown}</pre>
) : (
<div className={styles.fileList} role="list">
{preview.files.map((f) => (
<div key={f.path} role="listitem" className={styles.fileRow}>
<span className={styles.filePath}>{f.path}</span>
<span className={styles.fileRight}>
{f.executable && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Executable</T>
</span>
)}
{f.symlink && (
<span className={page.tag}>
<T>Symlink</T>
</span>
)}
<span>{formatBytes(f.size)}</span>
</span>
</div>
))}
</div>
)}
</div>
</>
)}
</div>
</Dialog>
);
}
+197
View File
@@ -33,3 +33,200 @@
font-size: var(--fs-small);
line-height: 1.4;
}
.installBody {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3) var(--space-4) 0;
}
.installSourceRow {
display: flex;
align-items: center;
gap: var(--space-2);
}
.installSourceInput {
flex: 1;
min-width: 0;
}
.installScopeRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.installScopeSelect {
min-width: 240px;
}
.candidateSection {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.candidateHeader {
display: flex;
align-items: center;
justify-content: space-between;
font-size: var(--fs-small);
color: var(--fg-muted);
}
.candidateList {
display: flex;
flex-wrap: wrap;
gap: var(--space-1-5);
max-height: 112px;
overflow-y: auto;
}
.candidateBtn {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
padding: 4px 10px;
border-radius: var(--r-sm);
border: 1px solid var(--border-popup);
background: var(--bg-elev);
color: var(--fg);
font-size: var(--fs-small);
cursor: pointer;
}
.candidateBtn:hover {
background: var(--bg-hover);
}
.candidateBtnActive {
border-color: var(--accent);
background: var(--bg-selected);
color: var(--fg-strong);
}
.candidateMeta {
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
.scanClean {
display: flex;
align-items: center;
gap: var(--space-2);
padding: 8px 10px;
border-radius: var(--r-sm);
border: 1px solid var(--border-popup);
background: var(--bg-elev);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.scanCleanIcon {
color: var(--success);
flex-shrink: 0;
}
.scanWarnBox {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 10px 12px;
border-radius: var(--r-sm);
border: 1px solid var(--warning);
background: var(--bg-elev);
font-size: var(--fs-small);
}
.scanWarnTitle {
display: flex;
align-items: center;
gap: var(--space-1-5);
font-weight: 600;
color: var(--warning);
}
.scanWarnList {
margin: 0;
padding-left: 18px;
display: flex;
flex-direction: column;
gap: var(--space-1);
color: var(--fg);
max-height: 120px;
overflow-y: auto;
}
.scanWarnCode {
font-family: var(--font-mono);
font-size: var(--fs-tiny);
color: var(--fg-secondary);
}
.previewBox {
display: flex;
flex-direction: column;
gap: var(--space-2);
border: 1px solid var(--border-popup);
border-radius: var(--r-sm);
padding: 10px;
background: var(--bg-app);
}
.previewMeta {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.previewMarkdown {
margin: 0;
max-height: 210px;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
font-family: var(--font-mono);
font-size: var(--fs-small);
line-height: 1.45;
color: var(--fg);
}
.fileList {
display: flex;
flex-direction: column;
gap: var(--space-1);
max-height: 210px;
overflow-y: auto;
}
.fileRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 3px 6px;
border-radius: var(--r-sm);
font-size: var(--fs-small);
}
.filePath {
font-family: var(--font-mono);
color: var(--fg);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.fileRight {
display: flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
font-size: var(--fs-tiny);
flex-shrink: 0;
}
+130 -2
View File
@@ -1,6 +1,14 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope, ProjectInfo } from "@/bindings";
import type {
AgentSkillMode,
AgentSkillSource,
AgentSkillState,
InstallRemoteSkillRequest,
McpScope,
ProjectInfo,
RemoteSkillPreview,
} from "@/bindings";
import { useProject } from "@/platform/project";
import { SkillsPage, type SkillsBackend } from "./SkillsPage";
@@ -46,7 +54,7 @@ function backend(): SkillsBackend & { setModeCalls: Array<{ name: string; scope:
/** Opens one row's select and picks an option by text. */
function pick(triggerLabel: string, option: string) {
fireEvent.click(screen.getByRole("button", { name: triggerLabel }));
fireEvent.click(within(screen.getByRole("listbox")).getByText(option));
fireEvent.click(within(screen.getByRole("listbox", { name: triggerLabel })).getByText(option));
}
afterEach(() => useProject.setState({ project: null }));
@@ -149,4 +157,124 @@ describe("SkillsPage", () => {
expect(await screen.findByText(/does not match the folder/)).toBeInTheDocument();
expect(screen.queryByText("SKILL.md is valid")).not.toBeInTheDocument();
});
it("browses a GitHub repo, previews SKILL.md & files, gates on static scan warnings, and installs", async () => {
const project = { root: "/proj", name: "Proj", trusted: true, isGit: true } as ProjectInfo;
useProject.setState({ project });
const installCalls: InstallRemoteSkillRequest[] = [];
const previews: Record<string, RemoteSkillPreview> = {
"skills/clean-doc": {
owner: "acme",
repo: "skills",
gitRef: "main",
treeSha: "abc123",
subpath: "skills/clean-doc",
skillName: "clean-doc",
description: "Clean documentation helper",
skillMarkdown: "---\nname: clean-doc\ndescription: Clean documentation helper\n---\nWrite clear docs.\n",
files: [{ path: "SKILL.md", size: 92, executable: false, symlink: false }],
scanWarnings: [],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
},
"skills/deploy-script": {
owner: "acme",
repo: "skills",
gitRef: "main",
treeSha: "abc123",
subpath: "skills/deploy-script",
skillName: "deploy-script",
description: "Deploys staging builds",
skillMarkdown:
"---\nname: deploy-script\ndescription: Deploys staging builds\nallowed-tools: Bash(git:*)\n---\nRun deploy.\n",
files: [
{ path: "SKILL.md", size: 112, executable: false, symlink: false },
{ path: "scripts/deploy.sh", size: 48, executable: true, symlink: false },
],
scanWarnings: [
{
kind: "executableScript",
file: "scripts/deploy.sh",
message: "Contains executable file mode (100755)",
},
{
kind: "allowedToolsShell",
file: "SKILL.md",
message: "`allowed-tools` grants shell/command execution (`Bash(git:*)`)",
},
],
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
},
};
const installerBackend: SkillsBackend = {
...backend(),
browse: vi.fn(async () => ({
owner: "acme",
repo: "skills",
gitRef: "main",
treeSha: "abc123",
truncated: false,
skills: [
{ folderName: "clean-doc", subpath: "skills/clean-doc", fileCount: 1, totalBytes: 92 },
{ folderName: "deploy-script", subpath: "skills/deploy-script", fileCount: 2, totalBytes: 160 },
],
})),
preview: vi.fn(async (_owner, _repo, _ref, subpath) => {
const found = previews[subpath];
if (!found) throw new Error(`missing preview for ${subpath}`);
return found;
}),
install: vi.fn(async (input) => {
installCalls.push(input);
return [...SKILLS, state("deploy-script", input.scope === "workspace" ? "workspace" : "user")];
}),
};
render(<SkillsPage backend={installerBackend} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Install Skill…" }));
const dialog = await screen.findByRole("dialog", { name: "Install Agent Skill" });
fireEvent.change(within(dialog).getByLabelText("Skill repository"), { target: { value: "acme/skills" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Fetch" }));
// First candidate (`clean-doc`) has 0 warnings -> Install is immediately enabled.
expect(await within(dialog).findByText(/Static scan passed/)).toBeInTheDocument();
expect(within(dialog).getByRole("button", { name: "Install" })).toBeEnabled();
// Switch to `deploy-script` -> warnings require confirmation checkbox before Install enables.
fireEvent.click(within(dialog).getByRole("option", { name: /deploy-script/ }));
expect(await within(dialog).findByText(/Static security scan found 2 warnings/)).toBeInTheDocument();
const installBtn = within(dialog).getByRole("button", { name: "Install" });
expect(installBtn).toBeDisabled();
// Inspect bundled file list tab.
fireEvent.click(within(dialog).getByRole("tab", { name: /Files \(2\)/ }));
expect(within(dialog).getAllByText("scripts/deploy.sh")).toHaveLength(2);
expect(within(dialog).getByText("Executable")).toBeInTheDocument();
// Confirm warnings and install into Workspace (.agents/skills).
pick("Install location", "Workspace (.agents/skills)");
fireEvent.click(within(dialog).getByLabelText("I reviewed these warnings and want to install this skill"));
expect(installBtn).toBeEnabled();
fireEvent.click(installBtn);
await waitFor(() =>
expect(installCalls).toEqual([
{
owner: "acme",
repo: "skills",
gitRef: "main",
subpath: "skills/deploy-script",
scope: "workspace",
confirmWarnings: true,
overwrite: false,
},
]),
);
await waitFor(() => expect(screen.getByText("deploy-script")).toBeInTheDocument());
});
});
+20
View File
@@ -13,6 +13,7 @@ import { isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Button, Icon, IconButton, SearchField, Select, Tabs, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { InstallSkillDialog } from "./InstallSkillDialog";
import { providerIcon } from "./model";
import {
SKILL_SOURCE_GROUPS,
@@ -50,11 +51,13 @@ function groupsForTab(tab: SourceTab): readonly SkillSource[] {
export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: SkillsBackend }) {
const tx = useTx();
const hasProject = useProject((s) => !!s.project?.root);
const hasTrustedProject = useProject((s) => !!s.project?.root && !!s.project?.trusted);
const [tab, setTab] = useState<SourceTab>("all");
const [skills, setSkills] = useState<AgentSkillState[]>([]);
const [query, setQuery] = useState("");
const [error, setError] = useState<string | null>(null);
const [busyName, setBusyName] = useState<string | null>(null);
const [installOpen, setInstallOpen] = useState(false);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
// The scope the row's mode selector writes to; defaults follow where the mode came from.
@@ -141,6 +144,11 @@ export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: Skill
<T>Skills</T>
</h2>
<div className={page.headerActions}>
{backend.browse && backend.preview && backend.install && (
<Button variant="primary" onClick={() => setInstallOpen(true)}>
<Icon name="plus" size={14} /> <T>Install Skill…</T>
</Button>
)}
<Button variant="secondary" onClick={load}>
<Icon name="refresh" size={14} /> <T>Rescan</T>
</Button>
@@ -269,6 +277,18 @@ export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: Skill
</div>
)}
</div>
{installOpen && (
<InstallSkillDialog
backend={backend}
hasTrustedProject={hasTrustedProject}
onInstalled={(next) => {
syncCatalog(next);
setInstallOpen(false);
}}
onClose={() => setInstallOpen(false)}
/>
)}
</div>
);
}
+23 -1
View File
@@ -5,18 +5,40 @@
*/
import { useEffect } from "react";
import { create } from "zustand";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope } from "@/bindings";
import type {
AgentSkillMode,
AgentSkillSource,
AgentSkillState,
InstallRemoteSkillRequest,
McpScope,
RemoteSkillBrowseResult,
RemoteSkillPreview,
RequestId,
} from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
export interface SkillsBackend {
list(): Promise<AgentSkillState[]>;
setMode(name: string, scope: McpScope, mode: AgentSkillMode): Promise<AgentSkillState[]>;
browse?(source: string, request: RequestId): Promise<RemoteSkillBrowseResult>;
preview?(
owner: string,
repo: string,
gitRef: string,
subpath: string,
request: RequestId,
): Promise<RemoteSkillPreview>;
install?(input: InstallRemoteSkillRequest, request: RequestId): Promise<AgentSkillState[]>;
}
export const defaultSkillsBackend: SkillsBackend = {
list: () => (typeof commands.agentSkillsList === "function" ? call(commands.agentSkillsList()) : Promise.resolve([])),
setMode: (name, scope, mode) => call(commands.agentSkillsSetMode(name, scope, mode)),
browse: (source, request) => call(commands.agentSkillsBrowse(source, request)),
preview: (owner, repo, gitRef, subpath, request) =>
call(commands.agentSkillsPreview(owner, repo, gitRef, subpath, request)),
install: (input, request) => call(commands.agentSkillsInstall(input, request)),
};
/** Which folder family a skill came from, with the paths it is discovered in. */
+25
View File
@@ -3023,6 +3023,31 @@
"Configure skills for this session": "Configure skills for this session",
"No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.",
"This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.",
"Install Skill…": "Install Skill…",
"Install Agent Skill": "Install Agent Skill",
"Enter a GitHub repository (owner/repo, owner/repo@skill, owner/repo/path@ref, or a GitHub URL). Only the chosen skill folder is downloaded after preview and static scan.": "Enter a GitHub repository (owner/repo, owner/repo@skill, owner/repo/path@ref, or a GitHub URL). Only the chosen skill folder is downloaded after preview and static scan.",
"owner/repo, owner/repo@skill, or GitHub URL": "owner/repo, owner/repo@skill, or GitHub URL",
"Skill repository": "Skill repository",
"Fetch": "Fetch",
"Install location": "Install location",
"User (~/.agents/skills)": "User (~/.agents/skills)",
"Workspace (.agents/skills)": "Workspace (.agents/skills)",
"SKILL.md": "SKILL.md",
"{count} skills found": "{count} skills found",
"Available skills": "Available skills",
"Scanning SKILL.md and bundled files…": "Scanning SKILL.md and bundled files…",
"Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable scripts detected.": "Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable scripts detected.",
"Static security scan warnings": "Static security scan warnings",
"Static security scan found {count} warnings": "Static security scan found {count} warnings",
"Hidden Unicode": "Hidden Unicode",
"Out-of-root symlink": "Out-of-root symlink",
"Executable script": "Executable script",
"Shell tool grant": "Shell tool grant",
"I reviewed these warnings and want to install this skill": "I reviewed these warnings and want to install this skill",
"Replace existing {name} folder in the selected location": "Replace existing {name} folder in the selected location",
"Skill preview": "Skill preview",
"Files ({count})": "Files ({count})",
"Symlink": "Symlink",
"Cannot find the source of {0}": "Cannot find the source of {0}",
"JavaScript and TypeScript": "JavaScript and TypeScript",
"Global function": "Global function",
+24
View File
@@ -9344,6 +9344,30 @@
"Configure skills for this session": "为此会话配置技能",
"No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "未在 .agents/skills、.openidea/skills、~/.agents/skills 或 Claude Code、GitHub Copilot、Codex 与 Cursor 的 CLI 文件夹中找到技能。",
"This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "该 CLI 会自己发现这个文件夹:关闭只会让 OpenIDEA 的 / 菜单不再提供该技能,并且只在 CLI 支持禁用时生效。",
"Install Skill…": "安装技能…",
"Install Agent Skill": "安装代理技能",
"Enter a GitHub repository (owner/repo, owner/repo@skill, owner/repo/path@ref, or a GitHub URL). Only the chosen skill folder is downloaded after preview and static scan.": "输入 GitHub 仓库(owner/repo、owner/repo@skill、owner/repo/path@ref 或 GitHub URL)。预览并完成静态扫描后,只会下载所选技能文件夹。",
"owner/repo, owner/repo@skill, or GitHub URL": "owner/repo、owner/repo@skill 或 GitHub URL",
"Skill repository": "技能仓库",
"Install location": "安装位置",
"User (~/.agents/skills)": "用户 (~/.agents/skills)",
"Workspace (.agents/skills)": "工作区 (.agents/skills)",
"SKILL.md": "SKILL.md",
"{count} skills found": "找到 {count} 个技能",
"Available skills": "可用技能",
"Scanning SKILL.md and bundled files…": "正在扫描 SKILL.md 与随附文件…",
"Static scan passed: no hidden Unicode, out-of-root symlinks, shell tool grants, or executable scripts detected.": "静态扫描通过:未发现隐藏 Unicode、越界符号链接、Shell 工具授权或可执行脚本。",
"Static security scan warnings": "静态安全扫描警告",
"Static security scan found {count} warnings": "静态安全扫描发现 {count} 项警告",
"Hidden Unicode": "隐藏 Unicode",
"Out-of-root symlink": "越界符号链接",
"Executable script": "可执行脚本",
"Shell tool grant": "Shell 工具授权",
"I reviewed these warnings and want to install this skill": "我已查看上述警告并确认安装此技能",
"Replace existing {name} folder in the selected location": "替换所选位置中已有的 {name} 文件夹",
"Skill preview": "技能预览",
"Files ({count})": "文件 ({count})",
"Symlink": "符号链接",
"Cannot find the source of {0}": "找不到 {0} 的源代码",
"JavaScript and TypeScript": "JavaScript 和 TypeScript",
"Global function": "全局函数",