dsh-half-page 0.3.53 → 0.4.48

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 (5) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +15 -6
  3. package/client.js +1013 -689
  4. package/index.js +1100 -125
  5. package/package.json +3 -2
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,73 @@ 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
+ const every = Math.min(1440, Math.max(5, Math.floor(Number(s.everyMinutes) || 30)))
454
+ const budget = Math.min(24, Math.max(1, Math.floor(Number(s.dailyBudget) || dBudget || 4)))
455
+ return {
456
+ id: String(s.id || ('slot-' + (i + 1))),
457
+ enabled: s.enabled === true,
458
+ from: String(s.from ?? ''),
459
+ to: String(s.to ?? ''),
460
+ everyMinutes: every,
461
+ dailyBudget: budget,
462
+ mode,
463
+ per: dBudget,
464
+ session: String(s.session ?? ''),
465
+ lastAt: Number(s.lastAt) || 0,
466
+ week: String(s.week || ''),
467
+ weekCount: Number(s.weekCount) || 0,
468
+ day: String(s.day || ''),
469
+ dayCount: Number(s.dayCount) || 0,
470
+ }
471
+ }
472
+
473
+ /** state.study.slots;一条都没有时用旧配置合成一条(老用户行为不变) */
474
+ export function studySlotsOf(st, cfg) {
475
+ const raw = Array.isArray(st?.study?.slots) ? st.study.slots : []
476
+ if (raw.length) return raw.map((s, i) => normaliseStudySlot(s, cfg, i))
477
+ return [normaliseStudySlot({
478
+ id: 'slot-1',
479
+ enabled: cfg?.studyEnabled === true,
480
+ from: cfg?.studyFrom ?? '',
481
+ to: cfg?.studyTo ?? '',
482
+ mode: studyModeOf(cfg),
483
+ per: studyModeOf(cfg) === 'day' ? studyPerDayOf(cfg) : studyPerWeekOf(cfg),
484
+ session: cfg?.studySession ?? '',
485
+ }, cfg, 0)]
486
+ }
487
+
488
+ /** 把一条 slot 摊成 decideStudy 认的 cfg 形状 */
489
+ export function slotCfgOf(slot) {
490
+ return {
491
+ studyEnabled: slot.enabled === true,
492
+ studyFrom: slot.from,
493
+ studyTo: slot.to,
494
+ studyMode: slot.mode,
495
+ studyPerDay: slot.per,
496
+ studyPerWeek: slot.per,
497
+ studyEveryMinutes: Math.min(1440, Math.max(5, Math.floor(Number(slot.everyMinutes) || 30))),
498
+ studyDailyBudget: Math.min(24, Math.max(1, Math.floor(Number(slot.dailyBudget) || slot.per || 4))),
499
+ }
500
+ }
501
+
502
+ /** 一条 slot 自己的计数(跨周/跨天归零) */
503
+ export function slotStudyOf(slot, now = Date.now()) {
504
+ const week = weekKeyOf(now)
505
+ const day = localDayOf(now)
506
+ return {
507
+ lastAt: Number(slot.lastAt) || 0,
508
+ week,
509
+ weekCount: slot.week === week ? Number(slot.weekCount) || 0 : 0,
510
+ day,
511
+ dayCount: slot.day === day ? Number(slot.dayCount) || 0 : 0,
512
+ }
513
+ }
514
+
242
515
  /** 今天有没有读过(任一书的 lastReadAt 落在本地今天) */
