@alexsun-top/opencode-chat-room 0.3.2 → 0.3.3

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.3.3 — 2026-11-04
4
+
5
+ - Added an always-visible copy button below every message, including system messages. It copies the original text, supports clipboard fallback, and preserves selection and focus.
6
+ - Moved per-message reader counts into circular badges beside message bubbles. Reader details remain available on desktop and mobile, with localized accessible labels.
7
+ - Fixed capped V2 notifications discarding receipts for complete short messages in the same batch. Only uniquely matched, fully rendered messages qualify; truncated, omitted, multiline capped, and ambiguous duplicate messages remain unreceipted.
8
+ - Flush up to eight ready receipt candidates per round with ordered rotation, so transient upload failures do not repeatedly block later candidates. Failed candidates remain queued for retry.
9
+ - Verified all 143 tests, including Edge browser coverage, and TypeScript checks. An isolated OpenCode 2.2.5 host using the modified engine recorded the complete message but not the truncated message in a mixed batch. The reported production incident has not been independently attributed to either fixed case.
10
+ - Upgrade the central server for the web changes and reload each V2 client plugin for receipt fixes. This release does not deploy servers, change OpenCode permissions, or implement image messages.
11
+
3
12
  ## 0.3.2 — 2026-11-02
4
13
 
5
14
  - Fixed V2 context-receipt attribution when the verified host owner is discovered after plugin setup, and propagate that owner across project attachments. A full short message can now record `context` evidence without `room.poll`; capped previews remain unreceipted. A previously unready candidate becomes eligible only if its complete original message appears in agent context again—there is no read-all backfill or synthetic empty-context replay.
package/README.md CHANGED
@@ -79,17 +79,17 @@ On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute
79
79
 
80
80
  ```bash
81
81
  # Show CLI options:
82
- npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --help
82
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --help
83
83
 
84
84
  # Start the local central server (choose any one runner):
85
- npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
86
- pnpx --package=@alexsun-top/opencode-chat-room@0.3.2 opencode-chat-room --host 0.0.0.0 --port 4399
87
- bunx @alexsun-top/opencode-chat-room@0.3.2 --host 0.0.0.0 --port 4399 --token secret
85
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --host 0.0.0.0 --port 4399
86
+ pnpx --package=@alexsun-top/opencode-chat-room@0.3.3 opencode-chat-room --host 0.0.0.0 --port 4399
87
+ bunx @alexsun-top/opencode-chat-room@0.3.3 --host 0.0.0.0 --port 4399 --token secret
88
88
 
89
89
  # Environment variables also work; CLI options take precedence:
90
90
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
91
91
  CHAT_ROOM_SERVER_TOKEN=secret \
92
- bunx @alexsun-top/opencode-chat-room@0.3.2
92
+ bunx @alexsun-top/opencode-chat-room@0.3.3
93
93
 
94
94
  # Local checkout:
95
95
  bun install
@@ -132,7 +132,9 @@ Browser tabs fetch messages with `GET /inbox?sessionID=…&roomId=…&excludeSel
132
132
 
133
133
  Central server 0.3.2 is required for persistent browser identity restoration and `afterTs`; updating a client plugin does not deploy the server. Receipt APIs first appeared in 0.3.1. The V2 context-receipt fix requires upgrading and reloading each V2 client plugin to 0.3.2.
134
134
 
135
- Image messages are not implemented in 0.3.2; see the [image-message proposal](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md).
135
+ Version 0.3.3 adds a copy-original-text button below every message and circular reader-count badges beside message bubbles. Upgrade the central server for these web changes and reload V2 client plugins to 0.3.3 for batch receipt fixes. Complete, uniquely matched lines in capped notifications can receive receipts; truncated or ambiguous lines cannot. Ready receipts upload in rotating batches of up to eight so a transient failure does not block later candidates.
136
+
137
+ Image messages are not implemented in 0.3.3; see the [image-message proposal](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md).
136
138
 
137
139
  On every client machine:
138
140
 
package/README.zh-CN.md CHANGED
@@ -77,17 +77,17 @@ OpenCode 2.2.1 会在默认 60 分钟无活动后卸载闲置项目的服务。W
77
77
 
