Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(workbench): Skills management page wrapping askill v0.1.13 (#358)

Call Whitebfc087e076c2
diff --git a/AGENTS.md b/AGENTS.md
index 6302b8421..da84e5689 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -217,6 +217,20 @@ Reuse design-system primitives — do not re-roll:
- if no existing primitive fits, add a new variant (or a new primitive in `ui/src/components/ui/`) so the next caller can reuse it. Prefer adjusting the design-system layer over re-implementing the visual locally in a feature component.
- the source of truth for visual tokens (colors, radii, spacing, variant names) is `design.pen` — extend primitives to match its variant names so design ↔ code stay aligned.
+**Reuse-first methodology (the reuse ladder).** This generalizes the rules above; it applies to shared backend logic too, not just UI:
+
+- **Inventory before you build.** Survey what already exists — primitives, tokens, services, and how sibling features solved the same problem — and build from that inventory, not from scratch.
+- **Walk the ladder in order:** reuse as-is → extend it (new `variant` / `size` / prop / arg) → promote a near-duplicate that lives in a feature folder into the shared layer so every caller gets it → only then build new, as a real reusable unit in its proper home, never an inline one-off.
+- **Extract on the third repeat.** When the same markup / logic / constant recurs in ~3 places, lift it into one shared component or util and retrofit the existing callers. Touching N call sites with the same pattern means extracting the pattern, not pasting it N times — one concept, one home.
+- Prefer extending the shared / design-system layer over patching the symptom in a feature file; the next caller should inherit the fix for free. Don't rush past reuse for speed — a clean, reusable change beats a fast local hack.
+
+**Match the design pixel-for-pixel.** UI that drifts from the design is a defect, not a detail:
+
+- `design.pen` is the visual source of truth; "looks roughly right" is not done.
+- **Map every value to an exact token or class** — each size, weight, spacing, radius, color, and shadow corresponds to a specific token / utility. Look it up; don't eyeball it. If a needed token is missing, add it to the token layer first instead of hardcoding a one-off.
+- **Verify by side-by-side comparison, not memory.** Render the built surface at the design's target viewport, place it next to the exported design frame, enumerate the deltas (spacing, type scale, color, radius, shadow, alignment), and fix until they match before calling it done.
+- Confirm the utility classes you used actually resolve to the intended values — a class that silently no-ops (missing or aliased token) looks fine in code and wrong on screen.
+
Important packaging caveat:
- the installed `vibe` command uses packaged UI assets, not raw `ui/dist/` from the repo by default
diff --git a/core/services/skills.py b/core/services/skills.py
new file mode 100644
index 000000000..5bdab96e8
--- /dev/null
+++ b/core/services/skills.py
@@ -0,0 +1,308 @@
+"""Business API for Agent Skills — a thin shell over the ``askill`` CLI.
+
+Wraps ``askill <cmd> --json`` (github.com/avibe-bot/askill, v0.1.13+) so the
+Web UI can manage global + project skills across backends without owning
+install logic. The CLI is the source of truth; this layer maps Vibe Remote
+concepts onto askill's flags, runs the binary, and parses the documented
+``--json`` contract into plain dicts.
+
+Layering (per ``docs/plans/workbench-dispatch-architecture.md`` §6, and the
+build plan in ``docs/plans/workbench-skills-page.md``):
+
+* Transport-agnostic and dependency-injected: the resolved ``askill`` binary
+ path is passed in by the caller (``vibe.api`` resolves it via
+ ``resolve_cli_path("askill")``), so ``core/`` never imports ``vibe/``.
+* Functions return plain ``dict`` payloads (the askill envelope). Failures
+ raise ``LookupError("askill_not_found")`` or ``SkillsError(code, message)``
+ for the route layer to translate.
+
+Scope-flag note: ``list`` distinguishes ``-g`` / ``-p`` / (all); but
+``add`` / ``remove`` / ``check`` / ``update`` only take ``-g`` for global —
+project scope is the default and is selected by running with ``cwd`` set to
+the project folder.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_TIMEOUT = 30.0
+
+# Vibe Remote backend id <-> askill agent id. One map, used everywhere.
+BACKEND_TO_AGENT: dict[str, str] = {
+ "claude": "claude-code",
+ "opencode": "opencode",
+ "codex": "codex",
+}
+AGENT_TO_BACKEND: dict[str, str] = {agent: backend for backend, agent in BACKEND_TO_AGENT.items()}
+
+
+class SkillsError(Exception):
+ """A failure with a stable ``code`` the route layer maps to HTTP/i18n."""
+
+ def __init__(self, code: str, message: str, *, details: Any = None) -> None:
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.details = details
+
+
+def _subprocess_env(askill_path: str) -> dict[str, str]:
+ """Env for the askill subprocess with the binary's own dir leading PATH.
+
+ askill is a Node CLI (``#!/usr/bin/env node``); when ``resolve_cli_path``
+ finds an npm/nvm install outside the service PATH, the shebang still needs
+ ``node`` — which lives alongside the askill binary — to be resolvable, else
+ every Skills action fails with no output. Mirrors
+ ``vibe.api._command_env_for`` (kept local so ``core`` stays free of ``vibe``
+ imports).
+ """
+ env = {**os.environ, "PATH": os.environ.get("PATH", "")}
+ binary_dir = os.path.dirname(os.path.abspath(askill_path))
+ if binary_dir:
+ entries = [e for e in env["PATH"].split(os.pathsep) if e and e != binary_dir]
+ env["PATH"] = os.pathsep.join([binary_dir, *entries])
+ return env
+
+
+async def _run_askill(
+ askill_path: str,
+ args: list[str],
+ *,
+ cwd: Optional[str] = None,
+ timeout: float = DEFAULT_TIMEOUT,
+) -> dict[str, Any]:
+ """Run ``askill <args> --json`` and parse stdout as JSON.
+
+ In ``--json`` mode askill emits a machine-readable envelope even on a
+ non-zero exit, so we parse stdout regardless of the return code and let
+ callers branch on ``data["ok"]`` / ``data["error"]``. Spawn, timeout, and
+ parse failures raise (``LookupError`` for a missing binary, ``SkillsError``
+ otherwise).
+ """
+ if not askill_path:
+ raise LookupError("askill_not_found")
+ if cwd is not None and not os.path.isdir(cwd):
+ # A deleted/moved project folder also makes create_subprocess_exec raise
+ # FileNotFoundError; distinguish it from a missing askill binary so the
+ # UI reports the actionable problem (the project path) not "not installed".
+ raise SkillsError("project_dir_missing", f"project folder not found: {cwd}")
+ cmd = [askill_path, *args, "--json"]
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *cmd,
+ cwd=cwd,
+ env=_subprocess_env(askill_path),
+ stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ except FileNotFoundError as err:
+ raise LookupError("askill_not_found") from err
+ try:
+ out, err = await asyncio.wait_for(proc.communicate(), timeout=timeout)
+ except (asyncio.TimeoutError, TimeoutError):
+ proc.kill()
+ await proc.communicate()
+ logger.info("askill timed out after %ss: %s", timeout, " ".join(args))
+ raise SkillsError("askill_timeout", f"askill timed out after {timeout:.0f}s")
+
+ text = (out or b"").decode("utf-8", errors="replace").strip()
+ if not text:
+ detail = (err or b"").decode("utf-8", errors="replace").strip()
+ logger.info("askill produced no stdout (%s): %s", " ".join(args), detail[:300])
+ raise SkillsError("askill_no_output", detail or "askill produced no output")
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError as exc:
+ logger.info("askill emitted non-JSON output (%s): %s", " ".join(args), text[:300])
+ raise SkillsError("askill_bad_json", "could not parse askill output") from exc
+ if not isinstance(data, dict):
+ raise SkillsError("askill_bad_json", "askill output was not a JSON object")
+ return data
+
+
+def _agent_flags(backends: Optional[list[str]]) -> list[str]:
+ """Expand selected Vibe backends into a single variadic ``-a`` flag.
+
+ askill parses ``-a, --agent <agents...>`` as one variadic option and each
+ later ``-a`` *replaces* the previous values (``options.agent = values``), so
+ multiple agents must share one flag — ``-a claude-code opencode`` — not
+ repeated ``-a`` flags, or only the last agent would receive the operation.
+ """
+ agents: list[str] = []
+ for backend in backends or []:
+ agent = BACKEND_TO_AGENT.get(backend)
+ if not agent:
+ raise SkillsError("invalid_backend", f"unknown backend: {backend}")
+ agents.append(agent)
+ return ["-a", *agents] if agents else []
+
+
+def _list_scope_flag(scope: str) -> list[str]:
+ """Scope flags for ``list`` (supports -g / -p / all)."""
+ if scope == "global":
+ return ["-g"]
+ if scope == "project":
+ return ["-p"]
+ if scope == "all":
+ return []
+ raise SkillsError("invalid_scope", f"unknown scope: {scope}")
+
+
+def _target_scope_flag(scope: str) -> list[str]:
+ """Scope flag for ``add`` / ``remove`` / ``check`` / ``update``.
+
+ These commands only take ``-g`` for global; project scope is the default
+ and is selected by running with ``cwd`` = the project folder (no flag).
+ """
+ if scope == "global":
+ return ["-g"]
+ if scope == "project":
+ return []
+ raise SkillsError("invalid_scope", f"unknown scope: {scope}")
+
+
+def _cwd_for(scope: str, project_dir: Optional[str]) -> Optional[str]:
+ # Project scope is selected by running in the project folder; refuse to fall
+ # back to the server's own cwd when a project-scoped op arrives without one.
+ if scope == "project" and not project_dir:
+ raise SkillsError("project_required", "a project is required for project-scoped skills")
+ return project_dir if scope != "global" else None
+
+
+# --- public API -----------------------------------------------------------
+
+
+async def list_skills(
+ askill_path: str,
+ *,
+ scope: str = "all",
+ project_dir: Optional[str] = None,
+ backends: Optional[list[str]] = None,
+) -> dict[str, Any]:
+ """List installed skills. ``scope`` is ``all`` | ``global`` | ``project``.
+
+ Project-scoped lists run with ``cwd=project_dir`` so askill resolves the
+ repo's ``.agents/skills``. Each item carries description / version / tags /
+ source / installSource / timestamps natively (askill v0.1.13+).
+ """
+ args = ["list", *_list_scope_flag(scope), *_agent_flags(backends)]
+ return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
+
+
+async def preview_source(
+ askill_path: str,
+ source: str,
+ *,
+ project_dir: Optional[str] = None,
+) -> dict[str, Any]:
+ """Discover the skills a source contains without installing.
+
+ Maps to ``askill add <source> --list --json``. ``source`` is a slug
+ (``gh:owner/repo[@name]``), a GitHub URL, or a local directory.
+ """
+ if not source:
+ raise SkillsError("missing_source", "no source provided")
+ return await _run_askill(askill_path, ["add", source, "--list"], cwd=project_dir)
+
+
+async def add_skill(
+ askill_path: str,
+ source: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+ backends: Optional[list[str]] = None,
+ all_skills: bool = False,
+ skill: Optional[str] = None,
+ copy: bool = False,
+) -> dict[str, Any]:
+ """Install skill(s) from a source. Non-interactive (``-y``).
+
+ ``askill add <source> [-g] [-a <agent>...] [--all|--skill <name>] [--copy] -y``.
+ ``skill`` installs one named skill from a multi-skill source (use this for
+ local dirs, where ``source@name`` is ambiguous); ``all_skills`` installs
+ every discovered skill. ``scope`` must be ``global`` or ``project``.
+ """
+ if not source:
+ raise SkillsError("missing_source", "no source provided")
+ if scope not in ("global", "project"):
+ raise SkillsError("invalid_scope", "install scope must be global or project")
+ args = ["add", source, *_target_scope_flag(scope), *_agent_flags(backends)]
+ if skill:
+ args += ["--skill", skill]
+ if all_skills:
+ args.append("--all")
+ if copy:
+ args.append("--copy")
+ args.append("-y")
+ return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
+
+
+async def remove_skill(
+ askill_path: str,
+ name: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+ backends: Optional[list[str]] = None,
+) -> dict[str, Any]:
+ """Remove an installed skill, optionally from specific backends only.
+
+ Maps to ``askill remove <name> [-g] [-a <agent>...]``.
+ """
+ if not name:
+ raise SkillsError("missing_skill", "no skill name provided")
+ if scope not in ("global", "project"):
+ raise SkillsError("invalid_scope", "remove scope must be global or project")
+ args = ["remove", name, *_target_scope_flag(scope), *_agent_flags(backends)]
+ return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
+
+
+async def find_skills(askill_path: str, query: str = "") -> dict[str, Any]:
+ """Search the askill.sh registry. Maps to ``askill find <query>``.
+
+ Returns ``{ok, query, filters, sort, pagination, count, skills[]}`` where
+ each skill carries ``aiScore`` / ``aiBreakdown`` / ``stars`` / ``tags``.
+ """
+ args = ["find"]
+ if query:
+ args.append(query)
+ return await _run_askill(askill_path, args)
+
+
+async def check(
+ askill_path: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+) -> dict[str, Any]:
+ """Check installed skills for available updates (no install).
+
+ Maps to ``askill check [-g] --json``. Returns ``{ok, summary, skills[]}``;
+ each skill has ``status`` (``update_available`` | ``up_to_date`` |
+ ``uncheckable``) plus ``localVersion`` / ``remoteVersion``.
+ """
+ args = ["check", *_target_scope_flag(scope)]
+ return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
+
+
+async def update(
+ askill_path: str,
+ name: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+) -> dict[str, Any]:
+ """Update one installed skill. Maps to ``askill update <name> [-g] -y``."""
+ if not name:
+ raise SkillsError("missing_skill", "no skill name provided")
+ args = ["update", name, *_target_scope_flag(scope), "-y"]
+ return await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
diff --git a/docs/plans/workbench-skills-page.md b/docs/plans/workbench-skills-page.md
new file mode 100644
index 000000000..d9d0b7469
--- /dev/null
+++ b/docs/plans/workbench-skills-page.md
@@ -0,0 +1,198 @@
+# Workbench Skills Page — Implementation Plan
+
+> **Branch**: `feature/workbench-skills` (from `origin/master` @ `88c8afe`)
+> **Status**: Design finalized 2026-05-30 — ready to build.
+> **Design source of truth**: `design.pen` (project root) — frames listed in §2. Read them via the `pencil` MCP tools, not text.
+> **Owner**: cyhhao
+> **Core principle**: extreme reuse + first-principles. Reuse a primitive → extend it → only then build new. Never re-roll a one-off variant inline. **Pixel-perfect 1:1 with the design is a hard requirement** (see §8).
+
+## 1. Goal
+
+Replace the `SkillsPage` placeholder (`ui/src/components/workbench/SkillsPage.tsx`, currently a 6-line `WorkbenchModulePlaceholder`) with the full Skills management surface: manage **global** and **project-scoped** Agent Skills across the Claude / OpenCode / Codex backends, search/discover from the askill.sh registry, and import skills from a **GitHub URL** or an **uploaded .zip**. The backend is a thin shell over the open-source **askill** CLI (`github.com/avibe-bot/askill`) in `--json` mode — Vibe Remote owns UI + orchestration only.
+
+This is a greenfield build: `/skills → SkillsPage` and the sidebar nav (`CAPABILITY_NAV`, `WorkbenchSidebar.tsx:36-41`) are already wired.
+
+**Out of scope (deferred):** Light theme + mobile variants. The whole new Workbench is dark-desktop-only today (only the Chat/Agents/Harness/Skills dark frames exist); Skills follows that until the Workbench gets a responsive/light pass as one coordinated effort.
+
+## 2. Design source of truth (design.pen frames)
+
+All Dark desktop, 1440×900, in the `WORKBENCH · SKILLS` shelf of `design.pen`:
+
+| Frame ID | Name | What it specifies |
+| --- | --- | --- |
+| `ua2wX` | Skills (Dark) | **Primary page.** Global scope. Header + scope/toolbar + flat skill list (rows) + 400px detail panel (pdf-tools selected). |
+| `ZigTZ` | Skills · Project scope (Dark) | Project tab active, **project-picker dropdown** (open state), project path context bar, two sections (PROJECT SKILLS / INHERITED FROM GLOBAL dimmed), full-width list (no detail panel). |
+| `gNDdF` | Skills · Add from GitHub (Dark) | "Add a skill" modal, **GitHub URL** source tab active: URL input + Fetch → discovered-skills checklist → scope + backend targets → Install. Footer shows the literal `askill add …` command. |
+| `KR9B0` | Skills · Upload ZIP (Dark) | Same modal, **Upload .zip** source tab active: dashed dropzone + uploaded-file card + "local, nothing uploaded" note → same discovered/scope/backends/install flow. |
+| `R2OBP` | Skills · Browse registry (Dark) | Registry search modal: search + tag filters + result cards (aiScore badge, owner/repo, tags, stars, Add / Installed). |
+
+When building, open each frame and read exact values (sizes, paddings, fills, effects) with `mcp__pencil__batch_get`. The token names in the frames (`$--surface-2`, `$--mint`, `#5BFFA066`, …) map 1:1 to `ui/src/index.css` (§8.2).
+
+## 3. Architecture
+
+```
+SkillsPage / dialogs (React)
+ → useApi() methods (ui/src/context/ApiContext.tsx)
+ → GET/POST/DELETE /api/skills/* (vibe/ui_server.py @app.route shims)
+ → vibe/api.py list_skills / add_skill / remove_skill / find_skills / preview_source
+ → core/services/skills.py SkillsService (transport-agnostic business layer)
+ → askill <cmd> --json (subprocess; resolve_cli_path("askill"))
+```
+
+This matches the existing `storage → api.py → ui_server.py` layering and the `core/services/` direction set by `docs/plans/workbench-dispatch-architecture.md` (Accepted). The Skills surface is **pure data CRUD** (list/add/remove/find) — it stays in the UI-server process via `core/services/`, and does **not** go through the Controller dispatch socket (boundary rule R1).
+
+## 4. Backend plan
+
+### 4.1 `core/services/skills.py` — new `SkillsService`
+
+Transport-agnostic. Wraps the askill CLI; returns plain `dict`s; raises `ValueError`/`LookupError` for the route layer to translate. Model the subprocess execution on the proven pattern in `core/agent_auth_service.py` (`_run_utility_command` `:988-1016` and `test_web_auth` `:1752-1908`, which already do `create_subprocess_exec` + `wait_for(communicate(), timeout)` + `json.loads(stdout)` + error classification; `_verify_login` `:1238-1283` runs `claude … --json` and parses it — direct precedent).
+
+Helper (async):
+
+```python
+async def _run_askill_json(args: list[str], *, cwd: str | None = None, timeout: float = 30.0) -> dict:
+ cli = resolve_cli_path("askill") # api.resolve_cli_path — checks ~/.local/bin, ~/.bun/bin, brew, npm globals, then which
+ if not cli:
+ raise LookupError("askill_not_found")
+ proc = await asyncio.create_subprocess_exec(
+ cli, *args, "--json",
+ cwd=cwd, stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
+ )
+ try:
+ out, err = await asyncio.wait_for(proc.communicate(), timeout)
+ except asyncio.TimeoutError:
+ proc.kill(); await proc.communicate(); raise TimeoutError("askill_timeout")
+ data = json.loads(out or b"{}") # askill emits machine JSON even on non-zero exit in --json mode
+ return data # caller inspects data["ok"] / data["error"]
+```
+
+### 4.2 askill command mapping (verified against askill `docs/cli-reference.md` + `docs/json-contracts/`)
+
+| Service method | askill invocation | Notes |
+| --- | --- | --- |
+| `list(scope, project_id)` | `askill list [-g\|-p] [-a <agent>] --json` | scope: global→`-g`, project→`-p` (run with `cwd=<project folder>`). Response: `{ok, filters{scope,agents[]}, summary{global,project}, skills[]{name,scope,path,agents[]{id,name}}}`. |
+| `preview(source)` | `askill add <slug> --json` (no `-y`) | For multi-skill repos askill returns `action:"preview"` + discovered `skills[]{name,description,frontmatter}` (or error `MULTIPLE_SKILLS_REQUIRE_SELECTION`). slug forms: `gh:owner/repo`, `gh:owner/repo@name`, `gh:owner/repo/path`, full URL, or a local dir/zip path. |
+| `add(source, scope, agents, all)` | `askill add <slug> [-g] [-a a b] [--all] -y --json` | Install. Response: `{ok, action:"install", source{}, scope, selectedAgents[], summary{}, results[]}`. |
+| `remove(name, scope, agents)` | `askill remove <name> [-g] [-a …] --json` | Response: `{ok, skill, scope, removedAgents[], skippedAgents[], failed[]}`. |
+| `find(query)` | `askill find <query> --json` | Registry search. Response: `{ok, query, count, skills[]{id,name,description,owner,repo,tags[],stars,aiScore,aiBreakdown[]{key,label,score},updatedAt,installSource,url}}`. |
+
+**ZIP upload flow:** the UI uploads the `.zip` to a `POST /api/skills/upload` endpoint → backend saves to a temp dir, unzips into a scratch folder, then runs `preview`/`add` against that **local path** (`askill add /tmp/…/unpacked --all -y --json`). Clean up the temp dir after. Nothing leaves the machine (mirror the design's "installed locally" copy).
+
+**Backend "Backend" filter** = askill `-a <agent>`. Map Vibe Remote backends → askill agent ids: `claude→claude-code`, `opencode→opencode`, `codex→codex`. Centralize this map in `skills.py`.
+
+### 4.3 Known askill gaps (tracked in [avibe-bot/askill#11](https://github.com/avibe-bot/askill/issues/11))
+
+`list --json` does not yet carry per-skill `description`/`version`/`source`, and `check`/`info` have no `--json`. **Until #11 lands**, enrich installed rows in `SkillsService.list()` by reading each skill's canonical `~/.agents/skills/<name>/SKILL.md` (or `<project>/.agents/skills/<name>/SKILL.md`) frontmatter for `description`/`version` — the path is already in the `list` payload. The "update available" badge is deferred until `check --json` exists (don't fake it). Keep the enrichment isolated so it can be deleted once #11 ships.
+
+### 4.4 `vibe/api.py` + `vibe/ui_server.py`
+
+Add pure functions in `api.py` (`async def list_skills(...)`, `add_skill`, `remove_skill`, `find_skills`, `preview_source`, `upload_skill_zip`) that call the `SkillsService`. Add thin `@app.route` shims in `ui_server.py` following the established pattern (`vibe_agents_get` `:1600-1612`): lazy `from vibe import api`, parse `request.args`/`request.json`, `await api.<fn>_async(...)` for async (NO `asyncio.run` bridges — AGENTS.md hard rule), `return jsonify(...)`. Routes:
+
+- `GET /api/skills?scope=&project_id=`
+- `POST /api/skills/preview` `{source}`
+- `POST /api/skills` `{source, scope, project_id?, agents[], all?}`
+- `DELETE /api/skills/<name>?scope=&project_id=&agents=`
+- `GET /api/skills/find?q=`
+- `POST /api/skills/upload` (multipart .zip) → preview payload
+
+## 5. API client plan (`ui/src/context/ApiContext.tsx`)
+
+Add 6 methods. **Three mechanical edits each** (do NOT touch the `useMemo([showToast, t])` deps — memoization is load-bearing, see the comment at `:816-839`):
+1. Signature in the `ApiContextType` block (`:6-131`).
+2. `export type`s near the other workbench types (`:136-689`): `SkillBrief` (`{name, scope:'global'|'project', path, agents:{id,name}[], description?, version?, source?}`), `SkillSearchResult` (mirrors askill `find` item), `SkillManifest` (preview: `{source, skills:{name,description}[]}`).
+3. Impl inside the `useMemo` object literal (`:840-1115`) reusing `getJson`/`postJson`/`deleteJson` + `URLSearchParams` + `encodeURIComponent` exactly as `listVibeAgents`/`removeVibeAgent` do (`:1009-1028`).
+
+Methods: `listSkills`, `previewSkillSource`, `addSkill`, `removeSkill`, `findSkills`, `uploadSkillZip`. Backend error `error.code` is surfaced via the existing `errors.<code>` i18n lookup (`:725`).
+
+## 6. Frontend component plan — reuse / extend / new
+
+**Page shell** — `SkillsPage.tsx`, single `/skills` route, **local state** for scope, selected skill, and dialog open/closed (this app uses local state for modals, not URL params — `AgentsPage` is the template). Wrapper: `<div className="mx-auto flex w-full max-w-[1200px] flex-col gap-5 py-2">`. Body is the master-detail grid `grid gap-5 lg:grid-cols-[1fr_400px]` (Global scope, detail open); Project scope is single-column full-width.
+
+### 6.1 Reuse AS-IS
+- **`Button`** (`ui/components/ui/button.tsx`): toolbar = `variant="outline" size="xs"`; primary "Add skill" = `variant="brand" size="xs"`; "Browse registry" = `variant="outline" size="xs"` (cyan icon); Remove = `variant="destructive-soft" size="xs"`; icon-only = `variant="ghost" size="icon"`.
+- **`Badge`**: GLOBAL/inherited tags + status pills. Quality "AI 9.5" pill = `badgeVariants` on a span. Backend chips build on it (§6.3).
+- **`Switch`** (`checked`/`onCheckedChange`/`label`): the per-backend link toggles in the detail panel's "Available to" section.
+- **`Popover`** (`Popover`/`PopoverTrigger`/`PopoverContent`): the dropdown idiom for the **Backend filter**, the **project picker** (Project scope), and skill-row `⋯` actions. Copy the `BackendFilter`/`ImportMenu` markup from `AgentsPage.tsx:390-468` and the project `…` menu from `WorkbenchSidebar.tsx:238-280`.
+- **`Combobox`** + `ComboboxOption {value,label}`: only if a searchable select is needed (not strictly required by these frames).
+- **`Input`**, **`Label`**, **`Separator`**, **`Card`**: as-is.
+- **`DirectoryBrowser`** (`ui/components/ui/directory-browser.tsx`): reuse for "Open a project folder…" in the project picker if we let users add a project from here.
+- **`SegmentedRadio`** (`ui/components/settings/shared/SegmentedRadio.tsx`, generic `SegmentedRadio<T>`): the **Global / Project** scope switch in the toolbar, and the GitHub/ZIP source switch + Global/Project scope inside the Add dialog. → **Promote it to `ui/components/ui/segmented.tsx`** (it's now used outside settings); update the settings imports. This is the "reuse, don't fork" principle applied.
+- **`useToast()`**, **`useApi()`**, AgentsPage's **`Field`** helper (`:835-847`, mono-uppercase label + slot) for the detail panel rows.
+
+### 6.2 Extend / promote
+- **`WorkbenchPageHeader`** — NEW shared component in `ui/components/workbench/`, props `{ icon, title, subtitle, actions? }`. AgentsPage, HarnessPage, and Skills all hand-roll the identical "40px mint-soft icon box + 24px title + 12px subtitle + Refresh" header (`AgentsPage.tsx:223-236`). Extract it once, render it in Skills, and **retrofit AgentsPage + HarnessPage** to use it. (User principle: don't duplicate; package and reuse.)
+- **`SegmentedRadio` → `ui/`** (promotion, above).
+
+### 6.3 New components (package, don't inline)
+Each is a real reusable component so the list, detail panel, and dialogs share them — no per-call rewrites.
+- **`ui/components/ui/checkbox.tsx`** — there is NO checkbox primitive. Add one (Radix `@radix-ui/react-checkbox` is already in the dep tree via other Radix primitives) for the discovered-skills multi-select in the Add dialog. Mint check on `bg-mint`, `bg-surface-3` + `border-border-strong` unchecked — matches design.
+- **`SkillRow`** — one installed-skill row: lead icon, name + scope/inherited badge, description, source·version·updated meta, `BackendChip[]`, `⋯` actions. Used by both Global and Project lists. `selected` + `inherited` (dimmed) states.
+- **`BackendChip`** — small pill (dot + label) colored by backend. Reuse the backend→color map (claude=mint, opencode=cyan, codex=violet) — lift `BACKEND_LABEL`/`BACKEND_ICON_CLASS` from `AgentsPage.tsx:36-46` into a shared `lib/backends.ts` and import in both.
+- **`QualityMeter`** — the AI-quality block: big aiScore + 5 labeled bars (Safety/Clarity/Reusability/Completeness/Actionability), colored by score (≥9 mint, ≥8.5 cyan, else gold). Used in the detail panel and (compact aiScore pill) in Browse cards.
+- **`FileDropzone`** — dashed-border drop area with uploaded-file card + Replace; emits the File for `uploadSkillZip`. Generic enough to reuse later.
+- **`SkillDetailPanel`** — 400px panel: source card (repo/branch/path/stars/View-on-GitHub), description, `QualityMeter`, "Available to" backend `Switch` rows, commands (`askill run …` mono chips), footer (Open SKILL.md / Remove). Reuses `Field`, `Switch`, `Button`.
+- **`AddSkillDialog`** — the "Add a skill" modal. Top `SegmentedRadio` source switch (GitHub URL / Upload .zip); GitHub state = URL `Input` + Fetch; ZIP state = `FileDropzone`; shared lower half = discovered `Checkbox` list + scope `SegmentedRadio` + backend `Checkbox`/chip multiselect + footer CLI-hint + Cancel/Install. **Follow the existing workbench dialog convention** (`NewAgentDialog`/`NewProjectDialog` hand-roll a fixed overlay — match that, don't introduce the Radix `Dialog` here unless we migrate all of them).
+- **`BrowseRegistryDialog`** — search `Input` + tag-filter pills (`Popover`-less inline toggles) + scrollable result cards (`QualityMeter` compact + stars + tags + Add `Button`). Calls `findSkills`.
+- **`ProjectPicker`** — `Popover` dropdown listing `useApi().listProjects()` results (the same projects shown in the sidebar), active one checked, with skill counts + "Open a project folder…". Shown in Project scope.
+
+### 6.4 Surface → frame mapping
+- Global page → `ua2wX`. Project page + picker → `ZigTZ`. Add dialog (GitHub) → `gNDdF`. Add dialog (ZIP) → `KR9B0`. Browse dialog → `R2OBP`.
+
+## 7. i18n (`ui/src/i18n/en.json` + `zh.json`, kept 1:1)
+
+Add a top-level `"skills": { … }` block in BOTH files, modeled on the rich `agents.*` block (`en.json:1244-1314`): `title`, `subtitle` (`{{count}}`), `searchPlaceholder`, `scopeGlobal`, `scopeProject`, `browseRegistry`, `addSkill`, `empty`, `noSearchMatch`, `removeConfirm` (`{{name}}`), nested `detail:{…}`, `addDialog:{ githubTab, zipTab, urlLabel, fetch, dropzoneHint, foundCount, installTo, backends, install }`, `browse:{…}`. Reuse `common.*` (`refresh`, `cancel`, `delete`, `close`, …) — don't re-add. Backend error codes resolve via `errors.<code>` — add any new askill codes (`askill_not_found`, `MULTIPLE_SKILLS_REQUIRE_SELECTION`, `INVALID_AGENTS`, …).
+
+## 8. Pixel-perfect mandate (the part that has gone wrong before)
+
+**Rule: every number in the design maps to an exact class — never eyeball it.** Build from this table, then verify by screenshot-diff.
+
+### 8.1 Exact specs (from the frames)
+- **Page**: `max-w-[1200px] gap-5 py-2`. Body grid `lg:grid-cols-[1fr_400px] gap-5`.
+- **Header icon box**: `size-10 rounded-[10px] border border-mint/40 bg-mint-soft text-mint shadow-[0_0_18px_-6px_rgba(91,255,160,0.5)]`; icon `size-5`. Title `text-[24px] font-bold text-foreground`. Subtitle `text-[12px] text-muted`.
+- **Toolbar**: `flex items-center gap-2.5`. Search: `flex items-center gap-2 rounded-md border border-border-strong bg-surface px-3 py-2`, icon `size-3.5 text-muted`, input `text-[12px] … placeholder:text-muted`. (Note `rounded-md` = **8px** here.)
+- **Skill row**: `rounded-xl border px-4 py-3` (16px radius); default `border-border bg-surface`; selected `border-mint/40 bg-mint-soft shadow-[0_0_18px_-10px_rgba(91,255,160,0.6)]`; inherited `opacity-[0.66]`. Lead icon `size-9 rounded-[9px] bg-surface-3 border border-border`. Name `text-[14px] font-semibold`; desc `text-[11.5px] text-muted`; meta `font-mono text-[10px] text-muted`.
+- **Backend chip**: `rounded-full px-2 py-0.5 border` + `bg-mint-soft text-mint border-mint/40` (claude) / cyan / violet; `font-mono text-[10px]`.
+- **Detail panel**: `rounded-2xl border border-border-strong bg-surface p-5` (the design uses surface; AgentsPage uses the same). Section labels: `font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted`.
+- **Dialog**: `rounded-2xl border border-border-strong bg-surface-2` + `shadow-[0_24px_60px_-12px_rgba(0,0,0,0.7)]`; scrim `bg-[#05050B]/[0.72] backdrop-blur-[6px]`; footer band `bg-surface-3 border-t border-border`. CLI hint `font-mono text-[10.5px] text-muted`.
+- **Fonts**: body = **Inter**; all labels/badges/meta/code/CLI = **JetBrains Mono**. Weights per frame (600 semibold names, 700 bold titles/eyebrows).
+- **Radii**: 6=`rounded-sm`, 8=`rounded-md`, 12=`rounded-lg`, 16=`rounded-xl`, 20=`rounded-2xl`, pill=`rounded-full`.
+
+### 8.2 Token classes (all verified to resolve in `ui/src/index.css`)
+`bg-background bg-surface bg-surface-2 bg-surface-3 text-foreground text-muted bg-mint-soft text-mint bg-mint/[0.08] bg-cyan-soft text-cyan bg-violet-soft text-violet text-gold border-border border-border-strong border-mint/40`. Backend brand fills via these; mint glow via the `--shadow-mint-card` token or the explicit arbitrary shadows above.
+
+### 8.3 ⚠️ Do NOT use `text-pink` / `bg-pink/*` / `border-pink/*`
+There is no `--pink` token in `index.css`; those utilities compile to **nothing** (verified against `ui/dist`). AgentsPage/WorkbenchSidebar use them but they silently no-op. For destructive/remove use `Button variant="destructive-soft"` (its pink is a baked arbitrary hex) or `destructive`. If a true pink accent is ever wanted, first add `--pink`/`--pink-soft` to the `@theme inline` + every theme block in `index.css`.
+
+### 8.4 Verification loop (mandatory, per surface)
+1. `npm run build` / dev-serve the UI.
+2. Screenshot the surface at exactly **1440×900, dark** (use the `chrome-devtools` MCP or the `verify`/`browse` skill; resize viewport to 1440 wide).
+3. Export the matching `design.pen` frame to PNG and put them side by side; enumerate deltas in spacing, font-size, weight, color, radius, shadow, alignment.
+4. Fix until they match. Do not mark a surface done on "looks close" — match the table in §8.1.
+5. Run the existing UI build + a quick interaction pass (open dialog, toggle scope, etc.).
+
+## 9. Build order (atomic commits on this one branch; one PR at the checkpoint)
+
+1. **C1 · backend** — `core/services/skills.py` + `api.py` fns + `ui_server.py` routes + a focused pytest (mock the CLI: feed canned `--json` fixtures, assert parsing/shape; model on existing service tests). No UI yet.
+2. **C2 · api client + i18n** — `ApiContext` methods/types; `skills.*` en+zh (1:1).
+3. **C3 · primitives** — promote `SegmentedRadio`→`ui/`; add `ui/checkbox.tsx`; add `lib/backends.ts`; extract `WorkbenchPageHeader` + retrofit Agents/Harness.
+4. **C4 · list + detail** — `SkillRow`, `BackendChip`, `QualityMeter`, `SkillDetailPanel`, `SkillsPage` Global scope (frame `ua2wX`). Pixel-verify.
+5. **C5 · project scope** — `ProjectPicker`, two-section list, context bar (frame `ZigTZ`). Pixel-verify.
+6. **C6 · add dialog** — `AddSkillDialog` + `FileDropzone` + upload endpoint wiring (frames `gNDdF`, `KR9B0`). Pixel-verify.
+7. **C7 · browse dialog** — `BrowseRegistryDialog` (frame `R2OBP`). Pixel-verify.
+
+Per AGENTS.md: before opening the PR run the reviewer subagent and fix significant issues; open a **non-draft** PR naming the capability + evidence layers (unit/contract/manual); then keep a Codex review-fix loop via the `background-watch-hook` skill. `ruff check` changed Python before pushing; `npm run build` in `ui/`.
+
+## 10. Reuse rules (restated — the project's core principle)
+
+- Reuse an existing `ui/` primitive. If it doesn't fit, **extend it** (new `variant`/`size`/prop) or **promote** a near-duplicate (e.g. `SegmentedRadio`) into `ui/`. Only build new when nothing fits — and then build it as a real reusable component in the right place, not inline in a feature file.
+- The source of truth for variant names, radii, colors is `design.pen` ↔ `index.css`. Extend primitives to match those names so design ↔ code stay aligned.
+- One backend→color map, one page-header, one segmented control, one checkbox — shared, not copied. Touching three pages with the same header means extracting the header, not pasting it three times.
+
+## 11. Open dependencies & gotchas
+- **askill#11** (check/info `--json`, list metadata, find tag/limit) — build against the current contract; enrich `list` via SKILL.md frontmatter until it lands; defer the "update available" badge.
+- **askill must be installed** — `resolve_cli_path("askill")` may return `None`; surface a clear empty/CTA state ("Install askill" with the one-liner) instead of erroring.
+- **Memoized `ApiContext`** — don't break `useMemo([showToast, t])`.
+- **No `asyncio.run()`** in UI request paths; await on the loop.
+- **No textarea primitive** — hand-roll if needed (as AgentsPage does), or add one to `ui/`.
+- **Dialog overlay** — match the hand-rolled workbench dialog convention, not the Radix `Dialog`, unless migrating all workbench dialogs together.
diff --git a/tests/test_skills_service.py b/tests/test_skills_service.py
new file mode 100644
index 000000000..b6bbc56b3
--- /dev/null
+++ b/tests/test_skills_service.py
@@ -0,0 +1,179 @@
+"""Unit tests for core/services/skills.py — the askill CLI shell.
+
+Hermetic: the subprocess boundary (`_run_askill`) is monkeypatched with canned
+``--json`` envelopes, so these run without askill installed and without the
+network. They pin the command construction (scope / agent / install flags,
+``--skill`` selection, ``check`` / ``update``) and the error paths.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+
+import pytest
+
+from core.services import skills
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+class _Recorder:
+ """Stand-in for ``_run_askill`` that records args and returns a fixture."""
+
+ def __init__(self, result):
+ self.calls: list[dict] = []
+ self.result = result
+
+ async def __call__(self, askill_path, args, *, cwd=None, timeout=skills.DEFAULT_TIMEOUT):
+ self.calls.append({"path": askill_path, "args": list(args), "cwd": cwd})
+ return self.result
+
+
+def test_list_global_uses_g_no_cwd(monkeypatch):
+ rec = _Recorder({"ok": True, "skills": []})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ out = _run(skills.list_skills("askill", scope="global"))
+ assert out == {"ok": True, "skills": []}
+ assert rec.calls[0]["args"] == ["list", "-g"]
+ assert rec.calls[0]["cwd"] is None
+
+
+def test_list_project_uses_p_and_cwd_and_agents(monkeypatch):
+ rec = _Recorder({"ok": True, "skills": []})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.list_skills("askill", scope="project", project_dir="/p", backends=["claude", "codex"]))
+ # list supports -p; agents expand to askill ids under ONE variadic -a.
+ assert rec.calls[0]["args"] == ["list", "-p", "-a", "claude-code", "codex"]
+ assert rec.calls[0]["cwd"] == "/p"
+
+
+def test_add_global_all(monkeypatch):
+ rec = _Recorder({"ok": True, "action": "install"})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.add_skill("askill", "gh:o/r", scope="global", backends=["opencode"], all_skills=True))
+ assert rec.calls[0]["args"] == ["add", "gh:o/r", "-g", "-a", "opencode", "--all", "-y"]
+ assert rec.calls[0]["cwd"] is None
+
+
+def test_add_multi_backend_uses_single_a(monkeypatch):
+ # askill -a is variadic and each later -a REPLACES the prior values, so all
+ # selected agents must share one -a, else only the last backend installs.
+ rec = _Recorder({"ok": True, "action": "install"})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.add_skill("askill", "gh:o/r", scope="global", backends=["claude", "opencode", "codex"], all_skills=True))
+ assert rec.calls[0]["args"] == ["add", "gh:o/r", "-g", "-a", "claude-code", "opencode", "codex", "--all", "-y"]
+
+
+def test_add_project_has_no_p_flag_and_uses_cwd(monkeypatch):
+ # add/remove do NOT take -p — project scope is the default, selected by cwd.
+ rec = _Recorder({"ok": True, "action": "install"})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.add_skill("askill", "./pkg", scope="project", project_dir="/p", copy=True))
+ assert rec.calls[0]["args"] == ["add", "./pkg", "--copy", "-y"]
+ assert rec.calls[0]["cwd"] == "/p"
+
+
+def test_add_with_skill_selector(monkeypatch):
+ rec = _Recorder({"ok": True, "action": "install"})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.add_skill("askill", "./pkg", scope="project", project_dir="/p", skill="formatter", backends=["opencode"]))
+ assert rec.calls[0]["args"] == ["add", "./pkg", "-a", "opencode", "--skill", "formatter", "-y"]
+
+
+def test_preview_uses_list_flag(monkeypatch):
+ rec = _Recorder({"ok": True, "action": "preview", "skills": []})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.preview_source("askill", "gh:o/r", project_dir="/p"))
+ assert rec.calls[0]["args"] == ["add", "gh:o/r", "--list"]
+ assert rec.calls[0]["cwd"] == "/p"
+
+
+def test_remove_project_no_p_flag(monkeypatch):
+ rec = _Recorder({"ok": True})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.remove_skill("askill", "pdf-tools", scope="project", project_dir="/p", backends=["claude"]))
+ assert rec.calls[0]["args"] == ["remove", "pdf-tools", "-a", "claude-code"]
+ assert rec.calls[0]["cwd"] == "/p"
+
+
+def test_remove_global(monkeypatch):
+ rec = _Recorder({"ok": True})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.remove_skill("askill", "pdf-tools", scope="global"))
+ assert rec.calls[0]["args"] == ["remove", "pdf-tools", "-g"]
+ assert rec.calls[0]["cwd"] is None
+
+
+def test_find_passes_query(monkeypatch):
+ rec = _Recorder({"ok": True, "skills": [{"name": "memory"}]})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ out = _run(skills.find_skills("askill", "memory"))
+ assert rec.calls[0]["args"] == ["find", "memory"]
+ assert out["skills"][0]["name"] == "memory"
+
+
+def test_check_global_and_project(monkeypatch):
+ rec = _Recorder({"ok": True, "summary": {}, "skills": []})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.check("askill", scope="global"))
+ assert rec.calls[0]["args"] == ["check", "-g"]
+ assert rec.calls[0]["cwd"] is None
+ _run(skills.check("askill", scope="project", project_dir="/p"))
+ assert rec.calls[1]["args"] == ["check"]
+ assert rec.calls[1]["cwd"] == "/p"
+
+
+def test_update_one_skill(monkeypatch):
+ rec = _Recorder({"ok": True, "results": []})
+ monkeypatch.setattr(skills, "_run_askill", rec)
+ _run(skills.update("askill", "pdf-tools", scope="project", project_dir="/p"))
+ assert rec.calls[0]["args"] == ["update", "pdf-tools", "-y"]
+ assert rec.calls[0]["cwd"] == "/p"
+ _run(skills.update("askill", "pdf-tools", scope="global"))
+ assert rec.calls[1]["args"] == ["update", "pdf-tools", "-g", "-y"]
+
+
+def test_invalid_backend_raises(monkeypatch):
+ monkeypatch.setattr(skills, "_run_askill", _Recorder({"ok": True}))
+ with pytest.raises(skills.SkillsError) as info:
+ _run(skills.list_skills("askill", scope="all", backends=["bogus"]))
+ assert info.value.code == "invalid_backend"
+
+
+def test_invalid_scope_raises(monkeypatch):
+ monkeypatch.setattr(skills, "_run_askill", _Recorder({"ok": True}))
+ with pytest.raises(skills.SkillsError) as info:
+ _run(skills.add_skill("askill", "gh:o/r", scope="all"))
+ assert info.value.code == "invalid_scope"
+
+
+def test_project_scope_requires_project_dir(monkeypatch):
+ # A project-scoped op without a project dir must not fall back to the
+ # server's cwd — it raises so the route returns an error instead.
+ monkeypatch.setattr(skills, "_run_askill", _Recorder({"ok": True}))
+ for call in (
+ lambda: skills.add_skill("askill", "gh:o/r", scope="project"),
+ lambda: skills.remove_skill("askill", "x", scope="project"),
+ lambda: skills.check("askill", scope="project"),
+ lambda: skills.update("askill", "x", scope="project"),
+ ):
+ with pytest.raises(skills.SkillsError) as info:
+ _run(call())
+ assert info.value.code == "project_required"
+
+
+def test_subprocess_env_prepends_binary_dir(monkeypatch):
+ # askill is a Node CLI; its bin dir (where node lives) must lead PATH.
+ monkeypatch.setenv("PATH", os.pathsep.join(["/usr/bin", "/bin"]))
+ env = skills._subprocess_env("/opt/nvm/v20/bin/askill")
+ parts = env["PATH"].split(os.pathsep)
+ assert parts[0] == "/opt/nvm/v20/bin"
+ assert "/usr/bin" in parts
+
+
+def test_missing_binary_raises_lookup():
+ with pytest.raises(LookupError):
+ _run(skills._run_askill("", ["list"]))
diff --git a/ui/src/components/settings/shared/SegmentedRadio.tsx b/ui/src/components/settings/shared/SegmentedRadio.tsx
index 07f371293..4c291670a 100644
--- a/ui/src/components/settings/shared/SegmentedRadio.tsx
+++ b/ui/src/components/settings/shared/SegmentedRadio.tsx
@@ -1,73 +1,5 @@
-import clsx from 'clsx';
-
-/**
- * Generic segmented-radio control used by the Settings → Backends auth-mode
- * tabs (Claude / Codex / OpenCode) and elsewhere. Previously cloned inline in
- * every page that needed it; lifted here once a third caller appeared.
- *
- * Visual contract mirrors ``shared/RoutingConfigPanel.tsx``:
- * - The whole row is one `role="radiogroup"` with the active option styled
- * mint-on-mint-soft and inactive options muted.
- * - When ``disabled`` is true, the row dims and individual buttons reject
- * clicks. Callers that need a stronger lock (e.g. defending against an iOS
- * Safari quirk where ``disabled`` buttons still register a tap) should
- * ALSO guard the state mutation site itself — see ``useOAuthFlowLock``.
- *
- * The generic ``T`` is a string-literal union of the radio's possible
- * values, so ``onChange`` is typed strictly to the option ids.
- */
-export type SegmentedRadioOption<T extends string> = {
- id: T;
- label: string;
-};
-
-export interface SegmentedRadioProps<T extends string> {
- value: T;
- onChange: (next: T) => void;
- options: ReadonlyArray<SegmentedRadioOption<T>>;
- ariaLabel: string;
- disabled?: boolean;
-}
-
-export function SegmentedRadio<T extends string>({
- value,
- onChange,
- options,
- ariaLabel,
- disabled,
-}: SegmentedRadioProps<T>) {
- return (
- <div
- role="radiogroup"
- aria-label={ariaLabel}
- aria-disabled={disabled || undefined}
- className={clsx(
- 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',
- disabled && 'opacity-60',
- )}
- >
- {options.map((opt) => {
- const active = value === opt.id;
- return (
- <button
- key={opt.id}
- type="button"
- role="radio"
- aria-checked={active}
- disabled={disabled}
- onClick={() => onChange(opt.id)}
- className={clsx(
- 'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',
- active
- ? 'border border-mint/30 bg-mint-soft font-bold text-mint'
- : 'font-medium text-muted hover:text-foreground',
- disabled && 'cursor-not-allowed',
- )}
- >
- {opt.label}
- </button>
- );
- })}
- </div>
- );
-}
+// Promoted to `ui/segmented.tsx` (now used outside Settings, by the Workbench
+// Skills page). This thin re-export keeps existing Settings imports working;
+// new callers should import from `@/components/ui/segmented` directly.
+export { SegmentedRadio } from '../../ui/segmented';
+export type { SegmentedRadioOption, SegmentedRadioProps } from '../../ui/segmented';
diff --git a/ui/src/components/ui/checkbox.tsx b/ui/src/components/ui/checkbox.tsx
new file mode 100644
index 000000000..b018b5d8a
--- /dev/null
+++ b/ui/src/components/ui/checkbox.tsx
@@ -0,0 +1,52 @@
+import { Check } from 'lucide-react';
+import clsx from 'clsx';
+
+export interface CheckboxProps {
+ checked: boolean;
+ onCheckedChange?: (next: boolean) => void;
+ disabled?: boolean;
+ label?: string;
+ className?: string;
+ /**
+ * Render a non-interactive visual box instead of a button. Use this inside a
+ * clickable row that already owns the toggle and the `checkbox` role — it
+ * avoids nested buttons and the double-toggle that follows from both the row
+ * and the checkbox firing the same handler.
+ */
+ presentational?: boolean;
+}
+
+/**
+ * Lightweight controlled checkbox (no Radix dependency — the repo only pulls
+ * in `@radix-ui/react-dialog`, and a checkbox this simple doesn't warrant a
+ * new one). Mint fill + dark check when checked; bordered surface when not.
+ * Visual contract mirrors design.pen's multi-select rows.
+ */
+export function Checkbox({ checked, onCheckedChange, disabled, label, className, presentational }: CheckboxProps) {
+ const visual = clsx(
+ 'flex size-[18px] shrink-0 items-center justify-center rounded-[5px] border transition-colors',
+ checked ? 'border-transparent bg-mint text-[#06060e]' : 'border-border-strong bg-surface-3 text-transparent',
+ disabled && 'cursor-not-allowed opacity-50',
+ className,
+ );
+ if (presentational) {
+ return (
+ <span aria-hidden className={clsx(visual, 'pointer-events-none')}>
+ <Check className="size-3" strokeWidth={3} />
+ </span>
+ );
+ }
+ return (
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={checked}
+ aria-label={label}
+ disabled={disabled}
+ onClick={() => onCheckedChange?.(!checked)}
+ className={visual}
+ >
+ <Check className="size-3" strokeWidth={3} />
+ </button>
+ );
+}
diff --git a/ui/src/components/ui/segmented.tsx b/ui/src/components/ui/segmented.tsx
new file mode 100644
index 000000000..b4251932a
--- /dev/null
+++ b/ui/src/components/ui/segmented.tsx
@@ -0,0 +1,74 @@
+import clsx from 'clsx';
+
+/**
+ * Generic segmented-radio control. Promoted here from
+ * `settings/shared/SegmentedRadio` once a non-Settings caller (the Workbench
+ * Skills page) needed it — the shared home is `ui/`, and Settings keeps
+ * importing it via a thin re-export shim.
+ *
+ * Visual contract:
+ * - The whole row is one `role="radiogroup"` with the active option styled
+ * mint-on-mint-soft and inactive options muted.
+ * - When `disabled` is true, the row dims and individual buttons reject
+ * clicks. Callers that need a stronger lock (e.g. defending against an iOS
+ * Safari quirk where `disabled` buttons still register a tap) should ALSO
+ * guard the state mutation site itself — see `useOAuthFlowLock`.
+ *
+ * The generic `T` is a string-literal union of the radio's possible values,
+ * so `onChange` is typed strictly to the option ids.
+ */
+export type SegmentedRadioOption<T extends string> = {
+ id: T;
+ label: string;
+};
+
+export interface SegmentedRadioProps<T extends string> {
+ value: T;
+ onChange: (next: T) => void;
+ options: ReadonlyArray<SegmentedRadioOption<T>>;
+ ariaLabel: string;
+ disabled?: boolean;
+}
+
+export function SegmentedRadio<T extends string>({
+ value,
+ onChange,
+ options,
+ ariaLabel,
+ disabled,
+}: SegmentedRadioProps<T>) {
+ return (
+ <div
+ role="radiogroup"
+ aria-label={ariaLabel}
+ aria-disabled={disabled || undefined}
+ className={clsx(
+ 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',
+ disabled && 'opacity-60',
+ )}
+ >
+ {options.map((opt) => {
+ const active = value === opt.id;
+ return (
+ <button
+ key={opt.id}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ disabled={disabled}
+ onClick={() => onChange(opt.id)}
+ className={clsx(
+ 'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',
+ active
+ ? 'border border-mint/30 bg-mint-soft font-bold text-mint'
+ : 'font-medium text-muted hover:text-foreground',
+ disabled && 'cursor-not-allowed',
+ )}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 51b1aadfb..b679ecd49 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -30,21 +30,15 @@ import type { ComboboxOption } from '../ui/combobox';
import { Textarea } from '../ui/textarea';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { estimateTokens } from '../../lib/tokenEstimate';
-
-const BACKEND_ORDER = ['claude', 'opencode', 'codex'] as const;
-type Backend = (typeof BACKEND_ORDER)[number];
-
-const BACKEND_LABEL: Record<Backend, string> = {
- claude: 'Claude',
- opencode: 'OpenCode',
- codex: 'Codex',
-};
-
-const BACKEND_ICON_CLASS: Record<Backend, string> = {
- claude: 'text-mint',
- opencode: 'text-cyan',
- codex: 'text-violet',
-};
+import { WorkbenchPageHeader } from './WorkbenchPageHeader';
+// Backend order / labels / accent classes live in lib/backendAccent, shared
+// with the Skills surface (BACKEND_TEXT is this page's old BACKEND_ICON_CLASS).
+import {
+ BACKEND_ORDER,
+ BACKEND_LABEL,
+ BACKEND_TEXT as BACKEND_ICON_CLASS,
+ type Backend,
+} from '../../lib/backendAccent';
const EFFORT_OPTIONS = ['low', 'medium', 'high', 'max'];
// Sentinel option that clears the model override back to the backend default
@@ -221,20 +215,18 @@ export const AgentsPage: React.FC = () => {
return (
<div className="mx-auto flex w-full max-w-[1200px] flex-col gap-5 py-2">
- {/* Header — design.pen l5V2m: 40x40 mint-soft icon + title + subtitle */}
- <div className="flex items-center gap-4">
- <div className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/40 bg-mint-soft text-mint shadow-[0_0_18px_-6px_rgba(91,255,160,0.5)]">
- <Bot className="size-5" />
- </div>
- <div className="flex flex-1 flex-col">
- <h1 className="text-[24px] font-bold text-foreground">{t('agents.title')}</h1>
- <p className="text-[12px] text-muted">{t('agents.subtitle', { count: agents.length })}</p>
- </div>
- <Button type="button" variant="outline" size="xs" onClick={() => refresh()} disabled={loading}>
- <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />
- {t('common.refresh')}
- </Button>
- </div>
+ {/* Header — shared WorkbenchPageHeader (design.pen: 40px mint icon + title + subtitle). */}
+ <WorkbenchPageHeader
+ icon={<Bot className="size-5" />}
+ title={t('agents.title')}
+ subtitle={t('agents.subtitle', { count: agents.length })}
+ actions={
+ <Button type="button" variant="outline" size="xs" onClick={() => refresh()} disabled={loading}>
+ <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />
+ {t('common.refresh')}
+ </Button>
+ }
+ />
{/* Toolbar — design.pen Imduv: search + backend filter + spacer + Import + 新建 Agent */}
<div className="flex flex-wrap items-center gap-2.5">
diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsx
index aadc6725c..0f11ca12e 100644
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@ -1,6 +1,422 @@
-import { WandSparkles } from 'lucide-react';
-import { WorkbenchModulePlaceholder } from './WorkbenchModulePlaceholder';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ChevronDown, Compass, Funnel, Info, Plus, RefreshCw, Search, Terminal, WandSparkles } from 'lucide-react';
+import clsx from 'clsx';
-export const SkillsPage: React.FC = () => (
- <WorkbenchModulePlaceholder icon={<WandSparkles className="size-6" />} i18nPrefix="workbench.modules.skills" />
-);
+import { useApi } from '../../context/ApiContext';
+import type { SkillBrief, SkillCheckItem, SkillScope, WorkbenchProject } from '../../context/ApiContext';
+import { useToast } from '../../context/ToastContext';
+import { BACKEND_LABEL, BACKEND_ORDER, backendsFromAgents, type Backend } from '../../lib/backendAccent';
+import { Button } from '../ui/button';
+import { SegmentedRadio } from '../ui/segmented';
+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
+import { WorkbenchPageHeader } from './WorkbenchPageHeader';
+import { SkillRow } from './skills/SkillRow';
+import { SkillDetailPanel } from './skills/SkillDetailPanel';
+import { ProjectPicker } from './skills/ProjectPicker';
+import { AddSkillDialog } from './skills/AddSkillDialog';
+import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';
+
+const skillKey = (s: SkillBrief) => `${s.scope}:${s.name}`;
+
+export const SkillsPage: React.FC = () => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+
+ const [scope, setScope] = useState<SkillScope>('global');
+ const [projects, setProjects] = useState<WorkbenchProject[]>([]);
+ const [projectId, setProjectId] = useState<string | null>(null);
+ const [skills, setSkills] = useState<SkillBrief[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [notInstalled, setNotInstalled] = useState(false);
+ const [search, setSearch] = useState('');
+ const [backendFilter, setBackendFilter] = useState<Backend | 'all'>('all');
+ const [selectedKey, setSelectedKey] = useState<string | null>(null);
+ const [busyBackend, setBusyBackend] = useState<Backend | null>(null);
+ const [showAdd, setShowAdd] = useState(false);
+ const [showBrowse, setShowBrowse] = useState(false);
+ const [checkMap, setCheckMap] = useState<Record<string, SkillCheckItem>>({});
+ const [updating, setUpdating] = useState(false);
+
+ const activeProject = projects.find((p) => p.id === projectId) ?? null;
+
+ useEffect(() => {
+ api
+ .listProjects()
+ .then((res) => {
+ setProjects(res.projects);
+ setProjectId((prev) => prev ?? res.projects[0]?.id ?? null);
+ })
+ .catch(() => undefined);
+ }, [api]);
+
+ const listReq = useRef(0);
+ const refresh = useCallback(async () => {
+ // Global tab → just global skills. Project tab → list everything for the
+ // project (cwd) so we can split project-local vs inherited-from-global.
+ if (scope === 'project' && !projectId) {
+ setSkills([]);
+ return;
+ }
+ // Token guard: a slower list for a previous project/scope must not land
+ // after a faster one for the current selection and replace its rows.
+ const reqId = (listReq.current += 1);
+ setLoading(true);
+ setError(null);
+ setNotInstalled(false);
+ try {
+ const res = await api.listSkills(
+ scope === 'global' ? { scope: 'global' } : { scope: 'all', projectId: projectId ?? undefined },
+ );
+ if (reqId !== listReq.current) return; // superseded by a newer refresh
+ if (res.ok) {
+ setSkills(res.skills ?? []);
+ } else if (res.error?.code === 'askill_not_found') {
+ setNotInstalled(true);
+ setSkills([]);
+ } else {
+ setError(res.error?.message ?? 'Failed to list skills');
+ setSkills([]);
+ }
+ } catch (err: any) {
+ if (reqId === listReq.current) setError(err?.message ?? String(err));
+ } finally {
+ if (reqId === listReq.current) setLoading(false);
+ }
+ }, [api, scope, projectId]);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ // Fetch update status (askill check) once the list loads so rows can show an
+ // "update available" badge. Best-effort; failures just clear it.
+ useEffect(() => {
+ if (notInstalled || (scope === 'project' && !projectId)) {
+ setCheckMap({});
+ return;
+ }
+ let cancelled = false;
+ // Project view lists project-local AND inherited-global rows, so check both
+ // scopes and merge — otherwise inherited globals never get an update badge.
+ const scopes = scope === 'global' ? (['global'] as const) : (['global', 'project'] as const);
+ Promise.all(
+ scopes.map((s) =>
+ api
+ .checkSkills({ scope: s, projectId: s === 'project' ? projectId ?? undefined : undefined })
+ .catch(() => null),
+ ),
+ )
+ .then((resList) => {
+ if (cancelled) return;
+ const map: Record<string, SkillCheckItem> = {};
+ for (const res of resList) for (const item of res?.skills ?? []) map[`${item.scope}:${item.name}`] = item;
+ setCheckMap(map);
+ })
+ .catch(() => {
+ if (!cancelled) setCheckMap({});
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [api, scope, projectId, skills, notInstalled]);
+
+ const matches = useCallback(
+ (skill: SkillBrief) => {
+ if (backendFilter !== 'all' && !backendsFromAgents(skill.agents).includes(backendFilter)) return false;
+ const q = search.trim().toLowerCase();
+ if (!q) return true;
+ return skill.name.toLowerCase().includes(q) || (skill.description ?? '').toLowerCase().includes(q);
+ },
+ [search, backendFilter],
+ );
+
+ const filtered = useMemo(() => skills.filter(matches), [skills, matches]);
+ const projectLocal = useMemo(() => filtered.filter((s) => s.scope === 'project'), [filtered]);
+ const inheritedGlobal = useMemo(() => filtered.filter((s) => s.scope === 'global'), [filtered]);
+ const selected = useMemo(() => skills.find((s) => skillKey(s) === selectedKey) ?? null, [skills, selectedKey]);
+ // In Project scope `skills` also carries inherited-global rows; only
+ // project-local installs should mark a registry result as already installed,
+ // so users can still add a project-local copy of a globally installed skill.
+ const installedNames = useMemo(
+ () => new Set(skills.filter((s) => scope !== 'project' || s.scope === 'project').map((s) => s.name)),
+ [skills, scope],
+ );
+
+ const onToggleBackend = async (backend: Backend, next: boolean) => {
+ if (!selected) return;
+ setBusyBackend(backend);
+ try {
+ const projectArg = selected.scope === 'project' ? projectId ?? undefined : undefined;
+ const res = next
+ ? await api.addSkill({ source: selected.path, scope: selected.scope, projectId: projectArg, backends: [backend] })
+ : await api.removeSkill(selected.name, { scope: selected.scope, projectId: projectArg, backends: [backend] });
+ if (!res.ok) showToast(res.error?.message ?? BACKEND_LABEL[backend], 'error');
+ await refresh();
+ } catch (err: any) {
+ showToast(err?.message ?? String(err), 'error');
+ } finally {
+ setBusyBackend(null);
+ }
+ };
+
+ const onRemove = async () => {
+ if (!selected) return;
+ if (!window.confirm(t('skills.removeConfirm', { name: selected.name }))) return;
+ try {
+ const projectArg = selected.scope === 'project' ? projectId ?? undefined : undefined;
+ const res = await api.removeSkill(selected.name, { scope: selected.scope, projectId: projectArg });
+ if (res.ok) {
+ showToast(t('skills.removeSuccess', { name: selected.name }), 'success');
+ setSelectedKey(null);
+ await refresh();
+ } else {
+ showToast(res.error?.message ?? selected.name, 'error');
+ }
+ } catch (err: any) {
+ showToast(err?.message ?? String(err), 'error');
+ }
+ };
+
+ const onUpdate = async () => {
+ if (!selected) return;
+ setUpdating(true);
+ try {
+ const projectArg = selected.scope === 'project' ? projectId ?? undefined : undefined;
+ const res = await api.updateSkill(selected.name, { scope: selected.scope, projectId: projectArg });
+ if (res.ok) {
+ showToast(t('skills.updateSuccess', { name: selected.name }), 'success');
+ await refresh();
+ } else {
+ showToast(res.error?.message ?? selected.name, 'error');
+ }
+ } catch (err: any) {
+ showToast(err?.message ?? String(err), 'error');
+ } finally {
+ setUpdating(false);
+ }
+ };
+
+ const afterDialog = () => {
+ setShowAdd(false);
+ setShowBrowse(false);
+ refresh();
+ };
+
+ const renderRows = (list: SkillBrief[], inherited?: boolean) =>
+ list.map((skill) => (
+ <SkillRow
+ key={skillKey(skill)}
+ skill={skill}
+ inherited={inherited}
+ updateAvailable={checkMap[skillKey(skill)]?.status === 'update_available'}
+ selected={selectedKey === skillKey(skill)}
+ onSelect={() => setSelectedKey(skillKey(skill))}
+ />
+ ));
+
+ const sectionLabel = (icon: React.ReactNode, label: string, hint?: string) => (
+ <div className="flex items-center gap-2 px-1">
+ {icon}
+ <span className="font-mono text-[10.5px] font-bold uppercase tracking-[0.1em] text-muted">{label}</span>
+ {hint ? <span className="font-mono text-[10px] text-muted">· {hint}</span> : null}
+ </div>
+ );
+
+ return (
+ <div className="mx-auto flex w-full max-w-[1200px] flex-col gap-5 py-2">
+ <WorkbenchPageHeader
+ icon={<WandSparkles className="size-5" />}
+ title={t('skills.title')}
+ subtitle={t('skills.subtitle')}
+ actions={
+ <Button type="button" variant="outline" size="xs" onClick={() => refresh()} disabled={loading}>
+ <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />
+ {t('common.refresh')}
+ </Button>
+ }
+ />
+
+ <div className="flex flex-wrap items-center gap-2.5">
+ <SegmentedRadio<SkillScope>
+ value={scope}
+ onChange={setScope}
+ ariaLabel={t('skills.scopeGlobal')}
+ options={[
+ { id: 'global', label: t('skills.scopeGlobal') },
+ { id: 'project', label: t('skills.scopeProject') },
+ ]}
+ />
+ {scope === 'project' && projects.length > 0 ? (
+ <ProjectPicker projects={projects} value={projectId} onChange={setProjectId} />
+ ) : null}
+
+ <div className="flex min-w-[220px] flex-1 items-center gap-2 rounded-md border border-border-strong bg-surface px-3 py-2">
+ <Search className="size-3.5 shrink-0 text-muted" />
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t(scope === 'project' ? 'skills.searchProjectPlaceholder' : 'skills.searchPlaceholder')}
+ className="flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted"
+ />
+ </div>
+
+ <BackendFilter value={backendFilter} onChange={setBackendFilter} />
+
+ <Button type="button" variant="outline" size="xs" onClick={() => setShowBrowse(true)}>
+ <Compass className="size-3.5 text-cyan" />
+ {t('skills.browseRegistry')}
+ </Button>
+ <Button type="button" variant="brand" size="xs" onClick={() => setShowAdd(true)}>
+ <Plus />
+ {t('skills.addSkill')}
+ </Button>
+ </div>
+
+ {scope === 'project' && activeProject ? (
+ <div className="flex items-center gap-2 rounded-[10px] border border-border-strong bg-surface-2 px-3.5 py-2.5">
+ <span className="truncate font-mono text-[10.5px] text-muted">{activeProject.folder_path}/.agents/skills</span>
+ <div className="flex-1" />
+ <Info className="size-3 text-muted" />
+ <span className="text-[11px] text-muted">{t('skills.globalAlsoAvailable')}</span>
+ </div>
+ ) : null}
+
+ {error ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">{error}</div>
+ ) : null}
+
+ {notInstalled ? (
+ <div className="flex flex-col items-center gap-2 rounded-xl border border-dashed border-border bg-surface px-6 py-12 text-center">
+ <Terminal className="size-7 text-muted" />
+ <div className="text-[14px] font-semibold text-foreground">{t('skills.notInstalled')}</div>
+ <div className="font-mono text-[11.5px] text-muted">{t('skills.notInstalledHint')}</div>
+ </div>
+ ) : (
+ <div className={clsx('grid gap-5', selected ? 'lg:grid-cols-[1fr_400px]' : 'grid-cols-1')}>
+ <div className="flex flex-col gap-4">
+ {scope === 'global' ? (
+ <div className="flex flex-col gap-2">{renderRows(filtered)}</div>
+ ) : (
+ <>
+ <div className="flex flex-col gap-2">
+ {sectionLabel(
+ <WandSparkles className="size-3.5 text-mint" />,
+ t('skills.projectSectionLocal'),
+ t('skills.projectSectionLocalHint'),
+ )}
+ {projectLocal.length > 0 ? (
+ <div className="flex flex-col gap-2">{renderRows(projectLocal)}</div>
+ ) : (
+ <div className="rounded-xl border border-dashed border-border bg-surface px-4 py-6 text-center text-[12px] text-muted">
+ {t('skills.empty')}
+ </div>
+ )}
+ </div>
+ {inheritedGlobal.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ {sectionLabel(
+ <Info className="size-3.5 text-muted" />,
+ t('skills.projectSectionGlobal'),
+ t('skills.projectSectionGlobalHint'),
+ )}
+ <div className="flex flex-col gap-2">{renderRows(inheritedGlobal, true)}</div>
+ </div>
+ ) : null}
+ </>
+ )}
+
+ {!loading && filtered.length === 0 && scope === 'global' ? (
+ <div className="rounded-xl border border-dashed border-border bg-surface px-6 py-12 text-center text-[12px] text-muted">
+ {skills.length === 0 ? t('skills.empty') : t('skills.noSearchMatch')}
+ </div>
+ ) : null}
+ </div>
+
+ {selected ? (
+ <SkillDetailPanel
+ skill={selected}
+ projectName={activeProject?.display_name}
+ busyBackend={busyBackend}
+ check={checkMap[skillKey(selected)]}
+ updating={updating}
+ onClose={() => setSelectedKey(null)}
+ onToggleBackend={onToggleBackend}
+ onUpdate={onUpdate}
+ onRemove={onRemove}
+ />
+ ) : null}
+ </div>
+ )}
+
+ {showAdd ? (
+ <AddSkillDialog
+ defaultScope={scope}
+ projectId={projectId ?? undefined}
+ projectName={activeProject?.display_name}
+ onClose={() => setShowAdd(false)}
+ onInstalled={afterDialog}
+ />
+ ) : null}
+ {showBrowse ? (
+ <BrowseRegistryDialog
+ scope={scope}
+ projectId={scope === 'project' ? projectId ?? undefined : undefined}
+ installedNames={installedNames}
+ onClose={() => setShowBrowse(false)}
+ onInstalled={afterDialog}
+ />
+ ) : null}
+ </div>
+ );
+};
+
+interface BackendFilterProps {
+ value: Backend | 'all';
+ onChange: (next: Backend | 'all') => void;
+}
+
+// Compact funnel popover, mirroring AgentsPage's BackendFilter idiom.
+const BackendFilter: React.FC<BackendFilterProps> = ({ value, onChange }) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const label = value === 'all' ? t('skills.backendAll') : BACKEND_LABEL[value];
+ const dot = (key: Backend | 'all') =>
+ key === 'all' ? 'bg-muted' : key === 'claude' ? 'bg-mint' : key === 'opencode' ? 'bg-cyan' : 'bg-violet';
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="flex items-center gap-1.5 rounded-md border border-border-strong bg-surface px-3 py-2 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"
+ >
+ <Funnel className="size-3 text-muted" />
+ <span className="text-muted">{t('skills.backendFilter')}:</span>
+ <span>{label}</span>
+ <ChevronDown className="size-3 text-muted" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[180px] p-1">
+ {(['all', ...BACKEND_ORDER] as const).map((key) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => {
+ onChange(key);
+ setOpen(false);
+ }}
+ className={clsx(
+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] transition',
+ value === key ? 'bg-mint-soft text-mint' : 'text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ <span className={clsx('size-2 rounded-full', dot(key))} />
+ <span>{key === 'all' ? t('skills.backendAll') : BACKEND_LABEL[key as Backend]}</span>
+ </button>
+ ))}
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/ui/src/components/workbench/WorkbenchPageHeader.tsx b/ui/src/components/workbench/WorkbenchPageHeader.tsx
new file mode 100644
index 000000000..df8b3a27b
--- /dev/null
+++ b/ui/src/components/workbench/WorkbenchPageHeader.tsx
@@ -0,0 +1,48 @@
+import type { ReactNode } from 'react';
+import clsx from 'clsx';
+
+type Accent = 'mint' | 'cyan' | 'violet' | 'gold';
+
+// Accent-driven icon-box surface. The mint variant is the canonical workbench
+// page header (Agents, Skills); cyan/violet/gold are available for siblings.
+const ACCENT_BOX: Record<Accent, string> = {
+ mint: 'border-mint/40 bg-mint-soft text-mint shadow-[0_0_18px_-6px_rgba(91,255,160,0.5)]',
+ cyan: 'border-cyan/40 bg-cyan-soft text-cyan shadow-[0_0_18px_-6px_rgba(63,224,229,0.5)]',
+ violet: 'border-violet/40 bg-violet-soft text-violet shadow-[0_0_18px_-6px_rgba(124,91,255,0.5)]',
+ gold: 'border-gold/40 bg-gold/[0.12] text-gold shadow-[0_0_18px_-6px_rgba(255,200,87,0.5)]',
+};
+
+export interface WorkbenchPageHeaderProps {
+ icon: ReactNode;
+ title: string;
+ subtitle?: string;
+ accent?: Accent;
+ /** Right-aligned actions (buttons). */
+ actions?: ReactNode;
+}
+
+/**
+ * Shared workbench page header: a 40px accent icon-box + title + subtitle +
+ * optional right-aligned actions. Mirrors design.pen (the Agents / Skills page
+ * headers are identical bar the icon + copy). Extracted so capability pages
+ * reuse one header instead of re-rolling the markup.
+ */
+export function WorkbenchPageHeader({ icon, title, subtitle, accent = 'mint', actions }: WorkbenchPageHeaderProps) {
+ return (
+ <div className="flex items-center gap-4">
+ <div
+ className={clsx(
+ 'flex size-10 shrink-0 items-center justify-center rounded-[10px] border',
+ ACCENT_BOX[accent],
+ )}
+ >
+ {icon}
+ </div>
+ <div className="flex flex-1 flex-col">
+ <h1 className="text-[24px] font-bold text-foreground">{title}</h1>
+ {subtitle ? <p className="text-[12px] text-muted">{subtitle}</p> : null}
+ </div>
+ {actions}
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/skills/AddSkillDialog.tsx b/ui/src/components/workbench/skills/AddSkillDialog.tsx
new file mode 100644
index 000000000..b306df679
--- /dev/null
+++ b/ui/src/components/workbench/skills/AddSkillDialog.tsx
@@ -0,0 +1,337 @@
+import { useMemo, useRef, useState } from 'react';
+import { Check, Download, Github, Loader2, PackageCheck, PackagePlus, Search, Terminal, X } from 'lucide-react';
+import clsx from 'clsx';
+import { useTranslation } from 'react-i18next';
+import { useApi } from '../../../context/ApiContext';
+import type { SkillDiscovered, SkillScope } from '../../../context/ApiContext';
+import { useToast } from '../../../context/ToastContext';
+import { SegmentedRadio } from '../../ui/segmented';
+import { Checkbox } from '../../ui/checkbox';
+import { BACKEND_CHIP, BACKEND_LABEL, BACKEND_ORDER, type Backend } from '../../../lib/backendAccent';
+import { FileDropzone } from './FileDropzone';
+
+const AGENT_OF: Record<Backend, string> = { claude: 'claude-code', opencode: 'opencode', codex: 'codex' };
+
+export interface AddSkillDialogProps {
+ defaultScope: SkillScope;
+ projectId?: string;
+ projectName?: string;
+ onClose: () => void;
+ onInstalled: () => void;
+}
+
+type SourceTab = 'github' | 'zip';
+
+/** "Add a skill" modal — import from a GitHub URL/slug or an uploaded .zip. */
+export function AddSkillDialog({ defaultScope, projectId, projectName, onClose, onInstalled }: AddSkillDialogProps) {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+
+ const [source, setSource] = useState<SourceTab>('github');
+ const [url, setUrl] = useState('');
+ const [file, setFile] = useState<File | null>(null);
+ const [uploadDir, setUploadDir] = useState<string | null>(null);
+ const [discovered, setDiscovered] = useState<SkillDiscovered[] | null>(null);
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [scope, setScope] = useState<SkillScope>(projectId ? defaultScope : 'global');
+ const [backends, setBackends] = useState<Set<Backend>>(new Set(BACKEND_ORDER));
+ const [busy, setBusy] = useState<'fetch' | 'install' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // Monotonic token: a slow preview that resolves after the source changed must
+ // not repopulate `discovered` with skills from the previous source.
+ const previewReq = useRef(0);
+
+ const baseSource = source === 'github' ? url.trim() : uploadDir;
+
+ const reset = () => {
+ previewReq.current += 1;
+ setDiscovered(null);
+ setSelected(new Set());
+ setError(null);
+ };
+
+ const onDiscovered = (skills: SkillDiscovered[]) => {
+ setDiscovered(skills);
+ setSelected(new Set(skills.map((s) => s.name)));
+ };
+
+ const fetchGithub = async () => {
+ if (!url.trim()) return;
+ const reqId = (previewReq.current += 1);
+ setBusy('fetch');
+ setError(null);
+ try {
+ const res = await api.previewSkillSource(url.trim(), { projectId });
+ if (reqId !== previewReq.current) return; // a newer source superseded this
+ if (res.ok && res.skills) onDiscovered(res.skills);
+ else setError(res.error?.message ?? t('skills.addDialog.fetchFirst'));
+ } catch (err: any) {
+ if (reqId === previewReq.current) setError(err?.message ?? String(err));
+ } finally {
+ if (reqId === previewReq.current) setBusy(null);
+ }
+ };
+
+ const onPickFile = async (picked: File | null) => {
+ setFile(picked);
+ reset();
+ setUploadDir(null);
+ if (!picked) return;
+ const reqId = (previewReq.current += 1);
+ setBusy('fetch');
+ try {
+ const res = await api.uploadSkillZip(picked, { projectId });
+ if (reqId !== previewReq.current) return; // a newer pick/source superseded this
+ if (res.ok && res.skills) {
+ setUploadDir(res.dir ?? null);
+ onDiscovered(res.skills);
+ } else {
+ setError(res.error?.message ?? t('skills.addDialog.fetchFirst'));
+ }
+ } catch (err: any) {
+ if (reqId === previewReq.current) setError(err?.message ?? String(err));
+ } finally {
+ if (reqId === previewReq.current) setBusy(null);
+ }
+ };
+
+ const toggleBackend = (backend: Backend) => {
+ setBackends((prev) => {
+ const next = new Set(prev);
+ if (next.has(backend)) next.delete(backend);
+ else next.add(backend);
+ return next;
+ });
+ };
+
+ const toggleSkill = (name: string) => {
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ return next;
+ });
+ };
+
+ const cliPreview = useMemo(() => {
+ if (!baseSource) return '';
+ const allSelected = discovered && selected.size === discovered.length;
+ // askill's -a is variadic — all agents share ONE flag.
+ const selectedAgents = BACKEND_ORDER.filter((b) => backends.has(b)).map((b) => AGENT_OF[b]);
+ const agentsArg = selectedAgents.length ? `-a ${selectedAgents.join(' ')}` : '';
+ const selector = allSelected
+ ? '--all'
+ : selected.size === 1
+ ? `--skill ${[...selected][0]}`
+ : `--skill … (×${selected.size})`;
+ return ['askill add', baseSource, selector, scope === 'global' ? '-g' : '', agentsArg, '-y']
+ .filter(Boolean)
+ .join(' ');
+ }, [baseSource, discovered, selected, backends, scope]);
+
+ const install = async () => {
+ if (!baseSource || selected.size === 0 || backends.size === 0) return;
+ setBusy('install');
+ setError(null);
+ const targetBackends = [...backends];
+ const targetProject = scope === 'project' ? projectId : undefined;
+ const allSelected = discovered != null && selected.size === discovered.length;
+ try {
+ // askill installs mutate the same .agents/.skill-lock.json + symlink
+ // targets, so a multi-skill subset must install sequentially — parallel
+ // calls race and can drop part of the selection. (--skill is one name
+ // per call; --all is a single call covering everything.)
+ let failed: Awaited<ReturnType<typeof api.addSkill>> | null = null;
+ if (allSelected) {
+ const r = await api.addSkill({ source: baseSource, scope, projectId: targetProject, backends: targetBackends, all: true });
+ if (!r.ok) failed = r;
+ } else {
+ for (const name of selected) {
+ // --skill keeps local-dir paths unambiguous (paths can contain '@').
+ const r = await api.addSkill({ source: baseSource, skill: name, scope, projectId: targetProject, backends: targetBackends });
+ if (!r.ok) {
+ failed = r;
+ break;
+ }
+ }
+ }
+ if (failed) {
+ setError(failed.error?.message ?? t('skills.addSkill'));
+ return;
+ }
+ showToast(t('skills.addSuccess', { count: selected.size }), 'success');
+ onInstalled();
+ } catch (err: any) {
+ setError(err?.message ?? String(err));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const scopeOptions = [
+ { id: 'global' as const, label: t('skills.scopeGlobal') },
+ { id: 'project' as const, label: projectName ? `${t('skills.scopeProject')}: ${projectName}` : t('skills.scopeProject') },
+ ];
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-[#05050B]/[0.72] p-10 backdrop-blur-[6px]">
+ <div className="flex w-full max-w-[560px] flex-col overflow-hidden rounded-2xl border border-border-strong bg-surface-2 shadow-[0_24px_60px_-12px_rgba(0,0,0,0.7)]">
+ <div className="flex items-center gap-3 border-b border-border px-5 py-4">
+ <span className="flex size-[34px] shrink-0 items-center justify-center rounded-[9px] border border-mint/40 bg-mint-soft text-mint">
+ <PackagePlus className="size-[17px]" />
+ </span>
+ <div className="flex flex-1 flex-col">
+ <div className="text-[16px] font-bold text-foreground">{t('skills.addDialog.title')}</div>
+ <div className="text-[11px] text-muted">{t('skills.addDialog.subtitle')}</div>
+ </div>
+ <button type="button" onClick={onClose} aria-label={t('common.close')} className="flex size-[26px] items-center justify-center rounded-md text-muted transition hover:bg-foreground/[0.06]">
+ <X className="size-3.5" />
+ </button>
+ </div>
+
+ <div className="flex flex-col gap-4 p-5">
+ <SegmentedRadio<SourceTab>
+ value={source}
+ onChange={(next) => {
+ setSource(next);
+ reset();
+ }}
+ ariaLabel={t('skills.addDialog.title')}
+ options={[
+ { id: 'github', label: t('skills.addDialog.githubTab') },
+ { id: 'zip', label: t('skills.addDialog.zipTab') },
+ ]}
+ />
+
+ {source === 'github' ? (
+ <label className="flex flex-col gap-1.5">
+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('skills.addDialog.urlLabel')}</span>
+ <div className="flex items-center gap-2 rounded-lg border border-border-strong bg-surface px-2.5 py-2">
+ <Github className="size-3.5 shrink-0 text-muted" />
+ <input
+ value={url}
+ onChange={(e) => {
+ setUrl(e.target.value);
+ reset();
+ }}
+ onKeyDown={(e) => e.key === 'Enter' && fetchGithub()}
+ placeholder={t('skills.addDialog.urlPlaceholder')}
+ className="flex-1 bg-transparent font-mono text-[12px] text-foreground outline-none placeholder:text-muted"
+ />
+ <button
+ type="button"
+ onClick={fetchGithub}
+ disabled={!url.trim() || busy === 'fetch'}
+ className="flex shrink-0 items-center gap-1.5 rounded-md border border-cyan/40 bg-cyan-soft px-2.5 py-1.5 text-[11.5px] font-semibold text-cyan transition hover:brightness-110 disabled:opacity-50"
+ >
+ {busy === 'fetch' ? <Loader2 className="size-3 animate-spin" /> : <Search className="size-3" />}
+ {t('skills.addDialog.fetch')}
+ </button>
+ </div>
+ </label>
+ ) : (
+ <div className="flex flex-col gap-1.5">
+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('skills.addDialog.package')}</span>
+ <FileDropzone
+ file={file}
+ onFile={onPickFile}
+ hint={t('skills.addDialog.dropzoneHint')}
+ replaceLabel={t('skills.addDialog.replace')}
+ meta={file && discovered ? `${(file.size / 1024).toFixed(0)} KB · ${discovered.length} skills` : undefined}
+ />
+ <span className="text-[11px] text-muted">{t('skills.addDialog.localNote')}</span>
+ </div>
+ )}
+
+ {discovered ? (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-1.5">
+ <PackageCheck className="size-3.5 text-mint" />
+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">
+ {t('skills.addDialog.found', { count: discovered.length })}
+ </span>
+ </div>
+ {discovered.map((skill) => {
+ const on = selected.has(skill.name);
+ return (
+ <button
+ key={skill.name}
+ type="button"
+ role="checkbox"
+ aria-checked={on}
+ aria-label={skill.name}
+ onClick={() => toggleSkill(skill.name)}
+ className={clsx(
+ 'flex items-center gap-3 rounded-lg border px-3 py-2.5 text-left transition',
+ on ? 'border-mint/40 bg-mint-soft' : 'border-border bg-surface hover:border-border-strong',
+ )}
+ >
+ <Checkbox checked={on} presentational />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="text-[13px] font-semibold text-foreground">{skill.name}</span>
+ {skill.description ? <span className="truncate text-[11px] text-muted">{skill.description}</span> : null}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+
+ <div className="flex flex-col gap-1.5">
+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('skills.addDialog.installTo')}</span>
+ <SegmentedRadio<SkillScope> value={scope} onChange={setScope} ariaLabel={t('skills.addDialog.installTo')} options={scopeOptions} disabled={!projectId} />
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('skills.addDialog.backends')}</span>
+ <div className="flex flex-wrap items-center gap-2">
+ {BACKEND_ORDER.map((backend) => {
+ const on = backends.has(backend);
+ return (
+ <button
+ key={backend}
+ type="button"
+ onClick={() => toggleBackend(backend)}
+ className={clsx(
+ 'flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[12px] font-medium transition',
+ on ? BACKEND_CHIP[backend] : 'border-border-strong bg-surface text-muted hover:text-foreground',
+ )}
+ >
+ <Check className={clsx('size-3', on ? '' : 'opacity-0')} />
+ {BACKEND_LABEL[backend]}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {error ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">{error}</div>
+ ) : null}
+ </div>
+
+ <div className="flex items-center justify-between gap-3 border-t border-border bg-surface-3 px-5 py-3.5">
+ <div className="flex min-w-0 flex-1 items-center gap-1.5">
+ <Terminal className="size-3 shrink-0 text-muted" />
+ <span className="truncate font-mono text-[10.5px] text-muted">{cliPreview || 'askill add …'}</span>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <button type="button" onClick={onClose} className="rounded-lg border border-border-strong px-3.5 py-2 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]">
+ {t('skills.addDialog.cancel')}
+ </button>
+ <button
+ type="button"
+ onClick={install}
+ disabled={!discovered || selected.size === 0 || backends.size === 0 || busy === 'install'}
+ className="flex items-center gap-1.5 rounded-lg bg-mint px-4 py-2 text-[12px] font-semibold text-[#080812] shadow-[0_4px_16px_-4px_rgba(91,255,160,0.5)] transition hover:brightness-110 disabled:opacity-50"
+ >
+ {busy === 'install' ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
+ {busy === 'install' ? t('skills.addDialog.installing') : t('skills.addDialog.install', { count: selected.size })}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/skills/BackendChip.tsx b/ui/src/components/workbench/skills/BackendChip.tsx
new file mode 100644
index 000000000..b7c6ab912
--- /dev/null
+++ b/ui/src/components/workbench/skills/BackendChip.tsx
@@ -0,0 +1,17 @@
+import clsx from 'clsx';
+import { BACKEND_CHIP, BACKEND_DOT, BACKEND_LABEL, type Backend } from '../../../lib/backendAccent';
+
+/** Small pill marking a backend a skill is linked to. Colour per backend. */
+export function BackendChip({ backend }: { backend: Backend }) {
+ return (
+ <span
+ className={clsx(
+ 'inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5',
+ BACKEND_CHIP[backend],
+ )}
+ >
+ <span className={clsx('size-[5px] rounded-full', BACKEND_DOT[backend])} />
+ <span className="font-mono text-[10px] font-medium">{BACKEND_LABEL[backend]}</span>
+ </span>
+ );
+}
diff --git a/ui/src/components/workbench/skills/BrowseRegistryDialog.tsx b/ui/src/components/workbench/skills/BrowseRegistryDialog.tsx
new file mode 100644
index 000000000..8ca390738
--- /dev/null
+++ b/ui/src/components/workbench/skills/BrowseRegistryDialog.tsx
@@ -0,0 +1,208 @@
+import { useEffect, useMemo, useState } from 'react';
+import { Check, Compass, Github, Loader2, Plus, Search, Star, X } from 'lucide-react';
+import clsx from 'clsx';
+import { useTranslation } from 'react-i18next';
+import { useApi } from '../../../context/ApiContext';
+import type { SkillScope, SkillSearchItem } from '../../../context/ApiContext';
+import { useToast } from '../../../context/ToastContext';
+import { AiScoreBadge } from './QualityMeter';
+
+export interface BrowseRegistryDialogProps {
+ scope: SkillScope;
+ projectId?: string;
+ installedNames: Set<string>;
+ onClose: () => void;
+ onInstalled: () => void;
+}
+
+/** Search the askill.sh registry (askill find) and install results. */
+export function BrowseRegistryDialog({ scope, projectId, installedNames, onClose, onInstalled }: BrowseRegistryDialogProps) {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState<SkillSearchItem[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [tag, setTag] = useState<string | null>(null);
+ const [installing, setInstalling] = useState<string | null>(null);
+
+ // Debounced registry search; an empty query lists popular skills.
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ const handle = window.setTimeout(async () => {
+ try {
+ const res = await api.findSkills(query);
+ if (!cancelled) setResults(res.ok && res.skills ? res.skills : []);
+ } catch {
+ if (!cancelled) setResults([]);
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ }, 250);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(handle);
+ };
+ }, [api, query]);
+
+ const tags = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const skill of results) for (const tg of skill.tags ?? []) counts.set(tg, (counts.get(tg) ?? 0) + 1);
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6).map(([name]) => name);
+ }, [results]);
+
+ const shown = tag ? results.filter((s) => (s.tags ?? []).includes(tag)) : results;
+
+ const install = async (item: SkillSearchItem) => {
+ setInstalling(item.installSource);
+ try {
+ const res = await api.addSkill({ source: item.installSource, scope, projectId, all: false });
+ if (res.ok) {
+ showToast(t('skills.addSuccess', { count: 1 }), 'success');
+ onInstalled();
+ } else {
+ showToast(res.error?.message ?? t('skills.addSkill'), 'error');
+ }
+ } catch (err: any) {
+ showToast(err?.message ?? String(err), 'error');
+ } finally {
+ setInstalling(null);
+ }
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-[#05050B]/[0.72] p-10 backdrop-blur-[6px]">
+ <div className="flex w-full max-w-[760px] flex-col overflow-hidden rounded-2xl border border-border-strong bg-surface-2 shadow-[0_24px_60px_-12px_rgba(0,0,0,0.7)]">
+ <div className="flex items-center gap-3 border-b border-border px-5 py-4">
+ <span className="flex size-[34px] shrink-0 items-center justify-center rounded-[9px] border border-cyan/40 bg-cyan-soft text-cyan">
+ <Compass className="size-[17px]" />
+ </span>
+ <div className="flex flex-1 flex-col">
+ <div className="text-[16px] font-bold text-foreground">{t('skills.browse.title')}</div>
+ <div className="text-[11px] text-muted">{t('skills.browse.subtitle')}</div>
+ </div>
+ <button type="button" onClick={onClose} aria-label={t('common.close')} className="flex size-[26px] items-center justify-center rounded-md text-muted transition hover:bg-foreground/[0.06]">
+ <X className="size-3.5" />
+ </button>
+ </div>
+
+ <div className="flex flex-col gap-3.5 p-5">
+ <div className="flex items-center gap-2.5 rounded-[10px] border border-border-strong bg-surface px-3.5 py-2.5">
+ <Search className="size-[15px] text-muted" />
+ <input
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('skills.browse.searchPlaceholder')}
+ className="flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted"
+ />
+ {loading ? <Loader2 className="size-3.5 animate-spin text-muted" /> : (
+ <span className="font-mono text-[10.5px] text-muted">{t('skills.browse.resultsCount', { count: results.length })}</span>
+ )}
+ </div>
+
+ {tags.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ onClick={() => setTag(null)}
+ className={clsx(
+ 'rounded-full border px-2.5 py-1 text-[11.5px] transition',
+ tag === null ? 'border-mint/40 bg-mint-soft font-semibold text-mint' : 'border-border-strong text-muted hover:text-foreground',
+ )}
+ >
+ {t('skills.browse.tagAll')}
+ </button>
+ {tags.map((tg) => (
+ <button
+ key={tg}
+ type="button"
+ onClick={() => setTag(tg)}
+ className={clsx(
+ 'rounded-full border px-2.5 py-1 text-[11.5px] transition',
+ tag === tg ? 'border-mint/40 bg-mint-soft font-semibold text-mint' : 'border-border-strong text-muted hover:text-foreground',
+ )}
+ >
+ {tg}
+ </button>
+ ))}
+ </div>
+ ) : null}
+
+ <div className="flex max-h-[420px] flex-col gap-2.5 overflow-y-auto">
+ {shown.length === 0 && !loading ? (
+ <div className="rounded-xl border border-dashed border-border px-4 py-10 text-center text-[12px] text-muted">
+ {t('skills.browse.empty')}
+ </div>
+ ) : null}
+ {shown.map((item) => {
+ const installed = installedNames.has(item.name);
+ const isInstalling = installing === item.installSource;
+ return (
+ <div key={String(item.id)} className="flex items-center gap-3 rounded-xl border border-border bg-surface px-3.5 py-3.5">
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-[14px] font-semibold text-foreground">{item.name}</span>
+ <AiScoreBadge score={item.aiScore} />
+ <Github className="size-3 text-muted" />
+ <span className="font-mono text-[10px] text-muted">
+ {item.owner}
+ {item.repo ? `/${item.repo}` : ''}
+ </span>
+ </div>
+ <div className="line-clamp-2 text-[11.5px] text-muted">{item.description}</div>
+ <div className="flex flex-wrap items-center gap-2 font-mono text-[10px] text-muted">
+ {(item.tags ?? []).slice(0, 3).map((tg) => (
+ <span key={tg} className="rounded border border-border bg-surface-3 px-1.5 py-0.5">
+ {tg}
+ </span>
+ ))}
+ {typeof item.stars === 'number' ? (
+ <span className="flex items-center gap-1">
+ <Star className="size-3 text-gold" />
+ {item.stars}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ {installed ? (
+ <span className="flex shrink-0 items-center gap-1.5 rounded-lg border border-border-strong bg-surface-3 px-3 py-2 text-[12px] font-medium text-muted">
+ <Check className="size-3.5 text-mint" />
+ {t('skills.browse.installed')}
+ </span>
+ ) : (
+ <button
+ type="button"
+ // Any install in flight disables all Add buttons — askill
+ // installs share one lock file and races drop entries.
+ disabled={installing !== null}
+ onClick={() => install(item)}
+ className="flex shrink-0 items-center gap-1.5 rounded-lg border border-mint/40 bg-mint-soft px-3.5 py-2 text-[12px] font-semibold text-mint transition hover:brightness-110 disabled:opacity-60"
+ >
+ {isInstalling ? <Loader2 className="size-3.5 animate-spin" /> : <Plus className="size-3.5" />}
+ {t('skills.browse.add')}
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="flex items-center justify-between gap-3 border-t border-border bg-surface-3 px-5 py-3.5">
+ <span className="font-mono text-[10.5px] text-muted">
+ {t('skills.browse.showing', { shown: shown.length, total: results.length })}
+ </span>
+ <button
+ type="button"
+ onClick={onClose}
+ className="rounded-lg border border-border-strong px-4 py-2 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"
+ >
+ {t('skills.browse.done')}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/skills/FileDropzone.tsx b/ui/src/components/workbench/skills/FileDropzone.tsx
new file mode 100644
index 000000000..0833f9204
--- /dev/null
+++ b/ui/src/components/workbench/skills/FileDropzone.tsx
@@ -0,0 +1,75 @@
+import { useRef, useState } from 'react';
+import { FileArchive, RefreshCw, UploadCloud } from 'lucide-react';
+import clsx from 'clsx';
+
+export interface FileDropzoneProps {
+ file: File | null;
+ onFile: (file: File | null) => void;
+ accept?: string;
+ hint?: string;
+ replaceLabel?: string;
+ /** Status line under the file name, e.g. "240 KB · 3 skills found". */
+ meta?: string;
+}
+
+function humanSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+/** Dashed drop area for a single file (the .zip skill package). */
+export function FileDropzone({ file, onFile, accept = '.zip', hint, replaceLabel = 'Replace', meta }: FileDropzoneProps) {
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [dragging, setDragging] = useState(false);
+ const pick = () => inputRef.current?.click();
+ return (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setDragging(true);
+ }}
+ onDragLeave={() => setDragging(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setDragging(false);
+ const dropped = e.dataTransfer.files?.[0];
+ if (dropped) onFile(dropped);
+ }}
+ className={clsx(
+ 'flex flex-col gap-2 rounded-[10px] border border-dashed p-3.5 transition',
+ file
+ ? 'border-mint/40 bg-mint/[0.04]'
+ : dragging
+ ? 'border-mint/60 bg-mint/[0.06]'
+ : 'border-border-strong bg-surface',
+ )}
+ >
+ <input ref={inputRef} type="file" accept={accept} className="hidden" onChange={(e) => onFile(e.target.files?.[0] ?? null)} />
+ {file ? (
+ <div className="flex items-center gap-2.5 rounded-lg border border-border-strong bg-surface px-3 py-2">
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-mint/40 bg-mint-soft text-mint">
+ <FileArchive className="size-4" />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate font-mono text-[12px] text-foreground">{file.name}</span>
+ <span className="text-[10.5px] text-muted">{meta ?? humanSize(file.size)}</span>
+ </div>
+ <button
+ type="button"
+ onClick={pick}
+ className="flex shrink-0 items-center gap-1.5 rounded-md border border-border-strong px-2.5 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"
+ >
+ <RefreshCw className="size-3 text-muted" />
+ {replaceLabel}
+ </button>
+ </div>
+ ) : (
+ <button type="button" onClick={pick} className="flex flex-col items-center gap-1.5 py-4 text-center">
+ <UploadCloud className="size-6 text-muted" />
+ <span className="text-[12px] text-muted">{hint}</span>
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/skills/ProjectPicker.tsx b/ui/src/components/workbench/skills/ProjectPicker.tsx
new file mode 100644
index 000000000..2759e695e
--- /dev/null
+++ b/ui/src/components/workbench/skills/ProjectPicker.tsx
@@ -0,0 +1,60 @@
+import { useState } from 'react';
+import { Check, ChevronDown, Folder, FolderGit2 } from 'lucide-react';
+import clsx from 'clsx';
+import { useTranslation } from 'react-i18next';
+import type { WorkbenchProject } from '../../../context/ApiContext';
+import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';
+
+export interface ProjectPickerProps {
+ projects: WorkbenchProject[];
+ value: string | null;
+ onChange: (projectId: string) => void;
+}
+
+/** Dropdown that switches which project's skills are being managed. Mirrors the
+ * open-state in design.pen — the project list is the workbench sidebar's. */
+export function ProjectPicker({ projects, value, onChange }: ProjectPickerProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const active = projects.find((p) => p.id === value) ?? null;
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="flex items-center gap-1.5 rounded-md border border-mint/40 bg-surface px-3 py-2 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"
+ >
+ <FolderGit2 className="size-3.5 text-cyan" />
+ <span className="max-w-[160px] truncate">{active?.display_name ?? t('skills.scopeProject')}</span>
+ <ChevronDown className="size-3 text-muted" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[280px] p-1.5">
+ <div className="px-2 py-1 font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">
+ {t('skills.picker.title')}
+ </div>
+ {projects.map((project) => {
+ const on = project.id === value;
+ return (
+ <button
+ key={project.id}
+ type="button"
+ onClick={() => {
+ onChange(project.id);
+ setOpen(false);
+ }}
+ className={clsx(
+ 'flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
+ on ? 'bg-mint-soft text-foreground' : 'text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ <Folder className={clsx('size-3.5 shrink-0', on ? 'text-mint' : 'text-muted')} />
+ <span className="flex-1 truncate">{project.display_name}</span>
+ {on ? <Check className="size-3.5 shrink-0 text-mint" /> : null}
+ </button>
+ );
+ })}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/ui/src/components/workbench/skills/QualityMeter.tsx b/ui/src/components/workbench/skills/QualityMeter.tsx
new file mode 100644
index 000000000..813d37918
--- /dev/null
+++ b/ui/src/components/workbench/skills/QualityMeter.tsx
@@ -0,0 +1,30 @@
+import { Sparkles } from 'lucide-react';
+import clsx from 'clsx';
+
+// askill's registry AI score is on a 0–100 scale. Mint ≥90, cyan ≥85, gold
+// below — and display mirrors askill's own formatScore (integer as-is, else
+// one decimal), so a 96 shows "AI 96", not "AI 96.0".
+function scoreChip(score: number): string {
+ if (score >= 90) return 'bg-mint-soft border-mint/40 text-mint';
+ if (score >= 85) return 'bg-cyan-soft border-cyan/40 text-cyan';
+ return 'bg-gold/[0.12] border-gold/40 text-gold';
+}
+
+/** Compact "AI 9.5" pill used on registry result cards. */
+export function AiScoreBadge({ score, className }: { score: number | null | undefined; className?: string }) {
+ // askill's aiScore can be null for unscored registry results — hide the badge
+ // rather than throwing on score.toFixed (which blanks the whole modal).
+ if (score == null || !Number.isFinite(score)) return null;
+ return (
+ <span
+ className={clsx(
+ 'inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 font-mono text-[10px] font-bold',
+ scoreChip(score),
+ className,
+ )}
+ >
+ <Sparkles className="size-2.5" />
+ AI {Number.isInteger(score) ? score : score.toFixed(1)}
+ </span>
+ );
+}
diff --git a/ui/src/components/workbench/skills/SkillDetailPanel.tsx b/ui/src/components/workbench/skills/SkillDetailPanel.tsx
new file mode 100644
index 000000000..9a31c7814
--- /dev/null
+++ b/ui/src/components/workbench/skills/SkillDetailPanel.tsx
@@ -0,0 +1,123 @@
+import type { ReactNode } from 'react';
+import { ArrowUp, Bot, Loader2, Trash2, WandSparkles, X } from 'lucide-react';
+import clsx from 'clsx';
+import { useTranslation } from 'react-i18next';
+import type { SkillBrief, SkillCheckItem } from '../../../context/ApiContext';
+import { BACKEND_LABEL, BACKEND_ORDER, BACKEND_TEXT, backendsFromAgents, type Backend } from '../../../lib/backendAccent';
+import { Button } from '../../ui/button';
+import { Switch } from '../../ui/switch';
+
+export interface SkillDetailPanelProps {
+ skill: SkillBrief;
+ projectName?: string;
+ /** Backend currently mid add/remove, to show a spinner on that row. */
+ busyBackend?: Backend | null;
+ /** Update status from `askill check`; drives the "Update" affordance. */
+ check?: SkillCheckItem | null;
+ updating?: boolean;
+ onClose: () => void;
+ onToggleBackend: (backend: Backend, next: boolean) => void;
+ onUpdate?: () => void;
+ onRemove: () => void;
+}
+
+function Eyebrow({ children }: { children: ReactNode }) {
+ return <span className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{children}</span>;
+}
+
+/**
+ * Right-hand detail panel for a selected installed skill. The "Available to"
+ * switches are the core management surface: ON links the skill to that
+ * backend (askill add <path> -a <agent>), OFF unlinks it (askill remove -a).
+ * Registry-only data (AI quality, commands) isn't in askill `list --json`
+ * yet (askill#11), so it's intentionally absent for installed skills.
+ */
+export function SkillDetailPanel({
+ skill,
+ projectName,
+ busyBackend,
+ check,
+ updating,
+ onClose,
+ onToggleBackend,
+ onUpdate,
+ onRemove,
+}: SkillDetailPanelProps) {
+ const { t } = useTranslation();
+ const linked = new Set(backendsFromAgents(skill.agents));
+ const updateAvailable = check?.status === 'update_available';
+ const versionDelta =
+ check?.localVersion || check?.remoteVersion ? `${check?.localVersion ?? '?'} → ${check?.remoteVersion ?? '?'}` : undefined;
+ return (
+ <div className="flex flex-col gap-3.5 self-start rounded-2xl border border-border-strong bg-surface p-5">
+ <div className="flex items-start gap-3">
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/40 bg-mint-soft text-mint shadow-[0_0_18px_-6px_rgba(91,255,160,0.5)]">
+ <WandSparkles className="size-5" />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-[16px] font-bold text-foreground">{skill.name}</span>
+ {updateAvailable ? (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-gold/40 bg-gold/[0.12] px-1.5 font-mono text-[9px] font-bold uppercase text-gold">
+ <ArrowUp className="size-2.5" />
+ {t('skills.updateBadge')}
+ </span>
+ ) : null}
+ </div>
+ <div className="truncate text-[10.5px] text-muted">
+ {skill.scope === 'global'
+ ? t('skills.detail.subtitleGlobal')
+ : t('skills.detail.subtitleProject', { project: projectName ?? '' })}
+ </div>
+ </div>
+ <Button type="button" variant="ghost" size="icon" className="size-6" onClick={onClose} aria-label={t('common.close')}>
+ <X className="size-3.5" />
+ </Button>
+ </div>
+
+ <div className="flex flex-col gap-1 rounded-[10px] border border-border bg-surface-3 px-3 py-2.5">
+ <Eyebrow>{t('skills.detail.source')}</Eyebrow>
+ <div className="truncate font-mono text-[11px] text-foreground" title={skill.path}>
+ {skill.path}
+ </div>
+ </div>
+
+ {skill.description ? <p className="text-[12px] leading-relaxed text-muted">{skill.description}</p> : null}
+
+ <div className="flex flex-col gap-2">
+ <Eyebrow>{t('skills.detail.availableTo')}</Eyebrow>
+ <div className="flex flex-col gap-1.5">
+ {BACKEND_ORDER.map((backend) => {
+ const on = linked.has(backend);
+ const busy = busyBackend === backend;
+ return (
+ <div key={backend} className="flex items-center gap-2 rounded-lg border border-border bg-surface-3 px-3 py-2">
+ <Bot className={clsx('size-3.5', BACKEND_TEXT[backend])} />
+ <span className="flex-1 text-[12.5px] font-medium text-foreground">{BACKEND_LABEL[backend]}</span>
+ {busy ? (
+ <Loader2 className="size-3.5 animate-spin text-muted" />
+ ) : (
+ <Switch checked={on} onCheckedChange={(next) => onToggleBackend(backend, next)} label={BACKEND_LABEL[backend]} />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2 pt-1">
+ {updateAvailable ? (
+ <Button type="button" variant="brand-gold" size="xs" onClick={onUpdate} disabled={updating} title={versionDelta}>
+ {updating ? <Loader2 className="size-3 animate-spin" /> : <ArrowUp className="size-3" />}
+ {t('skills.detail.update')}
+ </Button>
+ ) : null}
+ <div className="flex-1" />
+ <Button type="button" variant="destructive-soft" size="xs" onClick={onRemove}>
+ <Trash2 className="size-3" />
+ {t('skills.detail.remove')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/workbench/skills/SkillRow.tsx b/ui/src/components/workbench/skills/SkillRow.tsx
new file mode 100644
index 000000000..e84f2ebf7
--- /dev/null
+++ b/ui/src/components/workbench/skills/SkillRow.tsx
@@ -0,0 +1,77 @@
+import { ArrowUp, Ellipsis, Github, Globe, WandSparkles } from 'lucide-react';
+import clsx from 'clsx';
+import { useTranslation } from 'react-i18next';
+import type { SkillBrief } from '../../../context/ApiContext';
+import { backendsFromAgents } from '../../../lib/backendAccent';
+import { BackendChip } from './BackendChip';
+
+export interface SkillRowProps {
+ skill: SkillBrief;
+ selected?: boolean;
+ /** Dim + tag rows that are inherited from global into a project view. */
+ inherited?: boolean;
+ /** Gold "UPDATE" badge when `askill check` flags a newer version. */
+ updateAvailable?: boolean;
+ onSelect?: () => void;
+}
+
+/** One installed-skill row: lead icon · name + desc + source/version · backend chips. */
+export function SkillRow({ skill, selected, inherited, updateAvailable, onSelect }: SkillRowProps) {
+ const { t } = useTranslation();
+ const backends = backendsFromAgents(skill.agents);
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ className={clsx(
+ 'group flex w-full items-center gap-3 rounded-lg border px-[14px] py-3 text-left transition',
+ selected
+ ? 'border-mint/40 bg-mint-soft shadow-[0_0_18px_-10px_rgba(91,255,160,0.6)]'
+ : 'border-border bg-surface hover:border-border-strong hover:bg-surface-2',
+ inherited && 'opacity-[0.66]',
+ )}
+ >
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-[9px] border border-border bg-surface-3">
+ <WandSparkles className={clsx('size-4', selected ? 'text-mint' : 'text-muted')} />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="flex items-center gap-2">
+ <span className="truncate text-[14px] font-semibold text-foreground">{skill.name}</span>
+ {updateAvailable ? (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-gold/40 bg-gold/[0.12] px-1.5 font-mono text-[9px] font-bold uppercase text-gold">
+ <ArrowUp className="size-2.5" />
+ {t('skills.updateBadge')}
+ </span>
+ ) : null}
+ {inherited ? (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-border-strong px-1.5 font-mono text-[9px] font-bold uppercase text-muted">
+ <Globe className="size-2.5" />
+ {t('skills.globalBadge')}
+ </span>
+ ) : null}
+ </span>
+ {skill.description ? <span className="truncate text-[11.5px] text-muted">{skill.description}</span> : null}
+ {skill.installSource || skill.version ? (
+ <span className="flex items-center gap-1.5 font-mono text-[10px] text-muted">
+ {skill.installSource ? (
+ <>
+ <Github className="size-2.5 shrink-0" />
+ <span className="truncate">{skill.installSource}</span>
+ </>
+ ) : null}
+ {skill.installSource && skill.version ? <span>·</span> : null}
+ {skill.version ? <span>v{skill.version}</span> : null}
+ </span>
+ ) : null}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5">
+ {backends.map((backend) => (
+ <BackendChip key={backend} backend={backend} />
+ ))}
+ </span>
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted opacity-0 transition group-hover:opacity-100">
+ <Ellipsis className="size-3.5" />
+ </span>
+ </button>
+ );
+}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 423c3aae5..6bde33709 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -114,6 +114,15 @@ export type ApiContextType = {
setDefaultVibeAgent: (name: string) => Promise<{ ok: boolean; default_agent_name: string; agent: VibeAgentBrief }>;
removeVibeAgent: (name: string) => Promise<{ ok: boolean; code?: string; message?: string; references?: Record<string, number>; removed_agent?: string }>;
importVibeAgents: (payload: { from?: 'claude' | 'codex' | 'opencode'; name?: string; all?: boolean; file?: string; backend?: string }) => Promise<{ ok: boolean; imported?: any[]; skipped?: any[]; error?: string; code?: string; message?: string }>;
+ // Agent Skills — thin shells over the askill CLI (see /api/skills*).
+ listSkills: (params?: { scope?: SkillScope | 'all'; projectId?: string; backends?: string[] }) => Promise<SkillsListResult>;
+ previewSkillSource: (source: string, params?: { projectId?: string }) => Promise<SkillsPreviewResult>;
+ addSkill: (payload: { source: string; scope: SkillScope; projectId?: string; backends?: string[]; all?: boolean; skill?: string; copy?: boolean }) => Promise<SkillsMutationResult>;
+ removeSkill: (name: string, params?: { scope?: SkillScope; projectId?: string; backends?: string[] }) => Promise<SkillsMutationResult>;
+ findSkills: (query: string) => Promise<SkillsFindResult>;
+ uploadSkillZip: (file: File, params?: { projectId?: string }) => Promise<SkillsUploadResult>;
+ checkSkills: (params?: { scope?: SkillScope; projectId?: string }) => Promise<SkillsCheckResult>;
+ updateSkill: (name: string, params?: { scope?: SkillScope; projectId?: string }) => Promise<SkillsMutationResult>;
listHarnessTasks: () => Promise<{ tasks: HarnessTask[] }>;
setHarnessTaskEnabled: (taskId: string, enabled: boolean) => Promise<{ ok: boolean; task?: HarnessTask }>;
deleteHarnessTask: (taskId: string) => Promise<{ ok: boolean; id?: string }>;
@@ -222,6 +231,89 @@ export type VibeAgentCreatePayload = {
enabled?: boolean;
};
+// Agent Skills (askill CLI). The backend returns the askill --json envelope,
+// optionally enriched; logical failures come back as { ok: false, error }
+// with HTTP 200 (callers branch on `ok`, like the agents endpoints).
+export type SkillScope = 'global' | 'project';
+export type AskillAgentRef = { id: string; name: string };
+export type SkillsErrorBody = { code: string; message: string; details?: unknown };
+export type SkillBrief = {
+ name: string;
+ scope: SkillScope;
+ path: string;
+ agents: AskillAgentRef[];
+ description?: string | null;
+ version?: string | null;
+ // Enriched natively by `list --json` (askill v0.1.13+).
+ tags?: string[];
+ sourceType?: string | null;
+ sourceUrl?: string | null;
+ installSource?: string | null;
+ installedAt?: string | null;
+ updatedAt?: string | null;
+};
+export type SkillsListResult = {
+ ok: boolean;
+ error?: SkillsErrorBody;
+ filters?: { scope: string; agents: AskillAgentRef[] };
+ summary?: { global: number; project: number };
+ skills?: SkillBrief[];
+};
+export type SkillAiBreakdown = { key: string; label: string; score: number };
+export type SkillSearchItem = {
+ id: string | number;
+ name: string;
+ description: string;
+ owner: string;
+ repo: string | null;
+ tags: string[];
+ stars: number | null;
+ aiScore: number | null;
+ aiBreakdown: SkillAiBreakdown[];
+ updatedAt: string | null;
+ installSource: string;
+ url: string | null;
+};
+export type SkillsFindResult = {
+ ok: boolean;
+ error?: SkillsErrorBody;
+ query?: string;
+ count?: number;
+ skills?: SkillSearchItem[];
+};
+export type SkillDiscovered = { name: string; description: string; path?: string | null };
+export type SkillsPreviewResult = {
+ ok: boolean;
+ error?: SkillsErrorBody;
+ action?: string;
+ source?: Record<string, unknown>;
+ skills?: SkillDiscovered[];
+};
+export type SkillsMutationResult = { ok: boolean; error?: SkillsErrorBody; [key: string]: unknown };
+// Result of uploading a .zip: the server unpacks it and previews the skills
+// inside; `dir` is the server-side path to install from via addSkill.
+export type SkillsUploadResult = {
+ ok: boolean;
+ error?: SkillsErrorBody;
+ dir?: string;
+ skills?: SkillDiscovered[];
+};
+export type SkillCheckStatus = 'update_available' | 'up_to_date' | 'uncheckable';
+export type SkillCheckItem = {
+ name: string;
+ scope: SkillScope;
+ status: SkillCheckStatus;
+ localVersion?: string | null;
+ remoteVersion?: string | null;
+ reason?: string | null;
+};
+export type SkillsCheckResult = {
+ ok: boolean;
+ error?: SkillsErrorBody;
+ summary?: { total: number; updateAvailable: number; upToDate: number; uncheckable: number };
+ skills?: SkillCheckItem[];
+};
+
export type VibeAgentUpdatePayload = {
description?: string | null;
model?: string | null;
@@ -1027,6 +1119,60 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
setDefaultVibeAgent: (name) => postJson('/api/agents/default', { name }),
removeVibeAgent: (name) => deleteJson(`/api/agents/${encodeURIComponent(name)}`),
importVibeAgents: (payload) => postJson('/api/agents/import', payload),
+ listSkills: (params) => {
+ const search = new URLSearchParams();
+ if (params?.scope) search.set('scope', params.scope);
+ if (params?.projectId) search.set('project_id', params.projectId);
+ if (params?.backends?.length) search.set('backends', params.backends.join(','));
+ const qs = search.toString();
+ return getJson(qs ? `/api/skills?${qs}` : '/api/skills');
+ },
+ previewSkillSource: (source, params) =>
+ postJson('/api/skills/preview', { source, project_id: params?.projectId }),
+ addSkill: (payload) =>
+ postJson('/api/skills', {
+ source: payload.source,
+ scope: payload.scope,
+ project_id: payload.projectId,
+ backends: payload.backends,
+ all: payload.all,
+ skill: payload.skill,
+ copy: payload.copy,
+ }),
+ removeSkill: (name, params) => {
+ const search = new URLSearchParams();
+ if (params?.scope) search.set('scope', params.scope);
+ if (params?.projectId) search.set('project_id', params.projectId);
+ if (params?.backends?.length) search.set('backends', params.backends.join(','));
+ const qs = search.toString();
+ return deleteJson(qs ? `/api/skills/${encodeURIComponent(name)}?${qs}` : `/api/skills/${encodeURIComponent(name)}`);
+ },
+ findSkills: (query) => getJson(`/api/skills/find?q=${encodeURIComponent(query)}`),
+ uploadSkillZip: async (file, params) => {
+ // Read the file client-side and send it as base64 JSON so the upload
+ // rides the same /api route + auth as everything else (no multipart).
+ const dataUrl = await new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(file);
+ });
+ const base64 = dataUrl.split(',')[1] ?? '';
+ return postJson('/api/skills/upload', {
+ filename: file.name,
+ content_base64: base64,
+ project_id: params?.projectId,
+ });
+ },
+ checkSkills: (params) => {
+ const search = new URLSearchParams();
+ if (params?.scope) search.set('scope', params.scope);
+ if (params?.projectId) search.set('project_id', params.projectId);
+ const qs = search.toString();
+ return getJson(qs ? `/api/skills/check?${qs}` : '/api/skills/check');
+ },
+ updateSkill: (name, params) =>
+ postJson('/api/skills/update', { name, scope: params?.scope, project_id: params?.projectId }),
listHarnessTasks: () => getJson('/api/harness/tasks'),
setHarnessTaskEnabled: (taskId, enabled) =>
patchJson(`/api/harness/tasks/${encodeURIComponent(taskId)}`, { enabled }),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c45a369cc..c1c0ccacc 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1312,6 +1312,82 @@
"submit": "Create agent"
}
},
+ "skills": {
+ "title": "Skills",
+ "subtitle": "Manage global and project skills across your agent backends · powered by askill.",
+ "scopeGlobal": "Global",
+ "scopeProject": "Project",
+ "searchPlaceholder": "Search installed skills…",
+ "searchProjectPlaceholder": "Search this project's skills…",
+ "backendFilter": "Backend",
+ "backendAll": "All",
+ "browseRegistry": "Browse registry",
+ "addSkill": "Add skill",
+ "empty": "No skills installed yet. Add one from GitHub, a .zip, or the registry.",
+ "noSearchMatch": "No matching skills.",
+ "notInstalled": "askill isn't installed",
+ "notInstalledHint": "Install the askill CLI to manage skills: curl -fsSL https://askill.sh | sh",
+ "removeConfirm": "Remove skill \"{{name}}\"? This unlinks it from the selected scope.",
+ "removeSuccess": "Removed {{name}}.",
+ "addSuccess": "Installed {{count}} skill(s).",
+ "updateSuccess": "Updated {{name}}.",
+ "scopeGlobalPath": "~/.agents/skills · shared across all projects",
+ "projectSectionLocal": "Project skills",
+ "projectSectionLocalHint": "installed in this repo only",
+ "projectSectionGlobal": "Also available · inherited from global",
+ "projectSectionGlobalHint": "manage these in the Global tab",
+ "globalBadge": "Global",
+ "updateBadge": "Update",
+ "globalAlsoAvailable": "Global skills are available here too",
+ "picker": {
+ "title": "Switch project",
+ "openFolder": "Open a project folder…"
+ },
+ "detail": {
+ "subtitleGlobal": "Agent Skill · installed globally",
+ "subtitleProject": "Agent Skill · {{project}}",
+ "source": "Source",
+ "viewOnGithub": "View on GitHub",
+ "quality": "AI quality",
+ "availableTo": "Available to",
+ "commands": "Commands",
+ "openSkillMd": "Open SKILL.md",
+ "remove": "Remove",
+ "update": "Update"
+ },
+ "addDialog": {
+ "title": "Add a skill",
+ "subtitle": "From a GitHub repo, or upload a local .zip package.",
+ "githubTab": "GitHub URL",
+ "zipTab": "Upload .zip",
+ "urlLabel": "GitHub URL or slug",
+ "urlPlaceholder": "github.com/owner/repo or gh:owner/repo@skill",
+ "fetch": "Fetch",
+ "package": "Skill package",
+ "dropzoneHint": "Drag & drop a .zip here, or click to choose one.",
+ "localNote": "Unpacked and installed locally via askill — never sent to a third-party service.",
+ "replace": "Replace",
+ "found": "Found {{count}} skill(s) · select to install",
+ "installTo": "Install to",
+ "backends": "Install for backends",
+ "cancel": "Cancel",
+ "install": "Install {{count}} skill(s)",
+ "installing": "Installing…",
+ "fetchFirst": "Enter a source and fetch to see its skills."
+ },
+ "browse": {
+ "title": "Browse the askill registry",
+ "subtitle": "AI-reviewed skills from askill.sh.",
+ "searchPlaceholder": "Search skills…",
+ "resultsCount": "{{count}} results",
+ "showing": "Showing {{shown}} of {{total}} · ranked by AI score",
+ "tagAll": "All",
+ "add": "Add",
+ "installed": "Installed",
+ "done": "Done",
+ "empty": "No skills match your search."
+ }
+ },
"harness": {
"title": "Harness",
"subtitle": "Scheduled tasks, watches, webhooks, and the run history of all three.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 71bb255c1..f47cd6007 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1311,6 +1311,82 @@
"submit": "创建 Agent"
}
},
+ "skills": {
+ "title": "技能",
+ "subtitle": "跨各 Agent 后端管理全局与项目级技能 · 基于 askill。",
+ "scopeGlobal": "全局",
+ "scopeProject": "项目",
+ "searchPlaceholder": "搜索已安装技能…",
+ "searchProjectPlaceholder": "搜索本项目的技能…",
+ "backendFilter": "Backend",
+ "backendAll": "全部",
+ "browseRegistry": "浏览注册表",
+ "addSkill": "添加技能",
+ "empty": "还没有安装技能。可从 GitHub、.zip 或注册表添加。",
+ "noSearchMatch": "没有匹配的技能。",
+ "notInstalled": "尚未安装 askill",
+ "notInstalledHint": "安装 askill CLI 以管理技能:curl -fsSL https://askill.sh | sh",
+ "removeConfirm": "移除技能 \"{{name}}\"?这会从当前范围解除链接。",
+ "removeSuccess": "已移除 {{name}}。",
+ "addSuccess": "已安装 {{count}} 个技能。",
+ "updateSuccess": "已更新 {{name}}。",
+ "scopeGlobalPath": "~/.agents/skills · 所有项目共享",
+ "projectSectionLocal": "项目技能",
+ "projectSectionLocalHint": "仅安装在本仓库",
+ "projectSectionGlobal": "也可用 · 继承自全局",
+ "projectSectionGlobalHint": "请在「全局」标签页管理",
+ "globalBadge": "全局",
+ "updateBadge": "更新",
+ "globalAlsoAvailable": "全局技能在这里也可用",
+ "picker": {
+ "title": "切换项目",
+ "openFolder": "打开项目文件夹…"
+ },
+ "detail": {
+ "subtitleGlobal": "Agent 技能 · 已全局安装",
+ "subtitleProject": "Agent 技能 · {{project}}",
+ "source": "来源",
+ "viewOnGithub": "在 GitHub 查看",
+ "quality": "AI 质量",
+ "availableTo": "可用于",
+ "commands": "命令",
+ "openSkillMd": "打开 SKILL.md",
+ "remove": "移除",
+ "update": "更新"
+ },
+ "addDialog": {
+ "title": "添加技能",
+ "subtitle": "从 GitHub 仓库,或上传本地 .zip 包。",
+ "githubTab": "GitHub 链接",
+ "zipTab": "上传 .zip",
+ "urlLabel": "GitHub 链接或 slug",
+ "urlPlaceholder": "github.com/owner/repo 或 gh:owner/repo@skill",
+ "fetch": "获取",
+ "package": "技能包",
+ "dropzoneHint": "把 .zip 拖到这里,或点击选择。",
+ "localNote": "由 askill 在本地解包安装 — 不会发送给任何第三方服务。",
+ "replace": "更换",
+ "found": "发现 {{count}} 个技能 · 勾选要安装的",
+ "installTo": "安装到",
+ "backends": "为这些 Backend 安装",
+ "cancel": "取消",
+ "install": "安装 {{count}} 个技能",
+ "installing": "安装中…",
+ "fetchFirst": "输入来源并获取以查看其技能。"
+ },
+ "browse": {
+ "title": "浏览 askill 注册表",
+ "subtitle": "来自 askill.sh、经 AI 评审的技能。",
+ "searchPlaceholder": "搜索技能…",
+ "resultsCount": "{{count}} 条结果",
+ "showing": "显示 {{shown}}/{{total}} · 按 AI 评分排序",
+ "tagAll": "全部",
+ "add": "添加",
+ "installed": "已安装",
+ "done": "完成",
+ "empty": "没有匹配你搜索的技能。"
+ }
+ },
"harness": {
"title": "Harness",
"subtitle": "定时任务、Watch、Webhook 及其运行历史。",
diff --git a/ui/src/lib/backendAccent.ts b/ui/src/lib/backendAccent.ts
new file mode 100644
index 000000000..561887870
--- /dev/null
+++ b/ui/src/lib/backendAccent.ts
@@ -0,0 +1,58 @@
+// Per-backend brand accent (mint / cyan / violet) + labels, shared by the
+// Agents and Skills surfaces. Matches design.pen. This is the *accent* of a
+// backend; it is intentionally distinct from `lib/agentBackends.ts`, which
+// carries Settings-page backend-tile chrome (icons, tile classes, CLI
+// defaults) for a different visual context.
+
+export const BACKEND_ORDER = ['claude', 'opencode', 'codex'] as const;
+export type Backend = (typeof BACKEND_ORDER)[number];
+
+export const BACKEND_LABEL: Record<Backend, string> = {
+ claude: 'Claude',
+ opencode: 'OpenCode',
+ codex: 'Codex',
+};
+
+// Text / icon accent — e.g. <Icon className={BACKEND_TEXT[b]} />.
+export const BACKEND_TEXT: Record<Backend, string> = {
+ claude: 'text-mint',
+ opencode: 'text-cyan',
+ codex: 'text-violet',
+};
+
+// Solid dot fill — e.g. a status dot inside a chip.
+export const BACKEND_DOT: Record<Backend, string> = {
+ claude: 'bg-mint',
+ opencode: 'bg-cyan',
+ codex: 'bg-violet',
+};
+
+// Full pill surface (soft bg + 40% border + accent text) for backend chips.
+export const BACKEND_CHIP: Record<Backend, string> = {
+ claude: 'bg-mint-soft border-mint/40 text-mint',
+ opencode: 'bg-cyan-soft border-cyan/40 text-cyan',
+ codex: 'bg-violet-soft border-violet/40 text-violet',
+};
+
+export function isBackend(value: string): value is Backend {
+ return (BACKEND_ORDER as readonly string[]).includes(value);
+}
+
+// askill agent id (e.g. "claude-code") -> our backend id. Agents we don't
+// surface (cursor, windsurf, …) are intentionally absent.
+export const AGENT_ID_TO_BACKEND: Record<string, Backend> = {
+ 'claude-code': 'claude',
+ opencode: 'opencode',
+ codex: 'codex',
+};
+
+// Distinct backends a skill serves, in canonical order, from its linked
+// askill agents. Unknown/unsupported agents are dropped.
+export function backendsFromAgents(agents: ReadonlyArray<{ id: string }> | null | undefined): Backend[] {
+ const seen = new Set<Backend>();
+ for (const agent of agents ?? []) {
+ const backend = AGENT_ID_TO_BACKEND[agent.id];
+ if (backend) seen.add(backend);
+ }
+ return BACKEND_ORDER.filter((backend) => seen.has(backend));
+}
diff --git a/vibe/api.py b/vibe/api.py
index bda5acf1f..9cc2fba9a 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -4800,3 +4800,164 @@ def _stop_temp_ws_internal():
pass
_temp_ws_client = None
_temp_ws_thread = None
+
+
+# --- Agent Skills (askill CLI shell) --------------------------------------
+# Thin orchestration over core/services/skills.py: resolve the askill binary,
+# call the async service, and normalize failures into the {ok: false, error}
+# envelope the Web UI already reads. The resolved path is injected into the
+# service so core/ never imports vibe/. See docs/plans/workbench-skills-page.md.
+
+
+async def _skills_guarded(call):
+ askill = resolve_cli_path("askill")
+ if not askill:
+ return {"ok": False, "error": {"code": "askill_not_found", "message": "askill CLI not found on PATH"}}
+ from core.services import skills as skills_service
+
+ try:
+ return await call(askill, skills_service)
+ except skills_service.SkillsError as exc:
+ return {"ok": False, "error": {"code": exc.code, "message": exc.message, "details": exc.details}}
+ except LookupError:
+ return {"ok": False, "error": {"code": "askill_not_found", "message": "askill CLI not found on PATH"}}
+
+
+async def list_skills(
+ *, scope: str = "all", project_dir: Optional[str] = None, backends: Optional[List[str]] = None
+) -> dict:
+ return await _skills_guarded(
+ lambda askill, svc: svc.list_skills(askill, scope=scope, project_dir=project_dir, backends=backends)
+ )
+
+
+async def preview_skill_source(source: str, *, project_dir: Optional[str] = None) -> dict:
+ return await _skills_guarded(lambda askill, svc: svc.preview_source(askill, source, project_dir=project_dir))
+
+
+async def add_skill(
+ source: str,
+ *,
+ scope: str = "project",
+ project_dir: Optional[str] = None,
+ backends: Optional[List[str]] = None,
+ all_skills: bool = False,
+ skill: Optional[str] = None,
+ copy: bool = False,
+) -> dict:
+ return await _skills_guarded(
+ lambda askill, svc: svc.add_skill(
+ askill,
+ source,
+ scope=scope,
+ project_dir=project_dir,
+ backends=backends,
+ all_skills=all_skills,
+ skill=skill,
+ copy=copy,
+ )
+ )
+
+
+async def remove_skill(
+ name: str, *, scope: str = "project", project_dir: Optional[str] = None, backends: Optional[List[str]] = None
+) -> dict:
+ return await _skills_guarded(
+ lambda askill, svc: svc.remove_skill(askill, name, scope=scope, project_dir=project_dir, backends=backends)
+ )
+
+
+async def find_skills(query: str = "") -> dict:
+ return await _skills_guarded(lambda askill, svc: svc.find_skills(askill, query))
+
+
+async def check_skills(*, scope: str = "project", project_dir: Optional[str] = None) -> dict:
+ return await _skills_guarded(lambda askill, svc: svc.check(askill, scope=scope, project_dir=project_dir))
+
+
+async def update_skill(name: str, *, scope: str = "project", project_dir: Optional[str] = None) -> dict:
+ return await _skills_guarded(lambda askill, svc: svc.update(askill, name, scope=scope, project_dir=project_dir))
+
+
+async def upload_skill_zip(payload: dict, *, project_dir: Optional[str] = None) -> dict:
+ """Decode a base64 .zip, unpack it to a temp dir, and preview its skills.
+
+ The UI then calls add_skill with ``source`` = the returned ``dir``. The
+ temp dir is local-only; askill does the actual install/symlink from it.
+ """
+ import base64
+ import binascii
+ import io
+ import os
+ import shutil
+ import tempfile
+ import time
+ import zipfile
+
+ max_b64 = 24 * 1024 * 1024 # ~18 MB archive — skills are tiny; cap the body.
+ max_uncompressed = 64 * 1024 * 1024
+ max_entries = 2000
+
+ # Best-effort sweep of stale unpack dirs from earlier uploads (the dir has to
+ # outlive this request so add_skill can install from it, so it can't be
+ # removed in a finally; sweep anything older than a couple hours instead).
+ tmp_root = tempfile.gettempdir()
+ try:
+ cutoff = time.time() - 2 * 3600
+ for name in os.listdir(tmp_root):
+ if name.startswith("askill-upload-"):
+ stale = os.path.join(tmp_root, name)
+ try:
+ if os.path.getmtime(stale) < cutoff:
+ shutil.rmtree(stale, ignore_errors=True)
+ except OSError:
+ pass
+ except OSError:
+ pass
+
+ content_b64 = payload.get("content_base64") or ""
+ if not content_b64:
+ return {"ok": False, "error": {"code": "missing_file", "message": "no file content"}}
+ if len(content_b64) > max_b64:
+ return {"ok": False, "error": {"code": "file_too_large", "message": "archive exceeds the size limit"}}
+ try:
+ raw = base64.b64decode(content_b64, validate=True)
+ except (binascii.Error, ValueError):
+ return {"ok": False, "error": {"code": "bad_file", "message": "invalid base64 content"}}
+
+ workdir = tempfile.mkdtemp(prefix="askill-upload-")
+ unpack = os.path.join(workdir, "skill")
+ os.makedirs(unpack, exist_ok=True)
+ unpack_root = os.path.realpath(unpack)
+ try:
+ with zipfile.ZipFile(io.BytesIO(raw)) as archive:
+ infos = archive.infolist()
+ if len(infos) > max_entries:
+ raise ValueError("archive has too many entries")
+ if sum(info.file_size for info in infos) > max_uncompressed:
+ raise ValueError("archive is too large uncompressed")
+ for info in infos:
+ target = os.path.realpath(os.path.join(unpack, info.filename))
+ # Reject zip-slip (entries that escape the unpack dir).
+ if target != unpack_root and not target.startswith(unpack_root + os.sep):
+ raise ValueError("archive contains unsafe paths")
+ archive.extractall(unpack)
+ except zipfile.BadZipFile:
+ shutil.rmtree(workdir, ignore_errors=True)
+ return {"ok": False, "error": {"code": "bad_zip", "message": "not a valid .zip archive"}}
+ except ValueError as exc:
+ shutil.rmtree(workdir, ignore_errors=True)
+ return {"ok": False, "error": {"code": "bad_zip", "message": str(exc)}}
+ except (RuntimeError, NotImplementedError, OSError) as exc:
+ # Encrypted entry / unsupported compression method / filesystem error —
+ # extractall raises these (not BadZipFile), so catch them too.
+ shutil.rmtree(workdir, ignore_errors=True)
+ return {"ok": False, "error": {"code": "bad_zip", "message": f"could not extract archive: {exc}"}}
+
+ preview = await _skills_guarded(lambda askill, svc: svc.preview_source(askill, unpack, project_dir=project_dir))
+ if preview.get("ok"):
+ preview["dir"] = unpack
+ else:
+ # Nothing will install from it — don't leak the dir.
+ shutil.rmtree(workdir, ignore_errors=True)
+ return preview
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4dbe91408..a3b72e0c2 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2667,6 +2667,144 @@ def projects_archive(project_id: str):
return jsonify(project)
+def _resolve_project_dir(project_id):
+ """Map a workbench project id to its folder path for project-scoped skills.
+
+ Returns None when no project is given (global / all scope). Raises
+ LookupError for an unknown id, which each skills route turns into a 404.
+ """
+ if not project_id:
+ return None
+ from storage import projects_service
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ project = projects_service.get_project(conn, project_id)
+ return project.get("folder_path")
+
+
+def _project_not_found(err):
+ return jsonify({"ok": False, "error": {"code": "project_not_found", "message": str(err)}}), 404
+
+
+# Agent Skills — thin shells over api.* (which wraps the askill CLI). Pure
+# data CRUD, so it stays in the UI-server process via core/services (no
+# dispatch-socket round-trip). See docs/plans/workbench-skills-page.md.
[email protected]("/api/skills", methods=["GET"])
+async def skills_list():
+ from vibe import api
+
+ scope = request.args.get("scope") or "all"
+ backends = [b for b in (request.args.get("backends") or "").split(",") if b]
+ try:
+ project_dir = _resolve_project_dir(request.args.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(await api.list_skills(scope=scope, project_dir=project_dir, backends=backends or None))
+
+
[email protected]("/api/skills/preview", methods=["POST"])
+async def skills_preview():
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ project_dir = _resolve_project_dir(payload.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(await api.preview_skill_source(str(payload.get("source") or ""), project_dir=project_dir))
+
+
[email protected]("/api/skills", methods=["POST"])
+async def skills_add():
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ project_dir = _resolve_project_dir(payload.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(
+ await api.add_skill(
+ str(payload.get("source") or ""),
+ scope=payload.get("scope") or "project",
+ project_dir=project_dir,
+ backends=payload.get("backends") or None,
+ all_skills=bool(payload.get("all")),
+ skill=payload.get("skill") or None,
+ copy=bool(payload.get("copy")),
+ )
+ )
+
+
[email protected]("/api/skills/<name>", methods=["DELETE"])
+async def skills_remove(name):
+ from vibe import api
+
+ backends = [b for b in (request.args.get("backends") or "").split(",") if b]
+ try:
+ project_dir = _resolve_project_dir(request.args.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(
+ await api.remove_skill(
+ name,
+ scope=request.args.get("scope") or "project",
+ project_dir=project_dir,
+ backends=backends or None,
+ )
+ )
+
+
[email protected]("/api/skills/find", methods=["GET"])
+async def skills_find():
+ from vibe import api
+
+ return jsonify(await api.find_skills(request.args.get("q") or ""))
+
+
[email protected]("/api/skills/check", methods=["GET"])
+async def skills_check():
+ from vibe import api
+
+ scope = request.args.get("scope") or "project"
+ try:
+ project_dir = _resolve_project_dir(request.args.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(await api.check_skills(scope=scope, project_dir=project_dir))
+
+
[email protected]("/api/skills/update", methods=["POST"])
+async def skills_update():
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ project_dir = _resolve_project_dir(payload.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(
+ await api.update_skill(
+ str(payload.get("name") or ""),
+ scope=payload.get("scope") or "project",
+ project_dir=project_dir,
+ )
+ )
+
+
[email protected]("/api/skills/upload", methods=["POST"])
+async def skills_upload():
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ project_dir = _resolve_project_dir(payload.get("project_id"))
+ except LookupError as err:
+ return _project_not_found(err)
+ return jsonify(await api.upload_skill_zip(payload, project_dir=project_dir))
+
+
@app.route("/api/browse/mkdir", methods=["POST"])
def browse_mkdir():
"""Create a new folder for the directory picker.