fix(explorer): align directory mentions with workspace-root grammar
This commit is contained in:
1 parent
6fbfeedc01
commit
cb271e0d5a
7 files changed
+279
-18
No files matched your search
+3
-11
@@ -33,7 +33,7 @@ import { useSyncExternalStore } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { IconCloseFill14, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { Context } from '../context-types.ts'
|
||||
import { appendToDraft, insertFileReference } from './conversation-draft.ts'
|
||||
import { insertWorkspaceReference } from './conversation-draft.ts'
|
||||
import {
|
||||
BOTTOM_MIN, PANEL_MIN, agentUuidOf, firstLeaf, floatTab,
|
||||
isAgentTabId, leafWithTab, migrateBottomTabs,
|
||||
@@ -56,7 +56,6 @@ import { useHostFeeds } from './sidebar/use-host-feeds.ts'
|
||||
import { usePinnedTabs } from './sidebar/use-pinned-tabs.ts'
|
||||
import { FreeWindowLayer, useFloatDragout } from './sidebar/free-windows.tsx'
|
||||
import type { TabDragPayload } from './TabBar.tsx'
|
||||
import { relativeTo } from './paths.ts'
|
||||
import { t } from './locales.ts'
|
||||
import { api } from './api.ts'
|
||||
import css from './sidebar.module.css'
|
||||
@@ -752,15 +751,8 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
|
||||
*/
|
||||
const referenceInChat = useCallback((path: string, isDir: boolean): void => {
|
||||
if (sessionId === undefined) return
|
||||
const rel = relativeTo(cwd ?? '', path)
|
||||
if (isDir) {
|
||||
appendToDraft(ctx, sessionId, `@${rel === '.' ? './' : `${rel}/`}`)
|
||||
return
|
||||
}
|
||||
if (!insertFileReference(ctx, sessionId, rel)) {
|
||||
appendToDraft(ctx, sessionId, `@${rel}`)
|
||||
}
|
||||
}, [ctx, sessionId, cwd])
|
||||
insertWorkspaceReference(ctx, sessionId, path, isDir)
|
||||
}, [ctx, sessionId])
|
||||
|
||||
if (state === undefined || sessionId === undefined) {
|
||||
// Keep the unavailable controls focusable: touch users have no hover, so
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
* position (A|B + C + D → ACD|B).
|
||||
*/
|
||||
import type { Context, SidebarConversation } from '../context-types.ts'
|
||||
import { workspaceRelativePath } from './paths.ts'
|
||||
|
||||
/** A resolved composer caret/selection in draft coordinates. */
|
||||
export interface DraftCaret {
|
||||
@@ -211,14 +212,54 @@ export function fileMention(relativePath: string): { mention: string; label: str
|
||||
return { mention, label }
|
||||
}
|
||||
|
||||
/** A complete directory token: normalize separators and put '/' inside quotes. */
|
||||
export function directoryMention(relativePath: string): string | undefined {
|
||||
const reference = fileMention(relativePath.replace(/\\/g, '/'))
|
||||
if (reference === undefined) return undefined
|
||||
return reference.mention.endsWith('"')
|
||||
? `${reference.mention.slice(0, -1)}/"`
|
||||
: `${reference.mention}/`
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an explorer entry using WorkspaceView.path, selected by exact
|
||||
* session membership (the same lookup as the native conversation shell).
|
||||
* Read the public workspace snapshot at click time so reconnects and session
|
||||
* changes cannot leave a captured root stale. Missing/unready membership or
|
||||
* an unrepresentable path is a logged no-op; never guess from session cwd.
|
||||
*/
|
||||
export function insertWorkspaceReference(ctx: Context, sessionId: string, path: string, isDir: boolean): boolean {
|
||||
try {
|
||||
const snapshot = ctx.get('workspaces')?.list.getSnapshot()
|
||||
const root = snapshot?.phase === 'ready' && snapshot.state === 'idle'
|
||||
? snapshot.items.find(workspace => workspace.sessionIds.includes(sessionId))?.path
|
||||
: undefined
|
||||
const relative = workspaceRelativePath(root, path)
|
||||
if (relative === undefined) {
|
||||
console.warn('[dsh-better-sidebar] reference insert skipped: workspace root unavailable or path outside workspace')
|
||||
return false
|
||||
}
|
||||
const mention = isDir ? directoryMention(relative) : fileMention(relative)?.mention
|
||||
if (mention === undefined) {
|
||||
console.warn('[dsh-better-sidebar] reference insert skipped: path cannot be represented as a mention')
|
||||
return false
|
||||
}
|
||||
if (!isDir && insertFileReference(ctx, sessionId, relative)) return true
|
||||
return appendToDraft(ctx, sessionId, mention)
|
||||
} catch (error) {
|
||||
console.warn('[dsh-better-sidebar] workspace-reference insert failed:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert one FILE reference as a structured chip (like DSH's own `@` picker).
|
||||
* The chip displays `@<basename>` but serializes to `@<relative path>` on
|
||||
* send, so the reference stays a single link from trigger to basename.
|
||||
*
|
||||
* Directories are NOT handled here: DSH's folder grammar wants the trailing
|
||||
* slash as plain text (`@dir/`) so completion can descend, which
|
||||
* `appendToDraft` already covers.
|
||||
* Directories keep the sidebar's plain-text completion behavior (`@dir/`)
|
||||
* through `insertWorkspaceReference`. The rc.1 picker also supports folder
|
||||
* chips on explicit selection; its drill action still inserts plain text.
|
||||
*/
|
||||
export function insertFileReference(ctx: Context, sessionId: string, relativePath: string): boolean {
|
||||
const reference = fileMention(relativePath)
|
||||
|
||||
+23
-2
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Path projection helpers shared by the explorer rows: a path relative to
|
||||
* the session cwd (for the @-reference button and "copy relative path").
|
||||
* Path projection helpers shared by the explorer rows: workspace-relative
|
||||
* mentions and session-cwd-relative "copy relative path".
|
||||
* The fs-tree joins with '/' even on Windows, so both separators normalize
|
||||
* to '/' before comparison.
|
||||
*
|
||||
@@ -46,6 +46,27 @@ export function relativeTo(cwd: string, path: string): string {
|
||||
return path
|
||||
}
|
||||
|
||||
/**
|
||||
* Project an absolute explorer entry against the host-confirmed workspace
|
||||
* root. Unlike copy-relative-path's `relativeTo`, mention insertion must
|
||||
* never fall back to an absolute token. Unknown roots, traversal components
|
||||
* and paths outside the workspace are refused. Windows drive/UNC paths are
|
||||
* case-insensitive; POSIX paths retain their case-sensitive distinction.
|
||||
*/
|
||||
export function workspaceRelativePath(root: string | undefined, path: string): string | undefined {
|
||||
if (root === undefined || !isAbsolutePath(root) || !isAbsolutePath(path)) return undefined
|
||||
const norm = (value: string): string => value.replace(/\\/g, '/').replace(/\/+$/, '')
|
||||
const base = norm(root)
|
||||
const target = norm(path)
|
||||
if ([base, target].some(value => value.split('/').some(part => part === '.' || part === '..'))) return undefined
|
||||
const windows = /^[A-Za-z]:\//.test(root.replace(/\\/g, '/')) || /^[\\/]{2}/.test(root)
|
||||
const compare = (value: string): string => windows ? value.toLowerCase() : value
|
||||
if (compare(target) === compare(base)) return '.'
|
||||
if (!compare(target).startsWith(`${compare(base)}/`)) return undefined
|
||||
const relative = target.slice(base.length + 1)
|
||||
return relative === '' || isAbsolutePath(relative) ? undefined : relative
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `target` lies under `base` (or equals it), tolerant of separator
|
||||
* style and — on Windows-style drive paths — of letter case. A client-side
|
||||
|
||||
@@ -408,6 +408,21 @@ export interface SidebarConversation {
|
||||
}
|
||||
}
|
||||
|
||||
/** Read-only subset of api-workspace-controller's public IWorkspaces.list. */
|
||||
export interface SidebarWorkspacesService {
|
||||
readonly list: {
|
||||
getSnapshot(): {
|
||||
readonly phase: 'pending' | 'ready'
|
||||
readonly state: 'idle' | 'loading' | 'error'
|
||||
readonly items: readonly {
|
||||
/** Canonical host directory, from WorkspaceView.path. */
|
||||
readonly path: string
|
||||
readonly sessionIds: readonly string[]
|
||||
}[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The client `remote.session` namespace face (mirror of the gateway client's
|
||||
* RemoteNamespaceService for the session-controller contribution on alpha
|
||||
@@ -551,6 +566,8 @@ export interface SidebarContextShape {
|
||||
}
|
||||
/** The composer draft face (client ui-conversation, lazy `ctx.get` probe). */
|
||||
conversation: SidebarConversation
|
||||
/** Host-authoritative workspace membership; resolved lazily at reference insertion. */
|
||||
workspaces?: SidebarWorkspacesService
|
||||
/**
|
||||
* The client-side sidebar registry: external plugins register tab types
|
||||
* and file previewers here. Provided by the client half (see
|
||||
|
||||
+31
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isAbsolutePath, relativeTo } from '../src/client/paths.ts'
|
||||
import { isAbsolutePath, relativeTo, workspaceRelativePath } from '../src/client/paths.ts'
|
||||
import { resolveSidebarPath } from '../src/client/produced-files.ts'
|
||||
import { htmlUrl } from '../src/client/api.ts'
|
||||
|
||||
@@ -67,3 +67,33 @@ describe('path helpers', () => {
|
||||
.toBe('/sidebar/html/s/home/me/index.html')
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspaceRelativePath', () => {
|
||||
it.each([
|
||||
['/work', '/work/src/a.ts', 'src/a.ts'],
|
||||
['/work/', '/work', '.'],
|
||||
['/', '/src/a.ts', 'src/a.ts'],
|
||||
['/', '/', '.'],
|
||||
['C:\\Work', 'c:/work/SRC/a.ts', 'SRC/a.ts'],
|
||||
['C:\\Work\\', 'c:/WORK', '.'],
|
||||
['C:\\', 'c:/SRC/a.ts', 'SRC/a.ts'],
|
||||
['C:\\Work', 'c:/work/my dir\\a.ts', 'my dir/a.ts'],
|
||||
['\\\\server\\share\\Work', '//SERVER/share/work/src/a.ts', 'src/a.ts'],
|
||||
])('projects %s / %s', (root, path, expected) => {
|
||||
expect(workspaceRelativePath(root, path)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[undefined, '/work/a.ts'],
|
||||
['', '/work/a.ts'],
|
||||
['work', '/work/a.ts'],
|
||||
['/work', '/outside/a.ts'],
|
||||
['/work', '/work-other/a.ts'],
|
||||
['/work', '/WORK/a.ts'],
|
||||
['/work', '/work/../outside/a.ts'],
|
||||
['/work', 'src/a.ts'],
|
||||
['C:/Work', 'D:/Work/a.ts'],
|
||||
])('refuses an unavailable root or unsafe projection %j / %s', (root, path) => {
|
||||
expect(workspaceRelativePath(root, path)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { fileMention } from '../src/client/conversation-draft.ts'
|
||||
import { directoryMention, fileMention } from '../src/client/conversation-draft.ts'
|
||||
|
||||
describe('fileMention', () => {
|
||||
it('formats a plain relative file path as an @file mention', () => {
|
||||
@@ -28,3 +28,21 @@ describe('fileMention', () => {
|
||||
expect(fileMention('src/a\u0000b.ts')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('directoryMention', () => {
|
||||
it.each([
|
||||
['src', '@src/'],
|
||||
['my dir', '@"my dir/"'],
|
||||
['docs/my dir/notes here', '@"docs/my dir/notes here/"'],
|
||||
['src/', '@src/'],
|
||||
['.', '@./'],
|
||||
['src\\my dir\\', '@"src/my dir/"'],
|
||||
['src\\my dir/nested', '@"src/my dir/nested/"'],
|
||||
])('formats %s as a complete plain-text directory token', (path, mention) => {
|
||||
expect(directoryMention(path)).toBe(mention)
|
||||
})
|
||||
|
||||
it.each(['a"b', 'a\n b', 'a\t b', 'a\u0000b', 'a\u007fb', 'a\u0085b'])('rejects an unrepresentable directory %j', path => {
|
||||
expect(directoryMention(path)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { Sidebar } from '../src/client/Sidebar.tsx'
|
||||
import { createSidebarStore } from '../src/client/state.ts'
|
||||
import { createBetterSidebarService } from '../src/client/service.ts'
|
||||
import { setupReactAct } from './test-utils.ts'
|
||||
|
||||
setupReactAct()
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
function mount(cwd: string, options: { root?: string; phase?: 'pending' | 'ready'; state?: 'idle' | 'loading' | 'error'; chip?: boolean; workspaceService?: boolean } = {}) {
|
||||
vi.stubGlobal('WebSocket', class { close() {} })
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const store = createSidebarStore()
|
||||
store.setSession('s1')
|
||||
const service = createBetterSidebarService(store)
|
||||
const sessions = { current: 's1', byId: { s1: { id: 's1', cwd } } }
|
||||
const locale = { active: 'en' }
|
||||
let draft = 'before'
|
||||
let draftRev = 1
|
||||
const setDraft = vi.fn((text: string) => { draft = text; draftRev++ })
|
||||
const emit = vi.fn((_event: string, _payload: unknown) => {
|
||||
if (options.chip) draftRev++
|
||||
})
|
||||
const input = { state: { getSnapshot: () => ({ draft, draftRev }) }, setDraft }
|
||||
const workspaces = { list: { getSnapshot: () => ({
|
||||
phase: options.phase ?? 'ready',
|
||||
state: options.state ?? 'idle',
|
||||
items: [
|
||||
{ path: '/decoy', sessionIds: ['other'] },
|
||||
...(options.root === undefined ? [] : [{ path: options.root, sessionIds: ['s1'] }]),
|
||||
],
|
||||
}) } }
|
||||
const ctx = {
|
||||
locale: { subscribe: () => () => {}, getSnapshot: () => locale },
|
||||
sessions: {
|
||||
list: { subscribe: () => () => {}, getSnapshot: () => sessions },
|
||||
scope: () => ({ emit }),
|
||||
},
|
||||
get: (name: string) => ({
|
||||
betterSidebar: service,
|
||||
conversation: { input: { for: () => input } },
|
||||
workspaces: options.workspaceService === false ? undefined : workspaces,
|
||||
})[name],
|
||||
}
|
||||
let reference: ((path: string, isDir: boolean) => void) | undefined
|
||||
service.registerTab({ id: 'reference-test', title: 'Reference', component: props => {
|
||||
reference = props.onReferenceFile
|
||||
return null
|
||||
} })
|
||||
service.openTab({ type: 'reference-test', title: 'Reference' })
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root = createRoot(container)
|
||||
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
|
||||
expect(reference).toBeTypeOf('function')
|
||||
return {
|
||||
insert: (path: string, isDir: boolean) => { act(() => { reference!(path, isDir) }) },
|
||||
draft: () => draft, emit, setDraft, warn,
|
||||
unmount: () => { act(() => { root.unmount() }); container.remove() },
|
||||
}
|
||||
}
|
||||
|
||||
describe('Sidebar workspace references', () => {
|
||||
it.each(['/work', '/work/src'])('uses workspace membership with session cwd %s', cwd => {
|
||||
const view = mount(cwd, { root: '/work' })
|
||||
try {
|
||||
view.insert('/work/my dir', true)
|
||||
expect(view.draft()).toBe('before @"my dir/"')
|
||||
expect(view.emit).not.toHaveBeenCalled()
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('uses workspace-relative file chips outside the session cwd', () => {
|
||||
const view = mount('/work/src', { root: '/work', chip: true })
|
||||
try {
|
||||
view.insert('/work/docs/my notes.md', false)
|
||||
expect(view.emit).toHaveBeenCalledWith('slash/input-insert-reference', {
|
||||
reference: { source: 'reference', ref: '@"docs/my notes.md"', label: 'my notes.md', appearance: 'file', clipboardText: '@"docs/my notes.md"' },
|
||||
span: { draftRev: 1, start: 6, end: 6 },
|
||||
})
|
||||
expect(view.setDraft).not.toHaveBeenCalled()
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('keeps quoted file text when the chip event is not handled', () => {
|
||||
const view = mount('/work', { root: '/work' })
|
||||
try {
|
||||
view.insert('/work/my notes.md', false)
|
||||
expect(view.draft()).toBe('before @"my notes.md"')
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('normalizes Windows drive casing and mixed separators', () => {
|
||||
const view = mount('C:\\Work\\src', { root: 'C:\\Work\\' })
|
||||
try {
|
||||
view.insert('c:/WORK/my dir\\nested', true)
|
||||
expect(view.draft()).toBe('before @"my dir/nested/"')
|
||||
view.insert('c:/work', true)
|
||||
expect(view.draft()).toBe('before @"my dir/nested/" @./')
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ root: undefined },
|
||||
{ root: '/work', workspaceService: false },
|
||||
{ root: '/work', phase: 'pending' as const },
|
||||
{ root: '/work', state: 'loading' as const },
|
||||
{ root: '/work', state: 'error' as const },
|
||||
])('leaves the draft intact and logs when workspace data is unavailable: %j', options => {
|
||||
const view = mount('/work/src', options)
|
||||
try {
|
||||
view.insert('/work/src/a.ts', false)
|
||||
expect(view.draft()).toBe('before')
|
||||
expect(view.emit).not.toHaveBeenCalled()
|
||||
expect(view.warn).toHaveBeenCalled()
|
||||
// Resolve the host snapshot later: the next click must see fresh data.
|
||||
Object.assign(options, { root: '/work', phase: 'ready', state: 'idle', workspaceService: true })
|
||||
view.insert('/work/src', true)
|
||||
expect(view.draft()).toBe('before @src/')
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it.each(['/outside/file.ts', '/work/a"b', '/work/a\nb'])('never inserts an unsafe path %j as a file or directory', path => {
|
||||
const view = mount('/work', { root: '/work' })
|
||||
try {
|
||||
view.insert(path, false)
|
||||
view.insert(path, true)
|
||||
expect(view.draft()).toBe('before')
|
||||
expect(view.emit).not.toHaveBeenCalled()
|
||||
expect(view.warn).toHaveBeenCalled()
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user