Merge #848: feat(files): load file-browser directories on demand (@DodgyBadger)

This commit is contained in:
Codeman maintainer committed 2026-11-25 16:11:57 +01:00
commit d466e5c3bf
16 files changed
+1681 -78

No files matched your search

+43
View File
@@ -905,6 +905,49 @@ already serves non-media text inert (`text/plain`, `nosniff`), so this just
keeps the server from storing what it would serve or an agent could run, and
html and svg are the ones deliberately kept out.
## Listing a directory (`GET /api/v1/sessions/:id/files?lazy=1`)
The Files panel opts into one-directory listings for local workspaces with
`lazy=1`. Without `path`, the response lists immediate children of the selected
root. Expanding a folder sends its returned `path` to the same endpoint.
Directories omit `children` until the browser loads them. No descendant scan or
shared depth/node budget is spent on a lazy listing.
For example, the panel starts with `?lazy=1&root=live-any`, then requests
`?lazy=1&root=live-any&path=<returned-path>` to expand a folder. URL-encode the
returned path; it is not necessarily relative to the selected root.
The success envelope contains `data.root`, `lazy: true`, `tree`, per-page
`totalFiles`/`totalDirectories`, and `truncated`. Pages contain at most 500 entries,
directories first and then names in ascending order. A non-final page includes
an opaque `nextCursor`; pass it back as `cursor` with the same session, root,
path and `showHidden` preference. A cursor is a continuation key, not a filesystem
snapshot: changes before that key become visible on Refresh. Each request reads
the named directory's entries and obtains file metadata only for its page.
`showHidden=true` adds dot-prefixed entries; the existing generated-directory
exclusions remain. Requested folders retain workspace realpath confinement and
bounded reachability probes. Missing folders return 404, non-directories 400,
out-of-scope/excluded/hidden paths 403, and unavailable folders 422. Invalid or
incompatible cursors return 400.
Symbolic links retain the existing file-row representation, so the browser does
not expand directory links. Preview and download still use their existing path guards.
The existing `root=live`/`root=live-any` worktree rules and `worktree` metadata
apply. Paths remain relative to `workingDir` for inside worktrees and absolute
for followed outside worktrees. SSH sessions retain the existing listing behavior;
this mode adds no remote filesystem capability.
Without `lazy=1`, recursive listing responses are unchanged. A valid `q` query
uses the existing flat search response, including when `lazy=1` is present.
Search retains its 5,000-entry scan budget, 1,000-match cap, depth limit (default
5, maximum 10), and read ceiling. It reports `truncated: true` when a limit or an
unreachable folder leaves the search incomplete. Existing `q` responses are unchanged.
The panel's filtering, search, pagination and retry controls are described in
[Working With Files](wiki/Working-With-Files.md#the-file-viewer).
## Deleting a file (`DELETE /api/v1/sessions/:id/files?path=`)
The Files panel's delete button. `path` is what the listing gave the row: relative to the
+20
View File
@@ -824,6 +824,26 @@ Frontend `readmymind-ui.js`: header 🧠 marker-hidden (`btn-readmymind--hidden`
### Files panel search
The panel browses local workspaces through opt-in `lazy=1` directory pages (#759),
documented in [Listing a directory](api-reference.md#listing-a-directory-get-apiv1sessionsidfileslazy1).
Each request reads one directory, returns at most 500 entries and supplies `nextCursor`
when more remain. Cursor scope includes the session, selected root, directory and hidden
preference. Directories without `children` are unloaded; symbolic links keep their legacy
file-row representation, so the browser does not expand directory links. Path confinement, bounded
probes and the inside/outside worktree rules apply to every request.
The browser caches loaded pages in the current tree epoch. Owner, epoch, hidden preference,
selected root and tree identity guard folder/page responses. Typing filters loaded entries
without a request; Enter uses the existing workspace search, and clearing restores the tree.
Expand All opens only loaded folders. Refresh retains visible expansion state; automatic
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`
and `test/mobile/file-browser.test.ts`.
The recursive listing and `q` search policies below remain unchanged for existing callers.
**Files panel search** (COD-236, the `q` param on `GET /api/sessions/:id/files`): `compileFileQuery()` (`utils/file-query.ts`, pure, no IO, so it unit-tests directly) compiles the query into a reusable predicate, which is what lets the server-side walk prune instead of streaming the whole tree.
⚠️ **A query turns that endpoint into a FLAT match list rather than a nested tree**, and the walk deliberately recurses past non-matching directories, since the whole point of searching is to reach a file whose ancestors do not match. An empty or whitespace-only query compiles to `null`, which is what keeps the default tree response byte-identical when no search is requested.
+32 -8
View File
@@ -11,14 +11,38 @@ moved into ([Git Worktrees](Git-Worktrees#when-an-agent-moves-into-a-worktree)).
button is on by default on a desktop and off on a phone. The setting is per device: switch it
in **App Settings → Header & Panels** on the device you want it on.
The panel and its search list up to 5,000 files and folders per load, shallow levels first and
taking turns between folders, so one huge folder cannot use up that limit before the ones after it,
or the folders inside it, get a turn. They also stop opening folders after reading 250,000 entries,
so a workspace with several enormous folders can still leave later ones unread. When a workspace is
bigger than either limit the status line says `(truncated)`, and an expanded folder the scan did
not finish shows **Not fully scanned** rather than looking empty. A folder that does not answer,
such as a network mount that went away, is skipped rather than waited on and is marked the same way,
so a search can miss what is inside it. The panel's Refresh button tries it again.
For local workspaces, opening the panel lists the root's immediate files and folders.
Expanding a folder loads its contents, without scanning the folders inside it. Each page holds
up to 500 entries; **Load more** beneath a folder, or at the bottom of the root listing, adds
the next page. A large subtree no longer uses up the listing budget for unrelated folders.
Collapsing and reopening a loaded folder reuses its cached contents.
Use the search box as follows:
- **Type to filter loaded entries.** This makes no request and cannot find a file in a folder
you have not loaded. Matching ignores case; `*` separates pieces that must appear in order.
- **Press Enter to search the workspace**, including folders you have not opened, under the
root the panel is showing. Click a folder in the results to load its ancestors and browse it.
- **Clear the box to return to your tree**, with its expanded folders and loaded pages.
Workspace search keeps its existing limits: a 5,000-entry scan budget, up to 1,000 matches,
and depth and read limits. A limit or an unreachable folder can leave the search incomplete.
The status then says `(truncated)`; with no results the panel says **Search incomplete; no
matches in scanned files**, rather than implying the whole workspace has no matches. You can
still browse folders directly to reach files the search did not scan.
**Expand/Collapse All** opens folders whose contents are already loaded, or collapses them;
it does not fetch every folder in the workspace. The show-hidden button adds dot-prefixed files and
folders alongside ordinary entries and keeps the current filter or search and applicable
expanded folders. Generated directories such as `.git`, `node_modules`, `dist` and `build`
remain excluded.
**Refresh** clears the search and reloads the root and visible expanded folders, keeping
their expansion state. Contents behind a collapsed folder load when you reopen it. If a
folder or its next page fails to load, its error and **Retry loading** button appear there;
entries already loaded stay visible. Retry acts on that folder or page, while Refresh
reloads the visible tree. A failed load is never presented as an empty folder.
If the initial root listing fails, use Refresh.
Each file row has a download arrow and a × that deletes the file after you confirm. Both show
when you point at the row, and always on a touch screen. Delete removes one file at a time,
+18
View File
@@ -99,6 +99,24 @@ export interface FilesystemBrowseData {
truncated: boolean;
}
/** One page of immediate children for GET /sessions/:id/files?lazy=1. */
export interface LazyFileListingData {
root: string;
worktree?: { name: string; path: string; outside?: true };
lazy: true;
tree: Array<{
name: string;
path: string;
type: 'file' | 'directory';
size?: number;
extension?: string;
}>;
totalFiles: number;
totalDirectories: number;
truncated: boolean;
nextCursor?: string;
}
/** Response payload for `PUT /api/sessions/:id/file-content` (File Viewer edit mode). */
export interface FileWriteData {
/** Workspace-relative path as submitted */
+18
View File
@@ -1159,6 +1159,16 @@
'Filter by date range': '按日期范围筛选',
'Filter by session status': '按会话状态筛选',
'Filter files...': '筛选文件…',
'Filter loaded files · Enter to search workspace': '筛选已加载的文件 · 按 Enter 搜索工作区',
'Loading folder...': '正在加载文件夹…',
'Incomplete folder': '文件夹内容不完整',
'Load more': '加载更多',
'Retry loading': '重试加载',
'No files in this folder': '此文件夹中没有文件',
'Folder unavailable': '文件夹不可用',
'Workspace changed; refresh files': '工作区已更改,请刷新文件列表',
'No matches in loaded folders · Enter to search workspace': '已加载的文件夹中没有匹配项 · 按 Enter 搜索工作区',
'Search incomplete; no matches in scanned files': '搜索未完成;已扫描的文件中没有匹配项',
Worktree: '工作树',
'Session folder': '会话文件夹',
'Back to worktree': '返回工作树',
@@ -1702,6 +1712,14 @@
function translateDynamic(source) {
const patterns = [
[
/^(\d+) matches in loaded folders · Enter to search workspace$/,
(_m, n) => `已加载的文件夹中有 ${n} 个匹配项 · 按 Enter 搜索工作区`,
],
[
/^(\d+) files, (\d+) dirs · loaded folders( · hidden shown)?$/,
(_m, files, dirs, hidden) => `${files} 个文件,${dirs} 个文件夹 · 已加载${hidden ? ' · 已显示隐藏项' : ''}`,
],
[/^(\d+) tokens?$/, (_m, count) => `${count} 个 Token`],
[/^(\d+) sessions?$/, (_m, count) => `${count} 个会话`],
[/^(\d+) tasks?$/, (_m, count) => `${count} 个任务`],
+1 -1
View File
@@ -640,7 +640,7 @@
<button type="button" class="file-browser-root-switch" id="fileBrowserRootSwitch" onclick="app.toggleFileBrowserRoot()">Session folder</button>
</div>
<div class="file-browser-search">
<input type="text" id="fileBrowserSearch" placeholder="Filter files..." oninput="app.filterFileBrowser(this.value)">
<input type="text" id="fileBrowserSearch" placeholder="Filter loaded files · Enter to search workspace" oninput="app.filterFileBrowser(this.value)" onkeydown="if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); app.searchFileBrowser(this.value); }">
</div>
<div class="file-browser-body" id="fileBrowserTree">
<div class="file-browser-empty">Select a session to view files</div>
+251 -14
View File
@@ -2719,6 +2719,7 @@ Object.assign(CodemanApp.prototype, {
searchEpoch: 0,
ownerSessionId,
view: 'normal',
workspaceSearch: false,
normalState: this.fileBrowserData
? { sessionId: ownerSessionId, showHidden, treeEpoch: 0, phase: 'ready', data: this.fileBrowserData }
: null,
@@ -2753,6 +2754,7 @@ Object.assign(CodemanApp.prototype, {
state.deferredDirectoryTarget = null;
state.filter = '';
state.view = 'normal';
state.workspaceSearch = false;
state.sessionRootPinned = false;
state.pinnedWorktree = null;
this.fileBrowserData = null;
@@ -2798,6 +2800,7 @@ Object.assign(CodemanApp.prototype, {
state.deferredDirectoryTarget = null;
state.filter = '';
state.view = 'normal';
state.workspaceSearch = false;
state.sessionRootPinned = false;
state.pinnedWorktree = null;
this.fileBrowserData = null;
@@ -2837,8 +2840,21 @@ Object.assign(CodemanApp.prototype, {
_renderFileBrowserNormalStatus(data, showHidden) {
const statusEl = this.$('fileBrowserStatus');
if (!statusEl || !data) return;
const { totalFiles, totalDirectories, truncated } = data;
statusEl.textContent = `${totalFiles} files, ${totalDirectories} dirs${truncated ? ' (truncated)' : ''}${showHidden ? ' · hidden shown' : ''}`;
if (this._ensureFileBrowserState().filter.trim()) {
statusEl.textContent = `${this._fileBrowserLocalMatchCount || 0} matches in loaded folders · Enter to search workspace`;
return;
}
let { totalFiles, totalDirectories, truncated } = data;
if (data.lazy === true) {
totalFiles = 0;
totalDirectories = 0;
const count = nodes => nodes.forEach(node => {
if (node.type === 'directory') { totalDirectories++; count(node.children || []); }
else totalFiles++;
});
count(data.tree);
}
statusEl.textContent = `${totalFiles} files, ${totalDirectories} dirs${data.lazy ? ' · loaded folders' : truncated ? ' (truncated)' : ''}${showHidden ? ' · hidden shown' : ''}`;
},
_isFileBrowserNormalCompatible(candidate, sessionId, showHidden, treeEpoch) {
@@ -3084,6 +3100,7 @@ Object.assign(CodemanApp.prototype, {
const state = this._ensureFileBrowserState();
const rawInput = typeof state.filter === 'string' ? state.filter : '';
const query = rawInput.trim();
const workspaceSearch = state.workspaceSearch === true;
if (state.inFlight?.timer !== undefined && state.inFlight?.timer !== null) {
clearTimeout(state.inFlight.timer);
@@ -3112,7 +3129,8 @@ Object.assign(CodemanApp.prototype, {
if (!query || query.length > 256) return;
const continuation = { ownerSessionId, showHidden, treeEpoch, searchEpoch, rawInput, query };
if (this._canContinueFileBrowserHiddenReload(continuation, state.normalState)) {
this.filterFileBrowser(rawInput);
if (workspaceSearch) this.searchFileBrowser(rawInput);
else this.filterFileBrowser(rawInput);
}
},
@@ -3157,7 +3175,7 @@ Object.assign(CodemanApp.prototype, {
const request = (async () => {
try {
const res = await fetch(
`/api/sessions/${encodeURIComponent(sessionId)}/files?depth=5&showHidden=${showHidden}${this._fileBrowserRootParam()}`,
`/api/sessions/${encodeURIComponent(sessionId)}/files?lazy=1&showHidden=${showHidden}${this._fileBrowserRootParam()}`,
);
if (!res.ok) throw new Error('Failed to load files');
const result = await res.json();
@@ -3175,6 +3193,9 @@ Object.assign(CodemanApp.prototype, {
this.fileBrowserData = data;
const deferredRendered = this._completeDeferredFileBrowserDirectory?.(nextNormalState) === true;
if (!deferredRendered) this._renderFileBrowserNormalState(nextNormalState);
if (data.lazy === true && !deferredRendered) {
await this._restoreFileBrowserExpandedDirs(nextNormalState);
}
} catch (error) {
if (!this._isFileBrowserTreeContextCurrent(record, true)) return;
const nextNormalState = {
@@ -3198,6 +3219,164 @@ Object.assign(CodemanApp.prototype, {
return record.promise;
},
_isFileBrowserDirectoryRequestCurrent(request) {
return this._isFileBrowserTreeContextCurrent(request) &&
this.activeSessionId === request.sessionId &&
this._ensureFileBrowserState().normalState?.data === request.data &&
this._fileBrowserRootParam() === request.rootParam &&
this.$('fileBrowserPanel')?.classList.contains('visible') === true;
},
// A page belongs to one tree epoch. Refresh, visibility, root and owner changes can never
// append an old response to a replacement tree, even if the same folder is expanded again.
_loadFileBrowserDirectory(path, { more = false } = {}) {
const state = this._ensureFileBrowserState();
const normal = state.normalState;
const data = normal?.data;
if (normal?.phase !== 'ready' || data?.lazy !== true) return Promise.resolve();
const container = path ? this._findFileBrowserDirectory(data.tree, path)?.target : data;
if (!container) return Promise.resolve();
const listing = container._listing ||= { nextCursor: container.nextCursor || null };
if (listing.promise) return listing.promise;
if (more ? !listing.nextCursor : path && Array.isArray(container.children)) return Promise.resolve();
const cursor = more ? listing.nextCursor : null;
const request = {
sessionId: normal.sessionId, showHidden: normal.showHidden, treeEpoch: normal.treeEpoch,
data, rootParam: this._fileBrowserRootParam(),
};
if (!this._isFileBrowserDirectoryRequestCurrent(request)) return Promise.resolve();
listing.loading = true;
listing.error = null;
listing.failedMore = more;
const work = (async () => {
try {
const res = await fetch(`/api/sessions/${encodeURIComponent(request.sessionId)}/files?lazy=1&showHidden=${request.showHidden}${request.rootParam}${path ? `&path=${encodeURIComponent(path)}` : ''}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
const result = await res.json();
const page = this._validateFileBrowserTreeEnvelope(result);
if (!res.ok || !page || page.lazy !== true) throw new Error(result?.error || 'Folder unavailable');
if (page.root !== data.root) throw new Error('Workspace changed; refresh files');
if (!this._isFileBrowserDirectoryRequestCurrent(request)) return;
const key = path ? 'children' : 'tree';
const previous = more ? container[key] || [] : [];
const known = new Set(previous.map(node => node.path));
container[key] = [...previous, ...page.tree.filter(node => !known.has(node.path))];
listing.nextCursor = page.nextCursor || null;
if (!path) {
data.nextCursor = listing.nextCursor;
data.truncated = Boolean(listing.nextCursor);
}
} catch (error) {
if (this._isFileBrowserDirectoryRequestCurrent(request)) {
listing.error = this._normalizeFileBrowserTreeError(error);
}
} finally {
listing.loading = false;
listing.promise = null;
if (this._isFileBrowserDirectoryRequestCurrent(request)) this._renderFileBrowserNormalState(normal);
}
})();
listing.promise = work;
this._renderFileBrowserNormalState(normal);
return work;
},
// Follow only the ancestor chain of the named folder. Continuation is explicit for ordinary
// browsing; revealing a search hit/restoring an expansion reads the pages needed to reach it.
async _revealFileBrowserDirectory(target, normal, current, expandedOnly = false) {
const data = normal.data;
let container = data;
const paths = [];
while (current()) {
const nodes = container === data ? container.tree : container.children || [];
let found = nodes.find(node => node.type === 'directory' &&
(node.path === target || target.startsWith(node.path + '/') || target.startsWith(node.path + '\\')));
if (!found) {
// 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;
await this._loadFileBrowserDirectory(container === data ? '' : container.path, { more: true });
if (!current() || container._listing?.error) return null;
continue;
}
if (expandedOnly && !this.fileBrowserExpandedDirs.has(found.path)) return null;
if (expandedOnly && found._listing?.error) return null;
paths.push(found.path);
await this._loadFileBrowserDirectory(found.path);
if (!current() || found._listing?.error) return null;
if (found.path === target) return paths;
container = found;
}
return null;
},
async _restoreFileBrowserExpandedDirs(normal) {
if (normal?.data?.lazy !== true) return;
const request = { ...normal, rootParam: this._fileBrowserRootParam() };
const current = () => this._isFileBrowserDirectoryRequestCurrent(request);
// Root rows are immediate children, so their common path prefix is the listing root in
// returned-path terms. Dot segments in an inside worktree's prefix do not make its entries
// hidden. Skip inapplicable expansions before searching any continuation pages for them.
const first = normal.data.tree[0];
const rootPrefix = first?.name ? first.path.slice(0, -first.name.length) : null;
const separator = normal.data.root?.startsWith('/') ? '/' : '\\';
for (const path of [...this.fileBrowserExpandedDirs]) {
if (!current()) return;
if (rootPrefix === null || !path.startsWith(rootPrefix)) continue;
if (!normal.showHidden && path.slice(rootPrefix.length).split(separator).some(part => part.startsWith('.'))) continue;
await this._revealFileBrowserDirectory(path, normal, current, true);
}
},
_restoreFileBrowserAfterLoad(path, normal) {
if (normal?.data?.lazy !== true || this._ensureFileBrowserState().normalState !== normal) return;
const container = path ? this._findFileBrowserDirectory(normal.data.tree, path)?.target : normal.data;
if (container && !container._listing?.error && (!path || Array.isArray(container.children))) {
return this._restoreFileBrowserExpandedDirs(normal);
}
},
_fileBrowserListingControls(container, path, depth) {
const listing = container._listing;
const cursor = listing?.nextCursor ?? container.nextCursor;
let content = '';
if (listing?.loading) content = escapeHtml('Loading folder...');
else if (listing?.error) {
content = `${escapeHtml(listing.error)} · ${escapeHtml('Incomplete folder')} <button type="button" data-file-browser-load="${listing.failedMore ? 'more' : 'retry'}" data-path="${escapeHtml(path)}">${escapeHtml('Retry loading')}</button>`;
} else if (cursor) {
content = `<button type="button" data-file-browser-load="more" data-path="${escapeHtml(path)}">${escapeHtml('Load more')}</button>`;
} else if (path && Array.isArray(container.children) && !container.children.length) {
content = escapeHtml('No files in this folder');
}
return content ? `<div class="file-tree-incomplete file-tree-listing-state" data-depth="${depth}"${this._fileBrowserDepthStyle(depth)}>${content}</div>` : '';
},
// Legacy CSS covers depths 0–9; lazy browsing can reach deeper folders.
_fileBrowserDepthStyle(depth) {
return depth > 9 ? ` style="padding-inline-start: ${0.5 + depth * 0.75}rem"` : '';
},
// Ordered, case-insensitive substring pieces; no user-supplied regular expression.
_filterFileBrowserLoadedTree(nodes, query) {
const pieces = query.toLowerCase().split('*').filter(Boolean);
let count = 0;
const filter = entries => entries.flatMap(node => {
const text = (query.includes('/') ? node.path : node.name).toLowerCase();
let offset = 0;
const matches = pieces.every(piece => {
const next = text.indexOf(piece, offset);
if (next < 0) return false;
offset = next + piece.length;
return true;
});
if (matches) count++;
const children = filter(node.children || []);
return matches || children.length ? [{ ...node, ...(node.children && { children }) }] : [];
});
const tree = filter(nodes);
return { tree, count };
},
renderFileBrowserTree(ownerSessionId) {
const treeEl = this.$('fileBrowserTree');
if (!treeEl || !this.fileBrowserData) return;
@@ -3206,9 +3385,12 @@ Object.assign(CodemanApp.prototype, {
const owner = ownerSessionId || state.normalState?.sessionId || state.ownerSessionId || this.activeSessionId;
if (!owner) return;
const { tree } = this.fileBrowserData;
const query = state.view === 'normal' ? state.filter.trim() : '';
const filtered = query ? this._filterFileBrowserLoadedTree(this.fileBrowserData.tree, query) : null;
const tree = filtered ? filtered.tree : this.fileBrowserData.tree;
this._fileBrowserLocalMatchCount = filtered?.count || 0;
if (!tree || tree.length === 0) {
treeEl.innerHTML = '<div class="file-browser-empty">No files found</div>';
treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml(query ? 'No matches in loaded folders · Enter to search workspace' : 'No files found')}</div>`;
return;
}
@@ -3217,7 +3399,7 @@ Object.assign(CodemanApp.prototype, {
const renderNode = (node, depth) => {
const isDir = node.type === 'directory';
const isExpanded = this.fileBrowserExpandedDirs.has(node.path);
const isExpanded = query ? !!node.children?.length : this.fileBrowserExpandedDirs.has(node.path);
const icon = isDir
? (isExpanded ? '\uD83D\uDCC2' : '\uD83D\uDCC1')
@@ -3245,7 +3427,7 @@ Object.assign(CodemanApp.prototype, {
: '';
html.push(`
<div class="file-tree-item" data-path="${escapeHtml(node.path)}" data-type="${escapeHtml(node.type)}" data-depth="${depth}">
<div class="file-tree-item" data-path="${escapeHtml(node.path)}" data-type="${escapeHtml(node.type)}" data-depth="${depth}"${this._fileBrowserDepthStyle(depth)}>
${expandIcon}
<span class="file-tree-icon">${icon}</span>
<span class="${nameClass}">${escapeHtml(node.name)}</span>
@@ -3264,7 +3446,9 @@ Object.assign(CodemanApp.prototype, {
// The scan stopped at a limit or the folder did not answer, so what is listed above is not all
// of it. Not a .file-tree-item: the click wiring below would try to open it as a file.
if (isDir && isExpanded && node.incomplete === true) {
if (isDir && isExpanded && this.fileBrowserData.lazy === true && !query) {
html.push(this._fileBrowserListingControls(node, node.path, depth + 1));
} else if (isDir && isExpanded && node.incomplete === true) {
html.push(`<div class="file-tree-incomplete" data-depth="${depth + 1}">${escapeHtml('Not fully scanned')}</div>`);
}
};
@@ -3272,9 +3456,18 @@ Object.assign(CodemanApp.prototype, {
for (const node of tree) {
renderNode(node, 0);
}
if (this.fileBrowserData.lazy === true && !query) html.push(this._fileBrowserListingControls(this.fileBrowserData, '', 0));
treeEl.innerHTML = html.join('');
treeEl.querySelectorAll('[data-file-browser-load]').forEach(button => {
button.addEventListener('click', () => {
const normal = this._ensureFileBrowserState().normalState;
this._loadFileBrowserDirectory(button.dataset.path, { more: button.dataset.fileBrowserLoad === 'more' })
.then(() => this._restoreFileBrowserAfterLoad(button.dataset.path, normal));
});
});
// Add click handlers
treeEl.querySelectorAll('.file-tree-item').forEach(item => {
item.addEventListener('click', () => {
@@ -3307,14 +3500,40 @@ Object.assign(CodemanApp.prototype, {
this.fileBrowserExpandedDirs.delete(path);
} else {
this.fileBrowserExpandedDirs.add(path);
const normal = this._ensureFileBrowserState().normalState;
this._loadFileBrowserDirectory(path).then(() => this._restoreFileBrowserAfterLoad(path, normal));
}
this.renderFileBrowserTree();
},
filterFileBrowser(value) {
const state = this._ensureFileBrowserState();
if (state.inFlight?.timer != null) clearTimeout(state.inFlight.timer);
state.searchEpoch++;
state.inFlight = null;
state.matches = [];
state.deferredDirectoryTarget = null;
state.filter = this.fileBrowserFilter = String(value ?? '');
state.view = 'normal';
state.workspaceSearch = false;
this._syncFileBrowserExpandBtn();
if (state.filter.trim().length > 256) {
const message = 'Search queries are limited to 256 characters';
state.view = 'query-error';
const treeEl = this.$('fileBrowserTree');
if (treeEl) treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml(message)}</div>`;
const statusEl = this.$('fileBrowserStatus');
if (statusEl) statusEl.textContent = message;
return;
}
this._renderFileBrowserNormalState(state.normalState);
},
searchFileBrowser(value = this.fileBrowserFilter) {
const state = this._ensureFileBrowserState();
const rawInput = String(value ?? '');
const query = rawInput.trim();
state.workspaceSearch = query.length > 0 && query.length <= 256;
state.searchEpoch++;
state.filter = rawInput;
state.deferredDirectoryTarget = null;
@@ -3424,7 +3643,7 @@ Object.assign(CodemanApp.prototype, {
view: state.view,
};
if (matches.length === 0) {
treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml('No matches')}</div>`;
treeEl.innerHTML = `<div class="file-browser-empty">${escapeHtml(data.truncated ? 'Search incomplete; no matches in scanned files' : 'No matches')}</div>`;
} else {
const ownerPath = encodeURIComponent(ownerSessionId);
const canDelete = this._fileBrowserCanDelete(ownerSessionId);
@@ -3571,6 +3790,10 @@ Object.assign(CodemanApp.prototype, {
return;
}
if (normalState.data.lazy === true) {
return this._revealFileBrowserSearchDirectory(target, normalState);
}
const found = this._findFileBrowserDirectory(normalState.data?.tree, target.path);
if (!found) {
this._promptFileBrowserDirectoryReload();
@@ -3605,6 +3828,11 @@ Object.assign(CodemanApp.prototype, {
return false;
}
if (normalState.data.lazy === true) {
this._revealFileBrowserSearchDirectory(target, normalState);
return true;
}
const found = this._findFileBrowserDirectory(normalState.data?.tree, target.path);
if (!found) {
this._promptFileBrowserDirectoryReload();
@@ -3614,6 +3842,15 @@ Object.assign(CodemanApp.prototype, {
return true;
},
async _revealFileBrowserSearchDirectory(target, normalState) {
const current = () => this._isFileBrowserDirectoryContextCurrent(target) &&
this._ensureFileBrowserState().normalState === normalState;
const paths = await this._revealFileBrowserDirectory(target.path, normalState, current);
if (!current()) return;
if (!paths) { this._promptFileBrowserDirectoryReload(); return; }
this._leaveFileBrowserSearchForDirectory(paths, normalState);
},
_leaveFileBrowserSearchForDirectory(paths, normalState) {
const state = this._ensureFileBrowserState();
if (state.inFlight?.timer !== undefined && state.inFlight?.timer !== null) {
@@ -3626,6 +3863,7 @@ Object.assign(CodemanApp.prototype, {
state.deferredDirectoryTarget = null;
state.view = 'normal';
this.fileBrowserFilter = '';
state.workspaceSearch = false;
const input = this.$?.('fileBrowserSearch');
if (input) input.value = '';
@@ -3639,7 +3877,7 @@ Object.assign(CodemanApp.prototype, {
expandAllDirectories(nodes) {
for (const node of nodes) {
if (node.type === 'directory') {
if (node.type === 'directory' && Array.isArray(node.children)) {
this.fileBrowserExpandedDirs.add(node.path);
if (node.children) {
this.expandAllDirectories(node.children);
@@ -3681,11 +3919,10 @@ Object.assign(CodemanApp.prototype, {
state.matches = [];
state.deferredDirectoryTarget = null;
state.view = 'normal';
state.workspaceSearch = false;
this.fileBrowserFilter = '';
this.fileBrowserExpandedDirs.clear();
this.fileBrowserAllExpanded = false;
const expandBtn = this.$('fileBrowserExpandBtn');
if (expandBtn) expandBtn.innerHTML = '\u229E';
if (expandBtn) expandBtn.innerHTML = this.fileBrowserAllExpanded ? '\u229F' : '\u229E';
const searchInput = this.$('fileBrowserSearch');
if (searchInput) searchInput.value = '';
this._syncFileBrowserExpandBtn();
+30
View File
@@ -11803,6 +11803,36 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
cursor: default;
}
.file-tree-incomplete button {
margin-inline-start: 0.25rem;
padding: 0.2rem 0.45rem;
color: var(--text-primary);
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 4px;
font: inherit;
font-style: normal;
white-space: nowrap;
cursor: pointer;
}
.file-tree-listing-state {
white-space: normal;
overflow-wrap: anywhere;
}
.file-tree-incomplete button:hover,
.file-tree-incomplete button:focus-visible {
background: var(--bg-hover);
}
@media (pointer: coarse) {
.file-tree-incomplete button {
min-width: 44px;
min-height: 44px;
}
}
.file-tree-icon {
width: 1rem;
text-align: center;
+112 -1
View File
@@ -23,6 +23,7 @@ import type {
FilesystemPreviewKind,
FileDeleteData,
FileWriteData,
LazyFileListingData,
} from '../../types.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage } from '../../types.js';
import { compileFileQuery } from '../../utils/file-query.js';
@@ -91,6 +92,8 @@ import {
FilesystemMkdirSchema,
FilesystemPreviewQuerySchema,
FileWriteSchema,
LazyFileListingQuerySchema,
FileListingCursorSchema,
} from '../schemas.js';
import {
MAX_EDITABLE_BYTES,
@@ -1742,11 +1745,12 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
// File tree listing
app.get('/api/sessions/:id/files', async (req) => {
const { id } = req.params as { id: string };
const { depth, showHidden, q, root } = req.query as {
const { depth, showHidden, q, root, lazy } = req.query as {
depth?: string;
showHidden?: string;
q?: string;
root?: string;
lazy?: string;
};
const session = findSessionOrFail(ctx, id, req);
@@ -1821,6 +1825,113 @@ export function registerFileRoutes(app: FastifyInstance, ctx: SessionPort & Even
const isListed = (entry: Dirent): boolean =>
(includeHidden || !entry.name.startsWith('.')) && !(entry.isDirectory() && excludeDirs.has(entry.name));
// One folder at a time for the Files panel. Keep the legacy tree/search branches below
// untouched: existing callers depend on their exact response shape and scan policy.
if (lazy === '1' && !matcher && !session.remote) {
const parsed = LazyFileListingQuerySchema.safeParse(req.query);
if (!parsed.success) throwRouteError(400, ApiErrorCode.INVALID_INPUT, 'Invalid directory listing query');
const { path: directoryPath, cursor } = parsed.data;
const namedPath = directoryPath ? resolve(workingDir, directoryPath) : walkRoot;
const lexical = validateSessionFilePathLexical(walkRoot, namedPath);
if (!lexical) throwRouteError(403, ApiErrorCode.FORBIDDEN, 'Directory is outside the selected workspace');
const checkKind = async (folder: string): Promise<void> => {
const kind = await probePathKind(folder, { pastCap: true });
if (kind === 'unknown') {
throwRouteError(
422,
ApiErrorCode.OPERATION_FAILED,
describeUnknownPath('The folder', folder, { pastCap: true })
);
}
if (kind === 'absent') throwRouteError(404, ApiErrorCode.NOT_FOUND, 'Folder not found');
if (kind !== 'directory') throwRouteError(400, ApiErrorCode.INVALID_INPUT, 'Path is not a directory');
};
// Probe before synchronous confinement and before readdir (#516), including a request
// naming a directory on an unresponsive mount. Never turn unknown into an empty list.
await checkKind(walkRoot);
if (namedPath !== walkRoot) await checkKind(namedPath);
const validated = validateLocalSessionFilePath({ workingDir, liveWorktree }, namedPath);
const selected = validated && validateSessionFilePath(walkRoot, namedPath);
if (!selected) throwRouteError(403, ApiErrorCode.FORBIDDEN, 'Directory is outside the selected workspace');
const refusedSegment = (path: string): boolean =>
path.split(sep).some((part) => excludeDirs.has(part) || (!includeHidden && part.startsWith('.')));
// Both names matter: an alias may point at an excluded/hidden directory.
if (refusedSegment(lexical.relativePath) || refusedSegment(selected.relativePath)) {
throwRouteError(403, ApiErrorCode.FORBIDDEN, 'Directory is excluded or hidden');
}
const scope = createHash('sha256')
.update(JSON.stringify([id, walkRoot, namedPath, includeHidden]))
.digest('hex');
let after: { name: string; directory: boolean } | undefined;
if (cursor) {
try {
const decoded = FileListingCursorSchema.parse(JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')));
if (decoded.scope !== scope) throw new Error('Different listing');
after = decoded;
} catch {
throwRouteError(400, ApiErrorCode.INVALID_INPUT, 'Invalid directory continuation; refresh files');
}
}
const compare = (a: { name: string; directory: boolean }, b: { name: string; directory: boolean }): number =>
Number(b.directory) - Number(a.directory) ||
a.name.localeCompare(b.name) ||
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
let entries: Dirent[];
try {
entries = await fs.readdir(namedPath, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
throwRouteError(404, ApiErrorCode.NOT_FOUND, 'Folder not found');
throwRouteError(422, ApiErrorCode.OPERATION_FAILED, 'Folder unavailable; retry or refresh files');
}
const listed = entries
.filter(
(entry) =>
isListed(entry) && (!after || compare({ name: entry.name, directory: entry.isDirectory() }, after) > 0)
)
.sort((a, b) =>
compare({ name: a.name, directory: a.isDirectory() }, { name: b.name, directory: b.isDirectory() })
);
// Bound both the response and metadata reads, independently for every folder/page.
const page = listed.slice(0, 500);
const data: LazyFileListingData = {
root: walkRoot,
...(reportedWorktree && { worktree: reportedWorktree }),
lazy: true,
tree: [],
totalFiles: 0,
totalDirectories: 0,
truncated: listed.length > page.length,
};
for (const entry of page) {
const fullPath = join(namedPath, entry.name);
if (entry.isDirectory()) {
data.tree.push({ name: entry.name, path: nodePath(fullPath), type: 'directory' });
data.totalDirectories++;
} else {
// Match legacy leaf rows, including symbolic links; directory links are not traversed.
let size: number | undefined;
try {
size = (await fs.stat(fullPath)).size;
} catch {
/* A disappearing file is still a listed entry. */
}
const extension = entry.name.includes('.') ? entry.name.split('.').pop()?.toLowerCase() : undefined;
data.tree.push({ name: entry.name, path: nodePath(fullPath), type: 'file', size, extension });
data.totalFiles++;
}
}
if (data.truncated) {
const last = page[page.length - 1];
data.nextCursor = Buffer.from(
JSON.stringify({ scope, name: last.name, directory: last.isDirectory() })
).toString('base64url');
}
return { success: true, data };
}
// ===== Search mode =====
// A query turns this endpoint into a FLAT match list rather than a nested
// tree. It recurses past non-matching directories on purpose — the whole
+28
View File
@@ -134,6 +134,34 @@ export const FilesystemPreviewQuerySchema = z.object({
showHidden: showHiddenQuerySchema,
});
/** Additive Files-panel listing mode. Existing recursive callers are not parsed through this. */
export const LazyFileListingQuerySchema = z.object({
path: z
.string()
.max(4096)
.refine((p) => !p.includes('\0'))
.optional(),
cursor: z
.string()
.min(1)
.max(4096)
.regex(/^[A-Za-z0-9_-]+$/)
.optional(),
});
/** A continuation key, scoped to one session, root, directory and hidden-files preference. */
export const FileListingCursorSchema = z
.object({
scope: z.string().regex(/^[a-f0-9]{64}$/),
name: z
.string()
.min(1)
.max(255)
.refine((name) => !name.includes('\0') && !name.includes('/')),
directory: z.boolean(),
})
.strict();
/**
* Body validation for `PUT /api/sessions/:id/file-content` (File Viewer edit
* mode). `content.max()` counts UTF-16 code units, which for UTF-8 output is
+643
View File
@@ -0,0 +1,643 @@
/**
* @fileoverview Issue #759 lazy Files panel acceptance tests.
*
* The actual index.html panel (including inline search/header bindings) and panels-ui.js run in
* jsdom. Only HTTP is faked: clicks, input and Enter traverse the shipped DOM handlers. This is
* gate-runnable behavior coverage, not source-string assertions or a duplicate tree algorithm.
* Playwright layout verification lives in mobile/file-browser.test.ts; these tests need no server.
*
* The lazy wire additions are shared with routes/file-routes-lazy.test.ts: lazy=true,
* immediate children in tree, opaque nextCursor/cursor, and absent children means unloaded.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
const INDEX = readFileSync(resolve(PUBLIC, 'index.html'), 'utf8');
const PANELS = readFileSync(resolve(PUBLIC, 'panels-ui.js'), 'utf8');
interface Entry {
name: string;
path: string;
type: 'file' | 'directory';
size?: number;
extension?: string;
children?: Entry[];
}
const folder = (path: string): Entry => ({ name: path.split('/').pop()!, path, type: 'directory' });
const file = (path: string): Entry => ({
name: path.split('/').pop()!,
path,
type: 'file',
size: 1,
extension: 'ts',
});
const response = (data: unknown, ok = true) => ({
ok,
status: ok ? 200 : 503,
json: async () => (ok ? { success: true, data } : { success: false, error: 'Folder unavailable' }),
});
const page = (tree: Entry[], nextCursor?: string, root = '/repo') =>
response({
root,
lazy: true,
tree,
nextCursor,
totalFiles: tree.filter((entry) => entry.type === 'file').length,
totalDirectories: tree.filter((entry) => entry.type === 'directory').length,
truncated: Boolean(nextCursor),
});
const search = (matches: Entry[], truncated = false) =>
response({
root: '/repo',
mode: 'search',
tree: [],
query: 'needle',
matches,
matchCount: matches.length,
totalScanned: 10,
truncated,
});
type Response = ReturnType<typeof response>;
type Responder = (url: URL) => Response | Promise<Response>;
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
function loadPanel() {
const source = new JSDOM(INDEX);
const panel = source.window.document.getElementById('fileBrowserPanel');
if (!panel) throw new Error('Shipped Files panel is missing');
const markup = panel.outerHTML;
source.window.close();
const dom = new JSDOM(markup, { url: 'http://localhost/', runScripts: 'dangerously' });
const context = dom.getInternalVMContext();
Object.assign(context, {
console: { ...console, error: vi.fn() },
setTimeout,
clearTimeout,
CodemanBase: { url: (path: string) => path },
escapeHtml: (value: unknown) =>
String(value)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#039;'),
});
vm.runInContext('class CodemanApp {}', context);
vm.runInContext(PANELS, context, { filename: 'panels-ui.js' });
const app = vm.runInContext('new CodemanApp()', context) as Record<string, any>;
const document = dom.window.document;
app.$ = (id: string) => document.getElementById(id);
app.activeSessionId = 'sess-A';
app.fileBrowserData = null;
app.fileBrowserExpandedDirs = new Set<string>();
app.fileBrowserFilter = '';
app.fileBrowserAllExpanded = false;
app.fileBrowserShowHidden = false;
app.getFileIcon = () => '';
app.formatFileSize = () => '';
app.openFilePreview = vi.fn();
app.showToast = vi.fn();
context.app = app;
document.getElementById('fileBrowserPanel')!.classList.add('visible');
const requests: URL[] = [];
const server = {
respond: ((url: URL) => {
if (url.searchParams.has('q')) return search([folder('src/deep'), file('src/deep/needle.ts')]);
switch (url.searchParams.get('path')) {
case 'src':
return page([folder('src/deep'), file('src/visible.ts')]);
case 'src/deep':
return page([file('src/deep/needle.ts')]);
case 'empty':
return page([]);
default:
return page([folder('empty'), folder('src'), file('README.md')]);
}
}) as Responder,
};
context.fetch = (input: string) => {
const url = new URL(input, 'http://localhost/');
requests.push(url);
return Promise.resolve(server.respond(url));
};
const tree = document.getElementById('fileBrowserTree')!;
const input = document.getElementById('fileBrowserSearch') as HTMLInputElement;
const rows = () => [...tree.querySelectorAll<HTMLElement>('.file-tree-item')];
const paths = () => rows().map((row) => row.dataset.path);
const clickFolder = (path: string) => {
const row = rows().find((item) => item.dataset.path === path);
expect(row, `Missing folder row: ${path}`).toBeDefined();
expect(row!.dataset.type).toBe('directory');
row!.click();
};
const clickButton = (name: RegExp, within: Element = tree) => {
const button = [...within.querySelectorAll<HTMLButtonElement>('button')].find((item) =>
name.test([item.textContent, item.getAttribute('aria-label'), item.title].join(' '))
);
expect(button, `Missing button: ${name}`).toBeDefined();
expect(button!.disabled).toBe(false);
button!.click();
};
const type = (value: string) => {
input.value = value;
input.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
};
const enter = () =>
input.dispatchEvent(
new dom.window.KeyboardEvent('keydown', {
key: 'Enter',
code: 'Enter',
bubbles: true,
cancelable: true,
})
);
return { dom, app, document, tree, input, requests, server, paths, clickFolder, clickButton, type, enter };
}
type Panel = ReturnType<typeof loadPanel>;
const settle = () => vi.advanceTimersByTimeAsync(300);
describe('Files panel lazy browsing behavior (#759)', () => {
let ui: Panel;
beforeEach(() => {
vi.useFakeTimers();
ui = loadPanel();
});
afterEach(() => {
ui.dom.window.close();
vi.clearAllTimers();
vi.useRealTimers();
});
const open = () => ui.app.loadFileBrowser('sess-A');
const expand = async (path: string) => {
ui.clickFolder(path);
await settle();
};
const runSearch = async (value = 'needle') => {
ui.type(value);
ui.enter();
await settle();
};
it('opens with one lazy root request and renders all returned root entries', async () => {
await open();
expect(ui.requests).toHaveLength(1);
expect(ui.requests[0].searchParams.get('lazy')).toBe('1');
expect(ui.requests[0].searchParams.get('root')).toBe('live-any');
expect(ui.requests[0].searchParams.get('showHidden')).toBe('false');
expect(ui.paths()).toEqual(['empty', 'src', 'README.md']);
expect(ui.tree.textContent).not.toMatch(/empty folder|no files in/i);
});
it('loads just the expanded folder and reuses its children on collapse/reopen', async () => {
await open();
await expand('src');
expect(ui.requests).toHaveLength(2);
expect(ui.requests[1].searchParams.get('path')).toBe('src');
expect(ui.requests[1].searchParams.get('lazy')).toBe('1');
expect(ui.paths()).toContain('src/visible.ts');
expect(ui.paths()).not.toContain('src/deep/needle.ts');
await expand('src');
expect(ui.paths()).not.toContain('src/visible.ts');
await expand('src');
expect(ui.paths()).toContain('src/visible.ts');
expect(ui.requests).toHaveLength(2);
});
it('keeps indenting folder contents beyond the legacy recursive tree depth', async () => {
ui.server.respond = (url) => {
const path = url.searchParams.get('path');
const depth = path ? path.split('/').length : 0;
return page(depth < 11 ? [folder(`${path ? `${path}/` : ''}level-${depth}`)] : [file(`${path}/bottom.ts`)]);
};
await open();
let path = '';
for (let depth = 0; depth < 11; depth++) {
path = `${path ? `${path}/` : ''}level-${depth}`;
await expand(path);
}
const row = ui.tree.querySelector<HTMLElement>('[data-depth="11"]');
expect(row?.dataset.path).toBe(`${path}/bottom.ts`);
expect(row?.style.paddingInlineStart).toBe('8.75rem');
});
it('does not duplicate an unfinished folder request when rapidly reopened', async () => {
await open();
const pending = deferred<Response>();
ui.server.respond = () => pending.promise;
await expand('src');
await expand('src');
await expand('src');
expect(ui.requests).toHaveLength(2);
pending.resolve(page([file('src/visible.ts')]));
await settle();
expect(ui.paths()).toContain('src/visible.ts');
});
it('shows a completed empty folder differently from an unloaded or failed folder', async () => {
await open();
await expand('empty');
expect(ui.requests.at(-1)!.searchParams.get('path')).toBe('empty');
// Remove file/folder names: the folder named "empty" must not satisfy this assertion itself.
const messages = ui.tree.cloneNode(true) as HTMLElement;
messages.querySelectorAll('.file-tree-item').forEach((row) => row.remove());
expect(messages.textContent).toMatch(/empty|no files/i);
expect([...ui.tree.querySelectorAll('button')].some((button) => /retry/i.test(button.textContent!))).toBe(false);
await expand('empty');
await expand('empty');
expect(ui.requests).toHaveLength(2);
});
it.each(['root', 'folder'])(
'appends %s pages through Load more without refetching unrelated folders',
async (where) => {
ui.server.respond = (url) => {
const path = url.searchParams.get('path');
const cursor = url.searchParams.get('cursor');
if (where === 'folder' && !path) return page([folder('src'), folder('untouched')]);
const prefix = where === 'folder' ? 'src/' : '';
return cursor ? page([file(`${prefix}second.ts`)]) : page([file(`${prefix}first.ts`)], 'page-two');
};
await open();
if (where === 'folder') await expand('src');
const before = ui.requests.length;
ui.clickButton(/load more/i);
await settle();
expect(ui.requests).toHaveLength(before + 1);
expect(ui.requests.at(-1)!.searchParams.get('cursor')).toBe('page-two');
expect(ui.requests.at(-1)!.searchParams.get('path') ?? '').toBe(where === 'folder' ? 'src' : '');
const prefix = where === 'folder' ? 'src/' : '';
expect(ui.paths()).toContain(`${prefix}first.ts`);
expect(ui.paths()).toContain(`${prefix}second.ts`);
expect(new Set(ui.paths()).size).toBe(ui.paths().length);
expect([...ui.tree.querySelectorAll('button')].some((button) => /load more/i.test(button.textContent!))).toBe(
false
);
expect(ui.requests.some((url) => url.searchParams.get('path') === 'untouched')).toBe(false);
}
);
it('keeps previously loaded entries when the next page fails, and retries that page only', async () => {
let fail = true;
ui.server.respond = (url) => {
if (!url.searchParams.has('path')) return page([folder('src')]);
if (!url.searchParams.has('cursor')) return page([file('src/first.ts')], 'page-two');
return fail ? response(null, false) : page([file('src/second.ts')]);
};
await open();
await expand('src');
ui.clickButton(/load more/i);
await settle();
expect(ui.paths()).toContain('src/first.ts');
expect(ui.tree.textContent).toMatch(/unavailable|failed|incomplete|could not/i);
fail = false;
const before = ui.requests.length;
ui.clickButton(/retry/i);
await settle();
expect(ui.requests).toHaveLength(before + 1);
expect(ui.requests.at(-1)!.searchParams.get('cursor')).toBe('page-two');
expect(ui.paths()).toContain('src/first.ts');
expect(ui.paths()).toContain('src/second.ts');
});
it('offers a folder-local Retry without automatically refreshing the tree', async () => {
await open();
ui.server.respond = () => response(null, false);
await expand('src');
expect(ui.requests).toHaveLength(2);
expect(ui.paths()).toContain('README.md');
expect(ui.tree.textContent).toMatch(/unavailable|failed|could not/i);
ui.server.respond = () => page([file('src/recovered.ts')]);
ui.clickButton(/retry/i);
await settle();
expect(ui.requests).toHaveLength(3);
expect(ui.requests.at(-1)!.searchParams.get('path')).toBe('src');
expect(ui.paths()).toContain('src/recovered.ts');
});
it('does not retry a failed sibling when another folder loads successfully', async () => {
let fail = true;
ui.server.respond = (url) => {
const path = url.searchParams.get('path');
if (!path) return page([folder('bad'), folder('good')]);
if (path === 'bad' && fail) return response(null, false);
return page([file(`${path}/note.ts`)]);
};
await open();
await expand('bad');
await expand('good');
expect(ui.requests.map((url) => url.searchParams.get('path') ?? '')).toEqual(['', 'bad', 'good']);
expect(ui.paths()).toContain('good/note.ts');
fail = false;
ui.clickButton(/retry/i);
await settle();
expect(ui.requests.map((url) => url.searchParams.get('path') ?? '')).toEqual(['', 'bad', 'good', 'bad']);
expect(ui.paths()).toContain('bad/note.ts');
expect(ui.paths()).toContain('good/note.ts');
});
it('does not retry a failed root page during an unrelated folder expansion', async () => {
let refreshed = false;
let fail = true;
ui.server.respond = (url) => {
const path = url.searchParams.get('path');
if (path) return page([file(`${path}/note.ts`)]);
if (!refreshed) return page([folder('good'), folder('later')]);
if (url.searchParams.has('cursor')) return fail ? response(null, false) : page([folder('later')]);
return page([folder('good')], 'two');
};
await open();
await expand('later');
refreshed = true;
await ui.app.refreshFileBrowser(); // Restoring "later" reaches a failed root page.
const before = ui.requests.length;
await expand('good');
expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual(['good']);
fail = false;
ui.clickButton(/retry/i);
await settle();
expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual(['good', '', 'later']);
expect(ui.paths()).toContain('later/note.ts');
expect(ui.paths()).toContain('good/note.ts');
});
it('Expand All opens loaded directories without fetching unloaded descendants', async () => {
await open();
await expand('src');
await expand('src'); // Loaded, but collapsed again.
const before = ui.requests.length;
ui.clickButton(/expand\/collapse/i, ui.document.getElementById('fileBrowserPanel')!);
await settle();
expect(ui.paths()).toContain('src/visible.ts');
expect(ui.requests).toHaveLength(before);
expect(ui.app.fileBrowserExpandedDirs.has('src/deep')).toBe(false);
});
it('typing filters loaded files locally and never sends a request, even after the old debounce', async () => {
await open();
await expand('src');
const before = ui.requests.length;
ui.type('visible');
await settle();
expect(ui.requests).toHaveLength(before);
expect(ui.paths()).toContain('src/visible.ts');
expect(ui.paths()).not.toContain('README.md');
expect(ui.document.getElementById('fileBrowserStatus')!.textContent).toMatch(/loaded/i);
});
it('Enter searches the whole workspace, including unopened folders', async () => {
await open();
ui.type(' needle ');
await settle();
expect(ui.requests).toHaveLength(1);
ui.enter();
await settle();
expect(ui.requests).toHaveLength(2);
const request = ui.requests.at(-1)!;
expect(request.searchParams.get('q')).toBe('needle');
expect(request.searchParams.get('lazy')).not.toBe('1');
expect(request.searchParams.get('root')).toBe('live-any');
expect(ui.paths()).toContain('src/deep/needle.ts');
});
it('labels an incomplete zero-hit search instead of displaying an unqualified No matches', async () => {
await open();
ui.server.respond = () => search([], true);
await runSearch();
const message = `${ui.tree.textContent} ${ui.document.getElementById('fileBrowserStatus')!.textContent}`;
expect(message).toMatch(/incomplete|truncated|not fully/i);
expect(ui.tree.textContent!.trim()).not.toBe('No matches');
});
it('clearing search restores expanded folders and all loaded pages without network activity', async () => {
ui.server.respond = (url) => {
if (url.searchParams.has('q')) return search([file('elsewhere/needle.ts')]);
if (!url.searchParams.has('path')) return page([folder('src'), file('README.md')]);
return url.searchParams.has('cursor') ? page([file('src/second.ts')]) : page([file('src/first.ts')], 'page-two');
};
await open();
await expand('src');
ui.clickButton(/load more/i);
await settle();
const previous = ui.paths();
await runSearch();
expect(ui.paths()).toContain('elsewhere/needle.ts');
const before = ui.requests.length;
ui.type('');
await settle();
expect(ui.paths()).toEqual(previous);
expect(ui.app.fileBrowserExpandedDirs.has('src')).toBe(true);
expect(ui.requests).toHaveLength(before);
});
it('reveals a search-result folder by loading its ancestors and then its contents', async () => {
await open();
await runSearch();
ui.clickFolder('src/deep');
await settle();
expect(
ui.requests.filter((url) => url.searchParams.has('path')).map((url) => url.searchParams.get('path'))
).toEqual(['src', 'src/deep']);
expect(ui.input.value).toBe('');
expect(ui.paths()).toContain('src/deep/needle.ts');
expect(ui.app.fileBrowserExpandedDirs.has('src')).toBe(true);
expect(ui.app.fileBrowserExpandedDirs.has('src/deep')).toBe(true);
});
it('can reveal a search-result ancestor on a later root page', async () => {
const original = ui.server.respond;
ui.server.respond = (url) => {
if (url.searchParams.has('q') || url.searchParams.has('path')) return original(url);
return url.searchParams.has('cursor') ? page([folder('src')]) : page([folder('empty')], 'root-two');
};
await open();
await runSearch();
ui.clickFolder('src/deep');
await settle();
expect(ui.requests.some((url) => url.searchParams.get('cursor') === 'root-two')).toBe(true);
expect(ui.paths()).toContain('src/deep/needle.ts');
});
it('hidden toggles add entries and reload expanded folders without collapsing them', async () => {
await open();
await expand('src');
ui.server.respond = (url) =>
url.searchParams.has('path')
? page([file('src/.hidden.ts'), file('src/visible.ts')])
: page([folder('empty'), folder('src'), file('.env'), file('README.md')]);
ui.clickButton(/show hidden/i, ui.document.getElementById('fileBrowserPanel')!);
await settle();
expect(ui.app.fileBrowserExpandedDirs.has('src')).toBe(true);
expect(ui.paths()).toContain('README.md');
expect(ui.paths()).toContain('.env');
expect(ui.paths()).toContain('src/visible.ts');
expect(ui.paths()).toContain('src/.hidden.ts');
expect(ui.requests.slice(2).every((url) => url.searchParams.get('showHidden') === 'true')).toBe(true);
expect(ui.requests.slice(2).map((url) => url.searchParams.get('path') ?? '')).toEqual(['', 'src']);
});
it('does not drain root pages trying to restore a hidden folder after hiding it', async () => {
ui.app.fileBrowserShowHidden = true;
ui.server.respond = (url) => {
if (url.searchParams.get('path') === '.hidden') return page([file('.hidden/note.ts')]);
if (url.searchParams.get('showHidden') === 'true') return page([folder('.hidden'), file('a.ts')]);
if (url.searchParams.get('cursor') === 'two') return page([file('b.ts')], 'three');
if (url.searchParams.get('cursor') === 'three') return page([file('c.ts')]);
return page([file('a.ts')], 'two');
};
await open();
await expand('.hidden');
const before = ui.requests.length;
await ui.app.toggleFileBrowserHidden();
await settle();
expect(ui.requests.slice(before).map((url) => url.searchParams.get('cursor') ?? '')).toEqual(['']);
expect(ui.paths()).toEqual(['a.ts']);
expect(ui.tree.querySelector('[data-file-browser-load="more"]')).not.toBeNull();
});
it('restores visible folders under a dotted worktree prefix with hidden files off', async () => {
const prefix = '.claude/worktrees/feature';
const root = `/repo/${prefix}`;
ui.server.respond = (url) =>
url.searchParams.has('path')
? page([file(`${prefix}/src/note.ts`)], undefined, root)
: page([folder(`${prefix}/src`)], undefined, root);
await open();
await expand(`${prefix}/src`);
const before = ui.requests.length;
await ui.app.refreshFileBrowser();
expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual(['', `${prefix}/src`]);
expect(ui.paths()).toContain(`${prefix}/src/note.ts`);
});
it('Refresh reloads root and expanded folders, preserves expansion and leaves collapsed folders alone', async () => {
await open();
await expand('src');
const before = ui.requests.length;
ui.server.respond = (url) =>
url.searchParams.has('path')
? page([file('src/current.ts')])
: page([folder('empty'), folder('src'), file('NEW.md')]);
ui.clickButton(/refresh/i, ui.document.getElementById('fileBrowserPanel')!);
await settle();
expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual(['', 'src']);
expect(ui.app.fileBrowserExpandedDirs.has('src')).toBe(true);
expect(ui.paths()).toContain('src/current.ts');
expect(ui.paths()).toContain('NEW.md');
expect(ui.paths()).not.toContain('src/visible.ts');
});
it('refreshes no subtree behind a collapsed parent, then restores its expanded child on reopen', async () => {
await open();
await expand('src');
await expand('src/deep');
await expand('src'); // Collapse the parent, retaining the child expansion preference.
const before = ui.requests.length;
await ui.app.refreshFileBrowser();
expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual(['']);
expect(ui.app.fileBrowserExpandedDirs.has('src/deep')).toBe(true);
expect(ui.paths()).not.toContain('src/deep/needle.ts');
await expand('src');
expect(ui.requests.slice(before).map((url) => url.searchParams.get('path') ?? '')).toEqual(['', 'src', 'src/deep']);
expect(ui.paths()).toContain('src/deep/needle.ts');
});
it('preserves a local filter across a hidden toggle without silently starting whole-workspace search', async () => {
await open();
await expand('src');
ui.type('visible');
await settle();
const original = ui.server.respond;
ui.server.respond = (url) =>
url.searchParams.get('path') === 'src' ? page([file('src/.visible.ts'), file('src/visible.ts')]) : original(url);
const before = ui.requests.length;
ui.clickButton(/show hidden/i, ui.document.getElementById('fileBrowserPanel')!);
await settle();
expect(ui.input.value).toBe('visible');
expect(ui.paths()).toContain('src/.visible.ts');
expect(ui.paths()).toContain('src/visible.ts');
expect(ui.paths()).not.toContain('README.md');
expect(ui.requests.slice(before).every((url) => !url.searchParams.has('q'))).toBe(true);
});
it('rejects a page completion invalidated by Refresh instead of appending it to the new tree', async () => {
const pending = deferred<Response>();
ui.server.respond = (url) =>
url.searchParams.has('cursor') ? pending.promise : page([file('before.ts')], 'root-two');
await open();
ui.clickButton(/load more/i);
await settle();
expect(ui.requests.at(-1)!.searchParams.get('cursor')).toBe('root-two');
ui.server.respond = () => page([file('current.ts')]);
ui.app.refreshFileBrowser();
await settle();
pending.resolve(page([file('STALE.ts')]));
await settle();
expect(ui.paths()).toEqual(['current.ts']);
expect(JSON.stringify(ui.app.fileBrowserData)).not.toContain('STALE.ts');
});
it.each(['refresh', 'hidden', 'session', 'hide', 'root'])(
'drops a late folder response after %s changes the browsing context',
async (change) => {
await open();
const pending = deferred<Response>();
const original = ui.server.respond;
let intercepted = false;
ui.server.respond = (url) => {
if (!intercepted && url.searchParams.get('path') === 'src') {
intercepted = true;
return pending.promise;
}
return original(url);
};
await expand('src');
expect(intercepted).toBe(true);
if (change === 'refresh') ui.app.refreshFileBrowser();
if (change === 'hidden') ui.app.toggleFileBrowserHidden();
if (change === 'session') {
ui.app.activeSessionId = 'sess-B';
ui.app._activateFileBrowserSession('sess-B');
}
if (change === 'hide') {
ui.document.getElementById('fileBrowserPanel')!.classList.remove('visible');
ui.app._resetFileBrowserForHide();
}
if (change === 'root') ui.app.toggleFileBrowserRoot();
await settle();
const before = ui.tree.innerHTML;
pending.resolve(page([file('src/STALE.ts')]));
await settle();
expect(ui.tree.innerHTML).toBe(before);
expect(JSON.stringify(ui.app.fileBrowserData)).not.toContain('STALE.ts');
}
);
it('keeps preview and download actions bound to the listing owner after lazy expansion', async () => {
await open();
await expand('src');
const row = [...ui.tree.querySelectorAll<HTMLElement>('.file-tree-item')].find(
(item) => item.dataset.path === 'src/visible.ts'
);
expect(row).toBeDefined();
const download = row!.querySelector('a.file-tree-download');
expect(download).not.toBeNull();
const url = new URL(download!.getAttribute('href')!, 'http://localhost/');
expect(url.pathname).toBe('/api/sessions/sess-A/file-raw');
expect(url.searchParams.get('path')).toBe('src/visible.ts');
ui.app.activeSessionId = 'sess-B';
row!.click();
expect(ui.app.openFilePreview).toHaveBeenCalledWith('src/visible.ts', 'sess-A');
});
});
+46 -46
View File
@@ -1,5 +1,5 @@
/**
* @fileoverview File Viewer server-side search (COD-341).
* @fileoverview Explicit File Viewer workspace search (COD-341, Enter submission since #759).
*
* The browser module is loaded as the real CodemanApp mixin in a VM. The fake
* DOM intentionally implements only the element contract used by the File
@@ -332,7 +332,7 @@ function loadRealSelectSessionHarness(options: { terminalFailure?: boolean } = {
async function startSearch(app: Record<string, any>, query = 'widget') {
const input = app.$('fileBrowserSearch');
if (input) input.value = query;
app.filterFileBrowser(query);
app.searchFileBrowser(query);
await vi.advanceTimersByTimeAsync(250);
}
@@ -382,10 +382,10 @@ describe('File Viewer server search', () => {
vi.useRealTimers();
});
it('debounces for 250ms and encodes the owner and exact trimmed query', async () => {
it('debounces explicit workspace submissions and encodes the owner and exact trimmed query', async () => {
const { app, pending } = loadPanel();
app.filterFileBrowser('src & docs');
app.searchFileBrowser('src & docs');
await vi.advanceTimersByTimeAsync(249);
expect(pending).toHaveLength(0);
@@ -398,12 +398,12 @@ describe('File Viewer server search', () => {
it('is a safe no-op without a panel or session and can lazily adopt a later active owner', async () => {
const { app, elements, pending } = loadPanel({ sessionId: null });
app.filterFileBrowser('before-session');
app.searchFileBrowser('before-session');
await vi.advanceTimersByTimeAsync(250);
expect(pending).toHaveLength(0);
app.activeSessionId = 'session/B';
app.filterFileBrowser('after-session');
app.searchFileBrowser('after-session');
await vi.advanceTimersByTimeAsync(250);
expect(pending[0].url).toBe(
'/api/sessions/session%2FB/files?depth=5&showHidden=false&q=after-session&root=live-any'
@@ -414,7 +414,7 @@ describe('File Viewer server search', () => {
expect(elements.fileBrowserTree.innerHTML).toContain('No matches');
delete elements.fileBrowserPanel;
app.filterFileBrowser('without-panel');
app.searchFileBrowser('without-panel');
await vi.advanceTimersByTimeAsync(250);
expect(pending).toHaveLength(1);
});
@@ -424,34 +424,34 @@ describe('File Viewer server search', () => {
app._ensureFileBrowserState();
app.activeSessionId = null;
app.filterFileBrowser('missing-active');
app.searchFileBrowser('missing-active');
await vi.advanceTimersByTimeAsync(250);
expect(pending).toHaveLength(0);
expect(elements.fileBrowserTree.innerHTML).toBe('');
expect(app._fileBrowserState.inFlight).toBeNull();
app.activeSessionId = 'session/B';
app.filterFileBrowser('wrong-active');
app.searchFileBrowser('wrong-active');
await vi.advanceTimersByTimeAsync(250);
expect(pending).toHaveLength(0);
expect(elements.fileBrowserTree.innerHTML).toBe('');
expect(app._fileBrowserState.inFlight).toBeNull();
});
it('cancels the prior debounce and clears a deferred directory target on every input', async () => {
it('cancels the prior debounce and clears a deferred directory target on every submission', async () => {
const { app, pending } = loadPanel();
app._ensureFileBrowserState().deferredDirectoryTarget = {
ownerSessionId: 'session/A',
path: 'old-directory',
};
app.filterFileBrowser('first query');
app.searchFileBrowser('first query');
await vi.advanceTimersByTimeAsync(200);
app._fileBrowserState.deferredDirectoryTarget = {
ownerSessionId: 'session/A',
path: 'another-directory',
};
app.filterFileBrowser('second query');
app.searchFileBrowser('second query');
expect(app._fileBrowserState.deferredDirectoryTarget).toBeNull();
await vi.advanceTimersByTimeAsync(249);
@@ -583,9 +583,9 @@ describe('File Viewer server search', () => {
it('keeps query B rendered when its response beats an already-launched query A', async () => {
const { app, elements, pending } = loadPanel();
app.filterFileBrowser('query A');
app.searchFileBrowser('query A');
await vi.advanceTimersByTimeAsync(250);
app.filterFileBrowser('query B');
app.searchFileBrowser('query B');
await vi.advanceTimersByTimeAsync(250);
expect(pending).toHaveLength(2);
@@ -624,9 +624,9 @@ describe('File Viewer server search', () => {
truncated: false,
};
app.filterFileBrowser('cache');
app.searchFileBrowser('cache');
expect(elements.fileBrowserTree.innerHTML).toContain('Searching');
app.filterFileBrowser(' ');
app.searchFileBrowser(' ');
expect(pending).toHaveLength(0);
expect(elements.fileBrowserTree.innerHTML).toContain('cached.ts');
@@ -662,7 +662,7 @@ describe('File Viewer server search', () => {
it('accepts 256 trimmed characters', async () => {
const { app, pending } = loadPanel();
app.filterFileBrowser(` ${'x'.repeat(256)} `);
app.searchFileBrowser(` ${'x'.repeat(256)} `);
await vi.advanceTimersByTimeAsync(250);
@@ -672,7 +672,7 @@ describe('File Viewer server search', () => {
it('rejects 257 trimmed characters without a request', async () => {
const { app, elements, pending } = loadPanel();
app.filterFileBrowser('x'.repeat(257));
app.searchFileBrowser('x'.repeat(257));
await vi.advanceTimersByTimeAsync(1_000);
@@ -794,7 +794,7 @@ describe('File Viewer server search', () => {
expect(elements.fileBrowserTree.innerHTML).toContain('Loading files');
expect(elements.fileBrowserTree.innerHTML).not.toContain('old-result.ts');
expect(elements.fileBrowserTree.innerHTML).not.toContain('old-preference.ts');
expect(pending[1].url).toBe('/api/sessions/session%2FA/files?depth=5&showHidden=true&root=live-any');
expect(pending[1].url).toBe('/api/sessions/session%2FA/files?lazy=1&showHidden=true&root=live-any');
pending[1].reply.resolve(response(successfulTree('new-preference.ts')));
await toggle;
@@ -885,8 +885,8 @@ describe('File Viewer server search', () => {
const firstToggle = app.toggleFileBrowserHidden();
const secondToggle = app.toggleFileBrowserHidden();
expect(pending.slice(1).map(({ url }) => url)).toEqual([
'/api/sessions/session%2FA/files?depth=5&showHidden=true&root=live-any',
'/api/sessions/session%2FA/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FA/files?lazy=1&showHidden=true&root=live-any',
'/api/sessions/session%2FA/files?lazy=1&showHidden=false&root=live-any',
]);
pending[1].reply.resolve(response(successfulTree('stale-hidden.ts')));
@@ -923,7 +923,7 @@ describe('File Viewer server search', () => {
expect(pending).toHaveLength(2);
elements.fileBrowserSearch.value = '';
app.filterFileBrowser('');
app.searchFileBrowser('');
expect(elements.fileBrowserTree.innerHTML).toContain('&lt;img src=x onerror=boom&gt;');
});
@@ -947,7 +947,7 @@ describe('File Viewer server search', () => {
expect(elements.fileBrowserTree.innerHTML).toContain('newer.ts');
expect(app._fileBrowserState.normalState).toMatchObject({ phase: 'error', error: 'new preference failed' });
elements.fileBrowserSearch.value = '';
app.filterFileBrowser('');
app.searchFileBrowser('');
expect(elements.fileBrowserTree.innerHTML).toContain('new preference failed');
});
@@ -960,7 +960,7 @@ describe('File Viewer server search', () => {
const { app, elements, pending } = loadPanel();
const query = 'x'.repeat(257);
elements.fileBrowserSearch.value = query;
app.filterFileBrowser(query);
app.searchFileBrowser(query);
const message = elements.fileBrowserTree.innerHTML;
const beforeSearchEpoch = app._fileBrowserState.searchEpoch;
const beforeTreeEpoch = app._fileBrowserState.treeEpoch;
@@ -981,7 +981,7 @@ describe('File Viewer server search', () => {
expect(elements.fileBrowserTree.innerHTML).toBe(message);
expect(pending).toHaveLength(1);
elements.fileBrowserSearch.value = '';
app.filterFileBrowser('');
app.searchFileBrowser('');
if (fail) expect(elements.fileBrowserTree.innerHTML).toContain('hidden tree failed');
else expect(elements.fileBrowserTree.innerHTML).toContain('hidden-ready.ts');
}
@@ -1061,10 +1061,10 @@ describe('File Viewer server search', () => {
app.fileBrowserExpandedDirs.add('existing');
elements.fileBrowserExpandBtn.innerHTML = '\u229F';
elements.fileBrowserSearch.value = 'query';
app.filterFileBrowser('query');
app.searchFileBrowser('query');
elements.fileBrowserSearch.value = '';
app.filterFileBrowser('');
app.searchFileBrowser('');
expect(elements.fileBrowserExpandBtn.disabled).toBe(false);
expect(elements.fileBrowserExpandBtn.innerHTML).toBe('\u229F');
@@ -1230,7 +1230,7 @@ describe('File Viewer server search', () => {
expect(app._fileBrowserState.deferredDirectoryTarget).not.toBeNull();
elements.fileBrowserSearch.value = 'new query';
app.filterFileBrowser('new query');
app.searchFileBrowser('new query');
expect(app._fileBrowserState.deferredDirectoryTarget).toBeNull();
pending[0].reply.resolve(
response(successfulTree('unused', { tree: unixTree, totalFiles: 1, totalDirectories: 3 }))
@@ -1266,7 +1266,7 @@ describe('File Viewer server search', () => {
expect(app._fileBrowserState.normalState).toMatchObject({ phase: 'error', error: 'tree failed' });
elements.fileBrowserSearch.value = '';
app.filterFileBrowser('');
app.searchFileBrowser('');
expect(elements.fileBrowserTree.innerHTML).toContain('tree failed');
});
@@ -1424,10 +1424,10 @@ describe('File Viewer server search', () => {
expect(failed.elements.fileBrowserTree.innerHTML).toContain('&lt;img src=x onerror=boom&gt;');
});
it('refresh invalidates both work classes, clears navigation state, and forces an epoch-safe replacement', async () => {
it('refresh invalidates both work classes, preserves expansion, and forces an epoch-safe replacement', async () => {
const { app, elements, pending } = loadPanel();
const stale = app.loadFileBrowser('session/A');
app.filterFileBrowser('old query');
app.searchFileBrowser('old query');
app.fileBrowserExpandedDirs.add('src');
app.fileBrowserAllExpanded = true;
app._fileBrowserState.deferredDirectoryTarget = { ownerSessionId: 'session/A', path: 'src' };
@@ -1442,8 +1442,8 @@ describe('File Viewer server search', () => {
expect(app._fileBrowserState.matches).toEqual([]);
expect(app._fileBrowserState.deferredDirectoryTarget).toBeNull();
expect(app._fileBrowserState.view).toBe('normal');
expect(app.fileBrowserExpandedDirs.size).toBe(0);
expect(app.fileBrowserAllExpanded).toBe(false);
expect([...app.fileBrowserExpandedDirs]).toEqual(['src']);
expect(app.fileBrowserAllExpanded).toBe(true);
expect(elements.fileBrowserExpandBtn.disabled).toBe(false);
expect(elements.fileBrowserSearch.value).toBe('');
expect(elements.fileBrowserTree.innerHTML).toContain('Loading files');
@@ -1512,8 +1512,8 @@ describe('File Viewer server search', () => {
app._fileBrowserState.ownerSessionId = 'session/B';
app.activeSessionId = 'session/B';
const loadB = app.loadFileBrowser('session/B');
app.filterFileBrowser('temporary');
app.filterFileBrowser('');
app.searchFileBrowser('temporary');
app.searchFileBrowser('');
expect(elements.fileBrowserTree.innerHTML).toContain('Loading files');
expect(elements.fileBrowserTree.innerHTML).not.toContain('cached-A.ts');
@@ -1525,9 +1525,9 @@ describe('File Viewer server search', () => {
it('settles a compatible tree behind search without repainting and keeps tree/search epochs independent', async () => {
const { app, elements, pending } = loadPanel();
const treeLoad = app.loadFileBrowser('session/A');
app.filterFileBrowser('query A');
app.searchFileBrowser('query A');
await vi.advanceTimersByTimeAsync(250);
app.filterFileBrowser('query B');
app.searchFileBrowser('query B');
await vi.advanceTimersByTimeAsync(250);
expect(pending).toHaveLength(3);
@@ -1683,7 +1683,7 @@ describe('File Viewer server search', () => {
expect(immediateState.ownerSessionId).toBe('session/B');
expect(immediateState.resizeCalls).toBe(1);
expect(immediateState.fileUrls).toEqual([
'/api/sessions/session%2FB/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FB/files?lazy=1&showHidden=false&root=live-any',
]);
expect(filePending).toHaveLength(1);
@@ -1737,7 +1737,7 @@ describe('File Viewer server search', () => {
const { app, elements, pending } = loadPanel();
app.fileBrowserData = successfulTree('old-A.ts').data;
app.renderFileBrowserTree('session/A');
app.filterFileBrowser('old query');
app.searchFileBrowser('old query');
app.fileBrowserExpandedDirs.add('src');
app.fileBrowserAllExpanded = true;
app._fileBrowserState.deferredDirectoryTarget = { ownerSessionId: 'session/A', path: 'src' };
@@ -1766,7 +1766,7 @@ describe('File Viewer server search', () => {
expect(elements.fileBrowserTree.querySelectorAll('.file-tree-item')).toHaveLength(0);
expect(elements.fileBrowserTree.innerHTML).toContain('Loading files');
expect(pending.map(({ url }) => url)).toEqual([
'/api/sessions/session%2FB/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FB/files?lazy=1&showHidden=false&root=live-any',
]);
await vi.advanceTimersByTimeAsync(250);
@@ -1805,11 +1805,11 @@ describe('File Viewer server search', () => {
const { app, pending } = loadPanel();
app.activeSessionId = 'session/B';
app._activateFileBrowserSession('session/B');
app.filterFileBrowser('during load');
app.searchFileBrowser('during load');
await vi.advanceTimersByTimeAsync(250);
expect(pending.map(({ url }) => url)).toEqual([
'/api/sessions/session%2FB/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FB/files?lazy=1&showHidden=false&root=live-any',
'/api/sessions/session%2FB/files?depth=5&showHidden=false&q=during%20load&root=live-any',
]);
expect(pending.every(({ url }) => !url.includes('session%2FA'))).toBe(true);
@@ -1827,9 +1827,9 @@ describe('File Viewer server search', () => {
expect(secondA).not.toBe(firstA);
expect(pending.map(({ url }) => url)).toEqual([
'/api/sessions/session%2FA/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FB/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FA/files?depth=5&showHidden=false&root=live-any',
'/api/sessions/session%2FA/files?lazy=1&showHidden=false&root=live-any',
'/api/sessions/session%2FB/files?lazy=1&showHidden=false&root=live-any',
'/api/sessions/session%2FA/files?lazy=1&showHidden=false&root=live-any',
]);
pending[0].reply.resolve(response(successfulTree('stale-A.ts')));
@@ -1864,7 +1864,7 @@ describe('File Viewer server search', () => {
it('cancels an unlaunched debounce and clears all hide-reset controls and navigation state', async () => {
const { app, elements, pending } = loadPanel();
app.filterFileBrowser('not launched');
app.searchFileBrowser('not launched');
app.fileBrowserExpandedDirs.add('src');
app.fileBrowserAllExpanded = true;
app._fileBrowserState.matches = [{ name: 'old.ts' }];
+3 -1
View File
@@ -154,8 +154,10 @@ describe('Files panel in a git worktree', () => {
const { app, elements, server } = loadPanel();
server.worktree = WORKTREE;
await app.loadFileBrowser('sess-1');
app._fileBrowserState.filter = 'main';
elements.fileBrowserSearch.value = 'main';
app.searchFileBrowser('main');
await vi.waitFor(() => expect(server.requests.some((url) => url.includes('q=main'))).toBe(true));
server.requests.length = 0;
await app.toggleFileBrowserRoot();
await vi.waitFor(() => expect(server.requests.some((url) => url.includes('q=main'))).toBe(true));
+1 -1
View File
@@ -236,7 +236,7 @@ describe('deleteFileFromBrowser', () => {
});
await app.loadFileBrowser(SESSION);
(document.getElementById('fileBrowserSearch') as HTMLInputElement).value = 'me';
app.filterFileBrowser('me');
app.searchFileBrowser('me');
await vi.waitFor(() => expect(rowFor('src/delete-me.txt')).toBeTruthy());
expect(rowFor('src/other.md')).toBeUndefined();
+105 -6
View File
@@ -28,6 +28,15 @@ describe('File browser on a phone (issue #759)', () => {
await writeFile(join(workspace, 'README.md'), 'Phone browser fixture');
await writeFile(join(workspace, '.hidden.txt'), 'Hidden fixture');
await writeFile(join(workspace, 'src', 'note.txt'), 'Nested fixture');
await mkdir(join(workspace, 'src', 'deep'), { recursive: true });
await writeFile(join(workspace, 'src', 'deep', 'needle.ts'), 'Deep fixture');
await mkdir(join(workspace, 'bulk'));
await mkdir(join(workspace, 'unavailable'));
await Promise.all(
Array.from({ length: 501 }, (_, index) =>
writeFile(join(workspace, 'bulk', `entry-${String(index).padStart(4, '0')}.txt`), 'x')
)
);
server = await createTestServer();
baseUrl = `http://localhost:${server.boundPort}`;
const response = await fetch(`${baseUrl}/api/sessions`, {
@@ -70,16 +79,17 @@ describe('File browser on a phone (issue #759)', () => {
});
async function saveSetting(id: string, checked: boolean) {
await page.locator('.btn-settings-mobile').tap();
const mobileSettings = page.locator('.btn-settings-mobile');
const opener = (await mobileSettings.isVisible()) ? mobileSettings : page.locator('.btn-settings');
await opener.click();
const control = page.locator(`#${id}`);
// The chip's native checkbox is visually hidden; the label is the touch target.
if ((await control.isChecked()) !== checked) {
await page.locator(`label:has(#${id})`).tap();
await page.locator(`label:has(#${id})`).click();
}
await page
.locator('#appSettingsModal .set-head-save')
.filter({ hasText: /^Save$/ })
.tap();
const headSave = page.locator('#appSettingsModal .set-head-save').filter({ hasText: /^Save$/ });
const save = (await headSave.isVisible()) ? headSave : page.locator('#appSettingsModal .set-foot .btn-primary');
await save.click();
await expect.poll(() => page.locator('#appSettingsModal').isVisible()).toBe(false);
}
@@ -166,6 +176,8 @@ describe('File browser on a phone (issue #759)', () => {
}
await panel.locator('#fileBrowserExpandBtn').tap();
expect(await tree.locator('[data-path="src/note.txt"]').count()).toBe(0);
await tree.locator('[data-path="src"]').tap();
await tree.locator('[data-path="src/note.txt"]').waitFor({ state: 'visible' });
await panel.locator('#fileBrowserHiddenBtn').tap();
await tree.locator('[data-path=".hidden.txt"]').waitFor({ state: 'visible' });
@@ -178,4 +190,91 @@ describe('File browser on a phone (issue #759)', () => {
await panel.locator('button[title="Close"]').tap();
await expect.poll(() => panel.isVisible()).toBe(false);
});
it.each(['phone', 'desktop'])(
'loads folders and pages on demand and reveals a workspace-search folder on %s',
async (device) => {
const activate = (control: Locator) => (device === 'phone' ? control.tap() : control.click());
if (device === 'desktop') {
await context.close();
({ context, page } = await createDevicePage(
{
...REPRESENTATIVE_DEVICES['standard-phone'],
viewport: { width: 1280, height: 900 },
deviceScaleFactor: 1,
isMobile: false,
hasTouch: false,
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
},
baseUrl,
'chromium'
));
await page.waitForFunction((id) => (window as any).app?.sessions.has(id), sessionId);
await page.evaluate(async (id) => (window as any).app.selectSession(id), sessionId);
}
// The desktop may restore the panel from synced settings saved by the phone cases.
// Start this request-count assertion from an explicit close/open on either device.
const panel = page.locator('#fileBrowserPanel');
if (await panel.isVisible()) {
await activate(panel.locator('button[title="Close"]'));
await expect.poll(() => panel.isVisible()).toBe(false);
}
const requests: URL[] = [];
page.on('request', (request) => {
const url = new URL(request.url());
if (request.method() === 'GET' && url.pathname.endsWith(`/sessions/${sessionId}/files`)) requests.push(url);
});
await saveSetting('appSettingsShowFileBrowser', true);
const tree = panel.locator('#fileBrowserTree');
await tree.locator('[data-path="README.md"]').waitFor({ state: 'visible' });
expect(requests).toHaveLength(1);
expect(requests[0].searchParams.get('lazy')).toBe('1');
const input = panel.locator('#fileBrowserSearch');
await input.fill('deep');
await page.waitForTimeout(350); // Outwait the former automatic server-search debounce.
expect(requests).toHaveLength(1);
await input.press('Enter');
await tree.locator('[data-path="src/deep"]').waitFor({ state: 'visible' });
expect(requests.at(-1)!.searchParams.get('q')).toBe('deep');
await activate(tree.locator('[data-path="src/deep"]'));
await tree.locator('[data-path="src/deep/needle.ts"]').waitFor({ state: 'visible' });
expect(await input.inputValue()).toBe('');
expect(requests.filter((url) => url.searchParams.has('path')).map((url) => url.searchParams.get('path'))).toEqual(
['src', 'src/deep']
);
await activate(tree.locator('[data-path="bulk"]'));
const more = tree.locator('[data-file-browser-load="more"]');
await more.waitFor({ state: 'visible' });
if (device === 'phone') await assertTouchTarget(more);
expect(await tree.locator('[data-path^="bulk/"][data-type="file"]').count()).toBe(500);
await activate(more);
await expect.poll(() => tree.locator('[data-path^="bulk/"][data-type="file"]').count()).toBe(501);
expect(await more.count()).toBe(0);
expect(requests.at(-1)!.searchParams.get('cursor')).toBeTruthy();
expect(await tree.locator('[data-path="src/deep/needle.ts"]').isVisible()).toBe(true);
const unavailable = (url: URL) =>
url.pathname.endsWith(`/sessions/${sessionId}/files`) && url.searchParams.get('path') === 'unavailable';
await page.route(unavailable, (route) =>
route.fulfill({
status: 503,
contentType: 'application/json',
body: JSON.stringify({ success: false, error: 'Folder unavailable; retry or refresh files' }),
})
);
await activate(tree.locator('[data-path="unavailable"]'));
const retry = tree.locator('[data-file-browser-load="retry"]');
await retry.waitFor({ state: 'visible' });
await retry.scrollIntoViewIfNeeded();
await expectReachable(retry);
if (device === 'phone') await assertTouchTarget(retry);
await page.unroute(unavailable);
await activate(retry);
await expect.poll(() => retry.count()).toBe(0);
expect(await tree.locator('[data-path="src/deep/needle.ts"]').isVisible()).toBe(true);
}
);
});
+330
View File
@@ -0,0 +1,330 @@
/**
* @fileoverview Issue #759: opt-in, one-directory Files panel listings.
*
* Real folders exercise the shipped route, confinement, exclusions and continuation. Spies are
* limited to proving that a listing never opens descendants, and to simulating an unreachable
* mount (which a real fixture cannot do). No ports, real sessions or production HOME are used.
*
* Additive wire contract: lazy=1, optional path and opaque cursor; data.tree contains
* immediate children, directories omit children until loaded, and nextCursor is present only
* while another page remains (null/absent both mean finished). Page size is deliberately not
* prescribed here, apart from staying within the existing 5,000-entry response budget.
*/
import { mkdirSync, mkdtempSync, realpathSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';
import fs from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { safeRmHomeTree } from '../mocks/index.js';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
import * as pathProbe from '../../src/utils/bounded-path-probe.js';
interface Entry {
name: string;
path: string;
type: 'file' | 'directory';
children?: Entry[];
}
describe('Files panel directory-at-a-time route (#759)', () => {
let harness: RouteTestHarness;
let fixture: string;
let repo: string;
let outside: string;
beforeEach(async () => {
harness = await createRouteTestHarness(registerFileRoutes);
fixture = realpathSync(mkdtempSync(join(homedir(), 'files-lazy-')));
repo = join(fixture, 'repo');
outside = join(fixture, 'outside');
mkdirSync(join(repo, 'src', 'deep'), { recursive: true });
mkdirSync(join(repo, 'empty'));
mkdirSync(join(repo, '.config'));
mkdirSync(outside);
writeFileSync(join(repo, 'README.md'), 'readme');
writeFileSync(join(repo, '.env'), 'hidden');
writeFileSync(join(repo, '.config', 'prefs.json'), '{}');
writeFileSync(join(repo, 'src', 'visible.ts'), 'visible');
writeFileSync(join(repo, 'src', 'deep', 'needle.ts'), 'needle');
writeFileSync(join(outside, 'secret.txt'), 'secret');
harness.ctx._session.workingDir = repo;
});
afterEach(async () => {
vi.restoreAllMocks();
await harness.app.close();
safeRmHomeTree(fixture);
});
const request = (query: Record<string, string> = {}) =>
harness.app.inject({
method: 'GET',
url: `/api/sessions/${harness.ctx._sessionId}/files?${new URLSearchParams(query)}`,
});
const list = async (query: Record<string, string> = {}) => {
const res = await request({ lazy: '1', ...query });
expect(res.statusCode).toBe(200);
expect(res.json().success).toBe(true);
return res.json().data;
};
const paths = (entries: Entry[]) => entries.map((entry) => entry.path);
it('returns every ordinary root entry without opening or embedding descendants', async () => {
const reads = vi.spyOn(fs, 'readdir');
const data = await list();
expect(paths(data.tree)).toEqual(['empty', 'src', 'README.md']);
expect(data.root).toBe(repo);
expect(data.lazy).toBe(true);
expect(data.truncated).toBe(false);
expect(data.nextCursor ?? null).toBeNull();
for (const node of data.tree.filter((entry: Entry) => entry.type === 'directory')) {
expect(node).not.toHaveProperty('children');
}
expect(reads.mock.calls.map(([path]) => String(path))).toEqual([repo]);
});
it('loads just the requested folder and keeps paths usable by the existing preview', async () => {
const reads = vi.spyOn(fs, 'readdir');
const data = await list({ path: 'src' });
expect(paths(data.tree)).toEqual(['src/deep', 'src/visible.ts']);
expect(data.tree[0]).not.toHaveProperty('children');
expect(reads.mock.calls.map(([path]) => String(path))).toEqual([join(repo, 'src')]);
const preview = await harness.app.inject({
method: 'GET',
url: `/api/sessions/${harness.ctx._sessionId}/file-content?path=src%2Fvisible.ts`,
});
expect(preview.json().data.content).toBe('visible');
});
it('preserves a workspace file link as a legacy file row and previews its returned path', async () => {
symlinkSync(join(repo, 'README.md'), join(repo, 'AGENTS.md'));
const legacy = (await request()).json().data.tree.find((entry: Entry) => entry.path === 'AGENTS.md');
const lazy = (await list()).tree.find((entry: Entry) => entry.path === 'AGENTS.md');
expect(legacy).toMatchObject({ name: 'AGENTS.md', path: 'AGENTS.md', type: 'file' });
expect(lazy).toEqual(legacy);
const preview = await harness.app.inject({
method: 'GET',
url: `/api/sessions/${harness.ctx._sessionId}/file-content?path=${encodeURIComponent(lazy.path)}`,
});
expect(preview.statusCode).toBe(200);
expect(preview.json().data.content).toBe('readme');
});
it('keeps directory links and dangling links as legacy leaves without traversing them', async () => {
symlinkSync(join(repo, 'src'), join(repo, 'folder-link'));
symlinkSync(join(repo, 'missing.md'), join(repo, 'dangling.md'));
const legacy = (await request()).json().data.tree;
const reads = vi.spyOn(fs, 'readdir');
const data = await list();
for (const path of ['folder-link', 'dangling.md']) {
const row = data.tree.find((entry: Entry) => entry.path === path);
expect(row).toEqual(legacy.find((entry: Entry) => entry.path === path));
expect(row).toMatchObject({ type: 'file' });
expect(row).not.toHaveProperty('children');
}
expect(reads.mock.calls.map(([path]) => String(path))).toEqual([repo]);
});
it('distinguishes a successfully loaded empty folder from an unloaded one', async () => {
const data = await list({ path: 'empty' });
expect(data.tree).toEqual([]);
expect(data.truncated).toBe(false);
expect(data.nextCursor ?? null).toBeNull();
});
it('has no accumulated depth budget across successive folder expansions', async () => {
const deep = Array.from({ length: 12 }, (_, index) => `level-${index}`).join('/');
mkdirSync(join(repo, deep), { recursive: true });
writeFileSync(join(repo, deep, 'bottom.txt'), 'bottom');
const data = await list({ path: deep });
expect(paths(data.tree)).toEqual([`${deep}/bottom.txt`]);
expect(data.truncated).toBe(false);
});
it('adds hidden entries alongside visible entries at the root and below it', async () => {
expect(paths((await list()).tree)).toEqual(['empty', 'src', 'README.md']);
expect(paths((await list({ showHidden: 'true' })).tree)).toEqual(['.config', 'empty', 'src', '.env', 'README.md']);
writeFileSync(join(repo, 'src', '.hidden.ts'), 'hidden');
expect(paths((await list({ path: 'src', showHidden: 'true' })).tree)).toEqual([
'src/deep',
'src/.hidden.ts',
'src/visible.ts',
]);
});
it('requires the hidden preference to open a hidden path segment', async () => {
const denied = await request({ lazy: '1', path: '.config' });
expect(denied.statusCode).toBe(403);
expect(denied.json().success).toBe(false);
expect(paths((await list({ path: '.config', showHidden: 'true' })).tree)).toEqual(['.config/prefs.json']);
});
it('preserves generated-directory exclusions even when hidden files are enabled', async () => {
for (const name of ['.git', 'node_modules', 'dist', 'build', 'coverage']) {
mkdirSync(join(repo, name));
writeFileSync(join(repo, name, 'excluded.txt'), 'excluded');
}
const data = await list({ showHidden: 'true' });
expect(paths(data.tree)).toEqual(['.config', 'empty', 'src', '.env', 'README.md']);
});
it.each(['../outside', '/etc', 'src/../../outside'])(
'refuses a requested directory outside the session: %s',
async (path) => {
const res = await request({ lazy: '1', path, showHidden: 'true' });
expect(res.statusCode).toBe(403);
expect(res.json().success).toBe(false);
expect(res.body).not.toContain('secret.txt');
}
);
it('refuses a directory symlink escaping the workspace', async () => {
symlinkSync(outside, join(repo, 'escape'));
const res = await request({ lazy: '1', path: 'escape' });
expect(res.statusCode).toBe(403);
expect(res.json().success).toBe(false);
});
it.each(['missing', 'README.md'])('does not report %s as an empty directory', async (path) => {
const res = await request({ lazy: '1', path });
expect(res.statusCode).toBe(path === 'missing' ? 404 : 400);
expect(res.json().success).toBe(false);
});
it('probes a requested subfolder before readdir and never opens an unreachable folder', async () => {
const target = join(repo, 'src');
const realProbe = pathProbe.probePathKind;
vi.spyOn(pathProbe, 'probePathKind').mockImplementation((path, options) =>
path === target ? Promise.resolve('unknown') : realProbe(path, options)
);
const reads = vi.spyOn(fs, 'readdir');
const res = await request({ lazy: '1', path: 'src' });
expect(res.statusCode).toBe(422);
expect(res.json().success).toBe(false);
expect(vi.mocked(pathProbe.probePathKind).mock.calls.some(([path]) => path === target)).toBe(true);
expect(reads.mock.calls.map(([path]) => String(path))).not.toContain(target);
});
it.each(['', 'bulk'])('paginates an oversized %s directory without losing or repeating entries', async (path) => {
const folder = path ? join(repo, path) : repo;
if (path) mkdirSync(folder);
const expected = Array.from({ length: 5105 }, (_, index) => `item-${String(index).padStart(5, '0')}.txt`);
for (const name of expected) writeFileSync(join(folder, name), '');
const seen: string[] = [];
const cursors = new Set<string>();
let cursor: string | undefined;
do {
const data = await list({ ...(path && { path }), ...(cursor && { cursor }) });
expect(data.tree.length).toBeGreaterThan(0);
expect(data.tree.length).toBeLessThanOrEqual(500);
seen.push(...paths(data.tree));
cursor = data.nextCursor ?? undefined;
expect(data.truncated).toBe(Boolean(cursor));
if (cursor) {
expect(typeof cursor).toBe('string');
expect(cursors.has(cursor)).toBe(false);
cursors.add(cursor);
expect(cursors.size).toBeLessThan(100);
}
} while (cursor);
expect(cursors.size).toBeGreaterThan(0);
expect(new Set(seen).size).toBe(seen.length);
const wanted = expected.map((name) => (path ? `${path}/${name}` : name));
expect(seen.filter((entry) => entry.includes('item-')).sort()).toEqual(wanted);
expect(paths((await list({ path: 'src/deep' })).tree)).toEqual(['src/deep/needle.ts']);
});
it('rejects a malformed continuation rather than silently restarting at page one', async () => {
const res = await request({ lazy: '1', cursor: 'not-a-valid-cursor' });
expect(res.statusCode).toBe(400);
expect(res.json().success).toBe(false);
});
it('refuses to reuse a continuation for a different folder or hidden-files preference', async () => {
for (let index = 0; index < 501; index++) writeFileSync(join(repo, `item-${index}.txt`), '');
const { nextCursor } = await list();
expect(nextCursor).toBeTypeOf('string');
for (const changed of [{ path: 'src' }, { showHidden: 'true' }]) {
const res = await request({ lazy: '1', cursor: nextCursor, ...changed });
expect(res.statusCode).toBe(400);
expect(res.json().success).toBe(false);
}
});
it('keeps existing non-lazy response bytes and search behavior unchanged', async () => {
const legacy = await request();
expect(legacy.body).toBe(
JSON.stringify({
success: true,
data: {
root: repo,
tree: [
{ name: 'empty', path: 'empty', type: 'directory', children: [] },
{
name: 'src',
path: 'src',
type: 'directory',
children: [
{
name: 'deep',
path: 'src/deep',
type: 'directory',
children: [{ name: 'needle.ts', path: 'src/deep/needle.ts', type: 'file', size: 6, extension: 'ts' }],
},
{ name: 'visible.ts', path: 'src/visible.ts', type: 'file', size: 7, extension: 'ts' },
],
},
{ name: 'README.md', path: 'README.md', type: 'file', size: 6, extension: 'md' },
],
totalFiles: 3,
totalDirectories: 3,
truncated: false,
},
})
);
await list({ path: 'src' });
expect((await request()).body).toBe(legacy.body);
expect((await request({ lazy: '0' })).body).toBe(legacy.body);
const search = await request({ q: 'needle' });
expect(search.json().data.mode).toBe('search');
expect(paths(search.json().data.matches)).toEqual(['src/deep/needle.ts']);
});
it.each(['live', 'live-any'])('preserves inside-worktree paths for root=%s', async (root) => {
const prefix = '.claude/worktrees/feature';
const worktree = join(repo, prefix);
mkdirSync(join(worktree, 'src'), { recursive: true });
writeFileSync(join(worktree, 'src', 'feature.ts'), 'feature');
harness.ctx._session.liveWorktree = { name: 'feature', path: worktree };
const data = await list({ root });
expect(data.root).toBe(worktree);
expect(data.worktree).toEqual({ name: 'feature', path: worktree });
expect(paths(data.tree)).toEqual([`${prefix}/src`]);
expect(paths((await list({ root, path: `${prefix}/src` })).tree)).toEqual([`${prefix}/src/feature.ts`]);
});
it('keeps outside-worktree paths absolute only with root=live-any', async () => {
mkdirSync(join(outside, 'src'));
writeFileSync(join(outside, 'src', 'feature.ts'), 'feature');
harness.ctx._session.liveWorktree = { name: 'feature', path: outside, outside: true };
const data = await list({ root: 'live-any' });
expect(data.root).toBe(outside);
expect(data.worktree).toEqual({ name: 'feature', path: outside, outside: true });
expect(paths(data.tree)).toEqual([join(outside, 'src'), join(outside, 'secret.txt')]);
expect(paths((await list({ root: 'live-any', path: join(outside, 'src') })).tree)).toEqual([
join(outside, 'src', 'feature.ts'),
]);
expect(paths((await list({ root: 'live' })).tree)).toEqual(['empty', 'src', 'README.md']);
expect(paths((await list()).tree)).toEqual(['empty', 'src', 'README.md']);
});
it('rechecks an outside worktree replaced by a symlink before loading its children', async () => {
harness.ctx._session.liveWorktree = { name: 'feature', path: outside, outside: true };
renameSync(outside, `${outside}-moved`);
symlinkSync(repo, outside);
const res = await request({ lazy: '1', root: 'live-any', path: outside });
expect(res.statusCode).toBe(403);
expect(res.json().success).toBe(false);
});
});