cortico-world-bottle 0.8.0 → 0.8.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,14 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.8.2 · 小更新
4
+
5
+ - 修复读信后写回信导致共读次数重复增加的问题;现在只有点击「一起读」才会计次。
6
+
7
+ ## 0.8.1 · 紧急修复
8
+
9
+ - 修复小纸条寄出后本机记录消失的问题,寄出与收到的纸条都随原往来保留。
10
+ - 寄送中断时保留原文并可确认结果,避免重复扣机会;补充接收、重启和写盘失败保护。
11
+
3
12
  ## 0.8.0 · 大更新
4
13
 
5
14
  - 信箱换上新的信纸排版,新增「书信」主题,重调「暖纸」配色,优化手机阅读与按钮布局。
package/README.md CHANGED
@@ -18,7 +18,7 @@ Coo 写一封不超过 120 字的信。**寄不寄,由你决定**;别人家
18
18
 
19
19
  你寄出的信收到回信后,可在回信旁邀请桌宠给对方留最多 40 字的小纸条。正文只能由桌宠工具起草,人可请桌宠重写、确认寄出或放弃,页面不能填写或改字;重写失败保留原稿,且不延长最初一小时有效期;寄出用一次打捞机会,不影响已有回信。草稿只在当前 World 内存中保留最多一小时,寄出、放弃、删除往来或停止 World 时清除。生成纸条的那轮模型会看到这段往来与自己的输出;收到纸条会自动唤醒桌宠并递上纸条正文,请它转告你;原信和原回信不会随后台通知递出。
20
20
 
21
- 小纸条贴在对应信件下方,草稿贴在收到的回信下方,不再单独列出;此设备没有原信时显示对应往来的占位说明。收到纸条后先保存在本机再向服务端 ack;服务端未取走的纸条在创建七天后删除。本机已收到的纸条与已读标记永久保留,继续附在对应往来后;只有删除对应往来或清空信册时才清除正文,防重复恢复的无正文凭据到原期限删除。状态仅「未读 / 已读」,确认进入桌宠上下文后标已读。点击纸条下的「一起看」会单次附上小纸条、原信和原回信,只交流感想,不自动写回信。浏览器不另存正文,离开页面清除页面副本。防重复扣费的无正文凭据最多保留七天;服务端长期备份排除纸条正文。
21
+ 小纸条贴在对应信件下方,草稿贴在收到的回信下方,不再单独列出;此设备没有原信时显示对应往来的占位说明。收到纸条后先保存在本机再向服务端 ack;服务端未取走的纸条在创建七天后删除。本机收到的纸条与已读标记、寄出的纸条原文与寄送状态均永久保留,继续附在对应往来后;只有删除对应往来或清空信册时才清除正文,防重复恢复的无正文凭据到原期限删除。收到的纸条仅显示「未读 / 已读」,确认进入桌宠上下文后标已读;寄出的纸条显示「已寄出」。确认寄出时先保存原文,再联系服务端;断网或确认丢失时显示「寄送待确认」,可原文重试且不重复扣机会,超过七天的安全确认期限则保留原文、停止重试。确认寄送的本机副本不是未确认草稿,不受一小时草稿清理影响。点击纸条下的「一起看」会单次附上小纸条、原信和原回信,只交流感想,不自动写回信。浏览器不另存正文,离开页面清除页面副本。防重复扣费的无正文凭据最多保留七天;服务端长期备份排除纸条正文。
22
22
 
23
23
  随海啸远去的信,可在寄出信册点击「重新投出去」,用本机原文创建新信,消耗一次打捞机会。旧信保持失效;同一次重投重复请求不创建额外信或重复扣费。本机原文也丢失时明确提示无法找回。
24
24
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-bottle",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "type": "module",
5
5
  "description": "桌宠起草漂流瓶与小纸条,人确认寄出;共读、回信与星笺记忆分别授权。",
