DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ui): 大段粘贴折叠成引用 chip,发送时还原原文
hairyf3ba41572aea4
diff --git a/packages/dsh-tauri-ui/src/client/constants/index.ts b/packages/dsh-tauri-ui/src/client/constants/index.tsindex 613a9ccc..4c9654a7 100644--- a/packages/dsh-tauri-ui/src/client/constants/index.ts+++ b/packages/dsh-tauri-ui/src/client/constants/index.ts@@ -52,6 +52,12 @@ export const UNGROUPED_ROW_KEY = 'workspace:'/** dsh-im 客户端插件经 `ctx.provide` 发布的反射服务名(4.22.0 起)。 */export const DSH_IM_CLIENT_SERVICE = 'dshImClient'+/**+ * 折叠粘贴的引用源名:既是官方引用注册表里的唯一键,也是官方 chip 宿主元素写的+ * `data-composer-chip` 值(C 浏览器层的断言锚点)。+ */+export const PASTE_CHIP_SOURCE = `${PLUGIN_ID}-paste`+export const STYLES_EFFECT = `${PLUGIN_ID}: styles`export const LOCALE_EFFECT = `${PLUGIN_ID}: locale`export const SEAT_EFFECT = `${PLUGIN_ID}: shell.overlay seat`@@ -62,6 +68,7 @@ export const IM_PANEL_EFFECT = `${PLUGIN_ID}: im panel`export const HERO_WORKSPACE_EFFECT = `${PLUGIN_ID}: hero workspace picker`export const NEW_SESSION_EFFECT = `${PLUGIN_ID}: sidebar new session`export const UNGROUPED_NEW_SESSION_EFFECT = `${PLUGIN_ID}: sidebar ungrouped new session`+export const PASTE_COLLAPSE_EFFECT = `${PLUGIN_ID}: paste collapse`export const TURN_NAVIGATION_LABEL_ZH = '轮次导航'export const TURN_NAVIGATION_LABEL_EN = 'Turn navigation'diff --git a/packages/dsh-tauri-ui/src/client/index.ts b/packages/dsh-tauri-ui/src/client/index.tsindex c83bdf50..c827e6b0 100644--- a/packages/dsh-tauri-ui/src/client/index.ts+++ b/packages/dsh-tauri-ui/src/client/index.ts@@ -1,13 +1,14 @@import type {} from '@deepseek-ai/dsh-client-ui-layout/client'import type { ClientContext } from 'dsh-tauri/client'import { PLUGIN_ID } from '../shared/constants'-import { HERO_WORKSPACE_EFFECT, IM_PANEL_EFFECT, LOCALE_EFFECT, NEW_SESSION_EFFECT, OBSTRUCTIONS_EFFECT, SEAT_EFFECT, SECTIONS_EFFECT, SETTINGS_EFFECT, STYLES_EFFECT, UNGROUPED_NEW_SESSION_EFFECT } from './constants'+import { HERO_WORKSPACE_EFFECT, IM_PANEL_EFFECT, LOCALE_EFFECT, NEW_SESSION_EFFECT, OBSTRUCTIONS_EFFECT, PASTE_COLLAPSE_EFFECT, SEAT_EFFECT, SECTIONS_EFFECT, SETTINGS_EFFECT, STYLES_EFFECT, UNGROUPED_NEW_SESSION_EFFECT } from './constants'import { locale } from './locales'import { composerResumeFeature } from './register/composer-resume'import { heroWorkspaceFeature } from './register/hero-workspace'import { registerImPanel } from './register/im-panel'import { sidebarNewSessionFeature, ungroupedNewSessionFeature } from './register/new-session'import { registerSettingsObstructions } from './register/obstructions'+import { pasteCollapseFeature } from './register/paste-collapse'import { registerShellSeat } from './register/seat'import { registerSettingsSections } from './register/sections'import { registerSettings } from './register/settings'@@ -53,5 +54,6 @@ export function apply(ctx: ClientContext): void {ctx.effect(sidebarNewSessionFeature, NEW_SESSION_EFFECT)ctx.effect(ungroupedNewSessionFeature, UNGROUPED_NEW_SESSION_EFFECT)ctx.effect(composerResumeFeature, COMPOSER_RESUME_EFFECT)+ ctx.effect(pasteCollapseFeature, PASTE_COLLAPSE_EFFECT)ctx.effect(registerImPanel, IM_PANEL_EFFECT)}diff --git a/packages/dsh-tauri-ui/src/client/locales/index.ts b/packages/dsh-tauri-ui/src/client/locales/index.tsindex 39b85e81..b4ff6167 100644--- a/packages/dsh-tauri-ui/src/client/locales/index.ts+++ b/packages/dsh-tauri-ui/src/client/locales/index.ts@@ -11,6 +11,8 @@ export const locale = defineLocale(PLUGIN_ID, {im: 'IM',chooseWorkspace: '选择工作区',ungrouped: '未分组',+ pasteChip: '粘贴的文本 · {count} 字',+ pasteChipTitled: '{title} · {count} 字',addWorkspace: '添加工作区…',close: '关闭',cancel: '取消',@@ -59,6 +61,8 @@ export const locale = defineLocale(PLUGIN_ID, {im: 'IM',chooseWorkspace: 'Choose workspace',ungrouped: 'Ungrouped',+ pasteChip: 'Pasted text · {count} chars',+ pasteChipTitled: '{title} · {count} chars',addWorkspace: 'Add workspace…',close: 'Close',cancel: 'Cancel',diff --git a/packages/dsh-tauri-ui/src/client/register/paste-collapse.register.test.ts b/packages/dsh-tauri-ui/src/client/register/paste-collapse.register.test.tsnew file mode 100644index 00000000..1f566cf1--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/paste-collapse.register.test.ts@@ -0,0 +1,324 @@+import type { PasteReferenceInsert, PasteTokenSpan } from './paste-collapse.types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { pasteCollapseFeature } from './paste-collapse'++/**+ * 折叠粘贴的注册层契约:占位 chip 的插入参数、正文的双向(草稿投影 + 模型序列化)与+ * 「任何一环缺席都不接管」的退级。仓库未装 jsdom,DOM 用最小替身提供。+ */++const PASTE_SOURCE = 'dsh-tauri-ui-paste'+const LONG_TEXT = `### 环境信息 app:版本 1.0\n${'日志行'.repeat(200)}`++interface ControllerStub {+ paste: (event: unknown) => void+ dispose: () => void+}++const mocks = vi.hoisted(() => ({+ adapter: {} as Record<string, unknown>,+ controller: undefined as unknown,+ text: vi.fn((key: string) => key),+}))++vi.mock('dsh-tauri/client', () => {+ const defineLocale = (namespace: string) => ({+ NS: namespace,+ text: mocks.text,+ activeLocale: () => 'zh',+ isEnglishLocale: () => false,+ useLocale: () => 'zh',+ registerLocale: () => () => {},+ })+ const createLifecycleController = () => {+ const disposers: Array<() => void> = []+ let pasteHandler: ((event: unknown) => void) | undefined+ return {+ add: (disposer: () => void) => {+ disposers.push(disposer)+ },+ listen: (_type: string, handler: (event: unknown) => void) => {+ pasteHandler = handler+ return () => {}+ },+ observe: () => ({ disconnect: () => {} }),+ isDisposed: () => false,+ dispose: () => {+ for (const disposer of [...disposers])+ disposer()+ disposers.length = 0+ },+ paste: (event: unknown) => pasteHandler?.(event),+ }+ }+ return {+ defineLocale,+ createLifecycleController,+ defineRegister: (ctxOrSetup: unknown, maybeSetup?: unknown) => {+ const setup = (typeof maybeSetup === 'function' ? maybeSetup : ctxOrSetup) as+ (controller: unknown, ctx: unknown, adapter: unknown) => void+ return function registerEffect(this: unknown) {+ const controller = createLifecycleController()+ mocks.controller = controller+ setup(controller, this, mocks.adapter)+ return () => controller.dispose()+ }+ },+ }+})++class FakeElement {+ closest: (selector: string) => unknown = () => null+}++function snapshotSource<T>(initial: T) {+ let state = initial+ const listeners = new Set<() => void>()+ return {+ getSnapshot: () => state,+ subscribe: (listener: () => void) => {+ listeners.add(listener)+ return () => listeners.delete(listener)+ },+ publish: (next: T) => {+ state = next+ for (const listener of [...listeners])+ listener()+ },+ }+}++interface HarnessOptions {+ insertable?: boolean+ retained?: boolean+ triggersAvailable?: boolean+ /** 模拟 `0.1.5-rc.x`:动作面没有 captureInsertion,只有壳自身的 caretSpan。 */+ legacyActions?: boolean+}++function harness(options: HarnessOptions = {}) {+ const occurrences = snapshotSource<{ draftRev?: number, occurrences?: readonly { source?: string, ref?: string }[] }>({+ draftRev: 7,+ occurrences: [],+ })+ const span: PasteTokenSpan = { start: 3, end: 3, draftRev: 7 }+ const insertReference = vi.fn((_reference: PasteReferenceInsert, _span: PasteTokenSpan) => options.insertable ?? true)+ const sessionInput = {+ insertReference,+ state: occurrences,+ ...options.legacyActions === true ? { caretSpan: () => ({ start: 5, end: 5 }) } : {},+ }+ const list = snapshotSource({ current: 's-1' as string | undefined })+ const binding = vi.fn((id: string) =>+ id === 's-1' && options.retained !== false ? { ctx: { scope: id } } : undefined)+ const provideInfo = vi.fn(() => ({+ props: { inputActions: options.legacyActions === true ? {} : { captureInsertion: () => span } },+ }))+ const registered: { source?: { name?: string, trigger?: string, codec?: { clipboardText: (ref: string) => string, serialize: (ref: string, signal: AbortSignal) => Promise<string> } } } = {}+ const triggers = {+ registerSource: vi.fn((source: unknown) => {+ registered.source = source as typeof registered.source+ return () => {}+ }),+ }++ mocks.adapter.sessions = { list, binding, provideInfo }+ mocks.adapter.service = (name: string) => {+ if (name === 'conversation')+ return { input: { for: () => sessionInput } }+ if (name === 'inputTriggers')+ return options.triggersAvailable === false ? undefined : triggers+ return undefined+ }++ Object.assign(globalThis, { document: {}, Element: FakeElement })+ mocks.text.mockClear()++ const ctx = { inject: (_deps: readonly string[], callback: () => undefined | (() => void)) => callback() }+ const register = pasteCollapseFeature as unknown as (this: unknown) => () => void+ const cleanup = register.call(ctx)++ return {+ span,+ insertReference,+ occurrences,+ binding,+ provideInfo,+ triggers,+ triggerSource: () => registered.source,+ setCurrentSession: (sessionId: string | undefined) => list.publish({ current: sessionId }),+ paste: (event: unknown) => (mocks.controller as ControllerStub).paste(event),+ cleanup,+ }+}++function pasteEvent(options: {+ text?: string+ files?: number+ inComposer?: boolean+ defaultPrevented?: boolean+} = {}) {+ const target = new FakeElement()+ target.closest = (selector: string) => options.inComposer === false+ ? null+ : (selector === '[data-composer-card]' ? {} : null)+ return {+ clipboardData: {+ items: Array.from({ length: options.files ?? 0 }, () => ({ kind: 'file' })),+ getData: () => options.text ?? LONG_TEXT,+ },+ target,+ defaultPrevented: options.defaultPrevented ?? false,+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ }+}++beforeEach(() => {+ vi.useFakeTimers({ now: 0 })+})++afterEach(() => {+ vi.useRealTimers()+ delete mocks.adapter.sessions+ delete mocks.adapter.service+})++describe('pasteCollapseFeature', () => {+ it('超过 500 字的粘贴插入引用 chip,label 带首行与字数,正文随 chip 一起被 codec 还原', async () => {+ const h = harness()+ const event = pasteEvent()++ h.paste(event)++ expect(h.insertReference, '长文本必须走 chip 插入,而不是把原文灌进编辑器').toHaveBeenCalledTimes(1)+ const [insert, span] = h.insertReference.mock.calls[0]!+ expect(insert.source, 'chip 必须归属于本插件注册的引用源,否则发送时找不到 codec').toBe(PASTE_SOURCE)+ expect(insert.ref, 'ref 必须是本插件签发的标识').toMatch(new RegExp(`^${PASTE_SOURCE}-\\d+$`))+ expect(insert.appearance, 'chip 用文档图标').toBe('file')+ expect(insert.clipboardText, '草稿投影与原生复制必须是正文原文').toBe(LONG_TEXT)+ expect(mocks.text, 'label 走本地化文案,带首行与字数').toHaveBeenCalledWith('pasteChipTitled', {+ title: '### 环境信息 app:版本 1.0',+ count: LONG_TEXT.length,+ })+ expect(insert.label).toBe('pasteChipTitled')+ expect(span, '插入位置取自标准动作面的选区快照').toBe(h.span)++ expect(event.preventDefault, '接管后必须阻止浏览器默认插入').toHaveBeenCalledTimes(1)+ expect(event.stopPropagation, '接管后必须挡住官方的 paste 命令').toHaveBeenCalledTimes(1)++ const codec = h.triggerSource()?.codec+ expect(codec, '模型序列化依赖注册的引用源 codec').toBeDefined()+ await expect(codec!.serialize(insert.ref, new AbortController().signal)).resolves.toBe(LONG_TEXT)+ expect(codec!.clipboardText(insert.ref), '剪贴板/持久化投影同样是正文').toBe(LONG_TEXT)+ h.cleanup()+ })++ it('恰好 500 字的粘贴不接管:阈值是「超过」', () => {+ const h = harness()+ const event = pasteEvent({ text: 'x'.repeat(500) })++ h.paste(event)++ expect(h.insertReference, '恰好 500 字必须走官方粘贴路径').not.toHaveBeenCalled()+ expect(event.preventDefault).not.toHaveBeenCalled()+ h.cleanup()+ })++ it('带文件的粘贴不接管:文件入草稿由官方路径负责', () => {+ const h = harness()+ const event = pasteEvent({ files: 1 })++ h.paste(event)++ expect(h.insertReference).not.toHaveBeenCalled()+ expect(event.preventDefault).not.toHaveBeenCalled()+ h.cleanup()+ })++ it('composer 卡片之外的粘贴不接管', () => {+ const h = harness()+ const event = pasteEvent({ inComposer: false })++ h.paste(event)++ expect(h.binding, '非 composer 落点连会话都不必解析').not.toHaveBeenCalled()+ expect(h.insertReference).not.toHaveBeenCalled()+ expect(event.preventDefault).not.toHaveBeenCalled()+ h.cleanup()+ })++ it('chip 插入失败时不接管,也不留下无处引用的正文', () => {+ const h = harness({ insertable: false })+ const event = pasteEvent()++ h.paste(event)++ expect(h.insertReference).toHaveBeenCalledTimes(1)+ expect(event.preventDefault, '插入失败必须放行官方路径,绝不吞掉用户的粘贴').not.toHaveBeenCalled()+ const [insert] = h.insertReference.mock.calls[0]!+ expect(h.triggerSource()?.codec?.clipboardText(insert.ref), '失败插入的正文必须回滚').toBe('')+ h.cleanup()+ })++ it('草稿中已删除的 chip 过宽限期后回收正文,序列化报错而不是静默降级成空文本', async () => {+ const h = harness()+ h.paste(pasteEvent())+ const [insert] = h.insertReference.mock.calls[0]!+ const codec = h.triggerSource()!.codec!++ vi.setSystemTime(3000)+ h.occurrences.publish({ occurrences: [] })++ expect(codec.clipboardText(insert.ref), '正文必须随 chip 删除一起回收').toBe('')+ await expect(codec.serialize(insert.ref, new AbortController().signal)).rejects.toThrow(/已不在内存中/)+ h.cleanup()+ })++ it('宽限期内草稿投影尚未包含该 chip 时不回收正文', async () => {+ const h = harness()+ h.paste(pasteEvent())+ const [insert] = h.insertReference.mock.calls[0]!+ const codec = h.triggerSource()!.codec!++ h.occurrences.publish({ occurrences: [] })++ await expect(codec.serialize(insert.ref, new AbortController().signal)).resolves.toBe(LONG_TEXT)+ h.cleanup()+ })++ it('0.1.5-rc.x 动作面没有 captureInsertion 时退回壳自身的 caretSpan,chip 仍插在光标处', () => {+ const h = harness({ legacyActions: true })+ const event = pasteEvent()++ h.paste(event)++ expect(h.insertReference, '旧基线的折叠同样必须生效').toHaveBeenCalledTimes(1)+ expect(h.insertReference.mock.calls[0]![1], '快照由 caretSpan + state.draftRev 组成').toEqual({ start: 5, end: 5, draftRev: 7 })+ expect(event.preventDefault).toHaveBeenCalledTimes(1)+ h.cleanup()+ })++ it('引用源缺席(无 inputTriggers 服务)时不接管粘贴', () => {+ const h = harness({ triggersAvailable: false })+ const event = pasteEvent()++ h.paste(event)++ expect(h.triggers.registerSource, '服务缺席时不得注册半截引用源').not.toHaveBeenCalled()+ expect(h.insertReference).not.toHaveBeenCalled()+ expect(event.preventDefault).not.toHaveBeenCalled()+ h.cleanup()+ })++ it('会话未被保留(拿不到会话作用域)时不接管粘贴', () => {+ const h = harness({ retained: false })+ const event = pasteEvent()++ h.paste(event)++ expect(h.insertReference).not.toHaveBeenCalled()+ expect(event.preventDefault).not.toHaveBeenCalled()+ h.cleanup()+ })+})diff --git a/packages/dsh-tauri-ui/src/client/register/paste-collapse.ts b/packages/dsh-tauri-ui/src/client/register/paste-collapse.tsnew file mode 100644index 00000000..cd354556--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/paste-collapse.ts@@ -0,0 +1,150 @@+import type { ClientContext } from 'dsh-tauri/client'+import type {+ PasteConversationService,+ PasteSessionInput,+ PasteSessionServices,+ PasteTriggerRegistry,+} from './paste-collapse.types'+import { defineRegister } from 'dsh-tauri/client'+import { PLUGIN_ID } from '../../shared/constants'+import { PASTE_CHIP_SOURCE } from '../constants'+import { locale } from '../locales'+import { clipboardFileCount, isCollapsiblePaste, livePasteRefs, pasteChipTitle, resolveInsertionSpan, stalePasteRefs } from './paste-collapse.utils'++/**+ * 大段粘贴(>500 字)折叠成官方引用 chip:编辑器里只留一枚 `首行… · N 字` 的 chip,+ * 发送时由本插件注册的 codec 把正文还原给模型,Backspace 整块删除。+ *+ * 走官方公开面(退级阶梯第 1 级),不改内核产物:+ * - `ctx.inputTriggers.registerSource` 注册 chip 所属的引用源与其 codec(clipboardText 即正文,+ * 草稿投影、原生复制、持久化镜像都拿得到原文;模型侧由 codec.serialize 还原);+ * - `ctx.conversation.input.for(actx)` 在光标处插入 chip(官方 picks 用的是同一条通路);+ * - `sessions.provideInfo().props.inputActions.captureInsertion()` 取带修订号的选区快照+ * (`0.1.5-rc.x` 的动作面还没有它,退回壳自身的 `caretSpan()` + `state.draftRev`)。+ *+ * 任何一环缺席都不接管:官方 paste 路径照常把原文插入编辑器(退级第 4 级),绝不吞掉粘贴。+ * 文本落点判定只认官方 `[data-composer-card]`。+ */+const COMPOSER_CARD_SELECTOR = '[data-composer-card]'+const INPUT_TRIGGERS_SERVICE = 'inputTriggers'+const CONVERSATION_SERVICE = 'conversation'++/** chip 插入后草稿投影才发布,宽限期内把「未引用」当成已删除会连正文一起扔掉。 */+const PASTE_STASH_GRACE_MS = 2000++export const pasteCollapseFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {+ if (typeof document === 'undefined')+ return++ const stash = new Map<string, { text: string, at: number }>()+ let seq = 0+ let ready = false+ let watchedSessionId: string | undefined+ let unwatchState: (() => void) | undefined++ const sessions = (): PasteSessionServices => adapter.sessions as unknown as PasteSessionServices++ const chipLabel = (text: string): string => {+ const title = pasteChipTitle(text)+ return title === ''+ ? locale.text('pasteChip', { count: text.length })+ : locale.text('pasteChipTitled', { title, count: text.length })+ }++ const sessionInputOf = (sessionId: string): PasteSessionInput | undefined => {+ const scope = sessions().binding?.(sessionId)?.ctx+ if (scope === undefined)+ return undefined+ try {+ return adapter.service<PasteConversationService>(CONVERSATION_SERVICE)?.input?.for(scope)+ }+ catch {+ // 未被保留的会话拿不到输入面:按不可用处理,退回官方粘贴路径。+ return undefined+ }+ }++ const prune = (input: PasteSessionInput): void => {+ const live = livePasteRefs(input.state.getSnapshot().occurrences, PASTE_CHIP_SOURCE)+ for (const ref of stalePasteRefs(stash, live, Date.now(), PASTE_STASH_GRACE_MS))+ stash.delete(ref)+ }++ const watch = (sessionId: string, input: PasteSessionInput): void => {+ if (watchedSessionId === sessionId)+ return+ unwatchState?.()+ watchedSessionId = sessionId+ unwatchState = input.state.subscribe(() => prune(input))+ }++ const collapse = (event: ClipboardEvent): void => {+ const clipboard = event.clipboardData+ if (!ready || event.defaultPrevented || clipboard === null)+ return+ const target = event.target+ if (!(target instanceof Element) || target.closest(COMPOSER_CARD_SELECTOR) === null)+ return++ const text = clipboard.getData('text/plain')+ if (!isCollapsiblePaste({ text, fileCount: clipboardFileCount(clipboard) }))+ return++ const sessionId = sessions().list?.getSnapshot().current+ if (sessionId === undefined)+ return+ const input = sessionInputOf(sessionId)+ if (input === undefined)+ return+ const span = resolveInsertionSpan(sessions().provideInfo?.(sessionId)?.props?.inputActions, input)+ if (span === undefined)+ return++ const ref = `${PASTE_CHIP_SOURCE}-${seq + 1}`+ stash.set(ref, { text, at: Date.now() })+ const inserted = input.insertReference(+ { source: PASTE_CHIP_SOURCE, ref, label: chipLabel(text), appearance: 'file', clipboardText: text },+ span,+ )+ if (!inserted) {+ stash.delete(ref)+ return+ }++ seq += 1+ watch(sessionId, input)+ prune(input)+ event.preventDefault()+ event.stopPropagation()+ }++ ctx.inject([INPUT_TRIGGERS_SERVICE], () => {+ const triggers = adapter.service<PasteTriggerRegistry>(INPUT_TRIGGERS_SERVICE)+ if (triggers === undefined)+ return+ const dispose = triggers.registerSource({+ trigger: '@',+ name: PASTE_CHIP_SOURCE,+ showGroupTitle: false,+ candidates: async () => [],+ onPick: () => undefined,+ codec: {+ clipboardText: ref => stash.get(ref)?.text ?? '',+ serialize: async (ref) => {+ const held = stash.get(ref)+ if (held === undefined)+ throw new Error(`[${PLUGIN_ID}] 折叠的粘贴内容 ${ref} 已不在内存中,无法还原`)+ return held.text+ },+ },+ })+ ready = true+ return () => {+ ready = false+ dispose()+ }+ })++ controller.add(() => unwatchState?.())+ controller.add(controller.listen('paste', collapse, { capture: true }))+})diff --git a/packages/dsh-tauri-ui/src/client/register/paste-collapse.types.ts b/packages/dsh-tauri-ui/src/client/register/paste-collapse.types.tsnew file mode 100644index 00000000..b1b0011b--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/paste-collapse.types.ts@@ -0,0 +1,79 @@+/**+ * 官方 composer 折叠粘贴所需的跨包面(结构等价,不绑定核心版本)。+ *+ * 落点随核心版本漂移:`ctx.inputTriggers.registerSource` 提供引用 chip 的模型序列化,+ * `ctx.conversation.input.for(actx)` 提供每会话的输入面,`sessions.binding().ctx` /+ * `sessions.provideInfo` 提供会话作用域与标准动作面。全部按需可选,缺失即视为不可用。+ */++export interface PasteTokenSpan {+ start: number+ end: number+ draftRev: number+}++export interface PasteInputActions {+ captureInsertion?: () => PasteTokenSpan+}++export interface PasteReferenceInsert {+ source: string+ ref: string+ label: string+ appearance?: 'session' | 'file' | 'folder'+ clipboardText: string+}++export interface PasteOccurrence {+ source?: string+ ref?: string+}++export interface PasteInputState {+ draftRev?: number+ occurrences?: readonly PasteOccurrence[]+}++export interface PasteInputStateSource {+ getSnapshot: () => PasteInputState+ subscribe: (listener: () => void) => () => void+}++export interface PasteSessionInput {+ insertReference: (reference: PasteReferenceInsert, span: PasteTokenSpan) => boolean+ /** `0.1.5-rc.x` 的动作面还没有 `captureInsertion`:壳自身的同义方法仍在(后者就是它 + draftRev)。 */+ caretSpan?: () => { start: number, end: number }+ state: PasteInputStateSource+}++export interface PasteSessionBinding {+ ctx?: unknown+}++export interface PasteSessionServices {+ list?: { getSnapshot: () => { current?: string } }+ binding?: (sessionId: string) => PasteSessionBinding | undefined+ provideInfo?: (sessionId: string) => { props?: { inputActions?: PasteInputActions } } | undefined+}++export interface PasteConversationService {+ input?: { for: (actx: unknown) => PasteSessionInput | undefined }+}++export interface PasteTriggerCodec {+ clipboardText: (ref: string) => string+ serialize: (ref: string, signal: AbortSignal) => Promise<string>+}++export interface PasteTriggerSource {+ trigger: '@'+ name: string+ showGroupTitle: boolean+ candidates: () => Promise<readonly unknown[]>+ onPick: () => undefined+ codec: PasteTriggerCodec+}++export interface PasteTriggerRegistry {+ registerSource: (source: PasteTriggerSource) => () => void+}diff --git a/packages/dsh-tauri-ui/src/client/register/paste-collapse.utils.test.ts b/packages/dsh-tauri-ui/src/client/register/paste-collapse.utils.test.tsnew file mode 100644index 00000000..74063bfd--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/paste-collapse.utils.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it } from 'vitest'+import {+ clipboardFileCount,+ isCollapsiblePaste,+ livePasteRefs,+ pasteChipTitle,+ resolveInsertionSpan,+ stalePasteRefs,+} from './paste-collapse.utils'++describe('isCollapsiblePaste', () => {+ it('恰好 500 字的粘贴不折叠:阈值是「超过」', () => {+ expect(isCollapsiblePaste({ text: 'x'.repeat(500), fileCount: 0 })).toBe(false)+ })++ it('501 字的粘贴折叠', () => {+ expect(isCollapsiblePaste({ text: 'x'.repeat(501), fileCount: 0 })).toBe(true)+ })++ it('带文件的粘贴一律不折叠,文件入草稿留给官方路径', () => {+ expect(isCollapsiblePaste({ text: 'x'.repeat(501), fileCount: 1 })).toBe(false)+ })+})++describe('clipboardFileCount', () => {+ it('只数 kind=file 的剪贴板条目', () => {+ const clipboard = { items: [{ kind: 'file' }, { kind: 'string' }, { kind: 'file' }] } as unknown as DataTransfer++ expect(clipboardFileCount(clipboard)).toBe(2)+ })++ it('无文件条目时报 0', () => {+ expect(clipboardFileCount({ items: [] } as unknown as DataTransfer)).toBe(0)+ })+})++describe('pasteChipTitle', () => {+ it('取首个非空行并折叠行内空白', () => {+ expect(pasteChipTitle('\n\n ### 环境信息 \tapp \n更多')).toBe('### 环境信息 app')+ })++ it('超过 24 字截断并补省略号', () => {+ expect(pasteChipTitle('a'.repeat(30))).toBe(`${'a'.repeat(24)}…`)+ })++ it('整段没有可见字符时返回空串,由调用方改用与首行无关的文案', () => {+ expect(pasteChipTitle(' \n\t\n')).toBe('')+ })+})++describe('livePasteRefs', () => {+ it('只收本插件引用源且带 ref 的 occurrence', () => {+ const refs = livePasteRefs([+ { source: 'dsh-tauri-ui-paste', ref: 'a' },+ { source: 'files', ref: 'b' },+ { source: 'dsh-tauri-ui-paste' },+ ], 'dsh-tauri-ui-paste')++ expect([...refs]).toEqual(['a'])+ })++ it('草稿投影尚未发布(occurrences 缺席)时视为没有引用', () => {+ expect(livePasteRefs(undefined, 'dsh-tauri-ui-paste').size).toBe(0)+ })+})++describe('stalePasteRefs', () => {+ it('过了宽限期且不再被引用的 ref 回收', () => {+ const stash = new Map([['a', { at: 0 }], ['b', { at: 1500 }]])++ expect(stalePasteRefs(stash, new Set(), 2000, 2000)).toEqual(['a'])+ })++ it('宽限期内不回收:草稿投影晚于 chip 插入发布', () => {+ const stash = new Map([['a', { at: 1000 }]])++ expect(stalePasteRefs(stash, new Set(), 2000, 2000)).toEqual([])+ })++ it('仍被草稿引用的 ref 不回收', () => {+ const stash = new Map([['a', { at: 0 }]])++ expect(stalePasteRefs(stash, new Set(['a']), 60_000, 2000)).toEqual([])+ })+})++describe('resolveInsertionSpan', () => {+ it('动作面提供 captureInsertion 时直接用它的快照', () => {+ const span = { start: 4, end: 4, draftRev: 9 }++ expect(resolveInsertionSpan({ captureInsertion: () => span }, sessionInput())).toBe(span)+ })++ it('动作面没有 captureInsertion(0.1.5-rc.x)时退回 caretSpan + state.draftRev,组成同形快照', () => {+ const input = sessionInput({ caret: { start: 2, end: 5 }, draftRev: 12 })++ expect(resolveInsertionSpan({}, input)).toEqual({ start: 2, end: 5, draftRev: 12 })+ })++ it('两条通路都缺席时返回 undefined,由调用方退回官方粘贴', () => {+ expect(resolveInsertionSpan(undefined, sessionInput())).toBeUndefined()+ })+})++function sessionInput(options: { caret?: { start: number, end: number }, draftRev?: number } = {}) {+ return {+ insertReference: () => true,+ ...(options.caret === undefined ? {} : { caretSpan: () => options.caret! }),+ state: { getSnapshot: () => ({ occurrences: [], ...options.draftRev === undefined ? {} : { draftRev: options.draftRev } }), subscribe: () => () => {} },+ }+}diff --git a/packages/dsh-tauri-ui/src/client/register/paste-collapse.utils.ts b/packages/dsh-tauri-ui/src/client/register/paste-collapse.utils.tsnew file mode 100644index 00000000..cea7497d--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/paste-collapse.utils.ts@@ -0,0 +1,76 @@+import type { PasteInputActions, PasteOccurrence, PasteSessionInput, PasteTokenSpan } from './paste-collapse.types'++/** 超过该字符数的粘贴折叠成引用 chip;官方路径会把整段原文灌进编辑器,长文本即「一大串文字」。 */+const PASTE_COLLAPSE_THRESHOLD = 500++/** chip 标题(粘贴内容首行)的字符上限:chip 自身还有 240px 省略,这里只保证标题可读。 */+const PASTE_TITLE_MAX_LENGTH = 24++/**+ * 取插入 chip 用的选区快照(detect 坐标 + 修订号)。+ *+ * `0.1.5-rc.x` 的动作面只有 setDraft/submit,没有 `captureInsertion`;壳自身的 `caretSpan()`+ * 仍在,而 `0.1.7` 的 `captureInsertion` 实现就是「caretSpan + draftRev」。按能力探测取用,+ * 两条通路都缺席时返回 undefined,由调用方退回官方粘贴路径。+ */+export function resolveInsertionSpan(+ actions: PasteInputActions | undefined,+ input: PasteSessionInput,+): PasteTokenSpan | undefined {+ const captured = actions?.captureInsertion?.()+ if (captured !== undefined)+ return captured+ const caret = input.caretSpan?.()+ const draftRev = input.state.getSnapshot().draftRev+ return caret === undefined || draftRev === undefined ? undefined : { ...caret, draftRev }+}++/**+ * 是否接管这次粘贴:带文件的粘贴必须让给官方路径(它负责文件入草稿),空文本同样不接管。+ */+export function isCollapsiblePaste(input: { text: string, fileCount: number }): boolean {+ return input.fileCount === 0 && input.text.length > PASTE_COLLAPSE_THRESHOLD+}++export function clipboardFileCount(clipboard: DataTransfer): number {+ let count = 0+ for (const item of clipboard.items) {+ if (item.kind === 'file')+ count += 1+ }+ return count+}++/** chip 标题取首个非空行(折叠连续空白并限长);整段无可见字符时返回空串,由调用方退回首行无关的文案。 */+export function pasteChipTitle(text: string): string {+ const line = text.split(/\r?\n/)+ .find(part => part.trim() !== '')+ ?.replace(/\s+/g, ' ')+ .trim() ?? ''+ return line.length > PASTE_TITLE_MAX_LENGTH ? `${line.slice(0, PASTE_TITLE_MAX_LENGTH)}…` : line+}++/** 当前草稿里仍在使用本插件引用的 ref 集合(chip 被删除后即可回收其正文)。 */+export function livePasteRefs(occurrences: readonly PasteOccurrence[] | undefined, source: string): Set<string> {+ const refs = new Set<string>()+ for (const occurrence of occurrences ?? []) {+ if (occurrence.source === source && typeof occurrence.ref === 'string')+ refs.add(occurrence.ref)+ }+ return refs+}++/** 已不在草稿中、且过了插入宽限期的 ref:草稿投影晚于插入发布,宽限期内回收会把正文丢掉。 */+export function stalePasteRefs(+ stash: ReadonlyMap<string, { at: number }>,+ live: ReadonlySet<string>,+ now: number,+ graceMs: number,+): string[] {+ const stale: string[] = []+ for (const [ref, entry] of stash) {+ if (!live.has(ref) && now - entry.at >= graceMs)+ stale.push(ref)+ }+ return stale+}diff --git a/test/e2e/plugins/dsh-tauri-ui.e2e.ts b/test/e2e/plugins/dsh-tauri-ui.e2e.tsindex 7f13de4d..087576fa 100644--- a/test/e2e/plugins/dsh-tauri-ui.e2e.ts+++ b/test/e2e/plugins/dsh-tauri-ui.e2e.ts@@ -53,6 +53,42 @@ const OFFICIAL_HERO_WORKSPACE_CHIP = '[class$="heroWorkspaceRow"] button[aria-la*/const SIDEBAR_NEW_SESSION = 'button[aria-label="新建会话"]:visible'+/** 官方 composer 编辑器根(上游 `ComposerContentEditable` 的 `data-composer-input` 锚点)。 */+const COMPOSER_INPUT = '[data-composer-card] [data-composer-input]'++/**+ * 折叠粘贴后的引用 chip 宿主:官方 `ReferenceChipNode.createDOM` 写的 `data-composer-chip`,+ * 其值是本插件注册的引用源名(`packages/dsh-tauri-ui/src/client/constants/index.ts` 的 `PASTE_CHIP_SOURCE`)。+ */+const PASTE_CHIP = '[data-composer-chip="dsh-tauri-ui-paste"]'++/** 长粘贴夹具:首行是 chip 标题来源,整体远超 500 字阈值(`register/paste-collapse.utils.ts`)。 */+const LONG_PASTE = `### 环境信息 app:版本 1.0\n${'日志行'.repeat(200)}`++/** 阈值内夹具:必须原样进入编辑器。 */+const SHORT_PASTE = '短文本'.repeat(100)++/**+ * 在 composer 编辑器上派发一次合成粘贴事件。+ *+ * 真实剪贴板不可读(Playwright 无剪贴板权限),而官方 paste 命令本身也接受合成事件,+ * 因此这里按官方 `DataTransfer` + `ClipboardEvent` 的形态构造,只替换事件来源。+ * @returns 编辑器是否在位(不在位时本用例没有粘贴落点)。+ */+async function syntheticPaste(frame: import('playwright').Frame, text: string): Promise<{ editorFound: boolean }> {+ await frame.locator(COMPOSER_INPUT).click()+ return await frame.evaluate((payload) => {+ const editor = document.querySelector(payload.editorSelector)+ if (!(editor instanceof HTMLElement))+ return { editorFound: false }+ editor.focus()+ const dataTransfer = new DataTransfer()+ dataTransfer.setData('text/plain', payload.text)+ editor.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: dataTransfer }))+ return { editorFound: true }+ }, { editorSelector: COMPOSER_INPUT, text })+}+function url(): string {return `${inject('dshBaseUrl')}${RESUME_PATH}`}@@ -381,4 +417,61 @@ describe('L2 客户端', () => {await app.close()}})++ it('验证超过 500 字的粘贴折叠成引用 chip,chip 文案带首行与字数', async () => {+ const app = await newDshPage(browser, { ready: HERO_WORKSPACE_CHIP })+ try {+ await app.frame.locator(SIDEBAR_NEW_SESSION).first().click()+ await expect.poll(+ async () => await app.frame.locator(COMPOSER_INPUT).count(),+ { timeout: 20_000, message: '新建会话后 composer 编辑器必须挂载,否则本用例没有粘贴落点' },+ ).toBe(1)++ const paste = await syntheticPaste(app.frame, LONG_PASTE)+ expect(paste.editorFound, '夹具前置:composer 编辑器必须在位').toBe(true)++ await expect.poll(+ async () => await app.frame.locator(PASTE_CHIP).count(),+ { timeout: 10_000, message: '超过 500 字的粘贴必须折叠成引用 chip' },+ ).toBe(1)+ expect(+ await app.frame.locator(PASTE_CHIP).first().textContent(),+ 'chip 文案必须是「粘贴内容首行 · 字数」(本插件词典提供,中文语境下为「… 字」)',+ ).toBe(`### 环境信息 app:版本 1.0 · ${LONG_PASTE.length} 字`)+ expect(+ await app.frame.locator(COMPOSER_INPUT).first().textContent(),+ '原文不得作为一大串文字留在编辑器里',+ ).not.toContain(LONG_PASTE)++ expect(app.errors, '折叠粘贴不得抛出应用级错误').toEqual([])+ }+ finally {+ await app.close()+ }+ })++ it('验证 500 字以内的粘贴不折叠,原样进入编辑器', async () => {+ const app = await newDshPage(browser, { ready: HERO_WORKSPACE_CHIP })+ try {+ await app.frame.locator(SIDEBAR_NEW_SESSION).first().click()+ await expect.poll(+ async () => await app.frame.locator(COMPOSER_INPUT).count(),+ { timeout: 20_000, message: '新建会话后 composer 编辑器必须挂载,否则本用例没有粘贴落点' },+ ).toBe(1)++ const paste = await syntheticPaste(app.frame, SHORT_PASTE)+ expect(paste.editorFound, '夹具前置:composer 编辑器必须在位').toBe(true)++ await expect.poll(+ async () => await app.frame.locator(COMPOSER_INPUT).first().textContent() ?? '',+ { timeout: 10_000, message: '500 字以内的粘贴必须原样出现在编辑器里' },+ ).toContain(SHORT_PASTE)+ expect(await app.frame.locator(PASTE_CHIP).count(), '500 字以内不得出现折叠 chip').toBe(0)++ expect(app.errors, '阈值内的粘贴不得抛出应用级错误').toEqual([])+ }+ finally {+ await app.close()+ }+ })})