From fc41bb5b13ba1ad0f2a32040fe628fcd70f85920 Mon Sep 17 00:00:00 2001 From: Codeman maintainer Date: Wed, 25 Nov 2026 15:32:13 +0100 Subject: [PATCH] fix(files): the review items of #848 that go on top A restore no longer pages through a whole large folder for an expanded folder that is gone: directories are listed before files across pages, so a loaded file ends the search, and the expansion is forgotten. An expanded folder that waits for its turn in the restore says it is loading, and a search-result folder opened while the tree was loading runs the restore afterwards. The error line keeps its parts in separate elements so the zh-CN entries apply, one local match reads in the singular, and the search box labels the phone keyboard's Enter key. Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 2 +- docs/architecture-invariants.md | 8 ++- src/web/public/i18n.js | 2 +- src/web/public/index.html | 2 +- src/web/public/panels-ui.js | 23 +++++- test/file-browser-lazy.test.ts | 121 ++++++++++++++++++++++++++++++++ 6 files changed, 151 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 559ed973..fea8cb57 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -251,7 +251,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Files panel delete** (salvaged from #529; `DELETE /api/sessions/:id/files?path=`, the × on a file row of the Files panel, tree and search results): removes ONE regular file and is the **only file surface that deletes**. It takes the edit route's confinement and guards whole (ownership via `findSessionOrFail`, `validateLocalSessionFilePath` behind `withGuardedOutsideWorktree`, so an absolute path in a followed outside worktree obeys the same rules, sensitive/blocked/`.git` 403), and both spellings are checked, the realpath and the path as named. ⚠️ **A symbolic link is refused (400), never followed**: the confinement check returns the REALPATH, i.e. the link's target, so an `unlink` of it deleted `CLAUDE.md` for `AGENTS.md -> CLAUDE.md` and left the link dangling. The final component is `lstat`ed on the path AS NAMED, only a plain file goes on, the inode is compared again before `unlink`, and `unlink` never follows a final link. A dangling link fails realpath and reads as 404. ⚠️ Remote sessions are refused before any path check (a same-named local folder would take the delete), and so are adopted ones (the `/tmp` file-surface exception is not copied to a new surface); Docker workspaces are allowed like the edit route. The workspace (and the outside worktree root) is probed bounded first (#516, `422` on a dead mount). ⚠️ The button is bound from the row's escaped `data-path` in the `.file-tree-item` loops, NEVER an inline `onclick` (`encodeURIComponent` leaves `'` alone, so `x'-alert(1)-'.txt` ran script); it asks with `confirm()`, reloads through `_reloadFileBrowserKeepingQuery()` so a search re-runs, stays visible under `@media (hover: none)`, and is not drawn for remote or adopted sessions. Tests: `test/routes/file-delete-routes.test.ts`, `test/file-delete-ui.test.ts`. → [architecture-invariants#files-panel-delete](docs/architecture-invariants.md#files-panel-delete) -**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure) compiles the query into a predicate the server-side walk prunes with; a query returns a FLAT match list and the walk recurses past non-matching directories. An empty, whitespace-only or overlong (`MAX_QUERY_LENGTH`, 256) query compiles to `null`, keeping the default tree response byte-identical. ⚠️ **Never compile a glob into a RegExp** (`*a*a*a…` backtracks and freezes the event loop for the whole server): `globMatch()` is a two-pointer wildcard walk. Tree and search share one walk shape: a per-directory round-robin (breadth-first, so fair per directory, not per subtree) over one 5,000-node budget, where a folder's own files count as one share beside the subfolders it just found (`walkTurnEnd()`). ⚠️ That budget caps what is LISTED, never what is read: a read keeps only what the listing can use (`readWalkFolder()`) and `MAX_WALK_ENTRIES_READ` (250,000) stops opening folders, or one GET reads the whole workspace into memory. ⚠️ A folder below the walk's root is probed (#516) before its `readdir`, and anything but `directory` is skipped unflagged. ⚠️ A directory has its node before it is read, so every cursor still queued or unread when the walk ends must get `incomplete: true` or it reads as an empty folder. → [architecture-invariants#files-panel-search](docs/architecture-invariants.md#files-panel-search) +**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure) compiles the query into a predicate the server-side walk prunes with; a query returns a FLAT match list and the walk recurses past non-matching directories. An empty, whitespace-only or overlong (`MAX_QUERY_LENGTH`, 256) query compiles to `null`, keeping the default tree response byte-identical. ⚠️ **Never compile a glob into a RegExp** (`*a*a*a…` backtracks and freezes the event loop for the whole server): `globMatch()` is a two-pointer wildcard walk. Tree and search share one walk shape: a per-directory round-robin (breadth-first, so fair per directory, not per subtree) over one 5,000-node budget, where a folder's own files count as one share beside the subfolders it just found (`walkTurnEnd()`). ⚠️ That budget caps what is LISTED, never what is read: a read keeps only what the listing can use (`readWalkFolder()`) and `MAX_WALK_ENTRIES_READ` (250,000) stops opening folders, or one GET reads the whole workspace into memory. ⚠️ A folder below the walk's root is probed (#516) before its `readdir`, and anything but `directory` is skipped unflagged. ⚠️ A directory has its node before it is read, so every cursor still queued or unread when the walk ends must get `incomplete: true` or it reads as an empty folder. ⚠️ The PANEL itself no longer draws that tree for a local session: it browses with `lazy=1` (#759), ONE folder per request, 500 entries a page, with a `nextCursor` scoped to the session, root, folder and hidden preference. The folder is probed with `pastCap` before its `readdir`, refused segments are checked on both spellings (as named and resolved), and a directory row without `children` is NOT LOADED, never empty. A page lists directories before files and the order holds across pages; the panel's restore relies on it (a loaded file ends the search for a folder, `_revealFileBrowserDirectory()`). Typing filters loaded rows with no request; only Enter runs the workspace search. The legacy tree and `q` responses stay byte-identical for other callers and remote sessions. Tests: `test/routes/file-routes-lazy.test.ts`, `test/file-browser-lazy.test.ts`. → [architecture-invariants#files-panel-search](docs/architecture-invariants.md#files-panel-search) **Files panel in a worktree** (#765, `src/live-worktree.ts`, `root=live` and `root=live-any` on `GET /api/sessions/:id/files`): Claude's EnterWorktree moves the process, and `paneCwd` follows it (tmux reads the process cwd, measured on 2.1.318, back out on ExitWorktree too), while `workingDir` stays the session's identity. `refreshLiveWorktree()` (server.ts) turns a changed `paneCwd` into `SessionState.liveWorktree` by reading the `.git` FILE (never spawning git), walking up and stopping at `workingDir`, a repository or submodule of its own, or anything unreadable. That is the lookup for a pane inside `workingDir`; a pane outside it goes to `findOutsideWorktree()`, described below. ⚠️ The security argument has two halves. For a worktree inside `workingDir` the lookup only answers a folder strictly below it, but that is a LEXICAL judgement made when the pane moves, and a symlink can replace the folder or a parent later without moving the pane, so `root=live` re-checks on every request (`canWalkLiveWorktree()`, file-routes.ts: walk the worktree only when it resolves strictly inside the resolved `workingDir`, else walk `workingDir`). The walk starts there, returned `path`s stay relative to `workingDir`, and the routes keep confining to `workingDir`, so never make an INSIDE `liveWorktree` a confinement root. ⚠️ Only that check uses resolved paths: the walk keeps the session's spelling, or a workspace reached through a symlink stops producing paths relative to `workingDir`. ⚠️ A plain subfolder is deliberately no answer, or a `cd` in a shell would re-root the panel. ⚠️ A listing reports `worktree` whichever folder it walked, even when the worktree has gone or the check refused it: `_followFileBrowserWorktree()` compares that with the session's state, and an absent report would reload forever. The one exception is a listing without `root=live-any`, which omits an outside worktree; while the session folder is pinned, the panel compares with the worktree it pinned away from (`pinnedWorktree`, panels-ui.js). ⚠️ **A worktree OUTSIDE `workingDir` (`git worktree add ../feature`, or an EnterWorktree placed beside the repo) IS a second root**, answered only through `findOutsideWorktree()` with `outside: true` and published on the wire as `SessionState.outsideWorktree`, never in `liveWorktree`, which stays inside-only: the session's own repository must vouch for it by FILE READS (`workingDir` must be the top of its repository or worktree, so a session in a subfolder follows nothing outside it; the candidate's `.git` FILE names `/worktrees/` and that entry's `gitdir` names the candidate back, or its `.git` FOLDER is the session's common dir itself, which is the main worktree for a session started in a linked one, and a symlinked `.git` is refused; never spawn git from the pane watcher). It is refused at `/`, home or above, around `workingDir` and at/inside/around a Docker case workspace (an unreadable Docker list follows nothing). It is refused while attachment workspace confinement is on. It is also refused at, inside or around an attachment blocked tree, and at a root that is itself a sensitive folder such as `~/.ssh` (a child probe, since the sensitive patterns describe file locations). These rules are judged when the pane moves like the Docker rule, and multi-user mode applies `folderAllowedForUser`. The routes also re-check confinement and the blocked trees on every request (`isOutsideWorktreeRootRefused()`), so turning confinement on or blocking the folder stops serving it at once. ⚠️ `validateLocalSessionFilePath()` also refuses any file there that `isSensitivePath()` blocklists, so a root such as a credential folder can never serve its keys. Walking it is opt-in: only `root=live-any` (which the panel sends) lists it, with ABSOLUTE `path`s, while `root=live` never walks an outside worktree: it walks `workingDir` with relative paths, and its listing omits `worktree` for an outside one. An absolute path inside it is confined to it, falling back to `workingDir` when the worktree root refuses it (`validateLocalSessionFilePath()`, route-helpers.ts), while a relative path still resolves against `workingDir` alone. ⚠️ It is recorded as a REAL path, and every request re-checks that the folder still resolves to exactly that path (`outsideWorktreeRootFor()`, `canWalkOutsideWorktree()`), or a symlink swapped in would re-root the routes anywhere. Tests: `test/live-worktree.test.ts`, `test/live-worktree-outside.test.ts`, `test/routes/file-routes-live-worktree.test.ts`, `test/routes/file-routes-outside-worktree.test.ts`, `test/file-browser-worktree.test.ts`, `test/file-browser-outside-worktree.test.ts`. → [architecture-invariants#files-panel-in-a-worktree](docs/architecture-invariants.md#files-panel-in-a-worktree) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 28f3a394..f85c40eb 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -839,7 +839,13 @@ Expand All opens only loaded folders. Refresh retains visible expansion state; a restoration skips recorded load errors and hidden-off expansions before requesting pages. Hidden-path checks are relative to the listing root, so a worktree's dotted prefix does not hide its ordinary folders. Explicit Retry loads the failed folder/page; errors retain entries -already loaded. Tests: `test/routes/file-routes-lazy.test.ts`, `test/file-browser-lazy.test.ts` +already loaded. A page lists the folder's directories before its files, and that order holds +across pages, so a restore or a reveal that has a file loaded for a folder stops asking for +more pages: the folder it looks for is not there. A restore then forgets that expansion +(the folder was deleted or renamed); one stopped by a failed page keeps it. An expanded +folder whose own request has not started is drawn with the loading line, never as an empty +folder, and a search-result folder opened while the tree was still loading runs the restore +when it is done. Tests: `test/routes/file-routes-lazy.test.ts`, `test/file-browser-lazy.test.ts` and `test/mobile/file-browser.test.ts`. The recursive listing and `q` search policies below remain unchanged for existing callers. diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 65706501..408f000f 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -1713,7 +1713,7 @@ function translateDynamic(source) { const patterns = [ [ - /^(\d+) matches in loaded folders · Enter to search workspace$/, + /^(\d+) match(?:es)? in loaded folders · Enter to search workspace$/, (_m, n) => `已加载的文件夹中有 ${n} 个匹配项 · 按 Enter 搜索工作区`, ], [ diff --git a/src/web/public/index.html b/src/web/public/index.html index 2767f94e..902e5cac 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -640,7 +640,7 @@
Select a session to view files
diff --git a/src/web/public/panels-ui.js b/src/web/public/panels-ui.js index ee24e166..0b5e16e6 100644 --- a/src/web/public/panels-ui.js +++ b/src/web/public/panels-ui.js @@ -2841,7 +2841,8 @@ Object.assign(CodemanApp.prototype, { const statusEl = this.$('fileBrowserStatus'); if (!statusEl || !data) return; if (this._ensureFileBrowserState().filter.trim()) { - statusEl.textContent = `${this._fileBrowserLocalMatchCount || 0} matches in loaded folders · Enter to search workspace`; + const localCount = this._fileBrowserLocalMatchCount || 0; + statusEl.textContent = `${localCount} ${localCount === 1 ? 'match' : 'matches'} in loaded folders · Enter to search workspace`; return; } let { totalFiles, totalDirectories, truncated } = data; @@ -3294,7 +3295,14 @@ Object.assign(CodemanApp.prototype, { // Automatic restoration must not bypass a failed page's explicit Retry action. if (expandedOnly && container._listing?.error) return null; const cursor = container._listing?.nextCursor ?? container.nextCursor; - if (!cursor) return null; + // The server lists a folder's directories before its files, across every page. So once + // a loaded page holds a file, no later page can hold the folder that is looked for. + if (!cursor || nodes.some(node => node.type === 'file')) { + // A restore that cannot find its folder holds an expansion for a folder that is gone + // (deleted or renamed). Forget it, or every Refresh looks for it again. + if (expandedOnly) this.fileBrowserExpandedDirs.delete(target); + return null; + } await this._loadFileBrowserDirectory(container === data ? '' : container.path, { more: true }); if (!current() || container._listing?.error) return null; continue; @@ -3342,7 +3350,13 @@ Object.assign(CodemanApp.prototype, { let content = ''; if (listing?.loading) content = escapeHtml('Loading folder...'); else if (listing?.error) { - content = `${escapeHtml(listing.error)} · ${escapeHtml('Incomplete folder')} `; + // Separate elements: the translator replaces a text node only when its WHOLE text is an + // entry, so the error and the label joined into one node were never translated. + content = `${escapeHtml(listing.error)} · ${escapeHtml('Incomplete folder')} `; + } else if (path && !Array.isArray(container.children)) { + // Drawn open before its own request started (it waits its turn in the restore after a + // Refresh): an unfinished load is never shown as an empty folder. + content = escapeHtml('Loading folder...'); } else if (cursor) { content = ``; } else if (path && Array.isArray(container.children) && !container.children.length) { @@ -3849,6 +3863,9 @@ Object.assign(CodemanApp.prototype, { if (!current()) return; if (!paths) { this._promptFileBrowserDirectoryReload(); return; } this._leaveFileBrowserSearchForDirectory(paths, normalState); + // The tree is drawn again with every folder that was expanded before. A reveal that was + // waiting for the tree to load ran in place of the restore, so load those folders now. + await this._restoreFileBrowserExpandedDirs(normalState); }, _leaveFileBrowserSearchForDirectory(paths, normalState) { diff --git a/test/file-browser-lazy.test.ts b/test/file-browser-lazy.test.ts index cc531891..2bd28fa6 100644 --- a/test/file-browser-lazy.test.ts +++ b/test/file-browser-lazy.test.ts @@ -553,6 +553,127 @@ describe('Files panel lazy browsing behavior (#759)', () => { expect(ui.paths()).toContain('src/deep/needle.ts'); }); + // The server lists a folder's directories before its files across every page, so a loaded + // file proves no later page holds the folder a restore is looking for. + it('stops looking for an expanded folder that is gone at the first page holding a file, and forgets it', async () => { + ui.server.respond = (url) => + url.searchParams.get('path') === 'gone' ? page([file('gone/a.ts')]) : page([folder('gone'), file('a.ts')]); + await open(); + await expand('gone'); + ui.server.respond = (url) => { + if (url.searchParams.get('cursor') === 'c1') return page([file('b.ts')], 'c2'); + if (url.searchParams.get('cursor') === 'c2') return page([file('c.ts')]); + return page([folder('empty'), file('a.ts')], 'c1'); + }; + const before = ui.requests.length; + await ui.app.refreshFileBrowser(); + await settle(); + expect(ui.requests.slice(before).map((url) => url.searchParams.get('cursor') ?? '')).toEqual(['']); + expect(ui.app.fileBrowserExpandedDirs.has('gone')).toBe(false); + expect(ui.tree.querySelector('[data-file-browser-load="more"]')).not.toBeNull(); + }); + + it('still restores an expanded folder that moved to a later page of directories', async () => { + await open(); + await expand('src'); + ui.server.respond = (url) => { + if (url.searchParams.get('path') === 'src') return page([file('src/visible.ts')]); + return url.searchParams.has('cursor') ? page([folder('src'), file('z.ts')]) : page([folder('empty')], 'two'); + }; + const before = ui.requests.length; + await ui.app.refreshFileBrowser(); + await settle(); + expect( + ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? url.searchParams.get('cursor') ?? '') + ).toEqual(['', 'two', 'src']); + expect(ui.app.fileBrowserExpandedDirs.has('src')).toBe(true); + expect(ui.paths()).toContain('src/visible.ts'); + }); + + it('keeps the expansion of a folder behind a failed page: only a folder known to be gone is forgotten', async () => { + await open(); + await expand('src'); + ui.server.respond = (url) => { + if (url.searchParams.has('cursor')) return response(null, false); + return page([folder('empty')], 'two'); + }; + await ui.app.refreshFileBrowser(); + await settle(); + expect(ui.app.fileBrowserExpandedDirs.has('src')).toBe(true); + }); + + const stateLines = () => + [...ui.tree.querySelectorAll('.file-tree-listing-state')].map((line) => line.textContent!.trim()); + + it('shows an expanded folder that waits for its turn in the restore as loading, never as empty', async () => { + await open(); + await expand('src'); + await expand('empty'); + const held = deferred(); + const original = ui.server.respond; + ui.server.respond = (url) => (url.searchParams.get('path') === 'src' ? held.promise : original(url)); + void ui.app.refreshFileBrowser(); + await settle(); + // `src` is being fetched and `empty` has not started: both are drawn open and both say so. + expect(stateLines()).toEqual(['Loading folder...', 'Loading folder...']); + held.resolve(page([file('src/visible.ts')])); + await settle(); + expect(stateLines()).toEqual(['No files in this folder']); + expect(ui.paths()).toContain('src/visible.ts'); + }); + + it('loads the other expanded folders after a search-result folder was opened while the tree was loading', async () => { + await open(); + await expand('empty'); + const root = deferred(); + const original = ui.server.respond; + let holdRoot = true; + ui.server.respond = (url) => + holdRoot && !url.searchParams.has('q') && !url.searchParams.has('path') ? root.promise : original(url); + void ui.app.loadFileBrowser('sess-A', { force: true }); + await runSearch(); + const before = ui.requests.length; + ui.clickFolder('src/deep'); + await settle(); + expect(ui.requests).toHaveLength(before); // waits for the tree + holdRoot = false; + root.resolve(page([folder('empty'), folder('src'), file('README.md')])); + await settle(); + expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual([ + 'src', + 'src/deep', + 'empty', + ]); + expect(ui.paths()).toContain('src/deep/needle.ts'); + expect(stateLines()).toEqual(['No files in this folder']); + }); + + it('keeps a failed folder error and its label in separate elements, so each can be translated', async () => { + const original = ui.server.respond; + ui.server.respond = (url) => (url.searchParams.get('path') === 'src' ? response(null, false) : original(url)); + await open(); + await expand('src'); + const line = ui.tree.querySelector('.file-tree-listing-state')!; + expect([...line.querySelectorAll('span')].map((span) => span.textContent)).toEqual([ + 'Folder unavailable', + 'Incomplete folder', + ]); + }); + + it('counts one local match in the singular', async () => { + await open(); + ui.type('README'); + await settle(); + expect(ui.document.getElementById('fileBrowserStatus')!.textContent).toBe( + '1 match in loaded folders · Enter to search workspace' + ); + ui.type('e'); + await settle(); + expect(ui.document.getElementById('fileBrowserStatus')!.textContent).toMatch( + /^\d+ matches in loaded folders · Enter to search workspace$/ + ); + }); + it('preserves a local filter across a hidden toggle without silently starting whole-workspace search', async () => { await open(); await expand('src');