Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(skills): support multi-select bulk import in Copy from runtime (#2686)
AdamQQQfab067133233
diff --git a/packages/core/runtimes/local-skills.ts b/packages/core/runtimes/local-skills.tsindex 90a4eef4b6..20f7fe0b36 100644--- a/packages/core/runtimes/local-skills.ts+++ b/packages/core/runtimes/local-skills.ts@@ -14,6 +14,17 @@ export const runtimeLocalSkillsKeys = {const POLL_INTERVAL_MS = 500;const POLL_TIMEOUT_MS = 30_000;+// Import timeout is longer than discovery because old daemons (pre-batch) pop+// only one import per heartbeat cycle (~15s). With 10 queued imports the 10th+// can wait up to 150s in pending before being claimed, plus up to 60s for+// the daemon to actually run the import.+//+// Timeout invariant: IMPORT_POLL_TIMEOUT_MS must exceed+// runtimeLocalSkillPendingTimeout + runtimeLocalSkillRunningTimeout+// (server/internal/handler/runtime_local_skills.go).+// See also IMPORT_CONCURRENCY in packages/views/.../runtime-local-skill-import-panel.tsx+// and maxLocalSkillImportBatch in server/internal/handler/daemon.go.+const IMPORT_POLL_TIMEOUT_MS = 4 * 60_000; // 4 minutesexport async function resolveRuntimeLocalSkills(runtimeId: string,@@ -49,7 +60,7 @@ export async function resolveRuntimeLocalSkillImport(let current = initial;while (current.status === "pending" || current.status === "running") {- if (Date.now() - start > POLL_TIMEOUT_MS) {+ if (Date.now() - start > IMPORT_POLL_TIMEOUT_MS) {throw new Error("runtime local skill import timed out");}await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.jsonindex f0968d22e6..de6a32b0b2 100644--- a/packages/views/locales/en/skills.json+++ b/packages/views/locales/en/skills.json@@ -222,7 +222,18 @@"skill_description_label": "Description","skill_description_placeholder": "Optional — describe when an agent should use this skill.","toast_imported": "Skill imported",- "toast_import_failed": "Failed to import skill"+ "toast_import_failed": "Failed to import skill",+ "select_all": "Select all ({{count}})",+ "bulk_ready": "{{count}} skills selected",+ "bulk_import_button": "Import {{count}} Skills",+ "bulk_progress": "Importing {{completed}} / {{total}}…",+ "bulk_cancel_button": "Cancel",+ "bulk_complete_hint": "Import complete.",+ "bulk_cancelled_hint": "Import cancelled.",+ "bulk_done_button": "Done",+ "bulk_summary_imported": "Imported",+ "bulk_summary_skipped": "Skipped",+ "bulk_summary_failed": "Failed"},"file_tree": {"no_files": "No files"diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.jsonindex 906943bfe6..611a80cb41 100644--- a/packages/views/locales/zh-Hans/skills.json+++ b/packages/views/locales/zh-Hans/skills.json@@ -234,7 +234,18 @@"skill_description_label": "描述","skill_description_placeholder": "可选——描述智能体什么时候应该使用这个 skill。","toast_imported": "已导入 skill",- "toast_import_failed": "导入 skill 失败"+ "toast_import_failed": "导入 skill 失败",+ "select_all": "全选 ({{count}})",+ "bulk_ready": "已选择 {{count}} 个 skill",+ "bulk_import_button": "导入 {{count}} 个 skill",+ "bulk_progress": "正在导入 {{completed}} / {{total}}…",+ "bulk_cancel_button": "取消",+ "bulk_complete_hint": "导入完成。",+ "bulk_cancelled_hint": "导入已取消。",+ "bulk_done_button": "完成",+ "bulk_summary_imported": "已导入",+ "bulk_summary_skipped": "已跳过",+ "bulk_summary_failed": "失败"},"file_tree": {"no_files": "无文件"diff --git a/packages/views/skills/components/create-skill-dialog.tsx b/packages/views/skills/components/create-skill-dialog.tsxindex 2a4e15d1ce..e52908547e 100644--- a/packages/views/skills/components/create-skill-dialog.tsx+++ b/packages/views/skills/components/create-skill-dialog.tsx@@ -41,6 +41,7 @@ import { cn } from "@multica/ui/lib/utils";import { openExternal } from "../../platform";import { RuntimeLocalSkillImportPanel } from "./runtime-local-skill-import-panel";import { useT } from "../../i18n";+import { isNameConflictError } from "../lib/utils";type Method = "chooser" | "manual" | "url" | "runtime";@@ -54,10 +55,6 @@ function seedAfterCreate(qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });}-function isNameConflictError(msg: string): boolean {- return /\b(409|conflict|already exists|unique constraint)\b/i.test(msg);-}-// ---------------------------------------------------------------------------// Chooser — initial method picker (3 cards)// ---------------------------------------------------------------------------@@ -517,7 +514,10 @@ export function CreateSkillDialog({/>)}{method === "runtime" && (- <RuntimeLocalSkillImportPanel onImported={handleCreated} />+ <RuntimeLocalSkillImportPanel+ onImported={handleCreated}+ onBulkDone={onClose}+ />)}</DialogContent></Dialog>diff --git a/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx b/packages/views/skills/components/runtime-local-skill-import-panel.test.tsxindex b2739132cf..bff9953fef 100644--- a/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx+++ b/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx@@ -57,14 +57,75 @@ function I18nWrapper({ children }: { children: ReactNode }) {);}-function renderPanel() {+const MOCK_RUNTIME = {+ 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",+};++const MOCK_SKILL_A = {+ key: "review-helper",+ name: "Review Helper",+ description: "Review pull requests",+ provider: "claude",+ source_path: "~/.claude/skills/review-helper",+ file_count: 2,+};++const MOCK_SKILL_B = {+ key: "code-gen",+ name: "Code Gen",+ description: "Generate code from specs",+ provider: "claude",+ source_path: "~/.claude/skills/code-gen",+ file_count: 3,+};++const MOCK_IMPORTED_SKILL_A = {+ id: "skill-1",+ 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",+};++const MOCK_IMPORTED_SKILL_B = {+ id: "skill-2",+ workspace_id: "ws-1",+ name: "Code Gen",+ description: "Generate code from specs",+ content: "# Code Gen",+ config: {},+ files: [],+ created_by: "user-1",+ created_at: "2026-04-16T00:00:00Z",+ updated_at: "2026-04-16T00:00:00Z",+};++function renderPanel(props: { onImported?: (skill: unknown) => void; onBulkDone?: () => void } = {}) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});return render(<I18nWrapper><QueryClientProvider client={queryClient}>- <RuntimeLocalSkillImportPanel />+ <RuntimeLocalSkillImportPanel {...props} /></QueryClientProvider></I18nWrapper>,);@@ -76,70 +137,33 @@ describe("RuntimeLocalSkillImportPanel", () => {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",- },- ]),+ queryFn: () => Promise.resolve([MOCK_RUNTIME]),});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,- },- ],+ skills: [MOCK_SKILL_A],}),});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",- },+ skill: MOCK_IMPORTED_SKILL_A,});});- it("imports a local skill from the selected runtime", async () => {+ it("imports a single skill when selected via checkbox", async () => {renderPanel();- // Five-step async cascade (runtime list → setSelectedRuntimeId effect →- // skills query → auto-select effect → row render). Fast locally, slow on- // CI — bump timeouts above RTL's 1 s default so the jsdom/Vitest work- // queue actually has time to drain.+ // Wait for skill list to renderexpect(await screen.findByText("Review Helper", {}, { timeout: 5000 }),).toBeInTheDocument();+ // Click the skill row to toggle its checkbox+ const skillButton = screen.getByRole("button", { name: /Review Helper/i });+ fireEvent.click(skillButton);+const importButton = screen.getByRole("button", {name: /Import to Workspace/i,});@@ -165,4 +189,200 @@ describe("RuntimeLocalSkillImportPanel", () => {{ timeout: 5000 },);});++ it("imports multiple skills in sequence and shows summary", async () => {+ mockRuntimeLocalSkillsOptions.mockReturnValue({+ queryKey: ["runtimes", "local-skills", "runtime-1"],+ queryFn: () =>+ Promise.resolve({+ supported: true,+ skills: [MOCK_SKILL_A, MOCK_SKILL_B],+ }),+ });+ mockResolveRuntimeLocalSkillImport+ .mockResolvedValueOnce({ skill: MOCK_IMPORTED_SKILL_A })+ .mockResolvedValueOnce({ skill: MOCK_IMPORTED_SKILL_B });++ renderPanel();++ // Wait for skills to render+ expect(+ await screen.findByText("Review Helper", {}, { timeout: 5000 }),+ ).toBeInTheDocument();+ expect(screen.getByText("Code Gen")).toBeInTheDocument();++ // Click select all checkbox (the native one in the label)+ const selectAllLabel = screen.getByText(/Select all/i);+ const selectAllCheckbox = selectAllLabel.closest("label")!.querySelector("input[type='checkbox']")!;+ fireEvent.click(selectAllCheckbox);++ // Button should now say "Import 2 Skills"+ const importButton = screen.getByRole("button", {+ name: /Import 2 Skills/i,+ });+ await waitFor(+ () => {+ expect(importButton).not.toBeDisabled();+ },+ { timeout: 5000 },+ );+ fireEvent.click(importButton);++ // Wait for completion — summary should appear with "Done" button+ await waitFor(+ () => {+ expect(+ screen.getByRole("button", { name: /Done/i }),+ ).toBeInTheDocument();+ },+ { timeout: 10000 },+ );++ expect(mockResolveRuntimeLocalSkillImport).toHaveBeenCalledTimes(2);++ // Verify summary shows both as imported+ expect(screen.getByText("Imported")).toBeInTheDocument();+ });++ it("handles partial failures gracefully", async () => {+ mockRuntimeLocalSkillsOptions.mockReturnValue({+ queryKey: ["runtimes", "local-skills", "runtime-1"],+ queryFn: () =>+ Promise.resolve({+ supported: true,+ skills: [MOCK_SKILL_A, MOCK_SKILL_B],+ }),+ });+ mockResolveRuntimeLocalSkillImport+ .mockResolvedValueOnce({ skill: MOCK_IMPORTED_SKILL_A })+ .mockRejectedValueOnce(new Error("409 conflict: already exists"));++ renderPanel();++ // Wait for skills+ expect(+ await screen.findByText("Review Helper", {}, { timeout: 5000 }),+ ).toBeInTheDocument();++ // Select all+ const selectAllLabel2 = screen.getByText(/Select all/i);+ const selectAllCheckbox2 = selectAllLabel2.closest("label")!.querySelector("input[type='checkbox']")!;+ fireEvent.click(selectAllCheckbox2);++ // Import+ const importButton = screen.getByRole("button", {+ name: /Import 2 Skills/i,+ });+ await waitFor(+ () => {+ expect(importButton).not.toBeDisabled();+ },+ { timeout: 5000 },+ );+ fireEvent.click(importButton);++ // Wait for Done+ await waitFor(+ () => {+ expect(+ screen.getByRole("button", { name: /Done/i }),+ ).toBeInTheDocument();+ },+ { timeout: 10000 },+ );++ // Summary should show imported and skipped+ expect(screen.getByText("Imported")).toBeInTheDocument();+ expect(screen.getByText("Skipped")).toBeInTheDocument();+ });++ it("calls onImported when exactly one skill succeeds", async () => {+ const onImported = vi.fn();+ renderPanel({ onImported });++ expect(+ await screen.findByText("Review Helper", {}, { timeout: 5000 }),+ ).toBeInTheDocument();++ // Select the single skill+ const skillButton = screen.getByRole("button", { name: /Review Helper/i });+ fireEvent.click(skillButton);++ const importButton = screen.getByRole("button", {+ name: /Import to Workspace/i,+ });+ await waitFor(+ () => {+ expect(importButton).not.toBeDisabled();+ },+ { timeout: 5000 },+ );+ fireEvent.click(importButton);++ // Wait for Done button+ await waitFor(+ () => {+ expect(+ screen.getByRole("button", { name: /Done/i }),+ ).toBeInTheDocument();+ },+ { timeout: 10000 },+ );++ // Click Done — should call onImported with the single skill+ fireEvent.click(screen.getByRole("button", { name: /Done/i }));+ expect(onImported).toHaveBeenCalledWith(MOCK_IMPORTED_SKILL_A);+ });++ it("calls onBulkDone when multiple skills succeed", async () => {+ mockRuntimeLocalSkillsOptions.mockReturnValue({+ queryKey: ["runtimes", "local-skills", "runtime-1"],+ queryFn: () =>+ Promise.resolve({+ supported: true,+ skills: [MOCK_SKILL_A, MOCK_SKILL_B],+ }),+ });+ mockResolveRuntimeLocalSkillImport+ .mockResolvedValueOnce({ skill: MOCK_IMPORTED_SKILL_A })+ .mockResolvedValueOnce({ skill: MOCK_IMPORTED_SKILL_B });++ const onImported = vi.fn();+ const onBulkDone = vi.fn();+ renderPanel({ onImported, onBulkDone });++ expect(+ await screen.findByText("Review Helper", {}, { timeout: 5000 }),+ ).toBeInTheDocument();++ // Select all+ const selectAllLabel3 = screen.getByText(/Select all/i);+ const selectAllCheckbox3 = selectAllLabel3.closest("label")!.querySelector("input[type='checkbox']")!;+ fireEvent.click(selectAllCheckbox3);++ const importButton = screen.getByRole("button", {+ name: /Import 2 Skills/i,+ });+ await waitFor(+ () => {+ expect(importButton).not.toBeDisabled();+ },+ { timeout: 5000 },+ );+ fireEvent.click(importButton);++ await waitFor(+ () => {+ expect(+ screen.getByRole("button", { name: /Done/i }),+ ).toBeInTheDocument();+ },+ { timeout: 10000 },+ );++ // Click Done — should call onBulkDone, NOT onImported+ fireEvent.click(screen.getByRole("button", { name: /Done/i }));+ expect(onBulkDone).toHaveBeenCalledTimes(1);+ expect(onImported).not.toHaveBeenCalled();+ });});diff --git a/packages/views/skills/components/runtime-local-skill-import-panel.tsx b/packages/views/skills/components/runtime-local-skill-import-panel.tsxindex 9f8f0d5a05..88ea8bca12 100644--- a/packages/views/skills/components/runtime-local-skill-import-panel.tsx+++ b/packages/views/skills/components/runtime-local-skill-import-panel.tsx@@ -2,7 +2,14 @@import { useEffect, useMemo, useRef, useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";-import { AlertCircle, Download, FileText, HardDrive, Loader2 } from "lucide-react";+import {+ AlertCircle,+ CheckCircle2,+ Download,+ HardDrive,+ Loader2,+ SkipForward,+} from "lucide-react";import type {AgentRuntime,RuntimeLocalSkillSummary,@@ -21,9 +28,12 @@ import {workspaceKeys,} from "@multica/core/workspace/queries";import { Button } from "@multica/ui/components/ui/button";+import { Badge } from "@multica/ui/components/ui/badge";+import { Checkbox } from "@multica/ui/components/ui/checkbox";import { Input } from "@multica/ui/components/ui/input";import { Label } from "@multica/ui/components/ui/label";-import { Badge } from "@multica/ui/components/ui/badge";+import { Progress } from "@multica/ui/components/ui/progress";+import { Textarea } from "@multica/ui/components/ui/textarea";import {Select,SelectContent,@@ -32,51 +42,103 @@ import {SelectValue,} from "@multica/ui/components/ui/select";import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { Textarea } from "@multica/ui/components/ui/textarea";import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";-import { toast } from "sonner";import { useT } from "../../i18n";+import { isNameConflictError } from "../lib/utils";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++type BulkImportResult = {+ key: string;+ name: string;+ status: "success" | "skipped" | "failed";+ error?: string;+ skill?: Skill;+};++type BulkImportState = {+ phase: "idle" | "importing" | "done" | "cancelled";+ total: number;+ completed: number;+ results: BulkImportResult[];+};++const INITIAL_BULK_STATE: BulkImportState = {+ phase: "idle",+ total: 0,+ completed: 0,+ results: [],+};++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/**+ * Max concurrent imports. Higher = faster but more daemon/network pressure.+ *+ * Timeout invariant: IMPORT_CONCURRENCY × heartbeat period (~15s) must stay+ * within runtimeLocalSkillPendingTimeout (server/internal/handler/runtime_local_skills.go)+ * and IMPORT_POLL_TIMEOUT_MS (packages/core/runtimes/local-skills.ts).+ * See also maxLocalSkillImportBatch in server/internal/handler/daemon.go.+ */+const IMPORT_CONCURRENCY = 10;function runtimeLabel(runtime: AgentRuntime): string {return `${runtime.name} (${runtime.provider})`;}// ----------------------------------------------------------------------------// Skill row with inline-expanded name/description editor when selected+// Skill row with checkbox// ---------------------------------------------------------------------------function SkillItem({skill,- selected,- onSelect,- name,- description,+ checked,+ onToggle,+ disabled,+ expanded,+ editName,+ editDescription,onNameChange,onDescriptionChange,}: {skill: RuntimeLocalSkillSummary;- selected: boolean;- onSelect: () => void;- name: string;- description: string;- onNameChange: (v: string) => void;- onDescriptionChange: (v: string) => void;+ checked: boolean;+ onToggle: () => void;+ disabled?: boolean;+ expanded?: boolean;+ editName?: string;+ editDescription?: string;+ onNameChange?: (v: string) => void;+ onDescriptionChange?: (v: string) => void;}) {const { t } = useT("skills");return (<divclassName={`overflow-hidden rounded-lg border transition-colors ${- selected ? "border-primary bg-primary/5" : "hover:bg-accent/40"- }`}+ checked ? "border-primary bg-primary/5" : "hover:bg-accent/40"+ } ${disabled ? "pointer-events-none opacity-60" : ""}`}>- <button- type="button"- onClick={onSelect}+ <div+ role="button"+ tabIndex={disabled ? -1 : 0}+ onClick={onToggle}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onToggle();+ }+ }}className="flex w-full items-start gap-3 px-4 py-3 text-left">- <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>+ <Checkbox+ checked={checked}+ tabIndex={-1}+ className="pointer-events-none mt-0.5"+ /><div className="min-w-0 flex-1"><div className="flex items-center gap-2"><span className="truncate text-sm font-medium">{skill.name}</span>@@ -94,17 +156,17 @@ function SkillItem({<Badge variant="outline" className="shrink-0">{t(($) => $.runtime_import.skill_files, { count: skill.file_count })}</Badge>- </button>+ </div>- {selected && (+ {expanded && (<div className="space-y-2.5 border-t bg-card px-4 py-3"><div className="space-y-1"><Label className="text-xs text-muted-foreground">{t(($) => $.runtime_import.skill_name_label)}</Label><Input- value={name}- onChange={(e) => onNameChange(e.target.value)}+ value={editName ?? ""}+ onChange={(e) => onNameChange?.(e.target.value)}placeholder={skill.name}className="h-8 text-sm"/>@@ -114,8 +176,8 @@ function SkillItem({{t(($) => $.runtime_import.skill_description_label)}</Label><Textarea- value={description}- onChange={(e) => onDescriptionChange(e.target.value)}+ value={editDescription ?? ""}+ onChange={(e) => onDescriptionChange?.(e.target.value)}placeholder={t(($) => $.runtime_import.skill_description_placeholder)}rows={2}className="resize-none text-sm"@@ -127,14 +189,85 @@ function SkillItem({);}+// ---------------------------------------------------------------------------+// Summary view (shown after bulk import completes)+// ---------------------------------------------------------------------------++function BulkImportSummary({ results }: { results: BulkImportResult[] }) {+ const { t } = useT("skills");+ const succeeded = results.filter((r) => r.status === "success");+ const skipped = results.filter((r) => r.status === "skipped");+ const failed = results.filter((r) => r.status === "failed");++ return (+ <div className="space-y-4 py-2">+ {/* Summary counts */}+ <div className="grid grid-cols-3 gap-2 text-center">+ <div className="rounded-md bg-green-50 px-3 py-2 dark:bg-green-950/30">+ <div className="text-lg font-semibold text-green-700 dark:text-green-400">+ {succeeded.length}+ </div>+ <div className="text-xs text-muted-foreground">+ {t(($) => $.runtime_import.bulk_summary_imported)}+ </div>+ </div>+ <div className="rounded-md bg-yellow-50 px-3 py-2 dark:bg-yellow-950/30">+ <div className="text-lg font-semibold text-yellow-700 dark:text-yellow-400">+ {skipped.length}+ </div>+ <div className="text-xs text-muted-foreground">+ {t(($) => $.runtime_import.bulk_summary_skipped)}+ </div>+ </div>+ <div className="rounded-md bg-red-50 px-3 py-2 dark:bg-red-950/30">+ <div className="text-lg font-semibold text-red-700 dark:text-red-400">+ {failed.length}+ </div>+ <div className="text-xs text-muted-foreground">+ {t(($) => $.runtime_import.bulk_summary_failed)}+ </div>+ </div>+ </div>++ {/* Detailed results list */}+ <div className="max-h-64 space-y-1 overflow-y-auto rounded-md border p-2">+ {results.map((r) => (+ <div+ key={r.key}+ className="flex items-center gap-2 rounded px-2 py-1.5 text-xs"+ >+ {r.status === "success" && (+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-green-600" />+ )}+ {r.status === "skipped" && (+ <SkipForward className="h-3.5 w-3.5 shrink-0 text-yellow-600" />+ )}+ {r.status === "failed" && (+ <AlertCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />+ )}+ <span className="min-w-0 flex-1 truncate">{r.name}</span>+ {r.error && (+ <span className="max-w-[200px] shrink-0 truncate text-muted-foreground">+ {r.error}+ </span>+ )}+ </div>+ ))}+ </div>+ </div>+ );+}+// ---------------------------------------------------------------------------// Panel// ---------------------------------------------------------------------------export function RuntimeLocalSkillImportPanel({onImported,+ onBulkDone,}: {onImported?: (skill: Skill) => void;+ onBulkDone?: () => void;}) {const { t } = useT("skills");const wsId = useWorkspaceId();@@ -153,19 +286,24 @@ export function RuntimeLocalSkillImportPanel({);const [selectedRuntimeId, setSelectedRuntimeId] = useState<string>("");- const [selectedSkillKey, setSelectedSkillKey] = useState<string>("");- const [name, setName] = useState("");- const [description, setDescription] = useState("");- const [importing, setImporting] = useState(false);+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());+ const [bulkState, setBulkState] = useState<BulkImportState>(INITIAL_BULK_STATE);+ const cancelRef = useRef(false);+ // Single-select inline edit fields (shown when exactly 1 skill is checked)+ const [editName, setEditName] = useState("");+ const [editDescription, setEditDescription] = useState("");++ const importing = bulkState.phase === "importing";useEffect(() => {setSelectedRuntimeId((prev) => prev || localRuntimes[0]?.id || "");}, [localRuntimes]);useEffect(() => {- setSelectedSkillKey("");- setName("");- setDescription("");+ setSelectedKeys(new Set());+ setBulkState(INITIAL_BULK_STATE);+ setEditName("");+ setEditDescription("");}, [selectedRuntimeId]);const selectedRuntime = localRuntimes.find((r) => r.id === selectedRuntimeId);@@ -179,65 +317,201 @@ export function RuntimeLocalSkillImportPanel({() => skillsQuery.data?.skills ?? [],[skillsQuery.data],);- const selectedSkill = runtimeSkills.find((s) => s.key === selectedSkillKey);- useEffect(() => {- if (runtimeSkills.length === 0) return;- if (runtimeSkills.some((s) => s.key === selectedSkillKey)) return;- const first = runtimeSkills[0]!;- setSelectedSkillKey(first.key);- setName(first.name);- setDescription(first.description ?? "");- }, [runtimeSkills, selectedSkillKey]);-- const handleRowSelect = (s: RuntimeLocalSkillSummary) => {- setSelectedSkillKey(s.key);- setName(s.name);- setDescription(s.description ?? "");+ // The single selected skill (for inline editing). Only valid when exactly 1.+ const singleSelectedSkill =+ selectedKeys.size === 1+ ? runtimeSkills.find((s) => selectedKeys.has(s.key))+ : undefined;++ // -- Selection helpers --++ const toggleSkill = (key: string) => {+ setSelectedKeys((prev) => {+ const next = new Set(prev);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ // Seed edit fields when toggling to exactly-one selection+ if (next.size === 1) {+ const only = runtimeSkills.find((s) => next.has(s.key));+ if (only) {+ setEditName(only.name);+ setEditDescription(only.description ?? "");+ }+ }+ return next;+ });};- 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,+ const toggleAll = () => {+ if (selectedKeys.size === runtimeSkills.length) {+ setSelectedKeys(new Set());+ } else {+ setSelectedKeys(new Set(runtimeSkills.map((s) => s.key)));+ }+ };++ const allSelected =+ runtimeSkills.length > 0 && selectedKeys.size === runtimeSkills.length;+ const someSelected = selectedKeys.size > 0 && !allSelected;++ // -- Bulk import handler --++ const handleBulkImport = async () => {+ if (!selectedRuntimeId || selectedKeys.size === 0) return;++ const skillsToImport = runtimeSkills.filter((s) => selectedKeys.has(s.key));+ const total = skillsToImport.length;++ cancelRef.current = false;+ setBulkState({ phase: "importing", total, completed: 0, results: [] });++ const results: BulkImportResult[] = [];++ const importOne = async (skill: RuntimeLocalSkillSummary) => {+ // Single-select: use the user-edited name/description+ const importName =+ total === 1 ? editName.trim() || skill.name : skill.name;+ const importDescription =+ total === 1+ ? editDescription.trim() || skill.description || undefined+ : skill.description || undefined;+ try {+ const result = await resolveRuntimeLocalSkillImport(selectedRuntimeId, {+ skill_key: skill.key,+ name: importName,+ description: importDescription,+ });+ results.push({+ key: skill.key,+ name: importName,+ status: "success",+ skill: result.skill,+ });+ } catch (error) {+ const msg = error instanceof Error ? error.message : "";+ const isSkipped = isNameConflictError(msg);+ results.push({+ key: skill.key,+ name: skill.name,+ status: isSkipped ? "skipped" : "failed",+ error: msg || t(($) => $.runtime_import.toast_import_failed),+ });+ }++ setBulkState((prev) => ({+ ...prev,+ completed: prev.completed + 1,+ results: [...results],+ }));+ };++ // Concurrent pool — up to IMPORT_CONCURRENCY in-flight at once+ const executing = new Set<Promise<void>>();+ for (const skill of skillsToImport) {+ if (cancelRef.current) break;+ const p = importOne(skill).then(() => {+ executing.delete(p);});- qc.setQueryData(- skillDetailOptions(wsId, result.skill.id).queryKey,- result.skill,- );- await Promise.all([- qc.invalidateQueries({- queryKey: runtimeLocalSkillsKeys.forRuntime(selectedRuntimeId),- }),- qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) }),- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) }),- ]);- toast.success(t(($) => $.runtime_import.toast_imported));- onImported?.(result.skill);- } catch (error) {- toast.error(- error instanceof Error ? error.message : t(($) => $.runtime_import.toast_import_failed),- );- } finally {- setImporting(false);+ executing.add(p);+ if (executing.size >= IMPORT_CONCURRENCY) {+ await Promise.race(executing);+ }}+ await Promise.all(executing);++ // Invalidate queries ONCE at the end+ await Promise.all([+ qc.invalidateQueries({+ queryKey: runtimeLocalSkillsKeys.forRuntime(selectedRuntimeId),+ }),+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) }),+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) }),+ ]);++ // Seed query cache for each successfully imported skill+ for (const r of results) {+ if (r.status === "success" && r.skill) {+ qc.setQueryData(+ skillDetailOptions(wsId, r.skill.id).queryKey,+ r.skill,+ );+ }+ }++ setBulkState((prev) => ({+ ...prev,+ phase: cancelRef.current ? "cancelled" : "done",+ }));};const canImport =!!selectedRuntime &&selectedRuntime.status === "online" &&- !!selectedSkill &&- !!name.trim() &&+ selectedKeys.size > 0 &&+ // Single-select requires a non-empty name (user may be renaming)+ (selectedKeys.size > 1 || !!editName.trim()) &&!importing;+ const handleCancel = () => {+ cancelRef.current = true;+ };+const scrollRef = useRef<HTMLDivElement>(null);const fadeStyle = useScrollFade(scrollRef);+ // -- Middle content --+const middle = (() => {+ // Progress view during bulk import+ if (bulkState.phase === "importing") {+ const pct =+ bulkState.total > 0+ ? Math.round((bulkState.completed / bulkState.total) * 100)+ : 0;+ return (+ <div className="space-y-4 py-4">+ <div className="text-center">+ <Loader2 className="mx-auto h-6 w-6 animate-spin text-primary" />+ <p className="mt-3 text-sm font-medium">+ {t(($) => $.runtime_import.bulk_progress, {+ completed: bulkState.completed,+ total: bulkState.total,+ })}+ </p>+ </div>+ <Progress value={pct} />+ {/* Live result feed */}+ <div className="max-h-48 space-y-1 overflow-y-auto">+ {bulkState.results.map((r) => (+ <div+ key={r.key}+ className="flex items-center gap-2 rounded px-2 py-1 text-xs"+ >+ {r.status === "success" && (+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-green-600" />+ )}+ {r.status === "skipped" && (+ <SkipForward className="h-3.5 w-3.5 shrink-0 text-yellow-600" />+ )}+ {r.status === "failed" && (+ <AlertCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />+ )}+ <span className="truncate">{r.name}</span>+ </div>+ ))}+ </div>+ </div>+ );+ }++ // Summary view after bulk import (complete or cancelled)+ if (bulkState.phase === "done" || bulkState.phase === "cancelled") {+ return <BulkImportSummary results={bulkState.results} />;+ }++ // --- Idle phase: skill selection list ---+if (localRuntimes.length === 0) {return (<div className="rounded-lg border border-dashed px-4 py-10 text-center">@@ -311,22 +585,57 @@ export function RuntimeLocalSkillImportPanel({}return (<div className="space-y-2">+ {/* Select all header */}+ <label className="flex cursor-pointer items-center gap-2 px-1 py-1">+ <input+ type="checkbox"+ checked={allSelected}+ ref={(el) => {+ if (el) el.indeterminate = someSelected;+ }}+ onChange={toggleAll}+ className="cursor-pointer accent-primary"+ />+ <span className="text-xs text-muted-foreground">+ {t(($) => $.runtime_import.select_all, {+ count: runtimeSkills.length,+ })}+ </span>+ </label>+{runtimeSkills.map((s) => (<SkillItemkey={s.key}skill={s}- selected={selectedSkillKey === s.key}- onSelect={() => handleRowSelect(s)}- name={selectedSkillKey === s.key ? name : ""}- description={selectedSkillKey === s.key ? description : ""}- onNameChange={setName}- onDescriptionChange={setDescription}+ checked={selectedKeys.has(s.key)}+ onToggle={() => toggleSkill(s.key)}+ disabled={importing}+ expanded={singleSelectedSkill?.key === s.key}+ editName={singleSelectedSkill?.key === s.key ? editName : undefined}+ editDescription={+ singleSelectedSkill?.key === s.key ? editDescription : undefined+ }+ onNameChange={setEditName}+ onDescriptionChange={setEditDescription}/>))}</div>);})();+ // -- Handle "Done" button after import --++ const handleDone = () => {+ const succeeded = bulkState.results.filter((r) => r.status === "success");+ // Single-import flow: navigate to the imported skill detail page.+ // Multi-import flow: close the dialog even if only one succeeded.+ if (bulkState.total === 1 && succeeded.length === 1 && succeeded[0]!.skill) {+ onImported?.(succeeded[0]!.skill);+ } else {+ onBulkDone?.();+ }+ };+return (<div className="flex min-h-0 flex-1 flex-col">{/* Sticky top: runtime picker + status */}@@ -337,9 +646,9 @@ export function RuntimeLocalSkillImportPanel({}`}><div className="space-y-1.5">- <Label className="text-xs text-muted-foreground">+ <label className="text-xs text-muted-foreground">{t(($) => $.runtime_import.runtime_label)}- </Label>+ </label><Selectvalue={selectedRuntimeId}onValueChange={(v) => v && setSelectedRuntimeId(v)}@@ -381,49 +690,84 @@ export function RuntimeLocalSkillImportPanel({ref={scrollRef}style={fadeStyle}aria-disabled={importing || undefined}- className={`flex-1 min-h-0 overflow-y-auto px-5 py-3 ${- importing ? "pointer-events-none opacity-60" : ""+ className={`min-h-0 flex-1 overflow-y-auto px-5 py-3 ${+ importing && bulkState.phase !== "importing"+ ? "pointer-events-none opacity-60"+ : ""}`}>{middle}- <p className="mt-3 text-xs text-muted-foreground">- {t(($) => $.runtime_import.ignored_files_hint)}- </p>+ {bulkState.phase === "idle" && (+ <p className="mt-3 text-xs text-muted-foreground">+ {t(($) => $.runtime_import.ignored_files_hint)}+ </p>+ )}</div>- {/* Sticky bottom: Import button + context */}+ {/* Sticky bottom: contextual actions per phase */}<div className="flex shrink-0 items-center gap-3 border-t bg-muted/30 px-5 py-3">- <div className="min-w-0 flex-1 text-xs text-muted-foreground">- {selectedSkill ? (- <>- {t(($) => $.runtime_import.ready)}{" "}- <span className="font-medium text-foreground">- {name.trim() || selectedSkill.name}- </span>{" "}- {t(($) => $.runtime_import.into_workspace)}- </>- ) : (- t(($) => $.runtime_import.select_skill)- )}- </div>- <Button- type="button"- size="sm"- onClick={handleImport}- disabled={!canImport}- >- {importing ? (- <>- <Loader2 className="h-3 w-3 animate-spin" />- {t(($) => $.runtime_import.importing)}- </>- ) : (- <>+ {bulkState.phase === "done" || bulkState.phase === "cancelled" ? (+ <>+ <div className="min-w-0 flex-1 text-xs text-muted-foreground">+ {bulkState.phase === "cancelled"+ ? t(($) => $.runtime_import.bulk_cancelled_hint)+ : t(($) => $.runtime_import.bulk_complete_hint)}+ </div>+ <Button type="button" size="sm" onClick={handleDone}>+ {t(($) => $.runtime_import.bulk_done_button)}+ </Button>+ </>+ ) : importing ? (+ <>+ <div className="min-w-0 flex-1 text-xs text-muted-foreground">+ {t(($) => $.runtime_import.bulk_progress, {+ completed: bulkState.completed,+ total: bulkState.total,+ })}+ </div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={handleCancel}+ >+ {t(($) => $.runtime_import.bulk_cancel_button)}+ </Button>+ </>+ ) : (+ <>+ <div className="min-w-0 flex-1 text-xs text-muted-foreground">+ {singleSelectedSkill ? (+ <>+ {t(($) => $.runtime_import.ready)}{" "}+ <span className="font-medium text-foreground">+ {editName.trim() || singleSelectedSkill.name}+ </span>{" "}+ {t(($) => $.runtime_import.into_workspace)}+ </>+ ) : selectedKeys.size > 1 ? (+ t(($) => $.runtime_import.bulk_ready, {+ count: selectedKeys.size,+ })+ ) : (+ t(($) => $.runtime_import.select_skill)+ )}+ </div>+ <Button+ type="button"+ size="sm"+ onClick={handleBulkImport}+ disabled={!canImport}+ ><Download className="h-3 w-3" />- {t(($) => $.runtime_import.import_button)}- </>- )}- </Button>+ {selectedKeys.size > 1+ ? t(($) => $.runtime_import.bulk_import_button, {+ count: selectedKeys.size,+ })+ : t(($) => $.runtime_import.import_button)}+ </Button>+ </>+ )}</div></div>);diff --git a/packages/views/skills/lib/utils.ts b/packages/views/skills/lib/utils.tsnew file mode 100644index 0000000000..2fc2b6b78e--- /dev/null+++ b/packages/views/skills/lib/utils.ts@@ -0,0 +1,3 @@+export function isNameConflictError(msg: string): boolean {+ return /\b(409|conflict|already exists|unique constraint)\b/i.test(msg);+}diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex d0220c672e..f9fefd15fd 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -265,8 +265,9 @@ type (func (c *Client) SendHeartbeat(ctx context.Context, runtimeID string) (*HeartbeatResponse, error) {var resp HeartbeatResponse- if err := c.postJSON(ctx, "/api/daemon/heartbeat", map[string]string{- "runtime_id": runtimeID,+ if err := c.postJSON(ctx, "/api/daemon/heartbeat", map[string]any{+ "runtime_id": runtimeID,+ "supports_batch_import": true,}, &resp); err != nil {return nil, err}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 085ff07caa..c07b79ca1f 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -1296,7 +1296,14 @@ func (d *Daemon) handleHeartbeatActions(ctx context.Context, runtimeID string, rgo d.handleLocalSkillList(ctx, *rt, resp.PendingLocalSkills.ID)}}- if resp.PendingLocalSkillImport != nil {+ // Prefer the batch field (new backend); fall back to singular (old backend).+ if len(resp.PendingLocalSkillImports) > 0 {+ if rt := d.findRuntime(runtimeID); rt != nil {+ for _, imp := range resp.PendingLocalSkillImports {+ go d.handleLocalSkillImport(ctx, *rt, imp)+ }+ }+ } else if resp.PendingLocalSkillImport != nil {if rt := d.findRuntime(runtimeID); rt != nil {go d.handleLocalSkillImport(ctx, *rt, *resp.PendingLocalSkillImport)}diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex ad62c754c3..a5d8b075b2 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -205,7 +205,7 @@ func (d *Daemon) sendWSHeartbeats(ctx context.Context, runtimeIDs []string, writ}frame, err := json.Marshal(protocol.Message{Type: protocol.EventDaemonHeartbeat,- Payload: marshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: rid}),+ Payload: marshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: rid, SupportsBatchImport: true}),})if err != nil {d.logger.Debug("ws heartbeat marshal failed", "error", err, "runtime_id", rid)diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex 4496a6f86d..7690298ed4 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -69,7 +69,7 @@ func (c *client) markSeen(eventID string) bool {// runtimeID is one of identity.RuntimeIDs (the connection's authenticated// scope) and return the ack payload to send back. Returning an error skips// the ack and is logged at debug level.-type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error)+type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error)// Hub keeps daemon WebSocket connections indexed by runtime ID. Messages are// best-effort wakeup hints; the daemon still uses HTTP claim for correctness.@@ -389,7 +389,7 @@ func (c *client) handleHeartbeatFrame(raw json.RawMessage) {// that keeps the HTTP heartbeat from putting a per-call timeout on// PopPending. The natural bound is the read pump's lifetime (the conn// closes if the daemon goes away) plus Redis's own server-side limits.- ack, err := handler(context.Background(), c.identity, payload.RuntimeID)+ ack, err := handler(context.Background(), c.identity, payload.RuntimeID, payload.SupportsBatchImport)if err != nil {slog.Warn("daemon websocket heartbeat handler failed","error", err,diff --git a/server/internal/daemonws/hub_test.go b/server/internal/daemonws/hub_test.goindex 8f66351d4c..e4075359e5 100644--- a/server/internal/daemonws/hub_test.go+++ b/server/internal/daemonws/hub_test.go@@ -150,7 +150,7 @@ func TestHeartbeatRoundTrip(t *testing.T) {hub := NewHub()var calls atomic.Int32- hub.SetHeartbeatHandler(func(_ context.Context, identity ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error) {+ hub.SetHeartbeatHandler(func(_ context.Context, identity ClientIdentity, runtimeID string, _ bool) (*protocol.DaemonHeartbeatAckPayload, error) {calls.Add(1)if identity.WorkspaceID != "ws-1" {t.Errorf("identity workspace = %q, want ws-1", identity.WorkspaceID)@@ -232,7 +232,7 @@ func TestHeartbeatHandlerCtxNotTimeBounded(t *testing.T) {hub := NewHub()const stall = 250 * time.Millisecond- hub.SetHeartbeatHandler(func(ctx context.Context, _ ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error) {+ hub.SetHeartbeatHandler(func(ctx context.Context, _ ClientIdentity, runtimeID string, _ bool) (*protocol.DaemonHeartbeatAckPayload, error) {select {case <-time.After(stall):case <-ctx.Done():@@ -293,7 +293,7 @@ func TestHeartbeatRejectsUnauthorizedRuntime(t *testing.T) {hub := NewHub()var called atomic.Bool- hub.SetHeartbeatHandler(func(context.Context, ClientIdentity, string) (*protocol.DaemonHeartbeatAckPayload, error) {+ hub.SetHeartbeatHandler(func(context.Context, ClientIdentity, string, bool) (*protocol.DaemonHeartbeatAckPayload, error) {called.Store(true)return &protocol.DaemonHeartbeatAckPayload{Status: "ok"}, nil})diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 61d8e44ec4..4f05dc135b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -601,7 +601,8 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {}type DaemonHeartbeatRequest struct {- RuntimeID string `json:"runtime_id"`+ RuntimeID string `json:"runtime_id"`+ SupportsBatchImport bool `json:"supports_batch_import,omitempty"`}// heartbeatHasPendingTimeout bounds the cheap HasPending probe on the@@ -616,6 +617,16 @@ type DaemonHeartbeatRequest struct {// to claim, so we never start a claim we might have to abort.const heartbeatHasPendingTimeout = 1 * time.Second+// maxLocalSkillImportBatch is how many pending import requests the heartbeat+// handler pops per cycle. Higher values let the daemon process more imports+// in parallel but increase per-heartbeat latency.+//+// Timeout invariant: IMPORT_CONCURRENCY (views/.../runtime-local-skill-import-panel.tsx)+// × heartbeat period (~15s) must stay within runtimeLocalSkillPendingTimeout+// (runtime_local_skills.go), and IMPORT_POLL_TIMEOUT_MS (core/runtimes/local-skills.ts)+// must exceed pendingTimeout + runningTimeout.+const maxLocalSkillImportBatch = 10+// runtimeLivenessTTL is how long a Redis liveness record stays valid before// expiring. The daemon refreshes it every heartbeat (~15s), so this just// needs to be a few heartbeats long — the value (90s) tolerates ~6 missed@@ -722,7 +733,7 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {}authMs = time.Since(start).Milliseconds()- ack, m, err := h.processHeartbeat(r.Context(), rt)+ ack, m, err := h.processHeartbeat(r.Context(), rt, req.SupportsBatchImport)updateMs = m.UpdateMsprobeModelMs = m.ProbeModelMspopModelMs = m.PopModelMs@@ -756,6 +767,9 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {if ack.PendingLocalSkillImport != nil {resp["pending_local_skill_import"] = ack.PendingLocalSkillImport}+ if len(ack.PendingLocalSkillImports) > 0 {+ resp["pending_local_skill_imports"] = ack.PendingLocalSkillImports+ }writeJSON(w, http.StatusOK, resp)}@@ -773,7 +787,7 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {// and tells the daemon to drop the stale runtime and re-register. Other DB// errors still propagate as errors so they keep their existing Warn logging// and the daemon does not mistake a hiccup for a deletion.-func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws.ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error) {+func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws.ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error) {runtimeUUID, err := util.ParseUUID(runtimeID)if err != nil {return nil, fmt.Errorf("invalid runtime_id: %w", err)@@ -792,7 +806,7 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonwsif identity.WorkspaceID != "" && identity.WorkspaceID != uuidToString(rt.WorkspaceID) {return nil, fmt.Errorf("runtime not in connection workspace")}- ack, _, err := h.processHeartbeat(ctx, rt)+ ack, _, err := h.processHeartbeat(ctx, rt, supportsBatchImport)return ack, err}@@ -853,7 +867,7 @@ type heartbeatMetrics struct {// the WebSocket daemon:heartbeat path: records liveness and pulls any pending// actions queued for the runtime. Auth and request decoding live in the// caller because they differ between transports.-func (h *Handler) processHeartbeat(ctx context.Context, rt db.AgentRuntime) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {+func (h *Handler) processHeartbeat(ctx context.Context, rt db.AgentRuntime, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {var m heartbeatMetricsruntimeID := uuidToString(rt.ID)@@ -957,14 +971,42 @@ func (h *Handler) processHeartbeat(ctx context.Context, rt db.AgentRuntime) (*prswitch {case probeErr == nil && hasImport:popStart := time.Now()- pendingImport, popErr := h.LocalSkillImportStore.PopPending(ctx, runtimeID)- m.PopImportMs = time.Since(popStart).Milliseconds()- if popErr != nil {- slog.Warn("local skill import PopPending failed", "error", popErr, "runtime_id", runtimeID)- } else if pendingImport != nil {- ack.PendingLocalSkillImport = &protocol.DaemonHeartbeatPendingLocalSkillImport{- ID: pendingImport.ID,- SkillKey: pendingImport.SkillKey,+ if supportsBatchImport {+ pendingImports, popErr := h.LocalSkillImportStore.PopPendingBatch(ctx, runtimeID, maxLocalSkillImportBatch)+ m.PopImportMs = time.Since(popStart).Milliseconds()+ if popErr != nil {+ slog.Warn("local skill import PopPendingBatch failed", "error", popErr, "runtime_id", runtimeID, "claimed", len(pendingImports))+ }+ // Always dispatch whatever was claimed — even on partial+ // failure the claimed requests have already transitioned to+ // running in the store. Dropping them here would leave them+ // stranded until the running timeout.+ if len(pendingImports) > 0 {+ // Backwards compat: singular field carries the first item so+ // old daemons that don't know the plural field still get one.+ ack.PendingLocalSkillImport = &protocol.DaemonHeartbeatPendingLocalSkillImport{+ ID: pendingImports[0].ID,+ SkillKey: pendingImports[0].SkillKey,+ }+ batch := make([]protocol.DaemonHeartbeatPendingLocalSkillImport, 0, len(pendingImports))+ for _, p := range pendingImports {+ batch = append(batch, protocol.DaemonHeartbeatPendingLocalSkillImport{+ ID: p.ID,+ SkillKey: p.SkillKey,+ })+ }+ ack.PendingLocalSkillImports = batch+ }+ } else {+ pendingImport, popErr := h.LocalSkillImportStore.PopPending(ctx, runtimeID)+ m.PopImportMs = time.Since(popStart).Milliseconds()+ if popErr != nil {+ slog.Warn("local skill import PopPending failed", "error", popErr, "runtime_id", runtimeID)+ } else if pendingImport != nil {+ ack.PendingLocalSkillImport = &protocol.DaemonHeartbeatPendingLocalSkillImport{+ ID: pendingImport.ID,+ SkillKey: pendingImport.SkillKey,+ }}}case probeErr != nil:diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex d482a7fd30..a131ceeedd 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -205,7 +205,7 @@ func TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError(t *testing.T) {missingRuntime := uuid.New().String()ack, err := testHandler.HandleDaemonWSHeartbeat(context.Background(),daemonws.ClientIdentity{WorkspaceID: testWorkspaceID},- missingRuntime)+ missingRuntime, false)if err != nil {t.Fatalf("HandleDaemonWSHeartbeat: unexpected error %v", err)}diff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.goindex f80c75fdb1..8a392ba035 100644--- a/server/internal/handler/runtime_local_skills.go+++ b/server/internal/handler/runtime_local_skills.go@@ -5,6 +5,7 @@ import ("encoding/json""log/slog""net/http"+ "sort""strings""sync""time"@@ -25,9 +26,21 @@ const ()const (- runtimeLocalSkillPendingTimeout = 30 * time.Second+ // runtimeLocalSkillPendingTimeout bounds how long a request can sit in+ // pending before the server marks it timed out. The value must accommodate+ // old daemons that don't support batch import: they pop only one import+ // per heartbeat cycle (~15s). With maxLocalSkillImportBatch=10, the 10th+ // queued import waits up to 10×15s = 150s before being claimed. 3 minutes+ // gives a comfortable margin.+ //+ // Timeout invariant: IMPORT_CONCURRENCY (views/.../runtime-local-skill-import-panel.tsx)+ // × heartbeat period (~15s) ≤ runtimeLocalSkillPendingTimeout, and+ // IMPORT_POLL_TIMEOUT_MS (core/runtimes/local-skills.ts) must exceed+ // runtimeLocalSkillPendingTimeout + runtimeLocalSkillRunningTimeout.+ // See also maxLocalSkillImportBatch in daemon.go.+ runtimeLocalSkillPendingTimeout = 3 * time.MinuteruntimeLocalSkillRunningTimeout = 60 * time.Second- runtimeLocalSkillStoreRetention = 2 * time.Minute+ runtimeLocalSkillStoreRetention = 5 * time.Minute)// LocalSkillListStore tracks pending / running / completed runtime-local-skill@@ -56,6 +69,10 @@ type LocalSkillImportStore interface {Get(ctx context.Context, id string) (*RuntimeLocalSkillImportRequest, error)HasPending(ctx context.Context, runtimeID string) (bool, error)PopPending(ctx context.Context, runtimeID string) (*RuntimeLocalSkillImportRequest, error)+ // PopPendingBatch claims up to limit pending requests atomically and+ // transitions them to running. Used by the heartbeat handler to deliver+ // multiple imports per heartbeat cycle.+ PopPendingBatch(ctx context.Context, runtimeID string, limit int) ([]*RuntimeLocalSkillImportRequest, error)Complete(ctx context.Context, id string, skill SkillResponse) errorFail(ctx context.Context, id string, errMsg string) error}@@ -68,7 +85,7 @@ func applyLocalSkillListTimeout(req *RuntimeLocalSkillListRequest, now time.Timecase RuntimeLocalSkillPending:if now.Sub(req.CreatedAt) > runtimeLocalSkillPendingTimeout {req.Status = RuntimeLocalSkillTimeout- req.Error = "daemon did not respond within 30 seconds"+ req.Error = "daemon did not respond within 3 minutes"req.UpdatedAt = nowreturn true}@@ -88,7 +105,7 @@ func applyLocalSkillImportTimeout(req *RuntimeLocalSkillImportRequest, now time.case RuntimeLocalSkillPending:if now.Sub(req.CreatedAt) > runtimeLocalSkillPendingTimeout {req.Status = RuntimeLocalSkillTimeout- req.Error = "daemon did not respond within 30 seconds"+ req.Error = "daemon did not respond within 3 minutes"req.UpdatedAt = nowreturn true}@@ -333,6 +350,39 @@ func (s *InMemoryLocalSkillImportStore) PopPending(_ context.Context, runtimeIDreturn oldest, nil}+func (s *InMemoryLocalSkillImportStore) PopPendingBatch(_ context.Context, runtimeID string, limit int) ([]*RuntimeLocalSkillImportRequest, error) {+ s.mu.Lock()+ defer s.mu.Unlock()++ now := time.Now()++ // Collect all pending requests for this runtime, sorted by creation time.+ var pending []*RuntimeLocalSkillImportRequest+ for _, req := range s.requests {+ applyLocalSkillImportTimeout(req, now)+ if req.RuntimeID == runtimeID && req.Status == RuntimeLocalSkillPending {+ pending = append(pending, req)+ }+ }+ sort.Slice(pending, func(i, j int) bool {+ return pending[i].CreatedAt.Before(pending[j].CreatedAt)+ })++ if limit > len(pending) {+ limit = len(pending)+ }++ result := make([]*RuntimeLocalSkillImportRequest, 0, limit)+ for _, req := range pending[:limit] {+ req.Status = RuntimeLocalSkillRunning+ startedAt := now+ req.RunStartedAt = &startedAt+ req.UpdatedAt = now+ result = append(result, req)+ }+ return result, nil+}+func (s *InMemoryLocalSkillImportStore) Complete(_ context.Context, id string, skill SkillResponse) error {s.mu.Lock()defer s.mu.Unlock()diff --git a/server/internal/handler/runtime_local_skills_redis_store.go b/server/internal/handler/runtime_local_skills_redis_store.goindex eac459e0c6..61657f1948 100644--- a/server/internal/handler/runtime_local_skills_redis_store.go+++ b/server/internal/handler/runtime_local_skills_redis_store.go@@ -426,6 +426,60 @@ func (s *RedisLocalSkillImportStore) PopPending(ctx context.Context, runtimeID sreturn nil, nil}+func (s *RedisLocalSkillImportStore) PopPendingBatch(ctx context.Context, runtimeID string, limit int) ([]*RuntimeLocalSkillImportRequest, error) {+ pendingKey := localSkillImportPendingKey(runtimeID)++ // Fetch up to limit candidate IDs from the sorted set.+ ids, err := s.rdb.ZRange(ctx, pendingKey, 0, int64(limit)-1).Result()+ if err != nil {+ return nil, fmt.Errorf("zrange pending batch: %w", err)+ }+ if len(ids) == 0 {+ return nil, nil+ }++ // Try to claim each candidate individually using the existing atomic+ // Lua script. This is safe under multi-node contention: each ZREM is+ // atomic, so two nodes never claim the same request.+ var result []*RuntimeLocalSkillImportRequest+ for _, id := range ids {+ req, err := s.loadImportRequest(ctx, id)+ if err != nil {+ return result, err+ }+ if req == nil {+ s.rdb.ZRem(ctx, pendingKey, id)+ continue+ }+ if req.Status != RuntimeLocalSkillPending {+ s.rdb.ZRem(ctx, pendingKey, id)+ continue+ }++ now := time.Now()+ req.Status = RuntimeLocalSkillRunning+ req.RunStartedAt = &now+ req.UpdatedAt = now+ data, err := s.marshalImport(req)+ if err != nil {+ return result, err+ }++ claimed, err := claimPendingScript.Run(+ ctx, s.rdb,+ []string{pendingKey, localSkillImportKey(id)},+ id, data, int(runtimeLocalSkillStoreRetention.Seconds()),+ ).Int64()+ if err != nil {+ return result, fmt.Errorf("claim pending batch: %w", err)+ }+ if claimed == 1 {+ result = append(result, req)+ }+ }+ return result, nil+}+func (s *RedisLocalSkillImportStore) Complete(ctx context.Context, id string, skill SkillResponse) error {req, err := s.loadImportRequest(ctx, id)if err != nil {diff --git a/server/internal/handler/runtime_local_skills_redis_store_test.go b/server/internal/handler/runtime_local_skills_redis_store_test.goindex a7169ae1ed..4c782c9698 100644--- a/server/internal/handler/runtime_local_skills_redis_store_test.go+++ b/server/internal/handler/runtime_local_skills_redis_store_test.go@@ -2,6 +2,7 @@ package handlerimport ("context"+ "fmt""os""sync""testing"@@ -356,6 +357,54 @@ func TestRedisLocalSkillListStore_PopPendingAtomicClaim(t *testing.T) {}}+func TestRedisLocalSkillImportStore_PopPendingBatch(t *testing.T) {+ rdb := newRedisTestClient(t)+ ctx := context.Background()+ store := NewRedisLocalSkillImportStore(rdb)++ // Create 5 pending imports.+ ids := make([]string, 5)+ for i := range ids {+ req, err := store.Create(ctx, "runtime-batch", "user-1", fmt.Sprintf("skill-%d", i), nil, nil)+ if err != nil {+ t.Fatalf("create %d: %v", i, err)+ }+ ids[i] = req.ID+ }++ // Pop batch of 3 — should return 3 in creation order.+ batch, err := store.PopPendingBatch(ctx, "runtime-batch", 3)+ if err != nil {+ t.Fatalf("pop batch: %v", err)+ }+ if len(batch) != 3 {+ t.Fatalf("expected 3, got %d", len(batch))+ }+ for _, req := range batch {+ if req.Status != RuntimeLocalSkillRunning {+ t.Fatalf("batch item status = %s, want running", req.Status)+ }+ }++ // Pop remaining — should get 2.+ rest, err := store.PopPendingBatch(ctx, "runtime-batch", 10)+ if err != nil {+ t.Fatalf("pop rest: %v", err)+ }+ if len(rest) != 2 {+ t.Fatalf("expected 2 remaining, got %d", len(rest))+ }++ // Pop again — nothing left.+ empty, err := store.PopPendingBatch(ctx, "runtime-batch", 10)+ if err != nil {+ t.Fatalf("pop empty: %v", err)+ }+ if len(empty) != 0 {+ t.Fatalf("expected 0, got %d", len(empty))+ }+}+// Compile-time assertions: the Redis stores MUST satisfy the interfaces so// NewRouter's assignment stays type-safe.var (diff --git a/server/internal/handler/runtime_local_skills_test.go b/server/internal/handler/runtime_local_skills_test.goindex 7122c6d512..cd13cce70f 100644--- a/server/internal/handler/runtime_local_skills_test.go+++ b/server/internal/handler/runtime_local_skills_test.go@@ -369,6 +369,107 @@ func TestRuntimeLocalSkillImportFlow_EndToEnd(t *testing.T) {}}+func TestBatchImportViaHeartbeat(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)++ // Create 5 import requests.+ skillKeys := []string{"skill-a", "skill-b", "skill-c", "skill-d", "skill-e"}+ importIDs := make([]string, 0, len(skillKeys))+ for _, key := range skillKeys {+ w := httptest.NewRecorder()+ req := withURLParams(+ newRequestAsUser(testUserID, http.MethodPost, "/api/runtimes/"+runtimeID+"/local-skills/import", map[string]any{+ "skill_key": key,+ }),+ "runtimeId", runtimeID,+ )+ testHandler.InitiateImportLocalSkill(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("InitiateImportLocalSkill(%s): expected 200, got %d: %s", key, 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)+ }+ importIDs = append(importIDs, importReq.ID)+ }++ // Single heartbeat should return all 5 via the plural field.+ w := httptest.NewRecorder()+ heartbeatReq := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{+ "runtime_id": runtimeID,+ "supports_batch_import": true,+ }, 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)+ }++ // Singular field (backwards compat) should contain the first item.+ singular, ok := heartbeatResp["pending_local_skill_import"].(map[string]any)+ if !ok {+ t.Fatalf("expected pending_local_skill_import, got %v", heartbeatResp)+ }+ if singular["id"] != importIDs[0] {+ t.Fatalf("singular id = %v, want %s", singular["id"], importIDs[0])+ }++ // Plural field should contain all 5.+ pluralRaw, ok := heartbeatResp["pending_local_skill_imports"].([]any)+ if !ok {+ t.Fatalf("expected pending_local_skill_imports array, got %T", heartbeatResp["pending_local_skill_imports"])+ }+ if len(pluralRaw) != len(skillKeys) {+ t.Fatalf("expected %d pending imports, got %d", len(skillKeys), len(pluralRaw))+ }++ // Verify IDs match.+ gotIDs := make(map[string]bool)+ for _, item := range pluralRaw {+ m, ok := item.(map[string]any)+ if !ok {+ t.Fatalf("expected map, got %T", item)+ }+ gotIDs[m["id"].(string)] = true+ }+ for _, id := range importIDs {+ if !gotIDs[id] {+ t.Fatalf("missing import ID %s in plural field", id)+ }+ }++ // Second heartbeat should return nothing (all were claimed).+ w = httptest.NewRecorder()+ heartbeatReq2 := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{+ "runtime_id": runtimeID,+ "supports_batch_import": true,+ }, testWorkspaceID, "runtime-local-skills-daemon")+ testHandler.DaemonHeartbeat(w, heartbeatReq2)+ if w.Code != http.StatusOK {+ t.Fatalf("DaemonHeartbeat: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var heartbeatResp2 map[string]any+ if err := json.NewDecoder(w.Body).Decode(&heartbeatResp2); err != nil {+ t.Fatalf("decode heartbeat response: %v", err)+ }+ if _, ok := heartbeatResp2["pending_local_skill_import"]; ok {+ t.Fatalf("second heartbeat should have no pending imports, got %v", heartbeatResp2)+ }+ if _, ok := heartbeatResp2["pending_local_skill_imports"]; ok {+ t.Fatalf("second heartbeat should have no pending imports plural, got %v", heartbeatResp2)+ }+}+func TestReportLocalSkillImportResult_IgnoresTimedOutRequests(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex f10197e710..500a6141a2 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -116,7 +116,8 @@ type ChatSessionUpdatedPayload struct {// Mirrors the body of POST /api/daemon/heartbeat so both transports share// identical semantics.type DaemonHeartbeatRequestPayload struct {- RuntimeID string `json:"runtime_id"`+ RuntimeID string `json:"runtime_id"`+ SupportsBatchImport bool `json:"supports_batch_import,omitempty"`}// DaemonHeartbeatAckPayload is the server's reply to DaemonHeartbeatRequestPayload.@@ -137,6 +138,11 @@ type DaemonHeartbeatAckPayload struct {PendingModelList *DaemonHeartbeatPendingModelList `json:"pending_model_list,omitempty"`PendingLocalSkills *DaemonHeartbeatPendingLocalSkills `json:"pending_local_skills,omitempty"`PendingLocalSkillImport *DaemonHeartbeatPendingLocalSkillImport `json:"pending_local_skill_import,omitempty"`+ // PendingLocalSkillImports carries multiple import requests in a single+ // heartbeat so the daemon can process them concurrently. Old daemons+ // that don't know this field silently ignore it (standard JSON behavior)+ // and fall back to the singular PendingLocalSkillImport above.+ PendingLocalSkillImports []DaemonHeartbeatPendingLocalSkillImport `json:"pending_local_skill_imports,omitempty"`}// HeartbeatStatusRuntimeGone is the ack Status used when the runtime row no