@gongfpp/dsh-novel-fish 1.0.0 → 1.1.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.
Files changed (44) hide show
  1. package/README.md +42 -14
  2. package/docs/community-markets.md +18 -1
  3. package/docs/compatibility-101.md +41 -0
  4. package/docs/ebook-tests.md +99 -0
  5. package/docs/evidence/reading-demo-110.png +0 -0
  6. package/docs/evidence/reading-two-expansions-110.gif +0 -0
  7. package/docs/evidence/reading-two-expansions-110.json +89 -0
  8. package/docs/evidence/samples-110-capture.json +49 -0
  9. package/docs/evidence/settings-110.png +0 -0
  10. package/docs/marketplace.md +4 -4
  11. package/docs/release.md +25 -0
  12. package/index.json +24 -0
  13. package/lib/client.js +523 -95
  14. package/locale/en.json +6 -0
  15. package/locale/zh.json +6 -0
  16. package/package.json +10 -9
  17. package/samples/ebooks/LICENSE.md +355 -0
  18. package/samples/ebooks/NOTICE.md +33 -0
  19. package/samples/ebooks/aq-zheng-zhuan-wikisource.md +998 -0
  20. package/samples/ebooks/million-pound-bank-note-pg61522.txt +6970 -0
  21. package/samples/ebooks/sources.json +58 -0
  22. package/scripts/build.mjs +1 -0
  23. package/scripts/check-host-contracts.mjs +3 -2
  24. package/scripts/make-readme-gif.mjs +69 -0
  25. package/scripts/test-browser-samples.mjs +665 -0
  26. package/scripts/test-candidate-books.mjs +71 -0
  27. package/scripts/test-ebook-corpus.mjs +161 -0
  28. package/src/bundled-books.js +42 -0
  29. package/src/chat-adapter.js +34 -9
  30. package/src/client.js +8 -2
  31. package/src/novel-content.js +8 -0
  32. package/src/persistence.js +144 -3
  33. package/src/pg-notice.js +19 -0
  34. package/src/segments.js +115 -65
  35. package/src/settings.js +32 -8
  36. package/src/store.js +61 -3
  37. package/test/bundled-library.test.js +526 -0
  38. package/test/chat-adapter.test.js +87 -2
  39. package/test/client.test.js +49 -7
  40. package/test/ebooks.test.js +192 -0
  41. package/test/pg-notice.test.js +109 -0
  42. package/test/release.test.js +21 -7
  43. package/test/segments.test.js +136 -2
  44. package/test/settings.test.js +42 -1
