Skip to content

🙌 OpenHands: AI-Driven Development

feat(files): configure workspace file discovery (#17869)

kr1shna-exe917b5e15c474
diff --git a/.agents/skills/frontend-development/references/guide.md b/.agents/skills/frontend-development/references/guide.md
index e62cd07a36..99eb9facf5 100644
--- a/.agents/skills/frontend-development/references/guide.md
+++ b/.agents/skills/frontend-development/references/guide.md
@@ -5,6 +5,10 @@ Public skills are loaded from the `@openhands/extensions` npm package at build t
Bundled catalog skills use the persisted `enabled_skills` allow-list defaulted from `DEFAULT_ENABLED_SKILL_NAMES`. User and project skills remain enabled unless listed in `disabled_skills`. Keep this logic centralized in `src/utils/skill-enablement.ts`. The Agent Server no longer clones the extensions repository or uses `EXTENSIONS_REF` for public skills.
+## Workspace files
+
+Local Files discovery preferences belong to `misc_settings.app_preferences.workspace_file_discovery`, keyed by working directory on the active backend. `useWorkspaceFileDiscovery` reads the settings cache and saves sparse workspace patches. Preserve default exclusions and the 2,000-file cap when no configuration exists. Fetch one extra result to distinguish truncation from an exact-size list. Cloud keeps its server-side listing contract without these controls. See `specs/workspace-file-discovery.md`.
+
## No Magic Strings
Avoid inline string literals when they represent reusable user-facing copy or shared program identifiers. The `i18next/no-literal-string` rule is set to `"error"` for configured JSX text and attributes, and targeted `no-restricted-syntax` rules enforce shared translation and query-key patterns. Do not claim broader lint enforcement than `eslint.config.js` provides.
diff --git a/.pr/17863/01-before-files.png b/.pr/17863/01-before-files.png
new file mode 100644
index 0000000000..0f5f5d2ea1
Binary files /dev/null and b/.pr/17863/01-before-files.png differ
diff --git a/.pr/17863/02-after-files.png b/.pr/17863/02-after-files.png
new file mode 100644
index 0000000000..5aeee8d169
Binary files /dev/null and b/.pr/17863/02-after-files.png differ
diff --git a/.pr/17863/03-demo.mp4 b/.pr/17863/03-demo.mp4
new file mode 100644
index 0000000000..42c52e2925
Binary files /dev/null and b/.pr/17863/03-demo.mp4 differ
diff --git a/.pr/17863/04-settings.png b/.pr/17863/04-settings.png
new file mode 100644
index 0000000000..5a8b90932b
Binary files /dev/null and b/.pr/17863/04-settings.png differ
diff --git a/.pr/17863/05-truncated.png b/.pr/17863/05-truncated.png
new file mode 100644
index 0000000000..aa6dd75da0
Binary files /dev/null and b/.pr/17863/05-truncated.png differ
diff --git a/.pr/17863/design.md b/.pr/17863/design.md
new file mode 100644
index 0000000000..89011a514d
--- /dev/null
+++ b/.pr/17863/design.md
@@ -0,0 +1,43 @@
+# Configurable workspace file discovery
+
+The local Files panel can now list workspaces larger than 2,000 files and include file symlinks. Settings belong to the current backend and workspace. Existing defaults remain unchanged. Cloud listing keeps its existing API and behavior.
+
+## Before and after
+
+| Area | Before | After |
+| ------------------ | -------------------------------------------------- | ------------------------------------------------------------------ |
+| Discovery | Fixed directory exclusions and 2,000 regular files | Editable directory exclusions, an optional limit and file symlinks |
+| Incomplete results | Silent truncation | Fetch one extra result and show a warning when files are omitted |
+| Persistence | No discovery settings | Workspace-keyed values in existing server app preferences |
+| Controls | No configuration | Save, cancel and reset in the local Files panel |
+
+The [previous local listing hook](https://github.com/OpenHands/OpenHands/blob/a8c8fb377761fc7c562f19db1d9da75bba413cb9/src/hooks/query/use-workspace-files.ts) built a fixed shell command. The [updated hook](https://github.com/kr1shna-exe/OpenHands/blob/745692b2233da9766bb759cb3535fa4f996a4abe/src/hooks/query/use-workspace-files.ts#L45) waits for workspace settings and calls the [command builder](https://github.com/kr1shna-exe/OpenHands/blob/745692b2233da9766bb759cb3535fa4f996a4abe/src/utils/workspace-file-discovery.ts). That builder quotes exclusion patterns as shell data, prunes matching directories and fetches one extra path for finite limits. The parser removes the extra path while retaining the truncation flag.
+
+## State and compatibility
+
+The [settings hook](https://github.com/kr1shna-exe/OpenHands/blob/745692b2233da9766bb759cb3535fa4f996a4abe/src/hooks/query/use-workspace-file-discovery.ts) reads and writes `misc_settings.app_preferences.workspace_file_discovery` through the existing settings service. Each workspace path maps to `excludedPatterns`, `maxFiles` and `includeSymlinks`. A zero limit means unlimited. Sparse patches preserve other workspaces. Missing or malformed values fall back to existing defaults.
+
+The [dialog](https://github.com/kr1shna-exe/OpenHands/blob/745692b2233da9766bb759cb3535fa4f996a4abe/src/components/features/files-tab/workspace-file-discovery-settings.tsx) owns only unsaved input. Saving invalidates the settings query; cancel discards changes. A backend or workspace change resets the dialog scope. The mutation checks the active backend before writing. The [Files route](https://github.com/kr1shna-exe/OpenHands/blob/745692b2233da9766bb759cb3535fa4f996a4abe/src/routes/files-tab.tsx#L151) exposes the control and displays the truncation warning.
+
+This adds frontend-owned preferences to an existing opaque server field. It requires no new endpoint, server minimum-version increase or deployment migration.
+
+## Runtime evidence
+
+A real Agent Server 1.50.1 workspace contained 2,005 numbered files plus root `bin`, nested `bin`, `obj`, an instructions file and an `AGENTS.md` file symlink. The original command returned 2,000 paths. With unlimited discovery, file symlinks and exclusions `.git`, `node_modules`, `*/bin` and `obj`, the updated listing returned 2,008 paths. It retained root `bin`, omitted nested `bin` and `obj` and included the symlink. Reload preserved the configuration. Setting the limit to 3 showed the incomplete-tree warning.
+
+| Before | After |
+| -------------------------------------------- | --------------------------------------------- |
+| ![Original Files panel](01-before-files.png) | ![Configured Files panel](02-after-files.png) |
+
+[Settings screenshot](04-settings.png), [truncation warning](05-truncated.png) and [runtime recording](03-demo.mp4) show the same real backend flow. The recording includes initial UI setup. No model execution is needed for file discovery.
+
+## Verification and limits
+
+- `LANG=en_US.UTF-8 npm test`: 8,084 passed across 767 files with 7 existing TODOs.
+- Five focused suites: 78 passed, including shell-backed command execution and settings persistence.
+- `npm run lint`, `npm run build` and `npm run build:lib`: passed.
+- `npm run check-translation-completeness`: all 15 locales covered.
+
+Unlimited discovery can be expensive for large workspaces. Directory symlinks are not traversed. The existing line-based listing cannot represent filenames containing line breaks. Cross-window live settings synchronization is unchanged; reloading reads persisted values.
+
+These `.pr/17863/` files are temporary review artifacts and should be removed before merge. Source links use the implementation commit so they remain stable after artifact cleanup.
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.ts
index fff99df9c1..01094c5ca7 100644
--- a/__tests__/api/settings-service.test.ts
+++ b/__tests__/api/settings-service.test.ts
@@ -12,6 +12,7 @@ import { server } from "#/mocks/node";
import { resetTestHandlersMockSettings } from "#/mocks/settings-handlers";
import type { Settings } from "#/types/settings";
import { buildMcpServerPatch } from "#/utils/mcp-config";
+import { DEFAULT_FILE_DISCOVERY } from "#/utils/workspace-file-discovery";
const mockSaveCloudSettings = vi.fn();
const mockFetchCloudSettings = vi.fn();
@@ -173,6 +174,37 @@ describe("SettingsService", () => {
]);
});
+ // @spec WFD-002 — Workspace-scoped server persistence
+ it("sends a sparse workspace preference patch and hydrates the saved options", async () => {
+ const options = {
+ ...DEFAULT_FILE_DISCOVERY,
+ maxFiles: 0,
+ includeSymlinks: true,
+ };
+ const preferences = { workspace_file_discovery: { "/project": options } };
+ let patchBody: unknown;
+ server.use(
+ http.patch("*/api/settings", async ({ request }) => {
+ patchBody = await request.json();
+ return HttpResponse.json({});
+ }),
+ http.get("*/api/settings", () =>
+ HttpResponse.json({
+ agent_settings: {},
+ conversation_settings: {},
+ llm_api_key_is_set: false,
+ misc_settings: { app_preferences: preferences },
+ }),
+ ),
+ );
+ await SettingsService.saveSettings(preferences);
+ expect(patchBody).toEqual({
+ misc_settings_diff: { app_preferences: preferences },
+ });
+ const reloaded = await SettingsService.getSettings();
+ expect(reloaded.workspace_file_discovery?.["/project"]).toEqual(options);
+ });
+
it("stores the title profile as a local app preference", async () => {
const patchBodies: Array<Record<string, unknown>> = [];
server.use(
diff --git a/__tests__/components/features/files-tab/workspace-file-discovery-settings.test.tsx b/__tests__/components/features/files-tab/workspace-file-discovery-settings.test.tsx
new file mode 100644
index 0000000000..0a1145615b
--- /dev/null
+++ b/__tests__/components/features/files-tab/workspace-file-discovery-settings.test.tsx
@@ -0,0 +1,187 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { WorkspaceFileDiscoverySettings } from "#/components/features/files-tab/workspace-file-discovery-settings";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { DEFAULT_SETTINGS } from "#/services/settings";
+import { DEFAULT_FILE_DISCOVERY } from "#/utils/workspace-file-discovery";
+import { useSettings } from "#/hooks/query/use-settings";
+
+vi.mock("#/api/settings-service/settings-service.api", () => ({
+ default: { getSettings: vi.fn(), saveSettings: vi.fn() },
+}));
+
+const snapshots = {
+ local: { active: { backend: { id: "local", kind: "local" }, orgId: null } },
+ cloud: { active: { backend: { id: "cloud", kind: "cloud" }, orgId: null } },
+};
+let backend: keyof typeof snapshots = "local";
+vi.mock("#/api/backend-registry/active-store", () => ({
+ subscribeActiveBackend: () => () => {},
+ getSnapshot: () => snapshots[backend],
+ isNoBackend: () => false,
+}));
+
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => snapshots[backend].active,
+}));
+
+function SettingsConsumer() {
+ const { data } = useSettings();
+ return (
+ <output aria-label="MCP settings">
+ {JSON.stringify(data?.mcp_config)}
+ </output>
+ );
+}
+
+function setup() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const view = (path: string) => (
+ <QueryClientProvider client={client}>
+ <WorkspaceFileDiscoverySettings workingDir={path} />
+ </QueryClientProvider>
+ );
+ const rendered = render(view("/project"));
+ return {
+ user: userEvent.setup(),
+ navigate: (path: string) => rendered.rerender(view(path)),
+ };
+}
+
+// @spec WFD-002 — Workspace-scoped server persistence
+describe("workspace discovery settings", () => {
+ beforeEach(() => {
+ backend = "local";
+ vi.mocked(SettingsService.getSettings)
+ .mockReset()
+ .mockResolvedValue(DEFAULT_SETTINGS);
+ vi.mocked(SettingsService.saveSettings).mockReset().mockResolvedValue(true);
+ });
+
+ it("saves edited options for only the current workspace and reports failed saves", async () => {
+ const { user } = setup();
+ await user.click(
+ await screen.findByRole("button", { name: "FILES$DISCOVERY_SETTINGS" }),
+ );
+ await user.clear(screen.getByRole("spinbutton"));
+ await user.type(screen.getByRole("spinbutton"), "0");
+ await user.clear(screen.getByRole("textbox"));
+ await user.type(screen.getByRole("textbox"), "*/bin\nobj");
+ await user.click(screen.getByRole("checkbox"));
+ vi.mocked(SettingsService.saveSettings).mockRejectedValueOnce(
+ new Error("offline"),
+ );
+ await user.click(screen.getByRole("button", { name: "BUTTON$SAVE" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "FILES$DISCOVERY_SAVE_ERROR",
+ );
+ await user.click(screen.getByRole("button", { name: "BUTTON$SAVE" }));
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ expect(SettingsService.saveSettings).toHaveBeenLastCalledWith({
+ workspace_file_discovery: {
+ "/project": {
+ maxFiles: 0,
+ includeSymlinks: true,
+ excludedPatterns: ["*/bin", "obj"],
+ },
+ },
+ });
+ });
+
+ it("hydrates saved options, discards canceled drafts and restores defaults only on Save", async () => {
+ vi.mocked(SettingsService.getSettings).mockResolvedValue({
+ ...DEFAULT_SETTINGS,
+ workspace_file_discovery: {
+ "/project": {
+ excludedPatterns: [],
+ maxFiles: 3,
+ includeSymlinks: true,
+ },
+ },
+ });
+ const { user } = setup();
+ await user.click(
+ await screen.findByRole("button", { name: "FILES$DISCOVERY_SETTINGS" }),
+ );
+ expect(screen.getByRole("spinbutton")).toHaveValue(3);
+ await user.click(
+ screen.getByRole("button", { name: "FILES$DISCOVERY_RESET" }),
+ );
+ await user.click(screen.getByRole("button", { name: "BUTTON$CANCEL" }));
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ await user.click(
+ screen.getByRole("button", { name: "FILES$DISCOVERY_SETTINGS" }),
+ );
+ expect(screen.getByRole("spinbutton")).toHaveValue(3);
+ await user.click(
+ screen.getByRole("button", { name: "FILES$DISCOVERY_RESET" }),
+ );
+ await user.click(screen.getByRole("button", { name: "BUTTON$SAVE" }));
+ await waitFor(() =>
+ expect(SettingsService.saveSettings).toHaveBeenCalledWith({
+ workspace_file_discovery: { "/project": DEFAULT_FILE_DISCOVERY },
+ }),
+ );
+ });
+
+ it("discards an editor on workspace navigation and hides it on Cloud", async () => {
+ const { user, navigate } = setup();
+ await user.click(
+ await screen.findByRole("button", { name: "FILES$DISCOVERY_SETTINGS" }),
+ );
+ navigate("/other");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ backend = "cloud";
+ navigate("/other");
+ expect(
+ screen.queryByRole("button", { name: "FILES$DISCOVERY_SETTINGS" }),
+ ).not.toBeInTheDocument();
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ });
+
+ it("preserves normalized settings when file discovery mounts and saves", async () => {
+ const mcpConfig = {
+ docs: { transport: "sse" as const, url: "https://docs.example.test/sse" },
+ };
+ vi.mocked(SettingsService.getSettings).mockResolvedValue({
+ ...DEFAULT_SETTINGS,
+ agent_settings: { mcp_config: mcpConfig },
+ });
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const view = (showFiles: boolean) => (
+ <QueryClientProvider client={client}>
+ <SettingsConsumer />
+ {showFiles && <WorkspaceFileDiscoverySettings workingDir="/project" />}
+ </QueryClientProvider>
+ );
+ const rendered = render(view(false));
+ await waitFor(() =>
+ expect(
+ screen.getByRole("status", { name: "MCP settings" }),
+ ).toHaveTextContent(JSON.stringify(mcpConfig)),
+ );
+
+ rendered.rerender(view(true));
+ const user = userEvent.setup();
+ await user.click(
+ await screen.findByRole("button", { name: "FILES$DISCOVERY_SETTINGS" }),
+ );
+ await user.click(screen.getByRole("button", { name: "BUTTON$SAVE" }));
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+
+ expect(SettingsService.getSettings).toHaveBeenCalledTimes(2);
+ expect(
+ screen.getByRole("status", { name: "MCP settings" }),
+ ).toHaveTextContent(JSON.stringify(mcpConfig));
+ });
+});
diff --git a/__tests__/hooks/query/use-workspace-files.test.tsx b/__tests__/hooks/query/use-workspace-files.test.tsx
index b432e45936..0b066bad70 100644
--- a/__tests__/hooks/query/use-workspace-files.test.tsx
+++ b/__tests__/hooks/query/use-workspace-files.test.tsx
@@ -6,6 +6,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";
import { useWorkspaceFiles } from "#/hooks/query/use-workspace-files";
import { listCloudConversationFiles } from "#/api/cloud/conversation-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { DEFAULT_SETTINGS } from "#/services/settings";
+import { DEFAULT_FILE_DISCOVERY } from "#/utils/workspace-file-discovery";
+
+vi.mock("#/api/settings-service/settings-service.api", () => ({
+ default: { getSettings: vi.fn(), saveSettings: vi.fn() },
+}));
// The hook reads cloud/local from the backend-registry store (the same source
// the transport layer branches on), so drive the store snapshot in tests.
@@ -98,6 +105,7 @@ beforeEach(() => {
useOptionalConversationIdMock.mockReset();
executeCommandSpy.mockReset();
listCloudFilesMock.mockReset();
+ vi.mocked(SettingsService.getSettings).mockResolvedValue(DEFAULT_SETTINGS);
useRuntimeIsReadyMock.mockReturnValue(true);
useActiveConversationMock.mockReturnValue({ data: conversation });
@@ -114,6 +122,39 @@ describe("useWorkspaceFiles — local backend", () => {
storeBackendKind = "local";
});
+ // @spec WFD-002 — Workspace-scoped server persistence
+ it("uses persisted limits for the active workspace and changes them on navigation", async () => {
+ vi.mocked(SettingsService.getSettings).mockResolvedValue({
+ ...DEFAULT_SETTINGS,
+ workspace_file_discovery: {
+ "/workspace/project": { ...DEFAULT_FILE_DISCOVERY, maxFiles: 1 },
+ "/workspace/other": { ...DEFAULT_FILE_DISCOVERY, maxFiles: 0 },
+ },
+ });
+ executeCommandSpy.mockResolvedValue({
+ exit_code: 0,
+ stdout: "./a.txt\n./b.txt\n",
+ stderr: "",
+ });
+ const { result, rerender } = renderHook(() => useWorkspaceFiles(), {
+ wrapper: makeWrapper(),
+ });
+ await waitFor(() => expect(result.current.data).toEqual(["a.txt"]));
+ expect(result.current.isTruncated).toBe(true);
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ ...conversation,
+ id: "conv-2",
+ workspace: { working_dir: "/workspace/other" },
+ },
+ });
+ rerender();
+ await waitFor(() =>
+ expect(result.current.data).toEqual(["a.txt", "b.txt"]),
+ );
+ expect(result.current.isTruncated).toBe(false);
+ });
+
it("lists diagnostic files while the conversation is in Error", async () => {
const { useRuntimeIsReady } = await vi.importActual<
typeof import("#/hooks/use-runtime-is-ready")
diff --git a/__tests__/routes/files-tab.test.tsx b/__tests__/routes/files-tab.test.tsx
index 27afdf3f24..ab294eaed5 100644
--- a/__tests__/routes/files-tab.test.tsx
+++ b/__tests__/routes/files-tab.test.tsx
@@ -104,6 +104,19 @@ describe("FilesTab", () => {
).not.toBeInTheDocument();
});
+ // @spec WFD-001 — Configurable local workspace discovery
+ it("shows an incomplete-tree message when discovery is truncated", () => {
+ useWorkspaceFilesMock.mockReturnValue({
+ data: ["a.txt", "b.txt"],
+ isLoading: false,
+ isTruncated: true,
+ });
+ renderTab();
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "FILES$DISCOVERY_TRUNCATED",
+ );
+ });
+
it("does not open file tabs until a file is selected", () => {
renderTab();
diff --git a/__tests__/utils/workspace-file-discovery.test.ts b/__tests__/utils/workspace-file-discovery.test.ts
new file mode 100644
index 0000000000..be85b1e041
--- /dev/null
+++ b/__tests__/utils/workspace-file-discovery.test.ts
@@ -0,0 +1,85 @@
+import { execSync } from "node:child_process";
+import {
+ mkdtempSync,
+ mkdirSync,
+ writeFileSync,
+ symlinkSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ buildWorkspaceFileListCommand,
+ DEFAULT_FILE_DISCOVERY,
+ parseWorkspaceFileList,
+} from "#/utils/workspace-file-discovery";
+
+// @spec WFD-001 — Configurable local workspace discovery
+describe("workspace file discovery", () => {
+ let workspace: string;
+ beforeEach(() => {
+ workspace = mkdtempSync(join(tmpdir(), "workspace-discovery-"));
+ for (const directory of [
+ "bin",
+ "nested/bin",
+ "obj",
+ "node_modules",
+ "quoted'$(touch injected)",
+ ]) {
+ mkdirSync(join(workspace, directory), { recursive: true });
+ writeFileSync(join(workspace, directory, "file.txt"), "fixture");
+ }
+ writeFileSync(join(workspace, "instructions.md"), "fixture");
+ symlinkSync("instructions.md", join(workspace, "AGENTS.md"));
+ symlinkSync("nested", join(workspace, "directory-link"));
+ });
+ afterEach(() => rmSync(workspace, { recursive: true, force: true }));
+
+ const list = (options = DEFAULT_FILE_DISCOVERY) =>
+ parseWorkspaceFileList(
+ execSync(buildWorkspaceFileListCommand(options), {
+ cwd: workspace,
+ encoding: "utf8",
+ }),
+ options.maxFiles,
+ );
+
+ it("preserves default exclusions and omits symlinks", () => {
+ const result = list();
+ expect(result.paths).toContain("bin/file.txt");
+ expect(result.paths).not.toContain("node_modules/file.txt");
+ expect(result.paths).not.toContain("AGENTS.md");
+ expect(result.isTruncated).toBe(false);
+ });
+
+ it("prunes configured directories safely while preserving root bin and including file symlinks", () => {
+ const result = list({
+ maxFiles: 0,
+ includeSymlinks: true,
+ excludedPatterns: ["*/bin", "obj", "quoted'$(touch injected)"],
+ });
+ expect(result.paths).toEqual([
+ "AGENTS.md",
+ "bin/file.txt",
+ "instructions.md",
+ "node_modules/file.txt",
+ ]);
+ });
+
+ it("detects overflow without warning at an exact limit and removes the cap when unlimited", () => {
+ for (let index = 0; index < 2001; index += 1) {
+ writeFileSync(join(workspace, `${index}.txt`), "fixture");
+ }
+ expect(list().paths).toHaveLength(2000);
+ expect(list().isTruncated).toBe(true);
+ const unlimited = list({ ...DEFAULT_FILE_DISCOVERY, maxFiles: 0 });
+ expect(unlimited.paths.length).toBeGreaterThan(2000);
+ expect(unlimited.isTruncated).toBe(false);
+ const exact = list({
+ ...DEFAULT_FILE_DISCOVERY,
+ maxFiles: unlimited.paths.length,
+ });
+ expect(exact).toEqual(unlimited);
+ });
+});
diff --git a/specs/workspace-file-discovery.md b/specs/workspace-file-discovery.md
new file mode 100644
index 0000000000..cc427d8bf9
--- /dev/null
+++ b/specs/workspace-file-discovery.md
@@ -0,0 +1,20 @@
+# Workspace File Discovery
+
+### WFD-001: Configurable local workspace discovery
+
+- With no saved configuration, list at most 2,000 regular files using the existing directory exclusions.
+- Users can replace directory exclusions with name or workspace-relative path patterns. `*/bin` excludes nested `bin` directories while preserving root `bin`.
+- Quote every configured pattern as shell data. Patterns cannot execute commands.
+- A zero file limit means unlimited. A positive integer bounds the returned paths.
+- Optional symlink inclusion lists links to regular files without traversing directory links.
+- Read one extra path for a finite limit. Show an incomplete-tree message only when more paths exist than the configured limit.
+- Cloud file listing keeps its existing request and behavior.
+
+### WFD-002: Workspace-scoped server persistence
+
+- The local backend owns `misc_settings.app_preferences.workspace_file_discovery`, keyed by working directory.
+- Save a sparse map containing only the edited workspace so other workspace preferences survive the server's deep merge.
+- Conversations sharing a workspace use its configuration. A different workspace or backend uses its own configuration or defaults.
+- Saved preferences survive reload. Missing or invalid values fall back to conservative defaults.
+- Reset prepares the defaults for Save; Cancel discards the form draft. Failed saves keep the dialog open with an error.
+- Switching workspace or backend discards the open editor. Cloud never displays the editor or saves these settings.
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index 6bb1e58aff..388a0e3fb4 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -37,6 +37,7 @@ export const APP_PREFERENCE_FIELDS = [
"disabled_skills",
"enabled_skills",
"run_router_at_conversation_start",
+ "workspace_file_discovery",
] as const;
export type AppPreferenceField = (typeof APP_PREFERENCE_FIELDS)[number];
diff --git a/src/components/features/files-tab/workspace-file-discovery-settings.tsx b/src/components/features/files-tab/workspace-file-discovery-settings.tsx
new file mode 100644
index 0000000000..0ffd19f1c7
--- /dev/null
+++ b/src/components/features/files-tab/workspace-file-discovery-settings.tsx
@@ -0,0 +1,192 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { useWorkspaceFileDiscovery } from "#/hooks/query/use-workspace-file-discovery";
+import {
+ DEFAULT_FILE_DISCOVERY,
+ isValidFileLimit,
+ type WorkspaceFileDiscovery,
+} from "#/utils/workspace-file-discovery";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { ModalBody } from "#/components/shared/modals/modal-body";
+import { BrandButton } from "#/components/features/settings/brand-button";
+
+function DiscoveryForm({
+ options,
+ save,
+ isSaving,
+ onClose,
+}: {
+ options: WorkspaceFileDiscovery;
+ save: (options: WorkspaceFileDiscovery) => Promise<unknown>;
+ isSaving: boolean;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation("openhands");
+ // An unsaved form draft is discarded on cancel or workspace navigation.
+ const [patterns, setPatterns] = useState(options.excludedPatterns.join("\n"));
+ const [limit, setLimit] = useState(String(options.maxFiles));
+ const [includeSymlinks, setIncludeSymlinks] = useState(
+ options.includeSymlinks,
+ );
+ const [saveFailed, setSaveFailed] = useState(false);
+ const maxFiles = Number(limit);
+ const valid =
+ limit.trim() !== "" &&
+ isValidFileLimit(maxFiles) &&
+ !patterns.includes("\0");
+ const submit = async (value: WorkspaceFileDiscovery) => {
+ setSaveFailed(false);
+ try {
+ await save(value);
+ onClose();
+ } catch {
+ setSaveFailed(true);
+ }
+ };
+
+ return (
+ <ModalBackdrop
+ onClose={onClose}
+ aria-label={t(I18nKey.FILES$DISCOVERY_SETTINGS)}
+ closeOnEscape={!isSaving}
+ closeOnBackdropClick={!isSaving}
+ >
+ <ModalBody
+ width="md"
+ className="items-stretch max-h-[90vh] overflow-y-auto"
+ >
+ <h2 className="text-lg font-semibold">
+ {t(I18nKey.FILES$DISCOVERY_SETTINGS)}
+ </h2>
+ <p className="text-sm text-muted">{t(I18nKey.FILES$DISCOVERY_SCOPE)}</p>
+ <form
+ className="flex flex-col gap-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (valid && !isSaving)
+ void submit({
+ maxFiles,
+ includeSymlinks,
+ excludedPatterns: patterns
+ .split(/\r?\n/)
+ .map((pattern) => pattern.trim())
+ .filter(Boolean),
+ });
+ }}
+ >
+ <label className="flex flex-col gap-2 text-sm">
+ {t(I18nKey.FILES$DISCOVERY_EXCLUSIONS)}
+ <textarea
+ value={patterns}
+ onChange={(event) => setPatterns(event.target.value)}
+ rows={5}
+ disabled={isSaving}
+ className="rounded-md border border-border bg-base px-3 py-2 font-mono"
+ />
+ <span className="text-xs text-muted">
+ {t(I18nKey.FILES$DISCOVERY_PATTERN_HELP)}
+ </span>
+ </label>
+ <label className="flex flex-col gap-2 text-sm">
+ {t(I18nKey.FILES$DISCOVERY_LIMIT)}
+ <input
+ type="number"
+ min={0}
+ step={1}
+ max={Number.MAX_SAFE_INTEGER - 1}
+ required
+ value={limit}
+ disabled={isSaving}
+ onChange={(event) => setLimit(event.target.value)}
+ className="rounded-md border border-border bg-base px-3 py-2"
+ />
+ </label>
+ <label className="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ checked={includeSymlinks}
+ disabled={isSaving}
+ onChange={(event) => setIncludeSymlinks(event.target.checked)}
+ />
+ {t(I18nKey.FILES$DISCOVERY_SYMLINKS)}
+ </label>
+ {saveFailed && (
+ <p role="alert" className="text-sm text-danger">
+ {t(I18nKey.FILES$DISCOVERY_SAVE_ERROR)}
+ </p>
+ )}
+ <div className="flex flex-wrap justify-end gap-2">
+ <BrandButton
+ type="button"
+ variant="secondary"
+ isDisabled={isSaving}
+ onClick={() => {
+ setPatterns(DEFAULT_FILE_DISCOVERY.excludedPatterns.join("\n"));
+ setLimit(String(DEFAULT_FILE_DISCOVERY.maxFiles));
+ setIncludeSymlinks(DEFAULT_FILE_DISCOVERY.includeSymlinks);
+ }}
+ >
+ {t(I18nKey.FILES$DISCOVERY_RESET)}
+ </BrandButton>
+ <BrandButton
+ type="button"
+ variant="secondary"
+ isDisabled={isSaving}
+ onClick={onClose}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ type="submit"
+ variant="primary"
+ isDisabled={!valid || isSaving}
+ >
+ {t(isSaving ? I18nKey.SETTINGS$SAVING : I18nKey.BUTTON$SAVE)}
+ </BrandButton>
+ </div>
+ </form>
+ </ModalBody>
+ </ModalBackdrop>
+ );
+}
+
+function DiscoveryControl({
+ discovery,
+}: {
+ discovery: ReturnType<typeof useWorkspaceFileDiscovery>;
+}) {
+ const { t } = useTranslation("openhands");
+ const [isOpen, setIsOpen] = useState(false);
+ if (!discovery.canConfigure) return null;
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setIsOpen(true)}
+ className="px-2 py-1 text-xs text-muted hover:text-contrast"
+ data-testid="file-discovery-settings"
+ >
+ {t(I18nKey.FILES$DISCOVERY_SETTINGS)}
+ </button>
+ {isOpen && (
+ <DiscoveryForm
+ options={discovery.options}
+ save={discovery.save}
+ isSaving={discovery.isSaving}
+ onClose={() => setIsOpen(false)}
+ />
+ )}
+ </>
+ );
+}
+
+// @spec WFD-002 — Workspace-scoped server persistence
+export function WorkspaceFileDiscoverySettings({
+ workingDir,
+}: {
+ workingDir?: string;
+}) {
+ const discovery = useWorkspaceFileDiscovery(workingDir);
+ return <DiscoveryControl key={discovery.scopeKey} discovery={discovery} />;
+}
diff --git a/src/hooks/query/use-workspace-file-discovery.ts b/src/hooks/query/use-workspace-file-discovery.ts
new file mode 100644
index 0000000000..644b45b3df
--- /dev/null
+++ b/src/hooks/query/use-workspace-file-discovery.ts
@@ -0,0 +1,65 @@
+import { useSyncExternalStore } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ getSnapshot,
+ subscribeActiveBackend,
+} from "#/api/backend-registry/active-store";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import { getSettingsQueryFn } from "#/hooks/query/use-settings";
+import {
+ normalizeFileDiscovery,
+ type WorkspaceFileDiscovery,
+} from "#/utils/workspace-file-discovery";
+
+// @spec WFD-002 — Workspace-scoped server persistence
+export function useWorkspaceFileDiscovery(workingDir?: string) {
+ const { active } = useSyncExternalStore(
+ subscribeActiveBackend,
+ getSnapshot,
+ getSnapshot,
+ );
+ const isLocal = active.backend.kind === "local";
+ const client = useQueryClient();
+ const query = useQuery({
+ queryKey: [
+ ...SETTINGS_QUERY_KEYS.personal(),
+ active.backend.id,
+ active.orgId,
+ ],
+ queryFn: () => getSettingsQueryFn(),
+ enabled: isLocal && !!workingDir,
+ staleTime: 1000 * 60 * 5,
+ meta: { disableToast: true },
+ });
+ const backendId = active.backend.id;
+ const mutation = useMutation({
+ mutationFn: async (options: WorkspaceFileDiscovery) => {
+ // A dialog opened on one backend must never write into another.
+ if (
+ !workingDir ||
+ getSnapshot().active.backend.id !== backendId ||
+ !isLocal
+ ) {
+ throw new Error("Workspace backend changed");
+ }
+ await SettingsService.saveSettings({
+ workspace_file_discovery: { [workingDir]: options },
+ });
+ },
+ onSuccess: async () => {
+ await client.invalidateQueries({ queryKey: SETTINGS_QUERY_KEYS.all });
+ },
+ meta: { disableToast: true },
+ });
+ return {
+ options: normalizeFileDiscovery(
+ query.data?.workspace_file_discovery?.[workingDir ?? ""],
+ ),
+ isLoading: isLocal && !!workingDir && query.isLoading,
+ canConfigure: isLocal && !!workingDir && query.isSuccess,
+ scopeKey: `${backendId}:${workingDir ?? ""}`,
+ save: mutation.mutateAsync,
+ isSaving: mutation.isPending,
+ };
+}
diff --git a/src/hooks/query/use-workspace-files.ts b/src/hooks/query/use-workspace-files.ts
index c539b6e791..3c457d2016 100644
--- a/src/hooks/query/use-workspace-files.ts
+++ b/src/hooks/query/use-workspace-files.ts
@@ -11,6 +11,11 @@ import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
import { getGitPath } from "#/utils/get-git-path";
+import { useWorkspaceFileDiscovery } from "./use-workspace-file-discovery";
+import {
+ buildWorkspaceFileListCommand,
+ parseWorkspaceFileList,
+} from "#/utils/workspace-file-discovery";
// Cap the number of files we render so a giant repo doesn't freeze the UI.
const MAX_FILES = 2000;
@@ -18,32 +23,7 @@ const MAX_FILES = 2000;
export interface WorkspaceFilesResult {
data: string[] | undefined;
isLoading: boolean;
-}
-
-// Directory names that we never want to descend into when listing files.
-const EXCLUDED_DIRS = [
- ".git",
- "node_modules",
- ".venv",
- "venv",
- "__pycache__",
- "dist",
- "build",
- ".next",
- ".cache",
- ".pytest_cache",
- ".mypy_cache",
- ".turbo",
- ".parcel-cache",
- "target",
-];
-
-// Build a `find` invocation that lists files relative to the workspace root.
-function buildListCommand(): string {
- const pruneExpr = EXCLUDED_DIRS.map((dir) => `-name '${dir}' -prune`).join(
- " -o ",
- );
- return `find . \\( ${pruneExpr} \\) -o -type f -print 2>/dev/null | sort | head -n ${MAX_FILES}`;
+ isTruncated?: boolean;
}
function normalizePath(path: string): string {
@@ -70,20 +50,23 @@ function useLocalWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
const conversationUrl = conversation?.conversation_url;
const sessionApiKey = conversation?.session_api_key;
const workingDir = conversation?.workspace?.working_dir?.trim();
+ const discovery = useWorkspaceFileDiscovery(enabled ? workingDir : undefined);
+ const { options } = discovery;
- const query = useQuery<string[]>({
+ const query = useQuery({
queryKey: [
"workspace-files",
conversationId,
conversationUrl,
sessionApiKey,
workingDir,
+ options,
],
queryFn: async () => {
const result = await AgentServerRuntimeService.executeCommand(
conversationUrl,
sessionApiKey,
- buildListCommand(),
+ buildWorkspaceFileListCommand(options),
workingDir,
30,
conversationId,
@@ -95,23 +78,25 @@ function useLocalWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
);
}
- const lines = result.stdout
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter(Boolean)
- .map(normalizePath);
-
- // Defensive: keep results unique and bounded.
- return Array.from(new Set(lines)).slice(0, MAX_FILES);
+ return parseWorkspaceFileList(result.stdout, options.maxFiles);
},
- enabled: enabled && runtimeIsReady && !!conversationId && !!workingDir,
+ enabled:
+ enabled &&
+ runtimeIsReady &&
+ !!conversationId &&
+ !!workingDir &&
+ !discovery.isLoading,
retry: false,
staleTime: 1000 * 30,
gcTime: 1000 * 60 * 5,
meta: { disableToast: true },
});
- return { data: query.data, isLoading: query.isLoading };
+ return {
+ data: query.data?.paths,
+ isLoading: discovery.isLoading || query.isLoading,
+ isTruncated: query.data?.isTruncated ?? false,
+ };
}
/**
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index c1934dbdeb..6aac13a951 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -1,4 +1,157 @@
{
+ "FILES$DISCOVERY_SETTINGS": {
+ "en": "File discovery",
+ "ja": "ファイル探索",
+ "zh-CN": "文件发现",
+ "zh-TW": "檔案探索",
+ "ko-KR": "파일 검색",
+ "no": "Filoppdagelse",
+ "ar": "اكتشاف الملفات",
+ "de": "Dateisuche",
+ "fr": "Recherche de fichiers",
+ "it": "Ricerca file",
+ "pt": "Descoberta de arquivos",
+ "es": "Descubrimiento de archivos",
+ "ca": "Descobriment de fitxers",
+ "tr": "Dosya keşfi",
+ "uk": "Пошук файлів"
+ },
+ "FILES$DISCOVERY_SCOPE": {
+ "en": "Applies to this workspace on this backend, including other conversations using it.",
+ "ja": "このバックエンドの同じワークスペースを使う会話すべてに適用されます。",
+ "zh-CN": "适用于此后端上的当前工作区,包括使用它的其他对话。",
+ "zh-TW": "套用至此後端上的目前工作區,包括使用它的其他對話。",
+ "ko-KR": "이 백엔드에서 같은 작업 공간을 사용하는 모든 대화에 적용됩니다.",
+ "no": "Gjelder dette arbeidsområdet på denne backend-en, også andre samtaler som bruker det.",
+ "ar": "ينطبق على مساحة العمل هذه في هذه الواجهة الخلفية، بما في ذلك المحادثات الأخرى التي تستخدمها.",
+ "de": "Gilt für diesen Arbeitsbereich auf diesem Backend, auch für andere Unterhaltungen darin.",
+ "fr": "S’applique à cet espace de travail sur ce backend, y compris aux autres conversations qui l’utilisent.",
+ "it": "Si applica a questo spazio di lavoro su questo backend, incluse le altre conversazioni che lo usano.",
+ "pt": "Aplica-se a este espaço de trabalho neste backend, incluindo outras conversas que o utilizam.",
+ "es": "Se aplica a este espacio de trabajo en este backend, incluidas otras conversaciones que lo utilicen.",
+ "ca": "S’aplica a aquest espai de treball en aquest backend, incloses altres converses que l’utilitzin.",
+ "tr": "Bu arka uçta aynı çalışma alanını kullanan diğer konuşmalar için de geçerlidir.",
+ "uk": "Застосовується до цього робочого простору на цьому сервері, зокрема до інших розмов у ньому."
+ },
+ "FILES$DISCOVERY_EXCLUSIONS": {
+ "en": "Excluded directories",
+ "ja": "除外するディレクトリ",
+ "zh-CN": "排除的目录",
+ "zh-TW": "排除的目錄",
+ "ko-KR": "제외할 디렉터리",
+ "no": "Utelatte mapper",
+ "ar": "المجلدات المستبعدة",
+ "de": "Ausgeschlossene Verzeichnisse",
+ "fr": "Dossiers exclus",
+ "it": "Directory escluse",
+ "pt": "Diretórios excluídos",
+ "es": "Directorios excluidos",
+ "ca": "Directoris exclosos",
+ "tr": "Hariç tutulan dizinler",
+ "uk": "Виключені каталоги"
+ },
+ "FILES$DISCOVERY_PATTERN_HELP": {
+ "en": "One pattern per line. Names match anywhere; paths are relative to the workspace. Use */bin to exclude nested bin directories while keeping the root bin.",
+ "ja": "1行に1パターン。名前は全階層、パスはワークスペース基準です。*/bin はルートの bin を残して下位の bin を除外します。",
+ "zh-CN": "每行一个模式。名称匹配任意层级;路径相对于工作区。使用 */bin 排除嵌套 bin 目录并保留根目录的 bin。",
+ "zh-TW": "每行一個模式。名稱符合任意層級;路徑相對於工作區。使用 */bin 排除巢狀 bin 目錄並保留根目錄的 bin。",
+ "ko-KR": "한 줄에 패턴 하나를 입력하세요. 이름은 모든 위치에, 경로는 작업 공간 기준으로 적용됩니다. */bin은 루트 bin을 유지하고 하위 bin을 제외합니다.",
+ "no": "Ett mønster per linje. Navn gjelder overalt; stier er relative til arbeidsområdet. */bin utelater undermapper kalt bin, men beholder bin i roten.",
+ "ar": "نمط واحد في كل سطر. تطابق الأسماء في أي مكان؛ المسارات نسبية لمساحة العمل. استخدم */bin لاستبعاد مجلدات bin المتداخلة مع إبقاء bin في الجذر.",
+ "de": "Ein Muster pro Zeile. Namen gelten überall; Pfade sind relativ zum Arbeitsbereich. */bin schließt verschachtelte bin-Verzeichnisse aus und behält bin im Stamm.",
+ "fr": "Un motif par ligne. Les noms s’appliquent partout ; les chemins sont relatifs à l’espace de travail. */bin exclut les dossiers bin imbriqués et conserve celui à la racine.",
+ "it": "Un modello per riga. I nomi valgono ovunque; i percorsi sono relativi allo spazio di lavoro. */bin esclude le directory bin annidate ma mantiene quella nella radice.",
+ "pt": "Um padrão por linha. Nomes correspondem em qualquer local; caminhos são relativos ao espaço de trabalho. */bin exclui diretórios bin aninhados e mantém o bin da raiz.",
+ "es": "Un patrón por línea. Los nombres coinciden en cualquier nivel; las rutas son relativas al espacio de trabajo. */bin excluye directorios bin anidados y conserva el de la raíz.",
+ "ca": "Un patró per línia. Els noms coincideixen a qualsevol nivell; els camins són relatius a l’espai de treball. */bin exclou directoris bin imbricats i conserva el de l’arrel.",
+ "tr": "Her satıra bir desen yazın. Adlar her yerde eşleşir; yollar çalışma alanına göredir. */bin kökteki bin dizinini koruyup iç içe bin dizinlerini hariç tutar.",
+ "uk": "Один шаблон на рядок. Назви зіставляються всюди; шляхи відносні до робочого простору. */bin виключає вкладені каталоги bin, зберігаючи bin у корені."
+ },
+ "FILES$DISCOVERY_LIMIT": {
+ "en": "Maximum files (0 for unlimited)",
+ "ja": "最大ファイル数(0で無制限)",
+ "zh-CN": "最大文件数(0 表示无限制)",
+ "zh-TW": "最大檔案數(0 表示無限制)",
+ "ko-KR": "최대 파일 수 (0은 무제한)",
+ "no": "Maksimalt antall filer (0 for ubegrenset)",
+ "ar": "الحد الأقصى للملفات (0 دون حد)",
+ "de": "Maximale Dateianzahl (0 für unbegrenzt)",
+ "fr": "Nombre maximal de fichiers (0 pour illimité)",
+ "it": "Numero massimo di file (0 per illimitato)",
+ "pt": "Máximo de arquivos (0 para ilimitado)",
+ "es": "Máximo de archivos (0 para ilimitado)",
+ "ca": "Màxim de fitxers (0 per il·limitat)",
+ "tr": "En fazla dosya (sınırsız için 0)",
+ "uk": "Максимум файлів (0 — без обмежень)"
+ },
+ "FILES$DISCOVERY_SYMLINKS": {
+ "en": "Include symbolic links to files",
+ "ja": "ファイルへのシンボリックリンクを含める",
+ "zh-CN": "包含指向文件的符号链接",
+ "zh-TW": "包含指向檔案的符號連結",
+ "ko-KR": "파일 심볼릭 링크 포함",
+ "no": "Inkluder symbolske lenker til filer",
+ "ar": "تضمين الروابط الرمزية إلى الملفات",
+ "de": "Symbolische Links auf Dateien einschließen",
+ "fr": "Inclure les liens symboliques vers des fichiers",
+ "it": "Includi collegamenti simbolici ai file",
+ "pt": "Incluir links simbólicos para arquivos",
+ "es": "Incluir enlaces simbólicos a archivos",
+ "ca": "Inclou enllaços simbòlics a fitxers",
+ "tr": "Dosyalara sembolik bağlantıları dahil et",
+ "uk": "Включати символічні посилання на файли"
+ },
+ "FILES$DISCOVERY_SAVE_ERROR": {
+ "en": "Could not save file discovery settings. Try again.",
+ "ja": "ファイル探索設定を保存できませんでした。再試行してください。",
+ "zh-CN": "无法保存文件发现设置。请重试。",
+ "zh-TW": "無法儲存檔案探索設定。請重試。",
+ "ko-KR": "파일 검색 설정을 저장하지 못했습니다. 다시 시도하세요.",
+ "no": "Kunne ikke lagre innstillingene for filoppdagelse. Prøv igjen.",
+ "ar": "تعذر حفظ إعدادات اكتشاف الملفات. حاول مجددًا.",
+ "de": "Die Einstellungen zur Dateisuche konnten nicht gespeichert werden. Bitte erneut versuchen.",
+ "fr": "Impossible d’enregistrer les paramètres de recherche de fichiers. Réessayez.",
+ "it": "Impossibile salvare le impostazioni di ricerca file. Riprova.",
+ "pt": "Não foi possível salvar as configurações de descoberta de arquivos. Tente novamente.",
+ "es": "No se pudo guardar la configuración de descubrimiento de archivos. Inténtalo de nuevo.",
+ "ca": "No s’ha pogut desar la configuració de descobriment de fitxers. Torna-ho a provar.",
+ "tr": "Dosya keşfi ayarları kaydedilemedi. Tekrar deneyin.",
+ "uk": "Не вдалося зберегти налаштування пошуку файлів. Спробуйте ще раз."
+ },
+ "FILES$DISCOVERY_RESET": {
+ "en": "Restore defaults",
+ "ja": "既定値に戻す",
+ "zh-CN": "恢复默认值",
+ "zh-TW": "還原預設值",
+ "ko-KR": "기본값 복원",
+ "no": "Gjenopprett standardverdier",
+ "ar": "استعادة الإعدادات الافتراضية",
+ "de": "Standardwerte wiederherstellen",
+ "fr": "Rétablir les valeurs par défaut",
+ "it": "Ripristina valori predefiniti",
+ "pt": "Restaurar padrões",
+ "es": "Restaurar valores predeterminados",
+ "ca": "Restaura els valors per defecte",
+ "tr": "Varsayılanları geri yükle",
+ "uk": "Відновити типові значення"
+ },
+ "FILES$DISCOVERY_TRUNCATED": {
+ "en": "Showing the first {{count}} files. This tree is incomplete. Adjust File discovery to see more.",
+ "ja": "最初の {{count}} ファイルを表示しています。ツリーは不完全です。「ファイル探索」を調整してください。",
+ "zh-CN": "显示前 {{count}} 个文件。此文件树不完整。调整文件发现设置以查看更多。",
+ "zh-TW": "顯示前 {{count}} 個檔案。此檔案樹不完整。調整檔案探索設定以查看更多。",
+ "ko-KR": "처음 {{count}}개 파일만 표시합니다. 전체 트리가 아닙니다. 더 보려면 파일 검색 설정을 조정하세요.",
+ "no": "Viser de første {{count}} filene. Treet er ufullstendig. Juster Filoppdagelse for å se flere.",
+ "ar": "تُعرض أول {{count}} من الملفات. هذه الشجرة غير مكتملة. عدّل اكتشاف الملفات لرؤية المزيد.",
+ "de": "Die ersten {{count}} Dateien werden angezeigt. Der Baum ist unvollständig. Passen Sie die Dateisuche an, um mehr zu sehen.",
+ "fr": "Affichage des {{count}} premiers fichiers. Cette arborescence est incomplète. Ajustez la recherche de fichiers pour en voir davantage.",
+ "it": "Sono mostrati i primi {{count}} file. L’albero è incompleto. Modifica la ricerca file per visualizzarne altri.",
+ "pt": "Mostrando os primeiros {{count}} arquivos. Esta árvore está incompleta. Ajuste a descoberta de arquivos para ver mais.",
+ "es": "Se muestran los primeros {{count}} archivos. Este árbol está incompleto. Ajusta el descubrimiento de archivos para ver más.",
+ "ca": "Es mostren els primers {{count}} fitxers. Aquest arbre és incomplet. Ajusta el descobriment de fitxers per veure’n més.",
+ "tr": "İlk {{count}} dosya gösteriliyor. Bu ağaç eksik. Daha fazlası için Dosya keşfi ayarlarını değiştirin.",
+ "uk": "Показано перші {{count}} файлів. Це дерево неповне. Налаштуйте пошук файлів, щоб побачити більше."
+ },
"HOME$ISOLATED_WORKSPACE_NEW": {
"en": "New isolated workspace",
"ja": "新しい分離ワークスペース",
diff --git a/src/routes/files-tab.tsx b/src/routes/files-tab.tsx
index bc92f05f9f..32d53ca817 100644
--- a/src/routes/files-tab.tsx
+++ b/src/routes/files-tab.tsx
@@ -23,6 +23,7 @@ import { FileTreeView } from "#/components/features/files-tab/file-tree-view";
import { FileContentViewer } from "#/components/features/files-tab/file-content-viewer";
import { SegmentedToggle } from "#/components/features/files-tab/segmented-toggle";
import { WorkspacePath } from "#/components/features/files-tab/workspace-path";
+import { WorkspaceFileDiscoverySettings } from "#/components/features/files-tab/workspace-file-discovery-settings";
import type { ViewMode } from "#/components/features/files-tab/view-mode";
import {
FILES_TAB_TREE_DEFAULT_WIDTH_PX,
@@ -146,22 +147,25 @@ function FilesTab() {
};
const quickRowActions = (
- <button
- type="button"
- onClick={refreshFiles}
- disabled={isRefreshing}
- aria-label={t(I18nKey.FILES$REFRESH)}
- title={t(I18nKey.FILES$REFRESH)}
- data-testid="files-tab-refresh"
- className="flex items-center justify-center w-6.5 py-1 rounded-[7px] hover:enabled:bg-interactive-hover cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
- >
- <RefreshIcon
- width={12.75}
- height={15}
- color="#ffffff"
- className={isRefreshing ? "animate-spin" : ""}
- />
- </button>
+ <>
+ <WorkspaceFileDiscoverySettings workingDir={workspacePath?.trim()} />
+ <button
+ type="button"
+ onClick={refreshFiles}
+ disabled={isRefreshing}
+ aria-label={t(I18nKey.FILES$REFRESH)}
+ title={t(I18nKey.FILES$REFRESH)}
+ data-testid="files-tab-refresh"
+ className="flex items-center justify-center w-6.5 py-1 rounded-[7px] hover:enabled:bg-interactive-hover cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <RefreshIcon
+ width={12.75}
+ height={15}
+ color="#ffffff"
+ className={isRefreshing ? "animate-spin" : ""}
+ />
+ </button>
+ </>
);
return (
@@ -170,6 +174,14 @@ function FilesTab() {
data-testid="files-tab"
>
<WorkspacePath path={workspacePath} />
+ {filesQuery.isTruncated && (
+ <p
+ role="status"
+ className="border-b border-border px-3 py-2 text-xs text-muted"
+ >
+ {t(I18nKey.FILES$DISCOVERY_TRUNCATED, { count: paths.length })}
+ </p>
+ )}
{filesQuery.isLoading ? (
<div className="flex flex-1 items-center justify-center text-sm text-muted">
{t(I18nKey.FILES$LOADING_FILES)}
diff --git a/src/types/settings.ts b/src/types/settings.ts
index a4fbab30b1..15e21ef337 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -1,6 +1,7 @@
import type { MCPConfig } from "@openhands/typescript-client";
export type { MCPConfig } from "@openhands/typescript-client";
import type { SkillCategoryId } from "@openhands/extensions/skills";
+import type { WorkspaceFileDiscovery } from "#/utils/workspace-file-discovery";
export const ProviderOptions = {
github: "github",
@@ -110,6 +111,7 @@ export type SettingsScope = "personal";
export type AgentKind = "openhands" | "acp";
export type Settings = {
+ workspace_file_discovery?: Record<string, WorkspaceFileDiscovery | null>;
llm_model: string;
llm_base_url: string;
agent: string;
diff --git a/src/utils/workspace-file-discovery.ts b/src/utils/workspace-file-discovery.ts
new file mode 100644
index 0000000000..d0a11a1df9
--- /dev/null
+++ b/src/utils/workspace-file-discovery.ts
@@ -0,0 +1,93 @@
+export interface WorkspaceFileDiscovery {
+ excludedPatterns: string[];
+ /** Zero means unlimited. */
+ maxFiles: number;
+ includeSymlinks: boolean;
+}
+
+export const DEFAULT_FILE_DISCOVERY: WorkspaceFileDiscovery = {
+ excludedPatterns: [
+ ".git",
+ "node_modules",
+ ".venv",
+ "venv",
+ "__pycache__",
+ "dist",
+ "build",
+ ".next",
+ ".cache",
+ ".pytest_cache",
+ ".mypy_cache",
+ ".turbo",
+ ".parcel-cache",
+ "target",
+ ],
+ maxFiles: 2000,
+ includeSymlinks: false,
+};
+
+export function isValidFileLimit(value: number): boolean {
+ return (
+ Number.isSafeInteger(value) && value >= 0 && value < Number.MAX_SAFE_INTEGER
+ );
+}
+
+export function normalizeFileDiscovery(value: unknown): WorkspaceFileDiscovery {
+ if (!value || typeof value !== "object") return DEFAULT_FILE_DISCOVERY;
+ const options = value as Partial<WorkspaceFileDiscovery>;
+ return {
+ excludedPatterns:
+ Array.isArray(options.excludedPatterns) &&
+ options.excludedPatterns.every(
+ (pattern) =>
+ typeof pattern === "string" &&
+ pattern.length > 0 &&
+ !/[\0\r\n]/.test(pattern),
+ )
+ ? options.excludedPatterns
+ : DEFAULT_FILE_DISCOVERY.excludedPatterns,
+ maxFiles:
+ typeof options.maxFiles === "number" && isValidFileLimit(options.maxFiles)
+ ? options.maxFiles
+ : DEFAULT_FILE_DISCOVERY.maxFiles,
+ includeSymlinks: options.includeSymlinks === true,
+ };
+}
+
+const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
+
+// @spec WFD-001 — Configurable local workspace discovery
+export function buildWorkspaceFileListCommand(
+ options: WorkspaceFileDiscovery,
+): string {
+ const patterns = options.excludedPatterns.map((pattern) => {
+ if (!pattern.includes("/")) return `-name ${shellQuote(pattern)}`;
+ const relative = pattern.startsWith("./") ? pattern : `./${pattern}`;
+ return `-path ${shellQuote(relative)}`;
+ });
+ const prune = patterns.length
+ ? `-type d \\( ${patterns.join(" -o ")} \\) -prune -o `
+ : "";
+ const types = options.includeSymlinks
+ ? "\\( -type f -o \\( -type l -exec test -f {} \\; \\) \\)"
+ : "-type f";
+ // Fetch one extra path to distinguish truncation from an exact-size result.
+ const limit =
+ options.maxFiles > 0 ? ` | head -n ${options.maxFiles + 1}` : "";
+ return `find . ${prune}${types} -print 2>/dev/null | sort${limit}`;
+}
+
+export function parseWorkspaceFileList(stdout: string, maxFiles: number) {
+ const paths = Array.from(
+ new Set(
+ stdout
+ .split(/\r?\n/)
+ .filter(Boolean)
+ .map((path) => (path.startsWith("./") ? path.slice(2) : path)),
+ ),
+ );
+ return {
+ paths: maxFiles > 0 ? paths.slice(0, maxFiles) : paths,
+ isTruncated: maxFiles > 0 && paths.length > maxFiles,
+ };
+}