6
6
  "keywords": [
@@ -4,11 +4,14 @@ import { NOTE_TTL_MS, type ReceivedNote } from '../shared/contract.ts';
4
4
  import { checkNote } from '../shared/text.ts';
5
5
 
6
6
  /** expiresAt describes server retention only; it never expires this local copy. */
7
- export interface LocalNote extends ReceivedNote { readAt?: number }
7
+ export interface LocalNote extends ReceivedNote { readAt?: number; direction?: 'sent'; delivery?: 'pending' | 'sent' }
8
8
  interface ForgottenNote { id:string; letterId:string; expiresAt:string }
9
9
 
10
10
  /** Local archive: body and readAt remain until the human deletes the correspondence or
11
11
  * clears the letterbook. Server expiry is transport metadata, never a local deadline.
12
+ * Confirmed sending is archived before the network request; pending delivery receipts
13
+ * keep the exact body for idempotent confirmation after a disconnect or restart.
14
+ * Outgoing bodies, like incoming bodies, are deleted only with their correspondence.
12
15
  * Body-free deletion receipts prevent a failed server ACK from restoring removed notes;
13
16
  * these receipts alone expire at the server's original seven-day deadline.
14
17
  * Neither notes nor these receipts are included in letterbook exports or star memory. */
@@ -24,7 +27,7 @@ export class NoteCache {
24
27
  if(data.schemaVersion!==1)return;
25
28
  for(const value of Array.isArray(data.notes)?data.notes:[]) {
26
29
  const note=this.valid(value);if(!note)continue;
27
- this.records.set(note.id,{...note,...(typeof value.readAt==='number'&&Number.isFinite(value.readAt)&&value.readAt>0?{readAt:value.readAt}:{})});
30
+ this.records.set(note.id,{...note,...(value.direction==='sent'?{direction:'sent' as const,delivery:value.delivery==='pending'?'pending' as const:'sent' as const}:{}),...(typeof value.readAt==='number'&&Number.isFinite(value.readAt)&&value.readAt>0?{readAt:value.readAt}:{})});
28
31
  }
29
32
  for(const value of Array.isArray(data.forgotten)?data.forgotten:[]){
30
33
  if(value&&this.id(value.id)&&this.id(value.letterId)&&typeof value.expiresAt==='string'&&Date.parse(value.expiresAt)>this.now()){
@@ -51,6 +54,28 @@ export class NoteCache {
51
54
  if(added)this.records.set(note.id,note);
52
55
  try{this.save();}catch(error){if(added)this.records.delete(note.id);throw error;}return note.id;
53
56
  }
57
+ outgoing(letterId:string):LocalNote|undefined {
58
+ const note=this.records.get('sent:'+letterId);return note?.direction==='sent'?{...note}:undefined;
59
+ }
60
+ stageOutgoing(letterId:string,body:string,from:string):LocalNote {
61
+ const existing=this.outgoing(letterId);if(existing)return existing;
62
+ const at=this.now();
63
+ const note:LocalNote={id:'sent:'+letterId,letterId,from,body,at:new Date(at).toISOString(),expiresAt:new Date(at+NOTE_TTL_MS).toISOString(),direction:'sent',delivery:'pending'};
64
+ if(!this.valid(note))throw Error('Invalid outgoing note');
65
+ this.writeRecord(note);return {...note};
66
+ }
67
+ confirmOutgoing(letterId:string):void {
68
+ const note=this.outgoing(letterId);if(!note)throw Error('Missing outgoing note');
69
+ this.writeRecord({...note,delivery:'sent'});
70
+ }
71
+ discardPending(letterId:string):void {
72
+ const note=this.outgoing(letterId);if(!note||note.delivery!=='pending')return;
73
+ this.records.delete(note.id);try{this.save();}catch(error){this.records.set(note.id,note);throw error;}
74
+ }
75
+ private writeRecord(note:LocalNote):void {
76
+ const previous=this.records.get(note.id);this.records.set(note.id,note);
77
+ try{this.save();}catch(error){if(previous)this.records.set(note.id,previous);else this.records.delete(note.id);throw error;}
78
+ }
54
79
  all():LocalNote[]{this.prune();return [...this.records.values()].map(n=>({...n})).sort((a,b)=>Date.parse(a.at)-Date.parse(b.at));}
55
80
  get(id:string):LocalNote|undefined{this.prune();const note=this.records.get(id);return note?{...note}:undefined;}
56
81
  read(id:string):void {
@@ -59,7 +84,7 @@ export class NoteCache {
59
84
  }
60
85
  forget(letterId?:string):void {
61
86
  for(const [id,note] of this.records){if(letterId&&note.letterId!==letterId)continue;
62
- this.forgotten.set(id,{id,letterId:note.letterId,expiresAt:note.expiresAt});this.records.delete(id);
87
+ if(note.direction!=='sent')this.forgotten.set(id,{id,letterId:note.letterId,expiresAt:note.expiresAt});this.records.delete(id);
63
88
  }
64
89
  this.prune();this.save();
65
90
  }
@@ -35,7 +35,7 @@ export const extrasScript = String.raw`
35
35
  var hasDraft=slot===draftSlot&&!paperComposer.hidden;
36
36
  var hasNotes=Array.from(slot.children).some(function(node){return node!==paperComposer;});
37
37
  var tray=slot.closest('.paper-tray'), invite=tray&&tray.querySelector('.paper-invite');
38
- if(invite)invite.hidden=hasDraft;
38
+ if(invite)invite.hidden=hasDraft||Array.from(paperRows.values()).some(function(row){return row.letterId===slot.dataset.letterId&&row.direction==='sent';});
39
39
  if(tray)tray.hidden=!hasNotes&&!hasDraft&&!invite;
40
40
  var badge=slot.closest('.mail').querySelector('.paper-badge');
41
41
  if(badge)badge.hidden=!hasNotes&&!hasDraft;
@@ -70,15 +70,19 @@ export const extrasScript = String.raw`
70
70
  paperRows.forEach(function(row,id){if(!live.has(id)){row.node.textContent='';row.node.remove();paperRows.delete(id);added=true;}});
71
71
  rows.forEach(function(row){
72
72
  if(!row||typeof row.id!=='string'||typeof row.letterId!=='string'||!row.letterId||typeof row.body!=='string'||typeof row.from!=='string'||!Number.isFinite(Date.parse(row.at))||[...row.body].length>40)return;
73
+ var outgoing=row.direction==='sent',pending=outgoing&&row.delivery==='pending';
73
74
  var existing=paperRows.get(row.id);
74
- if(existing){if(existing.read!==row.read){existing.read=row.read===true;existing.status.textContent=existing.read?'已读':'未读';existing.status.className='paper-status '+(existing.read?'paper-read':'paper-unread');}return;}
75
+ if(existing){
76
+ if(existing.read===(row.read===true)&&existing.delivery===row.delivery&&existing.direction===row.direction)return;
77
+ existing.node.remove();paperRows.delete(row.id);
78
+ }
75
79
  var node=el('article','paper-slip');node.dataset.noteId=row.id;
76
- var heading=el('div','paper-heading');heading.appendChild(el('small',null,row.from+'留下的小纸条'));
77
- var status=el('span','paper-status '+(row.read?'paper-read':'paper-unread'),row.read?'已读':'未读');heading.appendChild(status);node.appendChild(heading);node.appendChild(el('p',null,row.body));
78
- var together=el('button','read-together','一起看');together.type='button';
79
- together.onclick=function(){if(together.disabled)return;together.disabled=true;api('/note/read',{id:row.id}).then(function(r){toast(r.message||'没有递过去,请稍后重试。',!r.ok);refreshPapers();}).catch(function(){toast('没有递过去,请稍后重试。',true);}).then(function(){together.disabled=false;});};
80
+ var heading=el('div','paper-heading');heading.appendChild(el('small',null,row.from+(outgoing?'寄出的小纸条':'留下的小纸条')));
81
+ var status=el('span','paper-status '+(pending||(!outgoing&&!row.read)?'paper-unread':'paper-read'),outgoing?(pending?'寄送待确认':'已寄出'):(row.read?'已读':'未读'));heading.appendChild(status);node.appendChild(heading);node.appendChild(el('p',null,row.body));
82
+ var together=el('button','read-together',pending?'确认寄送结果':'一起看');together.type='button';
83
+ together.onclick=function(){if(together.disabled)return;together.disabled=true;api(pending?'/note':'/note/read',pending?{letterId:row.letterId}:{id:row.id}).then(function(r){toast(r.message||'没有递过去,请稍后重试。',!r.ok);refreshPapers();refresh();}).catch(function(){toast('没有递过去,请稍后重试。',true);}).then(function(){together.disabled=false;});};
80
84
  node.appendChild(together);
81
- paperRows.set(row.id,{node:node,letterId:row.letterId,from:row.from,at:row.at,read:row.read===true,status:status});added=true;
85
+ paperRows.set(row.id,{node:node,letterId:row.letterId,from:row.from,at:row.at,read:row.read===true,direction:row.direction,delivery:row.delivery,status:status});added=true;
82
86
  });
83
87
  if(added&&state){captureDetails();renderBook();}else attachPapers();
84
88
  }).catch(function(){}).then(function(){paperFetching=false;});
@@ -786,7 +786,7 @@ var wakePolicies = ${JSON.stringify(WAKE_POLICIES)};
786
786
  if (item.reply) entries.push({ category: 'reply', item: item, at: item.reply.at, body: item.reply.body });
787
787
  });
788
788
  paperRows.forEach(function(row){
789
- if(!entries.some(function(entry){return entry.item.letterId===row.letterId;}))entries.push({category:'received',paperOnly:true,item:{letterId:row.letterId,from:row.from,at:row.at},at:row.at,body:''});
789
+ if(!entries.some(function(entry){return entry.item.letterId===row.letterId;}))entries.push({category:row.direction==='sent'?'sent':'received',paperOnly:true,item:{letterId:row.letterId,from:row.from,at:row.at},at:row.at,body:''});
790
790
  });
791
791
  return entries;
792
792
  }
