fix(client): narrow prompt input and defer skill highlighting
This commit is contained in:
1 parent
d7099f9e2e
commit
2c93df5620
13 files changed
+175
-144
No files matched your search
@@ -33,7 +33,7 @@ interface DraftSnapshot {
|
||||
const EMPTY: DraftSnapshot = { text: '', references: [] }
|
||||
|
||||
interface DraftOptions {
|
||||
prompt?: string | DraftSnapshot
|
||||
prompt?: string
|
||||
clearPreviousDraft?: boolean
|
||||
}
|
||||
|
||||
@@ -123,6 +123,25 @@ function storedDraft(page: Page, sessionId: SessionId): Promise<unknown> {
|
||||
}, sessionId)
|
||||
}
|
||||
|
||||
async function writeStoredDrafts(page: Page, drafts: readonly { sessionId: SessionId; draft: string | DraftSnapshot }[]): Promise<void> {
|
||||
await page.evaluate((drafts) => {
|
||||
for (const { sessionId, draft } of drafts) {
|
||||
const key = `dsh.conversation.${sessionId}`
|
||||
const raw = localStorage.getItem(key)
|
||||
const saved: unknown = raw === null ? { view: null, viewRequest: null } : JSON.parse(raw)
|
||||
if (typeof saved !== 'object' || saved === null || Array.isArray(saved)) {
|
||||
throw new Error(`Unexpected conversation record for ${sessionId}`)
|
||||
}
|
||||
localStorage.setItem(key, JSON.stringify({ ...saved, draft }))
|
||||
}
|
||||
}, drafts)
|
||||
}
|
||||
|
||||
async function restoreStoredDrafts(page: Page, drafts: readonly { sessionId: SessionId; draft: string | DraftSnapshot }[]): Promise<void> {
|
||||
await writeStoredDrafts(page, drafts)
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
}
|
||||
|
||||
function editorSelection(page: Page) {
|
||||
return composer(page).evaluate((element) => {
|
||||
const selection = element.ownerDocument.getSelection()
|
||||
@@ -162,7 +181,7 @@ async function assertDraft(page: Page, sessionId: SessionId, expected: DraftSnap
|
||||
[...element.children].map(paragraph => paragraph.textContent).join('\n')), SETTLE).toBe(displayed)
|
||||
}
|
||||
|
||||
async function initialize(page: Page, prompt: string | DraftSnapshot, workspaceId?: string, clearPreviousDraft = false) {
|
||||
async function initialize(page: Page, prompt: string, workspaceId?: string, clearPreviousDraft = false) {
|
||||
await startSession(page, workspaceId, { prompt, clearPreviousDraft })
|
||||
}
|
||||
|
||||
@@ -300,10 +319,16 @@ it('restores repeated file, folder and Session capsules across edits, Workspace
|
||||
await mkdir(join(workspace.path, '目录'))
|
||||
await writeFile(join(workspace.path, FILE_NAME), FILE_BODY)
|
||||
}
|
||||
const secondDraft = structuredDraft(firstId, '工作区乙')
|
||||
await initialize(page, secondDraft, second.id)
|
||||
await initialize(page, '', second.id)
|
||||
await expect.poll(() => second.sessionIds.length, SETTLE).toBe(1)
|
||||
const secondId = second.sessionIds[0]!
|
||||
await assertDraft(page, secondId, EMPTY)
|
||||
const firstDraft = structuredDraft(secondId, '工作区甲')
|
||||
const secondDraft = structuredDraft(firstId, '工作区乙')
|
||||
await restoreStoredDrafts(page, [
|
||||
{ sessionId: firstId, draft: firstDraft },
|
||||
{ sessionId: secondId, draft: secondDraft },
|
||||
])
|
||||
await assertDraft(page, secondId, secondDraft)
|
||||
expect(await composer(page).evaluate(element => ({
|
||||
paragraphs: [...element.children].map(paragraph => paragraph.textContent),
|
||||
@@ -354,8 +379,7 @@ it('restores repeated file, folder and Session capsules across edits, Workspace
|
||||
],
|
||||
}
|
||||
`)
|
||||
const firstDraft = structuredDraft(secondId, '工作区甲')
|
||||
await initialize(page, firstDraft, first.id)
|
||||
await openWorkspaceSession(page, first, firstId)
|
||||
await assertDraft(page, firstId, firstDraft)
|
||||
|
||||
const drafts = [
|
||||
@@ -404,11 +428,7 @@ it('restores repeated file, folder and Session capsules across edits, Workspace
|
||||
it('reads a legacy string from the existing conversation key and saves ordinary edits as a structured draft', async () => {
|
||||
const { scaffold, page, console, firstId } = await launchDraftFixture()
|
||||
const legacy = '旧字符串草稿 🧭\n普通 @notes,不是胶囊'
|
||||
// Seed the old storage representation before the reloaded client creates its stores.
|
||||
await page.addInitScript(({ id, text }) => {
|
||||
localStorage.setItem(`dsh.conversation.${id}`, JSON.stringify({ draft: text, view: null, viewRequest: null }))
|
||||
}, { id: firstId, text: legacy })
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
await restoreStoredDrafts(page, [{ sessionId: firstId, draft: legacy }])
|
||||
await expect.poll(() => selectedSession(page), SETTLE).toBe(firstId)
|
||||
await composer(page).waitFor()
|
||||
await expect.poll(() => composer(page).evaluate(element =>
|
||||
@@ -427,7 +447,7 @@ it('rematches the current draft after a delayed real skills catalog without repl
|
||||
const releaseCatalog = Promise.withResolvers<undefined>()
|
||||
let captured: { status: number; body: string; request: string | null } | undefined
|
||||
let catalogRequests = 0
|
||||
const { scaffold, page, console, first, firstId } = await launchDraftFixture(async (page, scaffold) => {
|
||||
const { scaffold, page, console, firstId } = await launchDraftFixture(async (_page, scaffold) => {
|
||||
for (const name of ['draft-late-original', 'draft-late-current']) {
|
||||
const directory = join(scaffold.workspaceCwd, '.agents', 'skills', name)
|
||||
await mkdir(directory, { recursive: true })
|
||||
@@ -437,27 +457,6 @@ it('rematches the current draft after a delayed real skills catalog without repl
|
||||
].join('\n'))
|
||||
}
|
||||
await writeFile(join(scaffold.workspaceCwd, FILE_NAME), FILE_BODY)
|
||||
let intercepted = false
|
||||
await page.route(url => url.pathname === '/api/skills/list', async (route) => {
|
||||
catalogRequests++
|
||||
if (intercepted) {
|
||||
await route.continue()
|
||||
return
|
||||
}
|
||||
intercepted = true
|
||||
const response = await route.fetch()
|
||||
try {
|
||||
captured = { status: response.status(), body: await response.text(), request: route.request().postData() }
|
||||
await releaseCatalog.promise
|
||||
await route.fulfill({ response })
|
||||
} finally {
|
||||
await response.dispose()
|
||||
}
|
||||
})
|
||||
onTestFinished(async () => {
|
||||
releaseCatalog.resolve(undefined)
|
||||
await page.unrouteAll({ behavior: 'wait' })
|
||||
})
|
||||
})
|
||||
const file = `@"${FILE_NAME}"`
|
||||
const originalPrefix = '/draft-late-original\n'
|
||||
@@ -469,8 +468,33 @@ it('rematches the current draft after a delayed real skills catalog without repl
|
||||
label: FILE_NAME, appearance: 'file', clipboardText: file,
|
||||
}],
|
||||
}
|
||||
await initialize(page, initial, first.id)
|
||||
await writeStoredDrafts(page, [{ sessionId: firstId, draft: initial }])
|
||||
// Only the new document's catalog may wait on this gate; the preceding page has no held routes.
|
||||
await page.goto('about:blank', { waitUntil: 'load' })
|
||||
let intercepted = false
|
||||
await page.route(url => url.pathname === '/api/skills/list', async (route) => {
|
||||
catalogRequests++
|
||||
if (intercepted) {
|
||||
await route.continue()
|
||||
return
|
||||
}
|
||||
intercepted = true
|
||||
const response = await route.fetch()
|
||||
try {
|
||||
captured = { status: response.status(), body: await response.text(), request: route.request().postData() }
|
||||
await releaseCatalog.promise
|
||||
await route.fulfill({ response })
|
||||
} finally {
|
||||
await response.dispose()
|
||||
}
|
||||
})
|
||||
onTestFinished(async () => {
|
||||
releaseCatalog.resolve(undefined)
|
||||
await page.unrouteAll({ behavior: 'wait' })
|
||||
})
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await assertDraft(page, firstId, initial)
|
||||
expect(await composer(page).locator('[data-composer-text-ref]').count()).toBe(0)
|
||||
await composer(page).click()
|
||||
await page.keyboard.press('ControlOrMeta+Home')
|
||||
await page.keyboard.press('End')
|
||||
@@ -499,7 +523,7 @@ it('rematches the current draft after a delayed real skills catalog without repl
|
||||
expect(selection.text).toBe('cd')
|
||||
expect(catalogRequests).toBe(1)
|
||||
await expect.poll(() => composer(page).locator('[data-composer-text-ref]').allTextContents(), SETTLE)
|
||||
.toEqual(['/draft-late-current', '/draft-late-missing'])
|
||||
.toEqual([])
|
||||
|
||||
const delivered = page.waitForResponse(response => new URL(response.url()).pathname === '/api/skills/list')
|
||||
releaseCatalog.resolve(undefined)
|
||||
@@ -526,7 +550,7 @@ it('carries all reference capsules through the real Workspace picker and leaves
|
||||
await writeFile(join(workspace.path, FILE_NAME), FILE_BODY)
|
||||
}
|
||||
const draft = structuredDraft(firstId, '切换工作区携带')
|
||||
await initialize(page, draft, first.id)
|
||||
await restoreStoredDrafts(page, [{ sessionId: firstId, draft }])
|
||||
await assertDraft(page, firstId, draft)
|
||||
await page.getByRole('button', { name: 'Choose workspace', exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: second.title, exact: true }).click()
|
||||
@@ -553,13 +577,18 @@ it('applies a parameter transition matrix to one reusable target without changin
|
||||
const { scaffold, page, console, first, firstId, second } = await launchDraftFixture()
|
||||
const source = structuredDraft(firstId, '源草稿保持不变')
|
||||
const structured = structuredDraft(firstId, '目标结构草稿')
|
||||
const replacement = structuredDraft(firstId, '目标替换草稿')
|
||||
const restored = structuredDraft(firstId, '目标恢复草稿')
|
||||
const replacement = { text: '目标替换文字 🧭', references: [] }
|
||||
const plain = { text: '已有目标文字 🧭', references: [] }
|
||||
await initialize(page, source, first.id)
|
||||
await assertDraft(page, firstId, source)
|
||||
await initialize(page, structured, second.id, true)
|
||||
const literalReferences = { text: structured.text, references: [] }
|
||||
await initialize(page, '', second.id, true)
|
||||
await expect.poll(() => second.sessionIds.length, SETTLE).toBe(1)
|
||||
const secondId = second.sessionIds[0]!
|
||||
await assertDraft(page, secondId, EMPTY)
|
||||
await restoreStoredDrafts(page, [
|
||||
{ sessionId: firstId, draft: source },
|
||||
{ sessionId: secondId, draft: structured },
|
||||
])
|
||||
await assertDraft(page, secondId, structured)
|
||||
|
||||
const transitions: {
|
||||
@@ -567,19 +596,24 @@ it('applies a parameter transition matrix to one reusable target without changin
|
||||
target: 'explicit' | 'current'
|
||||
options: DraftOptions
|
||||
expected: DraftSnapshot
|
||||
restore?: DraftSnapshot
|
||||
reload?: boolean
|
||||
}[] = [
|
||||
{ name: 'nonempty text preserves existing capsules', target: 'current', options: { prompt: 'ignored', clearPreviousDraft: false }, expected: structured },
|
||||
{ name: 'empty text preserves existing capsules', target: 'explicit', options: { prompt: '', clearPreviousDraft: false }, expected: structured },
|
||||
{ name: 'text replaces a nonempty structured draft', target: 'current', options: { prompt: plain.text, clearPreviousDraft: true }, expected: plain, reload: true },
|
||||
{ name: 'structured input preserves existing text', target: 'explicit', options: { prompt: structured, clearPreviousDraft: false }, expected: plain },
|
||||
{ name: 'nonempty text preserves existing text', target: 'explicit', options: { prompt: structured.text, clearPreviousDraft: false }, expected: plain },
|
||||
{ name: 'empty text explicitly clears existing text', target: 'current', options: { prompt: '', clearPreviousDraft: true }, expected: EMPTY },
|
||||
{ name: 'structured input fills a reused empty target', target: 'explicit', options: { prompt: structured, clearPreviousDraft: false }, expected: structured },
|
||||
{ name: 'structured input explicitly replaces capsules', target: 'current', options: { prompt: replacement, clearPreviousDraft: true }, expected: replacement, reload: true },
|
||||
{ name: 'absent prompt and false clear preserve capsules', target: 'explicit', options: { clearPreviousDraft: false }, expected: replacement },
|
||||
{ name: 'reference-like text fills an empty target without creating capsules', target: 'explicit', options: { prompt: structured.text, clearPreviousDraft: false }, expected: literalReferences },
|
||||
{ name: 'nonempty text explicitly replaces existing text', target: 'current', options: { prompt: replacement.text, clearPreviousDraft: true }, expected: replacement, reload: true },
|
||||
{ name: 'absent prompt and false clear preserve restored capsules', target: 'explicit', options: { clearPreviousDraft: false }, expected: restored, restore: restored },
|
||||
{ name: 'empty text explicitly clears capsules', target: 'current', options: { prompt: '', clearPreviousDraft: true }, expected: EMPTY, reload: true },
|
||||
]
|
||||
for (const transition of transitions) {
|
||||
if (transition.restore !== undefined) {
|
||||
await restoreStoredDrafts(page, [{ sessionId: secondId, draft: transition.restore }])
|
||||
await assertDraft(page, secondId, transition.restore)
|
||||
}
|
||||
if (transition.target === 'explicit') {
|
||||
await openWorkspaceSession(page, first, firstId)
|
||||
await assertDraft(page, firstId, source)
|
||||
@@ -609,8 +643,8 @@ it.each(['older-first', 'newer-first'] as const)(
|
||||
const third = await scaffold.ctx.workspaceRegistry.create(thirdPath, 'Draft latest')
|
||||
await page.getByText(third.title, { exact: true }).first().waitFor()
|
||||
const source = structuredDraft(firstId, '交错请求的源草稿')
|
||||
const latest = structuredDraft(firstId, '只有最后目标收到草稿')
|
||||
await initialize(page, source, first.id)
|
||||
const latest = { text: '只有最后目标收到文字草稿 🧭', references: [] }
|
||||
await restoreStoredDrafts(page, [{ sessionId: firstId, draft: source }])
|
||||
await assertDraft(page, firstId, source)
|
||||
|
||||
interface HeldCreation {
|
||||
@@ -658,7 +692,7 @@ it.each(['older-first', 'newer-first'] as const)(
|
||||
const secondId = second.sessionIds[0]!
|
||||
expect(older.response?.body).toContain(secondId)
|
||||
await assertDraft(page, firstId, source)
|
||||
await startSession(page, third.id, { prompt: latest, clearPreviousDraft: true })
|
||||
await startSession(page, third.id, { prompt: latest.text, clearPreviousDraft: true })
|
||||
await expect.poll(() => newer.response?.status, SETTLE).toBe(200)
|
||||
await expect.poll(() => third.sessionIds.length, SETTLE).toBe(1)
|
||||
const thirdId = third.sessionIds[0]!
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/cli
|
||||
import type { InboxState } from '@deepseek-ai/dsh-agent/types'
|
||||
import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
import type { ArbitrateKey, ArbitrateOutcome, DraftInput, Occurrence, ReferenceInsert, TokenSpan } from './draft-editor.ts'
|
||||
import type { ArbitrateKey, ArbitrateOutcome, Occurrence, ReferenceInsert, TokenSpan } from './draft-editor.ts'
|
||||
import type { InputSubmitMode, MessageSubmission } from './composer-submission.ts'
|
||||
|
||||
/** Attachment payload passed to a claimed command submission. */
|
||||
@@ -175,8 +175,8 @@ export interface InputTarget {
|
||||
|
||||
/** Per-session input facade owned by the conversation wiring layer. */
|
||||
export interface SessionInput extends InputTarget {
|
||||
/** Replace the whole draft (persisted-draft seed and programmatic writes). */
|
||||
setDraft(text: DraftInput): void
|
||||
/** Replace the whole draft with plain text, removing inline reference chips. */
|
||||
setDraft(text: string): void
|
||||
/** Append ordered browser-owned attachment ids; busy admission phases refuse. */
|
||||
addAttachments(ids: readonly DraftAttachmentId[]): boolean
|
||||
/** Remove one browser-owned attachment id; busy admission phases refuse. @returns whether the id was removed. */
|
||||
@@ -221,9 +221,9 @@ export interface SessionInputResolver {
|
||||
requestDraftInitialization(binding: SessionBinding, options: DraftInitializationOptions): DraftInitializationResult
|
||||
}
|
||||
|
||||
/** Initial content for a target Session; attachments remain under their existing owner. */
|
||||
/** Initial text for a target Session; attachments remain under their existing owner. */
|
||||
export interface DraftInitializationOptions {
|
||||
readonly prompt?: DraftInput
|
||||
readonly prompt?: string
|
||||
readonly clearPreviousDraft?: boolean
|
||||
}
|
||||
|
||||
@@ -246,8 +246,8 @@ export interface InputActions {
|
||||
* @returns false when the draft changed or submission locked the editor.
|
||||
*/
|
||||
insertText(text: string, span: TokenSpan): boolean
|
||||
/** Replace the whole draft (persisted-draft seed and programmatic writes). */
|
||||
setDraft(text: DraftInput): void
|
||||
/** Replace the whole draft with plain text, removing inline reference chips. */
|
||||
setDraft(text: string): void
|
||||
/** Write the current semantic document through the mounted persistence callback. */
|
||||
persistDraft(): void
|
||||
/** Append ordered browser-owned attachment ids; busy admission phases refuse. */
|
||||
|
||||
@@ -34,10 +34,10 @@ const SLASH_TOKEN_END_RE = /^(?:\s|$)/
|
||||
* Scan the draft for plain-text reference tokens against the hot lexicons.
|
||||
* Word-boundary discipline: the trigger must sit at the draft
|
||||
* start or after whitespace ('x/name' never matches); the name must be an
|
||||
* exact lexicon member when its catalog is available; a `/name` token must end at whitespace or the draft
|
||||
* exact lexicon member; a `/name` token must end at whitespace or the draft
|
||||
* end ('/name/x' is a path, '/name。' is prose).
|
||||
* @param draft - draft text.
|
||||
* @param lexicon - per-trigger name lists; missing slash catalogs allow syntax-only matches.
|
||||
* @param lexicon - per-trigger name lists; missing catalogs match no named tokens.
|
||||
* @returns matched ranges in draft order.
|
||||
*/
|
||||
export function scanTextRefs(
|
||||
@@ -51,7 +51,7 @@ export function scanTextRefs(
|
||||
const trigger = m[2] as '/' | '@'
|
||||
const name = m[3] ?? ''
|
||||
if (trigger === '/' && !SLASH_TOKEN_END_RE.test(draft.slice(m.index + m[0].length))) continue
|
||||
if ((trigger === '/' && !lexicon.has('/')) || lexicon.get(trigger)?.includes(name)) {
|
||||
if (lexicon.get(trigger)?.includes(name)) {
|
||||
const start = m.index + (m[1]?.length ?? 0)
|
||||
out.push({ start, end: start + 1 + name.length, trigger })
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ function projectionContentChanged(prev: EditorProjection, next: EditorProjection
|
||||
|
||||
const EMPTY_QUEUE: InboxState['next-turn'] = []
|
||||
|
||||
/** Unavailable catalogs leave syntax-only text decoration enabled. */
|
||||
/** Unavailable catalogs contain no named text references. */
|
||||
const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map()
|
||||
|
||||
/** Editor and attachment snapshot owned by one detached default send. */
|
||||
@@ -216,8 +216,6 @@ export class SessionInputShell implements SessionInput {
|
||||
* @param text - plain text or the complete semantic document.
|
||||
*/
|
||||
setDraft(text: DraftInput): void {
|
||||
// Catalog resolution can reenter InputHub, which caches this shell before importing its draft.
|
||||
this.refreshLexiconSubscription()
|
||||
const draft = resolveDraftInput(text)
|
||||
if (draft.references.length === 0) this.draftEditor.setDraft(draft.text)
|
||||
else this.draftEditor.restoreDraft(draft.text, draft.references)
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
|
||||
import { createConversationStore } from '../src/client/stores.ts'
|
||||
import type { SessionInputShell } from '../src/client/input/facade.ts'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
|
||||
usePinnedBrowserLanguages('zh-CN')
|
||||
@@ -551,7 +552,8 @@ describe('Conversation inject API', () => {
|
||||
references: [{ source: 'reference', ref: '@one.ts', label: 'one.ts', appearance: 'file' as const,
|
||||
clipboardText: '@one.ts', offset: 6, length: 7 }],
|
||||
}
|
||||
b.inputApi(ROOT).actions.setDraft(draft)
|
||||
const shell = b.inputApi(ROOT).actions as SessionInputShell
|
||||
shell.setDraft(draft)
|
||||
const other = 'structured-target' as SessionId
|
||||
await b.runtime.sessions.add({ id: other, session: {} })
|
||||
b.connectWorkspace.mockResolvedValueOnce(other)
|
||||
|
||||
@@ -53,6 +53,7 @@ function makeShell(overrides: Partial<SessionInputDeps> = {}): SessionInputShell
|
||||
...overrides,
|
||||
})
|
||||
onTestFinished(() => { shell.dispose() })
|
||||
shell.refreshLexiconSubscription()
|
||||
return shell
|
||||
}
|
||||
|
||||
@@ -90,7 +91,7 @@ function expectInitializationBlocked(shell: SessionInputShell): void {
|
||||
const unbind = shell.bindDraftPersistence(write)
|
||||
try {
|
||||
expect(shell.requestDraftInitialization({ clearPreviousDraft: true })).toBe('blocked')
|
||||
expect(shell.requestDraftInitialization({ prompt: documentOf('replacement ', folder), clearPreviousDraft: true })).toBe('blocked')
|
||||
expect(shell.requestDraftInitialization({ prompt: 'replacement @src/', clearPreviousDraft: true })).toBe('blocked')
|
||||
expect(shell.draftSnapshot).toBe(draft)
|
||||
expect(shell.snapshot.attachmentIds).toBe(attachmentIds)
|
||||
expect(chips(shell)).toEqual(references)
|
||||
@@ -308,12 +309,12 @@ describe('draft documents in the input shell', () => {
|
||||
expect(second).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('applies initial structured prompts without waiting for a view', () => {
|
||||
it('applies initial text without waiting for a view or inferring reference chips', () => {
|
||||
const shell = makeShell()
|
||||
const prompt = documentOf('read ', file)
|
||||
const prompt = `read ${file.clipboardText}`
|
||||
expect(shell.requestDraftInitialization({ prompt })).toBe('applied')
|
||||
expect(shell.draftSnapshot).toEqual(prompt)
|
||||
expect(chips(shell)).toHaveLength(1)
|
||||
expect(shell.draftSnapshot).toEqual({ text: prompt, references: [] })
|
||||
expect(chips(shell)).toEqual([])
|
||||
})
|
||||
|
||||
it('preserves existing text or attachments unless target text is explicitly cleared', () => {
|
||||
@@ -468,7 +469,7 @@ describe('draft documents in the input shell', () => {
|
||||
start: 0, end: '/older'.length, draftRev: shell.snapshot.draftRev,
|
||||
})).toBe(true)
|
||||
const draft = shell.draftSnapshot
|
||||
expect(textReferences(shell)).toEqual(['/current'])
|
||||
expect(textReferences(shell)).toEqual([])
|
||||
lexicon.set(new Map([['/', ['older']]]))
|
||||
await vi.waitFor(() => { expect(textReferences(shell)).toEqual([]) })
|
||||
expect(shell.draftSnapshot).toBe(draft)
|
||||
@@ -479,7 +480,11 @@ describe('draft documents in the input shell', () => {
|
||||
expect(chips(shell)).toHaveLength(1)
|
||||
shell.editor.dispatchCommand(UNDO_COMMAND, undefined)
|
||||
await vi.waitFor(() => { expect(shell.draftSnapshot).toEqual(previous) })
|
||||
expect(textReferences(shell)).toEqual(['/older'])
|
||||
// History retains the decoration state saved before the catalog was available.
|
||||
expect(textReferences(shell)).toEqual([])
|
||||
lexicon.set(new Map([['/', ['older', 'current', 'edited']]]))
|
||||
await vi.waitFor(() => { expect(textReferences(shell)).toEqual(['/older']) })
|
||||
expect(shell.draftSnapshot).toEqual(previous)
|
||||
shell.editor.dispatchCommand(REDO_COMMAND, undefined)
|
||||
await vi.waitFor(() => { expect(shell.draftSnapshot).toEqual(current) })
|
||||
expect(textReferences(shell)).toEqual(['/current'])
|
||||
@@ -590,22 +595,22 @@ describe('draft documents in the input shell', () => {
|
||||
})
|
||||
|
||||
describe('plain-text reference catalogs', () => {
|
||||
it('recognizes slash syntax only while its catalog is unavailable', () => {
|
||||
it('leaves named tokens plain until their own catalog includes them', () => {
|
||||
const unavailable = new Map<'/' | '@', readonly string[]>()
|
||||
expect(scanTextRefs('', unavailable)).toEqual([])
|
||||
expect(scanTextRefs('/plan /plan.md /plan/path /plan。 x/plan @person', unavailable)).toEqual([
|
||||
{ start: 0, end: 5, trigger: '/' },
|
||||
])
|
||||
expect(scanTextRefs('/plan /plan.md /plan/path /plan。 x/plan @person', unavailable)).toEqual([])
|
||||
expect(scanTextRefs('/plan @person', new Map([['/', []]]))).toEqual([])
|
||||
expect(scanTextRefs('/plan @person', new Map([['@', ['person']]]))).toEqual([
|
||||
{ start: 0, end: 5, trigger: '/' },
|
||||
{ start: 6, end: 13, trigger: '@' },
|
||||
])
|
||||
expect(scanTextRefs('/plan @person', new Map([['/', ['plan']]]))).toEqual([
|
||||
{ start: 0, end: 5, trigger: '/' },
|
||||
])
|
||||
})
|
||||
|
||||
it('orders folder and catalog references without overlapping ranges', () => {
|
||||
const text = '@src/ /plan @other/ @src/'
|
||||
expect(scanTextRefs(text, new Map([['@', ['src']]]))).toEqual([
|
||||
expect(scanTextRefs(text, new Map([['@', ['src']], ['/', ['plan']]]))).toEqual([
|
||||
{ start: 0, end: 4, trigger: '@' },
|
||||
{ start: 6, end: 11, trigger: '/' },
|
||||
{ start: 12, end: 19, trigger: '@' },
|
||||
|
||||
@@ -115,7 +115,7 @@ class TriggerProvider extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
it('does not resolve input triggers until the first draft initialization', async () => {
|
||||
it('leaves trigger subscription to lifecycle activation rather than construction or draft writes', async () => {
|
||||
const b = await storedSession(saved)
|
||||
const source = catalog(['saved'])
|
||||
const triggers = controller(() => source.source)
|
||||
@@ -134,7 +134,9 @@ it('does not resolve input triggers until the first draft initialization', async
|
||||
|
||||
expect(resolve).not.toHaveBeenCalled()
|
||||
shell.setDraft(saved)
|
||||
expect(resolve).toHaveBeenCalled()
|
||||
expect(source.subscribers).toBe(0)
|
||||
expect(shell.draftSnapshot).toEqual(saved)
|
||||
shell.refreshLexiconSubscription()
|
||||
expect(source.subscribers).toBe(1)
|
||||
expect(shell.draftSnapshot).toEqual(saved)
|
||||
})
|
||||
@@ -169,13 +171,19 @@ it('reuses one shell during synchronous catalog retention and restores its initi
|
||||
await provider.await()
|
||||
|
||||
const first = b.hub.shellFor(b.binding)
|
||||
expect(observed).toBe(true)
|
||||
const initial = first.draftSnapshot
|
||||
expect(initial).toEqual(saved)
|
||||
expect(first.editor.getEditorState().read(() => $nodesOfType(ReferenceChipNode).length)).toBe(1)
|
||||
await vi.waitFor(() => {
|
||||
expect(observed).toBe(true)
|
||||
expect(source.subscribers).toBe(1)
|
||||
})
|
||||
expect(reentered).toHaveLength(1)
|
||||
expect(retained).toHaveLength(1)
|
||||
expect(retained[0]?.binding).toBe(b.binding)
|
||||
expect(new Set([first, ...reentered, b.hub.shellFor(b.binding)]).size).toBe(1)
|
||||
expect(source.subscribers).toBe(1)
|
||||
expect(first.draftSnapshot).toEqual(saved)
|
||||
expect(first.draftSnapshot).toBe(initial)
|
||||
expect(reentered[0]?.draftSnapshot).toBe(first.draftSnapshot)
|
||||
expect(first.editor.getEditorState().read(() => $nodesOfType(ReferenceChipNode).length)).toBe(1)
|
||||
expect(localStorage.getItem(b.key)).toBe(b.raw)
|
||||
@@ -184,7 +192,7 @@ it('reuses one shell during synchronous catalog retention and restores its initi
|
||||
it('restores legacy text before a view and reuses the live draft on later shell lookups', async () => {
|
||||
const b = await fixture('/saved legacy\n🙂 中文')
|
||||
expect(b.shell.draftSnapshot).toEqual({ text: '/saved legacy\n🙂 中文', references: [] })
|
||||
expect(textReferences(b.shell)).toEqual(['/saved'])
|
||||
expect(textReferences(b.shell)).toEqual([])
|
||||
expect(localStorage.getItem(b.key)).toBe(b.raw)
|
||||
b.shell.setDraft('edited before mounting a view')
|
||||
expect(b.hub.shellFor(b.binding)).toBe(b.shell)
|
||||
@@ -196,6 +204,7 @@ it('restores legacy text before a view and reuses the live draft on later shell
|
||||
it('imports reference chips on the first Hub shell and preserves them without an explicit clear', async () => {
|
||||
const b = await fixture(saved)
|
||||
expect(b.shell.draftSnapshot).toEqual(saved)
|
||||
expect(textReferences(b.shell)).toEqual([])
|
||||
expect(b.shell.editor.getEditorState().read(() => $nodesOfType(ReferenceChipNode).length)).toBe(1)
|
||||
expect(b.hub.requestDraftInitialization(b.binding, { prompt: 'new text' })).toBe('preserved')
|
||||
expect(b.shell.draftSnapshot).toEqual(saved)
|
||||
@@ -209,7 +218,7 @@ it('subscribes when a provider arrives and disconnects each withdrawn provider',
|
||||
start: 0, end: '/saved'.length, draftRev: b.shell.snapshot.draftRev,
|
||||
})).toBe(true)
|
||||
const current = b.shell.draftSnapshot
|
||||
expect(textReferences(b.shell)).toEqual(['/current'])
|
||||
expect(textReferences(b.shell)).toEqual([])
|
||||
const first = catalog([])
|
||||
const firstProvider = b.ctx.plugin(TriggerProvider, { controller: controller(() => first.source) })
|
||||
await firstProvider.await()
|
||||
@@ -221,7 +230,10 @@ it('subscribes when a provider arrives and disconnects each withdrawn provider',
|
||||
first.set(['current'])
|
||||
await vi.waitFor(() => { expect(textReferences(b.shell)).toEqual(['/current']) })
|
||||
await firstProvider.dispose()
|
||||
expect(first.subscribers).toBe(0)
|
||||
await vi.waitFor(() => {
|
||||
expect(first.subscribers).toBe(0)
|
||||
expect(textReferences(b.shell)).toEqual([])
|
||||
})
|
||||
expect(first.releases).toBe(first.subscriptions)
|
||||
expect(b.sessions.binding(b.id)).toBe(b.binding)
|
||||
expect(b.hub.shellFor(b.binding)).toBe(b.shell)
|
||||
@@ -238,7 +250,10 @@ it('subscribes when a provider arrives and disconnects each withdrawn provider',
|
||||
second.set(['current'])
|
||||
await vi.waitFor(() => { expect(textReferences(b.shell)).toEqual(['/current']) })
|
||||
await secondProvider.dispose()
|
||||
expect(second.subscribers).toBe(0)
|
||||
await vi.waitFor(() => {
|
||||
expect(second.subscribers).toBe(0)
|
||||
expect(textReferences(b.shell)).toEqual([])
|
||||
})
|
||||
expect(second.releases).toBe(second.subscriptions)
|
||||
expect(b.shell.draftSnapshot).toBe(current)
|
||||
expect(b.sessions.binding(b.id)).toBe(b.binding)
|
||||
|
||||
@@ -136,6 +136,10 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo
|
||||
const serialize = vi.fn((ids: readonly DraftAttachmentId[]) => Promise.resolve(ids.map(() => PNG)))
|
||||
const release = vi.fn()
|
||||
const shell = new SessionInputShell({ actx, inputTriggers: () => controller, defaultSink: sink, commandAttachments: { serialize, release, unsupportedNotice: (token: string) => `${token.trim()} attachments-unsupported` } })
|
||||
actx.effect(() => {
|
||||
shell.refreshLexiconSubscription()
|
||||
return () => { shell.dispose() }
|
||||
}, 'test input shell')
|
||||
// The hub's listener wiring, verbatim.
|
||||
actx.on('slash/input-begin-command', req => shell.beginCommand(req.claim, req.span) ? true : undefined)
|
||||
actx.on('slash/input-insert-reference', req => shell.insertReference(req.reference, req.span) ? true : undefined)
|
||||
@@ -355,7 +359,7 @@ describe('scenario H: backspace breaks the token', () => {
|
||||
})
|
||||
|
||||
describe('scenario: reference decoration follows the current lexicon', () => {
|
||||
it('keeps provisional slash decoration for a matching catalog and removes it for an empty catalog', async () => {
|
||||
it('decorates only the current text when its catalog arrives and clears decoration for an empty catalog', async () => {
|
||||
let roll: readonly string[] | undefined
|
||||
let notify: (() => void) | undefined
|
||||
const b = await scopedBench((inputTriggers) => {
|
||||
@@ -370,22 +374,31 @@ describe('scenario: reference decoration follows the current lexicon', () => {
|
||||
},
|
||||
} as never)
|
||||
})
|
||||
b.type('/older now')
|
||||
expect(b.view.container.querySelector('[data-composer-text-ref]')).toBeNull()
|
||||
b.type('/deploy now')
|
||||
expect(b.view.container.querySelector('[data-composer-text-ref]')?.textContent).toBe('/deploy')
|
||||
// The catalog settles (ui-skill's settle path fires the same notification).
|
||||
const draft = b.shell.draftSnapshot
|
||||
expect(b.view.container.querySelector('[data-composer-text-ref]')).toBeNull()
|
||||
act(() => {
|
||||
roll = ['deploy']
|
||||
roll = ['older']
|
||||
notify?.()
|
||||
})
|
||||
act(() => { b.shell.editor.update(() => {}, { discrete: true }) }) // flush the queued re-scan
|
||||
const mark = b.view.container.querySelector('[data-composer-text-ref]')
|
||||
expect(mark?.textContent).toBe('/deploy')
|
||||
expect(b.controller.lexicon.getSnapshot().get('/')).toEqual(['older'])
|
||||
expect(b.view.container.querySelector('[data-composer-text-ref]')).toBeNull()
|
||||
act(() => {
|
||||
roll = ['older', 'deploy']
|
||||
notify?.()
|
||||
})
|
||||
await vi.waitFor(() => {
|
||||
expect(b.view.container.querySelector('[data-composer-text-ref]')?.textContent).toBe('/deploy')
|
||||
})
|
||||
expect(b.shell.draftSnapshot).toBe(draft)
|
||||
act(() => {
|
||||
roll = []
|
||||
notify?.()
|
||||
})
|
||||
act(() => { b.shell.editor.update(() => {}, { discrete: true }) })
|
||||
expect(b.view.container.querySelector('[data-composer-text-ref]')).toBeNull()
|
||||
await vi.waitFor(() => { expect(b.view.container.querySelector('[data-composer-text-ref]')).toBeNull() })
|
||||
expect(b.shell.draftSnapshot).toBe(draft)
|
||||
expect(b.shell.snapshot.draft).toBe('/deploy now')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -362,9 +362,10 @@ describe('decorations: scanTextRefs', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('matches slash syntax while the catalog is unavailable and narrows when it arrives', () => {
|
||||
expect(scanTextRefs('/goal x', new Map())).toEqual([{ start: 0, end: 5, trigger: '/' }])
|
||||
it('matches slash names only after their catalog is available', () => {
|
||||
expect(scanTextRefs('/goal x', new Map())).toEqual([])
|
||||
expect(scanTextRefs('/goal x', new Map([['/', []]]))).toEqual([])
|
||||
expect(scanTextRefs('/goal x', new Map([['/', ['goal']]]))).toEqual([{ start: 0, end: 5, trigger: '/' }])
|
||||
})
|
||||
|
||||
it('recognizes directory paths independently of the dynamic lexicon', () => {
|
||||
|
||||
@@ -227,7 +227,7 @@ class UiWorkspaceService extends Service implements UiWorkspace {
|
||||
}
|
||||
|
||||
startSession(workspaceId?: WorkspaceId, options?: StartSessionOptions): void {
|
||||
const draftOptions = options === undefined ? undefined : structuredClone(options)
|
||||
const draftOptions = options === undefined ? undefined : { ...options }
|
||||
const initializeDraft = draftOptions !== undefined
|
||||
&& (draftOptions.prompt !== undefined || draftOptions.clearPreviousDraft === true)
|
||||
const workspace = this.workspaces.list.getSnapshot()
|
||||
|
||||
@@ -761,18 +761,7 @@ describe('UiWorkspaceService', () => {
|
||||
{ name: 'plain text', options: { prompt: '草稿 🧭\nsecond line', clearPreviousDraft: true } },
|
||||
{ name: 'empty text', options: { prompt: '' } },
|
||||
{ name: 'clear without prompt', options: { clearPreviousDraft: true } },
|
||||
{
|
||||
name: 'structured references',
|
||||
options: {
|
||||
prompt: {
|
||||
text: '🧭 @notes.md',
|
||||
references: [{
|
||||
offset: 3, length: 9, source: 'reference', ref: '@notes.md', label: 'notes.md',
|
||||
appearance: 'file', clipboardText: '@notes.md',
|
||||
}],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ name: 'reference-like text', options: { prompt: '🧭 @notes.md' } },
|
||||
])('prepares $name on the retained target before replacing the current selection', async ({ options }) => {
|
||||
const backing = persistSelection({})
|
||||
const b = bench({ workspaces: workspaceState([workspace('a')]) })
|
||||
@@ -835,32 +824,23 @@ describe('UiWorkspaceService', () => {
|
||||
expect(b.notify).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('captures options and nested references before asynchronous Session creation', async () => {
|
||||
it('captures prompt text and clear intent before asynchronous Session creation', async () => {
|
||||
const b = bench({ workspaces: workspaceState([workspace('a')]) })
|
||||
const created = Promise.withResolvers<SessionId>()
|
||||
b.sessions.create.mockReturnValueOnce(created.promise)
|
||||
const opening = vi.spyOn(b.uiWorkspace, 'openWorkspace')
|
||||
const options = {
|
||||
prompt: {
|
||||
text: '🧭 @notes.md',
|
||||
references: [{
|
||||
offset: 3, length: 9, source: 'reference', ref: '@notes.md', label: 'notes.md',
|
||||
appearance: 'file' as const, clipboardText: '@notes.md',
|
||||
}],
|
||||
},
|
||||
prompt: '🧭 @notes.md',
|
||||
clearPreviousDraft: true,
|
||||
}
|
||||
const expected = structuredClone(options)
|
||||
const expected = { ...options }
|
||||
b.uiWorkspace.startSession(wid('a'), options)
|
||||
const completion = lastOpening(opening)
|
||||
expect(b.sessions.create).toHaveBeenCalledOnce()
|
||||
expect(b.requestDraftInitialization).not.toHaveBeenCalled()
|
||||
|
||||
options.clearPreviousDraft = false
|
||||
options.prompt.text = 'caller changed the text'
|
||||
options.prompt.references[0]!.label = 'caller changed the reference'
|
||||
options.prompt.references.length = 0
|
||||
options.prompt = { text: 'caller replaced the prompt', references: [] }
|
||||
options.prompt = 'caller replaced the prompt'
|
||||
created.resolve(sid('captured'))
|
||||
await completion
|
||||
|
||||
|
||||
@@ -581,19 +581,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'DraftInitializationOptions',
|
||||
declaration: 'export interface DraftInitializationOptions {\n readonly prompt?: DraftInput;\n readonly clearPreviousDraft?: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'DraftInput',
|
||||
declaration: 'export type DraftInput = string | DraftSnapshot;',
|
||||
},
|
||||
{
|
||||
name: 'DraftReference',
|
||||
declaration: 'export type DraftReference = Omit<Occurrence, \'occurrenceId\'>;',
|
||||
},
|
||||
{
|
||||
name: 'DraftSnapshot',
|
||||
declaration: 'export interface DraftSnapshot {\n readonly text: string;\n readonly references: readonly DraftReference[];\n}',
|
||||
declaration: 'export interface DraftInitializationOptions {\n readonly prompt?: string;\n readonly clearPreviousDraft?: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'EntryKeyOf',
|
||||
@@ -723,10 +711,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ObservableSnapshot',
|
||||
declaration: 'export interface ObservableSnapshot<T> {\n getSnapshot(): T;\n subscribe(fn: () => void): () => void;\n}',
|
||||
},
|
||||
{
|
||||
name: 'Occurrence',
|
||||
declaration: 'export interface Occurrence {\n readonly occurrenceId: number;\n readonly source: string;\n readonly ref: string;\n readonly offset: number;\n readonly length: number;\n readonly label: string;\n readonly appearance?: ReferenceInsert[\'appearance\'];\n readonly clipboardText: string;\n readonly invalid?: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'OpenState',
|
||||
declaration: 'export type OpenState = \'cold\' | \'loading\' | \'open\' | \'error\';',
|
||||
@@ -811,10 +795,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'QueueAction',
|
||||
declaration: 'export type QueueAction = {\n readonly kind: \'edit\';\n readonly content: readonly TextBlock[];\n} | {\n readonly kind: \'remove\';\n} | {\n readonly kind: \'steer\';\n};',
|
||||
},
|
||||
{
|
||||
name: 'ReferenceInsert',
|
||||
declaration: 'export interface ReferenceInsert {\n readonly source: string;\n readonly ref: string;\n readonly label: string;\n readonly appearance?: \'session\' | \'file\' | \'folder\';\n readonly clipboardText: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'RegisterFactory',
|
||||
declaration: 'export interface RegisterFactory {\n <F extends keyof SlotFactoryMap & string>(options: RegisterFactoryOptions<F>, component: SlotComponent<FactoryComponentPropsOf<F>>): () => void;\n}',
|
||||
|
||||
@@ -40,16 +40,19 @@ describe('Client Cordis inspect catalog', () => {
|
||||
expect(new Set(names).size).toBe(names.length)
|
||||
})
|
||||
|
||||
it('describes initial content and structured references in Workspace navigation', () => {
|
||||
it('describes text-only draft initialization in Workspace navigation', () => {
|
||||
const result = queryServiceApi('uiWorkspace') as {
|
||||
referencedTypes: readonly { name: string; declaration: string }[]
|
||||
}
|
||||
expect(result.referencedTypes.find(type => type.name === 'StartSessionOptions')?.declaration)
|
||||
.toContain('DraftInitializationOptions')
|
||||
expect(result.referencedTypes.find(type => type.name === 'DraftInitializationOptions')?.declaration)
|
||||
.toContain('readonly prompt?: DraftInput')
|
||||
expect(result.referencedTypes.find(type => type.name === 'DraftSnapshot')?.declaration)
|
||||
.toContain('readonly references: readonly DraftReference[]')
|
||||
.toContain('readonly prompt?: string')
|
||||
expect(result.referencedTypes.find(type => type.name === 'DraftInitializationOptions')?.declaration)
|
||||
.toContain('readonly clearPreviousDraft?: boolean')
|
||||
expect(result.referencedTypes.map(type => type.name)).not.toEqual(expect.arrayContaining([
|
||||
'DraftInput', 'DraftSnapshot', 'DraftReference',
|
||||
]))
|
||||
})
|
||||
|
||||
it('includes the current referenced type closure for the Sessions service', () => {
|
||||
|
||||
Reference in new issue
Block a user