The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): guard stale files refreshes
dougatbuck9abeb89a497f
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 8d29ec8b9de..8f538cfe650 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@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { HermesReadDirResult } from '@/global'import { $connection } from '@/store/session'+import { notifyWorkspaceChanged } from '@/store/workspace-events'import { clearProjectDirCache, readProjectDir } from './ipc'import { resetProjectTreeState, useProjectTree } from './use-project-tree'@@ -68,6 +69,36 @@ describe('useProjectTree', () => {expect(result.current.data).toEqual([])})+ it('does not fall back after a failed root read from a superseded connection', async () => {+ let resolveRootFromA: ((result: HermesReadDirResult) => void) | undefined+ const sanitizeWorkspaceCwd = vi.fn(async () => ({ cwd: '/fallback', sanitized: true }))+ readDir.mockImplementationOnce(+ () =>+ new Promise<HermesReadDirResult>(resolve => {+ resolveRootFromA = resolve+ })+ )+ readDir.mockResolvedValueOnce(ok([{ name: 'from-b', path: '/shared/from-b', isDirectory: false }]))+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { readDir, sanitizeWorkspaceCwd }+ $connection.set({ baseUrl: 'local-a', connectionId: 'connection-a', mode: 'local', profile: 'default' } as never)++ const { result } = renderHook(() => useProjectTree('/shared'))++ await waitFor(() => expect(readDir).toHaveBeenCalledTimes(1))++ act(() => {+ $connection.set({ baseUrl: 'local-b', connectionId: 'connection-b', mode: 'local', profile: 'default' } as never)+ })+ await waitFor(() => expect(readDir).toHaveBeenCalledTimes(2))++ await act(async () => {+ resolveRootFromA?.({ entries: [], error: 'ENOENT' })+ })++ await waitFor(() => expect(result.current.data.map(node => node.name)).toEqual(['from-b']))+ expect(sanitizeWorkspaceCwd).not.toHaveBeenCalled()+ })+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 }]))@@ -253,7 +284,83 @@ 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 () => {+ it('discards a stale live refresh after the active registered connection changes', async () => {+ let resolveRefreshFromA: ((result: HermesReadDirResult) => void) | undefined+ readDir.mockResolvedValueOnce(ok([{ name: 'from-a', path: '/shared/from-a', isDirectory: false }]))+ readDir.mockImplementationOnce(+ () =>+ new Promise<HermesReadDirResult>(resolve => {+ resolveRefreshFromA = 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(result.current.data.map(node => node.name)).toEqual(['from-a']))++ act(() => {+ notifyWorkspaceChanged()+ })+ await waitFor(() => expect(readDir).toHaveBeenCalledTimes(2))++ act(() => {+ $connection.set({+ baseUrl: 'https://gateway.example',+ connectionId: 'connection-b',+ mode: 'local',+ profile: 'default'+ } as never)+ })+ await waitFor(() => expect(result.current.data.map(node => node.name)).toEqual(['from-b']))++ await act(async () => {+ resolveRefreshFromA?.(ok([{ name: 'stale-a', path: '/shared/stale-a', isDirectory: false }]))+ })++ expect(result.current.data.map(node => node.name)).toEqual(['from-b'])+ })++ it('discards a stale child read after the active registered connection changes', async () => {+ let resolveChildFromA: ((result: HermesReadDirResult) => void) | undefined+ readDir.mockResolvedValueOnce(ok([{ name: 'src', path: '/shared/src', isDirectory: true }]))+ readDir.mockImplementationOnce(+ () =>+ new Promise<HermesReadDirResult>(resolve => {+ resolveChildFromA = resolve+ })+ )+ readDir.mockResolvedValueOnce(ok([{ name: 'src', path: '/shared/src', isDirectory: true }]))+ $connection.set({ baseUrl: 'https://gateway.example', connectionId: 'connection-a', mode: 'local', profile: 'default' } as never)++ const { result } = renderHook(() => useProjectTree('/shared'))++ await waitFor(() => expect(result.current.data[0]?.name).toBe('src'))++ act(() => {+ void result.current.loadChildren('/shared/src')+ })+ await waitFor(() => expect(readDir).toHaveBeenCalledTimes(2))++ act(() => {+ $connection.set({+ baseUrl: 'https://gateway.example',+ connectionId: 'connection-b',+ mode: 'local',+ profile: 'default'+ } as never)+ })+ await waitFor(() => expect(result.current.data[0]?.name).toBe('src'))++ await act(async () => {+ resolveChildFromA?.(ok([{ name: 'from-a', path: '/shared/src/from-a', isDirectory: false }]))+ })++ expect(result.current.data[0]).not.toMatchObject({ children: [{ name: 'from-a' }] })+ })++ it('discards a stale root read after the active registered connection changes', async () => {let resolveFirst: ((result: HermesReadDirResult) => void) | undefinedreadDir.mockImplementationOnce(() =>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 7bf7b2cc96f..22541fc51fa 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@@ -160,8 +160,8 @@ function clearProjectTree() {* than bricking the tree, display the sanitized workspace fallback (main* prefers the configured default project dir). Local connections only —* remote trees are read through the remote bridge. */-async function fallbackRootFor(cwd: string): Promise<string | null> {- if ($connection.get()?.mode === 'remote') {+async function fallbackRootFor(cwd: string, sourceIsRemote: boolean): Promise<string | null> {+ if (sourceIsRemote) {return null}@@ -180,7 +180,10 @@ async function fallbackRootFor(cwd: string): Promise<string | null> {}}-async function loadRoot(cwd: string, { force = false }: { force?: boolean } = {}) {+async function loadRoot(+ cwd: string,+ { connectionKey = desktopFsCacheKey(), force = false }: { connectionKey?: string; force?: boolean } = {}+) {if (!cwd) {clearProjectTree()@@ -213,6 +216,7 @@ async function loadRoot(cwd: string, { force = false }: { force?: boolean } = {}rootLoading: true})+ const sourceIsRemote = $connection.get()?.mode === 'remote'let resolvedCwd = cwdlet entries: ProjectTreeEntry[] = []let error: string | undefined@@ -220,8 +224,8 @@ async function loadRoot(cwd: string, { force = false }: { force?: boolean } = {}try {;({ entries, error } = await readProjectDir(cwd, cwd))- if (error) {- const fallback = await fallbackRootFor(cwd)+ if (error && desktopFsCacheKey() === connectionKey) {+ const fallback = await fallbackRootFor(cwd, sourceIsRemote)if (fallback) {const retry = await readProjectDir(fallback, fallback)@@ -238,7 +242,7 @@ async function loadRoot(cwd: string, { force = false }: { force?: boolean } = {}}setProjectTree(latest => {- if (latest.cwd !== cwd || latest.requestId !== requestId) {+ if (latest.cwd !== cwd || latest.requestId !== requestId || desktopFsCacheKey() !== connectionKey) {return latest}@@ -265,10 +269,14 @@ export function resetProjectTreeState() {// untouched folders never touch the filesystem or re-render. Falls back to// re-reading every loaded dir only when the mutation is opaque (a terminal// command / a path we couldn't resolve) — see store/workspace-events.-async function revalidateTree(cwd: string, change: { dirs: string[]; full: boolean }): Promise<void> {+async function revalidateTree(+ cwd: string,+ change: { dirs: string[]; full: boolean },+ connectionKey: string+): Promise<void> {const state = $projectTree.get()- if (!cwd || state.cwd !== cwd || !state.loaded) {+ if (!cwd || state.cwd !== cwd || !state.loaded || desktopFsCacheKey() !== connectionKey) {return}@@ -286,7 +294,7 @@ async function revalidateTree(cwd: string, change: { dirs: string[]; full: booleconst reads = await Promise.all(targets.map(async dir => ({ dir, ...(await readProjectDir(dir, rootPath)) })))setProjectTree(latest => {- if (latest.cwd !== cwd || !latest.loaded) {+ if (latest.cwd !== cwd || !latest.loaded || desktopFsCacheKey() !== connectionKey) {return latest}@@ -337,7 +345,9 @@ async function revalidateTree(cwd: string, change: { dirs: string[]; full: booleconst nextData = await reconcile(rootPath, state.data)- setProjectTree(latest => (latest.cwd === cwd && latest.loaded ? { ...latest, data: nextData } : latest))+ setProjectTree(latest =>+ latest.cwd === cwd && latest.loaded && desktopFsCacheKey() === connectionKey ? { ...latest, data: nextData } : latest+ )}/**@@ -353,7 +363,7 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {const workspaceTick = useStore($workspaceChangeTick)const connectionKey = desktopFsCacheKey(connection)- const refreshRoot = useCallback(() => loadRoot(cwd, { force: true }), [cwd])+ const refreshRoot = useCallback(() => loadRoot(cwd, { connectionKey, force: true }), [connectionKey, cwd])const setNodeOpen = useCallback((id: string, open: boolean) => {@@ -389,14 +399,16 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {const loadChildren = useCallback(async (id: string) => {- if (!cwd || inflight.has(id)) {+ const inflightKey = `${connectionKey}:${id}`++ if (!cwd || inflight.has(inflightKey)) {return}- inflight.add(id)+ inflight.add(inflightKey)setProjectTree(current => {- if (current.cwd !== cwd) {+ if (current.cwd !== cwd || desktopFsCacheKey() !== connectionKey) {return current}@@ -415,11 +427,11 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {} catch (cause) {error = readError(cause)} finally {- inflight.delete(id)+ inflight.delete(inflightKey)}setProjectTree(current => {- if (current.cwd !== cwd) {+ if (current.cwd !== cwd || desktopFsCacheKey() !== connectionKey) {return current}@@ -434,16 +446,16 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {}})},- [cwd]+ [connectionKey, cwd])// Live, non-destructive refresh when the agent touches the tree (skip the// very first render: tick 0 is the initial value, not a real change).useEffect(() => {if (workspaceTick > 0) {- void revalidateTree(cwd, consumeWorkspaceChange())+ void revalidateTree(cwd, consumeWorkspaceChange(), connectionKey)}- }, [workspaceTick, cwd])+ }, [connectionKey, cwd, workspaceTick])useEffect(() => {const connectionChanged = lastConnectionKey !== '' && lastConnectionKey !== connectionKey@@ -451,12 +463,12 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {if (connectionChanged) {clearProjectDirCache()- void loadRoot(cwd, { force: true })+ void loadRoot(cwd, { connectionKey, force: true })return}- void loadRoot(cwd)+ void loadRoot(cwd, { connectionKey })}, [connectionKey, cwd])// Self-heal: an errored root re-probes every few seconds while the tree is@@ -467,10 +479,10 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {return}- const timer = window.setTimeout(() => void loadRoot(cwd, { force: true }), ROOT_ERROR_RETRY_MS)+ const timer = window.setTimeout(() => void loadRoot(cwd, { connectionKey, force: true }), ROOT_ERROR_RETRY_MS)return () => window.clearTimeout(timer)- }, [cwd, state.cwd, state.requestId, state.rootError])+ }, [connectionKey, cwd, state.cwd, state.requestId, state.rootError])// While showing the fallback root, quietly re-probe the session's real cwd// (a worktree re-created, a checkout restored) and switch back when it@@ -485,18 +497,20 @@ export function useProjectTree(cwd: string): UseProjectTreeResult {let cancelled = falseconst timer = window.setInterval(() => {- void readProjectDir(cwd, cwd).then(({ error }) => {- if (!cancelled && !error) {- void loadRoot(cwd, { force: true })- }- })+ void readProjectDir(cwd, cwd)+ .then(({ error }) => {+ if (!cancelled && !error && desktopFsCacheKey() === connectionKey) {+ void loadRoot(cwd, { connectionKey, force: true })+ }+ })+ .catch(() => undefined)}, ROOT_ERROR_RETRY_MS)return () => {cancelled = truewindow.clearInterval(timer)}- }, [cwd, usingFallback])+ }, [connectionKey, cwd, usingFallback])return useMemo(() => ({