package/world/page.ts CHANGED
@@ -156,7 +156,7 @@ export interface PageResult {
156
156
  }
157
157
 
158
158
  export interface PageDeps {
159
- notes?(): Promise<Array<import('../shared/contract.ts').ReceivedNote & {read:boolean}>>;
159
+ notes?(): Promise<Array<import('./note-cache.ts').LocalNote & {read:boolean}>>;
160
160
  readNote?(id:string):Promise<PageResult>;
161
161
  ackNote?(id:string): Promise<PageResult>;
162
162
  note?(id:string): Promise<PageResult>;
package/world/world.ts CHANGED
@@ -25,7 +25,7 @@ import type { Language } from 'cortico/core/language.ts';
25
25
  import type { EventEnvelope, RunPhase, ToolDef, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
26
26
  import { nowIso } from 'cortico/core/util.ts';
27
27
  import type { WorldContext } from 'cortico/world.ts';
28
- import { BODY_MAX, REPLY_WINDOW_HOURS, type AnnouncementSummary, type Quota } from '../shared/contract.ts';
28
+ import { BODY_MAX, NOTE_TTL_MS, REPLY_WINDOW_HOURS, type AnnouncementSummary, type Quota } from '../shared/contract.ts';
29
29
  import { agoText } from '../shared/ago.ts';
30
30
  import { defaultLocalEnv, scanHints, type LocalEnv } from '../shared/hints.ts';
31
31
  import { checkBody, checkNote, checkTitle, countChars, safePseudonym } from '../shared/text.ts';
@@ -1290,9 +1290,7 @@ export class BottleWorld implements World {
1290
1290
  delete draft.autoSendKey;
1291
1291
  this.store.setDraft(draft);
1292
1292
  }
1293
- // A retry after a failed model turn is still the same unfinished reading.
1294
- // Count only once a valid reply draft exists, never when merely queuing the original.
1295
- this.store.noteRead('received', auth.letterId, this.now());
1293
+ // Reading counts belong to the explicit together-reading action, not reply drafting.
1296
1294
  this.authorized = null;
1297
1295
  this.autoReplyRetryAt=0;
1298
1296
  await this.checkAutoReply();
@@ -1340,7 +1338,7 @@ export class BottleWorld implements World {
1340
1338
  }catch{/* Old servers and temporary outages do not hide cached papers. */}
1341
1339
  if(generation!==this.generation||!this.host)return;
1342
1340
  try{
1343
- for(const note of this.receivedNotes.all())if(!note.readAt&&!this.queuedNotes.has(note.id)&&!this.authorizedNow())this.queueNote(note,'arrival');
1341
+ for(const note of this.receivedNotes.all())if(note.direction!=='sent'&&!note.readAt&&!this.queuedNotes.has(note.id)&&!this.authorizedNow())this.queueNote(note,'arrival');
1344
1342
  }catch{this.log('note delivery could not be queued');}
1345
1343
  })();
