merge #1052: feat(editor): 「添加到对话」改用引用 chip,正文只在发送时展开

# Conflicts:
#	src/client/conversation-draft.ts
#	src/context-types.ts
#	tests/conversation-draft.spec.ts
#	tests/reference-in-chat.spec.ts
#	tests/sidebar-workspace-reference.spec.tsx
This commit is contained in:
Menghuan1918 committed 2026-10-26 15:03:28 +08:00
commit 25fd296f99
12 files changed
+871 -780

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
# 选区引用改气泡:把「添加到对话」从铺开正文改成 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` | 草稿串里占位的那段文本 |
所以「显示短、发送长」本来就是宿主支持的能力,插件只需按这个形状发插入请求。
插入走宿主 facade 上的 `SessionInput.insertReference(ref, span)`——native `@` 选择器的监听器就是转调它,相位与 revision 守卫都在宿主里。宿主 `SessionInput` 上没有纯文本方法(`insertText` 在 InputBar 私有的 `InputActions` 上),所以「往已有气泡的草稿追加纯文本」只能发 `slash/input-insert-text` 事件。
## 3. 关键坑:两套坐标系
宿主对输入框维护两个投影:
| 投影 | 一个气泡占多长 | 谁在用 |
|---|---|---|
| clipboard(`InputState.draft`、`occurrences`) | 整个 `clipboardText` | 插件:读草稿串、算位置 |
| detect(`detectText`) | **1 个字符** `U+FFFC` | 宿主:所有插入事件的 `span` |
草稿为空时两套坐标重合,第一次插入成功;草稿里一旦有气泡,从草稿偏移直接算出的 `span` 必然越界,宿主拒绝(`applied = false`),**第二次插入静默失败**。
修复:`foldClipboardOffset` 按 `occurrences` 把草稿偏移折到 detect 偏移。唯一有意的偏离——偏移正好落在气泡**起点**时,返回气泡**之前**的位置(宿主自己的同名函数会把它读成「在气泡内部」而返回尾边)。
**命令气泡是第二个坑**:`/goal ` 这类命令 chip 在 detect 投影里同样只占 1 个字符,但它**不在** `occurrences` 里(宿主只收 `ReferenceChipNode`)。所以折叠前要先按 `claim.token` 把命令前缀摘掉,折完再加回 1。`appendOffset` 做这件事。
## 4. 改动
| 文件 | 变更 |
|---|---|
| `src/client/conversation-draft.ts` | 新增 `foldClipboardOffset`、`appendOffset`、`insertDraftReference`、`DraftReference`;`appendToDraft` 在草稿有气泡或处于 `claimed` 时改走 `slash/input-insert-text` |
| `src/client/selection-payload.ts` | `buildSelectionInsert` 返回 `{ label, text }`(原返回单个字符串) |
| `src/client/selection-popup.ts` | 三个导出接口与 hook 泛型化,默认 `T = string`,字符串调用方零改动 |
| `src/client/TextEditor.tsx` | `useSelectionPopup<DraftReference>`;commit 走 `insertReferenceOrText` |
| `src/context-types.ts` | `SidebarSessionInput` 补 `insertReference`、快照补 `occurrences` / `phase` / `claim` |
**为什么 `appendToDraft` 也要改**:`setDraft` 会 `root.clear()` 重建纯文本文档,把草稿里**每一个**气泡碾平。命令气泡更糟——碾平后 claim 丢失,宿主把 `/goal` 读成普通文字并取消命令。
**为什么气泡插入前要先占一个分隔位**:宿主的 `insertReference` 只在气泡**之后**补空格(`client.js:14758`),之前不补。草稿是 `hello` 时直接插会读成 `hello[chip]`。
**为什么 `clipboardText` 取短形态**:它是草稿串里对外可见的投影(复制、纯文本视图都读它),整段围栏正文放在那里就是这次要消灭的铺满输入框。注意这**不是**为了兼容重挂载——宿主持久化的是 `{text, references}`,气泡能正常恢复。
**为什么选区气泡不传 `appearance`**:宿主把 `appearance: 'file'` 的气泡标记成可点开,点击会把 `ref` 当路径交给文件打开器。选区气泡的 `ref` 是围栏正文,不是路径。
## 5. 验证
- `pnpm typecheck` / `pnpm lint` / `pnpm build` 通过。
- `pnpm test`:本机 4 例符号链接 `EPERM` 失败(Windows 权限差异,已在干净 `dev` 上复现同样 4 例),其余全绿。
- 本改动相关:`tests/conversation-draft.spec.ts` 32 passed、`tests/selection-payload.spec.ts` 16 passed、`tests/selection-popup.spec.tsx` 8 passed。
- 真机 mount lane:在 markdown 预览里选中一行、点提交按钮,断言 composer 里出现 `diagram.md:` 气泡、草稿不含三反引号围栏、气泡不与前一个词粘连、且气泡不带 `openable` 标记。
## 6. 已知边界
- 气泡的 `clipboardText` 取 `label`(文件引用另取 `@path`),`ref` 存发送用的完整正文,宿主提交前 `trim`。
- 插入一律追加在文档末尾:宿主 composer 是 contenteditable,这个面上没有光标 API。
- 冻结期(`adjudicating` / `submitting`)直接拒绝,不回退——回退会绕过宿主的相位守卫。
+5 -3
View File
@@ -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 { insertReferenceOrText, type PendingReference } from './conversation-draft.ts'
import { useSelectionPopup } from './selection-popup.ts'
import { buildSelectionInsert, linesOfSelection } from './selection-payload.ts'
import { analyzeMarkdownHtml } from './markdown-html.ts'
@@ -247,8 +247,10 @@ 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<PendingReference>({
onCommit: (insert) => {
insertReferenceOrText(ctx, scope.sessionId, insert)
},
// 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),
+282 -256
View File
@@ -5,200 +5,241 @@
* 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.
*
* **Inserts never go through `setDraft`.** `setDraft(text)` is DSH's
* whole-draft replacement: its documented contract is "replace the whole
* draft with plain text, **removing inline reference chips**"
* (`SessionInput.setDraft` in `@deepseek-ai/dsh-client-ui-conversation` — it
* clears the editor root and re-appends the string), so every chip already in
* the draft degrades to its clipboard text (`@dir/file.ts`) and loses its
* reference identity; DSH's plain-text scan then decorates only the folder
* prefix and the mention reads as two pieces. That was this module's own bug:
* one folder insert (or one file insert's fallback) flattened every earlier
* `@` pick. Both kinds now ride DSH's scoped composer events, which mutate the
* live document instead:
* 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.
*
* - `slash/input-insert-reference` — one chip (`clipboardText` = the mention),
* the exact event the native `@` picker emits (see `insertFileReference`);
* - `slash/input-insert-text` — plain text over a span, the event behind the
* host's own folder-drill action; a plain `@dir/` token's chip look is then
* DSH's scan-derived decoration, as designed.
*
* **Spans are detect coordinates.** A `TokenSpan` addresses DSH's detect
* projection, where every chip is exactly one character (U+FFFC), while
* `InputState.draft` is the clipboard projection (chips expanded to mention
* text). Handing the host a clipboard offset where it expects a detect offset
* is silently rejected (`selectSpan` refuses an end past the detect length),
* which is how a draft holding a single chip made every later insert fail and
* fall back to the destructive path. {@link clipboardToDetect} /
* {@link detectLength} fold one projection into the other from
* `InputState.occurrences`.
*
* Insert position (upstream issue #425): the draft store exposes no caret API,
* so the composer's own DOM is still probed ({@link probeComposerCaret}). The
* 0.1.7+ composer is a Lexical contenteditable rather than a `<textarea>`, so
* that probe answers null there and the insert appends at the draft end — and
* DSH puts the caret after whatever it inserted, so no DOM caret restoration
* of our own is needed (or wanted).
* Everything appends at the document end. The host composer is a Lexical
* contenteditable and this face publishes no caret, so a mid-draft insert
* would have to guess a position — see {@link appendOffset} for the one
* coordinate it does derive.
*/
import type { Context, SidebarConversation, SidebarSessionInput } from '../context-types.ts'
import type {
Context,
SidebarConversation,
SidebarReferenceInsert,
SidebarSessionInput,
SidebarSessionOccurrence,
} from '../context-types.ts'
import { baseName, workspaceRelativePath } from './paths.ts'
/** A resolved composer caret/selection in draft coordinates. */
export interface DraftCaret {
start: number
end: number
}
/**
* One reference occurrence in the clipboard projection
* (`InputState.occurrences`): where a chip's mention text sits in the draft
* string. Occurrences arrive ordered and non-overlapping.
*/
export interface DraftOccurrence {
readonly offset: number
readonly length: number
}
/** One insertion resolved against the clipboard draft, before projection folding. */
interface PlannedInsert {
/** Text handed to the host; a range insert replaces the span with exactly this. */
text: string
/** Clipboard-coordinate range the insert covers (collapsed for a plain caret). */
start: number
end: number
}
/**
* The detect-projection length of a clipboard draft: every chip collapses to
* one character, so each occurrence contributes `length - 1` fewer characters.
* This is the offset space every `TokenSpan` is expressed in.
*/
export function detectLength(draft: string, occurrences: readonly DraftOccurrence[]): number {
let length = draft.length
for (const occurrence of occurrences) length -= occurrence.length - 1
return length
}
/**
* Fold one clipboard-projection offset into detect coordinates. An offset
* strictly inside a chip's expansion cannot be addressed by the detect
* projection at all (the chip is atomic there), so it snaps to the position
* just before that chip — a plain caret never lands there, only a selection
* spanning chip text could.
*/
export function clipboardToDetect(occurrences: readonly DraftOccurrence[], offset: number): number {
let detect = offset
for (const occurrence of occurrences) {
if (offset <= occurrence.offset) break
const end = occurrence.offset + occurrence.length
if (offset < end) {
detect -= offset - occurrence.offset
break
}
detect -= occurrence.length - 1
}
return detect
}
/**
* Resolve where `text` lands and what exactly the host receives, with the
* whitespace-aware joins of {@link insertAtCaret}: one separating space per
* side, never doubled against neighbouring whitespace or the string edges.
* `caret === null` (position unknown) appends at the end, and a
* whitespace-only draft is replaced rather than indented — both the pre-fix
* behavior.
*/
function planInsert(draft: string, text: string, caret: DraftCaret | null): PlannedInsert {
if (caret === null) {
return draft.trim() === ''
? { text, start: 0, end: draft.length }
: { text: `${/\s$/.test(draft) ? '' : ' '}${text}`, start: draft.length, end: draft.length }
}
const prefix = draft.slice(0, caret.start)
const suffix = draft.slice(caret.end)
if (prefix === '' && suffix === '') return { text, start: caret.start, end: caret.end }
const left = prefix === '' || /\s$/.test(prefix) ? '' : ' '
const right = suffix === '' || /^\s/.test(suffix) || /\s$/.test(text) ? '' : ' '
return { text: `${left}${text}${right}`, start: caret.start, end: caret.end }
}
/**
* The spliced draft string (see {@link planInsert}); pure string math —
* unit-tested directly.
*/
export function insertAtCaret(draft: string, text: string, caret: DraftCaret | null): string {
const plan = planInsert(draft, text, caret)
return `${draft.slice(0, plan.start)}${plan.text}${draft.slice(plan.end)}`
}
/**
* Locate the composer `<textarea>` in the conversation column: prefer the
* `data-phase`-tagged textarea (the composer's marker), falling back to any
* textarea in the column, then to a bare data-phase textarea (older host
* layouts without the column attribute). Null in jsdom-less hosts.
*/
function findComposerTextarea(): HTMLTextAreaElement | null {
if (typeof document === 'undefined') return null
const column = document.querySelector('#root [data-slot="conversation"]')
const find = (scope: ParentNode): HTMLTextAreaElement | null =>
scope.querySelector('textarea[data-phase]') ?? scope.querySelector('textarea')
return column !== null
? find(column)
: document.querySelector<HTMLTextAreaElement>('textarea[data-phase]')
}
/**
* Resolve the composer's live caret from its DOM `<textarea>`. The draft
* store has no caret API, so the sidebar reads the composed input's selection
* directly; the value-sync check (`el.value === draft`) discards stale or
* wrong-composer reads — a caret must never be applied against a draft it
* was not measured on.
* 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.
*
* Returns null when the composer is missing, disabled/read-only, out of
* sync with the store draft, or has no measurable selection (jsdom/odd
* hosts report null selectionStart/End).
* Named `Pending*` to keep clear of the host's own `DraftReference`, which is
* the opposite thing: a chip ALREADY in the draft, carrying its offset and
* length.
*/
export function probeComposerCaret(draft: string): DraftCaret | null {
const el = findComposerTextarea()
if (el === null || el.disabled || el.readOnly) return null
if (el.value !== draft) return null
let start = el.selectionStart
let end = el.selectionEnd
if (typeof start !== 'number' || typeof end !== 'number') return null
if (!Number.isFinite(start) || !Number.isFinite(end)) return null
start = Math.max(0, Math.min(start, draft.length))
end = Math.max(start, Math.min(end, draft.length))
return { start, end }
export interface PendingReference {
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.
* This is the text other draft consumers (copy, plain projections) see, so
* it stays short — the full payload rides in `text` and is only expanded
* on send.
*/
clipboardText?: string
/**
* Chip icon family. Omit for a reference whose `text` is not a path: the
* host marks `'file'` chips openable, and a click would hand the raw text
* (a fenced block, for a selection) to the file opener.
*/
appearance?: 'file' | 'folder' | 'session'
}
/**
* Emit one scoped composer event on the session scope. The session-scope
* Context's typed `emit` is keyed to DSH's closed event map; these internal
* composer events are deliberately string-loose at runtime.
* The separating space an append needs on its left — one space, but never
* doubled against existing whitespace. Both the string append and the span
* channel (which does no splice math of its own) obey this single rule. A
* blank draft takes no separator: it is replaced outright.
*/
function emitComposerEvent(actx: object, name: string, payload: unknown): void {
;(actx as { emit(name: string, payload: unknown): void }).emit(name, payload)
function leadFor(draft: string): string {
if (draft.trim() === '') return ''
return /\s$/.test(draft) ? '' : ' '
}
/** The snapshot fields an insert needs: the draft, its revision, and the chips' ranges. */
function readDraftState(input: SidebarSessionInput): {
draft: string
draftRev: number
occurrences: readonly DraftOccurrence[]
} | undefined {
const state = input.state.getSnapshot()
if (state.draftRev === undefined) return undefined
return { draft: state.draft, draftRev: state.draftRev, occurrences: state.occurrences ?? [] }
/** `draft` with `text` appended behind one separating space when needed. */
export function appendText(draft: string, text: string): string {
return `${draft}${leadFor(draft)}${text}`
}
/**
* Insert `text` into the session's composer draft as plain text — the host's
* own folder-drill path (`slash/input-insert-text`), at the composer's live
* caret when one can be resolved and at the end otherwise. Returns false — and
* logs — when the conversation service or the session scope is unavailable, or
* when the draft carries no revision to address; an event no listener handled
* also reports false and leaves the draft untouched (forcing the text in by
* rewriting the whole draft is what used to destroy chips).
* 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 occurrence.offset - shrink + 1
}
break
}
return target - shrink
}
/**
* The detect-projection offset that appends at the document end, or
* `undefined` when it cannot be derived.
*
* `foldClipboardOffset` alone is not enough: a command chip (`/goal `, present
* while `phase === 'claimed'`) collapses to one detect character but never
* appears in `occurrences` — the host only collects reference chips. The chip
* covers exactly `claim.token`, a prefix of the draft, so its own characters
* fold away and one placeholder takes their place.
*/
function appendOffset(snapshot: ReturnType<SidebarSessionInput['state']['getSnapshot']>): number | undefined {
const { draft, claim } = snapshot
const occurrences = snapshot.occurrences ?? []
const token = snapshot.phase === 'claimed' && claim !== undefined && draft.startsWith(claim.token)
? claim.token
: ''
if (token === '') return foldClipboardOffset(draft, occurrences, draft.length)
// Fold the arguments behind the token, then add the command chip's one
// detect character in front.
const rest = draft.slice(token.length)
const offsetInRest = occurrences
.filter(occurrence => occurrence.offset >= token.length)
.map(occurrence => ({ offset: occurrence.offset - token.length, length: occurrence.length }))
return 1 + foldClipboardOffset(rest, offsetInRest, rest.length)
}
/**
* Mint one reference chip through the host's own `insertReference` — the
* same facade method the native `@` picker's event listener calls, so the
* composer shows a compact chip while the model receives `reference.text`.
* The host runs its own admission-phase and revision guards and reports
* whether the edit applied.
*
* The chip's `clipboardText` is the compact `label`, not the full payload —
* see {@link PendingReference.clipboardText}.
*
* 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: PendingReference,
): boolean {
let before: number | undefined
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 snapshot = input.state.getSnapshot()
if (input.insertReference === undefined || snapshot.draftRev === undefined) return false
if (snapshot.phase === 'adjudicating' || snapshot.phase === 'submitting') return false
before = snapshot.draftRev
// 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 = appendOffset(snapshot)
if (at === undefined) return false
// The host's insertReference adds a space AFTER the chip but never before
// it (client.js:14758), so a chip appended to `hello` would read
// `hello[chip]`. Reserve the separator first through the same span
// channel — a stray trailing space is harmless if the chip then fails.
let rev = snapshot.draftRev
let start = at
if (leadFor(snapshot.draft) !== '') {
const actxEmit = actx as unknown as { emit(name: string, payload: unknown): void }
actxEmit.emit('slash/input-insert-text', {
text: ' ',
span: { draftRev: rev, start: at, end: at },
})
const afterSpace = input.state.getSnapshot()
if (afterSpace.draftRev === rev) return false
rev = afterSpace.draftRev ?? rev
start = at + 1
}
const chip: SidebarReferenceInsert = {
source: 'reference',
ref: reference.text,
label: reference.label,
// A selection chip's `ref` is a fenced block, not a path: leaving
// `appearance` unset keeps the host from marking it openable (a click
// would otherwise feed that block to the file opener).
...reference.appearance === undefined ? {} : { appearance: reference.appearance },
clipboardText: reference.clipboardText ?? reference.label,
}
return input.insertReference(chip, { draftRev: rev, start, end: start })
} catch (error) {
// The host may have applied the edit and THEN thrown from its own update
// listeners — reporting false would make the caller insert the same
// reference a second time as plain text. A changed revision means the
// chip is already in the document.
console.warn('[dsh-better-sidebar] reference chip insert failed:', error)
return revisionChanged(ctx, sessionId, before)
}
}
/**
* Whether the session's draft revision moved past `revision` — the only
* trustworthy success signal after an exception swallowed the host's answer.
* A missing service or snapshot counts as "no evidence of success".
*/
function revisionChanged(ctx: Context, sessionId: string, revision?: number): boolean {
try {
const actx = ctx.sessions.scope(sessionId)
if (actx === undefined) return false
const conversation = ctx.get('conversation') as SidebarConversation | undefined
const input = conversation?.input.for(actx)
const now = input?.state.getSnapshot().draftRev
if (now === undefined || revision === undefined) return false
return now !== revision
} catch {
return false
}
}
/**
* Append `text` to the session's composer draft. Returns false — and logs —
* when the conversation service or the session scope is unavailable.
*
* The host composer is a Lexical contenteditable with no caret API on this
* face, so this appends at the end; a mid-draft insert would need the caret
* the host does not publish here.
*/
export function appendToDraft(ctx: Context, sessionId: string, text: string): boolean {
try {
@@ -213,24 +254,38 @@ export function appendToDraft(ctx: Context, sessionId: string, text: string): bo
return false
}
const input = conversation.input.for(actx)
const before = readDraftState(input)
if (before === undefined) {
console.warn('[dsh-better-sidebar] draft insert skipped: composer revision unavailable')
return false
}
const plan = planInsert(before.draft, text, probeComposerCaret(before.draft))
emitComposerEvent(actx, 'slash/input-insert-text', {
text: plan.text,
span: {
draftRev: before.draftRev,
start: clipboardToDetect(before.occurrences, plan.start),
end: clipboardToDetect(before.occurrences, plan.end),
},
})
if (input.state.getSnapshot().draftRev === before.draftRev) {
console.warn('[dsh-better-sidebar] draft insert skipped: the composer did not apply the insert event')
return false
const snapshot = input.state.getSnapshot()
const draft = snapshot.draft
const occurrences = snapshot.occurrences ?? []
// A command chip (`/goal`) is not a reference occurrence, but `setDraft`
// flattens it just the same — and flattening it also drops the claim, so
// the host re-reads the draft as plain text and cancels the command. Both
// chip kinds take the span path.
const hasChips = occurrences.length > 0 || snapshot.phase === 'claimed'
if (hasChips) {
// `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 host's
// `SessionInput` has no plain-text facade method (`insertText` lives on
// the InputBar-private `InputActions`), so this event is the only
// channel that preserves chips.
const at = appendOffset(snapshot)
if (snapshot.draftRev === undefined || at === 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
}
// The session-scope Context's typed `emit` is keyed to DSH's closed
// event map; this internal composer event is string-loose at runtime.
const actxEmit = actx as unknown as { emit(name: string, payload: unknown): void }
actxEmit.emit('slash/input-insert-text', {
text: `${leadFor(draft)}${text}`,
span: { draftRev: snapshot.draftRev, start: at, end: at },
})
return input.state.getSnapshot().draftRev !== snapshot.draftRev
}
input.setDraft(appendText(draft, text))
return true
} catch (error) {
console.warn('[dsh-better-sidebar] draft insert failed:', error)
@@ -238,6 +293,20 @@ export function appendToDraft(ctx: Context, sessionId: string, text: string): bo
}
}
/**
* Insert one reference as a chip, degrading to its plain-text form when the
* host has no chip channel or refuses the insert. This is the ONE place the
* fallback policy lives: the explorer's `@` button and the viewer selection
* popup both come through here.
*/
export function insertReferenceOrText(
ctx: Context,
sessionId: string,
reference: PendingReference,
): boolean {
return insertDraftReference(ctx, sessionId, reference) || appendToDraft(ctx, sessionId, reference.text)
}
/**
* The DSH `@` spelling for one relative path, mirroring the host grammar
* (`formatFileMention` in `@deepseek-ai/dsh-file-reference`): plain when
@@ -297,72 +366,29 @@ export function insertWorkspaceReference(ctx: Context, sessionId: string, path:
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) {
if (isDir) {
const mention = directoryMention(relative)
if (mention === undefined) {
console.warn('[dsh-better-sidebar] reference insert skipped: path cannot be represented as a mention')
return false
}
// 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, `${mention} `)
}
const file = mentionFor(relative, 'file')
if (file === 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
// Plain text is the fallback, not the primary path, for files (the chip
// serializes to the whole path; a plain `@dir/file.ts` only decorates its
// folder prefix). The host adds space after a file chip, but not before
// it, so complete directory inserts need their own separator for the next
// @ click. Either way this is a span insert — an existing chip survives it.
return appendToDraft(ctx, sessionId, isDir ? `${mention} ` : mention)
return insertReferenceOrText(ctx, sessionId, {
label: file.label,
text: file.mention,
clipboardText: file.mention,
appearance: 'file',
})
} 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.
*
* The chip lands at the composer's resolved caret end, or at the draft end
* when no caret is resolvable — the host adds the separating space *after* a
* chip and, like its own picker, none before it, so a programmatic chip sits
* flush against whatever preceded it.
*
* Directories keep the sidebar's plain-text completion behavior (`@dir/`)
* through `insertWorkspaceReference`. The 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')
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 = readDraftState(input)
if (before === undefined) return false
const caret = probeComposerCaret(before.draft)
const at = clipboardToDetect(before.occurrences, caret === null ? before.draft.length : caret.end)
emitComposerEvent(actx, 'slash/input-insert-reference', {
reference: {
source: 'reference',
ref: reference.mention,
label: reference.label,
appearance: 'file',
clipboardText: reference.mention,
},
span: {
draftRev: before.draftRev,
start: at,
end: at,
},
})
if (input.state.getSnapshot().draftRev === before.draftRev) {
console.warn('[dsh-better-sidebar] file-reference insert skipped: the composer did not apply the insert event')
return false
}
return true
} catch (error) {
console.warn('[dsh-better-sidebar] file-reference insert failed:', error)
return false
}
}
+9 -6
View File
@@ -17,8 +17,11 @@
* 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 (see {@link PendingReference}).
*/
import { relativeTo } from './paths.ts'
import type { PendingReference } from './conversation-draft.ts'
/** Max inserted selection length (UTF-16 code units, i.e. JS `.length`). */
export const SELECTION_LIMIT = 500
@@ -41,19 +44,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 {
): PendingReference {
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. */
+16 -13
View File
@@ -29,16 +29,19 @@
*/
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 belongs to the caller; the hook only carries it through.
*/
export interface SelectionPopup<T> {
insert: T
left: number
top: number
}
export interface SelectionPopupOptions {
export interface SelectionPopupOptions<T> {
/** 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 +50,20 @@ export interface SelectionPopupOptions {
getSurface(): HTMLElement | null
}
export interface SelectionPopupControls {
export interface SelectionPopupControls<T> {
/** The current popup (null = hidden). */
popup: SelectionPopup | null
popup: SelectionPopup<T> | null
/** Attach to the portaled button element. */
buttonRef: RefObject<HTMLButtonElement>
/** 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<T>(options: SelectionPopupOptions<T>): SelectionPopupControls<T> {
// 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 +71,16 @@ export function useSelectionPopup(options: SelectionPopupOptions): SelectionPopu
onCommitRef.current = options.onCommit
getSurfaceRef.current = options.getSurface
const [popup, setPopup] = useState<SelectionPopup | null>(null)
const [popup, setPopup] = useState<SelectionPopup<T> | null>(null)
/** Live mirror for click/event-time reads (no re-render race). */
const popupRef = useRef<SelectionPopup | null>(null)
const popupRef = useRef<SelectionPopup<T> | null>(null)
/** The portaled button itself (for the outside-click guard). */
const buttonRef = useRef<HTMLButtonElement>(null)
/** The surface visibility observer (created lazily on open). */
const observerRef = useRef<IntersectionObserver | null>(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<T> = {
insert,
left: Math.min(Math.max(left, 80), window.innerWidth - 80),
top,
+58 -11
View File
@@ -660,28 +660,75 @@ export interface SidebarLocaleService {
register(ns: string, locale: string, dict: Record<string, string>): () => 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
}
/** One structured reference chip's insertion payload (mirror of the host's
* `ReferenceInsert`). */
export interface SidebarReferenceInsert {
/** Trigger source id; `'reference'` for a programmatic insert. */
source: string
/** What the model receives on send — the chip's full serialized form. */
ref: string
/** What the composer shows in place of `ref`. */
label: string
/** Chip icon family; the host picks its own default when omitted. */
appearance?: 'session' | 'file' | 'folder'
/** The text this chip occupies in the draft projection. */
clipboardText: string
}
/** 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 —
* and `occurrences` are the chips' clipboard-coordinate ranges, the only
* way to fold `draft` (the clipboard projection) into the detect projection
* every `TokenSpan` addresses. */
* span-CAS revision — required to mint a structured reference chip. */
state: {
getSnapshot(): {
draft: string
draftRev?: number
occurrences?: readonly { offset: number; length: 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. `claimed` means a command chip (`/goal`) heads the
* draft; `adjudicating`/`submitting` freeze every write. A command chip
* is NOT in `occurrences` (the host only collects reference chips), yet
* it still collapses to one character in the detect projection — so a
* span derived from `draft` is wrong whenever `phase === 'claimed'`.
*/
phase?: 'plain' | 'adjudicating' | 'claimed' | 'submitting'
/**
* The claimed command's spelling with its trailing separator (`/goal `),
* present exactly while `phase` is `claimed`/`submitting`. The host
* treats it as one chip covering this exact draft prefix.
*/
claim?: { readonly token: string }
}
}
/**
* Replace the whole draft text. **Not an insert API**: it removes inline
* reference chips (the draft comes back as plain text), so both insertion
* paths emit scoped composer events instead — see
* `client/conversation-draft.ts`. If a future host changes that semantic
* (chip-preserving replacement, or a public insert/`captureInsertion` face),
* revisit this note together with both paths in that module.
* Replace the trigger span with one reference chip (span-CAS'd). Absent on
* hosts without the chip channel.
*/
insertReference?(
ref: SidebarReferenceInsert,
span: { start: number; end: number; draftRev: number },
): boolean
/** Replace the draft text — flattens every existing chip into its text. */
setDraft(text: string): void
}
+301 -402
View File
@@ -1,444 +1,343 @@
/**
* conversation-draft spec — composer insertion without whole-draft rewrites.
* conversation-draft spec — the composer draft insert path behind the
* explorer's @-reference button and the viewer selection popup.
*
* `insertAtCaret` is pure string math (splice with whitespace-aware joins);
* `probeComposerCaret` reads the live composer `<textarea>` selection out of
* the DOM, guarded by a value-sync check so a stale or wrong-composer caret is
* never applied (the 0.1.7+ composer is a contenteditable, so it answers null
* there and inserts append at the draft end).
* `foldClipboardOffset` folds a draft-projection offset into the editor's
* detect projection; `insertDraftReference` mints a chip through the host
* facade; `appendToDraft` appends plain text, taking the span channel when
* the draft already carries chips.
*
* Both insert paths ride DSH's scoped composer events, whose spans live in
* **detect** coordinates (one chip = one character), never `setDraft`: the
* host's whole-draft replacement is documented to remove inline reference
* chips, so it would flatten every earlier `@` pick into plain text. The fake
* composer below models both the projection folding and that refusal, so a
* reintroduced `setDraft` insert (or a clipboard-coordinate span) fails here.
* There is no DOM here on purpose: the host composer is a Lexical
* contenteditable and publishes no caret on the face this plugin reaches, so
* every insert appends at the document end.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Context } from '../src/context-types.ts'
import {
appendText,
appendToDraft,
clipboardToDetect,
detectLength,
insertAtCaret,
insertFileReference,
probeComposerCaret,
type DraftOccurrence,
foldClipboardOffset,
insertDraftReference,
} from '../src/client/conversation-draft.ts'
/**
* Mount a fake composer textarea inside the DSH conversation column
* (`#root [data-slot="conversation"] textarea[data-phase]`).
*/
function mountComposer(draft: string, selectionStart: number, selectionEnd: number): HTMLTextAreaElement {
const root = document.createElement('div')
root.id = 'root'
const column = document.createElement('div')
column.setAttribute('data-slot', 'conversation')
const textarea = document.createElement('textarea')
textarea.setAttribute('data-phase', 'plain')
textarea.value = draft
textarea.setSelectionRange(selectionStart, selectionEnd)
column.append(textarea)
root.append(column)
document.body.append(root)
return textarea
}
afterEach(() => {
document.body.innerHTML = ''
vi.restoreAllMocks()
})
describe('probeComposerCaret', () => {
it('returns the textarea selection when the DOM is in sync with the draft', () => {
mountComposer('hello world', 5, 5)
expect(probeComposerCaret('hello world')).toEqual({ start: 5, end: 5 })
describe('appendText', () => {
it('appends behind one separating space', () => {
expect(appendText('hello', 'X')).toBe('hello X')
expect(appendText('hello\n', 'X')).toBe('hello\nX')
})
it('reports a live selection range, not just a collapsed caret', () => {
mountComposer('hello world', 6, 11)
expect(probeComposerCaret('hello world')).toEqual({ start: 6, end: 11 })
})
it('returns null when no composer is mounted', () => {
expect(document.querySelector('textarea')).toBeNull()
expect(probeComposerCaret('anything')).toBeNull()
})
it('returns null when the composer DOM value is out of sync with the store draft', () => {
mountComposer('hello', 0, 0)
expect(probeComposerCaret('hello changed on the server')).toBeNull()
})
it('returns null for a disabled composer', () => {
const input = mountComposer('hello', 2, 2)
input.disabled = true
expect(probeComposerCaret('hello')).toBeNull()
})
it('returns null for a read-only composer', () => {
const input = mountComposer('hello', 2, 2)
input.readOnly = true
expect(probeComposerCaret('hello')).toBeNull()
})
it('clamps out-of-range selections into the draft bounds', () => {
const input = mountComposer('hi', 0, 0)
// Direct property writes (jsdom does not enforce bounds like browsers).
input.selectionStart = 5
input.selectionEnd = 9
expect(probeComposerCaret('hi')).toEqual({ start: 2, end: 2 })
it('replaces a blank draft outright', () => {
expect(appendText('', 'X')).toBe('X')
expect(appendText(' ', 'X')).toBe(' X')
})
})
describe('insertAtCaret', () => {
it('appends at the end when the caret is unknown (pre-fix behavior)', () => {
expect(insertAtCaret('', 'X', null)).toBe('X')
expect(insertAtCaret('hello', 'X', null)).toBe('hello X')
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')
})
it('only adds the separating spaces the neighbors actually need', () => {
expect(insertAtCaret('one two', 'CODE', { start: 3, end: 3 })).toBe('one CODE two')
// Doubled gap, caret right after the word: the leading space is added,
// the two after the caret stay untouched (like typing in the gap).
expect(insertAtCaret('one two', 'CODE', { start: 3, end: 3 })).toBe('one CODE two')
// Doubled gap, caret on the second space: neither side needs a new
// space, both originals flank the insertion.
expect(insertAtCaret('one two', 'CODE', { start: 4, end: 4 })).toBe('one CODE two')
expect(insertAtCaret('one two ', 'CODE', { start: 8, end: 8 })).toBe('one two CODE')
})
it('inserts at the start without a leading space', () => {
expect(insertAtCaret('hello', 'CODE', { start: 0, end: 0 })).toBe('CODE hello')
})
it('inserts at the end with a single trailing space', () => {
expect(insertAtCaret('hello', 'CODE', { start: 5, end: 5 })).toBe('hello CODE')
})
it('replaces the live selection', () => {
expect(insertAtCaret('a little tale', 'CODE', { start: 2, end: 8 })).toBe('a CODE tale')
})
it('replaces a selection surrounded by words with single-space joins', () => {
expect(insertAtCaret('abc def ghi', 'CODE', { start: 4, end: 7 })).toBe('abc CODE ghi')
})
it('replaces a selection spanning the whole draft', () => {
expect(insertAtCaret('old', 'CODE', { start: 0, end: 3 })).toBe('CODE')
})
it('handles an empty draft with a resolved caret', () => {
expect(insertAtCaret('', 'CODE', { start: 0, end: 0 })).toBe('CODE')
})
})
describe('clipboard → detect projection folding', () => {
it('counts every chip as one character', () => {
expect(detectLength('', [])).toBe(0)
expect(detectLength('@notes/ENV.md ', [{ offset: 0, length: 13 }])).toBe(2)
expect(detectLength('a @x.md b @y.md', [{ offset: 2, length: 5 }, { offset: 10, length: 5 }])).toBe(7)
})
it('passes offsets through when the draft holds no chip', () => {
expect(clipboardToDetect([], 0)).toBe(0)
expect(clipboardToDetect([], 42)).toBe(42)
})
it('folds offsets around one chip, snapping an inside offset before that chip', () => {
const chip: DraftOccurrence[] = [{ offset: 0, length: 13 }]
expect(clipboardToDetect(chip, 0)).toBe(0)
expect(clipboardToDetect(chip, 5)).toBe(0) // inside the chip: not addressable
expect(clipboardToDetect(chip, 13)).toBe(1)
expect(clipboardToDetect(chip, 14)).toBe(2)
})
it('folds offsets across several chips', () => {
const chips: DraftOccurrence[] = [{ offset: 0, length: 5 }, { offset: 10, length: 4 }]
expect(clipboardToDetect(chips, 0)).toBe(0)
expect(clipboardToDetect(chips, 5)).toBe(1)
expect(clipboardToDetect(chips, 9)).toBe(5)
expect(clipboardToDetect(chips, 10)).toBe(6)
expect(clipboardToDetect(chips, 14)).toBe(7)
})
})
/** One composer event the plugin emitted. */
interface EmittedEvent {
name: string
payload: Record<string, unknown>
}
/**
* A fake session-scope composer modelling the two host behaviours this module
* depends on: (a) `setDraft` replaces the whole draft as plain text and drops
* every chip occurrence, and (b) an insert whose span end is past the *detect*
* length is refused (`selectSpan`'s bounds check), leaving the revision alone.
*/
function fakeComposer(initial: {
draft?: string
draftRev?: number
occurrences?: readonly DraftOccurrence[]
} = {}): {
ctx: Context
events: EmittedEvent[]
setDrafts: string[]
read: () => { draft: string; draftRev: number; occurrences: readonly DraftOccurrence[] }
} {
const events: EmittedEvent[] = []
const setDrafts: string[] = []
let draft = initial.draft ?? ''
let draftRev = initial.draftRev ?? 0
let occurrences: readonly DraftOccurrence[] = initial.occurrences ?? []
/** Fold one detect offset back to clipboard coordinates (the host's document walk). */
const detectToClipboard = (offset: number): number => {
let absorbed = 0
for (const occurrence of occurrences) {
if (occurrence.offset - absorbed >= offset) break
absorbed += occurrence.length - 1
}
return offset + absorbed
}
const apply = (name: string, payload: Record<string, unknown>): void => {
const span = payload.span as { start: number; end: number } | undefined
if (span === undefined) return
if (span.start < 0 || span.start > span.end || span.end > detectLength(draft, occurrences)) return
const start = detectToClipboard(span.start)
const end = detectToClipboard(span.end)
if (name === 'slash/input-insert-reference') {
const reference = payload.reference as { clipboardText: string }
const text = reference.clipboardText
// The host mints the chip plus a separating space; the chip's mention
// becomes one occurrence over the clipboard projection.
draft = `${draft.slice(0, start)}${text} ${draft.slice(end)}`
occurrences = [
...occurrences.filter(occurrence => occurrence.offset < start),
{ offset: start, length: text.length },
...occurrences
.filter(occurrence => occurrence.offset >= end)
.map(occurrence => ({ ...occurrence, offset: occurrence.offset + text.length + 1 })),
].sort((left, right) => left.offset - right.offset)
draftRev += 1
return
}
if (name === 'slash/input-insert-text') {
const text = payload.text as string
// Plain text replaces the range; a chip covered by the range is consumed
// with it, and everything after it shifts.
draft = `${draft.slice(0, start)}${text}${draft.slice(end)}`
const delta = text.length - (end - start)
occurrences = occurrences
.filter(occurrence => occurrence.offset < start || occurrence.offset >= end)
.map(occurrence => (
occurrence.offset >= end ? { ...occurrence, offset: occurrence.offset + delta } : occurrence
))
draftRev += 1
}
}
const input = {
state: {
getSnapshot: (): { draft: string; draftRev: number; occurrences: readonly DraftOccurrence[] } =>
({ draft, draftRev, occurrences }),
},
setDraft: (next: string): void => {
setDrafts.push(next)
draft = next
occurrences = [] // the documented chip-flattening behavior
draftRev += 1
},
}
const scope = {
emit: (name: string, payload: Record<string, unknown>): void => {
if (name !== 'slash/input-insert-reference' && name !== 'slash/input-insert-text') return
events.push({ name, payload })
apply(name, payload)
},
}
const ctx = {
sessions: { scope: (): unknown => scope },
get: (name: string): unknown => (name === 'conversation' ? { input: { for: (): unknown => input } } : undefined),
} as unknown as Context
return { ctx, events, setDrafts, read: () => ({ draft, draftRev, occurrences }) }
}
describe('appendToDraft', () => {
it('inserts through the plain-text event, never through setDraft', () => {
const composer = fakeComposer()
expect(appendToDraft(composer.ctx, 's1', '@docs/ ')).toBe(true)
expect(composer.events.map(event => event.name)).toEqual(['slash/input-insert-text'])
expect(composer.setDrafts).toEqual([])
expect(composer.read().draft).toBe('@docs/ ')
})
it('appends at the end with the whitespace-aware separator when no caret is resolvable', () => {
const composer = fakeComposer({ draft: 'hello' })
appendToDraft(composer.ctx, 's1', '@docs/')
expect(composer.read().draft).toBe('hello @docs/')
appendToDraft(composer.ctx, 's1', '@src/ ')
expect(composer.read().draft).toBe('hello @docs/ @src/ ')
expect(composer.setDrafts).toEqual([])
})
it('replaces a whitespace-only draft instead of indenting it', () => {
const composer = fakeComposer({ draft: ' ' })
appendToDraft(composer.ctx, 's1', '@docs/ ')
expect(composer.read().draft).toBe('@docs/ ')
// The range insert replaces the blanks (the event carries a range, not a caret).
expect(composer.events[0]?.payload.span).toEqual({ draftRev: 0, start: 0, end: 3 })
})
it('inserts at the probed caret when the composer exposes one', () => {
mountComposer('AB', 1, 1)
const composer = fakeComposer({ draft: 'AB' })
appendToDraft(composer.ctx, 's1', 'C')
expect(composer.read().draft).toBe('A C B')
expect(composer.events[0]?.payload.span).toEqual({ draftRev: 0, start: 1, end: 1 })
})
it('keeps an existing chip: the span is folded into detect coordinates', () => {
const composer = fakeComposer({
draft: '@notes/ENV.md ',
draftRev: 3,
occurrences: [{ offset: 0, length: 13 }],
})
expect(appendToDraft(composer.ctx, 's1', '@docs/ ')).toBe(true)
// Detect coordinates: the chip is one character, so the append offset is
// 2 (chip + its trailing space) — not the clipboard length 14.
expect(composer.events[0]?.payload.span).toEqual({ draftRev: 3, start: 2, end: 2 })
expect(composer.read().draft).toBe('@notes/ENV.md @docs/ ')
expect(composer.read().occurrences).toEqual([{ offset: 0, length: 13 }])
expect(composer.setDrafts).toEqual([])
})
it('hands a multi-line payload to the host verbatim and keeps the chip (selection quote)', () => {
const composer = fakeComposer({
draft: '@notes/ENV.md ',
draftRev: 1,
occurrences: [{ offset: 0, length: 13 }],
})
const quote = ['```diagram.md:1-9', '# Diagram', 'tail text', '```'].join('\n')
expect(appendToDraft(composer.ctx, 's1', quote)).toBe(true)
// The draft already ends with whitespace, so the payload arrives untouched:
// no leading separator, every newline intact (the host renders them under
// the composer's `white-space: pre-wrap`).
expect(composer.events[0]?.payload.text).toBe(quote)
expect(composer.read().draft).toBe(`@notes/ENV.md ${quote}`)
expect(composer.read().occurrences).toEqual([{ offset: 0, length: 13 }])
expect(composer.setDrafts).toEqual([])
})
it('reports false — logs, and leaves the draft alone — when no listener handled the event', () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const composer = fakeComposer({ draft: 'hi', draftRev: 2 })
const ctx = {
sessions: { scope: (): unknown => ({ emit: (): void => undefined }) },
get: (name: string): unknown => composer.ctx.get(name),
/** A fake ctx exposing the conversation service face appendToDraft uses. */
function fakeCtx(
getDraft: () => string,
onSet: (next: string) => void,
withConversation = true,
): Context {
const input = {
state: { getSnapshot: (): { draft: string } => ({ draft: getDraft() }) },
setDraft: (next: string): void => { onSet(next) },
}
return {
sessions: { scope: (): unknown => ({}) },
get: (name: string): unknown =>
withConversation && name === 'conversation'
? { input: { for: (): unknown => input } }
: undefined,
} as unknown as Context
expect(appendToDraft(ctx, 's1', 'X')).toBe(false)
expect(composer.read().draft).toBe('hi')
expect(composer.setDrafts).toEqual([])
expect(consoleWarn).toHaveBeenCalledTimes(1)
consoleWarn.mockRestore()
}
it('appends with a separating space', () => {
const calls: string[] = []
const ctx = fakeCtx(() => 'hi', (next) => { calls.push(next) })
expect(appendToDraft(ctx, 's1', 'X')).toBe(true)
expect(calls).toEqual(['hi X'])
})
it('returns false and logs when the draft carries no revision to address', () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const composer = fakeComposer({ draft: 'hi' })
const ctx = {
sessions: { scope: (): unknown => ({ emit: (): void => undefined }) },
get: (name: string): unknown => (
name === 'conversation'
? { input: { for: (): unknown => ({ state: { getSnapshot: (): unknown => ({ draft: 'hi' }) } }) } }
: undefined
),
} as unknown as Context
expect(appendToDraft(ctx, 's1', 'X')).toBe(false)
expect(consoleWarn).toHaveBeenCalledTimes(1)
expect(composer.read().draft).toBe('hi')
consoleWarn.mockRestore()
it('appends to an empty draft without a separator', () => {
const calls: string[] = []
const ctx = fakeCtx(() => '', (next) => { calls.push(next) })
appendToDraft(ctx, 's1', 'X')
expect(calls).toEqual(['X'])
})
it('returns false and logs when the conversation service is unavailable', () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const ctx = {
sessions: { scope: (): unknown => ({}) },
get: (): unknown => undefined,
} as unknown as Context
const ctx = fakeCtx(() => '', (): void => undefined, false)
expect(appendToDraft(ctx, 's1', 'X')).toBe(false)
expect(consoleWarn).toHaveBeenCalledTimes(1)
consoleWarn.mockRestore()
})
})
describe('insertFileReference', () => {
it('inserts a chip at the draft end and keeps its occurrence', () => {
const composer = fakeComposer()
expect(insertFileReference(composer.ctx, 's1', 'notes/ENV.md')).toBe(true)
expect(composer.events.map(event => event.name)).toEqual(['slash/input-insert-reference'])
expect(composer.read().draft).toBe('@notes/ENV.md ')
expect(composer.read().occurrences).toEqual([{ offset: 0, length: 13 }])
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('still applies on a draft that already holds a chip (the shipped regression)', () => {
const composer = fakeComposer({
draft: '@notes/ENV.md ',
draftRev: 4,
occurrences: [{ offset: 0, length: 13 }],
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)
})
})
/**
* A fake composer exposing the conversation face these two functions use:
* the snapshot store, the `insertReference` facade, and the session-scope
* `emit` the span channel goes through. Every write records what it was
* called with so a test can assert which channel ran.
*/
function composerCtx(options: {
draft?: string
occurrences?: { offset: number; length: number }[]
draftRev?: number
phase?: 'plain' | 'adjudicating' | 'claimed' | 'submitting'
/** Omit the `insertReference` facade (an older host without chip support). */
withChipChannel?: boolean
/** Return false from the facade to simulate the host refusing the insert. */
accept?: boolean
/** Apply the edit, then throw — the host's own update listeners failing. */
throwAfterApply?: boolean
withConversation?: boolean
} = {}) {
let draft = options.draft ?? ''
// `draftRev: undefined` is a meaningful case (a host with no revision), so
// only an absent key takes the default.
let rev: number | undefined = 'draftRev' in options ? options.draftRev : 0
const bump = (): void => { if (rev !== undefined) rev += 1 }
const setDrafts: string[] = []
const emitted: { name: string; payload: unknown }[] = []
const chipInserts: { ref: unknown; span: unknown }[] = []
const input = {
state: {
getSnapshot: () => ({
draft,
...rev === undefined ? {} : { draftRev: rev },
occurrences: options.occurrences ?? [],
...options.phase === undefined ? {} : { phase: options.phase },
...options.phase !== 'claimed' ? {} : { claim: { token: '/goal ' } },
}),
},
setDraft: (next: string): void => { setDrafts.push(next); draft = next; bump() },
...options.withChipChannel === false
? {}
: {
insertReference: (ref: unknown, span: unknown): boolean => {
chipInserts.push({ ref, span })
if (options.accept === false) return false
bump()
if (options.throwAfterApply === true) throw new Error('host listener blew up')
return true
},
},
}
const actx = {
emit: (name: string, payload: unknown): void => {
emitted.push({ name, payload })
bump()
},
}
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, setDrafts, chipInserts }
}
describe('insertDraftReference', () => {
it('hands the host one chip carrying the label and the model text apart', () => {
const fake = composerCtx({ draft: 'hello' })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a.md:3', text: '```a.md:3\nx\n```' })).toBe(true)
// `hello` ends in a non-space, so a separator is inserted first (the host
// only adds one after the chip) — the chip then lands one place later.
expect(fake.emitted).toEqual([{
name: 'slash/input-insert-text',
payload: { text: ' ', span: { draftRev: 0, start: 5, end: 5 } },
}])
expect(fake.chipInserts).toEqual([{
ref: {
source: 'reference',
ref: '```a.md:3\nx\n```',
label: 'a.md:3',
// No `appearance`: this chip's text is a fenced block, not a path.
clipboardText: 'a.md:3',
},
span: { draftRev: 1, start: 6, end: 6 },
}])
})
it('folds the span past chips already in the draft', () => {
const fake = composerCtx({ draft: 'abdocs/a.md:12 cd', occurrences: [{ offset: 2, length: 12 }] })
insertDraftReference(fake.ctx, 's1', { label: 'b.md:1', text: 'B' })
expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(7)
})
it('reports false when the host refused the insert', () => {
const fake = composerCtx({ draft: 'x', accept: false })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false)
})
it('reports false when the host has no chip facade', () => {
const fake = composerCtx({ draft: 'x', withChipChannel: false })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false)
expect(fake.chipInserts).toEqual([])
})
it('reports false when the host exposes no draft revision', () => {
const fake = composerCtx({ draft: 'x', draftRev: undefined })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false)
})
it('reports false when the conversation service is missing', () => {
const fake = composerCtx({ withConversation: false })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false)
})
it('omits appearance for a reference whose text is not a path', () => {
const fake = composerCtx({ draft: 'hello' })
insertDraftReference(fake.ctx, 's1', { label: 'a.md:3', text: '```a.md:3\nx\n```' })
expect(fake.chipInserts[0]?.ref).not.toHaveProperty('appearance')
})
it('carries the appearance a path-shaped reference asks for', () => {
const fake = composerCtx({ draft: 'hello' })
insertDraftReference(fake.ctx, 's1', { label: 'a.md', text: '@a.md', appearance: 'file' })
expect((fake.chipInserts[0]?.ref as { appearance?: string }).appearance).toBe('file')
})
it('offsets past a command chip, which never appears in occurrences', () => {
// '/goal ' is a command chip: 6 draft characters, 1 detect character.
const fake = composerCtx({ draft: '/goal ', phase: 'claimed' })
insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })
expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(1)
})
it('adds both the command chip and reference chips to the offset', () => {
// '/goal ' (1 detect) + chip 'docs/a.md:12' (1 detect) → append at 2.
const fake = composerCtx({
draft: '/goal docs/a.md:12',
phase: 'claimed',
occurrences: [{ offset: 6, length: 12 }],
})
expect(insertFileReference(composer.ctx, 's1', 'notes/STATE.md')).toBe(true)
// The chip lands at the draft end in *detect* coordinates (1 + the space).
expect(composer.events[0]?.payload.span).toEqual({ draftRev: 4, start: 2, end: 2 })
expect(composer.read().draft).toBe('@notes/ENV.md @notes/STATE.md ')
expect(composer.read().occurrences).toEqual([
{ offset: 0, length: 13 },
{ offset: 14, length: 15 },
])
expect(composer.setDrafts).toEqual([])
insertDraftReference(fake.ctx, 's1', { label: 'b', text: 'b' })
// 2 folded positions + the reserved separator space.
expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(3)
})
it('reports false — logs, and leaves the draft alone — when no listener handled the event', () => {
it('reports false while the submission is frozen', () => {
const fake = composerCtx({ draft: 'x', phase: 'submitting' })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(false)
expect(fake.chipInserts).toEqual([])
})
it('reports true when the host applied the edit and then threw', () => {
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
const composer = fakeComposer({ draft: 'hi', draftRev: 2 })
const ctx = {
sessions: { scope: (): unknown => ({ emit: (): void => undefined }) },
get: (name: string): unknown => composer.ctx.get(name),
} as unknown as Context
expect(insertFileReference(ctx, 's1', 'notes/ENV.md')).toBe(false)
expect(composer.read().draft).toBe('hi')
expect(composer.setDrafts).toEqual([])
expect(consoleWarn).toHaveBeenCalledTimes(1)
const fake = composerCtx({ draft: 'x', throwAfterApply: true })
expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(true)
consoleWarn.mockRestore()
})
it('returns false without a revision to address', () => {
const composer = fakeComposer({ draft: 'hi' })
const ctx = {
sessions: { scope: (): unknown => ({ emit: (): void => undefined }) },
get: (name: string): unknown => (
name === 'conversation'
? { input: { for: (): unknown => ({ state: { getSnapshot: (): unknown => ({ draft: 'hi' }) } }) } }
: undefined
),
} as unknown as Context
expect(insertFileReference(ctx, 's1', 'notes/ENV.md')).toBe(false)
expect(composer.events).toEqual([])
it('reserves a separator so the chip cannot stick to the last word', () => {
// The host adds a space after a chip but not before it.
const fake = composerCtx({ draft: 'hello' })
insertDraftReference(fake.ctx, 's1', { label: 'a.md:3', text: 'A' })
expect(fake.emitted[0]?.payload).toMatchObject({ text: ' ' })
expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(6)
})
it('reserves no separator when the draft already ends in whitespace', () => {
const fake = composerCtx({ draft: 'hello ' })
insertDraftReference(fake.ctx, 's1', { label: 'a.md:3', text: 'A' })
expect(fake.emitted).toEqual([])
expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(6)
})
it('reserves no separator on an empty draft', () => {
const fake = composerCtx({ draft: '' })
insertDraftReference(fake.ctx, 's1', { label: 'a.md:3', text: 'A' })
expect(fake.emitted).toEqual([])
expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(0)
})
})
describe('appendToDraft on a draft that already carries chips', () => {
it('inserts through the span event instead of rebuilding the draft', () => {
const fake = composerCtx({ draft: 'abdocs/a.md:12 cd', draftRev: 3, occurrences: [{ 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 = composerCtx({ draft: 'abdocs/a.md:12', draftRev: 3, occurrences: [{ 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 = composerCtx({ draft: 'hello', draftRev: 3 })
appendToDraft(fake.ctx, 's1', 'X')
expect(fake.emitted).toEqual([])
expect(fake.setDrafts).toEqual(['hello X'])
})
it('never flattens a command chip, even though it is not an occurrence', () => {
// `setDraft` would rebuild `/goal ` as literal text and drop the claim.
const fake = composerCtx({ draft: '/goal ', draftRev: 3, phase: 'claimed' })
appendToDraft(fake.ctx, 's1', 'X')
expect(fake.setDrafts).toEqual([])
expect(fake.emitted).toHaveLength(1)
expect(fake.emitted[0]?.name).toBe('slash/input-insert-text')
// '/goal ' folds to one detect character; nothing follows it.
expect((fake.emitted[0]?.payload as { span: { start: number } }).span.start).toBe(1)
})
})
+23 -1
View File
@@ -200,6 +200,28 @@ export async function hostRpc<T = unknown>(
return result
}
/**
* The host composer's editable. Role+name: the placeholder label only exists
* on the empty composer, so this is for the first-message path — once the
* session has content the accessible name changes.
* @param page - the lane's page.
*/
export function composerLocator(page: Page) {
return page.getByRole('textbox', { name: /^(Describe what you want to build|描述你想要构建)/ })
}
/**
* The composer's editable once the session already has content — the
* placeholder name is gone by then. Anchored on the host's composer slot
* rather than a bare `[contenteditable]` match: the plugin's own CodeMirror
* surface is also contenteditable and stays in the DOM (merely hidden) in
* preview mode.
* @param page - the lane's page.
*/
export function composerEditable(page: Page) {
return page.locator('[data-slot="conversation.composer.bar"] [contenteditable="true"]').first()
}
/**
* Send one message in the session the shell opened, so the conversation header
* (and the native right Sidebar's corner control) exists: DSH renders the
@@ -212,7 +234,7 @@ export async function hostRpc<T = unknown>(
* @param page - the lane's page.
*/
export async function sendFirstMessage(page: Page): Promise<void> {
const composer = page.getByRole('textbox', { name: /^(Describe what you want to build|描述你想要构建)/ })
const composer = composerLocator(page)
await expect(composer).toBeVisible({ timeout: 60_000 })
await composer.click()
await page.keyboard.type('mount lane smoke')
+47 -1
View File
@@ -31,7 +31,7 @@ import { mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext } from '@playwright/test'
import { PAGE_URL, createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
import { PAGE_URL, composerEditable, createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
/** Workspace the sidebar renders against (created by the lane's seeding). */
const WORKSPACE_PATH = process.env.DSH_E2E_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-workspace')
@@ -577,6 +577,52 @@ 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.
// Seed the draft with a word that does NOT end in whitespace: the host's
// chip insert only adds a space after the chip, so without the plugin's own
// leading separator the chip would read `hello` + chip with no gap.
const composer = composerEditable(page)
await composer.click()
await page.keyboard.type('hello')
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()
// `data-composer-chip` is the host's own anchor for a composer chip (its
// JSDoc names e2e as the reason it exists) — a bare `[class*="reference"]`
// match could land on any element whose hashed class happens to contain it.
const chip = page.locator(`[data-composer-chip]`).filter({ hasText: `${SEEDED_MD_FILE}:` }).first()
await expect(chip, 'the selection must land in the composer as a reference chip')
.toBeVisible({ timeout: 10_000 })
// A selection chip's `ref` is a fenced block, not a path: the host must not
// mark it openable, or a click would hand that block to the file opener.
await expect(chip, 'a selection chip must not advertise itself as openable')
.not.toHaveClass(/openable/u)
const composerText = await composer.innerText()
expect(composerText, 'the draft must not carry the quoted body the chip replaced')
.not.toContain('```')
// The chip must not fuse with the word typed before it. The exact separator
// is the composer's business (Lexical may render it as a line break rather
// than a space), so assert the boundary, not the character.
expect(composerText, 'the chip must not stick to the word typed before it')
.toMatch(/hello\s/u)
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
+18 -38
View File
@@ -21,9 +21,7 @@
* unknown-caret path (append), which keeps the captured draft exactly the
* inserted token — plus, for a folder, the separating space a *complete*
* directory insert carries (#574) so the next `@` click cannot glue two
* tokens together. Both branches insert through a scoped composer event
* (`slash/input-insert-text` for plain text); `setDraft` stays untouched,
* since the host's whole-draft replacement would flatten inline chips.
* tokens together.
*/
import { describe, expect, it, vi } from 'vitest'
import type { Context } from '../src/context-types.ts'
@@ -53,31 +51,26 @@ interface EmittedReference {
ref: string
label: string
appearance: string
clipboardText: string
}
/**
* A fake ctx exposing the three faces `referenceInChat` uses: the host's
* A fake ctx exposing the 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 host's
* `slash/input-insert-text` event (plain folder mentions), and its
* `slash/input-insert-reference` event (file chips). `setDraft` is recorded
* but never expected to fire: it is the whole-draft replacement that removes
* inline chips. The fake models the host's chip faithfully enough for the
* draft to be readable — the chip's plain-text projection is the mention
* itself (`ReferenceChipNode.getTextContent()` returns the chip's
* `clipboardText`, which the plugin sets to the mention); the separating space
* the composer adds next to a chip is not part of the reference, so it is left
* out.
* matched by session membership — issue #479's base-path gap), the plain
* `setDraft` path (folders and file fallback) and the `insertReference`
* facade. The fake models the host's chip faithfully enough for the draft to
* be readable — the chip's plain-text projection is its `clipboardText`, and
* the separating space the composer adds next to a chip is not part of the
* reference, so it is left out.
*/
function fakeComposer(initial = ''): {
ctx: Context
drafts: string[]
inserted: string[]
emitted: EmittedReference[]
read: () => string
} {
const drafts: string[] = []
const inserted: string[] = []
const emitted: EmittedReference[] = []
let text = initial
let draftRev = 0
@@ -87,23 +80,14 @@ function fakeComposer(initial = ''): {
text = next
drafts.push(next)
},
}
const scope = {
emit: (name: string, payload: unknown): void => {
if (name === 'slash/input-insert-text') {
const { text: insertedText } = payload as { text: string }
inserted.push(insertedText)
text += insertedText
draftRev += 1
return
}
if (name !== 'slash/input-insert-reference') return
const { reference } = payload as { reference: EmittedReference }
insertReference: (reference: EmittedReference): boolean => {
emitted.push(reference)
text += reference.ref
text += reference.clipboardText
draftRev += 1
return true
},
}
const scope = { emit: (): void => undefined }
const workspaces = {
list: {
getSnapshot: (): unknown => ({ phase: 'ready', state: 'idle', items: [{ path: '/w', sessionIds: ['s1'] }] }),
@@ -117,7 +101,7 @@ function fakeComposer(initial = ''): {
: name === 'workspaces' ? workspaces : undefined
),
} as unknown as Context
return { ctx, drafts, inserted, emitted, read: () => text }
return { ctx, drafts, emitted, read: () => text }
}
describe('referenceInChat folder mentions', () => {
@@ -125,8 +109,7 @@ describe('referenceInChat folder mentions', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w/my dir', true)
// The token itself is unchanged by the separator that follows it (#574).
expect(composer.inserted).toEqual(['@"my dir/" '])
expect(composer.drafts).toEqual([]) // never a whole-draft rewrite (chips survive)
expect(composer.drafts).toEqual(['@"my dir/" '])
const draft = composer.read()
expect(hostFolderToken(draft)).toBe('@"my dir/')
expect(hostBubbleKind(draft)).toBe('folder')
@@ -144,8 +127,7 @@ describe('referenceInChat folder mentions', () => {
it('keeps a folder without whitespace plain', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w/docs', true)
expect(composer.inserted).toEqual(['@docs/ '])
expect(composer.drafts).toEqual([])
expect(composer.drafts).toEqual(['@docs/ '])
expect(hostFolderToken(composer.read())).toBe('@docs/')
expect(hostBubbleKind(composer.read())).toBe('folder')
})
@@ -153,14 +135,13 @@ describe('referenceInChat folder mentions', () => {
it('keeps the relative-root spelling for the cwd itself', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w', true)
expect(composer.inserted).toEqual(['@./ '])
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', '/we"ird dir', true)
expect(composer.inserted).toEqual([])
expect(composer.drafts).toEqual([])
expect(consoleWarn).toHaveBeenCalledTimes(1)
consoleWarn.mockRestore()
@@ -172,8 +153,7 @@ describe('referenceInChat file mentions (unchanged)', () => {
const composer = fakeComposer()
referenceInChat(composer.ctx, 's1', '/w/my notes.md', false)
expect(composer.emitted.map((reference) => reference.ref)).toEqual(['@"my notes.md"'])
expect(composer.inserted).toEqual([]) // the chip path, not a plain append
expect(composer.drafts).toEqual([])
expect(composer.drafts).toEqual([]) // the chip path, not a plain append
expect(composer.read()).toBe('@"my notes.md"')
expect(hostBubbleKind(composer.read())).toBe('file')
})
+16 -8
View File
@@ -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',
})
})
})
+23 -41
View File
@@ -27,26 +27,19 @@ function mount(cwd: string, options: { root?: string; phase?: 'pending' | 'ready
let draft = 'before'
let draftRev = 1
const setDraft = vi.fn((text: string) => { draft = text; draftRev++ })
// The host's two composer events, applied for real: plain text splices at
// the span, a reference mints the chip plus its separating space. `chip:
// false` models a host that refuses the structured insert, which is how the
// plugin's plain-text fallback is exercised.
const emit = vi.fn((event: string, payload: unknown) => {
if (event === 'slash/input-insert-text') {
const { text, span } = payload as { text: string; span: { start: number; end: number } }
draft = `${draft.slice(0, span.start)}${text}${draft.slice(span.end)}`
draftRev++
return
}
if (event !== 'slash/input-insert-reference' || !options.chip) return
const { reference, span } = payload as {
reference: { clipboardText: string }
span: { start: number; end: number }
}
draft = `${draft.slice(0, span.start)}${reference.clipboardText} ${draft.slice(span.end)}`
draftRev++
const emit = vi.fn((_event: string, _payload: unknown) => {
if (options.chip) draftRev++
})
const input = { state: { getSnapshot: () => ({ draft, draftRev }) }, setDraft }
const insertReference = vi.fn((_ref: unknown, _span: unknown) => {
if (!options.chip) return false
draftRev++
return true
})
const input = {
state: { getSnapshot: () => ({ draft, draftRev }) },
setDraft,
...options.chip === false ? {} : { insertReference },
}
const workspaces = { list: { getSnapshot: () => ({
phase: options.phase ?? 'ready',
state: options.state ?? 'idle',
@@ -80,7 +73,7 @@ function mount(cwd: string, options: { root?: string; phase?: 'pending' | 'ready
expect(reference).toBeTypeOf('function')
return {
insert: (path: string, isDir: boolean) => { act(() => { reference!(path, isDir) }) },
draft: () => draft, emit, setDraft, warn,
draft: () => draft, emit, insertReference, setDraft, warn,
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
}
@@ -91,13 +84,7 @@ describe('Sidebar workspace references', () => {
try {
view.insert('/work/my dir', true)
expect(view.draft()).toBe('before @"my dir/" ')
// A folder mention is plain text over a span — never a whole-draft
// rewrite, which would flatten every inline chip already in the draft.
expect(view.emit).toHaveBeenCalledWith('slash/input-insert-text', {
text: ' @"my dir/" ',
span: { draftRev: 1, start: 6, end: 6 },
})
expect(view.setDraft).not.toHaveBeenCalled()
expect(view.emit).not.toHaveBeenCalled()
} finally { view.unmount() }
})
@@ -105,10 +92,11 @@ describe('Sidebar workspace references', () => {
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 },
})
// The draft `before` ends in a non-space, so a separator is emitted
// first: the revision and the append offset both move one place.
expect(view.insertReference).toHaveBeenCalledWith({
source: 'reference', ref: '@"docs/my notes.md"', label: 'my notes.md', appearance: 'file', clipboardText: '@"docs/my notes.md"',
}, { draftRev: 2, start: 7, end: 7 })
expect(view.setDraft).not.toHaveBeenCalled()
} finally { view.unmount() }
})
@@ -120,16 +108,10 @@ describe('Sidebar workspace references', () => {
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 },
})
// The directory insert rode the plain-text event before it.
expect(view.emit).toHaveBeenNthCalledWith(1, 'slash/input-insert-text', {
text: expect.stringMatching(/^ @/u),
span: { draftRev: 1, start: 6, end: 6 },
})
expect(view.setDraft).not.toHaveBeenCalled()
expect(view.insertReference).toHaveBeenCalledWith({
source: 'reference', ref: '@notes.md', label: 'notes.md', appearance: 'file', clipboardText: '@notes.md',
}, { draftRev: 2, start: beforeFile.length, end: beforeFile.length })
expect(view.setDraft).toHaveBeenCalledTimes(1)
} finally { view.unmount() }
})