🤯 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
Fix file access for session worktrees on devices (#23302)
Bryan390bce997f5d
diff --git a/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts b/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.tsindex d8dbe33e53b..c291d780a28 100644--- a/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts+++ b/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts@@ -9,6 +9,8 @@ const mocks = vi.hoisted(() => ({createProjectDirectory: vi.fn(),createProjectFile: vi.fn(),findByDeviceId: vi.fn(),+ findTopic: vi.fn(),+ getLocalFilePreview: vi.fn(),getAgentAgencyConfig: vi.fn(),listClaudeCodeMemory: vi.fn(),moveProjectFiles: vi.fn(),@@ -44,12 +46,18 @@ vi.mock('@/database/models/device', () => ({findByDeviceId = mocks.findByDeviceId;},}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: class {+ findById = mocks.findTopic;+ },+}));vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({...(await importOriginal<object>()),deviceGateway: {copyProjectFiles: mocks.copyProjectFiles,createProjectDirectory: mocks.createProjectDirectory,createProjectFile: mocks.createProjectFile,+ getLocalFilePreview: mocks.getLocalFilePreview,listClaudeCodeMemory: mocks.listClaudeCodeMemory,moveProjectFiles: mocks.moveProjectFiles,renameProjectFile: mocks.renameProjectFile,@@ -126,6 +134,79 @@ describe('device project file mutations', () => {});});+describe('files in a persisted session worktree', () => {+ const approvedRoot = '/Users/me/proj';+ const worktreePath = '/Users/me/worktrees/first';+ const input = {+ ...base,+ path: `${worktreePath}/notes.md`,+ topicId: 'tpc_first',+ workingDirectory: worktreePath,+ };++ const topic = (worktree: string, source = approvedRoot, deviceId = base.deviceId) => ({+ metadata: {+ boundDeviceId: deviceId,+ workingDirectoryConfig: { git: { activeWorktree: worktree }, path: source },+ },+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findTopic.mockResolvedValue(topic(worktreePath));+ mocks.findByDeviceId.mockResolvedValue({+ workingDirs: [{ git: { activeWorktree: '/Users/me/worktrees/latest' }, path: approvedRoot }],+ });+ mocks.getLocalFilePreview.mockResolvedValue({ success: true });+ mocks.writeProjectFile.mockResolvedValue({ success: true });+ });++ it('previews and saves two session checkouts with no device workingDirs update', async () => {+ const secondCheckout = '/Users/me/worktrees/second';+ mocks.findTopic.mockImplementation(async (id: string) =>+ id === 'tpc_first' ? topic(worktreePath) : topic(secondCheckout),+ );++ for (const [topicId, checkout] of [+ ['tpc_first', worktreePath],+ ['tpc_second', secondCheckout],+ ]) {+ const args = { ...input, path: `${checkout}/notes.md`, topicId, workingDirectory: checkout };+ const worktree = { approvedRoot, sourcePath: approvedRoot, worktreePath: checkout };+ await expect(caller().getLocalFilePreview(args)).resolves.toEqual({ success: true });+ await expect(caller().writeProjectFile({ ...args, content: 'saved' })).resolves.toEqual({+ success: true,+ });+ expect(mocks.getLocalFilePreview).toHaveBeenLastCalledWith(+ expect.objectContaining({ path: args.path, worktree }),+ );+ expect(mocks.writeProjectFile).toHaveBeenLastCalledWith(+ expect.objectContaining({ content: 'saved', path: args.path, worktree }),+ );+ }++ expect(mocks.findTopic).toHaveBeenCalledWith('tpc_first');+ expect(mocks.findTopic).toHaveBeenCalledWith('tpc_second');+ });++ it.each([+ ['missing topic', undefined],+ ['wrong device', topic(worktreePath, approvedRoot, 'dev-2')],+ ['different worktree', topic('/Users/me/worktrees/other')],+ ['unregistered source', topic(worktreePath, '/Users/me/other')],+ ['legacy worktree slot as source', topic(worktreePath, '/Users/me/worktrees/latest')],+ ])('refuses access with %s', async (_label, savedTopic) => {+ mocks.findTopic.mockResolvedValue(savedTopic);++ await expect(caller().getLocalFilePreview(input)).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(caller().writeProjectFile({ ...input, content: 'x' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mocks.getLocalFilePreview).not.toHaveBeenCalled();+ expect(mocks.writeProjectFile).not.toHaveBeenCalled();+ });+});+describe('device listClaudeCodeMemory', () => {const memoryDir = '/Users/me/.claude/projects/-Users-me-proj/memory';const memoryFile = `${memoryDir}/MEMORY.md`;diff --git a/apps/server/src/routers/lambda/device/projectFiles.ts b/apps/server/src/routers/lambda/device/projectFiles.tsindex d3fce7b5494..90d7c07bfe2 100644--- a/apps/server/src/routers/lambda/device/projectFiles.ts+++ b/apps/server/src/routers/lambda/device/projectFiles.ts@@ -3,12 +3,22 @@ import { z } from 'zod';import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentModel } from '@/database/models/agent';+import { TopicModel } from '@/database/models/topic';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';-import { deviceGateway, isValidDirectoryName } from '@/server/services/deviceGateway';+import {+ deviceGateway,+ isPathWithinRoot,+ isValidDirectoryName,+} from '@/server/services/deviceGateway';+import {+ assertCanUseTopicTargets,+ assertCanViewTopicTargets,+} from '../_helpers/conversationResourceGuard';import {assertWorkspaceRootApproved,+ findRegisteredWorkspaceRoot,registerDeviceMemoryRoot,registerDeviceSkillRoots,} from '../deviceWorkspaceGuard';@@ -20,6 +30,8 @@ const workspaceFileInput = z.object({workingDirectory: z.string(),});+const topicFileInput = workspaceFileInput.extend({ topicId: z.string().min(1).optional() });+/*** `deviceProcedure` that additionally requires `workingDirectory` to be an* approved workspace root for the device. Builds the guard into the procedure@@ -37,12 +49,63 @@ const workspaceFileProcedure = deviceProcedure.input(workspaceFileInput).use(asyreturn opts.next();});+/** Use the persisted topic checkout when it isn't independently registered on the device. */+const topicFileProcedure = deviceProcedure.input(topicFileInput).use(async (opts) => {+ const { ctx } = opts;+ const { deviceId, topicId, workingDirectory } = topicFileInput.parse(await opts.getRawInput());+ try {+ await assertWorkspaceRootApproved(ctx.deviceModel, deviceId, workingDirectory, ctx.workspaceId);+ } catch (error) {+ if (!topicId || !(error instanceof TRPCError) || error.code !== 'FORBIDDEN') throw error;++ const { serverDB: db, userId, workspaceId } = ctx;+ const topicModel = new TopicModel(db, userId, workspaceId);+ const topic = await topicModel.findById(topicId);+ const config = topic?.metadata?.workingDirectoryConfig;+ const checkout = config?.git?.activeWorktree;+ if (+ !config ||+ !checkout ||+ topic?.metadata?.boundDeviceId !== deviceId ||+ !isPathWithinRoot(checkout, workingDirectory) ||+ !isPathWithinRoot(workingDirectory, checkout)+ )+ throw error;++ const assertTopicAccess =+ opts.type === 'query' ? assertCanViewTopicTargets : assertCanUseTopicTargets;+ await assertTopicAccess(+ {+ db,+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })+ .workspacePermissionCodes,+ userId,+ workspaceId,+ },+ [topicId],+ );+ const approvedRoot = await findRegisteredWorkspaceRoot(+ ctx.deviceModel,+ deviceId,+ config.path,+ workspaceId,+ );+ if (!approvedRoot) throw error;++ return opts.next({+ ctx: { worktree: { approvedRoot, sourcePath: config.path, worktreePath: workingDirectory } },+ });+ }++ return opts.next({ ctx: { worktree: undefined } });+});+/**- * `workspaceFileProcedure` for routes that change files on the device. In a+ * `topicFileProcedure` 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(+const workspaceFileWriteProcedure = topicFileProcedure.use(requireWorkspaceRoleWhenScoped('member'),);@@ -219,9 +282,9 @@ export const projectFilesRouter = router({}),/*** 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.+ * receives the serialized preview directly.*/- getLocalFilePreview: workspaceFileProcedure+ getLocalFilePreview: topicFileProcedure.input(z.object({accept: z.enum(['image']).optional(),@@ -236,6 +299,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),copyAssetForPublish: workspacePublishProcedure@@ -341,6 +405,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**@@ -362,6 +427,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**@@ -383,6 +449,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**@@ -404,6 +471,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**@@ -419,6 +487,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**@@ -440,6 +509,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**@@ -455,6 +525,7 @@ export const projectFilesRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,workingDirectory: input.workingDirectory,+ ...(ctx.worktree && { worktree: ctx.worktree }),});}),/**diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.tsindex 503712af2bd..1743b2ad37b 100644--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts@@ -163,6 +163,11 @@ export const isClaudeCodeTaskOutputDir = (return approvedRoots.some((root) => projectKeysOf(root).includes(projectKey));};+const findWorkspaceDevice = (deviceModel: DeviceModel, deviceId: string, workspaceId?: string) =>+ workspaceId+ ? deviceModel.findWorkspaceDeviceById(deviceId)+ : deviceModel.findByDeviceId(deviceId);+/*** Validate that a client-supplied workspace root is actually one the user has* bound to this device.@@ -199,9 +204,7 @@ export const assertWorkspaceRootApproved = async (});}- const device = workspaceId- ? await deviceModel.findWorkspaceDeviceById(deviceId)- : await deviceModel.findByDeviceId(deviceId);+ const device = await findWorkspaceDevice(deviceModel, deviceId, workspaceId);const approvedRoots = (device?.workingDirs ?? []).flatMap((dir) => [dir.path, dir.git?.activeWorktree])@@ -224,6 +227,21 @@ export const assertWorkspaceRootApproved = async (}};+/** A topic worktree inherits access only from a registered source directory. */+export const findRegisteredWorkspaceRoot = async (+ deviceModel: DeviceModel,+ deviceId: string,+ sourcePath: string,+ workspaceId?: string,+): Promise<string | undefined> => {+ const device = await findWorkspaceDevice(deviceModel, deviceId, workspaceId);+ const roots = [...(device?.workingDirs ?? []).map(({ path }) => path), device?.defaultCwd];+ return roots.reduce<string | undefined>((approved, root) => {+ if (!root || !isPathWithinRoot(root, sourcePath)) return approved;+ return !approved || isPathWithinRoot(root, approved) ? root : approved;+ }, undefined);+};+/*** Enforce the workspace device-visibility boundary for RPC routes.*diff --git a/apps/server/src/services/deviceGateway/index.fileMutations.test.ts b/apps/server/src/services/deviceGateway/index.fileMutations.test.tsindex 9117f295077..ca30548b7fe 100644--- a/apps/server/src/services/deviceGateway/index.fileMutations.test.ts+++ b/apps/server/src/services/deviceGateway/index.fileMutations.test.ts@@ -447,6 +447,36 @@ describe('DeviceGateway', () => {);});+ it('routes a worktree trash request through the desktop and makes only one RPC', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ error: 'Unknown device RPC method',+ success: false,+ });+ const worktree = { approvedRoot: '/repo', sourcePath: '/repo', worktreePath: '/checkout' };+ const paths = ['/checkout/a.ts'];++ await expect(+ new DeviceGateway().trashProjectFiles({+ deviceId: 'dev-1',+ paths,+ userId: 'user-1',+ workingDirectory: '/checkout',+ worktree,+ }),+ ).rejects.toThrow('Unknown device RPC method');+ expect(mockClient.invokeRpc).toHaveBeenCalledExactlyOnceWith(+ { clientKinds: ['desktop'], deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'runWorktreeFileOperation',+ params: {+ ...worktree,+ rpc: { method: 'trashLocalFiles', params: { paths, workspaceRoot: '/checkout' } },+ },+ },+ );+ });+it('throws when any path escapes the workspace', async () => {configure();const proxy = new DeviceGateway();diff --git a/apps/server/src/services/deviceGateway/projectFileMutations.ts b/apps/server/src/services/deviceGateway/projectFileMutations.tsindex d72d431ef92..fe747959b06 100644--- a/apps/server/src/services/deviceGateway/projectFileMutations.ts+++ b/apps/server/src/services/deviceGateway/projectFileMutations.ts@@ -18,6 +18,7 @@ import { isAbsolute } from 'pathe';import { assertNotWorkspaceRoot, assertPathsWithinWorkspace, joinDevicePath } from './paths';import type { DeviceClientGetter } from './types';+import { type DeviceWorktree, invokeWorkspaceFileRpc } from './workspaceFileRpc';const log = debug('lobe-server:device-gateway');@@ -36,6 +37,7 @@ export async function moveProjectFiles(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceMoveProjectFileResultItem[]> {@@ -52,9 +54,11 @@ export async function moveProjectFiles(items.map((item) => item.oldPath),);- const result = await client.invokeRpc<DeviceMoveProjectFileResultItem[]>(+ const result = await invokeWorkspaceFileRpc<DeviceMoveProjectFileResultItem[]>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'moveLocalFiles', params: { items, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {@@ -79,6 +83,7 @@ export async function renameProjectFile(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceRenameProjectFileResult> {@@ -99,9 +104,11 @@ export async function renameProjectFile(assertPathsWithinWorkspace(workingDirectory, [path]);assertNotWorkspaceRoot(workingDirectory, [path]);- const result = await client.invokeRpc<DeviceRenameProjectFileResult>(+ const result = await invokeWorkspaceFileRpc<DeviceRenameProjectFileResult>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'renameLocalFile', params: { newName, path, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {@@ -126,6 +133,7 @@ export async function writeProjectFile(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceWriteProjectFileResult> {@@ -143,9 +151,11 @@ export async function writeProjectFile(assertPathsWithinWorkspace(workingDirectory, [path]);- const result = await client.invokeRpc<DeviceWriteProjectFileResult>(+ const result = await invokeWorkspaceFileRpc<DeviceWriteProjectFileResult>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'writeLocalFile', params: { content, path, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {@@ -170,6 +180,7 @@ export async function createProjectFile(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceCreateProjectEntryResult> {@@ -187,9 +198,11 @@ export async function createProjectFile(assertPathsWithinWorkspace(workingDirectory, [path]);- const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(+ const result = await invokeWorkspaceFileRpc<DeviceCreateProjectEntryResult>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'createLocalFile', params: { content, path, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {@@ -212,6 +225,7 @@ export async function createProjectDirectory(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceCreateProjectEntryResult> {@@ -221,9 +235,11 @@ export async function createProjectDirectory(assertPathsWithinWorkspace(workingDirectory, [path]);- const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(+ const result = await invokeWorkspaceFileRpc<DeviceCreateProjectEntryResult>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'createLocalDirectory', params: { path, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {@@ -292,6 +308,7 @@ export async function copyProjectFiles(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceCopyProjectFileResultItem[]> {@@ -310,9 +327,11 @@ export async function copyProjectFiles(items.map((item) => item.sourcePath),);- const result = await client.invokeRpc<DeviceCopyProjectFileResultItem[]>(+ const result = await invokeWorkspaceFileRpc<DeviceCopyProjectFileResultItem[]>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'copyLocalFiles', params: { items, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {@@ -336,6 +355,7 @@ export async function trashProjectFiles(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceTrashProjectFilesResult> {@@ -346,9 +366,11 @@ export async function trashProjectFiles(assertPathsWithinWorkspace(workingDirectory, paths);assertNotWorkspaceRoot(workingDirectory, paths);- const result = await client.invokeRpc<DeviceTrashProjectFilesResult>(+ const result = await invokeWorkspaceFileRpc<DeviceTrashProjectFilesResult>(+ client,{ deviceId, timeout, userId, workspaceId },{ method: 'trashLocalFiles', params: { paths, workspaceRoot: workingDirectory } },+ params.worktree,);if (!result.success || !result.data) {diff --git a/apps/server/src/services/deviceGateway/projectFiles.ts b/apps/server/src/services/deviceGateway/projectFiles.tsindex 0ba028dea1e..99da9b119dd 100644--- a/apps/server/src/services/deviceGateway/projectFiles.ts+++ b/apps/server/src/services/deviceGateway/projectFiles.ts@@ -18,6 +18,7 @@ import debug from 'debug';import { assertPathsWithinWorkspace } from './paths';import type { DeviceClientGetter } from './types';+import { type DeviceWorktree, invokeWorkspaceFileRpc } from './workspaceFileRpc';const log = debug('lobe-server:device-gateway');@@ -209,6 +210,7 @@ export async function getLocalFilePreview(timeout?: number;userId: string;workingDirectory: string;+ worktree?: DeviceWorktree;workspaceId?: string;},): Promise<DeviceLocalFilePreviewResult> {@@ -225,12 +227,14 @@ export async function getLocalFilePreview(if (!client) return { error: 'Device gateway not configured', success: false };try {- const result = await client.invokeRpc<DeviceLocalFilePreviewResult>(+ const result = await invokeWorkspaceFileRpc<DeviceLocalFilePreviewResult>(+ client,{ deviceId, timeout, userId, workspaceId },{method: 'getLocalFilePreview',params: { accept, path, workingDirectory },},+ params.worktree,);if (!result.success || !result.data) {diff --git a/apps/server/src/services/deviceGateway/workspaceFileRpc.ts b/apps/server/src/services/deviceGateway/workspaceFileRpc.tsnew file mode 100644index 00000000000..d60b0b65367--- /dev/null+++ b/apps/server/src/services/deviceGateway/workspaceFileRpc.ts@@ -0,0 +1,21 @@+import { deviceRpcClients } from '@lobechat/device-control/rpc-clients';+import type { GatewayHttpClient } from '@lobechat/device-gateway-client';++export interface DeviceWorktree {+ approvedRoot: string;+ sourcePath: string;+ worktreePath: string;+}++export const invokeWorkspaceFileRpc = <T>(+ client: GatewayHttpClient,+ address: Parameters<GatewayHttpClient['invokeRpc']>[0],+ rpc: Parameters<GatewayHttpClient['invokeRpc']>[1],+ worktree?: DeviceWorktree,+) =>+ worktree+ ? client.invokeRpc<T>(+ { ...address, clientKinds: deviceRpcClients(rpc.method) },+ { method: 'runWorktreeFileOperation', params: { ...worktree, rpc } },+ )+ : client.invokeRpc<T>(address, rpc);diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 9e3a3990dec..92751ba0d6f 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -1,3 +1,4 @@+import { execFileSync } from 'node:child_process';import {mkdir,mkdtemp,@@ -124,6 +125,112 @@ describe('executeDeviceRpc', () => {);});+ describe('session worktree files', () => {+ let repo: string;+ let first: string;+ let second: string;++ beforeAll(async () => {+ const base = await realpath(root);+ repo = path.join(base, 'repo');+ first = path.join(base, 'first-worktree');+ second = path.join(base, 'second-worktree');+ await mkdir(repo);+ const git = (...args: string[]) =>+ execFileSync('git', ['-C', repo, ...args], { stdio: 'pipe' });+ git('init', '-q');+ await writeFile(path.join(repo, 'notes.txt'), 'original');+ git('add', 'notes.txt');+ git('-c', 'user.name=Test', '-c', '[email protected]', 'commit', '-qm', 'seed');+ git('worktree', 'add', '-b', 'first', first);+ git('worktree', 'add', '-b', 'second', second);+ });++ const run = (+ worktreePath: string,+ method: string,+ params: Record<string, unknown>,+ sourcePath = repo,+ ) =>+ executeDeviceRpc(+ 'runWorktreeFileOperation',+ { approvedRoot: repo, rpc: { method, params }, sourcePath, worktreePath },+ makeDeps(),+ );++ it('reads and writes two sibling Git worktrees without registering their paths', async () => {+ for (const checkout of [first, second]) {+ const filePath = path.join(checkout, 'notes.txt');+ const content = path.basename(checkout);+ await expect(+ run(checkout, 'writeLocalFile', { content, path: filePath, workspaceRoot: checkout }),+ ).resolves.toEqual({ success: true });+ await expect(+ run(checkout, 'getLocalFilePreview', { path: filePath, workingDirectory: checkout }),+ ).resolves.toMatchObject({ preview: { content, type: 'text' }, success: true });+ }+ expect(await readFile(path.join(repo, 'notes.txt'), 'utf8')).toBe('original');+ });++ it('refuses an unrelated directory and a source symlink that escapes the registered root', async () => {+ const unrelated = path.join(root, 'unrelated');+ const escapedSource = path.join(repo, 'escape');+ await mkdir(unrelated);+ await symlink(first, escapedSource, 'dir');+ await expect(+ run(unrelated, 'writeLocalFile', {+ content: 'must not write',+ path: path.join(unrelated, 'notes.txt'),+ workspaceRoot: unrelated,+ }),+ ).rejects.toThrow('not a registered worktree');+ await expect(+ run(+ second,+ 'getLocalFilePreview',+ {+ path: path.join(second, 'notes.txt'),+ workingDirectory: second,+ },+ escapedSource,+ ),+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);+ expect(await readdir(unrelated)).toEqual([]);+ });++ it('refuses to inherit access to worktrees from a registered subdirectory of the source', async () => {+ const approvedRoot = path.join(repo, 'registered-subdirectory');+ await mkdir(approvedRoot);++ await expect(+ executeDeviceRpc(+ 'runWorktreeFileOperation',+ {+ approvedRoot,+ rpc: {+ method: 'getLocalFilePreview',+ params: { path: path.join(first, 'notes.txt'), workingDirectory: first },+ },+ sourcePath: approvedRoot,+ worktreePath: first,+ },+ makeDeps(),+ ),+ ).rejects.toThrow('The source repository is outside the approved workspace');+ });++ it('refuses preview and write through a symlink to a sibling worktree', async () => {+ const link = path.join(first, 'linked.txt');+ await symlink(path.join(second, 'notes.txt'), link, 'file');+ await expect(+ run(first, 'getLocalFilePreview', { path: link, workingDirectory: first }),+ ).resolves.toMatchObject({ code: 'forbidden', success: false });+ await expect(+ run(first, 'writeLocalFile', { content: 'blocked', path: link, workspaceRoot: first }),+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);+ });+ });+describe('app update', () => {const state = { currentVersion: '2.1.0', stage: 'downloaded' as const, targetVersion: '2.2.0' };diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex d6976c9840a..b77b026b6bd 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -1,3 +1,5 @@+import { lstat, realpath } from 'node:fs/promises';+import type { AntigravityQuotaParams } from '@lobechat/heterogeneous-agents/quota';import {copyLocalFiles,@@ -9,6 +11,7 @@ import {} from '@lobechat/local-file-shell/file';import {addGitWorktree,+ assertLinkedWorktree,checkoutGitBranch,cleanupOwnedWorktree,deleteGitBranch,@@ -45,7 +48,11 @@ import { getAntigravityQuota } from './antigravityQuota';import { listClaudeCodeMemory } from './claudeCodeMemory';import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';-import { defaultCopyAssetForPublish, defaultReadExternalAssetForPublish } from './filePreview';+import {+ defaultCopyAssetForPublish,+ defaultGetLocalFilePreview,+ defaultReadExternalAssetForPublish,+} from './filePreview';import { getKimiCodeQuota, type GetKimiCodeQuotaParams } from './kimiCodeQuota';import { listListeningPorts, type ListListeningPortsParams } from './listeningPorts';import { defaultListProjectDirectory } from './projectFileIndex';@@ -102,6 +109,7 @@ export const DEVICE_RPC_METHODS = ['listProjectDirectory','searchProjectFiles','getLocalFilePreview',+ 'runWorktreeFileOperation','readExternalAssetForPublish','copyAssetForPublish','moveLocalFiles',@@ -197,6 +205,17 @@ const guardLegacyMutation = async (workspaceRoot: string | undefined, targets: sif (workspaceRoot) await assertEntriesWithinWorkspace(workspaceRoot, targets);};+const worktreeFileMethods = new Set([+ 'copyLocalFiles',+ 'createLocalDirectory',+ 'createLocalFile',+ 'getLocalFilePreview',+ 'moveLocalFiles',+ 'renameLocalFile',+ 'trashLocalFiles',+ 'writeLocalFile',+]);+/*** Dispatch a generic server-internal device RPC by method name. This is the* single device-control entry point shared by the desktop main process@@ -301,6 +320,44 @@ export const executeDeviceRpc = async (return deps.getLocalFilePreview(params as LocalFilePreviewUrlParams);}+ case 'runWorktreeFileOperation': {+ const { approvedRoot, rpc, sourcePath, worktreePath } = params as {+ approvedRoot: string;+ rpc: {+ method: string;+ params: { path?: string; workingDirectory?: string; workspaceRoot?: string };+ };+ sourcePath: string;+ worktreePath: string;+ };+ const isPreview = rpc.method === 'getLocalFilePreview';+ const root = isPreview ? rpc.params.workingDirectory : rpc.params.workspaceRoot;+ if (!worktreePath || !worktreeFileMethods.has(rpc.method) || root !== worktreePath)+ throw new Error('Invalid worktree file operation');+ const [realApprovedRoot, realSourcePath] = await Promise.all([+ realpath(approvedRoot),+ realpath(sourcePath),+ ]);+ if (realSourcePath !== realApprovedRoot) {+ await guardMutation(realApprovedRoot, [realSourcePath]);+ }+ await assertLinkedWorktree(realSourcePath, worktreePath, realApprovedRoot);++ // The Git check authorizes this request only. Use the contained reader+ // without adding the worktree to the desktop preview approval cache.+ if (isPreview) return defaultGetLocalFilePreview(rpc.params as LocalFilePreviewUrlParams);+ if (rpc.method === 'writeLocalFile' && rpc.params.path) {+ // Writes follow the final symlink. Other file mutations act on the entry itself.+ const file = rpc.params.path;+ const entry = await lstat(file).catch((error: NodeJS.ErrnoException) => {+ if (error.code !== 'ENOENT') throw error;+ return undefined;+ });+ if (entry?.isSymbolicLink()) await guardMutation(worktreePath, [await realpath(file)]);+ }+ return executeDeviceRpc(rpc.method, rpc.params, deps);+ }+case 'readExternalAssetForPublish': {return (deps.readExternalAssetForPublish ?? defaultReadExternalAssetForPublish)(params as ExternalAssetForPublishParams,diff --git a/packages/local-file-shell/src/git/ownedWorktree.ts b/packages/local-file-shell/src/git/ownedWorktree.tsindex 04c92d22d00..857646293d9 100644--- a/packages/local-file-shell/src/git/ownedWorktree.ts+++ b/packages/local-file-shell/src/git/ownedWorktree.ts@@ -86,6 +86,7 @@ interface ListedWorktree {branch?: string;locked?: boolean;path: string;+ prunable?: boolean;}/**@@ -95,12 +96,19 @@ interface ListedWorktree {const findLinkedWorktree = async (sourcePath: string,worktreePath: string,+ approvedRoot?: string,): Promise<ListedWorktree | undefined> => {const stdout = await git(sourcePath, ['worktree', 'list', '--porcelain', '-z']);const [main, ...linked] = parseGitWorktreeList(stdout);const target = await safeRealpath(worktreePath);- if (main && (await safeRealpath(main.path)) === target)- throw new GuardError('Refusing to remove the main worktree');+ const mainPath = main && (await safeRealpath(main.path));+ if (+ approvedRoot &&+ (!mainPath || (mainPath !== approvedRoot && !isStrictlyInside(approvedRoot, mainPath)))+ ) {+ throw new GuardError('The source repository is outside the approved workspace');+ }+ if (mainPath === target) throw new GuardError('Refusing to remove the main worktree');for (const entry of linked) {if (entry.bare) continue;if ((await safeRealpath(entry.path)) === target) return entry;@@ -167,6 +175,20 @@ const assertGitFilePointsToSource = async (sourcePath: string, worktreePath: strthrow new GuardError('Worktree .git does not point back to the source repository');};+/** Confirm a live linked checkout of an approved source before accessing its files. */+export const assertLinkedWorktree = async (+ sourcePath: string,+ worktreePath: string,+ approvedRoot: string,+) => {+ const stat = await lstat(worktreePath);+ const linked =+ stat.isDirectory() && (await findLinkedWorktree(sourcePath, worktreePath, approvedRoot));+ if (!linked || linked.prunable)+ throw new GuardError('Directory is not a registered worktree of the approved repository');+ await assertGitFilePointsToSource(sourcePath, worktreePath);+};+/*** Uncommitted work that would be lost: tracked changes (staged or not) and* untracked files — inside submodules too, whose working trees the removaldiff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsxindex f96fcacce7d..f625b145010 100644--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx@@ -259,6 +259,7 @@ describe('LocalFileLink Render', () => {filePath: '/Users/me/project/docs/x.pdf',workingDirectory: '/Users/me/project',}),+ topicId: 'topic-1',workingDirectory: '/Users/me/project',},]);diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileOperations.ts b/src/features/Conversation/WorkingSidebar/Files/useFileOperations.tsindex 888ef39e418..3813b8f5642 100644--- a/src/features/Conversation/WorkingSidebar/Files/useFileOperations.ts+++ b/src/features/Conversation/WorkingSidebar/Files/useFileOperations.ts@@ -226,11 +226,13 @@ export const useFileOperations = ({? await projectFileService.createProjectDirectory({deviceId,path,+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,}): await projectFileService.createProjectFile({deviceId,path,+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,});if (!result.success) throw new Error(result.error || 'Unknown error');@@ -249,7 +251,7 @@ export const useFileOperations = ({open: kind === 'file',});},- [afterWrite, deviceId, projectRoot, reasonOf, t, toAbsolute],+ [activeTopicId, afterWrite, deviceId, projectRoot, reasonOf, t, toAbsolute],);const commitRename = useCallback(@@ -260,6 +262,7 @@ export const useFileOperations = ({deviceId,newName,path: node.data.path,+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,});if (!result.success) throw new Error(String(result.error || 'Unknown error'));@@ -280,7 +283,7 @@ export const useFileOperations = ({const parentRel = getParentRelativePath(node.id) ?? '';await afterWrite({ id: toEntryId(`${parentRel}${newName}`, !!node.isFolder) });},- [afterWrite, deviceId, projectRoot, reasonOf, retargetLocalFiles, t],+ [activeTopicId, afterWrite, deviceId, projectRoot, reasonOf, retargetLocalFiles, t],);/** Moves entries into `targetDirRel`, skipping (and reporting) name clashes. */@@ -305,6 +308,7 @@ export const useFileOperations = ({newPath: join(targetDir, entry.name),oldPath: entry.path,})),+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,});} catch (error) {@@ -340,6 +344,7 @@ export const useFileOperations = ({return failed.length === 0;},[+ activeTopicId,afterWrite,caseInsensitive,deviceId,@@ -410,6 +415,7 @@ export const useFileOperations = ({const result = await projectFileService.trashProjectFiles({deviceId,paths: entries.map((entry) => entry.path),+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,});items = result.items;@@ -463,7 +469,17 @@ export const useFileOperations = ({: t('workingPanel.files.delete.confirmTitle', { name: first.name, trash: trashName }),});},- [afterWrite, closeLocalFilesAt, deviceId, dirtyFilePaths, projectRoot, reasonOf, t, trashName],+ [+ activeTopicId,+ afterWrite,+ closeLocalFilesAt,+ deviceId,+ dirtyFilePaths,+ projectRoot,+ reasonOf,+ t,+ trashName,+ ],);const duplicate = useCallback(@@ -472,6 +488,7 @@ export const useFileOperations = ({const [result] = await projectFileService.copyProjectFiles({deviceId,items: [{ sourcePath: entry.path }],+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,});if (!result?.success || !result.targetPath) {@@ -490,7 +507,7 @@ export const useFileOperations = ({);}},- [afterWrite, deviceId, projectRoot, reasonOf, t, toRelative],+ [activeTopicId, afterWrite, deviceId, projectRoot, reasonOf, t, toRelative],);const putOnClipboard = useCallback(@@ -535,6 +552,7 @@ export const useFileOperations = ({results = await projectFileService.copyProjectFiles({deviceId,items,+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory: projectRoot,});} catch (error) {@@ -561,6 +579,7 @@ export const useFileOperations = ({);},[+ activeTopicId,afterWrite,caseInsensitive,clearClipboard,diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.tsindex 636407076a8..d8da194ff71 100644--- a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts+++ b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts@@ -241,6 +241,7 @@ describe('useFileTreeActions — create', () => {expect(service.createProjectDirectory).toHaveBeenCalledWith({deviceId: 'dev_1',path: '/repo/docs',+ topicId: 'tpc_1',workingDirectory: '/repo',});expect(service.refreshProjectFiles).toHaveBeenCalledWith('dev_1', '/repo');diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 4e190daaf4d..99e6e9ce2dd 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -153,6 +153,7 @@ interface TextPreviewPaneProps {reloading?: boolean;resourceBaseUrl?: string;sandboxTopicId?: string;+ topicId?: string;workingDirectory: string;}@@ -170,6 +171,7 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(reloading = false,resourceBaseUrl,sandboxTopicId,+ topicId,workingDirectory,}) => {const { t } = useTranslation('chat');@@ -246,11 +248,12 @@ const TextPreviewPane = memo<TextPreviewPaneProps>({...props}deviceId={deviceId}markdownFilePath={filePath}+ topicId={topicId}workingDirectory={workingDirectory}/>),}) satisfies MarkdownProps['components'],- [deviceId, filePath, workingDirectory],+ [deviceId, filePath, topicId, workingDirectory],);const [modeByScope, setModeByScope] = useState<Record<string, TextPreviewMode>>({});@@ -399,6 +402,7 @@ interface ActiveFileViewProps {filePath: string;/** Read the file live from the topic's cloud sandbox instead of a filesystem. */sandboxTopicId?: string;+ topicId?: string;workingDirectory: string;}@@ -409,6 +413,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(deviceId,filePath,sandboxTopicId,+ topicId,workingDirectory,}) => {const { t } = useTranslation('chat');@@ -421,9 +426,10 @@ const ActiveFileView = memo<ActiveFileViewProps>(deviceId,filePath,sandboxTopicId,+ topicId,workingDirectory,}),- [allowExternalFilePreview, deviceId, filePath, sandboxTopicId, workingDirectory],+ [allowExternalFilePreview, deviceId, filePath, sandboxTopicId, topicId, workingDirectory],);const [useFetchPreview, beginSave, refreshPreview] = useLocalFilePreviewStore((s) => [s.useFetchPreview,@@ -521,6 +527,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(reloading={isValidating}resourceBaseUrl={preview.resourceBaseUrl}sandboxTopicId={sandboxTopicId}+ topicId={topicId}workingDirectory={workingDirectory}onReload={handleReload}onSaveStart={handleSaveStart}@@ -556,6 +563,7 @@ const Body = memo(() => {deviceId={activeFile.deviceId}filePath={activeFile.filePath}sandboxTopicId={activeFile.sandboxTopicId}+ topicId={activeFile.topicId}workingDirectory={activeFile.workingDirectory}/></Flexbox>diff --git a/src/features/Portal/LocalFile/MarkdownImage.tsx b/src/features/Portal/LocalFile/MarkdownImage.tsxindex 771e05fe08c..91813b8bf6c 100644--- a/src/features/Portal/LocalFile/MarkdownImage.tsx+++ b/src/features/Portal/LocalFile/MarkdownImage.tsx@@ -12,11 +12,12 @@ interface MarkdownImageProps extends ComponentProps<'img'> {deviceId?: string;markdownFilePath: string;node?: unknown;+ topicId?: string;workingDirectory: string;}const MarkdownImage = memo<MarkdownImageProps>(- ({ alt, className, deviceId, markdownFilePath, node, src, style, workingDirectory }) => {+ ({ alt, className, deviceId, markdownFilePath, node, src, style, topicId, workingDirectory }) => {void node;const markdownSrc = typeof src === 'string' ? src : undefined;@@ -31,6 +32,7 @@ const MarkdownImage = memo<MarkdownImageProps>(accept: 'image',deviceId,filePath: resolvedPath,+ topicId,workingDirectory,}): null,@@ -39,6 +41,7 @@ const MarkdownImage = memo<MarkdownImageProps>(accept: 'image',deviceId,path: resolvedPath!,+ ...(topicId && { topicId }),workingDirectory,}),{ revalidateOnFocus: false },diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex ab6655b1204..99027b3edeb 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -39,6 +39,7 @@ interface LocalFilePreviewKeyParams {resourceScope?: 'workspace';/** Topic scope when the previewed file lives in the topic's cloud sandbox. */sandboxTopicId?: string;+ topicId?: string;workingDirectory: string;}@@ -551,6 +552,7 @@ export const localFileKeys = {filePath,resourceScope,sandboxTopicId,+ topicId,workingDirectory,}: LocalFilePreviewKeyParams) => ['localFile:preview',@@ -560,6 +562,7 @@ export const localFileKeys = {accept ?? 'any',allowExternalFile ? 'external' : 'workspace',resourceScope ?? 'single-file',+ ...(deviceId && topicId ? [topicId] : []),],),projectIndex: def('localFile:projectIndex', (deviceId: string | undefined, dirPath: string) => [diff --git a/src/services/projectFile.ts b/src/services/projectFile.tsindex 6fd32f391b1..f6a1859d0ce 100644--- a/src/services/projectFile.ts+++ b/src/services/projectFile.ts@@ -29,6 +29,7 @@ export type { LocalFilePreview } from '@/services/electron/localFileService';export interface GetLocalFilePreviewParams extends LocalFilePreviewUrlParams {deviceId?: string;+ topicId?: string;}const base64ToBlob = (base64: string, contentType: string): Blob => {@@ -259,6 +260,7 @@ class ProjectFileService {/** File preview payload for a file in a project working directory. */async getLocalFilePreview({deviceId,+ topicId,...params}: GetLocalFilePreviewParams): Promise<LocalFilePreview> {if (deviceId) {@@ -266,6 +268,7 @@ class ProjectFileService {accept: params.accept,deviceId,path: params.path,+ ...(topicId && { topicId }),workingDirectory: params.workingDirectory,});@@ -350,10 +353,12 @@ class ProjectFileService {async moveProjectFiles({deviceId,items,+ topicId,workingDirectory,}: {deviceId?: string;items: MoveLocalFileParams[];+ topicId?: string;workingDirectory: string;}): Promise<LocalMoveFilesResultItem[]> {assertNotWorkspaceRoot(@@ -362,7 +367,12 @@ class ProjectFileService {);return deviceId- ? lambdaClient.device.moveProjectFiles.mutate({ deviceId, items, workingDirectory })+ ? lambdaClient.device.moveProjectFiles.mutate({+ deviceId,+ items,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.moveLocalFiles({ items });}@@ -371,17 +381,25 @@ class ProjectFileService {deviceId,newName,path,+ topicId,workingDirectory,}: {deviceId?: string;newName: string;path: string;+ topicId?: string;workingDirectory: string;}): Promise<RenameLocalFileResult> {assertNotWorkspaceRoot(workingDirectory, [path]);return deviceId- ? lambdaClient.device.renameProjectFile.mutate({ deviceId, newName, path, workingDirectory })+ ? lambdaClient.device.renameProjectFile.mutate({+ deviceId,+ newName,+ path,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.renameLocalFile({ newName, path });}@@ -395,15 +413,23 @@ class ProjectFileService {content,deviceId,path,+ topicId,workingDirectory,}: {content: string;deviceId?: string;path: string;+ topicId?: string;workingDirectory: string;}): Promise<{ error?: string; success: boolean }> {return deviceId- ? lambdaClient.device.writeProjectFile.mutate({ content, deviceId, path, workingDirectory })+ ? lambdaClient.device.writeProjectFile.mutate({+ content,+ deviceId,+ path,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.writeFile({ content, path });}@@ -415,15 +441,23 @@ class ProjectFileService {content,deviceId,path,+ topicId,workingDirectory,}: {content?: string;deviceId?: string;path: string;+ topicId?: string;workingDirectory: string;}): Promise<CreateLocalEntryResult> {return deviceId- ? lambdaClient.device.createProjectFile.mutate({ content, deviceId, path, workingDirectory })+ ? lambdaClient.device.createProjectFile.mutate({+ content,+ deviceId,+ path,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.createLocalFile({ content, path });}@@ -431,14 +465,21 @@ class ProjectFileService {async createProjectDirectory({deviceId,path,+ topicId,workingDirectory,}: {deviceId?: string;path: string;+ topicId?: string;workingDirectory: string;}): Promise<CreateLocalEntryResult> {return deviceId- ? lambdaClient.device.createProjectDirectory.mutate({ deviceId, path, workingDirectory })+ ? lambdaClient.device.createProjectDirectory.mutate({+ deviceId,+ path,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.createLocalDirectory({ path });}@@ -450,10 +491,12 @@ class ProjectFileService {async copyProjectFiles({deviceId,items,+ topicId,workingDirectory,}: {deviceId?: string;items: CopyLocalFileItem[];+ topicId?: string;workingDirectory: string;}): Promise<LocalCopyFilesResultItem[]> {assertNotWorkspaceRoot(@@ -462,7 +505,12 @@ class ProjectFileService {);return deviceId- ? lambdaClient.device.copyProjectFiles.mutate({ deviceId, items, workingDirectory })+ ? lambdaClient.device.copyProjectFiles.mutate({+ deviceId,+ items,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.copyLocalFiles({ items });}@@ -474,16 +522,23 @@ class ProjectFileService {async trashProjectFiles({deviceId,paths,+ topicId,workingDirectory,}: {deviceId?: string;paths: string[];+ topicId?: string;workingDirectory: string;}): Promise<TrashLocalFilesResult> {assertNotWorkspaceRoot(workingDirectory, paths);return deviceId- ? lambdaClient.device.trashProjectFiles.mutate({ deviceId, paths, workingDirectory })+ ? lambdaClient.device.trashProjectFiles.mutate({+ deviceId,+ paths,+ ...(topicId && { topicId }),+ workingDirectory,+ }): localFileService.trashLocalFiles({ paths });}}diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex 4b25de29ad9..c61a82bb683 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -530,7 +530,7 @@ export class ChatPortalActionImpl {sandboxTopicId,workingDirectory,}: OpenLocalFileParams): void => {- const { activeLocalFileIdsByScope, openLocalFiles } = this.#get();+ const { activeLocalFileIdsByScope, activeTopicId, openLocalFiles } = this.#get();const id = createLocalFileTabId({ deviceId, filePath, sandboxTopicId, workingDirectory });const exists = openLocalFiles.some((f) => getLocalFileTabId(f) === id);const nextFile = {@@ -539,6 +539,7 @@ export class ChatPortalActionImpl {...(sandboxTopicId ? { sandboxTopicId } : {}),filePath,id,+ ...(deviceId && activeTopicId && { topicId: activeTopicId }),workingDirectory,};const scopeKey = getLocalFileActivationScopeKey(this.#get(), nextFile);@@ -660,7 +661,7 @@ export class ChatPortalActionImpl {filePath,workingDirectory,}: OpenLocalFileParams): Promise<string | undefined> => {- const { dirtyLocalFileContents } = this.#get();+ const { dirtyLocalFileContents, openLocalFiles } = this.#get();// Edit buffers are scoped by tab identity (device + working directory +// path), so the same absolute path opened on two devices/workspaces keeps// independent unsaved content.@@ -669,10 +670,12 @@ export class ChatPortalActionImpl {if (buffer === undefined) return undefined;// deviceId routes the write to the remote device over RPC; local desktop// (no deviceId) goes straight to Electron IPC. The chokepoint hides the split.+ const topicId = findLocalFileById(openLocalFiles, tabId)?.topicId;const result = await projectFileService.writeProjectFile({content: buffer,deviceId,path: filePath,+ ...(topicId && { topicId }),workingDirectory,});// The remote RPC / local IPC report fs failures (permission denied, etc.) asdiff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex 5950e751882..35438641478 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -80,6 +80,8 @@ export interface OpenLocalFileParams {export interface OpenLocalFileEntry extends OpenLocalFileParams {id: string;+ /** The topic the device file was opened from. */+ topicId?: string;}/**diff --git a/src/store/localFilePreview/index.test.ts b/src/store/localFilePreview/index.test.tsindex 6958b4436b2..7529f20f948 100644--- a/src/store/localFilePreview/index.test.ts+++ b/src/store/localFilePreview/index.test.ts@@ -198,6 +198,19 @@ describe('local file preview replica', () => {);});+ it('includes the topic in the remote file preview request and cache key', async () => {+ const target = { ...NOTES, topicId: 'tpc_worktree' };+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue(textPreview('in topic'));++ const { result } = renderPreview(target);++ await waitFor(() => expect(result.current.preview).toEqual(textPreview('in topic')));+ expect(projectFileService.getLocalFilePreview).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'device-a', topicId: 'tpc_worktree' }),+ );+ expect(localFilePreviewKey(target)).not.toBe(localFilePreviewKey(NOTES));+ });+it.each(['local', 'sandbox:build'])('reads a device whose id is %s from that device, not a reserved source',async (deviceId) => {diff --git a/src/store/localFilePreview/index.ts b/src/store/localFilePreview/index.tsindex e2281b4937a..fee58876591 100644--- a/src/store/localFilePreview/index.ts+++ b/src/store/localFilePreview/index.ts@@ -60,8 +60,15 @@ const fetchSandboxFilePreview = async (};const fetchLocalFilePreview = (key: string): Promise<LocalFilePreview> => {- const { accept, allowExternalFile, deviceId, filePath, sandboxTopicId, workingDirectory } =- localFilePreviewTargetFromKey(key);+ const {+ accept,+ allowExternalFile,+ deviceId,+ filePath,+ sandboxTopicId,+ topicId,+ workingDirectory,+ } = localFilePreviewTargetFromKey(key);if (sandboxTopicId) return fetchSandboxFilePreview(filePath, sandboxTopicId);// A local HTML file resolves its relative URLs against sibling files.@@ -72,6 +79,7 @@ const fetchLocalFilePreview = (key: string): Promise<LocalFilePreview> => {deviceId,path: filePath,...(resourceScope && { resourceScope }),+ ...(topicId && { topicId }),workingDirectory,});};diff --git a/src/store/localFilePreview/projection.ts b/src/store/localFilePreview/projection.tsindex 156ff79bcef..aedf0a6a832 100644--- a/src/store/localFilePreview/projection.ts+++ b/src/store/localFilePreview/projection.ts@@ -15,6 +15,8 @@ export interface LocalFilePreviewTarget {filePath: string;/** Read live from this topic's cloud sandbox instead of a filesystem. */sandboxTopicId?: string;+ /** Authorize a remote checkout using this topic’s working directory. */+ topicId?: string;workingDirectory: string;}@@ -47,6 +49,7 @@ export const localFilePreviewKey = ({deviceId,filePath,sandboxTopicId,+ topicId,workingDirectory,}: LocalFilePreviewTarget): string =>JSON.stringify([@@ -58,18 +61,23 @@ export const localFilePreviewKey = ({workingDirectory,filePath,allowExternalFile ? 'external' : 'workspace',- ...(accept ? [accept] : []),+ ...(deviceId && topicId && !sandboxTopicId+ ? [accept ?? null, topicId]+ : accept+ ? [accept]+ : []),]);/** The target a {@link localFilePreviewKey} was built from (fetcher side). */export const localFilePreviewTargetFromKey = (key: string): LocalFilePreviewTarget => {- const [kind, id, workingDirectory, filePath, access, accept] = JSON.parse(key) as [+ const [kind, id, workingDirectory, filePath, access, accept, topicId] = JSON.parse(key) as ['device' | 'local' | 'sandbox',string | null,string,string,string,- 'image' | undefined,+ 'image' | null | undefined,+ (string | undefined)?,];return {accept: accept === 'image' ? accept : undefined,@@ -77,6 +85,7 @@ export const localFilePreviewTargetFromKey = (key: string): LocalFilePreviewTargdeviceId: kind === 'device' ? (id ?? undefined) : undefined,filePath,sandboxTopicId: kind === 'sandbox' ? (id ?? undefined) : undefined,+ ...(kind === 'device' && topicId && { topicId }),workingDirectory,};};