@@ -0,0 +1,526 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { readFile } from 'node:fs/promises'
4
+ import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'
5
+ import { IndexedDbStorage } from '../src/persistence.js'
6
+ import { DEFAULT_SETTINGS, NovelStore } from '../src/store.js'
7
+ import { parseTextBook } from '../src/segments.js'
8
+ import { MemoryStorage } from './helpers/memory-storage.js'
9
+
10
+ function bytesFile(name, bytes) {
11
+ const buffer = Uint8Array.from(bytes).buffer
12
+ return { name, arrayBuffer: async () => buffer }
13
+ }
14
+
15
+ function bundledBook(id, text = `${id} 正文。`, format = 'txt') {
16
+ return { id, title: `${id} 标题`, format, createFile: () => bytesFile(`${id}.${format}`, new TextEncoder().encode(text)) }
17
+ }
18
+
19
+ function makeStorage(factory = new IDBFactory()) {
20
+ return new IndexedDbStorage(factory, IDBKeyRange)
21
+ }
22
+
23
+ function entry(id, text = `${id} 正文。`) {
24
+ const segments = parseTextBook(text).segments
25
+ return {
26
+ book: { id: `bundled:${id}`, bundledId: id, title: `${id} 标题`, format: 'txt', segmentCount: segments.length, progress: 0, importedAt: 123 },
27
+ segments,
28
+ }
29
+ }
30
+
31
+ async function expectUninitialized(storage) {
32
+ assert.deepEqual(await storage.load(), { books: [], settings: undefined })
33
+ assert.equal(await storage.getSegment('bundled:first', 0), null)
34
+ assert.equal(await storage.getSegment('bundled:second', 0), null)
35
+ }
36
+
37
+ test('fresh library provisions real readable default books and selects the descriptor-first book', async () => {
38
+ const storage = makeStorage()
39
+ const store = new NovelStore(storage, { bundledBooks: [bundledBook('z-first'), bundledBook('a-second', '# 章节\n\nMarkdown 正文。', 'md')] })
40
+ try {
41
+ assert.equal(store.getSnapshot().hydrated, false)
42
+ await store.ready
43
+ const state = store.getSnapshot()
44
+ assert.equal(state.hydrated, true)
45
+ assert.equal(state.error, null)
46
+ assert.equal(state.books.length, 2)
47
+ assert.equal(state.settings.currentBookId, 'bundled:z-first')
48
+ assert.deepEqual(state.settings.targetTypes, ['reasoning'])
49
+ assert.equal(state.books.find(book => book.id === 'bundled:z-first').title, 'z-first 标题')
50
+ assert.equal(state.books.find(book => book.id === 'bundled:z-first').bundledId, 'z-first')
51
+ assert.equal((await storage.getSegment('bundled:a-second', 0)).chapterTitle, '章节')
52
+ assert.equal((await store.claimPassage('reading')).passage.text, 'z-first 正文。')
53
+ assert.equal((await storage.load()).books.find(book => book.id === 'bundled:z-first').progress, 1)
54
+ assert.equal((await storage.load()).bundledBooksInitialized, true)
55
+ assert.equal('bundledBooksInitialized' in store.getSettingsSnapshot(), false)
56
+ } finally {
57
+ store.dispose()
58
+ }
59
+ })
60
+
61
+ test('ready awaits async factories and complete initialization without blocking queued mutations', async () => {
62
+ const storage = makeStorage()
63
+ let release
64
+ const gate = new Promise(resolve => { release = resolve })
65
+ const descriptor = bundledBook('first')
66
+ const store = new NovelStore(storage, { bundledBooks: [{ ...descriptor, createFile: async () => { await gate; return descriptor.createFile() } }] })
67
+ const pendingSetting = store.setOption('mainTitle', 'queued title')
68
+ try {
69
+ assert.equal(store.getSnapshot().hydrated, false)
70
+ release()
71
+ await store.ready
72
+ await pendingSetting
73
+ assert.equal(store.getSnapshot().books.length, 1)
74
+ assert.equal(store.getSettingsSnapshot().mainTitle, 'queued title')
75
+ assert.equal((await storage.load()).bundledBooksInitialized, true)
76
+ } finally {
77
+ store.dispose()
78
+ }
79
+ })
80
+
81
+ test('existing books, progress, selection and settings survive provisioning unchanged', async () => {
82
+ const storage = makeStorage()
83
+ const originalBook = { id: 'user-book', title: 'User book', format: 'txt', segmentCount: 2, progress: 1, importedAt: 1 }
84
+ const settings = { ...DEFAULT_SETTINGS, currentBookId: originalBook.id, enabled: false, targetTypes: ['command'], mainTitle: 'custom', extraTitle: 'extra', continueOnReopen: true }
85
+ await storage.addBook(originalBook, [{ text: 'A' }, { text: 'B' }])
86
+ await storage.saveSettings(settings)
87
+ const store = new NovelStore(storage, { bundledBooks: [bundledBook('first'), bundledBook('second')] })
88
+ try {
89
+ await store.ready
90
+ assert.equal(store.getSnapshot().books.length, 3)
91
+ assert.deepEqual(store.getSnapshot().books.find(book => book.id === originalBook.id), originalBook)
92
+ assert.deepEqual(store.getSettingsSnapshot(), settings)
93
+ assert.deepEqual((await storage.load()).settings, settings)
94
+ assert.deepEqual(await storage.getSegment(originalBook.id, 1), { text: 'B' })
95
+ } finally {
96
+ store.dispose()
97
+ }
98
+ })
99
+
100
+ test('an existing library with no selected book is not automatically selected', async () => {
101
+ const storage = makeStorage()
102
+ await storage.addBook({ id: 'user-book', title: 'User', format: 'txt', segmentCount: 1, progress: 0 }, [{ text: 'existing' }])
103
+ await storage.saveSettings({ ...DEFAULT_SETTINGS, currentBookId: null })
104
+ const store = new NovelStore(storage, { bundledBooks: [bundledBook('first')] })
105
+ try {
106
+ await store.ready
107
+ assert.equal(store.getSettingsSnapshot().currentBookId, null)
108
+ assert.equal((await storage.load()).settings.currentBookId, null)
109
+ } finally {
110
+ store.dispose()
111
+ }
112
+ })
113
+
114
+ test('deleted defaults and an entirely deleted library never reappear after refresh', async () => {
115
+ const factory = new IDBFactory()
116
+ const descriptors = [bundledBook('first'), bundledBook('second')]
117
+ let store = new NovelStore(makeStorage(factory), { bundledBooks: descriptors })
118
+ try {
119
+ await store.ready
120
+ await store.deleteBook('bundled:first')
121
+ store.dispose()
122
+ const noParseDescriptors = descriptors.map(descriptor => ({ ...descriptor, createFile: () => { throw new Error('defaults must not be parsed again') } }))
123
+ store = new NovelStore(makeStorage(factory), { bundledBooks: noParseDescriptors })
124
+ await store.ready
125
+ assert.equal(store.getSnapshot().error, null)
126
+ assert.deepEqual(store.getSnapshot().books.map(book => book.id), ['bundled:second'])
127
+ await store.deleteBook('bundled:second')
128
+ await store.setOption('mainTitle', 'marker survives normal settings writes')
129
+ store.dispose()
130
+ store = new NovelStore(makeStorage(factory), { bundledBooks: noParseDescriptors })
131
+ await store.ready
132
+ assert.equal(store.getSnapshot().error, null)
133
+ assert.deepEqual(store.getSnapshot().books, [])
134
+ assert.equal(store.getSettingsSnapshot().currentBookId, null)
135
+ assert.equal(store.getSettingsSnapshot().mainTitle, 'marker survives normal settings writes')
136
+ assert.equal((await store.storage.load()).bundledBooksInitialized, true)
137
+ } finally {
138
+ store.dispose()
139
+ }
140
+ })
141
+
142
+ test('concurrent tabs recheck the marker atomically and both hydrate the winning library', async () => {
143
+ const factory = new IDBFactory()
144
+ let release
145
+ let entered = 0
146
+ const gate = new Promise(resolve => { release = resolve })
147
+ const descriptor = bundledBook('first')
148
+ const descriptors = [{ ...descriptor, createFile: async () => { entered += 1; if (entered === 2) release(); await gate; return descriptor.createFile() } }, bundledBook('second')]
149
+ const first = new NovelStore(makeStorage(factory), { bundledBooks: descriptors })
150
+ const second = new NovelStore(makeStorage(factory), { bundledBooks: descriptors })
151
+ try {
152
+ await Promise.all([first.ready, second.ready])
153
+ assert.equal(first.getSnapshot().error, null)
154
+ assert.equal(second.getSnapshot().error, null)
155
+ assert.deepEqual(first.getSnapshot().books, second.getSnapshot().books)
156
+ assert.equal(first.getSnapshot().books.length, 2)
157
+ assert.equal(second.getSettingsSnapshot().currentBookId, 'bundled:first')
158
+ await first.storage.initializeBundledBooks([entry('third')])
159
+ assert.equal((await first.storage.load()).books.length, 2, 'completed marker also prevents later direct reseeding')
160
+ } finally {
161
+ first.dispose()
162
+ second.dispose()
163
+ }
164
+ })
165
+
166
+ test('a legacy full AQ import is adopted only after every parsed segment matches, without changing progress or ID', async () => {
167
+ const factory = new IDBFactory()
168
+ const storage = makeStorage(factory)
169
+ const markdown = await readFile(new URL('../samples/ebooks/aq-zheng-zhuan-wikisource.md', import.meta.url), 'utf8')
170
+ const bytes = new TextEncoder().encode(markdown.slice('# 阿Q正傳\n\n'.length))
171
+ const file = bytesFile('阿Q正传.txt', bytes)
172
+ const original = new NovelStore(storage)
173
+ await original.ready
174
+ const imported = await original.importFile(file)
175
+ const advanced = { ...imported, progress: 7 }
176
+ await storage.updateBook(advanced)
177
+ const before = await storage.load()
178
+ original.dispose()
179
+ const store = new NovelStore(makeStorage(factory), { bundledBooks: [{ id: 'aq-zheng-zhuan', title: '阿Q正传', format: 'txt', createFile: () => file }, bundledBook('second')] })
180
+ try {
181
+ await store.ready
182
+ assert.equal(store.getSnapshot().error, null)
183
+ assert.equal(imported.segmentCount, 98)
184
+ assert.equal(store.getSnapshot().books.length, 2)
185
+ assert.deepEqual(store.getSnapshot().books.find(book => book.id === imported.id), advanced)
186
+ assert.equal(store.getSnapshot().books.some(book => book.id === 'bundled:aq-zheng-zhuan'), false)
187
+ assert.deepEqual((await store.storage.load()).settings, before.settings)
188
+ assert.equal((await store.storage.getSegment(imported.id, 97)).text.length > 0, true)
189
+ } finally {
190
+ store.dispose()
191
+ }
192
+ })
193
+
194
+ for (const mismatch of ['last text', 'chapter metadata']) {
195
+ test(`same title/format/count does not conflate different content: ${mismatch}`, async () => {
196
+ const storage = makeStorage()
197
+ const descriptor = bundledBook('first', '第一章 开始\n\n首段。\n\n第二章 结束\n\n末段。')
198
+ const parsed = parseTextBook('第一章 开始\n\n首段。\n\n第二章 结束\n\n末段。').segments
199
+ const changed = structuredClone(parsed)
200
+ if (mismatch === 'last text') changed.at(-1).text = '不同的末段。'
201
+ else changed.at(-1).chapterTitle = '不同章节'
202
+ const userBook = { id: 'user-book', title: descriptor.title, format: 'txt', segmentCount: parsed.length, progress: 1 }
203
+ await storage.addBook(userBook, changed)
204
+ const store = new NovelStore(storage, { bundledBooks: [descriptor] })
205
+ try {
206
+ await store.ready
207
+ assert.equal(store.getSnapshot().error, null)
208
+ assert.equal(store.getSnapshot().books.length, 2)
209
+ assert.deepEqual(store.getSnapshot().books.find(book => book.id === userBook.id), userBook)
210
+ assert.deepEqual(await storage.getSegment(userBook.id, 1), changed[1])
211
+ assert.deepEqual(await storage.getSegment('bundled:first', 1), parsed[1])
212
+ } finally {
213
+ store.dispose()
214
+ }
215
+ })
216
+ }
217
+
218
+ for (const failure of ['parse', 'factory']) {
219
+ test(`${failure} failure is visible, persists no partial library or marker, and permits refresh retry`, async () => {
220
+ const factory = new IDBFactory()
221
+ const broken = failure === 'parse'
222
+ ? bundledBook('second', ' ')
223
+ : { ...bundledBook('second'), createFile: async () => { throw new Error('factory failed') } }
224
+ let store = new NovelStore(makeStorage(factory), { bundledBooks: [bundledBook('first'), broken] })
225
+ try {
226
+ await store.ready
227
+ assert.equal(store.getSnapshot().hydrated, true)
228
+ assert.match(store.getSnapshot().error, failure === 'parse' ? /正文/ : /factory failed/)
229
+ await expectUninitialized(store.storage)
230
+ await assert.rejects(store.setOption('enabled', false), /本地书库不可用/)
231
+ store.dispose()
232
+ store = new NovelStore(makeStorage(factory), { bundledBooks: [bundledBook('first'), bundledBook('second')] })
233
+ await store.ready
234
+ assert.equal(store.getSnapshot().error, null)
235
+ assert.equal(store.getSnapshot().books.length, 2)
236
+ assert.equal((await store.storage.load()).bundledBooksInitialized, true)
237
+ } finally {
238
+ store.dispose()
239
+ }
240
+ })
241
+ }
242
+
243
+ test('synchronous transaction write failure rolls back preceding books, passages and marker', async () => {
244
+ const storage = makeStorage()
245
+ try {
246
+ const invalid = entry('second')
247
+ invalid.segments[0].uncloneable = () => undefined
248
+ await assert.rejects(storage.initializeBundledBooks([entry('first'), invalid]), { name: 'DataCloneError' })
249
+ await expectUninitialized(storage)
250
+ assert.equal((await storage.initializeBundledBooks([entry('first'), entry('second')])).books.length, 2)
251
+ } finally {
252
+ storage.close()
253
+ }
254
+ })
255
+
256
+ test('asynchronous abort after marker write rolls back all records and hydration can retry', async () => {
257
+ const storage = makeStorage()
258
+ await storage.load()
259
+ const db = storage.database
260
+ const transaction = db.transaction.bind(db)
261
+ db.transaction = (...args) => {
262
+ const tx = transaction(...args)
263
+ if (args[1] === 'readwrite') {
264
+ const settings = tx.objectStore('settings')
265
+ const put = settings.put.bind(settings)
266
+ settings.put = value => {
267
+ const request = put(value)
268
+ if (value.key === 'bundled-books-v1') request.addEventListener('success', () => tx.abort())
269
+ return request
270
+ }
271
+ }
272
+ return tx
273
+ }
274
+ const store = new NovelStore(storage, { bundledBooks: [bundledBook('first'), bundledBook('second')] })
275
+ try {
276
+ await store.ready
277
+ assert.ok(store.getSnapshot().error)
278
+ db.transaction = transaction
279
+ await expectUninitialized(storage)
280
+ const retried = await storage.initializeBundledBooks([entry('first'), entry('second')])
281
+ assert.equal(retried.books.length, 2)
282
+ assert.equal(retried.bundledBooksInitialized, true)
283
+ } finally {
284
+ store.dispose()
285
+ }
286
+ })
287
+
288
+ test('the original constructor leaves a library empty without requiring a provisioning API', async () => {
289
+ const memory = new MemoryStorage()
290
+ assert.equal(memory.initializeBundledBooks, undefined)
291
+ const oldStore = new NovelStore(memory)
292
+ const storage = makeStorage()
293
+ const emptyStore = new NovelStore(storage, { bundledBooks: [] })
294
+ try {
295
+ await Promise.all([oldStore.ready, emptyStore.ready])
296
+ assert.deepEqual(oldStore.getSnapshot().books, [])
297
+ assert.equal(oldStore.getSnapshot().error, null)
298
+ assert.deepEqual(emptyStore.getSnapshot().books, [])
299
+ await expectUninitialized(storage)
300
+ } finally {
301
+ oldStore.dispose()
302
+ emptyStore.dispose()
303
+ }
304
+ })
305
+
306
+ async function actualCatalog() {
307
+ const manifest = JSON.parse(await readFile(new URL('../samples/ebooks/sources.json', import.meta.url), 'utf8'))
308
+ const markdown = await readFile(new URL('../samples/ebooks/aq-zheng-zhuan-wikisource.md', import.meta.url), 'utf8')
309
+ const legacyText = markdown.slice('# 阿Q正傳\n\n'.length)
310
+ return {
311
+ legacyText,
312
+ bundledBooks: manifest.books.map(book => ({ ...book, createFile: async () => bytesFile(book.file, await readFile(new URL(`../samples/ebooks/${book.file}`, import.meta.url))) })),
313
+ bundledCatalog: { version: 2, removedIds: ['shanhaijing-illustrated'], updates: [{ id: 'aq-zheng-zhuan', fromFormat: 'txt', format: 'md', createFile: () => bytesFile('old.txt', new TextEncoder().encode(legacyText)) }] },
314
+ }
315
+ }
316
+ async function oldCatalog(storage, { selected = 'bundled:aq-zheng-zhuan', taggedRandom = false } = {}) {
317
+ const catalog = await actualCatalog()
318
+ const aq = entry('aq-zheng-zhuan', catalog.legacyText)
319
+ aq.book = { ...aq.book, ...(taggedRandom ? { id: 'tagged-aq' } : {}), title: '原来的阿Q标题', progress: 7, customMetadata: 'kept' }
320
+ const removed = entry('shanhaijing-illustrated', '旧版默认节选。')
321
+ if (taggedRandom) removed.book.id = 'tagged-removed'
322
+ const english = entry('million-pound-bank-note', 'English original remains untouched.')
323
+ await storage.initializeBundledBooks([english, removed, aq])
324
+ const settings = { ...DEFAULT_SETTINGS, currentBookId: selected, mainTitle: '用户标题', extraTitle: '附加', continueOnReopen: true, targetTypes: ['command'], customSetting: 'unchanged' }
325
+ await storage.saveSettings(settings)
326
+ return { catalog, aq, removed, english, settings }
327
+ }
328
+
329
+ test('actual fresh catalog provisions exactly English TXT and complete AQ MD and advances both markers atomically', async () => {
330
+ const catalog = await actualCatalog()
331
+ const storage = makeStorage()
332
+ const store = new NovelStore(storage, catalog)
333
+ try {
334
+ await store.ready
335
+ assert.equal(store.getSnapshot().error, null)
336
+ assert.deepEqual(store.getSnapshot().books.map(book => [book.bundledId, book.format]), [['aq-zheng-zhuan', 'md'], ['million-pound-bank-note', 'txt']])
337
+ assert.equal(store.getSettingsSnapshot().currentBookId, 'bundled:million-pound-bank-note')
338
+ assert.equal((await storage.load()).bundledCatalogVersion, 2)
339
+ const aq = store.getSnapshot().books.find(book => book.bundledId === 'aq-zheng-zhuan')
340
+ const body = (await Promise.all(Array.from({ length: aq.segmentCount }, (_, index) => storage.getSegment(aq.id, index)))).map(segment => segment.text).join('')
341
+ assert.match(body, /第九章/u)
342
+ assert.match(body, /Dbenbenn/u)
343
+ } finally { store.dispose() }
344
+ })
345
+
346
+ for (const taggedRandom of [false, true]) {
347
+ test(`v1 catalog migration preserves canonical AQ identity/progress/passages/settings and removes only defaults (tagged random: ${taggedRandom})`, async () => {
348
+ const storage = makeStorage()
349
+ const seed = await oldCatalog(storage, { taggedRandom, selected: taggedRandom ? 'tagged-aq' : 'bundled:aq-zheng-zhuan' })
350
+ if (!taggedRandom) {
351
+ // Stable default IDs are sufficient, even if an old record lost its tag.
352
+ delete seed.aq.book.bundledId
353
+ delete seed.removed.book.bundledId
354
+ await storage.updateBook(seed.aq.book)
355
+ await storage.updateBook(seed.removed.book)
356
+ }
357
+ const manual = [
358
+ { ...seed.aq.book, id: 'manual-aq', bundledId: undefined },
359
+ { ...seed.removed.book, id: 'manual-shanhaijing', bundledId: undefined },
360
+ ].map(({ bundledId: _tag, ...book }) => book)
361
+ await storage.addBook(manual[0], seed.aq.segments)
362
+ await storage.addBook(manual[1], seed.removed.segments)
363
+ const before = await storage.load()
364
+ const store = new NovelStore(storage, seed.catalog)
365
+ try {
366
+ await store.ready
367
+ assert.equal(store.getSnapshot().error, null)
368
+ const after = await storage.load()
369
+ assert.equal(after.bundledCatalogVersion, 2)
370
+ assert.equal(after.bundledBooksInitialized, true)
371
+ assert.deepEqual(after.settings, before.settings)
372
+ assert.equal(store.getSettingsSnapshot().currentBookId, seed.aq.book.id)
373
+ assert.deepEqual(after.books.find(book => book.id === seed.aq.book.id), { ...seed.aq.book, format: 'md' })
374
+ for (let index = 0; index < seed.aq.segments.length; index++) assert.deepEqual(await storage.getSegment(seed.aq.book.id, index), seed.aq.segments[index])
375
+ assert.equal(await storage.getSegment(seed.removed.book.id, 0), null)
376
+ assert.equal(after.books.some(book => book.id === seed.removed.book.id), false)
377
+ for (const book of manual) assert.deepEqual(after.books.find(candidate => candidate.id === book.id), book)
378
+ assert.deepEqual(await storage.getSegment(manual[1].id, 0), seed.removed.segments[0])
379
+ assert.deepEqual(after.books.find(book => book.id === seed.english.book.id), seed.english.book)
380
+ } finally { store.dispose() }
381
+ })
382
+ }
383
+
384
+ for (const keepEnglish of [false, true]) {
385
+ test(`removed current default selects a remaining book or null atomically (remaining: ${keepEnglish})`, async () => {
386
+ const storage = makeStorage()
387
+ const seed = await oldCatalog(storage, { selected: 'bundled:shanhaijing-illustrated' })
388
+ await storage.deleteBook(seed.aq.book.id)
389
+ if (!keepEnglish) await storage.deleteBook(seed.english.book.id)
390
+ const store = new NovelStore(storage, seed.catalog)
391
+ try {
392
+ await store.ready
393
+ assert.equal(store.getSnapshot().error, null)
394
+ const expectedId = keepEnglish ? seed.english.book.id : null
395
+ assert.equal(store.getSettingsSnapshot().currentBookId, expectedId)
396
+ assert.deepEqual((await storage.load()).settings, { ...seed.settings, currentBookId: expectedId })
397
+ assert.equal((await storage.load()).bundledCatalogVersion, 2)
398
+ assert.equal(await storage.getSegment(seed.removed.book.id, 0), null)
399
+ } finally { store.dispose() }
400
+ })
401
+ }
402
+
403
+ for (const clearAll of [false, true]) {
404
+ test(`v1 deleted defaults do not respawn during upgrade or subsequent refresh (cleared: ${clearAll})`, async () => {
405
+ const factory = new IDBFactory()
406
+ const storage = makeStorage(factory)
407
+ const seed = await oldCatalog(storage)
408
+ await storage.deleteBook(seed.aq.book.id)
409
+ await storage.deleteBook(seed.removed.book.id)
410
+ if (clearAll) await storage.deleteBook(seed.english.book.id)
411
+ await storage.saveSettings({ ...seed.settings, currentBookId: clearAll ? null : seed.english.book.id })
412
+ const noParse = { ...seed.catalog, bundledBooks: seed.catalog.bundledBooks.map(book => ({ ...book, createFile() { throw new Error('must not reseed') } })), bundledCatalog: { ...seed.catalog.bundledCatalog, updates: seed.catalog.bundledCatalog.updates.map(update => ({ ...update, createFile() { throw new Error('deleted AQ must not be parsed') } })) } }
413
+ let store = new NovelStore(storage, noParse)
414
+ try {
415
+ await store.ready
416
+ assert.equal(store.getSnapshot().error, null)
417
+ assert.equal((await storage.load()).bundledCatalogVersion, 2)
418
+ const before = await storage.load()
419
+ store.dispose()
420
+ store = new NovelStore(makeStorage(factory), noParse)
421
+ await store.ready
422
+ assert.equal(store.getSnapshot().error, null)
423
+ assert.deepEqual(await store.storage.load(), before)
424
+ assert.equal(store.getSnapshot().books.length, clearAll ? 0 : 1)
425
+ } finally { store.dispose() }
426
+ })
427
+ }
428
+
429
+ test('untagged legacy adopted imports remain user-owned despite exact canonical text and title', async () => {
430
+ const storage = makeStorage()
431
+ const seed = await oldCatalog(storage)
432
+ await storage.deleteBook(seed.aq.book.id)
433
+ const { bundledId: _tag, ...manual } = { ...seed.aq.book, id: 'random-legacy-adopted' }
434
+ await storage.addBook(manual, seed.aq.segments)
435
+ await storage.saveSettings({ ...seed.settings, currentBookId: manual.id })
436
+ const store = new NovelStore(storage, seed.catalog)
437
+ try {
438
+ await store.ready
439
+ assert.equal(store.getSnapshot().error, null)
440
+ assert.deepEqual(store.getSnapshot().books.find(book => book.id === manual.id), manual)
441
+ assert.equal(store.getSettingsSnapshot().currentBookId, manual.id)
442
+ assert.equal(store.getSnapshot().books.some(book => book.id === seed.aq.book.id), false)
443
+ } finally { store.dispose() }
444
+ })
445
+
446
+ for (const mismatch of ['text', 'chapter metadata', 'missing segment']) {
447
+ test(`identified AQ with noncanonical ${mismatch} is not rewritten or reset`, async () => {
448
+ const storage = makeStorage()
449
+ const seed = await oldCatalog(storage)
450
+ const changed = structuredClone(seed.aq.segments)
451
+ if (mismatch === 'text') changed.at(-1).text += ' 用户修改'
452
+ else if (mismatch === 'chapter metadata') changed.at(-1).chapterTitle = '用户章节'
453
+ else changed.pop()
454
+ await storage.deleteBook(seed.aq.book.id)
455
+ await storage.addBook(seed.aq.book, changed)
456
+ const store = new NovelStore(storage, seed.catalog)
457
+ try {
458
+ await store.ready
459
+ assert.equal(store.getSnapshot().error, null)
460
+ assert.deepEqual(store.getSnapshot().books.find(book => book.id === seed.aq.book.id), seed.aq.book)
461
+ assert.deepEqual(await storage.getSegment(seed.aq.book.id, changed.length - 1), changed.at(-1))
462
+ assert.equal((await storage.load()).bundledCatalogVersion, 2)
463
+ } finally { store.dispose() }
464
+ })
465
+ }
466
+
467
+ for (const failure of ['synchronous', 'abort']) {
468
+ test(`catalog ${failure} failure rolls back deletion, AQ metadata, selection and version; refresh retries`, async () => {
469
+ const factory = new IDBFactory()
470
+ const storage = makeStorage(factory)
471
+ const seed = await oldCatalog(storage, { selected: 'bundled:shanhaijing-illustrated' })
472
+ const before = await storage.load()
473
+ const db = storage.database
474
+ const transaction = db.transaction.bind(db)
475
+ db.transaction = (...args) => {
476
+ const tx = transaction(...args)
477
+ if (args[1] === 'readwrite') {
478
+ const settings = tx.objectStore('settings')
479
+ const put = settings.put.bind(settings)
480
+ settings.put = value => {
481
+ if (value.key !== 'bundled-catalog-version') return put(value)
482
+ if (failure === 'synchronous') return put({ ...value, uncloneable() {} })
483
+ const request = put(value)
484
+ request.addEventListener('success', () => tx.abort())
485
+ return request
486
+ }
487
+ }
488
+ return tx
489
+ }
490
+ let store = new NovelStore(storage, seed.catalog)
491
+ try {
492
+ await store.ready
493
+ assert.ok(store.getSnapshot().error)
494
+ db.transaction = transaction
495
+ assert.deepEqual(await storage.load(), before)
496
+ assert.deepEqual(await storage.getSegment(seed.removed.book.id, 0), seed.removed.segments[0])
497
+ assert.deepEqual(await storage.getSegment(seed.aq.book.id, 7), seed.aq.segments[7])
498
+ await assert.rejects(store.setOption('enabled', false), /本地书库不可用/u)
499
+ store.dispose()
500
+ store = new NovelStore(makeStorage(factory), seed.catalog)
501
+ await store.ready
502
+ assert.equal(store.getSnapshot().error, null)
503
+ assert.equal((await store.storage.load()).bundledCatalogVersion, 2)
504
+ assert.equal(store.getSnapshot().books.find(book => book.id === seed.aq.book.id).format, 'md')
505
+ assert.equal(await store.storage.getSegment(seed.removed.book.id, 0), null)
506
+ } finally { store.dispose() }
507
+ })
508
+ }
509
+
510
+ test('concurrent catalog migrations recheck the separate version and preserve winning state', async () => {
511
+ const factory = new IDBFactory()
512
+ const storage = makeStorage(factory)
513
+ const seed = await oldCatalog(storage)
514
+ storage.close()
515
+ const first = new NovelStore(makeStorage(factory), seed.catalog)
516
+ const second = new NovelStore(makeStorage(factory), seed.catalog)
517
+ try {
518
+ await Promise.all([first.ready, second.ready])
519
+ assert.equal(first.getSnapshot().error, null)
520
+ assert.equal(second.getSnapshot().error, null)
521
+ assert.deepEqual(first.getSnapshot(), second.getSnapshot())
522
+ assert.equal((await first.storage.load()).bundledCatalogVersion, 2)
523
+ assert.equal(first.getSnapshot().books.find(book => book.id === seed.aq.book.id).progress, 7)
524
+ assert.equal(first.getSnapshot().books.length, 2)
525
+ } finally { first.dispose(); second.dispose() }
526
+ })
@@ -5,6 +5,12 @@ import React from 'react'
5
5
  import TestRenderer, { act } from 'react-test-renderer'