243
516
  export function readSomethingToday(st, now = Date.now()) {
244
517
  const day = localDayOf(now)
@@ -278,7 +551,13 @@ export function decideStudy({ cfg, study, now, timeline }) {
278
551
  if (!w) return { ok: false, reason: 'no-window' }
279
552
  if (!inStudyWindow(w, new Date(now))) return { ok: false, reason: 'outside' }
280
553
  const mode = studyModeOf(cfg)
281
- if (mode === 'day') {
554
+ if (Number(cfg?.studyEveryMinutes) > 0) {
555
+ // 心跳那套:只靠「距上次叫满一个频次」和「今天上限」,读没读过都不管
556
+ const budget = Math.max(1, Math.floor(Number(cfg.studyDailyBudget) || 4))
557
+ if ((Number(study.dayCount) || 0) >= budget) return { ok: false, reason: 'day-budget' }
558
+ const gap = Math.max(5, Math.floor(Number(cfg.studyEveryMinutes) || 30)) * 60000
559
+ if (study.lastAt && localDayOf(study.lastAt) === localDayOf(now) && now - study.lastAt < gap) return { ok: false, reason: 'gap' }
560
+ } else if (mode === 'day') {
282
561
  if ((Number(study.dayCount) || 0) >= studyPerDayOf(cfg)) return { ok: false, reason: 'day-budget' }
283
562
  } else {
284
563
  if (study.lastAt && localDayOf(study.lastAt) === localDayOf(now)) return { ok: false, reason: 'today-called' }
@@ -548,6 +827,26 @@ export function readToday(st) {
548
827
  return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
549
828
  }
550
829
 
830
+ /** 记一格读书:全局 log + 这位读者自己的 rlog(两边都记,退章时一起退) */
831
+ export function bumpLog(st, t, id, readerId, inc = 1) {
832
+ const rid = readerId || LEGACY_READER
833
+ st.log = st.log || {}
834
+ st.log[t] = st.log[t] || {}
835
+ st.log[t][id] = Math.max(0, (Number(st.log[t][id]) || 0) + inc)
836
+ st.rlog = st.rlog || {}
837
+ st.rlog[t] = st.rlog[t] || {}
838
+ st.rlog[t][rid] = st.rlog[t][rid] || {}
839
+ st.rlog[t][rid][id] = Math.max(0, (Number(st.rlog[t][rid][id]) || 0) + inc)
840
+ }
841
+
842
+ /** 某位读者今天读了几章(按 rlog)。老账只有全局 log,所以「读书总进度」在没分片时回落到全局;具体读者记 0。 */
843
+ export function readTodayOf(st, readerId) {
844
+ const t = today()
845
+ const row = (st.rlog && st.rlog[t] && st.rlog[t][readerId]) || null
846
+ if (!row) return readerId === LEGACY_READER ? readToday(st) : 0
847
+ return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
848
+ }
849
+
551
850
  export async function notesPath(dir) {
552
851
  return join(dir, '读后感.md')
553
852
  }
@@ -575,32 +874,35 @@ async function latestSessionTitle() {
575
874
 
576
875
  export async function appendNote(dir, bookTitle, chapterTitle, lines, by) {
577
876
  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
877
+ // 同一秒两个窗口写会丢一条:整段「读—改—写」放进锁里(锁是 p + '.lock')
878
+ return withFileLock(p, async () => {
879
+ let raw = ''
880
+ try { raw = await readFile(p, 'utf8') } catch {}
881
+ const esc = bookTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
882
+ let block = `\n### ${chapterTitle}\n` + lines.map((l) => `- ${l}`).join('\n') + '\n'
883
+ if (by) {
884
+ const d = new Date()
885
+ const pad = (n) => String(n).padStart(2, '0')
886
+ const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
887
+ block += `- \u21b3 \u6765\u81ea\uff1a${by} \u00b7 ${ts}\n`
888
+ }
889
+ const headRe = new RegExp(`^##\\s+${esc}\\s*$`, 'm')
890
+ const m = headRe.exec(raw)
891
+ if (!m) {
892
+ raw = (raw.trim() ? raw.replace(/\s*$/, '') + '\n\n' : '') + `## ${bookTitle}\n` + block
597
893
  } else {
598
- const at = at0 + next
599
- raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
894
+ const at0 = m.index + m[0].length
895
+ const next = raw.slice(at0).search(/^##\s+/m)
896
+ if (next < 0) {
897
+ raw = raw.replace(/\s*$/, '') + '\n' + block
898
+ } else {
899
+ const at = at0 + next
900
+ raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
901
+ }
600
902
  }
601
- }
602
- await writeFile(p, raw, 'utf8')
603
- return p
903
+ await writeFile(p, raw, 'utf8')
904
+ return p
905
+ })
604
906
  }
605
907
 
606
908
  /* ---------------- 图片:作品与画 ------------------
@@ -778,6 +1080,55 @@ export function apply(ctx, rawConfig) {
778
1080
  return out
779
1081
  }
780
1082
 
1083
+ /** 这一拍是谁在读:会话 id 当读者 id,标题当名字;没有会话就是老数据那份「默认读者」。 */
1084
+ const READER_NAME_CACHE = new Map()
1085
+ /** 名字看起来就是会话 id(而不是人给的名字):这种不能拿来当读者名显示。 */
1086
+ function nameIsId(name, id) {
1087
+ const s = String(name || '').trim()
1088
+ if (!s || s === id) return true
1089
+ return /^session-[0-9a-f-]{8,}$/i.test(s)
1090
+ }
1091
+ async function readerOf(exec) {
1092
+ const sid = exec?.agent?.session?.id || exec?.agent?.id || ''
1093
+ if (!sid) return { id: LEGACY_READER, name: LEGACY_READER_NAME }
1094
+ let name = READER_NAME_CACHE.get(sid)
1095
+ if (!name) {
1096
+ const header = exec?.agent?.session?.header || {}
1097
+ name = header.title || exec?.agent?.session?.title || ''
1098
+ if (nameIsId(name, sid)) name = await sessionTitleOf(sid)
1099
+ if (nameIsId(name, sid)) name = '会话 ' + String(sid).slice(-8)
1100
+ READER_NAME_CACHE.set(sid, name)
1101
+ READER_NAMES.set(String(sid), name)
1102
+ }
1103
+ return { id: String(sid), name }
1104
+ }
1105
+
1106
+ /** 面板用的读者一览:顺手把「名字还存成会话 id」的那些补成真名字,并写回 state。 */
1107
+ async function readersFor(dir, st) {
1108
+ const list = readerSummary(st)
1109
+ let fixed = false
1110
+ for (const r of list) {
1111
+ if (r.id === LEGACY_READER) continue
1112
+ if (!nameIsId(r.name, r.id)) continue
1113
+ let real = await sessionTitleOf(r.id)
1114
+ if (nameIsId(real, r.id)) real = '会话 ' + String(r.id).slice(-8)
1115
+ r.name = real
1116
+ if (st.readers?.[r.id]) st.readers[r.id].name = real
1117
+ READER_NAME_CACHE.set(r.id, real)
1118
+ READER_NAMES.set(r.id, real)
1119
+ fixed = true
1120
+ }
1121
+ if (fixed) await saveState(dir, st)
1122
+ return list
1123
+ }
1124
+
1125
+ /** 面板传过来的读者(下拉选的);没有就用默认读者 */
1126
+ function readerParam(st, url) {
1127
+ const asked = String(url.searchParams.get('reader') || '').trim()
1128
+ if (asked && st.readers && st.readers[asked]) return { id: asked, name: st.readers[asked].name || asked }
1129
+ return { id: LEGACY_READER, name: (st.readers?.[LEGACY_READER]?.name) || LEGACY_READER_NAME }
1130
+ }
1131
+
781
1132
  /** 只投那一句;成功才返回 { ok, at } */
782
1133
  async function deliverStudy(sessionId) {
783
1134
  const agent = await resolveAgent(sessionId)
@@ -806,26 +1157,42 @@ export function apply(ctx, rawConfig) {
806
1157
  studyBusy = true
807
1158
  try {
808
1159
  const cfgNow = await config()
809
- if (cfgNow.studyEnabled !== true) return
810
1160
  const dir = cfgNow.dir
811
1161
  const st = await loadState(dir)
812
1162
  const now = Date.now()
813
- const study = studyStateOf(st, now)
814
- 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
1163
+ const slots = studySlotsOf(st, cfgNow)
1164
+ let changed = false
1165
+ for (const slot of slots) {
1166
+ if (slot.enabled !== true) continue
1167
+ const w = studyWindowOf(slotCfgOf(slot))
1168
+ if (!w) continue
1169
+ if (!inStudyWindow(w, new Date(now))) continue
1170
+ const counters = slotStudyOf(slot, now)
1171
+ const sessionId = slot.session || await newestSessionId(SESSIONS_ROOT)
1172
+ if (!sessionId) continue
1173
+ const timeline = await readTimeline(SESSIONS_ROOT, sessionId, { tailFrames: 200 })
1174
+ const verdict = decideStudy({ cfg: slotCfgOf(slot), study: counters, now, timeline })
1175
+ if (!verdict.ok) continue
1176
+ const sent = await deliverStudy(sessionId)
1177
+ if (!sent.ok) continue
1178
+ slot.lastAt = sent.at
1179
+ slot.week = counters.week
1180
+ slot.weekCount = counters.weekCount + 1
1181
+ slot.day = counters.day
1182
+ slot.dayCount = counters.dayCount + 1
1183
+ changed = true
1184
+ }
1185
+ if (!changed) return
822
1186
  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,
1187
+ st.study = { ...(st.study || {}), slots }
1188
+ // 顶上那几个旧字段跟着第一条走,面板/老代码读到的不至于错乱
1189
+ const first = slots[0]
1190
+ if (first) {
1191
+ st.study.lastAt = first.lastAt
1192
+ st.study.week = first.week
1193
+ st.study.weekCount = first.weekCount
1194
+ st.study.day = first.day
1195
+ st.study.dayCount = first.dayCount
829
1196
  }
830
1197
  await saveState(dir, st)
831
1198
  } catch {
@@ -847,10 +1214,26 @@ export function apply(ctx, rawConfig) {
847
1214
  }
848
1215
  })
849
1216
 
1217
+ let namesRepaired = false
850
1218
  const stateOf = async () => {
851
1219
  const { dir, perDay } = await config()
852
1220
  await ensureDir(dir)
853
1221
  const st = await loadState(dir)
1222
+ // 一次性把「名字存成会话 id」的读者修回标题(每个进程只做一次)
1223
+ if (!namesRepaired) {
1224
+ namesRepaired = true
1225
+ let fixed = false
1226
+ for (const [id, r] of Object.entries(st.readers || {})) {
1227
+ if (id === LEGACY_READER) continue
1228
+ if (!nameIsId(r.name, id)) { READER_NAMES.set(id, r.name); continue }
1229
+ let real = await sessionTitleOf(id)
1230
+ if (nameIsId(real, id)) real = '会话 ' + String(id).slice(-8)
1231
+ r.name = real
1232
+ READER_NAMES.set(id, real)
1233
+ fixed = true
1234
+ }
1235
+ if (fixed) await saveState(dir, st)
1236
+ }
854
1237
  const shelf = await listBooks(dir)
855
1238
  return { dir, perDay, st, shelf, today: today(), readToday: readToday(st) }
856
1239
  }
@@ -863,7 +1246,11 @@ export function apply(ctx, rawConfig) {
863
1246
  path: '/dsh-reading.state',
864
1247
  async handler(req, res) {
865
1248
  const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
1249
+ let localVersion = ''
1250
+ try { localVersion = JSON.parse(await readFile(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8')).version || '' } catch {}
1251
+
866
1252
  const cfgNow = await config()
1253
+ const rid0 = readerParam(st, new URL(req.url || '/', 'http://localhost')).id
867
1254
  const books = []
868
1255
  for (const b of shelf) {
869
1256
  const rec = st.books[b.id] || {}
@@ -874,6 +1261,16 @@ export function apply(ctx, rawConfig) {
874
1261
  chapters = (toc && toc.chapters && toc.chapters.length) || 0
875
1262
  } catch {}
876
1263
  }
1264
+ const ownShard = readerOwnBook(st, rid0, b.id)
1265
+ const mineN = Number(ownShard && ownShard.readThrough) || 0
1266
+ let mineTitle = ''
1267
+ if (mineN > 0) {
1268
+ try {
1269
+ const toc = await readTocOnly(dir, b.id)
1270
+ const ch = toc && toc.chapters && toc.chapters[mineN - 1]
1271
+ mineTitle = (ch && ch.title) || ''
1272
+ } catch {}
1273
+ }
877
1274
  books.push({
878
1275
  id: b.id,
879
1276
  title: rec.title || b.id,
@@ -881,6 +1278,10 @@ export function apply(ctx, rawConfig) {
881
1278
  mtime: b.mtime,
882
1279
  chapters,
883
1280
  readThrough: rec.readThrough || 0,
1281
+ mineReadThrough: mineN,
1282
+ mineChapterTitle: mineTitle,
1283
+ furthest: furthestOf(st, b.id),
1284
+ furthestReader: furthestReaderOf(st, b.id),
884
1285
  next: rec.next || 1,
885
1286
  lastReadAt: rec.lastReadAt || '',
886
1287
  current: st.current === b.id,
@@ -894,6 +1295,8 @@ export function apply(ctx, rawConfig) {
894
1295
  const liveSessions = await liveSessionList()
895
1296
  res.end(JSON.stringify({
896
1297
  ok: true, dir, perDay, today: today(), readToday: rt, current: st.current, books, notes,
1298
+ version: localVersion,
1299
+ readers: await readersFor(dir, st), liveSessions,
897
1300
  noteSort: Number(cfgNow.noteSort) || 0,
898
1301
  study: {
899
1302
  enabled: cfgNow.studyEnabled === true,
@@ -907,12 +1310,463 @@ export function apply(ctx, rawConfig) {
907
1310
  dayCount: st2.dayCount,
908
1311
  session: cfgNow.studySession || '',
909
1312
  sessions: liveSessions,
1313
+ slots: studySlotsOf(st, cfgNow).map((s, i) => {
1314
+ const c = slotStudyOf(s, Date.now())
1315
+ return {
1316
+ id: s.id, index: i, enabled: s.enabled, from: s.from, to: s.to, mode: s.mode, per: s.per,
1317
+ everyMinutes: s.everyMinutes, dailyBudget: s.dailyBudget,
1318
+ session: s.session, sessionName: (liveSessions.find((x) => x.id === s.session) || {}).title || '',
1319
+ lastAt: c.lastAt, dayCount: c.dayCount, weekCount: c.weekCount,
1320
+ }
1321
+ }),
910
1322
  },
911
1323
  }))
912
1324
  },
913
1325
  }),
914
1326
  )
915
1327
 
1328
+ // 保存「书房时间」列表(每条:启用/时段/频率/叫哪条会话)
1329
+ ctx.effect(() =>
1330
+ ctx.webServer.register({
1331
+ auth: sameSiteAuth,
1332
+ kind: 'exact',
1333
+ path: '/dsh-reading.restore',
1334
+ async handler(req, res) {
1335
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1336
+ const fail = (msg) => { try { res.end(JSON.stringify({ ok: false, error: String(msg) })) } catch {} }
1337
+ try {
1338
+ let body = ''
1339
+ for await (const c of req) body += c
1340
+ let j = {}
1341
+ try { j = JSON.parse(body || '{}') || {} } catch { return fail('不是合法的 JSON') }
1342
+ let src = j.json
1343
+ if (typeof src === 'string') { try { src = JSON.parse(src) } catch { return fail('这个文件不是半页的备份') } }
1344
+ if (!src || typeof src !== 'object') return fail('这个文件不是半页的备份')
1345
+ const prog = src.progress && typeof src.progress === 'object' ? src.progress : (src.books ? src : null)
1346
+ const notes = typeof src.notes === 'string' ? src.notes : ''
1347
+ if (!prog && !notes) return fail('文件里既没有读后感,也没有进度')
1348
+ if (prog && (!prog.books || typeof prog.books !== 'object')) return fail('进度里没有 books')
1349
+ // 防御:/dsh-reading.state 返回的 readers 是数组(给面板看的视图),若有人把那份响应当备份回灌,
1350
+ // 这里先把它归成 { <sid>: {name, books} },否则 state.json 会被写坏、所有分片查不到。
1351
+ if (prog && Array.isArray(prog.readers)) {
1352
+ const fixed = {}
1353
+ prog.readers.forEach((item, i) => {
1354
+ if (!item || typeof item !== 'object') return
1355
+ const rawId = String(item.id || '')
1356
+ const key = /^(session-|manual-|__legacy__)/.test(rawId) ? rawId : 'manual-restored-' + i
1357
+ fixed[key] = { name: String(item.name || key), books: item.books && typeof item.books === 'object' ? item.books : {} }
1358
+ })
1359
+ prog.readers = fixed
1360
+ }
1361
+ // 防御二:books 同样可能是数组(/dsh-reading.state 的响应就是数组形态),先归成 { <id>: {...} },
1362
+ // 否则 state.json 的 books 变成数组,之后书级 readThrough/lastReadAt 全写不进(数组挂字符串键会被 JSON 丢掉)。
1363
+ if (prog && Array.isArray(prog.books)) {
1364
+ const fixedBooks = {}
1365
+ for (const b of prog.books) {
1366
+ if (!b || typeof b !== 'object' || !b.id) continue
1367
+ fixedBooks[String(b.id)] = {
1368
+ id: String(b.id),
1369
+ title: String(b.title || b.id),
1370
+ chapters: Number(b.chapters) || 0,
1371
+ readThrough: Number(b.readThrough) || 0,
1372
+ next: Number(b.next) || 1,
1373
+ lastReadAt: b.lastReadAt || '',
1374
+ noteUntil: Number(b.noteUntil) || 0,
1375
+ furthest: Number(b.furthest) || Number(b.readThrough) || 0,
1376
+ }
1377
+ }
1378
+ prog.books = fixedBooks
1379
+ }
1380
+ const { dir, st } = await stateOf()
1381
+ await ensureDir(dir)
1382
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
1383
+ const backups = []
1384
+ if (prog) {
1385
+ const bak = 'state.json.bak-restore-' + stamp
1386
+ try { await copyFile(join(dir, 'state.json'), join(dir, bak)); backups.push(bak) } catch {}
1387
+ const merged = {
1388
+ ...st,
1389
+ current: typeof prog.current === 'string' && prog.current ? prog.current : st.current,
1390
+ books: prog.books,
1391
+ readers: prog.readers && typeof prog.readers === 'object' ? prog.readers : st.readers,
1392
+ log: prog.log && typeof prog.log === 'object' ? prog.log : st.log,
1393
+ rlog: prog.rlog && typeof prog.rlog === 'object' ? prog.rlog : st.rlog,
1394
+ }
1395
+ migrateReaders(merged)
1396
+ await saveState(dir, merged)
1397
+ }
1398
+ let noteLines = 0
1399
+ if (notes) {
1400
+ const np = await notesPath(dir)
1401
+ const bak = '读后感.md.bak-restore-' + stamp
1402
+ try { await copyFile(np, join(dir, bak)); backups.push(bak) } catch {}
1403
+ await writeFile(np, notes, 'utf8')
1404
+ noteLines = notes.split(/\r?\n/).filter((l) => /^[-*]\s+/.test(l)).length
1405
+ }
1406
+ res.end(JSON.stringify({ ok: true, books: prog ? Object.keys(prog.books || {}).length : 0, notes: noteLines, backups }))
1407
+ } catch (e) { fail((e && e.stack) || (e && e.message) || e) }
1408
+ },
1409
+ }),
1410
+ )
1411
+
1412
+ // 保存「书房时间」列表(每条:启用/时段/频率/叫哪条会话)
1413
+ ctx.effect(() =>
1414
+ ctx.webServer.register({
1415
+ auth: sameSiteAuth,
1416
+ kind: 'exact',
1417
+ path: '/dsh-reading.study',
1418
+ async handler(req, res) {
1419
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1420
+ let body = ''
1421
+ try { for await (const c of req) body += c } catch {}
1422
+ let j = {}
1423
+ try { j = JSON.parse(body || '{}') || {} } catch {}
1424
+ if (!Array.isArray(j.slots)) return res.end(JSON.stringify({ ok: false, error: 'slots 要是数组' }))
1425
+ const cfgNow = await config()
1426
+ const { dir, st } = await stateOf()
1427
+ const prev = studySlotsOf(st, cfgNow)
1428
+ const byId = new Map(prev.map((s) => [s.id, s]))
1429
+ const slots = j.slots.slice(0, 12).map((raw, i) => {
1430
+ const slot = normaliseStudySlot(raw, cfgNow, i)
1431
+ const old = byId.get(slot.id)
1432
+ if (old) {
1433
+ // 计数跟 id 走:改时段/换会话都不清零,删掉重加才是新的
1434
+ slot.lastAt = old.lastAt
1435
+ slot.week = old.week
1436
+ slot.weekCount = old.weekCount
1437
+ slot.day = old.day
1438
+ slot.dayCount = old.dayCount
1439
+ }
1440
+ return slot
1441
+ })
1442
+ await ensureDir(dir)
1443
+ st.study = { ...(st.study || {}), slots }
1444
+ const first = slots[0]
1445
+ if (first) {
1446
+ st.study.lastAt = first.lastAt
1447
+ st.study.week = first.week
1448
+ st.study.weekCount = first.weekCount
1449
+ st.study.day = first.day
1450
+ st.study.dayCount = first.dayCount
1451
+ }
1452
+ await saveState(dir, st)
1453
+ res.end(JSON.stringify({ ok: true, slots: slots.length }))
1454
+ },
1455
+ }),
1456
+ )
1457
+
1458
+ // 备份到文件:面板在 iframe 里,<a download> 不会弹保存框,所以由服务端写盘、把路径回给面板
1459
+ ctx.effect(() =>
1460
+ ctx.webServer.register({
1461
+ auth: sameSiteAuth,
1462
+ kind: 'exact',
1463
+ path: '/dsh-reading.backupFile',
1464
+ async handler(req, res) {
1465
+ try {
1466
+ const { appendFile: af } = await import('node:fs/promises')
1467
+ const { tmpdir: td } = await import('node:os')
1468
+ const { join: jn } = await import('node:path')
1469
+ await af(jn(td(), 'hp-backup-hit.log'), new Date().toISOString() + ' ' + req.method + ' origin=' + (req.headers.origin || '-') + ' host=' + (req.headers.host || '-') + '\n')
1470
+ } catch {}
1471
+
1472
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1473
+ try {
1474
+ const { dir, st } = await stateOf()
1475
+ await ensureDir(dir)
1476
+ let notes = ''
1477
+ try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
1478
+ const payload = { kind: 'dsh-half-page-backup', version: 1, at: new Date().toISOString(), notes, progress: st }
1479
+ const bdir = join(dir, 'backups')
1480
+ await mkdir(bdir, { recursive: true })
1481
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
1482
+ const out = join(bdir, '半页备份-' + stamp + '.json')
1483
+ const text = JSON.stringify(payload, null, 2)
1484
+ await writeFile(out, text, 'utf8')
1485
+ res.end(JSON.stringify({ ok: true, path: out, bytes: Buffer.byteLength(text) }))
1486
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1487
+ },
1488
+ }),
1489
+ )
1490
+
1491
+ // 读一个备份文件(面板读不到本地磁盘,只能让宿主读)
1492
+ ctx.effect(() =>
1493
+ ctx.webServer.register({
1494
+ auth: sameSiteAuth,
1495
+ kind: 'exact',
1496
+ path: '/dsh-reading.readFile',
1497
+ async handler(req, res) {
1498
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1499
+ try {
1500
+ const u = new URL(req.url || '/', 'http://localhost')
1501
+ const p = String(u.searchParams.get('path') || '').trim().replace(/^"|"$/g, '')
1502
+ if (!p) throw new Error('要一个文件路径')
1503
+ const s2 = await stat(p)
1504
+ if (!s2.isFile()) throw new Error('不是文件')
1505
+ if (s2.size > 50 * 1024 * 1024) throw new Error('文件太大(超过 50MB)')
1506
+ const text = await readFile(p, 'utf8')
1507
+ res.end(JSON.stringify({ ok: true, text }))
1508
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1509
+ },
1510
+ }),
1511
+ )
1512
+
1513
+ // 在资源管理器里选中一个文件(面板点「在文件夹里打开」时用)
1514
+ ctx.effect(() =>
1515
+ ctx.webServer.register({
1516
+ auth: sameSiteAuth,
1517
+ kind: 'exact',
1518
+ path: '/dsh-reading.reveal',
1519
+ async handler(req, res) {
1520
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1521
+ try {
1522
+ let body = ''
1523
+ for await (const c of req) body += c
1524
+ const j = JSON.parse(body || '{}') || {}
1525
+ const p = String(j.path || '').trim()
1526
+ if (!p) throw new Error('要一个文件路径')
1527
+ if (!isAbsolute(p)) throw new Error('要绝对路径')
1528
+ const s2 = await stat(p)
1529
+ if (!s2.isFile()) throw new Error('不是文件')
1530
+ if (process.platform === 'win32') {
1531
+ spawn('explorer.exe', ['/select,' + p], { detached: true, stdio: 'ignore' }).unref()
1532
+ } else if (process.platform === 'darwin') {
1533
+ spawn('open', ['-R', p], { detached: true, stdio: 'ignore' }).unref()
1534
+ } else {
1535
+ spawn('xdg-open', [dirname(p)], { detached: true, stdio: 'ignore' }).unref()
1536
+ }
1537
+ res.end(JSON.stringify({ ok: true, path: p }))
1538
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1539
+ },
1540
+ }),
1541
+ )
1542
+
1543
+ // 查 npm 上最新版(面板「检测更新」用)
1544
+ const checkUpdate = async () => {
1545
+ const here = dirname(fileURLToPath(import.meta.url))
1546
+
1547
+ let current = ''
1548
+ try {
1549
+ current = JSON.parse(await readFile(join(here, 'package.json'), 'utf8')).version || ''
1550
+ } catch { /* 拿不到就只说最新版 */ }
1551
+ let latest = ''
1552
+ try {
1553
+ const res = await fetch('https://registry.npmjs.org/dsh-half-page/latest', { headers: { accept: 'application/json' } })
1554
+ if (res.ok) latest = String((await res.json()).version || '')
1555
+ } catch { /* 离线 */ }
1556
+ const cmp = (a, b) => {
1557
+ const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0)
1558
+ const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0)
1559
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
1560
+ const d = (pa[i] || 0) - (pb[i] || 0)
1561
+ if (d) return d > 0 ? 1 : -1
1562
+ }
1563
+ return 0
1564
+ }
1565
+ const order = current && latest ? cmp(current, latest) : 0
1566
+ return { ok: true, current, latest, ahead: order > 0, outdated: order < 0, command: 'dsh plugin add dsh-half-page@latest' }
1567
+ }
1568
+
1569
+ ctx.effect(() =>
1570
+ ctx.webServer.register({
1571
+ auth: sameSiteAuth,
1572
+ kind: 'exact',
1573
+ path: '/dsh-reading.update',
1574
+ async handler(req, res) {
1575
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1576
+ try { res.end(JSON.stringify(await checkUpdate())) } catch (e) {
1577
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1578
+ }
1579
+ },
1580
+ }),
1581
+ )
1582
+
1583
+ // 弹系统「另存为」对话框:让用户自己选放哪(面板在 iframe 里不能自己弹)
1584
+ // 对话框脚本内嵌,运行时落到临时目录:不依赖安装位置的 toolkit(换机器也能用)
1585
+ // 对话框脚本内嵌,运行时落到临时目录:不依赖安装位置的 toolkit(换机器也能用)
1586
+ const hpDialogOverlay = (mode, suggested, source) => {
1587
+ const q = (s) => "'" + String(s || '').replace(/'/g, "''") + "'"
1588
+ return [
1589
+ 'Add-Type -AssemblyName System.Windows.Forms | Out-Null',
1590
+ 'Add-Type -AssemblyName System.Drawing | Out-Null',
1591
+ `$Mode = ${q(mode)}`,
1592
+ `$Suggested = ${q(suggested)}`,
1593
+ `$Source = ${q(source)}`,
1594
+ '$owner = New-Object System.Windows.Forms.Form',
1595
+ '$owner.TopMost = $true',
1596
+ '$owner.ShowInTaskbar = $false',
1597
+ '$owner.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None',
1598
+ '$owner.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen',
1599
+ '$owner.Size = New-Object System.Drawing.Size(1,1)',
1600
+ '$owner.Opacity = 0',
1601
+ '$owner.Show()',
1602
+ '$owner.Activate()',
1603
+ 'try {',
1604
+ ' if ($Mode -eq "save") {',
1605
+ ' $dlg = New-Object System.Windows.Forms.SaveFileDialog',
1606
+ ' $dlg.Filter = "JSON (*.json)|*.json|All files (*.*)|*.*"',
1607
+ ' $dlg.FileName = $Suggested',
1608
+ ' $dlg.OverwritePrompt = $true',
1609
+ ' } else {',
1610
+ ' $dlg = New-Object System.Windows.Forms.OpenFileDialog',
1611
+ ' $dlg.Filter = "JSON (*.json)|*.json|All files (*.*)|*.*"',
1612
+ ' }',
1613
+ ' $r = $dlg.ShowDialog($owner)',
1614
+ ' if ($r -ne [System.Windows.Forms.DialogResult]::OK) { $owner.Close(); Write-Output "CANCELLED"; exit 0 }',
1615
+ ' $target = $dlg.FileName',
1616
+ ' if ($Mode -eq "save" -and $Source -ne "") { Copy-Item -LiteralPath $Source -Destination $target -Force }',
1617
+ ' $owner.Close()',
1618
+ ' Write-Output $target',
1619
+ ' exit 0',
1620
+ '} catch {',
1621
+ ' $owner.Close()',
1622
+ ' Write-Output ("ERROR " + $_.Exception.Message)',
1623
+ ' exit 1',
1624
+ '}',
1625
+ '',
1626
+ ].join('\r\n')
1627
+ }
1628
+
1629
+ const hpDialogLog = async (line) => {
1630
+ try {
1631
+ await appendFile(join(tmpdir(), 'hp-dialog.log'), new Date().toISOString() + ' ' + line + '\n')
1632
+ } catch {}
1633
+ }
1634
+
1635
+ const runDialog = (mode, suggested, source) => new Promise((resolve2) => {
1636
+ let p
1637
+ try {
1638
+ const script = hpDialogOverlay(mode, suggested, source)
1639
+ const b64 = Buffer.from(script, 'utf16le').toString('base64')
1640
+ p = spawn('powershell.exe', ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', b64], { windowsHide: true })
1641
+ } catch (e) {
1642
+ hpDialogLog('spawn-throw ' + String((e && e.message) || e))
1643
+ resolve2({ ok: false, error: String((e && e.message) || e) })
1644
+ return
1645
+ }
1646
+ let out = ''
1647
+ let err = ''
1648
+ p.stdout.on('data', (d) => { out += String(d) })
1649
+ p.stderr.on('data', (d) => { err += String(d) })
1650
+ p.on('error', (e) => {
1651
+ hpDialogLog('spawn-error ' + String((e && e.message) || e))
1652
+ resolve2({ ok: false, error: String((e && e.message) || e) })
1653
+ })
1654
+ p.on('close', (code) => {
1655
+ const line = out.trim().split(/\r?\n/).filter(Boolean).pop() || ''
1656
+ hpDialogLog('mode=' + mode + ' exit=' + code + ' out=' + JSON.stringify(line).slice(0, 200) + ' err=' + JSON.stringify(err.trim()).slice(0, 300))
1657
+ if (!line || line === 'CANCELLED') resolve2({ ok: false, cancelled: true })
1658
+ else if (line.startsWith('ERROR')) resolve2({ ok: false, error: line.slice(6).trim() })
1659
+ else resolve2({ ok: true, path: line })
1660
+ })
1661
+ })
1662
+
1663
+ ctx.effect(() =>
1664
+ ctx.webServer.register({
1665
+ auth: sameSiteAuth,
1666
+ kind: 'exact',
1667
+ path: '/dsh-reading.saveAs',
1668
+ async handler(req, res) {
1669
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1670
+ try {
1671
+ const { dir, st } = await stateOf()
1672
+ await ensureDir(dir)
1673
+ let notes = ''
1674
+ try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
1675
+ const payload = { kind: 'dsh-half-page-backup', version: 1, at: new Date().toISOString(), notes, progress: st }
1676
+ const tmpDir = join(dir, 'backups')
1677
+ await mkdir(tmpDir, { recursive: true })
1678
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
1679
+ const tmp = join(tmpDir, '.tmp-export-' + stamp + '.json')
1680
+ await writeFile(tmp, JSON.stringify(payload, null, 2), 'utf8')
1681
+ const name = '半页备份-' + stamp.slice(0, 10) + '.json'
1682
+ const r = await runDialog('save', name, tmp)
1683
+ try { await unlink(tmp) } catch {}
1684
+ res.end(JSON.stringify(r))
1685
+ } catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
1686
+ },
1687
+ }),
1688
+ )
1689
+
1690
+ // 弹「打开」对话框,返回选中的备份文件路径
1691
+ ctx.effect(() =>
1692
+ ctx.webServer.register({
1693
+ auth: sameSiteAuth,
1694
+ kind: 'exact',
1695
+ path: '/dsh-reading.pickFile',
1696
+ async handler(req, res) {
1697
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1698
+ try { res.end(JSON.stringify(await runDialog('open'))) } catch (e) {
1699
+ res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1700
+ }
1701
+ },
1702
+ }),
1703
+ )
1704
+
1705
+ // 手动新增一位读者(给还没读过书的会话先占个位置;也可以纯手动起个名字)
1706
+ ctx.effect(() =>
1707
+ ctx.webServer.register({
1708
+ auth: sameSiteAuth,
1709
+ kind: 'exact',
1710
+ path: '/dsh-reading.addReader',
1711
+ async handler(req, res) {
1712
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1713
+ let body = ''
1714
+ try { for await (const c of req) body += c } catch {}
1715
+ let j = {}
1716
+ try { j = JSON.parse(body || '{}') || {} } catch {}
1717
+ const { dir, st } = await stateOf()
1718
+ migrateReaders(st)
1719
+ st.readers = st.readers || {}
1720
+ const sid = String(j.sessionId || '').trim()
1721
+ let name = String(j.name || '').trim()
1722
+ if (!sid && !name) return res.end(JSON.stringify({ ok: false, error: '要么选一条会话,要么写个名字' }))
1723
+ let id = sid
1724
+ if (!id) {
1725
+ // 纯手动读者:给个稳定的 id,不跟任何会话绑
1726
+ id = 'manual-' + Date.now().toString(36)
1727
+ if (!name) name = '读者 ' + id.slice(-4)
1728
+ } else if (!name) {
1729
+ const t = await sessionTitleOf(sid)
1730
+ name = nameIsId(t, sid) ? ('会话 ' + sid.slice(-8)) : (t || ('会话 ' + sid.slice(-8)))
1731
+ }
1732
+ if (st.readers[id]) return res.end(JSON.stringify({ ok: true, existed: true, id, name: st.readers[id].name || name }))
1733
+ st.readers[id] = { name, books: {}, manual: !sid }
1734
+ READER_NAMES.set(id, name)
1735
+ await saveState(dir, st)
1736
+ res.end(JSON.stringify({ ok: true, id, name, manual: !sid }))
1737
+ },
1738
+ }),
1739
+ )
1740
+
1741
+ // 把手里的书签直接接到「全机读得最远」那一步(他自己的分片,不影响别人)
1742
+ ctx.effect(() =>
1743
+ ctx.webServer.register({
1744
+ auth: sameSiteAuth,
1745
+ kind: 'exact',
1746
+ path: '/dsh-reading.adopt',
1747
+ async handler(req, res) {
1748
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1749
+ const url = new URL(req.url, 'http://x')
1750
+ const { dir, st } = await stateOf()
1751
+ migrateReaders(st)
1752
+ const id = url.searchParams.get('book') || st.current
1753
+ if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1754
+ const reader = readerParam(st, url)
1755
+ const far = furthestOf(st, id)
1756
+ if (!far) return res.end(JSON.stringify({ ok: false, error: '这本书还没有任何进度' }))
1757
+ const own = readerBook(st, reader.id, id)
1758
+ own.readThrough = far
1759
+ own.next = far + 1
1760
+ own.lastReadAt = new Date().toISOString()
1761
+ st.books[id].readThrough = Math.max(Number(st.books[id].readThrough) || 0, far)
1762
+ st.books[id].next = Math.min(Number(st.books[id].chapters) || Infinity, far + 1)
1763
+ furthestOf(st, id)
1764
+ await saveState(dir, st)
1765
+ res.end(JSON.stringify({ ok: true, reader: reader.name, book: id, readThrough: far, next: far + 1 }))
1766
+ },
1767
+ }),
1768
+ )
1769
+
916
1770
  // 把某本设为「正在读」
917
1771
  ctx.effect(() =>
918
1772
  ctx.webServer.register({
@@ -921,11 +1775,23 @@ export function apply(ctx, rawConfig) {
921
1775
  path: '/dsh-reading.setCurrent',
922
1776
  async handler(req, res) {
923
1777
  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) }
1778
+ // id 既可能来自 ?id=(老调用),也可能来自 POST 的 JSON body(面板点书名走这条)
1779
+ let id = url.searchParams.get('id') || ''
1780
+ if (!id) {
1781
+ let body = ''
1782
+ for await (const c of req) body += c
1783
+ try { id = String((JSON.parse(body || '{}') || {}).id || '') } catch {}
1784
+ }
1785
+ const { dir, st, shelf } = await stateOf()
1786
+ // 书架上的书不一定在 state.books 里(没读过就没条目),这里按书架兜底
1787
+ const onShelf = (shelf || []).find((b) => b && b.id === id)
1788
+ if (onShelf && !st.books[id]) {
1789
+ st.books[id] = { id, title: onShelf.id, file: onShelf.file, chapters: onShelf.chapters || 0, readThrough: 0, next: 1, lastReadAt: '' }
1790
+ }
1791
+ const exists = Boolean(st.books[id])
1792
+ if (exists) { st.current = id; await saveState(dir, st) }
927
1793
  res.setHeader('content-type', 'application/json; charset=utf-8')
928
- res.end(JSON.stringify({ ok: !!st.books[id], current: st.current }))
1794
+ res.end(JSON.stringify({ ok: exists, current: st.current }))
929
1795
  },
930
1796
  }),
931
1797
  )
@@ -944,8 +1810,9 @@ export function apply(ctx, rawConfig) {
944
1810
  res.setHeader('content-type', 'application/json; charset=utf-8')
945
1811
  try {
946
1812
  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)
1813
+ const reader = readerParam(st, url)
1814
+ const mine = readerBookRead(st, reader.id, id)
1815
+ const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (mine.readThrough || 1)
949
1816
  res.end(JSON.stringify({
950
1817
  ok: true, book: id, chapter: ch, total: info.chapters.length,
951
1818
  title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
@@ -967,20 +1834,24 @@ export function apply(ctx, rawConfig) {
967
1834
  const url = new URL(req.url, 'http://x')
968
1835
  const { dir, st, perDay, readToday: rt } = await stateOf()
969
1836
  const id = url.searchParams.get('book') || st.current
970
- const rec = st.books[id]
971
1837
  res.setHeader('content-type', 'application/json; charset=utf-8')
972
- if (!rec) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1838
+ if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1839
+ const reader = readerParam(st, url)
1840
+ const own = readerBook(st, reader.id, id)
1841
+ // 面板上点「从头读」:先把这份分片归零,再按一张张推进的方式读第 1 章
1842
+ if (url.searchParams.get('start') === '1') { own.readThrough = 0; own.next = 1 }
973
1843
  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()
1844
+ const n = Math.min(info.chapters.length, (own.readThrough || 0) + 1)
1845
+ own.readThrough = n
1846
+ own.next = Math.min(info.chapters.length, n + 1)
1847
+ own.lastReadAt = new Date().toISOString()
1848
+ st.books[id].readThrough = Math.max(Number(st.books[id].readThrough) || 0, n)
1849
+ st.books[id].next = Math.min(info.chapters.length, st.books[id].readThrough + 1)
1850
+ furthestOf(st, id)
978
1851
  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
1852
+ bumpLog(st, t, id, reader.id, 1)
982
1853
  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) }))
1854
+ 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
1855
  },
985
1856
  }),
986
1857
  )
@@ -995,21 +1866,22 @@ export function apply(ctx, rawConfig) {
995
1866
  const url = new URL(req.url, 'http://x')
996
1867
  const { dir, st } = await stateOf()
997
1868
  const id = url.searchParams.get('book') || st.current
998
- const rec = st.books[id]
999
1869
  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
1870
+ if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
1871
+ const reader = readerParam(st, url)
1872
+ const own = readerBook(st, reader.id, id)
1873
+ const cur = Number(own.readThrough) || 0
1002
1874
  if (cur <= 1) return res.end(JSON.stringify({ ok: false, error: '已经在第 1 章了,退不动' }))
1003
1875
  const n = cur - 1
1004
- rec.readThrough = n
1005
- rec.next = n + 1
1006
- rec.lastReadAt = new Date().toISOString()
1007
- // 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高
1876
+ own.readThrough = n
1877
+ own.next = n + 1
1878
+ own.lastReadAt = new Date().toISOString()
1879
+ // 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高(全局与这位读者各退一格)
1008
1880
  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
1881
+ bumpLog(st, t, id, reader.id, -1)
1010
1882
  await saveState(dir, st)
1011
1883
  const info = await bookInfo(dir, id)
1012
- res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length }))
1884
+ res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, reader: reader.id }))
1013
1885
  },
1014
1886
  }),
1015
1887
  )
@@ -1298,17 +2170,69 @@ async function signWork(rel, who) {
1298
2170
  let st = {}
1299
2171
  try { st = JSON.parse(stripBom(await readFile(join(dir, 'state.json'), 'utf8'))) || {} } catch {}
1300
2172
  const now = Date.now()
2173
+ migrateReaders(st)
2174
+ // 近况跟读者走:?reader=<rid> 给了就只报这位读者翻过的;给的是总进度就按书拆成「谁读到哪」
2175
+ let wanted = ''
2176
+ try { wanted = new URL(req.url, 'http://x').searchParams.get('reader') || '' } catch {}
2177
+ const readers = (st.readers && typeof st.readers === 'object') ? st.readers : {}
2178
+ const readerId = wanted && readers[wanted] ? wanted : ''
2179
+ const readerName = readerId ? (readers[readerId].name || readerId) : ''
2180
+ const perReader = []
2181
+ if (readerId) {
2182
+ if (readerId === LEGACY_READER) {
2183
+ for (const [rid, shard] of Object.entries(readers)) {
2184
+ if (rid === LEGACY_READER) continue
2185
+ const rb = (shard.books && shard.books[st.current]) || null
2186
+ if (!rb || !(Number(rb.readThrough) > 0)) continue
2187
+ perReader.push({ id: rid, name: shard.name || rid, readThrough: Number(rb.readThrough) || 0, lastReadAt: rb.lastReadAt || '' })
2188
+ }
2189
+ perReader.sort((a, b) => b.readThrough - a.readThrough)
2190
+ } else {
2191
+ const shard = readers[readerId]
2192
+ for (const [bid, rb] of Object.entries(shard.books || {})) {
2193
+ if (!(Number(rb.readThrough) > 0)) continue
2194
+ const bk = (st.books && st.books[bid]) || {}
2195
+ perReader.push({ id: bid, name: bk.title || bid, readThrough: Number(rb.readThrough) || 0, chapters: Number(bk.chapters) || 0, lastReadAt: rb.lastReadAt || '' })
2196
+ }
2197
+ perReader.sort((a, b) => String(b.lastReadAt).localeCompare(String(a.lastReadAt)))
2198
+ }
2199
+ }
1301
2200
  const key = (t) => {
1302
2201
  const d = new Date(t)
1303
2202
  return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10)
1304
2203
  }
1305
2204
  const today = key(now)
1306
- const log = st.log || {}
2205
+ // 给了读者就按读者的 rlog 记账;没给就还是全机 log
2206
+ let log = st.log || {}
2207
+ if (readerId) {
2208
+ const rl = st.rlog || {}
2209
+ log = {}
2210
+ for (const [k, byRid] of Object.entries(rl)) {
2211
+ const row = byRid && byRid[readerId]
2212
+ if (row) log[k] = row
2213
+ }
2214
+ }
1307
2215
  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
2216
+ // 近况说的是「这位读者最近在干什么」,不是面板上停在哪本:
2217
+ // 先找他最近读过的那本,找不到才用面板当前这本
2218
+ let focusId = st.current
2219
+ try {
2220
+ const lb = lastReadBookOf(st, readerId || LEGACY_READER)
2221
+ if (lb && st.books && st.books[lb]) focusId = lb
2222
+ } catch {}
2223
+ const focusRec = (st.books && st.books[focusId]) || null
2224
+ const ownShard = readerId && readerId !== LEGACY_READER ? readerBookRead(st, readerId, focusId) : null
2225
+ const view = ownShard || focusRec
2226
+ const todayCh = (log[today] && log[today][focusId]) || 0
2227
+ const lastRead = view && view.lastReadAt ? Date.parse(view.lastReadAt) : 0
1310
2228
  const hoursAgo = lastRead ? Math.max(0, Math.round((now - lastRead) / 3600000)) : -1
1311
2229
 
2230
+ let lastDay = ''
2231
+ if (readerId) {
2232
+ const rl = st.rlog || {}
2233
+ for (const k of Object.keys(rl).sort()) { if (rl[k] && rl[k][readerId]) lastDay = k }
2234
+ }
2235
+
1312
2236
  const days = []
1313
2237
  for (let i = 0; i < 7; i++) {
1314
2238
  const k = key(now - i * 86400000)
@@ -1339,20 +2263,25 @@ async function signWork(rel, who) {
1339
2263
  const top = works[0] || null
1340
2264
 
1341
2265
  let status = ''
1342
- if (todayCh > 0) status = '今天在《' + (st.current || '') + '》翻了 ' + todayCh + ' 章,读到第 ' + ((cur && cur.readThrough) || 0) + ' 章。'
2266
+ if (todayCh > 0) {
2267
+ const rawTitle = String((focusRec && focusRec.title) || focusId || '')
2268
+ const shownTitle = /^《/.test(rawTitle) ? rawTitle : '《' + rawTitle + '》'
2269
+ status = '今天在' + shownTitle + '翻了 ' + todayCh + ' 章,读到第 ' + ((view && view.readThrough) || 0) + ' 章。'
2270
+ }
1343
2271
  else if (hoursAgo >= 0 && hoursAgo <= 48) status = '上次翻书是 ' + hoursAgo + ' 小时前。'
1344
2272
  else if (hoursAgo > 48) status = '这两天没翻书。'
2273
+ else if (lastDay) status = '上次翻书是 ' + lastDay + '。'
1345
2274
  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 + '》。'
2275
+ if (top.days === 0) status += '今天有更新:《' + top.name + '》。'
2276
+ else if (top.days === 1) status += '昨天有更新:《' + top.name + '》。'
2277
+ else status += '上次更新是 ' + top.days + ' 天前的《' + top.name + '》。'
1349
2278
  }
1350
2279
  let mood = ''
1351
2280
  if (todayCh >= 12) mood = '翻书翻得犯困'
1352
2281
  else if (todayCh > 0) mood = works.some((w) => w.days === 0) ? '手痒,想写点东西' : '平静'
1353
2282
  else if (hoursAgo < 0 || hoursAgo > 48) mood = '有点闷'
1354
2283
  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) }))
