fix(client): 含空格的目录 @ 引用补引号,让宿主能识别成 folder(#479)

宿主的两处 token 读取都只认「引号闭合」的目录写法:
`FOLDER_REF_RE`(dsh-client-ui-conversation)的引号分支是 `@"[^"\n]*\/`,
消息气泡的 `@"[^"\n]+"` 也只在闭合时才把 token 判成 folder;而插件目录分支
原先直接拼 `@${rel}/`,含空格目录 `@my dir/` 在补全扫描里完全不命中、在气泡里
退化成只覆盖 `my` 的 file 芯片——文件分支经 fileMention 加引号,目录分支没有,
同一套引号规则被写了两遍,只有一份对。

把「构造 mention 字面量」抽成 conversation-draft.ts 的共用纯函数
`mentionFor(path, kind)`(fileMention 并入,两个调用点:insertFileReference 与
referenceInChat 的目录分支),沿用原有的控制字符/引号拒绝守卫;目录的尾斜杠拼在
引号内侧(`@"my dir/"`)。宿主自己的选择器在补全途中发的是开引号形式
(`@"my dir/`),那是未完成的补全态、气泡里同样判成 file;本插件的动作插入的是
一条完成的引用,所以闭合引号。

行为不变:无空格目录仍是 `@docs/`、cwd 仍是 `@./`、无空格文件仍是 `@notes.md`,
文件分支的引号与 chip 路径逐字未动。宿主 FOLDER_REF_RE 仍能读到 `@"my dir/`
(闭合引号落在 token 之外),文件夹补全不受影响。

验证:pnpm typecheck(exit 0);pnpm exec vitest run --maxWorkers=3(151 files /
1678 passed / 13 skipped);npx eslint 四个改动文件(exit 0)。
tests/reference-in-chat.spec.ts 把目录分支回退到旧写法后 2/7 红(草稿变成
`@my dir/`、守卫路径重新写入不可表示路径)。guide §4.2 的 onReferenceFile 说明
同步引号形式。

Refs #479
This commit is contained in:
Menghuan1918 committed 2026-10-05 01:31:29 +08:00
1 parent 1da9e92f79
commit eed2fee0e6
5 files changed
+217 -23

No files matched your search

+2 -1
View File
@@ -317,7 +317,8 @@ interface TabComponentProps {
// 以下由内置 tab 使用,外部 tab 可忽略:
expanded?: string[] // 文件树的展开目录集
onToggleDir?: (path: string) => void
// 在会话 composer 插入一条 @ 引用。isDir=true 为目录:纯文本 `@dir/`,
// 在会话 composer 插入一条 @ 引用。isDir=true 为目录:纯文本 `@dir/`
// (含空格时按宿主语法加引号成 `@"my dir/"`,否则宿主读不成 folder),
// 保留宿主文件夹装饰与补全;false 为文件:走宿主结构化引用 chip
// (显示 @basename、序列化为完整 @path),宿主拒绝时回退纯文本。
onReferenceFile?: (path: string, isDir: boolean) => void
+21 -6
View File
@@ -195,17 +195,32 @@ export function appendToDraft(ctx: Context, sessionId: string, text: string): bo
}
/**
* The DSH `@file` spelling for one relative path, mirroring the host grammar
* The DSH `@` spelling for one relative path, mirroring the host grammar
* (`formatFileMention` in `@deepseek-ai/dsh-file-reference`): plain when
* there is no whitespace, quoted when there is, and `undefined` when the
* path contains a control character or an embedded quote the editor grammar
* cannot represent.
*
* Files and folders share this one constructor so the quoting rule cannot
* drift between them. A folder spells the trailing slash *inside* the quotes
* (`@"my dir/"`, `@docs/`): the host's folder token matcher
* (`FOLDER_REF_RE` in `dsh-client-ui-conversation`) only accepts a quoted
* directory once the quote closes, and the message bubble's tokenizer
* (`@"[^"\n]+"` in `dsh-client-ui-primitives`) only classifies a closed
* quoted token as a folder — unquoted `@my dir/` decorates as a file chip
* covering just `my`. The host's own picker emits the *open* form
* (`@"my dir/`) while the user is still descending through completion; a
* programmatic reference is a finished mention, so it closes the quote.
*/
export function fileMention(relativePath: string): { mention: string; label: string } | undefined {
export function mentionFor(
relativePath: string,
kind: 'file' | 'folder',
): { mention: string; label: string } | undefined {
const path = relativePath.replace(/[\\/]+$/, '')
// eslint-disable-next-line no-control-regex -- rejecting control characters is the point of this guard
if (/[\u0000-\u001f\u007f-\u009f"]/u.test(path)) return undefined
const mention = /\s/u.test(path) ? `@"${path}"` : `@${path}`
const target = kind === 'folder' ? `${path}/` : path
const mention = /\s/u.test(target) ? `@"${target}"` : `@${target}`
const at = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
const label = at === -1 ? path : path.slice(at + 1)
return { mention, label }
@@ -217,11 +232,11 @@ export function fileMention(relativePath: string): { mention: string; label: str
* 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.
* slash as plain text (`@dir/`, see {@link mentionFor}) so completion can
* descend, which `appendToDraft` already covers.
*/
export function insertFileReference(ctx: Context, sessionId: string, relativePath: string): boolean {
const reference = fileMention(relativePath)
const reference = mentionFor(relativePath, 'file')
if (reference === undefined) return false
try {
const actx = ctx.sessions.scope(sessionId)
+18 -8
View File
@@ -2,18 +2,21 @@
* The explorer's `@`-reference button: insert one file or folder reference
* into the conversation draft of a session.
*
* Directories append the folder mention (`@dir/`) as plain text so DSH's
* folder decoration and completion keep working; files insert a structured
* chip like the native `@` picker, so the whole reference stays one link
* instead of decorating only the leading folder. The session-scope context and
* the conversation input service are resolved at click time; a missing service
* or scope degrades to a logged no-op, never a crash.
* Directories append the folder mention as plain text so DSH's folder
* decoration and completion keep working — spelled through the same
* constructor as file references (`@"my dir/"`, `@docs/`; an unquoted
* `@my dir/` is not a folder token to the host, see `mentionFor`); files
* insert a structured chip like the native `@` picker, so the whole
* reference stays one link instead of decorating only the leading folder.
* The session-scope context and the conversation input service are resolved
* at click time; a missing service or scope degrades to a logged no-op,
* never a crash.
*
* Shared by the plugin's own panel and the native right-Sidebar tab body, so
* both surfaces behave identically.
*/
import type { Context } from '../context-types.ts'
import { appendToDraft, insertFileReference } from './conversation-draft.ts'
import { appendToDraft, insertFileReference, mentionFor } from './conversation-draft.ts'
import { relativeTo } from './paths.ts'
/**
@@ -33,7 +36,14 @@ export function referenceInChat(
): void {
const rel = relativeTo(cwd ?? '', path)
if (isDir) {
appendToDraft(ctx, sessionId, `@${rel === '.' ? './' : `${rel}/`}`)
const folder = mentionFor(rel, 'folder')
if (folder === undefined) {
// Same guard as the file path: a path the editor grammar cannot
// represent is skipped rather than typed into the composer broken.
console.warn('[dsh-better-sidebar] folder reference skipped: unrepresentable path', path)
return
}
appendToDraft(ctx, sessionId, folder.mention)
return
}
if (!insertFileReference(ctx, sessionId, rel)) {
+156
View File
@@ -0,0 +1,156 @@
/**
* reference-in-chat spec — the explorer's `@`-reference button (issue #479).
*
* The draft spelling itself is `mentionFor`'s job (tests/reference-mention.spec.ts);
* what this spec pins is that the folder branch really goes through it and
* produces a token the host's two readers recognise. Both only see a quoted
* folder once the quote *closes*:
*
* - the composer's plain-text trigger scan (`FOLDER_REF_RE`) decorates
* `@dir/` and `@"my dir/"`, but reads nothing at all out of `@my dir/`;
* - the message bubble's tokenizer classifies a closed quoted token as a
* folder (`@"[^"\n]+"` → kind `folder`) while `@my dir/` falls into
* `@[^\s]+` → a *file* chip displaying just `my`.
*
* The two host regexes below are re-stated verbatim from the pinned DSH
* bundles (`@deepseek-ai/dsh-client-ui-conversation/lib/client.js` and
* `@deepseek-ai/dsh-client-ui-primitives/lib/index.js`), so a spelling the
* host cannot read fails here instead of silently mis-rendering.
*
* No composer DOM is mounted: `appendToDraft` then takes its documented
* unknown-caret path (append), which keeps the captured draft exactly the
* inserted token.
*/
import { describe, expect, it, vi } from 'vitest'
import type { Context } from '../src/context-types.ts'
import { referenceInChat } from '../src/client/reference-in-chat.ts'
/** `FOLDER_REF_RE` — the composer's folder token scan. */
const HOST_FOLDER_REF_RE = /(^|\s)(@(?:"[^"\n]*\/|[^\s"]+\/))/g
/** The message bubble's reference tokenizer. */
const HOST_BUBBLE_REF_RE = /(^|\s)(\/[\w-]+(?=\s|$)|@"[^"\n]+"|@[^\s]+)/gu
/** The host folder token inside `text`, or undefined when it reads none. */
function hostFolderToken(text: string): string | undefined {
HOST_FOLDER_REF_RE.lastIndex = 0
return HOST_FOLDER_REF_RE.exec(text)?.[2]
}
/** The message bubble's `referenceKind` for the first token of `text`. */
function hostBubbleKind(text: string): 'folder' | 'file' | undefined {
HOST_BUBBLE_REF_RE.lastIndex = 0
const label = HOST_BUBBLE_REF_RE.exec(text)?.[2]
if (label === undefined || !label.startsWith('@')) return undefined
return label.replace(/^@"|"$/gu, '').endsWith('/') ? 'folder' : 'file'
}
/** One reference the plugin handed to the host as a structured chip. */
interface EmittedReference {
ref: string
label: string
appearance: string
}
/**
* A fake ctx exposing the two composer faces `referenceInChat` uses: the
* plain `setDraft` path (folders and file fallback) and the host's
* `slash/input-insert-reference` event. The fake models the host's chip
* faithfully enough for the draft to be readable — the chip's plain-text
* projection is the mention itself (`ReferenceChipNode.getTextContent()`
* returns the chip's `clipboardText`, which the plugin sets to the mention);
* the separating space the composer adds next to a chip is not part of the
* reference, so it is left out.
*/
function fakeComposer(initial = ''): {
ctx: Context
drafts: string[]
emitted: EmittedReference[]
read: () => string
} {
const drafts: string[] = []
const emitted: EmittedReference[] = []
let text = initial
let draftRev = 0
const input = {
state: { getSnapshot: (): { draft: string; draftRev: number } => ({ draft: text, draftRev }) },
setDraft: (next: string): void => {
text = next
drafts.push(next)
},
}
const scope = {
emit: (name: string, payload: unknown): void => {
if (name !== 'slash/input-insert-reference') return
const { reference } = payload as { reference: EmittedReference }
emitted.push(reference)
text += reference.ref
draftRev += 1
},
}
const ctx = {
sessions: { scope: (): unknown => scope },
get: (name: string): unknown => (name === 'conversation' ? { input: { for: (): unknown => input } } : undefined),
} as unknown as Context
return { ctx, drafts, emitted, read: () => text }
}
describe('referenceInChat folder mentions', () => {
it('quotes a folder whose path contains whitespace so the host reads it as a folder (#479)', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', '/w/my dir', true)
expect(composer.drafts).toEqual(['@"my dir/"'])
const draft = composer.read()
expect(hostFolderToken(draft)).toBe('@"my dir/')
expect(hostBubbleKind(draft)).toBe('folder')
})
it('pins why the quoting is required: the unquoted spelling is read as a file', () => {
// The pre-fix spelling (`@my dir/`) is a folder token to neither reader —
// the bubble tokenizes `@my` as a file chip labelled `my`.
expect(hostFolderToken('@my dir/')).toBeUndefined()
expect(hostBubbleKind('@my dir/')).toBe('file')
expect(hostFolderToken('@"my dir/')).toBe('@"my dir/')
expect(hostBubbleKind('@"my dir/')).toBe('file')
})
it('keeps a folder without whitespace plain', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', '/w/docs', true)
expect(composer.drafts).toEqual(['@docs/'])
expect(hostFolderToken(composer.read())).toBe('@docs/')
expect(hostBubbleKind(composer.read())).toBe('folder')
})
it('keeps the relative-root spelling for the cwd itself', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', '/w', true)
expect(composer.drafts).toEqual(['@./'])
})
it('skips a folder path the mention grammar cannot represent (same guard as files)', () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', '/we"ird dir', true)
expect(composer.drafts).toEqual([])
expect(consoleWarn).toHaveBeenCalledTimes(1)
consoleWarn.mockRestore()
})
})
describe('referenceInChat file mentions (unchanged)', () => {
it('inserts a file with whitespace as one quoted chip reference', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', '/w/my notes.md', false)
expect(composer.emitted.map((reference) => reference.ref)).toEqual(['@"my notes.md"'])
expect(composer.drafts).toEqual([]) // the chip path, not a plain append
expect(composer.read()).toBe('@"my notes.md"')
expect(hostBubbleKind(composer.read())).toBe('file')
})
it('inserts a file without whitespace unchanged', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', '/w/notes.md', false)
expect(composer.emitted.map((reference) => reference.ref)).toEqual(['@notes.md'])
expect(composer.read()).toBe('@notes.md')
})
})
+20 -8
View File
@@ -1,30 +1,42 @@
import { describe, expect, it } from 'vitest'
import { fileMention } from '../src/client/conversation-draft.ts'
import { mentionFor } from '../src/client/conversation-draft.ts'
describe('fileMention', () => {
describe('mentionFor', () => {
it('formats a plain relative file path as an @file mention', () => {
expect(fileMention('src/client/paths.ts')).toEqual({
expect(mentionFor('src/client/paths.ts', 'file')).toEqual({
mention: '@src/client/paths.ts',
label: 'paths.ts',
})
})
it('quotes a path containing whitespace and keeps the full basename', () => {
expect(fileMention('docs/plan files/design notes.md')).toEqual({
expect(mentionFor('docs/plan files/design notes.md', 'file')).toEqual({
mention: '@"docs/plan files/design notes.md"',
label: 'design notes.md',
})
})
it('trims a trailing separator before deriving the basename', () => {
expect(fileMention('src/client/')).toEqual({
expect(mentionFor('src/client/', 'file')).toEqual({
mention: '@src/client',
label: 'client',
})
})
it('rejects embedded quotes and control characters', () => {
expect(fileMention('src/a"b.ts')).toBeUndefined()
expect(fileMention('src/a\u0000b.ts')).toBeUndefined()
it('rejects embedded quotes and control characters for both kinds', () => {
expect(mentionFor('src/a"b.ts', 'file')).toBeUndefined()
expect(mentionFor('src/a\u0000b.ts', 'file')).toBeUndefined()
expect(mentionFor('src/a"b', 'folder')).toBeUndefined()
})
it('keeps the trailing slash on a plain folder mention', () => {
expect(mentionFor('docs', 'folder')).toEqual({ mention: '@docs/', label: 'docs' })
expect(mentionFor('docs/', 'folder')).toEqual({ mention: '@docs/', label: 'docs' })
// The cwd itself stays the relative root spelling the composer expects.
expect(mentionFor('.', 'folder')).toEqual({ mention: '@./', label: '.' })
})
it('closes the quote around the trailing slash of a folder with whitespace', () => {
expect(mentionFor('my dir', 'folder')).toEqual({ mention: '@"my dir/"', label: 'my dir' })
})
})