Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions website/docs/frontend-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions website/src/apps/file-explorer/PathBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -121,7 +121,7 @@ export default function PathBar({ rootPath, gitInfo, onChangeRoot, onNavigate }:
<span key={`seg${i}`}>
{i > 0 && <span className="mc-fe-bc-sep">/</span>}
<span className="mc-fe-bc" onClick={(e) => { 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}
</span>
</span>
))}
Expand Down
13 changes: 8 additions & 5 deletions website/src/apps/file-explorer/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('\\'))
Expand All @@ -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(/\/+$/, '')
Expand All @@ -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(/\/+$/, '')
Expand Down
3 changes: 2 additions & 1 deletion website/src/components/DiffBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion website/src/components/FileRenderers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand Down Expand Up @@ -78,7 +79,7 @@ export const ImageViewer = memo(function ImageViewer({ filePath }: { filePath: s
<div className="flex items-center justify-center h-full overflow-auto p-4 bg-bg-elevated rounded-md border border-border">
<img
src={'/api/file-raw?path=' + encodeURIComponent(filePath)}
alt={filePath.split('/').pop()}
alt={pathBasename(filePath)}
className="max-w-full max-h-full object-contain"
draggable={false}
/>
Expand Down
3 changes: 2 additions & 1 deletion website/src/components/FoldableDiffBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
9 changes: 5 additions & 4 deletions website/src/components/MarkdownPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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' },
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -1294,7 +1295,7 @@ export default memo(forwardRef<MarkdownPanelHandle, Props>(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).
Expand Down
5 changes: 3 additions & 2 deletions website/src/components/chat-input/FilePreviewStrip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -89,7 +90,7 @@ export function FilePreviewStrip({ files, dirs = NO_DIRS, resizedInfo, onRemove,
<span className="absolute -top-1.5 -left-1.5 w-5 h-5 rounded-full bg-accent text-accent-fg text-[10px] font-bold flex items-center justify-center z-10">{i + 1}</span>
<button
type="button"
aria-label={i18nT('components.chatInput.open_preview_of', { name: path.split('/').pop() })}
aria-label={i18nT('components.chatInput.open_preview_of', { name: pathBasename(path) })}
className="block cursor-pointer"
onClick={(e) => { const img = e.currentTarget.querySelector('img'); if (img) dispatchLightbox(img) }}
>
Expand Down Expand Up @@ -126,7 +127,7 @@ export function FilePreviewStrip({ files, dirs = NO_DIRS, resizedInfo, onRemove,
})}
{nonImgs.map(path => (
<div key={path} role="group" aria-label={path} title={path} className="relative group/preview shrink-0 flex items-center gap-1.5 px-2 py-1 rounded border border-border bg-bg-hover text-[12px] text-text">
<span>{path.split('/').pop()}</span>
<span>{pathBasename(path)}</span>
{onRemove && (
<button className="text-muted hover:text-danger cursor-pointer bg-transparent border-none p-0" onClick={() => onRemove(path)} title={i18nT('components.chatInput.remove')} aria-label={i18nT('components.chatInput.remove')}><X size={12} /></button>
)}
Expand Down
3 changes: 2 additions & 1 deletion website/src/hooks/usePanelTabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<string, Bucket>
Expand Down
3 changes: 2 additions & 1 deletion website/src/pages/chat/FilesHomePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down
3 changes: 2 additions & 1 deletion website/src/pages/chat/FolderPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down
5 changes: 3 additions & 2 deletions website/src/pages/chat/ToolCallLine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1088,7 +1089,7 @@ export default memo(function ToolCallLine({ message, running: _running, slot, on
}}
>
<FileDiff size={12} className="shrink-0" aria-hidden />
{chipView.path && <span className="font-mono max-w-[240px] truncate">{chipView.path.split('/').pop()}</span>}
{chipView.path && <span className="font-mono max-w-[240px] truncate">{pathBasename(chipView.path)}</span>}
<span className="tabular-nums">
{chipView.removed > 0 && <span className="text-danger">{chipView.truncated ? '≥' : ''}-{chipView.removed}</span>}
{chipView.removed > 0 && chipView.added > 0 && ' '}
Expand Down
68 changes: 68 additions & 0 deletions website/src/test/pathBasename.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading
Loading