test: 引用 chip 的二次点击、落盘失败与真实注册契约
This commit is contained in:
1 parent
90238e1cc2
commit
5de590e61f
3 files changed
+227
-36
No files matched your search
@@ -14,14 +14,17 @@
|
||||
* see any of this: the host is what decides when a navigation is spent.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import type { TransactionSpec } from '@codemirror/state'
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import { EditorHost } from '../src/client/EditorHost.tsx'
|
||||
import { TextEditor } from '../src/client/TextEditor.tsx'
|
||||
import { createBetterSidebarService } from '../src/client/service.ts'
|
||||
import { quoteFlashEffect } from '../src/client/quote-flash.ts'
|
||||
import { allLeaves, createSidebarStore, type SidebarStore, type SidebarTab } from '../src/client/state.ts'
|
||||
|
||||
setupReactAct()
|
||||
@@ -234,3 +237,84 @@ describe('a spent line must not ride along to the next file', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/** Landings (selection dispatches) and quote flashes the editor applied. */
|
||||
const landings: number[] = []
|
||||
const flashes: { from: number; to: number }[] = []
|
||||
const originalDispatch = EditorView.prototype.dispatch
|
||||
|
||||
describe('clicking the same chip twice lands and flashes both times', () => {
|
||||
beforeEach(() => {
|
||||
landings.length = 0
|
||||
flashes.length = 0
|
||||
vi.spyOn(EditorView.prototype, 'dispatch').mockImplementation(function (
|
||||
this: EditorView,
|
||||
transaction: TransactionSpec,
|
||||
) {
|
||||
const spec = transaction as { selection?: { anchor?: number }; effects?: unknown }
|
||||
if (spec.selection?.anchor !== undefined) landings.push(spec.selection.anchor)
|
||||
const effects = Array.isArray(spec.effects) ? spec.effects : spec.effects === undefined ? [] : [spec.effects]
|
||||
for (const effect of effects as { is?: (type: unknown) => boolean; value?: unknown }[]) {
|
||||
if (effect?.is?.(quoteFlashEffect) === true) flashes.push(effect.value as { from: number; to: number })
|
||||
}
|
||||
return originalDispatch.call(this, transaction)
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('a second click on the same lines navigates and flashes again', async () => {
|
||||
const { ctx, store, tabOf } = harness()
|
||||
const scope = { sessionId: SESSION, cwd: '/tmp' }
|
||||
const host = (tab: SidebarTab): ReturnType<typeof createElement> => createElement(EditorHost, {
|
||||
ctx,
|
||||
store,
|
||||
scope,
|
||||
tab,
|
||||
visible: true,
|
||||
expanded: [],
|
||||
revealed: [],
|
||||
onToggleDir: () => {},
|
||||
onReferenceFile: () => {},
|
||||
})
|
||||
// Chip click #1: the open arms the quoted range BEFORE the tab renders.
|
||||
ctx.betterSidebar.openFile(scope, '/tmp/readme.md', undefined, { line: 3, lineEnd: 5 })
|
||||
const tab = tabOf('/tmp/readme.md', 3)
|
||||
const view = mount(ctx, tab, store)
|
||||
try {
|
||||
await settle()
|
||||
expect(editing(view.container)).toBe(true)
|
||||
expect(landings).toHaveLength(1)
|
||||
expect(flashes).toHaveLength(1)
|
||||
|
||||
// Leave the editor so the second landing is observable as a mode flip,
|
||||
// not just as a redundant dispatch on an already-edited file.
|
||||
click(modeButton(view.container, 'Preview'))
|
||||
await settle()
|
||||
expect(editing(view.container)).toBe(false)
|
||||
|
||||
// Chip click #2 on the SAME lines. The host's navigation does not move
|
||||
// (`params.line === existing.tab.line`, so its adapter patches nothing),
|
||||
// which is why the nonce from line-target.ts is what makes the editor
|
||||
// treat this as a fresh navigation. Without it neither the jump nor the
|
||||
// flash happened — and the arm left behind could flash a later ordinary
|
||||
// open of the same line.
|
||||
ctx.betterSidebar.openFile(scope, '/tmp/readme.md', undefined, { line: 3, lineEnd: 5 })
|
||||
view.rerender(host(tab))
|
||||
await settle()
|
||||
|
||||
expect(editing(view.container)).toBe(true)
|
||||
expect(landings).toHaveLength(2)
|
||||
expect(flashes).toHaveLength(2)
|
||||
// Both clicks flashed the SAME quoted span, starting where the caret
|
||||
// landed.
|
||||
expect(flashes[1]).toEqual(flashes[0])
|
||||
expect(flashes[0]?.from).toBe(landings[0])
|
||||
expect(flashes[1]?.from).toBe(landings[1])
|
||||
} finally {
|
||||
view.unmount()
|
||||
}
|
||||
})
|
||||
})
|
||||
+54
-28
@@ -1,57 +1,83 @@
|
||||
/**
|
||||
* The line-target side channel: a navigation's line RANGE is armed here at
|
||||
* open time and taken once by the viewer that renders that tab. The host's
|
||||
* resource-params map declares only `line`, so the range must not ride in
|
||||
* `params` (an undeclared host contract) — this module is the plugin-side
|
||||
* replacement, keyed by path + line so a stale arm cannot hit a later open.
|
||||
* The line-target side channel: a navigation's line RANGE and IDENTITY are
|
||||
* armed here at open time, read without spending (render-safe peek), and spent
|
||||
* once by the editor that hands the navigation to its viewer. The host's
|
||||
* resource-params map declares only `line`, and its tab adapter drops a
|
||||
* navigation whose line did not move — so the nonce is what distinguishes a
|
||||
* second click on the same chip from the already-spent first one, and the
|
||||
* consume is what keeps a stale arm from flashing a later ordinary open.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { armLineEnd, takeLineEnd } from '../src/client/line-target.ts'
|
||||
import { armLineEnd, consumeLineTarget, peekLineTarget } from '../src/client/line-target.ts'
|
||||
|
||||
describe('armLineEnd / takeLineEnd', () => {
|
||||
it('hands the armed range to the taker', () => {
|
||||
describe('armLineEnd / peekLineTarget / consumeLineTarget', () => {
|
||||
it('hands the armed range to the reader without spending it', () => {
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBe(7)
|
||||
const first = peekLineTarget('/w/a.ts', 3)
|
||||
expect(first?.end).toBe(7)
|
||||
// Peeking is render-safe: a re-render (or a discarded concurrent render)
|
||||
// must not eat the arm the committed one still needs.
|
||||
expect(peekLineTarget('/w/a.ts', 3)).toBe(first)
|
||||
})
|
||||
|
||||
it('is one-shot: a second take finds nothing', () => {
|
||||
it('is one-shot: consuming removes the arm', () => {
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBe(7)
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBeUndefined()
|
||||
consumeLineTarget('/w/a.ts', 3)
|
||||
expect(peekLineTarget('/w/a.ts', 3)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not confuse two files that share a line number', () => {
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
expect(takeLineEnd('/w/b.ts', 3)).toBeUndefined()
|
||||
expect(takeLineEnd('/w/a.ts', 4)).toBeUndefined()
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBe(7)
|
||||
expect(peekLineTarget('/w/b.ts', 3)).toBeUndefined()
|
||||
expect(peekLineTarget('/w/a.ts', 4)).toBeUndefined()
|
||||
expect(peekLineTarget('/w/a.ts', 3)?.end).toBe(7)
|
||||
})
|
||||
|
||||
it('replaces the pending range of the same path + line', () => {
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
armLineEnd('/w/a.ts', 3, 9)
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBe(9)
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBeUndefined()
|
||||
const next = armLineEnd('/w/a.ts', 3, 9)
|
||||
const target = peekLineTarget('/w/a.ts', 3)
|
||||
expect(target?.end).toBe(9)
|
||||
expect(target?.nonce).toBe(next)
|
||||
})
|
||||
|
||||
it('clears the pending range when a plain jump reuses the slot', () => {
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
armLineEnd('/w/a.ts', 3, undefined)
|
||||
expect(takeLineEnd('/w/a.ts', 3)).toBeUndefined()
|
||||
it('gives every arm of the same path + line a new identity (the re-click case)', () => {
|
||||
// Clicking the SAME chip again names the same `path#line`; the host's
|
||||
// navigation does not move, so without a new nonce the editor would read
|
||||
// the click as an already-spent landing and neither jump nor flash. This
|
||||
// is the module-level guarantee the editor's journal keys on.
|
||||
const first = armLineEnd('/w/a.ts', 3, 7)
|
||||
expect(peekLineTarget('/w/a.ts', 3)?.nonce).toBe(first)
|
||||
consumeLineTarget('/w/a.ts', 3)
|
||||
const second = armLineEnd('/w/a.ts', 3, 7)
|
||||
expect(second).not.toBe(first)
|
||||
expect(peekLineTarget('/w/a.ts', 3)).toEqual({ nonce: second, end: 7 })
|
||||
})
|
||||
|
||||
it('an armed range never outlives its own navigation', () => {
|
||||
it('still arms a navigation identity when there is no range (single-line chips)', () => {
|
||||
// A one-line quote lands (and must re-land on every click) without a flash
|
||||
// span: `end` is absent but the navigation is still fresh.
|
||||
const nonce = armLineEnd('/w/a.ts', 3, undefined)
|
||||
expect(peekLineTarget('/w/a.ts', 3)).toEqual({ nonce })
|
||||
consumeLineTarget('/w/a.ts', 3)
|
||||
expect(peekLineTarget('/w/a.ts', 3)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('an armed range never outlives the landing that spent it', () => {
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
// The viewer took it for THIS open (path+line); a later plain open of the
|
||||
// The editor took it for THIS navigation; a later ordinary open of the
|
||||
// same file at another line must not inherit the flash.
|
||||
takeLineEnd('/w/a.ts', 3)
|
||||
expect(takeLineEnd('/w/a.ts', 4)).toBeUndefined()
|
||||
consumeLineTarget('/w/a.ts', 3)
|
||||
expect(peekLineTarget('/w/a.ts', 4)).toBeUndefined()
|
||||
// A re-click arms a new one; the next landing sees it again.
|
||||
armLineEnd('/w/a.ts', 3, 7)
|
||||
expect(peekLineTarget('/w/a.ts', 3)?.end).toBe(7)
|
||||
})
|
||||
|
||||
it('caps the pending map so a burst of opens cannot grow it forever', () => {
|
||||
for (let line = 1; line <= 200; line++) armLineEnd('/w/a.ts', line, line + 1)
|
||||
// The oldest arms were evicted: only the most recent MAX_ARMED survive.
|
||||
expect(takeLineEnd('/w/a.ts', 1)).toBeUndefined()
|
||||
expect(takeLineEnd('/w/a.ts', 200)).toBe(201)
|
||||
expect(peekLineTarget('/w/a.ts', 1)).toBeUndefined()
|
||||
expect(peekLineTarget('/w/a.ts', 200)?.end).toBe(201)
|
||||
})
|
||||
})
|
||||
@@ -41,8 +41,17 @@ function fakeTriggers(): FakeTriggers {
|
||||
return {
|
||||
captured,
|
||||
registerSource: (src: SidebarQuoteSource): (() => void) => {
|
||||
// The REAL contract (`ctx.inputTriggers`): one source per (trigger,
|
||||
// name); a second registration THROWS. A permissive fake would hide the
|
||||
// borrowed-source lifecycle bug this file pins.
|
||||
if (captured.length > 0) {
|
||||
throw new Error('slash source "@betterSidebarQuote" is already registered')
|
||||
}
|
||||
captured.push(src)
|
||||
return () => { captured.splice(captured.indexOf(src), 1) }
|
||||
return () => {
|
||||
const at = captured.indexOf(src)
|
||||
if (at !== -1) captured.splice(at, 1)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -141,6 +150,56 @@ describe('quoteFallbackInsert', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('the record store (persistence is a prerequisite for a chip)', () => {
|
||||
it('skips the chip when the record cannot be written (the caller falls back)', async () => {
|
||||
const mod = await freshModule()
|
||||
mod.registerQuoteSource(fakeCtx({ triggers: fakeTriggers() }))
|
||||
// Private mode / quota: writes throw. There is no readable store at all.
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: {
|
||||
getItem: () => null,
|
||||
setItem: () => { throw new Error('QuotaExceededError') },
|
||||
removeItem: () => {},
|
||||
clear: () => {},
|
||||
key: () => null,
|
||||
length: 0,
|
||||
},
|
||||
})
|
||||
const composer = fakeComposer()
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
// A chip whose record never landed would click into nothing and make the
|
||||
// codec throw on send, so the insert must report false and leave the
|
||||
// composer to the built-in fallback (identical payload, not clickable).
|
||||
expect(mod.insertQuoteChip(fakeCtx({ composer }), 's1', SELECTION)).toBe(false)
|
||||
expect(composer.insertReference).not.toHaveBeenCalled()
|
||||
expect(warn).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('persists the size-reduced payload, not the raw selection', async () => {
|
||||
const mod = await freshModule()
|
||||
mod.registerQuoteSource(fakeCtx({ triggers: fakeTriggers() }))
|
||||
// A large selection is exactly what used to blow the quota: the record
|
||||
// must carry the send payload (header only past the limit), never the raw
|
||||
// text (200 records of whole selections).
|
||||
const huge = { ...SELECTION, text: 'x'.repeat(200_000) }
|
||||
expect(mod.insertQuoteChip(fakeCtx({ composer: fakeComposer() }), 's1', huge)).toBe(true)
|
||||
const record = storedRecord(mod)
|
||||
expect(record?.text).toBe('src/a.ts:2-3')
|
||||
const raw = localStorage.getItem(mod.QUOTE_STORE_KEY) ?? ''
|
||||
expect(raw.length).toBeLessThan(1_000)
|
||||
expect(raw).not.toContain('xxxx')
|
||||
})
|
||||
|
||||
it('stores the fenced block a normal selection sends, byte for byte', async () => {
|
||||
const mod = await freshModule()
|
||||
mod.registerQuoteSource(fakeCtx({ triggers: fakeTriggers() }))
|
||||
expect(mod.insertQuoteChip(fakeCtx({ composer: fakeComposer() }), 's1', SELECTION)).toBe(true)
|
||||
expect(storedRecord(mod)?.text).toBe('```src/a.ts:2-3\nconst x = 1\n```')
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertQuoteChip without a registered source', () => {
|
||||
it('refuses and leaves the store untouched (the caller falls back)', async () => {
|
||||
const mod = await freshModule()
|
||||
@@ -194,7 +253,7 @@ describe('lifecycle self-heal (a disposed fiber must not kill the feature silent
|
||||
expect(storedJson(mod)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('treats a duplicate registration as ready instead of staying off forever', async () => {
|
||||
it('treats the other instance\'s source as ready instead of staying off forever', async () => {
|
||||
const mod = await freshModule()
|
||||
// The exact host wording (ui-input-trigger service.ts:58) — it contains
|
||||
// "already registered", not "duplicate"; the tolerance must match it.
|
||||
@@ -203,17 +262,19 @@ describe('lifecycle self-heal (a disposed fiber must not kill the feature silent
|
||||
throw new Error('slash source "@betterSidebarQuote" is already registered')
|
||||
},
|
||||
}
|
||||
mod.registerQuoteSource(fakeCtx({ triggers: dup }))
|
||||
const ctx = fakeCtx({ triggers: dup, composer: fakeComposer() })
|
||||
mod.registerQuoteSource(ctx)
|
||||
// The gate passed → the insert path runs (and lands in the fake composer).
|
||||
expect(mod.insertQuoteChip(fakeCtx({ composer: fakeComposer() }), 's1', SELECTION)).toBe(true)
|
||||
expect(mod.insertQuoteChip(ctx, 's1', SELECTION)).toBe(true)
|
||||
expect(storedJson(mod)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('a second module instance (the editor chunk copy) self-registers and shares the store', async () => {
|
||||
it('a second module instance (the editor chunk copy) reuses the registered source and shares the store', async () => {
|
||||
// The build ships this module in the core bundle AND the lazy editor
|
||||
// chunk: two independent module instances at runtime. The core copy
|
||||
// registers at apply; the editor copy — the one the commit actually
|
||||
// calls — starts cold and must self-heal at commit.
|
||||
// calls — starts cold. The host refuses its duplicate registration, so it
|
||||
// must commit through the BORROWED source and reach the same store.
|
||||
const core = await freshModule()
|
||||
const triggers = fakeTriggers()
|
||||
core.registerQuoteSource(fakeCtx({ triggers, sidebar: { openFile: vi.fn() } }))
|
||||
@@ -221,7 +282,7 @@ describe('lifecycle self-heal (a disposed fiber must not kill the feature silent
|
||||
|
||||
const editor = await freshModule() // a cold second instance of the module
|
||||
expect(editor.insertQuoteChip(fakeCtx({ triggers, composer: fakeComposer() }), 's1', SELECTION)).toBe(true)
|
||||
expect(triggers.captured).toHaveLength(2) // THIS copy registered its own source
|
||||
expect(triggers.captured).toHaveLength(1) // no second source: the host refused it
|
||||
const record = storedRecord(editor)
|
||||
expect(record?.path).toBe('/w/src/a.ts')
|
||||
|
||||
@@ -229,6 +290,26 @@ describe('lifecycle self-heal (a disposed fiber must not kill the feature silent
|
||||
// localStorage (click routing / send serialization live there).
|
||||
expect(core.resolveQuote(record?.id as string)?.path).toBe('/w/src/a.ts')
|
||||
})
|
||||
|
||||
it('takes the source over after the owning instance disposes (a chip must never go dead)', async () => {
|
||||
const core = await freshModule()
|
||||
const triggers = fakeTriggers()
|
||||
const ctx = fakeCtx({ triggers, composer: fakeComposer() })
|
||||
const disposeCore = core.registerQuoteSource(ctx)
|
||||
const editor = await freshModule()
|
||||
// The editor copy borrows the live source from the core bundle.
|
||||
expect(editor.insertQuoteChip(ctx, 's1', SELECTION)).toBe(true)
|
||||
expect(triggers.captured).toHaveLength(1)
|
||||
// The owner goes away (session switch / socket reconnect / HMR). Nothing
|
||||
// tells the borrowing instance, so its next commit must notice the empty
|
||||
// slot and register — otherwise clicks are silently ignored and the codec
|
||||
// blocks the send.
|
||||
disposeCore()
|
||||
expect(triggers.captured).toHaveLength(0)
|
||||
expect(editor.insertQuoteChip(ctx, 's1', SELECTION)).toBe(true)
|
||||
expect(triggers.captured).toHaveLength(1)
|
||||
expect(triggers.captured[0]?.name).toBe(editor.QUOTE_SOURCE)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the registered source', () => {
|
||||
|
||||
Reference in new issue
Block a user