π€― 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(device): add remote directory browsing (#19221)
Tsukiab22456df5bf
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex e768444101e..1185441f8c7 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -605,6 +605,46 @@ export const deviceRouter = router({return result ?? null;}),+ /**+ * Browse one directory level on a remote device. Personal devices belong to+ * the caller. A workspace device may expose new paths only to its enroller or+ * a workspace owner; other members continue to use its approved recents.+ */+ browseDirectory: deviceProcedure+ .input(+ z.object({+ cursor: z.string().optional(),+ deviceId: z.string(),+ limit: z.number().int().positive().max(1000).optional(),+ path: z.string().optional(),+ }),+ )+ .query(async ({ ctx, input }) => {+ if (ctx.workspaceId) {+ const row = await ctx.deviceModel.findWorkspaceDeviceById(input.deviceId);+ if (!row) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });+ }+ const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;+ if (!canEditWorkspaceDevice(role, ctx.userId, row.userId)) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the enrolling member or a workspace owner can browse this device.',+ });+ }+ }++ const result = await deviceGateway.browseDirectory({+ cursor: input.cursor,+ deviceId: input.deviceId,+ limit: input.limit,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+/*** Search project files on a remote device. The device performs the match and* returns only the result subtree needed by the UI.diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 8b35102e1b6..c3cfe42bd61 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -13,6 +13,7 @@ import {import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import type { ClaudeCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';import type {+ DeviceDirectoryBrowseResult,DeviceGitAddWorktreeResult,DeviceGitAheadBehind,DeviceGitBranchDiffPatches,@@ -971,6 +972,50 @@ export class DeviceGateway {}}+ /** List one directory level on a remote execution device for folder pickers. */+ async browseDirectory(params: {+ cursor?: string;+ deviceId: string;+ limit?: number;+ path?: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ }): Promise<DeviceDirectoryBrowseResult | undefined> {+ const {+ cursor,+ deviceId,+ limit,+ path: directoryPath,+ timeout = 10_000,+ userId,+ workspaceId,+ } = params;+ const client = this.getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceDirectoryBrowseResult>(+ { deviceId, timeout, userId, workspaceId },+ {+ method: 'browseDirectory',+ params: { cursor, limit, path: directoryPath },+ },+ );++ if (!result.success || !result.data) {+ log('browseDirectory: failed for deviceId=%s', deviceId);+ return undefined;+ }++ return result.data;+ } catch (error) {+ const errorType = error instanceof Error ? error.name : typeof error;+ log('browseDirectory: error for deviceId=%s (%s)', deviceId, errorType);+ return undefined;+ }+ }+/*** Project file search for a directory on a remote device via the* `searchProjectFiles` device RPC. The device performs matching and returns adiff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 3747ab6aaf6..0496ba6705f 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -140,6 +140,34 @@ describe('executeDeviceRpc', () => {expect(result.isDirectory).toBe(true);});+ it('browses one directory level with pagination and excludes files and hidden folders', async () => {+ const browseRoot = await mkdtemp(path.join(tmpdir(), 'device-control-browse-'));+ try {+ await mkdir(path.join(browseRoot, '.hidden'));+ await mkdir(path.join(browseRoot, 'alpha'));+ await mkdir(path.join(browseRoot, 'beta'));+ await writeFile(path.join(browseRoot, 'notes.txt'), 'not a directory');++ const first = (await executeDeviceRpc(+ 'browseDirectory',+ { limit: 1, path: browseRoot },+ makeDeps(),+ )) as { entries: { name: string }[]; nextCursor?: string; truncated: boolean };+ expect(first.entries.map((entry) => entry.name)).toEqual(['alpha']);+ expect(first.truncated).toBe(true);++ const second = (await executeDeviceRpc(+ 'browseDirectory',+ { cursor: first.nextCursor, limit: 1, path: browseRoot },+ makeDeps(),+ )) as { entries: { name: string }[]; truncated: boolean };+ expect(second.entries.map((entry) => entry.name)).toEqual(['beta']);+ expect(second.truncated).toBe(false);+ } finally {+ await rm(browseRoot, { force: true, recursive: true });+ }+ });+it('routes heterogeneous agent model discovery to the execution host', async () => {const deps = makeDeps();deps.listHeterogeneousAgentModels = vi.fn(async () => ({diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex 7f3a17c779d..959205a3bf6 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -23,6 +23,7 @@ import {import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';import { prepareSkillDirectory } from './skillDirectory';import type {+ BrowseDirectoryParams,DeviceControlDeps,EnrollWorkspaceParams,InitWorkspaceParams,@@ -34,7 +35,7 @@ import type {ProjectFileSearchParams,UnenrollWorkspaceParams,} from './types';-import { initWorkspace, listProjectSkills, statPath } from './workspace';+import { browseDirectory, initWorkspace, listProjectSkills, statPath } from './workspace';/*** Every method name the device-control RPC dispatcher understands. Mirrors the@@ -50,6 +51,7 @@ export const DEVICE_RPC_METHODS = ['getClaudeCodeQuota','listProjectSkills','prepareSkillDirectory',+ 'browseDirectory','statPath','getProjectFileIndex','searchProjectFiles',@@ -134,6 +136,10 @@ export const executeDeviceRpc = async (return prepareSkillDirectory(params as PrepareSkillDirectoryParams, deps);}+ case 'browseDirectory': {+ return browseDirectory(params as BrowseDirectoryParams);+ }+case 'statPath': {return statPath(params as { path: string });}diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.tsindex 51f100ad803..ddcaae52894 100644--- a/packages/device-control/src/index.ts+++ b/packages/device-control/src/index.ts@@ -3,4 +3,4 @@ export { defaultGetLocalFilePreview } from './filePreview';export { defaultGetProjectFileIndex, defaultSearchProjectFiles } from './projectFileIndex';export { defaultSkillCacheRoot, prepareSkillDirectory } from './skillDirectory';export * from './types';-export { initWorkspace, listProjectSkills, statPath } from './workspace';+export { browseDirectory, initWorkspace, listProjectSkills, statPath } from './workspace';diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex 57ed1b64db7..6ecf66cc483 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -64,6 +64,29 @@ export interface StatPathResult {repoType?: 'git' | 'github';}+export interface BrowseDirectoryParams {+ cursor?: string;+ limit?: number;+ path?: string;+}++export interface BrowseDirectoryEntry {+ isSymlink: boolean;+ name: string;+ path: string;+ readable: boolean;+}++export interface BrowseDirectoryResult {+ entries: BrowseDirectoryEntry[];+ nextCursor?: string;+ parentPath: string | null;+ path: string;+ pathSeparator: '/' | '\\';+ roots: string[];+ truncated: boolean;+}+// βββ File preview βββexport type LocalFilePreviewAccept = 'image';diff --git a/packages/device-control/src/workspace.ts b/packages/device-control/src/workspace.tsindex c8df3453c88..80baf8d0130 100644--- a/packages/device-control/src/workspace.ts+++ b/packages/device-control/src/workspace.ts@@ -1,4 +1,5 @@-import { readdir, readFile, stat } from 'node:fs/promises';+import { constants } from 'node:fs';+import { access, readdir, readFile, realpath, stat } from 'node:fs/promises';import * as os from 'node:os';import path from 'node:path';@@ -6,6 +7,8 @@ import { detectRepoType } from '@lobechat/local-file-shell/git';import matter from 'gray-matter';import type {+ BrowseDirectoryParams,+ BrowseDirectoryResult,InitWorkspaceParams,InitWorkspaceResult,ListProjectSkillsParams,@@ -20,6 +23,8 @@ import type {// Cap recursion to guard against pathological directory trees.const MAX_SKILL_FILE_COUNT = 1000;+const DEFAULT_DIRECTORY_PAGE_SIZE = 200;+const MAX_DIRECTORY_PAGE_SIZE = 1000;const SKILL_SOURCES = ['.agents/skills',@@ -267,3 +272,97 @@ export const statPath = async (params: { path: string }): Promise<StatPathResultreturn { exists: false, isDirectory: false };}};++const parseDirectoryCursor = (cursor?: string): number => {+ if (!cursor || !/^\d+$/.test(cursor)) return 0;+ const offset = Number(cursor);+ return Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;+};++const listFilesystemRoots = async (): Promise<string[]> => {+ if (os.platform() !== 'win32') return ['/'];++ const roots = await Promise.all(+ Array.from({ length: 26 }, async (_, index) => {+ const root = `${String.fromCharCode(65 + index)}:\\`;+ try {+ await access(root, constants.R_OK);+ return root;+ } catch {+ return undefined;+ }+ }),+ );++ return roots.filter((root): root is string => !!root);+};++/**+ * List one level of folders on the execution device for remote directory pickers.+ * Files are intentionally excluded so browsing does not expose project contents or+ * pay the cost of the recursive project-file index.+ */+export const browseDirectory = async (+ params: BrowseDirectoryParams = {},+): Promise<BrowseDirectoryResult> => {+ const homeDir = await realpath(os.homedir());+ const requestedPath = params.path?.trim() || homeDir;+ const directoryPath = await realpath(requestedPath);+ const directoryStat = await stat(directoryPath);+ if (!directoryStat.isDirectory()) throw new Error('Browse path is not a directory');++ const requestedLimit = params.limit ?? DEFAULT_DIRECTORY_PAGE_SIZE;+ const limit = Number.isFinite(requestedLimit)+ ? Math.min(MAX_DIRECTORY_PAGE_SIZE, Math.max(1, Math.trunc(requestedLimit)))+ : DEFAULT_DIRECTORY_PAGE_SIZE;+ const offset = parseDirectoryCursor(params.cursor);+ const dirents = await readdir(directoryPath, { withFileTypes: true });+ const candidateResults = await Promise.all(+ dirents.map(async (dirent) => {+ if (!dirent.name || dirent.name === '.' || dirent.name === '..') return undefined;+ if (dirent.name.startsWith('.')) return undefined;++ const entryPath = path.join(directoryPath, dirent.name);+ if (dirent.isDirectory()) {+ return { isSymlink: false, name: dirent.name, path: entryPath };+ }+ if (!dirent.isSymbolicLink()) return undefined;++ try {+ const canonicalPath = await realpath(entryPath);+ if (!(await stat(canonicalPath)).isDirectory()) return undefined;+ return { isSymlink: true, name: dirent.name, path: canonicalPath };+ } catch {+ // Broken links and entries that disappear during enumeration are omitted.+ return undefined;+ }+ }),+ );+ const candidates = candidateResults+ .filter((entry): entry is NonNullable<typeof entry> => !!entry)+ .sort((left, right) => left.name.localeCompare(right.name));+ const page = candidates.slice(offset, offset + limit);+ const entries = await Promise.all(+ page.map(async (entry) => {+ try {+ await access(entry.path, constants.R_OK | constants.X_OK);+ return { ...entry, readable: true };+ } catch {+ return { ...entry, readable: false };+ }+ }),+ );+ const nextOffset = offset + page.length;+ const parent = path.dirname(directoryPath);+ const truncated = nextOffset < candidates.length;++ return {+ entries,+ ...(truncated ? { nextCursor: String(nextOffset) } : {}),+ parentPath: parent === directoryPath ? null : parent,+ path: directoryPath,+ pathSeparator: path.sep === '\\' ? '\\' : '/',+ roots: await listFilesystemRoots(),+ truncated,+ };+};diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 205c0ee1a65..d741b25c12d 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -383,6 +383,25 @@ export interface DeviceListItem {workingDirs: WorkingDirEntry[];}+export interface DeviceDirectoryBrowseEntry {+ isSymlink: boolean;+ name: string;+ /** Canonical absolute path on the execution device. */+ path: string;+ readable: boolean;+}++export interface DeviceDirectoryBrowseResult {+ entries: DeviceDirectoryBrowseEntry[];+ nextCursor?: string;+ parentPath: string | null;+ /** Canonical absolute directory currently being browsed. */+ path: string;+ pathSeparator: '/' | '\\';+ roots: string[];+ truncated: boolean;+}+/*** Branch name + detached-HEAD flag for a working directory, returned by the* `getGitBranch` device RPC. Mirrors the desktop `GitBranchInfo`.