6
6
  import { passageSnapshotKey } from '../src/store.js'
7
7
  import { registerChatAdapter } from '../src/chat-adapter.js'
8
+ import { PG_NOTICE, PG_LICENSE_DOWNLOAD } from '../src/pg-notice.js'
9
+ import { readFile } from 'node:fs/promises'
10
+
11
+ const fullLicense = await readFile(new URL('../samples/ebooks/LICENSE.md', import.meta.url), 'utf8')
12
+ const licenseHref = `data:text/plain;charset=utf-8,${encodeURIComponent(fullLicense)}`
13
+ const getSampleLicenseHref = () => licenseHref
8
14
 
9
15
  // Mirrors CURRENT 0.2.1-rc.2 DisclosureRow/TextShimmer nesting, not a replacement
10
16
  // renderer. Trusted events below are handler-contract probes, NOT browser evidence.
@@ -52,7 +58,7 @@ function adapterFixture(content = thought('node-a'), session = 'session-a') {
52
58
  }
53
59
  const ctx = { slots: { inject: (_key, fn) => fn(), register: () => () => {} }, effect: fn => { effects.push(fn()) } }
54
60
  return {
55
- dom, claims, continues, types, actions, start: () => registerChatAdapter(ctx, store, React, 'novel'),
61
+ dom, claims, continues, types, actions, start: () => registerChatAdapter(ctx, store, React, 'novel', { getSampleLicenseHref }),
56
62
  passage: (key, status) => { statuses.set(key, status); passagesChanged() },
57
63
  invalidate: () => { store.cacheGeneration += 1 },
58
64
  settings: patch => { settings = { ...settings, ...patch }; settingsChanged() },
@@ -240,7 +246,7 @@ function bodyFixture() {
240
246
  dom.window.document.querySelector('[data-variant="think"]').append(marker)
241
247
  let Body
242
248
  const ctx = { slots: { inject: (_key, fn) => fn(), register: (_options, component) => { Body = component; return () => {} } }, effect: () => {} }
243
- registerChatAdapter(ctx, {}, React, 'novel')
249
+ registerChatAdapter(ctx, {}, React, 'novel', { getSampleLicenseHref })
244
250
  return { dom, marker, Body }
245
251
  }
246
252
 
@@ -262,6 +268,11 @@ test('纯文本小说和章节位于原思考后的分隔线下;重挂载和
262
268
  await act(async () => { view = TestRenderer.create(React.createElement(Body, props), { createNodeMock: () => marker }) })
263
269
  assert.equal(view.root.findByProps({ 'data-novel-original': true }).findByType('p').children.join(''), props.text)
264
270
  assert.equal(view.root.findByProps({ 'data-novel-passage': 1 }).children.join(''), 'A cached passage')
271
+ const passage = view.root.findByProps({ 'data-novel-passage': 1 })
272
+ assert.equal(passage.props.style.maxHeight, 'min(40vh, 20.8em)')
273
+ assert.equal(passage.props.style.overflowY, 'auto')
274
+ assert.equal(passage.props.tabIndex, 0, '溢出的完整正文支持键盘滚动')
275
+ assert.equal(view.root.findByProps({ 'data-novel-original': true }).props.style, undefined, '不约束宿主原始正文')
265
276
  assert.equal(view.root.findByProps({ 'data-novel-label': true }).children.join(''), 'chat.novel · 第一章')
266
277
  assert.equal(view.root.findAllByType('hr').length, 1)
267
278
  assert.equal(view.toJSON().children[0].props['data-novel-original'], true)
@@ -329,6 +340,9 @@ test('五类区域独立定位,工具原正文保持且分隔线下只追加
329
340
  assert.ok(append.previousElementSibling.hasAttribute('data-native-output'), '小说位于原生工具正文之后')
330
341
  assert.match(append.querySelector('[data-novel-label]').textContent, /章节甲/u)
331
342
  assert.equal(append.lastElementChild.textContent, literal)
343
+ assert.equal(append.lastElementChild.style.maxHeight, 'min(40vh, 20.8em)')
344
+ assert.equal(append.lastElementChild.style.overflowY, 'auto')
345
+ assert.equal(append.lastElementChild.tabIndex, 0)
332
346
  assert.equal(append.querySelector('a, img, script, pre, h1'), null)
333
347
  }
334
348
  assert.deepEqual(outputs.map(node => node.outerHTML), originalOutputs)
@@ -431,3 +445,74 @@ test('流式文本和属性变更在同一帧内只合并成一次重扫', async
431
445
  assert.equal(cancelled, 0)
432
446
  } finally { f.close() }
433
447
  })
