@gongfpp/dsh-novel-fish 0.1.6 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,246 @@
1
+ #!/usr/bin/env node
2
+ // Read-only, offline probe of an installed DSH build. No server or user profile.
3
+ // Usage: node scripts/check-host-contracts.mjs /absolute/path/to/@deepseek-ai/dsh
4
+ import assert from 'node:assert/strict'
5
+ import { existsSync } from 'node:fs'
6
+ import { readFile, readdir } from 'node:fs/promises'
7
+ import { isAbsolute, join, dirname } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import vm from 'node:vm'
10
+ import { build } from 'esbuild'
11
+ import { JSDOM, VirtualConsole } from 'jsdom'
12
+ import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'
13
+
14
+ const project = fileURLToPath(new URL('../', import.meta.url))
15
+ const host = process.argv[2] ?? process.env.HOST_ROOT
16
+ const report = { hostVersion: null, checks: [], claims: null,
17
+ claimsMeaning: 'Observed book progress after an untrusted click, not claimPassage invocation count.', limitations: [
18
+ 'JSDOM, not a browser: no layout, animation, focus or trusted-user-event proof.',
19
+ 'Private host exports are exposed only in memory; host boot/apply and full UI renderer are not started.',
20
+ 'Identity ancestors and plugin-manager slot declaration are checked statically; small mounting/context facades are supplied by this probe.',
21
+ 'Tool/Bash rows and the plugin-manager page are statically checked, not rendered; settings menus/modal are closed.',
22
+ 'Plugin is built in memory from current src/client.js; lib/client.js freshness is not checked.',
23
+ 'Only the supplied installation is tested; this is not proof for other or future versions.',
24
+ ] }
25
+ const check = (name, detail) => report.checks.push({ name, detail })
26
+ const read = path => readFile(path, 'utf8')
27
+ let dom
28
+ try {
29
+ assert.ok(host && isAbsolute(host), 'Pass an absolute DSH installation path (or HOST_ROOT).')
30
+ report.hostVersion = JSON.parse(await read(join(host, 'package.json'))).version
31
+ // Global installs nest the client packages under the dsh package, while a plain
32
+ // `npm install @deepseek-ai/dsh` hoists them next to it. Accept both layouts.
33
+ const siblingScope = dirname(host)
34
+ const packageDir = name => {
35
+ const nested = join(host, 'node_modules/@deepseek-ai', `dsh-${name}`)
36
+ return existsSync(nested) ? nested : join(siblingScope, `dsh-${name}`)
37
+ }
38
+ const client = name => read(join(packageDir(name), 'lib/client.js'))
39
+ const [chat, tool, conversation, manager] = await Promise.all([
40
+ client('client-ui-chat'), client('client-ui-tool'), client('client-ui-conversation'), client('client-ui-plugin-manager'),
41
+ ])
42
+ for (const [source, markers] of [[chat, ['data-chat-node-key', 'data-chat-flow-kind']],
43
+ [tool, ['data-chat-call-id', 'data-tool', 'data-variant', 'data-sample']], [conversation, ['data-conversation-session']]]) {
44
+ for (const marker of markers) assert.ok(source.includes(`"${marker}"`), `Missing host DOM marker: ${marker}`)
45
+ }
46
+ const config = manager.match(/"plugins\.bundle\.config":\s*\{\s*kind:\s*"(\w+)",\s*scope:\s*"(\w+)"/)
47
+ assert.ok(config, 'Missing plugins.bundle.config declaration')
48
+ assert.equal(config[1], 'keyed')
49
+ assert.match(manager, /renderSlot\("plugins\.bundle\.config",\s*\{\s*view:\s*"page"\s*\},\s*\{\s*entryKey:\s*pkg\.name/)
50
+ check('static host markers and bundle-config seat', 'chat/tool/conversation markers; keyed config rendered by package name with view=page')
51
+
52
+ // Built-in modules live in the shipped web shell, not separate npm packages.
53
+ const assets = join(packageDir('web-frontend'), 'dist/assets')
54
+ const candidates = (await readdir(assets)).filter(name => /^index-.*\.js$/.test(name))
55
+ let entry, frontend, registry
56
+ for (const candidate of candidates) {
57
+ const source = await read(join(assets, candidate))
58
+ const match = source.match(/function\s+([\w$]+)\(\)\s*\{\s*return\s*\{\s*react:/)
59
+ if (match && source.includes('"@deepseek-ai/dsh-client-ui-primitives"')) {
60
+ entry = join(assets, candidate); frontend = source; registry = match[1]; break
61
+ }
62
+ }
63
+ assert.ok(registry, 'Cannot locate the shipped web static-module registry; probe needs an update')
64
+ // Disable only the final application boot block, never component/module code.
65
+ const boot = /try\s*\{\s*const\s+[\w$]+\s*=\s*document\.getElementById\("root"\)/
66
+ assert.ok(boot.test(frontend), 'Cannot isolate web application boot; refusing to execute shell')
67
+ frontend = frontend.replace(boot, match => `if (false) ${match}`)
68
+ const errors = []
69
+ const virtualConsole = new VirtualConsole()
70
+ virtualConsole.on('jsdomError', error => errors.push(error.message))
71
+ dom = new JSDOM('<!doctype html><html><head></head><body></body></html>', {
72
+ url: 'http://host-contract.invalid/', runScripts: 'outside-only', pretendToBeVisual: true, virtualConsole,
73
+ })
74
+ Object.assign(dom.window, {
75
+ TextEncoder, TextDecoder, indexedDB: new IDBFactory(), IDBKeyRange,
76
+ fetch: () => { throw new Error('Network is forbidden in host-contract probe') },
77
+ console: { ...console, error: error => { if (error?.message !== 'web app: missing #root') errors.push(String(error)) } },
78
+ })
79
+ const bundled = await build({ stdin: {
80
+ contents: `${frontend}\nglobalThis.__hostContracts = ${registry}();`, resolveDir: dirname(entry), sourcefile: entry,
81
+ }, bundle: true, write: false, format: 'iife', logLevel: 'silent' })
82
+ vm.runInContext(bundled.outputFiles[0].text, dom.getInternalVMContext(), { filename: entry, timeout: 15000 })
83
+ const modules = dom.window.__hostContracts
84
+ const React = modules.react, h = React.createElement
85
+ const primitives = modules['@deepseek-ai/dsh-client-ui-primitives']
86
+ for (const name of ['DisclosureRow', 'TextShimmer', 'Switch', 'Button', 'Input', 'Menu', 'Modal', 'IconChevronDownOutlineRegular']) {
87
+ assert.ok(primitives[name], `Missing real primitive ${name}`)
88
+ }
89
+ const core = new modules['@deepseek-ai/dsh-client-ui-slots'].SlotCore()
90
+ const disposers = [], waiting = new Map()
91
+ const register = (options, component) => {
92
+ const off = core.register(options, component)
93
+ disposers.push(off)
94
+ for (const [name, callback] of waiting) if (core.spec(name)) { waiting.delete(name); callback() }
95
+ return off
96
+ }
97
+ const ctx = {
98
+ slots: { register, registerFactory: (...args) => { const off = core.registerFactory(...args); disposers.push(off); return off },
99
+ inject: (name, callback) => core.spec(name) ? callback() : waiting.set(name, callback) },
100
+ effect: callback => { const off = callback(); if (typeof off === 'function') disposers.push(off) },
101
+ locale: { register: () => () => {}, bind: () => key => key },
102
+ }
103
+ // These two outer seats belong to much larger application trees. Their declarations
104
+ // are checked in the original builds; all subsequent registrations use real SlotCore.
105
+ assert.match(chat, /"conversation\.chat\.node":\s*\{\s*kind:\s*"keyed",\s*scope:\s*"session"/)
106
+ register({ name: 'root', children: {
107
+ 'conversation.chat.node': { kind: 'keyed', scope: 'session' },
108
+ 'plugins.bundle.config': { kind: config[1], scope: config[2] },
109
+ } }, () => null)
110
+ const capture = (source, filename, expose = '') => {
111
+ let definition
112
+ dom.window.__ModuleLoader__ = { load: value => { definition = value } }
113
+ if (expose) {
114
+ assert.equal(source.split('return module.exports;').length, 2, 'Unknown host factory return shape')
115
+ source = source.replace('return module.exports;', `module.exports.__probe = { ${expose} }; return module.exports;`)
116
+ }
117
+ vm.runInContext(source, dom.getInternalVMContext(), { filename, timeout: 10000 })
118
+ assert.ok(definition?.factory, `No module factory captured from ${filename}`)
119
+ const require = name => {
120
+ assert.ok(modules[name], `Unexpected host import: ${name}`)
121
+ return modules[name]
122
+ }
123
+ require.asset = path => `http://host-contract.invalid/assets/${path}` // CSS only; never fetched
124
+ return definition.factory(require)
125
+ }
126
+ const hostChat = capture(chat, 'host-chat-client.js', 'registerChatNodeRenderers, ReasoningRow')
127
+ hostChat.__probe.registerChatNodeRenderers(ctx, {}, {})
128
+ assert.equal(core.spec('conversation.chat.reasoning.body')?.kind, 'single')
129
+ assert.ok(core.factory('conversation.chat.reasoning.content'))
130
+ const originalBody = core.entriesOfSlot('conversation.chat.reasoning.body')[0]
131
+ const plugin = await build({ entryPoints: [join(project, 'src/client.js')], bundle: true, write: false,
132
+ format: 'iife', logLevel: 'silent' })
133
+ capture(plugin.outputFiles[0].text, 'novel-client-source.js').apply(ctx)
134
+ const body = core.entriesOfSlot('conversation.chat.reasoning.body')[0]
135
+ assert.notEqual(body, originalBody, 'Plugin body must shadow, not replace/delete, host body')
136
+ assert.ok(core.entries('conversation.chat.reasoning.body').includes(originalBody))
137
+ const settings = core.entriesOfSlot('plugins.bundle.config').find(entry => entry.options.key === '@gongfpp/dsh-novel-fish')
138
+ assert.ok(settings)
139
+ check('real SlotCore registrations', 'host registerChatNodeRenderers + plugin apply; body priority shadowing, content Factory and package-keyed settings')
140
+
141
+ const injected = settings.inject()
142
+ const state = injected.hooks.novelState
143
+ await new Promise((resolve, reject) => {
144
+ const timer = setTimeout(() => { off(); reject(new Error('IndexedDB hydration timed out')) }, 3000)
145
+ const ready = () => { if (state.getSnapshot().hydrated) { clearTimeout(timer); off(); resolve() } }
146
+ const off = state.subscribe(ready); ready()
147
+ })
148
+ assert.equal(state.getSnapshot().error, null)
149
+ await injected.onSetOption('mainTitle', 'Contract title')
150
+ await injected.onSetOption('extraTitle', 'Contract summary')
151
+ await injected.onSetOption('enabled', false)
152
+ const book = await injected.onImportFile({ name: 'contract.txt', arrayBuffer: async () => new TextEncoder().encode('Contract novel passage.').buffer })
153
+ await injected.onSelectBook(book.id)
154
+ const hooks = sources => Object.fromEntries(Object.entries(sources).map(([key, source]) => [
155
+ modules['@deepseek-ai/dsh-client-ui-slots'].standardHookPropName(key),
156
+ select => select(React.useSyncExternalStore(source.subscribe, source.getSnapshot)),
157
+ ]))
158
+ const t = key => key
159
+ const slotCalls = []
160
+ const renderFactorySlot = (name, props) => {
161
+ slotCalls.push({ name, ...props })
162
+ const factory = core.factory(name)
163
+ assert.ok(factory, `Unknown Factory ${name}`)
164
+ return h(factory.component, { ...props, t })
165
+ }
166
+ function ReasoningProbe() {
167
+ const [expanded, setExpanded] = React.useState(false)
168
+ return h(hostChat.__probe.ReasoningRow, {
169
+ text: 'Native summary\n\nNative reasoning', running: true, t,
170
+ usePresentation: select => select({ settledReasoningPreview: true }),
171
+ useDisclosure: () => ({ expanded, toggle: () => setExpanded(value => !value) }),
172
+ renderSlot: (name, props) => {
173
+ assert.equal(name, 'conversation.chat.reasoning.body')
174
+ const values = body.inject()
175
+ return h(body.component, { ...props, sessionId: 'probe-session', ...hooks(values.hooks), renderFactorySlot, t })
176
+ },
177
+ })
178
+ }
179
+ const mount = dom.window.document.createElement('main')
180
+ dom.window.document.body.append(mount)
181
+ const root = modules['react-dom/client'].createRoot(mount)
182
+ const flush = callback => modules['react-dom'].flushSync(callback)
183
+ const render = () => flush(() => root.render(h(React.Fragment, null,
184
+ h('div', { 'data-conversation-session': 'probe-session' },
185
+ h('div', { 'data-chat-flow-kind': 'assistant-step', 'data-chat-node-key': 'probe-node' }, h(ReasoningProbe))),
186
+ h(settings.component, { ...injected, ...hooks(injected.hooks), t, view: 'page' }),
187
+ )))
188
+ render()
189
+ await new Promise(resolve => setTimeout(resolve, 25))
190
+ const header = mount.querySelector('[data-disclosure-row]')
191
+ assert.ok(header)
192
+ assert.equal(header.getAttribute('role'), 'button')
193
+ assert.equal(header.getAttribute('aria-expanded'), 'false')
194
+ const nativeNodes = [...header.querySelectorAll('*')]
195
+ const glyphs = [...header.querySelectorAll('svg')]
196
+ const nativeGlyphs = glyphs.map(node => node.outerHTML)
197
+ assert.ok(glyphs.length > 0)
198
+ await injected.onSetOption('enabled', true)
199
+ await new Promise(resolve => setTimeout(resolve, 25))
200
+ assert.deepEqual([...header.querySelectorAll('*')], nativeNodes, 'Adapter must preserve native elements')
201
+ assert.deepEqual(glyphs.map(node => node.outerHTML), nativeGlyphs, 'Adapter must not change native SVGs')
202
+ assert.ok(header.textContent.includes('Contract title'))
203
+ assert.ok(header.textContent.includes('Contract summary'))
204
+ assert.deepEqual([...header.querySelectorAll('[data-shimmer-text]')].map(el => el.getAttribute('data-shimmer-text')), ['Contract title', 'Contract summary'])
205
+ assert.equal(mount.querySelectorAll('[data-novel-append]').length, 0)
206
+ check('real ReasoningRow / DisclosureRow / TextShimmer', 'plugin changes both native text and shimmer layers on actual shipped components; native SVGs remain')
207
+ // This event is intentionally untrusted: it opens React's host row but must never claim a passage.
208
+ flush(() => header.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })))
209
+ await new Promise(resolve => setTimeout(resolve, 25))
210
+ assert.equal(header.getAttribute('aria-expanded'), 'true')
211
+ assert.ok(slotCalls.some(call => call.name === 'conversation.chat.reasoning.content' && call.text === 'Native summary\n\nNative reasoning' && call.running === true))
212
+ assert.ok(mount.querySelector('[data-novel-original]').textContent.includes('Native reasoning'))
213
+ report.claims = state.getSnapshot().books.find(item => item.id === book.id).progress
214
+ assert.equal(report.claims, 0, 'Untrusted DOM click must not advance book progress')
215
+ check('untrusted-event guard', 'actual host click expands the row but imported in-memory book progress stays at zero; no trusted input is simulated')
216
+ assert.ok(mount.querySelector('[data-novel-settings] button'))
217
+ assert.ok(mount.querySelector('[data-novel-settings] input[type="file"]'))
218
+ check('real body Factory props and settings primitives', 'host row passes text/running; plugin calls actual MarkdownText Factory; settings mounts with real controls and memory IndexedDB')
219
+ await injected.onSetOption('enabled', false)
220
+ await new Promise(resolve => setTimeout(resolve, 25))
221
+ assert.ok(header.textContent.includes('message.think'), 'Disabling must restore native title')
222
+ assert.equal(mount.querySelector('[data-novel-target]'), null)
223
+ check('restore on disable', 'native title restored and adapter target marker removed')
224
+ // The adapter keeps the native row and only rewrites its text, so it depends on the
225
+ // shipped title layers, disclosure row and folding anchors staying put.
226
+ const anchors = {
227
+ chat: { source: chat, markers: ['data-chat-flow-key', 'data-turn-process-member', 'data-turn-process-hidden', 'data-shimmer-decoration'] },
228
+ conversation: { source: conversation, markers: ['data-conversation-session'] },
229
+ shell: { source: frontend, markers: ['data-shimmer-text', 'data-disclosure-row'] },
230
+ }
231
+ for (const [name, { source, markers }] of Object.entries(anchors)) {
232
+ for (const marker of markers) assert.ok(source.includes(`"${marker}"`), `Missing ${name} adapter anchor: ${marker}`)
233
+ }
234
+ check('adapter anchors for title layers and fold state', 'shimmer text/decoration, disclosure row, session identity and turn-process fold markers still ship; ambient DOM rescan has a contract to rescan')
235
+ flush(() => root.unmount())
236
+ for (const dispose of disposers.reverse()) dispose()
237
+ assert.deepEqual(errors, [], 'Unexpected host/JSDOM runtime errors')
238
+ report.ok = true
239
+ } catch (error) {
240
+ report.ok = false
241
+ report.error = error.stack ?? String(error)
242
+ process.exitCode = 1
243
+ } finally {
244
+ dom?.window.close()
245
+ console.log(JSON.stringify(report, null, 2))
246
+ }
@@ -98,6 +98,23 @@ export function registerChatAdapter(ctx, store, React, locale) {
98
98
  }
99
99
  }
100
100
 
101
+ // Streaming text mutates the DOM far more often than a frame; merge observer
102
+ // bursts into one scan so a long session cannot turn every token into a full
103
+ // rescan. Settings/passage updates still refresh immediately.
104
+ let queued = null
105
+ const coalescedRefresh = () => {
106
+ if (!queued) return
107
+ queued = null
108
+ if (!disposed) refresh()
109
+ }
110
+ const scheduleRefresh = () => {
111
+ if (queued) return
112
+ const entry = { frame: null }
113
+ queued = entry
114
+ if (view?.requestAnimationFrame) entry.frame = view.requestAnimationFrame(coalescedRefresh)
115
+ else queueMicrotask(coalescedRefresh)
116
+ }
117
+
101
118
  const activate = event => {
102
119
  if (!event.isTrusted || event.defaultPrevented) return
103
120
  if (event.type === 'keydown' && (event.repeat || !['Enter', ' '].includes(event.key))) return
@@ -125,13 +142,14 @@ export function registerChatAdapter(ctx, store, React, locale) {
125
142
  if (!disposed && toggle.isConnected && toggle.getAttribute('aria-expanded') === 'true'
126
143
  && current.enabled && current.currentBookId === bookId && isTarget(current, currentId)
127
144
  && store.cacheGeneration === intent.generation && readingKey(currentId) === intent.key) {
128
- void store.claimPassage(readingKey(id), id.type)
145
+ if (current.continueOnReopen === true) void store.continuePassage(readingKey(id), id.type)
146
+ else void store.claimPassage(readingKey(id), id.type)
129
147
  }
130
148
  }
131
149
  if (view?.requestAnimationFrame) intent.frame = view.requestAnimationFrame(verify)
132
150
  else queueMicrotask(verify)
133
151
  }
134
- const observer = new MutationObserver(refresh)
152
+ const observer = new MutationObserver(scheduleRefresh)
135
153
  observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true,
136
154
  attributeFilter: ['data-shimmer-text', 'aria-expanded', 'data-tool', 'data-state'] })
137
155
  document.addEventListener('click', activate, true)
@@ -144,6 +162,8 @@ export function registerChatAdapter(ctx, store, React, locale) {
144
162
  observer.disconnect(); stopSettings(); stopPassages()
145
163
  document.removeEventListener('click', activate, true)
146
164
  document.removeEventListener('keydown', activate, true)
165
+ if (queued && queued.frame !== null && view?.cancelAnimationFrame) view.cancelAnimationFrame(queued.frame)
166
+ queued = null
147
167
  for (const intent of pending.values()) if (intent.frame !== null) view.cancelAnimationFrame(intent.frame)
148
168
  pending.clear()
149
169
  for (const root of decorated.keys()) restore(root)
package/src/settings.js CHANGED
@@ -73,9 +73,11 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
73
73
  const [busy, setBusy] = React.useState(false)
74
74
  const [savingTypes, setSavingTypes] = React.useState(false)
75
75
  const [savingEnabled, setSavingEnabled] = React.useState(false)
76
+ const [savingContinue, setSavingContinue] = React.useState(false)
76
77
  const [removeBook, setRemoveBook] = React.useState(null)
77
78
  const [removeError, setRemoveError] = React.useState(null)
78
79
  const enabling = React.useRef(false)
80
+ const continuing = React.useRef(false)
79
81
  const changingTypes = React.useRef(false)
80
82
  const importing = React.useRef(false)
81
83
  const removing = React.useRef(false)
@@ -93,6 +95,13 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
93
95
  try { await perform(() => onSetOption('enabled', enabled)) }
94
96
  finally { enabling.current = false; setSavingEnabled(false) }
95
97
  }
98
+ const setContinue = async enabled => {
99
+ if (disabled || continuing.current) return
100
+ continuing.current = true
101
+ setSavingContinue(true)
102
+ try { await perform(() => onSetOption('continueOnReopen', enabled)) }
103
+ finally { continuing.current = false; setSavingContinue(false) }
104
+ }
96
105
  const setTypes = async types => {
97
106
  if (disabled || changingTypes.current) return
98
107
  changingTypes.current = true
@@ -171,6 +180,11 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
171
180
  }),