2284
+ 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
2285
  } catch (e) {
1357
2286
  res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
1358
2287
  }
@@ -1495,7 +2424,9 @@ async function signWork(rel, who) {
1495
2424
  '· 读后感不必一章一条:每读五六章写一段就够,标题会自动变成「第 23–27 章」;几千章的书也不会攒成几千条。',
1496
2425
  '· 写读后感必须带 by(比如「鹿野」或你所在对话的名字);不带会被拒绝。面板每条下面会标出是谁写的——同一台机器上可能有好几个你,别让它们分不清。',
1497
2426
  '· 写自己的作品也一样署名:文件开头写一行 `by: 你的名字`(或写完调 reading_sign);没署名的在面板上会标「未署名」。',
1498
- '· 书和进度是这台机器共用的(一个家一个书房),不分谁在读;只有读后感会标署名。',
2427
+ '· 书是同一架,进度按读者分开:每条会话各有一份「读到哪」,互不踩;书上另记一个「全机读得最远」,面板里能看到谁读到哪。',
2428
+ '· 接着读:默认接你自己的位置;你还没读过这本书,就接全机读得最远的地方。想从别处起就传 chapter 指定章号。',
2429
+ '· 读哪一本由你决定,不由面板决定:面板上他选的「当前这本」只是他想看哪本,不会改变你读哪本;只有他明确说「你去读某一本」,才按他说的读。',
1499
2430
  '· 装好之后可以问主人一次:要不要定个固定的读书时间;别自己偷偷建定时任务,也别反复问。',
1500
2431
  ].join('\n')
