The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): isolate files across connections
dougatbuck30150fd08261
diff --git a/apps/desktop/src/app/right-sidebar/files/use-project-tree.test.ts b/apps/desktop/src/app/right-sidebar/files/use-project-tree.test.tsindex 00962a9e45d..8d29ec8b9de 100644--- a/apps/desktop/src/app/right-sidebar/files/use-project-tree.test.ts+++ b/apps/desktop/src/app/right-sidebar/files/use-project-tree.test.ts@@ -68,6 +68,25 @@ describe('useProjectTree', () => {expect(result.current.data).toEqual([])})+ it('clears root loading and recovers when a root read rejects', async () => {+ readDir.mockRejectedValueOnce(new Error('remote request aborted'))+ readDir.mockResolvedValueOnce(ok([{ name: 'IDEA.md', path: '/remote/IDEA.md', isDirectory: false }]))++ const { result } = renderHook(() => useProjectTree('/remote'))++ await waitFor(() => {+ expect(result.current.rootError).toBe('remote request aborted')+ expect(result.current.rootLoading).toBe(false)+ })++ await act(async () => {+ await result.current.refreshRoot()+ })++ expect(result.current.rootError).toBeNull()+ expect(result.current.data.map(node => node.name)).toEqual(['IDEA.md'])+ })+it('lazy-loads children on loadChildren and replaces the placeholder', async () => {readDir.mockResolvedValueOnce(ok([{ name: 'src', path: '/p/src', isDirectory: true }]))readDir.mockResolvedValueOnce(@@ -168,6 +187,29 @@ describe('useProjectTree', () => {])})+ it('clears child loading and allows retry when a child read rejects', async () => {+ readDir.mockResolvedValueOnce(ok([{ name: 'src', path: '/p/src', isDirectory: true }]))+ readDir.mockRejectedValueOnce(new Error('child request aborted'))+ readDir.mockResolvedValueOnce(ok([{ name: 'index.ts', path: '/p/src/index.ts', isDirectory: false }]))++ const { result } = renderHook(() => useProjectTree('/p'))++ await waitFor(() => expect(result.current.data.length).toBe(1))++ await act(async () => {+ await result.current.loadChildren('/p/src')+ })++ expect(result.current.data[0]).toMatchObject({ error: 'child request aborted', loading: false })++ await act(async () => {+ await result.current.loadChildren('/p/src')+ })++ expect(result.current.data[0]).toMatchObject({ error: undefined, loading: false })+ expect(result.current.data[0].children?.map(node => node.name)).toEqual(['index.ts'])+ })+it('dedupes concurrent loadChildren calls for the same id', async () => {readDir.mockResolvedValueOnce(ok([{ name: 'src', path: '/p/src', isDirectory: true }]))@@ -211,6 +253,35 @@ describe('useProjectTree', () => {expect(result.current.data.map(n => n.name)).toEqual(['README.md'])})+ it('reloads the same path when the active registered connection changes', async () => {+ let resolveFirst: ((result: HermesReadDirResult) => void) | undefined+ readDir.mockImplementationOnce(+ () =>+ new Promise<HermesReadDirResult>(resolve => {+ resolveFirst = resolve+ })+ )+ readDir.mockResolvedValueOnce(ok([{ name: 'from-b', path: '/shared/from-b', isDirectory: false }]))+ $connection.set({ baseUrl: 'https://gateway.example', connectionId: 'connection-a', mode: 'local', profile: 'default' } as never)++ const { result } = renderHook(() => useProjectTree('/shared'))++ await waitFor(() => expect(readDir).toHaveBeenCalledTimes(1))++ act(() => {+ $connection.set({+ baseUrl: 'https://gateway.example',+ connectionId: 'connection-b',+ mode: 'local',+ profile: 'default'+ } as never)+ resolveFirst?.(ok([{ name: 'from-a', path: '/shared/from-a', isDirectory: false }]))+ })++ await waitFor(() => expect(result.current.data.map(node => node.name)).toEqual(['from-b']))+ expect(readDir).toHaveBeenCalledTimes(2)+ })+it('reloads when cwd changes', async () => {readDir.mockResolvedValueOnce(ok([{ name: 'one', path: '/a/one', isDirectory: false }]))readDir.mockResolvedValueOnce(ok([{ name: 'two', path: '/b/two', isDirectory: false }]))diff --git a/apps/desktop/src/app/right-sidebar/files/use-project-tree.ts b/apps/desktop/src/app/right-sidebar/files/use-project-tree.tsindex 69ece75af56..7bf7b2cc96f 100644--- a/apps/desktop/src/app/right-sidebar/files/use-project-tree.ts+++ b/apps/desktop/src/app/right-sidebar/files/use-project-tree.ts@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'import { atom } from 'nanostores'import { useCallback, useEffect, useMemo } from 'react'+import { desktopFsCacheKey } from '@/lib/desktop-fs'import { $connection } from '@/store/session'import { $workspaceChangeTick, consumeWorkspaceChange } from '@/store/workspace-events'@@ -88,6 +89,10 @@ function errorChild(parentId: string, error: string | undefined): TreeNode {}}+function readError(cause: unknown): string {+ return cause instanceof Error && cause.message ? cause.message : 'read-error'+}+export interface UseProjectTreeResult {/** Bumped by collapseAll so callers can remount the tree fully collapsed. */collapseNonce: number@@ -209,20 +214,27 @@ async function loadRoot(cwd: string, { force = false }: { force?: boolean } = {}})let resolvedCwd = cwd- let { entries, error } = await readProjectDir(cwd, cwd)+ let entries: ProjectTreeEntry[] = []+ let error: string | undefined++ try {+ ;({ entries, error } = await readProjectDir(cwd, cwd))- if (error) {- const fallback = await fallbackRootFor(cwd)+ if (error) {+ const fallback = await fallbackRootFor(cwd)- if (fallback) {- const retry = await readProjectDir(fallback, fallback)+ if (fallback) {+ const retry = await readProjectDir(fallback, fallback)- if (!retry.error) {- resolvedCwd = fallback- entries = retry.entries- error = undefined+ if (!retry.error) {+ resolvedCwd = fallback+ entries = retry.entries+ error = undefined+ }}}+ } catch (cause) {+ error = readError(cause)}setProjectTree(latest => {@@ -339,7 +351,7 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {const state = useStore($projectTree)const connection = useStore($connection)const workspaceTick = useStore($workspaceChangeTick)- const connectionKey = `${connection?.mode || 'local'}:${connection?.profile || ''}:${connection?.baseUrl || ''}`+ const connectionKey = desktopFsCacheKey(connection)const refreshRoot = useCallback(() => loadRoot(cwd, { force: true }), [cwd])@@ -395,9 +407,16 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {})const rootPath = $projectTree.get().resolvedCwd || cwd- const { entries, error } = await readProjectDir(id, rootPath)-- inflight.delete(id)+ let entries: ProjectTreeEntry[] = []+ let error: string | undefined++ try {+ ;({ entries, error } = await readProjectDir(id, rootPath))+ } catch (cause) {+ error = readError(cause)+ } finally {+ inflight.delete(id)+ }setProjectTree(current => {if (current.cwd !== cwd) {diff --git a/apps/desktop/src/app/right-sidebar/index.test.tsx b/apps/desktop/src/app/right-sidebar/index.test.tsxindex 73ca3d46946..47f427a4beb 100644--- a/apps/desktop/src/app/right-sidebar/index.test.tsx+++ b/apps/desktop/src/app/right-sidebar/index.test.tsx@@ -2,7 +2,12 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { HermesReadDirResult } from '@/global'-import { $connection, setCurrentCwd } from '@/store/session'+import {+ $connection,+ $selectedStoredSessionId,+ $workspaceCwdOwner,+ setCurrentCwd+} from '@/store/session'import { resetProjectTreeState } from './files/use-project-tree'@@ -17,6 +22,8 @@ function installBridge() {describe('RightSidebarPane', () => {beforeEach(() => {$connection.set(null)+ $selectedStoredSessionId.set(null)+ $workspaceCwdOwner.set(null)resetProjectTreeState()readDir.mockReset()readDir.mockResolvedValue({ entries: [{ isDirectory: false, name: 'README.md', path: '/repo/README.md' }] })@@ -26,6 +33,8 @@ describe('RightSidebarPane', () => {afterEach(() => {cleanup()$connection.set(null)+ $selectedStoredSessionId.set(null)+ $workspaceCwdOwner.set(null)setCurrentCwd('')resetProjectTreeState()delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop@@ -46,6 +55,17 @@ describe('RightSidebarPane', () => {expect(screen.queryByRole('button', { name: 'Open folder' })).toBeNull()})+ it('does not read a retained cwd while it belongs to a previous session', async () => {+ $selectedStoredSessionId.set('new-session')+ $workspaceCwdOwner.set('previous-session')+ setCurrentCwd('/home/doug/default-profile-workspace')++ render(<RightSidebarPane onActivateFile={vi.fn()} onActivateFolder={vi.fn()} />)++ await waitFor(() => expect(screen.queryByRole('button', { name: 'Refresh tree' })).toBeNull())+ expect(readDir).not.toHaveBeenCalled()+ })+it('shows no tree for a detached chat (no working dir)', async () => {setCurrentCwd('')diff --git a/apps/desktop/src/app/right-sidebar/index.tsx b/apps/desktop/src/app/right-sidebar/index.tsxindex 67a2563fb8a..ed68af2478b 100644--- a/apps/desktop/src/app/right-sidebar/index.tsx+++ b/apps/desktop/src/app/right-sidebar/index.tsx@@ -13,7 +13,7 @@ import { cn } from '@/lib/utils'import { $panesFlipped } from '@/store/layout'import { notifyError } from '@/store/notifications'import { openPreview } from '@/store/preview'-import { $currentCwd } from '@/store/session'+import { $currentCwd, $selectedStoredSessionId, $workspaceCwdOwner } from '@/store/session'import { SidebarPanelLabel } from '../shell/sidebar-label'@@ -30,12 +30,14 @@ export function RightSidebarPane({ onActivateFile, onActivateFolder }: RightSideconst r = t.rightSidebarconst panesFlipped = useStore($panesFlipped)const currentCwd = useStore($currentCwd).trim()+ const selectedStoredSessionId = useStore($selectedStoredSessionId)+ const workspaceCwdOwner = useStore($workspaceCwdOwner)- // The file tree is simply "browse the session's working directory". If the- // session has a cwd — a repo, a sibling worktree, or any folder — show it. A- // bare/detached chat (resolveNewSessionCwd → '') has none, so it shows the- // empty hint instead of whatever dir Hermes happens to run from.- const hasWorkspace = Boolean(currentCwd)+ // A transition intentionally retains the old CWD until the new session+ // confirms its workspace. Do not issue a filesystem read against that path:+ // under a gateway switch it may belong to a different remote machine.+ const hasWorkspace =+ Boolean(currentCwd) && (workspaceCwdOwner ?? null) === (selectedStoredSessionId ?? null)const {collapseAll,diff --git a/apps/desktop/src/lib/desktop-fs.test.ts b/apps/desktop/src/lib/desktop-fs.test.tsindex 53698cae695..809cca02c46 100644--- a/apps/desktop/src/lib/desktop-fs.test.ts+++ b/apps/desktop/src/lib/desktop-fs.test.ts@@ -165,6 +165,43 @@ describe('desktop filesystem facade', () => {})})+ it('pins remote filesystem requests to the active registry connection', async () => {+ $connection.set({ connectionId: 'mr-small', mode: 'remote', profile: 'default' } as never)+ setApiRequestConnection('mr-small')++ await readDesktopDir('/home/doug/default-profile-workspace')+ await readDesktopFileText('/home/doug/default-profile-workspace/IDEA.md')+ await readDesktopFileDataUrl('/home/doug/default-profile-workspace/IDEA.md')+ await desktopGitRoot('/home/doug/default-profile-workspace')+ await desktopDefaultCwd()+ await desktopFileDiff('/home/doug/default-profile-workspace', 'IDEA.md')++ expect(api).toHaveBeenCalledTimes(6)++ for (const [request] of api.mock.calls) {+ expect(request).toMatchObject({ connectionId: 'mr-small', profile: 'default' })+ }+ })++ it('separates filesystem cache keys for registered connections sharing a profile', () => {+ $connection.set({+ baseUrl: 'https://gateway.example',+ connectionId: 'mr-small',+ mode: 'remote',+ profile: 'default'+ } as never)+ const mrSmallKey = desktopFsCacheKey()++ $connection.set({+ baseUrl: 'https://gateway.example',+ connectionId: 'other-default',+ mode: 'remote',+ profile: 'default'+ } as never)++ expect(desktopFsCacheKey()).not.toBe(mrSmallKey)+ })+it('keys SSH filesystem caches by stable host identity instead of the forwarded port', () => {$connection.set({mode: 'remote',diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.tsindex 65ba0fcab43..193ca274123 100644--- a/apps/desktop/src/lib/desktop-fs.ts+++ b/apps/desktop/src/lib/desktop-fs.ts@@ -22,6 +22,13 @@ function connectionCacheKey(connection: HermesConnection | null) {return 'local:'}+ // A profile belongs to a registry connection, not the whole Desktop. Prefer+ // the stable registry id so two backends exposing the same profile/path never+ // share filesystem/gitignore cache entries during a connection switch.+ if (connection.connectionId) {+ return `connection:${connection.connectionId}:${connection.profile || ''}`+ }+const target =connection.remoteKind === 'ssh'? connection.remoteIdentity || connection.remoteHost || ''