diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index 900e1d01b6..7d06152986 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: ad2aa904beddb2fe941883c3c1827702dbec9964 -2026-07-28-directory-picker-capability-seam.zh.md: 30e719ad9b4e8374496106b447e961a042c7d8b6 +2026-07-28-directory-picker-capability-seam.md: a9f9bc81a8aeff4f9592257b574a199063c681ae +2026-07-28-directory-picker-capability-seam.zh.md: 6331440b04cc8ee6994cb49ff3fd1e6b49403fa4 diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index ad2aa904be..a9f9bc81a8 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -20,7 +20,7 @@ Placement and policy rulings folded into this decision: - **Dependency survey (hand-roll vs adopt).** Node's stdlib *is* the maintained cross-platform OS layer (`readdir(withFileTypes)`, `homedir`, path semantics); surveyed alternatives fail the dependency bar — file-manager packages (`node-file-manager`, `files-and-folders`, Syncfusion's provider) are whole HTTP apps (fit), drive-letter helpers (`drivelist` native addon, `windows-drive-letters` ~7y stale) fail health/proportionality. The browse backend is a thin adapter over stdlib. - **Hidden entries: return-and-flag.** The host stamps `hidden` (POSIX dot convention) and returns everything; the client filters. Display policy stays client-side, and the show-hidden toggle shipped as exactly that client-only change: a fixed-label footer toggle whose state lives in the pressed presentation (`aria-pressed` + check glyph), a dot-led path-draft prefix reveals the hidden entries it names, and the current selection is exempt from both the hidden and the prefix filter (it anchors the two-pane view). Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. - **Path-editor cancel scope: the dialog card.** The browse client's path editor cancels on Escape and on focus leaving the card, both observed at a card-scope wrapper rather than the input — after Tab parks focus on a filtered row the input is off the event path, yet Escape must collapse the editor (not the dialog) and a later focus departure must still cancel. Non-cancel exemptions: window/tab focus loss, in-card focus moves, and pointer paths (rows and the toggle suppress focus steal on mousedown while editing). Separators for seeding and draft-tail filtering are inferred from `listing.home`; the wire-field alternative below records the deferred authoritative form. Combobox semantics between the editor and the list it filters (`aria-expanded`/`aria-controls`/active-descendant, result announcements) are likewise deferred — today they read to assistive tech as separate widgets. -- **Navigation lands selection-anchored, progressively.** Away from the display root (the same collapse the crumb header renders, so crumbs and pane shape never disagree), the browse client's navigate commits the target level the moment it arrives — the editor closes and loading ends on that first settlement, so an Enter-submitted navigation is never withdrawn waiting on more — and a parent leg then upgrades the landing in place: the target's actual parent-level entry re-selected (platform case folding on Windows), its children on the right, so a crumb jump reads as stepping back one pane rather than collapsing to a single column. The parent leg runs under the landing's supersession scope and is aborted on the wire by any newer intent; a failed parent leg, or a truncated parent window lacking the target, leaves the committed single-pane landing — the upgrade must never orphan the selection it exists to anchor. +- **Navigation lands selection-anchored, progressively.** Away from the display root (the same collapse the crumb header renders, so crumbs and pane shape never disagree), the browse client's navigate commits the target level the moment it arrives — the editor closes and loading ends on that first settlement, so an Enter-submitted navigation is never withdrawn waiting on more — and a parent leg then upgrades the landing in place: the target's actual parent-level entry re-selected (platform case folding on Windows), its children on the right, so a crumb jump reads as stepping back one pane rather than collapsing to a single column. The parent leg runs under the landing's supersession scope and is aborted on the wire by any newer intent; a failed parent leg, or a truncated parent window lacking the target, leaves the committed single-pane landing — the upgrade must never orphan the selection it exists to anchor. Known boundaries of the progressive shape: a pointer press landing exactly inside the one-RTT upgrade window can lose its click when the pressed row node is replaced (keyboard focus is re-parked on the re-selected row; the pointer window is accepted); slash-platform typed-case drift (macOS) misses the parent-entry match and keeps the single-pane landing; and navigate always relists both legs even when the target is the currently shown level — a crumb tap doubles as the refresh gesture, so freshness wins over reusing possibly-stale in-hand listings at the cost of up to two host scans. - **Symlinks: follow for enterability.** `stat` probes symlinks (broken/cyclic → skipped); crumbs keep the logical path the operator navigated, and `workspace.create` already canonicalizes via realpath at adoption. - **Listing levels are bounded, and streamed.** One `list` call returns at most `maxEntries` rows (config, default 1000 — GitHub's web-UI directory-listing bound). The level streams via `opendir` into a name-sorted window of `maxEntries + 1` candidates, so memory stays O(maxEntries) and enterability probing touches only windowed candidates; the wire `DirectoryListing` carries a required `truncated` flag so the client states incompleteness instead of silently missing tail entries. A windowed broken symlink is not backfilled from beyond the window — the eviction already marks the level truncated. Window insertion is binary with an O(1) full-window tail rejection (an oversized level must not pay a window scan per dirent), and `list(path, signal)` threads the carrier's request signal so a scan of a stalled network directory cannot outlive a disconnected caller — every await in the scan (open, each read, each symlink probe) races the signal, an aborted exit abandons rather than awaits the close (Node queues close behind in-flight reads), and abandoned settlements are swallowed so cleanup can never surface as an unhandled rejection. An unbounded level is a memory/responsiveness hole for large or adversarial directories. - **Whole-filesystem scope, no roots config.** `workspace.create` accepts arbitrary paths and the API serves bash-driving methods, so a browse root would be UX scoping, not a boundary; configurability without a consumer fails the evidence bar. Deferred until a deployment needs it. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 30e719ad9b..6331440b04 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -20,7 +20,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **依赖调研(手写 vs 引入)。** Node 标准库本身就是维护中的跨平台 OS 层(`readdir(withFileTypes)`、`homedir`、路径语义);调研过的替代品都过不了依赖门槛——文件管理器包(`node-file-manager`、`files-and-folders`、Syncfusion 的 provider)是整套 HTTP 应用(契合度不过),盘符工具(原生插件 `drivelist`、约七年未更的 `windows-drive-letters`)健康度/比例失当。browse 后端是标准库上的薄适配。 - **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,"显示隐藏"开关正是作为这一纯客户端改动落地:标签固定的 footer 开关,其状态由按下态呈现承载(`aria-pressed` + 勾选符号);以点开头的路径草稿前缀会显出它所指名的隐藏条目;当前选中项则不受隐藏与前缀两种过滤影响(它锚定着双栏视图)。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 - **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从 `listing.home` 推断;下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。 -- **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。 +- **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台的键入大小写偏差(macOS)会错过父层级条目匹配,保留单栏落地;且导航总是重新列举两程,哪怕目标就是当前展示的层级——crumb 点按兼作刷新手势,因此宁要新鲜度也不复用手头可能已陈旧的列举,代价是至多两次宿主扫描。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 - **列举层级有上限,且流式处理。** 单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端目录列举的同一上限)。层级经 `opendir` 流入一个按名排序、容量 `maxEntries + 1` 的候选窗口,内存保持 O(maxEntries),可进入性探测只触及窗口内候选;线上 `DirectoryListing` 携带必填的 `truncated` 标志,让客户端明示不完整而不是静默缺尾。窗口内的断链符号链接不从窗口外回填——发生过驱逐本身已把层级标记为截断。窗口插入为二分查找、满窗尾部单次比较即拒绝(超大层级不能为每个 dirent 付出一次全窗扫描),且 `list(path, signal)` 透传载体的请求信号,滞塞网络目录的扫描不会在调用方断连后继续存活——扫描中的每个 await(打开、每次读取、每次符号链接探测)都与信号赛跑,中止路径放弃而非等待 close(Node 会把 close 排在在飞读取之后),被放弃的 settlement 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 - **全盘可浏览,不做 roots 配置。** `workspace.create` 接受任意路径且 API 本就提供驱动 bash 的方法,浏览根只会是 UX 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 859667d115..5c44492b77 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -55,13 +55,27 @@ function failureText(error: unknown): string { return error instanceof Error ? error.message : String(error) } +/** + * Case-folds a path for comparisons under the listing's platform: backslash + * (Windows) paths compare case-insensitively — a typed path legally differs + * in case from the host's stamped one — while slash platforms compare + * exactly (the filesystem may be case-sensitive; macOS typed-case drift + * degrades to the single-pane landing instead of a wrong match). + */ +function foldPathFor(listing: DirectoryListing): (value: string) => string { + const sep = separatorOf(listing) + return value => (sep === '\\' ? value.toLowerCase() : value) +} + /** * Breadcrumb rows for display: inside the home subtree the chain starts at a * localized Home crumb; outside it the full ancestry shows, the root labeled - * by its own path. + * by its own path. The home comparison folds per platform so a typed-case + * Windows path still collapses to the Home crumb. */ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryEntry[] { - const homeIndex = listing.crumbs.findIndex(crumb => crumb.path === listing.home) + const fold = foldPathFor(listing) + const homeIndex = listing.crumbs.findIndex(crumb => fold(crumb.path) === fold(listing.home)) if (homeIndex === -1) return listing.crumbs const tail = listing.crumbs.slice(homeIndex + 1) return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail] @@ -222,6 +236,12 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, * intent aborts it like the leg it continues, and it supersedes nothing. */ const continueScan = useCallback((path: string): Promise => { + // Abort whatever the slot last tracked before overwriting it (the + // caller's settled leg: a no-op) — the slot must never silently strand + // a live scan, the exact waste supersede() exists to prevent. + const displaced = scanController.current + /* v8 ignore next -- narrowing guard: the landing's target leg installed a controller before any follow-up runs. */ + if (displaced !== null) displaced.abort() const controller = new AbortController() scanController.current = controller return listDirectory(path, controller.signal) @@ -236,9 +256,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, * shape never disagree — a parent leg then upgrades the landing in place: * the target's ACTUAL parent-level entry re-selected (left pane = parent, * right pane = the target), so a crumb jump reads as stepping back one - * pane. A failed parent leg, or a truncated parent window that lacks the - * target, leaves the committed single-pane landing — the upgrade must - * never orphan the selection it exists to anchor. + * pane (Windows folds case; slash-platform typed-case drift degrades to + * the single-pane landing). A failed parent leg, or a truncated parent + * window that lacks the target, leaves the committed single-pane landing + * — the upgrade must never orphan the selection it exists to anchor. */ const navigate = useCallback((path?: string) => { const { seq, scan } = launchListing(path) @@ -259,11 +280,18 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, continueScan(parentCrumb.path).then((parentLevel) => { if (seq !== requestSeq.current) return // Windows resolves a typed path preserving its case; anchor on the - // parent level's actual entry so selection comparisons hold. - const sep = separatorOf(parentLevel) - const fold = (value: string): string => (sep === '\\' ? value.toLowerCase() : value) + // parent level's actual entry so selection comparisons hold (slash + // platforms compare exactly — see foldPathFor). + const fold = foldPathFor(parentLevel) const match = parentLevel.entries.find(entry => fold(entry.path) === fold(target.path)) if (match === undefined) return + // The upgrade replaces every committed row node; if focus lives + // among them (Tab reached the rows during the parent leg), arm the + // refocus effect so it re-parks on the re-selected row. + const rowHost = millerRowRef.current + /* v8 ignore next -- narrowing guard: the committed landing just rendered the miller row. */ + const focusInRows = rowHost !== null && rowHost.contains(document.activeElement) + if (focusInRows) refocusPick.current = true setParent(parentLevel) setSelected(match) setChild(target) @@ -279,11 +307,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [launchListing, continueScan]) - // Editor-close focus parking (consumed by the refocus effect below the - // miller-row ref): a pick parks on the selection's row, Enter and an - // input-focused Escape park on the crumb edit zone that replaces the - // input. Pointer-out cancels never set (or clear) these — yanking focus - // back from wherever the user clicked would be worse than the fall. + // Focus parking (consumed by the refocus effect below the miller-row + // ref): a pick — and a parent-leg upgrade that displaces focused rows — + // parks on the selection's row; Enter, an input-focused Escape, and a + // failed pick whose row unmounts park on the crumb edit zone (the latter + // only when focus actually fell to body). Pointer-out cancels never set + // (or clear) these — yanking focus back from wherever the user clicked + // would be worse than the fall. const refocusPick = useRef(false) const refocusEditZone = useRef(false) const pathInputRef = useRef(null) diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index 6fa9bb999f..fc2b6f564b 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -270,6 +270,59 @@ describe('DirectoryBrowser', () => { expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBeNull() }) + it('re-parks focus on the re-selected row when the upgrade displaces focused rows', async () => { + const settlers: ((value: DirectoryListing) => void)[] = [] + const listDirectory = vi.fn(async (path?: string) => { + if (path === HOME) { + return new Promise((resolve) => { settlers.push(resolve) }) + } + return listingFor(path) + }) + mount({ listDirectory }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + fireEvent.change(screen.getByLabelText('browser.editPath'), { target: { value: DOCS } }) + fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Enter' }) + // The committed landing is interactive; Tab reaches its rows while the + // parent leg is still in flight. + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + rowButton(screen.getByRole('listitem')).focus() + await waitFor(() => { expect(settlers).toHaveLength(1) }) + // The upgrade replaces every committed row node; focus re-parks on the + // re-selected row instead of falling to body. + await act(async () => { settlers[0]!(listingFor(HOME)) }) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + expect(document.activeElement?.textContent).toBe('Documents') + expect(document.activeElement?.getAttribute('aria-current')).toBe('true') + }) + + it('collapses a typed-case Windows home to the display root (single pane, Home crumb)', async () => { + const CANON = 'C:\\Users\\Alice' + const TYPED = 'c:\\users\\alice' + const typedHome: DirectoryListing = { + path: TYPED, + home: CANON, + crumbs: [ + { name: 'C:\\', path: 'C:\\', hidden: false }, + { name: 'users', path: 'c:\\users', hidden: false }, + { name: 'alice', path: TYPED, hidden: false }, + ], + entries: [{ name: 'Desktop', path: `${CANON}\\Desktop`, hidden: false }], + truncated: false, + } + const canonHome: DirectoryListing = { ...typedHome, path: CANON, crumbs: typedHome.crumbs } + mount({ listDirectory: vi.fn(async (path?: string) => (path === TYPED ? typedHome : canonHome)) }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + fireEvent.change(screen.getByLabelText('browser.editPath'), { target: { value: TYPED } }) + fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Enter' }) + // Case-folded home comparison: the typed-case home is still the display + // root — single pane, collapsed Home crumb, no parent leg. + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Desktop') }) + expect(columns()).toHaveLength(1) + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + }) + it('keeps the single-pane landing when the truncated parent level lacks the target', async () => { const listDirectory = vi.fn(async (path?: string) => { // The parent leg names HOME explicitly; serve it a truncated window