dsh-half-page 0.3.53 → 0.4.43

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 (4) hide show
  1. package/README.md +10 -2
  2. package/client.js +995 -672
  3. package/index.js +1087 -124
  4. package/package.json +1 -1
package/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // dsh-half-page · 半页(自己的读书与写字)
2
2
  // 宿主侧:书库、切章、读后感、进度;客户端面板读 HTTP 路由。
3
- import { readFile, writeFile, mkdir, readdir, stat, rename, open } from 'node:fs/promises'
3
+ import {readFile, writeFile, mkdir, readdir, stat, rename, open, unlink, copyFile, appendFile} from 'node:fs/promises'
4
4
  import { readFileSync } from 'node:fs'
5
+ import { spawn } from 'node:child_process'
5
6
  import { join, basename, dirname, extname, resolve, relative, isAbsolute } from 'node:path'
6
- import { homedir } from 'node:os'
7
+ import {homedir, tmpdir} from 'node:os'
7
8
  import { fileURLToPath } from 'node:url'
8
9
  import { readTimeline, newestSessionId } from './lib/session-probe.js'
9
10
  import { loadCreateUserMessage, SOURCE_KIND } from './lib/notice.js'
@@ -158,6 +159,211 @@ export async function saveState(dir, st) {
158
159
  await writeJson(join(dir, 'state.json'), st)
159
160
  }
160
161
 
162
+ /* ---------------- 一个书房,多个读者 ----------------
163
+ * 旧版本只有书级进度(books[id].readThrough/next/noteUntil),等于「这台机器上所有读者共用一条进度」。
164
+ * 现在加一层 readers[<读者 id>]:每个读者各有一份进度,书级只留「读得最远」(furthest)。
165
+ * 读者 id 就是会话 id;拿不到会话就落到 LEGACY_READER(老数据迁移过来的那份)。
166
+ * 读后感仍然只有一个 读后感.md,靠署名区分——不要拆成多个文件。
167
+ */
168
+ export const LEGACY_READER = '__legacy__'
169
+ /** 那份「所有人都从这儿接」的书签,面板上叫什么。以前叫「默认读者」,容易被当成一个人;它其实是书级进度。 */
170
+ export const LEGACY_READER_NAME = '读书总进度'
171
+ /** 读者 id → 名字的临时表:建分片时顺手把名字写对,别把会话 id 当名字存进去。 */
172
+ export const READER_NAMES = new Map()
173
+
174
+ /** 老状态没有 readers:把 books[id] 现有进度抄成「总读书进度」,幂等。
175
+ * 一本书都没读过(新机器第一次装)就不建这一份——不然别人装上会看见一个空的「总读书进度」。 */
176
+ export function migrateReaders(st) {
177
+ if (!st || typeof st !== 'object') return st
178
+ if (st.readers && typeof st.readers === 'object') {
179
+ if (st.readers[LEGACY_READER]) st.readers[LEGACY_READER].name = LEGACY_READER_NAME
180
+ return st
181
+ }
182
+ const legacy = { name: LEGACY_READER_NAME, books: {} }
183
+ for (const [id, rec] of Object.entries(st.books || {})) {
184
+ const has = (Number(rec.readThrough) || 0) > 0 || (Number(rec.noteUntil) || 0) > 0
185
+ || (Number(rec.next) || 1) > 1 || Boolean(rec.lastReadAt)
186
+ if (!Number.isFinite(Number(rec.furthest))) rec.furthest = Number(rec.readThrough) || 0
187
+ if (!has) continue
188
+ legacy.books[id] = {
189
+ readThrough: Number(rec.readThrough) || 0,
190
+ next: Number(rec.next) || 1,
191
+ noteUntil: Number(rec.noteUntil) || 0,
192
+ lastReadAt: rec.lastReadAt || '',
193
+ }
194
+ }
195
+ st.readers = Object.keys(legacy.books).length > 0 ? { [LEGACY_READER]: legacy } : {}
196
+ return st
197
+ }
198
+
199
+ /** 某个读者的分片(没有就建)。name 只是给人看的。 */
200
+ export function readerShard(st, rid, name) {
201
+ migrateReaders(st)
202
+ const key = String(rid || LEGACY_READER)
203
+ const r = st.readers[key] || (st.readers[key] = { name: name || (key === LEGACY_READER ? LEGACY_READER_NAME : key), books: {} })
204
+ if (name && r.name !== name) r.name = name
205
+ return r
206
+ }
207
+
208
+ /** 某个读者在某本书上的进度(没有就建空的;空分片先继承书级那份,等于「你还没动过,从大家读到的地方接」)。 */
209
+ export function readerBook(st, rid, id) {
210
+ const shard = readerShard(st, rid, READER_NAMES.get(String(rid)) || '')
211
+ const own = shard.books[id]
212
+ if (own) return own
213
+ const base = st.books?.[id] || {}
214
+ return (shard.books[id] = {
215
+ readThrough: Number(base.readThrough) || 0,
216
+ next: Number(base.next) || 1,
217
+ noteUntil: Number(base.noteUntil) || 0,
218
+ lastReadAt: base.lastReadAt || '',
219
+ })
220
+ }
221
+
222
+ /** 读进度但不建:面板/书架扫一遍时用,避免给没读过的书建空分片。没有分片就继承书级。 */
223
+ /** 只看这位读者自己的分片:没读过返回 null(不继承书级)。面板「我读到哪」用它,避免把书级进度当成我的。 */
224
+ export function readerOwnBook(st, rid, id) {
225
+ migrateReaders(st)
226
+ const b = st.readers?.[String(rid || LEGACY_READER)]?.books?.[id]
227
+ if (!b) return null
228
+ return {
229
+ readThrough: Number(b.readThrough) || 0,
230
+ next: Number(b.next) || 1,
231
+ noteUntil: Number(b.noteUntil) || 0,
232
+ lastReadAt: b.lastReadAt || '',
233
+ }
234
+ }
235
+
236
+ export function readerBookRead(st, rid, id) {
237
+ migrateReaders(st)
238
+ const b = st.readers?.[String(rid || LEGACY_READER)]?.books?.[id]
239
+ if (b) {
240
+ return {
241
+ readThrough: Number(b.readThrough) || 0,
242
+ next: Number(b.next) || 1,
243
+ noteUntil: Number(b.noteUntil) || 0,
244
+ lastReadAt: b.lastReadAt || '',
245
+ }
246
+ }
247
+ const base = st.books?.[id] || {}
248
+ return {
249
+ readThrough: Number(base.readThrough) || 0,
250
+ next: Number(base.next) || 1,
251
+ noteUntil: Number(base.noteUntil) || 0,
252
+ lastReadAt: base.lastReadAt || '',
253
+ }
254
+ }
255
+
256
+ /** 书级「读得最远」:所有读者里最大的 readThrough,只增不减。 */
257
+ export function furthestOf(st, id) {
258
+ migrateReaders(st)
259
+ let far = Number(st.books?.[id]?.furthest) || 0
260
+ for (const r of Object.values(st.readers || {})) {
261
+ far = Math.max(far, Number(r.books?.[id]?.readThrough) || 0)
262
+ }
263
+ const rec = st.books?.[id]
264
+ if (rec) {
265
+ far = Math.max(far, Number(rec.readThrough) || 0)
266
+ rec.furthest = far
267
+ }
268
+ return far
269
+ }
270
+
271
+ /** 书级「读得最远」是谁读的:返回 { name, readThrough };没人读过就返回总进度那个名字。 */
272
+ export function furthestReaderOf(st, id) {
273
+ migrateReaders(st)
274
+ const far = furthestOf(st, id)
275
+ let best = null
276
+ for (const [rid, r] of Object.entries(st.readers || {})) {
277
+ if (rid === LEGACY_READER) continue
278
+ const n = Number(r.books?.[id]?.readThrough) || 0
279
+ if (n > 0 && (!best || n > best.readThrough)) best = { id: rid, name: r.name || rid, readThrough: n }
280
+ }
281
+ // 书级数字比所有读者分片都高(那条会话不在了),就没有具体的人可报
282
+ if (!best || best.readThrough < far) return { id: LEGACY_READER, name: LEGACY_READER_NAME, readThrough: far }
283
+ return { id: best.id, name: best.name, readThrough: far }
284
+ }
285
+ /** 面板 / 工具都要的读者一览:id、名字、每本书读到哪。
286
+ * 「默认读者」没有会话在用,它的分片停在迁移那一刻;但它代表的那条书签(书级 next/readThrough)
287
+ * 是所有人共用、一直在往前走的,所以这里给它显示书级那份——否则面板上会显得它永远没动。 */
288
+ export function readerSummary(st) {
289
+ migrateReaders(st)
290
+ const out = []
291
+ for (const [id, r] of Object.entries(st.readers || {})) {
292
+ const books = {}
293
+ let lastAt = 0
294
+ const readingOf = id === LEGACY_READER ? (st.books || {}) : (r.books || {})
295
+ for (const [bid, b] of Object.entries(readingOf)) {
296
+ books[bid] = { readThrough: Number(b.readThrough) || 0, next: Number(b.next) || 1, noteUntil: Number(b.noteUntil) || 0 }
297
+ const at = typeof b.lastReadAt === 'number' ? b.lastReadAt : Date.parse(String(b.lastReadAt || ''))
298
+ if (Number.isFinite(at) && at > lastAt) lastAt = at
299
+ }
300
+ // 一本都没读过的读者不往面板上摆(新机器、或刚建分片还没读);手动加的读者例外——加它就是为让它出现
301
+ if (Object.keys(books).length === 0 && !r.manual) continue
302
+ out.push({ id, name: r.name || id, books, today: readTodayOf(st, id), lastAt, manual: r.manual === true })
303
+ }
304
+ return out.sort((a, b) => (a.id === LEGACY_READER ? -1 : b.id === LEGACY_READER ? 1 : 0))
305
+ }
306
+
307
+ /** 这个读者最后读过的那本书(按分片里的 lastReadAt 取最大);没有就空串。 */
308
+ export function lastReadBookOf(st, rid) {
309
+ const key = String(rid || LEGACY_READER)
310
+ const books = st?.readers?.[key]?.books || {}
311
+ let best = ''
312
+ let at = ''
313
+ for (const [bid, b] of Object.entries(books)) {
314
+ const when = String(b?.lastReadAt || '')
315
+ if (!when) continue
316
+ if (when >= at) { at = when; best = bid }
317
+ }
318
+ if (best) return best
319
+ // 兜底:老分片没记 lastReadAt(早期版本 / 被回灌坏过)。挑读得最远的那本,
320
+ // 再不行看整机书级,最后才回落面板当前那本——总之别因为缺一个时间戳就报「不知道读哪本」。
321
+ let far = ''
322
+ let farN = 0
323
+ const pick = (obj) => {
324
+ for (const [bid, b] of Object.entries(obj || {})) {
325
+ const n = Math.max(Number(b?.readThrough) || 0, Number(b?.furthest) || 0)
326
+ if (n > farN) { farN = n; far = bid }
327
+ }
328
+ }
329
+ pick(books)
330
+ if (far) return far
331
+ pick(st?.books)
332
+ if (far) return far
333
+ return String(st?.current || '') || Object.keys(st?.books || {})[0] || ''
334
+ }
335
+
336
+ /** 简单文件锁:读后感是「读进来—改—写回去」,两个窗口同时写会丢一条。
337
+ * 拿不到就一直等(上限 20 秒),超时才放弃——宁可慢一点,也不许两段同时写同一个文件。
338
+ * 锁文件超过 30 秒没被删,当上一个进程死掉了,直接接管。 */
339
+ async function withFileLock(target, fn, tries = 800) {
340
+ const lock = target + '.lock'
341
+ let handle = null
342
+ for (let i = 0; i < tries; i += 1) {
343
+ try {
344
+ handle = await open(lock, 'wx')
345
+ break
346
+ } catch {
347
+ try {
348
+ const info = await stat(lock)
349
+ if (Date.now() - info.mtimeMs > 30 * 1000) {
350
+ await unlink(lock)
351
+ continue
352
+ }
353
+ } catch {}
354
+ await new Promise((r) => setTimeout(r, 15 + Math.floor(Math.random() * 25)))
355
+ }
356
+ }
357
+ try {
358
+ return await fn()
359
+ } finally {
360
+ if (handle) {
361
+ try { await handle.close() } catch {}
362
+ try { await unlink(lock) } catch {}
363
+ }
364
+ }
365
+ }
366
+
161
367
  /** 把整本书切成章:返回 [{title, start, end}] */
