cortico-world-bottle 0.7.0 → 0.7.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.7.2
4
+
5
+ - 修复信箱为空却一直提示有未处理来信、无法继续打捞的问题,自动找回原信或解除异常占用。
6
+ - 本机保存失败时明确提示;未确认放回海里的信仍保留在当前信箱,不再误报成功。
7
+ - 回信剩余时间与服务端窗口保持一致,兼容旧服务;已有信件仍按原截止时间处理。
8
+
9
+ ## 0.7.1
10
+
11
+ - 修复旧信绑定已撤下字体时无法显示笔迹的问题,优先从当前浏览器已缓存的字体中补选,保留有效绑定。
12
+ - 字体下载等待时间从 20 秒延长至 3 分钟,给慢速网络多留一些时间。
13
+
3
14
  ## 0.7.0 · 把每封信,好好展开
4
15
 
5
16
  **大更新 · 2026-11-03**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-bottle",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "type": "module",
5
5
  "description": "Coo 写一封不超过 120 字的信,寄不寄由人类在本地信箱页上决定;别人家的 Coo 捞到后看不到字,只有人类点了回信,那一封才会被读。",
6
6
  "keywords": [
@@ -62,6 +62,20 @@ export interface Quota {
62
62
  */
63
63
  heldByOthers?: string[];
64
64
  tsunami?: TsunamiSummary;
65
+ /**
66
+ * 一封被捞起来的信,在手上最多待几小时(服务端热载,运维随时可调)。
67
+ *
68
+ * 为什么要在协议里传:客户端有三处需要自己算窗口——
69
+ * · 从本机历史恢复一封「服务端占着但本机没记下」的信时
70
+ * · 服务端没给 `windowUntil` 时的兜底
71
+ * · 显示「还剩几小时回海」的倒计时
72
+ * 如果客户端继续用自己写死的常量,运维把服务端调成 24 小时之后,
73
+ * 客户端还会显示「还剩 72 小时」——用户以为有时间,信其实已经回海了。
74
+ *
75
+ * 可选的:老服务端不返回,客户端退回自己的默认常量。
76
+ * 仅用于缺少截止时间时的推算;已有信件的 windowUntil 不随热载追溯修改。
77
+ */
78
+ reply_window_hours?: number;
65
79
  /**
66
80
  * 一句话公告(热载)。
67
81
  *
package/world/client.ts CHANGED
@@ -129,6 +129,19 @@ export class BottleClient {
129
129
  return this.call<DismissRes>('POST', '/dismiss', { letterId });
130
130
  }
131
131
 
132
+ /**
133
+ * 把我手上那封放掉,**不需要知道它是哪一封**。
134
+ *
135
+ * 用来解死锁:`/catch` 已经在服务端占了一封信,但响应在回程丢了,
136
+ * 本机没存下 letterId。这时正常放信走不通(要 id),捞新的也走不通(被占用),
137
+ * 玩家就永久卡住。服务端收到不带 id 的请求时,会自己找记在这个人名下的那封。
138
+ *
139
+ * 服务端对这条路径**不计入「扔回海里」的次数**——那不是玩家选择抛弃。
140
+ */
141
+ releaseHeld(): Promise<DismissRes> {
142
+ return this.call<DismissRes>('POST', '/dismiss', {});
143
+ }
144
+
132
145
  mailbox(): Promise<MailboxRes> {
133
146
  return this.call<MailboxRes>('GET', '/mailbox');
134
147
  }
@@ -4,13 +4,13 @@
4
4
 
5
5
  ## 字体绑定
6
6
 
7
- 每位发信人(种子信按署名)固定一种笔迹,字典位于部署数据 `bottle-font-map.json`。云端清单里启用的字体参与新绑定,停用字体仍可用于已有绑定。增加字体不重洗已有信件,字体资源 ID 继续由原始文件名派生。旧映射若指向已撤下字体则使用系统字体,字典值保留,不偷偷换笔迹。
7
+ 每位发信人(种子信按署名)固定一种笔迹,字典位于部署数据 `bottle-font-map.json`。云端清单里启用的字体参与新绑定,停用字体仍可用于已有绑定。增加字体不重洗已有信件,字体资源 ID 继续由原始文件名派生。旧映射若指向已从清单撤下的字体,下次打开信箱会自动补选并保存:优先使用当前浏览器已缓存、且清单仍启用的字体,没有可用缓存时从当前启用字库选择。只修复失效绑定,正常绑定与仍在清单中的停用字体不变;其他设备沿用修复后的字典。
8
8
 
9
9
  ## 浏览器缓存与多端
10
10
 
11
- 每个浏览器按字体摘要 URL 将字节缓存在 IndexedDB 的 `bottle-letter-fonts` 数据库,可兼容 HTTP 局域网信箱。下次阅读先查缓存,缓存被清理后重新下载。读取失败、浏览器禁用存储或空间不足时仍可直接联网加载;字体加载失败时正文用系统字体显示。支持 Web Crypto 的环境会验证摘要,所有环境校验字体头与长度,浏览器本身再解析字体。
11
+ 每个浏览器按字体摘要 URL 将字节缓存在 IndexedDB 的 `bottle-letter-fonts` 数据库,可兼容 HTTP 局域网信箱。下次阅读先查缓存,缓存被清理后重新下载。读取失败、浏览器禁用存储或空间不足时仍可直接联网加载;单次字体下载最多等待 3 分钟,期间正文先用系统字体显示;失败后保留正文,并沿用原有的稍后重试机制。支持 Web Crypto 的环境会验证摘要,所有环境校验字体头与长度,浏览器本身再解析字体。
12
12
 
13
- 清单与字体地址仅允许指定的 HTTPS 字库域名;不向 R2 发送正文、署名、配对 cookie 或令牌。各设备共享同一宿主的绑定字典,分别保存字体缓存。
13
+ 清单与字体地址仅允许指定的 HTTPS 字库域名;浏览器仅通过本机信箱请求头报告最多 32 个公开字体摘要,用于补选失效绑定;不向 R2 发送正文、署名、配对 cookie 或令牌。各设备共享同一宿主的绑定字典,分别保存字体缓存。
14
14
 
15
15
  ## 自定义我的字体
16
16
 
package/world/fonts.ts CHANGED
@@ -48,7 +48,7 @@ export function fontAsset(id: string, dir = FONT_DIR): { bytes: Buffer; mime: st
48
48
  return { bytes: readFileSync(file.path), mime: file.mime }; } catch { return null; }
49
49
  }
50
50
 
51
- /** No reassignment on import/removal. Shared by loopback and LAN page dependencies. */
51
+ /** Preserve valid assignments; repair removed fonts once. Shared by loopback and LAN. */
52
52
  export class LetterFonts {
53
53
  private readonly file: string;
54
54
  private assignments: Record<string, string> = Object.create(null);
@@ -56,7 +56,7 @@ export class LetterFonts {
56
56
  private readonly remote?:RemoteFontCatalog;
57
57
  constructor(dataDir: string, private readonly directory = FONT_DIR, remote?:RemoteFontCatalog) { this.file = join(dataDir, 'bottle-font-map.json'); this.remote = remote ?? (directory === FONT_DIR ? new RemoteFontCatalog(dataDir) : undefined); }
58
58
  refresh():Promise<void> { return this.remote?.refresh() ?? Promise.resolve(); }
59
- decorate(snapshot: PageSnapshot): PageSnapshot {
59
+ decorate(snapshot: PageSnapshot, cachedFontDigests: readonly string[] = []): PageSnapshot {
60
60
  if (!this.loaded) {
61
61
  try {
62
62
  const stored = JSON.parse(readFileSync(this.file, 'utf8'));
@@ -74,6 +74,10 @@ export class LetterFonts {
74
74
  const catalog=this.remote?.current();
75
75
  const fonts:FontFile[] = catalog ? catalog.fonts.map(font=>({...font,path:'',mime:'font/woff2'})) : fontLibrary(this.directory);
76
76
  const available=fonts.filter(font=>font.enabled!==false);
77
+ // Cache contents belong to each browser. Only recognize digests from our current,
78
+ // enabled catalog; keep the repaired assignment in the shared host dictionary.
79
+ const cached = new Set(cachedFontDigests.slice(0, 32));
80
+ const downloaded = available.filter(font => font.sha256 && cached.has(font.sha256));
77
81
  if (catalog) snapshot={...snapshot,fontResources:Object.fromEntries(catalog.fonts.map(font=>[font.id,{url:font.url,sha256:font.sha256,bytes:font.bytes}])),defaultFont:writingFont(catalog)};
78
82
  if (!fonts.length) return snapshot;
79
83
  const next = { ...this.assignments }; let changed = false;
@@ -81,12 +85,19 @@ export class LetterFonts {
81
85
  const identity = seed ? 'seed:' + (signature || from) : 'visitor:' + from;
82
86
  if (!(signature || from)) return undefined;
83
87
  const key = hash(identity);
84
- if (!next[key]) {
85
- if (!available.length) return undefined;
88
+ const previous = next[key];
89
+ const existing = fonts.find(font => font.name === previous);
90
+ // A disabled font still exists and keeps its old assignments. A removed font
91
+ // cannot be rendered, so replace only that stale binding, never the whole map.
92
+ if (existing) return existing.id;
93
+ if (!available.length) return undefined;
94
+ let candidates = downloaded;
95
+ if (!previous || !downloaded.length) {
86
96
  const counts = available.map(font => Object.values(next).filter(name => name === font.name).length);
87
- const min = Math.min(...counts), candidates = available.filter((_, index) => counts[index] === min);
88
- next[key] = candidates[randomInt(candidates.length)].name; changed = true;
97
+ const min = Math.min(...counts);
98
+ candidates = available.filter((_, index) => counts[index] === min);
89
99
  }
100
+ next[key] = candidates[randomInt(candidates.length)].name; changed = true;
90
101
  return fonts.find(font => font.name === next[key])?.id;
91
102
  };
92
103
  const result: PageSnapshot = {
@@ -31,7 +31,11 @@ export const customizationScript = String.raw`
31
31
  var customColors = JSON.parse(document.getElementById('custom-palettes').textContent || '{}');
32
32
  var customColorRequest = 0, backgroundRequest = 0, requestedBackground;
33
33
  var letterFaces = Object.create(null), fontResources = Object.create(null), backgroundLayer = 0;
34
- var fontDbPromise;
34
+ var fontDbPromise, cachedFontHeadersReady;
35
+ var cachedFontDigests = Object.create(null);
36
+ // Slow direct connections may take minutes for a full CJK font. Reading stays
37
+ // available while this background download completes.
38
+ var remoteFontDownloadTimeoutMs = 180000;
35
39
  function fontDatabase() {
36
40
  if (!fontDbPromise) fontDbPromise = new Promise(function (resolve) {
37
41
  var database;try{database=window.indexedDB;}catch(error){resolve(null);return;}
@@ -51,15 +55,26 @@ export const customizationScript = String.raw`
51
55
  if(!db){resolve(null);return;}
52
56
  var timer=setTimeout(function(){resolve(null);},1500);
53
57
  try {
54
- var tx=db.transaction('fonts',action==='get'?'readonly':'readwrite'),store=tx.objectStore('fonts');
55
- var request=action==='get'?store.get(key):action==='delete'?store.delete(key):store.put(value,key);
56
- request.onsuccess=function(){if(action==='get'){clearTimeout(timer);resolve(request.result);}};
58
+ var tx=db.transaction('fonts',action==='get'||action==='keys'?'readonly':'readwrite'),store=tx.objectStore('fonts');
59
+ var request=action==='get'?store.get(key):action==='keys'?store.getAllKeys():action==='delete'?store.delete(key):store.put(value,key);
60
+ request.onsuccess=function(){if(action==='get'||action==='keys'){clearTimeout(timer);resolve(request.result);}};
57
61
  tx.oncomplete=function(){clearTimeout(timer);resolve(null);};
58
62
  request.onerror=function(){clearTimeout(timer);resolve(null);};
59
63
  tx.onabort=function(){clearTimeout(timer);resolve(null);};
60
64
  } catch(error){clearTimeout(timer);resolve(null);}
61
65
  });});
62
66
  }
67
+ function fontSnapshotHeaders() {
68
+ if (!cachedFontHeadersReady) cachedFontHeadersReady = fontCache('keys').then(function(keys) {
69
+ (Array.isArray(keys) ? keys : []).forEach(function(url) {
70
+ var match = typeof url === 'string' && /^https:\/\/fontsforletters\.sqnori\.com\/fonts\/([a-f0-9]{64})\.woff2$/.exec(url);
71
+ if (match) cachedFontDigests[match[1]] = true;
72
+ });
73
+ });
74
+ return cachedFontHeadersReady.then(function() {
75
+ return { 'x-bottle-cached-fonts': Object.keys(cachedFontDigests).slice(0, 32).join(',') };
76
+ });
77
+ }
63
78
  function validFontResource(resource) {
64
79
  return resource && /^[a-f0-9]{64}$/.test(resource.sha256||'') && Number.isSafeInteger(resource.bytes) && resource.bytes>=48 && resource.bytes<=33554432 && resource.url==='https://fontsforletters.sqnori.com/fonts/'+resource.sha256+'.woff2';
65
80
  }
@@ -72,11 +87,11 @@ export const customizationScript = String.raw`
72
87
  async function remoteFontFace(family,resource) {
73
88
  var bytes=await fontCache('get',resource.url);
74
89
  if(bytes)try{await checkFontBytes(bytes,resource);var cached=new FontFace(family,bytes,{display:'swap'});await cached.load();return cached;}catch(error){await fontCache('delete',resource.url);}
75
- var response=await fetch(resource.url,{mode:'cors',credentials:'omit',cache:'force-cache',redirect:'error',signal:AbortSignal.timeout(20000)});
90
+ var response=await fetch(resource.url,{mode:'cors',credentials:'omit',cache:'force-cache',redirect:'error',signal:AbortSignal.timeout(remoteFontDownloadTimeoutMs)});
76
91
  if(!response.ok)throw Error('Font unavailable');
77
92
  bytes=await response.arrayBuffer();await checkFontBytes(bytes,resource);
78
93
  var face=new FontFace(family,bytes,{display:'swap'});await face.load();
79
- await fontCache('put',resource.url,bytes);return face;
94
+ await fontCache('put',resource.url,bytes);cachedFontDigests[resource.sha256]=true;return face;
80
95
  }
81
96
  function fontNode(node, fontId, own) {
82
97
  if (own) { node.dataset.myLetter = 'true'; fontId = myFontId || defaultMyFont.id; }
@@ -916,7 +916,7 @@ var wakePolicies = ${JSON.stringify(WAKE_POLICIES)};
916
916
  refreshHostTheme(false);
917
917
  refreshAnnouncement();
918
918
  var sequence = ++refreshSequence;
919
- fetch('/draft').then(function (res) { return res.json(); }).then(function (snapshot) {
919
+ fontSnapshotHeaders().then(function (headers) { return fetch('/draft', { headers: headers }); }).then(function (res) { return res.json(); }).then(function (snapshot) {
920
920
  if (sequence !== refreshSequence) return;
921
921
  if (window.bottleSound) window.bottleSound.snapshot(snapshot);
922
922
  state = snapshot;
package/world/page.ts CHANGED
@@ -141,7 +141,7 @@ export interface PageDeps {
141
141
  uploadBackground?(input: unknown): string;
142
142
  theme?(): Promise<MailboxTheme>;
143
143
  appearance?(preference?: ThemePreference): Promise<CardAppearance>;
144
- snapshot(): PageSnapshot;
144
+ snapshot(cachedFontDigests?: readonly string[]): PageSnapshot;
145
145
  announcement?(): Promise<AnnouncementSummary | null>;
146
146
  refresh?(): Promise<void>;
147
147
  wakeControl?(action: WakeAction, command: 'pause' | 'resume' | 'interval', hours?: number, dayLimit?: number): Promise<PageResult>;
@@ -170,6 +170,8 @@ export interface PageResponse {
170
170
 
171
171
  export interface PageRequestOptions {
172
172
  surface?: Surface;
173
+ /** Browser cache hints contain only public font digests, never letter identities. */
174
+ cachedFontDigests?: readonly string[];
173
175
  /** POST 的 JSON 体;只有 /forget 用得上。 */
174
176
  body?: unknown;
175
177
  }
@@ -244,7 +246,7 @@ export async function handlePage(
244
246
  try { return { status: 200, json: { announcement: await deps.announcement?.() ?? null } }; }
245
247
  catch { return { status: 503, json: { announcement: null } }; }
246
248
  }
247
- if (method === 'GET' && route === '/draft') { await deps.refresh?.(); return { status: 200, json: deps.snapshot() }; }
249
+ if (method === 'GET' && route === '/draft') { await deps.refresh?.(); return { status: 200, json: deps.snapshot(opts.cachedFontDigests) }; }
248
250
 
249
251
  if (method === 'POST' && route === '/forget') {
250
252
  const letterId = letterIdOf(opts.body);
@@ -367,7 +369,11 @@ export function pageHandler(deps: PageDeps, log?: (line: string) => void, remote
367
369
  res.end(JSON.stringify({ ok: false, message: '请求体读不出来,这个动作没有执行。' }));
368
370
  return null;
369
371
  }
370
- return handlePage(deps, method, path, { surface, body: read.value });
372
+ const cacheHeader = req.headers['x-bottle-cached-fonts'];
373
+ const cachedFontDigests = typeof cacheHeader === 'string' && cacheHeader.length <= 2079
374
+ ? [...new Set(cacheHeader.split(',').filter(value => /^[a-f0-9]{64}$/.test(value)))].slice(0, 32)
375
+ : [];
376
+ return handlePage(deps, method, path, { surface, body: read.value, cachedFontDigests });
371
377
  })
372
378
  .then((result) => {
373
379
  if (result === null) return; // 上面已经回过 400
package/world/store.ts CHANGED
@@ -99,12 +99,29 @@ function readJson<T>(path: string): T | null {
99
99
  }
100
100
  }
101
101
 
102
+ /**
103
+ * 上一次写盘失败的原因(`null` = 上次成功或还没写过)。
104
+ *
105
+ * 为什么要把失败暴露出来:以前这里 `catch {}` 全吞掉,注释写着"下一次动作还会再写一次"。
106
+ * 但「手里那封信的 letterId」只写一次——写失败就再也没有下一次了:
107
+ * 服务端占着信、本机不知道是哪封,玩家永久卡在「海边还记着一封未处理的信」。
108
+ * 所以现在至少留一个可读的状态,让上层能发现"这台机器的本机记录没写进去"。
109
+ */
110
+ let lastWriteError: string | null = null;
111
+
112
+ export function lastStoreWriteError(): string | null {
113
+ return lastWriteError;
114
+ }
115
+
102
116
  function writeJson(path: string, value: unknown): void {
103
117
  try {
104
118
  mkdirSync(dirname(path), { recursive: true });
105
119
  writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
106
- } catch {
107
- // 写不进去不影响主流程;下一次动作还会再写一次
120
+ lastWriteError = null;
121
+ } catch (error) {
122
+ // 仍然不打断主流程(一次 UI 动作不该因为磁盘满而整条失败),
123
+ // 但把原因记下来,别再让它无声无息。
124
+ lastWriteError = error instanceof Error ? error.message : String(error);
108
125
  }
109
126
  }
110
127
 
@@ -332,6 +349,22 @@ export class LocalStore {
332
349
  this.saveLetterbook();
333
350
  }
334
351
 
352
+ /**
353
+ * 写盘后立刻回读确认「手里那封信」真的落盘了。
354
+ *
355
+ * 用于打捞与原信恢复:记录未落盘时,重启会丢失本机的手中信件。
356
+ * 返回 `false` 时调用方应当尝试解除占用,并且只在服务端确认后清空 held;
357
+ * 释放失败则保留内存中的信,便于人继续处理。
358
+ */
359
+ heldPersisted(): boolean {
360
+ if (!this.held) return true;
361
+ const want = this.held.letterId;
362
+ this.saveLetterbook();
363
+ const disk = readJson<{ held?: { letterId?: unknown } }>(this.letterbookFile);
364
+ const got = disk?.held?.letterId;
365
+ return typeof got === 'string' && got === want;
366
+ }
367
+
335
368
  addReply(reply: LocalReply): void {
336
369
  if (this.replies.some((item) => item.letterId === reply.letterId)) return;
337
370
  this.replies.unshift(reply);
package/world/world.ts CHANGED
@@ -110,6 +110,8 @@ export class BottleWorld implements World {
110
110
  private timers: Array<ReturnType<typeof setInterval>> = [];
111
111
 
112
112
  private quota: Quota | null = null;
113
+ /** 最近一次服务端给出的有效回信窗口;老服务端缺省时用 72 小时。 */
114
+ private replyWindowHours: number | null = null;
113
115
  /** 上一次拿到额度回执的时刻;页面据此决定要不要顺手刷新。 */
114
116
  private quotaAt = 0;
115
117
  private quotaRevision = 0;
@@ -316,6 +318,7 @@ export class BottleWorld implements World {
316
318
 
317
319
  async start(host: WorldHost): Promise<void> {
318
320
  this.host = host;
321
+ this.replyWindowHours = null;
319
322
  this.store.load();
320
323
  this.generation += 1;
321
324
  this.announcementSession = randomUUID();
@@ -711,12 +714,21 @@ export class BottleWorld implements World {
711
714
  /** 额度只有一个入口:任何时候拿到的回执都顺手把信件状态吃进来。 */
712
715
  private setQuota(quota: Quota): void {
713
716
  this.quotaRevision += 1;
717
+ const hours = quota.reply_window_hours;
718
+ if (typeof hours === 'number' && Number.isFinite(hours) && hours > 0) {
719
+ this.replyWindowHours = hours;
720
+ }
714
721
  const { announcement: _announcement, ...visibleQuota } = quota;
715
722
  this.quota = visibleQuota;
716
723
  this.quotaAt = this.now();
717
724
  this.absorbLetterStates(quota);
718
725
  }
719
726
 
727
+ /** 只用于缺失截止时间时的推算,不能覆盖服务端已经给出的 windowUntil。 */
728
+ private windowHours(): number {
729
+ return this.replyWindowHours ?? REPLY_WINDOW_HOURS;
730
+ }
731
+
720
732
  private absorbLetterStates(quota: Quota): void {
721
733
  // 只有 `/quota` 才带这两个字段;动作回执里的 quota 是纯额度,不能拿它清空已知状态。
722
734
  if (quota.deadLetters !== undefined) this.deadLetters.clear();
@@ -989,12 +1001,13 @@ export class BottleWorld implements World {
989
1001
  }
990
1002
 
991
1003
  private async recoverLegacyHeld(): Promise<{ letterId: string; from: string; windowUntil: string; caughtAt?: string } | null> {
1004
+ const hours = this.windowHours();
992
1005
  for (const item of [...this.store.received].sort((a, b) => b.at - a.at)) {
993
1006
  const caughtAt = item.lastCaughtAt ?? item.at;
994
- if (item.seed || item.outcome === 'replied' || caughtAt + REPLY_WINDOW_HOURS * HOUR <= this.now()) continue;
1007
+ if (item.seed || item.outcome === 'replied' || caughtAt + hours * HOUR <= this.now()) continue;
995
1008
  try {
996
1009
  const letter = await this.authed(() => this.client.letter(item.letterId));
997
- return { letterId: item.letterId, from: letter.from, windowUntil: new Date(caughtAt + REPLY_WINDOW_HOURS * HOUR).toISOString(), caughtAt: new Date(caughtAt).toISOString() };
1010
+ return { letterId: item.letterId, from: letter.from, windowUntil: new Date(caughtAt + hours * HOUR).toISOString(), caughtAt: new Date(caughtAt).toISOString() };
998
1011
  } catch (error) {
999
1012
  if (!(error instanceof BottleError && (error.code === 'gone' || error.code === 'not_found'))) throw error;
1000
1013
  }
@@ -1031,10 +1044,33 @@ export class BottleWorld implements World {
1031
1044
  const held = res.held ?? await this.recoverLegacyHeld();
1032
1045
  if (held) res = { empty: false, ...held, quota: res.quota };
1033
1046
  }
1047
+
1048
+ // ── 死锁兜底:服务端占着一封,但本机完全找不回来 ──
1049
+ //
1050
+ // 会走到这里的情况:新服务端没给 held、本机历史也没有那封(第一次使用的人尤其常见)。
1051
+ // 以前这里只回一句话让玩家「等 72 小时」,等于把一次网络抖动变成三天的功能失效。
1052
+ //
1053
+ // 现在直接向服务端申请「把我手上那封放掉」——不带 letterId,服务端自己找。
1054
+ // 服务端对这条路径不计入扔回次数,所以瓶子不会因此裂开。
1055
+ if (res.empty && res.reason === 'holding') {
1056
+ try {
1057
+ const released = await this.authed(() => this.client.releaseHeld());
1058
+ this.setQuota(released.quota);
1059
+ this.log('holding deadlock released');
1060
+ // 占用已经解开,这一次动作仍然算「没捞到」,但下次就能正常捞了
1061
+ this.catchSucceeded = false;
1062
+ return `海边刚才记着一封没送到的信,已经替你放回海里了。现在可以再捞一次。${this.quotaLine(released.quota)}`;
1063
+ } catch (error) {
1064
+ this.log(`release held failed: ${error instanceof BottleError ? error.code : 'unknown'}`);
1065
+ // 兜底也失败(旧服务端不认这条路径):说清楚,但别让玩家以为是自己弄坏的
1066
+ this.catchSucceeded = false;
1067
+ return `海边记着一封没送到的信,暂时解不开。过一会儿再试;实在不行它会在回信窗口结束后自己回海。${this.quotaLine(res.quota)}`;
1068
+ }
1069
+ }
1070
+
1034
1071
  this.catchSucceeded = !res.empty || (res.reason !== 'holding' && res.reason !== 'quota');
1035
1072
  if (res.empty) {
1036
1073
  if (res.reason !== 'holding' && res.reason !== 'quota') this.wake?.success('catch');
1037
- if (res.reason === 'holding') return `海边还记着一封未处理的信,但本机记录没有找回。请更新海边服务端以恢复到信箱,或等这封信的回信窗口结束后再捞。${this.quotaLine(res.quota)}`;
1038
1074
  if (res.reason === 'quota') return `今天的捞取次数用完了。${this.quotaLine(res.quota)}`;
1039
1075
  return `今天海上很安静。${this.quotaLine(res.quota)}`;
1040
1076
  }
@@ -1068,7 +1104,7 @@ export class BottleWorld implements World {
1068
1104
  body,
1069
1105
  caughtBy: actor,
1070
1106
  caughtAt,
1071
- windowUntil: Date.parse(res.windowUntil) || this.now() + REPLY_WINDOW_HOURS * HOUR,
1107
+ windowUntil: Date.parse(res.windowUntil) || this.now() + this.windowHours() * HOUR,
1072
1108
  ...(isSeed ? { seed: true } : {}),
1073
1109
  ...(dead ? { dead: true } : {}),
1074
1110
  ...(signature ? { signature } : {}),
@@ -1086,6 +1122,36 @@ export class BottleWorld implements World {
1086
1122
  ...(topic ? { topic } : {}),
1087
1123
  });
1088
1124
  if (!recovered) this.store.noteCaught(this.now());
1125
+
1126
+ // ── 落盘校验:这是整条死锁链的源头 ──
1127
+ //
1128
+ // 服务端已经把信标记成「这个人拿着」了。如果本机这份 held 没写进去,
1129
+ // 玩家就会卡在「海边还记着一封未处理的信」——服务端占着、本机不知道是哪封、
1130
+ // 而放信又必须提供 letterId。一次磁盘写失败就换来一次永久卡死。
1131
+ //
1132
+ // 新捞到与恢复的信都校验。释放失败时保留内存中的原信,
1133
+ // 只有服务端确认放回后才清空 held,避免再制造一封无从处理的信。
1134
+ if (!this.store.heldPersisted()) {
1135
+ this.log('held not persisted; attempting to release server occupancy');
1136
+ this.catchSucceeded = false;
1137
+ // 种子信不占服务端手中信件,不能拿通用释放接口来处理它。
1138
+ if (!isSeed) {
1139
+ try {
1140
+ const released = await this.authed(() => this.client.releaseHeld());
1141
+ this.setQuota(released.quota);
1142
+ this.store.setReceivedOutcome(caughtId, 'dismissed');
1143
+ this.store.setHeld(null);
1144
+ return `这封没能存到本机(信箱目录可能不可写),已经放回海里了。请检查本机存储后再捞。${this.quotaLine(released.quota)}`;
1145
+ } catch (error) {
1146
+ this.log(`release after failed persist: ${error instanceof BottleError ? error.code : 'unknown'}`);
1147
+ }
1148
+ }
1149
+ if (!remote) this.showHeldCard();
1150
+ return isSeed
1151
+ ? `这封群岛来信没能存到本机,当前信箱仍保留着它。请先收好它,并检查信箱目录是否可写。${this.quotaLine(res.quota)}`
1152
+ : `这封信没能存到本机,且尚未放回海里。当前信箱仍保留着它,请先在信箱页处理,并检查信箱目录是否可写。${this.quotaLine(res.quota)}`;
1153
+ }
1154
+
1089
1155
  this.wake?.success('catch');
1090
1156
  if (!remote) this.showHeldCard();
1091
1157
 
@@ -1192,7 +1258,7 @@ export class BottleWorld implements World {
1192
1258
  if (preference) saveThemePreference(this.ctx.dataDir, preference);
1193
1259
  return cardAppearance(readThemePreference(this.ctx.dataDir) ?? DEFAULT_APPEARANCE, await readMailboxTheme(this.ctx.botDir));
1194
1260
  },
1195
- snapshot: () => this.letterFonts!.decorate(this.snapshot()),
1261
+ snapshot: cachedFontDigests => this.letterFonts!.decorate(this.snapshot(), cachedFontDigests),
1196
1262
  refresh: () => { void this.letterFonts!.refresh(); return this.refreshVisibleQuota(); },
1197
1263
  wakeControl: (action, command, hours, dayLimit) => this.wakeControl(action, command, hours, dayLimit),
1198
1264
  announcement: () => this.pageAnnouncement(),