78
78
  ```bash
79
79
  # 查看 CLI 选项:
80
- npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --help
80
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --help
81
81
 
82
82
  # 启动本地中心服务器(三选一):
83
- npx --yes --package=@alexsun-top/opencode-chat-room@0.3.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
84
- pnpx --package=@alexsun-top/opencode-chat-room@0.3.2 opencode-chat-room --host 0.0.0.0 --port 4399
85
- bunx @alexsun-top/opencode-chat-room@0.3.2 --host 0.0.0.0 --port 4399 --token secret
83
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.3.3 -- opencode-chat-room --host 0.0.0.0 --port 4399
84
+ pnpx --package=@alexsun-top/opencode-chat-room@0.3.3 opencode-chat-room --host 0.0.0.0 --port 4399
85
+ bunx @alexsun-top/opencode-chat-room@0.3.3 --host 0.0.0.0 --port 4399 --token secret
86
86
 
87
87
  # 也可以使用环境变量;CLI 参数优先:
88
88
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
89
89
  CHAT_ROOM_SERVER_TOKEN=secret \
90
- bunx @alexsun-top/opencode-chat-room@0.3.2
90
+ bunx @alexsun-top/opencode-chat-room@0.3.3
91
91
 
92
92
  # 本地 checkout:
93
93
  bun install
@@ -130,7 +130,9 @@ V2 使用 `POST /presence` 上报 owner 范围内递增的序号,每次最多
130
130
 
131
131
  浏览器持久身份恢复和 `afterTs` 需要中心服务器 0.3.2;只更新客户端插件不会部署服务端。回执 API 自 0.3.1 起提供。V2 上下文回执修复需要将每台 V2 客户端插件升级并重新加载到 0.3.2。
132
132
 
133
- 0.3.2 尚未实现图片消息;设计提案见[图片消息方案](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md)。
133
+ 0.3.3 在每条消息下方增加复制原文按钮,并将已读人数改为消息旁的圆形标记。网页变化需升级中心服务器,批量回执修复需将各 V2 客户端插件升级并重新加载至 0.3.3。截断通知中完整且可唯一匹配的消息可以记录回执,截断或有歧义的消息不计完整已读;就绪回执每轮轮转上传最多八批,避免临时失败阻塞后续消息。
134
+
135
+ 0.3.3 尚未实现图片消息;设计提案见[图片消息方案](https://github.com/agentsyaml/opencode-chat-room/blob/main/docs/image-messages-plan.md)。
134
136
 
135
137
  每台客户端机器上:
136
138
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,5 +1,5 @@
1
1
  import { LS } from "./state.js";
2
- import { copyCodeFromButton } from "./markdown.js";
2
+ import { copyCodeFromButton, copyTextToClipboard } from "./markdown.js";
3
3
 
4
4
  export function initEvents(app) {
5
5
  const $ = app.$;
@@ -80,6 +80,8 @@ export function initEvents(app) {
80
80
  $("#msgList").addEventListener("click", (event) => {
81
81
  const button = event.target.closest("[data-copy-code]");
82
82
  if (button) void copyCodeFromButton(button, app);
83
+ const messageButton = event.target.closest("[data-copy-message]");
84
+ if (messageButton) void copyTextToClipboard(messageButton._copyText).then((copied) => app.flash(messageButton, copied ? "copiedMessage" : "copyMessageFailed"));
83
85
  });
84
86
  ["#inRoomId", "#inName", "#inRoomName"].forEach((selector) => {
85
87
  $(selector).addEventListener("input", app.hideJoinError);
@@ -58,8 +58,27 @@ function replaceMentionTokens(fragment, mentions, app) {
58
58
 
59
59
  export function copyCodeFromButton(button, app) {
60
60
  const code = button.parentElement.querySelector("code")?.textContent || "";
61
- return navigator.clipboard?.writeText(code).then(
62
- () => app.flash(button, "copiedCode"),
63
- () => app.showSendError("copyCodeFailed"),
64
- ) ?? app.showSendError("copyCodeFailed");
61
+ return copyTextToClipboard(code).then((copied) => copied ? app.flash(button, "copiedCode") : app.showSendError("copyCodeFailed"));
62
+ }
63
+
64
+ export async function copyTextToClipboard(text) {
65
+ try {
66
+ if (navigator.clipboard?.writeText) {
67
+ await navigator.clipboard.writeText(text);
68
+ return true;
69
+ }
70
+ } catch { /* Use the legacy clipboard command when permission is unavailable. */ }
71
+ const field = document.createElement("textarea"), selection = getSelection(), active = document.activeElement;
72
+ const ranges = selection ? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange()) : [];
73
+ field.value = text;
74
+ field.setAttribute("readonly", "");
75
+ field.style.cssText = "position:fixed;left:-9999px;top:0";
76
+ document.body.append(field);
77
+ field.select();
78
+ let copied = false;
79
+ try { copied = document.execCommand("copy"); } catch { /* Clipboard access may be disabled. */ }
80
+ field.remove();
81
+ if (selection) { selection.removeAllRanges(); ranges.forEach((range) => selection.addRange(range)); }
82
+ if (active instanceof HTMLElement) active.focus({ preventScroll: true });
83
+ return copied;
65
84
  }
@@ -144,8 +144,19 @@ export function initMessages(app) {
144
144
  const body = document.createElement("div");
145
145
  body.className = "msg-text";
146
146
  renderMarkdown(body, message.text, app);
147
- row.append(meta, body, receiptDetails(message, app));
147
+ const content = document.createElement("div");
148
+ content.className = "msg-content";
149
+ content.append(body, receiptDetails(message, app));
150
+ row.append(meta, content);
148
151
  }
152
+ const copy = document.createElement("button");
153
+ copy.type = "button";
154
+ copy.className = "message-copy";
155
+ copy.dataset.copyMessage = "";
156
+ copy.dataset.i18n = "copyMessage";
157
+ copy.textContent = app.t("copyMessage");
158
+ copy._copyText = String(message.text ?? "");
159
+ row.append(copy);
149
160
  if (live) row.classList.add("in");
150
161
  return row;
151
162
  };
@@ -466,7 +477,10 @@ function updateReceiptDetails(row, message, app) {
466
477
  const senderID = message.senderSessionID || (app.state.room?.kind === "direct" ? message.senderId : "");
467
478
  const readers = (app.state.receipts.get(detailsKey) || []).filter((reader) => reader.sessionID !== senderID);
468
479
  details.hidden = readers.length === 0;
469
- details.querySelector(".receipt-count").textContent = app.t("receiptCount", { count: readers.length });
480
+ const summary = details.querySelector("summary"), label = app.t("receiptCount", { count: readers.length });
481
+ summary.setAttribute("aria-label", label);
482
+ summary.title = label;
483
+ details.querySelector(".receipt-count").textContent = String(readers.length);
470
484
  const list = details.querySelector(".receipt-reader-list");
471
485
  list.textContent = "";
472
486
  const members = app.state.memberSessions.get(app.state.room?.id) || [];
@@ -204,6 +204,7 @@ const messages = {
204
204
  earlierMessages: "Earlier messages omitted", you: "You", saved: "Saved",
205
205
  savedMemory: "Saved for this tab only", copyFailed: ({ id }) => `Copy failed. Copy manually: ${id}`,
206
206
  copyCode: "Copy code", copiedCode: "Copied", copyCodeFailed: "Could not copy code. Select and copy it manually.",
207
+ copyMessage: "Copy", copiedMessage: "Copied", copyMessageFailed: "Could not copy. Select and copy the message manually.",
207
208
  identityChanged: "This browser identity changed in another tab. Reload this tab before continuing.",
208
209
  networkError: "Network connection failed", requestFailed: ({ status }) => `Request failed (HTTP ${status})`,
209
210
  roomIdRequired: "Enter a room ID", nameRequired: "Enter your name", authRetry: "The server requires an access token. Enter it and try again.",
@@ -248,6 +249,7 @@ const messages = {
248
249
  today: "今天", yesterday: "昨天", earlierMessages: "更早的消息已省略", you: "我", saved: "已保存",
249
250
  savedMemory: "仅保存于当前标签页", copyFailed: ({ id }) => `复制失败,请手动复制:${id}`,
250
251
  copyCode: "复制代码", copiedCode: "已复制", copyCodeFailed: "复制失败,请手动选择并复制代码。",
252
+ copyMessage: "复制", copiedMessage: "已复制", copyMessageFailed: "复制失败,请手动选择并复制消息。",
251
253
  identityChanged: "此浏览器身份已在另一个标签页中更改,请重新加载此标签页后继续。",
252
254
  networkError: "网络连接失败", requestFailed: ({ status }) => `请求失败(HTTP ${status})`,
253
255
  roomIdRequired: "请输入房间 ID", nameRequired: "请输入你的昵称", authRetry: "服务器要求访问令牌,请填写后重试",
@@ -181,9 +181,29 @@
181
181
  overflow-wrap: anywhere;
182
182
  }
183
183
  .msg.own .msg-text { background: var(--accent-soft); border-bottom-left-radius: 14px; border-bottom-right-radius: 4px; }
184
- .message-readers { margin-top: 4px; color: var(--ink-3); font-size: 11px; }
185
- .message-readers summary { cursor: pointer; }
186
- .receipt-reader-list { margin: 4px 0 0; padding: 5px 8px; list-style: none; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); }
184
+ .msg-content { position: relative; display: flex; align-items: flex-end; gap: 6px; width: fit-content; max-width: 100%; }
185
+ .msg.own .msg-content { flex-direction: row-reverse; }
186
+ .message-copy {
187
+ align-self: flex-start;
188
+ margin: 2px 0 0 4px;
189
+ padding: 2px 6px;
190
+ border: 0;
191
+ border-radius: 5px;
192
+ color: var(--ink-3);
193
+ background: transparent;
194
+ font: inherit;
195
+ font-size: 11px;
196
+ cursor: pointer;
197
+ }
198
+ .msg.own .message-copy { align-self: flex-end; margin-right: 4px; }
199
+ .message-copy:hover, .message-copy:focus-visible { color: var(--ink); background: var(--surface-2); }
200
+ .message-copy:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
201
+ .message-readers { position: static; flex: 0 0 22px; margin: 0 0 4px; color: var(--ink-3); font-size: 11px; }
202
+ .message-readers summary { display: grid; place-items: center; width: 22px; height: 22px; box-sizing: border-box; border: 1px solid var(--line); border-radius: 50%; background: var(--surface); cursor: pointer; list-style: none; }
203
+ .message-readers summary::-webkit-details-marker { display: none; }
204
+ .message-readers summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
205
+ .receipt-reader-list { position: absolute; z-index: 5; left: 0; top: 100%; min-width: min(210px, calc(100vw - 32px)); max-width: calc(100vw - 24px); box-sizing: border-box; margin: 4px 0 0; padding: 5px 8px; list-style: none; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); box-shadow: var(--shadow); }
206
+ .msg.own .receipt-reader-list { right: 0; left: auto; }
187
207
  .receipt-reader-list li { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; }
188
208
  .receipt-reader-list li + li { margin-top: 4px; }
189
209
  .receipt-reader-list li span:last-child { color: var(--ink-3); }
@@ -297,15 +317,18 @@
297
317
  }
298
318
 
299
319
  .sys {
320
+ position: relative;
300
321
  display: flex;
322
+ flex-direction: column;
301
323
  align-items: center;
302
- gap: 12px;
324
+ gap: 8px;
303
325
  margin: 20px 0;
304
326
  font-size: 12.5px;
305
327
  color: var(--ink-2);
306
328
  }
307
- .sys::before, .sys::after { content: ""; flex: 1; height: 1px; background: var(--line); }
308
- .sys span { flex-shrink: 0; }
329
+ .sys::before { content: ""; position: absolute; top: 9px; left: 0; right: 0; height: 1px; background: var(--line); }
330
+ .sys span { position: relative; padding: 0 10px; background: var(--surface); }
331
+ .sys .message-copy { align-self: center; margin: -8px 0 0; }
309
332
 
310
333
  .day-sep {
311
334
  display: flex;
@@ -1,16 +1,21 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import path from "node:path";
3
- import { databasePath, recordMessageReceipts } from "./store";
3
+ import { databasePath, formatNotificationLines, NOTIFY_INSTRUCTION, recordMessageReceipts, timeOf } from "./store";
4
4
  import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "./receiver-state";
5
5
 
6
6
  // shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
7
7
  const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
8
- type Item = { id?: string; text: string };
8
+ type Item = { id?: string; text: string; senderId?: string; createdAt?: number };
9
+ type CappedItem = Item & { senderId: string; createdAt: number };
9
10
  export type ReceiptCandidate = {
10
11
  admissionID: string; sessionID: string; roomID: string; membershipID: string;
11
12
  receiverOwnerID: string; destination: string; messageIDs: string[]; textHash: string; createdAt: number;
12
13
  };
13
14
  const hash = (text: string) => createHash("sha256").update(text).digest("hex");
15
+ function hasCappedMetadata(item: Item): item is CappedItem {
16
+ return typeof item.senderId === "string" && typeof item.createdAt === "number" && Number.isSafeInteger(item.createdAt) &&
17
+ !/[\r\n]/.test(item.senderId) && !/[\r\n]/.test(item.text);
18
+ }
14
19
 
15
20
  export function receiptDestination(center: string): string {
16
21
  if (!center) return path.resolve(databasePath());
@@ -23,13 +28,41 @@ export function prepareReceiptCandidate(input: {
23
28
  admissionID: string; sessionID: string; roomID: string; membershipID?: string;
24
29
  receiverOwnerID?: string; destination: string; items: Item[]; prompt: string; capped: boolean;
25
30
  }): ReceiptCandidate | undefined {
26
- if (input.capped || !input.membershipID || input.membershipID.length > 128 || !input.receiverOwnerID ||
31
+ if (!input.membershipID || input.membershipID.length > 128 || !input.receiverOwnerID ||
27
32
  !input.sessionID || input.sessionID.length > 128 || !input.roomID || input.roomID.length > 128 ||
28
33
  !input.items.length || input.items.length > 500 || input.items.some((item) => typeof item.id !== "string" || !item.id || item.id.length > 128 || typeof item.text !== "string")) return undefined;
34
+ // shortcut: capped multiline notifications fail closed; use structured rendered-line metadata if partial proofs become necessary.
35
+ let evidenceItems = input.items;
36
+ if (input.capped) {
37
+ const cappedItems = input.items.filter(hasCappedMetadata);
38
+ if (cappedItems.length !== input.items.length) return undefined;
39
+ const instruction = input.prompt.lastIndexOf(`\n${NOTIFY_INSTRUCTION}\n</notification>`);
40
+ if (instruction < 0) return undefined;
41
+ const renderedCounts = new Map<string, number>();
42
+ for (const item of cappedItems) {
43
+ const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
44
+ const key = `${prefix}${item.text}`;
45
+ renderedCounts.set(key, (renderedCounts.get(key) ?? 0) + 1);
46
+ }
47
+ let tail = input.prompt.slice(0, instruction);
48
+ evidenceItems = [];
49
+ for (let index = cappedItems.length - 1; index >= 0; index--) {
50
+ const item = cappedItems[index]!;
51
+ const prefix = `\n- [${timeOf(item.createdAt)}] ${item.senderId}: `;
52
+ const line = tail.lastIndexOf(prefix);
53
+ if (line < 0) break;
54
+ const displayedText = tail.slice(line + prefix.length);
55
+ if (displayedText.includes("\n")) break;
56
+ if (displayedText === item.text && renderedCounts.get(`${prefix}${item.text}`) === 1 && !formatNotificationLines([item]).capped) evidenceItems.push(item);
57
+ tail = tail.slice(0, line);
58
+ }
59
+ evidenceItems.reverse();
60
+ }
61
+ if (!evidenceItems.length) return undefined;
29
62
  const candidate: ReceiptCandidate = {
30
63
  admissionID: input.admissionID, sessionID: input.sessionID, roomID: input.roomID,
31
64
  membershipID: input.membershipID, receiverOwnerID: input.receiverOwnerID,
32
- destination: input.destination, messageIDs: input.items.map((item) => item.id!),
65
+ destination: input.destination, messageIDs: evidenceItems.map((item) => item.id!),
33
66
  textHash: hash(input.prompt), createdAt: Date.now(),
34
67
  };
35
68
  const key = hash(JSON.stringify([candidate.sessionID, candidate.admissionID, candidate.roomID, candidate.destination, candidate.receiverOwnerID, candidate.membershipID]));
@@ -61,25 +94,37 @@ export function observeReceiptContext(sessionID: string, messages: readonly unkn
61
94
  }
62
95
 
63
96
  const receiptFlushes = new Map<string, Promise<void>>();
97
+ // shortcut: cursor resets on process restart; persist it if restart storms delay backlog progress.
98
+ const receiptFlushCursors = new Map<string, string>();
99
+ const RECEIPT_FLUSH_LIMIT = 8;
100
+ const RECEIPT_FLUSH_LEASE_MS = 30_000;
64
101
  export function flushReceiptCandidates(input: {
65
102
  destination: string; receiverOwnerID?: string; center?: string; token?: string;
66
103
  }): Promise<void> {
67
104
  const key = JSON.stringify([input.destination, input.receiverOwnerID ?? ""]);
68
105
  const running = receiptFlushes.get(key);
69
106
  if (running) return running;
70
- const task = flushOneReceiptCandidate(input).finally(() => receiptFlushes.delete(key));
107
+ const task = flushOneReceiptCandidate(input, key).finally(() => receiptFlushes.delete(key));
71
108
  receiptFlushes.set(key, task);
72
109
  return task;
73
110
  }
74
111
 
75
- async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }): Promise<void> {
76
- const leaseKey = `receipt-flush:${hash(JSON.stringify([input.destination, input.receiverOwnerID ?? ""]))}`;
112
+ async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }, cursorKey: string): Promise<void> {
113
+ const leaseKey = `receipt-flush:${hash(cursorKey)}`;
77
114
  const holder = randomUUID(), now = Date.now();
78
- if (!acquireDeliveryLease(leaseKey, holder, now, now + 5000)) return;
115
+ if (!acquireDeliveryLease(leaseKey, holder, now, now + RECEIPT_FLUSH_LEASE_MS)) return;
79
116
  try {
80
117
  let candidates: Array<{ id: string; value: ReceiptCandidate }>;
81
- try { candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), 1); }
118
+ let cursor = receiptFlushCursors.get(cursorKey) ?? "";
119
+ try {
120
+ candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), RECEIPT_FLUSH_LIMIT, cursor);
121
+ if (!candidates.length && cursor) {
122
+ cursor = "";
123
+ candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), RECEIPT_FLUSH_LIMIT);
124
+ }
125
+ }
82
126
  catch { return; }
127
+ if (candidates.length) receiptFlushCursors.set(cursorKey, candidates.at(-1)!.id);
83
128
  for (const { id, value } of candidates) {
84
129
  try {
85
130
  if (input.center) {
@@ -121,11 +121,13 @@ export function markReceiptCandidateReady(id: string): boolean {
121
121
  return immediate((db) => db.query("UPDATE receipt_candidates SET ready=1,expires_at=? WHERE candidate_id=? AND ready=0")
122
122
  .run(Number.MAX_SAFE_INTEGER, id).changes === 1);
123
123
  }
124
- export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number): Array<{ id: string; value: T }> {
124
+ export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number, afterID?: string): Array<{ id: string; value: T }> {
125
125
  return immediate((db) => {
126
126
  db.query("DELETE FROM receipt_candidates WHERE ready=0 AND expires_at<=?").run(now);
127
- const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" + (limit ? " LIMIT ?" : "");
128
- const rows = (limit ? db.query(query).all(destination, ownerID ?? "", limit) : db.query(query).all(destination, ownerID ?? "")) as Array<{ candidate_id: string; candidate: string }>;
127
+ const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" +
128
+ (afterID !== undefined ? " AND candidate_id>?" : "") + " ORDER BY candidate_id" + (limit ? " LIMIT ?" : "");
129
+ const args = [destination, ownerID ?? "", ...(afterID !== undefined ? [afterID] : []), ...(limit ? [limit] : [])];
130
+ const rows = db.query(query).all(...args) as Array<{ candidate_id: string; candidate: string }>;
129
131
  return rows.map((row) => ({ id: row.candidate_id, value: JSON.parse(row.candidate) as T }));
130
132
  });
131
133
  }