π OpenHands: AI-Driven Development
fix: scope files selection to conversation (#1354)
nanookclaw746a8b4a4fc0
diff --git a/__tests__/routes/files-tab.test.tsx b/__tests__/routes/files-tab.test.tsxindex 840efd2c32..03d08424d6 100644--- a/__tests__/routes/files-tab.test.tsx+++ b/__tests__/routes/files-tab.test.tsx@@ -7,6 +7,7 @@ import { MemoryRouter } from "react-router";import FilesTab from "#/routes/files-tab";import { useFilesTabStore } from "#/stores/files-tab-store";+import { NavigationProvider } from "#/context/navigation-context";// Mocks must be declared before the SUT is imported.const useHasAttachedSourceMock = vi.fn();@@ -44,15 +45,24 @@ vi.mock("#/routes/changes-tab", () => ({default: () => <div data-testid="changes-tab-content">Diff View</div>,}));-function renderTab() {+function renderTab(conversationId: string | null = null) {const client = new QueryClient({defaultOptions: { queries: { retry: false } },});return render(<MemoryRouter>- <QueryClientProvider client={client}>- <FilesTab />- </QueryClientProvider>+ <NavigationProvider+ value={{+ currentPath: "/",+ conversationId,+ isNavigating: false,+ navigate: () => {},+ }}+ >+ <QueryClientProvider client={client}>+ <FilesTab />+ </QueryClientProvider>+ </NavigationProvider></MemoryRouter>,);}@@ -65,7 +75,10 @@ describe("FilesTab", () => {// store polluted with the previous test's path. Resetting here, after// the previous test's cleanup() has unmounted any FilesTab, defeats// that race so each test starts with a clean selection.- useFilesTabStore.setState({ selectedPath: null });+ useFilesTabStore.setState({+ selectedPath: null,+ selectedConversationId: null,+ });useHasAttachedSourceMock.mockReset();useHasGitCommitsMock.mockReset();@@ -466,4 +479,114 @@ describe("FilesTab", () => {await user.click(refresh);expect(refetchGitChangesMock).toHaveBeenCalledTimes(1);});++ // Regression coverage for issue #1350: a file selected in one conversation+ // must not survive into another. The selection is global (Zustand) but+ // scoped to its conversation; the files tab ignores a path owned by a+ // different conversation so it never tries to open a file that only exists+ // in the previous conversation's workspace.+ describe("conversation switching", () => {+ beforeEach(() => {+ useHasAttachedSourceMock.mockReturnValue({+ hasAttachedSource: false,+ isLoading: false,+ });+ });++ it("ignores a stale selection from another conversation and auto-selects this conversation's file", async () => {+ // demo.html was opened in conversation A and only exists there.+ useFilesTabStore.setState({+ selectedPath: "demo.html",+ selectedConversationId: "conv-a",+ });+ // Conversation B's workspace does not contain demo.html.+ useWorkspaceFilesMock.mockReturnValue({+ data: ["app.html"],+ isLoading: false,+ });++ renderTab("conv-b");++ // The stale demo.html is never requested; B auto-selects its own file.+ await waitFor(() => {+ expect(useWorkspaceFileContentMock).toHaveBeenCalledWith("app.html");+ });+ expect(useWorkspaceFileContentMock).not.toHaveBeenCalledWith("demo.html");++ // The store ownership flips to the active conversation.+ await waitFor(() => {+ const state = useFilesTabStore.getState();+ expect(state.selectedPath).toBe("app.html");+ expect(state.selectedConversationId).toBe("conv-b");+ });+ });++ it("preserves a selection that belongs to the current conversation (explicit navigate_to_file)", async () => {+ // canvas_ui navigated this conversation to report.html outside React.+ useFilesTabStore.setState({+ selectedPath: "report.html",+ selectedConversationId: "conv-b",+ });+ useWorkspaceFilesMock.mockReturnValue({+ data: ["report.html", "app.html"],+ isLoading: false,+ });++ renderTab("conv-b");++ // The explicit selection is honored and auto-select does not override it.+ await waitFor(() => {+ expect(useWorkspaceFileContentMock).toHaveBeenCalledWith("report.html");+ });+ expect(useFilesTabStore.getState().selectedPath).toBe("report.html");+ });++ it("drops the selection when the tab switches to a different conversation", async () => {+ useWorkspaceFilesMock.mockReturnValue({+ data: ["demo.html"],+ isLoading: false,+ });++ const { rerender } = renderTab("conv-a");++ // Conversation A auto-selects and owns demo.html.+ await waitFor(() => {+ expect(useFilesTabStore.getState().selectedPath).toBe("demo.html");+ });+ expect(useFilesTabStore.getState().selectedConversationId).toBe("conv-a");++ // Switch the mounted tab to conversation B, whose workspace has app.html.+ useWorkspaceFileContentMock.mockClear();+ useWorkspaceFilesMock.mockReturnValue({+ data: ["app.html"],+ isLoading: false,+ });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ rerender(+ <MemoryRouter>+ <NavigationProvider+ value={{+ currentPath: "/",+ conversationId: "conv-b",+ isNavigating: false,+ navigate: () => {},+ }}+ >+ <QueryClientProvider client={client}>+ <FilesTab />+ </QueryClientProvider>+ </NavigationProvider>+ </MemoryRouter>,+ );++ // After the switch the tab follows B and never re-requests demo.html.+ await waitFor(() => {+ expect(useFilesTabStore.getState().selectedPath).toBe("app.html");+ });+ expect(useFilesTabStore.getState().selectedConversationId).toBe("conv-b");+ expect(useWorkspaceFileContentMock).not.toHaveBeenCalledWith("demo.html");+ });+ });});diff --git a/__tests__/services/canvas-ui.test.ts b/__tests__/services/canvas-ui.test.tsindex 2469b43267..71b084fe64 100644--- a/__tests__/services/canvas-ui.test.ts+++ b/__tests__/services/canvas-ui.test.ts@@ -22,18 +22,23 @@ describe("handleCanvasUIAction", () => {isRightPanelShown: false,hasRightPanelToggled: false,});- useFilesTabStore.setState({ selectedPath: null });+ useFilesTabStore.setState({+ selectedPath: null,+ selectedConversationId: null,+ });});it("navigate_to_file selects the files tab, reveals the panel, and sets selectedPath", () => {handleCanvasUIAction(action({ command: "navigate_to_file", path: "docs/intro.html" }),+ "conv-1",);const conv = useConversationStore.getState();expect(conv.selectedTab).toBe("files");expect(conv.isRightPanelShown).toBe(true);expect(useFilesTabStore.getState().selectedPath).toBe("docs/intro.html");+ expect(useFilesTabStore.getState().selectedConversationId).toBe("conv-1");});it("show_preview selects the files tab and the requested path", () => {diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsxindex c3c8389fdb..9e69e89902 100644--- a/src/contexts/conversation-websocket-context.tsx+++ b/src/contexts/conversation-websocket-context.tsx@@ -619,7 +619,7 @@ export function ConversationWebSocketProvider({// executes server-side as a no-op; the actual UI change happens// here on the client.if (isCanvasUIActionEvent(event)) {- handleCanvasUIAction(event.action);+ handleCanvasUIAction(event.action, conversationId ?? null);}}} catch (error) {diff --git a/src/routes/files-tab.tsx b/src/routes/files-tab.tsxindex eb42a38af3..4e6cbb36f8 100644--- a/src/routes/files-tab.tsx+++ b/src/routes/files-tab.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { useQueryClient } from "@tanstack/react-query";@@ -70,9 +70,26 @@ function FilesTab() {const filesQuery = useWorkspaceFiles();const paths = useMemo(() => filesQuery.data ?? [], [filesQuery.data]);- const selectedPath = useFilesTabStore((s) => s.selectedPath);+ const storedSelectedPath = useFilesTabStore((s) => s.selectedPath);+ const selectedConversationId = useFilesTabStore(+ (s) => s.selectedConversationId,+ );const setSelectedPath = useFilesTabStore((s) => s.setSelectedPath);+ // A selection is scoped to the conversation it was made in. Ignore a path+ // that belongs to a different conversation so we never try to open a file+ // that only exists in the previous conversation's workspace (issue #1350).+ // The auto-select effect below then picks this conversation's top file.+ const selectedPath =+ selectedConversationId === conversationId ? storedSelectedPath : null;++ // Tag every selection with the active conversation so it can't leak into+ // the next one. FileQuickRow / FileTreeView call this with just the path.+ const handleSelectFile = useCallback(+ (path: string) => setSelectedPath(path, conversationId),+ [conversationId, setSelectedPath],+ );+// Pre-fetch the selected file's content here too so the toolbar's// "open in new window" link can reach for its `staticUrl`. react-query// dedupes against `FileContentViewer`'s identical call, so this costs@@ -84,13 +101,18 @@ function FilesTab() {mutationCounter,);+ useEffect(() => {+ if (selectedConversationId === conversationId) return;+ setSelectedPath(null, conversationId);+ }, [selectedConversationId, conversationId, setSelectedPath]);+// Auto-select the highest-priority file the first time we load the list,// so users see something useful immediately.useEffect(() => {if (selectedPath || paths.length === 0) return;const [first] = sortFilesByPriority(paths);- if (first) setSelectedPath(first);- }, [paths, selectedPath]);+ if (first) setSelectedPath(first, conversationId);+ }, [paths, selectedPath, conversationId, setSelectedPath]);// Refresh button: covers the diff view (git changes) and the file viewer// (workspace listing + cached file contents). Lives in this toolbar β not@@ -188,7 +210,7 @@ function FilesTab() {<FileQuickRowpaths={paths}selectedPath={selectedPath}- onSelectFile={setSelectedPath}+ onSelectFile={handleSelectFile}isTreeVisible={isTreeVisible}onToggleTree={() => setIsTreeVisible((prev) => !prev)}/>@@ -201,7 +223,7 @@ function FilesTab() {<FileTreeViewpaths={paths}selectedPath={selectedPath}- onSelectFile={setSelectedPath}+ onSelectFile={handleSelectFile}/></aside>)}diff --git a/src/services/canvas-ui.ts b/src/services/canvas-ui.tsindex 5f531a54ce..583eb08d2a 100644--- a/src/services/canvas-ui.ts+++ b/src/services/canvas-ui.ts@@ -29,13 +29,18 @@ function isValidTab(value: string): value is ConversationTab {return VALID_TABS.has(value as ConversationTab);}-export function handleCanvasUIAction(action: CanvasUIAction): void {+export function handleCanvasUIAction(+ action: CanvasUIAction,+ conversationId: string | null = null,+): void {switch (action.command) {case "navigate_to_file":case "show_preview":navigateToTab("files");if (action.path) {- useFilesTabStore.getState().setSelectedPath(action.path);+ useFilesTabStore+ .getState()+ .setSelectedPath(action.path, conversationId);}return;case "open_tab":diff --git a/src/stores/files-tab-store.ts b/src/stores/files-tab-store.tsindex 59a32e754b..55cb1383e0 100644--- a/src/stores/files-tab-store.ts+++ b/src/stores/files-tab-store.ts@@ -2,12 +2,23 @@ import { create } from "zustand";interface FilesTabState {selectedPath: string | null;- setSelectedPath: (path: string | null) => void;+ // The conversation a selection belongs to. A file picked in one+ // conversation must not leak into another (it usually doesn't exist in the+ // other conversation's workspace, see issue #1350), so every selection is+ // tagged with its conversation and the files tab ignores a path owned by a+ // different conversation.+ selectedConversationId: string | null;+ setSelectedPath: (+ path: string | null,+ conversationId?: string | null,+ ) => void;}// Hoisted out of files-tab.tsx local state so non-React callers (e.g. the// canvas_ui tool dispatcher in the WebSocket context) can drive selection.export const useFilesTabStore = create<FilesTabState>((set) => ({selectedPath: null,- setSelectedPath: (selectedPath) => set({ selectedPath }),+ selectedConversationId: null,+ setSelectedPath: (selectedPath, conversationId = null) =>+ set({ selectedPath, selectedConversationId: conversationId }),}));