π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent): auto-scan project workspace (skills + AGENTS.md) for server agents (#15512)
Arvin Xub6ae130c9712
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 9a218162338..27550cd04a3 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -13,6 +13,7 @@ import type {GetCommandOutputParams,GlobFilesParams,GrepContentParams,+ InitWorkspaceParams,KillCommandParams,ListLocalFileParams,LocalReadFileParams,@@ -34,6 +35,7 @@ import LocalFileCtr from './LocalFileCtr';import McpCtr from './McpCtr';import RemoteServerConfigCtr from './RemoteServerConfigCtr';import ShellCommandCtr from './ShellCommandCtr';+import WorkspaceCtr from './WorkspaceCtr';/*** Inject the lh-notify protocol into the first turn of a new hetero-agent session.@@ -162,6 +164,10 @@ export default class GatewayConnectionCtr extends ControllerModule {return this.app.getController(LocalFileCtr);}+ private get workspaceCtr() {+ return this.app.getController(WorkspaceCtr);+ }+private get shellCommandCtr() {return this.app.getController(ShellCommandCtr);}@@ -203,6 +209,10 @@ export default class GatewayConnectionCtr extends ControllerModule {// Wire up agent run handlersrv.setAgentRunHandler((request) => this.executeAgentRun(request));+ // Wire up generic device RPC handler (server-internal method forwarding,+ // e.g. workspace-init scans β never surfaced to the agent)+ srv.setRpcHandler((method, params) => this.executeDeviceRpc(method, params));+// Wire up device registrar (persists this device to the server registry)srv.setDeviceRegistrar((info) => this.registerDevice(info));@@ -335,6 +345,23 @@ export default class GatewayConnectionCtr extends ControllerModule {return this.localSystemRuntime;}+ /**+ * Dispatch a generic server-internal device RPC (not an agent tool call) by+ * method name. Currently only `initWorkspace` (scan the bound project root for+ * skills + AGENTS.md); add new server-only device methods here.+ */+ private async executeDeviceRpc(method: string, params: unknown): Promise<unknown> {+ switch (method) {+ case 'initWorkspace': {+ return this.workspaceCtr.initWorkspace(params as InitWorkspaceParams);+ }++ default: {+ throw new Error(`Unknown device RPC method: ${method}`);+ }+ }+ }+private async executeToolCall(apiName: string,args: unknown,diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 9683c90abbc..244a7d87ad1 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -1,5 +1,5 @@import { constants } from 'node:fs';-import { access, mkdir, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';+import { access, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';import path from 'node:path';import {@@ -12,8 +12,6 @@ import {type GrepContentParams,type GrepContentResult,type ListLocalFileParams,- type ListProjectSkillsParams,- type ListProjectSkillsResult,type LocalFilePreviewUrlParams,type LocalFilePreviewUrlResult,type LocalMoveFilesResultItem,@@ -123,62 +121,6 @@ const collectProjectDirectories = (files: string[], root: string): ProjectFileInreturn [...directories].map((directory) => createProjectFileEntry(root, directory, true));};-const SKILL_FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/;--// Cap recursion to guard against pathological directory trees.-const MAX_SKILL_FILE_COUNT = 1000;--const listSkillFilesRecursive = async (dir: string): Promise<string[]> => {- const results: string[] = [];- const stack: string[] = [dir];-- while (stack.length > 0 && results.length < MAX_SKILL_FILE_COUNT) {- const current = stack.pop()!;- let entries;- try {- entries = await readdir(current, { withFileTypes: true });- } catch {- continue;- }- for (const entry of entries) {- if (entry.name.startsWith('.')) continue;- const full = path.join(current, entry.name);- if (entry.isDirectory()) {- stack.push(full);- } else if (entry.isFile()) {- results.push(toPosixRelativePath(path.relative(dir, full)));- if (results.length >= MAX_SKILL_FILE_COUNT) break;- }- }- }- return results.sort();-};--// Parse a minimal YAML frontmatter block for SKILL.md files.-// Only handles `key: value` lines; multi-line block scalars fall back to the first line.-const parseSkillFrontmatter = (raw: string): Record<string, string> => {- const match = raw.match(SKILL_FRONTMATTER_RE);- if (!match) return {};-- const fields: Record<string, string> = {};- for (const line of match[1].split(/\r?\n/)) {- const colonIdx = line.indexOf(':');- if (colonIdx === -1) continue;- const key = line.slice(0, colonIdx).trim();- if (!key || key.startsWith('#')) continue;- let value = line.slice(colonIdx + 1).trim();- if (value.startsWith('|') || value.startsWith('>')) continue;- if (- (value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith("'") && value.endsWith("'"))- ) {- value = value.slice(1, -1);- }- fields[key] = value;- }- return fields;-};-const createDetectedProjectFileEntry = async (root: string,absolutePath: string,@@ -661,61 +603,6 @@ export default class LocalFileCtr extends ControllerModule {};}- /**- * Scan agent skill directories under the project root and return parsed- * frontmatter for each SKILL.md. Used by the hetero agent's working sidebar- * to surface skills available in the current project.- */- @IpcMethod()- async listProjectSkills(params: ListProjectSkillsParams): Promise<ListProjectSkillsResult> {- const root = params.scope;- const sources = ['.agents/skills', '.claude/skills'] as const;-- for (const source of sources) {- const dir = path.join(root, source);- try {- const entries = await readdir(dir, { withFileTypes: true });- const skills = (- await Promise.all(- entries- .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())- .map(async (entry) => {- const skillDir = path.join(dir, entry.name);- const skillFile = path.join(skillDir, 'SKILL.md');- try {- const raw = await readFile(skillFile, 'utf8');- const fields = parseSkillFrontmatter(raw);- const files = await listSkillFilesRecursive(skillDir);- return {- description: fields.description || undefined,- fileCount: files.length,- files,- name: fields.name || entry.name,- path: skillFile,- skillDir,- source,- };- } catch {- return null;- }- }),- )- )- .filter((skill): skill is NonNullable<typeof skill> => skill !== null)- .sort((a, b) => a.name.localeCompare(b.name));-- if (skills.length > 0) {- await this.approveProjectRootForPreview(root);- return { root, skills, source };- }- } catch {- // Directory does not exist or is not readable; try the next candidate.- }- }-- return { root, skills: [], source: null };- }-/*** Handle IPC event for local file search*/diff --git a/apps/desktop/src/main/controllers/WorkspaceCtr.ts b/apps/desktop/src/main/controllers/WorkspaceCtr.tsnew file mode 100644index 00000000000..658ad210d83--- /dev/null+++ b/apps/desktop/src/main/controllers/WorkspaceCtr.ts@@ -0,0 +1,230 @@+import { readdir, readFile } from 'node:fs/promises';+import path from 'node:path';++import {+ type InitWorkspaceParams,+ type InitWorkspaceResult,+ type ListProjectSkillsParams,+ type ListProjectSkillsResult,+ type ProjectSkillItem,+} from '@lobechat/electron-client-ipc';++import { createLogger } from '@/utils/logger';++import { ControllerModule, IpcMethod } from './index';++const logger = createLogger('controllers:WorkspaceCtr');++const SKILL_FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/;++// Cap recursion to guard against pathological directory trees.+const MAX_SKILL_FILE_COUNT = 1000;++const toPosixRelativePath = (filePath: string) => filePath.split(path.sep).join('/');++const listSkillFilesRecursive = async (dir: string): Promise<string[]> => {+ const results: string[] = [];+ const stack: string[] = [dir];++ while (stack.length > 0 && results.length < MAX_SKILL_FILE_COUNT) {+ const current = stack.pop()!;+ let entries;+ try {+ entries = await readdir(current, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ const full = path.join(current, entry.name);+ if (entry.isDirectory()) {+ stack.push(full);+ } else if (entry.isFile()) {+ results.push(toPosixRelativePath(path.relative(dir, full)));+ if (results.length >= MAX_SKILL_FILE_COUNT) break;+ }+ }+ }+ return results.sort();+};++// Parse a minimal YAML frontmatter block for SKILL.md files.+// Only handles `key: value` lines; multi-line block scalars fall back to the first line.+const parseSkillFrontmatter = (raw: string): Record<string, string> => {+ const match = raw.match(SKILL_FRONTMATTER_RE);+ if (!match) return {};++ const fields: Record<string, string> = {};+ for (const line of match[1].split(/\r?\n/)) {+ const colonIdx = line.indexOf(':');+ if (colonIdx === -1) continue;+ const key = line.slice(0, colonIdx).trim();+ if (!key || key.startsWith('#')) continue;+ let value = line.slice(colonIdx + 1).trim();+ if (value.startsWith('|') || value.startsWith('>')) continue;+ if (+ (value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))+ ) {+ value = value.slice(1, -1);+ }+ fields[key] = value;+ }+ return fields;+};++/**+ * WorkspaceCtr+ *+ * Owns "project workspace" scanning: discovering agent skills (`.agents/skills`+ * / `.claude/skills`) and project-root instructions (`AGENTS.md` / `CLAUDE.md`)+ * under a bound project directory. Split out of LocalFileCtr so the+ * workspace/agent-config concern is distinct from generic local file ops.+ */+export default class WorkspaceCtr extends ControllerModule {+ static override readonly groupName = 'workspace';++ /**+ * Scan one skill source directory (e.g. `.agents/skills`) under `root` and+ * return parsed frontmatter for each `SKILL.md`. Returns `[]` when the source+ * directory is absent or unreadable. Unsorted β callers sort/merge.+ */+ private async scanSkillsInSource(+ root: string,+ source: ProjectSkillItem['source'],+ ): Promise<ProjectSkillItem[]> {+ const dir = path.join(root, source);+ let entries;+ try {+ entries = await readdir(dir, { withFileTypes: true });+ } catch {+ // Directory does not exist or is not readable.+ return [];+ }++ const skills = await Promise.all(+ entries+ .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())+ .map(async (entry) => {+ const skillDir = path.join(dir, entry.name);+ const skillFile = path.join(skillDir, 'SKILL.md');+ try {+ const raw = await readFile(skillFile, 'utf8');+ const fields = parseSkillFrontmatter(raw);+ const files = await listSkillFilesRecursive(skillDir);+ return {+ description: fields.description || undefined,+ fileCount: files.length,+ files,+ name: fields.name || entry.name,+ path: skillFile,+ skillDir,+ source,+ };+ } catch {+ return null;+ }+ }),+ );++ return skills.filter((skill): skill is ProjectSkillItem => skill !== null);+ }++ /**+ * Scan agent skill directories under the project root and return parsed+ * frontmatter for each SKILL.md. Used by the hetero agent's working sidebar+ * to surface skills available in the current project. Returns the first+ * source directory that yields any skills (`.agents/skills` wins).+ */+ @IpcMethod()+ async listProjectSkills(params: ListProjectSkillsParams): Promise<ListProjectSkillsResult> {+ const root = params.scope;+ const sources = ['.agents/skills', '.claude/skills'] as const;++ for (const source of sources) {+ const skills = (await this.scanSkillsInSource(root, source)).sort((a, b) =>+ a.name.localeCompare(b.name),+ );++ if (skills.length > 0) {+ await this.approveProjectRootForPreview(root);+ return { root, skills, source };+ }+ }++ return { root, skills: [], source: null };+ }++ /**+ * One-call "workspace init" scan of a bound project directory: merge the+ * project skills from BOTH `.agents/skills` and `.claude/skills` (deduped by+ * name, `.agents/skills` winning) and read the project-root agent+ * instructions file (`AGENTS.md`, else `CLAUDE.md`). Driven server-side at run+ * start via the generic device RPC (not an LLM-visible tool) and cached onto+ * `devices.workingDirs[].workspace`.+ *+ * Approves the root for the `lobe-file://` preview protocol (same as+ * `listProjectSkills`) so the user can later click through to the scanned+ * skills / instructions in the UI.+ */+ @IpcMethod()+ async initWorkspace(params: InitWorkspaceParams): Promise<InitWorkspaceResult> {+ const root = params.scope;+ const sources = ['.agents/skills', '.claude/skills'] as const;++ const seen = new Set<string>();+ const skills: ProjectSkillItem[] = [];+ for (const source of sources) {+ for (const skill of await this.scanSkillsInSource(root, source)) {+ if (seen.has(skill.name)) continue;+ seen.add(skill.name);+ skills.push(skill);+ }+ }+ skills.sort((a, b) => a.name.localeCompare(b.name));++ const instructions = await this.readWorkspaceInstructions(root);++ // Approve regardless of what was found β the run is now bound to this root,+ // so any later click-through to it should resolve through the preview+ // protocol even if the project carries neither skills nor instructions.+ await this.approveProjectRootForPreview(root);++ return { instructions, root, skills };+ }++ /**+ * Read the project-root agent instructions files. Collects every present+ * candidate (`AGENTS.md`, then `CLAUDE.md`) rather than first-match, since both+ * can coexist. Each body is capped so a pathologically large file can't bloat+ * the cached `workingDirs` payload or the injected system role.+ */+ private async readWorkspaceInstructions(+ root: string,+ ): Promise<InitWorkspaceResult['instructions']> {+ const MAX_INSTRUCTIONS_BYTES = 64 * 1024;+ const candidates = ['AGENTS.md', 'CLAUDE.md'] as const;++ const instructions: InitWorkspaceResult['instructions'] = [];+ for (const source of candidates) {+ try {+ const raw = await readFile(path.join(root, source), 'utf8');+ const content =+ raw.length > MAX_INSTRUCTIONS_BYTES ? raw.slice(0, MAX_INSTRUCTIONS_BYTES) : raw;+ instructions.push({ content, source });+ } catch {+ // File absent or unreadable; skip it.+ }+ }++ return instructions;+ }++ private async approveProjectRootForPreview(root: string) {+ try {+ await this.app.localFileProtocolManager.approveIndexedProjectRoot(root);+ } catch (error) {+ logger.error(`Failed to approve project preview root ${root}:`, error);+ }+ }+}diff --git a/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.tsnew file mode 100644index 00000000000..47b17df2fd4--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts@@ -0,0 +1,161 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type App } from '@/core/App';++import WorkspaceCtr from '../WorkspaceCtr';++const { ipcMainHandleMock } = vi.hoisted(() => ({+ ipcMainHandleMock: vi.fn(),+}));++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++vi.mock('electron', () => ({+ ipcMain: {+ handle: ipcMainHandleMock,+ },+}));++vi.mock('node:fs/promises', () => ({+ readFile: vi.fn(),+ readdir: vi.fn(),+}));++const mockLocalFileProtocolManager = {+ approveIndexedProjectRoot: vi.fn(),+};++const mockApp = {+ localFileProtocolManager: mockLocalFileProtocolManager,+} as unknown as App;++describe('WorkspaceCtr', () => {+ let workspaceCtr: WorkspaceCtr;+ let mockFsPromises: any;++ beforeEach(async () => {+ vi.clearAllMocks();+ mockFsPromises = await import('node:fs/promises');+ workspaceCtr = new WorkspaceCtr(mockApp);+ });++ const dirent = (name: string, kind: 'dir' | 'file') => ({+ isDirectory: () => kind === 'dir',+ isFile: () => kind === 'file',+ isSymbolicLink: () => false,+ name,+ });++ const frontmatter = (name: string, description: string) =>+ `---\nname: ${name}\ndescription: ${description}\n---\nbody`;++ describe('initWorkspace', () => {+ it('merges skills from both sources and reads instruction files', async () => {+ vi.mocked(mockFsPromises.readdir).mockImplementation(async (dir: string) => {+ if (dir === '/proj/.agents/skills') return [dirent('spa-routes', 'dir')];+ if (dir === '/proj/.agents/skills/spa-routes') return [dirent('SKILL.md', 'file')];+ if (dir === '/proj/.claude/skills') return [dirent('reviewer', 'dir')];+ if (dir === '/proj/.claude/skills/reviewer') return [dirent('SKILL.md', 'file')];+ throw new Error('ENOENT');+ });+ vi.mocked(mockFsPromises.readFile).mockImplementation(async (file: string) => {+ if (file === '/proj/.agents/skills/spa-routes/SKILL.md')+ return frontmatter('spa-routes', 'SPA routing');+ if (file === '/proj/.claude/skills/reviewer/SKILL.md')+ return frontmatter('reviewer', 'Code review');+ if (file === '/proj/AGENTS.md') return '# Agents';+ if (file === '/proj/CLAUDE.md') return '# Claude';+ throw new Error('ENOENT');+ });++ const result = await workspaceCtr.initWorkspace({ scope: '/proj' });++ expect(result.skills.map((s) => s.name)).toEqual(['reviewer', 'spa-routes']);+ expect(result.instructions).toEqual([+ { content: '# Agents', source: 'AGENTS.md' },+ { content: '# Claude', source: 'CLAUDE.md' },+ ]);+ // Approves the scanned root for the lobe-file:// preview protocol.+ expect(mockLocalFileProtocolManager.approveIndexedProjectRoot).toHaveBeenCalledWith('/proj');+ });++ it('dedupes skills by name with .agents/skills winning', async () => {+ vi.mocked(mockFsPromises.readdir).mockImplementation(async (dir: string) => {+ if (dir === '/proj/.agents/skills') return [dirent('shared', 'dir')];+ if (dir === '/proj/.claude/skills') return [dirent('shared', 'dir')];+ if (dir.endsWith('/shared')) return [dirent('SKILL.md', 'file')];+ throw new Error('ENOENT');+ });+ vi.mocked(mockFsPromises.readFile).mockImplementation(async (file: string) => {+ if (file === '/proj/.agents/skills/shared/SKILL.md')+ return frontmatter('shared', 'from agents');+ if (file === '/proj/.claude/skills/shared/SKILL.md')+ return frontmatter('shared', 'from claude');+ throw new Error('ENOENT');+ });++ const result = await workspaceCtr.initWorkspace({ scope: '/proj' });++ expect(result.skills).toHaveLength(1);+ expect(result.skills[0]).toMatchObject({+ description: 'from agents',+ path: '/proj/.agents/skills/shared/SKILL.md',+ });+ });++ it('caps instruction file content', async () => {+ vi.mocked(mockFsPromises.readdir).mockRejectedValue(new Error('ENOENT'));+ const huge = 'x'.repeat(100 * 1024);+ vi.mocked(mockFsPromises.readFile).mockImplementation(async (file: string) => {+ if (file === '/proj/AGENTS.md') return huge;+ throw new Error('ENOENT');+ });++ const result = await workspaceCtr.initWorkspace({ scope: '/proj' });++ expect(result.skills).toEqual([]);+ expect(result.instructions).toHaveLength(1);+ expect(result.instructions[0].content.length).toBe(64 * 1024);+ });++ it('returns empty skills and instructions when nothing is present', async () => {+ vi.mocked(mockFsPromises.readdir).mockRejectedValue(new Error('ENOENT'));+ vi.mocked(mockFsPromises.readFile).mockRejectedValue(new Error('ENOENT'));++ const result = await workspaceCtr.initWorkspace({ scope: '/proj' });++ expect(result).toEqual({ instructions: [], root: '/proj', skills: [] });+ });+ });++ describe('listProjectSkills', () => {+ it('returns the first source with skills (.agents/skills wins) and ignores .claude', async () => {+ vi.mocked(mockFsPromises.readdir).mockImplementation(async (dir: string) => {+ if (dir === '/proj/.agents/skills') return [dirent('alpha', 'dir')];+ if (dir === '/proj/.agents/skills/alpha') return [dirent('SKILL.md', 'file')];+ throw new Error('ENOENT');+ });+ vi.mocked(mockFsPromises.readFile).mockResolvedValue(frontmatter('alpha', 'A'));++ const result = await workspaceCtr.listProjectSkills({ scope: '/proj' });++ expect(result.source).toBe('.agents/skills');+ expect(result.skills.map((s) => s.name)).toEqual(['alpha']);+ });++ it('returns empty + null source when no skills exist', async () => {+ vi.mocked(mockFsPromises.readdir).mockRejectedValue(new Error('ENOENT'));++ const result = await workspaceCtr.listProjectSkills({ scope: '/proj' });++ expect(result).toEqual({ root: '/proj', skills: [], source: null });+ });+ });+});diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.tsindex b32ba30e620..8c4428a09d5 100644--- a/apps/desktop/src/main/controllers/registry.ts+++ b/apps/desktop/src/main/controllers/registry.ts@@ -24,6 +24,7 @@ import SystemController from './SystemCtr';import ToolDetectorCtr from './ToolDetectorCtr';import TrayMenuCtr from './TrayMenuCtr';import UpdaterCtr from './UpdaterCtr';+import WorkspaceCtr from './WorkspaceCtr';export const controllerIpcConstructors = [HeterogeneousAgentCtr,@@ -50,6 +51,7 @@ export const controllerIpcConstructors = [ToolDetectorCtr,TrayMenuCtr,UpdaterCtr,+ WorkspaceCtr,] as const satisfies readonly IpcServiceConstructor[];type DesktopControllerIpcConstructors = typeof controllerIpcConstructors;diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 2be53004499..28d6abadb21 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -5,6 +5,7 @@ import type {AgentRunRequestMessage,GatewayMcpStdioParams,MessageApiRequestMessage,+ RpcRequestMessage,SystemInfoRequestMessage,ToolCallRequestMessage,ToolCallResponseMessage,@@ -83,6 +84,15 @@ interface AgentRunHandler {(request: AgentRunRequestMessage): Promise<{ reason?: string; status: 'accepted' | 'rejected' }>;}+/**+ * Handler for generic server-internal device RPCs (e.g. workspace-init scans).+ * Dispatches by `method` name and returns the JSON-serializable result. Distinct+ * from {@link ToolCallHandler} β RPCs are never exposed to the agent.+ */+interface RpcHandler {+ (method: string, params: unknown): Promise<unknown>;+}+interface DeviceRegistrar {(info: {deviceId: string;@@ -112,6 +122,7 @@ export default class GatewayConnectionService extends ServiceModule {private mcpCallHandler: McpCallHandler | null = null;private messageApiHandler: MessageApiHandler | null = null;private agentRunHandler: AgentRunHandler | null = null;+ private rpcHandler: RpcHandler | null = null;private deviceRegistrar: DeviceRegistrar | null = null;// βββ Configuration βββ@@ -149,6 +160,15 @@ export default class GatewayConnectionService extends ServiceModule {this.messageApiHandler = handler;}+ /**+ * Set the generic device-RPC handler (routes server-internal method calls such+ * as workspace-init to the relevant controller). Distinct from the tool-call+ * handler β these are never surfaced to the agent.+ */+ setRpcHandler(handler: RpcHandler) {+ this.rpcHandler = handler;+ }+setAgentRunHandler(handler: AgentRunHandler) {this.agentRunHandler = handler;}@@ -337,6 +357,10 @@ export default class GatewayConnectionService extends ServiceModule {this.handleSystemInfoRequest(client, request);});+ client.on('rpc_request', (request) => {+ this.handleRpcRequest(client, request);+ });+client.on('agent_run_request', (request) => {this.handleAgentRunRequest(client, request);});@@ -402,6 +426,32 @@ export default class GatewayConnectionService extends ServiceModule {});}+ // βββ Generic Device RPC βββ++ private async handleRpcRequest(client: GatewayClient, request: RpcRequestMessage) {+ const { method, params, requestId } = request;+ logger.info(`Received rpc_request: method=${method}, requestId=${requestId}`);++ if (!this.rpcHandler) {+ client.sendRpcResponse({+ requestId,+ result: { error: 'No RPC handler registered', success: false },+ });+ return;+ }++ try {+ const data = await this.rpcHandler(method, params);+ client.sendRpcResponse({ requestId, result: { data, success: true } });+ } catch (error) {+ logger.error(`rpc_request method=${method} failed:`, serializeWireError(error));+ client.sendRpcResponse({+ requestId,+ result: { error: serializeWireError(error), success: false },+ });+ }+ }+// βββ Agent Run βββprivate handleAgentRunRequest = async (diff --git a/packages/database/src/schemas/device.ts b/packages/database/src/schemas/device.tsindex aaf802ed0cb..3ac733c260a 100644--- a/packages/database/src/schemas/device.ts+++ b/packages/database/src/schemas/device.ts@@ -1,3 +1,4 @@+import type { WorkspaceInitResult } from '@lobechat/types';import { index, jsonb, pgTable, text, uniqueIndex, uuid, varchar } from 'drizzle-orm/pg-core';import { timestamps, timestamptz } from './_helpers';@@ -13,6 +14,18 @@ import { workspaces } from './workspace';export interface WorkingDirEntry {path: string;repoType?: 'git' | 'github';+ /**+ * Cached "workspace init" scan of this directory (AGENTS.md + project skills).+ * Populated server-side at run start via `deviceGateway.initWorkspace` and+ * reused within the TTL gated by `workspaceScannedAt`. Also read directly by+ * the web UI to render the project's skills / instructions.+ */+ workspace?: WorkspaceInitResult;+ /**+ * Epoch ms when `workspace` was last scanned. Hoisted to the top level (out of+ * `workspace`) so freshness can be checked without deserializing the payload.+ */+ workspaceScannedAt?: number;}/**diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.tsindex fdfaf21e4e5..7fa2ba27ef5 100644--- a/packages/device-gateway-client/src/client.test.ts+++ b/packages/device-gateway-client/src/client.test.ts@@ -260,6 +260,21 @@ describe('GatewayClient', () => {expect(sysInfoCb).toHaveBeenCalledWith(msg);});+ it('should handle rpc_request', () => {+ const rpcCb = vi.fn();+ client.on('rpc_request', rpcCb);++ const msg = {+ method: 'initWorkspace',+ params: { scope: '/proj' },+ requestId: 'req-rpc',+ type: 'rpc_request',+ };+ handler(JSON.stringify(msg));++ expect(rpcCb).toHaveBeenCalledWith(msg);+ });+it('should handle auth_expired', () => {const expiredCb = vi.fn();client.on('auth_expired', expiredCb);@@ -365,6 +380,27 @@ describe('GatewayClient', () => {});});+ describe('sendRpcResponse', () => {+ it('should send rpc response message', async () => {+ client.connect();+ await vi.advanceTimersByTimeAsync(1);++ const ws = (client as any).ws;+ client.sendRpcResponse({+ requestId: 'req-rpc',+ result: { data: { skills: [] }, success: true },+ });++ expect(ws.send).toHaveBeenCalledWith(+ JSON.stringify({+ requestId: 'req-rpc',+ result: { data: { skills: [] }, success: true },+ type: 'rpc_response',+ }),+ );+ });+ });+describe('sendMessage when ws not open', () => {it('should not send when ws is null', () => {// Not connected, ws is nulldiff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.tsindex 83157433f0c..f9802c5057b 100644--- a/packages/device-gateway-client/src/client.ts+++ b/packages/device-gateway-client/src/client.ts@@ -12,6 +12,8 @@ import type {GatewayClientEvents,MessageApiRequestMessage,MessageApiResponseMessage,+ RpcRequestMessage,+ RpcResponseMessage,ServerMessage,SystemInfoRequestMessage,SystemInfoResponseMessage,@@ -184,6 +186,13 @@ export class GatewayClient extends EventEmitter {});}+ sendRpcResponse(response: Omit<RpcResponseMessage, 'type'>): void {+ this.sendMessage({+ ...response,+ type: 'rpc_response',+ });+ }+sendAgentRunAck(response: Omit<AgentRunAckMessage, 'type'>): void {this.sendMessage({...response,@@ -302,6 +311,11 @@ export class GatewayClient extends EventEmitter {break;}+ case 'rpc_request': {+ this.emit('rpc_request', message as RpcRequestMessage);+ break;+ }+case 'agent_run_request': {this.emit('agent_run_request', message as AgentRunRequestMessage);break;diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.tsindex f5ef6906f82..6d5e59f7669 100644--- a/packages/device-gateway-client/src/http.test.ts+++ b/packages/device-gateway-client/src/http.test.ts@@ -482,4 +482,51 @@ describe('GatewayHttpClient', () => {expect(result.success).toBe(false);});});++ describe('invokeRpc', () => {+ it('forwards method + params and returns data on success', async () => {+ const data = { instructions: [], skills: [] };+ mockFetch({+ json: vi.fn().mockResolvedValue({ data, success: true }),+ ok: true,+ });++ const result = await client.invokeRpc(+ { deviceId: 'device-1', userId: 'user-1' },+ { method: 'initWorkspace', params: { scope: '/proj' } },+ );++ expect(result).toEqual({ data, error: undefined, success: true });+ const [url, init] = vi.mocked(fetch).mock.calls[0];+ expect(url).toBe('https://gateway.test.com/api/device/rpc');+ expect(JSON.parse((init as any).body)).toEqual({+ deviceId: 'device-1',+ method: 'initWorkspace',+ params: { scope: '/proj' },+ userId: 'user-1',+ });+ });++ it('returns failure on non-ok response', async () => {+ mockFetch({ ok: false, status: 503, text: vi.fn().mockResolvedValue('offline') });++ const result = await client.invokeRpc(+ { deviceId: 'device-1', userId: 'user-1' },+ { method: 'initWorkspace' },+ );++ expect(result).toEqual({ error: 'offline', success: false });+ });++ it('defaults success to false when the field is missing', async () => {+ mockFetch({ json: vi.fn().mockResolvedValue({ data: {} }), ok: true });++ const result = await client.invokeRpc(+ { deviceId: 'device-1', userId: 'user-1' },+ { method: 'initWorkspace' },+ );++ expect(result.success).toBe(false);+ });+ });});diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex a4fdb1e11bc..1b8d08c288e 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -26,6 +26,12 @@ export interface DeviceMessageApiResult {success: boolean;}+export interface DeviceRpcResult<T = unknown> {+ data?: T;+ error?: string;+ success: boolean;+}+export interface GatewayHttpClientOptions {gatewayUrl: string;serviceToken: string;@@ -194,6 +200,42 @@ export class GatewayHttpClient {return { success: true };}+ /**+ * Invoke a named device-side method over the generic RPC relay. Server-only β+ * the gateway forwards `{ method, params }` opaquely to the device's RPC+ * dispatcher and correlates the response by `requestId`, so new methods need+ * no per-method gateway route. Distinct from {@link executeToolCall}, which is+ * the LLM-facing tool channel.+ */+ async invokeRpc<T = unknown>(+ params: { deviceId?: string; timeout?: number; userId: string },+ rpc: { method: string; params?: unknown },+ ): Promise<DeviceRpcResult<T>> {+ const timeout =+ typeof params.timeout === 'number' && Number.isFinite(params.timeout)+ ? Math.max(Math.trunc(params.timeout), 0)+ : DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS;+ const res = await this.post(+ '/api/device/rpc',+ {+ deviceId: params.deviceId,+ method: rpc.method,+ params: rpc.params,+ timeout: params.timeout,+ userId: params.userId,+ },+ { timeout: timeout + HTTP_CALL_TIMEOUT_PADDING_MS },+ );++ if (!res.ok) {+ const text = await res.text().catch(() => '');+ return { error: text || `HTTP ${res.status}`, success: false };+ }++ const data = await res.json();+ return { data: data.data, error: data.error, success: data.success ?? false };+ }+async getDeviceSystemInfo(userId: string,deviceId: string,diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.tsindex 418f4d5d17d..73b373a0536 100644--- a/packages/device-gateway-client/src/index.ts+++ b/packages/device-gateway-client/src/index.ts@@ -2,6 +2,7 @@ export type { GatewayClientLogger, GatewayClientOptions } from './client';export { GatewayClient } from './client';export type {DeviceMessageApiResult,+ DeviceRpcResult,DeviceStatusResult,DeviceToolCallResult,GatewayHttpClientOptions,diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 1e2d98bde39..0333e20815b 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -162,6 +162,36 @@ export interface SystemInfoResponseMessage {type: 'system_info_response';}+// βββ Generic device RPC (server-internal method forwarding) βββ+// Unlike tool calls, RPCs are server-initiated operations the LLM never sees+// (e.g. workspace-init scans). The gateway relays them opaquely, correlating by+// `requestId`, so new device methods need no per-method gateway route β only a+// new entry in the device-side RPC dispatcher.++// Server β Client+export interface RpcRequestMessage {+ /** Name of the device-side method to invoke (e.g. `initWorkspace`). */+ method: string;+ /** JSON-serializable arguments for the method. */+ params?: unknown;+ requestId: string;+ /** Per-call timeout (ms) the gateway forwards; clients pass it through. */+ timeout?: number;+ type: 'rpc_request';+}++// Client β Server+export interface RpcResponseMessage {+ requestId: string;+ result: {+ /** Method return value, present when `success`. */+ data?: unknown;+ error?: string;+ success: boolean;+ };+ type: 'rpc_response';+}+/** Server β Client: request the desktop to spawn `lh hetero exec`. */export interface AgentRunRequestMessage {agentType: string;@@ -194,6 +224,7 @@ export type ClientMessage =| AuthMessage| HeartbeatMessage| MessageApiResponseMessage+ | RpcResponseMessage| SystemInfoResponseMessage| ToolCallResponseMessage;export type ServerMessage =@@ -203,6 +234,7 @@ export type ServerMessage =| AuthSuccessMessage| HeartbeatAckMessage| MessageApiRequestMessage+ | RpcRequestMessage| SystemInfoRequestMessage| ToolCallRequestMessage;@@ -225,6 +257,7 @@ export interface GatewayClientEvents {heartbeat_ack: () => void;message_api_request: (request: MessageApiRequestMessage) => void;reconnecting: (delay: number) => void;+ rpc_request: (request: RpcRequestMessage) => void;status_changed: (status: ConnectionStatus) => void;system_info_request: (request: SystemInfoRequestMessage) => void;tool_call_request: (request: ToolCallRequestMessage) => void;diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 27b0aca6a93..9244c24ff54 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -453,3 +453,32 @@ export interface ListProjectSkillsResult {/** Source directory actually scanned (after fallback resolution). */source: ProjectSkillItem['source'] | null;}++export interface InitWorkspaceParams {+ /** Working directory used to resolve the project root. */+ scope: string;+}++/**+ * Project-root agent instructions (`AGENTS.md` / `CLAUDE.md`) read in one shot+ * during workspace init. Full body is carried (capped) so the server can inject+ * it into the system role and the web UI can render it without a second call.+ * Mirrors `WorkspaceInstructions` in `@lobechat/types` (kept local β this is a+ * leaf package with no `@lobechat/types` dependency).+ */+export interface WorkspaceInstructionsItem {+ content: string;+ source: 'AGENTS.md' | 'CLAUDE.md';+}++/**+ * One-call workspace scan: project-root instructions + project skills (both+ * `.agents/skills` and `.claude/skills`, merged). Mirrors `WorkspaceInitResult`+ * in `@lobechat/types`; the server narrows `skills` to `ProjectSkillMeta` when+ * caching onto `devices.workingDirs[].workspace`.+ */+export interface InitWorkspaceResult {+ instructions: WorkspaceInstructionsItem[];+ root: string;+ skills: ProjectSkillItem[];+}diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex f9ff178edc6..f579b80e7f7 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -109,6 +109,43 @@ export interface ProjectSkillMeta {path: string;}+/**+ * A single project-root agent instructions file (`AGENTS.md` / `CLAUDE.md`) read+ * from the device filesystem during workspace init. Unlike skills (metadata+ * only), the full body is carried so it can be injected into the system role and+ * rendered in web without a second device round-trip. Carried as a list on+ * {@link WorkspaceInitResult} since multiple files can coexist (e.g. both+ * `AGENTS.md` and `CLAUDE.md`, or future nested files).+ */+export interface WorkspaceInstructions {+ /** Full file content (capped at read time, e.g. 64KB). */+ content: string;+ /** Source file the instructions were read from. */+ source: 'AGENTS.md' | 'CLAUDE.md';+}++/**+ * Result of scanning a bound project directory ("workspace init"): the agent+ * instructions file plus the project-level skills discovered under+ * `.agents/skills` + `.claude/skills`. Produced in a single device round-trip+ * (`deviceGateway.initWorkspace`) and cached on `devices.workingDirs[].workspace`+ * so subsequent runs within the TTL β and the web UI β reuse it without+ * re-scanning. Intentionally open to growth (env info, git status, β¦) as more+ * environment-preparation logic lands.+ *+ * The scanned root is not stored here β it is always the enclosing+ * `WorkingDirEntry.path`.+ */+export interface WorkspaceInitResult {+ /**+ * Project-root agent instructions files (`AGENTS.md` / `CLAUDE.md`). Empty+ * when none are present.+ */+ instructions: WorkspaceInstructions[];+ /** Project-level skills discovered under the project root (metadata only). */+ skills: ProjectSkillMeta[];+}+/*** Parameters for execAgent - execute a single Agent* Either agentId or slug must be provided@@ -142,13 +179,6 @@ export interface ExecAgentParams {* sub-tree back to its root.*/parentOperationId?: string;- /**- * Project-level skills discovered on the device filesystem- * (`.agents/skills` / `.claude/skills`) at request time. Surfaced in the- * `<available_skills>` list and loaded on demand via the readFile tool.- * Only applied when a device is active for this run.- */- projectSkills?: ProjectSkillMeta[];/** The user input/prompt */prompt: string;/** Override the agent's default provider */diff --git a/src/features/ChatInput/RuntimeConfig/deviceCwd.ts b/src/features/ChatInput/RuntimeConfig/deviceCwd.tsindex bae809865e7..54dc5185469 100644--- a/src/features/ChatInput/RuntimeConfig/deviceCwd.ts+++ b/src/features/ChatInput/RuntimeConfig/deviceCwd.ts@@ -1,3 +1,5 @@+import type { WorkspaceInitResult } from '@lobechat/types';+/** Max number of working directories persisted per device. Matches the* `workingDirs` cap enforced by the `device.updateDevice` tRPC input. */export const WORKING_DIRS_MAX = 20;@@ -10,6 +12,10 @@ export const WORKING_DIRS_MAX = 20;export interface WorkingDirEntry {path: string;repoType?: 'git' | 'github';+ /** Cached "workspace init" scan (AGENTS.md + project skills). See DB `WorkingDirEntry`. */+ workspace?: WorkspaceInitResult;+ /** Epoch ms of the last `workspace` scan (top-level for cheap freshness checks). */+ workspaceScannedAt?: number;}/**diff --git a/src/server/routers/lambda/__tests__/deviceWorkingDirs.test.ts b/src/server/routers/lambda/__tests__/deviceWorkingDirs.test.tsnew file mode 100644index 00000000000..bde931f4fa1--- /dev/null+++ b/src/server/routers/lambda/__tests__/deviceWorkingDirs.test.ts@@ -0,0 +1,55 @@+import type { WorkingDirEntry } from '@lobechat/database/schemas';+import type { WorkspaceInitResult } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { preserveWorkspaceCache } from '../deviceWorkingDirs';++const workspace: WorkspaceInitResult = {+ instructions: [{ content: '# Rules', source: 'AGENTS.md' }],+ skills: [+ { description: 'spa', name: 'spa-routes', path: '/proj/.agents/skills/spa-routes/SKILL.md' },+ ],+};++describe('preserveWorkspaceCache', () => {+ it('re-attaches workspace + workspaceScannedAt by path onto stripped entries', () => {+ const incoming: WorkingDirEntry[] = [{ path: '/proj', repoType: 'git' }, { path: '/other' }];+ const stored: WorkingDirEntry[] = [+ { path: '/proj', repoType: 'git', workspace, workspaceScannedAt: 123 },+ { path: '/other' },+ ];++ expect(preserveWorkspaceCache(incoming, stored)).toEqual([+ { path: '/proj', repoType: 'git', workspace, workspaceScannedAt: 123 },+ { path: '/other' },+ ]);+ });++ it('drops the cache for a path no longer present (dir removed)', () => {+ const stored: WorkingDirEntry[] = [{ path: '/proj', workspace, workspaceScannedAt: 123 }];++ const result = preserveWorkspaceCache([{ path: '/other' }], stored);++ expect(result).toEqual([{ path: '/other' }]);+ });++ it('leaves brand-new paths without a cache', () => {+ const result = preserveWorkspaceCache([{ path: '/fresh' }], []);+ expect(result).toEqual([{ path: '/fresh' }]);+ });++ it('returns the incoming list unchanged when nothing is cached', () => {+ const incoming: WorkingDirEntry[] = [{ path: '/a' }, { path: '/b', repoType: 'github' }];+ expect(preserveWorkspaceCache(incoming, [{ path: '/a' }])).toEqual(incoming);+ });++ it('does not mutate the inputs', () => {+ const incoming: WorkingDirEntry[] = [{ path: '/proj' }];+ const stored: WorkingDirEntry[] = [{ path: '/proj', workspace, workspaceScannedAt: 1 }];+ const incomingSnapshot = structuredClone(incoming);++ preserveWorkspaceCache(incoming, stored);++ expect(incoming).toEqual(incomingSnapshot);+ });+});diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex fb6678bbc32..1d39902a13e 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -160,20 +160,6 @@ const ExecAgentSchema = zfileIds: z.array(z.string()).optional(),/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId: z.string().optional(),- /**- * Project-level skills discovered on the device filesystem- * (`.agents/skills` / `.claude/skills`) by the client at request time.- * Surfaced in `<available_skills>` and loaded on demand via readFile.- */- projectSkills: z- .array(- z.object({- description: z.string().optional(),- name: z.string(),- path: z.string(),- }),- )- .optional(),/** The user input/prompt */prompt: z.string(),/**@@ -647,7 +633,6 @@ export const aiAgentRouter = router({existingMessageIds = [],fileIds,parentMessageId,- projectSkills,resumeApproval,trigger,userInterventionConfig,@@ -664,7 +649,6 @@ export const aiAgentRouter = router({existingMessageIds,fileIds,parentMessageId,- projectSkills,prompt,// When parentMessageId is provided, this is a regeneration/continue or a// human-approval resume β either way, skip user message creation.diff --git a/src/server/routers/lambda/device.ts b/src/server/routers/lambda/device.tsindex 119606a64be..30dd19d88d6 100644--- a/src/server/routers/lambda/device.ts+++ b/src/server/routers/lambda/device.ts@@ -7,6 +7,8 @@ import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { deviceGateway } from '@/server/services/toolExecution/deviceGateway';+import { preserveWorkspaceCache } from './deviceWorkingDirs';+// Derive the zod enum from the canonical config so new platforms are// automatically covered without touching this file.const remotePlatformEnum = z.enum(@@ -242,8 +244,19 @@ export const deviceRouter = router({}),).mutation(async ({ ctx, input }) => {- const { deviceId, ...value } = input;- await ctx.deviceModel.update(deviceId, value);+ const { deviceId, workingDirs, ...value } = input;++ // The workspace-init cache (workspace / workspaceScannedAt) is stripped+ // from `workingDirs` by the strict schema above, so re-attach it from the+ // stored row by path β otherwise an ordinary cwd save wipes the cache.+ const nextWorkingDirs = workingDirs+ ? preserveWorkspaceCache(+ workingDirs,+ (await ctx.deviceModel.findByDeviceId(deviceId))?.workingDirs ?? [],+ )+ : undefined;++ await ctx.deviceModel.update(deviceId, { ...value, workingDirs: nextWorkingDirs });return { success: true };}),});diff --git a/src/server/routers/lambda/deviceWorkingDirs.ts b/src/server/routers/lambda/deviceWorkingDirs.tsnew file mode 100644index 00000000000..cf2e34be183--- /dev/null+++ b/src/server/routers/lambda/deviceWorkingDirs.ts@@ -0,0 +1,31 @@+import type { WorkingDirEntry } from '@lobechat/database/schemas';++/**+ * Re-attach the server-owned workspace-init cache (`workspace` /+ * `workspaceScannedAt`) onto a client-supplied `workingDirs` list, matched by+ * `path`.+ *+ * The `device.updateDevice` input only validates `{ path, repoType }` and zod+ * strips everything else, so a client cwd save would otherwise overwrite the+ * JSONB column with cache-less entries β wiping the scan written by+ * `resolveWorkspaceInit` and forcing every later run to rescan. The cache is+ * server-produced (the client never authors it), so we restore it here rather+ * than trusting the client to round-trip it.+ *+ * Entries dropped from `incoming` (e.g. the user removed a dir) lose their cache+ * by design; brand-new paths simply have none yet.+ */+export const preserveWorkspaceCache = (+ incoming: WorkingDirEntry[],+ stored: readonly WorkingDirEntry[] = [],+): WorkingDirEntry[] => {+ const cachedByPath = new Map(stored.filter((dir) => dir.workspace).map((dir) => [dir.path, dir]));+ if (cachedByPath.size === 0) return incoming;++ return incoming.map((entry) => {+ const cached = cachedByPath.get(entry.path);+ return cached+ ? { ...entry, workspace: cached.workspace, workspaceScannedAt: cached.workspaceScannedAt }+ : entry;+ });+};diff --git a/src/server/services/aiAgent/__tests__/workspaceInitCache.test.ts b/src/server/services/aiAgent/__tests__/workspaceInitCache.test.tsnew file mode 100644index 00000000000..1b921c40eb3--- /dev/null+++ b/src/server/services/aiAgent/__tests__/workspaceInitCache.test.ts@@ -0,0 +1,103 @@+import type { WorkingDirEntry } from '@lobechat/database/schemas';+import type { WorkspaceInitResult } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ isWorkspaceCacheFresh,+ upsertWorkspaceScan,+ WORKSPACE_INIT_MAX_DIRS,+ WORKSPACE_INIT_TTL_MS,+} from '../workspaceInitCache';++const workspace: WorkspaceInitResult = {+ instructions: [{ content: '# Rules', source: 'AGENTS.md' }],+ skills: [+ { description: 'spa', name: 'spa-routes', path: '/proj/.agents/skills/spa-routes/SKILL.md' },+ ],+};++describe('isWorkspaceCacheFresh', () => {+ const now = 1_000_000_000_000;++ it('returns false for undefined / no workspace', () => {+ expect(isWorkspaceCacheFresh(undefined, now)).toBe(false);+ expect(isWorkspaceCacheFresh({ path: '/proj' }, now)).toBe(false);+ });++ it('returns false when scannedAt is missing even if workspace is present', () => {+ expect(isWorkspaceCacheFresh({ path: '/proj', workspace }, now)).toBe(false);+ });++ it('returns true within the TTL window', () => {+ const entry: WorkingDirEntry = {+ path: '/proj',+ workspace,+ workspaceScannedAt: now - (WORKSPACE_INIT_TTL_MS - 1),+ };+ expect(isWorkspaceCacheFresh(entry, now)).toBe(true);+ });++ it('returns false at / past the TTL boundary', () => {+ const atBoundary: WorkingDirEntry = {+ path: '/proj',+ workspace,+ workspaceScannedAt: now - WORKSPACE_INIT_TTL_MS,+ };+ const expired: WorkingDirEntry = {+ path: '/proj',+ workspace,+ workspaceScannedAt: now - (WORKSPACE_INIT_TTL_MS + 1),+ };+ expect(isWorkspaceCacheFresh(atBoundary, now)).toBe(false);+ expect(isWorkspaceCacheFresh(expired, now)).toBe(false);+ });+});++describe('upsertWorkspaceScan', () => {+ const scannedAt = 1_700_000_000_000;++ it('updates the matching entry in place, preserving repoType and order', () => {+ const dirs: WorkingDirEntry[] = [+ { path: '/a', repoType: 'git' },+ { path: '/proj', repoType: 'github' },+ ];++ const result = upsertWorkspaceScan(dirs, '/proj', workspace, scannedAt);++ expect(result).toEqual([+ { path: '/a', repoType: 'git' },+ { path: '/proj', repoType: 'github', workspace, workspaceScannedAt: scannedAt },+ ]);+ });++ it('prepends a new most-recent-first entry when the cwd is unrecorded', () => {+ const dirs: WorkingDirEntry[] = [{ path: '/a' }];++ const result = upsertWorkspaceScan(dirs, '/proj', workspace, scannedAt);++ expect(result[0]).toEqual({ path: '/proj', workspace, workspaceScannedAt: scannedAt });+ expect(result[1]).toEqual({ path: '/a' });+ });++ it('caps the list at WORKSPACE_INIT_MAX_DIRS when prepending', () => {+ const dirs: WorkingDirEntry[] = Array.from({ length: WORKSPACE_INIT_MAX_DIRS }, (_, i) => ({+ path: `/dir-${i}`,+ }));++ const result = upsertWorkspaceScan(dirs, '/proj', workspace, scannedAt);++ expect(result).toHaveLength(WORKSPACE_INIT_MAX_DIRS);+ expect(result[0].path).toBe('/proj');+ // The oldest (last) entry is dropped.+ expect(result.some((d) => d.path === `/dir-${WORKSPACE_INIT_MAX_DIRS - 1}`)).toBe(false);+ });++ it('does not mutate the input array', () => {+ const dirs: WorkingDirEntry[] = [{ path: '/proj' }];+ const snapshot = structuredClone(dirs);++ upsertWorkspaceScan(dirs, '/proj', workspace, scannedAt);++ expect(dirs).toEqual(snapshot);+ });+});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex d790b799cd9..8fc27dcc343 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -37,6 +37,7 @@ import type {ExecSubAgentTaskResult,MessagePluginItem,UserInterventionConfig,+ WorkspaceInitResult,} from '@lobechat/types';import { RequestTrigger, ThreadStatus, ThreadType } from '@lobechat/types';import { nanoid } from '@lobechat/utils';@@ -92,6 +93,7 @@ import { markdownToTxt } from '@/utils/markdownToTxt';import { resolveDeviceAccessPolicy } from './deviceAccessPolicy';import { buildAllowedBuiltinTools, isDeviceToolIdentifier } from './deviceToolRegistry';import { ingestAttachment } from './ingestAttachment';+import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCache';const log = debug('lobe-server:ai-agent-service');@@ -295,6 +297,68 @@ export class AiAgentService {return task?.id;}+ /**+ * Resolve the "workspace init" scan (project skills + AGENTS.md) for a run+ * bound to a device's project directory. Reads the cache on+ * `devices.workingDirs[].workspace`, reusing it within {@link WORKSPACE_INIT_TTL_MS};+ * otherwise re-scans the device in one round-trip and writes the result back.+ *+ * Gated on `activeDeviceId` β without an online device there is nothing to+ * scan and no current working directory to key the cache on. The web UI reads+ * the same persisted `workingDirs` directly, so it can still render a last-known+ * scan even while the device is offline.+ */+ private async resolveWorkspaceInit(params: {+ activeDeviceId: string | undefined;+ topicId: string;+ }): Promise<WorkspaceInitResult> {+ const empty: WorkspaceInitResult = { instructions: [], skills: [] };+ const { activeDeviceId, topicId } = params;+ if (!activeDeviceId) return empty;++ try {+ const deviceModel = new DeviceModel(this.db, this.userId);+ const device = await deviceModel.findByDeviceId(activeDeviceId);+ if (!device) return empty;++ // The bound project root: a topic-pinned cwd wins, else the device default+ // (mirrors the hetero dispatch resolution). This is the directory we scan.+ const topic = await this.topicModel.findById(topicId);+ const boundCwd = topic?.metadata?.workingDirectory || device.defaultCwd || undefined;+ if (!boundCwd) return empty;++ const workingDirs = device.workingDirs ?? [];+ const cached = workingDirs.find((dir) => dir.path === boundCwd);++ if (isWorkspaceCacheFresh(cached, Date.now()) && cached?.workspace) {+ log('execAgent: reusing cached workspace init for %s', boundCwd);+ return cached.workspace;+ }++ const scanned = await deviceGateway.initWorkspace(this.userId, activeDeviceId, boundCwd);+ if (!scanned) {+ // Scan failed (offline mid-run / parse error). Fall back to a stale+ // cache rather than dropping the project's skills + instructions.+ if (cached?.workspace) {+ log('execAgent: workspace init scan failed, using stale cache for %s', boundCwd);+ return cached.workspace;+ }+ return empty;+ }++ // Persist the fresh scan back onto `workingDirs` (update in place or prepend+ // a new MRU entry), keeping the JSONB payload bounded.+ const updated = upsertWorkspaceScan(workingDirs, boundCwd, scanned, Date.now());+ await deviceModel.update(activeDeviceId, { workingDirs: updated });+ log('execAgent: scanned and cached workspace init for %s', boundCwd);++ return scanned;+ } catch (error) {+ log('execAgent: resolveWorkspaceInit failed: %O', error);+ return empty;+ }+ }+/*** Execute agent with just a prompt*@@ -2211,37 +2275,53 @@ export class AiAgentService {name: skill.name,}));- // Project skills are filesystem SKILL.md discovered on the device. Their- // presence in `params.projectSkills` is itself proof that a client just- // scanned the working directory, so we surface them in- // `<available_skills>` unconditionally β decoupled from `activeDeviceId`- // (a routing decision for `LocalSystemManifest` injection that can- // legitimately be `undefined` for multi-device-no-bind or- // device-just-went-offline cases). Whether SKILL.md can actually be read- // at activation time is re-gated at the executor in- // `serverRuntimes/skills.ts` β there `deviceFileAccess` is only built- // when `activeDeviceId` resolves, and a missing reader naturally fails- // the `activateSkill` call rather than silently hiding the option.- // Only `location` (absolute SKILL.md path) flows through; the directory- // tree is enumerated lazily at activation time via- // `local-system.listFiles`, keeping the op-param payload small.- const projectMetas =- params.projectSkills?.map((s) => ({- description: s.description ?? '',- identifier: `project:${s.name}`,- location: s.path,- name: s.name,- source: 'project' as const,- })) ?? [];-- if (params.projectSkills?.length) {+ // Project skills + the root AGENTS.md are discovered server-side by+ // scanning the device's bound project directory ("workspace init"), cached+ // on `devices.workingDirs` and reused within the TTL. Skills surface in+ // `<available_skills>` (metadata only β SKILL.md bodies are read lazily at+ // activation via `local-system` readFile, which `serverRuntimes/skills.ts`+ // re-gates on `activeDeviceId`). Only `location` (the absolute SKILL.md+ // path) flows through; the directory tree is enumerated lazily, keeping the+ // op-param payload small.+ const workspaceInit = await this.resolveWorkspaceInit({ activeDeviceId, topicId });++ const projectMetas = workspaceInit.skills.map((s) => ({+ description: s.description ?? '',+ identifier: `project:${s.name}`,+ location: s.path,+ name: s.name,+ source: 'project' as const,+ }));++ if (projectMetas.length) {log(- 'execAgent: projectSkills merged: %d (activeDeviceId=%s)',+ 'execAgent: workspace skills merged: %d (activeDeviceId=%s)',projectMetas.length,activeDeviceId ?? 'none',);}+ // Inject the project-root agent instructions (AGENTS.md / CLAUDE.md) as+ // trailing blocks on the system role β after the agent's persona and any+ // page/task/additional instructions. `agentConfig` is read by+ // `createOperation` below, so appending here still reaches the LLM.+ if (workspaceInit.instructions.length) {+ const block = workspaceInit.instructions+ .map(+ ({ content, source }) =>+ `<project_instructions source="${source}">\n${content}\n</project_instructions>`,+ )+ .join('\n\n');+ agentConfig.systemRole = agentConfig.systemRole+ ? `${agentConfig.systemRole}\n\n${block}`+ : block;+ log(+ 'execAgent: injected %d project instruction file(s): %s',+ workspaceInit.instructions.length,+ workspaceInit.instructions.map((i) => i.source).join(', '),+ );+ }+// Precedence on name collision: project > db > agent-skills > builtin.// Agent-skills carry the `agent-skills:` prefix in their `name`, so they// can only collide with each other β but we still dedupe by name to keepdiff --git a/src/server/services/aiAgent/workspaceInitCache.ts b/src/server/services/aiAgent/workspaceInitCache.tsnew file mode 100644index 00000000000..d947c9377ae--- /dev/null+++ b/src/server/services/aiAgent/workspaceInitCache.ts@@ -0,0 +1,45 @@+import type { WorkingDirEntry } from '@lobechat/database/schemas';+import type { WorkspaceInitResult } from '@lobechat/types';++/** Reuse a cached workspace-init scan for this long before re-scanning the device. */+export const WORKSPACE_INIT_TTL_MS = 60 * 60 * 1000;++/**+ * Cap on `workingDirs` entries when prepending a newly-scanned bound cwd. Matches+ * the client-side `WORKING_DIRS_MAX`; the client owns dedupe/ordering, so here we+ * only guard the length when inserting a previously-unrecorded directory.+ */+export const WORKSPACE_INIT_MAX_DIRS = 20;++/**+ * True when a cached workspace scan exists and is still within its TTL β i.e. it+ * can be reused without a fresh device round-trip.+ */+export const isWorkspaceCacheFresh = (entry: WorkingDirEntry | undefined, now: number): boolean =>+ !!entry?.workspace &&+ typeof entry.workspaceScannedAt === 'number' &&+ now - entry.workspaceScannedAt < WORKSPACE_INIT_TTL_MS;++/**+ * Merge a fresh scan into a device's `workingDirs`: update the matching entry in+ * place (preserving its `repoType`), or prepend a new most-recent-first entry+ * when the bound cwd wasn't recorded yet β mirroring the client's+ * `nextWorkingDirs` MRU convention, capped at {@link WORKSPACE_INIT_MAX_DIRS}.+ */+export const upsertWorkspaceScan = (+ workingDirs: readonly WorkingDirEntry[],+ path: string,+ workspace: WorkspaceInitResult,+ scannedAt: number,+): WorkingDirEntry[] => {+ if (workingDirs.some((dir) => dir.path === path)) {+ return workingDirs.map((dir) =>+ dir.path === path ? { ...dir, workspace, workspaceScannedAt: scannedAt } : dir,+ );+ }++ return [{ path, workspace, workspaceScannedAt: scannedAt }, ...workingDirs].slice(+ 0,+ WORKSPACE_INIT_MAX_DIRS,+ );+};diff --git a/src/server/services/toolExecution/__tests__/deviceGateway.test.ts b/src/server/services/toolExecution/__tests__/deviceGateway.test.tsindex 859b8db63ff..8e280abd937 100644--- a/src/server/services/toolExecution/__tests__/deviceGateway.test.ts+++ b/src/server/services/toolExecution/__tests__/deviceGateway.test.ts@@ -13,6 +13,7 @@ const mockClient = vi.hoisted(() => ({executeMessageApi: vi.fn(),executeToolCall: vi.fn(),getDeviceSystemInfo: vi.fn(),+ invokeRpc: vi.fn(),queryDeviceList: vi.fn(),queryDeviceStatus: vi.fn(),}));@@ -420,6 +421,116 @@ describe('DeviceGateway', () => {});});+ describe('initWorkspace', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('should return undefined when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace('user-1', 'dev-1', '/proj');+ expect(result).toBeUndefined();+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('narrows device skills to metadata and passes instructions through', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: {+ instructions: [{ content: '# Rules', source: 'AGENTS.md' }],+ // Device returns rich ProjectSkillItems; only name/description/path survive.+ skills: [+ {+ description: 'spa',+ fileCount: 3,+ files: ['SKILL.md'],+ name: 'spa-routes',+ path: '/proj/.agents/skills/spa-routes/SKILL.md',+ skillDir: '/proj/.agents/skills/spa-routes',+ source: '.agents/skills',+ },+ ],+ },+ success: true,+ });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace('user-1', 'dev-1', '/proj');++ expect(result).toEqual({+ instructions: [{ content: '# Rules', source: 'AGENTS.md' }],+ skills: [+ {+ description: 'spa',+ name: 'spa-routes',+ path: '/proj/.agents/skills/spa-routes/SKILL.md',+ },+ ],+ });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ { method: 'initWorkspace', params: { scope: '/proj' } },+ );+ });++ it('defaults instructions and skills to empty arrays when absent', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ data: {}, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace('user-1', 'dev-1', '/proj');++ expect(result).toEqual({ instructions: [], skills: [] });+ });++ it('returns undefined when the rpc reports failure', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace('user-1', 'dev-1', '/proj');++ expect(result).toBeUndefined();+ });++ it('returns undefined when the rpc succeeds without data', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace('user-1', 'dev-1', '/proj');++ expect(result).toBeUndefined();+ });++ it('returns undefined on exception', async () => {+ configure();+ mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace('user-1', 'dev-1', '/proj');++ expect(result).toBeUndefined();+ });++ it('forwards a custom timeout', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { instructions: [], skills: [] },+ success: true,+ });++ const proxy = new DeviceGateway();+ await proxy.initWorkspace('user-1', 'dev-1', '/proj', 60_000);++ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },+ { method: 'initWorkspace', params: { scope: '/proj' } },+ );+ });+ });+describe('getClient (lazy initialization)', () => {it('should return null when URL is missing', async () => {mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';diff --git a/src/server/services/toolExecution/deviceGateway.ts b/src/server/services/toolExecution/deviceGateway.tsindex 9a4f15b1230..08241bf2da8 100644--- a/src/server/services/toolExecution/deviceGateway.ts+++ b/src/server/services/toolExecution/deviceGateway.ts@@ -8,6 +8,7 @@ import {type GatewayMcpStdioParams,} from '@lobechat/device-gateway-client';import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import type { ProjectSkillMeta, WorkspaceInitResult } from '@lobechat/types';import debug from 'debug';import { gatewayEnv } from '@/envs/gateway';@@ -78,6 +79,54 @@ export class DeviceGateway {}}+ /**+ * Scan a bound project directory on the device in a single round-trip:+ * project skills (`.agents/skills` + `.claude/skills`) plus the root+ * `AGENTS.md` / `CLAUDE.md`. Routed through the generic device RPC relay+ * (`invokeRpc`) β a server-internal channel the agent never sees, distinct+ * from the LLM-facing tool-call path.+ *+ * Returns `undefined` when the gateway is unconfigured, the device is offline,+ * or the call fails β callers fall back to the cached scan.+ */+ async initWorkspace(+ userId: string,+ deviceId: string,+ scope: string,+ timeout = 30_000,+ ): Promise<WorkspaceInitResult | undefined> {+ const client = this.getClient();+ if (!client) return undefined;++ try {+ // The device returns rich `ProjectSkillItem`s; narrow to metadata only so+ // the cached `workingDirs` payload stays small (SKILL.md bodies are still+ // read lazily at activation time).+ const result = await client.invokeRpc<{+ instructions?: WorkspaceInitResult['instructions'];+ skills?: (ProjectSkillMeta & Record<string, unknown>)[];+ }>({ deviceId, timeout, userId }, { method: 'initWorkspace', params: { scope } });++ if (!result.success || !result.data) {+ log('initWorkspace: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ const { instructions, skills } = result.data;+ return {+ instructions: instructions ?? [],+ skills: (skills ?? []).map(({ description, name, path }) => ({+ description,+ name,+ path,+ })),+ };+ } catch (error) {+ log('initWorkspace: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+ }+async dispatchAgentRun(params: {agentType: HeterogeneousAgentType;cwd?: string;diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex c0cdf44464b..ae0cd618ff3 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -34,12 +34,6 @@ export interface ExecAgentTaskParams {fileIds?: string[];/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;- /**- * Project-level skills discovered on the device filesystem- * (`.agents/skills` / `.claude/skills`). Surfaced in `<available_skills>`- * and loaded on demand via the readFile tool.- */- projectSkills?: { description?: string; name: string; path: string }[];prompt: string;/** Resume a previous op paused on `human_approve_required` instead of starting from a fresh user prompt. */resumeApproval?: ResumeApprovalParam;diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.tsindex 35bc0fcdb4e..487cbf413b2 100644--- a/src/services/electron/localFileService.ts+++ b/src/services/electron/localFileService.ts@@ -65,7 +65,10 @@ class LocalFileService {}async listProjectSkills(params: ListProjectSkillsParams): Promise<ListProjectSkillsResult> {- return ensureElectronIpc().localSystem.listProjectSkills(params);+ // Project-skill scanning lives in the main-process WorkspaceCtr ('workspace'+ // group), split out of LocalFileCtr β hence the namespace differs from the+ // other local-file ops here.+ return ensureElectronIpc().workspace.listProjectSkills(params);}async openLocalFile(params: OpenLocalFileParams) {diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex 742dec5f894..945055f261e 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -9,11 +9,10 @@ import type { ConversationContext, ExecAgentResult, MessageMetadata } from '@lobimport { isDesktop } from '@/const/version';import { aiAgentService, type ResumeApprovalParam } from '@/services/aiAgent';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';-import { localFileService } from '@/services/electron/localFileService';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';-import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';import type { ChatStore } from '@/store/chat/store';@@ -22,38 +21,6 @@ import { useUserStore } from '@/store/user';import { createGatewayEventHandler } from './gatewayEventHandler';-/**- * Scan the active working directory for project-level skills- * (`.agents/skills` / `.claude/skills`) so the server can surface them in- * `<available_skills>`. Desktop-only and best-effort: a failed scan must not- * block the send.- */-const resolveProjectSkills = async (- get: () => ChatStore,-): Promise<{ description?: string; name: string; path: string }[] | undefined> => {- if (!isDesktop) return undefined;-- const topicWorkingDirectory = topicSelectors.currentTopicWorkingDirectory(get());- const agentWorkingDirectory = agentSelectors.currentAgentWorkingDirectory(getAgentStoreState());- const workingDirectory = topicWorkingDirectory ?? agentWorkingDirectory;- if (!workingDirectory) return undefined;-- try {- const { skills } = await localFileService.listProjectSkills({ scope: workingDirectory });- if (skills.length === 0) return undefined;- // The directory tree is enumerated lazily at activation time by the Skills- // runtime (via the local-system `listFiles` tool), so we drop `files` here- // β keeps the op-param payload small.- return skills.map((skill) => ({- description: skill.description,- name: skill.name,- path: skill.path,- }));- } catch {- return undefined;- }-};-/*** When the agent runs against the local machine ("ζ¬ζΊ"), resolve this desktop's* own gateway deviceId so it can be passed as the run's `deviceId`. The server@@ -388,10 +355,7 @@ export class GatewayActionImpl {? this.#get().getOperationAbortSignal(parentOperationId): undefined;- const [projectSkills, localDeviceId] = await Promise.all([- resolveProjectSkills(this.#get),- resolveLocalDeviceId(context.agentId),- ]);+ const localDeviceId = await resolveLocalDeviceId(context.agentId);const result = await aiAgentService.execAgentTask({@@ -410,7 +374,6 @@ export class GatewayActionImpl {deviceId: localDeviceId,fileIds,parentMessageId,- projectSkills,prompt: message,resumeApproval,trigger: metadata?.trigger,