From f854b7556bf88d10c3d002b2f66a26616194f3ef Mon Sep 17 00:00:00 2001 From: Yusheng Xu Date: Tue, 6 Oct 2026 19:56:33 +0000 Subject: [PATCH] fix(dashboard): show a Windows gateway path's file name at every basename site --- website/docs/frontend-conventions.md | 7 + website/src/apps/file-explorer/PathBar.tsx | 4 +- website/src/apps/file-explorer/utils.ts | 13 +- website/src/components/DiffBlock.tsx | 3 +- website/src/components/FileRenderers.tsx | 3 +- website/src/components/FoldableDiffBlock.tsx | 3 +- website/src/components/MarkdownPanel.tsx | 9 +- .../chat-input/FilePreviewStrip.tsx | 5 +- website/src/hooks/usePanelTabs.ts | 3 +- website/src/pages/chat/FilesHomePanel.tsx | 3 +- website/src/pages/chat/FolderPanel.tsx | 3 +- website/src/pages/chat/ToolCallLine.tsx | 5 +- website/src/test/pathBasename.test.ts | 68 +++++++++ .../src/test/windowsBasenameSites.test.tsx | 142 ++++++++++++++++++ website/src/utils/fileTokens.ts | 3 +- website/src/utils/pathBasename.ts | 38 +++++ 16 files changed, 290 insertions(+), 22 deletions(-) create mode 100644 website/src/test/pathBasename.test.ts create mode 100644 website/src/test/windowsBasenameSites.test.tsx create mode 100644 website/src/utils/pathBasename.ts diff --git a/website/docs/frontend-conventions.md b/website/docs/frontend-conventions.md index 4b5ba994579a..708f28f418ed 100644 --- a/website/docs/frontend-conventions.md +++ b/website/docs/frontend-conventions.md @@ -428,6 +428,13 @@ payloads. Widening that regex or its key scope is a security change — the same constant also decides which paths are treated as local file reads, so the two decisions must stay on the one exported copy in `urlTransform.ts`. +To SHOW a gateway path's file name, use `pathBasename` (and +`stripTrailingSeparators` for a directory) from `utils/pathBasename.ts`, never +`.split('/').pop()`: a Windows gateway reports `C:\repo\a.ts`, which a `/`-only +split shows whole. The helper treats `\` as a separator only in a drive-rooted +or backslash-UNC path, because on POSIX a backslash is a legal file-name +character. It is display-only and decides nothing about which paths may be read. + ## Data fetching The shared memory editor keeps the existing global V1 Key/Value/Set action diff --git a/website/src/apps/file-explorer/PathBar.tsx b/website/src/apps/file-explorer/PathBar.tsx index 2939a765d913..d4b96ead762e 100644 --- a/website/src/apps/file-explorer/PathBar.tsx +++ b/website/src/apps/file-explorer/PathBar.tsx @@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query' import { FolderTree, Folder, File, GitBranch } from 'lucide-react' import Clickable from '../../components/Clickable' import { fileExplorerApi } from './api' -import { basename, parentChain } from './utils' +import { crumbLabel, parentChain } from './utils' import { useDebouncedValue } from './hooks' import type { GitInfo, TreeEntry } from './types' @@ -121,7 +121,7 @@ export default function PathBar({ rootPath, gitInfo, onChangeRoot, onNavigate }: {i > 0 && /} { e.stopPropagation(); onChangeRoot(s) }} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onChangeRoot(s) } }}> - {i === 0 ? '/' : basename(s) || s} + {i === 0 ? '/' : crumbLabel(s) || s} ))} diff --git a/website/src/apps/file-explorer/utils.ts b/website/src/apps/file-explorer/utils.ts index b98f31a73e69..4c921d8324b4 100644 --- a/website/src/apps/file-explorer/utils.ts +++ b/website/src/apps/file-explorer/utils.ts @@ -2,6 +2,7 @@ import { safeSetItem } from '../../utils/safeStorage' import { STORAGE_KEY } from './constants' import { fmtBytes, fmtDateTimeNumeric } from '../../i18n/format' import { hasCommandModifier } from '../../utils/commandModifier' +import { pathBasename, stripTrailingSeparators } from '../../utils/pathBasename' export const extOf = (p: string) => { const slash = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')) @@ -11,11 +12,7 @@ export const extOf = (p: string) => { return base.slice(i).toLowerCase() } -export const basename = (p: string) => { - const s = p.replace(/\/+$/, '') - const i = s.lastIndexOf('/') - return i < 0 ? s : s.slice(i + 1) -} +export const basename = (p: string) => pathBasename(stripTrailingSeparators(p)) export const dirname = (p: string) => { const s = p.replace(/\/+$/, '') @@ -24,6 +21,12 @@ export const dirname = (p: string) => { return s.slice(0, i) } +/** Label for one `parentChain` crumb. The chain is built by splitting on `/` + * only, so its label splits on `/` only too: a Windows root stays one crumb + * showing the whole path, exactly as before #14581. Breadcrumb navigation for + * Windows roots is a separate change. */ +export const crumbLabel = (p: string) => p.replace(/\/+$/, '').split('/').at(-1) ?? '' + export const parentChain = (p: string) => { const out: string[] = [] let cur = p.replace(/\/+$/, '') diff --git a/website/src/components/DiffBlock.tsx b/website/src/components/DiffBlock.tsx index 20e332469809..46b1fc2eaf10 100644 --- a/website/src/components/DiffBlock.tsx +++ b/website/src/components/DiffBlock.tsx @@ -13,6 +13,7 @@ import { usePlainDiff } from '../hooks/usePlainDiff' import { i18nT } from '../i18n/t' import { useLanguageGeneration } from '../i18n/useLanguageGeneration' +import { pathBasename } from '../utils/pathBasename' /** Extract the target file path from unified-diff header lines. * @@ -93,7 +94,7 @@ export function extractFilePath(code: string): { path: string; prefixStripped: b * path, making "relative spelling absent" meaningless as evidence. */ const ROOTLESS_ABS_RE = /^(home|Users|tmp|var|opt|workplace)\// -const basename = (path: string) => path.slice(path.lastIndexOf('/') + 1) +const basename = pathBasename /** What a file's header row is titled: the basename, and for a rename the old * basename, an arrow, the new one. The full path is the wrapper's tooltip and diff --git a/website/src/components/FileRenderers.tsx b/website/src/components/FileRenderers.tsx index d5ae6b246697..41e3a2868ce2 100644 --- a/website/src/components/FileRenderers.tsx +++ b/website/src/components/FileRenderers.tsx @@ -10,6 +10,7 @@ import { useCanOpenFile, useCopyAck } from './FilePathMenu' import { fileDownloadUrl, fileStreamUrl, fileOfficePreviewUrl, fileOfficeSlidesUrl, fileOfficeSlideUrl } from '../utils/fileReadUrl' import { sendErrorToChat } from '../utils/errorReport' import { useLanguageGeneration } from '../i18n/useLanguageGeneration' +import { pathBasename } from '../utils/pathBasename' /* ── extension helpers ── */ const IMG_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.avif', '.svg', '.ico']) const CSV_EXTS = new Set(['.csv', '.tsv']) @@ -78,7 +79,7 @@ export const ImageViewer = memo(function ImageViewer({ filePath }: { filePath: s
{filePath.split('/').pop()} diff --git a/website/src/components/FoldableDiffBlock.tsx b/website/src/components/FoldableDiffBlock.tsx index 664c129c82f6..144f98a91483 100644 --- a/website/src/components/FoldableDiffBlock.tsx +++ b/website/src/components/FoldableDiffBlock.tsx @@ -5,6 +5,7 @@ import DiffBlock, { extractFilePath } from './DiffBlock' import { countDiffStats } from '../utils/diffLineCounts' import { i18nT } from '../i18n/t' import { useLanguageGeneration } from '../i18n/useLanguageGeneration' +import { pathBasename } from '../utils/pathBasename' /** * A prose ```diff fence, COLLAPSED to a one-line chip by default. @@ -76,7 +77,7 @@ export default memo(function FoldableDiffBlock({ code, complete, onFileOpen, pat const headerPath = useMemo(() => extractFilePath(code)?.path, [code]) ?? pathHint ?? null // The chip shows the basename; two changed files sharing a name would render // as identical chips, so the full path lives in the native tooltip. - const basename = headerPath ? headerPath.split('/').pop() : null + const basename = headerPath ? pathBasename(headerPath) : null // An aria-label REPLACES the button's text, so the counts have to be in it: // without them a screen-reader user cannot hear how large the patch is // without opening it, which is the one decision the chip exists to support. diff --git a/website/src/components/MarkdownPanel.tsx b/website/src/components/MarkdownPanel.tsx index a76c053e99e0..2f478679d667 100644 --- a/website/src/components/MarkdownPanel.tsx +++ b/website/src/components/MarkdownPanel.tsx @@ -373,6 +373,7 @@ import { i18nT } from '../i18n/t' import { useDocumentImeLatch, useImeGuard } from '../hooks/useImeGuard' import { useScrollMemory } from '../hooks/useScrollMemory' import FilePathMenu, { revealOrOpen, useRevealLabel, useCanOpenFile } from './FilePathMenu' +import { pathBasename } from '../utils/pathBasename' /** * File types that render through a dedicated viewer instead of a text editor. @@ -898,7 +899,7 @@ function useFileKnowledgeState(filePath: string, onError: ReportError) { }) const { mutate: add, isPending: adding, isSuccess: added, data: addResult, reset } = useMutation({ mutationFn: async () => { - const name = filePath.split('/').pop() || filePath + const name = pathBasename(filePath) || filePath const res = await fetch('/api/knowledge/sources', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -946,7 +947,7 @@ function useFileArtifactState(filePath: string, content: string, onError: Report const existing = data ?? null const { mutate: add, isPending: adding, isSuccess: added, reset: resetAdd } = useMutation({ mutationFn: async () => { - const name = filePath.split('/').pop() || filePath + const name = pathBasename(filePath) || filePath const ext = '.' + (filePath.split('.').pop() || '').toLowerCase() const kind: 'markdown' | 'json' | 'svg' | 'html' | 'text' = ext === '.md' || ext === '.markdown' || ext === '.mdx' ? 'markdown' @@ -1028,7 +1029,7 @@ function useFileArtifactState(filePath: string, content: string, onError: Report } // Not yet an artifact — create (file-backed), then pin. createArtifact // dedups on source_path server-side, so this stays idempotent. - const name = filePath.split('/').pop() || filePath + const name = pathBasename(filePath) || filePath const ext = '.' + (filePath.split('.').pop() || '').toLowerCase() const kind: 'markdown' | 'json' | 'svg' | 'html' | 'text' = ext === '.md' || ext === '.markdown' || ext === '.mdx' ? 'markdown' @@ -1294,7 +1295,7 @@ export default memo(forwardRef(function MarkdownPane // instead of yanking focus and aborting the composition // (`useDialogFocusTrap` is the reference consumer of the same seam). const fsImeLatch = useDocumentImeLatch(fullscreen) - const fileName = filePath.split('/').pop() || filePath + const fileName = pathBasename(filePath) || filePath // Artifact + knowledge state power the header star/knowledge toggles and // the ⋯ menu's Snapshot entry (same query cache as the OverflowMenu's own // hooks, so states stay coherent). diff --git a/website/src/components/chat-input/FilePreviewStrip.tsx b/website/src/components/chat-input/FilePreviewStrip.tsx index a64ebdf96db4..745cf41aba49 100644 --- a/website/src/components/chat-input/FilePreviewStrip.tsx +++ b/website/src/components/chat-input/FilePreviewStrip.tsx @@ -6,6 +6,7 @@ import { useScrollEdges } from '../../hooks/useScrollEdges' import { IMG_EXT, buildFileLabels } from '../../utils/fileTokens' import type { ResizeInfo } from '../../utils/resizeImage' import { i18nT } from '../../i18n/t' +import { pathBasename } from '../../utils/pathBasename' /** Accent pill under a downscaled attachment chip. Hover (or focus) shows a * styled tooltip with the resize details through the shared `InstantTip` @@ -89,7 +90,7 @@ export function FilePreviewStrip({ files, dirs = NO_DIRS, resizedInfo, onRemove, {i + 1} )} diff --git a/website/src/hooks/usePanelTabs.ts b/website/src/hooks/usePanelTabs.ts index 9206388d3406..267c3f54d9fc 100644 --- a/website/src/hooks/usePanelTabs.ts +++ b/website/src/hooks/usePanelTabs.ts @@ -9,6 +9,7 @@ import { panelTabDescriptor, type PanelTabDescriptor, } from './panelTabRegistry' +import { pathBasename, stripTrailingSeparators } from '../utils/pathBasename' /** Singleton "view" tabs (opened from the + menu, one instance each). */ export type ViewKind = 'changes' | 'issues' | 'links' | 'files' | 'artifacts' | 'subagents' | 'workflows' | 'logs' | 'crewlog' | 'context' | 'side' | 'browser' | 'git' | 'summary' | 'pins' | 'command-center' @@ -269,7 +270,7 @@ const nextRevealNonce = (): number => ++revealSeq /** Last path segment. Trailing slashes are stripped first: '/a/b/'.split('/') * ends in '' which is falsy, so the naive form would fall back to the whole * path and title a directory tab '/a/b/' instead of 'b'. */ -const basename = (p: string) => p.replace(/\/+$/, '').split('/').pop() || p +const basename = (p: string) => pathBasename(stripTrailingSeparators(p)) || p type Bucket = { tabs: PanelTab[]; activeId: string | null } type BySlot = Record diff --git a/website/src/pages/chat/FilesHomePanel.tsx b/website/src/pages/chat/FilesHomePanel.tsx index 14c8b9606e61..53ba0e163e4e 100644 --- a/website/src/pages/chat/FilesHomePanel.tsx +++ b/website/src/pages/chat/FilesHomePanel.tsx @@ -10,10 +10,11 @@ import { import FileBrowserRail, { useTreeState, useTreeQuery } from './FileBrowserRail' import { searchErrorCause, TREE_FAILURE_KEYS } from '../../lib/searchErrorCause' import { reportForError } from '../../utils/errorReport' +import { pathBasename, stripTrailingSeparators } from '../../utils/pathBasename' /** Last path segment, trailing slashes ignored. */ function basename(p: string): string { - return p.replace(/\/+$/, '').split('/').pop() || p + return pathBasename(stripTrailingSeparators(p)) || p } /** diff --git a/website/src/pages/chat/FolderPanel.tsx b/website/src/pages/chat/FolderPanel.tsx index d0512c1b29c0..f8b240444636 100644 --- a/website/src/pages/chat/FolderPanel.tsx +++ b/website/src/pages/chat/FolderPanel.tsx @@ -22,10 +22,11 @@ import { } from '../../lib/searchErrorCause' import { PierreWorkspaceTree } from '../../pierre/tree' import { useTreeState, useTreeQuery } from './FileBrowserRail' +import { pathBasename, stripTrailingSeparators } from '../../utils/pathBasename' /** Last path segment, trailing slashes ignored. */ function basename(p: string): string { - return p.replace(/\/+$/, '').split('/').pop() || p + return pathBasename(stripTrailingSeparators(p)) || p } /** diff --git a/website/src/pages/chat/ToolCallLine.tsx b/website/src/pages/chat/ToolCallLine.tsx index ee7146c83612..cefdaaf5f5f2 100644 --- a/website/src/pages/chat/ToolCallLine.tsx +++ b/website/src/pages/chat/ToolCallLine.tsx @@ -34,6 +34,7 @@ import { useLanguageGeneration } from '../../i18n/useLanguageGeneration' import { isRejectedDecision } from '../../utils/approvalDecision' import { selectToolRowIndex, lookupLogEntry, denySiblingContent } from './toolRowIndex' import type { ToolActivity } from '../../types' +import { pathBasename } from '../../utils/pathBasename' // Stable empties for slots with no per-slot state yet. A fresh `[]` per // selector run would change identity every dispatch and defeat the @@ -802,7 +803,7 @@ export default memo(function ToolCallLine({ message, running: _running, slot, on // icon, so the affordance names the file it opens — crucial in simplified / // purpose mode where the label is prose and no path is otherwise shown. The // full path stays in the button tooltip and the expanded details. - const basename = useMemo(() => (filePath ? (filePath.split('/').pop() || filePath) : null), [filePath]) + const basename = useMemo(() => (filePath ? (pathBasename(filePath) || filePath) : null), [filePath]) // When the chip is shown, strip the now-redundant path out of the visible // label. A derived `Read src/a.ts` → `Read` (the title carries the display // path, the chip the basename); purpose-mode prose contains no path substring @@ -1088,7 +1089,7 @@ export default memo(function ToolCallLine({ message, running: _running, slot, on }} > - {chipView.path && {chipView.path.split('/').pop()}} + {chipView.path && {pathBasename(chipView.path)}} {chipView.removed > 0 && {chipView.truncated ? '≥' : ''}-{chipView.removed}} {chipView.removed > 0 && chipView.added > 0 && ' '} diff --git a/website/src/test/pathBasename.test.ts b/website/src/test/pathBasename.test.ts new file mode 100644 index 000000000000..11535a181a48 --- /dev/null +++ b/website/src/test/pathBasename.test.ts @@ -0,0 +1,68 @@ +/** + * `pathBasename` / `stripTrailingSeparators` (utils/pathBasename.ts), issue + * #14581: `\` is a separator only in a Windows-shaped path (drive-rooted or + * backslash UNC); every other path splits on `/` exactly as + * `split('/').pop()` / `replace(/\/+$/, '')` always did. + */ +import { describe, it, expect } from 'vitest' +import { backslashIsSeparator, pathBasename, stripTrailingSeparators } from '../utils/pathBasename' + +describe('pathBasename', () => { + it.each([ + // Windows-shaped: `\` separates. + ['C:\\Users\\u\\report.md', 'report.md'], + ['c:\\report.md', 'report.md'], + ['C:/Users/u/report.md', 'report.md'], + ['C:\\Users\\u/mixed\\final.ts', 'final.ts'], + ['C:/Users\\u/report.md', 'report.md'], + ['\\\\host\\share\\dir\\report.md', 'report.md'], + ['\\\\host/share/report.md', 'report.md'], + ['C:\\repo\\', ''], + // POSIX: `\` is part of the name. + ['/tmp/we\\ird.md', 'we\\ird.md'], + ['src/report\\final.csv', 'report\\final.csv'], + ['back\\slash', 'back\\slash'], + ['/repo/src/a.ts', 'a.ts'], + ['a.ts', 'a.ts'], + ['/repo/', ''], + ['//host/share/a.ts', 'a.ts'], + ['', ''], + ])('%s -> %s', (input, expected) => { + expect(pathBasename(input)).toBe(expected) + }) + + it.each([ + '/repo/src/a.ts', '/tmp/we\\ird.md', 'src/x\\y', 'plain', '/a/b/', '', '/', + '//host/share/a.ts', 'C:not-rooted\\x', 'C:', '\\single\\lead', + ])('a non-Windows-shaped path splits exactly like split("/").pop(): %s', (p) => { + expect(pathBasename(p)).toBe(p.split('/').pop()) + }) +}) + +describe('stripTrailingSeparators', () => { + it.each([ + ['C:\\repo\\', 'C:\\repo'], + ['C:\\repo\\/\\', 'C:\\repo'], + ['C:/repo/', 'C:/repo'], + ['C:\\', 'C:'], + ['\\\\host\\share\\', '\\\\host\\share'], + ['/repo/', '/repo'], + ['/', ''], + ['/tmp/name\\', '/tmp/name\\'], + ])('%s -> %s', (input, expected) => { + expect(stripTrailingSeparators(input)).toBe(expected) + }) + + it.each(['/a/b//', '/tmp/x\\', 'rel/dir/', '', '//'])('a non-Windows-shaped path strips exactly like replace(/\\/+$/, ""): %s', (p) => { + expect(stripTrailingSeparators(p)).toBe(p.replace(/\/+$/, '')) + }) +}) + +describe('backslashIsSeparator', () => { + it.each([ + ['C:\\x', true], ['z:/x', true], ['\\\\host\\x', true], ['\\\\host/x', true], + ['/x\\y', false], ['x\\y', false], ['C:x\\y', false], ['\\\\', false], ['CD:\\x', false], + ])('%s -> %s', (p, expected) => { + expect(backslashIsSeparator(p)).toBe(expected) + }) +}) diff --git a/website/src/test/windowsBasenameSites.test.tsx b/website/src/test/windowsBasenameSites.test.tsx new file mode 100644 index 000000000000..07c81b9f0869 --- /dev/null +++ b/website/src/test/windowsBasenameSites.test.tsx @@ -0,0 +1,142 @@ +/** + * Issue #14581: every dashboard site that shows a gateway path's file name + * derives it through `pathBasename` (utils/pathBasename.ts), so a Windows + * gateway's `C:\…` path shows `report.md`, not the whole path, while a POSIX + * path splits exactly as before. + * + * The behaviour cases mount the cheap sites through their real code; the + * source scan pins the rest (MarkdownPanel, ToolCallLine, FilesHomePanel, + * FolderPanel, DiffBlock) against the POSIX-only shapes coming back, since + * each of those needs a full panel harness for a one-line derivation. + */ +import { describe, it, expect, beforeEach } from 'vitest' +import { render, renderHook, act } from '@testing-library/react' +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' + +import FoldableDiffBlock, { resetExpandedDiffFences } from '../components/FoldableDiffBlock' +import { FilePreviewStrip } from '../components/chat-input/FilePreviewStrip' +import { ImageViewer } from '../components/FileRenderers' +import { usePanelTabs, __resetPanelTabs } from '../hooks/usePanelTabs' +import { basename as explorerBasename, crumbLabel, parentChain } from '../apps/file-explorer/utils' +import { WINDOWS_SHAPED_PATH_RE } from '../utils/pathBasename' +import { isWindowsShapedPath, normalizeWindowsPath } from '../utils/fileTokens' + +const WIN = 'C:\\Users\\u\\docs\\report.md' +const UNC = '\\\\host\\share\\docs\\report.md' +const POSIX_BACKSLASH = '/tmp/we\\ird.md' + +describe('Windows gateway paths show their file name (#14581)', () => { + beforeEach(() => { resetExpandedDiffFences(); __resetPanelTabs() }) + + it.each([ + [WIN, 'report.md'], + [UNC, 'report.md'], + ['C:/Users/u/report.md', 'report.md'], + [POSIX_BACKSLASH, 'we\\ird.md'], + ['/repo/src/report.md', 'report.md'], + ])('FoldableDiffBlock chip names %s as %s', (pathHint, name) => { + const { container } = render() + const chip = container.querySelector('[data-testid="prose-diff-chip"]')! + expect(chip.querySelector('.font-mono')?.textContent).toBe(name) + }) + + it.each([ + [WIN, 'report.md'], + [POSIX_BACKSLASH, 'we\\ird.md'], + ])('FilePreviewStrip file chip names %s as %s', (path, name) => { + const { getByRole } = render() + expect(getByRole('group', { name: path }).querySelector('span')?.textContent).toBe(name) + }) + + it('FilePreviewStrip image preview label uses the file name of a Windows path', () => { + const { container } = render() + const btn = container.querySelector('button[aria-label]')! + expect(btn.getAttribute('aria-label')).toContain('shot.png') + expect(btn.getAttribute('aria-label')).not.toContain('C:\\') + }) + + it.each([ + ['C:\\Users\\u\\shot.png', 'shot.png'], + ['/tmp/we\\ird.png', 'we\\ird.png'], + ])('ImageViewer alt for %s is %s', (filePath, alt) => { + const { container } = render() + expect(container.querySelector('img')?.getAttribute('alt')).toBe(alt) + }) + + it.each([ + [WIN, 'report.md'], + ['C:\\Users\\u\\docs\\', 'docs'], + [POSIX_BACKSLASH, 'we\\ird.md'], + ['/a/b/', 'b'], + ])('usePanelTabs titles a tab for %s as %s', (path, title) => { + const { result } = renderHook(() => usePanelTabs(null, [])) + act(() => result.current.openFolder(path, 'slot-a')) + expect(result.current.tabs.at(-1)?.title).toBe(title) + }) + + it.each([ + [WIN, 'report.md'], + ['C:\\Users\\u\\docs\\', 'docs'], + [POSIX_BACKSLASH, 'we\\ird.md'], + ['/a/b/', 'b'], + ['/', ''], + ])('file-explorer basename(%s) is %s', (p, name) => { + expect(explorerBasename(p)).toBe(name) + }) + + // The sites listed on #14581 that are not mounted above. Each derived its + // name with a `/`-only split; the shared helper is the one place that knows + // when `\` separates. (composerDrop.ts, the Mochi drop site, is PR #10952's.) + it.each([ + 'components/MarkdownPanel.tsx', + 'components/FileRenderers.tsx', + 'components/chat-input/FilePreviewStrip.tsx', + 'pages/chat/ToolCallLine.tsx', + 'components/FoldableDiffBlock.tsx', + 'components/DiffBlock.tsx', + 'pages/chat/FilesHomePanel.tsx', + 'pages/chat/FolderPanel.tsx', + 'hooks/usePanelTabs.ts', + 'apps/file-explorer/utils.ts', + ])('%s derives file names through pathBasename only', (rel) => { + const src = readFileSync(resolve(__dirname, '..', rel), 'utf8') + expect(src).toMatch(/import \{[^}]*\bpathBasename\b[^}]*\} from '[./]+\/utils\/pathBasename'/) + expect(src).not.toMatch(/\.split\('\/'\)\.pop\(\)/) + expect(src).not.toMatch(/\.lastIndexOf\('\/'\) \+ 1\)/) + }) +}) + +// Breadcrumb navigation is out of scope: these pin main's behaviour so the +// separator-aware basename cannot collapse a Windows root crumb to `repo`. +describe('file-explorer breadcrumbs are unchanged by #14581', () => { + it.each([ + ['C:\\Users\\u\\repo', ['/', 'C:\\Users\\u\\repo']], + ['/a/b/c', ['/', '/a', '/a/b', '/a/b/c']], + ['/tmp/we\\ird', ['/', '/tmp', '/tmp/we\\ird']], + ])('parentChain(%s)', (p, chain) => { + expect(parentChain(p)).toEqual(chain) + }) + + it.each([ + ['C:\\Users\\u\\repo', 'C:\\Users\\u\\repo'], + ['C:/Users', 'Users'], + ['/a/b/', 'b'], + ['/tmp/we\\ird', 'we\\ird'], + ])('crumbLabel(%s) is %s', (p, label) => { + expect(crumbLabel(p)).toBe(label) + }) + + it('PathBar labels crumbs with crumbLabel, not the separator-aware basename', () => { + const src = readFileSync(resolve(__dirname, '../apps/file-explorer/PathBar.tsx'), 'utf8') + expect(src).toContain('crumbLabel(s)') + expect(src).not.toMatch(/\bbasename\(s\)/) + }) + + it('fileTokens uses the one Windows-shape regex', () => { + expect(normalizeWindowsPath('C:\\a\\b')).toBe('C:/a/b') + expect(isWindowsShapedPath('\\\\host\\s')).toBe(WINDOWS_SHAPED_PATH_RE.test('\\\\host\\s')) + const src = readFileSync(resolve(__dirname, '../utils/fileTokens.ts'), 'utf8') + expect(src).not.toContain('/^(?:[A-Za-z]:|') + }) +}) diff --git a/website/src/utils/fileTokens.ts b/website/src/utils/fileTokens.ts index 08a786b081d8..aa7e327419e8 100644 --- a/website/src/utils/fileTokens.ts +++ b/website/src/utils/fileTokens.ts @@ -1,6 +1,7 @@ /** Shared file-token utilities used by send() and renderUserContent(). */ import { decodeLocalPath } from './urlTransform' +import { WINDOWS_SHAPED_PATH_RE } from './pathBasename' export const IMG_EXT = /\.(png|jpe?g|gif|webp|bmp|svg)$/i @@ -421,7 +422,7 @@ export interface SendPayload { * host-naming UNC shape. A UNC upload is emitted as `//host/share/…`, which * reaches the renderer as a scheme-less relative URL and is validated against * the gateway's trusted attachment roots server-side. */ -const WIN_PRODUCER_PATH_RE = /^(?:[A-Za-z]:|\\\\[^\\/]+)[\\/]/ +const WIN_PRODUCER_PATH_RE = WINDOWS_SHAPED_PATH_RE /** Forward-slash form of a Windows-shaped absolute path (drive letter / UNC). * A path that is not Windows-shaped is returned untouched: on POSIX `\` is a diff --git a/website/src/utils/pathBasename.ts b/website/src/utils/pathBasename.ts new file mode 100644 index 000000000000..dde7f3999257 --- /dev/null +++ b/website/src/utils/pathBasename.ts @@ -0,0 +1,38 @@ +/** Separator-aware file-name helpers for gateway paths shown in the UI. + * + * A Windows gateway reports native paths (`C:\repo\src\a.ts`, + * `\\host\share\a.ts`), so splitting on `/` alone shows the whole path where a + * file name belongs. Splitting on `\` everywhere is wrong too: on POSIX a + * backslash is a legal file-name character, so `/tmp/we\ird.md` is ONE name. + * The rule here is the one `breadcrumbSegments` (MarkdownPanel.tsx) uses: `\` + * is a separator only when the path itself is Windows-shaped -- drive-rooted + * (`C:\`, `C:/`) or a backslash UNC path (`\\host\`). + * + * This module is display-only: it decides which characters to SHOW, never + * which paths may be read. The security-relevant predicate stays + * `WINDOWS_ABS_PATH_RE` in urlTransform.ts, which deliberately excludes UNC. + * The regex below is the one definition of that shape: fileTokens.ts imports + * it for `normalizeWindowsPath` rather than keeping its own copy. */ + +/** Drive-rooted (`C:\…`, `C:/…`) or backslash-UNC (`\\host\…`) path. */ +export const WINDOWS_SHAPED_PATH_RE = /^(?:[A-Za-z]:|\\\\[^\\/]+)[\\/]/ + +/** Whether `\` separates segments in `p` (see the module comment). */ +export function backslashIsSeparator(p: string): boolean { + return WINDOWS_SHAPED_PATH_RE.test(p) +} + +/** The text after the last separator of `p`; `''` when `p` ends with one. + * For a POSIX path this is exactly `p.split('/').pop()`. */ +export function pathBasename(p: string): string { + const cut = backslashIsSeparator(p) + ? Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')) + : p.lastIndexOf('/') + return p.slice(cut + 1) +} + +/** `p` without its trailing separators. For a POSIX path this is exactly + * `p.replace(/\/+$/, '')`; a Windows-shaped path also drops trailing `\`. */ +export function stripTrailingSeparators(p: string): string { + return p.replace(backslashIsSeparator(p) ? /[\\/]+$/ : /\/+$/, '') +}