A local-first multi-agent app development platform, built on PenguinHarness
Pick the Skills a new Agent starts with, from the library or from a project directory (#431)
Yaowei Zheng11d6d16efccd
diff --git a/changelog/unreleased/2026-08-23-agent-create-skills.md b/changelog/unreleased/2026-08-23-agent-create-skills.mdnew file mode 100644index 00000000..3c0aa21a--- /dev/null+++ b/changelog/unreleased/2026-08-23-agent-create-skills.md@@ -0,0 +1,58 @@+# Pick the Skills a new Agent starts with++- **Date:** 2026-08-23+- **Type:** feature+- **Scope:** `web`, `server`+- **PR:** [#431](https://github.com/Prism-Shadow/penguin-harness/pull/431)++[中文版](2026-08-23-agent-create-skills.zh.md)++The Agent create dialog gained a Skills field: a dropdown that takes several skills from the+library at once, and creating the Agent installs them into it.++## Details++- The field uses the form-variant picker trigger already shared by the schedule dialog's model and+ workspace pickers, over the same multi-select panel the chat composer's skills dropdown uses — a+ search box and one toggle row per library skill, the panel staying open as rows are toggled.+- That panel gained a bulk row, shown where a host asks for it: the running count of what is+ picked, plus **Select all** and **Select none**. Both act on the rows the search box currently+ leaves visible, so a filtered "select all" adds only the matches.+- `POST /api/projects/:p/agents` accepts a `skills` array of library skill names. The names are+ resolved against the library before the Agent directory exists — an unknown name answers 404+ `unknown_skill` and creates nothing — and are installed through the same writer the Skills tab's+ install uses, inside the same cleanup window as the rest of Agent initialization.+- Creating an Agent with nothing picked installs no skills, as before.++## Importing a checkout's own Skills++The same dialog can also install the Skills a project directory already carries, which a coding+agent leaves in `.agents/skills/` or `.claude/skills/`. Pick a directory and its Skills appear in+a picker of their own, with the same Select all / Select none row; nothing is installed that was+not picked.++- The directory field is its own field rather than more entries in the library picker, because a+ directory Skill may share a library Skill's name and still be the one installed — one flat list+ of picked names could not say which was meant.+- `.claude` is very often a symlink to `.agents`, which would otherwise offer every Skill twice:+ the two roots are resolved through `realpath` and a shared target is read once. Where both exist+ as real directories and carry the same name, `.agents` wins.+- A directory Skill installs over a library Skill of the same name picked alongside it: choosing a+ directory for this Agent is the narrower intent.+- A directory carrying nothing installable is a stated fact in the field, not an error, and what is+ passed over is passed over silently: a directory with no `SKILL.md`, one whose `SKILL.md` has no+ frontmatter, a name the installer would reject, a symlinked Skill directory, and a Skill whose+ files cannot be read or exceed the caps — one bad Skill does not hide the rest of the directory.+- Reading a picked directory reuses the archive import's caps and its walk discipline — 200 files,+ 5MB per file, 20MB total — so the numbers live in one place for both entry points rather than+ two. Every file is read only after a stat says it is a regular file within the cap, `SKILL.md`+ and `icon.svg` included, so a symlink cannot hand back a file from outside the Skill directory,+ a FIFO cannot block the read, and an oversized file is refused before it is in memory.+- Listing a directory reads only what describes a Skill; the auxiliary files that make up the+ installable payload are read for the picked names alone.+- Both entry points admit a client-supplied path the same way — absolute, existing, a directory,+ resolved through `realpath` — through one helper the `dirs` browser now shares.+- The client sends names, never Skill content: creation re-reads the files from disk, and both+ sources resolve completely before anything is written, so a name that has since disappeared fails+ while the Agent still does not exist.+diff --git a/changelog/unreleased/2026-08-23-agent-create-skills.zh.md b/changelog/unreleased/2026-08-23-agent-create-skills.zh.mdnew file mode 100644index 00000000..0707a75b--- /dev/null+++ b/changelog/unreleased/2026-08-23-agent-create-skills.zh.md@@ -0,0 +1,42 @@+# 新建 Agent 时选择预装技能++- **Date:** 2026-08-23+- **Type:** feature+- **Scope:** `web`, `server`+- **PR:** [#431](https://github.com/Prism-Shadow/penguin-harness/pull/431)++[English](2026-08-23-agent-create-skills.md)++新建 Agent 对话框新增「技能」字段:一个可一次勾选多个技能库条目的下拉选择,创建 Agent 时把选中的技能装入该 Agent。++## 细节++- 该字段复用定时任务对话框中模型、工作区选择器已在用的表单式触发器,面板则复用对话输入框技能下拉的同一个多选面板——顶部搜索框、每个技能库条目一行可勾选行,勾选时面板保持展开。+- 该面板新增一行批量控件,由使用方按需开启:左侧是已选数量,右侧是**全选**与**全不选**。两者都只作用于搜索框当前筛出的行,因此先筛选再全选只会加入匹配项。+- `POST /api/projects/:p/agents` 接受 `skills` 数组,元素为技能库中的技能名。这些名字在 Agent 目录创建之前就完成解析——未知的名字返回 404 `unknown_skill`,不创建任何内容——随后经由技能标签页安装所用的同一个写入函数装入,并处于 Agent 初始化其余步骤相同的清理窗口内。+- 未勾选任何技能时创建的 Agent 与此前一致,不安装任何技能。++## 导入项目目录自带的技能++同一个对话框还可以安装项目目录里已有的技能——编码 Agent 会把它们留在 `.agents/skills/` 或+`.claude/skills/`。选定目录后,其中的技能出现在一个独立的选择器里,同样带「全选/全不选」;未被+勾选的不会被安装。++- 目录技能独立成一个字段,而不是并入技能库选择器:目录技能可能与库中技能同名且仍是被安装的那一个,+ 单一的「已选名称」列表无法表达究竟指的是哪一个。+- `.claude` 常常是指向 `.agents` 的符号链接,否则每个技能都会被列出两次:两个根经 `realpath`+ 解析,指向同一目标时只读取一次。两者都作为真实目录存在且同名时,以 `.agents` 为准。+- 目录技能会覆盖同时选中的同名库技能:为这个 Agent 选定某个目录,是更明确的意图。+- 目录中没有可安装技能时,字段里如实说明,而不作为错误处理;被跳过的内容静默跳过:没有 `SKILL.md`+ 的目录、`SKILL.md` 没有 frontmatter 的目录、安装器不接受的名称、符号链接形式的技能目录,以及+ 文件读不出来或超出上限的技能——一个有问题的技能不会连累目录里的其余技能。+- 读取所选目录复用归档导入的上限与遍历规则——200 个文件、单文件 5MB、合计 20MB——因此这些数字对两+ 个入口只有一处定义,而不是各自一套。每个文件都先由 stat 确认是目录自身的常规文件且未超上限才读取,+ `SKILL.md` 与 `icon.svg` 同样如此:符号链接无法把技能目录外的文件带回来,FIFO 不会把读取卡死,+ 超大文件在进入内存之前就被拒绝。+- 列出目录只读取描述一个技能所需的内容;构成可安装内容的附属文件只为被勾选的名称读取。+- 两个入口以同一种方式接纳前端传来的路径——绝对路径、存在、是目录、经 `realpath` 解析——由一个+ helper 统一处理,目录浏览接口现在也共用它。+- 前端只发送名称,从不发送技能内容:创建时由服务端从磁盘重新读取,且两个来源都会先全部解析完成才写入+ 任何文件,因此一个已经消失的名称会在 Agent 尚不存在时就失败。+diff --git a/changelog/unreleased/2026-08-23-modal-esc-layer.md b/changelog/unreleased/2026-08-23-modal-esc-layer.mdnew file mode 100644index 00000000..e015605e--- /dev/null+++ b/changelog/unreleased/2026-08-23-modal-esc-layer.md@@ -0,0 +1,14 @@+# Escape inside a dialog's menu closes the menu, not the dialog++- **Date:** 2026-08-23+- **Type:** fix+- **Scope:** `web`+- **PR:** [#431](https://github.com/Prism-Shadow/penguin-harness/pull/431)++[中文版](2026-08-23-modal-esc-layer.zh.md)++`Modal` reads its `onClose` through a latest-callback ref, so the Escape-layer it registers is+pushed once when the dialog opens instead of being re-pushed on every render. Call sites pass an+inline arrow for `onClose`; the re-push moved the dialog's layer back above a menu opened inside+it, and Escape then closed the whole dialog — discarding whatever had been filled in — rather than+just the menu.diff --git a/changelog/unreleased/2026-08-23-modal-esc-layer.zh.md b/changelog/unreleased/2026-08-23-modal-esc-layer.zh.mdnew file mode 100644index 00000000..eae5bee2--- /dev/null+++ b/changelog/unreleased/2026-08-23-modal-esc-layer.zh.md@@ -0,0 +1,10 @@+# 对话框内菜单按 Escape 只关菜单,不再关掉整个对话框++- **Date:** 2026-08-23+- **Type:** fix+- **Scope:** `web`+- **PR:** [#431](https://github.com/Prism-Shadow/penguin-harness/pull/431)++[English](2026-08-23-modal-esc-layer.md)++`Modal` 改为通过 latest-callback ref 读取 `onClose`,其注册的 Escape 层只在对话框打开时入栈一次,不再每次渲染重新入栈。各调用点的 `onClose` 都是内联箭头函数,重新入栈会把对话框自身的层压回其内部已打开菜单之上,此时按 Escape 关闭的是整个对话框——已填写的内容随之丢弃——而不是只关掉那个菜单。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex aa60b96d..3047671d 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -774,6 +774,21 @@ export interface AgentCreateRequest {/** Display name; defaults to agentId. */name?: string;description?: string;+ /**+ * Library Skill names installed into the new Agent, seeding it at creation. Every name must+ * exist in the library (404 `unknown_skill` otherwise, before anything is created); omitted or+ * empty leaves the Agent with no Skills, which is what a plain Agent gets by default.+ */+ skills?: string[];+ /**+ * Skills imported from a directory on disk instead of the library. `skillsDirectory` is the+ * absolute path the user picked and `directorySkills` are the names to install from it, read+ * back from `.agents/skills` / `.claude/skills` at creation time. Both are required together,+ * and every name must still be there (404 `unknown_skill` otherwise, before anything is+ * created) — the client sends names, never Skill content.+ */+ skillsDirectory?: string;+ directorySkills?: string[];}export interface AgentCreateResponse {@@ -1142,6 +1157,19 @@ export interface DirListResponse {entries: DirEntryInfo[];}+/** One Skill found in a picked directory: metadata plus which of the two layouts it came from. */+export interface DirectorySkillItem extends SkillMetadataItem {+ /** `.agents/skills` or `.claude/skills` — shown so the origin of an offered Skill is visible. */+ source: string;+}++export interface DirectorySkillsResponse {+ /** Absolute path that was scanned (realpath). */+ path: string;+ /** Installable Skills found under the directory's Skill layouts; empty when it carries none. */+ skills: DirectorySkillItem[];+}+export interface SessionCreateRequest {/** Upstream id of the session's model; always sent together with provider. Omit both for the Project's default Model. */modelId?: string;diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 174744f3..117efe53 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -122,6 +122,7 @@ import { agentSkillsRoutes, skillLibraryRoutes } from "./http/routes/skills.js";import { agentTransferRoutes } from "./http/routes/agent-transfer.js";import { agentsRoutes } from "./http/routes/agents.js";import { dirsRoutes } from "./http/routes/dirs.js";+import { directorySkillsRoutes } from "./http/routes/directory-skills.js";import { agentConfigRoutes } from "./http/routes/agent-config.js";import { agentTracesRoutes } from "./http/routes/agent-traces.js";import { usageRoutes } from "./http/routes/usage.js";@@ -796,6 +797,7 @@ export function createApp(app.route("/api/projects/:projectId/command-policy", commandPolicyRoutes(deps));app.route("/api/projects/:projectId/agents", agentsRoutes(deps));app.route("/api/projects/:projectId/dirs", dirsRoutes(deps));+ app.route("/api/projects/:projectId/dir-skills", directorySkillsRoutes(deps));app.route("/api/projects/:projectId/agents/:agentId/config", agentConfigRoutes(deps));app.route("/api/projects/:projectId/agents/:agentId/vault", vaultRoutes(deps));app.route("/api/projects/:projectId/agents/:agentId/memory", memoryRoutes(deps));diff --git a/packages/server/src/http/routes/agents.ts b/packages/server/src/http/routes/agents.tsindex a61f0851..f7d3d4ee 100644--- a/packages/server/src/http/routes/agents.ts+++ b/packages/server/src/http/routes/agents.ts@@ -8,7 +8,15 @@ import { Hono } from "hono";import type { AgentCreateResponse, AgentsResponse, AgentSummary } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { settleWithin } from "../settle.js";-import { optionalString, readJson, requireString, requireValidId } from "../validate.js";+import {+ badRequest,+ optionalString,+ optionalStringArray,+ readJson,+ requireProjectDir,+ requireString,+ requireValidId,+} from "../validate.js";import type { AppDeps } from "../../app.js";/** Window size in days for the card's activity sparkline (last 30 days, including today). */@@ -50,7 +58,35 @@ export function agentsRoutes(deps: AppDeps): Hono<AppEnv> {maxLen: 2000,label: "description",});- const item = await deps.agentService.createAgent(projectId, agentId, name, description);+ // Library Skills to seed the new Agent with (the create dialog's picker); unknown names are+ // rejected before the Agent directory exists.+ const skills = optionalStringArray(body, "skills");+ // Skills imported from a directory the user picked. The pair only means anything together, so+ // half of it is a bad request rather than a silently ignored field.+ const skillsDirectory = optionalString(body, "skillsDirectory", {+ minLen: 1,+ maxLen: 4096,+ label: "skillsDirectory",+ });+ const directorySkills = optionalStringArray(body, "directorySkills");+ let directory: { path: string; names: string[] } | undefined;+ if (skillsDirectory !== undefined || directorySkills !== undefined) {+ if (skillsDirectory === undefined || directorySkills === undefined) {+ throw badRequest("skillsDirectory and directorySkills must be sent together.");+ }+ // The same admission the discovery route applies, so the two entry points cannot disagree+ // on what a valid directory is: a relative path would otherwise resolve against the server+ // process's cwd instead of being rejected.+ directory = { path: await requireProjectDir(skillsDirectory), names: directorySkills };+ }+ const item = await deps.agentService.createAgent(+ projectId,+ agentId,+ name,+ description,+ skills,+ directory,+ );const agent: AgentSummary = {...item,activeSessionCount: 0,diff --git a/packages/server/src/http/routes/directory-skills.ts b/packages/server/src/http/routes/directory-skills.tsnew file mode 100644index 00000000..8fd4e29d--- /dev/null+++ b/packages/server/src/http/routes/directory-skills.ts@@ -0,0 +1,45 @@+/**+ * Skill discovery in a picked directory:+ * GET /api/projects/:p/dir-skills?path=<absolute>.+ *+ * Answers "what would importing this directory install", so Agent creation can offer the Skills a+ * checkout carries next to the built-in library ones. Reads `<path>/.agents/skills` and+ * `<path>/.claude/skills` only — it never lists or descends anything else, so it is strictly+ * narrower than the directory browsing this sits beside.+ *+ * Authorization and path handling are the `dirs` route's, deliberately: `projectId` is the anchor+ * and the caller must have access to it, the path must be absolute, and it is resolved through+ * realpath before anything is read (`requireProjectDir`, shared with that route and with the+ * create route's `skillsDirectory`). A directory carrying no Skills answers with an empty list+ * rather than an error — pointing at one is a normal thing to do.+ */+import { Hono } from "hono";+import type { DirectorySkillsResponse } from "../../api/types.js";+import type { AppEnv } from "../../auth/middleware.js";+import { requireProjectDir, requireValidId } from "../validate.js";+import type { AppDeps } from "../../app.js";+import { discoverDirectorySkills } from "../../services/directory-skills.js";+import { toMetadataItem } from "../../services/skill-library.js";++export function directorySkillsRoutes(deps: AppDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.get("/", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);++ const real = await requireProjectDir(c.req.query("path"));++ const skills = await discoverDirectorySkills(real);+ return c.json({+ path: real,+ // The picker needs a description, not a payload: the body and the resolved server-side+ // path are projected away by the shared allowlist, and creation re-reads the Skill from+ // disk, so a megabyte of SKILL bodies never crosses the wire and the install can never be+ // driven by a body the client made up.+ skills: skills.map((skill) => ({ ...toMetadataItem(skill), source: skill.source })),+ } satisfies DirectorySkillsResponse);+ });++ return app;+}diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.tsindex 4683cd14..d7a89b63 100644--- a/packages/server/src/http/routes/dirs.ts+++ b/packages/server/src/http/routes/dirs.ts@@ -16,8 +16,7 @@ import path from "node:path";import { Hono } from "hono";import type { DirListResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";-import { HttpError } from "../errors.js";-import { requireValidId } from "../validate.js";+import { requireProjectDir, requireValidId } from "../validate.js";import type { AppDeps } from "../../app.js";export function dirsRoutes(deps: AppDeps): Hono<AppEnv> {@@ -29,25 +28,7 @@ export function dirsRoutes(deps: AppDeps): Hono<AppEnv> {// Default starting point: home directory; an explicit path must be absolute (the frontend always sends back the realpath result).const raw = c.req.query("path");- const target = raw && raw.trim() ? raw.trim() : os.homedir();- if (!path.isAbsolute(target)) {- throw new HttpError(400, "dir_not_absolute", "Directory must be an absolute path.");- }-- let real: string;- try {- real = await fs.realpath(target);- } catch {- throw new HttpError(- 404,- "dir_not_found",- `Directory does not exist or is inaccessible: ${target}.`,- );- }- const stat = await fs.stat(real);- if (!stat.isDirectory()) {- throw new HttpError(400, "not_a_dir", "Not a directory.");- }+ const real = await requireProjectDir(raw && raw.trim() ? raw.trim() : os.homedir());let dirents: import("node:fs").Dirent[] = [];try {diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.tsindex e4c2767d..1f489427 100644--- a/packages/server/src/http/routes/skills.ts+++ b/packages/server/src/http/routes/skills.ts@@ -24,49 +24,31 @@ import {skillsDir,} from "@prismshadow/penguin-core";import {- librarySkill,loadSkillGroups,parseSkillFrontmatter,SKILL_NAME_PATTERN,} from "@prismshadow/penguin-skills";-import type { LibrarySkill, SkillMetadata } from "@prismshadow/penguin-skills";-import type {- AgentSkillsResponse,- SkillLibraryResponse,- SkillMetadataItem,-} from "../../api/types.js";+import type { AgentSkillsResponse, SkillLibraryResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import type { AppDeps } from "../../app.js";import { HttpError } from "../errors.js";-import { badRequest, readJson, requireString, requireValidId } from "../validate.js";+import {+ badRequest,+ optionalStringArray,+ readJson,+ requireString,+ requireValidId,+} from "../validate.js";+import { resolveLibrarySkills, toMetadataItem } from "../../services/skill-library.js";+import {+ MAX_ARCHIVE_FILES,+ MAX_FILE_BYTES,+ MAX_TOTAL_BYTES,+ skillTooLarge,+} from "../../services/skill-import-limits.js";/** Decoded zip cap: aligned with the Agent snapshot import (stays within the 20MB body limit after base64). */const MAX_ARCHIVE_BYTES = 14 * 1024 * 1024;-/** Uncompressed limits (guard against zip bombs): entry count / per-file / total. */-const MAX_ARCHIVE_FILES = 200;-const MAX_FILE_BYTES = 5 * 1024 * 1024;-const MAX_TOTAL_BYTES = 20 * 1024 * 1024;--/**- * Strips the content off a LibrarySkill: the API only sends metadata; the full body is- * written to disk on install and read by the model on demand. The optional short- * description (shortDescription(Zh)) and custom icon (icon.svg source) are conditionally- * passed through — both the library side (LibrarySkill) and the installed side (core- * InstalledSkill) carry these fields.- */-function toMetadataItem(skill: SkillMetadata & { icon?: string }): SkillMetadataItem {- return {- name: skill.name,- description: skill.description,- ...(skill.shortDescription !== undefined ? { shortDescription: skill.shortDescription } : {}),- ...(skill.shortDescriptionZh !== undefined- ? { shortDescriptionZh: skill.shortDescriptionZh }- : {}),- ...(skill.icon !== undefined ? { icon: skill.icon } : {}),- version: skill.version,- updated: skill.updated,- };-}/** Library listing response: the files are the source of truth — read and parse the library directory fresh on every request (files are small, requests infrequent, no caching needed). */function libraryResponse(): SkillLibraryResponse {@@ -187,11 +169,7 @@ async function collectSkillArchive(dir: string, name: string): Promise<Record<stdata.byteLength > MAX_FILE_BYTES ||total > MAX_TOTAL_BYTES) {- throw new HttpError(- 413,- "skill_too_large",- `Skill directory exceeds the archive limits (${MAX_ARCHIVE_FILES} files, 5MB per file, 20MB total).`,- );+ throw skillTooLarge();}out[relChild] = data;}@@ -221,15 +199,11 @@ function explicitSkillVersion(skillMd: string): number | null {/** Validate the POST request body: names must be a non-empty array of strings. */function parseInstallNames(body: Record<string, unknown>): string[] {- if (!Array.isArray(body.names) || body.names.length === 0) {- throw badRequest("names must be a non-empty array.");- }- return body.names.map((v, i) => {- if (typeof v !== "string" || v.length === 0) {- throw badRequest(`names[${i}] must be a non-empty string.`);- }- return v;- });+ // The shape and the per-entry check are the shared validator's; install additionally requires+ // at least one name, unlike the optional field on Agent creation.+ const names = optionalStringArray(body, "names") ?? [];+ if (names.length === 0) throw badRequest("names must be a non-empty array.");+ return names;}/** GET /api/skills: Skill library groups & metadata (any logged-in user; no Project check). */@@ -281,11 +255,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {await deps.agentConfigService.requireExists(projectId, agentId);const names = parseInstallNames(await readJson(c));// Verify all names up front before writing anything: if any name isn't in the library, reject the whole request rather than leaving a half-installed state.- const skills: LibrarySkill[] = names.map((name) => {- const skill = librarySkill(name);- if (!skill) throw new HttpError(404, "unknown_skill", `Skill is not in the library: ${name}`);- return skill;- });+ const skills = resolveLibrarySkills(names);for (const skill of skills) {await installSkill(deps.config.root, projectId, agentId, skill);}diff --git a/packages/server/src/http/validate.ts b/packages/server/src/http/validate.tsindex 0504c9e3..7401b5cf 100644--- a/packages/server/src/http/validate.ts+++ b/packages/server/src/http/validate.ts@@ -4,6 +4,8 @@** No validation library: each helper checks one basic shape, throwing a 400 HttpError on failure.*/+import fs from "node:fs/promises";+import path from "node:path";import type { Context } from "hono";import { isValidId } from "@prismshadow/penguin-core";import { HttpError } from "./errors.js";@@ -137,6 +139,65 @@ export function optionalString(return requireString(obj, key, rule);}+/**+ * Optional array-of-strings body field: absent (or null) yields undefined, anything that is not+ * an array of non-empty strings is a 400. The per-item message carries the index, so a caller+ * sending one bad entry in a long list is told which one.+ */+export function optionalStringArray(+ obj: Record<string, unknown>,+ key: string,+ label = key,+): string[] | undefined {+ const v = obj[key];+ if (v === undefined || v === null) return undefined;+ if (!Array.isArray(v)) throw badRequest(`${label} must be an array of strings.`);+ return v.map((item, i) => {+ if (typeof item !== "string" || item.length === 0) {+ throw badRequest(`${label}[${i}] must be a non-empty string.`);+ }+ return item;+ });+}++/**+ * Admits a client-supplied filesystem path for a Project-scoped route and returns its realpath:+ * absolute, existing, and a directory. Shared by every route that takes a path from the client —+ * the `dirs` browser, Skill discovery, and Agent creation's `skillsDirectory` — so the three+ * cannot drift on what a valid path is or on which error code says so. The caller must already+ * have checked Project access.+ */+export async function requireProjectDir(raw: string | undefined): Promise<string> {+ const target = raw?.trim();+ if (!target || !path.isAbsolute(target)) {+ throw new HttpError(400, "dir_not_absolute", "Directory must be an absolute path.");+ }+ let real: string;+ try {+ real = await fs.realpath(target);+ } catch {+ throw new HttpError(+ 404,+ "dir_not_found",+ `Directory does not exist or is inaccessible: ${target}.`,+ );+ }+ // stat can still fail if the directory goes away between realpath and here; that is the same+ // "not there" the caller is being told about, not a server fault.+ const isDir = await fs.stat(real).then(+ (s) => s.isDirectory(),+ () => {+ throw new HttpError(+ 404,+ "dir_not_found",+ `Directory does not exist or is inaccessible: ${target}.`,+ );+ },+ );+ if (!isDir) throw new HttpError(400, "not_a_dir", "Not a directory.");+ return real;+}+export function requireEnum<T extends string>(obj: Record<string, unknown>,key: string,diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.tsindex 0eda5d46..1e005628 100644--- a/packages/server/src/services/agent-service.ts+++ b/packages/server/src/services/agent-service.ts@@ -19,6 +19,7 @@ import {agentsMdPath,BUILTIN_AGENT_IDS,createAgent as coreCreateAgent,+ installSkill,isValidId,loadAgentVault,memoryDir,@@ -30,6 +31,8 @@ import type { AgentsRepo } from "../db/repos/agents.js";import { SEMANTIC_ID_PATTERN, SEMANTIC_ID_RULE } from "./ids.js";import type { AgentConfigService } from "./agent-config-service.js";import { isTopicFileName } from "./memory-service.js";+import { resolveLibrarySkills } from "./skill-library.js";+import { resolveDirectorySkills } from "./directory-skills.js";export interface AgentListItem {agentId: string;@@ -230,13 +233,20 @@ export class AgentService {* Create an Agent: the id is chosen by the creator (a semantic id, checked for* duplicates against both the DB and the directory within the Project — a 409* if taken, which naturally also blocks built-in Agent ids) → initialize State →- * write name/description (name defaults to the id).+ * write name/description (name defaults to the id) → install the seed Skills.+ *+ * `skillNames` are library Skill names picked at creation; they go through the same+ * `installSkill` writer the Skills tab uses, inside the same cleanup window as the rest of+ * initialization, so an Agent never survives with only part of its picked set. They are+ * resolved before anything is created, so an unknown name creates no directory at all.*/async createAgent(projectId: string,agentId: string,name?: string,description?: string,+ skillNames?: readonly string[],+ directory?: { path: string; names: readonly string[] },): Promise<AgentListItem> {if (!SEMANTIC_ID_PATTERN.test(agentId)) {throw new HttpError(@@ -255,11 +265,23 @@ export class AgentService {throw new HttpError(409, "agent_exists", `Agent id is already taken: ${agentId}.`);}const displayName = name ?? agentId;+ // Both sources are resolved before a single file is written, so a name that has since left the+ // library or the directory fails while the Agent still does not exist. Directory Skills are+ // installed after the library ones and so win a name collision: the user picked that directory+ // for this Agent specifically, which is a narrower intent than "install the built-in one".+ const librarySeed = resolveLibrarySkills(skillNames ?? []);+ const directorySeed = directory+ ? await resolveDirectorySkills(directory.path, directory.names)+ : [];+ const seedSkills = [...librarySeed, ...directorySeed];await coreCreateAgent({ root: this.root, projectId, agentId });try {await this.agentConfig.updateConfig(projectId, agentId, {config: { name: displayName, ...(description !== undefined ? { description } : {}) },});+ for (const skill of seedSkills) {+ await installSkill(this.root, projectId, agentId, skill);+ }} catch (err) {// If initialization fails partway through, clean up the directory: an orphaned// directory would make retries with this agent id 409 forever.diff --git a/packages/server/src/services/directory-skills.ts b/packages/server/src/services/directory-skills.tsnew file mode 100644index 00000000..51df552a--- /dev/null+++ b/packages/server/src/services/directory-skills.ts@@ -0,0 +1,233 @@+/**+ * Skills read from a directory the user picked, rather than from the built-in library.+ *+ * A coding agent writes its Skills into one of two places in a checkout — `.agents/skills/` or+ * `.claude/skills/` — so both are read. `.claude` is very often a symlink to `.agents` (it is in+ * this repository), which would otherwise offer every Skill twice: the two roots are resolved+ * through `realpath` and a shared target is read once. Where both exist as real directories and+ * carry the same Skill name, `.agents` wins — it is the canonical location and `.claude` is the+ * compatibility alias.+ *+ * A directory the user points at is untrusted input in exactly the way an uploaded archive is, so+ * this reuses the archive import's caps (skill-import-limits.ts) and its walk discipline: **every**+ * file is read only after an `lstat`/`Dirent` says it is a regular file within the cap, so a+ * symlink cannot pull in a file outside the Skill directory, a FIFO or device node cannot block+ * the read forever, and an oversized file is refused before it is in memory rather than after.+ * A directory without a parseable `SKILL.md` is not a Skill and is passed over rather than+ * reported — these trees hold plenty that was never meant to be installed — and so is a Skill+ * whose files cannot be read or exceed the caps: one bad Skill must not hide the rest.+ *+ * Discovery is metadata-only. Auxiliary files are the installable payload, so they are read for+ * the names actually picked (`resolveDirectorySkills`) and never for a listing.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { parseSkillFrontmatter, SKILL_NAME_PATTERN } from "@prismshadow/penguin-skills";+import type { SkillMetadata } from "@prismshadow/penguin-skills";+import { HttpError } from "../http/errors.js";+import {+ MAX_ARCHIVE_FILES,+ MAX_FILE_BYTES,+ MAX_TOTAL_BYTES,+ skillTooLarge,+} from "./skill-import-limits.js";++/** The two layouts a coding agent writes, in precedence order: `.agents` wins a name collision. */+export const SKILL_SOURCE_DIRS = [".agents/skills", ".claude/skills"] as const;++export type SkillSourceDir = (typeof SKILL_SOURCE_DIRS)[number];++/** A Skill found on disk: library-shaped, so `installSkill` takes it unchanged. */+export interface DirectorySkill extends SkillMetadata {+ content: string;+ icon?: string;+ files?: Record<string, string>;+ /** Which of the two layouts it came from — shown in the picker so the origin is visible. */+ source: SkillSourceDir;+}++/**+ * What discovery returns: everything a picker needs, plus the resolved directory so an install+ * can go back for the payload. Never serialized — the route projects through `toMetadataItem`.+ */+export interface DirectorySkillEntry extends Omit<DirectorySkill, "files"> {+ /** Absolute path of the Skill's own directory. */+ abs: string;+}++/**+ * The distinct Skill roots under `dir`, in precedence order. A missing or unreadable root is+ * skipped; two roots resolving to the same real directory (the `.claude` → `.agents` symlink)+ * collapse to one, so its Skills are offered once.+ */+async function resolveSkillRoots(+ dir: string,+): Promise<Array<{ abs: string; source: SkillSourceDir }>> {+ const roots: Array<{ abs: string; source: SkillSourceDir }> = [];+ const seen = new Set<string>();+ for (const source of SKILL_SOURCE_DIRS) {+ let abs: string;+ try {+ abs = await fs.realpath(path.join(dir, source));+ if (!(await fs.stat(abs)).isDirectory()) continue;+ } catch {+ continue;+ }+ if (seen.has(abs)) continue;+ seen.add(abs);+ roots.push({ abs, source });+ }+ return roots;+}++/**+ * Mirrors core's `assertSafeSkillFile`, so a path the writer would reject is passed over here+ * rather than becoming a bare `Error` — a 500 — inside `installSkill`, after the Agent directory+ * already exists. A backslash in a filename is legal on Linux and common in trees copied from+ * Windows, so this is reachable without anything hostile.+ */+function isSafeSkillFilePath(rel: string): boolean {+ return (+ rel.length > 0 &&+ !path.isAbsolute(rel) &&+ !rel.includes("\\") &&+ !rel.split("/").some((segment) => segment === "..")+ );+}++/**+ * Reads one of a Skill's two named files (`SKILL.md`, `icon.svg`), or undefined when it is not+ * there. `lstat` first, and only a regular file within the per-file cap is read: a symlink named+ * `icon.svg` is how a file outside the Skill directory would otherwise be handed back verbatim in+ * a listing, a FIFO would block the read (and its libuv threadpool thread) forever, and a size+ * taken from the stat refuses an oversized file before it is in memory rather than after.+ */+async function readSkillFile(file: string): Promise<string | undefined> {+ let stat;+ try {+ stat = await fs.lstat(file);+ } catch {+ return undefined;+ }+ if (!stat.isFile()) return undefined;+ if (stat.size > MAX_FILE_BYTES) throw skillTooLarge();+ return fs.readFile(file, "utf8");+}++/**+ * Auxiliary files a SKILL.md ships alongside it (`reference/API.md` and the like), with the+ * archive caps applied across the whole Skill. `SKILL.md` and `icon.svg` are handled by the+ * caller and excluded here so they are not written twice.+ */+async function readAuxiliaryFiles(dir: string): Promise<Record<string, string>> {+ const files: Record<string, string> = {};+ let count = 0;+ let total = 0;+ const walk = async (abs: string, rel: string): Promise<void> => {+ for (const entry of await fs.readdir(abs, { withFileTypes: true })) {+ const relChild = rel ? `${rel}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ await walk(path.join(abs, entry.name), relChild);+ continue;+ }+ // Non-regular entries are skipped, symlinks included: a link is how a file outside the+ // Skill directory would otherwise be read.+ if (!entry.isFile()) continue;+ if (relChild === "SKILL.md" || relChild === "icon.svg") continue;+ if (!isSafeSkillFilePath(relChild)) continue;+ const child = path.join(abs, entry.name);+ // The caps come off the stat, so an oversized file never reaches the heap.+ const size = (await fs.stat(child)).size;+ count += 1;+ total += size;+ if (count > MAX_ARCHIVE_FILES || size > MAX_FILE_BYTES || total > MAX_TOTAL_BYTES) {+ throw skillTooLarge();+ }+ files[relChild] = await fs.readFile(child, "utf8");+ }+ };+ await walk(dir, "");+ return files;+}++/** One candidate directory's metadata, or null when it is not an installable Skill. */+async function readSkillEntry(+ abs: string,+ name: string,+ source: SkillSourceDir,+): Promise<DirectorySkillEntry | null> {+ const content = await readSkillFile(path.join(abs, "SKILL.md"));+ if (content === undefined) return null;+ const metadata = parseSkillFrontmatter(content);+ if (!metadata) return null;+ const icon = await readSkillFile(path.join(abs, "icon.svg"));+ return {+ ...metadata,+ // The directory name is authoritative: it is what the Skill installs as, and frontmatter+ // that disagrees with its own directory would install under a name the user did not pick.+ name,+ content,+ ...(icon !== undefined ? { icon } : {}),+ source,+ abs,+ };+}++/**+ * Every installable Skill under `dir`, name-sorted. An absent or empty `.agents/skills` and+ * `.claude/skills` is a quiet empty list, not an error — pointing at a directory that simply has+ * no Skills is a normal thing to do.+ */+export async function discoverDirectorySkills(dir: string): Promise<DirectorySkillEntry[]> {+ const byName = new Map<string, DirectorySkillEntry>();+ for (const root of await resolveSkillRoots(dir)) {+ let entries: import("node:fs").Dirent[];+ try {+ entries = await fs.readdir(root.abs, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ // A symlinked Skill directory is not a directory to Dirent, so it is skipped here too.+ if (!entry.isDirectory() || !SKILL_NAME_PATTERN.test(entry.name)) continue;+ if (byName.has(entry.name)) continue; // earlier root wins: .agents over .claude+ // One Skill that cannot be read — an unreadable file, an oversized SKILL.md — is passed+ // over like any other non-installable directory, rather than failing the whole listing.+ const skill = await readSkillEntry(+ path.join(root.abs, entry.name),+ entry.name,+ root.source,+ ).catch(() => null);+ if (skill) byName.set(entry.name, skill);+ }+ }+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));+}++/**+ * Resolves picked names against a directory, in the order given — the same+ * everything-before-anything-is-written contract as `resolveLibrarySkills`, so a name that is no+ * longer there fails before the Agent exists rather than leaving it half-seeded. The auxiliary+ * files are read here and only here: they are the installable payload, and a listing must not+ * cost the payload of every Skill in the checkout.+ */+export async function resolveDirectorySkills(+ dir: string,+ names: readonly string[],+): Promise<DirectorySkill[]> {+ if (names.length === 0) return [];+ const found = new Map((await discoverDirectorySkills(dir)).map((s) => [s.name, s]));+ const picked = names.map((name) => {+ const skill = found.get(name);+ if (!skill) {+ throw new HttpError(404, "unknown_skill", `Skill is not in ${dir}: ${name}`);+ }+ return skill;+ });+ return Promise.all(+ picked.map(async ({ abs, ...skill }) => {+ const files = await readAuxiliaryFiles(abs);+ return { ...skill, ...(Object.keys(files).length > 0 ? { files } : {}) };+ }),+ );+}diff --git a/packages/server/src/services/skill-import-limits.ts b/packages/server/src/services/skill-import-limits.tsnew file mode 100644index 00000000..27f2d5ac--- /dev/null+++ b/packages/server/src/services/skill-import-limits.ts@@ -0,0 +1,19 @@+/**+ * Caps shared by every path that pulls Skill files in from outside the library — the archive+ * upload/download routes and the directory import. One set of numbers, so a limit raised for one+ * entry point cannot quietly leave another behind, and one message, so the failure reads the same+ * wherever the user hit it.+ */+import { HttpError } from "../http/errors.js";++export const MAX_ARCHIVE_FILES = 200;+export const MAX_FILE_BYTES = 5 * 1024 * 1024;+export const MAX_TOTAL_BYTES = 20 * 1024 * 1024;++export function skillTooLarge(): HttpError {+ return new HttpError(+ 413,+ "skill_too_large",+ `Skill directory exceeds the archive limits (${MAX_ARCHIVE_FILES} files, 5MB per file, 20MB total).`,+ );+}diff --git a/packages/server/src/services/skill-library.ts b/packages/server/src/services/skill-library.tsnew file mode 100644index 00000000..b9ac741f--- /dev/null+++ b/packages/server/src/services/skill-library.ts@@ -0,0 +1,48 @@+/**+ * Library Skill lookup shared by every surface that installs from the built-in library: the+ * Skills tab's install route and Agent creation's seed list. Both resolve the whole batch of+ * names before a single file is written, so an unknown name leaves nothing half-installed.+ *+ * It also owns `toMetadataItem`, the one projection from a Skill onto the wire type. Every+ * endpoint that describes a Skill goes through it, so a field added to `SkillMetadata` cannot+ * start leaking out of one endpoint while the others correctly withhold it.+ */+import { librarySkill } from "@prismshadow/penguin-skills";+import type { LibrarySkill, SkillMetadata } from "@prismshadow/penguin-skills";+import type { SkillMetadataItem } from "../api/types.js";+import { HttpError } from "../http/errors.js";++/**+ * Resolves library Skill names to their entries, in the order given. Throws 404 `unknown_skill`+ * on the first name the library does not carry — the caller is expected to run this before it+ * creates or writes anything.+ */+export function resolveLibrarySkills(names: readonly string[]): LibrarySkill[] {+ return names.map((name) => {+ const skill = librarySkill(name);+ if (!skill) throw new HttpError(404, "unknown_skill", `Skill is not in the library: ${name}`);+ return skill;+ });+}++/**+ * Strips a Skill down to what the API sends: the full body is written to disk on install and+ * read by the model on demand, never shipped in a listing. An allowlist rather than a+ * strip-these-two spread, so a new `SkillMetadata` field is withheld until someone adds it here+ * on purpose. The optional short description (shortDescription(Zh)) and custom icon (icon.svg+ * source) are conditionally passed through — the library side (LibrarySkill), the installed side+ * (core InstalledSkill) and the directory side all carry these fields.+ */+export function toMetadataItem(skill: SkillMetadata & { icon?: string }): SkillMetadataItem {+ return {+ name: skill.name,+ description: skill.description,+ ...(skill.shortDescription !== undefined ? { shortDescription: skill.shortDescription } : {}),+ ...(skill.shortDescriptionZh !== undefined+ ? { shortDescriptionZh: skill.shortDescriptionZh }+ : {}),+ ...(skill.icon !== undefined ? { icon: skill.icon } : {}),+ version: skill.version,+ updated: skill.updated,+ };+}diff --git a/packages/server/test/directory-skills.test.ts b/packages/server/test/directory-skills.test.tsnew file mode 100644index 00000000..a995b77c--- /dev/null+++ b/packages/server/test/directory-skills.test.ts@@ -0,0 +1,296 @@+/**+ * Integration tests for importing Skills from a directory the user picked: discovery under+ * `.agents/skills` / `.claude/skills`, the `.claude`-is-a-symlink-to-`.agents` case that would+ * otherwise offer everything twice, which layout wins a name collision, what is passed over rather+ * than offered (no frontmatter, a symlinked Skill directory, an unsafe name), the empty directory+ * being a normal answer, path and authorization rejections, and Agent creation installing the+ * picked names — including a directory Skill shadowing a library Skill of the same name.+ *+ * It also pins the read discipline the module promises: `SKILL.md` and `icon.svg` are read only+ * when they are regular files the Skill directory owns, so a symlink cannot hand back a file+ * outside it; and one Skill that cannot be read does not take the rest of the directory with it.+ */+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { skillsDir } from "@prismshadow/penguin-core";+import { librarySkill } from "@prismshadow/penguin-skills";+import type {+ AgentCreateResponse,+ AgentSkillsResponse,+ DirectorySkillsResponse,+ ProjectCreateResponse,+} from "../src/api/types.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const skillMd = (name: string, description = `${name} does a thing`) =>+ `---\nname: ${name}\ndescription: ${description}\nversion: 3\nupdated: 2026-08-23\n---\n\nBody of ${name}.\n`;++describe("directory skills api", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let outsider: ReturnType<typeof apiClient>;+ let projectId: string;+ let dir: string;++ const listUrl = (p: string) =>+ `/api/projects/${projectId}/dir-skills?path=${encodeURIComponent(p)}`;++ /** Writes `<dir>/<layout>/<name>/SKILL.md`, plus any auxiliary files. */+ const writeSkill = async (+ layout: string,+ name: string,+ opts: { description?: string; files?: Record<string, string>; icon?: string } = {},+ ) => {+ const target = path.join(dir, layout, name);+ await fs.mkdir(target, { recursive: true });+ await fs.writeFile(path.join(target, "SKILL.md"), skillMd(name, opts.description));+ if (opts.icon) await fs.writeFile(path.join(target, "icon.svg"), opts.icon);+ for (const [rel, data] of Object.entries(opts.files ?? {})) {+ await fs.mkdir(path.dirname(path.join(target, rel)), { recursive: true });+ await fs.writeFile(path.join(target, rel), data);+ }+ };++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner_d");+ const b = await provisionUser(t.app, "outsider_d");+ owner = apiClient(t.app, a.cookie);+ outsider = apiClient(t.app, b.cookie);+ const created = (await (+ await owner.post("/api/projects", {+ projectId: "owner_d-dirskills",+ name: "directory skills project",+ })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-dirskills-"));+ });++ afterEach(async () => {+ // The app teardown must run even if the scratch checkout resists removal: a throw here would+ // skip `t.cleanup()`, leaking the db/hmr host into every later file in this worker — the+ // ci-windows cascade helpers.ts documents. Same maxRetries discipline, same reason.+ try {+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ } finally {+ await t.cleanup();+ }+ });++ it("finds Skills in both layouts and says which one each came from", async () => {+ await writeSkill(".agents/skills", "alpha");+ await writeSkill(".claude/skills", "beta");+ const res = (await (await owner.get(listUrl(dir))).json()) as DirectorySkillsResponse;+ expect(res.skills.map((s) => [s.name, s.source])).toEqual([+ ["alpha", ".agents/skills"],+ ["beta", ".claude/skills"],+ ]);+ // Metadata comes from the frontmatter, and content never crosses the wire.+ expect(res.skills[0]!.description).toBe("alpha does a thing");+ expect(res.skills[0]!.version).toBe(3);+ expect(res.skills[0]).not.toHaveProperty("content");+ });++ it("offers each Skill once when .claude is a symlink to .agents", async () => {+ await writeSkill(".agents/skills", "alpha");+ await writeSkill(".agents/skills", "gamma");+ await fs.symlink(path.join(dir, ".agents"), path.join(dir, ".claude"));+ const res = (await (await owner.get(listUrl(dir))).json()) as DirectorySkillsResponse;+ expect(res.skills.map((s) => s.name)).toEqual(["alpha", "gamma"]);+ expect(res.skills.every((s) => s.source === ".agents/skills")).toBe(true);+ });++ it("lets .agents win when both layouts carry the same name as real directories", async () => {+ await writeSkill(".agents/skills", "dup", { description: "from agents" });+ await writeSkill(".claude/skills", "dup", { description: "from claude" });+ const res = (await (await owner.get(listUrl(dir))).json()) as DirectorySkillsResponse;+ expect(res.skills).toHaveLength(1);+ expect(res.skills[0]!.description).toBe("from agents");+ expect(res.skills[0]!.source).toBe(".agents/skills");+ });++ it("passes over what is not an installable Skill instead of offering it", async () => {+ await writeSkill(".agents/skills", "real");+ // No SKILL.md at all.+ await fs.mkdir(path.join(dir, ".agents/skills/empty-dir"), { recursive: true });+ // A SKILL.md with no frontmatter.+ await fs.mkdir(path.join(dir, ".agents/skills/no-frontmatter"), { recursive: true });+ await fs.writeFile(path.join(dir, ".agents/skills/no-frontmatter/SKILL.md"), "just prose\n");+ // A name the installer would reject.+ await fs.mkdir(path.join(dir, ".agents/skills/bad name"), { recursive: true });+ await fs.writeFile(path.join(dir, ".agents/skills/bad name/SKILL.md"), skillMd("bad name"));+ // A symlinked Skill directory: how a tree outside the layout would otherwise be read.+ const outside = path.join(dir, "outside-skill");+ await fs.mkdir(outside, { recursive: true });+ await fs.writeFile(path.join(outside, "SKILL.md"), skillMd("linked"));+ await fs.symlink(outside, path.join(dir, ".agents/skills/linked"));++ const res = (await (await owner.get(listUrl(dir))).json()) as DirectorySkillsResponse;+ expect(res.skills.map((s) => s.name)).toEqual(["real"]);+ });++ it("does not follow a symlinked SKILL.md or icon.svg out of the Skill directory", async () => {+ const secret = path.join(dir, "outside", "id_rsa");+ await fs.mkdir(path.dirname(secret), { recursive: true });+ await fs.writeFile(secret, "-----BEGIN PRIVATE KEY-----\nSECRET\n");++ // A real Skill whose icon.svg is a link to that file: the Skill is still offered, without an+ // icon — the link's target never reaches the response, nor the Agent it would be installed on.+ await writeSkill(".agents/skills", "linked-icon");+ await fs.rm(path.join(dir, ".agents/skills/linked-icon/icon.svg"), { force: true });+ await fs.symlink(secret, path.join(dir, ".agents/skills/linked-icon/icon.svg"));+ // A Skill whose SKILL.md is itself a link is not a Skill at all.+ const outsideMd = path.join(dir, "outside", "SKILL.md");+ await fs.writeFile(outsideMd, skillMd("linked-md"));+ await fs.mkdir(path.join(dir, ".agents/skills/linked-md"), { recursive: true });+ await fs.symlink(outsideMd, path.join(dir, ".agents/skills/linked-md/SKILL.md"));++ const res = (await (await owner.get(listUrl(dir))).json()) as DirectorySkillsResponse;+ expect(res.skills.map((s) => s.name)).toEqual(["linked-icon"]);+ expect(res.skills[0]).not.toHaveProperty("icon");+ expect(JSON.stringify(res)).not.toContain("SECRET");++ const created = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "no_link_agent",+ skillsDirectory: dir,+ directorySkills: ["linked-icon"],+ });+ expect(created.status).toBe(201);+ await expect(+ fs.readFile(+ path.join(skillsDir(t.root, projectId, "no_link_agent"), "linked-icon", "icon.svg"),+ "utf8",+ ),+ ).rejects.toThrow();+ });++ it("passes over a Skill that busts the size caps instead of hiding the whole directory", async () => {+ await writeSkill(".agents/skills", "small");+ await writeSkill(".agents/skills", "fat", {+ // One auxiliary file over the 5MB per-file cap.+ files: { "blob.bin": "x".repeat(6 * 1024 * 1024) },+ });+ const res = await owner.get(listUrl(dir));+ expect(res.status).toBe(200);+ expect(((await res.json()) as DirectorySkillsResponse).skills.map((s) => s.name)).toEqual([+ "fat",+ "small",+ ]);+ // Picking the oversized one is still refused, and no Agent is left behind.+ const created = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "fat_agent",+ skillsDirectory: dir,+ directorySkills: ["fat"],+ });+ expect(created.status).toBe(413);+ expect(+ (await owner.post(`/api/projects/${projectId}/agents`, { agentId: "fat_agent" })).status,+ ).toBe(201);+ });++ it("answers an empty list for a directory that carries no Skills", async () => {+ const res = await owner.get(listUrl(dir));+ expect(res.status).toBe(200);+ expect(((await res.json()) as DirectorySkillsResponse).skills).toEqual([]);+ });++ it("rejects a relative path, a missing directory, and an outsider", async () => {+ expect((await owner.get(listUrl("relative/path"))).status).toBe(400);+ expect((await owner.get(listUrl(path.join(dir, "nope")))).status).toBe(404);+ expect((await outsider.get(listUrl(dir))).status).toBe(404);+ });++ it("installs the picked directory Skills at creation, files and icon included", async () => {+ await writeSkill(".agents/skills", "alpha", {+ icon: "<svg/>",+ files: { "reference/api.md": "aux body\n" },+ });+ await writeSkill(".claude/skills", "beta");+ const created = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "dir_agent",+ skillsDirectory: dir,+ directorySkills: ["alpha", "beta"],+ });+ expect(created.status).toBe(201);+ expect(((await created.json()) as AgentCreateResponse).agent.skillCount).toBe(2);++ const installed = skillsDir(t.root, projectId, "dir_agent");+ expect(await fs.readFile(path.join(installed, "alpha", "SKILL.md"), "utf8")).toBe(+ skillMd("alpha"),+ );+ expect(await fs.readFile(path.join(installed, "alpha", "icon.svg"), "utf8")).toBe("<svg/>");+ expect(await fs.readFile(path.join(installed, "alpha", "reference", "api.md"), "utf8")).toBe(+ "aux body\n",+ );+ const listed = (await (+ await owner.get(`/api/projects/${projectId}/agents/dir_agent/skills`)+ ).json()) as AgentSkillsResponse;+ expect(listed.skills.map((s) => s.name)).toEqual(["alpha", "beta"]);+ });++ it("lets a directory Skill shadow a library Skill of the same name", async () => {+ await writeSkill(".agents/skills", "penguin-sdk", { description: "the checkout's own" });+ const created = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "shadow_agent",+ skills: ["penguin-sdk"],+ skillsDirectory: dir,+ directorySkills: ["penguin-sdk"],+ });+ expect(created.status).toBe(201);+ const onDisk = await fs.readFile(+ path.join(skillsDir(t.root, projectId, "shadow_agent"), "penguin-sdk", "SKILL.md"),+ "utf8",+ );+ expect(onDisk).toBe(skillMd("penguin-sdk", "the checkout's own"));+ expect(onDisk).not.toBe(librarySkill("penguin-sdk")!.content);+ });++ it("is 404 with no Agent created when a picked directory Skill is gone", async () => {+ await writeSkill(".agents/skills", "alpha");+ const res = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "ghost_dir_agent",+ skillsDirectory: dir,+ directorySkills: ["alpha", "vanished"],+ });+ expect(res.status).toBe(404);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("unknown_skill");+ // The id is still free: nothing was written before the whole batch resolved.+ expect(+ (await owner.post(`/api/projects/${projectId}/agents`, { agentId: "ghost_dir_agent" }))+ .status,+ ).toBe(201);+ });++ it("rejects a relative skillsDirectory on create, like the discovery route does", async () => {+ const res = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "rel_agent",+ skillsDirectory: "relative/path",+ directorySkills: ["alpha"],+ });+ expect(res.status).toBe(400);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("dir_not_absolute");+ });++ it("rejects half of the directory pair rather than ignoring it", async () => {+ expect(+ (+ await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "half_a",+ skillsDirectory: dir,+ })+ ).status,+ ).toBe(400);+ expect(+ (+ await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "half_b",+ directorySkills: ["alpha"],+ })+ ).status,+ ).toBe(400);+ });+});diff --git a/packages/server/test/skills.test.ts b/packages/server/test/skills.test.tsindex 7788b577..791e2e37 100644--- a/packages/server/test/skills.test.ts+++ b/packages/server/test/skills.test.ts@@ -4,7 +4,8 @@* files matching the library content, idempotent update on reinstall, the* directory disappearing after uninstall, default_agent starting with the* preinstalled library set (preinstall: false skills stay manual-install)- * while a newly created plain Agent has none, and the zip+ * while a newly created plain Agent has none, Agent creation seeding the Skills picked in the+ * create dialog (unknown name = 404 with no Agent created), and the zip* archive install/export (layouts, zip-slip and limit rejections, 409* skill_exists + overwrite replace, byte-identical export round-trip).*/@@ -15,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";import { skillsDir } from "@prismshadow/penguin-core";import { librarySkill, loadPreinstalledSkills } from "@prismshadow/penguin-skills";import type {+ AgentCreateResponse,AgentSkillsResponse,ProjectCreateResponse,SkillLibraryResponse,@@ -247,6 +249,54 @@ describe("skills api", () => {expect(fresh.skills).toEqual([]);});+ it("agent create seeds the picked library skills; the files land verbatim and the card count follows", async () => {+ const created = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "seeded_agent",+ name: "Seeded",+ skills: ["penguin-sdk", "web-design"],+ });+ expect(created.status).toBe(201);+ const summary = (await created.json()) as AgentCreateResponse;+ expect(summary.agent.skillCount).toBe(2);++ // The installed list is the same shape a library install produces (name-sorted).+ const listed = (await (await member.get(base("seeded_agent"))).json()) as AgentSkillsResponse;+ expect(listed.skills.map((s) => s.name)).toEqual(["penguin-sdk", "web-design"]);+ // Installed through the same writer as the Skills tab: SKILL.md is the library file verbatim.+ const onDisk = await fs.readFile(+ path.join(skillsDir(t.root, projectId, "seeded_agent"), "penguin-sdk", "SKILL.md"),+ "utf8",+ );+ expect(onDisk).toBe(librarySkill("penguin-sdk")!.content);+ });++ it("agent create with an unknown skill is 404 unknown_skill and creates no Agent", async () => {+ const res = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "ghost_agent",+ skills: ["penguin-sdk", "no-such-skill"],+ });+ expect(res.status).toBe(404);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("unknown_skill");+ // Nothing was created: the id is still free, and no directory was left behind.+ await expect(+ fs.stat(path.join(skillsDir(t.root, projectId, "ghost_agent"), "..")),+ ).rejects.toThrow();+ expect(+ (await owner.post(`/api/projects/${projectId}/agents`, { agentId: "ghost_agent" })).status,+ ).toBe(201);+ });++ it("agent create without skills stays a plain Agent; a non-array skills field is 400", async () => {+ await createPlainAgent("plain_seed");+ const plain = (await (await member.get(base("plain_seed"))).json()) as AgentSkillsResponse;+ expect(plain.skills).toEqual([]);+ const bad = await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: "bad_seed",+ skills: "penguin-sdk",+ });+ expect(bad.status).toBe(400);+ });+// ---- POST .../skills/archive: install one skill from an uploaded zip ----const ZIP_SKILL_MD =diff --git a/packages/web/e2e/agent-create-skills.spec.mjs b/packages/web/e2e/agent-create-skills.spec.mjsnew file mode 100644index 00000000..4aa7dbb1--- /dev/null+++ b/packages/web/e2e/agent-create-skills.spec.mjs@@ -0,0 +1,115 @@+/**+ * End-to-end test for seeding a new Agent with library Skills from the create dialog (locale+ * zh-CN):+ * - the Agents page's "创建 Agent" ("Create agent") dialog carries a Skills field whose trigger+ * reads as a placeholder until something is picked, and whose panel is the shared multi-select+ * list — a search box, one toggle row per library skill, and a bulk row with 全选 / 全不选+ * ("select all" / "select none") beside the running count;+ * - 全选 picks every library skill and 全不选 clears them, both without closing the panel;+ * - the search box narrows the list, and the bulk controls then act on what the search leaves+ * visible rather than on the whole library — so a filtered 全选 adds only the matches;+ * - creating with a selection installs exactly those skills into the new Agent: the settings+ * page's Skills tab lists them, and the server's installed list agrees;+ * - creating with nothing picked still yields a plain Agent with no skills.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const U = "seeduser";+const P = "password123";++/** The bulk row's running count (exact: the trigger carries the same prefix with a trailing noun). */+const pickedCount = (page, n) => page.getByText(`已选 ${n} 个`, { exact: true });++/**+ * One library skill row in the picker panel. The row's accessible name is the skill name followed+ * by its description, so the match is anchored at the start AND closed at a non-name character:+ * a bare `^name` prefix would match `web-design` and `web-design-pro` both, and resolve to two+ * buttons the moment the library grows such a pair.+ */+const row = (page, name) =>+ page.getByRole("button", {+ name: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`),+ });++test("agent create: pick library skills (select all / none, filtered) -> they are installed on the new Agent", async ({+ page,+}) => {+ await provisionAndLogin(page.request, U, P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;++ // The library is the source of truth for what the picker offers.+ const library = await (await page.request.get(`${BASE}/api/skills`)).json();+ const libraryNames = library.groups.flatMap((g) => g.skills.map((s) => s.name));+ expect(libraryNames.length).toBeGreaterThan(2);++ await page.goto(`${BASE}/agents`);+ await page.getByRole("button", { name: "创建 Agent" }).first().click();++ const idField = page.getByRole("textbox", { name: /^Agent id/ });+ await expect(idField).toBeVisible();+ await idField.fill("seeded_agent");++ // —— The Skills field: placeholder until something is picked ——+ const picker = page.getByRole("button", { name: "技能", exact: true });+ await expect(picker).toContainText("未选择技能");+ await picker.click();++ // Every library skill has a row, and the bulk row reports an empty selection.+ for (const name of libraryNames) {+ await expect(row(page, name)).toBeVisible();+ }+ await expect(pickedCount(page, 0)).toBeVisible();++ // —— 全选 / 全不选: the panel stays open and the count follows ——+ await page.getByRole("button", { name: "全选" }).click();+ await expect(pickedCount(page, libraryNames.length)).toBeVisible();+ await expect(row(page, libraryNames[0])).toHaveAttribute("aria-pressed", "true");+ await page.getByRole("button", { name: "全不选" }).click();+ await expect(pickedCount(page, 0)).toBeVisible();+ await expect(row(page, libraryNames[0])).toHaveAttribute("aria-pressed", "false");++ // —— The search box narrows the list, and 全选 then acts on the matches only ——+ await page.getByPlaceholder("搜索技能").fill("penguin-sdk");+ await expect(row(page, "penguin-sdk")).toBeVisible();+ await page.getByRole("button", { name: "全选" }).click();+ await expect(pickedCount(page, 1)).toBeVisible();+ await page.getByPlaceholder("搜索技能").fill("");++ // A second skill picked by clicking its row (toggle, panel stays open).+ await row(page, "web-design").click();+ await expect(row(page, "web-design")).toHaveAttribute("aria-pressed", "true");+ await expect(pickedCount(page, 2)).toBeVisible();++ // Escape closes the picker panel without closing the dialog (the Esc-layer stack).+ await page.keyboard.press("Escape");+ await expect(picker).toContainText("已选 2 个技能");+ await expect(idField).toBeVisible();++ // —— Create: the picked skills are installed into the new Agent ——+ await page.getByRole("button", { name: "创建", exact: true }).click();+ await page.waitForURL(/\/agents\/seeded_agent$/);++ const installed = await (+ await page.request.get(`${BASE}/api/projects/${projectId}/agents/seeded_agent/skills`)+ ).json();+ expect(installed.skills.map((s) => s.name).sort()).toEqual(["penguin-sdk", "web-design"]);++ // The Skills tab shows the same two.+ await page.goto(`${BASE}/agents/seeded_agent?tab=skills`);+ await expect(page.getByText("penguin-sdk", { exact: true })).toBeVisible();+ await expect(page.getByText("web-design", { exact: true })).toBeVisible();++ // —— Creating without picking anything leaves a plain Agent ——+ await page.goto(`${BASE}/agents`);+ await page.getByRole("button", { name: "创建 Agent" }).first().click();+ await page.getByRole("textbox", { name: /^Agent id/ }).fill("plain_agent");+ await page.getByRole("button", { name: "创建", exact: true }).click();+ await page.waitForURL(/\/agents\/plain_agent$/);+ const none = await (+ await page.request.get(`${BASE}/api/projects/${projectId}/agents/plain_agent/skills`)+ ).json();+ expect(none.skills).toEqual([]);+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex ce88347b..c0ea1660 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -33,6 +33,7 @@ import type {CommandPolicyRuleDto,DefaultModelResponse,DefaultModelUpdateRequest,+ DirectorySkillsResponse,DirListResponse,EndpointModelListRequest,EndpointModelListResponse,@@ -454,6 +455,15 @@ export const listDirs = (projectId: string, path = "") =>`/api/projects/${encodeURIComponent(projectId)}/dirs?path=${encodeURIComponent(path)}`,);+/**+ * Skills a directory carries under `.agents/skills` / `.claude/skills`: what picking it at Agent+ * creation would offer to install. `path` must be absolute.+ */+export const listDirectorySkills = (projectId: string, path: string) =>+ apiFetch<DirectorySkillsResponse>(+ `/api/projects/${encodeURIComponent(projectId)}/dir-skills?path=${encodeURIComponent(path)}`,+ );+export const createSession = (projectId: string, agentId: string, body: SessionCreateRequest) =>apiFetch<SessionCreateResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/sessions`,diff --git a/packages/web/src/components/ui/modal.tsx b/packages/web/src/components/ui/modal.tsxindex cfc27e31..7414daa6 100644--- a/packages/web/src/components/ui/modal.tsx+++ b/packages/web/src/components/ui/modal.tsx@@ -11,7 +11,7 @@* portaling, every modal is a sibling child of body and stacks naturally in DOM* order.*/-import { useEffect } from "react";+import { useEffect, useRef } from "react";import { createPortal } from "react-dom";import type { ReactNode } from "react";import { CloseButton } from "./icons";@@ -71,18 +71,26 @@ export function Modal({headerless,bare,}: ModalProps) {+ // Latest-callback ref, so the effect below re-runs ONLY on open/close: call sites pass an+ // inline arrow for onClose, and re-running on its identity would pop and re-push this+ // dialog's esc-layer on every render — jumping it back above a menu opened inside it, so+ // Escape would close the whole dialog instead of just the menu. Dropdown keeps the same+ // guard for the same reason.+ const onCloseRef = useRef(onClose);+ onCloseRef.current = onClose;+useEffect(() => {if (!open) return;const id = pushEscLayer();const onKey = (e: KeyboardEvent) => {- if (e.key === "Escape" && isTopEscLayer(id)) onClose();+ if (e.key === "Escape" && isTopEscLayer(id)) onCloseRef.current();};window.addEventListener("keydown", onKey);return () => {window.removeEventListener("keydown", onKey);popEscLayer(id);};- }, [open, onClose]);+ }, [open]);if (!open) return null;return createPortal(diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsxindex b7afb5a8..b8eb85ec 100644--- a/packages/web/src/features/agents/agents-page.tsx+++ b/packages/web/src/features/agents/agents-page.tsx@@ -11,10 +11,14 @@* header) and "Settings" (goes to settings page) show text labels; "Usage" (deep links via* ?agentId= to the usage center) and "Delete" (with confirmation; built-in Agents show a* non-interactive light gray placeholder with an undeletable tooltip) are square icon buttons- * (tooltip shows the full name); "Create Agent" only fills in name + description.+ * (tooltip shows the full name); "Create Agent" fills in name + description and picks the Skills+ * the new Agent starts with — from the library, and from a project directory's .agents/skills or+ * .claude/skills — through form-variant dropdowns over the shared multi-select panel, with select+ * all / select none. A plain new Agent otherwise starts with none.*/-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { useLocation, useNavigate } from "react-router";+import type { SkillMetadataItem } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";@@ -26,6 +30,8 @@ import { useLocale } from "../../state/locale";import { agentDisplayName, useProject } from "../../state/project";import { Button } from "../../components/ui/button";import { Input, Textarea } from "../../components/ui/input";+import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";+import { FormPicker } from "../../components/ui/form-picker";import { Modal } from "../../components/ui/modal";import { ConfirmModal } from "../../components/ui/confirm-modal";import { Badge } from "../../components/ui/badge";@@ -38,6 +44,9 @@ import { STAT_ICONS } from "../../lib/stat-icons";import { DRAFT_SESSION_ID } from "../chat/chat-page";import { parkActiveDraft } from "../chat/draft-sessions";import { ActivitySparkline } from "./activity-sparkline";+import { WorkspaceSelect } from "../chat/workspace-select";+import { SkillPickList } from "../skills/skill-pick-list";+import { addSkillNames, removeSkillNames, toggleSkillName } from "../skills/skill-selection";import { ICON_SIZE } from "../../lib/icon-scale";/** Built-in Agent shipped with every Project (default_agent only; the server also rejects deletion, so no delete entry point is shown here). */@@ -89,6 +98,28 @@ export function AgentsPage() {// The id is the only validated create field; format problems and the server's duplicate-id rejection land beside it.const [idError, setIdError] = useState<string | undefined>(undefined);const [busy, setBusy] = useState(false);+ /**+ * Skill library for the create dialog's picker, flattened out of its groups: the picker is a+ * flat searchable list (the same panel the composer uses), so the grouping the library page+ * renders carries no meaning here. `null` until a fetch succeeds.+ */+ const [library, setLibrary] = useState<SkillMetadataItem[] | null>(null);+ const [libraryError, setLibraryError] = useState<string | null>(null);+ /** In-flight guard for that fetch (StrictMode runs the effect twice), released on failure so reopening retries. */+ const libraryPending = useRef(false);+ /** Library skills to install into the new Agent, in pick order. */+ const [createSkills, setCreateSkills] = useState<string[]>([]);+ const [skillsOpen, setSkillsOpen] = useState(false);+ /**+ * Skills imported from a directory instead of the library, kept as its own field rather than+ * merged into the list above: the server lets a directory Skill and a library Skill share a+ * name (the directory one wins), which one flat list of picked names could not express.+ */+ const [skillsDir, setSkillsDir] = useState("");+ const [dirSkills, setDirSkills] = useState<SkillMetadataItem[] | null>(null);+ const [dirSkillsError, setDirSkillsError] = useState<string | null>(null);+ const [createDirSkills, setCreateDirSkills] = useState<string[]>([]);+ const [dirSkillsOpen, setDirSkillsOpen] = useState(false);/** Open the create dialog: don't keep the previous draft, always start from an empty form. */const openCreate = () => {@@ -96,9 +127,33 @@ export function AgentsPage() {setName("");setDescription("");setIdError(undefined);+ setCreateSkills([]);+ setSkillsOpen(false);+ setSkillsDir("");+ setDirSkills(null);+ setDirSkillsError(null);+ setCreateDirSkills([]);+ setDirSkillsOpen(false);setCreateOpen(true);};+ // The library is fetched the first time the dialog opens, not on page load: the list itself+ // never needs it, and a failure here must not keep the dialog from creating a plain Agent —+ // the picker then offers nothing and the field states the error in place of its hint.+ useEffect(() => {+ if (!createOpen || library !== null || libraryPending.current) return;+ libraryPending.current = true;+ setLibraryError(null);+ api+ .getSkillLibrary()+ .then((res) => setLibrary(res.groups.flatMap((g) => g.skills)))+ .catch((e: unknown) => {+ // Leave `library` unset and release the guard, so the next open tries again.+ libraryPending.current = false;+ setLibraryError(apiErrorText(e));+ });+ }, [createOpen, library]);+// Cross-page create intent (the sidebar's mode-dependent "new" button navigates here// with { create: true } route state — the chat draft's route-state idiom): open the// existing create dialog once, then strip the state so a refresh or back-nav doesn't@@ -117,6 +172,48 @@ export function AgentsPage() {const projectId = currentProject?.projectId;+ // Re-read whenever the picked directory changes. A directory that carries no Skills answers with+ // an empty list, which the field states in place of its hint rather than treating as a failure.+ useEffect(() => {+ if (!createOpen || !skillsDir || !projectId) {+ setDirSkills(null);+ setDirSkillsError(null);+ return;+ }+ let cancelled = false;+ // The previous directory's Skills go first: keeping them would leave their rows on offer and+ // their picked names submittable against the newly picked directory.+ setDirSkills(null);+ setDirSkillsError(null);+ api+ .listDirectorySkills(projectId, skillsDir)+ .then((res) => {+ if (!cancelled) setDirSkills(res.skills);+ })+ .catch((e: unknown) => {+ if (cancelled) return;+ setDirSkills(null);+ setDirSkillsError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, [createOpen, projectId, skillsDir]);++ // Picked names are dropped when they are no longer on offer, so switching directories cannot+ // submit a name the new one does not carry.+ useEffect(() => {+ if (dirSkills === null) {+ setCreateDirSkills((prev) => (prev.length === 0 ? prev : []));+ return;+ }+ const available = new Set(dirSkills.map((skill) => skill.name));+ setCreateDirSkills((prev) => {+ const next = prev.filter((name) => available.has(name));+ return next.length === prev.length ? prev : next;+ });+ }, [dirSkills]);+const create = async () => {if (!projectId) return;const id = agentId.trim();@@ -132,9 +229,27 @@ export function AgentsPage() {setIdError(undefined);try {// Name defaults to the id (leave blank to let the server fill it in from the id).- const body: { agentId: string; name?: string; description?: string } = { agentId: id };+ const body: {+ agentId: string;+ name?: string;+ description?: string;+ skills?: string[];+ skillsDirectory?: string;+ directorySkills?: string[];+ } = {+ agentId: id,+ };if (name.trim()) body.name = name.trim();if (description.trim()) body.description = description.trim();+ // Picked Skills are seeded server-side inside the same create call, so a failure leaves no+ // half-equipped Agent behind.+ if (createSkills.length > 0) body.skills = createSkills;+ // The pair only means anything together, so it is sent only when a directory actually+ // contributed something — picking a directory and then no Skills from it is a plain Agent.+ if (skillsDir && createDirSkills.length > 0) {+ body.skillsDirectory = skillsDir;+ body.directorySkills = createDirSkills;+ }const res = await api.createAgent(projectId, body);setCreateOpen(false);await reloadAgents();@@ -464,6 +579,104 @@ export function AgentsPage() {value={description}onChange={(e) => setDescription(e.target.value)}/>+ {/* Seed Skills: the form-variant picker (same trigger as the schedule dialog's model+ and workspace pickers) over the shared multi-select panel, so a dialog field and the+ composer's dropdown offer one list with one set of row semantics. */}+ <div>+ <FieldLabel>{S.agent.createSkills}</FieldLabel>+ <FormPicker+ open={skillsOpen}+ setOpen={setSkillsOpen}+ label={+ createSkills.length === 0+ ? S.agent.createSkillsPlaceholder+ : S.agent.createSkillsPicked(createSkills.length)+ }+ muted={createSkills.length === 0}+ title={S.agent.createSkills}+ ariaLabel={S.agent.createSkills}+ disabled={busy}+ menuClass="w-[26rem]"+ >+ <SkillPickList+ skills={library ?? []}+ selected={createSkills}+ onToggle={(skillName) =>+ setCreateSkills((prev) => toggleSkillName(prev, skillName))+ }+ onSelectAll={(names) => setCreateSkills((prev) => addSkillNames(prev, names))}+ onSelectNone={(names) => setCreateSkills((prev) => removeSkillNames(prev, names))}+ emptyHint={library === null ? S.common.loading : S.agent.createSkillsEmpty}+ />+ </FormPicker>+ {libraryError ? (+ <FieldError>{libraryError}</FieldError>+ ) : (+ <FieldHint>{S.agent.createSkillsHint}</FieldHint>+ )}+ </div>+ {/* Skills a checkout already carries: pick the project directory, then pick from what+ its .agents/skills / .claude/skills hold. Separate from the library field because a+ directory Skill may share a library Skill's name and still be the one installed. */}+ <div>+ <FieldLabel>{S.agent.createDirSkills}</FieldLabel>+ <WorkspaceSelect+ projectId={projectId ?? ""}+ workspace={skillsDir}+ onChange={setSkillsDir}+ variant="form"+ fieldLabel={S.agent.createDirSkills}+ emptyLabel={S.agent.createDirSkillsPick}+ menuHint={S.agent.createDirSkillsHint}+ clearLabel={S.agent.createDirSkillsClear}+ />+ {skillsDir && dirSkills !== null && dirSkills.length > 0 && (+ <div className="mt-2">+ <FormPicker+ open={dirSkillsOpen}+ setOpen={setDirSkillsOpen}+ label={+ createDirSkills.length === 0+ ? S.agent.createSkillsPlaceholder+ : S.agent.createSkillsPicked(createDirSkills.length)+ }+ muted={createDirSkills.length === 0}+ title={S.agent.createDirSkills}+ ariaLabel={S.agent.createDirSkills}+ disabled={busy}+ menuClass="w-[26rem]"+ >+ <SkillPickList+ skills={dirSkills}+ selected={createDirSkills}+ onToggle={(skillName) =>+ setCreateDirSkills((prev) => toggleSkillName(prev, skillName))+ }+ onSelectAll={(names) =>+ setCreateDirSkills((prev) => addSkillNames(prev, names))+ }+ onSelectNone={(names) =>+ setCreateDirSkills((prev) => removeSkillNames(prev, names))+ }+ emptyHint={S.agent.createDirSkillsEmpty}+ />+ </FormPicker>+ </div>+ )}+ {dirSkillsError ? (+ <FieldError>{dirSkillsError}</FieldError>+ ) : (+ <FieldHint>+ {!skillsDir+ ? S.agent.createDirSkillsHint+ : dirSkills === null+ ? S.common.loading+ : dirSkills.length === 0+ ? S.agent.createDirSkillsEmpty+ : S.agent.createDirSkillsFound(dirSkills.length)}+ </FieldHint>+ )}+ </div></div></Modal>diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 8a400bc6..0d745843 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -101,6 +101,8 @@ import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { noAutofill } from "../../components/ui/input";import { toastError, toastInfo } from "../../components/ui/toast";import { SkillIcon } from "../skills/skill-icon-view";+import { SkillPickList } from "../skills/skill-pick-list";+import { toggleSkillName } from "../skills/skill-selection";import { ZoomableImage } from "../../components/ui/image-zoom";import { ProviderLogo } from "../../components/ui/provider-logo";import { sameModelRef } from "../models/model-grouping";@@ -108,13 +110,7 @@ import { filterAgents, stagedSendRoute } from "./agent-handoff";import { ModelMenuList, ModelSelect, PickerList, modelLabel } from "./model-select";import { matchSlash, removeSlashToken } from "./slash-token";import { SELECTABLE_THINKING_LEVELS, thinkingLevelLabel } from "./thinking-level";-import {- BOOK_ICON,- buildSkillsMessage,- filterSkills,- localizedShortText,- skillSlashItems,-} from "./skill-use";+import { BOOK_ICON, buildSkillsMessage, localizedShortText, skillSlashItems } from "./skill-use";import { GOAL_ICON, UNLIMITED_BUDGET, parseBudgetInput } from "./goal-use";import { mergeRecalledDraft } from "./recall-draft";import { buildExampleFill } from "./example-fill";@@ -477,12 +473,12 @@ function SteerModeRow({/*** Multi-select skills dropdown (bottom toolbar, after approval mode): styled like the model* selector — button = book icon + "Skills" label + selected-count badge (no badge at 0; when the- * card is narrower than @md the label hides, leaving just icon + badge); menu = top search box- * (filters by name and localized description) + option rows (name in monospace + truncated- * description + selected checkmark). Multi-select semantics: clicking a row toggles its- * selection and **the menu stays open**; closes on Escape / click outside (built into Dropdown).- * Shows empty-state copy when no skills are installed (prompting to add some from the skill- * library). Popup direction depends on context (same as the approval mode selector).+ * card is narrower than @md the label hides, leaving just icon + badge); the menu body is the+ * shared SkillPickList (search box + toggle rows), without its bulk row — picking skills to send+ * a message with is a per-message act on a handful of names, not a set to fill in. Multi-select+ * semantics: clicking a row toggles its selection and **the menu stays open**; closes on Escape /+ * click outside (built into Dropdown). Popup direction depends on context (same as the approval+ * mode selector).*/function SkillSelect({skills,@@ -497,10 +493,7 @@ function SkillSelect({disabled: boolean;direction?: "up" | "down";}) {- const { locale } = useLocale();const [open, setOpen] = useState(false);- const [query, setQuery] = useState("");- const filtered = filterSkills(skills, locale, query);return (<Dropdownopen={open}@@ -515,11 +508,8 @@ function SkillSelect({aria-label={S.chat.skillsSelect}title={S.chat.skillsSelect}disabled={disabled}- onClick={() => {- const next = !open;- setOpen(next);- if (next) setQuery(""); // Always start from the full list each time it opens- }}+ // The panel is unmounted while closed, so its search box starts empty on every open.+ onClick={() => setOpen(!open)}className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"><GlyphIcon d={BOOK_ICON} className="shrink-0" />@@ -535,55 +525,12 @@ function SkillSelect({</button>}>- {/* Quick search: filters by skill name and localized description */}- <div className="border-b border-gray-100 px-2 pb-1.5 pt-0.5 dark:border-gray-800">- <input- autoFocus- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder={S.chat.skillsSearchPlaceholder}- aria-label={S.chat.skillsSearchPlaceholder}- {...noAutofill}- className="w-full rounded border border-transparent bg-transparent px-1 py-0.5 text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"- />- </div>- <div className="max-h-56 overflow-y-auto">- {skills.length === 0 ? (- <p className="px-3 py-1.5 text-xs text-gray-400">{S.chat.skillsEmptyHint}</p>- ) : filtered.length === 0 ? (- <p className="px-3 py-1.5 text-xs text-gray-400">{S.chat.skillsNoMatch}</p>- ) : (- filtered.map((s) => {- const on = selected.includes(s.name);- return (- <button- key={s.name}- type="button"- aria-pressed={on}- onClick={() => onToggle(s.name)}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${- on- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }`}- >- {/* Each skill's custom icon (icon.svg, sanitized and inlined; falls back to the book icon if missing). */}- <SkillIcon- icon={s.icon}- size={ICON_SIZE.inlineGlyph}- className="shrink-0 text-gray-400 dark:text-gray-500"- />- <span className="shrink-0 font-mono">{s.name}</span>- {/* Prefers the short description (falls back to the full description if missing), per the UI language. */}- <span className="min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500">- {localizedShortText(locale, s)}- </span>- <span className="w-3 shrink-0 text-center">{on ? "✓" : ""}</span>- </button>- );- })- )}- </div>+ <SkillPickList+ skills={skills}+ selected={selected}+ onToggle={onToggle}+ emptyHint={S.chat.skillsEmptyHint}+ /></Dropdown>);}@@ -1433,9 +1380,7 @@ export function ChatInput({/** Toggle a skill on/off (shared by dropdown option clicks and the slash skill command); the change callback lets the parent write it into the draft. */const toggleSkill = useCallback((name: string) => {- const next = selectedSkills.includes(name)- ? selectedSkills.filter((n) => n !== name)- : [...selectedSkills, name];+ const next = toggleSkillName(selectedSkills, name);setSelectedSkills(next);onSkillsChange?.(next);},diff --git a/packages/web/src/features/chat/workspace-select.tsx b/packages/web/src/features/chat/workspace-select.tsxindex 1a104018..179492cd 100644--- a/packages/web/src/features/chat/workspace-select.tsx+++ b/packages/web/src/features/chat/workspace-select.tsx@@ -43,6 +43,10 @@ export function WorkspaceSelect({onChange,variant = "pill",trigger,+ fieldLabel,+ emptyLabel,+ menuHint,+ clearLabel,}: {projectId: string;workspace: string;@@ -55,7 +59,21 @@ export function WorkspaceSelect({* clip an in-flow panel. The same browse menu, byte for byte.*/trigger?: (open: boolean, toggle: () => void) => ReactNode;+ /**+ * Copy overrides for a host that browses for a directory which is not going to be a Workspace —+ * the Agent create dialog picks one to read Skills out of, where "temporary workspace" would+ * describe something this field does not do. `fieldLabel` names the field itself: it is the+ * accessible name of both triggers and of the path input, and the label the tooltip puts in+ * front of the picked path, so a host that overrides the visible copy is not left announcing+ * itself as "Workspace".+ */+ fieldLabel?: string;+ emptyLabel?: string;+ menuHint?: string;+ /** Copy for the "back to a temporary workspace" link, which for a non-Workspace host just clears the field. */+ clearLabel?: string;}) {+ const fieldName = fieldLabel ?? S.chat.workspace;const [open, setOpen] = useState(false);/*** Menu docking, measured on each open: the pill follows the agent pill in a wrapping row, so@@ -175,7 +193,9 @@ export function WorkspaceSelect({const trimmed = workspace.trim();// Pill short name: the last segment of the directory name (root gives "/"); shows "temporary workspace" when empty.- const label = trimmed ? (trimmed.split("/").filter(Boolean).pop() ?? "/") : S.chat.workspaceAuto;+ const label = trimmed+ ? (trimmed.split("/").filter(Boolean).pop() ?? "/")+ : (emptyLabel ?? S.chat.workspaceAuto);const parentPath = dir?.parent ?? null;// Hidden directories (starting with .) are excluded from the list.const entries = (dir?.entries ?? []).filter((e) => !e.name.startsWith("."));@@ -191,7 +211,7 @@ export function WorkspaceSelect({<inputvalue={pathDraft}placeholder="…"- aria-label={S.chat.workspace}+ aria-label={fieldName}{...noAutofill}onChange={(e) => setPathDraft(e.target.value)}onBlur={commitPathEdit}@@ -283,12 +303,12 @@ export function WorkspaceSelect({}}className="text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200">- {S.chat.workspaceClear}+ {clearLabel ?? S.chat.workspaceClear}</button>)}{/* Hint text (bottom of the menu) */}<p className="px-0.5 text-xs leading-5 text-gray-400 dark:text-gray-500">- {S.chat.workspaceHint}+ {menuHint ?? S.chat.workspaceHint}</p></div>);@@ -320,8 +340,8 @@ export function WorkspaceSelect({leading={folderIcon("")}label={label}{...(trimmed ? { labelClassName: "font-mono" } : {})}- title={trimmed ? `${S.chat.workspace}:${trimmed}` : S.chat.workspaceHint}- ariaLabel={S.chat.workspace}+ title={trimmed ? `${fieldName}:${trimmed}` : (menuHint ?? S.chat.workspaceHint)}+ ariaLabel={fieldName}ariaHaspopup="dialog"menuClass="w-80">@@ -342,8 +362,8 @@ export function WorkspaceSelect({button={<buttontype="button"- title={trimmed ? `${S.chat.workspace}:${trimmed}` : S.chat.workspaceHint}- aria-label={S.chat.workspace}+ title={trimmed ? `${fieldName}:${trimmed}` : (menuHint ?? S.chat.workspaceHint)}+ aria-label={fieldName}onClick={toggle}className={pillClass}>diff --git a/packages/web/src/features/skills/skill-pick-list.tsx b/packages/web/src/features/skills/skill-pick-list.tsxnew file mode 100644index 00000000..38a678ab--- /dev/null+++ b/packages/web/src/features/skills/skill-pick-list.tsx@@ -0,0 +1,125 @@+/**+ * The multi-select skill panel body, shared by every surface that picks several skills at once:+ * the composer's skills dropdown and the Agent create dialog's seed picker. It owns the search+ * box, the scroll cap, the row chrome and the toggle semantics — clicking a row toggles it and+ * the panel stays open — so the two hosts differ only in their trigger and in whether they offer+ * the bulk controls.+ *+ * `onSelectAll` / `onSelectNone` render the bulk row, and both receive the names **currently+ * matching the search box**. With an empty query that is the whole list, which is the common+ * case; with a query typed, acting on the filtered set is the only reading that matches what the+ * user can see.+ */+import { useState } from "react";+import type { SkillMetadataItem } from "@prismshadow/penguin-server/api";+import { S } from "../../lib/strings";+import { useLocale } from "../../state/locale";+import { ICON_SIZE } from "../../lib/icon-scale";+import { noAutofill } from "../../components/ui/input";+import { filterSkills, localizedShortText } from "../chat/skill-use";+import { SkillIcon } from "./skill-icon-view";++/** A bulk-row action: a plain text button, sized to sit inside the panel's chrome without competing with the rows. */+const bulkActionClass =+ "rounded px-1 py-0.5 text-xs text-gray-500 transition-colors duration-150 " ++ "hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200";++export function SkillPickList({+ skills,+ selected,+ onToggle,+ onSelectAll,+ onSelectNone,+ emptyHint,+}: {+ skills: SkillMetadataItem[];+ /** Selected skill names. */+ selected: string[];+ onToggle: (name: string) => void;+ /** Given the names matching the current query; omit (with onSelectNone) to hide the bulk row. */+ onSelectAll?: (names: string[]) => void;+ onSelectNone?: (names: string[]) => void;+ /** Shown in place of the list when there is nothing to pick from at all. */+ emptyHint: string;+}) {+ const { locale } = useLocale();+ const [query, setQuery] = useState("");+ const filtered = filterSkills(skills, locale, query);+ const bulk = onSelectAll !== undefined && onSelectNone !== undefined;+ return (+ <>+ {/* Quick search: filters by skill name and localized description */}+ <div className="border-b border-gray-100 px-2 pb-1.5 pt-0.5 dark:border-gray-800">+ <input+ autoFocus+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={S.chat.skillsSearchPlaceholder}+ aria-label={S.chat.skillsSearchPlaceholder}+ {...noAutofill}+ className="w-full rounded border border-transparent bg-transparent px-1 py-0.5 text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"+ />+ </div>+ {bulk && skills.length > 0 && (+ <div className="flex items-center justify-between gap-2 border-b border-gray-100 px-3 py-1 dark:border-gray-800">+ <span className="min-w-0 truncate text-xs text-gray-400 dark:text-gray-500">+ {S.skills.selectedCount(selected.length)}+ </span>+ <span className="flex shrink-0 items-center gap-0.5">+ <button+ type="button"+ className={bulkActionClass}+ onClick={() => onSelectAll(filtered.map((s) => s.name))}+ >+ {S.skills.selectAll}+ </button>+ <button+ type="button"+ className={bulkActionClass}+ onClick={() => onSelectNone(filtered.map((s) => s.name))}+ >+ {S.skills.selectNone}+ </button>+ </span>+ </div>+ )}+ <div className="max-h-56 overflow-y-auto">+ {skills.length === 0 ? (+ <p className="px-3 py-1.5 text-xs text-gray-400">{emptyHint}</p>+ ) : filtered.length === 0 ? (+ <p className="px-3 py-1.5 text-xs text-gray-400">{S.chat.skillsNoMatch}</p>+ ) : (+ filtered.map((s) => {+ const on = selected.includes(s.name);+ return (+ <button+ key={s.name}+ type="button"+ aria-pressed={on}+ onClick={() => onToggle(s.name)}+ className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${+ on+ ? "font-medium text-gray-900 dark:text-gray-100"+ : "text-gray-600 dark:text-gray-400"+ }`}+ >+ {/* Each skill's custom icon (icon.svg, sanitized and inlined; falls back to the book icon if missing). */}+ <SkillIcon+ icon={s.icon}+ size={ICON_SIZE.inlineGlyph}+ className="shrink-0 text-gray-400 dark:text-gray-500"+ />+ <span className="shrink-0 font-mono">{s.name}</span>+ {/* Prefers the short description (falls back to the full description if missing), per the UI language. */}+ <span className="min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500">+ {localizedShortText(locale, s)}+ </span>+ <span className="w-3 shrink-0 text-center">{on ? "✓" : ""}</span>+ </button>+ );+ })+ )}+ </div>+ </>+ );+}diff --git a/packages/web/src/features/skills/skill-selection.ts b/packages/web/src/features/skills/skill-selection.tsnew file mode 100644index 00000000..66c052ee--- /dev/null+++ b/packages/web/src/features/skills/skill-selection.ts@@ -0,0 +1,23 @@+/**+ * Selection arithmetic for the multi-select skill panel (pure, unit tested), shared by the+ * composer's dropdown and the Agent create dialog's seed picker.+ *+ * The selection is an ordered list rather than a set because pick order is what the composer+ * renders and sends: a name joins at the end and keeps its place, so nothing reshuffles under+ * the user while they keep picking. Every function returns a new array and never mutates.+ */++/** Adds the name when absent, drops it when present. */+export function toggleSkillName(selected: readonly string[], name: string): string[] {+ return selected.includes(name) ? selected.filter((n) => n !== name) : [...selected, name];+}++/** Adds every name not already selected, appended in the order given. */+export function addSkillNames(selected: readonly string[], names: readonly string[]): string[] {+ return [...selected, ...names.filter((n) => !selected.includes(n))];+}++/** Drops every named entry, leaving the rest in their existing order. */+export function removeSkillNames(selected: readonly string[], names: readonly string[]): string[] {+ return selected.filter((n) => !names.includes(n));+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex acd79246..413bcda3 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -376,6 +376,20 @@ export const en: Strings = {"2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",nameHint: "Leave empty to use the agent id as the name",description: "Description",+ createSkills: "Skills",+ createSkillsPlaceholder: "No skills selected",+ createSkillsPicked: (n: number): string => `${n} skill${n === 1 ? "" : "s"} selected`,+ createSkillsHint:+ "Installed into the agent at creation; add or remove them later in its Skills tab.",+ createSkillsEmpty: "The skill library has nothing to install.",+ createDirSkills: "Import Skills from a project directory",+ createDirSkillsPick: "No directory selected",+ createDirSkillsHint:+ "Pick a project directory to read the Skills under its .agents/skills and .claude/skills",+ createDirSkillsEmpty: "This directory carries no installable Skills",+ createDirSkillsFound: (n: number): string =>+ `${n} skill${n === 1 ? "" : "s"} found in this directory`,+ createDirSkillsClear: "Clear the selected directory",sessionCount: (n: number): string => `${n} session${n === 1 ? "" : "s"}`,toolCount: (n: number): string => `${n} tool${n === 1 ? "" : "s"}`,vaultKeyCount: (n: number): string => `${n} vault key${n === 1 ? "" : "s"}`,@@ -986,6 +1000,9 @@ export const en: Strings = {quickInvokeText: (name: string): string => `use the ${name} skill`,/** Title on a disabled quick-start button: quick start opens a draft on the currently selected agent, so a skill it hasn't installed (e.g. a preinstall:false skill like remote-claude-code) can't be quick-started until it's installed on that agent. */quickInvokeNeedsInstall: "Install this skill on the current agent first to quick-start",+ selectAll: "Select all",+ selectNone: "Select none",+ selectedCount: (n: number): string => `${n} selected`,manageInstall: "Manage installs",manageInstallTitle: (name: string): string => `Manage installs: ${name}`,install: "Install",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex afb62cca..2f3aa95f 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -364,6 +364,18 @@ export const zh = {idHint: "2~64 位:小写字母开头,仅小写字母、数字与下划线;创建后不可修改",nameHint: "留空则使用 Agent id 作为名称",description: "描述",+ /** Create dialog's skill picker: the library skills installed into the new Agent. */+ createSkills: "技能",+ createSkillsPlaceholder: "未选择技能",+ createSkillsPicked: (n: number): string => `已选 ${n} 个技能`,+ createSkillsHint: "创建时安装到该 Agent,之后可在其「技能」标签页增删",+ createSkillsEmpty: "技能库暂无可安装的技能",+ createDirSkills: "从项目目录导入技能",+ createDirSkillsPick: "未选择目录",+ createDirSkillsHint: "选择一个项目目录,读取其 .agents/skills 与 .claude/skills 下的技能",+ createDirSkillsEmpty: "该目录下没有可安装的技能",+ createDirSkillsFound: (n: number): string => `该目录下找到 ${n} 个技能`,+ createDirSkillsClear: "清除已选目录",sessionCount: (n: number): string => `${n} 个 Session`,toolCount: (n: number): string => `${n} 个工具`,vaultKeyCount: (n: number): string => `${n} 个密钥`,@@ -952,6 +964,10 @@ export const zh = {quickInvokeText: (name: string): string => `使用 ${name} 技能`,/** Title on a disabled quick-invoke button: quick invoke opens a draft on the currently selected agent, so a skill it hasn't installed (e.g. preinstall:false skills like remote-claude-code) can't be quick-invoked until it's installed on that agent. */quickInvokeNeedsInstall: "先在当前 Agent 安装该技能后才能快捷调用",+ /** Bulk controls of the multi-select skill panel; both act on the rows the search box currently leaves visible. */+ selectAll: "全选",+ selectNone: "全不选",+ selectedCount: (n: number): string => `已选 ${n} 个`,manageInstall: "管理安装",manageInstallTitle: (name: string): string => `管理安装:${name}`,install: "安装",diff --git a/packages/web/test/skill-selection.test.ts b/packages/web/test/skill-selection.test.tsnew file mode 100644index 00000000..8d6384cc--- /dev/null+++ b/packages/web/test/skill-selection.test.ts@@ -0,0 +1,39 @@+/**+ * skill-selection.ts unit test: the selection arithmetic behind the multi-select skill panel —+ * the composer's toggle and the Agent create dialog's select-all / select-none, which act on the+ * names the search box currently leaves visible rather than on the whole library.+ */+import { describe, expect, it } from "vitest";+import {+ addSkillNames,+ removeSkillNames,+ toggleSkillName,+} from "../src/features/skills/skill-selection";++describe("skill selection arithmetic", () => {+ it("toggle adds an absent name at the end and drops a present one, keeping the rest in order", () => {+ expect(toggleSkillName(["a", "b"], "c")).toEqual(["a", "b", "c"]);+ expect(toggleSkillName(["a", "b", "c"], "b")).toEqual(["a", "c"]);+ expect(toggleSkillName([], "a")).toEqual(["a"]);+ });++ it("select-all appends only what is missing, so an already-picked name keeps its position", () => {+ expect(addSkillNames(["c"], ["a", "b", "c"])).toEqual(["c", "a", "b"]);+ expect(addSkillNames([], ["a", "b"])).toEqual(["a", "b"]);+ expect(addSkillNames(["a"], [])).toEqual(["a"]);+ });++ it("select-none drops only the named entries, so a filtered clear leaves the rest picked", () => {+ expect(removeSkillNames(["a", "b", "c"], ["b"])).toEqual(["a", "c"]);+ expect(removeSkillNames(["a", "b"], ["a", "b"])).toEqual([]);+ expect(removeSkillNames(["a"], ["z"])).toEqual(["a"]);+ });++ it("never mutates the input array", () => {+ const selected = ["a", "b"];+ toggleSkillName(selected, "c");+ addSkillNames(selected, ["c"]);+ removeSkillNames(selected, ["a"]);+ expect(selected).toEqual(["a", "b"]);+ });+});