diff --git a/AGENTS.md b/AGENTS.md index 72e3ebf69..a28a39a8e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1083,12 +1083,11 @@ during the wait. - Successful selection, default cwd and worktree operations grant roots on the owning daemon. Browsing alone grants nothing. Main's `getAllowedFileRoots()` remains for the unrelated local config/import/skills readers, not workspace APIs. +- The Explorer's `type=list` hides nothing by name and there is no "show hidden" switch (no ignore lists here or in `/api/file-index`, which follows `.gitignore` in a Git repo and otherwise indexes regular files under its caps, skipping symlinks to both files and directories; when `git ls-files` fails it falls back to that walk, ignored files included). The tree sends `&root=` to the owning daemon: the listed directory's realpath must be inside the root's realpath (403 `outside_root`, also for an unknown or relative root; the root needs no allow-list check of its own, since the listed path already passed `authorizeFileAccess` and a root can only narrow it), and each symlink entry gets `linkTarget` (raw `readlink`) and, when it leaves the root or dangles, `outsideRoot: true` (the UI dims it and will not expand or open it; `flattenVisibleRows` never descends into a flagged dir). This limits the tree only; `read`/`download` keep the allow-list and session-reference rules. + The non-Git index walk uses asynchronous directory reads so other daemon requests can progress during a scan. Preserve breadth-first ordering, the existing depth/file/directory caps, truncation reporting and shared in-flight scans when changing this path. +- The Explorer calls the additive daemon capability `listFilesInRoot(input, root)`. Missing capability returns 501 `workspace_unsupported` with upgrade advice; never fall back to an unconfined listing. Keep the original `listFiles(input, showHidden: boolean)` wire contract for older web servers; it validates the flag but follows the current all-names listing policy. Both operations share one daemon-side listing implementation. - The session-id → file path cache (`cacheSessionPath`, `lib/session-reader.ts`) on main is filled by main's own scans and by wrappers on the local host; it only serves the readers listed under "Session list caching". -### Explorer hidden items -- The tree and index share `isIgnoredFileEntry` in `lib/file-dirent.ts`. -- The Explorer's "Show hidden items" toggle sends `?hidden=1`, which bypasses the skip-list for `type=list` only. It deliberately does NOT touch `/api/file-index` — @-mentions and file search keep ignoring those paths. State is AppShell-owned (localStorage `omp-web:show-hidden-files`, off by default); flipping it makes `FileExplorer` drop its cached listings and re-read the visible directories, keeping expansion. - ### Session list caching — new sessions must appear immediately - The sidebar and command palette list sessions per host: `listSessionsAllHosts()` (`lib/hosts/session-index.ts`) calls each host's `listSessions` op and caches it 30 s per host (`LIST_TTL_MS`, the daemon's own TTL). **This machine's list is its daemon's**; a host that fails or is offline keeps its last list. Nothing on main parses session files to build it. - The daemon's `listSessions` is `listAllSessions()` (`lib/session-reader.ts`): a 30 s TTL list cache plus an mtime-keyed directory walk in `lib/omp/session-files.ts` (`listSessionFiles`), both in the daemon process. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b0aed70f..76a82287d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,6 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Session search shows where each session matched.** While searching the sidebar, the arrow beside a session lists its matches one per line, best match first and newest first among equals, ten at a time with **Load more…**. Matches in the messages of the open conversation are highlighted, typos and partial words included (thinking, tool output and math are not searched; link addresses and image descriptions do not count), and clicking a match opens its session, scrolls to it and marks it as the current one, like the browser's find. Closing or clearing the search removes the highlights. Browsers without the CSS Custom Highlight API (before Chrome 105, Safari 17.2 or Firefox 140) still jump to the match but do not paint it. - **Show tool calls outside Process details.** A new setting keeps each tool call's row in the transcript instead of folding it; whether the row opens still follows "Keep tool calls collapsed". - **Never fold tool activity.** A new setting renders every turn flat, with no Process details rows at all. Long turns are paged, and jumping to a search match reveals its message even outside the current page. -- **Show hidden items in the Explorer.** A switch in the file panel's toolbar lists the folders the tree normally hides — `build/`, `dist/`, `node_modules/`, `target/` and the rest — so you can browse into them and open a file from there. It changes only the file tree; search and @-mentions keep ignoring those paths. It is off by default, and your choice is remembered. - **Connection diagnostics.** Turn on **Settings → Interface & Behavior → Show connection diagnostics** to get a **Connection** tab in the right panel, on desktop and mobile. It shows the transport actually in use (WebSocket or server-sent events, including fallback), connection status, reconnects, and latency statistics over the last 30 minutes: mean, p50, p95, p99.9 and max. Successful commands and sampled live events are grouped by transport. One-way times are clock-corrected estimates; web app ↔ omp includes processing, with `get_state` shown separately as a delivery proxy. p99.9 needs at least 1,000 samples. - **A message queued or steered during a run shows "Sending…" until it arrives.** It stays above the composer with a spinner until omp has taken it into its queue (then the queue chip replaces it) or refused it (then it goes back into the composer as before), instead of vanishing until an offline host refuses it seconds later. Pending indicators and refused-send recovery follow confirmed session-ID moves, including after navigating away and remounting the original composer; ordinary navigation remains isolated. - **Updates belong to each host.** Settings → Hosts now shows the ompweb daemon and OMP runtime versions, available updates, and update actions for every machine, including This machine. Checks and installations run on that host. An incompatible or unverifiable daemon update stays visible but blocked, with a reason to update the web server first; OMP updates are independent of the link protocol. A daemon update is refused while session processes or subagents run on that host (close them, then start it again), and the host refuses new sessions while it installs. The host update retains a backup and reports progress after reconnect. **System & Updates** is now **System**, containing only the web server's controls; it no longer updates or restarts a host's OMP sessions globally. @@ -39,6 +38,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Finished background tool calls no longer show up as running.** A `bash` or `task` call that omp moved to the background kept reporting progress after it returned, and ompweb counted each report as a running tool. Opening the chat mid-run then listed those long-finished calls as empty running rows below the transcript until the next event, and an open chat could briefly show a finished call as running again. Calls that returned before an ompweb server restart can still show this once. - **Removing an upload while offline still deletes it from the host.** A file you remove (or a finished upload you discard) is now deleted from the host's staging area once the browser, the server and the host can reach each other again, even if the browser connection dropped or the host was offline when you removed it. As a backstop, a running host now deletes staged files older than a day every hour, not only when it starts or receives a new upload, which also covers a removal that ompweb lost because it restarted while the host was offline. - **`!` commands you run have their own look.** A shell command you ran with `!` now shows as a terminal-style card with a `$ command` prompt line, instead of the same row as the agent's tool calls. A failed run shows its exit code (`exit 1`) or `cancelled`, and a `!!` run is tagged `local`. Click the card to show its output. Long pending commands wrap even on narrow screens, switching to a different run resets its expansion, and screen readers can identify successful runs. +- **The Explorer shows every file, including build output and `.git`, with no switch.** `node_modules`, `.git`, `dist`, `build`, `target`, caches and `.pyc` files are no longer hidden by name. A folder's contents load only when you expand it. This replaces the **Show hidden items** switch from #378, including its toolbar button and saved preference. Symlinks show their raw target (`name → ../target`); an outside-root or dangling link stays visible but cannot be opened or expanded from the tree. + File search and `@` mentions follow `.gitignore` in a Git repository. Outside Git, or when Git is missing or fails, the bounded fallback includes regular files without name exclusions, including ignored files, but skips symlink entries to both files and directories. +- **File search stays bounded and leaves the host responsive.** The non-Git fallback reads directories asynchronously instead of blocking other daemon requests for the whole scan. It still queues and reads at most 50,000 directories and reports truncated results at its limits. Blocked symlink tooltips explain both outside-workspace and missing targets in every language. +- **Explorer confinement upgrades without changing older daemon contracts.** The original boolean `listFiles` operation remains available to older web servers. The Explorer uses the separately advertised `listFilesInRoot` capability; a daemon without it returns an explicit upgrade-required response rather than an unconfined listing. - **Reconnecting uploads no longer leave Send blocked by a hanging retry.** The five-minute deadline stops an in-flight retry as well as its back-off, keeping staged bytes for Retry. A connection lost midway through an HTTP response resumes automatically, and tooltips identify network failures instead of showing only “Upload failed”. - **Files named `agent.db` or `models.yml` open again unless they are omp's own.** The file viewer refused those names anywhere under `~/.omp`, so an uploaded `agent.db` could not be opened from its link. It now refuses only the files omp keeps in its agent directory (and a profile's), with their SQLite sidecars, backups and `models.yaml`/`models.json`. Both symlinked agent directories and individually symlinked credential files keep their real targets protected, including targets with different names; unrelated uploaded copies still open. - **Uploads no longer leave submitted messages or restored pages stuck.** A slow attachment copy keeps its session alive even after you switch chats. Commands that change Advisor wait until that preparation is dispatched before they may replace the session's child. Returning through browser Back/Forward shows Retry for an interrupted upload instead of leaving Send permanently blocked. diff --git a/README.ja.md b/README.ja.md index 0aa95fefc..cc96ea7df 100644 --- a/README.ja.md +++ b/README.ja.md @@ -109,7 +109,7 @@ Linux トレイ、Windows サービス)はインストール時に `OMP_WEB_PA - **セッション管理**: プロジェクトごとに履歴を一覧表示、分岐やフォークにも対応。 - **下書きの復元**: 未送信のテキストを会話または新規セッションのワークスペースごとに保存し、ブラウザストレージが利用可能な場合は、同じタブでの「戻る」「進む」や再読み込み後に復元します(最大 50 件)。画像と添付ファイルはメモリ内にのみ保持されます。 - **ライブタスク&サブエージェント**: Todo リストと稼働中サブエージェントの進捗を折りたたみパネルでリアルタイム表示。 -- **ファイル閲覧・プレビュー**: チャットと並べてファイルを閲覧、コード・Markdown・画像・音声・PDF をプレビュー。「隠し項目を表示」でビルド生成物や依存関係も一覧できます。 +- **ファイル閲覧・プレビュー**: チャットと並べてファイルを閲覧、コード・Markdown・画像・音声・PDF をプレビュー。 - **各ホストのファイル**: エクスプローラー、検索、プレビュー、ダウンロード、ライブ更新は、そのホストのデーモンを使用します。アップロードは 1 ファイル 2 GiB までで、合計 100 MiB 制限はありません。プレビュー上限はテキスト 256 KiB、画像・DOCX 10 MiB のままです。チャットを切り替えてもファイルタブのホストは変わりません。 - **各ホストのワークスペース**: Git の差分とワークツリー操作、ディレクトリの移動、HTTPS/SSH リポジトリのクローンも、そのホストで実行します。クローンのキャンセルはプロセス終了と安全な削除を確認してから完了し、接続が切れた場合は結果が不明であることを表示します。 - クローンの削除中に保存先が置き換わった場合、退避したデータは非公開ディレクトリに保持され、エラーに保存場所が表示されます。削除や復元の前に内容を確認してください。 diff --git a/README.md b/README.md index 63226fdb1..410765182 100644 --- a/README.md +++ b/README.md @@ -675,7 +675,7 @@ Stop it with `Stop-ScheduledTask ompweb-host`, then end the running host with - **Draft Recovery**: Unsent text stays scoped to its conversation or new-session workspace and is restored after Back/Forward navigation or reload in the same tab when browser storage is available (up to 50 drafts). Images and file attachments remain in memory only. - **Live Plans & Subagents**: Collapsible panels pinned above the composer track live todo phases and running subagents (status, tool, retries, tokens/cost, nested tasks) with transcript dialogs and history recovery. - **Tool Preset Picker**: Choose the toolset for new sessions in the composer — `none` / `default` (`read,bash,edit,write`) / `full` (all tools including subagents). Persists to localStorage. -- **File Explorer & Previews**: Browse workspaces side-by-side with chat; preview code, markdown, Mermaid, images, audio, PDFs, and diffs with allow-listed access. The **Show hidden items** switch lists build and dependency folders. +- **File Explorer & Previews**: Browse workspaces side-by-side with chat; preview code, markdown, Mermaid, images, audio, PDFs, and diffs with allow-listed access. - **Git Worktree Support**: Create, switch, and manage Git worktrees directly from the sidebar; sessions and file roots stay grouped by project. - **Remote Hosts**: Link other machines (for example a MacBook) and run sessions there from one ompweb. The sidebar groups sessions by host. See [Run sessions on another machine](#run-sessions-on-another-machine). - **Usage & Analytics**: Dashboard in **Settings → Usage** for tokens, costs, cache savings, and breakdowns by provider / model / day / project with SQLite persistence. diff --git a/README.zh-CN.md b/README.zh-CN.md index 31cee8582..7228eeb46 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -102,7 +102,7 @@ Windows 服务)仍在安装时接受 `OMP_WEB_PASSWORD`,但在写入配置 - **会话管理**:按项目浏览历史会话,支持会话分叉与分支回溯。 - **草稿恢复**:未发送的文本按会话或新会话的工作区分别保存;浏览器存储可用时,在同一标签页后退、前进或重新加载后可恢复(最多 50 份草稿)。图片和文件附件仅保留在内存中。 - **实时任务与子智能体**:可折叠面板实时展示任务清单(todo)与子智能体进度,并支持查看完整转录。 -- **文件管理与预览**:与对话并排浏览文件,支持代码、Markdown、图片、音频及 PDF 预览。通过「显示隐藏项目」可列出构建产物与依赖目录。 +- **文件管理与预览**:与对话并排浏览文件,支持代码、Markdown、图片、音频及 PDF 预览。 - **各主机的文件**:文件浏览、搜索、预览、下载和实时更新都通过文件所属主机的守护进程执行。上传每个文件最多 2 GiB,不再限制批次总大小为 100 MiB。预览限制仍为文本 256 KiB、图片及 DOCX 10 MiB。切换对话不会改变文件标签页所属的主机。 - **各主机的工作区**:Git 差异、工作树操作、目录浏览以及 HTTPS/SSH 仓库克隆均在所属主机执行。取消克隆会等待进程退出和安全清理;连接中断时会明确提示结果未知。 - 若清理克隆时目标目录被替换,捕获的数据会保存在私有隔离目录中,错误信息会显示其位置。删除或恢复前请先检查内容。 diff --git a/app/api/file-index/route.ts b/app/api/file-index/route.ts index 6e216b97c..dd53a66b7 100644 --- a/app/api/file-index/route.ts +++ b/app/api/file-index/route.ts @@ -1,6 +1,8 @@ import { apiErrorResponse, opErrorResponse, resolveWorkspaceHost } from "@/lib/api-utils"; import { parseResultLimit } from "@/lib/file-fuzzy"; + + export async function GET(req: Request) { try { const params = new URL(req.url).searchParams; diff --git a/app/api/files/[...path]/route.ts b/app/api/files/[...path]/route.ts index ea2f9b52b..25aaec351 100644 --- a/app/api/files/[...path]/route.ts +++ b/app/api/files/[...path]/route.ts @@ -146,7 +146,7 @@ export async function GET( if ("response" in resolved) return resolved.response; const { host } = resolved; if (type === "list") { - const result = await host.workspaceOps.listFiles(input, searchParams.get("hidden") === "1"); + const result = await host.workspaceOps.listFilesInRoot(input, searchParams.get("root")); return result.ok ? Response.json(result.value) : opErrorResponse(result); } const checked = await host.workspaceOps.fileInfo(input); diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 75845b327..4d094a39d 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -112,9 +112,6 @@ const EXPAND_THINKING_STORAGE_KEY = "omp-web:expand-thinking"; const PROVIDER_USAGE_VISIBLE_STORAGE_KEY = "omp-web:provider-usage-visible"; const NATIVE_SELECT_ALL_STORAGE_KEY = "omp-web:scope-native-select-all"; const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "omp-web:open-url-automatically"; -// Off by default, so the Explorer keeps hiding build/, node_modules/ and the -// other IGNORED_NAMES directories until the toolbar switch is flipped. -const SHOW_HIDDEN_FILES_STORAGE_KEY = "omp-web:show-hidden-files"; type AutoNameStatus = @@ -186,7 +183,6 @@ export function AppShell({ appName }: { appName: string }) { const [providerUsageVisible, setProviderUsageVisible] = useState(true); const [scopeNativeSelectAll, setScopeNativeSelectAll] = useState(false); const [openUrlAutomatically, setOpenUrlAutomatically] = useState(false); - const [showHiddenFiles, setShowHiddenFiles] = useState(false); const [sidebarResizing, setSidebarResizing] = useState(false); // Active drag handlers so an unmount mid-drag can detach them. const sidebarResizeHandlersRef = useRef<{ onMove: (ev: MouseEvent) => void; onUp: () => void } | null>(null); @@ -207,7 +203,6 @@ export function AppShell({ appName }: { appName: string }) { setProviderUsageVisible(window.localStorage.getItem(PROVIDER_USAGE_VISIBLE_STORAGE_KEY) !== "false"); setScopeNativeSelectAll(window.localStorage.getItem(NATIVE_SELECT_ALL_STORAGE_KEY) === "true"); setOpenUrlAutomatically(window.localStorage.getItem(OPEN_URL_AUTOMATICALLY_STORAGE_KEY) === "true"); - setShowHiddenFiles(window.localStorage.getItem(SHOW_HIDDEN_FILES_STORAGE_KEY) === "true"); } catch { // Keep the compact default when storage is unavailable. } @@ -276,17 +271,6 @@ export function AppShell({ appName }: { appName: string }) { // The preference still applies for this page load. } }, []); - const handleToggleShowHiddenFiles = useCallback(() => { - setShowHiddenFiles((prev) => { - const next = !prev; - try { - window.localStorage.setItem(SHOW_HIDDEN_FILES_STORAGE_KEY, String(next)); - } catch { - // The preference still applies for this page load. - } - return next; - }); - }, []); // Persist the committed width (after each change; skipped mid-drag, then // written once the drag ends). The first run is skipped so the mount-time // default cannot overwrite the stored width before it is loaded. @@ -2698,8 +2682,6 @@ export function AppShell({ appName }: { appName: string }) { fileSearchOpen={fileSearchOpen} onToggleFileSearch={handleToggleFileSearch} onFileSearchOpenChange={setFileSearchOpen} - showHiddenFiles={showHiddenFiles} - onToggleShowHiddenFiles={handleToggleShowHiddenFiles} explorerUploadBusy={explorerUploadBusy} onUploadBusyChange={setExplorerUploadBusy} explorerGitCount={explorerGitCount} diff --git a/components/ConnectionDiagnostics.test.mjs b/components/ConnectionDiagnostics.test.mjs index 652847713..d657eb6dc 100644 --- a/components/ConnectionDiagnostics.test.mjs +++ b/components/ConnectionDiagnostics.test.mjs @@ -62,8 +62,6 @@ function rightPanelProps(overrides) { fileSearchOpen: false, onToggleFileSearch: () => {}, onFileSearchOpenChange: () => {}, - showHiddenFiles: false, - onToggleShowHiddenFiles: () => {}, explorerUploadBusy: false, onUploadBusyChange: () => {}, explorerGitCount: 0, diff --git a/components/FileExplorer.listing.test.mjs b/components/FileExplorer.listing.test.mjs new file mode 100644 index 000000000..9552af076 --- /dev/null +++ b/components/FileExplorer.listing.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test, { afterEach } from "node:test"; +import React from "react"; +const { cleanup, render, waitFor } = await import("@testing-library/react/pure.js"); + +const { FileExplorer } = await import("./FileExplorer.tsx"); + +const originalFetch = globalThis.fetch; +afterEach(() => { + cleanup(); + globalThis.fetch = originalFetch; +}); + +test("a listing that finishes after the directory changed does not overwrite the current one", async () => { + let releaseStale; + const stale = new Promise((resolve) => { releaseStale = resolve; }); + const file = (name) => ({ name, isDir: false, size: 0, modified: "" }); + let wsRequests = 0; + globalThis.fetch = async (url) => { + const href = String(url); + if (href.startsWith("/api/git/")) return { ok: true, json: async () => ({ isGitRepository: false, files: [] }) }; + if (href.startsWith("/api/files/ws?")) { + // The first request is the one the cwd change supersedes. + if (wsRequests++ === 0) { + await stale; + return { ok: true, json: async () => ({ entries: [file("stale.txt")] }) }; + } + return { ok: true, json: async () => ({ entries: [file("current.txt")] }) }; + } + return { ok: true, json: async () => ({ entries: [] }) }; + }; + + const props = { onOpenFile() {} }; + const { container, rerender } = render(React.createElement(FileExplorer, { ...props, cwd: "/ws" })); + rerender(React.createElement(FileExplorer, { ...props, cwd: "/other" })); + rerender(React.createElement(FileExplorer, { ...props, cwd: "/ws" })); + await waitFor(() => assert.ok(container.querySelector('[data-file-path="/ws/current.txt"]'))); + + releaseStale(); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(container.querySelector('[data-file-path="/ws/stale.txt"]'), null); + assert.ok(container.querySelector('[data-file-path="/ws/current.txt"]')); +}); diff --git a/components/FileExplorer.symlinks.test.mjs b/components/FileExplorer.symlinks.test.mjs new file mode 100644 index 000000000..820ab1671 --- /dev/null +++ b/components/FileExplorer.symlinks.test.mjs @@ -0,0 +1,114 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test, { afterEach } from "node:test"; +import React from "react"; +const { cleanup, fireEvent, render, waitFor } = await import("@testing-library/react/pure.js"); + +const { FileExplorer } = await import("./FileExplorer.tsx"); +const { translate } = await import("../lib/i18n/index.tsx"); + +const originalFetch = globalThis.fetch; +afterEach(() => { + cleanup(); + globalThis.fetch = originalFetch; +}); + +const gitStatus = { ok: true, json: async () => ({ isGitRepository: false, files: [] }) }; +const listing = (entries) => ({ ok: true, json: async () => ({ entries }) }); +const hasChevron = (row) => row.querySelector("svg.lucide-chevron-right") !== null; + +test("a link out of the workspace shows its target and neither expands nor opens", async () => { + const lists = []; + globalThis.fetch = async (url) => { + const href = String(url); + if (href.startsWith("/api/git/")) return gitStatus; + lists.push(href); + return listing([ + { name: "escape", isDir: true, size: 0, modified: "", linkTarget: "../shared/build", outsideRoot: true }, + { name: "shared", isDir: true, size: 0, modified: "", linkTarget: "real" }, + { name: "gone.txt", isDir: false, size: 0, modified: "", linkTarget: "../missing", outsideRoot: true }, + { name: "notes.txt", isDir: false, size: 0, modified: "" }, + ]); + }; + const opened = []; + const { container } = render(React.createElement(FileExplorer, { cwd: "/ws", hostId: "local", onOpenFile: (file) => opened.push(file) })); + const row = (path) => container.querySelector(`[data-file-path="${path}"]`); + await waitFor(() => assert.ok(row("/ws/escape"))); + + // The explorer states its root, so the server can hold the tree to it. + const listParams = new URL(lists[0], "http://localhost").searchParams; + assert.equal(listParams.get("type"), "list"); + assert.equal(listParams.get("root"), "/ws"); + assert.equal(listParams.get("hostId"), "local"); + + const outsideLabel = translate("fileExplorer.outsideRoot"); + assert.notEqual(outsideLabel, "fileExplorer.outsideRoot", "the string exists in the locale files"); + const escape = row("/ws/escape"); + assert.equal(escape.getAttribute("aria-disabled"), "true"); + assert.equal(escape.getAttribute("title"), outsideLabel); + assert.equal(escape.getAttribute("aria-expanded"), null); + assert.equal(escape.style.opacity, "0.5", "dimmed"); + assert.equal(hasChevron(escape), false); + assert.ok(escape.textContent.includes("→ ../shared/build")); + // Every symlink shows where it leads, inside the root or not; plain entries do not. + assert.equal(row("/ws/shared").style.opacity, "1"); + assert.equal(hasChevron(row("/ws/shared")), true, "an in-root link still expands"); + assert.ok(row("/ws/shared").textContent.includes("→ real")); + assert.equal(row("/ws/notes.txt").textContent.includes("→"), false); + + // A flagged file link has no way to fetch the file either. + const gone = row("/ws/gone.txt"); + assert.equal(gone.style.opacity, "0.5"); + assert.equal(gone.querySelector("a[download]"), null); + assert.notEqual(row("/ws/notes.txt").querySelector("a[download]"), null); + + for (const target of [escape, gone]) { + fireEvent.click(target); + fireEvent.keyDown(target, { key: "Enter" }); + fireEvent.keyDown(target, { key: " " }); + fireEvent.keyDown(target, { key: "ArrowRight" }); + } + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(lists.length, 1, "no directory is fetched for it"); + assert.equal(escape.getAttribute("aria-expanded"), null); + assert.deepEqual(opened, []); + + // A link that stays inside the root expands like any folder, and files still open. + fireEvent.click(row("/ws/shared")); + await waitFor(() => assert.equal(lists.length, 2)); + fireEvent.click(row("/ws/notes.txt")); + assert.deepEqual(opened, ["/ws/notes.txt"]); +}); + +test("a folder that becomes a link out of the workspace drops its stale children", async () => { + let flagged = false; + globalThis.fetch = async (url) => { + const href = String(url); + if (href.startsWith("/api/git/")) return gitStatus; + if (href.startsWith("/api/files/ws/sub?")) { + return flagged + ? { ok: false, status: 403, json: async () => ({ error: "Outside the explorer root" }) } + : listing([{ name: "child.txt", isDir: false, size: 0, modified: "" }]); + } + return listing([flagged + ? { name: "sub", isDir: true, size: 0, modified: "", linkTarget: "/elsewhere", outsideRoot: true } + : { name: "sub", isDir: true, size: 0, modified: "" }]); + }; + const opened = []; + const props = { cwd: "/ws", onOpenFile: (file) => opened.push(file) }; + const { container, rerender } = render(React.createElement(FileExplorer, props)); + const row = (path) => container.querySelector(`[data-file-path="${path}"]`); + await waitFor(() => assert.ok(row("/ws/sub"))); + fireEvent.click(row("/ws/sub")); + await waitFor(() => assert.ok(row("/ws/sub/child.txt"))); + + // A refresh re-reads the root and every expanded folder; sub is a link out now. + flagged = true; + rerender(React.createElement(FileExplorer, { ...props, refreshKey: 1 })); + await waitFor(() => assert.equal(row("/ws/sub").getAttribute("aria-disabled"), "true")); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(row("/ws/sub/child.txt"), null, "the old listing is not shown"); + fireEvent.click(row("/ws/sub")); + assert.equal(row("/ws/sub/child.txt"), null); + assert.deepEqual(opened, []); +}); diff --git a/components/FileExplorer.tsx b/components/FileExplorer.tsx index 186035a11..42e005a71 100644 --- a/components/FileExplorer.tsx +++ b/components/FileExplorer.tsx @@ -40,6 +40,10 @@ interface FileEntry { isDir: boolean; size: number; modified: string; + /** The symlink's raw `readlink` text (also for a dangling link). */ + linkTarget?: string; + /** A symlink whose target lies outside the explorer root (or is dangling). */ + outsideRoot?: boolean; } @@ -49,6 +53,8 @@ interface FileNode { isDir: boolean; size: number; children?: FileNode[]; + linkTarget?: string; + outsideRoot?: boolean; loaded?: boolean; } @@ -63,8 +69,6 @@ interface Props { onRefreshDone?: () => void; fileSearchOpen?: boolean; onFileSearchOpenChange?: (open: boolean) => void; - /** List the IGNORED_NAMES directories (build/, dist/, …) the tree hides by default. */ - showHidden?: boolean; /** Absolute path of the file open in the right panel — rendered selected. */ activeFilePath?: string | null; /** Absolute path to expand, highlight, and scroll into view (one-shot). */ @@ -108,8 +112,8 @@ interface PendingConflict { nonReplaceable: string[]; } -async function fetchEntries(dirPath: string, showHidden: boolean, hostId: string): Promise { - const res = await fetch(getFileApiUrl(dirPath, "list", hostId, null, showHidden ? { hidden: 1 } : {})); +async function fetchEntries(dirPath: string, root: string, hostId: string): Promise { + const res = await fetch(getFileApiUrl(dirPath, "list", hostId, null, { root })); if (!res.ok) { let message = translate("fileExplorer.loadFailed", { status: res.status }); try { @@ -125,6 +129,8 @@ async function fetchEntries(dirPath: string, showHidden: boolean, hostId: string name: e.name, fullPath: joinFilePath(dirPath, e.name), isDir: e.isDir, + linkTarget: e.linkTarget, + outsideRoot: e.outsideRoot, size: e.size, children: e.isDir ? [] : undefined, loaded: !e.isDir, @@ -199,7 +205,8 @@ function flattenVisibleRows( ): FlatRow[] { for (const node of nodes) { out.push({ kind: "node", node, depth }); - if (node.isDir && expandedPaths.has(node.fullPath)) { + // A dir flagged after it was expanded keeps its stale listing out of the tree. + if (node.isDir && !node.outsideRoot && expandedPaths.has(node.fullPath)) { const children = childrenByPath.get(node.fullPath); if (children) { if (children.length === 0) { @@ -276,6 +283,10 @@ const ExplorerRow = memo(function ExplorerRow({ ); const mentionLabel = t("fileExplorer.insertPathIntoChat"); const downloadLabel = t("fileExplorer.downloadFile"); + // A link out of the workspace is listed but cannot be opened from the tree. + const blocked = node.outsideRoot === true; + const outsideLabel = t("fileExplorer.outsideRoot"); + const linkSuffix = node.linkTarget !== undefined ? ", link to " + node.linkTarget : ""; return (
- {node.isDir && ( + {node.isDir && !blocked && (