π€― 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
β»οΈ refactor(server): split the 2,248-line device router into sub-domain modules (#21088)
Arvin Xufb3bbd81bad2
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsdeleted file mode 100644index 7aac7976a2e..00000000000--- a/apps/server/src/routers/lambda/device.ts+++ /dev/null@@ -1,2248 +0,0 @@-import { TUNNEL_TOKEN_PARAM } from '@lobechat/device-gateway-client';-import {- type HeterogeneousAgentScanMap,- REMOTE_HETEROGENEOUS_AGENT_CONFIGS,-} from '@lobechat/heterogeneous-agents';-import type {- DeviceChannel,- DeviceEnroller,- DeviceListItem,- DeviceRunningSummary,- DeviceScope,- DeviceWorkspaceShare,- WorkingDirEntry,-} from '@lobechat/types';-import { deriveWorktreePath, sortDevicesByActivity, workingDirConfigSchema } from '@lobechat/types';-import { TRPCError } from '@trpc/server';-import { z } from 'zod';--import {- requireWorkspaceRole,- requireWorkspaceRoleWhenScoped,- type WorkspaceRole,- wsCompatProcedure,- wsProcedure,-} from '@/business/server/trpc-middlewares/workspaceAuth';-import { DeviceModel, WorkspaceDevicePrivateConflictError } from '@/database/models/device';-import { getTopicDeviceId, TopicModel } from '@/database/models/topic';-import { UserModel } from '@/database/models/user';-import { router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { signTunnelAccessToken, signWorkspaceDeviceToken } from '@/libs/trpc/utils/internalJwt';-import {- type DeviceAttachment,- deviceGateway,- isValidDirectoryName,-} from '@/server/services/deviceGateway';-import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/scopedDevicePresence';-import { deviceTunnels, TUNNEL_MAX_TTL_SECONDS } from '@/server/services/deviceGateway/tunnels';--import { loadDeviceBoundAgents } from './deviceBoundAgents';-import { preserveWorkspaceCache } from './deviceWorkingDirs';-import {- assertWorkspaceDeviceEditable,- assertWorkspaceDeviceVisible,- assertWorkspaceRootApproved,- canEditWorkspaceDevice,- canOperateWorkspaceDevice,- registerDeviceSkillRoots,-} from './deviceWorkspaceGuard';-import { workspaceDeviceWorkingDirProcedures } from './deviceWorkspaceWorkingDirs';--// Derive the zod enum from the canonical config so new platforms are-// automatically covered without touching this file.-const remotePlatformEnum = z.enum(- REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => c.type) as [- (typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'],- ...(typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'][],- ],-);--const CAPABILITY_TIMEOUT_MS = 5_000;-const PROFILE_TIMEOUT_MS = 5_000;-// Batch scan probes every agent type (which + --version per binary, with-// login-shell PATH fallback), so it gets a longer budget than a single probe.-const SCAN_TIMEOUT_MS = 10_000;--/**- * A workspace device's user-editable fields (rename, working dirs, remove) may- * be modified by:- * 1. any workspace owner β managing shared infra is an owner privilege, OR- * 2. the workspace member who originally enrolled the device (`devices.userId`- * stores the first enroller for workspace rows, never overwritten on- * re-enroll β see `DeviceModel.registerWorkspaceDevice`).- *- * Members can therefore self-serve their own machines without touching anyone- * else's enrollment, while shared cleanup remains an owner action.- */-/**- * Gate an action that operates the machine itself β browsing folders, a- * terminal, exposing a port, updating its app. A public workspace device is- * shared infra every member works on, so any member may operate it; a private- * one stays limited to the enrolling member or a workspace owner.- */-const assertDeviceOperable = async (- ctx: {- deviceModel: DeviceModel;- userId: string;- workspaceId?: string;- workspaceRole?: WorkspaceRole;- },- deviceId: string,- action: string,-) => {- if (!ctx.workspaceId) return;-- const row = await ctx.deviceModel.findWorkspaceDeviceById(deviceId);- if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });- if (!canOperateWorkspaceDevice(ctx.workspaceRole, ctx.userId, row)) {- throw new TRPCError({- code: 'FORBIDDEN',- message:- row.visibility === 'public'- ? `Workspace viewers cannot ${action} on this device.`- : `Only the enrolling member or a workspace owner can ${action} on this private device.`,- });- }-};--/** Exposing a port is at least as sensitive as reading the filesystem. */-const assertTunnelDeviceWritable = (- ctx: Parameters<typeof assertDeviceOperable>[0],- deviceId: string,-) => assertDeviceOperable(ctx, deviceId, 'expose a port');--/**- * Base64 characters accepted by one `writeTerminal` call. A keystroke is a- * handful of bytes; this only bounds what a malicious caller can push through- * in a single request.- */-const MAX_TERMINAL_WRITE_CHARS = 65_536;--/**- * Relay a terminal call, surfacing the device's own reason. A device that is- * offline β or a client without PTY support β answers with a message the user- * needs to read; a bare 500 would make it look like a LobeHub bug.- */-const relayTerminal = async <T>(run: () => Promise<T>): Promise<T> => {- try {- return await run();- } catch (error) {- throw new TRPCError({- code: 'BAD_GATEWAY',- message: error instanceof Error ? error.message : String(error),- });- }-};--/** Append a freshly minted access token to a tunnel URL. */-const buildTunnelOpenUrl = async (- url: string,- ctx: { userId: string; workspaceId?: string },-): Promise<string> => {- const token = await signTunnelAccessToken({- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- // A dedicated param, not `?token=`: apps behind a tunnel own that name- // (Vite's HMR socket authenticates with it).- return `${url}?${TUNNEL_TOKEN_PARAM}=${encodeURIComponent(token)}`;-};--/**- * Fixed workspace agents promise every member the same execution device. Keep- * that promise intact until an editor changes the agent back to member choice- * (or binds a different public device) before hiding/removing this row.- */-const assertDeviceNotBoundToFixedAgent = async (- model: DeviceModel,- deviceId: string,-): Promise<void> => {- if (!(await model.hasFixedAgentBinding(deviceId))) return;-- throw new TRPCError({- cause: { data: { code: 'DeviceBoundToFixedAgent' } },- code: 'PRECONDITION_FAILED',- message:- 'This device is fixed to one or more workspace agents. Change those agent settings first.',- });-};--/**- * Workspace-write gate: membership + at least `member` role (excludes viewer).- * Enrolling a device mutates the shared workspace device pool, so read-only- * viewers must not pass β `wsProcedure` alone only checks membership.- */-const wsWritableProcedure = wsProcedure.use(requireWorkspaceRole('member'));--// Workspace-aware (compat): with an `X-Workspace-Id` header the device list also-// surfaces the workspace's shared devices; without it, the personal path is-// unchanged (`ctx.workspaceId === undefined`).-//-// Every route below that takes a `deviceId` input also passes the workspace-// visibility gate β see `assertWorkspaceDeviceVisible` for why filtering the-// list paths alone is not enough.-const deviceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {- const { ctx } = opts;- const wsId = ctx.workspaceId ?? undefined;- const deviceModel = new DeviceModel(ctx.serverDB, ctx.userId, wsId);-- if (wsId) {- const raw = (await opts.getRawInput()) as { deviceId?: unknown } | undefined;- if (typeof raw?.deviceId === 'string') {- await assertWorkspaceDeviceVisible(deviceModel, raw.deviceId);- }- }-- return opts.next({- ctx: {- deviceModel,- userId: ctx.userId,- workspaceId: wsId,- },- });-});--const workspaceFileInput = z.object({- deviceId: z.string(),- workingDirectory: z.string(),-});--/**- * `deviceProcedure` that additionally requires `workingDirectory` to be an- * approved workspace root for the device. Builds the guard into the procedure- * so every file-mutating route inherits it and can never forget the check β- * see {@link assertWorkspaceRootApproved} for why the check is necessary.- */-const workspaceFileProcedure = deviceProcedure.input(workspaceFileInput).use(async (opts) => {- const { deviceId, workingDirectory } = workspaceFileInput.parse(await opts.getRawInput());- await assertWorkspaceRootApproved(- opts.ctx.deviceModel,- deviceId,- workingDirectory,- opts.ctx.workspaceId,- );- return opts.next();-});--/**- * `workspaceFileProcedure` for routes that change files on the device. In a- * shared workspace a read-only viewer may browse the tree but not alter it, so- * writes also need at least the `member` role; personal mode stays open.- */-const workspaceFileWriteProcedure = workspaceFileProcedure.use(- requireWorkspaceRoleWhenScoped('member'),-);--/**- * `workspaceFileProcedure` for the publish-asset routes. Their source path may- * lie outside the approved root (the device confines only a copy's- * destination), so they can read any file on the device, and a copy also- * writes into the workspace. Gate them like writes: a read-only viewer must not- * pull arbitrary files off a shared device. Personal mode stays open.- */-const workspacePublishProcedure = workspaceFileProcedure.use(- requireWorkspaceRoleWhenScoped('member'),-);--/**- * Display info for the members behind a set of running topics. The ids come- * from topic rows the caller was already allowed to read, so this only adds- * the public-facing name and avatar.- */-const loadTopicUsers = async (- db: Parameters<typeof UserModel.getDisplayInfoByIds>[0],- userIds: string[],-): Promise<Map<string, DeviceEnroller>> => {- const rows = await UserModel.getDisplayInfoByIds(db, [...new Set(userIds)]);- return new Map(- rows.map((u) => [- u.id,- { avatar: u.avatar, fullName: u.fullName, userId: u.id, username: u.username },- ]),- );-};--/**- * The member running each topic now: the initiator of its current run, else- * its creator (a client-executed run writes no operation row). In a workspace- * a teammate can continue someone else's topic, so the creator alone would- * name the wrong person as using the device.- */-const resolveRunUserIds = async (- topicModel: TopicModel,- topics: { id: string; userId: string }[],-): Promise<Map<string, string>> => {- const initiators = await topicModel.findRunInitiators(topics.map((topic) => topic.id));- return new Map(topics.map((topic) => [topic.id, initiators.get(topic.id) ?? topic.userId]));-};--/**- * Upper bound on the running topics read for the device-list summary. A real- * account runs far fewer at once; the cap only bounds a pathological one.- */-const RUNNING_SUMMARY_LIMIT = 500;--export const deviceRouter = router({- ...workspaceDeviceWorkingDirProcedures,- /**- * Probe whether a specific agent platform (openclaw / hermes) is available- * on the given device. Dispatches a `checkPlatformCapability` tool call to- * the device via the gateway and waits up to 5 s for a response.- */- checkCapability: deviceProcedure- .input(- z.object({- deviceId: z.string(),- platform: remotePlatformEnum,- scope: z.enum(['personal', 'workspace']).optional(),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.executeToolCall(- {- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: input.scope === 'personal' ? undefined : ctx.workspaceId,- },- {- apiName: 'checkPlatformCapability',- arguments: JSON.stringify({ platform: input.platform }),- identifier: 'local',- },- CAPABILITY_TIMEOUT_MS,- );-- if (!result.success) {- return { available: false, reason: result.error ?? 'Device tool call failed' };- }-- try {- return JSON.parse(result.content) as {- available: boolean;- reason?: string;- version?: string;- };- } catch {- return { available: false, reason: 'Invalid response from device' };- }- }),-- /**- * Scan the given device for every known heterogeneous agent type in one- * pass. Dispatches a `scanHeterogeneousAgents` tool call to the device via- * the gateway; the device probes each binary and returns an availability- * map. On gateway failure (offline device, older client without the tool)- * returns an empty map plus the error so the client can distinguish- * "nothing installed" from "scan failed".- */- scanAgents: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .query(- async ({ ctx, input }): Promise<{ agents: HeterogeneousAgentScanMap; error?: string }> => {- const result = await deviceGateway.executeToolCall(- { deviceId: input.deviceId, userId: ctx.userId, workspaceId: ctx.workspaceId },- {- apiName: 'scanHeterogeneousAgents',- arguments: JSON.stringify({}),- identifier: 'local',- },- SCAN_TIMEOUT_MS,- );-- if (!result.success) {- return { agents: {}, error: result.error ?? 'Device tool call failed' };- }-- try {- const parsed = JSON.parse(result.content) as { agents?: HeterogeneousAgentScanMap };- return { agents: parsed.agents ?? {} };- } catch {- return { agents: {}, error: 'Invalid response from device' };- }- },- ),-- /**- * What the device is doing for the caller: topics running on it right now- * and the agents routed to it. Both reads go through the regular content- * scopes, so in a workspace a teammate's private agent (and the topics under- * it) never surface just because they share the machine.- *- * Agent bindings are resolved per caller: the stored agency config merged- * with the caller's own per-agent device override in this workspace, exactly- * as a run would route β see {@link loadDeviceBoundAgents}.- */- getDeviceActivity: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .query(async ({ ctx, input }) => {- const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const [agents, runningTopics] = await Promise.all([- loadDeviceBoundAgents({- db: ctx.serverDB,- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- topicModel.queryTopics({ deviceId: input.deviceId, statuses: ['running'] }),- ]);-- const runUserIds = await resolveRunUserIds(topicModel, runningTopics);- const users = await loadTopicUsers(ctx.serverDB, [...runUserIds.values()]);-- return {- agents,- runningTopics: runningTopics.map((topic) => ({- ...topic,- user: users.get(runUserIds.get(topic.id) ?? topic.userId) ?? null,- })),- };- }),-- /**- * Per-device running-topic counts and the members behind them, for the- * device list cards. One read for the whole list instead of a request per- * card; the same content scopes as {@link getDeviceActivity} apply, and a- * device the caller cannot see simply has no card to render its entry.- */- getRunningSummary: deviceProcedure.query(async ({ ctx }): Promise<DeviceRunningSummary[]> => {- // Most recently active first, so each device's avatar stack leads with- // whoever touched it last.- const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const runningTopics = (- await topicModel.queryTopics({ pageSize: RUNNING_SUMMARY_LIMIT, statuses: ['running'] })- ).filter((topic) => getTopicDeviceId(topic.metadata));- const runUserIds = await resolveRunUserIds(topicModel, runningTopics);-- const byDevice = new Map<string, { count: number; userIds: string[] }>();- for (const topic of runningTopics) {- const deviceId = getTopicDeviceId(topic.metadata)!;- const runUserId = runUserIds.get(topic.id) ?? topic.userId;- const entry = byDevice.get(deviceId) ?? { count: 0, userIds: [] };- entry.count += 1;- if (!entry.userIds.includes(runUserId)) entry.userIds.push(runUserId);- byDevice.set(deviceId, entry);- }-- const users = await loadTopicUsers(- ctx.serverDB,- [...byDevice.values()].flatMap((entry) => entry.userIds),- );-- return [...byDevice].map(([deviceId, { count, userIds }]) => ({- count,- deviceId,- users: userIds.flatMap((id) => users.get(id) ?? []),- }));- }),-- /**- * Granular git reads for a directory on a remote device, each via its own- * device RPC so the web/remote git status bar mirrors the local desktop's- * separate, differently-cadenced SWR hooks. Return `null` when offline / the- * directory isn't a git repo.- */- gitBranch: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitBranch({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- gitLinkedPullRequest: deviceProcedure- .input(- z.object({- branch: z.string(),- deviceId: z.string(),- path: z.string(),- pullRequestNumber: z.number().optional(),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitLinkedPullRequest({- branch: input.branch,- deviceId: input.deviceId,- path: input.path,- pullRequestNumber: input.pullRequestNumber,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- gitPullRequestDetail: deviceProcedure- .input(- z.object({- coreOnly: z.boolean().optional(),- deviceId: z.string(),- number: z.number().int().positive(),- path: z.string(),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitPullRequestDetail({- coreOnly: input.coreOnly,- deviceId: input.deviceId,- number: input.number,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- gitPullRequestActivity: deviceProcedure- .input(- z.object({ deviceId: z.string(), number: z.number().int().positive(), path: z.string() }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitPullRequestActivity({- deviceId: input.deviceId,- number: input.number,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- gitPullRequestMergeContext: deviceProcedure- .input(- z.object({- baseRefName: z.string(),- deviceId: z.string(),- headRefOid: z.string().regex(/^[a-f\d]{40}$/i),- number: z.number().int().positive(),- path: z.string(),- repo: z.object({ name: z.string(), owner: z.string() }),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitPullRequestMergeContext({- ...input,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- gitWorkingTreeStatus: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitWorkingTreeStatus({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- gitAheadBehind: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.gitAheadBehind({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Claude Code subscription quota sampled by the device with its own local- * credentials, so web clients can show live quota for a bound-device run.- * `null` when the device is offline or its client predates this RPC.- */- getClaudeCodeQuota: deviceProcedure- .input(- z.object({- deviceId: z.string(),- env: z.record(z.string(), z.string()).optional(),- force: z.boolean().optional(),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.claudeCodeQuota({- deviceId: input.deviceId,- env: input.env,- force: input.force,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /** Query a heterogeneous CLI's model catalog on the device that will execute the agent. */- listHeterogeneousAgentModels: deviceProcedure- .input(- z.object({- args: z.array(z.string()).optional(),- command: z.string().optional(),- cwd: z.string().optional(),- deviceId: z.string(),- env: z.record(z.string(), z.string()).optional(),- type: z.enum([- 'codebuddy',- 'codex',- 'cursor',- 'droid',- 'devin',- 'grok-build',- 'kimi-code',- 'opencode',- 'pi',- 'qoder',- 'trae',- ]),- }),- )- .query(async ({ ctx, input }) =>- deviceGateway.listHeterogeneousAgentModels({- args: input.args,- command: input.command,- cwd: input.cwd,- deviceId: input.deviceId,- env: input.env,- type: input.type,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * List the git worktrees attached to the same repository as a directory on a- * remote device, via the device's `listGitWorktrees` RPC. Lets the web/remote- * worktree picker mirror the local desktop's, populated over IPC.- */- listGitWorktrees: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.listGitWorktrees({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? [];- }),-- /**- * List the local branches of a directory on a remote device, via the device's- * `listGitBranches` RPC. Lets the web/remote branch switcher populate the same- * dropdown the local desktop renders over IPC.- */- listGitBranches: deviceProcedure- .input(- z.object({- deviceId: z.string(),- path: z.string(),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.listGitBranches({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? [];- }),-- /**- * Checkout (or create) a branch in a directory on a remote device, via the- * device's `checkoutGitBranch` RPC.- */- checkoutGitBranch: deviceProcedure- .input(- z.object({- branch: z.string(),- create: z.boolean().optional(),- deviceId: z.string(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) =>- deviceGateway.checkoutGitBranch({- branch: input.branch,- create: input.create,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Rename a branch in a directory on a remote device, via the device's- * `renameGitBranch` RPC.- */- renameGitBranch: deviceProcedure- .input(- z.object({- deviceId: z.string(),- from: z.string(),- path: z.string(),- to: z.string(),- }),- )- .mutation(async ({ ctx, input }) =>- deviceGateway.renameGitBranch({- deviceId: input.deviceId,- from: input.from,- path: input.path,- to: input.to,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Delete a branch in a directory on a remote device, via the device's- * `deleteGitBranch` RPC.- */- deleteGitBranch: deviceProcedure- .input(- z.object({- branch: z.string(),- deviceId: z.string(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) =>- deviceGateway.deleteGitBranch({- branch: input.branch,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Remove a worktree in a directory's repository on a remote device,- * via the device's `removeGitWorktree` RPC.- */- removeGitWorktree: deviceProcedure- .input(- z.object({- deviceId: z.string(),- path: z.string(),- worktreePath: z.string(),- }),- )- .mutation(async ({ ctx, input }) =>- deviceGateway.removeGitWorktree({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- worktreePath: input.worktreePath,- }),- ),-- /**- * Add a linked worktree on a fresh branch in a directory's repository on a- * remote device, via the device's `addGitWorktree` RPC.- *- * The target directory is derived here from the trusted `path` + `branch`- * (a `<repo>-<branch>` sibling) rather than accepted from the request, so a- * crafted web call can't ask the device to check out at an arbitrary absolute- * path β the branch is folded to `-` in the folder name, so it can't traverse.- */- addGitWorktree: deviceProcedure- .input(- z.object({- branch: z.string(),- deviceId: z.string(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) =>- deviceGateway.addGitWorktree({- branch: input.branch,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- worktreePath: deriveWorktreePath(input.path, input.branch),- }),- ),-- /**- * Pull (`--ff-only`) the current branch of a directory on a remote device, via- * the device's `pullGitBranch` RPC.- */- pullGitBranch: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .mutation(async ({ ctx, input }) =>- deviceGateway.pullGitBranch({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Push the current branch of a directory on a remote device, via the device's- * `pushGitBranch` RPC.- */- pushGitBranch: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .mutation(async ({ ctx, input }) =>- deviceGateway.pushGitBranch({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a- * directory on a remote device, via the device's `runPullRequestAction` RPC.- */- runGitPullRequestAction: deviceProcedure- .use(requireWorkspaceRoleWhenScoped('member'))- .input(- z.object({- action: z.discriminatedUnion('type', [- z.object({- admin: z.boolean().optional(),- deleteBranch: z.boolean().optional(),- headRefOid: z.string().regex(/^[a-f\d]{40}$/i),- method: z.enum(['squash', 'merge', 'rebase']),- type: z.literal('merge'),- }),- z.object({- headRefOid: z.string().regex(/^[a-f\d]{40}$/i),- method: z.enum(['squash', 'merge', 'rebase']),- type: z.literal('autoMerge'),- }),- z.object({ type: z.literal('disableAutoMerge') }),- z.object({ method: z.enum(['merge', 'rebase']), type: z.literal('updateBranch') }),- z.object({ type: z.literal('ready') }),- z.object({ body: z.string(), type: z.literal('comment') }),- z.object({ type: z.literal('close') }),- z.object({ type: z.literal('reopen') }),- z.object({ head: z.string(), type: z.literal('deleteBranch') }),- z.object({ base: z.string(), type: z.literal('changeBase') }),- ]),- deviceId: z.string(),- number: z.number().int().positive(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- await assertWorkspaceRootApproved(- ctx.deviceModel,- input.deviceId,- input.path,- ctx.workspaceId,- );- return deviceGateway.runGitPullRequestAction({- action: input.action,- deviceId: input.deviceId,- number: input.number,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- /**- * Working-tree (unstaged) per-file patches for a directory on a remote device,- * via the device's `getGitWorkingTreePatches` RPC. Powers the web/remote Review- * panel's unstaged diff. Returns `null` when offline / not a git repo.- */- getGitWorkingTreePatches: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.getGitWorkingTreePatches({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Branch diff (current branch vs base ref) per-file patches for a directory on- * a remote device, via the device's `getGitBranchDiff` RPC.- */- getGitBranchDiff: deviceProcedure- .input(z.object({ baseRef: z.string().optional(), deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.getGitBranchDiff({- baseRef: input.baseRef,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * List the remote branches of a directory on a remote device, via the device's- * `listGitRemoteBranches` RPC. Populates the Review base-ref picker.- */- listGitRemoteBranches: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.listGitRemoteBranches({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? [];- }),-- /**- * Repo-relative paths of dirty working-tree files for a directory on a remote- * device, via the device's `getGitWorkingTreeFiles` RPC. Powers the Files tab's- * git-status overlay. Returns `null` when offline / not a git repo.- */- getGitWorkingTreeFiles: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.getGitWorkingTreeFiles({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Project file index (tree) for a directory on a remote device, via the- * device's `getProjectFileIndex` RPC. Powers the Files tab's tree. Returns- * `null` when offline.- */- getProjectFileIndex: deviceProcedure- .input(z.object({ deviceId: z.string(), scope: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.getProjectFileIndex({- deviceId: input.deviceId,- scope: input.scope,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Children of one directory inside a project on a remote device. The Files- * tree calls this when the user expands a directory the index collapsed- * (a fully git-ignored folder). Returns `null` when offline.- */- listProjectDirectory: deviceProcedure- .input(z.object({ deviceId: z.string(), relativePath: z.string(), root: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.listProjectDirectory({- deviceId: input.deviceId,- relativePath: input.relativePath,- root: input.root,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Browse one directory level on a remote device. Personal devices belong to- * the caller; workspace devices follow {@link assertDeviceOperable}.- */- 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 }) => {- await assertDeviceOperable(ctx, input.deviceId, 'browse folders');-- 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;- }),-- /**- * Create a folder inside the directory a remote folder picker is browsing, so- * a new working directory can be made without leaving the picker. Same access- * rule as {@link browseDirectory}; a taken name is reported as `CONFLICT`.- */- createDirectory: deviceProcedure- .input(- z.object({- deviceId: z.string(),- name: z.string().min(1).max(255),- parentPath: z.string().min(1),- }),- )- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'create folders');-- if (- !isValidDirectoryName(input.name, input.parentPath) ||- !isValidDirectoryName(input.name.trim(), input.parentPath)- ) {- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid folder name.' });- }-- let result: Awaited<ReturnType<typeof deviceGateway.createDirectory>>;- try {- result = await deviceGateway.createDirectory({- deviceId: input.deviceId,- name: input.name.trim(),- parentPath: input.parentPath,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- // A device app predating `createLocalDirectory` needs an update, not a retry.- throw new TRPCError({- code: /Unknown device RPC method/.test(message) ? 'PRECONDITION_FAILED' : 'BAD_GATEWAY',- message,- });- }-- if (!result.success) {- throw new TRPCError({- code: /already exists/i.test(result.error ?? '') ? 'CONFLICT' : 'BAD_REQUEST',- message: result.error || 'Create folder failed',- });- }-- return result;- }),-- /**- * Search project files on a remote device. The device performs the match and- * returns only the result subtree needed by the UI.- */- searchProjectFiles: deviceProcedure- .input(- z.object({- changedOnly: z.boolean().optional(),- deviceId: z.string(),- excludeIgnored: z.boolean().optional(),- limit: z.number().int().positive().max(500).optional(),- query: z.string(),- scope: z.string(),- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.searchProjectFiles({- changedOnly: input.changedOnly,- deviceId: input.deviceId,- excludeIgnored: input.excludeIgnored,- limit: input.limit,- query: input.query,- scope: input.scope,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Read-only local file preview for a file on a remote device. The web client- * receives render data, not a `localfile://` URL; saving remains unsupported.- */- getLocalFilePreview: workspaceFileProcedure- .input(- z.object({- accept: z.enum(['image']).optional(),- path: z.string(),- }),- )- .query(async ({ ctx, input }) => {- return deviceGateway.getLocalFilePreview({- accept: input.accept,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- copyAssetForPublish: workspacePublishProcedure- .input(z.object({ from: z.string(), to: z.string() }))- .mutation(async ({ ctx, input }) =>- deviceGateway.copyAssetForPublish({- deviceId: input.deviceId,- from: input.from,- to: input.to,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- }),- ),-- readExternalAssetForPublish: workspacePublishProcedure- .input(z.object({ path: z.string() }))- .query(async ({ ctx, input }) =>- deviceGateway.readExternalAssetForPublish({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- }),- ),-- /**- * Project skills (`.agents/skills` / `.claude/skills`) for a directory on a- * remote device, via the device's `listProjectSkills` RPC. Powers the- * Resources tab's skills group in device mode. Returns `null` when offline.- */- listProjectSkills: deviceProcedure- .input(z.object({ deviceId: z.string(), scope: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.listProjectSkills({- deviceId: input.deviceId,- scope: input.scope,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });-- // Register device-scoped skill roots (~/.agents/skills / ~/.claude/skills)- // in an in-memory cache so subsequent getLocalFilePreview calls pass the- // workspace root guard without polluting the UI's working-directory list.- if (result?.skills) {- const skillRoots = [- ...new Set(result.skills.filter((s) => s.scope === 'device').map((s) => s.previewRoot)),- ].filter(Boolean);- registerDeviceSkillRoots(input.deviceId, skillRoots);- }-- return result ?? null;- }),-- /**- * Revert a single file in a directory on a remote device, via the device's- * `revertGitFile` RPC.- */- revertGitFile: deviceProcedure- .input(z.object({ deviceId: z.string(), filePath: z.string(), path: z.string() }))- .mutation(async ({ ctx, input }) =>- deviceGateway.revertGitFile({- deviceId: input.deviceId,- filePath: input.filePath,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Move files/folders within a directory on a remote device, via the device's- * `moveLocalFiles` RPC. Powers the Files tree's drag-to-move in device mode.- */- moveProjectFiles: workspaceFileWriteProcedure- .input(- z.object({- items: z.array(z.object({ newPath: z.string(), oldPath: z.string() })),- }),- )- .mutation(async ({ ctx, input }) => {- return deviceGateway.moveProjectFiles({- deviceId: input.deviceId,- items: input.items,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Rename a single file/folder in a directory on a remote device, via the- * device's `renameLocalFile` RPC.- */- renameProjectFile: workspaceFileWriteProcedure- .input(- z.object({- newName: z.string(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- return deviceGateway.renameProjectFile({- deviceId: input.deviceId,- newName: input.newName,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Save edited content back to a file on a remote device, via the device's- * `writeLocalFile` RPC. Powers remote save in the LocalFile editor.- */- writeProjectFile: workspaceFileWriteProcedure- .input(- z.object({- content: z.string(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- return deviceGateway.writeProjectFile({- content: input.content,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Create a new file on a remote device, via the device's `createLocalFile`- * RPC. Fails instead of overwriting when the path is taken.- */- createProjectFile: workspaceFileWriteProcedure- .input(- z.object({- content: z.string().optional(),- path: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- return deviceGateway.createProjectFile({- content: input.content,- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Create a new folder on a remote device, via the device's- * `createLocalDirectory` RPC. Fails when the path is taken.- */- createProjectDirectory: workspaceFileWriteProcedure- .input(z.object({ path: z.string() }))- .mutation(async ({ ctx, input }) => {- return deviceGateway.createProjectDirectory({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Copy files/folders on a remote device, via the device's `copyLocalFiles`- * RPC. An item without `targetPath` is duplicated in place.- */- copyProjectFiles: workspaceFileWriteProcedure- .input(- z.object({- items: z- .array(z.object({ sourcePath: z.string(), targetPath: z.string().optional() }))- .min(1),- }),- )- .mutation(async ({ ctx, input }) => {- return deviceGateway.copyProjectFiles({- deviceId: input.deviceId,- items: input.items,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Move files/folders to a remote device's trash, via the device's- * `trashLocalFiles` RPC. Devices without a trash reject rather than delete.- */- trashProjectFiles: workspaceFileWriteProcedure- .input(z.object({ paths: z.array(z.string()).min(1) }))- .mutation(async ({ ctx, input }) => {- return deviceGateway.trashProjectFiles({- deviceId: input.deviceId,- paths: input.paths,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- workingDirectory: input.workingDirectory,- });- }),-- /**- * Check whether a path exists on a remote device and is a directory, via the- * device's `statPath` RPC. Lets a web client validate a manually-entered- * working directory before binding it. Returns `null` when the device is- * unreachable (caller treats "can't verify" as non-blocking).- */- statPath: deviceProcedure- .input(z.object({ deviceId: z.string(), path: z.string() }))- .query(async ({ ctx, input }) => {- const result = await deviceGateway.statPath({- deviceId: input.deviceId,- path: input.path,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- /**- * Fetch the agent profile (title, description, avatar) from the platform- * installed on the given device. Used to pre-fill the creation modal.- * Returns an empty object on failure or when the platform has no profile.- */- getAgentProfile: deviceProcedure- .input(- z.object({- deviceId: z.string(),- platform: remotePlatformEnum,- }),- )- .query(async ({ ctx, input }) => {- const result = await deviceGateway.executeToolCall(- { deviceId: input.deviceId, userId: ctx.userId, workspaceId: ctx.workspaceId },- {- apiName: 'getAgentProfile',- arguments: JSON.stringify({ platform: input.platform }),- identifier: 'local',- },- PROFILE_TIMEOUT_MS,- );-- if (!result.success) return {};-- try {- return JSON.parse(result.content) as {- avatar?: string;- description?: string;- title?: string;- };- } catch {- return {};- }- }),-- getDeviceSystemInfo: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .query(async ({ ctx, input }) => {- return deviceGateway.queryDeviceSystemInfo(ctx.userId, input.deviceId, ctx.workspaceId);- }),-- /**- * All devices the user has ever registered (incl. offline). A device is keyed- * by its `deviceId`; the gateway's live WS sessions are NOT separate devices β- * each session is surfaced as a `channel` nested under its device. A single- * device may therefore hold multiple channels (e.g. desktop app + CLI both- * connected at once), and `online` is simply "has at least one live channel".- *- * Personal scope is a union rather than only DB rows: auto-registration may- * briefly lag a live socket. Workspace scope fails closed on visible registry- * rows because the row is the enrollment and authorization boundary.- */- listDevices: deviceProcedure.query(async ({ ctx }): Promise<DeviceListItem[]> => {- const wsId = ctx.workspaceId;-- // Personal devices resolve under the user principal; workspace devices under- // the `workspace:<id>` principal (a separate gateway pool). Fetch both.- const [personalRows, workspaceRows, sharedRows, personalOnline, workspaceOnline] =- await Promise.all([- ctx.deviceModel.queryPersonal(),- wsId ? ctx.deviceModel.queryWorkspaceDevices() : Promise.resolve([]),- ctx.deviceModel.querySharedWorkspaceDevices(),- deviceGateway.queryDeviceList(ctx.userId),- wsId ? deviceGateway.queryDeviceList(ctx.userId, wsId) : Promise.resolve([]),- ]);-- // Shares the caller created from their personal device list, grouped by the- // source personal deviceId β attached to personal rows below so the list can- // render "shared to N workspaces" and revoke individual shares.- const sharesByPersonalId = new Map<string, DeviceWorkspaceShare[]>();- for (const s of sharedRows) {- if (!s.sharedFromDeviceId || !s.workspaceId) continue;- const list = sharesByPersonalId.get(s.sharedFromDeviceId) ?? [];- list.push({- deviceId: s.deviceId,- visibility: s.visibility,- workspaceId: s.workspaceId,- workspaceName: s.workspaceName ?? null,- });- sharesByPersonalId.set(s.sharedFromDeviceId, list);- }-- // Resolve display info for every enroller in a single roundtrip, so each- // row can ship a self-contained `enroller` for the picker / settings UI.- // Personal rows always belong to the caller, but the same lookup keeps the- // shape uniform across scopes.- const enrollerIds = [...new Set([...personalRows, ...workspaceRows].map((d) => d.userId))];- const enrollerRows = enrollerIds.length- ? await UserModel.findByIds(ctx.serverDB, enrollerIds)- : [];- const enrollerById = new Map(- enrollerRows.map((u) => [- u.id,- {- avatar: u.avatar ?? null,- fullName: u.fullName ?? null,- userId: u.id,- username: u.username ?? null,- },- ]),- );-- // The gateway already groups by device, exposing live sessions as nested- // `channels`. Flatten one connection into the UI-facing channel shape; fall- // back to a single synthetic channel for a legacy gateway that omits the field.- const toChannels = (conn: DeviceAttachment): DeviceChannel[] =>- conn.channels && conn.channels.length > 0- ? conn.channels.map((c) => ({- channel: c.channel ?? null,- connectedAt: c.connectedAt,- hostname: conn.hostname ?? null,- platform: conn.platform ?? null,- }))- : [- {- channel: null,- connectedAt: conn.lastSeen,- hostname: conn.hostname ?? null,- platform: conn.platform ?? null,- },- ];-- // Merge a DB-registered set with its live gateway pool into the UI shape.- // `scope` tags the group; deviceIds never collide across pools (a personal id- // is derived from userId, a workspace id from workspaceId).- const buildItems = (- rows: Awaited<ReturnType<typeof ctx.deviceModel.queryPersonal>>,- onlineList: DeviceAttachment[],- scope: DeviceScope,- ): DeviceListItem[] => {- const registeredDeviceIds = new Set(rows.map((device) => device.deviceId));- const channelsByDevice = new Map<string, DeviceChannel[]>();- for (const conn of filterAuthorizedDevicePresence(registeredDeviceIds, onlineList, scope)) {- channelsByDevice.set(conn.deviceId, toChannels(conn));- }-- const seen = new Set<string>();- const fromDb = rows.map((d): DeviceListItem => {- seen.add(d.deviceId);- const channels = channelsByDevice.get(d.deviceId) ?? [];- const live = channels[0];- return {- architecture: d.architecture,- channels,- defaultCwd: d.defaultCwd,- deviceId: d.deviceId,- // For personal rows this is always the caller; for workspace rows it- // is the first enroller, surfaced so the UI can gate writes to "self- // or workspace owner" and render the enroller's avatar without a- // separate fetch. Falls back to a userId-only stub if the user row- // was deleted (cascade nullifies devices.userId? no β FK is set, so- // a stub keeps the gate fail-closed).- enroller: enrollerById.get(d.userId) ?? {- avatar: null,- fullName: null,- userId: d.userId,- username: null,- },- friendlyName: d.friendlyName,- hostname: d.hostname ?? live?.hostname ?? null,- identitySource: d.identitySource,- lastSeen: d.lastSeenAt.toISOString(),- metadata: d.metadata,- online: channels.length > 0,- platform: d.platform ?? live?.platform ?? null,- registered: true,- scope,- // Workspace rows only: member-shared (via the personal share flow)- // vs directly enrolled β drives the "Shared by {name}" tag.- sharedFromPersonal: scope === 'workspace' ? !!d.sharedFromDeviceId : undefined,- // Personal rows only: the workspaces this machine was shared into- // from the personal list (undefined for workspace rows and machines- // never shared).- sharedWorkspaces: scope === 'personal' ? sharesByPersonalId.get(d.deviceId) : undefined,- // Personal rows have no workspace-visibility dimension; the column's- // default is meaningless there, so normalise to null.- visibility: scope === 'workspace' ? d.visibility : null,- // Strip the heavy `workspace` scan (AGENTS.md + project skills, up to- // ~30KB per dir) from the list payload. It's a server-owned cache for- // the agent runtime (restored from the DB row on run start, never from- // this response) and no client UI renders it from the list β skills are- // re-derived live via `device.listProjectSkills`. Keep `workspaceScannedAt`- // (a cheap number) so clients can still show scan freshness.- workingDirs: (d.workingDirs ?? []).map(({ workspace: _workspace, ...rest }) => rest),- };- });-- // Personal clients auto-register immediately before opening their- // socket, so preserve their brief Gateway-first race. Workspace rows are- // authorization: a Gateway-only socket may be a stale process that missed- // Unshare, and must stay hidden and ineligible.- const ghosts = [...channelsByDevice.entries()]- .filter(([deviceId]) => !seen.has(deviceId))- .map(([deviceId, channels]): DeviceListItem => ({- channels,- defaultCwd: null,- deviceId,- // No row yet β no enroller; UI gates treat this as not-editable.- enroller: null,- friendlyName: null,- hostname: channels[0]?.hostname ?? null,- identitySource: null,- lastSeen: channels[0]?.connectedAt ?? new Date().toISOString(),- online: true,- platform: channels[0]?.platform ?? null,- registered: false,- scope,- visibility: null,- workingDirs: [] as WorkingDirEntry[],- }));-- return [...fromDb, ...ghosts];- };-- // Ordered here rather than in SQL: `online` is the primary key and only the- // gateway knows it, so no per-pool `ORDER BY` can produce it β the two pools- // and their ghosts have to be merged first, then ordered as one list.- // Consumers (settings list, picker) filter this down to a single scope, and- // filtering preserves order, so one pass serves every surface.- return sortDevicesByActivity([- ...buildItems(personalRows, personalOnline, 'personal'),- ...buildItems(workspaceRows, workspaceOnline, 'workspace'),- ]);- }),-- // βββ Tunnel links βββ- //- // A tunnel makes one loopback port on a device reachable at- // `https://<port>--<slug>.lobe.sh/`. Creating one is gated exactly like- // browsing the device's filesystem: on a public workspace device any- // non-viewer member may expose a port; on a private one, only the enrolling- // member or an owner.-- /** Open a link to `port` on a device. */- createTunnel: deviceProcedure- .input(- z.object({- deviceId: z.string(),- port: z.number().int().min(1).max(65_535),- ttlSeconds: z.number().int().positive().max(TUNNEL_MAX_TTL_SECONDS).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- await assertTunnelDeviceWritable(ctx, input.deviceId);-- const link = await deviceTunnels.create({- deviceId: input.deviceId,- port: input.port,- ttlSeconds: input.ttlSeconds,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (!link) {- throw new TRPCError({- code: 'PRECONDITION_FAILED',- message: 'Device gateway is not configured on this deployment.',- });- }-- return { ...link, openUrl: await buildTunnelOpenUrl(link.url, ctx) };- }),-- /**- * Ports the device is listening on, so the UI can offer "5173 Β· vite" to- * expose in one click. Gated like creating a tunnel: seeing which ports are- * open is only useful to someone allowed to expose them. `null` means the- * device couldn't answer (offline, or a client that predates detection).- */- listListeningPorts: deviceProcedure- .input(z.object({ cwd: z.string().optional(), deviceId: z.string() }))- .query(async ({ ctx, input }) => {- await assertTunnelDeviceWritable(ctx, input.deviceId);- const result = await deviceGateway.listListeningPorts({- cwd: input.cwd,- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- return result ?? null;- }),-- // βββ Remote app update βββ- //- // Update the desktop app on a device from anywhere: check (a found update- // downloads on its own), poll progress, then restart into it. Restarting- // interrupts whatever the machine is running, so every step is gated like- // exposing a port.-- getAppUpdateState: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .query(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'update the app');- return deviceGateway.getAppUpdateState({- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- checkAppUpdate: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'update the app');- return deviceGateway.checkAppUpdate({- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- installAppUpdate: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'update the app');- return deviceGateway.installAppUpdate({- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- // βββ Interactive terminal βββ- //- // A terminal hands the caller a shell on the device, so it is gated exactly- // like exposing a port. The check runs on the polling reads too, not just on- // create β otherwise a session would outlive the permission that opened it.-- createTerminalSession: deviceProcedure- .input(- z.object({- cols: z.number().int().min(1).max(1000),- cwd: z.string().optional(),- deviceId: z.string(),- rows: z.number().int().min(1).max(1000),- }),- )- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'open a terminal on');- return relayTerminal(() =>- deviceGateway.createTerminalSession({- cols: input.cols,- cwd: input.cwd,- deviceId: input.deviceId,- rows: input.rows,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- );- }),-- writeTerminal: deviceProcedure- .input(- z.object({- /** Base64 keystrokes. */- data: z.string().max(MAX_TERMINAL_WRITE_CHARS),- deviceId: z.string(),- id: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');- return relayTerminal(() =>- deviceGateway.writeTerminal({- data: input.data,- deviceId: input.deviceId,- id: input.id,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- );- }),-- readTerminal: deviceProcedure- .input(z.object({ cursor: z.number().int().min(0), deviceId: z.string(), id: z.string() }))- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');- return relayTerminal(() =>- deviceGateway.readTerminal({- cursor: input.cursor,- deviceId: input.deviceId,- id: input.id,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- );- }),-- resizeTerminal: deviceProcedure- .input(- z.object({- cols: z.number().int().min(1).max(1000),- deviceId: z.string(),- id: z.string(),- rows: z.number().int().min(1).max(1000),- }),- )- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');- return relayTerminal(() =>- deviceGateway.resizeTerminal({- cols: input.cols,- deviceId: input.deviceId,- id: input.id,- rows: input.rows,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- );- }),-- closeTerminal: deviceProcedure- .input(z.object({ deviceId: z.string(), id: z.string() }))- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');- return relayTerminal(() =>- deviceGateway.closeTerminal({- deviceId: input.deviceId,- id: input.id,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- );- }),-- getCliUpdateState: deviceProcedure- .input(z.object({ deviceId: z.string() }).strict())- .query(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');- return deviceGateway.getCliUpdateState({- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- checkCliUpdate: deviceProcedure- .input(z.object({ deviceId: z.string() }).strict())- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');- return deviceGateway.checkCliUpdate({- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- restartCli: deviceProcedure- .input(- z- .object({ deviceId: z.string(), requestId: z.string().uuid(), update: z.boolean() })- .strict(),- )- .mutation(async ({ ctx, input }) => {- await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');- return deviceGateway.restartCli({- ...input,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- }),-- /** Live tunnel links the caller can reach, newest first. */- listTunnels: deviceProcedure- .input(z.object({ deviceId: z.string().optional() }).optional())- .query(async ({ ctx, input }) =>- deviceTunnels.list({- deviceId: input?.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- }),- ),-- /**- * Mint the one-shot token that opens an existing link. Tokens are minted per- * click rather than stored with the link: the gateway swaps the token for a- * session cookie on first use, so the URL in hand stays clean.- */- openTunnel: deviceProcedure- .input(z.object({ slug: z.string() }))- .mutation(async ({ ctx, input }) => {- const links = await deviceTunnels.list({ userId: ctx.userId, workspaceId: ctx.workspaceId });- const link = links.find((candidate) => candidate.slug === input.slug);- if (!link) throw new TRPCError({ code: 'NOT_FOUND', message: 'Tunnel not found.' });-- return { openUrl: await buildTunnelOpenUrl(link.url, ctx), url: link.url };- }),-- /** Revoke a link. Its session cookies stop resolving immediately. */- revokeTunnel: deviceProcedure- .input(z.object({ slug: z.string() }))- .mutation(async ({ ctx, input }) => {- const outcome = await deviceTunnels.revoke({- slug: input.slug,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (outcome === 'forbidden') {- throw new TRPCError({ code: 'FORBIDDEN', message: 'This tunnel belongs to someone else.' });- }- if (outcome === 'not-found') {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Tunnel not found.' });- }- return { success: true };- }),-- /**- * Mint a short-lived connect token for enrolling a WORKSPACE-owned device.- * Workspace members (and owners) can call β enrolling a machine into the- * shared pool is self-service so members don't have to chase an owner to- * join their dev box. Viewers are blocked: writing a row to the workspace- * device pool is a mutation, not a read. The signed token carries the- * `workspace_id` claim the device gateway trusts to route the device to the- * `workspace:<id>` principal. The CLI (`lh connect --workspace`) / settings- * page use this.- */- mintWorkspaceConnectToken: wsWritableProcedure.mutation(async ({ ctx }) => {- const token = await signWorkspaceDeviceToken(ctx.workspaceId);- return { token, workspaceId: ctx.workspaceId };- }),-- /**- * Enroll the calling machine as a device of the current workspace.- * Workspace members (and owners) may call β viewers are blocked because- * enrollment writes a row to the shared pool. `devices.userId` records the- * first enroller of each `(workspaceId, deviceId)` pair and is preserved on- * re-enroll (see `DeviceModel.registerWorkspaceDevice`), which- * `updateWorkspaceDevice` / `removeWorkspaceDevice` use to gate writes to- * "self or owner". Used by `lh connect --workspace` after minting the- * connect token.- */- registerWorkspaceDevice: wsWritableProcedure- .use(serverDatabase)- .input(- z.object({- architecture: z.string().max(20).nullish(),- deviceId: z.string().min(1).max(64),- hostname: z.string().nullish(),- identitySource: z.enum(['machine-id', 'fallback']),- /** Extensible client-reported info bag; free-form, size-capped to guard the column. */- metadata: z- .record(z.string().max(64), z.string().max(200))- .refine((m) => Object.keys(m).length <= 20, 'metadata supports at most 20 keys')- .nullish(),- platform: z.string().max(20).nullish(),- // 'private' enrolls the device for the calling member only (settings- // page "Private" tab / `lh connect --workspace <id> --private`);- // defaults to the shared pool. Preserved on re-enroll β see- // `DeviceModel.registerWorkspaceDevice`.- visibility: z.enum(['private', 'public']).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- try {- return await model.registerWorkspaceDevice({ ...input, workspaceId: ctx.workspaceId });- } catch (error) {- if (error instanceof WorkspaceDevicePrivateConflictError) {- throw new TRPCError({ code: 'CONFLICT', message: error.message });- }- throw error;- }- }),-- /**- * Share one of the caller's PERSONAL devices into the current workspace- * without touching the machine: dispatch an `enrollWorkspace` RPC over the- * device's live personal connection (it derives its workspace-scoped- * deviceId and opens a second gateway connection with the minted token),- * then register the workspace row here β linked back to the personal device- * via `sharedFromDeviceId` so the personal list can render and revoke the- * share. Requires the device to be ONLINE; an offline device fails with- * PRECONDITION_FAILED and the UI keeps its share action disabled.- *- * Same write gate as enrolling on the machine (`wsWritableProcedure`:- * member+, viewers blocked). Visibility defaults to 'private' β see- * `DeviceModel.registerWorkspaceDevice`.- *- * The machine may ALREADY be enrolled in this workspace (e.g. via- * `lh connect --workspace`, which the personal share map can't link to).- * Silently upserting would discard the caller's explicit visibility choice- * (the conflict branch preserves the existing value), so instead the first- * call reports `alreadyEnrolled` without writing; a `confirmOverwrite`- * retry applies the requested visibility and links the row back to the- * personal device.- */- shareDeviceToWorkspace: wsWritableProcedure- .use(serverDatabase)- .input(- z.object({- confirmOverwrite: z.boolean().optional(),- deviceId: z.string().min(1).max(64),- visibility: z.enum(['private', 'public']).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const personal = await model.findByDeviceId(input.deviceId);- // findByDeviceId is (userId, deviceId)-scoped; exclude workspace rows the- // caller enrolled so only true personal devices are shareable.- if (!personal || personal.workspaceId) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Personal device not found.' });- }-- const token = await signWorkspaceDeviceToken(ctx.workspaceId);- // Identity-only probe: learn the machine's workspace deviceId WITHOUT the- // device opening or persisting a share connection, so backing out of the- // overwrite confirmation leaves the device untouched. Older clients- // ignore the flag and enroll here β that degrades to the pre-flag- // behaviour, never worse.- const probe = await deviceGateway.enrollWorkspace({- deviceId: personal.deviceId,- identityOnly: true,- token,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (!probe.success || !probe.identity) {- throw new TRPCError({- code: 'PRECONDITION_FAILED',- message: probe.error ?? 'Device is offline or does not support workspace sharing.',- });- }-- // Fail a cross-user PRIVATE collision NOW, before the machine opens and- // persists a workspace share connection β rejecting only at the later- // row write would leave the device connected (and auto-reconnecting)- // under the very id the rejection protects.- try {- await model.assertNoCrossUserPrivateConflict(probe.identity.deviceId);- } catch (error) {- if (error instanceof WorkspaceDevicePrivateConflictError) {- throw new TRPCError({ code: 'CONFLICT', message: error.message });- }- throw error;- }-- // Caller-invisible rows (another member's private enrollment) were- // rejected above, so an undefined here really means "no row yet".- const existing = await model.findWorkspaceDeviceById(probe.identity.deviceId);- if (existing) {- if (!input.confirmOverwrite) {- return {- alreadyEnrolled: true as const,- deviceId: existing.deviceId,- success: false as const,- visibility: existing.visibility,- };- }- const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;- if (!canEditWorkspaceDevice(role, ctx.userId, existing.userId)) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Only the enrolling member or a workspace owner can overwrite this device.',- });- }- if ((input.visibility ?? 'private') === 'private') {- await assertDeviceNotBoundToFixedAgent(model, existing.deviceId);- }- }-- // Real enrollment β only after the caller is committed (no pending- // confirmation and permission checks passed).- const result = await deviceGateway.enrollWorkspace({- deviceId: personal.deviceId,- token,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (!result.success || !result.identity) {- throw new TRPCError({- code: 'PRECONDITION_FAILED',- message: result.error ?? 'Device is offline or does not support workspace sharing.',- });- }-- if (existing) {- const row = await model.overwriteSharedWorkspaceDevice(existing.deviceId, {- sharedFromDeviceId: personal.deviceId,- visibility: input.visibility ?? 'private',- });- if (personal.friendlyName && !row?.friendlyName) {- await model.updateWorkspaceDevice(existing.deviceId, {- friendlyName: personal.friendlyName,- });- }- return {- deviceId: existing.deviceId,- success: true as const,- visibility: row?.visibility ?? input.visibility ?? 'private',- };- }-- let row;- try {- row = await model.registerWorkspaceDevice({- deviceId: result.identity.deviceId,- hostname: personal.hostname,- identitySource: result.identity.identitySource,- platform: personal.platform,- sharedFromDeviceId: personal.deviceId,- visibility: input.visibility,- workspaceId: ctx.workspaceId,- });- } catch (error) {- // The machine has already opened and persisted a share connection- // above, and this (private-by-default) row is what hides it from other- // members β on ANY write failure (conflict race, transient DB error),- // best-effort roll the connection back so it doesn't linger as an- // unregistered workspace ghost, then surface the original error.- await deviceGateway.unenrollWorkspace({- deviceId: result.identity.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (error instanceof WorkspaceDevicePrivateConflictError) {- throw new TRPCError({ code: 'CONFLICT', message: error.message });- }- throw error;- }- // Carry the personal alias over on first share so the workspace list shows- // the machine under the name its owner gave it; never clobber a name a- // re-share conflict-preserved.- if (personal.friendlyName && !row.friendlyName) {- await model.updateWorkspaceDevice(row.deviceId, { friendlyName: personal.friendlyName });- }-- return { deviceId: row.deviceId, success: true as const, visibility: row.visibility };- }),-- /**- * Publish a private workspace device to the shared pool, or pull a public one- * back to private. Mirrors the agent/file `setVisibility` contract:- * - the enrolling member may toggle their own device both ways;- * - nobody else may touch visibility: owners demoting another- * member's public device would appropriate it into that member's private- * list, and other members' private devices are invisible to everyone- * else by design (the lookup below already fails closed with NOT_FOUND),- * so the whole toggle is effectively enroller-only.- */- setWorkspaceDeviceVisibility: wsWritableProcedure- .use(serverDatabase)- .input(- z.object({- deviceId: z.string(),- visibility: z.enum(['private', 'public']),- }),- )- .mutation(async ({ ctx, input }) => {- const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const row = await model.findWorkspaceDeviceById(input.deviceId);- if (!row) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });- }- if (row.visibility === input.visibility) return { success: true };- if (row.userId !== ctx.userId) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Only the enrolling member can change this device visibility.',- });- }- if (input.visibility === 'private') {- await assertDeviceNotBoundToFixedAgent(model, input.deviceId);- }- await model.setWorkspaceDeviceVisibility(input.deviceId, input.visibility);- return { success: true };- }),-- /**- * Rename / replace the working dirs of a WORKSPACE device (enroller or owner only).- * Members edit one recent dir via `workspaceDeviceWorkingDirProcedures`.- */- updateWorkspaceDevice: wsWritableProcedure- .use(serverDatabase)- .input(- z.object({- defaultCwd: z.string().nullish(),- deviceId: z.string(),- friendlyName: z.string().max(100).nullish(),- workingDirs: z.array(workingDirConfigSchema).max(20).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const { deviceId, workingDirs, ...value } = input;- const row = await model.findWorkspaceDeviceById(deviceId);- if (!row) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });- }- const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;- assertWorkspaceDeviceEditable(role, ctx.userId, row.userId);- const nextWorkingDirs = workingDirs- ? preserveWorkspaceCache(workingDirs, row.workingDirs ?? [])- : undefined;- await model.updateWorkspaceDevice(deviceId, { ...value, workingDirs: nextWorkingDirs });- return { success: true };- }),-- /**- * Remove a WORKSPACE device. Scoped by `workspace_id` and gated by- * {@link canEditWorkspaceDevice}: owners may remove any device in the pool;- * members may remove only devices they enrolled themselves.- */- removeWorkspaceDevice: wsWritableProcedure- .use(serverDatabase)- .input(z.object({ deviceId: z.string() }))- .mutation(async ({ ctx, input }) => {- const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const row = await model.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 remove this device.',- });- }- await assertDeviceNotBoundToFixedAgent(model, input.deviceId);- // Tell a live device to drop its workspace connection and stop- // auto-reconnecting, so removal doesn't leave an online ghost. For most- // rows this stays best-effort β an offline device simply stops resolving.- const unenrolled = await deviceGateway.unenrollWorkspace({- deviceId: input.deviceId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- // But never delete the row under a still-live socket that did not- // acknowledge the unenroll (old client without the handler, RPC error):- // for a PRIVATE row that would resurface the machine to other members- // (the row is the only thing `queryWorkspaceHiddenDeviceIds` hides it- // by), and for ANY row it leaves an unregistered ghost that members can- // still dispatch to yet can no longer remove β there is no row left to- // delete. Fail the removal while the socket is demonstrably alive; a- // dead socket can't ghost, so an offline device still deletes fine.- if (!unenrolled.success) {- const online = await deviceGateway.queryDeviceList(ctx.userId, ctx.workspaceId);- if (online.some((d) => d.deviceId === input.deviceId)) {- throw new TRPCError({- code: 'PRECONDITION_FAILED',- message:- 'The device is still connected but did not acknowledge the unenroll β retry once it has disconnected or updated its client.',- });- }- }- await model.deleteWorkspaceDevice(input.deviceId);- return { success: true };- }),-- /**- * Auto-register the calling device (desktop after OIDC login / CLI on first- * `lh connect`). Upserts on (userId, deviceId); user-owned fields are- * preserved on conflict.- */- register: deviceProcedure- .input(- z.object({- architecture: z.string().max(20).nullish(),- deviceId: z.string().min(1).max(64),- hostname: z.string().nullish(),- identitySource: z.enum(['machine-id', 'fallback']),- /** Extensible client-reported info bag; free-form, size-capped to guard the column. */- metadata: z- .record(z.string().max(64), z.string().max(200))- .refine((m) => Object.keys(m).length <= 20, 'metadata supports at most 20 keys')- .nullish(),- platform: z.string().max(20).nullish(),- }),- )- .mutation(async ({ ctx, input }) => {- return ctx.deviceModel.register(input);- }),-- removeDevice: deviceProcedure- .input(z.object({ deviceId: z.string() }))- .mutation(async ({ ctx, input }) => {- await ctx.deviceModel.delete(input.deviceId);- return { success: true };- }),-- status: deviceProcedure.query(async ({ ctx }) => {- return deviceGateway.queryDeviceStatus(ctx.userId, ctx.workspaceId);- }),-- /** User-editable fields only β never the machine-reported identity columns. */- updateDevice: deviceProcedure- .input(- z.object({- defaultCwd: z.string().nullish(),- deviceId: z.string(),- friendlyName: z.string().max(100).nullish(),- workingDirs: z.array(workingDirConfigSchema).max(20).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- 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 };- }),- updateDeviceInfo: deviceProcedure- .input(- z.object({- architecture: z.string().min(1).max(20).optional(),- deviceId: z.string().min(1).max(64),- hostname: z.string().optional(),- metadata: z- .record(z.string().max(64), z.string().max(200))- .refine((m) => Object.keys(m).length <= 20, 'metadata supports at most 20 keys')- .optional(),- platform: z.string().max(20).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const { deviceId, ...value } = input;- const device = await ctx.deviceModel.updateDeviceInfo(deviceId, value);- if (!device) throw new TRPCError({ code: 'NOT_FOUND', message: 'Device not found' });- return { success: true };- }),-});diff --git a/apps/server/src/routers/lambda/device/agents.ts b/apps/server/src/routers/lambda/device/agents.tsnew file mode 100644index 00000000000..394dc562ede--- /dev/null+++ b/apps/server/src/routers/lambda/device/agents.ts@@ -0,0 +1,199 @@+import {+ type HeterogeneousAgentScanMap,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+} from '@lobechat/heterogeneous-agents';+import { z } from 'zod';++import { deviceGateway } from '@/server/services/deviceGateway';++import { deviceProcedure } from './procedures';++// Derive the zod enum from the canonical config so new platforms are+// automatically covered without touching this file.+const remotePlatformEnum = z.enum(+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => c.type) as [+ (typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'],+ ...(typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'][],+ ],+);++const CAPABILITY_TIMEOUT_MS = 5_000;++const PROFILE_TIMEOUT_MS = 5_000;++// Batch scan probes every agent type (which + --version per binary, with+// login-shell PATH fallback), so it gets a longer budget than a single probe.+const SCAN_TIMEOUT_MS = 10_000;++export const agentsProcedures = {+ /**+ * Probe whether a specific agent platform (openclaw / hermes) is available+ * on the given device. Dispatches a `checkPlatformCapability` tool call to+ * the device via the gateway and waits up to 5 s for a response.+ */+ checkCapability: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ platform: remotePlatformEnum,+ scope: z.enum(['personal', 'workspace']).optional(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.executeToolCall(+ {+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: input.scope === 'personal' ? undefined : ctx.workspaceId,+ },+ {+ apiName: 'checkPlatformCapability',+ arguments: JSON.stringify({ platform: input.platform }),+ identifier: 'local',+ },+ CAPABILITY_TIMEOUT_MS,+ );++ if (!result.success) {+ return { available: false, reason: result.error ?? 'Device tool call failed' };+ }++ try {+ return JSON.parse(result.content) as {+ available: boolean;+ reason?: string;+ version?: string;+ };+ } catch {+ return { available: false, reason: 'Invalid response from device' };+ }+ }),+ /**+ * Scan the given device for every known heterogeneous agent type in one+ * pass. Dispatches a `scanHeterogeneousAgents` tool call to the device via+ * the gateway; the device probes each binary and returns an availability+ * map. On gateway failure (offline device, older client without the tool)+ * returns an empty map plus the error so the client can distinguish+ * "nothing installed" from "scan failed".+ */+ scanAgents: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(+ async ({ ctx, input }): Promise<{ agents: HeterogeneousAgentScanMap; error?: string }> => {+ const result = await deviceGateway.executeToolCall(+ { deviceId: input.deviceId, userId: ctx.userId, workspaceId: ctx.workspaceId },+ {+ apiName: 'scanHeterogeneousAgents',+ arguments: JSON.stringify({}),+ identifier: 'local',+ },+ SCAN_TIMEOUT_MS,+ );++ if (!result.success) {+ return { agents: {}, error: result.error ?? 'Device tool call failed' };+ }++ try {+ const parsed = JSON.parse(result.content) as { agents?: HeterogeneousAgentScanMap };+ return { agents: parsed.agents ?? {} };+ } catch {+ return { agents: {}, error: 'Invalid response from device' };+ }+ },+ ),+ /**+ * Claude Code subscription quota sampled by the device with its own local+ * credentials, so web clients can show live quota for a bound-device run.+ * `null` when the device is offline or its client predates this RPC.+ */+ getClaudeCodeQuota: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ env: z.record(z.string(), z.string()).optional(),+ force: z.boolean().optional(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.claudeCodeQuota({+ deviceId: input.deviceId,+ env: input.env,+ force: input.force,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /** Query a heterogeneous CLI's model catalog on the device that will execute the agent. */+ listHeterogeneousAgentModels: deviceProcedure+ .input(+ z.object({+ args: z.array(z.string()).optional(),+ command: z.string().optional(),+ cwd: z.string().optional(),+ deviceId: z.string(),+ env: z.record(z.string(), z.string()).optional(),+ type: z.enum([+ 'codebuddy',+ 'codex',+ 'cursor',+ 'droid',+ 'devin',+ 'grok-build',+ 'kimi-code',+ 'opencode',+ 'pi',+ 'qoder',+ 'trae',+ ]),+ }),+ )+ .query(async ({ ctx, input }) =>+ deviceGateway.listHeterogeneousAgentModels({+ args: input.args,+ command: input.command,+ cwd: input.cwd,+ deviceId: input.deviceId,+ env: input.env,+ type: input.type,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Fetch the agent profile (title, description, avatar) from the platform+ * installed on the given device. Used to pre-fill the creation modal.+ * Returns an empty object on failure or when the platform has no profile.+ */+ getAgentProfile: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ platform: remotePlatformEnum,+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.executeToolCall(+ { deviceId: input.deviceId, userId: ctx.userId, workspaceId: ctx.workspaceId },+ {+ apiName: 'getAgentProfile',+ arguments: JSON.stringify({ platform: input.platform }),+ identifier: 'local',+ },+ PROFILE_TIMEOUT_MS,+ );++ if (!result.success) return {};++ try {+ return JSON.parse(result.content) as {+ avatar?: string;+ description?: string;+ title?: string;+ };+ } catch {+ return {};+ }+ }),+};diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.tsnew file mode 100644index 00000000000..c923f0bd389--- /dev/null+++ b/apps/server/src/routers/lambda/device/git.ts@@ -0,0 +1,432 @@+import { deriveWorktreePath } from '@lobechat/types';+import { z } from 'zod';++import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';+import { deviceGateway } from '@/server/services/deviceGateway';++import { assertWorkspaceRootApproved } from '../deviceWorkspaceGuard';+import { deviceProcedure } from './procedures';++export const gitProcedures = {+ /**+ * Granular git reads for a directory on a remote device, each via its own+ * device RPC so the web/remote git status bar mirrors the local desktop's+ * separate, differently-cadenced SWR hooks. Return `null` when offline / the+ * directory isn't a git repo.+ */+ gitBranch: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitBranch({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ gitLinkedPullRequest: deviceProcedure+ .input(+ z.object({+ branch: z.string(),+ deviceId: z.string(),+ path: z.string(),+ pullRequestNumber: z.number().optional(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitLinkedPullRequest({+ branch: input.branch,+ deviceId: input.deviceId,+ path: input.path,+ pullRequestNumber: input.pullRequestNumber,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ gitPullRequestDetail: deviceProcedure+ .input(+ z.object({+ coreOnly: z.boolean().optional(),+ deviceId: z.string(),+ number: z.number().int().positive(),+ path: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitPullRequestDetail({+ coreOnly: input.coreOnly,+ deviceId: input.deviceId,+ number: input.number,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ gitPullRequestActivity: deviceProcedure+ .input(+ z.object({ deviceId: z.string(), number: z.number().int().positive(), path: z.string() }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitPullRequestActivity({+ deviceId: input.deviceId,+ number: input.number,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ gitPullRequestMergeContext: deviceProcedure+ .input(+ z.object({+ baseRefName: z.string(),+ deviceId: z.string(),+ headRefOid: z.string().regex(/^[a-f\d]{40}$/i),+ number: z.number().int().positive(),+ path: z.string(),+ repo: z.object({ name: z.string(), owner: z.string() }),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitPullRequestMergeContext({+ ...input,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ gitWorkingTreeStatus: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitWorkingTreeStatus({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ gitAheadBehind: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.gitAheadBehind({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * List the git worktrees attached to the same repository as a directory on a+ * remote device, via the device's `listGitWorktrees` RPC. Lets the web/remote+ * worktree picker mirror the local desktop's, populated over IPC.+ */+ listGitWorktrees: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.listGitWorktrees({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? [];+ }),+ /**+ * List the local branches of a directory on a remote device, via the device's+ * `listGitBranches` RPC. Lets the web/remote branch switcher populate the same+ * dropdown the local desktop renders over IPC.+ */+ listGitBranches: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ path: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.listGitBranches({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? [];+ }),+ /**+ * Checkout (or create) a branch in a directory on a remote device, via the+ * device's `checkoutGitBranch` RPC.+ */+ checkoutGitBranch: deviceProcedure+ .input(+ z.object({+ branch: z.string(),+ create: z.boolean().optional(),+ deviceId: z.string(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.checkoutGitBranch({+ branch: input.branch,+ create: input.create,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Rename a branch in a directory on a remote device, via the device's+ * `renameGitBranch` RPC.+ */+ renameGitBranch: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ from: z.string(),+ path: z.string(),+ to: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.renameGitBranch({+ deviceId: input.deviceId,+ from: input.from,+ path: input.path,+ to: input.to,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Delete a branch in a directory on a remote device, via the device's+ * `deleteGitBranch` RPC.+ */+ deleteGitBranch: deviceProcedure+ .input(+ z.object({+ branch: z.string(),+ deviceId: z.string(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.deleteGitBranch({+ branch: input.branch,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Remove a worktree in a directory's repository on a remote device,+ * via the device's `removeGitWorktree` RPC.+ */+ removeGitWorktree: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ path: z.string(),+ worktreePath: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.removeGitWorktree({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ worktreePath: input.worktreePath,+ }),+ ),+ /**+ * Add a linked worktree on a fresh branch in a directory's repository on a+ * remote device, via the device's `addGitWorktree` RPC.+ *+ * The target directory is derived here from the trusted `path` + `branch`+ * (a `<repo>-<branch>` sibling) rather than accepted from the request, so a+ * crafted web call can't ask the device to check out at an arbitrary absolute+ * path β the branch is folded to `-` in the folder name, so it can't traverse.+ */+ addGitWorktree: deviceProcedure+ .input(+ z.object({+ branch: z.string(),+ deviceId: z.string(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ deviceGateway.addGitWorktree({+ branch: input.branch,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ worktreePath: deriveWorktreePath(input.path, input.branch),+ }),+ ),+ /**+ * Pull (`--ff-only`) the current branch of a directory on a remote device, via+ * the device's `pullGitBranch` RPC.+ */+ pullGitBranch: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .mutation(async ({ ctx, input }) =>+ deviceGateway.pullGitBranch({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Push the current branch of a directory on a remote device, via the device's+ * `pushGitBranch` RPC.+ */+ pushGitBranch: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .mutation(async ({ ctx, input }) =>+ deviceGateway.pushGitBranch({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a+ * directory on a remote device, via the device's `runPullRequestAction` RPC.+ */+ runGitPullRequestAction: deviceProcedure+ .use(requireWorkspaceRoleWhenScoped('member'))+ .input(+ z.object({+ action: z.discriminatedUnion('type', [+ z.object({+ admin: z.boolean().optional(),+ deleteBranch: z.boolean().optional(),+ headRefOid: z.string().regex(/^[a-f\d]{40}$/i),+ method: z.enum(['squash', 'merge', 'rebase']),+ type: z.literal('merge'),+ }),+ z.object({+ headRefOid: z.string().regex(/^[a-f\d]{40}$/i),+ method: z.enum(['squash', 'merge', 'rebase']),+ type: z.literal('autoMerge'),+ }),+ z.object({ type: z.literal('disableAutoMerge') }),+ z.object({ method: z.enum(['merge', 'rebase']), type: z.literal('updateBranch') }),+ z.object({ type: z.literal('ready') }),+ z.object({ body: z.string(), type: z.literal('comment') }),+ z.object({ type: z.literal('close') }),+ z.object({ type: z.literal('reopen') }),+ z.object({ head: z.string(), type: z.literal('deleteBranch') }),+ z.object({ base: z.string(), type: z.literal('changeBase') }),+ ]),+ deviceId: z.string(),+ number: z.number().int().positive(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertWorkspaceRootApproved(+ ctx.deviceModel,+ input.deviceId,+ input.path,+ ctx.workspaceId,+ );+ return deviceGateway.runGitPullRequestAction({+ action: input.action,+ deviceId: input.deviceId,+ number: input.number,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+ /**+ * Working-tree (unstaged) per-file patches for a directory on a remote device,+ * via the device's `getGitWorkingTreePatches` RPC. Powers the web/remote Review+ * panel's unstaged diff. Returns `null` when offline / not a git repo.+ */+ getGitWorkingTreePatches: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.getGitWorkingTreePatches({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * Branch diff (current branch vs base ref) per-file patches for a directory on+ * a remote device, via the device's `getGitBranchDiff` RPC.+ */+ getGitBranchDiff: deviceProcedure+ .input(z.object({ baseRef: z.string().optional(), deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.getGitBranchDiff({+ baseRef: input.baseRef,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * List the remote branches of a directory on a remote device, via the device's+ * `listGitRemoteBranches` RPC. Populates the Review base-ref picker.+ */+ listGitRemoteBranches: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.listGitRemoteBranches({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? [];+ }),+ /**+ * Repo-relative paths of dirty working-tree files for a directory on a remote+ * device, via the device's `getGitWorkingTreeFiles` RPC. Powers the Files tab's+ * git-status overlay. Returns `null` when offline / not a git repo.+ */+ getGitWorkingTreeFiles: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.getGitWorkingTreeFiles({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * Revert a single file in a directory on a remote device, via the device's+ * `revertGitFile` RPC.+ */+ revertGitFile: deviceProcedure+ .input(z.object({ deviceId: z.string(), filePath: z.string(), path: z.string() }))+ .mutation(async ({ ctx, input }) =>+ deviceGateway.revertGitFile({+ deviceId: input.deviceId,+ filePath: input.filePath,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+};diff --git a/apps/server/src/routers/lambda/device/guards.ts b/apps/server/src/routers/lambda/device/guards.tsnew file mode 100644index 00000000000..86b970f8541--- /dev/null+++ b/apps/server/src/routers/lambda/device/guards.ts@@ -0,0 +1,48 @@+import { TRPCError } from '@trpc/server';++import { type WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';+import type { DeviceModel } from '@/database/models/device';++import { canOperateWorkspaceDevice } from '../deviceWorkspaceGuard';++/**+ * A workspace device's user-editable fields (rename, working dirs, remove) may+ * be modified by:+ * 1. any workspace owner β managing shared infra is an owner privilege, OR+ * 2. the workspace member who originally enrolled the device (`devices.userId`+ * stores the first enroller for workspace rows, never overwritten on+ * re-enroll β see `DeviceModel.registerWorkspaceDevice`).+ *+ * Members can therefore self-serve their own machines without touching anyone+ * else's enrollment, while shared cleanup remains an owner action.+ */+/**+ * Gate an action that operates the machine itself β browsing folders, a+ * terminal, exposing a port, updating its app. A public workspace device is+ * shared infra every member works on, so any member may operate it; a private+ * one stays limited to the enrolling member or a workspace owner.+ */+export const assertDeviceOperable = async (+ ctx: {+ deviceModel: DeviceModel;+ userId: string;+ workspaceId?: string;+ workspaceRole?: WorkspaceRole;+ },+ deviceId: string,+ action: string,+) => {+ if (!ctx.workspaceId) return;++ const row = await ctx.deviceModel.findWorkspaceDeviceById(deviceId);+ if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });+ if (!canOperateWorkspaceDevice(ctx.workspaceRole, ctx.userId, row)) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message:+ row.visibility === 'public'+ ? `Workspace viewers cannot ${action} on this device.`+ : `Only the enrolling member or a workspace owner can ${action} on this private device.`,+ });+ }+};diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.tsnew file mode 100644index 00000000000..23689f96318--- /dev/null+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts@@ -0,0 +1,106 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { deviceRouter } from '.';++/**+ * Pins the router's public surface: every procedure path, its kind, and its+ * middleware chain length (which encodes the procedure builder and its input+ * parsers). Splitting the router across files must keep all three.+ */+describe('deviceRouter procedures', () => {+ const procedures = (deviceRouter as any)._def.procedures as Record<string, any>;++ it('exposes exactly the expected procedure paths', () => {+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));+ });++ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {+ expect(procedures[name]._def.type).toBe(type);+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);+ });+});++function expected(): Array<+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]+> {+ return [+ ['addGitWorktree', 'mutation', 12],+ ['addWorkspaceDeviceWorkingDir', 'mutation', 13],+ ['browseDirectory', 'query', 12],+ ['checkAppUpdate', 'mutation', 12],+ ['checkCapability', 'query', 12],+ ['checkCliUpdate', 'mutation', 12],+ ['checkoutGitBranch', 'mutation', 12],+ ['closeTerminal', 'mutation', 12],+ ['copyAssetForPublish', 'mutation', 15],+ ['copyProjectFiles', 'mutation', 15],+ ['createDirectory', 'mutation', 12],+ ['createProjectDirectory', 'mutation', 15],+ ['createProjectFile', 'mutation', 15],+ ['createTerminalSession', 'mutation', 12],+ ['createTunnel', 'mutation', 12],+ ['deleteGitBranch', 'mutation', 12],+ ['getAgentProfile', 'query', 12],+ ['getAppUpdateState', 'query', 12],+ ['getClaudeCodeQuota', 'query', 12],+ ['getCliUpdateState', 'query', 12],+ ['getDeviceActivity', 'query', 12],+ ['getDeviceSystemInfo', 'query', 12],+ ['getGitBranchDiff', 'query', 12],+ ['getGitWorkingTreeFiles', 'query', 12],+ ['getGitWorkingTreePatches', 'query', 12],+ ['getLocalFilePreview', 'query', 14],+ ['getProjectFileIndex', 'query', 12],+ ['getRunningSummary', 'query', 11],+ ['gitAheadBehind', 'query', 12],+ ['gitBranch', 'query', 12],+ ['gitLinkedPullRequest', 'query', 12],+ ['gitPullRequestActivity', 'query', 12],+ ['gitPullRequestDetail', 'query', 12],+ ['gitPullRequestMergeContext', 'query', 12],+ ['gitWorkingTreeStatus', 'query', 12],+ ['installAppUpdate', 'mutation', 12],+ ['listDevices', 'query', 11],+ ['listGitBranches', 'query', 12],+ ['listGitRemoteBranches', 'query', 12],+ ['listGitWorktrees', 'query', 12],+ ['listHeterogeneousAgentModels', 'query', 12],+ ['listListeningPorts', 'query', 12],+ ['listProjectDirectory', 'query', 12],+ ['listProjectSkills', 'query', 12],+ ['listTunnels', 'query', 12],+ ['mintWorkspaceConnectToken', 'mutation', 10],+ ['moveProjectFiles', 'mutation', 15],+ ['openTunnel', 'mutation', 12],+ ['pullGitBranch', 'mutation', 12],+ ['pushGitBranch', 'mutation', 12],+ ['readExternalAssetForPublish', 'query', 15],+ ['readTerminal', 'mutation', 12],+ ['register', 'mutation', 12],+ ['registerWorkspaceDevice', 'mutation', 12],+ ['removeDevice', 'mutation', 12],+ ['removeGitWorktree', 'mutation', 12],+ ['removeWorkspaceDevice', 'mutation', 12],+ ['removeWorkspaceDeviceWorkingDir', 'mutation', 13],+ ['renameGitBranch', 'mutation', 12],+ ['renameProjectFile', 'mutation', 15],+ ['resizeTerminal', 'mutation', 12],+ ['restartCli', 'mutation', 12],+ ['revertGitFile', 'mutation', 12],+ ['revokeTunnel', 'mutation', 12],+ ['runGitPullRequestAction', 'mutation', 13],+ ['scanAgents', 'query', 12],+ ['searchProjectFiles', 'query', 12],+ ['setWorkspaceDeviceVisibility', 'mutation', 12],+ ['shareDeviceToWorkspace', 'mutation', 12],+ ['statPath', 'query', 12],+ ['status', 'query', 11],+ ['trashProjectFiles', 'mutation', 15],+ ['updateDevice', 'mutation', 12],+ ['updateDeviceInfo', 'mutation', 12],+ ['updateWorkspaceDevice', 'mutation', 12],+ ['writeProjectFile', 'mutation', 15],+ ['writeTerminal', 'mutation', 12],+ ];+}diff --git a/apps/server/src/routers/lambda/device/index.ts b/apps/server/src/routers/lambda/device/index.tsnew file mode 100644index 00000000000..22e782ccf5e--- /dev/null+++ b/apps/server/src/routers/lambda/device/index.ts@@ -0,0 +1,19 @@+import { router } from '@/libs/trpc/lambda';++import { workspaceDeviceWorkingDirProcedures } from '../deviceWorkspaceWorkingDirs';+import { agentsProcedures } from './agents';+import { gitProcedures } from './git';+import { operateProcedures } from './operate';+import { projectFilesProcedures } from './projectFiles';+import { registryProcedures } from './registry';+import { workspaceProcedures } from './workspace';++export const deviceRouter = router({+ ...workspaceDeviceWorkingDirProcedures,+ ...agentsProcedures,+ ...registryProcedures,+ ...gitProcedures,+ ...projectFilesProcedures,+ ...operateProcedures,+ ...workspaceProcedures,+});diff --git a/apps/server/src/routers/lambda/device/operate.ts b/apps/server/src/routers/lambda/device/operate.tsnew file mode 100644index 00000000000..6872a091951--- /dev/null+++ b/apps/server/src/routers/lambda/device/operate.ts@@ -0,0 +1,312 @@+import { TUNNEL_TOKEN_PARAM } from '@lobechat/device-gateway-client';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { signTunnelAccessToken } from '@/libs/trpc/utils/internalJwt';+import { deviceGateway } from '@/server/services/deviceGateway';+import { deviceTunnels, TUNNEL_MAX_TTL_SECONDS } from '@/server/services/deviceGateway/tunnels';++import { assertDeviceOperable } from './guards';+import { deviceProcedure } from './procedures';++/** Exposing a port is at least as sensitive as reading the filesystem. */+const assertTunnelDeviceWritable = (+ ctx: Parameters<typeof assertDeviceOperable>[0],+ deviceId: string,+) => assertDeviceOperable(ctx, deviceId, 'expose a port');++/**+ * Base64 characters accepted by one `writeTerminal` call. A keystroke is a+ * handful of bytes; this only bounds what a malicious caller can push through+ * in a single request.+ */+const MAX_TERMINAL_WRITE_CHARS = 65_536;++/**+ * Relay a terminal call, surfacing the device's own reason. A device that is+ * offline β or a client without PTY support β answers with a message the user+ * needs to read; a bare 500 would make it look like a LobeHub bug.+ */+const relayTerminal = async <T>(run: () => Promise<T>): Promise<T> => {+ try {+ return await run();+ } catch (error) {+ throw new TRPCError({+ code: 'BAD_GATEWAY',+ message: error instanceof Error ? error.message : String(error),+ });+ }+};++/** Append a freshly minted access token to a tunnel URL. */+const buildTunnelOpenUrl = async (+ url: string,+ ctx: { userId: string; workspaceId?: string },+): Promise<string> => {+ const token = await signTunnelAccessToken({+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ // A dedicated param, not `?token=`: apps behind a tunnel own that name+ // (Vite's HMR socket authenticates with it).+ return `${url}?${TUNNEL_TOKEN_PARAM}=${encodeURIComponent(token)}`;+};++export const operateProcedures = {+ /** Open a link to `port` on a device. */+ createTunnel: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ port: z.number().int().min(1).max(65_535),+ ttlSeconds: z.number().int().positive().max(TUNNEL_MAX_TTL_SECONDS).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertTunnelDeviceWritable(ctx, input.deviceId);++ const link = await deviceTunnels.create({+ deviceId: input.deviceId,+ port: input.port,+ ttlSeconds: input.ttlSeconds,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (!link) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'Device gateway is not configured on this deployment.',+ });+ }++ return { ...link, openUrl: await buildTunnelOpenUrl(link.url, ctx) };+ }),+ /**+ * Ports the device is listening on, so the UI can offer "5173 Β· vite" to+ * expose in one click. Gated like creating a tunnel: seeing which ports are+ * open is only useful to someone allowed to expose them. `null` means the+ * device couldn't answer (offline, or a client that predates detection).+ */+ listListeningPorts: deviceProcedure+ .input(z.object({ cwd: z.string().optional(), deviceId: z.string() }))+ .query(async ({ ctx, input }) => {+ await assertTunnelDeviceWritable(ctx, input.deviceId);+ const result = await deviceGateway.listListeningPorts({+ cwd: input.cwd,+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),++ // βββ Remote app update βββ+ //+ // Update the desktop app on a device from anywhere: check (a found update+ // downloads on its own), poll progress, then restart into it. Restarting+ // interrupts whatever the machine is running, so every step is gated like+ // exposing a port.+ getAppUpdateState: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'update the app');+ return deviceGateway.getAppUpdateState({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+ checkAppUpdate: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'update the app');+ return deviceGateway.checkAppUpdate({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+ installAppUpdate: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'update the app');+ return deviceGateway.installAppUpdate({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),++ // βββ Interactive terminal βββ+ //+ // A terminal hands the caller a shell on the device, so it is gated exactly+ // like exposing a port. The check runs on the polling reads too, not just on+ // create β otherwise a session would outlive the permission that opened it.+ createTerminalSession: deviceProcedure+ .input(+ z.object({+ cols: z.number().int().min(1).max(1000),+ cwd: z.string().optional(),+ deviceId: z.string(),+ rows: z.number().int().min(1).max(1000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'open a terminal on');+ return relayTerminal(() =>+ deviceGateway.createTerminalSession({+ cols: input.cols,+ cwd: input.cwd,+ deviceId: input.deviceId,+ rows: input.rows,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),+ writeTerminal: deviceProcedure+ .input(+ z.object({+ /** Base64 keystrokes. */+ data: z.string().max(MAX_TERMINAL_WRITE_CHARS),+ deviceId: z.string(),+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.writeTerminal({+ data: input.data,+ deviceId: input.deviceId,+ id: input.id,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),+ readTerminal: deviceProcedure+ .input(z.object({ cursor: z.number().int().min(0), deviceId: z.string(), id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.readTerminal({+ cursor: input.cursor,+ deviceId: input.deviceId,+ id: input.id,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),+ resizeTerminal: deviceProcedure+ .input(+ z.object({+ cols: z.number().int().min(1).max(1000),+ deviceId: z.string(),+ id: z.string(),+ rows: z.number().int().min(1).max(1000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.resizeTerminal({+ cols: input.cols,+ deviceId: input.deviceId,+ id: input.id,+ rows: input.rows,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),+ closeTerminal: deviceProcedure+ .input(z.object({ deviceId: z.string(), id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'use a terminal on');+ return relayTerminal(() =>+ deviceGateway.closeTerminal({+ deviceId: input.deviceId,+ id: input.id,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ );+ }),+ getCliUpdateState: deviceProcedure+ .input(z.object({ deviceId: z.string() }).strict())+ .query(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');+ return deviceGateway.getCliUpdateState({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+ checkCliUpdate: deviceProcedure+ .input(z.object({ deviceId: z.string() }).strict())+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');+ return deviceGateway.checkCliUpdate({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+ restartCli: deviceProcedure+ .input(+ z+ .object({ deviceId: z.string(), requestId: z.string().uuid(), update: z.boolean() })+ .strict(),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');+ return deviceGateway.restartCli({+ ...input,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+ /** Live tunnel links the caller can reach, newest first. */+ listTunnels: deviceProcedure+ .input(z.object({ deviceId: z.string().optional() }).optional())+ .query(async ({ ctx, input }) =>+ deviceTunnels.list({+ deviceId: input?.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ),+ /**+ * Mint the one-shot token that opens an existing link. Tokens are minted per+ * click rather than stored with the link: the gateway swaps the token for a+ * session cookie on first use, so the URL in hand stays clean.+ */+ openTunnel: deviceProcedure+ .input(z.object({ slug: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const links = await deviceTunnels.list({ userId: ctx.userId, workspaceId: ctx.workspaceId });+ const link = links.find((candidate) => candidate.slug === input.slug);+ if (!link) throw new TRPCError({ code: 'NOT_FOUND', message: 'Tunnel not found.' });++ return { openUrl: await buildTunnelOpenUrl(link.url, ctx), url: link.url };+ }),+ /** Revoke a link. Its session cookies stop resolving immediately. */+ revokeTunnel: deviceProcedure+ .input(z.object({ slug: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const outcome = await deviceTunnels.revoke({+ slug: input.slug,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (outcome === 'forbidden') {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This tunnel belongs to someone else.' });+ }+ if (outcome === 'not-found') {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Tunnel not found.' });+ }+ return { success: true };+ }),+};diff --git a/apps/server/src/routers/lambda/device/procedures.ts b/apps/server/src/routers/lambda/device/procedures.tsnew file mode 100644index 00000000000..5779a3125b5--- /dev/null+++ b/apps/server/src/routers/lambda/device/procedures.ts@@ -0,0 +1,33 @@+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { DeviceModel } from '@/database/models/device';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++import { assertWorkspaceDeviceVisible } from '../deviceWorkspaceGuard';++// Workspace-aware (compat): with an `X-Workspace-Id` header the device list also+// surfaces the workspace's shared devices; without it, the personal path is+// unchanged (`ctx.workspaceId === undefined`).+//+// Every route below that takes a `deviceId` input also passes the workspace+// visibility gate β see `assertWorkspaceDeviceVisible` for why filtering the+// list paths alone is not enough.+export const deviceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ const wsId = ctx.workspaceId ?? undefined;+ const deviceModel = new DeviceModel(ctx.serverDB, ctx.userId, wsId);++ if (wsId) {+ const raw = (await opts.getRawInput()) as { deviceId?: unknown } | undefined;+ if (typeof raw?.deviceId === 'string') {+ await assertWorkspaceDeviceVisible(deviceModel, raw.deviceId);+ }+ }++ return opts.next({+ ctx: {+ deviceModel,+ userId: ctx.userId,+ workspaceId: wsId,+ },+ });+});diff --git a/apps/server/src/routers/lambda/device/projectFiles.ts b/apps/server/src/routers/lambda/device/projectFiles.tsnew file mode 100644index 00000000000..34e2139afbe--- /dev/null+++ b/apps/server/src/routers/lambda/device/projectFiles.ts@@ -0,0 +1,412 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';+import { deviceGateway, isValidDirectoryName } from '@/server/services/deviceGateway';++import { assertWorkspaceRootApproved, registerDeviceSkillRoots } from '../deviceWorkspaceGuard';+import { assertDeviceOperable } from './guards';+import { deviceProcedure } from './procedures';++const workspaceFileInput = z.object({+ deviceId: z.string(),+ workingDirectory: z.string(),+});++/**+ * `deviceProcedure` that additionally requires `workingDirectory` to be an+ * approved workspace root for the device. Builds the guard into the procedure+ * so every file-mutating route inherits it and can never forget the check β+ * see {@link assertWorkspaceRootApproved} for why the check is necessary.+ */+const workspaceFileProcedure = deviceProcedure.input(workspaceFileInput).use(async (opts) => {+ const { deviceId, workingDirectory } = workspaceFileInput.parse(await opts.getRawInput());+ await assertWorkspaceRootApproved(+ opts.ctx.deviceModel,+ deviceId,+ workingDirectory,+ opts.ctx.workspaceId,+ );+ return opts.next();+});++/**+ * `workspaceFileProcedure` for routes that change files on the device. In a+ * shared workspace a read-only viewer may browse the tree but not alter it, so+ * writes also need at least the `member` role; personal mode stays open.+ */+const workspaceFileWriteProcedure = workspaceFileProcedure.use(+ requireWorkspaceRoleWhenScoped('member'),+);++/**+ * `workspaceFileProcedure` for the publish-asset routes. Their source path may+ * lie outside the approved root (the device confines only a copy's+ * destination), so they can read any file on the device, and a copy also+ * writes into the workspace. Gate them like writes: a read-only viewer must not+ * pull arbitrary files off a shared device. Personal mode stays open.+ */+const workspacePublishProcedure = workspaceFileProcedure.use(+ requireWorkspaceRoleWhenScoped('member'),+);++export const projectFilesProcedures = {+ /**+ * Project file index (tree) for a directory on a remote device, via the+ * device's `getProjectFileIndex` RPC. Powers the Files tab's tree. Returns+ * `null` when offline.+ */+ getProjectFileIndex: deviceProcedure+ .input(z.object({ deviceId: z.string(), scope: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.getProjectFileIndex({+ deviceId: input.deviceId,+ scope: input.scope,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * Children of one directory inside a project on a remote device. The Files+ * tree calls this when the user expands a directory the index collapsed+ * (a fully git-ignored folder). Returns `null` when offline.+ */+ listProjectDirectory: deviceProcedure+ .input(z.object({ deviceId: z.string(), relativePath: z.string(), root: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.listProjectDirectory({+ deviceId: input.deviceId,+ relativePath: input.relativePath,+ root: input.root,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * Browse one directory level on a remote device. Personal devices belong to+ * the caller; workspace devices follow {@link assertDeviceOperable}.+ */+ 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 }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'browse folders');++ 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;+ }),+ /**+ * Create a folder inside the directory a remote folder picker is browsing, so+ * a new working directory can be made without leaving the picker. Same access+ * rule as {@link browseDirectory}; a taken name is reported as `CONFLICT`.+ */+ createDirectory: deviceProcedure+ .input(+ z.object({+ deviceId: z.string(),+ name: z.string().min(1).max(255),+ parentPath: z.string().min(1),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'create folders');++ if (+ !isValidDirectoryName(input.name, input.parentPath) ||+ !isValidDirectoryName(input.name.trim(), input.parentPath)+ ) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid folder name.' });+ }++ let result: Awaited<ReturnType<typeof deviceGateway.createDirectory>>;+ try {+ result = await deviceGateway.createDirectory({+ deviceId: input.deviceId,+ name: input.name.trim(),+ parentPath: input.parentPath,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ // A device app predating `createLocalDirectory` needs an update, not a retry.+ throw new TRPCError({+ code: /Unknown device RPC method/.test(message) ? 'PRECONDITION_FAILED' : 'BAD_GATEWAY',+ message,+ });+ }++ if (!result.success) {+ throw new TRPCError({+ code: /already exists/i.test(result.error ?? '') ? 'CONFLICT' : 'BAD_REQUEST',+ message: result.error || 'Create folder failed',+ });+ }++ return result;+ }),+ /**+ * Search project files on a remote device. The device performs the match and+ * returns only the result subtree needed by the UI.+ */+ searchProjectFiles: deviceProcedure+ .input(+ z.object({+ changedOnly: z.boolean().optional(),+ deviceId: z.string(),+ excludeIgnored: z.boolean().optional(),+ limit: z.number().int().positive().max(500).optional(),+ query: z.string(),+ scope: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.searchProjectFiles({+ changedOnly: input.changedOnly,+ deviceId: input.deviceId,+ excludeIgnored: input.excludeIgnored,+ limit: input.limit,+ query: input.query,+ scope: input.scope,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+ /**+ * Read-only local file preview for a file on a remote device. The web client+ * receives render data, not a `localfile://` URL; saving remains unsupported.+ */+ getLocalFilePreview: workspaceFileProcedure+ .input(+ z.object({+ accept: z.enum(['image']).optional(),+ path: z.string(),+ }),+ )+ .query(async ({ ctx, input }) => {+ return deviceGateway.getLocalFilePreview({+ accept: input.accept,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ copyAssetForPublish: workspacePublishProcedure+ .input(z.object({ from: z.string(), to: z.string() }))+ .mutation(async ({ ctx, input }) =>+ deviceGateway.copyAssetForPublish({+ deviceId: input.deviceId,+ from: input.from,+ to: input.to,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ }),+ ),+ readExternalAssetForPublish: workspacePublishProcedure+ .input(z.object({ path: z.string() }))+ .query(async ({ ctx, input }) =>+ deviceGateway.readExternalAssetForPublish({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ }),+ ),+ /**+ * Project skills (`.agents/skills` / `.claude/skills`) for a directory on a+ * remote device, via the device's `listProjectSkills` RPC. Powers the+ * Resources tab's skills group in device mode. Returns `null` when offline.+ */+ listProjectSkills: deviceProcedure+ .input(z.object({ deviceId: z.string(), scope: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.listProjectSkills({+ deviceId: input.deviceId,+ scope: input.scope,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ // Register device-scoped skill roots (~/.agents/skills / ~/.claude/skills)+ // in an in-memory cache so subsequent getLocalFilePreview calls pass the+ // workspace root guard without polluting the UI's working-directory list.+ if (result?.skills) {+ const skillRoots = [+ ...new Set(result.skills.filter((s) => s.scope === 'device').map((s) => s.previewRoot)),+ ].filter(Boolean);+ registerDeviceSkillRoots(input.deviceId, skillRoots);+ }++ return result ?? null;+ }),+ /**+ * Move files/folders within a directory on a remote device, via the device's+ * `moveLocalFiles` RPC. Powers the Files tree's drag-to-move in device mode.+ */+ moveProjectFiles: workspaceFileWriteProcedure+ .input(+ z.object({+ items: z.array(z.object({ newPath: z.string(), oldPath: z.string() })),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.moveProjectFiles({+ deviceId: input.deviceId,+ items: input.items,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Rename a single file/folder in a directory on a remote device, via the+ * device's `renameLocalFile` RPC.+ */+ renameProjectFile: workspaceFileWriteProcedure+ .input(+ z.object({+ newName: z.string(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.renameProjectFile({+ deviceId: input.deviceId,+ newName: input.newName,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Save edited content back to a file on a remote device, via the device's+ * `writeLocalFile` RPC. Powers remote save in the LocalFile editor.+ */+ writeProjectFile: workspaceFileWriteProcedure+ .input(+ z.object({+ content: z.string(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.writeProjectFile({+ content: input.content,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Create a new file on a remote device, via the device's `createLocalFile`+ * RPC. Fails instead of overwriting when the path is taken.+ */+ createProjectFile: workspaceFileWriteProcedure+ .input(+ z.object({+ content: z.string().optional(),+ path: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.createProjectFile({+ content: input.content,+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Create a new folder on a remote device, via the device's+ * `createLocalDirectory` RPC. Fails when the path is taken.+ */+ createProjectDirectory: workspaceFileWriteProcedure+ .input(z.object({ path: z.string() }))+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.createProjectDirectory({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Copy files/folders on a remote device, via the device's `copyLocalFiles`+ * RPC. An item without `targetPath` is duplicated in place.+ */+ copyProjectFiles: workspaceFileWriteProcedure+ .input(+ z.object({+ items: z+ .array(z.object({ sourcePath: z.string(), targetPath: z.string().optional() }))+ .min(1),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.copyProjectFiles({+ deviceId: input.deviceId,+ items: input.items,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Move files/folders to a remote device's trash, via the device's+ * `trashLocalFiles` RPC. Devices without a trash reject rather than delete.+ */+ trashProjectFiles: workspaceFileWriteProcedure+ .input(z.object({ paths: z.array(z.string()).min(1) }))+ .mutation(async ({ ctx, input }) => {+ return deviceGateway.trashProjectFiles({+ deviceId: input.deviceId,+ paths: input.paths,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ workingDirectory: input.workingDirectory,+ });+ }),+ /**+ * Check whether a path exists on a remote device and is a directory, via the+ * device's `statPath` RPC. Lets a web client validate a manually-entered+ * working directory before binding it. Returns `null` when the device is+ * unreachable (caller treats "can't verify" as non-blocking).+ */+ statPath: deviceProcedure+ .input(z.object({ deviceId: z.string(), path: z.string() }))+ .query(async ({ ctx, input }) => {+ const result = await deviceGateway.statPath({+ deviceId: input.deviceId,+ path: input.path,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return result ?? null;+ }),+};diff --git a/apps/server/src/routers/lambda/device/registry.ts b/apps/server/src/routers/lambda/device/registry.tsnew file mode 100644index 00000000000..e9cb88b69f2--- /dev/null+++ b/apps/server/src/routers/lambda/device/registry.ts@@ -0,0 +1,406 @@+import type {+ DeviceChannel,+ DeviceEnroller,+ DeviceListItem,+ DeviceRunningSummary,+ DeviceScope,+ DeviceWorkspaceShare,+ WorkingDirEntry,+} from '@lobechat/types';+import { sortDevicesByActivity, workingDirConfigSchema } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { getTopicDeviceId, TopicModel } from '@/database/models/topic';+import { UserModel } from '@/database/models/user';+import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGateway';+import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/scopedDevicePresence';++import { loadDeviceBoundAgents } from '../deviceBoundAgents';+import { preserveWorkspaceCache } from '../deviceWorkingDirs';+import { deviceProcedure } from './procedures';++/**+ * Display info for the members behind a set of running topics. The ids come+ * from topic rows the caller was already allowed to read, so this only adds+ * the public-facing name and avatar.+ */+const loadTopicUsers = async (+ db: Parameters<typeof UserModel.getDisplayInfoByIds>[0],+ userIds: string[],+): Promise<Map<string, DeviceEnroller>> => {+ const rows = await UserModel.getDisplayInfoByIds(db, [...new Set(userIds)]);+ return new Map(+ rows.map((u) => [+ u.id,+ { avatar: u.avatar, fullName: u.fullName, userId: u.id, username: u.username },+ ]),+ );+};++/**+ * The member running each topic now: the initiator of its current run, else+ * its creator (a client-executed run writes no operation row). In a workspace+ * a teammate can continue someone else's topic, so the creator alone would+ * name the wrong person as using the device.+ */+const resolveRunUserIds = async (+ topicModel: TopicModel,+ topics: { id: string; userId: string }[],+): Promise<Map<string, string>> => {+ const initiators = await topicModel.findRunInitiators(topics.map((topic) => topic.id));+ return new Map(topics.map((topic) => [topic.id, initiators.get(topic.id) ?? topic.userId]));+};++/**+ * Upper bound on the running topics read for the device-list summary. A real+ * account runs far fewer at once; the cap only bounds a pathological one.+ */+const RUNNING_SUMMARY_LIMIT = 500;++export const registryProcedures = {+ /**+ * What the device is doing for the caller: topics running on it right now+ * and the agents routed to it. Both reads go through the regular content+ * scopes, so in a workspace a teammate's private agent (and the topics under+ * it) never surface just because they share the machine.+ *+ * Agent bindings are resolved per caller: the stored agency config merged+ * with the caller's own per-agent device override in this workspace, exactly+ * as a run would route β see {@link loadDeviceBoundAgents}.+ */+ getDeviceActivity: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(async ({ ctx, input }) => {+ const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const [agents, runningTopics] = await Promise.all([+ loadDeviceBoundAgents({+ db: ctx.serverDB,+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ topicModel.queryTopics({ deviceId: input.deviceId, statuses: ['running'] }),+ ]);++ const runUserIds = await resolveRunUserIds(topicModel, runningTopics);+ const users = await loadTopicUsers(ctx.serverDB, [...runUserIds.values()]);++ return {+ agents,+ runningTopics: runningTopics.map((topic) => ({+ ...topic,+ user: users.get(runUserIds.get(topic.id) ?? topic.userId) ?? null,+ })),+ };+ }),+ /**+ * Per-device running-topic counts and the members behind them, for the+ * device list cards. One read for the whole list instead of a request per+ * card; the same content scopes as {@link getDeviceActivity} apply, and a+ * device the caller cannot see simply has no card to render its entry.+ */+ getRunningSummary: deviceProcedure.query(async ({ ctx }): Promise<DeviceRunningSummary[]> => {+ // Most recently active first, so each device's avatar stack leads with+ // whoever touched it last.+ const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const runningTopics = (+ await topicModel.queryTopics({ pageSize: RUNNING_SUMMARY_LIMIT, statuses: ['running'] })+ ).filter((topic) => getTopicDeviceId(topic.metadata));+ const runUserIds = await resolveRunUserIds(topicModel, runningTopics);++ const byDevice = new Map<string, { count: number; userIds: string[] }>();+ for (const topic of runningTopics) {+ const deviceId = getTopicDeviceId(topic.metadata)!;+ const runUserId = runUserIds.get(topic.id) ?? topic.userId;+ const entry = byDevice.get(deviceId) ?? { count: 0, userIds: [] };+ entry.count += 1;+ if (!entry.userIds.includes(runUserId)) entry.userIds.push(runUserId);+ byDevice.set(deviceId, entry);+ }++ const users = await loadTopicUsers(+ ctx.serverDB,+ [...byDevice.values()].flatMap((entry) => entry.userIds),+ );++ return [...byDevice].map(([deviceId, { count, userIds }]) => ({+ count,+ deviceId,+ users: userIds.flatMap((id) => users.get(id) ?? []),+ }));+ }),+ getDeviceSystemInfo: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(async ({ ctx, input }) => {+ return deviceGateway.queryDeviceSystemInfo(ctx.userId, input.deviceId, ctx.workspaceId);+ }),+ /**+ * All devices the user has ever registered (incl. offline). A device is keyed+ * by its `deviceId`; the gateway's live WS sessions are NOT separate devices β+ * each session is surfaced as a `channel` nested under its device. A single+ * device may therefore hold multiple channels (e.g. desktop app + CLI both+ * connected at once), and `online` is simply "has at least one live channel".+ *+ * Personal scope is a union rather than only DB rows: auto-registration may+ * briefly lag a live socket. Workspace scope fails closed on visible registry+ * rows because the row is the enrollment and authorization boundary.+ */+ listDevices: deviceProcedure.query(async ({ ctx }): Promise<DeviceListItem[]> => {+ const wsId = ctx.workspaceId;++ // Personal devices resolve under the user principal; workspace devices under+ // the `workspace:<id>` principal (a separate gateway pool). Fetch both.+ const [personalRows, workspaceRows, sharedRows, personalOnline, workspaceOnline] =+ await Promise.all([+ ctx.deviceModel.queryPersonal(),+ wsId ? ctx.deviceModel.queryWorkspaceDevices() : Promise.resolve([]),+ ctx.deviceModel.querySharedWorkspaceDevices(),+ deviceGateway.queryDeviceList(ctx.userId),+ wsId ? deviceGateway.queryDeviceList(ctx.userId, wsId) : Promise.resolve([]),+ ]);++ // Shares the caller created from their personal device list, grouped by the+ // source personal deviceId β attached to personal rows below so the list can+ // render "shared to N workspaces" and revoke individual shares.+ const sharesByPersonalId = new Map<string, DeviceWorkspaceShare[]>();+ for (const s of sharedRows) {+ if (!s.sharedFromDeviceId || !s.workspaceId) continue;+ const list = sharesByPersonalId.get(s.sharedFromDeviceId) ?? [];+ list.push({+ deviceId: s.deviceId,+ visibility: s.visibility,+ workspaceId: s.workspaceId,+ workspaceName: s.workspaceName ?? null,+ });+ sharesByPersonalId.set(s.sharedFromDeviceId, list);+ }++ // Resolve display info for every enroller in a single roundtrip, so each+ // row can ship a self-contained `enroller` for the picker / settings UI.+ // Personal rows always belong to the caller, but the same lookup keeps the+ // shape uniform across scopes.+ const enrollerIds = [...new Set([...personalRows, ...workspaceRows].map((d) => d.userId))];+ const enrollerRows = enrollerIds.length+ ? await UserModel.findByIds(ctx.serverDB, enrollerIds)+ : [];+ const enrollerById = new Map(+ enrollerRows.map((u) => [+ u.id,+ {+ avatar: u.avatar ?? null,+ fullName: u.fullName ?? null,+ userId: u.id,+ username: u.username ?? null,+ },+ ]),+ );++ // The gateway already groups by device, exposing live sessions as nested+ // `channels`. Flatten one connection into the UI-facing channel shape; fall+ // back to a single synthetic channel for a legacy gateway that omits the field.+ const toChannels = (conn: DeviceAttachment): DeviceChannel[] =>+ conn.channels && conn.channels.length > 0+ ? conn.channels.map((c) => ({+ channel: c.channel ?? null,+ connectedAt: c.connectedAt,+ hostname: conn.hostname ?? null,+ platform: conn.platform ?? null,+ }))+ : [+ {+ channel: null,+ connectedAt: conn.lastSeen,+ hostname: conn.hostname ?? null,+ platform: conn.platform ?? null,+ },+ ];++ // Merge a DB-registered set with its live gateway pool into the UI shape.+ // `scope` tags the group; deviceIds never collide across pools (a personal id+ // is derived from userId, a workspace id from workspaceId).+ const buildItems = (+ rows: Awaited<ReturnType<typeof ctx.deviceModel.queryPersonal>>,+ onlineList: DeviceAttachment[],+ scope: DeviceScope,+ ): DeviceListItem[] => {+ const registeredDeviceIds = new Set(rows.map((device) => device.deviceId));+ const channelsByDevice = new Map<string, DeviceChannel[]>();+ for (const conn of filterAuthorizedDevicePresence(registeredDeviceIds, onlineList, scope)) {+ channelsByDevice.set(conn.deviceId, toChannels(conn));+ }++ const seen = new Set<string>();+ const fromDb = rows.map((d): DeviceListItem => {+ seen.add(d.deviceId);+ const channels = channelsByDevice.get(d.deviceId) ?? [];+ const live = channels[0];+ return {+ architecture: d.architecture,+ channels,+ defaultCwd: d.defaultCwd,+ deviceId: d.deviceId,+ // For personal rows this is always the caller; for workspace rows it+ // is the first enroller, surfaced so the UI can gate writes to "self+ // or workspace owner" and render the enroller's avatar without a+ // separate fetch. Falls back to a userId-only stub if the user row+ // was deleted (cascade nullifies devices.userId? no β FK is set, so+ // a stub keeps the gate fail-closed).+ enroller: enrollerById.get(d.userId) ?? {+ avatar: null,+ fullName: null,+ userId: d.userId,+ username: null,+ },+ friendlyName: d.friendlyName,+ hostname: d.hostname ?? live?.hostname ?? null,+ identitySource: d.identitySource,+ lastSeen: d.lastSeenAt.toISOString(),+ metadata: d.metadata,+ online: channels.length > 0,+ platform: d.platform ?? live?.platform ?? null,+ registered: true,+ scope,+ // Workspace rows only: member-shared (via the personal share flow)+ // vs directly enrolled β drives the "Shared by {name}" tag.+ sharedFromPersonal: scope === 'workspace' ? !!d.sharedFromDeviceId : undefined,+ // Personal rows only: the workspaces this machine was shared into+ // from the personal list (undefined for workspace rows and machines+ // never shared).+ sharedWorkspaces: scope === 'personal' ? sharesByPersonalId.get(d.deviceId) : undefined,+ // Personal rows have no workspace-visibility dimension; the column's+ // default is meaningless there, so normalise to null.+ visibility: scope === 'workspace' ? d.visibility : null,+ // Strip the heavy `workspace` scan (AGENTS.md + project skills, up to+ // ~30KB per dir) from the list payload. It's a server-owned cache for+ // the agent runtime (restored from the DB row on run start, never from+ // this response) and no client UI renders it from the list β skills are+ // re-derived live via `device.listProjectSkills`. Keep `workspaceScannedAt`+ // (a cheap number) so clients can still show scan freshness.+ workingDirs: (d.workingDirs ?? []).map(({ workspace: _workspace, ...rest }) => rest),+ };+ });++ // Personal clients auto-register immediately before opening their+ // socket, so preserve their brief Gateway-first race. Workspace rows are+ // authorization: a Gateway-only socket may be a stale process that missed+ // Unshare, and must stay hidden and ineligible.+ const ghosts = [...channelsByDevice.entries()]+ .filter(([deviceId]) => !seen.has(deviceId))+ .map(([deviceId, channels]): DeviceListItem => ({+ channels,+ defaultCwd: null,+ deviceId,+ // No row yet β no enroller; UI gates treat this as not-editable.+ enroller: null,+ friendlyName: null,+ hostname: channels[0]?.hostname ?? null,+ identitySource: null,+ lastSeen: channels[0]?.connectedAt ?? new Date().toISOString(),+ online: true,+ platform: channels[0]?.platform ?? null,+ registered: false,+ scope,+ visibility: null,+ workingDirs: [] as WorkingDirEntry[],+ }));++ return [...fromDb, ...ghosts];+ };++ // Ordered here rather than in SQL: `online` is the primary key and only the+ // gateway knows it, so no per-pool `ORDER BY` can produce it β the two pools+ // and their ghosts have to be merged first, then ordered as one list.+ // Consumers (settings list, picker) filter this down to a single scope, and+ // filtering preserves order, so one pass serves every surface.+ return sortDevicesByActivity([+ ...buildItems(personalRows, personalOnline, 'personal'),+ ...buildItems(workspaceRows, workspaceOnline, 'workspace'),+ ]);+ }),++ // βββ Tunnel links βββ+ //+ // A tunnel makes one loopback port on a device reachable at+ // `https://<port>--<slug>.lobe.sh/`. Creating one is gated exactly like+ // browsing the device's filesystem: on a public workspace device any+ // non-viewer member may expose a port; on a private one, only the enrolling+ // member or an owner.+ /**+ * Auto-register the calling device (desktop after OIDC login / CLI on first+ * `lh connect`). Upserts on (userId, deviceId); user-owned fields are+ * preserved on conflict.+ */+ register: deviceProcedure+ .input(+ z.object({+ architecture: z.string().max(20).nullish(),+ deviceId: z.string().min(1).max(64),+ hostname: z.string().nullish(),+ identitySource: z.enum(['machine-id', 'fallback']),+ /** Extensible client-reported info bag; free-form, size-capped to guard the column. */+ metadata: z+ .record(z.string().max(64), z.string().max(200))+ .refine((m) => Object.keys(m).length <= 20, 'metadata supports at most 20 keys')+ .nullish(),+ platform: z.string().max(20).nullish(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.deviceModel.register(input);+ }),+ removeDevice: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await ctx.deviceModel.delete(input.deviceId);+ return { success: true };+ }),+ status: deviceProcedure.query(async ({ ctx }) => {+ return deviceGateway.queryDeviceStatus(ctx.userId, ctx.workspaceId);+ }),+ /** User-editable fields only β never the machine-reported identity columns. */+ updateDevice: deviceProcedure+ .input(+ z.object({+ defaultCwd: z.string().nullish(),+ deviceId: z.string(),+ friendlyName: z.string().max(100).nullish(),+ workingDirs: z.array(workingDirConfigSchema).max(20).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ 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 };+ }),+ updateDeviceInfo: deviceProcedure+ .input(+ z.object({+ architecture: z.string().min(1).max(20).optional(),+ deviceId: z.string().min(1).max(64),+ hostname: z.string().optional(),+ metadata: z+ .record(z.string().max(64), z.string().max(200))+ .refine((m) => Object.keys(m).length <= 20, 'metadata supports at most 20 keys')+ .optional(),+ platform: z.string().max(20).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { deviceId, ...value } = input;+ const device = await ctx.deviceModel.updateDeviceInfo(deviceId, value);+ if (!device) throw new TRPCError({ code: 'NOT_FOUND', message: 'Device not found' });+ return { success: true };+ }),+};diff --git a/apps/server/src/routers/lambda/device/workspace.ts b/apps/server/src/routers/lambda/device/workspace.tsnew file mode 100644index 00000000000..55178998d22--- /dev/null+++ b/apps/server/src/routers/lambda/device/workspace.ts@@ -0,0 +1,383 @@+import { workingDirConfigSchema } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import {+ requireWorkspaceRole,+ type WorkspaceRole,+ wsProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';+import { DeviceModel, WorkspaceDevicePrivateConflictError } from '@/database/models/device';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { signWorkspaceDeviceToken } from '@/libs/trpc/utils/internalJwt';+import { deviceGateway } from '@/server/services/deviceGateway';++import { preserveWorkspaceCache } from '../deviceWorkingDirs';+import { assertWorkspaceDeviceEditable, canEditWorkspaceDevice } from '../deviceWorkspaceGuard';++/**+ * Fixed workspace agents promise every member the same execution device. Keep+ * that promise intact until an editor changes the agent back to member choice+ * (or binds a different public device) before hiding/removing this row.+ */+const assertDeviceNotBoundToFixedAgent = async (+ model: DeviceModel,+ deviceId: string,+): Promise<void> => {+ if (!(await model.hasFixedAgentBinding(deviceId))) return;++ throw new TRPCError({+ cause: { data: { code: 'DeviceBoundToFixedAgent' } },+ code: 'PRECONDITION_FAILED',+ message:+ 'This device is fixed to one or more workspace agents. Change those agent settings first.',+ });+};++/**+ * Workspace-write gate: membership + at least `member` role (excludes viewer).+ * Enrolling a device mutates the shared workspace device pool, so read-only+ * viewers must not pass β `wsProcedure` alone only checks membership.+ */+const wsWritableProcedure = wsProcedure.use(requireWorkspaceRole('member'));++export const workspaceProcedures = {+ /**+ * Mint a short-lived connect token for enrolling a WORKSPACE-owned device.+ * Workspace members (and owners) can call β enrolling a machine into the+ * shared pool is self-service so members don't have to chase an owner to+ * join their dev box. Viewers are blocked: writing a row to the workspace+ * device pool is a mutation, not a read. The signed token carries the+ * `workspace_id` claim the device gateway trusts to route the device to the+ * `workspace:<id>` principal. The CLI (`lh connect --workspace`) / settings+ * page use this.+ */+ mintWorkspaceConnectToken: wsWritableProcedure.mutation(async ({ ctx }) => {+ const token = await signWorkspaceDeviceToken(ctx.workspaceId);+ return { token, workspaceId: ctx.workspaceId };+ }),+ /**+ * Enroll the calling machine as a device of the current workspace.+ * Workspace members (and owners) may call β viewers are blocked because+ * enrollment writes a row to the shared pool. `devices.userId` records the+ * first enroller of each `(workspaceId, deviceId)` pair and is preserved on+ * re-enroll (see `DeviceModel.registerWorkspaceDevice`), which+ * `updateWorkspaceDevice` / `removeWorkspaceDevice` use to gate writes to+ * "self or owner". Used by `lh connect --workspace` after minting the+ * connect token.+ */+ registerWorkspaceDevice: wsWritableProcedure+ .use(serverDatabase)+ .input(+ z.object({+ architecture: z.string().max(20).nullish(),+ deviceId: z.string().min(1).max(64),+ hostname: z.string().nullish(),+ identitySource: z.enum(['machine-id', 'fallback']),+ /** Extensible client-reported info bag; free-form, size-capped to guard the column. */+ metadata: z+ .record(z.string().max(64), z.string().max(200))+ .refine((m) => Object.keys(m).length <= 20, 'metadata supports at most 20 keys')+ .nullish(),+ platform: z.string().max(20).nullish(),+ // 'private' enrolls the device for the calling member only (settings+ // page "Private" tab / `lh connect --workspace <id> --private`);+ // defaults to the shared pool. Preserved on re-enroll β see+ // `DeviceModel.registerWorkspaceDevice`.+ visibility: z.enum(['private', 'public']).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ try {+ return await model.registerWorkspaceDevice({ ...input, workspaceId: ctx.workspaceId });+ } catch (error) {+ if (error instanceof WorkspaceDevicePrivateConflictError) {+ throw new TRPCError({ code: 'CONFLICT', message: error.message });+ }+ throw error;+ }+ }),+ /**+ * Share one of the caller's PERSONAL devices into the current workspace+ * without touching the machine: dispatch an `enrollWorkspace` RPC over the+ * device's live personal connection (it derives its workspace-scoped+ * deviceId and opens a second gateway connection with the minted token),+ * then register the workspace row here β linked back to the personal device+ * via `sharedFromDeviceId` so the personal list can render and revoke the+ * share. Requires the device to be ONLINE; an offline device fails with+ * PRECONDITION_FAILED and the UI keeps its share action disabled.+ *+ * Same write gate as enrolling on the machine (`wsWritableProcedure`:+ * member+, viewers blocked). Visibility defaults to 'private' β see+ * `DeviceModel.registerWorkspaceDevice`.+ *+ * The machine may ALREADY be enrolled in this workspace (e.g. via+ * `lh connect --workspace`, which the personal share map can't link to).+ * Silently upserting would discard the caller's explicit visibility choice+ * (the conflict branch preserves the existing value), so instead the first+ * call reports `alreadyEnrolled` without writing; a `confirmOverwrite`+ * retry applies the requested visibility and links the row back to the+ * personal device.+ */+ shareDeviceToWorkspace: wsWritableProcedure+ .use(serverDatabase)+ .input(+ z.object({+ confirmOverwrite: z.boolean().optional(),+ deviceId: z.string().min(1).max(64),+ visibility: z.enum(['private', 'public']).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const personal = await model.findByDeviceId(input.deviceId);+ // findByDeviceId is (userId, deviceId)-scoped; exclude workspace rows the+ // caller enrolled so only true personal devices are shareable.+ if (!personal || personal.workspaceId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Personal device not found.' });+ }++ const token = await signWorkspaceDeviceToken(ctx.workspaceId);+ // Identity-only probe: learn the machine's workspace deviceId WITHOUT the+ // device opening or persisting a share connection, so backing out of the+ // overwrite confirmation leaves the device untouched. Older clients+ // ignore the flag and enroll here β that degrades to the pre-flag+ // behaviour, never worse.+ const probe = await deviceGateway.enrollWorkspace({+ deviceId: personal.deviceId,+ identityOnly: true,+ token,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (!probe.success || !probe.identity) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: probe.error ?? 'Device is offline or does not support workspace sharing.',+ });+ }++ // Fail a cross-user PRIVATE collision NOW, before the machine opens and+ // persists a workspace share connection β rejecting only at the later+ // row write would leave the device connected (and auto-reconnecting)+ // under the very id the rejection protects.+ try {+ await model.assertNoCrossUserPrivateConflict(probe.identity.deviceId);+ } catch (error) {+ if (error instanceof WorkspaceDevicePrivateConflictError) {+ throw new TRPCError({ code: 'CONFLICT', message: error.message });+ }+ throw error;+ }++ // Caller-invisible rows (another member's private enrollment) were+ // rejected above, so an undefined here really means "no row yet".+ const existing = await model.findWorkspaceDeviceById(probe.identity.deviceId);+ if (existing) {+ if (!input.confirmOverwrite) {+ return {+ alreadyEnrolled: true as const,+ deviceId: existing.deviceId,+ success: false as const,+ visibility: existing.visibility,+ };+ }+ const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;+ if (!canEditWorkspaceDevice(role, ctx.userId, existing.userId)) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the enrolling member or a workspace owner can overwrite this device.',+ });+ }+ if ((input.visibility ?? 'private') === 'private') {+ await assertDeviceNotBoundToFixedAgent(model, existing.deviceId);+ }+ }++ // Real enrollment β only after the caller is committed (no pending+ // confirmation and permission checks passed).+ const result = await deviceGateway.enrollWorkspace({+ deviceId: personal.deviceId,+ token,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (!result.success || !result.identity) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: result.error ?? 'Device is offline or does not support workspace sharing.',+ });+ }++ if (existing) {+ const row = await model.overwriteSharedWorkspaceDevice(existing.deviceId, {+ sharedFromDeviceId: personal.deviceId,+ visibility: input.visibility ?? 'private',+ });+ if (personal.friendlyName && !row?.friendlyName) {+ await model.updateWorkspaceDevice(existing.deviceId, {+ friendlyName: personal.friendlyName,+ });+ }+ return {+ deviceId: existing.deviceId,+ success: true as const,+ visibility: row?.visibility ?? input.visibility ?? 'private',+ };+ }++ let row;+ try {+ row = await model.registerWorkspaceDevice({+ deviceId: result.identity.deviceId,+ hostname: personal.hostname,+ identitySource: result.identity.identitySource,+ platform: personal.platform,+ sharedFromDeviceId: personal.deviceId,+ visibility: input.visibility,+ workspaceId: ctx.workspaceId,+ });+ } catch (error) {+ // The machine has already opened and persisted a share connection+ // above, and this (private-by-default) row is what hides it from other+ // members β on ANY write failure (conflict race, transient DB error),+ // best-effort roll the connection back so it doesn't linger as an+ // unregistered workspace ghost, then surface the original error.+ await deviceGateway.unenrollWorkspace({+ deviceId: result.identity.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (error instanceof WorkspaceDevicePrivateConflictError) {+ throw new TRPCError({ code: 'CONFLICT', message: error.message });+ }+ throw error;+ }+ // Carry the personal alias over on first share so the workspace list shows+ // the machine under the name its owner gave it; never clobber a name a+ // re-share conflict-preserved.+ if (personal.friendlyName && !row.friendlyName) {+ await model.updateWorkspaceDevice(row.deviceId, { friendlyName: personal.friendlyName });+ }++ return { deviceId: row.deviceId, success: true as const, visibility: row.visibility };+ }),+ /**+ * Publish a private workspace device to the shared pool, or pull a public one+ * back to private. Mirrors the agent/file `setVisibility` contract:+ * - the enrolling member may toggle their own device both ways;+ * - nobody else may touch visibility: owners demoting another+ * member's public device would appropriate it into that member's private+ * list, and other members' private devices are invisible to everyone+ * else by design (the lookup below already fails closed with NOT_FOUND),+ * so the whole toggle is effectively enroller-only.+ */+ setWorkspaceDeviceVisibility: wsWritableProcedure+ .use(serverDatabase)+ .input(+ z.object({+ deviceId: z.string(),+ visibility: z.enum(['private', 'public']),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const row = await model.findWorkspaceDeviceById(input.deviceId);+ if (!row) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });+ }+ if (row.visibility === input.visibility) return { success: true };+ if (row.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the enrolling member can change this device visibility.',+ });+ }+ if (input.visibility === 'private') {+ await assertDeviceNotBoundToFixedAgent(model, input.deviceId);+ }+ await model.setWorkspaceDeviceVisibility(input.deviceId, input.visibility);+ return { success: true };+ }),+ /**+ * Rename / replace the working dirs of a WORKSPACE device (enroller or owner only).+ * Members edit one recent dir via `workspaceDeviceWorkingDirProcedures`.+ */+ updateWorkspaceDevice: wsWritableProcedure+ .use(serverDatabase)+ .input(+ z.object({+ defaultCwd: z.string().nullish(),+ deviceId: z.string(),+ friendlyName: z.string().max(100).nullish(),+ workingDirs: z.array(workingDirConfigSchema).max(20).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const { deviceId, workingDirs, ...value } = input;+ const row = await model.findWorkspaceDeviceById(deviceId);+ if (!row) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });+ }+ const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;+ assertWorkspaceDeviceEditable(role, ctx.userId, row.userId);+ const nextWorkingDirs = workingDirs+ ? preserveWorkspaceCache(workingDirs, row.workingDirs ?? [])+ : undefined;+ await model.updateWorkspaceDevice(deviceId, { ...value, workingDirs: nextWorkingDirs });+ return { success: true };+ }),+ /**+ * Remove a WORKSPACE device. Scoped by `workspace_id` and gated by+ * {@link canEditWorkspaceDevice}: owners may remove any device in the pool;+ * members may remove only devices they enrolled themselves.+ */+ removeWorkspaceDevice: wsWritableProcedure+ .use(serverDatabase)+ .input(z.object({ deviceId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const row = await model.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 remove this device.',+ });+ }+ await assertDeviceNotBoundToFixedAgent(model, input.deviceId);+ // Tell a live device to drop its workspace connection and stop+ // auto-reconnecting, so removal doesn't leave an online ghost. For most+ // rows this stays best-effort β an offline device simply stops resolving.+ const unenrolled = await deviceGateway.unenrollWorkspace({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ // But never delete the row under a still-live socket that did not+ // acknowledge the unenroll (old client without the handler, RPC error):+ // for a PRIVATE row that would resurface the machine to other members+ // (the row is the only thing `queryWorkspaceHiddenDeviceIds` hides it+ // by), and for ANY row it leaves an unregistered ghost that members can+ // still dispatch to yet can no longer remove β there is no row left to+ // delete. Fail the removal while the socket is demonstrably alive; a+ // dead socket can't ghost, so an offline device still deletes fine.+ if (!unenrolled.success) {+ const online = await deviceGateway.queryDeviceList(ctx.userId, ctx.workspaceId);+ if (online.some((d) => d.deviceId === input.deviceId)) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message:+ 'The device is still connected but did not acknowledge the unenroll β retry once it has disconnected or updated its client.',+ });+ }+ }+ await model.deleteWorkspaceDevice(input.deviceId);+ return { success: true };+ }),+};