448
+
449
+ test('PG reasoning has a full readable §1.E.1 notice and offline license outside the clipped passage', async () => {
450
+ const { dom, marker, Body } = bodyFixture()
451
+ const settings = { enabled: true, currentBookId: 'legacy-arbitrary-id', targetTypes: ['reasoning'] }
452
+ let status = { kind: 'ready', index: 12, projectGutenberg: true, passage: { text: 'PG prose <img src=x> $100' } }
453
+ const props = {
454
+ text: 'REAL HOST THOUGHT', running: true, sessionId: 'session-a',
455
+ useNovelSettings: select => select(settings),
456
+ useNovelPassages: select => select({ [passageSnapshotKey(settings.currentBookId, readingKey('session-a', '14:assistant-step1:1'))]: status }),
457
+ renderFactorySlot: (_name, input) => React.createElement('p', null, input.text), t: key => key,
458
+ }
459
+ let view
460
+ try {
461
+ await act(async () => { view = TestRenderer.create(React.createElement(Body, props), { createNodeMock: () => marker }) })
462
+ const notice = view.root.findByProps({ 'data-novel-pg-notice': true })
463
+ const passage = view.root.findByProps({ 'data-novel-passage': 13 })
464
+ assert.equal(notice.parent, passage.parent, 'notice is a sibling, never inside the scroll viewport')
465
+ assert.equal(notice.findByType('p').children.join(''), PG_NOTICE)
466
+ assert.equal(notice.props.style.maxHeight, undefined)
467
+ assert.equal(notice.props.style.overflowY, undefined)
468
+ assert.equal(notice.props.style.whiteSpace, 'normal')
469
+ assert.equal(view.root.findAllByType('details').length, 0)
470
+ const license = notice.findByType('a')
471
+ assert.equal(license.props.href, licenseHref)
472
+ assert.equal(license.props.download, PG_LICENSE_DOWNLOAD)
473
+ assert.equal(decodeURIComponent(license.props.href.split(',').slice(1).join(',')), fullLicense)
474
+ assert.equal(passage.children.join(''), status.passage.text, 'novel stays literal text')
475
+ assert.equal(view.root.findAllByType('img').length, 0)
476
+ assert.equal(view.root.findByProps({ 'data-novel-original': true }).findByType('p').children.join(''), props.text)
477
+ for (const next of [{ ...status, projectGutenberg: false }, { kind: 'loading' }, { kind: 'end' }, { kind: 'error' }]) {
478
+ status = next
479
+ await act(async () => view.update(React.createElement(Body, props)))
480
+ assert.equal(view.root.findAllByProps({ 'data-novel-pg-notice': true }).length, 0)
481
+ assert.equal(view.root.findAllByType('a').length, 0, 'AQ/unrelated books and status messages have no PG notice')
482
+ }
483
+ } finally { await act(async () => view?.unmount()); dom.window.close() }
484
+ })
485
+
486
+ test('PG tool append exposes identical full notice/offline license without touching host output', async () => {
487
+ const f = adapterFixture(toolRow('read', 'read', 'pg-call') + commandRow())
488
+ try {
489
+ f.start(); f.settings({ targetTypes: ['read-file', 'command'] })
490
+ const outputs = [...document.querySelectorAll('[data-native-output]')]
491
+ const originalOutputs = outputs.map(node => node.outerHTML)
492
+ for (const header of document.querySelectorAll('[data-disclosure-row], [data-sample="bash"]')) {
493
+ f.actions.click(trustedClick(header)); header.setAttribute('aria-expanded', 'true')
494
+ }
495
+ await settle()
496
+ for (const key of f.claims) f.passage(key, { kind: 'ready', index: 3, projectGutenberg: true, passage: { text: 'Literal PG <script> & prose' } })
497
+ await settle()
498
+ assert.equal(document.querySelectorAll('[data-novel-pg-notice]').length, 2)
499
+ for (const append of document.querySelectorAll('[data-novel-append]')) {
500
+ const notice = append.querySelector('[data-novel-pg-notice]')
501
+ const passage = append.querySelector('[data-novel-passage]')
502
+ assert.equal(notice.parentElement, passage.parentElement)
503
+ assert.equal(notice.querySelector('p').textContent, PG_NOTICE)
504
+ assert.equal(notice.style.maxHeight, '')
505
+ assert.equal(notice.style.overflowY, '')
506
+ assert.equal(append.querySelector('details, script'), null)
507
+ assert.equal(notice.querySelector('a').getAttribute('href'), licenseHref)
508
+ assert.equal(notice.querySelector('a').download, PG_LICENSE_DOWNLOAD)
509
+ assert.equal(passage.textContent, 'Literal PG <script> & prose')
510
+ }
511
+ assert.deepEqual(outputs.map(node => node.outerHTML), originalOutputs)
512
+ f.settings({ mainTitle: 'New title' })
513
+ assert.equal(document.querySelectorAll('[data-novel-pg-notice]').length, 2, 'refresh never duplicates notices')
514
+ for (const key of f.claims) f.passage(key, { kind: 'ready', index: 4, projectGutenberg: false, passage: { text: 'AQ or unrelated prose' } })
515
+ assert.equal(document.querySelector('[data-novel-pg-notice], [data-novel-append] a'), null)
516
+ assert.deepEqual(outputs.map(node => node.outerHTML), originalOutputs)
517
+ } finally { f.close() }
518
+ })