Merge pull request #574 from bulingbuling688/fix/explorer-workspace-mentions
fix(explorer): align directory mentions with workspace-root grammar
This commit is contained in:
12 files changed
+363
-54
No files matched your search
@@ -322,6 +322,12 @@ interface TabComponentProps {
|
||||
// (含空格时按宿主语法加引号成 `@"my dir/"`,否则宿主读不成 folder),
|
||||
// 保留宿主文件夹装饰与补全;false 为文件:走宿主结构化引用 chip
|
||||
// (显示 @basename、序列化为完整 @path),宿主拒绝时回退纯文本。
|
||||
// path 按宿主确认的 workspace root(客户端 `ctx.get('workspaces')` 的
|
||||
// `WorkspaceView.path`,按会话成员匹配)投影,不是会话 cwd:@ 语法以
|
||||
// workspace root 为基准。工作区数据不可用(服务缺失 / 快照未就绪 /
|
||||
// 会话不属于任何工作区)或路径在 workspace 之外时不写入草稿,只留一行
|
||||
// warn——绝不产出猜测的相对路径或绝对路径。目录插入会带一个尾随分隔空格,
|
||||
// 使连续两次点击不会粘成一条 token。
|
||||
onReferenceFile?: (path: string, isDir: boolean) => void
|
||||
onOpenFile?: (path: string) => void
|
||||
onOpenDiff?: (tab: SidebarTab) => void
|
||||
|
||||
+11
-11
@@ -531,20 +531,20 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
|
||||
}), [store, sessionId, cwd, ctx])
|
||||
|
||||
/**
|
||||
* The explorer's @-reference button. 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. Resolves the session-scope ctx and the conversation
|
||||
* input service at click time; a missing service or scope degrades to a
|
||||
* logged no-op, never a crash. Defined above the no-session early return
|
||||
* — a hook must never sit behind a conditional return (React counts hooks
|
||||
* per render).
|
||||
* The explorer's @-reference button. The token is spelled against the
|
||||
* host-confirmed workspace root (see `referenceInChat`), directories as a
|
||||
* complete plain-text folder mention so DSH's folder decoration and
|
||||
* completion keep working, files as a structured chip like the native `@`
|
||||
* picker. Resolves the session-scope ctx, the conversation input service
|
||||
* and the workspace snapshot at click time; a missing service or an
|
||||
* unresolved workspace degrades to a logged no-op, never a crash. Defined
|
||||
* above the no-session early return — a hook must never sit behind a
|
||||
* conditional return (React counts hooks per render).
|
||||
*/
|
||||
const referenceInChat = useCallback((path: string, isDir: boolean): void => {
|
||||
if (sessionId === undefined) return
|
||||
referenceInChatShared(ctx, sessionId, cwd, path, isDir)
|
||||
}, [ctx, sessionId, cwd])
|
||||
referenceInChatShared(ctx, sessionId, path, isDir)
|
||||
}, [ctx, sessionId])
|
||||
|
||||
if (state === undefined || sessionId === undefined) {
|
||||
// No conversation yet: the host stays mounted (the drag shield keeps
|
||||
|
||||
@@ -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 {
|
||||
@@ -58,7 +59,7 @@ interface SpliceResult {
|
||||
*/
|
||||
function spliceInsert(draft: string, text: string, caret: DraftCaret | null): SpliceResult {
|
||||
if (caret === null || draft === '') {
|
||||
const next = draft.trim() === '' ? text : `${draft} ${text}`
|
||||
const next = draft.trim() === '' ? text : `${draft}${/\s$/.test(draft) ? '' : ' '}${text}`
|
||||
return { draft: next, caretAfter: next.length }
|
||||
}
|
||||
const prefix = draft.slice(0, caret.start)
|
||||
@@ -68,7 +69,7 @@ function spliceInsert(draft: string, text: string, caret: DraftCaret | null): Sp
|
||||
// (or the string edges) — mirrors how typing in the middle of a sentence
|
||||
// behaves.
|
||||
const left = prefix === '' || /\s$/.test(prefix) ? '' : ' '
|
||||
const right = suffix === '' || /^\s/.test(suffix) ? '' : ' '
|
||||
const right = suffix === '' || /^\s/.test(suffix) || /\s$/.test(text) ? '' : ' '
|
||||
return {
|
||||
draft: `${prefix}${left}${text}${right}${suffix}`,
|
||||
caretAfter: prefix.length + left.length + text.length,
|
||||
@@ -226,14 +227,58 @@ export function mentionFor(
|
||||
return { mention, label }
|
||||
}
|
||||
|
||||
/**
|
||||
* A complete directory token (`@docs/`, `@"my dir/"`): the explorer inserts a
|
||||
* finished mention, so the trailing slash sits inside the closing quote.
|
||||
* Separators normalize to '/' first (the fs-tree spelling); the spelling
|
||||
* itself is {@link mentionFor}'s single job, folder kind — this helper adds no
|
||||
* quoting rule of its own.
|
||||
*/
|
||||
export function directoryMention(relativePath: string): string | undefined {
|
||||
return mentionFor(relativePath.replace(/\\/g, '/'), 'folder')?.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) : mentionFor(relative, 'file')?.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
|
||||
// The host adds space after a file chip, but not before it. Complete
|
||||
// directory inserts need their own separator for the next @ click.
|
||||
return appendToDraft(ctx, sessionId, isDir ? `${mention} ` : 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/`, see {@link mentionFor}) 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 = mentionFor(relativePath, 'file')
|
||||
|
||||
@@ -437,7 +437,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
|
||||
expanded: view.expanded,
|
||||
revealed: view.revealed,
|
||||
onToggleDir: (path: string) => { records.toggleExpanded(seatSessionId, nativeTab.id, path) },
|
||||
onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, scopeSessionId, cwd, path, isDir) },
|
||||
onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, scopeSessionId, path, isDir) },
|
||||
onOpenDiff: (tab: SidebarTab) => {
|
||||
service.openTab({
|
||||
type: 'diff',
|
||||
|
||||
+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.
|
||||
*
|
||||
@@ -49,6 +49,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
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
* The explorer's `@`-reference button: insert one file or folder reference
|
||||
* into the conversation draft of a session.
|
||||
*
|
||||
* The token is projected against the host-confirmed workspace root — the
|
||||
* session's `WorkspaceView.path`, matched by exact session membership — never
|
||||
* the session cwd: DSH's `@` grammar is workspace-root relative (#479), and a
|
||||
* cwd-relative guess silently names a different file whenever the two differ.
|
||||
* A missing service or membership, an unready snapshot, a path outside the
|
||||
* workspace and an unrepresentable path all degrade to a logged no-op, never
|
||||
* an absolute mention. `insertWorkspaceReference` owns that policy; this
|
||||
* module stays the single entry both surfaces share.
|
||||
*
|
||||
* 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
|
||||
@@ -16,37 +25,20 @@
|
||||
* both surfaces behave identically.
|
||||
*/
|
||||
import type { Context } from '../context-types.ts'
|
||||
import { appendToDraft, insertFileReference, mentionFor } from './conversation-draft.ts'
|
||||
import { relativeTo } from './paths.ts'
|
||||
import { insertWorkspaceReference } from './conversation-draft.ts'
|
||||
|
||||
/**
|
||||
* Reference one path in the session's conversation draft.
|
||||
* @param ctx - the client context.
|
||||
* @param sessionId - the session whose draft receives the reference.
|
||||
* @param cwd - that session's workspace root (for the relative spelling).
|
||||
* @param path - the absolute or workspace-relative path to reference.
|
||||
* @param path - the absolute entry path the explorer row carries.
|
||||
* @param isDir - whether the path is a directory (folder mention vs file chip).
|
||||
*/
|
||||
export function referenceInChat(
|
||||
ctx: Context,
|
||||
sessionId: string,
|
||||
cwd: string | undefined,
|
||||
path: string,
|
||||
isDir: boolean,
|
||||
): void {
|
||||
const rel = relativeTo(cwd ?? '', path)
|
||||
if (isDir) {
|
||||
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)) {
|
||||
appendToDraft(ctx, sessionId, `@${rel}`)
|
||||
}
|
||||
insertWorkspaceReference(ctx, sessionId, path, isDir)
|
||||
}
|
||||
@@ -626,6 +626,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 invariant service face (mirror of @deepseek-ai/dsh-invariants'
|
||||
* InvariantRegistry). The upstream augmentation does not reach this Context
|
||||
@@ -795,6 +810,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
|
||||
|
||||
@@ -92,6 +92,15 @@ describe('insertAtCaret', () => {
|
||||
expect(insertAtCaret(' ', 'X', null)).toBe('X')
|
||||
})
|
||||
|
||||
it('keeps a directory separator when appending another reference', () => {
|
||||
expect(insertAtCaret('@src/ ', '@notes.md', null)).toBe('@src/ @notes.md')
|
||||
expect(insertAtCaret('@src/\n', '@notes.md', null)).toBe('@src/\n@notes.md')
|
||||
})
|
||||
|
||||
it('uses the inserted directory separator before a following word', () => {
|
||||
expect(insertAtCaret('hello world', '@src/ ', { start: 6, end: 6 })).toBe('hello @src/ world')
|
||||
})
|
||||
|
||||
it('inserts at the caret in the middle of a sentence with one space each side', () => {
|
||||
expect(insertAtCaret('hello world', 'CODE', { start: 5, end: 5 })).toBe('hello CODE world')
|
||||
})
|
||||
|
||||
+31
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeHtmlUrl } from '../src/html-route.ts'
|
||||
import { isAbsolutePath, relativeTo } from '../src/client/paths.ts'
|
||||
import { isAbsolutePath, relativeTo, workspaceRelativePath } from '../src/client/paths.ts'
|
||||
import { resolveSidebarPath } from '../src/client/paths.ts'
|
||||
import { downloadUrl, htmlUrl, mediaUrl } from '../src/client/api.ts'
|
||||
|
||||
@@ -107,3 +107,33 @@ describe('preview URL path resolution', () => {
|
||||
expect(new URL(mediaUrl({ sessionId: 's' }, 'pic.png'), 'http://localhost').searchParams.get('path')).toBe('pic.png')
|
||||
})
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -19,7 +19,9 @@
|
||||
*
|
||||
* No composer DOM is mounted: `appendToDraft` then takes its documented
|
||||
* unknown-caret path (append), which keeps the captured draft exactly the
|
||||
* inserted token.
|
||||
* inserted token — plus, for a folder, the separating space a *complete*
|
||||
* directory insert carries (#574) so the next `@` click cannot glue two
|
||||
* tokens together.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
@@ -52,8 +54,10 @@ interface EmittedReference {
|
||||
}
|
||||
|
||||
/**
|
||||
* A fake ctx exposing the two composer faces `referenceInChat` uses: the
|
||||
* plain `setDraft` path (folders and file fallback) and the host's
|
||||
* A fake ctx exposing the three faces `referenceInChat` uses: the host's
|
||||
* `workspaces` snapshot (the token is projected against `WorkspaceView.path`,
|
||||
* matched by session membership — issue #479's base-path gap), 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()`
|
||||
@@ -87,9 +91,18 @@ function fakeComposer(initial = ''): {
|
||||
draftRev += 1
|
||||
},
|
||||
}
|
||||
const workspaces = {
|
||||
list: {
|
||||
getSnapshot: (): unknown => ({ phase: 'ready', state: 'idle', items: [{ path: '/w', sessionIds: ['s1'] }] }),
|
||||
},
|
||||
}
|
||||
const ctx = {
|
||||
sessions: { scope: (): unknown => scope },
|
||||
get: (name: string): unknown => (name === 'conversation' ? { input: { for: (): unknown => input } } : undefined),
|
||||
get: (name: string): unknown => (
|
||||
name === 'conversation'
|
||||
? { input: { for: (): unknown => input } }
|
||||
: name === 'workspaces' ? workspaces : undefined
|
||||
),
|
||||
} as unknown as Context
|
||||
return { ctx, drafts, emitted, read: () => text }
|
||||
}
|
||||
@@ -97,8 +110,9 @@ function fakeComposer(initial = ''): {
|
||||
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/"'])
|
||||
referenceInChat(composer.ctx, 's1', '/w/my dir', true)
|
||||
// The token itself is unchanged by the separator that follows it (#574).
|
||||
expect(composer.drafts).toEqual(['@"my dir/" '])
|
||||
const draft = composer.read()
|
||||
expect(hostFolderToken(draft)).toBe('@"my dir/')
|
||||
expect(hostBubbleKind(draft)).toBe('folder')
|
||||
@@ -115,22 +129,22 @@ describe('referenceInChat folder mentions', () => {
|
||||
|
||||
it('keeps a folder without whitespace plain', () => {
|
||||
const composer = fakeComposer()
|
||||
referenceInChat(composer.ctx, 's1', '/w', '/w/docs', true)
|
||||
expect(composer.drafts).toEqual(['@docs/'])
|
||||
referenceInChat(composer.ctx, 's1', '/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(['@./'])
|
||||
referenceInChat(composer.ctx, 's1', '/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)
|
||||
referenceInChat(composer.ctx, 's1', '/we"ird dir', true)
|
||||
expect(composer.drafts).toEqual([])
|
||||
expect(consoleWarn).toHaveBeenCalledTimes(1)
|
||||
consoleWarn.mockRestore()
|
||||
@@ -140,7 +154,7 @@ describe('referenceInChat folder mentions', () => {
|
||||
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)
|
||||
referenceInChat(composer.ctx, 's1', '/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"')
|
||||
@@ -149,7 +163,7 @@ describe('referenceInChat file mentions (unchanged)', () => {
|
||||
|
||||
it('inserts a file without whitespace unchanged', () => {
|
||||
const composer = fakeComposer()
|
||||
referenceInChat(composer.ctx, 's1', '/w', '/w/notes.md', false)
|
||||
referenceInChat(composer.ctx, 's1', '/w/notes.md', false)
|
||||
expect(composer.emitted.map((reference) => reference.ref)).toEqual(['@notes.md'])
|
||||
expect(composer.read()).toBe('@notes.md')
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mentionFor } from '../src/client/conversation-draft.ts'
|
||||
import { directoryMention, mentionFor } from '../src/client/conversation-draft.ts'
|
||||
|
||||
describe('mentionFor', () => {
|
||||
it('formats a plain relative file path as an @file mention', () => {
|
||||
@@ -40,3 +40,21 @@ describe('mentionFor', () => {
|
||||
expect(mentionFor('my dir', 'folder')).toEqual({ mention: '@"my dir/"', label: 'my dir' })
|
||||
})
|
||||
})
|
||||
|
||||
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,157 @@
|
||||
// @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.each(['src', 'my dir', 'docs/my dir'])('separates a directory %s from the next file chip', directory => {
|
||||
const view = mount('/work', { root: '/work', chip: true })
|
||||
try {
|
||||
view.insert(`/work/${directory}`, true)
|
||||
const beforeFile = view.draft()
|
||||
expect(beforeFile).toMatch(/\s$/)
|
||||
view.insert('/work/notes.md', false)
|
||||
expect(view.emit).toHaveBeenCalledWith('slash/input-insert-reference', {
|
||||
reference: { source: 'reference', ref: '@notes.md', label: 'notes.md', appearance: 'file', clipboardText: '@notes.md' },
|
||||
span: { draftRev: 2, start: beforeFile.length, end: beforeFile.length },
|
||||
})
|
||||
expect(view.setDraft).toHaveBeenCalledTimes(1)
|
||||
} 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