Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: slash command skills picker in web chat (#102)
Gener08f20d7a4a7f
diff --git a/package.json b/package.jsonindex 37bd79eb2..c75f5ed28 100644--- a/package.json+++ b/package.json@@ -34,7 +34,7 @@"prepare": "simple-git-hooks"},"simple-git-hooks": {- "pre-commit": "pnpm lint && pnpm test"+ "pre-commit": "pnpm typecheck && pnpm lint && pnpm test"},"devDependencies": {"simple-git-hooks": "^2.13.1",diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.tsindex 6491b1228..c21062599 100644--- a/src/cli/daemon/client.ts+++ b/src/cli/daemon/client.ts@@ -8,6 +8,7 @@ import {type PollResponse,type RegisterDaemonRequest,type RegisterResponse,+ type SkillSyncRequest,type TaskApi,type WorkspaceFileReport,} from "@alook/shared";@@ -206,4 +207,13 @@ export class DaemonClient {);}+ syncSkills(token: string, body: SkillSyncRequest) {+ return this.request(+ "POST",+ "/api/daemon/skills/sync",+ token,+ body,+ );+ }+}diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex 1612354fc..b04270aed 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -149,6 +149,9 @@ vi.mock("fs", () => ({readdirSync: (...args: any[]) => mockReaddirSync(...args),statSync: (...args: any[]) => mockStatSync(...args),unlinkSync: (...args: any[]) => mockUnlinkSync(...args),+ realpathSync: vi.fn((p: string) => p),+ readFileSync: vi.fn(() => ""),+ writeFileSync: vi.fn(),}));const mockReaddir = vi.fn(async () => [] as string[]);@@ -586,7 +589,7 @@ describe("daemon shutdown", () => {it("clears poll interval before calling deregister", async () => {await startDaemon();- expect(intervalTimers.length).toBe(3); // pollTimer + heartbeatTimer + sweepTimer+ expect(intervalTimers.length).toBe(4); // pollTimer + heartbeatTimer + sweepTimer + skillScannerTimerconst pollTimer = intervalTimers[0];const deregisterMock = mockClientInstance.deregister;@@ -609,7 +612,7 @@ describe("daemon shutdown", () => {await shutdownHandler!();expect(clearedTimers).toContain(pollTimer);- expect(deregisterCalledAt).toBe(3); // After clearing all 3 timers (poll + heartbeat + sweep)+ expect(deregisterCalledAt).toBe(4); // After clearing all 4 timers (poll + heartbeat + sweep + skillScanner)});it("deregisters each workspace with correct token on shutdown", async () => {diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex e0029d7c0..572f747ad 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -22,6 +22,7 @@ import {} from "./execenv/steering.js";import { TASK_TYPES } from "@alook/shared";import { readDirectoryTree, readFileContent, validatePath } from "./workspace-files.js";+import { startSkillScanner, stopSkillScanner } from "./skill-scanner.js";import { resolveLoginShellEnv } from "../lib/shell-env.js";import { existsSync, mkdirSync, openSync, closeSync, readdirSync, statSync, unlinkSync } from "fs";import { readdir, readFile, unlink, stat as fsStat } from "fs/promises";@@ -452,6 +453,7 @@ export async function startDaemon(}}+// Spawn meeting bots from merged poll responseif (meetings) {for (const m of meetings) {@@ -539,6 +541,7 @@ export async function startDaemon(break;}+case "daemon.meetings":for (const m of msg.meetings) {const ws = workspaceStates.find((w) => w.workspaceId === m.workspace_id);@@ -641,6 +644,17 @@ export async function startDaemon(};const sweepTimer = setInterval(sweepTick, config.sweepInterval);+ // --- Skill scanner: scans global + agent skills every 60s ---+ startSkillScanner(client, {+ workspacesRoot: config.workspacesRoot,+ workspaces: workspaces.map((ws) => ({+ workspaceId: ws.id,+ token: ws.token,+ agentIds: ws.agent_ids ?? [],+ })),+ runtimes: providers.map((p) => p.type as "claude" | "codex" | "opencode"),+ }, 60_000);+let shuttingDown = false;let restartRequested = false;@@ -656,6 +670,7 @@ export async function startDaemon(clearInterval(pollTimer);clearInterval(heartbeatTimer);clearInterval(sweepTimer);+ stopSkillScanner();wsClient?.close();const shutdownMs = restartRequested ? 30000 : (Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000);diff --git a/src/cli/daemon/skill-scanner.test.ts b/src/cli/daemon/skill-scanner.test.tsnew file mode 100644index 000000000..d2082059e--- /dev/null+++ b/src/cli/daemon/skill-scanner.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "fs";+import { join } from "path";+import { tmpdir } from "os";++const mockState = { home: "/tmp" };++vi.mock("os", async (importOriginal) => {+ const actual = await importOriginal<typeof import("os")>();+ return { ...actual, homedir: () => mockState.home };+});++vi.mock("../lib/logger.js", () => ({+ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++vi.mock("../lib/config.js", () => ({+ configDir: () => join(tmpdir(), "alook-skill-scanner-test-config-" + process.pid),+}));++import { startSkillScanner, stopSkillScanner, parseFrontmatter } from "./skill-scanner.js";+import type { DaemonClient } from "./client.js";++describe("parseFrontmatter", () => {+ it("parses name and description", () => {+ const content = `---\nname: my-skill\ndescription: Does stuff\n---\nBody`;+ expect(parseFrontmatter(content)).toEqual({ name: "my-skill", description: "Does stuff" });+ });++ it("returns null without frontmatter", () => {+ expect(parseFrontmatter("Just text")).toBeNull();+ });+});++describe("runScan global skills syncs to all workspaces", () => {+ let tempDir: string;+ let workspacesRoot: string;+ let mockClient: { syncSkills: ReturnType<typeof vi.fn> };++ beforeEach(() => {+ tempDir = mkdtempSync(join(tmpdir(), "skill-scan-"));+ workspacesRoot = join(tempDir, "workspaces");+ mkdirSync(workspacesRoot, { recursive: true });+ mockClient = {+ syncSkills: vi.fn(async () => ({})),+ };+ });++ afterEach(() => {+ stopSkillScanner();+ try { rmSync(tempDir, { recursive: true }); } catch { /* ok */ }+ });++ it("syncs global skills to multiple workspaces", async () => {+ const home = join(tempDir, "home");+ mockState.home = home;++ const skillDir = join(home, ".claude", "skills", "test-skill");+ mkdirSync(skillDir, { recursive: true });+ writeFileSync(join(skillDir, "SKILL.md"), "---\nname: test-skill\ndescription: A test\n---\nContent");++ const ws1Dir = join(workspacesRoot, "ws1", "agent1");+ const ws2Dir = join(workspacesRoot, "ws2", "agent2");+ mkdirSync(join(ws1Dir, "workdir"), { recursive: true });+ mkdirSync(join(ws2Dir, "workdir"), { recursive: true });++ startSkillScanner(mockClient as unknown as DaemonClient, {+ workspacesRoot,+ workspaces: [+ { workspaceId: "ws1", token: "token-ws1", agentIds: ["agent1"] },+ { workspaceId: "ws2", token: "token-ws2", agentIds: ["agent2"] },+ ],+ runtimes: ["claude"],+ }, 999_999);++ await new Promise((r) => setTimeout(r, 100));++ const globalCalls = mockClient.syncSkills.mock.calls.filter(+ (args) => (args[1] as { scope: string }).scope === "global"+ );+ expect(globalCalls.length).toBe(2);++ const tokens = globalCalls.map((args) => args[0] as string);+ expect(tokens).toContain("token-ws1");+ expect(tokens).toContain("token-ws2");+ });++ it("does nothing with empty workspaces array", () => {+ startSkillScanner(mockClient as unknown as DaemonClient, {+ workspacesRoot,+ workspaces: [],+ runtimes: ["claude"],+ }, 999_999);++ expect(mockClient.syncSkills).not.toHaveBeenCalled();+ });+});diff --git a/src/cli/daemon/skill-scanner.ts b/src/cli/daemon/skill-scanner.tsnew file mode 100644index 000000000..7b319eeb1--- /dev/null+++ b/src/cli/daemon/skill-scanner.ts@@ -0,0 +1,399 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync, realpathSync } from "fs";+import { join, basename } from "path";+import { homedir } from "os";+import { createHash } from "crypto";+import { createLogger } from "../lib/logger.js";+import { configDir } from "../lib/config.js";+import type { DaemonClient } from "./client.js";++const log = createLogger({ module: "skill-scanner" });++export interface SkillEntry {+ name: string;+ description: string;+}++function getCacheDir(): string {+ return join(configDir(), "skills");+}++++export function parseFrontmatter(content: string): { name: string; description: string } | null {+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);+ if (!match) return null;++ const block = match[1];+ const nameMatch = block.match(/^name:\s*(.+)$/m);+ const descMatch = block.match(/^description:\s*(.+)$/m);++ if (!nameMatch) return null;++ return {+ name: nameMatch[1].trim().replace(/^["']|["']$/g, ""),+ description: descMatch ? descMatch[1].trim().replace(/^["']|["']$/g, "") : "",+ };+}++function safeReadDir(dir: string): string[] {+ try {+ if (!existsSync(dir)) return [];+ return readdirSync(dir);+ } catch {+ return [];+ }+}++function findSkillFiles(baseDir: string, pattern: string): string[] {+ const results: string[] = [];+ if (!existsSync(baseDir)) return results;++ if (pattern === "*/SKILL.md") {+ for (const entry of safeReadDir(baseDir)) {+ const skillPath = join(baseDir, entry, "SKILL.md");+ try {+ if (existsSync(skillPath) && statSync(skillPath).isFile()) {+ results.push(skillPath);+ }+ } catch { /* skip */ }+ }+ } else if (pattern === "**/skills/*/SKILL.md") {+ walkForSkills(baseDir, results);+ } else if (pattern === "*.md") {+ for (const entry of safeReadDir(baseDir)) {+ if (entry.endsWith(".md")) {+ const filePath = join(baseDir, entry);+ try {+ if (statSync(filePath).isFile()) {+ results.push(filePath);+ }+ } catch { /* skip */ }+ }+ }+ }++ return results;+}++function walkForSkills(dir: string, results: string[], depth = 0): void {+ if (depth > 5) return;+ try {+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ try {+ const st = statSync(full);+ if (st.isDirectory()) {+ if (entry === "skills") {+ for (const skillDir of safeReadDir(full)) {+ const skillPath = join(full, skillDir, "SKILL.md");+ try {+ if (existsSync(skillPath) && statSync(skillPath).isFile()) {+ results.push(skillPath);+ }+ } catch { /* skip */ }+ }+ } else {+ walkForSkills(full, results, depth + 1);+ }+ }+ } catch { /* skip */ }+ }+ } catch { /* skip */ }+}++function scanFrontmatterSkills(paths: string[]): SkillEntry[] {+ const skills = new Map<string, SkillEntry>();+ for (const filePath of paths) {+ try {+ const content = readFileSync(filePath, "utf-8");+ const meta = parseFrontmatter(content);+ if (meta && !skills.has(meta.name)) {+ skills.set(meta.name, meta);+ }+ } catch { /* skip */ }+ }+ return Array.from(skills.values());+}++export function scanClaudeGlobalSkills(): SkillEntry[] {+ const home = homedir();+ const allSkills: SkillEntry[] = [];++ const directPaths = findSkillFiles(join(home, ".claude", "skills"), "*/SKILL.md");+ allSkills.push(...scanFrontmatterSkills(directPaths));++ const pluginCacheDir = join(home, ".claude", "plugins", "cache");+ const pluginPaths = findSkillFiles(pluginCacheDir, "**/skills/*/SKILL.md");+ const names = new Set(allSkills.map((s) => s.name));+ for (const filePath of pluginPaths) {+ try {+ const content = readFileSync(filePath, "utf-8");+ const meta = parseFrontmatter(content);+ if (meta && !names.has(meta.name)) {+ names.add(meta.name);+ allSkills.push(meta);+ }+ } catch { /* skip */ }+ }++ return allSkills;+}++export function scanClaudeAgentSkills(workdir: string): SkillEntry[] {+ const paths = findSkillFiles(join(workdir, ".claude", "skills"), "*/SKILL.md");+ return scanFrontmatterSkills(paths);+}++export function scanCodexGlobalSkills(): SkillEntry[] {+ const home = homedir();+ const allSkills: SkillEntry[] = [];++ const paths = [+ ...findSkillFiles(join(home, ".agents", "skills"), "*/SKILL.md"),+ ...findSkillFiles(join(home, ".codex", "skills", ".system"), "*/SKILL.md"),+ ];+ allSkills.push(...scanFrontmatterSkills(paths));++ const codexPluginDir = join(home, ".codex", "plugins", "cache");+ const pluginPaths = findSkillFiles(codexPluginDir, "**/skills/*/SKILL.md");+ const names = new Set(allSkills.map((s) => s.name));+ for (const filePath of pluginPaths) {+ try {+ const content = readFileSync(filePath, "utf-8");+ const meta = parseFrontmatter(content);+ if (meta && !names.has(meta.name)) {+ names.add(meta.name);+ allSkills.push(meta);+ }+ } catch { /* skip */ }+ }++ return allSkills;+}++export function scanCodexAgentSkills(workdir: string): SkillEntry[] {+ const paths = findSkillFiles(join(workdir, ".agents", "skills"), "*/SKILL.md");+ return scanFrontmatterSkills(paths);+}++function scanOpenCodeMdFiles(dir: string): SkillEntry[] {+ const skills: SkillEntry[] = [];+ const files = findSkillFiles(dir, "*.md");+ for (const filePath of files) {+ try {+ const content = readFileSync(filePath, "utf-8");+ const name = basename(filePath, ".md");+ const firstLine = content.split("\n").find((l) => l.trim().length > 0) ?? "";+ skills.push({ name, description: firstLine.replace(/^#\s*/, "").trim() });+ } catch { /* skip */ }+ }+ return skills;+}++export function scanOpenCodeGlobalSkills(): SkillEntry[] {+ const home = homedir();+ const skills: SkillEntry[] = [];+ const names = new Set<string>();++ for (const s of scanOpenCodeMdFiles(join(home, ".config", "opencode", "commands"))) {+ if (!names.has(s.name)) { names.add(s.name); skills.push(s); }+ }++ for (const s of scanOpenCodeMdFiles(join(home, ".config", "opencode", "skills"))) {+ if (!names.has(s.name)) { names.add(s.name); skills.push(s); }+ }++ return skills;+}++export function scanOpenCodeAgentSkills(workdir: string): SkillEntry[] {+ const skills: SkillEntry[] = [];+ const names = new Set<string>();++ for (const s of scanOpenCodeMdFiles(join(workdir, ".opencode", "commands"))) {+ if (!names.has(s.name)) { names.add(s.name); skills.push(s); }+ }++ for (const s of scanOpenCodeMdFiles(join(workdir, ".opencode", "skills"))) {+ if (!names.has(s.name)) { names.add(s.name); skills.push(s); }+ }++ return skills;+}++type Runtime = "claude" | "codex" | "opencode";++export interface SkillScannerConfig {+ workspacesRoot: string;+ workspaces: { workspaceId: string; token: string; agentIds: string[] }[];+ runtimes: Runtime[];+}+++interface SkillCache {+ hash: string;+ skills: SkillEntry[];+}++function computeHash(skills: SkillEntry[]): string {+ return createHash("md5").update(JSON.stringify(skills)).digest("hex");+}++function globalCachePath(runtime: Runtime): string {+ return join(getCacheDir(), "global", `${runtime}.json`);+}++function agentCachePath(agentId: string, runtime: Runtime): string {+ return join(getCacheDir(), "agents", agentId, `${runtime}.json`);+}++function readCacheHash(filePath: string): string | null {+ try {+ if (!existsSync(filePath)) return null;+ const data: SkillCache = JSON.parse(readFileSync(filePath, "utf-8"));+ return data.hash ?? null;+ } catch {+ return null;+ }+}++function writeCacheFile(filePath: string, hash: string, skills: SkillEntry[]) {+ const dir = join(filePath, "..");+ mkdirSync(dir, { recursive: true });+ const data: SkillCache = { hash, skills };+ writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");+}++let scanTimer: ReturnType<typeof setInterval> | null = null;+let scannerConfig: SkillScannerConfig | null = null;+let clientRef: DaemonClient | null = null;++function discoverTargets(): { agentId: string; workdir: string | null; runtime: Runtime; token: string }[] {+ if (!scannerConfig) return [];+ const rootExists = existsSync(scannerConfig.workspacesRoot);+ const rootReal = rootExists ? realpathSync(scannerConfig.workspacesRoot) : null;+ const targets: { agentId: string; workdir: string | null; runtime: Runtime; token: string }[] = [];++ for (const ws of scannerConfig.workspaces) {+ const agentIds = new Set(ws.agentIds);++ // Also discover agents from filesystem (covers agents not yet in config)+ if (rootReal) {+ const wsDir = join(scannerConfig.workspacesRoot, ws.workspaceId);+ try {+ if (existsSync(wsDir)) {+ for (const dir of readdirSync(wsDir)) {+ if (existsSync(join(wsDir, dir, "workdir"))) agentIds.add(dir);+ }+ }+ } catch { /* skip */ }+ }++ for (const agentId of agentIds) {+ let validWorkdir: string | null = null;+ if (rootReal) {+ const workdir = join(scannerConfig.workspacesRoot, ws.workspaceId, agentId, "workdir");+ if (existsSync(workdir)) {+ try {+ if (realpathSync(workdir).startsWith(rootReal)) validWorkdir = workdir;+ } catch { /* skip */ }+ }+ }+ for (const runtime of scannerConfig.runtimes) {+ targets.push({ agentId, workdir: validWorkdir, runtime, token: ws.token });+ }+ }+ }+ return targets;+}++function getGlobalScanner(runtime: Runtime): () => SkillEntry[] {+ if (runtime === "claude") return scanClaudeGlobalSkills;+ if (runtime === "codex") return scanCodexGlobalSkills;+ return scanOpenCodeGlobalSkills;+}++function getAgentScanner(runtime: Runtime): (workdir: string) => SkillEntry[] {+ if (runtime === "claude") return scanClaudeAgentSkills;+ if (runtime === "codex") return scanCodexAgentSkills;+ return scanOpenCodeAgentSkills;+}++function runScan() {+ if (!scannerConfig || !clientRef) return;++ if (scannerConfig.workspaces.length === 0) return;++ // 1. Scan + sync global skills per runtime to ALL workspaces+ for (const runtime of scannerConfig.runtimes) {+ try {+ const skills = getGlobalScanner(runtime)();+ const hash = computeHash(skills);+ const prevHash = readCacheHash(globalCachePath(runtime));++ if (prevHash !== hash) {+ const skillItems = skills.map((s) => ({ name: s.name, description: s.description }));+ log.info(`Syncing global ${runtime} — ${skills.length} skills`);+ const syncPromises = scannerConfig.workspaces.map((ws) =>+ clientRef!.syncSkills(ws.token, {+ scope: "global",+ runtime,+ skills: skillItems,+ })+ );+ Promise.all(syncPromises).then(() => {+ writeCacheFile(globalCachePath(runtime), hash, skills);+ }).catch((e) => log.debug("Global skill sync failed", e));+ }+ } catch (e) {+ log.debug(`Global scan error for ${runtime}`, e);+ }+ }++ // 2. Scan + sync agent-scope skills per agent (only if workdir exists)+ const targets = discoverTargets();++ for (const target of targets) {+ if (!target.workdir) continue;+ try {+ const skills = getAgentScanner(target.runtime)(target.workdir);+ const hash = computeHash(skills);+ const prevHash = readCacheHash(agentCachePath(target.agentId, target.runtime));++ if (prevHash !== hash) {+ const skillItems = skills.map((s) => ({ name: s.name, description: s.description }));+ log.info(`Syncing ${target.agentId}:${target.runtime} — ${skills.length} agent skills`);+ clientRef.syncSkills(target.token, {+ scope: "agent",+ agent_id: target.agentId,+ runtime: target.runtime,+ skills: skillItems,+ }).then(() => {+ writeCacheFile(agentCachePath(target.agentId, target.runtime), hash, skills);+ }).catch((e) => log.debug("Agent skill sync failed", e));+ }+ } catch (e) {+ log.debug(`Agent scan error for ${target.agentId}:${target.runtime}`, e);+ }+ }+}++export function startSkillScanner(+ client: DaemonClient,+ config: SkillScannerConfig,+ interval = 60_000,+): void {+ clientRef = client;+ scannerConfig = config;+ runScan();+ scanTimer = setInterval(runScan, interval);+}++export function stopSkillScanner(): void {+ if (scanTimer) {+ clearInterval(scanTimer);+ scanTimer = null;+ }+}++diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 99b57067d..8915995dd 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -23,6 +23,7 @@ export * as overview from "./queries/overview";export * as meetingSession from "./queries/meeting-session";export * as channel from "./queries/channel";export * as workspaceFileRequest from "./queries/workspace-file-request";+export * as agentSkill from "./queries/agent-skill";export * as conversationMap from "./queries/conversation-map";export * as agentLink from "./queries/agent-link";export * as inbox from "./queries/inbox";diff --git a/src/shared/src/db/queries/agent-skill.ts b/src/shared/src/db/queries/agent-skill.tsnew file mode 100644index 000000000..072e98def--- /dev/null+++ b/src/shared/src/db/queries/agent-skill.ts@@ -0,0 +1,89 @@+import { eq, and, isNull, or } from "drizzle-orm";+import { agentSkill } from "../schema";+import type { Database } from "../index";++interface SkillRow {+ name: string;+ description: string;+}++export async function syncGlobalSkills(+ db: Database,+ workspaceId: string,+ runtime: string,+ skills: SkillRow[],+) {+ const now = new Date().toISOString();+ const rows = skills.map((s) => ({+ workspaceId,+ agentId: null,+ runtime,+ name: s.name,+ description: s.description,+ syncedAt: now,+ }));++ const BATCH_SIZE = 10;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const statements: any[] = [+ db.delete(agentSkill).where(+ and(eq(agentSkill.workspaceId, workspaceId), eq(agentSkill.runtime, runtime), isNull(agentSkill.agentId))+ ),+ ];+ for (let i = 0; i < rows.length; i += BATCH_SIZE) {+ statements.push(db.insert(agentSkill).values(rows.slice(i, i + BATCH_SIZE)));+ }+ await db.batch(statements as [any, ...any[]]);+}++export async function syncAgentSkills(+ db: Database,+ agentId: string,+ runtime: string,+ workspaceId: string,+ skills: SkillRow[],+) {+ const now = new Date().toISOString();+ const rows = skills.map((s) => ({+ workspaceId,+ agentId,+ runtime,+ name: s.name,+ description: s.description,+ syncedAt: now,+ }));++ const BATCH_SIZE = 10;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const statements: any[] = [+ db.delete(agentSkill).where(+ and(eq(agentSkill.agentId, agentId), eq(agentSkill.runtime, runtime))+ ),+ ];+ for (let i = 0; i < rows.length; i += BATCH_SIZE) {+ statements.push(db.insert(agentSkill).values(rows.slice(i, i + BATCH_SIZE)));+ }+ await db.batch(statements as [any, ...any[]]);+}++export async function getSkills(+ db: Database,+ agentId: string,+ runtime: string,+ workspaceId: string,+) {+ return db+ .select({+ name: agentSkill.name,+ description: agentSkill.description,+ isGlobal: isNull(agentSkill.agentId),+ })+ .from(agentSkill)+ .where(+ and(+ eq(agentSkill.workspaceId, workspaceId),+ eq(agentSkill.runtime, runtime),+ or(isNull(agentSkill.agentId), eq(agentSkill.agentId, agentId))+ )+ );+}diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex ecb189f70..385cf0123 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -763,3 +763,27 @@ export const workspaceFileRequest = sqliteTable(index("idx_wfr_workspace_status").on(t.workspaceId, t.status),]);++export const agentSkill = sqliteTable(+ "agent_skill",+ {+ id: text("id").primaryKey().$defaultFn(() => "as_" + nanoid()),+ workspaceId: text("workspace_id")+ .notNull()+ .references(() => workspace.id, { onDelete: "cascade" }),+ agentId: text("agent_id"),+ runtime: text("runtime").notNull(),+ name: text("name").notNull(),+ description: text("description").notNull().default(""),+ syncedAt: text("synced_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ unique("agent_skill_ws_runtime_name_agent").on(t.workspaceId, t.runtime, t.name, t.agentId),+ index("idx_as_workspace_runtime").on(t.workspaceId, t.runtime),+ index("idx_as_agent_runtime").on(t.agentId, t.runtime),+ foreignKey({+ columns: [t.agentId, t.workspaceId],+ foreignColumns: [agent.id, agent.workspaceId],+ }).onDelete("cascade"),+ ]+);diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 99b252996..c5cdfe31e 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -160,6 +160,8 @@ export {WorkspaceFileBrowseRequestSchema,WorkspaceFileEntrySchema,WorkspaceFileReportSchema,+ SkillEntrySchema,+ SkillSyncRequestSchema,CreateStudioRequestSchema,DaemonPushMessageSchema,} from "./schemas";@@ -205,6 +207,8 @@ export type {WorkspaceFileEntry,WorkspaceFileBrowseRequest,WorkspaceFileReport,+ SkillEntry,+ SkillSyncRequest,CreateStudioRequest,DaemonPushMessageType,} from "./schemas";diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex c290266a2..b54df714a 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -721,6 +721,30 @@ export const WorkspaceFileReportSchema = z.object({});export type WorkspaceFileReport = z.infer<typeof WorkspaceFileReportSchema>;+// ---------------------------------------------------------------------------+// Workspace skill browsing (V2 — D1 cache)+// ---------------------------------------------------------------------------++export const SkillEntrySchema = z.object({+ name: z.string(),+ description: z.string(),+ isGlobal: z.boolean().optional(),+});+export type SkillEntry = z.infer<typeof SkillEntrySchema>;++const SkillItemSchema = z.object({+ name: z.string(),+ description: z.string(),+});++export const SkillSyncRequestSchema = z.object({+ scope: z.enum(["global", "agent"]),+ agent_id: z.string().min(1).optional(),+ runtime: z.enum(["claude", "codex", "opencode"]),+ skills: z.array(SkillItemSchema),+});+export type SkillSyncRequest = z.infer<typeof SkillSyncRequestSchema>;+// ---------------------------------------------------------------------------// Studio onboarding// ---------------------------------------------------------------------------diff --git a/src/shared/test/queries/agent-skill.test.ts b/src/shared/test/queries/agent-skill.test.tsnew file mode 100644index 000000000..46e6fe78a--- /dev/null+++ b/src/shared/test/queries/agent-skill.test.ts@@ -0,0 +1,26 @@+import { describe, it, expect } from "vitest";+import * as agentSkillQueries from "../../src/db/queries/agent-skill";++describe("agent-skill query module exports", () => {+ it("exports syncGlobalSkills", () => {+ expect(typeof agentSkillQueries.syncGlobalSkills).toBe("function");+ });+ it("exports syncAgentSkills", () => {+ expect(typeof agentSkillQueries.syncAgentSkills).toBe("function");+ });+ it("exports getSkills", () => {+ expect(typeof agentSkillQueries.getSkills).toBe("function");+ });+});++describe("agent-skill query function signatures", () => {+ it("syncGlobalSkills accepts (db, workspaceId, runtime, skills)", () => {+ expect(agentSkillQueries.syncGlobalSkills.length).toBe(4);+ });+ it("syncAgentSkills accepts (db, agentId, runtime, workspaceId, skills)", () => {+ expect(agentSkillQueries.syncAgentSkills.length).toBe(5);+ });+ it("getSkills accepts (db, agentId, runtime, workspaceId)", () => {+ expect(agentSkillQueries.getSkills.length).toBe(4);+ });+});diff --git a/src/web/migrations/0033_add_agent_skill.sql b/src/web/migrations/0033_add_agent_skill.sqlnew file mode 100644index 000000000..4f3dfd0e5--- /dev/null+++ b/src/web/migrations/0033_add_agent_skill.sql@@ -0,0 +1,16 @@+CREATE TABLE IF NOT EXISTS agent_skill (+ id TEXT PRIMARY KEY,+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,+ agent_id TEXT,+ runtime TEXT NOT NULL,+ name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ synced_at TEXT NOT NULL,+ -- Note: SQLite treats NULLs as distinct in UNIQUE constraints.+ -- Global skill uniqueness (agent_id=NULL) is enforced by atomic DELETE+INSERT in syncGlobalSkills.+ UNIQUE(workspace_id, runtime, name, agent_id),+ FOREIGN KEY (agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS idx_as_workspace_runtime ON agent_skill(workspace_id, runtime);+CREATE INDEX IF NOT EXISTS idx_as_agent_runtime ON agent_skill(agent_id, runtime);diff --git a/src/web/src/app/api/agents/[id]/skills/route.ts b/src/web/src/app/api/agents/[id]/skills/route.tsnew file mode 100644index 000000000..c6de9984c--- /dev/null+++ b/src/web/src/app/api/agents/[id]/skills/route.ts@@ -0,0 +1,37 @@+import { NextRequest } from "next/server";+import { getCloudflareContext } from "@opennextjs/cloudflare";+import { queries } from "@alook/shared";+import { withAuth } from "@/lib/middleware/auth";+import { writeJSON, writeError } from "@/lib/middleware/helpers";+import { getDb } from "@/lib/db";++export const GET = withAuth(async (req: NextRequest, ctx) => {+ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ const agentId = ctx.params?.id;+ if (!agentId) return writeError("agent id required", 400);++ const workspaceId = new URL(req.url).searchParams.get("workspace_id");+ if (!workspaceId) return writeError("workspace_id required", 400);++ const agent = await queries.agent.getAgent(db, agentId, workspaceId, ctx.userId);+ if (!agent) return writeError("agent not found", 404);++ const KNOWN_RUNTIMES = ["claude", "codex", "opencode"] as const;++ let runtime: string = "claude";+ if (agent.runtimeId) {+ const rt = await queries.runtime.getAgentRuntime(db, agent.runtimeId);+ if (rt) runtime = rt.provider;+ }++ if (!KNOWN_RUNTIMES.includes(runtime as typeof KNOWN_RUNTIMES[number])) {+ console.warn(`[skills] Unknown runtime "${runtime}" for agent ${agentId}, defaulting to "claude"`);+ runtime = "claude";+ }++ const skills = await queries.agentSkill.getSkills(db, agentId, runtime, workspaceId);++ return writeJSON({ skills });+});diff --git a/src/web/src/app/api/daemon/skills/sync/route.ts b/src/web/src/app/api/daemon/skills/sync/route.tsnew file mode 100644index 000000000..f621d6b5b--- /dev/null+++ b/src/web/src/app/api/daemon/skills/sync/route.ts@@ -0,0 +1,42 @@+import { NextRequest } from "next/server";+import { getCloudflareContext } from "@opennextjs/cloudflare";+import { queries, SkillSyncRequestSchema } from "@alook/shared";+import { withAuth } from "@/lib/middleware/auth";+import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";+import { getDb, withD1Retry } from "@/lib/db";++export const POST = withAuth(async (req: NextRequest, ctx) => {+ if (!ctx.workspaceId) {+ return writeError("Forbidden: machine token required", 403);+ }++ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ const [body, err] = await parseBody(req, SkillSyncRequestSchema);+ if (err) return err;++ if (body.scope === "global") {+ await withD1Retry(() =>+ queries.agentSkill.syncGlobalSkills(+ db,+ ctx.workspaceId!,+ body.runtime,+ body.skills,+ )+ );+ } else {+ if (!body.agent_id) return writeError("agent_id required for agent scope", 400);+ await withD1Retry(() =>+ queries.agentSkill.syncAgentSkills(+ db,+ body.agent_id!,+ body.runtime,+ ctx.workspaceId!,+ body.skills,+ )+ );+ }++ return writeJSON({ status: "ok" });+});diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex b3d5e1da3..6792f8395 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -31,10 +31,11 @@ import {listFlaggedMessageIds,flagMessage as apiFlagMessage,unflagMessage as apiUnflagMessage,+ getAgentSkills,} from "@/lib/api";import { appendCachedMessage, getCachedMessages, getCachedMessagesBefore, getCacheMeta, mergeCachedMessages } from "@/lib/chat-cache";import type { PreviousConversation, TraceTask } from "@/lib/api";-import type { Artifact, Conversation, Issue, IssueComment, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";+import type { Artifact, Conversation, Issue, IssueComment, Message, SkillEntry, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";import { useInboxCount } from "@/contexts/inbox-count-context";import { useFlagCount } from "@/contexts/flag-count-context";@@ -47,6 +48,8 @@ import { ArrowUp, BedDouble, Box, FileText, Loader2, Mail, MessageSquareQuote, Pimport { useCachedMessages } from "@/hooks/use-cached-messages";import { useMentionPopup } from "@/hooks/use-mention-popup";import { MentionPopup } from "@/components/agent-chat/mention-popup";+import { useSlashCommand } from "@/hooks/use-slash-command";+import { SlashCommandPopup } from "@/components/agent-chat/slash-command-popup";import { highlightMentions } from "@/lib/highlight-mentions";import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";import { EmailEventSheet } from "@/components/agent-chat/email-event-sheet";@@ -367,7 +370,13 @@ export function AgentChatView({const [renderNow] = useState(() => Date.now());const [pendingFilesByMessage, setPendingFilesByMessage] = useState<Map<string, File[]>>(() => new Map());- const [quotedText, setQuotedText] = useState<string | null>(null);+ const [quotedText, setQuotedText] = useState<string | null>(() => {+ if (typeof window === "undefined") return null;+ try {+ const meta = JSON.parse(localStorage.getItem(`chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`) ?? "null");+ return meta?.quote ?? null;+ } catch { return null; }+ });const [selectionPopup, setSelectionPopup] = useState<{ text: string; x: number; y: number } | null>(null);const [flaggedIds, setFlaggedIds] = useState<Set<string>>(new Set());const flaggedIdsRef = useRef(flaggedIds);@@ -448,6 +457,43 @@ export function AgentChatView({onInputChange: setInput,});+ // Slash command skills — fetch from D1 on mount+ const [agentSkills, setAgentSkills] = useState<SkillEntry[]>([]);+ const skillsFetchedRef = useRef(false);+ const draftMetaRestoredRef = useRef(false);++ useEffect(() => {+ if (skillsFetchedRef.current) return;+ skillsFetchedRef.current = true;+ getAgentSkills(agentId, workspaceId)+ .then((res) => setAgentSkills(res.skills as SkillEntry[]))+ .catch(() => {});+ }, [agentId, workspaceId]);++ const [initialActiveSkill] = useState<SkillEntry | null>(() => {+ if (typeof window === "undefined") return null;+ try {+ const meta = JSON.parse(localStorage.getItem(`chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`) ?? "null");+ return meta?.skill ?? null;+ } catch { return null; }+ });++ const slashCommand = useSlashCommand({+ input,+ caretIndex,+ textareaRef,+ skills: agentSkills,+ onInputChange: setInput,+ initialActiveSkill,+ });++ useEffect(() => {+ if (agentSkills.length === 0 || !slashCommand.activeSkill) return;+ const exists = agentSkills.some(s => s.name === slashCommand.activeSkill!.name);+ if (!exists) slashCommand.setActiveSkill(null);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally omits slashCommand; only re-validate when the skills list itself changes+ }, [agentSkills]);+useEffect(() => {const key = `chat-draft:${agentId}:${targetConvId ?? 'default'}`;if (input) {@@ -457,6 +503,23 @@ export function AgentChatView({}}, [input, agentId, targetConvId]);+ useEffect(() => {+ if (!draftMetaRestoredRef.current) return;+ const key = `chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`;+ const meta: { skill?: { name: string; description: string } | null; quote?: string | null } = {};+ if (slashCommand.activeSkill) {+ meta.skill = { name: slashCommand.activeSkill.name, description: slashCommand.activeSkill.description };+ }+ if (quotedText) {+ meta.quote = quotedText;+ }+ if (meta.skill || meta.quote) {+ localStorage.setItem(key, JSON.stringify(meta));+ } else {+ localStorage.removeItem(key);+ }+ }, [slashCommand.activeSkill, quotedText, agentId, targetConvId]);+useEffect(() => {if (!sending) {textareaRef.current?.focus();@@ -492,6 +555,21 @@ export function AgentChatView({setHasMoreConversations(false);oldestConversationCursorRef.current = null;setInput(localStorage.getItem(`chat-draft:${agentId}:${targetConvId ?? 'default'}`) ?? "");+ const metaRaw = localStorage.getItem(`chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`);+ if (metaRaw) {+ try {+ const meta = JSON.parse(metaRaw);+ setQuotedText(meta.quote ?? null);+ slashCommand.setActiveSkill(meta.skill ? (meta.skill as SkillEntry) : null);+ } catch {+ setQuotedText(null);+ slashCommand.setActiveSkill(null);+ }+ } else {+ setQuotedText(null);+ slashCommand.setActiveSkill(null);+ }+ draftMetaRestoredRef.current = true;setMessages([]);async function load() {let hasCachedMessages = false;@@ -1360,14 +1438,20 @@ export function AgentChatView({}// Prepend quoted text as blockquote if present- const content = quotedText+ let content = quotedText? `> ${quotedText.split("\n").join("\n> ")}\n\n${rawContent}`: rawContent;+ // Prepend skill instruction if active+ if (slashCommand.activeSkill) {+ content = `/${slashCommand.activeSkill.name} ${content}`;+ }+const filesToSend = [...pendingFiles];setInput("");setPendingFiles([]);setQuotedText(null);+ slashCommand.clearActiveSkill();setSending(true);const taskActive = !!activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);@@ -1626,6 +1710,7 @@ export function AgentChatView({const handleKeyDown = (e: React.KeyboardEvent) => {if (mentionPopup.handleMentionKeyDown(e)) return;+ if (slashCommand.handleSlashKeyDown(e)) return;if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {e.preventDefault();handleSend();@@ -1855,6 +1940,26 @@ export function AgentChatView({<p className="text-sm text-muted-foreground font-medium">Drop files here</p></div>)}+ {slashCommand.activeSkill && (+ <div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50">+ <div className="flex-1 min-w-0 flex items-center gap-2">+ <span className="shrink-0 text-xs font-medium text-primary">/{slashCommand.activeSkill.name}</span>+ {slashCommand.activeSkill.isGlobal && (+ <span className="text-[10px] font-medium text-muted-foreground bg-muted rounded px-1 py-0.5">Global</span>+ )}+ <span className="text-xs text-muted-foreground truncate">+ {slashCommand.activeSkill.description}+ </span>+ </div>+ <button+ type="button"+ onClick={slashCommand.clearActiveSkill}+ className="shrink-0 p-0.5 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"+ >+ <X className="size-3.5" />+ </button>+ </div>+ )}{quotedText && (<div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50"><div className="flex-1 min-w-0 flex items-start gap-2">@@ -1880,6 +1985,13 @@ export function AgentChatView({onSelect={mentionPopup.selectAgent}anchorPos={mentionPopup.anchorPos}/>+ <SlashCommandPopup+ isOpen={slashCommand.isOpen}+ skills={slashCommand.skills}+ selectedIndex={slashCommand.selectedIndex}+ onSelect={slashCommand.selectSkill}+ anchorPos={slashCommand.anchorPos}+ /><div className="relative"><divaria-hidden@@ -1918,7 +2030,7 @@ export function AgentChatView({const backdrop = (e.target as HTMLTextAreaElement).previousElementSibling;if (backdrop) backdrop.scrollTop = (e.target as HTMLTextAreaElement).scrollTop;}}- placeholder={isTaskActive ? "Type a follow-up..." : "Type a message..."}+ placeholder={isTaskActive ? "Type a follow-up..." : "Type a message or / for skills..."}rows={1}disabled={sending}className={cn(diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsxindex 1635ab958..844763076 100644--- a/src/web/src/components/agent-chat/message-list.tsx+++ b/src/web/src/components/agent-chat/message-list.tsx@@ -211,7 +211,7 @@ export const MessageItem = memo(function MessageItem({<div className={cn("group/msg",isFlagged && "bg-muted/30 rounded-lg px-2 -mx-2"- )}>+ )} {...(isTaskDone ? { "data-quote-source": true } : {})}><TaskStreamtask={activeTask}messages={taskMessages}@@ -230,6 +230,9 @@ export const MessageItem = memo(function MessageItem({)}{msg.role === "user" ? (() => {const awaitingRun = isLastMessage && !!activeTask && activeTask.status !== "running" && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);+ const slashMatch = msg.content.match(/^\/(\S+)\s?([\s\S]*)$/);+ const skillName = slashMatch?.[1] ?? null;+ const messageBody = slashMatch ? (slashMatch[2] || "") : msg.content;return (<div className="flex justify-end" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}><div className={cn(@@ -238,9 +241,16 @@ export const MessageItem = memo(function MessageItem({{awaitingRun && (<div className="absolute inset-0 rounded-lg animate-pulse pointer-events-none" style={{ boxShadow: "0 0 0 2px var(--bubble-glow)" }} />)}- <div className="markdown markdown-user">- <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: false, download: false, fullscreen: false } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(msg.content, agents)}</Streamdown>- </div>+ {skillName && (+ <span className="inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium bg-primary-foreground/15 text-primary-foreground mb-1">+ /{skillName}+ </span>+ )}+ {messageBody && (+ <div className="markdown markdown-user">+ <Streamdown controls={{ code: { copy: true, download: false }, table: { copy: false, download: false, fullscreen: false } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(messageBody, agents)}</Streamdown>+ </div>+ )}{msg.attachment_ids && msg.attachment_ids.length > 0 && (<AttachmentChips attachmentIds={msg.attachment_ids} artifacts={artifacts} onArtifactClick={onArtifactClick} />)}diff --git a/src/web/src/components/agent-chat/slash-command-popup.tsx b/src/web/src/components/agent-chat/slash-command-popup.tsxnew file mode 100644index 000000000..dbe4796d6--- /dev/null+++ b/src/web/src/components/agent-chat/slash-command-popup.tsx@@ -0,0 +1,85 @@+import React, { useRef, useEffect } from "react"+import type { SkillEntry } from "@alook/shared"+import { cn } from "@/lib/utils"++interface SlashCommandPopupProps {+ isOpen: boolean+ skills: SkillEntry[]+ selectedIndex: number+ onSelect: (skill: SkillEntry) => void+ anchorPos: { top: number; left: number }+}++function SkillRow({+ skill,+ isSelected,+ onSelect,+}: {+ skill: SkillEntry+ isSelected: boolean+ onSelect: (skill: SkillEntry) => void+}) {+ return (+ <button+ type="button"+ data-slash-item+ className={cn(+ "flex w-full flex-col gap-0.5 px-3 py-1.5 text-left text-sm transition-colors",+ isSelected ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",+ )}+ onMouseDown={(e) => {+ e.preventDefault()+ onSelect(skill)+ }}+ >+ <span className="flex w-full items-center gap-2">+ <span className="min-w-0 flex-1 truncate font-medium">/{skill.name}</span>+ {skill.isGlobal && (+ <span className="shrink-0 rounded px-1 py-0.5 text-[10px] font-medium bg-muted text-muted-foreground">+ Global+ </span>+ )}+ </span>+ {skill.description && (+ <span className="truncate text-xs text-muted-foreground">+ {skill.description.slice(0, 80)}+ </span>+ )}+ </button>+ )+}++export function SlashCommandPopup({ isOpen, skills, selectedIndex, onSelect, anchorPos }: SlashCommandPopupProps) {+ const listRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (!listRef.current) return+ const items = listRef.current.querySelectorAll("[data-slash-item]")+ const selected = items[selectedIndex] as HTMLElement | undefined+ selected?.scrollIntoView({ block: "nearest" })+ }, [selectedIndex])++ if (!isOpen || skills.length === 0) return null++ return (+ <div+ className="absolute z-50 w-70 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"+ style={{+ top: anchorPos.top - 4,+ left: anchorPos.left,+ transform: "translateY(-100%)",+ }}+ >+ <div ref={listRef} className="max-h-60 overflow-y-auto py-1 thin-scrollbar">+ {skills.map((skill, i) => (+ <SkillRow+ key={skill.name}+ skill={skill}+ isSelected={i === selectedIndex}+ onSelect={onSelect}+ />+ ))}+ </div>+ </div>+ )+}diff --git a/src/web/src/hooks/use-slash-command.ts b/src/web/src/hooks/use-slash-command.tsnew file mode 100644index 000000000..50bc48398--- /dev/null+++ b/src/web/src/hooks/use-slash-command.ts@@ -0,0 +1,200 @@+import { useState, useCallback, useMemo, useRef, useEffect } from "react"+import type { SkillEntry } from "@alook/shared"++export interface SlashCommandPopupState {+ isOpen: boolean+ query: string+ selectedIndex: number+ anchorPos: { top: number; left: number }+ skills: SkillEntry[]+ activeSkill: SkillEntry | null+ handleSlashKeyDown: (e: React.KeyboardEvent) => boolean+ selectSkill: (skill: SkillEntry) => void+ clearActiveSkill: () => void+ setActiveSkill: (skill: SkillEntry | null) => void+}++interface UseSlashCommandParams {+ input: string+ caretIndex: number | null+ textareaRef: React.RefObject<HTMLTextAreaElement | null>+ skills: SkillEntry[]+ onInputChange: (value: string) => void+ initialActiveSkill?: SkillEntry | null+}++const MAX_QUERY_LENGTH = 30+const POPUP_WIDTH = 280++function findSlashTrigger(input: string, caretIndex: number): { start: number; query: string } | null {+ if (!input.startsWith("/")) return null+ if (caretIndex === 0) return null+ let i = caretIndex - 1+ while (i >= 0 && caretIndex - i <= MAX_QUERY_LENGTH) {+ const ch = input.charCodeAt(i)+ if (ch === 47 && i === 0) { // '/' at position 0 only+ return { start: 0, query: input.slice(1, caretIndex) }+ }+ if (ch === 10 || ch === 13 || ch === 32) return null+ i--+ }+ return null+}++function getCaretCoordinates(textarea: HTMLTextAreaElement, position: number): { top: number; left: number } {+ const mirror = document.createElement("div")+ const style = window.getComputedStyle(textarea)++ const props = [+ "fontFamily", "fontSize", "fontWeight", "fontStyle", "letterSpacing",+ "textTransform", "wordSpacing", "textIndent", "lineHeight",+ "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",+ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth",+ "boxSizing", "whiteSpace", "wordWrap", "overflowWrap",+ ] as const++ mirror.style.position = "absolute"+ mirror.style.top = "-9999px"+ mirror.style.left = "-9999px"+ mirror.style.visibility = "hidden"+ mirror.style.overflow = "hidden"+ mirror.style.width = `${textarea.offsetWidth}px`++ for (const prop of props) {+ (mirror.style as unknown as Record<string, string>)[prop] = style.getPropertyValue(+ prop.replace(/([A-Z])/g, "-$1").toLowerCase()+ )+ }++ const textBefore = textarea.value.slice(0, position)+ mirror.textContent = textBefore+ const marker = document.createElement("span")+ marker.textContent = ""+ mirror.appendChild(marker)++ document.body.appendChild(mirror)+ const top = marker.offsetTop - textarea.scrollTop+ const left = Math.max(0, Math.min(marker.offsetLeft, textarea.offsetWidth - POPUP_WIDTH))+ document.body.removeChild(mirror)++ return { top, left }+}++export function useSlashCommand({+ input,+ caretIndex,+ textareaRef,+ skills,+ onInputChange,+ initialActiveSkill,+}: UseSlashCommandParams): SlashCommandPopupState {+ const [isOpen, setIsOpen] = useState(false)+ const [query, setQuery] = useState("")+ const [selectedIndex, setSelectedIndex] = useState(0)+ const [anchorPos, setAnchorPos] = useState({ top: 0, left: 0 })+ const triggerStartRef = useRef<number | null>(null)++ const filteredSkills = useMemo(() => {+ if (!isOpen) return []+ if (!query) return skills+ const q = query.toLowerCase()+ const startsWith: SkillEntry[] = []+ const includes: SkillEntry[] = []+ for (const s of skills) {+ const name = s.name.toLowerCase()+ if (name.startsWith(q)) startsWith.push(s)+ else if (name.includes(q)) includes.push(s)+ }+ return [...startsWith, ...includes]+ }, [isOpen, query, skills])++ useEffect(() => {+ setSelectedIndex(0)+ }, [filteredSkills.length, query])++ const [activeSkill, setActiveSkill] = useState<SkillEntry | null>(initialActiveSkill ?? null)++ useEffect(() => {+ if (activeSkill) {+ setIsOpen(false)+ return+ }+ if (caretIndex === null) {+ setIsOpen(false)+ return+ }++ const trigger = findSlashTrigger(input, caretIndex)+ if (trigger) {+ triggerStartRef.current = trigger.start+ setQuery(trigger.query)+ setIsOpen(true)++ if (textareaRef.current) {+ const coords = getCaretCoordinates(textareaRef.current, trigger.start)+ setAnchorPos(coords)+ }+ } else {+ setIsOpen(false)+ triggerStartRef.current = null+ }+ }, [input, caretIndex, textareaRef, activeSkill])++ const selectSkill = useCallback((skill: SkillEntry) => {+ setActiveSkill(skill)+ onInputChange("")+ setIsOpen(false)++ requestAnimationFrame(() => {+ const ta = textareaRef.current+ if (ta) {+ ta.focus()+ ta.setSelectionRange(0, 0)+ }+ })+ }, [textareaRef, onInputChange])++ const clearActiveSkill = useCallback(() => {+ setActiveSkill(null)+ }, [])++ const handleSlashKeyDown = useCallback((e: React.KeyboardEvent): boolean => {+ if (!isOpen || filteredSkills.length === 0) return false+ if (e.nativeEvent.isComposing) return false++ if (e.key === "ArrowDown") {+ e.preventDefault()+ setSelectedIndex(i => (i + 1) % filteredSkills.length)+ return true+ }+ if (e.key === "ArrowUp") {+ e.preventDefault()+ setSelectedIndex(i => (i - 1 + filteredSkills.length) % filteredSkills.length)+ return true+ }+ if (e.key === "Enter" || e.key === "Tab") {+ e.preventDefault()+ selectSkill(filteredSkills[selectedIndex])+ return true+ }+ if (e.key === "Escape") {+ e.preventDefault()+ setIsOpen(false)+ return true+ }+ return false+ }, [isOpen, filteredSkills, selectedIndex, selectSkill])++ return {+ isOpen,+ query,+ selectedIndex,+ anchorPos,+ skills: filteredSkills,+ activeSkill,+ handleSlashKeyDown,+ selectSkill,+ clearActiveSkill,+ setActiveSkill,+ }+}diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex ea5c24f69..ff594509c 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -1066,6 +1066,12 @@ export const requestWorkspaceBrowse = (},);+// Skill browsing+export const getAgentSkills = (agentId: string, workspaceId: string) =>+ apiFetch<{ skills: { name: string; description: string; isGlobal?: boolean }[] }>(+ `/api/agents/${agentId}/skills${wsQuery(workspaceId)}`,+ );+// Meetingsexport const listMeetings = (agentId: string, workspaceId: string) =>apiFetch<MeetingSession[]>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`);diff --git a/src/web/src/test/e2e/skill-sync.test.ts b/src/web/src/test/e2e/skill-sync.test.tsnew file mode 100644index 000000000..eb4e270fc--- /dev/null+++ b/src/web/src/test/e2e/skill-sync.test.ts@@ -0,0 +1,142 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { seedTestData, cleanupTestData, type TestSeed } from "../helpers/seed"+import { tokenRequest } from "../helpers/auth"+import { sqlQuery, sql } from "../helpers/db"++let seed: TestSeed++beforeAll(() => { seed = seedTestData() })+afterAll(() => {+ sql(`DELETE FROM agent_skill WHERE workspace_id = '${seed.workspaceId}'`)+ cleanupTestData(seed)+})++describe("POST /api/daemon/skills/sync", () => {+ it("syncs global skills (scope=global)", async () => {+ const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "global",+ runtime: "claude",+ skills: [+ { name: "test-skill-1", description: "Test skill one" },+ { name: "test-skill-2", description: "Test skill two" },+ ],+ }),+ })+ expect(res.status).toBe(200)+ const data = await res.json()+ expect(data.status).toBe("ok")++ const rows = sqlQuery<{ name: string; agent_id: string | null }>(+ `SELECT name, agent_id FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND runtime = 'claude' AND agent_id IS NULL ORDER BY name`+ )+ expect(rows).toHaveLength(2)+ expect(rows[0]!.name).toBe("test-skill-1")+ expect(rows[0]!.agent_id).toBeNull()+ })++ it("syncs agent-scoped skills (scope=agent)", async () => {+ const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "agent",+ runtime: "claude",+ agent_id: seed.agentId,+ skills: [+ { name: "agent-skill-1", description: "Agent specific" },+ ],+ }),+ })+ expect(res.status).toBe(200)++ const rows = sqlQuery<{ name: string; agent_id: string }>(+ `SELECT name, agent_id FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND agent_id = '${seed.agentId}'`+ )+ expect(rows).toHaveLength(1)+ expect(rows[0]!.name).toBe("agent-skill-1")+ expect(rows[0]!.agent_id).toBe(seed.agentId)+ })++ it("re-sync replaces old skills (idempotent)", async () => {+ const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "global",+ runtime: "claude",+ skills: [+ { name: "updated-skill", description: "Replaced" },+ ],+ }),+ })+ expect(res.status).toBe(200)++ const rows = sqlQuery<{ name: string }>(+ `SELECT name FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND runtime = 'claude' AND agent_id IS NULL`+ )+ expect(rows).toHaveLength(1)+ expect(rows[0]!.name).toBe("updated-skill")+ })++ it("returns 400 when agent scope missing agent_id", async () => {+ const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "agent",+ runtime: "claude",+ skills: [{ name: "x", description: "" }],+ }),+ })+ expect(res.status).toBe(400)+ })++ it("FK constraint: agent-scoped sync with invalid agent_id fails", async () => {+ const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "agent",+ runtime: "claude",+ agent_id: "ag_nonexistent_id_12345",+ skills: [{ name: "bad-skill", description: "" }],+ }),+ })+ expect(res.status).toBeGreaterThanOrEqual(400)+ })+})++describe("GET /api/agents/[id]/skills", () => {+ it("returns combined global + agent skills", async () => {+ await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "global",+ runtime: "claude",+ skills: [{ name: "global-one", description: "G" }],+ }),+ })+ await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "agent",+ runtime: "claude",+ agent_id: seed.agentId,+ skills: [{ name: "agent-one", description: "A" }],+ }),+ })++ const rows = sqlQuery<{ name: string }>(+ `SELECT name FROM agent_skill WHERE workspace_id = '${seed.workspaceId}' AND runtime = 'claude' AND (agent_id IS NULL OR agent_id = '${seed.agentId}') ORDER BY name`+ )+ expect(rows.length).toBeGreaterThanOrEqual(2)+ const names = rows.map(r => r.name)+ expect(names).toContain("global-one")+ expect(names).toContain("agent-one")+ })+})diff --git a/src/web/src/test/helpers/seed.ts b/src/web/src/test/helpers/seed.tsindex 4f233f383..cf3e3022a 100644--- a/src/web/src/test/helpers/seed.ts+++ b/src/web/src/test/helpers/seed.ts@@ -62,6 +62,7 @@ export function cleanupTestData(seed: TestSeed) {`DELETE FROM conversation WHERE workspace_id = '${ws}'`,`DELETE FROM meeting_session WHERE workspace_id = '${ws}'`,`DELETE FROM emails WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = '${ws}')`,+ `DELETE FROM agent_skill WHERE workspace_id = '${ws}'`,`DELETE FROM agent_whitelist WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = '${ws}')`,`DELETE FROM agent_access WHERE workspace_id = '${ws}'`,`DELETE FROM agent_pin WHERE workspace_id = '${ws}'`,