fix(editor): open a directory target as the folder window (#1029)

A path that resolves to a directory (a chat folder link, a sidebar_open
folder, or a directory pasted into the editor address bar) was read as a
file: the host answered 400 fs-error '"<path>" is a directory' and
EditorHost painted that raw message into the tab instead of the plugin's
folder window.

- fs.read / fs.readPage now answer a directory with the dedicated
  fs-directory wire code (src/wire.ts, readText/readPage).
- EditorHost promotes the tab to the folder window it already draws.
- The promoted root is a PLATFORM-NATIVE ABSOLUTE path, resolved against
  the session workspace root by the new resolveNativeSidebarPath helper
  (paths.ts): chat file addresses carry session-relative, forward-slash
  spellings, while the host keys every listing by its path.resolve'd
  absolute path and FileTree caches levels by the requested root. A
  relative root or a mixed-separator root lands in another cache key and
  the tree sits on its loading placeholder forever. The helper also drops
  a trailing separator (except a drive root) like path.resolve does.
- The fix covers all three entry points at once: conversation folder
  links (no meta.dir on the tab), sidebar_open folders (service.openTab
  drops the seed meta on the native resource route), and #933's
  pasted/stepped directory path.

Tests: isDirectoryReadError unit cases, the EditorHost relative-path and
Windows-root fallback render cases, resolveNativeSidebarPath win32/POSIX
cases, and the fs.readPage directory code. typecheck + build + lint pass;
targeted suites 78/78; the full suite's remaining failures reproduce on a
clean dev checkout (Windows symlink / pnpm pack / git smokes) and are
unrelated to this change. Verified in the live GUI: a folder opened after
the patch expands its tree immediately.
This commit is contained in:
NeedsTree committed 2026-10-22 17:58:10 +08:00
1 parent 0fab0afdbb
commit b4e9924982
12 files changed
+190 -9

No files matched your search

+4
View File
@@ -2,6 +2,10 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### Unreleased
- **目录目标不再按文件读取**([#1029](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1029),同一根因覆盖 [#933](https://github.com/omdsh-dev/DSH-better-sidebar/issues/933)):打开路径是文件夹时(会话里的目录链接、`sidebar_open` 目录、编辑器地址栏粘贴目录),`fs.read` / `fs.readPage` 返回专用错误码 `fs-directory`;`EditorHost` 捕获后把当前页签升级为文件夹窗口(`meta.dir: true` + 文件树),不再把原始 `"…" is a directory` 错误画成页签内容。升级时先把相对目标按会话工作区解析成**平台原生绝对路径**(Windows 分隔符规整、去尾部分隔符,见 `resolveNativeSidebarPath`)再作为文件夹根——host 返回的层级路径是 `path.resolve` 后的绝对路径,而 FileTree 按请求的根路径缓存层级;根是相对路径或混合斜杠时两者键不一致,文件树会永远停在「加载中」占位。
### v0.28.0
- **正式版支持线前移到 DSH 0.2.1-rc.1+**:13 条 DSH peer 下限统一为 `^0.2.1-rc.1`,开发依赖、CI 与安装脚本使用精确 RC 基线。不新增运行时兼容层、不改功能实现。
+4
View File
@@ -4,6 +4,10 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### Unreleased
- **A directory target is no longer read as a file** ([#1029](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1029); same root cause also covers [#933](https://github.com/omdsh-dev/DSH-better-sidebar/issues/933)): when the opened path is a folder (a chat folder link, a `sidebar_open` folder, a directory pasted into the editor address bar), `fs.read` / `fs.readPage` answer with the dedicated `fs-directory` code; `EditorHost` turns the tab into the folder window (`meta.dir: true` + file tree) instead of painting the raw `"…" is a directory` host error into the tab. The promotion resolves a relative target against the session workspace root first and normalizes it to the platform-native spelling (`resolveNativeSidebarPath`: separator dialect + no trailing separator): listing answers are keyed by the host's `path.resolve`'d absolute path while FileTree caches levels by the requested root, so a relative or mixed-separator root would sit on its loading placeholder forever.
### v0.28.0
- **Stable plugin support moves to DSH 0.2.1-rc.1+**: all 13 DSH peer floors are `^0.2.1-rc.1`; development dependencies, CI and installers pin the exact RC baseline. No runtime compatibility layer or feature implementation changes are introduced.
+1 -1
View File
@@ -1263,7 +1263,7 @@ better-sidebar 的内置 tab 和 viewer 就是参考实现("吃狗粮"),
- **`src/client/plugins-tabs.ts`** / **`plugins-viewers.ts`**:推荐插件目录(「添加插件」弹窗数据源;加一条数据即上架,`tests/plugin-list.spec.ts` 守护)
- **`src/client/FileTree.tsx`** / **`TreePanel.tsx`** / **`src/fs-search.ts`** / **`src/search-engines.ts`**:文件树 / 树面板 / host 文件搜索(`fs.search`)。查询分三态(#879):**普通名字**走引擎链——优先探测本机 fd / rg(DSH 自带 ripgrep 优先),缺失或运行失败回退 JS 遍历,两条路径共用同一份 `exclude` 探针(引擎侧是输出后置过滤:匹配条目不出现、被排除目录不下钻);**带分隔符的相对片段**(如 `records/exp1`,名字永不包含分隔符)由 JS 遍历按根相对路径匹配、不进引擎;**指名单一目标的查询**(绝对路径、`~/…`、`./x`、`../x`)经 `resolveTarget`(与 fs.read 同一解析原语:`~` 展开、会话 cwd 拼接、win32 WSL/dsh-remote 命名空间改写、词法 resolve)stat 直取,命中返回解析后的绝对路径、目标缺失立即空结果(不烧遍历预算,exclude 不作用于显式路径意图)。`dirs` 让目录命中行导航文件树而不是当文件打开;调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,缺省 `~/.dsh`。host 的 `listDirectory` 给目录行标记 `compact`(仅一个非 symlink 有效子项;POSIX 隐藏与 `explorerExclude` 排除条目不计入),client 的 `file-tree-compact.ts` 把单目录链折叠成 `a/b/c` 面包屑行并整链展开/折叠;`explorerExclude`(VS Code `files.exclude` 风格 glob 子集,见 `exclude-patterns.ts`;editor 卡片的声明式 patterns 行可编辑)把匹配条目从树与搜索中彻底移除,两个界面共用同一 host 侧编译好的 matcher;host 侧目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键。测试:`tests/fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `fs-tree-exclude.spec.ts` / `exclude-patterns.spec.ts` / `fs-search.spec.ts` / `search-engines.spec.ts`
- **`src/client/markdown-html.ts`** / **`MarkdownHtml.tsx`** / **`md-toc.tsx`**:markdown 内嵌 HTML 管线与目录大纲(注意 `md-toc.tsx` 头注释的「子组件读父 ref 为 null」时序陷阱)
- **`src/agent-opens.ts`** / **`/sidebar/ws/agent-opens`**:模型主动打开(`sidebar_open` 工具 + `agentOpenTools` 设置,默认关闭);文件夹窗口 = `meta.dir: true` 的 editor tab([设计文档](plans/2026-08-23-agent-open-tools-design.md))
- **`src/agent-opens.ts`** / **`/sidebar/ws/agent-opens`**:模型主动打开(`sidebar_open` 工具 + `agentOpenTools` 设置,默认关闭);文件夹窗口 = `meta.dir: true` 的 editor tab([设计文档](plans/2026-08-23-agent-open-tools-design.md))。文件夹窗口的 `path` 必须是**平台原生绝对路径**(`resolveNativeSidebarPath`):`FileTree` 按请求的根路径缓存层级,host 返回的是 `path.resolve` 后的绝对路径,相对路径或混合斜杠会让树永远停在「加载中」
- **`tests/service.spec.ts`** / **`tests/builtins.spec.ts`**:注册表生命周期 / 匹配算法 / dedupe / createTab / 启用态 gating;内置清单断言(6 tab + 3 viewer + 声明式元数据,并显式断言 image / pdf / binary-download **不在**内置清单里、但作为公开契约仍可被第三方注册)
- **`src/fs-watch.ts`** / **`src/client/use-dir-watch.ts`**:文件树实时刷新(按展开目录 watch,150ms 去抖、每连接 64 个句柄上限;`tests/fs-watch.spec.ts` 守护)
- **`docs/plans/`**:逐特性设计文档(含实施偏差记录,以现状为准);入口如 `2026-08-11-service-registry-design.md` / `2026-08-11-declarative-sidebar-settings-design.md`
+30 -2
View File
@@ -29,7 +29,7 @@ import { IconCheckOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegul
import type { Context } from '../context-types.ts'
import { api, mediaUrl, type SessionScope } from './api.ts'
import { BinaryDownload } from './binary-download.tsx'
import { planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts'
import { isDirectoryReadError, planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts'
import { clearEditorDirty, setEditorDirty } from './editor-dirty.ts'
import { baseName } from './FileTree.tsx'
import { createFrameBatcher } from './frame-batcher.ts'
@@ -41,7 +41,7 @@ import { createOpenInApp } from './open-in-app.ts'
import { TreePanel } from './TreePanel.tsx'
import { t } from './locales.ts'
import { relativeTo } from './paths.ts'
import { resolveSidebarPath } from './paths.ts'
import { resolveNativeSidebarPath, resolveSidebarPath } from './paths.ts'
import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from './tree-mutations.ts'
import type { EditorToolbarControls, EditorToolbarState, FileViewerDescriptor } from './service.ts'
import { firstLeaf, insertLeafAt, leafWithTab, mintTabId, type SidebarStore, type SidebarTab } from './state.ts'
@@ -472,6 +472,34 @@ export function EditorHost(props: {
else apply(outcome)
}).catch((error: unknown) => {
if (cancelled) return
if (isDirectoryReadError(error)) {
// A path that resolves to a DIRECTORY is not a failed read: the
// editor tab must become the plugin's folder window instead of
// showing the host's raw `"<path>" is a directory`. This is the
// path a chat folder link takes (the tab carries no meta.dir), a
// `sidebar_open` folder takes when its seed meta was dropped on the
// native resource route, and a directory pasted into this tab's
// address bar takes (#933 / #1029).
//
// The root MUST be the platform-native absolute path: every
// listing answer is keyed by the host's `path.resolve`'d spelling,
// while FileTree keys its level cache by the REQUESTED root path.
// A session-relative, forward-slash-only root (the chat address
// spelling) therefore lands in another cache key and the tree
// stays on its loading placeholder forever. `ctx.sessions` carries
// the workspace root the file address grammar is relative to;
// scope.cwd is the fallback (a stripped ctx may not expose the
// list). `resolveNativeSidebarPath` also normalizes separators to
// that root's dialect (#1029 follow-up).
const sessionCwd = ctx.sessions?.list?.getSnapshot?.()?.byId?.[scope.sessionId]?.cwd ?? scope.cwd
const absolute = resolveNativeSidebarPath(sessionCwd, path)
ctx.get('betterSidebar')?.updateTab(tab.id, {
path: absolute,
title: baseName(absolute),
meta: { ...metaOf(tab), dir: true },
}, scope.sessionId)
return
}
setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) })
})
return
+17
View File
@@ -14,6 +14,23 @@
*/
import type { FileViewerDescriptor } from './service.ts'
/**
* Whether one `fs.read` failure means the target is a DIRECTORY.
*
* The host answers a directory with the dedicated `fs-directory` wire code
* (`readText` in src/index.ts). That answer is not an error to show: the
* editor host promotes the tab to the plugin's folder window instead, so a
* chat folder link, a `sidebar_open` folder open whose seed lost `meta.dir`,
* and a directory pasted into the address bar all land on the tree. The test
* is structural on purpose — the jsdom fixtures model the wire error as a
* plain `{ code, message }` object, and the code is the whole contract.
*/
export function isDirectoryReadError(error: unknown): boolean {
return typeof error === 'object'
&& error !== null
&& (error as { code?: unknown }).code === 'fs-directory'
}
/** One host fs.read result (mirror of the wire; `head` present when binary
* or when the file was too large to hand over as a document). */
export type FsReadOutcome =
+22
View File
@@ -120,3 +120,25 @@ export function resolveSidebarPath(cwd: string | undefined, path: string): strin
const separator = base.includes('\\') ? '\\' : '/'
return `${base.replace(/[\\/]+$/, '')}${separator}${path}`
}
/**
* Resolve one client path and normalize it to the base's separator dialect.
*
* A folder window roots the shared FileTree at this value. The tree keys each
* level by the root it REQUESTED, while every listing answer is keyed by the
* host's `path.resolve`'d absolute path — on Windows a chat file address
* ("research/workspace-sections-campaign/x", session-relative and
* `/`-separated) joined onto a `C:\…` cwd used to leave MIXED separators: two
* different strings for one directory, so the root level waited on its
* loading placeholder forever (#1029 follow-up). Normalizing to the base's
* dialect also drops a trailing separator, exactly as `path.resolve` does
* (a drive root keeps it). A non-Windows base returns the plain join: on
* POSIX a backslash is a legal filename character.
*/
export function resolveNativeSidebarPath(cwd: string | undefined, path: string): string {
const resolved = resolveSidebarPath(cwd, path)
if (cwd === undefined || !cwd.includes('\\')) return resolved
const normalized = resolved.replace(/\//g, '\\')
if (/^[A-Za-z]:\\$/.test(normalized)) return normalized
return normalized.replace(/\\+$/, '')
}
+5 -2
View File
@@ -444,7 +444,10 @@ async function readText(path: string): Promise<SidebarReadResult> {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
if (info.isDirectory()) {
throw new SidebarError('fs-error', `"${path}" is a directory`, 400)
// A dedicated code, not a generic fs failure: the client promotes the tab
// to the plugin's folder window instead of rendering this as an error (a
// chat folder link, a sidebar_open folder, a pasted directory path).
throw new SidebarError('fs-directory', `"${path}" is a directory`, 400)
}
const size = info.size
const oversized = size > MAX_EDITABLE_BYTES
@@ -530,7 +533,7 @@ async function readPage(path: string, offset: number): Promise<ReadPageResult> {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
if (info.isDirectory()) {
throw new SidebarError('fs-error', `"${path}" is a directory`, 400)
throw new SidebarError('fs-directory', `"${path}" is a directory`, 400)
}
const size = info.size
if (offset >= size) {
+1
View File
@@ -19,6 +19,7 @@ export type SidebarErrorCode =
| 'too-large'
| 'unavailable'
| 'fs-error'
| 'fs-directory'
| 'fs-conflict'
| 'git-error'
| 'graph-stale'
+70
View File
@@ -651,6 +651,76 @@ describe('EditorHost (files window)', () => {
}
})
it('a directory opened as a file falls back to the folder window (#1029)', async () => {
const { store, ctx } = setup()
const service = ctx.betterSidebar
// The chat file-link route and the native sidebar_open route can hand the
// editor a DIRECTORY path with no meta.dir (issue #1029). The host answers
// the fs.read with its dedicated directory code; the tab must promote
// itself to the folder window instead of rendering the raw host error.
// The source path is RELATIVE on purpose: that is the spelling a chat link
// carries. A promotion that roots the tree at that relative path lists the
// level under the host-resolved ABSOLUTE key, so the root would sit on its
// loading placeholder forever — the promotion must absolutize first.
service.registerFileViewer({ id: 'test:dir-read', exts: [], fetchStrategy: 'fsRead', component: () => null })
fsRead.mockRejectedValueOnce({ code: 'fs-directory', message: '"/tmp/src" is a directory' })
service.openTab({ type: 'editor', title: 'src', path: 'src', id: 'editor:src' })
const tab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
.find(candidate => candidate.id === 'editor:src')!
const { container, rerender, unmount } = mountHost(ctx, store, tab)
try {
await act(async () => {
await new Promise<void>(resolve => { setTimeout(resolve, 0) })
})
expect(fsRead).toHaveBeenCalledWith(expect.anything(), 'src')
// The fallback persisted the folder flag exactly like a sidebar_open
// folder seed would have, and resolved the relative path against the
// session cwd (`/tmp` in setup()) before rooting the tree.
expect(tab().path).toBe('/tmp/src')
expect(tab().meta).toEqual({ dir: true })
rerender()
expect(container.querySelector('input[placeholder^="Search files"]')).not.toBeNull()
expect(container.textContent).not.toContain('is a directory')
} finally {
unmount()
}
})
it('a Windows session root normalizes the promoted folder root to backslashes (#1029)', async () => {
const { store, ctx } = setup()
const service = ctx.betterSidebar
// A chat file address carries a `/`-separated session-relative path. Joined
// onto a Windows cwd it must not keep the mixed spelling: the host keys
// every listing by its `path.resolve`'d absolute path while FileTree keys
// levels by the requested root, so mixed separators would leave the root on
// its "Loading…" placeholder forever.
const snapshot = (ctx.sessions as unknown as {
list: { getSnapshot: () => { byId: Record<string, { cwd: string }> } }
}).list.getSnapshot()
snapshot.byId[sessionId]!.cwd = 'C:\\work'
service.registerFileViewer({ id: 'test:dir-read-win', exts: [], fetchStrategy: 'fsRead', component: () => null })
fsRead.mockRejectedValueOnce({ code: 'fs-directory', message: '"C:\\work\\src" is a directory' })
service.openTab({ type: 'editor', title: 'src', path: 'src', id: 'editor:win-src' })
const tab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
.find(candidate => candidate.id === 'editor:win-src')!
const { container, rerender, unmount } = mountHost(ctx, store, tab)
try {
await act(async () => {
await new Promise<void>(resolve => { setTimeout(resolve, 0) })
})
expect(fsRead).toHaveBeenCalledWith(expect.anything(), 'src')
expect(tab().path).toBe('C:\\work\\src')
expect(tab().meta).toEqual({ dir: true })
rerender()
expect(container.querySelector('input[placeholder^="Search files"]')).not.toBeNull()
expect(container.textContent).not.toContain('is a directory')
} finally {
unmount()
}
})
it('a folder tab (meta.dir) renders the tree rooted at the folder, no editor chrome', () => {
const { store, ctx } = setup()
ctx.betterSidebar!.openTab({
+16 -1
View File
@@ -3,7 +3,7 @@
* editor host runs (planFirstMatch / planFsReadOutcome / decodeHead).
*/
import { describe, expect, it } from 'vitest'
import { decodeHead, planFirstMatch, planFsReadOutcome } from '../src/client/editor-load.ts'
import { decodeHead, isDirectoryReadError, planFirstMatch, planFsReadOutcome } from '../src/client/editor-load.ts'
import type { FileViewerDescriptor } from '../src/client/service.ts'
const viewer = (over: Partial<FileViewerDescriptor>): FileViewerDescriptor => ({
@@ -141,3 +141,18 @@ describe('decodeHead', () => {
expect(Array.from(head)).toEqual([0x00, 0xff, 0xff, 0x00])
})
})
describe('isDirectoryReadError', () => {
it('recognizes the dedicated directory wire code', () => {
expect(isDirectoryReadError({ code: 'fs-directory', message: '"/work/src" is a directory' })).toBe(true)
// The real wire failure class also exposes `code` (api.ts SidebarApiError).
expect(isDirectoryReadError(Object.assign(new Error('"/work/src" is a directory'), { code: 'fs-directory' }))).toBe(true)
})
it('leaves every other failure to the error face', () => {
expect(isDirectoryReadError({ code: 'fs-error', message: 'boom' })).toBe(false)
expect(isDirectoryReadError(new Error('boom'))).toBe(false)
expect(isDirectoryReadError(null)).toBe(false)
expect(isDirectoryReadError(undefined)).toBe(false)
})
})
+5 -2
View File
@@ -238,11 +238,14 @@ describe('fs.readPage', () => {
expect(walked.text).toBe(asciiPrefix + cjkTail)
})
it('refuses a directory and a path outside any session', async () => {
it('refuses a directory with its dedicated wire code', async () => {
const workspace = workspaceWith('dir', 'x')
mkdirSync(join(workspace, 'sub'))
const route = mountApi(workspace)
const onDir = await readPage(route, join(workspace, 'sub'), 0)
expect(onDir).toMatchObject({ ok: false, error: { code: 'fs-error' } })
// `fs-directory` is what lets the client turn the open into a folder
// window instead of rendering an error (the generic fs-error path is kept
// for unreadable paths).
expect(onDir).toMatchObject({ ok: false, error: { code: 'fs-directory' } })
})
})
+15 -1
View File
@@ -2,7 +2,7 @@ import './browser-globals.ts'
import { describe, expect, it } from 'vitest'
import { decodeHtmlUrl } from '../src/html-route.ts'
import { isAbsolutePath, relativeTo, workspaceRelativePath } from '../src/client/paths.ts'
import { resolveSidebarPath } from '../src/client/paths.ts'
import { resolveNativeSidebarPath, resolveSidebarPath } from '../src/client/paths.ts'
import { downloadUrl, htmlUrl, mediaUrl } from '../src/client/api.ts'
describe('path helpers', () => {
@@ -36,6 +36,20 @@ describe('path helpers', () => {
expect(resolveSidebarPath('C:\\work\\proj\\', 'C:\\abs\\x.ts')).toBe('C:\\abs\\x.ts')
})
it('normalizes a folder root to the cwd separator dialect (#1029)', () => {
// A chat file address is `/`-separated and session-relative; the host keys
// listings by path.resolve'd absolute paths, so the folder root the tree
// requests must speak the same dialect or it never matches its level.
expect(resolveNativeSidebarPath('C:\\work\\proj', 'src/a.ts')).toBe('C:\\work\\proj\\src\\a.ts')
// path.resolve drops a trailing separator; the helper mirrors that (a
// drive root keeps it).
expect(resolveNativeSidebarPath('C:\\work\\proj\\', 'src/a.ts/')).toBe('C:\\work\\proj\\src\\a.ts')
expect(resolveNativeSidebarPath('C:\\work\\proj', 'C:\\')).toBe('C:\\')
// POSIX keeps the plain join: a backslash is a legal filename character.
expect(resolveNativeSidebarPath('/home/me/proj', 'src/a.ts')).toBe('/home/me/proj/src/a.ts')
expect(resolveNativeSidebarPath(undefined, 'src/a.ts')).toBe('src/a.ts')
})
it('keeps UNC produced paths absolute instead of joining them onto the cwd', () => {
// Pure client function: UNC detection is platform-independent, so these
// assertions run on every host without a platform guard.