From cdcdd2221edd2b5e55b18a62070e4f776068d4c8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 12:52:59 +0800 Subject: [PATCH 01/34] feat(host): show-hidden toggle in the directory browser footer --- .../src/client/DirectoryBrowser.module.css | 26 +++++++++++++++++++ .../src/client/DirectoryBrowser.tsx | 22 +++++++++++++--- .../src/client/index.ts | 4 +++ .../tests/client-flow.spec.tsx | 2 ++ .../tests/directory-browser.spec.tsx | 17 ++++++++++++ 5 files changed, 67 insertions(+), 4 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 800af854a1..bdb57ca848 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -242,6 +242,32 @@ border-top: 1px solid var(--dsw-alias-border-l3); } +/* Show-hidden toggle: a subtle text button in the footer, left of the gap. */ +.showHiddenToggle { + border: none; + background: transparent; + padding: 0; + font-size: 13px; + line-height: 20px; + font-weight: 500; + color: var(--dsw-alias-label-secondary); + cursor: pointer; + white-space: nowrap; +} + +.showHiddenToggle:hover { + color: var(--dsw-alias-label-primary); +} + +.showHiddenToggle:disabled { + color: var(--dsw-alias-label-caption); + cursor: default; +} + +.showHiddenToggleActive { + color: var(--dsw-alias-label-primary); +} + .footerGap { flex: 1 1 0; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index f348f1dd8d..20fef7a827 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -10,8 +10,8 @@ * selects the created folder. Open adopts the selected folder, falling back * to the listed level. Pure consumer of the injected browse calls — the * owning flow decides what "Open" means and owns the workspace-creation - * error surface. Hidden entries are host-flagged and filtered here (a - * show-hidden toggle is deferred work, client-side only). + * error surface. Hidden entries are host-flagged and hidden by default; + * a "Show hidden files" toggle in the footer reveals them (client-side only). */ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' @@ -60,16 +60,17 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE } /** One column of folder rows (the Miller view renders one or two of these). */ -function LevelColumn({ entries, selectedPath, busy, onPick, wide }: { +function LevelColumn({ entries, selectedPath, busy, onPick, wide, showHidden }: { entries: readonly DirectoryEntry[] selectedPath: string | null busy: boolean onPick: (entry: DirectoryEntry) => void wide: boolean + showHidden: boolean }) { return (
- {entries.filter(entry => !entry.hidden).map((entry) => { + {entries.filter(entry => showHidden || !entry.hidden).map((entry) => { const selected = entry.path === selectedPath return ( // The wrapper carries the list semantics; the row keeps its NATIVE @@ -110,6 +111,8 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const [error, setError] = useState(null) // Path-edit state: null = breadcrumb mode; a string = the draft being typed. const [pathDraft, setPathDraft] = useState(null) + // Show-hidden toggle state (pure client-side filter, reset on close). + const [showHidden, setShowHidden] = useState(false) // Create-folder state: null = closed; a string = the nested dialog's draft. const [folderDraft, setFolderDraft] = useState(null) const [creatingFolder, setCreatingFolder] = useState(false) @@ -213,6 +216,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setSelected(null) setChild(null) setCreatingFolder(false) + setShowHidden(false) navigate() return } @@ -409,6 +413,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, busy={parentInert} onPick={select} wide={!twoPane} + showHidden={showHidden} /> )} {twoPane && } @@ -419,6 +424,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, busy={parentInert} onPick={advance} wide={false} + showHidden={showHidden} /> )}
@@ -442,6 +448,14 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, > {t('browser.newFolder')} + diff --git a/packages/host/directory-picker-browse/src/client/index.ts b/packages/host/directory-picker-browse/src/client/index.ts index e47613cdaf..a458ca94c7 100644 --- a/packages/host/directory-picker-browse/src/client/index.ts +++ b/packages/host/directory-picker-browse/src/client/index.ts @@ -47,7 +47,6 @@ export function apply(ctx: ClientContext): void { 'browser.loading': '加载中…', 'browser.truncated': '文件夹过多,仅显示开头部分。', 'browser.showHidden': '显示隐藏文件', - 'browser.hideHidden': '隐藏隐藏文件', }], ['en', { 'browser.title': 'Select Workspace Directory', @@ -63,7 +62,6 @@ export function apply(ctx: ClientContext): void { 'browser.loading': 'Loading…', 'browser.truncated': 'Too many folders to list; only the beginning is shown.', 'browser.showHidden': 'Show hidden files', - 'browser.hideHidden': 'Hide hidden files', }], ] try { diff --git a/packages/host/directory-picker-browse/tests/client-flow.spec.tsx b/packages/host/directory-picker-browse/tests/client-flow.spec.tsx index c29afc935c..31ec5a4927 100644 --- a/packages/host/directory-picker-browse/tests/client-flow.spec.tsx +++ b/packages/host/directory-picker-browse/tests/client-flow.spec.tsx @@ -163,7 +163,6 @@ describe('directory-picker-browse client half', () => { expect(injected.t('browser.title')).toBe('选择工作区目录') expect(injected.t('browser.newFolder')).toBe('新建文件夹') expect(injected.t('browser.showHidden')).toBe('显示隐藏文件') - expect(injected.t('browser.hideHidden')).toBe('隐藏隐藏文件') }) it('drives the injected browse calls through the hole entry', async () => { 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 624a2c8705..bc2ad81f76 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -107,11 +107,14 @@ describe('DirectoryBrowser', () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) expect(screen.queryByText('.config')).toBeNull() - // Toggle hidden files on. - fireEvent.click(screen.getByRole('button', { name: 'browser.showHidden' })) + // The fixed-label toggle reports its state through aria-pressed. + const toggle = screen.getByRole('button', { name: 'browser.showHidden' }) + expect(toggle.getAttribute('aria-pressed')).toBe('false') + fireEvent.click(toggle) + expect(toggle.getAttribute('aria-pressed')).toBe('true') expect(screen.getByText('.config')).toBeTruthy() - // Toggle hidden files off. - fireEvent.click(screen.getByRole('button', { name: 'browser.hideHidden' })) + fireEvent.click(toggle) + expect(toggle.getAttribute('aria-pressed')).toBe('false') expect(screen.queryByText('.config')).toBeNull() // Close resets the toggle. b.view.rerender() From 60383efef93e083763f7b86239afc7e4798c181e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 13:42:11 +0800 Subject: [PATCH 03/34] feat(host): blur cancels path editing; scrollbar clearance in the miller columns --- .../src/client/DirectoryBrowser.module.css | 11 ++++- .../src/client/DirectoryBrowser.tsx | 42 +++++++++++-------- .../tests/directory-browser.spec.tsx | 14 +++++++ 3 files changed, 48 insertions(+), 19 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index a2c712c811..444ff19cbf 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -55,7 +55,9 @@ align-items: stretch; flex: 1 1 0; min-height: 0; - gap: 20px; + /* Columns already end in an 8px scrollbar clearance, so the divider only + * needs a slim gap of its own on each side. */ + gap: 12px; overflow-x: auto; scrollbar-width: none; } @@ -136,7 +138,9 @@ flex-direction: column; flex: 1 1 0; min-height: 0; - padding: 16px 24px; + /* Right inset is slimmer than the left: the trailing column's own 8px + * scrollbar clearance makes up the optical difference. */ + padding: 16px 16px 16px 24px; } /* Two-pane columns split the row evenly around the divider; 256px is the @@ -149,6 +153,9 @@ flex: 1 1 0; min-width: 256px; overflow-y: auto; + /* The overlay scrollbar paints at the column's edge; keep the row pills + * clear of the thumb. */ + padding-right: 8px; } .columnWide { diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 149e04d87e..5c3391454e 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -200,6 +200,25 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [launchListing]) + /** Abandon path editing (Escape or clicking away) and restore the crumb view. */ + const cancelPathEdit = useCallback(() => { + // Cancel also withdraws a navigation the editor already launched: its + // late success must not jump to the cancelled path, so the pending + // request is superseded and the view leaves the loading state. + supersede() + setLoading(false) + setPathDraft(null) + setError(null) + // Editing may have superseded the selection's preview request; a + // selection with no preview would render a half-empty two-pane view, so + // cancel falls back to the single-pane level. + if (child === null) setSelected(null) + // With no level listed yet (the editor superseded the initial home + // listing), plain cancellation would leave a permanently blank picker: + // restart the home listing. + if (parent === null) navigate() + }, [supersede, child, parent, navigate]) + /** A right-column pick advances the view one level: child becomes the level. */ const advance = useCallback((entry: DirectoryEntry) => { /* v8 ignore next -- narrowing guard: the right column only renders with a child listing. */ @@ -382,25 +401,14 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, } if (event.key === 'Escape') { event.stopPropagation() - // Cancel also withdraws a navigation the editor already - // launched: its late success must not jump to the - // cancelled path, so the pending request is superseded - // and the view leaves the loading state. - supersede() - setLoading(false) - setPathDraft(null) - setError(null) - // Editing may have superseded the selection's preview - // request; a selection with no preview would render a - // half-empty two-pane view, so cancel falls back to the - // single-pane level. - if (child === null) setSelected(null) - // With no level listed yet (the editor superseded the - // initial home listing), plain cancellation would leave a - // permanently blank picker: restart the home listing. - if (parent === null) navigate() + cancelPathEdit() } }} + // Clicking anywhere outside the editor reads as leaving it: + // focus loss cancels the edit like Escape. Enter keeps focus + // in the input while its navigation is in flight, so a + // submitted path is never withdrawn by this handler. + onBlur={cancelPathEdit} /> )} 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 bc2ad81f76..d4fc9e2b89 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -220,6 +220,20 @@ describe('DirectoryBrowser', () => { expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() }) + it('clicking away from the path editor cancels it back to the crumb view', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: '/somewhere/else' } }) + // Focus moving anywhere outside the editor abandons the draft like Escape. + fireEvent.blur(input) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + // The crumb view is back and the abandoned draft was never navigated to. + expect(screen.getByRole('button', { name: 'browser.editPath' })).toBeTruthy() + expect(screen.getByRole('listitem').textContent).toBe('Documents') + }) + it('restarts the home listing when Escape cancels an edit opened before any level listed', async () => { // The initial home listing hangs; Edit Path supersedes it while parent // is still null, and Escape must not strand a blank picker. From e561c28232a273f834e66e557e8375a3bb2cf7d0 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 13:47:56 +0800 Subject: [PATCH 04/34] feat(host): seed path editor with a trailing separator; prefix-filter levels from the draft tail --- .../src/client/DirectoryBrowser.tsx | 44 +++++++++++++++-- .../tests/directory-browser.spec.tsx | 47 ++++++++++++++++++- 2 files changed, 86 insertions(+), 5 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 5c3391454e..01e69f314c 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -12,7 +12,10 @@ * owning flow decides what "Open" means and owns the workspace-creation * error surface. Hidden entries are host-flagged and hidden by default; the * footer's fixed-label "Show hidden files" toggle (aria-pressed, check when - * on) reveals them (client-side only). + * on) reveals them (client-side only). The path editor opens seeded with a + * trailing separator, and while the draft's directory part names a listed + * level, its final segment prefix-filters that level's rows (a dot-led + * prefix also reveals the hidden entries it names). */ import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' @@ -60,18 +63,45 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail] } +/** The separator a Host path's own platform uses (Windows listings carry backslashes). */ +function separatorOf(path: string): string { + return path.includes('\\') ? '\\' : '/' +} + +/** + * The path draft's final segment, when its directory part is exactly the + * level `listing` lists — the segment the level prefix-filters on while the + * user types. Any other draft (no separator yet, or naming some other + * directory) leaves the level unfiltered. + */ +function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { + if (draft === null) return null + const sep = separatorOf(draft) + const cut = draft.lastIndexOf(sep) + if (cut === -1) return null + const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` + return draft.slice(0, cut + 1) === level ? draft.slice(cut + 1) : null +} + /** One column of folder rows (the Miller view renders one or two of these). */ -function LevelColumn({ entries, selectedPath, busy, onPick, wide, showHidden }: { +function LevelColumn({ entries, selectedPath, busy, onPick, wide, showHidden, filterPrefix }: { entries: readonly DirectoryEntry[] selectedPath: string | null busy: boolean onPick: (entry: DirectoryEntry) => void wide: boolean showHidden: boolean + filterPrefix: string | null }) { + const visible = entries.filter((entry) => { + if (filterPrefix !== null && !entry.name.toLowerCase().startsWith(filterPrefix.toLowerCase())) return false + // A dot-led prefix names hidden entries explicitly, so matching ones + // surface even while the toggle keeps the rest hidden. + return showHidden || !entry.hidden || filterPrefix?.startsWith('.') === true + }) return (
- {entries.filter(entry => showHidden || !entry.hidden).map((entry) => { + {visible.map((entry) => { const selected = entry.path === selectedPath return ( // The wrapper carries the list semantics; the row keeps its NATIVE @@ -370,7 +400,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // otherwise close the editor via navigate's draft reset. supersede() setLoading(false) - setPathDraft(selected?.path ?? parent?.path ?? '') + // Seed with a trailing separator so typing immediately + // continues into child names (and prefix-filters below). + const base = selected?.path ?? parent?.path ?? '' + const sep = separatorOf(base) + setPathDraft(base === '' || base.endsWith(sep) ? base : `${base}${sep}`) }} /> @@ -423,6 +457,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onPick={select} wide={!twoPane} showHidden={showHidden} + filterPrefix={draftPrefixFor(parent, pathDraft)} /> )} {twoPane && } @@ -434,6 +469,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onPick={advance} wide={false} showHidden={showHidden} + filterPrefix={draftPrefixFor(child, pathDraft)} /> )}
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 d4fc9e2b89..98f3bd6e4f 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -206,7 +206,9 @@ describe('DirectoryBrowser', () => { await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) const input = screen.getByLabelText('browser.editPath') - expect(input.value).toBe(HOME) + // The editor seeds with a trailing separator so typing continues into + // child names. + expect(input.value).toBe(`${HOME}/`) fireEvent.change(input, { target: { value: DOCS } }) fireEvent.keyDown(input, { key: 'Enter' }) await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) @@ -220,6 +222,49 @@ describe('DirectoryBrowser', () => { expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() }) + it('prefix-filters the listed level from the draft tail, dot revealing hidden matches', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + // The seeded empty segment leaves the level as-is: hidden stays hidden. + expect(screen.getByRole('listitem').textContent).toBe('Documents') + // Case-insensitive prefix narrows the rows. + fireEvent.change(input, { target: { value: `${HOME}/do` } }) + expect(screen.getByRole('listitem').textContent).toBe('Documents') + // A dot-led prefix names hidden entries, so it reveals the match. + fireEvent.change(input, { target: { value: `${HOME}/.co` } }) + expect(screen.getByRole('listitem').textContent).toBe('.config') + // A prefix matching nothing empties the level (no stale rows linger). + fireEvent.change(input, { target: { value: `${HOME}/zzz` } }) + expect(screen.queryByRole('listitem')).toBeNull() + // A draft naming some other directory (or none) leaves the level whole. + fireEvent.change(input, { target: { value: 'no-separator' } }) + expect(screen.getByRole('listitem').textContent).toBe('Documents') + }) + + it('seeds and filters with backslashes on a Windows-rooted listing', async () => { + const ROOT = 'C:\\' + const windowsListing: DirectoryListing = { + path: ROOT, + home: ROOT, + crumbs: [{ name: 'C:\\', path: ROOT, hidden: false }], + entries: [ + { name: 'Program Files', path: `${ROOT}Program Files`, hidden: false }, + { name: 'Users', path: `${ROOT}Users`, hidden: false }, + ], + truncated: false, + } + mount({ listDirectory: vi.fn(async () => windowsListing) }) + await waitFor(() => { expect(screen.getAllByRole('listitem')).toHaveLength(2) }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + // The root already ends in its separator: no doubled backslash. + expect(input.value).toBe(ROOT) + fireEvent.change(input, { target: { value: `${ROOT}u` } }) + expect(screen.getByRole('listitem').textContent).toBe('Users') + }) + it('clicking away from the path editor cancels it back to the crumb view', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) From 7714c9fa8b4c890ebc495e766a9d2f778e141953 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 13:52:44 +0800 Subject: [PATCH 05/34] doc(host): document the show-hidden toggle and path-draft prefix filter; snapshot the flow --- ...directory-picker-capability-seam.i18n.yaml | 4 +-- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- apps/web/tests/workspace-flow.snapshot.ts | 33 +++++++++++++++++++ .../directory-picker-browse/README.i18n.yaml | 4 +-- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- 7 files changed, 41 insertions(+), 8 deletions(-) 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 bb9425fa64..6f21a60e83 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: 7c8f8cb67690cb4c5858cefb52b8cd79e649ec38 -2026-07-28-directory-picker-capability-seam.zh.md: 05545fc3cd758523814b31afa705249972d86464 +2026-07-28-directory-picker-capability-seam.md: 3f5e1436f3af14ce06ffab00ceca90167e16afd0 +2026-07-28-directory-picker-capability-seam.zh.md: 09a3e20f7c12e3c22d63875091593f9a6ca8a1ad 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 7c8f8cb676..3f5e1436f3 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 @@ -18,7 +18,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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 planned show-hidden toggle becomes a client-only change. Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. +- **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 (the browse client's footer toggle). Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. - **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 05545fc3cd..09a3e20f7c 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 @@ -18,7 +18,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 vs 引入)。** Node 标准库本身就是维护中的跨平台 OS 层(`readdir(withFileTypes)`、`homedir`、路径语义);调研过的替代品都过不了依赖门槛——文件管理器包(`node-file-manager`、`files-and-folders`、Syncfusion 的 provider)是整套 HTTP 应用(契合度不过),盘符工具(原生插件 `drivelist`、约七年未更的 `windows-drive-letters`)健康度/比例失当。browse 后端是标准库上的薄适配。 -- **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,计划中的"显示隐藏"开关变成纯客户端改动。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 +- **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,"显示隐藏"开关正是作为这一纯客户端改动落地(browse 客户端的 footer 开关)。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 - **符号链接:为可进入性而跟随。** 用 `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/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index 86a20e73fe..32d44b6fff 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -214,6 +214,39 @@ it('adopts a directory through the composed in-app browse flow and lands in its }) }) +it('reveals hidden fixture entries via the footer toggle and prefix-filters from the path draft', async () => { + boot('?fixture=empty') + + await findLockedComposer() + fireEvent.click(workspaceChip()) + fireEvent.click(await screen.findByRole('menuitem', { name: 'Open local folder…' })) + const dialog = await screen.findByRole('dialog', { name: '选择工作区目录' }, { timeout: 10_000 }) + await within(dialog).findByText('Documents', {}, { timeout: 10_000 }) + // The host flags .config hidden; the level filters it until the + // fixed-label footer toggle presses on (state lives in aria-pressed). + expect(within(dialog).queryByText('.config')).toBeNull() + const toggle = within(dialog).getByRole('button', { name: '显示隐藏文件' }) + expect(toggle.getAttribute('aria-pressed')).toBe('false') + fireEvent.click(toggle) + expect(toggle.getAttribute('aria-pressed')).toBe('true') + await within(dialog).findByText('.config', {}, { timeout: 10_000 }) + fireEvent.click(toggle) + expect(within(dialog).queryByText('.config')).toBeNull() + // The path editor seeds the level's path with a trailing separator and the + // draft's final segment prefix-filters the listed rows while typing. + fireEvent.click(within(dialog).getByRole('button', { name: '编辑路径' })) + const input = within(dialog).getByLabelText('编辑路径') + expect(input.value).toBe('/home/fixture/') + fireEvent.change(input, { target: { value: '/home/fixture/do' } }) + expect(within(dialog).getByText('Documents')).toBeDefined() + expect(within(dialog).getByText('Downloads')).toBeDefined() + expect(within(dialog).queryByText('.config')).toBeNull() + // A dot-led prefix names hidden entries, so its matches surface. + fireEvent.change(input, { target: { value: '/home/fixture/.c' } }) + await within(dialog).findByText('.config', {}, { timeout: 10_000 }) + expect(within(dialog).queryByText('Documents')).toBeNull() +}) + it('selects the recent Workspace and opens its blank Session on first load', async () => { boot('?fixture') diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 4454afde3a..f40742fc0d 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 318380405214d5f25ad77e348c4e134a8981ffb3 -README.zh.md: 2f88f64cc2974b8535e34eb9798f512ea109b754 +README.md: 9772baa2a6e632a5f0f18cc18b9b55b45cd845ca +README.zh.md: 682495fe10bdeed41f709a438dcd222d612129e3 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 3183804052..9772baa2a6 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -6,7 +6,7 @@ The **in-app browsing backend** of the [directory-picker seam](../directory-pick Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call returns at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings), and the level streams through a bounded window so memory stays O(maxEntries) no matter how many children the directory holds: a cut level keeps the name-sorted head, counts hidden rows against the bound, probes only windowed candidates, and reports `truncated: true` so the client can say the level is incomplete (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, and `list` threads the caller's `AbortSignal` so a disconnect or timeout stops the scan instead of letting it outlive the caller. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). -**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view, breadcrumb with a click-to-edit path zone, nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). +**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing, and cancels on Escape or focus loss; a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 2f88f64cc2..682495fe10 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -6,7 +6,7 @@ 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 -**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图、带点击即编辑路径区的面包屑、嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 +**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤、按 Escape 或失焦即取消;基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 ## 模型体验 From 998a5f33819c0ec3246763588b4f513cd526b8a3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 14:27:01 +0800 Subject: [PATCH 06/34] =?UTF-8?q?fix(host):=20review=20round=20=E2=80=94?= =?UTF-8?q?=20host-derived=20separator,=20click-safe=20blur=20cancel,=20de?= =?UTF-8?q?ad=20wide=20prop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../src/client/DirectoryBrowser.module.css | 15 ++--- .../src/client/DirectoryBrowser.tsx | 66 +++++++++++++------ .../tests/directory-browser.spec.tsx | 56 +++++++++++++++- 6 files changed, 112 insertions(+), 33 deletions(-) diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index f40742fc0d..eea9966b83 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 9772baa2a6e632a5f0f18cc18b9b55b45cd845ca -README.zh.md: 682495fe10bdeed41f709a438dcd222d612129e3 +README.md: 95d2d66406210f4ba687ef5a45a38b142abd6f26 +README.zh.md: 9da374bec80f80085ff36871c227c496bb1fde7b diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 9772baa2a6..95d2d66406 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -6,7 +6,7 @@ The **in-app browsing backend** of the [directory-picker seam](../directory-pick Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call returns at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings), and the level streams through a bounded window so memory stays O(maxEntries) no matter how many children the directory holds: a cut level keeps the name-sorted head, counts hidden rows against the bound, probes only windowed candidates, and reports `truncated: true` so the client can say the level is incomplete (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, and `list` threads the caller's `AbortSignal` so a disconnect or timeout stops the scan instead of letting it outlive the caller. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). -**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing, and cancels on Escape or focus loss; a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). +**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or focus loss; a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 682495fe10..9da374bec8 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -6,7 +6,7 @@ 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 -**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤、按 Escape 或失焦即取消;基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 +**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或失焦即取消;基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 444ff19cbf..3b681de32a 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -131,8 +131,8 @@ } /* Miller content: symmetric 16px vertical padding so the divider clears the - * header and footer rules evenly; columns are 256 wide (or full width solo) - * with the hairline divider centered between them; each column scrolls alone. */ + * header and footer rules evenly; each column scrolls alone (column widths + * live at .column). */ .content { display: flex; flex-direction: column; @@ -143,9 +143,10 @@ padding: 16px 16px 16px 24px; } -/* Two-pane columns split the row evenly around the divider; 256px is the - * floor below which the row scrolls (scrollbar hidden, the effect pins the - * child pane into view) instead of squeezing the panes. */ +/* Columns split the row evenly around the divider (a solo column takes the + * whole row); 256px is the floor below which the row scrolls (scrollbar + * hidden, the effect pins the child pane into view) instead of squeezing + * the panes. */ .column { display: flex; flex-direction: column; @@ -158,10 +159,6 @@ padding-right: 8px; } -.columnWide { - width: 100%; -} - .divider { flex: none; width: 1px; diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 01e69f314c..b924c072bb 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -1,10 +1,11 @@ /** * The in-app workspace-directory browser (figma Harness 813-23126 family): a - * 600×420 dialog (clamped to short/narrow viewports — the Miller row scrolls + * 680×500 dialog (clamped to short/narrow viewports — the Miller row scrolls * sideways, the columns scroll down) whose header carries the title, the selection-path * breadcrumb, and a click-to-edit path zone; below it a Miller view — one - * full-width level until a row is selected, then two 256px columns (level | - * selected folder's children) around a hairline divider. Selecting in the + * full-width level until a row is selected, then two columns splitting the + * row evenly (256px floor; level | selected folder's children) around a + * hairline divider. Selecting in the * right column shifts the view one level deeper. "New folder" opens a nested * create dialog targeting the selected folder (or the level itself) and * selects the created folder. Open adopts the selected folder, falling back @@ -63,20 +64,26 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail] } -/** The separator a Host path's own platform uses (Windows listings carry backslashes). */ -function separatorOf(path: string): string { - return path.includes('\\') ? '\\' : '/' +/** + * The listing's platform separator, read from the host-stamped home path — + * never sniffed from typed text or entry paths, where a backslash is a legal + * POSIX name character rather than a platform fact. + */ +function separatorOf(listing: DirectoryListing): '\\' | '/' { + return listing.home.includes('\\') ? '\\' : '/' } /** * The path draft's final segment, when its directory part is exactly the * level `listing` lists — the segment the level prefix-filters on while the * user types. Any other draft (no separator yet, or naming some other - * directory) leaves the level unfiltered. + * directory) leaves the level unfiltered. The directory part compares + * exactly (it is the host's own path text, reached by seeding or erasing); + * only the name filter downstream is case-insensitive. */ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { if (draft === null) return null - const sep = separatorOf(draft) + const sep = separatorOf(listing) const cut = draft.lastIndexOf(sep) if (cut === -1) return null const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` @@ -84,12 +91,11 @@ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string } /** One column of folder rows (the Miller view renders one or two of these). */ -function LevelColumn({ entries, selectedPath, busy, onPick, wide, showHidden, filterPrefix }: { +function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPrefix }: { entries: readonly DirectoryEntry[] selectedPath: string | null busy: boolean onPick: (entry: DirectoryEntry) => void - wide: boolean showHidden: boolean filterPrefix: string | null }) { @@ -100,7 +106,7 @@ function LevelColumn({ entries, selectedPath, busy, onPick, wide, showHidden, fi return showHidden || !entry.hidden || filterPrefix?.startsWith('.') === true }) return ( -
+
{visible.map((entry) => { const selected = entry.path === selectedPath return ( @@ -112,6 +118,10 @@ function LevelColumn({ entries, selectedPath, busy, onPick, wide, showHidden, fi aria-current={selected || undefined} className={clsx(css.row, selected && css.rowSelected)} disabled={busy} + // Keep focus where it is (the path editor, notably): a focus + // steal on mousedown would blur-cancel the editor, unmount the + // filtered rows mid-gesture, and drop this very click. + onMouseDown={(event) => { event.preventDefault() }} onClick={() => { onPick(entry) }} > {selected @@ -142,7 +152,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const [error, setError] = useState(null) // Path-edit state: null = breadcrumb mode; a string = the draft being typed. const [pathDraft, setPathDraft] = useState(null) - // Show-hidden toggle state (pure client-side filter, reset on close). + // Show-hidden toggle state (pure client-side filter, reset on each open). const [showHidden, setShowHidden] = useState(false) // Create-folder state: null = closed; a string = the nested dialog's draft. const [folderDraft, setFolderDraft] = useState(null) @@ -212,6 +222,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { const { seq, scan } = launchListing(entry.path) + // A pick while the path editor is open adopts the (filtered) row and + // closes the editor — the draft served its purpose. + setPathDraft(null) setSelected(entry) setChild(null) setLoading(true) @@ -402,9 +415,15 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setLoading(false) // Seed with a trailing separator so typing immediately // continues into child names (and prefix-filters below). - const base = selected?.path ?? parent?.path ?? '' - const sep = separatorOf(base) - setPathDraft(base === '' || base.endsWith(sep) ? base : `${base}${sep}`) + // No listed level means nothing to seed from (the editor + // is the recovery path for a failed home listing). + if (parent === null) { + setPathDraft('') + return + } + const base = selected?.path ?? parent.path + const sep = separatorOf(parent) + setPathDraft(base.endsWith(sep) ? base : `${base}${sep}`) }} /> @@ -441,8 +460,15 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // Clicking anywhere outside the editor reads as leaving it: // focus loss cancels the edit like Escape. Enter keeps focus // in the input while its navigation is in flight, so a - // submitted path is never withdrawn by this handler. - onBlur={cancelPathEdit} + // submitted path is never withdrawn by this handler; rows and + // the show-hidden toggle suppress focus steal on mousedown so + // a click on them lands before any cancel. Window/tab focus + // loss also fires blur in some engines — only a focus move + // within a focused document reads as leaving the editor. + onBlur={() => { + if (!document.hasFocus()) return + cancelPathEdit() + }} /> )}
@@ -455,7 +481,6 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, selectedPath={selected?.path ?? null} busy={parentInert} onPick={select} - wide={!twoPane} showHidden={showHidden} filterPrefix={draftPrefixFor(parent, pathDraft)} /> @@ -467,7 +492,6 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, selectedPath={null} busy={parentInert} onPick={advance} - wide={false} showHidden={showHidden} filterPrefix={draftPrefixFor(child, pathDraft)} /> @@ -498,6 +522,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, className={clsx(css.showHiddenToggle, showHidden && css.showHiddenToggleActive)} aria-pressed={showHidden} disabled={parentInert} + // The toggle composes with the path editor (dot-led prefixes and + // this filter interleave): don't steal focus, so toggling never + // blur-cancels a draft mid-thought. + onMouseDown={(event) => { event.preventDefault() }} onClick={() => { setShowHidden(prev => !prev) }} > {showHidden && } 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 98f3bd6e4f..af3aff5385 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -107,9 +107,11 @@ describe('DirectoryBrowser', () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) expect(screen.queryByText('.config')).toBeNull() - // The fixed-label toggle reports its state through aria-pressed. + // The fixed-label toggle reports its state through aria-pressed. Its + // mousedown never steals focus (so it composes with the path editor). const toggle = screen.getByRole('button', { name: 'browser.showHidden' }) expect(toggle.getAttribute('aria-pressed')).toBe('false') + fireEvent.mouseDown(toggle) fireEvent.click(toggle) expect(toggle.getAttribute('aria-pressed')).toBe('true') expect(screen.getByText('.config')).toBeTruthy() @@ -243,6 +245,58 @@ describe('DirectoryBrowser', () => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + it('filters the child pane in two-pane mode and follows the draft back up a level', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(rowButton(screen.getByRole('listitem'))) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + // The seed comes from the selection, so the draft tail addresses the + // RIGHT pane (the selection's children). + expect(input.value).toBe(`${DOCS}/`) + fireEvent.change(input, { target: { value: `${DOCS}/h` } }) + expect(within(columns()[1]!).getByText('harness')).toBeTruthy() + fireEvent.change(input, { target: { value: `${DOCS}/zzz` } }) + expect(within(columns()[1]!).queryAllByRole('listitem')).toHaveLength(0) + expect(within(columns()[0]!).getByText('Documents')).toBeTruthy() + // Erasing back into the parent's own path moves the filter to the LEFT + // pane and releases the right one. + fireEvent.change(input, { target: { value: `${HOME}/zz` } }) + expect(within(columns()[0]!).queryAllByRole('listitem')).toHaveLength(0) + expect(within(columns()[1]!).getByText('harness')).toBeTruthy() + }) + + it('keeps the path editor open when blur comes from window focus loss', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + // A blur while the document itself lost focus (window switch, dev-tools + // focus) must not discard the draft. + const hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(false) + fireEvent.blur(input) + expect(screen.getByLabelText('browser.editPath', { selector: 'input' })).toBeTruthy() + hasFocus.mockRestore() + }) + + it('picking a filtered row adopts it and closes the path editor', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: `${HOME}/do` } }) + // The row suppresses focus steal on mousedown (no blur-cancel unmounts + // the filtered rows mid-gesture), then the click both selects the row + // and closes the editor. + const row = rowButton(screen.getByRole('listitem')) + fireEvent.mouseDown(row) + fireEvent.click(row) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + await waitFor(() => { expect(columns()).toHaveLength(2) }) + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + }) + it('seeds and filters with backslashes on a Windows-rooted listing', async () => { const ROOT = 'C:\\' const windowsListing: DirectoryListing = { From 27053efffceacf9330388c062a0dfdc29c516a85 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 14:47:40 +0800 Subject: [PATCH 07/34] =?UTF-8?q?fix(host):=20review=20round=202=20?= =?UTF-8?q?=E2=80=94=20dialog-scoped=20blur=20cancel,=20editing-only=20foc?= =?UTF-8?q?us=20hold,=20selection=20exempt=20from=20filters?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/client/DirectoryBrowser.module.css | 5 +- .../src/client/DirectoryBrowser.tsx | 53 ++++++++++------- .../tests/directory-browser.spec.tsx | 57 +++++++++++++++++-- 3 files changed, 89 insertions(+), 26 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 3b681de32a..d4fa986371 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -55,8 +55,9 @@ align-items: stretch; flex: 1 1 0; min-height: 0; - /* Columns already end in an 8px scrollbar clearance, so the divider only - * needs a slim gap of its own on each side. */ + /* 12px of row gap on each side of the divider; the left side reads wider + * by the column's trailing 8px scrollbar clearance, which is deliberate — + * the thumb needs that room, the right pane's rows do not. */ gap: 12px; overflow-x: auto; scrollbar-width: none; diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index b924c072bb..9c3dc66fbb 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -65,9 +65,12 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE } /** - * The listing's platform separator, read from the host-stamped home path — - * never sniffed from typed text or entry paths, where a backslash is a legal - * POSIX name character rather than a platform fact. + * The listing's platform separator, inferred from the home path the host + * stamped — never from typed text or entry paths, where a backslash is a + * legal POSIX name character. Still a heuristic at the last step: a POSIX + * home directory whose own name contains a backslash would misread. + * TODO: replace with a host-stamped `separator` field on the wire + * DirectoryListing so the platform fact travels verbatim. */ function separatorOf(listing: DirectoryListing): '\\' | '/' { return listing.home.includes('\\') ? '\\' : '/' @@ -91,15 +94,20 @@ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string } /** One column of folder rows (the Miller view renders one or two of these). */ -function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPrefix }: { +function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPrefix, pathEditing }: { entries: readonly DirectoryEntry[] selectedPath: string | null busy: boolean onPick: (entry: DirectoryEntry) => void showHidden: boolean filterPrefix: string | null + pathEditing: boolean }) { const visible = entries.filter((entry) => { + // The selection is exempt from both filters: it anchors the two-pane + // view (crumbs and the child pane point at it), so neither the hidden + // filter after a dot-reveal pick nor a prefix miss may orphan it. + if (entry.path === selectedPath) return true if (filterPrefix !== null && !entry.name.toLowerCase().startsWith(filterPrefix.toLowerCase())) return false // A dot-led prefix names hidden entries explicitly, so matching ones // surface even while the toggle keeps the rest hidden. @@ -118,10 +126,11 @@ function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPr aria-current={selected || undefined} className={clsx(css.row, selected && css.rowSelected)} disabled={busy} - // Keep focus where it is (the path editor, notably): a focus - // steal on mousedown would blur-cancel the editor, unmount the - // filtered rows mid-gesture, and drop this very click. - onMouseDown={(event) => { event.preventDefault() }} + // While the path editor is open, keep focus in it: a focus + // steal on mousedown would blur the editor and (in engines + // where the blur lands before our guards) drop this click. + // Outside editing, rows keep native focus behavior. + onMouseDown={pathEditing ? (event) => { event.preventDefault() } : undefined} onClick={() => { onPick(entry) }} > {selected @@ -457,16 +466,19 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, cancelPathEdit() } }} - // Clicking anywhere outside the editor reads as leaving it: - // focus loss cancels the edit like Escape. Enter keeps focus + // Focus leaving the DIALOG reads as leaving the editor and + // cancels like Escape. Three guarded non-cancel paths: window + // or tab focus loss (document no longer focused); a focus + // move that stays inside the dialog card (keyboard Tab onto + // the filtered rows or the footer toggle); and pointer paths, + // where rows and the toggle suppress focus steal on mousedown + // while editing so their click lands first. Enter keeps focus // in the input while its navigation is in flight, so a - // submitted path is never withdrawn by this handler; rows and - // the show-hidden toggle suppress focus steal on mousedown so - // a click on them lands before any cancel. Window/tab focus - // loss also fires blur in some engines — only a focus move - // within a focused document reads as leaving the editor. - onBlur={() => { + // submitted path is never withdrawn here. + onBlur={(event) => { if (!document.hasFocus()) return + if (event.relatedTarget instanceof HTMLElement + && event.relatedTarget.closest('[role="dialog"]') !== null) return cancelPathEdit() }} /> @@ -483,6 +495,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onPick={select} showHidden={showHidden} filterPrefix={draftPrefixFor(parent, pathDraft)} + pathEditing={draftPending} /> )} {twoPane && } @@ -494,6 +507,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onPick={advance} showHidden={showHidden} filterPrefix={draftPrefixFor(child, pathDraft)} + pathEditing={draftPending} /> )}
@@ -523,9 +537,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, aria-pressed={showHidden} disabled={parentInert} // The toggle composes with the path editor (dot-led prefixes and - // this filter interleave): don't steal focus, so toggling never - // blur-cancels a draft mid-thought. - onMouseDown={(event) => { event.preventDefault() }} + // this filter interleave): while editing, don't steal focus, so + // toggling never blur-cancels a draft mid-thought. Outside editing + // it keeps native focus behavior. + onMouseDown={draftPending ? (event) => { event.preventDefault() } : undefined} onClick={() => { setShowHidden(prev => !prev) }} > {showHidden && } 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 af3aff5385..419572734c 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -29,6 +29,18 @@ function listingFor(path?: string): DirectoryListing { ], truncated: false, }, + [`${HOME}/.config`]: { + path: `${HOME}/.config`, + home: HOME, + crumbs: [ + { name: '/', path: '/', hidden: false }, + { name: 'home', path: '/home', hidden: false }, + { name: 'u', path: HOME, hidden: false }, + { name: '.config', path: `${HOME}/.config`, hidden: true }, + ], + entries: [], + truncated: false, + }, [DOCS]: { path: DOCS, home: HOME, @@ -261,23 +273,58 @@ describe('DirectoryBrowser', () => { expect(within(columns()[1]!).queryAllByRole('listitem')).toHaveLength(0) expect(within(columns()[0]!).getByText('Documents')).toBeTruthy() // Erasing back into the parent's own path moves the filter to the LEFT - // pane and releases the right one. + // pane and releases the right one. The selected row is exempt (it + // anchors the two-pane view), so it alone survives the miss. fireEvent.change(input, { target: { value: `${HOME}/zz` } }) - expect(within(columns()[0]!).queryAllByRole('listitem')).toHaveLength(0) + expect(within(columns()[0]!).getAllByRole('listitem').map(item => item.textContent)).toEqual(['Documents']) expect(within(columns()[1]!).getByText('harness')).toBeTruthy() }) - it('keeps the path editor open when blur comes from window focus loss', async () => { + it('keeps the draft and filter through window focus loss and in-dialog focus moves', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: `${HOME}/do` } }) // A blur while the document itself lost focus (window switch, dev-tools - // focus) must not discard the draft. + // focus) must not discard the draft: value and filter both survive. const hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(false) fireEvent.blur(input) - expect(screen.getByLabelText('browser.editPath', { selector: 'input' })).toBeTruthy() hasFocus.mockRestore() + expect(screen.getByLabelText('browser.editPath', { selector: 'input' }).value).toBe(`${HOME}/do`) + expect(screen.getByRole('listitem').textContent).toBe('Documents') + // A keyboard focus move that stays inside the dialog (Tab onto the + // filtered row) keeps the draft too — the results stay reachable. + fireEvent.blur(input, { relatedTarget: rowButton(screen.getByRole('listitem')) }) + expect(screen.getByLabelText('browser.editPath', { selector: 'input' }).value).toBe(`${HOME}/do`) + // Toggling show-hidden mid-edit suppresses focus steal: the draft and + // its filter survive the toggle in both directions. + const toggle = screen.getByRole('button', { name: 'browser.showHidden' }) + fireEvent.mouseDown(toggle) + fireEvent.click(toggle) + expect(toggle.getAttribute('aria-pressed')).toBe('true') + expect(screen.getByLabelText('browser.editPath', { selector: 'input' }).value).toBe(`${HOME}/do`) + expect(screen.getByRole('listitem').textContent).toBe('Documents') + // Focus landing outside the dialog cancels like Escape. + fireEvent.blur(input, { relatedTarget: document.body }) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + }) + + it('a picked dot-revealed hidden row stays visible as the selection', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: `${HOME}/.co` } }) + const row = rowButton(screen.getByRole('listitem')) + expect(row.textContent).toBe('.config') + fireEvent.mouseDown(row) + fireEvent.click(row) + // The pick cleared the draft (and with it the dot-reveal), but the + // selection is exempt from the hidden filter: the anchor row survives. + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + await waitFor(() => { expect(columns()).toHaveLength(2) }) + expect(within(columns()[0]!).getByText('.config')).toBeTruthy() }) it('picking a filtered row adopts it and closes the path editor', async () => { From 355d505b89a763d65c9593387feeebb59d35a225 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 15:10:35 +0800 Subject: [PATCH 08/34] =?UTF-8?q?fix(host):=20review=20round=203=20?= =?UTF-8?q?=E2=80=94=20card-scope=20escape/focus-leave=20cancel,=20pick=20?= =?UTF-8?q?refocus;=20record=20display-policy=20trade-offs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 6 +- ...-28-directory-picker-capability-seam.zh.md | 6 +- .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../src/client/DirectoryBrowser.module.css | 10 +- .../src/client/DirectoryBrowser.tsx | 351 ++++++++++-------- .../tests/directory-browser.spec.tsx | 35 +- 9 files changed, 244 insertions(+), 176 deletions(-) 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 6f21a60e83..dc22b8f807 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: 3f5e1436f3af14ce06ffab00ceca90167e16afd0 -2026-07-28-directory-picker-capability-seam.zh.md: 09a3e20f7c12e3c22d63875091593f9a6ca8a1ad +2026-07-28-directory-picker-capability-seam.md: f633cd60b32c10e63814bf06a06773d2dba396f2 +2026-07-28-directory-picker-capability-seam.zh.md: b708e6fffa46cf51fd35154bfc2b947d955e5e9c 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 3f5e1436f3..f633cd60b3 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 @@ -18,7 +18,8 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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 (the browse client's footer toggle). Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. +- **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. - **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. @@ -30,6 +31,9 @@ Placement and policy rulings folded into this decision: - **One uniform seam method set (`pick(): path`).** Rejected: an in-app browser cannot be served behind a single host-side call — the browsing loop lives in the client and needs primitives on the wire; the native chooser cannot implement primitives. The interaction difference is irreducible, hence the discriminant. - **Direct stdlib calls inside apiproxy (no seam).** Rejected: keeps the gateway the only swap point (source edits), loses fixture/test backends, and contradicts the plugin doctrine that motivated the work. - **Adopting a file-manager/drive-enumeration dependency.** Rejected per the survey above; recorded here as the dependency policy requires. +- **A flip-label show-hidden toggle ("Hide hidden files").** Rejected: a flipping action label is ambiguous between state and action and doubles the negative; the fixed label with a pressed presentation states both at once. +- **Pure relatedTarget blur cancellation (no mousedown suppression).** Rejected: Safari does not focus buttons on pointer down, so a click's focusout carries a null `relatedTarget` and would cancel the editor before the click lands; editing-scoped mousedown suppression plus the card-anchored relatedTarget guard covers pointer and keyboard paths together. +- **A wire `separator` field on `DirectoryListing` (host stamps `path.sep`).** Deferred, not rejected: it is the authoritative form — a POSIX home directory containing a backslash defeats the `listing.home` heuristic — but it touches the seam type and every backend; the browse client's `separatorOf` carries a TODO pointing at this alternative until a wire change is next scheduled. ## Consequences 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 09a3e20f7c..b708e6fffa 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 @@ -18,7 +18,8 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 vs 引入)。** Node 标准库本身就是维护中的跨平台 OS 层(`readdir(withFileTypes)`、`homedir`、路径语义);调研过的替代品都过不了依赖门槛——文件管理器包(`node-file-manager`、`files-and-folders`、Syncfusion 的 provider)是整套 HTTP 应用(契合度不过),盘符工具(原生插件 `drivelist`、约七年未更的 `windows-drive-letters`)健康度/比例失当。browse 后端是标准库上的薄适配。 -- **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,"显示隐藏"开关正是作为这一纯客户端改动落地(browse 客户端的 footer 开关)。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 +- **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,"显示隐藏"开关正是作为这一纯客户端改动落地:标签固定的 footer 开关,其状态由按下态呈现承载(`aria-pressed` + 勾选符号);以点开头的路径草稿前缀会显出它所指名的隐藏条目;当前选中项则不受隐藏与前缀两种过滤影响(它锚定着双栏视图)。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从 `listing.home` 推断;下文的线上字段替代方案记录了被延期的权威形态。 - **符号链接:为可进入性而跟随。** 用 `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 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 @@ -30,6 +31,9 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **统一方法集的 seam(`pick(): path`)。** 否决:应用内浏览器无法藏在一次宿主侧调用后面——浏览循环在客户端,需要协议上的原语;而对话框实现不了原语。交互差异不可约,故用判别标签。 - **apiproxy 里直接调标准库(不建 seam)。** 否决:换装点仍是改网关源码,失去 fixture/测试后端,与促成这项工作的插件教义相悖。 - **引入文件管理器/盘符枚举依赖。** 按上文调研否决;依赖政策要求记录于此。 +- **动作标签随状态翻转的"显示隐藏"开关("隐藏隐藏文件")。** 否决:会翻转的动作标签在状态与动作之间有歧义,还把否定叠了两层;固定标签加按下态呈现一次说清两者。 +- **纯 relatedTarget 失焦取消(不做 mousedown 抑制)。** 否决:Safari 在指针按下时不给按钮聚焦,点击触发的 focusout 因而携带空 `relatedTarget`,会在点击落地前就取消编辑器;编辑期作用的 mousedown 抑制加上锚定卡片的 relatedTarget 守卫才能同时覆盖指针与键盘路径。 +- **在 `DirectoryListing` 上增设线上 `separator` 字段(宿主标注 `path.sep`)。** 延期而非否决:它才是权威形态——含反斜杠的 POSIX 家目录会击穿 `listing.home` 启发式——但它触及 seam 类型与每个后端;browse 客户端的 `separatorOf` 挂着指向本方案的 TODO,直到下次安排线上变更。 ## 后果 diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index eea9966b83..e59cd22b1e 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 95d2d66406210f4ba687ef5a45a38b142abd6f26 -README.zh.md: 9da374bec80f80085ff36871c227c496bb1fde7b +README.md: 7813e0e9c589d1f37471b08ebafcf08878cbf768 +README.zh.md: 46538ed6f1cf23357cc4f8e289a8117d0e5e017d diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 95d2d66406..7813e0e9c5 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -6,7 +6,7 @@ The **in-app browsing backend** of the [directory-picker seam](../directory-pick Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call returns at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings), and the level streams through a bounded window so memory stays O(maxEntries) no matter how many children the directory holds: a cut level keeps the name-sorted head, counts hidden rows against the bound, probes only windowed candidates, and reports `truncated: true` so the client can say the level is incomplete (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, and `list` threads the caller's `AbortSignal` so a disconnect or timeout stops the scan instead of letting it outlive the caller. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). -**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or focus loss; a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). +**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or when focus leaves the dialog card (window/tab switches and in-card focus moves keep the draft); a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches and the current selection exempt from both filters; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 9da374bec8..46538ed6f1 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -6,7 +6,7 @@ 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 -**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或失焦即取消;基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 +**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或焦点离开对话框卡片即取消(窗口/标签页切换与卡片内焦点移动保留草稿);基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项,且当前选中项不受这两种过滤影响;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index d4fa986371..e6f1daba98 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -155,7 +155,8 @@ flex: 1 1 0; min-width: 256px; overflow-y: auto; - /* The overlay scrollbar paints at the column's edge; keep the row pills + /* The themed scrollbar occupies the column's edge (styled scrollbars are + * classic, gutter-taking ones); the extra clearance keeps the row pills * clear of the thumb. */ padding-right: 8px; } @@ -283,6 +284,13 @@ color: var(--dsw-alias-label-primary); } +/* Card-scope wrapper hosting the path editor's Escape and focus-leave + * observers; display:contents keeps header/content/footer as direct flex + * children of the Modal card. */ +.editorScope { + display: contents; +} + .footerGap { flex: 1 1 0; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 9c3dc66fbb..37c3d33982 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -70,7 +70,8 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE * legal POSIX name character. Still a heuristic at the last step: a POSIX * home directory whose own name contains a backslash would misread. * TODO: replace with a host-stamped `separator` field on the wire - * DirectoryListing so the platform fact travels verbatim. + * DirectoryListing so the platform fact travels verbatim (the trade-off is + * recorded in the directory-picker capability seam Agent Note). */ function separatorOf(listing: DirectoryListing): '\\' | '/' { return listing.home.includes('\\') ? '\\' : '/' @@ -131,7 +132,13 @@ function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPr // where the blur lands before our guards) drop this click. // Outside editing, rows keep native focus behavior. onMouseDown={pathEditing ? (event) => { event.preventDefault() } : undefined} - onClick={() => { onPick(entry) }} + onClick={(event) => { + // A pick during editing is about to unmount the focused + // input; park focus on the picked row so keyboard traversal + // stays inside the dialog (the Modal has no focus trap). + if (pathEditing) event.currentTarget.focus() + onPick(entry) + }} > {selected ? @@ -386,177 +393,197 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, className={clsx(css.dialog)} headless > -
-

{t('browser.title')}

-
- {pathDraft === null - ? ( - <> - - {crumbs.map((crumb, index) => ( - - {index > 0 && } - - - ))} - - {/* The empty zone right of the crumbs is the path-edit affordance. */} - + + ))} + + {/* The empty zone right of the crumbs is the path-edit affordance. */} +
+
+
+
+ {parent !== null && ( + )} -
-
-
-
- {parent !== null && ( - - )} - {twoPane && } - {twoPane && child !== null && ( - - )} -
- {loading &&
{t('browser.loading')}
} - {/* The backend bounds a level at its complete-result limit; say so + {twoPane && } + {twoPane && child !== null && ( + + )} +
+ {loading &&
{t('browser.loading')}
} + {/* The backend bounds a level at its complete-result limit; say so * whenever a visible pane was cut instead of letting the tail of a * huge directory go silently missing. */} - {(parent?.truncated === true || child?.truncated === true) && !loading + {(parent?.truncated === true || child?.truncated === true) && !loading &&
{t('browser.truncated')}
} - {error !== null &&
{error}
} - -
- - - - - + {error !== null &&
{error}
} +
+
+ + + + + +
{/* Nested create dialog (figma 813:23278): names one folder inside the target. */} { // A blur while the document itself lost focus (window switch, dev-tools // focus) must not discard the draft: value and filter both survive. const hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(false) - fireEvent.blur(input) + fireEvent.focusOut(input) hasFocus.mockRestore() expect(screen.getByLabelText('browser.editPath', { selector: 'input' }).value).toBe(`${HOME}/do`) expect(screen.getByRole('listitem').textContent).toBe('Documents') // A keyboard focus move that stays inside the dialog (Tab onto the // filtered row) keeps the draft too — the results stay reachable. - fireEvent.blur(input, { relatedTarget: rowButton(screen.getByRole('listitem')) }) + fireEvent.focusOut(input, { relatedTarget: rowButton(screen.getByRole('listitem')) }) expect(screen.getByLabelText('browser.editPath', { selector: 'input' }).value).toBe(`${HOME}/do`) // Toggling show-hidden mid-edit suppresses focus steal: the draft and // its filter survive the toggle in both directions. @@ -305,9 +305,31 @@ describe('DirectoryBrowser', () => { expect(toggle.getAttribute('aria-pressed')).toBe('true') expect(screen.getByLabelText('browser.editPath', { selector: 'input' }).value).toBe(`${HOME}/do`) expect(screen.getByRole('listitem').textContent).toBe('Documents') - // Focus landing outside the dialog cancels like Escape. - fireEvent.blur(input, { relatedTarget: document.body }) + // Focus landing outside the dialog cancels like Escape — even when the + // departure happens from a row the user had Tabbed onto, not the input + // (the observer lives on the card scope, not the input). + fireEvent.focusOut(rowButton(screen.getByRole('listitem')), { relatedTarget: document.body }) expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + // Outside editing the card-scope observer is inert. + fireEvent.focusOut(screen.getByRole('button', { name: 'browser.showHidden' })) + expect(screen.getByRole('button', { name: 'browser.editPath' })).toBeTruthy() + }) + + it('Escape with focus on a filtered row collapses the editor, not the dialog', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: `${HOME}/do` } }) + // Tab parked focus on the result row; Escape must still mean "leave + // path editing", not "close the whole dialog". + const row = rowButton(screen.getByRole('listitem')) + fireEvent.keyDown(row, { key: 'Escape' }) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + expect(b.onClose).not.toHaveBeenCalled() + // With no draft left, Escape falls through to the Modal and closes. + fireEvent.keyDown(row, { key: 'Escape' }) + expect(b.onClose).toHaveBeenCalledTimes(1) }) it('a picked dot-revealed hidden row stays visible as the selection', async () => { @@ -340,6 +362,9 @@ describe('DirectoryBrowser', () => { fireEvent.mouseDown(row) fireEvent.click(row) expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + // Focus parks on the picked row (the editor's input just unmounted and + // the Modal has no focus trap to catch a fall to body). + expect(document.activeElement).toBe(row) await waitFor(() => { expect(columns()).toHaveLength(2) }) expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() }) @@ -373,7 +398,7 @@ describe('DirectoryBrowser', () => { const input = screen.getByLabelText('browser.editPath') fireEvent.change(input, { target: { value: '/somewhere/else' } }) // Focus moving anywhere outside the editor abandons the draft like Escape. - fireEvent.blur(input) + fireEvent.focusOut(input) expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() // The crumb view is back and the abandoned draft was never navigated to. expect(screen.getByRole('button', { name: 'browser.editPath' })).toBeTruthy() From 9c9c32ed59de8ee0762dcd2b04334a8e366538f6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 15:26:00 +0800 Subject: [PATCH 09/34] =?UTF-8?q?fix(host):=20review=20round=204=20?= =?UTF-8?q?=E2=80=94=20post-commit=20refocus=20covers=20right-pane=20picks?= =?UTF-8?q?;=20combobox=20semantics=20recorded=20as=20deferred?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +-- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../src/client/DirectoryBrowser.module.css | 14 ++++---- .../src/client/DirectoryBrowser.tsx | 35 ++++++++++++++----- .../tests/directory-browser.spec.tsx | 19 ++++++++++ 6 files changed, 56 insertions(+), 20 deletions(-) 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 dc22b8f807..e70ac895a0 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: f633cd60b32c10e63814bf06a06773d2dba396f2 -2026-07-28-directory-picker-capability-seam.zh.md: b708e6fffa46cf51fd35154bfc2b947d955e5e9c +2026-07-28-directory-picker-capability-seam.md: 550d51cf2e4e5b70b0844401d42bfea2342612e7 +2026-07-28-directory-picker-capability-seam.zh.md: afaf277e866349b20d370fe1fd638b0c71e1a3e7 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 f633cd60b3..550d51cf2e 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 @@ -19,7 +19,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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. +- **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. - **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 b708e6fffa..afaf277e86 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 @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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` 推断;下文的线上字段替代方案记录了被延期的权威形态。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从 `listing.home` 推断;下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。 - **符号链接:为可进入性而跟随。** 用 `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.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index e6f1daba98..2c09dd2940 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -15,6 +15,13 @@ gap: 0; } +/* Card-scope wrapper hosting the path editor's Escape and focus-leave + * observers; display:contents keeps header/content/footer as direct flex + * children of the Modal card. */ +.editorScope { + display: contents; +} + /* Header block: pl24 pr14 pt16 pb8, 8px between title row and crumb row. */ .header { display: flex; @@ -284,13 +291,6 @@ color: var(--dsw-alias-label-primary); } -/* Card-scope wrapper hosting the path editor's Escape and focus-leave - * observers; display:contents keeps header/content/footer as direct flex - * children of the Modal card. */ -.editorScope { - display: contents; -} - .footerGap { flex: 1 1 0; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 37c3d33982..bb0c4c5d7c 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -132,13 +132,11 @@ function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPr // where the blur lands before our guards) drop this click. // Outside editing, rows keep native focus behavior. onMouseDown={pathEditing ? (event) => { event.preventDefault() } : undefined} - onClick={(event) => { - // A pick during editing is about to unmount the focused - // input; park focus on the picked row so keyboard traversal - // stays inside the dialog (the Modal has no focus trap). - if (pathEditing) event.currentTarget.focus() - onPick(entry) - }} + // Editing-time focus parking happens after commit (the + // DirectoryBrowser refocus effect): a right-pane pick replaces + // this very column, so focusing the clicked node here would + // still fall to body. + onClick={() => { onPick(entry) }} > {selected ? @@ -235,11 +233,18 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [launchListing]) + // An editing-time pick parks focus on the selection after commit; the + // flag is set by select() and consumed by the refocus effect below the + // miller-row ref. + const refocusPick = useRef(false) + /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { const { seq, scan } = launchListing(entry.path) // A pick while the path editor is open adopts the (filtered) row and - // closes the editor — the draft served its purpose. + // closes the editor — the draft served its purpose. Focus re-parks on + // the selection after commit (see the refocus effect below). + if (pathDraft !== null) refocusPick.current = true setPathDraft(null) setSelected(entry) setChild(null) @@ -257,7 +262,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // breadcrumb still names the level: fall back to the single pane. setSelected(null) }) - }, [launchListing]) + }, [launchListing, pathDraft]) /** Abandon path editing (Escape or clicking away) and restore the crumb view. */ const cancelPathEdit = useCallback(() => { @@ -368,6 +373,18 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const row = millerRowRef.current if (row !== null && childPath !== undefined) row.scrollLeft = row.scrollWidth }, [childPath]) + // An editing-time pick unmounts the focused input, and a right-pane pick + // additionally replaces the picked button's whole column (advance swaps + // both panes): park focus on the selection's row — aria-current in the + // freshly rendered left pane — after commit, so keyboard traversal stays + // inside the dialog (the Modal has no focus trap). + useEffect(() => { + if (!refocusPick.current) return + refocusPick.current = false + /* v8 ignore next 2 -- narrowing guard: the pick that set the flag just rendered its aria-current row inside the miller row. */ + const row = millerRowRef.current?.querySelector('button[aria-current="true"]') + row?.focus() + }) if (!open) return null const twoPane = selected !== 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 550146df41..217ffa481e 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -369,6 +369,25 @@ describe('DirectoryBrowser', () => { expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() }) + it('a right-pane pick while editing parks focus on the advanced selection', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(rowButton(screen.getByRole('listitem'))) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: `${DOCS}/h` } }) + // The advance replaces BOTH panes (the picked button's own column + // unmounts), so focus is re-parked on the selection's aria-current row + // in the freshly rendered left pane rather than the clicked node. + const row = rowButton(within(columns()[1]!).getByRole('listitem')) + fireEvent.mouseDown(row) + fireEvent.click(row) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + await waitFor(() => { expect(document.activeElement?.textContent).toBe('harness') }) + expect(document.activeElement?.getAttribute('aria-current')).toBe('true') + }) + it('seeds and filters with backslashes on a Windows-rooted listing', async () => { const ROOT = 'C:\\' const windowsListing: DirectoryListing = { From 23b74c5d7daa1245fe1aae28a2ee7b2f0a5da362 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 15:38:52 +0800 Subject: [PATCH 10/34] =?UTF-8?q?fix(host):=20review=20round=205=20nits=20?= =?UTF-8?q?=E2=80=94=20refocus=20covers=20Enter/Escape=20exits;=20trailing?= =?UTF-8?q?=20pressed=20check;=20narrowed=20v8=20ignores?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/client/DirectoryBrowser.tsx | 69 +++++++++++++++---- .../tests/directory-browser.spec.tsx | 8 +++ 2 files changed, 62 insertions(+), 15 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index bb0c4c5d7c..52211bed4a 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -233,10 +233,15 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [launchListing]) - // An editing-time pick parks focus on the selection after commit; the - // flag is set by select() and consumed by the refocus effect below the - // miller-row ref. + // 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. const refocusPick = useRef(false) + const refocusEditZone = useRef(false) + const pathInputRef = useRef(null) + const editZoneRef = useRef(null) /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { @@ -373,17 +378,33 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const row = millerRowRef.current if (row !== null && childPath !== undefined) row.scrollLeft = row.scrollWidth }, [childPath]) - // An editing-time pick unmounts the focused input, and a right-pane pick - // additionally replaces the picked button's whole column (advance swaps - // both panes): park focus on the selection's row — aria-current in the - // freshly rendered left pane — after commit, so keyboard traversal stays - // inside the dialog (the Modal has no focus trap). + // Every editor exit that would drop focus to body re-parks it after + // commit, so keyboard traversal stays inside the dialog (the Modal has no + // focus trap): a pick lands on the selection's row — aria-current in the + // freshly rendered left pane, which survives even a right-pane advance + // replacing the picked button's column — while Enter and an input-focused + // Escape land on the crumb edit zone that replaces the input. useEffect(() => { - if (!refocusPick.current) return - refocusPick.current = false - /* v8 ignore next 2 -- narrowing guard: the pick that set the flag just rendered its aria-current row inside the miller row. */ - const row = millerRowRef.current?.querySelector('button[aria-current="true"]') - row?.focus() + if (pathDraft !== null) return + if (refocusPick.current) { + refocusPick.current = false + refocusEditZone.current = false + const rowHost = millerRowRef.current + /* v8 ignore next -- narrowing guard: the miller row is mounted whenever a pick just committed. */ + if (rowHost === null) return + const row = rowHost.querySelector('button[aria-current="true"]') + /* v8 ignore next -- narrowing guard: the pick that set the flag just rendered its aria-current row. */ + if (row === null) return + row.focus() + return + } + if (refocusEditZone.current) { + refocusEditZone.current = false + const zone = editZoneRef.current + /* v8 ignore next -- narrowing guard: crumb mode renders the edit zone whenever the editor just closed. */ + if (zone === null) return + zone.focus() + } }) if (!open) return null @@ -424,6 +445,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // document listener — the same containment the input previously // provided for itself. event.stopPropagation() + // Escape while the input holds focus is about to unmount it; with + // focus already parked on a row, that row survives the cancel and + // keeps focus naturally. + if (document.activeElement === pathInputRef.current) refocusEditZone.current = true cancelPathEdit() }} // Focus leaving THIS dialog card while editing cancels like Escape. @@ -442,6 +467,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, /* v8 ignore next -- narrowing guard: this scope always renders inside the Modal card. */ if (card === null) return if (event.relatedTarget instanceof Node && card.contains(event.relatedTarget)) return + // The user moved focus out of the card themselves: cancel without + // re-parking (a lingering Enter-failure flag must not yank focus + // back either). + refocusEditZone.current = false cancelPathEdit() }} > @@ -475,6 +504,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // listing itself fails, typing an absolute path is the one // remaining way forward. disabled={parentInert} + ref={editZoneRef} onClick={() => { // Opening the editor supersedes any pending listing: a // settlement landing before the first keystroke would @@ -502,6 +532,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, value={pathDraft} aria-label={t('browser.editPath')} autoFocus + ref={pathInputRef} disabled={parentInert} onChange={(event) => { // Editing the draft supersedes any in-flight navigation: @@ -521,7 +552,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // Trim only detects a blank draft; the Host gets the // original text — a real directory name may end in // whitespace, and trimming would list its sibling. - if (pathDraft.trim() !== '') navigate(pathDraft) + if (pathDraft.trim() !== '') { + // Success will unmount the still-focused input; park + // focus on the returning crumb edit zone (a failure + // keeps the editor, so the flag waits until close). + refocusEditZone.current = true + navigate(pathDraft) + } } }} /> @@ -586,8 +623,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onMouseDown={draftPending ? (event) => { event.preventDefault() } : undefined} onClick={() => { setShowHidden(prev => !prev) }} > - {showHidden && } {t('browser.showHidden')} + {/* Trailing check (Menu's selected vocabulary): the label never + * shifts when the pressed state toggles. */} + {showHidden && } 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 217ffa481e..06f8b78a3f 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -227,6 +227,9 @@ describe('DirectoryBrowser', () => { fireEvent.keyDown(input, { key: 'Enter' }) await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) expect(columns()).toHaveLength(1) + // The submitted navigation unmounted the focused input; focus parks on + // the crumb edit zone that replaced it. + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) const again = screen.getByLabelText('browser.editPath') fireEvent.change(again, { target: { value: ' ' } }) @@ -234,6 +237,8 @@ describe('DirectoryBrowser', () => { expect(b.listDirectory).toHaveBeenCalledTimes(2) fireEvent.keyDown(again, { key: 'Escape' }) expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + // Escape with focus in the input parks focus on the returning edit zone. + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) }) it('prefix-filters the listed level from the draft tail, dot revealing hidden matches', async () => { @@ -324,9 +329,12 @@ describe('DirectoryBrowser', () => { // Tab parked focus on the result row; Escape must still mean "leave // path editing", not "close the whole dialog". const row = rowButton(screen.getByRole('listitem')) + row.focus() fireEvent.keyDown(row, { key: 'Escape' }) expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() expect(b.onClose).not.toHaveBeenCalled() + // Focus was already on a surviving row, so nothing re-parks it. + expect(document.activeElement).toBe(row) // With no draft left, Escape falls through to the Modal and closes. fireEvent.keyDown(row, { key: 'Escape' }) expect(b.onClose).toHaveBeenCalledTimes(1) From a1d752f79958d63e4d1ce3e28af37e04c2b790cb Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 21:12:04 +0800 Subject: [PATCH 11/34] =?UTF-8?q?feat(host):=20navigations=20land=20select?= =?UTF-8?q?ion-anchored=20=E2=80=94=20crumb=20jumps=20step=20back=20a=20pa?= =?UTF-8?q?ne=20instead=20of=20collapsing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 1 + ...-28-directory-picker-capability-seam.zh.md | 1 + apps/web/tests/workspace-flow.snapshot.ts | 6 + .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 52 +++++++-- .../tests/directory-browser.spec.tsx | 108 +++++++++++++++++- 9 files changed, 160 insertions(+), 20 deletions(-) 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 e70ac895a0..e270a79a11 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: 550d51cf2e4e5b70b0844401d42bfea2342612e7 -2026-07-28-directory-picker-capability-seam.zh.md: afaf277e866349b20d370fe1fd638b0c71e1a3e7 +2026-07-28-directory-picker-capability-seam.md: 51d71d15cb5144d555a5b156d9b108d7a2ad41b8 +2026-07-28-directory-picker-capability-seam.zh.md: 60bc14c13d1e4655faefbd5eaa63469119bf0ca3 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 550d51cf2e..51d71d15cb 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,6 +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.** Away from the display root, the browse client's navigate (a crumb jump or a submitted path) lists the target's parent level with the target selected and its children on the right — two panes throughout, so a crumb jump reads as stepping back one pane rather than collapsing to a single column. The display root (home, or a rootward chain with no parent crumb) keeps the single wide level; the parent leg runs under the same supersession scope as the landing, and its failure falls back to the single-pane landing quietly — the target listed fine, and nobody asked to see the parent. - **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 afaf277e86..60bc14c13d 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,6 +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、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。 +- **导航以选中项为锚落地。** 在展示根之外,browse 客户端的导航(crumb 跳转或提交的路径)列出目标的父层级,选中目标并在右侧展示其子项——全程双栏,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。展示根(home,或没有父 crumb 的抵根链)保持单个宽层级;父层级这一程与落地共用同一 supersession 范围,其失败会静默回退到单栏落地——目标本身列举无误,本也没有人要求查看父层级。 - **符号链接:为可进入性而跟随。** 用 `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/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index 32d44b6fff..2ed00f7cbf 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -202,6 +202,12 @@ it('adopts a directory through the composed in-app browse flow and lands in its // row's name span is stable (clicks bubble to the row button). fireEvent.click(await within(dialog).findByText('Documents', {}, { timeout: 10_000 })) fireEvent.click(await within(dialog).findByText('project', {}, { timeout: 10_000 })) + // A crumb jump away from the root steps BACK one pane instead of + // collapsing: Documents lands selected in the home level (Downloads is + // the home-level marker) with its children still on the right. + fireEvent.click(within(dialog).getByRole('button', { name: 'Documents' })) + await within(dialog).findByText('Downloads', {}, { timeout: 10_000 }) + fireEvent.click(await within(dialog).findByText('project', {}, { timeout: 10_000 })) // Open disables while the selection's child listing is in flight; wait for // the enabled state or the click lands on a dead button on slow runners. await waitFor(() => { diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index e59cd22b1e..842e91481c 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 7813e0e9c589d1f37471b08ebafcf08878cbf768 -README.zh.md: 46538ed6f1cf23357cc4f8e289a8117d0e5e017d +README.md: 51e27115b5179796810c19b618b08a3523de8d10 +README.zh.md: 4caeff1c2ebfea2c12e6bb598dae2c34f2e34d84 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 7813e0e9c5..51e27115b5 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -6,7 +6,7 @@ The **in-app browsing backend** of the [directory-picker seam](../directory-pick Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call returns at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings), and the level streams through a bounded window so memory stays O(maxEntries) no matter how many children the directory holds: a cut level keeps the name-sorted head, counts hidden rows against the bound, probes only windowed candidates, and reports `truncated: true` so the client can say the level is incomplete (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, and `list` threads the caller's `AbortSignal` so a disconnect or timeout stops the scan instead of letting it outlive the caller. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). -**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or when focus leaves the dialog card (window/tab switches and in-card focus moves keep the draft); a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches and the current selection exempt from both filters; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). +**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view whose navigations land selection-anchored: a crumb jump or a submitted path lists the target's parent level with the target selected, so stepping back keeps two panes while the display root keeps the single wide level; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or when focus leaves the dialog card (window/tab switches and in-card focus moves keep the draft); a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches and the current selection exempt from both filters; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 46538ed6f1..4caeff1c2e 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -6,7 +6,7 @@ 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 -**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或焦点离开对话框卡片即取消(窗口/标签页切换与卡片内焦点移动保留草稿);基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项,且当前选中项不受这两种过滤影响;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 +**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图,其导航以选中项为锚落地:crumb 跳转或提交的路径会列出目标的父层级并选中目标,因此后退仍保持双栏,而展示根保持单个宽层级;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或焦点离开对话框卡片即取消(窗口/标签页切换与卡片内焦点移动保留草稿);基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项,且当前选中项不受这两种过滤影响;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 52211bed4a..ba0502fc65 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -214,24 +214,60 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, return { seq, scan: listDirectory(path, controller.signal) } }, [supersede, listDirectory]) - /** Replace the whole view with one freshly listed level (no selection). */ + /** + * Replace the whole view with a freshly navigated level. Away from the + * display root the landing keeps the navigated directory SELECTED inside + * its parent level (left pane = parent, right pane = its children), so a + * crumb jump or a submitted path reads as stepping back one pane instead + * of collapsing to a single column; the display root (the home level, or + * a chain with no parent) keeps the single wide level. + */ const navigate = useCallback((path?: string) => { const { seq, scan } = launchListing(path) setLoading(true) setError(null) - scan.then((next) => { + scan.then((target) => { if (seq !== requestSeq.current) return - setParent(next) - setSelected(null) - setChild(null) - setLoading(false) - setPathDraft(null) + const parentCrumb = target.crumbs.at(-2) + const anchor = target.crumbs.at(-1) + if (target.path === target.home || parentCrumb === undefined + /* v8 ignore next -- narrowing: the anchor crumb exists whenever a parent crumb does (root-to-target inclusive chain). */ + || anchor === undefined) { + setParent(target) + setSelected(null) + setChild(null) + setLoading(false) + setPathDraft(null) + return + } + // Two-pane landing: the parent leg runs under the same supersession + // scope (a newer intent aborts it like the first leg). + const controller = new AbortController() + scanController.current = controller + listDirectory(parentCrumb.path, controller.signal).then((parentLevel) => { + if (seq !== requestSeq.current) return + setParent(parentLevel) + setSelected(anchor) + setChild(target) + setLoading(false) + setPathDraft(null) + }, () => { + if (seq !== requestSeq.current) return + // The target listed fine and is what the user asked for; a parent + // leg failure quietly falls back to the single-pane landing rather + // than surfacing an error for a level nobody requested. + setParent(target) + setSelected(null) + setChild(null) + setLoading(false) + setPathDraft(null) + }) }, (reason: unknown) => { if (seq !== requestSeq.current) return setLoading(false) setError(failureText(reason)) }) - }, [launchListing]) + }, [launchListing, listDirectory]) // 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 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 06f8b78a3f..ab60efcc5d 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -29,6 +29,13 @@ function listingFor(path?: string): DirectoryListing { ], truncated: false, }, + '/': { + path: '/', + home: HOME, + crumbs: [{ name: '/', path: '/', hidden: false }], + entries: [{ name: 'home', path: '/home', hidden: false }], + truncated: false, + }, [`${HOME}/.config`]: { path: `${HOME}/.config`, home: HOME, @@ -198,6 +205,88 @@ describe('DirectoryBrowser', () => { expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBeNull() }) + it('a crumb jump away from the root lands two-pane with the target selected', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(rowButton(screen.getByRole('listitem'))) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + fireEvent.click(rowButton(within(columns()[1]!).getByRole('listitem'))) + await waitFor(() => { expect(screen.getByRole('button', { name: 'harness' })).toBeTruthy() }) + // Jumping to the Documents crumb is a step BACK one pane, not a + // collapse: Documents stays selected in the home level, its children + // stay on the right. + fireEvent.click(screen.getByRole('button', { name: 'Documents' })) + await waitFor(() => { + expect(rowButton(within(columns()[0]!).getByRole('listitem')).getAttribute('aria-current')).toBe('true') + }) + expect(columns()).toHaveLength(2) + expect(within(columns()[0]!).getByText('Documents')).toBeTruthy() + expect(within(columns()[1]!).getByText('harness')).toBeTruthy() + }) + + it('a navigation to the filesystem root keeps the single wide level', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + fireEvent.change(screen.getByLabelText('browser.editPath'), { target: { value: '/' } }) + fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Enter' }) + // A one-crumb chain has no parent level to show on the left. + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('home') }) + expect(columns()).toHaveLength(1) + }) + + it('drops a parent leg that settles after a newer intent, resolving or rejecting', async () => { + const settlers: { resolve: (value: DirectoryListing) => void; reject: (reason: unknown) => void }[] = [] + const listDirectory = vi.fn(async (path?: string) => { + if (path === HOME) { + return new Promise((resolve, reject) => { settlers.push({ resolve, reject }) }) + } + return listingFor(path) + }) + mount({ listDirectory }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + // Enter lands the target leg; the parent leg hangs. Escape supersedes + // the landing, and the late parent RESOLUTION must change nothing. + 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' }) + await waitFor(() => { expect(settlers).toHaveLength(1) }) + fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' }) + await act(async () => { settlers[0]!.resolve(listingFor(HOME)) }) + expect(columns()).toHaveLength(1) + expect(screen.getByRole('listitem').textContent).toBe('Documents') + // Same shape, late parent REJECTION: equally silent. + 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' }) + await waitFor(() => { expect(settlers).toHaveLength(2) }) + fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' }) + await act(async () => { settlers[1]!.reject(new Error('late')) }) + expect(columns()).toHaveLength(1) + expect(screen.queryByRole('alert')).toBeNull() + }) + + it('falls back to the single-pane landing when the parent leg of a navigation fails', async () => { + const listDirectory = vi.fn(async (path?: string) => { + // The initial open lists home through the absent-path form; only the + // parent leg names HOME explicitly. + if (path === HOME) { + throw new DirectoryBrowseError({ code: 'directory-unreadable', message: 'parent gone', details: { path } }) + } + 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 target listed fine; the failed parent leg neither blocks the + // landing nor surfaces an error for a level nobody asked to see. + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + expect(columns()).toHaveLength(1) + expect(screen.queryByRole('alert')).toBeNull() + }) + it('opens the selection, else the listed level; Cancel closes; busy freezes Open', async () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) @@ -225,8 +314,11 @@ describe('DirectoryBrowser', () => { expect(input.value).toBe(`${HOME}/`) fireEvent.change(input, { target: { value: DOCS } }) fireEvent.keyDown(input, { key: 'Enter' }) - await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) - expect(columns()).toHaveLength(1) + // Away from the root a navigation lands two-pane: the target selected + // in its parent level, its own children on the right. + await waitFor(() => { expect(columns()).toHaveLength(2) }) + expect(rowButton(within(columns()[0]!).getByRole('listitem')).getAttribute('aria-current')).toBe('true') + expect(within(columns()[1]!).getByText('harness')).toBeTruthy() // The submitted navigation unmounted the focused input; focus parks on // the crumb edit zone that replaced it. expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) @@ -234,7 +326,9 @@ describe('DirectoryBrowser', () => { const again = screen.getByLabelText('browser.editPath') fireEvent.change(again, { target: { value: ' ' } }) fireEvent.keyDown(again, { key: 'Enter' }) - expect(b.listDirectory).toHaveBeenCalledTimes(2) + // Initial home + the DOCS target leg + its parent leg; the blank draft + // added none. + expect(b.listDirectory).toHaveBeenCalledTimes(3) fireEvent.keyDown(again, { key: 'Escape' }) expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() // Escape with focus in the input parks focus on the returning edit zone. @@ -945,11 +1039,13 @@ describe('DirectoryBrowser', () => { b.listDirectory.mockReturnValueOnce(slow) fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) fireEvent.click(within(screen.getByRole('navigation')).getByRole('button', { name: 'Documents' })) - await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + // The newer jump lands two-pane: Documents selected at home, children right. + await waitFor(() => { expect(within(columns()[1]!).getByText('harness')).toBeTruthy() }) resolveSlow(listingFor(undefined)) await new Promise(settle => setTimeout(settle, 0)) - // The stale home listing did not replace the newer Documents level. - expect(screen.getByRole('listitem').textContent).toBe('harness') + // The stale home listing did not replace the newer Documents landing. + expect(columns()).toHaveLength(2) + expect(within(columns()[1]!).getByText('harness')).toBeTruthy() }) it('names the create target by its path when the level reports no crumbs', async () => { From eac3b378fa8b8aac919403dd146e05ea8648dc60 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 21:34:30 +0800 Subject: [PATCH 12/34] =?UTF-8?q?fix(host):=20review=20round=206=20?= =?UTF-8?q?=E2=80=94=20progressive=20selection-anchored=20landing;=20ancho?= =?UTF-8?q?r=20on=20actual=20parent=20entries;=20focus-flag=20hygiene?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../src/client/DirectoryBrowser.module.css | 5 +- .../src/client/DirectoryBrowser.tsx | 98 ++++++++------ .../tests/directory-browser.spec.tsx | 127 +++++++++++++++--- 9 files changed, 182 insertions(+), 64 deletions(-) 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 e270a79a11..900e1d01b6 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: 51d71d15cb5144d555a5b156d9b108d7a2ad41b8 -2026-07-28-directory-picker-capability-seam.zh.md: 60bc14c13d1e4655faefbd5eaa63469119bf0ca3 +2026-07-28-directory-picker-capability-seam.md: ad2aa904beddb2fe941883c3c1827702dbec9964 +2026-07-28-directory-picker-capability-seam.zh.md: 30e719ad9b4e8374496106b447e961a042c7d8b6 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 51d71d15cb..ad2aa904be 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.** Away from the display root, the browse client's navigate (a crumb jump or a submitted path) lists the target's parent level with the target selected and its children on the right — two panes throughout, so a crumb jump reads as stepping back one pane rather than collapsing to a single column. The display root (home, or a rootward chain with no parent crumb) keeps the single wide level; the parent leg runs under the same supersession scope as the landing, and its failure falls back to the single-pane landing quietly — the target listed fine, and nobody asked to see the parent. +- **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. - **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 60bc14c13d..30e719ad9b 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、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。 -- **导航以选中项为锚落地。** 在展示根之外,browse 客户端的导航(crumb 跳转或提交的路径)列出目标的父层级,选中目标并在右侧展示其子项——全程双栏,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。展示根(home,或没有父 crumb 的抵根链)保持单个宽层级;父层级这一程与落地共用同一 supersession 范围,其失败会静默回退到单栏落地——目标本身列举无误,本也没有人要求查看父层级。 +- **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。 - **符号链接:为可进入性而跟随。** 用 `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/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 842e91481c..d807bd737a 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 51e27115b5179796810c19b618b08a3523de8d10 -README.zh.md: 4caeff1c2ebfea2c12e6bb598dae2c34f2e34d84 +README.md: 23153881b84dcb71dfb05d4f297a5818c410ca77 +README.zh.md: d7010e2941a801ba6358082824330eaae46e42b7 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 51e27115b5..23153881b8 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -6,7 +6,7 @@ The **in-app browsing backend** of the [directory-picker seam](../directory-pick Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call returns at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings), and the level streams through a bounded window so memory stays O(maxEntries) no matter how many children the directory holds: a cut level keeps the name-sorted head, counts hidden rows against the bound, probes only windowed candidates, and reports `truncated: true` so the client can say the level is incomplete (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, and `list` threads the caller's `AbortSignal` so a disconnect or timeout stops the scan instead of letting it outlive the caller. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). -**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view whose navigations land selection-anchored: a crumb jump or a submitted path lists the target's parent level with the target selected, so stepping back keeps two panes while the display root keeps the single wide level; breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or when focus leaves the dialog card (window/tab switches and in-card focus moves keep the draft); a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches and the current selection exempt from both filters; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). +**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view whose navigations land selection-anchored: a crumb jump or a submitted path commits the target immediately, then re-selects its actual entry in its parent level once that level arrives — two panes, so stepping back never collapses (a failed or truncated parent leg keeps the single-pane landing; the display root keeps the single wide level); breadcrumb with a click-to-edit path zone whose editor seeds a trailing separator, prefix-filters the listed level from the draft's final segment while typing (case-insensitively, over the listed — possibly truncated — rows only; Enter still navigates by the exact text), and cancels on Escape or when focus leaves the dialog card (window/tab switches and in-card focus moves keep the draft); a fixed-label show-hidden footer toggle over the host's `hidden` flags, with a dot-led typed prefix revealing its matches and the current selection exempt from both filters; nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 4caeff1c2e..d7010e2941 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -6,7 +6,7 @@ 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 -**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图,其导航以选中项为锚落地:crumb 跳转或提交的路径会列出目标的父层级并选中目标,因此后退仍保持双栏,而展示根保持单个宽层级;带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或焦点离开对话框卡片即取消(窗口/标签页切换与卡片内焦点移动保留草稿);基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项,且当前选中项不受这两种过滤影响;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 +**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图,其导航以选中项为锚落地:crumb 跳转或提交的路径会立即提交目标,待父层级到达后再在其中重新选中目标的实际条目——双栏,因此后退绝不塌缩(父层级这一程失败或被截断时保持单栏落地;展示根保持单个宽层级);带点击即编辑路径区的面包屑,其编辑器预填尾随分隔符、输入时以草稿末段对所列层级做前缀过滤(不区分大小写,且仅作用于已列出、可能被截断的行;Enter 仍按确切文本导航)、按 Escape 或焦点离开对话框卡片即取消(窗口/标签页切换与卡片内焦点移动保留草稿);基于宿主 `hidden` 标志、标签固定的"显示隐藏"footer 开关,键入以点开头的前缀会显出其匹配项,且当前选中项不受这两种过滤影响;嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 2c09dd2940..85349962e5 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -261,8 +261,9 @@ } /* Show-hidden toggle: a subtle fixed-label text button left of the gap; - * the pressed state seats a check glyph before the label (Menu's selected - * vocabulary) instead of flipping the wording. */ + * the pressed state seats a check glyph after the label (Menu's selected + * vocabulary; trailing so the label never shifts) instead of flipping the + * wording. */ .showHiddenToggle { display: inline-flex; align-items: center; diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index ba0502fc65..859667d115 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -5,7 +5,10 @@ * breadcrumb, and a click-to-edit path zone; below it a Miller view — one * full-width level until a row is selected, then two columns splitting the * row evenly (256px floor; level | selected folder's children) around a - * hairline divider. Selecting in the + * hairline divider. Navigations land selection-anchored: a crumb jump or a + * submitted path commits the target immediately, then re-selects it in its + * parent level once that level arrives, so stepping back keeps two panes + * away from the display root. Selecting in the * right column shifts the view one level deeper. "New folder" opens a nested * create dialog targeting the selected folder (or the level itself) and * selects the created folder. Open adopts the selected folder, falling back @@ -215,12 +218,27 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [supersede, listDirectory]) /** - * Replace the whole view with a freshly navigated level. Away from the - * display root the landing keeps the navigated directory SELECTED inside - * its parent level (left pane = parent, right pane = its children), so a - * crumb jump or a submitted path reads as stepping back one pane instead - * of collapsing to a single column; the display root (the home level, or - * a chain with no parent) keeps the single wide level. + * Launch a follow-up listing under the CURRENT supersession seq: a newer + * intent aborts it like the leg it continues, and it supersedes nothing. + */ + const continueScan = useCallback((path: string): Promise => { + const controller = new AbortController() + scanController.current = controller + return listDirectory(path, controller.signal) + }, [listDirectory]) + + /** + * Replace the whole view with a freshly navigated level. The target level + * commits the moment it arrives (single wide level: the editor closes and + * loading ends on this first settlement, so an Enter-submitted navigation + * is never withdrawn waiting on anything further). Away from the display + * root — the same collapse the crumb header renders, so crumbs and pane + * 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. */ const navigate = useCallback((path?: string) => { const { seq, scan } = launchListing(path) @@ -228,46 +246,38 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setError(null) scan.then((target) => { if (seq !== requestSeq.current) return + setParent(target) + setSelected(null) + setChild(null) + setLoading(false) + setPathDraft(null) + // Arity is label-independent: only the collapsed chain's depth decides. + if (displayCrumbs(target, '').length < 2) return const parentCrumb = target.crumbs.at(-2) - const anchor = target.crumbs.at(-1) - if (target.path === target.home || parentCrumb === undefined - /* v8 ignore next -- narrowing: the anchor crumb exists whenever a parent crumb does (root-to-target inclusive chain). */ - || anchor === undefined) { - setParent(target) - setSelected(null) - setChild(null) - setLoading(false) - setPathDraft(null) - return - } - // Two-pane landing: the parent leg runs under the same supersession - // scope (a newer intent aborts it like the first leg). - const controller = new AbortController() - scanController.current = controller - listDirectory(parentCrumb.path, controller.signal).then((parentLevel) => { + /* v8 ignore next -- narrowing: a two-deep display chain implies a parent crumb (root-to-target inclusive). */ + if (parentCrumb === undefined) return + 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) + const match = parentLevel.entries.find(entry => fold(entry.path) === fold(target.path)) + if (match === undefined) return setParent(parentLevel) - setSelected(anchor) + setSelected(match) setChild(target) - setLoading(false) - setPathDraft(null) }, () => { - if (seq !== requestSeq.current) return - // The target listed fine and is what the user asked for; a parent - // leg failure quietly falls back to the single-pane landing rather - // than surfacing an error for a level nobody requested. - setParent(target) - setSelected(null) - setChild(null) - setLoading(false) - setPathDraft(null) + // Swallows the parent-leg failure (its abort included): the + // committed single-pane landing stands, and nobody asked to see + // the parent level. }) }, (reason: unknown) => { if (seq !== requestSeq.current) return setLoading(false) setError(failureText(reason)) }) - }, [launchListing, listDirectory]) + }, [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 @@ -302,6 +312,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // An unreadable selection cannot be the committing target while the // breadcrumb still names the level: fall back to the single pane. setSelected(null) + // Clearing the selection can unmount the very row the pick parked + // focus on (a dot-revealed hidden row re-hides); the refocus effect + // re-parks on the edit zone only if focus actually fell to body. + refocusEditZone.current = true }) }, [launchListing, pathDraft]) @@ -350,6 +364,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setPathDraft(null) setFolderDraft(null) setCreateError(null) + // A close mid-flight (failed Enter, then Cancel) may leave refocus + // flags armed; retire them so a later render cannot consume them. + refocusPick.current = false + refocusEditZone.current = false }, [open, navigate, supersede]) /** The folder a create or Open acts on: the selection, else the listed level. */ @@ -436,6 +454,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, } if (refocusEditZone.current) { refocusEditZone.current = false + // Re-park only when the close actually dropped focus to body; focus + // the user parked elsewhere (a surviving row) stays theirs. + if (document.activeElement !== document.body) return const zone = editZoneRef.current /* v8 ignore next -- narrowing guard: crumb mode renders the edit zone whenever the editor just closed. */ if (zone === null) return @@ -483,8 +504,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, event.stopPropagation() // Escape while the input holds focus is about to unmount it; with // focus already parked on a row, that row survives the cancel and - // keeps focus naturally. - if (document.activeElement === pathInputRef.current) refocusEditZone.current = true + // keeps focus naturally. Assignment (not a conditional set) also + // retires a stale flag a failed or still-upgrading Enter left. + refocusEditZone.current = document.activeElement === pathInputRef.current cancelPathEdit() }} // Focus leaving THIS dialog card while editing cancels like Escape. 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 ab60efcc5d..6fa9bb999f 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -194,7 +194,7 @@ describe('DirectoryBrowser', () => { expect(signals[2]?.aborted).toBe(true) }) - it('jumps back through a crumb into a fresh single-column level', async () => { + it('a crumb jump to the display root (home) lands the single wide level', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) fireEvent.click(rowButton(screen.getByRole('listitem'))) @@ -235,35 +235,130 @@ describe('DirectoryBrowser', () => { expect(columns()).toHaveLength(1) }) - it('drops a parent leg that settles after a newer intent, resolving or rejecting', async () => { - const settlers: { resolve: (value: DirectoryListing) => void; reject: (reason: unknown) => void }[] = [] - const listDirectory = vi.fn(async (path?: string) => { - if (path === HOME) { - return new Promise((resolve, reject) => { settlers.push({ resolve, reject }) }) + it('commits the target immediately, aborts a superseded parent leg on the wire, and drops its late resolution', async () => { + const signals: (AbortSignal | undefined)[] = [] + const settlers: ((value: DirectoryListing) => void)[] = [] + // Only the FIRST explicit HOME request (the parent leg) hangs; the later + // home crumb jump lists normally. + let homeCalls = 0 + const listDirectory = vi.fn(async (path?: string, signal?: AbortSignal) => { + signals.push(signal) + if (path === HOME && ++homeCalls === 1) { + return new Promise((resolve) => { settlers.push(resolve) }) } return listingFor(path) }) mount({ listDirectory }) await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) - // Enter lands the target leg; the parent leg hangs. Escape supersedes - // the landing, and the late parent RESOLUTION must change nothing. 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 target leg commits at once: editor closed, single-pane DOCS level, + // while the parent leg (upgrade) is still in flight. + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + expect(columns()).toHaveLength(1) await waitFor(() => { expect(settlers).toHaveLength(1) }) - fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' }) - await act(async () => { settlers[0]!.resolve(listingFor(HOME)) }) + // A newer jump aborts the pending parent leg ON THE WIRE, not merely + // dropping its settlement. + fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) + expect(signals[2]?.aborted).toBe(true) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + // Its late resolution changes nothing either. + await act(async () => { settlers[0]!(listingFor(HOME)) }) expect(columns()).toHaveLength(1) - expect(screen.getByRole('listitem').textContent).toBe('Documents') - // Same shape, late parent REJECTION: equally silent. + expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBeNull() + }) + + 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 + // that misses Documents (the initial open uses the absent-path form). + if (path === HOME) return { ...listingFor(HOME), entries: [], truncated: true } + 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' }) - await waitFor(() => { expect(settlers).toHaveLength(2) }) - fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' }) - await act(async () => { settlers[1]!.reject(new Error('late')) }) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + // The upgrade would orphan the selection (no source row): it stays off. + await act(async () => {}) expect(columns()).toHaveLength(1) - expect(screen.queryByRole('alert')).toBeNull() + expect(screen.queryByText('browser.truncated')).toBeNull() + }) + + it('anchors the upgrade on the parent level actual entry under Windows case folding', async () => { + const ROOT = 'C:\\' + const TYPED = 'c:\\users' + const winRoot: DirectoryListing = { + path: ROOT, + home: ROOT, + crumbs: [{ name: 'C:\\', path: ROOT, hidden: false }], + entries: [{ name: 'Users', path: 'C:\\Users', hidden: false }], + truncated: false, + } + const winUsers: DirectoryListing = { + path: TYPED, + home: ROOT, + crumbs: [{ name: 'C:\\', path: ROOT, hidden: false }, { name: 'users', path: TYPED, hidden: false }], + entries: [], + truncated: false, + } + mount({ listDirectory: vi.fn(async (path?: string) => (path === TYPED ? winUsers : winRoot)) }) + 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' }) + // The typed case differs from the real entry; the upgrade selects the + // parent level's ACTUAL entry so aria-current and exemptions hold. + await waitFor(() => { + expect(rowButton(within(columns()[0]!).getByRole('listitem')).getAttribute('aria-current')).toBe('true') + }) + expect(within(columns()[0]!).getByText('Users')).toBeTruthy() + }) + + it('re-parks focus on the edit zone when a failed pick unmounts a dot-revealed row', async () => { + const listDirectory = vi.fn(async (path?: string) => { + if (path === `${HOME}/.config`) { + throw new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path } }) + } + 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: `${HOME}/.co` } }) + const row = rowButton(screen.getByRole('listitem')) + fireEvent.mouseDown(row) + fireEvent.click(row) + // The failed selection re-hides the picked row; focus fell to body and + // re-parks on the crumb edit zone. + await screen.findByRole('alert') + expect(screen.queryByText('.config')).toBeNull() + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) + }) + + it('leaves focus on a surviving row when its pick fails', async () => { + const listDirectory = vi.fn(async (path?: string) => { + if (path === DOCS) { + throw new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path } }) + } + 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: `${HOME}/do` } }) + const row = rowButton(screen.getByRole('listitem')) + row.focus() + fireEvent.mouseDown(row) + fireEvent.click(row) + // Documents survives the cleared selection (it is not hidden): the + // user's focus on it is not yanked to the edit zone. + await screen.findByRole('alert') + expect(document.activeElement).toBe(row) }) it('falls back to the single-pane landing when the parent leg of a navigation fails', async () => { From 3224ad92af202d483f915f2b8cd875f3a3478768 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 21:57:06 +0800 Subject: [PATCH 13/34] =?UTF-8?q?fix(host):=20review=20round=207=20?= =?UTF-8?q?=E2=80=94=20upgrade=20re-parks=20displaced=20row=20focus;=20cas?= =?UTF-8?q?e-folded=20display=20root;=20boundary=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 56 ++++++++++++++----- .../tests/directory-browser.spec.tsx | 53 ++++++++++++++++++ 5 files changed, 100 insertions(+), 17 deletions(-) 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 From 8b1a8d383aeabac28088fed0e6d96eb9a6d24cbe Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 22:20:48 +0800 Subject: [PATCH 14/34] =?UTF-8?q?fix(host):=20review=20round=208=20?= =?UTF-8?q?=E2=80=94=20platform-folded=20draft=20matching;=20honest=20slas?= =?UTF-8?q?h-platform=20boundary;=20coverage-visible=20guards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 75 +++++++++++-------- .../tests/directory-browser.spec.tsx | 12 ++- 5 files changed, 59 insertions(+), 36 deletions(-) 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 7d06152986..9fe765766f 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: a9f9bc81a8aeff4f9592257b574a199063c681ae -2026-07-28-directory-picker-capability-seam.zh.md: 6331440b04cc8ee6994cb49ff3fd1e6b49403fa4 +2026-07-28-directory-picker-capability-seam.md: 17131eaf390db03fb037216c2b72d3db0fab93bb +2026-07-28-directory-picker-capability-seam.zh.md: 41e9a89ddff05d9e659a93e306348480ea3db5dc 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 a9f9bc81a8..17131eaf39 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. 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. +- **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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 6331440b04..41e9a89ddf 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 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台的键入大小写偏差(macOS)会错过父层级条目匹配,保留单栏落地;且导航总是重新列举两程,哪怕目标就是当前展示的层级——crumb 点按兼作刷新手势,因此宁要新鲜度也不复用手头可能已陈旧的列举,代价是至多两次宿主扫描。 +- **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——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 5c44492b77..ab6ecb731c 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -95,20 +95,23 @@ function separatorOf(listing: DirectoryListing): '\\' | '/' { } /** - * The path draft's final segment, when its directory part is exactly the - * level `listing` lists — the segment the level prefix-filters on while the - * user types. Any other draft (no separator yet, or naming some other - * directory) leaves the level unfiltered. The directory part compares - * exactly (it is the host's own path text, reached by seeding or erasing); - * only the name filter downstream is case-insensitive. + * The path draft's final segment, when its directory part names the level + * `listing` lists — the segment the level prefix-filters on while the user + * types. Any other draft (no separator yet, or naming some other directory) + * leaves the level unfiltered. The directory part compares under the + * platform fold (exact on slash platforms; Windows folds case, since an + * upgraded selection may carry the actual entry's case while the level + * below still carries the typed one); the name filter downstream is + * case-insensitive everywhere. */ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { if (draft === null) return null const sep = separatorOf(listing) const cut = draft.lastIndexOf(sep) if (cut === -1) return null + const fold = foldPathFor(listing) const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` - return draft.slice(0, cut + 1) === level ? draft.slice(cut + 1) : null + return fold(draft.slice(0, cut + 1)) === fold(level) ? draft.slice(cut + 1) : null } /** One column of folder rows (the Miller view renders one or two of these). */ @@ -231,6 +234,21 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, return { seq, scan: listDirectory(path, controller.signal) } }, [supersede, listDirectory]) + // The miller row's scroll host, shared by the pin and refocus effects + // below and read by navigate's upgrade leg (declared ahead of both). + const millerRowRef = useRef(null) + // Focus parking (consumed by the refocus effect below): 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) + const editZoneRef = useRef(null) + /** * Launch a follow-up listing under the CURRENT supersession seq: a newer * intent aborts it like the leg it continues, and it supersedes nothing. @@ -240,8 +258,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // 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() + // Inverted so the live abort below stays in coverage: a supersede + // would have bumped the seq before any follow-up could run. + /* v8 ignore next -- narrowing guard: the landing's target leg installed a controller first. */ + if (displaced === null) throw new Error('continueScan launched before any leg installed a controller') + displaced.abort() const controller = new AbortController() scanController.current = controller return listDirectory(path, controller.signal) @@ -256,10 +277,13 @@ 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 (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. + * pane (Windows folds case; on slash platforms only a FINAL-segment case + * drift misses the match and keeps the single-pane landing — parent + * entries inherit the typed prefix, so ancestor-segment drift still + * matches, at the cost of the Home collapse). 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) @@ -289,9 +313,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // 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 + // Inverted so the live contains() probe below stays in coverage. /* 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 + if (rowHost === null) throw new Error('parent-leg upgrade before the miller row rendered') + if (rowHost.contains(document.activeElement)) refocusPick.current = true setParent(parentLevel) setSelected(match) setChild(target) @@ -307,18 +332,6 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [launchListing, continueScan]) - // 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) - const editZoneRef = useRef(null) - /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { const { seq, scan } = launchListing(entry.path) @@ -455,8 +468,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [crumbTail]) // On viewports too narrow for both fixed panes the Miller row scrolls; // whenever a child preview lands, pin it into view the way the crumb tail - // pins — otherwise descent is unreachable on a phone-width window. - const millerRowRef = useRef(null) + // pins — otherwise descent is unreachable on a phone-width window. On a + // parent-leg upgrade the refocus effect below runs after this pin and its + // row.focus() may scroll the selected LEFT row back into view: for that + // one landing, focus placement wins over the child pin by design. const childPath = child?.path useEffect(() => { const row = millerRowRef.current @@ -712,8 +727,6 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onClick={() => { setShowHidden(prev => !prev) }} > {t('browser.showHidden')} - {/* Trailing check (Menu's selected vocabulary): the label never - * shifts when the pressed state toggles. */} {showHidden && } 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 fc2b6f564b..95b60ced2f 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -356,7 +356,7 @@ describe('DirectoryBrowser', () => { path: TYPED, home: ROOT, crumbs: [{ name: 'C:\\', path: ROOT, hidden: false }, { name: 'users', path: TYPED, hidden: false }], - entries: [], + entries: [{ name: 'Alpha', path: `${TYPED}\\Alpha`, hidden: false }], truncated: false, } mount({ listDirectory: vi.fn(async (path?: string) => (path === TYPED ? winUsers : winRoot)) }) @@ -370,6 +370,16 @@ describe('DirectoryBrowser', () => { expect(rowButton(within(columns()[0]!).getByRole('listitem')).getAttribute('aria-current')).toBe('true') }) expect(within(columns()[0]!).getByText('Users')).toBeTruthy() + // The editor seeds from the actual-cased selection while the child + // level still carries the typed case: the draft's directory part folds + // per platform, so the right pane keeps prefix-filtering. + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + expect(input.value).toBe('C:\\Users\\') + fireEvent.change(input, { target: { value: 'C:\\Users\\a' } }) + expect(within(columns()[1]!).getByText('Alpha')).toBeTruthy() + fireEvent.change(input, { target: { value: 'C:\\Users\\z' } }) + expect(within(columns()[1]!).queryAllByRole('listitem')).toHaveLength(0) }) it('re-parks focus on the edit zone when a failed pick unmounts a dot-revealed row', async () => { From df9c03fbc2c19046a4092f480656cea40429abae Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 22:42:11 +0800 Subject: [PATCH 15/34] =?UTF-8?q?fix(host):=20review=20round=209=20?= =?UTF-8?q?=E2=80=94=20universal=20pick=20refocus;=20always-armed=20scan?= =?UTF-8?q?=20controller;=20graceful=20close-race=20guards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/client/DirectoryBrowser.tsx | 97 ++++++++++--------- .../tests/directory-browser.spec.tsx | 50 ++++++++++ 2 files changed, 103 insertions(+), 44 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index ab6ecb731c..c4c4068d2e 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -2,13 +2,14 @@ * The in-app workspace-directory browser (figma Harness 813-23126 family): a * 680×500 dialog (clamped to short/narrow viewports — the Miller row scrolls * sideways, the columns scroll down) whose header carries the title, the selection-path - * breadcrumb, and a click-to-edit path zone; below it a Miller view — one - * full-width level until a row is selected, then two columns splitting the - * row evenly (256px floor; level | selected folder's children) around a - * hairline divider. Navigations land selection-anchored: a crumb jump or a - * submitted path commits the target immediately, then re-selects it in its - * parent level once that level arrives, so stepping back keeps two panes - * away from the display root. Selecting in the + * breadcrumb, and a click-to-edit path zone; below it a Miller view of one + * or two columns splitting the row evenly (256px floor; level | selected + * folder's children) around a hairline divider — the display root and + * degraded landings keep the single wide level, while any selection opens + * the second pane, including the one a navigation lands with: a crumb jump + * or a submitted path commits the target immediately, then re-selects it + * in its parent level once that level arrives, so stepping back keeps two + * panes away from the display root. Selecting in the * right column shifts the view one level deeper. "New folder" opens a nested * create dialog targeting the selected folder (or the level itself) and * selects the created folder. Open adopts the selected folder, falling back @@ -56,14 +57,15 @@ function failureText(error: unknown): string { } /** - * 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). + * Case-folds a path for comparisons under the given separator'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; only a + * FINAL-segment macOS case drift misses parent-entry matching and keeps + * the single-pane landing, since parent entry paths inherit the typed + * prefix). */ -function foldPathFor(listing: DirectoryListing): (value: string) => string { - const sep = separatorOf(listing) +function foldPathFor(sep: '\\' | '/'): (value: string) => string { return value => (sep === '\\' ? value.toLowerCase() : value) } @@ -74,7 +76,7 @@ function foldPathFor(listing: DirectoryListing): (value: string) => string { * Windows path still collapses to the Home crumb. */ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryEntry[] { - const fold = foldPathFor(listing) + const fold = foldPathFor(separatorOf(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) @@ -109,7 +111,7 @@ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string const sep = separatorOf(listing) const cut = draft.lastIndexOf(sep) if (cut === -1) return null - const fold = foldPathFor(listing) + const fold = foldPathFor(sep) const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` return fold(draft.slice(0, cut + 1)) === fold(level) ? draft.slice(cut + 1) : null } @@ -195,8 +197,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const requestSeq = useRef(0) // The in-flight listing's controller: superseding intent aborts the wire // request too — the Host stops scanning — instead of only discarding the - // eventual result while the scan keeps consuming host resources. - const scanController = useRef(null) + // eventual result while the scan keeps consuming host resources. Always + // holds a controller (a settled or aborted one between scans) so no + // consumer needs a null guard. + const scanController = useRef(new AbortController()) // Bumped on every open/close edge: settlements from a previous open (a // pending creation included) must never mutate a reopened dialog. const openGeneration = useRef(0) @@ -212,7 +216,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, useEffect(() => () => { requestSeq.current += 1 openGeneration.current += 1 - scanController.current?.abort() + scanController.current.abort() }, []) const compositionGuard = { onCompositionStart: () => { composingRef.current = true }, @@ -221,8 +225,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, /** Newer intent wins: invalidate the pending listing's settlement AND abort its wire request. */ const supersede = useCallback((): number => { - scanController.current?.abort() - scanController.current = null + scanController.current.abort() return ++requestSeq.current }, []) @@ -257,12 +260,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // 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 - // Inverted so the live abort below stays in coverage: a supersede - // would have bumped the seq before any follow-up could run. - /* v8 ignore next -- narrowing guard: the landing's target leg installed a controller first. */ - if (displaced === null) throw new Error('continueScan launched before any leg installed a controller') - displaced.abort() + scanController.current.abort() const controller = new AbortController() scanController.current = controller return listDirectory(path, controller.signal) @@ -306,16 +304,18 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // Windows resolves a typed path preserving its case; anchor on the // parent level's actual entry so selection comparisons hold (slash // platforms compare exactly — see foldPathFor). - const fold = foldPathFor(parentLevel) + const fold = foldPathFor(separatorOf(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 - // Inverted so the live contains() probe below stays in coverage. - /* v8 ignore next -- narrowing guard: the committed landing just rendered the miller row. */ - if (rowHost === null) throw new Error('parent-leg upgrade before the miller row rendered') + // A close race can clear the ref before the close effect's + // supersede runs (commit precedes passive effects): drop the + // upgrade, the dialog is going away. + /* v8 ignore next -- close-race guard: the commit-to-effect window is not deterministically reproducible. */ + if (rowHost === null) return if (rowHost.contains(document.activeElement)) refocusPick.current = true setParent(parentLevel) setSelected(match) @@ -336,9 +336,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const select = useCallback((entry: DirectoryEntry) => { const { seq, scan } = launchListing(entry.path) // A pick while the path editor is open adopts the (filtered) row and - // closes the editor — the draft served its purpose. Focus re-parks on - // the selection after commit (see the refocus effect below). - if (pathDraft !== null) refocusPick.current = true + // closes the editor — the draft served its purpose. EVERY pick re-parks + // focus on the selection after commit (see the refocus effect below): + // a left-pane pick lands on the very row that was clicked (a near + // no-op), while a right-pane advance and a create landing replace the + // picked button's column entirely and would otherwise drop focus to + // body. + refocusPick.current = true setPathDraft(null) setSelected(entry) setChild(null) @@ -477,12 +481,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const row = millerRowRef.current if (row !== null && childPath !== undefined) row.scrollLeft = row.scrollWidth }, [childPath]) - // Every editor exit that would drop focus to body re-parks it after - // commit, so keyboard traversal stays inside the dialog (the Modal has no - // focus trap): a pick lands on the selection's row — aria-current in the - // freshly rendered left pane, which survives even a right-pane advance - // replacing the picked button's column — while Enter and an input-focused - // Escape land on the crumb edit zone that replaces the input. + // Every pick and editor exit that would drop focus to body re-parks it + // after commit, so keyboard traversal stays inside the dialog (the Modal + // has no focus trap): a pick lands on the selection's row — aria-current + // in the freshly rendered left pane, which survives even a right-pane + // advance or a create landing replacing the picked button's column — + // while Enter and an input-focused Escape land on the crumb edit zone + // that replaces the input. useEffect(() => { if (pathDraft !== null) return if (refocusPick.current) { @@ -492,10 +497,14 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, /* v8 ignore next -- narrowing guard: the miller row is mounted whenever a pick just committed. */ if (rowHost === null) return const row = rowHost.querySelector('button[aria-current="true"]') - /* v8 ignore next -- narrowing guard: the pick that set the flag just rendered its aria-current row. */ - if (row === null) return - row.focus() - return + if (row !== null) { + row.focus() + return + } + // The pick lost its row (a truncated relist after Create can drop + // the created directory outside the window): fall through to the + // edit-zone parking below instead of leaving focus where it fell. + refocusEditZone.current = true } if (refocusEditZone.current) { refocusEditZone.current = false 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 95b60ced2f..c5ed60fa5e 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -629,6 +629,56 @@ describe('DirectoryBrowser', () => { expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() }) + it('a plain right-pane advance parks focus on the new selection (no editor involved)', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(rowButton(screen.getByRole('listitem'))) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + // Keyboard reached the right pane; the advance replaces that whole + // column, so focus re-parks on the new left pane's selected row. + const row = rowButton(within(columns()[1]!).getByRole('listitem')) + row.focus() + fireEvent.click(row) + await waitFor(() => { expect(document.activeElement?.textContent).toBe('harness') }) + expect(document.activeElement?.getAttribute('aria-current')).toBe('true') + }) + + it('a create landing parks focus on the created row, or the edit zone when the relist lost it', async () => { + // First create: the relist contains the created directory. + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + b.listDirectory.mockImplementation(async (path?: string) => { + // The created directory is not in listingFor's fixed tree: serve its + // level before the fixture lookup can reject the unknown path. + if (path === `${HOME}/fresh`) return { ...listingFor(HOME), path: `${HOME}/fresh`, entries: [] } + const base = listingFor(path) + if (path === HOME) { + return { ...base, entries: [...base.entries, { name: 'fresh', path: `${HOME}/fresh`, hidden: false }] } + } + return base + }) + fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) + fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'fresh' } }) + fireEvent.click(screen.getByRole('button', { name: 'browser.create' })) + await waitFor(() => { expect(document.activeElement?.textContent).toBe('fresh') }) + expect(document.activeElement?.getAttribute('aria-current')).toBe('true') + }) + + it('a create landing whose truncated relist lost the created row parks on the edit zone', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + // The relist window misses the created directory (truncated tail). + b.listDirectory.mockImplementation(async (path?: string) => ({ ...listingFor(path), truncated: true })) + fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) + fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'zzz-tail' } }) + fireEvent.click(screen.getByRole('button', { name: 'browser.create' })) + // No aria-current row exists for the selection: focus falls back to the + // crumb edit zone instead of staying wherever it fell. + await waitFor(() => { + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) + }) + }) + it('a right-pane pick while editing parks focus on the advanced selection', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) From a22d9aea0bd584ffbd86336868b9eaed8eebe291 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 23:00:49 +0800 Subject: [PATCH 16/34] =?UTF-8?q?fix(host):=20review=20round=2010=20?= =?UTF-8?q?=E2=80=94=20trailing-separator=20home=20root;=20dead=20dep;=20l?= =?UTF-8?q?azy=20controller;=20focus-invariant=20doc=20home?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 50 ++++++++++++------- .../tests/directory-browser.spec.tsx | 15 +++++- 5 files changed, 50 insertions(+), 23 deletions(-) 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 9fe765766f..2a98ace12d 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: 17131eaf390db03fb037216c2b72d3db0fab93bb -2026-07-28-directory-picker-capability-seam.zh.md: 41e9a89ddff05d9e659a93e306348480ea3db5dc +2026-07-28-directory-picker-capability-seam.md: b860feab1fecead8130b77218005ab950575d5c9 +2026-07-28-directory-picker-capability-seam.zh.md: fea181800243b27499fa0a97acc44253078ad9db 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 17131eaf39..b860feab1f 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 @@ -19,7 +19,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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. +- **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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while Enter, an input-focused Escape, and a pick whose row vanished park on the crumb edit zone; keyboard traversal never falls out of the card (the Modal has no focus trap). - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. 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 41e9a89ddf..fea1818002 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 @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从 `listing.home` 推断;下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而 Enter、焦点在输入框上时的 Escape,以及所在行已消失的选取则停靠到 crumb 编辑区;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱)。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——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 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index c4c4068d2e..b2e007ec2f 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -69,15 +69,23 @@ function foldPathFor(sep: '\\' | '/'): (value: string) => string { return value => (sep === '\\' ? value.toLowerCase() : value) } +/** Drops one trailing separator (`HOME=/home/u/` ships verbatim while resolve() strips it) unless the path IS the bare root. */ +function trimTrailingSeparator(path: string, sep: '\\' | '/'): string { + return path.length > sep.length && path.endsWith(sep) ? path.slice(0, -sep.length) : path +} + /** * 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. The home comparison folds per platform so a typed-case - * Windows path still collapses to the Home crumb. + * by its own path. The home comparison folds per platform and normalizes a + * trailing separator, so a typed-case Windows path or a `HOME=/home/u/` + * shape still collapses to the Home crumb. */ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryEntry[] { - const fold = foldPathFor(separatorOf(listing)) - const homeIndex = listing.crumbs.findIndex(crumb => fold(crumb.path) === fold(listing.home)) + const sep = separatorOf(listing) + const fold = foldPathFor(sep) + const home = fold(trimTrailingSeparator(listing.home, sep)) + const homeIndex = listing.crumbs.findIndex(crumb => fold(trimTrailingSeparator(crumb.path, sep)) === home) if (homeIndex === -1) return listing.crumbs const tail = listing.crumbs.slice(homeIndex + 1) return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail] @@ -154,10 +162,10 @@ function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPr // where the blur lands before our guards) drop this click. // Outside editing, rows keep native focus behavior. onMouseDown={pathEditing ? (event) => { event.preventDefault() } : undefined} - // Editing-time focus parking happens after commit (the - // DirectoryBrowser refocus effect): a right-pane pick replaces - // this very column, so focusing the clicked node here would - // still fall to body. + // Focus parking happens after commit (the DirectoryBrowser + // refocus effect): a right-pane pick replaces this very + // column, so focusing the clicked node here would still fall + // to body. onClick={() => { onPick(entry) }} > {selected @@ -198,9 +206,12 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // The in-flight listing's controller: superseding intent aborts the wire // request too — the Host stops scanning — instead of only discarding the // eventual result while the scan keeps consuming host resources. Always - // holds a controller (a settled or aborted one between scans) so no - // consumer needs a null guard. - const scanController = useRef(new AbortController()) + // holds a controller so no consumer needs a null guard: initially a + // placeholder that the first supersede aborts unused (minted lazily — + // useRef evaluates its argument every render), afterwards the latest + // scan's, settled or aborted between scans. + const [initialScanController] = useState(() => new AbortController()) + const scanController = useRef(initialScanController) // Bumped on every open/close edge: settlements from a previous open (a // pending creation included) must never mutate a reopened dialog. const openGeneration = useRef(0) @@ -364,7 +375,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // re-parks on the edit zone only if focus actually fell to body. refocusEditZone.current = true }) - }, [launchListing, pathDraft]) + }, [launchListing]) /** Abandon path editing (Escape or clicking away) and restore the crumb view. */ const cancelPathEdit = useCallback(() => { @@ -472,10 +483,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [crumbTail]) // On viewports too narrow for both fixed panes the Miller row scrolls; // whenever a child preview lands, pin it into view the way the crumb tail - // pins — otherwise descent is unreachable on a phone-width window. On a - // parent-leg upgrade the refocus effect below runs after this pin and its - // row.focus() may scroll the selected LEFT row back into view: for that - // one landing, focus placement wins over the child pin by design. + // pins — otherwise descent is unreachable on a phone-width window. The + // refocus effect's row.focus() and this pin can fight on such viewports, + // and whichever commit runs later wins by design: on a parent-leg + // upgrade (one commit) focus placement runs after the pin and keeps the + // selected LEFT row in view; on a plain advance or create landing the + // child arrives in a later commit, so the pin runs after the focus and + // descent reachability wins. const childPath = child?.path useEffect(() => { const row = millerRowRef.current @@ -512,7 +526,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // the user parked elsewhere (a surviving row) stays theirs. if (document.activeElement !== document.body) return const zone = editZoneRef.current - /* v8 ignore next -- narrowing guard: crumb mode renders the edit zone whenever the editor just closed. */ + // The effect already returned while a draft is open, and the close + // reset cleared both flags — so crumb mode's zone is always mounted. + /* v8 ignore next -- narrowing guard: crumb mode always renders the edit zone. */ if (zone === null) return zone.focus() } 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 c5ed60fa5e..909714ae7d 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -224,6 +224,18 @@ describe('DirectoryBrowser', () => { expect(within(columns()[1]!).getByText('harness')).toBeTruthy() }) + it('a trailing-separator home is still the display root (single pane on open)', async () => { + const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}/` })) + mount({ listDirectory }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + // `HOME=/home/u/` ships verbatim while the listing path resolves without + // the trailing separator; the normalized comparison still collapses to + // the Home crumb and no parent leg launches. + expect(columns()).toHaveLength(1) + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + expect(listDirectory).toHaveBeenCalledTimes(1) + }) + it('a navigation to the filesystem root keeps the single wide level', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) @@ -643,8 +655,7 @@ describe('DirectoryBrowser', () => { expect(document.activeElement?.getAttribute('aria-current')).toBe('true') }) - it('a create landing parks focus on the created row, or the edit zone when the relist lost it', async () => { - // First create: the relist contains the created directory. + it('a create landing parks focus on the created row', async () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) b.listDirectory.mockImplementation(async (path?: string) => { From 4171f8eaa95295edeedb480017839c58710fc627 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 23:21:35 +0800 Subject: [PATCH 17/34] =?UTF-8?q?fix(host):=20review=20round=2011=20?= =?UTF-8?q?=E2=80=94=20every=20displacing=20exit=20re-parks=20focus;=20ful?= =?UTF-8?q?l=20trailing-separator=20trim?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 62 +++++++++++++----- .../tests/directory-browser.spec.tsx | 65 +++++++++++++++++++ 5 files changed, 114 insertions(+), 21 deletions(-) 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 2a98ace12d..b35392209c 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: b860feab1fecead8130b77218005ab950575d5c9 -2026-07-28-directory-picker-capability-seam.zh.md: fea181800243b27499fa0a97acc44253078ad9db +2026-07-28-directory-picker-capability-seam.md: c6241ecca4abfafcee104a0c5d9ecc1150627e42 +2026-07-28-directory-picker-capability-seam.zh.md: 1e559a3c95352b08f8ad1aafdf8ce3efa0edc5cb 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 b860feab1f..c6241ecca4 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 @@ -19,7 +19,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while Enter, an input-focused Escape, and a pick whose row vanished park on the crumb edit zone; keyboard traversal never falls out of the card (the Modal has no focus trap). +- **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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body; keyboard traversal never falls out of the card (the Modal has no focus trap). - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. 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 fea1818002..1e559a3c95 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 @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而 Enter、焦点在输入框上时的 Escape,以及所在行已消失的选取则停靠到 crumb 编辑区;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱)。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从 `listing.home` 推断;下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱)。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——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 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index b2e007ec2f..3ddf5ac540 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -69,9 +69,17 @@ function foldPathFor(sep: '\\' | '/'): (value: string) => string { return value => (sep === '\\' ? value.toLowerCase() : value) } -/** Drops one trailing separator (`HOME=/home/u/` ships verbatim while resolve() strips it) unless the path IS the bare root. */ +/** + * Drops every trailing separator (`HOME=/home/u//` ships verbatim while + * resolve() strips them) down to, but never past, one leading character — + * which keeps the POSIX root `/` intact. A backslash drive root (`C:\`) + * does lose its separator; that stays safe only because every comparison + * trims both sides symmetrically. + */ function trimTrailingSeparator(path: string, sep: '\\' | '/'): string { - return path.length > sep.length && path.endsWith(sep) ? path.slice(0, -sep.length) : path + let end = path.length + while (end > sep.length && path.endsWith(sep, end)) end -= sep.length + return path.slice(0, end) } /** @@ -253,14 +261,14 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const millerRowRef = useRef(null) // Focus parking (consumed by the refocus effect below): 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. + // selection's row; every other displacing exit (Enter, Escape, a landing + // whose new level dropped the focused row, a failed pick or relist, and + // the nested create dialog closing) parks on the crumb edit zone, each + // 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) const editZoneRef = useRef(null) /** @@ -300,6 +308,14 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setError(null) scan.then((target) => { if (seq !== requestSeq.current) return + // The landing replaces every row key; a slow jump leaves the OLD + // rows tabbable meanwhile (parentInert excludes loading), so focus + // may live among them. With no selection yet the edit zone is the + // park target (body-guarded, like every other exit). + const rowHost = millerRowRef.current + /* v8 ignore next -- close-race guard: the commit-to-effect window is not deterministically reproducible. */ + if (rowHost === null) return + if (rowHost.contains(document.activeElement)) refocusEditZone.current = true setParent(target) setSelected(null) setChild(null) @@ -343,6 +359,17 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [launchListing, continueScan]) + /** + * Close the nested create dialog. Its unmount drops focus to body (the + * Modal has no focus trap), so every exit — Escape, mask, Cancel, and a + * successful create — arms the body-guarded edit-zone parking; a create + * landing's later select() re-parks on the created row instead. + */ + const closeCreateDialog = useCallback(() => { + setFolderDraft(null) + refocusEditZone.current = true + }, []) + /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { const { seq, scan } = launchListing(entry.path) @@ -449,7 +476,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // the fresh dialog or issue a relist against the stale target. if (generation !== openGeneration.current) return setCreatingFolder(false) - setFolderDraft(null) + closeCreateDialog() // Land like a right-column pick (figma 802:57446 → 813:23278 flow): the // create target becomes the listed level and the new folder its selection. const { seq, scan } = launchListing(targetPath) @@ -572,11 +599,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // document listener — the same containment the input previously // provided for itself. event.stopPropagation() - // Escape while the input holds focus is about to unmount it; with - // focus already parked on a row, that row survives the cancel and - // keeps focus naturally. Assignment (not a conditional set) also + // The cancel may unmount whatever holds focus — the input, or a + // dot-revealed row the cleared draft re-hides. Arm the parking + // unconditionally: the refocus effect's body guard already + // distinguishes a surviving focused row (left alone) from focus + // that actually fell. Assignment (not a conditional set) also // retires a stale flag a failed or still-upgrading Enter left. - refocusEditZone.current = document.activeElement === pathInputRef.current + refocusEditZone.current = true cancelPathEdit() }} // Focus leaving THIS dialog card while editing cancels like Escape. @@ -660,7 +689,6 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, value={pathDraft} aria-label={t('browser.editPath')} autoFocus - ref={pathInputRef} disabled={parentInert} onChange={(event) => { // Editing the draft supersedes any in-flight navigation: @@ -770,7 +798,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, {/* Nested create dialog (figma 813:23278): names one folder inside the target. */} { if (!creatingFolder) setFolderDraft(null) }} + onClose={() => { if (!creatingFolder) closeCreateDialog() }} title={t('browser.newFolder')} className={clsx(css.createDialog)} headless @@ -794,13 +822,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, } if (event.key === 'Escape') { event.stopPropagation() - if (!creatingFolder) setFolderDraft(null) + if (!creatingFolder) closeCreateDialog() } }} /> {createError !== null &&
{createError}
}
- + 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 c27522a6cf..e2adc75881 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -349,6 +349,16 @@ describe('DirectoryBrowser', () => { expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) }) + it('a home carrying dot segments is still the display root', async () => { + // os.homedir() ships HOME verbatim; the backend resolves listing paths. + const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}/foo/../.` })) + mount({ listDirectory }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + expect(columns()).toHaveLength(1) + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + expect(listDirectory).toHaveBeenCalledTimes(1) + }) + it('a navigation to the filesystem root keeps the single wide level', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) @@ -1176,6 +1186,7 @@ describe('DirectoryBrowser', () => { expect(cancels.map(button => button.disabled).sort()).toEqual([false, true]) expect(screen.getByRole('button', { name: 'browser.open' }).disabled).toBe(true) expect(screen.getByRole('button', { name: 'browser.editPath' }).disabled).toBe(true) + expect(screen.getByRole('button', { name: 'browser.showHidden' }).disabled).toBe(true) for (const row of screen.getAllByRole('listitem')) { expect(rowButton(row).disabled).toBe(true) } From 4921b63fe353006c4319213e228c11a5ac1184ee Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 00:49:18 +0800 Subject: [PATCH 22/34] =?UTF-8?q?fix(host):=20review=20round=2016=20?= =?UTF-8?q?=E2=80=94=20UNC/forward-slash=20home=20forms;=20root-crumb=20se?= =?UTF-8?q?parator;=20scrollbar=20symmetry;=20test=20dedup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/client/DirectoryBrowser.module.css | 11 ++- .../src/client/DirectoryBrowser.tsx | 53 +++++++------ .../tests/directory-browser.spec.tsx | 75 +++++++++++++------ 3 files changed, 91 insertions(+), 48 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 8c8033d825..8bd044f610 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -62,6 +62,12 @@ scrollbar-width: none; } +/* Pseudo-element-path engines (see .millerRow's twin rule): the 20px crumb + * bar has no room for a bar at all. */ +.crumbTrail::-webkit-scrollbar { + display: none; +} + .crumbSeat { display: inline-flex; align-items: center; @@ -299,9 +305,8 @@ color: var(--dsw-alias-label-primary); } -/* Trailing pressed check (Menu's .check parallel): flex-none so wrap or - * narrow-viewport clamp pressure never squashes the glyph — the nowrap - * label refuses to shrink, leaving the icon as the only compressible item. */ +/* Flex-none: the nowrap label refuses to shrink, which would leave the + * glyph as the only compressible item under wrap or narrow-viewport clamp. */ .toggleCheck { flex: none; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 8507681150..d82b4f0abd 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -73,30 +73,37 @@ function foldPathFor(sep: '\\' | '/'): (value: string) => string { } /** - * Lexically normalizes an absolute host path for comparisons: collapses - * repeated and trailing separators, drops `.` segments, and applies `..` — - * mirroring the backend's resolve() for the shapes an environment-supplied - * HOME legally carries verbatim (`/home/u/`, `/home//u`, `/home/u/.`) - * while the backend's paths arrive already resolved. A lexical mirror - * only: symlinks are the backend's business, and the input always - * contains the separator (it is an absolute path). + * Lexically normalizes an absolute host path for comparisons: folds + * forward slashes on Windows (win32 accepts either), collapses repeated + * and trailing separators, drops `.` segments, and applies `..` without + * ever crossing the root — POSIX's `/`, a drive's `C:`, or UNC's + * `\\server\share` pair — mirroring the backend's resolve() for the + * shapes an environment-supplied HOME legally carries verbatim while the + * backend's own paths arrive already resolved. A lexical mirror only: + * symlinks are the backend's business. */ function normalizePathFor(sep: '\\' | '/'): (value: string) => string { - return (value) => { - const segments = value.split(sep) - const head = segments.shift() - /* v8 ignore next -- narrowing guard: split always yields at least one segment. */ - if (head === undefined) return value - const out: string[] = [] - for (const segment of segments) { + return (raw) => { + // win32 treats a forward slash as a separator too (resolve() folds + // them); POSIX must not — a backslash there is a name character. + const value = sep === '\\' ? raw.replaceAll('/', sep) : raw + const unc = sep === '\\' && value.startsWith(`${sep}${sep}`) + const segments = (unc ? value.slice(2) : value).split(sep) + // The unpoppable root: POSIX's leading empty segment / the drive + // segment, or UNC's server + share pair. + const rootLength = unc ? 2 : 1 + const out = segments.slice(0, rootLength) + for (const segment of segments.slice(rootLength)) { if (segment === '' || segment === '.') continue if (segment === '..') { - out.pop() + if (out.length > rootLength) out.pop() continue } out.push(segment) } - return `${head}${sep}${out.join(sep)}` + // A bare root keeps (or regains) the trailing separator resolve() + // emits for `/`, `C:\`, and `\\server\share\`. + return `${unc ? sep + sep : ''}${out.join(sep)}${out.length === rootLength ? sep : ''}` } } @@ -119,16 +126,20 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE } /** - * The listing's platform separator, inferred from the home path the host - * stamped — never from typed text or entry paths, where a backslash is a - * legal POSIX name character. Still a heuristic at the last step: a POSIX - * home directory whose own name contains a backslash would misread. + * The listing's platform separator, read from the host-resolved root crumb + * (`/`, `C:\`, `\\server\share\`) — exact for every root form the backend + * emits, immune both to a home delivered in the other slash flavor + * (`USERPROFILE=C:/Users/Alice`) and to backslashes inside POSIX names. * TODO: replace with a host-stamped `separator` field on the wire * DirectoryListing so the platform fact travels verbatim (the trade-off is * recorded in the directory-picker capability seam Agent Note). */ function separatorOf(listing: DirectoryListing): '\\' | '/' { - return listing.home.includes('\\') ? '\\' : '/' + const rootCrumb = listing.crumbs.at(0) + // Home is the honest fallback for an impossible empty chain. + /* v8 ignore next -- narrowing guard: the wire chain is root-to-target inclusive. */ + if (rootCrumb === undefined) return listing.home.includes('\\') ? '\\' : '/' + return rootCrumb.path.includes('\\') ? '\\' : '/' } /** 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 e2adc75881..fcc2b21f92 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -240,20 +240,12 @@ describe('DirectoryBrowser', () => { expect(within(columns()[1]!).getByText('harness')).toBeTruthy() }) - it('a trailing-separator home is still the display root (single pane on open)', async () => { - const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}/` })) - mount({ listDirectory }) - await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) - // `HOME=/home/u/` ships verbatim while the listing path resolves without - // the trailing separator; the normalized comparison still collapses to - // the Home crumb and no parent leg launches. - expect(columns()).toHaveLength(1) - expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() - expect(listDirectory).toHaveBeenCalledTimes(1) - }) - - it('a home with several trailing separators is still the display root', async () => { - const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}//` })) + // HOME ships verbatim from the environment while listing paths arrive + // resolved; each decoration (trailing, repeated, dot, dot-dot segments) + // must still normalize to the display root — single pane, Home crumb, + // and no parent leg launched. + it.each(['/', '//', '/foo/../.'])('a home decorated with "%s" is still the display root', async (decoration) => { + const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}${decoration}` })) mount({ listDirectory }) await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) expect(columns()).toHaveLength(1) @@ -349,16 +341,6 @@ describe('DirectoryBrowser', () => { expect(document.activeElement).toBe(screen.getByRole('button', { name: 'browser.editPath' })) }) - it('a home carrying dot segments is still the display root', async () => { - // os.homedir() ships HOME verbatim; the backend resolves listing paths. - const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}/foo/../.` })) - mount({ listDirectory }) - await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) - expect(columns()).toHaveLength(1) - expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() - expect(listDirectory).toHaveBeenCalledTimes(1) - }) - it('a navigation to the filesystem root keeps the single wide level', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) @@ -425,6 +407,51 @@ describe('DirectoryBrowser', () => { expect(document.activeElement?.getAttribute('aria-current')).toBe('true') }) + it('a UNC home with dot-dot never pops the share root and still collapses to Home', async () => { + const SHARE = '\\\\server\\share' + const listing: DirectoryListing = { + path: `${SHARE}\\x`, + // USERPROFILE ships verbatim; win32.resolve keeps \\server\share as + // the unpoppable root, so this normalizes to \\server\share\x. + home: `${SHARE}\\..\\x`, + crumbs: [ + { name: `${SHARE}\\`, path: `${SHARE}\\`, hidden: false }, + { name: 'x', path: `${SHARE}\\x`, hidden: false }, + ], + entries: [], + truncated: false, + } + const listDirectory = vi.fn(async () => listing) + mount({ listDirectory }) + await waitFor(() => { expect(listDirectory).toHaveBeenCalled() }) + await waitFor(() => { expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() }) + expect(columns()).toHaveLength(1) + expect(listDirectory).toHaveBeenCalledTimes(1) + }) + + it('a forward-slash Windows home still reads as the display root', async () => { + const listing: DirectoryListing = { + path: 'C:\\Users\\Alice', + // USERPROFILE may legally use forward slashes; the root crumb (not + // the home text) carries the platform, and normalization folds the + // slashes before comparing. + home: 'C:/Users/Alice', + crumbs: [ + { name: 'C:\\', path: 'C:\\', hidden: false }, + { name: 'Users', path: 'C:\\Users', hidden: false }, + { name: 'Alice', path: 'C:\\Users\\Alice', hidden: false }, + ], + entries: [{ name: 'Desktop', path: 'C:\\Users\\Alice\\Desktop', hidden: false }], + truncated: false, + } + const listDirectory = vi.fn(async () => listing) + mount({ listDirectory }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + expect(columns()).toHaveLength(1) + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + expect(listDirectory).toHaveBeenCalledTimes(1) + }) + 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' From 12d302ea591bc4439fc9c6102f495033b3b4cb18 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 01:10:37 +0800 Subject: [PATCH 23/34] =?UTF-8?q?fix(host):=20review=20round=2017=20?= =?UTF-8?q?=E2=80=94=20separator-fold=20drafts;=20UNC=20noise=20scrub;=20h?= =?UTF-8?q?onest=20empty-chain=20fallback;=20toggle=20focus=20keep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 4 +- ...-28-directory-picker-capability-seam.zh.md | 4 +- .../src/client/DirectoryBrowser.tsx | 47 ++++++++++---- .../tests/directory-browser.spec.tsx | 62 ++++++++++++++++++- 5 files changed, 102 insertions(+), 19 deletions(-) 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 0b17e08ce7..81c065227f 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: 75fda86788ec2ab1966f7919cdca7d503238da91 -2026-07-28-directory-picker-capability-seam.zh.md: 1e2c7819133366d5b9a0b26db195b46ac5ea62f4 +2026-07-28-directory-picker-capability-seam.md: 9008ba928c16a19fae601db0b8a83d44eaeeaae0 +2026-07-28-directory-picker-capability-seam.zh.md: 95ba66062aafb4ebe1ed37219efd5ad94f13f842 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 75fda86788..9008ba928c 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 @@ -19,7 +19,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body; keyboard traversal never falls out of the card (the Modal has no focus trap), except during the owner's adopt window, where `busy` inerts every control and the dialog is closing either way. +- **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body; keyboard traversal never falls out of the card (the Modal has no focus trap), except during the owner's adopt window, where `busy` inerts every control and the dialog is closing either way. - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. @@ -34,7 +34,7 @@ Placement and policy rulings folded into this decision: - **Adopting a file-manager/drive-enumeration dependency.** Rejected per the survey above; recorded here as the dependency policy requires. - **A flip-label show-hidden toggle ("Hide hidden files").** Rejected: a flipping action label is ambiguous between state and action and doubles the negative; the fixed label with a pressed presentation states both at once. - **Pure relatedTarget blur cancellation (no mousedown suppression).** Rejected: Safari does not focus buttons on pointer down, so a click's focusout carries a null `relatedTarget` and would cancel the editor before the click lands; editing-scoped mousedown suppression plus the card-anchored relatedTarget guard covers pointer and keyboard paths together. -- **A wire `separator` field on `DirectoryListing` (host stamps `path.sep`).** Deferred, not rejected: it is the authoritative form — a POSIX home directory containing a backslash defeats the `listing.home` heuristic — but it touches the seam type and every backend; the browse client's `separatorOf` carries a TODO pointing at this alternative until a wire change is next scheduled. +- **A wire `separator` field on `DirectoryListing` (host stamps `path.sep`).** Deferred, not rejected: it is the authoritative form. The root-crumb read the client uses today is exact for every root shape this backend emits, but it still infers a platform fact from path text and promotes "the chain starts at the root" from backend behavior into a client-relied invariant (the `crumbs` JSDoc does promise it), and it degrades to the old home-text heuristic on an empty chain; a wire field would travel verbatim and survive empty chains and future backends. It touches the seam type and every backend, so the browse client's `separatorOf` carries a TODO pointing at this alternative until a wire change is next scheduled. ## Consequences 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 1e2c781913..95ba66062a 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 @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱),仅 owner 的接纳窗口期间例外——此时 `busy` 把每个控件置为惰性,且对话框反正正在关闭。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱),仅 owner 的接纳窗口期间例外——此时 `busy` 把每个控件置为惰性,且对话框反正正在关闭。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——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 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 @@ -34,7 +34,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **引入文件管理器/盘符枚举依赖。** 按上文调研否决;依赖政策要求记录于此。 - **动作标签随状态翻转的"显示隐藏"开关("隐藏隐藏文件")。** 否决:会翻转的动作标签在状态与动作之间有歧义,还把否定叠了两层;固定标签加按下态呈现一次说清两者。 - **纯 relatedTarget 失焦取消(不做 mousedown 抑制)。** 否决:Safari 在指针按下时不给按钮聚焦,点击触发的 focusout 因而携带空 `relatedTarget`,会在点击落地前就取消编辑器;编辑期作用的 mousedown 抑制加上锚定卡片的 relatedTarget 守卫才能同时覆盖指针与键盘路径。 -- **在 `DirectoryListing` 上增设线上 `separator` 字段(宿主标注 `path.sep`)。** 延期而非否决:它才是权威形态——含反斜杠的 POSIX 家目录会击穿 `listing.home` 启发式——但它触及 seam 类型与每个后端;browse 客户端的 `separatorOf` 挂着指向本方案的 TODO,直到下次安排线上变更。 +- **在 `DirectoryListing` 上增设线上 `separator` 字段(宿主标注 `path.sep`)。** 延期而非否决:它才是权威形态。客户端今天所用的根 crumb 读取对该后端发出的每种根形态都精确,但它仍是从路径文本推断平台事实,还把"链从根开始"从后端行为提升为客户端所依赖的不变量(`crumbs` 的 JSDoc 确实承诺了这一点),并在链为空时退化回旧的 home 文本启发式;线上字段则会原样随线传输,经得住空链与未来的后端。它触及 seam 类型与每个后端,因此 browse 客户端的 `separatorOf` 挂着指向本方案的 TODO,直到下次安排线上变更。 ## 后果 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index d82b4f0abd..2e5e732548 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -82,13 +82,26 @@ function foldPathFor(sep: '\\' | '/'): (value: string) => string { * backend's own paths arrive already resolved. A lexical mirror only: * symlinks are the backend's business. */ +/** + * Folds separators to the platform's canonical one: win32 treats a forward + * slash as a separator too (resolve() folds them the same way), while + * POSIX must not — a backslash there is a name character. + */ +function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { + return value => (sep === '\\' ? value.replaceAll('/', sep) : value) +} + function normalizePathFor(sep: '\\' | '/'): (value: string) => string { + const foldSeparators = foldSeparatorsFor(sep) return (raw) => { - // win32 treats a forward slash as a separator too (resolve() folds - // them); POSIX must not — a backslash there is a name character. - const value = sep === '\\' ? raw.replaceAll('/', sep) : raw + const value = foldSeparators(raw) const unc = sep === '\\' && value.startsWith(`${sep}${sep}`) - const segments = (unc ? value.slice(2) : value).split(sep) + const rawSegments = (unc ? value.slice(2) : value).split(sep) + // Empty segments are separator noise everywhere except POSIX's leading + // root marker, which must survive as the first segment; scrubbing them + // up front keeps a doubled separator from being locked into the UNC + // server + share root below. + const segments = unc ? rawSegments.filter(segment => segment !== '') : rawSegments // The unpoppable root: POSIX's leading empty segment / the drive // segment, or UNC's server + share pair. const rootLength = unc ? 2 : 1 @@ -136,8 +149,10 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE */ function separatorOf(listing: DirectoryListing): '\\' | '/' { const rootCrumb = listing.crumbs.at(0) - // Home is the honest fallback for an impossible empty chain. - /* v8 ignore next -- narrowing guard: the wire chain is root-to-target inclusive. */ + // The seam type allows an empty chain (this backend never emits one, but + // create-target naming supports it, see targetName): degrade to a + // best-effort read of the home text — the pre-root-crumb heuristic, with + // its backslash-in-a-POSIX-name blind spot. if (rootCrumb === undefined) return listing.home.includes('\\') ? '\\' : '/' return rootCrumb.path.includes('\\') ? '\\' : '/' } @@ -149,17 +164,19 @@ function separatorOf(listing: DirectoryListing): '\\' | '/' { * leaves the level unfiltered. The directory part compares under the * platform fold (exact on slash platforms; Windows folds case, since an * upgraded selection may carry the actual entry's case while the level - * below still carries the typed one); the name filter downstream is - * case-insensitive everywhere. + * below still carries the typed one — and folds forward slashes, which + * win32 and the backend both accept in typed paths); the name filter + * downstream is case-insensitive everywhere. */ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { if (draft === null) return null const sep = separatorOf(listing) - const cut = draft.lastIndexOf(sep) + const folded = foldSeparatorsFor(sep)(draft) + const cut = folded.lastIndexOf(sep) if (cut === -1) return null const fold = foldPathFor(sep) const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` - return fold(draft.slice(0, cut + 1)) === fold(level) ? draft.slice(cut + 1) : null + return fold(folded.slice(0, cut + 1)) === fold(level) ? folded.slice(cut + 1) : null } /** One column of folder rows (the Miller view renders one or two of these). */ @@ -824,7 +841,15 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // toggling never blur-cancels a draft mid-thought. Outside editing // it keeps native focus behavior. onMouseDown={draftPending ? (event) => { event.preventDefault() } : undefined} - onClick={() => { setShowHidden(prev => !prev) }} + onClick={(event) => { + // The suppression above exists to protect the INPUT's focus; + // when focus is instead on a row that this very toggle may + // re-hide, restore the native outcome — the clicked toggle + // keeps focus in the card (the editing-time refocus effect + // deliberately stays out of the way). + if (focusInMillerRows()) event.currentTarget.focus() + setShowHidden(prev => !prev) + }} > {t('browser.showHidden')} {showHidden && } 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 fcc2b21f92..4434e31eaa 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -412,8 +412,9 @@ describe('DirectoryBrowser', () => { const listing: DirectoryListing = { path: `${SHARE}\\x`, // USERPROFILE ships verbatim; win32.resolve keeps \\server\share as - // the unpoppable root, so this normalizes to \\server\share\x. - home: `${SHARE}\\..\\x`, + // the unpoppable root and folds the doubled separator, so this + // normalizes to \\server\share\x. + home: '\\\\server\\\\share\\..\\x', crumbs: [ { name: `${SHARE}\\`, path: `${SHARE}\\`, hidden: false }, { name: 'x', path: `${SHARE}\\x`, hidden: false }, @@ -536,6 +537,10 @@ describe('DirectoryBrowser', () => { expect(within(columns()[1]!).getByText('Alpha')).toBeTruthy() fireEvent.change(input, { target: { value: 'C:\\Users\\z' } }) expect(within(columns()[1]!).queryAllByRole('listitem')).toHaveLength(0) + // Forward-slash drafts are equally legal on win32 (Enter navigates + // them); the filter folds them instead of going silent. + fireEvent.change(input, { target: { value: 'C:/Users/a' } }) + expect(within(columns()[1]!).getByText('Alpha')).toBeTruthy() }) it('re-parks focus on the edit zone when a failed pick unmounts a dot-revealed row', async () => { @@ -1423,6 +1428,59 @@ describe('DirectoryBrowser', () => { expect(screen.getByText('browser.createIn:/srv/data')).toBeTruthy() }) + it('a crumb-less Windows level still seeds the editor with a backslash', async () => { + // The empty chain degrades separatorOf to the home-text read; the + // backslash side of that fallback is the Windows shape. + const bare: DirectoryListing = { path: 'C:\\srv', home: 'C:\\Users\\u', crumbs: [], entries: [], truncated: false } + mount({ listDirectory: vi.fn(async () => bare) }) + await waitFor(() => { + expect(screen.getByRole('button', { name: 'browser.editPath' }).disabled).toBe(false) + }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + expect(screen.getByLabelText('browser.editPath').value).toBe('C:\\srv\\') + }) + + it('a POSIX home whose name contains a backslash still reads as the display root', async () => { + const WEIRD = '/home/we\\ird' + const listing: DirectoryListing = { + path: WEIRD, + home: WEIRD, + crumbs: [ + { name: '/', path: '/', hidden: false }, + { name: 'home', path: '/home', hidden: false }, + { name: 'we\\ird', path: WEIRD, hidden: false }, + ], + entries: [{ name: 'notes', path: `${WEIRD}/notes`, hidden: false }], + truncated: false, + } + const listDirectory = vi.fn(async () => listing) + mount({ listDirectory }) + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + // The root crumb ('/') decides the platform: the backslash in the name + // neither flips the fold nor breaks the Home collapse. + expect(columns()).toHaveLength(1) + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + expect(listDirectory).toHaveBeenCalledTimes(1) + }) + + it('pointer-toggling hidden off keeps focus on the toggle as the focused row re-hides', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + const toggle = screen.getByRole('button', { name: 'browser.showHidden' }) + fireEvent.click(toggle) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + // Tab parked focus on the revealed hidden row; the pointer click below + // would unmount it (toggle off + empty seeded prefix hides it again). + const hiddenRow = within(columns()[0]!).getByText('.config').closest('button')! + hiddenRow.focus() + fireEvent.mouseDown(toggle) + fireEvent.click(toggle) + expect(screen.queryByText('.config')).toBeNull() + expect(document.activeElement).toBe(toggle) + // The editor survives the whole exchange. + expect(screen.getByLabelText('browser.editPath', { selector: 'input' })).toBeTruthy() + }) + it('refuses to close the nested dialog while the creation is in flight', async () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) From 9545914c10bce92630dc89688114cc73a90f1517 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 01:28:55 +0800 Subject: [PATCH 24/34] =?UTF-8?q?fix(host):=20review=20round=2018=20?= =?UTF-8?q?=E2=80=94=20draft=20dirs=20fully=20normalized;=20JSDoc=20reatta?= =?UTF-8?q?ched;=20third=20parking=20target=20documented?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 70 +++++++++++-------- .../tests/directory-browser.spec.tsx | 9 +++ 5 files changed, 53 insertions(+), 34 deletions(-) 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 81c065227f..f5b5312f73 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: 9008ba928c16a19fae601db0b8a83d44eaeeaae0 -2026-07-28-directory-picker-capability-seam.zh.md: 95ba66062aafb4ebe1ed37219efd5ad94f13f842 +2026-07-28-directory-picker-capability-seam.md: a22b313649a9efb1784f88a30fff3f82b9828347 +2026-07-28-directory-picker-capability-seam.zh.md: fb800fe75bda07198f9b3dc67ac03fb385df919a 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 9008ba928c..a22b313649 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 @@ -19,7 +19,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body; keyboard traversal never falls out of the card (the Modal has no focus trap), except during the owner's adopt window, where `busy` inerts every control and the dialog is closing either way. +- **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body, and a show-hidden toggle click that finds focus among the rows parks synchronously on the toggle itself; keyboard traversal never falls out of the card (the Modal has no focus trap), except during the owner's adopt window, where `busy` inerts every control and the dialog is closing either way. - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. 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 95ba66062a..fb800fe75b 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 @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱),仅 owner 的接纳窗口期间例外——此时 `busy` 把每个控件置为惰性,且对话框反正正在关闭。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区,而点击"显示隐藏"开关时若发现焦点落在行间,则把焦点同步停靠到开关自身;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱),仅 owner 的接纳窗口期间例外——此时 `busy` 把每个控件置为惰性,且对话框反正正在关闭。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——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 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 2e5e732548..bdab232457 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -72,6 +72,15 @@ function foldPathFor(sep: '\\' | '/'): (value: string) => string { return value => (sep === '\\' ? value.toLowerCase() : value) } +/** + * Folds separators to the platform's canonical one: win32 treats a forward + * slash as a separator too (resolve() folds them the same way), while + * POSIX must not — a backslash there is a name character. + */ +function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { + return value => (sep === '\\' ? value.replaceAll('/', sep) : value) +} + /** * Lexically normalizes an absolute host path for comparisons: folds * forward slashes on Windows (win32 accepts either), collapses repeated @@ -82,15 +91,6 @@ function foldPathFor(sep: '\\' | '/'): (value: string) => string { * backend's own paths arrive already resolved. A lexical mirror only: * symlinks are the backend's business. */ -/** - * Folds separators to the platform's canonical one: win32 treats a forward - * slash as a separator too (resolve() folds them the same way), while - * POSIX must not — a backslash there is a name character. - */ -function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { - return value => (sep === '\\' ? value.replaceAll('/', sep) : value) -} - function normalizePathFor(sep: '\\' | '/'): (value: string) => string { const foldSeparators = foldSeparatorsFor(sep) return (raw) => { @@ -161,12 +161,13 @@ function separatorOf(listing: DirectoryListing): '\\' | '/' { * The path draft's final segment, when its directory part names the level * `listing` lists — the segment the level prefix-filters on while the user * types. Any other draft (no separator yet, or naming some other directory) - * leaves the level unfiltered. The directory part compares under the - * platform fold (exact on slash platforms; Windows folds case, since an - * upgraded selection may carry the actual entry's case while the level - * below still carries the typed one — and folds forward slashes, which - * win32 and the backend both accept in typed paths); the name filter - * downstream is case-insensitive everywhere. + * leaves the level unfiltered. The directory part compares lexically + * normalized (dot segments, repeated separators, and win32 forward + * slashes all match what Enter would navigate to) and under the platform + * case fold (exact on slash platforms; Windows folds, since an upgraded + * selection may carry the actual entry's case while the level below still + * carries the typed one); the name filter downstream is case-insensitive + * everywhere. */ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { if (draft === null) return null @@ -175,8 +176,10 @@ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string const cut = folded.lastIndexOf(sep) if (cut === -1) return null const fold = foldPathFor(sep) - const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` - return fold(folded.slice(0, cut + 1)) === fold(level) ? folded.slice(cut + 1) : null + const normalize = normalizePathFor(sep) + return fold(normalize(folded.slice(0, cut + 1))) === fold(normalize(listing.path)) + ? folded.slice(cut + 1) + : null } /** One column of folder rows (the Miller view renders one or two of these). */ @@ -312,25 +315,31 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // whose new level dropped the focused row, a failed pick, and every // create-dialog exit, whose close-time parking is also what a failed // relist inherits) parks on the crumb edit zone, each 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. + // actually fell to body. One parking bypasses both flags: the + // show-hidden toggle's click reclaims focus onto itself, synchronously, + // when the click finds focus among the rows. 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 editZoneRef = useRef(null) /** * Whether the focused element sits among the miller rows — probed before - * a landing replaces the row nodes, to decide focus parking. A probe - * only: it never gates the landing itself — a torn-down ref in a close - * race merely skips the parking, and committing the landing into a - * closing dialog is safe (the component already renders null, and the - * open effect resets parent/selected/child on the next open). + * a landing replaces the row nodes to decide focus parking, and by the + * show-hidden toggle's click to decide whether to reclaim the native + * focus outcome. A probe only: it never gates its caller — a torn-down + * ref in a landing's close race merely skips the parking, and + * committing the landing into a closing dialog is safe (the component + * already renders null, and the open effect resets parent/selected/child + * on the next open). * @returns true when `document.activeElement` is inside the miller row. */ const focusInMillerRows = useCallback((): boolean => { const rowHost = millerRowRef.current - /* v8 ignore next -- close-race guard: the commit-to-effect window is not deterministically reproducible. */ + // Only the landing callers can race a close (commit precedes the reset + // effect); the toggle's click caller always finds the host mounted. + /* v8 ignore next -- close-race guard: not deterministically reproducible. */ if (rowHost === null) return false return rowHost.contains(document.activeElement) }, []) @@ -843,10 +852,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onMouseDown={draftPending ? (event) => { event.preventDefault() } : undefined} onClick={(event) => { // The suppression above exists to protect the INPUT's focus; - // when focus is instead on a row that this very toggle may - // re-hide, restore the native outcome — the clicked toggle - // keeps focus in the card (the editing-time refocus effect - // deliberately stays out of the way). + // with focus among the rows instead, hand back the native + // click outcome wholesale — the clicked toggle takes focus + // and stays in the card. Accepted cost: this also moves + // focus off a row the toggle would NOT have hidden; tracking + // which rows a direction change unmounts is not worth it. if (focusInMillerRows()) event.currentTarget.focus() setShowHidden(prev => !prev) }} 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 4434e31eaa..af40e08fe7 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -541,6 +541,9 @@ describe('DirectoryBrowser', () => { // them); the filter folds them instead of going silent. fireEvent.change(input, { target: { value: 'C:/Users/a' } }) expect(within(columns()[1]!).getByText('Alpha')).toBeTruthy() + // Dot segments normalize on win32 too. + fireEvent.change(input, { target: { value: 'C:\\Users\\.\\a' } }) + expect(within(columns()[1]!).getByText('Alpha')).toBeTruthy() }) it('re-parks focus on the edit zone when a failed pick unmounts a dot-revealed row', async () => { @@ -673,6 +676,12 @@ describe('DirectoryBrowser', () => { // A draft naming some other directory (or none) leaves the level whole. fireEvent.change(input, { target: { value: 'no-separator' } }) expect(screen.getByRole('listitem').textContent).toBe('Documents') + // Dot segments and repeated separators are legal for Enter, so the + // filter's directory comparison normalizes them the same way. + fireEvent.change(input, { target: { value: `${HOME}/./do` } }) + expect(screen.getByRole('listitem').textContent).toBe('Documents') + fireEvent.change(input, { target: { value: `${HOME}//do` } }) + expect(screen.getByRole('listitem').textContent).toBe('Documents') }) it('filters the child pane in two-pane mode and follows the draft back up a level', async () => { From cc92b6b578d930505c57123896ef2f3e39b59793 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 01:50:45 +0800 Subject: [PATCH 25/34] =?UTF-8?q?fix(host,client):=20review=20round=2019?= =?UTF-8?q?=20=E2=80=94=20home=20ships=20resolved=20on=20the=20wire;=20cli?= =?UTF-8?q?ent=20mirror=20shrinks=20to=20the=20draft=20side;=20scoped=20fo?= =?UTF-8?q?cus=20guarantee?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- packages/host/apiproxy/src/api/host.ts | 2 +- .../src/client/DirectoryBrowser.tsx | 66 +++++++++---------- .../host/directory-picker-browse/src/index.ts | 7 +- .../tests/directory-browser.spec.tsx | 57 ++++------------ .../tests/home-shape.spec.ts | 28 ++++++++ .../tests/service.spec.ts | 6 +- packages/host/directory-picker/src/index.ts | 2 +- 10 files changed, 90 insertions(+), 86 deletions(-) create mode 100644 packages/host/directory-picker-browse/tests/home-shape.spec.ts 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 f5b5312f73..0502f5cd0d 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: a22b313649a9efb1784f88a30fff3f82b9828347 -2026-07-28-directory-picker-capability-seam.zh.md: fb800fe75bda07198f9b3dc67ac03fb385df919a +2026-07-28-directory-picker-capability-seam.md: 6cba49f9a5817d05e4933e397918a0b9a17ce845 +2026-07-28-directory-picker-capability-seam.zh.md: bfa9f80db32b1e73a198442826c7aea9972c7412 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 a22b313649..6cba49f9a5 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 @@ -19,7 +19,7 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body, and a show-hidden toggle click that finds focus among the rows parks synchronously on the toggle itself; keyboard traversal never falls out of the card (the Modal has no focus trap), except during the owner's adopt window, where `busy` inerts every control and the dialog is closing either way. +- **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body, and a show-hidden toggle click that finds focus among the rows parks synchronously on the toggle itself. The guarantee is scoped to the dialog's own node replacements — the Modal has no focus trap, so tabbing past the card's edge legitimately leaves, and the owner's adopt window (where `busy` inerts every control and the dialog is closing either way) is likewise outside it. - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. 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 fb800fe75b..bfa9f80db3 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 @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区,而点击"显示隐藏"开关时若发现焦点落在行间,则把焦点同步停靠到开关自身;键盘遍历绝不会落出卡片之外(Modal 没有焦点陷阱),仅 owner 的接纳窗口期间例外——此时 `busy` 把每个控件置为惰性,且对话框反正正在关闭。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区,而点击"显示隐藏"开关时若发现焦点落在行间,则把焦点同步停靠到开关自身。该保证的范围仅限对话框自身的节点替换——Modal 没有焦点陷阱,所以 Tab 越过卡片边缘属于正当离开,而 owner 的接纳窗口(其间 `busy` 把每个控件置为惰性,且对话框反正正在关闭)同样在此范围之外。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——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 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 3d0713e523..25a0698234 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -19,7 +19,7 @@ export interface DirectoryEntry { export interface DirectoryListing { /** Absolute path of the listed directory. */ path: string - /** The host account's home directory (breadcrumb "Home" rooting). */ + /** The host account's home directory (breadcrumb "Home" rooting), in the same resolved shape as `path` and `crumbs[].path`. */ home: string /** * Ancestor chain from the filesystem root to the listed directory diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index bdab232457..0ed8cf3eaa 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -82,19 +82,17 @@ function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { } /** - * Lexically normalizes an absolute host path for comparisons: folds - * forward slashes on Windows (win32 accepts either), collapses repeated - * and trailing separators, drops `.` segments, and applies `..` without - * ever crossing the root — POSIX's `/`, a drive's `C:`, or UNC's - * `\\server\share` pair — mirroring the backend's resolve() for the - * shapes an environment-supplied HOME legally carries verbatim while the - * backend's own paths arrive already resolved. A lexical mirror only: - * symlinks are the backend's business. + * Lexically normalizes a typed absolute path for comparisons against the + * backend's resolved ones (the wire contract keeps `path`, `crumbs[].path`, + * and `home` in resolved shape; only the DRAFT side needs this): collapses + * repeated and trailing separators, drops `.` segments, and applies `..` + * without ever crossing the root — POSIX's `/`, a drive's `C:`, or UNC's + * `\\server\share` pair — mirroring resolve()'s lexical behavior. Expects + * separators already folded to `sep` (foldSeparatorsFor); a lexical mirror + * only, symlinks are the backend's business. */ function normalizePathFor(sep: '\\' | '/'): (value: string) => string { - const foldSeparators = foldSeparatorsFor(sep) - return (raw) => { - const value = foldSeparators(raw) + return (value) => { const unc = sep === '\\' && value.startsWith(`${sep}${sep}`) const rawSegments = (unc ? value.slice(2) : value).split(sep) // Empty segments are separator noise everywhere except POSIX's leading @@ -123,16 +121,14 @@ function normalizePathFor(sep: '\\' | '/'): (value: string) => string { /** * 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. The home comparison folds per platform and lexically - * normalizes both sides, so a typed-case Windows path or a `HOME=/home/u/.` - * shape still collapses to the Home crumb. + * by its own path. `home` and every crumb path arrive in the same resolved + * shape (the wire contract), so only the platform case fold remains — a + * typed-case Windows chain still collapses to the Home crumb. */ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryEntry[] { - const sep = separatorOf(listing) - const fold = foldPathFor(sep) - const normalize = normalizePathFor(sep) - const home = fold(normalize(listing.home)) - const homeIndex = listing.crumbs.findIndex(crumb => fold(normalize(crumb.path)) === home) + const fold = foldPathFor(separatorOf(listing)) + const home = fold(listing.home) + const homeIndex = listing.crumbs.findIndex(crumb => fold(crumb.path) === home) if (homeIndex === -1) return listing.crumbs const tail = listing.crumbs.slice(homeIndex + 1) return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail] @@ -161,13 +157,14 @@ function separatorOf(listing: DirectoryListing): '\\' | '/' { * The path draft's final segment, when its directory part names the level * `listing` lists — the segment the level prefix-filters on while the user * types. Any other draft (no separator yet, or naming some other directory) - * leaves the level unfiltered. The directory part compares lexically - * normalized (dot segments, repeated separators, and win32 forward - * slashes all match what Enter would navigate to) and under the platform - * case fold (exact on slash platforms; Windows folds, since an upgraded - * selection may carry the actual entry's case while the level below still - * carries the typed one); the name filter downstream is case-insensitive - * everywhere. + * leaves the level unfiltered. Only the directory part is lexically + * normalized (dot segments, repeated separators, and win32 forward slashes + * all match what Enter would navigate to) and platform-case-folded (exact + * on slash platforms; Windows folds, since an upgraded selection may carry + * the actual entry's case while the level below still carries the typed + * one); the FINAL segment stays a literal name prefix — a lone `.` reads + * as the dot-reveal, `..` matches no entry (Enter still navigates it) — + * and the name filter downstream is case-insensitive everywhere. */ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { if (draft === null) return null @@ -177,7 +174,7 @@ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string if (cut === -1) return null const fold = foldPathFor(sep) const normalize = normalizePathFor(sep) - return fold(normalize(folded.slice(0, cut + 1))) === fold(normalize(listing.path)) + return fold(normalize(folded.slice(0, cut + 1))) === fold(listing.path) ? folded.slice(cut + 1) : null } @@ -593,15 +590,16 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, if (row !== null && childPath !== undefined) row.scrollLeft = row.scrollWidth }, [childPath]) // Every pick and editor exit that would drop focus to body re-parks it - // after commit, so keyboard traversal stays inside the dialog (the Modal - // has no focus trap): a pick lands on the selection's row — aria-current - // in the freshly rendered left pane, which survives even a right-pane + // after commit, so THIS DIALOG'S OWN node replacements never leak focus + // out of the card: a pick lands on the selection's row — aria-current in + // the freshly rendered left pane, which survives even a right-pane // advance or a create landing replacing the picked button's column — // while the edit-zone exits enumerated at the flag declarations fall - // back to the crumb edit zone. The one window outside this invariant is - // the owner's adopt: busy inerts every control in the card (browsers - // blur disabled elements to body) and no parking applies — the owner - // closes the dialog either way. + // back to the crumb edit zone. Outside the guarantee: the Modal has no + // focus trap, so tabbing past the card's edge legitimately leaves, and + // the owner's adopt window (busy inerts every control; browsers blur + // disabled elements to body) gets no parking — the owner closes the + // dialog either way. useEffect(() => { if (pathDraft !== null) return if (refocusPick.current) { diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index 6fa157ea87..3a2b3d4cdf 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -215,7 +215,12 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { } private async list(path?: string, signal?: AbortSignal): Promise { - const home = homedir() + // Resolved like every other path in the listing: the environment may + // decorate HOME (trailing or repeated separators, dot segments, win32 + // forward slashes) and homedir() ships it verbatim, while clients + // compare home against the resolved `path`/`crumbs` — the wire contract + // promises one canonical shape for all three. + const home = resolve(homedir()) // The seam contract takes fully qualified paths only; resolve() would // silently rebase a relative or empty wire value under the host process // cwd (or, for rooted drive-less Windows forms, its current drive). 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 af40e08fe7..38fe2a5cba 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -240,19 +240,6 @@ describe('DirectoryBrowser', () => { expect(within(columns()[1]!).getByText('harness')).toBeTruthy() }) - // HOME ships verbatim from the environment while listing paths arrive - // resolved; each decoration (trailing, repeated, dot, dot-dot segments) - // must still normalize to the display root — single pane, Home crumb, - // and no parent leg launched. - it.each(['/', '//', '/foo/../.'])('a home decorated with "%s" is still the display root', async (decoration) => { - const listDirectory = vi.fn(async (path?: string) => ({ ...listingFor(path), home: `${HOME}${decoration}` })) - mount({ listDirectory }) - await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) - expect(columns()).toHaveLength(1) - expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() - expect(listDirectory).toHaveBeenCalledTimes(1) - }) - it('a landing whose new level dropped the focused row parks on the edit zone', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) @@ -407,42 +394,16 @@ describe('DirectoryBrowser', () => { expect(document.activeElement?.getAttribute('aria-current')).toBe('true') }) - it('a UNC home with dot-dot never pops the share root and still collapses to Home', async () => { + it('a UNC level is home-collapsed and filters decorated UNC drafts without popping the share root', async () => { const SHARE = '\\\\server\\share' const listing: DirectoryListing = { path: `${SHARE}\\x`, - // USERPROFILE ships verbatim; win32.resolve keeps \\server\share as - // the unpoppable root and folds the doubled separator, so this - // normalizes to \\server\share\x. - home: '\\\\server\\\\share\\..\\x', + home: `${SHARE}\\x`, crumbs: [ { name: `${SHARE}\\`, path: `${SHARE}\\`, hidden: false }, { name: 'x', path: `${SHARE}\\x`, hidden: false }, ], - entries: [], - truncated: false, - } - const listDirectory = vi.fn(async () => listing) - mount({ listDirectory }) - await waitFor(() => { expect(listDirectory).toHaveBeenCalled() }) - await waitFor(() => { expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() }) - expect(columns()).toHaveLength(1) - expect(listDirectory).toHaveBeenCalledTimes(1) - }) - - it('a forward-slash Windows home still reads as the display root', async () => { - const listing: DirectoryListing = { - path: 'C:\\Users\\Alice', - // USERPROFILE may legally use forward slashes; the root crumb (not - // the home text) carries the platform, and normalization folds the - // slashes before comparing. - home: 'C:/Users/Alice', - crumbs: [ - { name: 'C:\\', path: 'C:\\', hidden: false }, - { name: 'Users', path: 'C:\\Users', hidden: false }, - { name: 'Alice', path: 'C:\\Users\\Alice', hidden: false }, - ], - entries: [{ name: 'Desktop', path: 'C:\\Users\\Alice\\Desktop', hidden: false }], + entries: [{ name: 'Alpha', path: `${SHARE}\\x\\Alpha`, hidden: false }], truncated: false, } const listDirectory = vi.fn(async () => listing) @@ -450,7 +411,15 @@ describe('DirectoryBrowser', () => { await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) expect(columns()).toHaveLength(1) expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() - expect(listDirectory).toHaveBeenCalledTimes(1) + // A decorated UNC draft (doubled separator, share-root-crossing dot-dot) + // still normalizes to the listed level: the filter matches what Enter + // would navigate to, and \\server\share stays unpoppable. + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + fireEvent.change(input, { target: { value: '\\\\server\\\\share\\..\\x\\a' } }) + expect(screen.getByText('Alpha')).toBeTruthy() + fireEvent.change(input, { target: { value: `${SHARE}\\x\\z` } }) + expect(screen.queryByRole('listitem')).toBeNull() }) it('collapses a typed-case Windows home to the display root (single pane, Home crumb)', async () => { @@ -682,6 +651,8 @@ describe('DirectoryBrowser', () => { expect(screen.getByRole('listitem').textContent).toBe('Documents') fireEvent.change(input, { target: { value: `${HOME}//do` } }) expect(screen.getByRole('listitem').textContent).toBe('Documents') + fireEvent.change(input, { target: { value: `${HOME}/foo/../do` } }) + expect(screen.getByRole('listitem').textContent).toBe('Documents') }) it('filters the child pane in two-pane mode and follows the draft back up a level', async () => { diff --git a/packages/host/directory-picker-browse/tests/home-shape.spec.ts b/packages/host/directory-picker-browse/tests/home-shape.spec.ts new file mode 100644 index 0000000000..153551f7f9 --- /dev/null +++ b/packages/host/directory-picker-browse/tests/home-shape.spec.ts @@ -0,0 +1,28 @@ +/** + * The wire contract's home shape: a decorated HOME (trailing/repeated + * separators, dot segments — homedir() ships it verbatim) still leaves the + * listing carrying the resolved form, matching `path` and `crumbs[].path`. + */ + +import { resolve } from 'node:path' +import { expect, it, vi } from 'vitest' +import { Context } from 'cordis' + +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, homedir: () => `${actual.homedir()}/.//.` } +}) + +it('resolves a decorated homedir before stamping listing.home', async () => { + const { homedir } = await vi.importActual('node:os') + const { default: BrowseDirectoryPicker } = await import('../src/index.ts') + const ctx = new Context() + const fiber = ctx.plugin(BrowseDirectoryPicker) + await fiber.await() + const picked = ctx.get('directoryPicker')!.capability() + if (picked.kind !== 'browse') throw new Error('browse backend must advertise the browse capability') + const listing = await picked.list() + expect(listing.home).toBe(resolve(homedir())) + expect(listing.path).toBe(listing.home) + await fiber.dispose() +}) diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 002d42e516..98adab3c5d 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -2,7 +2,7 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' import { homedir, tmpdir } from 'node:os' -import { basename, join } from 'node:path' +import { basename, join, resolve } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { Context } from 'cordis' import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker' @@ -48,7 +48,9 @@ describe('BrowseDirectoryPicker', () => { it('lists directories only, flags hidden rows, follows symlinks, skips broken links, sorts by name', async () => { const listing = await capability.list(root) expect(listing.path).toBe(root) - expect(listing.home).toBe(homedir()) + // Resolved like path and crumbs — the environment may decorate HOME, + // and the wire contract promises one canonical shape for all three. + expect(listing.home).toBe(resolve(homedir())) expect(listing.entries.map(entry => entry.name)).toEqual(['.hidden-dir', 'linked', 'projects']) expect(listing.entries.map(entry => entry.hidden)).toEqual([true, false, false]) // Every entry path is absolute and host-joined — clients never join segments. diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 4dba9c9c22..e6aa5791aa 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -38,7 +38,7 @@ export interface DirectoryEntry { export interface DirectoryListing { /** Absolute path of the listed directory. */ path: string - /** The host account's home directory (breadcrumb "Home" rooting). */ + /** The host account's home directory (breadcrumb "Home" rooting), in the same resolved shape as `path` and `crumbs[].path`. */ home: string /** * Ancestor chain from the filesystem root to the listed directory From 983e6d07a45f5e7c2912ed610d66e0ef3968e5ed Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 02:10:07 +0800 Subject: [PATCH 26/34] =?UTF-8?q?fix(host):=20review=20round=2020=20?= =?UTF-8?q?=E2=80=94=20canonical=20shape=20declared=20at=20the=20interface?= =?UTF-8?q?;=20hermetic=20home-shape=20spec;=20single=20resolve?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...directory-picker-capability-seam.i18n.yaml | 4 ++-- ...-07-28-directory-picker-capability-seam.md | 1 + ...-28-directory-picker-capability-seam.zh.md | 1 + .../client/connection/src/client/fixture.ts | 4 ++++ packages/host/apiproxy/src/api/host.ts | 11 +++++++-- .../src/client/DirectoryBrowser.tsx | 5 ++-- .../host/directory-picker-browse/src/index.ts | 11 +++++---- .../tests/home-shape.spec.ts | 24 +++++++++++++++---- packages/host/directory-picker/src/index.ts | 11 +++++++-- 9 files changed, 55 insertions(+), 17 deletions(-) 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 0502f5cd0d..cee7a5f948 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: 6cba49f9a5817d05e4933e397918a0b9a17ce845 -2026-07-28-directory-picker-capability-seam.zh.md: bfa9f80db32b1e73a198442826c7aea9972c7412 +2026-07-28-directory-picker-capability-seam.md: ebd40b9dbc89630c5cbbfacdcfb8be2b6a65fd49 +2026-07-28-directory-picker-capability-seam.zh.md: 6ba8eb347bf906f05ac6192cf941e76d3bc4f44a 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 6cba49f9a5..ebd40b9dbc 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 @@ -22,6 +22,7 @@ Placement and policy rulings folded into this decision: - **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body, and a show-hidden toggle click that finds focus among the rows parks synchronously on the toggle itself. The guarantee is scoped to the dialog's own node replacements — the Modal has no focus trap, so tabbing past the card's edge legitimately leaves, and the owner's adopt window (where `busy` inerts every control and the dialog is closing either way) is likewise outside it. - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. +- **One canonical path shape on the wire.** A listing's `path`, `crumbs[].path`, `entries[].path`, and `home` all ship host-resolved — homedir() output included, since the environment may decorate HOME and the backend resolves it before stamping. Clients compare listing paths verbatim on that promise; the only lexical mirror left in the browse client serves the draft side, the one path a user types and hence naturally non-canonical. Normalizing at the source replaces a client-side mirror of resolve() that had to anticipate every decoration (trailing and repeated separators, dot segments, UNC roots, forward slashes), and the promise binds every browse backend. - **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. - **The native backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide the `native` interaction through its own dialog API). Kind naming: `dialog` was the first pick and was dropped — the browse interaction also presents a dialog (the in-app modal), so the word failed to discriminate; `native` names where the chooser runs. 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 bfa9f80db3..6ba8eb347b 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 @@ -22,6 +22,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区,而点击"显示隐藏"开关时若发现焦点落在行间,则把焦点同步停靠到开关自身。该保证的范围仅限对话框自身的节点替换——Modal 没有焦点陷阱,所以 Tab 越过卡片边缘属于正当离开,而 owner 的接纳窗口(其间 `busy` 把每个控件置为惰性,且对话框反正正在关闭)同样在此范围之外。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——crumb 点按兼作刷新手势,因此宁要新鲜度也不复用手头可能已陈旧的列举,代价是至多两次宿主扫描。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 +- **线上只有一种规范路径形态。** 列举的 `path`、`crumbs[].path`、`entries[].path` 与 `home` 一律以宿主解析后的形态发出——homedir() 的输出也不例外,因为环境可能修饰 HOME,后端在标注前先行解析。客户端凭这一承诺逐字比较列举路径;browse 客户端仅剩的词法镜像服务于草稿一侧——用户键入的那一条路径,因而天然非规范。在源头做规范化,取代了客户端侧那份必须预判每种修饰(末尾与重复的分隔符、点段、UNC 根、正斜杠)的 resolve() 镜像,且这一承诺约束每一个 browse 后端。 - **列举层级有上限,且流式处理。** 单次 `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 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 - **native 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以经自己的对话框 API 提供 `native` 交互)。kind 命名:最初选了 `dialog` 后被放弃——browse 交互同样以对话框呈现(应用内弹窗),这个词起不到判别作用;`native` 命名的是选择器运行的位置。 diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index be9ba79347..22113e7fdb 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -1016,6 +1016,10 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { // same tree the browse primitives serve). pickDirectory: request => ok(request, { path: `${FIXTURE_HOME}/Documents/project` }), listDirectory: (request) => { + // The fixture accepts CANONICAL paths only: a decorated input + // (./, //, ..) misses the tree map and reads as unreadable, where + // the real backend resolve()s it first. The keyless lanes drive + // canonical paths, so the divergence stays out of transcripts. const target = request.payload.path ?? FIXTURE_HOME const children = childrenOf(target) if (children === undefined) { diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 25a0698234..033ca2f112 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -15,11 +15,18 @@ export interface DirectoryEntry { hidden: boolean } -/** host.listDirectory response value: one directory level plus its ancestry. */ +/** + * host.listDirectory response value: one directory level plus its ancestry. + * Every path in one listing — `path`, `crumbs[].path`, `entries[].path`, + * and `home` — is host-resolved canonical form: no `.`/`..` segments, no + * repeated or trailing separators (bare roots `/`, `C:\`, `\\server\share\` + * excepted), one platform separator. Clients compare paths on this promise + * without re-normalizing. + */ export interface DirectoryListing { /** Absolute path of the listed directory. */ path: string - /** The host account's home directory (breadcrumb "Home" rooting), in the same resolved shape as `path` and `crumbs[].path`. */ + /** The host account's home directory (breadcrumb "Home" rooting), in the interface's canonical shape like every other path here. */ home: string /** * Ancestor chain from the filesystem root to the listed directory diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 0ed8cf3eaa..109f69ff2d 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -137,8 +137,9 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE /** * The listing's platform separator, read from the host-resolved root crumb * (`/`, `C:\`, `\\server\share\`) — exact for every root form the backend - * emits, immune both to a home delivered in the other slash flavor - * (`USERPROFILE=C:/Users/Alice`) and to backslashes inside POSIX names. + * emits, and immune to backslashes inside POSIX names (which the home text + * may legally carry; the wire contract already excludes non-canonical + * shapes elsewhere). * TODO: replace with a host-stamped `separator` field on the wire * DirectoryListing so the platform fact travels verbatim (the trade-off is * recorded in the directory-picker capability seam Agent Note). diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index 3a2b3d4cdf..042794a769 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -217,9 +217,12 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { private async list(path?: string, signal?: AbortSignal): Promise { // Resolved like every other path in the listing: the environment may // decorate HOME (trailing or repeated separators, dot segments, win32 - // forward slashes) and homedir() ships it verbatim, while clients - // compare home against the resolved `path`/`crumbs` — the wire contract - // promises one canonical shape for all three. + // forward slashes) and homedir() ships it verbatim, while the wire + // contract promises one canonical shape for every listing path. A + // relative or drive-less HOME rebases under the process cwd / current + // drive here — the behavior the fullyQualified fence refuses for wire + // values — accepted for the host's own environment, since the listed + // target derives from home and stays consistent with it. const home = resolve(homedir()) // The seam contract takes fully qualified paths only; resolve() would // silently rebase a relative or empty wire value under the host process @@ -227,7 +230,7 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { if (path !== undefined && !fullyQualified(path)) { throw new DirectoryPickerError('directory-unreadable', path, `cannot list "${path}": not a fully qualified path`) } - const target = resolve(path ?? home) + const target = path === undefined ? home : resolve(path) // Stream the level (opendir, one dirent at a time) into a name-sorted // window of maxEntries + 1 candidates: memory stays bounded no matter how // many children the directory holds, the window keeps the name-sorted diff --git a/packages/host/directory-picker-browse/tests/home-shape.spec.ts b/packages/host/directory-picker-browse/tests/home-shape.spec.ts index 153551f7f9..569a631388 100644 --- a/packages/host/directory-picker-browse/tests/home-shape.spec.ts +++ b/packages/host/directory-picker-browse/tests/home-shape.spec.ts @@ -2,19 +2,33 @@ * The wire contract's home shape: a decorated HOME (trailing/repeated * separators, dot segments — homedir() ships it verbatim) still leaves the * listing carrying the resolved form, matching `path` and `crumbs[].path`. + * The mock points homedir at a scratch tree so the probe never scans the + * running machine's real home (same hermetic reasoning as service.spec's + * temporary tree); the mock spreads the actual module, so tmpdir stays real. */ -import { resolve } from 'node:path' -import { expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { afterAll, beforeAll, expect, it, vi } from 'vitest' import { Context } from 'cordis' +let scratch: string + vi.mock('node:os', async (importOriginal) => { const actual = await importOriginal() - return { ...actual, homedir: () => `${actual.homedir()}/.//.` } + return { ...actual, homedir: () => `${scratch}/.//.` } +}) + +beforeAll(async () => { + scratch = await mkdtemp(join(tmpdir(), 'dsh-home-shape-')) +}) + +afterAll(async () => { + await rm(scratch, { recursive: true, force: true }) }) it('resolves a decorated homedir before stamping listing.home', async () => { - const { homedir } = await vi.importActual('node:os') const { default: BrowseDirectoryPicker } = await import('../src/index.ts') const ctx = new Context() const fiber = ctx.plugin(BrowseDirectoryPicker) @@ -22,7 +36,7 @@ it('resolves a decorated homedir before stamping listing.home', async () => { const picked = ctx.get('directoryPicker')!.capability() if (picked.kind !== 'browse') throw new Error('browse backend must advertise the browse capability') const listing = await picked.list() - expect(listing.home).toBe(resolve(homedir())) + expect(listing.home).toBe(resolve(scratch)) expect(listing.path).toBe(listing.home) await fiber.dispose() }) diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index e6aa5791aa..1dd15fefa4 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -34,11 +34,18 @@ export interface DirectoryEntry { hidden: boolean } -/** One directory level plus its ancestry, as a browse backend reports it. */ +/** + * One directory level plus its ancestry, as a browse backend reports it. + * Every path in one listing — `path`, `crumbs[].path`, `entries[].path`, + * and `home` — is host-resolved canonical form: no `.`/`..` segments, no + * repeated or trailing separators (bare roots `/`, `C:\`, `\\server\share\` + * excepted), one platform separator. Clients compare paths on this promise + * without re-normalizing; every backend must resolve before stamping. + */ export interface DirectoryListing { /** Absolute path of the listed directory. */ path: string - /** The host account's home directory (breadcrumb "Home" rooting), in the same resolved shape as `path` and `crumbs[].path`. */ + /** The host account's home directory (breadcrumb "Home" rooting), in the interface's canonical shape like every other path here. */ home: string /** * Ancestor chain from the filesystem root to the listed directory From f36bb1e882a053808258537b084199c550315704 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 02:14:58 +0800 Subject: [PATCH 27/34] doc: regenerate cordis catalog for the canonical-shape seam JSDoc --- docs/cordis-catalog/services.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index e0dd17fa02..576b63e4d1 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -500,7 +500,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:131`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:138`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) From 56ac56bb26029ff943ac532f95bed54b331ace13 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 02:30:05 +0800 Subject: [PATCH 28/34] =?UTF-8?q?fix(host):=20review=20round=2021=20?= =?UTF-8?q?=E2=80=94=20create-path=20shape=20promised;=20lexical-not-realp?= =?UTF-8?q?ath=20named;=20hermetic-only=20home=20probes;=20enumerations=20?= =?UTF-8?q?point=20at=20the=20contract?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/host/apiproxy/src/api/host.ts | 9 ++++++--- .../src/client/DirectoryBrowser.tsx | 5 +++-- .../directory-picker-browse/tests/service.spec.ts | 9 ++------- packages/host/directory-picker/README.i18n.yaml | 4 ++-- packages/host/directory-picker/README.md | 2 +- packages/host/directory-picker/README.zh.md | 2 +- packages/host/directory-picker/src/index.ts | 12 +++++++++--- 7 files changed, 24 insertions(+), 19 deletions(-) diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 033ca2f112..19e16bf628 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -20,8 +20,9 @@ export interface DirectoryEntry { * Every path in one listing — `path`, `crumbs[].path`, `entries[].path`, * and `home` — is host-resolved canonical form: no `.`/`..` segments, no * repeated or trailing separators (bare roots `/`, `C:\`, `\\server\share\` - * excepted), one platform separator. Clients compare paths on this promise - * without re-normalizing. + * excepted), one platform separator. Resolution is lexical (`resolve()`), + * never realpath: a symlinked ancestry keeps the logical path the operator + * navigated. Clients compare paths on this promise without re-normalizing. */ export interface DirectoryListing { /** Absolute path of the listed directory. */ @@ -82,7 +83,9 @@ export interface HostApi { * Create one child directory under an existing parent (the browser's * "New folder"). Only served under the `browse` capability; an existing * child fails with `directory-exists`, every other filesystem failure with - * `directory-create-failed`. + * `directory-create-failed`. The returned path is in the listing + * contract's canonical shape — verbatim equal to the child's + * `entries[].path` in the parent's next listing. */ createDirectory( request: RpcRequest<{ path: string; name: string }>, diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 109f69ff2d..7614d77f50 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -83,8 +83,9 @@ function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { /** * Lexically normalizes a typed absolute path for comparisons against the - * backend's resolved ones (the wire contract keeps `path`, `crumbs[].path`, - * and `home` in resolved shape; only the DRAFT side needs this): collapses + * backend's resolved ones (every listing path arrives in the + * DirectoryListing contract's canonical shape; only the DRAFT side, the + * one path a user types, needs this): collapses * repeated and trailing separators, drops `.` segments, and applies `..` * without ever crossing the root — POSIX's `/`, a drive's `C:`, or UNC's * `\\server\share` pair — mirroring resolve()'s lexical behavior. Expects diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 98adab3c5d..0ace7811f1 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -48,8 +48,8 @@ describe('BrowseDirectoryPicker', () => { it('lists directories only, flags hidden rows, follows symlinks, skips broken links, sorts by name', async () => { const listing = await capability.list(root) expect(listing.path).toBe(root) - // Resolved like path and crumbs — the environment may decorate HOME, - // and the wire contract promises one canonical shape for all three. + // The environment may decorate HOME; every listing path ships in the + // DirectoryListing contract's canonical shape, home included. expect(listing.home).toBe(resolve(homedir())) expect(listing.entries.map(entry => entry.name)).toEqual(['.hidden-dir', 'linked', 'projects']) expect(listing.entries.map(entry => entry.hidden)).toEqual([true, false, false]) @@ -163,11 +163,6 @@ describe('BrowseDirectoryPicker', () => { expect(listing.crumbs[0]!.name).toBe(listing.crumbs[0]!.path) }) - it('lists the home directory when no path is given', async () => { - const listing = await capability.list() - expect(listing.path).toBe(homedir()) - }) - it('throws directory-unreadable for a missing target', async () => { const missing = join(root, 'no-such-dir') const failure = await capability.list(missing).catch((error: unknown) => error) diff --git a/packages/host/directory-picker/README.i18n.yaml b/packages/host/directory-picker/README.i18n.yaml index 3e5bae41b5..959608c1b5 100644 --- a/packages/host/directory-picker/README.i18n.yaml +++ b/packages/host/directory-picker/README.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 packages/host/directory-picker/README.md -README.md: 8ef8889c875f5b1d07c015ddef819591041c8d7f -README.zh.md: 8aefffa7b29a47205ea42d0d1df742d1e1b2502d +README.md: 4445af3071d268c5919078278b26f369d9f3ba07 +README.zh.md: 16a90eb698b48438d04154d47afda937c71a4985 diff --git a/packages/host/directory-picker/README.md b/packages/host/directory-picker/README.md index 8ef8889c87..4445af3071 100644 --- a/packages/host/directory-picker/README.md +++ b/packages/host/directory-picker/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The **workspace-directory picking seam** for the web-GUI host: an abstract `DirectoryPicker` service (`ctx.directoryPicker`) whose single contract method `capability()` returns a discriminated capability describing how an operator selects a directory. Backends differ in interaction shape, not just mechanism, so the seam models the shapes explicitly instead of one method set: `{ kind: 'native', pick(signal) }` opens one native OS chooser on the host display ([`-native`](../directory-picker-native/README.md)); `{ kind: 'browse', list(path?), createDirectory(path, name) }` serves listing/creation primitives an in-app browser drives, which works for remote clients no OS chooser can reach ([`-browse`](../directory-picker-browse/README.md)). Consumers switch on `capability().kind`; the union derives from the merge-extensible `DirectoryPickerCapabilities` map (a new backend declaration-merges its shape there), and the documented default for an unknown kind is to hide the picking affordance rather than fail. The capability object must be stable for the service lifetime. The client side mirrors the seam without a wire advertisement: each backend package is dual-face, its browser half registering the matching picking interaction into ui-workspace's directory-flow slots — so one composition row swaps both the host capability and the client flow together. -Browse primitives fail with the typed `DirectoryPickerError` (`directory-unreadable` / `directory-exists` / `directory-create-failed`, each carrying the subject `path`), which the consuming gateway maps 1:1 onto wire error codes. `DirectoryEntry` rows carry a host-owned `hidden` flag (POSIX dot convention) so display policy stays client-side; `DirectoryListing.crumbs` is the ancestor chain from the filesystem root, every crumb a jump target. Design rationale, the `ctx.fs` separation, and the policy decisions live in [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +Browse primitives fail with the typed `DirectoryPickerError` (`directory-unreadable` / `directory-exists` / `directory-create-failed`, each carrying the subject `path`), which the consuming gateway maps 1:1 onto wire error codes. `DirectoryEntry` rows carry a host-owned `hidden` flag (POSIX dot convention) so display policy stays client-side; `DirectoryListing.crumbs` is the ancestor chain from the filesystem root, every crumb a jump target. Every path in one listing — and `createDirectory`'s returned path — ships in host-resolved canonical shape (lexical `resolve()`, never realpath): clients compare listing paths verbatim, so every backend must resolve before stamping. Design rationale, the `ctx.fs` separation, and the policy decisions live in [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). ## Model Experience diff --git a/packages/host/directory-picker/README.zh.md b/packages/host/directory-picker/README.zh.md index 8aefffa7b2..16a90eb698 100644 --- a/packages/host/directory-picker/README.zh.md +++ b/packages/host/directory-picker/README.zh.md @@ -4,7 +4,7 @@ web GUI 宿主的**工作区目录选择 seam**:抽象服务 `DirectoryPicker`(`ctx.directoryPicker`),唯一契约方法 `capability()` 返回一个可辨识能力对象,描述操作者以何种方式选择目录。后端之间的差异在交互形态而不只是机制,因此 seam 显式建模形态而非统一方法集:`{ kind: 'native', pick(signal) }` 在宿主屏幕上打开一个原生 OS 选择器([`-native`](../directory-picker-native/README.md));`{ kind: 'browse', list(path?), createDirectory(path, name) }` 提供应用内浏览器驱动的列举/创建原语,可服务任何 OS 对话框都触及不到的远程客户端([`-browse`](../directory-picker-browse/README.md))。消费方按 `capability().kind` 分支;联合类型由可合并扩展的 `DirectoryPickerCapabilities` 映射派生(新后端在其中声明合并自己的形态),未知 kind 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。client 侧以镜像方式承接该 seam 而不经 wire 广播:每个后端包都是双面包,其 browser half 把匹配的选取交互注册进 ui-workspace 的目录流 slot——因此一行组合同时切换宿主能力与 client 流程。 -浏览原语以带类型的 `DirectoryPickerError` 失败(`directory-unreadable`/`directory-exists`/`directory-create-failed`,各自携带主体 `path`),消费网关将其 1:1 映射为协议错误码。`DirectoryEntry` 行携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示策略留在客户端;`DirectoryListing.crumbs` 是从文件系统根开始的祖先链,每个 crumb 都是跳转目标。设计依据、与 `ctx.fs` 的切分、策略裁决见[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +浏览原语以带类型的 `DirectoryPickerError` 失败(`directory-unreadable`/`directory-exists`/`directory-create-failed`,各自携带主体 `path`),消费网关将其 1:1 映射为协议错误码。`DirectoryEntry` 行携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示策略留在客户端;`DirectoryListing.crumbs` 是从文件系统根开始的祖先链,每个 crumb 都是跳转目标。单次列举中的每个路径——连同 `createDirectory` 返回的路径——都以宿主解析的规范形态交付(词法 `resolve()`,从不 realpath):客户端逐字比较列举路径,因此每个后端都必须先解析再标注。设计依据、与 `ctx.fs` 的切分、策略裁决见[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 ## 模型体验 diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 1dd15fefa4..3f1b523f7e 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -39,8 +39,11 @@ export interface DirectoryEntry { * Every path in one listing — `path`, `crumbs[].path`, `entries[].path`, * and `home` — is host-resolved canonical form: no `.`/`..` segments, no * repeated or trailing separators (bare roots `/`, `C:\`, `\\server\share\` - * excepted), one platform separator. Clients compare paths on this promise - * without re-normalizing; every backend must resolve before stamping. + * excepted), one platform separator. Resolution is lexical (`resolve()`), + * never realpath: a symlinked ancestry keeps the logical path the operator + * navigated (the seam Agent Note's symlink ruling). Clients compare paths + * on this promise without re-normalizing; every backend must resolve + * before stamping. */ export interface DirectoryListing { /** Absolute path of the listed directory. */ @@ -86,7 +89,10 @@ export interface DirectoryPickerBrowseCapability { * Create one child directory under an existing parent. * @param path - absolute existing parent directory. * @param name - single non-blank path segment (no separators, not `.`/`..`). - * @returns the created directory's absolute path. + * @returns the created directory's absolute path, in the listing + * contract's canonical shape — verbatim equal to the child's + * `entries[].path` in the parent's next listing (clients anchor the + * create landing's selection and focus on that equality). * @throws {DirectoryPickerError} `directory-exists` for an existing child, * `directory-create-failed` for a parent that is not fully qualified or any other failure. */ From 8016591ebe757dd207b06e85c479fcefe3c8b1d2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 02:33:06 +0800 Subject: [PATCH 29/34] doc: regenerate cordis catalog for the create-path and lexical-shape seam JSDoc --- docs/cordis-catalog/services.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 576b63e4d1..ea109431ea 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -500,7 +500,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:138`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:144`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) From de24461b9147b0b40e701ca9d93b71094a471412 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 02:53:45 +0800 Subject: [PATCH 30/34] =?UTF-8?q?fix(host):=20review=20round=2022=20?= =?UTF-8?q?=E2=80=94=20note=20enumeration=20includes=20the=20create=20path?= =?UTF-8?q?;=20cross-method=20equality=20pinned;=20NFD-volume=20boundary?= =?UTF-8?q?=20recorded?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...-07-28-directory-picker-capability-seam.i18n.yaml | 4 ++-- .../2026-07-28-directory-picker-capability-seam.md | 2 +- ...2026-07-28-directory-picker-capability-seam.zh.md | 2 +- packages/client/test-runtime/src/workspaces.ts | 4 +++- .../host/directory-picker-browse/README.i18n.yaml | 4 ++-- packages/host/directory-picker-browse/README.md | 1 + packages/host/directory-picker-browse/README.zh.md | 1 + .../src/client/DirectoryBrowser.tsx | 12 ++++++------ .../directory-picker-browse/tests/home-shape.spec.ts | 1 + .../directory-picker-browse/tests/service.spec.ts | 4 ++++ 10 files changed, 22 insertions(+), 13 deletions(-) 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 cee7a5f948..bc62880e58 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: ebd40b9dbc89630c5cbbfacdcfb8be2b6a65fd49 -2026-07-28-directory-picker-capability-seam.zh.md: 6ba8eb347bf906f05ac6192cf941e76d3bc4f44a +2026-07-28-directory-picker-capability-seam.md: 6768ed8f898765396d6a4549a661674b5336c1f3 +2026-07-28-directory-picker-capability-seam.zh.md: f20ea0af278151cb6f9ebd963185701cc3f3f2fd 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 ebd40b9dbc..6768ed8f89 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 @@ -22,7 +22,7 @@ Placement and policy rulings folded into this decision: - **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body, and a show-hidden toggle click that finds focus among the rows parks synchronously on the toggle itself. The guarantee is scoped to the dialog's own node replacements — the Modal has no focus trap, so tabbing past the card's edge legitimately leaves, and the owner's adopt window (where `busy` inerts every control and the dialog is closing either way) is likewise outside it. - **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. -- **One canonical path shape on the wire.** A listing's `path`, `crumbs[].path`, `entries[].path`, and `home` all ship host-resolved — homedir() output included, since the environment may decorate HOME and the backend resolves it before stamping. Clients compare listing paths verbatim on that promise; the only lexical mirror left in the browse client serves the draft side, the one path a user types and hence naturally non-canonical. Normalizing at the source replaces a client-side mirror of resolve() that had to anticipate every decoration (trailing and repeated separators, dot segments, UNC roots, forward slashes), and the promise binds every browse backend. +- **One canonical path shape on the wire.** A listing's `path`, `crumbs[].path`, `entries[].path`, and `home` — and `createDirectory`'s returned path, which clients compare verbatim against the child's next `entries[].path` to anchor the create landing — all ship host-resolved: lexical `resolve()`, never realpath (the symlink ruling above keeps ancestries logical), with homedir() output included since the environment may decorate HOME and the backend resolves it before stamping. Clients compare listing paths verbatim on that promise; the only lexical mirror left in the browse client serves the draft side, the one path a user types and hence naturally non-canonical. Normalizing at the source replaces a client-side mirror of resolve() that had to anticipate every decoration (trailing and repeated separators, dot segments, UNC roots, forward slashes), and the promise binds every browse backend. - **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. - **The native backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide the `native` interaction through its own dialog API). Kind naming: `dialog` was the first pick and was dropped — the browse interaction also presents a dialog (the in-app modal), so the word failed to discriminate; `native` names where the chooser runs. 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 6ba8eb347b..f20ea0af27 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 @@ -22,7 +22,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区,而点击"显示隐藏"开关时若发现焦点落在行间,则把焦点同步停靠到开关自身。该保证的范围仅限对话框自身的节点替换——Modal 没有焦点陷阱,所以 Tab 越过卡片边缘属于正当离开,而 owner 的接纳窗口(其间 `busy` 把每个控件置为惰性,且对话框反正正在关闭)同样在此范围之外。 - **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——crumb 点按兼作刷新手势,因此宁要新鲜度也不复用手头可能已陈旧的列举,代价是至多两次宿主扫描。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 -- **线上只有一种规范路径形态。** 列举的 `path`、`crumbs[].path`、`entries[].path` 与 `home` 一律以宿主解析后的形态发出——homedir() 的输出也不例外,因为环境可能修饰 HOME,后端在标注前先行解析。客户端凭这一承诺逐字比较列举路径;browse 客户端仅剩的词法镜像服务于草稿一侧——用户键入的那一条路径,因而天然非规范。在源头做规范化,取代了客户端侧那份必须预判每种修饰(末尾与重复的分隔符、点段、UNC 根、正斜杠)的 resolve() 镜像,且这一承诺约束每一个 browse 后端。 +- **线上只有一种规范路径形态。** 列举的 `path`、`crumbs[].path`、`entries[].path` 与 `home`——连同 `createDirectory` 返回的路径,客户端拿它与该子项下一次的 `entries[].path` 逐字比较以锚定创建落地——一律以宿主解析后的形态发出:词法 `resolve()`,绝不做 realpath(上文的符号链接裁决保持祖先链为逻辑路径);homedir() 的输出也不例外,因为环境可能修饰 HOME,后端在标注前先行解析。客户端凭这一承诺逐字比较列举路径;browse 客户端仅剩的词法镜像服务于草稿一侧——用户键入的那一条路径,因而天然非规范。在源头做规范化,取代了客户端侧那份必须预判每种修饰(末尾与重复的分隔符、点段、UNC 根、正斜杠)的 resolve() 镜像,且这一承诺约束每一个 browse 后端。 - **列举层级有上限,且流式处理。** 单次 `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 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 - **native 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以经自己的对话框 API 提供 `native` 交互)。kind 命名:最初选了 `dialog` 后被放弃——browse 交互同样以对话框呈现(应用内弹窗),这个词起不到判别作用;`native` 命名的是选择器运行的位置。 diff --git a/packages/client/test-runtime/src/workspaces.ts b/packages/client/test-runtime/src/workspaces.ts index 6c1a9d0aad..d24e7b8c8a 100644 --- a/packages/client/test-runtime/src/workspaces.ts +++ b/packages/client/test-runtime/src/workspaces.ts @@ -142,7 +142,9 @@ export class TestWorkspaces implements IWorkspaces { * Browse child creation (recorded). The default joins parent and name. * @param path - absolute existing parent directory. * @param name - single path segment. - * @returns the created directory's absolute path. + * @returns the created directory's absolute path, in the shape + * `DirectoryPickerBrowseCapability.createDirectory` contracts (verbatim + * equal to the child's `entries[].path` in the parent's next listing). */ async createDirectory(path: string, name: string): Promise { this.calls.push({ method: 'createDirectory', args: [path, name] }) diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index d807bd737a..7d37891821 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 23153881b84dcb71dfb05d4f297a5818c410ca77 -README.zh.md: d7010e2941a801ba6358082824330eaae46e42b7 +README.md: 01e2b9e5afcfd7c47a3f42a76cc1388a25477334 +README.zh.md: 8cb63048713dc964f92762546de783d2ce6ce5a7 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 23153881b8..01e2b9e5af 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -19,5 +19,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **Windows hidden attribute is not read** — Node dirents do not expose `FILE_ATTRIBUTE_HIDDEN`, so `hidden` means dot-prefixed on every platform until a native probe is worth its cost. +- **Name-normalizing volumes void the create-path equality** — `createDirectory` promises its return verbatim-equal to the child's next `entries[].path`; Node's namespaced Win32 paths store even trailing-dot/space segments literally, but a volume that rewrites names on storage (NFD normalization on HFS+-style volumes) breaks the match, and the create landing degrades to the documented single-pane / edit-zone fallback. - **No drive-root enumeration** — on Windows the ancestry stops at the drive root; crossing drives waits for the browser UI's path-entry affordance rather than an enumeration primitive here. - **Whole-filesystem scope** — no per-deployment browse-root restriction; `workspace.create` accepts arbitrary paths today, so a root here would be UX scoping, not a boundary — deferred until a deployment needs it. diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index d7010e2941..8cb6304871 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -19,5 +19,6 @@ ## 已知限制与延期工作 - **不读取 Windows 隐藏属性**——Node 的 dirent 不暴露 `FILE_ATTRIBUTE_HIDDEN`,因此在所有平台上 `hidden` 都意味着点前缀,直到原生探测值回其成本为止。 +- **名称规范化的卷会使创建路径等式失效**——`createDirectory` 承诺其返回值与该子项下一次的 `entries[].path` 逐字相等;Node 带命名空间的 Win32 路径连末尾点/空格段都按字面存储,但在存储时改写名称的卷(HFS+ 风格卷上的 NFD 规范化)会破坏这一匹配,创建落地随之退化为文档所述的单栏/编辑区回退。 - **不枚举盘符根**——Windows 上祖先链止于盘符根;跨盘依赖浏览器 UI 的路径输入入口,而不是这里的枚举原语。 - **全盘可浏览**——没有按部署限定的浏览根;`workspace.create` 今天就接受任意路径,这里的根只会是 UX 范围而非边界——等到有部署需要时再做。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 7614d77f50..3fff931685 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -85,12 +85,12 @@ function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { * Lexically normalizes a typed absolute path for comparisons against the * backend's resolved ones (every listing path arrives in the * DirectoryListing contract's canonical shape; only the DRAFT side, the - * one path a user types, needs this): collapses - * repeated and trailing separators, drops `.` segments, and applies `..` - * without ever crossing the root — POSIX's `/`, a drive's `C:`, or UNC's - * `\\server\share` pair — mirroring resolve()'s lexical behavior. Expects - * separators already folded to `sep` (foldSeparatorsFor); a lexical mirror - * only, symlinks are the backend's business. + * one path a user types, needs this): collapses repeated and trailing + * separators, drops `.` segments, and applies `..` without ever crossing + * the root — POSIX's `/`, a drive's `C:`, or UNC's `\\server\share` pair — + * mirroring resolve()'s lexical behavior. Expects separators already + * folded to `sep` (foldSeparatorsFor); a lexical mirror only, symlinks are + * the backend's business. */ function normalizePathFor(sep: '\\' | '/'): (value: string) => string { return (value) => { diff --git a/packages/host/directory-picker-browse/tests/home-shape.spec.ts b/packages/host/directory-picker-browse/tests/home-shape.spec.ts index 569a631388..b0ae26a921 100644 --- a/packages/host/directory-picker-browse/tests/home-shape.spec.ts +++ b/packages/host/directory-picker-browse/tests/home-shape.spec.ts @@ -38,5 +38,6 @@ it('resolves a decorated homedir before stamping listing.home', async () => { const listing = await picked.list() expect(listing.home).toBe(resolve(scratch)) expect(listing.path).toBe(listing.home) + expect(listing.crumbs.at(-1)!.path).toBe(listing.home) await fiber.dispose() }) diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 0ace7811f1..cfb65af627 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -207,6 +207,10 @@ describe('BrowseDirectoryPicker', () => { expect(created).toBe(join(root, 'fresh')) const listing = await capability.list(root) expect(listing.entries.map(entry => entry.name)).toContain('fresh') + // The contract's cross-method equality: the returned path is verbatim + // the child's entries[].path (clients anchor the create landing's + // selection and focus on it). + expect(listing.entries.find(entry => entry.name === 'fresh')!.path).toBe(created) }) it('refuses an existing child with directory-exists', async () => { From df313b753110e71c41f733c834bae80b482424f3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 03:17:30 +0800 Subject: [PATCH 31/34] =?UTF-8?q?fix(host,client):=20review=20round=2023?= =?UTF-8?q?=20=E2=80=94=20create-path=20contract=20at=20every=20client=20d?= =?UTF-8?q?eclaration;=20close-edge=20resets;=20NFD=20tripwire;=20canonica?= =?UTF-8?q?l=20double=20join?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/src/client/contract/workspaces.ts | 5 +++- .../runtime/src/client/workspaces/service.ts | 3 ++- .../client/test-runtime/src/workspaces.ts | 6 ++--- .../test-runtime/tests/runtime.spec.tsx | 4 ++++ .../directory-picker-browse/README.i18n.yaml | 4 ++-- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../src/client/DirectoryBrowser.tsx | 23 +++++++++++++------ .../src/client/flow.ts | 6 ++++- .../tests/service.spec.ts | 12 ++++++---- 10 files changed, 46 insertions(+), 21 deletions(-) diff --git a/packages/client/runtime/src/client/contract/workspaces.ts b/packages/client/runtime/src/client/contract/workspaces.ts index 9238ea5fd0..ea8dfcf57f 100644 --- a/packages/client/runtime/src/client/contract/workspaces.ts +++ b/packages/client/runtime/src/client/contract/workspaces.ts @@ -48,7 +48,10 @@ export interface IWorkspaces { * Create one child directory through the Host's `browse` capability. * @param path - absolute existing parent directory. * @param name - single non-blank path segment. - * @returns the created directory's absolute path. + * @returns the created directory's absolute path, in the shape + * `DirectoryPickerBrowseCapability.createDirectory` contracts: verbatim + * equal to the child's `entries[].path` in the parent's next listing + * (the browser anchors a create landing's selection on that equality). */ createDirectory(path: string, name: string): Promise /** diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index 1dd3319e79..df7f69a19b 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -208,7 +208,8 @@ export class WorkspacesService implements IWorkspaces { * Create one child directory through the Host's `browse` capability. * @param path - absolute existing parent directory. * @param name - single non-blank path segment. - * @returns the created directory's absolute path. + * @returns the created directory's absolute path, in the shape + * `IWorkspaces.createDirectory` contracts. */ async createDirectory(path: string, name: string): Promise { const response = await this.api.host.createDirectory({ path, name }) diff --git a/packages/client/test-runtime/src/workspaces.ts b/packages/client/test-runtime/src/workspaces.ts index d24e7b8c8a..bfaa414e9f 100644 --- a/packages/client/test-runtime/src/workspaces.ts +++ b/packages/client/test-runtime/src/workspaces.ts @@ -143,14 +143,14 @@ export class TestWorkspaces implements IWorkspaces { * @param path - absolute existing parent directory. * @param name - single path segment. * @returns the created directory's absolute path, in the shape - * `DirectoryPickerBrowseCapability.createDirectory` contracts (verbatim - * equal to the child's `entries[].path` in the parent's next listing). + * `IWorkspaces.createDirectory` contracts. */ async createDirectory(path: string, name: string): Promise { this.calls.push({ method: 'createDirectory', args: [path, name] }) const stub = this.stubs.get('createDirectory') if (stub !== undefined) return await (stub(path, name) as Promise) - return `${path}/${name}` + // Canonical join: a bare-root parent must not double the separator. + return path.endsWith('/') ? `${path}${name}` : `${path}/${name}` } /** diff --git a/packages/client/test-runtime/tests/runtime.spec.tsx b/packages/client/test-runtime/tests/runtime.spec.tsx index b170f69ba2..826a5e4326 100644 --- a/packages/client/test-runtime/tests/runtime.spec.tsx +++ b/packages/client/test-runtime/tests/runtime.spec.tsx @@ -329,12 +329,16 @@ describe('workspaces', () => { await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] }) await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' }) await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh') + // Canonical join: a bare-root parent yields /top, not //top (the + // IWorkspaces contract's verbatim entries[].path equality). + await expect(runtime.workspaces.createDirectory('/', 'top')).resolves.toBe('/top') // The recorded signal seat mirrors the production face (undefined here; // cancellation tests pass and observe a real one). expect(runtime.workspaces.calls).toEqual([ { method: 'listDirectory', args: [undefined, undefined] }, { method: 'listDirectory', args: ['/home/test', undefined] }, { method: 'createDirectory', args: ['/home/test', 'fresh'] }, + { method: 'createDirectory', args: ['/', 'top'] }, ]) // Stubs replace the defaults like every sibling method. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] } diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 7d37891821..2ab8b5a667 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: 01e2b9e5afcfd7c47a3f42a76cc1388a25477334 -README.zh.md: 8cb63048713dc964f92762546de783d2ce6ce5a7 +README.md: d6ed7181ffbec85d11e0abf2aa8d0053173ba4e9 +README.zh.md: 67f5f2bc40297d96bc3fcd3cfba0a3fd26855adc diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 01e2b9e5af..d6ed7181ff 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -19,6 +19,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **Windows hidden attribute is not read** — Node dirents do not expose `FILE_ATTRIBUTE_HIDDEN`, so `hidden` means dot-prefixed on every platform until a native probe is worth its cost. -- **Name-normalizing volumes void the create-path equality** — `createDirectory` promises its return verbatim-equal to the child's next `entries[].path`; Node's namespaced Win32 paths store even trailing-dot/space segments literally, but a volume that rewrites names on storage (NFD normalization on HFS+-style volumes) breaks the match, and the create landing degrades to the documented single-pane / edit-zone fallback. +- **Name-normalizing volumes void the create-path equality** — `createDirectory` promises its return verbatim-equal to the child's next `entries[].path`; Node's namespaced Win32 paths store even trailing-dot/space segments literally, but a volume that rewrites names on storage (NFD normalization on HFS+-style volumes) breaks the match, and the create landing degrades to a two-pane view whose left pane lacks the aria-current row while focus falls back to the crumb edit zone. - **No drive-root enumeration** — on Windows the ancestry stops at the drive root; crossing drives waits for the browser UI's path-entry affordance rather than an enumeration primitive here. - **Whole-filesystem scope** — no per-deployment browse-root restriction; `workspace.create` accepts arbitrary paths today, so a root here would be UX scoping, not a boundary — deferred until a deployment needs it. diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 8cb6304871..67f5f2bc40 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -19,6 +19,6 @@ ## 已知限制与延期工作 - **不读取 Windows 隐藏属性**——Node 的 dirent 不暴露 `FILE_ATTRIBUTE_HIDDEN`,因此在所有平台上 `hidden` 都意味着点前缀,直到原生探测值回其成本为止。 -- **名称规范化的卷会使创建路径等式失效**——`createDirectory` 承诺其返回值与该子项下一次的 `entries[].path` 逐字相等;Node 带命名空间的 Win32 路径连末尾点/空格段都按字面存储,但在存储时改写名称的卷(HFS+ 风格卷上的 NFD 规范化)会破坏这一匹配,创建落地随之退化为文档所述的单栏/编辑区回退。 +- **名称规范化的卷会使创建路径等式失效**——`createDirectory` 承诺其返回值与该子项下一次的 `entries[].path` 逐字相等;Node 带命名空间的 Win32 路径连末尾点/空格段都按字面存储,但在存储时改写名称的卷(HFS+ 风格卷上的 NFD 规范化)会破坏这一匹配,创建落地随之退化为左栏缺少 aria-current 行的双栏视图,同时焦点回落至 crumb 编辑区。 - **不枚举盘符根**——Windows 上祖先链止于盘符根;跨盘依赖浏览器 UI 的路径输入入口,而不是这里的枚举原语。 - **全盘可浏览**——没有按部署限定的浏览根;`workspace.create` 今天就接受任意路径,这里的根只会是 UX 范围而非边界——等到有部署需要时再做。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 3fff931685..7414e08031 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -41,7 +41,12 @@ export interface DirectoryBrowserProps { open: boolean /** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan on the wire. */ listDirectory: (path?: string, signal?: AbortSignal) => Promise - /** Create one child directory under an existing parent. */ + /** + * Create one child directory under an existing parent; the returned path + * is verbatim the child's `entries[].path` in the parent's next listing + * (`IWorkspaces.createDirectory`'s contract) — the create landing anchors + * its selection and focus on that equality. + */ createDirectory: (path: string, name: string) => Promise /** The operator confirmed a directory (the selection, else the listed level). */ onOpen: (path: string) => void @@ -500,19 +505,23 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [child, select]) // Every open starts fresh at the Host home directory; closing invalidates - // any in-flight response so a late arrival cannot repopulate a closed dialog. + // any in-flight response so a late arrival cannot repopulate a closed + // dialog. The per-open state resets live on the CLOSE edge: resetting on + // open would let the reopen's first commit paint one frame of the stale + // view (revealed hidden rows, a pressed toggle) before this passive + // effect runs. useEffect(() => { openGeneration.current += 1 if (open) { - setParent(null) - setSelected(null) - setChild(null) - setCreatingFolder(false) - setShowHidden(false) navigate() return } supersede() + setParent(null) + setSelected(null) + setChild(null) + setCreatingFolder(false) + setShowHidden(false) setError(null) setPathDraft(null) setFolderDraft(null) diff --git a/packages/host/directory-picker-browse/src/client/flow.ts b/packages/host/directory-picker-browse/src/client/flow.ts index 84e49b2c98..878bf7e4db 100644 --- a/packages/host/directory-picker-browse/src/client/flow.ts +++ b/packages/host/directory-picker-browse/src/client/flow.ts @@ -15,7 +15,11 @@ import { DirectoryBrowser } from './DirectoryBrowser.tsx' export interface BrowseFlowInjected { /** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan. */ listDirectory: (path?: string, signal?: AbortSignal) => Promise - /** Create one child directory under an existing parent. */ + /** + * Create one child directory under an existing parent; returns the + * created path in the shape `IWorkspaces.createDirectory` contracts + * (verbatim equal to the child's next `entries[].path`). + */ createDirectory: (path: string, name: string) => Promise /** Localized dialog copy (this package's namespace). */ t: Translate diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index cfb65af627..09b888f5cc 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -203,14 +203,18 @@ describe('BrowseDirectoryPicker', () => { }) it('creates one child directory and surfaces it in the next listing', async () => { - const created = await capability.createDirectory(root, 'fresh') - expect(created).toBe(join(root, 'fresh')) + // The composed-form name (U+00E9) doubles as the name-rewriting + // tripwire: a volume that stores names NFD-decomposed hands back a + // different dirent.name and the equality below goes red — the README's + // documented boundary. + const created = await capability.createDirectory(root, 'café') + expect(created).toBe(join(root, 'café')) const listing = await capability.list(root) - expect(listing.entries.map(entry => entry.name)).toContain('fresh') + expect(listing.entries.map(entry => entry.name)).toContain('café') // The contract's cross-method equality: the returned path is verbatim // the child's entries[].path (clients anchor the create landing's // selection and focus on it). - expect(listing.entries.find(entry => entry.name === 'fresh')!.path).toBe(created) + expect(listing.entries.find(entry => entry.name === 'café')!.path).toBe(created) }) it('refuses an existing child with directory-exists', async () => { From 53e85101b924beedacd9501e0fa839d97cf668ff Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 03:38:43 +0800 Subject: [PATCH 32/34] =?UTF-8?q?fix(host,client):=20review=20round=2024?= =?UTF-8?q?=20=E2=80=94=20close-edge=20facts=20synced;=20wire-hop=20pointe?= =?UTF-8?q?r;=20platform-flavored=20double=20join;=20loading=20reset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../runtime/src/client/contract/workspaces.ts | 8 ++++---- packages/client/test-runtime/src/workspaces.ts | 7 +++++-- .../client/test-runtime/tests/runtime.spec.tsx | 7 ++++++- .../src/client/DirectoryBrowser.tsx | 16 ++++++++++------ .../directory-picker-browse/src/client/flow.ts | 6 +----- 5 files changed, 26 insertions(+), 18 deletions(-) diff --git a/packages/client/runtime/src/client/contract/workspaces.ts b/packages/client/runtime/src/client/contract/workspaces.ts index ea8dfcf57f..2b6f5f4d34 100644 --- a/packages/client/runtime/src/client/contract/workspaces.ts +++ b/packages/client/runtime/src/client/contract/workspaces.ts @@ -48,10 +48,10 @@ export interface IWorkspaces { * Create one child directory through the Host's `browse` capability. * @param path - absolute existing parent directory. * @param name - single non-blank path segment. - * @returns the created directory's absolute path, in the shape - * `DirectoryPickerBrowseCapability.createDirectory` contracts: verbatim - * equal to the child's `entries[].path` in the parent's next listing - * (the browser anchors a create landing's selection on that equality). + * @returns the created directory's absolute path, in the shape the wire + * `HostApi.createDirectory` contracts: verbatim equal to the child's + * `entries[].path` in the parent's next listing (the browser anchors a + * create landing's selection on that equality). */ createDirectory(path: string, name: string): Promise /** diff --git a/packages/client/test-runtime/src/workspaces.ts b/packages/client/test-runtime/src/workspaces.ts index bfaa414e9f..75779f266b 100644 --- a/packages/client/test-runtime/src/workspaces.ts +++ b/packages/client/test-runtime/src/workspaces.ts @@ -149,8 +149,11 @@ export class TestWorkspaces implements IWorkspaces { this.calls.push({ method: 'createDirectory', args: [path, name] }) const stub = this.stubs.get('createDirectory') if (stub !== undefined) return await (stub(path, name) as Promise) - // Canonical join: a bare-root parent must not double the separator. - return path.endsWith('/') ? `${path}${name}` : `${path}/${name}` + // Join in the parent's own separator flavor (a canonical parent ends + // with one only when it is a bare root), so the contract's verbatim + // equality holds for POSIX and Windows fixture trees alike. + const sep = path.includes('\\') ? '\\' : '/' + return path.endsWith(sep) ? `${path}${name}` : `${path}${sep}${name}` } /** diff --git a/packages/client/test-runtime/tests/runtime.spec.tsx b/packages/client/test-runtime/tests/runtime.spec.tsx index 826a5e4326..dcd4bfaadf 100644 --- a/packages/client/test-runtime/tests/runtime.spec.tsx +++ b/packages/client/test-runtime/tests/runtime.spec.tsx @@ -329,9 +329,12 @@ describe('workspaces', () => { await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] }) await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' }) await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh') - // Canonical join: a bare-root parent yields /top, not //top (the + // Canonical join in the parent's own separator flavor: bare roots do + // not double the separator, Windows parents keep backslashes (the // IWorkspaces contract's verbatim entries[].path equality). await expect(runtime.workspaces.createDirectory('/', 'top')).resolves.toBe('/top') + await expect(runtime.workspaces.createDirectory('C:\\', 'top')).resolves.toBe('C:\\top') + await expect(runtime.workspaces.createDirectory('C:\\Users', 'Alice')).resolves.toBe('C:\\Users\\Alice') // The recorded signal seat mirrors the production face (undefined here; // cancellation tests pass and observe a real one). expect(runtime.workspaces.calls).toEqual([ @@ -339,6 +342,8 @@ describe('workspaces', () => { { method: 'listDirectory', args: ['/home/test', undefined] }, { method: 'createDirectory', args: ['/home/test', 'fresh'] }, { method: 'createDirectory', args: ['/', 'top'] }, + { method: 'createDirectory', args: ['C:\\', 'top'] }, + { method: 'createDirectory', args: ['C:\\Users', 'Alice'] }, ]) // Stubs replace the defaults like every sibling method. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 7414e08031..f0f153ecc6 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -37,7 +37,7 @@ import css from './DirectoryBrowser.module.css' /** Owner-supplied browser props: browse calls, pick semantics, and copy. */ export interface DirectoryBrowserProps { - /** Dialog visibility (owner-local; closed unmounts nothing but resets on reopen). */ + /** Dialog visibility (owner-local; closing resets the per-open state, so a reopen starts clean on its first frame). */ open: boolean /** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan on the wire. */ listDirectory: (path?: string, signal?: AbortSignal) => Promise @@ -258,7 +258,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const [error, setError] = useState(null) // Path-edit state: null = breadcrumb mode; a string = the draft being typed. const [pathDraft, setPathDraft] = useState(null) - // Show-hidden toggle state (pure client-side filter, reset on each open). + // Show-hidden toggle state (pure client-side filter, reset on close). const [showHidden, setShowHidden] = useState(false) // Create-folder state: null = closed; a string = the nested dialog's draft. const [folderDraft, setFolderDraft] = useState(null) @@ -334,9 +334,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, * show-hidden toggle's click to decide whether to reclaim the native * focus outcome. A probe only: it never gates its caller — a torn-down * ref in a landing's close race merely skips the parking, and - * committing the landing into a closing dialog is safe (the component - * already renders null, and the open effect resets parent/selected/child - * on the next open). + * committing the landing into a closing dialog is safe: the close edge's + * supersede() fences every later settlement, and the same close effect + * zeroes parent/selected/child for the one frame that can slip between + * the close render and its effect. * @returns true when `document.activeElement` is inside the miller row. */ const focusInMillerRows = useCallback((): boolean => { @@ -509,7 +510,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // dialog. The per-open state resets live on the CLOSE edge: resetting on // open would let the reopen's first commit paint one frame of the stale // view (revealed hidden rows, a pressed toggle) before this passive - // effect runs. + // effect runs. No automated gate observes that ordering (act() hides the + // frame in tests) — this comment is the guard; read it before moving + // these back. useEffect(() => { openGeneration.current += 1 if (open) { @@ -522,6 +525,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setChild(null) setCreatingFolder(false) setShowHidden(false) + setLoading(false) setError(null) setPathDraft(null) setFolderDraft(null) diff --git a/packages/host/directory-picker-browse/src/client/flow.ts b/packages/host/directory-picker-browse/src/client/flow.ts index 878bf7e4db..831eee9476 100644 --- a/packages/host/directory-picker-browse/src/client/flow.ts +++ b/packages/host/directory-picker-browse/src/client/flow.ts @@ -15,11 +15,7 @@ import { DirectoryBrowser } from './DirectoryBrowser.tsx' export interface BrowseFlowInjected { /** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan. */ listDirectory: (path?: string, signal?: AbortSignal) => Promise - /** - * Create one child directory under an existing parent; returns the - * created path in the shape `IWorkspaces.createDirectory` contracts - * (verbatim equal to the child's next `entries[].path`). - */ + /** Create one child directory under an existing parent; returns the created path in the shape `IWorkspaces.createDirectory` contracts. */ createDirectory: (path: string, name: string) => Promise /** Localized dialog copy (this package's namespace). */ t: Translate From b46dcb16cbb570c7ff984cdb292481903f04de09 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 30 Jul 2026 09:22:16 +0800 Subject: [PATCH 33/34] revert: restore the reviewer-approved tree (97a192d7b) ZiyaZhang approved 97a192d7b; the subsequent bot-review rounds (7-24) landed after that approval and were not requested by a human reviewer. This commit restores the approved tree verbatim as a forward commit (pushed history stays intact). git diff 97a192d7b is empty. --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 7 +- ...-28-directory-picker-capability-seam.zh.md | 7 +- docs/cordis-catalog/services.md | 2 +- .../client/connection/src/client/fixture.ts | 4 - .../runtime/src/client/contract/workspaces.ts | 5 +- .../runtime/src/client/workspaces/service.ts | 3 +- .../client/test-runtime/src/workspaces.ts | 9 +- .../test-runtime/tests/runtime.spec.tsx | 9 - packages/host/apiproxy/src/api/host.ts | 16 +- .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 1 - .../host/directory-picker-browse/README.zh.md | 1 - .../src/client/DirectoryBrowser.module.css | 59 +-- .../src/client/DirectoryBrowser.tsx | 371 +++++------------- .../src/client/flow.ts | 2 +- .../host/directory-picker-browse/src/index.ts | 12 +- .../tests/directory-browser.spec.tsx | 309 +-------------- .../tests/home-shape.spec.ts | 43 -- .../tests/service.spec.ts | 25 +- .../host/directory-picker/README.i18n.yaml | 4 +- packages/host/directory-picker/README.md | 2 +- packages/host/directory-picker/README.zh.md | 2 +- packages/host/directory-picker/src/index.ts | 19 +- 24 files changed, 149 insertions(+), 771 deletions(-) delete mode 100644 packages/host/directory-picker-browse/tests/home-shape.spec.ts 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 bc62880e58..900e1d01b6 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: 6768ed8f898765396d6a4549a661674b5336c1f3 -2026-07-28-directory-picker-capability-seam.zh.md: f20ea0af278151cb6f9ebd963185701cc3f3f2fd +2026-07-28-directory-picker-capability-seam.md: ad2aa904beddb2fe941883c3c1827702dbec9964 +2026-07-28-directory-picker-capability-seam.zh.md: 30e719ad9b4e8374496106b447e961a042c7d8b6 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 6768ed8f89..ad2aa904be 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 @@ -19,10 +19,9 @@ Placement and policy rulings folded into this decision: - **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. - **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 read from the host-resolved root crumb (exact for every root form this backend emits: `/`, `C:\`, `\\server\share\`); 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. Focus parking is a card-wide invariant, not an editor-only one: every pick — editing or not, including right-pane advances and create landings whose columns are replaced — re-parks focus on the selection's row after commit, while every other displacing exit (Enter, Escape, a navigation landing whose new level dropped the focused row, a failed pick or create relist, and the nested create dialog closing) falls back to the crumb edit zone whenever focus actually fell to body, and a show-hidden toggle click that finds focus among the rows parks synchronously on the toggle itself. The guarantee is scoped to the dialog's own node replacements — the Modal has no focus trap, so tabbing past the card's edge legitimately leaves, and the owner's adopt window (where `busy` inerts every control and the dialog is closing either way) is likewise outside it. -- **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); on slash platforms (macOS) only a final-segment case drift misses the parent-entry match and keeps the single-pane landing, while ancestor-segment drift still matches — parent entry paths inherit the typed prefix — and lands two panes at the cost of the Home collapse; 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. +- **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. - **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. -- **One canonical path shape on the wire.** A listing's `path`, `crumbs[].path`, `entries[].path`, and `home` — and `createDirectory`'s returned path, which clients compare verbatim against the child's next `entries[].path` to anchor the create landing — all ship host-resolved: lexical `resolve()`, never realpath (the symlink ruling above keeps ancestries logical), with homedir() output included since the environment may decorate HOME and the backend resolves it before stamping. Clients compare listing paths verbatim on that promise; the only lexical mirror left in the browse client serves the draft side, the one path a user types and hence naturally non-canonical. Normalizing at the source replaces a client-side mirror of resolve() that had to anticipate every decoration (trailing and repeated separators, dot segments, UNC roots, forward slashes), and the promise binds every browse backend. - **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. - **The native backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide the `native` interaction through its own dialog API). Kind naming: `dialog` was the first pick and was dropped — the browse interaction also presents a dialog (the in-app modal), so the word failed to discriminate; `native` names where the chooser runs. @@ -35,7 +34,7 @@ Placement and policy rulings folded into this decision: - **Adopting a file-manager/drive-enumeration dependency.** Rejected per the survey above; recorded here as the dependency policy requires. - **A flip-label show-hidden toggle ("Hide hidden files").** Rejected: a flipping action label is ambiguous between state and action and doubles the negative; the fixed label with a pressed presentation states both at once. - **Pure relatedTarget blur cancellation (no mousedown suppression).** Rejected: Safari does not focus buttons on pointer down, so a click's focusout carries a null `relatedTarget` and would cancel the editor before the click lands; editing-scoped mousedown suppression plus the card-anchored relatedTarget guard covers pointer and keyboard paths together. -- **A wire `separator` field on `DirectoryListing` (host stamps `path.sep`).** Deferred, not rejected: it is the authoritative form. The root-crumb read the client uses today is exact for every root shape this backend emits, but it still infers a platform fact from path text and promotes "the chain starts at the root" from backend behavior into a client-relied invariant (the `crumbs` JSDoc does promise it), and it degrades to the old home-text heuristic on an empty chain; a wire field would travel verbatim and survive empty chains and future backends. It touches the seam type and every backend, so the browse client's `separatorOf` carries a TODO pointing at this alternative until a wire change is next scheduled. +- **A wire `separator` field on `DirectoryListing` (host stamps `path.sep`).** Deferred, not rejected: it is the authoritative form — a POSIX home directory containing a backslash defeats the `listing.home` heuristic — but it touches the seam type and every backend; the browse client's `separatorOf` carries a TODO pointing at this alternative until a wire change is next scheduled. ## Consequences 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 f20ea0af27..30e719ad9b 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 @@ -19,10 +19,9 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 - **依赖调研(手写 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 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从宿主解析的根 crumb 读取(对该后端发出的每种根形态都精确:`/`、`C:\`、`\\server\share\`);下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。焦点停靠是卡片全域的不变量,而非编辑器独有:每次选取——无论是否处于编辑态,包括右栏推进与各列被替换的创建落地——提交后都把焦点重新停靠到选中项所在的行上,而其余所有会顶离焦点的退出(Enter、Escape、新层级已不含焦点所在行的导航落地、选取或创建失败后的重新列举,以及嵌套创建对话框的关闭)只要焦点确实落到了 body 上,就回落到 crumb 编辑区,而点击"显示隐藏"开关时若发现焦点落在行间,则把焦点同步停靠到开关自身。该保证的范围仅限对话框自身的节点替换——Modal 没有焦点陷阱,所以 Tab 越过卡片边缘属于正当离开,而 owner 的接纳窗口(其间 `busy` 把每个控件置为惰性,且对话框反正正在关闭)同样在此范围之外。 -- **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。渐进形态的已知边界:指针按压若恰好落在单个 RTT 的升级窗口内,可能因所按行节点被替换而丢失点击(键盘焦点会重新停靠到重新选中的行上;指针的这段窗口则被接受);斜杠平台(macOS)上仅末段的大小写偏差会错过父层级条目匹配,保留单栏落地,而祖先段的偏差仍能匹配——父层级条目路径继承键入的前缀——并落地双栏,代价是 Home 塌缩;且导航总是重新列举两程,哪怕目标就是当前展示的层级——crumb 点按兼作刷新手势,因此宁要新鲜度也不复用手头可能已陈旧的列举,代价是至多两次宿主扫描。 +- **路径编辑器的取消范围:对话框卡片。** browse 客户端的路径编辑器在按 Escape 与焦点离开卡片时取消,两者都在卡片范围的包装层而非输入框上监听——Tab 把焦点停到某个过滤命中的行之后,输入框已不在事件路径上,但 Escape 仍须收起编辑器(而非对话框),其后的焦点离开也仍须取消。不取消的豁免:窗口/标签页失焦、卡片内焦点移动,以及指针路径(编辑期间行与开关在 mousedown 时抑制焦点夺取)。预填与草稿末段过滤所用的分隔符从 `listing.home` 推断;下文的线上字段替代方案记录了被延期的权威形态。编辑器与其过滤的列表之间的 combobox 语义(`aria-expanded`/`aria-controls`/active-descendant、结果播报)同样被延期——目前二者在辅助技术看来是彼此独立的控件。 +- **导航以选中项为锚、渐进落地。** 在展示根之外(与 crumb 头部渲染的是同一塌缩,因此 crumb 与分栏形态永不相左),browse 客户端的导航在目标层级到达的那一刻即提交它——这次首个落定即关闭编辑器并结束加载,因此 Enter 提交的导航绝不会为等待更多内容而被撤回——随后父层级这一程就地升级这次落地:重新选中目标在父层级中的实际条目(Windows 上按平台惯例折叠大小写),右侧展示其子项,因此 crumb 跳转读作后退一栏,而不是塌缩成单列。父层级这一程在落地的 supersession 范围下运行,任何较新的意图都会在线上将其中止;父层级这一程失败,或被截断的父窗口缺少目标时,都保留已提交的单栏落地——升级的存在正是为了锚定选中项,绝不能反而让它悬空。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 -- **线上只有一种规范路径形态。** 列举的 `path`、`crumbs[].path`、`entries[].path` 与 `home`——连同 `createDirectory` 返回的路径,客户端拿它与该子项下一次的 `entries[].path` 逐字比较以锚定创建落地——一律以宿主解析后的形态发出:词法 `resolve()`,绝不做 realpath(上文的符号链接裁决保持祖先链为逻辑路径);homedir() 的输出也不例外,因为环境可能修饰 HOME,后端在标注前先行解析。客户端凭这一承诺逐字比较列举路径;browse 客户端仅剩的词法镜像服务于草稿一侧——用户键入的那一条路径,因而天然非规范。在源头做规范化,取代了客户端侧那份必须预判每种修饰(末尾与重复的分隔符、点段、UNC 根、正斜杠)的 resolve() 镜像,且这一承诺约束每一个 browse 后端。 - **列举层级有上限,且流式处理。** 单次 `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 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 - **native 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以经自己的对话框 API 提供 `native` 交互)。kind 命名:最初选了 `dialog` 后被放弃——browse 交互同样以对话框呈现(应用内弹窗),这个词起不到判别作用;`native` 命名的是选择器运行的位置。 @@ -35,7 +34,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **引入文件管理器/盘符枚举依赖。** 按上文调研否决;依赖政策要求记录于此。 - **动作标签随状态翻转的"显示隐藏"开关("隐藏隐藏文件")。** 否决:会翻转的动作标签在状态与动作之间有歧义,还把否定叠了两层;固定标签加按下态呈现一次说清两者。 - **纯 relatedTarget 失焦取消(不做 mousedown 抑制)。** 否决:Safari 在指针按下时不给按钮聚焦,点击触发的 focusout 因而携带空 `relatedTarget`,会在点击落地前就取消编辑器;编辑期作用的 mousedown 抑制加上锚定卡片的 relatedTarget 守卫才能同时覆盖指针与键盘路径。 -- **在 `DirectoryListing` 上增设线上 `separator` 字段(宿主标注 `path.sep`)。** 延期而非否决:它才是权威形态。客户端今天所用的根 crumb 读取对该后端发出的每种根形态都精确,但它仍是从路径文本推断平台事实,还把"链从根开始"从后端行为提升为客户端所依赖的不变量(`crumbs` 的 JSDoc 确实承诺了这一点),并在链为空时退化回旧的 home 文本启发式;线上字段则会原样随线传输,经得住空链与未来的后端。它触及 seam 类型与每个后端,因此 browse 客户端的 `separatorOf` 挂着指向本方案的 TODO,直到下次安排线上变更。 +- **在 `DirectoryListing` 上增设线上 `separator` 字段(宿主标注 `path.sep`)。** 延期而非否决:它才是权威形态——含反斜杠的 POSIX 家目录会击穿 `listing.home` 启发式——但它触及 seam 类型与每个后端;browse 客户端的 `separatorOf` 挂着指向本方案的 TODO,直到下次安排线上变更。 ## 后果 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index ea109431ea..e0dd17fa02 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -500,7 +500,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:144`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:131`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 22113e7fdb..be9ba79347 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -1016,10 +1016,6 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { // same tree the browse primitives serve). pickDirectory: request => ok(request, { path: `${FIXTURE_HOME}/Documents/project` }), listDirectory: (request) => { - // The fixture accepts CANONICAL paths only: a decorated input - // (./, //, ..) misses the tree map and reads as unreadable, where - // the real backend resolve()s it first. The keyless lanes drive - // canonical paths, so the divergence stays out of transcripts. const target = request.payload.path ?? FIXTURE_HOME const children = childrenOf(target) if (children === undefined) { diff --git a/packages/client/runtime/src/client/contract/workspaces.ts b/packages/client/runtime/src/client/contract/workspaces.ts index 2b6f5f4d34..9238ea5fd0 100644 --- a/packages/client/runtime/src/client/contract/workspaces.ts +++ b/packages/client/runtime/src/client/contract/workspaces.ts @@ -48,10 +48,7 @@ export interface IWorkspaces { * Create one child directory through the Host's `browse` capability. * @param path - absolute existing parent directory. * @param name - single non-blank path segment. - * @returns the created directory's absolute path, in the shape the wire - * `HostApi.createDirectory` contracts: verbatim equal to the child's - * `entries[].path` in the parent's next listing (the browser anchors a - * create landing's selection on that equality). + * @returns the created directory's absolute path. */ createDirectory(path: string, name: string): Promise /** diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index df7f69a19b..1dd3319e79 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -208,8 +208,7 @@ export class WorkspacesService implements IWorkspaces { * Create one child directory through the Host's `browse` capability. * @param path - absolute existing parent directory. * @param name - single non-blank path segment. - * @returns the created directory's absolute path, in the shape - * `IWorkspaces.createDirectory` contracts. + * @returns the created directory's absolute path. */ async createDirectory(path: string, name: string): Promise { const response = await this.api.host.createDirectory({ path, name }) diff --git a/packages/client/test-runtime/src/workspaces.ts b/packages/client/test-runtime/src/workspaces.ts index 75779f266b..6c1a9d0aad 100644 --- a/packages/client/test-runtime/src/workspaces.ts +++ b/packages/client/test-runtime/src/workspaces.ts @@ -142,18 +142,13 @@ export class TestWorkspaces implements IWorkspaces { * Browse child creation (recorded). The default joins parent and name. * @param path - absolute existing parent directory. * @param name - single path segment. - * @returns the created directory's absolute path, in the shape - * `IWorkspaces.createDirectory` contracts. + * @returns the created directory's absolute path. */ async createDirectory(path: string, name: string): Promise { this.calls.push({ method: 'createDirectory', args: [path, name] }) const stub = this.stubs.get('createDirectory') if (stub !== undefined) return await (stub(path, name) as Promise) - // Join in the parent's own separator flavor (a canonical parent ends - // with one only when it is a bare root), so the contract's verbatim - // equality holds for POSIX and Windows fixture trees alike. - const sep = path.includes('\\') ? '\\' : '/' - return path.endsWith(sep) ? `${path}${name}` : `${path}${sep}${name}` + return `${path}/${name}` } /** diff --git a/packages/client/test-runtime/tests/runtime.spec.tsx b/packages/client/test-runtime/tests/runtime.spec.tsx index dcd4bfaadf..b170f69ba2 100644 --- a/packages/client/test-runtime/tests/runtime.spec.tsx +++ b/packages/client/test-runtime/tests/runtime.spec.tsx @@ -329,21 +329,12 @@ describe('workspaces', () => { await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] }) await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' }) await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh') - // Canonical join in the parent's own separator flavor: bare roots do - // not double the separator, Windows parents keep backslashes (the - // IWorkspaces contract's verbatim entries[].path equality). - await expect(runtime.workspaces.createDirectory('/', 'top')).resolves.toBe('/top') - await expect(runtime.workspaces.createDirectory('C:\\', 'top')).resolves.toBe('C:\\top') - await expect(runtime.workspaces.createDirectory('C:\\Users', 'Alice')).resolves.toBe('C:\\Users\\Alice') // The recorded signal seat mirrors the production face (undefined here; // cancellation tests pass and observe a real one). expect(runtime.workspaces.calls).toEqual([ { method: 'listDirectory', args: [undefined, undefined] }, { method: 'listDirectory', args: ['/home/test', undefined] }, { method: 'createDirectory', args: ['/home/test', 'fresh'] }, - { method: 'createDirectory', args: ['/', 'top'] }, - { method: 'createDirectory', args: ['C:\\', 'top'] }, - { method: 'createDirectory', args: ['C:\\Users', 'Alice'] }, ]) // Stubs replace the defaults like every sibling method. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] } diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 19e16bf628..3d0713e523 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -15,19 +15,11 @@ export interface DirectoryEntry { hidden: boolean } -/** - * host.listDirectory response value: one directory level plus its ancestry. - * Every path in one listing — `path`, `crumbs[].path`, `entries[].path`, - * and `home` — is host-resolved canonical form: no `.`/`..` segments, no - * repeated or trailing separators (bare roots `/`, `C:\`, `\\server\share\` - * excepted), one platform separator. Resolution is lexical (`resolve()`), - * never realpath: a symlinked ancestry keeps the logical path the operator - * navigated. Clients compare paths on this promise without re-normalizing. - */ +/** host.listDirectory response value: one directory level plus its ancestry. */ export interface DirectoryListing { /** Absolute path of the listed directory. */ path: string - /** The host account's home directory (breadcrumb "Home" rooting), in the interface's canonical shape like every other path here. */ + /** The host account's home directory (breadcrumb "Home" rooting). */ home: string /** * Ancestor chain from the filesystem root to the listed directory @@ -83,9 +75,7 @@ export interface HostApi { * Create one child directory under an existing parent (the browser's * "New folder"). Only served under the `browse` capability; an existing * child fails with `directory-exists`, every other filesystem failure with - * `directory-create-failed`. The returned path is in the listing - * contract's canonical shape — verbatim equal to the child's - * `entries[].path` in the parent's next listing. + * `directory-create-failed`. */ createDirectory( request: RpcRequest<{ path: string; name: string }>, diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 2ab8b5a667..d807bd737a 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.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 packages/host/directory-picker-browse/README.md -README.md: d6ed7181ffbec85d11e0abf2aa8d0053173ba4e9 -README.zh.md: 67f5f2bc40297d96bc3fcd3cfba0a3fd26855adc +README.md: 23153881b84dcb71dfb05d4f297a5818c410ca77 +README.zh.md: d7010e2941a801ba6358082824330eaae46e42b7 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index d6ed7181ff..23153881b8 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -19,6 +19,5 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **Windows hidden attribute is not read** — Node dirents do not expose `FILE_ATTRIBUTE_HIDDEN`, so `hidden` means dot-prefixed on every platform until a native probe is worth its cost. -- **Name-normalizing volumes void the create-path equality** — `createDirectory` promises its return verbatim-equal to the child's next `entries[].path`; Node's namespaced Win32 paths store even trailing-dot/space segments literally, but a volume that rewrites names on storage (NFD normalization on HFS+-style volumes) breaks the match, and the create landing degrades to a two-pane view whose left pane lacks the aria-current row while focus falls back to the crumb edit zone. - **No drive-root enumeration** — on Windows the ancestry stops at the drive root; crossing drives waits for the browser UI's path-entry affordance rather than an enumeration primitive here. - **Whole-filesystem scope** — no per-deployment browse-root restriction; `workspace.create` accepts arbitrary paths today, so a root here would be UX scoping, not a boundary — deferred until a deployment needs it. diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 67f5f2bc40..d7010e2941 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -19,6 +19,5 @@ ## 已知限制与延期工作 - **不读取 Windows 隐藏属性**——Node 的 dirent 不暴露 `FILE_ATTRIBUTE_HIDDEN`,因此在所有平台上 `hidden` 都意味着点前缀,直到原生探测值回其成本为止。 -- **名称规范化的卷会使创建路径等式失效**——`createDirectory` 承诺其返回值与该子项下一次的 `entries[].path` 逐字相等;Node 带命名空间的 Win32 路径连末尾点/空格段都按字面存储,但在存储时改写名称的卷(HFS+ 风格卷上的 NFD 规范化)会破坏这一匹配,创建落地随之退化为左栏缺少 aria-current 行的双栏视图,同时焦点回落至 crumb 编辑区。 - **不枚举盘符根**——Windows 上祖先链止于盘符根;跨盘依赖浏览器 UI 的路径输入入口,而不是这里的枚举原语。 - **全盘可浏览**——没有按部署限定的浏览根;`workspace.create` 今天就接受任意路径,这里的根只会是 UX 范围而非边界——等到有部署需要时再做。 diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 8bd044f610..85349962e5 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -52,6 +52,24 @@ /* Deep chains scroll inside the trail (the effect pins the tail into view) * so the edit zone to the right never leaves the bar. */ +/* The Miller columns keep their own row so a status/error line below never + * competes with the fixed column widths for horizontal space. */ +/* A narrow viewport shrinks the dialog below two fixed panes; the row + * scrolls horizontally (the effect pins the child pane into view) so + * descent never hides behind the Modal's clipping. */ +.millerRow { + display: flex; + align-items: stretch; + flex: 1 1 0; + min-height: 0; + /* 12px of row gap on each side of the divider; the left side reads wider + * by the column's trailing 8px scrollbar clearance, which is deliberate — + * the thumb needs that room, the right pane's rows do not. */ + gap: 12px; + overflow-x: auto; + scrollbar-width: none; +} + .crumbTrail { display: flex; align-items: center; @@ -62,12 +80,6 @@ scrollbar-width: none; } -/* Pseudo-element-path engines (see .millerRow's twin rule): the 20px crumb - * bar has no room for a bar at all. */ -.crumbTrail::-webkit-scrollbar { - display: none; -} - .crumbSeat { display: inline-flex; align-items: center; @@ -134,36 +146,11 @@ flex-direction: column; flex: 1 1 0; min-height: 0; - /* Right inset is slimmer than the left: the trailing column's own - * scrollbar clearance (see .column) makes up the optical difference. */ + /* Right inset is slimmer than the left: the trailing column's own 8px + * scrollbar clearance makes up the optical difference. */ padding: 16px 16px 16px 24px; } -/* The Miller columns keep their own row so a status/error line below never - * competes with the fixed column widths for horizontal space. */ -/* A narrow viewport shrinks the dialog below two fixed panes; the row - * scrolls horizontally (the effect pins the child pane into view) so - * descent never hides behind the Modal's clipping. */ -.millerRow { - display: flex; - align-items: stretch; - flex: 1 1 0; - min-height: 0; - /* 12px of row gap on each side of the divider; the left side reads wider - * by the column's trailing scrollbar clearance (see .column) — the thumb - * needs that room, the right pane's rows do not. */ - gap: 12px; - overflow-x: auto; - scrollbar-width: none; -} - -/* Engines that predate scrollbar-width take the pseudo-element path (the - * two are mutually exclusive by construction — see ui-theme's scrollbar - * contract); hide the row's horizontal bar there too. */ -.millerRow::-webkit-scrollbar { - display: none; -} - /* Columns split the row evenly around the divider (a solo column takes the * whole row); 256px is the floor below which the row scrolls (scrollbar * hidden, the effect pins the child pane into view) instead of squeezing @@ -305,12 +292,6 @@ color: var(--dsw-alias-label-primary); } -/* Flex-none: the nowrap label refuses to shrink, which would leave the - * glyph as the only compressible item under wrap or narrow-viewport clamp. */ -.toggleCheck { - flex: none; -} - .footerGap { flex: 1 1 0; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index f0f153ecc6..859667d115 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -2,20 +2,16 @@ * The in-app workspace-directory browser (figma Harness 813-23126 family): a * 680×500 dialog (clamped to short/narrow viewports — the Miller row scrolls * sideways, the columns scroll down) whose header carries the title, the selection-path - * breadcrumb, and a click-to-edit path zone; below it a Miller view of one - * or two columns splitting the row evenly (256px floor; level | selected - * folder's children) around a hairline divider — the display root and - * degraded landings keep the single wide level, while any selection opens - * the second pane, including the one a navigation lands with: a crumb jump - * or a submitted path commits the target immediately, then re-selects it - * in its parent level once that level arrives, so stepping back keeps two - * panes away from the display root. Selecting in the + * breadcrumb, and a click-to-edit path zone; below it a Miller view — one + * full-width level until a row is selected, then two columns splitting the + * row evenly (256px floor; level | selected folder's children) around a + * hairline divider. Navigations land selection-anchored: a crumb jump or a + * submitted path commits the target immediately, then re-selects it in its + * parent level once that level arrives, so stepping back keeps two panes + * away from the display root. Selecting in the * right column shifts the view one level deeper. "New folder" opens a nested * create dialog targeting the selected folder (or the level itself) and - * selects the created folder — unless a newer pick or crumb jump supersedes - * the post-create relist, in which case neither the level nor the selection - * refreshes (see closeCreateDialog's two-stage parking for the matching - * focus story). Open adopts the selected folder, falling back + * selects the created folder. Open adopts the selected folder, falling back * to the listed level. Pure consumer of the injected browse calls — the * owning flow decides what "Open" means and owns the workspace-creation * error surface. Hidden entries are host-flagged and hidden by default; the @@ -37,16 +33,11 @@ import css from './DirectoryBrowser.module.css' /** Owner-supplied browser props: browse calls, pick semantics, and copy. */ export interface DirectoryBrowserProps { - /** Dialog visibility (owner-local; closing resets the per-open state, so a reopen starts clean on its first frame). */ + /** Dialog visibility (owner-local; closed unmounts nothing but resets on reopen). */ open: boolean /** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan on the wire. */ listDirectory: (path?: string, signal?: AbortSignal) => Promise - /** - * Create one child directory under an existing parent; the returned path - * is verbatim the child's `entries[].path` in the parent's next listing - * (`IWorkspaces.createDirectory`'s contract) — the create landing anchors - * its selection and focus on that equality. - */ + /** Create one child directory under an existing parent. */ createDirectory: (path: string, name: string) => Promise /** The operator confirmed a directory (the selection, else the listed level). */ onOpen: (path: string) => void @@ -64,126 +55,46 @@ function failureText(error: unknown): string { return error instanceof Error ? error.message : String(error) } -/** - * Case-folds a path for comparisons under the given separator'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; only a - * FINAL-segment macOS case drift misses parent-entry matching and keeps - * the single-pane landing, since parent entry paths inherit the typed - * prefix). - */ -function foldPathFor(sep: '\\' | '/'): (value: string) => string { - return value => (sep === '\\' ? value.toLowerCase() : value) -} - -/** - * Folds separators to the platform's canonical one: win32 treats a forward - * slash as a separator too (resolve() folds them the same way), while - * POSIX must not — a backslash there is a name character. - */ -function foldSeparatorsFor(sep: '\\' | '/'): (value: string) => string { - return value => (sep === '\\' ? value.replaceAll('/', sep) : value) -} - -/** - * Lexically normalizes a typed absolute path for comparisons against the - * backend's resolved ones (every listing path arrives in the - * DirectoryListing contract's canonical shape; only the DRAFT side, the - * one path a user types, needs this): collapses repeated and trailing - * separators, drops `.` segments, and applies `..` without ever crossing - * the root — POSIX's `/`, a drive's `C:`, or UNC's `\\server\share` pair — - * mirroring resolve()'s lexical behavior. Expects separators already - * folded to `sep` (foldSeparatorsFor); a lexical mirror only, symlinks are - * the backend's business. - */ -function normalizePathFor(sep: '\\' | '/'): (value: string) => string { - return (value) => { - const unc = sep === '\\' && value.startsWith(`${sep}${sep}`) - const rawSegments = (unc ? value.slice(2) : value).split(sep) - // Empty segments are separator noise everywhere except POSIX's leading - // root marker, which must survive as the first segment; scrubbing them - // up front keeps a doubled separator from being locked into the UNC - // server + share root below. - const segments = unc ? rawSegments.filter(segment => segment !== '') : rawSegments - // The unpoppable root: POSIX's leading empty segment / the drive - // segment, or UNC's server + share pair. - const rootLength = unc ? 2 : 1 - const out = segments.slice(0, rootLength) - for (const segment of segments.slice(rootLength)) { - if (segment === '' || segment === '.') continue - if (segment === '..') { - if (out.length > rootLength) out.pop() - continue - } - out.push(segment) - } - // A bare root keeps (or regains) the trailing separator resolve() - // emits for `/`, `C:\`, and `\\server\share\`. - return `${unc ? sep + sep : ''}${out.join(sep)}${out.length === rootLength ? sep : ''}` - } -} - /** * 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. `home` and every crumb path arrive in the same resolved - * shape (the wire contract), so only the platform case fold remains — a - * typed-case Windows chain still collapses to the Home crumb. + * by its own path. */ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryEntry[] { - const fold = foldPathFor(separatorOf(listing)) - const home = fold(listing.home) - const homeIndex = listing.crumbs.findIndex(crumb => fold(crumb.path) === home) + const homeIndex = listing.crumbs.findIndex(crumb => crumb.path === listing.home) if (homeIndex === -1) return listing.crumbs const tail = listing.crumbs.slice(homeIndex + 1) return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail] } /** - * The listing's platform separator, read from the host-resolved root crumb - * (`/`, `C:\`, `\\server\share\`) — exact for every root form the backend - * emits, and immune to backslashes inside POSIX names (which the home text - * may legally carry; the wire contract already excludes non-canonical - * shapes elsewhere). + * The listing's platform separator, inferred from the home path the host + * stamped — never from typed text or entry paths, where a backslash is a + * legal POSIX name character. Still a heuristic at the last step: a POSIX + * home directory whose own name contains a backslash would misread. * TODO: replace with a host-stamped `separator` field on the wire * DirectoryListing so the platform fact travels verbatim (the trade-off is * recorded in the directory-picker capability seam Agent Note). */ function separatorOf(listing: DirectoryListing): '\\' | '/' { - const rootCrumb = listing.crumbs.at(0) - // The seam type allows an empty chain (this backend never emits one, but - // create-target naming supports it, see targetName): degrade to a - // best-effort read of the home text — the pre-root-crumb heuristic, with - // its backslash-in-a-POSIX-name blind spot. - if (rootCrumb === undefined) return listing.home.includes('\\') ? '\\' : '/' - return rootCrumb.path.includes('\\') ? '\\' : '/' + return listing.home.includes('\\') ? '\\' : '/' } /** - * The path draft's final segment, when its directory part names the level - * `listing` lists — the segment the level prefix-filters on while the user - * types. Any other draft (no separator yet, or naming some other directory) - * leaves the level unfiltered. Only the directory part is lexically - * normalized (dot segments, repeated separators, and win32 forward slashes - * all match what Enter would navigate to) and platform-case-folded (exact - * on slash platforms; Windows folds, since an upgraded selection may carry - * the actual entry's case while the level below still carries the typed - * one); the FINAL segment stays a literal name prefix — a lone `.` reads - * as the dot-reveal, `..` matches no entry (Enter still navigates it) — - * and the name filter downstream is case-insensitive everywhere. + * The path draft's final segment, when its directory part is exactly the + * level `listing` lists — the segment the level prefix-filters on while the + * user types. Any other draft (no separator yet, or naming some other + * directory) leaves the level unfiltered. The directory part compares + * exactly (it is the host's own path text, reached by seeding or erasing); + * only the name filter downstream is case-insensitive. */ function draftPrefixFor(listing: DirectoryListing, draft: string | null): string | null { if (draft === null) return null const sep = separatorOf(listing) - const folded = foldSeparatorsFor(sep)(draft) - const cut = folded.lastIndexOf(sep) + const cut = draft.lastIndexOf(sep) if (cut === -1) return null - const fold = foldPathFor(sep) - const normalize = normalizePathFor(sep) - return fold(normalize(folded.slice(0, cut + 1))) === fold(listing.path) - ? folded.slice(cut + 1) - : null + const level = listing.path.endsWith(sep) ? listing.path : `${listing.path}${sep}` + return draft.slice(0, cut + 1) === level ? draft.slice(cut + 1) : null } /** One column of folder rows (the Miller view renders one or two of these). */ @@ -224,10 +135,10 @@ function LevelColumn({ entries, selectedPath, busy, onPick, showHidden, filterPr // where the blur lands before our guards) drop this click. // Outside editing, rows keep native focus behavior. onMouseDown={pathEditing ? (event) => { event.preventDefault() } : undefined} - // Focus parking happens after commit (the DirectoryBrowser - // refocus effect): a right-pane pick replaces this very - // column, so focusing the clicked node here would still fall - // to body. + // Editing-time focus parking happens after commit (the + // DirectoryBrowser refocus effect): a right-pane pick replaces + // this very column, so focusing the clicked node here would + // still fall to body. onClick={() => { onPick(entry) }} > {selected @@ -258,7 +169,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const [error, setError] = useState(null) // Path-edit state: null = breadcrumb mode; a string = the draft being typed. const [pathDraft, setPathDraft] = useState(null) - // Show-hidden toggle state (pure client-side filter, reset on close). + // Show-hidden toggle state (pure client-side filter, reset on each open). const [showHidden, setShowHidden] = useState(false) // Create-folder state: null = closed; a string = the nested dialog's draft. const [folderDraft, setFolderDraft] = useState(null) @@ -267,13 +178,8 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const requestSeq = useRef(0) // The in-flight listing's controller: superseding intent aborts the wire // request too — the Host stops scanning — instead of only discarding the - // eventual result while the scan keeps consuming host resources. Always - // holds a controller so no consumer needs a null guard: initially a - // placeholder that the first supersede aborts unused (minted lazily — - // useRef evaluates its argument every render), afterwards the latest - // scan's, settled or aborted between scans. - const [initialScanController] = useState(() => new AbortController()) - const scanController = useRef(initialScanController) + // eventual result while the scan keeps consuming host resources. + const scanController = useRef(null) // Bumped on every open/close edge: settlements from a previous open (a // pending creation included) must never mutate a reopened dialog. const openGeneration = useRef(0) @@ -289,7 +195,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, useEffect(() => () => { requestSeq.current += 1 openGeneration.current += 1 - scanController.current.abort() + scanController.current?.abort() }, []) const compositionGuard = { onCompositionStart: () => { composingRef.current = true }, @@ -298,7 +204,8 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, /** Newer intent wins: invalidate the pending listing's settlement AND abort its wire request. */ const supersede = useCallback((): number => { - scanController.current.abort() + scanController.current?.abort() + scanController.current = null return ++requestSeq.current }, []) @@ -310,54 +217,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, return { seq, scan: listDirectory(path, controller.signal) } }, [supersede, listDirectory]) - // The miller row's scroll host, shared by the pin and refocus effects - // below and read by navigate's upgrade leg (declared ahead of both). - const millerRowRef = useRef(null) - // Focus parking (consumed by the refocus effect below): a pick — and a - // parent-leg upgrade that displaces focused rows — parks on the - // selection's row; every other displacing exit (Enter, Escape, a landing - // whose new level dropped the focused row, a failed pick, and every - // create-dialog exit, whose close-time parking is also what a failed - // relist inherits) parks on the crumb edit zone, each only when focus - // actually fell to body. One parking bypasses both flags: the - // show-hidden toggle's click reclaims focus onto itself, synchronously, - // when the click finds focus among the rows. 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 editZoneRef = useRef(null) - - /** - * Whether the focused element sits among the miller rows — probed before - * a landing replaces the row nodes to decide focus parking, and by the - * show-hidden toggle's click to decide whether to reclaim the native - * focus outcome. A probe only: it never gates its caller — a torn-down - * ref in a landing's close race merely skips the parking, and - * committing the landing into a closing dialog is safe: the close edge's - * supersede() fences every later settlement, and the same close effect - * zeroes parent/selected/child for the one frame that can slip between - * the close render and its effect. - * @returns true when `document.activeElement` is inside the miller row. - */ - const focusInMillerRows = useCallback((): boolean => { - const rowHost = millerRowRef.current - // Only the landing callers can race a close (commit precedes the reset - // effect); the toggle's click caller always finds the host mounted. - /* v8 ignore next -- close-race guard: not deterministically reproducible. */ - if (rowHost === null) return false - return rowHost.contains(document.activeElement) - }, []) - /** * Launch a follow-up listing under the CURRENT supersession seq: a newer * 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. - scanController.current.abort() const controller = new AbortController() scanController.current = controller return listDirectory(path, controller.signal) @@ -372,13 +236,9 @@ 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 (Windows folds case; on slash platforms only a FINAL-segment case - * drift misses the match and keeps the single-pane landing — parent - * entries inherit the typed prefix, so ancestor-segment drift still - * matches, at the cost of the Home collapse). 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. 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) @@ -386,13 +246,6 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setError(null) scan.then((target) => { if (seq !== requestSeq.current) return - // The landing replaces every row key; a slow jump leaves the OLD - // rows tabbable meanwhile (parentInert excludes loading), so focus - // may live among them. With no selection yet the edit zone is the - // park target (body-guarded, like every other exit). The probe never - // gates the commit below — stranding the dialog in loading over a - // focus check would be far worse than a skipped parking. - if (focusInMillerRows()) refocusEditZone.current = true setParent(target) setSelected(null) setChild(null) @@ -406,15 +259,11 @@ 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 (slash - // platforms compare exactly — see foldPathFor). - const fold = foldPathFor(separatorOf(parentLevel)) + // parent level's actual entry so selection comparisons hold. + const sep = separatorOf(parentLevel) + const fold = (value: string): string => (sep === '\\' ? value.toLowerCase() : value) 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. - if (focusInMillerRows()) refocusPick.current = true setParent(parentLevel) setSelected(match) setChild(target) @@ -428,33 +277,25 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setLoading(false) setError(failureText(reason)) }) - }, [launchListing, continueScan, focusInMillerRows]) + }, [launchListing, continueScan]) - /** - * Close the nested create dialog. Its unmount drops focus to body (the - * Modal has no focus trap), so every exit — Escape, mask, Cancel, and a - * successful create — arms the body-guarded edit-zone parking. A - * successful create therefore parks in TWO stages: the edit zone on this - * close, then the relist's select() re-parks on the created row one RTT - * later — deliberately re-parking even focus the user moved during the - * relist window, and doubling as the parking a failed relist inherits. - */ - const closeCreateDialog = useCallback(() => { - setFolderDraft(null) - refocusEditZone.current = true - }, []) + // 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. + const refocusPick = useRef(false) + const refocusEditZone = useRef(false) + const pathInputRef = useRef(null) + const editZoneRef = useRef(null) /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { const { seq, scan } = launchListing(entry.path) // A pick while the path editor is open adopts the (filtered) row and - // closes the editor — the draft served its purpose. EVERY pick re-parks - // focus on the selection after commit (see the refocus effect below): - // a left-pane pick lands on the very row that was clicked (a near - // no-op), while a right-pane advance and a create landing replace the - // picked button's column entirely and would otherwise drop focus to - // body. - refocusPick.current = true + // closes the editor — the draft served its purpose. Focus re-parks on + // the selection after commit (see the refocus effect below). + if (pathDraft !== null) refocusPick.current = true setPathDraft(null) setSelected(entry) setChild(null) @@ -476,7 +317,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // re-parks on the edit zone only if focus actually fell to body. refocusEditZone.current = true }) - }, [launchListing]) + }, [launchListing, pathDraft]) /** Abandon path editing (Escape or clicking away) and restore the crumb view. */ const cancelPathEdit = useCallback(() => { @@ -506,26 +347,19 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [child, select]) // Every open starts fresh at the Host home directory; closing invalidates - // any in-flight response so a late arrival cannot repopulate a closed - // dialog. The per-open state resets live on the CLOSE edge: resetting on - // open would let the reopen's first commit paint one frame of the stale - // view (revealed hidden rows, a pressed toggle) before this passive - // effect runs. No automated gate observes that ordering (act() hides the - // frame in tests) — this comment is the guard; read it before moving - // these back. + // any in-flight response so a late arrival cannot repopulate a closed dialog. useEffect(() => { openGeneration.current += 1 if (open) { + setParent(null) + setSelected(null) + setChild(null) + setCreatingFolder(false) + setShowHidden(false) navigate() return } supersede() - setParent(null) - setSelected(null) - setChild(null) - setCreatingFolder(false) - setShowHidden(false) - setLoading(false) setError(null) setPathDraft(null) setFolderDraft(null) @@ -557,20 +391,19 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // the fresh dialog or issue a relist against the stale target. if (generation !== openGeneration.current) return setCreatingFolder(false) - closeCreateDialog() + setFolderDraft(null) // Land like a right-column pick (figma 802:57446 → 813:23278 flow): the // create target becomes the listed level and the new folder its selection. const { seq, scan } = launchListing(targetPath) setLoading(true) scan.then((level) => { - // The nested dialog closed before this relist launched, so the card - // is interactive meanwhile: a pick or crumb jump supersedes it. + /* v8 ignore next -- same fence as navigate/select; the modal blocks superseding input */ if (seq !== requestSeq.current) return setParent(level) setLoading(false) select({ name, path: createdPath, hidden: false }) }, (reason: unknown) => { - // Same interactive-window fence as the success branch above. + /* v8 ignore next -- same fence as navigate/select; the modal blocks superseding input */ if (seq !== requestSeq.current) return setLoading(false) setError(failureText(reason)) @@ -592,29 +425,19 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [crumbTail]) // On viewports too narrow for both fixed panes the Miller row scrolls; // whenever a child preview lands, pin it into view the way the crumb tail - // pins — otherwise descent is unreachable on a phone-width window. The - // refocus effect's row.focus() and this pin can fight on such viewports, - // and whichever commit runs later wins by design: on a parent-leg - // upgrade (one commit) focus placement runs after the pin and keeps the - // selected LEFT row in view; on a plain advance or create landing the - // child arrives in a later commit, so the pin runs after the focus and - // descent reachability wins. + // pins — otherwise descent is unreachable on a phone-width window. + const millerRowRef = useRef(null) const childPath = child?.path useEffect(() => { const row = millerRowRef.current if (row !== null && childPath !== undefined) row.scrollLeft = row.scrollWidth }, [childPath]) - // Every pick and editor exit that would drop focus to body re-parks it - // after commit, so THIS DIALOG'S OWN node replacements never leak focus - // out of the card: a pick lands on the selection's row — aria-current in - // the freshly rendered left pane, which survives even a right-pane - // advance or a create landing replacing the picked button's column — - // while the edit-zone exits enumerated at the flag declarations fall - // back to the crumb edit zone. Outside the guarantee: the Modal has no - // focus trap, so tabbing past the card's edge legitimately leaves, and - // the owner's adopt window (busy inerts every control; browsers blur - // disabled elements to body) gets no parking — the owner closes the - // dialog either way. + // Every editor exit that would drop focus to body re-parks it after + // commit, so keyboard traversal stays inside the dialog (the Modal has no + // focus trap): a pick lands on the selection's row — aria-current in the + // freshly rendered left pane, which survives even a right-pane advance + // replacing the picked button's column — while Enter and an input-focused + // Escape land on the crumb edit zone that replaces the input. useEffect(() => { if (pathDraft !== null) return if (refocusPick.current) { @@ -624,14 +447,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, /* v8 ignore next -- narrowing guard: the miller row is mounted whenever a pick just committed. */ if (rowHost === null) return const row = rowHost.querySelector('button[aria-current="true"]') - if (row !== null) { - row.focus() - return - } - // The pick lost its row (a truncated relist after Create can drop - // the created directory outside the window): fall through to the - // edit-zone parking below instead of leaving focus where it fell. - refocusEditZone.current = true + /* v8 ignore next -- narrowing guard: the pick that set the flag just rendered its aria-current row. */ + if (row === null) return + row.focus() + return } if (refocusEditZone.current) { refocusEditZone.current = false @@ -639,9 +458,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // the user parked elsewhere (a surviving row) stays theirs. if (document.activeElement !== document.body) return const zone = editZoneRef.current - // The effect already returned while a draft is open, and the close - // reset cleared both flags — so crumb mode's zone is always mounted. - /* v8 ignore next -- narrowing guard: crumb mode always renders the edit zone. */ + /* v8 ignore next -- narrowing guard: crumb mode renders the edit zone whenever the editor just closed. */ if (zone === null) return zone.focus() } @@ -685,13 +502,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // document listener — the same containment the input previously // provided for itself. event.stopPropagation() - // The cancel may unmount whatever holds focus — the input, or a - // dot-revealed row the cleared draft re-hides. Arm the parking - // unconditionally: the refocus effect's body guard already - // distinguishes a surviving focused row (left alone) from focus - // that actually fell. Assignment (not a conditional set) also + // Escape while the input holds focus is about to unmount it; with + // focus already parked on a row, that row survives the cancel and + // keeps focus naturally. Assignment (not a conditional set) also // retires a stale flag a failed or still-upgrading Enter left. - refocusEditZone.current = true + refocusEditZone.current = document.activeElement === pathInputRef.current cancelPathEdit() }} // Focus leaving THIS dialog card while editing cancels like Escape. @@ -775,6 +590,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, value={pathDraft} aria-label={t('browser.editPath')} autoFocus + ref={pathInputRef} disabled={parentInert} onChange={(event) => { // Editing the draft supersedes any in-flight navigation: @@ -863,19 +679,12 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // toggling never blur-cancels a draft mid-thought. Outside editing // it keeps native focus behavior. onMouseDown={draftPending ? (event) => { event.preventDefault() } : undefined} - onClick={(event) => { - // The suppression above exists to protect the INPUT's focus; - // with focus among the rows instead, hand back the native - // click outcome wholesale — the clicked toggle takes focus - // and stays in the card. Accepted cost: this also moves - // focus off a row the toggle would NOT have hidden; tracking - // which rows a direction change unmounts is not worth it. - if (focusInMillerRows()) event.currentTarget.focus() - setShowHidden(prev => !prev) - }} + onClick={() => { setShowHidden(prev => !prev) }} > {t('browser.showHidden')} - {showHidden && } + {/* Trailing check (Menu's selected vocabulary): the label never + * shifts when the pressed state toggles. */} + {showHidden && } @@ -893,7 +702,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, {/* Nested create dialog (figma 813:23278): names one folder inside the target. */} { if (!creatingFolder) closeCreateDialog() }} + onClose={() => { if (!creatingFolder) setFolderDraft(null) }} title={t('browser.newFolder')} className={clsx(css.createDialog)} headless @@ -917,13 +726,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, } if (event.key === 'Escape') { event.stopPropagation() - if (!creatingFolder) closeCreateDialog() + if (!creatingFolder) setFolderDraft(null) } }} /> {createError !== null &&
{createError}
}
- +