Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8641: fix(skills): add explicit local source choice and batch folder imports (#9505)

j-tide41885a6d8168
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 870f0d2422..ca82f4f9cf 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -2808,6 +2808,26 @@ describe("ApiClient workspace MCP servers", () => {
});
describe("importSkillArchive", () => {
+ it("pins archive upload and CSRF retry headers to the original workspace", async () => {
+ setCurrentWorkspace("workspace-a", "ws-1");
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(async () => {
+ setCurrentWorkspace("workspace-b", "ws-2");
+ return new Response(JSON.stringify({ error: "CSRF validation failed" }), { status: 403 });
+ })
+ .mockResolvedValueOnce(new Response(JSON.stringify({ status: "created", skill: { id: "alpha", workspace_id: "ws-1", name: "alpha" } }), { status: 201 }));
+ vi.stubGlobal("fetch", fetchMock);
+ try {
+ const result = await new ApiClient("https://api.example.test").importSkillArchive(
+ new File(["zip"], "alpha.skill"), "fail", { workspaceSlug: "workspace-a" },
+ );
+ expect(result.workspace_id).toBe("ws-1");
+ expect(fetchMock.mock.calls.map((call) => call[1].headers["X-Workspace-Slug"])).toEqual(["workspace-a", "workspace-a"]);
+ } finally {
+ setCurrentWorkspace(null, null);
+ }
+ });
+
it("POSTs multipart form data without a JSON content-type", async () => {
const skill = {
id: "skill-1",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 35febb5a9f..653a9b88d6 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -3636,11 +3636,22 @@ export class ApiClient {
}
// Skills
- async listSkills(): Promise<SkillSummary[]> {
- const raw = await this.fetch<unknown>("/api/skills");
- return parseWithFallback(raw, SkillSummaryListSchema, EMPTY_SKILL_SUMMARY_LIST, {
- endpoint: "GET /api/skills",
- });
+ async listSkills(options?: {
+ requireValidResponse?: boolean;
+ workspaceSlug?: string;
+ }): Promise<SkillSummary[]> {
+ const raw = await this.fetch<unknown>("/api/skills", {
+ headers: options?.workspaceSlug ? { "X-Workspace-Slug": options.workspaceSlug } : undefined,
+ });
+ // Rendering can degrade to an empty list; absence checks must fail closed.
+ const skills = parseWithFallback<SkillSummary[] | null>(
+ raw,
+ options?.requireValidResponse ? SkillSummaryListSchema.removeDefault() : SkillSummaryListSchema,
+ options?.requireValidResponse ? null : EMPTY_SKILL_SUMMARY_LIST,
+ { endpoint: "GET /api/skills" },
+ );
+ if (skills === null) throw new Error("Invalid skill list response");
+ return skills;
}
async getSkill(id: string): Promise<Skill> {
@@ -3683,6 +3694,7 @@ export class ApiClient {
async importSkillArchive(
file: File,
onConflict?: "fail" | "overwrite" | "rename" | "skip",
+ options?: { workspaceSlug: string },
): Promise<Skill> {
const formData = new FormData();
formData.append("file", file, file.name || "skill.zip");
@@ -3693,6 +3705,8 @@ export class ApiClient {
res = await this.fetchRaw("/api/skills/import", {
method: "POST",
body: formData,
+ // Pin retries to the workspace that owns this import queue.
+ headers: options ? { "X-Workspace-Slug": options.workspaceSlug } : undefined,
});
} catch (err) {
throw remapSkillImportError(err);
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 509035a12a..208cfcca5b 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -1,3 +1,4 @@
+// @vitest-environment node
import { afterEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { ApiClient, ApiError } from "./client";
@@ -172,6 +173,32 @@ describe("ApiClient schema fallback", () => {
expect(res).toEqual([]);
});
+ it.each([{ body: { skills: [] } }, { body: null }, { body: [{ id: "missing-identity" }] }])(
+ "rejects malformed skill lists for absence checks while preserving rendering fallback: %j",
+ async ({ body }) => {
+ stubFetchJson(body);
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.listSkills()).resolves.toEqual([]);
+ stubFetchJson(body);
+ await expect(client.listSkills({ requireValidResponse: true })).rejects.toThrow("Invalid skill list response");
+ },
+ );
+
+ it("does not accept a defaulted 204 response as proof of absence", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => new Response(null, { status: 204 })));
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.listSkills()).resolves.toEqual([]);
+ await expect(client.listSkills({ requireValidResponse: true })).rejects.toThrow("Invalid skill list response");
+ });
+
+ it("accepts a verified empty list and older valid rows for absence checks", async () => {
+ const client = new ApiClient("https://api.example.test");
+ stubFetchJson([]);
+ await expect(client.listSkills({ requireValidResponse: true })).resolves.toEqual([]);
+ stubFetchJson([baseSkill]);
+ await expect(client.listSkills({ requireValidResponse: true })).resolves.toMatchObject([{ id: "skill-1", name: "review-helper" }]);
+ });
+
it("treats a missing labels field as an empty array (older backends)", async () => {
stubFetchJson([baseSkill]);
const client = new ApiClient("https://api.example.test");
diff --git a/packages/core/skills/frontmatter.test.ts b/packages/core/skills/frontmatter.test.ts
index a011d6df8f..5bec855e5e 100644
--- a/packages/core/skills/frontmatter.test.ts
+++ b/packages/core/skills/frontmatter.test.ts
@@ -1,5 +1,6 @@
+// @vitest-environment node
import { describe, it, expect } from "vitest";
-import { parseFrontmatter } from "./frontmatter";
+import { parseFrontmatter, skillImportReconciliationName } from "./frontmatter";
describe("parseFrontmatter", () => {
it("parses single-line values", () => {
@@ -121,3 +122,25 @@ describe("parseFrontmatter", () => {
});
});
});
+
+describe("skillImportReconciliationName", () => {
+ it.each([
+ ["---\nname: [invalid\n---\n", null],
+ ["---\nname: ' alpha '\n---\n", "alpha"],
+ ["---\nname: |\n alpha\n---\n", "alpha"],
+ ["# No frontmatter", " original folder "],
+ ["---\nname: ''\n---\n", " original folder "],
+ ["---\ndescription: text\n---\n", " original folder "],
+ ['---\nname: "\\u0085alpha\\u0085"\n---\n', "alpha"],
+ ['---\nname: "\\uFEFFalpha\\uFEFF"\n---\n', "\ufeffalpha\ufeff"],
+ ["---\nname: alpha\n? [a, b]\n: invalid-key\n---\n", null],
+ ["---\nname: 2001-01-01\n---\n", null],
+ ["---\nname: 012\n---\n", null],
+ ["---\nname: true\n---\n", null],
+ ["---\nname: { z: last, a: first }\n---\n", null],
+ ])("derives only confirmed server names for %j", (content, expected) => {
+ expect(skillImportReconciliationName(content!, " original folder ")).toBe(
+ expected,
+ );
+ });
+});
diff --git a/packages/core/skills/frontmatter.ts b/packages/core/skills/frontmatter.ts
index a621247c02..fc13619574 100644
--- a/packages/core/skills/frontmatter.ts
+++ b/packages/core/skills/frontmatter.ts
@@ -47,3 +47,39 @@ export function parseFrontmatter(raw: string): ParsedFrontmatter {
body,
};
}
+
+/** Only return names whose scalar interpretation agrees with the Go importer. */
+export function skillImportReconciliationName(
+ raw: string,
+ fallback: string,
+): string | null {
+ const match = FRONTMATTER_RE.exec(raw);
+ if (!match) return raw.startsWith("---") ? null : fallback;
+ try {
+ // YAML 1.1 also resolves timestamps and legacy numeric forms. Treat those,
+ // structured values and malformed documents as unknown rather than guess
+ // how Go will coerce them to a name.
+ const parsed: unknown = parseYaml(match[1]!, { version: "1.1", mapAsMap: true });
+ const seen = new Set<unknown>();
+ const hasSafeKeys = (value: unknown): boolean => {
+ if (!value || typeof value !== "object") return true;
+ if (seen.has(value)) return false;
+ seen.add(value);
+ if (value instanceof Map) {
+ return [...value].every(([key, entry]) => typeof key === "string" && hasSafeKeys(entry));
+ }
+ return !Array.isArray(value) || value.every(hasSafeKeys);
+ };
+ // Go rejects collection keys; JS would otherwise stringify them and keep
+ // a sibling name even when the server discards the entire frontmatter.
+ if (!(parsed instanceof Map) || !hasSafeKeys(parsed)) return null;
+ const name: unknown = parsed.get("name");
+ if (name == null) return fallback;
+ if (typeof name !== "string") return null;
+ // Go strings.TrimSpace includes NEL but excludes BOM, unlike JS trim().
+ const space = "[\\t-\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
+ return name.replace(new RegExp(`^${space}+|${space}+$`, "g"), "") || fallback;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/core/skills/pack-archive.test.ts b/packages/core/skills/pack-archive.test.ts
index d9579ae937..5e16d76b59 100644
--- a/packages/core/skills/pack-archive.test.ts
+++ b/packages/core/skills/pack-archive.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
import {
MAX_SKILL_FILE_BYTES,
+ MAX_SKILL_FILE_COUNT,
+ discoverSkillArchivesFromPickerFiles,
isIgnoredArchiveEntry,
isSkillArchiveFilename,
packStoreZip,
@@ -54,6 +57,7 @@ describe("prepareSkillArchiveFromEntries", () => {
expect(prepared.ok).toBe(true);
if (!prepared.ok) return;
expect(prepared.preview.skillName).toBe("review-helper");
+ expect(prepared.reconciliationName).toBe("review-helper");
expect(prepared.preview.description).toBe("Reviews code changes");
expect(prepared.preview.fileCount).toBe(2);
expect(prepared.preview.source).toBe("folder");
@@ -65,9 +69,9 @@ describe("prepareSkillArchiveFromEntries", () => {
"review-helper/SKILL.md",
"review-helper/scripts/run.sh",
]);
- expect(new TextDecoder().decode(files.get("review-helper/scripts/run.sh"))).toBe(
- "echo hi",
- );
+ expect(
+ new TextDecoder().decode(files.get("review-helper/scripts/run.sh")),
+ ).toBe("echo hi");
});
it("packs a root-level SKILL.md", () => {
@@ -110,7 +114,10 @@ describe("prepareSkillArchiveFromEntries", () => {
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]) },
+ {
+ relativePath: "skill/icon.png",
+ data: new Uint8Array([0x89, 0x50, 0x4e, 0x47]),
+ },
]);
expect(prepared.ok).toBe(true);
if (!prepared.ok) return;
@@ -229,6 +236,172 @@ describe("packStoreZip", () => {
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");
+ expect(new TextDecoder().decode(files.get("scripts/run.sh"))).toBe(
+ "echo hi",
+ );
+ });
+});
+
+describe("discoverSkillArchivesFromPickerFiles", () => {
+ const entry = (path: string) =>
+ fileWithPath("SKILL.md", path, bytes(SKILL_MD));
+
+ it("discovers 13 sibling roots in stable path order and packs isolated contents", async () => {
+ const files = Array.from({ length: 13 }, (_, i) =>
+ entry(`skills/skill-${String(i).padStart(2, "0")}/SKILL.md`),
+ ).reverse();
+ const result = await discoverSkillArchivesFromPickerFiles(files);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.items).toHaveLength(13);
+ expect(result.items.map((item) => item.id)).toEqual(
+ [...result.items.map((item) => item.id)].sort(),
+ );
+ for (const item of result.items) {
+ const packed = await item.prepare();
+ expect(packed.ok).toBe(true);
+ if (packed.ok)
+ expect([
+ ...unzipStore(new Uint8Array(await packed.file.arrayBuffer())).keys(),
+ ]).toEqual([`${item.id}SKILL.md`]);
+ }
+ });
+
+ it("keeps different-depth siblings and similar prefixes separate, stopping at parent roots", async () => {
+ const result = await discoverSkillArchivesFromPickerFiles([
+ entry("skills/foo/SKILL.md"),
+ entry("skills/foobar/SKILL.md"),
+ entry("skills/group/deep/SKILL.md"),
+ entry("skills/foo/example/SKILL.md"),
+ entry("skills/.hidden/SKILL.md"),
+ ]);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.items.map((item) => item.id)).toEqual([
+ "skills/foo/",
+ "skills/foobar/",
+ "skills/group/deep/",
+ ]);
+ const packed = await result.items[0]!.prepare();
+ if (!packed.ok) throw new Error("packing failed");
+ expect([
+ ...unzipStore(new Uint8Array(await packed.file.arrayBuffer())).keys(),
+ ]).toEqual(["skills/foo/SKILL.md", "skills/foo/example/SKILL.md"]);
+ });
+
+ it("treats a selected root with SKILL.md as one skill", async () => {
+ const result = await discoverSkillArchivesFromPickerFiles([
+ entry("skills/SKILL.md"),
+ entry("skills/child/SKILL.md"),
+ ]);
+ expect(result.ok && result.items.map((item) => item.id)).toEqual([
+ "skills/",
+ ]);
+ });
+
+ it("rejects missing entrypoints and empty selections", async () => {
+ expect(await discoverSkillArchivesFromPickerFiles([])).toEqual({
+ ok: false,
+ error: "empty",
+ });
+ expect(
+ await discoverSkillArchivesFromPickerFiles([
+ fileWithPath("README.md", "skills/README.md", bytes("readme")),
+ ]),
+ ).toEqual({ ok: false, error: "missing_skill_md" });
+ });
+
+ it("isolates size, count and read failures without reading supporting files at discovery", async () => {
+ const read = vi.fn(async () => {
+ throw new Error("must not read supporting files during discovery");
+ });
+ const result = await discoverSkillArchivesFromPickerFiles([
+ entry("skills/good/SKILL.md"),
+ fileWithPath("doc.md", "skills/good/doc.md", bytes("doc"), {
+ arrayBuffer: read,
+ }),
+ fileWithPath("SKILL.md", "skills/large/SKILL.md", bytes(""), {
+ size: MAX_SKILL_FILE_BYTES + 1,
+ arrayBuffer: read,
+ }),
+ entry("skills/count/SKILL.md"),
+ ...Array.from({ length: MAX_SKILL_FILE_COUNT + 1 }, (_, i) =>
+ fileWithPath(`${i}.md`, `skills/count/${i}.md`, bytes(""), {
+ arrayBuffer: read,
+ }),
+ ),
+ fileWithPath("SKILL.md", "skills/unreadable/SKILL.md", bytes(""), {
+ arrayBuffer: read,
+ }),
+ fileWithPath("icon.png", "skills/good/icon.png", bytes(""), {
+ arrayBuffer: read,
+ }),
+ fileWithPath(".hidden", "skills/good/.hidden", bytes(""), {
+ arrayBuffer: read,
+ }),
+ ]);
+ if (!result.ok) throw new Error("discovery failed");
+ expect(result.items.map((item) => [item.id, item.error])).toEqual([
+ ["skills/count/", "too_many_files"],
+ ["skills/good/", undefined],
+ ["skills/large/", "too_large"],
+ ["skills/unreadable/", "unreadable"],
+ ]);
+ expect(result.items[1]!.preview.fileCount).toBe(2);
+ expect(read).toHaveBeenCalledTimes(1);
+ });
+ it("applies the bundle byte limit per root", async () => {
+ const result = await discoverSkillArchivesFromPickerFiles([
+ fileWithPath("SKILL.md", "skills/large/SKILL.md", bytes(SKILL_MD)),
+ ...Array.from({ length: 9 }, (_, i) =>
+ fileWithPath(`${i}.md`, `skills/large/${i}.md`, bytes(""), {
+ size: MAX_SKILL_FILE_BYTES,
+ }),
+ ),
+ fileWithPath("SKILL.md", "skills/small/SKILL.md", bytes(SKILL_MD)),
+ ]);
+ if (!result.ok) throw new Error("discovery failed");
+ expect(result.items.map((item) => item.error)).toEqual([
+ "too_large",
+ undefined,
+ ]);
+ expect((await result.items[1]!.prepare()).ok).toBe(true);
+ });
+});
+
+describe("prepared archive reconciliation identity", () => {
+ it.each(["entries", "picker"] as const)(
+ "uses raw BOM semantics for %s while preserving preview and uploaded bytes",
+ async (source) => {
+ const content = bytes("\ufeff---\nname: alpha\n---\n# Alpha");
+ const relativePath = "download/SKILL.md";
+ const archive =
+ source === "entries"
+ ? prepareSkillArchiveFromEntries([{ relativePath, data: content }])
+ : await prepareSkillArchiveFromPickerFiles([
+ fileWithPath("SKILL.md", relativePath, content),
+ ]);
+ if (!archive.ok) throw new Error("packing failed");
+ expect(archive.preview.skillName).toBe("alpha");
+ expect(archive.reconciliationName).toBe("download");
+ const packed = unzipStore(
+ new Uint8Array(await archive.file.arrayBuffer()),
+ );
+ expect(packed.get(relativePath)).toEqual(content);
+ },
+ );
+
+ it("uses the generated upload name for a root-level entry without frontmatter", () => {
+ const archive = prepareSkillArchiveFromEntries([
+ { relativePath: "SKILL.md", data: bytes("# Root") },
+ ]);
+ if (!archive.ok) throw new Error("packing failed");
+ expect(archive.reconciliationName).toBe("skill");
+ });
+
+ it("keeps a prebuilt archive identity unknown regardless of its filename", () => {
+ const archive = wrapExistingSkillArchive(new File(["zip"], "download.zip"));
+ if (!archive.ok) throw new Error("wrapping failed");
+ expect(archive.reconciliationName).toBeNull();
});
});
diff --git a/packages/core/skills/pack-archive.ts b/packages/core/skills/pack-archive.ts
index 61185ab2c1..6f353c0268 100644
--- a/packages/core/skills/pack-archive.ts
+++ b/packages/core/skills/pack-archive.ts
@@ -1,4 +1,4 @@
-import { parseFrontmatter } from "./frontmatter";
+import { parseFrontmatter, skillImportReconciliationName } from "./frontmatter";
/** Mirrors server/internal/handler maxImportFileSize. */
export const MAX_SKILL_FILE_BYTES = 1 << 20; // 1 MiB
@@ -20,12 +20,15 @@ export type PreparedSkillArchiveError =
| "missing_skill_md"
| "empty"
| "too_large"
- | "too_many_files";
+ | "too_many_files"
+ | "unreadable";
export type PreparedSkillArchive =
| {
ok: true;
file: File;
+ /** Null when the server import identity cannot be established safely. */
+ reconciliationName: string | null;
preview: {
displayName: string;
skillName: string;
@@ -50,6 +53,7 @@ export function wrapExistingSkillArchive(file: File): PreparedSkillArchive {
return {
ok: true,
file,
+ reconciliationName: null,
preview: {
displayName: base,
skillName,
@@ -110,6 +114,11 @@ function buildPreparedArchive(
return {
ok: true,
file,
+ reconciliationName: skillImportReconciliationName(
+ // Go keeps a leading BOM and therefore does not parse that frontmatter.
+ new TextDecoder("utf-8", { ignoreBOM: true }).decode(dataFor(selection.skillMdPath)),
+ wrapperName || stripArchiveExtension(filename).trim(),
+ ),
preview: {
displayName: wrapperName || skillName,
skillName,
@@ -238,6 +247,90 @@ export async function prepareSkillArchiveFromPickerFiles(
return buildPreparedArchive(picked, (path) => data.get(path) ?? EMPTY_BYTES);
}
+export type DiscoveredSkillArchive = {
+ id: string;
+ preview: Extract<PreparedSkillArchive, { ok: true }>["preview"];
+ error?: PreparedSkillArchiveError;
+ prepare: () => Promise<PreparedSkillArchive>;
+};
+
+export type SkillArchiveDiscovery =
+ | { ok: true; items: DiscoveredSkillArchive[] }
+ | { ok: false; error: PreparedSkillArchiveError };
+
+/** Discover roots using metadata, reading only bounded entrypoints for preview. */
+export async function discoverSkillArchivesFromPickerFiles(
+ files: File[],
+): Promise<SkillArchiveDiscovery> {
+ const members = files.map((file) => ({
+ path: pickerRelativePath(file),
+ size: file.size,
+ }));
+ const prefixes = [
+ ...new Set(
+ members
+ .filter(
+ (member) =>
+ !isIgnoredArchiveEntry(member.path) && isSkillMdPath(member.path),
+ )
+ .map((member) => archiveEntryPrefix(member.path)),
+ ),
+ ].sort();
+ const roots: string[] = [];
+ for (const prefix of prefixes) {
+ if (!roots.some((root) => prefix.startsWith(root))) roots.push(prefix);
+ }
+ if (!roots.length)
+ return { ok: false, error: files.length ? "missing_skill_md" : "empty" };
+
+ const items: DiscoveredSkillArchive[] = [];
+ for (const prefix of roots) {
+ const group = files.filter((file) =>
+ pickerRelativePath(file).startsWith(prefix),
+ );
+ const selection = selectSkillArchiveMembers(
+ group.map((file) => ({
+ path: pickerRelativePath(file),
+ size: file.size,
+ })),
+ );
+ const fallback = wrapperNameFromPrefix(prefix) || "skill";
+ let error = selection.ok ? undefined : selection.error;
+ let skillName = fallback;
+ let description = "";
+ if (selection.ok) {
+ try {
+ const source = group.find(
+ (file) => pickerRelativePath(file) === selection.skillMdPath,
+ )!;
+ const { frontmatter } = parseFrontmatter(
+ new TextDecoder().decode(await source.arrayBuffer()),
+ );
+ skillName = frontmatter?.name?.trim() || fallback;
+ description = frontmatter?.description?.trim() ?? "";
+ } catch {
+ error = "unreadable";
+ }
+ }
+ items.push({
+ id: prefix || ".",
+ preview: {
+ displayName: fallback,
+ skillName,
+ description,
+ fileCount: selection.ok ? selection.selected.length : null,
+ source: "folder",
+ },
+ error,
+ prepare: () =>
+ error
+ ? Promise.resolve({ ok: false, error })
+ : prepareSkillArchiveFromPickerFiles(group),
+ });
+ }
+ return { ok: true, items };
+}
+
// --- zip (STORE / uncompressed) -------------------------------------------
const CRC32_TABLE = (() => {
diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.json
index 0d8d6882db..987c65efa7 100644
--- a/packages/views/locales/en/skills.json
+++ b/packages/views/locales/en/skills.json
@@ -309,7 +309,19 @@
"cancel": "Cancel",
"import": "Import",
"importing": "Importing…",
- "toast_imported": "Skill imported"
+ "toast_imported": "Skill imported",
+ "select_all": "Select all",
+ "import_count": "Import {{count}}",
+ "done": "Done",
+ "stop": "Stop after current",
+ "unreadable": "Could not read this skill. Choose the folder again.",
+ "uncertain": "The result is uncertain. Check the refreshed skill list before retrying. Existing names remain locked; review them in the list.",
+ "check_results": "Check results",
+ "retry_ready": "Not found in the refreshed list. You can retry this item.",
+ "uncertain_manual": "The result is uncertain and the archive’s skill name is unknown. Check the skills list manually before importing this archive again.",
+ "check_failed": "Could not verify the skill list. Imports with uncertain results remain locked. Try checking again or review the list manually.",
+ "workspace_changed": "The workspace changed. Remaining imports were stopped. Close this dialog and reopen it in the intended workspace.",
+ "summary": "Imported: {{success}} · Failed or uncertain: {{failed}}"
},
"url": {
"url_label": "Skill URL",
diff --git a/packages/views/locales/es/skills.json b/packages/views/locales/es/skills.json
index c16b79aa93..42ac6a91f1 100644
--- a/packages/views/locales/es/skills.json
+++ b/packages/views/locales/es/skills.json
@@ -309,7 +309,19 @@
"cancel": "Cancelar",
"import": "Importar",
"importing": "Importando…",
- "toast_imported": "Skill importada"
+ "toast_imported": "Skill importada",
+ "select_all": "Seleccionar todo",
+ "import_count": "Importar {{count}}",
+ "done": "Listo",
+ "stop": "Detener tras el elemento actual",
+ "unreadable": "No se ha podido leer esta skill. Vuelve a elegir la carpeta.",
+ "uncertain": "El resultado es incierto. Actualiza la lista de skills y compruébala antes de reintentar. Si ya existe el mismo nombre, la importación seguirá bloqueada; revísala en la lista.",
+ "check_results": "Comprobar resultados",
+ "retry_ready": "No aparece en la lista actualizada. Puedes reintentar esta importación.",
+ "uncertain_manual": "El resultado es incierto y no se conoce el nombre de la skill del archivo. Revisa la lista de skills manualmente antes de volver a importar este archivo.",
+ "check_failed": "No se ha podido verificar la lista de skills. Las importaciones con resultados inciertos siguen bloqueadas. Vuelve a comprobarlo o revisa la lista manualmente.",
+ "workspace_changed": "Ha cambiado el espacio de trabajo. Se han detenido las importaciones pendientes. Cierra este diálogo y ábrelo de nuevo en el espacio de trabajo correcto.",
+ "summary": "Importadas: {{success}} · Fallidas o sin confirmar: {{failed}}"
},
"url": {
"url_label": "URL de la skill",
diff --git a/packages/views/locales/fr/skills.json b/packages/views/locales/fr/skills.json
index 8328bf6699..c7795fb7c0 100644
--- a/packages/views/locales/fr/skills.json
+++ b/packages/views/locales/fr/skills.json
@@ -309,7 +309,19 @@
"cancel": "Annuler",
"import": "Importer",
"importing": "Importation…",
- "toast_imported": "Skill importé"
+ "toast_imported": "Skill importé",
+ "select_all": "Tout sélectionner",
+ "import_count": "Importer {{count}}",
+ "done": "Terminer",
+ "stop": "Arrêter après cet élément",
+ "unreadable": "Impossible de lire ce skill. Sélectionnez à nouveau le dossier.",
+ "uncertain": "Résultat incertain. Actualisez la liste avant de réessayer. Les noms déjà présents restent verrouillés ; consultez la liste.",
+ "check_results": "Vérifier les résultats",
+ "retry_ready": "Absent de la liste actualisée. Vous pouvez réessayer.",
+ "uncertain_manual": "Résultat incertain et nom du skill dans l’archive inconnu. Vérifiez manuellement la liste avant de réimporter cette archive.",
+ "check_failed": "Impossible de vérifier la liste. Les imports incertains restent verrouillés. Réessayez la vérification ou consultez la liste manuellement.",
+ "workspace_changed": "L’espace de travail a changé. Les imports restants sont arrêtés. Fermez cette fenêtre et rouvrez-la dans l’espace souhaité.",
+ "summary": "Importés : {{success}} · Échecs ou incertains : {{failed}}"
},
"url": {
"url_label": "URL du skill",
diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.json
index 8483cf167e..63e6f86d68 100644
--- a/packages/views/locales/ja/skills.json
+++ b/packages/views/locales/ja/skills.json
@@ -297,7 +297,19 @@
"cancel": "キャンセル",
"import": "インポート",
"importing": "インポート中…",
- "toast_imported": "スキルをインポートしました"
+ "toast_imported": "スキルをインポートしました",
+ "select_all": "すべて選択",
+ "import_count": "{{count}} 件をインポート",
+ "done": "完了",
+ "stop": "現在の処理後に停止",
+ "unreadable": "skill を読み取れません。フォルダーを再選択してください。",
+ "uncertain": "結果を確認できません。再試行前に一覧を更新して確認してください。同名の項目がある場合はロックされます。",
+ "check_results": "結果を確認",
+ "retry_ready": "更新した一覧に見つかりません。再試行できます。",
+ "uncertain_manual": "結果が不確実で、アーカイブ内のスキル名を確認できません。再インポート前に一覧を手動で確認してください。",
+ "check_failed": "一覧を検証できませんでした。結果が不確実な項目はロックされたままです。再確認するか、一覧を手動で確認してください。",
+ "workspace_changed": "ワークスペースが変わったため、残りのインポートを停止しました。この画面を閉じ、目的のワークスペースで開き直してください。",
+ "summary": "成功: {{success}} · 失敗または未確認: {{failed}}"
},
"url": {
"url_label": "スキル URL",
diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.json
index 0ac4a61a2e..d88ea7a96e 100644
--- a/packages/views/locales/ko/skills.json
+++ b/packages/views/locales/ko/skills.json
@@ -297,7 +297,19 @@
"cancel": "취소",
"import": "가져오기",
"importing": "가져오는 중...",
- "toast_imported": "스킬을 가져왔습니다"
+ "toast_imported": "스킬을 가져왔습니다",
+ "select_all": "모두 선택",
+ "import_count": "{{count}}개 가져오기",
+ "done": "완료",
+ "stop": "현재 항목 후 중지",
+ "unreadable": "skill을 읽을 수 없습니다. 폴더를 다시 선택하세요.",
+ "uncertain": "결과가 불확실합니다. 재시도 전에 목록을 새로 고쳐 확인하세요. 같은 이름이 있으면 잠금이 유지됩니다.",
+ "check_results": "결과 확인",
+ "retry_ready": "새로 고친 목록에 없습니다. 다시 시도할 수 있습니다.",
+ "uncertain_manual": "결과가 불확실하며 압축 파일의 스킬 이름을 확인할 수 없습니다. 다시 가져오기 전에 목록을 직접 확인하세요.",
+ "check_failed": "목록을 검증할 수 없습니다. 결과가 불확실한 항목은 잠금이 유지됩니다. 다시 확인하거나 목록을 직접 검토하세요.",
+ "workspace_changed": "워크스페이스가 변경되어 나머지 가져오기를 중지했습니다. 대화상자를 닫고 대상 워크스페이스에서 다시 여세요.",
+ "summary": "성공: {{success}} · 실패 또는 미확인: {{failed}}"
},
"url": {
"url_label": "스킬 URL",
diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.json
index c9e480ace0..2409834359 100644
--- a/packages/views/locales/zh-Hans/skills.json
+++ b/packages/views/locales/zh-Hans/skills.json
@@ -297,7 +297,19 @@
"cancel": "取消",
"import": "导入",
"importing": "导入中...",
- "toast_imported": "已导入 skill"
+ "toast_imported": "已导入 skill",
+ "select_all": "全选",
+ "import_count": "导入 {{count}} 个",
+ "done": "完成",
+ "stop": "当前项完成后停止",
+ "unreadable": "无法读取此 skill,请重新选择文件夹。",
+ "uncertain": "导入结果尚不确定,请刷新核对后再重试。列表中已有同名项的 skill 将保持锁定,请前往列表查看。",
+ "check_results": "刷新核对",
+ "retry_ready": "刷新后的列表中未找到此 skill,可以重试。",
+ "uncertain_manual": "导入结果尚不确定,且无法确认压缩包内的 skill 名称。再次导入此压缩包前,请前往 skill 列表人工核对。",
+ "check_failed": "无法核对 skill 列表,结果不确定的导入项仍保持锁定。请重新核对,或前往列表人工查看。",
+ "workspace_changed": "工作区已切换,后续导入已停止。请关闭弹窗,在目标工作区重新打开。",
+ "summary": "成功 {{success}} 个 · 失败或待核对 {{failed}} 个"
},
"url": {
"url_label": "Skill URL",
diff --git a/packages/views/locales/zh-Hant/skills.json b/packages/views/locales/zh-Hant/skills.json
index 21ae4da1c3..ffa1459563 100644
--- a/packages/views/locales/zh-Hant/skills.json
+++ b/packages/views/locales/zh-Hant/skills.json
@@ -297,7 +297,19 @@
"cancel": "取消",
"import": "匯入",
"importing": "匯入中...",
- "toast_imported": "已匯入 skill"
+ "toast_imported": "已匯入 skill",
+ "select_all": "全選",
+ "import_count": "匯入 {{count}} 個",
+ "done": "完成",
+ "stop": "目前項目完成後停止",
+ "unreadable": "無法讀取此 skill,請重新選擇資料夾。",
+ "uncertain": "匯入結果尚不確定。請重新整理 skill 列表並核對後再重試;已有同名項目的匯入會保持鎖定,請前往列表查看。",
+ "check_results": "重新整理並核對",
+ "retry_ready": "重新整理後的列表中未找到此 skill,可以重試。",
+ "uncertain_manual": "匯入結果尚不確定,且無法確認壓縮包內的 skill 名稱。再次匯入此壓縮包前,請先手動核對 skill 列表。",
+ "check_failed": "無法核對 skill 列表,結果不確定的匯入項目仍保持鎖定。請重新核對,或前往列表手動查看。",
+ "workspace_changed": "工作區已切換,後續匯入已停止。請關閉此對話框,並在目標工作區重新開啟。",
+ "summary": "成功 {{success}} 個 · 失敗或待核對 {{failed}} 個"
},
"url": {
"url_label": "Skill URL",
diff --git a/packages/views/skills/components/create-skill-dialog.test.tsx b/packages/views/skills/components/create-skill-dialog.test.tsx
index 46e82d46c2..111faf55cb 100644
--- a/packages/views/skills/components/create-skill-dialog.test.tsx
+++ b/packages/views/skills/components/create-skill-dialog.test.tsx
@@ -1,6 +1,14 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { setCurrentWorkspace } from "@multica/core/platform";
+import { skillDetailOptions } from "@multica/core/workspace/queries";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enSkills from "../../locales/en/skills.json";
@@ -11,25 +19,36 @@ const TEST_RESOURCES = {
const mockImportSkillArchive = vi.hoisted(() => vi.fn());
const mockPrepareFromPicker = vi.hoisted(() => vi.fn());
+const mockListSkills = vi.hoisted(() => vi.fn());
+const mockWorkspaceId = vi.hoisted(() => ({ value: "ws-1" }));
const mockWrap = vi.hoisted(() => vi.fn());
-vi.mock("@multica/core/api", () => ({
- api: {
- importSkillArchive: (...args: unknown[]) => mockImportSkillArchive(...args),
- },
-}));
+vi.mock("@multica/core/api", async () => {
+ const { ApiError } =
+ await vi.importActual<typeof import("@multica/core/api")>(
+ "@multica/core/api",
+ );
+ return {
+ ApiError,
+ api: {
+ listSkills: (...args: unknown[]) => mockListSkills(...args),
+ importSkillArchive: (...args: unknown[]) =>
+ mockImportSkillArchive(...args),
+ },
+ };
+});
vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "ws-1",
+ useWorkspaceId: () => mockWorkspaceId.value,
}));
vi.mock("@multica/core/skills", async () => {
- const actual = await vi.importActual<
- typeof import("@multica/core/skills")
- >("@multica/core/skills");
+ const actual = await vi.importActual<typeof import("@multica/core/skills")>(
+ "@multica/core/skills",
+ );
return {
...actual,
- prepareSkillArchiveFromPickerFiles: (...args: unknown[]) =>
+ discoverSkillArchivesFromPickerFiles: (...args: unknown[]) =>
mockPrepareFromPicker(...args),
wrapExistingSkillArchive: (...args: unknown[]) => mockWrap(...args),
};
@@ -48,6 +67,7 @@ const ARCHIVE_FILE = new File(["pk"], "review-helper.skill", {
const PREPARED_OK = {
ok: true as const,
file: ARCHIVE_FILE,
+ reconciliationName: "review-helper",
preview: {
displayName: "review-helper",
skillName: "review-helper",
@@ -57,6 +77,19 @@ const PREPARED_OK = {
},
};
+function discovery(prepared = PREPARED_OK) {
+ return {
+ ok: true as const,
+ items: [
+ {
+ id: prepared.preview.displayName,
+ preview: prepared.preview,
+ prepare: async () => prepared,
+ },
+ ],
+ };
+}
+
/**
* Chromium's input.files is a live FileList: setting input.value = "" empties
* it. jsdom's fireEvent `{ target: { files } }` bypasses that, so this helper
@@ -95,19 +128,22 @@ function renderDialog(
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ </I18nProvider>
+ );
return {
onCreated,
onClose,
+ queryClient,
...render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <QueryClientProvider client={queryClient}>
- <CreateSkillDialog
- onClose={onClose}
- onCreated={onCreated}
- initialMethod={initialMethod}
- />
- </QueryClientProvider>
- </I18nProvider>,
+ <CreateSkillDialog
+ onClose={onClose}
+ onCreated={onCreated}
+ initialMethod={initialMethod}
+ />,
+ { wrapper },
),
};
}
@@ -115,9 +151,13 @@ function renderDialog(
describe("CreateSkillDialog local import", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockPrepareFromPicker.mockResolvedValue(PREPARED_OK);
+ mockWorkspaceId.value = "ws-1";
+ setCurrentWorkspace("workspace-a", "ws-1");
+ mockPrepareFromPicker.mockResolvedValue(discovery());
+ mockListSkills.mockResolvedValue([]);
mockWrap.mockReturnValue({
...PREPARED_OK,
+ reconciliationName: null,
preview: { ...PREPARED_OK.preview, source: "archive", fileCount: null },
});
mockImportSkillArchive.mockResolvedValue({
@@ -134,7 +174,12 @@ describe("CreateSkillDialog local import", () => {
});
});
- it("opens the folder picker when Import from local is clicked", () => {
+ afterEach(() => {
+ setCurrentWorkspace(null, null);
+ vi.unstubAllGlobals();
+ });
+
+ it("waits for an explicit source choice before opening either picker", () => {
renderDialog();
const click = vi.fn();
const input = document.querySelector(
@@ -143,8 +188,15 @@ describe("CreateSkillDialog local import", () => {
expect(input).not.toBeNull();
if (!input) return;
input.click = click;
+ const archiveClick = vi.fn();
+ (document.querySelector("input[accept]") as HTMLInputElement).click =
+ archiveClick;
fireEvent.click(screen.getByRole("button", { name: /Import from local/i }));
- expect(click).toHaveBeenCalled();
+ expect(click).not.toHaveBeenCalled();
+ expect(archiveClick).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: /Choose folder/i }));
+ expect(click).toHaveBeenCalledTimes(1);
+ expect(archiveClick).not.toHaveBeenCalled();
});
// The local panel keeps its footer at Cancel + Import: a footer that also
@@ -177,15 +229,22 @@ describe("CreateSkillDialog local import", () => {
'input[type="file"][multiple]',
) as HTMLInputElement;
fireEvent.change(input, {
- target: { files: [new File(["---\nname: review-helper\n---\n"], "SKILL.md")] },
+ target: {
+ files: [new File(["---\nname: review-helper\n---\n"], "SKILL.md")],
+ },
});
- expect((await screen.findAllByText("review-helper")).length).toBeGreaterThan(0);
+ expect(
+ (await screen.findAllByText("review-helper")).length,
+ ).toBeGreaterThan(0);
expect(screen.getByRole("button", { name: /^Import$/i })).toBeEnabled();
});
it("does not import when the folder has no SKILL.md", async () => {
- mockPrepareFromPicker.mockResolvedValue({ ok: false, error: "missing_skill_md" });
+ mockPrepareFromPicker.mockResolvedValue({
+ ok: false,
+ error: "missing_skill_md",
+ });
renderDialog();
const input = document.querySelector(
@@ -205,7 +264,7 @@ describe("CreateSkillDialog local import", () => {
if (list.length === 0) {
throw new Error("live FileList was emptied before snapshot");
}
- return PREPARED_OK;
+ return discovery();
});
renderDialog();
@@ -216,10 +275,16 @@ describe("CreateSkillDialog local import", () => {
installLiveFileList(input, [file]);
fireEvent.change(input);
- expect((await screen.findAllByText("review-helper")).length).toBeGreaterThan(0);
+ 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);
+ installLiveFileList(input, [file]);
+ fireEvent.change(input);
+ await waitFor(() => expect(mockPrepareFromPicker).toHaveBeenCalledTimes(2));
+ expect(input.value).toBe("");
});
it("imports a packed folder and closes", async () => {
@@ -231,11 +296,17 @@ describe("CreateSkillDialog local import", () => {
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);
+ 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");
+ expect(mockImportSkillArchive).toHaveBeenCalledWith(
+ ARCHIVE_FILE,
+ "fail",
+ { workspaceSlug: "workspace-a" },
+ );
});
await waitFor(() => {
expect(onCreated).toHaveBeenCalled();
@@ -247,13 +318,14 @@ describe("CreateSkillDialog local import", () => {
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(
+ (await screen.findAllByText("review-helper")).length,
+ ).toBeGreaterThan(0);
expect(mockWrap).toHaveBeenCalledWith(ARCHIVE_FILE);
fireEvent.click(screen.getByRole("button", { name: /^Import$/i }));
await waitFor(() => {
@@ -271,8 +343,8 @@ describe("CreateSkillDialog local import", () => {
});
return { promise, resolve };
};
- const first = deferred<typeof PREPARED_OK>();
- const second = deferred<typeof PREPARED_OK>();
+ const first = deferred<ReturnType<typeof discovery>>();
+ const second = deferred<ReturnType<typeof discovery>>();
mockPrepareFromPicker
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(second.promise);
@@ -281,20 +353,32 @@ describe("CreateSkillDialog local import", () => {
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")] } });
+ 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" },
+ preview: {
+ ...PREPARED_OK.preview,
+ skillName: "skill-b",
+ displayName: "skill-b",
+ },
};
const preparedA = {
...PREPARED_OK,
- preview: { ...PREPARED_OK.preview, skillName: "skill-a", displayName: "skill-a" },
+ preview: {
+ ...PREPARED_OK.preview,
+ skillName: "skill-a",
+ displayName: "skill-a",
+ },
};
- second.resolve(preparedB);
+ second.resolve(discovery(preparedB));
expect((await screen.findAllByText("skill-b")).length).toBeGreaterThan(0);
- first.resolve(preparedA);
+ first.resolve(discovery(preparedA));
await waitFor(() => {
expect(screen.queryByText("skill-a")).not.toBeInTheDocument();
});
@@ -303,36 +387,723 @@ describe("CreateSkillDialog local import", () => {
it("clears a previous import error when a new folder is picked", async () => {
mockImportSkillArchive.mockRejectedValueOnce(
- new Error("a skill with this name already exists"),
+ new (await import("@multica/core/api")).ApiError(
+ "a skill with this name already exists",
+ 409,
+ "Conflict",
+ ),
);
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.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(
+ discovery({
+ ...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();
+ });
+ function pickBatch(
+ names = ["alpha", "beta", "gamma"],
+ prepare?: (name: string) => Promise<typeof PREPARED_OK>,
+ ) {
+ mockPrepareFromPicker.mockResolvedValue({
+ ok: true,
+ items: names.map((name) => ({
+ id: `skills/${name}/`,
+ preview: { ...PREPARED_OK.preview, skillName: name },
+ prepare: () =>
+ prepare
+ ? prepare(name)
+ : Promise.resolve({
+ ...PREPARED_OK,
+ file: new File([name], `${name}.skill`),
+ reconciliationName: name,
+ }),
+ })),
+ });
+ const rendered = renderDialog();
+ fireEvent.change(document.querySelector("input[multiple]")!, {
+ target: { files: [new File(["a"], "SKILL.md")] },
+ });
+ return rendered;
+ }
+
+ it("imports only selected items, continues after conflicts and retries only failures", async () => {
+ const { onClose, onCreated } = pickBatch();
+ await screen.findByText("alpha");
+ fireEvent.click(screen.getByRole("checkbox", { name: "gamma" }));
+ mockImportSkillArchive.mockRejectedValueOnce(
+ new (await import("@multica/core/api")).ApiError(
+ "name exists",
+ 409,
+ "Conflict",
+ ),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ await screen.findByText("Imported: 1 · Failed or uncertain: 1");
+ expect(
+ mockImportSkillArchive.mock.calls.map((call) => call[0].name),
+ ).toEqual(["alpha.skill", "beta.skill"]);
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onCreated).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Import 1" }));
+ await screen.findByText("Imported: 2 · Failed or uncertain: 0");
+ expect(
+ mockImportSkillArchive.mock.calls.map((call) => call[0].name),
+ ).toEqual(["alpha.skill", "beta.skill", "alpha.skill"]);
+ fireEvent.click(screen.getByRole("button", { name: "Done" }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onCreated).not.toHaveBeenCalled();
+ });
+
+ it("locks dismissal and reselection during upload and stops only subsequent items", async () => {
+ let resolve!: (value: { id: string; workspace_id: string }) => void;
+ mockImportSkillArchive.mockReturnValueOnce(
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const { onClose } = pickBatch();
+ await screen.findByText("alpha");
+ fireEvent.click(screen.getByRole("button", { name: "Import 3" }));
+ await waitFor(() =>
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(1),
+ );
+ expect(
+ screen.getByRole("button", { name: /Choose folder/i }),
+ ).toBeDisabled();
+ expect(screen.getByRole("button", { name: /Close/i })).toBeDisabled();
+ expect(screen.getByRole("button", { name: /Back/i })).toBeDisabled();
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(onClose).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Stop after current" }));
+ resolve({ id: "alpha-id", workspace_id: "ws-1" });
+ await screen.findByText("Imported: 1 · Failed or uncertain: 0");
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole("button", { name: "Import 2" })).toBeEnabled();
+ });
+
+ it("requires a successful refresh before explicitly retrying uncertain results", async () => {
+ const { onClose } = pickBatch(["alpha", "beta"]);
+ await screen.findByText("alpha");
+ mockImportSkillArchive.mockRejectedValueOnce(
+ new TypeError("network error"),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ await screen.findByText("Imported: 1 · Failed or uncertain: 1");
+ expect(screen.getByRole("button", { name: "Import 0" })).toBeDisabled();
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(2);
+ mockListSkills.mockRejectedValueOnce(new TypeError("offline"));
+ fireEvent.click(screen.getByRole("button", { name: "Check results" }));
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Check results" }),
+ ).toBeEnabled(),
+ );
+ expect(screen.getByRole("button", { name: "Import 0" })).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "Check results" }));
+ await screen.findByText(
+ "Not found in the refreshed list. You can retry this item.",
+ );
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(2);
+ fireEvent.click(screen.getByRole("button", { name: "Import 1" }));
+ await screen.findByText("Imported: 2 · Failed or uncertain: 0");
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(3);
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("leaves invalid items disabled while valid items remain importable", async () => {
mockPrepareFromPicker.mockResolvedValue({
- ...PREPARED_OK,
- preview: {
- ...PREPARED_OK.preview,
- skillName: "other-skill",
- displayName: "other-skill",
+ ok: true,
+ items: [
+ ...discovery().items,
+ {
+ ...discovery().items[0],
+ id: "oversized/",
+ preview: { ...PREPARED_OK.preview, skillName: "oversized" },
+ error: "too_large",
+ },
+ ],
+ });
+ renderDialog();
+ fireEvent.change(document.querySelector("input[multiple]")!, {
+ target: { files: [new File(["a"], "SKILL.md")] },
+ });
+ await screen.findByText("This skill is too large to import.");
+ expect(screen.getByRole("checkbox", { name: "oversized" })).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ );
+ fireEvent.click(screen.getByRole("checkbox", { name: "oversized" }));
+ expect(screen.getByRole("checkbox", { name: "oversized" })).toHaveAttribute(
+ "aria-checked",
+ "false",
+ );
+ expect(screen.getByRole("button", { name: "Import 1" })).toBeEnabled();
+ });
+
+ it("ignores a slow folder preview after an archive is chosen and handles cancellation", async () => {
+ let resolve!: (value: ReturnType<typeof discovery>) => void;
+ mockPrepareFromPicker.mockReturnValueOnce(
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: /Import from local/i }));
+ const folder = document.querySelector("input[multiple]")!;
+ fireEvent.change(folder, { target: { files: [] } });
+ expect(screen.getByRole("button", { name: /^Import$/ })).toBeDisabled();
+ fireEvent.change(folder, {
+ target: { files: [new File(["a"], "SKILL.md")] },
+ });
+ fireEvent.change(document.querySelector("input[accept]")!, {
+ target: { files: [ARCHIVE_FILE] },
+ });
+ await screen.findByText("review-helper");
+ resolve(
+ discovery({
+ ...PREPARED_OK,
+ preview: { ...PREPARED_OK.preview, skillName: "stale" },
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.queryByText("stale")).not.toBeInTheDocument(),
+ );
+ fireEvent.change(folder, { target: { files: [] } });
+ expect(screen.getByRole("button", { name: /^Import$/ })).toBeEnabled();
+ });
+ it("keeps uncertain names locked when a refreshed list contains the same name", async () => {
+ pickBatch(["alpha", "beta"]);
+ await screen.findByText("alpha");
+ mockImportSkillArchive.mockRejectedValueOnce(
+ new (await import("@multica/core/api")).ApiError(
+ "server error",
+ 500,
+ "Internal Server Error",
+ ),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ await screen.findByText("Imported: 1 · Failed or uncertain: 1");
+ mockListSkills.mockResolvedValueOnce([
+ { name: "alpha", workspace_id: "ws-1" },
+ ]);
+ fireEvent.click(screen.getByRole("button", { name: "Check results" }));
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Check results" }),
+ ).toBeEnabled(),
+ );
+ expect(screen.getByRole("button", { name: "Import 0" })).toBeDisabled();
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(2);
+ });
+ it("must stop queued writes after unmount and workspace change", async () => {
+ const { ApiClient } =
+ await vi.importActual<typeof import("@multica/core/api")>(
+ "@multica/core/api",
+ );
+ const { setCurrentWorkspace } = await import("@multica/core/platform");
+ const client = new ApiClient("https://api.example.test");
+ let resolveFirst!: (value: Response) => void;
+ const first = new Promise<Response>((resolve) => {
+ resolveFirst = resolve;
+ });
+ const reply = (name: string) =>
+ new Response(
+ JSON.stringify({
+ status: "created",
+ skill: { id: name, workspace_id: "ws-1", name },
+ }),
+ { status: 201, headers: { "Content-Type": "application/json" } },
+ );
+ const fetchMock = vi
+ .fn()
+ .mockReturnValueOnce(first)
+ .mockImplementation(async () => reply("beta"));
+ vi.stubGlobal("fetch", fetchMock);
+ setCurrentWorkspace("workspace-a", "ws-1");
+ try {
+ mockImportSkillArchive.mockImplementation(
+ (...args: Parameters<typeof client.importSkillArchive>) =>
+ client.importSkillArchive(...args),
+ );
+ const { unmount, queryClient, onClose, onCreated } = pickBatch([
+ "alpha",
+ "beta",
+ ]);
+ await screen.findByText("alpha");
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ unmount();
+ setCurrentWorkspace("workspace-b", "ws-2");
+ await act(async () => {
+ resolveFirst(reply("alpha"));
+ await first;
+ });
+ expect(
+ fetchMock.mock.calls.map((call) => call[1].headers["X-Workspace-Slug"]),
+ ).toEqual(["workspace-a"]);
+ expect(
+ queryClient.getQueryData(skillDetailOptions("ws-1", "alpha").queryKey),
+ ).toMatchObject({ id: "alpha", workspace_id: "ws-1" });
+ expect(
+ queryClient.getQueryData(skillDetailOptions("ws-2", "alpha").queryKey),
+ ).toBeUndefined();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onCreated).not.toHaveBeenCalled();
+ } finally {
+ setCurrentWorkspace(null, null);
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it.each(["alpha", "download", "empty"])(
+ "keeps archive identity unknown when the verified list contains %s",
+ async (listedName) => {
+ const actual = await vi.importActual<
+ typeof import("@multica/core/skills")
+ >("@multica/core/skills");
+ mockWrap.mockImplementation(actual.wrapExistingSkillArchive);
+ const packed = actual.packStoreZip([
+ {
+ path: "alpha/SKILL.md",
+ data: new TextEncoder().encode("---\nname: alpha\n---\n# Alpha\n"),
+ },
+ ]);
+ const archive = new File(
+ [new Uint8Array(packed).buffer],
+ "download.zip",
+ { type: "application/zip" },
+ );
+ renderDialog();
+ fireEvent.change(document.querySelector("input[accept]")!, {
+ target: { files: [archive] },
+ });
+ await screen.findByText("download");
+ mockImportSkillArchive.mockRejectedValueOnce(
+ new TypeError("response lost after server committed alpha"),
+ );
+ fireEvent.click(screen.getByRole("button", { name: /^Import$/ }));
+ await screen.findByRole("button", { name: "Check results" });
+ mockListSkills.mockResolvedValueOnce(
+ listedName === "empty"
+ ? []
+ : [{ id: listedName, workspace_id: "ws-1", name: listedName }],
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Check results" }));
+ await waitFor(() => expect(mockListSkills).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(screen.getByRole("button", { name: /^Import$/ })).toBeDisabled();
+ expect(screen.getByText(/skill name is unknown/i)).toBeInTheDocument();
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it.each([
+ { body: { skills: [] }, verified: false },
+ { body: [], verified: true },
+ ])(
+ "only unlocks directory imports with a verified list: $verified",
+ async ({ body, verified }) => {
+ const { ApiClient } =
+ await vi.importActual<typeof import("@multica/core/api")>(
+ "@multica/core/api",
+ );
+ const client = new ApiClient("https://api.example.test");
+ const { onClose } = pickBatch(["alpha", "beta"]);
+ await screen.findByText("alpha");
+ mockImportSkillArchive.mockRejectedValueOnce(
+ new TypeError("response lost"),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ await screen.findByText("Imported: 1 · Failed or uncertain: 1");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+ mockListSkills.mockImplementation(
+ (...args: Parameters<typeof client.listSkills>) =>
+ client.listSkills(...args),
+ );
+ try {
+ fireEvent.click(screen.getByRole("button", { name: "Check results" }));
+ await waitFor(() => expect(mockListSkills).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(mockListSkills).toHaveBeenCalledWith({
+ requireValidResponse: true,
+ workspaceSlug: "workspace-a",
+ });
+ if (verified) {
+ expect(
+ screen.getByText(
+ "Not found in the refreshed list. You can retry this item.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Import 1" }),
+ ).toBeEnabled();
+ } else {
+ expect(
+ screen.queryByText(
+ "Not found in the refreshed list. You can retry this item.",
+ ),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Import 0" }),
+ ).toBeDisabled();
+ expect(
+ screen.getByText(/Could not verify the skill list/i),
+ ).toBeInTheDocument();
+ }
+ expect(onClose).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ },
+ );
+ it("does not upload when unmounted during asynchronous archive preparation", async () => {
+ const { ApiClient } =
+ await vi.importActual<typeof import("@multica/core/api")>(
+ "@multica/core/api",
+ );
+ const client = new ApiClient("https://api.example.test");
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ mockImportSkillArchive.mockImplementation(
+ (...args: Parameters<typeof client.importSkillArchive>) =>
+ client.importSkillArchive(...args),
+ );
+ let resolve!: (value: typeof PREPARED_OK) => void;
+ const prepare = vi.fn(
+ () =>
+ new Promise<typeof PREPARED_OK>((r) => {
+ resolve = r;
+ }),
+ );
+ const { unmount, queryClient } = pickBatch(["alpha", "beta"], prepare);
+ await screen.findByText("alpha");
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ expect(prepare).toHaveBeenCalledTimes(1);
+ unmount();
+ setCurrentWorkspace("workspace-b", "ws-2");
+ await act(async () => {
+ resolve(PREPARED_OK);
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(prepare).toHaveBeenCalledTimes(1);
+ expect(
+ queryClient.getQueryData(skillDetailOptions("ws-1", "alpha").queryKey),
+ ).toBeUndefined();
+ });
+
+ it.each(["preparing", "uploading"])(
+ "stops an A queue when workspace changes without unmounting during %s",
+ async (phase) => {
+ const { ApiClient } =
+ await vi.importActual<typeof import("@multica/core/api")>(
+ "@multica/core/api",
+ );
+ const client = new ApiClient("https://api.example.test");
+ let resolveUpload!: (value: Response) => void;
+ const fetchMock = vi.fn(
+ (_url: string, _init?: RequestInit) =>
+ new Promise<Response>((r) => {
+ resolveUpload = r;
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ mockImportSkillArchive.mockImplementation(
+ (...args: Parameters<typeof client.importSkillArchive>) =>
+ client.importSkillArchive(...args),
+ );
+ let resolvePrepare!: (value: typeof PREPARED_OK) => void;
+ const prepare =
+ phase === "preparing"
+ ? vi.fn(
+ () =>
+ new Promise<typeof PREPARED_OK>((r) => {
+ resolvePrepare = r;
+ }),
+ )
+ : undefined;
+ const { queryClient, rerender, onClose, onCreated } = pickBatch(
+ ["alpha", "beta"],
+ prepare,
+ );
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+ const aList = [{ id: "existing-a" }];
+ const bList = [{ id: "existing-b" }];
+ queryClient.setQueryData(["workspaces", "ws-1", "skills"], aList);
+ queryClient.setQueryData(["workspaces", "ws-2", "skills"], bList);
+ await screen.findByText("alpha");
+ fireEvent.click(screen.getByRole("button", { name: "Import 2" }));
+ if (phase === "uploading")
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ mockWorkspaceId.value = "ws-2";
+ await act(async () => {
+ setCurrentWorkspace("workspace-b", "ws-2");
+ rerender(<CreateSkillDialog onClose={onClose} onCreated={onCreated} />);
+ });
+ if (phase === "preparing") {
+ await act(async () => {
+ resolvePrepare(PREPARED_OK);
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(prepare).toHaveBeenCalledTimes(1);
+ } else {
+ await act(async () => {
+ resolveUpload(
+ new Response(
+ JSON.stringify({
+ status: "created",
+ skill: { id: "alpha", workspace_id: "ws-1", name: "alpha" },
+ }),
+ { status: 201 },
+ ),
+ );
+ });
+ expect(
+ fetchMock.mock.calls.map((call) => (call[1] as RequestInit).headers),
+ ).toEqual([
+ expect.objectContaining({ "X-Workspace-Slug": "workspace-a" }),
+ ]);
+ expect(
+ queryClient.getQueryData(
+ skillDetailOptions("ws-1", "alpha").queryKey,
+ ),
+ ).toMatchObject({ id: "alpha", workspace_id: "ws-1" });
+ expect(
+ queryClient.getQueryData(
+ skillDetailOptions("ws-2", "alpha").queryKey,
+ ),
+ ).toBeUndefined();
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: ["workspaces", "ws-1", "skills"],
+ refetchType: "none",
+ });
+ expect(
+ screen.getByText("Imported: 1 · Failed or uncertain: 0"),
+ ).toBeInTheDocument();
+ }
+ expect(
+ queryClient.getQueryData(["workspaces", "ws-1", "skills"]),
+ ).toEqual(aList);
+ expect(
+ queryClient.getQueryData(["workspaces", "ws-2", "skills"]),
+ ).toEqual(bList);
+ expect(screen.getByText(/workspace changed/i)).toBeInTheDocument();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onCreated).not.toHaveBeenCalled();
+ },
+ );
+ it("retains selection ownership when workspace changes before the local panel commits", async () => {
+ let resolve!: (value: ReturnType<typeof discovery>) => void;
+ mockPrepareFromPicker.mockReturnValueOnce(
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const { rerender, onClose, onCreated } = renderDialog();
+ await act(async () => {
+ fireEvent.change(document.querySelector("input[multiple]")!, {
+ target: { files: [new File(["a"], "SKILL.md")] },
+ });
+ mockWorkspaceId.value = "ws-2";
+ setCurrentWorkspace("workspace-b", "ws-2");
+ rerender(<CreateSkillDialog onClose={onClose} onCreated={onCreated} />);
+ });
+ await act(async () => {
+ resolve(discovery());
+ });
+ expect(screen.getByText(/workspace changed/i)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /^Import$/ })).toBeDisabled();
+ expect(mockImportSkillArchive).not.toHaveBeenCalled();
+ });
+ it("keeps a BOM directory uncertain when its server fallback name exists", async () => {
+ const actual = await vi.importActual<typeof import("@multica/core/skills")>(
+ "@multica/core/skills",
+ );
+ const packed = actual.prepareSkillArchiveFromEntries([
+ {
+ relativePath: "download/SKILL.md",
+ data: new TextEncoder().encode("\ufeff---\nname: alpha\n---\n# Alpha"),
},
+ ]);
+ if (!packed.ok) throw new Error("packing failed");
+ mockPrepareFromPicker.mockResolvedValueOnce({
+ ok: true,
+ items: [
+ {
+ id: "download",
+ preview: packed.preview,
+ prepare: async () => packed,
+ },
+ ],
});
- fireEvent.change(input, { target: { files: [new File(["b"], "SKILL.md")] } });
- expect((await screen.findAllByText("other-skill")).length).toBeGreaterThan(0);
+ renderDialog();
+ fireEvent.change(document.querySelector("input[multiple]")!, {
+ target: { files: [new File(["bom"], "SKILL.md")] },
+ });
+ await screen.findByText("alpha");
+ mockImportSkillArchive.mockRejectedValueOnce(
+ new TypeError("response lost after server created download"),
+ );
+ fireEvent.click(screen.getByRole("button", { name: /^Import$/ }));
+ await screen.findByRole("button", { name: "Check results" });
+ mockListSkills.mockResolvedValueOnce([
+ { id: "download-id", workspace_id: "ws-1", name: "download" },
+ ]);
+ fireEvent.click(screen.getByRole("button", { name: "Check results" }));
+ await waitFor(() => expect(mockListSkills).toHaveBeenCalledTimes(1));
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Check results" }),
+ ).toBeEnabled(),
+ );
expect(
- screen.queryByText(/a skill with this name already exists/i),
+ screen.queryByText(
+ "Not found in the refreshed list. You can retry this item.",
+ ),
).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /^Import$/ })).toBeDisabled();
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(1);
+ expect(mockListSkills).toHaveBeenCalledWith({
+ requireValidResponse: true,
+ workspaceSlug: "workspace-a",
+ });
+ expect(
+ screen.getByText("Imported: 0 · Failed or uncertain: 1"),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps a late single success in A without closing or navigating", async () => {
+ let resolve!: (value: {
+ id: string;
+ workspace_id: string;
+ name: string;
+ }) => void;
+ mockImportSkillArchive.mockReturnValueOnce(
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const { onClose, onCreated, queryClient, unmount } = renderDialog();
+ fireEvent.change(document.querySelector("input[multiple]")!, {
+ target: { files: [new File(["a"], "SKILL.md")] },
+ });
+ await screen.findAllByText("review-helper");
+ fireEvent.click(screen.getByRole("button", { name: /^Import$/ }));
+ await waitFor(() =>
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(1),
+ );
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+ unmount();
+ setCurrentWorkspace("workspace-b", "ws-2");
+ await act(async () => {
+ resolve({ id: "late-alpha", workspace_id: "ws-1", name: "alpha" });
+ });
+ expect(
+ queryClient.getQueryData(
+ skillDetailOptions("ws-1", "late-alpha").queryKey,
+ ),
+ ).toMatchObject({ workspace_id: "ws-1" });
+ expect(
+ queryClient.getQueryData(
+ skillDetailOptions("ws-2", "late-alpha").queryKey,
+ ),
+ ).toBeUndefined();
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: ["workspaces", "ws-1", "skills"],
+ refetchType: "none",
+ });
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onCreated).not.toHaveBeenCalled();
+ });
+
+ it("invalidates A without refetch after a late single upload failure", async () => {
+ let reject!: (value: Error) => void;
+ mockImportSkillArchive.mockReturnValueOnce(
+ new Promise((_, r) => {
+ reject = r;
+ }),
+ );
+ const { queryClient, unmount } = renderDialog();
+ fireEvent.change(document.querySelector("input[multiple]")!, {
+ target: { files: [new File(["a"], "SKILL.md")] },
+ });
+ await screen.findAllByText("review-helper");
+ fireEvent.click(screen.getByRole("button", { name: /^Import$/ }));
+ await waitFor(() =>
+ expect(mockImportSkillArchive).toHaveBeenCalledTimes(1),
+ );
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+ unmount();
+ setCurrentWorkspace("workspace-b", "ws-2");
+ await act(async () => {
+ reject(new TypeError("network error"));
+ });
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: ["workspaces", "ws-1", "skills"],
+ refetchType: "none",
+ });
+ expect(invalidate).not.toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: ["workspaces", "ws-2", "skills"] }),
+ );
});
});
describe("CreateSkillDialog opened on a method", () => {
+ it("opens local source choices directly and Cancel leaves the dialog", () => {
+ const click = vi.spyOn(HTMLInputElement.prototype, "click");
+ try {
+ const { onClose } = renderDialog(vi.fn(), vi.fn(), "local");
+ expect(screen.getByRole("button", { name: /Choose folder/i })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Choose \.skill \/ \.zip/i })).toBeInTheDocument();
+ expect(click).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: enSkills.create.local.cancel }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole("button", { name: /Import from URL/i })).toBeNull();
+ } finally {
+ click.mockRestore();
+ }
+ });
+
it("skips the chooser, and Cancel leaves the dialog", () => {
const { onClose } = renderDialog(vi.fn(), vi.fn(), "manual");
expect(screen.getByText(enSkills.create.manual.name_label)).toBeInTheDocument();
diff --git a/packages/views/skills/components/create-skill-dialog.tsx b/packages/views/skills/components/create-skill-dialog.tsx
index 9631735b1a..f4397a102a 100644
--- a/packages/views/skills/components/create-skill-dialog.tsx
+++ b/packages/views/skills/components/create-skill-dialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useRef, useState, type ChangeEvent } from "react";
+import { useLayoutEffect, useRef, useState, type ChangeEvent } from "react";
import {
AlertCircle,
ArrowLeft,
@@ -16,12 +16,18 @@ import {
} from "@multica/ui/icons";
import { toast } from "sonner";
import { useQueryClient } from "@tanstack/react-query";
-import { api } from "@multica/core/api";
+import { api, ApiError } from "@multica/core/api";
+import {
+ getCurrentSlug,
+ getCurrentWsId,
+ subscribeToCurrentSlug,
+} from "@multica/core/platform";
import type { Skill } from "@multica/core/types";
import {
- prepareSkillArchiveFromPickerFiles,
+ discoverSkillArchivesFromPickerFiles,
wrapExistingSkillArchive,
- type PreparedSkillArchive,
+ type SkillArchiveDiscovery,
+ type PreparedSkillArchiveError,
} from "@multica/core/skills";
import { useWorkspaceId } from "@multica/core/hooks";
import { isImeComposing } from "@multica/core/utils";
@@ -40,6 +46,7 @@ import {
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { Button } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
import { Input } from "@multica/ui/components/ui/input";
import { Label } from "@multica/ui/components/ui/label";
import { Textarea } from "@multica/ui/components/ui/textarea";
@@ -58,10 +65,11 @@ function seedAfterCreate(
qc: ReturnType<typeof useQueryClient>,
wsId: string,
skill: Skill,
+ refetchType: "active" | "none" = "active",
) {
qc.setQueryData(skillDetailOptions(wsId, skill.id).queryKey, skill);
- qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId), refetchType });
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId), refetchType });
}
// Chooser — initial method picker (4 cards)
@@ -428,55 +436,222 @@ function UrlForm({
function LocalForm({
prepared,
preparing,
+ selectionWorkspace,
onCreated,
onCancel,
+ onDone,
onChooseFolder,
onChooseArchive,
+ onBusyChange,
}: {
- prepared: PreparedSkillArchive | null;
+ prepared: SkillArchiveDiscovery | null;
+ selectionWorkspace: { wsId: string; slug: string | null };
preparing: boolean;
onCreated: (skill: Skill) => void;
onCancel: () => void;
+ onDone: () => void;
onChooseFolder: () => void;
onChooseArchive: () => void;
+ onBusyChange: (busy: boolean) => void;
}) {
const { t } = useT("skills");
const qc = useQueryClient();
const wsId = useWorkspaceId();
const [loading, setLoading] = useState(false);
- const [error, setError] = useState("");
+ const running = useRef(false);
+ const stop = useRef(false);
+ const mounted = useRef(false);
+ const cancelled = useRef(false);
+ const owner = useRef(selectionWorkspace).current;
+ const [workspaceChanged, setWorkspaceChanged] = useState(false);
+ const [checkError, setCheckError] = useState("");
+ const isOwnerWorkspace = () =>
+ owner.wsId === getCurrentWsId() && owner.slug === getCurrentSlug();
+ const canContinue = () =>
+ mounted.current && !cancelled.current && isOwnerWorkspace();
+
+ useLayoutEffect(() => {
+ mounted.current = true;
+ const checkWorkspace = () => {
+ if (
+ wsId !== owner.wsId ||
+ owner.wsId !== getCurrentWsId() ||
+ owner.slug !== getCurrentSlug()
+ ) {
+ cancelled.current = true;
+ stop.current = true;
+ setWorkspaceChanged(true);
+ }
+ };
+ checkWorkspace();
+ const unsubscribe = subscribeToCurrentSlug(checkWorkspace);
+ return () => {
+ mounted.current = false;
+ stop.current = true;
+ unsubscribe();
+ };
+ }, [wsId, owner]);
+ const [excluded, setExcluded] = useState<Set<string>>(new Set());
+ const [results, setResults] = useState<
+ Record<
+ string,
+ {
+ status: "success" | "failed" | "uncertain";
+ error?: string;
+ reconciliationName?: string | null;
+ }
+ >
+ >({});
const scrollRef = useRef<HTMLDivElement>(null);
const fadeStyle = useScrollFade(scrollRef);
+ const items = prepared?.ok ? prepared.items : [];
+ const bulk = items.length > 1;
+ const eligible = items.filter(
+ (item) =>
+ !workspaceChanged &&
+ !item.error &&
+ !["success", "uncertain"].includes(results[item.id]?.status ?? ""),
+ );
+ const selected = eligible.filter((item) => !excluded.has(item.id));
+ const completed = Object.keys(results).length > 0;
+ const errorLabel = (error: PreparedSkillArchiveError) =>
+ ({
+ 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),
+ unreadable: t(($) => $.create.local.unreadable),
+ })[error];
+
+ const setBusy = (busy: boolean) => {
+ running.current = busy;
+ if (mounted.current) {
+ setLoading(busy);
+ onBusyChange(busy);
+ }
+ };
- // Import stays disabled until a valid selection exists, so an invalid one
- // never reaches here — `prepareError` below already explains why.
const submit = async () => {
- if (!prepared?.ok) return;
- setLoading(true);
- setError("");
+ if (running.current || !selected.length || !canContinue() || !owner.slug)
+ return;
+ setBusy(true);
+ stop.current = false;
+ setCheckError("");
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);
+ for (const item of selected) {
+ if (stop.current || !canContinue()) break;
+ let uploading = false;
+ let reconciliationName: string | null = null;
+ try {
+ const archive = await item.prepare();
+ if (!canContinue()) break;
+ if (!archive.ok) {
+ setResults((prev) => ({
+ ...prev,
+ [item.id]: { status: "failed", error: errorLabel(archive.error) },
+ }));
+ continue;
+ }
+ reconciliationName = archive.reconciliationName;
+ if (!canContinue()) break;
+ uploading = true;
+ const skill = await api.importSkillArchive(archive.file, "fail", {
+ workspaceSlug: owner.slug,
+ });
+ if (skill.workspace_id !== owner.wsId)
+ throw new Error("Import response workspace mismatch");
+ // An in-flight success still belongs to A after the UI moves to B.
+ // Do not refetch A through query functions that read the new global slug.
+ seedAfterCreate(
+ qc,
+ owner.wsId,
+ skill,
+ canContinue() ? "active" : "none",
+ );
+ if (mounted.current)
+ setResults((prev) => ({
+ ...prev,
+ [item.id]: { status: "success" },
+ }));
+ if (!bulk && canContinue()) {
+ toast.success(t(($) => $.create.local.toast_imported));
+ onCreated(skill);
+ }
+ } catch (err) {
+ // A transport/server failure may occur after the server committed the import.
+ const uncertain =
+ uploading &&
+ (!(err instanceof ApiError) ||
+ err.status >= 500 ||
+ err.status === 408);
+ if (mounted.current)
+ setResults((prev) => ({
+ ...prev,
+ [item.id]: {
+ reconciliationName,
+ status: uncertain ? "uncertain" : "failed",
+ error: uncertain
+ ? reconciliationName === null
+ ? t(($) => $.create.local.uncertain_manual)
+ : t(($) => $.create.local.uncertain)
+ : err instanceof Error
+ ? err.message
+ : t(($) => $.create.local.fallback_error),
+ },
+ }));
+ if (uncertain)
+ await qc.invalidateQueries({
+ queryKey: workspaceKeys.skills(owner.wsId),
+ refetchType: canContinue() ? "active" : "none",
+ });
+ }
+ }
+ } finally {
+ setBusy(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;
+ const checkResults = async () => {
+ if (running.current || !canContinue() || !owner.slug) return;
+ setBusy(true);
+ setCheckError("");
+ try {
+ const skills = await api.listSkills({
+ requireValidResponse: true,
+ workspaceSlug: owner.slug,
+ });
+ if (!canContinue()) return;
+ if (skills.some((skill) => skill.workspace_id !== owner.wsId))
+ throw new Error("Skill list workspace mismatch");
+ await qc.invalidateQueries({
+ queryKey: workspaceKeys.skills(owner.wsId),
+ refetchType: "none",
+ });
+ if (!canContinue()) return;
+ setResults((prev) => {
+ const next = { ...prev };
+ for (const item of items) {
+ if (
+ next[item.id]?.status === "uncertain" &&
+ next[item.id]?.reconciliationName != null &&
+ !skills.some(
+ (skill) => skill.name === next[item.id]?.reconciliationName,
+ )
+ ) {
+ next[item.id] = {
+ status: "failed",
+ error: t(($) => $.create.local.retry_ready),
+ };
+ }
+ }
+ return next;
+ });
+ } catch {
+ if (canContinue()) setCheckError(t(($) => $.create.local.check_failed));
+ } finally {
+ setBusy(false);
+ }
+ };
return (
<>
@@ -484,54 +659,25 @@ function LocalForm({
ref={scrollRef}
style={fadeStyle}
className="flex-1 min-h-0 space-y-4 overflow-y-auto px-5 py-4"
+ aria-busy={loading || preparing}
>
- {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>
+ {workspaceChanged && (
+ <p role="alert" className="text-caption text-destructive">
+ {t(($) => $.create.local.workspace_changed)}
+ </p>
)}
-
- {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>
+ {checkError && (
+ <p role="alert" className="text-caption text-destructive">
+ {checkError}
+ </p>
)}
-
- {/* Source pickers belong in the body: four buttons in the footer
- overflow the dialog width and clip Cancel (MUL-6794). */}
- <div className="grid grid-cols-2 gap-2">
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
<Button
type="button"
variant="outline"
size="sm"
- className="w-full"
onClick={onChooseFolder}
- disabled={loading || preparing}
+ disabled={loading || workspaceChanged}
>
<FolderOpen className="h-3 w-3" />
{t(($) => $.create.local.choose_folder)}
@@ -540,57 +686,165 @@ function LocalForm({
type="button"
variant="outline"
size="sm"
- className="w-full"
onClick={onChooseArchive}
- disabled={loading || preparing}
+ disabled={loading || workspaceChanged}
>
<FileArchive className="h-3 w-3" />
{t(($) => $.create.local.choose_archive)}
</Button>
</div>
-
- {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)}</>
+ {preparing && (
+ <p role="status" className="text-caption text-muted-foreground">
+ {t(($) => $.create.local.importing)}
+ </p>
+ )}
+ {prepared && !prepared.ok && (
+ <p role="alert" className="text-caption text-destructive">
+ {errorLabel(prepared.error)}
+ </p>
+ )}
+ {bulk && (
+ <label className="flex items-center gap-2 text-caption">
+ <Checkbox
+ disabled={loading || !eligible.length}
+ checked={
+ eligible.length > 0 && selected.length === eligible.length
+ }
+ indeterminate={
+ selected.length > 0 && selected.length < eligible.length
+ }
+ onCheckedChange={(checked) =>
+ setExcluded(
+ checked
+ ? new Set()
+ : new Set(eligible.map((item) => item.id)),
+ )
+ }
+ />
+ {t(($) => $.create.local.select_all)}
+ </label>
+ )}
+ {items.map((item) => (
+ <div key={item.id} className="space-y-1 rounded-md border p-3">
+ <label className="flex items-start gap-2 text-body font-medium">
+ {bulk && (
+ <Checkbox
+ disabled={loading || !eligible.includes(item)}
+ checked={!item.error && !excluded.has(item.id)}
+ onCheckedChange={(checked) =>
+ setExcluded((prev) => {
+ const next = new Set(prev);
+ if (checked) next.delete(item.id);
+ else next.add(item.id);
+ return next;
+ })
+ }
+ />
)}
- </span>
+ <span className="min-w-0 break-words">
+ {item.preview.skillName}
+ </span>
+ </label>
+ <p className="break-all text-caption text-muted-foreground">
+ {item.id}
+ </p>
+ {item.preview.description && (
+ <p className="text-caption text-muted-foreground">
+ {item.preview.description}
+ </p>
+ )}
+ {item.preview.fileCount != null && (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.create.local.files, {
+ count: item.preview.fileCount,
+ })}
+ </p>
+ )}
+ {item.error && (
+ <p role="alert" className="text-caption text-destructive">
+ {errorLabel(item.error)}
+ </p>
+ )}
+ {results[item.id]?.status === "success" && (
+ <p role="status" className="text-caption">
+ {t(($) => $.create.local.toast_imported)}
+ </p>
+ )}
+ {results[item.id]?.error && (
+ <p role="alert" className="text-caption text-destructive">
+ {results[item.id]?.error}
+ {isNameConflictError(results[item.id]?.error ?? "") &&
+ t(($) => $.create.local.name_conflict_hint)}
+ </p>
+ )}
</div>
+ ))}
+ {completed && (
+ <p role="status" className="text-caption">
+ {t(($) => $.create.local.summary, {
+ success: Object.values(results).filter(
+ (result) => result.status === "success",
+ ).length,
+ failed: Object.values(results).filter(
+ (result) => result.status !== "success",
+ ).length,
+ })}
+ </p>
+ )}
+ {Object.values(results).some(
+ (result) => result.status === "uncertain",
+ ) && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={checkResults}
+ disabled={loading || workspaceChanged}
+ >
+ {t(($) => $.create.local.check_results)}
+ </Button>
)}
</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>
+ <div className="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t bg-muted/30 px-5 py-3">
+ {loading ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ stop.current = true;
+ }}
+ >
+ {t(($) => $.create.local.stop)}
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={completed ? onDone : onCancel}
+ >
+ {completed
+ ? t(($) => $.create.local.done)
+ : t(($) => $.create.local.cancel)}
+ </Button>
+ )}
<Button
type="button"
size="sm"
onClick={submit}
- disabled={!prepared?.ok || loading || preparing}
+ disabled={!selected.length || loading || preparing}
+ aria-busy={loading}
>
{loading ? (
<>
<Loader2 className="h-3 w-3 animate-spin" />
{t(($) => $.create.local.importing)}
</>
+ ) : bulk ? (
+ t(($) => $.create.local.import_count, { count: selected.length })
) : (
- <>
- <FolderOpen className="h-3 w-3" />
- {t(($) => $.create.local.import)}
- </>
+ t(($) => $.create.local.import)
)}
</Button>
</div>
@@ -611,13 +865,20 @@ export function CreateSkillDialog({
onCreated?: (skill: Skill) => void;
}) {
const { t } = useT("skills");
+ const wsId = useWorkspaceId();
+ const localSelectionWorkspace = useRef({ wsId, slug: getCurrentSlug() });
const [method, setMethod] = useState<Method>(initialMethod ?? "chooser");
- const [localPrepared, setLocalPrepared] = useState<PreparedSkillArchive | null>(
- null,
- );
+ const [localPrepared, setLocalPrepared] =
+ useState<SkillArchiveDiscovery | null>(null);
const [localPreparing, setLocalPreparing] = useState(false);
const [localEpoch, setLocalEpoch] = useState(0);
const localGeneration = useRef(0);
+ const [localBusy, setLocalBusy] = useState(false);
+ const localBusyRef = useRef(false);
+ const setLocalBusyState = (busy: boolean) => {
+ localBusyRef.current = busy;
+ setLocalBusy(busy);
+ };
const folderInputRef = useRef<HTMLInputElement>(null);
const archiveInputRef = useRef<HTMLInputElement>(null);
@@ -627,6 +888,7 @@ export function CreateSkillDialog({
};
const beginLocalSelection = (): number => {
+ localSelectionWorkspace.current = { wsId, slug: getCurrentSlug() };
const next = localGeneration.current + 1;
localGeneration.current = next;
setLocalEpoch(next);
@@ -655,14 +917,6 @@ export function CreateSkillDialog({
};
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);
};
@@ -671,6 +925,7 @@ export function CreateSkillDialog({
// 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.
+ if (localBusyRef.current) return;
const files = Array.from(e.target.files ?? []);
e.target.value = "";
if (files.length === 0) return;
@@ -679,25 +934,40 @@ export function CreateSkillDialog({
setLocalPreparing(true);
setLocalPrepared(null);
try {
- const prepared = await prepareSkillArchiveFromPickerFiles(files);
+ const prepared = await discoverSkillArchivesFromPickerFiles(files);
if (gen !== localGeneration.current) return;
setLocalPrepared(prepared);
} catch {
if (gen !== localGeneration.current) return;
- setLocalPrepared({ ok: false, error: "empty" });
+ setLocalPrepared({ ok: false, error: "unreadable" });
} finally {
if (gen === localGeneration.current) setLocalPreparing(false);
}
};
const onArchivePicked = (e: ChangeEvent<HTMLInputElement>) => {
+ if (localBusyRef.current) return;
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
beginLocalSelection();
setMethod("local");
setLocalPreparing(false);
- setLocalPrepared(wrapExistingSkillArchive(file));
+ const archive = wrapExistingSkillArchive(file);
+ setLocalPrepared(
+ archive.ok
+ ? {
+ ok: true,
+ items: [
+ {
+ id: file.name,
+ preview: archive.preview,
+ prepare: async () => archive,
+ },
+ ],
+ }
+ : archive,
+ );
};
// Opened on a method, Cancel leaves the dialog: the chooser it would fall
@@ -710,7 +980,12 @@ export function CreateSkillDialog({
const wide = method === "runtime";
return (
- <Dialog open onOpenChange={(v) => !v && onClose()}>
+ <Dialog
+ open
+ onOpenChange={(v) => {
+ if (!v && !localBusyRef.current) onClose();
+ }}
+ >
<DialogContent
showCloseButton={false}
className={cn(
@@ -730,6 +1005,7 @@ export function CreateSkillDialog({
render={
<button
type="button"
+ disabled={localBusy}
onClick={() => {
resetLocal();
setMethod("chooser");
@@ -741,7 +1017,9 @@ export function CreateSkillDialog({
</button>
}
/>
- <TooltipContent side="bottom">{t(($) => $.create.back)}</TooltipContent>
+ <TooltipContent side="bottom">
+ {t(($) => $.create.back)}
+ </TooltipContent>
</Tooltip>
)}
<div className="min-w-0">
@@ -758,6 +1036,7 @@ export function CreateSkillDialog({
render={
<button
type="button"
+ disabled={localBusy}
onClick={onClose}
className="rounded-sm p-1 text-faint-foreground transition-colors hover:bg-accent/60 hover:text-muted-foreground"
aria-label={t(($) => $.create.close_aria)}
@@ -766,12 +1045,13 @@ export function CreateSkillDialog({
</button>
}
/>
- <TooltipContent side="bottom">{t(($) => $.create.close)}</TooltipContent>
+ <TooltipContent side="bottom">
+ {t(($) => $.create.close)}
+ </TooltipContent>
</Tooltip>
</div>
- {/* Hidden pickers stay mounted so the chooser click can open them
- in the same user-gesture (browsers otherwise block input.click()). */}
+ {/* Source buttons open these pickers synchronously in their click handlers. */}
<input
ref={bindDirectoryInput}
type="file"
@@ -799,6 +1079,9 @@ export function CreateSkillDialog({
{method === "local" && (
<LocalForm
key={localEpoch}
+ onDone={onClose}
+ onBusyChange={setLocalBusyState}
+ selectionWorkspace={localSelectionWorkspace.current}
prepared={localPrepared}
preparing={localPreparing}
onCreated={handleCreated}