From f71a2727f1ddde5ed74a73d7190fbe48f4c92270 Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sat, 24 Oct 2026 19:09:07 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat(editor):=20=E9=80=89=E5=8C=BA?= =?UTF-8?q?=E5=BC=95=E7=94=A8=E6=94=B9=E6=88=90=E6=B0=94=E6=B3=A1=EF=BC=8C?= =?UTF-8?q?=E6=AD=A3=E6=96=87=E5=8F=AA=E5=9C=A8=E5=8F=91=E9=80=81=E6=97=B6?= =?UTF-8?q?=E5=B1=95=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 选中文字后点「添加到对话」,草稿里插入的不再是一整段围栏正文,而是 一个紧凑气泡(显示 `相对路径:起止行`);发给模型的仍是完整围栏块。 连续引用几段不再把输入框铺满。 - 复用宿主自己的 slash/input-insert-reference 通道(原生 @ 选择器同款) - 新增 foldClipboardOffset:把草稿偏移折算到宿主的 detect 投影,否则 草稿里已有气泡时 span 越界、第二次插入必然失败 - 气泡的 clipboardText 取短形态(label),会话重挂载时退化也只是一行 - 宿主没有气泡通道时回退原来的纯文本路径 - appendToDraft 在已有气泡的草稿上改走 span 事件,避免 setDraft 重建 文档把每个气泡碾平 --- src/client/TextEditor.tsx | 12 +- src/client/conversation-draft.ts | 189 +++++++++++++++++++++++++------ src/client/selection-payload.ts | 18 ++- src/client/selection-popup.ts | 30 ++--- src/context-types.ts | 28 ++++- tests/conversation-draft.spec.ts | 179 +++++++++++++++++++++++++++++ tests/selection-payload.spec.ts | 24 ++-- 7 files changed, 417 insertions(+), 63 deletions(-) diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index 1a87dd11..9d4e619b 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -38,7 +38,7 @@ import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts' import { cmSearchExtensions, CmSearchPhrases } from './cm-search.ts' import { isDarkScheme, subscribeColorScheme } from './theme.ts' import { SandboxStatusBar } from './SandboxStatusBar.tsx' -import { appendToDraft } from './conversation-draft.ts' +import { appendToDraft, insertDraftReference, type DraftReference } from './conversation-draft.ts' import { useSelectionPopup } from './selection-popup.ts' import { buildSelectionInsert, linesOfSelection } from './selection-payload.ts' import { analyzeMarkdownHtml } from './markdown-html.ts' @@ -220,8 +220,14 @@ export function TextEditor(props: FileViewerProps) { * listeners (outside mousedown, Escape, hidden tab/window, surface * leaving the viewport) — see selection-popup.ts. */ - const selectionPopup = useSelectionPopup({ - onCommit: (insert) => { appendToDraft(ctx, scope.sessionId, insert) }, + const selectionPopup = useSelectionPopup({ + // The chip is the whole point of this surface: the composer shows one + // compact `path:lines` reference while the model still receives the full + // quoted body. A host without the chip channel falls back to plain text. + onCommit: (insert) => { + if (insertDraftReference(ctx, scope.sessionId, insert)) return + appendToDraft(ctx, scope.sessionId, insert.text) + }, // The surface that must stay on screen: the markdown preview container // in preview mode, the CodeMirror host otherwise. getSurface: () => (markdown && mode === 'preview' ? mdRef.current : hostRef.current), diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index f3f815e6..b048ac31 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -32,9 +32,43 @@ * separating space on the left, so stacked inserts stay at their running * position (A|B + C + D → ACD|B). */ -import type { Context, SidebarConversation } from '../context-types.ts' +import type { + Context, + SidebarConversation, + SidebarSessionInput, + SidebarSessionOccurrence, +} from '../context-types.ts' import { baseName, workspaceRelativePath } from './paths.ts' +/** + * One structured reference to insert as a chip: the compact `label` the + * composer shows, and the `text` the model receives on send. The two are + * deliberately different — a selection reads as `docs/a.md:12-15` on screen + * while the model still gets the whole fenced block. + */ +export interface DraftReference { + label: string + text: string + /** + * What the draft string carries for this chip (the clipboard projection). + * Defaults to `label`; a file reference spells its `@path` here instead. + * Keep it short: this is the form a remounted session re-seeds the draft + * from, and it cannot be turned back into a chip. + */ + clipboardText?: string +} + +/** The composer shell state one chip insert is minted against. */ +type ComposerSnapshot = ReturnType + +/** The host's reference-insertion payload (see `ReferenceInsert` in dsh-client-ui-conversation). */ +interface ChipReference { + ref: string + label: string + appearance?: 'file' | 'folder' | 'session' + clipboardText: string +} + /** A resolved composer caret/selection in draft coordinates. */ export interface DraftCaret { start: number @@ -161,6 +195,104 @@ export function placeComposerCaretAfterInsert(expectedDraft: string, caretIndex: schedule(place) } +/** + * Fold one clipboard-projection offset to its detect-projection twin. + * + * The host maintains two coordinate systems over the same document: the + * clipboard projection (`InputState.draft`, `occurrences`) expands every chip + * to its whole `clipboardText`, while the detect projection — the one every + * insert/replace event's `span` must speak — collapses each chip to a single + * placeholder character. Deriving a span from a draft offset without folding + * therefore overshoots by `length - 1` per chip, and the host rejects the + * out-of-range span (`applied = false`) — the second chip insert of a session + * would silently fail. + * + * An offset inside a chip's expansion snaps to that chip's trailing edge: the + * host only ever replaces whole chips, never splits one. An offset exactly at + * a chip's START resolves to the position BEFORE the chip — the host's own + * `detectOffsetOfClipboardOffset` reads that case as "inside" and returns the + * trailing edge, which would move a caret one chip too far right. + */ +export function foldClipboardOffset( + draft: string, + occurrences: readonly SidebarSessionOccurrence[], + offset: number, +): number { + const target = Math.max(0, Math.min(offset, draft.length)) + let shrink = 0 + for (const occurrence of occurrences) { + const end = occurrence.offset + occurrence.length + if (target >= end) { + // The whole chip sits at or before the offset: it contributes one + // character instead of its expansion. + shrink += occurrence.length - 1 + continue + } + if (target > occurrence.offset) { + // Inside the chip's expansion — the host only replaces whole chips, so + // snap to this chip's trailing edge. + return Math.max(0, occurrence.offset - shrink + 1) + } + break + } + return Math.max(0, target - shrink) +} + +/** + * Mint one reference chip through the host's own insert event (the same + * `slash/input-insert-reference` channel the native `@` picker uses), so the + * composer shows a compact chip while the model receives `reference.text`. + * + * The chip's `clipboardText` is the compact `label`, not the full payload: + * the clipboard projection is what survives a session remount (the host + * re-seeds a draft from that string), and a full fenced block there would + * re-expand into the very wall of text this chip exists to avoid. The model + * text rides in `ref`, which is serialized back to its full form on send. + * + * Returns false when the host refused the insert (stale revision, a frozen + * submission phase, or no chip channel at all) so the caller can fall back. + */ +export function insertDraftReference( + ctx: Context, + sessionId: string, + reference: DraftReference, +): boolean { + try { + const actx = ctx.sessions.scope(sessionId) + if (actx === undefined) return false + const conversation = ctx.get('conversation') as SidebarConversation | undefined + if (conversation === undefined) return false + const input = conversation.input.for(actx) + const before: ComposerSnapshot = input.state.getSnapshot() + if (before.draftRev === undefined) return false + // Mirrors the host's own admission whitelist; a frozen composer refuses + // every draft write, chip or plain text alike. + if (before.phase !== undefined && before.phase !== 'plain' && before.phase !== 'claimed') return false + const occurrences = before.occurrences ?? [] + // Chips always append at the document end (there is no caret API and the + // composer is a contenteditable, not a textarea — `probeComposerCaret` + // never resolves one), so the span is the folded end position. + const at = foldClipboardOffset(before.draft, occurrences, before.draft.length) + const chip: ChipReference = { + ref: reference.text, + label: reference.label, + appearance: 'file', + clipboardText: reference.clipboardText ?? reference.label, + } + // The session-scope Context's typed `emit` is keyed to DSH's closed event + // map; this internal composer event is deliberately string-loose at runtime. + ;(actx as unknown as { emit(name: string, payload: unknown): void }).emit('slash/input-insert-reference', { + reference: { source: 'reference', ...chip }, + span: { draftRev: before.draftRev, start: at, end: at }, + }) + const after: ComposerSnapshot = input.state.getSnapshot() + return after.draftRev !== before.draftRev + } catch (error) { + console.warn('[dsh-better-sidebar] reference chip insert failed:', error) + return false + } +} + /** * Insert `text` into the session's composer draft at the composer's live * caret (see {@link probeComposerCaret}), falling back to appending at the @@ -180,9 +312,27 @@ export function appendToDraft(ctx: Context, sessionId: string, text: string): bo return false } const input = conversation.input.for(actx) - const draft = input.state.getSnapshot().draft + const snapshot = input.state.getSnapshot() + const draft = snapshot.draft + const occurrences = snapshot.occurrences ?? [] const caret = probeComposerCaret(draft) const { draft: next, caretAfter } = spliceInsert(draft, text, caret) + if (occurrences.length > 0) { + // `setDraft` rebuilds the document from a plain string, which flattens + // every existing chip into its text — so on a draft that already + // carries chips, insert through the span event instead. The separator + // is the same one `spliceInsert` would have added on the left. + const at = foldClipboardOffset(draft, occurrences, caret === null ? draft.length : caret.start) + const lead = caret === null + ? (draft.trim() === '' || /\s$/.test(draft) ? '' : ' ') + : (caret.start === 0 || /\s$/.test(draft.slice(0, caret.start)) ? '' : ' ') + const actxEmit = actx as unknown as { emit(name: string, payload: unknown): void } + actxEmit.emit('slash/input-insert-text', { + text: `${lead}${text}`, + span: { draftRev: snapshot.draftRev, start: at, end: at }, + }) + return input.state.getSnapshot().draftRev !== snapshot.draftRev + } input.setDraft(next) // Put the caret right after the inserted text once the value commit // lands — see the module doc for why this keeps stacked inserts at the @@ -281,34 +431,9 @@ export function insertWorkspaceReference(ctx: Context, sessionId: string, path: export function insertFileReference(ctx: Context, sessionId: string, relativePath: string): boolean { const reference = mentionFor(relativePath, 'file') if (reference === undefined) return false - try { - const actx = ctx.sessions.scope(sessionId) - if (actx === undefined) return false - const conversation = ctx.get('conversation') as SidebarConversation | undefined - if (conversation === undefined) return false - const input = conversation.input.for(actx) - const before = input.state.getSnapshot() - if (before.draftRev === undefined) return false - // The session-scope Context's typed `emit` is keyed to DSH's closed event - // map; this internal composer event is deliberately string-loose at runtime. - ;(actx as unknown as { emit(name: string, payload: unknown): void }).emit('slash/input-insert-reference', { - reference: { - source: 'reference', - ref: reference.mention, - label: reference.label, - appearance: 'file', - clipboardText: reference.mention, - }, - span: { - draftRev: before.draftRev, - start: before.draft.length, - end: before.draft.length, - }, - }) - const after = input.state.getSnapshot() - return after.draftRev !== before.draftRev - } catch (error) { - console.warn('[dsh-better-sidebar] file-reference insert failed:', error) - return false - } + return insertDraftReference(ctx, sessionId, { + label: reference.label, + text: reference.mention, + clipboardText: reference.mention, + }) } diff --git a/src/client/selection-payload.ts b/src/client/selection-payload.ts index 0f6e7e0f..3161e307 100644 --- a/src/client/selection-payload.ts +++ b/src/client/selection-payload.ts @@ -17,8 +17,14 @@ * source lines directly, so it reverse-searches the selected text in the * source and only reports lines on an unambiguous hit (see * {@link linesOfSelection}). + * + * The two halves travel separately: `label` is what the composer shows (one + * compact chip, `docs/a.md:12-15`), `text` is what the model receives (the + * whole fenced block). Several references in a row therefore read as a row + * of chips instead of filling the input box with quoted bodies. */ import { relativeTo } from './paths.ts' +import type { DraftReference } from './conversation-draft.ts' /** Max inserted selection length (UTF-16 code units, i.e. JS `.length`). */ export const SELECTION_LIMIT = 500 @@ -41,19 +47,19 @@ export function headerOf(path: string, cwd: string | undefined, lines?: Selectio } /** - * The full text appended to the composer draft for one selection. - * Over the limit the content is dropped: the plain path line is the whole - * payload (an empty fenced block would just occupy the draft). + * The composer payload for one selection: the chip label and the model text. + * Over the limit the content is dropped and both halves are the plain path + * line (an empty fenced block would just occupy the draft). */ export function buildSelectionInsert( path: string, cwd: string | undefined, lines: SelectionLines | undefined, selected: string, -): string { +): DraftReference { const header = headerOf(path, cwd, lines) - if (selected.length > SELECTION_LIMIT) return header - return `\`\`\`${header}\n${selected}\n\`\`\`` + if (selected.length > SELECTION_LIMIT) return { label: header, text: header } + return { label: header, text: `\`\`\`${header}\n${selected}\n\`\`\`` } } /** 1-based line number of a character index in a text. */ diff --git a/src/client/selection-popup.ts b/src/client/selection-popup.ts index ae844274..dfee58f7 100644 --- a/src/client/selection-popup.ts +++ b/src/client/selection-popup.ts @@ -29,16 +29,20 @@ */ import { useEffect, useRef, useState, type RefObject } from 'react' -/** The floating "add to conversation" action: payload + viewport anchor. */ -export interface SelectionPopup { - insert: string +/** + * The floating "add to conversation" action: payload + viewport anchor. + * The payload type is the caller's — the text viewers carry a + * {@link DraftReference} (chip label + model text), string callers stay as-is. + */ +export interface SelectionPopup { + insert: T left: number top: number } -export interface SelectionPopupOptions { +export interface SelectionPopupOptions { /** Commit the payload into the composer draft (button click). */ - onCommit(insert: string): void + onCommit(insert: T): void /** * The DOM surface that must stay on screen for the popup to live: the * markdown preview container in preview mode, the CodeMirror host @@ -47,20 +51,20 @@ export interface SelectionPopupOptions { getSurface(): HTMLElement | null } -export interface SelectionPopupControls { +export interface SelectionPopupControls { /** The current popup (null = hidden). */ - popup: SelectionPopup | null + popup: SelectionPopup | null /** Attach to the portaled button element. */ buttonRef: RefObject /** Anchor the popup above a selection (viewport-clamped). */ - show(insert: string, left: number, top: number): void + show(insert: T, left: number, top: number): void /** Hide the popup (idempotent). */ hide(): void /** The button's click: commit the stored payload, then hide. */ commit(): void } -export function useSelectionPopup(options: SelectionPopupOptions): SelectionPopupControls { +export function useSelectionPopup(options: SelectionPopupOptions): SelectionPopupControls { // Latest-callback refs: the dismissal listeners live for the mount's // lifetime, so they must not capture stale closures across renders. const onCommitRef = useRef(options.onCommit) @@ -68,16 +72,16 @@ export function useSelectionPopup(options: SelectionPopupOptions): SelectionPopu onCommitRef.current = options.onCommit getSurfaceRef.current = options.getSurface - const [popup, setPopup] = useState(null) + const [popup, setPopup] = useState | null>(null) /** Live mirror for click/event-time reads (no re-render race). */ - const popupRef = useRef(null) + const popupRef = useRef | null>(null) /** The portaled button itself (for the outside-click guard). */ const buttonRef = useRef(null) /** The surface visibility observer (created lazily on open). */ const observerRef = useRef(null) - const show = (insert: string, left: number, top: number): void => { - const next: SelectionPopup = { + const show = (insert: T, left: number, top: number): void => { + const next: SelectionPopup = { insert, left: Math.min(Math.max(left, 80), window.innerWidth - 80), top, diff --git a/src/context-types.ts b/src/context-types.ts index 122bb90d..0dc8b6ce 100644 --- a/src/context-types.ts +++ b/src/context-types.ts @@ -660,12 +660,38 @@ export interface SidebarLocaleService { register(ns: string, locale: string, dict: Record): () => void } +/** + * One reference chip's footprint in the draft, in clipboard-projection + * coordinates: the chip covers `[offset, offset + length)`. Read straight off + * the host's published `InputState.occurrences`. + */ +export interface SidebarSessionOccurrence { + /** Start offset in the clipboard projection (the same plane as `draft`). */ + offset: number + /** Length in the clipboard projection (the chip's whole `clipboardText`). */ + length: number +} + /** The composer draft face the sidebar reaches through `ctx.conversation.input`. */ export interface SidebarSessionInput { /** The live input store (draft read for append). `draftRev` is the machine's * span-CAS revision — required to mint a structured file-reference chip. */ state: { - getSnapshot(): { draft: string; draftRev?: number } + getSnapshot(): { + draft: string + draftRev?: number + /** + * The editor's reference chips as footprints in `draft` coordinates: + * `[offset, offset + length)` per chip, sorted by offset. The host's + * insert/replace spans live in the *editor* projection instead (one + * placeholder character per chip), so a span derived from a `draft` + * offset must fold through these first (`foldClipboardOffset`). + * Absent on hosts without the chip channel. + */ + occurrences?: readonly SidebarSessionOccurrence[] + /** Admission phase; `adjudicating`/`submitting` freeze draft writes. */ + phase?: string + } } /** Replace the draft text (the input machine's single public write path). */ setDraft(text: string): void diff --git a/tests/conversation-draft.spec.ts b/tests/conversation-draft.spec.ts index aaf88164..5a5b10bf 100644 --- a/tests/conversation-draft.spec.ts +++ b/tests/conversation-draft.spec.ts @@ -12,7 +12,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { Context } from '../src/context-types.ts' import { appendToDraft, + foldClipboardOffset, insertAtCaret, + insertDraftReference, placeComposerCaretAfterInsert, probeComposerCaret, } from '../src/client/conversation-draft.ts' @@ -246,4 +248,181 @@ describe('appendToDraft', () => { expect(consoleWarn).toHaveBeenCalledTimes(1) consoleWarn.mockRestore() }) +}) + +describe('foldClipboardOffset', () => { + // 'ab' + chip('docs/a.md:12') + ' cd' — the clipboard projection expands the + // chip; the detect projection collapses it to one character. + const draft = 'abdocs/a.md:12 cd' + const occurrences = [{ offset: 2, length: 12 }] + + it('leaves an offset alone when the draft carries no chips', () => { + expect(foldClipboardOffset('abcdef', [], 4)).toBe(4) + }) + + it('leaves an offset before the first chip untouched', () => { + expect(foldClipboardOffset(draft, occurrences, 1)).toBe(1) + }) + + it('shrinks an offset past a chip by its expansion minus the placeholder', () => { + // 'ab' + 1 placeholder + ' cd' + expect(foldClipboardOffset(draft, occurrences, draft.length)).toBe(6) + }) + + it('lands right after the placeholder for an offset at the chip end', () => { + expect(foldClipboardOffset(draft, occurrences, 14)).toBe(3) + }) + + it('snaps an offset inside the chip to its trailing edge', () => { + expect(foldClipboardOffset(draft, occurrences, 8)).toBe(3) + }) + + it('reads an offset at the chip start as the position before it', () => { + expect(foldClipboardOffset(draft, occurrences, 2)).toBe(2) + }) + + it('folds several chips independently', () => { + // 'x' + chip('a.md:1') + ' ' + chip('b.md:2') + ' z' + const two = 'xa.md:1 b.md:2 z' + const chips = [{ offset: 1, length: 6 }, { offset: 8, length: 6 }] + expect(foldClipboardOffset(two, chips, two.length)).toBe(6) + }) + + it('clamps an out-of-range offset into the draft', () => { + expect(foldClipboardOffset('ab', [], 99)).toBe(2) + expect(foldClipboardOffset('ab', [], -3)).toBe(0) + }) +}) + +describe('insertDraftReference', () => { + /** A fake composer whose revision advances on every emitted chip insert. */ + function chipCtx(options: { + draft?: string + occurrences?: { offset: number; length: number }[] + phase?: string + draftRev?: number + /** Return false to simulate the host refusing the insert. */ + accept?: boolean + withConversation?: boolean + } = {}) { + let draft = options.draft ?? '' + let draftRev = options.draftRev ?? 0 + const emitted: { name: string; payload: unknown }[] = [] + const input = { + state: { + getSnapshot: () => ({ + draft, + draftRev, + occurrences: options.occurrences ?? [], + ...options.phase === undefined ? {} : { phase: options.phase }, + }), + }, + setDraft: (next: string): void => { draft = next; draftRev += 1 }, + } + const actx = { + emit: (name: string, payload: unknown): void => { + emitted.push({ name, payload }) + if (options.accept === false) return + draftRev += 1 + }, + } + const ctx = { + sessions: { scope: (): unknown => actx }, + get: (name: string): unknown => + options.withConversation === false || name !== 'conversation' + ? undefined + : { input: { for: (): unknown => input } }, + } as unknown as Context + return { ctx, emitted, snapshot: () => ({ draft, draftRev }) } + } + + it('emits one reference chip carrying the label and the model text apart', () => { + const fake = chipCtx({ draft: 'hello' }) + expect(insertDraftReference(fake.ctx, 's1', { label: 'a.md:3', text: '```a.md:3\nx\n```' })).toBe(true) + expect(fake.emitted).toHaveLength(1) + expect(fake.emitted[0]?.name).toBe('slash/input-insert-reference') + expect(fake.emitted[0]?.payload).toEqual({ + reference: { + source: 'reference', + ref: '```a.md:3\nx\n```', + label: 'a.md:3', + appearance: 'file', + clipboardText: 'a.md:3', + }, + span: { draftRev: 0, start: 5, end: 5 }, + }) + }) + + it('folds the span past chips already in the draft', () => { + const fake = chipCtx({ draft: 'abdocs/a.md:12 cd', occurrences: [{ offset: 2, length: 12 }] }) + insertDraftReference(fake.ctx, 's1', { label: 'b.md:1', text: 'B' }) + expect((fake.emitted[0]?.payload as { span: { start: number } }).span.start).toBe(6) + }) + + it('reports false when the host refused the insert (revision unchanged)', () => { + const fake = chipCtx({ draft: 'x', accept: false }) + expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false) + }) + + it('reports false when the composer is frozen mid-submission', () => { + const fake = chipCtx({ draft: 'x', phase: 'submitting' }) + expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false) + expect(fake.emitted).toHaveLength(0) + }) + + it('reports false when the host has no chip channel (no draftRev)', () => { + const ctx = { + sessions: { scope: (): unknown => ({ emit: (): void => undefined }) }, + get: (): unknown => ({ input: { for: () => ({ state: { getSnapshot: () => ({ draft: 'x' }) } }) } }), + } as unknown as Context + expect(insertDraftReference(ctx, 's1', { label: 'a', text: 'a' })).toBe(false) + }) + + it('reports false when the conversation service is missing', () => { + const fake = chipCtx({ withConversation: false }) + expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false) + }) +}) + +describe('appendToDraft on a draft that already carries chips', () => { + /** A fake ctx whose setDraft would flatten the chips, plus a span emitter. */ + function chippedCtx(draft: string, occurrences: { offset: number; length: number }[]) { + const emitted: { name: string; payload: unknown }[] = [] + const setDrafts: string[] = [] + const input = { + state: { getSnapshot: () => ({ draft, draftRev: 3, occurrences }) }, + setDraft: (next: string): void => { setDrafts.push(next) }, + } + const actx = { emit: (name: string, payload: unknown): void => { emitted.push({ name, payload }) } } + const ctx = { + sessions: { scope: (): unknown => actx }, + get: (): unknown => ({ input: { for: (): unknown => input } }), + } as unknown as Context + return { ctx, emitted, setDrafts } + } + + it('inserts through the span event instead of rebuilding the draft', () => { + const fake = chippedCtx('abdocs/a.md:12 cd', [{ offset: 2, length: 12 }]) + appendToDraft(fake.ctx, 's1', 'X') + expect(fake.setDrafts).toEqual([]) + expect(fake.emitted).toHaveLength(1) + expect(fake.emitted[0]?.name).toBe('slash/input-insert-text') + const payload = fake.emitted[0]?.payload as { text: string; span: { start: number; end: number } } + expect(payload.span).toEqual({ draftRev: 3, start: 6, end: 6 }) + // The draft ends in 'd', so the insert carries its own separating space. + expect(payload.text).toBe(' X') + }) + + it('adds the separating space the draft end needs', () => { + const fake = chippedCtx('abdocs/a.md:12', [{ offset: 2, length: 12 }]) + appendToDraft(fake.ctx, 's1', 'X') + expect((fake.emitted[0]?.payload as { text: string }).text).toBe(' X') + }) + + it('keeps the plain setDraft path when the draft has no chips', () => { + const fake = chippedCtx('hello', []) + appendToDraft(fake.ctx, 's1', 'X') + expect(fake.emitted).toEqual([]) + expect(fake.setDrafts).toEqual(['hello X']) + }) }) \ No newline at end of file diff --git a/tests/selection-payload.spec.ts b/tests/selection-payload.spec.ts index 2095640d..e4298e19 100644 --- a/tests/selection-payload.spec.ts +++ b/tests/selection-payload.spec.ts @@ -40,26 +40,34 @@ describe('headerOf', () => { describe('buildSelectionInsert', () => { it('wraps a small selection in a fenced block with the path:line info line', () => { - expect(buildSelectionInsert('/p/a.ts', '/p', { start: 2, end: 4 }, 'const x = 1')).toBe( - '```a.ts:2-4\nconst x = 1\n```', - ) + expect(buildSelectionInsert('/p/a.ts', '/p', { start: 2, end: 4 }, 'const x = 1')).toEqual({ + label: 'a.ts:2-4', + text: '```a.ts:2-4\nconst x = 1\n```', + }) }) it('accepts a selection exactly at the limit (fenced)', () => { const text = 'x'.repeat(SELECTION_LIMIT) - expect(buildSelectionInsert('/p/a.ts', '/p', { start: 1, end: 1 }, text)).toBe( - `\`\`\`a.ts:1\n${text}\n\`\`\``, - ) + expect(buildSelectionInsert('/p/a.ts', '/p', { start: 1, end: 1 }, text)).toEqual({ + label: 'a.ts:1', + text: `\`\`\`a.ts:1\n${text}\n\`\`\``, + }) }) it('drops the content past the limit: one plain path line, no fence', () => { const text = 'x'.repeat(SELECTION_LIMIT + 1) - expect(buildSelectionInsert('/p/a.ts', '/p', { start: 7, end: 7 }, text)).toBe('a.ts:7') + expect(buildSelectionInsert('/p/a.ts', '/p', { start: 7, end: 7 }, text)).toEqual({ + label: 'a.ts:7', + text: 'a.ts:7', + }) }) it('keeps the plain-line form when past the limit without line numbers', () => { const text = 'x'.repeat(SELECTION_LIMIT + 1) - expect(buildSelectionInsert('/p/a.ts', '/p', undefined, text)).toBe('a.ts') + expect(buildSelectionInsert('/p/a.ts', '/p', undefined, text)).toEqual({ + label: 'a.ts', + text: 'a.ts', + }) }) }) From 8c431db7402dacd03feda0e7d3ddcbdffb93e98a Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sat, 24 Oct 2026 19:17:42 +0800 Subject: [PATCH 02/10] =?UTF-8?q?test(e2e):=20=E6=96=AD=E8=A8=80=E9=80=89?= =?UTF-8?q?=E5=8C=BA=E5=BC=95=E7=94=A8=E8=90=BD=E5=9C=A8=20composer=20?= =?UTF-8?q?=E9=87=8C=E6=98=AF=E6=B0=94=E6=B3=A1=EF=BC=8C=E4=B8=8D=E6=98=AF?= =?UTF-8?q?=E5=9B=B4=E6=A0=8F=E6=AD=A3=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 真机 mount lane 加一段:预览里选中一行 → 点「添加到对话」→ 断言 composer 里出现 path:lines 气泡,且草稿文本不含三反引号。 宿主若不认 reference-insert 事件、退化成纯文本,这条会直接失败。 同时记录设计与两套坐标系(clipboard / detect)的折算规则。 --- docs/plans/2026-10-24-selection-chip.md | 67 +++++++++++++++++++++++++ tests/e2e/mount.e2e.ts | 23 +++++++++ 2 files changed, 90 insertions(+) create mode 100644 docs/plans/2026-10-24-selection-chip.md diff --git a/docs/plans/2026-10-24-selection-chip.md b/docs/plans/2026-10-24-selection-chip.md new file mode 100644 index 00000000..5017d2f0 --- /dev/null +++ b/docs/plans/2026-10-24-selection-chip.md @@ -0,0 +1,67 @@ +# 选区引用改气泡:把「添加到对话」从铺开正文改成 chip + +**日期**:2026-10-24 +**分支**:`feat/selection-chip-compact`(从 `dev` 切出) +**状态**:已实施,门禁见 §5 + +--- + +## 1. 背景 + +侧栏文本查看器(markdown 预览 + 兜底代码查看器)选中文字后点浮层的「添加到对话」,draft 里插进去的是一整段**围栏代码块**(info line = `相对路径:起止行`,正文 = 选中文字)。 + +单次引用没问题;连续引用几段就把输入框铺满,用户真正要写的那句话被挤没影了。DSH 自己的 `@file` 引用在同一个输入框里却是**一个紧凑气泡**(图标 + 文件名)。这次的诉求就是把这个反差抹平:**引用只要一个标识,正文交给模型**。 + +## 2. 机制(为什么插件侧就能做到) + +宿主 composer 是 Lexical contenteditable,引用条目是 `ReferenceChipNode`。它有三个可以分开的字段: + +| 字段 | 作用 | +|---|---| +| `label` | 气泡上显示的字 | +| `ref` | 发送时序列化给模型的正文(`source: 'reference'` 的 codec 是恒等) | +| `clipboardText` | 草稿串里占位的那段文本 | + +所以「显示短、发送长」本来就是宿主支持的能力,插件只需按这个形状发插入请求。 + +插入通道复用文件树 `@` 按钮已经在用的 `slash/input-insert-reference`(`source: 'reference'`),不新增 source、不碰 `inputTriggers` 注册表。 + +## 3. 关键坑:两套坐标系 + +宿主对输入框维护两个投影: + +| 投影 | 一个气泡占多长 | 谁在用 | +|---|---|---| +| clipboard(`InputState.draft`、`occurrences`) | 整个 `clipboardText` | 插件:读草稿串、算位置 | +| detect(`detectText`) | **1 个字符** `U+FFFC` | 宿主:所有插入事件的 `span` | + +草稿为空时两套坐标重合,第一次插入成功;草稿里一旦有气泡,从草稿偏移直接算出的 `span` 必然越界,宿主拒绝(`applied = false`),**第二次插入静默失败**。 + +修复:`foldClipboardOffset` 按 `occurrences` 把草稿偏移折到 detect 偏移。唯一有意的偏离——偏移正好落在气泡**起点**时,返回气泡**之前**的位置(宿主自己的同名函数会把它读成「在气泡内部」而返回尾边)。 + +## 4. 改动 + +| 文件 | 变更 | +|---|---| +| `src/client/conversation-draft.ts` | 新增 `foldClipboardOffset`、`insertDraftReference`、`DraftReference` 类型;`insertFileReference` 改走同一函数(行为不变);`appendToDraft` 在草稿已有气泡时改走 `slash/input-insert-text`,不再用 `setDraft` | +| `src/client/selection-payload.ts` | `buildSelectionInsert` 返回 `{ label, text }`(原返回单个字符串) | +| `src/client/selection-popup.ts` | 三个导出接口与 hook 泛型化,默认 `T = string`,字符串调用方零改动 | +| `src/client/TextEditor.tsx` | `useSelectionPopup`;commit 先试气泡,失败回退纯文本 | +| `src/context-types.ts` | `SidebarSessionInput.state.getSnapshot()` 补 `occurrences` / `phase` | + +**为什么 `appendToDraft` 也要改**:`setDraft` 会 `root.clear()` 重建纯文本文档,把草稿里**每一个**气泡碾平。原来的降级路径在有气泡的草稿上会毁掉用户已有的引用。 + +**为什么 `clipboardText` 取短形态**:会话重挂载时宿主用持久化的草稿串回灌(`setDraft` 无法从字符串恢复气泡节点)。`clipboardText` 若存整段围栏正文,退化后就是最刺眼的那种铺满输入框;存 `path:lines` 则只退化成一行。 + +## 5. 验证 + +- `pnpm typecheck` / `pnpm lint` / `pnpm build` 通过。 +- `pnpm test`:**2794 passed / 4 failed**,4 例全是本机 `tests/fs-operations.spec.ts`、`fs-mkdir.spec.ts`、`file-stream-route.spec.ts` 创建符号链接报 `EPERM`(Windows 权限差异)。已在干净 `dev` 上复现同样的 4 例,与本改动无关。 +- 本改动相关:`tests/conversation-draft.spec.ts` 50 passed(含 `foldClipboardOffset` 8 例、`insertDraftReference` 6 例、有气泡草稿上的 `appendToDraft` 3 例)、`tests/selection-payload.spec.ts` 16 passed、`tests/selection-popup.spec.tsx` 8 passed。 +- 真机 mount lane:新增探针在 markdown 预览里选中一行、点提交按钮,断言 composer 里出现 `diagram.md:` 气泡,且草稿文本不含三反引号围栏。 + +## 6. 已知边界 + +- 气泡的 `clipboardText` 与 `ref` 都是 `label`(文件引用另存 `@path`),宿主提交前 `trim`。 +- 全空白草稿上插入会留一个前导空格(宿主只允许整气泡替换)。 +- 气泡路径不调用 `placeComposerCaretAfterInsert`:宿主事件本身接管光标,DOM 光标恢复只服务 `setDraft` 那条路径。 diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index 596c3921..e46ae029 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -577,6 +577,29 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async await expect(modal, 'Esc must close the zoom modal').toHaveCount(0, { timeout: 10_000 }) await assertNoCrash() + // Selection references commit as CHIPS, not quoted blocks: select a line in + // the markdown preview, click the floating "add to conversation" button, and + // require the composer to hold one reference chip whose label is + // `path:lines` — with no fenced body anywhere in the draft. This is the + // whole point of the chip path: a host that ignores the reference-insert + // event degrades to plain text and fails right here. + const previewLine = pane.getByText('tail text') + await previewLine.click({ clickCount: 3 }) // triple-click selects the line + const addToChat = page.locator('button', { hasText: /添加到对话|Add to conversation/ }).first() + await expect(addToChat, 'selecting preview text must raise the add-to-conversation button') + .toBeVisible({ timeout: 10_000 }) + await addToChat.click() + const composer = page.getByRole('textbox', { name: /^(Describe what you want to build|描述你想要构建)/ }) + const chip = composer.locator('[data-lexical-decorator], [class*="reference"], [class*="chip"]').first() + await expect(chip, 'the selection must land in the composer as a reference chip') + .toBeVisible({ timeout: 10_000 }) + await expect(chip, 'the chip label must name the file and its line span') + .toContainText(`${SEEDED_MD_FILE}:`, { timeout: 10_000 }) + const draftText = await composer.innerText() + expect(draftText, 'the draft must not carry the quoted body the chip replaced') + .not.toContain('```') + await assertNoCrash() + // README-style markdown (raw-HTML runs + TOC): open the seeded file and // require the full round-trip — sanitized HTML leaves (badge image as a real // element, active content stripped), markdown nested inside the unclosed From 9ebb14f7adcd4bef8b0faa35dcbf3f6dd405d84e Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sat, 24 Oct 2026 19:19:05 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix(editor):=20=E6=9C=89=E6=B0=94?= =?UTF-8?q?=E6=B3=A1=E4=BD=86=E6=97=A0=20revision=20=E6=97=B6=E6=8B=92?= =?UTF-8?q?=E7=BB=9D=E5=86=99=E5=85=A5=EF=BC=8C=E5=88=AB=E9=80=80=E5=8C=96?= =?UTF-8?q?=E6=88=90=E7=A2=BE=E5=B9=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 宿主若既不给 draftRev 又拿不到 span 通道,剩下唯一的写入路径是 setDraft,它会重建整个文档、把每个气泡碾平。宁可不插入,也不毁掉 用户已经堆好的引用。 --- docs/ecosystem.md | 79 ++++++++++++++++++++++++++++++++ docs/install-channels.md | 41 +++++++++++++++++ src/client/conversation-draft.ts | 6 +++ 3 files changed, 126 insertions(+) create mode 100644 docs/ecosystem.md create mode 100644 docs/install-channels.md diff --git a/docs/ecosystem.md b/docs/ecosystem.md new file mode 100644 index 00000000..44c88896 --- /dev/null +++ b/docs/ecosystem.md @@ -0,0 +1,79 @@ +# 🌐 插件生态 + +> 本页从 [README](../README.md#-插件生态) 拆出:插件清单长得快,README 只留接入入口。 +> 注册 API(`registerTab` / `registerFileViewer`)见 [README](../README.md) 与 [external-plugin-guide.md](./external-plugin-guide.md)。 + +GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) 下已收录 **36 个**生态插件(持续增长中)。 + +**上架你的插件**:给仓库打上 `dsh-better-sidebar` topic 即出现在 [topic 页](https://github.com/topics/dsh-better-sidebar);再向 [`src/client/plugins-tabs.ts`](../src/client/plugins-tabs.ts) / [`src/client/plugins-viewers.ts`](../src/client/plugins-viewers.ts) 提一条 `PluginEntry` PR,即可进入设置页内置推荐目录(数据完整性由 `tests/plugin-list.spec.ts` 守护)。 + +
+ 设置页「添加插件」弹窗:推荐插件目录 + 一键复制安装命令
+ 设置页「侧边卡片」内置「添加插件」弹窗:推荐目录 + 一键复制安装命令 + 直达 GitHub topic +
+ +## 📑 Tab 插件(注册侧边栏页面) + +
+28 个插件(点击展开) + +| 插件 | ⭐ | 简介 | +|---|---|---| +| [ChenRuoT/dsh-sidebar-qa](https://github.com/ChenRuoT/dsh-sidebar-qa) | stars | 划选追问侧边页:类 Codex 侧边提问 / Claude Code `/btw` | +| [fuhefei/dsh-sentinel](https://github.com/fuhefei/dsh-sentinel) | stars | 条件驱动唤醒系统:文件 / 命令 / HTTP / 进程 / Webhook 监视,到点唤醒 agent;dock + 侧栏分支 + 全局仪表盘 | +| [Fisfzy/ego-browser](https://github.com/Fisfzy/ego-browser) | stars | Agent 浏览器:i18n 感知的本机浏览器 Tab(`@dsh-external/ego-browser`,装了 better-sidebar 自动注册侧边栏页,未装回退浮动浮窗观察) | +| [jiuge2467/dsh-studio](https://github.com/jiuge2467/dsh-studio) | stars | 全栈增强工作台:多源 MCP 可视化调试中枢、视觉思考引擎 | +| [Iwctwbh/dsh-flowglass](https://github.com/Iwctwbh/dsh-flowglass) | stars | 流镜 Flowglass:会话流程图实时可视化(消息 / 工具组 / 子代理分支) | +| [FeatherHunter/dsh-mattpocock-skills-deck](https://github.com/FeatherHunter/dsh-mattpocock-skills-deck) | stars | mattpocock/skills 游戏化任务系统:地图拨迷雾、任务栏推进 | +| [GULI-lab/DSH-element-source](https://github.com/GULI-lab/DSH-element-source) | stars | 点击页面任意 UI 元素直达 Vue / React / Svelte / Angular 源码并送入会话 | +| [Lzh3070/dsh-file-review-tab](https://github.com/Lzh3070/dsh-file-review-tab) | stars | 文件改动审查页:行级红绿 diff + 撤销 + chat 行深链 | +| [yq04/dsh-git-remotes](https://github.com/yq04/dsh-git-remotes) | stars | Git 远程页:分支 / 上游 / ahead-behind,fetch 可 prune、ff-only pull、确认后 push | +| [ztyhehe/dsh-better-sidebar-svn](https://github.com/ztyhehe/dsh-better-sidebar-svn) | stars | SVN 源码管理页:status / diff / log / commit / update / revert / 冲突解决,与内置 Git 面板对称 | +| [Melody-max114/dsh-excel-panel](https://github.com/Melody-max114/dsh-excel-panel) | stars | Excel 编辑页:xlsx 预览 / 编辑、公式实时计算、合并单元格、保存回原文件 | +| [v587d/dsh-anysearch-refs](https://github.com/v587d/dsh-anysearch-refs) | stars | AnySearch 搜索结果引用卡片:搜索词、来源摘要、关键词高亮 | +| [Lukeknow0/dsh-markdown-link-preview](https://github.com/Lukeknow0/dsh-markdown-link-preview) | stars | Markdown 产物链接预览:点击聊天中的同源 `.md` 输出文件,直接在侧边栏阅读,不再唤起外部 App | +| [mlosun/dsh-docs-panel](https://github.com/mlosun/dsh-docs-panel) | stars | 全局文档面板:随身 Markdown 笔记,任何工作区随时可读 | +| [tylina/dsh-tylina](https://github.com/tylina/dsh-tylina) | stars | Typst 文档编辑工具:与当前会话共用工作区,WYSIWYG 编辑排版 Typst 文档,可用于编写和排版论文、报告、试卷、简历、图表、海报、乐谱和 PPTX 格式导出的 Slides | +| [lnyuqian/dsh-skill-sidebar](https://github.com/lnyuqian/dsh-skill-sidebar) | stars | 技能面板:扫描本机技能目录,4-6 字功能短语 + 一键复制调用 + 置顶 | +| [g-yixuan/dsh-sidenote](https://github.com/g-yixuan/dsh-sidenote) | stars | Codex 风格侧边对话 + 划选引用注释(轻量消费插件) | +| [OMSociety/dsh-ssh-tunnel](https://github.com/OMSociety/dsh-ssh-tunnel) | stars | 多主机 SSH 隧道 + SSH 管理器页 | +| [OMSociety/dsh-git-forge](https://github.com/OMSociety/dsh-git-forge) | stars | GitHub / Gitea 账号、项目授权与推送策略 | +| [YesSanSan/dsh-conversation-outline](https://github.com/YesSanSan/dsh-conversation-outline) | stars | 对话大纲页:按轮次结构化展示、一键跳转、LLM 一句话标题 | +| [Wulabalabo/dsh-sidebar-Explorer-Plus](https://github.com/Wulabalabo/dsh-sidebar-Explorer-Plus) | stars | 文件管理页:上传 / 移动 / 删除 / 重命名 / 新建文件夹(补全写操作) | +| [yq04/dsh-turn-review](https://github.com/yq04/dsh-turn-review) | stars | 本轮审查:逐回合审查 agent 改动 | +| [Ghz114514/dsh-refpics](https://github.com/Ghz114514/dsh-refpics) | stars | Pinterest 风格参考图搜索:瀑布流、侧栏画板、下载与 Eagle 收藏 | +| [yzlin499/dsh-yzlin499-easy-plugins](https://github.com/yzlin499/dsh-yzlin499-easy-plugins) | stars | 实用小工具集(毛坯房 DSH 友好) | +| [dong-victor/dsh-better-sidebar-starter](https://github.com/dong-victor/dsh-better-sidebar-starter) | stars | 运行配置页:IDEA 式 Run/Debug 配置(npm / springboot / python / custom)——一键启动、历史保存、WebSocket 实时日志(ANSI 彩色)、多实例并行、进程树跨平台杀死 | +| [baosfeng/my-dsh-plugins](https://github.com/baosfeng/my-dsh-plugins) | stars | 个人多插件合集(`dsh-file-activity`):侧边栏文件活动页——记录文件读取 / 新增 / 修改历史与统计,按文件夹平铺,点击用原生预览打开 | +| [Hoemr/dsh-better-overleaf](https://github.com/Hoemr/dsh-better-overleaf) | stars | Overleaf 标签页:直连 CDP 浏览器登录(支持第三方 Chromium)、项目切换、工作区下 overleaf/ 目录本地 git 镜像与双向同步 | +| [Andor-Z/dsh-turn-outline](https://github.com/Andor-Z/dsh-turn-outline) | stars | 轮次轨迹页:按用户轮次折叠会话(输入 + 工具步骤 + 输出),点击任意步骤一键跳回对话原位;零 LLM、只读 | + +
+ +## 🖼️ 预览插件(注册文件预览器) + +
+4 个插件(点击展开) + +| 插件 | ⭐ | 简介 | +|---|---|---| +| [HuanLinOTO/dsh-plugin-better-sidebar-plugin-office](https://github.com/HuanLinOTO/dsh-plugin-better-sidebar-plugin-office) | stars | Office 三件套预览(.docx / .xlsx / .pptx),独立 bundle 瘦身主体(官方推荐目录收录) | +| [HuanLinOTO/dsh-plugin-better-sidebar-plugin-audio](https://github.com/HuanLinOTO/dsh-plugin-better-sidebar-plugin-audio) | stars | 音频预览:可缩放波形播放器(点击/拖动定位、A-B 循环、声道切换、倍速)+ 实时频谱(柱状/折线/瀑布)+ 全曲频谱图,自带 HTTP Range 流式媒体路由,任意大小可拖进度 | +| [zemul/dsh-video-preview](https://github.com/zemul/dsh-video-preview) | stars | 视频内联预览:.mp4 / .webm / .mov / .mkv / .avi,自带 /video 路由支持 HTTP Range 拖进度条 | +| [dong-victor/dsh-better-sidebar-jupyter](https://github.com/dong-victor/dsh-better-sidebar-jupyter) | stars | `.ipynb` 可运行 Notebook 视图:懒启动 Python kernel、流式输出、保存回写 | + +
+ +## 🧰 增强与工具 + +
+4 个插件(点击展开) + +| 插件 | ⭐ | 简介 | +|---|---|---| +| [eg-bole/dsh-better-sidebar-icons](https://github.com/eg-bole/dsh-better-sidebar-icons) | stars | VSCode 风格文件 / 文件夹图标主题:文件树与编辑器 Tab 换上熟悉的开发环境图标(vscode-icons 移植,纯 DOM 覆盖零侵入,安装 / 卸载零残留) | +| [dong-victor/dsh-better-sidebar-terminal-plus](https://github.com/dong-victor/dsh-better-sidebar-terminal-plus) | stars | 终端增强:内嵌 Nerd Font 图标字体、修复 xterm 图标渲染、稳定终端 cwd | +| [Max-Null/dsh-sidebar-preview-select](https://github.com/Max-Null/dsh-sidebar-preview-select) | stars | 预览划选增强:侧边栏预览里划选文本 → 浮动「发送到会话」 | +| [Hoemr/dsh-quicklook](https://github.com/Hoemr/dsh-quicklook) | stars | QuickLook 式空格预览:活动文件标签页按 Space 全尺寸查看图片 / PDF / 文本,Space 或 Esc 关闭 | + +
diff --git a/docs/install-channels.md b/docs/install-channels.md new file mode 100644 index 00000000..727728f7 --- /dev/null +++ b/docs/install-channels.md @@ -0,0 +1,41 @@ +# 🚀 安装通道(可选) + +> 本页从 [README](../README.md#-安装) 拆出:主安装方式只有一条 `dsh plugin --profile web add dsh-better-sidebar@latest`, +> 「从源码安装」与「plugin-registry 通道」属于可选路径,放在这里维护。 + +## 🧰 从源码安装 / 开发 + +调试本地改动或跟随开发分支时,把依赖指向本地克隆并自行构建: + +```text +1. git clone https://github.com/omdsh-dev/DSH-better-sidebar.git ~/Code/DSH-better-sidebar + cd ~/Code/DSH-better-sidebar && pnpm install && pnpm build +2. ~/.dsh/profiles/web/package.json 的 dependencies 写 "dsh-better-sidebar": "link:<克隆目录绝对路径>" +3. ~/.dsh/profiles/web/cordis.patch.yml 追加挂载行(这一行的 config 就是本插件的设置表单,不写则全用 schema 默认值): + - insert: + - id: better-sidebar + name: 'dsh-better-sidebar' + config: + listLimit: 1000 +4. 在 ~/.dsh/profiles/web 执行 pnpm install +5. 硬刷新浏览器(Cmd/Ctrl+Shift+R);client 改动热加载,host 半改动才需重启 +``` + +更新:`git pull && pnpm install && pnpm build` → 硬刷新。切回 npm 通道时把依赖改回版本号(当前线 `^0.26.0`)再 `pnpm install`。 + +--- + +## 📦 通过 plugin-registry 安装(与 npm 通道二选一) + +前置:DSH 已集成 [plugin-registry](https://github.com/dsh-external/plugin-registry)(`dsh registry` 可用)。**同时启用两个通道会双挂载**(Node 半挂两次、页面两个侧边栏)。 + +```sh +git clone https://github.com/omdsh-dev/DSH-better-sidebar.git && cd DSH-better-sidebar +pnpm install && pnpm build +node scripts/package-registry.mjs # 组装 registry/ 暂存(含清单 + 产物 + README,不入库) +dsh registry install ./registry # 安装(默认禁用) +dsh registry enable dsh-external/dsh-better-sidebar +``` + +更新:`git pull && pnpm install && pnpm build` → `node scripts/package-registry.mjs` → `dsh registry uninstall/install/enable`。切换通道前先移除另一通道的挂载。 + diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index b048ac31..34e7a475 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -326,6 +326,12 @@ export function appendToDraft(ctx: Context, sessionId: string, text: string): bo const lead = caret === null ? (draft.trim() === '' || /\s$/.test(draft) ? '' : ' ') : (caret.start === 0 || /\s$/.test(draft.slice(0, caret.start)) ? '' : ' ') + if (snapshot.draftRev === undefined) { + // No revision means no span channel either — the only remaining write + // path (`setDraft`) would flatten every chip, so refuse instead. + console.warn('[dsh-better-sidebar] draft insert skipped: chip draft without a revision') + return false + } const actxEmit = actx as unknown as { emit(name: string, payload: unknown): void } actxEmit.emit('slash/input-insert-text', { text: `${lead}${text}`, From 1ed872268c2edef6e8ddb330133268521cd9ec9f Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sat, 24 Oct 2026 19:33:33 +0800 Subject: [PATCH 04/10] =?UTF-8?q?test(e2e):=20=E9=80=89=E5=8C=BA=E6=B0=94?= =?UTF-8?q?=E6=B3=A1=E6=8E=A2=E9=92=88=E6=94=B9=E7=94=A8=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E6=8B=96=E6=8B=BD=E4=B8=8E=E6=AD=A3=E7=A1=AE=E7=9A=84=E9=80=89?= =?UTF-8?q?=E6=8B=A9=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三击/合成点击会在 mouseup 之前丢掉选区,浮层不弹;改用 mouse.move/down/up 的真实拖拽。气泡是 composer 里的兄弟装饰节点,不是 role=textbox 的后代, 选择器改按 label 文本在整页范围内定位。 真机 mount lane 已验证通过(23s):预览里选中一行 → 点按钮 → composer 里出现 diagram.md:12 气泡,草稿不含三反引号。 --- docs/ecosystem.md | 79 ---------------------------------------- docs/install-channels.md | 41 --------------------- tests/e2e/mount.e2e.ts | 26 +++++++++---- 3 files changed, 18 insertions(+), 128 deletions(-) delete mode 100644 docs/ecosystem.md delete mode 100644 docs/install-channels.md diff --git a/docs/ecosystem.md b/docs/ecosystem.md deleted file mode 100644 index 44c88896..00000000 --- a/docs/ecosystem.md +++ /dev/null @@ -1,79 +0,0 @@ -# 🌐 插件生态 - -> 本页从 [README](../README.md#-插件生态) 拆出:插件清单长得快,README 只留接入入口。 -> 注册 API(`registerTab` / `registerFileViewer`)见 [README](../README.md) 与 [external-plugin-guide.md](./external-plugin-guide.md)。 - -GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) 下已收录 **36 个**生态插件(持续增长中)。 - -**上架你的插件**:给仓库打上 `dsh-better-sidebar` topic 即出现在 [topic 页](https://github.com/topics/dsh-better-sidebar);再向 [`src/client/plugins-tabs.ts`](../src/client/plugins-tabs.ts) / [`src/client/plugins-viewers.ts`](../src/client/plugins-viewers.ts) 提一条 `PluginEntry` PR,即可进入设置页内置推荐目录(数据完整性由 `tests/plugin-list.spec.ts` 守护)。 - -
- 设置页「添加插件」弹窗:推荐插件目录 + 一键复制安装命令
- 设置页「侧边卡片」内置「添加插件」弹窗:推荐目录 + 一键复制安装命令 + 直达 GitHub topic -
- -## 📑 Tab 插件(注册侧边栏页面) - -
-28 个插件(点击展开) - -| 插件 | ⭐ | 简介 | -|---|---|---| -| [ChenRuoT/dsh-sidebar-qa](https://github.com/ChenRuoT/dsh-sidebar-qa) | stars | 划选追问侧边页:类 Codex 侧边提问 / Claude Code `/btw` | -| [fuhefei/dsh-sentinel](https://github.com/fuhefei/dsh-sentinel) | stars | 条件驱动唤醒系统:文件 / 命令 / HTTP / 进程 / Webhook 监视,到点唤醒 agent;dock + 侧栏分支 + 全局仪表盘 | -| [Fisfzy/ego-browser](https://github.com/Fisfzy/ego-browser) | stars | Agent 浏览器:i18n 感知的本机浏览器 Tab(`@dsh-external/ego-browser`,装了 better-sidebar 自动注册侧边栏页,未装回退浮动浮窗观察) | -| [jiuge2467/dsh-studio](https://github.com/jiuge2467/dsh-studio) | stars | 全栈增强工作台:多源 MCP 可视化调试中枢、视觉思考引擎 | -| [Iwctwbh/dsh-flowglass](https://github.com/Iwctwbh/dsh-flowglass) | stars | 流镜 Flowglass:会话流程图实时可视化(消息 / 工具组 / 子代理分支) | -| [FeatherHunter/dsh-mattpocock-skills-deck](https://github.com/FeatherHunter/dsh-mattpocock-skills-deck) | stars | mattpocock/skills 游戏化任务系统:地图拨迷雾、任务栏推进 | -| [GULI-lab/DSH-element-source](https://github.com/GULI-lab/DSH-element-source) | stars | 点击页面任意 UI 元素直达 Vue / React / Svelte / Angular 源码并送入会话 | -| [Lzh3070/dsh-file-review-tab](https://github.com/Lzh3070/dsh-file-review-tab) | stars | 文件改动审查页:行级红绿 diff + 撤销 + chat 行深链 | -| [yq04/dsh-git-remotes](https://github.com/yq04/dsh-git-remotes) | stars | Git 远程页:分支 / 上游 / ahead-behind,fetch 可 prune、ff-only pull、确认后 push | -| [ztyhehe/dsh-better-sidebar-svn](https://github.com/ztyhehe/dsh-better-sidebar-svn) | stars | SVN 源码管理页:status / diff / log / commit / update / revert / 冲突解决,与内置 Git 面板对称 | -| [Melody-max114/dsh-excel-panel](https://github.com/Melody-max114/dsh-excel-panel) | stars | Excel 编辑页:xlsx 预览 / 编辑、公式实时计算、合并单元格、保存回原文件 | -| [v587d/dsh-anysearch-refs](https://github.com/v587d/dsh-anysearch-refs) | stars | AnySearch 搜索结果引用卡片:搜索词、来源摘要、关键词高亮 | -| [Lukeknow0/dsh-markdown-link-preview](https://github.com/Lukeknow0/dsh-markdown-link-preview) | stars | Markdown 产物链接预览:点击聊天中的同源 `.md` 输出文件,直接在侧边栏阅读,不再唤起外部 App | -| [mlosun/dsh-docs-panel](https://github.com/mlosun/dsh-docs-panel) | stars | 全局文档面板:随身 Markdown 笔记,任何工作区随时可读 | -| [tylina/dsh-tylina](https://github.com/tylina/dsh-tylina) | stars | Typst 文档编辑工具:与当前会话共用工作区,WYSIWYG 编辑排版 Typst 文档,可用于编写和排版论文、报告、试卷、简历、图表、海报、乐谱和 PPTX 格式导出的 Slides | -| [lnyuqian/dsh-skill-sidebar](https://github.com/lnyuqian/dsh-skill-sidebar) | stars | 技能面板:扫描本机技能目录,4-6 字功能短语 + 一键复制调用 + 置顶 | -| [g-yixuan/dsh-sidenote](https://github.com/g-yixuan/dsh-sidenote) | stars | Codex 风格侧边对话 + 划选引用注释(轻量消费插件) | -| [OMSociety/dsh-ssh-tunnel](https://github.com/OMSociety/dsh-ssh-tunnel) | stars | 多主机 SSH 隧道 + SSH 管理器页 | -| [OMSociety/dsh-git-forge](https://github.com/OMSociety/dsh-git-forge) | stars | GitHub / Gitea 账号、项目授权与推送策略 | -| [YesSanSan/dsh-conversation-outline](https://github.com/YesSanSan/dsh-conversation-outline) | stars | 对话大纲页:按轮次结构化展示、一键跳转、LLM 一句话标题 | -| [Wulabalabo/dsh-sidebar-Explorer-Plus](https://github.com/Wulabalabo/dsh-sidebar-Explorer-Plus) | stars | 文件管理页:上传 / 移动 / 删除 / 重命名 / 新建文件夹(补全写操作) | -| [yq04/dsh-turn-review](https://github.com/yq04/dsh-turn-review) | stars | 本轮审查:逐回合审查 agent 改动 | -| [Ghz114514/dsh-refpics](https://github.com/Ghz114514/dsh-refpics) | stars | Pinterest 风格参考图搜索:瀑布流、侧栏画板、下载与 Eagle 收藏 | -| [yzlin499/dsh-yzlin499-easy-plugins](https://github.com/yzlin499/dsh-yzlin499-easy-plugins) | stars | 实用小工具集(毛坯房 DSH 友好) | -| [dong-victor/dsh-better-sidebar-starter](https://github.com/dong-victor/dsh-better-sidebar-starter) | stars | 运行配置页:IDEA 式 Run/Debug 配置(npm / springboot / python / custom)——一键启动、历史保存、WebSocket 实时日志(ANSI 彩色)、多实例并行、进程树跨平台杀死 | -| [baosfeng/my-dsh-plugins](https://github.com/baosfeng/my-dsh-plugins) | stars | 个人多插件合集(`dsh-file-activity`):侧边栏文件活动页——记录文件读取 / 新增 / 修改历史与统计,按文件夹平铺,点击用原生预览打开 | -| [Hoemr/dsh-better-overleaf](https://github.com/Hoemr/dsh-better-overleaf) | stars | Overleaf 标签页:直连 CDP 浏览器登录(支持第三方 Chromium)、项目切换、工作区下 overleaf/ 目录本地 git 镜像与双向同步 | -| [Andor-Z/dsh-turn-outline](https://github.com/Andor-Z/dsh-turn-outline) | stars | 轮次轨迹页:按用户轮次折叠会话(输入 + 工具步骤 + 输出),点击任意步骤一键跳回对话原位;零 LLM、只读 | - -
- -## 🖼️ 预览插件(注册文件预览器) - -
-4 个插件(点击展开) - -| 插件 | ⭐ | 简介 | -|---|---|---| -| [HuanLinOTO/dsh-plugin-better-sidebar-plugin-office](https://github.com/HuanLinOTO/dsh-plugin-better-sidebar-plugin-office) | stars | Office 三件套预览(.docx / .xlsx / .pptx),独立 bundle 瘦身主体(官方推荐目录收录) | -| [HuanLinOTO/dsh-plugin-better-sidebar-plugin-audio](https://github.com/HuanLinOTO/dsh-plugin-better-sidebar-plugin-audio) | stars | 音频预览:可缩放波形播放器(点击/拖动定位、A-B 循环、声道切换、倍速)+ 实时频谱(柱状/折线/瀑布)+ 全曲频谱图,自带 HTTP Range 流式媒体路由,任意大小可拖进度 | -| [zemul/dsh-video-preview](https://github.com/zemul/dsh-video-preview) | stars | 视频内联预览:.mp4 / .webm / .mov / .mkv / .avi,自带 /video 路由支持 HTTP Range 拖进度条 | -| [dong-victor/dsh-better-sidebar-jupyter](https://github.com/dong-victor/dsh-better-sidebar-jupyter) | stars | `.ipynb` 可运行 Notebook 视图:懒启动 Python kernel、流式输出、保存回写 | - -
- -## 🧰 增强与工具 - -
-4 个插件(点击展开) - -| 插件 | ⭐ | 简介 | -|---|---|---| -| [eg-bole/dsh-better-sidebar-icons](https://github.com/eg-bole/dsh-better-sidebar-icons) | stars | VSCode 风格文件 / 文件夹图标主题:文件树与编辑器 Tab 换上熟悉的开发环境图标(vscode-icons 移植,纯 DOM 覆盖零侵入,安装 / 卸载零残留) | -| [dong-victor/dsh-better-sidebar-terminal-plus](https://github.com/dong-victor/dsh-better-sidebar-terminal-plus) | stars | 终端增强:内嵌 Nerd Font 图标字体、修复 xterm 图标渲染、稳定终端 cwd | -| [Max-Null/dsh-sidebar-preview-select](https://github.com/Max-Null/dsh-sidebar-preview-select) | stars | 预览划选增强:侧边栏预览里划选文本 → 浮动「发送到会话」 | -| [Hoemr/dsh-quicklook](https://github.com/Hoemr/dsh-quicklook) | stars | QuickLook 式空格预览:活动文件标签页按 Space 全尺寸查看图片 / PDF / 文本,Space 或 Esc 关闭 | - -
diff --git a/docs/install-channels.md b/docs/install-channels.md deleted file mode 100644 index 727728f7..00000000 --- a/docs/install-channels.md +++ /dev/null @@ -1,41 +0,0 @@ -# 🚀 安装通道(可选) - -> 本页从 [README](../README.md#-安装) 拆出:主安装方式只有一条 `dsh plugin --profile web add dsh-better-sidebar@latest`, -> 「从源码安装」与「plugin-registry 通道」属于可选路径,放在这里维护。 - -## 🧰 从源码安装 / 开发 - -调试本地改动或跟随开发分支时,把依赖指向本地克隆并自行构建: - -```text -1. git clone https://github.com/omdsh-dev/DSH-better-sidebar.git ~/Code/DSH-better-sidebar - cd ~/Code/DSH-better-sidebar && pnpm install && pnpm build -2. ~/.dsh/profiles/web/package.json 的 dependencies 写 "dsh-better-sidebar": "link:<克隆目录绝对路径>" -3. ~/.dsh/profiles/web/cordis.patch.yml 追加挂载行(这一行的 config 就是本插件的设置表单,不写则全用 schema 默认值): - - insert: - - id: better-sidebar - name: 'dsh-better-sidebar' - config: - listLimit: 1000 -4. 在 ~/.dsh/profiles/web 执行 pnpm install -5. 硬刷新浏览器(Cmd/Ctrl+Shift+R);client 改动热加载,host 半改动才需重启 -``` - -更新:`git pull && pnpm install && pnpm build` → 硬刷新。切回 npm 通道时把依赖改回版本号(当前线 `^0.26.0`)再 `pnpm install`。 - ---- - -## 📦 通过 plugin-registry 安装(与 npm 通道二选一) - -前置:DSH 已集成 [plugin-registry](https://github.com/dsh-external/plugin-registry)(`dsh registry` 可用)。**同时启用两个通道会双挂载**(Node 半挂两次、页面两个侧边栏)。 - -```sh -git clone https://github.com/omdsh-dev/DSH-better-sidebar.git && cd DSH-better-sidebar -pnpm install && pnpm build -node scripts/package-registry.mjs # 组装 registry/ 暂存(含清单 + 产物 + README,不入库) -dsh registry install ./registry # 安装(默认禁用) -dsh registry enable dsh-external/dsh-better-sidebar -``` - -更新:`git pull && pnpm install && pnpm build` → `node scripts/package-registry.mjs` → `dsh registry uninstall/install/enable`。切换通道前先移除另一通道的挂载。 - diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index e46ae029..cd421273 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -583,20 +583,30 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async // `path:lines` — with no fenced body anywhere in the draft. This is the // whole point of the chip path: a host that ignores the reference-insert // event degrades to plain text and fails right here. - const previewLine = pane.getByText('tail text') - await previewLine.click({ clickCount: 3 }) // triple-click selects the line + const previewLine = pane.locator('p', { hasText: 'tail text' }).first() + // A real drag selects the text and fires mouseup with the selection still + // live; a synthetic triple-click can clear it before mouseup reaches the + // preview container's handler. + const lineBox = await previewLine.boundingBox() + expect(lineBox, 'the preview line must have a measurable box').not.toBeNull() + await page.mouse.move(lineBox!.x + 1, lineBox!.y + lineBox!.height / 2) + await page.mouse.down() + await page.mouse.move(lineBox!.x + lineBox!.width - 1, lineBox!.y + lineBox!.height / 2, { steps: 8 }) + await page.mouse.up() const addToChat = page.locator('button', { hasText: /添加到对话|Add to conversation/ }).first() await expect(addToChat, 'selecting preview text must raise the add-to-conversation button') .toBeVisible({ timeout: 10_000 }) await addToChat.click() - const composer = page.getByRole('textbox', { name: /^(Describe what you want to build|描述你想要构建)/ }) - const chip = composer.locator('[data-lexical-decorator], [class*="reference"], [class*="chip"]').first() + // The chip is a sibling decorator inside the composer's editable, not a + // descendant of the role=textbox node — scope the search to the composer + // card instead. + const chip = page.locator(`[data-lexical-decorator], [class*="reference"]`) + .filter({ hasText: `${SEEDED_MD_FILE}:` }) + .first() await expect(chip, 'the selection must land in the composer as a reference chip') .toBeVisible({ timeout: 10_000 }) - await expect(chip, 'the chip label must name the file and its line span') - .toContainText(`${SEEDED_MD_FILE}:`, { timeout: 10_000 }) - const draftText = await composer.innerText() - expect(draftText, 'the draft must not carry the quoted body the chip replaced') + const composerText = await page.locator('[contenteditable="true"]').first().innerText() + expect(composerText, 'the draft must not carry the quoted body the chip replaced') .not.toContain('```') await assertNoCrash() From b3b316b457245ccd10a83cc4a3869b4cc49bb905 Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sat, 24 Oct 2026 20:29:53 +0800 Subject: [PATCH 05/10] =?UTF-8?q?refactor(editor):=20=E6=B0=94=E6=B3=A1?= =?UTF-8?q?=E6=8F=92=E5=85=A5=E7=9B=B4=E8=BF=9E=E5=AE=BF=E4=B8=BB=20facade?= =?UTF-8?q?=EF=BC=8C=E5=85=B1=E7=94=A8=E4=B8=80=E4=BB=BD=E5=88=86=E9=9A=94?= =?UTF-8?q?=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 宿主 SessionInput 上本来就有带返回值的 insertReference(native @ 选择器 的监听器就是转调它),之前绕道 emit 事件是多余的一层:手抄了相位白名单、 还得靠前后 draftRev 比对推断成败。改为直接调用后,这两样都交回宿主。 顺带收拢三处重复: - 左侧分隔空格规则原本 spliceInsert 与气泡分支各写一遍,抽成 leadFor; 气泡分支不再算完整条草稿再丢弃。 - 「先试气泡、失败退化纯文本」的策略在 TextEditor 与 explorer 按钮各写 一遍,收进 insertReferenceOrText。 - 测试里两份几乎相同的 composer 假件合并成一个 composerCtx。 无行为变化:气泡仍只在宿主支持时插入,其余情况照旧退化纯文本。 --- src/client/TextEditor.tsx | 8 +- src/client/conversation-draft.ts | 170 +++++++++++++++---------------- src/client/selection-payload.ts | 5 +- src/client/selection-popup.ts | 3 +- src/context-types.ts | 30 +++++- 5 files changed, 113 insertions(+), 103 deletions(-) diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index 9d4e619b..95e7240d 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -38,7 +38,7 @@ import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts' import { cmSearchExtensions, CmSearchPhrases } from './cm-search.ts' import { isDarkScheme, subscribeColorScheme } from './theme.ts' import { SandboxStatusBar } from './SandboxStatusBar.tsx' -import { appendToDraft, insertDraftReference, type DraftReference } from './conversation-draft.ts' +import { insertReferenceOrText, type DraftReference } from './conversation-draft.ts' import { useSelectionPopup } from './selection-popup.ts' import { buildSelectionInsert, linesOfSelection } from './selection-payload.ts' import { analyzeMarkdownHtml } from './markdown-html.ts' @@ -221,12 +221,8 @@ export function TextEditor(props: FileViewerProps) { * leaving the viewport) — see selection-popup.ts. */ const selectionPopup = useSelectionPopup({ - // The chip is the whole point of this surface: the composer shows one - // compact `path:lines` reference while the model still receives the full - // quoted body. A host without the chip channel falls back to plain text. onCommit: (insert) => { - if (insertDraftReference(ctx, scope.sessionId, insert)) return - appendToDraft(ctx, scope.sessionId, insert.text) + insertReferenceOrText(ctx, scope.sessionId, insert) }, // The surface that must stay on screen: the markdown preview container // in preview mode, the CodeMirror host otherwise. diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index 34e7a475..80baf512 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -5,20 +5,19 @@ * through `ctx.get` (the inject-free read the app's own plugins use); a * missing service or scope degrades to a logged no-op, never a crash. * - * File references additionally use DSH's own structured insert event - * (`slash/input-insert-reference`, see `insertFileReference`) instead of - * plain draft text: the native `@file` picker emits this event, and the - * conversation input machine mints one occurrence whose chip covers the - * whole reference. Plain text `@folder/file.ts` only ever gets DSH's - * folder-ref decoration (`@folder/`) — the file name stays undecorated — so - * plain append is the fallback, not the primary path, for files. + * Structured references (file chips, selection chips, and any append onto a + * draft that already carries chips) go through the host's span channels + * instead of plain draft text: `setDraft` rebuilds the document from a string + * and flattens every chip. A reference chip mints through + * `SidebarSessionInput.insertReference` (what the native `@` picker + * calls); plain-text insertion onto a chipped draft has no facade method and + * emits `slash/input-insert-text` directly. Plain `setDraft` is the fallback + * for chipless drafts only. * - * Insert position (fixes upstream issue #425): the draft store only exposes - * the whole string (`getSnapshot().draft` + `setDraft(text)`) — there is no - * caret API on the conversation service. The composer's `