Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(skills): import runtime local skills into workspace (#1431)
gezilinllf247a4f544fa
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 80e74cd460..b38ea8978c 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -36,6 +36,9 @@ import type {RuntimePing,RuntimeUpdate,RuntimeModelListRequest,+ RuntimeLocalSkillListRequest,+ CreateRuntimeLocalSkillImportRequest,+ RuntimeLocalSkillImportRequest,TimelineEntry,AssigneeFrequencyEntry,TaskMessagePayload,@@ -577,6 +580,38 @@ export class ApiClient {return this.fetch(`/api/runtimes/${runtimeId}/models/${requestId}`);}+ async initiateListLocalSkills(+ runtimeId: string,+ ): Promise<RuntimeLocalSkillListRequest> {+ return this.fetch(`/api/runtimes/${runtimeId}/local-skills`, {+ method: "POST",+ });+ }++ async getListLocalSkillsResult(+ runtimeId: string,+ requestId: string,+ ): Promise<RuntimeLocalSkillListRequest> {+ return this.fetch(`/api/runtimes/${runtimeId}/local-skills/${requestId}`);+ }++ async initiateImportLocalSkill(+ runtimeId: string,+ data: CreateRuntimeLocalSkillImportRequest,+ ): Promise<RuntimeLocalSkillImportRequest> {+ return this.fetch(`/api/runtimes/${runtimeId}/local-skills/import`, {+ method: "POST",+ body: JSON.stringify(data),+ });+ }++ async getImportLocalSkillResult(+ runtimeId: string,+ requestId: string,+ ): Promise<RuntimeLocalSkillImportRequest> {+ return this.fetch(`/api/runtimes/${runtimeId}/local-skills/import/${requestId}`);+ }+async listAgentTasks(agentId: string): Promise<AgentTask[]> {return this.fetch(`/api/agents/${agentId}/tasks`);}diff --git a/packages/core/runtimes/index.ts b/packages/core/runtimes/index.tsindex 899882513f..cc25aa8250 100644--- a/packages/core/runtimes/index.ts+++ b/packages/core/runtimes/index.ts@@ -2,3 +2,4 @@ export * from "./queries";export * from "./mutations";export * from "./hooks";export * from "./models";+export * from "./local-skills";diff --git a/packages/core/runtimes/local-skills.ts b/packages/core/runtimes/local-skills.tsnew file mode 100644index 0000000000..90a4eef4b6--- /dev/null+++ b/packages/core/runtimes/local-skills.ts@@ -0,0 +1,79 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";+import type {+ CreateRuntimeLocalSkillImportRequest,+ RuntimeLocalSkillImportResult,+ RuntimeLocalSkillsResult,+} from "../types";++export const runtimeLocalSkillsKeys = {+ all: () => ["runtimes", "local-skills"] as const,+ forRuntime: (runtimeId: string) =>+ [...runtimeLocalSkillsKeys.all(), runtimeId] as const,+};++const POLL_INTERVAL_MS = 500;+const POLL_TIMEOUT_MS = 30_000;++export async function resolveRuntimeLocalSkills(+ runtimeId: string,+): Promise<RuntimeLocalSkillsResult> {+ const initial = await api.initiateListLocalSkills(runtimeId);+ const start = Date.now();+ let current = initial;++ while (current.status === "pending" || current.status === "running") {+ if (Date.now() - start > POLL_TIMEOUT_MS) {+ throw new Error("runtime local skill discovery timed out");+ }+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ current = await api.getListLocalSkillsResult(runtimeId, initial.id);+ }++ if (current.status === "failed" || current.status === "timeout") {+ throw new Error(current.error || "runtime local skill discovery failed");+ }++ return {+ skills: current.skills ?? [],+ supported: current.supported,+ };+}++export async function resolveRuntimeLocalSkillImport(+ runtimeId: string,+ payload: CreateRuntimeLocalSkillImportRequest,+): Promise<RuntimeLocalSkillImportResult> {+ const initial = await api.initiateImportLocalSkill(runtimeId, payload);+ const start = Date.now();+ let current = initial;++ while (current.status === "pending" || current.status === "running") {+ if (Date.now() - start > POLL_TIMEOUT_MS) {+ throw new Error("runtime local skill import timed out");+ }+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ current = await api.getImportLocalSkillResult(runtimeId, initial.id);+ }++ if (current.status === "failed" || current.status === "timeout") {+ throw new Error(current.error || "runtime local skill import failed");+ }+ if (!current.skill) {+ throw new Error("runtime local skill import did not return a skill");+ }++ return { skill: current.skill };+}++export function runtimeLocalSkillsOptions(runtimeId: string | null | undefined) {+ return queryOptions({+ queryKey: runtimeId+ ? runtimeLocalSkillsKeys.forRuntime(runtimeId)+ : runtimeLocalSkillsKeys.all(),+ queryFn: () => resolveRuntimeLocalSkills(runtimeId as string),+ enabled: Boolean(runtimeId),+ staleTime: 30_000,+ retry: false,+ });+}diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex eb6c0fcceb..8240e75999 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -223,3 +223,58 @@ export interface RuntimeModelsResult {models: RuntimeModel[];supported: boolean;}++export type RuntimeLocalSkillStatus =+ | "pending"+ | "running"+ | "completed"+ | "failed"+ | "timeout";++export interface RuntimeLocalSkillSummary {+ key: string;+ name: string;+ description?: string;+ source_path: string;+ provider: string;+ file_count: number;+}++export interface RuntimeLocalSkillListRequest {+ id: string;+ runtime_id: string;+ status: RuntimeLocalSkillStatus;+ skills?: RuntimeLocalSkillSummary[];+ supported: boolean;+ error?: string;+ created_at: string;+ updated_at: string;+}++export interface CreateRuntimeLocalSkillImportRequest {+ skill_key: string;+ name?: string;+ description?: string;+}++export interface RuntimeLocalSkillImportRequest {+ id: string;+ runtime_id: string;+ skill_key: string;+ name?: string;+ description?: string;+ status: RuntimeLocalSkillStatus;+ skill?: Skill;+ error?: string;+ created_at: string;+ updated_at: string;+}++export interface RuntimeLocalSkillsResult {+ skills: RuntimeLocalSkillSummary[];+ supported: boolean;+}++export interface RuntimeLocalSkillImportResult {+ skill: Skill;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex e61cdd4736..c493a498db 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -24,6 +24,13 @@ export type {RuntimeModelListRequest,RuntimeModelListStatus,RuntimeModelsResult,+ RuntimeLocalSkillStatus,+ RuntimeLocalSkillSummary,+ RuntimeLocalSkillListRequest,+ CreateRuntimeLocalSkillImportRequest,+ RuntimeLocalSkillImportRequest,+ RuntimeLocalSkillsResult,+ RuntimeLocalSkillImportResult,IssueUsageSummary,} from "./agent";export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";diff --git a/packages/views/agents/components/tabs/skills-tab.test.tsx b/packages/views/agents/components/tabs/skills-tab.test.tsxnew file mode 100644index 0000000000..5d2fd60160--- /dev/null+++ b/packages/views/agents/components/tabs/skills-tab.test.tsx@@ -0,0 +1,139 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, waitFor } from "@testing-library/react";+import type { Agent } from "@multica/core/types";++const mockListSkills = vi.hoisted(() => vi.fn());+const mockRuntimeListOptions = vi.hoisted(() => vi.fn());+const mockRuntimeLocalSkillsOptions = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@multica/core/api", () => ({+ api: {+ listSkills: (...args: unknown[]) => mockListSkills(...args),+ setAgentSkills: vi.fn(),+ },+}));++vi.mock("@multica/core/runtimes", () => ({+ runtimeListOptions: (...args: unknown[]) => mockRuntimeListOptions(...args),+ runtimeLocalSkillsOptions: (...args: unknown[]) =>+ mockRuntimeLocalSkillsOptions(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ error: vi.fn(),+ success: vi.fn(),+ },+}));++import { SkillsTab } from "./skills-tab";++const agent: Agent = {+ id: "agent-1",+ workspace_id: "ws-1",+ runtime_id: "runtime-1",+ name: "Agent",+ description: "",+ instructions: "",+ avatar_url: null,+ runtime_mode: "local",+ runtime_config: {},+ custom_env: {},+ custom_args: [],+ custom_env_redacted: false,+ visibility: "workspace",+ status: "idle",+ max_concurrent_tasks: 1,+ model: "",+ owner_id: "user-1",+ skills: [],+ created_at: "2026-04-16T00:00:00Z",+ updated_at: "2026-04-16T00:00:00Z",+ archived_at: null,+ archived_by: null,+};++function renderSkillsTab() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ });++ return render(+ <QueryClientProvider client={queryClient}>+ <SkillsTab agent={agent} />+ </QueryClientProvider>,+ );+}++describe("SkillsTab", () => {+ beforeEach(() => {+ vi.clearAllMocks();++ mockListSkills.mockResolvedValue([]);+ mockRuntimeListOptions.mockReturnValue({+ queryKey: ["runtimes", "ws-1", "list"],+ queryFn: () =>+ Promise.resolve([+ {+ id: "runtime-1",+ workspace_id: "ws-1",+ daemon_id: "daemon-1",+ name: "Claude (MacBook)",+ runtime_mode: "local",+ provider: "claude",+ launch_header: "",+ status: "online",+ device_info: "",+ metadata: {},+ owner_id: "user-1",+ last_seen_at: null,+ created_at: "2026-04-16T00:00:00Z",+ updated_at: "2026-04-16T00:00:00Z",+ },+ ]),+ });+ mockRuntimeLocalSkillsOptions.mockReturnValue({+ queryKey: ["runtimes", "local-skills", "runtime-1"],+ queryFn: () =>+ Promise.resolve({+ supported: true,+ skills: [+ {+ key: "review-helper",+ name: "Review Helper",+ description: "Review pull requests",+ provider: "claude",+ source_path: "~/.claude/skills/review-helper",+ file_count: 2,+ },+ ],+ }),+ });+ });++ it("shows runtime local skills for local agents", async () => {+ renderSkillsTab();++ expect(await screen.findByText("Local Runtime Skills")).toBeInTheDocument();+ expect(await screen.findByText("Review Helper")).toBeInTheDocument();+ expect(screen.getByText("claude")).toBeInTheDocument();+ expect(screen.getByText("~/.claude/skills/review-helper")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Import to Workspace/i })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /Import From Runtime/i })).not.toBeInTheDocument();++ await waitFor(() => {+ expect(mockRuntimeLocalSkillsOptions).toHaveBeenCalledWith("runtime-1");+ });+ });+});diff --git a/packages/views/agents/components/tabs/skills-tab.tsx b/packages/views/agents/components/tabs/skills-tab.tsxindex af41e53428..76ac206be5 100644--- a/packages/views/agents/components/tabs/skills-tab.tsx+++ b/packages/views/agents/components/tabs/skills-tab.tsx@@ -1,7 +1,7 @@"use client";import { useState } from "react";-import { Plus, FileText, Trash2, Info } from "lucide-react";+import { Plus, FileText, Trash2, Info, Download, AlertCircle } from "lucide-react";import type { Agent } from "@multica/core/types";import {Dialog,@@ -16,7 +16,10 @@ import { toast } from "sonner";import { api } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";import { skillListOptions, workspaceKeys } from "@multica/core/workspace/queries";+import { runtimeListOptions, runtimeLocalSkillsOptions } from "@multica/core/runtimes";import { useQuery, useQueryClient } from "@tanstack/react-query";+import { RuntimeLocalSkillImportDialog } from "../../../skills/components/runtime-local-skill-import-dialog";+import { RuntimeLocalSkillRow } from "../../../skills/components/runtime-local-skill-row";export function SkillsTab({agent,@@ -26,11 +29,22 @@ export function SkillsTab({const qc = useQueryClient();const wsId = useWorkspaceId();const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));const [saving, setSaving] = useState(false);const [showPicker, setShowPicker] = useState(false);+ const [showRuntimeImport, setShowRuntimeImport] = useState(false);+ const [runtimeImportSkillKey, setRuntimeImportSkillKey] = useState<string | null>(null);const agentSkillIds = new Set(agent.skills.map((s) => s.id));const availableSkills = workspaceSkills.filter((s) => !agentSkillIds.has(s.id));+ const runtime = runtimes.find((item) => item.id === agent.runtime_id);+ const localSkillsQuery = useQuery({+ ...runtimeLocalSkillsOptions(runtime?.id ?? null),+ enabled:+ agent.runtime_mode === "local" &&+ !!runtime?.id &&+ runtime.status === "online",+ });const handleAdd = async (skillId: string) => {setSaving(true);@@ -82,7 +96,7 @@ export function SkillsTab({<div className="flex items-start gap-2 rounded-md border border-info/20 bg-info/5 px-3 py-2.5"><Info className="h-3.5 w-3.5 shrink-0 text-info mt-0.5" /><p className="text-xs text-muted-foreground">- Local runtime skills (from your CLI's skills directory) are always available automatically — no need to add them here.+ Local runtime skills are always available automatically. Importing creates a workspace copy that your team can edit and reuse.</p></div>@@ -137,6 +151,77 @@ export function SkillsTab({</div>)}+ {agent.runtime_mode === "local" && (+ <div className="space-y-3 rounded-lg border p-4">+ <div>+ <h4 className="text-sm font-semibold">Local Runtime Skills</h4>+ <p className="mt-0.5 text-xs text-muted-foreground">+ Browse local skills discovered from this runtime. They are read-only here until imported into the workspace.+ </p>+ </div>++ {!runtime ? (+ <div className="rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ Runtime details are unavailable for this agent right now.+ </div>+ ) : runtime.status !== "online" ? (+ <div className="flex items-start gap-2 rounded-md bg-warning/10 px-3 py-2 text-xs text-muted-foreground">+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" />+ Runtime must be online to browse local skills.+ </div>+ ) : localSkillsQuery.isLoading ? (+ <div className="space-y-2">+ {Array.from({ length: 2 }).map((_, index) => (+ <div key={index} className="rounded-lg border px-4 py-3">+ <div className="h-4 w-36 rounded bg-muted" />+ <div className="mt-2 h-3 w-52 rounded bg-muted" />+ </div>+ ))}+ </div>+ ) : localSkillsQuery.error ? (+ <div className="flex items-start gap-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {localSkillsQuery.error instanceof Error+ ? localSkillsQuery.error.message+ : "Failed to load runtime local skills"}+ </div>+ ) : !localSkillsQuery.data?.supported ? (+ <div className="rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ This runtime provider does not expose local skill inventory yet.+ </div>+ ) : (localSkillsQuery.data.skills ?? []).length === 0 ? (+ <div className="rounded-md border border-dashed px-4 py-8 text-center">+ <p className="text-sm text-muted-foreground">No local skills found</p>+ <p className="mt-1 text-xs text-muted-foreground">+ Add local skills to this runtime first, then import the ones you want to share.+ </p>+ </div>+ ) : (+ <div className="space-y-2">+ {(localSkillsQuery.data.skills ?? []).map((skill) => (+ <RuntimeLocalSkillRow+ key={skill.key}+ skill={skill}+ action={+ <Button+ variant="outline"+ size="xs"+ onClick={() => {+ setRuntimeImportSkillKey(skill.key);+ setShowRuntimeImport(true);+ }}+ >+ <Download className="h-3 w-3" />+ Import to Workspace+ </Button>+ }+ />+ ))}+ </div>+ )}+ </div>+ )}+{/* Skill Picker Dialog */}{showPicker && (<Dialog open onOpenChange={(v) => { if (!v) setShowPicker(false); }}>@@ -180,6 +265,16 @@ export function SkillsTab({</DialogContent></Dialog>)}++ {showRuntimeImport && runtime && (+ <RuntimeLocalSkillImportDialog+ open={showRuntimeImport}+ onClose={() => setShowRuntimeImport(false)}+ fixedRuntimeId={runtime.id}+ initialRuntimeId={runtime.id}+ initialSkillKey={runtimeImportSkillKey}+ />+ )}</div>);}diff --git a/packages/views/skills/components/runtime-local-skill-import-dialog.tsx b/packages/views/skills/components/runtime-local-skill-import-dialog.tsxnew file mode 100644index 0000000000..f51ba75af5--- /dev/null+++ b/packages/views/skills/components/runtime-local-skill-import-dialog.tsx@@ -0,0 +1,339 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { HardDrive, Download, AlertCircle } from "lucide-react";+import type { AgentRuntime, Skill } from "@multica/core/types";+import { useWorkspaceId } from "@multica/core/hooks";+import {+ runtimeListOptions,+ runtimeLocalSkillsKeys,+ runtimeLocalSkillsOptions,+ resolveRuntimeLocalSkillImport,+} from "@multica/core/runtimes";+import { workspaceKeys } from "@multica/core/workspace/queries";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { Label } from "@multica/ui/components/ui/label";+import { Badge } from "@multica/ui/components/ui/badge";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { toast } from "sonner";+import { RuntimeLocalSkillRow } from "./runtime-local-skill-row";++function runtimeLabel(runtime: AgentRuntime): string {+ return `${runtime.name} (${runtime.provider})`;+}++export function RuntimeLocalSkillImportDialog({+ open,+ onClose,+ initialRuntimeId,+ initialSkillKey,+ fixedRuntimeId,+ onImported,+}: {+ open: boolean;+ onClose: () => void;+ initialRuntimeId?: string | null;+ initialSkillKey?: string | null;+ fixedRuntimeId?: string | null;+ onImported?: (skill: Skill) => void;+}) {+ const wsId = useWorkspaceId();+ const qc = useQueryClient();+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));+ const localRuntimes = useMemo(+ () => runtimes.filter((runtime) => runtime.runtime_mode === "local"),+ [runtimes],+ );++ const [selectedRuntimeId, setSelectedRuntimeId] = useState<string>("");+ const [selectedSkillKey, setSelectedSkillKey] = useState<string>("");+ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [importing, setImporting] = useState(false);++ useEffect(() => {+ if (!open) {+ return;+ }++ const preferredRuntimeId =+ fixedRuntimeId ??+ initialRuntimeId ??+ localRuntimes[0]?.id ??+ "";+ setSelectedRuntimeId(preferredRuntimeId);+ }, [fixedRuntimeId, initialRuntimeId, localRuntimes, open]);++ const selectedRuntime = localRuntimes.find(+ (runtime) => runtime.id === selectedRuntimeId,+ );+ const canBrowseSkills = open && !!selectedRuntimeId && selectedRuntime?.status === "online";+ const skillsQuery = useQuery({+ ...runtimeLocalSkillsOptions(selectedRuntimeId || null),+ enabled: canBrowseSkills,+ });++ const runtimeSkills = skillsQuery.data?.skills ?? [];+ const selectedSkill = runtimeSkills.find((skill) => skill.key === selectedSkillKey);++ useEffect(() => {+ if (!open) {+ return;+ }++ const preferredSkill =+ (initialSkillKey+ ? runtimeSkills.find((skill) => skill.key === initialSkillKey)+ : null) ?? runtimeSkills[0];+ const nextSkill = preferredSkill;+ if (!nextSkill) {+ setSelectedSkillKey("");+ setName("");+ setDescription("");+ return;+ }++ if (!runtimeSkills.some((skill) => skill.key === selectedSkillKey)) {+ setSelectedSkillKey(nextSkill.key);+ setName(nextSkill.name);+ setDescription(nextSkill.description ?? "");+ }+ }, [initialSkillKey, open, runtimeSkills, selectedSkillKey]);++ useEffect(() => {+ if (!selectedSkill) {+ return;+ }+ setName(selectedSkill.name);+ setDescription(selectedSkill.description ?? "");+ }, [selectedSkillKey, selectedSkill]);++ const handleImport = async () => {+ if (!selectedRuntimeId || !selectedSkill) {+ return;+ }++ setImporting(true);+ try {+ const result = await resolveRuntimeLocalSkillImport(selectedRuntimeId, {+ skill_key: selectedSkill.key,+ name: name.trim() || undefined,+ description: description.trim() || undefined,+ });+ await Promise.all([+ qc.invalidateQueries({ queryKey: runtimeLocalSkillsKeys.forRuntime(selectedRuntimeId) }),+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) }),+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) }),+ ]);+ toast.success("Skill imported");+ onImported?.(result.skill);+ onClose();+ } catch (error) {+ toast.error(error instanceof Error ? error.message : "Failed to import skill");+ } finally {+ setImporting(false);+ }+ };++ const renderSkillContent = () => {+ if (localRuntimes.length === 0) {+ return (+ <div className="rounded-lg border border-dashed px-4 py-8 text-center">+ <p className="text-sm text-muted-foreground">No local runtimes available</p>+ <p className="mt-1 text-xs text-muted-foreground">+ Connect a local runtime to browse and import its local skills.+ </p>+ </div>+ );+ }++ if (!selectedRuntime) {+ return (+ <div className="rounded-lg border border-dashed px-4 py-8 text-center">+ <p className="text-sm text-muted-foreground">Choose a runtime to continue</p>+ </div>+ );+ }++ if (selectedRuntime.status !== "online") {+ return (+ <div className="flex items-start gap-2 rounded-md bg-warning/10 px-3 py-2 text-xs text-muted-foreground">+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" />+ Runtime must be online to browse local skills.+ </div>+ );+ }++ if (skillsQuery.isLoading) {+ return (+ <div className="space-y-2">+ {Array.from({ length: 3 }).map((_, index) => (+ <div key={index} className="rounded-lg border px-4 py-3">+ <Skeleton className="h-4 w-32" />+ <Skeleton className="mt-2 h-3 w-48" />+ </div>+ ))}+ </div>+ );+ }++ if (skillsQuery.error) {+ return (+ <div className="flex items-start gap-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {skillsQuery.error instanceof Error+ ? skillsQuery.error.message+ : "Failed to load runtime local skills"}+ </div>+ );+ }++ if (!skillsQuery.data?.supported) {+ return (+ <div className="flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ This runtime provider does not expose local skill inventory yet.+ </div>+ );+ }++ if (runtimeSkills.length === 0) {+ return (+ <div className="rounded-lg border border-dashed px-4 py-8 text-center">+ <p className="text-sm text-muted-foreground">No local skills found</p>+ <p className="mt-1 text-xs text-muted-foreground">+ This runtime does not have any discoverable local skills yet.+ </p>+ </div>+ );+ }++ return (+ <div className="space-y-4">+ <div className="space-y-2">+ {runtimeSkills.map((skill) => (+ <RuntimeLocalSkillRow+ key={skill.key}+ skill={skill}+ selected={selectedSkillKey === skill.key}+ onSelect={() => setSelectedSkillKey(skill.key)}+ />+ ))}+ </div>++ {selectedSkill && (+ <div className="space-y-3 rounded-lg border bg-muted/20 p-4">+ <div>+ <Label className="text-xs text-muted-foreground">Workspace skill name</Label>+ <Input+ value={name}+ onChange={(event) => setName(event.target.value)}+ className="mt-1"+ />+ </div>+ <div>+ <Label className="text-xs text-muted-foreground">Description</Label>+ <Input+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ className="mt-1"+ placeholder="Optional description override"+ />+ </div>+ </div>+ )}+ </div>+ );+ };++ return (+ <Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose(); }}>+ <DialogContent className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle>Import Runtime Skill</DialogTitle>+ <DialogDescription>+ Local skills are runtime-owned and auto-used. Import creates a workspace copy for team sharing and editing.+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ {!fixedRuntimeId && (+ <div className="space-y-1.5">+ <Label className="text-xs text-muted-foreground">Runtime</Label>+ <Select value={selectedRuntimeId} onValueChange={(value) => value && setSelectedRuntimeId(value)}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a local runtime" />+ </SelectTrigger>+ <SelectContent>+ {localRuntimes.map((runtime) => (+ <SelectItem key={runtime.id} value={runtime.id}>+ {runtimeLabel(runtime)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}++ {selectedRuntime && (+ <div className="flex items-center gap-2 rounded-lg border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ <HardDrive className="h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate">{runtimeLabel(selectedRuntime)}</span>+ <Badge variant={selectedRuntime.status === "online" ? "secondary" : "outline"}>+ {selectedRuntime.status}+ </Badge>+ </div>+ )}++ {renderSkillContent()}++ <p className="text-xs text-muted-foreground">+ Symlinks, unreadable files, oversized files, and very large bundles are ignored during import.+ </p>+ </div>++ <DialogFooter>+ <Button variant="ghost" onClick={onClose}>+ Cancel+ </Button>+ <Button+ onClick={handleImport}+ disabled={+ importing ||+ !selectedRuntime ||+ selectedRuntime.status !== "online" ||+ !selectedSkill ||+ !name.trim()+ }+ >+ {importing ? (+ "Importing..."+ ) : (+ <>+ <Download className="h-3 w-3" />+ Import to Workspace+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/skills/components/runtime-local-skill-row.tsx b/packages/views/skills/components/runtime-local-skill-row.tsxnew file mode 100644index 0000000000..be650bd63f--- /dev/null+++ b/packages/views/skills/components/runtime-local-skill-row.tsx@@ -0,0 +1,59 @@+"use client";++import type { ReactNode } from "react";+import { FileText } from "lucide-react";+import type { RuntimeLocalSkillSummary } from "@multica/core/types";+import { Badge } from "@multica/ui/components/ui/badge";++export function RuntimeLocalSkillRow({+ skill,+ selected = false,+ onSelect,+ action,+}: {+ skill: RuntimeLocalSkillSummary;+ selected?: boolean;+ onSelect?: () => void;+ action?: ReactNode;+}) {+ const content = (+ <>+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-muted">+ <FileText className="h-4 w-4 text-muted-foreground" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-sm font-medium">{skill.name}</span>+ <Badge variant="secondary">{skill.provider}</Badge>+ </div>+ {skill.description && (+ <p className="mt-1 text-xs text-muted-foreground">{skill.description}</p>+ )}+ <p className="mt-1 truncate font-mono text-[11px] text-muted-foreground">+ {skill.source_path}+ </p>+ </div>+ {action ?? (+ <Badge variant="outline">+ {skill.file_count} file{skill.file_count === 1 ? "" : "s"}+ </Badge>+ )}+ </>+ );++ if (onSelect) {+ return (+ <button+ type="button"+ onClick={onSelect}+ className={`flex w-full items-start gap-3 rounded-lg border px-4 py-3 text-left transition-colors ${+ selected ? "border-primary bg-primary/5" : "hover:bg-accent/50"+ }`}+ >+ {content}+ </button>+ );+ }++ return <div className="flex items-start gap-3 rounded-lg border px-4 py-3">{content}</div>;+}diff --git a/packages/views/skills/components/skills-page.test.tsx b/packages/views/skills/components/skills-page.test.tsxnew file mode 100644index 0000000000..293d23420e--- /dev/null+++ b/packages/views/skills/components/skills-page.test.tsx@@ -0,0 +1,163 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";++const mockListSkills = vi.hoisted(() => vi.fn());+const mockResolveRuntimeLocalSkillImport = vi.hoisted(() => vi.fn());+const mockRuntimeListOptions = vi.hoisted(() => vi.fn());+const mockRuntimeLocalSkillsOptions = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@multica/core/api", () => ({+ api: {+ listSkills: (...args: unknown[]) => mockListSkills(...args),+ createSkill: vi.fn(),+ importSkill: vi.fn(),+ updateSkill: vi.fn(),+ deleteSkill: vi.fn(),+ getSkill: vi.fn(),+ },+}));++vi.mock("@multica/core/runtimes", () => ({+ runtimeListOptions: (...args: unknown[]) => mockRuntimeListOptions(...args),+ runtimeLocalSkillsOptions: (...args: unknown[]) =>+ mockRuntimeLocalSkillsOptions(...args),+ runtimeLocalSkillsKeys: {+ forRuntime: (runtimeId: string) => ["runtimes", "local-skills", runtimeId],+ },+ resolveRuntimeLocalSkillImport: (...args: unknown[]) =>+ mockResolveRuntimeLocalSkillImport(...args),+}));++vi.mock("react-resizable-panels", () => ({+ useDefaultLayout: () => ({+ defaultLayout: undefined,+ onLayoutChanged: vi.fn(),+ }),+}));++vi.mock("@multica/ui/components/ui/resizable", () => ({+ ResizablePanelGroup: ({ children }: any) => <div>{children}</div>,+ ResizablePanel: ({ children }: any) => <div>{children}</div>,+ ResizableHandle: () => <div data-testid="resize-handle" />,+}));++vi.mock("sonner", () => ({+ toast: {+ error: vi.fn(),+ success: vi.fn(),+ },+}));++import SkillsPage from "./skills-page";++function renderSkillsPage() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ });++ return render(+ <QueryClientProvider client={queryClient}>+ <SkillsPage />+ </QueryClientProvider>,+ );+}++describe("SkillsPage", () => {+ beforeEach(() => {+ vi.clearAllMocks();++ mockListSkills.mockResolvedValue([]);+ mockRuntimeListOptions.mockReturnValue({+ queryKey: ["runtimes", "ws-1", "list"],+ queryFn: () =>+ Promise.resolve([+ {+ id: "runtime-1",+ workspace_id: "ws-1",+ daemon_id: "daemon-1",+ name: "Claude (MacBook)",+ runtime_mode: "local",+ provider: "claude",+ launch_header: "",+ status: "online",+ device_info: "",+ metadata: {},+ owner_id: "user-1",+ last_seen_at: null,+ created_at: "2026-04-16T00:00:00Z",+ updated_at: "2026-04-16T00:00:00Z",+ },+ ]),+ });+ mockRuntimeLocalSkillsOptions.mockReturnValue({+ queryKey: ["runtimes", "local-skills", "runtime-1"],+ queryFn: () =>+ Promise.resolve({+ supported: true,+ skills: [+ {+ key: "review-helper",+ name: "Review Helper",+ description: "Review pull requests",+ provider: "claude",+ source_path: "~/.claude/skills/review-helper",+ file_count: 2,+ },+ ],+ }),+ });+ mockResolveRuntimeLocalSkillImport.mockResolvedValue({+ skill: {+ id: "skill-2",+ workspace_id: "ws-1",+ name: "Review Helper",+ description: "Review pull requests",+ content: "# Review Helper",+ config: {},+ files: [],+ created_by: "user-1",+ created_at: "2026-04-16T00:00:00Z",+ updated_at: "2026-04-16T00:00:00Z",+ },+ });+ });++ it("opens the runtime import dialog and imports a local skill", async () => {+ renderSkillsPage();++ const importButtons = await screen.findAllByRole("button", {+ name: /Import From Runtime/i,+ });+ fireEvent.click(importButtons[0]!);++ expect(await screen.findByText("Import Runtime Skill")).toBeInTheDocument();+ expect(await screen.findByText("Review Helper")).toBeInTheDocument();++ const importButton = screen.getByRole("button", {+ name: /Import to Workspace/i,+ });+ await waitFor(() => {+ expect(importButton).not.toBeDisabled();+ });+ fireEvent.click(importButton);++ await waitFor(() => {+ expect(mockResolveRuntimeLocalSkillImport).toHaveBeenCalledWith("runtime-1", {+ skill_key: "review-helper",+ name: "Review Helper",+ description: "Review pull requests",+ });+ });+ });+});diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsxindex 19f9279712..d1e060a330 100644--- a/packages/views/skills/components/skills-page.tsx+++ b/packages/views/skills/components/skills-page.tsx@@ -9,6 +9,7 @@ import {Save,AlertCircle,Download,+ HardDrive,} from "lucide-react";import type { Skill, CreateSkillRequest, UpdateSkillRequest } from "@multica/core/types";import {@@ -40,6 +41,7 @@ import { skillListOptions, workspaceKeys } from "@multica/core/workspace/queriesimport { PageHeader } from "../../layout/page-header";import { FileTree } from "./file-tree";import { FileViewer } from "./file-viewer";+import { RuntimeLocalSkillImportDialog } from "./runtime-local-skill-import-dialog";// ---------------------------------------------------------------------------// Create Skill Dialog@@ -618,6 +620,7 @@ export default function SkillsPage() {const { data: skills = [], isLoading } = useQuery(skillListOptions(wsId));const [selectedId, setSelectedId] = useState<string>("");const [showCreate, setShowCreate] = useState(false);+ const [showRuntimeImport, setShowRuntimeImport] = useState(false);const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: "multica_skills_layout",});@@ -725,20 +728,36 @@ export default function SkillsPage() {<div className="overflow-y-auto h-full border-r"><PageHeader className="justify-between"><h1 className="text-sm font-semibold">Skills</h1>- <Tooltip>- <TooltipTrigger- render={- <Button- variant="ghost"- size="icon-sm"- onClick={() => setShowCreate(true)}- >- <Plus className="h-4 w-4 text-muted-foreground" />- </Button>- }- />- <TooltipContent side="bottom">Create skill</TooltipContent>- </Tooltip>+ <div className="flex items-center gap-1">+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={() => setShowRuntimeImport(true)}+ >+ <HardDrive className="h-4 w-4 text-muted-foreground" />+ </Button>+ }+ />+ <TooltipContent side="bottom">Import from runtime</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={() => setShowCreate(true)}+ >+ <Plus className="h-4 w-4 text-muted-foreground" />+ </Button>+ }+ />+ <TooltipContent side="bottom">Create skill</TooltipContent>+ </Tooltip>+ </div></PageHeader>{skills.length === 0 ? (<div className="flex flex-col items-center justify-center px-4 py-12">@@ -747,14 +766,23 @@ export default function SkillsPage() {<p className="mt-1 text-xs text-muted-foreground text-center max-w-[280px]">Workspace skills are shared across your team and injected into agent runs. Skills already installed in your local runtime are used automatically.</p>- <Button- onClick={() => setShowCreate(true)}- size="xs"- className="mt-3"- >- <Plus className="h-3 w-3" />- Create Skill- </Button>+ <div className="mt-3 flex items-center gap-2">+ <Button+ onClick={() => setShowRuntimeImport(true)}+ size="xs"+ variant="outline"+ >+ <HardDrive className="h-3 w-3" />+ Import From Runtime+ </Button>+ <Button+ onClick={() => setShowCreate(true)}+ size="xs"+ >+ <Plus className="h-3 w-3" />+ Create Skill+ </Button>+ </div></div>) : (<div className="divide-y">@@ -798,6 +826,15 @@ export default function SkillsPage() {<Plus className="h-3 w-3" />Create Skill</Button>+ <Button+ onClick={() => setShowRuntimeImport(true)}+ size="xs"+ variant="outline"+ className="mt-2"+ >+ <HardDrive className="h-3 w-3" />+ Import From Runtime+ </Button></div>)}</div>@@ -810,6 +847,13 @@ export default function SkillsPage() {onImport={handleImport}/>)}+ {showRuntimeImport && (+ <RuntimeLocalSkillImportDialog+ open={showRuntimeImport}+ onClose={() => setShowRuntimeImport(false)}+ onImported={(skill) => setSelectedId(skill.id)}+ />+ )}</ResizablePanelGroup>);}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex d92acc1f62..d8444bfe82 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -71,7 +71,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics}cfSigner := auth.NewCloudFrontSignerFromEnv()-+signupConfig := handler.Config{AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),@@ -147,6 +147,8 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsr.Post("/runtimes/{runtimeId}/ping/{pingId}/result", h.ReportPingResult)r.Post("/runtimes/{runtimeId}/update/{updateId}/result", h.ReportUpdateResult)r.Post("/runtimes/{runtimeId}/models/{requestId}/result", h.ReportModelListResult)+ r.Post("/runtimes/{runtimeId}/local-skills/{requestId}/result", h.ReportLocalSkillListResult)+ r.Post("/runtimes/{runtimeId}/local-skills/import/{requestId}/result", h.ReportLocalSkillImportResult)r.Get("/tasks/{taskId}/status", h.GetTaskStatus)r.Post("/tasks/{taskId}/start", h.StartTask)@@ -359,6 +361,10 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsr.Get("/update/{updateId}", h.GetUpdate)r.Post("/models", h.InitiateListModels)r.Get("/models/{requestId}", h.GetModelListRequest)+ r.Post("/local-skills", h.InitiateListLocalSkills)+ r.Get("/local-skills/{requestId}", h.GetLocalSkillListRequest)+ r.Post("/local-skills/import", h.InitiateImportLocalSkill)+ r.Get("/local-skills/import/{requestId}", h.GetLocalSkillImportRequest)r.Delete("/", h.DeleteAgentRuntime)})})diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex aae32b0dea..6f3b193a26 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -173,10 +173,12 @@ func (c *Client) GetTaskStatus(ctx context.Context, taskID string) (string, erro// HeartbeatResponse contains the server's response to a heartbeat, including any pending actions.type HeartbeatResponse struct {- Status string `json:"status"`- PendingPing *PendingPing `json:"pending_ping,omitempty"`- PendingUpdate *PendingUpdate `json:"pending_update,omitempty"`- PendingModelList *PendingModelList `json:"pending_model_list,omitempty"`+ Status string `json:"status"`+ PendingPing *PendingPing `json:"pending_ping,omitempty"`+ PendingUpdate *PendingUpdate `json:"pending_update,omitempty"`+ PendingModelList *PendingModelList `json:"pending_model_list,omitempty"`+ PendingLocalSkills *PendingLocalSkills `json:"pending_local_skills,omitempty"`+ PendingLocalSkillImport *PendingLocalSkillImport `json:"pending_local_skill_import,omitempty"`}// PendingPing represents a ping test request from the server.@@ -195,6 +197,17 @@ type PendingModelList struct {ID string `json:"id"`}+// PendingLocalSkills represents a request to enumerate runtime local skills.+type PendingLocalSkills struct {+ ID string `json:"id"`+}++// PendingLocalSkillImport represents a request to import a runtime local skill.+type PendingLocalSkillImport struct {+ ID string `json:"id"`+ SkillKey string `json:"skill_key"`+}+func (c *Client) SendHeartbeat(ctx context.Context, runtimeID string) (*HeartbeatResponse, error) {var resp HeartbeatResponseif err := c.postJSON(ctx, "/api/daemon/heartbeat", map[string]string{@@ -219,6 +232,16 @@ func (c *Client) ReportModelListResult(ctx context.Context, runtimeID, requestIDreturn c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/models/%s/result", runtimeID, requestID), result, nil)}+// ReportLocalSkillListResult sends the runtime-local-skill inventory back to the server.+func (c *Client) ReportLocalSkillListResult(ctx context.Context, runtimeID, requestID string, result map[string]any) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/local-skills/%s/result", runtimeID, requestID), result, nil)+}++// ReportLocalSkillImportResult sends a runtime-local-skill bundle back to the server.+func (c *Client) ReportLocalSkillImportResult(ctx context.Context, runtimeID, requestID string, result map[string]any) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/local-skills/import/%s/result", runtimeID, requestID), result, nil)+}+// WorkspaceInfo holds minimal workspace metadata returned by the API.type WorkspaceInfo struct {ID string `json:"id"`diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 600c368b83..a230d5d509 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -514,6 +514,22 @@ func (d *Daemon) heartbeatLoop(ctx context.Context) {go d.handleModelList(ctx, *rt, resp.PendingModelList.ID)}}++ // Handle pending runtime-local-skill inventory requests.+ if resp.PendingLocalSkills != nil {+ rt := d.findRuntime(rid)+ if rt != nil {+ go d.handleLocalSkillList(ctx, *rt, resp.PendingLocalSkills.ID)+ }+ }++ // Handle pending runtime-local-skill import requests.+ if resp.PendingLocalSkillImport != nil {+ rt := d.findRuntime(rid)+ if rt != nil {+ go d.handleLocalSkillImport(ctx, *rt, *resp.PendingLocalSkillImport)+ }+ }}}}@@ -570,6 +586,50 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri})}+func (d *Daemon) handleLocalSkillList(ctx context.Context, rt Runtime, requestID string) {+ d.logger.Info("runtime local skills requested", "runtime_id", rt.ID, "request_id", requestID, "provider", rt.Provider)++ skills, supported, err := listRuntimeLocalSkills(rt.Provider)+ if err != nil {+ d.client.ReportLocalSkillListResult(ctx, rt.ID, requestID, map[string]any{+ "status": "failed",+ "error": err.Error(),+ })+ return+ }++ d.client.ReportLocalSkillListResult(ctx, rt.ID, requestID, map[string]any{+ "status": "completed",+ "skills": skills,+ "supported": supported,+ })+}++func (d *Daemon) handleLocalSkillImport(ctx context.Context, rt Runtime, pending PendingLocalSkillImport) {+ d.logger.Info("runtime local skill import requested", "runtime_id", rt.ID, "request_id", pending.ID, "provider", rt.Provider, "skill_key", pending.SkillKey)++ skill, supported, err := loadRuntimeLocalSkillBundle(rt.Provider, pending.SkillKey)+ if err != nil {+ d.client.ReportLocalSkillImportResult(ctx, rt.ID, pending.ID, map[string]any{+ "status": "failed",+ "error": err.Error(),+ })+ return+ }+ if !supported {+ d.client.ReportLocalSkillImportResult(ctx, rt.ID, pending.ID, map[string]any{+ "status": "failed",+ "error": fmt.Sprintf("provider %q does not expose runtime local skills", rt.Provider),+ })+ return+ }++ d.client.ReportLocalSkillImportResult(ctx, rt.ID, pending.ID, map[string]any{+ "status": "completed",+ "skill": skill,+ })+}+func (d *Daemon) handlePing(ctx context.Context, rt Runtime, pingID string) {d.logger.Info("ping requested", "runtime_id", rt.ID, "ping_id", pingID, "provider", rt.Provider)diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.gonew file mode 100644index 0000000000..7055d737cc--- /dev/null+++ b/server/internal/daemon/local_skills.go@@ -0,0 +1,351 @@+package daemon++import (+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++const (+ maxLocalSkillFileSize int64 = 1 << 20+ maxLocalSkillBundleSize int64 = 8 << 20+ maxLocalSkillFileCount = 128+)++type runtimeLocalSkillSummary struct {+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ SourcePath string `json:"source_path"`+ Provider string `json:"provider"`+ FileCount int `json:"file_count"`+}++type runtimeLocalSkillBundle struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ Content string `json:"content"`+ SourcePath string `json:"source_path"`+ Provider string `json:"provider"`+ Files []SkillFileData `json:"files,omitempty"`+}++// localSkillRootForProvider tracks the user-level skill locations exposed by+// each runtime/provider. Keep these in sync with upstream docs / conventions:+// - GitHub Copilot: https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-skills+// - OpenCode: https://opencode.ai/docs/skills+// - OpenClaw: https://github.com/openclaw/openclaw/blob/main/docs/tools/skills.md+// - Pi: https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md+// - Cursor: official forum guidance referencing the built-in /create-skill flow+// (https://forum.cursor.com/t/cursor-doesnt-know-new-skills-arens-saved/158507)+//+// Longer-term this mapping would be better colocated with the provider+// definitions under server/pkg/agent so adding a new runtime can't silently+// miss the local-skills surface.+func localSkillRootForProvider(provider string) (string, bool, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", false, fmt.Errorf("resolve user home: %w", err)+ }++ switch provider {+ case "claude":+ return filepath.Join(home, ".claude", "skills"), true, nil+ case "codex":+ codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME"))+ if codexHome == "" {+ codexHome = filepath.Join(home, ".codex")+ }+ return filepath.Join(codexHome, "skills"), true, nil+ case "copilot":+ return filepath.Join(home, ".copilot", "skills"), true, nil+ case "opencode":+ return filepath.Join(home, ".config", "opencode", "skills"), true, nil+ case "openclaw":+ return filepath.Join(home, ".openclaw", "skills"), true, nil+ case "pi":+ return filepath.Join(home, ".pi", "agent", "skills"), true, nil+ case "cursor":+ return filepath.Join(home, ".cursor", "skills"), true, nil+ default:+ return "", false, nil+ }+}++func isIgnoredLocalSkillEntry(name string) bool {+ if name == "" {+ return true+ }+ if strings.HasPrefix(name, ".") {+ return true+ }+ switch strings.ToLower(name) {+ case "license", "license.md", "license.txt":+ return true+ default:+ return false+ }+}++func normalizeLocalSkillKey(key string) (string, error) {+ if strings.TrimSpace(key) == "" {+ return "", fmt.Errorf("skill key is required")+ }+ cleaned := filepath.Clean(filepath.FromSlash(strings.TrimSpace(key)))+ if cleaned == "." || filepath.IsAbs(cleaned) || strings.HasPrefix(cleaned, "..") {+ return "", fmt.Errorf("invalid skill key")+ }+ return filepath.ToSlash(cleaned), nil+}++func relativizeHomePath(path string) string {+ home, err := os.UserHomeDir()+ if err != nil {+ return filepath.ToSlash(path)+ }+ if path == home {+ return "~"+ }+ prefix := home + string(filepath.Separator)+ if strings.HasPrefix(path, prefix) {+ return filepath.ToSlash("~" + string(filepath.Separator) + strings.TrimPrefix(path, prefix))+ }+ return filepath.ToSlash(path)+}++func parseLocalSkillFrontmatter(content string) (name, description string) {+ if !strings.HasPrefix(content, "---") {+ return "", ""+ }+ end := strings.Index(content[3:], "---")+ if end < 0 {+ return "", ""+ }+ frontmatter := content[3 : 3+end]+ for _, line := range strings.Split(frontmatter, "\n") {+ line = strings.TrimSpace(line)+ if strings.HasPrefix(line, "name:") {+ name = strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "name:")), "\"'")+ } else if strings.HasPrefix(line, "description:") {+ description = strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "description:")), "\"'")+ }+ }+ return name, description+}++func readLocalSkillMainFile(skillDir string) (string, error) {+ mainPath := filepath.Join(skillDir, "SKILL.md")+ info, err := os.Stat(mainPath)+ if err != nil {+ return "", err+ }+ if info.Size() > maxLocalSkillFileSize {+ return "", fmt.Errorf("SKILL.md exceeds %d bytes", maxLocalSkillFileSize)+ }+ content, err := os.ReadFile(mainPath)+ if err != nil {+ return "", err+ }+ return string(content), nil+}++func collectLocalSkillFiles(skillDir string, includeContent bool) ([]SkillFileData, error) {+ files := make([]SkillFileData, 0)+ var totalSize int64++ err := filepath.WalkDir(skillDir, func(path string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return nil+ }+ if path == skillDir {+ return nil+ }+ if entry.Type()&os.ModeSymlink != 0 {+ if entry.IsDir() {+ return filepath.SkipDir+ }+ return nil+ }+ if entry.IsDir() {+ if isIgnoredLocalSkillEntry(entry.Name()) {+ return filepath.SkipDir+ }+ return nil+ }+ if isIgnoredLocalSkillEntry(entry.Name()) || strings.EqualFold(entry.Name(), "SKILL.md") {+ return nil+ }++ rel, err := filepath.Rel(skillDir, path)+ if err != nil {+ return nil+ }+ rel = filepath.Clean(rel)+ if rel == "." || filepath.IsAbs(rel) || strings.HasPrefix(rel, "..") {+ return nil+ }++ info, err := entry.Info()+ if err != nil || info.Size() > maxLocalSkillFileSize {+ return nil+ }+ if len(files) >= maxLocalSkillFileCount {+ return fmt.Errorf("local skill exceeds %d files", maxLocalSkillFileCount)+ }+ totalSize += info.Size()+ if totalSize > maxLocalSkillBundleSize {+ return fmt.Errorf("local skill exceeds %d bytes in total", maxLocalSkillBundleSize)+ }++ file := SkillFileData{Path: filepath.ToSlash(rel)}+ if includeContent {+ content, err := os.ReadFile(path)+ if err != nil {+ return nil+ }+ file.Content = string(content)+ }+ files = append(files, file)+ return nil+ })+ if err != nil {+ return nil, err+ }++ sort.Slice(files, func(i, j int) bool {+ return files[i].Path < files[j].Path+ })+ return files, nil+}++func listRuntimeLocalSkills(provider string) ([]runtimeLocalSkillSummary, bool, error) {+ root, supported, err := localSkillRootForProvider(provider)+ if err != nil || !supported {+ return nil, supported, err+ }++ if _, err := os.Stat(root); err != nil {+ if os.IsNotExist(err) {+ return []runtimeLocalSkillSummary{}, true, nil+ }+ return nil, true, err+ }++ skills := make([]runtimeLocalSkillSummary, 0)+ err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return nil+ }+ if path == root {+ return nil+ }+ if entry.Type()&os.ModeSymlink != 0 {+ if entry.IsDir() {+ return filepath.SkipDir+ }+ return nil+ }+ if !entry.IsDir() {+ return nil+ }+ if isIgnoredLocalSkillEntry(entry.Name()) {+ return filepath.SkipDir+ }++ mainPath := filepath.Join(path, "SKILL.md")+ if _, err := os.Stat(mainPath); err != nil {+ return nil+ }++ rel, err := filepath.Rel(root, path)+ if err != nil {+ return filepath.SkipDir+ }+ key, err := normalizeLocalSkillKey(rel)+ if err != nil {+ return filepath.SkipDir+ }++ content, err := readLocalSkillMainFile(path)+ if err != nil {+ return filepath.SkipDir+ }+ name, description := parseLocalSkillFrontmatter(content)+ if name == "" {+ name = filepath.Base(path)+ }++ files, err := collectLocalSkillFiles(path, false)+ if err != nil {+ return filepath.SkipDir+ }++ skills = append(skills, runtimeLocalSkillSummary{+ Key: key,+ Name: name,+ Description: description,+ SourcePath: relativizeHomePath(path),+ Provider: provider,+ FileCount: len(files),+ })+ return filepath.SkipDir+ })+ if err != nil {+ return nil, true, err+ }++ sort.Slice(skills, func(i, j int) bool {+ return skills[i].Key < skills[j].Key+ })+ return skills, true, nil+}++func loadRuntimeLocalSkillBundle(provider, skillKey string) (*runtimeLocalSkillBundle, bool, error) {+ root, supported, err := localSkillRootForProvider(provider)+ if err != nil || !supported {+ return nil, supported, err+ }++ key, err := normalizeLocalSkillKey(skillKey)+ if err != nil {+ return nil, true, err+ }++ skillDir := filepath.Join(root, filepath.FromSlash(key))+ info, err := os.Stat(skillDir)+ if err != nil {+ if os.IsNotExist(err) {+ return nil, true, fmt.Errorf("local skill not found")+ }+ return nil, true, err+ }+ if !info.IsDir() {+ return nil, true, fmt.Errorf("local skill is not a directory")+ }++ content, err := readLocalSkillMainFile(skillDir)+ if err != nil {+ return nil, true, err+ }+ name, description := parseLocalSkillFrontmatter(content)+ if name == "" {+ name = filepath.Base(skillDir)+ }++ files, err := collectLocalSkillFiles(skillDir, true)+ if err != nil {+ return nil, true, err+ }++ return &runtimeLocalSkillBundle{+ Name: name,+ Description: description,+ Content: content,+ SourcePath: relativizeHomePath(skillDir),+ Provider: provider,+ Files: files,+ }, true, nil+}diff --git a/server/internal/daemon/local_skills_test.go b/server/internal/daemon/local_skills_test.gonew file mode 100644index 0000000000..a81efb92c3--- /dev/null+++ b/server/internal/daemon/local_skills_test.go@@ -0,0 +1,186 @@+package daemon++import (+ "os"+ "path/filepath"+ "testing"+)++func writeTestLocalSkill(t *testing.T, root, rel string, files map[string]string) string {+ t.Helper()++ skillDir := filepath.Join(root, filepath.FromSlash(rel))+ if err := os.MkdirAll(skillDir, 0o755); err != nil {+ t.Fatalf("mkdir skill dir: %v", err)+ }+ for path, content := range files {+ fullPath := filepath.Join(skillDir, filepath.FromSlash(path))+ if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {+ t.Fatalf("mkdir parents for %s: %v", path, err)+ }+ if err := os.WriteFile(fullPath, []byte(content), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+ }+ return skillDir+}++func TestListRuntimeLocalSkills_Claude(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)++ writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "review-helper", map[string]string{+ "SKILL.md": "---\nname: Review Helper\ndescription: Review pull requests\n---\n# Review Helper\n",+ "templates/check.md": "checklist",+ "LICENSE": "ignored",+ ".secret": "ignored",+ })++ skills, supported, err := listRuntimeLocalSkills("claude")+ if err != nil {+ t.Fatalf("listRuntimeLocalSkills: %v", err)+ }+ if !supported {+ t.Fatal("claude should be supported")+ }+ if len(skills) != 1 {+ t.Fatalf("expected 1 skill, got %d", len(skills))+ }++ skill := skills[0]+ if skill.Key != "review-helper" {+ t.Fatalf("key = %q, want review-helper", skill.Key)+ }+ if skill.Name != "Review Helper" {+ t.Fatalf("name = %q, want Review Helper", skill.Name)+ }+ if skill.Description != "Review pull requests" {+ t.Fatalf("description = %q", skill.Description)+ }+ if skill.FileCount != 1 {+ t.Fatalf("file_count = %d, want 1", skill.FileCount)+ }+ if skill.SourcePath != "~/.claude/skills/review-helper" {+ t.Fatalf("source_path = %q", skill.SourcePath)+ }+}++func TestListRuntimeLocalSkills_CodexUsesSharedCODEXHOME(t *testing.T) {+ home := t.TempDir()+ codexHome := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("CODEX_HOME", codexHome)++ writeTestLocalSkill(t, filepath.Join(codexHome, "skills"), "debugger", map[string]string{+ "SKILL.md": "# Debugger\n",+ })+ writeTestLocalSkill(t, filepath.Join(home, ".codex", "skills"), "wrong-home", map[string]string{+ "SKILL.md": "# Wrong Home\n",+ })++ skills, supported, err := listRuntimeLocalSkills("codex")+ if err != nil {+ t.Fatalf("listRuntimeLocalSkills: %v", err)+ }+ if !supported {+ t.Fatal("codex should be supported")+ }+ if len(skills) != 1 {+ t.Fatalf("expected 1 skill, got %d", len(skills))+ }+ if skills[0].Key != "debugger" {+ t.Fatalf("key = %q, want debugger", skills[0].Key)+ }+ if skills[0].SourcePath != filepath.Join(codexHome, "skills", "debugger") {+ t.Fatalf("source_path = %q", skills[0].SourcePath)+ }+}++func TestLoadRuntimeLocalSkillBundle_OpenCode(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)++ writeTestLocalSkill(t, filepath.Join(home, ".config", "opencode", "skills"), "release/reporter", map[string]string{+ "SKILL.md": "---\nname: Release Reporter\ndescription: Summarize release notes\n---\n# Release Reporter\n",+ "docs/template.md": "template body",+ "examples/sample.md": "sample body",+ })++ bundle, supported, err := loadRuntimeLocalSkillBundle("opencode", "release/reporter")+ if err != nil {+ t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)+ }+ if !supported {+ t.Fatal("opencode should be supported")+ }+ if bundle.Name != "Release Reporter" {+ t.Fatalf("name = %q", bundle.Name)+ }+ if bundle.Description != "Summarize release notes" {+ t.Fatalf("description = %q", bundle.Description)+ }+ if len(bundle.Files) != 2 {+ t.Fatalf("expected 2 supporting files, got %d", len(bundle.Files))+ }+ if bundle.Files[0].Path != "docs/template.md" || bundle.Files[0].Content != "template body" {+ t.Fatalf("unexpected first file: %+v", bundle.Files[0])+ }+ if bundle.Files[1].Path != "examples/sample.md" || bundle.Files[1].Content != "sample body" {+ t.Fatalf("unexpected second file: %+v", bundle.Files[1])+ }+ if bundle.SourcePath != "~/.config/opencode/skills/release/reporter" {+ t.Fatalf("source_path = %q", bundle.SourcePath)+ }+}++func TestListRuntimeLocalSkills_OpenClaw(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)++ writeTestLocalSkill(t, filepath.Join(home, ".openclaw", "skills"), "planner", map[string]string{+ "SKILL.md": "# Planner\n",+ })++ skills, supported, err := listRuntimeLocalSkills("openclaw")+ if err != nil {+ t.Fatalf("listRuntimeLocalSkills: %v", err)+ }+ if !supported {+ t.Fatal("openclaw should be supported")+ }+ if len(skills) != 1 {+ t.Fatalf("expected 1 skill, got %d", len(skills))+ }+ if skills[0].SourcePath != "~/.openclaw/skills/planner" {+ t.Fatalf("source_path = %q", skills[0].SourcePath)+ }+}++func TestLoadRuntimeLocalSkillBundle_Cursor(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)++ writeTestLocalSkill(t, filepath.Join(home, ".cursor", "skills"), "docs-helper", map[string]string{+ "SKILL.md": "---\nname: Docs Helper\n---\n# Docs Helper\n",+ "notes/tips.md": "tips",+ "examples/a.txt": "example",+ ".hidden/skip.txt": "ignore",+ })++ bundle, supported, err := loadRuntimeLocalSkillBundle("cursor", "docs-helper")+ if err != nil {+ t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)+ }+ if !supported {+ t.Fatal("cursor should be supported")+ }+ if bundle.Name != "Docs Helper" {+ t.Fatalf("name = %q", bundle.Name)+ }+ if len(bundle.Files) != 2 {+ t.Fatalf("expected 2 files, got %d", len(bundle.Files))+ }+ if bundle.SourcePath != "~/.cursor/skills/docs-helper" {+ t.Fatalf("source_path = %q", bundle.SourcePath)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 7de03b5163..f562c4fa6e 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -528,6 +528,20 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {resp["pending_model_list"] = map[string]string{"id": pending.ID}}+ // Check for pending local-skill list requests for this runtime.+ if pending := h.LocalSkillListStore.PopPending(req.RuntimeID); pending != nil {+ resp["pending_local_skills"] = map[string]string{"id": pending.ID}+ }++ // Check for pending local-skill import requests for this runtime.+ if pending := h.LocalSkillImportStore.PopPending(req.RuntimeID); pending != nil {+ payload := map[string]string{+ "id": pending.ID,+ "skill_key": pending.SkillKey,+ }+ resp["pending_local_skill_import"] = payload+ }+writeJSON(w, http.StatusOK, resp)}@@ -556,9 +570,9 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {start := time.Now()var (- outcome = "unauth"- authMs, claimMs, buildMs int64- buildStart time.Time+ outcome = "unauth"+ authMs, claimMs, buildMs int64+ buildStart time.Time)defer func() {// Emit at function exit so error / unauth paths also carry timing.diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex fa5b7b3f2f..1eb9e16ec3 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -39,21 +39,23 @@ type Config struct {}type Handler struct {- Queries *db.Queries- DB dbExecutor- TxStarter txStarter- Hub *realtime.Hub- Bus *events.Bus- TaskService *service.TaskService- AutopilotService *service.AutopilotService- EmailService *service.EmailService- PingStore *PingStore- UpdateStore *UpdateStore- ModelListStore *ModelListStore- Storage storage.Storage- CFSigner *auth.CloudFrontSigner- Analytics analytics.Client- cfg Config+ Queries *db.Queries+ DB dbExecutor+ TxStarter txStarter+ Hub *realtime.Hub+ Bus *events.Bus+ TaskService *service.TaskService+ AutopilotService *service.AutopilotService+ EmailService *service.EmailService+ PingStore *PingStore+ UpdateStore *UpdateStore+ ModelListStore *ModelListStore+ LocalSkillListStore *RuntimeLocalSkillListStore+ LocalSkillImportStore *RuntimeLocalSkillImportStore+ Storage storage.Storage+ CFSigner *auth.CloudFrontSigner+ Analytics analytics.Client+ cfg Config}func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, analyticsClient analytics.Client, cfg Config) *Handler {@@ -68,21 +70,23 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventtaskSvc := service.NewTaskService(queries, txStarter, hub, bus)return &Handler{- Queries: queries,- DB: executor,- TxStarter: txStarter,- Hub: hub,- Bus: bus,- TaskService: taskSvc,- AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),- EmailService: emailService,- PingStore: NewPingStore(),- UpdateStore: NewUpdateStore(),- ModelListStore: NewModelListStore(),- Storage: store,- CFSigner: cfSigner,- Analytics: analyticsClient,- cfg: cfg,+ Queries: queries,+ DB: executor,+ TxStarter: txStarter,+ Hub: hub,+ Bus: bus,+ TaskService: taskSvc,+ AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),+ EmailService: emailService,+ PingStore: NewPingStore(),+ UpdateStore: NewUpdateStore(),+ ModelListStore: NewModelListStore(),+ LocalSkillListStore: NewRuntimeLocalSkillListStore(),+ LocalSkillImportStore: NewRuntimeLocalSkillImportStore(),+ Storage: store,+ CFSigner: cfSigner,+ Analytics: analyticsClient,+ cfg: cfg,}}diff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.gonew file mode 100644index 0000000000..0abe6e5a06--- /dev/null+++ b/server/internal/handler/runtime_local_skills.go@@ -0,0 +1,557 @@+package handler++import (+ "encoding/json"+ "log/slog"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type RuntimeLocalSkillRequestStatus string++const (+ RuntimeLocalSkillPending RuntimeLocalSkillRequestStatus = "pending"+ RuntimeLocalSkillRunning RuntimeLocalSkillRequestStatus = "running"+ RuntimeLocalSkillCompleted RuntimeLocalSkillRequestStatus = "completed"+ RuntimeLocalSkillFailed RuntimeLocalSkillRequestStatus = "failed"+ RuntimeLocalSkillTimeout RuntimeLocalSkillRequestStatus = "timeout"+)++const (+ runtimeLocalSkillPendingTimeout = 30 * time.Second+ runtimeLocalSkillRunningTimeout = 60 * time.Second+ runtimeLocalSkillStoreRetention = 2 * time.Minute+)++type RuntimeLocalSkillSummary struct {+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ SourcePath string `json:"source_path"`+ Provider string `json:"provider"`+ FileCount int `json:"file_count"`+}++type RuntimeLocalSkillListRequest struct {+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ Status RuntimeLocalSkillRequestStatus `json:"status"`+ Skills []RuntimeLocalSkillSummary `json:"skills,omitempty"`+ Supported bool `json:"supported"`+ Error string `json:"error,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ RunStartedAt *time.Time `json:"-"`+}++type RuntimeLocalSkillImportRequest struct {+ ID string `json:"id"`+ RuntimeID string `json:"runtime_id"`+ SkillKey string `json:"skill_key"`+ Name *string `json:"name,omitempty"`+ Description *string `json:"description,omitempty"`+ Status RuntimeLocalSkillRequestStatus `json:"status"`+ Skill *SkillResponse `json:"skill,omitempty"`+ Error string `json:"error,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ CreatorID string `json:"-"`+ RunStartedAt *time.Time `json:"-"`+}++type RuntimeLocalSkillListStore struct {+ mu sync.Mutex+ requests map[string]*RuntimeLocalSkillListRequest+}++func NewRuntimeLocalSkillListStore() *RuntimeLocalSkillListStore {+ return &RuntimeLocalSkillListStore{requests: make(map[string]*RuntimeLocalSkillListRequest)}+}++func (s *RuntimeLocalSkillListStore) Create(runtimeID string) *RuntimeLocalSkillListRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ for id, req := range s.requests {+ if time.Since(req.CreatedAt) > runtimeLocalSkillStoreRetention {+ delete(s.requests, id)+ }+ }++ req := &RuntimeLocalSkillListRequest{+ ID: randomID(),+ RuntimeID: runtimeID,+ Status: RuntimeLocalSkillPending,+ Supported: true,+ CreatedAt: time.Now(),+ UpdatedAt: time.Now(),+ }+ s.requests[req.ID] = req+ return req+}++func (s *RuntimeLocalSkillListStore) Get(id string) *RuntimeLocalSkillListRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ req, ok := s.requests[id]+ if !ok {+ return nil+ }+ s.applyTimeout(req, time.Now())+ return req+}++func (s *RuntimeLocalSkillListStore) PopPending(runtimeID string) *RuntimeLocalSkillListRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ var oldest *RuntimeLocalSkillListRequest+ now := time.Now()+ for _, req := range s.requests {+ s.applyTimeout(req, now)+ if req.RuntimeID == runtimeID && req.Status == RuntimeLocalSkillPending {+ if oldest == nil || req.CreatedAt.Before(oldest.CreatedAt) {+ oldest = req+ }+ }+ }+ if oldest != nil {+ oldest.Status = RuntimeLocalSkillRunning+ startedAt := now+ oldest.RunStartedAt = &startedAt+ oldest.UpdatedAt = now+ }+ return oldest+}++func (s *RuntimeLocalSkillListStore) Complete(id string, skills []RuntimeLocalSkillSummary, supported bool) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if req, ok := s.requests[id]; ok {+ req.Status = RuntimeLocalSkillCompleted+ req.Skills = skills+ req.Supported = supported+ req.UpdatedAt = time.Now()+ }+}++func (s *RuntimeLocalSkillListStore) Fail(id string, errMsg string) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if req, ok := s.requests[id]; ok {+ req.Status = RuntimeLocalSkillFailed+ req.Error = errMsg+ req.UpdatedAt = time.Now()+ }+}++func (s *RuntimeLocalSkillListStore) applyTimeout(req *RuntimeLocalSkillListRequest, now time.Time) {+ switch req.Status {+ case RuntimeLocalSkillPending:+ if now.Sub(req.CreatedAt) > runtimeLocalSkillPendingTimeout {+ req.Status = RuntimeLocalSkillTimeout+ req.Error = "daemon did not respond within 30 seconds"+ req.UpdatedAt = now+ }+ case RuntimeLocalSkillRunning:+ if req.RunStartedAt != nil && now.Sub(*req.RunStartedAt) > runtimeLocalSkillRunningTimeout {+ req.Status = RuntimeLocalSkillTimeout+ req.Error = "daemon did not finish within 60 seconds"+ req.UpdatedAt = now+ }+ }+}++type RuntimeLocalSkillImportStore struct {+ mu sync.Mutex+ requests map[string]*RuntimeLocalSkillImportRequest+}++func NewRuntimeLocalSkillImportStore() *RuntimeLocalSkillImportStore {+ return &RuntimeLocalSkillImportStore{requests: make(map[string]*RuntimeLocalSkillImportRequest)}+}++func (s *RuntimeLocalSkillImportStore) Create(runtimeID, creatorID, skillKey string, name, description *string) *RuntimeLocalSkillImportRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ for id, req := range s.requests {+ if time.Since(req.CreatedAt) > runtimeLocalSkillStoreRetention {+ delete(s.requests, id)+ }+ }++ req := &RuntimeLocalSkillImportRequest{+ ID: randomID(),+ RuntimeID: runtimeID,+ SkillKey: skillKey,+ Name: name,+ Description: description,+ Status: RuntimeLocalSkillPending,+ CreatedAt: time.Now(),+ UpdatedAt: time.Now(),+ CreatorID: creatorID,+ }+ s.requests[req.ID] = req+ return req+}++func (s *RuntimeLocalSkillImportStore) Get(id string) *RuntimeLocalSkillImportRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ req, ok := s.requests[id]+ if !ok {+ return nil+ }+ s.applyTimeout(req, time.Now())+ return req+}++func (s *RuntimeLocalSkillImportStore) PopPending(runtimeID string) *RuntimeLocalSkillImportRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ var oldest *RuntimeLocalSkillImportRequest+ now := time.Now()+ for _, req := range s.requests {+ s.applyTimeout(req, now)+ if req.RuntimeID == runtimeID && req.Status == RuntimeLocalSkillPending {+ if oldest == nil || req.CreatedAt.Before(oldest.CreatedAt) {+ oldest = req+ }+ }+ }+ if oldest != nil {+ oldest.Status = RuntimeLocalSkillRunning+ startedAt := now+ oldest.RunStartedAt = &startedAt+ oldest.UpdatedAt = now+ }+ return oldest+}++func (s *RuntimeLocalSkillImportStore) Complete(id string, skill SkillResponse) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if req, ok := s.requests[id]; ok {+ req.Status = RuntimeLocalSkillCompleted+ req.Skill = &skill+ req.UpdatedAt = time.Now()+ }+}++func (s *RuntimeLocalSkillImportStore) Fail(id string, errMsg string) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if req, ok := s.requests[id]; ok {+ req.Status = RuntimeLocalSkillFailed+ req.Error = errMsg+ req.UpdatedAt = time.Now()+ }+}++func (s *RuntimeLocalSkillImportStore) applyTimeout(req *RuntimeLocalSkillImportRequest, now time.Time) {+ switch req.Status {+ case RuntimeLocalSkillPending:+ if now.Sub(req.CreatedAt) > runtimeLocalSkillPendingTimeout {+ req.Status = RuntimeLocalSkillTimeout+ req.Error = "daemon did not respond within 30 seconds"+ req.UpdatedAt = now+ }+ case RuntimeLocalSkillRunning:+ if req.RunStartedAt != nil && now.Sub(*req.RunStartedAt) > runtimeLocalSkillRunningTimeout {+ req.Status = RuntimeLocalSkillTimeout+ req.Error = "daemon did not finish within 60 seconds"+ req.UpdatedAt = now+ }+ }+}++type CreateRuntimeLocalSkillImportRequest struct {+ SkillKey string `json:"skill_key"`+ Name *string `json:"name,omitempty"`+ Description *string `json:"description,omitempty"`+}++type reportedRuntimeLocalSkill struct {+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ SourcePath string `json:"source_path"`+ Provider string `json:"provider"`+ Files []CreateSkillFileRequest `json:"files,omitempty"`+}++func cleanOptionalString(value *string) *string {+ if value == nil {+ return nil+ }+ trimmed := strings.TrimSpace(*value)+ if trimmed == "" {+ return nil+ }+ return &trimmed+}++func runtimeLocalSkillRequestTerminal(status RuntimeLocalSkillRequestStatus) bool {+ return status == RuntimeLocalSkillCompleted || status == RuntimeLocalSkillFailed || status == RuntimeLocalSkillTimeout+}++func (h *Handler) requireRuntimeLocalSkillAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (runtimeIDAndWorkspace, bool) {+ rt, err := h.Queries.GetAgentRuntime(r.Context(), parseUUID(runtimeID))+ if err != nil {+ writeError(w, http.StatusNotFound, "runtime not found")+ return runtimeIDAndWorkspace{}, false+ }++ wsID := uuidToString(rt.WorkspaceID)+ member, ok := h.requireWorkspaceMember(w, r, wsID, "runtime not found")+ if !ok {+ return runtimeIDAndWorkspace{}, false+ }++ if rt.OwnerID.Valid && uuidToString(rt.OwnerID) == uuidToString(member.UserID) {+ return runtimeIDAndWorkspace{+ runtimeID: runtimeID,+ workspaceID: wsID,+ provider: rt.Provider,+ status: rt.Status,+ }, true+ }++ writeError(w, http.StatusForbidden, "insufficient permissions")+ return runtimeIDAndWorkspace{}, false+}++type runtimeIDAndWorkspace struct {+ runtimeID string+ workspaceID string+ provider string+ status string+}++func (h *Handler) InitiateListLocalSkills(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ rt, ok := h.requireRuntimeLocalSkillAccess(w, r, runtimeID)+ if !ok {+ return+ }+ if rt.status != "online" {+ writeError(w, http.StatusServiceUnavailable, "runtime is offline")+ return+ }++ req := h.LocalSkillListStore.Create(runtimeID)+ writeJSON(w, http.StatusOK, req)+}++func (h *Handler) GetLocalSkillListRequest(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ if _, ok := h.requireRuntimeLocalSkillAccess(w, r, runtimeID); !ok {+ return+ }++ requestID := chi.URLParam(r, "requestId")+ req := h.LocalSkillListStore.Get(requestID)+ if req == nil || req.RuntimeID != runtimeID {+ writeError(w, http.StatusNotFound, "request not found")+ return+ }++ writeJSON(w, http.StatusOK, req)+}++func (h *Handler) InitiateImportLocalSkill(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ rt, ok := h.requireRuntimeLocalSkillAccess(w, r, runtimeID)+ if !ok {+ return+ }+ if rt.status != "online" {+ writeError(w, http.StatusServiceUnavailable, "runtime is offline")+ return+ }++ creatorID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ var req CreateRuntimeLocalSkillImportRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if strings.TrimSpace(req.SkillKey) == "" {+ writeError(w, http.StatusBadRequest, "skill_key is required")+ return+ }++ importReq := h.LocalSkillImportStore.Create(+ runtimeID,+ creatorID,+ strings.TrimSpace(req.SkillKey),+ cleanOptionalString(req.Name),+ cleanOptionalString(req.Description),+ )+ writeJSON(w, http.StatusOK, importReq)+}++func (h *Handler) GetLocalSkillImportRequest(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ if _, ok := h.requireRuntimeLocalSkillAccess(w, r, runtimeID); !ok {+ return+ }++ requestID := chi.URLParam(r, "requestId")+ req := h.LocalSkillImportStore.Get(requestID)+ if req == nil || req.RuntimeID != runtimeID {+ writeError(w, http.StatusNotFound, "request not found")+ return+ }++ writeJSON(w, http.StatusOK, req)+}++func (h *Handler) ReportLocalSkillListResult(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {+ return+ }++ requestID := chi.URLParam(r, "requestId")+ req := h.LocalSkillListStore.Get(requestID)+ if req == nil || req.RuntimeID != runtimeID {+ writeError(w, http.StatusNotFound, "request not found")+ return+ }+ if runtimeLocalSkillRequestTerminal(req.Status) {+ slog.Debug("ignoring stale runtime local skills report", "runtime_id", runtimeID, "request_id", requestID, "status", req.Status)+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+ return+ }++ var body struct {+ Status string `json:"status"`+ Skills []RuntimeLocalSkillSummary `json:"skills"`+ Supported *bool `json:"supported"`+ Error string `json:"error"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ if body.Status == "completed" {+ supported := true+ if body.Supported != nil {+ supported = *body.Supported+ }+ h.LocalSkillListStore.Complete(requestID, body.Skills, supported)+ } else {+ h.LocalSkillListStore.Fail(requestID, body.Error)+ }++ slog.Debug("runtime local skills report", "runtime_id", runtimeID, "request_id", requestID, "status", body.Status, "count", len(body.Skills))+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+}++func (h *Handler) ReportLocalSkillImportResult(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ rt, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID)+ if !ok {+ return+ }++ requestID := chi.URLParam(r, "requestId")+ req := h.LocalSkillImportStore.Get(requestID)+ if req == nil || req.RuntimeID != runtimeID {+ writeError(w, http.StatusNotFound, "request not found")+ return+ }+ if runtimeLocalSkillRequestTerminal(req.Status) {+ slog.Debug("ignoring stale runtime local skill import report", "runtime_id", runtimeID, "request_id", requestID, "status", req.Status)+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+ return+ }++ var body struct {+ Status string `json:"status"`+ Skill *reportedRuntimeLocalSkill `json:"skill"`+ Error string `json:"error"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ if body.Status != "completed" {+ h.LocalSkillImportStore.Fail(requestID, body.Error)+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+ return+ }+ if body.Skill == nil {+ h.LocalSkillImportStore.Fail(requestID, "daemon returned an empty skill bundle")+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+ return+ }++ name := body.Skill.Name+ if req.Name != nil {+ name = *req.Name+ }+ description := body.Skill.Description+ if req.Description != nil {+ description = *req.Description+ }++ files := make([]CreateSkillFileRequest, 0, len(body.Skill.Files))+ for _, f := range body.Skill.Files {+ if !validateFilePath(f.Path) {+ continue+ }+ files = append(files, f)+ }++ resp, err := h.createSkillWithFiles(r.Context(), skillCreateInput{+ WorkspaceID: uuidToString(rt.WorkspaceID),+ CreatorID: req.CreatorID,+ Name: name,+ Description: description,+ Content: body.Skill.Content,+ Config: map[string]any{+ "origin": map[string]any{+ "type": "runtime_local",+ "runtime_id": runtimeID,+ "provider": body.Skill.Provider,+ "source_path": body.Skill.SourcePath,+ },+ },+ Files: files,+ })+ if err != nil {+ if isUniqueViolation(err) {+ h.LocalSkillImportStore.Fail(requestID, "a skill with this name already exists")+ } else {+ h.LocalSkillImportStore.Fail(requestID, err.Error())+ }+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+ return+ }++ h.LocalSkillImportStore.Complete(requestID, resp.SkillResponse)+ h.publish(protocol.EventSkillCreated, uuidToString(rt.WorkspaceID), "member", req.CreatorID, map[string]any{"skill": resp})+ slog.Debug("runtime local skill imported", "runtime_id", runtimeID, "request_id", requestID, "skill_id", resp.ID)+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})+}diff --git a/server/internal/handler/runtime_local_skills_test.go b/server/internal/handler/runtime_local_skills_test.gonew file mode 100644index 0000000000..e8507a5894--- /dev/null+++ b/server/internal/handler/runtime_local_skills_test.go@@ -0,0 +1,438 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func newRequestAsUser(userID, method, path string, body any) *http.Request {+ var buf bytes.Buffer+ if body != nil {+ json.NewEncoder(&buf).Encode(body)+ }+ req := httptest.NewRequest(method, path, &buf)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-User-ID", userID)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ return req+}++func createRuntimeLocalSkillTestRuntime(t *testing.T, ownerID string) string {+ t.Helper()++ runtimeName := fmt.Sprintf("runtime-local-skill-%d", time.Now().UnixNano())+ daemonID := fmt.Sprintf("runtime-local-skill-daemon-%d", time.Now().UnixNano())++ var runtimeID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO agent_runtime (+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at+ )+ VALUES ($1, $2, $3, 'local', 'claude', 'online', 'Runtime Local Skills Test', '{}'::jsonb, $4, now())+ RETURNING id+ `, testWorkspaceID, daemonID, runtimeName, ownerID).Scan(&runtimeID); err != nil {+ t.Fatalf("create local runtime: %v", err)+ }++ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+ })++ return runtimeID+}++func createRuntimeLocalSkillTestMember(t *testing.T, role string) string {+ t.Helper()++ email := fmt.Sprintf("runtime-local-skills-%[email protected]", time.Now().UnixNano())+ name := fmt.Sprintf("Runtime Local Skills %s", role)++ var userID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO "user" (name, email)+ VALUES ($1, $2)+ RETURNING id+ `, name, email).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }++ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO member (workspace_id, user_id, role)+ VALUES ($1, $2, $3)+ `, testWorkspaceID, userID, role); err != nil {+ t.Fatalf("create member: %v", err)+ }++ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })++ return userID+}++func countSkillsByName(t *testing.T, name string) int {+ t.Helper()++ var count int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*)+ FROM skill+ WHERE workspace_id = $1 AND name = $2+ `, testWorkspaceID, name).Scan(&count); err != nil {+ t.Fatalf("count skills: %v", err)+ }++ return count+}++func countSkillFiles(t *testing.T, skillID string) int {+ t.Helper()++ var count int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*)+ FROM skill_file+ WHERE skill_id = $1+ `, skillID).Scan(&count); err != nil {+ t.Fatalf("count skill files: %v", err)+ }++ return count+}++func TestRuntimeLocalSkillListStore_PreservesSummaries(t *testing.T) {+ store := NewRuntimeLocalSkillListStore()+ req := store.Create("runtime-xyz")++ body := map[string]any{+ "status": "completed",+ "supported": true,+ "skills": []map[string]any{+ {+ "key": "review-helper",+ "name": "Review Helper",+ "description": "Review PRs",+ "source_path": "~/.claude/skills/review-helper",+ "provider": "claude",+ "file_count": 2,+ },+ },+ }+ raw, _ := json.Marshal(body)++ var parsed struct {+ Skills []RuntimeLocalSkillSummary `json:"skills"`+ }+ if err := json.Unmarshal(raw, &parsed); err != nil {+ t.Fatalf("unmarshal report body: %v", err)+ }++ store.Complete(req.ID, parsed.Skills, true)+ got := store.Get(req.ID)+ if got == nil {+ t.Fatal("expected stored result")+ }+ if len(got.Skills) != 1 {+ t.Fatalf("expected 1 skill, got %d", len(got.Skills))+ }+ if got.Skills[0].SourcePath != "~/.claude/skills/review-helper" {+ t.Fatalf("source_path = %q", got.Skills[0].SourcePath)+ }+ if got.Skills[0].FileCount != 2 {+ t.Fatalf("file_count = %d", got.Skills[0].FileCount)+ }+}++func TestRuntimeLocalSkillListStore_TimesOutRunningRequests(t *testing.T) {+ store := NewRuntimeLocalSkillListStore()+ req := store.Create("runtime-xyz")+ req.Status = RuntimeLocalSkillRunning+ startedAt := time.Now().Add(-61 * time.Second)+ req.RunStartedAt = &startedAt++ got := store.Get(req.ID)+ if got == nil {+ t.Fatal("expected stored request")+ }+ if got.Status != RuntimeLocalSkillTimeout {+ t.Fatalf("expected timeout, got %s", got.Status)+ }+ if got.Error == "" {+ t.Fatal("expected timeout error")+ }+}++func TestRuntimeLocalSkillImportStore_TimesOutRunningRequests(t *testing.T) {+ store := NewRuntimeLocalSkillImportStore()+ req := store.Create("runtime-xyz", "user-1", "review-helper", nil, nil)+ req.Status = RuntimeLocalSkillRunning+ startedAt := time.Now().Add(-61 * time.Second)+ req.RunStartedAt = &startedAt++ got := store.Get(req.ID)+ if got == nil {+ t.Fatal("expected stored request")+ }+ if got.Status != RuntimeLocalSkillTimeout {+ t.Fatalf("expected timeout, got %s", got.Status)+ }+ if got.Error == "" {+ t.Fatal("expected timeout error")+ }+}++func TestInitiateListLocalSkills_RequiresRuntimeOwner(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ adminUserID := createRuntimeLocalSkillTestMember(t, "admin")++ w := httptest.NewRecorder()+ req := withURLParams(+ newRequestAsUser(adminUserID, http.MethodPost, "/api/runtimes/"+runtimeID+"/local-skills", nil),+ "runtimeId", runtimeID,+ )++ testHandler.InitiateListLocalSkills(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())+ }+}++func TestGetLocalSkillImportRequest_RequiresRuntimeOwner(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ adminUserID := createRuntimeLocalSkillTestMember(t, "admin")+ importReq := testHandler.LocalSkillImportStore.Create(runtimeID, testUserID, "review-helper", nil, nil)++ w := httptest.NewRecorder()+ req := withURLParams(+ newRequestAsUser(adminUserID, http.MethodGet, "/api/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID, nil),+ "runtimeId", runtimeID,+ "requestId", importReq.ID,+ )++ testHandler.GetLocalSkillImportRequest(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())+ }+}++func TestRuntimeLocalSkillImportFlow_EndToEnd(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)++ w := httptest.NewRecorder()+ initReq := withURLParams(+ newRequestAsUser(testUserID, http.MethodPost, "/api/runtimes/"+runtimeID+"/local-skills/import", map[string]any{+ "skill_key": "review-helper",+ "name": "Imported Review Helper",+ "description": "Imported description",+ }),+ "runtimeId", runtimeID,+ )+ testHandler.InitiateImportLocalSkill(w, initReq)+ if w.Code != http.StatusOK {+ t.Fatalf("InitiateImportLocalSkill: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var importReq RuntimeLocalSkillImportRequest+ if err := json.NewDecoder(w.Body).Decode(&importReq); err != nil {+ t.Fatalf("decode import request: %v", err)+ }++ w = httptest.NewRecorder()+ heartbeatReq := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{+ "runtime_id": runtimeID,+ }, testWorkspaceID, "runtime-local-skills-daemon")+ testHandler.DaemonHeartbeat(w, heartbeatReq)+ if w.Code != http.StatusOK {+ t.Fatalf("DaemonHeartbeat: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var heartbeatResp map[string]any+ if err := json.NewDecoder(w.Body).Decode(&heartbeatResp); err != nil {+ t.Fatalf("decode heartbeat response: %v", err)+ }+ pending, ok := heartbeatResp["pending_local_skill_import"].(map[string]any)+ if !ok {+ t.Fatalf("expected pending_local_skill_import, got %v", heartbeatResp)+ }+ if pending["id"] != importReq.ID {+ t.Fatalf("pending id = %v, want %s", pending["id"], importReq.ID)+ }+ if pending["skill_key"] != "review-helper" {+ t.Fatalf("pending skill_key = %v", pending["skill_key"])+ }+ if _, ok := pending["name"]; ok {+ t.Fatalf("heartbeat payload should not include name: %v", pending)+ }+ if _, ok := pending["description"]; ok {+ t.Fatalf("heartbeat payload should not include description: %v", pending)+ }++ w = httptest.NewRecorder()+ reportReq := withURLParams(+ newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{+ "status": "completed",+ "skill": map[string]any{+ "name": "Original Review Helper",+ "description": "Original description",+ "content": "# Review Helper",+ "source_path": "~/.claude/skills/review-helper",+ "provider": "claude",+ "files": []map[string]any{+ {+ "path": "templates/check.md",+ "content": "body",+ },+ },+ },+ }, testWorkspaceID, "runtime-local-skills-daemon"),+ "runtimeId", runtimeID,+ "requestId", importReq.ID,+ )+ testHandler.ReportLocalSkillImportResult(w, reportReq)+ if w.Code != http.StatusOK {+ t.Fatalf("ReportLocalSkillImportResult: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ w = httptest.NewRecorder()+ pollReq := withURLParams(+ newRequestAsUser(testUserID, http.MethodGet, "/api/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID, nil),+ "runtimeId", runtimeID,+ "requestId", importReq.ID,+ )+ testHandler.GetLocalSkillImportRequest(w, pollReq)+ if w.Code != http.StatusOK {+ t.Fatalf("GetLocalSkillImportRequest: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var completed RuntimeLocalSkillImportRequest+ if err := json.NewDecoder(w.Body).Decode(&completed); err != nil {+ t.Fatalf("decode poll response: %v", err)+ }+ if completed.Status != RuntimeLocalSkillCompleted {+ t.Fatalf("expected completed status, got %s", completed.Status)+ }+ if completed.Skill == nil {+ t.Fatal("expected imported skill")+ }+ if completed.Skill.Name != "Imported Review Helper" {+ t.Fatalf("imported name = %q", completed.Skill.Name)+ }+ if completed.Skill.Description != "Imported description" {+ t.Fatalf("imported description = %q", completed.Skill.Description)+ }+ if got := countSkillFiles(t, completed.Skill.ID); got != 1 {+ t.Fatalf("expected 1 imported file, got %d", got)+ }+}++func TestReportLocalSkillImportResult_IgnoresTimedOutRequests(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ importReq := testHandler.LocalSkillImportStore.Create(+ runtimeID,+ testUserID,+ "review-helper",+ cleanOptionalString(ptr("Timed Out Import")),+ cleanOptionalString(ptr("Should not be created")),+ )+ importReq.Status = RuntimeLocalSkillRunning+ startedAt := time.Now().Add(-61 * time.Second)+ importReq.RunStartedAt = &startedAt++ timedOut := testHandler.LocalSkillImportStore.Get(importReq.ID)+ if timedOut == nil || timedOut.Status != RuntimeLocalSkillTimeout {+ t.Fatalf("expected timed out request, got %#v", timedOut)+ }++ beforeCount := countSkillsByName(t, "Timed Out Import")++ w := httptest.NewRecorder()+ reportReq := withURLParams(+ newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{+ "status": "completed",+ "skill": map[string]any{+ "name": "Original Review Helper",+ "description": "Original description",+ "content": "# Review Helper",+ "source_path": "~/.claude/skills/review-helper",+ "provider": "claude",+ },+ }, testWorkspaceID, "runtime-local-skills-daemon"),+ "runtimeId", runtimeID,+ "requestId", importReq.ID,+ )+ testHandler.ReportLocalSkillImportResult(w, reportReq)+ if w.Code != http.StatusOK {+ t.Fatalf("ReportLocalSkillImportResult: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ afterCount := countSkillsByName(t, "Timed Out Import")+ if afterCount != beforeCount {+ t.Fatalf("expected timed out report to be ignored, count before=%d after=%d", beforeCount, afterCount)+ }+}++func TestReportLocalSkillImportResult_RejectsCrossWorkspaceDaemonToken(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ importReq := testHandler.LocalSkillImportStore.Create(runtimeID, testUserID, "review-helper", nil, nil)++ w := httptest.NewRecorder()+ reportReq := withURLParams(+ newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{+ "status": "failed",+ "error": "forbidden",+ }, "00000000-0000-0000-0000-000000000000", "attacker-daemon"),+ "runtimeId", runtimeID,+ "requestId", importReq.ID,+ )+ testHandler.ReportLocalSkillImportResult(w, reportReq)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestCleanOptionalString(t *testing.T) {+ if got := cleanOptionalString(nil); got != nil {+ t.Fatalf("expected nil, got %q", *got)+ }++ raw := " "+ if got := cleanOptionalString(&raw); got != nil {+ t.Fatalf("expected nil for whitespace-only value, got %q", *got)+ }++ value := " Review Helper "+ got := cleanOptionalString(&value)+ if got == nil || *got != "Review Helper" {+ t.Fatalf("expected trimmed value, got %#v", got)+ }+}++func ptr[T any](value T) *T {+ return &value+}diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex 71de39aa21..b79bdf772c 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -209,27 +209,14 @@ func (h *Handler) CreateSkill(w http.ResponseWriter, r *http.Request) {}}- config, _ := json.Marshal(req.Config)- if req.Config == nil {- config = []byte("{}")- }-- tx, err := h.TxStarter.Begin(r.Context())- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to start transaction")- return- }- defer tx.Rollback(r.Context())-- qtx := h.Queries.WithTx(tx)-- skill, err := qtx.CreateSkill(r.Context(), db.CreateSkillParams{- WorkspaceID: parseUUID(workspaceID),+ resp, err := h.createSkillWithFiles(r.Context(), skillCreateInput{+ WorkspaceID: workspaceID,+ CreatorID: creatorID,Name: req.Name,Description: req.Description,Content: req.Content,- Config: config,- CreatedBy: parseUUID(creatorID),+ Config: req.Config,+ Files: req.Files,})if err != nil {if isUniqueViolation(err) {@@ -239,30 +226,6 @@ func (h *Handler) CreateSkill(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to create skill: "+err.Error())return}-- fileResps := make([]SkillFileResponse, 0, len(req.Files))- for _, f := range req.Files {- sf, err := qtx.UpsertSkillFile(r.Context(), db.UpsertSkillFileParams{- SkillID: skill.ID,- Path: f.Path,- Content: f.Content,- })- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to create skill file: "+err.Error())- return- }- fileResps = append(fileResps, skillFileToResponse(sf))- }-- if err := tx.Commit(r.Context()); err != nil {- writeError(w, http.StatusInternalServerError, "failed to commit")- return- }-- resp := SkillWithFilesResponse{- SkillResponse: skillToResponse(skill),- Files: fileResps,- }actorType, actorID := h.resolveActor(r, creatorID, workspaceID)h.publish(protocol.EventSkillCreated, workspaceID, actorType, actorID, map[string]any{"skill": resp})writeJSON(w, http.StatusCreated, resp)@@ -868,23 +831,25 @@ func (h *Handler) ImportSkill(w http.ResponseWriter, r *http.Request) {return}- // Create skill in database- tx, err := h.TxStarter.Begin(r.Context())- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to start transaction")- return+ files := make([]CreateSkillFileRequest, 0, len(imported.files))+ for _, f := range imported.files {+ if !validateFilePath(f.path) {+ continue+ }+ files = append(files, CreateSkillFileRequest{+ Path: f.path,+ Content: f.content,+ })}- defer tx.Rollback(r.Context())- qtx := h.Queries.WithTx(tx)-- skill, err := qtx.CreateSkill(r.Context(), db.CreateSkillParams{- WorkspaceID: parseUUID(workspaceID),+ resp, err := h.createSkillWithFiles(r.Context(), skillCreateInput{+ WorkspaceID: workspaceID,+ CreatorID: creatorID,Name: imported.name,Description: imported.description,Content: imported.content,- Config: []byte("{}"),- CreatedBy: parseUUID(creatorID),+ Config: map[string]any{},+ Files: files,})if err != nil {if isUniqueViolation(err) {@@ -894,32 +859,6 @@ func (h *Handler) ImportSkill(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to create skill: "+err.Error())return}-- fileResps := make([]SkillFileResponse, 0, len(imported.files))- for _, f := range imported.files {- if !validateFilePath(f.path) {- continue- }- sf, err := qtx.UpsertSkillFile(r.Context(), db.UpsertSkillFileParams{- SkillID: skill.ID,- Path: f.path,- Content: f.content,- })- if err != nil {- continue- }- fileResps = append(fileResps, skillFileToResponse(sf))- }-- if err := tx.Commit(r.Context()); err != nil {- writeError(w, http.StatusInternalServerError, "failed to commit")- return- }-- resp := SkillWithFilesResponse{- SkillResponse: skillToResponse(skill),- Files: fileResps,- }actorType, actorID := h.resolveActor(r, creatorID, workspaceID)h.publish(protocol.EventSkillCreated, workspaceID, actorType, actorID, map[string]any{"skill": resp})writeJSON(w, http.StatusCreated, resp)diff --git a/server/internal/handler/skill_create.go b/server/internal/handler/skill_create.gonew file mode 100644index 0000000000..0e3a70b285--- /dev/null+++ b/server/internal/handler/skill_create.go@@ -0,0 +1,70 @@+package handler++import (+ "context"+ "encoding/json"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type skillCreateInput struct {+ WorkspaceID string+ CreatorID string+ Name string+ Description string+ Content string+ Config any+ Files []CreateSkillFileRequest+}++func (h *Handler) createSkillWithFiles(ctx context.Context, input skillCreateInput) (SkillWithFilesResponse, error) {+ config, err := json.Marshal(input.Config)+ if err != nil {+ return SkillWithFilesResponse{}, err+ }+ if input.Config == nil {+ config = []byte("{}")+ }++ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return SkillWithFilesResponse{}, err+ }+ defer tx.Rollback(ctx)++ qtx := h.Queries.WithTx(tx)++ skill, err := qtx.CreateSkill(ctx, db.CreateSkillParams{+ WorkspaceID: parseUUID(input.WorkspaceID),+ Name: input.Name,+ Description: input.Description,+ Content: input.Content,+ Config: config,+ CreatedBy: parseUUID(input.CreatorID),+ })+ if err != nil {+ return SkillWithFilesResponse{}, err+ }++ fileResps := make([]SkillFileResponse, 0, len(input.Files))+ for _, f := range input.Files {+ sf, err := qtx.UpsertSkillFile(ctx, db.UpsertSkillFileParams{+ SkillID: skill.ID,+ Path: f.Path,+ Content: f.Content,+ })+ if err != nil {+ return SkillWithFilesResponse{}, err+ }+ fileResps = append(fileResps, skillFileToResponse(sf))+ }++ if err := tx.Commit(ctx); err != nil {+ return SkillWithFilesResponse{}, err+ }++ return SkillWithFilesResponse{+ SkillResponse: skillToResponse(skill),+ Files: fileResps,+ }, nil+}