From cb271e0d5a5316a33dfa91ad07c9936a78730859 Mon Sep 17 00:00:00 2001 From: wang shi zhuo <147490150+bulingbuling688@users.noreply.github.com> Date: Mon, 7 Sep 2026 17:54:44 +0800 Subject: [PATCH 1/2] fix(explorer): align directory mentions with workspace-root grammar --- src/client/Sidebar.tsx | 14 +- src/client/conversation-draft.ts | 47 ++++++- src/client/paths.ts | 25 +++- src/context-types.ts | 17 +++ tests/paths.spec.ts | 32 ++++- tests/reference-mention.spec.ts | 20 ++- tests/sidebar-workspace-reference.spec.tsx | 142 +++++++++++++++++++++ 7 files changed, 279 insertions(+), 18 deletions(-) create mode 100644 tests/sidebar-workspace-reference.spec.tsx diff --git a/src/client/Sidebar.tsx b/src/client/Sidebar.tsx index f20ce7ad..23584443 100644 --- a/src/client/Sidebar.tsx +++ b/src/client/Sidebar.tsx @@ -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 diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index 92350596..23c30688 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -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 `@` but serializes to `@` 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) diff --git a/src/client/paths.ts b/src/client/paths.ts index e43ea104..1b826769 100644 --- a/src/client/paths.ts +++ b/src/client/paths.ts @@ -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 diff --git a/src/context-types.ts b/src/context-types.ts index 37307492..b27aa9bd 100644 --- a/src/context-types.ts +++ b/src/context-types.ts @@ -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 diff --git a/tests/paths.spec.ts b/tests/paths.spec.ts index cee6fec6..ed1b7aea 100644 --- a/tests/paths.spec.ts +++ b/tests/paths.spec.ts @@ -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() + }) +}) diff --git a/tests/reference-mention.spec.ts b/tests/reference-mention.spec.ts index 3ecaaf84..5d76d70f 100644 --- a/tests/reference-mention.spec.ts +++ b/tests/reference-mention.spec.ts @@ -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() + }) +}) diff --git a/tests/sidebar-workspace-reference.spec.tsx b/tests/sidebar-workspace-reference.spec.tsx new file mode 100644 index 00000000..6e41402d --- /dev/null +++ b/tests/sidebar-workspace-reference.spec.tsx @@ -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() } + }) +}) From 1ad9ac75068261ffcf4e595d7e2d71dfde7808bb Mon Sep 17 00:00:00 2001 From: wang shi zhuo <147490150+bulingbuling688@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:52:18 +0800 Subject: [PATCH 2/2] fix(explorer): separate completed directory references --- src/client/conversation-draft.ts | 8 +++++--- tests/conversation-draft.spec.ts | 9 +++++++++ tests/sidebar-workspace-reference.spec.tsx | 23 ++++++++++++++++++---- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index 23c30688..9936cf1b 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -59,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) @@ -69,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, @@ -245,7 +245,9 @@ export function insertWorkspaceReference(ctx: Context, sessionId: string, path: return false } if (!isDir && insertFileReference(ctx, sessionId, relative)) return true - return appendToDraft(ctx, sessionId, mention) + // 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 diff --git a/tests/conversation-draft.spec.ts b/tests/conversation-draft.spec.ts index 3953c7d6..aaf88164 100644 --- a/tests/conversation-draft.spec.ts +++ b/tests/conversation-draft.spec.ts @@ -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') }) diff --git a/tests/sidebar-workspace-reference.spec.tsx b/tests/sidebar-workspace-reference.spec.tsx index 6e41402d..0b5bcc51 100644 --- a/tests/sidebar-workspace-reference.spec.tsx +++ b/tests/sidebar-workspace-reference.spec.tsx @@ -74,7 +74,7 @@ describe('Sidebar workspace references', () => { const view = mount(cwd, { root: '/work' }) try { view.insert('/work/my dir', true) - expect(view.draft()).toBe('before @"my dir/"') + expect(view.draft()).toBe('before @"my dir/" ') expect(view.emit).not.toHaveBeenCalled() } finally { view.unmount() } }) @@ -91,6 +91,21 @@ describe('Sidebar workspace references', () => { } 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 { @@ -103,9 +118,9 @@ describe('Sidebar workspace references', () => { 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/"') + expect(view.draft()).toBe('before @"my dir/nested/" ') view.insert('c:/work', true) - expect(view.draft()).toBe('before @"my dir/nested/" @./') + expect(view.draft()).toBe('before @"my dir/nested/" @./ ') } finally { view.unmount() } }) @@ -125,7 +140,7 @@ describe('Sidebar workspace references', () => { // 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/') + expect(view.draft()).toBe('before @src/ ') } finally { view.unmount() } })