172
181
  h('p', { className: 'novel-fish-hint' }, t('settings.typeHint')),
173
182
  ),
183
+ h('div', { className: 'novel-fish-row' },
184
+ h('span', null, t('settings.continueOnReopen')),
185
+ h(Switch, { checked: state.settings.continueOnReopen === true, disabled: disabled || savingContinue, label: t('settings.continueOnReopen'), onChange: enabled => { void setContinue(enabled) } }),
186
+ ),
187
+ h('p', { className: 'novel-fish-hint' }, t('settings.continueOnReopenHint')),
174
188
  ),
175
189
  h('section', { className: 'novel-fish-section' },
176
190
  h('h3', null, t('settings.appearance')),
package/src/store.js CHANGED
@@ -10,6 +10,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
10
10
  targetTypes: Object.freeze(['reasoning']),
11
11
  mainTitle: '',
12
12
  extraTitle: '',
13
+ continueOnReopen: false,
13
14
  })
14
15
 
15
16
  const EMPTY_STATUS = Object.freeze({ kind: 'empty' })
@@ -76,15 +77,17 @@ export class NovelStore {
76
77
  }
77
78
 
78
79
  async setOption(key, value) {
79
- if (!['enabled', 'targetTypes', 'mainTitle', 'extraTitle'].includes(key)) throw new Error('未知设置项')
80
+ if (!['enabled', 'targetTypes', 'mainTitle', 'extraTitle', 'continueOnReopen'].includes(key)) throw new Error('未知设置项')
80
81
  let normalized
81
82
  if (key === 'targetTypes') {
82
83
  if (!Array.isArray(value) || value.some(type => !TARGET_TYPES.includes(type)) || new Set(value).size !== value.length) {
83
84
  throw new Error('阅读类型必须是有效且不重复的类型数组')
84
85
  }
85
86
  normalized = Object.freeze([...value])
87
+ } else if (key === 'enabled' || key === 'continueOnReopen') {
88
+ normalized = Boolean(value)
86
89
  } else {
87
- normalized = key === 'enabled' ? Boolean(value) : String(value)
90
+ normalized = String(value)
88
91
  }
89
92
  // Invalidate at intent time, not after a queued settings write finishes.
90
93
  // Any type update also covers removals from settings writes still in flight.
@@ -142,7 +145,22 @@ export class NovelStore {
142
145
  })