1501
2432
 
@@ -1537,11 +2468,13 @@ async function signWork(rel, who) {
1537
2468
  + '想知道「我现在读到哪、还能读几章」就用它。',
1538
2469
  parameters: obj(),
1539
2470
  output: textOut,
1540
- async execute() {
2471
+ async execute(args, exec) {
1541
2472
  const { dir, perDay, st, shelf, readToday: rt, today: t } = await stateOf()
2473
+ const reader = await readerOf(exec)
1542
2474
  const books = []
1543
2475
  for (const b of shelf) {
1544
2476
  const r = st.books[b.id] || {}
2477
+ const mine = readerBookRead(st, reader.id, b.id)
1545
2478
  let chapters = r.chapters || 0
1546
2479
  if (!chapters) {
1547
2480
  try {
@@ -1549,10 +2482,19 @@ async function signWork(rel, who) {
1549
2482
  chapters = (toc && toc.chapters && toc.chapters.length) || 0
1550
2483
  } catch {}
1551
2484
  }
1552
- books.push({ id: b.id, chapters, readThrough: r.readThrough || 0, next: r.next || 1, lastReadAt: r.lastReadAt || '' })
2485
+ books.push({
2486
+ id: b.id,
2487
+ chapters,
2488
+ readThrough: mine.readThrough,
2489
+ next: mine.next || 1,
2490
+ furthest: furthestOf(st, b.id),
2491
+ furthestReader: furthestReaderOf(st, b.id),
2492
+ lastReadAt: mine.lastReadAt || '',
2493
+ })
1553
2494
  }
1554
2495
  return {
1555
2496
  dir,
2497
+ reader: reader.name,
1556
2498
  today: t,
1557
2499
  perDay,
1558
2500
  readToday: rt,
@@ -1573,33 +2515,45 @@ async function signWork(rel, who) {
1573
2515
  + '超过每日上限时会提示,但仍允许读(上限是提醒不是锁)。'
1574
2516
  + '配置了静音时段时,这段时间内会被拒绝;真要读就传 force: true。',
1575
2517
  parameters: obj({
1576
- book: { type: 'string', description: '书名 id(不填=当前正在读的那本)' },
2518
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本;都没读过就用书架当前那本,跟 reading_note 一致)' },
1577
2519
  chapter: { type: 'number', description: '第几章(不填=接着上次的下一章)' },
1578
2520
  force: { type: 'boolean', description: '静音时段内仍然要读,传 true(默认 false)' },
2521
+ from: { type: 'string', enum: ['me', 'book', 'start'], description: '不填 chapter 时从哪接着读:me=我上次的位置(默认)、book=这本书全机读得最远的地方、start=从头(第 1 章)' },
1579
2522
  }),
1580
2523
  output: textOut,
1581
- async execute(args) {
2524
+ async execute(args, exec) {
1582
2525
  if (args?.force !== true) {
1583
2526
  const q = inQuietNow(await config())
1584
2527
  if (q) throw new Error(`静音时段(${q.fromText}–${q.toText}),不自动读。真要读请传 force: true`)
1585
2528
  }
1586
2529
  const { dir, perDay, st, readToday: rt } = await stateOf()
1587
- const id = args?.book || st.current
1588
- if (!id) throw new Error('书架是空的:先用 reading_import 导入一本 txt')
2530
+ const reader = await readerOf(exec)
2531
+ // 取书口径跟 reading_note 一致:明说 > 我自己刚读的那本 > 全局当前那本
2532
+ const id = args?.book || lastReadBookOf(st, reader.id)
2533
+ if (!id) throw new Error('不知道读哪本:传 book,或先读过一本')
1589
2534
  const info = await bookInfo(dir, id)
1590
2535
  const rec = st.books[id] || (st.books[id] = { id, title: id, chapters: info.chapters.length, readThrough: 0, next: 1 })
1591
2536
  rec.chapters = info.chapters.length
1592
- const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
2537
+ const own = readerBook(st, reader.id, id)
2538
+ // from:"start" = 明说从头读:先把自己这份归零,否则下面 max(mine, n) 会把它顶回书级进度(测试鱼 2026-11-27 测出来的)
2539
+ if (args?.from === 'start') { own.readThrough = 0; own.next = 1 }
2540
+ // 默认接着「我自己」上次的位置;我还没读过这本书就接书级的 next(换窗口能接着读)
2541
+ const mine = Number(own.readThrough) || 0
2542
+ // start=明说从头读;否则接着我自己,我没读过就接书级 next
2543
+ const startAt = args?.from === 'start' ? 1 : (args?.from === 'book' || !mine ? (rec.next || 1) : (own.next || mine + 1))
2544
+ const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : startAt
1593
2545
  if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
1594
2546
  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
2547
+ own.readThrough = Math.max(mine, n)
2548
+ own.next = Math.min(info.chapters.length, own.readThrough + 1)
2549
+ own.lastReadAt = new Date().toISOString()
2550
+ rec.readThrough = Math.max(Number(rec.readThrough) || 0, n)
2551
+ rec.next = Math.min(info.chapters.length, rec.readThrough + 1)
2552
+ rec.lastReadAt = own.lastReadAt
2553
+ furthestOf(st, id)
2554
+ // 读书不动「面板上正在显示的那本」:current 只在用户手动选书时改(2026-11-27)
1599
2555
  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
2556
+ bumpLog(st, t, id, reader.id, 1)
1603
2557
  await saveState(dir, st)
1604
2558
  return {
1605
2559
  book: id,
@@ -1608,7 +2562,10 @@ async function signWork(rel, who) {
1608
2562
  chapters: info.chapters.length,
1609
2563
  tocPath: info.tocPath || '',
1610
2564
  chars: body.length,
1611
- next: rec.next,
2565
+ next: own.next,
2566
+ reader: reader.name,
2567
+ readThrough: own.readThrough,
2568
+ furthest: rec.furthest || own.readThrough,
1612
2569
  perDay,
1613
2570
  readToday: rt + 1,
1614
2571
  left: Math.max(0, perDay - rt - 1),
@@ -1626,14 +2583,17 @@ async function signWork(rel, who) {
1626
2583
  + '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
1627
2584
  + '已读到只进不退(跳读可以,回退不会把进度改小)。',
1628
2585
  parameters: obj({
1629
- book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主、古文观止' },
2586
+ book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主(不填=我刚读过的那本)' },
1630
2587
  chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
1631
2588
  todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
1632
2589
  }),
1633
2590
  output: textOut,
1634
- async execute(args) {
2591
+ async execute(args, exec) {
1635
2592
  const { dir, st, shelf } = await stateOf()
1636
- const id = resolveBookId(st, shelf, args?.book)
2593
+ const reader = await readerOf(exec)
2594
+ const wanted = args?.book || lastReadBookOf(st, reader.id)
2595
+ if (!wanted) throw new Error('不知道记哪本:传 book,或先读过一本')
2596
+ const id = resolveBookId(st, shelf, wanted)
1637
2597
  // 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
1638
2598
  const toc = await readTocOnly(dir, id)
1639
2599
  const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
@@ -1643,16 +2603,19 @@ async function signWork(rel, who) {
1643
2603
  const incRaw = Math.floor(Number(args?.todayCount))
1644
2604
  const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
1645
2605
  const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
1646
- const before = Number(rec.readThrough) || 0
2606
+ const own = readerBook(st, reader.id, id)
2607
+ const before = Number(own.readThrough) || 0
1647
2608
  if (chapters) rec.chapters = chapters
1648
- rec.readThrough = Math.max(before, n)
2609
+ own.readThrough = Math.max(before, n)
2610
+ own.next = chapters ? Math.min(chapters, own.readThrough + 1) : own.readThrough + 1
2611
+ own.lastReadAt = new Date().toISOString()
2612
+ rec.readThrough = Math.max(Number(rec.readThrough) || 0, own.readThrough)
1649
2613
  rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
1650
- rec.lastReadAt = new Date().toISOString()
1651
- st.current = id
2614
+ rec.lastReadAt = own.lastReadAt
2615
+ furthestOf(st, id)
2616
+ // 读书不动「面板上正在显示的那本」:current 只在用户手动选书时改(2026-11-27)
1652
2617
  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
2618
+ bumpLog(st, t, id, reader.id, inc)
1656
2619
  await saveState(dir, st)
1657
2620
  const todayCount = Number(st.log[t][id]) || 0
1658
2621
  // textOut 的 schema 是 object,必须返回对象(以前返回字符串,工具报 "value" must be an object)
@@ -1661,11 +2624,13 @@ async function signWork(rel, who) {
1661
2624
  book: rec.title || id,
1662
2625
  id,
1663
2626
  before,
1664
- readThrough: rec.readThrough,
1665
- next: rec.next,
2627
+ readThrough: own.readThrough,
2628
+ next: own.next,
1666
2629
  chapters: chapters || null,
1667
2630
  today: todayCount,
1668
- text: `ok readThrough ${before} -> ${rec.readThrough} next ${rec.next} today ${todayCount}`,
2631
+ reader: reader.name,
2632
+ furthest: rec.furthest || own.readThrough,
2633
+ text: `ok readThrough ${before} -> ${own.readThrough} next ${own.next} today ${todayCount}`,
1669
2634
  }
1670
2635
  },
1671
2636
  }),
@@ -1679,20 +2644,24 @@ async function signWork(rel, who) {
1679
2644
  + '默认按「上次写到哪 → 这次读到哪」自动起标题(如「第 23–27 章」),不必一章一条。'
1680
2645
  + '只记真的打动你的:一句话的判断、一个比喻、一处想不通。这不是交作业,想不出就不写。',
1681
2646
  parameters: obj({
1682
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
2647
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
1683
2648
  chapter: { type: 'string', description: '标题(不填=自动用「第 A–B 章」,A 是上次写到的下一章)' },
1684
2649
  lines: { type: 'array', items: { type: 'string' }, description: '一到三条,每条一句,短。' },
1685
- by: { type: 'string', description: '谁写的(必填,比如「鹿野」或你所在对话的名字)' },
2650
+ by: { type: 'string', description: '谁写的(必填,写你自己那个名字,比如「鹿野」「鹿野(DSH)」)' },
1686
2651
  }),
1687
2652
  output: textOut,
1688
- async execute(args) {
2653
+ async execute(args, exec) {
1689
2654
  const { dir, st } = await stateOf()
1690
- const id = args?.book || st.current
1691
- if (!id) throw new Error('还没有正在读的书')
2655
+ const reader = await readerOf(exec)
2656
+ // 不填 book 时落到「我自己最后读过的那本」;别再拿全局 st.current——
2657
+ // 别人/别的窗口一读就把 current 改走了,读后感会落错书(2026-11-27 主对话测出来的)
2658
+ const id = args?.book || lastReadBookOf(st, reader.id)
2659
+ if (!id) throw new Error('不知道读哪本:传 book,或先读过一本')
1692
2660
  const rec = st.books[id] || {}
1693
2661
  const info = await bookInfo(dir, id)
1694
- const end = Number(rec.readThrough) || 0
1695
- const from = Number(rec.noteUntil) || 0
2662
+ const own = readerBook(st, reader.id, id)
2663
+ const end = Number(own.readThrough) || 0
2664
+ const from = Number(own.noteUntil) || 0
1696
2665
  // 默认按「一段」写:上次写到第 X 章,这次写到读到的地方,标题用「第 A–B 章」
1697
2666
  const autoTitle = (from < end)
1698
2667
  ? (from + 1 === end ? `第 ${end} 章` : `第 ${from + 1}–${end} 章`)
@@ -1702,14 +2671,15 @@ async function signWork(rel, who) {
1702
2671
  if (!lines.length) throw new Error('lines 不能为空')
1703
2672
  const who = String(args?.by || '').trim()
1704
2673
  if (!who) {
1705
- throw new Error('写读后感必须带 by(谁写的),比如 by: "鹿野";这不是流程,是为了让别人知道这句是谁读出来的。')
2674
+ throw new Error(`写读后感必须带 by(谁写的),比如 by: "${reader.name}";这不是流程,是为了让别人知道这句是谁读出来的。`)
1706
2675
  }
1707
2676
  const p = await appendNote(dir, rec.title || id, chTitle, lines, who)
1708
2677
  if (end) {
1709
- st.books[id] = { ...rec, noteUntil: end }
2678
+ own.noteUntil = end
2679
+ rec.noteUntil = Math.max(Number(rec.noteUntil) || 0, end)
1710
2680
  await saveState(dir, st)
1711
2681
  }
1712
- return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length }
2682
+ return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length, reader: reader.name }
1713
2683
  },
1714
2684
  }),
1715
2685
  )
@@ -1740,17 +2710,18 @@ async function signWork(rel, who) {
1740
2710
  '在书里搜一个词或名字,返回它出现在第几章、那一行原文。想找“这句话在哪”“这个人第几章出场”时用它,比一页页翻省得多。',
1741
2711
  parameters: obj({
1742
2712
  query: { type: 'string', description: '要搜的词(人名、地名、一句话都行)' },
1743
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
2713
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
1744
2714
  limit: { type: 'number', description: '最多几条,默认 8' },
1745
2715
  }),
1746
2716
  output: textOut,
1747
- async execute(args) {
2717
+ async execute(args, exec) {
1748
2718
  const q = String(args?.query || '').trim()
1749
2719
  if (!q) throw new Error('需要 query')
1750
2720
  const limit = Math.max(1, Math.min(30, Number(args?.limit) || 8))
1751
2721
  const { dir, st } = await stateOf()
1752
- const id = args?.book || st.current
1753
- if (!id) throw new Error('还没有正在读的书')
2722
+ const reader = await readerOf(exec)
2723
+ const id = args?.book || lastReadBookOf(st, reader.id)
2724
+ if (!id) throw new Error('不知道搜哪本:传 book,或先读过一本')
1754
2725
  const { text, chapters } = await fullTextOf(dir, id)
1755
2726
  const hits = []
1756
2727
  let at = text.indexOf(q)
@@ -1784,16 +2755,18 @@ async function signWork(rel, who) {
1784
2755
  description:
1785
2756
  '把这本书已读的部分压成一页:读到第几章、读过哪些章名、每章自己写了几条批注。上一句“我读到哪了、想过什么”说不清时用它。',
1786
2757
  parameters: obj({
1787
- book: { type: 'string', description: '书名 id(不填=当前这本)' },
2758
+ book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
1788
2759
  }),
1789
2760
  output: textOut,
1790
- async execute(args) {
2761
+ async execute(args, exec) {
1791
2762
  const { dir, st } = await stateOf()
1792
- const id = args?.book || st.current
1793
- if (!id) throw new Error('还没有正在读的书')
2763
+ const reader = await readerOf(exec)
2764
+ const id = args?.book || lastReadBookOf(st, reader.id)
2765
+ if (!id) throw new Error('不知道看哪本:传 book,或先读过一本')
1794
2766
  const rec = st.books[id] || {}
1795
2767
  const info = await bookInfo(dir, id)
1796
- const n = Number(rec.readThrough) || 0
2768
+ const mine = readerBookRead(st, reader.id, id)
2769
+ const n = Number(mine.readThrough) || 0
1797
2770
  const titles = info.chapters.slice(0, n).map((c, i) => ({ n: i + 1, title: c.title }))
1798
2771
  const notes = {}
1799
2772
  try {
@@ -1809,7 +2782,9 @@ async function signWork(rel, who) {
1809
2782
  ok: true,
1810
2783
  book: id,
1811
2784
  title: rec.title || id,
2785
+ reader: reader.name,
1812
2786
  readThrough: n,
2787
+ furthest: furthestOf(st, id),
1813
2788
  total: info.chapters.length,
1814
2789
  next: n + 1,
1815
2790
  titles,
@@ -1818,4 +2793,4 @@ async function signWork(rel, who) {
1818
2793
  },
1819
2794
  }),
1820
2795
  )
1821
- }
2796
+ }