diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index 80baf512..c38dce90 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -35,6 +35,7 @@ import type { Context, SidebarConversation, SidebarReferenceInsert, + SidebarSessionInput, SidebarSessionOccurrence, } from '../context-types.ts' import { baseName, workspaceRelativePath } from './paths.ts' @@ -51,10 +52,16 @@ export interface DraftReference { /** * What the draft string carries for this chip (the clipboard projection). * Defaults to `label`; a file reference spells its `@path` here instead. - * Keep it short: this is the form a remounted session re-seeds the draft + * Keep it short — this is the form a remounted session re-seeds the draft * from, and it cannot be turned back into a chip. */ clipboardText?: string + /** + * 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' } /** A resolved composer caret/selection in draft coordinates. */ @@ -239,6 +246,32 @@ export function foldClipboardOffset( 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): 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 @@ -260,6 +293,7 @@ export function insertDraftReference( sessionId: string, reference: DraftReference, ): boolean { + let before: number | undefined try { const actx = ctx.sessions.scope(sessionId) if (actx === undefined) return false @@ -268,20 +302,66 @@ export function insertDraftReference( 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 = foldClipboardOffset(snapshot.draft, snapshot.occurrences ?? [], snapshot.draft.length) + 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, null) !== '') { + 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, - appearance: 'file', + // 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: snapshot.draftRev, start: at, end: at }) + 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 } } @@ -308,26 +388,31 @@ export function appendToDraft(ctx: Context, sessionId: string, text: string): bo const snapshot = input.state.getSnapshot() const draft = snapshot.draft const occurrences = snapshot.occurrences ?? [] - const caret = probeComposerCaret(draft) - if (occurrences.length > 0) { + // 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' + const caret = hasChips ? null : probeComposerCaret(draft) + 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. - if (snapshot.draftRev === undefined) { + 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 } - const at = foldClipboardOffset(draft, occurrences, caret === null ? draft.length : caret.start) // 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, caret)}${text}`, + text: `${leadFor(draft, null)}${text}`, span: { draftRev: snapshot.draftRev, start: at, end: at }, }) return input.state.getSnapshot().draftRev !== snapshot.draftRev @@ -355,9 +440,8 @@ export function insertReferenceOrText( ctx: Context, sessionId: string, reference: DraftReference, - fallbackText: string = reference.text, ): boolean { - return insertDraftReference(ctx, sessionId, reference) || appendToDraft(ctx, sessionId, fallbackText) + return insertDraftReference(ctx, sessionId, reference) || appendToDraft(ctx, sessionId, reference.text) } /** @@ -419,20 +503,26 @@ 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 } - // The host adds space after a file chip, but not before it. Complete - // directory inserts need their own separator for the next @ click. - if (isDir) return appendToDraft(ctx, sessionId, `${mention} `) - const file = mentionFor(relative, 'file') - if (file === undefined) return false 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) diff --git a/src/context-types.ts b/src/context-types.ts index 467a4953..c9afd94c 100644 --- a/src/context-types.ts +++ b/src/context-types.ts @@ -704,6 +704,20 @@ export interface SidebarSessionInput { * 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 } } } /** diff --git a/tests/conversation-draft.spec.ts b/tests/conversation-draft.spec.ts index 7d6737ac..279684a3 100644 --- a/tests/conversation-draft.spec.ts +++ b/tests/conversation-draft.spec.ts @@ -304,10 +304,13 @@ 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 ?? '' @@ -324,6 +327,8 @@ function composerCtx(options: { 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() }, @@ -334,6 +339,7 @@ function composerCtx(options: { chipInserts.push({ ref, span }) if (options.accept === false) return false bump() + if (options.throwAfterApply === true) throw new Error('host listener blew up') return true }, }, @@ -358,22 +364,28 @@ 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', - appearance: 'file', + // No `appearance`: this chip's text is a fenced block, not a path. clipboardText: 'a.md:3', }, - span: { draftRev: 0, start: 5, end: 5 }, + 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(6) + expect((fake.chipInserts[0]?.span as { start: number }).start).toBe(7) }) it('reports false when the host refused the insert', () => { @@ -396,6 +408,72 @@ describe('insertDraftReference', () => { 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 }], + }) + 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 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 fake = composerCtx({ draft: 'x', throwAfterApply: true }) + expect(insertDraftReference(fake.ctx, 's1', { label: 'a', text: 'a' })).toBe(true) + consoleWarn.mockRestore() + }) + + 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', () => { @@ -423,4 +501,15 @@ describe('appendToDraft on a draft that already carries chips', () => { 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) + }) }) \ No newline at end of file diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index ad07a189..03505d97 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -583,6 +583,12 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async // `path:lines` — with no fenced body anywhere in the draft. This is the // whole point of the chip path: a host that ignores the reference-insert // event degrades to plain text and fails right here. + // 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 @@ -597,17 +603,24 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async await expect(addToChat, 'selecting preview text must raise the add-to-conversation button') .toBeVisible({ timeout: 10_000 }) await addToChat.click() - // The chip is a sibling decorator inside the composer's editable, not a - // descendant of the role=textbox node — scope the search to the composer - // card instead. - const chip = page.locator(`[data-lexical-decorator], [class*="reference"]`) - .filter({ hasText: `${SEEDED_MD_FILE}:` }) - .first() + // `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 }) - const composerText = await composerEditable(page).innerText() + // 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 diff --git a/tests/sidebar-workspace-reference.spec.tsx b/tests/sidebar-workspace-reference.spec.tsx index 482f28aa..26875873 100644 --- a/tests/sidebar-workspace-reference.spec.tsx +++ b/tests/sidebar-workspace-reference.spec.tsx @@ -92,9 +92,11 @@ describe('Sidebar workspace references', () => { const view = mount('/work/src', { root: '/work', chip: true }) try { view.insert('/work/docs/my notes.md', false) + // 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: 1, start: 6, end: 6 }) + }, { draftRev: 2, start: 7, end: 7 }) expect(view.setDraft).not.toHaveBeenCalled() } finally { view.unmount() } })