162
368
  export function splitChapters(text) {
163
369
  const idx = []
@@ -239,6 +445,67 @@ export function studyStateOf(st, now = Date.now()) {
239
445
  }
240
446
  }
241
447
 
448
+ /** 一条书房时间:字段齐全、缺的给默认;came from state.study.slots 或旧配置合成 */
449
+ export function normaliseStudySlot(raw, cfg, i = 0) {
450
+ const s = raw || {}
451
+ const mode = s.mode === 'day' || s.mode === 'week' ? s.mode : studyModeOf(cfg)
452
+ const dBudget = Math.min(7, Math.max(1, Math.floor(Number(s.per) || (mode === 'day' ? studyPerDayOf(cfg) : studyPerWeekOf(cfg)))))
453
+ return {
454
+ id: String(s.id || ('slot-' + (i + 1))),
455
+ enabled: s.enabled === true,
456
+ from: String(s.from ?? ''),
457
+ to: String(s.to ?? ''),
458
+ mode,
459
+ per: dBudget,
460
+ session: String(s.session ?? ''),
461
+ lastAt: Number(s.lastAt) || 0,
462
+ week: String(s.week || ''),
463
+ weekCount: Number(s.weekCount) || 0,
464
+ day: String(s.day || ''),
465
+ dayCount: Number(s.dayCount) || 0,
466
+ }
467
+ }
468
+
469
+ /** state.study.slots;一条都没有时用旧配置合成一条(老用户行为不变) */
470
+ export function studySlotsOf(st, cfg) {
471
+ const raw = Array.isArray(st?.study?.slots) ? st.study.slots : []
472
+ if (raw.length) return raw.map((s, i) => normaliseStudySlot(s, cfg, i))
473
+ return [normaliseStudySlot({
474
+ id: 'slot-1',
475
+ enabled: cfg?.studyEnabled === true,
476
+ from: cfg?.studyFrom ?? '',
477
+ to: cfg?.studyTo ?? '',
478
+ mode: studyModeOf(cfg),
479
+ per: studyModeOf(cfg) === 'day' ? studyPerDayOf(cfg) : studyPerWeekOf(cfg),
480
+ session: cfg?.studySession ?? '',
481
+ }, cfg, 0)]
482
+ }
483
+
484
+ /** 把一条 slot 摊成 decideStudy 认的 cfg 形状 */
485
+ export function slotCfgOf(slot) {
486
+ return {
487
+ studyEnabled: slot.enabled === true,
488
+ studyFrom: slot.from,
489
+ studyTo: slot.to,
490
+ studyMode: slot.mode,
491
+ studyPerDay: slot.per,
492
+ studyPerWeek: slot.per,
493
+ }
494
+ }
495
+
496
+ /** 一条 slot 自己的计数(跨周/跨天归零) */
497
+ export function slotStudyOf(slot, now = Date.now()) {
498
+ const week = weekKeyOf(now)
499
+ const day = localDayOf(now)
500
+ return {
501
+ lastAt: Number(slot.lastAt) || 0,
502
+ week,
503
+ weekCount: slot.week === week ? Number(slot.weekCount) || 0 : 0,
504
+ day,
505
+ dayCount: slot.day === day ? Number(slot.dayCount) || 0 : 0,
506
+ }
507
+ }
508
+
242
509
  /** 今天有没有读过(任一书的 lastReadAt 落在本地今天) */
