π€― 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(device): correct shared file previews and local folder actions (#20886)
AmAzing-d01989ac8415
diff --git a/apps/server/src/routers/lambda/__tests__/deviceFilePreview.test.ts b/apps/server/src/routers/lambda/__tests__/deviceFilePreview.test.tsnew file mode 100644index 00000000000..b743d0d4344--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceFilePreview.test.ts@@ -0,0 +1,96 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ findByDeviceId: vi.fn(),+ findWorkspaceDeviceById: vi.fn(),+ getLocalFilePreview: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ findByDeviceId = mocks.findByDeviceId;+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;+ },+}));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: { getLocalFilePreview: mocks.getLocalFilePreview },+}));++describe('device file preview workspace authorization', () => {+ const input = {+ deviceId: 'shared-device',+ path: '/shared/project/index.html',+ workingDirectory: '/shared/project',+ };+ const preview = {+ preview: { content: '<h1>Shared preview</h1>', contentType: 'text/html', type: 'text' },+ success: true,+ };+ const workspaceCaller = deviceRouter.createCaller({+ userId: 'member',+ workspaceId: 'workspace',+ workspaceRole: 'member',+ } as never);+ const personalCaller = deviceRouter.createCaller({ userId: 'member' } as never);++ beforeEach(() => {+ vi.resetAllMocks();+ mocks.findWorkspaceDeviceById.mockResolvedValue({+ deviceId: input.deviceId,+ userId: 'another-member',+ workingDirs: [{ path: '/shared/project' }],+ workspaceId: 'workspace',+ });+ mocks.getLocalFilePreview.mockResolvedValue(preview);+ });++ it('previews an HTML file on a public device enrolled by another member', async () => {+ await expect(workspaceCaller.getLocalFilePreview(input)).resolves.toEqual(preview);+ });++ it.each([+ { defaultCwd: '/shared/project', workingDirs: [] },+ { workingDirs: [{ path: '/shared' }] },+ { workingDirs: [{ git: { activeWorktree: '/shared/project' }, path: '/repo' }] },+ ])('accepts approved workspace directories from %j', async (roots) => {+ mocks.findWorkspaceDeviceById.mockResolvedValue({ userId: 'another-member', ...roots });+ await expect(workspaceCaller.getLocalFilePreview(input)).resolves.toEqual(preview);+ });++ it.each(['/', '/shared/project-other', '/shared/project/../private'])(+ 'rejects an unapproved workspace directory %s even if the personal device permits it',+ async (workingDirectory) => {+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/' }] });+ await expect(+ workspaceCaller.getLocalFilePreview({ ...input, workingDirectory }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.getLocalFilePreview).not.toHaveBeenCalled();+ },+ );++ it('rejects an invisible workspace device even if a personal device permits the path', async () => {+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/shared/project' }] });+ await expect(workspaceCaller.getLocalFilePreview(input)).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mocks.getLocalFilePreview).not.toHaveBeenCalled();+ });++ it('does not borrow workspace authorization for a personal request', async () => {+ await expect(personalCaller.getLocalFilePreview(input)).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mocks.getLocalFilePreview).not.toHaveBeenCalled();+ });++ it('preserves previews on an approved personal device', async () => {+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/shared/project' }] });+ await expect(personalCaller.getLocalFilePreview(input)).resolves.toEqual(preview);+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/devicePublishAsset.test.ts b/apps/server/src/routers/lambda/__tests__/devicePublishAsset.test.tsnew file mode 100644index 00000000000..081589eca62--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/devicePublishAsset.test.ts@@ -0,0 +1,143 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ copyAssetForPublish: vi.fn(),+ findByDeviceId: vi.fn(),+ findWorkspaceDeviceById: vi.fn(),+ getLocalFilePreview: vi.fn(),+ readExternalAssetForPublish: vi.fn(),+}));++// OSS ships a no-op role guard. Model the cloud contract to exercise the+// router's write gate, including fail-closed scoped requests and personal mode.+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ const { trpc } = await import('@/libs/trpc/lambda/init');+ const ranks = { admin: 2, member: 1, owner: 3, viewer: 0 };++ return {+ ...actual,+ requireWorkspaceRoleWhenScoped: (minRole: WorkspaceRole) =>+ trpc.middleware(async ({ ctx, next }) => {+ const { workspaceId, workspaceRole } = ctx as {+ workspaceId?: string;+ workspaceRole?: WorkspaceRole;+ };+ if (workspaceId && (!workspaceRole || ranks[workspaceRole] < ranks[minRole])) {+ throw new TRPCError({ code: 'FORBIDDEN' });+ }+ return next();+ }),+ };+});++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ findByDeviceId = mocks.findByDeviceId;+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;+ },+}));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: {+ copyAssetForPublish: mocks.copyAssetForPublish,+ getLocalFilePreview: mocks.getLocalFilePreview,+ readExternalAssetForPublish: mocks.readExternalAssetForPublish,+ },+}));++type Caller = ReturnType<typeof deviceRouter.createCaller>;++const base = { deviceId: 'shared-device', workingDirectory: '/shared/project' };++// Both routes reach files outside the approved root on the device: the source+// of a copy and the external asset read are not confined to `workingDirectory`.+const routes = [+ {+ gateway: mocks.copyAssetForPublish,+ name: 'copyAssetForPublish',+ run: (caller: Caller) =>+ caller.copyAssetForPublish({+ ...base,+ from: '/outside/logo.png',+ to: '/shared/project/assets/logo.png',+ }),+ },+ {+ gateway: mocks.readExternalAssetForPublish,+ name: 'readExternalAssetForPublish',+ run: (caller: Caller) =>+ caller.readExternalAssetForPublish({ ...base, path: '/outside/logo.png' }),+ },+];++const workspaceCaller = (workspaceRole?: WorkspaceRole) =>+ deviceRouter.createCaller({+ userId: 'caller',+ workspaceId: 'workspace',+ workspaceRole,+ } as never);++describe('device publish asset workspace boundary', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findByDeviceId.mockResolvedValue(undefined);+ mocks.findWorkspaceDeviceById.mockResolvedValue({+ deviceId: base.deviceId,+ userId: 'enroller',+ visibility: 'public',+ workingDirs: [{ path: base.workingDirectory }],+ workspaceId: 'workspace',+ });+ mocks.copyAssetForPublish.mockResolvedValue({ success: true });+ mocks.readExternalAssetForPublish.mockResolvedValue({ success: true });+ mocks.getLocalFilePreview.mockResolvedValue({ success: true });+ });++ it.each(routes)(+ '$name rejects a workspace viewer before reaching the shared device',+ async ({ gateway, run }) => {+ await expect(run(workspaceCaller('viewer'))).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(gateway).not.toHaveBeenCalled();+ },+ );++ it.each(routes)(+ '$name rejects a workspace request without a role before reaching the device',+ async ({ gateway, run }) => {+ await expect(run(workspaceCaller())).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(gateway).not.toHaveBeenCalled();+ },+ );++ it.each(routes)(+ '$name allows a member on a public device enrolled by another member',+ async ({ gateway, run }) => {+ await expect(run(workspaceCaller('member'))).resolves.toEqual({ success: true });+ expect(gateway).toHaveBeenCalledOnce();+ },+ );++ it.each(routes)('$name allows a personal device without a workspace role', async ({ run }) => {+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: base.workingDirectory }] });+ const personal = deviceRouter.createCaller({ userId: 'enroller' } as never);++ await expect(run(personal)).resolves.toEqual({ success: true });+ });++ it('keeps read-only previews inside the approved root open to viewers', async () => {+ await expect(+ workspaceCaller('viewer').getLocalFilePreview({+ ...base,+ path: '/shared/project/index.html',+ }),+ ).resolves.toEqual({ success: true });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts b/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.tsindex 331784994ac..6cb63a81d5a 100644--- a/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts+++ b/apps/server/src/routers/lambda/__tests__/devicePullRequest.test.ts@@ -1,18 +1,45 @@// @vitest-environment node+import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';+import { deviceRouter } from '../device';const mocks = vi.hoisted(() => ({findByDeviceId: vi.fn(),+ findWorkspaceDeviceById: vi.fn(),runGitPullRequestAction: vi.fn(),}));+// OSS ships a no-op role guard. Model the cloud contract to exercise the+// router's write gate, including fail-closed scoped requests and personal mode.+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ const { trpc } = await import('@/libs/trpc/lambda/init');+ const ranks = { admin: 2, member: 1, owner: 3, viewer: 0 };++ return {+ ...actual,+ requireWorkspaceRoleWhenScoped: (minRole: WorkspaceRole) =>+ trpc.middleware(async ({ ctx, next }) => {+ const { workspaceId, workspaceRole } = ctx as {+ workspaceId?: string;+ workspaceRole?: WorkspaceRole;+ };+ if (workspaceId && (!workspaceRole || ranks[workspaceRole] < ranks[minRole])) {+ throw new TRPCError({ code: 'FORBIDDEN' });+ }+ return next();+ }),+ };+});+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));vi.mock('@/database/models/device', () => ({DeviceModel: class {findByDeviceId = mocks.findByDeviceId;- findWorkspaceDeviceById = async () => ({ deviceId: 'device' });+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;},}));vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({@@ -21,13 +48,88 @@ vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({}));describe('PR mutation workspace boundary', () => {- const caller = deviceRouter.createCaller({ userId: 'member', workspaceId: 'workspace' } as never);+ const caller = deviceRouter.createCaller({+ userId: 'member',+ workspaceId: 'workspace',+ workspaceRole: 'member',+ } as never);beforeEach(() => {vi.clearAllMocks();- mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/approved' }] });+ mocks.findByDeviceId.mockResolvedValue(undefined);+ mocks.findWorkspaceDeviceById.mockResolvedValue({+ deviceId: 'device',+ userId: 'enroller',+ visibility: 'public',+ workingDirs: [{ path: '/approved' }],+ });mocks.runGitPullRequestAction.mockResolvedValue({ success: true });});+ const actions = [+ { headRefOid: 'a'.repeat(40), method: 'squash', type: 'merge' },+ { headRefOid: 'a'.repeat(40), method: 'squash', type: 'autoMerge' },+ { type: 'disableAutoMerge' },+ { method: 'merge', type: 'updateBranch' },+ { type: 'ready' },+ { body: 'A comment', type: 'comment' },+ { type: 'close' },+ { type: 'reopen' },+ { head: 'feature', type: 'deleteBranch' },+ { base: 'canary', type: 'changeBase' },+ ] as const;++ it.each(actions)(+ 'rejects viewer action $type before reaching the shared device',+ async (action) => {+ const viewer = deviceRouter.createCaller({+ userId: 'viewer',+ workspaceId: 'workspace',+ workspaceRole: 'viewer',+ } as never);++ await expect(+ viewer.runGitPullRequestAction({+ action,+ deviceId: 'device',+ number: 42,+ path: '/approved',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.runGitPullRequestAction).not.toHaveBeenCalled();+ },+ );++ it('rejects a workspace request without a role before reaching the device', async () => {+ const unverified = deviceRouter.createCaller({+ userId: 'member',+ workspaceId: 'workspace',+ } as never);++ await expect(+ unverified.runGitPullRequestAction({+ action: { type: 'close' },+ deviceId: 'device',+ number: 42,+ path: '/approved',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.runGitPullRequestAction).not.toHaveBeenCalled();+ });++ it('allows personal device writes without a workspace role', async () => {+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/approved' }] });+ const personal = deviceRouter.createCaller({ userId: 'enroller' } as never);++ await expect(+ personal.runGitPullRequestAction({+ action: { type: 'close' },+ deviceId: 'device',+ number: 42,+ path: '/approved',+ }),+ ).resolves.toEqual({ success: true });+ });+it('rejects another repository before sending any command to the device', async () => {await expect(caller.runGitPullRequestAction({diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 704e026a791..84e63e0a562 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -231,7 +231,12 @@ const workspaceFileInput = z.object({*/const workspaceFileProcedure = deviceProcedure.input(workspaceFileInput).use(async (opts) => {const { deviceId, workingDirectory } = workspaceFileInput.parse(await opts.getRawInput());- await assertWorkspaceRootApproved(opts.ctx.deviceModel, deviceId, workingDirectory);+ await assertWorkspaceRootApproved(+ opts.ctx.deviceModel,+ deviceId,+ workingDirectory,+ opts.ctx.workspaceId,+ );return opts.next();});@@ -244,6 +249,17 @@ 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@@ -808,6 +824,7 @@ export const deviceRouter = router({* directory on a remote device, via the device's `runPullRequestAction` RPC.*/runGitPullRequestAction: deviceProcedure+ .use(requireWorkspaceRoleWhenScoped('member')).input(z.object({action: z.discriminatedUnion('type', [@@ -838,7 +855,12 @@ export const deviceRouter = router({}),).mutation(async ({ ctx, input }) => {- await assertWorkspaceRootApproved(ctx.deviceModel, input.deviceId, input.path);+ await assertWorkspaceRootApproved(+ ctx.deviceModel,+ input.deviceId,+ input.path,+ ctx.workspaceId,+ );return deviceGateway.runGitPullRequestAction({action: input.action,deviceId: input.deviceId,@@ -1080,7 +1102,7 @@ export const deviceRouter = router({});}),- copyAssetForPublish: workspaceFileProcedure+ copyAssetForPublish: workspacePublishProcedure.input(z.object({ from: z.string(), to: z.string() })).mutation(async ({ ctx, input }) =>deviceGateway.copyAssetForPublish({@@ -1093,7 +1115,7 @@ export const deviceRouter = router({}),),- readExternalAssetForPublish: workspaceFileProcedure+ readExternalAssetForPublish: workspacePublishProcedure.input(z.object({ path: z.string() })).query(async ({ ctx, input }) =>deviceGateway.readExternalAssetForPublish({diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.tsindex ded910d8171..29359fb6334 100644--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts@@ -40,11 +40,16 @@ const isWithinSkillRoots = (deviceId: string, workingDirectory: string): boolean* RPC is forwarded. The picker upserts every chosen directory into `workingDirs`* (see `useCommitWorkingDirectory`) and run start upserts the bound cwd, so a* legitimately-selected workspace is always present here.+ *+ * Use the request's authorized workspace scope for shared devices: their+ * `userId` is the enroller, not necessarily the caller. Never fall back to a+ * personal row, whose approved directories belong to a different device scope.*/export const assertWorkspaceRootApproved = async (deviceModel: DeviceModel,deviceId: string,workingDirectory: string,+ workspaceId?: string,): Promise<void> => {if (!workingDirectory) {throw new TRPCError({@@ -53,7 +58,9 @@ export const assertWorkspaceRootApproved = async (});}- const device = await deviceModel.findByDeviceId(deviceId);+ const device = workspaceId+ ? await deviceModel.findWorkspaceDeviceById(deviceId)+ : await deviceModel.findByDeviceId(deviceId);const approvedRoots = (device?.workingDirs ?? []).flatMap((dir) => [dir.path, dir.git?.activeWorktree])diff --git a/src/features/Portal/LocalFile/Header.tsx b/src/features/Portal/LocalFile/Header.tsxindex 5214cd95298..bb35089dc88 100644--- a/src/features/Portal/LocalFile/Header.tsx+++ b/src/features/Portal/LocalFile/Header.tsx@@ -16,11 +16,8 @@ import TabStrip from './TabStrip';const Header = memo<{ onClose?: () => void }>(({ onClose }) => {const { t } = useTranslation('chat');const activeLocalFilePath = useChatStore(chatPortalSelectors.activeLocalFilePath);- // Sandbox-backed tabs point at paths inside the cloud sandbox, not the local- // filesystem β "show in system" would open an unrelated folder or fail.- const isSandboxFile = useChatStore(- (s) => !!chatPortalSelectors.currentLocalFile(s)?.sandboxTopicId,- );+ // Remote device and sandbox paths cannot be revealed in the local filesystem.+ const isRemoteFile = useChatStore(chatPortalSelectors.isCurrentLocalFileRemote);const handleOpenFileFolder = useCallback(() => {if (!activeLocalFilePath) return;@@ -36,7 +33,7 @@ const Header = memo<{ onClose?: () => void }>(({ onClose }) => {rightExtra={isDesktop &&activeLocalFilePath &&- !isSandboxFile && (+ !isRemoteFile && (<ActionIconaria-label={t('workingPanel.files.showInSystem')}icon={FolderOpen}diff --git a/src/features/Portal/LocalFile/TabStrip.tsx b/src/features/Portal/LocalFile/TabStrip.tsxindex b685075d470..81416ff73e7 100644--- a/src/features/Portal/LocalFile/TabStrip.tsx+++ b/src/features/Portal/LocalFile/TabStrip.tsx@@ -13,7 +13,7 @@ import FileIcon from '@/components/FileIcon';import { localFileService } from '@/services/electron/localFileService';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';-import { getLocalFileTabId } from '@/store/chat/slices/portal/helpers';+import { getLocalFileTabId, isRemoteLocalFile } from '@/store/chat/slices/portal/helpers';const SKILL_PATH_RE = /\/\.(?:agents|claude)\/skills\/([^/]+)\/SKILL\.md$/;@@ -209,10 +209,9 @@ const TabStrip = memo(() => {label: t('workingPanel.localFile.closeOther'),onClick: () => closeOtherLocalFileTabs(id),},- // Sandbox-backed tabs point at paths inside the cloud sandbox β a local- // "show in system" would open an unrelated folder or fail.+ // Remote device and sandbox paths cannot be revealed in the local filesystem....(isDesktop &&- !openLocalFiles.find((file) => getLocalFileTabId(file) === id)?.sandboxTopicId+ !isRemoteLocalFile(openLocalFiles.find((file) => getLocalFileTabId(file) === id))? [{key: 'showInSystem',diff --git a/src/store/chat/slices/portal/helpers.test.ts b/src/store/chat/slices/portal/helpers.test.tsnew file mode 100644index 00000000000..6772074cbce--- /dev/null+++ b/src/store/chat/slices/portal/helpers.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++import { isRemoteLocalFile } from './helpers';++describe('isRemoteLocalFile', () => {+ const file = { filePath: '/work/index.html', workingDirectory: '/work' };++ it.each([+ ['local', file, false],+ ['remote device', { ...file, deviceId: 'remote-device' }, true],+ ['cloud sandbox', { ...file, sandboxTopicId: 'topic-a' }, true],+ ['missing', undefined, false],+ ])('identifies a %s file', (_label, entry, expected) => {+ expect(isRemoteLocalFile(entry)).toBe(expected);+ });+});diff --git a/src/store/chat/slices/portal/helpers.ts b/src/store/chat/slices/portal/helpers.tsindex b3ff3d4a76b..f931fbc5bbc 100644--- a/src/store/chat/slices/portal/helpers.ts+++ b/src/store/chat/slices/portal/helpers.ts@@ -36,3 +36,11 @@ export const createLocalFileTabId = ({export const getLocalFileTabId = (entry: OpenLocalFileParams & { id?: string }): string =>entry.id ?? createLocalFileTabId(entry);++/**+ * Whether a tab's path lives on another machine (a remote device or the cloud+ * sandbox) rather than this one's filesystem, so local OS actions such as+ * "show in system" would open an unrelated folder or fail.+ */+export const isRemoteLocalFile = (entry?: OpenLocalFileParams): boolean =>+ !!entry?.deviceId || !!entry?.sandboxTopicId;diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.tsindex 03eceffe5ec..eed72972634 100644--- a/src/store/chat/slices/portal/selectors.test.ts+++ b/src/store/chat/slices/portal/selectors.test.ts@@ -345,6 +345,34 @@ describe('chatDockSelectors', () => {});});+ describe('isCurrentLocalFileRemote', () => {+ it.each([+ ['local', {}, false],+ ['remote device', { deviceId: 'remote-device' }, true],+ ['cloud sandbox', { sandboxTopicId: 'topic-a' }, true],+ ])('identifies a %s file', (_label, source, expected) => {+ const file = { filePath: '/work/index.html', workingDirectory: '', ...source };+ const state = createState({+ activeLocalFilePath: file.filePath,+ activeTopicId: 'topic-a',+ openLocalFiles: [file],+ });+ expect(chatPortalSelectors.isCurrentLocalFileRemote(state)).toBe(expected);+ });++ it('follows the active tab when local and remote files share the same path', () => {+ const local = { filePath: '/work/index.html', workingDirectory: '/work' };+ const remote = { ...local, deviceId: 'remote-device' };+ const state = createState({+ activeLocalFileId: createLocalFileTabId(remote),+ openLocalFiles: [local, remote],+ });+ expect(chatPortalSelectors.isCurrentLocalFileRemote(state)).toBe(true);+ state.activeLocalFileId = createLocalFileTabId(local);+ expect(chatPortalSelectors.isCurrentLocalFileRemote(state)).toBe(false);+ });+ });+describe('currentLocalFile', () => {it('should return undefined when activeLocalFilePath is undefined', () => {expect(chatPortalSelectors.currentLocalFile(createState())).toBeUndefined();diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex 6ea80d2af44..4d153940bb7 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -8,6 +8,7 @@ import {createLocalFileScopeKey,createSandboxLocalFileScopeKey,getLocalFileTabId,+ isRemoteLocalFile,} from './helpers';import { type OpenLocalFileEntry, type PortalFile, type PortalViewData } from './initialState';import { PortalViewType } from './initialState';@@ -230,6 +231,9 @@ const currentLocalFile = (s: ChatStoreState): OpenLocalFileEntry | undefined =>);};+const isCurrentLocalFileRemote = (s: ChatStoreState): boolean =>+ isRemoteLocalFile(currentLocalFile(s));+const localFilePath = (s: ChatStoreState) => currentLocalFile(s)?.filePath;const localFileWorkingDirectory = (s: ChatStoreState) => currentLocalFile(s)?.workingDirectory;@@ -369,6 +373,7 @@ export const chatPortalSelectors = {activeLocalFileId,activeLocalFilePath,currentLocalFile,+ isCurrentLocalFileRemote,dirtyLocalFileContents,isLocalFileDirty,localFileBuffer,