143
146
  }
144
147
 
148
+ /** Reopening a region shows the passage it already holds; a first expansion reads the next one. */
145
149
  async claimPassage(stepKey, targetType = 'reasoning') {
150
+ return this.#readPassage(stepKey, targetType, false)
151
+ }
152
+
153
+ /**
154
+ * Same contract as claimPassage, except a region that already shows a passage
155
+ * advances to the next one. Only an explicit reopen can reach this path, so a
156
+ * repeated expansion still cannot paginate by accident while long reads
157
+ * continue inside the same native row.
158
+ */
159
+ async continuePassage(stepKey, targetType = 'reasoning') {
160
+ return this.#readPassage(stepKey, targetType, true)
161
+ }
162
+
163
+ async #readPassage(stepKey, targetType, advance) {
146
164
  if (this.disposed) return EMPTY_STATUS
147
165
  const generation = this.cacheGeneration
148
166
  const requestKey = `${generation}\u0000${targetType}\u0000${stepKey}`
@@ -156,7 +174,8 @@ export class NovelStore {
156
174
  bookId = this.state.settings.currentBookId
157
175
  if (!bookId) return EMPTY_STATUS
158
176
  const existing = this.getPassageStatus(bookId, stepKey)
159
- if (existing.kind === 'ready' || existing.kind === 'end') return existing
177
+ if (existing.kind === 'end') return existing
178
+ if (!advance && existing.kind === 'ready') return existing
160
179
  const book = this.state.books.find(item => item.id === bookId)
161
180
  if (!book || book.progress >= book.segmentCount) {
162
181
  return this.#writePassageStatus(bookId, stepKey, { kind: 'end', bookId })
@@ -34,8 +34,8 @@ function installDom(dom) {
34
34
  function adapterFixture(content = thought('node-a'), session = 'session-a') {
35
35
  const dom = new JSDOM(`<body><div data-conversation-session="${session}">${content}</div></body>`)
36
36
  const restoreDom = installDom(dom)
37
- let settings = { enabled: true, currentBookId: 'book', targetTypes: ['reasoning'], mainTitle: '思考', extraTitle: 'Checking project structure' }
38
- const claims = [], types = [], effects = [], actions = {}
37
+ let settings = { enabled: true, currentBookId: 'book', targetTypes: ['reasoning'], mainTitle: '思考', extraTitle: 'Checking project structure', continueOnReopen: false }
38
+ const claims = [], continues = [], types = [], effects = [], actions = {}
39
39
  const statuses = new Map()
40
40
  let passagesChanged
41
41
  const add = document.addEventListener.bind(document)
@@ -48,10 +48,11 @@ function adapterFixture(content = thought('node-a'), session = 'session-a') {
48
48
  subscribePassages: callback => { passagesChanged = callback; return () => {} },
49
49
  getPassageStatus: (_book, key) => statuses.get(key) ?? ({ kind: 'empty' }),
50
50
  claimPassage: (key, type) => { claims.push(key); types.push(type); return Promise.resolve() },
51
+ continuePassage: (key, type) => { continues.push(key); types.push(type); return Promise.resolve() },
51
52
  }
52
53
  const ctx = { slots: { inject: (_key, fn) => fn(), register: () => () => {} }, effect: fn => { effects.push(fn()) } }
53
54
  return {
54
- dom, claims, types, actions, start: () => registerChatAdapter(ctx, store, React, 'novel'),
55
+ dom, claims, continues, types, actions, start: () => registerChatAdapter(ctx, store, React, 'novel'),
55
56
  passage: (key, status) => { statuses.set(key, status); passagesChanged() },
56
57
  invalidate: () => { store.cacheGeneration += 1 },
57
58
  settings: patch => { settings = { ...settings, ...patch }; settingsChanged() },
@@ -373,3 +374,60 @@ test('native thought remains visible when its DOM identity is unavailable', asyn
373
374
  assert.equal(view.root.findAllByProps({ 'data-novel-append': true }).length, 0)
374
375
  } finally { await act(async () => view?.unmount()); dom.window.close() }
375
376
  })
377
+
378
+ test('默认关闭续读时同一区域重复主动展开仍走缓存 claim', async () => {
379
+ const f = adapterFixture(thought('node-a'))
380
+ try {
381
+ f.start()
382
+ const header = document.querySelector('[data-disclosure-row]')
383
+ for (let index = 0; index < 2; index += 1) {
384
+ header.setAttribute('aria-expanded', 'false')
385
+ f.actions.click(trustedClick(header))
386
+ header.setAttribute('aria-expanded', 'true')
387
+ await settle()
388
+ }
389
+ assert.equal(f.continues.length, 0)
390
+ assert.deepEqual(f.claims, [readingKey('session-a', 'node-a'), readingKey('session-a', 'node-a')])
391
+ } finally { f.close() }
392
+ })
393
+
394
+ test('开启续读后同一区域主动展开改为继续下一段,非可信事件仍不读', async () => {
395
+ const f = adapterFixture(thought('node-a'))
396
+ try {
397
+ f.start()
398
+ f.settings({ continueOnReopen: true })
399
+ const header = document.querySelector('[data-disclosure-row]')
400
+ header.setAttribute('aria-expanded', 'false')
401
+ f.actions.click({ ...trustedClick(header), isTrusted: false })
402
+ header.setAttribute('aria-expanded', 'true')
403
+ await settle()
404
+ assert.equal(f.continues.length, 0, '未验证的用户事件不推进阅读')
405
+ for (let index = 0; index < 2; index += 1) {
406
+ header.setAttribute('aria-expanded', 'false')
407
+ f.actions.click(trustedClick(header))
408
+ header.setAttribute('aria-expanded', 'true')
409
+ await settle()
410
+ }
411
+ assert.deepEqual(f.continues, [readingKey('session-a', 'node-a'), readingKey('session-a', 'node-a')])
412
+ assert.equal(f.claims.length, 0)
413
+ } finally { f.close() }
414
+ })
415
+
416
+ test('流式文本和属性变更在同一帧内只合并成一次重扫', async () => {
417
+ const f = adapterFixture(thought('node-a'))
418
+ const frames = []
419
+ let cancelled = 0
420
+ f.dom.window.requestAnimationFrame = callback => { frames.push(callback); return frames.length }
421
+ f.dom.window.cancelAnimationFrame = () => { cancelled += 1 }
422
+ try {
423
+ f.start()
424
+ const title = document.querySelector('.native-title')
425
+ for (let index = 0; index < 4; index += 1) title.firstChild.nodeValue = `stream ${index}`
426
+ document.querySelector('[data-disclosure-row]').setAttribute('data-state', 'open')
427
+ await settle()
428
+ assert.equal(frames.length, 1, '一帧内的多次变更共享一次刷新,而不是每个 token 全量扫描')
429
+ frames[0]()
430
+ assert.equal(title.textContent, '思考')
431
+ assert.equal(cancelled, 0)
432
+ } finally { f.close() }
433
+ })
@@ -63,10 +63,11 @@ test('构建产物只在本包详情注册设置,复用宿主 Switch 与原有
63
63
  useNovelUi: select => select(React.useSyncExternalStore(injected.hooks.novelUi.subscribe, injected.hooks.novelUi.getSnapshot)),
64
64
  }
65
65
  await act(async () => { view = TestRenderer.create(React.createElement(own.Component, props)) })
66
- assert.equal(view.root.findByType(HostSwitch).props.checked, false)
66
+ const enabledSwitch = () => view.root.findAllByType(HostSwitch).find(node => node.props.label === 'settings.enabled')
67
+ assert.equal(enabledSwitch().props.checked, false)
67
68
  assert.equal(source.getSnapshot().books[0].progress, 1)
68
69
  await act(async () => { await injected.onSetOption('enabled', true) })
69
- assert.equal(view.root.findByType(HostSwitch).props.checked, true)
70
+ assert.equal(enabledSwitch().props.checked, true)
70
71
  const saved = await storage.load()
71
72
  assert.equal(saved.settings.enabled, true)
72
73
  assert.equal(saved.settings.currentBookId, book.id)
@@ -0,0 +1,32 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { spawnSync } from 'node:child_process'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ const script = fileURLToPath(new URL('../scripts/check-host-contracts.mjs', import.meta.url))
7
+ const run = args => spawnSync(process.execPath, [script, ...args], {
8
+ encoding: 'utf8', timeout: 30000, env: { ...process.env, HOST_ROOT: '' },
9
+ })
10
+
11
+ test('host-contract probe rejects relative installation paths with a JSON failure', () => {
12
+ const result = run(['relative/host'])
13
+ assert.equal(result.status, 1)
14
+ const report = JSON.parse(result.stdout)
15
+ assert.equal(report.ok, false)
16
+ assert.match(report.error, /absolute DSH installation path/)
17
+ assert.equal(report.claims, null, 'failed setup must not claim a measured result')
18
+ })
19
+
20
+ test('host-contract probe exercises a real installation when HOST_ROOT is supplied', {
21
+ skip: process.env.HOST_ROOT ? false : 'Set HOST_ROOT to an absolute installed DSH directory to run real-host integration',
22
+ }, () => {
23
+ const result = run([process.env.HOST_ROOT])
24
+ assert.equal(result.status, 0, result.stdout + result.stderr)
25
+ const report = JSON.parse(result.stdout)
26
+ assert.equal(report.ok, true)
27
+ assert.equal(report.claims, 0)
28
+ assert.ok(report.checks.some(check => check.name === 'real SlotCore registrations'))
29
+ assert.ok(report.checks.some(check => check.name === 'real ReasoningRow / DisclosureRow / TextShimmer'))
30
+ assert.ok(report.checks.some(check => check.name === 'adapter anchors for title layers and fold state'))
31
+ assert.ok(report.limitations.some(limit => limit.includes('trusted-user-event')))
32
+ })