fix(client): 草稿插入不再整份重写,chip 不再被展平(@ 提及两段式)
`appendToDraft` 走的是宿主 `setDraft(整串)`,而该 API 的契约原文就是「用纯文本替换整份 草稿、移除内联引用 chip」:草稿里已有的每个 chip 会被展平成 `@dir/file.ts` 文本,宿主再只 装饰 `@dir/` 前缀——所以侧栏 @ 引用按钮插一次目录(或文件插入失败回退一次),之前所有 @ 选择都会退化成「`@notes/` + 文件名」两段。另外文件插入的 span 用的是剪贴板长度,而宿主 `TokenSpan` 是 detect 坐标(chip = 一个 U+FFFC),草稿里只要已有一个 chip 就越界被拒, 于是那次插入必然落到上面这条破坏性回退上——这正是「第一次正常、第二次把第一次变成两段式」。 - 文件与目录都改走宿主的 scoped composer 事件(`slash/input-insert-reference` / `slash/input-insert-text`):只改目标区间,其它节点原样保留; - 新增 `detectLength` / `clipboardToDetect`,用 `InputState.occurrences` 把 span 折进 detect 坐标(落在 chip 内部的位置吸附到该 chip 之前); - 删掉 `placeComposerCaretAfterInsert`:事件插入后由宿主落 caret,而 0.1.7+ 的 composer 是 Lexical contenteditable,`<textarea>` 探测恒 null,那套补偿已是死代码; - 事件没人处理时返回 false 并保持草稿不动(宁可什么都不插,也不再整份重写); - 回归:`tests/conversation-draft.spec.ts` 的假宿主同时模拟 detect 坐标折叠与「越界拒绝」, `tests/sidebar-workspace-reference.spec.tsx` / `tests/reference-in-chat.spec.ts` 改为断言 事件载荷,并断言 `setDraft` 从不被调用。
This commit is contained in:
1 parent
2bcee4c635
commit
3757f75ca7
5 files changed
+485
-222
No files matched your search
+154
-108
@@ -5,34 +5,42 @@
|
||||
* 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.
|
||||
* **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:
|
||||
*
|
||||
* 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 `<textarea>` keeps
|
||||
* its last selection even while unfocused, so the live caret is probed from
|
||||
* the DOM (guarded by a value-sync check), and the text is spliced at that
|
||||
* position, replacing any live selection — with whitespace-aware joins, an
|
||||
* insert into the middle of a sentence keeps single-space separation like
|
||||
* the append path. An unknown/stale caret falls back to appending at the
|
||||
* end (the pre-fix behavior).
|
||||
* - `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.
|
||||
*
|
||||
* The caret is also *restored* after the insert: committing a programmatic
|
||||
* draft change resets the controlled textarea's caret (observed landing at
|
||||
* the start of the value), which would make every later insert probe the
|
||||
* reset position and drift the stack (A|B + C + D ended up as |DACB). The
|
||||
* placement (`placeComposerCaretAfterInsert`) puts the caret right after the
|
||||
* inserted text once the value commit lands — the index accounts for the
|
||||
* separating space on the left, so stacked inserts stay at their running
|
||||
* position (A|B + C + D → ACD|B).
|
||||
* **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).
|
||||
*/
|
||||
import type { Context, SidebarConversation } from '../context-types.ts'
|
||||
import type { Context, SidebarConversation, SidebarSessionInput } from '../context-types.ts'
|
||||
import { baseName, workspaceRelativePath } from './paths.ts'
|
||||
|
||||
/** A resolved composer caret/selection in draft coordinates. */
|
||||
@@ -42,46 +50,85 @@ export interface DraftCaret {
|
||||
}
|
||||
|
||||
/**
|
||||
* The spliced draft plus the caret index (in that draft) right after the
|
||||
* inserted text — the left-side separating space shifts the caret by one,
|
||||
* which naive `start + text.length` misses (it would land before the tail).
|
||||
* 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.
|
||||
*/
|
||||
interface SpliceResult {
|
||||
draft: string
|
||||
caretAfter: number
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice `text` into `draft` at `caret` (replacing any live selection) with
|
||||
* whitespace-aware joins and report the caret position right after the
|
||||
* inserted text. `caret === null` (position unknown) appends at the end,
|
||||
* exactly like the original behavior.
|
||||
* 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.
|
||||
*/
|
||||
function spliceInsert(draft: string, text: string, caret: DraftCaret | null): SpliceResult {
|
||||
if (caret === null || draft === '') {
|
||||
const next = draft.trim() === '' ? text : `${draft}${/\s$/.test(draft) ? '' : ' '}${text}`
|
||||
return { draft: next, caretAfter: next.length }
|
||||
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 { draft: text, caretAfter: text.length }
|
||||
// One separating space, but never doubled against adjacent whitespace
|
||||
// (or the string edges) — mirrors how typing in the middle of a sentence
|
||||
// behaves.
|
||||
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 {
|
||||
draft: `${prefix}${left}${text}${right}${suffix}`,
|
||||
caretAfter: prefix.length + left.length + text.length,
|
||||
}
|
||||
return { text: `${left}${text}${right}`, start: caret.start, end: caret.end }
|
||||
}
|
||||
|
||||
/**
|
||||
* The spliced draft string (see {@link spliceInsert}); pure string math —
|
||||
* The spliced draft string (see {@link planInsert}); pure string math —
|
||||
* unit-tested directly.
|
||||
*/
|
||||
export function insertAtCaret(draft: string, text: string, caret: DraftCaret | null): string {
|
||||
return spliceInsert(draft, text, caret).draft
|
||||
const plan = planInsert(draft, text, caret)
|
||||
return `${draft.slice(0, plan.start)}${plan.text}${draft.slice(plan.end)}`
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,47 +172,33 @@ export function probeComposerCaret(draft: string): DraftCaret | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore the composer caret to `caretIndex` after a programmatic
|
||||
* `setDraft` commit. A controlled textarea update resets the caret (React
|
||||
* commits the value asynchronously and the browser moves the caret to the
|
||||
* start/end), so the placement is scheduled and retried across at most two
|
||||
* animation frames (setTimeout fallback for jsdom), and only applied when
|
||||
* the textarea still matches `expectedDraft` — a newer edit or a different
|
||||
* composer wins the race untouched. The caret is clamped into the value
|
||||
* bounds, mirroring how browsers clamp type-in positions.
|
||||
* 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.
|
||||
*/
|
||||
export function placeComposerCaretAfterInsert(expectedDraft: string, caretIndex: number): void {
|
||||
let remaining = 2
|
||||
let scheduled = false
|
||||
const schedule = (fn: () => void): void => {
|
||||
if (scheduled) return
|
||||
scheduled = true
|
||||
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(fn)
|
||||
else setTimeout(fn, 0)
|
||||
}
|
||||
const place = (): void => {
|
||||
scheduled = false
|
||||
if (remaining <= 0) return
|
||||
remaining -= 1
|
||||
const el = findComposerTextarea()
|
||||
if (el === null || el.disabled || el.readOnly) return
|
||||
if (el.value !== expectedDraft) {
|
||||
// The commit has not landed yet (or a competing edit won) — one more
|
||||
// frame before giving up.
|
||||
schedule(place)
|
||||
return
|
||||
}
|
||||
const clamped = Math.max(0, Math.min(caretIndex, el.value.length))
|
||||
el.setSelectionRange(clamped, clamped)
|
||||
}
|
||||
schedule(place)
|
||||
function emitComposerEvent(actx: object, name: string, payload: unknown): void {
|
||||
;(actx as { emit(name: string, payload: unknown): void }).emit(name, payload)
|
||||
}
|
||||
|
||||
/** 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 ?? [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert `text` into the session's composer draft at the composer's live
|
||||
* caret (see {@link probeComposerCaret}), falling back to appending at the
|
||||
* end when the caret cannot be resolved. Returns false — and logs — when the
|
||||
* conversation service or the session scope is unavailable.
|
||||
* 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).
|
||||
*/
|
||||
export function appendToDraft(ctx: Context, sessionId: string, text: string): boolean {
|
||||
try {
|
||||
@@ -180,15 +213,21 @@ 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 caret = probeComposerCaret(draft)
|
||||
const { draft: next, caretAfter } = spliceInsert(draft, text, caret)
|
||||
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
|
||||
// running position.
|
||||
placeComposerCaretAfterInsert(next, caretAfter)
|
||||
return true
|
||||
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),
|
||||
},
|
||||
})
|
||||
return input.state.getSnapshot().draftRev !== before.draftRev
|
||||
} catch (error) {
|
||||
console.warn('[dsh-better-sidebar] draft insert failed:', error)
|
||||
return false
|
||||
@@ -260,8 +299,11 @@ export function insertWorkspaceReference(ctx: Context, sessionId: string, path:
|
||||
return false
|
||||
}
|
||||
if (!isDir && insertFileReference(ctx, sessionId, relative)) return true
|
||||
// The host adds space after a file chip, but not before it. Complete
|
||||
// directory inserts need their own separator for the next @ click.
|
||||
// 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)
|
||||
} catch (error) {
|
||||
console.warn('[dsh-better-sidebar] workspace-reference insert failed:', error)
|
||||
@@ -274,9 +316,14 @@ export function insertWorkspaceReference(ctx: Context, sessionId: string, path:
|
||||
* 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 rc.1 picker also supports folder
|
||||
* chips on explicit selection; its drill action still inserts plain text.
|
||||
* 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')
|
||||
@@ -287,11 +334,11 @@ export function insertFileReference(ctx: Context, sessionId: string, relativePat
|
||||
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', {
|
||||
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,
|
||||
@@ -301,12 +348,11 @@ export function insertFileReference(ctx: Context, sessionId: string, relativePat
|
||||
},
|
||||
span: {
|
||||
draftRev: before.draftRev,
|
||||
start: before.draft.length,
|
||||
end: before.draft.length,
|
||||
start: at,
|
||||
end: at,
|
||||
},
|
||||
})
|
||||
const after = input.state.getSnapshot()
|
||||
return after.draftRev !== before.draftRev
|
||||
return input.state.getSnapshot().draftRev !== before.draftRev
|
||||
} catch (error) {
|
||||
console.warn('[dsh-better-sidebar] file-reference insert failed:', error)
|
||||
return false
|
||||
|
||||
+15
-3
@@ -655,11 +655,23 @@ export interface SidebarLocaleService {
|
||||
/** 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. */
|
||||
* 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. */
|
||||
state: {
|
||||
getSnapshot(): { draft: string; draftRev?: number }
|
||||
getSnapshot(): {
|
||||
draft: string
|
||||
draftRev?: number
|
||||
occurrences?: readonly { offset: number; length: number }[]
|
||||
}
|
||||
}
|
||||
/** Replace the draft text (the input machine's single public write path). */
|
||||
/**
|
||||
* 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`.
|
||||
*/
|
||||
setDraft(text: string): void
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,30 @@
|
||||
/**
|
||||
* conversation-draft spec — the caret-resolved composer insertion (upstream
|
||||
* issue #425 ②). `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; `placeComposerCaretAfterInsert`
|
||||
* restores the caret right after the inserted text once the setDraft value
|
||||
* commit lands, keeping stacked inserts at their running position.
|
||||
* conversation-draft spec — composer insertion without whole-draft rewrites.
|
||||
*
|
||||
* `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).
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import {
|
||||
appendToDraft,
|
||||
clipboardToDetect,
|
||||
detectLength,
|
||||
insertAtCaret,
|
||||
placeComposerCaretAfterInsert,
|
||||
insertFileReference,
|
||||
probeComposerCaret,
|
||||
type DraftOccurrence,
|
||||
} from '../src/client/conversation-draft.ts'
|
||||
|
||||
/**
|
||||
@@ -40,9 +50,6 @@ afterEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
/** Let the scheduled caret placement (rAF or setTimeout fallback) settle. */
|
||||
const tick = (): Promise<void> => new Promise((resolve) => { setTimeout(resolve, 30) })
|
||||
|
||||
describe('probeComposerCaret', () => {
|
||||
it('returns the textarea selection when the DOM is in sync with the draft', () => {
|
||||
mountComposer('hello world', 5, 5)
|
||||
@@ -141,109 +148,263 @@ describe('insertAtCaret', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('placeComposerCaretAfterInsert', () => {
|
||||
it('places the caret right after the inserted text once the value commits', async () => {
|
||||
const input = mountComposer('AB', 1, 1) // pre-insert draft still shown
|
||||
placeComposerCaretAfterInsert('A C B', 1 + 1)
|
||||
input.value = 'A C B' // the setDraft commit lands
|
||||
await tick()
|
||||
expect(input.selectionStart).toBe(2)
|
||||
expect(input.selectionEnd).toBe(2)
|
||||
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('places the caret when the value already matches (no commit needed)', async () => {
|
||||
const input = mountComposer('A C B', 0, 0)
|
||||
placeComposerCaretAfterInsert('A C B', 2)
|
||||
await tick()
|
||||
expect(input.selectionStart).toBe(2)
|
||||
it('passes offsets through when the draft holds no chip', () => {
|
||||
expect(clipboardToDetect([], 0)).toBe(0)
|
||||
expect(clipboardToDetect([], 42)).toBe(42)
|
||||
})
|
||||
|
||||
it('clamps an out-of-range caret into the composer bounds', async () => {
|
||||
const input = mountComposer('A C B', 0, 0)
|
||||
placeComposerCaretAfterInsert('A C B', 99)
|
||||
await tick()
|
||||
expect(input.selectionStart).toBe(5)
|
||||
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('does not clobber a composer that never matches the expected draft', async () => {
|
||||
const input = mountComposer('OLD', 0, 0)
|
||||
input.value = 'UNRELATED' // a competing update wins the race
|
||||
input.setSelectionRange(1, 1)
|
||||
placeComposerCaretAfterInsert('NEW DRAFT', 2)
|
||||
await tick()
|
||||
expect(input.selectionStart).toBe(1)
|
||||
})
|
||||
|
||||
it('leaves the caret alone when no composer is mounted', async () => {
|
||||
placeComposerCaretAfterInsert('X', 0)
|
||||
await tick() // must not throw
|
||||
expect(document.querySelector('textarea')).toBeNull()
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
describe('appendToDraft', () => {
|
||||
/** 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) },
|
||||
/** 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 {
|
||||
sessions: { scope: (): unknown => ({}) },
|
||||
get: (name: string): unknown =>
|
||||
withConversation && name === 'conversation'
|
||||
? { input: { for: (): unknown => input } }
|
||||
: undefined,
|
||||
} as unknown as Context
|
||||
return offset + absorbed
|
||||
}
|
||||
|
||||
it('splices at the probed caret and restores the caret right after the insert', async () => {
|
||||
const composer = mountComposer('AB', 1, 1)
|
||||
const calls: string[] = []
|
||||
const ctx = fakeCtx(() => 'AB', (next) => { calls.push(next); composer.value = next })
|
||||
expect(appendToDraft(ctx, 's1', 'C')).toBe(true)
|
||||
expect(calls).toEqual(['A C B'])
|
||||
await tick()
|
||||
// 'A C| B' — the caret sits right after the inserted text (the left
|
||||
// separating space shifts it past `start + text.length`).
|
||||
expect(composer.selectionStart).toBe(3)
|
||||
expect(composer.selectionEnd).toBe(3)
|
||||
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 and places the caret at the end when the caret is unknown', async () => {
|
||||
const composer = mountComposer('hi', 0, 0)
|
||||
composer.value = 'hi changed' // out of sync → caret unresolved → append
|
||||
const calls: string[] = []
|
||||
const ctx = fakeCtx(() => 'hi', (next) => { calls.push(next); composer.value = next })
|
||||
appendToDraft(ctx, 's1', 'X')
|
||||
expect(calls).toEqual(['hi X'])
|
||||
await tick()
|
||||
expect(composer.selectionStart).toBe(4)
|
||||
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('keeps stacked inserts at the running caret (A|B + C + D → ACD|B)', async () => {
|
||||
const composer = mountComposer('AB', 1, 1)
|
||||
let draft = 'AB'
|
||||
const ctx = fakeCtx(() => draft, (next) => { draft = next; composer.value = next })
|
||||
appendToDraft(ctx, 's1', 'C')
|
||||
await tick()
|
||||
expect(draft).toBe('A C B')
|
||||
expect(composer.selectionStart).toBe(3) // A C| B
|
||||
appendToDraft(ctx, 's1', 'D')
|
||||
await tick()
|
||||
expect(draft).toBe('A C D B')
|
||||
expect(composer.selectionStart).toBe(5) // A C D| B
|
||||
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('reports false — and leaves the draft alone — when no listener handled the event', () => {
|
||||
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(appendToDraft(ctx, 's1', 'X')).toBe(false)
|
||||
expect(composer.read().draft).toBe('hi')
|
||||
expect(composer.setDrafts).toEqual([])
|
||||
})
|
||||
|
||||
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('returns false and logs when the conversation service is unavailable', () => {
|
||||
const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
const ctx = fakeCtx(() => '', (): void => undefined, false)
|
||||
const ctx = {
|
||||
sessions: { scope: (): unknown => ({}) },
|
||||
get: (): unknown => undefined,
|
||||
} as unknown as Context
|
||||
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 }])
|
||||
})
|
||||
|
||||
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 }],
|
||||
})
|
||||
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([])
|
||||
})
|
||||
|
||||
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([])
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,9 @@
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
@@ -56,22 +58,26 @@ interface EmittedReference {
|
||||
/**
|
||||
* A fake ctx exposing the three faces `referenceInChat` uses: the host's
|
||||
* `workspaces` snapshot (the token is projected against `WorkspaceView.path`,
|
||||
* matched by session membership — issue #479's base-path gap), the plain
|
||||
* `setDraft` path (folders and file fallback) and the host's
|
||||
* `slash/input-insert-reference` event. The fake models the host's chip
|
||||
* faithfully enough for the draft to be readable — the chip's plain-text
|
||||
* projection is the mention itself (`ReferenceChipNode.getTextContent()`
|
||||
* 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 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.
|
||||
*/
|
||||
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
|
||||
@@ -84,6 +90,13 @@ function fakeComposer(initial = ''): {
|
||||
}
|
||||
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 }
|
||||
emitted.push(reference)
|
||||
@@ -104,7 +117,7 @@ function fakeComposer(initial = ''): {
|
||||
: name === 'workspaces' ? workspaces : undefined
|
||||
),
|
||||
} as unknown as Context
|
||||
return { ctx, drafts, emitted, read: () => text }
|
||||
return { ctx, drafts, inserted, emitted, read: () => text }
|
||||
}
|
||||
|
||||
describe('referenceInChat folder mentions', () => {
|
||||
@@ -112,7 +125,8 @@ 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.drafts).toEqual(['@"my dir/" '])
|
||||
expect(composer.inserted).toEqual(['@"my dir/" '])
|
||||
expect(composer.drafts).toEqual([]) // never a whole-draft rewrite (chips survive)
|
||||
const draft = composer.read()
|
||||
expect(hostFolderToken(draft)).toBe('@"my dir/')
|
||||
expect(hostBubbleKind(draft)).toBe('folder')
|
||||
@@ -130,7 +144,8 @@ describe('referenceInChat folder mentions', () => {
|
||||
it('keeps a folder without whitespace plain', () => {
|
||||
const composer = fakeComposer()
|
||||
referenceInChat(composer.ctx, 's1', '/w/docs', true)
|
||||
expect(composer.drafts).toEqual(['@docs/ '])
|
||||
expect(composer.inserted).toEqual(['@docs/ '])
|
||||
expect(composer.drafts).toEqual([])
|
||||
expect(hostFolderToken(composer.read())).toBe('@docs/')
|
||||
expect(hostBubbleKind(composer.read())).toBe('folder')
|
||||
})
|
||||
@@ -138,13 +153,14 @@ 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.drafts).toEqual(['@./ '])
|
||||
expect(composer.inserted).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()
|
||||
@@ -156,7 +172,8 @@ 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.drafts).toEqual([]) // the chip path, not a plain append
|
||||
expect(composer.inserted).toEqual([]) // the chip path, not a plain append
|
||||
expect(composer.drafts).toEqual([])
|
||||
expect(composer.read()).toBe('@"my notes.md"')
|
||||
expect(hostBubbleKind(composer.read())).toBe('file')
|
||||
})
|
||||
|
||||
@@ -27,8 +27,24 @@ 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++ })
|
||||
const emit = vi.fn((_event: string, _payload: unknown) => {
|
||||
if (options.chip) 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 input = { state: { getSnapshot: () => ({ draft, draftRev }) }, setDraft }
|
||||
const workspaces = { list: { getSnapshot: () => ({
|
||||
@@ -75,7 +91,13 @@ describe('Sidebar workspace references', () => {
|
||||
try {
|
||||
view.insert('/work/my dir', true)
|
||||
expect(view.draft()).toBe('before @"my dir/" ')
|
||||
expect(view.emit).not.toHaveBeenCalled()
|
||||
// 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()
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
@@ -102,7 +124,12 @@ describe('Sidebar workspace references', () => {
|
||||
reference: { source: 'reference', ref: '@notes.md', label: 'notes.md', appearance: 'file', clipboardText: '@notes.md' },
|
||||
span: { draftRev: 2, start: beforeFile.length, end: beforeFile.length },
|
||||
})
|
||||
expect(view.setDraft).toHaveBeenCalledTimes(1)
|
||||
// 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()
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user