Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(skills): add Import from local to the New skill dialog (MUL-6703) (#7570)
loonger9a19c90f8e84
diff --git a/apps/docs/content/docs/skills.ja.mdx b/apps/docs/content/docs/skills.ja.mdxindex 92d78e1a4d..a23b8be623 100644--- a/apps/docs/content/docs/skills.ja.mdx+++ b/apps/docs/content/docs/skills.ja.mdx@@ -19,17 +19,18 @@ import { Callout } from "fumadocs-ui/components/callout";## スキルの作成とインポート-ワークスペースの **スキル** ページで「新規スキル」を選ぶと、3 つの方法が使えます。+ワークスペースの **スキル** ページで「新規スキル」を選ぶと、4 つの方法が使えます。| 方法 | 向いている場合 ||---|---|| **手動で作成** | 空白の `SKILL.md` から書き始める。 |+| **ローカルからインポート** | `SKILL.md` を含むフォルダ、またはこのコンピュータ上の `.skill` / `.zip` アーカイブを選ぶ。 || **URL からインポート** | GitHub、ClawHub、Skills.sh で公開済みのスキルをインポートする。 || **ランタイムからコピー** | 接続中のコンピュータにあるスキルをスキャンし、選んだものをワークスペースへコピーする。 |ランタイムからのコピーは、その時点のファイルのスナップショットです。後からローカルファイルが変わっても、ワークスペース側のバージョンは自動更新されません。再インポートするか、Multica 上で編集してください。-CLI では、`.skill` や `.zip` ファイルからもインポートできます。+同じアーカイブ形式は CLI からも使えます。```bashmultica skill import --file ./review-helper.skilldiff --git a/apps/docs/content/docs/skills.ko.mdx b/apps/docs/content/docs/skills.ko.mdxindex c0d682eb72..eeba131f89 100644--- a/apps/docs/content/docs/skills.ko.mdx+++ b/apps/docs/content/docs/skills.ko.mdx@@ -19,17 +19,18 @@ import { Callout } from "fumadocs-ui/components/callout";## 스킬 생성 또는 가져오기-워크스페이스의 **스킬** 페이지에서 "새 스킬"을 선택하면 세 가지 방법을 사용할 수 있습니다.+워크스페이스의 **스킬** 페이지에서 "새 스킬"을 선택하면 네 가지 방법을 사용할 수 있습니다.| 방법 | 적합한 경우 ||---|---|| **직접 만들기** | 빈 `SKILL.md`에서 작성합니다. |+| **로컬에서 가져오기** | `SKILL.md`가 있는 폴더, 또는 이 컴퓨터의 `.skill` / `.zip` 아카이브를 선택합니다. || **URL에서 가져오기** | GitHub, ClawHub, Skills.sh에 게시된 스킬을 가져옵니다. || **런타임에서 복사** | 연결된 컴퓨터의 스킬을 스캔하고 선택한 내용을 워크스페이스로 복사합니다. |런타임에서 복사되는 내용은 그 시점의 파일 스냅샷입니다. 이후 로컬 파일이 바뀌어도 워크스페이스 버전은 자동으로 업데이트되지 않습니다. 다시 가져오거나 Multica에서 수정해야 합니다.-CLI에서는 `.skill` 또는 `.zip` 파일에서도 가져올 수 있습니다.+같은 아카이브 형식은 CLI에서도 사용할 수 있습니다.```bashmultica skill import --file ./review-helper.skilldiff --git a/apps/docs/content/docs/skills.mdx b/apps/docs/content/docs/skills.mdxindex 15ed6ea9ba..f2691f593c 100644--- a/apps/docs/content/docs/skills.mdx+++ b/apps/docs/content/docs/skills.mdx@@ -19,17 +19,18 @@ Add a skill to an [agent](/agents) and the agent uses its guidance when executin## Creating or importing a skill-On the workspace **Skills** page, choose "New skill". Three options are available:+On the workspace **Skills** page, choose "New skill". Four options are available:| Option | When it fits ||---|---|| **Create manually** | Start writing from a blank `SKILL.md`. |+| **Import from local** | Pick a folder that contains `SKILL.md`, or a `.skill` / `.zip` archive on this computer. || **Import from URL** | Import a published skill from GitHub, ClawHub, or Skills.sh. || **Copy from a runtime** | Scan skills on a connected computer and copy the selected ones into the workspace. |Copying from a runtime takes a snapshot of the files at that moment. Later changes to the local files do not update the workspace version automatically; re-import or edit in Multica.-With the CLI, you can also import from a `.skill` or `.zip` file:+The same archive format works from the CLI:```bashmultica skill import --file ./review-helper.skilldiff --git a/apps/docs/content/docs/skills.zh.mdx b/apps/docs/content/docs/skills.zh.mdxindex 7311843a55..2422ddee5c 100644--- a/apps/docs/content/docs/skills.zh.mdx+++ b/apps/docs/content/docs/skills.zh.mdx@@ -19,17 +19,18 @@ Skill 是工作区中可以复用的一组工作方法。它以 `SKILL.md` 为## 创建或导入 skill-在工作区的 **Skills** 页面选择"新建 skill",可以使用三种方式:+在工作区的 **Skills** 页面选择"新建 skill",可以使用四种方式:| 方式 | 适合什么情况 ||---|---|| **手动创建** | 从空白的 `SKILL.md` 开始编写。 |+| **从本地导入** | 选择包含 `SKILL.md` 的文件夹,或这台电脑上的 `.skill` / `.zip` 压缩包。 || **从 URL 导入** | 从 GitHub、ClawHub 或 Skills.sh 导入已经发布的 skill。 || **从运行时复制** | 扫描连接电脑上的 skill,并把选中的内容复制到工作区。 |从运行时复制的是当时的文件快照。之后本地文件发生变化,不会自动更新工作区中的版本;需要重新导入或在 Multica 中编辑。-使用 CLI 时,也可以从 `.skill` 或 `.zip` 文件导入:+同一套压缩包格式也可以用 CLI 导入:```bashmultica skill import --file ./review-helper.skilldiff --git a/apps/docs/content/docs/tutorial.ja.mdx b/apps/docs/content/docs/tutorial.ja.mdxindex ac7ce94d3b..fa963f2723 100644--- a/apps/docs/content/docs/tutorial.ja.mdx+++ b/apps/docs/content/docs/tutorial.ja.mdx@@ -275,9 +275,9 @@ MUL-1 のサイクルは一通り回りましたが、つなぎ目はすべて- **tdd** は Engineer に紐づけた、エンジニアリングの方法です。まず失敗するテストを書き、次にそれをちょうど通すだけの実装を書きます。- **i-have-adhd** は Lead に紐づけた、報告のスタイルです。1 行目は必ず実行できる次のステップで、手順が複数あるときは番号を振り、進捗が見えるようにします。リーダーの成果物はすべてあなたへの報告なので、このスキルがあなたの読むものを決めます。-チームの進め方をスキルとして蓄積しておけば、新しいエージェントは紐づけるだけで引き継げます。インポートだけが入手方法ではありません。**新規スキル** には、手動で作成する、URL からインポートする、ローカルのランタイムからコピーする、という 3 つの方法があります。ここでは詳しく触れません。[スキルのドキュメント](/skills)を参照してください。+チームの進め方をスキルとして蓄積しておけば、新しいエージェントは紐づけるだけで引き継げます。インポートだけが入手方法ではありません。**新規スキル** には、手動で作成する、ローカルからインポートする、URL からインポートする、ローカルのランタイムからコピーする、という 4 つの方法があります。ここでは詳しく触れません。[スキルのドキュメント](/skills)を参照してください。-+サードパーティのスキルをインポートする前に、そのファイルに一度目を通してください。Multica はサンドボックスによる隔離を行わず、スキルの内容はそのまま AI コーディングツールへ渡されます。diff --git a/apps/docs/content/docs/tutorial.ko.mdx b/apps/docs/content/docs/tutorial.ko.mdxindex 6ca003f728..aee9d12b08 100644--- a/apps/docs/content/docs/tutorial.ko.mdx+++ b/apps/docs/content/docs/tutorial.ko.mdx@@ -275,9 +275,9 @@ MUL-1의 순환은 잘 돌아갔지만 이어지는 단계는 매번 사람이- **tdd**는 Engineer에 연결한 엔지니어링 방법입니다. 실패하는 테스트를 먼저 쓰고, 그 테스트를 통과시키는 만큼만 구현합니다.- **i-have-adhd**는 Lead에 연결한 보고 스타일입니다. 첫 줄은 항상 실행 가능한 다음 단계이고, 여러 단계는 번호를 붙이며, 진행 상황이 드러납니다. 리더의 결과물은 전부 사람에게 보내는 보고이므로 이 스킬이 읽게 되는 형태를 결정합니다.-팀의 작업 방식을 스킬로 축적하면 새 에이전트는 연결하는 것만으로 이어받습니다. 가져오기만 있는 것은 아닙니다. **새 스킬**은 직접 만들기, URL에서 가져오기, 로컬 런타임에서 복사하기 세 가지 방법을 제공합니다. 여기서는 다루지 않으며 [스킬 문서](/skills)를 참고하세요.+팀의 작업 방식을 스킬로 축적하면 새 에이전트는 연결하는 것만으로 이어받습니다. 가져오기만 있는 것은 아닙니다. **새 스킬**은 직접 만들기, 로컬에서 가져오기, URL에서 가져오기, 로컬 런타임에서 복사하기 네 가지 방법을 제공합니다. 여기서는 다루지 않으며 [스킬 문서](/skills)를 참고하세요.-+외부 스킬을 가져오기 전에 파일을 먼저 읽어 보세요. Multica는 샌드박스로 격리하지 않으며 스킬의 내용은 그대로 AI 코딩 도구에 전달됩니다.diff --git a/apps/docs/content/docs/tutorial.mdx b/apps/docs/content/docs/tutorial.mdxindex 73d4745936..57b87d697c 100644--- a/apps/docs/content/docs/tutorial.mdx+++ b/apps/docs/content/docs/tutorial.mdx@@ -275,9 +275,9 @@ One of these two skills is about doing the work, the other about reporting it:- **tdd**, attached to Engineer, is an engineering method: write a failing test first, then the implementation that makes exactly that test pass;- **i-have-adhd**, attached to Lead, is a reporting style: the first line is always an actionable next step, multi-step items are numbered, and progress stays visible. Everything the leader produces is a report addressed to you, so this skill decides what you end up reading.-A team's way of working settles into skills, and a new agent inherits it by attaching one. Import is not the only source: **New skill** offers three routes — create manually, import from URL, and copy from a local runtime — not covered in detail here; see [Skills](/skills):+A team's way of working settles into skills, and a new agent inherits it by attaching one. Import is not the only source: **New skill** offers four routes — create manually, import from a local folder, import from URL, and copy from a local runtime — not covered in detail here; see [Skills](/skills):-+Read the files of a third-party skill before importing it: Multica does not sandbox them, and a skill's content is handed to the AI coding tool as-is.diff --git a/apps/docs/content/docs/tutorial.zh.mdx b/apps/docs/content/docs/tutorial.zh.mdxindex 2c2129cd03..a8a45253c9 100644--- a/apps/docs/content/docs/tutorial.zh.mdx+++ b/apps/docs/content/docs/tutorial.zh.mdx@@ -275,9 +275,9 @@ Skill 是给智能体的知识包:一个 `SKILL.md` 加上可选的支持文- **tdd** 挂给 Engineer,是工程方法:先写失败的测试,再写恰好让它通过的实现;- **i-have-adhd** 挂给 Lead,是汇报风格:第一行永远是可执行的下一步,多步骤编号,进度可见。队长的产出全是发给你的汇报,这个 skill 决定你读到的样子。-团队的工作方式沉淀成 skill,新智能体挂上就能继承。导入也不是唯一来源,**新建 skill** 提供三种方式——手动新建、从 URL 导入、从本机运行时复制——这里不展开,见 [Skills 文档](/skills):+团队的工作方式沉淀成 skill,新智能体挂上就能继承。导入也不是唯一来源,**新建 skill** 提供四种方式——手动新建、从本地导入、从 URL 导入、从本机运行时复制——这里不展开,见 [Skills 文档](/skills):-+导入第三方 skill 前,先读一遍它的文件:Multica 不做沙盒隔离,skill 的内容会原样交给 AI 编程工具。diff --git a/apps/docs/public/images/docs/tutorial-skill-new-modal.webp b/apps/docs/public/images/docs/tutorial-skill-new-modal.webpindex 6f068c2cf8..c617eb60de 100644Binary files a/apps/docs/public/images/docs/tutorial-skill-new-modal.webp and b/apps/docs/public/images/docs/tutorial-skill-new-modal.webp differdiff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex e3c9894507..475251db8b 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -2495,6 +2495,101 @@ describe("ApiClient workspace MCP servers", () => {});});+describe("importSkillArchive", () => {+ it("POSTs multipart form data without a JSON content-type", async () => {+ const skill = {+ id: "skill-1",+ workspace_id: "ws-1",+ name: "review-helper",+ description: "Reviews code",+ content: "# Review",+ config: {},+ files: [],+ created_by: "user-1",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ status: "created", skill }), {+ status: 201,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const file = new File(["pk"], "review-helper.skill", { type: "application/zip" });+ const result = await new ApiClient("https://api.example.test").importSkillArchive(+ file,+ "fail",+ );++ expect(result.id).toBe("skill-1");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe("https://api.example.test/api/skills/import");+ expect(init?.method).toBe("POST");+ const headers = init?.headers as Record<string, string>;+ expect(headers["Content-Type"]).toBeUndefined();+ const body = init?.body as FormData;+ expect(body).toBeInstanceOf(FormData);+ expect(body.get("on_conflict")).toBe("fail");+ const uploaded = body.get("file");+ expect(uploaded).toBeInstanceOf(File);+ expect((uploaded as File).name).toBe("review-helper.skill");+ });++ it("falls back to Import failed when the archive envelope is malformed", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ not_a_status: true, skill: 42 }), {+ status: 201,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const file = new File(["pk"], "review-helper.skill");+ await expect(+ new ApiClient("https://api.example.test").importSkillArchive(file),+ ).rejects.toThrow(/import failed/i);+ });++ it("keeps the server reason for a status this client does not know", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({ status: "quarantined", reason: "pending review" }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const file = new File(["pk"], "review-helper.skill");+ await expect(+ new ApiClient("https://api.example.test").importSkillArchive(file),+ ).rejects.toThrow("pending review");+ });++ it("throws the structured reason on a name conflict", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ status: "conflict",+ reason: "a skill with this name already exists",+ }),+ { status: 409, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const file = new File(["pk"], "review-helper.skill");+ await expect(+ new ApiClient("https://api.example.test").importSkillArchive(file),+ ).rejects.toMatchObject({+ message: "a skill with this name already exists",+ status: 409,+ });+ });+});+describe("clientErrorMessage", () => {it("returns a 4xx message, which handlers write for the user", () => {expect(clientErrorMessage(new ApiError("autopilot is not active", 400, "Bad Request")))diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex d2ef7c8f4e..62b78d319c 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -414,6 +414,8 @@ import {MALFORMED_RUNTIME_MODEL_LIST_REQUEST,SkillSchema,EMPTY_SKILL,+ SkillImportResultSchema,+ EMPTY_SKILL_IMPORT_RESULT,IssueViewSchema,IssueViewListSchema,IssueViewPreferenceSchema,@@ -580,6 +582,37 @@ export class PreviewUnsupportedError extends Error {}}+function remapSkillImportError(err: unknown): unknown {+ if (!(err instanceof ApiError) || !err.body || typeof err.body !== "object") {+ return err;+ }+ const body = err.body as { reason?: unknown; error?: unknown };+ const reason = typeof body.reason === "string" && body.reason ? body.reason : "";+ const error = typeof body.error === "string" && body.error ? body.error : "";+ const message = reason || error;+ if (!message || message === err.message) return err;+ return new ApiError(message, err.status, err.statusText, err.body);+}++function skillFromImportResult(raw: unknown, endpoint: string): Skill {+ const result = parseWithFallback(+ raw,+ SkillImportResultSchema,+ EMPTY_SKILL_IMPORT_RESULT,+ { endpoint },+ );+ if (+ (result.status === "created" || result.status === "updated") &&+ result.skill+ ) {+ const skill = parseWithFallback(result.skill, SkillSchema, EMPTY_SKILL, {+ endpoint,+ });+ if (skill.id) return skill;+ }+ throw new Error(result.reason || "Import failed");+}+/*** Advertised in X-Client-Capabilities so the server knows this client can* recover a cancelled prompt from the durable draft-restore row (#5219).@@ -3009,6 +3042,36 @@ export class ApiClient {});}+ /**+ * Imports a skill from a local .skill / .zip archive. Not routed through+ * `this.fetch`: the browser has to set the multipart boundary itself.+ *+ * The archive path always returns a structured `{ status, skill, reason }`+ * body. Created/updated responses yield the skill; anything else throws+ * with the server's reason (or `error`) so the dialog can show it.+ */+ async importSkillArchive(+ file: File,+ onConflict?: "fail" | "overwrite" | "rename" | "skip",+ ): Promise<Skill> {+ const formData = new FormData();+ formData.append("file", file, file.name || "skill.zip");+ if (onConflict) formData.append("on_conflict", onConflict);++ let res: Response;+ try {+ res = await this.fetchRaw("/api/skills/import", {+ method: "POST",+ body: formData,+ });+ } catch (err) {+ throw remapSkillImportError(err);+ }++ const raw = (await res.json()) as unknown;+ return skillFromImportResult(raw, "POST /api/skills/import");+ }+// Re-downloads the skill from its stored config.origin source, replacing// name/description/content/files in place while preserving the skill id and// its agent bindings.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 80c6ae3578..ac720a1530 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -79,6 +79,7 @@ import type {ShareLink,ShareLinkInfo,Skill,+ SkillImportResult,Squad,TimelineEntry,User,@@ -3118,6 +3119,35 @@ export const EMPTY_SKILL: Skill = {files: [],};+export const SkillImportExistingSkillSchema = z.object({+ id: z.string(),+ name: z.string(),+ created_by: z.string().optional(),+ can_overwrite: z.boolean().optional(),+}).loose();++/**+ * Envelope of POST /api/skills/import.+ *+ * `status` stays a plain string (not an enum) so a status added by a newer+ * backend still parses and its `reason` survives to the user. `z.enum` here+ * would fail the whole envelope on an unknown value, drop the server's reason+ * and leave only a generic "Import failed" — the server field is a bare+ * `string`, so it is free to grow. `skillFromImportResult` has the default+ * branch: anything outside created/updated is treated as a failure.+ */+export const SkillImportResultSchema = z.object({+ status: z.string().default("failed"),+ reason: z.string().optional().default(""),+ skill: SkillSchema.optional(),+ existing_skill: SkillImportExistingSkillSchema.optional(),+}).loose();++export const EMPTY_SKILL_IMPORT_RESULT: SkillImportResult = {+ status: "failed",+ reason: "",+};+/*** Read shape of one workspace MCP server.*diff --git a/packages/core/package.json b/packages/core/package.jsonindex 26e978a992..0ea7437232 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -156,6 +156,7 @@"./i18n/browser": "./i18n/browser.ts","./skills": "./skills/index.ts","./skills/frontmatter": "./skills/frontmatter.ts",+ "./skills/pack-archive": "./skills/pack-archive.ts","./skills/stores": "./skills/stores/index.ts","./autopilots/stores": "./autopilots/stores/index.ts"},diff --git a/packages/core/skills/index.ts b/packages/core/skills/index.tsindex 9340abdbde..c13cbb7bfb 100644--- a/packages/core/skills/index.ts+++ b/packages/core/skills/index.ts@@ -1 +1,2 @@export * from "./frontmatter";+export * from "./pack-archive";diff --git a/packages/core/skills/pack-archive.test.ts b/packages/core/skills/pack-archive.test.tsnew file mode 100644index 0000000000..d9579ae937--- /dev/null+++ b/packages/core/skills/pack-archive.test.ts@@ -0,0 +1,234 @@+import { describe, expect, it } from "vitest";+import {+ MAX_SKILL_FILE_BYTES,+ isIgnoredArchiveEntry,+ isSkillArchiveFilename,+ packStoreZip,+ prepareSkillArchiveFromEntries,+ prepareSkillArchiveFromPickerFiles,+ wrapExistingSkillArchive,+} from "./pack-archive";++const SKILL_MD = `---+name: review-helper+description: Reviews code changes+---++# Review Helper++Do the review.+`;++function bytes(s: string): Uint8Array {+ return new TextEncoder().encode(s);+}++/** Minimal STORE-zip reader for round-trip assertions. */+function unzipStore(data: Uint8Array): Map<string, Uint8Array> {+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);+ const out = new Map<string, Uint8Array>();+ let offset = 0;+ while (offset + 4 <= data.length) {+ const sig = view.getUint32(offset, true);+ if (sig !== 0x04034b50) break;+ const nameLen = view.getUint16(offset + 26, true);+ const extraLen = view.getUint16(offset + 28, true);+ const size = view.getUint32(offset + 22, true);+ const name = new TextDecoder().decode(+ data.subarray(offset + 30, offset + 30 + nameLen),+ );+ const start = offset + 30 + nameLen + extraLen;+ out.set(name, data.subarray(start, start + size));+ offset = start + size;+ }+ return out;+}++describe("prepareSkillArchiveFromEntries", () => {+ it("packs a nested wrapper directory", async () => {+ const prepared = prepareSkillArchiveFromEntries([+ { relativePath: "review-helper/SKILL.md", data: bytes(SKILL_MD) },+ { relativePath: "review-helper/scripts/run.sh", data: bytes("echo hi") },+ { relativePath: "review-helper/.DS_Store", data: bytes("junk") },+ ]);+ expect(prepared.ok).toBe(true);+ if (!prepared.ok) return;+ expect(prepared.preview.skillName).toBe("review-helper");+ expect(prepared.preview.description).toBe("Reviews code changes");+ expect(prepared.preview.fileCount).toBe(2);+ expect(prepared.preview.source).toBe("folder");+ expect(prepared.file.name).toBe("review-helper.skill");++ const zip = new Uint8Array(await prepared.file.arrayBuffer());+ const files = unzipStore(zip);+ expect([...files.keys()].sort()).toEqual([+ "review-helper/SKILL.md",+ "review-helper/scripts/run.sh",+ ]);+ expect(new TextDecoder().decode(files.get("review-helper/scripts/run.sh"))).toBe(+ "echo hi",+ );+ });++ it("packs a root-level SKILL.md", () => {+ const prepared = prepareSkillArchiveFromEntries([+ { relativePath: "SKILL.md", data: bytes(SKILL_MD) },+ { relativePath: "references/doc.md", data: bytes("doc") },+ ]);+ expect(prepared.ok).toBe(true);+ if (!prepared.ok) return;+ expect(prepared.preview.skillName).toBe("review-helper");+ expect(prepared.preview.fileCount).toBe(2);+ });++ it("uses the wrapper directory name when frontmatter has no name", () => {+ const prepared = prepareSkillArchiveFromEntries([+ {+ relativePath: "my-skill/SKILL.md",+ data: bytes("# Untitled\n"),+ },+ ]);+ expect(prepared.ok).toBe(true);+ if (!prepared.ok) return;+ expect(prepared.preview.skillName).toBe("my-skill");+ });++ it("rejects a folder without SKILL.md", () => {+ const prepared = prepareSkillArchiveFromEntries([+ { relativePath: "notes/readme.md", data: bytes("hi") },+ ]);+ expect(prepared).toEqual({ ok: false, error: "missing_skill_md" });+ });++ it("rejects an empty file list", () => {+ expect(prepareSkillArchiveFromEntries([])).toEqual({+ ok: false,+ error: "empty",+ });+ });++ it("skips binary supporting files instead of failing the import", () => {+ const prepared = prepareSkillArchiveFromEntries([+ { relativePath: "skill/SKILL.md", data: bytes(SKILL_MD) },+ { relativePath: "skill/icon.png", data: new Uint8Array([0x89, 0x50, 0x4e, 0x47]) },+ ]);+ expect(prepared.ok).toBe(true);+ if (!prepared.ok) return;+ expect(prepared.preview.fileCount).toBe(1);+ });+});++describe("wrapExistingSkillArchive", () => {+ it("keeps a .skill file as-is", () => {+ const payload = bytes("pk");+ const copy = new Uint8Array(payload.byteLength);+ copy.set(payload);+ const file = new File([copy.buffer], "review-helper.skill", {+ type: "application/zip",+ });+ const prepared = wrapExistingSkillArchive(file);+ expect(prepared.ok).toBe(true);+ if (!prepared.ok) return;+ expect(prepared.file).toBe(file);+ expect(prepared.preview.skillName).toBe("review-helper");+ expect(prepared.preview.source).toBe("archive");+ expect(prepared.preview.fileCount).toBeNull();+ });+});++describe("isSkillArchiveFilename", () => {+ it("accepts .skill and .zip", () => {+ expect(isSkillArchiveFilename("foo.skill")).toBe(true);+ expect(isSkillArchiveFilename("Foo.ZIP")).toBe(true);+ expect(isSkillArchiveFilename("SKILL.md")).toBe(false);+ });+});++describe("isIgnoredArchiveEntry", () => {+ it("drops editor/OS noise and license files", () => {+ expect(isIgnoredArchiveEntry("skill/.DS_Store")).toBe(true);+ expect(isIgnoredArchiveEntry("__MACOSX/foo")).toBe(true);+ expect(isIgnoredArchiveEntry("skill/LICENSE")).toBe(true);+ expect(isIgnoredArchiveEntry("skill/scripts/run.sh")).toBe(false);+ });+});++function fileWithPath(+ name: string,+ relativePath: string,+ content: Uint8Array,+ opts?: { size?: number; arrayBuffer?: () => Promise<ArrayBuffer> },+): File {+ const copy = new Uint8Array(content.byteLength);+ copy.set(content);+ const file = new File([copy.buffer], name);+ Object.defineProperty(file, "webkitRelativePath", { value: relativePath });+ if (opts?.size != null) {+ Object.defineProperty(file, "size", { value: opts.size });+ }+ if (opts?.arrayBuffer) {+ Object.defineProperty(file, "arrayBuffer", { value: opts.arrayBuffer });+ }+ return file;+}++describe("prepareSkillArchiveFromPickerFiles", () => {+ it("does not call arrayBuffer for ignored or oversized entries", async () => {+ const skill = fileWithPath("SKILL.md", "skill/SKILL.md", bytes(SKILL_MD));+ const ignored = fileWithPath(+ ".DS_Store",+ "skill/.DS_Store",+ new Uint8Array([1]),+ {+ arrayBuffer: async () => {+ throw new Error("should not read ignored");+ },+ },+ );+ const oversized = fileWithPath(+ "big.md",+ "skill/big.md",+ new Uint8Array(0),+ {+ size: MAX_SKILL_FILE_BYTES + 1,+ arrayBuffer: async () => {+ throw new Error("should not read oversized");+ },+ },+ );+ const binary = fileWithPath(+ "icon.png",+ "skill/icon.png",+ new Uint8Array([0x89, 0x50]),+ {+ arrayBuffer: async () => {+ throw new Error("should not read binary");+ },+ },+ );++ const prepared = await prepareSkillArchiveFromPickerFiles([+ skill,+ ignored,+ oversized,+ binary,+ ]);+ expect(prepared.ok).toBe(true);+ if (!prepared.ok) return;+ expect(prepared.preview.fileCount).toBe(1);+ });+});++describe("packStoreZip", () => {+ it("round-trips file names and contents", () => {+ const zip = packStoreZip([+ { path: "SKILL.md", data: bytes("hello") },+ { path: "scripts/run.sh", data: bytes("echo hi") },+ ]);+ expect(zip[0]).toBe(0x50);+ expect(zip[1]).toBe(0x4b);+ const files = unzipStore(zip);+ expect(new TextDecoder().decode(files.get("SKILL.md"))).toBe("hello");+ expect(new TextDecoder().decode(files.get("scripts/run.sh"))).toBe("echo hi");+ });+});diff --git a/packages/core/skills/pack-archive.ts b/packages/core/skills/pack-archive.tsnew file mode 100644index 0000000000..abaa79e6c5--- /dev/null+++ b/packages/core/skills/pack-archive.ts@@ -0,0 +1,451 @@+import { parseFrontmatter } from "./frontmatter";++/** Mirrors server/internal/handler maxImportFileSize. */+export const MAX_SKILL_FILE_BYTES = 1 << 20; // 1 MiB+/** Mirrors server/internal/handler maxImportTotalSize (supporting files). */+export const MAX_SKILL_BUNDLE_BYTES = 8 << 20; // 8 MiB+/** Mirrors server/internal/handler maxImportFileCount. */+export const MAX_SKILL_FILE_COUNT = 256;+/** Mirrors server/internal/handler maxImportArchiveUploadSize. */+export const MAX_SKILL_ARCHIVE_BYTES = 16 << 20; // 16 MiB++const SKILL_MD = "skill.md";++export type SkillArchiveEntry = {+ relativePath: string;+ data: Uint8Array;+};++export type PreparedSkillArchiveError =+ | "missing_skill_md"+ | "empty"+ | "too_large"+ | "too_many_files";++export type PreparedSkillArchive =+ | {+ ok: true;+ file: File;+ preview: {+ displayName: string;+ skillName: string;+ description: string;+ fileCount: number | null;+ source: "folder" | "archive";+ };+ }+ | { ok: false; error: PreparedSkillArchiveError };++export function isSkillArchiveFilename(name: string): boolean {+ const lower = name.toLowerCase();+ return lower.endsWith(".skill") || lower.endsWith(".zip");+}++export function wrapExistingSkillArchive(file: File): PreparedSkillArchive {+ if (file.size > MAX_SKILL_ARCHIVE_BYTES) {+ return { ok: false, error: "too_large" };+ }+ const base = file.name.replace(/\\/g, "/").split("/").pop() ?? file.name;+ const skillName = stripArchiveExtension(base) || "skill";+ return {+ ok: true,+ file,+ preview: {+ displayName: base,+ skillName,+ description: "",+ fileCount: null,+ source: "archive",+ },+ };+}++export function prepareSkillArchiveFromEntries(+ entries: SkillArchiveEntry[],+): PreparedSkillArchive {+ const data = new Map<string, Uint8Array>();+ const members: SkillArchiveMemberMeta[] = [];+ for (const entry of entries) {+ const path = normalizeRelPath(entry.relativePath);+ members.push({ path, size: entry.data.byteLength });+ if (!data.has(path)) data.set(path, entry.data);+ }++ const picked = selectSkillArchiveMembers(members);+ if (!picked.ok) return picked;+ return buildPreparedArchive(picked, (path) => data.get(path) ?? EMPTY_BYTES);+}++const EMPTY_BYTES = new Uint8Array();++/**+ * Shared tail of both prepare paths: zip the members `selectSkillArchiveMembers`+ * already approved and derive the preview. `dataFor` supplies the bytes of a+ * selected path — the entries path holds them in memory, the picker path reads+ * them only once selection is done.+ */+function buildPreparedArchive(+ selection: SkillArchiveSelection,+ dataFor: (path: string) => Uint8Array,+): PreparedSkillArchive {+ const packed = selection.selected.map((member) => ({+ path: member.path,+ data: dataFor(member.path),+ }));++ const content = new TextDecoder("utf-8").decode(dataFor(selection.skillMdPath));+ const { frontmatter } = parseFrontmatter(content);+ const wrapperName = wrapperNameFromPrefix(selection.prefix);+ const skillName = frontmatter?.name?.trim() || wrapperName || "skill";+ const description = frontmatter?.description?.trim() ?? "";+ const zip = packStoreZip(packed);+ if (zip.byteLength > MAX_SKILL_ARCHIVE_BYTES) {+ return { ok: false, error: "too_large" };+ }++ const filename = `${sanitizeArchiveBasename(skillName)}.skill`;+ const file = new File([uint8ToArrayBuffer(zip)], filename, {+ type: "application/zip",+ });+ return {+ ok: true,+ file,+ preview: {+ displayName: wrapperName || skillName,+ skillName,+ description,+ fileCount: packed.length,+ source: "folder",+ },+ };+}++export type SkillArchiveMemberMeta = {+ path: string;+ size: number;+};++export type SkillArchiveSelection = {+ /** Members to pack, in input order, with normalized paths. */+ selected: SkillArchiveMemberMeta[];+ /** Normalized path of the SKILL.md that rooted the skill. */+ skillMdPath: string;+ /** Directory prefix of the skill root; "" when SKILL.md sits at the root. */+ prefix: string;+};++/**+ * The single place the ignore rules and the size / count limits are applied.+ * Decides membership from path + size alone — no I/O — so the picker path can+ * reject a directory before reading it, and both prepare paths stay in step by+ * construction rather than by keeping two copies of these rules in agreement.+ * Mirrors the server importer.+ */+export function selectSkillArchiveMembers(+ files: SkillArchiveMemberMeta[],+):+ | ({ ok: true } & SkillArchiveSelection)+ | { ok: false; error: PreparedSkillArchiveError } {+ if (files.length === 0) return { ok: false, error: "empty" };++ const normalized: SkillArchiveMemberMeta[] = [];+ for (const file of files) {+ const path = normalizeRelPath(file.path);+ if (!path || isIgnoredArchiveEntry(path)) continue;+ normalized.push({ path, size: file.size });+ }+ if (normalized.length === 0) return { ok: false, error: "empty" };++ let skillMd: (SkillArchiveMemberMeta & { prefix: string }) | null = null;+ for (const file of normalized) {+ if (!isSkillMdPath(file.path)) continue;+ const prefix = archiveEntryPrefix(file.path);+ if (!skillMd || prefix.length < skillMd.prefix.length) {+ skillMd = { ...file, prefix };+ }+ }+ if (!skillMd) return { ok: false, error: "missing_skill_md" };+ if (skillMd.size > MAX_SKILL_FILE_BYTES) {+ return { ok: false, error: "too_large" };+ }++ const selected: SkillArchiveMemberMeta[] = [];+ let supportingCount = 0;+ let supportingBytes = 0;+ for (const file of normalized) {+ if (skillMd.prefix && !file.path.startsWith(skillMd.prefix)) continue;+ const rel = skillMd.prefix ? file.path.slice(skillMd.prefix.length) : file.path;+ if (!rel || rel.endsWith("/")) continue;+ if (isSkillMdPath(rel)) {+ selected.push(file);+ continue;+ }+ if (isLikelyBinaryFilePath(rel)) continue;+ if (file.size > MAX_SKILL_FILE_BYTES) continue;+ supportingCount += 1;+ if (supportingCount > MAX_SKILL_FILE_COUNT) {+ return { ok: false, error: "too_many_files" };+ }+ supportingBytes += file.size;+ if (supportingBytes > MAX_SKILL_BUNDLE_BYTES) {+ return { ok: false, error: "too_large" };+ }+ selected.push(file);+ }+ return {+ ok: true,+ selected,+ skillMdPath: skillMd.path,+ prefix: skillMd.prefix,+ };+}++function pickerRelativePath(file: File): string {+ const rel =+ typeof file.webkitRelativePath === "string" && file.webkitRelativePath+ ? file.webkitRelativePath+ : file.name;+ return normalizeRelPath(rel);+}++/**+ * Pack a directory picker result. Ignored, binary, oversized and out-of-root+ * files are dropped from path + `File.size` before any `arrayBuffer()` call.+ */+export async function prepareSkillArchiveFromPickerFiles(+ files: File[],+): Promise<PreparedSkillArchive> {+ const sources = new Map<string, File>();+ const members: SkillArchiveMemberMeta[] = [];+ for (const file of files) {+ const path = pickerRelativePath(file);+ members.push({ path, size: file.size });+ if (!sources.has(path)) sources.set(path, file);+ }++ const picked = selectSkillArchiveMembers(members);+ if (!picked.ok) return picked;++ const data = new Map<string, Uint8Array>();+ for (const member of picked.selected) {+ if (data.has(member.path)) continue;+ const source = sources.get(member.path);+ data.set(+ member.path,+ source ? new Uint8Array(await source.arrayBuffer()) : EMPTY_BYTES,+ );+ }+ return buildPreparedArchive(picked, (path) => data.get(path) ?? EMPTY_BYTES);+}++// --- zip (STORE / uncompressed) -------------------------------------------++const CRC32_TABLE = (() => {+ const table = new Uint32Array(256);+ for (let i = 0; i < 256; i++) {+ let c = i;+ for (let j = 0; j < 8; j++) {+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ }+ table[i] = c >>> 0;+ }+ return table;+})();++function crc32(data: Uint8Array): number {+ let c = 0xffffffff;+ for (let i = 0; i < data.length; i++) {+ c = CRC32_TABLE[(c ^ data[i]!) & 0xff]! ^ (c >>> 8);+ }+ return (c ^ 0xffffffff) >>> 0;+}++function utf8(s: string): Uint8Array {+ return new TextEncoder().encode(s);+}++function uint8ToArrayBuffer(data: Uint8Array): ArrayBuffer {+ const copy = new Uint8Array(data.byteLength);+ copy.set(data);+ return copy.buffer;+}++/**+ * Builds an uncompressed zip. The server parser (`parseSkillArchive`) accepts+ * STORE archives; skipping compression keeps this helper dependency-free.+ */+export function packStoreZip(entries: { path: string; data: Uint8Array }[]): Uint8Array {+ const files = entries.map((e) => ({+ name: utf8(e.path.replace(/\\/g, "/")),+ data: e.data,+ crc: crc32(e.data),+ }));++ let localSize = 0;+ let centralSize = 0;+ for (const f of files) {+ localSize += 30 + f.name.length + f.data.length;+ centralSize += 46 + f.name.length;+ }+ const out = new Uint8Array(localSize + centralSize + 22);+ const view = new DataView(out.buffer);+ let offset = 0;+ const localOffsets: number[] = [];++ for (const f of files) {+ localOffsets.push(offset);+ view.setUint32(offset, 0x04034b50, true);+ view.setUint16(offset + 4, 20, true);+ view.setUint16(offset + 6, 0x0800, true); // UTF-8 names+ view.setUint16(offset + 8, 0, true); // STORE+ view.setUint16(offset + 10, 0, true);+ view.setUint16(offset + 12, 0, true);+ view.setUint32(offset + 14, f.crc, true);+ view.setUint32(offset + 18, f.data.length, true);+ view.setUint32(offset + 22, f.data.length, true);+ view.setUint16(offset + 26, f.name.length, true);+ view.setUint16(offset + 28, 0, true);+ out.set(f.name, offset + 30);+ out.set(f.data, offset + 30 + f.name.length);+ offset += 30 + f.name.length + f.data.length;+ }++ const centralStart = offset;+ for (let i = 0; i < files.length; i++) {+ const f = files[i]!;+ view.setUint32(offset, 0x02014b50, true);+ view.setUint16(offset + 4, 20, true);+ view.setUint16(offset + 6, 20, true);+ view.setUint16(offset + 8, 0x0800, true);+ view.setUint16(offset + 10, 0, true);+ view.setUint16(offset + 12, 0, true);+ view.setUint16(offset + 14, 0, true);+ view.setUint32(offset + 16, f.crc, true);+ view.setUint32(offset + 20, f.data.length, true);+ view.setUint32(offset + 24, f.data.length, true);+ view.setUint16(offset + 28, f.name.length, true);+ view.setUint16(offset + 30, 0, true);+ view.setUint16(offset + 32, 0, true);+ view.setUint16(offset + 34, 0, true);+ view.setUint16(offset + 36, 0, true);+ view.setUint32(offset + 38, 0, true);+ view.setUint32(offset + 42, localOffsets[i]!, true);+ out.set(f.name, offset + 46);+ offset += 46 + f.name.length;+ }++ view.setUint32(offset, 0x06054b50, true);+ view.setUint16(offset + 4, 0, true);+ view.setUint16(offset + 6, 0, true);+ view.setUint16(offset + 8, files.length, true);+ view.setUint16(offset + 10, files.length, true);+ view.setUint32(offset + 12, offset - centralStart, true);+ view.setUint32(offset + 16, centralStart, true);+ view.setUint16(offset + 20, 0, true);+ return out;+}++// --- path helpers (mirror skill_import_archive.go) ------------------------++function normalizeRelPath(p: string): string {+ return p.replace(/\\/g, "/").replace(/^\/+/, "");+}++function isSkillMdPath(path: string): boolean {+ const base = path.split("/").pop() ?? "";+ return base.toLowerCase() === SKILL_MD;+}++function archiveEntryPrefix(cleanName: string): string {+ const i = cleanName.lastIndexOf("/");+ if (i <= 0) return "";+ return cleanName.slice(0, i + 1);+}++function wrapperNameFromPrefix(prefix: string): string {+ const trimmed = prefix.replace(/\/+$/, "");+ if (!trimmed) return "";+ const base = trimmed.split("/").pop() ?? "";+ if (base === "." || base === "..") return "";+ return base;+}++export function isIgnoredArchiveEntry(rel: string): boolean {+ const segments = rel.split("/");+ for (const seg of segments) {+ if (seg === "" || seg === "__MACOSX" || seg.startsWith(".")) return true;+ }+ const base = (segments[segments.length - 1] ?? "").toLowerCase();+ return base === "license" || base === "license.md" || base === "license.txt";+}++export function isLikelyBinaryFilePath(path: string): boolean {+ const ext = extensionOf(path);+ switch (ext) {+ case ".png":+ case ".jpg":+ case ".jpeg":+ case ".gif":+ case ".webp":+ case ".bmp":+ case ".tiff":+ case ".ico":+ case ".heic":+ case ".ttf":+ case ".otf":+ case ".woff":+ case ".woff2":+ case ".eot":+ case ".zip":+ case ".gz":+ case ".tar":+ case ".bz2":+ case ".7z":+ case ".rar":+ case ".pdf":+ case ".docx":+ case ".xlsx":+ case ".pptx":+ case ".doc":+ case ".xls":+ case ".ppt":+ case ".mp3":+ case ".mp4":+ case ".wav":+ case ".avi":+ case ".mov":+ case ".webm":+ case ".m4a":+ case ".flac":+ case ".exe":+ case ".dll":+ case ".so":+ case ".dylib":+ case ".class":+ case ".jar":+ case ".wasm":+ case ".db":+ case ".sqlite":+ case ".sqlite3":+ case ".pyc":+ return true;+ default:+ return false;+ }+}++function extensionOf(path: string): string {+ const base = path.split("/").pop() ?? path;+ const i = base.lastIndexOf(".");+ if (i <= 0) return "";+ return base.slice(i).toLowerCase();+}++function stripArchiveExtension(name: string): string {+ return name.replace(/\.(skill|zip)$/i, "");+}++function sanitizeArchiveBasename(name: string): string {+ const cleaned = name.replace(/[/\\?%*:|"<>]/g, "-").trim();+ return cleaned || "skill";+}diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 8a45294560..66c7982dc2 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -863,6 +863,19 @@ export interface CreateSkillRequest {files?: { path: string; content: string }[];}+/** Structured body of POST /api/skills/import when uploading an archive. */+export interface SkillImportResult {+ status: "created" | "updated" | "conflict" | "skipped" | "failed";+ reason?: string;+ skill?: Skill;+ existing_skill?: {+ id: string;+ name: string;+ created_by?: string;+ can_overwrite?: boolean;+ };+}+export interface UpdateSkillRequest {name?: string;description?: string;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex bab037321c..69da919ca4 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -49,6 +49,7 @@ export type {SetAgentRuntimeSkillEnabledRequest,SkillFile,CreateSkillRequest,+ SkillImportResult,UpdateSkillRequest,SetAgentSkillsRequest,RuntimeUsage,diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.jsonindex abd5612f1a..ee2b859d97 100644--- a/packages/views/locales/en/skills.json+++ b/packages/views/locales/en/skills.json@@ -25,7 +25,7 @@},"empty": {"title": "No skills yet",- "description": "Create your first skill, import one from a URL, or copy one from a connected runtime — and every agent in the workspace can use it."+ "description": "Create your first skill, import one from a URL or a local folder, or copy one from a connected runtime — and every agent in the workspace can use it."},"no_matches": {"title": "No matches",@@ -36,7 +36,7 @@},"intro_banner": {"title": "Shared with your workspace.",- "body": "Anyone can create a skill, import one from a URL, or copy one from their local runtime — and every agent can use it.",+ "body": "Anyone can create a skill, import one from a URL or a local folder, or copy one from their local runtime — and every agent can use it.","highlight": "Local runtime skills stay private until you copy one here."},"list_error": {@@ -254,6 +254,10 @@"title": "Create manually","desc": "Write a new SKILL.md from scratch."},+ "local": {+ "title": "Import from local",+ "desc": "Choose a skill folder on this computer. Files are packed and uploaded."+ },"url": {"title": "Import from URL","desc": "Fetch a published skill by URL. Files are pulled server-side."@@ -266,6 +270,8 @@"method_card": {"manual_title": "Create manually","manual_desc": "Start from a blank SKILL.md and write your own instructions.",+ "local_title": "Import from local",+ "local_desc": "Pick a folder that contains SKILL.md, or a .skill / .zip archive.","url_title": "Import from URL","url_desc": "Pull a published skill from ClawHub or Skills.sh.","runtime_title": "Copy from runtime",@@ -284,6 +290,25 @@"submitting": "Creating…","toast_created": "Skill created"},+ "local": {+ "choose_folder": "Choose folder",+ "choose_archive": "Choose .skill / .zip",+ "pick_hint": "Select a folder that contains SKILL.md, or a packaged .skill / .zip file.",+ "folder_label": "Folder",+ "archive_label": "Archive",+ "files_one": "{{count}} file",+ "files_other": "{{count}} files",+ "missing_skill_md": "This folder is not a skill — it has no SKILL.md.",+ "too_large": "This skill is too large to import.",+ "empty": "The folder is empty.",+ "too_many_files": "This skill has too many files to import.",+ "name_conflict_hint": " The imported skill's name already exists — delete the existing one before retrying.",+ "fallback_error": "Import failed",+ "cancel": "Cancel",+ "import": "Import",+ "importing": "Importing…",+ "toast_imported": "Skill imported"+ },"url": {"url_label": "Skill URL","supported_sources": "Supported sources",diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.jsonindex 6e1f7def5c..e0fada4fdd 100644--- a/packages/views/locales/ja/skills.json+++ b/packages/views/locales/ja/skills.json@@ -25,7 +25,7 @@},"empty": {"title": "まだスキルがありません",- "description": "最初のスキルを作成するか、URL からインポートするか、接続済みのランタイムからコピーしてください。ワークスペースのすべてのエージェントが使用できます。"+ "description": "最初のスキルを作成するか、URL やローカルフォルダからインポートするか、接続済みのランタイムからコピーしてください。ワークスペースのすべてのエージェントが使用できます。"},"no_matches": {"title": "一致なし",@@ -36,7 +36,7 @@},"intro_banner": {"title": "ワークスペースと共有されます。",- "body": "誰でもスキルを作成したり、URL からインポートしたり、ローカルランタイムからコピーしたりでき、すべてのエージェントが使用できます。",+ "body": "誰でもスキルを作成したり、URL やローカルフォルダからインポートしたり、ローカルランタイムからコピーしたりでき、すべてのエージェントが使用できます。","highlight": "ローカルランタイムのスキルは、ここにコピーするまで非公開のままです。"},"list_error": {@@ -239,6 +239,10 @@"title": "手動で作成","desc": "新しい SKILL.md を一から作成します。"},+ "local": {+ "title": "ローカルからインポート",+ "desc": "このコンピュータ上のスキルフォルダを選びます。ファイルはまとめてアップロードされます。"+ },"url": {"title": "URL からインポート","desc": "公開済みのスキルを URL で取得します。ファイルはサーバー側で取得されます。"@@ -251,6 +255,8 @@"method_card": {"manual_title": "手動で作成","manual_desc": "空の SKILL.md から始めて、独自の指示を記述します。",+ "local_title": "ローカルからインポート",+ "local_desc": "SKILL.md を含むフォルダ、または .skill / .zip アーカイブを選びます。","url_title": "URL からインポート","url_desc": "ClawHub または Skills.sh の公開スキルを取得します。","runtime_title": "ランタイムからコピー",@@ -269,6 +275,24 @@"submitting": "作成中…","toast_created": "スキルを作成しました"},+ "local": {+ "choose_folder": "フォルダを選択",+ "choose_archive": ".skill / .zip を選択",+ "pick_hint": "SKILL.md を含むフォルダ、またはパッケージ済みの .skill / .zip ファイルを選択してください。",+ "folder_label": "フォルダ",+ "archive_label": "アーカイブ",+ "files_other": "{{count}} 個のファイル",+ "missing_skill_md": "このフォルダはスキルではありません。SKILL.md がありません。",+ "too_large": "このスキルは大きすぎてインポートできません。",+ "empty": "フォルダが空です。",+ "too_many_files": "このスキルのファイル数が多すぎてインポートできません。",+ "name_conflict_hint": " インポートしたスキル名はすでに存在します。再試行する前に既存のものを削除してください。",+ "fallback_error": "インポートに失敗しました",+ "cancel": "キャンセル",+ "import": "インポート",+ "importing": "インポート中…",+ "toast_imported": "スキルをインポートしました"+ },"url": {"url_label": "スキル URL","supported_sources": "対応ソース",diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.jsonindex b188907afd..ec1c220e69 100644--- a/packages/views/locales/ko/skills.json+++ b/packages/views/locales/ko/skills.json@@ -25,7 +25,7 @@},"empty": {"title": "아직 스킬이 없습니다",- "description": "첫 스킬을 만들거나, URL에서 가져오거나, 연결된 런타임에서 복사하세요. 워크스페이스의 모든 에이전트가 사용할 수 있습니다."+ "description": "첫 스킬을 만들거나, URL이나 로컬 폴더에서 가져오거나, 연결된 런타임에서 복사하세요. 워크스페이스의 모든 에이전트가 사용할 수 있습니다."},"no_matches": {"title": "일치하는 결과 없음",@@ -36,7 +36,7 @@},"intro_banner": {"title": "워크스페이스와 공유됩니다.",- "body": "누구나 스킬을 만들거나 URL에서 가져오거나 로컬 런타임에서 복사할 수 있으며, 모든 에이전트가 사용할 수 있습니다.",+ "body": "누구나 스킬을 만들거나 URL이나 로컬 폴더에서 가져오거나 로컬 런타임에서 복사할 수 있으며, 모든 에이전트가 사용할 수 있습니다.","highlight": "로컬 런타임 스킬은 여기로 복사하기 전까지 비공개로 유지됩니다."},"list_error": {@@ -239,6 +239,10 @@"title": "직접 만들기","desc": "새 SKILL.md를 처음부터 작성합니다."},+ "local": {+ "title": "로컬에서 가져오기",+ "desc": "이 컴퓨터의 스킬 폴더를 선택합니다. 파일은 묶어서 업로드됩니다."+ },"url": {"title": "URL에서 가져오기","desc": "공개된 스킬을 URL로 가져옵니다. 파일은 서버에서 가져옵니다."@@ -251,6 +255,8 @@"method_card": {"manual_title": "직접 만들기","manual_desc": "빈 SKILL.md에서 시작해 직접 지침을 작성합니다.",+ "local_title": "로컬에서 가져오기",+ "local_desc": "SKILL.md가 있는 폴더, 또는 .skill / .zip 아카이브를 선택합니다.","url_title": "URL에서 가져오기","url_desc": "ClawHub 또는 Skills.sh의 공개 스킬을 가져옵니다.","runtime_title": "런타임에서 복사",@@ -269,6 +275,24 @@"submitting": "만드는 중...","toast_created": "스킬을 만들었습니다"},+ "local": {+ "choose_folder": "폴더 선택",+ "choose_archive": ".skill / .zip 선택",+ "pick_hint": "SKILL.md가 있는 폴더, 또는 패키지된 .skill / .zip 파일을 선택하세요.",+ "folder_label": "폴더",+ "archive_label": "아카이브",+ "files_other": "파일 {{count}}개",+ "missing_skill_md": "이 폴더는 스킬이 아닙니다. SKILL.md가 없습니다.",+ "too_large": "이 스킬은 너무 커서 가져올 수 없습니다.",+ "empty": "폴더가 비어 있습니다.",+ "too_many_files": "이 스킬의 파일이 너무 많아 가져올 수 없습니다.",+ "name_conflict_hint": " 가져온 스킬 이름이 이미 있습니다. 다시 시도하기 전에 기존 스킬을 삭제하세요.",+ "fallback_error": "가져오기 실패",+ "cancel": "취소",+ "import": "가져오기",+ "importing": "가져오는 중...",+ "toast_imported": "스킬을 가져왔습니다"+ },"url": {"url_label": "스킬 URL","supported_sources": "지원 출처",diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.jsonindex fa7351b8ce..2fcf31bb55 100644--- a/packages/views/locales/zh-Hans/skills.json+++ b/packages/views/locales/zh-Hans/skills.json@@ -25,7 +25,7 @@},"empty": {"title": "还没有 skill",- "description": "创建第一个 skill、从 URL 导入、或从已连接的运行时复制——之后工作区里每个智能体都能用它。"+ "description": "创建第一个 skill、从 URL 或本地文件夹导入、或从已连接的运行时复制——之后工作区里每个智能体都能用它。"},"no_matches": {"title": "无匹配",@@ -36,7 +36,7 @@},"intro_banner": {"title": "在工作区内共享。",- "body": "任何成员都可以创建 skill、从 URL 导入、或从本地运行时复制——之后所有智能体都能用它。",+ "body": "任何成员都可以创建 skill、从 URL 或本地文件夹导入、或从本地运行时复制——之后所有智能体都能用它。","highlight": "本地运行时里的 skill 在你复制过来之前是私有的。"},"list_error": {@@ -239,6 +239,10 @@"title": "手动创建","desc": "从空白 SKILL.md 开始写。"},+ "local": {+ "title": "从本地导入",+ "desc": "在这台电脑上选择一个 skill 文件夹,文件会打包后上传。"+ },"url": {"title": "从 URL 导入","desc": "通过 URL 拉取已发布的 skill,文件由服务端拉取。"@@ -251,6 +255,8 @@"method_card": {"manual_title": "手动创建","manual_desc": "从空白 SKILL.md 开始,自己写指令。",+ "local_title": "从本地导入",+ "local_desc": "选择包含 SKILL.md 的文件夹,或一个 .skill / .zip 压缩包。","url_title": "从 URL 导入","url_desc": "从 ClawHub 或 Skills.sh 拉取已发布的 skill。","runtime_title": "从运行时复制",@@ -269,6 +275,24 @@"submitting": "创建中...","toast_created": "已创建 skill"},+ "local": {+ "choose_folder": "选择文件夹",+ "choose_archive": "选择 .skill / .zip",+ "pick_hint": "选择包含 SKILL.md 的文件夹,或打包好的 .skill / .zip 文件。",+ "folder_label": "文件夹",+ "archive_label": "压缩包",+ "files_other": "{{count}} 个文件",+ "missing_skill_md": "这个文件夹不是 skill——里面没有 SKILL.md。",+ "too_large": "这个 skill 太大,无法导入。",+ "empty": "文件夹是空的。",+ "too_many_files": "这个 skill 的文件太多,无法导入。",+ "name_conflict_hint": "导入的 skill 名称已存在——请先删除已有的再重试。",+ "fallback_error": "导入失败",+ "cancel": "取消",+ "import": "导入",+ "importing": "导入中...",+ "toast_imported": "已导入 skill"+ },"url": {"url_label": "Skill URL","supported_sources": "支持的来源",diff --git a/packages/views/skills/components/create-skill-dialog.test.tsx b/packages/views/skills/components/create-skill-dialog.test.tsxnew file mode 100644index 0000000000..c6bf6f9a14--- /dev/null+++ b/packages/views/skills/components/create-skill-dialog.test.tsx@@ -0,0 +1,304 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSkills from "../../locales/en/skills.json";++const TEST_RESOURCES = {+ en: { common: enCommon, skills: enSkills },+};++const mockImportSkillArchive = vi.hoisted(() => vi.fn());+const mockPrepareFromPicker = vi.hoisted(() => vi.fn());+const mockWrap = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", () => ({+ api: {+ importSkillArchive: (...args: unknown[]) => mockImportSkillArchive(...args),+ },+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@multica/core/skills", async () => {+ const actual = await vi.importActual<+ typeof import("@multica/core/skills")+ >("@multica/core/skills");+ return {+ ...actual,+ prepareSkillArchiveFromPickerFiles: (...args: unknown[]) =>+ mockPrepareFromPicker(...args),+ wrapExistingSkillArchive: (...args: unknown[]) => mockWrap(...args),+ };+});++vi.mock("sonner", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));++import { CreateSkillDialog } from "./create-skill-dialog";++const ARCHIVE_FILE = new File(["pk"], "review-helper.skill", {+ type: "application/zip",+});++const PREPARED_OK = {+ ok: true as const,+ file: ARCHIVE_FILE,+ preview: {+ displayName: "review-helper",+ skillName: "review-helper",+ description: "Reviews code changes",+ fileCount: 2,+ source: "folder" as const,+ },+};++/**+ * Chromium's input.files is a live FileList: setting input.value = "" empties+ * it. jsdom's fireEvent `{ target: { files } }` bypasses that, so this helper+ * installs a live list to pin the snapshot-before-reset behaviour.+ */+function installLiveFileList(input: HTMLInputElement, files: File[]) {+ let current = files.slice();+ const list = () => {+ const live = Object.assign(current.slice(), {+ length: current.length,+ item: (i: number) => current[i] ?? null,+ [Symbol.iterator]: function* () {+ yield* current;+ },+ });+ return live as unknown as FileList;+ };+ Object.defineProperty(input, "files", {+ configurable: true,+ get: list,+ });+ Object.defineProperty(input, "value", {+ configurable: true,+ get: () => (current[0] ? `C:\\fakepath\\${current[0].name}` : ""),+ set: (next: string) => {+ if (next === "") current = [];+ },+ });+}++function renderDialog(onCreated = vi.fn(), onClose = vi.fn()) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return {+ onCreated,+ onClose,+ ...render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={queryClient}>+ <CreateSkillDialog onClose={onClose} onCreated={onCreated} />+ </QueryClientProvider>+ </I18nProvider>,+ ),+ };+}++describe("CreateSkillDialog local import", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockPrepareFromPicker.mockResolvedValue(PREPARED_OK);+ mockWrap.mockReturnValue({+ ...PREPARED_OK,+ preview: { ...PREPARED_OK.preview, source: "archive", fileCount: null },+ });+ mockImportSkillArchive.mockResolvedValue({+ id: "skill-1",+ workspace_id: "ws-1",+ name: "review-helper",+ description: "Reviews code changes",+ content: "# Review Helper",+ config: {},+ files: [],+ created_by: "user-1",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ });+ });++ it("lists Import from local as the second method", () => {+ renderDialog();+ const cards = screen.getAllByRole("button");+ const titles = cards+ .map((el) => el.textContent ?? "")+ .filter((text) =>+ /Create manually|Import from local|Import from URL|Copy from runtime/.test(+ text,+ ),+ );+ expect(titles[0]).toContain("Create manually");+ expect(titles[1]).toContain("Import from local");+ expect(titles[2]).toContain("Import from URL");+ expect(titles[3]).toContain("Copy from runtime");+ });++ it("opens the folder picker when Import from local is clicked", () => {+ renderDialog();+ const click = vi.fn();+ const input = document.querySelector(+ 'input[type="file"][multiple]',+ ) as HTMLInputElement | null;+ expect(input).not.toBeNull();+ if (!input) return;+ input.click = click;+ fireEvent.click(screen.getByRole("button", { name: /Import from local/i }));+ expect(click).toHaveBeenCalled();+ });++ it("does not import when the folder has no SKILL.md", async () => {+ mockPrepareFromPicker.mockResolvedValue({ ok: false, error: "missing_skill_md" });+ renderDialog();++ const input = document.querySelector(+ 'input[type="file"][multiple]',+ ) as HTMLInputElement;+ const file = new File(["# no"], "readme.md", { type: "text/markdown" });+ fireEvent.change(input, { target: { files: [file] } });++ expect(+ await screen.findByText(/This folder is not a skill/i),+ ).toBeInTheDocument();+ expect(mockImportSkillArchive).not.toHaveBeenCalled();+ });++ it("snapshots folder files before resetting the live FileList", async () => {+ mockPrepareFromPicker.mockImplementation(async (list: File[]) => {+ if (list.length === 0) {+ throw new Error("live FileList was emptied before snapshot");+ }+ return PREPARED_OK;+ });+ renderDialog();++ const input = document.querySelector(+ 'input[type="file"][multiple]',+ ) as HTMLInputElement;+ const file = new File(["---\nname: review-helper\n---\n"], "SKILL.md");+ installLiveFileList(input, [file]);+ fireEvent.change(input);++ expect((await screen.findAllByText("review-helper")).length).toBeGreaterThan(0);+ expect(mockPrepareFromPicker).toHaveBeenCalled();+ const passed = mockPrepareFromPicker.mock.calls[0]![0] as File[];+ expect(Array.from(passed)).toHaveLength(1);+ });++ it("imports a packed folder and closes", async () => {+ const { onCreated, onClose } = renderDialog();++ const input = document.querySelector(+ 'input[type="file"][multiple]',+ ) as HTMLInputElement;+ const file = new File(["---\nname: review-helper\n---\n"], "SKILL.md");+ fireEvent.change(input, { target: { files: [file] } });++ expect((await screen.findAllByText("review-helper")).length).toBeGreaterThan(0);+ fireEvent.click(screen.getByRole("button", { name: /^Import$/i }));++ await waitFor(() => {+ expect(mockImportSkillArchive).toHaveBeenCalledWith(ARCHIVE_FILE, "fail");+ });+ await waitFor(() => {+ expect(onCreated).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });+ });++ it("uploads a chosen .skill archive without re-packing", async () => {+ renderDialog();+ fireEvent.click(screen.getByRole("button", { name: /Import from local/i }));++ // Stay on chooser until a file is picked; open the local panel via archive.+ const archiveInput = document.querySelector(+ 'input[type="file"][accept]',+ ) as HTMLInputElement;+ fireEvent.change(archiveInput, { target: { files: [ARCHIVE_FILE] } });++ expect((await screen.findAllByText("review-helper")).length).toBeGreaterThan(0);+ expect(mockWrap).toHaveBeenCalledWith(ARCHIVE_FILE);+ fireEvent.click(screen.getByRole("button", { name: /^Import$/i }));+ await waitFor(() => {+ expect(mockImportSkillArchive).toHaveBeenCalled();+ });+ expect(mockPrepareFromPicker).not.toHaveBeenCalled();+ });++ it("ignores a slower earlier folder selection", async () => {+ type Deferred<T> = { promise: Promise<T>; resolve: (value: T) => void };+ const deferred = <T,>(): Deferred<T> => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+ };+ const first = deferred<typeof PREPARED_OK>();+ const second = deferred<typeof PREPARED_OK>();+ mockPrepareFromPicker+ .mockReturnValueOnce(first.promise)+ .mockReturnValueOnce(second.promise);++ renderDialog();+ const input = document.querySelector(+ 'input[type="file"][multiple]',+ ) as HTMLInputElement;+ fireEvent.change(input, { target: { files: [new File(["a"], "SKILL.md")] } });+ fireEvent.change(input, { target: { files: [new File(["b"], "SKILL.md")] } });++ const preparedB = {+ ...PREPARED_OK,+ preview: { ...PREPARED_OK.preview, skillName: "skill-b", displayName: "skill-b" },+ };+ const preparedA = {+ ...PREPARED_OK,+ preview: { ...PREPARED_OK.preview, skillName: "skill-a", displayName: "skill-a" },+ };+ second.resolve(preparedB);+ expect((await screen.findAllByText("skill-b")).length).toBeGreaterThan(0);+ first.resolve(preparedA);+ await waitFor(() => {+ expect(screen.queryByText("skill-a")).not.toBeInTheDocument();+ });+ expect(screen.getAllByText("skill-b").length).toBeGreaterThan(0);+ });++ it("clears a previous import error when a new folder is picked", async () => {+ mockImportSkillArchive.mockRejectedValueOnce(+ new Error("a skill with this name already exists"),+ );+ renderDialog();+ const input = document.querySelector(+ 'input[type="file"][multiple]',+ ) as HTMLInputElement;+ fireEvent.change(input, { target: { files: [new File(["a"], "SKILL.md")] } });+ expect((await screen.findAllByText("review-helper")).length).toBeGreaterThan(0);+ fireEvent.click(screen.getByRole("button", { name: /^Import$/i }));+ expect(+ await screen.findByText(/a skill with this name already exists/i),+ ).toBeInTheDocument();++ mockPrepareFromPicker.mockResolvedValue({+ ...PREPARED_OK,+ preview: {+ ...PREPARED_OK.preview,+ skillName: "other-skill",+ displayName: "other-skill",+ },+ });+ fireEvent.change(input, { target: { files: [new File(["b"], "SKILL.md")] } });+ expect((await screen.findAllByText("other-skill")).length).toBeGreaterThan(0);+ expect(+ screen.queryByText(/a skill with this name already exists/i),+ ).not.toBeInTheDocument();+ });+});diff --git a/packages/views/skills/components/create-skill-dialog.tsx b/packages/views/skills/components/create-skill-dialog.tsxindex 8ac8bb6044..46457e5ba9 100644--- a/packages/views/skills/components/create-skill-dialog.tsx+++ b/packages/views/skills/components/create-skill-dialog.tsx@@ -1,11 +1,13 @@"use client";-import { useRef, useState } from "react";+import { useRef, useState, type ChangeEvent } from "react";import {AlertCircle,ArrowLeft,ChevronRight,Download,+ FileArchive,+ FolderOpen,HardDrive,Loader2,Pencil,@@ -16,6 +18,11 @@ import { toast } from "sonner";import { useQueryClient } from "@tanstack/react-query";import { api } from "@multica/core/api";import type { Skill } from "@multica/core/types";+import {+ prepareSkillArchiveFromPickerFiles,+ wrapExistingSkillArchive,+ type PreparedSkillArchive,+} from "@multica/core/skills";import { useWorkspaceId } from "@multica/core/hooks";import { isImeComposing } from "@multica/core/utils";import {@@ -43,7 +50,7 @@ import { RuntimeLocalSkillImportPanel } from "./runtime-local-skill-import-panelimport { useT } from "../../i18n";import { isNameConflictError } from "../lib/utils";-type Method = "chooser" | "manual" | "url" | "runtime";+type Method = "chooser" | "manual" | "local" | "url" | "runtime";function seedAfterCreate(qc: ReturnType<typeof useQueryClient>,@@ -56,7 +63,7 @@ function seedAfterCreate(}// ----------------------------------------------------------------------------// Chooser — initial method picker (3 cards)+// Chooser — initial method picker (4 cards)// ---------------------------------------------------------------------------function MethodChooser({ onChoose }: { onChoose: (m: Method) => void }) {@@ -64,9 +71,10 @@ function MethodChooser({ onChoose }: { onChoose: (m: Method) => void }) {const methods: {key: Method;icon: typeof Plus;- titleKey: "manual" | "url" | "runtime";+ titleKey: "manual" | "local" | "url" | "runtime";}[] = [{ key: "manual", icon: Plus, titleKey: "manual" },+ { key: "local", icon: FolderOpen, titleKey: "local" },{ key: "url", icon: Download, titleKey: "url" },{ key: "runtime", icon: HardDrive, titleKey: "runtime" },];@@ -420,6 +428,192 @@ function UrlForm({);}+// ---------------------------------------------------------------------------+// Local folder / archive import+// ---------------------------------------------------------------------------++function LocalForm({+ prepared,+ preparing,+ onCreated,+ onCancel,+ onChooseFolder,+ onChooseArchive,+}: {+ prepared: PreparedSkillArchive | null;+ preparing: boolean;+ onCreated: (skill: Skill) => void;+ onCancel: () => void;+ onChooseFolder: () => void;+ onChooseArchive: () => void;+}) {+ const { t } = useT("skills");+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState("");+ const scrollRef = useRef<HTMLDivElement>(null);+ const fadeStyle = useScrollFade(scrollRef);++ const submit = async () => {+ if (!prepared || !prepared.ok) {+ setError(+ prepared && !prepared.ok+ ? {+ missing_skill_md: t(($) => $.create.local.missing_skill_md),+ too_large: t(($) => $.create.local.too_large),+ empty: t(($) => $.create.local.empty),+ too_many_files: t(($) => $.create.local.too_many_files),+ }[prepared.error]+ : t(($) => $.create.local.pick_hint),+ );+ return;+ }+ setLoading(true);+ setError("");+ try {+ const skill = await api.importSkillArchive(prepared.file, "fail");+ seedAfterCreate(qc, wsId, skill);+ toast.success(t(($) => $.create.local.toast_imported));+ onCreated(skill);+ } catch (err) {+ setError(+ err instanceof Error ? err.message : t(($) => $.create.local.fallback_error),+ );+ setLoading(false);+ }+ };++ const prepareError =+ prepared && !prepared.ok+ ? {+ missing_skill_md: t(($) => $.create.local.missing_skill_md),+ too_large: t(($) => $.create.local.too_large),+ empty: t(($) => $.create.local.empty),+ too_many_files: t(($) => $.create.local.too_many_files),+ }[prepared.error]+ : "";+ const displayError = error || prepareError;++ return (+ <>+ <div+ ref={scrollRef}+ style={fadeStyle}+ className="flex-1 min-h-0 space-y-4 overflow-y-auto px-5 py-4"+ >+ {preparing && (+ <div className="flex items-center gap-2 text-caption text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t(($) => $.create.local.importing)}+ </div>+ )}++ {prepared?.ok && (+ <div className="space-y-3">+ <div className="rounded-md border px-3 py-2.5">+ <div className="text-caption text-muted-foreground">+ {prepared.preview.source === "archive"+ ? t(($) => $.create.local.archive_label)+ : t(($) => $.create.local.folder_label)}+ </div>+ <div className="mt-0.5 truncate text-body font-medium">+ {prepared.preview.displayName}+ </div>+ </div>+ <div className="space-y-1">+ <div className="text-body font-medium">{prepared.preview.skillName}</div>+ {prepared.preview.description ? (+ <p className="text-caption text-muted-foreground">+ {prepared.preview.description}+ </p>+ ) : null}+ {prepared.preview.fileCount != null ? (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.create.local.files, {+ count: prepared.preview.fileCount,+ })}+ </p>+ ) : null}+ </div>+ </div>+ )}++ {!preparing && !prepared && (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.create.local.pick_hint)}+ </p>+ )}++ {displayError && (+ <div+ role="alert"+ className="flex items-start gap-2 rounded-md bg-destructive/10 px-3 py-2 text-caption text-destructive"+ >+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <span>+ {displayError}+ {isNameConflictError(displayError) && (+ <>{t(($) => $.create.local.name_conflict_hint)}</>+ )}+ </span>+ </div>+ )}+ </div>++ <div className="flex shrink-0 items-center justify-end gap-2 border-t bg-muted/30 px-5 py-3">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={onCancel}+ disabled={loading}+ >+ {t(($) => $.create.local.cancel)}+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={onChooseArchive}+ disabled={loading || preparing}+ >+ <FileArchive className="h-3 w-3" />+ {t(($) => $.create.local.choose_archive)}+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={onChooseFolder}+ disabled={loading || preparing}+ >+ <FolderOpen className="h-3 w-3" />+ {t(($) => $.create.local.choose_folder)}+ </Button>+ <Button+ type="button"+ size="sm"+ onClick={submit}+ disabled={loading || preparing}+ >+ {loading ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ {t(($) => $.create.local.importing)}+ </>+ ) : (+ <>+ <FolderOpen className="h-3 w-3" />+ {t(($) => $.create.local.import)}+ </>+ )}+ </Button>+ </div>+ </>+ );+}+// ---------------------------------------------------------------------------// Root dialog// ---------------------------------------------------------------------------@@ -433,12 +627,94 @@ export function CreateSkillDialog({}) {const { t } = useT("skills");const [method, setMethod] = useState<Method>("chooser");+ const [localPrepared, setLocalPrepared] = useState<PreparedSkillArchive | null>(+ null,+ );+ const [localPreparing, setLocalPreparing] = useState(false);+ const [localEpoch, setLocalEpoch] = useState(0);+ const localGeneration = useRef(0);+ const folderInputRef = useRef<HTMLInputElement>(null);+ const archiveInputRef = useRef<HTMLInputElement>(null);const handleCreated = (skill: Skill) => {onCreated?.(skill);onClose();};+ const beginLocalSelection = (): number => {+ const next = localGeneration.current + 1;+ localGeneration.current = next;+ setLocalEpoch(next);+ return next;+ };++ const resetLocal = () => {+ beginLocalSelection();+ setLocalPrepared(null);+ setLocalPreparing(false);+ };++ const bindDirectoryInput = (el: HTMLInputElement | null) => {+ folderInputRef.current = el;+ if (!el) return;+ el.setAttribute("webkitdirectory", "");+ el.setAttribute("directory", "");+ };++ const openFolderPicker = () => {+ folderInputRef.current?.click();+ };++ const openArchivePicker = () => {+ archiveInputRef.current?.click();+ };++ const handleChoose = (next: Method) => {+ if (next === "local") {+ // Switch first so cancelling the picker still lands on the local+ // panel (choose-folder / choose-archive), rather than silently+ // staying on the chooser with no way to pick a .skill file.+ setMethod("local");+ openFolderPicker();+ return;+ }+ resetLocal();+ setMethod(next);+ };++ const onFolderPicked = async (e: ChangeEvent<HTMLInputElement>) => {+ // FileList is live: clearing the input empties the same object. Snapshot+ // File handles first so resetting `value` (to allow picking the same+ // folder again) cannot drop the selection.+ const files = Array.from(e.target.files ?? []);+ e.target.value = "";+ if (files.length === 0) return;+ const gen = beginLocalSelection();+ setMethod("local");+ setLocalPreparing(true);+ setLocalPrepared(null);+ try {+ const prepared = await prepareSkillArchiveFromPickerFiles(files);+ if (gen !== localGeneration.current) return;+ setLocalPrepared(prepared);+ } catch {+ if (gen !== localGeneration.current) return;+ setLocalPrepared({ ok: false, error: "empty" });+ } finally {+ if (gen === localGeneration.current) setLocalPreparing(false);+ }+ };++ const onArchivePicked = (e: ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ e.target.value = "";+ if (!file) return;+ beginLocalSelection();+ setMethod("local");+ setLocalPreparing(false);+ setLocalPrepared(wrapExistingSkillArchive(file));+ };+const wide = method === "runtime";return (@@ -462,7 +738,10 @@ export function CreateSkillDialog({render={<buttontype="button"- onClick={() => setMethod("chooser")}+ onClick={() => {+ resetLocal();+ setMethod("chooser");+ }}className="-ml-1 rounded-sm p-1 text-faint-foreground transition-colors hover:bg-accent/60 hover:text-muted-foreground"aria-label={t(($) => $.create.back_aria)}>@@ -499,14 +778,49 @@ export function CreateSkillDialog({</Tooltip></div>+ {/* Hidden pickers stay mounted so the chooser click can open them+ in the same user-gesture (browsers otherwise block input.click()). */}+ <input+ ref={bindDirectoryInput}+ type="file"+ multiple+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={onFolderPicked}+ />+ <input+ ref={archiveInputRef}+ type="file"+ accept=".skill,.zip,application/zip"+ className="sr-only"+ tabIndex={-1}+ aria-hidden+ onChange={onArchivePicked}+ />+{/* Method body — each form owns its scroll middle + footer */}- {method === "chooser" && <MethodChooser onChoose={setMethod} />}+ {method === "chooser" && <MethodChooser onChoose={handleChoose} />}{method === "manual" && (<ManualFormonCreated={handleCreated}onCancel={() => setMethod("chooser")}/>)}+ {method === "local" && (+ <LocalForm+ key={localEpoch}+ prepared={localPrepared}+ preparing={localPreparing}+ onCreated={handleCreated}+ onCancel={() => {+ resetLocal();+ setMethod("chooser");+ }}+ onChooseFolder={openFolderPicker}+ onChooseArchive={openArchivePicker}+ />+ )}{method === "url" && (<UrlFormonCreated={handleCreated}