1346
1344
  this.noteRefresh=work;void work.finally(()=>{if(this.noteRefresh===work)this.noteRefresh=null;});return work;
@@ -1382,6 +1380,7 @@ export class BottleWorld implements World {
1382
1380
  if(!this.host)return {ok:false,message:'还没有连上。'};
1383
1381
  if(this.authorizedNow()||this.perusePending)return {ok:false,message:'请等当前这轮读完,再一起看。'};
1384
1382
  const paper=this.receivedNotes.get(id);if(!paper)return {ok:false,message:'这张小纸条已经不在信箱里了。'};
1383
+ if(paper.direction==='sent'&&paper.delivery==='pending')return {ok:false,message:'请先确认这张小纸条的寄送结果。'};
1385
1384
  try{this.queueNote(paper,'together');return {ok:true,message:`已把小纸条和原信、原回信一起递给${this.botName}。`};}
1386
1385
  catch{return {ok:false,message:'还没有递过去,请稍后重试。'};}
1387
1386
  }
@@ -1392,6 +1391,7 @@ export class BottleWorld implements World {
1392
1391
  if(this.phase!=='idle'||this.runningTools>0||(this.pendingRequest&&this.pendingRequest.until>this.now())||this.wake?.snapshot().active)return {ok:false,message:`${this.botName}正在处理别的事,稍后再邀请吧。`};
1393
1392
  if(this.noteDraft && this.now()-this.noteDraft.at>=HOUR)this.noteDraft=null;
1394
1393
  if(this.noteSending)return {ok:false,message:'小纸条正在寄出,请稍候。'};
1394
+ if(this.receivedNotes.outgoing(id))return {ok:false,message:'这段往来已有小纸条,请在原信下查看或确认寄送结果。'};
1395
1395
  if(rewrite && this.noteDraft?.letterId!==id)return {ok:false,message:'没有可重写的小纸条,请先邀请起草。'};
1396
1396
  if(!rewrite && this.noteDraft)return {ok:false,message:'先寄出、重写或放弃现有的小纸条。'};
1397
1397
  const original=this.store.sent.find(n=>n.letterId===id),reply=this.store.replies.find(n=>n.letterId===id);
@@ -1420,11 +1420,30 @@ export class BottleWorld implements World {
1420
1420
  private async sendNote(id:string): Promise<PageResult> {
1421
1421
  if(this.noteSending)return {ok:false,message:'小纸条正在寄出,请稍候。'};
1422
1422
  if(this.authorizedNow()?.intent==='note')return {ok:false,message:`${this.botName}正在写小纸条,请等写好后再寄出。`};
1423
- const draft=this.noteDraft;
1424
- if(!draft||draft.letterId!==id||this.now()-draft.at>=HOUR){if(draft&&this.now()-draft.at>=HOUR)this.noteDraft=null;return {ok:false,message:'没有可寄出的小纸条,请先邀请起草。'};}
1423
+ const archived=this.receivedNotes.outgoing(id);
1424
+ if(archived?.delivery==='sent')return {ok:true,message:'这张小纸条已经寄出,本机记录保存在原信下方。'};
1425
+ if(archived&&this.now()-Date.parse(archived.at)>=NOTE_TTL_MS)return {ok:false,message:'寄送结果未能确认,已超过可安全重试的期限。原文仍保存在本机,请勿重复寄送。'};
1426
+ const draft=archived?{letterId:id,body:archived.body,at:Date.parse(archived.at)}:this.noteDraft;
1427
+ if(!draft||draft.letterId!==id||(!archived&&this.now()-draft.at>=HOUR)){if(draft&&!archived&&this.now()-draft.at>=HOUR)this.noteDraft=null;return {ok:false,message:'没有可寄出的小纸条,请先邀请起草。'};}
1425
1428
  const sending={};this.noteSending=sending;
1426
- try{const result=await this.authed(()=>this.client.note(id,draft.body));this.setQuota(result.quota);if(this.noteDraft===draft)this.noteDraft=null;return {ok:true,message:result.repeated?'这封信已经留过纸条,没有重复投递或扣机会。':'小纸条已寄给回信的那位。'};}
1427
- catch(error){return {ok:false,message:error instanceof BottleError?error.message:'纸条没有寄出,草稿还在,请稍后重试。'};}
1429
+ let staged=false,accepted=false;
1430
+ try{
1431
+ // Human-confirmed outgoing text is durable before the server can accept it.
1432
+ this.receivedNotes.stageOutgoing(id,draft.body,this.botName);staged=true;
1433
+ const result=await this.authed(()=>this.client.note(id,draft.body));accepted=true;this.setQuota(result.quota);
1434
+ if(result.repeated&&!archived){
1435
+ // An older client may have sent different text. Never claim this draft was sent.
1436
+ this.receivedNotes.discardPending(id);
1437
+ return {ok:false,message:'这封信以前已留过纸条,本稿没有重新寄出。旧版本未保存的纸条原文无法从回执找回。'};
1438
+ }
1439
+ this.receivedNotes.confirmOutgoing(id);
1440
+ if(this.noteDraft?.letterId===id)this.noteDraft=null;
1441
+ return {ok:true,message:result.repeated?'已确认寄出,纸条保存在原信下方,没有重复扣机会。':'小纸条已寄给回信的那位,本机记录保存在原信下方。'};
1442
+ }
1443
+ catch(error){
1444
+ if(!staged)return {ok:false,message:'本机未能保存纸条,没有尝试寄出。草稿还在,请检查信箱目录是否可写。'};
1445
+ return {ok:false,message:accepted?'纸条已寄出,本机寄送状态尚未保存。原文已保留,请确认寄送结果。':(error instanceof BottleError?error.message+' 原文已保留,可在原信下确认寄送结果。':'寄送结果尚未确认,原文已保留,可在原信下确认寄送结果。')};
1446
+ }
1428
1447
  finally{if(this.noteSending===sending)this.noteSending=null;}
1429
1448
  }
1430
1449
 
@@ -1734,7 +1753,7 @@ export class BottleWorld implements World {
1734
1753
  }
1735
1754
  : null;
1736
1755
  const snapshot: PageSnapshot = {
1737
- noteDraft: this.noteDraft,
1756
+ noteDraft: this.noteDraft&&!this.receivedNotes.outgoing(this.noteDraft.letterId)?this.noteDraft:null,
1738
1757
  noteRewriting: this.authorizedNow()?.intent==='note' && !!this.authorized?.noteRewrite,
1739
1758
  starMemoryEnabled: this.ctx.cfg.starMemoryEnabled === true,
1740
1759
  stars: this.starViews(),
@@ -1809,8 +1828,11 @@ export class BottleWorld implements World {
1809
1828
  }
1810
1829
 
1811
1830
  private async forgetHistory(letterId?: string): Promise<PageResult> {
1831
+ if(this.noteSending)return {ok:false,message:'小纸条正在寄出,请稍候再删除往来。'};
1812
1832
  if ((!letterId || this.store.draft?.letterId === letterId) && !await this.cancelAutoReply())
1813
1833
  return { ok: false, message: '尚未取消待寄回信,记录仍保留,请联网后重试。' };
1834
+ // Cancelling an auto-reply may yield while a note send starts in another tab.
1835
+ if(this.noteSending)return {ok:false,message:'小纸条正在寄出,请稍候再删除往来。'};
1814
1836
  if (!letterId || this.store.draft?.letterId === letterId) { this.store.setDraft(null); this.authorized = null; }
1815
1837
  if(!letterId||this.noteDraft?.letterId===letterId)this.noteDraft=null;
1816
1838
  if((this.authorized?.intent==='note'||this.authorized?.paperToken)&&(!letterId||this.authorized.letterId===letterId))this.authorized=null;