243
510
  export function readSomethingToday(st, now = Date.now()) {
244
511
  const day = localDayOf(now)
@@ -548,6 +815,26 @@ export function readToday(st) {
548
815
  return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
549
816
  }
550
817
 
818
+ /** 记一格读书:全局 log + 这位读者自己的 rlog(两边都记,退章时一起退) */
819
+ export function bumpLog(st, t, id, readerId, inc = 1) {
820
+ const rid = readerId || LEGACY_READER
821
+ st.log = st.log || {}
822
+ st.log[t] = st.log[t] || {}
823
+ st.log[t][id] = Math.max(0, (Number(st.log[t][id]) || 0) + inc)
824
+ st.rlog = st.rlog || {}
825
+ st.rlog[t] = st.rlog[t] || {}
826
+ st.rlog[t][rid] = st.rlog[t][rid] || {}
827
+ st.rlog[t][rid][id] = Math.max(0, (Number(st.rlog[t][rid][id]) || 0) + inc)
828
+ }
829
+
830
+ /** 某位读者今天读了几章(按 rlog)。老账只有全局 log,所以「读书总进度」在没分片时回落到全局;具体读者记 0。 */
831
+ export function readTodayOf(st, readerId) {
832
+ const t = today()
833
+ const row = (st.rlog && st.rlog[t] && st.rlog[t][readerId]) || null
834
+ if (!row) return readerId === LEGACY_READER ? readToday(st) : 0
835
+ return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
836
+ }
837
+
551
838
  export async function notesPath(dir) {
552
839
  return join(dir, '读后感.md')
553
840
  }
@@ -575,32 +862,35 @@ async function latestSessionTitle() {
575
862
 
576
863
  export async function appendNote(dir, bookTitle, chapterTitle, lines, by) {
577
864
  const p = await notesPath(dir)
578
- let raw = ''
579
- try { raw = await readFile(p, 'utf8') } catch {}
580
- const esc = bookTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
581
- let block = `\n### ${chapterTitle}\n` + lines.map((l) => `- ${l}`).join('\n') + '\n'
582
- if (by) {
583
- const d = new Date()
584
- const pad = (n) => String(n).padStart(2, '0')
585
- const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
586
- block += `- \u21b3 \u6765\u81ea\uff1a${by} \u00b7 ${ts}\n`
587
- }
588
- const headRe = new RegExp(`^##\\s+${esc}\\s*$`, 'm')
589
- const m = headRe.exec(raw)
590
- if (!m) {
591
- raw = (raw.trim() ? raw.replace(/\s*$/, '') + '\n\n' : '') + `## ${bookTitle}\n` + block
592
- } else {
593
- const at0 = m.index + m[0].length
594
- const next = raw.slice(at0).search(/^##\s+/m)
595
- if (next < 0) {
596
- raw = raw.replace(/\s*$/, '') + '\n' + block
865
+ // 同一秒两个窗口写会丢一条:整段「读—改—写」放进锁里(锁是 p + '.lock')
866
+ return withFileLock(p, async () => {
867
+ let raw = ''
868
+ try { raw = await readFile(p, 'utf8') } catch {}
869
+ const esc = bookTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
870
+ let block = `\n### ${chapterTitle}\n` + lines.map((l) => `- ${l}`).join('\n') + '\n'
871
+ if (by) {
872
+ const d = new Date()
873
+ const pad = (n) => String(n).padStart(2, '0')
874
+ const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
875
+ block += `- \u21b3 \u6765\u81ea\uff1a${by} \u00b7 ${ts}\n`
876
+ }
877
+ const headRe = new RegExp(`^##\\s+${esc}\\s*$`, 'm')
878
+ const m = headRe.exec(raw)
879
+ if (!m) {
880
+ raw = (raw.trim() ? raw.replace(/\s*$/, '') + '\n\n' : '') + `## ${bookTitle}\n` + block
597
881
  } else {
598
- const at = at0 + next
599
- raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
882
+ const at0 = m.index + m[0].length
883
+ const next = raw.slice(at0).search(/^##\s+/m)
884
+ if (next < 0) {
885
+ raw = raw.replace(/\s*$/, '') + '\n' + block
886
+ } else {
887
+ const at = at0 + next
888
+ raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
889
+ }
600
890
  }
601
- }
602
- await writeFile(p, raw, 'utf8')
603
- return p
891
+ await writeFile(p, raw, 'utf8')
892
+ return p
893
+ })
604
894
  }
605
895
 
606
896
  /* ---------------- 图片:作品与画 ------------------
@@ -778,6 +1068,55 @@ export function apply(ctx, rawConfig) {
778
1068
  return out
779
1069
  }
780
1070
 
1071
+ /** 这一拍是谁在读:会话 id 当读者 id,标题当名字;没有会话就是老数据那份「默认读者」。 */
1072
+ const READER_NAME_CACHE = new Map()
1073
+ /** 名字看起来就是会话 id(而不是人给的名字):这种不能拿来当读者名显示。 */
1074
+ function nameIsId(name, id) {
1075
+ const s = String(name || '').trim()
1076
+ if (!s || s === id) return true
1077
+ return /^session-[0-9a-f-]{8,}$/i.test(s)
1078
+ }
1079
+ async function readerOf(exec) {
1080
+ const sid = exec?.agent?.session?.id || exec?.agent?.id || ''
1081
+ if (!sid) return { id: LEGACY_READER, name: LEGACY_READER_NAME }
1082
+ let name = READER_NAME_CACHE.get(sid)
1083
+ if (!name) {
1084
+ const header = exec?.agent?.session?.header || {}
1085
+ name = header.title || exec?.agent?.session?.title || ''
1086
+ if (nameIsId(name, sid)) name = await sessionTitleOf(sid)
1087
+ if (nameIsId(name, sid)) name = '会话 ' + String(sid).slice(-8)
1088
+ READER_NAME_CACHE.set(sid, name)
1089
+ READER_NAMES.set(String(sid), name)
1090
+ }
1091
+ return { id: String(sid), name }
1092
+ }
1093
+
1094
+ /** 面板用的读者一览:顺手把「名字还存成会话 id」的那些补成真名字,并写回 state。 */
1095
+ async function readersFor(dir, st) {
1096
+ const list = readerSummary(st)
1097
+ let fixed = false
1098
+ for (const r of list) {
1099
+ if (r.id === LEGACY_READER) continue
1100
+ if (!nameIsId(r.name, r.id)) continue
1101
+ let real = await sessionTitleOf(r.id)
1102
+ if (nameIsId(real, r.id)) real = '会话 ' + String(r.id).slice(-8)
1103
+ r.name = real
1104
+ if (st.readers?.[r.id]) st.readers[r.id].name = real
1105
+ READER_NAME_CACHE.set(r.id, real)
1106
+ READER_NAMES.set(r.id, real)
1107
+ fixed = true
1108
+ }
1109
+ if (fixed) await saveState(dir, st)
1110
+ return list
1111
+ }
1112
+
1113
+ /** 面板传过来的读者(下拉选的);没有就用默认读者 */
1114
+ function readerParam(st, url) {
1115
+ const asked = String(url.searchParams.get('reader') || '').trim()
1116
+ if (asked && st.readers && st.readers[asked]) return { id: asked, name: st.readers[asked].name || asked }
1117
+ return { id: LEGACY_READER, name: (st.readers?.[LEGACY_READER]?.name) || LEGACY_READER_NAME }
1118
+ }
1119
+
781
1120
  /** 只投那一句;成功才返回 { ok, at } */
782
1121
  async function deliverStudy(sessionId) {
783
1122
  const agent = await resolveAgent(sessionId)
@@ -806,26 +1145,43 @@ export function apply(ctx, rawConfig) {
806
1145
  studyBusy = true
807
1146
  try {
808
1147
  const cfgNow = await config()
809
- if (cfgNow.studyEnabled !== true) return
810
1148
  const dir = cfgNow.dir
811
1149
  const st = await loadState(dir)
812
1150
  const now = Date.now()
813
- const study = studyStateOf(st, now)
814
1151
  if (readSomethingToday(st, now)) return
815
- const sessionId = cfgNow.studySession || await newestSessionId(SESSIONS_ROOT)
816
- if (!sessionId) return
817
- const timeline = await readTimeline(SESSIONS_ROOT, sessionId, { tailFrames: 200 })
818
- const verdict = decideStudy({ cfg: cfgNow, study, now, timeline })
819
- if (!verdict.ok) return
820
- const sent = await deliverStudy(sessionId)
821
- if (!sent.ok) return
1152
+ const slots = studySlotsOf(st, cfgNow)
1153
+ let changed = false
1154
+ for (const slot of slots) {
1155
+ if (slot.enabled !== true) continue
1156
+ const w = studyWindowOf(slotCfgOf(slot))
1157
+ if (!w) continue
1158
+ if (!inStudyWindow(w, new Date(now))) continue
1159
+ const counters = slotStudyOf(slot, now)
1160
+ const sessionId = slot.session || await newestSessionId(SESSIONS_ROOT)
1161
+ if (!sessionId) continue
1162
+ const timeline = await readTimeline(SESSIONS_ROOT, sessionId, { tailFrames: 200 })
1163
+ const verdict = decideStudy({ cfg: slotCfgOf(slot), study: counters, now, timeline })
1164
+ if (!verdict.ok) continue
1165
+ const sent = await deliverStudy(sessionId)
1166
+ if (!sent.ok) continue
1167
+ slot.lastAt = sent.at
1168
+ slot.week = counters.week
1169
+ slot.weekCount = counters.weekCount + 1
1170
+ slot.day = counters.day
1171
+ slot.dayCount = counters.dayCount + 1
1172
+ changed = true
1173
+ }
1174
+ if (!changed) return
822
1175
  await ensureDir(dir)
823
- st.study = {
824
- lastAt: sent.at,
825
- week: study.week,
826
- weekCount: study.weekCount + 1,
827
- day: study.day,
828
- dayCount: study.dayCount + 1,
1176
+ st.study = { ...(st.study || {}), slots }
1177
+ // 顶上那几个旧字段跟着第一条走,面板/老代码读到的不至于错乱
1178
+ const first = slots[0]
1179
+ if (first) {
1180
+ st.study.lastAt = first.lastAt
1181
+ st.study.week = first.week
1182
+ st.study.weekCount = first.weekCount
1183
+ st.study.day = first.day
1184
+ st.study.dayCount = first.dayCount
829
1185
  }
830
1186
  await saveState(dir, st)
831
1187
  } catch {
@@ -847,10 +1203,26 @@ export function apply(ctx, rawConfig) {
847
1203
  }
848
1204
  })
849
1205
 
1206
+ let namesRepaired = false
850
1207
  const stateOf = async () => {
851
1208
  const { dir, perDay } = await config()
852
1209
  await ensureDir(dir)
853
1210
  const st = await loadState(dir)
1211
+ // 一次性把「名字存成会话 id」的读者修回标题(每个进程只做一次)
1212
+ if (!namesRepaired) {
1213
+ namesRepaired = true
1214
+ let fixed = false
1215
+ for (const [id, r] of Object.entries(st.readers || {})) {
1216
+ if (id === LEGACY_READER) continue
1217
+ if (!nameIsId(r.name, id)) { READER_NAMES.set(id, r.name); continue }
1218
+ let real = await sessionTitleOf(id)
1219
+ if (nameIsId(real, id)) real = '会话 ' + String(id).slice(-8)
1220
+ r.name = real
1221
+ READER_NAMES.set(id, real)
1222
+ fixed = true
1223
+ }
1224
+ if (fixed) await saveState(dir, st)
1225
+ }
854
1226
  const shelf = await listBooks(dir)
855
1227
  return { dir, perDay, st, shelf, today: today(), readToday: readToday(st) }
856
1228
  }
@@ -862,8 +1234,12 @@ export function apply(ctx, rawConfig) {
862
1234
  kind: 'exact',
863
1235
  path: '/dsh-reading.state',
864
1236
  async handler(req, res) {
865
- const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
1237
+ const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
1238
+ let localVersion = ''
1239
+ try { localVersion = JSON.parse(await readFile(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8')).version || '' } catch {}
1240
+
866
1241
  const cfgNow = await config()
1242
+ const rid0 = readerParam(st, new URL(req.url || '/', 'http://localhost')).id
867
1243
  const books = []
868
1244
  for (const b of shelf) {
869
1245
  const rec = st.books[b.id] || {}
@@ -874,6 +1250,16 @@ export function apply(ctx, rawConfig) {
874
1250
  chapters = (toc && toc.chapters && toc.chapters.length) || 0
875
1251
  } catch {}
876
1252
  }
1253
+ const ownShard = readerOwnBook(st, rid0, b.id)
1254
+ const mineN = Number(ownShard && ownShard.readThrough) || 0
1255
+ let mineTitle = ''
1256
+ if (mineN > 0) {
1257
+ try {
1258
+ const toc = await readTocOnly(dir, b.id)
1259
+ const ch = toc && toc.chapters && toc.chapters[mineN - 1]
1260
+ mineTitle = (ch && ch.title) || ''
1261
+ } catch {}
1262
+ }
877
1263
  books.push({
878
1264
  id: b.id,
879
1265
  title: rec.title || b.id,
@@ -881,6 +1267,10 @@ export function apply(ctx, rawConfig) {
881
1267
  mtime: b.mtime,
882
1268
  chapters,
883
1269
  readThrough: rec.readThrough || 0,
1270
+ mineReadThrough: mineN,
1271
+ mineChapterTitle: mineTitle,
1272
+ furthest: furthestOf(st, b.id),
1273
+ furthestReader: furthestReaderOf(st, b.id),
884
1274
  next: rec.next || 1,
885
1275
  lastReadAt: rec.lastReadAt || '',
886
1276
  current: st.current === b.id,
@@ -894,6 +1284,8 @@ export function apply(ctx, rawConfig) {
894
1284
  const liveSessions = await liveSessionList()
895
1285
  res.end(JSON.stringify({
896
1286
  ok: true, dir, perDay, today: today(), readToday: rt, current: st.current, books, notes,
1287
+ version: localVersion,
1288
+ readers: await readersFor(dir, st), liveSessions,
897
1289
  noteSort: Number(cfgNow.noteSort) || 0,
898
1290
  study: {
899
1291
  enabled: cfgNow.studyEnabled === true,
@@ -907,12 +1299,462 @@ export function apply(ctx, rawConfig) {
907
1299
  dayCount: st2.dayCount,
908
1300
  session: cfgNow.studySession || '',
909
1301
  sessions: liveSessions,
1302
+ slots: studySlotsOf(st, cfgNow).map((s, i) => {
1303
+ const c = slotStudyOf(s, Date.now())
1304
+ return {
1305
+ id: s.id, index: i, enabled: s.enabled, from: s.from, to: s.to, mode: s.mode, per: s.per,
1306
+ session: s.session, sessionName: (liveSessions.find((x) => x.id === s.session) || {}).title || '',
1307
+ lastAt: c.lastAt, dayCount: c.dayCount, weekCount: c.weekCount,
1308
+ }
1309
+ }),
910
1310
  },
911
1311
  }))
912
1312
  },
913
1313
  }),
914
1314
  )
915
1315
 
1316
+ // 保存「书房时间」列表(每条:启用/时段/频率/叫哪条会话)
1317
+ ctx.effect(() =>
1318
+ ctx.webServer.register({
1319
+ auth: sameSiteAuth,
1320
+ kind: 'exact',
1321
+ path: '/dsh-reading.restore',
1322
+ async handler(req, res) {
1323
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1324
+ const fail = (msg) => { try { res.end(JSON.stringify({ ok: false, error: String(msg) })) } catch {} }
1325
+ try {
1326
+ let body = ''
1327
+ for await (const c of req) body += c
1328
+ let j = {}
1329
+ try { j = JSON.parse(body || '{}') || {} } catch { return fail('不是合法的 JSON') }
1330
+ let src = j.json
1331
+ if (typeof src === 'string') { try { src = JSON.parse(src) } catch { return fail('这个文件不是半页的备份') } }
1332
+ if (!src || typeof src !== 'object') return fail('这个文件不是半页的备份')
1333
+ const prog = src.progress && typeof src.progress === 'object' ? src.progress : (src.books ? src : null)
1334
+ const notes = typeof src.notes === 'string' ? src.notes : ''
1335
+ if (!prog && !notes) return fail('文件里既没有读后感,也没有进度')
1336
+ if (prog && (!prog.books || typeof prog.books !== 'object')) return fail('进度里没有 books')
1337
+ // 防御:/dsh-reading.state 返回的 readers 是数组(给面板看的视图),若有人把那份响应当备份回灌,
1338
+ // 这里先把它归成 { <sid>: {name, books} },否则 state.json 会被写坏、所有分片查不到。
1339
+ if (prog && Array.isArray(prog.readers)) {
1340
+ const fixed = {}
1341
+ prog.readers.forEach((item, i) => {
1342
+ if (!item || typeof item !== 'object') return
1343
+ const rawId = String(item.id || '')
1344
+ const key = /^(session-|manual-|__legacy__)/.test(rawId) ? rawId : 'manual-restored-' + i
1345
+ fixed[key] = { name: String(item.name || key), books: item.books && typeof item.books === 'object' ? item.books : {} }
1346
+ })
1347
+ prog.readers = fixed
1348
+ }
1349
+ // 防御二:books 同样可能是数组(/dsh-reading.state 的响应就是数组形态),先归成 { <id>: {...} },
1350
+ // 否则 state.json 的 books 变成数组,之后书级 readThrough/lastReadAt 全写不进(数组挂字符串键会被 JSON 丢掉)。
1351
+ if (prog && Array.isArray(prog.books)) {
1352
+ const fixedBooks = {}
1353
+ for (const b of prog.books) {
1354
+ if (!b || typeof b !== 'object' || !b.id) continue
1355
+ fixedBooks[String(b.id)] = {
1356
+ id: String(b.id),
1357
+ title: String(b.title || b.id),
1358
+ chapters: Number(b.chapters) || 0,
1359
+ readThrough: Number(b.readThrough) || 0,
1360
+ next: Number(b.next) || 1,
1361
+ lastReadAt: b.lastReadAt || '',
1362
+ noteUntil: Number(b.noteUntil) || 0,
1363
+ furthest: Number(b.furthest) || Number(b.readThrough) || 0,
1364
+ }
1365
+ }
1366
+ prog.books = fixedBooks
1367
+ }
1368
+ const { dir, st } = await stateOf()
1369
+ await ensureDir(dir)
1370
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
1371
+ const backups = []
1372
+ if (prog) {
1373
+ const bak = 'state.json.bak-restore-' + stamp
1374
+ try { await copyFile(join(dir, 'state.json'), join(dir, bak)); backups.push(bak) } catch {}
1375
+ const merged = {
1376
+ ...st,
1377
+ current: typeof prog.current === 'string' && prog.current ? prog.current : st.current,
1378
+ books: prog.books,
1379
+ readers: prog.readers && typeof prog.readers === 'object' ? prog.readers : st.readers,
1380
+ log: prog.log && typeof prog.log === 'object' ? prog.log : st.log,
1381
+ rlog: prog.rlog && typeof prog.rlog === 'object' ? prog.rlog : st.rlog,
1382
+ }
1383
+ migrateReaders(merged)
1384
+ await saveState(dir, merged)
1385
+ }
1386
+ let noteLines = 0
1387
+ if (notes) {
1388
+ const np = await notesPath(dir)
1389
+ const bak = '读后感.md.bak-restore-' + stamp
1390
+ try { await copyFile(np, join(dir, bak)); backups.push(bak) } catch {}
1391
+ await writeFile(np, notes, 'utf8')
1392
+ noteLines = notes.split(/\r?\n/).filter((l) => /^[-*]\s+/.test(l)).length
1393
+ }
1394
+ res.end(JSON.stringify({ ok: true, books: prog ? Object.keys(prog.books || {}).length : 0, notes: noteLines, backups }))
1395
+ } catch (e) { fail((e && e.stack) || (e && e.message) || e) }
1396
+ },
1397
+ }),
1398
+ )
1399
+
1400
+ // 保存「书房时间」列表(每条:启用/时段/频率/叫哪条会话)
1401
+ ctx.effect(() =>
1402
+ ctx.webServer.register({
1403
+ auth: sameSiteAuth,
1404
+ kind: 'exact',
1405
+ path: '/dsh-reading.study',
1406
+ async handler(req, res) {
1407
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1408
+ let body = ''
1409
+ try { for await (const c of req) body += c } catch {}
1410
+ let j = {}
1411
+ try { j = JSON.parse(body || '{}') || {} } catch {}
1412
+ if (!Array.isArray(j.slots)) return res.end(JSON.stringify({ ok: false, error: 'slots 要是数组' }))
1413
+ const cfgNow = await config()
1414
+ const { dir, st } = await stateOf()
1415
+ const prev = studySlotsOf(st, cfgNow)
1416
+ const byId = new Map(prev.map((s) => [s.id, s]))
1417
+ const slots = j.slots.slice(0, 12).map((raw, i) => {
1418
+ const slot = normaliseStudySlot(raw, cfgNow, i)
1419
+ const old = byId.get(slot.id)
1420
+ if (old) {
1421
+ // 计数跟 id 走:改时段/换会话都不清零,删掉重加才是新的
1422
+ slot.lastAt = old.lastAt
1423
+ slot.week = old.week
1424
+ slot.weekCount = old.weekCount
1425
+ slot.day = old.day
1426
+ slot.dayCount = old.dayCount
1427
+ }
1428
+ return slot
1429
+ })
1430
+ await ensureDir(dir)
1431
+ st.study = { ...(st.study || {}), slots }
1432
+ const first = slots[0]
1433
+ if (first) {
1434
+ st.study.lastAt = first.lastAt
1435
+ st.study.week = first.week
1436
+ st.study.weekCount = first.weekCount
1437
+ st.study.day = first.day
1438
+ st.study.dayCount = first.dayCount
1439
+ }
1440
+ await saveState(dir, st)
1441
+ res.end(JSON.stringify({ ok: true, slots: slots.length }))
1442
+ },
1443
+ }),
1444
+ )
1445
+
1446
+ // 备份到文件:面板在 iframe 里,<a download> 不会弹保存框,所以由服务端写盘、把路径回给面板
1447
+ ctx.effect(() =>
1448
+ ctx.webServer.register({
1449
+ auth: sameSiteAuth,
1450
+ kind: 'exact',
1451
+ path: '/dsh-reading.backupFile',
1452
+ async handler(req, res) {
1453
+ try {
1454
+ const { appendFile: af } = await import('node:fs/promises')
1455
+ const { tmpdir: td } = await import('node:os')
1456
+ const { join: jn } = await import('node:path')
1457
+ await af(jn(td(), 'hp-backup-hit.log'), new Date().toISOString() + ' ' + req.method + ' origin=' + (req.headers.origin || '-') + ' host=' + (req.headers.host || '-') + '\n')
1458
+ } catch {}
1459
+
1460
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1461
+ try {
1462
+ const { dir, st } = await stateOf()
1463
+ await ensureDir(dir)
1464
+ let notes = ''
1465
+ try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
1466
+ const payload = { kind: 'dsh-half-page-backup', version: 1, at: new Date().toISOString(), notes, progress: st }
1467
+ const bdir = join(dir, 'backups')
1468
+ await mkdir(bdir, { recursive: true })
1469
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
1470
+ const out = join(bdir, '半页备份-' + stamp + '.json')
1471
+ const text = JSON.stringify(payload, null, 2)
1472
+ await writeFile(out, text, 'utf8')
1473
+ res.end(JSON.stringify({ ok: true, path: out, bytes: Buffer.byteLength(text) }))
1474
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1475
+ },
1476
+ }),
1477
+ )
1478
+
1479
+ // 读一个备份文件(面板读不到本地磁盘,只能让宿主读)
1480
+ ctx.effect(() =>
1481
+ ctx.webServer.register({
1482
+ auth: sameSiteAuth,
1483
+ kind: 'exact',
1484
+ path: '/dsh-reading.readFile',
1485
+ async handler(req, res) {
1486
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1487
+ try {
1488
+ const u = new URL(req.url || '/', 'http://localhost')
1489
+ const p = String(u.searchParams.get('path') || '').trim().replace(/^"|"$/g, '')
1490
+ if (!p) throw new Error('要一个文件路径')
1491
+ const s2 = await stat(p)
1492
+ if (!s2.isFile()) throw new Error('不是文件')
1493
+ if (s2.size > 50 * 1024 * 1024) throw new Error('文件太大(超过 50MB)')
1494
+ const text = await readFile(p, 'utf8')
1495
+ res.end(JSON.stringify({ ok: true, text }))
1496
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1497
+ },
1498
+ }),
1499
+ )
1500
+
1501
+ // 在资源管理器里选中一个文件(面板点「在文件夹里打开」时用)
1502
+ ctx.effect(() =>
1503
+ ctx.webServer.register({
1504
+ auth: sameSiteAuth,
1505
+ kind: 'exact',
1506
+ path: '/dsh-reading.reveal',
1507
+ async handler(req, res) {
1508
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1509
+ try {
1510
+ let body = ''
1511
+ for await (const c of req) body += c
1512
+ const j = JSON.parse(body || '{}') || {}
1513
+ const p = String(j.path || '').trim()
1514
+ if (!p) throw new Error('要一个文件路径')
1515
+ if (!isAbsolute(p)) throw new Error('要绝对路径')
1516
+ const s2 = await stat(p)
1517
+ if (!s2.isFile()) throw new Error('不是文件')
1518
+ if (process.platform === 'win32') {
1519
+ spawn('explorer.exe', ['/select,' + p], { detached: true, stdio: 'ignore' }).unref()
1520
+ } else if (process.platform === 'darwin') {
1521
+ spawn('open', ['-R', p], { detached: true, stdio: 'ignore' }).unref()
1522
+ } else {
1523
+ spawn('xdg-open', [dirname(p)], { detached: true, stdio: 'ignore' }).unref()
1524
+ }
1525
+ res.end(JSON.stringify({ ok: true, path: p }))
1526
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1527
+ },
1528
+ }),
1529
+ )
1530
+
1531
+ // 查 npm 上最新版(面板「检测更新」用)
1532
+ const checkUpdate = async () => {
1533
+ const here = dirname(fileURLToPath(import.meta.url))
1534
+
1535
+ let current = ''
1536
+ try {
1537
+ current = JSON.parse(await readFile(join(here, 'package.json'), 'utf8')).version || ''
1538
+ } catch { /* 拿不到就只说最新版 */ }
1539
+ let latest = ''
1540
+ try {
1541
+ const res = await fetch('https://registry.npmjs.org/dsh-half-page/latest', { headers: { accept: 'application/json' } })
1542
+ if (res.ok) latest = String((await res.json()).version || '')
1543
+ } catch { /* 离线 */ }
1544
+ const cmp = (a, b) => {
1545
+ const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0)
1546
+ const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0)
1547
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
1548
+ const d = (pa[i] || 0) - (pb[i] || 0)
1549
+ if (d) return d > 0 ? 1 : -1
1550
+ }
1551
+ return 0
1552
+ }
1553
+ const order = current && latest ? cmp(current, latest) : 0
1554
+ return { ok: true, current, latest, ahead: order > 0, outdated: order < 0, command: 'dsh plugin add dsh-half-page@latest' }
1555
+ }
1556
+
1557
+ ctx.effect(() =>
1558
+ ctx.webServer.register({
1559
+ auth: sameSiteAuth,
1560
+ kind: 'exact',
1561
+ path: '/dsh-reading.update',
1562
+ async handler(req, res) {
1563
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1564
+ try { res.end(JSON.stringify(await checkUpdate())) } catch (e) {
1565
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1566
+ }
1567
+ },
1568
+ }),
1569
+ )
1570
+
1571
+ // 弹系统「另存为」对话框:让用户自己选放哪(面板在 iframe 里不能自己弹)
1572
+ // 对话框脚本内嵌,运行时落到临时目录:不依赖安装位置的 toolkit(换机器也能用)
1573
+ // 对话框脚本内嵌,运行时落到临时目录:不依赖安装位置的 toolkit(换机器也能用)
1574
+ const hpDialogOverlay = (mode, suggested, source) => {
1575
+ const q = (s) => "'" + String(s || '').replace(/'/g, "''") + "'"
1576
+ return [
1577
+ 'Add-Type -AssemblyName System.Windows.Forms | Out-Null',
1578
+ 'Add-Type -AssemblyName System.Drawing | Out-Null',
1579
+ `$Mode = ${q(mode)}`,
1580
+ `$Suggested = ${q(suggested)}`,
1581
+ `$Source = ${q(source)}`,
1582
+ '$owner = New-Object System.Windows.Forms.Form',
1583
+ '$owner.TopMost = $true',
1584
+ '$owner.ShowInTaskbar = $false',
1585
+ '$owner.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None',
1586
+ '$owner.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen',
1587
+ '$owner.Size = New-Object System.Drawing.Size(1,1)',
1588
+ '$owner.Opacity = 0',
1589
+ '$owner.Show()',
1590
+ '$owner.Activate()',
1591
+ 'try {',
1592
+ ' if ($Mode -eq "save") {',
1593
+ ' $dlg = New-Object System.Windows.Forms.SaveFileDialog',
1594
+ ' $dlg.Filter = "JSON (*.json)|*.json|All files (*.*)|*.*"',
1595
+ ' $dlg.FileName = $Suggested',
1596
+ ' $dlg.OverwritePrompt = $true',
1597
+ ' } else {',
1598
+ ' $dlg = New-Object System.Windows.Forms.OpenFileDialog',
1599
+ ' $dlg.Filter = "JSON (*.json)|*.json|All files (*.*)|*.*"',
1600
+ ' }',
1601
+ ' $r = $dlg.ShowDialog($owner)',
1602
+ ' if ($r -ne [System.Windows.Forms.DialogResult]::OK) { $owner.Close(); Write-Output "CANCELLED"; exit 0 }',
1603
+ ' $target = $dlg.FileName',
1604
+ ' if ($Mode -eq "save" -and $Source -ne "") { Copy-Item -LiteralPath $Source -Destination $target -Force }',
1605
+ ' $owner.Close()',
1606
+ ' Write-Output $target',
1607
+ ' exit 0',
1608
+ '} catch {',
1609
+ ' $owner.Close()',
1610
+ ' Write-Output ("ERROR " + $_.Exception.Message)',
1611
+ ' exit 1',
1612
+ '}',
1613
+ '',
1614
+ ].join('\r\n')
1615
+ }
1616
+
1617
+ const hpDialogLog = async (line) => {
1618
+ try {
1619
+ await appendFile(join(tmpdir(), 'hp-dialog.log'), new Date().toISOString() + ' ' + line + '\n')
1620
+ } catch {}
1621
+ }
1622
+
1623
+ const runDialog = (mode, suggested, source) => new Promise((resolve2) => {
1624
+ let p
1625
+ try {
1626
+ const script = hpDialogOverlay(mode, suggested, source)
1627
+ const b64 = Buffer.from(script, 'utf16le').toString('base64')
1628
+ p = spawn('powershell.exe', ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', b64], { windowsHide: true })
1629
+ } catch (e) {
1630
+ hpDialogLog('spawn-throw ' + String((e && e.message) || e))
1631
+ resolve2({ ok: false, error: String((e && e.message) || e) })
1632
+ return
1633
+ }
1634
+ let out = ''
1635
+ let err = ''
1636
+ p.stdout.on('data', (d) => { out += String(d) })
1637
+ p.stderr.on('data', (d) => { err += String(d) })
1638
+ p.on('error', (e) => {
1639
+ hpDialogLog('spawn-error ' + String((e && e.message) || e))
1640
+ resolve2({ ok: false, error: String((e && e.message) || e) })
1641
+ })
1642
+ p.on('close', (code) => {
1643
+ const line = out.trim().split(/\r?\n/).filter(Boolean).pop() || ''
1644
+ hpDialogLog('mode=' + mode + ' exit=' + code + ' out=' + JSON.stringify(line).slice(0, 200) + ' err=' + JSON.stringify(err.trim()).slice(0, 300))
1645
+ if (!line || line === 'CANCELLED') resolve2({ ok: false, cancelled: true })
1646
+ else if (line.startsWith('ERROR')) resolve2({ ok: false, error: line.slice(6).trim() })
1647
+ else resolve2({ ok: true, path: line })
1648
+ })
1649
+ })
1650
+
1651
+ ctx.effect(() =>
1652
+ ctx.webServer.register({
1653
+ auth: sameSiteAuth,
1654
+ kind: 'exact',
1655
+ path: '/dsh-reading.saveAs',
1656
+ async handler(req, res) {
1657
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1658
+ try {
1659
+ const { dir, st } = await stateOf()
1660
+ await ensureDir(dir)
1661
+ let notes = ''
1662
+ try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
1663
+ const payload = { kind: 'dsh-half-page-backup', version: 1, at: new Date().toISOString(), notes, progress: st }
1664
+ const tmpDir = join(dir, 'backups')
1665
+ await mkdir(tmpDir, { recursive: true })
1666
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
1667
+ const tmp = join(tmpDir, '.tmp-export-' + stamp + '.json')
1668
+ await writeFile(tmp, JSON.stringify(payload, null, 2), 'utf8')
1669
+ const name = '半页备份-' + stamp.slice(0, 10) + '.json'
1670
+ const r = await runDialog('save', name, tmp)
1671
+ try { await unlink(tmp) } catch {}
1672
+ res.end(JSON.stringify(r))
1673
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1674
+ },
1675
+ }),
1676
+ )
1677
+
1678
+ // 弹「打开」对话框,返回选中的备份文件路径
1679
+ ctx.effect(() =>
1680
+ ctx.webServer.register({
1681
+ auth: sameSiteAuth,
1682
+ kind: 'exact',
1683
+ path: '/dsh-reading.pickFile',
1684
+ async handler(req, res) {
1685
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1686
+ try { res.end(JSON.stringify(await runDialog('open'))) } catch (e) {
1687
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1688
+ }
1689
+ },
1690
+ }),
1691
+ )
1692
+
1693
+ // 手动新增一位读者(给还没读过书的会话先占个位置;也可以纯手动起个名字)
1694
+ ctx.effect(() =>
1695
+ ctx.webServer.register({
1696
+ auth: sameSiteAuth,
1697
+ kind: 'exact',
1698
+ path: '/dsh-reading.addReader',
1699
+ async handler(req, res) {
1700
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1701
+ let body = ''
1702
+ try { for await (const c of req) body += c } catch {}
1703
+ let j = {}
1704
+ try { j = JSON.parse(body || '{}') || {} } catch {}
1705
+ const { dir, st } = await stateOf()
1706
+ migrateReaders(st)
1707
+ st.readers = st.readers || {}
1708
+ const sid = String(j.sessionId || '').trim()
1709
+ let name = String(j.name || '').trim()
1710
+ if (!sid && !name) return res.end(JSON.stringify({ ok: false, error: '要么选一条会话,要么写个名字' }))
1711
+ let id = sid
1712
+ if (!id) {
1713
+ // 纯手动读者:给个稳定的 id,不跟任何会话绑
1714
+ id = 'manual-' + Date.now().toString(36)
1715
+ if (!name) name = '读者 ' + id.slice(-4)
1716
+ } else if (!name) {
1717
+ const t = await sessionTitleOf(sid)
1718
+ name = nameIsId(t, sid) ? ('会话 ' + sid.slice(-8)) : (t || ('会话 ' + sid.slice(-8)))
1719
+ }
1720
+ if (st.readers[id]) return res.end(JSON.stringify({ ok: true, existed: true, id, name: st.readers[id].name || name }))
1721
+ st.readers[id] = { name, books: {}, manual: !sid }
1722
+ READER_NAMES.set(id, name)
1723
+ await saveState(dir, st)
1724
+ res.end(JSON.stringify({ ok: true, id, name, manual: !sid }))
1725
+ },
1726
+ }),
1727
+ )
1728
+
1729
+ // 把手里的书签直接接到「全机读得最远」那一步(他自己的分片,不影响别人)
1730
+ ctx.effect(() =>
1731
+ ctx.webServer.register({
1732
+ auth: sameSiteAuth,
1733
+ kind: 'exact',
1734
+ path: '/dsh-reading.adopt',
1735
+ async handler(req, res) {
1736
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1737
+ const url = new URL(req.url, 'http://x')
1738
+ const { dir, st } = await stateOf()
1739
+ migrateReaders(st)
1740
+ const id = url.searchParams.get('book') || st.current
1741
+ if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1742
+ const reader = readerParam(st, url)
1743
+ const far = furthestOf(st, id)
1744
+ if (!far) return res.end(JSON.stringify({ ok: false, error: '这本书还没有任何进度' }))
1745
+ const own = readerBook(st, reader.id, id)
1746
+ own.readThrough = far
1747
+ own.next = far + 1
1748
+ own.lastReadAt = new Date().toISOString()
1749
+ st.books[id].readThrough = Math.max(Number(st.books[id].readThrough) || 0, far)
1750
+ st.books[id].next = Math.min(Number(st.books[id].chapters) || Infinity, far + 1)
1751
+ furthestOf(st, id)
1752
+ await saveState(dir, st)
1753
+ res.end(JSON.stringify({ ok: true, reader: reader.name, book: id, readThrough: far, next: far + 1 }))
1754
+ },
1755
+ }),
1756
+ )
1757
+
916
1758
  // 把某本设为「正在读」
917
1759
  ctx.effect(() =>
918
1760
  ctx.webServer.register({
@@ -921,11 +1763,23 @@ export function apply(ctx, rawConfig) {
921
1763
  path: '/dsh-reading.setCurrent',
922
1764
  async handler(req, res) {
923
1765
  const url = new URL(req.url, 'http://x')
924
- const id = url.searchParams.get('id') || ''
925
- const { dir, st } = await stateOf()
926
- if (st.books[id]) { st.current = id; await saveState(dir, st) }
1766
+ // id 既可能来自 ?id=(老调用),也可能来自 POST 的 JSON body(面板点书名走这条)
1767
+ let id = url.searchParams.get('id') || ''
1768
+ if (!id) {
1769
+ let body = ''
1770
+ for await (const c of req) body += c
1771
+ try { id = String((JSON.parse(body || '{}') || {}).id || '') } catch {}
1772
+ }
1773
+ const { dir, st, shelf } = await stateOf()
1774
+ // 书架上的书不一定在 state.books 里(没读过就没条目),这里按书架兜底
1775
+ const onShelf = (shelf || []).find((b) => b && b.id === id)
1776
+ if (onShelf && !st.books[id]) {
1777
+ st.books[id] = { id, title: onShelf.id, file: onShelf.file, chapters: onShelf.chapters || 0, readThrough: 0, next: 1, lastReadAt: '' }
1778
+ }
1779
+ const exists = Boolean(st.books[id])
1780
+ if (exists) { st.current = id; await saveState(dir, st) }
927
1781
  res.setHeader('content-type', 'application/json; charset=utf-8')
928
- res.end(JSON.stringify({ ok: !!st.books[id], current: st.current }))
1782
+ res.end(JSON.stringify({ ok: exists, current: st.current }))
929
1783
  },
930
1784
  }),
931
1785
  )
@@ -944,8 +1798,9 @@ export function apply(ctx, rawConfig) {
944
1798
  res.setHeader('content-type', 'application/json; charset=utf-8')
945
1799
  try {
946
1800
  const info = await bookInfo(dir, id)
947
- const rec = st.books[id] || {}
948
- const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (rec.readThrough || 1)
1801
+ const reader = readerParam(st, url)
1802
+ const mine = readerBookRead(st, reader.id, id)
1803
+ const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (mine.readThrough || 1)
949
1804
  res.end(JSON.stringify({
950
1805
  ok: true, book: id, chapter: ch, total: info.chapters.length,
951
1806
  title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
@@ -967,20 +1822,24 @@ export function apply(ctx, rawConfig) {
967
1822
  const url = new URL(req.url, 'http://x')
968
1823
  const { dir, st, perDay, readToday: rt } = await stateOf()
969
1824
  const id = url.searchParams.get('book') || st.current
970
- const rec = st.books[id]
971
1825
  res.setHeader('content-type', 'application/json; charset=utf-8')
972
- if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1826
+ if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1827
+ const reader = readerParam(st, url)
1828
+ const own = readerBook(st, reader.id, id)
1829
+ // 面板上点「从头读」:先把这份分片归零,再按一张张推进的方式读第 1 章
1830
+ if (url.searchParams.get('start') === '1') { own.readThrough = 0; own.next = 1 }
973
1831
  const info = await bookInfo(dir, id)
974
- const n = Math.min(info.chapters.length, (rec.readThrough || 0) + 1)
975
- rec.readThrough = n
976
- rec.next = Math.min(info.chapters.length, n + 1)
977
- rec.lastReadAt = new Date().toISOString()
1832
+ const n = Math.min(info.chapters.length, (own.readThrough || 0) + 1)
1833
+ own.readThrough = n
1834
+ own.next = Math.min(info.chapters.length, n + 1)
1835
+ own.lastReadAt = new Date().toISOString()
1836
+ st.books[id].readThrough = Math.max(Number(st.books[id].readThrough) || 0, n)
1837
+ st.books[id].next = Math.min(info.chapters.length, st.books[id].readThrough + 1)
1838
+ furthestOf(st, id)
978
1839
  const t = today()
979
- st.log = st.log || {}
980
- st.log[t] = st.log[t] || {}
981
- st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
1840
+ bumpLog(st, t, id, reader.id, 1)
982
1841
  await saveState(dir, st)
983
- res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, readToday: rt + 1, perDay, left: Math.max(0, perDay - rt - 1) }))
1842
+ res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, readToday: rt + 1, perDay, left: Math.max(0, perDay - rt - 1), reader: reader.id, readThrough: own.readThrough }))
984
1843
  },
985
1844
  }),
986
1845
  )
@@ -995,21 +1854,22 @@ export function apply(ctx, rawConfig) {
995
1854
  const url = new URL(req.url, 'http://x')
996
1855
  const { dir, st } = await stateOf()
997
1856
  const id = url.searchParams.get('book') || st.current
998
- const rec = st.books[id]
999
1857
  res.setHeader('content-type', 'application/json; charset=utf-8')
1000
- if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1001
- const cur = Number(rec.readThrough) || 0
1858
+ if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1859
+ const reader = readerParam(st, url)
1860
+ const own = readerBook(st, reader.id, id)
1861
+ const cur = Number(own.readThrough) || 0
1002
1862
  if (cur <= 1) return res.end(JSON.stringify({ ok: false, error: '已经在第 1 章了,退不动' }))
1003
1863
  const n = cur - 1
1004
- rec.readThrough = n
1005
- rec.next = n + 1
1006
- rec.lastReadAt = new Date().toISOString()
1007
- // 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高
1864
+ own.readThrough = n
1865
+ own.next = n + 1
1866
+ own.lastReadAt = new Date().toISOString()
1867
+ // 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高(全局与这位读者各退一格)
1008
1868
  const t = today()
1009
- if (st.log && st.log[t] && Number(st.log[t][id]) > 0) st.log[t][id] = Number(st.log[t][id]) - 1
1869
+ bumpLog(st, t, id, reader.id, -1)
1010
1870
  await saveState(dir, st)
1011
1871
  const info = await bookInfo(dir, id)
1012
- res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length }))
1872
+ res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, reader: reader.id }))
1013
1873
  },
1014
1874
  }),
1015
1875
  )
@@ -1298,17 +2158,69 @@ async function signWork(rel, who) {
1298
2158
  let st = {}
1299
2159
  try { st = JSON.parse(stripBom(await readFile(join(dir, 'state.json'), 'utf8'))) || {} } catch {}
1300
2160
  const now = Date.now()
2161
+ migrateReaders(st)
2162
+ // 近况跟读者走:?reader=<rid> 给了就只报这位读者翻过的;给的是总进度就按书拆成「谁读到哪」
2163
+ let wanted = ''
2164
+ try { wanted = new URL(req.url, 'http://x').searchParams.get('reader') || '' } catch {}
2165
+ const readers = (st.readers && typeof st.readers === 'object') ? st.readers : {}
2166
+ const readerId = wanted && readers[wanted] ? wanted : ''
2167
+ const readerName = readerId ? (readers[readerId].name || readerId) : ''
2168
+ const perReader = []
2169
+ if (readerId) {
2170
+ if (readerId === LEGACY_READER) {
2171
+ for (const [rid, shard] of Object.entries(readers)) {
2172
+ if (rid === LEGACY_READER) continue
2173
+ const rb = (shard.books && shard.books[st.current]) || null
2174
+ if (!rb || !(Number(rb.readThrough) > 0)) continue
2175
+ perReader.push({ id: rid, name: shard.name || rid, readThrough: Number(rb.readThrough) || 0, lastReadAt: rb.lastReadAt || '' })
2176
+ }
2177
+ perReader.sort((a, b) => b.readThrough - a.readThrough)
2178
+ } else {
2179
+ const shard = readers[readerId]
2180
+ for (const [bid, rb] of Object.entries(shard.books || {})) {
2181
+ if (!(Number(rb.readThrough) > 0)) continue
2182
+ const bk = (st.books && st.books[bid]) || {}
2183
+ perReader.push({ id: bid, name: bk.title || bid, readThrough: Number(rb.readThrough) || 0, chapters: Number(bk.chapters) || 0, lastReadAt: rb.lastReadAt || '' })
2184
+ }
2185
+ perReader.sort((a, b) => String(b.lastReadAt).localeCompare(String(a.lastReadAt)))
2186
+ }
2187
+ }
1301
2188
  const key = (t) => {
1302
2189
  const d = new Date(t)
1303
2190
  return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10)
1304
2191
  }
1305
2192
  const today = key(now)
1306
- const log = st.log || {}
2193
+ // 给了读者就按读者的 rlog 记账;没给就还是全机 log
2194
+ let log = st.log || {}
2195
+ if (readerId) {
2196
+ const rl = st.rlog || {}
2197
+ log = {}
2198
+ for (const [k, byRid] of Object.entries(rl)) {
2199
+ const row = byRid && byRid[readerId]
2200
+ if (row) log[k] = row
2201
+ }
2202
+ }
1307
2203
  const cur = (st.books && st.current && st.books[st.current]) || null
1308
- const todayCh = (log[today] && log[today][st.current]) || 0
1309
- const lastRead = cur && cur.lastReadAt ? Date.parse(cur.lastReadAt) : 0
2204
+ // 近况说的是「这位读者最近在干什么」,不是面板上停在哪本:
2205
+ // 先找他最近读过的那本,找不到才用面板当前这本
2206
+ let focusId = st.current
2207
+ try {
2208
+ const lb = lastReadBookOf(st, readerId || LEGACY_READER)
2209
+ if (lb && st.books && st.books[lb]) focusId = lb
2210
+ } catch {}
2211
+ const focusRec = (st.books && st.books[focusId]) || null
2212
+ const ownShard = readerId && readerId !== LEGACY_READER ? readerBookRead(st, readerId, focusId) : null
2213
+ const view = ownShard || focusRec
2214
+ const todayCh = (log[today] && log[today][focusId]) || 0
2215
+ const lastRead = view && view.lastReadAt ? Date.parse(view.lastReadAt) : 0
1310
2216
  const hoursAgo = lastRead ? Math.max(0, Math.round((now - lastRead) / 3600000)) : -1
1311
2217
 
2218
+ let lastDay = ''
2219
+ if (readerId) {
2220
+ const rl = st.rlog || {}
2221
+ for (const k of Object.keys(rl).sort()) { if (rl[k] && rl[k][readerId]) lastDay = k }
2222
+ }
2223
+
1312
2224
  const days = []
1313
2225
  for (let i = 0; i < 7; i++) {
1314
2226
  const k = key(now - i * 86400000)
@@ -1339,20 +2251,25 @@ async function signWork(rel, who) {
1339
2251
  const top = works[0] || null
1340
2252
 
1341
2253
  let status = ''
1342
- if (todayCh > 0) status = '今天在《' + (st.current || '') + '》翻了 ' + todayCh + ' 章,读到第 ' + ((cur && cur.readThrough) || 0) + ' 章。'
2254
+ if (todayCh > 0) {
2255
+ const rawTitle = String((focusRec && focusRec.title) || focusId || '')
2256
+ const shownTitle = /^《/.test(rawTitle) ? rawTitle : '《' + rawTitle + '》'
2257
+ status = '今天在' + shownTitle + '翻了 ' + todayCh + ' 章,读到第 ' + ((view && view.readThrough) || 0) + ' 章。'
2258
+ }
1343
2259
  else if (hoursAgo >= 0 && hoursAgo <= 48) status = '上次翻书是 ' + hoursAgo + ' 小时前。'
1344
2260
  else if (hoursAgo > 48) status = '这两天没翻书。'
2261
+ else if (lastDay) status = '上次翻书是 ' + lastDay + '。'
1345
2262
  if (top) {
1346
- if (top.days === 0) status += '今天还动过笔,写《' + top.name + '》。'
1347
- else if (top.days === 1) status += '昨天动过笔,写《' + top.name + '》。'
1348
- else status += '上次动笔是 ' + top.days + ' 天前的《' + top.name + '》。'
2263
+ if (top.days === 0) status += '今天有更新:《' + top.name + '》。'
2264
+ else if (top.days === 1) status += '昨天有更新:《' + top.name + '》。'
2265
+ else status += '上次更新是 ' + top.days + ' 天前的《' + top.name + '》。'
1349
2266
  }
1350
2267
  let mood = ''
1351
2268
  if (todayCh >= 12) mood = '翻书翻得犯困'
1352
2269
  else if (todayCh > 0) mood = works.some((w) => w.days === 0) ? '手痒,想写点东西' : '平静'
1353
2270
  else if (hoursAgo < 0 || hoursAgo > 48) mood = '有点闷'
1354
2271
  else mood = '没什么兴致'
1355
- res.end(JSON.stringify({ ok: true, mood, status, today, todayChapters: todayCh, current: st.current || '', readThrough: (cur && cur.readThrough) || 0, hoursAgo, days, works: works.slice(0, 5) }))
2272
+ res.end(JSON.stringify({ ok: true, mood, status, today, todayChapters: todayCh, current: st.current || '', readThrough: (cur && cur.readThrough) || 0, hoursAgo, days, works: works.slice(0, 5), reader: readerId, readerName, perReader }))
1356
2273
  } catch (e) {
1357
2274
  res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1358
2275
  }
@@ -1495,7 +2412,9 @@ async function signWork(rel, who) {
1495
2412
  '· 读后感不必一章一条:每读五六章写一段就够,标题会自动变成「第 23–27 章」;几千章的书也不会攒成几千条。',
1496
2413
  '· 写读后感必须带 by(比如「鹿野」或你所在对话的名字);不带会被拒绝。面板每条下面会标出是谁写的——同一台机器上可能有好几个你,别让它们分不清。',
1497
2414
  '· 写自己的作品也一样署名:文件开头写一行 `by: 你的名字`(或写完调 reading_sign);没署名的在面板上会标「未署名」。',
1498
- '· 书和进度是这台机器共用的(一个家一个书房),不分谁在读;只有读后感会标署名。',
2415
+ '· 书是同一架,进度按读者分开:每条会话各有一份「读到哪」,互不踩;书上另记一个「全机读得最远」,面板里能看到谁读到哪。',
2416
+ '· 接着读:默认接你自己的位置;你还没读过这本书,就接全机读得最远的地方。想从别处起就传 chapter 指定章号。',
2417
+ '· 读哪一本由你决定,不由面板决定:面板上他选的「当前这本」只是他想看哪本,不会改变你读哪本;只有他明确说「你去读某一本」,才按他说的读。',
1499
2418
  '· 装好之后可以问主人一次:要不要定个固定的读书时间;别自己偷偷建定时任务,也别反复问。',
1500
2419
  ].join('\n')
1501
2420
 
@@ -1537,11 +2456,13 @@ async function signWork(rel, who) {
1537
2456
  + '想知道「我现在读到哪、还能读几章」就用它。',
1538
2457
  parameters: obj(),
1539
2458
  output: textOut,
1540
- async execute() {
2459
+ async execute(args, exec) {
1541
2460
  const { dir, perDay, st, shelf, readToday: rt, today: t } = await stateOf()
2461
+ const reader = await readerOf(exec)
1542
2462
  const books = []
1543
2463
  for (const b of shelf) {
1544
2464
  const r = st.books[b.id] || {}
2465
+ const mine = readerBookRead(st, reader.id, b.id)
1545
2466
  let chapters = r.chapters || 0
1546
2467
  if (!chapters) {
1547
2468
  try {
@@ -1549,10 +2470,19 @@ async function signWork(rel, who) {
1549
2470
  chapters = (toc && toc.chapters && toc.chapters.length) || 0
1550
2471
  } catch {}
1551
2472
  }
1552
- books.push({ id: b.id, chapters, readThrough: r.readThrough || 0, next: r.next || 1, lastReadAt: r.lastReadAt || '' })
2473
+ books.push({
2474
+ id: b.id,
2475
+ chapters,
2476
+ readThrough: mine.readThrough,
2477
+ next: mine.next || 1,
2478
+ furthest: furthestOf(st, b.id),
2479
+ furthestReader: furthestReaderOf(st, b.id),
2480
+ lastReadAt: mine.lastReadAt || '',
2481
+ })
1553
2482
  }
1554
2483
  return {
1555
2484
  dir,
2485
+ reader: reader.name,
1556
2486
  today: t,
1557
2487
  perDay,
1558
2488
  readToday: rt,
@@ -1573,33 +2503,45 @@ async function signWork(rel, who) {
1573
2503
  + '超过每日上限时会提示,但仍允许读(上限是提醒不是锁)。'
1574
2504
  + '配置了静音时段时,这段时间内会被拒绝;真要读就传 force: true。',
1575
2505
  parameters: obj({
1576
- book: { type: 'string', description: '书名 id(不填=当前正在读的那本)' },
2506
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本;都没读过就用书架当前那本,跟 reading_note 一致)' },
1577
2507
  chapter: { type: 'number', description: '第几章(不填=接着上次的下一章)' },
1578
2508
  force: { type: 'boolean', description: '静音时段内仍然要读,传 true(默认 false)' },
2509
+ from: { type: 'string', enum: ['me', 'book', 'start'], description: '不填 chapter 时从哪接着读:me=我上次的位置(默认)、book=这本书全机读得最远的地方、start=从头(第 1 章)' },
1579
2510
  }),
1580
2511
  output: textOut,
1581
- async execute(args) {
2512
+ async execute(args, exec) {
1582
2513
  if (args?.force !== true) {
1583
2514
  const q = inQuietNow(await config())
1584
2515
  if (q) throw new Error(`静音时段(${q.fromText}–${q.toText}),不自动读。真要读请传 force: true`)
1585
2516
  }
1586
2517
  const { dir, perDay, st, readToday: rt } = await stateOf()
1587
- const id = args?.book || st.current
1588
- if (!id) throw new Error('书架是空的:先用 reading_import 导入一本 txt')
2518
+ const reader = await readerOf(exec)
2519
+ // 取书口径跟 reading_note 一致:明说 > 我自己刚读的那本 > 全局当前那本
2520
+ const id = args?.book || lastReadBookOf(st, reader.id)
2521
+ if (!id) throw new Error('不知道读哪本:传 book,或先读过一本')
1589
2522
  const info = await bookInfo(dir, id)
1590
2523
  const rec = st.books[id] || (st.books[id] = { id, title: id, chapters: info.chapters.length, readThrough: 0, next: 1 })
1591
2524
  rec.chapters = info.chapters.length
1592
- const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
2525
+ const own = readerBook(st, reader.id, id)
2526
+ // from:"start" = 明说从头读:先把自己这份归零,否则下面 max(mine, n) 会把它顶回书级进度(测试鱼 2026-11-27 测出来的)
2527
+ if (args?.from === 'start') { own.readThrough = 0; own.next = 1 }
2528
+ // 默认接着「我自己」上次的位置;我还没读过这本书就接书级的 next(换窗口能接着读)
2529
+ const mine = Number(own.readThrough) || 0
2530
+ // start=明说从头读;否则接着我自己,我没读过就接书级 next
2531
+ const startAt = args?.from === 'start' ? 1 : (args?.from === 'book' || !mine ? (rec.next || 1) : (own.next || mine + 1))
2532
+ const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : startAt
1593
2533
  if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
1594
2534
  const body = await chapterBody(dir, id, info, n)
1595
- rec.readThrough = Math.max(rec.readThrough || 0, n)
1596
- rec.next = Math.min(info.chapters.length, n + 1)
1597
- rec.lastReadAt = new Date().toISOString()
1598
- st.current = id
2535
+ own.readThrough = Math.max(mine, n)
2536
+ own.next = Math.min(info.chapters.length, own.readThrough + 1)
2537
+ own.lastReadAt = new Date().toISOString()
2538
+ rec.readThrough = Math.max(Number(rec.readThrough) || 0, n)
2539
+ rec.next = Math.min(info.chapters.length, rec.readThrough + 1)
2540
+ rec.lastReadAt = own.lastReadAt
2541
+ furthestOf(st, id)
2542
+ // 读书不动「面板上正在显示的那本」:current 只在用户手动选书时改(2026-11-27)
1599
2543
  const t = today()
1600
- st.log = st.log || {}
1601
- st.log[t] = st.log[t] || {}
1602
- st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
2544
+ bumpLog(st, t, id, reader.id, 1)
1603
2545
  await saveState(dir, st)
1604
2546
  return {
1605
2547
  book: id,
@@ -1608,7 +2550,10 @@ async function signWork(rel, who) {
1608
2550
  chapters: info.chapters.length,
1609
2551
  tocPath: info.tocPath || '',
1610
2552
  chars: body.length,
1611
- next: rec.next,
2553
+ next: own.next,
2554
+ reader: reader.name,
2555
+ readThrough: own.readThrough,
2556
+ furthest: rec.furthest || own.readThrough,
1612
2557
  perDay,
1613
2558
  readToday: rt + 1,
1614
2559
  left: Math.max(0, perDay - rt - 1),
@@ -1626,14 +2571,17 @@ async function signWork(rel, who) {
1626
2571
  + '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
1627
2572
  + '已读到只进不退(跳读可以,回退不会把进度改小)。',
1628
2573
  parameters: obj({
1629
- book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主、古文观止' },
2574
+ book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主(不填=我刚读过的那本)' },
1630
2575
  chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
1631
2576
  todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
1632
2577
  }),
1633
2578
  output: textOut,
1634
- async execute(args) {
2579
+ async execute(args, exec) {
1635
2580
  const { dir, st, shelf } = await stateOf()
1636
- const id = resolveBookId(st, shelf, args?.book)
2581
+ const reader = await readerOf(exec)
2582
+ const wanted = args?.book || lastReadBookOf(st, reader.id)
2583
+ if (!wanted) throw new Error('不知道记哪本:传 book,或先读过一本')
2584
+ const id = resolveBookId(st, shelf, wanted)
1637
2585
  // 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
1638
2586
  const toc = await readTocOnly(dir, id)
1639
2587
  const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
@@ -1643,16 +2591,19 @@ async function signWork(rel, who) {
1643
2591
  const incRaw = Math.floor(Number(args?.todayCount))
1644
2592
  const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
1645
2593
  const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
1646
- const before = Number(rec.readThrough) || 0
2594
+ const own = readerBook(st, reader.id, id)
2595
+ const before = Number(own.readThrough) || 0
1647
2596
  if (chapters) rec.chapters = chapters
1648
- rec.readThrough = Math.max(before, n)
2597
+ own.readThrough = Math.max(before, n)
2598
+ own.next = chapters ? Math.min(chapters, own.readThrough + 1) : own.readThrough + 1
2599
+ own.lastReadAt = new Date().toISOString()
2600
+ rec.readThrough = Math.max(Number(rec.readThrough) || 0, own.readThrough)
1649
2601
  rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
1650
- rec.lastReadAt = new Date().toISOString()
1651
- st.current = id
2602
+ rec.lastReadAt = own.lastReadAt
2603
+ furthestOf(st, id)
2604
+ // 读书不动「面板上正在显示的那本」:current 只在用户手动选书时改(2026-11-27)
1652
2605
  const t = today()
1653
- st.log = st.log || {}
1654
- st.log[t] = st.log[t] || {}
1655
- st.log[t][id] = (Number(st.log[t][id]) || 0) + inc
2606
+ bumpLog(st, t, id, reader.id, inc)
1656
2607
  await saveState(dir, st)
1657
2608
  const todayCount = Number(st.log[t][id]) || 0
1658
2609
  // textOut 的 schema 是 object,必须返回对象(以前返回字符串,工具报 "value" must be an object)
@@ -1661,11 +2612,13 @@ async function signWork(rel, who) {
1661
2612
  book: rec.title || id,
1662
2613
  id,
1663
2614
  before,
1664
- readThrough: rec.readThrough,
1665
- next: rec.next,
2615
+ readThrough: own.readThrough,
2616
+ next: own.next,
1666
2617
  chapters: chapters || null,
1667
2618
  today: todayCount,
1668
- text: `ok readThrough ${before} -> ${rec.readThrough} next ${rec.next} today ${todayCount}`,
2619
+ reader: reader.name,
2620
+ furthest: rec.furthest || own.readThrough,
2621
+ text: `ok readThrough ${before} -> ${own.readThrough} next ${own.next} today ${todayCount}`,
1669
2622
  }
1670
2623
  },
1671
2624
  }),
@@ -1679,20 +2632,24 @@ async function signWork(rel, who) {
1679
2632
  + '默认按「上次写到哪 → 这次读到哪」自动起标题(如「第 23–27 章」),不必一章一条。'
1680
2633
  + '只记真的打动你的:一句话的判断、一个比喻、一处想不通。这不是交作业,想不出就不写。',
1681
2634
  parameters: obj({
1682
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
2635
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
1683
2636
  chapter: { type: 'string', description: '标题(不填=自动用「第 A–B 章」,A 是上次写到的下一章)' },
1684
2637
  lines: { type: 'array', items: { type: 'string' }, description: '一到三条,每条一句,短。' },
1685
- by: { type: 'string', description: '谁写的(必填,比如「鹿野」或你所在对话的名字)' },
2638
+ by: { type: 'string', description: '谁写的(必填,写你自己那个名字,比如「鹿野」「鹿野(DSH)」)' },
1686
2639
  }),
1687
2640
  output: textOut,
1688
- async execute(args) {
2641
+ async execute(args, exec) {
1689
2642
  const { dir, st } = await stateOf()
1690
- const id = args?.book || st.current
1691
- if (!id) throw new Error('还没有正在读的书')
2643
+ const reader = await readerOf(exec)
2644
+ // 不填 book 时落到「我自己最后读过的那本」;别再拿全局 st.current——
2645
+ // 别人/别的窗口一读就把 current 改走了,读后感会落错书(2026-11-27 主对话测出来的)
2646
+ const id = args?.book || lastReadBookOf(st, reader.id)
2647
+ if (!id) throw new Error('不知道读哪本:传 book,或先读过一本')
1692
2648
  const rec = st.books[id] || {}
1693
2649
  const info = await bookInfo(dir, id)
1694
- const end = Number(rec.readThrough) || 0
1695
- const from = Number(rec.noteUntil) || 0
2650
+ const own = readerBook(st, reader.id, id)
2651
+ const end = Number(own.readThrough) || 0
2652
+ const from = Number(own.noteUntil) || 0
1696
2653
  // 默认按「一段」写:上次写到第 X 章,这次写到读到的地方,标题用「第 A–B 章」
1697
2654
  const autoTitle = (from < end)
1698
2655
  ? (from + 1 === end ? `第 ${end} 章` : `第 ${from + 1}–${end} 章`)
@@ -1702,14 +2659,15 @@ async function signWork(rel, who) {
1702
2659
  if (!lines.length) throw new Error('lines 不能为空')
1703
2660
  const who = String(args?.by || '').trim()
1704
2661
  if (!who) {
1705
- throw new Error('写读后感必须带 by(谁写的),比如 by: "鹿野";这不是流程,是为了让别人知道这句是谁读出来的。')
2662
+ throw new Error(`写读后感必须带 by(谁写的),比如 by: "${reader.name}";这不是流程,是为了让别人知道这句是谁读出来的。`)
1706
2663
  }
1707
2664
  const p = await appendNote(dir, rec.title || id, chTitle, lines, who)
1708
2665
  if (end) {
1709
- st.books[id] = { ...rec, noteUntil: end }
2666
+ own.noteUntil = end
2667
+ rec.noteUntil = Math.max(Number(rec.noteUntil) || 0, end)
1710
2668
  await saveState(dir, st)
1711
2669
  }
1712
- return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length }
2670
+ return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length, reader: reader.name }
1713
2671
  },
1714
2672
  }),
1715
2673
  )
@@ -1740,17 +2698,18 @@ async function signWork(rel, who) {
1740
2698
  '在书里搜一个词或名字,返回它出现在第几章、那一行原文。想找“这句话在哪”“这个人第几章出场”时用它,比一页页翻省得多。',
1741
2699
  parameters: obj({
1742
2700
  query: { type: 'string', description: '要搜的词(人名、地名、一句话都行)' },
1743
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
2701
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
1744
2702
  limit: { type: 'number', description: '最多几条,默认 8' },
1745
2703
  }),
1746
2704
  output: textOut,
1747
- async execute(args) {
2705
+ async execute(args, exec) {
1748
2706
  const q = String(args?.query || '').trim()
1749
2707
  if (!q) throw new Error('需要 query')
1750
2708
  const limit = Math.max(1, Math.min(30, Number(args?.limit) || 8))
1751
2709
  const { dir, st } = await stateOf()
1752
- const id = args?.book || st.current
1753
- if (!id) throw new Error('还没有正在读的书')
2710
+ const reader = await readerOf(exec)
2711
+ const id = args?.book || lastReadBookOf(st, reader.id)
2712
+ if (!id) throw new Error('不知道搜哪本:传 book,或先读过一本')
1754
2713
  const { text, chapters } = await fullTextOf(dir, id)
1755
2714
  const hits = []
1756
2715
  let at = text.indexOf(q)
@@ -1784,16 +2743,18 @@ async function signWork(rel, who) {
1784
2743
  description:
1785
2744
  '把这本书已读的部分压成一页:读到第几章、读过哪些章名、每章自己写了几条批注。上一句“我读到哪了、想过什么”说不清时用它。',
1786
2745
  parameters: obj({
1787
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
2746
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
1788
2747
  }),
1789
2748
  output: textOut,
1790
- async execute(args) {
2749
+ async execute(args, exec) {
1791
2750
  const { dir, st } = await stateOf()
1792
- const id = args?.book || st.current
1793
- if (!id) throw new Error('还没有正在读的书')
2751
+ const reader = await readerOf(exec)
2752
+ const id = args?.book || lastReadBookOf(st, reader.id)
2753
+ if (!id) throw new Error('不知道看哪本:传 book,或先读过一本')
1794
2754
  const rec = st.books[id] || {}
1795
2755
  const info = await bookInfo(dir, id)
1796
- const n = Number(rec.readThrough) || 0
2756
+ const mine = readerBookRead(st, reader.id, id)
2757
+ const n = Number(mine.readThrough) || 0
1797
2758
  const titles = info.chapters.slice(0, n).map((c, i) => ({ n: i + 1, title: c.title }))
1798
2759
  const notes = {}
1799
2760
  try {
@@ -1809,7 +2770,9 @@ async function signWork(rel, who) {
1809
2770
  ok: true,
1810
2771
  book: id,
1811
2772
  title: rec.title || id,
2773
+ reader: reader.name,
1812
2774
  readThrough: n,
2775
+ furthest: furthestOf(st, id),
1813
2776
  total: info.chapters.length,
1814
2777
  next: n + 1,
1815
2778
  titles,
@@ -1818,4 +2781,4 @@ async function signWork(rel, who) {
1818
2781
  },
1819
2782
  }),
1820
2783
  )
1821
- }
2784
+ }