A desktop coding agent with free access to frontier models.
TypeScript
feat(app): upload a skill as a folder or .zip and manage its files
Samrat Talukdar28cb2d1bc912
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 122ca884..0e16160a 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -1,3 +1,9 @@+import type {+ SkillBundleInstallResult,+ SkillBundlePreview,+ SkillFileTree,+ SkillUploadFile,+} from "./skill-upload";import type { McpStatusMap } from "../types";import type { Message, Part, Session, Todo } from "@opencode-ai/sdk/v2/client";import {@@ -2053,6 +2059,37 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: smethod: "POST",body: payload,}),+ /** Validates a skill folder/zip upload without writing it (and reports a name collision). */+ previewSkillBundle: (workspaceId: string, payload: { files: SkillUploadFile[]; name?: string }) =>+ requestJson<SkillBundlePreview>(baseUrl, `/workspace/${workspaceId}/skills/bundle/preview`, {+ token,+ hostToken,+ method: "POST",+ body: payload,+ timeoutMs: 120_000,+ }),+ installSkillBundle: (+ workspaceId: string,+ payload: { files: SkillUploadFile[]; name?: string; onConflict?: "fail" | "replace" },+ ) =>+ requestJson<SkillBundleInstallResult>(baseUrl, `/workspace/${workspaceId}/skills/bundle`, {+ token,+ hostToken,+ method: "POST",+ body: payload,+ timeoutMs: 120_000,+ }),+ listSkillFiles: (workspaceId: string, name: string) =>+ requestJson<SkillFileTree>(baseUrl, `/workspace/${workspaceId}/skills/${encodeURIComponent(name)}/files`, {+ token,+ hostToken,+ }),+ updateSkillFiles: (workspaceId: string, name: string, payload: { add?: SkillUploadFile[]; remove?: string[] }) =>+ requestJson<SkillFileTree & { added: string[]; removed: string[] }>(+ baseUrl,+ `/workspace/${workspaceId}/skills/${encodeURIComponent(name)}/files`,+ { token, hostToken, method: "POST", body: payload, timeoutMs: 120_000 },+ ),deleteSkill: (workspaceId: string, name: string) =>requestJson<{ path: string }>(baseUrl,diff --git a/apps/app/src/app/lib/skill-upload.ts b/apps/app/src/app/lib/skill-upload.tsnew file mode 100644index 00000000..1412fe7c--- /dev/null+++ b/apps/app/src/app/lib/skill-upload.ts@@ -0,0 +1,382 @@+/**+ * Reading a skill for upload: a folder (picker, `<input webkitdirectory>`,+ * drag and drop), a .zip, or loose files. Everything becomes a flat list of+ * `/`-separated relative paths + bytes that the local server validates and+ * installs (`POST /workspace/:id/skills/bundle`), so the rules live in one+ * place. The client only does what the server cannot see or should not have+ * to receive: it refuses zip entries that are symlinks or encrypted, skips OS+ * and VCS litter before reading it, and stops at the same caps early.+ */++/** Mirrors apps/server/src/skill-bundle.ts SKILL_BUNDLE_LIMITS. */+export const SKILL_UPLOAD_LIMITS = {+ maxFiles: 200,+ maxRawEntries: 2_000,+ maxFileBytes: 10 * 1024 * 1024,+ maxTotalBytes: 25 * 1024 * 1024,+ /** A .zip larger than this is refused before it is read. */+ maxZipBytes: 30 * 1024 * 1024,+} as const;++export type SkillUploadFile = {+ path: string;+ contentBase64: string;+ executable?: boolean;+};++export type SkillUploadSource = {+ kind: "folder" | "zip" | "files";+ /** What the user picked, for display (folder or archive name). */+ label: string;+ files: SkillUploadFile[];+ /** Litter dropped before upload (.DS_Store, __MACOSX/, .git/, node_modules/, ...). */+ skipped: string[];+};++export class SkillUploadError extends Error {}++const JUNK_NAMES = new Set([".ds_store", "thumbs.db", "desktop.ini", ".localized"]);+const JUNK_DIRS = new Set(["__macosx", ".git", "node_modules", "__pycache__", ".svn", ".hg", ".venv", ".idea", ".vscode"]);++export function isSkillUploadJunk(path: string): boolean {+ const parts = path.split("/").filter(Boolean);+ const name = parts.at(-1)?.toLowerCase() ?? "";+ if (JUNK_NAMES.has(name) || name.startsWith("._") || name.endsWith(".pyc")) return true;+ return parts.slice(0, -1).some((part) => JUNK_DIRS.has(part.toLowerCase()));+}++export function isJunkDirectoryName(name: string): boolean {+ return JUNK_DIRS.has(name.toLowerCase());+}++export function formatUploadBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;+ return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`;+}++export function bytesToBase64(bytes: Uint8Array): string {+ let binary = "";+ const chunk = 0x8000;+ for (let index = 0; index < bytes.length; index += chunk) {+ binary += String.fromCharCode(...bytes.subarray(index, index + chunk));+ }+ return btoa(binary);+}++export function isZipName(name: string): boolean {+ return /\.zip$/i.test(name.trim());+}++/** Running totals shared by every reader so a huge pick stops early. */+class Budget {+ entries = 0;+ files = 0;+ bytes = 0;++ entry() {+ this.entries += 1;+ if (this.entries > SKILL_UPLOAD_LIMITS.maxRawEntries) {+ throw new SkillUploadError(`That has more than ${SKILL_UPLOAD_LIMITS.maxRawEntries} entries. A skill holds at most ${SKILL_UPLOAD_LIMITS.maxFiles} files.`);+ }+ }++ file(path: string, size: number) {+ if (size > SKILL_UPLOAD_LIMITS.maxFileBytes) {+ throw new SkillUploadError(`${path} is larger than ${formatUploadBytes(SKILL_UPLOAD_LIMITS.maxFileBytes)}.`);+ }+ this.files += 1;+ this.bytes += size;+ if (this.files > SKILL_UPLOAD_LIMITS.maxFiles) {+ throw new SkillUploadError(`A skill holds at most ${SKILL_UPLOAD_LIMITS.maxFiles} files.`);+ }+ if (this.bytes > SKILL_UPLOAD_LIMITS.maxTotalBytes) {+ throw new SkillUploadError(`A skill holds at most ${formatUploadBytes(SKILL_UPLOAD_LIMITS.maxTotalBytes)} of files.`);+ }+ }+}++async function fileEntry(path: string, file: Blob, budget: Budget): Promise<SkillUploadFile> {+ budget.file(path, file.size);+ const bytes = new Uint8Array(await file.arrayBuffer());+ return { path, contentBase64: bytesToBase64(bytes) };+}++// --- <input webkitdirectory> / <input multiple> -----------------------------------++type RelativeFile = File & { webkitRelativePath?: string };++/**+ * Files from a directory input (paths from `webkitRelativePath`, which start+ * with the picked folder's name) or a plain multi-file input (bare names).+ */+export async function readSkillFromFileList(list: ArrayLike<RelativeFile>): Promise<SkillUploadSource> {+ const files = Array.from(list);+ if (files.length === 1 && isZipName(files[0]!.name) && !files[0]!.webkitRelativePath) {+ return readSkillFromZipFile(files[0]!);+ }+ const budget = new Budget();+ const out: SkillUploadFile[] = [];+ const skipped: string[] = [];+ const folder = files.find((file) => file.webkitRelativePath)?.webkitRelativePath?.split("/")[0] ?? "";+ for (const file of files) {+ budget.entry();+ const path = (file.webkitRelativePath || file.name).replace(/^\/+/, "");+ if (isSkillUploadJunk(path)) {+ skipped.push(path);+ continue;+ }+ out.push(await fileEntry(path, file, budget));+ }+ return { kind: folder ? "folder" : "files", label: folder || `${out.length} files`, files: out, skipped };+}++// --- drag and drop ------------------------------------------------------------------++type EntryLike = {+ isFile: boolean;+ isDirectory: boolean;+ name: string;+ fullPath: string;+ file?: (success: (file: File) => void, failure?: (error: unknown) => void) => void;+ createReader?: () => { readEntries: (success: (entries: EntryLike[]) => void, failure?: (error: unknown) => void) => void };+};++function entryFile(entry: EntryLike): Promise<File> {+ return new Promise((resolve, reject) => entry.file!(resolve, reject));+}++async function readAllEntries(entry: EntryLike): Promise<EntryLike[]> {+ const reader = entry.createReader!();+ const all: EntryLike[] = [];+ // readEntries returns batches (100 in Chromium) until an empty one.+ for (;;) {+ const batch = await new Promise<EntryLike[]>((resolve, reject) => reader.readEntries(resolve, reject));+ if (!batch.length) return all;+ all.push(...batch);+ }+}++/** What a drop carries: a zip, a folder (with its local path on the desktop), or loose files. */+export type DroppedSkill =+ | { kind: "zip"; file: File }+ | { kind: "folder"; entry: EntryLike; file: File | null }+ | { kind: "files"; entries: EntryLike[]; files: File[] };++export function classifyDrop(dataTransfer: DataTransfer): DroppedSkill | null {+ const items = Array.from(dataTransfer.items ?? []).filter((item) => item.kind === "file");+ const entries: EntryLike[] = [];+ for (const item of items) {+ const entry = (item.webkitGetAsEntry?.() ?? null) as unknown as EntryLike | null;+ if (entry) entries.push(entry);+ }+ const files = Array.from(dataTransfer.files ?? []);+ if (files.length === 1 && isZipName(files[0]!.name) && !(entries[0]?.isDirectory)) return { kind: "zip", file: files[0]! };+ if (entries.length === 1 && entries[0]!.isDirectory) return { kind: "folder", entry: entries[0]!, file: files[0] ?? null };+ if (entries.some((entry) => entry.isDirectory)) {+ throw new SkillUploadError("Drop one skill folder (or its .zip) at a time.");+ }+ if (!files.length) return null;+ return { kind: "files", entries, files };+}++export async function readSkillFromDroppedFolder(root: EntryLike): Promise<SkillUploadSource> {+ const budget = new Budget();+ const out: SkillUploadFile[] = [];+ const skipped: string[] = [];+ const prefix = root.fullPath.replace(/\/+$/, "");+ const relativeOf = (entry: EntryLike) => `${root.name}${entry.fullPath.slice(prefix.length)}`;+ const walk = async (dir: EntryLike) => {+ for (const entry of await readAllEntries(dir)) {+ budget.entry();+ const path = relativeOf(entry);+ if (entry.isDirectory) {+ if (isJunkDirectoryName(entry.name)) {+ skipped.push(`${path}/`);+ continue;+ }+ await walk(entry);+ continue;+ }+ if (isSkillUploadJunk(path)) {+ skipped.push(path);+ continue;+ }+ out.push(await fileEntry(path, await entryFile(entry), budget));+ }+ };+ await walk(root);+ return { kind: "folder", label: root.name, files: out, skipped };+}++// --- .zip -----------------------------------------------------------------------------++const EOCD = 0x06054b50;+const CENTRAL = 0x02014b50;+const LOCAL = 0x04034b50;+const S_IFMT = 0o170000;+const S_IFLNK = 0o120000;+const S_IFDIR = 0o040000;++type ZipEntry = {+ name: string;+ method: number;+ compressedSize: number;+ size: number;+ localOffset: number;+ executable: boolean;+};++async function inflateRaw(data: Uint8Array, expected: number, name: string): Promise<Uint8Array> {+ const stream = new Blob([data as BlobPart]).stream().pipeThrough(new DecompressionStream("deflate-raw"));+ const reader = stream.getReader();+ const out = new Uint8Array(expected);+ let offset = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (offset + value.length > expected) {+ await reader.cancel().catch(() => undefined);+ throw new SkillUploadError(`${name} in the .zip is larger than it claims to be.`);+ }+ out.set(value, offset);+ offset += value.length;+ }+ if (offset !== expected) throw new SkillUploadError(`${name} in the .zip is damaged.`);+ return out;+}++/** Parses a .zip in memory (no ZIP64, no encryption), refusing symlink entries. */+export async function readSkillFromZipBytes(bytes: Uint8Array, label = "archive.zip"): Promise<SkillUploadSource> {+ if (bytes.length > SKILL_UPLOAD_LIMITS.maxZipBytes) {+ throw new SkillUploadError(`The .zip is larger than ${formatUploadBytes(SKILL_UPLOAD_LIMITS.maxZipBytes)}.`);+ }+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let eocd = -1;+ for (let index = bytes.length - 22; index >= Math.max(0, bytes.length - 22 - 0xffff); index -= 1) {+ if (view.getUint32(index, true) === EOCD) {+ eocd = index;+ break;+ }+ }+ if (eocd < 0) throw new SkillUploadError("That file is not a .zip archive.");+ const count = view.getUint16(eocd + 10, true);+ const centralSize = view.getUint32(eocd + 12, true);+ const centralOffset = view.getUint32(eocd + 16, true);+ if (count === 0xffff || centralOffset === 0xffffffff || centralSize === 0xffffffff) {+ throw new SkillUploadError("ZIP64 archives are not supported. Upload the folder instead.");+ }+ if (centralOffset + centralSize > bytes.length) throw new SkillUploadError("The .zip is damaged.");++ const decoder = new TextDecoder("utf-8");+ const entries: ZipEntry[] = [];+ const skipped: string[] = [];+ const links: string[] = [];+ const budget = new Budget();+ let cursor = centralOffset;+ for (let index = 0; index < count; index += 1) {+ if (cursor + 46 > bytes.length || view.getUint32(cursor, true) !== CENTRAL) throw new SkillUploadError("The .zip is damaged.");+ budget.entry();+ const madeBy = view.getUint16(cursor + 4, true);+ const flags = view.getUint16(cursor + 8, true);+ const method = view.getUint16(cursor + 10, true);+ const compressedSize = view.getUint32(cursor + 20, true);+ const size = view.getUint32(cursor + 24, true);+ const nameLength = view.getUint16(cursor + 28, true);+ const extraLength = view.getUint16(cursor + 30, true);+ const commentLength = view.getUint16(cursor + 32, true);+ const external = view.getUint32(cursor + 38, true);+ const localOffset = view.getUint32(cursor + 42, true);+ const name = decoder.decode(bytes.subarray(cursor + 46, cursor + 46 + nameLength));+ cursor += 46 + nameLength + extraLength + commentLength;++ const unixMode = madeBy >> 8 === 3 ? external >>> 16 : 0;+ const isDir = name.endsWith("/") || (unixMode & S_IFMT) === S_IFDIR || (madeBy >> 8 === 0 && (external & 0x10) !== 0);+ if (isDir) continue;+ if ((unixMode & S_IFMT) === S_IFLNK) {+ links.push(name);+ continue;+ }+ if (isSkillUploadJunk(name)) {+ skipped.push(name);+ continue;+ }+ if (flags & 0x1) throw new SkillUploadError("Encrypted .zip archives are not supported.");+ if (method !== 0 && method !== 8) throw new SkillUploadError(`${name} uses an unsupported .zip compression method.`);+ budget.file(name, size);+ entries.push({ name, method, compressedSize, size, localOffset, executable: (unixMode & 0o111) !== 0 });+ }+ if (links.length) {+ throw new SkillUploadError(`Skills cannot contain links (symlinks). Replace them with the real files: ${links.slice(0, 10).join(", ")}`);+ }++ const files: SkillUploadFile[] = [];+ for (const entry of entries) {+ const at = entry.localOffset;+ if (at + 30 > bytes.length || view.getUint32(at, true) !== LOCAL) throw new SkillUploadError("The .zip is damaged.");+ const start = at + 30 + view.getUint16(at + 26, true) + view.getUint16(at + 28, true);+ const data = bytes.subarray(start, start + entry.compressedSize);+ if (data.length !== entry.compressedSize) throw new SkillUploadError("The .zip is damaged.");+ let content: Uint8Array;+ if (entry.method === 0) {+ if (entry.compressedSize !== entry.size) throw new SkillUploadError("The .zip is damaged.");+ content = data;+ } else {+ content = await inflateRaw(data, entry.size, entry.name);+ }+ files.push({ path: entry.name, contentBase64: bytesToBase64(content), ...(entry.executable ? { executable: true } : {}) });+ }+ return { kind: "zip", label, files, skipped };+}++export async function readSkillFromZipFile(file: File): Promise<SkillUploadSource> {+ if (file.size > SKILL_UPLOAD_LIMITS.maxZipBytes) {+ throw new SkillUploadError(`The .zip is larger than ${formatUploadBytes(SKILL_UPLOAD_LIMITS.maxZipBytes)}.`);+ }+ return readSkillFromZipBytes(new Uint8Array(await file.arrayBuffer()), file.name);+}++// --- server payloads -----------------------------------------------------------------++export type SkillBundleSummary = {+ name: string;+ description: string;+ files: Array<{ path: string; size: number; executable: boolean }>;+ skipped: string[];+ strippedRoot: string | null;+ totalBytes: number;+};++export type SkillConflict = {+ name: string;+ path: string;+ scope: "project" | "global";+ replaceable: boolean;+};++export type SkillBundlePreview = SkillBundleSummary & { conflict: SkillConflict | null };++export type SkillBundleInstallResult = SkillBundleSummary & {+ path: string;+ dir: string;+ action: "added" | "updated";+};++export type SkillFileEntry = { path: string; size: number; executable: boolean; kind: "file" | "symlink" | "other" };++export type SkillFileTree = { name: string; dir: string; files: SkillFileEntry[]; truncated: boolean };++/** Groups a flat path list into folders for the preview ("" = the skill root). */+export function groupSkillFiles<T extends { path: string }>(files: T[]): Array<{ folder: string; files: T[] }> {+ const groups = new Map<string, T[]>();+ for (const file of files) {+ const slash = file.path.lastIndexOf("/");+ const folder = slash < 0 ? "" : file.path.slice(0, slash);+ const list = groups.get(folder) ?? [];+ list.push(file);+ groups.set(folder, list);+ }+ return [...groups.entries()]+ .sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b)))+ .map(([folder, list]) => ({ folder, files: list }));+}diff --git a/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsx b/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsxindex 442afe20..10934913 100644--- a/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsx+++ b/apps/app/src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsx@@ -15,6 +15,8 @@ import { Button } from "@/components/ui/button";import { Textarea } from "@/components/ui/textarea";import { t } from "../../../../i18n";import { TextInput } from "../../../design-system/text-input";+import type { SkillBundleInstallResult, SkillBundlePreview, SkillUploadFile } from "../../../../app/lib/skill-upload";+import { SkillUploadPane } from "./skill-upload-pane";/*** Local workspace skill authoring.@@ -25,6 +27,10 @@ import { TextInput } from "../../../design-system/text-input";* `.opencode/skills/<name>/SKILL.md` through the local server* (`POST /workspace/:id/skills`), which validates, audits, and emits the reload* event the engine needs.+ *+ * "Upload folder or .zip" installs a whole skill folder (SKILL.md plus its+ * scripts/, references/, assets/ ...) through `POST /workspace/:id/skills/bundle`+ * after a server-side preview; see skill-upload-pane.tsx.*//** Mirrors the server: kebab-case, 1-64 chars (validators.ts validateSkillName). */@@ -124,8 +130,17 @@ export type LibraryAddWorkspaceSkillModalProps = {onCreate: (draft: WorkspaceSkillDraft) => Promise<void>;/** Called after a successful create with the final skill name. */onCreated?: (name: string) => void;+ /** Folder/.zip upload; the Upload tab is offered only when both are given. */+ onPreviewBundle?: (payload: { files: SkillUploadFile[]; name?: string }) => Promise<SkillBundlePreview>;+ onInstallBundle?: (payload: {+ files: SkillUploadFile[];+ name?: string;+ onConflict?: "fail" | "replace";+ }) => Promise<SkillBundleInstallResult>;};+export type WorkspaceSkillAddMode = "write" | "upload";+export function LibraryAddWorkspaceSkillModal(props: LibraryAddWorkspaceSkillModalProps) {const [name, setName] = useState("");const [nameTouched, setNameTouched] = useState(false);@@ -133,9 +148,14 @@ export function LibraryAddWorkspaceSkillModal(props: LibraryAddWorkspaceSkillModconst [content, setContent] = useState("");const [error, setError] = useState<string | null>(null);const [submitting, setSubmitting] = useState(false);+ const [mode, setMode] = useState<WorkspaceSkillAddMode>("write");+ const [uploading, setUploading] = useState(false);+ const uploadAvailable = Boolean(props.onPreviewBundle && props.onInstallBundle);useEffect(() => {if (!props.open) return;+ setMode("write");+ setUploading(false);setName("");setNameTouched(false);setDescription("");@@ -145,7 +165,7 @@ export function LibraryAddWorkspaceSkillModal(props: LibraryAddWorkspaceSkillMod}, [props.open]);const handleClose = () => {- if (submitting) return;+ if (submitting || uploading) return;props.onClose();};@@ -200,6 +220,42 @@ export function LibraryAddWorkspaceSkillModal(props: LibraryAddWorkspaceSkillMod)}</DialogDescription></DialogHeader>+ {uploadAvailable ? (+ <div role="group" aria-label={label("extensions.skill_add_mode", "How to add the skill")} className="flex gap-1.5" data-testid="workspace-skill-mode">+ {([+ ["write", label("extensions.skill_add_mode_write", "Write SKILL.md")],+ ["upload", label("extensions.skill_add_mode_upload", "Upload folder or .zip")],+ ] as const).map(([value, text]) => (+ <button+ key={value}+ type="button"+ aria-pressed={mode === value}+ disabled={submitting || uploading}+ className={`rounded-lg px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-60 ${+ mode === value ? "bg-foreground text-background" : "bg-dls-hover text-dls-secondary hover:text-dls-text"+ }`}+ onClick={() => {+ setError(null);+ setMode(value);+ }}+ >+ {text}+ </button>+ ))}+ </div>+ ) : null}+ {uploadAvailable && mode === "upload" ? (+ <SkillUploadPane+ disabled={props.busy}+ onPreview={props.onPreviewBundle!}+ onInstall={props.onInstallBundle!}+ onBusyChange={setUploading}+ onInstalled={(result) => {+ props.onCreated?.(result.name);+ props.onClose();+ }}+ />+ ) : (<formclassName="flex flex-col gap-4"onSubmit={(event) => {@@ -264,6 +320,7 @@ export function LibraryAddWorkspaceSkillModal(props: LibraryAddWorkspaceSkillMod</Button></DialogFooter></form>+ )}</DialogContent></Dialog>);diff --git a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsxindex c3b9d709..0bda3e46 100644--- a/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/mcp-view.tsx@@ -32,6 +32,13 @@ import { evaluateEnablement } from "../../../../app/enablement";import type { EnablementResult } from "../../../../app/extensions";import type { CloudImportedPlugin, CloudImportedPluginFile } from "../../../../app/cloud/import-state";import { ExtensionCard, type ExtensionLayout } from "../../../design-system/extension-card";+import { SkillFilesPanel } from "./skill-files-panel";+import type {+ SkillBundleInstallResult,+ SkillBundlePreview,+ SkillFileTree,+ SkillUploadFile,+} from "../../../../app/lib/skill-upload";import { ExtensionDetailModal } from "../../../design-system/extension-detail-modal";import {isOrgMcpConnectionReady,@@ -237,6 +244,17 @@ export type McpViewProps = {* with a message when the server refuses the skill.*/createWorkspaceSkill?: (input: WorkspaceSkillDraft) => Promise<void>;+ /** Skill folder / .zip upload through the local server (preview, then install). */+ previewSkillBundle?: (payload: { files: SkillUploadFile[]; name?: string }) => Promise<SkillBundlePreview>;+ installSkillBundle?: (payload: {+ files: SkillUploadFile[];+ name?: string;+ onConflict?: "fail" | "replace";+ }) => Promise<SkillBundleInstallResult>;+ /** Helper files and SKILL.md of an installed workspace skill. */+ listSkillFiles?: (name: string) => Promise<SkillFileTree>;+ updateSkillFiles?: (name: string, payload: { add?: SkillUploadFile[]; remove?: string[] }) => Promise<SkillFileTree>;+ saveSkillContent?: (input: { name: string; content: string }) => Promise<void>;/** Reload composer command and agent lists after a Library create. */onLibraryListsRefresh?: () => Promise<void> | void;onRefresh?: () => void;@@ -1112,7 +1130,22 @@ export function McpView(props: McpViewProps) {instructionsHint={t("extensions.detail_instructions_skill_hint")}openFileLabel={t("extensions.detail_open_skill")}contentPreview={detailSkillContent ?? undefined}- configSlot={openInDenAction({ id: detailSkill.path })}+ configSlot={(+ <>+ {openInDenAction({ id: detailSkill.path })}+ {detailSkill.origin !== "omnirush-connect" && props.listSkillFiles && props.updateSkillFiles && props.saveSkillContent ? (+ <SkillFilesPanel+ key={detailSkill.name}+ name={detailSkill.name}+ listFiles={props.listSkillFiles}+ updateFiles={props.updateSkillFiles}+ content={detailSkillContent}+ saveContent={props.saveSkillContent}+ onContentSaved={(content) => setDetailSkillContent(content)}+ />+ ) : null}+ </>+ )}onReveal={detailSkill.path && detailSkill.origin !== "omnirush-connect" ? () => {void revealDesktopItemInDir(detailSkill.path);} : undefined}@@ -1685,6 +1718,8 @@ export function McpView(props: McpViewProps) {busy={props.busy}onClose={() => setWorkspaceSkillModalOpen(false)}onCreate={props.createWorkspaceSkill}+ onPreviewBundle={props.previewSkillBundle}+ onInstallBundle={props.installSkillBundle}onCreated={() => {// The store's skill refresh lands the new card; keep the user on// the skills list so it appears in place.diff --git a/apps/app/src/react-app/domains/settings/pages/skill-files-panel.tsx b/apps/app/src/react-app/domains/settings/pages/skill-files-panel.tsxnew file mode 100644index 00000000..d3bf8661--- /dev/null+++ b/apps/app/src/react-app/domains/settings/pages/skill-files-panel.tsx@@ -0,0 +1,275 @@+/** @jsxImportSource react */+import { useCallback, useEffect, useRef, useState } from "react";+import { FilePlus, FileText, Folder, FolderPlus, Link2, Loader2, Pencil, Terminal, Trash2 } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Card } from "@/components/ui/card";+import { Textarea } from "@/components/ui/textarea";+import { t } from "../../../../i18n";+import {+ formatUploadBytes,+ groupSkillFiles,+ readSkillFromFileList,+ type SkillFileTree,+ type SkillUploadFile,+} from "../../../../app/lib/skill-upload";++/**+ * Files of an installed workspace skill, shown in its detail view: the+ * SKILL.md editor (saved through the regular skill upsert, which leaves helper+ * files alone) and the helper files, which can be added (into the root or a+ * folder such as scripts/) and removed. The local server applies the same+ * path, credential and size rules as a fresh upload.+ */++export type SkillFilesPanelProps = {+ name: string;+ listFiles: (name: string) => Promise<SkillFileTree>;+ updateFiles: (name: string, payload: { add?: SkillUploadFile[]; remove?: string[] }) => Promise<SkillFileTree>;+ /** Current SKILL.md text (as the detail view loaded it). */+ content: string | null;+ saveContent: (input: { name: string; content: string }) => Promise<void>;+ onContentSaved?: (content: string) => void;+};++function label(key: string, fallback: string): string {+ const value = t(key);+ return value === key ? fallback : value;+}++const TARGET_FOLDERS = ["", "scripts", "references", "assets"] as const;++/** Places picked files under a target folder ("" = the skill root). */+export function placeSkillFiles(files: SkillUploadFile[], folder: string): SkillUploadFile[] {+ const prefix = folder.trim().replace(/^\/+|\/+$/g, "");+ return files.map((file) => ({ ...file, path: prefix ? `${prefix}/${file.path}` : file.path }));+}++export function SkillFilesPanel(props: SkillFilesPanelProps) {+ const [tree, setTree] = useState<SkillFileTree | null>(null);+ const [hidden, setHidden] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [working, setWorking] = useState(false);+ const [target, setTarget] = useState<string>("scripts");+ const [confirmRemove, setConfirmRemove] = useState<string | null>(null);+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState("");+ const filesInput = useRef<HTMLInputElement | null>(null);+ const folderInput = useRef<HTMLInputElement | null>(null);++ const { listFiles, name } = props;+ const refresh = useCallback(async () => {+ try {+ setTree(await listFiles(name));+ setHidden(false);+ } catch (cause) {+ // Global, plugin and Connect skills are not editable here.+ if ((cause as { status?: number } | null)?.status === 404) setHidden(true);+ else setError(cause instanceof Error ? cause.message : String(cause));+ }+ }, [listFiles, name]);++ useEffect(() => {+ setTree(null);+ setEditing(false);+ setError(null);+ void refresh();+ }, [refresh]);++ if (hidden) return null;++ const run = async (action: () => Promise<void>) => {+ if (working) return;+ setWorking(true);+ setError(null);+ try {+ await action();+ } catch (cause) {+ const paths = (cause as { details?: { paths?: unknown } } | null)?.details?.paths;+ const message = cause instanceof Error ? cause.message : String(cause);+ setError(Array.isArray(paths) && paths.length && !message.includes(String(paths[0])) ? `${message}: ${paths.join(", ")}` : message);+ } finally {+ setWorking(false);+ }+ };++ const addFrom = (list: FileList | null) => {+ if (!list?.length) return;+ const files = Array.from(list);+ void run(async () => {+ const read = await readSkillFromFileList(files);+ if (read.kind === "zip") throw new Error(label("extensions.skill_files_zip", "To install a .zip, use Add skill > Upload folder or .zip."));+ setTree(await props.updateFiles(props.name, { add: placeSkillFiles(read.files, target) }));+ });+ };++ const groups = tree ? groupSkillFiles(tree.files) : [];+ const helperCount = tree ? tree.files.filter((file) => file.path !== "SKILL.md").length : 0;++ return (+ <Card variant="outline" size="sm" className="overflow-hidden py-0" data-testid="skill-files-panel">+ <input+ ref={filesInput}+ type="file"+ multiple+ className="hidden"+ data-testid="skill-files-add-input"+ onChange={(event) => {+ addFrom(event.currentTarget.files);+ event.currentTarget.value = "";+ }}+ />+ <input+ ref={(node) => {+ folderInput.current = node;+ node?.setAttribute("webkitdirectory", "");+ }}+ type="file"+ multiple+ className="hidden"+ onChange={(event) => {+ addFrom(event.currentTarget.files);+ event.currentTarget.value = "";+ }}+ />+ <div className="flex items-center justify-between gap-2 border-b border-border px-4 py-3">+ <div className="text-sm font-semibold text-card-foreground">+ {label("extensions.skill_files_title", "Skill files")}+ {tree ? <span className="ml-2 text-xs font-normal text-muted-foreground">{helperCount} helper {helperCount === 1 ? "file" : "files"}</span> : null}+ </div>+ {working ? <Loader2 size={14} className="animate-spin text-muted-foreground" /> : null}+ </div>++ {editing ? (+ <div className="flex flex-col gap-2 border-b border-border px-4 py-3">+ <Textarea+ rows={14}+ className="min-h-56 font-mono text-xs leading-5"+ value={draft}+ disabled={working}+ data-testid="skill-md-editor"+ onChange={(event) => setDraft(event.currentTarget.value)}+ />+ <div className="flex justify-end gap-2">+ <Button variant="outline" size="sm" type="button" disabled={working} onClick={() => setEditing(false)}>+ {t("common.cancel")}+ </Button>+ <Button+ size="sm"+ type="button"+ disabled={working || !draft.trim()}+ data-testid="skill-md-save"+ onClick={() => void run(async () => {+ await props.saveContent({ name: props.name, content: draft });+ props.onContentSaved?.(draft);+ setEditing(false);+ setTree(await props.listFiles(props.name));+ })}+ >+ {label("extensions.skill_md_save", "Save SKILL.md")}+ </Button>+ </div>+ </div>+ ) : null}++ <div className="max-h-72 overflow-y-auto">+ {!tree ? (+ <p className="px-4 py-3 text-sm text-muted-foreground">{t("common.loading") === "common.loading" ? "Loading…" : t("common.loading")}</p>+ ) : groups.map((group) => (+ <div key={group.folder || "."}>+ {group.folder ? (+ <div className="flex items-center gap-1.5 border-b border-border bg-muted/40 px-4 py-1.5 font-mono text-[11px] text-muted-foreground">+ <Folder size={12} /> {group.folder}/+ </div>+ ) : null}+ {group.files.map((file) => {+ const isSkillMd = file.path === "SKILL.md";+ return (+ <div key={file.path} className="group flex items-center gap-2 border-b border-border px-4 py-1.5" data-testid="skill-file-row">+ {file.kind === "symlink" ? <Link2 size={12} className="text-amber-11" /> : file.executable ? <Terminal size={12} className="text-muted-foreground" /> : <FileText size={12} className="text-muted-foreground" />}+ <span className={`min-w-0 flex-1 truncate font-mono text-xs ${group.folder ? "pl-3" : ""}`} title={file.path}>+ {file.path.slice(group.folder ? group.folder.length + 1 : 0)}+ {file.kind === "symlink" ? <span className="ml-2 text-[10px] text-amber-11">link (not uploaded by the desktop)</span> : null}+ </span>+ <span className="text-[11px] tabular-nums text-muted-foreground">{formatUploadBytes(file.size)}</span>+ {isSkillMd ? (+ <Button+ variant="ghost"+ size="xs"+ type="button"+ disabled={working || props.content === null}+ data-testid="skill-md-edit"+ onClick={() => {+ setDraft(props.content ?? "");+ setEditing(true);+ }}+ >+ <Pencil size={12} /> {label("extensions.skill_md_edit", "Edit")}+ </Button>+ ) : confirmRemove === file.path ? (+ <span className="flex items-center gap-1">+ <Button+ variant="destructive"+ size="xs"+ type="button"+ disabled={working}+ data-testid="skill-file-remove-confirm"+ onClick={() => void run(async () => {+ setTree(await props.updateFiles(props.name, { remove: [file.path] }));+ setConfirmRemove(null);+ })}+ >+ {label("extensions.skill_file_remove_confirm", "Remove")}+ </Button>+ <Button variant="ghost" size="xs" type="button" onClick={() => setConfirmRemove(null)}>+ {t("common.cancel")}+ </Button>+ </span>+ ) : (+ <Button+ variant="ghost"+ size="icon-xs"+ type="button"+ aria-label={`Remove ${file.path}`}+ disabled={working}+ data-testid="skill-file-remove"+ onClick={() => setConfirmRemove(file.path)}+ >+ <Trash2 size={12} />+ </Button>+ )}+ </div>+ );+ })}+ </div>+ ))}+ </div>++ <div className="flex flex-wrap items-center gap-2 px-4 py-3">+ <label className="flex items-center gap-1.5 text-xs text-muted-foreground">+ {label("extensions.skill_files_into", "Add into")}+ <select+ className="rounded-md border border-border bg-transparent px-1.5 py-1 font-mono text-xs text-foreground"+ value={target}+ disabled={working}+ data-testid="skill-files-target"+ onChange={(event) => setTarget(event.currentTarget.value)}+ >+ {TARGET_FOLDERS.map((folder) => (+ <option key={folder || "root"} value={folder}>{folder ? `${folder}/` : "skill root"}</option>+ ))}+ </select>+ </label>+ <Button variant="outline" size="sm" type="button" disabled={working || !tree} onClick={() => filesInput.current?.click()} data-testid="skill-files-add">+ <FilePlus size={13} /> {label("extensions.skill_files_add", "Add files")}+ </Button>+ <Button variant="outline" size="sm" type="button" disabled={working || !tree} onClick={() => folderInput.current?.click()}>+ <FolderPlus size={13} /> {label("extensions.skill_files_add_folder", "Add folder")}+ </Button>+ </div>+ {error ? (+ <p role="alert" className="border-t border-border px-4 py-2 text-xs text-red-11" data-testid="skill-files-error">{error}</p>+ ) : null}+ </Card>+ );+}diff --git a/apps/app/src/react-app/domains/settings/pages/skill-upload-pane.tsx b/apps/app/src/react-app/domains/settings/pages/skill-upload-pane.tsxnew file mode 100644index 00000000..9b53baad--- /dev/null+++ b/apps/app/src/react-app/domains/settings/pages/skill-upload-pane.tsx@@ -0,0 +1,366 @@+/** @jsxImportSource react */+import { useRef, useState, type DragEvent, type ReactNode } from "react";+import { AlertTriangle, FileArchive, FileText, Folder, FolderUp, Loader2, Terminal, X } from "lucide-react";++import { Button } from "@/components/ui/button";+import { t } from "../../../../i18n";+import {+ classifyDrop,+ formatUploadBytes,+ groupSkillFiles,+ readSkillFromDroppedFolder,+ readSkillFromFileList,+ readSkillFromZipFile,+ SKILL_UPLOAD_LIMITS,+ SkillUploadError,+ type SkillBundleInstallResult,+ type SkillBundlePreview,+ type SkillUploadFile,+ type SkillUploadSource,+} from "../../../../app/lib/skill-upload";+import { electronLocalPathForFile, pickDirectory, readSkillFolder } from "../../../../app/lib/desktop";+import { isDesktopRuntime } from "../../../../app/lib/runtime-env";+import { TextInput } from "../../../design-system/text-input";++/**+ * "Upload folder or .zip" half of the workspace Add skill modal. A pick or a+ * drop is read into relative paths + bytes, the local server previews it with+ * the same checks the install runs, and the user sees every file (and any name+ * collision) before anything is written.+ */++export type SkillUploadPaneProps = {+ disabled?: boolean;+ onPreview: (payload: { files: SkillUploadFile[]; name?: string }) => Promise<SkillBundlePreview>;+ onInstall: (payload: { files: SkillUploadFile[]; name?: string; onConflict?: "fail" | "replace" }) => Promise<SkillBundleInstallResult>;+ onInstalled: (result: SkillBundleInstallResult) => void;+ onBusyChange?: (busy: boolean) => void;+};++function label(key: string, fallback: string): string {+ const value = t(key);+ return value === key ? fallback : value;+}++function errorText(cause: unknown): string {+ return cause instanceof Error && cause.message ? cause.message : t("common.something_went_wrong");+}++/** Reads a local folder through the desktop (links refused there), else null. */+async function readDesktopFolder(path: string): Promise<SkillUploadSource> {+ const result = await readSkillFolder(path);+ return { kind: "folder", label: result.name, files: result.files, skipped: result.skipped };+}++export function SkillUploadPane(props: SkillUploadPaneProps) {+ const folderInput = useRef<HTMLInputElement | null>(null);+ const zipInput = useRef<HTMLInputElement | null>(null);+ const [source, setSource] = useState<SkillUploadSource | null>(null);+ const [preview, setPreview] = useState<SkillBundlePreview | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [errorPaths, setErrorPaths] = useState<string[]>([]);+ const [working, setWorking] = useState<null | "reading" | "checking" | "installing">(null);+ const [dragging, setDragging] = useState(false);+ const [resolution, setResolution] = useState<"replace" | "rename">("rename");+ const [rename, setRename] = useState("");++ const busy = working !== null || props.disabled === true;+ const setBusy = (next: typeof working) => {+ setWorking(next);+ props.onBusyChange?.(next !== null);+ };++ const reset = () => {+ setSource(null);+ setPreview(null);+ setError(null);+ setErrorPaths([]);+ setRename("");+ };++ const fail = (cause: unknown) => {+ setError(errorText(cause));+ const details = (cause as { details?: { paths?: unknown } } | null)?.details;+ const message = errorText(cause);+ const paths = Array.isArray(details?.paths) ? details.paths.map(String).slice(0, 20) : [];+ // The server names up to ten paths in the message itself; list them only when it did not.+ setErrorPaths(paths.every((path) => message.includes(path)) ? [] : paths);+ };++ const load = async (read: () => Promise<SkillUploadSource | null>) => {+ if (busy) return;+ reset();+ setBusy("reading");+ try {+ const next = await read();+ if (!next) return;+ if (!next.files.length) throw new SkillUploadError(label("extensions.skill_upload_empty", "Nothing to upload: the folder is empty (after skipping system files)."));+ setSource(next);+ setBusy("checking");+ const checked = await props.onPreview({ files: next.files });+ setPreview(checked);+ setResolution(checked.conflict?.replaceable ? "replace" : "rename");+ setRename(checked.conflict ? `${checked.name}-2`.slice(0, 64) : "");+ } catch (cause) {+ fail(cause);+ } finally {+ setBusy(null);+ }+ };++ const chooseFolder = () => {+ if (isDesktopRuntime()) {+ void load(async () => {+ const picked = await pickDirectory({ title: label("extensions.skill_upload_pick_folder", "Choose a skill folder") });+ const path = typeof picked === "string" ? picked : Array.isArray(picked) ? picked[0] : null;+ return path ? readDesktopFolder(path) : null;+ });+ return;+ }+ folderInput.current?.click();+ };++ const onDrop = (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ setDragging(false);+ if (busy) return;+ let dropped: ReturnType<typeof classifyDrop>;+ try {+ dropped = classifyDrop(event.dataTransfer);+ } catch (cause) {+ fail(cause);+ return;+ }+ if (!dropped) return;+ const drop = dropped;+ void load(async () => {+ if (drop.kind === "zip") return readSkillFromZipFile(drop.file);+ if (drop.kind === "folder") {+ const local = drop.file ? electronLocalPathForFile(drop.file) : null;+ return local ? readDesktopFolder(local) : readSkillFromDroppedFolder(drop.entry);+ }+ return readSkillFromFileList(drop.files);+ });+ };++ const install = async () => {+ if (!source || !preview || busy) return;+ const conflict = preview.conflict;+ const name = conflict && resolution === "rename" ? rename.trim() : undefined;+ if (conflict && resolution === "rename" && !name) {+ setError(label("extensions.skill_upload_rename_required", "Enter a new name for the skill."));+ return;+ }+ setError(null);+ setErrorPaths([]);+ setBusy("installing");+ try {+ const result = await props.onInstall({+ files: source.files,+ ...(name ? { name } : {}),+ onConflict: conflict && resolution === "replace" ? "replace" : "fail",+ });+ props.onInstalled(result);+ } catch (cause) {+ fail(cause);+ } finally {+ setBusy(null);+ }+ };++ const hiddenInputs = (+ <>+ <input+ ref={(node) => {+ folderInput.current = node;+ // React does not type the directory-picker attributes.+ node?.setAttribute("webkitdirectory", "");+ node?.setAttribute("directory", "");+ }}+ type="file"+ multiple+ className="hidden"+ data-testid="skill-upload-folder-input"+ onChange={(event) => {+ const files = event.currentTarget.files;+ if (files?.length) void load(() => readSkillFromFileList(Array.from(files)));+ event.currentTarget.value = "";+ }}+ />+ <input+ ref={zipInput}+ type="file"+ accept=".zip,application/zip,application/x-zip-compressed"+ className="hidden"+ data-testid="skill-upload-zip-input"+ onChange={(event) => {+ const file = event.currentTarget.files?.[0];+ if (file) void load(() => readSkillFromZipFile(file));+ event.currentTarget.value = "";+ }}+ />+ </>+ );++ const errorBox = error ? (+ <div role="alert" className="rounded-xl border border-red-7/40 bg-red-3/40 px-3 py-2 text-sm text-red-11" data-testid="skill-upload-error">+ <p>{error}</p>+ {errorPaths.length ? (+ <ul className="mt-1 list-disc pl-5 font-mono text-xs">+ {errorPaths.map((path) => <li key={path}>{path}</li>)}+ </ul>+ ) : null}+ </div>+ ) : null;++ if (source && preview) {+ const conflict = preview.conflict;+ const groups = groupSkillFiles(preview.files);+ return (+ <div className="flex flex-col gap-4" data-testid="skill-upload-preview">+ {hiddenInputs}+ <div className="flex items-start justify-between gap-3 rounded-xl bg-dls-hover/60 px-4 py-3">+ <div className="min-w-0">+ <div className="font-mono text-sm font-semibold text-dls-text" data-testid="skill-upload-name">{preview.name}</div>+ <p className="mt-0.5 line-clamp-3 text-xs text-dls-secondary">{preview.description}</p>+ <p className="mt-1.5 text-[11px] text-dls-secondary">+ {source.kind === "zip" ? <FileArchive size={11} className="mr-1 inline" /> : <Folder size={11} className="mr-1 inline" />}+ {source.label}+ {" · "}+ {preview.files.length} {preview.files.length === 1 ? "file" : "files"}+ {" · "}+ {formatUploadBytes(preview.totalBytes)}+ </p>+ </div>+ <Button variant="ghost" size="icon-sm" type="button" aria-label={label("extensions.skill_upload_clear", "Choose something else")} disabled={busy} onClick={reset}>+ <X size={14} />+ </Button>+ </div>++ <div className="max-h-64 overflow-y-auto rounded-xl border border-dls-border" data-testid="skill-upload-files">+ {groups.map((group) => (+ <div key={group.folder || "."}>+ {group.folder ? (+ <div className="flex items-center gap-1.5 border-b border-dls-border bg-dls-hover/40 px-3 py-1.5 font-mono text-[11px] text-dls-secondary">+ <Folder size={12} /> {group.folder}/+ </div>+ ) : null}+ {group.files.map((file) => (+ <div key={file.path} className="flex items-center gap-2 border-b border-dls-border px-3 py-1.5 last:border-b-0">+ {file.executable ? <Terminal size={12} className="shrink-0 text-dls-secondary" /> : <FileText size={12} className="shrink-0 text-dls-secondary" />}+ <span className={`min-w-0 flex-1 truncate font-mono text-xs ${group.folder ? "pl-3" : ""}`}>{file.path.slice(group.folder ? group.folder.length + 1 : 0)}</span>+ {file.executable ? <span className="rounded bg-dls-hover px-1.5 py-0.5 text-[10px] text-dls-secondary">exec</span> : null}+ <span className="shrink-0 text-[11px] tabular-nums text-dls-secondary">{formatUploadBytes(file.size)}</span>+ </div>+ ))}+ </div>+ ))}+ </div>++ {preview.strippedRoot || preview.skipped.length || source.skipped.length ? (+ <p className="text-[11px] text-dls-secondary">+ {preview.strippedRoot ? `SKILL.md was found inside “${preview.strippedRoot}/”; its contents become the skill folder. ` : ""}+ {preview.skipped.length + source.skipped.length > 0+ ? `Skipped ${preview.skipped.length + source.skipped.length} system ${preview.skipped.length + source.skipped.length === 1 ? "entry" : "entries"} (${[...source.skipped, ...preview.skipped].slice(0, 4).join(", ")}${preview.skipped.length + source.skipped.length > 4 ? ", …" : ""}).`+ : ""}+ </p>+ ) : null}++ {conflict ? (+ <div className="flex flex-col gap-2 rounded-xl border border-amber-7/40 bg-amber-3/30 px-4 py-3" data-testid="skill-upload-conflict">+ <p className="flex items-center gap-1.5 text-sm font-medium text-dls-text">+ <AlertTriangle size={14} className="text-amber-11" />+ {conflict.replaceable+ ? `A skill named “${conflict.name}” already exists in this workspace.`+ : `A skill named “${conflict.name}” is already installed ${conflict.scope === "global" ? "globally" : "in another skills folder"}.`}+ </p>+ <p className="break-all font-mono text-[11px] text-dls-secondary">{conflict.path}</p>+ {conflict.replaceable ? (+ <label className="flex items-center gap-2 text-sm">+ <input type="radio" name="skill-conflict" checked={resolution === "replace"} disabled={busy} onChange={() => setResolution("replace")} />+ {label("extensions.skill_upload_replace", "Replace it (its files are removed)")}+ </label>+ ) : null}+ <label className="flex items-center gap-2 text-sm">+ <input type="radio" name="skill-conflict" checked={resolution === "rename"} disabled={busy} onChange={() => setResolution("rename")} />+ {label("extensions.skill_upload_rename", "Install under a new name")}+ </label>+ {resolution === "rename" ? (+ <TextInput+ aria-label={label("extensions.skill_upload_rename", "Install under a new name")}+ value={rename}+ disabled={busy}+ placeholder="new-skill-name"+ className="rounded-xl border-transparent bg-dls-hover shadow-none"+ onChange={(event) => setRename(event.currentTarget.value)}+ />+ ) : null}+ </div>+ ) : null}++ {errorBox}++ <div className="flex justify-end gap-2">+ <Button variant="outline" type="button" disabled={busy} onClick={reset}>+ {label("extensions.skill_upload_back", "Choose another")}+ </Button>+ <Button type="button" disabled={busy} onClick={() => void install()} data-testid="skill-upload-install">+ {working === "installing" ? <Loader2 size={16} className="animate-spin" /> : null}+ {conflict && resolution === "replace"+ ? label("extensions.skill_upload_replace_submit", "Replace skill")+ : label("extensions.skill_upload_install", "Install skill")}+ </Button>+ </div>+ </div>+ );+ }++ let status: ReactNode = null;+ if (working === "reading") status = label("extensions.skill_upload_reading", "Reading files…");+ if (working === "checking") status = label("extensions.skill_upload_checking", "Checking the skill…");++ return (+ <div className="flex flex-col gap-3" data-testid="skill-upload-pane">+ {hiddenInputs}+ <div+ role="region"+ aria-label={label("extensions.skill_upload_drop", "Drop a skill folder or .zip")}+ data-testid="skill-upload-dropzone"+ onDragOver={(event) => {+ event.preventDefault();+ if (!dragging) setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={onDrop}+ className={`flex flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed px-6 py-10 text-center transition ${+ dragging ? "border-foreground/50 bg-dls-hover" : "border-dls-border bg-dls-hover/40"+ }`}+ >+ {working ? <Loader2 size={22} className="animate-spin text-dls-secondary" /> : <FolderUp size={22} className="text-dls-secondary" />}+ <div>+ <p className="text-sm font-medium text-dls-text">+ {status ?? label("extensions.skill_upload_drop", "Drop a skill folder or .zip here")}+ </p>+ <p className="mt-1 text-xs text-dls-secondary">+ {label(+ "extensions.skill_upload_hint",+ "A folder with SKILL.md at its root, plus any scripts/, references/ or assets/ it uses.",+ )}+ </p>+ </div>+ <div className="flex flex-wrap justify-center gap-2">+ <Button variant="outline" size="sm" type="button" disabled={busy} onClick={chooseFolder} data-testid="skill-upload-choose-folder">+ <Folder size={14} /> {label("extensions.skill_upload_choose_folder", "Choose folder")}+ </Button>+ <Button variant="outline" size="sm" type="button" disabled={busy} onClick={() => zipInput.current?.click()} data-testid="skill-upload-choose-zip">+ <FileArchive size={14} /> {label("extensions.skill_upload_choose_zip", "Choose .zip")}+ </Button>+ </div>+ <p className="text-[11px] text-dls-secondary">+ {`Up to ${SKILL_UPLOAD_LIMITS.maxFiles} files, ${formatUploadBytes(SKILL_UPLOAD_LIMITS.maxFileBytes)} per file, ${formatUploadBytes(SKILL_UPLOAD_LIMITS.maxTotalBytes)} in total. No links or credential files (.env, keys, certificates).`}+ </p>+ </div>+ {errorBox}+ </div>+ );+}diff --git a/apps/app/src/react-app/domains/settings/state/extensions-store.ts b/apps/app/src/react-app/domains/settings/state/extensions-store.tsindex b0036862..5c59a5ae 100644--- a/apps/app/src/react-app/domains/settings/state/extensions-store.ts+++ b/apps/app/src/react-app/domains/settings/state/extensions-store.ts@@ -1,3 +1,9 @@+import type {+ SkillBundleInstallResult,+ SkillBundlePreview,+ SkillFileTree,+ SkillUploadFile,+} from "../../../../app/lib/skill-upload";import * as React from "react";import { desktopRestrictionNotice, type DesktopAppRestrictionChecker } from "../../../../app/cloud/desktop-app-restrictions";@@ -2179,6 +2185,77 @@ export function createExtensionsStore(options: {}}+ /**+ * The workspace's local server, waiting a little for it: right after launch+ * (or a workspace switch) the Library is usable before the server is.+ */+ async function awaitWorkspaceServerTarget(timeoutMs = 20_000) {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const target = await resolveWorkspaceServerTarget();+ if (target.hasOmniRushTarget && target.omnirushClient && target.omnirushWorkspaceId) {+ return { ...target, omnirushClient: target.omnirushClient, omnirushWorkspaceId: target.omnirushWorkspaceId };+ }+ if (Date.now() >= deadline) {+ throw new Error("The local omnirush.ai server is not connected for this workspace yet. Try again in a moment.");+ }+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ }++ /**+ * The local server client for skill-folder operations. These throw readable+ * errors (instead of writing store status) so the upload modal and the skill+ * files panel can show them in place.+ */+ async function skillFilesTarget() {+ if (options.checkDesktopAppRestriction({ restriction: "allowManageExtensions" })) {+ throw new Error(desktopRestrictionNotice("allowManageExtensions"));+ }+ const { omnirushSnapshot, omnirushClient, omnirushWorkspaceId } = await awaitWorkspaceServerTarget();+ if (omnirushSnapshot.omnirushServerCapabilities?.skills?.write === false) {+ throw new Error("omnirush.ai server cannot write skills for this workspace.");+ }+ return { client: omnirushClient, workspaceId: omnirushWorkspaceId };+ }++ async function previewSkillBundle(payload: { files: SkillUploadFile[]; name?: string }): Promise<SkillBundlePreview> {+ const { client, workspaceId } = await skillFilesTarget();+ return client.previewSkillBundle(workspaceId, payload);+ }++ async function installSkillBundle(payload: {+ files: SkillUploadFile[];+ name?: string;+ onConflict?: "fail" | "replace";+ }): Promise<SkillBundleInstallResult> {+ const { client, workspaceId } = await skillFilesTarget();+ const result = await client.installSkillBundle(workspaceId, payload);+ options.markReloadRequired?.("skills", { type: "skill", name: result.name, action: result.action });+ await refreshSkills({ force: true });+ return result;+ }++ async function listSkillFiles(name: string): Promise<SkillFileTree> {+ const { omnirushClient, omnirushWorkspaceId } = await awaitWorkspaceServerTarget();+ return omnirushClient.listSkillFiles(omnirushWorkspaceId, name);+ }++ async function updateSkillFiles(name: string, payload: { add?: SkillUploadFile[]; remove?: string[] }): Promise<SkillFileTree> {+ const { client, workspaceId } = await skillFilesTarget();+ const result = await client.updateSkillFiles(workspaceId, name, payload);+ options.markReloadRequired?.("skills", { type: "skill", name, action: "updated" });+ return result;+ }++ /** Saves an edited SKILL.md (helper files are untouched), throwing on refusal. */+ async function saveSkillContent(input: { name: string; content: string }): Promise<void> {+ const { client, workspaceId } = await skillFilesTarget();+ await client.upsertSkill(workspaceId, { name: input.name.trim(), content: input.content });+ options.markReloadRequired?.("skills", { type: "skill", name: input.name.trim(), action: "updated" });+ await refreshSkills({ force: true });+ }+async function saveSkill(input: { name: string; content: string; description?: string }) {if (extensionMutationDenied()) return;const trimmed = input.name.trim();@@ -2443,6 +2520,11 @@ export function createExtensionsStore(options: {uninstallSkill,readSkill,saveSkill,+ saveSkillContent,+ previewSkillBundle,+ installSkillBundle,+ listSkillFiles,+ updateSkillFiles,createLibraryItem,abortRefreshes,ensureSkillsFresh,diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex f92d701c..808dec73 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -2440,6 +2440,11 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {disconnectOrgMcp={(connectionId) => { void orgMcpConnections.disconnect(connectionId); }}readSkill={readLibrarySkill}createWorkspaceSkill={async (input) => { await extensionsStore.saveSkill(input); }}+ previewSkillBundle={extensionsStore.previewSkillBundle}+ installSkillBundle={extensionsStore.installSkillBundle}+ listSkillFiles={extensionsStore.listSkillFiles}+ updateSkillFiles={extensionsStore.updateSkillFiles}+ saveSkillContent={extensionsStore.saveSkillContent}previewClaudePlugin={(url) => extensionsStore.previewClaudePlugin(url)}installClaudePlugin={(url) => extensionsStore.installClaudePlugin(url)}createLibraryItem={(kind, input) => extensionsStore.createLibraryItem(kind, input)}diff --git a/apps/app/tests/skill-upload.test.ts b/apps/app/tests/skill-upload.test.tsnew file mode 100644index 00000000..c4055827--- /dev/null+++ b/apps/app/tests/skill-upload.test.ts@@ -0,0 +1,243 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { join } from "node:path";++import {+ bytesToBase64,+ classifyDrop,+ groupSkillFiles,+ isSkillUploadJunk,+ readSkillFromDroppedFolder,+ readSkillFromFileList,+ readSkillFromZipBytes,+ SKILL_UPLOAD_LIMITS,+ SkillUploadError,+} from "../src/app/lib/skill-upload";+import { placeSkillFiles } from "../src/react-app/domains/settings/pages/skill-files-panel";++const text = (value: string) => new TextEncoder().encode(value);+const decode = (base64: string) => Buffer.from(base64, "base64").toString("utf8");++type ZipSpec = { name: string; data?: string; mode?: number; deflate?: boolean; encrypted?: boolean };++async function deflateRaw(bytes: Uint8Array): Promise<Uint8Array> {+ const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream("deflate-raw"));+ return new Uint8Array(await new Response(stream).arrayBuffer());+}++/** A minimal zip writer (CRCs are not checked by the reader). */+async function zip(entries: ZipSpec[]): Promise<Uint8Array> {+ const locals: Uint8Array[] = [];+ const centrals: Uint8Array[] = [];+ let offset = 0;+ for (const entry of entries) {+ const name = text(entry.name);+ const raw = text(entry.data ?? "");+ const body = entry.deflate ? await deflateRaw(raw) : raw;+ const local = new Uint8Array(30 + name.length + body.length);+ const lv = new DataView(local.buffer);+ lv.setUint32(0, 0x04034b50, true);+ lv.setUint16(6, entry.encrypted ? 1 : 0x800, true);+ lv.setUint16(8, entry.deflate ? 8 : 0, true);+ lv.setUint32(18, body.length, true);+ lv.setUint32(22, raw.length, true);+ lv.setUint16(26, name.length, true);+ local.set(name, 30);+ local.set(body, 30 + name.length);+ const central = new Uint8Array(46 + name.length);+ const cv = new DataView(central.buffer);+ cv.setUint32(0, 0x02014b50, true);+ cv.setUint16(4, (3 << 8) | 20, true);+ cv.setUint16(8, entry.encrypted ? 1 : 0x800, true);+ cv.setUint16(10, entry.deflate ? 8 : 0, true);+ cv.setUint32(20, body.length, true);+ cv.setUint32(24, raw.length, true);+ cv.setUint16(28, name.length, true);+ cv.setUint32(38, ((entry.mode ?? 0o100644) << 16) >>> 0, true);+ cv.setUint32(42, offset, true);+ central.set(name, 46);+ locals.push(local);+ centrals.push(central);+ offset += local.length;+ }+ const centralSize = centrals.reduce((sum, c) => sum + c.length, 0);+ const eocd = new Uint8Array(22);+ const ev = new DataView(eocd.buffer);+ ev.setUint32(0, 0x06054b50, true);+ ev.setUint16(8, entries.length, true);+ ev.setUint16(10, entries.length, true);+ ev.setUint32(12, centralSize, true);+ ev.setUint32(16, offset, true);+ const out = new Uint8Array(offset + centralSize + 22);+ let at = 0;+ for (const part of [...locals, ...centrals, eocd]) {+ out.set(part, at);+ at += part.length;+ }+ return out;+}++const SKILL = "---\nname: greeter\ndescription: Greets\n---\n";++describe("readSkillFromZipBytes", () => {+ test("reads stored and deflated entries with exec bits, skipping dirs and junk", async () => {+ const bytes = await zip([+ { name: "greeter/", mode: 0o040755 },+ { name: "greeter/SKILL.md", data: SKILL, deflate: true },+ { name: "greeter/scripts/greet.sh", data: "#!/bin/sh\necho hi\n", mode: 0o100755 },+ { name: "__MACOSX/greeter/._SKILL.md", data: "junk" },+ { name: "greeter/.DS_Store", data: "junk" },+ ]);+ const read = await readSkillFromZipBytes(bytes, "greeter.zip");+ expect(read.kind).toBe("zip");+ expect(read.label).toBe("greeter.zip");+ expect(read.files.map((f) => f.path)).toEqual(["greeter/SKILL.md", "greeter/scripts/greet.sh"]);+ expect(decode(read.files[0]!.contentBase64)).toBe(SKILL);+ expect(read.files[0]!.executable).toBeUndefined();+ expect(read.files[1]!.executable).toBe(true);+ expect(read.skipped).toEqual(["__MACOSX/greeter/._SKILL.md", "greeter/.DS_Store"]);+ });++ test("refuses symlink entries, encryption, non-zips and oversized entries", async () => {+ const link = await zip([{ name: "SKILL.md", data: SKILL }, { name: "scripts/leak", data: "/etc/passwd", mode: 0o120777 }]);+ await expect(readSkillFromZipBytes(link)).rejects.toThrow(/cannot contain links.*scripts\/leak/);+ const encrypted = await zip([{ name: "SKILL.md", data: SKILL, encrypted: true }]);+ await expect(readSkillFromZipBytes(encrypted)).rejects.toThrow(/Encrypted/);+ await expect(readSkillFromZipBytes(text("not a zip at all, just text"))).rejects.toBeInstanceOf(SkillUploadError);+ const big = await zip([{ name: "big.txt", data: "a".repeat(SKILL_UPLOAD_LIMITS.maxFileBytes + 1), deflate: true }]);+ await expect(readSkillFromZipBytes(big)).rejects.toThrow(/larger than/);+ });++ test("a deflated entry that inflates past its declared size is refused (zip bomb)", async () => {+ const bytes = await zip([{ name: "SKILL.md", data: "a".repeat(100_000), deflate: true }]);+ // Lie about the uncompressed size in the central directory.+ const view = new DataView(bytes.buffer);+ const central = bytes.length - 22 - (46 + "SKILL.md".length);+ view.setUint32(central + 24, 10, true);+ await expect(readSkillFromZipBytes(bytes)).rejects.toThrow(/larger than it claims/);+ });+});++function relativeFile(path: string, content: string): File {+ const file = new File([content], path.split("/").at(-1)!);+ Object.defineProperty(file, "webkitRelativePath", { value: path });+ return file;+}++describe("readSkillFromFileList", () => {+ test("keeps directory-input paths (with the picked folder) and drops junk", async () => {+ const read = await readSkillFromFileList([+ relativeFile("greeter/SKILL.md", SKILL),+ relativeFile("greeter/scripts/greet.sh", "#!/bin/sh\n"),+ relativeFile("greeter/.git/HEAD", "ref"),+ ]);+ expect(read.kind).toBe("folder");+ expect(read.label).toBe("greeter");+ expect(read.files.map((f) => f.path)).toEqual(["greeter/SKILL.md", "greeter/scripts/greet.sh"]);+ expect(read.skipped).toEqual(["greeter/.git/HEAD"]);+ });++ test("a single .zip from a file input is read as an archive", async () => {+ const bytes = await zip([{ name: "SKILL.md", data: SKILL }]);+ const read = await readSkillFromFileList([new File([bytes as BlobPart], "skill.zip")]);+ expect(read.kind).toBe("zip");+ expect(read.files.map((f) => f.path)).toEqual(["SKILL.md"]);+ });++ test("stops at the file cap", async () => {+ const many = Array.from({ length: SKILL_UPLOAD_LIMITS.maxFiles + 1 }, (_, i) => relativeFile(`s/${i}.md`, "x"));+ await expect(readSkillFromFileList(many)).rejects.toThrow(/at most/);+ });+});++type FakeEntry = {+ isFile: boolean;+ isDirectory: boolean;+ name: string;+ fullPath: string;+ file?: (ok: (file: File) => void) => void;+ createReader?: () => { readEntries: (ok: (entries: FakeEntry[]) => void) => void };+};++function fakeDir(fullPath: string, children: FakeEntry[]): FakeEntry {+ return {+ isFile: false,+ isDirectory: true,+ name: fullPath.split("/").at(-1)!,+ fullPath,+ createReader: () => {+ let done = false;+ return { readEntries: (ok) => { ok(done ? [] : children); done = true; } };+ },+ };+}++function fakeFile(fullPath: string, content: string): FakeEntry {+ const name = fullPath.split("/").at(-1)!;+ return { isFile: true, isDirectory: false, name, fullPath, file: (ok) => ok(new File([content], name)) };+}++describe("drag and drop", () => {+ test("walks a dropped folder without descending into skipped folders", async () => {+ let nodeModulesRead = false;+ const nodeModules = fakeDir("/greeter/node_modules", []);+ nodeModules.createReader = () => {+ nodeModulesRead = true;+ return { readEntries: (ok) => ok([]) };+ };+ const root = fakeDir("/greeter", [+ fakeFile("/greeter/SKILL.md", SKILL),+ fakeDir("/greeter/scripts", [fakeFile("/greeter/scripts/greet.sh", "#!/bin/sh\n")]),+ nodeModules,+ ]);+ const read = await readSkillFromDroppedFolder(root);+ expect(read.files.map((f) => f.path)).toEqual(["greeter/SKILL.md", "greeter/scripts/greet.sh"]);+ expect(read.skipped).toEqual(["greeter/node_modules/"]);+ expect(nodeModulesRead).toBe(false);+ });++ test("classifies a zip, a folder, loose files, and refuses several folders", () => {+ const transfer = (entries: Array<FakeEntry | null>, files: File[]) => ({+ items: entries.map((entry) => ({ kind: "file", webkitGetAsEntry: () => entry })),+ files,+ }) as unknown as DataTransfer;+ const zipFile = new File(["x"], "skill.zip");+ expect(classifyDrop(transfer([fakeFile("/skill.zip", "x")], [zipFile]))?.kind).toBe("zip");+ expect(classifyDrop(transfer([fakeDir("/greeter", [])], [new File([], "greeter")]))?.kind).toBe("folder");+ expect(classifyDrop(transfer([fakeFile("/SKILL.md", SKILL)], [new File([SKILL], "SKILL.md")]))?.kind).toBe("files");+ expect(() => classifyDrop(transfer([fakeDir("/a", []), fakeDir("/b", [])], []))).toThrow(/one skill folder/);+ });+});++describe("helpers", () => {+ test("junk, base64, grouping and placement", () => {+ expect(isSkillUploadJunk("x/.DS_Store")).toBe(true);+ expect(isSkillUploadJunk("x/__pycache__/a.pyc")).toBe(true);+ expect(isSkillUploadJunk("scripts/run.py")).toBe(false);+ expect(bytesToBase64(text("héllo"))).toBe(Buffer.from("héllo").toString("base64"));+ expect(groupSkillFiles([{ path: "scripts/b.sh" }, { path: "SKILL.md" }, { path: "assets/x.png" }]).map((g) => g.folder)).toEqual(["", "assets", "scripts"]);+ expect(placeSkillFiles([{ path: "run.sh", contentBase64: "" }], "scripts").map((f) => f.path)).toEqual(["scripts/run.sh"]);+ expect(placeSkillFiles([{ path: "run.sh", contentBase64: "" }], "").map((f) => f.path)).toEqual(["run.sh"]);+ });+});++describe("Library wiring", () => {+ const mcpView = readFileSync(join(import.meta.dir, "../src/react-app/domains/settings/pages/mcp-view.tsx"), "utf8");+ const modal = readFileSync(join(import.meta.dir, "../src/react-app/domains/settings/pages/library-add-workspace-skill-modal.tsx"), "utf8");+ const route = readFileSync(join(import.meta.dir, "../src/react-app/shell/settings-route.tsx"), "utf8");++ test("the Add skill modal offers upload next to the SKILL.md editor", () => {+ expect(mcpView).toContain("onPreviewBundle={props.previewSkillBundle}");+ expect(mcpView).toContain("onInstallBundle={props.installSkillBundle}");+ expect(modal).toContain("<SkillUploadPane");+ // The paste flow is still the default mode.+ expect(modal).toContain('setMode("write")');+ });++ test("installed workspace skills show their files (not Connect skills)", () => {+ expect(mcpView).toMatch(/detailSkill\.origin !== "omnirush-connect" && props\.listSkillFiles[\s\S]*<SkillFilesPanel/);+ for (const prop of ["previewSkillBundle", "installSkillBundle", "listSkillFiles", "updateSkillFiles", "saveSkillContent"]) {+ expect(route).toContain(`${prop}={extensionsStore.${prop}}`);+ }+ });+});